text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import { Store } from '@ngrx/store'; import { BehaviorSubject, of as observableOf, Subject, Subscription } from 'rxjs'; import websocketConnect from 'rxjs-websockets'; import { catchError, combineLatest, filter, first, map, mergeMap, share, switchMap, tap } from 'rxjs/operators'; import { CFAppState } from '../../../../../cloud-foundry/src/cf-app-state'; import { organizationEntityType, spaceEntityType } from '../../../../../cloud-foundry/src/cf-entity-types'; import { selectCfEntity } from '../../../../../cloud-foundry/src/store/selectors/api.selectors'; import { selectDeployAppState } from '../../../../../cloud-foundry/src/store/selectors/deploy-application.selector'; import { AppData, DeployApplicationSource, DeployApplicationState, OverrideAppDetails, SocketEventTypes, } from '../../../../../cloud-foundry/src/store/types/deploy-application.types'; import { environment } from '../../../../../core/src/environments/environment.prod'; import { CfOrgSpaceDataService } from '../../../shared/data-services/cf-org-space-service.service'; import { FileScannerInfo } from './deploy-application-step2/deploy-application-fs/deploy-application-fs-scanner'; import { DEPLOY_TYPES_IDS } from './deploy-application-steps.types'; export interface DeployApplicationDeployerStatus { error: boolean; errorMsg?: string; deploying: boolean; } export interface FileTransferStatus { totalFiles: number; filesSent: number; bytesSent: number; totalBytes: number; fileName: string; } interface DeploySource { type: string; } interface GitSCMSourceInfo extends DeploySource { project: string; branch: string; url: string; commit: string; scm: string; endpointGuid: string; } // Structure used to provide metadata about the Git Url source interface GitUrlSourceInfo extends DeploySource { branch: string; url: string; } // DockerImageSourceInfo - Structure used to provide metadata about the docker source interface DockerImageSourceInfo extends DeploySource { applicationName: string; dockerImage: string; dockerUsername: string; } interface FolderSourceInfo extends DeploySource { wait: boolean; files: number; folders: string[]; } export class DeployApplicationDeployer { isRedeploy: string; connectSub: Subscription; updateSub: Subscription; msgSub: Subscription; streamTitle = 'Preparing...'; appData: AppData; proxyAPIVersion = environment.proxyAPIVersion; cfGuid: string; orgGuid: string; spaceGuid: string; applicationSource: any; applicationOverrides: OverrideAppDetails; status$ = new BehaviorSubject<DeployApplicationDeployerStatus>({ error: false, deploying: false }); // Observable on the application GUID of the application being deployed applicationGuid$ = new BehaviorSubject<string>(null); // Status of file transfers fileTransferStatus$ = new BehaviorSubject<FileTransferStatus>(undefined); public messages = new BehaviorSubject<string>(''); // Are we deploying? deploying = false; private inputStream; private isOpen = false; public fsFileInfo: FileScannerInfo; private fileTransfers; private fileTransferStatus: FileTransferStatus; private currentFileTransfer; constructor( private store: Store<CFAppState>, public cfOrgSpaceService: CfOrgSpaceDataService, ) { } updateStatus(error = false, errorMsg?: string) { this.status$.next({ error, errorMsg, deploying: this.deploying }); } close() { // Unsubscribe from the websocket stream if (this.msgSub) { this.msgSub.unsubscribe(); } if (this.connectSub) { this.connectSub.unsubscribe(); } if (this.updateSub) { this.updateSub.unsubscribe(); } this.isOpen = false; this.currentFileTransfer = undefined; } open() { if (this.isOpen) { return; } const readyFilter = this.fsFileInfo ? () => true : (appDetail: DeployApplicationState) => { if (!appDetail.applicationSource || !appDetail.applicationOverrides) { return; } return (!!appDetail.applicationSource.gitDetails && !!appDetail.applicationSource.gitDetails.projectName) || (!!appDetail.applicationSource.dockerDetails && !!appDetail.applicationSource.dockerDetails.dockerImage); }; this.isOpen = true; this.connectSub = this.store.select(selectDeployAppState).pipe( filter((appDetail: DeployApplicationState) => !!appDetail.cloudFoundryDetails && readyFilter(appDetail)), mergeMap(appDetails => { const orgSubscription = this.store.select(selectCfEntity(organizationEntityType, appDetails.cloudFoundryDetails.org)); const spaceSubscription = this.store.select(selectCfEntity(spaceEntityType, appDetails.cloudFoundryDetails.space)); return observableOf(appDetails).pipe(combineLatest(orgSubscription, spaceSubscription)); }), first(), tap(([appDetail, org, space]) => { this.cfGuid = appDetail.cloudFoundryDetails.cloudFoundry; this.orgGuid = appDetail.cloudFoundryDetails.org; this.spaceGuid = appDetail.cloudFoundryDetails.space; this.applicationSource = appDetail.applicationSource; this.applicationOverrides = appDetail.applicationOverrides; const host = window.location.host; const appId = this.isRedeploy ? `&app=${this.isRedeploy}` : ''; const streamUrl = ( `wss://${host}/pp/${this.proxyAPIVersion}/${this.cfGuid}/${this.orgGuid}/${this.spaceGuid}/deploy` + `?org=${org.entity.name}&space=${space.entity.name}${appId}` ); this.inputStream = new Subject<string>(); const buffer = websocketConnect(streamUrl) .pipe( switchMap((get) => get(this.inputStream)), catchError(e => { return []; }), filter(l => !!l), map(log => JSON.parse(log)), tap((log) => { // Deal with control messages if (log.type !== SocketEventTypes.DATA) { this.processWebSocketMessage(log); } }), filter((log) => log.type === SocketEventTypes.DATA), map((log) => log.message), share(), ); // Buffer messages until each newline character let b = ''; this.msgSub = buffer.subscribe(m => { b = b + m; if (b.endsWith('\n')) { this.messages.next(b); b = ''; } }); }) ).subscribe(); // Watch for updates to the app overrides - use case is app overrides being set after source file/folder upload this.updateSub = this.store.select(selectDeployAppState).pipe( filter((appDetail: DeployApplicationState) => !!appDetail.cloudFoundryDetails && readyFilter(appDetail)), tap((appDetail) => { this.applicationOverrides = appDetail.applicationOverrides; }) ).subscribe(); } deploy() { // After the source has been sent, acknowledge the wait const msg = { message: '', timestamp: Math.round((new Date()).getTime() / 1000), type: SocketEventTypes.SOURCE_WAIT_ACK }; this.inputStream.next(JSON.stringify(msg)); } sendAppOverride = (appOverrides: OverrideAppDetails) => { const msg = { message: JSON.stringify(appOverrides), timestamp: Math.round((new Date()).getTime() / 1000), type: SocketEventTypes.OVERRIDES_SUPPLIED }; return JSON.stringify(msg); }; sendProjectInfo = (appSource: DeployApplicationSource) => { if (appSource.type.group === 'gitscm') { return this.sendGitSCMSourceMetadata(appSource); } else if (appSource.type.id === DEPLOY_TYPES_IDS.GIT_URL) { return this.sendGitUrlSourceMetadata(appSource); } else if (appSource.type.id === DEPLOY_TYPES_IDS.FILE || appSource.type.id === DEPLOY_TYPES_IDS.FOLDER) { return this.sendLocalSourceMetadata(); } else if (appSource.type.id === DEPLOY_TYPES_IDS.DOCKER_IMG) { return this.sendDockerImageMetadata(appSource); } return ''; }; sendGitSCMSourceMetadata = (appSource: DeployApplicationSource) => { const gitscm: GitSCMSourceInfo = { project: appSource.gitDetails.projectName, branch: appSource.gitDetails.branch.name, type: appSource.type.group, commit: appSource.gitDetails.commit, url: appSource.gitDetails.url, scm: appSource.type.id, endpointGuid: appSource.gitDetails.endpointGuid }; const msg = { message: JSON.stringify(gitscm), timestamp: Math.round((new Date()).getTime() / 1000), type: SocketEventTypes.SOURCE_GITSCM }; return JSON.stringify(msg); }; sendGitUrlSourceMetadata = (appSource: DeployApplicationSource) => { const gitUrl: GitUrlSourceInfo = { url: appSource.gitDetails.projectName, branch: appSource.gitDetails.branch.name, type: appSource.type.id }; const msg = { message: JSON.stringify(gitUrl), timestamp: Math.round((new Date()).getTime() / 1000), type: SocketEventTypes.SOURCE_GITURL }; return JSON.stringify(msg); }; sendDockerImageMetadata = (appSource: DeployApplicationSource) => { const dockerInfo: DockerImageSourceInfo = { applicationName: appSource.dockerDetails.applicationName, dockerImage: appSource.dockerDetails.dockerImage, dockerUsername: appSource.dockerDetails.dockerUsername, type: appSource.type.id }; const msg = { message: JSON.stringify(dockerInfo), timestamp: Math.round((new Date()).getTime() / 1000), type: SocketEventTypes.SOURCE_DOCKER_IMG }; return JSON.stringify(msg); }; sendCloseAcknowledgement = () => { const msg = { message: '{}', timestamp: Math.round((new Date()).getTime() / 1000), type: SocketEventTypes.CLOSE_ACK }; return JSON.stringify(msg); }; processWebSocketMessage = (log) => { switch (log.type) { case SocketEventTypes.MANIFEST: this.streamTitle = 'Starting deployment...'; // This info is will be used to retrieve the app Id this.appData = JSON.parse(log.message).Applications[0]; break; case SocketEventTypes.APP_GUID_NOTIFY: // Notification of the application GUID for the application this.applicationGuid$.next(log.message); break; case SocketEventTypes.EVENT_PUSH_STARTED: this.streamTitle = 'Deploying...'; this.deploying = true; this.updateStatus(); break; case SocketEventTypes.EVENT_PUSH_COMPLETED: // Done this.streamTitle = 'Deployed'; this.deploying = false; this.updateStatus(); break; case SocketEventTypes.CLOSE_SUCCESS: // Acknowledge this.inputStream.next(this.sendCloseAcknowledgement()); this.onClose(log, null, null); break; case SocketEventTypes.CLOSE_INVALID_MANIFEST: this.onClose(log, 'Deploy Failed - Invalid manifest!', 'Failed to deploy app! Please make sure that a valid manifest.yaml was provided.'); break; case SocketEventTypes.CLOSE_NO_MANIFEST: this.onClose(log, 'Deploy Failed - No manifest present!', 'Failed to deploy app! Please make sure that a valid manifest.yaml is present.'); break; case SocketEventTypes.CLOSE_FAILED_CLONE: this.onClose(log, 'Deploy Failed - Failed to clone repository!', 'Failed to deploy app! Please make sure the repository is accessible.'); break; case SocketEventTypes.CLOSE_FAILED_NO_BRANCH: this.onClose(log, 'Deploy Failed - Failed to located branch!', 'Failed to deploy app! Please make sure that the branch exists.'); break; case SocketEventTypes.CLOSE_FAILURE: case SocketEventTypes.CLOSE_PUSH_ERROR: case SocketEventTypes.CLOSE_NO_SESSION: case SocketEventTypes.CLOSE_NO_CNSI: case SocketEventTypes.CLOSE_NO_CNSI_USERTOKEN: this.onClose(log, 'Deploy Failed!', 'Failed to deploy app!'); break; case SocketEventTypes.SOURCE_REQUIRED: const sourceInfo = this.sendProjectInfo(this.applicationSource); if (!sourceInfo) { this.onClose(log, 'Deploy Failed - Unknown source type', 'Failed to deploy the app - unknown source type'); } else { this.inputStream.next(sourceInfo); } break; case SocketEventTypes.OVERRIDES_REQUIRED: const overrides = this.sendAppOverride(this.applicationOverrides); this.inputStream.next(overrides); break; case SocketEventTypes.EVENT_CLONED: case SocketEventTypes.EVENT_FETCHED_MANIFEST: case SocketEventTypes.MANIFEST: break; case SocketEventTypes.SOURCE_FILE_ACK: this.sendNextFile(); break; default: // noop } }; private sendNextFile() { // Update for the previous file transfer if (this.currentFileTransfer) { this.fileTransferStatus.bytesSent += this.currentFileTransfer.size; this.fileTransferStatus.filesSent++; this.fileTransferStatus$.next(this.fileTransferStatus); } if (this.fileTransfers.length > 0) { const file = this.fileTransfers.shift(); // Send file metadata const msg = { message: file.fullPath, timestamp: Math.round((new Date()).getTime() / 1000), type: SocketEventTypes.SOURCE_FILE }; this.fileTransferStatus.fileName = file.fullPath; this.fileTransferStatus$.next(this.fileTransferStatus); // Send the file name metadata this.inputStream.next(JSON.stringify(msg)); // Now send the file data as a binary message const reader = new FileReader(); reader.onload = () => { this.currentFileTransfer = file; const output = reader.result; this.inputStream.next(output); }; reader.readAsArrayBuffer(file); } } private onClose(log, title, error) { if (title) { this.streamTitle = title; } this.deploying = false; this.updateStatus( error, error ? `${error}\nReason: ${log.message}` : undefined ); } // File Upload sendLocalSourceMetadata() { const metadata = { files: [], folders: [] }; this.collectFoldersAndFiles(metadata, null, this.fsFileInfo.root); this.fileTransfers = metadata.files; this.fileTransferStatus = { totalFiles: metadata.files.length, filesSent: 0, bytesSent: 0, totalBytes: this.fsFileInfo.total, fileName: '' }; this.fileTransferStatus$.next(this.fileTransferStatus); const transferMetadata: FolderSourceInfo = { files: metadata.files.length, folders: metadata.folders, type: 'filefolder', wait: true }; // Send the source metadata return JSON.stringify({ message: JSON.stringify(transferMetadata), timestamp: Math.round((new Date()).getTime() / 1000), type: SocketEventTypes.SOURCE_FOLDER }); } // Flatten files and folders collectFoldersAndFiles(metadata, base, folder) { if (folder.files) { folder.files.forEach(file => { file.fullPath = base ? base + '/' + file.name : file.name; metadata.files.push(file); }); } if (folder.folders) { Object.keys(folder.folders).forEach(name => { const sub = folder.folders[name]; const fullPath = base ? base + '/' + name : name; metadata.folders.push(fullPath); this.collectFoldersAndFiles(metadata, fullPath, sub); }); } } }
the_stack
import { ConfigSaveComponent, ArmSaveConfigs } from 'app/shared/components/config-save-component'; import { LogService } from './../../../shared/services/log.service'; import { LogCategories, SiteTabIds } from './../../../shared/models/constants'; import { SiteService } from './../../../shared/services/site.service'; import { Component, Injector, Input, OnChanges, OnDestroy, SimpleChanges } from '@angular/core'; import { FormArray, FormBuilder, FormGroup } from '@angular/forms'; import { Observable } from 'rxjs/Observable'; import { TranslateService } from '@ngx-translate/core'; import { HandlerMapping } from './../../../shared/models/arm/handler-mapping'; import { SiteConfig } from './../../../shared/models/arm/site-config'; import { PortalResources } from './../../../shared/models/portal-resources'; import { CustomFormControl, CustomFormGroup } from './../../../controls/click-to-edit/click-to-edit.component'; import { ArmObj, ResourceId } from './../../../shared/models/arm/arm-obj'; import { AuthzService } from './../../../shared/services/authz.service'; import { RequiredValidator } from 'app/shared/validators/requiredValidator'; @Component({ selector: 'handler-mappings', templateUrl: './handler-mappings.component.html', styleUrls: ['./../site-config.component.scss'], }) export class HandlerMappingsComponent extends ConfigSaveComponent implements OnChanges, OnDestroy { @Input() mainForm: FormGroup; @Input() resourceId: ResourceId; public Resources = PortalResources; public groupArray: FormArray; public hasWritePermissions: boolean; public permissionsMessage: string; public showPermissionsMessage: boolean; public showReadOnlySettingsMessage: string; public loadingFailureMessage: string; public loadingMessage: string; public newItem: CustomFormGroup; public originalItemsDeleted: number; private _requiredValidator: RequiredValidator; constructor( private _fb: FormBuilder, private _translateService: TranslateService, private _logService: LogService, private _authZService: AuthzService, private _siteService: SiteService, injector: Injector ) { super('HandlerMappingsComponent', injector, ['SiteConfig'], SiteTabIds.applicationSettings); this._resetPermissionsAndLoadingState(); this.newItem = null; this.originalItemsDeleted = 0; } protected setup(inputEvents: Observable<ResourceId>) { return inputEvents .distinctUntilChanged() .switchMap(() => { this._saveFailed = false; this._resetSubmittedStates(); this._resetConfigs(); this.groupArray = null; this.newItem = null; this.originalItemsDeleted = 0; this._resetPermissionsAndLoadingState(); return Observable.zip( this._siteService.getSiteConfig(this.resourceId, true), this._authZService.hasPermission(this.resourceId, [AuthzService.writeScope]), this._authZService.hasReadOnlyLock(this.resourceId) ); }) .do(results => { if (!results[0].isSuccessful) { this._logService.error(LogCategories.handlerMappings, '/handler-mappings', results[0].error.result); this._setupForm(null); this.loadingFailureMessage = this._translateService.instant(PortalResources.configLoadFailure); } else { this.siteConfigArm = results[0].result; this._setPermissions(results[1], results[2]); this._setupForm(this.siteConfigArm); } this.loadingMessage = null; this.showPermissionsMessage = true; }); } protected get _isPristine() { return this.groupArray && this.groupArray.pristine; } ngOnChanges(changes: SimpleChanges) { if (changes['resourceId']) { this.setInput(this.resourceId); } if (changes['mainForm'] && !changes['resourceId']) { this._setupForm(this.siteConfigArm); } } private _resetPermissionsAndLoadingState() { this.hasWritePermissions = true; this.permissionsMessage = ''; this.showPermissionsMessage = false; this.showReadOnlySettingsMessage = this._translateService.instant(PortalResources.configViewReadOnlySettings); this.loadingFailureMessage = ''; this.loadingMessage = this._translateService.instant(PortalResources.loading); } private _setPermissions(writePermission: boolean, readOnlyLock: boolean) { if (!writePermission) { this.permissionsMessage = this._translateService.instant(PortalResources.configRequiresWritePermissionOnApp); } else if (readOnlyLock) { this.permissionsMessage = this._translateService.instant(PortalResources.configDisabledReadOnlyLockOnApp); } else { this.permissionsMessage = ''; } this.hasWritePermissions = writePermission && !readOnlyLock; } private _setupForm(siteConfigArm: ArmObj<SiteConfig>) { if (!!siteConfigArm) { if (!this._saveFailed || !this.groupArray) { this.newItem = null; this.originalItemsDeleted = 0; this.groupArray = this._fb.array([]); this._requiredValidator = new RequiredValidator(this._translateService); if (siteConfigArm.properties.handlerMappings) { siteConfigArm.properties.handlerMappings.forEach(mapping => { const group = this._fb.group({ extension: [ { value: mapping.extension, disabled: !this.hasWritePermissions }, this._requiredValidator.validate.bind(this._requiredValidator), ], scriptProcessor: [ { value: mapping.scriptProcessor, disabled: !this.hasWritePermissions }, this._requiredValidator.validate.bind(this._requiredValidator), ], arguments: [{ value: mapping.arguments, disabled: !this.hasWritePermissions }], }) as CustomFormGroup; group.msExistenceState = 'original'; this.groupArray.push(group); }); } this._validateAllControls(this.groupArray.controls as CustomFormGroup[]); } if (this.mainForm.contains('handlerMappings')) { this.mainForm.setControl('handlerMappings', this.groupArray); } else { this.mainForm.addControl('handlerMappings', this.groupArray); } } else { this.newItem = null; this.originalItemsDeleted = 0; this.groupArray = null; if (this.mainForm.contains('handlerMappings')) { this.mainForm.removeControl('handlerMappings'); } } this._saveFailed = false; this._resetSubmittedStates(); } validate() { const groups = this.groupArray.controls; // Purge any added entries that were never modified for (let i = groups.length - 1; i >= 0; i--) { const group = groups[i] as CustomFormGroup; if (group.msStartInEditMode && group.pristine) { groups.splice(i, 1); if (group === this.newItem) { this.newItem = null; } } } this._validateAllControls(groups as CustomFormGroup[]); } private _validateAllControls(groups: CustomFormGroup[]) { groups.forEach(group => { const controls = (<FormGroup>group).controls; for (const controlName in controls) { const control = <CustomFormControl>controls[controlName]; control._msRunValidation = true; control.updateValueAndValidity(); } }); } protected _getConfigsFromForms(saveConfigs: ArmSaveConfigs): ArmSaveConfigs { const siteConfigArm: ArmObj<SiteConfig> = saveConfigs && saveConfigs.siteConfigArm ? JSON.parse(JSON.stringify(saveConfigs.siteConfigArm)) : JSON.parse(JSON.stringify(this.siteConfigArm)); siteConfigArm.id = `${this.resourceId}/config/web`; siteConfigArm.properties.handlerMappings = []; const handlerMappings: HandlerMapping[] = siteConfigArm.properties.handlerMappings; this.groupArray.controls.forEach(group => { if ((group as CustomFormGroup).msExistenceState !== 'deleted') { const formGroup: FormGroup = group as FormGroup; handlerMappings.push({ extension: formGroup.controls['extension'].value, scriptProcessor: formGroup.controls['scriptProcessor'].value, arguments: formGroup.controls['arguments'].value, }); } }); return { siteConfigArm: siteConfigArm, }; } deleteItem(group: FormGroup) { const groups = this.groupArray; const index = groups.controls.indexOf(group); if (index >= 0) { if ((group as CustomFormGroup).msExistenceState === 'original') { this._deleteOriginalItem(groups, group); } else { this._deleteAddedItem(groups, group, index); } } } private _deleteOriginalItem(groups: FormArray, group: FormGroup) { // Keep the deleted group around with its state set to dirty. // This keeps the overall state of this.groupArray and this.mainForm dirty. group.markAsDirty(); // Set the group.msExistenceState to 'deleted' so we know to ignore it when validating and saving. (group as CustomFormGroup).msExistenceState = 'deleted'; // Force the deleted group to have a valid state by clear all validators on the controls and then running validation. for (const key in group.controls) { const control = group.controls[key]; control.clearAsyncValidators(); control.clearValidators(); control.updateValueAndValidity(); } this.originalItemsDeleted++; groups.updateValueAndValidity(); } private _deleteAddedItem(groups: FormArray, group: FormGroup, index: number) { // Remove group from groups groups.removeAt(index); if (group === this.newItem) { this.newItem = null; } // If group was dirty, then groups is also dirty. // If all the remaining controls in groups are pristine, mark groups as pristine. if (!group.pristine) { let pristine = true; for (const control of groups.controls) { pristine = pristine && control.pristine; } if (pristine) { groups.markAsPristine(); } } groups.updateValueAndValidity(); } addItem() { const groups = this.groupArray; this.newItem = this._fb.group({ extension: [null, this._requiredValidator.validate.bind(this._requiredValidator)], scriptProcessor: [null, this._requiredValidator.validate.bind(this._requiredValidator)], arguments: [null], }) as CustomFormGroup; this.newItem.msExistenceState = 'new'; this.newItem.msStartInEditMode = true; groups.push(this.newItem); } }
the_stack
const specialOptionKeys = [ "parent", "style", "dataset" ]; export default function html(tag: string, options?: HTMLOptions): HTMLElement; export default function html(tag: "div", options?: HTMLOptions): HTMLDivElement; export default function html(tag: "span", options?: HTMLOptions): HTMLDivElement; export default function html(tag: "img", options?: HTMLImageOptions): HTMLImageElement; export default function html(tag: "button", options?: HTMLInputOptions): HTMLButtonElement; export default function html(tag: "input", options?: HTMLInputOptions): HTMLInputElement; export default function html(tag: "label", options?: HTMLLabelOptions): HTMLLabelElement; export default function html(tag: "textarea", options?: HTMLInputOptions): HTMLTextAreaElement; export default function html(tag: "select", options?: HTMLInputOptions): HTMLSelectElement; export default function html(tag: "option", options?: HTMLOptionOptions): HTMLOptGroupElement; export default function html(tag: "optgroup", options?: HTMLOptionOptions): HTMLOptGroupElement; export default function html(tag: "ol", options?: HTMLOptions): HTMLOListElement; export default function html(tag: "ul", options?: HTMLOptions): HTMLUListElement; export default function html(tag: "li", options?: HTMLOptions): HTMLLIElement; export default function html(tag: string, classList?: string|string[], options?: HTMLOptions): HTMLElement; export default function html(tag: "div", classList?: string|string[], options?: HTMLOptions): HTMLDivElement; export default function html(tag: "span", classList?: string|string[], options?: HTMLOptions): HTMLDivElement; export default function html(tag: "img", classList?: string|string[], options?: HTMLImageOptions): HTMLImageElement; export default function html(tag: "button", classList?: string|string[], options?: HTMLInputOptions): HTMLButtonElement; export default function html(tag: "input", classList?: string|string[], options?: HTMLInputOptions): HTMLInputElement; export default function html(tag: "label", classList?: string|string[], options?: HTMLLabelOptions): HTMLLabelElement; export default function html(tag: "textarea", classList?: string|string[], options?: HTMLInputOptions): HTMLTextAreaElement; export default function html(tag: "select", classList?: string|string[], options?: HTMLInputOptions): HTMLSelectElement; export default function html(tag: "option", classList?: string|string[], options?: HTMLOptionOptions): HTMLOptGroupElement; export default function html(tag: "optgroup", classList?: string|string[], options?: HTMLOptionOptions): HTMLOptGroupElement; export default function html(tag: "ol", classList?: string|string[], options?: HTMLOptions): HTMLOListElement; export default function html(tag: "ul", classList?: string|string[], options?: HTMLOptions): HTMLUListElement; export default function html(tag: "li", classList?: string|string[], options?: HTMLOptions): HTMLLIElement; export default function html(tag: string, classList?: string|string[]|HTMLInputOptions, options?: HTMLInputOptions) { if (options == null) { if (typeof classList === "object" && !Array.isArray(classList)) { options = classList; classList = null; } else { options = {}; } } if (typeof classList === "string") classList = [ classList ] as any; const elt = document.createElement(tag); if (classList != null) { // NOTE: `elt.classList.add.apply(elt, classList);` // throws IllegalInvocationException at least in Chrome for (const name of classList as string[]) elt.classList.add(name); } for (const key in options) { if (specialOptionKeys.indexOf(key) !== -1) continue; const value = (options as any)[key]; (elt as any)[key] = value; } if (options.parent != null) options.parent.appendChild(elt); if (options.style != null) for (const key in options.style) (elt.style as any)[key] = (options.style as any)[key]; if (options.dataset != null) for (const key in options.dataset) elt.dataset[key] = options.dataset[key]; return elt; } interface HTMLOptions { id?: string; parent?: HTMLElement; style?: HTMLStyleOptions; dataset?: { [key: string]: string; }; textContent?: string; innerHTML?: string; title?: string; hidden?: boolean; disabled?: boolean; required?: boolean; draggable?: boolean; } interface HTMLImageOptions extends HTMLOptions { src?: string; } interface HTMLLabelOptions extends HTMLOptions { htmlFor?: string; } interface HTMLInputOptions extends HTMLOptions { type?: string; value?: string; accept?: string; placeholder?: string; pattern?: string; checked?: boolean; } interface HTMLOptionOptions extends HTMLOptions { label?: string; value?: string; } interface HTMLStyleOptions { alignContent?: string; alignItems?: string; alignSelf?: string; alignmentBaseline?: string; animation?: string; animationDelay?: string; animationDirection?: string; animationDuration?: string; animationFillMode?: string; animationIterationCount?: string; animationName?: string; animationPlayState?: string; animationTimingFunction?: string; backfaceVisibility?: string; background?: string; backgroundAttachment?: string; backgroundClip?: string; backgroundColor?: string; backgroundImage?: string; backgroundOrigin?: string; backgroundPosition?: string; backgroundPositionX?: string; backgroundPositionY?: string; backgroundRepeat?: string; backgroundSize?: string; baselineShift?: string; border?: string; borderBottom?: string; borderBottomColor?: string; borderBottomLeftRadius?: string; borderBottomRightRadius?: string; borderBottomStyle?: string; borderBottomWidth?: string; borderCollapse?: string; borderColor?: string; borderImage?: string; borderImageOutset?: string; borderImageRepeat?: string; borderImageSlice?: string; borderImageSource?: string; borderImageWidth?: string; borderLeft?: string; borderLeftColor?: string; borderLeftStyle?: string; borderLeftWidth?: string; borderRadius?: string; borderRight?: string; borderRightColor?: string; borderRightStyle?: string; borderRightWidth?: string; borderSpacing?: string; borderStyle?: string; borderTop?: string; borderTopColor?: string; borderTopLeftRadius?: string; borderTopRightRadius?: string; borderTopStyle?: string; borderTopWidth?: string; borderWidth?: string; bottom?: string; boxShadow?: string; boxSizing?: string; breakAfter?: string; breakBefore?: string; breakInside?: string; captionSide?: string; clear?: string; clip?: string; clipPath?: string; clipRule?: string; color?: string; colorInterpolationFilters?: string; columnCount?: any; columnFill?: string; columnGap?: any; columnRule?: string; columnRuleColor?: any; columnRuleStyle?: string; columnRuleWidth?: any; columnSpan?: string; columnWidth?: any; columns?: string; content?: string; counterIncrement?: string; counterReset?: string; cssFloat?: string; cssText?: string; cursor?: string; direction?: string; display?: string; dominantBaseline?: string; emptyCells?: string; enableBackground?: string; fill?: string; fillOpacity?: string; fillRule?: string; filter?: string; flex?: string; flexBasis?: string; flexDirection?: string; flexFlow?: string; flexGrow?: string; flexShrink?: string; flexWrap?: string; floodColor?: string; floodOpacity?: string; font?: string; fontFamily?: string; fontFeatureSettings?: string; fontSize?: string; fontSizeAdjust?: string; fontStretch?: string; fontStyle?: string; fontVariant?: string; fontWeight?: string; glyphOrientationHorizontal?: string; glyphOrientationVertical?: string; height?: string; imeMode?: string; justifyContent?: string; kerning?: string; left?: string; length?: number; letterSpacing?: string; lightingColor?: string; lineHeight?: string; listStyle?: string; listStyleImage?: string; listStylePosition?: string; listStyleType?: string; margin?: string; marginBottom?: string; marginLeft?: string; marginRight?: string; marginTop?: string; marker?: string; markerEnd?: string; markerMid?: string; markerStart?: string; mask?: string; maxHeight?: string; maxWidth?: string; minHeight?: string; minWidth?: string; opacity?: string; order?: string; orphans?: string; outline?: string; outlineColor?: string; outlineStyle?: string; outlineWidth?: string; overflow?: string; overflowX?: string; overflowY?: string; padding?: string; paddingBottom?: string; paddingLeft?: string; paddingRight?: string; paddingTop?: string; pageBreakAfter?: string; pageBreakBefore?: string; pageBreakInside?: string; parentRule?: CSSRule; perspective?: string; perspectiveOrigin?: string; pointerEvents?: string; position?: string; quotes?: string; resize?: string; right?: string; rubyAlign?: string; rubyOverhang?: string; rubyPosition?: string; stopColor?: string; stopOpacity?: string; stroke?: string; strokeDasharray?: string; strokeDashoffset?: string; strokeLinecap?: string; strokeLinejoin?: string; strokeMiterlimit?: string; strokeOpacity?: string; strokeWidth?: string; tableLayout?: string; textAlign?: string; textAlignLast?: string; textAnchor?: string; textDecoration?: string; textFillColor?: string; textIndent?: string; textJustify?: string; textKashida?: string; textKashidaSpace?: string; textOverflow?: string; textShadow?: string; textTransform?: string; textUnderlinePosition?: string; top?: string; touchAction?: string; transform?: string; transformOrigin?: string; transformStyle?: string; transition?: string; transitionDelay?: string; transitionDuration?: string; transitionProperty?: string; transitionTimingFunction?: string; unicodeBidi?: string; verticalAlign?: string; visibility?: string; whiteSpace?: string; widows?: string; width?: string; wordBreak?: string; wordSpacing?: string; wordWrap?: string; writingMode?: string; zIndex?: string; zoom?: string; }
the_stack
import * as express from "express"; import { Intent } from "./Intent"; import { AppserviceJoinRoomStrategy, EncryptedRoomEvent, EventKind, IAppserviceCryptoStorageProvider, IAppserviceStorageProvider, IJoinRoomStrategy, IPreprocessor, LogService, MatrixClient, MemoryStorageProvider, Metrics, OTKAlgorithm, } from ".."; import { EventEmitter } from "events"; import * as morgan from "morgan"; import { MatrixBridge } from "./MatrixBridge"; import * as LRU from "lru-cache"; import { IApplicationServiceProtocol } from "./http_responses"; const EDU_ANNOTATION_KEY = "io.t2bot.sdk.bot.type"; enum EduAnnotation { ToDevice = "to_device", Ephemeral = "ephemeral", } /** * Represents an application service's registration file. This is expected to be * loaded from another source, such as a YAML file. * @category Application services */ export interface IAppserviceRegistration { /** * Optional ID for the appplication service. Used by homeservers to track which application * service registers what. */ id?: string; /** * Optional URL at which the application service can be contacted. */ url?: string; /** * The token the application service uses to communicate with the homeserver. */ as_token: string; /** * The token the homeserver uses to communicate with the application service. */ hs_token: string; /** * The application service's own localpart (eg: "_irc_bot" in the user ID "@_irc_bot:domain.com") */ sender_localpart: string; /** * The various namespaces the application service can support. */ namespaces: { /** * The user namespaces the application service is requesting. */ users: { /** * Whether or not the application service holds an exclusive lock on the namespace. This * means that no other user on the homeserver may register users that match this namespace. */ exclusive: boolean; /** * The regular expression that the homeserver uses to determine if a user is in this namespace. */ regex: string; /** * An optional group ID to enable flair for users in this namespace. */ groupId?: string; }[]; /** * The room namespaces the application service is requesting. This is not for alises. */ rooms: { /** * Whether or not the application service holds an exclusive lock on the namespace. */ exclusive: boolean; /** * The regular expression that the homeserver uses to determine if a user is in this namespace. */ regex: string; }[]; /** * The room alias namespaces the application service is requesting. */ aliases: { /** * Whether or not the application service holds an exclusive lock on the namespace. This means * that no other user on the homeserver may register aliases that match this namespace. */ exclusive: boolean; /** * The regular expression that the homeserver uses to determine if an alias is in this namespace. */ regex: string; }[]; }; /** * The protocols the application service supports. Optional. */ protocols?: string[]; /** * If the application service is rate limited by the homeserver. Optional. */ rate_limited?: boolean; /** * **Experimental** * * Should the application service receive ephemeral events from the homeserver. Optional. * @see https://github.com/matrix-org/matrix-doc/pull/2409 */ "de.sorunome.msc2409.push_ephemeral"?: boolean; // not interested in other options } /** * General options for the application service * @category Application services */ export interface IAppserviceOptions { /** * The port to listen for requests from the homeserver on. */ port: number; /** * The bind address to listen for requests on. */ bindAddress: string; /** * The name of the homeserver, as presented over federation (eg: "matrix.org") */ homeserverName: string; /** * The URL to the homeserver's client server API (eg: "https://matrix.org") */ homeserverUrl: string; /** * The storage provider to use for this application service. */ storage?: IAppserviceStorageProvider; /** * The storage provider to use for setting up encryption. Encryption will be * disabled for all intents and the appservice if not configured. */ cryptoStorage?: IAppserviceCryptoStorageProvider; /** * The registration for this application service. */ registration: IAppserviceRegistration; /** * The join strategy to use for all intents, if any. */ joinStrategy?: IJoinRoomStrategy; /** * Options for how Intents are handled. */ intentOptions?: { /** * The maximum number of intents to keep cached. Defaults to 10 thousand. */ maxCached?: number; /** * The maximum age in milliseconds to keep an Intent around for, provided * the maximum number of intents has been reached. Defaults to 60 minutes. */ maxAgeMs?: number; /** * If false (default), crypto will not be automatically set up for all intent * instances - it will need to be manually enabled with * `await intent.enableEncryption()`. * * If true, crypto will be automatically set up. * * Note that the appservice bot account is considered an intent. */ encryption?: boolean; }; } /** * Represents an application service. This provides helper utilities such as tracking * of user intents (clients that are aware of their membership in rooms). * @category Application services */ export class Appservice extends EventEmitter { /** * The metrics instance for this appservice. This will raise all metrics * from this appservice instance as well as any intents/MatrixClients created * by the appservice. */ public readonly metrics: Metrics = new Metrics(); private readonly userPrefix: string | null; private readonly aliasPrefix: string | null; private readonly registration: IAppserviceRegistration; private readonly storage: IAppserviceStorageProvider; private readonly cryptoStorage: IAppserviceCryptoStorageProvider; private readonly bridgeInstance = new MatrixBridge(this); private app = express(); private appServer: any; private intentsCache: LRU; private eventProcessors: { [eventType: string]: IPreprocessor[] } = {}; private pendingTransactions: { [txnId: string]: Promise<any> } = {}; /** * Creates a new application service. * @param {IAppserviceOptions} options The options for the application service. */ constructor(private options: IAppserviceOptions) { super(); options.joinStrategy = new AppserviceJoinRoomStrategy(options.joinStrategy, this); if (!options.intentOptions) options.intentOptions = {}; if (!options.intentOptions.maxAgeMs) options.intentOptions.maxAgeMs = 60 * 60 * 1000; if (!options.intentOptions.maxCached) options.intentOptions.maxCached = 10000; this.intentsCache = new LRU({ max: options.intentOptions.maxCached, maxAge: options.intentOptions.maxAgeMs, }); this.registration = options.registration; // If protocol is not defined, define an empty array. if (!this.registration.protocols) { this.registration.protocols = []; } this.storage = options.storage || new MemoryStorageProvider(); options.storage = this.storage; this.cryptoStorage = options.cryptoStorage; this.app.use(express.json({limit: Number.MAX_SAFE_INTEGER})); // disable limits, use a reverse proxy this.app.use(morgan("combined")); // ETag headers break the tests sometimes, and we don't actually need them anyways for // appservices - none of this should be cached. this.app.set('etag', false); this.app.get("/users/:userId", this.onUser.bind(this)); this.app.get("/rooms/:roomAlias", this.onRoomAlias.bind(this)); this.app.put("/transactions/:txnId", this.onTransaction.bind(this)); this.app.get("/_matrix/app/v1/users/:userId", this.onUser.bind(this)); this.app.get("/_matrix/app/v1/rooms/:roomAlias", this.onRoomAlias.bind(this)); this.app.put("/_matrix/app/v1/transactions/:txnId", this.onTransaction.bind(this)); this.app.get("/_matrix/app/v1/thirdparty/protocol/:protocol", this.onThirdpartyProtocol.bind(this)); this.app.get("/_matrix/app/v1/thirdparty/user/:protocol", this.onThirdpartyUser.bind(this)); this.app.get("/_matrix/app/v1/thirdparty/user", this.onThirdpartyUser.bind(this)); this.app.get("/_matrix/app/v1/thirdparty/location/:protocol", this.onThirdpartyLocation.bind(this)); this.app.get("/_matrix/app/v1/thirdparty/location", this.onThirdpartyLocation.bind(this)); // Everything else can 404 if (!this.registration.namespaces || !this.registration.namespaces.users || this.registration.namespaces.users.length === 0) { throw new Error("No user namespaces in registration"); } if (this.registration.namespaces.users.length !== 1) { throw new Error("Too many user namespaces registered: expecting exactly one"); } let userPrefix = (this.registration.namespaces.users[0].regex || "").split(":")[0]; if (!userPrefix.endsWith(".*") && !userPrefix.endsWith(".+")) { this.userPrefix = null; } else { this.userPrefix = userPrefix.substring(0, userPrefix.length - 2); // trim off the .* part } if (!this.registration.namespaces || !this.registration.namespaces.aliases || this.registration.namespaces.aliases.length === 0 || this.registration.namespaces.aliases.length !== 1) { this.aliasPrefix = null; } else { this.aliasPrefix = (this.registration.namespaces.aliases[0].regex || "").split(":")[0]; if (!this.aliasPrefix.endsWith(".*") && !this.aliasPrefix.endsWith(".+")) { this.aliasPrefix = null; } else { this.aliasPrefix = this.aliasPrefix.substring(0, this.aliasPrefix.length - 2); // trim off the .* part } } } /** * Gets the express app instance which is serving requests. Not recommended for * general usage, but may be used to append routes to the web server. */ public get expressAppInstance() { return this.app; } /** * Gets the bridge-specific APIs for this application service. */ public get bridge(): MatrixBridge { return this.bridgeInstance; } /** * Get the application service's "bot" user ID (the sender_localpart). */ public get botUserId(): string { return this.getUserId(this.registration.sender_localpart); } /** * Get the application service's "bot" Intent (the sender_localpart). * @returns {Intent} The intent for the application service itself. */ public get botIntent(): Intent { return this.getIntentForUserId(this.botUserId); } /** * Get the application service's "bot" MatrixClient (the sender_localpart). * Normally the botIntent should be used to ensure that the bot user is safely * handled. * @returns {MatrixClient} The client for the application service itself. */ public get botClient(): MatrixClient { return this.botIntent.underlyingClient; } /** * Starts the application service, opening the bind address to begin processing requests. * @returns {Promise<void>} resolves when started */ public begin(): Promise<void> { return new Promise<void>((resolve, reject) => { this.appServer = this.app.listen(this.options.port, this.options.bindAddress, () => resolve()); }).then(async () => { if (this.options.intentOptions?.encryption) { await this.botIntent.enableEncryption(); } else { await this.botIntent.ensureRegistered(); } }); } /** * Stops the application service, freeing the web server. */ public stop(): void { if (!this.appServer) return; this.appServer.close(); } /** * Gets an intent for a given localpart. The user ID will be formed with the domain name given * in the constructor. * @param localpart The localpart to get an Intent for. * @returns {Intent} An Intent for the user. */ public getIntent(localpart: string): Intent { return this.getIntentForUserId(this.getUserId(localpart)); } /** * Gets a full user ID for a given localpart. The user ID will be formed with the domain name given * in the constructor. * @param localpart The localpart to get a user ID for. * @returns {string} The user's ID. */ public getUserId(localpart: string): string { return `@${localpart}:${this.options.homeserverName}`; } /** * Gets an Intent for a given user suffix. The prefix is automatically detected from the registration * options. * @param suffix The user's suffix * @returns {Intent} An Intent for the user. */ public getIntentForSuffix(suffix: string): Intent { return this.getIntentForUserId(this.getUserIdForSuffix(suffix)); } /** * Gets a full user ID for a given suffix. The prefix is automatically detected from the registration * options. * @param suffix The user's suffix * @returns {string} The user's ID. */ public getUserIdForSuffix(suffix: string): string { if (!this.userPrefix) { throw new Error(`Cannot use getUserIdForSuffix, provided namespace did not include a valid suffix`); } return `${this.userPrefix}${suffix}:${this.options.homeserverName}`; } /** * Gets an Intent for a given user ID. * @param {string} userId The user ID to get an Intent for. * @returns {Intent} An Intent for the user. */ public getIntentForUserId(userId: string): Intent { let intent: Intent = this.intentsCache.get(userId); if (!intent) { intent = new Intent(this.options, userId, this); this.intentsCache.set(userId, intent); if (this.options.intentOptions.encryption) { intent.enableEncryption().catch(e => { LogService.error("Appservice", `Failed to set up crypto on intent ${userId}`, e); throw e; // re-throw to cause unhandled exception }); } } return intent; } /** * Gets the suffix for the provided user ID. If the user ID is not a namespaced * user, this will return a falsey value. * @param {string} userId The user ID to parse * @returns {string} The suffix from the user ID. */ public getSuffixForUserId(userId: string): string { if (!this.userPrefix) { throw new Error(`Cannot use getUserIdForSuffix, provided namespace did not include a valid suffix`); } if (!userId || !userId.startsWith(this.userPrefix) || !userId.endsWith(`:${this.options.homeserverName}`)) { // Invalid ID return null; } return userId .split('') .slice(this.userPrefix.length) .reverse() .slice(this.options.homeserverName.length + 1) .reverse() .join(''); } /** * Determines if a given user ID is namespaced by this application service. * @param {string} userId The user ID to check * @returns {boolean} true if the user is namespaced, false otherwise */ public isNamespacedUser(userId: string): boolean { return userId === this.botUserId || !!this.registration.namespaces?.users.find(({regex}) => new RegExp(regex).test(userId) ); } /** * Gets a full alias for a given localpart. The alias will be formed with the domain name given * in the constructor. * @param localpart The localpart to get an alias for. * @returns {string} The alias. */ public getAlias(localpart: string): string { return `#${localpart}:${this.options.homeserverName}`; } /** * Gets a full alias for a given suffix. The prefix is automatically detected from the registration * options. * @param suffix The alias's suffix * @returns {string} The alias. */ public getAliasForSuffix(suffix: string): string { if (!this.aliasPrefix) { throw new Error("Invalid configured alias prefix"); } return `${this.aliasPrefix}${suffix}:${this.options.homeserverName}`; } /** * Gets the localpart of an alias for a given suffix. The prefix is automatically detected from the registration * options. Useful for the createRoom endpoint. * @param suffix The alias's suffix * @returns {string} The alias localpart. */ public getAliasLocalpartForSuffix(suffix: string): string { if (!this.aliasPrefix) { throw new Error("Invalid configured alias prefix"); } return `${this.aliasPrefix.substr(1)}${suffix}`; } /** * Gets the suffix for the provided alias. If the alias is not a namespaced * alias, this will return a falsey value. * @param {string} alias The alias to parse * @returns {string} The suffix from the alias. */ public getSuffixForAlias(alias: string): string { if (!this.aliasPrefix) { throw new Error("Invalid configured alias prefix"); } if (!alias || !this.isNamespacedAlias(alias)) { // Invalid ID return null; } return alias .split('') .slice(this.aliasPrefix.length) .reverse() .slice(this.options.homeserverName.length + 1) .reverse() .join(''); } /** * Determines if a given alias is namespaced by this application service. * @param {string} alias The alias to check * @returns {boolean} true if the alias is namespaced, false otherwise */ public isNamespacedAlias(alias: string): boolean { if (!this.aliasPrefix) { throw new Error("Invalid configured alias prefix"); } return alias.startsWith(this.aliasPrefix) && alias.endsWith(":" + this.options.homeserverName); } /** * Adds a preprocessor to the event pipeline. When this appservice encounters an event, it * will try to run it through the preprocessors it can in the order they were added. * @param {IPreprocessor} preprocessor the preprocessor to add */ public addPreprocessor(preprocessor: IPreprocessor): void { if (!preprocessor) throw new Error("Preprocessor cannot be null"); const eventTypes = preprocessor.getSupportedEventTypes(); if (!eventTypes) return; // Nothing to do for (const eventType of eventTypes) { if (!this.eventProcessors[eventType]) this.eventProcessors[eventType] = []; this.eventProcessors[eventType].push(preprocessor); } } /** * Sets the visibility of a room in the appservice's room directory. * @param {string} networkId The network ID to group the room under. * @param {string} roomId The room ID to manipulate the visibility of. * @param {"public" | "private"} visibility The visibility to set for the room. * @return {Promise<any>} resolves when the visibility has been updated. */ public setRoomDirectoryVisibility(networkId: string, roomId: string, visibility: "public" | "private") { roomId = encodeURIComponent(roomId); networkId = encodeURIComponent(networkId); return this.botClient.doRequest("PUT", `/_matrix/client/r0/directory/list/appservice/${networkId}/${roomId}`, null, { visibility, }); } private async processEphemeralEvent(event: any): Promise<any> { if (!event) return event; if (!this.eventProcessors[event["type"]]) return event; for (const processor of this.eventProcessors[event["type"]]) { await processor.processEvent(event, this.botIntent.underlyingClient, EventKind.EphemeralEvent); } return event; } private async processEvent(event: any): Promise<any> { if (!event) return event; if (!this.eventProcessors[event["type"]]) return event; for (const processor of this.eventProcessors[event["type"]]) { await processor.processEvent(event, this.botIntent.underlyingClient, EventKind.RoomEvent); } return event; } private processMembershipEvent(event: any): void { if (!event["content"]) return; const targetMembership = event["content"]["membership"]; if (targetMembership === "join") { this.emit("room.join", event["room_id"], event); } else if (targetMembership === "ban" || targetMembership === "leave") { this.emit("room.leave", event["room_id"], event); } else if (targetMembership === "invite") { this.emit("room.invite", event["room_id"], event); } } private isAuthed(req: any): boolean { let providedToken = req.query ? req.query["access_token"] : null; if (req.headers && req.headers["Authorization"]) { const authHeader = req.headers["Authorization"]; if (!authHeader.startsWith("Bearer ")) providedToken = null; else providedToken = authHeader.substring("Bearer ".length); } return providedToken === this.registration.hs_token; } private async onTransaction(req: express.Request, res: express.Response): Promise<any> { if (!this.isAuthed(req)) { res.status(401).json({errcode: "AUTH_FAILED", error: "Authentication failed"}); return; } if (typeof (req.body) !== "object") { res.status(400).json({errcode: "BAD_REQUEST", error: "Expected JSON"}); return; } if (!req.body["events"] || !Array.isArray(req.body["events"])) { res.status(400).json({errcode: "BAD_REQUEST", error: "Invalid JSON: expected events"}); return; } const txnId = req.params["txnId"]; if (await Promise.resolve(this.storage.isTransactionCompleted(txnId))) { res.status(200).json({}); return; } if (this.pendingTransactions[txnId]) { try { await this.pendingTransactions[txnId]; res.status(200).json({}); } catch (e) { LogService.error("Appservice", e); res.status(500).json({}); } return; } LogService.info("Appservice", "Processing transaction " + txnId); this.pendingTransactions[txnId] = new Promise<void>(async (resolve) => { // Process all the crypto stuff first to ensure that future transactions (if not this one) // will decrypt successfully. We start with EDUs because we need structures to put counts // and such into in a later stage, and EDUs are independent of crypto. const byUserId: { [userId: string]: { counts: Record<string, Number>; toDevice: any[]; unusedFallbacks: OTKAlgorithm[]; }; } = {}; const orderedEdus = []; if (Array.isArray(req.body["de.sorunome.msc2409.to_device"])) { orderedEdus.push(...req.body["de.sorunome.msc2409.to_device"].map(e => ({ ...e, unsigned: { ...e['unsigned'], [EDU_ANNOTATION_KEY]: EduAnnotation.ToDevice, }, }))); } if (Array.isArray(req.body["de.sorunome.msc2409.ephemeral"])) { orderedEdus.push(...req.body["de.sorunome.msc2409.ephemeral"].map(e => ({ ...e, unsigned: { ...e['unsigned'], [EDU_ANNOTATION_KEY]: EduAnnotation.Ephemeral, }, }))); } for (let event of orderedEdus) { if (event['edu_type']) event['type'] = event['edu_type']; // handle property change during MSC2409's course LogService.info("Appservice", `Processing ${event['unsigned'][EDU_ANNOTATION_KEY]} event of type ${event["type"]}`); event = await this.processEphemeralEvent(event); // These events aren't tied to rooms, so just emit them generically this.emit("ephemeral.event", event); if (event["type"] === "m.room.encrypted" || event[EDU_ANNOTATION_KEY] === EduAnnotation.ToDevice) { const toUser = event["to_user_id"]; const intent = this.getIntentForUserId(toUser); await intent.enableEncryption(); if (!byUserId[toUser]) byUserId[toUser] = {counts: null, toDevice: null, unusedFallbacks: null}; if (!byUserId[toUser].toDevice) byUserId[toUser].toDevice = []; byUserId[toUser].toDevice.push(event); } } if (this.cryptoStorage) { const deviceLists: {changed: string[], removed: string[]} = req.body["org.matrix.msc3202.device_lists"] ?? { changed: [], removed: [] }; const otks = req.body["org.matrix.msc3202.device_one_time_key_counts"]; if (otks) { for (const userId of Object.keys(otks)) { const intent = this.getIntentForUserId(userId); await intent.enableEncryption(); const otksForUser = otks[userId][intent.underlyingClient.crypto.clientDeviceId]; if (otksForUser) { if (!byUserId[userId]) byUserId[userId] = {counts: null, toDevice: null, unusedFallbacks: null}; byUserId[userId].counts = otksForUser; } } } const fallbacks = req.body["org.matrix.msc3202.device_unused_fallback_key_types"]; if (fallbacks) { for (const userId of Object.keys(fallbacks)) { const intent = this.getIntentForUserId(userId); await intent.enableEncryption(); const fallbacksForUser = fallbacks[userId][intent.underlyingClient.crypto.clientDeviceId]; if (Array.isArray(fallbacksForUser) && !fallbacksForUser.includes(OTKAlgorithm.Signed)) { if (!byUserId[userId]) byUserId[userId] = {counts: null, toDevice: null, unusedFallbacks: null}; byUserId[userId].unusedFallbacks = fallbacksForUser; } } } for (const userId of Object.keys(byUserId)) { const intent = this.getIntentForUserId(userId); await intent.enableEncryption(); const info = byUserId[userId]; const userStorage = this.storage.storageForUser(userId); if (!info.toDevice) info.toDevice = []; if (!info.unusedFallbacks) info.unusedFallbacks = JSON.parse(await userStorage.readValue("last_unused_fallbacks") || "[]"); if (!info.counts) info.counts = JSON.parse(await userStorage.readValue("last_counts") || "{}"); LogService.info("Appservice", `Updating crypto state for ${userId}`); await intent.underlyingClient.crypto.updateSyncData(info.toDevice, info.counts, info.unusedFallbacks, deviceLists.changed, deviceLists.removed); } } for (let event of req.body["events"]) { LogService.info("Appservice", `Processing event of type ${event["type"]}`); event = await this.processEvent(event); if (event['type'] === 'm.room.encrypted' && this.cryptoStorage) { this.emit("room.encrypted_event", event["room_id"], event); try { const encrypted = new EncryptedRoomEvent(event); const roomId = event['room_id']; try { event = (await this.botClient.crypto.decryptRoomEvent(encrypted, roomId)).raw; event = await this.processEvent(event); this.emit("room.decrypted_event", roomId, event); // For logging purposes: show that the event was decrypted LogService.info("Appservice", `Processing decrypted event of type ${event["type"]}`); } catch (e1) { LogService.warn("Appservice", `Bot client was not able to decrypt ${roomId} ${event['event_id']} - trying other intents`); let tryUserId: string; try { // TODO: This could be more efficient const userIdsInRoom = await this.botClient.getJoinedRoomMembers(roomId); tryUserId = userIdsInRoom.find(u => this.isNamespacedUser(u)); } catch (e) { LogService.error("Appservice", "Failed to get members of room - cannot decrypt message"); } if (tryUserId) { const intent = this.getIntentForUserId(tryUserId); event = (await intent.underlyingClient.crypto.decryptRoomEvent(encrypted, roomId)).raw; event = await this.processEvent(event); this.emit("room.decrypted_event", roomId, event); // For logging purposes: show that the event was decrypted LogService.info("Appservice", `Processing decrypted event of type ${event["type"]}`); } else { // noinspection ExceptionCaughtLocallyJS throw e1; } } } catch (e) { LogService.error("Appservice", `Decryption error on ${event['room_id']} ${event['event_id']}`, e); this.emit("room.failed_decryption", event['room_id'], event, e); } } this.emit("room.event", event["room_id"], event); if (event['type'] === 'm.room.message') { this.emit("room.message", event["room_id"], event); } if (event['type'] === 'm.room.member' && this.isNamespacedUser(event['state_key'])) { this.processMembershipEvent(event); } if (event['type'] === 'm.room.tombstone' && event['state_key'] === '') { this.emit("room.archived", event['room_id'], event); } if (event['type'] === 'm.room.create' && event['state_key'] === '' && event['content'] && event['content']['predecessor']) { this.emit("room.upgraded", event['room_id'], event); } } resolve(); }); try { await this.pendingTransactions[txnId]; await Promise.resolve(this.storage.setTransactionCompleted(txnId)); res.status(200).json({}); } catch (e) { LogService.error("Appservice", e); res.status(500).json({}); } } private async onUser(req: express.Request, res: express.Response): Promise<any> { if (!this.isAuthed(req)) { res.status(401).json({errcode: "AUTH_FAILED", error: "Authentication failed"}); return; } const userId = req.params["userId"]; this.emit("query.user", userId, async (result) => { if (result.then) result = await result; if (result === false) { res.status(404).json({errcode: "USER_DOES_NOT_EXIST", error: "User not created"}); } else { const intent = this.getIntentForUserId(userId); await intent.ensureRegistered(); if (result.display_name) await intent.underlyingClient.setDisplayName(result.display_name); if (result.avatar_mxc) await intent.underlyingClient.setAvatarUrl(result.avatar_mxc); res.status(200).json(result); // return result for debugging + testing } }); } private async onRoomAlias(req: express.Request, res: express.Response): Promise<any> { if (!this.isAuthed(req)) { res.status(401).json({errcode: "AUTH_FAILED", error: "Authentication failed"}); return; } const roomAlias = req.params["roomAlias"]; this.emit("query.room", roomAlias, async (result) => { if (result.then) result = await result; if (result === false) { res.status(404).json({errcode: "ROOM_DOES_NOT_EXIST", error: "Room not created"}); } else { const intent = this.botIntent; await intent.ensureRegistered(); result["room_alias_name"] = roomAlias.substring(1).split(':')[0]; result["__roomId"] = await intent.underlyingClient.createRoom(result); res.status(200).json(result); // return result for debugging + testing } }); } private onThirdpartyProtocol(req: express.Request, res: express.Response) { if (!this.isAuthed(req)) { res.status(401).json({errcode: "AUTH_FAILED", error: "Authentication failed"}); return; } const protocol = req.params["protocol"]; if (!this.registration.protocols.includes(protocol)) { res.status(404).json({ errcode: "PROTOCOL_NOT_HANDLED", error: "Protocol is not handled by this appservice" }); return; } this.emit("thirdparty.protocol", protocol, (protocolResponse: IApplicationServiceProtocol) => { res.status(200).json(protocolResponse); }); } private handleThirdpartyObject(req: express.Request, res: express.Response, objType: string, matrixId?: string) { if (!this.isAuthed(req)) { res.status(401).json({errcode: "AUTH_FAILED", error: "Authentication failed"}); return; } const protocol = req.params["protocol"]; const responseFunc = (items: any[]) => { if (items && items.length > 0) { res.status(200).json(items); return; } res.status(404).json({ errcode: "NO_MAPPING_FOUND", error: "No mappings found" }); }; // Lookup remote objects(s) if (protocol) { // If protocol is given, we are looking up a objects based on fields if (!this.registration.protocols.includes(protocol)) { res.status(404).json({ errcode: "PROTOCOL_NOT_HANDLED", error: "Protocol is not handled by this appservice" }); return; } // Remove the access_token delete req.query.access_token; this.emit(`thirdparty.${objType}.remote`, protocol, req.query, responseFunc); return; } else if (matrixId) { // If a user ID is given, we are looking up a remote objects based on a id this.emit(`thirdparty.${objType}.matrix`, matrixId, responseFunc); return; } res.status(400).json({ errcode: "INVALID_PARAMETERS", error: "Invalid parameters given" }); } private onThirdpartyUser(req: express.Request, res: express.Response) { return this.handleThirdpartyObject(req, res, "user", req.query["userid"] as string); } private onThirdpartyLocation(req: express.Request, res: express.Response) { return this.handleThirdpartyObject(req, res, "location", req.query["alias"] as string); } }
the_stack
import React, { useState, useEffect, useCallback } from "react"; import CopyToClipboard from "react-copy-to-clipboard"; import { Card, Button, Text, Box, Heading, Flex } from "theme-ui"; import { Percent, MINIMUM_COLLATERAL_RATIO, CRITICAL_COLLATERAL_RATIO, UserTrove, Decimal } from "@liquity/lib-base"; import { BlockPolledLiquityStoreState } from "@liquity/lib-ethers"; import { useLiquitySelector } from "@liquity/lib-react"; import { shortenAddress } from "../utils/shortenAddress"; import { useLiquity } from "../hooks/LiquityContext"; import { COIN } from "../strings"; import { Icon } from "./Icon"; import { LoadingOverlay } from "./LoadingOverlay"; import { Transaction } from "./Transaction"; import { Tooltip } from "./Tooltip"; import { Abbreviation } from "./Abbreviation"; const rowHeight = "40px"; const liquidatableInNormalMode = (trove: UserTrove, price: Decimal) => [trove.collateralRatioIsBelowMinimum(price), "Collateral ratio not low enough"] as const; const liquidatableInRecoveryMode = ( trove: UserTrove, price: Decimal, totalCollateralRatio: Decimal, lusdInStabilityPool: Decimal ) => { const collateralRatio = trove.collateralRatio(price); if (collateralRatio.gte(MINIMUM_COLLATERAL_RATIO) && collateralRatio.lt(totalCollateralRatio)) { return [ trove.debt.lte(lusdInStabilityPool), "There's not enough LUSD in the Stability pool to cover the debt" ] as const; } else { return liquidatableInNormalMode(trove, price); } }; type RiskyTrovesProps = { pageSize: number; }; const select = ({ numberOfTroves, price, total, lusdInStabilityPool, blockTag }: BlockPolledLiquityStoreState) => ({ numberOfTroves, price, recoveryMode: total.collateralRatioIsBelowCritical(price), totalCollateralRatio: total.collateralRatio(price), lusdInStabilityPool, blockTag }); export const RiskyTroves: React.FC<RiskyTrovesProps> = ({ pageSize }) => { const { blockTag, numberOfTroves, recoveryMode, totalCollateralRatio, lusdInStabilityPool, price } = useLiquitySelector(select); const { liquity } = useLiquity(); const [loading, setLoading] = useState(true); const [troves, setTroves] = useState<UserTrove[]>(); const [reload, setReload] = useState({}); const forceReload = useCallback(() => setReload({}), []); const [page, setPage] = useState(0); const numberOfPages = Math.ceil(numberOfTroves / pageSize) || 1; const clampedPage = Math.min(page, numberOfPages - 1); const nextPage = () => { if (clampedPage < numberOfPages - 1) { setPage(clampedPage + 1); } }; const previousPage = () => { if (clampedPage > 0) { setPage(clampedPage - 1); } }; useEffect(() => { if (page !== clampedPage) { setPage(clampedPage); } }, [page, clampedPage]); useEffect(() => { let mounted = true; setLoading(true); liquity .getTroves( { first: pageSize, sortedBy: "ascendingCollateralRatio", startingAt: clampedPage * pageSize }, { blockTag } ) .then(troves => { if (mounted) { setTroves(troves); setLoading(false); } }); return () => { mounted = false; }; // Omit blockTag from deps on purpose // eslint-disable-next-line }, [liquity, clampedPage, pageSize, reload]); useEffect(() => { forceReload(); }, [forceReload, numberOfTroves]); const [copied, setCopied] = useState<string>(); useEffect(() => { if (copied !== undefined) { let cancelled = false; setTimeout(() => { if (!cancelled) { setCopied(undefined); } }, 2000); return () => { cancelled = true; }; } }, [copied]); return ( <Card sx={{ width: "100%" }}> <Heading> <Abbreviation short="Troves">Risky Troves</Abbreviation> <Flex sx={{ alignItems: "center" }}> {numberOfTroves !== 0 && ( <> <Abbreviation short={`page ${clampedPage + 1} / ${numberOfPages}`} sx={{ mr: [0, 3], fontWeight: "body", fontSize: [1, 2], letterSpacing: [-1, 0] }} > {clampedPage * pageSize + 1}-{Math.min((clampedPage + 1) * pageSize, numberOfTroves)}{" "} of {numberOfTroves} </Abbreviation> <Button variant="titleIcon" onClick={previousPage} disabled={clampedPage <= 0}> <Icon name="chevron-left" size="lg" /> </Button> <Button variant="titleIcon" onClick={nextPage} disabled={clampedPage >= numberOfPages - 1} > <Icon name="chevron-right" size="lg" /> </Button> </> )} <Button variant="titleIcon" sx={{ opacity: loading ? 0 : 1, ml: [0, 3] }} onClick={forceReload} > <Icon name="redo" size="lg" /> </Button> </Flex> </Heading> {!troves || troves.length === 0 ? ( <Box sx={{ p: [2, 3] }}> <Box sx={{ p: 4, fontSize: 3, textAlign: "center" }}> {!troves ? "Loading..." : "There are no Troves yet"} </Box> </Box> ) : ( <Box sx={{ p: [2, 3] }}> <Box as="table" sx={{ mt: 2, pl: [1, 4], width: "100%", textAlign: "center", lineHeight: 1.15 }} > <colgroup> <col style={{ width: "50px" }} /> <col /> <col /> <col /> <col style={{ width: rowHeight }} /> </colgroup> <thead> <tr> <th>Owner</th> <th> <Abbreviation short="Coll.">Collateral</Abbreviation> <Box sx={{ fontSize: [0, 1], fontWeight: "body", opacity: 0.5 }}>ETH</Box> </th> <th> Debt <Box sx={{ fontSize: [0, 1], fontWeight: "body", opacity: 0.5 }}>{COIN}</Box> </th> <th> Coll. <br /> Ratio </th> <th></th> </tr> </thead> <tbody> {troves.map( trove => !trove.isEmpty && ( // making sure the Trove hasn't been liquidated // (TODO: remove check after we can fetch multiple Troves in one call) <tr key={trove.ownerAddress}> <td style={{ display: "flex", alignItems: "center", height: rowHeight }} > <Tooltip message={trove.ownerAddress} placement="top"> <Text variant="address" sx={{ width: ["73px", "unset"], overflow: "hidden", position: "relative" }} > {shortenAddress(trove.ownerAddress)} <Box sx={{ display: ["block", "none"], position: "absolute", top: 0, right: 0, width: "50px", height: "100%", background: "linear-gradient(90deg, rgba(255,255,255,0) 0%, rgba(255,255,255,1) 100%)" }} /> </Text> </Tooltip> <CopyToClipboard text={trove.ownerAddress} onCopy={() => setCopied(trove.ownerAddress)} > <Button variant="icon" sx={{ width: "24px", height: "24px" }}> <Icon name={copied === trove.ownerAddress ? "clipboard-check" : "clipboard"} size="sm" /> </Button> </CopyToClipboard> </td> <td> <Abbreviation short={trove.collateral.shorten()}> {trove.collateral.prettify(4)} </Abbreviation> </td> <td> <Abbreviation short={trove.debt.shorten()}> {trove.debt.prettify()} </Abbreviation> </td> <td> {(collateralRatio => ( <Text color={ collateralRatio.gt(CRITICAL_COLLATERAL_RATIO) ? "success" : collateralRatio.gt(1.2) ? "warning" : "danger" } > {new Percent(collateralRatio).prettify()} </Text> ))(trove.collateralRatio(price))} </td> <td> <Transaction id={`liquidate-${trove.ownerAddress}`} tooltip="Liquidate" requires={[ recoveryMode ? liquidatableInRecoveryMode( trove, price, totalCollateralRatio, lusdInStabilityPool ) : liquidatableInNormalMode(trove, price) ]} send={liquity.send.liquidate.bind(liquity.send, trove.ownerAddress)} > <Button variant="dangerIcon"> <Icon name="trash" /> </Button> </Transaction> </td> </tr> ) )} </tbody> </Box> </Box> )} {loading && <LoadingOverlay />} </Card> ); };
the_stack
import { Form, Radio } from 'antd'; import { LoadingMask } from 'app/components'; import useI18NPrefix from 'app/hooks/useI18NPrefix'; import classnames from 'classnames'; import { memo, useCallback, useMemo, useState } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import styled from 'styled-components/macro'; import { listToTree } from 'utils/utils'; import { PermissionLevels, ResourceTypes, SubjectTypes, Viewpoints, VizResourceSubTypes, } from '../../constants'; import { makeSelectPrivileges } from '../../slice/selectors'; import { grantPermissions } from '../../slice/thunks'; import { DataSourceTreeNode, DataSourceViewModel, GrantPermissionParams, Privilege, } from '../../slice/types'; import { getDefaultPermissionArray } from '../../utils'; import { IndependentPermissionSetting } from './IndependentPermissionSetting'; import { PermissionTable } from './PermissionTable'; import { calcPermission, getChangedPermission, getIndependentPermissionChangeParams, getPrivilegeResult, getRecalculatedPrivileges, getTreeNodeWithPermission, setTreeDataWithPrivilege, } from './utils'; interface PermissionFormProps { viewpoint: Viewpoints; viewpointType: ResourceTypes | SubjectTypes; viewpointId: string; selected: boolean; orgId: string; dataSourceType: ResourceTypes; folders: DataSourceViewModel[] | undefined; storyboards: DataSourceViewModel[] | undefined; folderListLoading: boolean; storyboardListLoading: boolean; permissionLoading: boolean; } export const VizPermissionForm = memo( ({ viewpoint, viewpointType, viewpointId, selected, orgId, dataSourceType, folders, storyboards, folderListLoading, storyboardListLoading, permissionLoading, }: PermissionFormProps) => { const [vizType, setVizType] = useState<'folder' | 'persentation'>('folder'); const dispatch = useDispatch(); const selectPrivileges = useMemo(makeSelectPrivileges, []); const privileges = useSelector(state => selectPrivileges(state, { viewpoint, dataSourceType }), ); const t = useI18NPrefix('permission'); const vizTreeData = useMemo(() => { if (folders && storyboards && privileges) { const originTreeData = listToTree( folders.concat(storyboards), null, [], ) as DataSourceTreeNode[]; return setTreeDataWithPrivilege( originTreeData, [...privileges], viewpoint, viewpointType, dataSourceType, ); } else { return []; } }, [ viewpoint, viewpointType, dataSourceType, folders, storyboards, privileges, ]); const vizTypeChange = useCallback(e => { setVizType(e.target.value); }, []); const { moduleEnabled, storyboardCreateEnabled } = useMemo(() => { let moduleEnabled = PermissionLevels.Disable; let storyboardCreateEnabled = PermissionLevels.Disable; privileges?.forEach(({ resourceId, permission }) => { if (resourceId === '*') { moduleEnabled = permission; } if (resourceId === VizResourceSubTypes.Storyboard) { storyboardCreateEnabled = permission; } }); return { moduleEnabled, storyboardCreateEnabled }; }, [privileges]); const independentPermissionChange = useCallback( resourceId => e => { if (privileges) { const val = e.target.value; const params = getIndependentPermissionChangeParams( resourceId, val, privileges, orgId, viewpointId, viewpointType as SubjectTypes, dataSourceType as ResourceTypes, ); dispatch( grantPermissions({ params, options: { viewpoint, viewpointType, dataSourceType, reserved: val ? privileges : privileges.filter(p => p.resourceId !== resourceId), }, resolve: () => {}, }), ); } }, [ dispatch, viewpoint, viewpointType, viewpointId, dataSourceType, privileges, orgId, ], ); const privilegeChange = useCallback( () => ( record: DataSourceTreeNode, newPermissionArray: PermissionLevels[], index: number, base: PermissionLevels, ) => { if (viewpoint === Viewpoints.Subject) { // 找到变化的的单条资源,设置它及其子资源权限 const changedTreeData = getTreeNodeWithPermission( vizTreeData, ({ id, permissionArray, path }, parentPermissionArray) => id === record.id ? newPermissionArray : path.includes(record.id) ? getChangedPermission( parentPermissionArray[index] === PermissionLevels.Disable, permissionArray, index, base, ) : permissionArray, getDefaultPermissionArray(), ); // 根据改变后的树重新计算出权限列表 const recalculatedPrivileges = getRecalculatedPrivileges( changedTreeData, viewpoint, viewpointType, viewpointId, orgId, ); // 根据新旧权限列表计算出请求参数 const { created, updated, deleted, reserved } = getPrivilegeResult( [...privileges!], recalculatedPrivileges, ); dispatch( grantPermissions({ params: { permissionToCreate: created, permissionToDelete: deleted, permissionToUpdate: updated, }, options: { viewpoint, viewpointType, dataSourceType, reserved }, resolve: () => {}, }), ); } else { let changedPrivilege: Privilege | undefined; const params: GrantPermissionParams['params'] = { permissionToCreate: [], permissionToDelete: [], permissionToUpdate: [], }; let reserved: Privilege[] = []; const newPermission = calcPermission(newPermissionArray); if ( calcPermission(record.permissionArray) === PermissionLevels.Disable ) { changedPrivilege = { orgId, resourceId: viewpointId, resourceType: viewpointType as ResourceTypes, subjectId: record.id, subjectType: record.type as SubjectTypes, permission: newPermission, }; params.permissionToCreate.push(changedPrivilege); reserved = [...privileges!]; } else { privileges!.forEach(p => { if (p.subjectId === record.id) { changedPrivilege = { ...p, permission: newPermission, }; if (newPermission === PermissionLevels.Disable) { params.permissionToDelete.push(changedPrivilege); } else { params.permissionToUpdate.push(changedPrivilege); reserved.push(changedPrivilege); } } else { reserved.push(p); } }); } dispatch( grantPermissions({ params, options: { viewpoint, viewpointType, dataSourceType, reserved }, resolve: () => {}, }), ); } }, [ dispatch, viewpoint, viewpointId, viewpointType, dataSourceType, orgId, privileges, vizTreeData, ], ); const modulePermissionValues = useMemo( () => [ { text: t( `modulePermissionLabel.${ PermissionLevels[PermissionLevels.Disable] }`, ), value: PermissionLevels.Disable, }, { text: t( `modulePermissionLabel.${ PermissionLevels[PermissionLevels.Enable] }`, ), value: PermissionLevels.Enable, }, ], [t], ); const createPermissionValues = useMemo( () => [ { text: t( `createPermissionLabel.${ PermissionLevels[PermissionLevels.Disable] }`, ), value: PermissionLevels.Disable, }, { text: t( `createPermissionLabel.${ PermissionLevels[PermissionLevels.Create] }`, ), value: PermissionLevels.Create, }, ], [t], ); return ( <Wrapper className={classnames({ selected })}> <LoadingMask loading={permissionLoading}> <FormContent labelAlign="left" labelCol={{ span: 4 }} wrapperCol={{ span: 18 }} > <IndependentPermissionSetting enabled={moduleEnabled} label={t('modulePermission')} extra={t('modulePermissionDesc')} values={modulePermissionValues} onChange={independentPermissionChange('*')} /> <Form.Item label={t('resourceDetail')}> <Radio.Group value={vizType} onChange={vizTypeChange}> <Radio value="folder">{t('folder')}</Radio> <Radio value="persentation">{t('presentation')}</Radio> </Radio.Group> </Form.Item> <Form.Item label=" " colon={false} className={classnames({ vizTable: true, selected: vizType === 'folder', })} > <PermissionTable viewpoint={viewpoint} viewpointType={viewpointType} dataSourceType={dataSourceType} dataSource={folders} resourceLoading={folderListLoading} privileges={privileges} onPrivilegeChange={privilegeChange} /> </Form.Item> {vizType === 'persentation' && ( <IndependentPermissionSetting enabled={storyboardCreateEnabled} label={t('createStoryboard')} values={createPermissionValues} onChange={independentPermissionChange( VizResourceSubTypes.Storyboard, )} /> )} <Form.Item label=" " colon={false} className={classnames({ vizTable: true, selected: vizType === 'persentation', })} > <PermissionTable viewpoint={viewpoint} viewpointType={viewpointType} dataSourceType={dataSourceType} dataSource={storyboards} resourceLoading={storyboardListLoading} privileges={privileges} onPrivilegeChange={privilegeChange} /> </Form.Item> </FormContent> </LoadingMask> </Wrapper> ); }, ); const Wrapper = styled.div` display: none; &.selected { position: relative; display: block; } `; const FormContent = styled(Form)` width: 960px; .vizTable { display: none; &.selected { display: flex; } } `;
the_stack
import { Injectable } from '@angular/core'; import Nano from 'hw-app-nano'; import TransportU2F from '@ledgerhq/hw-transport-u2f'; import TransportUSB from '@ledgerhq/hw-transport-webusb'; import TransportHID from '@ledgerhq/hw-transport-webhid'; import TransportBLE from '@ledgerhq/hw-transport-web-ble'; import Transport from '@ledgerhq/hw-transport'; import * as LedgerLogs from '@ledgerhq/logs'; import {Subject} from 'rxjs'; import {ApiService} from './api.service'; import {NotificationService} from './notification.service'; import { environment } from '../../environments/environment'; import {DesktopService} from './desktop.service'; import { AppSettingsService } from './app-settings.service'; export const STATUS_CODES = { SECURITY_STATUS_NOT_SATISFIED: 0x6982, CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985, INVALID_SIGNATURE: 0x6a81, CACHE_MISS: 0x6a82 }; export const LedgerStatus = { NOT_CONNECTED: 'not-connected', LOCKED: 'locked', READY: 'ready', }; export interface LedgerData { status: string; nano: any|null; transport: Transport|null; } export interface LedgerLog { type: string; message?: string; data?: any; id: string; date: Date; } const zeroBlock = '0000000000000000000000000000000000000000000000000000000000000000'; @Injectable() export class LedgerService { walletPrefix = `44'/165'/`; waitTimeout = 300000; normalTimeout = 5000; pollInterval = 15000; pollingLedger = false; ledger: LedgerData = { status: LedgerStatus.NOT_CONNECTED, nano: null, transport: null, }; // isDesktop = true; isDesktop = environment.desktop; queryingDesktopLedger = false; supportsU2F = false; supportsWebHID = false; supportsWebUSB = false; supportsBluetooth = false; supportsUSB = false; transportMode: 'U2F' | 'USB' | 'HID' | 'Bluetooth' = 'U2F'; DynamicTransport = TransportU2F; ledgerStatus$: Subject<any> = new Subject(); desktopMessage$ = new Subject(); constructor(private api: ApiService, private desktop: DesktopService, private notifications: NotificationService, private appSettings: AppSettingsService) { if (this.isDesktop) { this.configureDesktop(); } else { this.checkBrowserSupport().then(() => { if (appSettings.getAppSetting('ledgerReconnect') === 'bluetooth') { this.enableBluetoothMode(true); } }); } } // Scraps binding to any existing transport/nano object resetLedger() { this.ledger.transport = null; this.ledger.nano = null; } /** * Prepare the main listener for events from the desktop client. * Dispatches new messages via the main Observables */ configureDesktop() { this.desktop.connect(); this.desktop.on('ledger', (event, message) => { if (!message || !message.event) return; switch (message.event) { case 'ledger-status': this.ledger.status = message.data.status; this.ledgerStatus$.next({ status: message.data.status, statusText: message.data.statusText }); break; case 'account-details': case 'cache-block': case 'sign-block': this.desktopMessage$.next(message); break; } }); this.supportsUSB = true; } /** * Check which transport protocols are supported by the browser */ async checkBrowserSupport() { await Promise.all([ TransportU2F.isSupported().then(supported => this.supportsU2F = supported), TransportHID.isSupported().then(supported => this.supportsWebHID = supported), TransportUSB.isSupported().then(supported => this.supportsWebUSB = supported), TransportBLE.isSupported().then(supported => this.supportsBluetooth = supported), ]); this.supportsUSB = this.supportsU2F || this.supportsWebHID || this.supportsWebUSB; } /** * Detect the optimal USB transport protocol for the current browser and OS */ detectUsbTransport() { const isWindows = window.navigator.platform.includes('Win'); if (isWindows && this.supportsWebHID) { // Prefer WebHID on Windows due to stability issues with WebUSB this.transportMode = 'HID'; this.DynamicTransport = TransportHID; } else if (this.supportsWebUSB) { // Else prefer WebUSB this.transportMode = 'USB'; this.DynamicTransport = TransportUSB; } else if (this.supportsWebHID) { // Fallback to WebHID this.transportMode = 'HID'; this.DynamicTransport = TransportHID; } else { // Legacy browsers this.transportMode = 'U2F'; this.DynamicTransport = TransportU2F; } } /** * Enable or disable bluetooth communication, if supported * @param enabled The bluetooth enabled state */ enableBluetoothMode(enabled: boolean) { if (this.supportsBluetooth && enabled) { this.transportMode = 'Bluetooth'; this.DynamicTransport = TransportBLE; } else { this.detectUsbTransport(); } } /** * Get the next response coming from the desktop client for a specific event/filter * @param eventType * @param {any} filterFn * @returns {Promise<any>} */ async getDesktopResponse(eventType, filterFn?) { return new Promise((resolve, reject) => { const sub = this.desktopMessage$ .subscribe((response: any) => { // Listen to all desktop messages until one passes our filters if (response.event !== eventType) { return; // Not the event we want. } if (filterFn) { const shouldSkip = filterFn(response.data); // This function should return boolean if (!shouldSkip) return; // This is not the message the subscriber wants } sub.unsubscribe(); // This is a message we want, safe to unsubscribe to further messages now. if (response.data && response.data.error === true) { return reject(new Error(response.data.errorMessage)); // Request failed! } resolve(response.data); }, err => { console.log(`Desktop message got error!`, err); reject(err); }); }); } async getLedgerAccountDesktop(accountIndex, showOnScreen) { if (this.queryingDesktopLedger) { throw new Error(`Already querying desktop device, please wait`); } this.queryingDesktopLedger = true; this.desktop.send('ledger', { event: 'account-details', data: { accountIndex, showOnScreen } }); try { const details = await this.getDesktopResponse('account-details', a => a.accountIndex === accountIndex); this.queryingDesktopLedger = false; return details; } catch (err) { this.queryingDesktopLedger = false; throw err; } } async updateCacheDesktop(accountIndex, cacheData, signature) { if (this.queryingDesktopLedger) { throw new Error(`Already querying desktop device, please wait`); } this.queryingDesktopLedger = true; this.desktop.send('ledger', { event: 'cache-block', data: { accountIndex, cacheData, signature } }); try { const details = await this.getDesktopResponse('cache-block', a => a.accountIndex === accountIndex); this.queryingDesktopLedger = false; return details; } catch (err) { this.queryingDesktopLedger = false; throw new Error(`Error caching block: ${err.message}`); } } async signBlockDesktop(accountIndex, blockData) { if (this.queryingDesktopLedger) { throw new Error(`Already querying desktop device, please wait`); } this.queryingDesktopLedger = true; this.desktop.send('ledger', { event: 'sign-block', data: { accountIndex, blockData } }); try { const details = await this.getDesktopResponse('sign-block', a => a.accountIndex === accountIndex); this.queryingDesktopLedger = false; return details; } catch (err) { this.queryingDesktopLedger = false; throw new Error(`Error signing block: ${err.message}`); } } async loadTransport() { return new Promise((resolve, reject) => { this.DynamicTransport.create().then(trans => { // LedgerLogs.listen((log: LedgerLog) => console.log(`Ledger: ${log.type}: ${log.message}`)); this.ledger.transport = trans; this.ledger.transport.setExchangeTimeout(this.waitTimeout); // 5 minutes this.ledger.nano = new Nano(this.ledger.transport); resolve(this.ledger.transport); }).catch(reject); }); } /** * Main ledger loading function. Can be called multiple times to attempt a reconnect. * @param {boolean} hideNotifications * @returns {Promise<any>} */ async loadLedger(hideNotifications = false) { return new Promise(async (resolve, reject) => { // Desktop is handled completely differently. Send a message for status instead of setting anything up if (this.isDesktop) { if (!this.desktop.send('ledger', { event: 'get-ledger-status', data: { bluetooth: this.transportMode === 'Bluetooth' } })) { reject(new Error(`Electron\'s IPC was not loaded`)); } // Any response will be handled by the configureDesktop() function, which pipes responses into this observable const sub = this.ledgerStatus$.subscribe(newStatus => { if (newStatus.status === LedgerStatus.READY) { resolve(true); } else { reject(new Error(newStatus.statusText || `Unable to load desktop Ledger device`)); } sub.unsubscribe(); }, reject); return; } if (!this.ledger.transport) { // If in USB mode, detect best transport option if (this.transportMode !== 'Bluetooth') { this.detectUsbTransport(); this.appSettings.setAppSetting('ledgerReconnect', 'usb'); } else { this.appSettings.setAppSetting('ledgerReconnect', 'bluetooth'); } try { await this.loadTransport(); } catch (err) { if (err.name !== 'TransportOpenUserCancelled') { console.log(`Error loading ${this.transportMode} transport `, err); this.ledger.status = LedgerStatus.NOT_CONNECTED; this.ledgerStatus$.next({ status: this.ledger.status, statusText: `Unable to load Ledger transport: ${err.message || err}` }); } this.resetLedger(); resolve(false); } } if (!this.ledger.transport || !this.ledger.nano) { return resolve(false); } if (this.ledger.status === LedgerStatus.READY) { return resolve(true); // Already ready? } let resolved = false; // Set up a timeout when things are not ready setTimeout(() => { if (resolved) return; console.log(`Timeout expired, sending not connected`); this.ledger.status = LedgerStatus.NOT_CONNECTED; this.ledgerStatus$.next({ status: this.ledger.status, statusText: `Unable to detect Nano Ledger application (Timeout)` }); if (!hideNotifications) { this.notifications.sendWarning(`Unable to connect to the Ledger device. Make sure it is unlocked and the nano application is open`); } resolved = true; return resolve(false); }, 10000); // Try to load the app config try { const ledgerConfig = await this.ledger.nano.getAppConfiguration(); resolved = true; if (!ledgerConfig) return resolve(false); if (ledgerConfig && ledgerConfig.version) { this.ledger.status = LedgerStatus.LOCKED; this.ledgerStatus$.next({ status: this.ledger.status, statusText: `Nano app detected, but ledger is locked` }); } } catch (err) { console.log(`App config error: `, err); if (err.statusText === 'HALTED') { this.resetLedger(); } if (!hideNotifications && !resolved) { this.notifications.sendWarning(`Unable to connect to the Ledger device. Make sure your Ledger is unlocked. Restart the nano app on your Ledger if the error persists`); } resolved = true; return resolve(false); } // Attempt to load account 0 - which confirms the app is unlocked and ready try { const accountDetails = await this.getLedgerAccount(0); this.ledger.status = LedgerStatus.READY; this.ledgerStatus$.next({ status: this.ledger.status, statusText: `Nano Ledger application connected` }); if (!this.pollingLedger) { this.pollingLedger = true; this.pollLedgerStatus(); } } catch (err) { console.log(`Error on account details: `, err); if (err.statusCode === STATUS_CODES.SECURITY_STATUS_NOT_SATISFIED) { this.ledger.status = LedgerStatus.LOCKED; if (!hideNotifications) { this.notifications.sendWarning(`Ledger device locked. Unlock and open the nano application`); } } } resolve(true); }).catch(err => { console.log(`error when loading ledger `, err); if (!hideNotifications) { this.notifications.sendWarning(`Error loading Ledger device: ${typeof err === 'string' ? err : err.message}`, { length: 6000 }); } return null; }); } async updateCache(accountIndex, blockHash) { if (this.ledger.status !== LedgerStatus.READY) { await this.loadLedger(); // Make sure ledger is ready } const blockResponse = await this.api.blocksInfo([blockHash]); const blockData = blockResponse.blocks[blockHash]; if (!blockData) throw new Error(`Unable to load block data`); blockData.contents = JSON.parse(blockData.contents); const cacheData = { representative: blockData.contents.representative, balance: blockData.contents.balance, previousBlock: blockData.contents.previous === zeroBlock ? null : blockData.contents.previous, sourceBlock: blockData.contents.link, }; if (this.isDesktop) { return await this.updateCacheDesktop(accountIndex, cacheData, blockData.contents.signature); } else { return await this.ledger.nano.cacheBlock(this.ledgerPath(accountIndex), cacheData, blockData.contents.signature); } } async updateCacheOffline(accountIndex, blockData) { if (this.ledger.status !== LedgerStatus.READY) { await this.loadLedger(); // Make sure ledger is ready } const cacheData = { representative: blockData.representative, balance: blockData.balance, previousBlock: blockData.previous === zeroBlock ? null : blockData.previous, sourceBlock: blockData.link, }; if (this.isDesktop) { return await this.updateCacheDesktop(accountIndex, cacheData, blockData.signature); } else { return await this.ledger.nano.cacheBlock(this.ledgerPath(accountIndex), cacheData, blockData.signature); } } async signBlock(accountIndex: number, blockData: any) { if (this.ledger.status !== LedgerStatus.READY) { await this.loadLedger(); // Make sure ledger is ready } if (this.isDesktop) { return this.signBlockDesktop(accountIndex, blockData); } else { this.ledger.transport.setExchangeTimeout(this.waitTimeout); return await this.ledger.nano.signBlock(this.ledgerPath(accountIndex), blockData); } } ledgerPath(accountIndex: number) { return `${this.walletPrefix}${accountIndex}'`; } async getLedgerAccountWeb(accountIndex: number, showOnScreen = false) { this.ledger.transport.setExchangeTimeout(showOnScreen ? this.waitTimeout : this.normalTimeout); try { return await this.ledger.nano.getAddress(this.ledgerPath(accountIndex), showOnScreen); } catch (err) { throw err; } } async getLedgerAccount(accountIndex: number, showOnScreen = false) { if (this.isDesktop) { return await this.getLedgerAccountDesktop(accountIndex, showOnScreen); } else { return await this.getLedgerAccountWeb(accountIndex, showOnScreen); } } pollLedgerStatus() { if (!this.pollingLedger) return; setTimeout(async () => { await this.checkLedgerStatus(); this.pollLedgerStatus(); }, this.pollInterval); } async checkLedgerStatus() { if (this.ledger.status !== LedgerStatus.READY) { return; } try { const accountDetails = await this.getLedgerAccount(0); this.ledger.status = LedgerStatus.READY; } catch (err) { // Ignore race condition error, which means an action is pending on the ledger (such as block confirmation) if (err.name !== 'TransportRaceCondition') { console.log('Check ledger status failed ', err); this.ledger.status = LedgerStatus.NOT_CONNECTED; this.pollingLedger = false; this.resetLedger(); } } this.ledgerStatus$.next({ status: this.ledger.status, statusText: `` }); } }
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 Code that deals with condition-based filtering against lists of aircraft. */ namespace VRS { /** * The settings to use when creating a new instance of an AircraftFilterPropertyHandler. */ export interface AircraftFilterPropertyHandler_Settings extends FilterPropertyHandler_Settings { /** * The VRS.AircraftFilterProperty that this object handles. */ property: AircraftFilterPropertyEnum; /** * The callback that returns the value for this property from the aircraft. */ getValueCallback: (aircraft: Aircraft, options?: Filter_Options) => any; } /** * An object that describes a property on an aircraft, the ranges that the filters can be set to, its description and * how to fetch the property value from an aircraft object. */ export class AircraftFilterPropertyHandler extends FilterPropertyHandler { // Keeping these as public fields for backwards compatability property: AircraftFilterPropertyEnum; getValueCallback: (aircraft: Aircraft, options?: Filter_Options) => any; constructor(settings: AircraftFilterPropertyHandler_Settings) { super($.extend({ propertyEnumObject: VRS.AircraftFilterProperty }, settings)); if(!settings.getValueCallback) throw 'You must supply a getValueCallback'; this.property = settings.property; this.getValueCallback = settings.getValueCallback; } } /** * The pre-built list of VRS (and potentially 3rd party) property handlers. */ export var aircraftFilterPropertyHandlers: { [index: string]: AircraftFilterPropertyHandler } = VRS.aircraftFilterPropertyHandlers || {}; VRS.aircraftFilterPropertyHandlers[VRS.AircraftFilterProperty.Airport] = new VRS.AircraftFilterPropertyHandler({ property: VRS.AircraftFilterProperty.Airport, type: VRS.FilterPropertyType.TextListMatch, labelKey: 'Airport', isUpperCase: true, inputWidth: VRS.InputWidth.SixChar, getValueCallback: function(aircraft) { return aircraft.getAirportCodes(); }, serverFilterName: 'fAir' }); VRS.aircraftFilterPropertyHandlers[VRS.AircraftFilterProperty.Altitude] = new VRS.AircraftFilterPropertyHandler({ property: VRS.AircraftFilterProperty.Altitude, type: VRS.FilterPropertyType.NumberRange, labelKey: 'Altitude', minimumValue: -2000, maximumValue: 100000, decimalPlaces: 0, inputWidth: VRS.InputWidth.SixChar, getValueCallback: function(aircraft) { return aircraft.altitude.val; }, serverFilterName: 'fAlt', normaliseValue: function(value, unitDisplayPreferences) { return VRS.unitConverter.convertHeight(value, unitDisplayPreferences.getHeightUnit(), VRS.Height.Feet); } }); VRS.aircraftFilterPropertyHandlers[VRS.AircraftFilterProperty.Callsign] = new VRS.AircraftFilterPropertyHandler({ property: VRS.AircraftFilterProperty.Callsign, type: VRS.FilterPropertyType.TextMatch, labelKey: 'Callsign', isUpperCase: true, inputWidth: VRS.InputWidth.SixChar, getValueCallback: function(aircraft) { return aircraft.callsign.val; }, serverFilterName: 'fCall' }); VRS.aircraftFilterPropertyHandlers[VRS.AircraftFilterProperty.Country] = new VRS.AircraftFilterPropertyHandler({ property: VRS.AircraftFilterProperty.Country, type: VRS.FilterPropertyType.TextMatch, labelKey: 'Country', inputWidth: VRS.InputWidth.Long, getValueCallback: function(aircraft) { return aircraft.country.val; }, serverFilterName: 'fCou' }); VRS.aircraftFilterPropertyHandlers[VRS.AircraftFilterProperty.Distance] = new VRS.AircraftFilterPropertyHandler({ property: VRS.AircraftFilterProperty.Distance, type: VRS.FilterPropertyType.NumberRange, labelKey: 'Distance', minimumValue: 0, maximumValue: 30000, decimalPlaces: 2, inputWidth: VRS.InputWidth.SixChar, getValueCallback: function(aircraft) { return aircraft.distanceFromHereKm.val; }, serverFilterName: 'fDst', normaliseValue: function(value, unitDisplayPreferences) { return VRS.unitConverter.convertDistance(value, unitDisplayPreferences.getDistanceUnit(), VRS.Distance.Kilometre); } }); VRS.aircraftFilterPropertyHandlers[VRS.AircraftFilterProperty.EngineType] = new VRS.AircraftFilterPropertyHandler({ property: VRS.AircraftFilterProperty.EngineType, type: VRS.FilterPropertyType.EnumMatch, labelKey: 'EngineType', getValueCallback: function(aircraft) { return aircraft.engineType.val; }, getEnumValues: function() { return [ new VRS.ValueText({ value: VRS.EngineType.None, textKey: 'None' }), new VRS.ValueText({ value: VRS.EngineType.Piston, textKey: 'Piston' }), new VRS.ValueText({ value: VRS.EngineType.Turbo, textKey: 'Turbo' }), new VRS.ValueText({ value: VRS.EngineType.Electric, textKey: 'Electric' }), new VRS.ValueText({ value: VRS.EngineType.Jet, textKey: 'Jet' }), new VRS.ValueText({ value: VRS.EngineType.Rocket, textKey: 'Rocket' }) ];}, serverFilterName: 'fEgt' }); VRS.aircraftFilterPropertyHandlers[VRS.AircraftFilterProperty.HideNoPosition] = new VRS.AircraftFilterPropertyHandler({ property: VRS.AircraftFilterProperty.HideNoPosition, type: VRS.FilterPropertyType.OnOff, labelKey: 'HideNoPosition', getValueCallback: function(aircraft) { return aircraft.hasPosition(); }, serverFilterName: 'fNoPos' }); VRS.aircraftFilterPropertyHandlers[VRS.AircraftFilterProperty.Icao] = new VRS.AircraftFilterPropertyHandler({ property: VRS.AircraftFilterProperty.Icao, type: VRS.FilterPropertyType.TextMatch, labelKey: 'Icao', isUpperCase: true, inputWidth: VRS.InputWidth.SixChar, getValueCallback: function(aircraft) { return aircraft.icao.val; }, serverFilterName: 'fIco' }); VRS.aircraftFilterPropertyHandlers[VRS.AircraftFilterProperty.IsMilitary] = new VRS.AircraftFilterPropertyHandler({ property: VRS.AircraftFilterProperty.IsMilitary, type: VRS.FilterPropertyType.OnOff, labelKey: 'IsMilitary', getValueCallback: function(aircraft) { return aircraft.isMilitary.val; }, serverFilterName: 'fMil' }); VRS.aircraftFilterPropertyHandlers[VRS.AircraftFilterProperty.ModelIcao] = new VRS.AircraftFilterPropertyHandler({ property: VRS.AircraftFilterProperty.ModelIcao, type: VRS.FilterPropertyType.TextMatch, labelKey: 'ModelIcao', isUpperCase: true, inputWidth: VRS.InputWidth.SixChar, getValueCallback: function(aircraft) { return aircraft.modelIcao.val; }, serverFilterName: 'fTyp' }); VRS.aircraftFilterPropertyHandlers[VRS.AircraftFilterProperty.Operator] = new VRS.AircraftFilterPropertyHandler({ property: VRS.AircraftFilterProperty.Operator, type: VRS.FilterPropertyType.TextMatch, labelKey: 'Operator', inputWidth: VRS.InputWidth.Long, getValueCallback: function(aircraft) { return aircraft.operator.val; }, serverFilterName: 'fOp' }); VRS.aircraftFilterPropertyHandlers[VRS.AircraftFilterProperty.OperatorCode] = new VRS.AircraftFilterPropertyHandler({ property: VRS.AircraftFilterProperty.OperatorCode, type: VRS.FilterPropertyType.TextMatch, labelKey: 'OperatorCode', inputWidth: VRS.InputWidth.ThreeChar, getValueCallback: function(aircraft) { return aircraft.operatorIcao.val; }, serverFilterName: 'fOpIcao' }); VRS.aircraftFilterPropertyHandlers[VRS.AircraftFilterProperty.Registration] = new VRS.AircraftFilterPropertyHandler({ property: VRS.AircraftFilterProperty.Registration, type: VRS.FilterPropertyType.TextMatch, labelKey: 'Registration', isUpperCase: true, inputWidth: VRS.InputWidth.SixChar, getValueCallback: function(aircraft) { return aircraft.registration.val; }, serverFilterName: 'fReg' }); VRS.aircraftFilterPropertyHandlers[VRS.AircraftFilterProperty.Species] = new VRS.AircraftFilterPropertyHandler({ property: VRS.AircraftFilterProperty.Species, type: VRS.FilterPropertyType.EnumMatch, labelKey: 'Species', getValueCallback: function(aircraft) { return aircraft.species.val; }, getEnumValues: function() { return [ new VRS.ValueText({ value: VRS.Species.None, textKey: 'None' }), new VRS.ValueText({ value: VRS.Species.LandPlane, textKey: 'LandPlane' }), new VRS.ValueText({ value: VRS.Species.SeaPlane, textKey: 'SeaPlane' }), new VRS.ValueText({ value: VRS.Species.Amphibian, textKey: 'Amphibian' }), new VRS.ValueText({ value: VRS.Species.Helicopter, textKey: 'Helicopter' }), new VRS.ValueText({ value: VRS.Species.Gyrocopter, textKey: 'Gyrocopter' }), new VRS.ValueText({ value: VRS.Species.Tiltwing, textKey: 'Tiltwing' }), new VRS.ValueText({ value: VRS.Species.GroundVehicle, textKey: 'GroundVehicle' }), new VRS.ValueText({ value: VRS.Species.Tower, textKey: 'RadioMast' }) ];}, serverFilterName: 'fSpc' }); VRS.aircraftFilterPropertyHandlers[VRS.AircraftFilterProperty.Squawk] = new VRS.AircraftFilterPropertyHandler({ property: VRS.AircraftFilterProperty.Squawk, type: VRS.FilterPropertyType.NumberRange, labelKey: 'Squawk', minimumValue: 0, maximumValue: 7777, decimalPlaces: 0, inputWidth: VRS.InputWidth.SixChar, getValueCallback: function(aircraft) { return aircraft.squawk.val ? Number(aircraft.squawk.val) : 0; }, serverFilterName: 'fSqk' }); VRS.aircraftFilterPropertyHandlers[VRS.AircraftFilterProperty.UserTag] = new VRS.AircraftFilterPropertyHandler({ property: VRS.AircraftFilterProperty.UserTag, type: VRS.FilterPropertyType.TextMatch, labelKey: 'UserTag', getValueCallback: function(aircraft) { return aircraft.userTag.val; }, serverFilterName: 'fUt' }); VRS.aircraftFilterPropertyHandlers[VRS.AircraftFilterProperty.UserInterested] = new VRS.AircraftFilterPropertyHandler({ property: VRS.AircraftFilterProperty.UserInterested, type: VRS.FilterPropertyType.OnOff, labelKey: 'Interesting', getValueCallback: function(aircraft) { return aircraft.userInterested.val; }, serverFilterName: 'fInt' }); VRS.aircraftFilterPropertyHandlers[VRS.AircraftFilterProperty.Wtc] = new VRS.AircraftFilterPropertyHandler({ property: VRS.AircraftFilterProperty.Wtc, type: VRS.FilterPropertyType.EnumMatch, labelKey: 'WakeTurbulenceCategory', getValueCallback: function(aircraft) { return aircraft.wakeTurbulenceCat.val; }, getEnumValues: function() { return [ new VRS.ValueText({ value: VRS.WakeTurbulenceCategory.None, textKey: 'None' }), new VRS.ValueText({ value: VRS.WakeTurbulenceCategory.Light, textKey: 'WtcLight' }), new VRS.ValueText({ value: VRS.WakeTurbulenceCategory.Medium, textKey: 'WtcMedium' }), new VRS.ValueText({ value: VRS.WakeTurbulenceCategory.Heavy, textKey: 'WtcHeavy' }) ];}, serverFilterName: 'fWtc' }); /** * Joins together a property identifier and a filter object to allow a condition to be tested against an aircraft's property. * @param {VRS.AircraftFilterProperty} property A VRS.AircraftFilterProperty enum value. * @param {VRS_ANY_VALUECONDITION} valueCondition The object that describes the condition and values to compare against an aircraft's property. * @constructor * @augments VRS.Filter */ export class AircraftFilter extends Filter { constructor(property: AircraftFilterPropertyEnum, valueCondition: ValueCondition) { super({ property: property, valueCondition: valueCondition, propertyEnumObject: VRS.AircraftFilterProperty, cloneCallback: function(property, filter) { return new VRS.AircraftFilter(property, filter); }, filterPropertyHandlers: VRS.aircraftFilterPropertyHandlers }); } /** * Returns true if the aircraft's value for the property matches the condition described by the parameters. */ passes(aircraft: Aircraft, options: Filter_Options) : boolean { var result = false; var handler = VRS.aircraftFilterPropertyHandlers[this.getProperty()]; if(handler) { var value = handler.getValueCallback(aircraft, options); if(value !== undefined) { var typeHandler = VRS.filterPropertyTypeHandlers[handler.type]; if(typeHandler) { result = typeHandler.valuePassesCallback(value, this.getValueCondition(), options); } } } return result; } } /** * A helper object that can deal with common routine tasks when working with aircraft property filters. */ export class AircraftFilterHelper extends FilterHelper { constructor() { super({ propertyEnumObject: VRS.AircraftFilterProperty, filterPropertyHandlers: VRS.aircraftFilterPropertyHandlers, createFilterCallback: function(propertyHandler: AircraftFilterPropertyHandler, valueCondition: ValueCondition) { return new VRS.AircraftFilter(propertyHandler.property, valueCondition); } }); } /** * Takes an aircraft and a list of filters and returns true if the aircraft passes them. */ aircraftPasses(aircraft: Aircraft, aircraftFilters: AircraftFilter[], options?: Filter_Options) : boolean { var result = true; options = options || {}; var length = aircraftFilters.length; for(var i = 0;i < length;++i) { var aircraftFilter = aircraftFilters[i]; result = aircraftFilter.passes(aircraft, options); if(!result) break; } return result; } } /* * Pre-builts */ export var aircraftFilterHelper = new VRS.AircraftFilterHelper(); }
the_stack
import { IRepresentationInfos, } from "../adaptation"; import Representation from "../representation"; const minimalRepresentationIndex = { getInitSegment() { return null; }, getSegments() { return []; }, shouldRefresh() { return false; }, getFirstPosition() : undefined { return ; }, getLastPosition() : undefined { return ; }, checkDiscontinuity() { return null; }, isSegmentStillAvailable() : undefined { return ; }, canBeOutOfSyncError() : true { return true; }, isFinished() : true { return true; }, areSegmentsChronologicallyGenerated() { return true; }, _replace() { /* noop */ }, _update() { /* noop */ }, }; const defaultRepresentationSpy = jest.fn(arg => { return { bitrate: arg.bitrate, id: arg.id, isSupported: true, index: arg.index }; }); describe("Manifest - Adaptation", () => { beforeEach(() => { jest.resetModules(); }); afterEach(() => { defaultRepresentationSpy.mockClear(); }); it("should be able to create a minimal Adaptation", () => { jest.mock("../representation", () => ({ __esModule: true as const, default: defaultRepresentationSpy })); const Adaptation = require("../adaptation").default; const args = { id: "12", representations: [], type: "video" }; const adaptation = new Adaptation(args); expect(adaptation.id).toBe("12"); expect(adaptation.representations).toEqual([]); expect(adaptation.type).toBe("video"); expect(adaptation.isAudioDescription).toBe(undefined); expect(adaptation.isClosedCaption).toBe(undefined); expect(adaptation.language).toBe(undefined); expect(adaptation.normalizedLanguage).toBe(undefined); expect(adaptation.manuallyAdded).toBe(false); expect(adaptation.getAvailableBitrates()).toEqual([]); expect(adaptation.getRepresentation("")).toBe(undefined); expect(defaultRepresentationSpy).not.toHaveBeenCalled(); }); it("should normalize a given language", () => { jest.mock("../representation", () => ({ __esModule: true as const, default: defaultRepresentationSpy })); const normalizeSpy = jest.fn((lang : string) => lang + "foo"); jest.mock("../../utils/languages", () => ({ __esModule: true as const, default: normalizeSpy })); const Adaptation = require("../adaptation").default; const args1 = { id: "12", representations: [], language: "fr", type: "video"as const }; const adaptation1 = new Adaptation(args1); expect(adaptation1.language).toBe("fr"); expect(adaptation1.normalizedLanguage).toBe("frfoo"); expect(normalizeSpy).toHaveBeenCalledTimes(1); expect(normalizeSpy).toHaveBeenCalledWith("fr"); normalizeSpy.mockClear(); const args2 = { id: "12", representations: [], language: "toto", type: "video" }; const adaptation2 = new Adaptation(args2); expect(adaptation2.language).toBe("toto"); expect(adaptation2.normalizedLanguage).toBe("totofoo"); expect(normalizeSpy).toHaveBeenCalledTimes(1); expect(normalizeSpy).toHaveBeenCalledWith("toto"); }); it("should not call normalize if no language is given", () => { jest.mock("../representation", () => ({ __esModule: true as const, default: defaultRepresentationSpy })); const normalizeSpy = jest.fn((lang : string) => lang + "foo"); jest.mock("../../utils/languages", () => ({ __esModule: true as const, default: normalizeSpy })); const Adaptation = require("../adaptation").default; const args1 = { id: "12", representations: [], type: "video" }; const adaptation1 = new Adaptation(args1); expect(adaptation1.language).toBe(undefined); expect(adaptation1.normalizedLanguage).toBe(undefined); expect(normalizeSpy).not.toHaveBeenCalled(); }); it("should create and sort the corresponding Representations", () => { jest.mock("../representation", () => ({ __esModule: true as const, default: defaultRepresentationSpy })); const Adaptation = require("../adaptation").default; const rep1 = { bitrate: 10, id: "rep1", index: minimalRepresentationIndex }; const rep2 = { bitrate: 30, id: "rep2", index: minimalRepresentationIndex }; const rep3 = { bitrate: 20, id: "rep3", index: minimalRepresentationIndex }; const representations = [rep1, rep2, rep3]; const args = { id: "12", representations, type: "text" as const }; const adaptation = new Adaptation(args); const parsedRepresentations = adaptation.representations; expect(defaultRepresentationSpy).toHaveBeenCalledTimes(3); expect(defaultRepresentationSpy).toHaveBeenNthCalledWith(1, rep1, { type: "text" }); expect(defaultRepresentationSpy).toHaveBeenNthCalledWith(2, rep2, { type: "text" }); expect(defaultRepresentationSpy).toHaveBeenNthCalledWith(3, rep3, { type: "text" }); expect(parsedRepresentations.length).toBe(3); expect(parsedRepresentations[0].id).toEqual("rep1"); expect(parsedRepresentations[1].id).toEqual("rep3"); expect(parsedRepresentations[2].id).toEqual("rep2"); expect(adaptation.getAvailableBitrates()).toEqual([10, 20, 30]); expect(adaptation.getRepresentation("rep2").bitrate).toEqual(30); }); it("should execute the representationFilter if given", () => { const representationSpy = jest.fn(arg => { return { bitrate: arg.bitrate, id: arg.id, isSupported: arg.id !== "rep4", index: arg.index }; }); jest.mock("../representation", () => ({ __esModule: true as const, default: representationSpy })); const Adaptation = require("../adaptation").default; const rep1 = { bitrate: 10, id: "rep1", index: minimalRepresentationIndex }; const rep2 = { bitrate: 20, id: "rep2", index: minimalRepresentationIndex }; const rep3 = { bitrate: 30, id: "rep3", index: minimalRepresentationIndex }; const rep4 = { bitrate: 40, id: "rep4", index: minimalRepresentationIndex }; const rep5 = { bitrate: 50, id: "rep5", index: minimalRepresentationIndex }; const rep6 = { bitrate: 60, id: "rep6", index: minimalRepresentationIndex }; const representations = [rep1, rep2, rep3, rep4, rep5, rep6]; const representationFilter = jest.fn(( representation : Representation, adaptationInfos : IRepresentationInfos ) => { if (adaptationInfos.language === "fr" && representation.bitrate < 40) { return false; } return true; }); const args = { id: "12", language: "fr", representations, type: "text" as const }; const adaptation = new Adaptation(args, { representationFilter }); const parsedRepresentations = adaptation.representations; expect(representationFilter).toHaveBeenCalledTimes(6); expect(parsedRepresentations.length).toBe(3); expect(parsedRepresentations[0].id).toEqual("rep4"); expect(parsedRepresentations[1].id).toEqual("rep5"); expect(parsedRepresentations[2].id).toEqual("rep6"); expect(adaptation.getAvailableBitrates()).toEqual([40, 50, 60]); expect(adaptation.getRepresentation("rep2")).toBe(undefined); expect(adaptation.getRepresentation("rep4").id).toEqual("rep4"); }); it("should set an isDub value if one", () => { jest.mock("../representation", () => ({ __esModule: true as const, default: defaultRepresentationSpy })); const normalizeSpy = jest.fn((lang : string) => lang + "foo"); jest.mock("../../utils/languages", () => ({ __esModule: true as const, default: normalizeSpy })); const Adaptation = require("../adaptation").default; const args1 = { id: "12", representations: [], isDub: false, type: "video" }; const adaptation1 = new Adaptation(args1); expect(adaptation1.language).toBe(undefined); expect(adaptation1.normalizedLanguage).toBe(undefined); expect(adaptation1.isDub).toEqual(false); expect(normalizeSpy).not.toHaveBeenCalled(); const args2 = { id: "12", representations: [], isDub: true, type: "video" }; const adaptation2 = new Adaptation(args2); expect(adaptation2.language).toBe(undefined); expect(adaptation2.normalizedLanguage).toBe(undefined); expect(adaptation2.isDub).toEqual(true); expect(normalizeSpy).not.toHaveBeenCalled(); }); it("should set an isClosedCaption value if one", () => { jest.mock("../representation", () => ({ __esModule: true as const, default: defaultRepresentationSpy })); const normalizeSpy = jest.fn((lang : string) => lang + "foo"); jest.mock("../../utils/languages", () => ({ __esModule: true as const, default: normalizeSpy })); const Adaptation = require("../adaptation").default; const args1 = { id: "12", representations: [], closedCaption: false, type: "video" }; const adaptation1 = new Adaptation(args1); expect(adaptation1.language).toBe(undefined); expect(adaptation1.normalizedLanguage).toBe(undefined); expect(adaptation1.isClosedCaption).toEqual(false); expect(normalizeSpy).not.toHaveBeenCalled(); const args2 = { id: "12", representations: [], closedCaption: true, type: "video" }; const adaptation2 = new Adaptation(args2); expect(adaptation2.language).toBe(undefined); expect(adaptation2.normalizedLanguage).toBe(undefined); expect(adaptation2.isClosedCaption).toEqual(true); expect(normalizeSpy).not.toHaveBeenCalled(); }); it("should set an isAudioDescription value if one", () => { jest.mock("../representation", () => ({ __esModule: true as const, default: defaultRepresentationSpy })); const normalizeSpy = jest.fn((lang : string) => lang + "foo"); jest.mock("../../utils/languages", () => ({ __esModule: true as const, default: normalizeSpy })); const Adaptation = require("../adaptation").default; const args1 = { id: "12", representations: [], audioDescription: false, type: "video" }; const adaptation1 = new Adaptation(args1); expect(adaptation1.language).toBe(undefined); expect(adaptation1.normalizedLanguage).toBe(undefined); expect(adaptation1.isAudioDescription).toEqual(false); expect(normalizeSpy).not.toHaveBeenCalled(); const args2 = { id: "12", representations: [], audioDescription: true, type: "video" }; const adaptation2 = new Adaptation(args2); expect(adaptation2.language).toBe(undefined); expect(adaptation2.normalizedLanguage).toBe(undefined); expect(adaptation2.isAudioDescription).toEqual(true); expect(normalizeSpy).not.toHaveBeenCalled(); }); it("should set a manuallyAdded value if one", () => { jest.mock("../representation", () => ({ __esModule: true as const, default: defaultRepresentationSpy })); const normalizeSpy = jest.fn((lang : string) => lang + "foo"); jest.mock("../../utils/languages", () => ({ __esModule: true as const, default: normalizeSpy })); const Adaptation = require("../adaptation").default; const args1 = { id: "12", representations: [], type: "video" }; const adaptation1 = new Adaptation(args1, { isManuallyAdded: false }); expect(adaptation1.language).toBe(undefined); expect(adaptation1.normalizedLanguage).toBe(undefined); expect(adaptation1.manuallyAdded).toEqual(false); expect(normalizeSpy).not.toHaveBeenCalled(); const args2 = { id: "12", representations: [], type: "video" }; const adaptation2 = new Adaptation(args2, { isManuallyAdded: true }); expect(adaptation2.language).toBe(undefined); expect(adaptation2.normalizedLanguage).toBe(undefined); expect(adaptation2.manuallyAdded).toEqual(true); expect(normalizeSpy).not.toHaveBeenCalled(); }); /* eslint-disable max-len */ it("should filter Representation with duplicate bitrates in getAvailableBitrates", () => { /* eslint-enable max-len */ jest.mock("../representation", () => ({ __esModule: true as const, default: defaultRepresentationSpy })); const uniqSpy = jest.fn(() => [45, 92]); jest.mock("../../utils/uniq", () => ({ __esModule: true as const, default: uniqSpy })); const Adaptation = require("../adaptation").default; const rep1 = { bitrate: 10, id: "rep1", index: minimalRepresentationIndex }; const rep2 = { bitrate: 20, id: "rep2", index: minimalRepresentationIndex }; const rep3 = { bitrate: 20, id: "rep3", index: minimalRepresentationIndex }; const representations = [rep1, rep2, rep3]; const args = { id: "12", representations, type: "text" as const }; const adaptation = new Adaptation(args); const parsedRepresentations = adaptation.representations; expect(parsedRepresentations.length).toBe(3); expect(adaptation.getAvailableBitrates()).toEqual([45, 92]); expect(uniqSpy).toHaveBeenCalledTimes(1); expect(uniqSpy).toHaveBeenCalledWith(representations.map(r => r.bitrate)); }); /* eslint-disable max-len */ it("should return the first Representation with the given Id with `getRepresentation`", () => { /* eslint-enable max-len */ jest.mock("../representation", () => ({ __esModule: true as const, default: defaultRepresentationSpy })); const Adaptation = require("../adaptation").default; const rep1 = { bitrate: 10, id: "rep1", index: minimalRepresentationIndex }; const rep2 = { bitrate: 20, id: "rep2", index: minimalRepresentationIndex }; const rep3 = { bitrate: 30, id: "rep2", index: minimalRepresentationIndex }; const representations = [rep1, rep2, rep3]; const args = { id: "12", representations, type: "text" as const }; const adaptation = new Adaptation(args); expect(adaptation.getRepresentation("rep1").bitrate).toEqual(10); expect(adaptation.getRepresentation("rep2").bitrate).toEqual(20); }); /* eslint-disable max-len */ it("should return undefined in `getRepresentation` if no representation is found with this Id", () => { /* eslint-enable max-len */ jest.mock("../representation", () => ({ __esModule: true as const, default: defaultRepresentationSpy })); const Adaptation = require("../adaptation").default; const rep1 = { bitrate: 10, id: "rep1", index: minimalRepresentationIndex }; const rep2 = { bitrate: 20, id: "rep2", index: minimalRepresentationIndex }; const rep3 = { bitrate: 30, id: "rep2", index: minimalRepresentationIndex }; const representations = [rep1, rep2, rep3]; const args = { id: "12", representations, type: "text" as const }; const adaptation = new Adaptation(args); expect(adaptation.getRepresentation("rep5")).toBe(undefined); }); /* eslint-disable max-len */ it("should return only supported and decipherable representation when calling `getPlayableRepresentations`", () => { /* eslint-enable max-len */ const representationSpy = jest.fn(arg => { return { bitrate: arg.bitrate, id: arg.id, isSupported: arg.id !== "rep3" && arg.id !== "rep8", decipherable: arg.id === "rep6" ? false : arg.id === "rep8" ? false : arg.id === "rep4" ? true : undefined, index: arg.index }; }); jest.mock("../representation", () => ({ __esModule: true as const, default: representationSpy })); const Adaptation = require("../adaptation").default; const rep1 = { bitrate: 10, id: "rep1", index: minimalRepresentationIndex }; const rep2 = { bitrate: 20, id: "rep2", index: minimalRepresentationIndex }; const rep3 = { bitrate: 30, id: "rep3", index: minimalRepresentationIndex }; const rep4 = { bitrate: 40, id: "rep4", index: minimalRepresentationIndex }; const rep5 = { bitrate: 50, id: "rep5", index: minimalRepresentationIndex }; const rep6 = { bitrate: 60, id: "rep6", index: minimalRepresentationIndex }; const rep7 = { bitrate: 70, id: "rep7", index: minimalRepresentationIndex }; const rep8 = { bitrate: 80, id: "rep8", index: minimalRepresentationIndex }; const representations = [rep1, rep2, rep3, rep4, rep5, rep6, rep7, rep8]; const args = { id: "12", representations, type: "text" as const }; const adaptation = new Adaptation(args); const playableRepresentations = adaptation.getPlayableRepresentations(); expect(playableRepresentations.length).toEqual(5); expect(playableRepresentations[0].id).toEqual("rep1"); expect(playableRepresentations[1].id).toEqual("rep2"); expect(playableRepresentations[2].id).toEqual("rep4"); expect(playableRepresentations[3].id).toEqual("rep5"); expect(playableRepresentations[4].id).toEqual("rep7"); }); });
the_stack
import Artifact from "../Artifact/Artifact"; import { maxBuildsToShowDefault, maxBuildsToShowList } from "../Build/Build"; import { initialBuildSettings } from "../Build/BuildSetting"; import { ascensionMaxLevel } from "../Data/LevelData"; import Stat from "../Stat"; import { allMainStatKeys, allSubstats, ICachedArtifact, IArtifact, ICachedSubstat, ISubstat, SubstatKey } from "../Types/artifact"; import { ICachedCharacter, ICharacter } from "../Types/character"; import { allArtifactRarities, allArtifactSets, allCharacterKeys, allElements, allHitModes, allReactionModes, allSlotKeys, allWeaponKeys } from "../Types/consts"; import { IWeapon, ICachedWeapon } from "../Types/weapon"; import { objectFromKeyMap } from "../Util/Util"; // MIGRATION STEP: Always keep validate/parse in sync with the latest format /// Returns the closest (not necessarily valid) artifact, including errors as necessary export function validateArtifact(flex: IArtifact, id: string): { artifact: ICachedArtifact, errors: Displayable[] } { const { location, exclude, lock, setKey, slotKey, rarity, mainStatKey } = flex const level = Math.round(Math.min(Math.max(0, flex.level), rarity >= 3 ? rarity * 4 : 4)) const mainStatVal = Artifact.mainStatValue(mainStatKey, rarity, level)! const errors: Displayable[] = [] const substats: ICachedSubstat[] = flex.substats.map(substat => ({ ...substat, rolls: [], efficiency: 0 })) const validated: ICachedArtifact = { id, setKey, location, slotKey, exclude, lock, mainStatKey, rarity, level, substats, mainStatVal } const allPossibleRolls: { index: number, substatRolls: number[][] }[] = [] let totalUnambiguousRolls = 0 function efficiency(rolls: number[], key: SubstatKey): number { return rolls.reduce((a, b) => a + b, 0) / Artifact.maxSubstatValues(key) * 100 / rolls.length } substats.forEach((substat, index) => { const { key, value } = substat if (!key) return substat.value = 0 const possibleRolls = Artifact.getSubstatRolls(key, value, rarity) if (possibleRolls.length) { // Valid Substat const possibleLengths = new Set(possibleRolls.map(roll => roll.length)) if (possibleLengths.size !== 1) { // Ambiguous Rolls allPossibleRolls.push({ index, substatRolls: possibleRolls }) } else { // Unambiguous Rolls totalUnambiguousRolls += possibleRolls[0].length } substat.rolls = possibleRolls.reduce((best, current) => best.length < current.length ? best : current) substat.efficiency = efficiency(substat.rolls, key) } else { // Invalid Substat substat.rolls = [] substat.efficiency = 0 errors.push(<>Invalid substat {Stat.getStatNameWithPercent(substat.key)}</>) } }) if (errors.length) return { artifact: validated, errors } const { low, high } = Artifact.rollInfo(rarity), lowerBound = low + Math.floor(level / 4), upperBound = high + Math.floor(level / 4) let highestScore = -Infinity // -Max(substats.rolls[i].length) over ambiguous rolls const tryAllSubstats = (rolls: { index: number, roll: number[] }[], currentScore: number, total: number) => { if (rolls.length === allPossibleRolls.length) { if (total <= upperBound && total >= lowerBound && highestScore < currentScore) { highestScore = currentScore for (const { index, roll } of rolls) { const key = substats[index].key as SubstatKey substats[index].rolls = roll substats[index].efficiency = efficiency(roll, key) } } return } const { index, substatRolls } = allPossibleRolls[rolls.length] for (const roll of substatRolls) { rolls.push({ index, roll }) let newScore = Math.min(currentScore, -roll.length) if (newScore >= highestScore) // Scores won't get better, so we can skip. tryAllSubstats(rolls, newScore, total + roll.length) rolls.pop() } } tryAllSubstats([], Infinity, totalUnambiguousRolls) const totalRolls = substats.reduce((accu, { rolls }) => accu + rolls.length, 0) if (totalRolls > upperBound) errors.push(`${rarity}-star artifact (level ${level}) should have no more than ${upperBound} rolls. It currently has ${totalRolls} rolls.`) else if (totalRolls < lowerBound) errors.push(`${rarity}-star artifact (level ${level}) should have at least ${lowerBound} rolls. It currently has ${totalRolls} rolls.`) if (substats.some((substat) => !substat.key)) { let substat = substats.find(substat => (substat.rolls?.length ?? 0) > 1) if (substat) errors.push(<>Substat {Stat.getStatNameWithPercent(substat.key)} has {'>'} 1 roll, but not all substats are unlocked.</>) } return { artifact: validated, errors } } /// Returns the closest flex artifact, or undefined if it's not recoverable export function parseArtifact(obj: any): IArtifact | undefined { if (typeof obj !== "object") return let { setKey, rarity, level, slotKey, mainStatKey, substats, location, exclude, lock, } = obj ?? {} if (!allArtifactSets.includes(setKey) || !allSlotKeys.includes(slotKey) || !allMainStatKeys.includes(mainStatKey) || !allArtifactRarities.includes(rarity) || typeof level !== "number" || level < 0 || level > 20) return // non-recoverable substats = parseSubstats(substats) lock = !!lock exclude = !!exclude level = Math.round(level) if (!allCharacterKeys.includes(location)) location = "" return { setKey, rarity, level, slotKey, mainStatKey, substats, location, exclude, lock } } /// Return a new flex artifact from given artifact. All extra keys are removed export function removeArtifactCache(artifact: ICachedArtifact): IArtifact { const { setKey, rarity, level, slotKey, mainStatKey, substats, location, exclude, lock } = artifact return { setKey, rarity, level, slotKey, mainStatKey, substats: substats.map(substat => ({ key: substat.key, value: substat.value })), location, exclude, lock } } function parseSubstats(obj: any): ISubstat[] { if (!Array.isArray(obj)) return new Array(4).map(_ => ({ key: "", value: 0 })) const substats = obj.slice(0, 4).map(({ key = undefined, value = undefined }) => { if (!allSubstats.includes(key) || typeof value !== "number" || !isFinite(value)) return { key: "", value: 0 } value = key.endsWith("_") ? parseFloat(value.toFixed(1)) : parseInt(value.toFixed()) return { key, value } }) while (substats.length < 4) substats.push({ key: "", value: 0 }) return substats } /// Returns the closest character export function validateCharacter(flex: ICharacter): ICachedCharacter { // TODO: Add more validations to make sure the returned value is a "valid" character return { equippedArtifacts: objectFromKeyMap(allSlotKeys, () => ""), equippedWeapon: "", ...flex, } } /// Returns the closest flex character, or undefined if it's not recoverable export function parseCharacter(obj: any): ICharacter | undefined { if (typeof obj !== "object") return let { key: characterKey, level, ascension, hitMode, elementKey, reactionMode, conditionalValues, bonusStats, talent, infusionAura, constellation, buildSettings, } = obj if (!allCharacterKeys.includes(characterKey) || typeof level !== "number" || level < 0 || level > 90) return // non-recoverable if (!allHitModes.includes(hitMode)) hitMode = "avgHit" if (characterKey !== "Traveler") elementKey = undefined else if (!allElements.includes(elementKey)) elementKey = "anemo" if (!allReactionModes.includes(reactionMode)) reactionMode = "" if (!allElements.includes(infusionAura)) infusionAura = "" if (typeof constellation !== "number" && constellation < 0 && constellation > 6) constellation = 0 if (typeof ascension !== "number" || !(ascension in ascensionMaxLevel) || level > ascensionMaxLevel[ascension] || level < (ascensionMaxLevel[ascension - 1] ?? 0)) ascension = ascensionMaxLevel.findIndex(maxLvl => level <= maxLvl) if (typeof talent !== "object") talent = { auto: 1, skill: 1, burst: 1 } else { let { auto, skill, burst } = talent if (typeof auto !== "number" || auto < 1 || auto > 15) auto = 1 if (typeof skill !== "number" || skill < 1 || skill > 15) skill = 1 if (typeof burst !== "number" || burst < 1 || burst > 15) burst = 1 talent = { auto, skill, burst } } if (buildSettings && typeof buildSettings === "object") {//buildSettings let { setFilters, statFilters, mainStatKeys, optimizationTarget, mainStatAssumptionLevel, useExcludedArts, useEquippedArts, builds, buildDate, maxBuildsToShow } = buildSettings ?? {} if (!Array.isArray(setFilters)) setFilters = initialBuildSettings().setFilters //make sure set effects are all numbers setFilters = setFilters.map(({ key, num }) => { if (Number.isInteger(num)) return { key, num } return { key: "", num: 0 } }) //move all the empty entries to the back setFilters = [...setFilters.filter(s => s.key), ...setFilters.filter(s => !s.key)] if (typeof statFilters !== "object") statFilters = {} if (!mainStatKeys || !mainStatKeys.sands || !mainStatKeys.goblet || !mainStatKeys.circlet) { const tempmainStatKeys = initialBuildSettings().mainStatKeys if (Array.isArray(mainStatKeys)) { const [sands, goblet, circlet] = mainStatKeys if (sands) tempmainStatKeys.sands = [sands] if (goblet) tempmainStatKeys.goblet = [goblet] if (circlet) tempmainStatKeys.circlet = [circlet] } mainStatKeys = tempmainStatKeys } if (!optimizationTarget) optimizationTarget = "finalAtk" if (typeof mainStatAssumptionLevel !== "number" || mainStatAssumptionLevel < 0 || mainStatAssumptionLevel > 20) mainStatAssumptionLevel = 0 useExcludedArts = !!useExcludedArts useEquippedArts = !!useEquippedArts if (!Array.isArray(builds) || !builds.every(b => Array.isArray(b) && b.every(s => typeof s === "string"))) { builds = [] buildDate = 0 } if (!Number.isInteger(buildDate)) buildDate = 0 if (!maxBuildsToShowList.includes(maxBuildsToShow)) maxBuildsToShow = maxBuildsToShowDefault buildSettings = { setFilters, statFilters, mainStatKeys, optimizationTarget, mainStatAssumptionLevel, useExcludedArts, useEquippedArts, builds, buildDate, maxBuildsToShow } } // TODO: validate bonusStats, conditionalValues const result: ICharacter = { key: characterKey, level, ascension, hitMode, reactionMode, conditionalValues, bonusStats, talent, infusionAura, constellation, } if (buildSettings) result.buildSettings = buildSettings if (elementKey) result.elementKey = elementKey return result } /// Return a new flex character from given character. All extra keys are removed export function removeCharacterCache(char: ICachedCharacter): ICharacter { const { key: characterKey, level, ascension, hitMode, elementKey, reactionMode, conditionalValues, bonusStats, talent, infusionAura, constellation, buildSettings, } = char const result: ICharacter = { key: characterKey, level, ascension, hitMode, reactionMode, conditionalValues, bonusStats, talent, infusionAura, constellation, buildSettings, } if (elementKey) result.elementKey = elementKey return result } export function validateWeapon(flex: IWeapon, id: string): ICachedWeapon { //TODO: weapon validation return { ...flex, id } } export function parseWeapon(obj: any): IWeapon | undefined { if (typeof obj !== "object") return let { key, level, ascension, refinement, location, lock } = obj if (!allWeaponKeys.includes(key)) return if (typeof level !== "number" || level < 1 || level > 90) level = 1 if (typeof ascension !== "number" || ascension < 0 || ascension > 6) ascension = 0 // TODO: Check if level-ascension matches if (typeof refinement !== "number" || refinement < 1 || refinement > 5) refinement = 1 if (!allCharacterKeys.includes(location)) location = "" return { key, level, ascension, refinement, location, lock } } /// Return a new flex character from given character. All extra keys are removed export function removeWeaponCache(weapon: ICachedWeapon): IWeapon { const { key, level, ascension, refinement, location, lock } = weapon return { key, level, ascension, refinement, location, lock } }
the_stack
import { CursorConfiguration, ICursorSimpleModel, SingleCursorState } from 'vs/editor/common/cursorCommon'; import { CursorColumns } from 'vs/editor/common/core/cursorColumns'; import { Position } from 'vs/editor/common/core/position'; import { Range } from 'vs/editor/common/core/range'; import * as strings from 'vs/base/common/strings'; import { Constants } from 'vs/base/common/uint'; import { AtomicTabMoveOperations, Direction } from 'vs/editor/common/cursor/cursorAtomicMoveOperations'; import { PositionAffinity } from 'vs/editor/common/model'; export class CursorPosition { _cursorPositionBrand: void = undefined; public readonly lineNumber: number; public readonly column: number; public readonly leftoverVisibleColumns: number; constructor(lineNumber: number, column: number, leftoverVisibleColumns: number) { this.lineNumber = lineNumber; this.column = column; this.leftoverVisibleColumns = leftoverVisibleColumns; } } export class MoveOperations { public static leftPosition(model: ICursorSimpleModel, position: Position): Position { if (position.column > model.getLineMinColumn(position.lineNumber)) { return position.delta(undefined, -strings.prevCharLength(model.getLineContent(position.lineNumber), position.column - 1)); } else if (position.lineNumber > 1) { const newLineNumber = position.lineNumber - 1; return new Position(newLineNumber, model.getLineMaxColumn(newLineNumber)); } else { return position; } } private static leftPositionAtomicSoftTabs(model: ICursorSimpleModel, position: Position, tabSize: number): Position { if (position.column <= model.getLineIndentColumn(position.lineNumber)) { const minColumn = model.getLineMinColumn(position.lineNumber); const lineContent = model.getLineContent(position.lineNumber); const newPosition = AtomicTabMoveOperations.atomicPosition(lineContent, position.column - 1, tabSize, Direction.Left); if (newPosition !== -1 && newPosition + 1 >= minColumn) { return new Position(position.lineNumber, newPosition + 1); } } return this.leftPosition(model, position); } private static left(config: CursorConfiguration, model: ICursorSimpleModel, position: Position): CursorPosition { const pos = config.stickyTabStops ? MoveOperations.leftPositionAtomicSoftTabs(model, position, config.tabSize) : MoveOperations.leftPosition(model, position); return new CursorPosition(pos.lineNumber, pos.column, 0); } /** * @param noOfColumns Must be either `1` * or `Math.round(viewModel.getLineContent(viewLineNumber).length / 2)` (for half lines). */ public static moveLeft(config: CursorConfiguration, model: ICursorSimpleModel, cursor: SingleCursorState, inSelectionMode: boolean, noOfColumns: number): SingleCursorState { let lineNumber: number, column: number; if (cursor.hasSelection() && !inSelectionMode) { // If the user has a selection and does not want to extend it, // put the cursor at the beginning of the selection. lineNumber = cursor.selection.startLineNumber; column = cursor.selection.startColumn; } else { // This has no effect if noOfColumns === 1. // It is ok to do so in the half-line scenario. const pos = cursor.position.delta(undefined, -(noOfColumns - 1)); // We clip the position before normalization, as normalization is not defined // for possibly negative columns. const normalizedPos = model.normalizePosition(MoveOperations.clipPositionColumn(pos, model), PositionAffinity.Left); const p = MoveOperations.left(config, model, normalizedPos); lineNumber = p.lineNumber; column = p.column; } return cursor.move(inSelectionMode, lineNumber, column, 0); } /** * Adjusts the column so that it is within min/max of the line. */ private static clipPositionColumn(position: Position, model: ICursorSimpleModel): Position { return new Position( position.lineNumber, MoveOperations.clipRange(position.column, model.getLineMinColumn(position.lineNumber), model.getLineMaxColumn(position.lineNumber)) ); } private static clipRange(value: number, min: number, max: number): number { if (value < min) { return min; } if (value > max) { return max; } return value; } public static rightPosition(model: ICursorSimpleModel, lineNumber: number, column: number): Position { if (column < model.getLineMaxColumn(lineNumber)) { column = column + strings.nextCharLength(model.getLineContent(lineNumber), column - 1); } else if (lineNumber < model.getLineCount()) { lineNumber = lineNumber + 1; column = model.getLineMinColumn(lineNumber); } return new Position(lineNumber, column); } public static rightPositionAtomicSoftTabs(model: ICursorSimpleModel, lineNumber: number, column: number, tabSize: number, indentSize: number): Position { if (column < model.getLineIndentColumn(lineNumber)) { const lineContent = model.getLineContent(lineNumber); const newPosition = AtomicTabMoveOperations.atomicPosition(lineContent, column - 1, tabSize, Direction.Right); if (newPosition !== -1) { return new Position(lineNumber, newPosition + 1); } } return this.rightPosition(model, lineNumber, column); } public static right(config: CursorConfiguration, model: ICursorSimpleModel, position: Position): CursorPosition { const pos = config.stickyTabStops ? MoveOperations.rightPositionAtomicSoftTabs(model, position.lineNumber, position.column, config.tabSize, config.indentSize) : MoveOperations.rightPosition(model, position.lineNumber, position.column); return new CursorPosition(pos.lineNumber, pos.column, 0); } public static moveRight(config: CursorConfiguration, model: ICursorSimpleModel, cursor: SingleCursorState, inSelectionMode: boolean, noOfColumns: number): SingleCursorState { let lineNumber: number, column: number; if (cursor.hasSelection() && !inSelectionMode) { // If we are in selection mode, move right without selection cancels selection and puts cursor at the end of the selection lineNumber = cursor.selection.endLineNumber; column = cursor.selection.endColumn; } else { const pos = cursor.position.delta(undefined, noOfColumns - 1); const normalizedPos = model.normalizePosition(MoveOperations.clipPositionColumn(pos, model), PositionAffinity.Right); const r = MoveOperations.right(config, model, normalizedPos); lineNumber = r.lineNumber; column = r.column; } return cursor.move(inSelectionMode, lineNumber, column, 0); } public static vertical(config: CursorConfiguration, model: ICursorSimpleModel, lineNumber: number, column: number, leftoverVisibleColumns: number, newLineNumber: number, allowMoveOnEdgeLine: boolean, normalizationAffinity?: PositionAffinity): CursorPosition { const currentVisibleColumn = CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize) + leftoverVisibleColumns; const lineCount = model.getLineCount(); const wasOnFirstPosition = (lineNumber === 1 && column === 1); const wasOnLastPosition = (lineNumber === lineCount && column === model.getLineMaxColumn(lineNumber)); const wasAtEdgePosition = (newLineNumber < lineNumber ? wasOnFirstPosition : wasOnLastPosition); lineNumber = newLineNumber; if (lineNumber < 1) { lineNumber = 1; if (allowMoveOnEdgeLine) { column = model.getLineMinColumn(lineNumber); } else { column = Math.min(model.getLineMaxColumn(lineNumber), column); } } else if (lineNumber > lineCount) { lineNumber = lineCount; if (allowMoveOnEdgeLine) { column = model.getLineMaxColumn(lineNumber); } else { column = Math.min(model.getLineMaxColumn(lineNumber), column); } } else { column = config.columnFromVisibleColumn(model, lineNumber, currentVisibleColumn); } if (wasAtEdgePosition) { leftoverVisibleColumns = 0; } else { leftoverVisibleColumns = currentVisibleColumn - CursorColumns.visibleColumnFromColumn(model.getLineContent(lineNumber), column, config.tabSize); } if (normalizationAffinity !== undefined) { const position = new Position(lineNumber, column); const newPosition = model.normalizePosition(position, normalizationAffinity); leftoverVisibleColumns = leftoverVisibleColumns + (column - newPosition.column); lineNumber = newPosition.lineNumber; column = newPosition.column; } return new CursorPosition(lineNumber, column, leftoverVisibleColumns); } public static down(config: CursorConfiguration, model: ICursorSimpleModel, lineNumber: number, column: number, leftoverVisibleColumns: number, count: number, allowMoveOnLastLine: boolean): CursorPosition { return this.vertical(config, model, lineNumber, column, leftoverVisibleColumns, lineNumber + count, allowMoveOnLastLine, PositionAffinity.RightOfInjectedText); } public static moveDown(config: CursorConfiguration, model: ICursorSimpleModel, cursor: SingleCursorState, inSelectionMode: boolean, linesCount: number): SingleCursorState { let lineNumber: number, column: number; if (cursor.hasSelection() && !inSelectionMode) { // If we are in selection mode, move down acts relative to the end of selection lineNumber = cursor.selection.endLineNumber; column = cursor.selection.endColumn; } else { lineNumber = cursor.position.lineNumber; column = cursor.position.column; } const r = MoveOperations.down(config, model, lineNumber, column, cursor.leftoverVisibleColumns, linesCount, true); return cursor.move(inSelectionMode, r.lineNumber, r.column, r.leftoverVisibleColumns); } public static translateDown(config: CursorConfiguration, model: ICursorSimpleModel, cursor: SingleCursorState): SingleCursorState { const selection = cursor.selection; const selectionStart = MoveOperations.down(config, model, selection.selectionStartLineNumber, selection.selectionStartColumn, cursor.selectionStartLeftoverVisibleColumns, 1, false); const position = MoveOperations.down(config, model, selection.positionLineNumber, selection.positionColumn, cursor.leftoverVisibleColumns, 1, false); return new SingleCursorState( new Range(selectionStart.lineNumber, selectionStart.column, selectionStart.lineNumber, selectionStart.column), selectionStart.leftoverVisibleColumns, new Position(position.lineNumber, position.column), position.leftoverVisibleColumns ); } public static up(config: CursorConfiguration, model: ICursorSimpleModel, lineNumber: number, column: number, leftoverVisibleColumns: number, count: number, allowMoveOnFirstLine: boolean): CursorPosition { return this.vertical(config, model, lineNumber, column, leftoverVisibleColumns, lineNumber - count, allowMoveOnFirstLine, PositionAffinity.LeftOfInjectedText); } public static moveUp(config: CursorConfiguration, model: ICursorSimpleModel, cursor: SingleCursorState, inSelectionMode: boolean, linesCount: number): SingleCursorState { let lineNumber: number, column: number; if (cursor.hasSelection() && !inSelectionMode) { // If we are in selection mode, move up acts relative to the beginning of selection lineNumber = cursor.selection.startLineNumber; column = cursor.selection.startColumn; } else { lineNumber = cursor.position.lineNumber; column = cursor.position.column; } const r = MoveOperations.up(config, model, lineNumber, column, cursor.leftoverVisibleColumns, linesCount, true); return cursor.move(inSelectionMode, r.lineNumber, r.column, r.leftoverVisibleColumns); } public static translateUp(config: CursorConfiguration, model: ICursorSimpleModel, cursor: SingleCursorState): SingleCursorState { const selection = cursor.selection; const selectionStart = MoveOperations.up(config, model, selection.selectionStartLineNumber, selection.selectionStartColumn, cursor.selectionStartLeftoverVisibleColumns, 1, false); const position = MoveOperations.up(config, model, selection.positionLineNumber, selection.positionColumn, cursor.leftoverVisibleColumns, 1, false); return new SingleCursorState( new Range(selectionStart.lineNumber, selectionStart.column, selectionStart.lineNumber, selectionStart.column), selectionStart.leftoverVisibleColumns, new Position(position.lineNumber, position.column), position.leftoverVisibleColumns ); } private static _isBlankLine(model: ICursorSimpleModel, lineNumber: number): boolean { if (model.getLineFirstNonWhitespaceColumn(lineNumber) === 0) { // empty or contains only whitespace return true; } return false; } public static moveToPrevBlankLine(config: CursorConfiguration, model: ICursorSimpleModel, cursor: SingleCursorState, inSelectionMode: boolean): SingleCursorState { let lineNumber = cursor.position.lineNumber; // If our current line is blank, move to the previous non-blank line while (lineNumber > 1 && this._isBlankLine(model, lineNumber)) { lineNumber--; } // Find the previous blank line while (lineNumber > 1 && !this._isBlankLine(model, lineNumber)) { lineNumber--; } return cursor.move(inSelectionMode, lineNumber, model.getLineMinColumn(lineNumber), 0); } public static moveToNextBlankLine(config: CursorConfiguration, model: ICursorSimpleModel, cursor: SingleCursorState, inSelectionMode: boolean): SingleCursorState { const lineCount = model.getLineCount(); let lineNumber = cursor.position.lineNumber; // If our current line is blank, move to the next non-blank line while (lineNumber < lineCount && this._isBlankLine(model, lineNumber)) { lineNumber++; } // Find the next blank line while (lineNumber < lineCount && !this._isBlankLine(model, lineNumber)) { lineNumber++; } return cursor.move(inSelectionMode, lineNumber, model.getLineMinColumn(lineNumber), 0); } public static moveToBeginningOfLine(config: CursorConfiguration, model: ICursorSimpleModel, cursor: SingleCursorState, inSelectionMode: boolean): SingleCursorState { const lineNumber = cursor.position.lineNumber; const minColumn = model.getLineMinColumn(lineNumber); const firstNonBlankColumn = model.getLineFirstNonWhitespaceColumn(lineNumber) || minColumn; let column: number; const relevantColumnNumber = cursor.position.column; if (relevantColumnNumber === firstNonBlankColumn) { column = minColumn; } else { column = firstNonBlankColumn; } return cursor.move(inSelectionMode, lineNumber, column, 0); } public static moveToEndOfLine(config: CursorConfiguration, model: ICursorSimpleModel, cursor: SingleCursorState, inSelectionMode: boolean, sticky: boolean): SingleCursorState { const lineNumber = cursor.position.lineNumber; const maxColumn = model.getLineMaxColumn(lineNumber); return cursor.move(inSelectionMode, lineNumber, maxColumn, sticky ? Constants.MAX_SAFE_SMALL_INTEGER - maxColumn : 0); } public static moveToBeginningOfBuffer(config: CursorConfiguration, model: ICursorSimpleModel, cursor: SingleCursorState, inSelectionMode: boolean): SingleCursorState { return cursor.move(inSelectionMode, 1, 1, 0); } public static moveToEndOfBuffer(config: CursorConfiguration, model: ICursorSimpleModel, cursor: SingleCursorState, inSelectionMode: boolean): SingleCursorState { const lastLineNumber = model.getLineCount(); const lastColumn = model.getLineMaxColumn(lastLineNumber); return cursor.move(inSelectionMode, lastLineNumber, lastColumn, 0); } }
the_stack
import { expect } from "chai"; import { assert } from "@itwin/core-bentley"; import { IModelConnection, SnapshotConnection } from "@itwin/core-frontend"; import { ChildNodeSpecificationTypes, NodeKey, RelationshipDirection, Ruleset, RuleTypes, StandardNodeTypes } from "@itwin/presentation-common"; import { Presentation } from "@itwin/presentation-frontend"; import { initialize, terminate } from "../../../IntegrationTests"; import { printRuleset } from "../../Utils"; describe("Learning Snippets", () => { let imodel: IModelConnection; beforeEach(async () => { await initialize(); imodel = await SnapshotConnection.openFile("assets/datasets/Properties_60InstancesWithUrl2.ibim"); }); afterEach(async () => { await imodel.close(); await terminate(); }); describe("Hierarchy Specifications", () => { it("uses `hideNodesInHierarchy` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.Hierarchies.Specification.HideNodesInHierarchy.Ruleset // The ruleset contains a root node specification for `bis.PhysicalModel` nodes which are grouped by class and hidden. This // means class grouping nodes are displayed, but instance nodes are hidden and instead their children are displayed. The // children are determined by another rule. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.RootNodes, specifications: [{ specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses, classes: { schemaName: "BisCore", classNames: ["PhysicalModel"], arePolymorphic: true }, hideNodesInHierarchy: true, }], }, { ruleType: RuleTypes.ChildNodes, specifications: [{ specType: ChildNodeSpecificationTypes.CustomNode, type: "child", label: "Child", }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // Verify PhysicalModel's class grouping node is displayed, but the instance node - not const classGroupingNodes = await Presentation.presentation.getNodes({ imodel, rulesetOrId: ruleset }); expect(classGroupingNodes).to.have.lengthOf(1).and.to.containSubset([{ label: { displayValue: "Physical Model" }, }]); const customNodes = await Presentation.presentation.getNodes({ imodel, rulesetOrId: ruleset, parentKey: classGroupingNodes[0].key }); expect(customNodes).to.have.lengthOf(1).and.to.containSubset([{ label: { displayValue: "Child" }, }]); }); it("uses `hideIfNoChildren` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.Hierarchies.Specification.HideIfNoChildren.Ruleset // The ruleset contains root node specifications for two custom nodes which are only // displayed if they have children. One of them has children and the other - not, so // only one of them is displayed const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.RootNodes, specifications: [{ specType: ChildNodeSpecificationTypes.CustomNode, type: "2d", label: "2d Elements", hideIfNoChildren: true, }, { specType: ChildNodeSpecificationTypes.CustomNode, type: "3d", label: "3d Elements", hideIfNoChildren: true, }], }, { ruleType: RuleTypes.ChildNodes, condition: `ParentNode.Type = "2d"`, specifications: [{ specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses, classes: { schemaName: "BisCore", classNames: ["GeometricElement2d"], arePolymorphic: true }, }], }, { ruleType: RuleTypes.ChildNodes, condition: `ParentNode.Type = "3d"`, specifications: [{ specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses, classes: { schemaName: "BisCore", classNames: ["GeometricElement3d"], arePolymorphic: true }, }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // Verify that only 3d elements' custom node is loaded const rootNodes = await Presentation.presentation.getNodes({ imodel, rulesetOrId: ruleset }); expect(rootNodes).to.have.lengthOf(1).and.to.containSubset([{ key: { type: "3d" }, label: { displayValue: "3d Elements" }, hasChildren: true, }]); const element3dNodes = await Presentation.presentation.getNodes({ imodel, rulesetOrId: ruleset, parentKey: rootNodes[0].key }); expect(element3dNodes).to.not.be.empty; }); it("uses `hideExpression` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.Hierarchies.Specification.HideExpression.Ruleset // The ruleset contains root node specifications for two custom nodes which are only // displayed if they have children. One of them has children and the other - not, so // only one of them is displayed const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.RootNodes, specifications: [{ specType: ChildNodeSpecificationTypes.CustomNode, type: "2d", label: "2d Elements", hideExpression: `ThisNode.HasChildren = FALSE`, }, { specType: ChildNodeSpecificationTypes.CustomNode, type: "3d", label: "3d Elements", hideExpression: `ThisNode.HasChildren = FALSE`, }], }, { ruleType: RuleTypes.ChildNodes, condition: `ParentNode.Type = "2d"`, specifications: [{ specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses, classes: { schemaName: "BisCore", classNames: ["GeometricElement2d"], arePolymorphic: true }, }], }, { ruleType: RuleTypes.ChildNodes, condition: `ParentNode.Type = "3d"`, specifications: [{ specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses, classes: { schemaName: "BisCore", classNames: ["GeometricElement3d"], arePolymorphic: true }, }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // Verify that only 3d elements' custom node is loaded const rootNodes = await Presentation.presentation.getNodes({ imodel, rulesetOrId: ruleset }); expect(rootNodes).to.have.lengthOf(1).and.to.containSubset([{ key: { type: "3d" }, label: { displayValue: "3d Elements" }, hasChildren: true, }]); const element3dNodes = await Presentation.presentation.getNodes({ imodel, rulesetOrId: ruleset, parentKey: rootNodes[0].key }); expect(element3dNodes).to.not.be.empty; }); it("uses `suppressSimilarAncestorsCheck` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.Hierarchies.Specification.SuppressSimilarAncestorsCheck.Ruleset // The ruleset contains a root node specification that returns the root `bis.Subject` node. Also, there are two // child node rules: // - For any `bis.Model` node, return its contained `bis.Element` nodes. // - For any `bis.Element` node, return its children `bis.Model` nodes. // Children of the root `bis.Subject` are all in the single `bis.RepositoryModel` and some of their children are in the same // `bis.RepositoryModel` as their parent. This means the `bis.RepositoryModel` node has to be repeated in the hierarchy, but // that wouldn't happen due to duplicate nodes prevention, unless the `suppressSimilarAncestorsCheck` flag is set. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.RootNodes, specifications: [{ specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses, classes: { schemaName: "BisCore", classNames: ["Subject"] }, instanceFilter: `this.ECInstanceId = 1`, groupByClass: false, groupByLabel: false, }], }, { ruleType: RuleTypes.ChildNodes, condition: `ParentNode.IsOfClass("Model", "BisCore")`, specifications: [{ specType: ChildNodeSpecificationTypes.RelatedInstanceNodes, relationshipPaths: [{ relationship: { schemaName: "BisCore", className: "ModelContainsElements" }, direction: RelationshipDirection.Forward, }], groupByClass: false, groupByLabel: false, }], }, { ruleType: RuleTypes.ChildNodes, condition: `ParentNode.IsOfClass("Element", "BisCore")`, specifications: [{ specType: ChildNodeSpecificationTypes.RelatedInstanceNodes, relationshipPaths: [[{ relationship: { schemaName: "BisCore", className: "ElementOwnsChildElements" }, direction: RelationshipDirection.Forward, }, { relationship: { schemaName: "BisCore", className: "ModelContainsElements" }, direction: RelationshipDirection.Backward, }]], suppressSimilarAncestorsCheck: true, groupByClass: false, groupByLabel: false, }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // Verify that RepositoryModel is repeated in the hierarchy const rootSubjectNodes = await Presentation.presentation.getNodes({ imodel, rulesetOrId: ruleset }); expect(rootSubjectNodes).to.have.lengthOf(1).and.to.containSubset([{ key: { type: StandardNodeTypes.ECInstancesNode, instanceKeys: [{ className: "BisCore:Subject", id: "0x1" }] }, label: { displayValue: "DgnV8Bridge" }, }]); const rootSubjectChildNodes = await Presentation.presentation.getNodes({ imodel, rulesetOrId: ruleset, parentKey: rootSubjectNodes[0].key }); expect(rootSubjectChildNodes).to.have.lengthOf(1).and.to.containSubset([{ key: { type: StandardNodeTypes.ECInstancesNode, instanceKeys: [{ className: "BisCore:RepositoryModel", id: "0x1" }] }, }]); const repositoryModelChildNodes = await Presentation.presentation.getNodes({ imodel, rulesetOrId: ruleset, parentKey: rootSubjectChildNodes[0].key }); expect(repositoryModelChildNodes).to.have.lengthOf(11).and.to.containSubset([{ label: { displayValue: "DgnV8Bridge" }, }, { label: { displayValue: "BisCore.RealityDataSources" }, }, { label: { displayValue: "BisCore.DictionaryModel" }, }, { label: { displayValue: "Properties_60InstancesWithUrl2.dgn" }, }, { label: { displayValue: "DgnV8Bridge:D:\\Temp\\Properties_60InstancesWithUrl2.dgn, Default" }, }, { label: { displayValue: "Converted Groups" }, }, { label: { displayValue: "Converted Drawings" }, }, { label: { displayValue: "Converted Sheets" }, }, { label: { displayValue: "Definition Model For DgnV8Bridge:D:\\Temp\\Properties_60InstancesWithUrl2.dgn, Default" }, }, { label: { displayValue: "Properties_60InstancesWithUrl2" }, }, { label: { displayValue: "Properties_60InstancesWithUrl2" }, }]); const repositoryModelNodes2 = await Presentation.presentation.getNodes({ imodel, rulesetOrId: ruleset, parentKey: repositoryModelChildNodes.find((n) => n.label.displayValue === "DgnV8Bridge")!.key }); expect(repositoryModelNodes2).to.have.lengthOf(1).and.to.containSubset([{ key: { type: StandardNodeTypes.ECInstancesNode, instanceKeys: [{ className: "BisCore:RepositoryModel", id: "0x1" }] }, }]); }); it("uses `priority` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.Hierarchies.Specification.Priority.Ruleset // This ruleset produces a list of `bis.PhysicalModel` and `bis.SpatialCategory` instances and groups them by // class. "Spatial Category" group will appear first because it has been given a higher priority value. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.RootNodes, specifications: [{ specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses, priority: 1, classes: { schemaName: "BisCore", classNames: ["PhysicalModel"], arePolymorphic: true }, }, { specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses, priority: 2, classes: { schemaName: "BisCore", classNames: ["SpatialCategory"], arePolymorphic: true }, }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // Verify that SpatialCategory comes before PhysicalModel const nodes = await Presentation.presentation.getNodes({ imodel, rulesetOrId: ruleset }); expect(nodes).to.have.lengthOf(2); expect(nodes[0]).to.containSubset({ label: { displayValue: "Spatial Category" }, }); expect(nodes[1]).to.containSubset({ label: { displayValue: "Physical Model" }, }); }); it("uses `doNotSort` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.Hierarchies.Specification.DoNotSort.Ruleset // The ruleset has a specification that returns unsorted `bis.Model` nodes - the order is undefined. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.RootNodes, specifications: [{ specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses, classes: [{ schemaName: "BisCore", classNames: ["Model"], arePolymorphic: true }], doNotSort: true, }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // Verify that nodes were returned unsorted const nodes = await Presentation.presentation.getNodes({ imodel, rulesetOrId: ruleset }); const sorted = [...nodes].sort((lhs, rhs) => lhs.label.displayValue.localeCompare(rhs.label.displayValue)); expect(nodes).to.not.deep.eq(sorted); }); it("uses `groupByClass` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.Hierarchies.Specification.GroupByClass.Ruleset // The ruleset contains a specification that returns `bis.Model` nodes without grouping them // by class. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.RootNodes, specifications: [{ specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses, classes: [{ schemaName: "BisCore", classNames: ["Model"], arePolymorphic: true }], groupByClass: false, }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // Verify that Models were not grouped by class const nodes = await Presentation.presentation.getNodes({ imodel, rulesetOrId: ruleset }); expect(nodes).to.not.be.empty; nodes.forEach((node) => expect(NodeKey.isClassGroupingNodeKey(node.key)).to.be.false); }); it("uses `groupByLabel` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.Hierarchies.Specification.GroupByLabel.Ruleset // The ruleset contains a specification that returns `meta.ECPropertyDef` nodes without grouping them // by label. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.RootNodes, specifications: [{ specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses, classes: [{ schemaName: "ECDbMeta", classNames: ["ECPropertyDef"] }], groupByLabel: false, }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // Verify that instances were not grouped by label const classGroupingNodes = await Presentation.presentation.getNodes({ imodel, rulesetOrId: ruleset }); const classGroupingNode = classGroupingNodes.find((node) => { assert(NodeKey.isClassGroupingNodeKey(node.key)); return node.key.className === "ECDbMeta:ECPropertyDef"; })!; const nodes = await Presentation.presentation.getNodes({ imodel, rulesetOrId: ruleset, parentKey: classGroupingNode.key }); expect(nodes).to.not.be.empty; nodes.forEach((node) => expect(NodeKey.isLabelGroupingNodeKey(node.key)).to.be.false); }); it("uses `hasChildren` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.Hierarchies.Specification.HasChildren.Ruleset // This ruleset produces a hierarchy of a single root node that hosts a list of `Model` instances. Assuming all // iModels contain at least one model, the result of this ruleset can be computed quicker by setting // `hasChildren` attribute to `"Always"`. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.RootNodes, specifications: [{ specType: ChildNodeSpecificationTypes.CustomNode, type: "T_ROOT_NODE", label: "My Root Node", hasChildren: "Always", }], }, { ruleType: RuleTypes.ChildNodes, condition: `ParentNode.Type="T_ROOT_NODE"`, specifications: [{ specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses, classes: [{ schemaName: "BisCore", classNames: ["Model"], arePolymorphic: true }], }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // Verify that the custom node has `hasChildren` flag and children const rootNodes = await Presentation.presentation.getNodes({ imodel, rulesetOrId: ruleset }); expect(rootNodes).to.have.lengthOf(1).and.to.containSubset([{ key: { type: "T_ROOT_NODE" }, hasChildren: true, }]); const modelClassGroupingNodes = await Presentation.presentation.getNodes({ imodel, rulesetOrId: ruleset, parentKey: rootNodes[0].key }); expect(modelClassGroupingNodes).to.have.lengthOf(7).and.to.containSubset([{ key: { type: StandardNodeTypes.ECClassGroupingNode }, label: { displayValue: "Definition Model" }, }, { key: { type: StandardNodeTypes.ECClassGroupingNode }, label: { displayValue: "Dictionary Model" }, }, { key: { type: StandardNodeTypes.ECClassGroupingNode }, label: { displayValue: "Document List" }, }, { key: { type: StandardNodeTypes.ECClassGroupingNode }, label: { displayValue: "Group Model" }, }, { key: { type: StandardNodeTypes.ECClassGroupingNode }, label: { displayValue: "Link Model" }, }, { key: { type: StandardNodeTypes.ECClassGroupingNode }, label: { displayValue: "Physical Model" }, }, { key: { type: StandardNodeTypes.ECClassGroupingNode }, label: { displayValue: "Repository Model" }, }]); }); it("uses `relatedInstances` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.Hierarchies.Specification.RelatedInstances.Ruleset // The ruleset contains a root nodes' specification that returns nodes for `bis.Elements` that are in // a category containing "a" in either `UserLabel` or `CodeValue` property. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.RootNodes, specifications: [{ specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses, classes: [{ schemaName: "BisCore", classNames: ["GeometricElement3d"], arePolymorphic: true }], relatedInstances: [{ relationshipPath: [{ relationship: { schemaName: "BisCore", className: "GeometricElement3dIsInCategory" }, direction: RelationshipDirection.Forward, }], alias: "category", isRequired: true, }], instanceFilter: `category.UserLabel ~ "%a%" OR category.CodeValue ~ "%a%"`, }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // Verify that Elements whose Category contains "a" in either UserLabel or CodeValue are returned const nodes = await Presentation.presentation.getNodes({ imodel, rulesetOrId: ruleset }); expect(nodes).to.have.lengthOf(2).and.to.containSubset([{ key: { type: StandardNodeTypes.ECClassGroupingNode, className: "Generic:PhysicalObject" }, }, { key: { type: StandardNodeTypes.ECClassGroupingNode, className: "PCJ_TestSchema:TestClass" }, }]); }); it("uses `nestedRules` attribute", async () => { // __PUBLISH_EXTRACT_START__ Presentation.Hierarchies.Specification.NestedRules.Ruleset // The ruleset contains two root nodes' specifications: // - The first one returns `bis.SpatialCategory` nodes // - The second one returns `bis.PhysicalModel` nodes and also has a nested child node rule // that creates a static "child" node. // Nested rules apply only to nodes created by the same specification, so the static "child" // node is created only for the `bis.PhysicalModel`, but not `bis.SpatialCategory`. const ruleset: Ruleset = { id: "example", rules: [{ ruleType: RuleTypes.RootNodes, specifications: [{ specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses, classes: [{ schemaName: "BisCore", classNames: ["SpatialCategory"] }], groupByClass: false, }, { specType: ChildNodeSpecificationTypes.InstanceNodesOfSpecificClasses, classes: [{ schemaName: "BisCore", classNames: ["PhysicalModel"] }], groupByClass: false, nestedRules: [{ ruleType: RuleTypes.ChildNodes, specifications: [{ specType: ChildNodeSpecificationTypes.CustomNode, type: "T_CHILD", label: "child", }], }], }], }], }; // __PUBLISH_EXTRACT_END__ printRuleset(ruleset); // Verify that PhysicalModel node has a child node const rootNodes = await Presentation.presentation.getNodes({ imodel, rulesetOrId: ruleset }); expect(rootNodes).to.have.lengthOf(2).and.to.containSubset([{ key: { instanceKeys: [{ className: "BisCore:SpatialCategory" }] }, hasChildren: undefined, }, { key: { instanceKeys: [{ className: "BisCore:PhysicalModel" }] }, hasChildren: true, }]); const modelChildren = await Presentation.presentation.getNodes({ imodel, rulesetOrId: ruleset, parentKey: rootNodes[1].key }); expect(modelChildren).to.have.lengthOf(1).and.to.containSubset([{ label: { displayValue: "child" }, }]); }); }); });
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs, enums } from "./types"; import * as utilities from "./utilities"; /** * Provides a DigitalOcean Load Balancer resource. This can be used to create, * modify, and delete Load Balancers. * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as digitalocean from "@pulumi/digitalocean"; * * const web = new digitalocean.Droplet("web", { * size: "s-1vcpu-1gb", * image: "ubuntu-18-04-x64", * region: "nyc3", * }); * const _public = new digitalocean.LoadBalancer("public", { * region: "nyc3", * forwardingRules: [{ * entryPort: 80, * entryProtocol: "http", * targetPort: 80, * targetProtocol: "http", * }], * healthcheck: { * port: 22, * protocol: "tcp", * }, * dropletIds: [web.id], * }); * ``` * * When managing certificates attached to the load balancer, make sure to add the `createBeforeDestroy` * lifecycle property in order to ensure the certificate is correctly updated when changed. The order of * operations will then be: `Create new certificate` > `Update loadbalancer with new certificate` -> * `Delete old certificate`. When doing so, you must also change the name of the certificate, * as there cannot be multiple certificates with the same name in an account. * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as digitalocean from "@pulumi/digitalocean"; * * const cert = new digitalocean.Certificate("cert", { * privateKey: "file('key.pem')", * leafCertificate: "file('cert.pem')", * }); * const web = new digitalocean.Droplet("web", { * size: "s-1vcpu-1gb", * image: "ubuntu-18-04-x64", * region: "nyc3", * }); * const _public = new digitalocean.LoadBalancer("public", { * region: "nyc3", * forwardingRules: [{ * entryPort: 443, * entryProtocol: "https", * targetPort: 80, * targetProtocol: "http", * certificateName: cert.name, * }], * healthcheck: { * port: 22, * protocol: "tcp", * }, * dropletIds: [web.id], * }); * ``` * * ## Import * * Load Balancers can be imported using the `id`, e.g. * * ```sh * $ pulumi import digitalocean:index/loadBalancer:LoadBalancer myloadbalancer 4de7ac8b-495b-4884-9a69-1050c6793cd6 * ``` */ export class LoadBalancer extends pulumi.CustomResource { /** * Get an existing LoadBalancer resource's state with the given name, ID, and optional extra * properties used to qualify the lookup. * * @param name The _unique_ name of the resulting resource. * @param id The _unique_ provider ID of the resource to lookup. * @param state Any extra arguments used during the lookup. * @param opts Optional settings to control the behavior of the CustomResource. */ public static get(name: string, id: pulumi.Input<pulumi.ID>, state?: LoadBalancerState, opts?: pulumi.CustomResourceOptions): LoadBalancer { return new LoadBalancer(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'digitalocean:index/loadBalancer:LoadBalancer'; /** * Returns true if the given object is an instance of LoadBalancer. This is designed to work even * when multiple copies of the Pulumi SDK have been loaded into the same process. */ public static isInstance(obj: any): obj is LoadBalancer { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === LoadBalancer.__pulumiType; } /** * The load balancing algorithm used to determine * which backend Droplet will be selected by a client. It must be either `roundRobin` * or `leastConnections`. The default value is `roundRobin`. */ public readonly algorithm!: pulumi.Output<string | undefined>; /** * A list of the IDs of each droplet to be attached to the Load Balancer. */ public readonly dropletIds!: pulumi.Output<number[]>; /** * The name of a Droplet tag corresponding to Droplets to be assigned to the Load Balancer. */ public readonly dropletTag!: pulumi.Output<string | undefined>; /** * A boolean value indicating whether HTTP keepalive connections are maintained to target Droplets. Default value is `false`. */ public readonly enableBackendKeepalive!: pulumi.Output<boolean | undefined>; /** * A boolean value indicating whether PROXY * Protocol should be used to pass information from connecting client requests to * the backend service. Default value is `false`. */ public readonly enableProxyProtocol!: pulumi.Output<boolean | undefined>; /** * A list of `forwardingRule` to be assigned to the * Load Balancer. The `forwardingRule` block is documented below. */ public readonly forwardingRules!: pulumi.Output<outputs.LoadBalancerForwardingRule[]>; /** * A `healthcheck` block to be assigned to the * Load Balancer. The `healthcheck` block is documented below. Only 1 healthcheck is allowed. */ public readonly healthcheck!: pulumi.Output<outputs.LoadBalancerHealthcheck>; public /*out*/ readonly ip!: pulumi.Output<string>; /** * The uniform resource name for the Load Balancer */ public /*out*/ readonly loadBalancerUrn!: pulumi.Output<string>; /** * The Load Balancer name */ public readonly name!: pulumi.Output<string>; /** * A boolean value indicating whether * HTTP requests to the Load Balancer on port 80 will be redirected to HTTPS on port 443. * Default value is `false`. */ public readonly redirectHttpToHttps!: pulumi.Output<boolean | undefined>; /** * The region to start in */ public readonly region!: pulumi.Output<string>; /** * The size of the Load Balancer. It must be either `lb-small`, `lb-medium`, or `lb-large`. Defaults to `lb-small`. */ public readonly size!: pulumi.Output<string | undefined>; public /*out*/ readonly status!: pulumi.Output<string>; /** * A `stickySessions` block to be assigned to the * Load Balancer. The `stickySessions` block is documented below. Only 1 stickySessions block is allowed. */ public readonly stickySessions!: pulumi.Output<outputs.LoadBalancerStickySessions>; /** * The ID of the VPC where the load balancer will be located. */ public readonly vpcUuid!: pulumi.Output<string>; /** * Create a LoadBalancer resource with the given unique name, arguments, and options. * * @param name The _unique_ name of the resource. * @param args The arguments to use to populate this resource's properties. * @param opts A bag of options that control this resource's behavior. */ constructor(name: string, args: LoadBalancerArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: LoadBalancerArgs | LoadBalancerState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as LoadBalancerState | undefined; inputs["algorithm"] = state ? state.algorithm : undefined; inputs["dropletIds"] = state ? state.dropletIds : undefined; inputs["dropletTag"] = state ? state.dropletTag : undefined; inputs["enableBackendKeepalive"] = state ? state.enableBackendKeepalive : undefined; inputs["enableProxyProtocol"] = state ? state.enableProxyProtocol : undefined; inputs["forwardingRules"] = state ? state.forwardingRules : undefined; inputs["healthcheck"] = state ? state.healthcheck : undefined; inputs["ip"] = state ? state.ip : undefined; inputs["loadBalancerUrn"] = state ? state.loadBalancerUrn : undefined; inputs["name"] = state ? state.name : undefined; inputs["redirectHttpToHttps"] = state ? state.redirectHttpToHttps : undefined; inputs["region"] = state ? state.region : undefined; inputs["size"] = state ? state.size : undefined; inputs["status"] = state ? state.status : undefined; inputs["stickySessions"] = state ? state.stickySessions : undefined; inputs["vpcUuid"] = state ? state.vpcUuid : undefined; } else { const args = argsOrState as LoadBalancerArgs | undefined; if ((!args || args.forwardingRules === undefined) && !opts.urn) { throw new Error("Missing required property 'forwardingRules'"); } if ((!args || args.region === undefined) && !opts.urn) { throw new Error("Missing required property 'region'"); } inputs["algorithm"] = args ? args.algorithm : undefined; inputs["dropletIds"] = args ? args.dropletIds : undefined; inputs["dropletTag"] = args ? args.dropletTag : undefined; inputs["enableBackendKeepalive"] = args ? args.enableBackendKeepalive : undefined; inputs["enableProxyProtocol"] = args ? args.enableProxyProtocol : undefined; inputs["forwardingRules"] = args ? args.forwardingRules : undefined; inputs["healthcheck"] = args ? args.healthcheck : undefined; inputs["name"] = args ? args.name : undefined; inputs["redirectHttpToHttps"] = args ? args.redirectHttpToHttps : undefined; inputs["region"] = args ? args.region : undefined; inputs["size"] = args ? args.size : undefined; inputs["stickySessions"] = args ? args.stickySessions : undefined; inputs["vpcUuid"] = args ? args.vpcUuid : undefined; inputs["ip"] = undefined /*out*/; inputs["loadBalancerUrn"] = undefined /*out*/; inputs["status"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(LoadBalancer.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering LoadBalancer resources. */ export interface LoadBalancerState { /** * The load balancing algorithm used to determine * which backend Droplet will be selected by a client. It must be either `roundRobin` * or `leastConnections`. The default value is `roundRobin`. */ algorithm?: pulumi.Input<string | enums.Algorithm>; /** * A list of the IDs of each droplet to be attached to the Load Balancer. */ dropletIds?: pulumi.Input<pulumi.Input<number>[]>; /** * The name of a Droplet tag corresponding to Droplets to be assigned to the Load Balancer. */ dropletTag?: pulumi.Input<string>; /** * A boolean value indicating whether HTTP keepalive connections are maintained to target Droplets. Default value is `false`. */ enableBackendKeepalive?: pulumi.Input<boolean>; /** * A boolean value indicating whether PROXY * Protocol should be used to pass information from connecting client requests to * the backend service. Default value is `false`. */ enableProxyProtocol?: pulumi.Input<boolean>; /** * A list of `forwardingRule` to be assigned to the * Load Balancer. The `forwardingRule` block is documented below. */ forwardingRules?: pulumi.Input<pulumi.Input<inputs.LoadBalancerForwardingRule>[]>; /** * A `healthcheck` block to be assigned to the * Load Balancer. The `healthcheck` block is documented below. Only 1 healthcheck is allowed. */ healthcheck?: pulumi.Input<inputs.LoadBalancerHealthcheck>; ip?: pulumi.Input<string>; /** * The uniform resource name for the Load Balancer */ loadBalancerUrn?: pulumi.Input<string>; /** * The Load Balancer name */ name?: pulumi.Input<string>; /** * A boolean value indicating whether * HTTP requests to the Load Balancer on port 80 will be redirected to HTTPS on port 443. * Default value is `false`. */ redirectHttpToHttps?: pulumi.Input<boolean>; /** * The region to start in */ region?: pulumi.Input<string | enums.Region>; /** * The size of the Load Balancer. It must be either `lb-small`, `lb-medium`, or `lb-large`. Defaults to `lb-small`. */ size?: pulumi.Input<string>; status?: pulumi.Input<string>; /** * A `stickySessions` block to be assigned to the * Load Balancer. The `stickySessions` block is documented below. Only 1 stickySessions block is allowed. */ stickySessions?: pulumi.Input<inputs.LoadBalancerStickySessions>; /** * The ID of the VPC where the load balancer will be located. */ vpcUuid?: pulumi.Input<string>; } /** * The set of arguments for constructing a LoadBalancer resource. */ export interface LoadBalancerArgs { /** * The load balancing algorithm used to determine * which backend Droplet will be selected by a client. It must be either `roundRobin` * or `leastConnections`. The default value is `roundRobin`. */ algorithm?: pulumi.Input<string | enums.Algorithm>; /** * A list of the IDs of each droplet to be attached to the Load Balancer. */ dropletIds?: pulumi.Input<pulumi.Input<number>[]>; /** * The name of a Droplet tag corresponding to Droplets to be assigned to the Load Balancer. */ dropletTag?: pulumi.Input<string>; /** * A boolean value indicating whether HTTP keepalive connections are maintained to target Droplets. Default value is `false`. */ enableBackendKeepalive?: pulumi.Input<boolean>; /** * A boolean value indicating whether PROXY * Protocol should be used to pass information from connecting client requests to * the backend service. Default value is `false`. */ enableProxyProtocol?: pulumi.Input<boolean>; /** * A list of `forwardingRule` to be assigned to the * Load Balancer. The `forwardingRule` block is documented below. */ forwardingRules: pulumi.Input<pulumi.Input<inputs.LoadBalancerForwardingRule>[]>; /** * A `healthcheck` block to be assigned to the * Load Balancer. The `healthcheck` block is documented below. Only 1 healthcheck is allowed. */ healthcheck?: pulumi.Input<inputs.LoadBalancerHealthcheck>; /** * The Load Balancer name */ name?: pulumi.Input<string>; /** * A boolean value indicating whether * HTTP requests to the Load Balancer on port 80 will be redirected to HTTPS on port 443. * Default value is `false`. */ redirectHttpToHttps?: pulumi.Input<boolean>; /** * The region to start in */ region: pulumi.Input<string | enums.Region>; /** * The size of the Load Balancer. It must be either `lb-small`, `lb-medium`, or `lb-large`. Defaults to `lb-small`. */ size?: pulumi.Input<string>; /** * A `stickySessions` block to be assigned to the * Load Balancer. The `stickySessions` block is documented below. Only 1 stickySessions block is allowed. */ stickySessions?: pulumi.Input<inputs.LoadBalancerStickySessions>; /** * The ID of the VPC where the load balancer will be located. */ vpcUuid?: pulumi.Input<string>; }
the_stack
import "@/components/icon/Icon"; import { Key } from "@/constants"; import { customElementWithCheck, FocusMixin } from "@/mixins"; import reset from "@/wc_scss/reset.scss"; import { internalProperty, LitElement, property, PropertyValues, query, queryAll } from "lit-element"; import { html } from "lit-html"; import { classMap } from "lit-html/directives/class-map.js"; import { repeat } from "lit-html/directives/repeat.js"; import styles from "./scss/module.scss"; const EMPTY_KEY = ""; export namespace Dropdown { type OptionMember = { [key: string]: string }; type Option = string | OptionMember; type RenderOptionMember = { key: string; value: string; option?: Option }; export type EventDetail = { "dropdown-focus-in": undefined; "dropdown-focus-out": undefined; "dropdown-selected": { option: Option; }; }; @customElementWithCheck("md-dropdown") export class ELEMENT extends FocusMixin(LitElement) { @property({ type: String, attribute: "title" }) title = "Select..."; @property({ type: Array }) options: Option[] = []; @property({ type: String, attribute: "option-id" }) optionId = ""; @property({ type: String, attribute: "option-value" }) optionValue = ""; @property({ type: Object }) defaultOption: Option = EMPTY_KEY; @property({ type: Boolean, reflect: true }) disabled = false; @property({ type: Boolean, attribute: "allow-unselected", reflect: true }) allowUnselected = false; @property({ type: Number, attribute: "visible-option", reflect: true }) visibleOptions = 8; @internalProperty() private renderOptions: RenderOptionMember[] = []; @internalProperty() private selectedKey: string = EMPTY_KEY; @internalProperty() private expanded = false; @internalProperty() private focusedIndex = -1; @query("label") label!: HTMLLabelElement; @query("ul.md-dropdown-list") optionsList!: HTMLUListElement; @queryAll("li.md-dropdown-option") optionsListItems?: HTMLLIElement[]; private lastMaxHeight = ""; connectedCallback() { super.connectedCallback(); this.setupEvents(); } disconnectedCallback() { super.disconnectedCallback(); this.teardownEvents(); } protected firstUpdated(changedProperties: PropertyValues) { super.firstUpdated(changedProperties); this.setAttribute("tabindex", "0"); changedProperties.forEach((oldValue, name) => { if (name === "defaultOption") { if (this.defaultOption) { const { key } = this.getOptionKeyValuePair(this.defaultOption); this.selectedKey = key; } } }); } protected updated(changedProperties: PropertyValues) { super.updated(changedProperties); changedProperties.forEach((oldValue, name) => { if (name === "options") { this.updateRenderOptions(); } if (name === "selectedKey") { const idx = this.renderOptions.findIndex(o => o.key === this.selectedKey); if (idx !== -1) { this.focusToIndex(idx); } } if (name === "expanded") { this.updateListDOM(); } if (name === "focusedIndex") { this.updateListDOM(); } if (name === "disabled") { this.setAttribute("tabindex", !this.disabled ? "0" : "-1"); } }); } updateRenderOptions() { const existingKeys: string[] = []; this.focusReset(); const renderOptions = this.options.reduce((acc, option) => { const { key, value } = this.getOptionKeyValuePair(option); if (existingKeys.indexOf(key) !== -1) { console.error(`Dropdown already have option key: "${key}". Ignoring `); } else if (!key) { console.error(`Dropdown key is not defined: "${key}". (value: "${value}"). Ignoring `); } else { existingKeys.push(key); acc.push({ key, value, option }); } return acc; }, [] as RenderOptionMember[]); if (this.allowUnselected) { renderOptions.unshift({ key: EMPTY_KEY, value: this.title // || "" ? }); } this.renderOptions = renderOptions; } async updateListDOM() { if (!this.expanded) { return; } await this.resizeDropdownList(); await this.scrollToIndex(this.focusedIndex); } async resizeDropdownList() { await new Promise<void>(resolve => requestAnimationFrame(() => { if (this.optionsListItems) { if (this.optionsListItems.length > this.visibleOptions) { const maxHeight = [...this.optionsListItems] .slice(0, this.visibleOptions) .reduce((acc, option) => acc + option.offsetHeight, 0); const nextMaxHeight = `${maxHeight}px`; if (this.lastMaxHeight !== nextMaxHeight) { this.optionsList.style.maxHeight = nextMaxHeight; this.lastMaxHeight = nextMaxHeight; } } else { const nextMaxHeight = `auto`; if (this.lastMaxHeight !== nextMaxHeight) { this.optionsList.style.maxHeight = nextMaxHeight; this.lastMaxHeight = nextMaxHeight; } } } resolve(); }) ); } protected handleFocusIn(event: Event) { if (!this.disabled) { super.handleFocusIn && super.handleFocusIn(event); } this.dispatchEvent( new CustomEvent<EventDetail["dropdown-focus-in"]>("dropdown-focus-in", { composed: true, bubbles: true }) ); } protected handleFocusOut(event: Event) { super.handleFocusOut && super.handleFocusOut(event); this.dispatchEvent( new CustomEvent<EventDetail["dropdown-focus-out"]>("dropdown-focus-out", { composed: true, bubbles: true }) ); } static get styles() { return [reset, styles]; } setupEvents() { document.addEventListener("click", this.onOutsideClick); this.addEventListener("keydown", this.onKeyDown); } teardownEvents() { document.removeEventListener("click", this.onOutsideClick); this.removeEventListener("keydown", this.onKeyDown); } expand() { this.expanded = true; if (this.focusedIndex === -1) { this.focusNext(); } } collapse() { this.expanded = false; } toggle() { !this.expanded ? this.expand() : this.collapse(); } select() { if (this.focusedIndex !== -1) { const renderOption = this.renderOptions[this.focusedIndex]; const nextSelectedKey = renderOption.key; const prevSelectedKey = this.selectedKey; if (nextSelectedKey !== prevSelectedKey) { this.selectedKey = nextSelectedKey; this.dispatchEvent( new CustomEvent<EventDetail["dropdown-selected"]>("dropdown-selected", { composed: true, bubbles: true, detail: { option: renderOption.option ? renderOption.option : renderOption.key } }) ); } } } onOutsideClick = (e: MouseEvent) => { let insideSelfClick = false; const path = e.composedPath(); if (path.length) { insideSelfClick = !!path.find(element => element === this); if (!insideSelfClick) { this.collapse(); } } }; onKeyDown = (e: KeyboardEvent) => { switch (e.code) { case Key.Enter: { if (!this.expanded) { this.expand(); } else { this.select(); this.collapse(); } break; } case Key.ArrowDown: { if (!this.expanded) { this.expand(); } else { this.focusNext(); } break; } case Key.ArrowUp: { if (!this.expanded) { this.expand(); } else { this.focusPrev(); } break; } case Key.Home: { if (!this.expanded) { this.expand(); } else { this.focusFirst(); } break; } case Key.End: { if (!this.expanded) { this.expand(); } else { this.focusLast(); } break; } case Key.Escape || Key.Backspace: { if (this.expanded) { this.collapse(); } break; } } }; onLabelClick() { this.toggle(); } focusFirst() { if (this.renderOptions.length) { this.focusedIndex = 0; } } focusLast() { if (this.renderOptions.length) { this.focusedIndex = this.renderOptions.length - 1; } } focusNext() { if (this.renderOptions.length) { if (this.focusedIndex !== -1 && this.focusedIndex < this.renderOptions.length - 1) { this.focusedIndex++; } else { this.focusFirst(); } } } focusPrev() { if (this.renderOptions.length) { if (this.focusedIndex > 0) { this.focusedIndex--; } else { this.focusLast(); } } } focusToIndex(n: number) { if (this.renderOptions.length) { if (n >= 0 && n <= this.renderOptions.length - 1) { this.focusedIndex = n; } } } focusReset() { this.focusedIndex = -1; } async scrollToIndex(n: number) { await new Promise<void>(resolve => { requestAnimationFrame(() => { if ( this.optionsListItems && this.optionsListItems.length > this.visibleOptions && n >= 0 && this.optionsListItems.length > n ) { let distance = 0; const { top, bottom } = this.optionsList.getBoundingClientRect(); const option = this.optionsListItems[n]; const nextOption = this.optionsListItems[n + 1] || option; const prevOption = this.optionsListItems[n - 1] || option; const nextOptionRect = nextOption.getBoundingClientRect(); const prevOptionRect = prevOption.getBoundingClientRect(); if (nextOptionRect.bottom > bottom) { distance = nextOptionRect.bottom - bottom + 2; } else if (prevOptionRect.top < top) { distance = prevOptionRect.top - top - 2; } this.optionsList.scrollTop += distance; } resolve(); }); }); } getOptionKeyValuePair(option: Option) { if (typeof option === "string") { return { key: option.trim(), value: option }; } if (option && typeof option === "object") { const optionKeys = Object.keys(option as OptionMember); const optionValues = Object.values(option as OptionMember); if (optionKeys.length) { if (optionKeys.length === 1 || !this.optionId) { return { key: optionKeys[0], value: optionValues[0] }; } else if (this.optionId) { return { key: option[this.optionId], value: option[this.optionValue || this.optionId] }; } } } return { key: "undefined", value: "undefined" }; } get labelTitle() { if (this.selectedKey) { const option = this.renderOptions.find(o => o.key === this.selectedKey); if (option) { return option.value; } } return this.title; } get dropDownClassMap() { return { "md-dropdown__expanded": this.expanded }; } render() { return html` <div class="md-dropdown ${classMap(this.dropDownClassMap)}" part="dropdown"> <label class="md-dropdown-label" aria-expanded="${this.expanded}" aria-label="${this.labelTitle}" aria-controls="md-dropdown-list" ?disabled="${this.disabled}" @click="${() => this.onLabelClick()}" part="dropdown-header" > <span class="md-dropdown-label--text">${this.labelTitle}</span> <span class="md-dropdown-label--icon"> <md-icon name="icon-arrow-down_16"></md-icon> </span> </label> <ul id="md-dropdown-list" class="md-dropdown-list" role="listbox" aria-label="${this.labelTitle}" aria-hidden="${!this.expanded}" part="dropdown-options" > ${repeat( this.renderOptions, o => o.key, (o, idx) => html` <li class="md-dropdown-option" role="option" aria-label="${o.value}" aria-selected="${idx === this.focusedIndex}" part="dropdown-option" ?focused="${idx === this.focusedIndex}" @click="${() => { this.focusToIndex(idx); this.select(); this.collapse(); }}" > <span class="select-label" part="label"> <span>${o.value}</span> </span> </li> ` )} </ul> </div> `; } } } declare global { interface HTMLElementTagNameMap { "md-dropdown": Dropdown.ELEMENT; } }
the_stack
import { Emitter } from "./emitter"; import { isMetaElementKind, isTokenKind, SyntaxKind } from "../tokens"; import { UnicodeCharacterLiteral, UnicodeCharacterRange, Prose, Parameter, ParameterList, OneOfList, Terminal, SymbolSet, EmptyAssertion, LookaheadAssertion, NoSymbolHereAssertion, LexicalGoalAssertion, Constraints, ProseAssertion, Argument, ArgumentList, Nonterminal, OneOfSymbol, LexicalSymbol, ButNotSymbol, SymbolSpan, RightHandSide, RightHandSideList, Production, TextContent, Define, Line, Import, SourceFile, Node, StringLiteral, NumberLiteral, TerminalLiteral } from "../nodes"; /** {@docCategory Emit} */ export class GrammarkdownEmitter extends Emitter { protected extension = ".grammar"; protected emitNode(node: Node | undefined) { if (node && isTokenKind(node.kind)) { return this.emitToken(node); } switch (node?.kind) { case SyntaxKind.StringLiteral: return this.emitStringLiteral(node as StringLiteral); case SyntaxKind.NumberLiteral: return this.emitNumberLiteral(node as NumberLiteral); } return super.emitNode(node); } protected emitSourceFile(node: SourceFile) { let lastElementWasMeta = false; let lastCollapsedProduction: Production | undefined; let hasWrittenElement = false; for (const element of node.elements) { const thisElementIsMeta = isMetaElementKind(element.kind); const thisCollapsedProduction = element.kind === SyntaxKind.Production && element.body?.kind === SyntaxKind.RightHandSide ? element : undefined; if (hasWrittenElement) { if (!(thisElementIsMeta && lastElementWasMeta) && !(thisCollapsedProduction && lastCollapsedProduction && thisCollapsedProduction.name.text === lastCollapsedProduction.name.text)) { this.writer.commitLine(); this.writer.writeln(); } } this.emitNode(element); lastElementWasMeta = thisElementIsMeta; lastCollapsedProduction = thisCollapsedProduction; hasWrittenElement = true; } this.writer.writeln(); } private emitStringLiteral(node: StringLiteral) { this.writer.write(JSON.stringify(node.text ?? "")); } private emitNumberLiteral(node: NumberLiteral) { this.emitTextContent(node); } protected emitProduction(node: Production) { this.emitIdentifier(node.name); this.emitNode(node.parameterList); this.writer.write(" "); this.emitTokenKind(node.colonToken?.kind ?? SyntaxKind.ColonToken); switch (node.body?.kind) { case SyntaxKind.OneOfList: case SyntaxKind.RightHandSide: this.writer.write(" "); break; } this.emitNode(node.body); this.writer.writeln(); } protected emitParameterList(node: ParameterList) { this.writer.write("["); if (node.elements) { for (let i = 0; i < node.elements.length; ++i) { if (i > 0) { this.writer.write(`, `); } this.emitNode(node.elements[i]); } } this.writer.write(`]`); } protected emitParameter(node: Parameter) { this.emitIdentifier(node.name); } protected emitOneOfList(node: OneOfList) { this.emitTokenKind(SyntaxKind.OneKeyword); this.writer.write(" "); this.emitTokenKind(SyntaxKind.OfKeyword); if (node.terminals?.length) { let maxLength = 1; for (const child of node.terminals) { const len = child.text?.length ?? 0; if (len > maxLength) maxLength = len; } const columnCount = Math.max(1, Math.floor(56 / (maxLength + 2))); this.writer.writeln(); this.writer.indent(); const columnSizes = Array<number>(columnCount).fill(0); for (let i = 0; i < node.terminals.length; i++) { columnSizes[i % columnCount] = Math.max(columnSizes[i % columnCount], node.terminals[i].text?.length ?? 0); } for (let i = 0; i < node.terminals.length; i++) { if (i > 0) { if ((i % columnCount) === 0) { this.writer.writeln(); } else { const lastColumnSize = columnSizes[(i % columnCount) - 1]; const lastLen = node.terminals[i - 1].text?.length ?? 1; this.writer.write(" ".repeat(lastColumnSize - lastLen + 1)); } } this.emitNode(node.terminals[i]); } this.writer.dedent(); } } protected emitRightHandSideList(node: RightHandSideList) { this.writer.indent(); if (node.elements) { for (const rhs of node.elements) { this.writer.writeln(); this.emitNode(rhs); } } this.writer.dedent(); } protected emitRightHandSide(node: RightHandSide) { this.emitChildren(node); } protected emitSymbolSpan(node: SymbolSpan) { this.emitNode(node.symbol); if (node.next) { this.writer.write(" "); this.emitNode(node.next); } } protected emitPlaceholder(node: LexicalSymbol) { this.emitTokenKind(SyntaxKind.AtToken); } protected emitTerminal(node: Terminal) { this.emitNode(node.literal); this.emitNode(node.questionToken); } protected emitNonterminal(node: Nonterminal) { this.emitChildren(node); } protected emitArgumentList(node: ArgumentList) { this.writer.write("["); if (node.elements) { for (let i = 0; i < node.elements.length; ++i) { if (i > 0) { this.writer.write(`, `); } this.emitNode(node.elements[i]); } } this.writer.write(`]`); } protected emitArgument(node: Argument) { this.emitToken(node.operatorToken); this.emitNode(node.name); } protected emitUnicodeCharacterRange(node: UnicodeCharacterRange) { this.emitTextContent(node.left); this.writer.write(` through `); this.emitTextContent(node.right); } protected emitUnicodeCharacterLiteral(node: UnicodeCharacterLiteral) { this.emitTextContent(node); } protected emitTerminalLiteral(node: TerminalLiteral) { if (node.text === "`") { this.writer.write("```"); } else { this.writer.write("`"); this.writer.write(node.text ?? ""); this.writer.write("`"); } } protected emitProse(node: Prose) { this.writer.write("> "); node.fragments && this.emitNodes(node.fragments); } protected emitEmptyAssertion(node: EmptyAssertion) { this.writer.write("[empty]"); } protected emitSymbolSet(node: SymbolSet) { this.writer.write(`{`); if (node.elements) { for (let i = 0; i < node.elements.length; ++i) { if (i > 0) { this.writer.write(`,`); } this.writer.write(` `); this.emitNode(node.elements[i]); } } this.writer.write(` }`); } protected emitLookaheadAssertion(node: LookaheadAssertion) { this.writer.write(`[`); this.emitToken(node.lookaheadKeyword); this.writer.write(" "); this.emitTokenKind(node.operatorToken?.kind ?? SyntaxKind.EqualsToken); this.writer.write(" "); this.emitNode(node.lookahead); this.writer.write(`]`); } protected emitLexicalGoalAssertion(node: LexicalGoalAssertion): void { this.writer.write(`[lexical goal `); this.emitNode(node.symbol); this.writer.write(`]`); } protected emitNoSymbolHereAssertion(node: NoSymbolHereAssertion): void { this.writer.write(`[no `); if (node.symbols) { for (let i = 0; i < node.symbols.length; ++i) { if (i > 0) { this.writer.write(` or `); } this.emitNode(node.symbols[i]); } } this.writer.write(` here]`); } protected emitConstraints(node: Constraints): void { this.writer.write("["); if (node.elements) { for (let i = 0; i < node.elements.length; ++i) { if (i > 0) { this.writer.write(`, `); } this.emitNode(node.elements[i]); } } this.writer.write("] "); } protected emitProseAssertion(node: ProseAssertion): void { this.writer.write(`[>`); if (node.fragments) { for (const fragment of node.fragments) { this.emitNode(fragment); } } this.writer.write(`]`); } protected emitButNotSymbol(node: ButNotSymbol) { this.emitNode(node.left); this.writer.write(` but not `); this.emitNode(node.right); } protected emitOneOfSymbol(node: OneOfSymbol) { this.writer.write(`one of `); if (node.symbols) { for (let i = 0; i < node.symbols.length; ++i) { if (i > 0) { this.writer.write(` or `); } this.emitNode(node.symbols[i]); } } } protected emitTextContent(node: TextContent) { if (node?.text) { this.writer.write(node.text); } } protected emitDefine(node: Define) { this.emitNode(node.atToken); this.emitNode(node.defineKeyword); this.writer.write(" "); this.emitNode(node.key); this.writer.write(" "); this.emitNode(node.valueToken); this.writer.writeln(); } protected emitLine(node: Line) { this.emitNode(node.atToken); this.emitNode(node.lineKeyword); this.writer.write(" "); this.emitNode(node.number); if (node.path) { this.writer.write(" "); this.emitNode(node.path); } this.writer.writeln(); } protected emitImport(node: Import) { this.emitNode(node.atToken); this.emitNode(node.importKeyword); this.writer.write(" "); this.emitNode(node.path); this.writer.writeln(); } }
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement } from "../shared"; /** * Statement provider for service [ds](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsdirectoryservice.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Ds extends PolicyStatement { public servicePrefix = 'ds'; /** * Statement provider for service [ds](https://docs.aws.amazon.com/service-authorization/latest/reference/list_awsdirectoryservice.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ constructor (sid?: string) { super(sid); } /** * Accepts a directory sharing request that was sent from the directory owner account. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_AcceptSharedDirectory.html */ public toAcceptSharedDirectory() { return this.to('AcceptSharedDirectory'); } /** * Adds a CIDR address block to correctly route traffic to and from your Microsoft AD on Amazon Web Services * * Access Level: Write * * Dependent actions: * - ec2:AuthorizeSecurityGroupEgress * - ec2:AuthorizeSecurityGroupIngress * - ec2:DescribeSecurityGroups * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_AddIpRoutes.html */ public toAddIpRoutes() { return this.to('AddIpRoutes'); } /** * Adds two domain controllers in the specified Region for the specified directory. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_AddRegion.html */ public toAddRegion() { return this.to('AddRegion'); } /** * Adds or overwrites one or more tags for the specified Amazon Directory Services directory. * * Access Level: Tagging * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * Dependent actions: * - ec2:CreateTags * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_AddTagsToResource.html */ public toAddTagsToResource() { return this.to('AddTagsToResource'); } /** * Authorizes an application for your AWS Directory. * * Access Level: Write */ public toAuthorizeApplication() { return this.to('AuthorizeApplication'); } /** * Cancels an in-progress schema extension to a Microsoft AD directory. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_CancelSchemaExtension.html */ public toCancelSchemaExtension() { return this.to('CancelSchemaExtension'); } /** * Verifies that the alias is available for use. * * Access Level: Read */ public toCheckAlias() { return this.to('CheckAlias'); } /** * Creates an AD Connector to connect to an on-premises directory. * * Access Level: Tagging * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * Dependent actions: * - ec2:AuthorizeSecurityGroupEgress * - ec2:AuthorizeSecurityGroupIngress * - ec2:CreateNetworkInterface * - ec2:CreateSecurityGroup * - ec2:CreateTags * - ec2:DescribeNetworkInterfaces * - ec2:DescribeSubnets * - ec2:DescribeVpcs * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_ConnectDirectory.html */ public toConnectDirectory() { return this.to('ConnectDirectory'); } /** * Creates an alias for a directory and assigns the alias to the directory. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_CreateAlias.html */ public toCreateAlias() { return this.to('CreateAlias'); } /** * Creates a computer account in the specified directory, and joins the computer to the directory. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_CreateComputer.html */ public toCreateComputer() { return this.to('CreateComputer'); } /** * Creates a conditional forwarder associated with your AWS directory. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_CreateConditionalForwarder.html */ public toCreateConditionalForwarder() { return this.to('CreateConditionalForwarder'); } /** * Creates a Simple AD directory. * * Access Level: Tagging * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * Dependent actions: * - ec2:AuthorizeSecurityGroupEgress * - ec2:AuthorizeSecurityGroupIngress * - ec2:CreateNetworkInterface * - ec2:CreateSecurityGroup * - ec2:CreateTags * - ec2:DescribeNetworkInterfaces * - ec2:DescribeSubnets * - ec2:DescribeVpcs * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_CreateDirectory.html */ public toCreateDirectory() { return this.to('CreateDirectory'); } /** * Creates a IdentityPool Directory in the AWS cloud. * * Access Level: Tagging * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() */ public toCreateIdentityPoolDirectory() { return this.to('CreateIdentityPoolDirectory'); } /** * Creates a subscription to forward real time Directory Service domain controller security logs to the specified CloudWatch log group in your AWS account. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_CreateLogSubscription.html */ public toCreateLogSubscription() { return this.to('CreateLogSubscription'); } /** * Creates a Microsoft AD in the AWS cloud. * * Access Level: Tagging * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * Dependent actions: * - ec2:AuthorizeSecurityGroupEgress * - ec2:AuthorizeSecurityGroupIngress * - ec2:CreateNetworkInterface * - ec2:CreateSecurityGroup * - ec2:CreateTags * - ec2:DescribeNetworkInterfaces * - ec2:DescribeSubnets * - ec2:DescribeVpcs * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_CreateMicrosoftAD.html */ public toCreateMicrosoftAD() { return this.to('CreateMicrosoftAD'); } /** * Creates a snapshot of a Simple AD or Microsoft AD directory in the AWS cloud. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_CreateSnapshot.html */ public toCreateSnapshot() { return this.to('CreateSnapshot'); } /** * Initiates the creation of the AWS side of a trust relationship between a Microsoft AD in the AWS cloud and an external domain. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_CreateTrust.html */ public toCreateTrust() { return this.to('CreateTrust'); } /** * Deletes a conditional forwarder that has been set up for your AWS directory. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_DeleteConditionalForwarder.html */ public toDeleteConditionalForwarder() { return this.to('DeleteConditionalForwarder'); } /** * Deletes an AWS Directory Service directory. * * Access Level: Write * * Dependent actions: * - ec2:DeleteNetworkInterface * - ec2:DeleteSecurityGroup * - ec2:DescribeNetworkInterfaces * - ec2:RevokeSecurityGroupEgress * - ec2:RevokeSecurityGroupIngress * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_DeleteDirectory.html */ public toDeleteDirectory() { return this.to('DeleteDirectory'); } /** * Deletes the specified log subscription. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_DeleteLogSubscription.html */ public toDeleteLogSubscription() { return this.to('DeleteLogSubscription'); } /** * Deletes a directory snapshot. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_DeleteSnapshot.html */ public toDeleteSnapshot() { return this.to('DeleteSnapshot'); } /** * Deletes an existing trust relationship between your Microsoft AD in the AWS cloud and an external domain. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/DeleteTrust.html */ public toDeleteTrust() { return this.to('DeleteTrust'); } /** * Deletes from the system the certificate that was registered for a secured LDAP connection. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_DeregisterCertificate.html */ public toDeregisterCertificate() { return this.to('DeregisterCertificate'); } /** * Removes the specified directory as a publisher to the specified SNS topic. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_DeregisterEventTopic.html */ public toDeregisterEventTopic() { return this.to('DeregisterEventTopic'); } /** * Displays information about the certificate registered for a secured LDAP connection. * * Access Level: Read * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_DescribeCertificate.html */ public toDescribeCertificate() { return this.to('DescribeCertificate'); } /** * Obtains information about the conditional forwarders for this account. * * Access Level: Read * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_DescribeConditionalForwarders.html */ public toDescribeConditionalForwarders() { return this.to('DescribeConditionalForwarders'); } /** * Obtains information about the directories that belong to this account. * * Access Level: List * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_DescribeDirectories.html */ public toDescribeDirectories() { return this.to('DescribeDirectories'); } /** * Provides information about any domain controllers in your directory. * * Access Level: Read * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_DescribeDomainControllers.html */ public toDescribeDomainControllers() { return this.to('DescribeDomainControllers'); } /** * Obtains information about which SNS topics receive status messages from the specified directory. * * Access Level: Read * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_DescribeEventTopics.html */ public toDescribeEventTopics() { return this.to('DescribeEventTopics'); } /** * Describes the status of LDAP security for the specified directory. * * Access Level: Read * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_DescribeLDAPSSettings.html */ public toDescribeLDAPSSettings() { return this.to('DescribeLDAPSSettings'); } /** * Provides information about the Regions that are configured for multi-Region replication. * * Access Level: Read * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_DescribeRegions.html */ public toDescribeRegions() { return this.to('DescribeRegions'); } /** * Returns the shared directories in your account. * * Access Level: Read * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_DescribeSharedDirectories.html */ public toDescribeSharedDirectories() { return this.to('DescribeSharedDirectories'); } /** * Obtains information about the directory snapshots that belong to this account. * * Access Level: Read * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_DescribeSnapshots.html */ public toDescribeSnapshots() { return this.to('DescribeSnapshots'); } /** * Obtains information about the trust relationships for this account. * * Access Level: Read * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_DescribeTrusts.html */ public toDescribeTrusts() { return this.to('DescribeTrusts'); } /** * Disables alternative client authentication methods for the specified directory. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_DisableClientAuthentication.html */ public toDisableClientAuthentication() { return this.to('DisableClientAuthentication'); } /** * Deactivates LDAP secure calls for the specified directory. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_DisableLDAPS.html */ public toDisableLDAPS() { return this.to('DisableLDAPS'); } /** * Disables multi-factor authentication (MFA) with the Remote Authentication Dial In User Service (RADIUS) server for an AD Connector directory. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_DisableRadius.html */ public toDisableRadius() { return this.to('DisableRadius'); } /** * Disables single-sign on for a directory. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_DisableSso.html */ public toDisableSso() { return this.to('DisableSso'); } /** * Enables alternative client authentication methods for the specified directory. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_EnableClientAuthentication.html */ public toEnableClientAuthentication() { return this.to('EnableClientAuthentication'); } /** * Activates the switch for the specific directory to always use LDAP secure calls. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_EnableLDAPS.html */ public toEnableLDAPS() { return this.to('EnableLDAPS'); } /** * Enables multi-factor authentication (MFA) with the Remote Authentication Dial In User Service (RADIUS) server for an AD Connector directory. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_EnableRadius.html */ public toEnableRadius() { return this.to('EnableRadius'); } /** * Enables single-sign on for a directory. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_EnableSso.html */ public toEnableSso() { return this.to('EnableSso'); } /** * * * Access Level: Read * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_GetAuthorizedApplicationDetails.html */ public toGetAuthorizedApplicationDetails() { return this.to('GetAuthorizedApplicationDetails'); } /** * Obtains directory limit information for the current region. * * Access Level: Read * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_GetDirectoryLimits.html */ public toGetDirectoryLimits() { return this.to('GetDirectoryLimits'); } /** * Obtains the manual snapshot limits for a directory. * * Access Level: Read * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_GetSnapshotLimits.html */ public toGetSnapshotLimits() { return this.to('GetSnapshotLimits'); } /** * Obtains the aws applications authorized for a directory. * * Access Level: Read */ public toListAuthorizedApplications() { return this.to('ListAuthorizedApplications'); } /** * For the specified directory, lists all the certificates registered for a secured LDAP connection. * * Access Level: List * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_ListCertificates.html */ public toListCertificates() { return this.to('ListCertificates'); } /** * Lists the address blocks that you have added to a directory. * * Access Level: Read * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_ListIpRoutes.html */ public toListIpRoutes() { return this.to('ListIpRoutes'); } /** * Lists the active log subscriptions for the AWS account. * * Access Level: Read * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_ListLogSubscriptions.html */ public toListLogSubscriptions() { return this.to('ListLogSubscriptions'); } /** * Lists all schema extensions applied to a Microsoft AD Directory. * * Access Level: List * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_ListSchemaExtensions.html */ public toListSchemaExtensions() { return this.to('ListSchemaExtensions'); } /** * Lists all tags on an Amazon Directory Services directory. * * Access Level: Read * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Registers a certificate for secured LDAP connection. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_RegisterCertificate.html */ public toRegisterCertificate() { return this.to('RegisterCertificate'); } /** * Associates a directory with an SNS topic. * * Access Level: Write * * Dependent actions: * - sns:GetTopicAttributes * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_RegisterEventTopic.html */ public toRegisterEventTopic() { return this.to('RegisterEventTopic'); } /** * Rejects a directory sharing request that was sent from the directory owner account. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_RejectSharedDirectory.html */ public toRejectSharedDirectory() { return this.to('RejectSharedDirectory'); } /** * Removes IP address blocks from a directory. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_RemoveIpRoutes.html */ public toRemoveIpRoutes() { return this.to('RemoveIpRoutes'); } /** * Stops all replication and removes the domain controllers from the specified Region. You cannot remove the primary Region with this operation. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_RemoveRegion.html */ public toRemoveRegion() { return this.to('RemoveRegion'); } /** * Removes tags from an Amazon Directory Services directory. * * Access Level: Tagging * * Possible conditions: * - .ifAwsRequestTag() * - .ifAwsTagKeys() * * Dependent actions: * - ec2:DeleteTags * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_RemoveTagsFromResource.html */ public toRemoveTagsFromResource() { return this.to('RemoveTagsFromResource'); } /** * Resets the password for any user in your AWS Managed Microsoft AD or Simple AD directory. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_ResetUserPassword.html */ public toResetUserPassword() { return this.to('ResetUserPassword'); } /** * Restores a directory using an existing directory snapshot. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_RestoreFromSnapshot.html */ public toRestoreFromSnapshot() { return this.to('RestoreFromSnapshot'); } /** * Shares a specified directory in your AWS account (directory owner) with another AWS account (directory consumer). With this operation you can use your directory from any AWS account and from any Amazon VPC within an AWS Region. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_ShareDirectory.html */ public toShareDirectory() { return this.to('ShareDirectory'); } /** * Applies a schema extension to a Microsoft AD directory. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_StartSchemaExtension.html */ public toStartSchemaExtension() { return this.to('StartSchemaExtension'); } /** * Unauthorizes an application from your AWS Directory. * * Access Level: Write */ public toUnauthorizeApplication() { return this.to('UnauthorizeApplication'); } /** * Stops the directory sharing between the directory owner and consumer accounts. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_UnshareDirectory.html */ public toUnshareDirectory() { return this.to('UnshareDirectory'); } /** * Updates a conditional forwarder that has been set up for your AWS directory. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_UpdateConditionalForwarder.html */ public toUpdateConditionalForwarder() { return this.to('UpdateConditionalForwarder'); } /** * Adds or removes domain controllers to or from the directory. Based on the difference between current value and new value (provided through this API call), domain controllers will be added or removed. It may take up to 45 minutes for any new domain controllers to become fully active once the requested number of domain controllers is updated. During this time, you cannot make another update request. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_UpdateNumberOfDomainControllers.html */ public toUpdateNumberOfDomainControllers() { return this.to('UpdateNumberOfDomainControllers'); } /** * Updates the Remote Authentication Dial In User Service (RADIUS) server information for an AD Connector directory. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_UpdateRadius.html */ public toUpdateRadius() { return this.to('UpdateRadius'); } /** * Updates the trust that has been set up between your AWS Managed Microsoft AD directory and an on-premises Active Directory. * * Access Level: Write * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_UpdateTrust.html */ public toUpdateTrust() { return this.to('UpdateTrust'); } /** * Verifies a trust relationship between your Microsoft AD in the AWS cloud and an external domain. * * Access Level: Read * * https://docs.aws.amazon.com/directoryservice/latest/devguide/API_VerifyTrust.html */ public toVerifyTrust() { return this.to('VerifyTrust'); } protected accessLevelList: AccessLevelList = { "Write": [ "AcceptSharedDirectory", "AddIpRoutes", "AddRegion", "AuthorizeApplication", "CancelSchemaExtension", "CreateAlias", "CreateComputer", "CreateConditionalForwarder", "CreateLogSubscription", "CreateSnapshot", "CreateTrust", "DeleteConditionalForwarder", "DeleteDirectory", "DeleteLogSubscription", "DeleteSnapshot", "DeleteTrust", "DeregisterCertificate", "DeregisterEventTopic", "DisableClientAuthentication", "DisableLDAPS", "DisableRadius", "DisableSso", "EnableClientAuthentication", "EnableLDAPS", "EnableRadius", "EnableSso", "RegisterCertificate", "RegisterEventTopic", "RejectSharedDirectory", "RemoveIpRoutes", "RemoveRegion", "ResetUserPassword", "RestoreFromSnapshot", "ShareDirectory", "StartSchemaExtension", "UnauthorizeApplication", "UnshareDirectory", "UpdateConditionalForwarder", "UpdateNumberOfDomainControllers", "UpdateRadius", "UpdateTrust" ], "Tagging": [ "AddTagsToResource", "ConnectDirectory", "CreateDirectory", "CreateIdentityPoolDirectory", "CreateMicrosoftAD", "RemoveTagsFromResource" ], "Read": [ "CheckAlias", "DescribeCertificate", "DescribeConditionalForwarders", "DescribeDomainControllers", "DescribeEventTopics", "DescribeLDAPSSettings", "DescribeRegions", "DescribeSharedDirectories", "DescribeSnapshots", "DescribeTrusts", "GetAuthorizedApplicationDetails", "GetDirectoryLimits", "GetSnapshotLimits", "ListAuthorizedApplications", "ListIpRoutes", "ListLogSubscriptions", "ListTagsForResource", "VerifyTrust" ], "List": [ "DescribeDirectories", "ListCertificates", "ListSchemaExtensions" ] }; /** * Adds a resource of type directory to the statement * * @param directoryId - Identifier for the directoryId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. * * Possible conditions: * - .ifAwsResourceTag() */ public onDirectory(directoryId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ds:${Region}:${Account}:directory/${DirectoryId}'; arn = arn.replace('${DirectoryId}', directoryId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } }
the_stack
import React, { useCallback, useState, useMemo, lazy, useEffect } from 'react'; import ConfigurationController from '~/components/MiniDashboard/ConfigurationController'; import s from './Dashboard.module.less'; import { Menu, Select, Tooltip, Modal, Row, Col, Input, Button } from 'antd'; import { ClusterOutlined, CodeOutlined, CopyOutlined, DeleteOutlined, FormatPainterOutlined, ToolOutlined, } from '@ant-design/icons'; import reject from 'lodash/reject'; import { useDispatch, useSelector } from 'react-redux'; import { RootState, Dispatch } from '~/redux/store'; import StyleController from '../StyleController'; import usePostMessage from '~/hooks/usePostMessage'; import { v4 as uuidv4 } from 'uuid'; import cloneDeep from 'lodash/cloneDeep'; import useKeyDown from '~/hooks/useKeyDown'; import RunningTimesModal from '../RunningTimesModal'; const { confirm } = Modal; interface Props {} const Dashboard: React.FC<Props> = () => { // 复制模块 const [showCopyedModal, setShowCopyedModal] = useState(false); // 复制模块名称 const [newModalName, setNewModalName] = useState<string>(); const [showRunningTimes, setShowRunningTimes] = useState(false); const runningTimes = useSelector((state: RootState) => state.runningTimes); // appdata const appData = useSelector((state: RootState) => state.appData); // 模板ID const moduleId = useSelector( (state: RootState) => state.activationItem.moduleId, ); const activationItem = useSelector( (state: RootState) => state.activationItem, ); const updateActivationItem = useDispatch<Dispatch>().activationItem.updateActivationItem; const updateAppData = useDispatch<Dispatch>().appData.updateAppData; const removeActivationItem = useDispatch<Dispatch>().activationItem.removeActivationItem; // 样式与设置菜单面板 const [mainTag, setMainTag] = useState('config'); const onSelectMainTag = useCallback((e) => { setMainTag(e.key); }, []); const sendMessage = usePostMessage(() => {}); // 收发处理,子窗口onload时向子窗口发送信息, 通知当前正处于编辑模式下, // 重置当前被选择项 const onChangeSelect = useCallback( (e) => { if (activationItem.moduleId === e) return; for (let index = 0; index < appData.length; index++) { const element = appData[index]; if (element.moduleId === e) { const value = { ...element }; updateActivationItem(value); const win = ( document.getElementById('wrapiframe') as HTMLIFrameElement ).contentWindow; if (win) { sendMessage({ tag: 'id', value: element.moduleId }, win); } break; } } }, [activationItem.moduleId, appData, sendMessage, updateActivationItem], ); // =====================================模块删除=======================================// const [isDeleteComp, setIsDeleteComp] = useState(false); const delModule = useCallback(() => { const optAppData = reject([...appData], { moduleId }); const win = (document.getElementById('wrapiframe') as HTMLIFrameElement) .contentWindow; updateAppData(optAppData); removeActivationItem(); sendMessage( { tag: 'updateAppData', value: optAppData, }, win, ); console.log(4); sendMessage( { tag: 'removeActivationItem', value: undefined, }, win, ); setIsDeleteComp(false); }, [appData, moduleId, removeActivationItem, sendMessage, updateAppData]); const confirmModal = useCallback(() => { if (isDeleteComp) return; setIsDeleteComp(true); confirm({ content: ( <div> <h3>确定删除</h3> <br /> 模块名称:{activationItem.moduleName} <br /> Id: {activationItem.moduleId} <br /> <span className={s.warn}> 当前模块将被移除,请手动清除其他模块事件中引用的当前模块方法。 </span> </div> ), okText: '确定', cancelText: '取消', onCancel: () => setIsDeleteComp(false), onOk: delModule, }); }, [ isDeleteComp, activationItem.moduleName, activationItem.moduleId, delModule, ]); // 模块删除快捷键 // key deletd useKeyDown((event) => { const activeNode = document.activeElement?.tagName.toLowerCase(); if (!isDeleteComp && activeNode !== 'input' && activeNode !== 'textarea') { event.preventDefault(); confirmModal(); } }, 'Delete'); // =====================================模块复制=======================================// // copyData const beforCopyModule = useCallback(() => { setNewModalName(`${activationItem.moduleName} 拷贝`); setShowCopyedModal(true); }, [activationItem.moduleName]); // 初始化或,取消复制弹窗 const initCopyModule = useCallback(() => { setShowCopyedModal(false); setNewModalName(undefined); }, []); // 方法,复制当前选中的组件 const copyModule = useCallback(() => { // 准备创建 const oprateActivationItem = cloneDeep(activationItem); const copyAppData = cloneDeep(appData); const moduleId = uuidv4(); oprateActivationItem.moduleId = moduleId; oprateActivationItem.layout!.i = moduleId; oprateActivationItem.moduleName = newModalName || `${activationItem.moduleName} 拷贝`; // 模块位置 if (copyAppData.length > 1) { copyAppData.sort((a, b) => (b.layout?.y || 0) - (a.layout?.y || 0)); } const layoutY = copyAppData[0].layout?.y || 0; const layoutH = copyAppData[0].layout?.h || 0; oprateActivationItem.layout!.y = layoutY + layoutH; // 复制模块,更新当前模块到全局并设为当前被选择模块 updateAppData([...appData, oprateActivationItem]); updateActivationItem(oprateActivationItem); // 初始化复制窗口 initCopyModule(); }, [ activationItem, appData, newModalName, updateAppData, updateActivationItem, initCopyModule, ]); // 处理键盘事件 // 模拟模块复制 useKeyDown( () => { const activeNode = document.activeElement?.tagName.toLowerCase(); if (activeNode === 'iframe') { beforCopyModule(); } }, 'c', 'ctrlKey', ); // // 确认复制模块 useKeyDown((event) => { if (showCopyedModal) { event.preventDefault(); copyModule(); } }, 'Enter'); const CodeEditor = useMemo( () => lazy(() => import(`../CodeEditor/index`)), [], ); return ( <> <div className={s.headtab}> <div className={s.moduleselect}> <Select onChange={onChangeSelect} className={s.select} value={moduleId} showSearch placeholder="请选择编辑模块" optionFilterProp="children" filterOption={ (input, option) => { const str = option?.children.join('').toLowerCase(); if (str.indexOf(input) !== -1) { return true; } return false; } // option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0 } > {appData.map((item) => ( <Select.Option value={item.moduleId} key={item.moduleId}> {item.moduleName || '(未标题)'}-{item.type} </Select.Option> ))} </Select> </div> <Menu onClick={() => setMainTag('config')} onSelect={onSelectMainTag} selectedKeys={[mainTag]} mode="horizontal" className={s.contentmenu} > <Menu.Item key="config" icon={<ToolOutlined />}> 设置 </Menu.Item> <Menu.Item key="style" icon={<FormatPainterOutlined />}> 样式 </Menu.Item> <Menu.Item key="code" icon={<CodeOutlined />}> code </Menu.Item> </Menu> <div className={s.info}> <Tooltip placement="bottomRight" title="查看全局发布变量"> <ClusterOutlined className={s.delete} onClick={() => setShowRunningTimes(true)} /> </Tooltip> </div> <div className={s.info}> <Tooltip placement="bottomRight" title={ <div className={s.tips}> <h3>复制为新模块</h3> 当前模块信息 <br /> 模块:{activationItem.moduleName} <br /> 类型:{activationItem.type} <br /> Id:{activationItem.moduleId} </div> } > <CopyOutlined alt="复制模块" onClick={beforCopyModule} /> </Tooltip> </div> <div> <Tooltip placement="bottomRight" title={`删除 ${ activationItem.moduleName || activationItem.moduleId }`} > <DeleteOutlined className={s.delete} onClick={confirmModal} /> </Tooltip> </div> </div> <div className={s.root} style={{ height: `${window.innerHeight - 80}px` }} > <div className={s.controllerwrap} style={{ display: mainTag === 'style' ? 'block' : 'none' }} > <StyleController /> </div> <div className={s.controllerwrap} style={{ display: mainTag === 'config' ? 'block' : 'none' }} > <ConfigurationController /> </div> <div className={s.controllerwrap} style={{ display: mainTag === 'code' ? 'block' : 'none' }} > <CodeEditor /> </div> </div> <Modal title={`复制${activationItem?.moduleName || ''}(${ activationItem?.type || '' })模块`} visible={!!showCopyedModal} footer={null} onCancel={initCopyModule} > <Row gutter={[16, 16]}> <Col span={3}></Col> <Col span={15}> <Input type="text" value={newModalName as any} onChange={(e) => setNewModalName(e.target.value || undefined)} placeholder={`请输入${activationItem?.type || ''}模块的别名`} /> </Col> <Col span={6}> <Button type="primary" onClick={copyModule}> 确定 </Button> </Col> </Row> <br /> </Modal> <RunningTimesModal visible={showRunningTimes} data={runningTimes} onCancel={() => setShowRunningTimes(false)} /> </> ); }; export default Dashboard;
the_stack
import { useScreenDimensions } from "lib/utils/useScreenDimensions" import { throttle } from "lodash" import React, { useCallback, useEffect, useMemo, useRef, useState } from "react" import { Animated } from "react-native" import { Rect, Size } from "../../geometry" import { EventStream, useEvents } from "../useEventStream" import { VISUAL_DEBUG_MODE } from "./__deepZoomDebug" import { getVisibleRowsAndColumns, ZoomScaleBoundaries } from "./deepZoomGeometry" import { DeepZoomPyramid } from "./DeepZoomPyramid" import { DeepZoomTile, DeepZoomTileID } from "./DeepZoomTile" /** * DeepZoomLevel is responsible for showing one layer of tile images at a particular resolution. * It scales and translates the tiles in accordance with the zoomScale + contentOffset properties of the * controlling scroll view. In addition it uses the position of the view port to decide which rows and columns * to show at a given point in time. */ export const DeepZoomLevel: React.FC<{ $contentOffsetX: Animated.Animated $contentOffsetY: Animated.Animated $zoomScale: Animated.Animated imageFittedWithinScreen: Size & { marginHorizontal: number; marginVertical: number } level: number levelDimensions: Size makeUrl: (props: { row: number; col: number }) => string pyramid: DeepZoomPyramid tileSize: number viewPortChanges: EventStream<Rect> zoomScaleBoundaries: ZoomScaleBoundaries triggerScrollEvent(): void }> = ({ $contentOffsetX, $contentOffsetY, $zoomScale, imageFittedWithinScreen, level, levelDimensions, makeUrl, pyramid, tileSize, viewPortChanges, zoomScaleBoundaries, triggerScrollEvent, }) => { // Store the rendered JSX for the tiles in state, so that we can be very selective about when to trigger // re-rendering const [tiles, setTiles] = useState<JSX.Element[]>() // This is a tiny perf thing, but to help the react reconciler do less work, we cache the shallow JSX // for each tile const tileCache: { [url: string]: JSX.Element } = useMemo(() => ({}), []) // We use a 'fingerprint' of which rows and columns are currently being shown to decide whether to update // the `tiles` state. const lastFingerprint = useRef("") // Here we calculate the transform for the whole level. It's a hariy one, pay attention const transform = useMemo(() => { // in debug mode we ignore the controlling ScrollView so that it doesn't zoom or pan and you can see the whole pyramid at a glance const zoomScale = VISUAL_DEBUG_MODE ? 1 : $zoomScale const contentOffsetY = VISUAL_DEBUG_MODE ? -imageFittedWithinScreen.marginVertical : $contentOffsetY const contentOffsetX = VISUAL_DEBUG_MODE ? -imageFittedWithinScreen.marginHorizontal : $contentOffsetX // the first thing we want to do is place this level directly over the place where the base // image in the scroll view is (so, centered on screen when zoomScale === 1) // Most often this image is much bigger than the base image so it probably looks like this // to begin with: // +---------------+ // |--------------------------------------------+ // || | | // || | | // || | | // || | | // || | | // || | this level | // || | | // || | | // || | | // || | | // +--------------------------------------------+ // | | // | | // | phone screen | // | | // +---------------+ // but we want it to be like this // +---------------+ // | | // | | // | | // | | // | | // +---------------+ // || || // || this level || // || || // +---------------+ // | | // | | // | | // | phone screen | // | | // +---------------+ // and it turns out the easiest way to do that is by centering the original-sized image over // the place where it's meant to be, before scaling it down. // like this // +--------------+ // | | // | | // +----------------------------------+ // | | | | // | | | | // | | | | // | | | | // | | | | // | | | | // | | this level | | // | | | | // | | | | // | | | | // +----------------------------------+ // | | // | phone screen | // +--------------+ // so we do that by finding out where the top of the base image is // (remember the base image is rendered inside the scroll view so it's being zoomed and // panned and everything) const baseImageTop = Animated.multiply(contentOffsetY, -1) // and then we find it's center Y position const baseImageHeight = Animated.multiply(imageFittedWithinScreen.height, zoomScale) const baseImageCenterY = Animated.add(baseImageTop, Animated.divide(baseImageHeight, 2)) // and then we subtract half of the level height from that to get the top position of the // level at full resolution const levelPreScaleTop = Animated.subtract(baseImageCenterY, levelDimensions.height / 2) // then we do the same thing with left + width const baseImageLeft = Animated.multiply(contentOffsetX, -1) const baseImageWidth = Animated.multiply(imageFittedWithinScreen.width, zoomScale) const baseImageCenterX = Animated.add(baseImageLeft, Animated.divide(baseImageWidth, 2)) const levelPreScaleLeft = Animated.subtract(baseImageCenterX, levelDimensions.width / 2) // Then we need to find the scale to divide by const levelScale = levelDimensions.width / imageFittedWithinScreen.width // and then we want it to get bigger as the user zooms so we multiply that by the zoomScale const scale = Animated.divide(zoomScale, levelScale) return [ // position centered over base image { translateX: levelPreScaleLeft }, { translateY: levelPreScaleTop }, // scale it down { scale }, ] }, [levelDimensions, $contentOffsetX, $contentOffsetY, $zoomScale, imageFittedWithinScreen]) const screenDimensions = useScreenDimensions() const updateTiles = useCallback((viewPort: Rect) => { // first check whether we should even be showing any tiles at all on this level const zoomScale = screenDimensions.width / viewPort.width // we'll show tiles as long as the zoomScale start boundary has been breached. // this means the resolution of the last set of images is starting to get low enough // that it makes sense to bring the next higher-resolution level in to play. // we're ignoring the end boundary for now because it doesn't seem to help perf if (zoomScale < zoomScaleBoundaries.startZoomScale) { setTiles((arr) => { // if the array is already empty we want it to remain referentially identical so // react doesn't trigger a re-render. if (arr && arr.length === 0) { return arr } return [] }) lastFingerprint.current = "" return } const { minRow, minCol, maxRow, maxCol, numCols, numRows } = getVisibleRowsAndColumns({ imageFittedWithinScreen, levelDimensions, tileSize, viewPort, grow: 1, }) const fingerprint = `${minRow}:${minCol}:${maxRow}:${maxCol}` if (fingerprint === lastFingerprint.current) { return } lastFingerprint.current = fingerprint const result: JSX.Element[] = [] for (let row = minRow; row <= maxRow; row++) { for (let col = minCol; col <= maxCol; col++) { const url = makeUrl({ col, row }) if (!tileCache[url]) { const tileTop = row * tileSize const tileLeft = col * tileSize // the bottommost or rightmost tiles might not be exactly tileSize, so we need a special case const tileWidth = col < numCols - 1 ? tileSize : levelDimensions.width % tileSize const tileHeight = row < numRows - 1 ? tileSize : levelDimensions.height % tileSize tileCache[url] = ( <DeepZoomTile id={DeepZoomTileID.create(level, row, col)} pyramid={pyramid} key={url} url={url} top={tileTop} left={tileLeft} width={tileWidth} height={tileHeight} /> ) } result.push(tileCache[url]) } } setTiles(result) }, []) // TODO: find a reliable way to throttle this based on whether or not react has finished reconciling. // React doesn't have a way to drop frames so if we limit this to 10fps but a frame takes a whole second // to reconcile for some reason, then there's a 9-frame backlag of useless frames to render // (the user was probably panning and zooming to a different place during that one second) // I tried a few ways of doing this with hooks but couldn't figure out something 100% reliable. const throttledUpdateTiles = useMemo(() => throttle(updateTiles, 100, { trailing: true }), []) useEvents(viewPortChanges, throttledUpdateTiles) // trigger a scroll event on mount to make sure the initial tiles (if any) are displayed useEffect(() => { triggerScrollEvent() }, []) return ( <Animated.View style={{ position: "absolute", ...levelDimensions, transform, }} > {tiles} </Animated.View> ) }
the_stack
import { Pagination } from '@alfresco/js-api'; import { Injectable } from '@angular/core'; import { Observable, of } from 'rxjs'; import { map, switchMap } from 'rxjs/operators'; import { AppConfigService } from '../app-config/app-config.service'; import { IdentityGroupModel } from '../models/identity-group.model'; import { IdentityRoleModel } from '../models/identity-role.model'; import { IdentityUserModel } from '../models/identity-user.model'; import { JwtHelperService } from './jwt-helper.service'; import { OAuth2Service } from './oauth2.service'; export interface IdentityUserQueryResponse { entries: IdentityUserModel[]; pagination: Pagination; } export interface IdentityUserPasswordModel { type?: string; value?: string; temporary?: boolean; } export interface IdentityUserQueryCloudRequestModel { first: number; max: number; } export interface IdentityJoinGroupRequestModel { realm: string; userId: string; groupId: string; } @Injectable({ providedIn: 'root' }) export class IdentityUserService { constructor( private jwtHelperService: JwtHelperService, private oAuth2Service: OAuth2Service, private appConfigService: AppConfigService) { } private get identityHost(): string { return `${this.appConfigService.get('identityHost')}`; } private buildUserUrl(): string { return `${this.identityHost}/users`; } /** * Gets the name and other basic details of the current user. * @returns The user's details */ getCurrentUserInfo(): IdentityUserModel { const familyName = this.jwtHelperService.getValueFromLocalAccessToken<string>(JwtHelperService.FAMILY_NAME); const givenName = this.jwtHelperService.getValueFromLocalAccessToken<string>(JwtHelperService.GIVEN_NAME); const email = this.jwtHelperService.getValueFromLocalAccessToken<string>(JwtHelperService.USER_EMAIL); const username = this.jwtHelperService.getValueFromLocalAccessToken<string>(JwtHelperService.USER_PREFERRED_USERNAME); return { firstName: givenName, lastName: familyName, email: email, username: username }; } /** * Find users based on search input. * @param search Search query string * @returns List of users */ findUsersByName(search: string): Observable<IdentityUserModel[]> { if (search === '') { return of([]); } const url = this.buildUserUrl(); const queryParams = { search: search }; return this.oAuth2Service.get({ url, queryParams }); } /** * Find users based on username input. * @param username Search query string * @returns List of users */ findUserByUsername(username: string): Observable<IdentityUserModel[]> { if (username === '') { return of([]); } const url = this.buildUserUrl(); const queryParams = { username: username }; return this.oAuth2Service.get({url, queryParams }); } /** * Find users based on email input. * @param email Search query string * @returns List of users */ findUserByEmail(email: string): Observable<IdentityUserModel[]> { if (email === '') { return of([]); } const url = this.buildUserUrl(); const queryParams = { email: email }; return this.oAuth2Service.get({ url, queryParams }); } /** * Find users based on id input. * @param id Search query string * @returns users object */ findUserById(id: string): Observable<any> { if (id === '') { return of([]); } const url = this.buildUserUrl() + '/' + id; return this.oAuth2Service.get({ url }); } /** * Get client roles of a user for a particular client. * @param userId ID of the target user * @param clientId ID of the client app * @returns List of client roles */ getClientRoles(userId: string, clientId: string): Observable<any[]> { const url = `${this.identityHost}/users/${userId}/role-mappings/clients/${clientId}/composite`; return this.oAuth2Service.get({ url }); } /** * Checks whether user has access to a client app. * @param userId ID of the target user * @param clientId ID of the client app * @returns True if the user has access, false otherwise */ checkUserHasClientApp(userId: string, clientId: string): Observable<boolean> { return this.getClientRoles(userId, clientId).pipe( map((clientRoles) => clientRoles.length > 0) ); } /** * Checks whether a user has any of the client app roles. * @param userId ID of the target user * @param clientId ID of the client app * @param roleNames List of role names to check for * @returns True if the user has one or more of the roles, false otherwise */ checkUserHasAnyClientAppRole(userId: string, clientId: string, roleNames: string[]): Observable<boolean> { return this.getClientRoles(userId, clientId).pipe( map((clientRoles: any[]) => { let hasRole = false; if (clientRoles.length > 0) { roleNames.forEach((roleName) => { const role = clientRoles.find(({ name }) => name === roleName); if (role) { hasRole = true; return; } }); } return hasRole; }) ); } /** * Gets the client ID for an application. * @param applicationName Name of the application * @returns Client ID string */ getClientIdByApplicationName(applicationName: string): Observable<string> { const url = `${this.identityHost}/clients`; const queryParams = { clientId: applicationName }; return this.oAuth2Service .get<any[]>({url, queryParams }) .pipe( map((response) => response && response.length > 0 ? response[0].id : '') ); } /** * Checks if a user has access to an application. * @param userId ID of the user * @param applicationName Name of the application * @returns True if the user has access, false otherwise */ checkUserHasApplicationAccess(userId: string, applicationName: string): Observable<boolean> { return this.getClientIdByApplicationName(applicationName).pipe( switchMap((clientId: string) => { return this.checkUserHasClientApp(userId, clientId); }) ); } /** * Checks if a user has any application role. * @param userId ID of the target user * @param applicationName Name of the application * @param roleNames List of role names to check for * @returns True if the user has one or more of the roles, false otherwise */ checkUserHasAnyApplicationRole(userId: string, applicationName: string, roleNames: string[]): Observable<boolean> { return this.getClientIdByApplicationName(applicationName).pipe( switchMap((clientId: string) => { return this.checkUserHasAnyClientAppRole(userId, clientId, roleNames); }) ); } /** * Gets details for all users. * @returns Array of user info objects */ getUsers(): Observable<IdentityUserModel[]> { const url = this.buildUserUrl(); return this.oAuth2Service.get({ url }); } /** * Gets a list of roles for a user. * @param userId ID of the user * @returns Array of role info objects */ getUserRoles(userId: string): Observable<IdentityRoleModel[]> { const url = `${this.identityHost}/users/${userId}/role-mappings/realm/composite`; return this.oAuth2Service.get({ url }); } /** * Gets an array of users (including the current user) who have any of the roles in the supplied list. * @param roleNames List of role names to look for * @returns Array of user info objects */ async getUsersByRolesWithCurrentUser(roleNames: string[]): Promise<IdentityUserModel[]> { const filteredUsers: IdentityUserModel[] = []; if (roleNames && roleNames.length > 0) { const users = await this.getUsers().toPromise(); for (let i = 0; i < users.length; i++) { const hasAnyRole = await this.userHasAnyRole(users[i].id, roleNames); if (hasAnyRole) { filteredUsers.push(users[i]); } } } return filteredUsers; } /** * Gets an array of users (not including the current user) who have any of the roles in the supplied list. * @param roleNames List of role names to look for * @returns Array of user info objects */ async getUsersByRolesWithoutCurrentUser(roleNames: string[]): Promise<IdentityUserModel[]> { const filteredUsers: IdentityUserModel[] = []; if (roleNames && roleNames.length > 0) { const currentUser = this.getCurrentUserInfo(); let users = await this.getUsers().toPromise(); users = users.filter(({ username }) => username !== currentUser.username); for (let i = 0; i < users.length; i++) { const hasAnyRole = await this.userHasAnyRole(users[i].id, roleNames); if (hasAnyRole) { filteredUsers.push(users[i]); } } } return filteredUsers; } private async userHasAnyRole(userId: string, roleNames: string[]): Promise<boolean> { const userRoles = await this.getUserRoles(userId).toPromise(); const hasAnyRole = roleNames.some((roleName) => { const filteredRoles = userRoles.filter((userRole) => { return userRole.name.toLocaleLowerCase() === roleName.toLocaleLowerCase(); }); return filteredRoles.length > 0; }); return hasAnyRole; } /** * Checks if a user has one of the roles from a list. * @param userId ID of the target user * @param roleNames Array of roles to check for * @returns True if the user has one of the roles, false otherwise */ checkUserHasRole(userId: string, roleNames: string[]): Observable<boolean> { return this.getUserRoles(userId).pipe(map((userRoles: IdentityRoleModel[]) => { let hasRole = false; if (userRoles && userRoles.length > 0) { roleNames.forEach((roleName: string) => { const role = userRoles.find(({ name }) => roleName === name); if (role) { hasRole = true; return; } }); } return hasRole; })); } /** * Gets details for all users. * @returns Array of user information objects. */ queryUsers(requestQuery: IdentityUserQueryCloudRequestModel): Observable<IdentityUserQueryResponse> { const url = this.buildUserUrl(); const queryParams = { first: requestQuery.first, max: requestQuery.max }; return this.getTotalUsersCount().pipe( switchMap((totalCount) => this.oAuth2Service.get<IdentityUserModel[]>({ url, queryParams }).pipe( map((response) => { return <IdentityUserQueryResponse> { entries: response, pagination: { skipCount: requestQuery.first, maxItems: requestQuery.max, count: totalCount, hasMoreItems: false, totalItems: totalCount } }; }) ) ) ); } /** * Gets users total count. * @returns Number of users count. */ getTotalUsersCount(): Observable<number> { const url = this.buildUserUrl() + `/count`; return this.oAuth2Service.get({ url }); } /** * Creates new user. * @param newUser Object containing the new user details. * @returns Empty response when the user created. */ createUser(newUser: IdentityUserModel): Observable<any> { const url = this.buildUserUrl(); const bodyParam = JSON.stringify(newUser); return this.oAuth2Service.post({ url, bodyParam }); } /** * Updates user details. * @param userId Id of the user. * @param updatedUser Object containing the user details. * @returns Empty response when the user updated. */ updateUser(userId: string, updatedUser: IdentityUserModel): Observable<any> { const url = this.buildUserUrl() + '/' + userId; const bodyParam = JSON.stringify(updatedUser); return this.oAuth2Service.put({ url, bodyParam }); } /** * Deletes User. * @param userId Id of the user. * @returns Empty response when the user deleted. */ deleteUser(userId: string): Observable<any> { const url = this.buildUserUrl() + '/' + userId; return this.oAuth2Service.delete({ url }); } /** * Changes user password. * @param userId Id of the user. * @param credentials Details of user Credentials. * @returns Empty response when the password changed. */ changePassword(userId: string, newPassword: IdentityUserPasswordModel): Observable<any> { const url = this.buildUserUrl() + '/' + userId + '/reset-password'; const bodyParam = JSON.stringify(newPassword); return this.oAuth2Service.put({ url, bodyParam }); } /** * Gets involved groups. * @param userId Id of the user. * @returns Array of involved groups information objects. */ getInvolvedGroups(userId: string): Observable<IdentityGroupModel[]> { const url = this.buildUserUrl() + '/' + userId + '/groups/'; const pathParams = { id: userId }; return this.oAuth2Service.get({ url, pathParams }); } /** * Joins group. * @param joinGroupRequest Details of join group request (IdentityJoinGroupRequestModel). * @returns Empty response when the user joined the group. */ joinGroup(joinGroupRequest: IdentityJoinGroupRequestModel): Observable<any> { const url = this.buildUserUrl() + '/' + joinGroupRequest.userId + '/groups/' + joinGroupRequest.groupId; const bodyParam = JSON.stringify(joinGroupRequest); return this.oAuth2Service.put({ url, bodyParam }); } /** * Leaves group. * @param userId Id of the user. * @param groupId Id of the group. * @returns Empty response when the user left the group. */ leaveGroup(userId: any, groupId: string): Observable<any> { const url = this.buildUserUrl() + '/' + userId + '/groups/' + groupId; return this.oAuth2Service.delete({ url }); } /** * Gets available roles * @param userId Id of the user. * @returns Array of available roles information objects */ getAvailableRoles(userId: string): Observable<IdentityRoleModel[]> { const url = this.buildUserUrl() + '/' + userId + '/role-mappings/realm/available'; return this.oAuth2Service.get({ url }); } /** * Gets assigned roles. * @param userId Id of the user. * @returns Array of assigned roles information objects */ getAssignedRoles(userId: string): Observable<IdentityRoleModel[]> { const url = this.buildUserUrl() + '/' + userId + '/role-mappings/realm'; const pathParams = { id: userId }; return this.oAuth2Service.get({ url, pathParams }); } /** * Gets effective roles. * @param userId Id of the user. * @returns Array of composite roles information objects */ getEffectiveRoles(userId: string): Observable<IdentityRoleModel[]> { const url = this.buildUserUrl() + '/' + userId + '/role-mappings/realm/composite'; const pathParams = { id: userId }; return this.oAuth2Service.get({ url, pathParams }); } /** * Assigns roles to the user. * @param userId Id of the user. * @param roles Array of roles. * @returns Empty response when the role assigned. */ assignRoles(userId: string, roles: IdentityRoleModel[]): Observable<any> { const url = this.buildUserUrl() + '/' + userId + '/role-mappings/realm'; const bodyParam = JSON.stringify(roles); return this.oAuth2Service.post({ url, bodyParam }); } /** * Removes assigned roles. * @param userId Id of the user. * @param roles Array of roles. * @returns Empty response when the role removed. */ removeRoles(userId: string, removedRoles: IdentityRoleModel[]): Observable<any> { const url = this.buildUserUrl() + '/' + userId + '/role-mappings/realm'; const bodyParam = JSON.stringify(removedRoles); return this.oAuth2Service.delete({ url, bodyParam }); } }
the_stack
import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { IconProp } from '@fortawesome/fontawesome-svg-core'; import { ProfileService } from 'app/shared/layouts/profiles/profile.service'; @Component({ selector: 'jhi-feature-overview', templateUrl: './feature-overview.component.html', styleUrls: ['./feature-overview.scss'], }) export class FeatureOverviewComponent implements OnInit { features: Feature[]; targetAudience = TargetAudience.INSTRUCTORS; constructor(private route: ActivatedRoute, private profileService: ProfileService) {} /** * Initialises the feature overview page either for students or for instructors, depending on the url. * Sets up the features to be displayed */ ngOnInit(): void { if (this.route.snapshot.url[0]?.toString() === 'students') { this.targetAudience = TargetAudience.STUDENTS; } if (this.targetAudience === TargetAudience.INSTRUCTORS) { this.setupInstructorFeatures(); } else { this.setupStudentFeatures(); } } private setupStudentFeatures() { // set up student features const featurelocalIDE = new Feature( 'featureOverview.students.feature.localIDE.title', 'featureOverview.students.feature.localIDE.shortDescription', 'featureOverview.students.feature.localIDE.descriptionTextOne', 'code-branch', undefined, '/content/images/feature-overview/students/clone_repository.png', ); featurelocalIDE.centerTextAndImageOne(); const featureCodeEditor = new Feature( 'featureOverview.students.feature.codeEditor.title', 'featureOverview.students.feature.codeEditor.shortDescription', 'featureOverview.students.feature.codeEditor.descriptionTextOne', 'code', undefined, '/content/images/feature-overview/students/code_editor.png', ); const featureTextEditor = new Feature( 'featureOverview.students.feature.textEditor.title', 'featureOverview.students.feature.textEditor.shortDescription', 'featureOverview.students.feature.textEditor.descriptionTextOne', 'file', undefined, '/content/images/feature-overview/students/text_editor.png', ); featureTextEditor.centerTextAndImageOne(); const featureApollonEditor = new Feature( 'featureOverview.students.feature.apollonEditor.title', 'featureOverview.students.feature.apollonEditor.shortDescription', 'featureOverview.students.feature.apollonEditor.descriptionTextOne', 'object-group', undefined, '/content/images/feature-overview/students/modeling_editor.png', ); const featureQuizExercises = new Feature( 'featureOverview.students.feature.quizExercises.title', 'featureOverview.students.feature.quizExercises.shortDescription', 'featureOverview.students.feature.quizExercises.descriptionTextOne', 'check-square', undefined, '/content/images/feature-overview/students/quiz_exercises.png', ); featureQuizExercises.alignFirstImageLeft(); const featureLogin = new Feature( 'featureOverview.students.feature.login.title', 'featureOverview.students.feature.login.shortDescription', 'featureOverview.students.feature.login.descriptionTextOne', 'sign-in-alt', undefined, '/content/images/feature-overview/students/login.png', ); featureLogin.centerAndShrinkImage(); const featureUserInterface = new Feature( 'featureOverview.students.feature.userInterface.title', 'featureOverview.students.feature.userInterface.shortDescription', 'featureOverview.students.feature.userInterface.descriptionTextOne', 'puzzle-piece', 'featureOverview.students.feature.userInterface.descriptionTextTwo', '/content/images/feature-overview/students/user_interface.png', ); const featureConduction = new Feature( 'featureOverview.students.feature.conduction.title', 'featureOverview.students.feature.conduction.shortDescription', 'featureOverview.students.feature.conduction.descriptionTextOne', 'play', undefined, '/content/images/feature-overview/students/online_exams.png', ); featureConduction.centerAndExpandImage(); const featureOffline = new Feature( 'featureOverview.students.feature.offline.title', 'featureOverview.students.feature.offline.shortDescription', 'featureOverview.students.feature.offline.descriptionTextOne', 'signal', ); const featureSummary = new Feature( 'featureOverview.students.feature.summary.title', 'featureOverview.students.feature.summary.shortDescription', 'featureOverview.students.feature.summary.descriptionTextOne', 'th-list', undefined, '/content/images/feature-overview/students/summary.png', ); const featureQualityAndFair = new Feature( 'featureOverview.students.feature.qualityAndFair.title', 'featureOverview.students.feature.qualityAndFair.shortDescription', 'featureOverview.students.feature.qualityAndFair.descriptionTextOne', 'eye', ); const featureOnlineReview = new Feature( 'featureOverview.students.feature.onlineReview.title', 'featureOverview.students.feature.onlineReview.shortDescription', 'featureOverview.students.feature.onlineReview.descriptionTextOne', 'comment', undefined, '/content/images/feature-overview/students/complaint.png', ); this.features = [ featureConduction, featureOffline, featureUserInterface, featureCodeEditor, featurelocalIDE, featureApollonEditor, featureTextEditor, featureQuizExercises, featureSummary, featureQualityAndFair, featureOnlineReview, ]; // only add login feature for tum accounts this.profileService.getProfileInfo().subscribe((profileInfo) => { if (profileInfo) { const accountName = profileInfo.accountName; if (accountName === 'TUM') { this.features.push(featureLogin); } } }); } private setupInstructorFeatures() { // Set up instructor features const featureCreateConductAssess = new Feature( 'featureOverview.instructor.feature.createConductAssess.title', 'featureOverview.instructor.feature.createConductAssess.shortDescription', 'featureOverview.instructor.feature.createConductAssess.descriptionTextOne', 'cubes', undefined, '/content/images/feature-overview/instructors/create_conduct_assess.png', ); featureCreateConductAssess.centerAndExpandImage(); const featureConfiguration = new Feature( 'featureOverview.instructor.feature.configuration.title', 'featureOverview.instructor.feature.configuration.shortDescription', 'featureOverview.instructor.feature.configuration.descriptionTextOne', 'cogs', undefined, '/content/images/feature-overview/instructors/import_students.png', '/content/images/feature-overview/instructors/fully_configurable.png', ); const featureExerciseTypes = new Feature( 'featureOverview.instructor.feature.exerciseTypes.title', 'featureOverview.instructor.feature.exerciseTypes.shortDescription', 'featureOverview.instructor.feature.exerciseTypes.descriptionTextOne', 'tasks', undefined, '/content/images/feature-overview/instructors/multiple_exercises.png', ); featureExerciseTypes.alignFirstImageLeft(); const featureExerciseVariants = new Feature( 'featureOverview.instructor.feature.exerciseVariants.title', 'featureOverview.instructor.feature.exerciseVariants.shortDescription', 'featureOverview.instructor.feature.exerciseVariants.descriptionTextOne', 'copy', undefined, '/content/images/feature-overview/instructors/exercise_variants.png', ); featureExerciseVariants.centerTextAndImageOne(); const featureTestRuns = new Feature( 'featureOverview.instructor.feature.testRunConduction.title', 'featureOverview.instructor.feature.testRunConduction.shortDescription', 'featureOverview.instructor.feature.testRunConduction.descriptionTextOne', 'pencil-alt', undefined, ); const featureSessionMonitoring = new Feature( 'featureOverview.instructor.feature.sessionMonitoring.title', 'featureOverview.instructor.feature.sessionMonitoring.shortDescription', 'featureOverview.instructor.feature.sessionMonitoring.descriptionTextOne', 'hdd', ); const featurePlagiarismDetection = new Feature( 'featureOverview.instructor.feature.plagiarismDetection.title', 'featureOverview.instructor.feature.plagiarismDetection.shortDescription', 'featureOverview.instructor.feature.plagiarismDetection.descriptionTextOne', 'user-secret', undefined, '/content/images/feature-overview/instructors/plagiarism.png', ); const featureAnonymousAssessment = new Feature( 'featureOverview.instructor.feature.anonymousAssessment.title', 'featureOverview.instructor.feature.anonymousAssessment.shortDescription', 'featureOverview.instructor.feature.anonymousAssessment.descriptionTextOne', 'shield-alt', undefined, '/content/images/feature-overview/instructors/anonymous_assessment.png', ); const featureAutomaticAssessment = new Feature( 'featureOverview.instructor.feature.automaticAssessment.title', 'featureOverview.instructor.feature.automaticAssessment.shortDescription', 'featureOverview.instructor.feature.automaticAssessment.descriptionTextOne', 'magic', ); const featureReviewIndividualExams = new Feature( 'featureOverview.instructor.feature.reviewIndividualExams.title', 'featureOverview.instructor.feature.reviewIndividualExams.shortDescription', 'featureOverview.instructor.feature.reviewIndividualExams.descriptionTextOne', 'search-plus', undefined, '/content/images/feature-overview/instructors/student_exams.png', ); const featureAssessmentMonitoring = new Feature( 'featureOverview.instructor.feature.assessmentMonitoring.title', 'featureOverview.instructor.feature.assessmentMonitoring.shortDescription', 'featureOverview.instructor.feature.assessmentMonitoring.descriptionTextOne', 'microchip', undefined, '/content/images/feature-overview/instructors/progress_monitoring.png', ); featureAssessmentMonitoring.alignFirstImageLeft(); const featureComplaints = new Feature( 'featureOverview.instructor.feature.complaints.title', 'featureOverview.instructor.feature.complaints.shortDescription', 'featureOverview.instructor.feature.complaints.descriptionTextOne', 'question', undefined, '/content/images/feature-overview/instructors/complaint_response.png', ); featureComplaints.alignFirstImageLeft(); const featureStatistics = new Feature( 'featureOverview.instructor.feature.statistics.title', 'featureOverview.instructor.feature.statistics.shortDescription', 'featureOverview.instructor.feature.statistics.descriptionTextOne', 'chart-pie', undefined, '/content/images/feature-overview/instructors/exam_statistics.png', ); this.features = [ featureCreateConductAssess, featureConfiguration, featureExerciseTypes, featureExerciseVariants, featureTestRuns, featureSessionMonitoring, featurePlagiarismDetection, featureAnonymousAssessment, featureAutomaticAssessment, featureReviewIndividualExams, featureAssessmentMonitoring, featureComplaints, featureStatistics, ]; } navigateToFeature(featureId: string): void { // get html element for feature const element = document.getElementById('feature' + featureId); if (element) { // scroll to correct y const y = element.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({ top: y, behavior: 'smooth' }); } } } export enum TargetAudience { INSTRUCTORS = 'instructor', STUDENTS = 'students', } class Feature { title: string; shortDescription: string; descriptionTextOne: string; centered = false; expandedImage = false; shrunkImage = false; descriptionTextTwo?: string; imageOne?: string; imageTwo?: string; firstImageLeft = false; icon: IconProp; id: string; constructor(title: string, shortDescription: string, descriptionTextOne: string, icon: IconProp, descriptionTextTwo?: string, imageOne?: string, imageTwo?: string) { this.title = title; this.shortDescription = shortDescription; this.descriptionTextOne = descriptionTextOne; this.descriptionTextTwo = descriptionTextTwo; this.imageOne = imageOne; this.imageTwo = imageTwo; this.icon = icon; this.id = this.setId(); } /** * Math.random should be unique because of its seeding algorithm. * Convert it to base 36 (numbers + letters), and grab the first 9 characters after the decimal. * @private */ setId(): string { return '_' + Math.random().toString(36).substr(2, 9); } /** * Centers the text and first image. * Note: Only has an effect if there is no second text */ centerTextAndImageOne(): void { this.centered = true; } /** * Centers the text and first image. * Additionally it makes the first image larger. Use for big images which need more space. * Note: Only has an effect if there is no second text */ centerAndExpandImage(): void { this.centered = true; this.expandedImage = true; } /** * Centers the text and first image. * Additionally it makes the first image smaller. Use for low resolution images. * Note: Only has an effect if there is no second text */ centerAndShrinkImage(): void { this.centered = true; this.shrunkImage = true; } /** * Align the first image to the left, instead of the right */ alignFirstImageLeft() { this.firstImageLeft = true; } }
the_stack
import {h} from 'maquette'; import * as Langs from '../definitions/languages'; import * as Graph from '../definitions/graph'; import * as Values from '../definitions/values'; import {createOutputPreview, createMonacoEditor} from '../editors/editor'; // import Plotly from 'Plotly'; import ts from 'typescript'; import axios from 'axios'; import {Md5} from 'ts-md5'; import {AsyncLazy} from '../common/lazy'; import * as Doc from '../services/documentService'; import { Log } from '../common/log'; export class JavascriptBlockKind implements Langs.Block { language : string; source : string; constructor(source:string) { this.language = "javascript"; this.source = source; } } export interface JavascriptSwitchTabEvent { kind: "switchtab" index: number } export type JavascriptEvent = JavascriptSwitchTabEvent export type JavascriptState = { id: number block: JavascriptBlockKind tabID: number } async function getCachedOrEval(body, context:Langs.EvaluationContext, datastoreURI:string, argDictionary) : Promise<any> { let cacheUrl = datastoreURI.concat("/" + body.hash).concat("/.cached") try { let params = {headers: {'Accept': 'application/json'}} Log.trace("js", "Checking cached response: %s", cacheUrl) let response = await axios.get(cacheUrl, params) return {values: response.data, outputs: undefined} } catch(e) { Log.trace("js", "Checking failed at JS, calling eval (%s)", e) var addOutput = function(f) { outputs.push(f) } var outputs : ((id:string) => void)[] = []; let values : { (key:string) : any[] } = eval(body.code)(context, addOutput, argDictionary); return {values: values, outputs: outputs} } } async function getCodeResourcesAndExports(context:Langs.BindingContext, source: string, datastoreURI:string): Promise<Langs.BindingResult> { let language = "javascript" let regex_global:RegExp = /^\x2F\x2Fglobal/; let regex_local:RegExp = /^\x2F\x2Flocal/; let newResources : Array<Langs.Resource> = [] function resourceExists(fileName):boolean{ for (let r = 0; r < context.resources.length; r++) { if (context.resources[r].fileName == fileName) return true } return false } async function putResource(fileName:string, code: string, datastoreURI:string) : Promise<string> { let hash = Md5.hashStr(fileName) try { let url = datastoreURI.concat("/"+hash).concat("/"+fileName) // let url = "http://wrattler_wrattler_data_store_1:7102" let headers = {'Content-Type': 'text/html'} var response = await axios.put(url, code, {headers: headers}); return url // return "http://wrattler_wrattler_data_store_1:7102".concat("/"+hash).concat("/"+variableName) } catch (error) { throw error; } } let src = source.replace(/\r/g,'\n') let srcArray = src.split('\n') let strippedSrc = '' for (let l = 0; l < srcArray.length && l < 5; l++) Log.trace("functions", "srcArray[%d/%d]: %s", l, srcArray.length, JSON.stringify(srcArray[l])); for (let l = 0; l < srcArray.length; l++) { if ((srcArray[l].match(regex_global))||(srcArray[l].match(regex_local))){ let scope : "global" | "local" = srcArray[l].match(regex_global) ? 'global' : 'local' let resourceName = srcArray[l].split(' ')[1] Log.trace("functions", "Resource Name: %s", JSON.stringify(resourceName)) if (!resourceExists(resourceName)) { let response = await Doc.getResourceContent(context.resourceServerUrl, resourceName) let newResource:Langs.Resource = {fileName:resourceName, language:language, scope: scope, url:await putResource(resourceName, response, datastoreURI) } newResources.push(newResource) } } else { strippedSrc = strippedSrc.concat(srcArray[l]).concat('\n') } } let tsSourceFile = ts.createSourceFile( __filename, strippedSrc, ts.ScriptTarget.Latest ); let antecedents : Graph.Node[] = [] function addAntedents(expr:ts.Node) { ts.forEachChild(expr, function(child) { switch(child.kind) { case ts.SyntaxKind.Identifier: // REVIEW: As above, 'escapedText' is actually '__String' which might cause problems let argumentName = <string>(<ts.Identifier>child).escapedText; // if (argumentName in context.scope) { // let antecedentNode = context.scope[argumentName] // if (antecedents.indexOf(antecedentNode) == -1) // antecedents.push(antecedentNode); // } if (argumentName in context.scope) { let antecedentNode = context.scope[argumentName] if (antecedentNode.language != undefined && antecedents.indexOf(antecedentNode) == -1) antecedents.push(antecedentNode); } break; } addAntedents(child) }) } addAntedents(tsSourceFile) let allHash = Md5.hashStr(antecedents.map(a => a.hash).join("-") + source) let initialNode:Graph.JsCodeNode = { language:"javascript", antecedents:antecedents, exportedVariables:[], kind: 'code', hash: <string>allHash, value: null, source: source, errors: [] } let cachedNode = <Graph.JsCodeNode>context.cache.tryFindNode(initialNode) let dependencies:Graph.JsExportNode[] = []; function addExports(expr:ts.Node) { ts.forEachChild(expr, function(child) { switch(child.kind) { case ts.SyntaxKind.VariableStatement: let decl = (<ts.VariableStatement>child).declarationList.declarations[0].name // REVIEW: This could fail if 'decl' is 'BindingPattern' and not 'Identifier' // REVIEW: Also, TypeScript uses some strange '__String' that might not be valid 'string' let name = <string>(<ts.Identifier>decl).escapedText let exportNode:Graph.JsExportNode = { variableName: name, value: null, hash: <string>Md5.hashStr(allHash + name), language:"javascript", code: cachedNode, kind: 'export', antecedents:[cachedNode], errors:[] }; let cachedExportNode = <Graph.JsExportNode>context.cache.tryFindNode(exportNode) dependencies.push(cachedExportNode); cachedNode.exportedVariables.push(cachedExportNode.variableName); break; } addExports(child) }) } addExports(tsSourceFile) return {code: cachedNode, exports: dependencies, resources: newResources}; } export const javascriptEditor : Langs.Editor<JavascriptState, JavascriptEvent> = { initialize: (id:number, block:Langs.Block) => { return { id: id, block: <JavascriptBlockKind>block, tabID:0} }, update: (state:JavascriptState, event:JavascriptEvent) => { switch(event.kind) { case 'switchtab': { return { id: state.id, block: state.block, tabID: event.index } } } return state }, render: (cell: Langs.BlockState, state:JavascriptState, context:Langs.EditorContext<JavascriptEvent>) => { let previewButton = h('button', { class:'preview-button', onclick:() => { Log.trace("editor", "Evaluate button clicked in external language plugin") context.evaluate(cell.editor.id) } }, ["Evaluate!"] ) let spinner = h('i', {id:'cellSpinner_'+cell.editor.id, class: 'fa fa-spinner fa-spin' }, []) let triggerSelect = (t:number) => context.trigger({kind:'switchtab', index: t}) let preview = h('div', {class:'preview'}, [(cell.code.value==undefined) ? (cell.evaluationState=='pending')?spinner:previewButton : (createOutputPreview(cell, triggerSelect, state.tabID, <Values.ExportsValue>cell.code.value))]); let code = createMonacoEditor("javascript", state.block.source, cell, context) return h('div', { }, [code, preview]) } } export class JavascriptLanguagePlugin implements Langs.LanguagePlugin { readonly language: string readonly iconClassName: string readonly editor: Langs.Editor<JavascriptState, JavascriptEvent> readonly datastoreURI:string constructor(datastoreURI:string) { this.language = "javascript" this.iconClassName= "fab fa-js-square" this.editor= javascriptEditor this.datastoreURI = datastoreURI } getDefaultCode(id:number):string { return "// This is a javascript cell. \n//var js" + id + " = [{'id':" + id + ", 'language':'javascript'}]" } async evaluate(context:Langs.EvaluationContext, node:Graph.Node) : Promise<Langs.EvaluationResult> { let jsnode = <Graph.JsNode>node let regex_global:RegExp = /^\x2F\x2Fglobal/; let regex_local:RegExp = /^\x2F\x2Flocal/; async function putValue(variableName, hash, value, datastoreURI) : Promise<string> { let url = datastoreURI.concat("/"+hash).concat("/"+variableName) let headers = {'Content-Type': 'application/json'} try { var response = await axios.put(url, value, {headers: headers}); return datastoreURI.concat("/"+hash).concat("/"+variableName) // return "http://wrattler_wrattler_data_store_1:7102".concat("/"+hash).concat("/"+variableName) } catch (error) { console.error(error); throw error } } async function putValues(values:{ (key:string) : any[] }, datastoreURI) : Promise<Values.ExportsValue> { try { var results : Values.ExportsValue = { kind:"exports", exports:{} } for (let value in values) { let df = values[value]; // Only attempt to store things that look like array of objects (this check may still fail though..) if ((df != undefined) && Array.isArray(df) && (df.length == 0 || typeof(df[0]) =="object")) { let dfString = JSON.stringify(values[value]) let hash = Md5.hashStr(dfString) let df_url = await putValue(value, hash, dfString, datastoreURI) var exp : Values.DataFrame = { kind:"dataframe", url: df_url, data: new AsyncLazy(async () => values[value]), preview:values[value].slice(0, 10) } results.exports[value] = exp } } return results; } catch (error) { console.error(error); throw error } } switch(jsnode.kind) { case 'code': let returnArgs = "var __res = {};\n"; let evalCode = ""; let jsCodeNode = <Graph.JsCodeNode>node for (var e = 0; e < jsCodeNode.exportedVariables.length; e++) { var v = jsCodeNode.exportedVariables[e]; returnArgs = returnArgs.concat("if (typeof(VAR)!='undefined') __res.VAR = VAR;\n".replace(/VAR/g, v)); } returnArgs = returnArgs.concat("return __res;") let importedVars = ""; var argDictionary:{[key: string]: any} = {} for (var i = 0; i < jsCodeNode.antecedents.length; i++) { let imported = <Graph.ExportNode>jsCodeNode.antecedents[i] if ((<Values.DataFrame>imported.value) != null) { argDictionary[imported.variableName] = await (<Values.DataFrame>imported.value).data.getValue(); importedVars = importedVars.concat("\nlet "+imported.variableName + " = args[\""+imported.variableName+"\"];"); } } let srcArray = jsCodeNode.source.split('\n') let strippedSrc = '' let importedFiles : Array<string> = []; for (let l = 0; l < srcArray.length; l++) { if (srcArray[l].match(regex_local)) { let resourceName = srcArray[l].split(' ')[1] importedFiles.push(resourceName) } else if (srcArray[l].match(regex_global)){ } else { strippedSrc = strippedSrc.concat(srcArray[l]).concat('\n') } } for (let r = 0; r < context.resources.length; r++) { if ((context.resources[r].scope == 'global')&&(context.resources[r].language == 'javascript')) { importedFiles.push(context.resources[r].fileName) } } let importedResourceContent:string = '' for (let f = 0; f < importedFiles.length; f++) { importedResourceContent=importedResourceContent.concat(await Doc.getResourceContent(context.resourceServerUrl, importedFiles[f])).concat("\n") } evalCode = "(function f(context, addOutput, args) {\n\t " + importedVars + "\n" + importedResourceContent + "\n" + strippedSrc + "\n" + returnArgs + "\n" + "})" let body = {"code": evalCode, "hash": jsnode.hash, "files" : importedFiles, "frames": importedVars} let response : {values:{ (key:string) : any[] }, outputs: any} = await getCachedOrEval(body, context, this.datastoreURI, argDictionary) let exports = await putValues(response.values, this.datastoreURI) for(let i = 0; i < response.outputs.length; i++) { var exp : Values.JavaScriptOutputValue = { kind:"jsoutput", render: response.outputs[i] } exports.exports["output" + i] = exp } return {kind: 'success', value: exports} case 'export': let jsExportNode = <Graph.JsExportNode>node let exportNodeName= jsExportNode.variableName let exportsValue = <Values.ExportsValue>jsExportNode.code.value // return exportsValue.exports[exportNodeName] return {kind: 'success', value: exportsValue.exports[exportNodeName]} } } parse (code:string): JavascriptBlockKind{ return new JavascriptBlockKind(code); } async bind (context:Langs.BindingContext, block: Langs.Block):Promise<Langs.BindingResult> { let jsBlock = <JavascriptBlockKind>block return getCodeResourcesAndExports(context, jsBlock.source, this.datastoreURI); } save (block:Langs.Block) : string { let jsBlock:JavascriptBlockKind = <JavascriptBlockKind> block let content:string = "" content = content .concat("```javascript\n") .concat(jsBlock.source) .concat("\n") .concat("```\n") return content } }
the_stack
* @module Editing */ import { CompressedId64Set, Id64String, IModelStatus } from "@itwin/core-bentley"; import { Matrix3dProps, Range3dProps, TransformProps, XYZProps } from "@itwin/core-geometry"; import { ColorDefProps, EcefLocationProps, ElementGeometryDataEntry, ElementGeometryInfo, ElementGeometryOpcode, GeometricElementProps, GeometryPartProps } from "@itwin/core-common"; import { EditCommandIpc } from "./EditorIpc"; /** @alpha */ export const editorBuiltInCmdIds = { cmdBasicManipulation: "basicManipulation", cmdSolidModeling: "solidModeling", }; /** @alpha */ export interface FlatBufferGeometricElementData { /** The geometry stream data */ entryArray: ElementGeometryDataEntry[]; /** Whether entries are supplied local to placement transform or in world coordinates */ isWorld?: boolean; /** If true, create geometry that displays oriented to face the camera */ viewIndependent?: boolean; } /** @alpha */ export interface FlatBufferGeometryPartData { /** The geometry stream data */ entryArray: ElementGeometryDataEntry[]; /** If true, create geometry part with 2d geometry */ is2dPart?: boolean; } /** @alpha */ export interface FlatBufferGeometryFilter { /** Optional limit on number of displayable entries to accept */ maxDisplayable?: number; /** Optional array of displayable opCodes to accept */ accept?: ElementGeometryOpcode[]; /** Optional array of displayable opCodes to reject */ reject?: ElementGeometryOpcode[]; /** Optional geometry type filter * curves - true to accept single curves and paths * surfaces - true to accept loops, planar regions, open polyfaces, and sheet bodies * solids - true to accept capped solids, closed polyfaces, and solid bodies */ geometry?: { curves: boolean, surfaces: boolean, solids: boolean }; } /** @alpha */ export interface BasicManipulationCommandIpc extends EditCommandIpc { deleteElements(ids: CompressedId64Set): Promise<IModelStatus>; transformPlacement(ids: CompressedId64Set, transform: TransformProps): Promise<IModelStatus>; rotatePlacement(ids: CompressedId64Set, matrix: Matrix3dProps, aboutCenter: boolean): Promise<IModelStatus>; /** Create and insert a new geometric element. * @param props Properties for the new [GeometricElement]($backend) * @param data Optional binary format GeometryStream representation used in lieu of [[GeometricElementProps.geom]]. * @see [GeometryStream]($docs/learning/common/geometrystream.md), [ElementGeometry]($backend) * @throws [[IModelError]] if unable to insert the element */ insertGeometricElement(props: GeometricElementProps, data?: FlatBufferGeometricElementData): Promise<Id64String>; /** Create and insert a new geometry part element. * @param props Properties for the new [GeometryPart]($backend) * @param data Optional binary format GeometryStream representation used in lieu of [[GeometryPartProps.geom]]. * @see [GeometryStream]($docs/learning/common/geometrystream.md), [ElementGeometry]($backend) * @throws [[IModelError]] if unable to insert the element */ insertGeometryPart(props: GeometryPartProps, data?: FlatBufferGeometryPartData): Promise<Id64String>; /** Update an existing geometric element. * @param propsOrId Properties or element id to update for an existing [GeometricElement]($backend) * @param data Optional binary format GeometryStream representation used in lieu of [[GeometricElementProps.geom]]. * @see [GeometryStream]($docs/learning/common/geometrystream.md), [ElementGeometry]($backend) * @throws [[IModelError]] if unable to update the element */ updateGeometricElement(propsOrId: GeometricElementProps | Id64String, data?: FlatBufferGeometricElementData): Promise<void>; /** Request geometry from an existing element. Because a GeometryStream can be large and may contain information * that is not always useful to frontend code, filter options are provided to restrict what GeometryStreams are returned. * For example, a tool may only be interested in a GeometryStream that stores a single CurveCollection. * @param id Element id of an existing [GeometricElement]($backend) or [GeometryPart]($backend). * @param filter Optional criteria for accepting a GeometryStream. * @see [GeometryStream]($docs/learning/common/geometrystream.md), [ElementGeometry]($backend) * @throws [[IModelError]] if unable to query the element */ requestElementGeometry(id: Id64String, filter?: FlatBufferGeometryFilter): Promise<ElementGeometryInfo | undefined>; /** Update the project extents for the iModel. * @param extents New project extents. * @throws [[IModelError]] if unable to update the extents property. */ updateProjectExtents(extents: Range3dProps): Promise<void>; /** Update the position of the iModel on the earth. * @param ecefLocation New ecef location properties. * @throws [[IModelError]] if unable to update the ecef location property. * @note Clears the geographic coordinate reference system of the iModel, should only be called if invalid. */ updateEcefLocation(ecefLocation: EcefLocationProps): Promise<void>; } /** @alpha */ export interface ElementGeometryCacheFilter { /** Optional lower limit on number of geometric primitives to accept */ minGeom?: number; /** Optional upper limit on number of geometric primitives to accept */ maxGeom?: number; /** Whether to accept geometry from parts. */ parts: boolean; /** Whether to accept single curves and paths. */ curves: boolean; /** Whether to accept loops, planar regions, open polyfaces, and sheet bodies. */ surfaces: boolean; /** Whether to accept capped solids, closed polyfaces, and solid bodies. */ solids: boolean; /** Whether to accept text, image graphics, etc. */ other: boolean; } /** @alpha */ export interface ElementGeometryResultOptions { /** If true, return geometry as data that can be converted to a render graphic */ wantGraphic?: true | undefined; /** If true, return geometry as flatbuffer format data. * The data is potentially large and may include brep entries that cannot be directly * inspected or manipulated on the frontend, request only as needed. */ wantGeometry?: true | undefined; /** If true, return geometry range. */ wantRange?: true | undefined; /** If true, return geometry appearance information. */ wantAppearance?: true | undefined; /** The chord tolerance to use when creating the graphic (default is 0.01) */ chordTolerance?: number; /** Unique identifier for the render graphic request */ requestId?: string; /** If true, a successful result updates the source element or is inserted as a new element when insertProps is supplied */ writeChanges?: true | undefined; /** If specified, writeChanges inserts a new [GeometricElement]($backend) using these properties */ insertProps?: GeometricElementProps; } /** @alpha */ export interface ElementGeometryResultProps { /** The element's geometry stream graphic data in world coordinates */ graphic?: Uint8Array; /** The element's geometry stream information */ geometry?: ElementGeometryInfo; /** The element's range box (available as ElementGeometryInfo.bbox when returning geometry) */ range?: Range3dProps; /** The element's category (available as ElementGeometryInfo.category when returning geometry) */ categoryId?: Id64String; /** The result element id (different than source id when requesting insert instead of update) */ elementId?: Id64String; } /** @alpha */ export enum SubEntityType { /** A single bounded part of a surface */ Face = 0, /** A single bounded part of a curve */ Edge = 1, /** A single point */ Vertex = 2, } /** @alpha */ export interface SubEntityProps { /** Identifies the geometric primitive in the geometry stream that owns this sub-entity when there are more than one */ index?: number; /** Identifies the type of sub-entity */ type: SubEntityType; /** Identifies a face, edge, or vertex of the geometric primitive */ id: number; } /** @alpha */ export interface SubEntityLocationProps { /** The information to identify the sub-entity */ subEntity: SubEntityProps; /** The face, edge, or vertex location in world coordinates from closest point or locate request */ point?: XYZProps; /** The face normal in world coordinates of the identified location on sub-entity */ normal?: XYZProps; /** The face or edge u parameter of identified location on sub-entity */ uParam?: number; /** The face v parameter of identified location on sub-entity */ vParam?: number; } /** @alpha */ export interface SubEntityAppearanceProps { /** Category id for geometry. */ category: Id64String; /** SubCategory id for geometry. */ subCategory?: Id64String; /** Material id for geometry. */ material?: Id64String; /** color of geometry. */ color?: ColorDefProps; /** transparency of geometry. */ transparency?: number; /** weight of geometry. */ weight?: number; } /** @alpha */ export interface SubEntityGeometryProps { /** The face, edge, or vertex graphic data in world coordinates */ graphic?: Uint8Array; /** The face, edge, or vertex geometry in world coordinates */ geometry?: ElementGeometryDataEntry; /** The face or edge range box for the sub-entity geometry */ range?: Range3dProps; /** The appearance information for the sub-entity geometry */ appearance?: SubEntityAppearanceProps; } /** @alpha */ export interface OffsetFacesProps { /** The faces to offset */ faces: SubEntityProps | SubEntityProps[]; /** The offset to apply to all faces, or the offset for each face */ distances: number | number[]; } /** @alpha */ export interface SubEntityFilter { /** true to reject non-planar faces */ nonPlanarFaces?: true; /** true to reject non-linear edges */ nonLinearEdges?: true; /** true to reject laminar edges */ laminarEdges?: true; /** true to reject smooth edges */ smoothEdges?: true; /** true to reject smooth vertices */ smoothVertices?: true; } /** @alpha */ export interface LocateSubEntityProps { /** The maximum number of face hits to return. Pass 0 to not pick faces. */ maxFace: number; /** The maximum number of edge hits to return. Pass 0 to not pick edges. */ maxEdge: number; /** The maximum number of vertex hits to return. Pass 0 to not pick vertices. */ maxVertex: number; /** An edge will be picked if it is within this distance from the ray, a vertex twice this distance. */ maxDistance?: number; /** When not locating faces, true to allow locate of back edges and vertices. */ hiddenEdgesVisible: boolean; /** Optional filter to reject common types of faces, edges, and vertices. */ filter?: SubEntityFilter; } /** @alpha */ export interface SolidModelingCommandIpc extends EditCommandIpc { clearElementGeometryCache(): Promise<void>; createElementGeometryCache(id: Id64String, filter?: ElementGeometryCacheFilter): Promise<boolean>; getSubEntityGeometry(id: Id64String, subEntity: SubEntityProps, opts: Omit<ElementGeometryResultOptions, "writeChanges" | "insertProps">): Promise<SubEntityGeometryProps | undefined>; locateSubEntities(id: Id64String, spacePoint: XYZProps, direction: XYZProps, opts: LocateSubEntityProps): Promise<SubEntityLocationProps[] | undefined>; getClosestFace(id: Id64String, testPoint: XYZProps, preferredDirection?: XYZProps): Promise<SubEntityLocationProps | undefined>; offsetFaces(id: Id64String, params: OffsetFacesProps, opts: ElementGeometryResultOptions): Promise<ElementGeometryResultProps | undefined>; }
the_stack
import { IncomingRequestCfProperties } from './cloudflare_workers_types.d.ts'; import { setEqual, setSubtract, setUnion } from './sets.ts'; // Types For Found Tail Websocket Message Payloads export interface TailOptions { readonly filters: readonly TailFilter[]; } export type TailFilter = ClientIpFilter | QueryFilter | HeaderFilter | MethodFilter | SampleRateFilter | OutcomeFilter; export interface ClientIpFilter { readonly 'client_ip': string[]; // ip address or "self" (which doesn't seem to work) } export interface QueryFilter { readonly query: string; // text match on console.log messages } export interface HeaderFilter { readonly key: string; readonly query?: string; } export function parseHeaderFilter(header: string): HeaderFilter { const i = header.indexOf(':'); if (i < 0) return { key: header }; const key = header.substring(0, i).trim(); const query = header.substring(i + 1).trim(); return { key, query }; } export interface MethodFilter { readonly method: readonly string[]; // GET, POST, etc } export interface SampleRateFilter { readonly 'sampling_rate': number; // e.g. 0.01 for 1% } export interface OutcomeFilter { readonly outcome: readonly Outcome[]; } export type Outcome = 'ok' | 'exception' | 'exceededCpu' | 'canceled' | 'unknown'; export interface TailMessage { readonly outcome: Outcome; readonly scriptName: null; readonly exceptions: readonly TailMessageException[]; readonly logs: readonly TailMessageLog[]; readonly eventTimestamp: number; // epoch millis readonly event: TailMessageEvent; } export type TailMessageEvent = TailMessageCronEvent | TailMessageRequestEvent; const REQUIRED_TAIL_MESSAGE_KEYS = new Set(['outcome', 'scriptName', 'exceptions', 'logs', 'eventTimestamp', 'event']); const KNOWN_OUTCOMES = new Set(['ok', 'exception', 'exceededCpu', 'canceled', 'unknown']); export function parseTailMessage(obj: unknown): TailMessage { if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) throw new Error(`Bad tailMessage: Expected object, found ${JSON.stringify(obj)}`); checkKeys(obj, REQUIRED_TAIL_MESSAGE_KEYS); // deno-lint-ignore no-explicit-any const objAsAny = obj as any; const { outcome, scriptName, eventTimestamp } = objAsAny; if (!KNOWN_OUTCOMES.has(outcome)) throw new Error(`Bad outcome: expected one of [${[...KNOWN_OUTCOMES].join(', ')}], found ${JSON.stringify(outcome)}`); if (scriptName !== null) throw new Error(`Bad scriptName: expected null, found ${JSON.stringify(scriptName)}`); const logs = parseLogs(objAsAny.logs); const exceptions = parseExceptions(objAsAny.exceptions); if (!(typeof eventTimestamp === 'number' && eventTimestamp > 0)) throw new Error(`Bad eventTimestamp: expected positive number, found ${JSON.stringify(eventTimestamp)}`); const event = objAsAny.event && objAsAny.event.request ? parseTailMessageRequestEvent(objAsAny.event) : parseTailMessageCronEvent(objAsAny.event); return { outcome, scriptName, exceptions, logs, eventTimestamp, event }; } function parseLogs(obj: unknown): readonly TailMessageLog[] { if (!(Array.isArray(obj))) throw new Error(`Bad logs: expected array, found ${JSON.stringify(obj)}`); return [...obj].map(parseTailMessageLog); } function parseExceptions(obj: unknown): readonly TailMessageException[] { if (!(Array.isArray(obj))) throw new Error(`Bad exceptions: expected array, found ${JSON.stringify(obj)}`); return [...obj].map(parseTailMessageException); } // export interface TailMessageLog { readonly message: readonly LogMessagePart[]; readonly level: string; // e.g. log readonly timestamp: number; // epoch millis } // deno-lint-ignore ban-types export type LogMessagePart = string | number | boolean | undefined | object; function isLogMessagePart(value: unknown): value is LogMessagePart { const t = typeof value; return t === 'string' || t === 'number' || t === 'boolean' || t === 'undefined' || t === 'object'; } const REQUIRED_TAIL_MESSAGE_LOG_KEYS = new Set(['message', 'level', 'timestamp']); function parseTailMessageLog(obj: unknown): TailMessageLog { if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) throw new Error(`Bad tailMessageLog: Expected object, found ${JSON.stringify(obj)}`); checkKeys(obj, REQUIRED_TAIL_MESSAGE_LOG_KEYS); // deno-lint-ignore no-explicit-any const objAsAny = obj as any; const message = parseLogMessagePartArray(objAsAny.message, 'message'); const { level, timestamp } = objAsAny; if (!(typeof level === 'string')) throw new Error(`Bad level: expected string, found ${JSON.stringify(level)}`); if (!(typeof timestamp === 'number' && timestamp > 0)) throw new Error(`Bad timestamp: expected positive number, found ${JSON.stringify(timestamp)}`); return { message, level, timestamp }; } // export interface TailMessageException { readonly name: string; // e.g. Error readonly message: string; // Error.message readonly timestamp: number; // epoch millis } const REQUIRED_TAIL_MESSAGE_EXCEPTION_KEYS = new Set(['name', 'message', 'timestamp']); function parseTailMessageException(obj: unknown): TailMessageException { if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) throw new Error(`Bad tailMessageException: Expected object, found ${JSON.stringify(obj)}`); checkKeys(obj, REQUIRED_TAIL_MESSAGE_EXCEPTION_KEYS); // deno-lint-ignore no-explicit-any const objAsAny = obj as any; const { name, message, timestamp } = objAsAny; if (!(typeof name === 'string')) throw new Error(`Bad name: expected string, found ${JSON.stringify(name)}`); if (!(typeof message === 'string')) throw new Error(`Bad message: expected string, found ${JSON.stringify(message)}`); if (!(typeof timestamp === 'number' && timestamp > 0)) throw new Error(`Bad timestamp: expected positive number, found ${JSON.stringify(timestamp)}`); return { name, message, timestamp }; } // export interface TailMessageCronEvent { readonly cron: string; // e.g. "*/1 * * * *" readonly scheduledTime: number; // epoch millis } const REQUIRED_TAIL_MESSAGE_CRON_EVENT_KEYS = new Set(['cron', 'scheduledTime']); export function isTailMessageCronEvent(obj: unknown): obj is TailMessageCronEvent { if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) return false; const keys = new Set(Object.keys(obj)); return setEqual(keys, REQUIRED_TAIL_MESSAGE_CRON_EVENT_KEYS); } function parseTailMessageCronEvent(obj: unknown): TailMessageCronEvent { if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) throw new Error(`Bad tailMessageCronEvent: Expected object, found ${JSON.stringify(obj)}`); checkKeys(obj, REQUIRED_TAIL_MESSAGE_CRON_EVENT_KEYS); // deno-lint-ignore no-explicit-any const objAsAny = obj as any; const { cron, scheduledTime } = objAsAny; if (!(typeof cron === 'string')) throw new Error(`Bad cron: expected string, found ${JSON.stringify(cron)}`); if (!(typeof scheduledTime === 'number' && scheduledTime > 0)) throw new Error(`Bad scheduledTime: expected positive number, found ${JSON.stringify(scheduledTime)}`); return { cron, scheduledTime }; } // export interface TailMessageRequestEvent { readonly request: TailMessageEventRequest; } const REQUIRED_TAIL_MESSAGE_REQUEST_EVENT_KEYS = new Set(['request']); function parseTailMessageRequestEvent(obj: unknown): TailMessageRequestEvent { if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) throw new Error(`Bad tailMessageRequestEvent: Expected object, found ${JSON.stringify(obj)}`); checkKeys(obj, REQUIRED_TAIL_MESSAGE_REQUEST_EVENT_KEYS); // deno-lint-ignore no-explicit-any const objAsAny = obj as any; const request = parseTailMessageEventRequest(objAsAny.request); return { request }; } // export interface TailMessageEventRequest { readonly url: string; readonly method: string; readonly headers: Record<string, string>; readonly cf?: IncomingRequestCfProperties; // undefined for DO requests } const REQUIRED_TAIL_MESSAGE_EVENT_REQUEST_KEYS = new Set(['url', 'method', 'headers']); const OPTIONAL_TAIL_MESSAGE_EVENT_REQUEST_KEYS = new Set(['cf']); const ALL_TAIL_MESSAGE_EVENT_REQUEST_KEYS = setUnion(REQUIRED_TAIL_MESSAGE_EVENT_REQUEST_KEYS, OPTIONAL_TAIL_MESSAGE_EVENT_REQUEST_KEYS); function parseTailMessageEventRequest(obj: unknown): TailMessageEventRequest { if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) throw new Error(`Bad tailMessageEventRequest: Expected object, found ${JSON.stringify(obj)}`); checkKeys(obj, REQUIRED_TAIL_MESSAGE_EVENT_REQUEST_KEYS, ALL_TAIL_MESSAGE_EVENT_REQUEST_KEYS); // deno-lint-ignore no-explicit-any const objAsAny = obj as any; const { url, method } = objAsAny; if (!(typeof url === 'string')) throw new Error(`Bad url: expected string, found ${JSON.stringify(url)}`); if (!(typeof method === 'string')) throw new Error(`Bad method: expected string, found ${JSON.stringify(method)}`); const headers = parseStringRecord(objAsAny.headers, 'headers'); const cf = objAsAny.cf === undefined ? undefined : parseIncomingRequestCfProperties(objAsAny.cf); return { url, method, headers, cf }; } // // deno-lint-ignore ban-types function checkKeys(obj: object, requiredKeys: Set<string>, allKeys?: Set<string>) { const keys = new Set(Object.keys(obj)); const missingKeys = setSubtract(requiredKeys, keys); if (missingKeys.size > 0) throw new Error(`Missing keys: ${[...missingKeys].join(', ')}`); const extraKeys = setSubtract(keys, allKeys || requiredKeys); if (extraKeys.size > 0) throw new Error(`Extra keys: ${[...extraKeys].join(', ')}`); } function parseStringRecord(obj: unknown, name: string): Record<string, string> { if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) throw new Error(`Bad ${name}: Expected string record, found ${JSON.stringify(obj)}`); for (const [_, value] of Object.entries(obj)) { if (typeof value !== 'string') throw new Error(`Bad ${name}: Expected string record, found ${JSON.stringify(obj)}`); } return obj as Record<string, string>; } function parseLogMessagePartArray(obj: unknown, name: string): readonly LogMessagePart[] { if (typeof obj !== 'object' || !Array.isArray(obj)) throw new Error(`Bad ${name}: Expected log message part array, found ${JSON.stringify(obj)}`); for (const value of obj) { if (!isLogMessagePart(value)) throw new Error(`Bad ${name}: Expected log message part array, found ${JSON.stringify(obj)}`); } return obj as readonly LogMessagePart[]; } function parseIncomingRequestCfProperties(obj: unknown): IncomingRequestCfProperties { if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) throw new Error(`Bad cf: Expected object, found ${JSON.stringify(obj)}`); // good enough return obj as IncomingRequestCfProperties; }
the_stack
import { sort, arraySwap } from '../../mol-data/util'; import { GraphicsRenderObject } from '../../mol-gl/render-object'; import { MeshValues } from '../../mol-gl/renderable/mesh'; import { LinesValues } from '../../mol-gl/renderable/lines'; import { PointsValues } from '../../mol-gl/renderable/points'; import { SpheresValues } from '../../mol-gl/renderable/spheres'; import { CylindersValues } from '../../mol-gl/renderable/cylinders'; import { TextureMeshValues } from '../../mol-gl/renderable/texture-mesh'; import { BaseValues, SizeValues } from '../../mol-gl/renderable/schema'; import { TextureImage } from '../../mol-gl/renderable/util'; import { WebGLContext } from '../../mol-gl/webgl/context'; import { getTrilinearlyInterpolated } from '../../mol-geo/geometry/mesh/color-smoothing'; import { Mesh } from '../../mol-geo/geometry/mesh/mesh'; import { MeshBuilder } from '../../mol-geo/geometry/mesh/mesh-builder'; import { addSphere } from '../../mol-geo/geometry/mesh/builder/sphere'; import { addCylinder } from '../../mol-geo/geometry/mesh/builder/cylinder'; import { sizeDataFactor } from '../../mol-geo/geometry/size-data'; import { Vec3 } from '../../mol-math/linear-algebra'; import { RuntimeContext } from '../../mol-task'; import { Color } from '../../mol-util/color/color'; import { decodeFloatRGB } from '../../mol-util/float-packing'; import { RenderObjectExporter, RenderObjectExportData } from './render-object-exporter'; const GeoExportName = 'geo-export'; // avoiding namespace lookup improved performance in Chrome (Aug 2020) const v3fromArray = Vec3.fromArray; export interface AddMeshInput { mesh: { vertices: Float32Array normals: Float32Array indices: Uint32Array | undefined groups: Float32Array | Uint8Array vertexCount: number drawCount: number } | undefined meshes: Mesh[] | undefined values: BaseValues isGeoTexture: boolean webgl: WebGLContext | undefined ctx: RuntimeContext } export abstract class MeshExporter<D extends RenderObjectExportData> implements RenderObjectExporter<D> { abstract readonly fileExtension: string; private static getSizeFromTexture(tSize: TextureImage<Uint8Array>, i: number): number { const r = tSize.array[i * 3]; const g = tSize.array[i * 3 + 1]; const b = tSize.array[i * 3 + 2]; return decodeFloatRGB(r, g, b) / sizeDataFactor; } private static getSize(values: BaseValues & SizeValues, instanceIndex: number, group: number): number { const tSize = values.tSize.ref.value; let size = 0; switch (values.dSizeType.ref.value) { case 'uniform': size = values.uSize.ref.value; break; case 'instance': size = MeshExporter.getSizeFromTexture(tSize, instanceIndex); break; case 'group': size = MeshExporter.getSizeFromTexture(tSize, group); break; case 'groupInstance': const groupCount = values.uGroupCount.ref.value; size = MeshExporter.getSizeFromTexture(tSize, instanceIndex * groupCount + group); break; } return size * values.uSizeFactor.ref.value; } protected static getGroup(groups: Float32Array | Uint8Array, i: number): number { const i4 = i * 4; const r = groups[i4]; const g = groups[i4 + 1]; const b = groups[i4 + 2]; if (groups instanceof Float32Array) { return decodeFloatRGB(r * 255 + 0.5, g * 255 + 0.5, b * 255 + 0.5); } return decodeFloatRGB(r, g, b); } protected static getInterpolatedColors(vertices: Float32Array, vertexCount: number, values: BaseValues, stride: number, colorType: 'volume' | 'volumeInstance', webgl: WebGLContext) { const colorGridTransform = values.uColorGridTransform.ref.value; const colorGridDim = values.uColorGridDim.ref.value; const colorTexDim = values.uColorTexDim.ref.value; const aTransform = values.aTransform.ref.value; const instanceCount = values.uInstanceCount.ref.value; if (!webgl.namedFramebuffers[GeoExportName]) { webgl.namedFramebuffers[GeoExportName] = webgl.resources.framebuffer(); } const framebuffer = webgl.namedFramebuffers[GeoExportName]; const [width, height] = colorTexDim; const colorGrid = new Uint8Array(width * height * 4); framebuffer.bind(); values.tColorGrid.ref.value.attachFramebuffer(framebuffer, 0); webgl.readPixels(0, 0, width, height, colorGrid); const interpolated = getTrilinearlyInterpolated({ vertexCount, instanceCount, transformBuffer: aTransform, positionBuffer: vertices, colorType, grid: colorGrid, gridDim: colorGridDim, gridTexDim: colorTexDim, gridTransform: colorGridTransform, vertexStride: stride, colorStride: 4 }); return interpolated.array; } protected static quantizeColors(colorArray: Uint8Array, vertexCount: number) { if (vertexCount <= 1024) return; const rgb = Vec3(); const min = Vec3(); const max = Vec3(); const sum = Vec3(); const colorMap = new Map<Color, Color>(); const colorComparers = [ (colors: Color[], i: number, j: number) => (Color.toVec3(rgb, colors[i])[0] - Color.toVec3(rgb, colors[j])[0]), (colors: Color[], i: number, j: number) => (Color.toVec3(rgb, colors[i])[1] - Color.toVec3(rgb, colors[j])[1]), (colors: Color[], i: number, j: number) => (Color.toVec3(rgb, colors[i])[2] - Color.toVec3(rgb, colors[j])[2]), ]; const medianCut = (colors: Color[], l: number, r: number, depth: number) => { if (l > r) return; if (l === r || depth >= 10) { // Find the average color. Vec3.set(sum, 0, 0, 0); for (let i = l; i <= r; ++i) { Color.toVec3(rgb, colors[i]); Vec3.add(sum, sum, rgb); } Vec3.round(rgb, Vec3.scale(rgb, sum, 1 / (r - l + 1))); const averageColor = Color.fromArray(rgb, 0); for (let i = l; i <= r; ++i) colorMap.set(colors[i], averageColor); return; } // Find the color channel with the greatest range. Vec3.set(min, 255, 255, 255); Vec3.set(max, 0, 0, 0); for (let i = l; i <= r; ++i) { Color.toVec3(rgb, colors[i]); for (let j = 0; j < 3; ++j) { Vec3.min(min, min, rgb); Vec3.max(max, max, rgb); } } let k = 0; if (max[1] - min[1] > max[k] - min[k]) k = 1; if (max[2] - min[2] > max[k] - min[k]) k = 2; sort(colors, l, r + 1, colorComparers[k], arraySwap); const m = (l + r) >> 1; medianCut(colors, l, m, depth + 1); medianCut(colors, m + 1, r, depth + 1); }; // Create an array of unique colors and use the median cut algorithm. const colorSet = new Set<Color>(); for (let i = 0; i < vertexCount; ++i) { colorSet.add(Color.fromArray(colorArray, i * 3)); } const colors = Array.from(colorSet); medianCut(colors, 0, colors.length - 1, 0); // Map actual colors to quantized colors. for (let i = 0; i < vertexCount; ++i) { const color = colorMap.get(Color.fromArray(colorArray, i * 3)); Color.toArray(color!, colorArray, i * 3); } } protected static getInstance(input: AddMeshInput, instanceIndex: number) { const { mesh, meshes } = input; if (mesh !== undefined) { return mesh; } else { const mesh = meshes![instanceIndex]; return { vertices: mesh.vertexBuffer.ref.value, normals: mesh.normalBuffer.ref.value, indices: mesh.indexBuffer.ref.value, groups: mesh.groupBuffer.ref.value, vertexCount: mesh.vertexCount, drawCount: mesh.triangleCount * 3 }; } } protected static getColor(values: BaseValues, groups: Float32Array | Uint8Array, vertexCount: number, instanceIndex: number, isGeoTexture: boolean, interpolatedColors: Uint8Array | undefined, vertexIndex: number): Color { const groupCount = values.uGroupCount.ref.value; const colorType = values.dColorType.ref.value; const uColor = values.uColor.ref.value; const tColor = values.tColor.ref.value.array; const dOverpaint = values.dOverpaint.ref.value; const tOverpaint = values.tOverpaint.ref.value.array; let color: Color; switch (colorType) { case 'uniform': color = Color.fromNormalizedArray(uColor, 0); break; case 'instance': color = Color.fromArray(tColor, instanceIndex * 3); break; case 'group': { const group = isGeoTexture ? MeshExporter.getGroup(groups, vertexIndex) : groups[vertexIndex]; color = Color.fromArray(tColor, group * 3); break; } case 'groupInstance': { const group = isGeoTexture ? MeshExporter.getGroup(groups, vertexIndex) : groups[vertexIndex]; color = Color.fromArray(tColor, (instanceIndex * groupCount + group) * 3); break; } case 'vertex': color = Color.fromArray(tColor, vertexIndex * 3); break; case 'vertexInstance': color = Color.fromArray(tColor, (instanceIndex * vertexCount + vertexIndex) * 3); break; case 'volume': color = Color.fromArray(interpolatedColors!, vertexIndex * 3); break; case 'volumeInstance': color = Color.fromArray(interpolatedColors!, (instanceIndex * vertexCount + vertexIndex) * 3); break; default: throw new Error('Unsupported color type.'); } if (dOverpaint) { const group = isGeoTexture ? MeshExporter.getGroup(groups, vertexIndex) : groups[vertexIndex]; const overpaintColor = Color.fromArray(tOverpaint, (instanceIndex * groupCount + group) * 4); const overpaintAlpha = tOverpaint[(instanceIndex * groupCount + group) * 4 + 3] / 255; color = Color.interpolate(color, overpaintColor, overpaintAlpha); } return color; } protected abstract addMeshWithColors(input: AddMeshInput): void; private async addMesh(values: MeshValues, webgl: WebGLContext, ctx: RuntimeContext) { const aPosition = values.aPosition.ref.value; const aNormal = values.aNormal.ref.value; const aGroup = values.aGroup.ref.value; const originalData = Mesh.getOriginalData(values); let indices: Uint32Array; let vertexCount: number; let drawCount: number; if (originalData) { indices = originalData.indexBuffer; vertexCount = originalData.vertexCount; drawCount = originalData.triangleCount * 3; } else { indices = values.elements.ref.value; vertexCount = values.uVertexCount.ref.value; drawCount = values.drawCount.ref.value; } await this.addMeshWithColors({ mesh: { vertices: aPosition, normals: aNormal, indices, groups: aGroup, vertexCount, drawCount }, meshes: undefined, values, isGeoTexture: false, webgl, ctx }); } private async addLines(values: LinesValues, webgl: WebGLContext, ctx: RuntimeContext) { // TODO } private async addPoints(values: PointsValues, webgl: WebGLContext, ctx: RuntimeContext) { // TODO } private async addSpheres(values: SpheresValues, webgl: WebGLContext, ctx: RuntimeContext) { const center = Vec3(); const aPosition = values.aPosition.ref.value; const aGroup = values.aGroup.ref.value; const instanceCount = values.instanceCount.ref.value; const vertexCount = values.uVertexCount.ref.value; const meshes: Mesh[] = []; const sphereCount = vertexCount / 4 * instanceCount; let detail: number; if (sphereCount < 2000) detail = 3; else if (sphereCount < 20000) detail = 2; else detail = 1; for (let instanceIndex = 0; instanceIndex < instanceCount; ++instanceIndex) { const state = MeshBuilder.createState(512, 256); for (let i = 0; i < vertexCount; i += 4) { v3fromArray(center, aPosition, i * 3); const group = aGroup[i]; const radius = MeshExporter.getSize(values, instanceIndex, group); state.currentGroup = group; addSphere(state, center, radius, detail); } meshes.push(MeshBuilder.getMesh(state)); } await this.addMeshWithColors({ mesh: undefined, meshes, values, isGeoTexture: false, webgl, ctx }); } private async addCylinders(values: CylindersValues, webgl: WebGLContext, ctx: RuntimeContext) { const start = Vec3(); const end = Vec3(); const aStart = values.aStart.ref.value; const aEnd = values.aEnd.ref.value; const aScale = values.aScale.ref.value; const aCap = values.aCap.ref.value; const aGroup = values.aGroup.ref.value; const instanceCount = values.instanceCount.ref.value; const vertexCount = values.uVertexCount.ref.value; const meshes: Mesh[] = []; const cylinderCount = vertexCount / 6 * instanceCount; let radialSegments: number; if (cylinderCount < 2000) radialSegments = 36; else if (cylinderCount < 20000) radialSegments = 24; else radialSegments = 12; for (let instanceIndex = 0; instanceIndex < instanceCount; ++instanceIndex) { const state = MeshBuilder.createState(512, 256); for (let i = 0; i < vertexCount; i += 6) { v3fromArray(start, aStart, i * 3); v3fromArray(end, aEnd, i * 3); const group = aGroup[i]; const radius = MeshExporter.getSize(values, instanceIndex, group) * aScale[i]; const cap = aCap[i]; const topCap = cap === 1 || cap === 3; const bottomCap = cap >= 2; const cylinderProps = { radiusTop: radius, radiusBottom: radius, topCap, bottomCap, radialSegments }; state.currentGroup = aGroup[i]; addCylinder(state, start, end, 1, cylinderProps); } meshes.push(MeshBuilder.getMesh(state)); } await this.addMeshWithColors({ mesh: undefined, meshes, values, isGeoTexture: false, webgl, ctx }); } private async addTextureMesh(values: TextureMeshValues, webgl: WebGLContext, ctx: RuntimeContext) { if (!webgl.namedFramebuffers[GeoExportName]) { webgl.namedFramebuffers[GeoExportName] = webgl.resources.framebuffer(); } const framebuffer = webgl.namedFramebuffers[GeoExportName]; const [width, height] = values.uGeoTexDim.ref.value; const vertices = new Float32Array(width * height * 4); const normals = new Float32Array(width * height * 4); const groups = webgl.isWebGL2 ? new Uint8Array(width * height * 4) : new Float32Array(width * height * 4); framebuffer.bind(); values.tPosition.ref.value.attachFramebuffer(framebuffer, 0); webgl.readPixels(0, 0, width, height, vertices); values.tNormal.ref.value.attachFramebuffer(framebuffer, 0); webgl.readPixels(0, 0, width, height, normals); values.tGroup.ref.value.attachFramebuffer(framebuffer, 0); webgl.readPixels(0, 0, width, height, groups); const vertexCount = values.uVertexCount.ref.value; const drawCount = values.drawCount.ref.value; await this.addMeshWithColors({ mesh: { vertices, normals, indices: undefined, groups, vertexCount, drawCount }, meshes: undefined, values, isGeoTexture: true, webgl, ctx }); } add(renderObject: GraphicsRenderObject, webgl: WebGLContext, ctx: RuntimeContext) { if (!renderObject.state.visible) return; switch (renderObject.type) { case 'mesh': return this.addMesh(renderObject.values as MeshValues, webgl, ctx); case 'lines': return this.addLines(renderObject.values as LinesValues, webgl, ctx); case 'points': return this.addPoints(renderObject.values as PointsValues, webgl, ctx); case 'spheres': return this.addSpheres(renderObject.values as SpheresValues, webgl, ctx); case 'cylinders': return this.addCylinders(renderObject.values as CylindersValues, webgl, ctx); case 'texture-mesh': return this.addTextureMesh(renderObject.values as TextureMeshValues, webgl, ctx); } } abstract getData(ctx: RuntimeContext): Promise<D>; abstract getBlob(ctx: RuntimeContext): Promise<Blob>; }
the_stack
import { assert } from "@itwin/core-bentley"; import { ComboBox, ComboBoxEntry, createButton, createCheckBox, createComboBox, createLabeledNumericInput, createSlider, LabeledNumericInput, Slider } from "@itwin/frontend-devtools"; import { Point3d, Range1d } from "@itwin/core-geometry"; import { calculateSolarDirectionFromAngles, ColorByName, ColorDef, ThematicDisplay, ThematicDisplayMode, ThematicDisplayProps, ThematicDisplaySensorProps, ThematicGradientColorScheme, ThematicGradientMode, ViewFlags, } from "@itwin/core-common"; import { Viewport, ViewState, ViewState3d } from "@itwin/core-frontend"; type Required<T> = { [P in keyof T]-?: T[P]; }; const defaultSettings: Required<ThematicDisplayProps> = { displayMode: ThematicDisplayMode.Height, gradientSettings: { mode: ThematicGradientMode.Smooth, marginColor: ColorByName.blanchedAlmond, colorScheme: ThematicGradientColorScheme.BlueRed, }, axis: [0.0, 0.0, 1.0], range: [0, 1], sunDirection: calculateSolarDirectionFromAngles({ azimuth: 315.0, elevation: 45.0 }).toJSON(), sensorSettings: { sensors: [], distanceCutoff: 0, }, }; export class ThematicDisplayEditor { // create a 32x32 grid of sensors spread evenly within the extents of the project private _createSensorGrid(sensors: ThematicDisplaySensorProps[]) { const sensorGridXLength = 32; const sensorGridYLength = 32; const sensorValues: number[] = [0.1, 0.9, 0.25, 0.15, 0.8, 0.34, 0.78, 0.32, 0.15, 0.29, 0.878, 0.95, 0.5, 0.278, 0.44, 0.33, 0.71]; const extents = this._vp.view.iModel.projectExtents; const xRange = Range1d.createXX(extents.xLow, extents.xHigh); const yRange = Range1d.createXX(extents.yLow, extents.yHigh); const sensorZ = extents.low.z + (extents.high.z - extents.low.z) / 2.0; let sensorValueIndex = 0; for (let y = 0; y < sensorGridYLength; y++) { const sensorY = yRange.fractionToPoint(y / (sensorGridYLength - 1)); for (let x = 0; x < sensorGridXLength; x++) { const sensorX = xRange.fractionToPoint(x / (sensorGridXLength - 1)); const sensorPos = Point3d.create(sensorX, sensorY, sensorZ); this._pushNewSensor(sensors, { position: sensorPos, value: sensorValues[sensorValueIndex] }); sensorValueIndex++; if (sensorValueIndex >= sensorValues.length) sensorValueIndex = 0; } } } private _pushNewSensor(sensors: ThematicDisplaySensorProps[], sensorProps?: ThematicDisplaySensorProps) { if (undefined !== sensorProps) { sensors.push(sensorProps); return; } const extents = this._vp.view.iModel.projectExtents; defaultSettings.range = { low: extents.zLow, high: extents.zHigh }; const sensorZ = extents.low.z + (extents.high.z - extents.low.z) / 2.0; const sensorLow = extents.low.cloneAsPoint3d(); const sensorHigh = extents.high.cloneAsPoint3d(); sensorLow.z = sensorHigh.z = sensorZ; const sensorPos = sensorLow.interpolate(0.5, sensorHigh); sensors.push({ position: sensorPos, value: 0.5 }); } private _resetSensorEntries(count: number) { const select = this._thematicSensor.select; while (select.length > 0) select.remove(0); for (let i = 0; i < count; i++) this._appendSensorEntry(`Sensor ${i.toString()}`); } private _appendSensorEntry(name: string) { const option = document.createElement("option"); option.innerText = name; this._thematicSensor.select.appendChild(option); } private readonly _vp: Viewport; private readonly _scratchViewFlags = new ViewFlags(); private readonly _update: (view: ViewState) => void; private readonly _thematicDisplayMode: ComboBox; private readonly _thematicGradientMode: ComboBox; private readonly _thematicStepCount: LabeledNumericInput; private readonly _thematicColorScheme: ComboBox; private readonly _thematicRangeLow: LabeledNumericInput; private readonly _thematicRangeHigh: LabeledNumericInput; private readonly _thematicColorMix: Slider; private readonly _thematicAxisX: LabeledNumericInput; private readonly _thematicAxisY: LabeledNumericInput; private readonly _thematicAxisZ: LabeledNumericInput; private readonly _thematicSunDirX: LabeledNumericInput; private readonly _thematicSunDirY: LabeledNumericInput; private readonly _thematicSunDirZ: LabeledNumericInput; private readonly _thematicDistanceCutoff: LabeledNumericInput; private readonly _thematicSensor: ComboBox; private readonly _thematicSensorX: LabeledNumericInput; private readonly _thematicSensorY: LabeledNumericInput; private readonly _thematicSensorZ: LabeledNumericInput; private readonly _thematicSensorValue: LabeledNumericInput; private static _gradientModeEntriesForHeight = [ { name: "Smooth", value: ThematicGradientMode.Smooth }, { name: "Stepped", value: ThematicGradientMode.Stepped }, { name: "SteppedWithDelimiter", value: ThematicGradientMode.SteppedWithDelimiter }, { name: "IsoLines", value: ThematicGradientMode.IsoLines }, ]; private static _gradientModeEntriesForOthers = [ { name: "Smooth", value: ThematicGradientMode.Smooth }, { name: "Stepped", value: ThematicGradientMode.Stepped }, ]; private static _appendComboBoxEntry(select: HTMLSelectElement, entry: ComboBoxEntry) { const option = document.createElement("option"); option.innerText = entry.name; if (undefined !== entry.value) option.value = entry.value.toString(); select.appendChild(option); } private static _setComboBoxEntries(cb: ComboBox, entries: ComboBoxEntry[]) { // remove all existing entries let i; const ln = cb.select.options.length - 1; for (i = ln; i >= 0; i--) { cb.select.remove(i); } // add new entries for (const entry of entries) { ThematicDisplayEditor._appendComboBoxEntry(cb.select, entry); } } public updateDefaultRange() { const extents = this._vp.view.iModel.projectExtents; defaultSettings.range = { low: extents.zLow, high: extents.zHigh }; } public constructor(vp: Viewport, parent: HTMLElement) { this._vp = vp; const isThematicDisplaySupported = (view: ViewState) => view.is3d(); const isThematicDisplayEnabled = (view: ViewState) => view.viewFlags.thematicDisplay; const div = document.createElement("div"); const thematicControlsDiv = document.createElement("div")!; const showHideControls = (show: boolean) => { const display = show ? "block" : "none"; thematicControlsDiv.style.display = display; }; const enableThematicDisplay = (enabled: boolean) => { const extents = this._vp.view.iModel.projectExtents; defaultSettings.range = { low: extents.zLow, high: extents.zHigh }; const sensors = defaultSettings.sensorSettings.sensors!; defaultSettings.sensorSettings.distanceCutoff = extents.xLength() / 25.0; const sensorZ = extents.low.z + (extents.high.z - extents.low.z) / 2.0; const sensorLow = extents.low.cloneAsPoint3d(); const sensorHigh = extents.high.cloneAsPoint3d(); sensorLow.z = sensorHigh.z = sensorZ; const sensorPosA = sensorLow.interpolate(0.25, sensorHigh); const sensorPosB = sensorLow.interpolate(0.5, sensorHigh); const sensorPosC = sensorLow.interpolate(0.65, sensorHigh); const sensorPosD = sensorLow.interpolate(0.75, sensorHigh); sensors[0] = { position: sensorPosA, value: 0.025 }; sensors[1] = { position: sensorPosB, value: 0.5 }; sensors[2] = { position: sensorPosC, value: 0.025 }; sensors[3] = { position: sensorPosD, value: 0.75 }; this._resetSensorEntries(4); const displaySettings = (this._vp.view as ViewState3d).getDisplayStyle3d().settings; displaySettings.thematic = ThematicDisplay.fromJSON(defaultSettings); this._vp.viewFlags = this._vp.viewFlags.with("thematicDisplay", enabled); showHideControls(enabled); this.sync(); }; const checkboxInterface = createCheckBox({ parent: div, handler: (cb) => enableThematicDisplay(cb.checked), name: "Thematic Display", id: "cbx_Thematic", }); const checkbox = checkboxInterface.checkbox; const checkboxLabel = checkboxInterface.label; const displayModeEntries = [ { name: "Height", value: ThematicDisplayMode.Height }, { name: "InverseDistanceWeightedSensors", value: ThematicDisplayMode.InverseDistanceWeightedSensors }, { name: "Slope", value: ThematicDisplayMode.Slope }, { name: "HillShade", value: ThematicDisplayMode.HillShade }, ]; this._thematicDisplayMode = createComboBox({ parent: thematicControlsDiv, name: "Display Mode: ", entries: displayModeEntries, id: "thematic_displayMode", value: 0, handler: (thing) => this.updateThematicDisplay((view): ThematicDisplayProps => { const props = this.getThematicSettingsProps(view); const prevDisplayMode = props.displayMode; const newDisplayMode = props.displayMode = Number.parseInt(thing.value, 10); if (ThematicDisplayMode.Slope === newDisplayMode) { props.range = { low: 0.0, high: 90.0 }; } else if (ThematicDisplayMode.Slope === prevDisplayMode) { this.updateDefaultRange(); const range1d = Range1d.fromJSON(defaultSettings.range); props.range = { low: range1d.low, high: range1d.high }; } return props; }), }); this._thematicGradientMode = createComboBox({ parent: thematicControlsDiv, name: "Gradient Mode: ", entries: ThematicDisplayEditor._gradientModeEntriesForHeight, id: "thematic_gradientMode", value: 0, handler: (thing) => this.updateThematicDisplay((view): ThematicDisplayProps => { const props = this.getThematicSettingsProps(view); props.gradientSettings!.mode = Number.parseInt(thing.value, 10); return props; }), }); const spanStepAndColor = document.createElement("span"); spanStepAndColor.style.display = "flex"; thematicControlsDiv.appendChild(spanStepAndColor); this._thematicStepCount = createLabeledNumericInput({ id: "thematic_stepCount", parent: spanStepAndColor, value: 1, handler: (value, _) => this.updateThematicDisplay((view): ThematicDisplayProps => { const props = this.getThematicSettingsProps(view); props.gradientSettings!.stepCount = value; return props; }), min: 2, max: 65536, step: 1, name: "Step Count: ", }); this._thematicStepCount.div.style.marginRight = "1.5em"; const colorSchemeEntries = [ { name: "BlueRed", value: ThematicGradientColorScheme.BlueRed }, { name: "RedBlue", value: ThematicGradientColorScheme.RedBlue }, { name: "Monochrome", value: ThematicGradientColorScheme.Monochrome }, { name: "Topographic", value: ThematicGradientColorScheme.Topographic }, { name: "SeaMountain", value: ThematicGradientColorScheme.SeaMountain }, { name: "Custom", value: ThematicGradientColorScheme.Custom }, ]; this._thematicColorScheme = createComboBox({ parent: spanStepAndColor, name: "Color Scheme: ", entries: colorSchemeEntries, id: "thematic_colorScheme", value: 0, handler: (thing) => this.updateThematicDisplay((view): ThematicDisplayProps => { const props = this.getThematicSettingsProps(view); props.gradientSettings!.colorScheme = Number.parseInt(thing.value, 10); // For now, we just hard code a custom color scheme in here. ###TODO - allow user to specify their own custom values. if (props.gradientSettings!.colorScheme === ThematicGradientColorScheme.Custom) { const customKeyValues = [[0.0, 255, 255, 0], [0.5, 255, 0, 255], [1.0, 0, 255, 255]]; props.gradientSettings!.customKeys = []; customKeyValues.forEach((key) => props.gradientSettings!.customKeys!.push({ value: key[0], color: ColorDef.computeTbgrFromComponents(key[1], key[2], key[3]) })); } return props; }), }); const spanRange = document.createElement("span"); spanRange.style.display = "flex"; thematicControlsDiv.appendChild(spanRange); this._thematicRangeHigh = createLabeledNumericInput({ id: "thematic_rangeHigh", parent: spanRange, value: -1.0, handler: (value, _) => this.updateThematicDisplay((view): ThematicDisplayProps => { const props = this.getThematicSettingsProps(view); const oldRange = Range1d.fromJSON(props.range); props.range = { low: oldRange.low, high: value }; return props; }), min: -100000.0, max: 100000.0, step: 1.0, parseAsFloat: true, name: "High range: ", }); this._thematicRangeHigh.div.style.marginRight = "0.5em"; this._thematicRangeLow = createLabeledNumericInput({ id: "thematic_rangeLow", parent: spanRange, value: 1.0, handler: (value, _) => this.updateThematicDisplay((view): ThematicDisplayProps => { const props = this.getThematicSettingsProps(view); const oldRange = Range1d.fromJSON(props.range); props.range = { low: value, high: oldRange.high }; return props; }), min: -100000.0, max: 100000.0, step: 1.0, parseAsFloat: true, name: "Low range: ", }); const defaultAxis = Point3d.fromJSON(defaultSettings.axis); const spanAxis = document.createElement("span"); spanAxis.style.display = "flex"; thematicControlsDiv.appendChild(spanAxis); this._thematicAxisX = createLabeledNumericInput({ id: "thematic_axisX", parent: spanAxis, value: defaultAxis.x, handler: (value, _) => this.updateThematicDisplay((view): ThematicDisplayProps => { const props = this.getThematicSettingsProps(view); const axis = Point3d.fromJSON(props.axis); axis.x = value; props.axis = axis.toJSON(); return props; }), min: -1.0, max: 1.0, step: 0.1, parseAsFloat: true, name: "Axis X: ", }); this._thematicAxisX.div.style.marginRight = "0.5em"; this._thematicAxisY = createLabeledNumericInput({ id: "thematic_axisY", parent: spanAxis, value: defaultAxis.y, handler: (value, _) => this.updateThematicDisplay((view): ThematicDisplayProps => { const props = this.getThematicSettingsProps(view); const axis = Point3d.fromJSON(props.axis); axis.y = value; props.axis = axis.toJSON(); return props; }), min: -1.0, max: 1.0, step: 0.1, parseAsFloat: true, name: "Y: ", }); this._thematicAxisY.div.style.marginRight = "0.5em"; this._thematicAxisZ = createLabeledNumericInput({ id: "thematic_axisZ", parent: spanAxis, value: defaultAxis.z, handler: (value, _) => this.updateThematicDisplay((view): ThematicDisplayProps => { const props = this.getThematicSettingsProps(view); const axis = Point3d.fromJSON(props.axis); axis.z = value; props.axis = axis.toJSON(); return props; }), min: -1.0, max: 1.0, step: 0.1, parseAsFloat: true, name: "Z: ", }); this._thematicColorMix = createSlider({ id: "thematic_colorMix", name: "Terrain/PointCloud Mix", parent: thematicControlsDiv, min: "0.0", max: "1.0", step: "0.05", value: "0.0", handler: (_) => this.updateThematicDisplay((view): ThematicDisplayProps => { const props = this.getThematicSettingsProps(view); props.gradientSettings!.colorMix = parseFloat(this._thematicColorMix.slider.value); return props; }), }); this._thematicColorMix.div.style.textAlign = "left"; const spanSunDir = document.createElement("span"); spanSunDir.style.display = "flex"; thematicControlsDiv.appendChild(spanSunDir); this._thematicSunDirX = createLabeledNumericInput({ id: "thematic_sunDirX", parent: spanSunDir, value: 0.0, handler: (value, _) => this.updateThematicDisplay((view): ThematicDisplayProps => { const props = this.getThematicSettingsProps(view); const sunDir = Point3d.fromJSON(props.sunDirection); sunDir.x = value; props.sunDirection = sunDir.toJSON(); return props; }), min: -1.0, max: 1.0, step: 0.1, parseAsFloat: true, name: "Sun Direction X: ", }); this._thematicSunDirX.div.style.marginRight = "0.5em"; this._thematicSunDirY = createLabeledNumericInput({ id: "thematic_sunDirY", parent: spanSunDir, value: 0.0, handler: (value, _) => this.updateThematicDisplay((view): ThematicDisplayProps => { const props = this.getThematicSettingsProps(view); const sunDir = Point3d.fromJSON(props.sunDirection); sunDir.y = value; props.sunDirection = sunDir.toJSON(); return props; }), min: -1.0, max: 1.0, step: 0.1, parseAsFloat: true, name: "Y: ", }); this._thematicSunDirY.div.style.marginRight = "0.5em"; this._thematicSunDirZ = createLabeledNumericInput({ id: "thematic_sunDirZ", parent: spanSunDir, value: 0.0, handler: (value, _) => this.updateThematicDisplay((view): ThematicDisplayProps => { const props = this.getThematicSettingsProps(view); const sunDir = Point3d.fromJSON(props.sunDirection); sunDir.z = value; props.sunDirection = sunDir.toJSON(); return props; }), min: -1.0, max: 1.0, step: 0.1, parseAsFloat: true, name: "Z: ", }); this._thematicDistanceCutoff = createLabeledNumericInput({ id: "thematic_distanceCutoff", parent: thematicControlsDiv, value: 0.0, handler: (value, _) => this.updateThematicDisplay((view): ThematicDisplayProps => { const props = this.getThematicSettingsProps(view); props.sensorSettings!.distanceCutoff = value; return props; }), min: -999999.0, max: 999999.0, step: 0.1, parseAsFloat: true, name: "Distance Cutoff: ", }); this._thematicSensor = createComboBox({ parent: thematicControlsDiv, name: "Selected Sensor: ", entries: [], id: "thematic_sensor", value: 0, handler: (_thing) => this.updateThematicDisplay((view): ThematicDisplayProps => { return this.getThematicSettingsProps(view); }), }); const spanSensor = document.createElement("span"); spanSensor.style.display = "flex"; thematicControlsDiv.appendChild(spanSensor); this._thematicSensorX = createLabeledNumericInput({ id: "thematic_sensorX", parent: spanSensor, value: 0.0, handler: (value, _) => this.updateThematicDisplay((view): ThematicDisplayProps => { const props = this.getThematicSettingsProps(view); const selectedSensor = this._thematicSensor.select.options.selectedIndex; const pos = Point3d.fromJSON(props.sensorSettings!.sensors![selectedSensor].position); pos.x = value; props.sensorSettings!.sensors![selectedSensor].position = pos.toJSON(); return props; }), min: -999999.0, max: 999999.0, step: 0.1, parseAsFloat: true, name: "Sensor X: ", }); this._thematicSensorX.div.style.marginRight = "0.5em"; this._thematicSensorY = createLabeledNumericInput({ id: "thematic_sensorY", parent: spanSensor, value: 0.0, handler: (value, _) => this.updateThematicDisplay((view): ThematicDisplayProps => { const props = this.getThematicSettingsProps(view); const selectedSensor = this._thematicSensor.select.options.selectedIndex; const pos = Point3d.fromJSON(props.sensorSettings!.sensors![selectedSensor].position); pos.y = value; props.sensorSettings!.sensors![selectedSensor].position = pos.toJSON(); return props; }), min: -999999.0, max: 999999.0, step: 0.1, parseAsFloat: true, name: "Y: ", }); this._thematicSensorY.div.style.marginRight = "0.5em"; this._thematicSensorZ = createLabeledNumericInput({ id: "thematic_sensorZ", parent: spanSensor, value: 0.0, handler: (value, _) => this.updateThematicDisplay((view): ThematicDisplayProps => { const props = this.getThematicSettingsProps(view); const selectedSensor = this._thematicSensor.select.options.selectedIndex; const pos = Point3d.fromJSON(props.sensorSettings!.sensors![selectedSensor].position); pos.z = value; props.sensorSettings!.sensors![selectedSensor].position = pos.toJSON(); return props; }), min: -999999.0, max: 999999.0, step: 0.1, parseAsFloat: true, name: "Z: ", }); this._thematicSensorValue = createLabeledNumericInput({ id: "thematic_sensorValue", parent: thematicControlsDiv, value: 0.0, handler: (value, _) => this.updateThematicDisplay((view): ThematicDisplayProps => { const props = this.getThematicSettingsProps(view); const selectedSensor = this._thematicSensor.select.options.selectedIndex; props.sensorSettings!.sensors![selectedSensor].value = value; return props; }), min: 0.0, max: 1.0, step: 0.025, parseAsFloat: true, name: "Sensor Value: ", }); const sensorsControlsDiv = document.createElement("div")!; createButton({ parent: sensorsControlsDiv, id: "thematic_addSensor", value: "Add Sensor", inline: true, handler: () => this.updateThematicDisplay((view): ThematicDisplayProps => { const props = this.getThematicSettingsProps(view); if (props.sensorSettings!.sensors !== undefined) { this._pushNewSensor(props.sensorSettings!.sensors); this._resetSensorEntries(props.sensorSettings!.sensors.length); this._thematicSensor.select.selectedIndex = props.sensorSettings!.sensors.length - 1; } return props; }), }); createButton({ parent: sensorsControlsDiv, id: "thematic_deleteSensor", value: "Delete Sensor", inline: true, handler: () => this.updateThematicDisplay((view): ThematicDisplayProps => { const props = this.getThematicSettingsProps(view); if (props.sensorSettings!.sensors !== undefined && props.sensorSettings!.sensors.length > 1) { const selectedSensorIndex = this._thematicSensor.select.options.selectedIndex; props.sensorSettings!.sensors.splice(selectedSensorIndex, 1); if (props.sensorSettings!.sensors === undefined) props.sensorSettings!.sensors = []; this._thematicSensor.select.options.remove(selectedSensorIndex); } return props; }), }); createButton({ parent: sensorsControlsDiv, id: "thematic_createSensorGrid", value: "Create Sensor Grid", inline: true, handler: () => this.updateThematicDisplay((view): ThematicDisplayProps => { const props = this.getThematicSettingsProps(view); if (props.sensorSettings!.sensors !== undefined) { props.sensorSettings!.sensors = []; this._createSensorGrid(props.sensorSettings!.sensors); this._resetSensorEntries(props.sensorSettings!.sensors.length); this._thematicSensor.select.selectedIndex = props.sensorSettings!.sensors.length - 1; } return props; }), }); sensorsControlsDiv.style.textAlign = "center"; thematicControlsDiv.appendChild(sensorsControlsDiv); const resetButton = createButton({ parent: thematicControlsDiv, id: "thematic_reset", value: "Reset", handler: () => this.resetThematicDisplay(), }); resetButton.div.style.textAlign = "center"; this._update = (view) => { const visible = isThematicDisplaySupported(view); div.style.display = visible ? "block" : "none"; if (!visible) return; checkbox.checked = isThematicDisplayEnabled(view); checkboxLabel.style.fontWeight = checkbox.checked ? "bold" : "500"; showHideControls(checkbox.checked); this.updateThematicDisplayUI(view); }; div.appendChild(thematicControlsDiv); const hr = document.createElement("hr"); hr.style.borderColor = "grey"; div.appendChild(hr); parent.appendChild(div); } public update(view: ViewState): void { this._update(view); } private getThematicSettings(view: ViewState): ThematicDisplay { assert(view.is3d()); return view.displayStyle.settings.thematic; } private getThematicSettingsProps(view: ViewState): ThematicDisplayProps { return this.getThematicSettings(view).toJSON(); } private updateThematicDisplayUI(view: ViewState) { const settings = this.getThematicSettings(view); let range = settings.range; if (range.isNull) { this.updateDefaultRange(); range = Range1d.fromJSON(defaultSettings.range); } this._thematicRangeLow.input.value = range.low.toString(); this._thematicRangeHigh.input.value = range.high.toString(); this._thematicDisplayMode.select.value = settings.displayMode.toString(); const displayMode = Number.parseInt(this._thematicDisplayMode.select.value, 10); if (ThematicDisplayMode.Height === displayMode) { ThematicDisplayEditor._setComboBoxEntries(this._thematicGradientMode, ThematicDisplayEditor._gradientModeEntriesForHeight); } else { ThematicDisplayEditor._setComboBoxEntries(this._thematicGradientMode, ThematicDisplayEditor._gradientModeEntriesForOthers); } this._thematicGradientMode.select.value = settings.gradientSettings.mode.toString(); this._thematicStepCount.input.value = settings.gradientSettings.stepCount.toString(); this._thematicColorScheme.select.value = settings.gradientSettings.colorScheme.toString(); this._thematicColorMix.slider.value = settings.gradientSettings.colorMix.toString(); this._thematicAxisX.input.value = settings.axis.x.toString(); this._thematicAxisY.input.value = settings.axis.y.toString(); this._thematicAxisZ.input.value = settings.axis.z.toString(); this._thematicSunDirX.input.value = settings.sunDirection.x.toString(); this._thematicSunDirY.input.value = settings.sunDirection.y.toString(); this._thematicSunDirZ.input.value = settings.sunDirection.z.toString(); this._thematicDistanceCutoff.input.value = settings.sensorSettings.distanceCutoff.toString(); const sensors = settings.sensorSettings.sensors; if (sensors.length > 0) { if (this._thematicSensor.select.length < 1) this._resetSensorEntries(sensors.length); const selectedSensor = this._thematicSensor.select.options.selectedIndex; const pos = Point3d.fromJSON(sensors[selectedSensor].position); this._thematicSensorX.input.value = pos.x.toString(); this._thematicSensorY.input.value = pos.y.toString(); this._thematicSensorZ.input.value = pos.z.toString(); this._thematicSensorValue.input.value = sensors[selectedSensor].value.toString(); } } private updateThematicDisplay(updateFunction: (view: ViewState) => ThematicDisplayProps) { const props = updateFunction(this._vp.view); (this._vp.view as ViewState3d).getDisplayStyle3d().settings.thematic = ThematicDisplay.fromJSON(props); this.sync(); } private resetThematicDisplay(): void { const thematicDisplay = ThematicDisplay.fromJSON(defaultSettings); (this._vp.view as ViewState3d).getDisplayStyle3d().settings.thematic = thematicDisplay; this._resetSensorEntries(thematicDisplay.sensorSettings.sensors.length); this.sync(); this.updateThematicDisplayUI(this._vp.view); } private sync(): void { this._vp.synchWithView(); } }
the_stack
import Obniz from '../../../dist/src/obniz/index'; import ObnizBoard from '../../../dist/src/obniz/libs/hw/obnizBoard'; const OBNIZ_ID = '1234-5678'; /** * https://obniz.io/ja/doc/sdk/doc/display */ class DisplayTest { public clear() { const obniz = new Obniz(OBNIZ_ID); obniz.display!.clear(); } public print() { const obniz = new Obniz(OBNIZ_ID); obniz.display!.print('Hello!'); obniz.display!.font('Serif', 18); obniz.display!.print('Hello World🧡'); } public pos() { const obniz = new Obniz(OBNIZ_ID); obniz.display!.pos(0, 30); obniz.display!.print('YES. こんにちは'); } public font() { const obniz = new Obniz(OBNIZ_ID); obniz.display!.font('Avenir', 30); obniz.display!.print('Avenir'); obniz.display!.font(null, 30); // デフォルトフォント(Arial)の30px obniz.display!.font('Avenir'); // Avenirのデフォルトサイズ(16px) } public line() { const obniz = new Obniz(OBNIZ_ID); obniz.display!.line(30, 30, 100, 30); obniz.display!.rect(20, 20, 20, 20); obniz.display!.circle(100, 30, 20); obniz.display!.line(60, 50, 100, 30); obniz.display!.rect(50, 40, 20, 20, true); obniz.display!.line(50, 10, 100, 30); obniz.display!.circle(50, 10, 10, true); } public rect() { const obniz = new Obniz(OBNIZ_ID); obniz.display!.rect(10, 10, 20, 20); obniz.display!.rect(20, 20, 20, 20, true); // filled rect } public circle() { const obniz = new Obniz(OBNIZ_ID); obniz.display!.circle(40, 30, 20); obniz.display!.circle(90, 30, 20, true); // filled circle } public drawing() { const obniz = new Obniz(OBNIZ_ID); obniz.display!.drawing(false); for (let i = 0; i < 100; i++) { const x0 = Math.random() * 128; const y0 = Math.random() * 64; const x1 = Math.random() * 128; const y1 = Math.random() * 64; obniz.display!.clear(); obniz.display!.line(x0, y0, x1, y1); } obniz.display!.drawing(true); } public qr() { const obniz = new Obniz(OBNIZ_ID); obniz.display!.qr('https://obniz.io'); } public raw() { const obniz = new Obniz(OBNIZ_ID); obniz.display!.raw([255, 255]); // must be 128*64 bits(=1024byte) } public draw() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { // 1. load existing const canvas1 = document.getElementById('canvas') as HTMLCanvasElement; const ctx1 = canvas1.getContext('2d')!; obniz.display!.draw(ctx1); // 2. create new canvas dom and load it. const ctx2 = obniz.util.createCanvasContext( obniz.display!.width, obniz.display!.height ); obniz.display!.draw(ctx2); // 3. running with node.js // npm install canvas. ( version 2.0.0 or later required ) // eslint-disable-next-line @typescript-eslint/no-var-requires const { createCanvas } = require('canvas'); const canvas = createCanvas(128, 64); const ctx3 = canvas.getContext('2d'); ctx3.fillStyle = 'white'; ctx3.font = '30px Avenir'; ctx3.fillText('Avenir', 0, 40); obniz.display!.draw(ctx3); }; } } /** * https://obniz.io/doc/sdk/doc/ad */ class ADTest { public start() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { obniz.ad0!.start((voltage) => { console.log('changed to ' + voltage + ' v'); }); obniz.ad0!.start(); obniz.ad0!.onchange = (voltage) => { console.log('changed to ' + voltage + ' v'); }; obniz.ad0!.start(); while (true) { console.log('changed to ' + obniz.ad0!.value + ' v'); await obniz.wait(10); // 10ms wait } }; } public getWait() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { obniz.io0!.output(true); const voltage = await obniz.ad0!.getWait(); obniz.io0!.output(false); console.log('' + voltage + ' should be closed to 5.00'); }; } public end() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { obniz.ad0!.start(); obniz.ad0!.end(); }; } public onchange() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { obniz.ad0!.start(); obniz.ad0!.onchange = (voltage) => { console.log('voltage = ' + voltage); }; }; } } /** * https://obniz.io/doc/sdk/doc/i2c */ class I2CTest { public getFreeI2C() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { const i2c = obniz.getFreeI2C(); }; } public start() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { obniz.i2c0!.start({ mode: 'master', sda: 2, scl: 3, clock: 400000 }); obniz.i2c0!.write(0x50, [0x00, 0x00, 0x12]); const ret = await obniz.i2c0!.readWait(0x50, 1); console.log('read ' + ret); // use internal pull up obniz.i2c0!.start({ mode: 'master', sda: 2, scl: 3, clock: 400000, pull: '5v', }); obniz.i2c0!.start({ mode: 'master', sda: 2, scl: 3, clock: 100000, pull: '3v', }); // slave mode obniz.i2c0!.start({ mode: 'slave', sda: 0, scl: 1, slave_address: 0x01 }); }; } public write() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { obniz.i2c0!.start({ mode: 'master', sda: 2, scl: 3, clock: 400000 }); obniz.i2c0!.write(0x50, [0x00, 0x00, 0x12]); }; } public readWait() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { obniz.i2c0!.start({ mode: 'master', sda: 2, scl: 3, clock: 400000 }); const ret = await obniz.i2c0!.readWait(0x50, 1); console.log('read ' + ret); }; } public onwritten() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { obniz.i2c0!.start({ mode: 'slave', sda: 0, scl: 1, slave_address: 0x01 }); obniz.i2c0!.onwritten = (data) => { console.log(data); }; }; } public onerror() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { obniz.i2c0!.start({ mode: 'master', sda: 2, scl: 3, clock: 400000 }); obniz.i2c0!.onerror = (err) => { console.log('Error', err); }; const ret = await obniz.i2c0!.readWait(0x50, 1); }; } public end() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { obniz.i2c0!.start({ mode: 'master', sda: 2, scl: 3, clock: 400000 }); obniz.i2c0!.end(); }; } } /** * https://obniz.io/doc/sdk/doc/io */ class IOTest { public output() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { obniz.io1!.output(true); // io1 is 5v obniz.io2!.output(1); // io2 is 5v obniz.io3!.drive('3v'); obniz.io3!.output(1); // io3 is around 3v. }; } public drive() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { obniz.io0!.output(true); // output push-pull 5v obniz.io1!.drive('3v'); obniz.io1!.output(true); // output push-pull 3v obniz.io2!.pull('5v'); obniz.io2!.drive('open-drain'); obniz.io2!.output(true); // output open-drain with 5v pull-up }; } public pull() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { obniz.io0!.pull('3v'); obniz.io0!.drive('open-drain'); // output open-drain obniz.io0!.output(false); }; } public input() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { obniz.io0!.input((value: any) => { console.log('changed to ' + value); }); }; } public inputWait() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { const value = await obniz.io0!.inputWait(); console.log(value); }; } public end() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { obniz.io0!.output(true); obniz.io0!.end(); }; } public animation() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { obniz.io!.animation('animation-1', 'loop', [ { duration: 10, state(index: number) { // index = 0 obniz.io0!.output(false); obniz.io1!.output(true); }, }, { duration: 10, state(index: number) { // index = 1 obniz.io0!.output(true); obniz.io1!.output(false); }, }, ]); }; } public repeatWait() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { await obniz.io!.repeatWait( [ { duration: 1000, state(index: number) { obniz.io0!.output(true); }, }, { duration: 1000, state(index: number) { obniz.io0!.output(false); }, }, ], 4 ); }; } } /** * https://obniz.io/doc/sdk/doc/pwm */ class PWMTest { public getFreePwm() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { const pwm = obniz.getFreePwm(); }; } public start() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { const pwm = obniz.getFreePwm(); pwm.start({ io: 0 }); // start pwm. output at io0 pwm.freq(1000); pwm.duty(50); const pwm2 = obniz.getFreePwm(); pwm2.start({ io: 1, drive: 'open-drain', pull: '5v' }); }; } public freq() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { const pwm = obniz.getFreePwm(); pwm.start({ io: 0 }); pwm.freq(1000); // set pwm. frequency to 1khz }; } public pulse() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { const pwm = obniz.getFreePwm(); pwm.start({ io: 0 }); pwm.freq(2000); // set pwm frequency to 2khz pwm.pulse(0.5); // set pwm pulse 0.5ms. so this is 25% ratio. }; } public duty() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { const pwm = obniz.getFreePwm(); pwm.start({ io: 0 }); pwm.freq(2000); // set pwm frequency to 2khz pwm.duty(50); // set pwm pulse width 50% }; } public modulate() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { const pwm = obniz.getFreePwm(); pwm.start({ io: 0 }); pwm.freq(38000); // set pwm frequency to 38khz // signal for room heater's remote signal const arr = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, ]; pwm.modulate('am', 0.07, arr); // am modulate. symbol length = 70us. }; } public end() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { const pwm = obniz.getFreePwm(); pwm.start({ io: 0 }); pwm.end(); }; } } /** * https://obniz.io/doc/sdk/doc/spi */ class SPITest { public getFreeSpi() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { const spi = obniz.getFreeSpi(); }; } public start() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { obniz.spi0!.start({ mode: 'master', clk: 0, mosi: 1, miso: 2, frequency: 1000000, }); const ret = await obniz.spi0!.writeWait([0x12, 0x98]); console.log('received: ' + ret); // drive and pull is optional obniz.spi0!.start({ mode: 'master', clk: 0, mosi: 1, miso: 2, frequency: 1000000, drive: '5v', }); }; } public writeWait() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { obniz.spi0!.start({ mode: 'master', clk: 0, mosi: 1, miso: 2, frequency: 1000000, }); const ret = await obniz.spi0!.writeWait([0x12, 0x98]); console.log('received: ' + ret); }; } public write() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { obniz.spi0!.start({ mode: 'master', clk: 0, mosi: 1, miso: 2, frequency: 1000000, }); obniz.spi0!.write([0x12, 0x98]); }; } public end() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { // obniz.spi0!.start({ mode: 'master', clk: 0, mosi: 1, miso: 2, clock: 1000000 }); obniz.spi0!.start({ mode: 'master', clk: 0, mosi: 1, miso: 2, frequency: 1000000, }); obniz.spi0!.write([0x12, 0x98]); obniz.spi0!.end(); }; } } /** * https://obniz.io/doc/sdk/doc/uart */ class UARTTest { public getFreeUart() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { const uart = obniz.getFreeUart(); }; } public start() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { obniz.io0!.output(false); // for sharing GND. obniz.uart0!.start({ tx: 1, rx: 2, baud: 9600, bits: 7 }); obniz.uart0!.send('Hi'); obniz.uart1!.start({ tx: 3, rx: 4, cts: 5, rts: 6, flowcontrol: 'rts-cts', }); obniz.uart1!.send('Hi'); }; } public send() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { obniz.uart0!.start({ tx: 0, rx: 1 }); obniz.uart0!.send('Hi'); obniz.uart0!.send(0x11); obniz.uart0!.send([0x11, 0x45, 0x44]); }; } public end() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { obniz.uart0!.start({ tx: 0, rx: 1 }); obniz.uart0!.send('Hi'); obniz.uart0!.end(); }; } public onreceive() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { obniz.uart0!.start({ tx: 0, rx: 1 }); obniz.uart0!.onreceive = (data, text) => { console.log(data); console.log(text); }; obniz.uart0!.send('Hello'); }; } public isDataExists() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { obniz.uart0!.start({ tx: 0, rx: 1 }); while (1) { if (obniz.uart0!.isDataExists()) { console.log(obniz.uart0!.readText()); } await obniz.wait(10); // wait for 10ms } }; } public readByte() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { obniz.uart0!.start({ tx: 0, rx: 1 }); while (1) { while (obniz.uart0!.isDataExists()) { console.log(obniz.uart0!.readByte()); } await obniz.wait(10); // wait for 10ms } }; } public readBytes() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { obniz.uart0!.start({ tx: 0, rx: 1 }); while (1) { if (obniz.uart0!.isDataExists()) { console.log(obniz.uart0!.readBytes()); } await obniz.wait(10); // wait for 10ms } }; } public readText() { const obniz = new Obniz(OBNIZ_ID); obniz.onconnect = async () => { obniz.uart0!.start({ tx: 0, rx: 1 }); while (1) { if (obniz.uart0!.isDataExists()) { console.log(obniz.uart0!.readText()); } await obniz.wait(10); // wait for 10ms } }; } }
the_stack
import {BigTableView} from "../modules"; import {BucketsInfo, IColumnDescription, RangeFilterArrayDescription, RecordOrder, RemoteObjectId} from "../javaBridge"; import {FullPage, PageTitle} from "../ui/fullPage"; import {D3SvgElement, DragEventKind, Point, Resolution, ViewKind} from "../ui/ui"; import {TextOverlay} from "../ui/textOverlay"; import {PlottingSurface} from "../ui/plottingSurface"; import {TopMenu} from "../ui/menu"; import {drag as d3drag} from "d3-drag"; import {event as d3event, mouse as d3mouse} from "d3-selection"; import {AxisData} from "./axisData"; import {Dialog} from "../ui/dialog"; import {NextKReceiver, TableView} from "../modules"; import {TableMeta} from "../ui/receiver"; /** * A ChartView is a common base class for many views that * display charts. */ export abstract class ChartView<D> extends BigTableView { /** * True while the mouse is being dragged. */ protected dragging: boolean; /** * True if the mouse has been moved after starting dragging. */ protected moved: boolean; /** * Coordinates of mouse within canvas. */ protected selectionOrigin: Point | null; /** * Rectangle in canvas used to display the current selection. */ protected selectionRectangle: D3SvgElement; /** * Describes the data currently pointed by the mouse. */ protected pointDescription: TextOverlay | null; /** * The main surface on top of which the image is drawn. * There may exist other surfaces as well besides this one. */ protected surface: PlottingSurface | null; /** * Top-level menu. */ protected menu: TopMenu; /** * Data that is being displayed. */ protected data: D; protected constructor(remoteObjectId: RemoteObjectId, meta: TableMeta, page: FullPage, viewKind: ViewKind) { super(remoteObjectId, meta, page, viewKind); this.topLevel.className = "chart-page"; this.dragging = false; this.moved = false; this.selectionOrigin = null; this.selectionRectangle = null; this.pointDescription = null; this.surface = null; this.page.registerDropHandler("XAxis", (p) => this.replaceAxis(p, "XAxis")); this.page.registerDropHandler("YAxis", (p) => this.replaceAxis(p, "YAxis")); this.page.registerDropHandler("GAxis", (p) => this.replaceAxis(p, "GAxis")); this.page.setDataView(this); } protected showTable(columns: IColumnDescription[], provenance: string): void { const newPage = this.dataset.newPage(new PageTitle("Table", provenance), this.page); const table = new TableView(this.getRemoteObjectId()!, this.meta, newPage); newPage.setDataView(table); const order = new RecordOrder( columns.map(c => { return { columnDescription: c, isAscending: true }})); const rr = table.createNextKRequest(order, null, Resolution.tableRowsOnScreen, null, null); rr.invoke(new NextKReceiver(newPage, table, rr, false, order, null)); } protected setupMouse(): void { this.topLevel.onkeydown = (e) => this.keyDown(e); this.topLevel.tabIndex = 1; // seems to be necessary to get keyboard events const drag = d3drag() .on("start", () => this.dragStart()) .on("drag", () => this.dragMove()) .on("end", () => this.dragEnd()); const canvas = this.surface!.getCanvas(); canvas.call(drag) .on("mousemove", () => this.onMouseMove()) .on("mouseenter", () => this.onMouseEnter()) .on("mouseleave", () => this.onMouseLeave()); this.selectionRectangle = canvas .append("rect") .attr("class", "dashed") .attr("stroke", "red") .attr("width", 0) .attr("height", 0); } protected keyDown(ev: KeyboardEvent): void { if (ev.code === "Escape") this.cancelDrag(); } protected onMouseEnter(): void { if (this.pointDescription != null) { this.pointDescription.show(true); } } protected onMouseLeave(): void { if (this.pointDescription != null) { this.pointDescription.show(false); } } protected cancelDrag(): void { this.dragging = false; this.moved = false; this.hideSelectionRectangle(); } /** * Converts a point coordinate in canvas to a point coordinate in the chart surface. */ public canvasToChart(point: Point): Point { return { x: point.x - this.surface!.leftMargin, y: point.y - this.surface!.topMargin }; } protected abstract onMouseMove(): void; protected dragStart(): void { this.dragging = true; this.moved = false; } protected dragStartRectangle(): void { this.dragging = true; this.moved = false; const position = d3mouse(this.surface!.getCanvas().node()); this.selectionOrigin = { x: position[0], y: position[1] }; } /** * Get the range of the specified axis. * @param dragEvent A drag event kind; some of these correspond to dragging axes. */ public getAxisData(dragEvent: DragEventKind): AxisData | null { return null; } /** * Called when an event caused by the dragging of an axis happens. * @param pageId Source page where the drag data comes from. * @param eventKind Drag event kind. */ protected replaceAxis(pageId: string, eventKind: DragEventKind): void {} public static canDragAxisFromTo(source: ViewKind, destination: ViewKind): boolean { if (source.indexOf("Heatmap") >= 0) return destination.indexOf("Heatmap") >= 0; if (source.indexOf("Histogram") >= 0) return destination.indexOf("Histogram") >= 0; return false; } protected chooseTrellis(columns: string[]): void { if (columns.length === 0) { this.page.reportError("No acceptable columns found"); return; } const dialog = new Dialog("Choose column", "Select a column to group on."); dialog.addColumnSelectField("column", "column", columns, null, "The column that will be used to group on."); dialog.setAction(() => this.showTrellis(dialog.getColumnName("column"))); dialog.show(); } protected abstract showTrellis(colName: string): void; public getSourceAxisRange(sourcePageId: string, dragEvent: DragEventKind): BucketsInfo | null { const page = this.dataset.findPage(Number(sourcePageId)); if (page == null) return null; const source = page.getDataView() as ChartView<D>; if (source == null) return null; // Check compatibility const thisView = this.page.getDataView(); if (thisView == null) return null; if (!ChartView.canDragAxisFromTo(source.viewKind, thisView.viewKind)) { this.page.reportError("Cannot drag axis between these views"); return null; } const sourceAxis = source.getAxisData(dragEvent); if (sourceAxis == null) return null; // check that the two axes are on the same column const myAxis = this.getAxisData(dragEvent); if (myAxis == null) return null; if (sourceAxis.description.name !== myAxis.description.name || sourceAxis.description.kind !== myAxis.description.kind) { this.page.reportError("Axis is on different columns: " + sourceAxis.description.name + " and " + myAxis.description.name); return null; } return sourceAxis.dataRange; } /** * An implementation of dragMove that is suitable when * we track the precise mouse position. */ protected dragMoveRectangle(): boolean { this.onMouseMove(); if (!this.dragging) { return false; } this.moved = true; let ox = this.selectionOrigin!.x; let oy = this.selectionOrigin!.y; const position = d3mouse(this.surface!.getCanvas().node()); const x = position[0]; const y = position[1]; let width = x - ox; let height = y - oy; if (width < 0) { ox = x; width = -width; } if (height < 0) { oy = y; height = -height; } this.selectionRectangle .attr("x", ox) .attr("y", oy) .attr("width", width) .attr("height", height); return true; } protected dragMove(): boolean { this.onMouseMove(); if (!this.dragging) { return false; } this.moved = true; return true; } protected hideSelectionRectangle(): void { this.selectionRectangle .attr("width", 0) .attr("height", 0); } /** * Returns true if there has been some interesting dragging. */ protected dragEnd(): boolean { if (!this.dragging || !this.moved) { return false; } this.dragging = false; this.hideSelectionRectangle(); return true; } /** * Create a 2D filter that selects the specified rectangle of data. * The mouse coordinates xl, xr, yl, yr are within the canvas. */ protected filterSelectionRectangle(xl: number, xr: number, yl: number, yr: number, xAxisData: AxisData, yAxisData: AxisData): RangeFilterArrayDescription | null{ if (xAxisData.axis == null || yAxisData.axis == null) { return null; } xl -= this.surface!.leftMargin; xr -= this.surface!.leftMargin; yl -= this.surface!.topMargin; yr -= this.surface!.topMargin; const xRange = xAxisData.getFilter(xl, xr); const yRange = yAxisData.getFilter(yl, yr); return { filters: [xRange, yRange], complement: d3event.sourceEvent.ctrlKey }; } }
the_stack
import algoliasearchHelper, { SearchResults } from 'algoliasearch-helper'; import { createInstantSearch } from '../../../../test/mock/createInstantSearch'; import { createSearchClient } from '../../../../test/mock/createSearchClient'; import { createInitOptions, createRenderOptions, } from '../../../../test/mock/createWidget'; import { createSingleSearchResponse } from '../../../../test/mock/createAPIResponse'; import { wait } from '../../../../test/utils/wait'; import connectAnswers from '../connectAnswers'; const defaultRenderDebounceTime = 10; const defaultSearchDebounceTime = 10; describe('connectAnswers', () => { describe('Usage', () => { it('throws without render function', () => { expect(() => { // @ts-expect-error: test connectAnswers with invalid parameters connectAnswers()({}); }).toThrowErrorMatchingInlineSnapshot(` "The render function is not valid (received type Undefined). See documentation: https://www.algolia.com/doc/api-reference/widgets/answers/js/#connector" `); }); it('throws without `queryLanguages`', () => { expect(() => { // @ts-expect-error: test connectAnswers with invalid parameters connectAnswers(() => {})({}); }).toThrowErrorMatchingInlineSnapshot(` "The \`queryLanguages\` expects an array of strings. See documentation: https://www.algolia.com/doc/api-reference/widgets/answers/js/#connector" `); }); }); const setupTestEnvironment = ({ hits, attributesForPrediction = ['description'], renderDebounceTime = defaultRenderDebounceTime, searchDebounceTime = defaultSearchDebounceTime, }: { hits: any[]; attributesForPrediction?: string[]; renderDebounceTime?: number; searchDebounceTime?: number; }) => { const renderFn = jest.fn(); const unmountFn = jest.fn(); const client = createSearchClient({ // @ts-ignore-next-line initIndex() { return { findAnswers: () => Promise.resolve({ hits }), }; }, }); const instantSearchInstance = createInstantSearch({ client }); const makeWidget = connectAnswers(renderFn, unmountFn); const widget = makeWidget({ queryLanguages: ['en'], attributesForPrediction, renderDebounceTime, searchDebounceTime, }); const helper = algoliasearchHelper(client, '', {}); return { renderFn, unmountFn, instantSearchInstance, widget, helper, }; }; it('is a widget', () => { const render = jest.fn(); const unmount = jest.fn(); const makeWidget = connectAnswers(render, unmount); const widget = makeWidget({ queryLanguages: ['en'], attributesForPrediction: ['description'], }); expect(widget).toEqual( expect.objectContaining({ $$type: 'ais.answers', init: expect.any(Function), render: expect.any(Function), dispose: expect.any(Function), getRenderState: expect.any(Function), getWidgetRenderState: expect.any(Function), getWidgetSearchParameters: expect.any(Function), }) ); }); it('Renders during init and render', () => { const { renderFn, widget, instantSearchInstance, helper } = setupTestEnvironment({ hits: [] }); expect(renderFn).toHaveBeenCalledTimes(0); widget.init!( createInitOptions({ instantSearchInstance, state: helper.state, helper, }) ); expect(renderFn).toHaveBeenCalledTimes(1); expect(renderFn).toHaveBeenLastCalledWith( expect.objectContaining({ instantSearchInstance, hits: [], isLoading: false, widgetParams: { queryLanguages: ['en'], attributesForPrediction: ['description'], renderDebounceTime: 10, searchDebounceTime: 10, }, }), true ); widget.render!( createRenderOptions({ results: new SearchResults(helper.state, [ createSingleSearchResponse({ hits: [] }), ]), state: helper.state, instantSearchInstance, helper, }) ); expect(renderFn).toHaveBeenCalledTimes(2); expect(renderFn).toHaveBeenLastCalledWith( expect.objectContaining({ instantSearchInstance, hits: [], isLoading: false, widgetParams: { queryLanguages: ['en'], attributesForPrediction: ['description'], renderDebounceTime: 10, searchDebounceTime: 10, }, }), false ); }); it('renders empty hits when query is not given', () => { const { renderFn, widget, helper, instantSearchInstance } = setupTestEnvironment({ hits: [] }); widget.init!( createInitOptions({ instantSearchInstance, state: helper.state, helper, }) ); helper.state.query = ''; widget.render!( createRenderOptions({ results: new SearchResults(helper.state, [ createSingleSearchResponse({ hits: [] }), ]), state: helper.state, instantSearchInstance, helper, }) ); expect(renderFn).toHaveBeenNthCalledWith( 2, expect.objectContaining({ instantSearchInstance, hits: [], isLoading: false, widgetParams: { queryLanguages: ['en'], attributesForPrediction: ['description'], renderDebounceTime: 10, searchDebounceTime: 10, }, }), false ); }); it('renders loader and results when query is given', async () => { const hits = [{ title: '', objectID: 'a' }]; const { renderFn, instantSearchInstance, widget, helper } = setupTestEnvironment({ hits, }); widget.init!( createInitOptions({ instantSearchInstance, state: helper.state, helper, }) ); helper.state.query = 'a'; widget.render!( createRenderOptions({ state: helper.state, instantSearchInstance, helper, }) ); // render with isLoading and no hit expect(renderFn).toHaveBeenCalledTimes(2); expect(renderFn).toHaveBeenNthCalledWith( 2, expect.objectContaining({ hits: [], isLoading: true, }), false ); await wait(30); // 10(render debounce) + 10(search debounce) + 10(just to make sure) // render with hits const expectedHits = [{ title: '', objectID: 'a', __position: 1 }]; expect(renderFn).toHaveBeenCalledTimes(3); expect(renderFn).toHaveBeenNthCalledWith( 3, expect.objectContaining({ hits: expectedHits, isLoading: false, }), false ); }); it('debounces renders', async () => { const hits = [{ title: '', objectID: 'a' }]; const { renderFn, instantSearchInstance, widget, helper } = setupTestEnvironment({ hits, }); widget.init!( createInitOptions({ instantSearchInstance, state: helper.state, helper, }) ); helper.state.query = 'a'; widget.render!( createRenderOptions({ state: helper.state, instantSearchInstance, helper, }) ); // render with isLoading and no hit expect(renderFn).toHaveBeenCalledTimes(2); expect(renderFn).toHaveBeenNthCalledWith( 2, expect.objectContaining({ hits: [], isLoading: true, }), false ); // another query helper.state.query = 'ab'; widget.render!( createRenderOptions({ state: helper.state, instantSearchInstance, helper, }) ); // no debounce for rendering loader expect(renderFn).toHaveBeenCalledTimes(3); // wait for debounce await wait(30); const expectedHits = [{ title: '', objectID: 'a', __position: 1 }]; expect(renderFn).toHaveBeenCalledTimes(4); expect(renderFn).toHaveBeenNthCalledWith( 4, expect.objectContaining({ hits: expectedHits, isLoading: false, }), false ); // wait await wait(30); // but no more rendering expect(renderFn).toHaveBeenCalledTimes(4); }); describe('getRenderState', () => { it('returns the render state', () => { const { instantSearchInstance, widget, helper } = setupTestEnvironment({ hits: [], }); expect( widget.getRenderState( {}, createInitOptions({ instantSearchInstance, state: helper.state, helper, }) ) ).toEqual({ answers: { hits: [], isLoading: false, widgetParams: { queryLanguages: ['en'], attributesForPrediction: ['description'], renderDebounceTime: 10, searchDebounceTime: 10, }, }, }); widget.init!( createInitOptions({ instantSearchInstance, state: helper.state, helper, }) ); expect( widget.getRenderState( {}, createInitOptions({ instantSearchInstance, state: helper.state, helper, }) ) ).toEqual({ answers: { hits: [], isLoading: false, widgetParams: { queryLanguages: ['en'], attributesForPrediction: ['description'], renderDebounceTime: 10, searchDebounceTime: 10, }, }, }); }); }); describe('getWidgetRenderState', () => { it('returns the widget render state', async () => { const { instantSearchInstance, widget, helper } = setupTestEnvironment({ hits: [{ title: '', objectID: 'a' }], }); widget.init!( createInitOptions({ instantSearchInstance, state: helper.state, helper, }) ); helper.state.query = 'a'; widget.render!( createRenderOptions({ instantSearchInstance, state: helper.state, helper, }) ); // render the loading state expect( widget.getWidgetRenderState( createRenderOptions({ instantSearchInstance, state: helper.state, helper, }) ) ).toEqual({ hits: [], isLoading: true, widgetParams: { queryLanguages: ['en'], attributesForPrediction: ['description'], renderDebounceTime: 10, searchDebounceTime: 10, }, }); await wait(30); const expectedHits = [{ title: '', objectID: 'a', __position: 1 }]; expect( widget.getWidgetRenderState( createRenderOptions({ instantSearchInstance, state: helper.state, helper, }) ) ).toEqual({ hits: expectedHits, isLoading: false, widgetParams: { queryLanguages: ['en'], attributesForPrediction: ['description'], renderDebounceTime: 10, searchDebounceTime: 10, }, }); }); }); });
the_stack
import { css } from '@emotion/react'; import styled from '@emotion/styled'; import Button from '@theme/components/Button'; import Card from '@theme/components/Card'; import Checkbox from '@theme/components/Checkbox'; import Grid from '@theme/components/Grid'; import { ArrowIcon, ContactIcon, EnterIcon, ExternalIcon, PortfolioIcon, RSSIcon, TwitterIcon, } from '@theme/components/Icons'; import TextInput from '@theme/components/TextInput'; import Logo from '@theme/components/Logo'; import TextArea from '@theme/components/TextArea'; import Flex from '@theme/components/Flex'; import Glow from '@theme/components/Glow'; import Callout from '@theme/components/MDX/Callout'; import { VARIANT } from '@theme/components/MDX/Callout/Callout'; import CodeBlock from '@theme/components/MDX/Code/CodeBlock'; import LiveCodeBlock from '@theme/components/MDX/Code/LiveCodeBlock'; import InlineCode from '@theme/components/MDX/InlineCode'; import MDXBody, { ListItem } from '@theme/components/MDX/MDX'; import Pill, { PillVariant } from '@theme/components/Pill'; import Radio from '@theme/components/Radio'; import Range from '@theme/components/Range'; import Seo from '@theme/components/Seo'; import Switch from '@theme/components/Switch'; import Tooltip from '@theme/components/Tooltip'; import Tweet from '@theme/components/Tweet'; import Layout from '@theme/layout'; import { AnimatePresence } from 'framer-motion'; import { getTweets } from 'lib/tweets'; import dynamic from 'next/dynamic'; import React from 'react'; import { TransformedTweet } from 'types/tweet'; /** * TODO: * - Decouple Search in 2 components => Overlay and Command Center * - Rename Search * - Polish interface for lists => should be in global.css if possible? * - VARIANT callout should be renamed "CalloutVariant" * - Small Responsive issue with Live Code Block on medium size screen * * - MAKE LINK/ANCHOR COMPONENT WITH COOL ANIMATION (mayve link and navigation with arrow icon) * * NOTES: * - use var(--maximeheckel-colors-foreground) instead of --maximeheckel-border-color: hsl(var(--palette-gray-80)) ?? */ const Search = dynamic(() => import('@theme/components/Search'), { ssr: false, }); const HR = styled('hr')` height: 2px; width: 100%; background: hsl(var(--palette-gray-20)); border: none; margin-bottom: 16px; `; const Label = styled('p')` margin-bottom: 8px; `; export default function Design(props: { tweets: Record<string, TransformedTweet>; }) { const [showSearch, setShowSearch] = React.useState(false); const [email, setEmail] = React.useState(''); const colorScaleNumbers = React.useMemo( () => Array.from(Array(19).keys()).map((items) => { const num = (items + 1) * 5; if (num === 5) { return `0${num}`; } return num.toString(); }), [] ); const palette = ['gray', 'blue', 'red', 'orange', 'green', 'pink', 'indigo']; return ( <Layout footer> <Seo title="Design" /> <Grid columns="var(--layout-medium)" columnGap={20} rowGap={64} css={css` padding-top: 128px; padding-top: 64px; > * { grid-column: 2; } `} > <div> <h1 css={css` margin-bottom: 0px; `} > Components / Design System{' '} </h1> <HR /> <Grid gap={12} columns="140px 50px"> <Pill variant={PillVariant.WARNING}>Work In Progress</Pill> <Pill variant={PillVariant.INFO}>v1.0</Pill> </Grid> </div> <section id="logo"> <h2>Logo</h2> <Logo /> </section> <section id="Colors"> <h2>Colors</h2> <Grid gap={12}> Brand: <Tooltip id="brand" tooltipText="--brand"> <div css={css` width: 44px; height: 44px; border-radius: 50%; background: var(--maximeheckel-colors-brand); border: 2px solid var(--maximeheckel-border-color); `} /> </Tooltip> Background: <Tooltip id="background" tooltipText="--background"> <div css={css` width: 44px; height: 44px; border-radius: 50%; background: var(--maximeheckel-colors-background); border: 2px solid var(--maximeheckel-border-color); `} /> </Tooltip> Foreground: <Tooltip id="foreground" tooltipText="--foreground"> <div css={css` width: 44px; height: 44px; border-radius: 50%; background: var(--maximeheckel-colors-foreground); border: 2px solid var(--maximeheckel-border-color); `} /> </Tooltip> Typeface: <Grid columns="repeat(3, 44px)" gap={12}> <Tooltip id="typeface-primary" tooltipText="--typeface-primary"> <div css={css` width: 44px; height: 44px; border-radius: 50%; background: var(--maximeheckel-colors-typeface-primary); border: 2px solid var(--maximeheckel-border-color); `} /> </Tooltip> <Tooltip id="typeface-secondary" tooltipText="--typeface-secondary" > <div css={css` width: 44px; height: 44px; border-radius: 50%; background: var(--maximeheckel-colors-typeface-secondary); border: 2px solid var(--maximeheckel-border-color); `} /> </Tooltip> <Tooltip id="typeface-tertiary" tooltipText="--typeface-teriary"> <div css={css` width: 44px; height: 44px; border-radius: 50%; background: var(--maximeheckel-colors-typeface-tertiary); border: 2px solid var(--maximeheckel-border-color); `} /> </Tooltip> </Grid> </Grid> </section> <section id="Palette"> <h2>Palette</h2> <div css={css` display: grid; gap: 2rem; grid-template-columns: repeat(auto-fill, minmax(10rem, 1fr)); `} > {palette.map((paletteItem) => ( <div key={paletteItem} css={css` display: grid; grid-template-columns: repeat(auto-fill, minmax(2rem, 1fr)); margin-right: 12px; `} > {colorScaleNumbers.map((shade) => ( <Tooltip id={`${paletteItem}-${shade}`} key={`${paletteItem}-${shade}`} tooltipText={`--palette-${paletteItem}-${shade}`} > <div css={css` width: 44px; height: 44px; border-radius: 50%; background: hsl(var(--palette-${paletteItem}-${shade})); border: 2px solid var(--maximeheckel-border-color); `} /> </Tooltip> ))} </div> ))} </div> </section> <section id="typography"> <h2>Typography</h2> <Label>h1</Label> <h1>Almost before we knew it, we had left the ground.</h1> <Label>h2</Label> <h2>Almost before we knew it, we had left the ground.</h2> <Label>h3</Label> <h3>Almost before we knew it, we had left the ground.</h3> <Label>h4</Label> <h4>Almost before we knew it, we had left the ground.</h4> <Label>p</Label> <p>Almost before we knew it, we had left the ground.</p> <Label>p (bold)</Label> <p style={{ fontWeight: 700 }}> Almost before we knew it, we had left the ground. </p> <Label>p (italic)</Label> <p style={{ fontStyle: 'italic' }}> Almost before we knew it, we had left the ground. </p> </section> <section id="lists"> <h2>Lists</h2> <MDXBody /** * Cancel grid MDXBody here */ css={css` display: block; `} > <ul> {/*@ts-ignore */} <ListItem>First</ListItem> {/*@ts-ignore */} <ListItem>Second</ListItem> {/*@ts-ignore */} <ListItem>Third</ListItem> </ul> <ol> <li>First</li> <li>Second</li> <li>Third</li> </ol> </MDXBody> </section> <section id="button"> <h2>Buttons</h2> <Grid gap={24}> <Glow> <Button variant="primary">Button</Button> </Glow> <Button variant="primary">Button</Button> <Button variant="primary" endIcon={<ExternalIcon />}> Portfolio </Button> <Button variant="primary" startIcon={<TwitterIcon />}> Follow me! </Button> <Button variant="primary" disabled> Button </Button> <Button variant="secondary">Button</Button> <Button variant="secondary" endIcon={<ExternalIcon />}> Portfolio </Button> <Button variant="secondary" startIcon={<TwitterIcon />}> Follow me! </Button> <Button variant="secondary" disabled> Button </Button> <Button aria-label="Follow me on Twitter!" variant="icon" icon={<TwitterIcon />} /> <Button aria-label="Follow me on Twitter!" disabled variant="icon" icon={<TwitterIcon />} /> </Grid> </section> <section id="form-components"> <h2>Form Components</h2> <Flex gap={8}> <TextInput aria-label="Email" id="email-input" type="email" placeholder="hello@maximeheckel.com" onChange={(event) => setEmail(event.currentTarget.value)} value={email} /> <Button variant="primary">Subscribe</Button> </Flex> <br /> <Grid gap={24} columns="repeat(auto-fit, minmax(300px, 1fr))"> <TextInput label="Name" aria-label="Name" id="name-input" placeholder="Name" onChange={() => {}} /> <TextInput label="Name" aria-label="Name" id="name-input-disabled" placeholder="Name" disabled onChange={() => {}} value="Maxime Heckel" /> <TextInput aria-label="Email" id="email-input" type="email" placeholder="hello@maximeheckel.com" onChange={(event) => setEmail(event.currentTarget.value)} value={email} autoComplete="off" /> <TextInput aria-label="Email" id="email-input-disabled" type="email" disabled placeholder="hello@maximeheckel.com" onChange={() => {}} value="hello@maximeheckel.com" /> <TextInput aria-label="Password" id="password-input" type="password" placeholder="Password" onChange={() => {}} /> <TextInput aria-label="Password" id="password-input-disabled" type="password" disabled onChange={() => {}} value="supersecretpassword" /> <TextArea aria-label="Example Text" id="example-text-1" label="Example Text" onChange={() => {}} placeholder="Type some text here" resize="none" /> <TextArea aria-label="Example Text" disabled id="example-text-2" label="Example Text" onChange={() => {}} placeholder="Type some text here" resize="none" value={`Here's to the crazy ones. The misfits. The rebels. The troublemakers. The round pegs in the square holes. The ones who see things differently. They're not fond of rules. And they have no respect for the status quo. You can quote them, disagree with them, glorify or vilify them. About the only thing you can't do is ignore them. Because they change things. They push the human race forward. While some may see them as the crazy ones, we see genius. Because the people who are crazy enough to think they can change the world, are the ones who do.`} /> </Grid> <br /> <Grid gap={12} columns="repeat(2, minmax(2rem, 1fr))"> <Checkbox aria-label="Checkbox" id="checkbox1" label="Checkbox" /> <Checkbox aria-label="Checkbox" id="checkbox3" label="Checkbox" disabled /> <Checkbox aria-label="Checkbox" id="checkbox2" label="Checkbox" onChange={() => {}} checked /> <Checkbox aria-label="Checkbox" id="checkbox4" label="Checkbox" onChange={() => {}} checked disabled /> </Grid> <br /> <Grid gap={12} columns="repeat(2, minmax(2rem, 1fr))"> <Switch id="switch1" aria-label="Switch" label="Switch" /> <Switch id="switch2" aria-label="Switch" label="Switch" disabled /> <Switch id="switch3" aria-label="Switch" label="Switch" onChange={() => {}} toggled /> <Switch id="switch4" aria-label="Switch" label="Switch" disabled onChange={() => {}} toggled /> </Grid> <br /> <Grid gap={12} columns="repeat(2, minmax(2rem, 1fr))"> <Radio.Group name="options" direction="vertical" onChange={() => {}} > <Radio.Item id="option-1" value="option1" aria-label="Option 1" label="Option 1" /> <Radio.Item id="option-2" value="option2" aria-label="Option 2" label="Option 2" checked /> </Radio.Group> <Radio.Group name="options-disabled" direction="vertical" onChange={() => {}} > <Radio.Item id="radio-3" value="option3" aria-label="Option 3" label="Option 3" disabled /> <Radio.Item id="radio-4" value="option4" aria-label="Option 4" label="Option 4" disabled checked /> </Radio.Group> <Radio.Group name="options-horizontal" direction="horizontal" onChange={() => {}} > <Radio.Item id="option-5" value="option5" aria-label="Option 5" label="Option 5" /> <Radio.Item id="option-6" value="option6" aria-label="Option 6" label="Option 6" checked /> </Radio.Group> </Grid> <br /> <Grid gap={12} columns="repeat(2, minmax(2rem, 1fr))"> <Range id="range-1" aria-label="Range" label="Range" value={250} min={0} max={500} onChange={() => {}} /> <Range id="range-2" aria-label="Range" label="Range" value={250} min={0} max={500} onChange={() => {}} disabled /> </Grid> </section> <section id="cards"> <h2>Card</h2> <Grid rowGap={30}> <Card> <Card.Body>Base Card</Card.Body> </Card> <Card title="Title for the card"> <Card.Body> Card with <InlineCode>title</InlineCode> prop </Card.Body> </Card> <Card> <Card.Header>Some Custom Header</Card.Header> <Card.Body>Card With Custom Header</Card.Body> </Card> <Card> <div css={css` padding: 40px; display: flex; align-items: center; justify-content: center; `} > Card With custom Body </div> </Card> <Card depth={0}> <Card.Body> Card <InlineCode>depth={0}</InlineCode> </Card.Body> </Card> <Card depth={1}> <Card.Body> Card <InlineCode>depth={1}</InlineCode> </Card.Body> </Card> <Card depth={2}> <Card.Body> Card <InlineCode>depth={2}</InlineCode> </Card.Body> </Card> <Card depth={3}> <Card.Body> Card <InlineCode>depth={3}</InlineCode> </Card.Body> </Card> </Grid> </section> <section id="icons"> <h2>Icons</h2> <TwitterIcon stroke="var(--maximeheckel-colors-typeface-tertiary)" />{' '} <ExternalIcon stroke="var(--maximeheckel-colors-typeface-tertiary)" />{' '} <RSSIcon stroke="var(--maximeheckel-colors-typeface-tertiary)" />{' '} <ContactIcon stroke="var(--maximeheckel-colors-typeface-tertiary)" />{' '} <EnterIcon stroke="var(--maximeheckel-colors-typeface-tertiary)" />{' '} <PortfolioIcon stroke="var(--maximeheckel-colors-typeface-tertiary)" />{' '} <ArrowIcon stroke="var(--maximeheckel-colors-typeface-tertiary)" /> </section> <section id="tooltip"> <h2>Tooltip</h2> <Tooltip id="exampletooltip" tooltipText="@MaximeHeckel" tooltipVisuallyHiddenText="Follow Me on Twitter" > <div css={css` display: flex; align-items: center; justify-content: space-between; height: 50px; width: 150px; padding: 8px; `} aria-describedby="exampletooltip" > <TwitterIcon stroke="var(--maximeheckel-colors-typeface-tertiary)" />{' '} Hover Me! </div> </Tooltip> </section> <section id="pill"> <h2>Pill</h2> <Grid rowGap={32}> <div> <Pill variant={PillVariant.INFO}>Info Pill</Pill> </div> <div> <Pill variant={PillVariant.SUCCESS}>Success Pill</Pill> </div> <div> <Pill variant={PillVariant.WARNING}>Warning Pill</Pill> </div> <div> <Pill variant={PillVariant.DANGER}>Danger Pill</Pill> </div> </Grid> </section> <section id="callout"> <h2>Callout</h2> <Grid rowGap={32}> <div> <Callout variant={VARIANT.INFO}>Info Callout</Callout> </div> <div> <Callout variant={VARIANT.DANGER}>Danger Callout</Callout> </div> </Grid> </section> <section id="inline-code"> <h2>Inline Code</h2> <InlineCode>Some Inline Code</InlineCode> </section> <section id="code-block"> <h2>Code Block</h2> <Label>Basic</Label> <CodeBlock metastring="" language="javascript" codeString={`console.log("hello world") /** * Some comments */ function sayHi(name) { var message = \`hi \${name}\` return message; }`} /> <Label>With title and highlighting</Label> <CodeBlock metastring="{6-8} title=Code snippet title" language="javascript" codeString={`console.log("hello world") /** * Some comments */ function sayHi(name) { var message = \`hi \${name}\` return message; }`} /> <Label>Live (for React code only)</Label> <LiveCodeBlock live metastring="" language="javascript" codeString={`const WavingHand = () => ( <motion.div style={{ marginBottom: '-20px', marginRight: '-45px', paddingBottom: '20px', paddingRight: '45px', display: 'inline-block', }} animate={{ rotate: 20 }} transition={{ yoyo: Infinity, from: 0, duration: 0.2, ease: 'easeInOut', type: 'tween', }} > 👋 </motion.div> ); const Hi = () => ( <h1> Hi <WavingHand /> ! </h1> ); render(<Hi />);`} /> </section> <section id="command-center"> <h2>Command Center / Search </h2> <Button variant="primary" onClick={() => setShowSearch(true)}> Show Command Center </Button> <AnimatePresence> {showSearch ? ( <Search onClose={() => setShowSearch(false)} /> ) : null} </AnimatePresence> </section> <section id="tweet"> <h2>Tweet</h2> <Tweet tweet={props.tweets['1386013361809281024']} /> </section> </Grid> </Layout> ); } export async function getStaticProps() { const tweets = await getTweets(['1386013361809281024']); return { props: { tweets } }; }
the_stack
import "@plumier/testing" import { DefaultFacility, PlumierApplication, RouteMetadata } from "@plumier/core" import { CookieName, OAuthProviderOption, OAuthUser, redirectUri } from "@plumier/social-login" import Axios from "axios" import Csrf from "csrf" import { Context } from "koa" import { bind, Class, response, route } from "plumier" import qs from "querystring" import { fixture } from "../helper" import { error, getLoginUrl, params, portRegex, runServer } from "./helper" import { FakeOAuth10aFacility, oAuth10aServer } from "./oauth10a-server" import { FakeOAuth2Facility, oAuth20Server } from "./oauth20-server" /** * Run 2 fake oauth servers and a single oauth consumer server. */ async function appStub(controller: Class, mazeOpt?: OAuthProviderOption, googolOpt?: OAuthProviderOption, teeterOpt?: OAuthProviderOption, debugMode?: boolean) { // run fake oauth servers const mazeServer = await runServer(await oAuth20Server()) const googolServer = await runServer(await oAuth20Server()) const teeterServer = await runServer(await oAuth10aServer()) const debug = debugMode ? "debug" : "production" // run oauth consumer server on another port const koa = await fixture(controller) .set(new FakeOAuth2Facility("MazeBook", mazeServer.origin, mazeOpt)) .set(new FakeOAuth2Facility("Googol", googolServer.origin, googolOpt)) .set(new FakeOAuth10aFacility("Teeter", teeterServer.origin, teeterOpt)) .set({ mode: debug }) .initialize() const consumer = await runServer(koa) return { origin: consumer.origin, close: () => { mazeServer.server.close(); googolServer.server.close(); consumer.server.close() teeterServer.server.close() } } } async function login(url: string): Promise<{ status: number, profile: any, authUrl: string, cookie: string[] }> { const loginResp = await Axios.get(url) const loginUrl = getLoginUrl(loginResp.data) const cookie: string = (loginResp.headers["set-cookie"] as unknown as string[]).join("; ") var profileResp: any try { profileResp = await Axios.post(loginUrl, undefined, { headers: { cookie } }) } catch (e) { profileResp = e.response } return { status: profileResp.status, profile: profileResp.data, authUrl: loginUrl, cookie: loginResp.headers["set-cookie"] as any } } const opt = { clientSecret: "super secret", clientId: "1234" } class AuthController { @redirectUri() callback(@bind.oAuthUser() user: OAuthUser) { return user } } describe("OAuth 2.0", () => { it("Should login properly", async () => { const servers = await appStub(AuthController, opt, opt, opt) const mazeProfile = await login(`${servers.origin}/auth/mazebook/login`) const googolProfile = await login(`${servers.origin}/auth/googol/login`) expect({ ...mazeProfile, authUrl: "", cookie: "" }).toMatchSnapshot() expect({ ...googolProfile, authUrl: "", cookie: "" }).toMatchSnapshot() servers.close() }) it("Should save provider on cookie", async () => { const servers = await appStub(AuthController, opt, opt, opt) const { cookie } = await login(`${servers.origin}/auth/mazebook/login`) expect(cookie.find(x => x.match(CookieName.provider))).toMatchSnapshot() servers.close() }) it("Should save CSRF secret on cookie and CSRF token on state parameter", async () => { const servers = await appStub(AuthController, opt, opt, opt) const { cookie, authUrl } = await login(`${servers.origin}/auth/mazebook/login`) const tokenRegex = /^plum-oauth:csrf-secret=(.*?);.*/i const theCookie = cookie.find(x => x.match(CookieName.csrfSecret))! const secret = theCookie.match(tokenRegex)![1] const token = params(authUrl).state; const csrf = new Csrf() expect(csrf.verify(secret, token)).toBe(true) expect(theCookie.replace(secret, "")).toMatchSnapshot() servers.close() }) it("Should attach proper redirect URI on login url", async () => { const servers = await appStub(AuthController, opt, opt, opt) const { authUrl } = await login(`${servers.origin}/auth/mazebook/login`) const redirect = params(authUrl).redirect_uri.replace(portRegex, "") expect(redirect).toMatchSnapshot() servers.close() }) it("Should able to change login url", async () => { const servers = await appStub(AuthController, { clientSecret: "super secret", clientId: "1234", loginEndPoint: "/auth/mazebook/sign-in", }, opt, opt) const { status } = await login(`${servers.origin}/auth/mazebook/sign-in`) expect(status).toBe(200) servers.close() }) it("Should able add extra profile params", async () => { const servers = await appStub(AuthController, { clientSecret: "super secret", clientId: "1234", profileParams: { lorem: "ipsum", dolor: "sit" } }, opt, opt) const { authUrl, cookie, ...profile } = await login(`${servers.origin}/auth/mazebook/login`) expect(profile).toMatchSnapshot() servers.close() }) it("Should able to distinguish global callback and specific callback", async () => { class AuthController { @redirectUri() callback(@bind.oAuthUser() user: OAuthUser) { return user } @redirectUri("MazeBook" as any) fake(@bind.oAuthUser() user: OAuthUser) { return { lorem: "ipsum" } } } const servers = await appStub(AuthController, opt, opt, opt) const { authUrl, cookie, ...profile } = await login(`${servers.origin}/auth/mazebook/login`) expect(profile).toMatchSnapshot() servers.close() }) it("Should able to send postMessage UI", async () => { class AuthController { @redirectUri() callback(@bind.oAuthUser() user: OAuthUser) { return response.postMessage(user) } } const servers = await appStub(AuthController, opt, opt, opt) const profile = await login(`${servers.origin}/auth/mazebook/login`) expect(profile.profile.replace(/var message = '(.*)';/, "")).toMatchSnapshot() servers.close() }) it("Should able to set postMessage origin", async () => { class AuthController { @redirectUri() callback(@bind.oAuthUser() user: OAuthUser, @bind.ctx() ctx: Context) { return response.postMessage(user, ctx.origin) } } const servers = await appStub(AuthController, opt, opt, opt) const profile = await login(`${servers.origin}/auth/mazebook/login`) expect(profile.profile.replace(/var message = '(.*)';/, "").replace(portRegex, "")).toMatchSnapshot() servers.close() }) it("Should able to bind the raw profile", async () => { class AuthController { @redirectUri() callback(@bind.oAuthProfile() user: any) { return user } } const servers = await appStub(AuthController, opt, opt, opt) const profile = await login(`${servers.origin}/auth/mazebook/login`) expect(profile.profile).toMatchSnapshot() servers.close() }) it("Should able to bind the oauth access_token", async () => { class AuthController { @redirectUri() callback(@bind.oAuthToken() token: any) { return token } } const servers = await appStub(AuthController, opt, opt, opt) const profile = await login(`${servers.origin}/auth/mazebook/login`) expect(profile.profile).toMatchSnapshot() servers.close() }) it("Should check for invalid CSRF token", async () => { const servers = await appStub(AuthController, opt, opt, opt) const loginResp = await Axios.get(`${servers.origin}/auth/mazebook/login`) const loginUrl = /const REDIRECT = '(.*)'/.exec(loginResp.data)![1] const pars = params(loginUrl) delete pars.state const newLoginUrl = loginUrl.split("?")![0] + "?" + qs.stringify(pars) const cookie: string = (loginResp.headers["set-cookie"] as unknown as string[]).join("; ") const fn = jest.fn() try { await Axios.post(newLoginUrl, undefined, { headers: { cookie } }) } catch (e) { fn(e.response) } expect(fn.mock.calls[0][0].status).toBe(400) servers.close() }) }) describe("OAuth 1.0a", () => { it("Should login properly", async () => { const servers = await appStub(AuthController, opt, opt, opt) const teeterProfile = await login(`${servers.origin}/auth/teeter/login`) expect({ ...teeterProfile, authUrl: "", cookie: "" }).toMatchSnapshot() servers.close() }) it("Should show proper error when no oauth_token provided on cookie", async () => { const servers = await appStub(AuthController, opt, opt, opt) const loginResp = await Axios.get(`${servers.origin}/auth/teeter/login`) const loginUrl = /const REDIRECT = '(.*)'/.exec(loginResp.data)![1] const pars = params(loginUrl) delete pars.oauth_token const newLoginUrl = loginUrl.split("?")![0] + "?" + qs.stringify(pars) const cookie: string = (loginResp.headers["set-cookie"] as unknown as string[]).join("; ") const fn = jest.fn() try { await Axios.post(newLoginUrl, undefined, { headers: { cookie } }) } catch (e) { fn(e.response) } expect(fn.mock.calls[0][0].status).toBe(400) servers.close() }) }) describe("Virtual Routes", () => { it("Should print virtual routes properly", async () => { const mock = console.mock() const servers = await appStub(AuthController, opt, opt, opt, true) expect(mock.mock.calls).toMatchSnapshot() servers.close() }) it("Should provide proper route information for swagger", async () => { const fn = jest.fn() class MyFacility extends DefaultFacility { async initialize(app: Readonly<PlumierApplication>, routes: RouteMetadata[]) { fn(routes.find(x => x.kind === "VirtualRoute")) } } const mazeServer = await runServer(await oAuth20Server()) // run oauth consumer server on another port const koa = await fixture(AuthController) .set(new FakeOAuth2Facility("MazeBook", mazeServer.origin, { clientSecret: "super secret", clientId: "1234" })) .set(new MyFacility()) .set({ mode: "production" }) .initialize() const consumer = await runServer(koa) expect(fn.mock.calls).toMatchSnapshot() mazeServer.server.close(); consumer.server.close() }) }) describe("Durability", () => { it("Should use default environment variable", async () => { process.env.PLUM_MAZEBOOK_CLIENT_ID = "123" process.env.PLUM_MAZEBOOK_CLIENT_SECRET = "secret" process.env.PLUM_GOOGOL_CLIENT_ID = "123" process.env.PLUM_GOOGOL_CLIENT_SECRET = "secret" process.env.PLUM_TEETER_CLIENT_ID = "123" process.env.PLUM_TEETER_CLIENT_SECRET = "secret" const servers = await appStub(AuthController) const { status } = await login(`${servers.origin}/auth/mazebook/login`) expect(status).toBe(200) servers.close() delete process.env.PLUM_MAZEBOOK_CLIENT_ID delete process.env.PLUM_MAZEBOOK_CLIENT_SECRET delete process.env.PLUM_GOOGOL_CLIENT_ID delete process.env.PLUM_GOOGOL_CLIENT_SECRET delete process.env.PLUM_TEETER_CLIENT_ID delete process.env.PLUM_TEETER_CLIENT_SECRET }) it("Should throw error when no Client ID provided", async () => { const plum = fixture(AuthController) .set(new FakeOAuth2Facility("MazeBook", "http://mazebook.com", opt)) .set(new FakeOAuth2Facility("Googol", "http://googol.com", { clientSecret: "lorem" })) const fn = await error(plum.initialize()) expect(fn.mock.calls).toMatchSnapshot() }) it("Should throw error when no Client SECRET provided", async () => { const plum = fixture(AuthController) .set(new FakeOAuth2Facility("MazeBook", "http://mazebook.com", { clientId: "123" })) .set(new FakeOAuth2Facility("Googol", "http://googol.com", opt)) const fn = await error(plum.initialize()) expect(fn.mock.calls).toMatchSnapshot() }) it("Should throw error when no redirect uri provided", async () => { class AnimalController { @redirectUri("Googol" as any) callback(@bind.oAuthUser() user: OAuthUser) { return user } } const plum = fixture(AnimalController) .set(new FakeOAuth2Facility("Googol", "http://googol.com", opt)) .set(new FakeOAuth2Facility("MazeBook", "http://mazebook.com", { clientId: "123" })) const fn = await error(plum.initialize()) expect(fn.mock.calls).toMatchSnapshot() }) it("Should throw error when provided redirect uri with parameter", async () => { class AnimalController { @redirectUri() @route.get("/callback/:id") callback(id: string, @bind.oAuthUser() user: OAuthUser) { return user } } const plum = fixture(AnimalController) .set(new FakeOAuth2Facility("Googol", "http://googol.com", opt)) .set(new FakeOAuth2Facility("MazeBook", "http://mazebook.com", { clientId: "123" })) const fn = await error(plum.initialize()) expect(fn.mock.calls).toMatchSnapshot() }) it("Should throw error when provided non GET redirect uri", async () => { class AnimalController { @redirectUri() @route.post() callback(@bind.oAuthUser() user: OAuthUser) { return user } } const plum = fixture(AnimalController) .set(new FakeOAuth2Facility("Googol", "http://googol.com", opt)) .set(new FakeOAuth2Facility("MazeBook", "http://mazebook.com", { clientId: "123" })) const fn = await error(plum.initialize()) expect(fn.mock.calls).toMatchSnapshot() }) it("Should show proper error when internal OAuth server error occur", async () => { class AuthController { @redirectUri() @route.get("/auth/invalid-redirect") callback(@bind.oAuthUser() user: OAuthUser) { return user } } const servers = await appStub(AuthController, opt, opt, opt) const { authUrl, cookie, ...profile } = await login(`${servers.origin}/auth/mazebook/login`) expect(profile).toMatchSnapshot() servers.close() }) })
the_stack
const { describe, it, beforeEach, afterEach } = intern.getInterface('bdd'); import * as sinon from 'sinon'; import { tsx, node } from '@dojo/framework/core/vdom'; import global from '@dojo/framework/shim/global'; import { createHarness, stubEvent, compareResource, createTestResource } from '../../common/tests/support/test-helpers'; import resize from '@dojo/framework/core/middleware/resize'; import { createResizeMock } from '@dojo/framework/testing/mocks/middleware/resize'; import createNodeMock from '@dojo/framework/testing/mocks/middleware/node'; import assertionTemplate from '@dojo/framework/testing/harness/assertionTemplate'; import Icon from '../../icon'; import Select from '../../select'; import Pagination from '..'; import * as css from '../../theme/default/pagination.m.css'; import bundle from '../nls/Pagination'; const { messages } = bundle; const harness = createHarness([compareResource]); describe('Pagination', () => { const noop = () => {}; const prev = ( <button assertion-key="prev" key="prev" type="button" onclick={noop} classes={[css.prev, css.link]} > <div classes={css.icon}> <Icon type="leftIcon" /> </div> <div classes={css.label}>Previous</div> </button> ); const next = ( <button key="next" type="button" onclick={noop} classes={[css.next, css.link]}> <div classes={css.icon}> <Icon type="rightIcon" /> </div> <div classes={css.label}>{messages.next}</div> </button> ); const makeLinks = (start: number, end?: number) => { const links = []; if (!end) { end = start; } for (let i = start; i <= end; i++) { links.push( <button key={`numberedLink-${i}`} type="button" onclick={noop} classes={[css.numberedLink, css.link]} > {i.toString()} </button> ); } return links; }; const hiddenAssertion = assertionTemplate(() => ( <div key="root" classes={[undefined, css.root]}> <div key="links" classes={css.linksWrapper} styles={{ opacity: '0' }}> {prev} <div key="current" classes={css.currentPage}> 10 </div> {next} </div> </div> )); const visibleAssertion = assertionTemplate(() => ( <div key="root" classes={[undefined, css.root]}> <div key="links" classes={css.linksWrapper} styles={{ opacity: '1' }}> {prev} {...makeLinks(1, 9)} <div key="current" classes={css.currentPage}> 10 </div> {...makeLinks(11, 20)} {next} </div> </div> )); const sb = sinon.sandbox.create(); const resizeMock = createResizeMock(); let nodeMock: ReturnType<typeof createNodeMock>; function mockWidth(key: string, width: number) { nodeMock(key, { getBoundingClientRect() { return { width }; } }); } beforeEach(() => { sb.stub(global.window.HTMLDivElement.prototype, 'getBoundingClientRect').callsFake(() => ({ width: 45 })); nodeMock = createNodeMock(); }); afterEach(() => { sb.restore(); }); it('renders standard use case', () => { const h = harness(() => <Pagination total={20} initialPage={10} onPage={noop} />); h.expect(hiddenAssertion); }); it('renders nothing with only 1 page', () => { const h = harness(() => <Pagination total={1} onPage={noop} />); h.expect(() => false); }); it('raises page change events', () => {}); describe('page change events', () => { it('raises event from prev link', () => { const onPageChange = sinon.stub(); const h = harness(() => ( <Pagination total={20} initialPage={10} onPage={onPageChange} /> )); h.expect(hiddenAssertion); h.trigger('@prev', 'onclick', stubEvent); sinon.assert.calledWith(onPageChange, 9); }); it('raises event from next link', () => { const onPageChange = sinon.stub(); const h = harness(() => ( <Pagination total={20} initialPage={10} onPage={onPageChange} /> )); h.expect(hiddenAssertion); h.trigger('@next', 'onclick', stubEvent); sinon.assert.calledWith(onPageChange, 11); }); it('raises event from trailing links', () => { mockWidth('links', 10000); const onPageChange = sinon.stub(); const h = harness( () => <Pagination total={20} initialPage={10} onPage={onPageChange} />, { middleware: [[resize, resizeMock], [node, nodeMock]] } ); h.expect(visibleAssertion); h.trigger('@numberedLink-11', 'onclick', stubEvent); sinon.assert.calledWith(onPageChange, 11); }); it('raises event from leading links', () => { mockWidth('links', 1000); const onPageChange = sinon.stub(); const h = harness( () => <Pagination total={20} initialPage={10} onPage={onPageChange} />, { middleware: [[resize, resizeMock], [node, nodeMock]] } ); h.expect(visibleAssertion); h.trigger('@numberedLink-9', 'onclick', stubEvent); sinon.assert.calledWith(onPageChange, 9); }); it('ignores page change events when controlled', () => { mockWidth('links', 1000); const onPageChange = sinon.stub(); const h = harness(() => <Pagination total={20} page={10} onPage={onPageChange} />, { middleware: [[resize, resizeMock], [node, nodeMock]] }); h.expect(visibleAssertion); h.trigger('@numberedLink-9', 'onclick', stubEvent); h.expect(visibleAssertion); }); }); it('renders without "prev" button when there is no prev', () => { mockWidth('links', 1000); const h = harness(() => <Pagination total={3} initialPage={1} onPage={noop} />, { middleware: [[resize, resizeMock], [node, nodeMock]] }); h.expect( assertionTemplate(() => ( <div key="root" classes={[undefined, css.root]}> <div key="links" classes={css.linksWrapper} styles={{ opacity: '1' }}> <div key="current" classes={css.currentPage}> 1 </div> {...makeLinks(2, 3)} {next} </div> </div> )) ); }); it('renders without "next" button when there is no next', () => { mockWidth('links', 10000); const h = harness(() => <Pagination total={3} initialPage={3} onPage={noop} />, { middleware: [[resize, resizeMock], [node, nodeMock]] }); h.expect( assertionTemplate(() => ( <div key="root" classes={[undefined, css.root]}> <div key="links" classes={css.linksWrapper} styles={{ opacity: '1' }}> {prev} {...makeLinks(1, 2)} <div key="current" classes={css.currentPage}> 3 </div> </div> </div> )) ); }); it('renders with specified sibling count', () => { mockWidth('links', 1000); const h = harness( () => <Pagination total={20} initialPage={10} siblingCount={5} onPage={noop} />, { middleware: [[resize, resizeMock], [node, nodeMock]] } ); h.expect( visibleAssertion.replaceChildren('@links', () => [ prev, ...makeLinks(5, 9), <div key="current" classes={css.currentPage}> 10 </div>, ...makeLinks(11, 15), next ]) ); }); describe('page size selector', () => { const sizeSelectorAssertion = visibleAssertion.append(':root', () => [ <div classes={css.selectWrapper}> <Select key="page-size-select" initialValue="20" resource={createTestResource([{ value: '10' }, { value: '20' }], 'value')} onValue={noop} value={undefined} /> </div> ]); const pageSizes = [10, 20]; it('renders', () => { mockWidth('links', 1000); const h = harness( () => ( <Pagination initialPage={10} initialPageSize={20} total={20} onPage={noop} pageSizes={pageSizes} /> ), { middleware: [[resize, resizeMock], [node, nodeMock]] } ); h.expect(sizeSelectorAssertion); }); it('raises page-size change events', () => { mockWidth('links', 1000); const onPageSizeChange = sinon.stub(); const h = harness( () => ( <Pagination initialPage={10} initialPageSize={20} total={20} onPage={noop} onPageSize={onPageSizeChange} pageSizes={pageSizes} /> ), { middleware: [[resize, resizeMock], [node, nodeMock]] } ); h.expect(sizeSelectorAssertion); h.trigger('@page-size-select', 'onValue', { value: '10', label: '10' }); sinon.assert.calledWith(onPageSizeChange, 10); }); it('passes a value when controlled', () => { mockWidth('links', 1000); const onPageSizeChange = sinon.stub(); const h = harness( () => ( <Pagination initialPage={10} pageSize={20} total={20} onPage={noop} onPageSize={onPageSizeChange} pageSizes={pageSizes} /> ), { middleware: [[resize, resizeMock], [node, nodeMock]] } ); h.expect( sizeSelectorAssertion .setProperty('@page-size-select', 'value', '20') .setProperty('@page-size-select', 'initialValue', undefined) ); h.trigger('@page-size-select', 'onValue', { value: '10', label: '10' }); sinon.assert.calledWith(onPageSizeChange, 10); }); }); describe('sibling resizing', () => { it('limits siblings to siblingCount', () => { mockWidth('links', 1000); const h = harness( () => <Pagination total={20} initialPage={10} siblingCount={3} onPage={noop} />, { middleware: [[resize, resizeMock], [node, nodeMock]] } ); h.expect( visibleAssertion.setChildren('@links', () => [ prev, ...makeLinks(7, 9), <div key="current" classes={css.currentPage}> 10 </div>, ...makeLinks(11, 13), next ]) ); }); it('excludes siblings when insufficient space', () => { // available width is 400 // available width after next/prev/current is 400 - (45*3) = 265 // leaving room for 265 / 45 = 5.8 => 5 total siblings => 2 siblings on each side mockWidth('links', 400); const h = harness(() => <Pagination total={20} initialPage={10} onPage={noop} />, { middleware: [[resize, resizeMock], [node, nodeMock]] }); h.expect( visibleAssertion .setProperty('@links', 'styles', { opacity: '1' }) .setChildren('@links', () => [ prev, ...makeLinks(8, 9), <div key="current" classes={css.currentPage}> 10 </div>, ...makeLinks(11, 12), next ]) ); }); it('excludes siblings unevenly when applicable', () => { // available width is 400 // available width after next/prev/current is 400 - (45*3) = 265 // leaving room for 265 / 45 = 5.8 => 5 total siblings // but there's only one leading sibling possible. mockWidth('links', 400); const h = harness(() => <Pagination total={10} initialPage={2} onPage={noop} />, { middleware: [[resize, resizeMock], [node, nodeMock]] }); h.expect( visibleAssertion.setChildren('@links', () => [ prev, ...makeLinks(1), <div key="current" classes={css.currentPage}> 2 </div>, ...makeLinks(3, 6), next ]) ); }); }); });
the_stack
function test_base() { let tb: d3kit.Base; let another: d3kit.Base; let options: d3kit.ChartOptions; let margins: d3kit.ChartMargin; let offsets: [number, number]; let defopts: d3kit.ChartOptions; let w: number; let h: number; let d: [number, number]; let p: number; // create examples of margins, offsets, options margins = { top: 20, right: 20, bottom: 20, left: 20}; offsets = [0.5, 0.5]; options = { initialWidth: 400, initialHeight: 300, margin: margins, offset: offsets }; /** * Test constructor */ tb = new d3kit.Base(); // empty tb = new d3kit.Base(options); // with options another = new d3kit.Base(); /** * Test static function */ defopts = d3kit.Base.getDefaultOptions(); // without options defopts = d3kit.Base.getDefaultOptions(options); // with options /** * Test getters */ w = tb.width(); h = tb.height(); d = tb.dimension(); p = tb.pixelRatio(); margins = tb.margin(); offsets = tb.offset(); /** * Test setters */ tb.width(w); tb.height(h); tb.dimension(d); tb.margin(margins); tb.offset(offsets); tb.pixelRatio(window.devicePixelRatio); tb.copyDimension(another); /** * Test events */ tb.dimension(d).updateDimensionNow(); } function test_abstract_plate() { let el: Element; let margins: d3kit.ChartMargin; let offsets: [number, number]; let plate: d3kit.AbstractPlate; let options: d3kit.ChartOptions; let sel: d3.Selection<d3.BaseType, any, d3.BaseType, any>; // create a div, append to body, return Node as type Element el = document.body.appendChild(document.createElement('div')) as Element; // create example of options margins = { top: 20, right: 20, bottom: 20, left: 20}; offsets = [0.5, 0.5]; options = { initialWidth: 400, initialHeight: 300, margin: margins, offset: offsets }; /** * Test constructor */ plate = new d3kit.AbstractPlate(el); // without options plate = new d3kit.AbstractPlate(el, options); // with options /** * Test functions */ el = plate.getNode(); sel = plate.getSelection(); } function test_canvas_plate() { let el: Element; let margins: d3kit.ChartMargin; let offsets: [number, number]; let plate: d3kit.CanvasPlate; let options: d3kit.ChartOptions; let sel: d3.Selection<d3.BaseType, any, d3.BaseType, any>; let context: CanvasRenderingContext2D; // create example of options margins = { top: 20, right: 20, bottom: 20, left: 20}; offsets = [0.5, 0.5]; options = { initialWidth: 400, initialHeight: 300, margin: margins, offset: offsets }; /** * Test constructor */ plate = new d3kit.CanvasPlate(); // without options plate = new d3kit.CanvasPlate(options); // with options /** * Test functions */ el = plate.getNode(); sel = plate.getSelection(); plate = plate.clear(); context = plate.getContext2d(); } function test_div_plate() { let el: Element; let margins: d3kit.ChartMargin; let offsets: [number, number]; let plate: d3kit.DivPlate; let options: d3kit.ChartOptions; let sel: d3.Selection<d3.BaseType, any, d3.BaseType, any>; // create example of options margins = { top: 20, right: 20, bottom: 20, left: 20}; offsets = [0.5, 0.5]; options = { initialWidth: 400, initialHeight: 300, margin: margins, offset: offsets }; /** * Test constructor */ plate = new d3kit.DivPlate(); // without options plate = new d3kit.DivPlate(options); // with options /** * Test functions */ el = plate.getNode(); sel = plate.getSelection(); } function test_svg_plate() { let el: Element; let margins: d3kit.ChartMargin; let offsets: [number, number]; let plate: d3kit.SvgPlate; let options: d3kit.ChartOptions; let sel: d3.Selection<d3.BaseType, any, d3.BaseType, any>; let rootg: d3.Selection<d3.BaseType, any, d3.BaseType, any>; let layers: d3kit.LayerOrganizer; // create example of options margins = { top: 20, right: 20, bottom: 20, left: 20}; offsets = [0.5, 0.5]; options = { initialWidth: 400, initialHeight: 300, margin: margins, offset: offsets }; /** * Test constructor */ plate = new d3kit.SvgPlate(); // without options plate = new d3kit.SvgPlate(options); // with options /** * Test properties */ rootg = plate.rootG; layers = plate.layers; /** * Test functions */ el = plate.getNode(); sel = plate.getSelection(); } function test_abstract_chart() { let el: Element; let chart: d3kit.AbstractChart; let another: d3kit.AbstractChart; let options: d3kit.ChartOptions; let margins: d3kit.ChartMargin; let offsets: [number, number]; let defopts: d3kit.ChartOptions; let fitopts: d3kit.FitOptions; let watchop: d3kit.WatchOptions; let events: string[]; let w: number; let h: number; let d: [number, number]; let a: any; let b: boolean; let p: number; let plate: d3kit.AbstractPlate; // create a div, append to body, return Node as type Element el = document.body.appendChild(document.createElement('div')) as Element; // create examples of margins, offsets, options, fit options, watch options margins = { top: 20, right: 20, bottom: 20, left: 20}; offsets = [0.5, 0.5]; options = { initialWidth: 400, initialHeight: 300, margin: margins, offset: offsets }; fitopts = { mode: 'basic', width: '90%', ratio: 4 / 3 }; watchop = { mode: 'window', target: null, interval: 500 }; plate = new d3kit.AbstractPlate(el); /** * Test constructor */ chart = new d3kit.AbstractChart(el); // with element chart = new d3kit.AbstractChart('div#chart'); // with selector chart = new d3kit.AbstractChart(el, options); // with element+options chart = new d3kit.AbstractChart('div#chart', options); // with selector+options another = new d3kit.AbstractChart(el); /** * Test static functions */ defopts = d3kit.AbstractChart.getDefaultOptions(); events = d3kit.AbstractChart.getCustomEventNames(); /** * Test getters */ w = chart.getInnerWidth(); h = chart.getInnerHeight(); w = chart.width(); h = chart.height(); d = chart.dimension(); p = chart.pixelRatio(); a = chart.data(); margins = chart.margin(); offsets = chart.offset(); options = chart.options(); events = chart.getCustomEventNames(); /** * Test setters */ chart.width(w); chart.height(h); chart.dimension(d); chart.data([1, 2, 3, 4, 5, 6]); chart.margin(margins); chart.offset(offsets); chart.options(options); chart.pixelRatio(window.devicePixelRatio); chart.copyDimension(another); /** * Test booleans */ b = chart.hasData(); b = chart.hasNonZeroArea(); /** * Test plate functions */ plate = chart.addPlate('a-plate', plate, true); // with doNotAppend chart = chart.addPlate('a-plate', plate); // without doNotAppend chart = chart.removePlate('a-plate'); /** * Test events */ chart.dimension(d).updateDimensionNow(); chart.setupDispatcher(['click', 'mouseover']); chart.fit(fitopts); // without watch options chart.fit(fitopts, true); // with boolean for watch options chart.fit(fitopts, watchop); // with explicit watch options chart.stopFitWatcher(); chart.on('mouseover', () => { chart.stopFitWatcher(); }); chart.off('mouseover'); chart.destroy(); } function test_svg_chart() { let el: Element; let chart: d3kit.SvgChart; let options: d3kit.ChartOptions; let margins: d3kit.ChartMargin; let offsets: [number, number]; let svg: d3.Selection<d3.BaseType, any, d3.BaseType, any>; let rootg: d3.Selection<d3.BaseType, any, d3.BaseType, any>; let layers: d3kit.LayerOrganizer; let plate: d3kit.SvgPlate; // create a div, append to body, return Node as type Element el = document.body.appendChild(document.createElement('div')) as Element; // create examples of margins, offsets, options, fit options, watch options margins = { top: 20, right: 20, bottom: 20, left: 20}; offsets = [0.5, 0.5]; options = { initialWidth: 400, initialHeight: 300, margin: margins, offset: offsets }; /** * Test constructor */ chart = new d3kit.SvgChart(el); // with element chart = new d3kit.SvgChart('div#chart'); // with selector chart = new d3kit.SvgChart(el, options); // with element+options chart = new d3kit.SvgChart('div#chart', options); // with selector+options /** * Test plate functions */ plate = new d3kit.SvgPlate(); plate = chart.addPlate('a-plate', plate, true) as d3kit.SvgPlate; // with doNotAppend chart = chart.addPlate('a-plate', plate); // without doNotAppend chart = chart.removePlate('a-plate'); /** * Test properties */ svg = chart.svg; rootg = chart.rootG; layers = chart.layers; plate = chart.plate; } function test_canvas_chart() { let el: Element; let chart: d3kit.CanvasChart; let options: d3kit.ChartOptions; let margins: d3kit.ChartMargin; let offsets: [number, number]; let context: CanvasRenderingContext2D; // create a div, append to body, return Node as type Element el = document.body.appendChild(document.createElement('div')) as Element; // create examples of margins, offsets, options, fit options, watch options margins = { top: 20, right: 20, bottom: 20, left: 20}; offsets = [0.5, 0.5]; options = { initialWidth: 400, initialHeight: 300, margin: margins, offset: offsets, pixelRatio: 1 }; /** * Test constructor */ chart = new d3kit.CanvasChart(el); // with element chart = new d3kit.CanvasChart('div#chart'); // with selector chart = new d3kit.CanvasChart(el, options); // with element+options chart = new d3kit.CanvasChart('div#chart', options); // with selector+options /** * Test canvas chart functions */ context = chart.getContext2d(); options = d3kit.CanvasChart.getDefaultOptions(); chart.clear(); } function test_hybrid_chart() { let el: Element; let chart: d3kit.HybridChart; let options: d3kit.ChartOptions; let margins: d3kit.ChartMargin; let offsets: [number, number]; let svg: d3.Selection<d3.BaseType, any, d3.BaseType, any>; let rootg: d3.Selection<d3.BaseType, any, d3.BaseType, any>; let layers: d3kit.LayerOrganizer; let plate: d3kit.SvgPlate; let context: CanvasRenderingContext2D; // create a div, append to body, return Node as type Element el = document.body.appendChild(document.createElement('div')) as Element; // create examples of margins, offsets, options, fit options, watch options margins = { top: 20, right: 20, bottom: 20, left: 20}; offsets = [0.5, 0.5]; options = { initialWidth: 400, initialHeight: 300, margin: margins, offset: offsets }; /** * Test constructor */ chart = new d3kit.HybridChart(el); // with element chart = new d3kit.HybridChart('div#chart'); // with selector chart = new d3kit.HybridChart(el, options); // with element+options chart = new d3kit.HybridChart('div#chart', options); // with selector+options /** * Test plate functions */ plate = new d3kit.SvgPlate(); plate = chart.addPlate('a-plate', plate, true) as d3kit.SvgPlate; // with doNotAppend chart = chart.addPlate('a-plate', plate); // without doNotAppend chart = chart.removePlate('a-plate'); /** * Test SVG properties */ svg = chart.svg; rootg = chart.rootG; layers = chart.layers; plate = chart.plate; /** * Test canvas chart functions */ context = chart.getContext2d(); options = d3kit.CanvasChart.getDefaultOptions(); chart.clear(); } function test_layer_organizer() { let selection: d3.Selection<d3.BaseType, any, d3.BaseType, any>; let layer: d3.Selection<d3.BaseType, any, d3.BaseType, any>; let layers: d3kit.LayerOrganizer; let hasXAxis: boolean; selection = d3.select('svg'); /** * Test constructor */ layers = new d3kit.LayerOrganizer(selection); // without specifying tag layers = new d3kit.LayerOrganizer(selection, 'div'); // specifying tag /** * Test layer creation */ layers.create('graph'); layers.create(['graph', 'highlight']); layers.create({graph: [{axes: ['x-axis', 'y-axis']}, {labels: ['x-label', 'y-label', 'title']}]}); layers.create([{axes: ['x-axis', 'y-axis']}, {labels: ['x-label', 'y-label', 'title']}]); /** * Test other layer organizer functions */ layer = layers.get('x-axis'); hasXAxis = layers.has('x-axis'); } function test_helper() { const simple1: {} = { one: 1 }; const simple2: {} = { two: 2 }; const complex: {} = { fruit: ["apple", "pear", "grape"], prez: { fn: "Barack", ln: "Obama" } }; const anObject: {} = { this: "isanobject"}; let merged1: {}; let merged2: {}; let isObj: boolean; let aFuncxn = () => "this is a function"; let isFunc: boolean; let kebabed: string; let dbouncd: any; let throtld: any; dbouncd = d3kit.helper.debounce(aFuncxn, 300); merged1 = d3kit.helper.extend(simple1, simple2); merged2 = d3kit.helper.deepExtend(simple1, complex); aFuncxn = d3kit.helper.functor(aFuncxn); // with a function argument aFuncxn = d3kit.helper.functor(simple1); // with a value argument isObj = d3kit.helper.isObject(anObject); isFunc = d3kit.helper.isFunction(aFuncxn); kebabed = d3kit.helper.kebabCase("a string to convert to kebab case"); throtld = d3kit.helper.throttle(aFuncxn, 300); }
the_stack
import expect from 'expect'; import { gasLimit, createConnection, deploy, transaction, aliceKeypair, daveKeypair } from './index'; import { ContractPromise } from '@polkadot/api-contract'; import { ApiPromise } from '@polkadot/api'; import { KeyringPair } from '@polkadot/keyring/types'; import type { Codec } from '@polkadot/types/types'; const MINIMUM_LIQUIDITY = BigInt(1000); const TOTAL_SUPPLY = BigInt(10000e18); describe('UniswapV2Pair', () => { let conn: ApiPromise; let factory: ContractPromise; let pair: ContractPromise; let token0: ContractPromise; let token1: ContractPromise; let alice: KeyringPair; let dave: KeyringPair; beforeEach(async function () { conn = await createConnection(); alice = aliceKeypair(); dave = daveKeypair(); // Upload UniswapV2Pair contract code so that it can instantiated from the factory // there probably is a better way of doing this than deploying a contract. Patches welcome. const pairTmp = await deploy(conn, alice, 'UniswapV2Pair.contract'); const pairAbi = pairTmp.abi; let deploy_contract = await deploy(conn, alice, 'UniswapV2Factory.contract', alice.address); factory = new ContractPromise(conn, deploy_contract.abi, deploy_contract.address); const tokenA_contract = await deploy(conn, alice, 'ERC20.contract', TOTAL_SUPPLY); const tokenA = new ContractPromise(conn, tokenA_contract.abi, tokenA_contract.address); const tokenB_contract = await deploy(conn, alice, 'ERC20.contract', TOTAL_SUPPLY); const tokenB = new ContractPromise(conn, tokenB_contract.abi, tokenB_contract.address); let tx = factory.tx.createPair({ gasLimit }, tokenA.address, tokenB.address); await transaction(tx, alice); const { output: get_pair } = await factory.query.getPair(alice.address, {}, tokenA.address, tokenB.address); pair = new ContractPromise(conn, pairAbi, get_pair!.toString()); const { output: token0_address } = await pair.query.token0(alice.address, {}); if (tokenA.address.toString() == token0_address!.toString()) { token0 = tokenA; token1 = tokenB; } else { expect(tokenB.address.toString()).toEqual(token0_address!.toString()); token0 = tokenB; token1 = tokenA; } }); afterEach(async function () { await conn.disconnect(); }); it('mint', async () => { const token0Amount = BigInt(1e18) const token1Amount = BigInt(4e18) let tx = token0.tx.transfer({ gasLimit }, pair.address, token0Amount); await transaction(tx, alice); tx = token1.tx.transfer({ gasLimit }, pair.address, token1Amount); await transaction(tx, alice); const expectedLiquidity = BigInt(2e18) tx = pair.tx.mint({ gasLimit }, alice.address); await transaction(tx, alice); const { output: totalSupply } = await pair.query.totalSupply(alice.address, {}); expect(totalSupply?.eq(expectedLiquidity)).toBeTruthy(); const { output: bal } = await pair.query.balanceOf(alice.address, {}, alice.address); expect(bal?.eq(expectedLiquidity - MINIMUM_LIQUIDITY)).toBeTruthy(); const { output: bal0 } = await token0.query.balanceOf(alice.address, {}, pair.address); expect(bal0?.eq(token0Amount)).toBeTruthy(); const { output: bal1 } = await token1.query.balanceOf(alice.address, {}, pair.address); expect(bal1?.eq(token1Amount)).toBeTruthy(); const { output: reserves } = await pair.query.getReserves(alice.address, {}); // surely there must be a better way. let v: any = reserves; let v0: Codec = v._reserve0; expect(v0.eq(token0Amount)).toBeTruthy(); let v1: Codec = v._reserve1; expect(v1.eq(token1Amount)).toBeTruthy(); }) async function addLiquidity(token0Amount: BigInt, token1Amount: BigInt) { let tx = token0.tx.transfer({ gasLimit }, pair.address, token0Amount); await transaction(tx, alice); tx = token1.tx.transfer({ gasLimit }, pair.address, token1Amount); await transaction(tx, alice); tx = pair.tx.mint({ gasLimit }, alice.address); await transaction(tx, alice); } it('swap:token0', async () => { const token0Amount = BigInt(5e18) const token1Amount = BigInt(10e18) await addLiquidity(token0Amount, token1Amount) const swapAmount = BigInt(1e18) const expectedOutputAmount = BigInt(1662497915624478906) let tx = token0.tx.transfer({ gasLimit }, pair.address, swapAmount); await transaction(tx, alice); tx = pair.tx.swap({ gasLimit }, 0, expectedOutputAmount, alice.address, ''); await transaction(tx, alice); const { output: reserves } = await pair.query.getReserves(alice.address, {}); // surely there must be a better way. let v: any = reserves; let v0: Codec = v._reserve0; expect(v0.eq(token0Amount + swapAmount)).toBeTruthy(); let v1: Codec = v._reserve1; expect(v1.eq(token1Amount - expectedOutputAmount)).toBeTruthy(); const { output: bal0 } = await token0.query.balanceOf(alice.address, {}, pair.address); expect(bal0?.eq(token0Amount + swapAmount)).toBeTruthy(); const { output: bal1 } = await token1.query.balanceOf(alice.address, {}, pair.address); expect(bal1?.eq(token1Amount - expectedOutputAmount)).toBeTruthy(); const { output: returnTotalSupplyToken0 } = await token0.query.totalSupply(alice.address, {}); const { output: returnTotalSupplyToken1 } = await token1.query.totalSupply(alice.address, {}); const { output: walletBal0 } = await token0.query.balanceOf(alice.address, {}, alice.address); const { output: walletBal1 } = await token1.query.balanceOf(alice.address, {}, alice.address); const totalSupplyToken0 = BigInt(returnTotalSupplyToken0!.toString()); const totalSupplyToken1 = BigInt(returnTotalSupplyToken1!.toString()); expect(walletBal0?.eq(totalSupplyToken0 - token0Amount - swapAmount)).toBeTruthy(); expect(walletBal1?.eq(totalSupplyToken1 - token1Amount + expectedOutputAmount)).toBeTruthy(); }) it('swap:token1', async () => { const token0Amount = BigInt(5e18) const token1Amount = BigInt(10e18) await addLiquidity(token0Amount, token1Amount) const swapAmount = BigInt(1e18) const expectedOutputAmount = BigInt(453305446940074565) let tx = token1.tx.transfer({ gasLimit }, pair.address, swapAmount); await transaction(tx, alice); tx = pair.tx.swap({ gasLimit }, expectedOutputAmount, 0, alice.address, ''); await transaction(tx, alice); const { output: reserves } = await pair.query.getReserves(alice.address, {}); // surely there must be a better way. let v: any = reserves; let v0: Codec = v._reserve0; expect(v0.eq(token0Amount - expectedOutputAmount)).toBeTruthy(); let v1: Codec = v._reserve1; expect(v1.eq(token1Amount + swapAmount)).toBeTruthy(); const { output: bal0 } = await token0.query.balanceOf(alice.address, {}, pair.address); expect(bal0?.eq(token0Amount - expectedOutputAmount)).toBeTruthy(); const { output: bal1 } = await token1.query.balanceOf(alice.address, {}, pair.address); expect(bal1?.eq(token1Amount + swapAmount)).toBeTruthy(); const { output: returnTotalSupplyToken0 } = await token0.query.totalSupply(alice.address, {}); const { output: returnTotalSupplyToken1 } = await token1.query.totalSupply(alice.address, {}); const { output: walletBal0 } = await token0.query.balanceOf(alice.address, {}, alice.address); const { output: walletBal1 } = await token1.query.balanceOf(alice.address, {}, alice.address); const totalSupplyToken0 = BigInt(returnTotalSupplyToken0!.toString()); const totalSupplyToken1 = BigInt(returnTotalSupplyToken1!.toString()); expect(walletBal0?.eq(totalSupplyToken0 - token0Amount + expectedOutputAmount)).toBeTruthy(); expect(walletBal1?.eq(totalSupplyToken1 - token1Amount - swapAmount)).toBeTruthy(); }) it('burn', async () => { const token0Amount = BigInt(3e18) const token1Amount = BigInt(3e18) await addLiquidity(token0Amount, token1Amount) const expectedLiquidity = BigInt(3e18) let tx = pair.tx.transfer({ gasLimit }, pair.address, expectedLiquidity - MINIMUM_LIQUIDITY); await transaction(tx, alice); tx = pair.tx.burn({ gasLimit }, alice.address); await transaction(tx, alice); const { output: walletBal0 } = await pair.query.balanceOf(alice.address, {}, alice.address); expect(walletBal0?.eq(0)).toBeTruthy(); const { output: pairTotalSupply } = await pair.query.totalSupply(alice.address, {}); expect(pairTotalSupply?.eq(MINIMUM_LIQUIDITY)).toBeTruthy(); const { output: token0pairBal } = await token0.query.balanceOf(alice.address, {}, pair.address); expect(token0pairBal?.eq(1000)).toBeTruthy(); const { output: token1pairBal } = await token1.query.balanceOf(alice.address, {}, pair.address); expect(token1pairBal?.eq(1000)).toBeTruthy(); const { output: retToken0TotalSupply } = await token0.query.totalSupply(alice.address, {}); const { output: retToken1TotalSupply } = await token1.query.totalSupply(alice.address, {}); const totalSupplyToken0 = BigInt(retToken0TotalSupply!.toString()); const totalSupplyToken1 = BigInt(retToken1TotalSupply!.toString()); const { output: bal0 } = await token0.query.balanceOf(alice.address, {}, alice.address); expect(bal0?.eq(totalSupplyToken0 - 1000n)).toBeTruthy(); const { output: bal1 } = await token1.query.balanceOf(alice.address, {}, alice.address); expect(bal1?.eq(totalSupplyToken1 - 1000n)).toBeTruthy(); }) });
the_stack
let AWasPressed: boolean let BWasPressed: boolean let wasShake: boolean let dots025: Image dots025 = images.createImage(` . . . . . # . . . . # # . . . # # # . . # # # # . # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . . . . # # . . . # # # . . # # # # . # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . . . . # # . . . # # # . . # # # # . # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . . . . # # . . . # # # . . # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . . . . # # . . . # # # . . # # # # . # # # # # `) let tests = "DABPXYZSCT" let test = 0 let prevTest = -1 startIOMonitor() while (true) { let testLetter = tests[test] let autoRun = false if (testLetter == "D" || testLetter == "A" || testLetter == "B") { autoRun = true } if (!(test == prevTest)) { basic.showString(tests[test], 200) prevTest = test } if (AWasPressed || autoRun) { AWasPressed = false if (testLetter == "D") { testDisplay() test = test + 1 } else if (testLetter == "A") { testButtonA() test = test + 1 } else if (testLetter == "B") { testButtonB() test = test + 1 } else if (testLetter == "P") { testPads() } else if (testLetter == "X") { testTiltX() } else if (testLetter == "Y") { testTiltY() } else if (testLetter == "Z") { testTiltZ() } else if (testLetter == "S") { testShake() } else if (testLetter == "C") { testCompass() } else if (testLetter == "T") { testTemperature() } else { // end of tests basic.showLeds(` . . . . . . . . . # . . . # . # . # . . . # . . . `, 400) } prevTest = -1 AWasPressed = false BWasPressed = false } else if (BWasPressed) { BWasPressed = false if (test < tests.length - 1) { test = test + 1 } else { test = 3 } } else { basic.pause(100) } } /** * flash all LEDs 5 times */ function testDisplay() { for (let i = 0; i < 5; i++) { basic.plotLeds(` # # # # # # # # # # # # # # # # # # # # # # # # # `) basic.pause(200) basic.clearScreen() basic.pause(200) } // cycle all LEDs from 1 to 25 basic.showAnimation(` # . . . . # # . . . # # # . . # # # # . # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # . . . . . . . . . . . . . . . . . . . . . . . . . # . . . . # # . . . # # # . . # # # # . # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . . . . # # . . . # # # . . # # # # . # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . . . . # # . . . # # # . . # # # # . # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . . . . # # . . . # # # . . # # # # . # # # # # `, 400) } function testButtonA() { basic.plotLeds(` . . # . . . # . # . . # # # . . # . # . . # . # . `) // wait for A pressed while (!input.buttonIsPressed(Button.A)) { basic.pause(100) } basic.plotLeds(` . # . . . # . # . . # # # . . # . # . . # . # . . `) // wait for A released while (input.buttonIsPressed(Button.A)) { basic.pause(100) } basic.plotLeds(` . . # . . . # . # . . # # # . . # . # . . # . # . `) basic.pause(1000) } function testTiltX() { basic.clearScreen() let prevx = 0 while (!AWasPressed && !BWasPressed) { basic.pause(100) let x = input.acceleration(Dimension.X) let x2 = x / 512 + 2 let x3 = Math.clamp(0, 4, x2) // sticky trace led.plot(x3, 0) // middle line is actual/live if (x3 != prevx) { led.unplot(prevx, 2) prevx = x3 } led.plot(x3, 2) // bottom line is -4G, -2G, 1G, +2G, +4G if (x <= -2048) { led.plot(0, 4) } else if (x <= -1024) { led.plot(1, 4) } else if (x <= 1024) { led.plot(2, 4) } else if (x <= 2048) { led.plot(3, 4) } else { led.plot(4, 4) } } } function testShake() { wasShake = false basic.plotLeds(` . . . . . . . . . . . . # . . . . . . . . . . . . `) while (!AWasPressed && !BWasPressed) { if (wasShake) { wasShake = false basic.plotLeds(` # # # # # # # # # # # # # # # # # # # # # # # # # `) basic.pause(500) basic.plotLeds(` . . . . . . . . . . . . # . . . . . . . . . . . . `) } else { basic.pause(100) } } } function testCompass() { if (input.compassHeading() < 0) { input.calibrate() } basic.clearScreen() while (!AWasPressed && !BWasPressed) { let d = input.compassHeading() d = d / 22 d = Math.clamp(0, 15, d) d = (d + 2) % 16 if (d < 4) { led.plot(d, 0) } else if (d < 8) { led.plot(4, d - 4) } else if (d < 12) { led.plot(4 - d - 8, 4) } else { led.plot(0, 4 - d - 12) } basic.pause(100) } } function testPads() { let TESTSPEED = 500 AWasPressed = false BWasPressed = false // Make sure all pins are inputs, before test starts let p0 = pins.digitalReadPin(DigitalPin.P0) let p1 = pins.digitalReadPin(DigitalPin.P1) let p2 = pins.digitalReadPin(DigitalPin.P2) let ok0 = 0 let ok1 = 0 let ok2 = 0 while (!AWasPressed && !BWasPressed) { basic.clearScreen() // ## P0 out low, read from P1 and P2 ok0 = 0 pins.digitalWritePin(DigitalPin.P0, 0) basic.pause(TESTSPEED) p1 = pins.digitalReadPin(DigitalPin.P1) p2 = pins.digitalReadPin(DigitalPin.P2) if (p1 == 0) { led.plot(0, 0) ok0 = ok0 + 1 } if (p2 == 0) { led.plot(1, 0) ok0 = ok0 + 1 } // ## P0 out high, read from P1 and P2 pins.digitalWritePin(DigitalPin.P0, 1) basic.pause(TESTSPEED) p1 = pins.digitalReadPin(DigitalPin.P1) p2 = pins.digitalReadPin(DigitalPin.P2) if (p1 == 1) { led.plot(2, 0) ok0 = ok0 + 1 } if (p2 == 1) { led.plot(3, 0) ok0 = ok0 + 1 } // set back to an input p0 = pins.digitalReadPin(DigitalPin.P0) // ## P1 out low, read from P0 and P2 ok1 = 0 pins.digitalWritePin(DigitalPin.P1, 0) basic.pause(TESTSPEED) p0 = pins.digitalReadPin(DigitalPin.P0) p2 = pins.digitalReadPin(DigitalPin.P2) if (p0 == 0) { led.plot(0, 1) ok1 = ok1 + 1 } if (p2 == 0) { led.plot(1, 1) ok1 = ok1 + 1 } // ## P1 out high, read from P0 and P2 pins.digitalWritePin(DigitalPin.P1, 1) basic.pause(TESTSPEED) p0 = pins.digitalReadPin(DigitalPin.P0) p2 = pins.digitalReadPin(DigitalPin.P2) if (p0 == 1) { led.plot(2, 1) ok1 = ok1 + 1 } if (p2 == 1) { led.plot(3, 1) ok1 = ok1 + 1 } // set back to an input p0 = pins.digitalReadPin(DigitalPin.P1) // ## P2 out low, read from P0 and P1 ok2 = 0 pins.digitalWritePin(DigitalPin.P2, 0) basic.pause(TESTSPEED) p0 = pins.digitalReadPin(DigitalPin.P0) p1 = pins.digitalReadPin(DigitalPin.P1) if (p0 == 0) { led.plot(0, 2) ok2 = ok2 + 1 } if (p1 == 0) { led.plot(1, 2) ok2 = ok2 + 1 } // ## P2 out high, read from P0 and P1 pins.digitalWritePin(DigitalPin.P2, 1) basic.pause(TESTSPEED) p0 = pins.digitalReadPin(DigitalPin.P0) p1 = pins.digitalReadPin(DigitalPin.P1) if (p0 == 1) { led.plot(2, 2) ok2 = ok2 + 1 } if (p1 == 1) { led.plot(3, 2) ok2 = ok2 + 1 } p2 = pins.digitalReadPin(DigitalPin.P2) // ## Assess final test status if (ok0 == 4) { led.plot(4, 0) } basic.pause(TESTSPEED) if (ok1 == 4) { led.plot(4, 1) } basic.pause(TESTSPEED) if (ok2 == 4) { led.plot(4, 2) } basic.pause(TESTSPEED) if (ok0 + ok1 + ok2 == 12) { // all tests passed led.plot(4, 4) } // ## Test cycle finished basic.pause(1000) } // intentionally don't clear A and B flags, so main loop can process them. } /** * - show number of dots on screen (0..25) to represent temperature in celcius */ function testTemperature() { while (!AWasPressed && !BWasPressed) { let temp = input.temperature() - 10 temp = Math.clamp(0, 25, temp) dots025.plotFrame(temp) basic.pause(500) } } function testButtonB() { basic.plotLeds(` . # # . . . # . # . . # # . . . # . # . . # # . . `) // wait for B pressed while (!input.buttonIsPressed(Button.B)) { basic.pause(100) } basic.plotLeds(` . . # # . . . # . # . . # # . . . # . # . . # # . `) // wait for B released while (input.buttonIsPressed(Button.B)) { basic.pause(100) } basic.plotLeds(` . # # . . . # . # . . # # . . . # . # . . # # . . `) basic.pause(1000) } function testTiltY() { basic.clearScreen() let prevy = 0 while (!AWasPressed && !BWasPressed) { basic.pause(100) let y = input.acceleration(Dimension.Y) let y2 = y / 512 + 2 let y3 = Math.clamp(0, 4, y2) // sticky trace led.plot(0, y3) // middle line is actual/live if (y3 != prevy) { led.unplot(2, prevy) prevy = y3 } led.plot(2, y3) // bottom line is -4G, -2G, 1G, +2G, +4G if (y <= -2048) { led.plot(4, 0) } else if (y <= -1024) { led.plot(4, 1) } else if (y <= 1024) { led.plot(4, 2) } else if (y <= 2048) { led.plot(4, 3) } else { led.plot(4, 4) } } } function testTiltZ() { basic.clearScreen() while (!AWasPressed && !BWasPressed) { let z = input.acceleration(Dimension.Z) if (z < -2000) { basic.plotLeds(` # . . . # # . . . # # . . . # # . . . # # . . . # `) } else if (z <= -1030) { basic.plotLeds(` . # . # . . # . # . . # . # . . # . # . . # . # . `) } else if (z <= 1000) { basic.plotLeds(` . . # . . . . # . . . . # . . . . # . . . . # . . `) } else if (z <= 1030) { basic.plotLeds(` . . . . . . . . . . # # # # # . . . . . . . . . . `) } else if (z <= 2000) { basic.plotLeds(` . . . . . # # # # # . . . . . # # # # # . . . . . `) } else { basic.plotLeds(` # # # # # . . . . . . . . . . . . . . . # # # # # `) } basic.pause(100) } } function startIOMonitor() { input.onButtonPressed(Button.A, () => { AWasPressed = true }) input.onButtonPressed(Button.B, () => { BWasPressed = true }) input.onShake(() => { wasShake = true }) }
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { MsixPackages } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { DesktopVirtualizationAPIClient } from "../desktopVirtualizationAPIClient"; import { MsixPackage, MsixPackagesListNextOptionalParams, MsixPackagesListOptionalParams, MsixPackagesGetOptionalParams, MsixPackagesGetResponse, MsixPackagesCreateOrUpdateOptionalParams, MsixPackagesCreateOrUpdateResponse, MsixPackagesDeleteOptionalParams, MsixPackagesUpdateOptionalParams, MsixPackagesUpdateResponse, MsixPackagesListResponse, MsixPackagesListNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing MsixPackages operations. */ export class MsixPackagesImpl implements MsixPackages { private readonly client: DesktopVirtualizationAPIClient; /** * Initialize a new instance of the class MsixPackages class. * @param client Reference to the service client */ constructor(client: DesktopVirtualizationAPIClient) { this.client = client; } /** * List MSIX packages in hostpool. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param hostPoolName The name of the host pool within the specified resource group * @param options The options parameters. */ public list( resourceGroupName: string, hostPoolName: string, options?: MsixPackagesListOptionalParams ): PagedAsyncIterableIterator<MsixPackage> { const iter = this.listPagingAll(resourceGroupName, hostPoolName, options); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listPagingPage(resourceGroupName, hostPoolName, options); } }; } private async *listPagingPage( resourceGroupName: string, hostPoolName: string, options?: MsixPackagesListOptionalParams ): AsyncIterableIterator<MsixPackage[]> { let result = await this._list(resourceGroupName, hostPoolName, options); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listNext( resourceGroupName, hostPoolName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listPagingAll( resourceGroupName: string, hostPoolName: string, options?: MsixPackagesListOptionalParams ): AsyncIterableIterator<MsixPackage> { for await (const page of this.listPagingPage( resourceGroupName, hostPoolName, options )) { yield* page; } } /** * Get a msixpackage. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param hostPoolName The name of the host pool within the specified resource group * @param msixPackageFullName The version specific package full name of the MSIX package within * specified hostpool * @param options The options parameters. */ get( resourceGroupName: string, hostPoolName: string, msixPackageFullName: string, options?: MsixPackagesGetOptionalParams ): Promise<MsixPackagesGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, hostPoolName, msixPackageFullName, options }, getOperationSpec ); } /** * Create or update a MSIX package. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param hostPoolName The name of the host pool within the specified resource group * @param msixPackageFullName The version specific package full name of the MSIX package within * specified hostpool * @param msixPackage Object containing MSIX Package definitions. * @param options The options parameters. */ createOrUpdate( resourceGroupName: string, hostPoolName: string, msixPackageFullName: string, msixPackage: MsixPackage, options?: MsixPackagesCreateOrUpdateOptionalParams ): Promise<MsixPackagesCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, hostPoolName, msixPackageFullName, msixPackage, options }, createOrUpdateOperationSpec ); } /** * Remove an MSIX Package. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param hostPoolName The name of the host pool within the specified resource group * @param msixPackageFullName The version specific package full name of the MSIX package within * specified hostpool * @param options The options parameters. */ delete( resourceGroupName: string, hostPoolName: string, msixPackageFullName: string, options?: MsixPackagesDeleteOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, hostPoolName, msixPackageFullName, options }, deleteOperationSpec ); } /** * Update an MSIX Package. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param hostPoolName The name of the host pool within the specified resource group * @param msixPackageFullName The version specific package full name of the MSIX package within * specified hostpool * @param options The options parameters. */ update( resourceGroupName: string, hostPoolName: string, msixPackageFullName: string, options?: MsixPackagesUpdateOptionalParams ): Promise<MsixPackagesUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, hostPoolName, msixPackageFullName, options }, updateOperationSpec ); } /** * List MSIX packages in hostpool. * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param hostPoolName The name of the host pool within the specified resource group * @param options The options parameters. */ private _list( resourceGroupName: string, hostPoolName: string, options?: MsixPackagesListOptionalParams ): Promise<MsixPackagesListResponse> { return this.client.sendOperationRequest( { resourceGroupName, hostPoolName, options }, listOperationSpec ); } /** * ListNext * @param resourceGroupName The name of the resource group. The name is case insensitive. * @param hostPoolName The name of the host pool within the specified resource group * @param nextLink The nextLink from the previous successful call to the List method. * @param options The options parameters. */ private _listNext( resourceGroupName: string, hostPoolName: string, nextLink: string, options?: MsixPackagesListNextOptionalParams ): Promise<MsixPackagesListNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, hostPoolName, nextLink, options }, listNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.DesktopVirtualization/hostPools/{hostPoolName}/msixPackages/{msixPackageFullName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.MsixPackage }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.hostPoolName, Parameters.msixPackageFullName ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.DesktopVirtualization/hostPools/{hostPoolName}/msixPackages/{msixPackageFullName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.MsixPackage }, 201: { bodyMapper: Mappers.MsixPackage }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.msixPackage, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.hostPoolName, Parameters.msixPackageFullName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.DesktopVirtualization/hostPools/{hostPoolName}/msixPackages/{msixPackageFullName}", httpMethod: "DELETE", responses: { 200: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.hostPoolName, Parameters.msixPackageFullName ], headerParameters: [Parameters.accept], serializer }; const updateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.DesktopVirtualization/hostPools/{hostPoolName}/msixPackages/{msixPackageFullName}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.MsixPackage }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.msixPackage1, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.hostPoolName, Parameters.msixPackageFullName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/Microsoft.DesktopVirtualization/hostPools/{hostPoolName}/msixPackages", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.MsixPackageList }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.hostPoolName ], headerParameters: [Parameters.accept], serializer }; const listNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.MsixPackageList }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.hostPoolName ], headerParameters: [Parameters.accept], serializer };
the_stack
import {fakeAsync, TestBed, tick} from "@angular/core/testing"; import * as Immutable from "immutable"; import {ViewFileComparator, ViewFileService} from "../../../../services/files/view-file.service"; import {LoggerService} from "../../../../services/utils/logger.service"; import {StreamServiceRegistry} from "../../../../services/base/stream-service.registry"; import {MockStreamServiceRegistry} from "../../../mocks/mock-stream-service.registry"; import {ConnectedService} from "../../../../services/utils/connected.service"; import {MockModelFileService} from "../../../mocks/mock-model-file.service"; import {ModelFile} from "../../../../services/files/model-file"; import {ViewFile} from "../../../../services/files/view-file"; import {ViewFileFilterCriteria} from "../../../../services/files/view-file.service"; describe("Testing view file service", () => { let viewService: ViewFileService; let mockModelService: MockModelFileService; beforeEach(() => { TestBed.configureTestingModule({ providers: [ ViewFileService, LoggerService, ConnectedService, {provide: StreamServiceRegistry, useClass: MockStreamServiceRegistry} ] }); viewService = TestBed.get(ViewFileService); let mockRegistry: MockStreamServiceRegistry = TestBed.get(StreamServiceRegistry); mockModelService = mockRegistry.modelFileService; }); it("should create an instance", () => { expect(viewService).toBeDefined(); }); it("should forward an empty model by default", fakeAsync(() => { let count = 0; viewService.files.subscribe({ next: list => { expect(list.size).toBe(0); count++; } }); tick(); expect(count).toBe(1); })); it("should forward an empty model", fakeAsync(() => { let model = Immutable.Map<string, ModelFile>(); mockModelService._files.next(model); tick(); let count = 0; viewService.files.subscribe({ next: list => { expect(list.size).toBe(0); count++; } }); tick(); expect(count).toBe(1); })); it("should correctly populate ViewFile props from a ModelFile", fakeAsync(() => { let model = Immutable.Map<string, ModelFile>(); model = model.set("a", new ModelFile({ name: "a", is_dir: true, local_size: 0, remote_size: 11, state: ModelFile.State.DEFAULT, downloading_speed: 111, eta: 1111, full_path: "root/a", is_extractable: true, local_created_timestamp: new Date("November 9, 2018 21:40:18"), local_modified_timestamp: new Date(1541828418943), remote_created_timestamp: null, remote_modified_timestamp: new Date(1541828418943), })); mockModelService._files.next(model); tick(); let count = 0; viewService.files.subscribe({ next: list => { expect(list.size).toBe(1); let file = list.get(0); expect(file.name).toBe("a"); expect(file.isDir).toBe(true); expect(file.localSize).toBe(0); expect(file.remoteSize).toBe(11); expect(file.status).toBe(ViewFile.Status.DEFAULT); expect(file.downloadingSpeed).toBe(111); expect(file.eta).toBe(1111); expect(file.fullPath).toBe("root/a"); expect(file.isArchive).toBe(true); expect(file.localCreatedTimestamp).toEqual(new Date("November 9, 2018 21:40:18")); expect(file.localModifiedTimestamp).toEqual(new Date(1541828418943)); expect(file.remoteCreatedTimestamp).toBeNull(); expect(file.remoteModifiedTimestamp).toEqual(new Date(1541828418943)); count++; } }); tick(); expect(count).toBe(1); })); it("should correctly set the ViewFile status", fakeAsync(() => { let modelFile = new ModelFile({ name: "a", state: ModelFile.State.DEFAULT, }); let model = Immutable.Map<string, ModelFile>(); model = model.set(modelFile.name, modelFile); let expectedStates = [ ViewFile.Status.DEFAULT, ViewFile.Status.QUEUED, ViewFile.Status.DOWNLOADING, ViewFile.Status.DOWNLOADED, ViewFile.Status.STOPPED, ViewFile.Status.DELETED, ViewFile.Status.EXTRACTING, ViewFile.Status.EXTRACTED ]; // First state - DEFAULT mockModelService._files.next(model); tick(); let count = 0; viewService.files.subscribe({ next: list => { expect(list.size).toBe(1); let file = list.get(0); expect(file.status).toBe(expectedStates[count++]); } }); tick(); expect(count).toBe(1); // Next state - QUEUED modelFile = new ModelFile(modelFile.set("state", ModelFile.State.QUEUED)); model = model.set(modelFile.name, modelFile); mockModelService._files.next(model); tick(); expect(count).toBe(2); // Next state - DOWNLOADING modelFile = new ModelFile(modelFile.set("state", ModelFile.State.DOWNLOADING)); model = model.set(modelFile.name, modelFile); mockModelService._files.next(model); tick(); expect(count).toBe(3); // Next state - DOWNLOADED modelFile = new ModelFile(modelFile.set("state", ModelFile.State.DOWNLOADED)); model = model.set(modelFile.name, modelFile); mockModelService._files.next(model); tick(); expect(count).toBe(4); // Next state - STOPPED // local size and remote size > 0 modelFile = new ModelFile(modelFile.set("state", ModelFile.State.DEFAULT)); modelFile = new ModelFile(modelFile.set("local_size", 50)); modelFile = new ModelFile(modelFile.set("remote_size", 50)); model = model.set(modelFile.name, modelFile); mockModelService._files.next(model); tick(); expect(count).toBe(5); // Next state - DELETED modelFile = new ModelFile(modelFile.set("state", ModelFile.State.DELETED)); model = model.set(modelFile.name, modelFile); mockModelService._files.next(model); tick(); expect(count).toBe(6); // Next state - DELETED modelFile = new ModelFile(modelFile.set("state", ModelFile.State.EXTRACTING)); model = model.set(modelFile.name, modelFile); mockModelService._files.next(model); tick(); expect(count).toBe(7); // Next state - DELETED modelFile = new ModelFile(modelFile.set("state", ModelFile.State.EXTRACTED)); model = model.set(modelFile.name, modelFile); mockModelService._files.next(model); tick(); expect(count).toBe(8); })); it("should always set a non-null file sizes in ViewFile", fakeAsync(() => { let model = Immutable.Map<string, ModelFile>(); model = model.set("a", new ModelFile({ name: "a", local_size: null, remote_size: null, })); mockModelService._files.next(model); tick(); let count = 0; viewService.files.subscribe({ next: list => { expect(list.size).toBe(1); let file = list.get(0); expect(file.localSize).toBe(0); expect(file.remoteSize).toBe(0); count++; } }); tick(); expect(count).toBe(1); })); it("should correctly set ViewFile percent downloaded", fakeAsync(() => { // Test vectors of local size, remote size, percentage let testVectors = [ [0, 10, 0], [5, 10, 50], [10, 10, 100], [null, 10, 0], [10, null, 100] ]; let count = -1; viewService.files.subscribe({ next: list => { // Ignore first if(count >= 0) { expect(list.size).toBe(1); let file = list.get(0); expect(file.percentDownloaded).toBe(testVectors[count][2]); } count++; } }); tick(); expect(count).toBe(0); // Send over the test vectors for(let vector of testVectors) { let model = Immutable.Map<string, ModelFile>(); model = model.set("a", new ModelFile({ name: "a", local_size: vector[0], remote_size: vector[1], })); mockModelService._files.next(model); tick(); } expect(count).toBe(testVectors.length); })); it("should should correctly set ViewFile isQueueable", fakeAsync(() => { // Test and expected result vectors // test - [ModelFile.State, local size, remote size] // result - [isQueueable, ViewFile.Status] let testVectors: any[][][] = [ // Default remote file is queueable [[ModelFile.State.DEFAULT, null, 100], [true, ViewFile.Status.DEFAULT]], // Default local file is NOT queueable [[ModelFile.State.DEFAULT, 100, null], [false, ViewFile.Status.DEFAULT]], // Stopped file is queueable [[ModelFile.State.DEFAULT, 50, 100], [true, ViewFile.Status.STOPPED]], // Deleted file is queueable [[ModelFile.State.DELETED, null, 100], [true, ViewFile.Status.DELETED]], // Queued file is NOT queueable [[ModelFile.State.QUEUED, null, 100], [false, ViewFile.Status.QUEUED]], // Downloading file is NOT queueable [[ModelFile.State.DOWNLOADING, 10, 100], [false, ViewFile.Status.DOWNLOADING]], // Downloaded file is NOT queueable [[ModelFile.State.DOWNLOADED, 100, 100], [false, ViewFile.Status.DOWNLOADED]], // Extracting file is NOT queueable [[ModelFile.State.EXTRACTING, 100, 100], [false, ViewFile.Status.EXTRACTING]], // Extracting local-only file is NOT queueable [[ModelFile.State.EXTRACTING, 100, null], [false, ViewFile.Status.EXTRACTING]], // Extracted file is NOT queueable [[ModelFile.State.EXTRACTED, 100, 100], [false, ViewFile.Status.EXTRACTED]], ]; let count = -1; viewService.files.subscribe({ next: list => { // Ignore first if(count >= 0) { expect(list.size).toBe(1); let file = list.get(0); let resultVector = testVectors[count][1]; expect(file.isQueueable).toBe(resultVector[0]); expect(file.status).toBe(resultVector[1]); } count++; } }); tick(); expect(count).toBe(0); // Send over the test vectors for(let vector of testVectors) { let testVector = vector[0]; let model = Immutable.Map<string, ModelFile>(); model = model.set("a", new ModelFile({ name: "a", state: testVector[0], local_size: testVector[1], remote_size: testVector[2], })); mockModelService._files.next(model); tick(); } expect(count).toBe(testVectors.length); })); it("should should correctly set ViewFile isStoppable", fakeAsync(() => { // Test and expected result vectors // test - [ModelFile.State, local size, remote size] // result - [isStoppable, ViewFile.Status] let testVectors: any[][][] = [ // Default remote file is NOT stoppable [[ModelFile.State.DEFAULT, null, 100], [false, ViewFile.Status.DEFAULT]], // Default local file is NOT stoppable [[ModelFile.State.DEFAULT, 100, null], [false, ViewFile.Status.DEFAULT]], // Stopped file is NOT stoppable [[ModelFile.State.DEFAULT, 50, 100], [false, ViewFile.Status.STOPPED]], // Deleted file is NOT stoppable [[ModelFile.State.DELETED, null, 100], [false, ViewFile.Status.DELETED]], // Queued file is stoppable [[ModelFile.State.QUEUED, null, 100], [true, ViewFile.Status.QUEUED]], // Downloading file is stoppable [[ModelFile.State.DOWNLOADING, 10, 100], [true, ViewFile.Status.DOWNLOADING]], // Downloaded file is NOT stoppable [[ModelFile.State.DOWNLOADED, 100, 100], [false, ViewFile.Status.DOWNLOADED]], // Extracting file is NOT stoppable [[ModelFile.State.EXTRACTING, 100, 100], [false, ViewFile.Status.EXTRACTING]], // Extracted file is NOT stoppable [[ModelFile.State.EXTRACTED, 100, 100], [false, ViewFile.Status.EXTRACTED]], ]; let count = -1; viewService.files.subscribe({ next: list => { // Ignore first if(count >= 0) { expect(list.size).toBe(1); let file = list.get(0); let resultVector = testVectors[count][1]; expect(file.isStoppable).toBe(resultVector[0]); expect(file.status).toBe(resultVector[1]); } count++; } }); tick(); expect(count).toBe(0); // Send over the test vectors for(let vector of testVectors) { let testVector = vector[0]; let model = Immutable.Map<string, ModelFile>(); model = model.set("a", new ModelFile({ name: "a", state: testVector[0], local_size: testVector[1], remote_size: testVector[2], })); mockModelService._files.next(model); tick(); } expect(count).toBe(testVectors.length); })); it("should should correctly set ViewFile isExtractable", fakeAsync(() => { // Test and expected result vectors // test - [ModelFile.State, local size, remote size] // result - [isExtractable, ViewFile.Status] let testVectors: any[][][] = [ // Default remote file is NOT extractable [[ModelFile.State.DEFAULT, null, 100], [false, ViewFile.Status.DEFAULT]], // Default local file is extractable [[ModelFile.State.DEFAULT, 100, null], [true, ViewFile.Status.DEFAULT]], // Stopped file is extractable [[ModelFile.State.DEFAULT, 50, 100], [true, ViewFile.Status.STOPPED]], // Deleted file is NOT extractable [[ModelFile.State.DELETED, null, 100], [false, ViewFile.Status.DELETED]], // Queued file is NOT extractable [[ModelFile.State.QUEUED, null, 100], [false, ViewFile.Status.QUEUED]], // Downloading file is NOT extractable [[ModelFile.State.DOWNLOADING, 10, 100], [false, ViewFile.Status.DOWNLOADING]], // Downloaded file is extractable [[ModelFile.State.DOWNLOADED, 100, 100], [true, ViewFile.Status.DOWNLOADED]], // Extracting file is NOT extractable [[ModelFile.State.EXTRACTING, 100, 100], [false, ViewFile.Status.EXTRACTING]], // Extracted file is extractable [[ModelFile.State.EXTRACTED, 100, 100], [true, ViewFile.Status.EXTRACTED]], ]; let count = -1; viewService.files.subscribe({ next: list => { // Ignore first if(count >= 0) { expect(list.size).toBe(1); let file = list.get(0); let resultVector = testVectors[count][1]; expect(file.isExtractable).toBe(resultVector[0]); expect(file.status).toBe(resultVector[1]); } count++; } }); tick(); expect(count).toBe(0); // Send over the test vectors for(let vector of testVectors) { let testVector = vector[0]; let model = Immutable.Map<string, ModelFile>(); model = model.set("a", new ModelFile({ name: "a", state: testVector[0], local_size: testVector[1], remote_size: testVector[2], })); mockModelService._files.next(model); tick(); } expect(count).toBe(testVectors.length); })); // it("should sort view files by status then name", fakeAsync(() => { // // Test vectors to create model file // // name, ModelFile.State, local size, remote size // let testVector: any[][] = [ // ["a", ModelFile.State.DEFAULT, null, 100], // ["b", ModelFile.State.DEFAULT, 100, null], // ["c", ModelFile.State.DEFAULT, 50, 100], // ["d", ModelFile.State.DELETED, null, 100], // ["e", ModelFile.State.QUEUED, null, 100], // ["f", ModelFile.State.DOWNLOADING, 50, 100], // ["g", ModelFile.State.DOWNLOADED, 50, 100], // ["h", ModelFile.State.EXTRACTING, 50, 100], // ["i", ModelFile.State.EXTRACTED, 50, 100] // ]; // // // Except result vector in order of view file name and state // let resultVector: any[][] = [ // ["h", ViewFile.Status.EXTRACTING], // ["f", ViewFile.Status.DOWNLOADING], // ["e", ViewFile.Status.QUEUED], // ["i", ViewFile.Status.EXTRACTED], // ["g", ViewFile.Status.DOWNLOADED], // ["c", ViewFile.Status.STOPPED], // ["a", ViewFile.Status.DEFAULT], // ["b", ViewFile.Status.DEFAULT], // ["d", ViewFile.Status.DELETED] // ]; // // let model = Immutable.Map<string, ModelFile>(); // for(let vector of testVector) { // model = model.set(vector[0], new ModelFile({ // name: vector[0], // state: vector[1], // local_size: vector[2], // remote_size: vector[3], // })); // } // mockModelService._files.next(model); // tick(); // // let count = 0; // viewService.files.subscribe({ // next: list => { // expect(list.size).toBe(resultVector.length); // resultVector.forEach((item, index) => { // let file = list.get(index); // expect(file.name).toBe(item[0]); // expect(file.status).toBe(item[1]); // }); // count++; // } // }); // tick(); // expect(count).toBe(1); // })); it("should correctly set and unset the selected file", fakeAsync(() => { let model = Immutable.Map<string, ModelFile>(); model = model.set("a", new ModelFile({name: "a"})); model = model.set("b", new ModelFile({name: "b"})); model = model.set("c", new ModelFile({name: "c"})); let expectedSelectedFileIndex = -1; mockModelService._files.next(model); tick(); let viewFileList; let count = 0; viewService.files.subscribe({ next: list => { viewFileList = list; expect(list.size).toBe(3); expect(list.get(0).name).toBe("a"); expect(list.get(1).name).toBe("b"); expect(list.get(2).name).toBe("c"); list.forEach((item, index) => { // Only 1 file is selected at a time if(index == expectedSelectedFileIndex) { expect(item.isSelected).toBe(true); } else { expect(item.isSelected).toBe(false); } }); count++; } }); tick(); expect(count).toBe(1); // select "a" expectedSelectedFileIndex = 0; viewService.setSelected(viewFileList.get(0)); tick(); expect(count).toBe(2); // unselect "a" expectedSelectedFileIndex = -1; viewService.unsetSelected(); tick(); expect(count).toBe(3); // select "b" expectedSelectedFileIndex = 1; viewService.setSelected(viewFileList.get(1)); tick(); expect(count).toBe(4); // select "c" expectedSelectedFileIndex = 2; viewService.setSelected(viewFileList.get(2)); tick(); expect(count).toBe(5); // select "b" again expectedSelectedFileIndex = 1; viewService.setSelected(viewFileList.get(1)); tick(); expect(count).toBe(6); // unselect "b" expectedSelectedFileIndex = -1; viewService.unsetSelected(); tick(); expect(count).toBe(7); })); it("should should correctly set ViewFile isLocallyDeletable", fakeAsync(() => { // Test and expected result vectors // test - [ModelFile.State, local size, remote size] // result - [isLocallyDeletable, ViewFile.Status] let testVectors: any[][][] = [ // Default remote file is NOT locally deletable [[ModelFile.State.DEFAULT, null, 100], [false, ViewFile.Status.DEFAULT]], // Default local file is locally deletable [[ModelFile.State.DEFAULT, 100, null], [true, ViewFile.Status.DEFAULT]], // Stopped file is locally deletable [[ModelFile.State.DEFAULT, 50, 100], [true, ViewFile.Status.STOPPED]], // Deleted file is NOT locally deletable [[ModelFile.State.DELETED, null, 100], [false, ViewFile.Status.DELETED]], // Queued file is NOT locally deletable [[ModelFile.State.QUEUED, null, 100], [false, ViewFile.Status.QUEUED]], // Downloading file is NOT locally deletable [[ModelFile.State.DOWNLOADING, 10, 100], [false, ViewFile.Status.DOWNLOADING]], // Downloaded file is locally deletable [[ModelFile.State.DOWNLOADED, 100, 100], [true, ViewFile.Status.DOWNLOADED]], // Extracting file is NOT locally deletable [[ModelFile.State.EXTRACTING, 100, 100], [false, ViewFile.Status.EXTRACTING]], // Extracted file is locally deletable [[ModelFile.State.EXTRACTED, 100, 100], [true, ViewFile.Status.EXTRACTED]], ]; let count = -1; viewService.files.subscribe({ next: list => { // Ignore first if(count >= 0) { expect(list.size).toBe(1); let file = list.get(0); let resultVector = testVectors[count][1]; expect(file.isLocallyDeletable).toBe(resultVector[0]); expect(file.status).toBe(resultVector[1]); } count++; } }); tick(); expect(count).toBe(0); // Send over the test vectors for(let vector of testVectors) { let testVector = vector[0]; let model = Immutable.Map<string, ModelFile>(); model = model.set("a", new ModelFile({ name: "a", state: testVector[0], local_size: testVector[1], remote_size: testVector[2], })); mockModelService._files.next(model); tick(); } expect(count).toBe(testVectors.length); })); it("should should correctly set ViewFile isRemotelyDeletable", fakeAsync(() => { // Test and expected result vectors // test - [ModelFile.State, local size, remote size] // result - [isRemotelyDeletable, ViewFile.Status] let testVectors: any[][][] = [ // Default remote file is remotely deletable [[ModelFile.State.DEFAULT, null, 100], [true, ViewFile.Status.DEFAULT]], // Default local file is NOT remotely deletable [[ModelFile.State.DEFAULT, 100, null], [false, ViewFile.Status.DEFAULT]], // Stopped file is remotely deletable [[ModelFile.State.DEFAULT, 50, 100], [true, ViewFile.Status.STOPPED]], // Deleted file is remotely deletable [[ModelFile.State.DELETED, null, 100], [true, ViewFile.Status.DELETED]], // Queued file is NOT remotely deletable [[ModelFile.State.QUEUED, null, 100], [false, ViewFile.Status.QUEUED]], // Downloading file is NOT remotely deletable [[ModelFile.State.DOWNLOADING, 10, 100], [false, ViewFile.Status.DOWNLOADING]], // Downloaded file is remotely deletable [[ModelFile.State.DOWNLOADED, 100, 100], [true, ViewFile.Status.DOWNLOADED]], // Extracting file is NOT remotely deletable [[ModelFile.State.EXTRACTING, 100, 100], [false, ViewFile.Status.EXTRACTING]], // Extracted file is remotely deletable [[ModelFile.State.EXTRACTED, 100, 100], [true, ViewFile.Status.EXTRACTED]], ]; let count = -1; viewService.files.subscribe({ next: list => { // Ignore first if(count >= 0) { expect(list.size).toBe(1); let file = list.get(0); let resultVector = testVectors[count][1]; expect(file.isRemotelyDeletable).toBe(resultVector[0]); expect(file.status).toBe(resultVector[1]); } count++; } }); tick(); expect(count).toBe(0); // Send over the test vectors for(let vector of testVectors) { let testVector = vector[0]; let model = Immutable.Map<string, ModelFile>(); model = model.set("a", new ModelFile({ name: "a", state: testVector[0], local_size: testVector[1], remote_size: testVector[2], })); mockModelService._files.next(model); tick(); } expect(count).toBe(testVectors.length); })); it("should not filter any files by default", fakeAsync(() => { const model = Immutable.Map({ "aaaa": new ModelFile({name: "aaaa", state: ModelFile.State.DEFAULT}), "tofu": new ModelFile({name: "tofu", state: ModelFile.State.QUEUED}), "flower": new ModelFile({name: "flower", state: ModelFile.State.QUEUED}), "power": new ModelFile({name: "power", state: ModelFile.State.DOWNLOADING}), "max": new ModelFile({name: "max", state: ModelFile.State.DOWNLOADED}), "mrx": new ModelFile({name: "mrx", state: ModelFile.State.EXTRACTING}), "blueman": new ModelFile({name: "blueman", state: ModelFile.State.EXTRACTED}), "spicy": new ModelFile({name: "spicy", state: ModelFile.State.DELETED}), }); mockModelService._files.next(model); let count = 0; let viewFiles: Immutable.List<ViewFile> = null; viewService.filteredFiles.subscribe({ next: list => { viewFiles = list; count++; } }); tick(); expect(count).toBe(1); expect(viewFiles.size).toBe(8); })); it("should apply filter criteria correctly", fakeAsync(() => { class TestCriteria implements ViewFileFilterCriteria { meetsCriteria(viewFile: ViewFile): boolean { return viewFile.status === ViewFile.Status.QUEUED || viewFile.status === ViewFile.Status.EXTRACTED; } } viewService.setFilterCriteria(new TestCriteria()); const model = Immutable.Map({ "aaaa": new ModelFile({name: "aaaa", state: ModelFile.State.DEFAULT}), "tofu": new ModelFile({name: "tofu", state: ModelFile.State.QUEUED}), "flower": new ModelFile({name: "flower", state: ModelFile.State.QUEUED}), "power": new ModelFile({name: "power", state: ModelFile.State.DOWNLOADING}), "max": new ModelFile({name: "max", state: ModelFile.State.DOWNLOADED}), "mrx": new ModelFile({name: "mrx", state: ModelFile.State.EXTRACTING}), "blueman": new ModelFile({name: "blueman", state: ModelFile.State.EXTRACTED}), "spicy": new ModelFile({name: "spicy", state: ModelFile.State.DELETED}), }); mockModelService._files.next(model); tick(); let count = 0; let viewFiles: Immutable.List<ViewFile> = null; let viewFilesMap: Map<string, ViewFile> = null; viewService.filteredFiles.subscribe({ next: list => { viewFiles = list; viewFilesMap = new Map<string, ViewFile>(); list.forEach(value => viewFilesMap.set(value.name, value)); count++; } }); tick(); expect(count).toBe(1); expect(viewFiles.size).toBe(3); expect(viewFilesMap.has("tofu")).toBe(true); expect(viewFilesMap.has("flower")).toBe(true); expect(viewFilesMap.has("blueman")).toBe(true); })); it("should resend filtered files on criteria change", fakeAsync(() => { class TestCriteria implements ViewFileFilterCriteria { constructor(public flag: boolean) {} meetsCriteria(viewFile: ViewFile): boolean { if (this.flag) { return viewFile.status === ViewFile.Status.QUEUED; } else { return viewFile.status === ViewFile.Status.EXTRACTED; } } } viewService.setFilterCriteria(new TestCriteria(true)); let count = 0; let viewFiles: Immutable.List<ViewFile> = null; let viewFilesMap: Map<string, ViewFile> = null; viewService.filteredFiles.subscribe({ next: list => { viewFiles = list; viewFilesMap = new Map<string, ViewFile>(); list.forEach(value => viewFilesMap.set(value.name, value)); count++; } }); expect(count).toBe(1); const model = Immutable.Map({ "aaaa": new ModelFile({name: "aaaa", state: ModelFile.State.DEFAULT}), "tofu": new ModelFile({name: "tofu", state: ModelFile.State.QUEUED}), "flower": new ModelFile({name: "flower", state: ModelFile.State.QUEUED}), "power": new ModelFile({name: "power", state: ModelFile.State.DOWNLOADING}), "max": new ModelFile({name: "max", state: ModelFile.State.DOWNLOADED}), "mrx": new ModelFile({name: "mrx", state: ModelFile.State.EXTRACTING}), "blueman": new ModelFile({name: "blueman", state: ModelFile.State.EXTRACTED}), "spicy": new ModelFile({name: "spicy", state: ModelFile.State.DELETED}), }); mockModelService._files.next(model); tick(); expect(count).toBe(2); expect(viewFiles.size).toBe(2); expect(viewFilesMap.has("tofu")).toBe(true); expect(viewFilesMap.has("flower")).toBe(true); // Update the filter criteria viewService.setFilterCriteria(new TestCriteria(false)); expect(count).toBe(3); expect(viewFiles.size).toBe(1); expect(viewFilesMap.has("blueman")).toBe(true); })); it("should not sort files by default", fakeAsync(() => { const model = Immutable.Map({ "aaaa": new ModelFile({name: "aaaa", state: ModelFile.State.DEFAULT}), "tofu": new ModelFile({name: "tofu", state: ModelFile.State.QUEUED}), "flower": new ModelFile({name: "flower", state: ModelFile.State.QUEUED}), "power": new ModelFile({name: "power", state: ModelFile.State.DOWNLOADING}), "max": new ModelFile({name: "max", state: ModelFile.State.DOWNLOADED}), "mrx": new ModelFile({name: "mrx", state: ModelFile.State.EXTRACTING}), "blueman": new ModelFile({name: "blueman", state: ModelFile.State.EXTRACTED}), "spicy": new ModelFile({name: "spicy", state: ModelFile.State.DELETED}), }); mockModelService._files.next(model); let count = 0; let viewFiles: Immutable.List<ViewFile> = null; viewService.files.subscribe({ next: list => { viewFiles = list; count++; } }); tick(); expect(count).toBe(1); expect(viewFiles.size).toBe(8); expect(viewFiles.get(0).name).toBe("aaaa"); expect(viewFiles.get(1).name).toBe("tofu"); expect(viewFiles.get(2).name).toBe("flower"); expect(viewFiles.get(3).name).toBe("power"); expect(viewFiles.get(4).name).toBe("max"); expect(viewFiles.get(5).name).toBe("mrx"); expect(viewFiles.get(6).name).toBe("blueman"); expect(viewFiles.get(7).name).toBe("spicy"); })); it("should sort new model correctly", fakeAsync(() => { const comparator: ViewFileComparator = function(a: ViewFile, b: ViewFile) { // alphabetical order return a.name.localeCompare(b.name); }; viewService.setComparator(comparator); const model = Immutable.Map({ "aaaa": new ModelFile({name: "aaaa", state: ModelFile.State.DEFAULT}), "tofu": new ModelFile({name: "tofu", state: ModelFile.State.QUEUED}), "flower": new ModelFile({name: "flower", state: ModelFile.State.QUEUED}), "power": new ModelFile({name: "power", state: ModelFile.State.DOWNLOADING}), "max": new ModelFile({name: "max", state: ModelFile.State.DOWNLOADED}), "mrx": new ModelFile({name: "mrx", state: ModelFile.State.EXTRACTING}), "blueman": new ModelFile({name: "blueman", state: ModelFile.State.EXTRACTED}), "spicy": new ModelFile({name: "spicy", state: ModelFile.State.DELETED}), }); mockModelService._files.next(model); let count = 0; let viewFiles: Immutable.List<ViewFile> = null; viewService.files.subscribe({ next: list => { viewFiles = list; count++; } }); tick(); expect(count).toBe(1); expect(viewFiles.size).toBe(8); expect(viewFiles.get(0).name).toBe("aaaa"); expect(viewFiles.get(1).name).toBe("blueman"); expect(viewFiles.get(2).name).toBe("flower"); expect(viewFiles.get(3).name).toBe("max"); expect(viewFiles.get(4).name).toBe("mrx"); expect(viewFiles.get(5).name).toBe("power"); expect(viewFiles.get(6).name).toBe("spicy"); expect(viewFiles.get(7).name).toBe("tofu"); })); it("should sort existing model on setComparator", fakeAsync(() => { const model = Immutable.Map({ "aaaa": new ModelFile({name: "aaaa", state: ModelFile.State.DEFAULT}), "tofu": new ModelFile({name: "tofu", state: ModelFile.State.QUEUED}), "flower": new ModelFile({name: "flower", state: ModelFile.State.QUEUED}), "power": new ModelFile({name: "power", state: ModelFile.State.DOWNLOADING}), "max": new ModelFile({name: "max", state: ModelFile.State.DOWNLOADED}), "mrx": new ModelFile({name: "mrx", state: ModelFile.State.EXTRACTING}), "blueman": new ModelFile({name: "blueman", state: ModelFile.State.EXTRACTED}), "spicy": new ModelFile({name: "spicy", state: ModelFile.State.DELETED}), }); mockModelService._files.next(model); let count = 0; let viewFiles: Immutable.List<ViewFile> = null; viewService.files.subscribe({ next: list => { viewFiles = list; count++; } }); tick(); expect(count).toBe(1); const comparator: ViewFileComparator = function(a: ViewFile, b: ViewFile) { // reverse alphabetical order return -1 * a.name.localeCompare(b.name); }; viewService.setComparator(comparator); tick(); expect(count).toBe(2); expect(viewFiles.size).toBe(8); expect(viewFiles.get(0).name).toBe("tofu"); expect(viewFiles.get(1).name).toBe("spicy"); expect(viewFiles.get(2).name).toBe("power"); expect(viewFiles.get(3).name).toBe("mrx"); expect(viewFiles.get(4).name).toBe("max"); expect(viewFiles.get(5).name).toBe("flower"); expect(viewFiles.get(6).name).toBe("blueman"); expect(viewFiles.get(7).name).toBe("aaaa"); })); });
the_stack
namespace LogDog { /** Stream status entry, as rendered by the view. */ export type StreamStatusEntry = {name: string; desc: string;}; /** LoadingState is the current stream loading state. */ export enum LoadingState { /** No loading state (no status, loaded). */ NONE, /** Resolving a glob into the set of streams via query. */ RESOLVING, /** Loading / rendering stream content */ LOADING, /** Version of LOADING when the stream has been loading for a long time. */ LOADING_BEEN_A_WHILE, /** No operations in progress, but the log isn't fully loaded.. */ PAUSED, /** Error: Attempt to load failed w/ "Unauthenticated". */ NEEDS_AUTH, /** Error: generic loading failure. */ ERROR, } /** Registered callbacks used by Model. Implemented by View. */ export interface ViewBinding { pushLogEntries(entries: LogDog.LogEntry[], l: Location): void; clearLogEntries(): void; updateControls(c: Controls): void; locationIsVisible(l: Location): boolean; } /** State of the split UI component. */ export enum SplitState { /** The UI cannot be split. */ CANNOT_SPLIT, /** The UI can be split, and isn't split. */ CAN_SPLIT, /** The UI cannot be split, and is split. */ IS_SPLIT, } /** * Represents state in the View. * * Modifying this will propagate to the view via "updateControls". */ type Controls = { /** Is the content fully loaded? */ fullyLoaded: boolean; /** True if we should show the split option to the user. */ splitState: SplitState; /** If not undefined, link to this URL for the log stream. */ logStreamUrl: string | undefined; /** Text in the status bar. */ loadingState: LoadingState; /** Stream status entries, or null for no status window. */ streamStatus: StreamStatusEntry[]; }; /** A value for the "status-bar" element. */ type StatusBarValue = {value: string;}; /** * The underlying "logdog-stream-view" Polymer component * (see logdog-stream-view.html). * * View will manipulate the view via modifications to Component. */ type Component = { /** Polymer accessor functions. Each member is an element w/ an ID. */ $: { client: luci.PolymerClient; mainView: HTMLElement; buttons: HTMLElement; streamStatus: HTMLElement; logSplit: HTMLElement; logBottom: HTMLElement; logEnd: HTMLElement; logs: HTMLElement; }; // Polymer properties. streams: string[]; streamLinkUrl: string | undefined; mobile: boolean; isSplit: boolean; metadata: boolean; playing: boolean; backfill: boolean; /** Polymer read-only setter functions. */ _setStatusBar(v: StatusBarValue|null): void; _setShowPlayPause(v: boolean): void; _setShowStreamControls(v: boolean): void; _setShowSplitButton(v: boolean): void; _setShowSplitControls(v: boolean): void; _setStreamStatus(v: StreamStatusEntry[]): void; /** Update functions. */ _updateSplitVisible(v: boolean): void; _updateBottomVisible(v: boolean): void; /** Special Polymer callback to apply child styles. */ _polymerAppendChild(child: HTMLElement): void; }; /** * View contains the view manipulation logic. * * It is bound to a Model, which represents the underlying viewer state and * data. The Model can interact with View as a ViewBinding. * * View, in turn, manipulates the actual "logdog-stream-view" Polymer * component using a Component reference. */ export class View implements ViewBinding { private onScrollHandler = () => { this.onScroll(); } private scrollTimeoutId: number|null = null; private model: Model|null = null; private renderedLogs = false; /** * We start out following by default. Every time we add new logs to the * bottom, we will scroll to them. If users scroll or pause, we will stop * following permanently. */ private following = true; constructor(readonly comp: Component) {} /** Resets and reloads current viewer state. */ reset() { this.detach(); // Create "onScrollHandler", which just invokes "_onScroll" while bound // to "this". We create it here so we can unregister it later, since // "bind" returns a modified value. window.addEventListener('scroll', this.onScrollHandler); this.resetScroll(); this.renderedLogs = false; // Instantiate our view, and install callbacks. let profile = ((this.comp.mobile) ? Model.MOBILE_PROFILE : Model.DEFAULT_PROFILE); this.model = new LogDog.Model(new luci.Client(this.comp.$.client), profile, this); this.handleStreamsChanged(); } /** Called to detach any resources used by View (Polymer "detach()"). */ detach() { window.removeEventListener('scroll', this.onScrollHandler); this.model = null; } /** Called when a mouse wheel event occurs. */ handleMouseWheel(down: boolean) { // Once someone scrolls, stop following. if (!down) { this.following = false; } } /** Called when the split "Down" button is clicked. */ handleDownClick() { if (this.model) { this.model.fetchLocation(Location.HEAD, true); } } /** Called when the split "Up" button is clicked. */ handleUpClick() { if (this.model) { this.model.fetchLocation(Location.TAIL, true); } } /** Called when the split "Bottom" button is clicked. */ handleBottomClick() { if (this.model) { this.model.fetchLocation(Location.BOTTOM, true); } } /** Called when the "streams" property value changes. */ async handleStreamsChanged() { if (!this.model) { return; } await this.model.resolve(this.comp.streams); // If we're not on mobile, start with playing state. this.comp.playing = (!this.comp.mobile); // Perform the initial fetch after resolution. if (this.model) { this.model.automatic = this.comp.playing; this.model.setFetchFromTail(!this.comp.backfill); this.model.fetch(false); } } stop() { if (this.model) { this.model.automatic = false; this.model.clearCurrentOperation(); } } /** Called when the "playing" property value changes. */ handlePlayPauseChanged(v: boolean) { if (this.model) { // If we're playing, begin log fetching. this.model.automatic = v; // Once someone manually uses this control, stop following. // // Only apply this after we've started rendering logs, since before that // this may toggle during setup. if (this.renderedLogs) { this.following = false; } if (!v) { this.model.clearCurrentOperation(); } } } /** Called when the "backfill" property value changes. */ handleBackfillChanged(v: boolean) { if (this.model) { // If we're backfilling, then we're not tailing. this.model.setFetchFromTail(!v); } } /** Called when the "split" button is clicked. */ handleSplitClicked() { if (!this.model) { return; } // After a split, toggle off playing. this.model.setFetchFromTail(true); this.model.split(); this.comp.playing = false; } /** Called when the "scroll to split" button is clicked. */ handleScrollToSplitClicked() { this.maybeScrollToElement(this.comp.$.logSplit, true); } /** Called when a sign-in event is fired from "google-signin-aware". */ handleSignin() { if (this.model) { this.model.notifyAuthenticationChanged(); } } /** Returns true if our Model is currently automatically loading logs. */ private get isPlaying() { return (this.model && this.model.automatic); } /** Clears asynchornous scroll event status. */ private resetScroll() { if (this.scrollTimeoutId !== null) { window.clearTimeout(this.scrollTimeoutId); this.scrollTimeoutId = null; } } /** * Called each time a scroll event is fired. Since this can be really * frequent, this will kick off a "scroll handler" in the background at an * interval. Multiple scroll events within that interval will only result * in one scroll handler invocation. */ private onScroll() { if (this.scrollTimeoutId !== null) { return; } window.setTimeout(() => { this.handleScrollEvent(); }, 100); } private handleScrollEvent() { this.resetScroll(); // Update our button bar position to be relative to the parent's height. // TODO: Investigate using CSS or a less manual mathod for this. this.adjustToTop(this.comp.$.buttons); this.adjustToTop(this.comp.$.streamStatus); } private adjustToTop(elem: HTMLElement) { // Update our button bar position to be relative to the parent's height. let pageRect = this.comp.$.mainView.getBoundingClientRect(); let elemRect = elem.getBoundingClientRect(); let adjusted = (elem.offsetTop + pageRect.top - elemRect.top); if (adjusted < 0) { adjusted = 0; } elem.style.top = String(adjusted); } private appendMetaLine(root: HTMLElement, key: string, value: string|null) { let line = document.createElement('div'); line.className = 'log-entry-meta-line'; let keyE = document.createElement('strong'); keyE.textContent = key; line.appendChild(keyE); if (value) { let e = document.createElement('span'); e.textContent = value; line.appendChild(e); } root.appendChild(line); } pushLogEntries(entries: LogDog.LogEntry[], insertion: Location) { // Mark that we've rendered logs (show bars now). this.renderedLogs = true; // Build our log entry chunk. let logEntryChunk = document.createElement('div'); logEntryChunk.className = 'log-entry-chunk'; let lastLogEntry = logEntryChunk; let lines = new Array<string>(); entries.forEach(le => { let text = le.text; if (!(text && text.lines)) { return; } // If we're rendering metadata, render an element per log entry. if (this.comp.metadata) { let entryRow = document.createElement('div'); entryRow.className = 'log-entry'; // Metadata column. let metadataBlock = document.createElement('div'); metadataBlock.className = 'log-entry-meta'; this.appendMetaLine( metadataBlock, 'Timestamp:', String(le.timestamp)); if (le.desc) { this.appendMetaLine(metadataBlock, 'Stream:', le.desc.name); } this.appendMetaLine(metadataBlock, 'Index:', String(le.streamIndex)); // Log column. let logDataBlock = document.createElement('div'); logDataBlock.className = 'log-entry-content'; text.lines.forEach(function(line) { if (line.value) { lines.push(line.value); } }); logDataBlock.textContent = lines.join('\n'); lines.length = 0; entryRow.appendChild(metadataBlock); entryRow.appendChild(logDataBlock); logEntryChunk.appendChild(entryRow); lastLogEntry = entryRow; } else { // Add this to the lines. We'll assign this directly to logEntryChunk // after the loop. text.lines.forEach(function(line) { if (line.value) { lines.push(line.value); } }); } }); if (!this.comp.metadata) { // Only one HTML element: the chunk. logEntryChunk.textContent = lines.join('\n'); lastLogEntry = logEntryChunk; } // To have styles apply correctly, we need to add it twice, see // https://github.com/Polymer/polymer/issues/3100. this.comp._polymerAppendChild(logEntryChunk); // Add the log entry to the appropriate place. let anchor: Element|null; let scrollToTop = false; switch (insertion) { case Location.HEAD: // PREPEND to "logSplit". this.comp.$.logs.insertBefore(logEntryChunk, this.comp.$.logSplit); // If we're not split, scroll to the log bottom. Otherwise, scroll to // the split. anchor = lastLogEntry; if (this.following) { this.maybeScrollToElement(anchor, scrollToTop); } break; case Location.TAIL: // APPEND to "logSplit". anchor = this.comp.$.logSplit; // Identify the element *after* our insertion point and scroll to it. // This provides a semblance of stability as we top-insert. // // As a special case, if the next element is the log bottom, just // scroll to the split, since there is no content to stabilize. if (anchor.nextElementSibling !== this.comp.$.logBottom) { anchor = anchor.nextElementSibling; } // Insert logs by adding them before the sibling following the log // split (append to this.$.logSplit). this.comp.$.logs.insertBefore( logEntryChunk, this.comp.$.logSplit.nextSibling); // When tailing, always scroll to the anchor point. scrollToTop = true; break; case Location.BOTTOM: // PREPEND to "logBottom". anchor = this.comp.$.logBottom; this.comp.$.logs.insertBefore(logEntryChunk, anchor); if (this.following) { this.maybeScrollToElement(anchor, scrollToTop); } break; default: anchor = null; break; } } clearLogEntries() { // Remove all current log elements. */ for (let cur: Element|null = <Element>this.comp.$.logs.firstChild; cur;) { let del = cur; cur = cur.nextElementSibling; if (del.classList && del.classList.contains('log-entry-chunk')) { this.comp.$.logs.removeChild(del); } } } locationIsVisible(l: Location) { let anchor: HTMLElement; switch (l) { case Location.HEAD: case Location.TAIL: anchor = this.comp.$.logSplit; break; case Location.BOTTOM: anchor = this.comp.$.logBottom; break; default: return false; } return this.elementInViewport(anchor); } updateControls(c: Controls) { let canSplit = false; let isSplit = false; if (!c.fullyLoaded) { switch (c.splitState) { case SplitState.CAN_SPLIT: canSplit = true; break; case SplitState.IS_SPLIT: isSplit = true; break; default: break; } } this.comp._setShowPlayPause(!c.fullyLoaded); this.comp._setShowStreamControls(c.fullyLoaded || !this.isPlaying); this.comp._setShowSplitButton(canSplit && !this.isPlaying); this.comp._setShowSplitControls(isSplit); this.comp._updateSplitVisible(isSplit); this.comp.streamLinkUrl = c.logStreamUrl; switch (c.loadingState) { case LogDog.LoadingState.RESOLVING: this.loadStatusBar('Resolving stream names...'); break; case LogDog.LoadingState.LOADING: this.loadStatusBar('Loading streams...'); break; case LogDog.LoadingState.LOADING_BEEN_A_WHILE: this.loadStatusBar('Loading streams (has the build crashed?)...'); break; case LogDog.LoadingState.PAUSED: this.loadStatusBar('Paused.'); break; case LogDog.LoadingState.NEEDS_AUTH: this.loadStatusBar('Not authenticated. Please log in.'); break; case LogDog.LoadingState.ERROR: this.loadStatusBar('Error loading streams (see console).'); break; case LogDog.LoadingState.NONE: default: this.loadStatusBar(null); break; } this.comp._setStreamStatus(c.streamStatus); } /** * Scrolls to the specified element, centering it at the top or bottom of * the view. By default,t his will only happen if "follow" is enabled; * however, it can be forced via "force". */ private maybeScrollToElement(element: Element, topOfView: boolean) { if (topOfView) { element.scrollIntoView({ behavior: 'auto', block: 'end', }); } else { // Bug? "block: start" doesn't seem to work the same as false. element.scrollIntoView(false); } } /** * Loads text content into the status bar. * * If null is passed, the status bar will be cleared. If text is passed, the * status bar will become visible with the supplied content. */ private loadStatusBar(v: string|null) { let st: StatusBarValue|null = null; if (v) { st = { value: v, }; } this.comp._setStatusBar(st); } private elementInViewport(el: HTMLElement) { let top = el.offsetTop; let left = el.offsetLeft; let width = el.offsetWidth; let height = el.offsetHeight; while (el.offsetParent) { el = <HTMLElement>el.offsetParent; top += el.offsetTop; left += el.offsetLeft; } return ( top < (window.pageYOffset + window.innerHeight) && left < (window.pageXOffset + window.innerWidth) && (top + height) > window.pageYOffset && (left + width) > window.pageXOffset); } } }
the_stack
import { AfterContentInit, ContentChild, ContentChildren, Directive, ElementRef, EventEmitter, HostBinding, Input, OnDestroy, OnInit, Optional, Output, QueryList, Renderer2, Self, Inject, HostListener, forwardRef } from '@angular/core'; import { DOCUMENT } from '@angular/common'; import { MDCDialogFoundation, MDCDialogAdapter, util, cssClasses } from '@material/dialog'; import { ponyfill } from '@material/dom' import { MdcEventRegistry } from '../../utils/mdc.event.registry'; import { MdcButtonDirective } from '../button/mdc.button.directive'; import { AbstractMdcFocusInitial, AbstractMdcFocusTrap, FocusTrapHandle } from '../focus-trap/abstract.mdc.focus-trap'; import { HasId } from '../abstract/mixin.mdc.hasid'; import { applyMixins } from '../../utils/mixins'; @Directive() class MdcDialogTitleDirectiveBase {} interface MdcDialogTitleDirectiveBase extends HasId {} applyMixins(MdcDialogTitleDirectiveBase, [HasId]); /** * Directive for the title of an `mdcDialog`. * A title is optional. If used, it should be the first child of an `mdcDialogSurface`. * Please note that there should be no whitespace separating the start/end tag and the title * itself. (The easiest way to achieve this is to *not* set the `preserveWhitespaces` option to * `true` the `angularCompilerOptions`). */ @Directive({ selector: '[mdcDialogTitle]' }) export class MdcDialogTitleDirective extends MdcDialogTitleDirectiveBase implements OnInit { /** @internal */ @HostBinding('class.mdc-dialog__title') readonly _cls = true; ngOnInit() { this.initId(); } } @Directive() class MdcDialogContentDirectiveBase {} interface MdcDialogContentDirectiveBase extends HasId {} applyMixins(MdcDialogContentDirectiveBase, [HasId]); /** * Directive for the content part of an `mdcDialog`. * This should be added as a child element of an `mdcDialogSurface`. */ @Directive({ selector: '[mdcDialogContent]' }) export class MdcDialogContentDirective extends MdcDialogContentDirectiveBase implements OnInit { /** @internal */ @HostBinding('class.mdc-dialog__content') readonly _cls = true; constructor(public _elm: ElementRef) { super(); } ngOnInit() { this.initId(); } } /** * Directive for the actions (footer) of an `mdcDialog`. * This is an (optional) last child of the `mdcDialogSurface` directive. * This directive should contain buttons, for that should use the `mdcButton` * directive. * * Action buttons should typically close the dialog, and should therefore * also set a value for the `mdcDialogTrigger` directive. */ @Directive({ selector: '[mdcDialogActions]', }) export class MdcDialogActionsDirective implements AfterContentInit { /** @internal */ @HostBinding('class.mdc-dialog__actions') readonly _cls = true; /** @internal */ @ContentChildren(MdcButtonDirective, {descendants: true}) _buttons?: QueryList<MdcButtonDirective>; constructor(private _rndr: Renderer2) { } ngAfterContentInit() { this.initButtons(); this._buttons!.changes.subscribe(() => { this.initButtons(); }); } private initButtons() { this._buttons!.forEach(btn => { this._rndr.addClass(btn._elm.nativeElement, 'mdc-dialog__button'); }); } } /** * Any element within a dialog may include this directive (and assigne a non empty value to it) * to indicate that interacting with it should close the dialog with the specified action. * * This action is then reflected via the `action` field in the `closing` and `closed` events of * the dialog. A value of `close` will also trigger the `cancel` event of the dialog, and a value of * `accept` will trigger the `accept` event. * * Any action buttons within the dialog that equate to a dismissal with no further action should * use set `mdcDialogTrigger="close"`. This will make it easy to handle all such interactions consistently * (via either the `cancel`, `closing`, or `closed` events), while separately handling other actions. */ @Directive({ selector: '[mdcDialogTrigger]' }) export class MdcDialogTriggerDirective { constructor(public _elm: ElementRef) { } /** * Set the `action` value that should be send to `closing` and `closed` events when a user * interacts with this element. (When set to an empty string the button/element will not be wired * to close the dialog). */ @Input() mdcDialogTrigger: string | null = null; } /** * This directive can be used to mark one of the dialogs action buttons as the default action. * This action will then be triggered by pressing the enter key while the dialog has focus. * The default action also will receive focus when the dialog is opened. Unless another * element within the dialog has the `mdcFocusInitial` directive. */ @Directive({ selector: '[mdcDialogDefault]', providers: [{provide: AbstractMdcFocusInitial, useExisting: forwardRef(() => MdcDialogDefaultDirective) }] }) export class MdcDialogDefaultDirective extends AbstractMdcFocusInitial { /** @internal */ readonly priority = 0; // must be lower than prio of MdcFocusInitialDirective constructor(public _elm: ElementRef) { super(); } } /** * Directive for the surface of a dialog. The surface contains the actual content of a dialog, * wrapped in elements with the `mdcDialogHeader`, `mdcDialogContent`, and `mdcDialogActions` * directives. * * # Accessibility * * The role attribute will be set to `alertdialog` by default * * The `aria-modal` attribute will be set to `true` by default * * If there is an `mdcDialogTitle`, the `aria-labelledBy` attribute will be set to the id * of that element (and a unique id will be assigned to it, if none was provided) * * If there is an `mdcDialogContent`, the `aria-describedby` attribute will be set to the * id of that element (and a unique id will be assigned to it, if none was provided) */ @Directive({ selector: '[mdcDialogSurface]' }) export class MdcDialogSurfaceDirective { /** @internal */ @HostBinding('class.mdc-dialog__surface') readonly _cls = true; /** @internal */ @HostBinding('attr.role') _role = 'alertdialog'; /** @internal */ @HostBinding('attr.aria-modal') _modal = 'true'; /** @internal */ @HostBinding('attr.aria-labelledby') _labelledBy: string | null = null; /** @internal */ @HostBinding('attr.aria-describedby') _describedBy: string | null = null; /** @internal */ @ContentChildren(MdcDialogTitleDirective) _titles?: QueryList<MdcDialogTitleDirective>; /** @internal */ @ContentChildren(MdcDialogContentDirective) _contents?: QueryList<MdcDialogContentDirective>; ngAfterContentInit() { this._titles!.changes.subscribe(() => this.setAriaLabels()); this._contents!.changes.subscribe(() => this.setAriaLabels()); this.setAriaLabels(); } private setAriaLabels() { this._labelledBy = this._titles!.first?.id; this._describedBy = this._contents!.first?.id; } } /** * This directive should be the first child of an `mdcDialog`, and contains the `mdcDialogSurface`. */ @Directive({ selector: '[mdcDialogContainer]' }) export class MdcDialogContainerDirective { /** @internal */ @HostBinding('class.mdc-dialog__container') readonly _cls = true; } /** * Directive for the backdrop of a dialog. The backdrop provides the styles for overlaying the * page content when the dialog is opened. This guides user attention to the dialog. */ @Directive({ selector: '[mdcDialogScrim]' }) export class MdcDialogScrimDirective { /** @internal */ @HostBinding('class.mdc-dialog__scrim') readonly _cls = true; } /** * Directive for creating a modal dialog with Material Design styling. The dialog should have two * child elements: a surface (marked with the <code>mdcDialogSurface</code> directive), and a * backdrop (marked with the <code>mdcDialogBackdrop</code> directive). * * When the dialog is opened, it will activate a focus trap on the elements within the dialog, * so that the surface behind the dialog is not accessible. See `mdcFocusTrap` for more information. */ @Directive({ selector: '[mdcDialog]', exportAs: 'mdcDialog' }) export class MdcDialogDirective implements AfterContentInit, OnDestroy { /** @internal */ @HostBinding('class.mdc-dialog') readonly _cls = true; /** @internal */ @ContentChild(MdcDialogSurfaceDirective) _surface: MdcDialogSurfaceDirective | null = null; /** @internal */ @ContentChildren(MdcDialogTriggerDirective, {descendants: true}) _triggers?: QueryList<MdcDialogTriggerDirective>; /** @internal */ @ContentChildren(MdcDialogContentDirective, {descendants: true}) _contents?: QueryList<MdcDialogContentDirective>; /** @internal */ @ContentChildren(MdcDialogActionsDirective, {descendants: true}) _footers?: QueryList<MdcDialogActionsDirective>; /** @internal */ @ContentChildren(MdcDialogDefaultDirective, {descendants: true}) _defaultActions?: QueryList<MdcDialogDefaultDirective>; /** * Event emitted when the user accepts the dialog, e.g. by pressing enter or clicking the button * with `mdcDialogTrigger="accept"`. */ @Output() readonly accept: EventEmitter<void> = new EventEmitter(); /** * Event emitted when the user cancels the dialog, e.g. by clicking outside the dialog, pressing the escape key, * or clicking an element with `mdcDialogTrigger="close"`. */ @Output() readonly cancel: EventEmitter<void> = new EventEmitter(); /** * Event emitted when the dialog starts opening. */ @Output() readonly opening: EventEmitter<void> = new EventEmitter(); /** * Event emitted when the dialog is opened. */ @Output() readonly opened: EventEmitter<void> = new EventEmitter(); /** * Event emitted when the dialog starts closing. The 'action' field contains the reason for closing, see * `mdcDialogTrigger` for more information. */ @Output() readonly closing: EventEmitter<{action: string}> = new EventEmitter(); /** * Event emitted when the dialog is closed. The 'action' field contains the reason for closing, see * `mdcDialogTrigger` for more information. */ @Output() readonly closed: EventEmitter<{action: string}> = new EventEmitter(); private _onDocumentKeydown = (event: KeyboardEvent) => this.onDocumentKeydown(event); private focusTrapHandle: FocusTrapHandle | null = null; private mdcAdapter: MDCDialogAdapter = { addClass: (className: string) => this._rndr.addClass(this._elm.nativeElement, className), removeClass: (className: string) => this._rndr.removeClass(this._elm.nativeElement, className), addBodyClass: (className: string) => this._rndr.addClass(this.document.body, className), removeBodyClass: (className: string) => this._rndr.removeClass(this.document.body, className), areButtonsStacked: () => this._footers?.first ? util.areTopsMisaligned(this._footers.first?._buttons!.map(b => b._elm.nativeElement)) : false, clickDefaultButton: () => this._defaultActions?.first?._elm.nativeElement.click(), eventTargetMatches: (target, selector) => target ? ponyfill.matches(target as Element, selector) : false, getActionFromEvent: (evt: Event) => { const action = this.closest(evt.target as Element, this._triggers!.toArray()); return action?.mdcDialogTrigger || null; }, getInitialFocusEl: () => null, // ignored in our implementation. mdcFocusTrap determines this by itself hasClass: (className) => { if (className === cssClasses.STACKED) return false; // currently not supporting (auto-)stacking of buttons return this._elm.nativeElement.classList.contains(className); }, isContentScrollable: () => util.isScrollable(this._content?._elm.nativeElement), notifyClosed: (action) => { this.closed.emit({action}); }, notifyClosing: (action) => { this.document.removeEventListener('keydown', this._onDocumentKeydown); this.closing.emit({action}); if (action === 'accept') this.accept.emit(); else if (action === 'close') this.cancel.emit(); }, notifyOpened: () => { this.opened.emit(); }, notifyOpening: () => { this.document.addEventListener('keydown', this._onDocumentKeydown); this.opening.emit(); }, releaseFocus: () => this.untrapFocus(), // we're currently not supporting auto-stacking, cause we can't just reverse buttons in the dom // and expect that to not break stuff in angular: reverseButtons: () => undefined, trapFocus: () => this.trapFocus() }; private foundation: MDCDialogFoundation | null = null; private document: Document; constructor(private _elm: ElementRef, private _rndr: Renderer2, private _registry: MdcEventRegistry, @Optional() @Self() private _focusTrap: AbstractMdcFocusTrap, @Inject(DOCUMENT) doc: any) { this.document = doc as Document; // work around ngc issue https://github.com/angular/angular/issues/20351 } ngAfterContentInit() { this.foundation = new MDCDialogFoundation(this.mdcAdapter); this.foundation.init(); this.foundation.setAutoStackButtons(false); // currently not supported } ngOnDestroy() { this.document.removeEventListener('keydown', this._onDocumentKeydown); this.foundation?.destroy(); this.foundation = null; } /** * Call this method to open the dialog. */ open() { this.foundation!.open(); } /** * Call this method to close the dialog with the specified action, e.g. `accept` to indicate an acceptance action * (and trigger the `accept` event), or `close` to indicate dismissal (and trigger the `cancel` event). */ close(action = 'close') { this.foundation!.close(action); } /** * Recalculates layout and automatically adds/removes modifier classes (for instance to detect if the dialog content * should be scrollable) */ layout() { this.foundation!.layout(); } private trapFocus() { this.untrapFocus(); if (this._focusTrap) this.focusTrapHandle = this._focusTrap.trapFocus(); } private untrapFocus() { if (this.focusTrapHandle && this.focusTrapHandle.active) { this.focusTrapHandle.untrap(); this.focusTrapHandle = null; } } /** @internal */ @HostListener('click', ['$event']) onClick(event: MouseEvent) { this.foundation?.handleClick(event); } /** @internal */ @HostListener('keydown', ['$event']) onKeydown(event: KeyboardEvent) { this.foundation?.handleKeydown(event); } /** @internal */ onDocumentKeydown(event: KeyboardEvent) { this.foundation?.handleDocumentKeydown(event); } private get _content() { return this._contents!.first; } private closest(elm: Element, choices: MdcDialogTriggerDirective[]) { let match: Element | null = elm; while (match && match !== this._elm.nativeElement) { for (let i = 0; i != choices.length; ++i) { if (choices[i]._elm.nativeElement === match) return choices[i]; } match = match.parentElement; } return null; } } export const DIALOG_DIRECTIVES = [ MdcDialogDirective, MdcDialogTitleDirective, MdcDialogContentDirective, MdcDialogSurfaceDirective, MdcDialogContainerDirective, MdcDialogActionsDirective, MdcDialogTriggerDirective, MdcDialogDefaultDirective, MdcDialogScrimDirective ];
the_stack
importScripts("../resource/typescriptServices.js"); /** * TSWorker contains all the code that runs in the webworker and not the main UI thread. * All the compiling and code completion is done in a webworker so the UI in not blocked. */ module Cats.TSWorker { function respond(message:any) { postMessage(message,<any>[]); } /** * Simple function to stub console.log functionality since this is * not available in a webworker. */ export var console = { log: function(str: string) { respond({ method: "console", params: ["log",str] }); }, error: function(str: string) { respond({ method: "console", params: ["error",str] }); }, info: function(str: string) { respond({ method: "console", params: ["info",str] }); } }; /** * Case insensitive sorting algoritme */ function caseInsensitiveSort(a: { name: string; }, b: { name: string; }) { if (a.name.toLowerCase() < b.name.toLowerCase()) return -1; if (a.name.toLowerCase() > b.name.toLowerCase()) return 1; // the lower-case strings are equal, so now put them in local order.. if (a.name < b.name) return -1; if (a.name > b.name) return 1; return 0; } class ISense { private maxErrors = 100; private ls: ts.LanguageService; private lsHost: LanguageServiceHost; private formatOptions: ts.FormatCodeOptions; private documentRegistry: ts.DocumentRegistry; /** * Create a new TypeScript ISense instance. * */ constructor() { this.lsHost = new LanguageServiceHost(); this.documentRegistry = ts.createDocumentRegistry(); this.ls = ts.createLanguageService(this.lsHost, this.documentRegistry); this.formatOptions = this.getDefaultFormatOptions(); } private getDefaultFormatOptions(): ts.FormatCodeOptions { return { IndentSize: 4, IndentStyle: ts.IndentStyle.Smart, TabSize: 4, NewLineCharacter: "\n", ConvertTabsToSpaces: true, InsertSpaceAfterCommaDelimiter: true, InsertSpaceAfterSemicolonInForStatements: true, InsertSpaceBeforeAndAfterBinaryOperators: true, InsertSpaceAfterOpeningAndBeforeClosingNonemptyBrackets: true, InsertSpaceAfterKeywordsInControlFlowStatements: true, InsertSpaceAfterFunctionKeywordForAnonymousFunctions: true, InsertSpaceAfterOpeningAndBeforeClosingNonemptyParenthesis: false, InsertSpaceAfterOpeningAndBeforeClosingTemplateStringBraces: false, PlaceOpenBraceOnNewLineForFunctions: false, PlaceOpenBraceOnNewLineForControlBlocks: false }; } /** * Sometimes of the TS language services don't work first time * This method tries to fix that */ initialize() { try { // this.ls.refresh(); this.compile(); } catch (err) { // Silently ignore } } getTypeDefinitionAtPosition(fileName: string, pos: Position): Cats.FileRange { var script = this.lsHost.getScript(fileName); var chars = script.getPositionFromCursor(pos); var infos = this.ls.getTypeDefinitionAtPosition(fileName, chars); if (infos) { var info = infos[0]; var script2 = this.lsHost.getScript(info.fileName); // TODO handle better return { fileName: info.fileName, range: script2.getRangeFromSpan(info.textSpan) }; } else { return null; } } getDefinitionAtPosition(fileName: string, pos: Position): Cats.FileRange { var script = this.lsHost.getScript(fileName); var chars = script.getPositionFromCursor(pos); var infos = this.ls.getDefinitionAtPosition(fileName, chars); if (infos) { var info = infos[0]; var script2 = this.lsHost.getScript(info.fileName); // TODO handle better return { fileName: info.fileName, range: script2.getRangeFromSpan(info.textSpan) }; } else { return null; } } /** * Convert Services to Cats NavigateToItems */ private convertNavigateTo(item: ts.NavigateToItem): NavigateToItem { var script = this.lsHost.getScript(item.fileName); var result = { range : script.getRangeFromSpan(item.textSpan), name : item.name, fileName: item.fileName, kind: item.kind } return result; } /** * Convert the errors from a TypeScript format into Cats format */ private convertError(error: ts.Diagnostic): Cats.FileRange { var message = ts.flattenDiagnosticMessageText(error.messageText, "\n"); var severity:Severity; switch (error.category) { case ts.DiagnosticCategory.Warning: severity = Severity.Warning; return; case ts.DiagnosticCategory.Message: severity = Severity.Info; return; case ts.DiagnosticCategory.Error: default: severity = Severity.Error; } var result:Cats.FileRange = { message: message + "", severity: severity }; if (error.file) { var script = this.lsHost.getScript(error.file.fileName); result.range = script.getRange(error.start, error.length); result.fileName= error.file.fileName } return result; } /** * Get the diagnostic messages for one source file * * @param fileName name of the script. */ getErrors(fileName: string): FileRange[] { var script = this.lsHost.getScript(fileName); var errors = script.getErrors(); var result = errors.map((error) => {return this.convertError(error)}); return result; } /** * Get the diagnostic messages for all the files and compiler. */ getAllDiagnostics() { var errors: FileRange[] = []; // Let's first get the errors related to the source files this.lsHost.getScriptFileNames().forEach((fileName) => { errors = errors.concat(this.getErrors(fileName)); }); // And then let's see if one or more compiler setttings are wrong var compilerSettingsErrors = this.ls.getCompilerOptionsDiagnostics(); var newErrors = compilerSettingsErrors.map(this.convertError); errors = errors.concat(newErrors); return errors; } /** * Get the various annotations in the comments, like TODO items. */ getTodoItems() { var result:FileRange[] = []; this.lsHost.getScripts().forEach((script)=> { var entries = script.getTodoItems(); result = result.concat(entries); }); return result; } insertDocComments(fileName: string, position: Cats.Position) { var script = this.lsHost.getScript(fileName); var t = script.insertDoc(position); return t; } /** * Compile the loaded TS files and return the * compiles JS sources, mapfiles and errors (if any). */ compile(): Cats.CompileResults { var scripts = this.lsHost.getScriptFileNames(); var outputFiles: ts.OutputFile[] = []; var errors: FileRange[] = []; var alreadyProcessed :{ [fileName: string]: boolean; } = {} this.lsHost.getScripts().forEach((script) => { try { var emits = script.emitOutput(); emits.forEach((file) => { if (! alreadyProcessed[file.name]) outputFiles.push(file); alreadyProcessed[file.name] = true; }); // No need to request other files if there is only one output file // if (outputFiles.length > 0 && this.lsHost.getCompilationSettings().out) { // break; // } } catch (err) {/* ignore */} }); errors = this.getAllDiagnostics(); console.info("Errors found: " + errors.length); return { outputFiles: outputFiles, errors: errors }; } /** * Use the TSConfig file to set the compiler options */ setConfigFile(path:string,content) { var result = ts.readConfigFile(path,(path) => {return content}); var options = result.config.compilerOptions; this.lsHost.setCompilationSettings(options); this.formatOptions = this.getDefaultFormatOptions(); let editorOptions = options.formatCodeOptions || {}; for (var i in editorOptions) { this.formatOptions[i] = editorOptions[i]; } } private isExecutable(kind:string) { if (kind === "method" || kind === "function" || kind === "constructor") return true; return false; } /** * Convert the data for outline usage. */ private getOutlineModelData(fileName:string, data: ts.NavigationBarItem[]) { if ((!data) || (!data.length)) { return []; } var result:OutlineModelEntry[] = []; var script = this.lsHost.getScript(fileName); data.forEach((item) => { var extension = this.isExecutable(item.kind) ? "()" : ""; var entry:OutlineModelEntry = { label: item.text + extension, pos: script.positionToLineCol(item.spans[0].start), kind: item.kind, kids: null }; entry.kids = this.getOutlineModelData(fileName, item.childItems) result.push(entry); }); return result; } public getFormattedTextForRange(fileName: string, range?:Cats.Range): string { var start:number, end:number; var script = this.lsHost.getScript(fileName); var content = script.getContent(); if (range == null) { start = 0; end = content.length; } else { start = script.getPositionFromCursor(range.start); end = script.getPositionFromCursor(range.end); } var edits = this.ls.getFormattingEditsForRange(fileName, start, end, this.formatOptions); var result = applyEdits(content, edits); return result; } /** * Add a new script to the compiler environment */ public addScript(fileName: string, content: string) { if (this.lsHost.getScript(fileName)) { this.updateScript(fileName, content); } else { var script = this.lsHost.addScript(fileName, content, this.ls); } } // updated the content of a script public updateScript(fileName: string, content: string) { var script = this.lsHost.getScript(fileName); if (script) script.updateContent(content); } /** * Get the info at a certain position. Used for the tooltip in the editor * */ public getInfoAtPosition(fileName: string, coord: Cats.Position):TypeInfo { var script = this.lsHost.getScript(fileName); return script.getInfoAtPosition(coord); } public getNavigateToItems(search: string) { var results = this.ls.getNavigateToItems(search); return results.map(this.convertNavigateTo); } public getScriptOutline(fileName: string) { var result = this.ls.getNavigationBarItems(fileName); return this.getOutlineModelData(fileName, result); } public getRenameInfo(fileName:string, cursor: Position) { var script = this.lsHost.getScript(fileName); return script.getRenameInfo(cursor); } public findRenameLocations(fileName: string, position: Position, findInStrings: boolean, findInComments: boolean) { var script = this.lsHost.getScript(fileName); var pos = script.getPositionFromCursor(position); var result: Cats.FileRange[] = []; var entries = this.ls.findRenameLocations(fileName,pos,findInStrings,findInComments); for (var i = 0; i < entries.length; i++) { var ref = entries[i]; var refScript = this.lsHost.getScript(ref.fileName); result.push({ fileName: ref.fileName, range: refScript.getRangeFromSpan(ref.textSpan), message: refScript.getLine(ref.textSpan) }); } return result; } /** * Generic method to get references, implementations or occurences of a certain * element at a position in a source file. * * getReferencesAtPosition * getOccurrencesAtPosition * getImplementorsAtPosition */ public getCrossReference(method: string, fileName: string, cursor: Position): Cats.FileRange[] { var script = this.lsHost.getScript(fileName); var pos = script.getPositionFromCursor(cursor); var result: Cats.FileRange[] = []; var entries: ts.ReferenceEntry[]; switch (method) { case "getReferencesAtPosition": entries = this.ls.getReferencesAtPosition(fileName, pos); break; case "getOccurrencesAtPosition": entries = this.ls.getOccurrencesAtPosition(fileName, pos); break; } if (! entries) return result; for (var i = 0; i < entries.length; i++) { var ref = entries[i]; var refScript = this.lsHost.getScript(ref.fileName); result.push({ fileName: ref.fileName, range: refScript.getRangeFromSpan(ref.textSpan), message: refScript.getLine(ref.textSpan) }); } return result; } /** * Determine the possible completions available at a certain position in a file. */ public getCompletions(fileName: string, cursor: Position): ts.CompletionEntry[] { var script = this.lsHost.getScript(fileName); if (!script) return []; var completions = script.getCompletions(cursor) ; completions.sort(caseInsensitiveSort); // Sort case insensitive return completions; } } /** * Indicate to the main UI thread if this worker is busy or not * * @param value true is busy, false othewise */ function setBusy(value: boolean, methodName:string) { respond({ method: "setBusy", params: [value,methodName] }); } /******************************************************************* Create and initiate the message listener for incomming messages *******************************************************************/ var tsh: ISense; addEventListener('message', function(e) { if (!tsh) tsh = new ISense(); var msg: Cats.JSONRPCRequest = e["data"]; var methodName = msg.method; var params = msg.params; setBusy(true, methodName); try { var fn:Function = tsh[methodName]; var result = fn.apply(tsh,params); respond({ id: msg.id, result: result }); } catch (err) { var error = { description: err.description, stack: err.stack, method: methodName }; console.error("Error during processing message " + methodName); respond({ id: msg.id, error: error }); } finally { setBusy(false, methodName); } }, false); }
the_stack
import { inferModelType, isTextureSource, loadCapeToCanvas, loadImage, loadSkinToCanvas, ModelType, RemoteImage, TextureSource } from "skinview-utils"; import { Color, ColorRepresentation, EquirectangularReflectionMapping, Group, NearestFilter, PerspectiveCamera, Scene, Texture, Vector2, WebGLRenderer } from "three"; import { RootAnimation } from "./animation.js"; import { BackEquipment, PlayerObject } from "./model.js"; export interface LoadOptions { /** * Whether to make the object visible after the texture is loaded. Default is true. */ makeVisible?: boolean; } export interface CapeLoadOptions extends LoadOptions { /** * The equipment (cape or elytra) to show, defaults to "cape". * If makeVisible is set to false, this option will have no effect. */ backEquipment?: BackEquipment; } export interface SkinViewerOptions { width?: number; height?: number; skin?: RemoteImage | TextureSource; model?: ModelType | "auto-detect"; cape?: RemoteImage | TextureSource; /** * Whether the canvas contains an alpha buffer. Default is true. * This option can be turned off if you use an opaque background. */ alpha?: boolean; /** * Render target. * A new canvas is created if this parameter is unspecified. */ canvas?: HTMLCanvasElement; /** * Whether to preserve the buffers until manually cleared or overwritten. Default is false. */ preserveDrawingBuffer?: boolean; /** * The initial value of `SkinViewer.renderPaused`. Default is false. * If this option is true, rendering and animation loops will not start. */ renderPaused?: boolean; /** * The background of the scene. Default is transparent. */ background?: ColorRepresentation | Texture; /** * The panorama background to use. This option overrides 'background' option. */ panorama?: RemoteImage | TextureSource; /** * Camera vertical field of view, in degrees. Default is 50. * The distance between the object and the camera is automatically computed. */ fov?: number; } export class SkinViewer { readonly canvas: HTMLCanvasElement; readonly scene: Scene; readonly camera: PerspectiveCamera; readonly renderer: WebGLRenderer; readonly playerObject: PlayerObject; readonly playerWrapper: Group; readonly animations: RootAnimation = new RootAnimation(); readonly skinCanvas: HTMLCanvasElement; readonly capeCanvas: HTMLCanvasElement; private readonly skinTexture: Texture; private readonly capeTexture: Texture; private backgroundTexture: Texture | null = null; private _disposed: boolean = false; private _renderPaused: boolean = false; private animationID: number | null; private onContextLost: (event: Event) => void; private onContextRestored: () => void; constructor(options: SkinViewerOptions = {}) { this.canvas = options.canvas === undefined ? document.createElement("canvas") : options.canvas; // texture this.skinCanvas = document.createElement("canvas"); this.skinTexture = new Texture(this.skinCanvas); this.skinTexture.magFilter = NearestFilter; this.skinTexture.minFilter = NearestFilter; this.capeCanvas = document.createElement("canvas"); this.capeTexture = new Texture(this.capeCanvas); this.capeTexture.magFilter = NearestFilter; this.capeTexture.minFilter = NearestFilter; this.scene = new Scene(); this.camera = new PerspectiveCamera(); this.camera.position.z = 60; this.renderer = new WebGLRenderer({ canvas: this.canvas, alpha: options.alpha !== false, // default: true preserveDrawingBuffer: options.preserveDrawingBuffer === true // default: false }); this.renderer.setPixelRatio(window.devicePixelRatio); this.playerObject = new PlayerObject(this.skinTexture, this.capeTexture); this.playerObject.name = "player"; this.playerObject.skin.visible = false; this.playerObject.cape.visible = false; this.playerWrapper = new Group(); this.playerWrapper.add(this.playerObject); this.playerWrapper.position.y = 8; this.scene.add(this.playerWrapper); if (options.skin !== undefined) { this.loadSkin(options.skin, options.model); } if (options.cape !== undefined) { this.loadCape(options.cape); } if (options.width !== undefined) { this.width = options.width; } if (options.height !== undefined) { this.height = options.height; } if (options.background !== undefined) { this.background = options.background; } if (options.panorama !== undefined) { this.loadPanorama(options.panorama); } this.fov = options.fov === undefined ? 50 : options.fov; if (options.renderPaused === true) { this._renderPaused = true; this.animationID = null; } else { this.animationID = window.requestAnimationFrame(() => this.draw()); } this.onContextLost = (event: Event) => { event.preventDefault(); if (this.animationID !== null) { window.cancelAnimationFrame(this.animationID); this.animationID = null; } }; this.onContextRestored = () => { if (!this._renderPaused && !this._disposed && this.animationID === null) { this.animationID = window.requestAnimationFrame(() => this.draw()); } }; this.canvas.addEventListener("webglcontextlost", this.onContextLost, false); this.canvas.addEventListener("webglcontextrestored", this.onContextRestored, false); } loadSkin(empty: null): void; loadSkin<S extends TextureSource | RemoteImage>( source: S, model?: ModelType | "auto-detect", options?: LoadOptions ): S extends TextureSource ? void : Promise<void>; loadSkin( source: TextureSource | RemoteImage | null, model: ModelType | "auto-detect" = "auto-detect", options: LoadOptions = {} ): void | Promise<void> { if (source === null) { this.resetSkin(); } else if (isTextureSource(source)) { loadSkinToCanvas(this.skinCanvas, source); const actualModel = model === "auto-detect" ? inferModelType(this.skinCanvas) : model; this.skinTexture.needsUpdate = true; this.playerObject.skin.modelType = actualModel; if (options.makeVisible !== false) { this.playerObject.skin.visible = true; } } else { return loadImage(source).then(image => this.loadSkin(image, model, options)); } } resetSkin(): void { this.playerObject.skin.visible = false; } loadCape(empty: null): void; loadCape<S extends TextureSource | RemoteImage>( source: S, options?: CapeLoadOptions ): S extends TextureSource ? void : Promise<void>; loadCape( source: TextureSource | RemoteImage | null, options: CapeLoadOptions = {} ): void | Promise<void> { if (source === null) { this.resetCape(); } else if (isTextureSource(source)) { loadCapeToCanvas(this.capeCanvas, source); this.capeTexture.needsUpdate = true; if (options.makeVisible !== false) { this.playerObject.backEquipment = options.backEquipment === undefined ? "cape" : options.backEquipment; } } else { return loadImage(source).then(image => this.loadCape(image, options)); } } resetCape(): void { this.playerObject.backEquipment = null; } loadPanorama<S extends TextureSource | RemoteImage>( source: S ): S extends TextureSource ? void : Promise<void>; loadPanorama<S extends TextureSource | RemoteImage>( source: S ): void | Promise<void> { if (isTextureSource(source)) { if (this.backgroundTexture !== null) { this.backgroundTexture.dispose(); } this.backgroundTexture = new Texture(); this.backgroundTexture.image = source; this.backgroundTexture.mapping = EquirectangularReflectionMapping; this.backgroundTexture.needsUpdate = true; this.scene.background = this.backgroundTexture; } else { return loadImage(source).then(image => this.loadPanorama(image)); } } private draw(): void { this.animations.runAnimationLoop(this.playerObject); this.render(); this.animationID = window.requestAnimationFrame(() => this.draw()); } /** * Renders the scene to the canvas. * This method does not change the animation progress. */ render(): void { this.renderer.render(this.scene, this.camera); } setSize(width: number, height: number): void { this.camera.aspect = width / height; this.camera.updateProjectionMatrix(); this.renderer.setSize(width, height); } dispose(): void { this._disposed = true; this.canvas.removeEventListener("webglcontextlost", this.onContextLost, false); this.canvas.removeEventListener("webglcontextrestored", this.onContextRestored, false); if (this.animationID !== null) { window.cancelAnimationFrame(this.animationID); this.animationID = null; } this.renderer.dispose(); this.skinTexture.dispose(); this.capeTexture.dispose(); if (this.backgroundTexture !== null) { this.backgroundTexture.dispose(); this.backgroundTexture = null; } } get disposed(): boolean { return this._disposed; } /** * Whether rendering and animations are paused. * Setting this property to true will stop both rendering and animation loops. * Setting it back to false will resume them. */ get renderPaused(): boolean { return this._renderPaused; } set renderPaused(value: boolean) { this._renderPaused = value; if (this._renderPaused && this.animationID !== null) { window.cancelAnimationFrame(this.animationID); this.animationID = null; } else if (!this._renderPaused && !this._disposed && !this.renderer.getContext().isContextLost() && this.animationID == null) { this.animationID = window.requestAnimationFrame(() => this.draw()); } } get width(): number { return this.renderer.getSize(new Vector2()).width; } set width(newWidth: number) { this.setSize(newWidth, this.height); } get height(): number { return this.renderer.getSize(new Vector2()).height; } set height(newHeight: number) { this.setSize(this.width, newHeight); } get background(): null | Color | Texture { return this.scene.background; } set background(value: null | ColorRepresentation | Texture) { if (value === null || value instanceof Color || value instanceof Texture) { this.scene.background = value; } else { this.scene.background = new Color(value); } if (this.backgroundTexture !== null && value !== this.backgroundTexture) { this.backgroundTexture.dispose(); this.backgroundTexture = null; } } get fov(): number { return this.camera.fov; } set fov(value: number) { this.camera.fov = value; let distance = 4 + 20 / Math.tan(value / 180 * Math.PI / 2); if (distance < 10) { distance = 10; } this.camera.position.multiplyScalar(distance / this.camera.position.length()); this.camera.updateProjectionMatrix(); } }
the_stack
import { Channel, Client, Committer, ConnectOptions, Discoverer, DiscoveryService, Endorsement, EndorsementResponse, Endorser, Endpoint, IdentityContext, ProposalResponse, User, Utils } from 'fabric-common'; import * as protos from 'fabric-protos'; import { Contract, Gateway, GatewayOptions, Identity, IdentityProvider, Network, Transaction, Wallet } from 'fabric-network'; import { LifecycleCommon } from './LifecycleCommon'; import { Lifecycle } from './Lifecycle'; import { LifecyclePeer } from './LifecyclePeer'; import { EndorsementPolicy } from './Policy'; import { Collection, CollectionConfig } from './CollectionConfig'; import { URL } from 'url'; import deepEqual = require('deep-equal'); const logger: any = Utils.getLogger('LifecycleChannel'); export interface SmartContractDefinitionOptions { sequence: number; smartContractName: string; smartContractVersion: string; packageId?: string; endorsementPlugin?: string; validationPlugin?: string; endorsementPolicy?: string; collectionConfig?: Collection[] initRequired?: boolean; } export interface DefinedSmartContract { smartContractName: string; smartContractVersion: string; sequence: number; endorsementPolicy?: Buffer; collectionConfig?: Buffer; initRequired?: boolean; endorsementPlugin?: string; validationPlugin?: string; approvals?: Map<string, boolean>; } export class LifecycleChannel { private lifecycle: Lifecycle; private readonly channelName: string; private readonly wallet: Wallet; private readonly identity: string; private APPROVE: string = 'approve'; private COMMIT: string = 'commit'; private INSTANTIATE: string = 'deploy'; private UPGRADE: string = 'upgrade'; /** * internal use only * @param lifecycle * @param channelName * @param wallet * @param identity */ constructor(lifecycle: Lifecycle, channelName: string, wallet: Wallet, identity: string) { this.lifecycle = lifecycle; this.channelName = channelName; this.wallet = wallet; this.identity = identity; } /** * Approve a smart contract definition * @param peerNames string[], the names of the peer to endorse the transaction * @param ordererName string, the orderer to send the request to * @param options SmartContractDefinitionOptions, the details of the definition * @param requestTimeout number, [optional] the timeout used when performing the install operation */ public async approveSmartContractDefinition(peerNames: string[], ordererName: string, options: SmartContractDefinitionOptions, requestTimeout?: number): Promise<void> { const method: string = 'approvePackage'; logger.debug('%s - start', method); return this.submitTransaction(peerNames, ordererName, options, this.APPROVE, requestTimeout); } /** * Commit a smart contract definition * @param peerNames string[], the names of the peer to endorse the transaction * @param ordererName string, the orderer to send the request to * @param options SmartContractDefinitionOptions, the details of the definition * @param requestTimeout number, [optional] the timeout used when performing the install operation */ public async commitSmartContractDefinition(peerNames: string[], ordererName: string, options: SmartContractDefinitionOptions, requestTimeout?: number): Promise<void> { const method: string = 'commit'; logger.debug('%s - start', method); return this.submitTransaction(peerNames, ordererName, options, this.COMMIT, requestTimeout); } public async instantiateOrUpgradeSmartContractDefinition(peerNames: string[], ordererName: string, options: SmartContractDefinitionOptions, fcn: string, args: Array<string>, isUpgrade: boolean, requestTimeout?: number): Promise<void> { const functionName: string = isUpgrade ? this.UPGRADE : this.INSTANTIATE logger.debug('%s - start', functionName); const specArgs: Buffer[] = []; const specFcn: string = typeof fcn === 'undefined' ? 'init' : fcn; if (specFcn) { specArgs.push(Buffer.from(specFcn, 'utf8')); } if (!args) { args = []; } for (const arg of args) { specArgs.push(Buffer.from(arg, 'utf8')); } const ccSpec: any = { // TODO Golang is defaul in v1 fabric-client, and v1 exension always used default. Should we try to extract language from packaged contracts somehow? type: protos.protos.ChaincodeSpec.Type.GOLANG, chaincode_id: { name: options.smartContractName, version: options.smartContractVersion }, input: { args: specArgs } }; const chaincodeDeploymentSpec: protos.protos.ChaincodeDeploymentSpec = new protos.protos.ChaincodeDeploymentSpec(); chaincodeDeploymentSpec.chaincode_spec = ccSpec; const lcccSpecArgs: string[] = [ functionName, this.channelName, protos.protos.ChaincodeDeploymentSpec.encode(chaincodeDeploymentSpec).finish().toString(), '', 'escc', // default 'vscc' // default ]; return this.submitTransaction(peerNames, ordererName, options, functionName, requestTimeout, 'lscc', lcccSpecArgs); } /** * Get the commit readiness of a smart contract definition * @param peerName string, the name of the peer to endorse the transaction * @param options SmartContractDefinitionOptions, the details of the definition * @param requestTimeout number, [optional] the timeout used when performing the install operation * @return Promise<Map<string, boolean>>, the status of if an organisation has approved the definition or not */ public async getCommitReadiness(peerName: string, options: SmartContractDefinitionOptions, requestTimeout?: number): Promise<Map<string, boolean>> { const method: string = 'getCommitReadiness'; logger.debug('%s - start', method); if (!peerName) { throw new Error('parameter peerName is missing'); } if (!options) { throw new Error('parameter options is missing'); } if (!options.smartContractName) { throw new Error('missing option smartContractName'); } if (!options.smartContractVersion) { throw new Error('missing option smartContractVersion'); } const commitReadiness: Map<string, boolean> = new Map(); try { logger.debug('%s - build the get defined smart contract request', method); const protoArgs: protos.lifecycle.ICheckCommitReadinessArgs = {}; protoArgs.name = options.smartContractName; protoArgs.version = options.smartContractVersion; protoArgs.sequence = options.sequence; if (typeof options.initRequired === 'boolean') { protoArgs.init_required = options.initRequired; } if (options.endorsementPlugin) { protoArgs.endorsement_plugin = options.endorsementPlugin; } if (options.validationPlugin) { protoArgs.validation_plugin = options.validationPlugin; } if (options.endorsementPolicy) { protoArgs.validation_parameter = LifecycleChannel.getEndorsementPolicyBytes(options.endorsementPolicy); } if (options.collectionConfig) { protoArgs.collections = LifecycleChannel.getCollectionConfig(options.collectionConfig) as protos.common.ICollectionConfigPackage; } const arg: Uint8Array = protos.lifecycle.CheckCommitReadinessArgs.encode(protoArgs).finish(); const buildRequest: { fcn: string; args: Buffer[] } = { fcn: 'CheckCommitReadiness', args: [Buffer.from(arg)] }; const responses: ProposalResponse = await this.evaluateTransaction(peerName, buildRequest, requestTimeout); const payloads: Buffer[] = await LifecycleCommon.processResponse(responses); const results: protos.lifecycle.CheckCommitReadinessResult = protos.lifecycle.CheckCommitReadinessResult.decode(payloads[0]); const approvals: { [k: string]: boolean } = results.approvals; const approvalMap: Map<string, boolean> = new Map(Object.entries(approvals)); const keys: IterableIterator<string> = approvalMap.keys(); let key: any; while ((key = keys.next()).done !== true) { const isApproved: boolean = approvalMap.get(key.value); commitReadiness.set(key.value, isApproved); } logger.debug('%s - end', method); return commitReadiness; } catch (error) { logger.error('Problem with the request :: %s', error); logger.error(' problem at ::' + error.stack); throw new Error(`Could not get commit readiness, received error: ${error.message}`); } } /** * Get a list of all the committed smart contracts * @param peerName string, the name of the peer to endorse the transaction * @param requestTimeout number, [optional] the timeout used when performing the install operation * @return DefinedSmartContract[], a list of the defined smart contracts */ public async getAllCommittedSmartContracts(peerName: string, requestTimeout?: number): Promise<DefinedSmartContract[]> { const method: string = 'getAllCommittedSmartContracts'; logger.debug('%s - start', method); if (!peerName) { throw new Error('parameter peerName is missing'); } const definitions: DefinedSmartContract[] = []; try { logger.debug('%s - build the get defined smart contract request', method); const protoArgs: protos.lifecycle.IQueryChaincodeDefinitionsArgs = {}; const arg: Uint8Array = protos.lifecycle.QueryChaincodeDefinitionsArgs.encode(protoArgs).finish(); const buildRequest: { fcn: string; args: Buffer[] } = { fcn: 'QueryChaincodeDefinitions', args: [Buffer.from(arg)] }; const responses: ProposalResponse = await this.evaluateTransaction(peerName, buildRequest, requestTimeout); const payloads: Buffer[] = await LifecycleCommon.processResponse(responses); // only sent the request to one peer so only expect one response const results: protos.lifecycle.QueryChaincodeDefinitionsResult = protos.lifecycle.QueryChaincodeDefinitionsResult.decode(payloads[0]); const smartContractDefinitions: protos.lifecycle.QueryChaincodeDefinitionsResult.IChaincodeDefinition[] = results.chaincode_definitions; for (const smartContractDefinition of smartContractDefinitions) { const defined: DefinedSmartContract = { smartContractName: smartContractDefinition.name, sequence: Number(smartContractDefinition.sequence), smartContractVersion: smartContractDefinition.version, initRequired: smartContractDefinition.init_required, endorsementPlugin: smartContractDefinition.endorsement_plugin, validationPlugin: smartContractDefinition.validation_plugin, endorsementPolicy: Buffer.from(smartContractDefinition.validation_parameter), collectionConfig: Buffer.from(smartContractDefinition.collections.config), }; definitions.push(defined); } logger.debug('%s - end', method); return definitions; } catch (error) { logger.error('Problem with request :: %s', error); logger.error(' problem at ::' + error.stack); throw new Error(`Could not get smart contract definitions, received error: ${error.message}`); } } /** * Get a list of all the committed smart contracts * @param peerName * @param requestTimeout * @return DefinedSmartContract[], a list of the defined smart contracts */ public async getAllInstantiatedSmartContracts(peerName: string, requestTimeout?: number): Promise<DefinedSmartContract[]> { const method: string = 'getAllInstantiatedSmartContracts'; logger.debug('%s - start', method); if (!peerName) { throw new Error('parameter peerName is missing'); } const definitions: DefinedSmartContract[] = []; try { logger.debug('%s - build the get defined smart contract request', method); const buildRequest: { fcn: string; args: Buffer[] } = { fcn: 'GetChaincodes', args: [] }; const result: ProposalResponse = await this.evaluateTransaction(peerName, buildRequest, requestTimeout, 'lscc'); if (result) { // will only be one response as we are only querying one peer if (result.errors && result.errors[0] instanceof Error) { throw result.errors[0]; } const response: EndorsementResponse = result.responses[0]; if (response.response) { if (response.response.status === 200) { const queryTrans: protos.protos.ChaincodeQueryResponse = protos.protos.ChaincodeQueryResponse.decode(response.response.payload); for (const chaincode of queryTrans.chaincodes) { const defined: DefinedSmartContract = { smartContractName: chaincode.name, sequence: Number(-1), smartContractVersion: chaincode.version, initRequired: undefined, endorsementPlugin: chaincode.escc, validationPlugin: chaincode.vscc, endorsementPolicy: undefined, collectionConfig: undefined, }; definitions.push(defined); } logger.debug('%s - end', method); return definitions; } else if (response.response.message) { throw new Error(response.response.message); } } // no idea what we have, lets fail it and send it back throw new Error(response.toString()); } throw new Error('Payload results are missing from the query'); } catch (error) { logger.error('Problem with request :: %s', error); logger.error(' problem at ::' + error.stack); throw new Error(`Could not get smart contract definitions, received error: ${error.message}`); } } /** * Get the details of a committed smart contract * @param peerName string, the name of the peer to endorse the transaction * @param smartContractName string, the name of the comitted smart contract to get the details for * @param requestTimeout number, [optional] the timeout used when performing the install operation * @return DefinedSmartContract, the defined smart contract */ public async getCommittedSmartContract(peerName: string, smartContractName: string, requestTimeout?: number): Promise<DefinedSmartContract> { const method: string = 'getCommittedSmartContract'; logger.debug('%s - start', method); if (!peerName) { throw new Error('parameter peerName is missing'); } if (!smartContractName) { throw new Error('parameter smartContractName is missing'); } let defined: DefinedSmartContract; try { logger.debug('%s - build the get defined smart contract request', method); const protoArgs: protos.lifecycle.IQueryChaincodeDefinitionArgs = { name: smartContractName }; const arg: Uint8Array = protos.lifecycle.QueryChaincodeDefinitionArgs.encode(protoArgs).finish(); const buildRequest: { fcn: string; args: Buffer[] } = { fcn: 'QueryChaincodeDefinition', args: [Buffer.from(arg)] }; const responses: ProposalResponse = await this.evaluateTransaction(peerName, buildRequest, requestTimeout); const payloads: Buffer[] = await LifecycleCommon.processResponse(responses); const results: protos.lifecycle.QueryChaincodeDefinitionResult = protos.lifecycle.QueryChaincodeDefinitionResult.decode(payloads[0]); defined = { smartContractName: smartContractName, sequence: Number(results.sequence), smartContractVersion: results.version, initRequired: results.init_required, endorsementPlugin: results.endorsement_plugin, validationPlugin: results.validation_plugin, endorsementPolicy: Buffer.from(results.validation_parameter), collectionConfig: Buffer.from(results.collections.config) }; const approvals: { [k: string]: boolean } = results.approvals; const approvalMap: Map<string, boolean> = new Map(Object.entries(approvals)) const keys: IterableIterator<string> = approvalMap.keys(); let key: any; defined.approvals = new Map<string, boolean>(); while ((key = keys.next()).done !== true) { const isApproved: boolean = approvalMap.get(key.value); defined.approvals.set(key.value, isApproved); } logger.debug('%s - end', method); return defined; } catch (error) { logger.error('Problem with the request :: %s', error); logger.error(' problem at ::' + error.stack); throw new Error(`Could not get smart contract definition, received error: ${error.message}`); } } public static getEndorsementPolicyBytes(endorsementPolicy: string, isV1: boolean = false): Buffer { const method: string = 'getEndorsementPolicyBytes'; logger.debug('%s - start', method); if (!endorsementPolicy || endorsementPolicy === '') { throw new Error('Missing parameter endorsementPolicy'); } const protoArgs: protos.common.IApplicationPolicy = {}; if (endorsementPolicy.startsWith(EndorsementPolicy.AND) || endorsementPolicy.startsWith(EndorsementPolicy.OR) || endorsementPolicy.startsWith(EndorsementPolicy.OUT_OF)) { logger.debug('%s - have an actual policy :: %s', method, endorsementPolicy); const policy: EndorsementPolicy = new EndorsementPolicy(); const signaturePolicy: protos.common.SignaturePolicyEnvelope = policy.buildPolicy(endorsementPolicy); protoArgs.signature_policy = signaturePolicy; } else if (isV1) { throw new Error(`Cannot build endorsement policy from user input: ${endorsementPolicy}`); } else { logger.debug('%s - have a policy reference :: %s', method, endorsementPolicy); protoArgs.channel_config_policy_reference = endorsementPolicy; } let applicationPolicy: Uint8Array; if (isV1) { applicationPolicy = protos.common.SignaturePolicyEnvelope.encode(protoArgs.signature_policy).finish(); } else { applicationPolicy = protos.common.ApplicationPolicy.encode(protoArgs).finish(); } return Buffer.from(applicationPolicy); } public static getCollectionConfig(collectionConfig: Collection[], asBuffer: boolean = false): Buffer | protos.common.CollectionConfigPackage { const collection: protos.common.CollectionConfigPackage = CollectionConfig.buildCollectionConfigPackage(collectionConfig); if (asBuffer) { const arg: Uint8Array = protos.common.CollectionConfigPackage.encode({ config: collection.config }).finish(); return Buffer.from(arg); } else { return collection; } } public async getDiscoveredPeerNames(peerNames: string[], requestTimeout?: number): Promise<string[]> { if (!peerNames || peerNames.length === 0) { throw new Error('parameter peers was missing or empty array'); } const gateway: Gateway = new Gateway(); const gatewayOptions: GatewayOptions = { wallet: this.wallet, identity: this.identity, discovery: { enabled: false } }; if (requestTimeout) { gatewayOptions.eventHandlerOptions = { commitTimeout: requestTimeout, endorseTimeout: requestTimeout }; } try { const fabricClient: Client = new Client('lifecycle'); logger.debug('%s - connect to the network'); await gateway.connect(fabricClient, gatewayOptions); const network: Network = await gateway.getNetwork(this.channelName); logger.debug('%s - add the endorsers to the channel'); const channel: Channel = network.getChannel(); const allEndorsers: Endorser[] = await this.discoverPeers(peerNames, fabricClient, channel, gateway); const filteredEndorsers: Endorser[] = this.filterDuplicateEndorsers(allEndorsers); // Endorsers should be unique as they've been filtered out by endpoint urls. return filteredEndorsers.map((endorser: Endorser) => { return endorser.name; }); } catch (error) { throw new Error(`Could discover peers, received error ${error.message}`); } finally { gateway.disconnect(); } } public async getDiscoveredPeers(peerNames: string[], requestTimeout?: number): Promise<Endorser[]> { if (!peerNames || peerNames.length === 0) { throw new Error('parameter peers was missing or empty array'); } const gateway: Gateway = new Gateway(); const gatewayOptions: GatewayOptions = { wallet: this.wallet, identity: this.identity, discovery: { enabled: false } }; if (requestTimeout) { gatewayOptions.eventHandlerOptions = { commitTimeout: requestTimeout, endorseTimeout: requestTimeout }; } try { const fabricClient: Client = new Client('lifecycle'); logger.debug('%s - connect to the network'); await gateway.connect(fabricClient, gatewayOptions); const network: Network = await gateway.getNetwork(this.channelName); logger.debug('%s - add the endorsers to the channel'); const channel: Channel = network.getChannel(); const allEndorsers: Endorser[] = await this.discoverPeers(peerNames, fabricClient, channel, gateway); const filteredEndorsers: Endorser[] = this.filterDuplicateEndorsers(allEndorsers); // Endorsers should be unique as they've been filtered out by endpoint urls. return filteredEndorsers; } catch (error) { throw new Error(`Could discover peers, received error ${error.message}`); } finally { gateway.disconnect(); } } private filterDuplicateEndorsers(endorsers: Endorser[]): Endorser[] { // TODO JAKE: THIS MIGHT NOT BE REQUIRED ANYMORE WHEN WE UPGRADE TO USE LATEST SDK, AS THERE WAS A PR TO FIX DUPLICATE ENDORSERS. for (let currentIndex: number = endorsers.length - 1; currentIndex >= 0; currentIndex--) { const endorser: Endorser = endorsers[currentIndex]; const duplicateIndex: number = endorsers.findIndex((_endorser: Endorser) => { if (_endorser.endpoint['url'] !== endorser.endpoint['url']) { return false; } else if (!deepEqual(_endorser.endpoint['options'] || {}, endorser.endpoint['options'] || {})) { return false; } else { return _endorser.name !== endorser.name; } }); if (duplicateIndex === -1) { continue; } else { const duplicateEndorser: Endorser = endorsers[duplicateIndex]; const duplicateEndorserIsUrl: boolean = duplicateEndorser.name.includes('.') || duplicateEndorser.name.includes(':'); const endorserIsUrl: boolean = endorser.name.includes('.') || endorser.name.includes(':'); let indexToRemove: number; if (duplicateEndorserIsUrl && !endorserIsUrl) { indexToRemove = duplicateIndex; } else if (!duplicateEndorserIsUrl && endorserIsUrl) { indexToRemove = currentIndex; } else { // Keep either one indexToRemove = duplicateIndex; } endorsers.splice(indexToRemove, 1); } } return endorsers; } public async discoverChannel(peerNames: string[], fabricClient: Client, channel: Channel, gateway: Gateway): Promise<any> { const endorsers: Endorser[] = []; const asLocalHost: boolean = this.hasLocalhostURLs(peerNames); for (const peerName of peerNames) { const endorser: Endorser = await this.createEndorser(peerName, fabricClient); channel.addEndorser(endorser, true); endorsers.push(endorser); } const discoverers: Discoverer[] = []; for (const peer of endorsers) { const discoverer: Discoverer = channel.client.newDiscoverer(peer.name, peer.mspid); await discoverer.connect(peer.endpoint); discoverers.push(discoverer); } const discoveryService: DiscoveryService = channel.newDiscoveryService(this.channelName); const identity: Identity = gateway.getIdentity(); const provider: IdentityProvider = this.wallet.getProviderRegistry().getProvider(identity.type); const user: User = await provider.getUserContext(identity, this.identity); const identityContext: IdentityContext = fabricClient.newIdentityContext(user); // do the three steps discoveryService.build(identityContext); discoveryService.sign(identityContext); const result: {msps: any, orderers: any, peers_by_org: any, timestamp: number} = await discoveryService.send({ asLocalhost: asLocalHost, targets: discoverers }); return result; } private async discoverPeers(peerNames: string[], fabricClient: Client, channel: Channel, gateway: Gateway): Promise<Endorser[]> { await this.discoverChannel(peerNames, fabricClient, channel, gateway); const allEndorsers: Endorser[] = channel.getEndorsers(); return allEndorsers; } public async submitTransaction(peerNames: string[], ordererName: string, options: SmartContractDefinitionOptions, functionName: string, requestTimeout?: number, smartContract: string = '_lifecycle', lcccSpecArgs?: string[]): Promise<void> { if (!peerNames || peerNames.length === 0 ) { throw new Error('parameter peers was missing or empty array'); } if (!options) { throw new Error('parameter options is missing'); } if (!options.sequence) { throw new Error('missing option sequence'); } if (!options.smartContractName) { throw new Error('missing option smartContractName'); } if (!options.smartContractVersion) { throw new Error('missing option smartContractVersion'); } const endorsers: Endorser[] = []; let committer: Committer; const gateway: Gateway = new Gateway(); try { const gatewayOptions: GatewayOptions = { wallet: this.wallet, identity: this.identity, discovery: { enabled: false } }; if (requestTimeout) { gatewayOptions.eventHandlerOptions = { commitTimeout: requestTimeout, endorseTimeout: requestTimeout }; } const fabricClient: Client = new Client('lifecycle'); logger.debug('%s - connect to the network'); await gateway.connect(fabricClient, gatewayOptions); const network: Network = await gateway.getNetwork(this.channelName); logger.debug('%s - add the endorsers to the channel'); const channel: Channel = network.getChannel(); const alreadyKnownPeers: string[] = peerNames.filter((peerName: string) => { return this.lifecycle.peerExists(peerName); }); let channelDiscoveryResults: {msps: any, orderers: any, peers_by_org: any, timestamp: number}; if (!ordererName) { // Discover channel msps, orderers, peers, etc. channelDiscoveryResults = await this.discoverChannel(peerNames, fabricClient, channel, gateway); if (channelDiscoveryResults.orderers && Object.keys(channelDiscoveryResults.orderers).length > 0){ const orderers: any = Object.entries(channelDiscoveryResults.orderers); // Get first orderer ordererName = orderers[0][1].endpoints[0].host; } if (!ordererName){ throw new Error('Unable to discover any orderers.'); } } const allEndorsers: Endorser[] = await this.discoverPeers(alreadyKnownPeers, fabricClient, channel, gateway); for (const peerName of peerNames) { const endorser: Endorser = allEndorsers.find((_endorser: Endorser) => { return _endorser.name === peerName; }); if (!endorser) { throw new Error(`Could not find peer ${peerName} in discovered peers`); } else { endorsers.push(endorser); } } let ordererConnectOptions: ConnectOptions = this.lifecycle.getOrderer(ordererName); if (!ordererConnectOptions){ // If the user hasn't provided an orderer, try to manualy build the connection options. const orderers: any = Object.entries(channelDiscoveryResults.orderers); // Get first orderer's url - will be used for building connection options. const _ordererUrl: string = orderers[0][1].endpoints[0].name // Get first orderer's msp. const _ordererMsp: any = channelDiscoveryResults.msps[orderers[0][0]] const isGrpcs: boolean = endorsers[0].endpoint['protocol'] === 'grpcs' ? true : false; // Initiate connection options. ordererConnectOptions = { url: (isGrpcs) ? `grpcs://${_ordererUrl}` : `grpc://${_ordererUrl}` }; if (isGrpcs){ // Set pem if (_ordererMsp.tlsRootCerts && _ordererMsp.tlsIntermediateCerts){ // Root and intermediate certs. ordererConnectOptions.pem = [_ordererMsp.tlsRootCerts, _ordererMsp.tlsIntermediateCerts].join('\n'); } else { // Only a root cert. ordererConnectOptions.pem = _ordererMsp.tlsRootCerts; } } } committer = fabricClient.getCommitter(ordererName); const endpoint: Endpoint = fabricClient.newEndpoint(ordererConnectOptions); committer.setEndpoint(endpoint); // @ts-ignore await committer.connect(); channel.addCommitter(committer, true); const contract: Contract = network.getContract(smartContract); let transaction: Transaction; let arg: Uint8Array; if (functionName === this.APPROVE || functionName === this.COMMIT) { const protoArgs: protos.lifecycle.IApproveChaincodeDefinitionForMyOrgArgs | protos.lifecycle.ICommitChaincodeDefinitionArgs = {}; if (functionName === this.APPROVE) { logger.debug('%s - build the approve smart contract argument'); const source: protos.lifecycle.ChaincodeSource = new protos.lifecycle.ChaincodeSource(); if (options.packageId) { const local: protos.lifecycle.ChaincodeSource.Local = new protos.lifecycle.ChaincodeSource.Local(); local.package_id = options.packageId; source.local_package = local; } else { const unavailable: protos.lifecycle.ChaincodeSource.Unavailable = new protos.lifecycle.ChaincodeSource.Unavailable(); source.unavailable = unavailable; } (protoArgs as protos.lifecycle.IApproveChaincodeDefinitionForMyOrgArgs).source = source; } else { logger.debug('%s - build the commit smart contract argument'); } protoArgs.name = options.smartContractName; protoArgs.version = options.smartContractVersion; protoArgs.sequence = options.sequence; if (typeof options.initRequired === 'boolean') { protoArgs.init_required = options.initRequired; } if (options.endorsementPlugin) { protoArgs.endorsement_plugin = options.endorsementPlugin; } if (options.validationPlugin) { protoArgs.validation_plugin = options.validationPlugin; } if (options.endorsementPolicy) { const endorsementPolicyBuffer: Buffer = LifecycleChannel.getEndorsementPolicyBytes(options.endorsementPolicy); protoArgs.validation_parameter = endorsementPolicyBuffer; } if (options.collectionConfig) { protoArgs.collections = LifecycleChannel.getCollectionConfig(options.collectionConfig) as protos.common.ICollectionConfigPackage; } if (functionName === this.APPROVE) { transaction = contract.createTransaction('ApproveChaincodeDefinitionForMyOrg'); arg = protos.lifecycle.ApproveChaincodeDefinitionForMyOrgArgs.encode(protoArgs).finish(); } else { transaction = contract.createTransaction('CommitChaincodeDefinition'); arg = protos.lifecycle.CommitChaincodeDefinitionArgs.encode(protoArgs).finish(); } } else { // functionName === this.INSTANTIATE || functionName === this.UPGRADE if (options.endorsementPolicy) { const endorsementPolicyBuffer: Buffer = LifecycleChannel.getEndorsementPolicyBytes(options.endorsementPolicy, true); lcccSpecArgs[3] = endorsementPolicyBuffer.toString(); } if (options.endorsementPlugin && typeof options.endorsementPlugin === 'string') { lcccSpecArgs[4] = options.endorsementPlugin; } if (options.validationPlugin && typeof options.validationPlugin === 'string') { lcccSpecArgs[5] = options.validationPlugin; } if (options.collectionConfig) { lcccSpecArgs[6] = LifecycleChannel.getCollectionConfig(options.collectionConfig, true).toString(); } transaction = contract.createTransaction(functionName); } transaction.setEndorsingPeers(endorsers); if (!lcccSpecArgs) { const txArg: Buffer = Buffer.from(arg); await transaction.submit(txArg as any); } else if (options.collectionConfig) { await transaction.submit(lcccSpecArgs[1], lcccSpecArgs[2], lcccSpecArgs[3], lcccSpecArgs[4], lcccSpecArgs[5], lcccSpecArgs[6]); } else { await transaction.submit(lcccSpecArgs[1], lcccSpecArgs[2], lcccSpecArgs[3], lcccSpecArgs[4], lcccSpecArgs[5]); } logger.debug('%s - submitted successfully'); } catch (error) { logger.error('Problem with the lifecycle approval :: %s', error); logger.error(' problem at ::' + error.stack); throw new Error(`Could not ${functionName} smart contract definition, received error: ${error.message}`); } finally { // this will disconnect the endorsers and committer gateway.disconnect(); } } private async createEndorser(peerName: string, fabricClient: Client): Promise<Endorser> { const peer: LifecyclePeer = this.lifecycle.peers.get(peerName); fabricClient.setTlsClientCertAndKey(peer.clientCertKey!, peer.clientKey!); const peerConnectOptions: ConnectOptions = { url: peer.url }; if (peer.pem) { peerConnectOptions.pem = peer.pem; } if (peer.sslTargetNameOverride) { peerConnectOptions['ssl-target-name-override'] = peer.sslTargetNameOverride; } if (peer.requestTimeout) { peerConnectOptions.requestTimeout = peer.requestTimeout; } if (peer.apiOptions) { Object.assign(peerConnectOptions, peer.apiOptions); } // this will add the peer to the list of endorsers const endorser: Endorser = fabricClient.getEndorser(peer.name, peer.mspid); if (!endorser['connected']){ const endpoint: Endpoint = fabricClient.newEndpoint(peerConnectOptions); endorser.setEndpoint(endpoint); // @ts-ignore await endorser.connect(); } return endorser; } private async evaluateTransaction(peerName: string, buildRequest: any, requestTimeout?: number, smartContractName: string = '_lifecycle'): Promise<ProposalResponse> { const gateway: Gateway = new Gateway(); const fabricClient: Client = new Client('lifecycle'); const endorser: Endorser = await this.createEndorser(peerName, fabricClient); try { const gatewayOptions: GatewayOptions = { wallet: this.wallet, identity: this.identity, discovery: { enabled: false } }; logger.debug('%s - connect to the network'); await gateway.connect(fabricClient, gatewayOptions); const network: Network = await gateway.getNetwork(this.channelName); // we are going to talk to lifecycle which is really just a smart contract const endorsement: Endorsement = network.getChannel().newEndorsement(smartContractName); endorsement.build(network.getGateway().identityContext, buildRequest); logger.debug('%s - sign the request'); endorsement.sign(network.getGateway().identityContext); const endorseRequest: any = { targets: [endorser] }; if (requestTimeout) { endorseRequest.requestTimeout = requestTimeout; } logger.debug('%s - send the query request'); const response: ProposalResponse = await endorsement.send(endorseRequest); return response; } finally { gateway.disconnect(); endorser.disconnect(); } } private isLocalhostURL(url: string): boolean { const parsedURL: URL = new URL(url); const localhosts: string[] = [ 'localhost', '127.0.0.1' ]; return localhosts.indexOf(parsedURL.hostname) !== -1; } private hasLocalhostURLs(peerNames: string[]): boolean { const urls: string[] = []; for (const peerName of peerNames) { const peer: LifecyclePeer = this.lifecycle.peers.get(peerName); urls.push(peer.url); } return urls.some((url: string) => this.isLocalhostURL(url)); } }
the_stack
* @module OrbitGT */ //package orbitgt.system.buffer; type int8 = number; type int16 = number; type int32 = number; type float32 = number; type float64 = number; import { InStream } from "../io/InStream"; import { OutStream } from "../io/OutStream"; import { ALong } from "../runtime/ALong"; import { Numbers } from "../runtime/Numbers"; import { Strings } from "../runtime/Strings"; import { ABuffer } from "./ABuffer"; /** * Helper class for reading multi-byte numbers. */ /** @internal */ export class LittleEndian { /** * This class has static methods only. */ private constructor() { } /** * Read an unsigned 8-bit integer. */ public static readBufferByte(buffer: ABuffer, offset: int32): int32 { let b0: int32 = buffer.get(offset); return (b0); } /** * Read an unsigned 8-bit integer. */ public static readStreamByte(stream: InStream): int32 { let b0: int32 = stream.read(); return (b0); } /** * Write an unsigned 8-bit integer. */ public static writeBufferByte(buffer: ABuffer, offset: int32, value: int32): void { buffer.set(offset, value); } /** * Write an unsigned 8-bit integer. */ public static writeStreamByte(stream: OutStream, value: int32): void { stream.write(value); } /** * Read an unsigned 16-bit integer. */ public static readBufferShort(buffer: ABuffer, offset: int32): int32 { let b0: int32 = buffer.get(offset++); let b1: int32 = buffer.get(offset++); return (b1 << 8) | (b0); } /** * Read an unsigned 16-bit integer. */ public static readStreamShort(stream: InStream): int32 { let b0: int32 = stream.read(); let b1: int32 = stream.read(); return (b1 << 8) | (b0); } /** * Write an unsigned 16-bit integer. */ public static writeBufferShort(buffer: ABuffer, offset: int32, value: int32): void { buffer.set(offset++, (value >> 0)); buffer.set(offset++, (value >> 8)); } /** * Write an unsigned 16-bit integer. */ public static writeStreamShort(stream: OutStream, value: int32): void { stream.write(value >> 0); stream.write(value >> 8); } /** * Read an unsigned 24-bit integer. */ public static readBufferInt3(buffer: ABuffer, offset: int32): int32 { let b0: int32 = buffer.get(offset++); let b1: int32 = buffer.get(offset++); let b2: int32 = buffer.get(offset++); return (b2 << 16) | (b1 << 8) | (b0); } /** * Read an unsigned 24-bit integer. */ public static readStreamInt3(stream: InStream): int32 { let b0: int32 = stream.read(); let b1: int32 = stream.read(); let b2: int32 = stream.read(); return (b2 << 16) | (b1 << 8) | (b0); } /** * Write an unsigned 24-bit integer. */ public static writeBufferInt3(buffer: ABuffer, offset: int32, value: int32): void { buffer.set(offset++, (value >> 0)); buffer.set(offset++, (value >> 8)); buffer.set(offset++, (value >> 16)); } /** * Write an unsigned 24-bit integer. */ public static writeStreamInt3(stream: OutStream, value: int32): void { stream.write(value >> 0); stream.write(value >> 8); stream.write(value >> 16); } /** * Read a signed 32-bit integer. */ public static readBufferInt(buffer: ABuffer, offset: int32): int32 { let b0: int32 = buffer.get(offset++); let b1: int32 = buffer.get(offset++); let b2: int32 = buffer.get(offset++); let b3: int32 = buffer.get(offset++); return (b3 << 24) | (b2 << 16) | (b1 << 8) | (b0); } /** * Read a signed 32-bit integer. */ public static readStreamInt(stream: InStream): int32 { let b0: int32 = stream.read(); let b1: int32 = stream.read(); let b2: int32 = stream.read(); let b3: int32 = stream.read(); return (b3 << 24) | (b2 << 16) | (b1 << 8) | (b0); } /** * Write a signed 32-bit integer. */ public static writeBufferInt(buffer: ABuffer, offset: int32, value: int32): void { buffer.set(offset++, (value >> 0)); buffer.set(offset++, (value >> 8)); buffer.set(offset++, (value >> 16)); buffer.set(offset++, (value >> 24)); } /** * Write a signed 32-bit integer. */ public static writeStreamInt(stream: OutStream, value: int32): void { stream.write(value >> 0); stream.write(value >> 8); stream.write(value >> 16); stream.write(value >> 24); } /** * Read a signed 64-bit integer. */ public static readBufferLong(buffer: ABuffer, offset: int32): ALong { let b0: int32 = buffer.get(offset++); let b1: int32 = buffer.get(offset++); let b2: int32 = buffer.get(offset++); let b3: int32 = buffer.get(offset++); let b4: int32 = buffer.get(offset++); let b5: int32 = buffer.get(offset++); let b6: int32 = buffer.get(offset++); let b7: int32 = buffer.get(offset++); return ALong.fromBytes(b7, b6, b5, b4, b3, b2, b1, b0); } /** * Read a signed 64-bit integer. */ public static readStreamLong(stream: InStream): ALong { let b0: int32 = stream.read(); let b1: int32 = stream.read(); let b2: int32 = stream.read(); let b3: int32 = stream.read(); let b4: int32 = stream.read(); let b5: int32 = stream.read(); let b6: int32 = stream.read(); let b7: int32 = stream.read(); return ALong.fromBytes(b7, b6, b5, b4, b3, b2, b1, b0); } /** * Write a signed 64-bit integer. */ public static writeBufferLong(buffer: ABuffer, offset: int32, value: ALong): void { buffer.set(offset++, value.getByte(0)); buffer.set(offset++, value.getByte(1)); buffer.set(offset++, value.getByte(2)); buffer.set(offset++, value.getByte(3)); buffer.set(offset++, value.getByte(4)); buffer.set(offset++, value.getByte(5)); buffer.set(offset++, value.getByte(6)); buffer.set(offset++, value.getByte(7)); } /** * Write a signed 64-bit integer. */ public static writeStreamLong(stream: OutStream, value: ALong): void { stream.write(value.getByte(0)); stream.write(value.getByte(1)); stream.write(value.getByte(2)); stream.write(value.getByte(3)); stream.write(value.getByte(4)); stream.write(value.getByte(5)); stream.write(value.getByte(6)); stream.write(value.getByte(7)); } /** * Read a signed 32-bit float. */ public static readBufferFloat(buffer: ABuffer, offset: int32): float32 { return Numbers.intBitsToFloat(LittleEndian.readBufferInt(buffer, offset)); } /** * Read a signed 32-bit float. */ public static readStreamFloat(stream: InStream): float32 { return Numbers.intBitsToFloat(LittleEndian.readStreamInt(stream)); } /** * Write a signed 32-bit float. */ public static writeBufferFloat(buffer: ABuffer, offset: int32, value: float32): void { LittleEndian.writeBufferInt(buffer, offset, Numbers.floatToIntBits(value)); } /** * Write a signed 32-bit float. */ public static writeStreamFloat(stream: OutStream, value: float32): void { LittleEndian.writeStreamInt(stream, Numbers.floatToIntBits(value)); } /** * Read a signed 64-bit float. */ public static readBufferDouble(buffer: ABuffer, offset: int32): float64 { return Numbers.longBitsToDouble(LittleEndian.readBufferLong(buffer, offset)); } /** * Read a signed 64-bit float. */ public static readStreamDouble(stream: InStream): float64 { return Numbers.longBitsToDouble(LittleEndian.readStreamLong(stream)); } /** * Write a signed 64-bit float. */ public static writeBufferDouble(buffer: ABuffer, offset: int32, value: float64): void { LittleEndian.writeBufferLong(buffer, offset, Numbers.doubleToLongBits(value)); } /** * Write a signed 64-bit float. */ public static writeStreamDouble(stream: OutStream, value: float64): void { LittleEndian.writeStreamLong(stream, Numbers.doubleToLongBits(value)); } /** * Read a string. */ public static readBufferString(buffer: ABuffer, offset: int32): string { let valueLength: int32 = LittleEndian.readBufferInt(buffer, offset); if (valueLength < 0) return null; offset += 4; let value: string = ""; for (let i: number = 0; i < valueLength; i++) value = Strings.appendChar(value, LittleEndian.readBufferShort(buffer, offset + 2 * i)); return value; } /** * Read a string. */ public static readStreamString(stream: InStream): string { let valueLength: int32 = LittleEndian.readStreamInt(stream); if (valueLength < 0) return null; let value: string = ""; for (let i: number = 0; i < valueLength; i++) value = Strings.appendChar(value, LittleEndian.readStreamShort(stream)); return value; } /** * Write a string. */ public static writeStreamString(stream: OutStream, value: string): void { if (value == null) { LittleEndian.writeStreamInt(stream, -1); } else { let valueLength: int32 = Strings.getLength(value); LittleEndian.writeStreamInt(stream, valueLength); for (let i: number = 0; i < valueLength; i++) LittleEndian.writeStreamShort(stream, Strings.getCharAt(value, i)); } } /** * Get the number of bytes in a string. */ public static getStringByteCount(value: string): int32 { if (value == null) return 4; else return 4 + 2 * Strings.getLength(value); } }
the_stack
* 文本返回的自定义词库结果 */ export interface CustomResult { /** * 命中的自定义关键词 */ Keywords?: Array<string> /** * 自定义库id */ LibId?: string /** * 自定义词库名称 */ LibName?: string /** * 命中的自定义关键词的类型 */ Type?: string } /** * 文本识别结果详情 */ export interface TextData { /** * 是否恶意 0:正常 1:可疑 */ EvilFlag: number /** * 恶意类型 100:正常 20001:政治 20002:色情 20006:涉毒违法 20007:谩骂 20105:广告引流 24001:暴恐 */ EvilType: number /** * 消息类公共相关参数 */ Common?: TextOutputComm /** * 返回的自定义词库结果 */ CustomResult?: Array<CustomResult> /** * 返回的详细结果 */ DetailResult?: Array<DetailResult> /** * 消息类ID信息 */ ID?: TextOutputID /** * 消息类输出结果 */ Res?: TextOutputRes /** * 账号风险检测结果 */ RiskDetails?: Array<RiskDetails> /** * 最终使用的BizType */ BizType?: number /** * 和请求中的DataId一致,原样返回 */ DataId?: string /** * 恶意标签,Normal:正常,Polity:涉政,Porn:色情,Illegal:违法,Abuse:谩骂,Terror:暴恐,Ad:广告,Custom:自定义关键词 */ EvilLabel?: string /** * 输出的其他信息,不同客户内容不同 */ Extra?: string /** * 命中的关键词 */ Keywords?: Array<string> /** * 命中的模型分值 */ Score?: number /** * 建议值,Block:打击,Review:待复审,Normal:正常 */ Suggestion?: string } /** * TextModeration请求参数结构体 */ export interface TextModerationRequest { /** * 文本内容Base64编码。原文长度需小于15000字节,即5000个汉字以内。 */ Content: string /** * 设备相关信息 */ Device?: Device /** * 用户相关信息 */ User?: User /** * 该字段用于标识业务场景。您可以在内容安全控制台创建对应的ID,配置不同的内容审核策略,通过接口调用,默认不填为0,后端使用默认策略 */ BizType?: number /** * 数据ID,英文字母、下划线、-组成,不超过64个字符 */ DataId?: string /** * 业务应用ID */ SdkAppId?: number } /** * 文本返回的详细结果 */ export interface DetailResult { /** * 恶意标签,Normal:正常,Polity:涉政,Porn:色情,Illegal:违法,Abuse:谩骂,Terror:暴恐,Ad:广告,Custom:自定义关键词 */ EvilLabel?: string /** * 恶意类型 100:正常 20001:政治 20002:色情 20006:涉毒违法 20007:谩骂 20105:广告引流 24001:暴恐 */ EvilType?: number /** * 该标签下命中的关键词 */ Keywords?: Array<string> /** * 该标签模型命中的分值 */ Score?: number } /** * ImageModeration返回参数结构体 */ export interface ImageModerationResponse { /** * 识别结果 */ Data?: ImageData /** * 业务返回码 */ BusinessCode?: number /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * TextModeration返回参数结构体 */ export interface TextModerationResponse { /** * 识别结果 */ Data?: TextData /** * 业务返回码 */ BusinessCode?: number /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * ImageModeration请求参数结构体 */ export interface ImageModerationRequest { /** * 文件内容 Base64,与FileUrl必须二填一 */ FileContent?: string /** * 文件MD5值 */ FileMD5?: string /** * 文件地址 */ FileUrl?: string } /** * CreateFileSample请求参数结构体 */ export interface CreateFileSampleRequest { /** * 文件类型结构数组 */ Contents: Array<FileSample> /** * 恶意类型 100:正常 20001:政治 20002:色情 20006:涉毒违法 20007:谩骂 24001:暴恐 20105:广告引流 */ EvilType: number /** * image:图片 */ FileType: string /** * 样本类型 1:黑库 2:白库 */ Label: number } /** * 图片识别结果详情 */ export interface ImageData { /** * 是否恶意 0:正常 1:可疑 */ EvilFlag: number /** * 恶意类型 100:正常 20001:政治 20002:色情 20006:涉毒违法 20007:谩骂 20103:性感 24001:暴恐 */ EvilType: number /** * 图片二维码详情 */ CodeDetect?: CodeDetect /** * 图片性感详情 */ HotDetect?: ImageHotDetect /** * 图片违法详情 */ IllegalDetect?: ImageIllegalDetect /** * logo详情 */ LogoDetect?: LogoDetail /** * 图片OCR详情 */ OCRDetect?: OCRDetect /** * 手机检测详情 */ PhoneDetect?: PhoneDetect /** * 图片涉政详情 */ PolityDetect?: ImagePolityDetect /** * 图片涉黄详情 */ PornDetect?: ImagePornDetect /** * 图片相似度详情 */ Similar?: Similar /** * 图片暴恐详情 */ TerrorDetect?: ImageTerrorDetect } /** * 图片涉黄详情 */ export interface ImagePornDetect { /** * 恶意类型 100:正常 20002:色情 */ EvilType: number /** * 处置判定 0:正常 1:可疑 */ HitFlag: number /** * 关键词明细 */ Keywords?: Array<string> /** * 色情标签:色情特征中文描述 */ Labels?: Array<string> /** * 色情分:分值范围 0-100,分数越高色情倾向越明显 */ Score?: number } /** * DeleteTextSample返回参数结构体 */ export interface DeleteTextSampleResponse { /** * 任务状态 1:已完成 2:处理中 */ Progress?: number /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 文字样本信息 */ export interface TextSample { /** * 处理错误码 */ Code: number /** * 关键词 */ Content: string /** * 创建时间戳 */ CreatedAt: number /** * 恶意类型 100:正常 20001:政治 20002:色情 20006:涉毒违法 20007:谩骂 20105:广告引流 24001:暴恐 */ EvilType: number /** * 唯一标识 */ Id: string /** * 样本类型 1:黑库 2:白库 */ Label: number /** * 任务状态 1:已完成 2:处理中 */ Status: number } /** * CreateTextSample返回参数结构体 */ export interface CreateTextSampleResponse { /** * 操作样本失败时返回的错误信息示例: "样本1":错误码,"样本2":错误码 */ ErrMsg?: string /** * 任务状态 1:已完成 2:处理中 */ Progress?: number /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 消息类输出ID参数 */ export interface TextOutputID { /** * 接入业务的唯一ID */ MsgID?: string /** * 用户账号uin,对应请求协议里的Content.User.Uin。旁路结果有回带,串联结果无该字段 */ Uin?: string } /** * ManualReview请求参数结构体 */ export interface ManualReviewRequest { /** * 人工审核信息 */ ReviewContent: ManualReviewContent } /** * 用户相关信息 */ export interface User { /** * 账号类别,"1-微信uin 2-QQ号 3-微信群uin 4-qq群号 5-微信openid 6-QQopenid 7-其它string" */ AccountType?: number /** * 年龄 默认0 未知 */ Age?: number /** * 性别 默认0 未知 1 男性 2 女性 */ Gender?: number /** * 用户等级,默认0 未知 1 低 2 中 3 高 */ Level?: number /** * 用户昵称 */ Nickname?: string /** * 手机号 */ Phone?: string /** * 用户账号ID,如填写,会根据账号历史恶意情况,判定消息有害结果,特别是有利于可疑恶意情况下的辅助判断。账号可以填写微信uin、QQ号、微信openid、QQopenid、字符串等。该字段和账号类别确定唯一账号。 */ UserId?: string } /** * 文件样本返回信息 */ export interface FileSampleInfo { /** * 处理错误码 */ Code: number /** * 创建时间戳 */ CreatedAt: number /** * 恶意类型 100:正常 20001:政治 20002:色情 20006:涉毒违法 20007:谩骂 24001:暴恐 */ EvilType: number /** * 文件的md5 */ FileMd5: string /** * 文件名称 */ FileName: string /** * 文件类型 */ FileType: string /** * 唯一标识 */ Id: string /** * 样本类型 1:黑库 2:白库 */ Label: number /** * 任务状态 1:添加完成 2:添加处理中 3:下载中 4:下载完成 5:上传完成 6:步骤完成 */ Status: number /** * 文件压缩后云url */ CompressFileUrl?: string /** * 文件的url */ FileUrl?: string } /** * DescribeFileSample请求参数结构体 */ export interface DescribeFileSampleRequest { /** * 支持通过标签值进行筛选 */ Filters?: Array<Filter> /** * 数量限制,默认为20,最大值为100 */ Limit?: number /** * 偏移量,默认为0 */ Offset?: number /** * 升序(asc)还是降序(desc),默认:desc */ OrderDirection?: string /** * 按某个字段排序,目前仅支持CreatedAt排序 */ OrderField?: string } /** * 设备信息 */ export interface Device { /** * 设备指纹ID */ DeviceId?: string /** * IOS设备,Identifier For Advertising(广告标识符) */ IDFA?: string /** * IOS设备,IDFV - Identifier For Vendor(应用开发商标识符) */ IDFV?: string /** * 设备序列号 */ IMEI?: string /** * 用户IP */ IP?: string /** * Mac地址 */ Mac?: string /** * 设备指纹Token */ TokenId?: string } /** * 图片二维码详情 */ export interface CodeDetect { /** * 从图片中检测到的二维码,可能为多个 */ ModerationDetail?: Array<CodeDetail> /** * 检测是否成功,0:成功,-1:出错 */ ModerationCode?: number } /** * 图片暴恐详情 */ export interface ImageTerrorDetect { /** * 恶意类型 100:正常 24001:暴恐 */ EvilType?: number /** * 处置判定 0:正常 1:可疑 */ HitFlag?: number /** * 关键词明细 */ Keywords?: Array<string> /** * 暴恐标签:返回暴恐特征中文描述 */ Labels?: Array<string> /** * 暴恐分:分值范围0--100,分数越高暴恐倾向越明显 */ Score?: number } /** * DescribeTextSample返回参数结构体 */ export interface DescribeTextSampleResponse { /** * 符合要求的样本的信息 */ TextSampleSet?: Array<TextSample> /** * 符合要求的样本的数量 */ TotalCount?: number /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 二维码在图片中的位置,由边界点的坐标表示 */ export interface CodePosition { /** * 二维码边界点X轴坐标 */ FloatX?: number /** * 二维码边界点Y轴坐标 */ FloatY?: number } /** * DeleteFileSample返回参数结构体 */ export interface DeleteFileSampleResponse { /** * 任务状态 1:已完成 2:处理中 */ Progress?: number /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 文件类型样本 */ export interface FileSample { /** * 文件md5 */ FileMd5: string /** * 文件名称 */ FileName: string /** * 文件url */ FileUrl: string /** * 文件压缩后云url */ CompressFileUrl?: string } /** * DescribeFileSample返回参数结构体 */ export interface DescribeFileSampleResponse { /** * 符合要求的样本的信息 */ FileSampleSet?: Array<FileSampleInfo> /** * 符合要求的样本的数量 */ TotalCount?: number /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * 消息类输出结果参数 */ export interface TextOutputRes { /** * 操作人,信安处理人企业微信ID */ Operator?: string /** * 恶意操作码, 删除(1), 通过(2), 先审后发(100012) */ ResultCode?: number /** * 操作结果备注说明 */ ResultMsg?: string /** * 恶意类型,广告(10001), 政治(20001), 色情(20002), 社会事件(20004), 暴力(20011), 低俗(20012), 违法犯罪(20006), 欺诈(20008), 版权(20013), 谣言(20104), 其他(21000) */ ResultType?: number } /** * 账号风险检测结果 */ export interface RiskDetails { /** * 预留字段,暂时不使用 */ Keywords?: Array<string> /** * 风险类别,RiskAccount,RiskIP, RiskIMEI */ Label?: string /** * 预留字段,暂时不用 */ Lable?: string /** * 风险等级,1:疑似,2:恶意 */ Level?: number } /** * CreateTextSample请求参数结构体 */ export interface CreateTextSampleRequest { /** * 关键词数组 */ Contents: Array<string> /** * 恶意类型 100:正常 20001:政治 20002:色情 20006:涉毒违法 20007:谩骂 24001:暴恐 20105:广告引流 */ EvilType: number /** * 样本类型 1:黑库 2:白库 */ Label: number /** * 测试修改参数 */ Test?: string } /** * DeleteFileSample请求参数结构体 */ export interface DeleteFileSampleRequest { /** * 唯一标识数组 */ Ids: Array<string> } /** * 筛选数据结构 */ export interface Filter { /** * 需要过滤的字段 */ Name: string /** * 需要过滤字段的值 */ Value: string } /** * 人工审核接口返回结果,由ContentId和BatchId组成 */ export interface ManualReviewData { /** * 人审内容批次号 */ BatchId: string /** * 人审内容ID */ ContentId: string } /** * OCR识别结果详情 */ export interface OCRDetect { /** * 识别到的详细信息 */ Item?: Array<OCRItem> /** * 识别到的文本信息 */ TextInfo?: string } /** * 人审审核数据相关信息 */ export interface ManualReviewContent { /** * 审核批次号 */ BatchId: string /** * 审核内容 */ Content: string /** * 消息Id */ ContentId: string /** * 审核内容类型 1 图片 2 视频 3 文本 4 音频 */ ContentType: number /** * 用户信息 */ UserInfo?: User /** * 机器审核类型,与腾讯机器审核定义一致 100 正常 20001 政治 20002 色情 20006 违法 20007 谩骂 24001 暴恐 20105 广告 20103 性感 */ AutoDetailCode?: number /** * 机器审核结果 0 放过 1 拦截 */ AutoResult?: number /** * 回调信息标识,回传数据时原样返回 */ CallBackInfo?: string /** * 创建时间 格式“2020-01-01 00:00:12” */ CreateTime?: string /** * 审核优先级,可选值 [1,2,3,4],其中 1 最高,4 最低 */ Priority?: number /** * 标题 */ Title?: string } /** * 坐标 */ export interface Coordinate { /** * 左上角横坐标 */ Cx?: number /** * 左上角纵坐标 */ Cy?: number /** * 高度 */ Height?: number /** * 宽度 */ Width?: number } /** * 相似度详情 */ export interface Similar { /** * 恶意类型 100:正常 20001:政治 20002:色情 20006:涉毒违法 20007:谩骂 24001:暴恐 */ EvilType: number /** * 处置判定 0:未匹配到 1:恶意 2:白样本 */ HitFlag: number /** * 返回的种子url */ SeedUrl: string } /** * 图片性感详情 */ export interface ImageHotDetect { /** * 恶意类型 100:正常 20103:性感 */ EvilType: number /** * 处置判定 0:正常 1:可疑 */ HitFlag: number /** * 关键词明细 */ Keywords?: Array<string> /** * 性感标签:性感特征中文描述 */ Labels?: Array<string> /** * 性感分:分值范围 0-100,分数越高性感倾向越明显 */ Score?: number } /** * 消息类输出公共参数 */ export interface TextOutputComm { /** * 接入业务的唯一ID */ AppID?: number /** * 接口唯一ID,旁路调用接口返回有该字段,标识唯一接口 */ BUCtrlID?: number /** * 消息发送时间 */ SendTime?: number /** * 请求字段里的Common.Uin */ Uin?: number } /** * DescribeTextSample请求参数结构体 */ export interface DescribeTextSampleRequest { /** * 支持通过标签值进行筛选 */ Filters?: Array<Filter> /** * 数量限制,默认为20,最大值为100 */ Limit?: number /** * 偏移量,默认为0 */ Offset?: number /** * 升序(asc)还是降序(desc),默认:desc */ OrderDirection?: string /** * 按某个字段排序,目前仅支持CreatedAt排序 */ OrderField?: string } /** * 从图片中检测到的二维码,可能为多个 */ export interface CodeDetail { /** * 二维码在图片中的位置,由边界点的坐标表示 */ CodePosition?: Array<CodePosition> /** * 二维码文本的编码格式 */ CodeCharset?: string /** * 二维码的文本内容 */ CodeText?: string /** * 二维码的类型:1:ONED_BARCODE,2:QRCOD,3:WXCODE,4:PDF417,5:DATAMATRIX */ CodeType?: number } /** * 图片涉政详情 */ export interface ImagePolityDetect { /** * 恶意类型 100:正常 20001:政治 */ EvilType: number /** * 处置判定 0:正常 1:可疑 */ HitFlag: number /** * 命中的logo标签信息 */ PolityLogoDetail?: Array<Logo> /** * 命中的人脸名称 */ FaceNames?: Array<string> /** * 关键词明细 */ Keywords?: Array<string> /** * 命中的政治物品名称 */ PolityItems?: Array<string> /** * 政治(人脸)分:分值范围 0-100,分数越高可疑程度越高 */ Score?: number } /** * OCR详情 */ export interface OCRItem { /** * 检测到的文本坐标信息 */ TextPosition?: Coordinate /** * 文本命中具体标签 */ EvilLabel?: string /** * 文本命中恶意违规类型 */ EvilType?: number /** * 文本命中违规的关键词 */ Keywords?: Array<string> /** * 文本涉嫌违规分值 */ Rate?: number /** * 检测到的文本信息 */ TextContent?: string } /** * 图片违法详情 */ export interface ImageIllegalDetect { /** * 恶意类型 100:正常 20006:涉毒违法 */ EvilType: number /** * 处置判定 0:正常 1:可疑 */ HitFlag: number /** * 关键词明细 */ Keywords?: Array<string> /** * 违法标签:返回违法特征中文描述,如赌桌,枪支 */ Labels?: Array<string> /** * 违法分:分值范围 0-100,分数越高违法倾向越明显 */ Score?: number } /** * logo位置信息 */ export interface RrectF { /** * logo横坐标 */ Cx?: number /** * logo纵坐标 */ Cy?: number /** * logo图标高度 */ Height?: number /** * logo图标中心旋转度 */ Rotate?: number /** * logo图标宽度 */ Width?: number } /** * CreateFileSample返回参数结构体 */ export interface CreateFileSampleResponse { /** * 任务状态 1:已完成 2:处理中 */ Progress?: number /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * ManualReview返回参数结构体 */ export interface ManualReviewResponse { /** * 人审接口同步响应结果 */ Data?: ManualReviewData /** * 唯一请求 ID,每次请求都会返回。定位问题时需要提供该次请求的 RequestId。 */ RequestId?: string } /** * LogoDetail */ export interface LogoDetail { /** * 命中的Applogo详情 */ AppLogoDetail?: Array<Logo> } /** * Logo */ export interface Logo { /** * logo图标坐标信息 */ RrectF?: RrectF /** * logo图标置信度 */ Confidence?: number /** * logo图标名称 */ Name?: string } /** * 手机模型识别检测 */ export interface PhoneDetect { /** * 恶意类型 100:正常 21000:综合 */ EvilType?: number /** * 处置判定 0:正常 1:可疑 */ HitFlag?: number /** * 特征中文描述 */ Labels?: Array<string> /** * 分值范围 0-100,分数越高倾向越明显 */ Score?: number } /** * DeleteTextSample请求参数结构体 */ export interface DeleteTextSampleRequest { /** * 唯一标识数组,目前暂时只支持单个删除 */ Ids: Array<string> }
the_stack
import { assert } from 'chai'; import configApp from '../helpers/config-app'; import getInitDb from '../helpers/get-init-db'; import { populate } from '../../src'; ['array', 'obj'].forEach(type => { describe(`services populate - 1:1 & 1:m & m:1 - ${type}`, () => { let hookAfter: any; let hookAfterArray: any; let schema: any; let app: any; let recommendation; beforeEach(() => { app = configApp(['recommendation', 'posts', 'users', 'comments']); recommendation = clone(getInitDb('recommendation').store); hookAfter = { type: 'after', method: 'create', params: { provider: 'rest' }, path: 'recommendations', result: recommendation['1'] }; hookAfterArray = { type: 'after', method: 'create', params: { provider: 'rest' }, path: 'recommendations', result: [recommendation['1'], recommendation['2'], recommendation['3']] }; schema = { permissions: '', include: makeInclude(type, { service: 'posts', nameAs: 'post', parentField: 'postId', childField: 'id', include: [ { // 1:1 service: 'users', permissions: '', nameAs: 'authorInfo', parentField: 'author', childField: 'id' }, { // 1:m service: 'comments', permissions: '', nameAs: 'commentsInfo', parentField: 'id', childField: 'postId', select: (_hook: any, _parent: any) => ({ $limit: 6 }), asArray: true, query: { $limit: 5, $select: ['title', 'content', 'postId'], $sort: { createdAt: -1 } } }, { // m:1 service: 'users', permissions: '', nameAs: 'readersInfo', parentField: 'readers', childField: 'id' } ] }) }; }); it('for one item', () => { const hook = clone(hookAfter); hook.app = app; // app is a func and wouldn't be cloned // @ts-ignore return populate({ schema, checkPermissions: () => true, profile: 'test' })(hook) // @ts-ignore .then((hook1: any) => { assert.deepEqual(hook1.result, { userId: 'as61389dadhga62343hads6712', postId: 1, updatedAt: 1480793101475, _include: ['post'], _elapsed: { post: 1, total: 1 }, post: { id: 1, title: 'Post 1', content: 'Lorem ipsum dolor sit amet 4', author: 'as61389dadhga62343hads6712', readers: ['as61389dadhga62343hads6712', '167asdf3689348sdad7312131s'], createdAt: 1480793101559, _include: ['authorInfo', 'commentsInfo', 'readersInfo'], _elapsed: { authorInfo: 2, commentsInfo: 2, readersInfo: 2, total: 2 }, authorInfo: { id: 'as61389dadhga62343hads6712', name: 'Author 1', email: 'author1@posties.com', password: '2347wjkadhad8y7t2eeiudhd98eu2rygr', age: 55 }, commentsInfo: [{ title: 'Comment 1', content: 'Lorem ipsum dolor sit amet 1', postId: 1 }, { title: 'Comment 3', content: 'Lorem ipsum dolor sit amet 3', postId: 1 }], readersInfo: [{ id: 'as61389dadhga62343hads6712', name: 'Author 1', email: 'author1@posties.com', password: '2347wjkadhad8y7t2eeiudhd98eu2rygr', age: 55 }, { id: '167asdf3689348sdad7312131s', name: 'Author 2', email: 'author2@posties.com', password: '2347wjkadhad8y7t2eeiudhd98eu2rygr', age: 16 }] } } ); }); }); it('for an item array', () => { const hook = clone(hookAfterArray); hook.app = app; // app is a func and wouldn't be cloned // @ts-ignore return populate({ schema, checkPermissions: () => true, profile: 'test' })(hook) // @ts-ignore .then((hook1: any) => { assert.deepEqual(hook1.result, [{ userId: 'as61389dadhga62343hads6712', postId: 1, updatedAt: 1480793101475, _include: ['post'], _elapsed: { post: 1, total: 1 }, post: { id: 1, title: 'Post 1', content: 'Lorem ipsum dolor sit amet 4', author: 'as61389dadhga62343hads6712', readers: ['as61389dadhga62343hads6712', '167asdf3689348sdad7312131s'], createdAt: 1480793101559, _include: ['authorInfo', 'commentsInfo', 'readersInfo'], _elapsed: { authorInfo: 2, commentsInfo: 2, readersInfo: 2, total: 2 }, authorInfo: { id: 'as61389dadhga62343hads6712', name: 'Author 1', email: 'author1@posties.com', password: '2347wjkadhad8y7t2eeiudhd98eu2rygr', age: 55 }, commentsInfo: [{ title: 'Comment 1', content: 'Lorem ipsum dolor sit amet 1', postId: 1 }, { title: 'Comment 3', content: 'Lorem ipsum dolor sit amet 3', postId: 1 }], readersInfo: [{ id: 'as61389dadhga62343hads6712', name: 'Author 1', email: 'author1@posties.com', password: '2347wjkadhad8y7t2eeiudhd98eu2rygr', age: 55 }, { id: '167asdf3689348sdad7312131s', name: 'Author 2', email: 'author2@posties.com', password: '2347wjkadhad8y7t2eeiudhd98eu2rygr', age: 16 }] } }, { userId: 'as61389dadhga62343hads6712', postId: 2, updatedAt: 1480793101475, _include: ['post'], _elapsed: { post: 1, total: 1 }, post: { id: 2, title: 'Post 2', content: 'Lorem ipsum dolor sit amet 5', author: '167asdf3689348sdad7312131s', readers: ['as61389dadhga62343hads6712', '167asdf3689348sdad7312131s'], createdAt: 1480793101559, _include: ['authorInfo', 'commentsInfo', 'readersInfo'], _elapsed: { authorInfo: 2, commentsInfo: 2, readersInfo: 2, total: 2 }, authorInfo: { id: '167asdf3689348sdad7312131s', name: 'Author 2', email: 'author2@posties.com', password: '2347wjkadhad8y7t2eeiudhd98eu2rygr', age: 16 }, commentsInfo: [{ title: 'Comment 2', content: 'Lorem ipsum dolor sit amet 2', postId: 2 }], readersInfo: [{ id: 'as61389dadhga62343hads6712', name: 'Author 1', email: 'author1@posties.com', password: '2347wjkadhad8y7t2eeiudhd98eu2rygr', age: 55 }, { id: '167asdf3689348sdad7312131s', name: 'Author 2', email: 'author2@posties.com', password: '2347wjkadhad8y7t2eeiudhd98eu2rygr', age: 16 }] } }, { userId: '167asdf3689348sdad7312131s', postId: 1, updatedAt: 1480793101475, _include: ['post'], _elapsed: { post: 1, total: 1 }, post: { id: 1, title: 'Post 1', content: 'Lorem ipsum dolor sit amet 4', author: 'as61389dadhga62343hads6712', readers: ['as61389dadhga62343hads6712', '167asdf3689348sdad7312131s'], createdAt: 1480793101559, _include: ['authorInfo', 'commentsInfo', 'readersInfo'], _elapsed: { authorInfo: 2, commentsInfo: 2, readersInfo: 2, total: 2 }, authorInfo: { id: 'as61389dadhga62343hads6712', name: 'Author 1', email: 'author1@posties.com', password: '2347wjkadhad8y7t2eeiudhd98eu2rygr', age: 55 }, commentsInfo: [{ title: 'Comment 1', content: 'Lorem ipsum dolor sit amet 1', postId: 1 }, { title: 'Comment 3', content: 'Lorem ipsum dolor sit amet 3', postId: 1 }], readersInfo: [{ id: 'as61389dadhga62343hads6712', name: 'Author 1', email: 'author1@posties.com', password: '2347wjkadhad8y7t2eeiudhd98eu2rygr', age: 55 }, { id: '167asdf3689348sdad7312131s', name: 'Author 2', email: 'author2@posties.com', password: '2347wjkadhad8y7t2eeiudhd98eu2rygr', age: 16 }] } }] ); }); }); }); }); // Helpers function makeInclude (type: any, obj: any) { return type === 'obj' ? obj : [obj]; } function clone (obj: any) { return JSON.parse(JSON.stringify(obj)); }
the_stack
import { closestCenter, CollisionDetection, KeyboardSensor, DndContextProps, MouseSensor, rectIntersection, TouchSensor, UniqueIdentifier, useSensor, useSensors, Active, Over, MeasuringStrategy, pointerWithin, } from '@dnd-kit/core' import { sortableKeyboardCoordinates } from '@dnd-kit/sortable' import { useCallback, useEffect, useMemo, useRef, useState } from 'react' export interface Identifyable { id: UniqueIdentifier } export interface KanbanContainer<T extends Identifyable> extends Identifyable { items: T[] } type Helpers< T extends Identifyable, U extends KanbanContainer<T> > = Partial<DndContextProps> & { containers: U[] active: { type: 'item'; item: T } | { type: 'container'; item: U } | null } export type Move<T extends Identifyable, U extends KanbanContainer<T>> = | { type: 'in-container'; container: U; item: T; after?: T } | { type: 'cross-container' item: T after?: T previous: U new: U } | { type: 'container'; container: U; after: U } function useMultiContainerDragDrop< T extends Identifyable, U extends KanbanContainer<T> >(containers: U[], onMove: (move: Move<T, U>) => void): Helpers<T, U> { const [active, setActive] = useState<Helpers<T, U>['active']>(null) const lastOverId = useRef<string | null>(null) const recentlyMovedToNewContainer = useRef(false) const [cloned, setCloned] = useState<U[] | null>(null) const workingData = useMemo(() => { return cloned || containers }, [containers, cloned]) const collisionDetection: CollisionDetection = useCallback( (args) => { if (active != null && active.type === 'container') { return closestCenter({ ...args, droppableContainers: args.droppableContainers.filter((container) => containers.some((cnt) => cnt.id === container.id) ), }) } const pointerIntersections = pointerWithin(args) const intersections = pointerIntersections.length > 0 ? pointerIntersections : rectIntersection(args) let overId: string | null = null intersections.forEach((intersection) => (overId = intersection.id)) if (overId != null) { const overContainer = containers.find( (container) => container.id === overId ) if (overContainer != null) { const containerItems = overContainer.items if (containerItems.length > 0) { overId = closestCenter({ ...args, droppableContainers: args.droppableContainers.filter( (container) => container.id !== overId && containerItems.some(({ id }) => id === container.id) ), })[0]?.id } } lastOverId.current = overId return [{ id: overId }] } // When a draggable item moves to a new container, the layout may shift // and the `overId` may become `null`. We manually set the cached `lastOverId` // to the id of the draggable item that was moved to the new container, otherwise // the previous `overId` will be returned which can cause items to incorrectly shift positions if (recentlyMovedToNewContainer.current) { lastOverId.current = active?.item.id || null } return lastOverId.current != null ? [{ id: lastOverId.current }] : [] }, [active, containers] ) useEffect(() => { requestAnimationFrame(() => { recentlyMovedToNewContainer.current = false }) }, [workingData]) const sensors = useSensors( useSensor(MouseSensor, { activationConstraint: { distance: 10 } }), useSensor(TouchSensor, { activationConstraint: { distance: 5 } }), useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates, }) ) const findContainer = useCallback( (id: string) => { const list = workingData.find((list) => list.id === id) if (list != null) { return list } const containerList = workingData.find((list) => list.items.some((item) => item.id === id) ) return containerList != null ? containerList : null }, [workingData] ) const onDragCancel = useCallback(() => { setActive(null) setCloned(null) }, []) const onDragStart: DndContextProps['onDragStart'] = useCallback( ({ active }) => { const container = findContainer(active.id) if (container == null) { setActive(null) } else if (container.id === active.id) { setActive({ type: 'container', item: container }) } else { const item = container.items.find((item) => item.id === active.id) setActive(item != null ? { type: 'item', item } : null) } setCloned(containers) }, [findContainer, containers] ) const onDragEnd: DndContextProps['onDragEnd'] = useCallback( ({ active, over }) => { const overId = over?.id if (overId == null) { setActive(null) setCloned(null) return } const containerIndex = workingData.findIndex( (list) => list.id === active.id ) if (containerIndex !== -1) { const overContainerIndex = workingData.findIndex( (list) => list.id === overId ) if ( overContainerIndex !== -1 && overContainerIndex !== containerIndex ) { onMove({ type: 'container', container: workingData[containerIndex], after: workingData[ containerIndex > overContainerIndex ? overContainerIndex - 1 : overContainerIndex ], }) } setActive(null) setCloned(null) return } const activeContainer = findContainer(active.id) const overContainer = findContainer(overId) if (activeContainer == null || overContainer == null) { setActive(null) setCloned(null) return } const activeItemIndex = activeContainer.items.findIndex( (item) => item.id === active.id ) const overItemIndex = overContainer.items.findIndex( (item) => item.id === overId ) if (activeItemIndex === -1) { setActive(null) setCloned(null) return } const realContainer = containers.find((container) => container.items.some((item) => item.id === active.id) ) if (realContainer == null) { setActive(null) setCloned(null) return } if (realContainer.id === overContainer.id) { if (overItemIndex !== -1 && overItemIndex !== activeItemIndex) { onMove({ type: 'in-container', container: activeContainer, item: activeContainer.items[activeItemIndex], after: overContainer.items[ activeItemIndex > overItemIndex ? overItemIndex - 1 : overItemIndex ], }) } } else { const afterIndex = overItemIndex === -1 ? overContainer.items.length - 1 : activeItemIndex > overItemIndex ? overItemIndex - 1 : overItemIndex onMove({ type: 'cross-container', previous: realContainer, new: overContainer, item: activeContainer.items[activeItemIndex], after: overContainer.items[afterIndex] == null || overContainer.items[afterIndex].id === activeContainer.items[activeItemIndex].id ? undefined : overContainer.items[afterIndex], }) } setActive(null) setCloned(null) }, [workingData, onMove, findContainer, containers] ) const onDragOver: DndContextProps['onDragOver'] = useCallback( ({ active, over }) => { const overId = over?.id if (!overId) { return } const overContainer = findContainer(overId) const activeContainer = findContainer(active.id) if (!overContainer || !activeContainer) { return } if (activeContainer.id !== overContainer.id) { setCloned((containers) => { if (containers == null) { return containers } const overIndex = overContainer.items.findIndex( (item) => item.id === overId ) const activeItem = activeContainer.items.find( (item) => item.id === active.id ) if (activeItem == null) { return containers } let newIndex: number if (containers.some((list) => list.id == overId)) { newIndex = overContainer.items.length + 1 } else { const isBelowOverItem = over && isBelow(active, over) const modifier = isBelowOverItem ? 1 : 0 newIndex = overIndex >= 0 ? overIndex + modifier : overContainer.items.length + 1 } recentlyMovedToNewContainer.current = true return containers.map((list) => { if (list.id === activeContainer.id) { return { ...list, items: list.items.filter((item) => item.id !== active.id), } } if (list.id === overContainer.id) { return { ...list, items: [ ...list.items.slice(0, newIndex), activeItem, ...list.items.slice(newIndex, list.items.length), ], } } return list }) }) } }, [findContainer] ) return { containers: workingData, measuring: { droppable: { strategy: MeasuringStrategy.Always } }, sensors, collisionDetection, onDragStart, onDragOver, onDragCancel, onDragEnd, active, } } export default useMultiContainerDragDrop function isBelow(active: Active, over: Over): boolean { if (active.rect.current.translated == null) { return false } return active.rect.current.translated.top > over.rect.top + over.rect.height }
the_stack
'use strict'; import fs = require('fs'); import path = require('path'); import util = require('util'); import globMod = require('glob'); import VError = require('verror'); import Promise = require('bluebird'); import mkdirp = require('mkdirp'); import rimrafMod = require('rimraf'); import assertVar = require('./assertVar'); var mkdirpP = Promise.promisify(mkdirp); // make nested tree from filename for high-volume folders: abcdefg.txt -> a/b/c/abcdefg.txt export function distributeDir(base: string, name: string, levels: number, chunk: number = 1): string { name = name.replace(/(^[\\\/]+)|([\\\/]+$)/g, ''); if (levels === 0) { return base; } if (chunk === 0) { return base; } var arr = [base]; var steps = Math.max(0, Math.min(name.length - 2, levels * chunk)); for (var i = 0; i < steps; i += chunk) { arr.push(name.substr(i, chunk)); } return path.join.apply(path, arr); } export function parseJson(text: string): any { var json: any; try { json = JSON.parse(text); } catch (err) { if (err.name === 'SyntaxError') { // TODO find/write module to pretty print parse errors /*console.error(err); console.log('---'); console.log(text.substr(0, 1024)); console.log('---');*/ } // rethrow throw (err); } return json; } export function readJSONSync(src: string): any { return parseJson(String(fs.readFileSync(src, {encoding: 'utf8'}))); } export function readJSONCB(src: string, callback: (err: Error, res: any) => void): void { fs.readFile(path.resolve(src), {encoding: 'utf8'}, (err: Error, text: string) => { if (err || typeof text !== 'string') { return callback(err, null); } var json: any = null; try { json = parseJson(text); } catch (err) { return callback(err, null); } return callback(null, json); }); } export function readJSON(src: string): Promise<any> { return read(src, {encoding: 'utf8'}).then((text: string) => { return parseJson(text); }); } export function writeJSONSync(dest: string, data: any) { dest = path.resolve(dest); mkdirCheckSync(path.dirname(dest)); fs.writeFileSync(dest, JSON.stringify(data, null, 2), {encoding: 'utf8'}); } export function writeJSON(filename: string, data: any): Promise<void> { return write(filename, JSON.stringify(data, null, 2), {encoding: 'utf8'}); } // lazy wrapper as alternative to readJSONSync export function readFileSync(dest: string, encoding: string = 'utf8') { return fs.readFileSync(dest, {encoding: encoding}); } // lazy wrapper as alternative to writeJSONSync export function writeFileSync(dest: string, data: any, encoding: string = 'utf8') { dest = path.resolve(dest); mkdirCheckSync(path.dirname(dest), true); fs.writeFileSync(dest, data, {encoding: encoding}); } /* mkdirCheck: like mkdirp but with writable rights and verification, synchronous */ // TODO unit test this export function mkdirCheckSync(dir: string, writable: boolean = false): string { dir = path.resolve(dir); if (fs.existsSync(dir)) { if (!fs.statSync(dir).isDirectory()) { throw new Error('path exists but is not a directory ' + dir); } if (writable) { fs.chmodSync(dir, '744'); } } else { if (writable) { mkdirp.sync(dir, '744'); } else { mkdirp.sync(dir); } } return dir; } /* mkdirCheckQ: like mkdirp but with writable rights and verification, returns a promise */ // TODO unit test this // TODO why not by default make writable? why ever use this without writable? export function mkdirCheck(dir: string, writable: boolean = false): Promise<string> { dir = path.resolve(dir); return exists(dir).then((exists: boolean) => { if (exists) { return isDirectory(dir).then((isDir: boolean) => { if (!isDir) { throw (new Error('path exists but is not a directory ' + dir)); } if (writable) { return chmod(dir, '744'); } }); } else if (writable) { return mkdirpP(dir, '744'); } else { return mkdirpP(dir); } }).return(dir); } export function canWriteFile(targetPath: string, overwrite: boolean) { return exists(targetPath).then((exists: boolean) => { if (!exists) { return Promise.resolve(true); } return isFile(targetPath).then((isFile: boolean) => { if (isFile) { return overwrite; } // TODO add folder write test? return false; }); }); } export function removeFile(target: string): Promise<void> { return exists(target).then((exists: boolean) => { if (!exists) { return; } return isFile(target).then((isFile: boolean) => { if (!isFile) { throw new Error('not a file ' + target); } return remove(target); }); }); } export function removeAllFilesFromDir(target: string) { if (!fs.existsSync(target)) { return; } var files = fs.readdirSync(target); files.forEach(function(file) { if (fs.statSync(path.join(target, file)).isFile()) { fs.unlinkSync(path.join(target, file)); } }); } export function getDirNameList(target: string): string[] { var list = []; if ( fs.existsSync(target) ) { fs.readdirSync(target).forEach(function(file, index) { if (fs.statSync(path.join(target, file)).isDirectory()) { list.push(file); } }); } return list; } export function removeDirSync(target: string) { syncDeleteFolderRecursive(target); } export function rimraf(target: string): Promise<void> { return new Promise<void>((resolve, reject) => { rimrafMod(target, (err) => { if (err) { reject(err); } else { resolve(undefined); } }); }); } var utimes = Promise.promisify(fs.utimes); // TODO what about directories? export function touchFile(src: string, atime?: Date, mtime?: Date): Promise<void> { return stat(src).then((stat: fs.Stats) => { atime = (atime || new Date()); mtime = (mtime || stat.mtime); return utimes(src, atime, mtime); }).return(); } export function findup(dir: string, name: string): Promise<string> { return Promise.attempt<string>(() => { if (dir === '/') { throw new Error('could not find package.json up from ' + dir); } else if (!dir || dir === '.') { throw new Error('cannot find package.json from unspecified directory'); } var file = path.join(dir, name); return exists(file).then((exists: boolean) => { if (exists) { return Promise.resolve(file); } // one-up var dirName = path.dirname(dir); if (dirName === dir) { throw new Error('cannot find file ' + name); } return findup(path.dirname(dir), name).then((file: string) => { return file; }); }); }); } export function exists(filename: string): any { return new Promise<boolean>((resolve) => { fs.exists(filename, resolve); }).catch(() => { return false; }); } export function stat(filename: string): Promise<fs.Stats> { return new Promise<fs.Stats>((resolve, reject) => { fs.stat(filename, (err, stat: fs.Stats) => { if (err) { reject(err); } else { resolve(stat); } }); }); } export function isFile(filename: string): Promise<boolean> { return stat(filename).then((stat) => { return stat.isFile(); }).catch((e) => { return false; }); } export function isDirectory(filename: string): Promise<boolean> { return stat(filename).then((stat) => { return stat.isDirectory(); }).catch((e) => { return false; }); } export function read(filename: string, opts?: Object): Promise<any> { return new Promise<any>((resolve, reject) => { fs.readFile(filename, opts, (err, content) => { if (err) { reject(err); } else { resolve(content); } }); }); } export function write(filename: string, content: any, opts?: Object): Promise<void> { filename = path.resolve(filename); return mkdirCheck(path.dirname(filename), true).then(() => { return new Promise<void>((resolve, reject) => { fs.writeFile(filename, content, opts, (err) => { if (err) { reject(err); } else { resolve(undefined); } }); }); }); } export function remove(filename: string): Promise<void> { return new Promise<void>((resolve, reject) => { fs.unlink(filename, (err) => { if (err) { reject(err); } else { resolve(undefined); } }); }); } export function syncDeleteFolderRecursive(path: string) { if (fs.existsSync(path)) { fs.readdirSync(path).forEach(function(file, index) { var curPath = path + '/' + file; if (fs.lstatSync(curPath).isDirectory()) { // recurse syncDeleteFolderRecursive(curPath); } else { // delete file fs.unlinkSync(curPath); } }); fs.rmdirSync(path); } } export function chmod(filename: string, mode: string): Promise<void> { return new Promise<void>((resolve, reject) => { fs.chmod(filename, mode, (err) => { if (err) { reject(err); } else { resolve(undefined); } }); }); } export function glob(pattern: string, opts?: globMod.IOptions): Promise<string[]> { return new Promise<string[]>((resolve, reject) => { globMod(pattern, (opts || {}), (err, paths: string[]) => { if (err) { reject(err); } else { resolve(paths); } }); }); } function concat(arrays) { return Array.prototype.concat.apply([], arrays); }; // lifted from Q-io export function readdir(basePath: string): Promise<string[]> { return new Promise<string[]>((resolve, reject) => { fs.readdir(basePath, (error, list) => { if (error) { return reject(new VError(error, 'Can\'t list %s', JSON.stringify(path))); } else { resolve(list); } }); }); } // lifted from Q-io export function listTree(basePath: string, guard?: (basePath: string, stat: fs.Stats) => boolean): Promise<string[]> { basePath = String(basePath || ''); if (!basePath) { basePath = '.'; } guard = guard || function (basePath, stat) { return true; }; return stat(basePath).then((stat) => { var paths = []; // true:include, false:exclude, null:no-recur var include = guard(basePath, stat); if (include) { paths.push([basePath]); } if (include !== null && stat.isDirectory()) { return readdir(basePath).then((children) => { paths.push.apply(paths, children.map((child) => { return listTree(path.join(basePath, child), guard); })); return paths; }); } else { return Promise.resolve(paths); } }).catch((reason) => { return []; }).then(Promise.all).then(concat); } export function copyFileSync( source, target ) { var targetFile = target; if ( fs.existsSync( target ) ) { if ( fs.lstatSync( target ).isDirectory() ) { targetFile = path.join( target, path.basename( source ) ); } } fs.createReadStream( source ).pipe( fs.createWriteStream( targetFile ) ); } export function copyFolderRecursiveSync( source, target, inscludeSource? ) { var files = []; var targetFolder = ''; if (inscludeSource) { targetFolder = path.resolve('..', target); } else { targetFolder = path.join( target, path.basename( source ) ); } if ( !fs.existsSync( targetFolder ) ) { fs.mkdirSync( targetFolder ); } if ( fs.lstatSync( source ).isDirectory() ) { files = fs.readdirSync( source ); files.forEach( function ( file ) { var curSource = path.join( source, file ); if ( fs.lstatSync( curSource ).isDirectory() ) { copyFolderRecursiveSync( curSource, targetFolder ); } else { copyFileSync( curSource, targetFolder ); } } ); } }
the_stack
declare module dtos { interface IReturn<T> { } interface IReturnVoid { } interface IMeta { meta?: { [index:string]: string; }; } interface IGet { } interface IPost { } interface IPut { } interface IDelete { } interface IPatch { } interface IHasSessionId { sessionId?: string; } interface IHasVersion { version?: number; } interface QueryBase { // @DataMember(Order=1) skip?: number; // @DataMember(Order=2) take?: number; // @DataMember(Order=3) orderBy?: string; // @DataMember(Order=4) orderByDesc?: string; // @DataMember(Order=5) include?: string; // @DataMember(Order=6) fields?: string; // @DataMember(Order=7) meta?: { [index:string]: string; }; } interface QueryData<T> extends QueryBase { } interface RequestLogEntry { id?: number; dateTime?: string; statusCode?: number; statusDescription?: string; httpMethod?: string; absoluteUri?: string; pathInfo?: string; requestBody?: string; requestDto?: Object; userAuthId?: string; sessionId?: string; ipAddress?: string; forwardedFor?: string; referer?: string; headers?: { [index:string]: string; }; formData?: { [index:string]: string; }; items?: { [index:string]: string; }; session?: Object; responseDto?: Object; errorResponse?: Object; exceptionSource?: string; exceptionData?: any; requestDuration?: string; } // @DataContract interface ResponseError { // @DataMember(Order=1, EmitDefaultValue=false) errorCode?: string; // @DataMember(Order=2, EmitDefaultValue=false) fieldName?: string; // @DataMember(Order=3, EmitDefaultValue=false) message?: string; // @DataMember(Order=4, EmitDefaultValue=false) meta?: { [index:string]: string; }; } // @DataContract interface ResponseStatus { // @DataMember(Order=1) errorCode?: string; // @DataMember(Order=2) message?: string; // @DataMember(Order=3) stackTrace?: string; // @DataMember(Order=4) errors?: ResponseError[]; // @DataMember(Order=5) meta?: { [index:string]: string; }; } interface QueryDb_1<T> extends QueryBase { } interface Rockstar { /** * Идентификатор */ id?: number; /** * Фамилия */ firstName?: string; /** * Имя */ lastName?: string; /** * Возраст */ age?: number; } interface ObjectDesign { id?: number; } interface MetadataTestNestedChild { name?: string; } interface MetadataTestChild { name?: string; results?: MetadataTestNestedChild[]; } interface MenuItemExampleItem { // @DataMember(Order=1) // @ApiMember() name1?: string; } interface MenuItemExample { // @DataMember(Order=1) // @ApiMember() name1?: string; menuItemExampleItem?: MenuItemExampleItem; } // @DataContract interface MenuExample { // @DataMember(Order=1) // @ApiMember() menuItemExample1?: MenuItemExample; } interface MetadataTypeName { name?: string; namespace?: string; genericArgs?: string[]; } interface MetadataRoute { path?: string; verbs?: string; notes?: string; summary?: string; } interface MetadataDataContract { name?: string; namespace?: string; } interface MetadataDataMember { name?: string; order?: number; isRequired?: boolean; emitDefaultValue?: boolean; } interface MetadataAttribute { name?: string; constructorArgs?: MetadataPropertyType[]; args?: MetadataPropertyType[]; } interface MetadataPropertyType { name?: string; type?: string; isValueType?: boolean; isSystemType?: boolean; isEnum?: boolean; typeNamespace?: string; genericArgs?: string[]; value?: string; description?: string; dataMember?: MetadataDataMember; readOnly?: boolean; paramType?: string; displayType?: string; isRequired?: boolean; allowableValues?: string[]; allowableMin?: number; allowableMax?: number; attributes?: MetadataAttribute[]; } interface MetadataType { name?: string; namespace?: string; genericArgs?: string[]; inherits?: MetadataTypeName; implements?: MetadataTypeName[]; displayType?: string; description?: string; returnVoidMarker?: boolean; isNested?: boolean; isEnum?: boolean; isEnumInt?: boolean; isInterface?: boolean; isAbstract?: boolean; returnMarkerTypeName?: MetadataTypeName; routes?: MetadataRoute[]; dataContract?: MetadataDataContract; properties?: MetadataPropertyType[]; attributes?: MetadataAttribute[]; innerTypes?: MetadataTypeName[]; enumNames?: string[]; enumValues?: string[]; meta?: { [index:string]: string; }; } interface AutoQueryConvention { name?: string; value?: string; types?: string; } interface AutoQueryViewerConfig { serviceBaseUrl?: string; serviceName?: string; serviceDescription?: string; serviceIconUrl?: string; formats?: string[]; maxLimit?: number; isPublic?: boolean; onlyShowAnnotatedServices?: boolean; implicitConventions?: AutoQueryConvention[]; defaultSearchField?: string; defaultSearchType?: string; defaultSearchText?: string; brandUrl?: string; brandImageUrl?: string; textColor?: string; linkColor?: string; backgroundColor?: string; backgroundImageUrl?: string; iconUrl?: string; meta?: { [index:string]: string; }; } interface AutoQueryViewerUserInfo { isAuthenticated?: boolean; queryCount?: number; meta?: { [index:string]: string; }; } interface AutoQueryOperation { request?: string; from?: string; to?: string; meta?: { [index:string]: string; }; } interface NativeTypesTestService { } interface NestedClass { value?: string; } interface ListResult { result?: string; } interface OnlyInReturnListArg { result?: string; } interface ArrayResult { result?: string; } type EnumType = "Value1" | "Value2"; type EnumWithValues = "Value1" | "Value2"; // @Flags() enum EnumFlags { Value1 = 1, Value2 = 2, Value3 = 4, } interface Poco { name?: string; } interface AllCollectionTypes { intArray?: number[]; intList?: number[]; stringArray?: string[]; stringList?: string[]; pocoArray?: Poco[]; pocoList?: Poco[]; nullableByteArray?: Uint8Array; nullableByteList?: number[]; nullableDateTimeArray?: string[]; nullableDateTimeList?: string[]; pocoLookup?: { [index:string]: Poco[]; }; pocoLookupMap?: { [index:string]: { [index:string]: Poco; }[]; }; } interface KeyValuePair<TKey, TValue> { key?: TKey; value?: TValue; } interface SubType { id?: number; name?: string; } interface HelloBase { id?: number; } interface HelloResponseBase { refId?: number; } interface HelloBase_1<T> { items?: T[]; counts?: number[]; } interface Item { value?: string; } interface InheritedItem { name?: string; } interface HelloWithReturnResponse { result?: string; } interface HelloType { result?: string; } interface IAuthTokens { provider?: string; userId?: string; accessToken?: string; accessTokenSecret?: string; refreshToken?: string; refreshTokenExpiry?: string; requestToken?: string; requestTokenSecret?: string; items?: { [index:string]: string; }; } // @DataContract interface AuthUserSession { // @DataMember(Order=1) referrerUrl?: string; // @DataMember(Order=2) id?: string; // @DataMember(Order=3) userAuthId?: string; // @DataMember(Order=4) userAuthName?: string; // @DataMember(Order=5) userName?: string; // @DataMember(Order=6) twitterUserId?: string; // @DataMember(Order=7) twitterScreenName?: string; // @DataMember(Order=8) facebookUserId?: string; // @DataMember(Order=9) facebookUserName?: string; // @DataMember(Order=10) firstName?: string; // @DataMember(Order=11) lastName?: string; // @DataMember(Order=12) displayName?: string; // @DataMember(Order=13) company?: string; // @DataMember(Order=14) email?: string; // @DataMember(Order=15) primaryEmail?: string; // @DataMember(Order=16) phoneNumber?: string; // @DataMember(Order=17) birthDate?: string; // @DataMember(Order=18) birthDateRaw?: string; // @DataMember(Order=19) address?: string; // @DataMember(Order=20) address2?: string; // @DataMember(Order=21) city?: string; // @DataMember(Order=22) state?: string; // @DataMember(Order=23) country?: string; // @DataMember(Order=24) culture?: string; // @DataMember(Order=25) fullName?: string; // @DataMember(Order=26) gender?: string; // @DataMember(Order=27) language?: string; // @DataMember(Order=28) mailAddress?: string; // @DataMember(Order=29) nickname?: string; // @DataMember(Order=30) postalCode?: string; // @DataMember(Order=31) timeZone?: string; // @DataMember(Order=32) requestTokenSecret?: string; // @DataMember(Order=33) createdAt?: string; // @DataMember(Order=34) lastModified?: string; // @DataMember(Order=35) roles?: string[]; // @DataMember(Order=36) permissions?: string[]; // @DataMember(Order=37) isAuthenticated?: boolean; // @DataMember(Order=38) fromToken?: boolean; // @DataMember(Order=39) profileUrl?: string; // @DataMember(Order=40) sequence?: string; // @DataMember(Order=41) tag?: number; // @DataMember(Order=42) authProvider?: string; // @DataMember(Order=43) providerOAuthAccess?: IAuthTokens[]; // @DataMember(Order=44) meta?: { [index:string]: string; }; } interface IPoco { name?: string; } interface IEmptyInterface { } interface EmptyClass { } interface ImplementsPoco { name?: string; } interface TypeB { foo?: string; } interface TypeA { bar?: TypeB[]; } interface InnerType { id?: number; name?: string; } type InnerEnum = "Foo" | "Bar" | "Baz"; interface InnerTypeItem { id?: number; name?: string; } type DayOfWeek = "Sunday" | "Monday" | "Tuesday" | "Wednesday" | "Thursday" | "Friday" | "Saturday"; // @DataContract type ScopeType = "Global" | "Sale"; interface Tuple_2<T1, T2> { item1?: T1; item2?: T2; } interface Tuple_3<T1, T2, T3> { item1?: T1; item2?: T2; item3?: T3; } interface IEcho { sentence?: string; } type MyColor = "Red" | "Green" | "Blue"; interface SwaggerNestedModel { /** * NestedProperty description */ // @ApiMember(Description="NestedProperty description") nestedProperty?: boolean; } interface SwaggerNestedModel2 { /** * NestedProperty2 description */ // @ApiMember(Description="NestedProperty2 description") nestedProperty2?: boolean; /** * MultipleValues description */ // @ApiMember(Description="MultipleValues description") multipleValues?: string; /** * TestRange description */ // @ApiMember(Description="TestRange description") testRange?: number; } type MyEnum = "A" | "B" | "C"; // @DataContract interface UserApiKey { // @DataMember(Order=1) key?: string; // @DataMember(Order=2) keyType?: string; // @DataMember(Order=3) expiryDate?: string; } interface PgRockstar extends Rockstar { } interface QueryDb_2<From, Into> extends QueryBase { } interface CustomRockstar { // @AutoQueryViewerField(Title="Name") firstName?: string; // @AutoQueryViewerField(HideInSummary=true) lastName?: string; age?: number; // @AutoQueryViewerField(Title="Album") rockstarAlbumName?: string; // @AutoQueryViewerField(Title="Genre") rockstarGenreName?: string; } interface IFilterRockstars { } interface Movie { id?: number; imdbId?: string; title?: string; rating?: string; score?: number; director?: string; releaseDate?: string; tagLine?: string; genres?: string[]; } interface RockstarAlbum { id?: number; rockstarId?: number; name?: string; } interface RockstarReference { id?: number; firstName?: string; lastName?: string; age?: number; albums?: RockstarAlbum[]; } interface OnlyDefinedInGenericType { id?: number; name?: string; } interface OnlyDefinedInGenericTypeFrom { id?: number; name?: string; } interface OnlyDefinedInGenericTypeInto { id?: number; name?: string; } interface TypesGroup { } // @DataContract interface QueryResponse<T> { // @DataMember(Order=1) offset?: number; // @DataMember(Order=2) total?: number; // @DataMember(Order=3) results?: T[]; // @DataMember(Order=4) meta?: { [index:string]: string; }; // @DataMember(Order=5) responseStatus?: ResponseStatus; } // @DataContract interface UpdateEventSubscriberResponse { // @DataMember(Order=1) responseStatus?: ResponseStatus; } interface ChangeRequestResponse { contentType?: string; header?: string; queryString?: string; form?: string; responseStatus?: ResponseStatus; } interface CustomHttpErrorResponse { custom?: string; responseStatus?: ResponseStatus; } // @Route("/alwaysthrows") interface AlwaysThrows extends IReturn<AlwaysThrows> { } // @Route("/alwaysthrowsfilterattribute") interface AlwaysThrowsFilterAttribute extends IReturn<AlwaysThrowsFilterAttribute> { } // @Route("/alwaysthrowsglobalfilter") interface AlwaysThrowsGlobalFilter extends IReturn<AlwaysThrowsGlobalFilter> { } interface CustomFieldHttpErrorResponse { custom?: string; responseStatus?: ResponseStatus; } interface NoRepeatResponse { id?: string; } interface BatchThrowsResponse { result?: string; responseStatus?: ResponseStatus; } interface ObjectDesignResponse { data?: ObjectDesign; } interface MetadataTestResponse { id?: number; results?: MetadataTestChild[]; } // @DataContract interface GetExampleResponse { // @DataMember(Order=1) responseStatus?: ResponseStatus; // @DataMember(Order=2) // @ApiMember() menuExample1?: MenuExample; } interface AutoQueryMetadataResponse { config?: AutoQueryViewerConfig; userInfo?: AutoQueryViewerUserInfo; operations?: AutoQueryOperation[]; types?: MetadataType[]; responseStatus?: ResponseStatus; meta?: { [index:string]: string; }; } // @DataContract interface HelloACodeGenTestResponse { /** * Description for FirstResult */ // @DataMember firstResult?: number; /** * Description for SecondResult */ // @DataMember // @ApiMember(Description="Description for SecondResult") secondResult?: number; } interface HelloResponse { result?: string; } /** * Description on HelloAllResponse type */ // @DataContract interface HelloAnnotatedResponse { // @DataMember result?: string; } interface HelloList extends IReturn<Array<ListResult>> { names?: string[]; } interface HelloArray extends IReturn<Array<ArrayResult>> { names?: string[]; } interface HelloExistingResponse { helloList?: HelloList; helloArray?: HelloArray; arrayResults?: ArrayResult[]; listResults?: ListResult[]; } interface AllTypes extends IReturn<AllTypes> { id?: number; nullableId?: number; byte?: number; short?: number; int?: number; long?: number; uShort?: number; uInt?: number; uLong?: number; float?: number; double?: number; decimal?: number; string?: string; dateTime?: string; timeSpan?: string; dateTimeOffset?: string; guid?: string; char?: string; keyValuePair?: KeyValuePair<string, string>; nullableDateTime?: string; nullableTimeSpan?: string; stringList?: string[]; stringArray?: string[]; stringMap?: { [index:string]: string; }; intStringMap?: { [index:number]: string; }; subType?: SubType; point?: string; // @DataMember(Name="aliasedName") originalName?: string; } interface HelloAllTypesResponse { result?: string; allTypes?: AllTypes; allCollectionTypes?: AllCollectionTypes; } // @DataContract interface HelloWithDataContractResponse { // @DataMember(Name="result", Order=1, IsRequired=true, EmitDefaultValue=false) result?: string; } /** * Description on HelloWithDescriptionResponse type */ interface HelloWithDescriptionResponse { result?: string; } interface HelloWithInheritanceResponse extends HelloResponseBase { result?: string; } interface HelloWithAlternateReturnResponse extends HelloWithReturnResponse { altResult?: string; } interface HelloWithRouteResponse { result?: string; } interface HelloWithTypeResponse { result?: HelloType; } interface HelloStruct extends IReturn<HelloStruct> { point?: string; nullablePoint?: string; } interface HelloSessionResponse { result?: AuthUserSession; } interface HelloImplementsInterface extends IReturn<HelloImplementsInterface>, ImplementsPoco { name?: string; } interface Request1Response { test?: TypeA; } interface Request2Response { test?: TypeA; } interface HelloInnerTypesResponse { innerType?: InnerType; innerEnum?: InnerEnum; innerList?: InnerTypeItem[]; } interface CustomUserSession extends AuthUserSession { // @DataMember customName?: string; // @DataMember customInfo?: string; } // @DataContract interface QueryResponseTemplate<T> { // @DataMember(Order=1) offset?: number; // @DataMember(Order=2) total?: number; // @DataMember(Order=3) results?: T[]; // @DataMember(Order=4) meta?: { [index:string]: string; }; // @DataMember(Order=5) responseStatus?: ResponseStatus; } interface HelloVerbResponse { result?: string; } interface EnumResponse { operator?: ScopeType; } interface ExcludeTestNested { id?: number; } interface RestrictLocalhost extends IReturn<RestrictLocalhost> { id?: number; } interface RestrictInternal extends IReturn<RestrictInternal> { id?: number; } interface HelloTuple extends IReturn<HelloTuple> { tuple2?: Tuple_2<string, number>; tuple3?: Tuple_3<string, number, boolean>; tuples2?: Tuple_2<string,number>[]; tuples3?: Tuple_3<string,number,boolean>[]; } interface HelloAuthenticatedResponse { version?: number; sessionId?: string; userName?: string; email?: string; isAuthenticated?: boolean; responseStatus?: ResponseStatus; } interface Echo { sentence?: string; } interface ThrowHttpErrorResponse { } interface ThrowTypeResponse { responseStatus?: ResponseStatus; } interface ThrowValidationResponse { age?: number; required?: string; email?: string; responseStatus?: ResponseStatus; } interface acsprofileResponse { profileId?: string; } interface ReturnedDto { id?: number; } // @Route("/matchroute/html") interface MatchesHtml extends IReturn<MatchesHtml> { name?: string; } // @Route("/matchroute/json") interface MatchesJson extends IReturn<MatchesJson> { name?: string; } interface TimestampData { timestamp?: number; } // @Route("/test/html") interface TestHtml extends IReturn<TestHtml> { name?: string; } interface SwaggerComplexResponse { // @DataMember // @ApiMember() isRequired?: boolean; // @DataMember // @ApiMember(IsRequired=true) arrayString?: string[]; // @DataMember // @ApiMember() arrayInt?: number[]; // @DataMember // @ApiMember() listString?: string[]; // @DataMember // @ApiMember() listInt?: number[]; // @DataMember // @ApiMember() dictionaryString?: { [index:string]: string; }; } /** * Api GET All */ // @Route("/swaggerexamples", "GET") // @Api(Description="Api GET All") interface GetSwaggerExamples extends IReturn<GetSwaggerExamples> { get?: string; } /** * Api GET Id */ // @Route("/swaggerexamples/{Id}", "GET") // @Api(Description="Api GET Id") interface GetSwaggerExample extends IReturn<GetSwaggerExample> { id?: number; get?: string; } /** * Api POST */ // @Route("/swaggerexamples", "POST") // @Api(Description="Api POST") interface PostSwaggerExamples extends IReturn<PostSwaggerExamples> { post?: string; } /** * Api PUT Id */ // @Route("/swaggerexamples/{Id}", "PUT") // @Api(Description="Api PUT Id") interface PutSwaggerExample extends IReturn<PutSwaggerExample> { id?: number; get?: string; } // @Route("/lists", "GET") interface GetLists extends IReturn<GetLists> { id?: string; } // @DataContract interface AuthenticateResponse { // @DataMember(Order=1) userId?: string; // @DataMember(Order=2) sessionId?: string; // @DataMember(Order=3) userName?: string; // @DataMember(Order=4) displayName?: string; // @DataMember(Order=5) referrerUrl?: string; // @DataMember(Order=6) bearerToken?: string; // @DataMember(Order=7) refreshToken?: string; // @DataMember(Order=8) responseStatus?: ResponseStatus; // @DataMember(Order=9) meta?: { [index:string]: string; }; } // @DataContract interface AssignRolesResponse { // @DataMember(Order=1) allRoles?: string[]; // @DataMember(Order=2) allPermissions?: string[]; // @DataMember(Order=3) responseStatus?: ResponseStatus; } // @DataContract interface UnAssignRolesResponse { // @DataMember(Order=1) allRoles?: string[]; // @DataMember(Order=2) allPermissions?: string[]; // @DataMember(Order=3) responseStatus?: ResponseStatus; } // @DataContract interface GetApiKeysResponse { // @DataMember(Order=1) results?: UserApiKey[]; // @DataMember(Order=2) responseStatus?: ResponseStatus; } // @DataContract interface RegisterResponse { // @DataMember(Order=1) userId?: string; // @DataMember(Order=2) sessionId?: string; // @DataMember(Order=3) userName?: string; // @DataMember(Order=4) referrerUrl?: string; // @DataMember(Order=5) bearerToken?: string; // @DataMember(Order=6) refreshToken?: string; // @DataMember(Order=7) responseStatus?: ResponseStatus; // @DataMember(Order=8) meta?: { [index:string]: string; }; } // @Route("/anontype") interface AnonType { } // @Route("/query/requestlogs") // @Route("/query/requestlogs/{Date}") interface QueryRequestLogs extends QueryData<RequestLogEntry>, IReturn<QueryResponse<RequestLogEntry>>, IMeta { date?: string; viewErrors?: boolean; } interface TodayLogs extends QueryData<RequestLogEntry>, IReturn<QueryResponse<RequestLogEntry>>, IMeta { } interface TodayErrorLogs extends QueryData<RequestLogEntry>, IReturn<QueryResponse<RequestLogEntry>>, IMeta { } interface YesterdayLogs extends QueryData<RequestLogEntry>, IReturn<QueryResponse<RequestLogEntry>>, IMeta { } interface YesterdayErrorLogs extends QueryData<RequestLogEntry>, IReturn<QueryResponse<RequestLogEntry>>, IMeta { } // @Route("/query/rockstars") interface QueryRockstars extends QueryDb_1<Rockstar>, IReturn<QueryResponse<Rockstar>>, IMeta { age?: number; } interface GetEventSubscribers extends IReturn<any>, IGet { channels?: string[]; } // @Route("/event-subscribers/{Id}", "POST") // @DataContract interface UpdateEventSubscriber extends IReturn<UpdateEventSubscriberResponse>, IPost { // @DataMember(Order=1) id?: string; // @DataMember(Order=2) subscribeChannels?: string[]; // @DataMember(Order=3) unsubscribeChannels?: string[]; } // @Route("/changerequest/{Id}") interface ChangeRequest extends IReturn<ChangeRequestResponse> { id?: string; } // @Route("/compress/{Path*}") interface CompressFile { path?: string; } // @Route("/Routing/LeadPost.aspx") interface LegacyLeadPost { leadType?: string; myId?: number; } // @Route("/info/{Id}") interface Info { id?: string; } interface CustomHttpError extends IReturn<CustomHttpErrorResponse> { statusCode?: number; statusDescription?: string; } interface CustomFieldHttpError extends IReturn<CustomFieldHttpErrorResponse> { } interface FallbackRoute { pathInfo?: string; } interface NoRepeat extends IReturn<NoRepeatResponse> { id?: string; } interface BatchThrows extends IReturn<BatchThrowsResponse> { id?: number; name?: string; } interface BatchThrowsAsync extends IReturn<BatchThrowsResponse> { id?: number; name?: string; } // @Route("/code/object", "GET") interface ObjectId extends IReturn<ObjectDesignResponse> { objectName?: string; } interface MetadataTest extends IReturn<MetadataTestResponse> { id?: number; } // @Route("/example", "GET") // @DataContract interface GetExample extends IReturn<GetExampleResponse> { } interface MetadataRequest extends IReturn<AutoQueryMetadataResponse> { metadataType?: MetadataType; } interface ExcludeMetadataProperty { id?: number; } // @Route("/namedconnection") interface NamedConnection { emailAddresses?: string; } /** * Description for HelloACodeGenTest */ interface HelloACodeGenTest extends IReturn<HelloACodeGenTestResponse> { /** * Description for FirstField */ firstField?: number; secondFields?: string[]; } interface HelloInService extends IReturn<HelloResponse> { name?: string; } // @Route("/hello") // @Route("/hello/{Name}") interface Hello extends IReturn<HelloResponse> { // @Required() name: string; title?: string; } /** * Description on HelloAll type */ // @DataContract interface HelloAnnotated extends IReturn<HelloAnnotatedResponse> { // @DataMember name?: string; } interface HelloWithNestedClass extends IReturn<HelloResponse> { name?: string; nestedClassProp?: NestedClass; } interface HelloReturnList extends IReturn<Array<OnlyInReturnListArg>> { names?: string[]; } interface HelloExisting extends IReturn<HelloExistingResponse> { names?: string[]; } interface HelloWithEnum { enumProp?: EnumType; enumWithValues?: EnumWithValues; nullableEnumProp?: EnumType; enumFlags?: EnumFlags; } interface RestrictedAttributes { id?: number; name?: string; hello?: Hello; } /** * AllowedAttributes Description */ // @Route("/allowed-attributes", "GET") // @Api(Description="AllowedAttributes Description") // @ApiResponse(Description="Your request was not understood", StatusCode=400) // @DataContract interface AllowedAttributes { // @DataMember // @Required() id: number; /** * Range Description */ // @DataMember(Name="Aliased") // @ApiMember(DataType="double", Description="Range Description", IsRequired=true, ParameterType="path") range?: number; } /** * Multi Line Class */ // @Api(Description="Multi Line Class") interface HelloMultiline { /** * Multi Line Property */ // @ApiMember(Description="Multi Line Property") overflow?: string; } interface HelloAllTypes extends IReturn<HelloAllTypesResponse> { name?: string; allTypes?: AllTypes; allCollectionTypes?: AllCollectionTypes; } interface HelloString extends IReturn<string> { name?: string; } interface HelloVoid extends IReturnVoid { name?: string; } // @DataContract interface HelloWithDataContract extends IReturn<HelloWithDataContractResponse> { // @DataMember(Name="name", Order=1, IsRequired=true, EmitDefaultValue=false) name?: string; // @DataMember(Name="id", Order=2, EmitDefaultValue=false) id?: number; } /** * Description on HelloWithDescription type */ interface HelloWithDescription extends IReturn<HelloWithDescriptionResponse> { name?: string; } interface HelloWithInheritance extends HelloBase, IReturn<HelloWithInheritanceResponse> { name?: string; } interface HelloWithGenericInheritance extends HelloBase_1<Poco> { result?: string; } interface HelloWithGenericInheritance2 extends HelloBase_1<Hello> { result?: string; } interface HelloWithNestedInheritance extends HelloBase_1<Item> { } interface HelloWithListInheritance extends Array<InheritedItem> { } interface HelloWithReturn extends IReturn<HelloWithAlternateReturnResponse> { name?: string; } // @Route("/helloroute") interface HelloWithRoute extends IReturn<HelloWithRouteResponse> { name?: string; } interface HelloWithType extends IReturn<HelloWithTypeResponse> { name?: string; } interface HelloSession extends IReturn<HelloSessionResponse> { } interface HelloInterface { poco?: IPoco; emptyInterface?: IEmptyInterface; emptyClass?: EmptyClass; value?: string; } interface Request1 extends IReturn<Request1Response> { test?: TypeA; } interface Request2 extends IReturn<Request2Response> { test?: TypeA; } interface HelloInnerTypes extends IReturn<HelloInnerTypesResponse> { } interface GetUserSession extends IReturn<CustomUserSession> { } interface QueryTemplate extends IReturn<QueryResponseTemplate<Poco>> { } interface HelloReserved { class?: string; type?: string; extension?: string; } interface HelloDictionary extends IReturn<any> { key?: string; value?: string; } interface HelloBuiltin { dayOfWeek?: DayOfWeek; } interface HelloGet extends IReturn<HelloVerbResponse>, IGet { id?: number; } interface HelloPost extends HelloBase, IReturn<HelloVerbResponse>, IPost { } interface HelloPut extends IReturn<HelloVerbResponse>, IPut { id?: number; } interface HelloDelete extends IReturn<HelloVerbResponse>, IDelete { id?: number; } interface HelloPatch extends IReturn<HelloVerbResponse>, IPatch { id?: number; } interface HelloReturnVoid extends IReturnVoid { id?: number; } interface EnumRequest extends IReturn<EnumResponse>, IPut { operator?: ScopeType; } interface ExcludeTest1 extends IReturn<ExcludeTestNested> { } interface ExcludeTest2 extends IReturn<string> { excludeTestNested?: ExcludeTestNested; } interface HelloAuthenticated extends IReturn<HelloAuthenticatedResponse>, IHasSessionId { sessionId?: string; version?: number; } /** * Echoes a sentence */ // @Route("/echoes", "POST") // @Api(Description="Echoes a sentence") interface Echoes extends IReturn<Echo> { /** * The sentence to echo. */ // @ApiMember(DataType="string", Description="The sentence to echo.", IsRequired=true, Name="Sentence", ParameterType="form") sentence?: string; } interface CachedEcho extends IReturn<Echo> { reload?: boolean; sentence?: string; } interface AsyncTest extends IReturn<Echo> { } // @Route("/throwhttperror/{Status}") interface ThrowHttpError extends IReturn<ThrowHttpErrorResponse> { status?: number; message?: string; } // @Route("/throw404") // @Route("/throw404/{Message}") interface Throw404 { message?: string; } // @Route("/return404") interface Return404 { } // @Route("/return404result") interface Return404Result { } // @Route("/throw/{Type}") interface ThrowType extends IReturn<ThrowTypeResponse> { type?: string; message?: string; } // @Route("/throwvalidation") interface ThrowValidation extends IReturn<ThrowValidationResponse> { age?: number; required?: string; email?: string; } // @Route("/api/acsprofiles", "POST,PUT,PATCH,DELETE") // @Route("/api/acsprofiles/{profileId}") interface ACSProfile extends IReturn<acsprofileResponse>, IHasVersion, IHasSessionId { profileId?: string; // @Required() // @StringLength(20) shortName: string; // @StringLength(60) longName?: string; // @StringLength(20) regionId?: string; // @StringLength(20) groupId?: string; // @StringLength(12) deviceID?: string; lastUpdated?: string; enabled?: boolean; version?: number; sessionId?: string; } // @Route("/return/string") interface ReturnString extends IReturn<string> { data?: string; } // @Route("/return/bytes") interface ReturnBytes extends IReturn<Uint8Array> { data?: Uint8Array; } // @Route("/return/stream") interface ReturnStream extends IReturn<Blob> { data?: Uint8Array; } // @Route("/Request1/", "GET") interface GetRequest1 extends IReturn<Array<ReturnedDto>>, IGet { } // @Route("/Request3", "GET") interface GetRequest2 extends IReturn<ReturnedDto>, IGet { } // @Route("/matchlast/{Id}") interface MatchesLastInt { id?: number; } // @Route("/matchlast/{Slug}") interface MatchesNotLastInt { slug?: string; } // @Route("/matchregex/{Id}") interface MatchesId { id?: number; } // @Route("/matchregex/{Slug}") interface MatchesSlug { slug?: string; } // @Route("/{Version}/userdata", "GET") interface SwaggerVersionTest { version?: string; } // @Route("/test/errorview") interface TestErrorView { id?: string; } // @Route("/timestamp", "GET") interface GetTimestamp extends IReturn<TimestampData> { } interface TestMiniverView { } // @Route("/testexecproc") interface TestExecProc { } // @Route("/files/{Path*}") interface GetFile { path?: string; } // @Route("/test/html2") interface TestHtml2 { name?: string; } // @Route("/views/request") interface ViewRequest { name?: string; } // @Route("/index") interface IndexPage { pathInfo?: string; } // @Route("/return/text") interface ReturnText { text?: string; } /** * SwaggerTest Service Description */ // @Route("/swagger", "GET") // @Route("/swagger/{Name}", "GET") // @Route("/swagger/{Name}", "POST") // @Api(Description="SwaggerTest Service Description") // @ApiResponse(Description="Your request was not understood", StatusCode=400) // @ApiResponse(Description="Oops, something broke", StatusCode=500) // @DataContract interface SwaggerTest { /** * Color Description */ // @DataMember // @ApiMember(DataType="string", Description="Color Description", IsRequired=true, ParameterType="path") name?: string; // @DataMember // @ApiMember() color?: MyColor; /** * Aliased Description */ // @DataMember(Name="Aliased") // @ApiMember(DataType="string", Description="Aliased Description", IsRequired=true) original?: string; /** * Not Aliased Description */ // @DataMember // @ApiMember(DataType="string", Description="Not Aliased Description", IsRequired=true) notAliased?: string; /** * Format as password */ // @DataMember // @ApiMember(DataType="password", Description="Format as password") password?: string; // @DataMember // @ApiMember(AllowMultiple=true) myDateBetween?: string[]; /** * Nested model 1 */ // @DataMember // @ApiMember(DataType="SwaggerNestedModel", Description="Nested model 1") nestedModel1?: SwaggerNestedModel; /** * Nested model 2 */ // @DataMember // @ApiMember(DataType="SwaggerNestedModel2", Description="Nested model 2") nestedModel2?: SwaggerNestedModel2; } // @Route("/swaggertest2", "POST") interface SwaggerTest2 { // @ApiMember() myEnumProperty?: MyEnum; // @ApiMember(DataType="string", IsRequired=true, Name="Token", ParameterType="header") token?: string; } // @Route("/swagger-complex", "POST") interface SwaggerComplex extends IReturn<SwaggerComplexResponse> { // @DataMember // @ApiMember() isRequired?: boolean; // @DataMember // @ApiMember(IsRequired=true) arrayString?: string[]; // @DataMember // @ApiMember() arrayInt?: number[]; // @DataMember // @ApiMember() listString?: string[]; // @DataMember // @ApiMember() listInt?: number[]; // @DataMember // @ApiMember() dictionaryString?: { [index:string]: string; }; } // @Route("/swaggerpost/{Required1}", "GET") // @Route("/swaggerpost/{Required1}/{Optional1}", "GET") // @Route("/swaggerpost", "POST") interface SwaggerPostTest extends IReturn<HelloResponse> { // @ApiMember(Verb="POST") // @ApiMember(ParameterType="path", Route="/swaggerpost/{Required1}", Verb="GET") // @ApiMember(ParameterType="path", Route="/swaggerpost/{Required1}/{Optional1}", Verb="GET") required1?: string; // @ApiMember(Verb="POST") // @ApiMember(ParameterType="path", Route="/swaggerpost/{Required1}/{Optional1}", Verb="GET") optional1?: string; } // @Route("/swaggerpost2/{Required1}/{Required2}", "GET") // @Route("/swaggerpost2/{Required1}/{Required2}/{Optional1}", "GET") // @Route("/swaggerpost2", "POST") interface SwaggerPostTest2 extends IReturn<HelloResponse> { // @ApiMember(ParameterType="path", Route="/swaggerpost2/{Required1}/{Required2}", Verb="GET") // @ApiMember(ParameterType="path", Route="/swaggerpost2/{Required1}/{Required2}/{Optional1}", Verb="GET") required1?: string; // @ApiMember(ParameterType="path", Route="/swaggerpost2/{Required1}/{Required2}", Verb="GET") // @ApiMember(ParameterType="path", Route="/swaggerpost2/{Required1}/{Required2}/{Optional1}", Verb="GET") required2?: string; // @ApiMember(ParameterType="path", Route="/swaggerpost2/{Required1}/{Required2}/{Optional1}", Verb="GET") optional1?: string; } // @Route("/swagger/multiattrtest", "POST") // @ApiResponse(Description="Code 1", StatusCode=400) // @ApiResponse(Description="Code 2", StatusCode=402) // @ApiResponse(Description="Code 3", StatusCode=401) interface SwaggerMultiApiResponseTest extends IReturnVoid { } // @Route("/dynamically/registered/{Name}") interface DynamicallyRegistered { name?: string; } // @Route("/auth") // @Route("/auth/{provider}") // @Route("/authenticate") // @Route("/authenticate/{provider}") // @DataContract interface Authenticate extends IReturn<AuthenticateResponse>, IPost, IMeta { // @DataMember(Order=1) provider?: string; // @DataMember(Order=2) state?: string; // @DataMember(Order=3) oauth_token?: string; // @DataMember(Order=4) oauth_verifier?: string; // @DataMember(Order=5) userName?: string; // @DataMember(Order=6) password?: string; // @DataMember(Order=7) rememberMe?: boolean; // @DataMember(Order=8) continue?: string; // @DataMember(Order=9) nonce?: string; // @DataMember(Order=10) uri?: string; // @DataMember(Order=11) response?: string; // @DataMember(Order=12) qop?: string; // @DataMember(Order=13) nc?: string; // @DataMember(Order=14) cnonce?: string; // @DataMember(Order=15) useTokenCookie?: boolean; // @DataMember(Order=16) accessToken?: string; // @DataMember(Order=17) accessTokenSecret?: string; // @DataMember(Order=18) meta?: { [index:string]: string; }; } // @Route("/assignroles") // @DataContract interface AssignRoles extends IReturn<AssignRolesResponse>, IPost { // @DataMember(Order=1) userName?: string; // @DataMember(Order=2) permissions?: string[]; // @DataMember(Order=3) roles?: string[]; } // @Route("/unassignroles") // @DataContract interface UnAssignRoles extends IReturn<UnAssignRolesResponse>, IPost { // @DataMember(Order=1) userName?: string; // @DataMember(Order=2) permissions?: string[]; // @DataMember(Order=3) roles?: string[]; } // @Route("/apikeys") // @Route("/apikeys/{Environment}") // @DataContract interface GetApiKeys extends IReturn<GetApiKeysResponse>, IGet { // @DataMember(Order=1) environment?: string; } // @Route("/apikeys/regenerate") // @Route("/apikeys/regenerate/{Environment}") // @DataContract interface RegenerateApiKeys extends IReturn<GetApiKeysResponse>, IPost { // @DataMember(Order=1) environment?: string; } // @Route("/register") // @DataContract interface Register extends IReturn<RegisterResponse>, IPost { // @DataMember(Order=1) userName?: string; // @DataMember(Order=2) firstName?: string; // @DataMember(Order=3) lastName?: string; // @DataMember(Order=4) displayName?: string; // @DataMember(Order=5) email?: string; // @DataMember(Order=6) password?: string; // @DataMember(Order=7) autoLogin?: boolean; // @DataMember(Order=8) continue?: string; } // @Route("/pgsql/rockstars") interface QueryPostgresRockstars extends QueryDb_1<Rockstar>, IReturn<QueryResponse<Rockstar>>, IMeta { age?: number; } // @Route("/pgsql/pgrockstars") interface QueryPostgresPgRockstars extends QueryDb_1<PgRockstar>, IReturn<QueryResponse<PgRockstar>>, IMeta { age?: number; } interface QueryRockstarsConventions extends QueryDb_1<Rockstar>, IReturn<QueryResponse<Rockstar>>, IMeta { ids?: number[]; ageOlderThan?: number; ageGreaterThanOrEqualTo?: number; ageGreaterThan?: number; greaterThanAge?: number; firstNameStartsWith?: string; lastNameEndsWith?: string; lastNameContains?: string; rockstarAlbumNameContains?: string; rockstarIdAfter?: number; rockstarIdOnOrAfter?: number; } // @AutoQueryViewer(Description="Use this option to search for Rockstars!", Title="Search for Rockstars") interface QueryCustomRockstars extends QueryDb_2<Rockstar, CustomRockstar>, IReturn<QueryResponse<CustomRockstar>>, IMeta { age?: number; } // @Route("/customrockstars") interface QueryRockstarAlbums extends QueryDb_2<Rockstar, CustomRockstar>, IReturn<QueryResponse<CustomRockstar>>, IMeta { age?: number; rockstarAlbumName?: string; } interface QueryRockstarAlbumsImplicit extends QueryDb_2<Rockstar, CustomRockstar>, IReturn<QueryResponse<CustomRockstar>>, IMeta { } interface QueryRockstarAlbumsLeftJoin extends QueryDb_2<Rockstar, CustomRockstar>, IReturn<QueryResponse<CustomRockstar>>, IMeta { age?: number; albumName?: string; } interface QueryOverridedRockstars extends QueryDb_1<Rockstar>, IReturn<QueryResponse<Rockstar>>, IMeta { age?: number; } interface QueryOverridedCustomRockstars extends QueryDb_2<Rockstar, CustomRockstar>, IReturn<QueryResponse<CustomRockstar>>, IMeta { age?: number; } // @Route("/query-custom/rockstars") interface QueryFieldRockstars extends QueryDb_1<Rockstar>, IReturn<QueryResponse<Rockstar>>, IMeta { firstName?: string; firstNames?: string[]; age?: number; firstNameCaseInsensitive?: string; firstNameStartsWith?: string; lastNameEndsWith?: string; firstNameBetween?: string[]; orLastName?: string; firstNameContainsMulti?: string[]; } interface QueryFieldRockstarsDynamic extends QueryDb_1<Rockstar>, IReturn<QueryResponse<Rockstar>>, IMeta { age?: number; } interface QueryRockstarsFilter extends QueryDb_1<Rockstar>, IReturn<QueryResponse<Rockstar>>, IMeta { age?: number; } interface QueryCustomRockstarsFilter extends QueryDb_2<Rockstar, CustomRockstar>, IReturn<QueryResponse<CustomRockstar>>, IMeta { age?: number; } interface QueryRockstarsIFilter extends QueryDb_1<Rockstar>, IReturn<QueryResponse<Rockstar>>, IMeta, IFilterRockstars { age?: number; } // @Route("/OrRockstars") interface QueryOrRockstars extends QueryDb_1<Rockstar>, IReturn<QueryResponse<Rockstar>>, IMeta { age?: number; firstName?: string; } interface QueryGetRockstars extends QueryDb_1<Rockstar>, IReturn<QueryResponse<Rockstar>>, IMeta { ids?: number[]; ages?: number[]; firstNames?: string[]; idsBetween?: number[]; } interface QueryGetRockstarsDynamic extends QueryDb_1<Rockstar>, IReturn<QueryResponse<Rockstar>>, IMeta { } // @Route("/movies/search") interface SearchMovies extends QueryDb_1<Movie>, IReturn<QueryResponse<Movie>>, IMeta { } // @Route("/movies") interface QueryMovies extends QueryDb_1<Movie>, IReturn<QueryResponse<Movie>>, IMeta { ids?: number[]; imdbIds?: string[]; ratings?: string[]; } interface StreamMovies extends QueryDb_1<Movie>, IReturn<QueryResponse<Movie>>, IMeta { ratings?: string[]; } interface QueryUnknownRockstars extends QueryDb_1<Rockstar>, IReturn<QueryResponse<Rockstar>>, IMeta { unknownInt?: number; unknownProperty?: string; } // @Route("/query/rockstar-references") interface QueryRockstarsWithReferences extends QueryDb_1<RockstarReference>, IReturn<QueryResponse<RockstarReference>>, IMeta { age?: number; } interface QueryPocoBase extends QueryDb_1<OnlyDefinedInGenericType>, IReturn<QueryResponse<OnlyDefinedInGenericType>>, IMeta { id?: number; } interface QueryPocoIntoBase extends QueryDb_2<OnlyDefinedInGenericTypeFrom, OnlyDefinedInGenericTypeInto>, IReturn<QueryResponse<OnlyDefinedInGenericTypeInto>>, IMeta { id?: number; } // @Route("/query/alltypes") interface QueryAllTypes extends QueryDb_1<AllTypes>, IReturn<QueryResponse<AllTypes>>, IMeta { } // @Route("/querydata/rockstars") interface QueryDataRockstars extends QueryData<Rockstar>, IReturn<QueryResponse<Rockstar>>, IMeta { age?: number; } }
the_stack
import { Memory, MemberOf, MemoryPages, byte, word } from './types'; import { toHex } from './util'; export const FLAVOR_6502 = '6502'; export const FLAVOR_ROCKWELL_65C02 = 'rockwell65c02'; export const FLAVOR_WDC_65C02 = 'wdc65c02'; export const FLAVORS_65C02 = [ FLAVOR_ROCKWELL_65C02, FLAVOR_WDC_65C02 ]; export const FLAVORS = [ FLAVOR_6502, ...FLAVORS_65C02 ]; export type Flavor = MemberOf<typeof FLAVORS>; export interface CpuOptions { flavor?: Flavor } export interface CpuState { /** Accumulator */ a: byte, /** X index */ x: byte, /** Y index */ y: byte, /** Status register */ s: byte, /** Program counter */ pc: word, /** Stack pointer */ sp: byte, /** Elapsed cycles */ cycles: number } export type Mode = 'accumulator' | // A (Accumulator) 'implied' | // Implied 'immediate' | // # Immediate 'absolute' | // a Absolute 'zeroPage' | // zp Zero Page 'relative' | // r Relative 'absoluteX' | // a,X Absolute, X 'absoluteY' | // a,Y Absolute, Y 'zeroPageX' | // zp,X Zero Page, X 'zeroPageY' | // zp,Y Zero Page, Y 'absoluteIndirect' | // (a) Indirect 'zeroPageXIndirect' | // (zp,X) Zero Page Indexed Indirect 'zeroPageIndirectY' | // (zp),Y Zero Page Indexed with Y 'zeroPageIndirect' | // (zp), 'absoluteXIndirect' | // (a, X), 'zeroPage_relative'; // zp, Relative export type Modes = Record<Mode, number>; /** Addressing mode name to instruction size mapping. */ export const sizes: Modes = { accumulator: 1, implied: 1, immediate: 2, absolute: 3, zeroPage: 2, relative: 2, absoluteX: 3, absoluteY: 3, zeroPageX: 2, zeroPageY: 2, absoluteIndirect: 3, zeroPageXIndirect: 2, zeroPageIndirectY: 2, /* 65c02 */ zeroPageIndirect: 2, absoluteXIndirect: 3, zeroPage_relative: 3 }; /** Status register flag numbers. */ export type flag = 0x80 | 0x40 | 0x20 | 0x10 | 0x08 | 0x04 | 0x02 | 0x01; /** * */ export type DebugInfo = { /** Program counter */ pc: word, /** Accumulator */ ar: byte, /** X index */ xr: byte, /** Y index */ yr: byte, /** Status register */ sr: byte, /** Stack pointer */ sp: byte, /** Current command */ cmd: byte[], }; /** Flags to status byte mask. */ export const flags: { [key: string]: flag } = { N: 0x80, // Negative V: 0x40, // oVerflow X: 0x20, // Unused, always 1 B: 0x10, // Break D: 0x08, // Decimal I: 0x04, // Interrupt Z: 0x02, // Zero C: 0x01 // Carry }; /** CPU-referenced memory locations. */ const loc = { STACK: 0x100, NMI: 0xFFFA, RESET: 0xFFFC, BRK: 0xFFFE }; interface ResettablePageHandler extends MemoryPages { reset(): void; } function isResettablePageHandler(pageHandler: MemoryPages | ResettablePageHandler): pageHandler is ResettablePageHandler { return (pageHandler as ResettablePageHandler).reset !== undefined; } const BLANK_PAGE: Memory = { read: function () { return 0; }, write: function () { } }; interface Opts { inc?: boolean; } type ReadFn = () => byte; type WriteFn = (val: byte) => void; type ReadAddrFn = (opts?: Opts) => word; type ImpliedFn = () => void interface Instruction<T = any> { name: string mode: Mode op: (fn: T) => void modeFn: T } type StrictInstruction = Instruction<ReadFn> | Instruction<WriteFn> | Instruction<ReadAddrFn> | Instruction<ImpliedFn> | Instruction<flag> | Instruction<flag|0> | Instruction<byte> type Instructions = Record<byte, StrictInstruction> type callback = (cpu: CPU6502) => boolean | void; export default class CPU6502 { /** flavor */ private readonly flavor: Flavor; /** 65C02 emulation mode flag */ private readonly is65C02: boolean; /** * Registers */ /** Program counter */ private pc: word = 0; /** Status register */ private sr: byte = flags.X; /** Accumulator */ private ar: byte = 0; /** X index */ private xr: byte = 0; /** Y index */ private yr: byte = 0; /** Stack pointer */ private sp: byte = 0xff; /** Current instruction */ private op: Instruction; /** Last accessed memory address */ private addr: word = 0; /** Filled array of memory handlers by address page */ private memPages: Memory[] = new Array(0x100); /** Callbacks invoked on reset signal */ private resetHandlers: ResettablePageHandler[] = []; /** Elapsed cycles */ private cycles = 0; /** Command being fetched signal */ private sync = false; /** Processor is in WAI mode */ private wait = false; /** Processor is in STP mode */ private stop = false; /** Filled array of CPU operations */ private readonly opary: Instruction[]; constructor({ flavor }: CpuOptions = {}) { this.flavor = flavor ?? FLAVOR_6502; this.is65C02 = !!flavor && FLAVORS_65C02.includes(flavor); this.memPages.fill(BLANK_PAGE); this.memPages.fill(BLANK_PAGE); // Create this CPU's instruction table let ops = { ...this.OPS_6502 }; switch (this.flavor) { case FLAVOR_WDC_65C02: ops = { ...ops, ...this.OPS_65C02, ...this.OPS_WDC_65C02, }; break; case FLAVOR_ROCKWELL_65C02: ops = { ...ops, ...this.OPS_65C02, ...this.OPS_ROCKWELL_65C02, }; break; default: ops = { ...ops, ...this.OPS_NMOS_6502, }; } // Certain browsers benefit from using arrays over maps this.opary = new Array(0x100); for (let idx = 0; idx < 0x100; idx++) { this.opary[idx] = ops[idx] || this.unknown(idx); } } /** * Set or clears `f` in the status register. `f` must be a byte with a * single bit set. */ private setFlag(f: flag, on: boolean) { this.sr = on ? (this.sr | f) : (this.sr & ~f); } /** Updates the status register's zero flag and negative flag. */ private testNZ(val: byte) { this.sr = val === 0 ? (this.sr | flags.Z) : (this.sr & ~flags.Z); this.sr = (val & 0x80) ? (this.sr | flags.N) : (this.sr & ~flags.N); return val; } /** Updates the status register's zero flag. */ private testZ(val: byte) { this.sr = val === 0 ? (this.sr | flags.Z) : (this.sr & ~flags.Z); return val; } /** * Returns `a + b`, unless `sub` is true, in which case it performs * `a - b`. The status register is updated according to the result. */ private add(a: byte, b: byte, sub: boolean): byte { const a7 = a >> 7; const b7 = b >> 7; const ci = this.sr & flags.C; let c; let co; let v; let n; let z; const updateFlags = (c: byte) => { const bin = c & 0xff; n = bin >> 7; co = c >> 8; z = !((a + b + ci) & 0xff); v = a7 ^ b7 ^ n ^ co; }; const updateBCDFlags = (c: byte) => { if (this.is65C02) { const bin = c & 0xff; n = bin >> 7; z = !bin; if (this.op.mode === 'immediate') { if (this.flavor === FLAVOR_WDC_65C02) { this.readByte(sub ? 0xB8 : 0x7F); } else { // rockwell65c02 this.readByte(sub ? 0xB1 : 0x59); } } else { this.readByte(this.addr); } } if (!sub) { co = c >> 8; } }; c = (a & 0x0f) + (b & 0x0f) + ci; if ((this.sr & flags.D) !== 0) { // BCD if (sub) { if (c < 0x10) { c = (c - 0x06) & 0x0f; } c += (a & 0xf0) + (b & 0xf0); updateFlags(c); if (c < 0x100) { c += 0xa0; } } else { if (c > 0x9) { c = 0x10 + ((c + 0x6) & 0xf); } c += (a & 0xf0) + (b & 0xf0); updateFlags(c); if (c >= 0xa0) { c += 0x60; } } updateBCDFlags(c); } else { c += (a & 0xf0) + (b & 0xf0); updateFlags(c); } c = c & 0xff; this.setFlag(flags.N, !!n); this.setFlag(flags.V, !!v); this.setFlag(flags.Z, !!z); this.setFlag(flags.C, !!co); return c; } /** Increments `a` and returns the value, setting the status register. */ private increment(a: byte) { return this.testNZ((a + 0x01) & 0xff); } private decrement(a: byte) { return this.testNZ((a + 0xff) & 0xff); } private readBytePC(): byte { const result = this.readByte(this.pc); this.pc = (this.pc + 1) & 0xffff; return result; } private readByte(addr: word): byte { this.addr = addr; const page = addr >> 8, off = addr & 0xff; const result = this.memPages[page].read(page, off); this.cycles++; return result; } private writeByte(addr: word, val: byte) { this.addr = addr; const page = addr >> 8, off = addr & 0xff; this.memPages[page].write(page, off, val); this.cycles++; } private readWord(addr: word): word { return this.readByte(addr) | (this.readByte(addr + 1) << 8); } private readWordPC(): word { return this.readBytePC() | (this.readBytePC() << 8); } private readZPWord(addr: byte): word { const lsb = this.readByte(addr & 0xff); const msb = this.readByte((addr + 1) & 0xff); return (msb << 8) | lsb; } private pushByte(val: byte) { this.writeByte(loc.STACK | this.sp, val); this.sp = (this.sp + 0xff) & 0xff; } private pushWord(val: word) { this.pushByte(val >> 8); this.pushByte(val & 0xff); } private pullByte(): byte { this.sp = (this.sp + 0x01) & 0xff; return this.readByte(loc.STACK | this.sp); } private pullWordRaw(): word { const lsb = this.pullByte(); const msb = this.pullByte(); return (msb << 8) | lsb; } // Helpers that replicate false reads and writes during work cycles that // vary between CPU versions private workCycle(addr: word, val: byte) { if (this.is65C02) { this.readByte(addr); } else { this.writeByte(addr, val); } } private workCycleIndexedWrite(pc: word, addr: word, addrIdx: word): void { const oldPage = addr & 0xff00; if (this.is65C02) { this.readByte(pc); } else { const off = addrIdx & 0xff; this.readByte(oldPage | off); } } private workCycleIndexedRead(pc: word, addr: word, addrIdx: word): void { const oldPage = addr & 0xff00; const newPage = addrIdx & 0xff00; if (newPage !== oldPage) { if (this.is65C02) { this.readByte(pc); } else { const off = addrIdx & 0xff; this.readByte(oldPage | off); } } } /* * Implied function */ implied = () => { this.readByte(this.pc); }; /* * Read functions */ // #$00 readImmediate = (): byte => { return this.readBytePC(); }; // $0000 readAbsolute = (): byte => { return this.readByte(this.readWordPC()); }; // $00 readZeroPage = (): byte => { return this.readByte(this.readBytePC()); }; // $0000,X readAbsoluteX = (): byte => { const addr = this.readWordPC(); const pc = this.addr; const addrIdx = (addr + this.xr) & 0xffff; this.workCycleIndexedRead(pc, addr, addrIdx); return this.readByte(addrIdx); }; // $0000,Y readAbsoluteY = (): byte => { const addr = this.readWordPC(); const pc = this.addr; const addrIdx = (addr + this.yr) & 0xffff; this.workCycleIndexedRead(pc, addr, addrIdx); return this.readByte(addrIdx); }; // $00,X readZeroPageX = (): byte => { const zpAddr = this.readBytePC(); this.readByte(zpAddr); return this.readByte((zpAddr + this.xr) & 0xff); }; // $00,Y readZeroPageY = (): byte => { const zpAddr = this.readBytePC(); this.readByte(zpAddr); return this.readByte((zpAddr + this.yr) & 0xff); }; // ($00,X) readZeroPageXIndirect = (): byte => { const zpAddr = this.readBytePC(); this.readByte(zpAddr); const addr = this.readZPWord((zpAddr + this.xr) & 0xff); return this.readByte(addr); }; // ($00),Y readZeroPageIndirectY = (): byte => { const zpAddr = this.readBytePC(); const pc = this.addr; const addr = this.readZPWord(zpAddr); const addrIdx = (addr + this.yr) & 0xffff; this.workCycleIndexedRead(pc, addr, addrIdx); return this.readByte(addrIdx); }; // ($00) (65C02) readZeroPageIndirect = (): byte => { return this.readByte(this.readZPWord(this.readBytePC())); }; /* * Write Functions */ // $0000 writeAbsolute = (val: byte) => { this.writeByte(this.readWordPC(), val); }; // $00 writeZeroPage = (val: byte) => { this.writeByte(this.readBytePC(), val); }; // $0000,X writeAbsoluteX = (val: byte) => { const addr = this.readWordPC(); const pc = this.addr; const addrIdx = (addr + this.xr) & 0xffff; this.workCycleIndexedWrite(pc, addr, addrIdx); this.writeByte(addrIdx, val); }; // $0000,Y writeAbsoluteY = (val: byte) => { const addr = this.readWordPC(); const pc = this.addr; const addrIdx = (addr + this.yr) & 0xffff; this.workCycleIndexedWrite(pc, addr, addrIdx); this.writeByte(addrIdx, val); }; // $00,X writeZeroPageX = (val: byte) => { const zpAddr = this.readBytePC(); this.readByte(zpAddr); this.writeByte((zpAddr + this.xr) & 0xff, val); }; // $00,Y writeZeroPageY = (val: byte) => { const zpAddr = this.readBytePC(); this.readByte(zpAddr); this.writeByte((zpAddr + this.yr) & 0xff, val); }; // ($00,X) writeZeroPageXIndirect = (val: byte) => { const zpAddr = this.readBytePC(); this.readByte(zpAddr); const addr = this.readZPWord((zpAddr + this.xr) & 0xff); this.writeByte(addr, val); }; // ($00),Y writeZeroPageIndirectY = (val: byte) => { const zpAddr = this.readBytePC(); const pc = this.addr; const addr = this.readZPWord(zpAddr); const addrIdx = (addr + this.yr) & 0xffff; this.workCycleIndexedWrite(pc, addr, addrIdx); this.writeByte(addrIdx, val); }; // ($00) (65C02) writeZeroPageIndirect = (val: byte) => { this.writeByte(this.readZPWord(this.readBytePC()), val); }; // $00 readAddrZeroPage = () => { return this.readBytePC(); }; // $00,X readAddrZeroPageX = () => { const zpAddr = this.readBytePC(); this.readByte(zpAddr); return (zpAddr + this.xr) & 0xff; }; // $0000 (65C02) readAddrAbsolute = (): word => { return this.readWordPC(); }; // ($0000) (6502) readAddrAbsoluteIndirectBug = (): word => { const addr = this.readWordPC(); const page = addr & 0xff00; const off = addr & 0x00ff; const lsb = this.readByte(addr); const msb = this.readByte(page | ((off + 0x01) & 0xff)); return msb << 8 | lsb; }; // ($0000) (65C02) readAddrAbsoluteIndirect = (): word => { const addr = this.readWord(this.readWordPC()); this.readByte(this.addr); return addr; }; // $0000,X readAddrAbsoluteX = (opts?: Opts): word => { let addr = this.readWordPC(); const page = addr & 0xff00; addr = (addr + this.xr) & 0xffff; if (this.is65C02) { if (opts?.inc) { this.readByte(this.addr); } else { const newPage = addr & 0xff00; if (page !== newPage) { this.readByte(this.addr); } } } else { const off = addr & 0x00ff; this.readByte(page | off); } return addr; }; // $0000,Y (NMOS 6502) readAddrAbsoluteY = (): word => { let addr = this.readWordPC(); const page = addr & 0xff00; addr = (addr + this.yr) & 0xffff; const off = addr & 0x00ff; this.readByte(page | off); return addr; }; // ($00,X) (NMOS 6502) readAddrZeroPageXIndirect = () => { const zpAddr = this.readBytePC(); this.readByte(zpAddr); return this.readZPWord((zpAddr + this.xr) & 0xff); }; // ($00),Y (NMOS 6502) readAddrZeroPageIndirectY = () => { const zpAddr = this.readBytePC(); const addr = this.readZPWord(zpAddr); const addrIdx = (addr + this.yr) & 0xffff; const oldPage = addr & 0xff00; const off = addrIdx & 0xff; this.readByte(oldPage | off); return addrIdx; }; // $(0000,X) (65C02) readAddrAbsoluteXIndirect = (): word => { const lsb = this.readBytePC(); const pc = this.addr; const msb = this.readBytePC(); const addr = (((msb << 8) | lsb) + this.xr) & 0xffff; this.readByte(pc); return this.readWord(addr); }; // 5C, DC, FC NOP (65C02) readNop = (): void => { this.readWordPC(); this.readByte(this.addr); }; // NOP (65C02) readNopImplied = (): void => { // Op is 1 cycle }; /* Break */ brk = (readFn: ReadFn) => { readFn(); this.pushWord(this.pc); this.pushByte(this.sr | flags.B); if (this.is65C02) { this.setFlag(flags.D, false); } this.setFlag(flags.I, true); this.pc = this.readWord(loc.BRK); }; /* Stop (65C02) */ stp = () => { this.stop = true; this.readByte(this.pc); this.readByte(this.pc); }; /* Wait (65C02) */ wai = () => { this.wait = true; this.readByte(this.pc); this.readByte(this.pc); }; /* Load Accumulator */ lda = (readFn: ReadFn) => { this.ar = this.testNZ(readFn()); }; /* Load X Register */ ldx = (readFn: ReadFn) => { this.xr = this.testNZ(readFn()); }; /* Load Y Register */ ldy = (readFn: ReadFn) => { this.yr = this.testNZ(readFn()); }; /* Store Accumulator */ sta = (writeFn: WriteFn) => { writeFn(this.ar); }; /* Store X Register */ stx = (writeFn: WriteFn) => { writeFn(this.xr); }; /* Store Y Register */ sty = (writeFn: WriteFn) => { writeFn(this.yr); }; /* Store Zero */ stz = (writeFn: WriteFn) => { writeFn(0); }; /* Add with Carry */ adc = (readFn: ReadFn) => { this.ar = this.add(this.ar, readFn(), /* sub= */ false); }; /* Subtract with Carry */ sbc = (readFn: ReadFn) => { this.ar = this.add(this.ar, readFn() ^ 0xff, /* sub= */ true); }; /* Increment Memory */ incA = () => { this.readByte(this.pc); this.ar = this.increment(this.ar); }; inc = (readAddrFn: ReadAddrFn) => { const addr = readAddrFn({ inc: true }); const oldVal = this.readByte(addr); this.workCycle(addr, oldVal); const val = this.increment(oldVal); this.writeByte(addr, val); }; /* Increment X */ inx = () => { this.readByte(this.pc); this.xr = this.increment(this.xr); }; /* Increment Y */ iny = () => { this.readByte(this.pc); this.yr = this.increment(this.yr); }; /* Decrement Memory */ decA = () => { this.readByte(this.pc); this.ar = this.decrement(this.ar); }; dec = (readAddrFn: ReadAddrFn) => { const addr = readAddrFn({ inc: true}); const oldVal = this.readByte(addr); this.workCycle(addr, oldVal); const val = this.decrement(oldVal); this.writeByte(addr, val); }; /* Decrement X */ dex = () => { this.readByte(this.pc); this.xr = this.decrement(this.xr); }; /* Decrement Y */ dey = () => { this.readByte(this.pc); this.yr = this.decrement(this.yr); }; shiftLeft = (val: byte) => { this.setFlag(flags.C, !!(val & 0x80)); return this.testNZ((val << 1) & 0xff); }; /* Arithmetic Shift Left */ aslA = () => { this.readByte(this.pc); this.ar = this.shiftLeft(this.ar); }; asl = (readAddrFn: ReadAddrFn) => { const addr = readAddrFn(); const oldVal = this.readByte(addr); this.workCycle(addr, oldVal); const val = this.shiftLeft(oldVal); this.writeByte(addr, val); }; shiftRight = (val: byte) => { this.setFlag(flags.C, !!(val & 0x01)); return this.testNZ(val >> 1); }; /* Logical Shift Right */ lsrA = () => { this.readByte(this.pc); this.ar = this.shiftRight(this.ar); }; lsr = (readAddrFn: ReadAddrFn) => { const addr = readAddrFn(); const oldVal = this.readByte(addr); this.workCycle(addr, oldVal); const val = this.shiftRight(oldVal); this.writeByte(addr, val); }; rotateLeft = (val: byte) => { const c = (this.sr & flags.C); this.setFlag(flags.C, !!(val & 0x80)); return this.testNZ(((val << 1) | (c ? 0x01 : 0x00)) & 0xff); }; /* Rotate Left */ rolA = () => { this.readByte(this.pc); this.ar = this.rotateLeft(this.ar); }; rol = (readAddrFn: ReadAddrFn) => { const addr = readAddrFn(); const oldVal = this.readByte(addr); this.workCycle(addr, oldVal); const val = this.rotateLeft(oldVal); this.writeByte(addr, val); }; private rotateRight(a: byte) { const c = (this.sr & flags.C); this.setFlag(flags.C, !!(a & 0x01)); return this.testNZ((a >> 1) | (c ? 0x80 : 0x00)); } /* Rotate Right */ rorA = () => { this.readByte(this.pc); this.ar = this.rotateRight(this.ar); }; ror = (readAddrFn: ReadAddrFn) => { const addr = readAddrFn(); const oldVal = this.readByte(addr); this.workCycle(addr, oldVal); const val = this.rotateRight(oldVal); this.writeByte(addr, val); }; /* Logical And Accumulator */ and = (readFn: ReadFn) => { this.ar = this.testNZ(this.ar & readFn()); }; /* Logical Or Accumulator */ ora = (readFn: ReadFn) => { this.ar = this.testNZ(this.ar | readFn()); }; /* Logical Exclusive Or Accumulator */ eor = (readFn: ReadFn) => { this.ar = this.testNZ(this.ar ^ readFn()); }; /* Reset Bit */ rmb = (b: byte) => { const bit = (0x1 << b) ^ 0xFF; const addr = this.readBytePC(); let val = this.readByte(addr); this.readByte(addr); val &= bit; this.writeByte(addr, val); }; /* Set Bit */ smb = (b: byte) => { const bit = 0x1 << b; const addr = this.readBytePC(); let val = this.readByte(addr); this.readByte(addr); val |= bit; this.writeByte(addr, val); }; /* Test and Reset Bits */ trb = (readAddrFn: ReadAddrFn) => { const addr = readAddrFn(); const val = this.readByte(addr); this.testZ(val & this.ar); this.readByte(addr); this.writeByte(addr, val & ~this.ar); }; /* Test and Set Bits */ tsb = (readAddrFn: ReadAddrFn) => { const addr = readAddrFn(); const val = this.readByte(addr); this.testZ(val & this.ar); this.readByte(addr); this.writeByte(addr, val | this.ar); }; /* Bit */ bit = (readFn: ReadFn) => { const val = readFn(); this.setFlag(flags.Z, (val & this.ar) === 0); this.setFlag(flags.N, !!(val & 0x80)); this.setFlag(flags.V, !!(val & 0x40)); }; /* Bit Immediate*/ bitI = (readFn: ReadFn) => { const val = readFn(); this.setFlag(flags.Z, (val & this.ar) === 0); }; private compare(a: byte, b: byte) { b = (b ^ 0xff); const c = a + b + 1; this.setFlag(flags.C, c > 0xff); this.testNZ(c & 0xff); } cmp = (readFn: ReadFn) => { this.compare(this.ar, readFn()); }; cpx = (readFn: ReadFn) => { this.compare(this.xr, readFn()); }; cpy = (readFn: ReadFn) => { this.compare(this.yr, readFn()); }; /* Branches */ brs = (f: flag) => { const off = this.readBytePC(); // changes pc if ((f & this.sr) !== 0) { this.readByte(this.pc); const oldPage = this.pc & 0xff00; this.pc += off > 127 ? off - 256 : off; this.pc &= 0xffff; const newPage = this.pc & 0xff00; const newOff = this.pc & 0xff; if (newPage !== oldPage) this.readByte(oldPage | newOff); } }; brc = (f: flag|0) => { const off = this.readBytePC(); // changes pc if ((f & this.sr) === 0) { this.readByte(this.pc); const oldPage = this.pc & 0xff00; this.pc += off > 127 ? off - 256 : off; this.pc &= 0xffff; const newPage = this.pc & 0xff00; const newOff = this.pc & 0xff; if (newPage !== oldPage) this.readByte(oldPage | newOff); } }; /* WDC 65C02 branches */ bbr = (b: byte) => { const zpAddr = this.readBytePC(); const val = this.readByte(zpAddr); this.writeByte(zpAddr, val); const off = this.readBytePC(); // changes pc const oldPc = this.pc; const oldPage = oldPc & 0xff00; let newPC = this.pc + (off > 127 ? off - 256 : off); newPC &= 0xffff; const newOff = newPC & 0xff; this.readByte(oldPage | newOff); if (((1 << b) & val) === 0) { this.pc = newPC; } }; bbs = (b: byte) => { const zpAddr = this.readBytePC(); const val = this.readByte(zpAddr); this.writeByte(zpAddr, val); const off = this.readBytePC(); // changes pc const oldPc = this.pc; const oldPage = oldPc & 0xff00; let newPC = this.pc + (off > 127 ? off - 256 : off); newPC &= 0xffff; const newOff = newPC & 0xff; this.readByte(oldPage | newOff); if (((1 << b) & val) !== 0) { this.pc = newPC; } }; /* Transfers and stack */ tax = () => { this.readByte(this.pc); this.testNZ(this.xr = this.ar); }; txa = () => { this.readByte(this.pc); this.testNZ(this.ar = this.xr); }; tay = () => { this.readByte(this.pc); this.testNZ(this.yr = this.ar); }; tya = () => { this.readByte(this.pc); this.testNZ(this.ar = this.yr); }; tsx = () => { this.readByte(this.pc); this.testNZ(this.xr = this.sp); }; txs = () => { this.readByte(this.pc); this.sp = this.xr; }; pha = () => { this.readByte(this.pc); this.pushByte(this.ar); }; pla = () => { this.readByte(this.pc); this.readByte(0x0100 | this.sp); this.testNZ(this.ar = this.pullByte()); }; phx = () => { this.readByte(this.pc); this.pushByte(this.xr); }; plx = () => { this.readByte(this.pc); this.readByte(0x0100 | this.sp); this.testNZ(this.xr = this.pullByte()); }; phy = () => { this.readByte(this.pc); this.pushByte(this.yr); }; ply = () => { this.readByte(this.pc); this.readByte(0x0100 | this.sp); this.testNZ(this.yr = this.pullByte()); }; php = () => { this.readByte(this.pc); this.pushByte(this.sr | flags.B); }; plp = () => { this.readByte(this.pc); this.readByte(0x0100 | this.sp); this.sr = (this.pullByte() & ~flags.B) | flags.X; }; /* Jump */ jmp = (readAddrFn: ReadAddrFn) => { this.pc = readAddrFn(); }; /* Jump Subroutine */ jsr = () => { const lsb = this.readBytePC(); this.readByte(0x0100 | this.sp); this.pushWord(this.pc); const msb = this.readBytePC(); this.pc = (msb << 8 | lsb) & 0xffff; }; /* Return from Subroutine */ rts = () => { this.readByte(this.pc); this.readByte(0x0100 | this.sp); const addr = this.pullWordRaw(); this.readByte(addr); this.pc = (addr + 1) & 0xffff; }; /* Return from Interrupt */ rti = () => { this.readByte(this.pc); this.readByte(0x0100 | this.sp); this.sr = (this.pullByte() & ~flags.B) | flags.X; this.pc = this.pullWordRaw(); }; /* Set and Clear */ set = (flag: flag) => { this.readByte(this.pc); this.sr |= flag; }; clr = (flag: flag) => { this.readByte(this.pc); this.sr &= ~flag; }; /* No-Op */ nop = (readFn: ImpliedFn | ReadFn) => { readFn(); }; /* NMOS 6502 Illegal opcodes */ /* ASO = ASL + ORA */ aso = (readAddrFn: ReadAddrFn) => { const addr = readAddrFn(); const oldVal = this.readByte(addr); this.workCycle(addr, oldVal); const val = this.shiftLeft(oldVal); this.writeByte(addr, val); this.ar |= val; this.testNZ(this.ar); }; /* RLA = ROL + AND */ rla = (readAddrFn: ReadAddrFn) => { const addr = readAddrFn(); const oldVal = this.readByte(addr); this.workCycle(addr, oldVal); const val = this.rotateLeft(oldVal); this.writeByte(addr, val); this.ar &= val; this.testNZ(this.ar); }; /* LSE = LSR + EOR */ lse = (readAddrFn: ReadAddrFn) => { const addr = readAddrFn(); const oldVal = this.readByte(addr); this.workCycle(addr, oldVal); const val = this.shiftRight(oldVal); this.writeByte(addr, val); this.ar ^= val; this.testNZ(this.ar); }; /* RRA = ROR + ADC */ rra = (readAddrFn: ReadAddrFn) => { const addr = readAddrFn(); const oldVal = this.readByte(addr); this.workCycle(addr, oldVal); const val = this.rotateRight(oldVal); this.writeByte(addr, val); this.ar = this.add(this.ar, val, false); }; /* AXS = Store A & X */ axs = (writeFn: WriteFn) => { writeFn(this.ar & this.xr); }; /* LAX = Load A & X */ lax = (readFn: ReadFn) => { const val = readFn(); this.ar = val; this.xr = val; this.testNZ(val); }; /* DCM = DEC + CMP */ dcm = (readAddrFn: ReadAddrFn) => { const addr = readAddrFn({ inc: true}); const oldVal = this.readByte(addr); this.workCycle(addr, oldVal); const val = this.decrement(oldVal); this.writeByte(addr, val); this.compare(this.ar, val); }; /* INS = INC + SBC */ ins = (readAddrFn: ReadAddrFn) => { const addr = readAddrFn({ inc: true}); const oldVal = this.readByte(addr); this.workCycle(addr, oldVal); const val = this.increment(oldVal); this.writeByte(addr, val); this.ar = this.add(this.ar, val ^ 0xff, true); }; /* ALR = AND + LSR */ alr = (readFn: ReadFn) => { const val = readFn() & this.ar; this.ar = this.shiftRight(val); }; /* ARR = AND + ROR */ arr = (readFn: ReadFn) => { const val = readFn() & this.ar; const ah = val >> 4; const al = val & 0xf; const b7 = val >> 7; const b6 = (val >> 6) & 0x1; this.ar = this.rotateRight(val); let c = !!b7; const v = !!(b7 ^ b6); if (this.sr & flags.D) { if (al + (al & 0x1) > 0x5) { this.ar = (this.ar & 0xf0) | ((this.ar + 0x6) & 0xf); } if (ah + (ah & 0x1) > 5) { c = true; this.ar =((this.ar + 0x60) & 0xff); } } this.setFlag(flags.V, v); this.setFlag(flags.C, c); }; /* XAA = TAX + AND */ xaa = (readFn: ReadFn) => { const val = readFn(); this.ar = (this.xr & 0xEE) | (this.xr & this.ar & 0x11); this.ar = this.testNZ(this.ar & val); }; /** OAL = ORA + AND */ oal = (readFn: ReadFn) => { this.ar |= 0xEE; const val = this.testNZ(this.ar & readFn()); this.ar = val; this.xr = val; }; /* SAX = A & X + SBC */ sax = (readFn: ReadFn) => { const a = this.xr & this.ar; let b = readFn(); b = (b ^ 0xff); const c = a + b + 1; this.setFlag(flags.C, c > 0xff); this.xr = this.testNZ(c & 0xff); }; /* TAS = X & Y -> S */ tas = (readAddrFn: ReadAddrFn) => { const addr = readAddrFn(); let val = this.xr & this.ar; this.sp = val; const msb = addr >> 8; val = val & ((msb + 1) & 0xff); this.writeByte(addr, val); }; /* SAY = Y & AH + 1 */ say = (readAddrFn: ReadAddrFn) => { const addr = readAddrFn(); const msb = addr >> 8; const val = this.yr & ((msb + 1) & 0xff); this.writeByte(addr, val); }; /* XAS = X & AH + 1 */ xas = (readAddrFn: ReadAddrFn) => { const addr = readAddrFn(); const msb = addr >> 8; const val = this.xr & ((msb + 1) & 0xff); this.writeByte(addr, val); }; /* AXA = X & AH + 1 */ axa = (readAddrFn: ReadAddrFn) => { const addr = readAddrFn(); let val = this.xr & this.ar; const msb = addr >> 8; val = val & ((msb + 1) & 0xff); this.writeByte(addr, val); }; /* ANC = AND with carry */ anc = (readFn: ReadFn) => { this.ar = this.testNZ(this.ar & readFn()); const c = !!(this.ar & 0x80); this.setFlag(flags.C, c); }; /* LAS = RD & SP -> A, X, S */ las = (readFn: ReadFn) => { const val = this.sp & readFn(); this.sp = val; this.xr = val; this.ar = this.testNZ(val); }; /* SKB/SKW */ skp = (readFn: ReadFn) => { readFn(); }; /* HLT */ hlt = (_impliedFn: ImpliedFn) => { this.readByte(this.pc); this.readByte(this.pc); // PC shouldn't have advanced this.pc = (--this.pc) & 0xffff; this.stop = true; }; private unknown(b: byte) { let unk: StrictInstruction; if (this.is65C02) { // Default behavior is a 1 cycle NOP unk = { name: 'NOP', op: this.nop, modeFn: this.readNopImplied, mode: 'implied', }; } else { // All 6502 Instructions should be defined throw new Error(`Missing ${toHex(b)}`); } return unk; } public step(cb?: callback) { this.sync = true; this.op = this.opary[this.readBytePC()]; this.sync = false; this.op.op(this.op.modeFn); cb?.(this); } public stepN(n: number, cb?: callback) { for (let idx = 0; idx < n; idx++) { this.sync = true; this.op = this.opary[this.readBytePC()]; this.sync = false; this.op.op(this.op.modeFn); if (cb?.(this)) { return; } } } public stepCycles(c: number) { const end = this.cycles + c; while (this.cycles < end) { this.sync = true; this.op = this.opary[this.readBytePC()]; this.sync = false; this.op.op(this.op.modeFn); } } public stepCyclesDebug(c: number, cb?: callback): void { const end = this.cycles + c; while (this.cycles < end) { this.sync = true; this.op = this.opary[this.readBytePC()]; this.sync = false; this.op.op(this.op.modeFn); if (cb?.(this)) { return; } } } public addPageHandler(pho: (MemoryPages | ResettablePageHandler)) { for (let idx = pho.start(); idx <= pho.end(); idx++) { this.memPages[idx] = pho; } if (isResettablePageHandler(pho)) this.resetHandlers.push(pho); } public reset() { // cycles = 0; this.sr = flags.X; this.sp = 0xff; this.ar = 0; this.yr = 0; this.xr = 0; this.pc = this.readWord(loc.RESET); this.wait = false; this.stop = false; for (let idx = 0; idx < this.resetHandlers.length; idx++) { this.resetHandlers[idx].reset(); } } /* IRQ - Interrupt Request */ public irq() { if ((this.sr & flags.I) === 0) { this.pushWord(this.pc); this.pushByte(this.sr & ~flags.B); if (this.is65C02) { this.setFlag(flags.D, false); } this.setFlag(flags.I, true); this.pc = this.readWord(loc.BRK); this.wait = false; } } /* NMI Non-maskable Interrupt */ public nmi() { this.pushWord(this.pc); this.pushByte(this.sr & ~flags.B); if (this.is65C02) { this.setFlag(flags.D, false); } this.setFlag(flags.I, true); this.pc = this.readWord(loc.NMI); this.wait = false; } public getPC() { return this.pc; } public setPC(pc: word) { this.pc = pc; } public getDebugInfo(): DebugInfo { const b = this.read(this.pc); const op = this.opary[b]; const size = sizes[op.mode]; const cmd = new Array(size); cmd[0] = b; for (let idx = 1; idx < size; idx++) { cmd[idx] = this.read(this.pc + idx); } return { pc: this.pc, ar: this.ar, xr: this.xr, yr: this.yr, sr: this.sr, sp: this.sp, cmd }; } public getSync() { return this.sync; } public getStop() { return this.stop; } public getWait() { return this.wait; } public getCycles() { return this.cycles; } public getOpInfo(opcode: byte) { return this.opary[opcode]; } public getState(): CpuState { return { a: this.ar, x: this.xr, y: this.yr, s: this.sr, pc: this.pc, sp: this.sp, cycles: this.cycles }; } public setState(state: CpuState) { this.ar = state.a; this.xr = state.x; this.yr = state.y; this.sr = state.s; this.pc = state.pc; this.sp = state.sp; this.cycles = state.cycles; } public read(addr: word): byte; public read(page: byte, off: byte): byte; public read(a: number, b?: number): byte { let page, off; if (b !== undefined) { page = a; off = b; } else { page = a >> 8; off = a & 0xff; } return this.memPages[page].read(page, off); } public write(addr: word, val: byte): void; public write(page: byte, off: byte, val: byte): void; public write(a: number, b: number, c?: byte): void { let page, off, val; if (c !== undefined ) { page = a; off = b; val = c; } else { page = a >> 8; off = a & 0xff; val = b; } this.memPages[page].write(page, off, val); } OPS_6502: Instructions = { // LDA 0xa9: { name: 'LDA', op: this.lda, modeFn: this.readImmediate, mode: 'immediate' }, 0xa5: { name: 'LDA', op: this.lda, modeFn: this.readZeroPage, mode: 'zeroPage' }, 0xb5: { name: 'LDA', op: this.lda, modeFn: this.readZeroPageX, mode: 'zeroPageX' }, 0xad: { name: 'LDA', op: this.lda, modeFn: this.readAbsolute, mode: 'absolute' }, 0xbd: { name: 'LDA', op: this.lda, modeFn: this.readAbsoluteX, mode: 'absoluteX' }, 0xb9: { name: 'LDA', op: this.lda, modeFn: this.readAbsoluteY, mode: 'absoluteY' }, 0xa1: { name: 'LDA', op: this.lda, modeFn: this.readZeroPageXIndirect, mode: 'zeroPageXIndirect' }, 0xb1: { name: 'LDA', op: this.lda, modeFn: this.readZeroPageIndirectY, mode: 'zeroPageIndirectY' }, // LDX 0xa2: { name: 'LDX', op: this.ldx, modeFn: this.readImmediate, mode: 'immediate' }, 0xa6: { name: 'LDX', op: this.ldx, modeFn: this.readZeroPage, mode: 'zeroPage' }, 0xb6: { name: 'LDX', op: this.ldx, modeFn: this.readZeroPageY, mode: 'zeroPageY' }, 0xae: { name: 'LDX', op: this.ldx, modeFn: this.readAbsolute, mode: 'absolute' }, 0xbe: { name: 'LDX', op: this.ldx, modeFn: this.readAbsoluteY, mode: 'absoluteY' }, // LDY 0xa0: { name: 'LDY', op: this.ldy, modeFn: this.readImmediate, mode: 'immediate' }, 0xa4: { name: 'LDY', op: this.ldy, modeFn: this.readZeroPage, mode: 'zeroPage' }, 0xb4: { name: 'LDY', op: this.ldy, modeFn: this.readZeroPageX, mode: 'zeroPageX' }, 0xac: { name: 'LDY', op: this.ldy, modeFn: this.readAbsolute, mode: 'absolute' }, 0xbc: { name: 'LDY', op: this.ldy, modeFn: this.readAbsoluteX, mode: 'absoluteX' }, // STA 0x85: { name: 'STA', op: this.sta, modeFn: this.writeZeroPage, mode: 'zeroPage' }, 0x95: { name: 'STA', op: this.sta, modeFn: this.writeZeroPageX, mode: 'zeroPageX' }, 0x8d: { name: 'STA', op: this.sta, modeFn: this.writeAbsolute, mode: 'absolute' }, 0x9d: { name: 'STA', op: this.sta, modeFn: this.writeAbsoluteX, mode: 'absoluteX' }, 0x99: { name: 'STA', op: this.sta, modeFn: this.writeAbsoluteY, mode: 'absoluteY' }, 0x81: { name: 'STA', op: this.sta, modeFn: this.writeZeroPageXIndirect, mode: 'zeroPageXIndirect' }, 0x91: { name: 'STA', op: this.sta, modeFn: this.writeZeroPageIndirectY, mode: 'zeroPageIndirectY' }, // STX 0x86: { name: 'STX', op: this.stx, modeFn: this.writeZeroPage, mode: 'zeroPage' }, 0x96: { name: 'STX', op: this.stx, modeFn: this.writeZeroPageY, mode: 'zeroPageY' }, 0x8e: { name: 'STX', op: this.stx, modeFn: this.writeAbsolute, mode: 'absolute' }, // STY 0x84: { name: 'STY', op: this.sty, modeFn: this.writeZeroPage, mode: 'zeroPage' }, 0x94: { name: 'STY', op: this.sty, modeFn: this.writeZeroPageX, mode: 'zeroPageX' }, 0x8c: { name: 'STY', op: this.sty, modeFn: this.writeAbsolute, mode: 'absolute' }, // ADC 0x69: { name: 'ADC', op: this.adc, modeFn: this.readImmediate, mode: 'immediate' }, 0x65: { name: 'ADC', op: this.adc, modeFn: this.readZeroPage, mode: 'zeroPage' }, 0x75: { name: 'ADC', op: this.adc, modeFn: this.readZeroPageX, mode: 'zeroPageX' }, 0x6D: { name: 'ADC', op: this.adc, modeFn: this.readAbsolute, mode: 'absolute' }, 0x7D: { name: 'ADC', op: this.adc, modeFn: this.readAbsoluteX, mode: 'absoluteX' }, 0x79: { name: 'ADC', op: this.adc, modeFn: this.readAbsoluteY, mode: 'absoluteY' }, 0x61: { name: 'ADC', op: this.adc, modeFn: this.readZeroPageXIndirect, mode: 'zeroPageXIndirect' }, 0x71: { name: 'ADC', op: this.adc, modeFn: this.readZeroPageIndirectY, mode: 'zeroPageIndirectY' }, // SBC 0xe9: { name: 'SBC', op: this.sbc, modeFn: this.readImmediate, mode: 'immediate' }, 0xe5: { name: 'SBC', op: this.sbc, modeFn: this.readZeroPage, mode: 'zeroPage' }, 0xf5: { name: 'SBC', op: this.sbc, modeFn: this.readZeroPageX, mode: 'zeroPageX' }, 0xeD: { name: 'SBC', op: this.sbc, modeFn: this.readAbsolute, mode: 'absolute' }, 0xfD: { name: 'SBC', op: this.sbc, modeFn: this.readAbsoluteX, mode: 'absoluteX' }, 0xf9: { name: 'SBC', op: this.sbc, modeFn: this.readAbsoluteY, mode: 'absoluteY' }, 0xe1: { name: 'SBC', op: this.sbc, modeFn: this.readZeroPageXIndirect, mode: 'zeroPageXIndirect' }, 0xf1: { name: 'SBC', op: this.sbc, modeFn: this.readZeroPageIndirectY, mode: 'zeroPageIndirectY' }, // INC 0xe6: { name: 'INC', op: this.inc, modeFn: this.readAddrZeroPage, mode: 'zeroPage' }, 0xf6: { name: 'INC', op: this.inc, modeFn: this.readAddrZeroPageX, mode: 'zeroPageX' }, 0xee: { name: 'INC', op: this.inc, modeFn: this.readAddrAbsolute, mode: 'absolute' }, 0xfe: { name: 'INC', op: this.inc, modeFn: this.readAddrAbsoluteX, mode: 'absoluteX' }, // INX 0xe8: { name: 'INX', op: this.inx, modeFn: this.implied, mode: 'implied' }, // INY 0xc8: { name: 'INY', op: this.iny, modeFn: this.implied, mode: 'implied' }, // DEC 0xc6: { name: 'DEC', op: this.dec, modeFn: this.readAddrZeroPage, mode: 'zeroPage' }, 0xd6: { name: 'DEC', op: this.dec, modeFn: this.readAddrZeroPageX, mode: 'zeroPageX' }, 0xce: { name: 'DEC', op: this.dec, modeFn: this.readAddrAbsolute, mode: 'absolute' }, 0xde: { name: 'DEC', op: this.dec, modeFn: this.readAddrAbsoluteX, mode: 'absoluteX' }, // DEX 0xca: { name: 'DEX', op: this.dex, modeFn: this.implied, mode: 'implied' }, // DEY 0x88: { name: 'DEY', op: this.dey, modeFn: this.implied, mode: 'implied' }, // ASL 0x0A: { name: 'ASL', op: this.aslA, modeFn: this.implied, mode: 'accumulator' }, 0x06: { name: 'ASL', op: this.asl, modeFn: this.readAddrZeroPage, mode: 'zeroPage' }, 0x16: { name: 'ASL', op: this.asl, modeFn: this.readAddrZeroPageX, mode: 'zeroPageX' }, 0x0E: { name: 'ASL', op: this.asl, modeFn: this.readAddrAbsolute, mode: 'absolute' }, 0x1E: { name: 'ASL', op: this.asl, modeFn: this.readAddrAbsoluteX, mode: 'absoluteX' }, // LSR 0x4A: { name: 'LSR', op: this.lsrA, modeFn: this.implied, mode: 'accumulator' }, 0x46: { name: 'LSR', op: this.lsr, modeFn: this.readAddrZeroPage, mode: 'zeroPage' }, 0x56: { name: 'LSR', op: this.lsr, modeFn: this.readAddrZeroPageX, mode: 'zeroPageX' }, 0x4E: { name: 'LSR', op: this.lsr, modeFn: this.readAddrAbsolute, mode: 'absolute' }, 0x5E: { name: 'LSR', op: this.lsr, modeFn: this.readAddrAbsoluteX, mode: 'absoluteX' }, // ROL 0x2A: { name: 'ROL', op: this.rolA, modeFn: this.implied, mode: 'accumulator' }, 0x26: { name: 'ROL', op: this.rol, modeFn: this.readAddrZeroPage, mode: 'zeroPage' }, 0x36: { name: 'ROL', op: this.rol, modeFn: this.readAddrZeroPageX, mode: 'zeroPageX' }, 0x2E: { name: 'ROL', op: this.rol, modeFn: this.readAddrAbsolute, mode: 'absolute' }, 0x3E: { name: 'ROL', op: this.rol, modeFn: this.readAddrAbsoluteX, mode: 'absoluteX' }, // ROR 0x6A: { name: 'ROR', op: this.rorA, modeFn: this.implied, mode: 'accumulator' }, 0x66: { name: 'ROR', op: this.ror, modeFn: this.readAddrZeroPage, mode: 'zeroPage' }, 0x76: { name: 'ROR', op: this.ror, modeFn: this.readAddrZeroPageX, mode: 'zeroPageX' }, 0x6E: { name: 'ROR', op: this.ror, modeFn: this.readAddrAbsolute, mode: 'absolute' }, 0x7E: { name: 'ROR', op: this.ror, modeFn: this.readAddrAbsoluteX, mode: 'absoluteX' }, // AND 0x29: { name: 'AND', op: this.and, modeFn: this.readImmediate, mode: 'immediate' }, 0x25: { name: 'AND', op: this.and, modeFn: this.readZeroPage, mode: 'zeroPage' }, 0x35: { name: 'AND', op: this.and, modeFn: this.readZeroPageX, mode: 'zeroPageX' }, 0x2D: { name: 'AND', op: this.and, modeFn: this.readAbsolute, mode: 'absolute' }, 0x3D: { name: 'AND', op: this.and, modeFn: this.readAbsoluteX, mode: 'absoluteX' }, 0x39: { name: 'AND', op: this.and, modeFn: this.readAbsoluteY, mode: 'absoluteY' }, 0x21: { name: 'AND', op: this.and, modeFn: this.readZeroPageXIndirect, mode: 'zeroPageXIndirect' }, 0x31: { name: 'AND', op: this.and, modeFn: this.readZeroPageIndirectY, mode: 'zeroPageIndirectY' }, // ORA 0x09: { name: 'ORA', op: this.ora, modeFn: this.readImmediate, mode: 'immediate' }, 0x05: { name: 'ORA', op: this.ora, modeFn: this.readZeroPage, mode: 'zeroPage' }, 0x15: { name: 'ORA', op: this.ora, modeFn: this.readZeroPageX, mode: 'zeroPageX' }, 0x0D: { name: 'ORA', op: this.ora, modeFn: this.readAbsolute, mode: 'absolute' }, 0x1D: { name: 'ORA', op: this.ora, modeFn: this.readAbsoluteX, mode: 'absoluteX' }, 0x19: { name: 'ORA', op: this.ora, modeFn: this.readAbsoluteY, mode: 'absoluteY' }, 0x01: { name: 'ORA', op: this.ora, modeFn: this.readZeroPageXIndirect, mode: 'zeroPageXIndirect' }, 0x11: { name: 'ORA', op: this.ora, modeFn: this.readZeroPageIndirectY, mode: 'zeroPageIndirectY' }, // EOR 0x49: { name: 'EOR', op: this.eor, modeFn: this.readImmediate, mode: 'immediate' }, 0x45: { name: 'EOR', op: this.eor, modeFn: this.readZeroPage, mode: 'zeroPage' }, 0x55: { name: 'EOR', op: this.eor, modeFn: this.readZeroPageX, mode: 'zeroPageX' }, 0x4D: { name: 'EOR', op: this.eor, modeFn: this.readAbsolute, mode: 'absolute' }, 0x5D: { name: 'EOR', op: this.eor, modeFn: this.readAbsoluteX, mode: 'absoluteX' }, 0x59: { name: 'EOR', op: this.eor, modeFn: this.readAbsoluteY, mode: 'absoluteY' }, 0x41: { name: 'EOR', op: this.eor, modeFn: this.readZeroPageXIndirect, mode: 'zeroPageXIndirect' }, 0x51: { name: 'EOR', op: this.eor, modeFn: this.readZeroPageIndirectY, mode: 'zeroPageIndirectY' }, // CMP 0xc9: { name: 'CMP', op: this.cmp, modeFn: this.readImmediate, mode: 'immediate' }, 0xc5: { name: 'CMP', op: this.cmp, modeFn: this.readZeroPage, mode: 'zeroPage' }, 0xd5: { name: 'CMP', op: this.cmp, modeFn: this.readZeroPageX, mode: 'zeroPageX' }, 0xcD: { name: 'CMP', op: this.cmp, modeFn: this.readAbsolute, mode: 'absolute' }, 0xdD: { name: 'CMP', op: this.cmp, modeFn: this.readAbsoluteX, mode: 'absoluteX' }, 0xd9: { name: 'CMP', op: this.cmp, modeFn: this.readAbsoluteY, mode: 'absoluteY' }, 0xc1: { name: 'CMP', op: this.cmp, modeFn: this.readZeroPageXIndirect, mode: 'zeroPageXIndirect' }, 0xd1: { name: 'CMP', op: this.cmp, modeFn: this.readZeroPageIndirectY, mode: 'zeroPageIndirectY' }, // CPX 0xE0: { name: 'CPX', op: this.cpx, modeFn: this.readImmediate, mode: 'immediate' }, 0xE4: { name: 'CPX', op: this.cpx, modeFn: this.readZeroPage, mode: 'zeroPage' }, 0xEC: { name: 'CPX', op: this.cpx, modeFn: this.readAbsolute, mode: 'absolute' }, // CPY 0xC0: { name: 'CPY', op: this.cpy, modeFn: this.readImmediate, mode: 'immediate' }, 0xC4: { name: 'CPY', op: this.cpy, modeFn: this.readZeroPage, mode: 'zeroPage' }, 0xCC: { name: 'CPY', op: this.cpy, modeFn: this.readAbsolute, mode: 'absolute' }, // BIT 0x24: { name: 'BIT', op: this.bit, modeFn: this.readZeroPage, mode: 'zeroPage' }, 0x2C: { name: 'BIT', op: this.bit, modeFn: this.readAbsolute, mode: 'absolute' }, // BCC 0x90: { name: 'BCC', op: this.brc, modeFn: flags.C, mode: 'relative' }, // BCS 0xB0: { name: 'BCS', op: this.brs, modeFn: flags.C, mode: 'relative' }, // BEQ 0xF0: { name: 'BEQ', op: this.brs, modeFn: flags.Z, mode: 'relative' }, // BMI 0x30: { name: 'BMI', op: this.brs, modeFn: flags.N, mode: 'relative' }, // BNE 0xD0: { name: 'BNE', op: this.brc, modeFn: flags.Z, mode: 'relative' }, // BPL 0x10: { name: 'BPL', op: this.brc, modeFn: flags.N, mode: 'relative' }, // BVC 0x50: { name: 'BVC', op: this.brc, modeFn: flags.V, mode: 'relative' }, // BVS 0x70: { name: 'BVS', op: this.brs, modeFn: flags.V, mode: 'relative' }, // TAX 0xAA: { name: 'TAX', op: this.tax, modeFn: this.implied, mode: 'implied' }, // TXA 0x8A: { name: 'TXA', op: this.txa, modeFn: this.implied, mode: 'implied' }, // TAY 0xA8: { name: 'TAY', op: this.tay, modeFn: this.implied, mode: 'implied' }, // TYA 0x98: { name: 'TYA', op: this.tya, modeFn: this.implied, mode: 'implied' }, // TSX 0xBA: { name: 'TSX', op: this.tsx, modeFn: this.implied, mode: 'implied' }, // TXS 0x9A: { name: 'TXS', op: this.txs, modeFn: this.implied, mode: 'implied' }, // PHA 0x48: { name: 'PHA', op: this.pha, modeFn: this.implied, mode: 'implied' }, // PLA 0x68: { name: 'PLA', op: this.pla, modeFn: this.implied, mode: 'implied' }, // PHP 0x08: { name: 'PHP', op: this.php, modeFn: this.implied, mode: 'implied' }, // PLP 0x28: { name: 'PLP', op: this.plp, modeFn: this.implied, mode: 'implied' }, // JMP 0x4C: { name: 'JMP', op: this.jmp, modeFn: this.readAddrAbsolute, mode: 'absolute' }, 0x6C: { name: 'JMP', op: this.jmp, modeFn: this.readAddrAbsoluteIndirectBug, mode: 'absoluteIndirect' }, // JSR 0x20: { name: 'JSR', op: this.jsr, modeFn: this.readAddrAbsolute, mode: 'absolute' }, // RTS 0x60: { name: 'RTS', op: this.rts, modeFn: this.implied, mode: 'implied' }, // RTI 0x40: { name: 'RTI', op: this.rti, modeFn: this.implied, mode: 'implied' }, // SEC 0x38: { name: 'SEC', op: this.set, modeFn: flags.C, mode: 'implied' }, // SED 0xF8: { name: 'SED', op: this.set, modeFn: flags.D, mode: 'implied' }, // SEI 0x78: { name: 'SEI', op: this.set, modeFn: flags.I, mode: 'implied' }, // CLC 0x18: { name: 'CLC', op: this.clr, modeFn: flags.C, mode: 'implied' }, // CLD 0xD8: { name: 'CLD', op: this.clr, modeFn: flags.D, mode: 'implied' }, // CLI 0x58: { name: 'CLI', op: this.clr, modeFn: flags.I, mode: 'implied' }, // CLV 0xB8: { name: 'CLV', op: this.clr, modeFn: flags.V, mode: 'implied' }, // NOP 0xea: { name: 'NOP', op: this.nop, modeFn: this.implied, mode: 'implied' }, // BRK 0x00: { name: 'BRK', op: this.brk, modeFn: this.readImmediate, mode: 'immediate' } }; /* 65C02 Instructions */ OPS_65C02: Instructions = { // INC / DEC A 0x1A: { name: 'INC', op: this.incA, modeFn: this.implied, mode: 'accumulator' }, 0x3A: { name: 'DEC', op: this.decA, modeFn: this.implied, mode: 'accumulator' }, // Indirect Zero Page for the masses 0x12: { name: 'ORA', op: this.ora, modeFn: this.readZeroPageIndirect, mode: 'zeroPageIndirect' }, 0x32: { name: 'AND', op: this.and, modeFn: this.readZeroPageIndirect, mode: 'zeroPageIndirect' }, 0x52: { name: 'EOR', op: this.eor, modeFn: this.readZeroPageIndirect, mode: 'zeroPageIndirect' }, 0x72: { name: 'ADC', op: this.adc, modeFn: this.readZeroPageIndirect, mode: 'zeroPageIndirect' }, 0x92: { name: 'STA', op: this.sta, modeFn: this.writeZeroPageIndirect, mode: 'zeroPageIndirect' }, 0xB2: { name: 'LDA', op: this.lda, modeFn: this.readZeroPageIndirect, mode: 'zeroPageIndirect' }, 0xD2: { name: 'CMP', op: this.cmp, modeFn: this.readZeroPageIndirect, mode: 'zeroPageIndirect' }, 0xF2: { name: 'SBC', op: this.sbc, modeFn: this.readZeroPageIndirect, mode: 'zeroPageIndirect' }, // Better BIT 0x34: { name: 'BIT', op: this.bit, modeFn: this.readZeroPageX, mode: 'zeroPageX' }, 0x3C: { name: 'BIT', op: this.bit, modeFn: this.readAbsoluteX, mode: 'absoluteX' }, 0x89: { name: 'BIT', op: this.bitI, modeFn: this.readImmediate, mode: 'immediate' }, // JMP absolute indirect indexed 0x6C: { name: 'JMP', op: this.jmp, modeFn: this.readAddrAbsoluteIndirect, mode: 'absoluteIndirect' }, 0x7C: { name: 'JMP', op: this.jmp, modeFn: this.readAddrAbsoluteXIndirect, mode: 'absoluteXIndirect' }, // BBR/BBS 0x0F: { name: 'BBR0', op: this.bbr, modeFn: 0, mode: 'zeroPage_relative' }, 0x1F: { name: 'BBR1', op: this.bbr, modeFn: 1, mode: 'zeroPage_relative' }, 0x2F: { name: 'BBR2', op: this.bbr, modeFn: 2, mode: 'zeroPage_relative' }, 0x3F: { name: 'BBR3', op: this.bbr, modeFn: 3, mode: 'zeroPage_relative' }, 0x4F: { name: 'BBR4', op: this.bbr, modeFn: 4, mode: 'zeroPage_relative' }, 0x5F: { name: 'BBR5', op: this.bbr, modeFn: 5, mode: 'zeroPage_relative' }, 0x6F: { name: 'BBR6', op: this.bbr, modeFn: 6, mode: 'zeroPage_relative' }, 0x7F: { name: 'BBR7', op: this.bbr, modeFn: 7, mode: 'zeroPage_relative' }, 0x8F: { name: 'BBS0', op: this.bbs, modeFn: 0, mode: 'zeroPage_relative' }, 0x9F: { name: 'BBS1', op: this.bbs, modeFn: 1, mode: 'zeroPage_relative' }, 0xAF: { name: 'BBS2', op: this.bbs, modeFn: 2, mode: 'zeroPage_relative' }, 0xBF: { name: 'BBS3', op: this.bbs, modeFn: 3, mode: 'zeroPage_relative' }, 0xCF: { name: 'BBS4', op: this.bbs, modeFn: 4, mode: 'zeroPage_relative' }, 0xDF: { name: 'BBS5', op: this.bbs, modeFn: 5, mode: 'zeroPage_relative' }, 0xEF: { name: 'BBS6', op: this.bbs, modeFn: 6, mode: 'zeroPage_relative' }, 0xFF: { name: 'BBS7', op: this.bbs, modeFn: 7, mode: 'zeroPage_relative' }, // BRA 0x80: { name: 'BRA', op: this.brc, modeFn: 0, mode: 'relative' }, // NOP 0x02: { name: 'NOP', op: this.nop, modeFn: this.readImmediate, mode: 'immediate' }, 0x22: { name: 'NOP', op: this.nop, modeFn: this.readImmediate, mode: 'immediate' }, 0x42: { name: 'NOP', op: this.nop, modeFn: this.readImmediate, mode: 'immediate' }, 0x44: { name: 'NOP', op: this.nop, modeFn: this.readZeroPage, mode: 'immediate' }, 0x54: { name: 'NOP', op: this.nop, modeFn: this.readZeroPageX, mode: 'immediate' }, 0x62: { name: 'NOP', op: this.nop, modeFn: this.readImmediate, mode: 'immediate' }, 0x82: { name: 'NOP', op: this.nop, modeFn: this.readImmediate, mode: 'immediate' }, 0xC2: { name: 'NOP', op: this.nop, modeFn: this.readImmediate, mode: 'immediate' }, 0xD4: { name: 'NOP', op: this.nop, modeFn: this.readZeroPageX, mode: 'immediate' }, 0xE2: { name: 'NOP', op: this.nop, modeFn: this.readImmediate, mode: 'immediate' }, 0xF4: { name: 'NOP', op: this.nop, modeFn: this.readZeroPageX, mode: 'immediate' }, 0x5C: { name: 'NOP', op: this.nop, modeFn: this.readNop, mode: 'absolute' }, 0xDC: { name: 'NOP', op: this.nop, modeFn: this.readNop, mode: 'absolute' }, 0xFC: { name: 'NOP', op: this.nop, modeFn: this.readNop, mode: 'absolute' }, // PHX 0xDA: { name: 'PHX', op: this.phx, modeFn: this.implied, mode: 'implied' }, // PHY 0x5A: { name: 'PHY', op: this.phy, modeFn: this.implied, mode: 'implied' }, // PLX 0xFA: { name: 'PLX', op: this.plx, modeFn: this.implied, mode: 'implied' }, // PLY 0x7A: { name: 'PLY', op: this.ply, modeFn: this.implied, mode: 'implied' }, // RMB/SMB 0x07: { name: 'RMB0', op: this.rmb, modeFn: 0, mode: 'zeroPage' }, 0x17: { name: 'RMB1', op: this.rmb, modeFn: 1, mode: 'zeroPage' }, 0x27: { name: 'RMB2', op: this.rmb, modeFn: 2, mode: 'zeroPage' }, 0x37: { name: 'RMB3', op: this.rmb, modeFn: 3, mode: 'zeroPage' }, 0x47: { name: 'RMB4', op: this.rmb, modeFn: 4, mode: 'zeroPage' }, 0x57: { name: 'RMB5', op: this.rmb, modeFn: 5, mode: 'zeroPage' }, 0x67: { name: 'RMB6', op: this.rmb, modeFn: 6, mode: 'zeroPage' }, 0x77: { name: 'RMB7', op: this.rmb, modeFn: 7, mode: 'zeroPage' }, 0x87: { name: 'SMB0', op: this.smb, modeFn: 0, mode: 'zeroPage' }, 0x97: { name: 'SMB1', op: this.smb, modeFn: 1, mode: 'zeroPage' }, 0xA7: { name: 'SMB2', op: this.smb, modeFn: 2, mode: 'zeroPage' }, 0xB7: { name: 'SMB3', op: this.smb, modeFn: 3, mode: 'zeroPage' }, 0xC7: { name: 'SMB4', op: this.smb, modeFn: 4, mode: 'zeroPage' }, 0xD7: { name: 'SMB5', op: this.smb, modeFn: 5, mode: 'zeroPage' }, 0xE7: { name: 'SMB6', op: this.smb, modeFn: 6, mode: 'zeroPage' }, 0xF7: { name: 'SMB7', op: this.smb, modeFn: 7, mode: 'zeroPage' }, // STZ 0x64: { name: 'STZ', op: this.stz, modeFn: this.writeZeroPage, mode: 'zeroPage' }, 0x74: { name: 'STZ', op: this.stz, modeFn: this.writeZeroPageX, mode: 'zeroPageX' }, 0x9C: { name: 'STZ', op: this.stz, modeFn: this.writeAbsolute, mode: 'absolute' }, 0x9E: { name: 'STZ', op: this.stz, modeFn: this.writeAbsoluteX, mode: 'absoluteX' }, // TRB 0x14: { name: 'TRB', op: this.trb, modeFn: this.readAddrZeroPage, mode: 'zeroPage' }, 0x1C: { name: 'TRB', op: this.trb, modeFn: this.readAddrAbsolute, mode: 'absolute' }, // TSB 0x04: { name: 'TSB', op: this.tsb, modeFn: this.readAddrZeroPage, mode: 'zeroPage' }, 0x0C: { name: 'TSB', op: this.tsb, modeFn: this.readAddrAbsolute, mode: 'absolute' } }; OPS_NMOS_6502: Instructions = { // ASO 0x0F: { name: 'ASO', op: this.aso, modeFn: this.readAddrAbsolute, mode: 'absolute' }, 0x1F: { name: 'ASO', op: this.aso, modeFn: this.readAddrAbsoluteX, mode: 'absoluteX' }, 0x1B: { name: 'ASO', op: this.aso, modeFn: this.readAddrAbsoluteY, mode: 'absoluteY' }, 0x07: { name: 'ASO', op: this.aso, modeFn: this.readAddrZeroPage, mode: 'zeroPage' }, 0x17: { name: 'ASO', op: this.aso, modeFn: this.readAddrZeroPageX, mode: 'zeroPageX' }, 0x03: { name: 'ASO', op: this.aso, modeFn: this.readAddrZeroPageXIndirect, mode: 'zeroPageXIndirect' }, 0x13: { name: 'ASO', op: this.aso, modeFn: this.readAddrZeroPageIndirectY, mode: 'zeroPageIndirectY' }, // RLA 0x2F: { name: 'RLA', op: this.rla, modeFn: this.readAddrAbsolute, mode: 'absolute' }, 0x3F: { name: 'RLA', op: this.rla, modeFn: this.readAddrAbsoluteX, mode: 'absoluteX' }, 0x3B: { name: 'RLA', op: this.rla, modeFn: this.readAddrAbsoluteY, mode: 'absoluteY' }, 0x27: { name: 'RLA', op: this.rla, modeFn: this.readAddrZeroPage, mode: 'zeroPage' }, 0x37: { name: 'RLA', op: this.rla, modeFn: this.readAddrZeroPageX, mode: 'zeroPageX' }, 0x23: { name: 'RLA', op: this.rla, modeFn: this.readAddrZeroPageXIndirect, mode: 'zeroPageXIndirect' }, 0x33: { name: 'RLA', op: this.rla, modeFn: this.readAddrZeroPageIndirectY, mode: 'zeroPageIndirectY' }, // LSE 0x4F: { name: 'LSE', op: this.lse, modeFn: this.readAddrAbsolute, mode: 'absolute' }, 0x5F: { name: 'LSE', op: this.lse, modeFn: this.readAddrAbsoluteX, mode: 'absoluteX' }, 0x5B: { name: 'LSE', op: this.lse, modeFn: this.readAddrAbsoluteY, mode: 'absoluteY' }, 0x47: { name: 'LSE', op: this.lse, modeFn: this.readAddrZeroPage, mode: 'zeroPage' }, 0x57: { name: 'LSE', op: this.lse, modeFn: this.readAddrZeroPageX, mode: 'zeroPageX' }, 0x43: { name: 'LSE', op: this.lse, modeFn: this.readAddrZeroPageXIndirect, mode: 'zeroPageXIndirect' }, 0x53: { name: 'LSE', op: this.lse, modeFn: this.readAddrZeroPageIndirectY, mode: 'zeroPageIndirectY' }, // RRA 0x6F: { name: 'RRA', op: this.rra, modeFn: this.readAddrAbsolute, mode: 'absolute' }, 0x7F: { name: 'RRA', op: this.rra, modeFn: this.readAddrAbsoluteX, mode: 'absoluteX' }, 0x7B: { name: 'RRA', op: this.rra, modeFn: this.readAddrAbsoluteY, mode: 'absoluteY' }, 0x67: { name: 'RRA', op: this.rra, modeFn: this.readAddrZeroPage, mode: 'zeroPage' }, 0x77: { name: 'RRA', op: this.rra, modeFn: this.readAddrZeroPageX, mode: 'zeroPageX' }, 0x63: { name: 'RRA', op: this.rra, modeFn: this.readAddrZeroPageXIndirect, mode: 'zeroPageXIndirect' }, 0x73: { name: 'RRA', op: this.rra, modeFn: this.readAddrZeroPageIndirectY, mode: 'zeroPageIndirectY' }, // AXS 0x8F: { name: 'AXS', op: this.axs, modeFn: this.writeAbsolute, mode: 'absolute'}, 0x87: { name: 'AXS', op: this.axs, modeFn: this.writeZeroPage, mode: 'zeroPage'}, 0x97: { name: 'AXS', op: this.axs, modeFn: this.writeZeroPageY, mode: 'zeroPageY'}, 0x83: { name: 'AXS', op: this.axs, modeFn: this.writeZeroPageXIndirect, mode: 'zeroPageXIndirect'}, // LAX 0xAF: { name: 'LAX', op: this.lax, modeFn: this.readAbsolute, mode: 'absolute'}, 0xBF: { name: 'LAX', op: this.lax, modeFn: this.readAbsoluteY, mode: 'absoluteY'}, 0xA7: { name: 'LAX', op: this.lax, modeFn: this.readZeroPage, mode: 'zeroPage'}, 0xB7: { name: 'LAX', op: this.lax, modeFn: this.readZeroPageY, mode: 'zeroPageY'}, 0xA3: { name: 'LAX', op: this.lax, modeFn: this.readZeroPageXIndirect, mode: 'zeroPageXIndirect'}, 0xB3: { name: 'LAX', op: this.lax, modeFn: this.readZeroPageIndirectY, mode: 'zeroPageIndirectY'}, // DCM 0xCF: { name: 'DCM', op: this.dcm, modeFn: this.readAddrAbsolute, mode: 'absolute' }, 0xDF: { name: 'DCM', op: this.dcm, modeFn: this.readAddrAbsoluteX, mode: 'absoluteX' }, 0xDB: { name: 'DCM', op: this.dcm, modeFn: this.readAddrAbsoluteY, mode: 'absoluteY' }, 0xC7: { name: 'DCM', op: this.dcm, modeFn: this.readAddrZeroPage, mode: 'zeroPage' }, 0xD7: { name: 'DCM', op: this.dcm, modeFn: this.readAddrZeroPageX, mode: 'zeroPageX' }, 0xC3: { name: 'DCM', op: this.dcm, modeFn: this.readAddrZeroPageXIndirect, mode: 'zeroPageXIndirect' }, 0xD3: { name: 'DCM', op: this.dcm, modeFn: this.readAddrZeroPageIndirectY, mode: 'zeroPageIndirectY' }, // INS 0xEF: { name: 'INS', op: this.ins, modeFn: this.readAddrAbsolute, mode: 'absolute' }, 0xFF: { name: 'INS', op: this.ins, modeFn: this.readAddrAbsoluteX, mode: 'absoluteX' }, 0xFB: { name: 'INS', op: this.ins, modeFn: this.readAddrAbsoluteY, mode: 'absoluteY' }, 0xE7: { name: 'INS', op: this.ins, modeFn: this.readAddrZeroPage, mode: 'zeroPage' }, 0xF7: { name: 'INS', op: this.ins, modeFn: this.readAddrZeroPageX, mode: 'zeroPageX' }, 0xE3: { name: 'INS', op: this.ins, modeFn: this.readAddrZeroPageXIndirect, mode: 'zeroPageXIndirect' }, 0xF3: { name: 'INS', op: this.ins, modeFn: this.readAddrZeroPageIndirectY, mode: 'zeroPageIndirectY' }, // ALR 0x4B: { name: 'ALR', op: this.alr, modeFn: this.readImmediate, mode: 'immediate' }, // ARR 0x6B: { name: 'ARR', op: this.arr, modeFn: this.readImmediate, mode: 'immediate' }, // XAA 0x8B: { name: 'XAA', op: this.xaa, modeFn: this.readImmediate, mode: 'immediate' }, // OAL 0xAB: { name: 'OAL', op: this.oal, modeFn: this.readImmediate, mode: 'immediate' }, // SAX 0xCB: { name: 'SAX', op: this.sax, modeFn: this.readImmediate, mode: 'immediate' }, // NOP 0x1a: { name: 'NOP', op: this.nop, modeFn: this.implied, mode: 'implied' }, 0x3a: { name: 'NOP', op: this.nop, modeFn: this.implied, mode: 'implied' }, 0x5a: { name: 'NOP', op: this.nop, modeFn: this.implied, mode: 'implied' }, 0x7a: { name: 'NOP', op: this.nop, modeFn: this.implied, mode: 'implied' }, 0xda: { name: 'NOP', op: this.nop, modeFn: this.implied, mode: 'implied' }, 0xfa: { name: 'NOP', op: this.nop, modeFn: this.implied, mode: 'implied' }, // SKB 0x80: { name: 'SKB', op: this.skp, modeFn: this.readImmediate, mode: 'immediate' }, 0x82: { name: 'SKB', op: this.skp, modeFn: this.readImmediate, mode: 'immediate' }, 0x89: { name: 'SKB', op: this.skp, modeFn: this.readImmediate, mode: 'immediate' }, 0xC2: { name: 'SKB', op: this.skp, modeFn: this.readImmediate, mode: 'immediate' }, 0xE2: { name: 'SKB', op: this.skp, modeFn: this.readImmediate, mode: 'immediate' }, 0x04: { name: 'SKB', op: this.skp, modeFn: this.readZeroPage, mode: 'zeroPage' }, 0x14: { name: 'SKB', op: this.skp, modeFn: this.readZeroPageX, mode: 'zeroPageX' }, 0x34: { name: 'SKB', op: this.skp, modeFn: this.readZeroPageX, mode: 'zeroPageX' }, 0x44: { name: 'SKB', op: this.skp, modeFn: this.readZeroPage, mode: 'zeroPage' }, 0x54: { name: 'SKB', op: this.skp, modeFn: this.readZeroPageX, mode: 'zeroPageX' }, 0x64: { name: 'SKB', op: this.skp, modeFn: this.readZeroPage, mode: 'zeroPage' }, 0x74: { name: 'SKB', op: this.skp, modeFn: this.readZeroPageX, mode: 'zeroPageX' }, 0xD4: { name: 'SKB', op: this.skp, modeFn: this.readZeroPageX, mode: 'zeroPageX' }, 0xF4: { name: 'SKB', op: this.skp, modeFn: this.readZeroPageX, mode: 'zeroPageX' }, // SKW 0x0C: { name: 'SKW', op: this.skp, modeFn: this.readAddrAbsolute, mode: 'absolute' }, 0x1C: { name: 'SKW', op: this.skp, modeFn: this.readAddrAbsoluteX, mode: 'absoluteX' }, 0x3C: { name: 'SKW', op: this.skp, modeFn: this.readAddrAbsoluteX, mode: 'absoluteX' }, 0x5C: { name: 'SKW', op: this.skp, modeFn: this.readAddrAbsoluteX, mode: 'absoluteX' }, 0x7C: { name: 'SKW', op: this.skp, modeFn: this.readAddrAbsoluteX, mode: 'absoluteX' }, 0xDC: { name: 'SKW', op: this.skp, modeFn: this.readAddrAbsoluteX, mode: 'absoluteX' }, 0xFC: { name: 'SKW', op: this.skp, modeFn: this.readAddrAbsoluteX, mode: 'absoluteX' }, // HLT 0x02: { name: 'HLT', op: this.hlt, modeFn: this.readNopImplied, mode: 'implied' }, 0x12: { name: 'HLT', op: this.hlt, modeFn: this.readNopImplied, mode: 'implied' }, 0x22: { name: 'HLT', op: this.hlt, modeFn: this.readNopImplied, mode: 'implied' }, 0x32: { name: 'HLT', op: this.hlt, modeFn: this.readNopImplied, mode: 'implied' }, 0x42: { name: 'HLT', op: this.hlt, modeFn: this.readNopImplied, mode: 'implied' }, 0x52: { name: 'HLT', op: this.hlt, modeFn: this.readNopImplied, mode: 'implied' }, 0x62: { name: 'HLT', op: this.hlt, modeFn: this.readNopImplied, mode: 'implied' }, 0x72: { name: 'HLT', op: this.hlt, modeFn: this.readNopImplied, mode: 'implied' }, 0x92: { name: 'HLT', op: this.hlt, modeFn: this.readNopImplied, mode: 'implied' }, 0xB2: { name: 'HLT', op: this.hlt, modeFn: this.readNopImplied, mode: 'implied' }, 0xD2: { name: 'HLT', op: this.hlt, modeFn: this.readNopImplied, mode: 'implied' }, 0xF2: { name: 'HLT', op: this.hlt, modeFn: this.readNopImplied, mode: 'implied' }, // TAS 0x9B: { name: 'TAS', op: this.tas, modeFn: this.readAddrAbsoluteY, mode: 'absoluteY'}, // SAY 0x9C: { name: 'SAY', op: this.say, modeFn: this.readAddrAbsoluteX, mode: 'absoluteX'}, // XAS 0x9E: { name: 'XAS', op: this.xas, modeFn: this.readAddrAbsoluteY, mode: 'absoluteY'}, // AXA 0x9F: { name: 'AXA', op: this.axa, modeFn: this.readAddrAbsoluteY, mode: 'absoluteY'}, 0x93: { name: 'AXA', op: this.axa, modeFn: this.readAddrZeroPageIndirectY, mode: 'zeroPageIndirectY'}, // ANC 0x2b: { name: 'ANC', op: this.anc, modeFn: this.readImmediate, mode: 'immediate' }, 0x0b: { name: 'ANC', op: this.anc, modeFn: this.readImmediate, mode: 'immediate' }, // LAS 0xBB: { name: 'LAS', op: this.las, modeFn: this.readAbsoluteY, mode: 'absoluteY'}, // SBC 0xEB: { name: 'SBC', op: this.sbc, modeFn: this.readImmediate, mode: 'immediate'} }; OPS_ROCKWELL_65C02: Instructions = { 0xCB: { name: 'NOP', op: this.nop, modeFn: this.implied, mode: 'implied' }, 0xDB: { name: 'NOP', op: this.nop, modeFn: this.readZeroPageX, mode: 'immediate' }, }; /* WDC 65C02 Instructions */ OPS_WDC_65C02: Instructions = { 0xCB: { name: 'WAI', op: this.wai, modeFn: this.implied, mode: 'implied' }, 0xDB: { name: 'STP', op: this.stp, modeFn: this.implied, mode: 'implied' } }; }
the_stack
import { EDGE_MAX_VALUE, IOption } from "./maxrects_packer"; import { Rectangle, IRectangle } from "./geom/Rectangle"; import { Bin } from "./abstract_bin"; import { ImageRect } from './geom/ImageRect'; export class MaxRectsBin extends Bin { public width: number; public height: number; public freeRects: Rectangle[] = []; public rects: ImageRect[] = []; private verticalExpand: boolean = false; private stage: Rectangle; constructor ( public index:number, public maxWidth: number = EDGE_MAX_VALUE, public maxHeight: number = EDGE_MAX_VALUE, public border: number = 0, public padding: number = 0, public options: IOption = { smart: true, pot: true, square: true } ) { super(); this.width = this.options.smart ? 0 : maxWidth; this.height = this.options.smart ? 0 : maxHeight; this.freeRects.push(new Rectangle(border, border, this.maxWidth + this.padding*2 - this.border, this.maxHeight + this.padding*2 - this.border)); this.stage = new Rectangle(0, 0, this.width, this.height); } public add (rect:ImageRect): boolean { var PAD = this.padding * 2; var width:number = rect.width; var height:number = rect.height; let node: Rectangle | undefined = this.findNode(width + PAD, height + PAD); if (node) { this.updateBinSize(node); let numRectToProcess = this.freeRects.length; let i: number = 0; while (i < numRectToProcess) { if (this.splitNode(this.freeRects[i], node)) { this.freeRects.splice(i, 1); numRectToProcess--; i--; } i++; } this.pruneFreeList(); this.verticalExpand = this.width > this.height ? true : false; rect.x = node.x; rect.y = node.y; this.pushRect(rect, false); return true; } else if (!this.verticalExpand) { if (this.updateBinSize(new Rectangle(this.width + PAD, 0, width + this.padding, height + PAD)) || this.updateBinSize(new Rectangle(0, this.height + PAD, width + PAD, height + PAD))) { return this.add(rect); } } else { if (this.updateBinSize(new Rectangle( 0, this.height + PAD, width + PAD, height + PAD )) || this.updateBinSize(new Rectangle( this.width + PAD, 0, width + PAD, height + PAD ))) { return this.add(rect); } } return undefined; } /* public add (width: number, height: number, data: any): Rectangle | undefined { let node: Rectangle | undefined = this.findNode(width + this.padding, height + this.padding); if (node) { this.updateBinSize(node); let numRectToProcess = this.freeRects.length; let i: number = 0; while (i < numRectToProcess) { if (this.splitNode(this.freeRects[i], node)) { this.freeRects.splice(i, 1); numRectToProcess--; i--; } i++; } this.pruneFreeList(); this.verticalExpand = this.width > this.height ? true : false; let rect: Rectangle = new Rectangle(node.x, node.y, width, height); rect.data = data; this.rects.push(rect); return rect; } else if (!this.verticalExpand) { if (this.updateBinSize(new Rectangle(this.width + this.padding, 0, width + this.padding, height + this.padding)) || this.updateBinSize(new Rectangle(0, this.height + this.padding, width + this.padding, height + this.padding))) { return this.add(width, height, data); } } else { if (this.updateBinSize(new Rectangle( 0, this.height + this.padding, width + this.padding, height + this.padding )) || this.updateBinSize(new Rectangle( this.width + this.padding, 0, width + this.padding, height + this.padding ))) { return this.add(width, height, data); } } return undefined; } */ private findNode (width: number, height: number): Rectangle | undefined { let score: number = Number.MAX_VALUE; let areaFit: number; let r: Rectangle; let bestNode: Rectangle | undefined; for (let i in this.freeRects) { r = this.freeRects[i]; if (r.width >= width && r.height >= height) { areaFit = r.width * r.height - width * height; if (areaFit < score) { // bestNode.x = r.x; // bestNode.y = r.y; // bestNode.width = width; // bestNode.height = height; bestNode = new Rectangle(r.x, r.y, width, height); score = areaFit; } } } return bestNode; } private splitNode (freeRect: Rectangle, usedNode: Rectangle): boolean { // Test if usedNode intersect with freeRect if (!freeRect.collide(usedNode)) return false; // Do vertical split if (usedNode.x < freeRect.x + freeRect.width && usedNode.x + usedNode.width > freeRect.x) { // New node at the top side of the used node if (usedNode.y > freeRect.y && usedNode.y < freeRect.y + freeRect.height) { let newNode: Rectangle = new Rectangle(freeRect.x, freeRect.y, freeRect.width, usedNode.y - freeRect.y); this.freeRects.push(newNode); } // New node at the bottom side of the used node if (usedNode.y + usedNode.height < freeRect.y + freeRect.height) { let newNode = new Rectangle( freeRect.x, usedNode.y + usedNode.height, freeRect.width, freeRect.y + freeRect.height - (usedNode.y + usedNode.height) ); this.freeRects.push(newNode); } } // Do Horizontal split if (usedNode.y < freeRect.y + freeRect.height && usedNode.y + usedNode.height > freeRect.y) { // New node at the left side of the used node. if (usedNode.x > freeRect.x && usedNode.x < freeRect.x + freeRect.width) { let newNode = new Rectangle(freeRect.x, freeRect.y, usedNode.x - freeRect.x, freeRect.height); this.freeRects.push(newNode); } // New node at the right side of the used node. if (usedNode.x + usedNode.width < freeRect.x + freeRect.width) { let newNode = new Rectangle( usedNode.x + usedNode.width, freeRect.y, freeRect.x + freeRect.width - (usedNode.x + usedNode.width), freeRect.height ); this.freeRects.push(newNode); } } return true; } private pruneFreeList () { // Go through each pair of freeRects and remove any rects that is redundant let i: number = 0; let j: number = 0; let len: number = this.freeRects.length; while (i < len) { j = i + 1; let tmpRect1 = this.freeRects[i]; while (j < len) { let tmpRect2 = this.freeRects[j]; if (tmpRect2.contain(tmpRect1)) { this.freeRects.splice(i, 1); i--; len--; break; } if (tmpRect1.contain(tmpRect2)) { this.freeRects.splice(j, 1); j--; len--; } j++; } i++; } } private updateBinSize (node: Rectangle): boolean { if (!this.options.smart) return false; if (this.stage.contain(node)) return false; var PAD = this.padding * 2; let tmpWidth: number = Math.max(this.width, node.x + node.width - PAD); let tmpHeight: number = Math.max(this.height, node.y + node.height - PAD); if (this.options.pot) { tmpWidth = Math.pow(2, Math.ceil(Math.log(tmpWidth) * Math.LOG2E)); tmpHeight = Math.pow(2, Math.ceil(Math.log(tmpHeight) * Math.LOG2E)); } if (this.options.square) { tmpWidth = tmpHeight = Math.max(tmpWidth, tmpHeight); } if (tmpWidth > this.maxWidth + PAD || tmpHeight > this.maxHeight + PAD) { return false; } this.expandFreeRects(tmpWidth + PAD, tmpHeight + PAD); this.width = this.stage.width = tmpWidth; this.height = this.stage.height = tmpHeight; return true; } private expandFreeRects (width: number, height: number) { var PAD = this.padding * 2; this.freeRects.forEach((freeRect, index) => { if (freeRect.x + freeRect.width >= Math.min(this.width + PAD, width)) { freeRect.width = width - freeRect.x; } if (freeRect.y + freeRect.height >= Math.min(this.height + PAD, height)) { freeRect.height = height - freeRect.y; } }, this); this.freeRects.push(new Rectangle(this.width + PAD, 0, width - this.width - PAD, height)); this.freeRects.push(new Rectangle(0, this.height + PAD, width, height - this.height - PAD)); this.freeRects.forEach((freeRect, index) => { if (freeRect.width <= 0 || freeRect.height <= 0) { this.freeRects.splice(index, 1); } }, this); this.pruneFreeList(); } }
the_stack
import {fakeAsync, TestBed, tick} from '@angular/core/testing'; import {MatDialog} from '@angular/material/dialog'; import {MatSnackBar} from '@angular/material/snack-bar'; import {BrowserDynamicTestingModule, platformBrowserDynamicTesting} from '@angular/platform-browser-dynamic/testing'; import {NoopAnimationsModule} from '@angular/platform-browser/animations'; import * as d3 from 'd3'; import {BehaviorSubject, of} from 'rxjs'; import {CollectionParameters, CpuIdleWaitLayer, CpuInterval, CpuIntervalCollection, CpuRunningLayer, CpuWaitQueueLayer, Interval, Layer, ThreadInterval} from '../models'; import * as services from '../models/render_data_services'; import {LocalMetricsService} from '../services/metrics_service'; import {LocalRenderDataService, RenderDataService} from '../services/render_data_service'; import {ShortcutId, ShortcutService} from '../services/shortcut_service'; import {triggerShortcut} from '../services/shortcut_service_test'; import {SystemTopology, Viewport} from '../util'; import * as clipboard from '../util/clipboard'; import {Heatmap} from './heatmap'; import {HeatmapModule} from './heatmap_module'; import {DialogChooseThreadLayer} from './intervals_layer'; const TICK_DURATION = 1000; const START_TIME = 5e8; const END_TIME = 2.5e+9; const CPU_COUNT = 72; const CPUS: number[] = []; for (let i = 0; i < CPU_COUNT; i++) { CPUS.push(i); } try { TestBed.initTestEnvironment( BrowserDynamicTestingModule, platformBrowserDynamicTesting()); } catch { // Ignore exceptions when calling it multiple times. } function setupHeatmap(component: Heatmap) { component.parameters = new BehaviorSubject<CollectionParameters|undefined>(mockParameters()); component.systemTopology = mockTopology(); component.preview = new BehaviorSubject<Interval|undefined>(undefined); component.layers = new BehaviorSubject<Array<BehaviorSubject<Layer>>>([ new BehaviorSubject(new CpuRunningLayer() as unknown as Layer), new BehaviorSubject(new CpuIdleWaitLayer() as unknown as Layer), new BehaviorSubject(new CpuWaitQueueLayer() as unknown as Layer), ]); component.viewport = new BehaviorSubject<Viewport>(new Viewport()); component.cpuFilter = new BehaviorSubject<string>(''); component.maxIntervalCount = new BehaviorSubject<number>(5000); component.showMigrations = new BehaviorSubject<boolean>(true); component.showSleeping = new BehaviorSubject<boolean>(true); } function addMockIntervals(component: Heatmap): CpuIntervalCollection[] { const params = mockParameters(); const runningThreads = [ { thread: { pid: 0, command: '<h3>hey!</h3>', priority: 120, }, duration: (params.endTimeNs - params.startTimeNs) / 2, state: services.ThreadState.RUNNING_STATE, droppedEventIDs: [], includesSyntheticTransitions: false }, { thread: { pid: 1, command: 'test2', priority: 100, }, duration: (params.endTimeNs - params.startTimeNs) / 2, state: services.ThreadState.RUNNING_STATE, droppedEventIDs: [], includesSyntheticTransitions: false }, ]; const waitingThreads = [ { thread: { pid: 2, command: '<script>expect("xss").toBeNull()</script>', priority: 120, }, duration: (params.endTimeNs - params.startTimeNs), state: services.ThreadState.WAITING_STATE, droppedEventIDs: [], includesSyntheticTransitions: false }, { thread: { pid: 3, command: 'test4', priority: 80, }, duration: (params.endTimeNs - params.startTimeNs), state: services.ThreadState.WAITING_STATE, droppedEventIDs: [], includesSyntheticTransitions: false }, ]; const cpuIntervalCollection = [ new CpuIntervalCollection( 0, [ new CpuInterval( params, 0, params.startTimeNs, params.endTimeNs, runningThreads, waitingThreads, ), ], ), ]; component.setCpuIntervals(cpuIntervalCollection); return cpuIntervalCollection; } function mockParameters(): CollectionParameters { return new CollectionParameters('foo', CPUS, START_TIME, END_TIME); } function mockTopology(): SystemTopology { return new SystemTopology(CPUS); } function createHoverEvent(xPos: number, yPos: number): MouseEvent { const event = document.createEvent('MouseEvent'); event.initMouseEvent( 'mouseover', true, true, window, 0, 0, 0, xPos, yPos, false, false, false, false, 0, null); return event; } function isTooltipBelow(tooltipRect: ClientRect | DOMRect, yPos: number) { // Since the tooltip is offset from the cursor, the Y position of the cursor // will always be between the top and bottom edges of the tooltip. So, to // determine if the tooltip is below the cursor, we will do a relative // comparison of the distance to the top and bottom edges. return Math.abs(tooltipRect.top - yPos) < Math.abs(tooltipRect.bottom - yPos); } function isTooltipOnRight(tooltipRect: ClientRect|DOMRect, xPos: number) { return tooltipRect.left > xPos; } describe('Heatmap', () => { beforeEach(async () => { document.body.style.width = '500px'; document.body.style.height = '500px'; await TestBed .configureTestingModule({ imports: [ HeatmapModule, NoopAnimationsModule, ], providers: [ {provide: 'MetricsService', useClass: LocalMetricsService}, {provide: 'RenderDataService', useClass: LocalRenderDataService}, {provide: 'ShortcutService', useClass: ShortcutService}, ], }) .compileComponents(); }); it('should create', () => { const fixture = TestBed.createComponent(Heatmap); const component = fixture.componentInstance; setupHeatmap(component); fixture.detectChanges(); expect(component).toBeTruthy(); }); it('should render CPU intervals', () => { const fixture = TestBed.createComponent(Heatmap); const component = fixture.componentInstance; setupHeatmap(component); fixture.detectChanges(); const element = fixture.nativeElement; const layers = component.layers.value; expect(layers.length).toEqual(3); expect(layers[0].value.intervals.length).toBeGreaterThan(1); const renderedLayers = element.querySelectorAll('.layersGroup'); expect(renderedLayers.length).toEqual(3); // Check layers render in reverse order, with expected interval count drawn let intervalCount = renderedLayers[0].querySelectorAll('rect').length; expect(intervalCount).toEqual(layers[2].value.intervals.length); intervalCount = renderedLayers[2].querySelectorAll('rect').length; expect(intervalCount).toEqual(layers[0].value.intervals.length); // TODO(sainsley): Check base intervals set }); it('should open a dialog when clicking on a merged interval', async () => { const fixture = TestBed.createComponent(Heatmap); const component = fixture.componentInstance; setupHeatmap(component); component.ngOnInit(); fixture.detectChanges(); await fixture.whenStable(); const mockIntervals = addMockIntervals(component); const runningThreads = mockIntervals[0].running[0].running; fixture.detectChanges(); await fixture.whenStable(); const dialog = TestBed.get(MatDialog) as MatDialog; const dialogSpy = spyOn(dialog, 'open').and.callThrough(); const event = document.createEvent('SVGEvents'); event.initEvent('click', true, true); (document.querySelector('.interval') as SVGElement).dispatchEvent(event); await fixture.whenStable(); expect(dialogSpy).toHaveBeenCalledTimes(1); expect(dialogSpy).toHaveBeenCalledWith( DialogChooseThreadLayer, {data: runningThreads}); }); it('should not open a dialog when clicking on a non-merged interval', async () => { const fixture = TestBed.createComponent(Heatmap); const component = fixture.componentInstance; setupHeatmap(component); component.ngOnInit(); fixture.detectChanges(); await fixture.whenStable(); const mockIntervals = addMockIntervals(component); const runningThreads = mockIntervals[0].running[0].running; delete runningThreads[1]; fixture.detectChanges(); await fixture.whenStable(); const dialog = TestBed.get(MatDialog) as MatDialog; const dialogSpy = spyOn(dialog, 'open').and.callThrough(); const event = document.createEvent('SVGEvents'); event.initEvent('click', true, true); (document.querySelector('.interval') as SVGElement).dispatchEvent(event); await fixture.whenStable(); expect(dialogSpy).not.toHaveBeenCalled(); }); it('should create a tooltip on hover', async () => { const fixture = TestBed.createComponent(Heatmap); const component = fixture.componentInstance; setupHeatmap(component); component.ngOnInit(); fixture.detectChanges(); await fixture.whenStable(); addMockIntervals(component); fixture.detectChanges(); await fixture.whenStable(); const event = document.createEvent('SVGEvents'); event.initEvent('mouseover', true, true); (document.querySelector('.interval') as SVGElement).dispatchEvent(event); await fixture.whenStable(); fixture.detectChanges(); await fixture.whenStable(); const tooltip = document.querySelector('.tooltip') as HTMLElement; expect(tooltip.innerText) .toBe( 'Running: \n' + ' (50.0%) 0:<h3>hey!</h3> (P:120)\n' + ' (50.0%) 1:test2 (P:100)\n' + 'CPU: 0\n' + 'Start Time: 500 msec\n' + 'End Time: 2.5 sec\n' + 'Duration: 2 sec\n' + 'Idle Time: (0.00%) 0 nsec\n' + 'Running Time: (100%) 2 sec\n' + 'Waiting Time: (200%) 4 sec\n' + 'Waiting PID Count: 2\n' + 'Waiting: \n' + ' (100%) 2:<script>expect("xss").toBeNull()</script> (P:120)\n' + ' (100%) 3:test4 (P:80)'); }); it('should place tooltip below and to the right by default', async () => { const fixture = TestBed.createComponent(Heatmap); const component = fixture.componentInstance; setupHeatmap(component); component.ngOnInit(); // Expand the container element to allow room for tooltip to go in any // direction const rootElement = (fixture.nativeElement as HTMLElement); rootElement.style.height = '1000px'; rootElement.style.width = '1000px'; addMockIntervals(component); fixture.detectChanges(); await fixture.whenStable(); const interval = document.querySelector('.interval') as SVGElement; const tooltip = document.querySelector('.tooltip') as HTMLElement; // Hover in the middle of the screen, check that tooltip is below and to the // right const yPos = Math.floor(rootElement.getBoundingClientRect().bottom / 2); const xPos = Math.floor(rootElement.getBoundingClientRect().right / 2); interval.dispatchEvent(createHoverEvent(xPos, yPos)); await fixture.whenStable(); fixture.detectChanges(); await fixture.whenStable(); const tooltipRect = tooltip.getBoundingClientRect(); expect(isTooltipBelow(tooltipRect, yPos)).toBe(true); expect(isTooltipOnRight(tooltipRect, xPos)).toBe(true); }); it(`should place tooltip properly at the corners of the container`, async () => { const fixture = TestBed.createComponent(Heatmap); const component = fixture.componentInstance; setupHeatmap(component); component.ngOnInit(); const rootElement = (fixture.nativeElement as HTMLElement); rootElement.style.height = '1000px'; rootElement.style.width = '1000px'; addMockIntervals(component); fixture.detectChanges(); await fixture.whenStable(); const containerTop = rootElement.getBoundingClientRect().top; const containerBottom = rootElement.getBoundingClientRect().bottom; const containerLeft = rootElement.getBoundingClientRect().left; const containerRight = rootElement.getBoundingClientRect().right; const testCases = [ { cornerLocation: 'top left', hoverCoordinate: {x: containerLeft, y: containerTop}, expectedTooltipPlacement: {below: true, right: true} }, { cornerLocation: 'top right', hoverCoordinate: {x: containerRight, y: containerTop}, expectedTooltipPlacement: {below: true, right: false} }, { cornerLocation: 'bottom right', hoverCoordinate: {x: containerRight, y: containerBottom}, expectedTooltipPlacement: {below: false, right: false} }, { cornerLocation: 'bottom left', hoverCoordinate: {x: containerLeft, y: containerBottom}, expectedTooltipPlacement: {below: false, right: true} }, ]; // Simulate each hover and verify the resulting tooltip locations in turn for (const testCase of testCases) { const cursorX = testCase.hoverCoordinate.x; const cursorY = testCase.hoverCoordinate.y; const interval = document.querySelector('.interval') as SVGElement; interval.dispatchEvent(createHoverEvent(cursorX, cursorY)); await fixture.whenStable(); fixture.detectChanges(); await fixture.whenStable(); const tooltip = document.querySelector('.tooltip') as HTMLElement; const tooltipRect = tooltip.getBoundingClientRect(); expect(isTooltipBelow(tooltipRect, cursorY)) .toBe( testCase.expectedTooltipPlacement.below, `Incorrect vertical placement for corner location: ${ testCase.cornerLocation}`); expect(isTooltipOnRight(tooltipRect, cursorX)) .toBe( testCase.expectedTooltipPlacement.right, `Incorrect horizontal placement for corner location: ${ testCase.cornerLocation}`); } }); it('should fetch PID intervals on thread layer added', async () => { const fixture = TestBed.createComponent(Heatmap); const component = fixture.componentInstance; setupHeatmap(component); fixture.detectChanges(); const element = fixture.nativeElement; const layers = component.layers.value; const green = 'rgb(0, 255, 0)'; const newLayer = new BehaviorSubject<Layer>( new Layer('thread_foo', 'Thread', [1234], green)); layers.push(newLayer); component.layers.next(layers); await fixture.whenStable(); const fetchedIntervalCount = newLayer.value.intervals.length; expect(fetchedIntervalCount).toBe(1296); const renderedLayers = element.querySelectorAll('.layersGroup'); expect(renderedLayers.length).toEqual(4); // Query interval count for newest (top-most) layer const drawnIntervals = renderedLayers[0].querySelectorAll('rect'); expect(fetchedIntervalCount).toEqual(drawnIntervals.length); for (const interval of drawnIntervals) { expect(d3.select(interval).style('fill')).toEqual(green); expect(Number(d3.select(interval).attr('rx'))).toBeGreaterThan(0); } }); it('should make only one request when multiple PID layers are added at once', async () => { const fixture = TestBed.createComponent(Heatmap); const component = fixture.componentInstance; setupHeatmap(component); fixture.detectChanges(); const renderDataService = TestBed.get('RenderDataService') as RenderDataService; const requestSpy = spyOn(renderDataService, 'getPidIntervals').and.callThrough(); const layers = component.layers.value; layers.push(new BehaviorSubject<Layer>( new Layer('thread_foo', 'Thread', [1234], 'rgb(0, 255, 0)'))); layers.push(new BehaviorSubject<Layer>( new Layer('thread_bar', 'Thread', [4321], 'rgb(255, 0, 0)'))); component.layers.next(layers); await fixture.whenStable(); expect(requestSpy).toHaveBeenCalledTimes(1); }); it('should fetch sched events on event layer added', () => { const fixture = TestBed.createComponent(Heatmap); const component = fixture.componentInstance; setupHeatmap(component); fixture.detectChanges(); const element = fixture.nativeElement; const layers = component.layers.value; const red = 'rgb(255, 0, 0)'; const newLayer = new BehaviorSubject<Layer>( new Layer('event_foo', 'SchedEvent', [], red)); layers.push(newLayer); component.layers.next(layers); const fetchedIntervalCount = newLayer.value.intervals.length; expect(fetchedIntervalCount).toBeGreaterThan(0); const renderedLayers = element.querySelectorAll('.layersGroup'); expect(renderedLayers.length).toEqual(4); // Query interval count for newest (top-most) layer const drawnIntervals = renderedLayers[0].querySelectorAll('rect'); expect(fetchedIntervalCount).toEqual(drawnIntervals.length); for (const interval of drawnIntervals) { expect(d3.select(interval).style('fill')).toEqual(red); expect(Number(d3.select(interval).attr('rx'))).toEqual(0); } }); it('should reuse base intervals when fully zoomed out', fakeAsync(() => { const fixture = TestBed.createComponent(Heatmap); const component = fixture.componentInstance; const renderService = component.renderDataService; setupHeatmap(component); fixture.detectChanges(); const spy = spyOn(renderService, 'getCpuIntervals').and.callThrough(); const viewport = new Viewport(); viewport.left = 0.25; viewport.right = 0.75; component.viewport.next(viewport); tick(TICK_DURATION); // Should fetch new intervals on zoom in expect(viewport.width).toBe(0.5); expect(renderService.getCpuIntervals).toHaveBeenCalled(); spy.calls.reset(); component.viewport.next(new Viewport()); // Should fetch new intervals on zoom out to default tick(TICK_DURATION); expect(renderService.getCpuIntervals).not.toHaveBeenCalled(); })); it('should reset viewport height on CPU filter change', fakeAsync(() => { const fixture = TestBed.createComponent(Heatmap); const component = fixture.componentInstance; const renderService = component.renderDataService; const spy = spyOn(renderService, 'getCpuIntervals').and.callThrough(); setupHeatmap(component); fixture.detectChanges(); tick(TICK_DURATION); spy.calls.reset(); const viewport = new Viewport(); // First, zoom in viewport.left = 0.25; viewport.right = 0.75; viewport.top = 0.25; viewport.bottom = 0.75; component.viewport.next(viewport); tick(TICK_DURATION); expect(spy.calls.count()).toBe(1); expect(viewport.width).toBe(0.5); // Then set a CPU filter component.cpuFilter.next('5-10'); tick(TICK_DURATION); // Expect viewport to reset expect(spy.calls.count()).toBe(2); const newViewport = component.viewport.value; expect(newViewport.left).toBe(viewport.left); expect(newViewport.right).toBe(viewport.right); expect(newViewport.height).toBe(1.0); })); it('should update d3 zoom transform on viewport update', fakeAsync(() => { const fixture = TestBed.createComponent(Heatmap); const component = fixture.componentInstance; const renderService = component.renderDataService; const spy = spyOn(renderService, 'getCpuIntervals').and.callThrough(); setupHeatmap(component); fixture.detectChanges(); tick(TICK_DURATION); spy.calls.reset(); const viewport = new Viewport(); viewport.left = 0.25; viewport.right = 0.75; component.viewport.next(viewport); tick(TICK_DURATION); expect(spy.calls.count()).toBe(1); expect(viewport.width).toBe(0.5); expect(d3.select(component.zoomGroup.nativeElement).attr('transform')) .toBe('translate(-250, 0)'); })); it('should fetch new intervals on max interval count change', fakeAsync(() => { const maxIntervalCount = 100; const fixture = TestBed.createComponent(Heatmap); const component = fixture.componentInstance; const renderService = component.renderDataService; const spy = spyOn(renderService, 'getCpuIntervals').and.callThrough(); setupHeatmap(component); fixture.detectChanges(); tick(TICK_DURATION); spy.calls.reset(); // Update max interval count -- expect new intervals to be fetched component.maxIntervalCount.next(maxIntervalCount); tick(TICK_DURATION); expect(spy.calls.count()).toBe(1); // TODO(sainsley): Check that base intervals update const intervals = component.cpuRunLayer.value.intervals; expect(maxIntervalCount).toBeGreaterThan(intervals.length); })); it('should update y zoom on shift-zoom', fakeAsync(() => { const fixture = TestBed.createComponent(Heatmap); const component = fixture.componentInstance; setupHeatmap(component); fixture.detectChanges(); const transform = d3.zoomIdentity.scale(2); expect(transform.k).toBe(2); component.maybeUpdateViewport(transform, true); tick(TICK_DURATION); const viewport = component.viewport.value; expect(viewport.height).toBe(0.5); expect(viewport.width).toBe(0.5); })); it('should not update y on default zoom-out or zoom-in', fakeAsync(() => { const fixture = TestBed.createComponent(Heatmap); const component = fixture.componentInstance; setupHeatmap(component); const renderService = component.renderDataService; const spy = spyOn(renderService, 'getCpuIntervals').and.callThrough(); fixture.detectChanges(); tick(TICK_DURATION); spy.calls.reset(); let transform = d3.zoomIdentity.scale(2); expect(transform.k).toBe(2); // Zoom in just x component.maybeUpdateViewport(transform, false); tick(TICK_DURATION); expect(spy.calls.count()).toBe(1); const viewport = component.viewport.value; expect(viewport.width).toBe(0.5); expect(viewport.height).toBe(1.0); transform = d3.zoomIdentity.scale(1.25); // Zoom out in just x component.maybeUpdateViewport(transform, false); tick(TICK_DURATION); expect(spy.calls.count()).toBe(2); expect(viewport.width).toBe(0.8); expect(viewport.height).toBe(1.0); })); it('should update y on default zoom-out when viewport width == 1', fakeAsync(() => { const fixture = TestBed.createComponent(Heatmap); const component = fixture.componentInstance; setupHeatmap(component); const renderService = component.renderDataService; const spy = spyOn(renderService, 'getCpuIntervals').and.callThrough(); fixture.detectChanges(); tick(TICK_DURATION); spy.calls.reset(); let transform = d3.zoomIdentity.scale(2); expect(transform.k).toBe(2); component.maybeUpdateViewport(transform, true); tick(TICK_DURATION); expect(spy.calls.count()).toBe(1); const viewport = component.viewport.value; // Both should zoom in both axes on shift expect(viewport.width).toBe(0.5); expect(viewport.height).toBe(0.5); transform = d3.zoomIdentity.scale(1); component.maybeUpdateViewport(transform, false); tick(TICK_DURATION); expect(spy.calls.count()).toBe(2); // Only x should zoom out w/o shift expect(viewport.width).toBe(1.0); expect(viewport.height).toBe(0.5); transform = d3.zoomIdentity.scale(0.5); component.maybeUpdateViewport(transform, false); tick(TICK_DURATION); // Only y should zoom out with x maximized expect(spy.calls.count()).toBe(2); expect(viewport.width).toBe(1.0); expect(viewport.height).toBe(1.0); })); it('should pan in x when viewport width is less than 1 and zoom delta is 0', fakeAsync(() => { const fixture = TestBed.createComponent(Heatmap); const component = fixture.componentInstance; setupHeatmap(component); fixture.detectChanges(); const renderService = component.renderDataService; const spy = spyOn(renderService, 'getCpuIntervals').and.callThrough(); tick(TICK_DURATION); spy.calls.reset(); // First zoom let transform = d3.zoomIdentity.scale(2); expect(transform.k).toBe(2); component.maybeUpdateViewport(transform, false); tick(TICK_DURATION); expect(spy.calls.count()).toBe(1); const viewport = component.viewport.value; expect(viewport.height).toBe(1.0); expect(viewport.width).toBe(0.5); expect(viewport.left).toBe(0); // Trigger pan transform = d3.zoomIdentity.scale(2).translate(-200, 0); expect(transform.x).toBe(-400); component.maybeUpdateViewport(transform, false); tick(TICK_DURATION); expect(spy.calls.count()).toBe(2); expect(viewport.height).toBe(1.0); expect(viewport.width).toBe(0.5); expect(viewport.left).toBe(0.4); })); it('should pan in y when viewport height is less than 1 and zoom delta is 0', fakeAsync(() => { const fixture = TestBed.createComponent(Heatmap); const component = fixture.componentInstance; setupHeatmap(component); fixture.detectChanges(); const renderService = component.renderDataService; const spy = spyOn(renderService, 'getCpuIntervals').and.callThrough(); tick(TICK_DURATION); spy.calls.reset(); // First zoom let transform = d3.zoomIdentity.scale(2); expect(transform.k).toBe(2); component.maybeUpdateViewport(transform, true); tick(TICK_DURATION); expect(spy.calls.count()).toBe(1); const viewport = component.viewport.value; expect(viewport.height).toBe(0.5); expect(viewport.width).toBe(0.5); expect(viewport.top).toBe(0); // Trigger pan transform = d3.zoomIdentity.scale(2).translate(0, -200); expect(transform.y).toBe(-400); component.maybeUpdateViewport(transform, false); tick(TICK_DURATION); expect(spy.calls.count()).toBe(2); expect(viewport.height).toBe(0.5); expect(viewport.width).toBe(0.5); expect(viewport.top).toBe(0.4); })); it('should redraw on zoom-in', fakeAsync(() => { const fixture = TestBed.createComponent(Heatmap); const component = fixture.componentInstance; setupHeatmap(component); fixture.detectChanges(); const renderService = component.renderDataService; const spy = spyOn(renderService, 'getCpuIntervals').and.callThrough(); tick(TICK_DURATION); spy.calls.reset(); const element = fixture.nativeElement; let renderedLayers = element.querySelectorAll('.layersGroup'); const preZoomIntervalCount = renderedLayers[2].querySelectorAll('rect').length; // Zoom const viewport = new Viewport(); viewport.left = 0.25; viewport.right = 0.75; component.viewport.next(viewport); tick(TICK_DURATION); expect(spy.calls.count()).toBe(1); renderedLayers = element.querySelectorAll('.layersGroup'); const zoomedIntervalCount = renderedLayers[2].querySelectorAll('rect').length; expect(zoomedIntervalCount).not.toEqual(preZoomIntervalCount); })); it('should not zoom out when viewport width and height are 1', fakeAsync(() => { const fixture = TestBed.createComponent(Heatmap); const component = fixture.componentInstance; setupHeatmap(component); fixture.detectChanges(); const renderService = component.renderDataService; const spy = spyOn(renderService, 'getCpuIntervals').and.callThrough(); tick(TICK_DURATION); spy.calls.reset(); // Attempt zoom out const transform = d3.zoomIdentity.scale(0.5); component.maybeUpdateViewport(transform, true); tick(TICK_DURATION); expect(spy.calls.count()).toBe(0); const viewport = component.viewport.value; expect(viewport.height).toBe(1.0); expect(viewport.top).toBe(0.0); expect(viewport.width).toBe(1.0); expect(viewport.left).toBe(0.0); })); it('should not zoom in x when viewport is at minimum width', fakeAsync(() => { const fixture = TestBed.createComponent(Heatmap); const component = fixture.componentInstance; setupHeatmap(component); fixture.detectChanges(); const renderService = component.renderDataService; const spy = spyOn(renderService, 'getCpuIntervals').and.callThrough(); tick(TICK_DURATION); spy.calls.reset(); const maxZoomX = component.domainSize / 1E5; // Initial zoom in let transform = d3.zoomIdentity.scale(maxZoomX); component.maybeUpdateViewport(transform, false); tick(TICK_DURATION); expect(spy.calls.count()).toBe(1); const viewport = component.viewport.value; expect(viewport.width).toBe(0.00005); // Attempt zoom past min transform = d3.zoomIdentity.scale(2 * maxZoomX); component.maybeUpdateViewport(transform, false); tick(TICK_DURATION); expect(spy.calls.count()).toBe(1); expect(viewport.width).toBe(0.00005); })); it('should not zoom in y when viewport is at minimum height', fakeAsync(() => { const fixture = TestBed.createComponent(Heatmap); const component = fixture.componentInstance; setupHeatmap(component); fixture.detectChanges(); const renderService = component.renderDataService; const spy = spyOn(renderService, 'getCpuIntervals').and.callThrough(); tick(TICK_DURATION); spy.calls.reset(); const maxZoomY = CPU_COUNT; // Initial zoom in let transform = d3.zoomIdentity.scale(maxZoomY); component.maybeUpdateViewport(transform, true); tick(TICK_DURATION); expect(spy.calls.count()).toBe(1); const viewport = component.viewport.value; expect(viewport.height).toBe(1 / maxZoomY); expect(viewport.width).toBe(1 / maxZoomY); // Attempt zoom past min transform = d3.zoomIdentity.scale(2 * maxZoomY); component.maybeUpdateViewport(transform, true); tick(TICK_DURATION); expect(spy.calls.count()).toBe(2); expect(viewport.height).toBe(1 / maxZoomY); expect(viewport.width).toBe(0.5 / maxZoomY); })); it('should shown loading bar while intervals are pending', fakeAsync(() => { const fixture = TestBed.createComponent(Heatmap); const component = fixture.componentInstance; const element = fixture.nativeElement; const renderService = component.renderDataService; setupHeatmap(component); fixture.detectChanges(); spyOn(renderService, 'getCpuIntervals').and.callFake(() => { expect(component.loading).toBe(true); component.cdr.detectChanges(); expect(element.querySelectorAll('.heatmap-loading').length).toBe(1); return of([]); }); const viewport = new Viewport(); viewport.left = 0.25; viewport.right = 0.75; viewport.top = 0.25; viewport.bottom = 0.75; component.viewport.next(viewport); tick(TICK_DURATION); expect(element.querySelectorAll('.heatmap-loading').length).toBe(0); })); it('should not move the center line on zoom', fakeAsync(() => { const fixture = TestBed.createComponent(Heatmap); const component = fixture.componentInstance; setupHeatmap(component); fixture.detectChanges(); const renderService = component.renderDataService; const spy = spyOn(renderService, 'getCpuIntervals').and.callThrough(); tick(TICK_DURATION); spy.calls.reset(); const viewport = component.viewport.value; const transform = d3.zoomIdentity.scale(2).translate(-viewport.chartWidthPx / 4, 0); component.maybeUpdateViewport(transform, false); tick(TICK_DURATION); expect(spy.calls.count()).toBe(1); expect(viewport.width).toBe(0.5); expect(viewport.left).toBe(0.25); })); it('should arrange waiting pid queues such that no two overlap', () => { const fixture = TestBed.createComponent(Heatmap); const component = fixture.componentInstance; setupHeatmap(component); fixture.detectChanges(); const startTime = START_TIME; const duration = END_TIME - START_TIME; const layer1 = new Layer('thread_foo', 'Thread', [1234], '#ff0000'); const layer2 = new Layer('thread_bar', 'Thread', [3456], '#00ff00'); const layer3 = new Layer('thread_foo_bar', 'Thread', [4567], '#0000ff'); const layers = [layer1, layer2, layer3]; // Create three layers each with a few intervals w/ waiting // One full width, one that overlaps with 1/3 of intervals, and one that // overlaps with both const durations = [ [{start: startTime, end: startTime + duration}], [ {start: startTime, end: startTime + duration / 3}, {start: startTime + 2 * duration / 3, end: startTime + duration} ], [{start: startTime + 3 * duration / 4, end: startTime + duration}] ]; for (let i = 0; i < layers.length; i++) { for (let ii = 0; ii < durations[i].length; ii++) { const duration = durations[i][ii]; const layer = layers[i]; layer.intervals.push(new ThreadInterval( mockParameters(), 0, duration.start, duration.end, layer.ids[0], layer.name, [{ thread: { pid: 2, command: 'waiter', priority: 120, }, duration: duration.end - duration.start, state: services.ThreadState.WAITING_STATE, droppedEventIDs: [], includesSyntheticTransitions: false }])); } } component.arrangeWaitingPids(layers); const expectations = [ [{offset: 0, count: 4}], [{offset: 1, count: 2}, {offset: 1, count: 3}], [{offset: 2, count: 3}] ]; for (let i = 0; i < layers.length; i++) { for (let ii = 0; ii < expectations[i].length; ii++) { const expectation = expectations[i][ii]; const interval = layers[i].intervals[ii] as ThreadInterval; expect(interval.queueOffset).toBe(expectation.offset); expect(interval.queueCount).toBe(expectation.count); } } }); it('should register copy to clipboard handler', async () => { const fixture = TestBed.createComponent(Heatmap); const component = fixture.componentInstance; setupHeatmap(component); component.ngOnInit(); addMockIntervals(component); await fixture.whenStable(); fixture.detectChanges(); // Trigger a tooltip const event = document.createEvent('SVGEvents'); event.initEvent('mouseover', true, true); (document.querySelector('.interval') as SVGElement).dispatchEvent(event); await fixture.whenStable(); const snackBar = TestBed.get(MatSnackBar) as MatSnackBar; const snackBarSpy = spyOn(snackBar, 'open'); const shortcutId = ShortcutId.COPY_TOOLTIP; const copyToClipboardSpy = spyOn(clipboard, 'copyToClipboard').and.returnValue(true); const shortcutService = fixture.debugElement.injector.get(ShortcutService); const shortcut = shortcutService.getShortcuts()[shortcutId]; expect(shortcut.isEnabled).toBe(true); triggerShortcut(shortcut); expect(copyToClipboardSpy).toHaveBeenCalledTimes(1); const tooltip = document.querySelector('.tooltip') as HTMLElement; expect(copyToClipboardSpy) .toHaveBeenCalledWith(tooltip.innerText); const snackBarMessage = snackBarSpy.calls.mostRecent().args[0]; expect(snackBarMessage).toBe('Tooltip copied to clipboard'); // Verify that shortcut is deregistered component.ngOnDestroy(); const shortcutAfterDestroy = shortcutService.getShortcuts()[shortcutId]; expect(shortcutAfterDestroy.isEnabled).toBe(false); }); it('should handle copy to clipboard shortcut error', async () => { const fixture = TestBed.createComponent(Heatmap); const component = fixture.componentInstance; setupHeatmap(component); component.ngOnInit(); addMockIntervals(component); await fixture.whenStable(); fixture.detectChanges(); const event = document.createEvent('SVGEvents'); event.initEvent('mouseover', true, true); (document.querySelector('.interval') as SVGElement).dispatchEvent(event); await fixture.whenStable(); const snackBar = TestBed.get(MatSnackBar) as MatSnackBar; const snackBarSpy = spyOn(snackBar, 'open'); const copyToClipboardSpy = spyOn(clipboard, 'copyToClipboard').and.returnValue(false); const shortcutService = fixture.debugElement.injector.get(ShortcutService); const shortcut = shortcutService.getShortcuts()[ShortcutId.COPY_TOOLTIP]; triggerShortcut(shortcut); expect(copyToClipboardSpy).toHaveBeenCalledTimes(1); const tooltip = document.querySelector('.tooltip') as HTMLElement; expect(copyToClipboardSpy).toHaveBeenCalledWith(tooltip.innerText); const snackBarMessage = snackBarSpy.calls.mostRecent().args[0]; expect(snackBarMessage).toBe('Error copying tooltip to clipboard'); }); it('should register reset viewport shortcut', async () => { const fixture = TestBed.createComponent(Heatmap); const component = fixture.componentInstance; setupHeatmap(component); component.ngOnInit(); addMockIntervals(component); fixture.detectChanges(); await fixture.whenStable(); const shortcutId = ShortcutId.RESET_VIEWPORT; const shortcutService = fixture.debugElement.injector.get(ShortcutService); const shortcut = shortcutService.getShortcuts()[shortcutId]; const viewport = new Viewport(); viewport.left = 0.25; viewport.right = 0.75; component.viewport.next(viewport); expect(shortcut.isEnabled).toBe(true); triggerShortcut(shortcut); const viewportAfter = component.viewport.value; expect(viewportAfter.left).toBe(0); expect(viewportAfter.right).toBe(1); // Verify that shortcut is deregistered component.ngOnDestroy(); const shortcutAfterDestroy = shortcutService.getShortcuts()[shortcutId]; expect(shortcutAfterDestroy.isEnabled).toBe(false); }); it('should register clear CPU filter shortcut', async () => { const fixture = TestBed.createComponent(Heatmap); const component = fixture.componentInstance; setupHeatmap(component); component.ngOnInit(); addMockIntervals(component); fixture.detectChanges(); await fixture.whenStable(); component.cpuFilter.next('1'); const shortcutId = ShortcutId.CLEAR_CPU_FILTER; const shortcutService = fixture.debugElement.injector.get(ShortcutService); const shortcut = shortcutService.getShortcuts()[shortcutId]; triggerShortcut(shortcut); expect(component.cpuFilter.value).toBe(''); // Verify that shortcut is deregistered component.ngOnDestroy(); const shortcutAfterDestroy = shortcutService.getShortcuts()[shortcutId]; expect(shortcutAfterDestroy.isEnabled).toBe(false); }); });
the_stack
import * as GModule from "@gi-types/gmodule"; import * as Gio from "@gi-types/gio"; import * as GObject from "@gi-types/gobject"; import * as GLib from "@gi-types/glib"; export const PIXBUF_FEATURES_H: number; export const PIXBUF_MAJOR: number; export const PIXBUF_MICRO: number; export const PIXBUF_MINOR: number; export const PIXBUF_VERSION: string; export function pixbuf_error_quark(): GLib.Quark; export type PixbufDestroyNotify = (pixels: Uint8Array | string) => void; export type PixbufSaveFunc = (buf: Uint8Array | string) => boolean; export namespace Colorspace { export const $gtype: GObject.GType<Colorspace>; } export enum Colorspace { RGB = 0, } export namespace InterpType { export const $gtype: GObject.GType<InterpType>; } export enum InterpType { NEAREST = 0, TILES = 1, BILINEAR = 2, HYPER = 3, } export namespace PixbufAlphaMode { export const $gtype: GObject.GType<PixbufAlphaMode>; } export enum PixbufAlphaMode { BILEVEL = 0, FULL = 1, } export class PixbufError extends GLib.Error { static $gtype: GObject.GType<PixbufError>; constructor(options: { message: string; code: number }); constructor(copy: PixbufError); // Properties static CORRUPT_IMAGE: number; static INSUFFICIENT_MEMORY: number; static BAD_OPTION: number; static UNKNOWN_TYPE: number; static UNSUPPORTED_OPERATION: number; static FAILED: number; static INCOMPLETE_ANIMATION: number; // Members static quark(): GLib.Quark; } export namespace PixbufRotation { export const $gtype: GObject.GType<PixbufRotation>; } export enum PixbufRotation { NONE = 0, COUNTERCLOCKWISE = 90, UPSIDEDOWN = 180, CLOCKWISE = 270, } export module Pixbuf { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; bits_per_sample: number; bitsPerSample: number; colorspace: Colorspace; has_alpha: boolean; hasAlpha: boolean; height: number; n_channels: number; nChannels: number; pixel_bytes: GLib.Bytes; pixelBytes: GLib.Bytes; pixels: any; rowstride: number; width: number; } } export class Pixbuf extends GObject.Object implements Gio.Icon, Gio.LoadableIcon { static $gtype: GObject.GType<Pixbuf>; constructor(properties?: Partial<Pixbuf.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<Pixbuf.ConstructorProperties>, ...args: any[]): void; // Properties bits_per_sample: number; bitsPerSample: number; colorspace: Colorspace; has_alpha: boolean; hasAlpha: boolean; height: number; n_channels: number; nChannels: number; pixel_bytes: GLib.Bytes; pixelBytes: GLib.Bytes; pixels: any; rowstride: number; width: number; // Constructors static ["new"]( colorspace: Colorspace, has_alpha: boolean, bits_per_sample: number, width: number, height: number ): Pixbuf; static new_from_bytes( data: GLib.Bytes | Uint8Array, colorspace: Colorspace, has_alpha: boolean, bits_per_sample: number, width: number, height: number, rowstride: number ): Pixbuf; static new_from_data( data: Uint8Array | string, colorspace: Colorspace, has_alpha: boolean, bits_per_sample: number, width: number, height: number, rowstride: number, destroy_fn?: PixbufDestroyNotify | null ): Pixbuf; static new_from_file(filename: string): Pixbuf; static new_from_file_at_scale( filename: string, width: number, height: number, preserve_aspect_ratio: boolean ): Pixbuf; static new_from_file_at_size(filename: string, width: number, height: number): Pixbuf; static new_from_inline(data: Uint8Array | string, copy_pixels: boolean): Pixbuf; static new_from_resource(resource_path: string): Pixbuf; static new_from_resource_at_scale( resource_path: string, width: number, height: number, preserve_aspect_ratio: boolean ): Pixbuf; static new_from_stream(stream: Gio.InputStream, cancellable?: Gio.Cancellable | null): Pixbuf; static new_from_stream_at_scale( stream: Gio.InputStream, width: number, height: number, preserve_aspect_ratio: boolean, cancellable?: Gio.Cancellable | null ): Pixbuf; static new_from_stream_finish(async_result: Gio.AsyncResult): Pixbuf; static new_from_xpm_data(data: string[]): Pixbuf; // Members add_alpha(substitute_color: boolean, r: number, g: number, b: number): Pixbuf; apply_embedded_orientation(): Pixbuf; composite( dest: Pixbuf, dest_x: number, dest_y: number, dest_width: number, dest_height: number, offset_x: number, offset_y: number, scale_x: number, scale_y: number, interp_type: InterpType, overall_alpha: number ): void; composite_color( dest: Pixbuf, dest_x: number, dest_y: number, dest_width: number, dest_height: number, offset_x: number, offset_y: number, scale_x: number, scale_y: number, interp_type: InterpType, overall_alpha: number, check_x: number, check_y: number, check_size: number, color1: number, color2: number ): void; composite_color_simple( dest_width: number, dest_height: number, interp_type: InterpType, overall_alpha: number, check_size: number, color1: number, color2: number ): Pixbuf | null; copy(): Pixbuf | null; copy_area( src_x: number, src_y: number, width: number, height: number, dest_pixbuf: Pixbuf, dest_x: number, dest_y: number ): void; copy_options(dest_pixbuf: Pixbuf): boolean; fill(pixel: number): void; flip(horizontal: boolean): Pixbuf | null; get_bits_per_sample(): number; get_byte_length(): number; get_colorspace(): Colorspace; get_has_alpha(): boolean; get_height(): number; get_n_channels(): number; get_option(key: string): string; get_options(): GLib.HashTable<string, string>; get_pixels(): Uint8Array; get_pixels(): Uint8Array; get_rowstride(): number; get_width(): number; new_subpixbuf(src_x: number, src_y: number, width: number, height: number): Pixbuf; read_pixel_bytes(): GLib.Bytes; read_pixels(): number; remove_option(key: string): boolean; rotate_simple(angle: PixbufRotation): Pixbuf | null; saturate_and_pixelate(dest: Pixbuf, saturation: number, pixelate: boolean): void; save_to_bufferv(type: string, option_keys: string[], option_values: string[]): [boolean, Uint8Array]; save_to_callbackv(save_func: PixbufSaveFunc, type: string, option_keys: string[], option_values: string[]): boolean; save_to_streamv( stream: Gio.OutputStream, type: string, option_keys: string[], option_values: string[], cancellable?: Gio.Cancellable | null ): boolean; save_to_streamv_async( stream: Gio.OutputStream, type: string, option_keys: string[], option_values: string[], cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): void; savev(filename: string, type: string, option_keys: string[], option_values: string[]): boolean; scale( dest: Pixbuf, dest_x: number, dest_y: number, dest_width: number, dest_height: number, offset_x: number, offset_y: number, scale_x: number, scale_y: number, interp_type: InterpType ): void; scale_simple(dest_width: number, dest_height: number, interp_type: InterpType): Pixbuf | null; set_option(key: string, value: string): boolean; static calculate_rowstride( colorspace: Colorspace, has_alpha: boolean, bits_per_sample: number, width: number, height: number ): number; static get_file_info(filename: string): [PixbufFormat | null, number | null, number | null]; static get_file_info_async( filename: string, cancellable?: Gio.Cancellable | null ): Promise<[PixbufFormat, number, number]>; static get_file_info_async( filename: string, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<Pixbuf> | null ): void; static get_file_info_async( filename: string, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<Pixbuf> | null ): Promise<[PixbufFormat, number, number]> | void; static get_file_info_finish(async_result: Gio.AsyncResult): [PixbufFormat, number, number]; static get_formats(): PixbufFormat[]; static init_modules(path: string): boolean; static new_from_stream_async(stream: Gio.InputStream, cancellable?: Gio.Cancellable | null): Promise<Pixbuf>; static new_from_stream_async( stream: Gio.InputStream, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<Pixbuf> | null ): void; static new_from_stream_async( stream: Gio.InputStream, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<Pixbuf> | null ): Promise<Pixbuf> | void; static new_from_stream_at_scale_async( stream: Gio.InputStream, width: number, height: number, preserve_aspect_ratio: boolean, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<Pixbuf> | null ): void; static save_to_stream_finish(async_result: Gio.AsyncResult): boolean; // Implemented Members equal(icon2?: Gio.Icon | null): boolean; serialize(): GLib.Variant; to_string(): string | null; vfunc_equal(icon2?: Gio.Icon | null): boolean; vfunc_hash(): number; vfunc_serialize(): GLib.Variant; load(size: number, cancellable?: Gio.Cancellable | null): [Gio.InputStream, string | null]; load_async(size: number, cancellable?: Gio.Cancellable | null): Promise<[Gio.InputStream, string | null]>; load_async(size: number, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null): void; load_async( size: number, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<[Gio.InputStream, string | null]> | void; load_finish(res: Gio.AsyncResult): [Gio.InputStream, string | null]; vfunc_load(size: number, cancellable?: Gio.Cancellable | null): [Gio.InputStream, string | null]; vfunc_load_async(size: number, cancellable?: Gio.Cancellable | null): Promise<[Gio.InputStream, string | null]>; vfunc_load_async( size: number, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<this> | null ): void; vfunc_load_async( size: number, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<this> | null ): Promise<[Gio.InputStream, string | null]> | void; vfunc_load_finish(res: Gio.AsyncResult): [Gio.InputStream, string | null]; } export module PixbufAnimation { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class PixbufAnimation extends GObject.Object { static $gtype: GObject.GType<PixbufAnimation>; constructor(properties?: Partial<PixbufAnimation.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<PixbufAnimation.ConstructorProperties>, ...args: any[]): void; // Constructors static new_from_file(filename: string): PixbufAnimation; static new_from_resource(resource_path: string): PixbufAnimation; static new_from_stream(stream: Gio.InputStream, cancellable?: Gio.Cancellable | null): PixbufAnimation; static new_from_stream_finish(async_result: Gio.AsyncResult): PixbufAnimation; // Members get_height(): number; get_iter(start_time?: GLib.TimeVal | null): PixbufAnimationIter; get_static_image(): Pixbuf; get_width(): number; is_static_image(): boolean; static new_from_stream_async( stream: Gio.InputStream, cancellable?: Gio.Cancellable | null ): Promise<PixbufAnimation>; static new_from_stream_async( stream: Gio.InputStream, cancellable: Gio.Cancellable | null, callback: Gio.AsyncReadyCallback<PixbufAnimation> | null ): void; static new_from_stream_async( stream: Gio.InputStream, cancellable?: Gio.Cancellable | null, callback?: Gio.AsyncReadyCallback<PixbufAnimation> | null ): Promise<PixbufAnimation> | void; } export module PixbufAnimationIter { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class PixbufAnimationIter extends GObject.Object { static $gtype: GObject.GType<PixbufAnimationIter>; constructor(properties?: Partial<PixbufAnimationIter.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<PixbufAnimationIter.ConstructorProperties>, ...args: any[]): void; // Members advance(current_time?: GLib.TimeVal | null): boolean; get_delay_time(): number; get_pixbuf(): Pixbuf; on_currently_loading_frame(): boolean; } export module PixbufLoader { export interface ConstructorProperties extends GObject.Object.ConstructorProperties { [key: string]: any; } } export class PixbufLoader extends GObject.Object { static $gtype: GObject.GType<PixbufLoader>; constructor(properties?: Partial<PixbufLoader.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<PixbufLoader.ConstructorProperties>, ...args: any[]): void; // Signals connect(id: string, callback: (...args: any[]) => any): number; connect_after(id: string, callback: (...args: any[]) => any): number; emit(id: string, ...args: any[]): void; connect(signal: "area-prepared", callback: (_source: this) => void): number; connect_after(signal: "area-prepared", callback: (_source: this) => void): number; emit(signal: "area-prepared"): void; connect( signal: "area-updated", callback: (_source: this, x: number, y: number, width: number, height: number) => void ): number; connect_after( signal: "area-updated", callback: (_source: this, x: number, y: number, width: number, height: number) => void ): number; emit(signal: "area-updated", x: number, y: number, width: number, height: number): void; connect(signal: "closed", callback: (_source: this) => void): number; connect_after(signal: "closed", callback: (_source: this) => void): number; emit(signal: "closed"): void; connect(signal: "size-prepared", callback: (_source: this, width: number, height: number) => void): number; connect_after(signal: "size-prepared", callback: (_source: this, width: number, height: number) => void): number; emit(signal: "size-prepared", width: number, height: number): void; // Constructors static ["new"](): PixbufLoader; static new_with_mime_type(mime_type: string): PixbufLoader; static new_with_type(image_type: string): PixbufLoader; // Members close(): boolean; get_animation(): PixbufAnimation; get_format(): PixbufFormat | null; get_pixbuf(): Pixbuf; set_size(width: number, height: number): void; write(buf: Uint8Array | string): boolean; write_bytes(buffer: GLib.Bytes | Uint8Array): boolean; vfunc_area_prepared(): void; vfunc_area_updated(x: number, y: number, width: number, height: number): void; vfunc_closed(): void; vfunc_size_prepared(width: number, height: number): void; } export module PixbufSimpleAnim { export interface ConstructorProperties extends PixbufAnimation.ConstructorProperties { [key: string]: any; loop: boolean; } } export class PixbufSimpleAnim extends PixbufAnimation { static $gtype: GObject.GType<PixbufSimpleAnim>; constructor(properties?: Partial<PixbufSimpleAnim.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<PixbufSimpleAnim.ConstructorProperties>, ...args: any[]): void; // Properties loop: boolean; // Constructors static ["new"](width: number, height: number, rate: number): PixbufSimpleAnim; // Members add_frame(pixbuf: Pixbuf): void; get_loop(): boolean; set_loop(loop: boolean): void; } export module PixbufSimpleAnimIter { export interface ConstructorProperties extends PixbufAnimationIter.ConstructorProperties { [key: string]: any; } } export class PixbufSimpleAnimIter extends PixbufAnimationIter { static $gtype: GObject.GType<PixbufSimpleAnimIter>; constructor(properties?: Partial<PixbufSimpleAnimIter.ConstructorProperties>, ...args: any[]); _init(properties?: Partial<PixbufSimpleAnimIter.ConstructorProperties>, ...args: any[]): void; } export class PixbufFormat { static $gtype: GObject.GType<PixbufFormat>; constructor(copy: PixbufFormat); // Members copy(): PixbufFormat; free(): void; get_description(): string; get_extensions(): string[]; get_license(): string; get_mime_types(): string[]; get_name(): string; is_disabled(): boolean; is_save_option_supported(option_key: string): boolean; is_scalable(): boolean; is_writable(): boolean; set_disabled(disabled: boolean): void; }
the_stack
import {Action, Dispatch} from "redux"; import {HTTPVerb, RSAA, RSAAction} from "redux-api-middleware"; import {ThunkAction} from "redux-thunk"; import {RootState} from "../../reducers/index"; import {JSON_HEADERS, JSONAPI_HEADERS} from "../constants" import { JSONAPIRelationship, JSONAPIRelationships, RSAAChildIndexActionRequest, RSAAIndexActionRequest, RSAAIndexActionResponse, RSAAPatchActionRequest, RSAAReadActionRequest, RSAAReadActionResponse, } from "../json-api"; import {JSONAPIDetailResponse, JSONAPIErrorResponse} from "../json-api"; import {Tag} from "../tags/types"; import {Command, Device, DeviceRelationship} from "./types"; import { encodeJSONAPIChildIndexParameters, encodeJSONAPIIndexParameters, FlaskFilter, FlaskFilters } from "../../flask-rest-jsonapi"; export enum DevicesActionTypes { INDEX_REQUEST = "devices/INDEX_REQUEST", INDEX_SUCCESS = "devices/INDEX_SUCCESS", INDEX_FAILURE = "devices/INDEX_FAILURE", READ_REQUEST = "devices/READ_REQUEST", READ_SUCCESS = "devices/READ_SUCCESS", READ_FAILURE = "devices/READ_FAILURE", PATCH_REQUEST = "devices/PATCH_REQUEST", PATCH_SUCCESS = "devices/PATCH_SUCCESS", PATCH_FAILURE = "devices/PATCH_FAILURE", // Relationships COMMANDS_REQUEST = "devices/COMMANDS_REQUEST", COMMANDS_SUCCESS = "devices/COMMANDS_SUCCESS", COMMANDS_FAILURE = "devices/COMMANDS_FAILURE", REL_POST_REQUEST = "devices/REL_POST_REQUEST", REL_POST_SUCCESS = "devices/REL_POST_SUCCESS", REL_POST_FAILURE = "devices/REL_POST_FAILURE", // Interactive methods PUSH_REQUEST = "devices/PUSH_REQUEST", PUSH_SUCCESS = "devices/PUSH_SUCCESS", PUSH_FAILURE = "devices/PUSH_FAILURE", ERASE_REQUEST = "devices/ERASE_REQUEST", ERASE_SUCCESS = "devices/ERASE_SUCCESS", ERASE_FAILURE = "devices/ERASE_FAILURE", LOCK_REQUEST = "devices/LOCK_REQUEST", LOCK_SUCCESS = "devices/LOCK_SUCCESS", LOCK_FAILURE = "devices/LOCK_FAILURE", RESTART_REQUEST = "devices/RESTART_REQUEST", RESTART_SUCCESS = "devices/RESTART_SUCCESS", RESTART_FAILURE = "devices/RESTART_FAILURE", SHUTDOWN_REQUEST = "devices/SHUTDOWN_REQUEST", SHUTDOWN_SUCCESS = "devices/SHUTDOWN_SUCCESS", SHUTDOWN_FAILURE = "devices/SHUTDOWN_FAILURE", CLEARPASSCODE_REQUEST = "devices/CLEARPASSCODE_REQUEST", CLEARPASSCODE_SUCCESS = "devices/CLEARPASSCODE_SUCCESS", CLEARPASSCODE_FAILURE = "devices/CLEARPASSCODE_FAILURE", INVENTORY_REQUEST = "devices/INVENTORY_REQUEST", INVENTORY_SUCCESS = "devices/INVENTORY_SUCCESS", INVENTORY_FAILURE = "devices/INVENTORY_FAILURE", } export type IndexActionRequest = RSAAIndexActionRequest<DevicesActionTypes.INDEX_REQUEST, DevicesActionTypes.INDEX_SUCCESS, DevicesActionTypes.INDEX_FAILURE>; export type IndexActionResponse = RSAAIndexActionResponse<DevicesActionTypes.INDEX_REQUEST, DevicesActionTypes.INDEX_SUCCESS, DevicesActionTypes.INDEX_FAILURE, Device>; export const index = encodeJSONAPIIndexParameters((queryParameters: string[]) => { return ({ [RSAA]: { endpoint: "/api/v1/devices?" + queryParameters.join("&"), headers: (state: RootState) => ({ ...JSONAPI_HEADERS, Authorization: `Bearer ${state.auth.access_token}`, }), method: ("GET" as HTTPVerb), types: [ DevicesActionTypes.INDEX_REQUEST, DevicesActionTypes.INDEX_SUCCESS, DevicesActionTypes.INDEX_FAILURE, ], }, } as RSAAction< DevicesActionTypes.INDEX_REQUEST, DevicesActionTypes.INDEX_SUCCESS, DevicesActionTypes.INDEX_FAILURE>); }); export const fetchDevicesIfRequired = ( size: number = 10, pageNumber: number = 1, sort?: string[], filters?: FlaskFilters, ): ThunkAction<void, RootState, void, IndexActionResponse> => (dispatch: Dispatch, getState: () => RootState) => { const { auth: { access_token } } = getState(); // const { devices } = getState(); // if (devices.lastReceived) { // const now = new Date(); // const seconds = 10; // if ((now.getTime() - devices.lastReceived.getTime()) / 1000 < seconds) { // console.log("cache hit"); // return; // } // } dispatch(index(size, pageNumber, sort, filters)); }; export type ReadActionRequest = RSAAReadActionRequest< DevicesActionTypes.READ_REQUEST, DevicesActionTypes.READ_SUCCESS, DevicesActionTypes.READ_FAILURE>; export type ReadActionResponse = RSAAReadActionResponse< DevicesActionTypes.READ_REQUEST, DevicesActionTypes.READ_SUCCESS, DevicesActionTypes.READ_FAILURE, JSONAPIDetailResponse<Device, undefined>>; export const read: ReadActionRequest = (id: string, include?: string[]) => { let inclusions = ""; if (include && include.length) { inclusions = "include=" + include.join(",") } return { [RSAA]: { endpoint: `/api/v1/devices/${id}?${inclusions}`, headers: (state: RootState) => ({ ...JSONAPI_HEADERS, Authorization: `Bearer ${state.auth.access_token}`, }), method: "GET", types: [ DevicesActionTypes.READ_REQUEST, DevicesActionTypes.READ_SUCCESS, DevicesActionTypes.READ_FAILURE, ], }, } }; export const READ_CACHE_HIT = "devices/READ_CACHE_HIT"; export type READ_CACHE_HIT = typeof READ_CACHE_HIT; export type CacheFetchActionRequest = (id: string, include?: string[]) => ThunkAction<void, RootState, any, ReadActionResponse>; export const fetchDeviceIfRequired = ( id: string, include?: string[], ) => ( dispatch: Dispatch, getState: () => RootState, ) => { const { devices } = getState(); // if (devices.lastReceived) { // const now = new Date(); // const seconds = 10; // if ((now.getTime() - devices.lastReceived.getTime()) / 1000 < seconds) { // if (devices.byId.hasOwnProperty(id)) { // dispatch({type: READ_CACHE_HIT, id}); // const payload = { // type: READ_SUCCESS, // payload: { // data: devices.byId[id] // } // }; // dispatch(payload); // return; // } // } // } dispatch(read(id, include)); }; export type PushActionRequest = (id: string | number) => RSAAction<DevicesActionTypes.PUSH_REQUEST, DevicesActionTypes.PUSH_SUCCESS, DevicesActionTypes.PUSH_FAILURE>; export interface PushActionResponse { type: DevicesActionTypes.PUSH_REQUEST | DevicesActionTypes.PUSH_SUCCESS | DevicesActionTypes.PUSH_FAILURE; payload?: JSONAPIDetailResponse<any, undefined> | JSONAPIErrorResponse; } export const push: PushActionRequest = (id: string | number) => { return { [RSAA]: { endpoint: `/api/v1/devices/${id}/push`, headers: (state: RootState) => ({ ...JSONAPI_HEADERS, Authorization: `Bearer ${state.auth.access_token}`, }), method: "POST", types: [ DevicesActionTypes.PUSH_REQUEST, DevicesActionTypes.PUSH_SUCCESS, DevicesActionTypes.PUSH_FAILURE, ], }, } }; export type RestartActionRequest = (id: string | number) => RSAAction< DevicesActionTypes.RESTART_REQUEST, DevicesActionTypes.RESTART_SUCCESS, DevicesActionTypes.RESTART_FAILURE>; export interface RestartActionResponse { type: DevicesActionTypes.RESTART_REQUEST | DevicesActionTypes.RESTART_SUCCESS | DevicesActionTypes.RESTART_FAILURE; payload?: JSONAPIDetailResponse<any, undefined> | JSONAPIErrorResponse; } export const restart: RestartActionRequest = (deviceId: string | number) => { return { [RSAA]: { endpoint: `/api/v1/devices/${deviceId}/restart`, headers: (state: RootState) => ({ ...JSONAPI_HEADERS, Authorization: `Bearer ${state.auth.access_token}`, }), method: "POST", types: [ DevicesActionTypes.RESTART_REQUEST, DevicesActionTypes.RESTART_SUCCESS, DevicesActionTypes.RESTART_FAILURE, ], }, } }; export type ShutdownActionRequest = (id: string | number) => RSAAction< DevicesActionTypes.SHUTDOWN_REQUEST, DevicesActionTypes.SHUTDOWN_SUCCESS, DevicesActionTypes.SHUTDOWN_FAILURE>; export interface ShutdownActionResponse { type: DevicesActionTypes.SHUTDOWN_REQUEST | DevicesActionTypes.SHUTDOWN_SUCCESS | DevicesActionTypes.SHUTDOWN_FAILURE; payload?: JSONAPIDetailResponse<any, undefined> | JSONAPIErrorResponse; } export const shutdown: ShutdownActionRequest = (id: string | number) => { return { [RSAA]: { endpoint: `/api/v1/devices/${id}/shutdown`, headers: (state: RootState) => ({ ...JSONAPI_HEADERS, Authorization: `Bearer ${state.auth.access_token}`, }), method: "POST", types: [ DevicesActionTypes.SHUTDOWN_REQUEST, DevicesActionTypes.SHUTDOWN_SUCCESS, DevicesActionTypes.SHUTDOWN_FAILURE, ], }, } }; export type EraseActionRequest = (id: string | number) => RSAAction< DevicesActionTypes.ERASE_REQUEST, DevicesActionTypes.ERASE_SUCCESS, DevicesActionTypes.ERASE_FAILURE>; export interface EraseActionResponse { type: DevicesActionTypes.ERASE_REQUEST | DevicesActionTypes.ERASE_SUCCESS | DevicesActionTypes.ERASE_FAILURE; payload?: JSONAPIDetailResponse<any, undefined> | JSONAPIErrorResponse; } export const erase: EraseActionRequest = (id: string | number) => { return { [RSAA]: { endpoint: `/api/v1/devices/${id}/erase`, headers: (state: RootState) => ({ ...JSONAPI_HEADERS, Authorization: `Bearer ${state.auth.access_token}`, }), method: "POST", types: [ DevicesActionTypes.ERASE_REQUEST, DevicesActionTypes.ERASE_SUCCESS, DevicesActionTypes.ERASE_FAILURE, ], }, } }; export type LockActionRequest = (id: string | number, pin?: string, message?: string, phoneNumber?: string) => RSAAction< DevicesActionTypes.LOCK_REQUEST, DevicesActionTypes.LOCK_SUCCESS, DevicesActionTypes.LOCK_FAILURE>; export interface LockActionResponse { type: DevicesActionTypes.LOCK_REQUEST | DevicesActionTypes.LOCK_SUCCESS | DevicesActionTypes.LOCK_FAILURE; payload?: JSONAPIDetailResponse<any, undefined> | JSONAPIErrorResponse; } export const lock: LockActionRequest = (deviceId: string | number, pin?: string, message?: string, phoneNumber?: string) => { return { [RSAA]: { body: JSON.stringify({ message, phoneNumber, pin, }), endpoint: `/api/v1/devices/${deviceId}/lock`, headers: (state: RootState) => ({ ...JSONAPI_HEADERS, Authorization: `Bearer ${state.auth.access_token}`, }), method: "POST", types: [ DevicesActionTypes.LOCK_REQUEST, DevicesActionTypes.LOCK_SUCCESS, DevicesActionTypes.LOCK_FAILURE, ], }, } }; export type ClearPasscodeActionRequest = (id: string | number) => RSAAction< DevicesActionTypes.CLEARPASSCODE_REQUEST, DevicesActionTypes.CLEARPASSCODE_SUCCESS, DevicesActionTypes.CLEARPASSCODE_FAILURE>; export interface ClearPasscodeActionResponse { type: DevicesActionTypes.CLEARPASSCODE_REQUEST | DevicesActionTypes.CLEARPASSCODE_SUCCESS | DevicesActionTypes.CLEARPASSCODE_FAILURE; payload?: JSONAPIDetailResponse<any, undefined> | JSONAPIErrorResponse; } export const clearPasscode: ClearPasscodeActionRequest = (id: string | number) => { return { [RSAA]: { endpoint: `/api/v1/devices/${id}/clear_passcode`, headers: (state: RootState) => ({ ...JSONAPI_HEADERS, Authorization: `Bearer ${state.auth.access_token}`, }), method: "POST", types: [ DevicesActionTypes.CLEARPASSCODE_REQUEST, DevicesActionTypes.CLEARPASSCODE_SUCCESS, DevicesActionTypes.CLEARPASSCODE_FAILURE, ], }, } }; export type InventoryActionRequest = (id: string | number) => RSAAction<DevicesActionTypes.INVENTORY_REQUEST, DevicesActionTypes.INVENTORY_SUCCESS, DevicesActionTypes.INVENTORY_FAILURE>; export interface InventoryActionResponse { type: DevicesActionTypes.INVENTORY_REQUEST | DevicesActionTypes.INVENTORY_SUCCESS | DevicesActionTypes.INVENTORY_FAILURE; payload?: JSONAPIDetailResponse<any, undefined> | JSONAPIErrorResponse; } export const inventory: InventoryActionRequest = (id: string | number) => { return { [RSAA]: { endpoint: `/api/v1/devices/inventory/${id}`, headers: (state: RootState) => ({ ...JSONAPI_HEADERS, Authorization: `Bearer ${state.auth.access_token}`, }), method: "GET", types: [ DevicesActionTypes.INVENTORY_REQUEST, DevicesActionTypes.INVENTORY_SUCCESS, DevicesActionTypes.INVENTORY_FAILURE, ], }, } }; export type TEST_REQUEST = "devices/TEST_REQUEST"; export const TEST_REQUEST: TEST_REQUEST = "devices/TEST_REQUEST"; export type TEST_SUCCESS = "devices/TEST_SUCCESS"; export const TEST_SUCCESS: TEST_SUCCESS = "devices/TEST_SUCCESS"; export type TEST_FAILURE = "devices/TEST_FAILURE"; export const TEST_FAILURE: TEST_FAILURE = "devices/TEST_FAILURE"; export type TestActionRequest = (id: string | number) => RSAAction<TEST_REQUEST, TEST_SUCCESS, TEST_FAILURE>; export interface TestActionResponse { type: TEST_REQUEST | TEST_SUCCESS | TEST_FAILURE; payload?: JSONAPIDetailResponse<any, undefined> | JSONAPIErrorResponse; } export const test: TestActionRequest = (id: string | number) => { return { [RSAA]: { endpoint: `/api/v1/devices/test/${id}`, headers: (state: RootState) => ({ ...JSONAPI_HEADERS, Authorization: `Bearer ${state.auth.access_token}`, }), method: "POST", types: [ TEST_REQUEST, TEST_SUCCESS, TEST_FAILURE, ], }, } }; export type CommandsActionRequest = RSAAChildIndexActionRequest< DevicesActionTypes.COMMANDS_REQUEST, DevicesActionTypes.COMMANDS_SUCCESS, DevicesActionTypes.COMMANDS_FAILURE>; export type CommandsActionResponse = RSAAIndexActionResponse< DevicesActionTypes.COMMANDS_REQUEST, DevicesActionTypes.COMMANDS_SUCCESS, DevicesActionTypes.COMMANDS_FAILURE, Command>; export const commands = encodeJSONAPIChildIndexParameters((deviceId: string, queryParameters: string[]) => { return ({ [RSAA]: { endpoint: `/api/v1/devices/${deviceId}/commands?${queryParameters.join("&")}`, headers: (state: RootState) => ({ ...JSONAPI_HEADERS, Authorization: `Bearer ${state.auth.access_token}`, }), method: "GET", types: [ DevicesActionTypes.COMMANDS_REQUEST, DevicesActionTypes.COMMANDS_SUCCESS, DevicesActionTypes.COMMANDS_FAILURE, ], }, } as RSAAction< DevicesActionTypes.COMMANDS_REQUEST, DevicesActionTypes.COMMANDS_SUCCESS, DevicesActionTypes.COMMANDS_FAILURE>); }); export type PatchActionRequest = RSAAPatchActionRequest< DevicesActionTypes.PATCH_REQUEST, DevicesActionTypes.PATCH_SUCCESS, DevicesActionTypes.PATCH_FAILURE, Device>; export type PatchActionResponse = RSAAReadActionResponse< DevicesActionTypes.PATCH_REQUEST, DevicesActionTypes.PATCH_SUCCESS, DevicesActionTypes.PATCH_FAILURE, JSONAPIDetailResponse<Device, Tag>>; export const patch: PatchActionRequest = (deviceId: string, values: Device) => { return { [RSAA]: { body: JSON.stringify({ data: { attributes: values, type: "devices", }, }), endpoint: `/api/v1/devices/${deviceId}`, headers: (state: RootState) => ({ ...JSONAPI_HEADERS, Authorization: `Bearer ${state.auth.access_token}`, }), method: "PATCH", types: [ DevicesActionTypes.PATCH_REQUEST, DevicesActionTypes.PATCH_SUCCESS, DevicesActionTypes.PATCH_FAILURE, ], }, } }; type PostRelationshipActionRequest = (parentId: string, relationship: DeviceRelationship, data: JSONAPIRelationship[]) => RSAAction<DevicesActionTypes.REL_POST_REQUEST, DevicesActionTypes.REL_POST_SUCCESS, DevicesActionTypes.REL_POST_FAILURE>; export type PostRelationshipActionResponse = RSAAReadActionResponse< DevicesActionTypes.REL_POST_REQUEST, DevicesActionTypes.REL_POST_SUCCESS, DevicesActionTypes.REL_POST_FAILURE, JSONAPIDetailResponse<Device, undefined>>; export const postRelationship: PostRelationshipActionRequest = (id: string, relationship: DeviceRelationship, data: JSONAPIRelationship[]) => { return { [RSAA]: { body: JSON.stringify({ data }), endpoint: `/api/v1/devices/${id}/relationships/${relationship}`, headers: (state: RootState) => ({ ...JSONAPI_HEADERS, Authorization: `Bearer ${state.auth.access_token}`, }), method: "POST", types: [ DevicesActionTypes.REL_POST_REQUEST, DevicesActionTypes.REL_POST_SUCCESS, DevicesActionTypes.REL_POST_FAILURE, ], }, } }; export const RCPOST_REQUEST = "devices/RCPOST_REQUEST"; export type RCPOST_REQUEST = typeof RCPOST_REQUEST; export const RCPOST_SUCCESS = "devices/RCPOST_SUCCESS"; export type RCPOST_SUCCESS = typeof RCPOST_SUCCESS; export const RCPOST_FAILURE = "devices/RCPOST_FAILURE"; export type RCPOST_FAILURE = typeof RCPOST_FAILURE; export type PostRelatedActionRequest = <TRelated>(parentId: string, relationship: DeviceRelationship, data: TRelated) => RSAAction<RCPOST_REQUEST, RCPOST_SUCCESS, RCPOST_FAILURE>; export type PostRelatedActionResponse = RSAAReadActionResponse<RCPOST_REQUEST, RCPOST_SUCCESS, RCPOST_FAILURE, JSONAPIDetailResponse<any, undefined>>; export const postRelated: PostRelatedActionRequest = <TRelated>( parentId: string, relationship: DeviceRelationship, data: TRelated): RSAAction<RCPOST_REQUEST, RCPOST_SUCCESS, RCPOST_FAILURE> => { return { [RSAA]: { body: JSON.stringify({ data: { attributes: data, relationships: { devices: { data: [ { id: parentId, type: "devices", }, ], }, }, type: relationship, } }), endpoint: `/api/v1/devices/${parentId}/${relationship}`, headers: (state: RootState) => ({ ...JSONAPI_HEADERS, Authorization: `Bearer ${state.auth.access_token}`, }), method: "POST", types: [ RCPOST_REQUEST, RCPOST_SUCCESS, RCPOST_FAILURE, ], }, } }; export const RPATCH_REQUEST = "devices/RPATCH_REQUEST"; export type RPATCH_REQUEST = typeof RPATCH_REQUEST; export const RPATCH_SUCCESS = "devices/RPATCH_SUCCESS"; export type RPATCH_SUCCESS = typeof RPATCH_SUCCESS; export const RPATCH_FAILURE = "devices/RPATCH_FAILURE"; export type RPATCH_FAILURE = typeof RPATCH_FAILURE; export type PatchRelationshipActionRequest = ( parentId: string, relationship: DeviceRelationship, data: JSONAPIRelationship[]) => RSAAction<RPATCH_REQUEST, RPATCH_SUCCESS, RPATCH_FAILURE>; export type PatchRelationshipActionResponse = RSAAReadActionResponse< RPATCH_REQUEST, RPATCH_SUCCESS, RPATCH_FAILURE, JSONAPIDetailResponse<Device, undefined>>; export const patchRelationship: PatchRelationshipActionRequest = ( id: string, relationship: DeviceRelationship, data: JSONAPIRelationship[]) => { return { [RSAA]: { body: JSON.stringify({ data }), endpoint: `/api/v1/devices/${id}/relationships/${relationship}`, headers: (state: RootState) => ({ ...JSONAPI_HEADERS, Authorization: `Bearer ${state.auth.access_token}`, }), method: "PATCH", types: [ RPATCH_REQUEST, RPATCH_SUCCESS, RPATCH_FAILURE, ], }, } };
the_stack
import Type from './type'; import { ArgDirection, FunctionDef, ArgumentDef } from './ast/function_def'; import { DateValue } from './ast/values'; import type * as Builtin from './runtime/builtins'; // Definitions of ThingTalk operators /** * Declare the implementation of a ThingTalk operator. */ export interface OpImplementation { /** * A JavaScript operator that implement this ThingTalk operator. */ op ?: string; /** * A function in the {@link Builtin} namespace that implements this operator. */ fn ?: keyof typeof Builtin; /** * Invert the arguments of the JS function/operator compared to the ThingTalk operator. */ flip ?: boolean; /** * Pass the ExecEnvironment as the first argument to the function. */ env ?: boolean; } export type OverloadResolver = (...types : Type[]) => OpImplementation; /** * Definition of a ThingTalk operator. */ export interface OpDefinition extends OpImplementation { /** * The possible overloads of this operator. Each array member is an overload: * the first N-1 elements are the input types and the last * is the result type. */ types : Array<Array<(Type | string)>>; /** * Compute which implementation to use for a given overload. */ overload ?: OverloadResolver; } /** * Definitions (type signatures) of ThingTalk binary comparison operators. * * @package */ export const BinaryOps : { [op : string] : OpDefinition } = { '>=': { types: [[Type.String, Type.String, Type.Boolean], [new Type.Measure(''), new Type.Measure(''), Type.Boolean], [Type.Number, Type.Number, Type.Boolean], [Type.Date, Type.Date, Type.Boolean], [Type.Time, Type.Time, Type.Boolean], [Type.Currency, Type.Currency, Type.Boolean]], op: '>=' }, '<=': { types: [[Type.String, Type.String, Type.Boolean], [new Type.Measure(''), new Type.Measure(''), Type.Boolean], [Type.Number, Type.Number, Type.Boolean], [Type.Date, Type.Date, Type.Boolean], [Type.Time, Type.Time, Type.Boolean], [Type.Currency, Type.Currency, Type.Boolean]], op: '<=' }, '==': { types: [['a', 'a', Type.Boolean]], fn: 'equality', }, '=~': { types: [[Type.String, Type.String, Type.Boolean], [new Type.Entity(''), Type.String, Type.Boolean]], fn: 'like', }, '~=': { types: [[Type.String, Type.String, Type.Boolean], [Type.String, new Type.Entity(''), Type.Boolean]], fn: 'like', flip: true }, starts_with: { types: [[Type.String, Type.String, Type.Boolean]], fn: 'startsWith', }, ends_with: { types: [[Type.String, Type.String, Type.Boolean]], fn: 'endsWith', }, prefix_of: { types: [[Type.String, Type.String, Type.Boolean]], fn: 'startsWith', flip: true }, suffix_of: { types: [[Type.String, Type.String, Type.Boolean]], fn: 'endsWith', flip: true }, /** * `contains`: array containment with equality * * `contains(a, b) = ∃ x. x ∈ a && b == x` */ 'contains': { types: [[new Type.Array('a'), 'a', Type.Boolean], [Type.RecurrentTimeSpecification, Type.Date, Type.Boolean], [Type.RecurrentTimeSpecification, Type.Time, Type.Boolean]], overload: (t1 : Type, t2 : Type, t3 : Type) : OpImplementation => { if (t1 === Type.RecurrentTimeSpecification) return { fn: 'recurrentTimeSpecContains' }; else return { fn: 'contains' }; } }, /** * `in_array`: array membership with equality * * `in_array(a, b) = ∃ x. x ∈ b && a == x` * * NOTE (Thm): `in_array(a, [x1, x2, ... xn]) = a == x1 || a == x2 || ... || x == xn` */ 'in_array': { types: [['a', new Type.Array('a'), Type.Boolean]], fn: 'contains', flip: true }, /** * `contains~`: array containment with similarity * * `contains~(a, b) = ∃ x. x ∈ a && b =~ x` */ 'contains~': { types: [[new Type.Array(Type.String), Type.String, Type.Boolean], [new Type.Array(new Type.Entity('')), Type.String, Type.Boolean]], fn: 'containsLike', }, /** * `in_array~`: array membership with similarity * * `in_array~(a, b) = ∃ x. x ∈ b && x =~ a` * * NOTE (Thm): `in_array~(a, [x1, x2, ... xn]) = x1 =~ a || x2 =~ a || ... || xn =~ a` */ 'in_array~': { types: [[Type.String, new Type.Array(Type.String), Type.Boolean], [new Type.Entity(''), new Type.Array(Type.String), Type.Boolean]], fn: 'inArrayLike', }, /** * `~contains`: reverse array containment with similarity * * `~contains(a, b) = ∃ x. x ∈ a && b ~= x` * * NOTE (Thm): `~contains(a, b) = in_array~(b, a)` */ '~contains': { types: [[new Type.Array(Type.String), Type.String, Type.Boolean], [new Type.Array(Type.String), new Type.Entity(''), Type.Boolean]], fn: 'inArrayLike', flip: true, }, /** * `~in_array`: array membership with similarity * * `~in_array(a, b) = ∃ x. x ∈ b && x ~= a` * * NOTE (Thm): `~in_array(a, b) = contains~(b, a)` */ '~in_array': { types: [[Type.String, new Type.Array(Type.String), Type.Boolean], [Type.String, new Type.Array(new Type.Entity('')), Type.Boolean]], fn: 'containsLike', flip: true, }, 'has_member': { types: [[new Type.Entity('tt:contact_group'), new Type.Entity('tt:contact'), Type.Boolean]], }, 'group_member': { types: [[new Type.Entity('tt:contact'), new Type.Entity('tt:contact_group'), Type.Boolean]], } }; /** * Definitions (type signatures) of ThingTalk unary operators. */ export const UnaryOps : { [op : string] : OpDefinition } = { '!': { types: [[Type.Boolean, Type.Boolean]], op: '!' }, 'get_time': { types: [[Type.Date, Type.Time]], fn: 'getTime' }, 'get_currency': { types: [[Type.Number, Type.Currency]], fn: 'getCurrency' } }; /** * Definitions (type signatures) of ThingTalk scalar operators. */ export const ScalarExpressionOps : { [op : string] : OpDefinition } = { '+': { types: [[Type.String, Type.String, Type.String], [Type.Number, Type.Number, Type.Number], [Type.Currency, Type.Currency, Type.Currency], [new Type.Measure(''), new Type.Measure(''), new Type.Measure('')], [Type.Date, new Type.Measure('ms'), Type.Date], [Type.Time, new Type.Measure('ms'), Type.Time]], overload: (t1 : Type, t2 : Type, t3 : Type) : OpImplementation => { if (t1 === Type.Date) return { fn: 'dateAdd' }; else if (t1 === Type.Time) return { fn: 'timeAdd' }; else return { op: '+' }; } }, '-': { types: [[Type.Number, Type.Number, Type.Number], [Type.Currency, Type.Currency, Type.Currency], [new Type.Measure(''), new Type.Measure(''), new Type.Measure('')], [Type.Date, new Type.Measure('ms'), Type.Date], [Type.Time, new Type.Measure('ms'), Type.Time]], op: '-', overload: (t1 : Type, t2 : Type, t3 : Type) : OpImplementation => { if (t1 === Type.Date) return { fn: 'dateSub' }; else if (t1 === Type.Time) return { fn: 'timeSub' }; else return { op: '-' }; } }, '*': { types: [[Type.Number, Type.Number, Type.Number], [Type.Currency, Type.Number, Type.Currency], [new Type.Measure(''), Type.Number, new Type.Measure('')]], op: '*' }, '/': { types: [[Type.Number, Type.Number, Type.Number], [Type.Currency, Type.Number, Type.Currency], [new Type.Measure(''), Type.Number, new Type.Measure('')]], op: '/' }, '%': { types: [[Type.Number, Type.Number, Type.Number]], op: '%' }, '**': { types: [[Type.Number, Type.Number, Type.Number]], op: '**' }, 'distance': { types: [[Type.Location, Type.Location, new Type.Measure('m')]], fn: 'distance' }, 'max': { types: [[new Type.Array(Type.Number), Type.Number], [new Type.Array(Type.Currency), Type.Currency], [new Type.Array(new Type.Measure('')), new Type.Measure('')]], fn: 'aggregateMax', }, 'min': { types: [[new Type.Array(Type.Number), Type.Number], [new Type.Array(Type.Currency), Type.Currency], [new Type.Array(new Type.Measure('')), new Type.Measure('')]], fn: 'aggregateMin', }, 'sum': { types: [[new Type.Array(Type.Number), Type.Number], [new Type.Array(Type.Currency), Type.Currency], [new Type.Array(new Type.Measure('')), new Type.Measure('')]], fn: 'aggregateSum', }, 'avg': { types: [[new Type.Array(Type.Number), Type.Number], [new Type.Array(Type.Currency), Type.Currency], [new Type.Array(new Type.Measure('')), new Type.Measure('')]], fn: 'aggregateAvg', }, 'count': { types: [[new Type.Array('x'), Type.Number]], fn: 'count', }, 'set_time': { types: [[Type.Date, Type.Time, Type.Date]], fn: 'setTime', env: true } }; /** * Definitions (type signatures) of ThingTalk aggregation operators. */ export const Aggregations : { [op : string] : OpDefinition } = { 'max': { types: [[Type.Number, Type.Number], [Type.Currency, Type.Currency], [new Type.Measure(''), new Type.Measure('')]] }, 'min': { types: [[Type.Number, Type.Number], [Type.Currency, Type.Currency], [new Type.Measure(''), new Type.Measure('')]] }, 'sum': { types: [[Type.Number, Type.Number], [Type.Currency, Type.Currency], [new Type.Measure(''), new Type.Measure('')]] }, 'avg': { types: [[Type.Number, Type.Number], [Type.Currency, Type.Currency], [new Type.Measure(''), new Type.Measure('')]] }, 'count': { types: [[Type.Any, Type.Number]] } }; const TIMER_SCHEMA = new FunctionDef(null, 'stream', null, // class 'timer', [], // extends { is_list: false, is_monitorable: true }, [ new ArgumentDef(null, ArgDirection.IN_OPT, 'base', Type.Date, { impl: { default: new DateValue(null) // $now } }), new ArgumentDef(null, ArgDirection.IN_REQ, 'interval', new Type.Measure('ms')), new ArgumentDef(null, ArgDirection.IN_OPT, 'frequency', Type.Number), ], {} ); const AT_TIMER_SCHEMA = new FunctionDef(null, 'stream', null, // class 'attimer', [], // extends { is_list: false, is_monitorable: true }, [ new ArgumentDef(null, ArgDirection.IN_REQ, 'time', new Type.Array(Type.Time)), new ArgumentDef(null, ArgDirection.IN_OPT, 'expiration_date', Type.Date), ], {} ); const ON_TIMER_SCHEMA = new FunctionDef(null, 'stream', null, //class 'ontimer', [], //extends { is_list: false, is_monitorable: true }, [ new ArgumentDef(null, ArgDirection.IN_REQ, 'date', new Type.Array(Type.Date)) ], {} ); /** * Definitions (type signatures) of builtin ThingTalk functions. * * These are functions that are predefined and can be called without the @-sign. */ export const Functions : { [key : string] : FunctionDef } = { 'timer': TIMER_SCHEMA, 'attimer': AT_TIMER_SCHEMA, 'ontimer': ON_TIMER_SCHEMA };
the_stack
import { FALLBACK_COLOR } from '../types'; import { ThemeColors } from './createColors'; /** * @alpha */ export interface ThemeVisualizationColors { /** Only for internal use by color schemes */ palette: string[]; /** Lookup the real color given the name */ getColorByName: (color: string) => string; /** Colors organized by hue */ hues: ThemeVizHue[]; } /** * @alpha */ export interface ThemeVizColor { color: string; name: string; aliases?: string[]; primary?: boolean; } /** * @alpha */ export interface ThemeVizHue { name: string; shades: ThemeVizColor[]; } /** * @internal */ export function createVisualizationColors(colors: ThemeColors): ThemeVisualizationColors { let hues: ThemeVizHue[] = []; if (colors.mode === 'dark') { hues = getDarkHues(); } else if (colors.mode === 'light') { hues = getLightHues(); } const byNameIndex: Record<string, string> = {}; for (const hue of hues) { for (const shade of hue.shades) { byNameIndex[shade.name] = shade.color; if (shade.aliases) { for (const alias of shade.aliases) { byNameIndex[alias] = shade.color; } } } } // special colors byNameIndex['transparent'] = 'rgba(0,0,0,0)'; byNameIndex['panel-bg'] = colors.background.primary; byNameIndex['text'] = colors.text.primary; const getColorByName = (colorName: string) => { if (!colorName) { return FALLBACK_COLOR; } const realColor = byNameIndex[colorName]; if (realColor) { return realColor; } if (colorName[0] === '#') { return colorName; } if (colorName.indexOf('rgb') > -1) { return colorName; } const nativeColor = nativeColorNames[colorName.toLowerCase()]; if (nativeColor) { byNameIndex[colorName] = nativeColor; return nativeColor; } return colorName; }; const palette = getClassicPalette(); return { hues, palette, getColorByName, }; } function getDarkHues(): ThemeVizHue[] { return [ { name: 'red', shades: [ { color: '#FFA6B0', name: 'super-light-red' }, { color: '#FF7383', name: 'light-red' }, { color: '#F2495C', name: 'red', primary: true }, { color: '#E02F44', name: 'semi-dark-red' }, { color: '#C4162A', name: 'dark-red' }, ], }, { name: 'orange', shades: [ { color: '#FFCB7D', name: 'super-light-orange', aliases: [] }, { color: '#FFB357', name: 'light-orange', aliases: [] }, { color: '#FF9830', name: 'orange', aliases: [], primary: true }, { color: '#FF780A', name: 'semi-dark-orange', aliases: [] }, { color: '#FA6400', name: 'dark-orange', aliases: [] }, ], }, { name: 'yellow', shades: [ { color: '#FFF899', name: 'super-light-yellow', aliases: [] }, { color: '#FFEE52', name: 'light-yellow', aliases: [] }, { color: '#FADE2A', name: 'yellow', aliases: [], primary: true }, { color: '#F2CC0C', name: 'semi-dark-yellow', aliases: [] }, { color: '#E0B400', name: 'dark-yellow', aliases: [] }, ], }, { name: 'green', shades: [ { color: '#C8F2C2', name: 'super-light-green', aliases: [] }, { color: '#96D98D', name: 'light-green', aliases: [] }, { color: '#73BF69', name: 'green', aliases: [], primary: true }, { color: '#56A64B', name: 'semi-dark-green', aliases: [] }, { color: '#37872D', name: 'dark-green', aliases: [] }, ], }, { name: 'blue', shades: [ { color: '#C0D8FF', name: 'super-light-blue', aliases: [] }, { color: '#8AB8FF', name: 'light-blue', aliases: [] }, { color: '#5794F2', name: 'blue', aliases: [], primary: true }, { color: '#3274D9', name: 'semi-dark-blue', aliases: [] }, { color: '#1F60C4', name: 'dark-blue', aliases: [] }, ], }, { name: 'purple', shades: [ { color: '#DEB6F2', name: 'super-light-purple', aliases: [] }, { color: '#CA95E5', name: 'light-purple', aliases: [] }, { color: '#B877D9', name: 'purple', aliases: [], primary: true }, { color: '#A352CC', name: 'semi-dark-purple', aliases: [] }, { color: '#8F3BB8', name: 'dark-purple', aliases: [] }, ], }, ]; } function getLightHues(): ThemeVizHue[] { return [ { name: 'red', shades: [ { color: '#FF7383', name: 'super-light-red' }, { color: '#F2495C', name: 'light-red' }, { color: '#E02F44', name: 'red', primary: true }, { color: '#C4162A', name: 'semi-dark-red' }, { color: '#AD0317', name: 'dark-red' }, ], }, { name: 'orange', shades: [ { color: '#FFB357', name: 'super-light-orange', aliases: [] }, { color: '#FF9830', name: 'light-orange', aliases: [] }, { color: '#FF780A', name: 'orange', aliases: [], primary: true }, { color: '#FA6400', name: 'semi-dark-orange', aliases: [] }, { color: '#E55400', name: 'dark-orange', aliases: [] }, ], }, { name: 'yellow', shades: [ { color: '#FFEE52', name: 'super-light-yellow', aliases: [] }, { color: '#FADE2A', name: 'light-yellow', aliases: [] }, { color: '#F2CC0C', name: 'yellow', aliases: [], primary: true }, { color: '#E0B400', name: 'semi-dark-yellow', aliases: [] }, { color: '#CC9D00', name: 'dark-yellow', aliases: [] }, ], }, { name: 'green', shades: [ { color: '#96D98D', name: 'super-light-green', aliases: [] }, { color: '#73BF69', name: 'light-green', aliases: [] }, { color: '#56A64B', name: 'green', aliases: [], primary: true }, { color: '#37872D', name: 'semi-dark-green', aliases: [] }, { color: '#19730E', name: 'dark-green', aliases: [] }, ], }, { name: 'blue', shades: [ { color: '#8AB8FF', name: 'super-light-blue', aliases: [] }, { color: '#5794F2', name: 'light-blue', aliases: [] }, { color: '#3274D9', name: 'blue', aliases: [], primary: true }, { color: '#1F60C4', name: 'semi-dark-blue', aliases: [] }, { color: '#1250B0', name: 'dark-blue', aliases: [] }, ], }, { name: 'purple', shades: [ { color: '#CA95E5', name: 'super-light-purple', aliases: [] }, { color: '#B877D9', name: 'light-purple', aliases: [] }, { color: '#A352CC', name: 'purple', aliases: [], primary: true }, { color: '#8F3BB8', name: 'semi-dark-purple', aliases: [] }, { color: '#7C2EA3', name: 'dark-purple', aliases: [] }, ], }, ]; } function getClassicPalette() { // Todo replace these with named colors (as many as possible) return [ 'green', // '#7EB26D', // 0: pale green 'semi-dark-yellow', // '#EAB839', // 1: mustard 'light-blue', // #6ED0E0', // 2: light blue 'semi-dark-orange', // '#EF843C', // 3: orange 'red', // '#E24D42', // 4: red 'blue', // #1F78C1', // 5: ocean 'purple', // '#BA43A9', // 6: purple '#705DA0', // 7: violet 'dark-green', // '#508642', // 8: dark green 'yellow', //'#CCA300', // 9: dark sand '#447EBC', '#C15C17', '#890F02', '#0A437C', '#6D1F62', '#584477', '#B7DBAB', '#F4D598', '#70DBED', '#F9BA8F', '#F29191', '#82B5D8', '#E5A8E2', '#AEA2E0', '#629E51', '#E5AC0E', '#64B0C8', '#E0752D', '#BF1B00', '#0A50A1', '#962D82', '#614D93', '#9AC48A', '#F2C96D', '#65C5DB', '#F9934E', '#EA6460', '#5195CE', '#D683CE', '#806EB7', '#3F6833', '#967302', '#2F575E', '#99440A', '#58140C', '#052B51', '#511749', '#3F2B5B', '#E0F9D7', '#FCEACA', '#CFFAFF', '#F9E2D2', '#FCE2DE', '#BADFF4', '#F9D9F9', '#DEDAF7', ]; } // Old hues // function getDarkHues(): ThemeVizHue[] { // return [ // { // name: 'red', // shades: [ // { name: 'red1', color: '#FFC2D4', aliases: ['super-light-red'] }, // { name: 'red2', color: '#FFA8C2', aliases: ['light-red'] }, // { name: 'red3', color: '#FF85A9', aliases: ['red'], primary: true }, // { name: 'red4', color: '#FF5286', aliases: ['semi-dark-red'] }, // { name: 'red5', color: '#E0226E', aliases: ['dark-red'] }, // ], // }, // { // name: 'orange', // shades: [ // { name: 'orange1', color: '#FFC0AD', aliases: ['super-light-orange'] }, // { name: 'orange2', color: '#FFA98F', aliases: ['light-orange'] }, // { name: 'orange3', color: '#FF825C', aliases: ['orange'], primary: true }, // { name: 'orange4', color: '#FF5F2E', aliases: ['semi-dark-orange'] }, // { name: 'orange5', color: '#E73903', aliases: ['dark-orange'] }, // ], // }, // { // name: 'yellow', // shades: [ // { name: 'yellow1', color: '#FFE68F', aliases: ['super-light-yellow'] }, // { name: 'yellow2', color: '#FAD34A', aliases: ['light-yellow'] }, // { name: 'yellow3', color: '#ECBB09', aliases: ['yellow'], primary: true }, // { name: 'yellow4', color: '#CFA302', aliases: ['semi-dark-yellow'] }, // { name: 'yellow5', color: '#AD8800', aliases: ['dark-yellow'] }, // ], // }, // { // name: 'green', // shades: [ // { name: 'green1', color: '#93ECCB', aliases: ['super-light-green'] }, // { name: 'green2', color: '#65DCB1', aliases: ['light-green'] }, // { name: 'green3', color: '#2DC88F', aliases: ['green'], primary: true }, // { name: 'green4', color: '#25A777', aliases: ['semi-dark-green'] }, // { name: 'green5', color: '#1B855E', aliases: ['dark-green'] }, // ], // }, // { // name: 'teal', // shades: [ // { name: 'teal1', color: '#73E7F7' }, // { name: 'teal2', color: '#2BD6EE' }, // { name: 'teal3', color: '#11BDD4', primary: true }, // { name: 'teal4', color: '#0EA0B4' }, // { name: 'teal5', color: '#077D8D' }, // ], // }, // { // name: 'blue', // shades: [ // { name: 'blue1', color: '#C2D7FF', aliases: ['super-light-blue'] }, // { name: 'blue2', color: '#A3C2FF', aliases: ['light-blue'] }, // { name: 'blue3', color: '#83ACFC', aliases: ['blue'], primary: true }, // { name: 'blue4', color: '#5D8FEF', aliases: ['semi-dark-blue'] }, // { name: 'blue5', color: '#3871DC', aliases: ['dark-blue'] }, // ], // }, // { // name: 'violet', // shades: [ // { name: 'violet1', color: '#DACCFF' }, // { name: 'violet2', color: '#C7B2FF' }, // { name: 'violet3', color: '#B094FF', primary: true }, // { name: 'violet4', color: '#9271EF' }, // { name: 'violet5', color: '#7E63CA' }, // ], // }, // { // name: 'purple', // shades: [ // { name: 'purple1', color: '#FFBDFF', aliases: ['super-light-purple'] }, // { name: 'purple2', color: '#F5A3F5', aliases: ['light-purple'] }, // { name: 'purple3', color: '#E48BE4', aliases: ['purple'], primary: true }, // { name: 'purple4', color: '#CA68CA', aliases: ['semi-dark-purple'] }, // { name: 'purple5', color: '#B545B5', aliases: ['dark-purple'] }, // ], // }, // ]; // } const nativeColorNames: Record<string, string> = { aliceblue: '#f0f8ff', antiquewhite: '#faebd7', aqua: '#00ffff', aquamarine: '#7fffd4', azure: '#f0ffff', beige: '#f5f5dc', bisque: '#ffe4c4', black: '#000000', blanchedalmond: '#ffebcd', blue: '#0000ff', blueviolet: '#8a2be2', brown: '#a52a2a', burlywood: '#deb887', cadetblue: '#5f9ea0', chartreuse: '#7fff00', chocolate: '#d2691e', coral: '#ff7f50', cornflowerblue: '#6495ed', cornsilk: '#fff8dc', crimson: '#dc143c', cyan: '#00ffff', darkblue: '#00008b', darkcyan: '#008b8b', darkgoldenrod: '#b8860b', darkgray: '#a9a9a9', darkgreen: '#006400', darkkhaki: '#bdb76b', darkmagenta: '#8b008b', darkolivegreen: '#556b2f', darkorange: '#ff8c00', darkorchid: '#9932cc', darkred: '#8b0000', darksalmon: '#e9967a', darkseagreen: '#8fbc8f', darkslateblue: '#483d8b', darkslategray: '#2f4f4f', darkturquoise: '#00ced1', darkviolet: '#9400d3', deeppink: '#ff1493', deepskyblue: '#00bfff', dimgray: '#696969', dodgerblue: '#1e90ff', firebrick: '#b22222', floralwhite: '#fffaf0', forestgreen: '#228b22', fuchsia: '#ff00ff', gainsboro: '#dcdcdc', ghostwhite: '#f8f8ff', gold: '#ffd700', goldenrod: '#daa520', gray: '#808080', green: '#008000', greenyellow: '#adff2f', honeydew: '#f0fff0', hotpink: '#ff69b4', 'indianred ': '#cd5c5c', indigo: '#4b0082', ivory: '#fffff0', khaki: '#f0e68c', lavender: '#e6e6fa', lavenderblush: '#fff0f5', lawngreen: '#7cfc00', lemonchiffon: '#fffacd', lightblue: '#add8e6', lightcoral: '#f08080', lightcyan: '#e0ffff', lightgoldenrodyellow: '#fafad2', lightgrey: '#d3d3d3', lightgreen: '#90ee90', lightpink: '#ffb6c1', lightsalmon: '#ffa07a', lightseagreen: '#20b2aa', lightskyblue: '#87cefa', lightslategray: '#778899', lightsteelblue: '#b0c4de', lightyellow: '#ffffe0', lime: '#00ff00', limegreen: '#32cd32', linen: '#faf0e6', magenta: '#ff00ff', maroon: '#800000', mediumaquamarine: '#66cdaa', mediumblue: '#0000cd', mediumorchid: '#ba55d3', mediumpurple: '#9370d8', mediumseagreen: '#3cb371', mediumslateblue: '#7b68ee', mediumspringgreen: '#00fa9a', mediumturquoise: '#48d1cc', mediumvioletred: '#c71585', midnightblue: '#191970', mintcream: '#f5fffa', mistyrose: '#ffe4e1', moccasin: '#ffe4b5', navajowhite: '#ffdead', navy: '#000080', oldlace: '#fdf5e6', olive: '#808000', olivedrab: '#6b8e23', orange: '#ffa500', orangered: '#ff4500', orchid: '#da70d6', palegoldenrod: '#eee8aa', palegreen: '#98fb98', paleturquoise: '#afeeee', palevioletred: '#d87093', papayawhip: '#ffefd5', peachpuff: '#ffdab9', peru: '#cd853f', pink: '#ffc0cb', plum: '#dda0dd', powderblue: '#b0e0e6', purple: '#800080', rebeccapurple: '#663399', red: '#ff0000', rosybrown: '#bc8f8f', royalblue: '#4169e1', saddlebrown: '#8b4513', salmon: '#fa8072', sandybrown: '#f4a460', seagreen: '#2e8b57', seashell: '#fff5ee', sienna: '#a0522d', silver: '#c0c0c0', skyblue: '#87ceeb', slateblue: '#6a5acd', slategray: '#708090', snow: '#fffafa', springgreen: '#00ff7f', steelblue: '#4682b4', tan: '#d2b48c', teal: '#008080', thistle: '#d8bfd8', tomato: '#ff6347', turquoise: '#40e0d0', violet: '#ee82ee', wheat: '#f5deb3', white: '#ffffff', whitesmoke: '#f5f5f5', yellow: '#ffff00', yellowgreen: '#9acd32', };
the_stack
import React, {CSSProperties} from 'react'; import {IssueEntity} from '../Type/IssueEntity'; import {View} from './View'; import {ClickView} from './ClickView'; import styled, {keyframes} from 'styled-components'; import {IconNameType} from '../Type/IconNameType'; import {color} from '../Style/color'; import {Icon} from './Icon'; import {Text} from './Text'; import {border, font, fontWeight, icon, iconFont, space} from '../Style/layout'; import {Image} from './Image'; import {appTheme} from '../Style/appTheme'; import {ColorUtil} from '../Util/ColorUtil'; import {GitHubUtil} from '../Util/GitHubUtil'; import {IssueRepo} from '../../Repository/IssueRepo'; import {DateUtil} from '../Util/DateUtil'; import {clipboard} from 'electron'; import {ContextMenu, ContextMenuType} from './ContextMenu'; import ReactDOM from 'react-dom'; import {IconButton} from './IconButton'; import {PlatformUtil} from '../Util/PlatformUtil'; import {UserIcon} from './UserIcon'; import {ShellUtil} from '../Util/ShellUtil'; type Props = { issue: IssueEntity; selected: boolean; fadeIn?: boolean; disableMenu?: boolean; slim?: boolean; scrollIntoViewIfNeededWithCenter: boolean; skipHandlerSameCheck: boolean; onSelect: (issue: IssueEntity) => void; onReadAll?: (issue: IssueEntity) => void; onReadCurrentAll?: (issue: IssueEntity) => void; onUnsubscribe?: (issue: IssueEntity) => void | null; onToggleMark?: (issue: IssueEntity) => void; onToggleArchive?: (issue: IssueEntity) => void; onToggleRead?: (issue: IssueEntity) => void; onToggleIssueType?: (issue: IssueEntity) => void; onToggleProject?: (issue: IssueEntity, projectName: string, projectColumn: string) => void; onToggleMilestone?: (issue: IssueEntity) => void; onToggleLabel?: (issue: IssueEntity, label: string) => void; onToggleAuthor?: (issue: IssueEntity) => void; onToggleAssignee?: (issue: IssueEntity, assignee: string) => void; onToggleReviewRequested?: (issue: IssueEntity, loginName: string) => void; onToggleReview?: (issue: IssueEntity, loginName: string) => void; onToggleRepoOrg?: (issue: IssueEntity) => void; onToggleRepoName?: (issue: IssueEntity) => void; onToggleIssueNumber?: (issue: IssueEntity) => void; onCreateFilterStream?: (issue: IssueEntity) => void; className?: string; } type State = { showMenu: boolean; } export class IssueRow extends React.Component<Props, State> { state: State = { showMenu: false, } private contextMenus: ContextMenuType[] = []; private contextMenuPos: {left: number; top: number}; private contextMenuHorizontalLeft: boolean; private contextMenuHideBrowserView: boolean; shouldComponentUpdate(nextProps: Readonly<Props>, nextState: Readonly<State>, _nextContext: any): boolean { if (nextState.showMenu !== this.state.showMenu) return true; if (nextProps.issue !== this.props.issue) return true; if (nextProps.issue.read_at !== this.props.issue.read_at) return true; if (nextProps.issue.closed_at !== this.props.issue.closed_at) return true; if (nextProps.issue.marked_at !== this.props.issue.marked_at) return true; if (nextProps.issue.archived_at !== this.props.issue.archived_at) return true; if (nextProps.issue.updated_at !== this.props.issue.updated_at) return true; if (nextProps.issue.merged_at !== this.props.issue.merged_at) return true; if (nextProps.selected !== this.props.selected) return true; if (nextProps.fadeIn !== this.props.fadeIn) return true; if (nextProps.className !== this.props.className) return true; if (nextProps.slim !== this.props.slim) return true; if (nextProps.scrollIntoViewIfNeededWithCenter !== this.props.scrollIntoViewIfNeededWithCenter) return true; // handlerは基本的に毎回新しく渡ってくるので、それをチェックしてしまうと、毎回renderすることになる // なので、明示的にsame check指示されたときのみチェックする if (!nextProps.skipHandlerSameCheck) { if (nextProps.onSelect !== this.props.onSelect) return true; if (nextProps.onReadAll !== this.props.onReadAll) return true; if (nextProps.onReadCurrentAll !== this.props.onReadCurrentAll) return true; if (nextProps.onUnsubscribe !== this.props.onUnsubscribe) return true; if (nextProps.onToggleMark !== this.props.onToggleMark) return true; if (nextProps.onToggleArchive !== this.props.onToggleArchive) return true; if (nextProps.onToggleRead !== this.props.onToggleRead) return true; if (nextProps.onToggleIssueType !== this.props.onToggleIssueType) return true; if (nextProps.onToggleProject !== this.props.onToggleProject) return true; if (nextProps.onToggleMilestone !== this.props.onToggleMilestone) return true; if (nextProps.onToggleLabel !== this.props.onToggleLabel) return true; if (nextProps.onToggleAuthor !== this.props.onToggleAuthor) return true; if (nextProps.onToggleAssignee !== this.props.onToggleAssignee) return true; if (nextProps.onToggleReviewRequested !== this.props.onToggleReviewRequested) return true; if (nextProps.onToggleReview !== this.props.onToggleReview) return true; if (nextProps.onToggleRepoOrg !== this.props.onToggleRepoOrg) return true; if (nextProps.onToggleRepoName !== this.props.onToggleRepoName) return true; if (nextProps.onToggleIssueNumber !== this.props.onToggleIssueNumber) return true; if (nextProps.onCreateFilterStream !== this.props.onCreateFilterStream) return true; } return false; } componentDidUpdate(prevProps: Readonly<Props>, _prevState: Readonly<State>, _snapshot?: any) { // 選択されたときには強制的に表示領域に入るようにする if (!prevProps.selected && this.props.selected) { const el = ReactDOM.findDOMNode(this) as HTMLDivElement; // @ts-ignore el.scrollIntoViewIfNeeded(this.props.scrollIntoViewIfNeededWithCenter); } } private isOpenRequest(ev: React.MouseEvent): boolean { return !!(ev.shiftKey || ev.metaKey) } private isFilterToggleRequest(ev: React.MouseEvent): boolean { return ev.altKey; } private openPath(path: string) { const urlObj = new URL(this.props.issue.html_url); const url = `${urlObj.origin}${path}`; ShellUtil.openExternal(url); } private openIssues() { const issue = this.props.issue; const {state} = GitHubUtil.getIssueTypeInfo(issue); const query = encodeURIComponent(`is:${issue.type} is:${state}`); const path = `/${issue.repo}/${issue.type === 'issue' ? 'issues' : 'pulls'}?q=${query}`; this.openPath(path); } private openProject(projectUrl: string) { ShellUtil.openExternal(projectUrl); } private openMilestone() { const url = this.props.issue.value.milestone.html_url; ShellUtil.openExternal(url); } private openLabel(label: string) { const path = `/${this.props.issue.repo}/labels/${label}`; this.openPath(path); } private openUser(loginName: string) { if (loginName.includes('/')) { // team name const tmp = loginName.split('/'); const path = `/orgs/${tmp[0]}/teams/${tmp[1]}`; this.openPath(path); } else { const path = `/${loginName}`; this.openPath(path); } } private openOrg() { const path = `/${this.props.issue.user}`; this.openPath(path); } private openRepo() { const path = `/${this.props.issue.repo}`; this.openPath(path); } private openIssue() { ShellUtil.openExternal(this.props.issue.html_url); } private handleContextMenu(ev: React.MouseEvent, horizontalLeft: boolean) { if (this.props.disableMenu) return; // todo: だいぶ雑な実装なので適切に計算するようにしたい const issueRect = (ReactDOM.findDOMNode(this) as HTMLElement).getBoundingClientRect(); if (horizontalLeft) { this.contextMenuHorizontalLeft = horizontalLeft; this.contextMenuHideBrowserView = false; } else { this.contextMenuHorizontalLeft = false; if (ev.clientX - issueRect.x < issueRect.width / 4) { // 左1/4をクリックしてたらブラウザを隠さなくても良い this.contextMenuHideBrowserView = false; } else { this.contextMenuHideBrowserView = true; } } const hideUnsubscribe = !this.props.onUnsubscribe; // const isRead = IssueRepo.isRead(this.props.issue); // const isBookmark = !!this.props.issue.marked_at; // const isArchived = !!this.props.issue.archived_at; this.contextMenus = [ // {label: isRead? 'Mark as Unread' : 'Mark as Read', icon: isRead? 'clipboard-outline' : 'clipboard-check', handler: () => this.handleToggleRead()}, // {label: isBookmark? 'Remove from Bookmark' : 'Add to Bookmark', icon: isBookmark? 'bookmark-outline' : 'bookmark', handler: () => this.handleToggleBookmark()}, // {label: isArchived? 'Remove from Archive' : 'Move to Archive', icon: isArchived? 'archive-outline' : 'archive', handler: () => this.handleToggleArchive()}, // {type: 'separator', hide: hideUnsubscribe}, {label: 'Unsubscribe', icon: 'volume-off', handler: () => this.handleUnsubscribe(), hide: hideUnsubscribe}, {type: 'separator', hide: hideUnsubscribe}, {label: 'Copy as URL', icon: 'content-copy', handler: () => this.handleCopyURL()}, {label: 'Copy as JSON', icon: 'code-json', handler: () => this.handleCopyValue()}, {type: 'separator'}, {label: 'Open with Browser', subLabel: PlatformUtil.isMac() ? '(⌘ Click)' : '(Shift Click)', icon: 'open-in-new', handler: () => this.handleOpenURL()}, {type: 'separator'}, {label: 'Mark All Current as Read', icon: 'check', handler: () => this.handleReadCurrentAll()}, {label: 'Mark All as Read', icon: 'check-all', handler: () => this.handleReadAll()}, ]; if (this.props.onCreateFilterStream) { this.contextMenus.push( {type: 'separator'}, {label: 'Create Filter Stream', icon: 'file-tree', handler: () => this.handleCreateFilterStream()}, ); } this.contextMenuPos = {top: ev.clientY, left: ev.clientX}; this.setState({showMenu: true}); } private handleContextMenuIssueType(ev: React.MouseEvent) { if (this.props.disableMenu) return; if (this.isFilterToggleRequest(ev)) { this.props.onToggleIssueType(this.props.issue); return; } if (this.isOpenRequest(ev)) { this.openIssue(); return; } this.contextMenus = [ {label: 'Filter Issue State', subLabel: `(${PlatformUtil.select('⌥', 'Alt')} Click)`, icon: 'filter-outline', handler: () => this.props.onToggleIssueType(this.props.issue)}, {type: 'separator'}, {label: 'Open Issues', subLabel: `(${PlatformUtil.select('⌘', 'Shift')} Click)`, icon: 'open-in-new', handler: () => this.openIssues()}, ]; this.contextMenuHideBrowserView = true; this.contextMenuHorizontalLeft = false; this.contextMenuPos = {top: ev.clientY, left: ev.clientX}; this.setState({showMenu: true}); } private handleContextMenuProject(ev: React.MouseEvent, projectName: string, projectColumn: string, projectUrl: string) { if (this.props.disableMenu) return; if (this.isFilterToggleRequest(ev)) { this.props.onToggleProject(this.props.issue, projectName, projectColumn); return; } if (this.isOpenRequest(ev)) { this.openProject(projectUrl); return; } this.contextMenus = [ {label: 'Filter Project', subLabel: `(${PlatformUtil.select('⌥', 'Alt')} Click)`, icon: 'filter-outline', handler: () => this.props.onToggleProject(this.props.issue, projectName, projectColumn)}, {type: 'separator'}, {label: 'Open Project', subLabel: `(${PlatformUtil.select('⌘', 'Shift')} Click)`, icon: 'open-in-new', handler: () => this.openProject(projectUrl)}, ]; this.contextMenuHideBrowserView = true; this.contextMenuHorizontalLeft = false; this.contextMenuPos = {top: ev.clientY, left: ev.clientX}; this.setState({showMenu: true}); } private handleContextMenuMilestone(ev: React.MouseEvent) { if (this.props.disableMenu) return; if (this.isFilterToggleRequest(ev)) { this.props.onToggleMilestone(this.props.issue); return; } if (this.isOpenRequest(ev)) { this.openMilestone(); return; } this.contextMenus = [ {label: 'Filter Milestone', subLabel: `(${PlatformUtil.select('⌥', 'Alt')} Click)`, icon: 'filter-outline', handler: () => this.props.onToggleMilestone(this.props.issue)}, {type: 'separator'}, {label: 'Open Milestone', subLabel: `(${PlatformUtil.select('⌘', 'Shift')} Click)`, icon: 'open-in-new', handler: () => this.openMilestone()}, ]; this.contextMenuHideBrowserView = true; this.contextMenuHorizontalLeft = false; this.contextMenuPos = {top: ev.clientY, left: ev.clientX}; this.setState({showMenu: true}); } private handleContextMenuLabel(ev: React.MouseEvent, label: string) { if (this.props.disableMenu) return; if (this.isFilterToggleRequest(ev)) { this.props.onToggleLabel(this.props.issue, label); return; } if (this.isOpenRequest(ev)) { this.openLabel(label); return; } this.contextMenus = [ {label: 'Filter Label', subLabel: `(${PlatformUtil.select('⌥', 'Alt')} Click)`, icon: 'filter-outline', handler: () => this.props.onToggleLabel(this.props.issue, label)}, {type: 'separator'}, {label: 'Open Label', subLabel: `(${PlatformUtil.select('⌘', 'Shift')} Click)`, icon: 'open-in-new', handler: () => this.openLabel(label)}, ]; this.contextMenuHideBrowserView = true; this.contextMenuHorizontalLeft = false; this.contextMenuPos = {top: ev.clientY, left: ev.clientX}; this.setState({showMenu: true}); } private handleContextMenuAuthor(ev: React.MouseEvent) { if (this.props.disableMenu) return; if (this.isFilterToggleRequest(ev)) { this.props.onToggleAuthor(this.props.issue); return; } if (this.isOpenRequest(ev)) { this.openUser(this.props.issue.author); return; } this.contextMenus = [ {label: 'Filter Author', subLabel: `(${PlatformUtil.select('⌥', 'Alt')} Click)`, icon: 'filter-outline', handler: () => this.props.onToggleAuthor(this.props.issue)}, {type: 'separator'}, {label: 'Open Author', subLabel: `(${PlatformUtil.select('⌘', 'Shift')} Click)`, icon: 'open-in-new', handler: () => this.openUser(this.props.issue.author)}, ]; this.contextMenuHideBrowserView = true; this.contextMenuHorizontalLeft = false; this.contextMenuPos = {top: ev.clientY, left: ev.clientX}; this.setState({showMenu: true}); } private handleContextMenuAssignee(ev: React.MouseEvent, loginName: string) { if (this.props.disableMenu) return; if (this.isFilterToggleRequest(ev)) { this.props.onToggleAssignee(this.props.issue, loginName); return; } if (this.isOpenRequest(ev)) { this.openUser(loginName); return; } this.contextMenus = [ {label: 'Filter Assignee', subLabel: `(${PlatformUtil.select('⌥', 'Alt')} Click)`, icon: 'filter-outline', handler: () => this.props.onToggleAssignee(this.props.issue, loginName)}, {type: 'separator'}, {label: 'Open Assignee', subLabel: `(${PlatformUtil.select('⌘', 'Shift')} Click)`, icon: 'open-in-new', handler: () => this.openUser(loginName)}, ]; this.contextMenuHideBrowserView = true; this.contextMenuHorizontalLeft = false; this.contextMenuPos = {top: ev.clientY, left: ev.clientX}; this.setState({showMenu: true}); } private handleContextMenuReviewRequested(ev: React.MouseEvent, loginName: string) { if (this.props.disableMenu) return; if (this.isFilterToggleRequest(ev)) { this.props.onToggleReviewRequested(this.props.issue, loginName); return; } if (this.isOpenRequest(ev)) { this.openUser(loginName); return; } this.contextMenus = [ {label: 'Filter Review Requested', subLabel: `(${PlatformUtil.select('⌥', 'Alt')} Click)`, icon: 'filter-outline', handler: () => this.props.onToggleReviewRequested(this.props.issue, loginName)}, {type: 'separator'}, {label: 'Open Review Requested', subLabel: `(${PlatformUtil.select('⌘', 'Shift')} Click)`, icon: 'open-in-new', handler: () => this.openUser(loginName)}, ]; this.contextMenuHideBrowserView = true; this.contextMenuHorizontalLeft = false; this.contextMenuPos = {top: ev.clientY, left: ev.clientX}; this.setState({showMenu: true}); } private handleContextMenuReview(ev: React.MouseEvent, loginName: string) { if (this.props.disableMenu) return; if (this.isFilterToggleRequest(ev)) { this.props.onToggleReview(this.props.issue, loginName); return; } if (this.isOpenRequest(ev)) { this.openUser(loginName); return; } this.contextMenus = [ {label: 'Filter Review', subLabel: `(${PlatformUtil.select('⌥', 'Alt')} Click)`, icon: 'filter-outline', handler: () => this.props.onToggleReview(this.props.issue, loginName)}, {type: 'separator'}, {label: 'Open Review', subLabel: `(${PlatformUtil.select('⌘', 'Shift')} Click)`, icon: 'open-in-new', handler: () => this.openUser(loginName)}, ]; this.contextMenuHideBrowserView = true; this.contextMenuHorizontalLeft = false; this.contextMenuPos = {top: ev.clientY, left: ev.clientX}; this.setState({showMenu: true}); } private handleContextMenuOrg(ev: React.MouseEvent) { if (this.props.disableMenu) return; if (this.isFilterToggleRequest(ev)) { this.props.onToggleRepoOrg(this.props.issue); return; } if (this.isOpenRequest(ev)) { this.openOrg(); return; } this.contextMenus = [ {label: 'Filter Org/User', subLabel: `(${PlatformUtil.select('⌥', 'Alt')} Click)`, icon: 'filter-outline', handler: () => this.props.onToggleRepoOrg(this.props.issue)}, {type: 'separator'}, {label: 'Open Org/User', subLabel: `(${PlatformUtil.select('⌘', 'Shift')} Click)`, icon: 'open-in-new', handler: () => this.openOrg()}, ]; this.contextMenuHideBrowserView = true; this.contextMenuHorizontalLeft = false; this.contextMenuPos = {top: ev.clientY, left: ev.clientX}; this.setState({showMenu: true}); } private handleContextMenuRepo(ev: React.MouseEvent) { if (this.props.disableMenu) return; if (this.isFilterToggleRequest(ev)) { this.props.onToggleRepoName(this.props.issue); return; } if (this.isOpenRequest(ev)) { this.openRepo(); return; } this.contextMenus = [ {label: 'Filter Repository', subLabel: `(${PlatformUtil.select('⌥', 'Alt')} Click)`, icon: 'filter-outline', handler: () => this.props.onToggleRepoName(this.props.issue)}, {type: 'separator'}, {label: 'Open Repository', subLabel: `(${PlatformUtil.select('⌘', 'Shift')} Click)`, icon: 'open-in-new', handler: () => this.openRepo()}, ]; this.contextMenuHideBrowserView = true; this.contextMenuHorizontalLeft = false; this.contextMenuPos = {top: ev.clientY, left: ev.clientX}; this.setState({showMenu: true}); } private handleContextMenuNumber(ev: React.MouseEvent) { if (this.props.disableMenu) return; if (this.isFilterToggleRequest(ev)) { this.props.onToggleIssueNumber(this.props.issue); return; } if (this.isOpenRequest(ev)) { this.openIssue(); return; } this.contextMenus = [ {label: 'Filter Number', subLabel: `(${PlatformUtil.select('⌥', 'Alt')} Click)`, icon: 'filter-outline', handler: () => this.props.onToggleIssueNumber(this.props.issue)}, {type: 'separator'}, {label: 'Open Issue/PR', subLabel: `(${PlatformUtil.select('⌘', 'Shift')} Click)`, icon: 'open-in-new', handler: () => this.openIssue()}, ]; this.contextMenuHideBrowserView = true; this.contextMenuHorizontalLeft = false; this.contextMenuPos = {top: ev.clientY, left: ev.clientX}; this.setState({showMenu: true}); } private handleSelect(ev: React.MouseEvent) { if (this.isOpenRequest(ev)) { ShellUtil.openExternal(this.props.issue.value.html_url); return; } this.props.onSelect(this.props.issue); } private handleToggleRead() { this.props.onToggleRead?.(this.props.issue); } private handleToggleBookmark() { this.props.onToggleMark?.(this.props.issue); } private handleToggleArchive() { this.props.onToggleArchive?.(this.props.issue); } private handleUnsubscribe() { this.props.onUnsubscribe?.(this.props.issue); } private handleReadCurrentAll() { this.props.onReadCurrentAll?.(this.props.issue); } private handleReadAll() { this.props.onReadAll?.(this.props.issue); } private handleOpenURL() { ShellUtil.openExternal(this.props.issue.value.html_url); } private handleCopyURL() { clipboard.writeText(this.props.issue.value.html_url); } private handleCopyValue() { clipboard.writeText(JSON.stringify(this.props.issue.value, null, 2)); } private handleCreateFilterStream() { this.props.onCreateFilterStream?.(this.props.issue); } render() { const readClassName = IssueRepo.isRead(this.props.issue) ? 'issue-read' : 'issue-unread'; const selectedClassName = this.props.selected ? 'issue-selected' : 'issue-unselected'; const fadeInClassName = this.props.fadeIn ? 'issue-fadein' : ''; const slimClassName = this.props.slim ? 'issue-slim' : '' return ( <Root className={`${this.props.className} issue-row ${readClassName} ${selectedClassName} ${fadeInClassName} ${slimClassName}`} onClick={ev => this.handleSelect(ev)} onContextMenu={(ev) => this.handleContextMenu(ev, false)} > {this.renderBody()} {this.renderAttributes()} {this.renderUsers()} {this.renderFooter()} {this.renderBookmark()} {this.renderActions()} <ContextMenu show={this.state.showMenu} onClose={() => this.setState({showMenu: false})} menus={this.contextMenus} pos={this.contextMenuPos} hideBrowserView={this.contextMenuHideBrowserView} horizontalLeft={this.contextMenuHorizontalLeft} /> </Root> ); } private renderBody() { const issue = this.props.issue; const selected = this.props.selected; const {icon: iconName, color: iconColor, label} = GitHubUtil.getIssueTypeInfo(issue); const style: CSSProperties = {}; if (selected) style.background = iconColor; let warningMergeable; if (issue.value.mergeable === 'CONFLICTING') { warningMergeable = <WarningMergeableIcon name='exclamation-thick' color={color.white} size={iconFont.nano}/> } return ( <Body> <IssueType // onClick={ev => this.handleClickIssueType(ev)} onClick={ev => this.handleContextMenuIssueType(ev)} onContextMenu={ev => this.handleContextMenuIssueType(ev)} style={style} title={`${label} ${issue.type === 'issue' ? 'Issue' : 'PR'} (Ctrl + Click)`} > <Icon name={iconName} color={selected ? color.white : iconColor} size={selected ? 20 : 26}/> {warningMergeable} </IssueType> <Title> <TitleText>{this.props.issue.value.title}</TitleText> </Title> </Body> ); } private renderAttributes() { return ( <Attributes> {this.renderProjects()} {this.renderMilestone()} {this.renderLabels()} </Attributes> ); } private renderProjects() { const projects = this.props.issue.value.projects; if (!projects?.length) return; const projectViews = projects.map((project, index) => { const label = `${project.name}:${project.column}` return ( <Project // onClick={(ev) => this.handleClickProject(ev, project.name, project.column, project.url)} onClick={ev => this.handleContextMenuProject(ev, project.name, project.column, project.url)} onContextMenu={ev => this.handleContextMenuProject(ev, project.name, project.column, project.url)} title={`${label} (Ctrl + Click)`} key={index} > <Icon name='rocket-launch-outline' size={iconFont.small}/> <ProjectText singleLine={true}>{label}</ProjectText> </Project> ); }); return ( <React.Fragment> {projectViews} </React.Fragment> ); } private renderMilestone() { const milestone = this.props.issue.value.milestone; if (!milestone) return; return ( <Milestone // onClick={(ev) => this.handleClickMilestone(ev)} onClick={ev => this.handleContextMenuMilestone(ev)} onContextMenu={ev => this.handleContextMenuMilestone(ev)} title={`${milestone.title} (Ctrl + Click)`} > <Icon name='flag-variant' size={iconFont.small}/> <MilestoneText singleLine={true}>{milestone.title}</MilestoneText> </Milestone> ); } private renderLabels() { const labels = this.props.issue.value.labels; if (!labels?.length) return; const labelViews = labels.map((label, index) => { const textColor = ColorUtil.suitTextColor(label.color); return ( <Label // onClick={(ev) => this.handleClickLabel(ev, label.name)} onClick={ev => this.handleContextMenuLabel(ev, label.name)} onContextMenu={ev => this.handleContextMenuLabel(ev, label.name)} title={`${label.name} (Ctrl + Click)`} key={index} style={{background: `#${label.color}`}} > <LabelText singleLine={true} style={{color: `#${textColor}`}}>{label.name}</LabelText> </Label> ); }); return ( <React.Fragment> {labelViews} </React.Fragment> ); } private renderUsers() { const updated = DateUtil.localToString(new Date(this.props.issue.value.updated_at)); const read = DateUtil.localToString(new Date(this.props.issue.read_at)); const iconColor = this.props.selected ? color.white : appTheme().icon.soft; return ( <Users> <Author // onClick={(ev) => this.handleClickAuthor(ev)} onClick={ev => this.handleContextMenuAuthor(ev)} onContextMenu={ev => this.handleContextMenuAuthor(ev)} title={`Author ${this.props.issue.author} (Ctrl + Click)`} > <Image source={{url: this.props.issue.value.user.avatar_url}}/> </Author> {this.renderAssignees()} <View style={{flex: 1}}/> {this.renderReview()} <CommentCount title={`Updated at ${updated}\n Read at ${read}`}> <Icon name='comment-text-outline' size={iconFont.tiny} color={iconColor}/> <CommentCountText>{this.props.issue.value.comments}</CommentCountText> </CommentCount> </Users> ); } private renderAssignees() { const assignees = this.props.issue.value.assignees; if (!assignees?.length) return; const assigneeViews = assignees.map((assignee, index) => { return ( <Assignee // onClick={(ev) => this.handleClickAssignee(ev, assignee.login)} onClick={ev => this.handleContextMenuAssignee(ev, assignee.login)} onContextMenu={ev => this.handleContextMenuAssignee(ev, assignee.login)} key={index} title={`Assign: ${assignee.login} (Ctrl + Click)`} > <Image source={{url: assignee.avatar_url}}/> </Assignee> ) }); return ( <React.Fragment> <AssigneeArrow>→</AssigneeArrow> {assigneeViews} </React.Fragment> ); } private renderReview() { const author = this.props.issue.author; const reviews = this.props.issue.value.reviews ?.filter(review => review.login !== author) ?.sort((a, b) => b.state > a.state ? 1 : -1); // 'COMMENTED', 'CHANGES_REQUESTED', 'APPROVED' の順番に表示する const reviewRequested = this.props.issue.value.requested_reviewers; if (!reviewRequested?.length && !reviews?.length) return; const doneReviewers = reviews?.map((review, index) => { const className = `issue-row-review-${review.state}`; const iconName: IconNameType = review.state === 'APPROVED' ? 'check-bold' : review.state === 'CHANGES_REQUESTED' ? 'exclamation-thick' : 'plus-thick'; return ( <Reviewer // onClick={(ev) => this.handleClickReview(ev, review.login)} onClick={ev => this.handleContextMenuReview(ev, review.login)} onContextMenu={ev => this.handleContextMenuReview(ev, review.login)} key={index} > <UserIcon title={`Review: ${review.login} (Ctrl + Click)`} userName={review.login} iconUrl={review.avatar_url} size={icon.small2} /> <ReviewStateMark className={className}> <Icon name={iconName} size={iconFont.nano} color={color.white}/> </ReviewStateMark> </Reviewer> ); }); const reviewLoginNames = reviews?.map(review => review.login) || []; const reqReviewers = reviewRequested?.filter(req => !reviewLoginNames.includes(req.login)).map((reviewRequested, index) => { return ( <Reviewer // onClick={(ev) => this.handleClickReviewRequested(ev, reviewRequested.login)} onClick={ev => this.handleContextMenuReviewRequested(ev, reviewRequested.login)} onContextMenu={ev => this.handleContextMenuReviewRequested(ev, reviewRequested.login)} key={index} className='issue-row-review-requested' > <UserIcon title={`Review Requested: ${reviewRequested.login} (Ctrl + Click)`} userName={reviewRequested.login} iconUrl={reviewRequested.avatar_url} size={icon.small2} /> <ReviewStateMark className='issue-row-review-requested'> <Icon name='dots-horizontal' size={iconFont.nano} color={color.white}/> </ReviewStateMark> </Reviewer> ); }); return ( <React.Fragment> {reqReviewers} {doneReviewers} </React.Fragment> ); } private renderFooter() { const {repoOrg, repoName} = GitHubUtil.getInfo(this.props.issue.value.url); const date = new Date(this.props.issue.value.updated_at); const updated = DateUtil.localToString(date); const read = DateUtil.localToString(new Date(this.props.issue.read_at)); let privateIcon; if (this.props.issue.repo_private) { const iconColor = this.props.selected ? color.white : appTheme().icon.soft; privateIcon = ( <PrivateIconWrap> <Icon name='lock-outline' size={iconFont.tiny} color={iconColor}/> </PrivateIconWrap> ); } return ( <Footer> {privateIcon} <RepoName> <ClickView onClick={(ev) => this.handleContextMenuOrg(ev)} onContextMenu={ev => this.handleContextMenuOrg(ev)} title={`${repoOrg} (Ctrl + Click)`}> <RepoNameText singleLine={true}>{repoOrg}</RepoNameText> </ClickView> <ClickView onClick={(ev) => this.handleContextMenuRepo(ev)} onContextMenu={ev => this.handleContextMenuRepo(ev)} title={`${repoName} (Ctrl + Click)`}> <RepoNameText singleLine={true}>/{repoName}</RepoNameText> </ClickView> <Number onClick={(ev) => this.handleContextMenuNumber(ev)} onContextMenu={ev => this.handleContextMenuNumber(ev)} title={`#${this.props.issue.number} (Ctrl + Click)`}> <NumberText>#{this.props.issue.value.number}</NumberText> </Number> </RepoName> <View style={{flex: 1}}/> <UpdatedAt title={`Updated at ${updated}\n Read at ${read}`}> <UpdatedAtText singleLine={true}>{DateUtil.fromNow(date)}</UpdatedAtText> </UpdatedAt> </Footer> ); } private renderBookmark() { if (!this.props.issue.marked_at) return null; return ( <BookmarkWrap onClick={() => this.handleToggleBookmark()} title='Remove from Bookmark' name='bookmark' color={this.props.selected ? color.white : appTheme().accent.normal} /> ); } private renderActions() { if (this.props.disableMenu) return; const readIconName: IconNameType = IssueRepo.isRead(this.props.issue) ? 'clipboard-check' : 'clipboard-outline'; const markIconName: IconNameType = this.props.issue.marked_at ? 'bookmark' : 'bookmark-outline'; const archiveIconName: IconNameType = this.props.issue.archived_at ? 'archive' : 'archive-outline'; return ( <Actions> <Action onClick={() => this.handleToggleRead()} name={readIconName} title={`${IssueRepo.isRead(this.props.issue) ? 'Mark as Unread' : 'Mark as Read'}`} color={appTheme().icon.soft} size={iconFont.small} /> <Action onClick={() => this.handleToggleBookmark()} name={markIconName} title={`${this.props.issue.marked_at ? 'Remove from Bookmark' : 'Add to Bookmark'}`} color={appTheme().icon.soft} size={iconFont.small} /> <Action onClick={() => this.handleToggleArchive()} name={archiveIconName} title={`${this.props.issue.archived_at ? 'Remove from Archive' : 'Move to Archive'}`} color={appTheme().icon.soft} size={iconFont.small} /> <Action onClick={(ev) => this.handleContextMenu(ev, true)} name='dots-vertical' color={appTheme().icon.soft} size={iconFont.small} style={{marginLeft: 0}} /> </Actions> ); } } const fadein = keyframes` from { opacity: 0.2; } to { opacity: 1; } `; const Root = styled(ClickView)` position: relative; border-bottom: solid ${border.medium}px ${() => appTheme().border.normal}; padding: ${space.medium}px; &.issue-unread { background: ${() => appTheme().issue.unreadBg}; } &.issue-read { background: ${() => appTheme().issue.readBg}; } &.issue-selected { background: ${() => appTheme().accent.normal}; } &.issue-unselected { } &.issue-fadein { animation: ${fadein} 1s; } `; const PrivateIconWrap = styled(View)` padding-bottom: ${space.tiny}px; padding-right: ${space.tiny}px; align-self: flex-end; `; // body const Body = styled(View)` flex-direction: row; width: 100%; .issue-slim & { padding-bottom: ${space.medium}px; } `; const IssueType = styled(ClickView)` position: relative; border-radius: 100px; width: 26px; height: 26px; align-items: center; justify-content: center; overflow: visible; &:hover { opacity: 0.7; } `; const WarningMergeableIcon = styled(Icon)` position: absolute; bottom: -4px; right: -4px; width: 18px !important; height: 18px !important; border-radius: 100px; background: ${color.issue.warningMergeable}; border: solid ${border.large}px ${() => appTheme().bg.primary}; `; const Title = styled(View)` flex: 1; min-height: 40px; padding-left: ${space.medium}px; padding-right: ${space.medium}px; .issue-slim & { min-height: initial; } `; const TitleText = styled(Text)` .issue-unread & { font-weight: ${fontWeight.bold}; } .issue-read & { color: ${() => appTheme().issue.readTitle}; font-weight: ${fontWeight.thin}; } .issue-selected & { color: ${color.white}; } `; // attributes const Attributes = styled(View)` flex-direction: row; align-items: center; flex-wrap: wrap; padding-top: ${space.medium}px; .issue-slim & { display: none; } `; const Project = styled(ClickView)` flex-direction: row; align-items: center; background: ${() => appTheme().bg.primary}; border: solid ${border.medium}px ${() => appTheme().border.bold}; border-radius: 4px; padding: 0 ${space.small}px; margin-right: ${space.medium}px; margin-bottom: ${space.medium}px; &:hover { opacity: 0.7; } .issue-selected & { opacity: 0.8; } `; const ProjectText = styled(Text)` font-size: ${font.small}px; font-weight: ${fontWeight.softBold}; padding-left: ${space.tiny}px; max-width: 100px; `; const Milestone = styled(ClickView)` flex-direction: row; align-items: center; background: ${() => appTheme().bg.primary}; border: solid ${border.medium}px ${() => appTheme().border.bold}; border-radius: 4px; padding: 0 ${space.small}px; margin-right: ${space.medium}px; margin-bottom: ${space.medium}px; &:hover { opacity: 0.7; } .issue-selected & { opacity: 0.8; } `; const MilestoneText = styled(Text)` font-size: ${font.small}px; font-weight: ${fontWeight.softBold}; max-width: 100px; `; const Label = styled(ClickView)` border-radius: 4px; padding: 0 ${space.small}px; margin-right: ${space.medium}px; margin-bottom: ${space.medium}px; &:hover { opacity: 0.7; } .issue-selected & { opacity: 0.8; } `; const LabelText = styled(Text)` font-size: ${font.small}px; font-weight: ${fontWeight.softBold}; max-width: 100px; `; // users const Users = styled(View)` flex-direction: row; align-items: center; padding-top: ${space.medium}px; overflow: visible; flex-wrap: wrap; .issue-slim & { display: none; } `; const Author = styled(ClickView)` width: ${icon.small2}px; height: ${icon.small2}px; border-radius: 100%; &:hover { opacity: 0.7; } `; const Assignee = styled(ClickView)` width: ${icon.small2}px; height: ${icon.small2}px; border-radius: 100%; margin-right: ${space.small}px; &:hover { opacity: 0.7; } `; const AssigneeArrow = styled(Text)` font-size: ${font.small}px; margin: 0 ${space.small}px; font-weight: ${fontWeight.bold}; .issue-selected & { color: ${color.white}; } `; const Reviewer = styled(ClickView)` position: relative; margin-right: ${space.small2}px; margin-left: ${space.small}px; /* review state markを表示するため */ overflow: visible; &:hover { opacity: 0.7; } `; const ReviewStateMark = styled(View)` position: absolute; bottom: -4px; right: -6px; border: solid ${border.large}px ${() => appTheme().bg.primary}; border-radius: 100px; &.issue-row-review-requested { background: ${color.issue.review.reviewRequested}; } &.issue-row-review-APPROVED { background: ${color.issue.review.approved}; } &.issue-row-review-COMMENTED { background: ${color.issue.review.commented}; } &.issue-row-review-CHANGES_REQUESTED { background: ${color.issue.review.changesRequested}; } `; // footer const Footer = styled(View)` flex-direction: row; align-items: center; padding-top: ${space.medium}px; .issue-slim & { padding-top: 0; } `; const RepoName = styled(View)` flex-direction: row; align-items: center; `; const RepoNameText = styled(Text)` font-size: ${font.small}px; color: ${() => appTheme().text.tiny}; &:hover { opacity: 0.7; } .issue-read & { font-weight: ${fontWeight.thin}; } .issue-selected & { color: ${color.white}; } `; const Number = styled(ClickView)` padding-left: ${space.small}px; `; const NumberText = styled(Text)` font-size: ${font.small}px; color: ${() => appTheme().text.tiny}; &:hover { opacity: 0.7; } .issue-read & { font-weight: ${fontWeight.thin}; } .issue-selected & { color: ${color.white}; } `; const CommentCount = styled(View)` flex-direction: row; align-items: center; padding-left: ${space.small2}px; position: relative; top: 4px; `; const CommentCountText = styled(Text)` font-size: ${font.tiny}px; color: ${() => appTheme().text.tiny}; padding-left: ${space.tiny}px; .issue-read & { font-weight: ${fontWeight.thin}; } .issue-selected & { color: ${color.white}; } `; const UpdatedAt = styled(View)` padding-left: ${space.small}px; `; const UpdatedAtText = styled(Text)` font-size: ${font.small}px; color: ${() => appTheme().text.tiny}; .issue-read & { font-weight: ${fontWeight.thin}; } .issue-selected & { color: ${color.white}; } `; const BookmarkWrap = styled(IconButton)` position: absolute; top: -8px; right: 0; padding: ${space.small}px; `; const Actions = styled(View)` display: none; position: absolute; bottom: ${space.small}px; right: ${space.small}px; border: solid ${border.medium}px ${() => appTheme().border.normal}; background: ${() => appTheme().bg.primary}; border-radius: 6px; padding: 1px ${space.tiny}px; flex-direction: row; align-items: center; box-shadow: 0 0 4px 1px #00000008; .issue-row:hover & { display: flex; } `; const Action = styled(IconButton)` padding: ${space.small}px ${space.small}px; margin: 0 ${space.tiny}px; `;
the_stack
import type { Attributes } from 'preact' import { h } from 'preact' import { useTitleTemplate } from 'hoofd/preact' import { Routes } from '../constants' import Zap from 'feather-icons/dist/icons/zap.svg' import MessageCircle from 'feather-icons/dist/icons/message-circle.svg' import ArrowRight from 'feather-icons/dist/icons/arrow-right.svg' import Feather from 'feather-icons/dist/icons/feather.svg' import Shield from 'feather-icons/dist/icons/shield.svg' import Home from 'feather-icons/dist/icons/home.svg' import Update from 'feather-icons/dist/icons/refresh-cw.svg' import Terminal from 'feather-icons/dist/icons/terminal.svg' import Download from 'feather-icons/dist/icons/download-cloud.svg' import PenTool from 'feather-icons/dist/icons/pen-tool.svg' import Coffee from 'feather-icons/dist/icons/coffee.svg' import BatteryCharging from 'feather-icons/dist/icons/battery-charging.svg' import Disc from 'feather-icons/dist/icons/disc.svg' import Plugin from '../assets/icons/plugin.svg' import Theme from '../assets/icons/brush.svg' import style from './homepage.module.css' import sharedStyle from './shared.module.css' type FeatureOldProps = { icon: any, title: string, desc: string, soon?: boolean } function FeatureOld ({ icon, title, desc, soon }: FeatureOldProps) { return ( <div className={style.featureOld}> {h(icon, { className: style.featureIconOld })} <h2 className={style.featureNameOld}>{title}</h2> <p className={style.featureDescriptionOld}>{desc}</p> {soon && <span className={style.soonOld}>soon™️</span>} </div> ) } function HomepageOld (_: Attributes) { useTitleTemplate('Powercord') return ( <main> <h1 className={style.titleOld}>Powerful and simple Discord client mod</h1> <div className={style.featuresOld}> <FeatureOld icon={Feather} title='Lightweight' desc={'Powercord is designed to use low to no extra resources. You won\'t even notice it\'s here!*'} /> <FeatureOld icon={Home} title='Native Feeling' desc={'We put effort in making our UIs look the same as Discord\'s UIs and ensure high compatibility with themes.'} /> <FeatureOld icon={Update} title='Built-in Updater' desc='Get the newest features, the latest fixes, automatically. We even handle update conflicts for you!' /> <FeatureOld icon={Terminal} title='Robust APIs' desc='Develop great plugins with our powerful APIs. We even take care of error handling when we can!' /> <FeatureOld icon={Download} title='Plugin/Themes Installer' desc='Browse plugins and themes, and install the ones you like by a simple click. All without leaving Discord.' soon /> <FeatureOld icon={PenTool} title='Theme Customization' desc='Themes, redefined. Theme devs can let you make the theme *your* theme through an easy configuration screen.' soon /> </div> <p className={style.note}> *Powercord still runs on top of the official Discord client, so it won't magically make it consume less memory or CPU. However, we try our best to not consume even more resources. </p> <div className={style.installOld}> <h2>What are you waiting for???</h2> <p>Make your Discord spicier. <a href={Routes.INSTALLATION}>Install Powercord!</a></p> </div> </main> ) } /** ------ */ type FeatureProps = { icon: any, title: string, description: string, note?: string, link?: { href: string, label: string } } function Feature ({ icon, title, description, note, link }: FeatureProps) { return ( <section className={style.feature}> <div className={style.featureIcon}>{h(icon, null)}</div> <h3 className={style.featureTitle}>{title}</h3> <p className={style.featureDescription}>{description}</p> {note && <p className={style.note}>{note}</p>} {link && <a href={link.href} className={style.featureLink}> <ArrowRight/> <span>{link.label}</span> </a>} </section> ) } function Homepage (_: Attributes) { useTitleTemplate('Powercord') return ( <main className={style.container}> <div className={style.heading}> <div className={style.wrapper}> <h1 className={style.title}>Powerful and simple Discord client mod</h1> <p className={style.motto}>Enhance your Discord experience with new feature and looks. Make your Discord truly yours.</p> <div className={style.buttons}> <a href={Routes.INSTALLATION} className={sharedStyle.button}> <Zap className={sharedStyle.icon}/> <span>Installation</span> </a> <a href={Routes.DICKSWORD} className={sharedStyle.buttonLink}> <MessageCircle className={sharedStyle.icon}/> <span>Discord Server</span> </a> </div> </div> </div> <div className={style.wrapper}> <section className={style.section}> <h2 className={style.sectionTitle}>Zero-compromise experience</h2> <p className={style.sectionDescription}> Powercord has everything you need to enhance your Discord client, without compromising on performance or security. </p> <div className={style.features}> <Feature icon={Plugin} title='Plugins' description={'Add new features to your Discord client, or enhance already existing ones by extending them. You can even write your own plugins!'} link={{ href: Routes.STORE_PLUGINS, label: 'Explore available plugins' }} /> <Feature icon={Theme} title='Themes' description={'Give your Discord client a fresh new look, that matches your taste. You\'re no longer limited by what Discord gave you, only imagination!'} link={{ href: Routes.STORE_THEMES, label: 'Explore available themes' }} /> <Feature icon={PenTool} title='Customizable' description={'Plugins and themes are fully customizable, though easy-to-use interfaces, allowing you to turn your Discord client into what you want, whatever that is. Unnecessary feature? Disable it. Don\'t like the color? Change it.'} /> <Feature icon={Feather} title='Lightweight' description={'Powercord is designed to consume as little resources as possible, and provides to plugin developers powerful tools to build efficient and robust plugins.'} note={'Note that Powercord still runs on top of the official client, and can\'t magically make it lighter. We just do our best to not consume even more resources.'} /> <Feature icon={Shield} title='Secure by design' description={'Unlike on other mods, plugins have no way of reading your personal information or to access sensible parts of your Discord client, such as authentication tokens.'} note={'In addition, plugins are reviewed to ensure no malicious plugin can make its way through.'} /> <Feature icon={Home} title='Feels like home' description={'We try to integrate as smoothly as possible within Discord\'s design language. Every modded element feels like it always has been there. You\'ll almost forget you\'re running a modded client!'} /> </div> </section> <hr/> <section className={style.section}> <h2 className={style.sectionTitle}>Powerful APIs for amazing plugins</h2> <p className={style.sectionDescription}> Powercord gives plugins and theme developers the tools they need to build their next amazing plugin or theme. </p> <div className={style.features}> <Feature icon={Coffee} title='Standard library' description={'Don\'t struggle with basic setup or boilerplate code. Powercord already provides everything you need to get started and do your patchwork.'} link={{ href: Routes.DOCS, label: 'Read the documentation' }} /> <Feature icon={BatteryCharging} title='Efficient code' description={'An efficient plugin keeps users happy, their Discord client speedy, and preserves their laptop\'s battery. Powercord gives you in-depth insights and detects inefficient code to help you make better and more efficient plugins.'} /> <Feature icon={Disc} title='Error handling' description={'Discord is a rolling-release product and injections can quickly go wrong. Powercord has built-in error handling that is designed to ensure plugins cannot brick Discord clients. No more crashes, or at least way fewer.'} /> </div> </section> <hr/> <section className={style.section}> <h2 className={style.sectionTitle}>Make your Discord spicier</h2> <p className={style.sectionDescription}> Stop limiting yourself to what Discord gives you. Get Powercord! </p> <div className={sharedStyle.buttons}> <a href={Routes.INSTALLATION} className={sharedStyle.button}> <Zap className={sharedStyle.icon}/> <span>Installation</span> </a> <a href={Routes.DICKSWORD} className={sharedStyle.buttonLink}> <MessageCircle className={sharedStyle.icon}/> <span>Discord Server</span> </a> </div> </section> </div> </main> ) } export default function HomepageWrapper (_: Attributes) { if (!import.meta.env.DEV) { return <HomepageOld/> } return <Homepage/> }
the_stack
import facadeFieldFactories from "./entryFields"; import { createFieldDescriptor, getEntryPropertyValueType, setEntryPropertyValueType } from "./tools"; import Entry from "../core/Entry"; import Group from "../core/Group"; import { EntryFacade, EntryFacadeField, EntryID, EntryPropertyType, EntryType, EntryPropertyValueType, GroupID, VaultFacade } from "../types"; export interface CreateEntryFacadeOptions { type?: EntryType; } const { FacadeType: FacadeTypeAttribute } = Entry.Attributes; /** * Add extra fields to a fields array that are not mentioned in a preset * Facades are creaded by presets which don't mention all property values (custom user * added items). This method adds the unmentioned items to the facade fields so that * they can be edited as well. * @param entry An Entry instance * @param fields An array of fields * @returns A new array with all combined fields * @private */ function addExtraFieldsNonDestructive(entry: Entry, fields: Array<EntryFacadeField>) { const exists = (propName: string, fieldType: EntryPropertyType) => fields.find(item => item.propertyType === fieldType && item.property === propName); const properties = entry.getProperty(); const attributes = entry.getAttribute(); return [ ...fields, ...Object.keys(properties) .filter(name => !exists(name, EntryPropertyType.Property)) .map(name => createFieldDescriptor( entry, // Entry instance "", // Title EntryPropertyType.Property, // Type name, // Property name { removeable: true } ) ), ...Object.keys(attributes) .filter(name => !exists(name, EntryPropertyType.Attribute)) .map(name => createFieldDescriptor( entry, // Entry instance "", // Title EntryPropertyType.Attribute, // Type name // Property name ) ) ]; } /** * Apply a facade field descriptor to an entry * Takes data from the descriptor and writes it to the entry. * @param entry The entry to apply to * @param descriptor The descriptor object * @private */ function applyFieldDescriptor(entry: Entry, descriptor: EntryFacadeField) { setEntryValue(entry, descriptor.propertyType, descriptor.property, descriptor.value, descriptor.valueType); } /** * Process a modified entry facade * @param entry The entry to apply processed data on * @param facade The facade object * @memberof module:Buttercup */ export function consumeEntryFacade(entry: Entry, facade: EntryFacade) { const facadeType = getEntryFacadeType(entry); if (facade && facade.type) { const properties = entry.getProperty(); const attributes = entry.getAttribute(); if (facade.type !== facadeType) { throw new Error(`Failed consuming entry data: Expected type "${facadeType}" but received "${facade.type}"`); } // update data (facade.fields || []).forEach(field => applyFieldDescriptor(entry, field)); // remove missing properties Object.keys(properties).forEach(propKey => { const correspondingField = facade.fields.find( ({ propertyType, property }) => propertyType === "property" && property === propKey ); if (typeof correspondingField === "undefined") { entry.deleteProperty(propKey); } }); // remove missing attributes Object.keys(attributes).forEach(attrKey => { const correspondingField = facade.fields.find( ({ propertyType, property }) => propertyType === "attribute" && property === attrKey ); if (typeof correspondingField === "undefined") { entry.deleteAttribute(attrKey); } }); return; } throw new Error("Failed consuming entry data: Invalid item passed as a facade"); } /** * Create a data/input facade for an Entry instance * @param entry The Entry instance * @param options Options for the entry facade creation * @returns A newly created facade * @memberof module:Buttercup */ export function createEntryFacade(entry?: Entry, options: CreateEntryFacadeOptions = {}): EntryFacade { if (entry && entry instanceof Entry !== true) { throw new Error("Failed creating entry facade: Provided item is not an Entry"); } const { type } = options; const facadeType = type || getEntryFacadeType(entry); const createFields = facadeFieldFactories[facadeType]; if (!createFields) { throw new Error(`Failed creating entry facade: No factory found for type "${facadeType}"`); } const fields = entry ? addExtraFieldsNonDestructive(entry, createFields(entry)) : createFields(entry); if ( !fields.find( field => field.propertyType === EntryPropertyType.Attribute && field.property === FacadeTypeAttribute ) ) { const entryTypeField = createFieldDescriptor( entry, // Entry instance "", // Title EntryPropertyType.Attribute, // Type FacadeTypeAttribute // Property name ); entryTypeField.value = facadeType; fields.push(entryTypeField); } return { id: entry ? entry.id : null, type: facadeType, fields, parentID: entry ? entry.getGroup().id : null, _history: [], // deprecated _changes: entry ? entry.getChanges() : [] }; } /** * Create a new entry using an entry facade * @param group The parent group * @param facade The entry facade * @returns A newly created Entry * @memberof module:Buttercup */ export function createEntryFromFacade(group: Group, facade: EntryFacade): Entry { const entry = group.createEntry(); const baseFacadeType = getEntryFacadeType(entry); const facadeType = facade.type || baseFacadeType; const preparedFacade: EntryFacade = { ...facade, parentID: group.id, // Keep type same as new entry, for now.. type: baseFacadeType, id: null }; consumeEntryFacade(entry, preparedFacade); if (facadeType !== baseFacadeType) { // Set intended facade type entry.setAttribute(Entry.Attributes.FacadeType, facadeType); } return entry; } /** * Convert an array of entry facade fields to a * key-value object with only properties * @param facadeFields Array of fields * @memberof module:Buttercup */ export function fieldsToProperties(facadeFields: Array<EntryFacadeField>): { [key: string]: string } { return facadeFields.reduce((output, field) => { if (field.propertyType !== "property") return output; output[field.property] = field.value; return output; }, {}); } export function getEntryFacadePath(entryID: EntryID, facade: VaultFacade): Array<GroupID> { const entry = facade.entries.find(entry => entry.id === entryID); if (!entry) { throw new Error(`No entry facade found for ID: ${entryID}`); } let targetGroupID: GroupID = null; const path: Array<GroupID> = []; do { targetGroupID = targetGroupID ? facade.groups.find(g => g.id === targetGroupID).parentID : entry.parentID; if (targetGroupID && targetGroupID != "0") { path.unshift(targetGroupID); } } while (targetGroupID && targetGroupID != "0"); return path; } /** * Get the facade type for an entry * @param entry The entry instance * @returns The facade type * @private */ function getEntryFacadeType(entry?: Entry): EntryType { if (!entry) { return EntryType.Login; } return entry.getType(); } /** * Set the value type of an entry property within a facade * @param facade The entry facade to modify * @param propertyName The property to apply a new value type to * @param valueType The new value type */ export function setEntryFacadePropertyValueType( facade: EntryFacade, propertyName: string, valueType: EntryPropertyValueType ) { const matchingPropertyField = facade.fields.find( field => field.property === propertyName && field.propertyType === EntryPropertyType.Property ); const matchingAttributeField = facade.fields.find( field => field.property === `${Entry.Attributes.FieldTypePrefix}${propertyName}` && field.propertyType === EntryPropertyType.Attribute ); if (matchingPropertyField) { matchingPropertyField.valueType = valueType; } if (matchingAttributeField) { matchingAttributeField.value = valueType; } } /** * Set a value on an entry * @param entry The entry instance * @param propertyType Type of property ("property"/"attribute") * @param property The property name * @param value The value to set * @param valueType Value type to set * @throws {Error} Throws if the property type is not recognised * @private */ function setEntryValue( entry: Entry, propertyType: EntryPropertyType, property: string, value: string, valueType?: EntryPropertyValueType ) { switch (propertyType) { case "property": if (entry.getProperty(property) !== value) { // Only update if changed entry.setProperty(property, value); } break; case "attribute": if (entry.getAttribute(property) !== value) { // Only update if changed entry.setAttribute(property, value); } break; default: throw new Error(`Cannot set value: Unknown property type: ${propertyType}`); } if (valueType && getEntryPropertyValueType(entry, property) !== valueType) { setEntryPropertyValueType(entry, property, valueType); } }
the_stack
* This file is automatically generated from the TPM 2.0 rev. 1.62 specification documents. * Do not edit it directly. */ import * as tt from "./TpmTypes.js"; import { TpmBase, TpmError } from "./TpmBase.js"; import { TpmBuffer } from "./TpmMarshaller.js"; export class Tpm extends TpmBase { /** TPM2_Startup() is always preceded by _TPM_Init, which is the physical indication that * TPM initialization is necessary because of a system-wide reset. TPM2_Startup() is only * valid after _TPM_Init. Additional TPM2_Startup() commands are not allowed after it has * completed successfully. If a TPM requires TPM2_Startup() and another command is * received, or if the TPM receives TPM2_Startup() when it is not required, the TPM shall * return TPM_RC_INITIALIZE. * @param startupType TPM_SU_CLEAR or TPM_SU_STATE */ Startup(startupType: tt.TPM_SU, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_Startup_REQUEST(startupType); this.dispatchCommand(tt.TPM_CC.Startup, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // Startup() /** This command is used to prepare the TPM for a power cycle. The shutdownType parameter * indicates how the subsequent TPM2_Startup() will be processed. * @param shutdownType TPM_SU_CLEAR or TPM_SU_STATE */ Shutdown(shutdownType: tt.TPM_SU, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_Shutdown_REQUEST(shutdownType); this.dispatchCommand(tt.TPM_CC.Shutdown, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // Shutdown() /** This command causes the TPM to perform a test of its capabilities. If the fullTest is * YES, the TPM will test all functions. If fullTest = NO, the TPM will only test those * functions that have not previously been tested. * @param fullTest YES if full test to be performed * NO if only test of untested functions required */ SelfTest(fullTest: number, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_SelfTest_REQUEST(fullTest); this.dispatchCommand(tt.TPM_CC.SelfTest, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // SelfTest() /** This command causes the TPM to perform a test of the selected algorithms. * @param toTest List of algorithms that should be tested * @return toDoList - List of algorithms that need testing */ IncrementalSelfTest(toTest: tt.TPM_ALG_ID[], continuation: (err: TpmError, res?: tt.TPM_ALG_ID[]) => void) { let req = new tt.TPM2_IncrementalSelfTest_REQUEST(toTest); this.dispatchCommand(tt.TPM_CC.IncrementalSelfTest, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.IncrementalSelfTestResponse); setImmediate(continuation, this.lastError, res?.toDoList); }); } // IncrementalSelfTest() /** This command returns manufacturer-specific information regarding the results of a * self-test and an indication of the test status. * @return outData - Test result data * contains manufacturer-specific information<br> * testResult - TBD */ GetTestResult(continuation: (err: TpmError, res?: tt.GetTestResultResponse) => void) { let req = new tt.TPM2_GetTestResult_REQUEST(); this.dispatchCommand(tt.TPM_CC.GetTestResult, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.GetTestResultResponse); setImmediate(continuation, this.lastError, res); }); } // GetTestResult() /** This command is used to start an authorization session using alternative methods of * establishing the session key (sessionKey). The session key is then used to derive * values used for authorization and for encrypting parameters. * @param tpmKey Handle of a loaded decrypt key used to encrypt salt * may be TPM_RH_NULL * Auth Index: None * @param bind Entity providing the authValue * may be TPM_RH_NULL * Auth Index: None * @param nonceCaller Initial nonceCaller, sets nonceTPM size for the session * shall be at least 16 octets * @param encryptedSalt Value encrypted according to the type of tpmKey * If tpmKey is TPM_RH_NULL, this shall be the Empty Buffer. * @param sessionType Indicates the type of the session; simple HMAC or policy (including * a * trial policy) * @param symmetric The algorithm and key size for parameter encryption * may select TPM_ALG_NULL * @param authHash Hash algorithm to use for the session * Shall be a hash algorithm supported by the TPM and not TPM_ALG_NULL * @return handle - Handle for the newly created session<br> * nonceTPM - The initial nonce from the TPM, used in the computation of the sessionKey */ StartAuthSession(tpmKey: tt.TPM_HANDLE, bind: tt.TPM_HANDLE, nonceCaller: Buffer, encryptedSalt: Buffer, sessionType: tt.TPM_SE, symmetric: tt.TPMT_SYM_DEF, authHash: tt.TPM_ALG_ID, continuation: (err: TpmError, res?: tt.StartAuthSessionResponse) => void) { let req = new tt.TPM2_StartAuthSession_REQUEST(tpmKey, bind, nonceCaller, encryptedSalt, sessionType, symmetric, authHash); this.dispatchCommand(tt.TPM_CC.StartAuthSession, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.StartAuthSessionResponse); setImmediate(continuation, this.lastError, res); }); } // StartAuthSession() /** This command allows a policy authorization session to be returned to its initial * state. This command is used after the TPM returns TPM_RC_PCR_CHANGED. That response * code indicates that a policy will fail because the PCR have changed after * TPM2_PolicyPCR() was executed. Restarting the session allows the authorizations to be * replayed because the session restarts with the same nonceTPM. If the PCR are valid for * the policy, the policy may then succeed. * @param sessionHandle The handle for the policy session */ PolicyRestart(sessionHandle: tt.TPM_HANDLE, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_PolicyRestart_REQUEST(sessionHandle); this.dispatchCommand(tt.TPM_CC.PolicyRestart, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // PolicyRestart() /** This command is used to create an object that can be loaded into a TPM using * TPM2_Load(). If the command completes successfully, the TPM will create the new object * and return the objects creation data (creationData), its public area (outPublic), and * its encrypted sensitive area (outPrivate). Preservation of the returned data is the * responsibility of the caller. The object will need to be loaded (TPM2_Load()) before * it may be used. The only difference between the inPublic TPMT_PUBLIC template and the * outPublic TPMT_PUBLIC object is in the unique field. * @param parentHandle Handle of parent for new object * Auth Index: 1 * Auth Role: USER * @param inSensitive The sensitive data * @param inPublic The public template * @param outsideInfo Data that will be included in the creation data for this object to * provide permanent, verifiable linkage between this object and some object owner * data * @param creationPCR PCR that will be used in creation data * @return outPrivate - The private portion of the object<br> * outPublic - The public portion of the created object<br> * creationData - Contains a TPMS_CREATION_DATA<br> * creationHash - Digest of creationData using nameAlg of outPublic<br> * creationTicket - Ticket used by TPM2_CertifyCreation() to validate that the * creation data was produced by the TPM */ Create(parentHandle: tt.TPM_HANDLE, inSensitive: tt.TPMS_SENSITIVE_CREATE, inPublic: tt.TPMT_PUBLIC, outsideInfo: Buffer, creationPCR: tt.TPMS_PCR_SELECTION[], continuation: (err: TpmError, res?: tt.CreateResponse) => void) { let req = new tt.TPM2_Create_REQUEST(parentHandle, inSensitive, inPublic, outsideInfo, creationPCR); this.dispatchCommand(tt.TPM_CC.Create, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.CreateResponse); setImmediate(continuation, this.lastError, res); }); } // Create() /** This command is used to load objects into the TPM. This command is used when both a * TPM2B_PUBLIC and TPM2B_PRIVATE are to be loaded. If only a TPM2B_PUBLIC is to be * loaded, the TPM2_LoadExternal command is used. * @param parentHandle TPM handle of parent key; shall not be a reserved handle * Auth Index: 1 * Auth Role: USER * @param inPrivate The private portion of the object * @param inPublic The public portion of the object * @return handle - Handle of type TPM_HT_TRANSIENT for the loaded object */ Load(parentHandle: tt.TPM_HANDLE, inPrivate: tt.TPM2B_PRIVATE, inPublic: tt.TPMT_PUBLIC, continuation: (err: TpmError, res?: tt.TPM_HANDLE) => void) { let req = new tt.TPM2_Load_REQUEST(parentHandle, inPrivate, inPublic); this.dispatchCommand(tt.TPM_CC.Load, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.LoadResponse); setImmediate(continuation, this.lastError, res?.handle); }); } // Load() /** This command is used to load an object that is not a Protected Object into the TPM. * The command allows loading of a public area or both a public and sensitive area. * @param inPrivate The sensitive portion of the object (optional) * @param inPublic The public portion of the object * @param hierarchy Hierarchy with which the object area is associated * @return handle - Handle of type TPM_HT_TRANSIENT for the loaded object */ LoadExternal(inPrivate: tt.TPMT_SENSITIVE, inPublic: tt.TPMT_PUBLIC, hierarchy: tt.TPM_HANDLE, continuation: (err: TpmError, res?: tt.TPM_HANDLE) => void) { let req = new tt.TPM2_LoadExternal_REQUEST(inPrivate, inPublic, hierarchy); this.dispatchCommand(tt.TPM_CC.LoadExternal, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.LoadExternalResponse); setImmediate(continuation, this.lastError, res?.handle); }); } // LoadExternal() /** This command allows access to the public area of a loaded object. * @param objectHandle TPM handle of an object * Auth Index: None * @return outPublic - Structure containing the public area of an object<br> * name - Name of the object<br> * qualifiedName - The Qualified Name of the object */ ReadPublic(objectHandle: tt.TPM_HANDLE, continuation: (err: TpmError, res?: tt.ReadPublicResponse) => void) { let req = new tt.TPM2_ReadPublic_REQUEST(objectHandle); this.dispatchCommand(tt.TPM_CC.ReadPublic, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.ReadPublicResponse); setImmediate(continuation, this.lastError, res); }); } // ReadPublic() /** This command enables the association of a credential with an object in a way that * ensures that the TPM has validated the parameters of the credentialed object. * @param activateHandle Handle of the object associated with certificate in credentialBlob * Auth Index: 1 * Auth Role: ADMIN * @param keyHandle Loaded key used to decrypt the TPMS_SENSITIVE in credentialBlob * Auth Index: 2 * Auth Role: USER * @param credentialBlob The credential * @param secret KeyHandle algorithm-dependent encrypted seed that protects credentialBlob * @return certInfo - The decrypted certificate information * the data should be no larger than the size of the digest of the nameAlg * associated with keyHandle */ ActivateCredential(activateHandle: tt.TPM_HANDLE, keyHandle: tt.TPM_HANDLE, credentialBlob: tt.TPMS_ID_OBJECT, secret: Buffer, continuation: (err: TpmError, res?: Buffer) => void) { let req = new tt.TPM2_ActivateCredential_REQUEST(activateHandle, keyHandle, credentialBlob, secret); this.dispatchCommand(tt.TPM_CC.ActivateCredential, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.ActivateCredentialResponse); setImmediate(continuation, this.lastError, res?.certInfo); }); } // ActivateCredential() /** This command allows the TPM to perform the actions required of a Certificate Authority * (CA) in creating a TPM2B_ID_OBJECT containing an activation credential. * @param handle Loaded public area, used to encrypt the sensitive area containing the * credential key * Auth Index: None * @param credential The credential information * @param objectName Name of the object to which the credential applies * @return credentialBlob - The credential<br> * secret - Handle algorithm-dependent data that wraps the key that encrypts credentialBlob */ MakeCredential(handle: tt.TPM_HANDLE, credential: Buffer, objectName: Buffer, continuation: (err: TpmError, res?: tt.MakeCredentialResponse) => void) { let req = new tt.TPM2_MakeCredential_REQUEST(handle, credential, objectName); this.dispatchCommand(tt.TPM_CC.MakeCredential, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.MakeCredentialResponse); setImmediate(continuation, this.lastError, res); }); } // MakeCredential() /** This command returns the data in a loaded Sealed Data Object. * @param itemHandle Handle of a loaded data object * Auth Index: 1 * Auth Role: USER * @return outData - Unsealed data * Size of outData is limited to be no more than 128 octets. */ Unseal(itemHandle: tt.TPM_HANDLE, continuation: (err: TpmError, res?: Buffer) => void) { let req = new tt.TPM2_Unseal_REQUEST(itemHandle); this.dispatchCommand(tt.TPM_CC.Unseal, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.UnsealResponse); setImmediate(continuation, this.lastError, res?.outData); }); } // Unseal() /** This command is used to change the authorization secret for a TPM-resident object. * @param objectHandle Handle of the object * Auth Index: 1 * Auth Role: ADMIN * @param parentHandle Handle of the parent * Auth Index: None * @param newAuth New authorization value * @return outPrivate - Private area containing the new authorization value */ ObjectChangeAuth(objectHandle: tt.TPM_HANDLE, parentHandle: tt.TPM_HANDLE, newAuth: Buffer, continuation: (err: TpmError, res?: tt.TPM2B_PRIVATE) => void) { let req = new tt.TPM2_ObjectChangeAuth_REQUEST(objectHandle, parentHandle, newAuth); this.dispatchCommand(tt.TPM_CC.ObjectChangeAuth, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.ObjectChangeAuthResponse); setImmediate(continuation, this.lastError, res?.outPrivate); }); } // ObjectChangeAuth() /** This command creates an object and loads it in the TPM. This command allows creation * of any type of object (Primary, Ordinary, or Derived) depending on the type of * parentHandle. If parentHandle references a Primary Seed, then a Primary Object is * created; if parentHandle references a Storage Parent, then an Ordinary Object is * created; and if parentHandle references a Derivation Parent, then a Derived Object is generated. * @param parentHandle Handle of a transient storage key, a persistent storage key, * TPM_RH_ENDORSEMENT, TPM_RH_OWNER, TPM_RH_PLATFORM+{PP}, or TPM_RH_NULL * Auth Index: 1 * Auth Role: USER * @param inSensitive The sensitive data, see TPM 2.0 Part 1 Sensitive Values * @param inPublic The public template * @return handle - Handle of type TPM_HT_TRANSIENT for created object<br> * outPrivate - The sensitive area of the object (optional)<br> * outPublic - The public portion of the created object<br> * name - The name of the created object */ CreateLoaded(parentHandle: tt.TPM_HANDLE, inSensitive: tt.TPMS_SENSITIVE_CREATE, inPublic: Buffer, continuation: (err: TpmError, res?: tt.CreateLoadedResponse) => void) { let req = new tt.TPM2_CreateLoaded_REQUEST(parentHandle, inSensitive, inPublic); this.dispatchCommand(tt.TPM_CC.CreateLoaded, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.CreateLoadedResponse); setImmediate(continuation, this.lastError, res); }); } // CreateLoaded() /** This command duplicates a loaded object so that it may be used in a different * hierarchy. The new parent key for the duplicate may be on the same or different TPM or * TPM_RH_NULL. Only the public area of newParentHandle is required to be loaded. * @param objectHandle Loaded object to duplicate * Auth Index: 1 * Auth Role: DUP * @param newParentHandle Shall reference the public area of an asymmetric key * Auth Index: None * @param encryptionKeyIn Optional symmetric encryption key * The size for this key is set to zero when the TPM is to generate the key. This * parameter may be encrypted. * @param symmetricAlg Definition for the symmetric algorithm to be used for the inner wrapper * may be TPM_ALG_NULL if no inner wrapper is applied * @return encryptionKeyOut - If the caller provided an encryption key or if symmetricAlg * was * TPM_ALG_NULL, then this will be the Empty Buffer; * otherwise, it * shall contain the TPM-generated, symmetric encryption key for * the inner wrapper.<br> * duplicate - Private area that may be encrypted by encryptionKeyIn; and may be * doubly encrypted<br> * outSymSeed - Seed protected by the asymmetric algorithms of new parent (NP) */ Duplicate(objectHandle: tt.TPM_HANDLE, newParentHandle: tt.TPM_HANDLE, encryptionKeyIn: Buffer, symmetricAlg: tt.TPMT_SYM_DEF_OBJECT, continuation: (err: TpmError, res?: tt.DuplicateResponse) => void) { let req = new tt.TPM2_Duplicate_REQUEST(objectHandle, newParentHandle, encryptionKeyIn, symmetricAlg); this.dispatchCommand(tt.TPM_CC.Duplicate, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.DuplicateResponse); setImmediate(continuation, this.lastError, res); }); } // Duplicate() /** This command allows the TPM to serve in the role as a Duplication Authority. If proper * authorization for use of the oldParent is provided, then an HMAC key and a symmetric * key are recovered from inSymSeed and used to integrity check and decrypt inDuplicate. * A new protection seed value is generated according to the methods appropriate for * newParent and the blob is re-encrypted and a new integrity value is computed. The * re-encrypted blob is returned in outDuplicate and the symmetric key returned in outSymKey. * @param oldParent Parent of object * Auth Index: 1 * Auth Role: User * @param newParent New parent of the object * Auth Index: None * @param inDuplicate An object encrypted using symmetric key derived from inSymSeed * @param name The Name of the object being rewrapped * @param inSymSeed The seed for the symmetric key and HMAC key * needs oldParent private key to recover the seed and generate the symmetric key * @return outDuplicate - An object encrypted using symmetric key derived from outSymSeed<br> * outSymSeed - Seed for a symmetric key protected by newParent asymmetric key */ Rewrap(oldParent: tt.TPM_HANDLE, newParent: tt.TPM_HANDLE, inDuplicate: tt.TPM2B_PRIVATE, name: Buffer, inSymSeed: Buffer, continuation: (err: TpmError, res?: tt.RewrapResponse) => void) { let req = new tt.TPM2_Rewrap_REQUEST(oldParent, newParent, inDuplicate, name, inSymSeed); this.dispatchCommand(tt.TPM_CC.Rewrap, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.RewrapResponse); setImmediate(continuation, this.lastError, res); }); } // Rewrap() /** This command allows an object to be encrypted using the symmetric encryption values of * a Storage Key. After encryption, the object may be loaded and used in the new * hierarchy. The imported object (duplicate) may be singly encrypted, multiply * encrypted, or unencrypted. * @param parentHandle The handle of the new parent for the object * Auth Index: 1 * Auth Role: USER * @param encryptionKey The optional symmetric encryption key used as the inner wrapper * for duplicate * If symmetricAlg is TPM_ALG_NULL, then this parameter shall be the Empty Buffer. * @param objectPublic The public area of the object to be imported * This is provided so that the integrity value for duplicate and the object * attributes can be checked. * NOTE Even if the integrity value of the object is not checked on input, the object * Name is required to create the integrity value for the imported object. * @param duplicate The symmetrically encrypted duplicate object that may contain an inner * symmetric wrapper * @param inSymSeed The seed for the symmetric key and HMAC key * inSymSeed is encrypted/encoded using the algorithms of newParent. * @param symmetricAlg Definition for the symmetric algorithm to use for the inner wrapper * If this algorithm is TPM_ALG_NULL, no inner wrapper is present and encryptionKey * shall be the Empty Buffer. * @return outPrivate - The sensitive area encrypted with the symmetric key of parentHandle */ Import(parentHandle: tt.TPM_HANDLE, encryptionKey: Buffer, objectPublic: tt.TPMT_PUBLIC, duplicate: tt.TPM2B_PRIVATE, inSymSeed: Buffer, symmetricAlg: tt.TPMT_SYM_DEF_OBJECT, continuation: (err: TpmError, res?: tt.TPM2B_PRIVATE) => void) { let req = new tt.TPM2_Import_REQUEST(parentHandle, encryptionKey, objectPublic, duplicate, inSymSeed, symmetricAlg); this.dispatchCommand(tt.TPM_CC.Import, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.ImportResponse); setImmediate(continuation, this.lastError, res?.outPrivate); }); } // Import() /** This command performs RSA encryption using the indicated padding scheme according to * IETF RFC 8017. If the scheme of keyHandle is TPM_ALG_NULL, then the caller may use * inScheme to specify the padding scheme. If scheme of keyHandle is not TPM_ALG_NULL, * then inScheme shall either be TPM_ALG_NULL or be the same as scheme (TPM_RC_SCHEME). * @param keyHandle Reference to public portion of RSA key to use for encryption * Auth Index: None * @param message Message to be encrypted * NOTE 1 The data type was chosen because it limits the overall size of the input * to * no greater than the size of the largest RSA public key. This may be larger than * allowed for keyHandle. * @param inScheme The padding scheme to use if scheme associated with keyHandle is TPM_ALG_NULL * One of: TPMS_KEY_SCHEME_ECDH, TPMS_KEY_SCHEME_ECMQV, TPMS_SIG_SCHEME_RSASSA, * TPMS_SIG_SCHEME_RSAPSS, TPMS_SIG_SCHEME_ECDSA, TPMS_SIG_SCHEME_ECDAA, * TPMS_SIG_SCHEME_SM2, TPMS_SIG_SCHEME_ECSCHNORR, TPMS_ENC_SCHEME_RSAES, * TPMS_ENC_SCHEME_OAEP, TPMS_SCHEME_HASH, TPMS_NULL_ASYM_SCHEME. * @param label Optional label L to be associated with the message * Size of the buffer is zero if no label is present * NOTE 2 See description of label above. * @return outData - Encrypted output */ RSA_Encrypt(keyHandle: tt.TPM_HANDLE, message: Buffer, inScheme: tt.TPMU_ASYM_SCHEME, label: Buffer, continuation: (err: TpmError, res?: Buffer) => void) { let req = new tt.TPM2_RSA_Encrypt_REQUEST(keyHandle, message, inScheme, label); this.dispatchCommand(tt.TPM_CC.RSA_Encrypt, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.RSA_EncryptResponse); setImmediate(continuation, this.lastError, res?.outData); }); } // RSA_Encrypt() /** This command performs RSA decryption using the indicated padding scheme according to * IETF RFC 8017 ((PKCS#1). * @param keyHandle RSA key to use for decryption * Auth Index: 1 * Auth Role: USER * @param cipherText Cipher text to be decrypted * NOTE An encrypted RSA data block is the size of the public modulus. * @param inScheme The padding scheme to use if scheme associated with keyHandle is TPM_ALG_NULL * One of: TPMS_KEY_SCHEME_ECDH, TPMS_KEY_SCHEME_ECMQV, TPMS_SIG_SCHEME_RSASSA, * TPMS_SIG_SCHEME_RSAPSS, TPMS_SIG_SCHEME_ECDSA, TPMS_SIG_SCHEME_ECDAA, * TPMS_SIG_SCHEME_SM2, TPMS_SIG_SCHEME_ECSCHNORR, TPMS_ENC_SCHEME_RSAES, * TPMS_ENC_SCHEME_OAEP, TPMS_SCHEME_HASH, TPMS_NULL_ASYM_SCHEME. * @param label Label whose association with the message is to be verified * @return message - Decrypted output */ RSA_Decrypt(keyHandle: tt.TPM_HANDLE, cipherText: Buffer, inScheme: tt.TPMU_ASYM_SCHEME, label: Buffer, continuation: (err: TpmError, res?: Buffer) => void) { let req = new tt.TPM2_RSA_Decrypt_REQUEST(keyHandle, cipherText, inScheme, label); this.dispatchCommand(tt.TPM_CC.RSA_Decrypt, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.RSA_DecryptResponse); setImmediate(continuation, this.lastError, res?.message); }); } // RSA_Decrypt() /** This command uses the TPM to generate an ephemeral key pair (de, Qe where Qe [de]G). * It uses the private ephemeral key and a loaded public key (QS) to compute the shared * secret value (P [hde]QS). * @param keyHandle Handle of a loaded ECC key public area. * Auth Index: None * @return zPoint - Results of P h[de]Qs<br> * pubPoint - Generated ephemeral public point (Qe) */ ECDH_KeyGen(keyHandle: tt.TPM_HANDLE, continuation: (err: TpmError, res?: tt.ECDH_KeyGenResponse) => void) { let req = new tt.TPM2_ECDH_KeyGen_REQUEST(keyHandle); this.dispatchCommand(tt.TPM_CC.ECDH_KeyGen, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.ECDH_KeyGenResponse); setImmediate(continuation, this.lastError, res); }); } // ECDH_KeyGen() /** This command uses the TPM to recover the Z value from a public point (QB) and a * private key (ds). It will perform the multiplication of the provided inPoint (QB) with * the private key (ds) and return the coordinates of the resultant point (Z = (xZ , yZ) * [hds]QB; where h is the cofactor of the curve). * @param keyHandle Handle of a loaded ECC key * Auth Index: 1 * Auth Role: USER * @param inPoint A public key * @return outPoint - X and Y coordinates of the product of the multiplication Z = (xZ , * yZ) [hdS]QB */ ECDH_ZGen(keyHandle: tt.TPM_HANDLE, inPoint: tt.TPMS_ECC_POINT, continuation: (err: TpmError, res?: tt.TPMS_ECC_POINT) => void) { let req = new tt.TPM2_ECDH_ZGen_REQUEST(keyHandle, inPoint); this.dispatchCommand(tt.TPM_CC.ECDH_ZGen, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.ECDH_ZGenResponse); setImmediate(continuation, this.lastError, res?.outPoint); }); } // ECDH_ZGen() /** This command returns the parameters of an ECC curve identified by its TCG-assigned curveID. * @param curveID Parameter set selector * @return parameters - ECC parameters for the selected curve */ ECC_Parameters(curveID: tt.TPM_ECC_CURVE, continuation: (err: TpmError, res?: tt.TPMS_ALGORITHM_DETAIL_ECC) => void) { let req = new tt.TPM2_ECC_Parameters_REQUEST(curveID); this.dispatchCommand(tt.TPM_CC.ECC_Parameters, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.ECC_ParametersResponse); setImmediate(continuation, this.lastError, res?.parameters); }); } // ECC_Parameters() /** This command supports two-phase key exchange protocols. The command is used in * combination with TPM2_EC_Ephemeral(). TPM2_EC_Ephemeral() generates an ephemeral key * and returns the public point of that ephemeral key along with a numeric value that * allows the TPM to regenerate the associated private key. * @param keyA Handle of an unrestricted decryption key ECC * The private key referenced by this handle is used as dS,A * Auth Index: 1 * Auth Role: USER * @param inQsB Other partys static public key (Qs,B = (Xs,B, Ys,B)) * @param inQeB Other party's ephemeral public key (Qe,B = (Xe,B, Ye,B)) * @param inScheme The key exchange scheme * @param counter Value returned by TPM2_EC_Ephemeral() * @return outZ1 - X and Y coordinates of the computed value (scheme dependent)<br> * outZ2 - X and Y coordinates of the second computed value (scheme dependent) */ ZGen_2Phase(keyA: tt.TPM_HANDLE, inQsB: tt.TPMS_ECC_POINT, inQeB: tt.TPMS_ECC_POINT, inScheme: tt.TPM_ALG_ID, counter: number, continuation: (err: TpmError, res?: tt.ZGen_2PhaseResponse) => void) { let req = new tt.TPM2_ZGen_2Phase_REQUEST(keyA, inQsB, inQeB, inScheme, counter); this.dispatchCommand(tt.TPM_CC.ZGen_2Phase, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.ZGen_2PhaseResponse); setImmediate(continuation, this.lastError, res); }); } // ZGen_2Phase() /** This command performs ECC encryption as described in Part 1, Annex D. * @param keyHandle Reference to public portion of ECC key to use for encryption * Auth Index: None * @param plainText Plaintext to be encrypted * @param inScheme The KDF to use if scheme associated with keyHandle is TPM_ALG_NULL * One of: TPMS_KDF_SCHEME_MGF1, TPMS_KDF_SCHEME_KDF1_SP800_56A, TPMS_KDF_SCHEME_KDF2, * TPMS_KDF_SCHEME_KDF1_SP800_108, TPMS_SCHEME_HASH, TPMS_NULL_KDF_SCHEME. * @return C1 - The public ephemeral key used for ECDH<br> * C2 - The data block produced by the XOR process<br> * C3 - The integrity value */ ECC_Encrypt(keyHandle: tt.TPM_HANDLE, plainText: Buffer, inScheme: tt.TPMU_KDF_SCHEME, continuation: (err: TpmError, res?: tt.ECC_EncryptResponse) => void) { let req = new tt.TPM2_ECC_Encrypt_REQUEST(keyHandle, plainText, inScheme); this.dispatchCommand(tt.TPM_CC.ECC_Encrypt, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.ECC_EncryptResponse); setImmediate(continuation, this.lastError, res); }); } // ECC_Encrypt() /** This command performs ECC decryption. * @param keyHandle ECC key to use for decryption * Auth Index: 1 * Auth Role: USER * @param C1 The public ephemeral key used for ECDH * @param C2 The data block produced by the XOR process * @param C3 The integrity value * @param inScheme The KDF to use if scheme associated with keyHandle is TPM_ALG_NULL * One of: TPMS_KDF_SCHEME_MGF1, TPMS_KDF_SCHEME_KDF1_SP800_56A, TPMS_KDF_SCHEME_KDF2, * TPMS_KDF_SCHEME_KDF1_SP800_108, TPMS_SCHEME_HASH, TPMS_NULL_KDF_SCHEME. * @return plainText - Decrypted output */ ECC_Decrypt(keyHandle: tt.TPM_HANDLE, C1: tt.TPMS_ECC_POINT, C2: Buffer, C3: Buffer, inScheme: tt.TPMU_KDF_SCHEME, continuation: (err: TpmError, res?: Buffer) => void) { let req = new tt.TPM2_ECC_Decrypt_REQUEST(keyHandle, C1, C2, C3, inScheme); this.dispatchCommand(tt.TPM_CC.ECC_Decrypt, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.ECC_DecryptResponse); setImmediate(continuation, this.lastError, res?.plainText); }); } // ECC_Decrypt() /** NOTE 1 This command is deprecated, and TPM2_EncryptDecrypt2() is preferred. This * should be reflected in platform-specific specifications. * @param keyHandle The symmetric key used for the operation * Auth Index: 1 * Auth Role: USER * @param decrypt If YES, then the operation is decryption; if NO, the operation is encryption * @param mode Symmetric encryption/decryption mode * this field shall match the default mode of the key or be TPM_ALG_NULL. * @param ivIn An initial value as required by the algorithm * @param inData The data to be encrypted/decrypted * @return outData - Encrypted or decrypted output<br> * ivOut - Chaining value to use for IV in next round */ EncryptDecrypt(keyHandle: tt.TPM_HANDLE, decrypt: number, mode: tt.TPM_ALG_ID, ivIn: Buffer, inData: Buffer, continuation: (err: TpmError, res?: tt.EncryptDecryptResponse) => void) { let req = new tt.TPM2_EncryptDecrypt_REQUEST(keyHandle, decrypt, mode, ivIn, inData); this.dispatchCommand(tt.TPM_CC.EncryptDecrypt, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.EncryptDecryptResponse); setImmediate(continuation, this.lastError, res); }); } // EncryptDecrypt() /** This command is identical to TPM2_EncryptDecrypt(), except that the inData parameter * is the first parameter. This permits inData to be parameter encrypted. * @param keyHandle The symmetric key used for the operation * Auth Index: 1 * Auth Role: USER * @param inData The data to be encrypted/decrypted * @param decrypt If YES, then the operation is decryption; if NO, the operation is encryption * @param mode Symmetric mode * this field shall match the default mode of the key or be TPM_ALG_NULL. * @param ivIn An initial value as required by the algorithm * @return outData - Encrypted or decrypted output<br> * ivOut - Chaining value to use for IV in next round */ EncryptDecrypt2(keyHandle: tt.TPM_HANDLE, inData: Buffer, decrypt: number, mode: tt.TPM_ALG_ID, ivIn: Buffer, continuation: (err: TpmError, res?: tt.EncryptDecrypt2Response) => void) { let req = new tt.TPM2_EncryptDecrypt2_REQUEST(keyHandle, inData, decrypt, mode, ivIn); this.dispatchCommand(tt.TPM_CC.EncryptDecrypt2, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.EncryptDecrypt2Response); setImmediate(continuation, this.lastError, res); }); } // EncryptDecrypt2() /** This command performs a hash operation on a data buffer and returns the results. * @param data Data to be hashed * @param hashAlg Algorithm for the hash being computed shall not be TPM_ALG_NULL * @param hierarchy Hierarchy to use for the ticket (TPM_RH_NULL allowed) * @return outHash - Results<br> * validation - Ticket indicating that the sequence of octets used to compute * outDigest did not start with TPM_GENERATED_VALUE * will be a NULL ticket if the digest may not be signed with a * restricted key */ Hash(data: Buffer, hashAlg: tt.TPM_ALG_ID, hierarchy: tt.TPM_HANDLE, continuation: (err: TpmError, res?: tt.HashResponse) => void) { let req = new tt.TPM2_Hash_REQUEST(data, hashAlg, hierarchy); this.dispatchCommand(tt.TPM_CC.Hash, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.HashResponse); setImmediate(continuation, this.lastError, res); }); } // Hash() /** This command performs an HMAC on the supplied data using the indicated hash algorithm. * @param handle Handle for the symmetric signing key providing the HMAC key * Auth Index: 1 * Auth Role: USER * @param buffer HMAC data * @param hashAlg Algorithm to use for HMAC * @return outHMAC - The returned HMAC in a sized buffer */ HMAC(handle: tt.TPM_HANDLE, buffer: Buffer, hashAlg: tt.TPM_ALG_ID, continuation: (err: TpmError, res?: Buffer) => void) { let req = new tt.TPM2_HMAC_REQUEST(handle, buffer, hashAlg); this.dispatchCommand(tt.TPM_CC.HMAC, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.HMACResponse); setImmediate(continuation, this.lastError, res?.outHMAC); }); } // HMAC() /** This command performs an HMAC or a block cipher MAC on the supplied data using the * indicated algorithm. * @param handle Handle for the symmetric signing key providing the MAC key * Auth Index: 1 * Auth Role: USER * @param buffer MAC data * @param inScheme Algorithm to use for MAC * @return outMAC - The returned MAC in a sized buffer */ MAC(handle: tt.TPM_HANDLE, buffer: Buffer, inScheme: tt.TPM_ALG_ID, continuation: (err: TpmError, res?: Buffer) => void) { let req = new tt.TPM2_MAC_REQUEST(handle, buffer, inScheme); this.dispatchCommand(tt.TPM_CC.MAC, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.MACResponse); setImmediate(continuation, this.lastError, res?.outMAC); }); } // MAC() /** This command returns the next bytesRequested octets from the random number generator (RNG). * @param bytesRequested Number of octets to return * @return randomBytes - The random octets */ GetRandom(bytesRequested: number, continuation: (err: TpmError, res?: Buffer) => void) { let req = new tt.TPM2_GetRandom_REQUEST(bytesRequested); this.dispatchCommand(tt.TPM_CC.GetRandom, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.GetRandomResponse); setImmediate(continuation, this.lastError, res?.randomBytes); }); } // GetRandom() /** This command is used to add "additional information" to the RNG state. * @param inData Additional information */ StirRandom(inData: Buffer, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_StirRandom_REQUEST(inData); this.dispatchCommand(tt.TPM_CC.StirRandom, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // StirRandom() /** This command starts an HMAC sequence. The TPM will create and initialize an HMAC * sequence structure, assign a handle to the sequence, and set the authValue of the * sequence object to the value in auth. * @param handle Handle of an HMAC key * Auth Index: 1 * Auth Role: USER * @param auth Authorization value for subsequent use of the sequence * @param hashAlg The hash algorithm to use for the HMAC * @return handle - A handle to reference the sequence */ HMAC_Start(handle: tt.TPM_HANDLE, auth: Buffer, hashAlg: tt.TPM_ALG_ID, continuation: (err: TpmError, res?: tt.TPM_HANDLE) => void) { let req = new tt.TPM2_HMAC_Start_REQUEST(handle, auth, hashAlg); this.dispatchCommand(tt.TPM_CC.HMAC_Start, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.HMAC_StartResponse); setImmediate(continuation, this.lastError, res?.handle); }); } // HMAC_Start() /** This command starts a MAC sequence. The TPM will create and initialize a MAC sequence * structure, assign a handle to the sequence, and set the authValue of the sequence * object to the value in auth. * @param handle Handle of a MAC key * Auth Index: 1 * Auth Role: USER * @param auth Authorization value for subsequent use of the sequence * @param inScheme The algorithm to use for the MAC * @return handle - A handle to reference the sequence */ MAC_Start(handle: tt.TPM_HANDLE, auth: Buffer, inScheme: tt.TPM_ALG_ID, continuation: (err: TpmError, res?: tt.TPM_HANDLE) => void) { let req = new tt.TPM2_MAC_Start_REQUEST(handle, auth, inScheme); this.dispatchCommand(tt.TPM_CC.MAC_Start, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.MAC_StartResponse); setImmediate(continuation, this.lastError, res?.handle); }); } // MAC_Start() /** This command starts a hash or an Event Sequence. If hashAlg is an implemented hash, * then a hash sequence is started. If hashAlg is TPM_ALG_NULL, then an Event Sequence is * started. If hashAlg is neither an implemented algorithm nor TPM_ALG_NULL, then the TPM * shall return TPM_RC_HASH. * @param auth Authorization value for subsequent use of the sequence * @param hashAlg The hash algorithm to use for the hash sequence * An Event Sequence starts if this is TPM_ALG_NULL. * @return handle - A handle to reference the sequence */ HashSequenceStart(auth: Buffer, hashAlg: tt.TPM_ALG_ID, continuation: (err: TpmError, res?: tt.TPM_HANDLE) => void) { let req = new tt.TPM2_HashSequenceStart_REQUEST(auth, hashAlg); this.dispatchCommand(tt.TPM_CC.HashSequenceStart, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.HashSequenceStartResponse); setImmediate(continuation, this.lastError, res?.handle); }); } // HashSequenceStart() /** This command is used to add data to a hash or HMAC sequence. The amount of data in * buffer may be any size up to the limits of the TPM. * @param sequenceHandle Handle for the sequence object * Auth Index: 1 * Auth Role: USER * @param buffer Data to be added to hash */ SequenceUpdate(sequenceHandle: tt.TPM_HANDLE, buffer: Buffer, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_SequenceUpdate_REQUEST(sequenceHandle, buffer); this.dispatchCommand(tt.TPM_CC.SequenceUpdate, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // SequenceUpdate() /** This command adds the last part of data, if any, to a hash/HMAC sequence and returns * the result. * @param sequenceHandle Authorization for the sequence * Auth Index: 1 * Auth Role: USER * @param buffer Data to be added to the hash/HMAC * @param hierarchy Hierarchy of the ticket for a hash * @return result - The returned HMAC or digest in a sized buffer<br> * validation - Ticket indicating that the sequence of octets used to compute * outDigest did not start with TPM_GENERATED_VALUE * This is a NULL Ticket when the sequence is HMAC. */ SequenceComplete(sequenceHandle: tt.TPM_HANDLE, buffer: Buffer, hierarchy: tt.TPM_HANDLE, continuation: (err: TpmError, res?: tt.SequenceCompleteResponse) => void) { let req = new tt.TPM2_SequenceComplete_REQUEST(sequenceHandle, buffer, hierarchy); this.dispatchCommand(tt.TPM_CC.SequenceComplete, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.SequenceCompleteResponse); setImmediate(continuation, this.lastError, res); }); } // SequenceComplete() /** This command adds the last part of data, if any, to an Event Sequence and returns the * result in a digest list. If pcrHandle references a PCR and not TPM_RH_NULL, then the * returned digest list is processed in the same manner as the digest list input * parameter to TPM2_PCR_Extend(). That is, if a bank contains a PCR associated with * pcrHandle, it is extended with the associated digest value from the list. * @param pcrHandle PCR to be extended with the Event data * Auth Index: 1 * Auth Role: USER * @param sequenceHandle Authorization for the sequence * Auth Index: 2 * Auth Role: USER * @param buffer Data to be added to the Event * @return results - List of digests computed for the PCR */ EventSequenceComplete(pcrHandle: tt.TPM_HANDLE, sequenceHandle: tt.TPM_HANDLE, buffer: Buffer, continuation: (err: TpmError, res?: tt.TPMT_HA[]) => void) { let req = new tt.TPM2_EventSequenceComplete_REQUEST(pcrHandle, sequenceHandle, buffer); this.dispatchCommand(tt.TPM_CC.EventSequenceComplete, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.EventSequenceCompleteResponse); setImmediate(continuation, this.lastError, res?.results); }); } // EventSequenceComplete() /** The purpose of this command is to prove that an object with a specific Name is loaded * in the TPM. By certifying that the object is loaded, the TPM warrants that a public * area with a given Name is self-consistent and associated with a valid sensitive area. * If a relying party has a public area that has the same Name as a Name certified with * this command, then the values in that public area are correct. * @param objectHandle Handle of the object to be certified * Auth Index: 1 * Auth Role: ADMIN * @param signHandle Handle of the key used to sign the attestation structure * Auth Index: 2 * Auth Role: USER * @param qualifyingData User provided qualifying data * @param inScheme Signing scheme to use if the scheme for signHandle is TPM_ALG_NULL * One of: TPMS_SIG_SCHEME_RSASSA, TPMS_SIG_SCHEME_RSAPSS, TPMS_SIG_SCHEME_ECDSA, * TPMS_SIG_SCHEME_ECDAA, TPMS_SIG_SCHEME_SM2, TPMS_SIG_SCHEME_ECSCHNORR, * TPMS_SCHEME_HMAC, TPMS_SCHEME_HASH, TPMS_NULL_SIG_SCHEME. * @return certifyInfo - The structure that was signed<br> * signature - The asymmetric signature over certifyInfo using the key referenced * by signHandle */ Certify(objectHandle: tt.TPM_HANDLE, signHandle: tt.TPM_HANDLE, qualifyingData: Buffer, inScheme: tt.TPMU_SIG_SCHEME, continuation: (err: TpmError, res?: tt.CertifyResponse) => void) { let req = new tt.TPM2_Certify_REQUEST(objectHandle, signHandle, qualifyingData, inScheme); this.dispatchCommand(tt.TPM_CC.Certify, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.CertifyResponse); setImmediate(continuation, this.lastError, res); }); } // Certify() /** This command is used to prove the association between an object and its creation data. * The TPM will validate that the ticket was produced by the TPM and that the ticket * validates the association between a loaded public area and the provided hash of the * creation data (creationHash). * @param signHandle Handle of the key that will sign the attestation block * Auth Index: 1 * Auth Role: USER * @param objectHandle The object associated with the creation data * Auth Index: None * @param qualifyingData User-provided qualifying data * @param creationHash Hash of the creation data produced by TPM2_Create() or TPM2_CreatePrimary() * @param inScheme Signing scheme to use if the scheme for signHandle is TPM_ALG_NULL * One of: TPMS_SIG_SCHEME_RSASSA, TPMS_SIG_SCHEME_RSAPSS, TPMS_SIG_SCHEME_ECDSA, * TPMS_SIG_SCHEME_ECDAA, TPMS_SIG_SCHEME_SM2, TPMS_SIG_SCHEME_ECSCHNORR, * TPMS_SCHEME_HMAC, TPMS_SCHEME_HASH, TPMS_NULL_SIG_SCHEME. * @param creationTicket Ticket produced by TPM2_Create() or TPM2_CreatePrimary() * @return certifyInfo - The structure that was signed<br> * signature - The signature over certifyInfo */ CertifyCreation(signHandle: tt.TPM_HANDLE, objectHandle: tt.TPM_HANDLE, qualifyingData: Buffer, creationHash: Buffer, inScheme: tt.TPMU_SIG_SCHEME, creationTicket: tt.TPMT_TK_CREATION, continuation: (err: TpmError, res?: tt.CertifyCreationResponse) => void) { let req = new tt.TPM2_CertifyCreation_REQUEST(signHandle, objectHandle, qualifyingData, creationHash, inScheme, creationTicket); this.dispatchCommand(tt.TPM_CC.CertifyCreation, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.CertifyCreationResponse); setImmediate(continuation, this.lastError, res); }); } // CertifyCreation() /** This command is used to quote PCR values. * @param signHandle Handle of key that will perform signature * Auth Index: 1 * Auth Role: USER * @param qualifyingData Data supplied by the caller * @param inScheme Signing scheme to use if the scheme for signHandle is TPM_ALG_NULL * One of: TPMS_SIG_SCHEME_RSASSA, TPMS_SIG_SCHEME_RSAPSS, TPMS_SIG_SCHEME_ECDSA, * TPMS_SIG_SCHEME_ECDAA, TPMS_SIG_SCHEME_SM2, TPMS_SIG_SCHEME_ECSCHNORR, * TPMS_SCHEME_HMAC, TPMS_SCHEME_HASH, TPMS_NULL_SIG_SCHEME. * @param PCRselect PCR set to quote * @return quoted - The quoted information<br> * signature - The signature over quoted */ Quote(signHandle: tt.TPM_HANDLE, qualifyingData: Buffer, inScheme: tt.TPMU_SIG_SCHEME, PCRselect: tt.TPMS_PCR_SELECTION[], continuation: (err: TpmError, res?: tt.QuoteResponse) => void) { let req = new tt.TPM2_Quote_REQUEST(signHandle, qualifyingData, inScheme, PCRselect); this.dispatchCommand(tt.TPM_CC.Quote, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.QuoteResponse); setImmediate(continuation, this.lastError, res); }); } // Quote() /** This command returns a digital signature of the audit session digest. * @param privacyAdminHandle Handle of the privacy administrator (TPM_RH_ENDORSEMENT) * Auth Index: 1 * Auth Role: USER * @param signHandle Handle of the signing key * Auth Index: 2 * Auth Role: USER * @param sessionHandle Handle of the audit session * Auth Index: None * @param qualifyingData User-provided qualifying data may be zero-length * @param inScheme Signing scheme to use if the scheme for signHandle is TPM_ALG_NULL * One of: TPMS_SIG_SCHEME_RSASSA, TPMS_SIG_SCHEME_RSAPSS, TPMS_SIG_SCHEME_ECDSA, * TPMS_SIG_SCHEME_ECDAA, TPMS_SIG_SCHEME_SM2, TPMS_SIG_SCHEME_ECSCHNORR, * TPMS_SCHEME_HMAC, TPMS_SCHEME_HASH, TPMS_NULL_SIG_SCHEME. * @return auditInfo - The audit information that was signed<br> * signature - The signature over auditInfo */ GetSessionAuditDigest(privacyAdminHandle: tt.TPM_HANDLE, signHandle: tt.TPM_HANDLE, sessionHandle: tt.TPM_HANDLE, qualifyingData: Buffer, inScheme: tt.TPMU_SIG_SCHEME, continuation: (err: TpmError, res?: tt.GetSessionAuditDigestResponse) => void) { let req = new tt.TPM2_GetSessionAuditDigest_REQUEST(privacyAdminHandle, signHandle, sessionHandle, qualifyingData, inScheme); this.dispatchCommand(tt.TPM_CC.GetSessionAuditDigest, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.GetSessionAuditDigestResponse); setImmediate(continuation, this.lastError, res); }); } // GetSessionAuditDigest() /** This command returns the current value of the command audit digest, a digest of the * commands being audited, and the audit hash algorithm. These values are placed in an * attestation structure and signed with the key referenced by signHandle. * @param privacyHandle Handle of the privacy administrator (TPM_RH_ENDORSEMENT) * Auth Index: 1 * Auth Role: USER * @param signHandle The handle of the signing key * Auth Index: 2 * Auth Role: USER * @param qualifyingData Other data to associate with this audit digest * @param inScheme Signing scheme to use if the scheme for signHandle is TPM_ALG_NULL * One of: TPMS_SIG_SCHEME_RSASSA, TPMS_SIG_SCHEME_RSAPSS, TPMS_SIG_SCHEME_ECDSA, * TPMS_SIG_SCHEME_ECDAA, TPMS_SIG_SCHEME_SM2, TPMS_SIG_SCHEME_ECSCHNORR, * TPMS_SCHEME_HMAC, TPMS_SCHEME_HASH, TPMS_NULL_SIG_SCHEME. * @return auditInfo - The auditInfo that was signed<br> * signature - The signature over auditInfo */ GetCommandAuditDigest(privacyHandle: tt.TPM_HANDLE, signHandle: tt.TPM_HANDLE, qualifyingData: Buffer, inScheme: tt.TPMU_SIG_SCHEME, continuation: (err: TpmError, res?: tt.GetCommandAuditDigestResponse) => void) { let req = new tt.TPM2_GetCommandAuditDigest_REQUEST(privacyHandle, signHandle, qualifyingData, inScheme); this.dispatchCommand(tt.TPM_CC.GetCommandAuditDigest, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.GetCommandAuditDigestResponse); setImmediate(continuation, this.lastError, res); }); } // GetCommandAuditDigest() /** This command returns the current values of Time and Clock. * @param privacyAdminHandle Handle of the privacy administrator (TPM_RH_ENDORSEMENT) * Auth Index: 1 * Auth Role: USER * @param signHandle The keyHandle identifier of a loaded key that can perform digital signatures * Auth Index: 2 * Auth Role: USER * @param qualifyingData Data to tick stamp * @param inScheme Signing scheme to use if the scheme for signHandle is TPM_ALG_NULL * One of: TPMS_SIG_SCHEME_RSASSA, TPMS_SIG_SCHEME_RSAPSS, TPMS_SIG_SCHEME_ECDSA, * TPMS_SIG_SCHEME_ECDAA, TPMS_SIG_SCHEME_SM2, TPMS_SIG_SCHEME_ECSCHNORR, * TPMS_SCHEME_HMAC, TPMS_SCHEME_HASH, TPMS_NULL_SIG_SCHEME. * @return timeInfo - Standard TPM-generated attestation block<br> * signature - The signature over timeInfo */ GetTime(privacyAdminHandle: tt.TPM_HANDLE, signHandle: tt.TPM_HANDLE, qualifyingData: Buffer, inScheme: tt.TPMU_SIG_SCHEME, continuation: (err: TpmError, res?: tt.GetTimeResponse) => void) { let req = new tt.TPM2_GetTime_REQUEST(privacyAdminHandle, signHandle, qualifyingData, inScheme); this.dispatchCommand(tt.TPM_CC.GetTime, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.GetTimeResponse); setImmediate(continuation, this.lastError, res); }); } // GetTime() /** The purpose of this command is to generate an X.509 certificate that proves an object * with a specific public key and attributes is loaded in the TPM. In contrast to * TPM2_Certify, which uses a TCG-defined data structure to convey attestation * information, TPM2_CertifyX509 encodes the attestation information in a DER-encoded * X.509 certificate that is compliant with RFC5280 Internet X.509 Public Key * Infrastructure Certificate and Certificate Revocation List (CRL) Profile. * @param objectHandle Handle of the object to be certified * Auth Index: 1 * Auth Role: ADMIN * @param signHandle Handle of the key used to sign the attestation structure * Auth Index: 2 * Auth Role: USER * @param reserved Shall be an Empty Buffer * @param inScheme Signing scheme to use if the scheme for signHandle is TPM_ALG_NULL * One of: TPMS_SIG_SCHEME_RSASSA, TPMS_SIG_SCHEME_RSAPSS, TPMS_SIG_SCHEME_ECDSA, * TPMS_SIG_SCHEME_ECDAA, TPMS_SIG_SCHEME_SM2, TPMS_SIG_SCHEME_ECSCHNORR, * TPMS_SCHEME_HMAC, TPMS_SCHEME_HASH, TPMS_NULL_SIG_SCHEME. * @param partialCertificate A DER encoded partial certificate * @return addedToCertificate - A DER encoded SEQUENCE containing the DER encoded fields * added to partialCertificate to make it a complete RFC5280 * TBSCertificate.<br> * tbsDigest - The digest that was signed<br> * signature - The signature over tbsDigest */ CertifyX509(objectHandle: tt.TPM_HANDLE, signHandle: tt.TPM_HANDLE, reserved: Buffer, inScheme: tt.TPMU_SIG_SCHEME, partialCertificate: Buffer, continuation: (err: TpmError, res?: tt.CertifyX509Response) => void) { let req = new tt.TPM2_CertifyX509_REQUEST(objectHandle, signHandle, reserved, inScheme, partialCertificate); this.dispatchCommand(tt.TPM_CC.CertifyX509, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.CertifyX509Response); setImmediate(continuation, this.lastError, res); }); } // CertifyX509() /** TPM2_Commit() performs the first part of an ECC anonymous signing operation. The TPM * will perform the point multiplications on the provided points and return intermediate * signing values. The signHandle parameter shall refer to an ECC key and the signing * scheme must be anonymous (TPM_RC_SCHEME). * @param signHandle Handle of the key that will be used in the signing operation * Auth Index: 1 * Auth Role: USER * @param P1 A point (M) on the curve used by signHandle * @param s2 Octet array used to derive x-coordinate of a base point * @param y2 Y coordinate of the point associated with s2 * @return K - ECC point K [ds](x2, y2)<br> * L - ECC point L [r](x2, y2)<br> * E - ECC point E [r]P1<br> * counter - Least-significant 16 bits of commitCount */ Commit(signHandle: tt.TPM_HANDLE, P1: tt.TPMS_ECC_POINT, s2: Buffer, y2: Buffer, continuation: (err: TpmError, res?: tt.CommitResponse) => void) { let req = new tt.TPM2_Commit_REQUEST(signHandle, P1, s2, y2); this.dispatchCommand(tt.TPM_CC.Commit, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.CommitResponse); setImmediate(continuation, this.lastError, res); }); } // Commit() /** TPM2_EC_Ephemeral() creates an ephemeral key for use in a two-phase key exchange protocol. * @param curveID The curve for the computed ephemeral point * @return Q - Ephemeral public key Q [r]G<br> * counter - Least-significant 16 bits of commitCount */ EC_Ephemeral(curveID: tt.TPM_ECC_CURVE, continuation: (err: TpmError, res?: tt.EC_EphemeralResponse) => void) { let req = new tt.TPM2_EC_Ephemeral_REQUEST(curveID); this.dispatchCommand(tt.TPM_CC.EC_Ephemeral, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.EC_EphemeralResponse); setImmediate(continuation, this.lastError, res); }); } // EC_Ephemeral() /** This command uses loaded keys to validate a signature on a message with the message * digest passed to the TPM. * @param keyHandle Handle of public key that will be used in the validation * Auth Index: None * @param digest Digest of the signed message * @param signature Signature to be tested * One of: TPMS_SIGNATURE_RSASSA, TPMS_SIGNATURE_RSAPSS, TPMS_SIGNATURE_ECDSA, * TPMS_SIGNATURE_ECDAA, TPMS_SIGNATURE_SM2, TPMS_SIGNATURE_ECSCHNORR, TPMT_HA, * TPMS_SCHEME_HASH, TPMS_NULL_SIGNATURE. * @return validation - This ticket is produced by TPM2_VerifySignature(). This formulation * is used for multiple ticket uses. The ticket provides evidence that * the TPM has validated that a digest was signed by a key with the Name * of keyName. The ticket is computed by */ VerifySignature(keyHandle: tt.TPM_HANDLE, digest: Buffer, signature: tt.TPMU_SIGNATURE, continuation: (err: TpmError, res?: tt.TPMT_TK_VERIFIED) => void) { let req = new tt.TPM2_VerifySignature_REQUEST(keyHandle, digest, signature); this.dispatchCommand(tt.TPM_CC.VerifySignature, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.VerifySignatureResponse); setImmediate(continuation, this.lastError, res?.validation); }); } // VerifySignature() /** This command causes the TPM to sign an externally provided hash with the specified * symmetric or asymmetric signing key. * @param keyHandle Handle of key that will perform signing * Auth Index: 1 * Auth Role: USER * @param digest Digest to be signed * @param inScheme Signing scheme to use if the scheme for keyHandle is TPM_ALG_NULL * One of: TPMS_SIG_SCHEME_RSASSA, TPMS_SIG_SCHEME_RSAPSS, TPMS_SIG_SCHEME_ECDSA, * TPMS_SIG_SCHEME_ECDAA, TPMS_SIG_SCHEME_SM2, TPMS_SIG_SCHEME_ECSCHNORR, * TPMS_SCHEME_HMAC, TPMS_SCHEME_HASH, TPMS_NULL_SIG_SCHEME. * @param validation Proof that digest was created by the TPM * If keyHandle is not a restricted signing key, then this may be a NULL Ticket with * tag = TPM_ST_CHECKHASH. * @return signature - The signature */ Sign(keyHandle: tt.TPM_HANDLE, digest: Buffer, inScheme: tt.TPMU_SIG_SCHEME, validation: tt.TPMT_TK_HASHCHECK, continuation: (err: TpmError, res?: tt.TPMU_SIGNATURE) => void) { let req = new tt.TPM2_Sign_REQUEST(keyHandle, digest, inScheme, validation); this.dispatchCommand(tt.TPM_CC.Sign, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.SignResponse); setImmediate(continuation, this.lastError, res?.signature); }); } // Sign() /** This command may be used by the Privacy Administrator or platform to change the audit * status of a command or to set the hash algorithm used for the audit digest, but not * both at the same time. * @param auth TPM_RH_OWNER or TPM_RH_PLATFORM+{PP} * Auth Index: 1 * Auth Role: USER * @param auditAlg Hash algorithm for the audit digest; if TPM_ALG_NULL, then the hash is * not * changed * @param setList List of commands that will be added to those that will be audited * @param clearList List of commands that will no longer be audited */ SetCommandCodeAuditStatus(auth: tt.TPM_HANDLE, auditAlg: tt.TPM_ALG_ID, setList: tt.TPM_CC[], clearList: tt.TPM_CC[], continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_SetCommandCodeAuditStatus_REQUEST(auth, auditAlg, setList, clearList); this.dispatchCommand(tt.TPM_CC.SetCommandCodeAuditStatus, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // SetCommandCodeAuditStatus() /** This command is used to cause an update to the indicated PCR. The digests parameter * contains one or more tagged digest values identified by an algorithm ID. For each * digest, the PCR associated with pcrHandle is Extended into the bank identified by the * tag (hashAlg). * @param pcrHandle Handle of the PCR * Auth Handle: 1 * Auth Role: USER * @param digests List of tagged digest values to be extended */ PCR_Extend(pcrHandle: tt.TPM_HANDLE, digests: tt.TPMT_HA[], continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_PCR_Extend_REQUEST(pcrHandle, digests); this.dispatchCommand(tt.TPM_CC.PCR_Extend, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // PCR_Extend() /** This command is used to cause an update to the indicated PCR. * @param pcrHandle Handle of the PCR * Auth Handle: 1 * Auth Role: USER * @param eventData Event data in sized buffer * @return digests - Table 80 shows the basic hash-agile structure used in this * specification. To handle hash agility, this structure uses the hashAlg * parameter to indicate the algorithm used to compute the digest and, by * implication, the size of the digest. */ PCR_Event(pcrHandle: tt.TPM_HANDLE, eventData: Buffer, continuation: (err: TpmError, res?: tt.TPMT_HA[]) => void) { let req = new tt.TPM2_PCR_Event_REQUEST(pcrHandle, eventData); this.dispatchCommand(tt.TPM_CC.PCR_Event, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.PCR_EventResponse); setImmediate(continuation, this.lastError, res?.digests); }); } // PCR_Event() /** This command returns the values of all PCR specified in pcrSelectionIn. * @param pcrSelectionIn The selection of PCR to read * @return pcrUpdateCounter - The current value of the PCR update counter<br> * pcrSelectionOut - The PCR in the returned list<br> * pcrValues - The contents of the PCR indicated in pcrSelectOut-˃ pcrSelection[] * as * tagged digests */ PCR_Read(pcrSelectionIn: tt.TPMS_PCR_SELECTION[], continuation: (err: TpmError, res?: tt.PCR_ReadResponse) => void) { let req = new tt.TPM2_PCR_Read_REQUEST(pcrSelectionIn); this.dispatchCommand(tt.TPM_CC.PCR_Read, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.PCR_ReadResponse); setImmediate(continuation, this.lastError, res); }); } // PCR_Read() /** This command is used to set the desired PCR allocation of PCR and algorithms. This * command requires Platform Authorization. * @param authHandle TPM_RH_PLATFORM+{PP} * Auth Index: 1 * Auth Role: USER * @param pcrAllocation The requested allocation * @return allocationSuccess - YES if the allocation succeeded<br> * maxPCR - Maximum number of PCR that may be in a bank<br> * sizeNeeded - Number of octets required to satisfy the request<br> * sizeAvailable - Number of octets available. Computed before the allocation. */ PCR_Allocate(authHandle: tt.TPM_HANDLE, pcrAllocation: tt.TPMS_PCR_SELECTION[], continuation: (err: TpmError, res?: tt.PCR_AllocateResponse) => void) { let req = new tt.TPM2_PCR_Allocate_REQUEST(authHandle, pcrAllocation); this.dispatchCommand(tt.TPM_CC.PCR_Allocate, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.PCR_AllocateResponse); setImmediate(continuation, this.lastError, res); }); } // PCR_Allocate() /** This command is used to associate a policy with a PCR or group of PCR. The policy * determines the conditions under which a PCR may be extended or reset. * @param authHandle TPM_RH_PLATFORM+{PP} * Auth Index: 1 * Auth Role: USER * @param authPolicy The desired authPolicy * @param hashAlg The hash algorithm of the policy * @param pcrNum The PCR for which the policy is to be set */ PCR_SetAuthPolicy(authHandle: tt.TPM_HANDLE, authPolicy: Buffer, hashAlg: tt.TPM_ALG_ID, pcrNum: tt.TPM_HANDLE, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_PCR_SetAuthPolicy_REQUEST(authHandle, authPolicy, hashAlg, pcrNum); this.dispatchCommand(tt.TPM_CC.PCR_SetAuthPolicy, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // PCR_SetAuthPolicy() /** This command changes the authValue of a PCR or group of PCR. * @param pcrHandle Handle for a PCR that may have an authorization value set * Auth Index: 1 * Auth Role: USER * @param auth The desired authorization value */ PCR_SetAuthValue(pcrHandle: tt.TPM_HANDLE, auth: Buffer, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_PCR_SetAuthValue_REQUEST(pcrHandle, auth); this.dispatchCommand(tt.TPM_CC.PCR_SetAuthValue, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // PCR_SetAuthValue() /** If the attribute of a PCR allows the PCR to be reset and proper authorization is * provided, then this command may be used to set the PCR in all banks to zero. The * attributes of the PCR may restrict the locality that can perform the reset operation. * @param pcrHandle The PCR to reset * Auth Index: 1 * Auth Role: USER */ PCR_Reset(pcrHandle: tt.TPM_HANDLE, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_PCR_Reset_REQUEST(pcrHandle); this.dispatchCommand(tt.TPM_CC.PCR_Reset, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // PCR_Reset() /** This command includes a signed authorization in a policy. The command ties the policy * to a signing key by including the Name of the signing key in the policyDigest * @param authObject Handle for a key that will validate the signature * Auth Index: None * @param policySession Handle for the policy session being extended * Auth Index: None * @param nonceTPM The policy nonce for the session * This can be the Empty Buffer. * @param cpHashA Digest of the command parameters to which this authorization is limited * This is not the cpHash for this command but the cpHash for the command to which * this policy session will be applied. If it is not limited, the parameter will be * the Empty Buffer. * @param policyRef A reference to a policy relating to the authorization may be the * Empty Buffer * Size is limited to be no larger than the nonce size supported on the TPM. * @param expiration Time when authorization will expire, measured in seconds from the time * that nonceTPM was generated * If expiration is non-negative, a NULL Ticket is returned. See 23.2.5. * @param auth Signed authorization (not optional) * One of: TPMS_SIGNATURE_RSASSA, TPMS_SIGNATURE_RSAPSS, TPMS_SIGNATURE_ECDSA, * TPMS_SIGNATURE_ECDAA, TPMS_SIGNATURE_SM2, TPMS_SIGNATURE_ECSCHNORR, TPMT_HA, * TPMS_SCHEME_HASH, TPMS_NULL_SIGNATURE. * @return timeout - Implementation-specific time value, used to indicate to the TPM when * the * ticket expires * NOTE If policyTicket is a NULL Ticket, then this shall be the Empty Buffer.<br> * policyTicket - Produced if the command succeeds and expiration in the command was * non-zero; this ticket will use the TPMT_ST_AUTH_SIGNED structure * tag. See 23.2.5 */ PolicySigned(authObject: tt.TPM_HANDLE, policySession: tt.TPM_HANDLE, nonceTPM: Buffer, cpHashA: Buffer, policyRef: Buffer, expiration: number, auth: tt.TPMU_SIGNATURE, continuation: (err: TpmError, res?: tt.PolicySignedResponse) => void) { let req = new tt.TPM2_PolicySigned_REQUEST(authObject, policySession, nonceTPM, cpHashA, policyRef, expiration, auth); this.dispatchCommand(tt.TPM_CC.PolicySigned, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.PolicySignedResponse); setImmediate(continuation, this.lastError, res); }); } // PolicySigned() /** This command includes a secret-based authorization to a policy. The caller proves * knowledge of the secret value using an authorization session using the authValue * associated with authHandle. A password session, an HMAC session, or a policy session * containing TPM2_PolicyAuthValue() or TPM2_PolicyPassword() will satisfy this requirement. * @param authHandle Handle for an entity providing the authorization * Auth Index: 1 * Auth Role: USER * @param policySession Handle for the policy session being extended * Auth Index: None * @param nonceTPM The policy nonce for the session * This can be the Empty Buffer. * @param cpHashA Digest of the command parameters to which this authorization is limited * This not the cpHash for this command but the cpHash for the command to which this * policy session will be applied. If it is not limited, the parameter will be the * Empty Buffer. * @param policyRef A reference to a policy relating to the authorization may be the * Empty Buffer * Size is limited to be no larger than the nonce size supported on the TPM. * @param expiration Time when authorization will expire, measured in seconds from the time * that nonceTPM was generated * If expiration is non-negative, a NULL Ticket is returned. See 23.2.5. * @return timeout - Implementation-specific time value used to indicate to the TPM when the * ticket expires<br> * policyTicket - Produced if the command succeeds and expiration in the command was * non-zero ( See 23.2.5). This ticket will use the * TPMT_ST_AUTH_SECRET structure tag */ PolicySecret(authHandle: tt.TPM_HANDLE, policySession: tt.TPM_HANDLE, nonceTPM: Buffer, cpHashA: Buffer, policyRef: Buffer, expiration: number, continuation: (err: TpmError, res?: tt.PolicySecretResponse) => void) { let req = new tt.TPM2_PolicySecret_REQUEST(authHandle, policySession, nonceTPM, cpHashA, policyRef, expiration); this.dispatchCommand(tt.TPM_CC.PolicySecret, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.PolicySecretResponse); setImmediate(continuation, this.lastError, res); }); } // PolicySecret() /** This command is similar to TPM2_PolicySigned() except that it takes a ticket instead * of a signed authorization. The ticket represents a validated authorization that had an * expiration time associated with it. * @param policySession Handle for the policy session being extended * Auth Index: None * @param timeout Time when authorization will expire * The contents are TPM specific. This shall be the value returned when ticket was * produced. * @param cpHashA Digest of the command parameters to which this authorization is limited * If it is not limited, the parameter will be the Empty Buffer. * @param policyRef Reference to a qualifier for the policy may be the Empty Buffer * @param authName Name of the object that provided the authorization * @param ticket An authorization ticket returned by the TPM in response to a * TPM2_PolicySigned() or TPM2_PolicySecret() */ PolicyTicket(policySession: tt.TPM_HANDLE, timeout: Buffer, cpHashA: Buffer, policyRef: Buffer, authName: Buffer, ticket: tt.TPMT_TK_AUTH, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_PolicyTicket_REQUEST(policySession, timeout, cpHashA, policyRef, authName, ticket); this.dispatchCommand(tt.TPM_CC.PolicyTicket, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // PolicyTicket() /** This command allows options in authorizations without requiring that the TPM evaluate * all of the options. If a policy may be satisfied by different sets of conditions, the * TPM need only evaluate one set that satisfies the policy. This command will indicate * that one of the required sets of conditions has been satisfied. * @param policySession Handle for the policy session being extended * Auth Index: None * @param pHashList The list of hashes to check for a match */ PolicyOR(policySession: tt.TPM_HANDLE, pHashList: tt.TPM2B_DIGEST[], continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_PolicyOR_REQUEST(policySession, pHashList); this.dispatchCommand(tt.TPM_CC.PolicyOR, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // PolicyOR() /** This command is used to cause conditional gating of a policy based on PCR. This * command together with TPM2_PolicyOR() allows one group of authorizations to occur when * PCR are in one state and a different set of authorizations when the PCR are in a * different state. * @param policySession Handle for the policy session being extended * Auth Index: None * @param pcrDigest Expected digest value of the selected PCR using the hash algorithm of * the * session; may be zero length * @param pcrs The PCR to include in the check digest */ PolicyPCR(policySession: tt.TPM_HANDLE, pcrDigest: Buffer, pcrs: tt.TPMS_PCR_SELECTION[], continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_PolicyPCR_REQUEST(policySession, pcrDigest, pcrs); this.dispatchCommand(tt.TPM_CC.PolicyPCR, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // PolicyPCR() /** This command indicates that the authorization will be limited to a specific locality. * @param policySession Handle for the policy session being extended * Auth Index: None * @param locality The allowed localities for the policy */ PolicyLocality(policySession: tt.TPM_HANDLE, locality: tt.TPMA_LOCALITY, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_PolicyLocality_REQUEST(policySession, locality); this.dispatchCommand(tt.TPM_CC.PolicyLocality, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // PolicyLocality() /** This command is used to cause conditional gating of a policy based on the contents of * an NV Index. It is an immediate assertion. The NV index is validated during the * TPM2_PolicyNV() command, not when the session is used for authorization. * @param authHandle Handle indicating the source of the authorization value * Auth Index: 1 * Auth Role: USER * @param nvIndex The NV Index of the area to read * Auth Index: None * @param policySession Handle for the policy session being extended * Auth Index: None * @param operandB The second operand * @param offset The octet offset in the NV Index for the start of operand A * @param operation The comparison to make */ PolicyNV(authHandle: tt.TPM_HANDLE, nvIndex: tt.TPM_HANDLE, policySession: tt.TPM_HANDLE, operandB: Buffer, offset: number, operation: tt.TPM_EO, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_PolicyNV_REQUEST(authHandle, nvIndex, policySession, operandB, offset, operation); this.dispatchCommand(tt.TPM_CC.PolicyNV, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // PolicyNV() /** This command is used to cause conditional gating of a policy based on the contents of * the TPMS_TIME_INFO structure. * @param policySession Handle for the policy session being extended * Auth Index: None * @param operandB The second operand * @param offset The octet offset in the TPMS_TIME_INFO structure for the start of * operand A * @param operation The comparison to make */ PolicyCounterTimer(policySession: tt.TPM_HANDLE, operandB: Buffer, offset: number, operation: tt.TPM_EO, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_PolicyCounterTimer_REQUEST(policySession, operandB, offset, operation); this.dispatchCommand(tt.TPM_CC.PolicyCounterTimer, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // PolicyCounterTimer() /** This command indicates that the authorization will be limited to a specific command code. * @param policySession Handle for the policy session being extended * Auth Index: None * @param code The allowed commandCode */ PolicyCommandCode(policySession: tt.TPM_HANDLE, code: tt.TPM_CC, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_PolicyCommandCode_REQUEST(policySession, code); this.dispatchCommand(tt.TPM_CC.PolicyCommandCode, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // PolicyCommandCode() /** This command indicates that physical presence will need to be asserted at the time the * authorization is performed. * @param policySession Handle for the policy session being extended * Auth Index: None */ PolicyPhysicalPresence(policySession: tt.TPM_HANDLE, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_PolicyPhysicalPresence_REQUEST(policySession); this.dispatchCommand(tt.TPM_CC.PolicyPhysicalPresence, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // PolicyPhysicalPresence() /** This command is used to allow a policy to be bound to a specific command and command parameters. * @param policySession Handle for the policy session being extended * Auth Index: None * @param cpHashA The cpHash added to the policy */ PolicyCpHash(policySession: tt.TPM_HANDLE, cpHashA: Buffer, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_PolicyCpHash_REQUEST(policySession, cpHashA); this.dispatchCommand(tt.TPM_CC.PolicyCpHash, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // PolicyCpHash() /** This command allows a policy to be bound to a specific set of TPM entities without * being bound to the parameters of the command. This is most useful for commands such as * TPM2_Duplicate() and for TPM2_PCR_Event() when the referenced PCR requires a policy. * @param policySession Handle for the policy session being extended * Auth Index: None * @param nameHash The digest to be added to the policy */ PolicyNameHash(policySession: tt.TPM_HANDLE, nameHash: Buffer, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_PolicyNameHash_REQUEST(policySession, nameHash); this.dispatchCommand(tt.TPM_CC.PolicyNameHash, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // PolicyNameHash() /** This command allows qualification of duplication to allow duplication to a selected * new parent. * @param policySession Handle for the policy session being extended * Auth Index: None * @param objectName The Name of the object to be duplicated * @param newParentName The Name of the new parent * @param includeObject If YES, the objectName will be included in the value in * policySessionpolicyDigest */ PolicyDuplicationSelect(policySession: tt.TPM_HANDLE, objectName: Buffer, newParentName: Buffer, includeObject: number, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_PolicyDuplicationSelect_REQUEST(policySession, objectName, newParentName, includeObject); this.dispatchCommand(tt.TPM_CC.PolicyDuplicationSelect, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // PolicyDuplicationSelect() /** This command allows policies to change. If a policy were static, then it would be * difficult to add users to a policy. This command lets a policy authority sign a new * policy so that it may be used in an existing policy. * @param policySession Handle for the policy session being extended * Auth Index: None * @param approvedPolicy Digest of the policy being approved * @param policyRef A policy qualifier * @param keySign Name of a key that can sign a policy addition * @param checkTicket Ticket validating that approvedPolicy and policyRef were signed by keySign */ PolicyAuthorize(policySession: tt.TPM_HANDLE, approvedPolicy: Buffer, policyRef: Buffer, keySign: Buffer, checkTicket: tt.TPMT_TK_VERIFIED, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_PolicyAuthorize_REQUEST(policySession, approvedPolicy, policyRef, keySign, checkTicket); this.dispatchCommand(tt.TPM_CC.PolicyAuthorize, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // PolicyAuthorize() /** This command allows a policy to be bound to the authorization value of the authorized entity. * @param policySession Handle for the policy session being extended * Auth Index: None */ PolicyAuthValue(policySession: tt.TPM_HANDLE, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_PolicyAuthValue_REQUEST(policySession); this.dispatchCommand(tt.TPM_CC.PolicyAuthValue, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // PolicyAuthValue() /** This command allows a policy to be bound to the authorization value of the authorized object. * @param policySession Handle for the policy session being extended * Auth Index: None */ PolicyPassword(policySession: tt.TPM_HANDLE, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_PolicyPassword_REQUEST(policySession); this.dispatchCommand(tt.TPM_CC.PolicyPassword, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // PolicyPassword() /** This command returns the current policyDigest of the session. This command allows the * TPM to be used to perform the actions required to pre-compute the authPolicy for an object. * @param policySession Handle for the policy session * Auth Index: None * @return policyDigest - The current value of the policySessionpolicyDigest */ PolicyGetDigest(policySession: tt.TPM_HANDLE, continuation: (err: TpmError, res?: Buffer) => void) { let req = new tt.TPM2_PolicyGetDigest_REQUEST(policySession); this.dispatchCommand(tt.TPM_CC.PolicyGetDigest, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.PolicyGetDigestResponse); setImmediate(continuation, this.lastError, res?.policyDigest); }); } // PolicyGetDigest() /** This command allows a policy to be bound to the TPMA_NV_WRITTEN attributes. This is a * deferred assertion. Values are stored in the policy session context and checked when * the policy is used for authorization. * @param policySession Handle for the policy session being extended * Auth Index: None * @param writtenSet YES if NV Index is required to have been written * NO if NV Index is required not to have been written */ PolicyNvWritten(policySession: tt.TPM_HANDLE, writtenSet: number, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_PolicyNvWritten_REQUEST(policySession, writtenSet); this.dispatchCommand(tt.TPM_CC.PolicyNvWritten, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // PolicyNvWritten() /** This command allows a policy to be bound to a specific creation template. This is most * useful for an object creation command such as TPM2_Create(), TPM2_CreatePrimary(), or * TPM2_CreateLoaded(). * @param policySession Handle for the policy session being extended * Auth Index: None * @param templateHash The digest to be added to the policy */ PolicyTemplate(policySession: tt.TPM_HANDLE, templateHash: Buffer, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_PolicyTemplate_REQUEST(policySession, templateHash); this.dispatchCommand(tt.TPM_CC.PolicyTemplate, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // PolicyTemplate() /** This command provides a capability that is the equivalent of a revocable policy. With * TPM2_PolicyAuthorize(), the authorization ticket never expires, so the authorization * may not be withdrawn. With this command, the approved policy is kept in an NV Index * location so that the policy may be changed as needed to render the old policy unusable. * @param authHandle Handle indicating the source of the authorization value * Auth Index: 1 * Auth Role: USER * @param nvIndex The NV Index of the area to read * Auth Index: None * @param policySession Handle for the policy session being extended * Auth Index: None */ PolicyAuthorizeNV(authHandle: tt.TPM_HANDLE, nvIndex: tt.TPM_HANDLE, policySession: tt.TPM_HANDLE, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_PolicyAuthorizeNV_REQUEST(authHandle, nvIndex, policySession); this.dispatchCommand(tt.TPM_CC.PolicyAuthorizeNV, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // PolicyAuthorizeNV() /** This command is used to create a Primary Object under one of the Primary Seeds or a * Temporary Object under TPM_RH_NULL. The command uses a TPM2B_PUBLIC as a template for * the object to be created. The size of the unique field shall not be checked for * consistency with the other object parameters. The command will create and load a * Primary Object. The sensitive area is not returned. * @param primaryHandle TPM_RH_ENDORSEMENT, TPM_RH_OWNER, TPM_RH_PLATFORM+{PP}, or TPM_RH_NULL * Auth Index: 1 * Auth Role: USER * @param inSensitive The sensitive data, see TPM 2.0 Part 1 Sensitive Values * @param inPublic The public template * @param outsideInfo Data that will be included in the creation data for this object to * provide permanent, verifiable linkage between this object and some object owner * data * @param creationPCR PCR that will be used in creation data * @return handle - Handle of type TPM_HT_TRANSIENT for created Primary Object<br> * outPublic - The public portion of the created object<br> * creationData - Contains a TPMT_CREATION_DATA<br> * creationHash - Digest of creationData using nameAlg of outPublic<br> * creationTicket - Ticket used by TPM2_CertifyCreation() to validate that the * creation data was produced by the TPM<br> * name - The name of the created object */ CreatePrimary(primaryHandle: tt.TPM_HANDLE, inSensitive: tt.TPMS_SENSITIVE_CREATE, inPublic: tt.TPMT_PUBLIC, outsideInfo: Buffer, creationPCR: tt.TPMS_PCR_SELECTION[], continuation: (err: TpmError, res?: tt.CreatePrimaryResponse) => void) { let req = new tt.TPM2_CreatePrimary_REQUEST(primaryHandle, inSensitive, inPublic, outsideInfo, creationPCR); this.dispatchCommand(tt.TPM_CC.CreatePrimary, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.CreatePrimaryResponse); setImmediate(continuation, this.lastError, res); }); } // CreatePrimary() /** This command enables and disables use of a hierarchy and its associated NV storage. * The command allows phEnable, phEnableNV, shEnable, and ehEnable to be changed when the * proper authorization is provided. * @param authHandle TPM_RH_ENDORSEMENT, TPM_RH_OWNER or TPM_RH_PLATFORM+{PP} * Auth Index: 1 * Auth Role: USER * @param enable The enable being modified * TPM_RH_ENDORSEMENT, TPM_RH_OWNER, TPM_RH_PLATFORM, or TPM_RH_PLATFORM_NV * @param state YES if the enable should be SET, NO if the enable should be CLEAR */ HierarchyControl(authHandle: tt.TPM_HANDLE, enable: tt.TPM_HANDLE, state: number, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_HierarchyControl_REQUEST(authHandle, enable, state); this.dispatchCommand(tt.TPM_CC.HierarchyControl, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // HierarchyControl() /** This command allows setting of the authorization policy for the lockout * (lockoutPolicy), the platform hierarchy (platformPolicy), the storage hierarchy * (ownerPolicy), and the endorsement hierarchy (endorsementPolicy). On TPMs implementing * Authenticated Countdown Timers (ACT), this command may also be used to set the * authorization policy for an ACT. * @param authHandle TPM_RH_LOCKOUT, TPM_RH_ENDORSEMENT, TPM_RH_OWNER, TPMI_RH_ACT or * TPM_RH_PLATFORM+{PP} * Auth Index: 1 * Auth Role: USER * @param authPolicy An authorization policy digest; may be the Empty Buffer * If hashAlg is TPM_ALG_NULL, then this shall be an Empty Buffer. * @param hashAlg The hash algorithm to use for the policy * If the authPolicy is an Empty Buffer, then this field shall be TPM_ALG_NULL. */ SetPrimaryPolicy(authHandle: tt.TPM_HANDLE, authPolicy: Buffer, hashAlg: tt.TPM_ALG_ID, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_SetPrimaryPolicy_REQUEST(authHandle, authPolicy, hashAlg); this.dispatchCommand(tt.TPM_CC.SetPrimaryPolicy, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // SetPrimaryPolicy() /** This replaces the current platform primary seed (PPS) with a value from the RNG and * sets platformPolicy to the default initialization value (the Empty Buffer). * @param authHandle TPM_RH_PLATFORM+{PP} * Auth Index: 1 * Auth Role: USER */ ChangePPS(authHandle: tt.TPM_HANDLE, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_ChangePPS_REQUEST(authHandle); this.dispatchCommand(tt.TPM_CC.ChangePPS, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // ChangePPS() /** This replaces the current endorsement primary seed (EPS) with a value from the RNG and * sets the Endorsement hierarchy controls to their default initialization values: * ehEnable is SET, endorsementAuth and endorsementPolicy are both set to the Empty * Buffer. It will flush any resident objects (transient or persistent) in the * Endorsement hierarchy and not allow objects in the hierarchy associated with the * previous EPS to be loaded. * @param authHandle TPM_RH_PLATFORM+{PP} * Auth Handle: 1 * Auth Role: USER */ ChangeEPS(authHandle: tt.TPM_HANDLE, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_ChangeEPS_REQUEST(authHandle); this.dispatchCommand(tt.TPM_CC.ChangeEPS, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // ChangeEPS() /** This command removes all TPM context associated with a specific Owner. * @param authHandle TPM_RH_LOCKOUT or TPM_RH_PLATFORM+{PP} * Auth Handle: 1 * Auth Role: USER */ Clear(authHandle: tt.TPM_HANDLE, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_Clear_REQUEST(authHandle); this.dispatchCommand(tt.TPM_CC.Clear, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // Clear() /** TPM2_ClearControl() disables and enables the execution of TPM2_Clear(). * @param auth TPM_RH_LOCKOUT or TPM_RH_PLATFORM+{PP} * Auth Handle: 1 * Auth Role: USER * @param disable YES if the disableOwnerClear flag is to be SET, NO if the flag is to be * CLEAR. */ ClearControl(auth: tt.TPM_HANDLE, disable: number, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_ClearControl_REQUEST(auth, disable); this.dispatchCommand(tt.TPM_CC.ClearControl, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // ClearControl() /** This command allows the authorization secret for a hierarchy or lockout to be changed * using the current authorization value as the command authorization. * @param authHandle TPM_RH_LOCKOUT, TPM_RH_ENDORSEMENT, TPM_RH_OWNER or TPM_RH_PLATFORM+{PP} * Auth Index: 1 * Auth Role: USER * @param newAuth New authorization value */ HierarchyChangeAuth(authHandle: tt.TPM_HANDLE, newAuth: Buffer, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_HierarchyChangeAuth_REQUEST(authHandle, newAuth); this.dispatchCommand(tt.TPM_CC.HierarchyChangeAuth, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // HierarchyChangeAuth() /** This command cancels the effect of a TPM lockout due to a number of successive * authorization failures. If this command is properly authorized, the lockout counter is * set to zero. * @param lockHandle TPM_RH_LOCKOUT * Auth Index: 1 * Auth Role: USER */ DictionaryAttackLockReset(lockHandle: tt.TPM_HANDLE, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_DictionaryAttackLockReset_REQUEST(lockHandle); this.dispatchCommand(tt.TPM_CC.DictionaryAttackLockReset, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // DictionaryAttackLockReset() /** This command changes the lockout parameters. * @param lockHandle TPM_RH_LOCKOUT * Auth Index: 1 * Auth Role: USER * @param newMaxTries Count of authorization failures before the lockout is imposed * @param newRecoveryTime Time in seconds before the authorization failure count is * automatically decremented * A value of zero indicates that DA protection is disabled. * @param lockoutRecovery Time in seconds after a lockoutAuth failure before use of * lockoutAuth is allowed * A value of zero indicates that a reboot is required. */ DictionaryAttackParameters(lockHandle: tt.TPM_HANDLE, newMaxTries: number, newRecoveryTime: number, lockoutRecovery: number, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_DictionaryAttackParameters_REQUEST(lockHandle, newMaxTries, newRecoveryTime, lockoutRecovery); this.dispatchCommand(tt.TPM_CC.DictionaryAttackParameters, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // DictionaryAttackParameters() /** This command is used to determine which commands require assertion of Physical * Presence (PP) in addition to platformAuth/platformPolicy. * @param auth TPM_RH_PLATFORM+PP * Auth Index: 1 * Auth Role: USER + Physical Presence * @param setList List of commands to be added to those that will require that Physical * Presence be asserted * @param clearList List of commands that will no longer require that Physical Presence * be asserted */ PP_Commands(auth: tt.TPM_HANDLE, setList: tt.TPM_CC[], clearList: tt.TPM_CC[], continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_PP_Commands_REQUEST(auth, setList, clearList); this.dispatchCommand(tt.TPM_CC.PP_Commands, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // PP_Commands() /** This command allows the platform to change the set of algorithms that are used by the * TPM. The algorithmSet setting is a vendor-dependent value. * @param authHandle TPM_RH_PLATFORM * Auth Index: 1 * Auth Role: USER * @param algorithmSet A TPM vendor-dependent value indicating the algorithm set selection */ SetAlgorithmSet(authHandle: tt.TPM_HANDLE, algorithmSet: number, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_SetAlgorithmSet_REQUEST(authHandle, algorithmSet); this.dispatchCommand(tt.TPM_CC.SetAlgorithmSet, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // SetAlgorithmSet() /** This command uses platformPolicy and a TPM Vendor Authorization Key to authorize a * Field Upgrade Manifest. * @param authorization TPM_RH_PLATFORM+{PP} * Auth Index:1 * Auth Role: ADMIN * @param keyHandle Handle of a public area that contains the TPM Vendor Authorization Key * that will be used to validate manifestSignature * Auth Index: None * @param fuDigest Digest of the first block in the field upgrade sequence * @param manifestSignature Signature over fuDigest using the key associated with keyHandle * (not optional) * One of: TPMS_SIGNATURE_RSASSA, TPMS_SIGNATURE_RSAPSS, TPMS_SIGNATURE_ECDSA, * TPMS_SIGNATURE_ECDAA, TPMS_SIGNATURE_SM2, TPMS_SIGNATURE_ECSCHNORR, TPMT_HA, * TPMS_SCHEME_HASH, TPMS_NULL_SIGNATURE. */ FieldUpgradeStart(authorization: tt.TPM_HANDLE, keyHandle: tt.TPM_HANDLE, fuDigest: Buffer, manifestSignature: tt.TPMU_SIGNATURE, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_FieldUpgradeStart_REQUEST(authorization, keyHandle, fuDigest, manifestSignature); this.dispatchCommand(tt.TPM_CC.FieldUpgradeStart, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // FieldUpgradeStart() /** This command will take the actual field upgrade image to be installed on the TPM. The * exact format of fuData is vendor-specific. This command is only possible following a * successful TPM2_FieldUpgradeStart(). If the TPM has not received a properly authorized * TPM2_FieldUpgradeStart(), then the TPM shall return TPM_RC_FIELDUPGRADE. * @param fuData Field upgrade image data * @return nextDigest - Tagged digest of the next block * TPM_ALG_NULL if field update is complete<br> * firstDigest - Tagged digest of the first block of the sequence */ FieldUpgradeData(fuData: Buffer, continuation: (err: TpmError, res?: tt.FieldUpgradeDataResponse) => void) { let req = new tt.TPM2_FieldUpgradeData_REQUEST(fuData); this.dispatchCommand(tt.TPM_CC.FieldUpgradeData, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.FieldUpgradeDataResponse); setImmediate(continuation, this.lastError, res); }); } // FieldUpgradeData() /** This command is used to read a copy of the current firmware installed in the TPM. * @param sequenceNumber The number of previous calls to this command in this sequence * set to 0 on the first call * @return fuData - Field upgrade image data */ FirmwareRead(sequenceNumber: number, continuation: (err: TpmError, res?: Buffer) => void) { let req = new tt.TPM2_FirmwareRead_REQUEST(sequenceNumber); this.dispatchCommand(tt.TPM_CC.FirmwareRead, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.FirmwareReadResponse); setImmediate(continuation, this.lastError, res?.fuData); }); } // FirmwareRead() /** This command saves a session context, object context, or sequence object context * outside the TPM. * @param saveHandle Handle of the resource to save * Auth Index: None * @return context - This structure is used in TPM2_ContextLoad() and TPM2_ContextSave(). * If * the values of the TPMS_CONTEXT structure in TPM2_ContextLoad() are not * the same as the values when the context was saved (TPM2_ContextSave()), * then the TPM shall not load the context. */ ContextSave(saveHandle: tt.TPM_HANDLE, continuation: (err: TpmError, res?: tt.TPMS_CONTEXT) => void) { let req = new tt.TPM2_ContextSave_REQUEST(saveHandle); this.dispatchCommand(tt.TPM_CC.ContextSave, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.ContextSaveResponse); setImmediate(continuation, this.lastError, res?.context); }); } // ContextSave() /** This command is used to reload a context that has been saved by TPM2_ContextSave(). * @param context The context blob * @return handle - The handle assigned to the resource after it has been successfully loaded */ ContextLoad(context: tt.TPMS_CONTEXT, continuation: (err: TpmError, res?: tt.TPM_HANDLE) => void) { let req = new tt.TPM2_ContextLoad_REQUEST(context); this.dispatchCommand(tt.TPM_CC.ContextLoad, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.ContextLoadResponse); setImmediate(continuation, this.lastError, res?.handle); }); } // ContextLoad() /** This command causes all context associated with a loaded object, sequence object, or * session to be removed from TPM memory. * @param flushHandle The handle of the item to flush * NOTE This is a use of a handle as a parameter. */ FlushContext(flushHandle: tt.TPM_HANDLE, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_FlushContext_REQUEST(flushHandle); this.dispatchCommand(tt.TPM_CC.FlushContext, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // FlushContext() /** This command allows certain Transient Objects to be made persistent or a persistent * object to be evicted. * @param auth TPM_RH_OWNER or TPM_RH_PLATFORM+{PP} * Auth Handle: 1 * Auth Role: USER * @param objectHandle The handle of a loaded object * Auth Index: None * @param persistentHandle If objectHandle is a transient object handle, then this is the * persistent handle for the object * if objectHandle is a persistent object handle, then it shall be the same value as * persistentHandle */ EvictControl(auth: tt.TPM_HANDLE, objectHandle: tt.TPM_HANDLE, persistentHandle: tt.TPM_HANDLE, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_EvictControl_REQUEST(auth, objectHandle, persistentHandle); this.dispatchCommand(tt.TPM_CC.EvictControl, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // EvictControl() /** This command reads the current TPMS_TIME_INFO structure that contains the current * setting of Time, Clock, resetCount, and restartCount. * @return currentTime - This structure is used in, e.g., the TPM2_GetTime() attestation and * TPM2_ReadClock(). */ ReadClock(continuation: (err: TpmError, res?: tt.TPMS_TIME_INFO) => void) { let req = new tt.TPM2_ReadClock_REQUEST(); this.dispatchCommand(tt.TPM_CC.ReadClock, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.ReadClockResponse); setImmediate(continuation, this.lastError, res?.currentTime); }); } // ReadClock() /** This command is used to advance the value of the TPMs Clock. The command will fail if * newTime is less than the current value of Clock or if the new time is greater than * FFFF00000000000016. If both of these checks succeed, Clock is set to newTime. If * either of these checks fails, the TPM shall return TPM_RC_VALUE and make no change to Clock. * @param auth TPM_RH_OWNER or TPM_RH_PLATFORM+{PP} * Auth Handle: 1 * Auth Role: USER * @param newTime New Clock setting in milliseconds */ ClockSet(auth: tt.TPM_HANDLE, newTime: number, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_ClockSet_REQUEST(auth, newTime); this.dispatchCommand(tt.TPM_CC.ClockSet, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // ClockSet() /** This command adjusts the rate of advance of Clock and Time to provide a better * approximation to real time. * @param auth TPM_RH_OWNER or TPM_RH_PLATFORM+{PP} * Auth Handle: 1 * Auth Role: USER * @param rateAdjust Adjustment to current Clock update rate */ ClockRateAdjust(auth: tt.TPM_HANDLE, rateAdjust: tt.TPM_CLOCK_ADJUST, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_ClockRateAdjust_REQUEST(auth, rateAdjust); this.dispatchCommand(tt.TPM_CC.ClockRateAdjust, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // ClockRateAdjust() /** This command returns various information regarding the TPM and its current state. * @param capability Group selection; determines the format of the response * @param property Further definition of information * @param propertyCount Number of properties of the indicated type to return * @return moreData - Flag to indicate if there are more values of this type<br> * capabilityData - The capability data */ GetCapability(capability: tt.TPM_CAP, property: number, propertyCount: number, continuation: (err: TpmError, res?: tt.GetCapabilityResponse) => void) { let req = new tt.TPM2_GetCapability_REQUEST(capability, property, propertyCount); this.dispatchCommand(tt.TPM_CC.GetCapability, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.GetCapabilityResponse); setImmediate(continuation, this.lastError, res); }); } // GetCapability() /** This command is used to check to see if specific combinations of algorithm parameters * are supported. * @param parameters Algorithm parameters to be validated * One of: TPMS_KEYEDHASH_PARMS, TPMS_SYMCIPHER_PARMS, TPMS_RSA_PARMS, TPMS_ECC_PARMS, * TPMS_ASYM_PARMS. */ TestParms(parameters: tt.TPMU_PUBLIC_PARMS, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_TestParms_REQUEST(parameters); this.dispatchCommand(tt.TPM_CC.TestParms, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // TestParms() /** This command defines the attributes of an NV Index and causes the TPM to reserve space * to hold the data associated with the NV Index. If a definition already exists at the * NV Index, the TPM will return TPM_RC_NV_DEFINED. * @param authHandle TPM_RH_OWNER or TPM_RH_PLATFORM+{PP} * Auth Index: 1 * Auth Role: USER * @param auth The authorization value * @param publicInfo The public parameters of the NV area */ NV_DefineSpace(authHandle: tt.TPM_HANDLE, auth: Buffer, publicInfo: tt.TPMS_NV_PUBLIC, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_NV_DefineSpace_REQUEST(authHandle, auth, publicInfo); this.dispatchCommand(tt.TPM_CC.NV_DefineSpace, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // NV_DefineSpace() /** This command removes an Index from the TPM. * @param authHandle TPM_RH_OWNER or TPM_RH_PLATFORM+{PP} * Auth Index: 1 * Auth Role: USER * @param nvIndex The NV Index to remove from NV space * Auth Index: None */ NV_UndefineSpace(authHandle: tt.TPM_HANDLE, nvIndex: tt.TPM_HANDLE, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_NV_UndefineSpace_REQUEST(authHandle, nvIndex); this.dispatchCommand(tt.TPM_CC.NV_UndefineSpace, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // NV_UndefineSpace() /** This command allows removal of a platform-created NV Index that has * TPMA_NV_POLICY_DELETE SET. * @param nvIndex Index to be deleted * Auth Index: 1 * Auth Role: ADMIN * @param platform TPM_RH_PLATFORM + {PP} * Auth Index: 2 * Auth Role: USER */ NV_UndefineSpaceSpecial(nvIndex: tt.TPM_HANDLE, platform: tt.TPM_HANDLE, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_NV_UndefineSpaceSpecial_REQUEST(nvIndex, platform); this.dispatchCommand(tt.TPM_CC.NV_UndefineSpaceSpecial, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // NV_UndefineSpaceSpecial() /** This command is used to read the public area and Name of an NV Index. The public area * of an Index is not privacy-sensitive and no authorization is required to read this data. * @param nvIndex The NV Index * Auth Index: None * @return nvPublic - The public area of the NV Index<br> * nvName - The Name of the nvIndex */ NV_ReadPublic(nvIndex: tt.TPM_HANDLE, continuation: (err: TpmError, res?: tt.NV_ReadPublicResponse) => void) { let req = new tt.TPM2_NV_ReadPublic_REQUEST(nvIndex); this.dispatchCommand(tt.TPM_CC.NV_ReadPublic, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.NV_ReadPublicResponse); setImmediate(continuation, this.lastError, res); }); } // NV_ReadPublic() /** This command writes a value to an area in NV memory that was previously defined by * TPM2_NV_DefineSpace(). * @param authHandle Handle indicating the source of the authorization value * Auth Index: 1 * Auth Role: USER * @param nvIndex The NV Index of the area to write * Auth Index: None * @param data The data to write * @param offset The octet offset into the NV Area */ NV_Write(authHandle: tt.TPM_HANDLE, nvIndex: tt.TPM_HANDLE, data: Buffer, offset: number, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_NV_Write_REQUEST(authHandle, nvIndex, data, offset); this.dispatchCommand(tt.TPM_CC.NV_Write, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // NV_Write() /** This command is used to increment the value in an NV Index that has the TPM_NT_COUNTER * attribute. The data value of the NV Index is incremented by one. * @param authHandle Handle indicating the source of the authorization value * Auth Index: 1 * Auth Role: USER * @param nvIndex The NV Index to increment * Auth Index: None */ NV_Increment(authHandle: tt.TPM_HANDLE, nvIndex: tt.TPM_HANDLE, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_NV_Increment_REQUEST(authHandle, nvIndex); this.dispatchCommand(tt.TPM_CC.NV_Increment, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // NV_Increment() /** This command extends a value to an area in NV memory that was previously defined by * TPM2_NV_DefineSpace. * @param authHandle Handle indicating the source of the authorization value * Auth Index: 1 * Auth Role: USER * @param nvIndex The NV Index to extend * Auth Index: None * @param data The data to extend */ NV_Extend(authHandle: tt.TPM_HANDLE, nvIndex: tt.TPM_HANDLE, data: Buffer, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_NV_Extend_REQUEST(authHandle, nvIndex, data); this.dispatchCommand(tt.TPM_CC.NV_Extend, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // NV_Extend() /** This command is used to SET bits in an NV Index that was created as a bit field. Any * number of bits from 0 to 64 may be SET. The contents of bits are ORed with the current * contents of the NV Index. * @param authHandle Handle indicating the source of the authorization value * Auth Index: 1 * Auth Role: USER * @param nvIndex NV Index of the area in which the bit is to be set * Auth Index: None * @param bits The data to OR with the current contents */ NV_SetBits(authHandle: tt.TPM_HANDLE, nvIndex: tt.TPM_HANDLE, bits: number, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_NV_SetBits_REQUEST(authHandle, nvIndex, bits); this.dispatchCommand(tt.TPM_CC.NV_SetBits, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // NV_SetBits() /** If the TPMA_NV_WRITEDEFINE or TPMA_NV_WRITE_STCLEAR attributes of an NV location are * SET, then this command may be used to inhibit further writes of the NV Index. * @param authHandle Handle indicating the source of the authorization value * Auth Index: 1 * Auth Role: USER * @param nvIndex The NV Index of the area to lock * Auth Index: None */ NV_WriteLock(authHandle: tt.TPM_HANDLE, nvIndex: tt.TPM_HANDLE, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_NV_WriteLock_REQUEST(authHandle, nvIndex); this.dispatchCommand(tt.TPM_CC.NV_WriteLock, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // NV_WriteLock() /** The command will SET TPMA_NV_WRITELOCKED for all indexes that have their * TPMA_NV_GLOBALLOCK attribute SET. * @param authHandle TPM_RH_OWNER or TPM_RH_PLATFORM+{PP} * Auth Index: 1 * Auth Role: USER */ NV_GlobalWriteLock(authHandle: tt.TPM_HANDLE, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_NV_GlobalWriteLock_REQUEST(authHandle); this.dispatchCommand(tt.TPM_CC.NV_GlobalWriteLock, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // NV_GlobalWriteLock() /** This command reads a value from an area in NV memory previously defined by TPM2_NV_DefineSpace(). * @param authHandle The handle indicating the source of the authorization value * Auth Index: 1 * Auth Role: USER * @param nvIndex The NV Index to be read * Auth Index: None * @param size Number of octets to read * @param offset Octet offset into the NV area * This value shall be less than or equal to the size of the nvIndex data. * @return data - The data read */ NV_Read(authHandle: tt.TPM_HANDLE, nvIndex: tt.TPM_HANDLE, size: number, offset: number, continuation: (err: TpmError, res?: Buffer) => void) { let req = new tt.TPM2_NV_Read_REQUEST(authHandle, nvIndex, size, offset); this.dispatchCommand(tt.TPM_CC.NV_Read, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.NV_ReadResponse); setImmediate(continuation, this.lastError, res?.data); }); } // NV_Read() /** If TPMA_NV_READ_STCLEAR is SET in an Index, then this command may be used to prevent * further reads of the NV Index until the next TPM2_Startup (TPM_SU_CLEAR). * @param authHandle The handle indicating the source of the authorization value * Auth Index: 1 * Auth Role: USER * @param nvIndex The NV Index to be locked * Auth Index: None */ NV_ReadLock(authHandle: tt.TPM_HANDLE, nvIndex: tt.TPM_HANDLE, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_NV_ReadLock_REQUEST(authHandle, nvIndex); this.dispatchCommand(tt.TPM_CC.NV_ReadLock, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // NV_ReadLock() /** This command allows the authorization secret for an NV Index to be changed. * @param nvIndex Handle of the entity * Auth Index: 1 * Auth Role: ADMIN * @param newAuth New authorization value */ NV_ChangeAuth(nvIndex: tt.TPM_HANDLE, newAuth: Buffer, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_NV_ChangeAuth_REQUEST(nvIndex, newAuth); this.dispatchCommand(tt.TPM_CC.NV_ChangeAuth, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // NV_ChangeAuth() /** The purpose of this command is to certify the contents of an NV Index or portion of an * NV Index. * @param signHandle Handle of the key used to sign the attestation structure * Auth Index: 1 * Auth Role: USER * @param authHandle Handle indicating the source of the authorization value for the NV Index * Auth Index: 2 * Auth Role: USER * @param nvIndex Index for the area to be certified * Auth Index: None * @param qualifyingData User-provided qualifying data * @param inScheme Signing scheme to use if the scheme for signHandle is TPM_ALG_NULL * One of: TPMS_SIG_SCHEME_RSASSA, TPMS_SIG_SCHEME_RSAPSS, TPMS_SIG_SCHEME_ECDSA, * TPMS_SIG_SCHEME_ECDAA, TPMS_SIG_SCHEME_SM2, TPMS_SIG_SCHEME_ECSCHNORR, * TPMS_SCHEME_HMAC, TPMS_SCHEME_HASH, TPMS_NULL_SIG_SCHEME. * @param size Number of octets to certify * @param offset Octet offset into the NV area * This value shall be less than or equal to the size of the nvIndex data. * @return certifyInfo - The structure that was signed<br> * signature - The asymmetric signature over certifyInfo using the key referenced * by signHandle */ NV_Certify(signHandle: tt.TPM_HANDLE, authHandle: tt.TPM_HANDLE, nvIndex: tt.TPM_HANDLE, qualifyingData: Buffer, inScheme: tt.TPMU_SIG_SCHEME, size: number, offset: number, continuation: (err: TpmError, res?: tt.NV_CertifyResponse) => void) { let req = new tt.TPM2_NV_Certify_REQUEST(signHandle, authHandle, nvIndex, qualifyingData, inScheme, size, offset); this.dispatchCommand(tt.TPM_CC.NV_Certify, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.NV_CertifyResponse); setImmediate(continuation, this.lastError, res); }); } // NV_Certify() /** The purpose of this command is to obtain information about an Attached Component * referenced by an AC handle. * @param ac Handle indicating the Attached Component * Auth Index: None * @param capability Starting info type * @param count Maximum number of values to return * @return moreData - Flag to indicate whether there are more values<br> * capabilitiesData - List of capabilities */ AC_GetCapability(ac: tt.TPM_HANDLE, capability: tt.TPM_AT, count: number, continuation: (err: TpmError, res?: tt.AC_GetCapabilityResponse) => void) { let req = new tt.TPM2_AC_GetCapability_REQUEST(ac, capability, count); this.dispatchCommand(tt.TPM_CC.AC_GetCapability, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.AC_GetCapabilityResponse); setImmediate(continuation, this.lastError, res); }); } // AC_GetCapability() /** The purpose of this command is to send (copy) a loaded object from the TPM to an * Attached Component. * @param sendObject Handle of the object being sent to ac * Auth Index: 1 * Auth Role: DUP * @param authHandle The handle indicating the source of the authorization value * Auth Index: 2 * Auth Role: USER * @param ac Handle indicating the Attached Component to which the object will be sent * Auth Index: None * @param acDataIn Optional non sensitive information related to the object * @return acDataOut - May include AC specific data or information about an error. */ AC_Send(sendObject: tt.TPM_HANDLE, authHandle: tt.TPM_HANDLE, ac: tt.TPM_HANDLE, acDataIn: Buffer, continuation: (err: TpmError, res?: tt.TPMS_AC_OUTPUT) => void) { let req = new tt.TPM2_AC_Send_REQUEST(sendObject, authHandle, ac, acDataIn); this.dispatchCommand(tt.TPM_CC.AC_Send, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.AC_SendResponse); setImmediate(continuation, this.lastError, res?.acDataOut); }); } // AC_Send() /** This command allows qualification of the sending (copying) of an Object to an Attached * Component (AC). Qualification includes selection of the receiving AC and the method of * authentication for the AC, and, in certain circumstances, the Object to be sent may be * specified. * @param policySession Handle for the policy session being extended * Auth Index: None * @param objectName The Name of the Object to be sent * @param authHandleName The Name associated with authHandle used in the TPM2_AC_Send() command * @param acName The Name of the Attached Component to which the Object will be sent * @param includeObject If SET, objectName will be included in the value in * policySessionpolicyDigest */ Policy_AC_SendSelect(policySession: tt.TPM_HANDLE, objectName: Buffer, authHandleName: Buffer, acName: Buffer, includeObject: number, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_Policy_AC_SendSelect_REQUEST(policySession, objectName, authHandleName, acName, includeObject); this.dispatchCommand(tt.TPM_CC.Policy_AC_SendSelect, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // Policy_AC_SendSelect() /** This command is used to set the time remaining before an Authenticated Countdown Timer * (ACT) expires. * @param actHandle Handle of the selected ACT * Auth Index: 1 * Auth Role: USER * @param startTimeout The start timeout value for the ACT in seconds */ ACT_SetTimeout(actHandle: tt.TPM_HANDLE, startTimeout: number, continuation: (err: TpmError, res?: void) => void) { let req = new tt.TPM2_ACT_SetTimeout_REQUEST(actHandle, startTimeout); this.dispatchCommand(tt.TPM_CC.ACT_SetTimeout, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf); setImmediate(continuation, this.lastError); }); } // ACT_SetTimeout() /** This is a placeholder to allow testing of the dispatch code. * @param inputData Dummy data * @return outputData - Dummy data */ Vendor_TCG_Test(inputData: Buffer, continuation: (err: TpmError, res?: Buffer) => void) { let req = new tt.TPM2_Vendor_TCG_Test_REQUEST(inputData); this.dispatchCommand(tt.TPM_CC.Vendor_TCG_Test, req, (respBuf: TpmBuffer): void => { let res = this.processResponse(respBuf, tt.Vendor_TCG_TestResponse); setImmediate(continuation, this.lastError, res?.outputData); }); } // Vendor_TCG_Test() } // class Tpm
the_stack
import * as path from "path"; import { DataType } from "./dataType"; import { Location, Uri, TextDocument, Position, Range } from "vscode"; import { Function, getScriptFunctionArgRanges } from "./function"; import { Parameter } from "./parameter"; import { Signature } from "./signature"; import { Component, isSubcomponentOrEqual } from "./component"; import { Variable, parseVariableAssignments, collectDocumentVariableAssignments, getApplicationVariables, getBestMatchingVariable, getVariableExpressionPrefixPattern } from "./variable"; import { Scope } from "./scope"; import { DocBlockKeyValue, parseDocBlock, getKeyPattern } from "./docblock"; import { Attributes, Attribute, parseAttributes } from "./attribute"; import { equalsIgnoreCase } from "../utils/textUtil"; import { MyMap, MySet } from "../utils/collections"; import { getComponent, hasComponent } from "../features/cachedEntities"; import { parseTags, Tag } from "./tag"; import { DocumentStateContext, DocumentPositionStateContext } from "../utils/documentUtil"; import { getClosingPosition, getNextCharacterPosition, isInRanges, getCfScriptRanges } from "../utils/contextUtil"; const scriptFunctionPattern: RegExp = /((\/\*\*((?:\*(?!\/)|[^*])*)\*\/\s+)?(?:\b(private|package|public|remote|static|final|abstract|default)\s+)?(?:\b(private|package|public|remote|static|final|abstract|default)\s+)?)(?:\b([A-Za-z0-9_\.$]+)\s+)?function\s+([_$a-zA-Z][$\w]*)\s*\(/gi; const scriptFunctionArgPattern: RegExp = /((?:(required)\s+)?(?:\b([\w.]+)\b\s+)?(\b[_$a-zA-Z][$\w]*\b)(?:\s*=\s*(\{[^\}]*\}|\[[^\]]*\]|\([^\)]*\)|(?:(?!\b\w+\s*=).)+))?)(.*)?/i; export const functionValuePattern: RegExp = /^function\s*\(/i; /* const userFunctionAttributeNames: MySet<string> = new MySet([ "name", "access", "description", "displayname", "hint", "output", "returnformat", "returntype", "roles", "securejson", "verifyclient", "restpath", "httpmethod", "produces", "consumes" ]); */ const userFunctionBooleanAttributes: MySet<string> = new MySet([ "static", "abstract", "final" ]); const accessArr: string[] = ["public", "private", "package", "remote"]; // TODO: Add pattern for arrow function export enum Access { Public = "public", Private = "private", Package = "package", Remote = "remote" } export namespace Access { /** * Resolves a string value of access type to an enumeration member * @param access The access type string to resolve */ export function valueOf(access: string): Access { switch (access.toLowerCase()) { case "public": return Access.Public; case "private": return Access.Private; case "package": return Access.Package; case "remote": return Access.Remote; default: return Access.Public; } } } export interface Argument extends Parameter { // description is hint nameRange: Range; dataTypeRange?: Range; dataTypeComponentUri?: Uri; // Only when dataType is Component } interface ArgumentAttributes { name: string; type?: string; default?: string; displayname?: string; hint?: string; required?: string; restargsource?: string; restargname?: string; } /* const argumentAttributesToInterfaceMapping = { type: "dataType", default: "default", hint: "description", required: "required" }; */ const argumentAttributeNames: MySet<string> = new MySet([ "name", "type", "default", "displayname", "hint", "required", "restargsource", "restargname" ]); /* const argumentBooleanAttributes: MySet<string> = new MySet([ "required" ]); */ export interface UserFunctionSignature extends Signature { parameters: Argument[]; } export interface UserFunction extends Function { access: Access; static: boolean; abstract: boolean; final: boolean; returnTypeUri?: Uri; // Only when returntype is Component returnTypeRange?: Range; nameRange: Range; bodyRange?: Range; signatures: UserFunctionSignature[]; location: Location; isImplicit: boolean; } export interface UserFunctionVariable extends Variable { signature: UserFunctionSignature; // returnType? } /** * Checks whether a Variable is a UserFunction * @param variable The variable object to check */ export function isUserFunctionVariable(variable: Variable): variable is UserFunctionVariable { return "signature" in variable; } // Collection of user functions for a particular component. Key is function name lowercased. export class ComponentFunctions extends MyMap<string, UserFunction> { } /* export interface UserFunctionsByUri { [uri: string]: ComponentFunctions; // key is Uri.toString() } */ export interface UserFunctionByUri { [uri: string]: UserFunction; // key is Uri.toString() } export interface UserFunctionsByName { [name: string]: UserFunctionByUri; // key is UserFunction.name lowercased } /** * Parses the CFScript function definitions and returns an array of UserFunction objects * @param documentStateContext The context information for a TextDocument in which to parse the CFScript functions */ export function parseScriptFunctions(documentStateContext: DocumentStateContext): UserFunction[] { const document: TextDocument = documentStateContext.document; let userFunctions: UserFunction[] = []; // sanitizedDocumentText removes doc blocks const componentBody: string = document.getText(); let scriptFunctionMatch: RegExpExecArray = null; while (scriptFunctionMatch = scriptFunctionPattern.exec(componentBody)) { const fullMatch: string = scriptFunctionMatch[0]; const returnTypePrefix: string = scriptFunctionMatch[1]; const fullDocBlock: string = scriptFunctionMatch[2]; const scriptDocBlockContent: string = scriptFunctionMatch[3]; const modifier1: string = scriptFunctionMatch[4]; const modifier2: string = scriptFunctionMatch[5]; const returnType: string = scriptFunctionMatch[6]; const functionName: string = scriptFunctionMatch[7]; const functionNameStartOffset: number = scriptFunctionMatch.index + fullMatch.lastIndexOf(functionName); const functionNameRange: Range = new Range( document.positionAt(functionNameStartOffset), document.positionAt(functionNameStartOffset + functionName.length) ); const argumentsStartOffset: number = scriptFunctionMatch.index + fullMatch.length; const argumentsEndPosition: Position = getClosingPosition(documentStateContext, argumentsStartOffset, ")"); const functionArgsRange: Range = new Range( document.positionAt(argumentsStartOffset), argumentsEndPosition.translate(0, -1) ); let functionBodyStartPos: Position; let functionEndPosition: Position; let functionAttributeRange: Range; let functionBodyRange: Range; if ((documentStateContext.component && documentStateContext.component.isInterface && !equalsIgnoreCase(modifier1, "default") && !equalsIgnoreCase(modifier2, "default")) || equalsIgnoreCase(modifier1, "abstract") || equalsIgnoreCase(modifier2, "abstract") ) { functionBodyStartPos = getNextCharacterPosition(documentStateContext, document.offsetAt(argumentsEndPosition), componentBody.length - 1, ";", false); functionEndPosition = functionBodyStartPos; functionAttributeRange = new Range( argumentsEndPosition, functionEndPosition ); } else { functionBodyStartPos = getNextCharacterPosition(documentStateContext, document.offsetAt(argumentsEndPosition), componentBody.length - 1, "{"); functionEndPosition = getClosingPosition(documentStateContext, document.offsetAt(functionBodyStartPos), "}"); try { functionAttributeRange = new Range( argumentsEndPosition, functionBodyStartPos.translate(0, -1) ); } catch (ex) { console.error(ex); console.error(`Error parsing ${document.uri.fsPath}:${functionName}`); functionAttributeRange = new Range( argumentsEndPosition, functionBodyStartPos ); } functionBodyRange = new Range( functionBodyStartPos, functionEndPosition.translate(0, -1) ); } const functionRange: Range = new Range( document.positionAt(scriptFunctionMatch.index), functionEndPosition ); let userFunction: UserFunction = { access: Access.Public, static: false, abstract: false, final: false, name: functionName, description: "", returntype: DataType.Any, signatures: [], nameRange: functionNameRange, bodyRange: functionBodyRange, location: new Location(document.uri, functionRange), isImplicit: false }; if (returnType) { const checkDataType = DataType.getDataTypeAndUri(returnType, document.uri); if (checkDataType) { userFunction.returntype = checkDataType[0]; if (checkDataType[1]) { userFunction.returnTypeUri = checkDataType[1]; } const returnTypeOffset: number = scriptFunctionMatch.index + returnTypePrefix.length; userFunction.returnTypeRange = new Range( document.positionAt(returnTypeOffset), document.positionAt(returnTypeOffset + returnType.length) ); } } if (modifier1) { const modifier1Type: string = parseModifier(modifier1); if (modifier1Type === "access") { userFunction.access = Access.valueOf(modifier1); } else { userFunction[modifier1Type] = true; } } if (modifier2) { const modifier2Type = parseModifier(modifier2); if (modifier2Type === "access") { userFunction.access = Access.valueOf(modifier2); } else { userFunction[modifier2Type] = true; } } const parsedAttributes: Attributes = parseAttributes(document, functionAttributeRange); userFunction = assignFunctionAttributes(userFunction, parsedAttributes); let scriptDocBlockParsed: DocBlockKeyValue[] = []; if (fullDocBlock) { scriptDocBlockParsed = parseDocBlock(document, new Range( document.positionAt(scriptFunctionMatch.index + 3), document.positionAt(scriptFunctionMatch.index + 3 + scriptDocBlockContent.length) ) ); scriptDocBlockParsed.forEach((docElem: DocBlockKeyValue) => { if (docElem.key === "access") { userFunction.access = Access.valueOf(docElem.value); } else if (docElem.key === "returntype") { const checkDataType = DataType.getDataTypeAndUri(docElem.value, document.uri); if (checkDataType) { userFunction.returntype = checkDataType[0]; const returnTypeKeyMatch: RegExpExecArray = getKeyPattern("returnType").exec(fullDocBlock); if (returnTypeKeyMatch) { const returnTypePath: string = returnTypeKeyMatch[1]; const returnTypeOffset: number = scriptFunctionMatch.index + returnTypeKeyMatch.index; userFunction.returnTypeRange = new Range( document.positionAt(returnTypeOffset), document.positionAt(returnTypeOffset + returnTypePath.length) ); } if (checkDataType[1]) { userFunction.returnTypeUri = checkDataType[1]; } } } else if (userFunctionBooleanAttributes.has(docElem.key)) { userFunction[docElem.key] = DataType.isTruthy(docElem.value); } else if (docElem.key === "hint") { userFunction.description = docElem.value; } else if (docElem.key === "description" && userFunction.description === "") { userFunction.description = docElem.value; } }); } const signature: UserFunctionSignature = { parameters: parseScriptFunctionArgs(documentStateContext, functionArgsRange, scriptDocBlockParsed) }; userFunction.signatures = [signature]; userFunctions.push(userFunction); } return userFunctions; } /** * Parses the given arguments into an array of Argument objects that is returned * @param documentStateContext The context information for a TextDocument possibly containing function arguments * @param argsRange A range within the given document that contains the CFScript arguments * @param docBlock The parsed documentation block for the function to which these arguments belong */ export function parseScriptFunctionArgs(documentStateContext: DocumentStateContext, argsRange: Range, docBlock: DocBlockKeyValue[]): Argument[] { let args: Argument[] = []; const document: TextDocument = documentStateContext.document; const documentUri: Uri = document.uri; const scriptArgRanges: Range[] = getScriptFunctionArgRanges(documentStateContext, argsRange); scriptArgRanges.forEach((argRange: Range) => { const argText: string = documentStateContext.sanitizedDocumentText.slice(document.offsetAt(argRange.start), document.offsetAt(argRange.end)); const argStartOffset = document.offsetAt(argRange.start); const scriptFunctionArgMatch: RegExpExecArray = scriptFunctionArgPattern.exec(argText); if (scriptFunctionArgMatch) { const fullArg = scriptFunctionArgMatch[0]; const attributePrefix = scriptFunctionArgMatch[1]; const argRequired = scriptFunctionArgMatch[2]; const argType = scriptFunctionArgMatch[3]; const argName = scriptFunctionArgMatch[4]; let argDefault = scriptFunctionArgMatch[5]; const argAttributes = scriptFunctionArgMatch[6]; const argOffset = argStartOffset + scriptFunctionArgMatch.index; if (!argName) { return; } let argDefaultAndAttributesLen = 0; if (argDefault) { argDefaultAndAttributesLen += argDefault.length; } let parsedArgAttributes: Attributes; if (argAttributes) { argDefaultAndAttributesLen += argAttributes.length; const functionArgPrefixOffset = argOffset + attributePrefix.length; // Account for trailing comma? const functionArgRange = new Range( document.positionAt(functionArgPrefixOffset), document.positionAt(functionArgPrefixOffset + argDefaultAndAttributesLen) ); parsedArgAttributes = parseAttributes(document, functionArgRange, argumentAttributeNames); } let removedDefaultAndAttributes = fullArg; if (argDefaultAndAttributesLen > 0) { removedDefaultAndAttributes = fullArg.slice(0, -argDefaultAndAttributesLen); } const argNameOffset = argOffset + removedDefaultAndAttributes.lastIndexOf(argName); let convertedArgType: DataType = DataType.Any; let typeUri: Uri; let argTypeRange: Range; if (argType) { const checkDataType = DataType.getDataTypeAndUri(argType, documentUri); if (checkDataType) { convertedArgType = checkDataType[0]; if (checkDataType[1]) { typeUri = checkDataType[1]; } const argTypeOffset: number = fullArg.indexOf(argType); argTypeRange = new Range( document.positionAt(argOffset + argTypeOffset), document.positionAt(argOffset + argTypeOffset + argType.length) ); } } let argument: Argument = { name: argName, required: argRequired ? true : false, dataType: convertedArgType, description: "", nameRange: new Range( document.positionAt(argNameOffset), document.positionAt(argNameOffset + argName.length) ) }; if (argDefault) { argDefault = argDefault.trim(); if (argDefault.length > 1 && /['"]/.test(argDefault.charAt(0)) && /['"]/.test(argDefault.charAt(argDefault.length - 1))) { argDefault = argDefault.slice(1, -1).trim(); } if (argDefault.length > 2 && argDefault.startsWith("#") && argDefault.endsWith("#") && !argDefault.slice(1, -1).includes("#")) { argDefault = argDefault.slice(1, -1).trim(); } argument.default = argDefault; } if (typeUri) { argument.dataTypeComponentUri = typeUri; } if (argTypeRange) { argument.dataTypeRange = argTypeRange; } if (parsedArgAttributes) { parsedArgAttributes.forEach((attr: Attribute) => { const argAttrName: string = attr.name; const argAttrVal: string = attr.value; if (argAttrName === "required") { argument.required = DataType.isTruthy(argAttrVal); } else if (argAttrName === "hint") { argument.description = argAttrVal; } else if (argAttrName === "default") { argument.default = argAttrVal; } else if (argAttrName === "type") { let checkDataType = DataType.getDataTypeAndUri(argAttrVal, documentUri); if (checkDataType) { argument.dataType = checkDataType[0]; if (checkDataType[1]) { argument.dataTypeComponentUri = checkDataType[1]; } argument.dataTypeRange = new Range( attr.valueRange.start, attr.valueRange.end ); } } }); } docBlock.filter((docElem: DocBlockKeyValue) => { return equalsIgnoreCase(docElem.key, argument.name); }).forEach((docElem: DocBlockKeyValue) => { if (docElem.subkey === "required") { argument.required = DataType.isTruthy(docElem.value); } else if (!docElem.subkey || docElem.subkey === "hint") { argument.description = docElem.value; } else if (docElem.subkey === "default") { argument.default = docElem.value; } else if (docElem.subkey === "type") { let checkDataType = DataType.getDataTypeAndUri(docElem.value, documentUri); if (checkDataType) { argument.dataType = checkDataType[0]; if (checkDataType[1]) { argument.dataTypeComponentUri = checkDataType[1]; } argument.dataTypeRange = new Range( docElem.valueRange.start, docElem.valueRange.end ); } } }); args.push(argument); } }); return args; } /** * Parses the tag function definitions and returns an array of UserFunction objects * @param documentStateContext The context information for a TextDocument in which to parse the tag functions */ export function parseTagFunctions(documentStateContext: DocumentStateContext): UserFunction[] { let userFunctions: UserFunction[] = []; const documentUri: Uri = documentStateContext.document.uri; const parsedFunctionTags: Tag[] = parseTags(documentStateContext, "cffunction"); parsedFunctionTags.forEach((tag: Tag) => { const functionRange: Range = tag.tagRange; const functionBodyRange: Range = tag.bodyRange; const parsedAttributes: Attributes = tag.attributes; if (!parsedAttributes.has("name") || !parsedAttributes.get("name").value) { return; } let userFunction: UserFunction = { access: Access.Public, static: false, abstract: false, final: false, name: parsedAttributes.get("name").value, description: "", returntype: DataType.Any, signatures: [], nameRange: parsedAttributes.get("name").valueRange, bodyRange: functionBodyRange, location: new Location(documentUri, functionRange), isImplicit: false }; assignFunctionAttributes(userFunction, parsedAttributes); const signature: UserFunctionSignature = { parameters: parseTagFunctionArguments(documentStateContext, functionBodyRange) }; userFunction.signatures = [signature]; userFunctions.push(userFunction); }); return userFunctions; } /** * Parses the given function body to extract the arguments into an array of Argument objects that is returned * @param documentStateContext The context information for a TextDocument containing these function arguments * @param functionBodyRange A range in the given document for the function body */ function parseTagFunctionArguments(documentStateContext: DocumentStateContext, functionBodyRange: Range | undefined): Argument[] { let args: Argument[] = []; const documentUri: Uri = documentStateContext.document.uri; if (functionBodyRange === undefined) { return args; } const parsedArgumentTags: Tag[] = parseTags(documentStateContext, "cfargument", functionBodyRange); parsedArgumentTags.forEach((tag: Tag) => { const parsedAttributes: Attributes = tag.attributes; const argumentAttributes: ArgumentAttributes = processArgumentAttributes(parsedAttributes); if (!argumentAttributes) { return; } const argNameRange: Range = parsedAttributes.get("name").valueRange; let argRequired: boolean; if (argumentAttributes.required) { argRequired = DataType.isTruthy(argumentAttributes.required); } else { argRequired = false; } const argType = argumentAttributes.type; let convertedArgType: DataType = DataType.Any; let typeUri: Uri; let argTypeRange: Range; if (argType) { const checkDataType = DataType.getDataTypeAndUri(argType, documentUri); if (checkDataType) { convertedArgType = checkDataType[0]; if (checkDataType[1]) { typeUri = checkDataType[1]; } argTypeRange = parsedAttributes.get("type").valueRange; argTypeRange = new Range( argTypeRange.start, argTypeRange.end ); } } let argument: Argument = { name: argumentAttributes.name, required: argRequired, dataType: convertedArgType, description: argumentAttributes.hint ? argumentAttributes.hint : "", nameRange: argNameRange }; let argDefault: string = argumentAttributes.default; if (argDefault) { argDefault = argDefault.trim(); if (argDefault.length > 1 && /['"]/.test(argDefault.charAt(0)) && /['"]/.test(argDefault.charAt(argDefault.length - 1))) { argDefault = argDefault.slice(1, -1).trim(); } if (argDefault.length > 2 && argDefault.startsWith("#") && argDefault.endsWith("#") && !argDefault.slice(1, -1).includes("#")) { argDefault = argDefault.slice(1, -1).trim(); } argument.default = argDefault; } if (typeUri) { argument.dataTypeComponentUri = typeUri; } if (argTypeRange) { argument.dataTypeRange = argTypeRange; } args.push(argument); }); return args; } /** * Assigns the given function attributes to the given user function * @param userFunction The user function to which the attributes will be assigned * @param functionAttributes The attributes that will be assigned to the user function */ function assignFunctionAttributes(userFunction: UserFunction, functionAttributes: Attributes): UserFunction { functionAttributes.forEach((attribute: Attribute) => { const attrName: string = attribute.name; if (attribute.value) { const attrVal: string = attribute.value; if (attrName === "access") { userFunction.access = Access.valueOf(attrVal); } else if (attrName === "returntype") { const checkDataType = DataType.getDataTypeAndUri(attrVal, userFunction.location.uri); if (checkDataType) { userFunction.returntype = checkDataType[0]; if (checkDataType[1]) { userFunction.returnTypeUri = checkDataType[1]; } const returnTypeRange: Range = functionAttributes.get("returntype").valueRange; userFunction.returnTypeRange = new Range( returnTypeRange.start, returnTypeRange.end ); } } else if (userFunctionBooleanAttributes.has(attrName)) { userFunction[attrVal] = DataType.isTruthy(attrVal); } else if (attrName === "hint") { userFunction.description = attrVal; } else if (attrName === "description" && userFunction.description === "") { userFunction.description = attrVal; } } }); return userFunction; } /** * Parses a set of attribute/value pairs for a function argument and returns an object conforming to the ArgumentAttributes interface * @param attributes A set of attribute/value pairs for a function argument */ function processArgumentAttributes(attributes: Attributes): ArgumentAttributes { let attributeObj = {}; attributes.forEach((attr: Attribute, attrKey: string) => { attributeObj[attrKey] = attr.value; }); if (!attributeObj["name"]) { return null; } return attributeObj as ArgumentAttributes; } /** * Parses the given user function to extract the local variables into an array of Variable objects that is returned * @param func The UserFunction within which to parse local variables * @param documentStateContext The contextual information of the state of a document containing the given function * @param isScript Whether this function is defined entirely in CFScript */ export function getLocalVariables(func: UserFunction, documentStateContext: DocumentStateContext, isScript: boolean): Variable[] { if (!func || !func.bodyRange) { return []; } const allVariables: Variable[] = parseVariableAssignments(documentStateContext, isScript, func.bodyRange); return allVariables.filter((variable: Variable) => { return (variable.scope === Scope.Local); }); } /** * Identifies if the modifier is of an Access type or other * @param modifier A string representing the function modifier */ function parseModifier(modifier: string): string { if (accessArr.includes(modifier.toLowerCase())) { return "access"; } return modifier; } /** * Gets the function based on its key and position in the document * @param documentPositionStateContext The contextual information of the state of a document and the cursor position * @param functionKey The function key for which to get * @param docPrefix The document prefix of the function if not the same as docPrefix within documentPositionStateContext */ export async function getFunctionFromPrefix(documentPositionStateContext: DocumentPositionStateContext, functionKey: string, docPrefix?: string): Promise<UserFunction | undefined> { let foundFunction: UserFunction; if (docPrefix === undefined) { docPrefix = documentPositionStateContext.docPrefix; } // TODO: Replace regex check with variable references range check // TODO: Check for function variables? const varPrefixMatch: RegExpExecArray = getVariableExpressionPrefixPattern().exec(docPrefix); if (varPrefixMatch) { const varMatchText: string = varPrefixMatch[0]; const varScope: string = varPrefixMatch[2]; const varQuote: string = varPrefixMatch[3]; const varName: string = varPrefixMatch[4]; let dotSeparatedCount = 2; if (varScope && !varQuote) { dotSeparatedCount++; } if (varMatchText.split(".").length === dotSeparatedCount) { if (documentPositionStateContext.isCfcFile && !varScope && equalsIgnoreCase(varName, "super")) { if (documentPositionStateContext.component && documentPositionStateContext.component.extends) { const baseComponent: Component = getComponent(documentPositionStateContext.component.extends); if (baseComponent) { foundFunction = getFunctionFromComponent(baseComponent, functionKey, documentPositionStateContext.document.uri); } } } else if (documentPositionStateContext.isCfcFile && !varScope && (equalsIgnoreCase(varName, Scope.Variables) || equalsIgnoreCase(varName, Scope.This))) { // TODO: Disallow implicit functions if using variables scope let disallowedAccess: Access; if (equalsIgnoreCase(varName, Scope.This)) { disallowedAccess = Access.Private; } const disallowImplicit: boolean = equalsIgnoreCase(varName, Scope.Variables); foundFunction = getFunctionFromComponent(documentPositionStateContext.component, functionKey, documentPositionStateContext.document.uri, disallowedAccess, disallowImplicit); } else if (documentPositionStateContext.isCfmFile && !varScope && equalsIgnoreCase(varName, Scope.Variables)) { foundFunction = getFunctionFromTemplate(documentPositionStateContext, functionKey); } else { // TODO: Allow passing variable assignments const allDocumentVariableAssignments: Variable[] = collectDocumentVariableAssignments(documentPositionStateContext); let variableAssignments: Variable[] = allDocumentVariableAssignments; const fileName: string = path.basename(documentPositionStateContext.document.uri.fsPath); if (varScope && fileName !== "Application.cfm") { const applicationDocVariables: Variable[] = await getApplicationVariables(documentPositionStateContext.document.uri); variableAssignments = variableAssignments.concat(applicationDocVariables); } const scopeVal: Scope = varScope ? Scope.valueOf(varScope) : undefined; const foundVar: Variable = getBestMatchingVariable(variableAssignments, varName, scopeVal); if (foundVar && foundVar.dataTypeComponentUri) { const foundVarComponent: Component = getComponent(foundVar.dataTypeComponentUri); if (foundVarComponent) { foundFunction = getFunctionFromComponent(foundVarComponent, functionKey, documentPositionStateContext.document.uri); } } } } } else if (documentPositionStateContext.isCfmFile) { foundFunction = getFunctionFromTemplate(documentPositionStateContext, functionKey); } else if (documentPositionStateContext.component) { foundFunction = getFunctionFromComponent(documentPositionStateContext.component, functionKey, documentPositionStateContext.document.uri); } return foundFunction; } /** * Gets the function based on the component to which it belongs, its name, and from where it is being called * @param component The component in which to begin looking * @param lowerFunctionName The function name all lowercased * @param callerUri The URI of the document from which the function is being called * @param disallowedAccess An access specifier to disallow * @param disallowImplicit Whether to disallow implicit functions from being checked */ export function getFunctionFromComponent(component: Component, lowerFunctionName: string, callerUri: Uri, disallowedAccess?: Access, disallowImplicit: boolean = false): UserFunction | undefined { let validFunctionAccess: MySet<Access> = new MySet([Access.Remote, Access.Public]); if (hasComponent(callerUri)) { let callerComponent: Component = getComponent(callerUri); if (isSubcomponentOrEqual(callerComponent, component)) { validFunctionAccess.add(Access.Private); validFunctionAccess.add(Access.Package); } } if (!validFunctionAccess.has(Access.Package) && path.dirname(callerUri.fsPath) === path.dirname(component.uri.fsPath)) { validFunctionAccess.add(Access.Package); } if (disallowedAccess && validFunctionAccess.has(disallowedAccess)) { validFunctionAccess.delete(disallowedAccess); } let currComponent: Component = component; while (currComponent) { if (currComponent.functions.has(lowerFunctionName)) { const foundFunc: UserFunction = currComponent.functions.get(lowerFunctionName); if (validFunctionAccess.has(foundFunc.access) && !(disallowImplicit && foundFunc.isImplicit)) { return foundFunc; } } if (currComponent.extends) { currComponent = getComponent(currComponent.extends); } else { currComponent = undefined; } } return undefined; } /** * Gets the function based on the document to which it belongs and its name * @param documentStateContext The contextual information of the state of a document * @param lowerFunctionName The function name all lowercased */ export function getFunctionFromTemplate(documentStateContext: DocumentStateContext, lowerFunctionName: string): UserFunction | undefined { const tagFunctions: UserFunction[] = parseTagFunctions(documentStateContext); const cfscriptRanges: Range[] = getCfScriptRanges(documentStateContext.document); const scriptFunctions: UserFunction[] = parseScriptFunctions(documentStateContext).filter((func: UserFunction) => { return isInRanges(cfscriptRanges, func.location.range.start); }); const allTemplateFunctions: UserFunction[] = tagFunctions.concat(scriptFunctions); return allTemplateFunctions.find((func: UserFunction) => { return equalsIgnoreCase(func.name, lowerFunctionName); }); } /** * Returns UserFunction array representation of function variables with some properties undefined * @param variables The variables to convert */ export function variablesToUserFunctions(variables: UserFunctionVariable[]): UserFunction[] { return variables.map((variable: UserFunctionVariable) => { const userFun: UserFunction = { name: variable.identifier, description: variable.description ? variable.description : "", returntype: DataType.Any, // Get this from variable access: undefined, // Define? static: false, abstract: false, final: variable.final, nameRange: variable.declarationLocation.range, bodyRange: undefined, // Define signatures: [variable.signature], location: variable.declarationLocation, // Range is only declaration isImplicit: false }; return userFun; }); }
the_stack
import { Readable as ReadableStream } from 'stream'; import nodeFetch from 'node-fetch'; import HttpsProxyAgent from 'https-proxy-agent'; import { Agent as NodeAgent, AgentOptions } from 'https'; import { hasProperties, retry, bold } from '../utils/common'; import { URL, parse as parseURL } from 'url'; import { globalConfig } from '../config'; import gitCredentialNode = require('git-credential-node'); import { Project } from '../project'; // TODO: add an "http2" option to fetchOptions for http/2 support interface Agent extends NodeAgent { options: AgentOptions }; export type HttpsProxyAgentOptions = string | ProxyAgentOptions; export interface ProxyAgentOptions extends AgentOptions { host: string; port: number; secureProxy?: boolean; headers?: { [name: string]: string }; }; const emptyCredentials = Object.freeze(Object.create(null)); export interface FetchOptions { // These properties are part of the Fetch Standard method?: string, headers?: { [name: string]: string }, body?: void | ReadableStream, redirect?: 'manual' | 'error' | 'follow', // The following properties are node-fetch extensions follow?: number, // when timeout is set, retries applies 3 times automatically timeout?: number, compress?: true, size?: 0, // jspm-only extensions credentials?: Credentials | false, // whether to get credentials again on failure reauthorize?: boolean, // whether to retry on network failure retries?: number }; export interface Credentials { basicAuth?: { username: string, password: string } ca?: string | string[], cert?: string, proxy?: string | HttpsProxyAgentOptions, strictSSL?: boolean, headers?: Record<string, string> }; const agents: Agent[] = []; const proxyAgents = new Map<HttpsProxyAgentOptions,Agent[]>(); const strictSSL = globalConfig.get('strictSSL') === false ? false : null; const httpProxy = process.env.HTTP_PROXY ? process.env.HTTP_PROXY : null; const httpsProxy = process.env.HTTPS_PROXY ? process.env.HTTPS_PROXY : null; export type Fetch = typeof FetchClass.prototype.fetch; export type GetCredentials = typeof FetchClass.prototype.getCredentials; export default class FetchClass { project: Project; cachedCredentials: { [urlBase: string]: Promise<Credentials> }; netrc: any; debugLog: (msg: string) => void; constructor (project: Project) { this.project = project; this.cachedCredentials = {}; this.netrc = undefined; this.debugLog = project.log.debug.bind(project.log); } getCredentials (url: string, method?: string, unauthorizedHeaders?: Record<string, string>): Promise<Credentials> { this.debugLog(`Getting credentials for ${url}`); if (!unauthorizedHeaders) for (const urlBase in this.cachedCredentials) { if (url.startsWith(urlBase)) return this.cachedCredentials[urlBase]; } const urlObj = new URL(url); let urlBase = urlObj.origin; if (urlBase === 'null') urlBase = `${urlObj.protocol}//${urlObj.host}`; return this.cachedCredentials[urlBase] = (async () => { const credentials = { basicAuth: undefined, authorization: undefined, ca: undefined, cert: undefined, proxy: undefined, strictSSL: true }; // support proxy environment variables and global strictSSL false configuration if (httpProxy !== null && urlObj.protocol === 'http:') credentials.proxy = httpProxy; else if (httpsProxy !== null && urlObj.protocol === 'https:') credentials.proxy = httpsProxy; if (strictSSL === false) credentials.strictSSL = false; // source with inline credentials takes priority if (urlObj.username || urlObj.password) return credentials; // run auth hook for jspm registries, returning if matched // ...for some reason TypeScript needs double brackets here... let credentialsRegistry; if (credentialsRegistry = await this.project.registryManager.auth(urlObj, method, credentials, unauthorizedHeaders)) { this.project.log.debug(`Credentials for ${urlBase} provided by ${bold(credentialsRegistry)} registry.`); return credentials; } // fallback to reading netrc if (this.netrc === undefined) { try { this.netrc = require('netrc')(); } catch (e) { this.netrc = {}; } } const hostname = urlObj.hostname; let creds = this.netrc[hostname]; // support reading subdomain auth from top level domain let upperHostnameIndex = hostname.indexOf('.'); while (!creds) { let nextHostnameIndex = hostname.indexOf('.', upperHostnameIndex + 1); if (nextHostnameIndex === -1) break; creds = this.netrc[hostname.substr(upperHostnameIndex + 1)]; upperHostnameIndex = nextHostnameIndex; } if (creds) { this.project.log.debug(`Credentials for ${urlBase} provided by local .netrc file.`); credentials.basicAuth = { username: creds.password ? creds.login : 'Token', password: creds.password ? creds.password : creds.login }; return credentials; } // and then finally using auth directly from git try { const data = await gitCredentialNode.fill(urlObj.origin); if (data) { this.project.log.debug(`Credentials for ${urlBase} provided by git credential manager.`); // for some reason, on TravisCI we get "Username: " as username and "Password: " as password if (data.username !== 'Username: ') { credentials.basicAuth = data; return credentials; } } } catch (e) { this.project.log.debug('Git credentials error: ' + e.toString()); } this.project.log.debug(`No credentials details found for ${urlBase}.`); return emptyCredentials; })(); } fetch (url: string, options?: FetchOptions) { return retry(async (retryNum) => { if (retryNum > 1) this.debugLog(`Fetch of ${url} failed, retrying (attempt ${retryNum})`); return this.doFetch(url, options); }, options && options.retries); } async doFetch (url: string, options?: FetchOptions) { let requestUrl = url; const method = options.method && options.method.toUpperCase() || 'GET'; let credentials: Credentials; if (options && options.credentials) credentials = options.credentials; // we support credentials: false if (credentials == undefined) credentials = await this.getCredentials(url, method); let agent; // TODO: support keepalive let agentOptions: AgentOptions | HttpsProxyAgentOptions = { keepAlive: false }; if (credentials.ca) agentOptions.ca = credentials.ca; if (credentials.cert) agentOptions.cert = credentials.cert; if (credentials.strictSSL === false) agentOptions.rejectUnauthorized = false; // TODO: properly support http proxy agent if (credentials.proxy && url.startsWith('http:')) this.debugLog(`Http proxy not supported for ${url}. Please post an issue.`); if (credentials.proxy && url.startsWith('https:')) { if (typeof credentials.proxy === 'string') { const proxyURL = parseURL(credentials.proxy); (<ProxyAgentOptions>agentOptions).host = proxyURL.host; (<ProxyAgentOptions>agentOptions).port = parseInt(proxyURL.port); } else { Object.assign(agentOptions, credentials.proxy); } } if (credentials.headers) { if (!options) { options = { headers: credentials.headers }; } else { if (options.headers) options.headers = Object.assign({}, credentials.headers, options.headers); else options.headers = credentials.headers; } } if (hasProperties(agentOptions) && url.startsWith('https:')) { let existingAgents; if (credentials.proxy) existingAgents = proxyAgents.get(credentials.proxy); else existingAgents = agents; if (existingAgents) agent = agents.find(agent => { return !Object.keys(agentOptions).some(opt => agent.options[opt] !== agentOptions[opt]); }); if (!agent) { if (credentials.proxy) { if (!existingAgents) proxyAgents.set(credentials.proxy, existingAgents = []); existingAgents.push(agent = new HttpsProxyAgent(Object.assign({}, credentials.proxy))); } else { agents.push(agent = <Agent>(new NodeAgent(agentOptions))); } } } this.debugLog(`${method} ${url}${writeCredentialLog(credentials)}`); if (credentials.basicAuth) { const urlObj = new URL(url); if (!urlObj.username && !urlObj.password) { ({ username: urlObj.username, password: urlObj.password } = credentials.basicAuth); requestUrl = urlObj.href; } } if (agent) options = Object.assign({ agent }, options); if (!options || !options.headers || !options.headers['user-agent']) { const headers = Object.assign({ 'user-agent': `jspm/2.0` }, options && options.headers); options = Object.assign({ headers }, options); } try { var res = await nodeFetch(requestUrl, options); } catch (err) { if (err.type === 'request-timeout') { err.retriable = true; err.hideStack = true; } else if (err.code) { switch (err.code) { case 'ENOTFOUND': if (err.toString().indexOf('getaddrinfo') === -1) break; case 'EINVAL': case 'ECONNRESET': case 'ETIMEDOUT': case 'ESOCKETTIMEDOUT': err.retriable = true; err.hideStack = true; } } throw err; } // re-authorize once if reauthorizable authorization failure if ((res.status === 401 || res.status === 403) && options.reauthorize !== false) { this.project.log.warn(`Invalid authorization for ${method} ${url}.`); options.reauthorize = false; options.credentials = await this.getCredentials(url, method, res.headers.raw()); return this.fetch(url, options); } return res; } } function writeCredentialLog (credentials: Credentials): string { let outStr = ''; if (typeof credentials.proxy === 'string') outStr += ` over proxy ${credentials.proxy}`; else if (credentials.proxy) outStr += ` over proxy ${credentials.proxy.host}`; if (credentials.basicAuth) outStr += ` with basic auth for "${credentials.basicAuth.username}", "${credentials.basicAuth.password}"`; else if (credentials.headers) outStr += ` with ${Object.keys(credentials.headers).join(', ')} header${Object.keys(credentials.headers).length > 1 ? 's' : ''}`; else outStr += ` without auth`; if (credentials.cert || credentials.ca || credentials.strictSSL === false) { if (credentials.strictSSL === false) outStr += ` (Strict SSL Disabled)`; else if (credentials.cert && credentials.ca) outStr += ` (custom ca enabled, custom cert enabled)`; else if (credentials.ca) outStr += ` (custom ca enabled)`; else if (credentials.cert) outStr += ` (custom cert enabled)`; } return outStr; }
the_stack
import HierarchicalLayoutStage from './HierarchicalLayoutStage'; import { DIRECTION } from '../../../util/Constants'; import MaxLog from '../../../gui/MaxLog'; import WeightedCellSorter from '../util/WeightedCellSorter'; import Dictionary from '../../../util/Dictionary'; import Point from '../../geometry/Point'; import HierarchicalEdgeStyle from '../datatypes/HierarchicalEdgeStyle'; import HierarchicalLayout from '../HierarchicalLayout'; import GraphHierarchyModel from './GraphHierarchyModel'; import Cell from '../../../view/cell/Cell'; import GraphHierarchyNode from '../datatypes/GraphHierarchyNode'; import GraphAbstractHierarchyCell from '../datatypes/GraphAbstractHierarchyCell'; import { _mxCompactTreeLayoutNode } from '../CompactTreeLayout'; import { Graph } from '../../../view/Graph'; import Geometry from '../../../view/geometry/Geometry'; import GraphHierarchyEdge from '../datatypes/GraphHierarchyEdge'; import SwimlaneLayout from '../SwimlaneLayout'; /** * Sets the horizontal locations of node and edge dummy nodes on each layer. * Uses median down and up weighings as well as heuristics to straighten edges as * far as possible. * * Constructor: mxCoordinateAssignment * * Creates a coordinate assignment. * * Arguments: * * intraCellSpacing - the minimum buffer between cells on the same rank * interRankCellSpacing - the minimum distance between cells on adjacent ranks * orientation - the position of the root node(s) relative to the graph * initialX - the leftmost coordinate node placement starts at */ class CoordinateAssignment extends HierarchicalLayoutStage { constructor( layout: HierarchicalLayout | SwimlaneLayout, intraCellSpacing: number=30, interRankCellSpacing: number=100, orientation: DIRECTION, initialX: number, parallelEdgeSpacing: number=10 ) { super(); this.layout = layout; this.intraCellSpacing = intraCellSpacing; this.interRankCellSpacing = interRankCellSpacing; this.orientation = orientation; this.initialX = initialX; this.parallelEdgeSpacing = parallelEdgeSpacing; } /** * Reference to the enclosing <HierarchicalLayout>. */ layout: HierarchicalLayout | SwimlaneLayout; /** * The minimum buffer between cells on the same rank. Default is 30. */ intraCellSpacing = 30; /** * The minimum distance between cells on adjacent ranks. Default is 100. */ interRankCellSpacing = 100; /** * The distance between each parallel edge on each ranks for long edges. * Default is 10. */ parallelEdgeSpacing = 10; /** * The number of heuristic iterations to run. Default is 8. */ maxIterations = 8; /** * The preferred horizontal distance between edges exiting a vertex Default is 5. */ prefHozEdgeSep = 5; /** * The preferred vertical offset between edges exiting a vertex Default is 2. */ prefVertEdgeOff = 2; /** * The minimum distance for an edge jetty from a vertex Default is 12. */ minEdgeJetty = 12; /** * The size of the vertical buffer in the center of inter-rank channels * where edge control points should not be placed Default is 4. */ channelBuffer = 4; /** * Map of internal edges and (x,y) pair of positions of the start and end jetty * for that edge where it connects to the source and target vertices. * Note this should technically be a WeakHashMap, but since JS does not * have an equivalent, housekeeping must be performed before using. * i.e. check all edges are still in the model and clear the values. * Note that the y co-ord is the offset of the jetty, not the * absolute point */ jettyPositions: { [key: string]: number[] } | null = null; /** * The position of the root ( start ) node(s) relative to the rest of the * laid out graph. Default is <mxConstants.DIRECTION.NORTH>. */ orientation: DIRECTION = DIRECTION.NORTH; /** * The minimum x position node placement starts at */ initialX: number; /** * The maximum x value this positioning lays up to */ limitX: number | null = null; /** * The sum of x-displacements for the current iteration */ currentXDelta: number | null = null; /** * The rank that has the widest x position */ widestRank: number | null = null; /** * Internal cache of top-most values of Y for each rank */ rankTopY: number[] | null = null; /** * Internal cache of bottom-most value of Y for each rank */ rankBottomY: number[] | null = null; /** * The X-coordinate of the edge of the widest rank */ widestRankValue: number | null = null; /** * The width of all the ranks */ rankWidths: number[] | null = null; /** * The Y-coordinate of all the ranks */ rankY: number[] | null = null; /** * Whether or not to perform local optimisations and iterate multiple times * through the algorithm. Default is true. */ fineTuning = true; /** * A store of connections to the layer above for speed */ nextLayerConnectedCache = null; /** * A store of connections to the layer below for speed */ previousLayerConnectedCache = null; /** * Padding added to resized parents Default is 10. */ groupPadding = 10; /** * Utility method to display current positions */ printStatus() { const model = <GraphHierarchyModel>this.layout.getDataModel(); const ranks = <GraphAbstractHierarchyCell[][]>model.ranks; MaxLog.show(); MaxLog.writeln('======Coord assignment debug======='); for (let j = 0; j < ranks.length; j++) { MaxLog.write('Rank ', String(j), ' : '); const rank = ranks[j]; for (let k = 0; k < rank.length; k++) { const cell = rank[k]; MaxLog.write(String(cell.getGeneralPurposeVariable(j)), ' '); } MaxLog.writeln(); } MaxLog.writeln('===================================='); } /** * A basic horizontal coordinate assignment algorithm */ execute(parent: any) { this.jettyPositions = Object(); const model = <GraphHierarchyModel>this.layout.getDataModel(); this.currentXDelta = 0.0; this.initialCoords(this.layout.getGraph(), model); // this.printStatus(); if (this.fineTuning) { this.minNode(model); } let bestXDelta = 100000000.0; if (this.fineTuning) { for (let i = 0; i < this.maxIterations; i += 1) { // this.printStatus(); // Median Heuristic if (i !== 0) { this.medianPos(i, model); this.minNode(model); } // if the total offset is less for the current positioning, // there are less heavily angled edges and so the current // positioning is used const ranks = <GraphAbstractHierarchyCell[][]>model.ranks; if (this.currentXDelta < bestXDelta) { for (let j = 0; j < ranks.length; j++) { const rank = ranks[j]; for (let k = 0; k < rank.length; k++) { const cell = rank[k]; cell.setX(j, <number>cell.getGeneralPurposeVariable(j)); } } bestXDelta = this.currentXDelta; } else { // Restore the best positions for (let j = 0; j < ranks.length; j++) { const rank = ranks[j]; for (let k = 0; k < rank.length; k++) { const cell = rank[k]; cell.setGeneralPurposeVariable(j, cell.getX(j)); } } } this.minPath(this.layout.getGraph(), model); this.currentXDelta = 0; } } this.setCellLocations(this.layout.getGraph(), model); } /** * Performs one median positioning sweep in both directions */ minNode(model: GraphHierarchyModel) { // Queue all nodes const nodeList: WeightedCellSorter[] = []; // Need to be able to map from cell to cellWrapper const map: Dictionary<GraphAbstractHierarchyCell, WeightedCellSorter> = new Dictionary(); const rank = []; for (let i = 0; i <= model.maxRank; i += 1) { rank[i] = (<GraphAbstractHierarchyCell[][]>model.ranks)[i]; for (let j = 0; j < rank[i].length; j += 1) { // Use the weight to store the rank and visited to store whether // or not the cell is in the list const node = rank[i][j]; const nodeWrapper = new WeightedCellSorter(node, i); nodeWrapper.rankIndex = j; nodeWrapper.visited = true; nodeList.push(nodeWrapper); map.put(node, nodeWrapper); } } // Set a limit of the maximum number of times we will access the queue // in case a loop appears const maxTries = nodeList.length * 10; let count = 0; // Don't move cell within this value of their median const tolerance = 1; while (nodeList.length > 0 && count <= maxTries) { const cellWrapper = <WeightedCellSorter>nodeList.shift(); const cell: GraphAbstractHierarchyCell = <GraphAbstractHierarchyCell>cellWrapper.cell; const rankValue = cellWrapper.weightedValue; const rankIndex = parseInt(String(cellWrapper.rankIndex)); const nextLayerConnectedCells = <GraphAbstractHierarchyCell[]>cell.getNextLayerConnectedCells(rankValue); const previousLayerConnectedCells = <GraphAbstractHierarchyCell[]>cell.getPreviousLayerConnectedCells(rankValue); const numNextLayerConnected = nextLayerConnectedCells.length; const numPreviousLayerConnected = previousLayerConnectedCells.length; const medianNextLevel = this.medianXValue(nextLayerConnectedCells, rankValue + 1); const medianPreviousLevel = this.medianXValue(previousLayerConnectedCells, rankValue - 1); const numConnectedNeighbours = numNextLayerConnected + numPreviousLayerConnected; const currentPosition = <number>cell.getGeneralPurposeVariable(rankValue); let cellMedian = <number>currentPosition; if (numConnectedNeighbours > 0) { cellMedian = (medianNextLevel * numNextLayerConnected + medianPreviousLevel * numPreviousLayerConnected) / numConnectedNeighbours; } // Flag storing whether or not position has changed let positionChanged = false; if (cellMedian < currentPosition - tolerance) { if (rankIndex === 0) { cell.setGeneralPurposeVariable(rankValue, cellMedian); positionChanged = true; } else { const leftCell = rank[rankValue][rankIndex - 1]; let leftLimit = <number>leftCell.getGeneralPurposeVariable(rankValue); leftLimit = leftLimit + leftCell.width / 2 + this.intraCellSpacing + cell.width / 2; if (leftLimit < cellMedian) { cell.setGeneralPurposeVariable(rankValue, cellMedian); positionChanged = true; } else if (leftLimit < <number>cell.getGeneralPurposeVariable(rankValue) - tolerance) { cell.setGeneralPurposeVariable(rankValue, leftLimit); positionChanged = true; } } } else if (cellMedian > currentPosition + tolerance) { const rankSize = rank[rankValue].length; if (rankIndex === rankSize - 1) { cell.setGeneralPurposeVariable(rankValue, cellMedian); positionChanged = true; } else { const rightCell = rank[rankValue][rankIndex + 1]; let rightLimit = <number>rightCell.getGeneralPurposeVariable(rankValue); rightLimit = rightLimit - rightCell.width / 2 - this.intraCellSpacing - cell.width / 2; if (rightLimit > cellMedian) { cell.setGeneralPurposeVariable(rankValue, cellMedian); positionChanged = true; } else if (rightLimit > <number>cell.getGeneralPurposeVariable(rankValue) + tolerance) { cell.setGeneralPurposeVariable(rankValue, rightLimit); positionChanged = true; } } } if (positionChanged) { // Add connected nodes to map and list for (let i = 0; i < nextLayerConnectedCells.length; i += 1) { const connectedCell: GraphAbstractHierarchyCell = nextLayerConnectedCells[i]; const connectedCellWrapper = map.get(connectedCell); if (connectedCellWrapper != null) { if (connectedCellWrapper.visited == false) { connectedCellWrapper.visited = true; nodeList.push(connectedCellWrapper); } } } // Add connected nodes to map and list for (let i = 0; i < previousLayerConnectedCells.length; i += 1) { const connectedCell = previousLayerConnectedCells[i]; const connectedCellWrapper = map.get(connectedCell); if (connectedCellWrapper != null) { if (connectedCellWrapper.visited == false) { connectedCellWrapper.visited = true; nodeList.push(connectedCellWrapper); } } } } cellWrapper.visited = false; count += 1; } } /** * Performs one median positioning sweep in one direction * * @param i the iteration of the whole process * @param model an internal model of the hierarchical layout */ medianPos(i: number, model: GraphHierarchyModel) { // Reverse sweep direction each time through this method const downwardSweep = i % 2 === 0; if (downwardSweep) { for (let j = model.maxRank; j > 0; j--) { this.rankMedianPosition(j - 1, model, j); } } else { for (let j = 0; j < model.maxRank - 1; j++) { this.rankMedianPosition(j + 1, model, j); } } } /** * Performs median minimisation over one rank. * * @param rankValue the layer number of this rank * @param model an internal model of the hierarchical layout * @param nextRankValue the layer number whose connected cels are to be laid out * relative to */ rankMedianPosition( rankValue: number, model: GraphHierarchyModel, nextRankValue: number ) { const ranks = <GraphAbstractHierarchyCell[][]>model.ranks; const rank = ranks[rankValue]; // Form an array of the order in which the cell are to be processed // , the order is given by the weighted sum of the in or out edges, // depending on whether we're traveling up or down the hierarchy. const weightedValues = []; const cellMap: { [key: string]: WeightedCellSorter } = {}; for (let i = 0; i < rank.length; i += 1) { const currentCell = rank[i]; weightedValues[i] = new WeightedCellSorter(currentCell); weightedValues[i].rankIndex = i; cellMap[<string>currentCell.id] = weightedValues[i]; let nextLayerConnectedCells = null; if (nextRankValue < rankValue) { nextLayerConnectedCells = currentCell.getPreviousLayerConnectedCells(rankValue); } else { nextLayerConnectedCells = currentCell.getNextLayerConnectedCells(rankValue); } // Calculate the weighing based on this node type and those this // node is connected to on the next layer weightedValues[i].weightedValue = this.calculatedWeightedValue( currentCell, <GraphAbstractHierarchyCell[]>nextLayerConnectedCells ); } weightedValues.sort(WeightedCellSorter.compare); // Set the new position of each node within the rank using // its temp variable for (let i = 0; i < weightedValues.length; i += 1) { let numConnectionsNextLevel = 0; const cell = <GraphHierarchyNode><unknown>weightedValues[i].cell; let nextLayerConnectedCells = null; let medianNextLevel = 0; if (nextRankValue < rankValue) { nextLayerConnectedCells = cell .getPreviousLayerConnectedCells(rankValue) .slice(); } else { nextLayerConnectedCells = cell .getNextLayerConnectedCells(rankValue) .slice(); } if (nextLayerConnectedCells != null) { numConnectionsNextLevel = nextLayerConnectedCells.length; if (numConnectionsNextLevel > 0) { medianNextLevel = this.medianXValue( nextLayerConnectedCells, nextRankValue ); } else { // For case of no connections on the next level set the // median to be the current position and try to be // positioned there medianNextLevel = cell.getGeneralPurposeVariable(rankValue); } } let leftBuffer = 0.0; let leftLimit = -100000000.0; for (let j = <number>weightedValues[i].rankIndex - 1; j >= 0; ) { const weightedValue = cellMap[<string>rank[j].id]; if (weightedValue != null) { const leftCell = <GraphHierarchyNode><unknown>weightedValue.cell; if (weightedValue.visited) { // The left limit is the right hand limit of that // cell plus any allowance for unallocated cells // in-between leftLimit = leftCell.getGeneralPurposeVariable(rankValue) + leftCell.width / 2.0 + this.intraCellSpacing + leftBuffer + cell.width / 2.0; j = -1; } else { leftBuffer += leftCell.width + this.intraCellSpacing; j--; } } } let rightBuffer = 0.0; let rightLimit = 100000000.0; for ( let j = <number>weightedValues[i].rankIndex + 1; j < weightedValues.length; ) { const weightedValue = cellMap[<string>rank[j].id]; if (weightedValue != null) { const rightCell = <GraphHierarchyNode><unknown>weightedValue.cell; if (weightedValue.visited) { // The left limit is the right hand limit of that // cell plus any allowance for unallocated cells // in-between rightLimit = rightCell.getGeneralPurposeVariable(rankValue) - rightCell.width / 2.0 - this.intraCellSpacing - rightBuffer - cell.width / 2.0; j = weightedValues.length; } else { rightBuffer += rightCell.width + this.intraCellSpacing; j++; } } } if (medianNextLevel >= leftLimit && medianNextLevel <= rightLimit) { cell.setGeneralPurposeVariable(rankValue, medianNextLevel); } else if (medianNextLevel < leftLimit) { // Couldn't place at median value, place as close to that // value as possible cell.setGeneralPurposeVariable(rankValue, leftLimit); this.currentXDelta = <number>this.currentXDelta + leftLimit - medianNextLevel; } else if (medianNextLevel > rightLimit) { // Couldn't place at median value, place as close to that // value as possible cell.setGeneralPurposeVariable(rankValue, rightLimit); this.currentXDelta = <number>this.currentXDelta + medianNextLevel - rightLimit; } weightedValues[i].visited = true; } } /** * Calculates the priority the specified cell has based on the type of its * cell and the cells it is connected to on the next layer * * @param currentCell the cell whose weight is to be calculated * @param collection the cells the specified cell is connected to */ calculatedWeightedValue(currentCell: Cell, collection: GraphAbstractHierarchyCell[]) { let totalWeight = 0; for (let i = 0; i < collection.length; i += 1) { const cell = collection[i]; if (currentCell.isVertex() && cell.isVertex()) { totalWeight += 1; } else if (currentCell.isEdge() && cell.isEdge()) { totalWeight += 8; } else { totalWeight += 2; } } return totalWeight; } /** * Calculates the median position of the connected cell on the specified * rank * * @param connectedCells the cells the candidate connects to on this level * @param rankValue the layer number of this rank */ medianXValue(connectedCells: GraphAbstractHierarchyCell[], rankValue: number) { if (connectedCells.length === 0) { return 0; } const medianValues = []; for (let i = 0; i < connectedCells.length; i += 1) { medianValues[i] = <number>connectedCells[i].getGeneralPurposeVariable(rankValue); } medianValues.sort((a: number, b: number) => a - b); if (connectedCells.length % 2 === 1) { // For odd numbers of adjacent vertices return the median return medianValues[Math.floor(connectedCells.length / 2)]; } const medianPoint = connectedCells.length / 2; const leftMedian = medianValues[medianPoint - 1]; const rightMedian = medianValues[medianPoint]; return (leftMedian + rightMedian) / 2; } /** * Sets up the layout in an initial positioning. The ranks are all centered * as much as possible along the middle vertex in each rank. The other cells * are then placed as close as possible on either side. * * @param facade the facade describing the input graph * @param model an internal model of the hierarchical layout */ initialCoords(facade: Graph, model: GraphHierarchyModel) { this.calculateWidestRank(facade, model); // Sweep up and down from the widest rank for (let i = <number>this.widestRank; i >= 0; i--) { if (i < model.maxRank) { this.rankCoordinates(i, facade, model); } } for (let i = <number>this.widestRank + 1; i <= model.maxRank; i += 1) { if (i > 0) { this.rankCoordinates(i, facade, model); } } } /** * Sets up the layout in an initial positioning. All the first cells in each * rank are moved to the left and the rest of the rank inserted as close * together as their size and buffering permits. This method works on just * the specified rank. * * @param rankValue the current rank being processed * @param graph the facade describing the input graph * @param model an internal model of the hierarchical layout */ rankCoordinates(rankValue: number, graph: Graph, model: GraphHierarchyModel) { const ranks = <GraphAbstractHierarchyCell[][]>model.ranks; const rank = ranks[rankValue]; let maxY = 0.0; let localX = this.initialX + (<number>this.widestRankValue - (<number[]>this.rankWidths)[rankValue]) / 2; // Store whether or not any of the cells' bounds were unavailable so // to only issue the warning once for all cells let boundsWarning = false; for (let i = 0; i < rank.length; i += 1) { const node = rank[i]; if (node.isVertex()) { const bounds = this.layout.getVertexBounds((<GraphHierarchyNode>node).cell); if (bounds != null) { if ( this.orientation === DIRECTION.NORTH || this.orientation === DIRECTION.SOUTH ) { node.width = bounds.width; node.height = bounds.height; } else { node.width = bounds.height; node.height = bounds.width; } } else { boundsWarning = true; } maxY = Math.max(maxY, node.height); } else if (node.isEdge()) { // The width is the number of additional parallel edges // time the parallel edge spacing let numEdges = 1; if (node.edges != null) { numEdges = node.edges.length; } else { MaxLog.warn('edge.edges is null'); } node.width = (numEdges - 1) * this.parallelEdgeSpacing; } // Set the initial x-value as being the best result so far localX += node.width / 2.0; node.setX(rankValue, localX); node.setGeneralPurposeVariable(rankValue, localX); localX += node.width / 2.0; localX += this.intraCellSpacing; } if (boundsWarning == true) { MaxLog.warn('At least one cell has no bounds'); } } /** * Calculates the width rank in the hierarchy. Also set the y value of each * rank whilst performing the calculation * * @param graph the facade describing the input graph * @param model an internal model of the hierarchical layout */ calculateWidestRank(graph: Graph, model: GraphHierarchyModel) { // Starting y co-ordinate let y = -this.interRankCellSpacing; // Track the widest cell on the last rank since the y // difference depends on it let lastRankMaxCellHeight = 0.0; this.rankWidths = []; this.rankY = []; for (let rankValue = model.maxRank; rankValue >= 0; rankValue -= 1) { // Keep track of the widest cell on this rank let maxCellHeight = 0.0; const ranks = <GraphAbstractHierarchyCell[][]>model.ranks; const rank = ranks[rankValue]; let localX = this.initialX; // Store whether or not any of the cells' bounds were unavailable so // to only issue the warning once for all cells let boundsWarning = false; for (let i = 0; i < rank.length; i += 1) { const node = rank[i]; if (node.isVertex()) { const bounds = this.layout.getVertexBounds((<GraphHierarchyNode>node).cell); if (bounds != null) { if ( this.orientation === DIRECTION.NORTH || this.orientation === DIRECTION.SOUTH ) { node.width = bounds.width; node.height = bounds.height; } else { node.width = bounds.height; node.height = bounds.width; } } else { boundsWarning = true; } maxCellHeight = Math.max(maxCellHeight, node.height); } else if (node.isEdge()) { // The width is the number of additional parallel edges // time the parallel edge spacing let numEdges = 1; if (node.edges != null) { numEdges = node.edges.length; } else { MaxLog.warn('edge.edges is null'); } node.width = (numEdges - 1) * this.parallelEdgeSpacing; } // Set the initial x-value as being the best result so far localX += node.width / 2.0; node.setX(rankValue, localX); node.setGeneralPurposeVariable(rankValue, localX); localX += node.width / 2.0; localX += this.intraCellSpacing; if (localX > <number>this.widestRankValue) { this.widestRankValue = localX; this.widestRank = rankValue; } this.rankWidths[rankValue] = localX; } if (boundsWarning == true) { MaxLog.warn('At least one cell has no bounds'); } this.rankY[rankValue] = y; const distanceToNextRank = maxCellHeight / 2.0 + lastRankMaxCellHeight / 2.0 + this.interRankCellSpacing; lastRankMaxCellHeight = maxCellHeight; if ( this.orientation === DIRECTION.NORTH || this.orientation === DIRECTION.WEST ) { y += distanceToNextRank; } else { y -= distanceToNextRank; } for (let i = 0; i < rank.length; i += 1) { const cell = rank[i]; cell.setY(rankValue, y); } } } /** * Straightens out chains of virtual nodes where possibleacade to those stored after this layout * processing step has completed. * * @param graph the facade describing the input graph * @param model an internal model of the hierarchical layout */ minPath(graph: Graph, model: GraphHierarchyModel) { // Work down and up each edge with at least 2 control points // trying to straighten each one out. If the same number of // straight segments are formed in both directions, the // preferred direction used is the one where the final // control points have the least offset from the connectable // region of the terminating vertices const edges = model.edgeMapper.getValues(); for (let j = 0; j < edges.length; j++) { const cell = edges[j]; if (cell.maxRank - cell.minRank - 1 < 1) { continue; } // At least two virtual nodes in the edge // Check first whether the edge is already straight let referenceX = cell.getGeneralPurposeVariable(cell.minRank + 1); let edgeStraight = true; let refSegCount = 0; for (let i = cell.minRank + 2; i < cell.maxRank; i += 1) { const x = cell.getGeneralPurposeVariable(i); if (referenceX !== x) { edgeStraight = false; referenceX = x; } else { refSegCount += 1; } } if (!edgeStraight) { let upSegCount = 0; let downSegCount = 0; const upXPositions = []; const downXPositions = []; let i = 0; let currentX = cell.getGeneralPurposeVariable(cell.minRank + 1); for (i = cell.minRank + 1; i < cell.maxRank - 1; i += 1) { // Attempt to straight out the control point on the // next segment up with the current control point. const nextX = cell.getX(i + 1); if (currentX === nextX) { upXPositions[i - cell.minRank - 1] = currentX; upSegCount += 1; } else if (this.repositionValid(model, cell, i + 1, currentX)) { upXPositions[i - cell.minRank - 1] = currentX; upSegCount += 1; // Leave currentX at same value } else { upXPositions[i - cell.minRank - 1] = nextX; currentX = nextX; } } currentX = cell.getX(i); for (let i = cell.maxRank - 1; i > cell.minRank + 1; i--) { // Attempt to straight out the control point on the // next segment down with the current control point. const nextX = cell.getX(i - 1); if (currentX === nextX) { downXPositions[i - cell.minRank - 2] = currentX; downSegCount += 1; } else if (this.repositionValid(model, cell, i - 1, currentX)) { downXPositions[i - cell.minRank - 2] = currentX; downSegCount += 1; // Leave currentX at same value } else { downXPositions[i - cell.minRank - 2] = cell.getX(i - 1); currentX = nextX; } } if (downSegCount > refSegCount || upSegCount > refSegCount) { if (downSegCount >= upSegCount) { // Apply down calculation values for (let i = cell.maxRank - 2; i > cell.minRank; i--) { cell.setX(i, downXPositions[i - cell.minRank - 1]); } } else if (upSegCount > downSegCount) { // Apply up calculation values for (let i = cell.minRank + 2; i < cell.maxRank; i += 1) { cell.setX(i, upXPositions[i - cell.minRank - 2]); } } else { // Neither direction provided a favourable result // But both calculations are better than the // existing solution, so apply the one with minimal // offset to attached vertices at either end. } } } } } /** * Determines whether or not a node may be moved to the specified x * position on the specified rank * * @param model the layout model * @param cell the cell being analysed * @param rank the layer of the cell * @param position the x position being sought */ repositionValid(model: GraphHierarchyModel, cell: GraphHierarchyEdge | GraphHierarchyNode, rank: number, position: number) { const ranks = <GraphAbstractHierarchyCell[][]>model.ranks; const rankArray = ranks[rank]; let rankIndex = -1; for (let i = 0; i < rankArray.length; i += 1) { if (cell === rankArray[i]) { rankIndex = i; break; } } if (rankIndex < 0) { return false; } const currentX = cell.getGeneralPurposeVariable(rank); if (position < currentX) { // Trying to move node to the left. if (rankIndex === 0) { // Left-most node, can move anywhere return true; } const leftCell = rankArray[rankIndex - 1]; let leftLimit = <number>leftCell.getGeneralPurposeVariable(rank); leftLimit = leftLimit + leftCell.width / 2 + this.intraCellSpacing + cell.width / 2; return leftLimit <= position; } if (position > currentX) { // Trying to move node to the right. if (rankIndex === rankArray.length - 1) { // Right-most node, can move anywhere return true; } const rightCell = rankArray[rankIndex + 1]; let rightLimit = <number>rightCell.getGeneralPurposeVariable(rank); rightLimit = rightLimit - rightCell.width / 2 - this.intraCellSpacing - cell.width / 2; return rightLimit >= position; } return true; } /** * Sets the cell locations in the facade to those stored after this layout * processing step has completed. * * @param graph the input graph * @param model the layout model */ setCellLocations(graph: Graph, model: GraphHierarchyModel) { this.rankTopY = []; this.rankBottomY = []; const ranks = <GraphAbstractHierarchyCell[][]>model.ranks; for (let i = 0; i < ranks.length; i += 1) { this.rankTopY[i] = Number.MAX_VALUE; this.rankBottomY[i] = -Number.MAX_VALUE; } const vertices = model.vertexMapper.getValues(); // Process vertices all first, since they define the lower and // limits of each rank. Between these limits lie the channels // where the edges can be routed across the graph for (let i = 0; i < vertices.length; i += 1) { this.setVertexLocation(vertices[i]); } // Post process edge styles. Needs the vertex locations set for initial // values of the top and bottoms of each rank if ( this.layout.edgeStyle === HierarchicalEdgeStyle.ORTHOGONAL || this.layout.edgeStyle === HierarchicalEdgeStyle.POLYLINE || this.layout.edgeStyle === HierarchicalEdgeStyle.CURVE ) { this.localEdgeProcessing(model); } const edges = model.edgeMapper.getValues(); for (let i = 0; i < edges.length; i += 1) { this.setEdgePosition(edges[i]); } } /** * Separates the x position of edges as they connect to vertices * * @param model the layout model */ localEdgeProcessing(model: GraphHierarchyModel) { // Iterate through each vertex, look at the edges connected in // both directions. const ranks = <GraphAbstractHierarchyCell[][]>model.ranks; for (let rankIndex = 0; rankIndex < ranks.length; rankIndex += 1) { const rank = ranks[rankIndex]; for (let cellIndex = 0; cellIndex < rank.length; cellIndex += 1) { const cell = rank[cellIndex]; if (cell.isVertex()) { let currentCells = cell.getPreviousLayerConnectedCells(rankIndex); let currentRank = rankIndex - 1; // Two loops, last connected cells, and next for (let k = 0; k < 2; k += 1) { if ( currentRank > -1 && currentRank < ranks.length && currentCells != null && currentCells.length > 0 ) { const sortedCells = []; for (let j = 0; j < currentCells.length; j++) { const sorter = new WeightedCellSorter( currentCells[j], currentCells[j].getX(currentRank) ); sortedCells.push(sorter); } sortedCells.sort(WeightedCellSorter.compare); let leftLimit = cell.x[0] - cell.width / 2; let rightLimit = leftLimit + cell.width; // Connected edge count starts at 1 to allow for buffer // with edge of vertex let connectedEdgeCount = 0; let connectedEdgeGroupCount = 0; const connectedEdges = []; // Calculate width requirements for all connected edges for (let j = 0; j < sortedCells.length; j++) { const innerCell = <GraphHierarchyNode>sortedCells[j].cell; var connections; if (innerCell.isVertex()) { // Get the connecting edge if (k === 0) { connections = (<GraphHierarchyNode>cell).connectsAsSource; } else { connections = (<GraphHierarchyNode>cell).connectsAsTarget; } for ( let connIndex = 0; connIndex < connections.length; connIndex += 1 ) { if ( connections[connIndex].source === innerCell || connections[connIndex].target === innerCell ) { connectedEdgeCount += connections[connIndex].edges.length; connectedEdgeGroupCount += 1; connectedEdges.push(connections[connIndex]); } } } else { connectedEdgeCount += innerCell.edges.length; connectedEdgeGroupCount += 1; connectedEdges.push(innerCell); } } const requiredWidth = (connectedEdgeCount + 1) * this.prefHozEdgeSep; // Add a buffer on the edges of the vertex if the edge count allows if (cell.width > requiredWidth + 2 * this.prefHozEdgeSep) { leftLimit += this.prefHozEdgeSep; rightLimit -= this.prefHozEdgeSep; } const availableWidth = rightLimit - leftLimit; const edgeSpacing = availableWidth / connectedEdgeCount; let currentX = leftLimit + edgeSpacing / 2.0; let currentYOffset = this.minEdgeJetty - this.prefVertEdgeOff; let maxYOffset = 0; for (let j = 0; j < connectedEdges.length; j++) { const numActualEdges = connectedEdges[j].edges.length; const jettyPositions = <{ [key: string]: number[] }>this.jettyPositions; let pos = jettyPositions[connectedEdges[j].ids[0]]; if (pos == null) { pos = []; jettyPositions[connectedEdges[j].ids[0]] = pos; } if (j < connectedEdgeCount / 2) { currentYOffset += this.prefVertEdgeOff; } else if (j > connectedEdgeCount / 2) { currentYOffset -= this.prefVertEdgeOff; } // Ignore the case if equals, this means the second of 2 // jettys with the same y (even number of edges) for (let m = 0; m < numActualEdges; m += 1) { pos[m * 4 + k * 2] = currentX; currentX += edgeSpacing; pos[m * 4 + k * 2 + 1] = currentYOffset; } maxYOffset = Math.max(maxYOffset, currentYOffset); } } currentCells = cell.getNextLayerConnectedCells(rankIndex); currentRank = rankIndex + 1; } } } } } /** * Fixes the control points */ setEdgePosition(cell: GraphHierarchyEdge) { // For parallel edges we need to seperate out the points a // little let offsetX = 0; // Only set the edge control points once if (cell.temp[0] !== 101207) { let { maxRank } = cell; let { minRank } = cell; if (maxRank === minRank) { maxRank = (<GraphHierarchyNode>cell.source).maxRank; minRank = (<GraphHierarchyNode>cell.target).minRank; } let parallelEdgeCount = 0; const jettyPositions = <{ [key: string]: number[] }>this.jettyPositions; const jettys = jettyPositions[cell.ids[0]]; const source = cell.isReversed ? (<GraphHierarchyNode>cell.target).cell : (<GraphHierarchyNode>cell.source).cell; const { graph } = this.layout; const layoutReversed = this.orientation === DIRECTION.EAST || this.orientation === DIRECTION.SOUTH; for (let i = 0; i < cell.edges.length; i += 1) { const realEdge = cell.edges[i]; const realSource = this.layout.getVisibleTerminal(realEdge, true); // List oldPoints = graph.getPoints(realEdge); const newPoints = []; // Single length reversed edges end up with the jettys in the wrong // places. Since single length edges only have jettys, not segment // control points, we just say the edge isn't reversed in this section let reversed = cell.isReversed; if (realSource !== source) { // The real edges include all core model edges and these can go // in both directions. If the source of the hierarchical model edge // isn't the source of the specific real edge in this iteration // treat if as reversed reversed = !reversed; } // First jetty of edge if (jettys != null) { const arrayOffset = reversed ? 2 : 0; const rankBottomY = <number[]>this.rankBottomY; const rankTopY = <number[]>this.rankTopY; let y = reversed ? layoutReversed ? rankBottomY[minRank] : rankTopY[minRank] : layoutReversed ? rankTopY[maxRank] : rankBottomY[maxRank]; let jetty = jettys[parallelEdgeCount * 4 + 1 + arrayOffset]; if (reversed !== layoutReversed) { jetty = -jetty; } y += jetty; let x = jettys[parallelEdgeCount * 4 + arrayOffset]; const modelSource = <Cell>realEdge.getTerminal(true); if (this.layout.isPort(modelSource) && modelSource.getParent() === realSource) { const state = graph.view.getState(modelSource); if (state != null) { x = state.x; } else { x = (<Geometry>(<Cell>realSource).geometry).x + (<GraphHierarchyNode>cell.source).width * (<Geometry>modelSource.geometry).x; } } if (this.orientation === DIRECTION.NORTH || this.orientation === DIRECTION.SOUTH) { newPoints.push(new Point(x, y)); if (this.layout.edgeStyle === HierarchicalEdgeStyle.CURVE) { newPoints.push(new Point(x, y + jetty)); } } else { newPoints.push(new Point(y, x)); if (this.layout.edgeStyle === HierarchicalEdgeStyle.CURVE) { newPoints.push(new Point(y + jetty, x)); } } } // Declare variables to define loop through edge points and // change direction if edge is reversed let loopStart = cell.x.length - 1; let loopLimit = -1; let loopDelta = -1; let currentRank = cell.maxRank - 1; if (reversed) { loopStart = 0; loopLimit = cell.x.length; loopDelta = 1; currentRank = cell.minRank + 1; } // Reversed edges need the points inserted in // reverse order for ( let j = loopStart; cell.maxRank !== cell.minRank && j !== loopLimit; j += loopDelta ) { // The horizontal position in a vertical layout const positionX = cell.x[j] + offsetX; // Work out the vertical positions in a vertical layout // in the edge buffer channels above and below this rank const rankTopY = <number[]>this.rankTopY; const rankBottomY = <number[]>this.rankBottomY; let topChannelY = (rankTopY[currentRank] + rankBottomY[currentRank + 1]) / 2.0; let bottomChannelY = (rankTopY[currentRank - 1] + rankBottomY[currentRank]) / 2.0; if (reversed) { const tmp = topChannelY; topChannelY = bottomChannelY; bottomChannelY = tmp; } if ( this.orientation === DIRECTION.NORTH || this.orientation === DIRECTION.SOUTH ) { newPoints.push(new Point(positionX, topChannelY)); newPoints.push(new Point(positionX, bottomChannelY)); } else { newPoints.push(new Point(topChannelY, positionX)); newPoints.push(new Point(bottomChannelY, positionX)); } this.limitX = Math.max(<number>this.limitX, positionX); currentRank += loopDelta; } // Second jetty of edge if (jettys != null) { const arrayOffset = reversed ? 2 : 0; const rankTopY = <number[]>this.rankTopY; const rankBottomY = <number[]>this.rankBottomY; const rankY = reversed ? layoutReversed ? rankTopY[maxRank] : rankBottomY[maxRank] : layoutReversed ? rankBottomY[minRank] : rankTopY[minRank]; let jetty = jettys[parallelEdgeCount * 4 + 3 - arrayOffset]; if (reversed !== layoutReversed) { jetty = -jetty; } const y = rankY - jetty; let x = jettys[parallelEdgeCount * 4 + 2 - arrayOffset]; const modelTarget = <Cell>realEdge.getTerminal(false); const realTarget = <Cell>this.layout.getVisibleTerminal(realEdge, false); if ( this.layout.isPort(modelTarget) && modelTarget.getParent() === realTarget ) { const state = graph.view.getState(modelTarget); if (state != null) { x = state.x; } else { x = (<Geometry>realTarget.geometry).x + (<GraphHierarchyNode>cell.target).width * (<Geometry>modelTarget.geometry).x; } } if ( this.orientation === DIRECTION.NORTH || this.orientation === DIRECTION.SOUTH ) { if (this.layout.edgeStyle === HierarchicalEdgeStyle.CURVE) { newPoints.push(new Point(x, y - jetty)); } newPoints.push(new Point(x, y)); } else { if (this.layout.edgeStyle === HierarchicalEdgeStyle.CURVE) { newPoints.push(new Point(y - jetty, x)); } newPoints.push(new Point(y, x)); } } if (cell.isReversed) { this.processReversedEdge(cell, realEdge); } this.layout.setEdgePoints(realEdge, newPoints); // Increase offset so next edge is drawn next to // this one if (offsetX === 0.0) { offsetX = this.parallelEdgeSpacing; } else if (offsetX > 0) { offsetX = -offsetX; } else { offsetX = -offsetX + this.parallelEdgeSpacing; } parallelEdgeCount++; } cell.temp[0] = 101207; } } /** * Fixes the position of the specified vertex. * * @param cell the vertex to position */ setVertexLocation(cell: GraphHierarchyNode) { const realCell = cell.cell; const positionX = cell.x[0] - cell.width / 2; const positionY = cell.y[0] - cell.height / 2; const rankTopY = <number[]>this.rankTopY; const rankBottomY = <number[]>this.rankBottomY; rankTopY[cell.minRank] = Math.min(rankTopY[cell.minRank], positionY); rankBottomY[cell.minRank] = Math.max(rankBottomY[cell.minRank], positionY + cell.height); if ( this.orientation === DIRECTION.NORTH || this.orientation === DIRECTION.SOUTH ) { this.layout.setVertexLocation(realCell, positionX, positionY); } else { this.layout.setVertexLocation(realCell, positionY, positionX); } this.limitX = Math.max(<number>this.limitX, positionX + cell.width); } /** * Hook to add additional processing * * @param edge the hierarchical model edge * @param realEdge the real edge in the graph */ processReversedEdge(edge: GraphHierarchyEdge, realEdge: Cell) { // hook for subclassers } } export default CoordinateAssignment;
the_stack
import Taro, { Component, Config } from '@tarojs/taro' import { View, PickerView } from '@tarojs/components' import { AtIcon, AtAvatar, AtSegmentedControl, AtSearchBar ,AtDivider} from 'taro-ui' import './trending.scss' export default class Trending extends Component { config: Config = { navigationBarTitleText: 'GitHub' } constructor() { super(...arguments) this.state = { data: [], language: '', since: 1, sort: 'stars', gitType: 'taro', list: '', idx:0, baseUrl: 'http://anly.leanapp.cn/api/github/trending/vue?since=weekly', temp: [ { 'avatar': 'https://avatars0.githubusercontent.com/u/8121621?s=40&v=4', 'desc': '\ud83c\udf89 A magical vue admin http://panjiachen.github.io/vue-element-admin', 'link': 'https://github.com/PanJiaChen/vue-element-admin', 'owner': 'PanJiaChen', 'repo': 'vue-element-admin', 'stars': '23,082' }, { 'avatar': 'https://avatars2.githubusercontent.com/u/10095631?s=40&v=4', 'desc': 'A Vue.js 2.0 UI Toolkit for Web', 'link': 'https://github.com/ElemeFE/element', 'owner': 'ElemeFE', 'repo': 'element', 'stars': '32,943' }, { 'avatar': 'https://avatars0.githubusercontent.com/u/24296884?s=40&v=4', 'desc': '\u4f7f\u7528 Vue.js \u5f00\u53d1\u8de8\u5e73\u53f0\u5e94\u7528\u7684\u524d\u7aef\u6846\u67b6', 'link': 'https://github.com/dcloudio/uni-app', 'owner': 'dcloudio', 'repo': 'uni-app', 'stars': '932' }, { 'avatar': 'https://avatars0.githubusercontent.com/u/20297227?s=40&v=4', 'desc': '\u57fa\u4e8e vue2 + vuex \u6784\u5efa\u4e00\u4e2a\u5177\u6709 45 \u4e2a\u9875\u9762\u7684\u5927\u578b\u5355\u9875\u9762\u5e94\u7528', 'link': 'https://github.com/bailicangdu/vue2-elm', 'owner': 'bailicangdu', 'repo': 'vue2-elm', 'stars': '23,753' }, { 'avatar': 'https://avatars0.githubusercontent.com/u/5370542?s=40&v=4', 'desc': 'A high quality UI Toolkit built on Vue.js 2.0', 'link': 'https://github.com/iview/iview', 'owner': 'iview', 'repo': 'iview', 'stars': '18,561' }, { 'avatar': 'https://avatars0.githubusercontent.com/u/20942571?s=40&v=4', 'desc': 'Vue 2.0 admin management system template based on iView', 'link': 'https://github.com/iview/iview-admin', 'owner': 'iview', 'repo': 'iview-admin', 'stars': '9,595' }, { 'avatar': 'https://avatars0.githubusercontent.com/u/211899?s=40&v=4', 'desc': 'Vue Storefront - PWA for eCommerce. 100% offline, platform agnostic, headless, Magento 2 supported. Always Open Source, MIT license. Join us as contributor (contributors@vuestorefront.io).', 'link': 'https://github.com/DivanteLtd/vue-storefront', 'owner': 'DivanteLtd', 'repo': 'vue-storefront', 'stars': '3,556' }, { 'avatar': 'https://avatars3.githubusercontent.com/u/6937879?s=40&v=4', 'desc': 'An enterprise-class UI components based on Ant Design and Vue. \ud83d\udc1c', 'link': 'https://github.com/vueComponent/ant-design-vue', 'owner': 'vueComponent', 'repo': 'ant-design-vue', 'stars': '3,093' }, { 'avatar': 'https://avatars0.githubusercontent.com/u/7237365?s=40&v=4', 'desc': 'Lightweight Mobile UI Components built on Vue', 'link': 'https://github.com/youzan/vant', 'owner': 'youzan', 'repo': 'vant', 'stars': '6,681' }, { 'avatar': 'https://avatars0.githubusercontent.com/u/12621342?s=40&v=4', 'desc': '\ud83d\ude80 A simple & beautiful tool for pictures uploading built by electron-vue', 'link': 'https://github.com/Molunerfinn/PicGo', 'owner': 'Molunerfinn', 'repo': 'PicGo', 'stars': '2,812' }, { 'avatar': 'https://avatars3.githubusercontent.com/u/559179?s=40&v=4', 'desc': 'Mobile UI Components based on Vue & WeUI', 'link': 'https://github.com/airyland/vux', 'owner': 'airyland', 'repo': 'vux', 'stars': '14,590' }, { 'avatar': 'https://avatars3.githubusercontent.com/u/17480987?s=40&v=4', 'desc': 'Is a pack of more than 480 beautiful open source Eva icons as Vue components', 'link': 'https://github.com/antonreshetov/vue-eva-icons', 'owner': 'antonreshetov', 'repo': 'vue-eva-icons', 'stars': '69' }, { 'avatar': 'https://avatars2.githubusercontent.com/u/1472352?s=40&v=4', 'desc': '\u4e00\u523b\u793e\u533a\u524d\u7aef\u6e90\u7801', 'link': 'https://github.com/overtrue/yike.io', 'owner': 'overtrue', 'repo': 'yike.io', 'stars': '346' }, { 'avatar': 'https://avatars0.githubusercontent.com/u/18370605?s=40&v=4', 'desc': 'Lightweight UI components for Vue.js based on Bulma', 'link': 'https://github.com/buefy/buefy', 'owner': 'buefy', 'repo': 'buefy', 'stars': '4,145' }, { 'avatar': 'https://avatars1.githubusercontent.com/u/22343354?s=40&v=4', 'desc': 'Mysql web\u7aefsql\u5ba1\u6838\u5e73\u53f0', 'link': 'https://github.com/cookieY/Yearning', 'owner': 'cookieY', 'repo': 'Yearning', 'stars': '1,463' }, { 'avatar': 'https://avatars3.githubusercontent.com/u/854406?s=40&v=4', 'desc': 'A simple region selector, provide Chinese administrative division data', 'link': 'https://github.com/TerryZ/v-region', 'owner': 'TerryZ', 'repo': 'v-region', 'stars': '369' }, { 'avatar': 'https://avatars2.githubusercontent.com/u/1357885?s=40&v=4', 'desc': 'Material design for Vue.js', 'link': 'https://github.com/vuematerial/vue-material', 'owner': 'vuematerial', 'repo': 'vue-material', 'stars': '7,282' }, { 'avatar': 'https://avatars3.githubusercontent.com/u/7221389?s=40&v=4', 'desc': '\ud83d\udcd6 Read Quran Anywhere, Directly from Your Browser, No Need Installing Apps Anymore.', 'link': 'https://github.com/mazipan/quran-offline', 'owner': 'mazipan', 'repo': 'quran-offline', 'stars': '36' }, { 'avatar': 'https://avatars3.githubusercontent.com/u/22396965?s=40&v=4', 'desc': 'A Vue.js 2.0 slideshow component working with Three.js', 'link': 'https://github.com/AlbanCrepel/vue-displacement-slideshow', 'owner': 'AlbanCrepel', 'repo': 'vue-displacement-slideshow', 'stars': '39' }, { 'avatar': 'https://avatars2.githubusercontent.com/u/26454305?s=40&v=4', 'desc': 'mavonEditor - A markdown editor based on Vue that supports a variety of personalized features', 'link': 'https://github.com/hinesboy/mavonEditor', 'owner': 'hinesboy', 'repo': 'mavonEditor', 'stars': '1,873' }, { 'avatar': 'https://avatars3.githubusercontent.com/u/19411940?s=40&v=4', 'desc': '', 'link': 'https://github.com/ftdus/PyUI', 'owner': 'ftdus', 'repo': 'PyUI', 'stars': '46' }, { 'avatar': 'https://avatars1.githubusercontent.com/u/29813435?s=40&v=4', 'desc': '\u7cbe\u81f4\u7684\u4e0b\u62c9\u5237\u65b0\u548c\u4e0a\u62c9\u52a0\u8f7d js\u6846\u67b6.\u652f\u6301vue,\u5b8c\u7f8e\u8fd0\u884c\u4e8e\u79fb\u52a8\u7aef\u548c\u4e3b\u6d41PC\u6d4f\u89c8\u5668 (JS framework for pull-refresh and pull-up-loading)', 'link': 'https://github.com/mescroll/mescroll', 'owner': 'mescroll', 'repo': 'mescroll', 'stars': '1,522' }, { 'avatar': 'https://avatars0.githubusercontent.com/u/13193407?s=40&v=4', 'desc': '\ud83d\udcf1 \u4e00\u5957 Vue \u4ee3\u7801\uff0c\u4e24\u7aef\u539f\u751f\u5e94\u7528 \uff0c\u6216\u8bb8\u53ef\u4ee5\u53eb\u6211 weex-native\u3002', 'link': 'https://github.com/bmfe/eros', 'owner': 'bmfe', 'repo': 'eros', 'stars': '1,431' }, { 'avatar': 'https://avatars1.githubusercontent.com/u/421233?s=40&v=4', 'desc': 'A collection of components that visualizes DaySpan Calendars and Schedules using Vuetify', 'link': 'https://github.com/ClickerMonkey/dayspan-vuetify', 'owner': 'ClickerMonkey', 'repo': 'dayspan-vuetify', 'stars': '314' }, { 'avatar': 'https://avatars0.githubusercontent.com/u/3674348?s=40&v=4', 'desc': 'Vue.js admin dashboard', 'link': 'https://github.com/epicmaxco/vuestic-admin', 'owner': 'epicmaxco', 'repo': 'vuestic-admin', 'stars': '4,934' } ] } } componentDidMount() { // Taro.request({ url: this.state.baseUrl }).then(res => { // console.log(res) // }) this.fetchDate(''); } onReachBottom() { this.state.idx <= 30 ? this.setState({idx:this.state.idx+6}) :''; } toLink(e) { // <web-view src="https://github.com/PanJiaChen/vue-element-admin"></web-view> } onChange(value) { this.setState({ language: value }) } onActionClick() { this.fetchDate(this.state.language, this.state.sort) } choseSince(val) { let sort = 'stars' if (val === 0) { sort = 'match' this.setState({ since: 0 }) } else if (val === 2) { sort = 'forks' this.setState({ since: 2 }) } else { this.setState({ since: 1 }) } this.fetchDate(this.state.language, sort) } fetchDate(language, sort = 'stars') { Taro.showLoading({ title: '获取中...', }) language = language || 'taro' let url = `https://api.github.com/search/repositories?q=${language}&sort=${sort}&order=desc` Taro.request({ url: url }).then(res => { this.setState({ list: res.data.items }) Taro.hideLoading() }) } render() { let list = this.state.list.slice(0,this.state.idx+6) return ( <View onClick={this.toLink}> <AtSearchBar actionName='搜一下' value={this.state.language} onChange={this.onChange.bind(this)} onActionClick={this.onActionClick.bind(this)} /> <AtSegmentedControl values={['Match', 'Stars', 'Forks']} onClick={this.choseSince.bind(this)} current={this.state.since} /> <View class="itemsView"> {list && list.map(item => { return ( <View key={item.owner} class='items'> {/* <Text>{item.link}</Text> */} <View class='itemCont'> <View class='itemInfo'> <View> <Text data-link={item.link}>{item.name}</Text> </View> <Text class='itemDesc'>{item.description ? item.description.slice(0, 100)+'...' : ''}</Text> </View> <View class='itemOwner'> <Image src={item.owner.avatar_url} class='ownerImg'></Image> <Text class='owner'>{item.owner.login}</Text> </View> </View> <View class='itemStars'> <View> <Text class='iconfont icon-shezhi_tougao_edit'></Text> <Text>{item.language}</Text> </View> <View> <Text class='iconfont icon-star1'></Text> <Text>{item.stargazers_count}</Text> </View> <View> <Text class='iconfont icon-fork'></Text> <Text>{item.forks}</Text> </View> </View> </View> ) })} </View> {this.state.idx>=30 && <AtDivider content='没有更多了' />} </View> ) } }
the_stack
import * as coreClient from "@azure/core-client"; export interface ErrorModel { status?: number; message?: string; } export interface MyException { statusCode?: string; } export interface C { httpCode?: string; } export interface D { httpStatusCode?: string; } export type B = MyException & { textStatusCode?: string; }; /** Defines headers for HttpRedirects_head300 operation. */ export interface HttpRedirectsHead300Headers { /** The redirect location for this request */ location?: "/http/success/head/200"; } /** Defines headers for HttpRedirects_get300 operation. */ export interface HttpRedirectsGet300Headers { /** The redirect location for this request */ location?: "/http/success/get/200"; } /** Defines headers for HttpRedirects_head301 operation. */ export interface HttpRedirectsHead301Headers { /** The redirect location for this request */ location?: "/http/success/head/200"; } /** Defines headers for HttpRedirects_get301 operation. */ export interface HttpRedirectsGet301Headers { /** The redirect location for this request */ location?: "/http/success/get/200"; } /** Defines headers for HttpRedirects_put301 operation. */ export interface HttpRedirectsPut301Headers { /** The redirect location for this request */ location?: "/http/failure/500"; } /** Defines headers for HttpRedirects_head302 operation. */ export interface HttpRedirectsHead302Headers { /** The redirect location for this request */ location?: "/http/success/head/200"; } /** Defines headers for HttpRedirects_get302 operation. */ export interface HttpRedirectsGet302Headers { /** The redirect location for this request */ location?: "/http/success/get/200"; } /** Defines headers for HttpRedirects_patch302 operation. */ export interface HttpRedirectsPatch302Headers { /** The redirect location for this request */ location?: "/http/failure/500"; } /** Defines headers for HttpRedirects_post303 operation. */ export interface HttpRedirectsPost303Headers { /** The redirect location for this request */ location?: "/http/success/get/200"; } /** Defines headers for HttpRedirects_head307 operation. */ export interface HttpRedirectsHead307Headers { /** The redirect location for this request */ location?: "/http/success/head/200"; } /** Defines headers for HttpRedirects_get307 operation. */ export interface HttpRedirectsGet307Headers { /** The redirect location for this request */ location?: "/http/success/get/200"; } /** Defines headers for HttpRedirects_options307 operation. */ export interface HttpRedirectsOptions307Headers { /** The redirect location for this request */ location?: "/http/success/options/200"; } /** Defines headers for HttpRedirects_put307 operation. */ export interface HttpRedirectsPut307Headers { /** The redirect location for this request */ location?: "/http/success/put/200"; } /** Defines headers for HttpRedirects_patch307 operation. */ export interface HttpRedirectsPatch307Headers { /** The redirect location for this request */ location?: "/http/success/patch/200"; } /** Defines headers for HttpRedirects_post307 operation. */ export interface HttpRedirectsPost307Headers { /** The redirect location for this request */ location?: "/http/success/post/200"; } /** Defines headers for HttpRedirects_delete307 operation. */ export interface HttpRedirectsDelete307Headers { /** The redirect location for this request */ location?: "/http/success/delete/200"; } /** Optional parameters. */ export interface HttpFailureGetEmptyErrorOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getEmptyError operation. */ export type HttpFailureGetEmptyErrorResponse = { /** The parsed response body. */ body: boolean; }; /** Optional parameters. */ export interface HttpFailureGetNoModelErrorOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getNoModelError operation. */ export type HttpFailureGetNoModelErrorResponse = { /** The parsed response body. */ body: boolean; }; /** Optional parameters. */ export interface HttpFailureGetNoModelEmptyOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getNoModelEmpty operation. */ export type HttpFailureGetNoModelEmptyResponse = { /** The parsed response body. */ body: boolean; }; /** Optional parameters. */ export interface HttpSuccessHead200OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpSuccessGet200OptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get200 operation. */ export type HttpSuccessGet200Response = { /** The parsed response body. */ body: boolean; }; /** Optional parameters. */ export interface HttpSuccessOptions200OptionalParams extends coreClient.OperationOptions {} /** Contains response data for the options200 operation. */ export type HttpSuccessOptions200Response = { /** The parsed response body. */ body: boolean; }; /** Optional parameters. */ export interface HttpSuccessPut200OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpSuccessPatch200OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpSuccessPost200OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpSuccessDelete200OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpSuccessPut201OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpSuccessPost201OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpSuccessPut202OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpSuccessPatch202OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpSuccessPost202OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpSuccessDelete202OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpSuccessHead204OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpSuccessPut204OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpSuccessPatch204OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpSuccessPost204OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpSuccessDelete204OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpSuccessHead404OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpRedirectsHead300OptionalParams extends coreClient.OperationOptions {} /** Contains response data for the head300 operation. */ export type HttpRedirectsHead300Response = HttpRedirectsHead300Headers; /** Optional parameters. */ export interface HttpRedirectsGet300OptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get300 operation. */ export type HttpRedirectsGet300Response = HttpRedirectsGet300Headers & { /** The parsed response body. */ body: string[]; }; /** Optional parameters. */ export interface HttpRedirectsHead301OptionalParams extends coreClient.OperationOptions {} /** Contains response data for the head301 operation. */ export type HttpRedirectsHead301Response = HttpRedirectsHead301Headers; /** Optional parameters. */ export interface HttpRedirectsGet301OptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get301 operation. */ export type HttpRedirectsGet301Response = HttpRedirectsGet301Headers; /** Optional parameters. */ export interface HttpRedirectsPut301OptionalParams extends coreClient.OperationOptions {} /** Contains response data for the put301 operation. */ export type HttpRedirectsPut301Response = HttpRedirectsPut301Headers; /** Optional parameters. */ export interface HttpRedirectsHead302OptionalParams extends coreClient.OperationOptions {} /** Contains response data for the head302 operation. */ export type HttpRedirectsHead302Response = HttpRedirectsHead302Headers; /** Optional parameters. */ export interface HttpRedirectsGet302OptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get302 operation. */ export type HttpRedirectsGet302Response = HttpRedirectsGet302Headers; /** Optional parameters. */ export interface HttpRedirectsPatch302OptionalParams extends coreClient.OperationOptions {} /** Contains response data for the patch302 operation. */ export type HttpRedirectsPatch302Response = HttpRedirectsPatch302Headers; /** Optional parameters. */ export interface HttpRedirectsPost303OptionalParams extends coreClient.OperationOptions {} /** Contains response data for the post303 operation. */ export type HttpRedirectsPost303Response = HttpRedirectsPost303Headers; /** Optional parameters. */ export interface HttpRedirectsHead307OptionalParams extends coreClient.OperationOptions {} /** Contains response data for the head307 operation. */ export type HttpRedirectsHead307Response = HttpRedirectsHead307Headers; /** Optional parameters. */ export interface HttpRedirectsGet307OptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get307 operation. */ export type HttpRedirectsGet307Response = HttpRedirectsGet307Headers; /** Optional parameters. */ export interface HttpRedirectsOptions307OptionalParams extends coreClient.OperationOptions {} /** Contains response data for the options307 operation. */ export type HttpRedirectsOptions307Response = HttpRedirectsOptions307Headers; /** Optional parameters. */ export interface HttpRedirectsPut307OptionalParams extends coreClient.OperationOptions {} /** Contains response data for the put307 operation. */ export type HttpRedirectsPut307Response = HttpRedirectsPut307Headers; /** Optional parameters. */ export interface HttpRedirectsPatch307OptionalParams extends coreClient.OperationOptions {} /** Contains response data for the patch307 operation. */ export type HttpRedirectsPatch307Response = HttpRedirectsPatch307Headers; /** Optional parameters. */ export interface HttpRedirectsPost307OptionalParams extends coreClient.OperationOptions {} /** Contains response data for the post307 operation. */ export type HttpRedirectsPost307Response = HttpRedirectsPost307Headers; /** Optional parameters. */ export interface HttpRedirectsDelete307OptionalParams extends coreClient.OperationOptions {} /** Contains response data for the delete307 operation. */ export type HttpRedirectsDelete307Response = HttpRedirectsDelete307Headers; /** Optional parameters. */ export interface HttpClientFailureHead400OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpClientFailureGet400OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpClientFailureOptions400OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpClientFailurePut400OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpClientFailurePatch400OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpClientFailurePost400OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpClientFailureDelete400OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpClientFailureHead401OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpClientFailureGet402OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpClientFailureOptions403OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpClientFailureGet403OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpClientFailurePut404OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpClientFailurePatch405OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpClientFailurePost406OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpClientFailureDelete407OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpClientFailurePut409OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpClientFailureHead410OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpClientFailureGet411OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpClientFailureOptions412OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpClientFailureGet412OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpClientFailurePut413OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpClientFailurePatch414OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpClientFailurePost415OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpClientFailureGet416OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpClientFailureDelete417OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpClientFailureHead429OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpServerFailureHead501OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpServerFailureGet501OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpServerFailurePost505OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpServerFailureDelete505OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpRetryHead408OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpRetryPut500OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpRetryPatch500OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpRetryGet502OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpRetryOptions502OptionalParams extends coreClient.OperationOptions {} /** Contains response data for the options502 operation. */ export type HttpRetryOptions502Response = { /** The parsed response body. */ body: boolean; }; /** Optional parameters. */ export interface HttpRetryPost503OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpRetryDelete503OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpRetryPut504OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface HttpRetryPatch504OptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface MultipleResponsesGet200Model204NoModelDefaultError200ValidOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get200Model204NoModelDefaultError200Valid operation. */ export type MultipleResponsesGet200Model204NoModelDefaultError200ValidResponse = MyException; /** Optional parameters. */ export interface MultipleResponsesGet200Model204NoModelDefaultError204ValidOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get200Model204NoModelDefaultError204Valid operation. */ export type MultipleResponsesGet200Model204NoModelDefaultError204ValidResponse = MyException; /** Optional parameters. */ export interface MultipleResponsesGet200Model204NoModelDefaultError201InvalidOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get200Model204NoModelDefaultError201Invalid operation. */ export type MultipleResponsesGet200Model204NoModelDefaultError201InvalidResponse = MyException; /** Optional parameters. */ export interface MultipleResponsesGet200Model204NoModelDefaultError202NoneOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get200Model204NoModelDefaultError202None operation. */ export type MultipleResponsesGet200Model204NoModelDefaultError202NoneResponse = MyException; /** Optional parameters. */ export interface MultipleResponsesGet200Model204NoModelDefaultError400ValidOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get200Model204NoModelDefaultError400Valid operation. */ export type MultipleResponsesGet200Model204NoModelDefaultError400ValidResponse = MyException; /** Optional parameters. */ export interface MultipleResponsesGet200Model201ModelDefaultError200ValidOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get200Model201ModelDefaultError200Valid operation. */ export type MultipleResponsesGet200Model201ModelDefaultError200ValidResponse = MyException; /** Optional parameters. */ export interface MultipleResponsesGet200Model201ModelDefaultError201ValidOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get200Model201ModelDefaultError201Valid operation. */ export type MultipleResponsesGet200Model201ModelDefaultError201ValidResponse = MyException; /** Optional parameters. */ export interface MultipleResponsesGet200Model201ModelDefaultError400ValidOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get200Model201ModelDefaultError400Valid operation. */ export type MultipleResponsesGet200Model201ModelDefaultError400ValidResponse = MyException; /** Optional parameters. */ export interface MultipleResponsesGet200ModelA201ModelC404ModelDDefaultError200ValidOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get200ModelA201ModelC404ModelDDefaultError200Valid operation. */ export type MultipleResponsesGet200ModelA201ModelC404ModelDDefaultError200ValidResponse = MyException; /** Optional parameters. */ export interface MultipleResponsesGet200ModelA201ModelC404ModelDDefaultError201ValidOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get200ModelA201ModelC404ModelDDefaultError201Valid operation. */ export type MultipleResponsesGet200ModelA201ModelC404ModelDDefaultError201ValidResponse = MyException; /** Optional parameters. */ export interface MultipleResponsesGet200ModelA201ModelC404ModelDDefaultError404ValidOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get200ModelA201ModelC404ModelDDefaultError404Valid operation. */ export type MultipleResponsesGet200ModelA201ModelC404ModelDDefaultError404ValidResponse = MyException; /** Optional parameters. */ export interface MultipleResponsesGet200ModelA201ModelC404ModelDDefaultError400ValidOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get200ModelA201ModelC404ModelDDefaultError400Valid operation. */ export type MultipleResponsesGet200ModelA201ModelC404ModelDDefaultError400ValidResponse = MyException; /** Optional parameters. */ export interface MultipleResponsesGet202None204NoneDefaultError202NoneOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface MultipleResponsesGet202None204NoneDefaultError204NoneOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface MultipleResponsesGet202None204NoneDefaultError400ValidOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface MultipleResponsesGet202None204NoneDefaultNone202InvalidOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface MultipleResponsesGet202None204NoneDefaultNone204NoneOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface MultipleResponsesGet202None204NoneDefaultNone400NoneOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface MultipleResponsesGet202None204NoneDefaultNone400InvalidOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface MultipleResponsesGetDefaultModelA200ValidOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getDefaultModelA200Valid operation. */ export type MultipleResponsesGetDefaultModelA200ValidResponse = MyException; /** Optional parameters. */ export interface MultipleResponsesGetDefaultModelA200NoneOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the getDefaultModelA200None operation. */ export type MultipleResponsesGetDefaultModelA200NoneResponse = MyException; /** Optional parameters. */ export interface MultipleResponsesGetDefaultModelA400ValidOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface MultipleResponsesGetDefaultModelA400NoneOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface MultipleResponsesGetDefaultNone200InvalidOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface MultipleResponsesGetDefaultNone200NoneOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface MultipleResponsesGetDefaultNone400InvalidOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface MultipleResponsesGetDefaultNone400NoneOptionalParams extends coreClient.OperationOptions {} /** Optional parameters. */ export interface MultipleResponsesGet200ModelA200NoneOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get200ModelA200None operation. */ export type MultipleResponsesGet200ModelA200NoneResponse = MyException; /** Optional parameters. */ export interface MultipleResponsesGet200ModelA200ValidOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get200ModelA200Valid operation. */ export type MultipleResponsesGet200ModelA200ValidResponse = MyException; /** Optional parameters. */ export interface MultipleResponsesGet200ModelA200InvalidOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get200ModelA200Invalid operation. */ export type MultipleResponsesGet200ModelA200InvalidResponse = MyException; /** Optional parameters. */ export interface MultipleResponsesGet200ModelA400NoneOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get200ModelA400None operation. */ export type MultipleResponsesGet200ModelA400NoneResponse = MyException; /** Optional parameters. */ export interface MultipleResponsesGet200ModelA400ValidOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get200ModelA400Valid operation. */ export type MultipleResponsesGet200ModelA400ValidResponse = MyException; /** Optional parameters. */ export interface MultipleResponsesGet200ModelA400InvalidOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get200ModelA400Invalid operation. */ export type MultipleResponsesGet200ModelA400InvalidResponse = MyException; /** Optional parameters. */ export interface MultipleResponsesGet200ModelA202ValidOptionalParams extends coreClient.OperationOptions {} /** Contains response data for the get200ModelA202Valid operation. */ export type MultipleResponsesGet200ModelA202ValidResponse = MyException; /** Optional parameters. */ export interface HttpInfrastructureClientOptionalParams extends coreClient.ServiceClientOptions { /** server parameter */ $host?: string; /** Overrides client endpoint. */ endpoint?: string; }
the_stack
import ITransaction from '../../src/interfaces/ITransaction'; import ISmartContract from '../../src/interfaces/ISmartContract'; import IAssociatedTxdata from '../../src/interfaces/IAssociatedTxdata'; import IDataFileTransaction from '../../src/interfaces/IDataFileTransaction'; import { ITransactionViewData } from '../../src/interfaces/IAppState'; chai.should(); interface IMessage { path: string; transactionViewData: ITransactionViewData; } describe('Transaction page', () => { const emptyTransaction: ITransaction = { name: '', parameters: [], returns: { type: '', }, tag: [], }; const transactionOne: ITransaction = { name: 'transactionOne', parameters: [{ description: '', name: 'name', schema: {} }], returns: { type: '' }, tag: ['submit'] }; const transactionTwo: ITransaction = { name: 'transactionTwo', parameters: [{ description: '', name: 'size', schema: {} }], returns: { type: '' }, tag: ['submit'] }; const greenContract: ISmartContract = { name: 'greenContract', version: '0.0.1', channel: 'mychannel', label: 'greenContract@0.0.1', transactions: [transactionOne, transactionTwo], namespace: 'GreenContract', contractName: 'GreenContract', peerNames: ['peer1', 'peer2'] }; const mockMessage: IMessage = { path: 'transaction', transactionViewData: { gatewayName: 'myGateway', smartContracts: [greenContract], preselectedSmartContract: greenContract, preselectedTransaction: emptyTransaction, associatedTxdata: {}, } }; const mockOutput: {transactionOutput: string} = { transactionOutput: 'some transaction output' }; const txdataTransactions: IDataFileTransaction[] = [{ transactionName: transactionOne.name, transactionLabel: transactionOne.name, txDataFile: '', arguments: [], transientData: {} }]; const associatedTxdata: IAssociatedTxdata = { [greenContract.name]: { channelName: 'mychannel', transactionDataPath: 'transactionDataPath', transactions: txdataTransactions, } }; beforeEach(() => { cy.visit('build/index.html').then((window: Window) => { window.postMessage(mockMessage, '*'); }); cy.get('.vscode-dark').invoke('attr', 'class', 'vscode-light'); // Use the light theme as components render properly. }); describe('Manual Input', () => { it('generates appropriate arguments when a transaction is selected', () => { cy.get('#transaction-select').contains('Select the transaction name'); cy.get('#transaction-select').click(); // Expand dropdown cy.get('#transaction-select').contains('transactionOne').click(); // Click on option cy.get('#transaction-select').contains('transactionOne'); cy.get('#arguments-text-area') .invoke('val') .then((text: JQuery<HTMLElement>): void => { expect(text).to.equal('{\n "name": ""\n}'); }); }); it('replaces generated arguments when a new transaction is selected', () => { cy.get('#transaction-select').contains('Select the transaction name'); cy.get('#transaction-select').click(); // Expand dropdown cy.get('#transaction-select').contains('transactionOne').click(); // Click on option cy.get('#transaction-select').contains('transactionOne'); cy.get('#arguments-text-area') .invoke('val') .then((text: JQuery<HTMLElement>): void => { expect(text).to.equal('{\n "name": ""\n}'); }); cy.get('#transaction-select').click(); // Expand dropdown cy.get('#transaction-select').contains('transactionTwo').click(); // Click on option cy.get('#transaction-select').contains('transactionTwo'); cy.get('#arguments-text-area') .invoke('val') .then((text: JQuery<HTMLElement>): void => { expect(text).to.equal('{\n "size": ""\n}'); }); }); it(`can submit a transaction with the user's input`, () => { cy.get('#transaction-select').contains('Select the transaction name'); cy.get('#transaction-select').click(); // Expand dropdown cy.get('#transaction-select').contains('transactionOne').click(); // Click on option cy.get('#transaction-select').contains('transactionOne'); cy.get('#arguments-text-area').type('{leftarrow}{leftarrow}{leftarrow}penguin'); cy.get('#submit-button').click(); cy.window().then((window: Window) => { window.postMessage(mockOutput, '*'); }); cy.get('.output-body').contains(mockOutput.transactionOutput); }); it(`can submit a transaction with transient data`, () => { cy.get('#transaction-select').contains('Select the transaction name'); cy.get('#transaction-select').click(); // Expand dropdown cy.get('#transaction-select').contains('transactionOne').click(); // Click on option cy.get('#transaction-select').contains('transactionOne'); cy.get('#arguments-text-area').type('{leftarrow}{leftarrow}{leftarrow}penguin'); cy.get('#transient-data-input').type('{"some": "data"}', {parseSpecialCharSequences: false}); cy.get('#submit-button').click(); cy.window().then((window: Window) => { window.postMessage(mockOutput, '*'); }); cy.get('.output-body').contains(mockOutput.transactionOutput); }); it(`can submit a transaction with custom peer`, () => { cy.get('#transaction-select').contains('Select the transaction name'); cy.get('#transaction-select').click(); // Expand dropdown cy.get('#transaction-select').contains('transactionOne').click(); // Click on option cy.get('#transaction-select').contains('transactionOne'); cy.get('#peer-select').contains('Select peers'); cy.get('#peer-select').click(); // Expand dropdown cy.get('#peer-select').contains('peer1').click(); // Click on option cy.get('#peer-select').contains('peer1'); cy.get('#peer-select').click(); // Close dropdown cy.get('#submit-button').click(); cy.window().then((window: Window) => { window.postMessage(mockOutput, '*'); }); cy.get('.output-body').contains(mockOutput.transactionOutput); }); it(`can evaluate a transaction with the user's input`, () => { cy.get('#transaction-select').contains('Select the transaction name'); cy.get('#transaction-select').click(); // Expand dropdown cy.get('#transaction-select').contains('transactionTwo').click(); // Click on option cy.get('#transaction-select').contains('transactionTwo'); cy.get('#arguments-text-area').type('{leftarrow}{leftarrow}{leftarrow}big'); cy.get('#evaluate-button').click(); cy.window().then((window: Window) => { window.postMessage(mockOutput, '*'); }); cy.get('.output-body').contains(mockOutput.transactionOutput); }); it(`can evaluate a transaction with transient data`, () => { cy.get('#transaction-select').contains('Select the transaction name'); cy.get('#transaction-select').click(); // Expand dropdown cy.get('#transaction-select').contains('transactionTwo').click(); // Click on option cy.get('#transaction-select').contains('transactionTwo'); cy.get('#arguments-text-area').type('{leftarrow}{leftarrow}{leftarrow}big'); cy.get('#transient-data-input').type('{"some": "data"}', {parseSpecialCharSequences: false}); cy.get('#evaluate-button').click(); cy.window().then((window: Window) => { window.postMessage(mockOutput, '*'); }); cy.get('.output-body').contains(mockOutput.transactionOutput); }); it(`can submit a transaction with custom peer`, () => { cy.get('#transaction-select').contains('Select the transaction name'); cy.get('#transaction-select').click(); // Expand dropdown cy.get('#transaction-select').contains('transactionOne').click(); // Click on option cy.get('#transaction-select').contains('transactionOne'); cy.get('#peer-select').contains('Select peers'); cy.get('#peer-select').click(); // Expand dropdown cy.get('#peer-select').contains('peer1').click(); // Click on option cy.get('#peer-select').contains('peer1'); cy.get('#peer-select').click(); // Close dropdown cy.get('#evaluate-button').click(); cy.window().then((window: Window) => { window.postMessage(mockOutput, '*'); }); cy.get('.output-body').contains(mockOutput.transactionOutput); }); }); describe('Data file input', () => { beforeEach(() => { cy.get('[data-testid="content-switch-data"]').click(); }); it(`can submit a transaction with custom peer when a data directory is associated`, () => { const message: IMessage = { path: mockMessage.path, transactionViewData: { ...mockMessage.transactionViewData, associatedTxdata, } }; cy.window().then((window: Window) => { window.postMessage(message, '*'); }); cy.get('#transaction-data-select').contains('Select the transaction name'); cy.get('#transaction-data-select').click(); // Expand dropdown cy.get('#transaction-data-select').contains('transactionOne').click(); // Click on option cy.get('#transaction-data-select').contains('transactionOne'); cy.get('#peer-select').contains('Select peers'); cy.get('#peer-select').click(); // Expand dropdown cy.get('#peer-select').contains('peer1').click(); // Click on option cy.get('#peer-select').contains('peer1'); cy.get('#peer-select').click(); // Close dropdown cy.get('#submit-button').click(); cy.window().then((window: Window) => { window.postMessage(mockOutput, '*'); }); cy.get('.output-body').contains(mockOutput.transactionOutput); }); it(`can evaluate a transaction with custom peer when a data directory is associated`, () => { const message: IMessage = { path: mockMessage.path, transactionViewData: { ...mockMessage.transactionViewData, associatedTxdata, } }; cy.window().then((window: Window) => { window.postMessage(message, '*'); }); cy.get('#transaction-data-select').contains('Select the transaction name'); cy.get('#transaction-data-select').click(); // Expand dropdown cy.get('#transaction-data-select').contains('transactionOne').click(); // Click on option cy.get('#transaction-data-select').contains('transactionOne'); cy.get('#peer-select').contains('Select peers'); cy.get('#peer-select').click(); // Expand dropdown cy.get('#peer-select').contains('peer1').click(); // Click on option cy.get('#peer-select').contains('peer1'); cy.get('#peer-select').click(); // Close dropdown cy.get('#evaluate-button').click(); cy.window().then((window: Window) => { window.postMessage(mockOutput, '*'); }); cy.get('.output-body').contains(mockOutput.transactionOutput); }); }); });
the_stack
import chai from 'chai'; import chaiAsPromised from 'chai-as-promised'; import extractSlides from '../src/parser/extract_slides'; const expect = chai.expect; chai.use(chaiAsPromised); describe('extractSlides', () => { describe('with a title slide', () => { const markdown = '# Title\n' + '## Subtitle\n'; const slides = extractSlides(markdown); it('should return a slide', () => { return expect(slides).to.have.length(1); }); it('should have a title', () => { console.log(slides); return expect(slides).to.have.nested.property( '[0].title.rawText', 'Title' ); }); it('should have a subtitle', () => { return expect(slides).to.have.nested.property( '[0].subtitle.rawText', 'Subtitle' ); }); it('should have empty bodies', () => { return expect(slides).to.have.nested.property('[0].bodies').empty; }); }); describe('with an empty slide', () => { const markdown = '---\n' + '\n'; ('---\n'); const slides = extractSlides(markdown); it('should return a slide', () => { return expect(slides).to.have.length(1); }); it('should have no title', () => { return expect(slides).to.not.have.nested.property('[0].title'); }); it('should have empty bodies', () => { return expect(slides).to.have.nested.property('[0].bodies').empty; }); }); describe('with a title & body slide', () => { const markdown = '# Title\n' + 'hello world\n'; const slides = extractSlides(markdown); it('should have a title', () => { return expect(slides).to.have.nested.property( '[0].title.rawText', 'Title' ); }); it('should have 1 body', () => { return expect(slides).to.have.nested.property('[0].bodies').length(1); }); it('should have body text', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].text.rawText', 'hello world\n' ); }); }); describe('with a two column slide', () => { const markdown = '# Title\n' + 'hello\n' + '\n' + '{.column}\n' + '\n' + 'world\n'; const slides = extractSlides(markdown); it('should have a title', () => { return expect(slides).to.have.nested.property( '[0].title.rawText', 'Title' ); }); it('should have 2 bodies', () => { return expect(slides).to.have.nested.property('[0].bodies').length(2); }); it('should have 1st column text', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].text.rawText', 'hello\n' ); }); it('should have 2nd column text', () => { return expect(slides).to.have.nested.property( '[0].bodies[1].text.rawText', 'world\n' ); }); }); describe('with background image', () => { const markdown = '# Title\n' + '![](https://example.com/image.jpg){.background}\n' + 'hello world\n'; const slides = extractSlides(markdown); it('should have a background image', () => { return expect(slides).to.have.nested.property( '[0].backgroundImage.url', 'https://example.com/image.jpg' ); }); }); describe('with inline images', () => { const markdown = '# Title\n' + '\n' + '![](https://example.com/image.jpg){offset-x=100 offset-y=200}\n' + 'hello world\n'; const slides = extractSlides(markdown); it('should have a background image', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].images[0].url', 'https://example.com/image.jpg' ); }); it('should have an image x offset', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].images[0].offsetX', 100 ); }); it('should have an image y offset', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].images[0].offsetY', 200 ); }); }); describe('with video', () => { const markdown = '# Title\n' + '\n' + '@[youtube](12345)\n' + 'hello world\n'; const slides = extractSlides(markdown); it('should have a video', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].videos[0].id', '12345' ); }); }); describe('with tables', () => { const markdown = '# Title\n' + '\n' + 'H1 | H2\n' + '---|---\n' + ' a | b\n' + ' c | d\n' + ' e | f\n' + '\n'; const slides = extractSlides(markdown); it('should have a table', () => { return expect(slides).to.have.nested.property('[0].tables').length(1); }); it('should have four rows', () => { return expect(slides) .to.have.nested.property('[0].tables[0].rows') .eql(4); }); it('should have two columns', () => { return expect(slides) .to.have.nested.property('[0].tables[0].columns') .eql(2); }); }); describe('with unordered lists', () => { const markdown = '# Title\n' + '* item 1\n' + '* item 2\n'; const slides = extractSlides(markdown); it('should have list markers', () => { return expect(slides) .to.have.nested.property('[0].bodies[0].text.listMarkers') .length(1); }); it('should have the correct start', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].text.listMarkers[0].start', 0 ); }); it('should have the correct end', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].text.listMarkers[0].end', 14 ); }); it('should have the correct tyoe', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].text.listMarkers[0].type', 'unordered' ); }); }); describe('with ordered lists', () => { const markdown = '# Title\n' + '1. item 1\n' + '1. item 2\n'; const slides = extractSlides(markdown); it('should have list markers', () => { return expect(slides) .to.have.nested.property('[0].bodies[0].text.listMarkers') .length(1); }); it('should have the correct start', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].text.listMarkers[0].start', 0 ); }); it('should have the correct end', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].text.listMarkers[0].end', 14 ); }); it('should have the correct type', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].text.listMarkers[0].type', 'ordered' ); }); }); describe('with text formats', () => { const markdown = '*italic*, **bold**, ~~strikethrough~~\n'; const slides = extractSlides(markdown); it('should have text runs', () => { return expect(slides) .to.have.nested.property('[0].bodies[0].text.textRuns') .length(3); }); it('should have the correct italic start', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].text.textRuns[0].start', 0 ); }); it('should have the correct italic end', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].text.textRuns[0].end', 6 ); }); it('should have the correct italic style', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].text.textRuns[0].italic', true ); }); it('should have the correct bold start', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].text.textRuns[1].start', 8 ); }); it('should have the correct bold end', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].text.textRuns[1].end', 12 ); }); it('should have the correct bold style', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].text.textRuns[1].bold', true ); }); it('should have the correct strikethrough start', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].text.textRuns[2].start', 14 ); }); it('should have the correct strikethrough end', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].text.textRuns[2].end', 27 ); }); it('should have the correct strikethrough style', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].text.textRuns[2].strikethrough', true ); }); }); describe('with emoji', () => { const markdown = ':heart:\n'; const slides = extractSlides(markdown); it('should have emoji', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].text.rawText', '❤️\n' ); }); }); describe('with markdown attributes', () => { const markdown = '*hello*{style="color: #EFEFEF; font-size: 5pt"}\n'; const slides = extractSlides(markdown); it('should have text runs', () => { return expect(slides) .to.have.nested.property('[0].bodies[0].text.textRuns') .length(1); }); it('should have the correct start', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].text.textRuns[0].start', 0 ); }); it('should have the correct end', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].text.textRuns[0].end', 5 ); }); it('should have the color style', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].text.textRuns[0].foregroundColor' ); }); it('should have the font size style', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].text.textRuns[0].fontSize' ); }); }); describe('with inline HTML span', () => { const markdown = '<span style="color: #EFEFEF; font-size: 5pt">hello</span>\n'; const slides = extractSlides(markdown); it('should have text runs', () => { return expect(slides) .to.have.nested.property('[0].bodies[0].text.textRuns') .length(1); }); it('should have the correct start', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].text.textRuns[0].start', 0 ); }); it('should have the correct end', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].text.textRuns[0].end', 5 ); }); it('should have the color style', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].text.textRuns[0].foregroundColor' ); }); it('should have the font size style', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].text.textRuns[0].fontSize' ); }); }); describe('with inline HTML subscript', () => { const markdown = 'H<sub>2</sub>O\n'; const slides = extractSlides(markdown); it('should have text runs', () => { return expect(slides) .to.have.nested.property('[0].bodies[0].text.textRuns') .length(1); }); it('should have the correct start', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].text.textRuns[0].start', 1 ); }); it('should have the correct end', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].text.textRuns[0].end', 2 ); }); it('should have the correct style', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].text.textRuns[0].baselineOffset', 'SUBSCRIPT' ); }); }); describe('with inline HTML superscript', () => { const markdown = 'Hello<sup>1</sup>\n'; const slides = extractSlides(markdown); it('should have text runs', () => { return expect(slides) .to.have.nested.property('[0].bodies[0].text.textRuns') .length(1); }); it('should have the correct start', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].text.textRuns[0].start', 5 ); }); it('should have the correct end', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].text.textRuns[0].end', 6 ); }); it('should have the correct style', () => { return expect(slides).to.have.nested.property( '[0].bodies[0].text.textRuns[0].baselineOffset', 'SUPERSCRIPT' ); }); }); describe('with speaker notes', () => { const markdown = '# Title\n' + '<!-- \n' + 'Hello **world**\n' + '\n' + '* one\n' + '* two\n' + '-->\n'; const slides = extractSlides(markdown); it('should have speaker notes', () => { return expect(slides).to.have.nested.property( '[0].notes.rawText', 'Hello world\none\ntwo\n' ); }); it('should have text runs', () => { return expect(slides) .to.have.nested.property('[0].notes.textRuns') .length(1); }); it('should have list markers', () => { return expect(slides) .to.have.nested.property('[0].notes.listMarkers') .length(1); }); }); describe('with a custom layout', () => { const markdown = '{layout="my custom layout"}\n' + '# Title\n'; const slides = extractSlides(markdown); it('should have a customLayout', () => { return expect(slides).to.have.nested.property( '[0].customLayout', 'my custom layout' ); }); }); });
the_stack
import AppDispatcher from "../../events/AppDispatcher"; import SystemLogStore from "../SystemLogStore"; import * as SystemLogTypes from "../../constants/SystemLogTypes"; import * as EventTypes from "../../constants/EventTypes"; import * as ActionTypes from "../../constants/ActionTypes"; function resetLogData(subscriptionID, newLogData) { const originalAddEntries = SystemLogStore.addEntries; // Overload addEntries to clear out log data for 'subscriptionID' SystemLogStore.addEntries = jasmine .createSpy("#addEntries") .and.returnValue(newLogData); SystemLogStore.processLogAppend(subscriptionID); // Reset addEntries to it's original functionality SystemLogStore.addEntries = originalAddEntries; } describe("SystemLogStore", () => { afterEach(() => { resetLogData("subscriptionID", null); }); describe("#addEntries", () => { it("appends data to existing data", () => { const entries = [ { fields: { MESSAGE: "foo" } }, { fields: { MESSAGE: "bar" } }, { fields: { MESSAGE: "baz" } }, ]; const logData = { entries: [ { fields: { MESSAGE: "one" } }, { fields: { MESSAGE: "two" } }, ], totalSize: 6, }; const result = SystemLogStore.addEntries( logData, entries, SystemLogTypes.APPEND ); expect(result.entries.map((entry) => entry.fields.MESSAGE)).toEqual([ "one", "two", "foo", "bar", "baz", ]); expect(result.totalSize).toEqual(15); }); it("doesn't remove when there is no length added", () => { const entires = [ { fields: { MESSAGE: "" } }, { fields: { MESSAGE: "" } }, { fields: { MESSAGE: "" } }, ]; const logData = { entries: [ { fields: { MESSAGE: "one" } }, { fields: { MESSAGE: "two" } }, ], // Allow room for one more entry, but not the two following totalSize: 500000, }; const result = SystemLogStore.addEntries( logData, entires, SystemLogTypes.APPEND ); const entries = result.entries.map((entry) => entry.fields.MESSAGE); expect(entries).toEqual(["one", "two", "", "", ""]); expect(result.totalSize).toEqual(500000); }); it("prepends data to existing data", () => { const entires = [ { fields: { MESSAGE: "foo" } }, { fields: { MESSAGE: "bar" } }, { fields: { MESSAGE: "baz" } }, ]; const logData = { entries: [ { fields: { MESSAGE: "one" } }, { fields: { MESSAGE: "two" } }, ], totalSize: 6, }; const result = SystemLogStore.addEntries( logData, entires, SystemLogTypes.PREPEND ); const entries = result.entries.map((entry) => entry.fields.MESSAGE); expect(entries).toEqual(["foo", "bar", "baz", "one", "two"]); expect(result.totalSize).toEqual(15); }); it("doesn't remove when there is no length added", () => { const entries = [ { fields: { MESSAGE: "" } }, { fields: { MESSAGE: "" } }, { fields: { MESSAGE: "" } }, ]; const logData = { entries: [ { fields: { MESSAGE: "one" } }, { fields: { MESSAGE: "two" } }, ], // Allow room for one more entry, but not the two following totalSize: 500000, }; const result = SystemLogStore.addEntries( logData, entries, SystemLogTypes.PREPEND ); expect(result.entries.map((entry) => entry.fields.MESSAGE)).toEqual([ "", "", "", "one", "two", ]); expect(result.totalSize).toEqual(500000); }); }); describe("#processLogAppend", () => { it("appends data to existing data", () => { resetLogData("subscriptionID", { entries: [ { fields: { MESSAGE: "one" } }, { fields: { MESSAGE: "two" } }, ], totalSize: 6, }); SystemLogStore.processLogAppend("subscriptionID", [ { fields: { MESSAGE: "foo" } }, ]); SystemLogStore.processLogAppend("subscriptionID", [ { fields: { MESSAGE: "bar" } }, ]); SystemLogStore.processLogAppend("subscriptionID", [ { fields: { MESSAGE: "baz" } }, ]); expect(SystemLogStore.getFullLog("subscriptionID")).toEqual( "one\ntwo\nfoo\nbar\nbaz" ); }); it("doesn't add empty MESSAGEs", () => { resetLogData("subscriptionID", { entries: [ { fields: { MESSAGE: "one" } }, { fields: { MESSAGE: "two" } }, ], // Allow room for one more entry, but not the two following totalSize: 500000, }); SystemLogStore.processLogAppend("subscriptionID", [ { fields: { MESSAGE: "" } }, ]); SystemLogStore.processLogAppend("subscriptionID", [ { fields: { MESSAGE: "" } }, ]); SystemLogStore.processLogAppend("subscriptionID", [ { fields: { MESSAGE: "" } }, ]); expect(SystemLogStore.getFullLog("subscriptionID")).toEqual("one\ntwo"); }); }); describe("#processLogPrepend", () => { it("prepends data to existing data", () => { resetLogData("subscriptionID", { entries: [ { fields: { MESSAGE: "one" } }, { fields: { MESSAGE: "two" } }, ], totalSize: 6, }); SystemLogStore.processLogPrepend("subscriptionID", false, [ { fields: { MESSAGE: "foo" } }, { fields: { MESSAGE: "bar" } }, { fields: { MESSAGE: "baz" } }, ]); expect(SystemLogStore.getFullLog("subscriptionID")).toEqual( "foo\nbar\nbaz\none\ntwo" ); }); it("doesn't remove when there is no length added", () => { resetLogData("subscriptionID", { entries: [ { fields: { MESSAGE: "one" } }, { fields: { MESSAGE: "two" } }, ], // Allow room for one more entry, but not the two following totalSize: 500000, }); SystemLogStore.processLogPrepend("subscriptionID", false, [ { fields: { MESSAGE: "" } }, { fields: { MESSAGE: "" } }, { fields: { MESSAGE: "" } }, ]); expect(SystemLogStore.getFullLog("subscriptionID")).toEqual("one\ntwo"); }); }); describe("#getFullLog", () => { it("returns full log", () => { SystemLogStore.processLogAppend("subscriptionID", [ { fields: { MESSAGE: "foo" } }, ]); SystemLogStore.processLogAppend("subscriptionID", [ { fields: { MESSAGE: "bar" } }, ]); SystemLogStore.processLogAppend("subscriptionID", [ { fields: { MESSAGE: "baz" } }, ]); const result = SystemLogStore.getFullLog("subscriptionID"); expect(result).toEqual("foo\nbar\nbaz"); }); it("returns correct format", () => { SystemLogStore.processLogAppend("subscriptionID", [ { fields: { MESSAGE: "foo" }, realtime_timestamp: 10000000 }, ]); SystemLogStore.processLogAppend("subscriptionID", [ { fields: { MESSAGE: "bar" } }, ]); const result = SystemLogStore.getFullLog("subscriptionID"); expect(result).toEqual("1970-01-01 12:00:10: foo\nbar"); }); it("returns empty string for a log that doesn't exist", () => { const result = SystemLogStore.getFullLog("subscriptionID"); expect(result).toEqual(""); }); }); describe("storeID", () => { it("returns 'systemLog'", () => { expect(SystemLogStore.storeID).toEqual("systemLog"); }); }); describe("dispatcher", () => { it("emits event after #processLogAppend event is dispatched", () => { const changeHandler = jasmine.createSpy("changeHandler"); SystemLogStore.addChangeListener( EventTypes.SYSTEM_LOG_CHANGE, changeHandler ); AppDispatcher.handleServerAction({ type: ActionTypes.REQUEST_SYSTEM_LOG_SUCCESS, data: [{ fields: { MESSAGE: "foo" } }], subscriptionID: "subscriptionID", }); expect(changeHandler).toHaveBeenCalledWith( "subscriptionID", SystemLogTypes.APPEND ); }); it("emits event after #processLogError event is dispatched", () => { const changeHandler = jasmine.createSpy("changeHandler"); SystemLogStore.addChangeListener( EventTypes.SYSTEM_LOG_REQUEST_ERROR, changeHandler ); AppDispatcher.handleServerAction({ type: ActionTypes.REQUEST_SYSTEM_LOG_ERROR, data: { error: "foo" }, subscriptionID: "subscriptionID", }); expect(changeHandler).toHaveBeenCalledWith( "subscriptionID", SystemLogTypes.APPEND, { error: "foo", } ); }); it("emits event after #processLogPrepend event is dispatched", () => { const changeHandler = jasmine.createSpy("changeHandler"); SystemLogStore.addChangeListener( EventTypes.SYSTEM_LOG_CHANGE, changeHandler ); AppDispatcher.handleServerAction({ type: ActionTypes.REQUEST_PREVIOUS_SYSTEM_LOG_SUCCESS, data: [{ fields: { MESSAGE: "foo" } }], firstEntry: false, subscriptionID: "subscriptionID", }); expect(changeHandler).toHaveBeenCalledWith( "subscriptionID", SystemLogTypes.PREPEND ); }); it("emits event after #processLogPrependError event is dispatched", () => { const changeHandler = jasmine.createSpy("changeHandler"); SystemLogStore.addChangeListener( EventTypes.SYSTEM_LOG_REQUEST_ERROR, changeHandler ); AppDispatcher.handleServerAction({ type: ActionTypes.REQUEST_SYSTEM_LOG_ERROR, data: { error: "foo" }, subscriptionID: "subscriptionID", }); expect(changeHandler).toHaveBeenCalledWith( "subscriptionID", SystemLogTypes.APPEND, { error: "foo", } ); }); }); });
the_stack
import { assert } from 'chai'; import { addStage, Konva, simulateMouseDown, simulateMouseMove, simulateMouseUp, } from './test-utils'; describe('DragAndDropEvents', function () { // ====================================================== it('test dragstart, dragmove, dragend', function (done) { var stage = addStage(); var layer = new Konva.Layer(); var greenCircle = new Konva.Circle({ x: 40, y: 40, radius: 20, strokeWidth: 4, fill: 'green', stroke: 'black', opacity: 0.5, }); var circle = new Konva.Circle({ x: 380, y: stage.height() / 2, radius: 70, strokeWidth: 4, fill: 'red', stroke: 'black', opacity: 0.5, }); circle.setDraggable(true); layer.add(circle); layer.add(greenCircle); stage.add(layer); var dragStart = false; var dragMove = false; var dragEnd = false; var events = []; circle.on('dragstart', function () { dragStart = true; }); circle.on('dragmove', function () { dragMove = true; }); circle.on('dragend', function () { dragEnd = true; events.push('dragend'); }); circle.on('mouseup', function () { events.push('mouseup'); }); assert(!Konva.isDragging(), ' isDragging() should be false 1'); assert(!Konva.isDragReady(), ' isDragReady()) should be false 2'); /* * simulate drag and drop */ simulateMouseDown(stage, { x: 380, y: 98, }); assert(!dragStart, 'dragstart event should not have been triggered 3'); //assert.equal(!dragMove, 'dragmove event should not have been triggered'); assert(!dragEnd, 'dragend event should not have been triggered 4'); assert(!Konva.isDragging(), ' isDragging() should be false 5'); assert(Konva.isDragReady(), ' isDragReady()) should be true 6'); setTimeout(function () { simulateMouseMove(stage, { x: 385, y: 98, }); assert(Konva.isDragging(), ' isDragging() should be true 7'); assert(Konva.isDragReady(), ' isDragReady()) should be true 8'); assert(dragStart, 'dragstart event was not triggered 9'); //assert.equal(dragMove, 'dragmove event was not triggered'); assert(!dragEnd, 'dragend event should not have been triggered 10'); simulateMouseUp(stage, { x: 385, y: 98, }); assert(dragStart, 'dragstart event was not triggered 11'); assert(dragMove, 'dragmove event was not triggered 12'); assert(dragEnd, 'dragend event was not triggered 13'); assert.equal( events.toString(), 'mouseup,dragend', 'mouseup should occur before dragend 14' ); assert(!Konva.isDragging(), ' isDragging() should be false 15'); assert(!Konva.isDragReady(), ' isDragReady()) should be false 16'); //console.log(greenCircle.getPosition()); //console.log(circle.getPosition()); assert.equal(greenCircle.x(), 40, 'green circle x should be 40'); assert.equal(greenCircle.y(), 40, 'green circle y should be 40'); assert.equal(circle.x(), 385, 'circle x should be 100'); assert.equal(circle.y(), 100, 'circle y should be 100'); done(); }, 20); }); // ====================================================== it('destroy shape while dragging', function (done) { var stage = addStage(); var layer = new Konva.Layer(); var greenCircle = new Konva.Circle({ x: 40, y: 40, radius: 20, strokeWidth: 4, fill: 'green', stroke: 'black', opacity: 0.5, }); var circle = new Konva.Circle({ x: 380, y: stage.height() / 2, radius: 70, strokeWidth: 4, fill: 'red', stroke: 'black', opacity: 0.5, }); circle.setDraggable(true); layer.add(circle); layer.add(greenCircle); stage.add(layer); var dragEnd = false; circle.on('dragend', function () { dragEnd = true; }); assert(!Konva.isDragging(), ' isDragging() should be false'); assert(!Konva.isDragReady(), ' isDragReady()) should be false'); simulateMouseDown(stage, { x: 380, y: 98, }); assert(!circle.isDragging(), 'circle should not be dragging'); setTimeout(function () { simulateMouseMove(stage, { x: 100, y: 98, }); assert(circle.isDragging(), 'circle should be dragging'); assert(!dragEnd, 'dragEnd should not have fired yet'); // at this point, we are in drag and drop mode // removing or destroying the circle should trigger dragend circle.destroy(); layer.draw(); assert( !circle.isDragging(), 'destroying circle should stop drag and drop' ); assert(dragEnd, 'dragEnd should have fired'); done(); }, 20); }); // ====================================================== it('click should not occur after drag and drop', function (done) { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ x: 40, y: 40, radius: 20, strokeWidth: 4, fill: 'green', stroke: 'black', draggable: true, }); layer.add(circle); stage.add(layer); var clicked = false; circle.on('click', function () { //console.log('click'); clicked = true; }); circle.on('dblclick', function () { //console.log('dblclick'); }); simulateMouseDown(stage, { x: 40, y: 40, }); setTimeout(function () { simulateMouseMove(stage, { x: 100, y: 100, }); simulateMouseUp(stage, { x: 100, y: 100, }); assert(!clicked, 'click event should not have been fired'); done(); }, 20); }); // ====================================================== it('drag and drop distance', function (done) { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ x: 40, y: 40, radius: 20, strokeWidth: 4, fill: 'green', stroke: 'black', draggable: true, }); layer.add(circle); stage.add(layer); circle.dragDistance(4); simulateMouseDown(stage, { x: 40, y: 40, }); setTimeout(function () { simulateMouseMove(stage, { x: 40, y: 42, }); assert(!circle.isDragging(), 'still not dragging'); simulateMouseMove(stage, { x: 40, y: 45, }); assert(circle.isDragging(), 'now circle is dragging'); simulateMouseUp(stage, { x: 41, y: 45, }); done(); }, 20); }); // ====================================================== it('cancel drag and drop by setting draggable to false', function (done) { var stage = addStage(); var layer = new Konva.Layer(); var circle = new Konva.Circle({ x: 380, y: 100, radius: 70, strokeWidth: 4, fill: 'red', stroke: 'black', draggable: true, }); var dragStart = false; var dragMove = false; var dragEnd = false; circle.on('dragstart', function () { dragStart = true; }); circle.on('dragmove', function () { dragMove = true; }); circle.on('dragend', function () { dragEnd = true; }); circle.on('mousedown', function () { circle.setDraggable(false); }); layer.add(circle); stage.add(layer); /* * simulate drag and drop */ simulateMouseDown(stage, { x: 380, y: 100, }); setTimeout(function () { simulateMouseMove(stage, { x: 100, y: 100, }); simulateMouseUp(stage, { x: 100, y: 100, }); assert.equal(circle.getPosition().x, 380, 'circle x should be 380'); assert.equal(circle.getPosition().y, 100, 'circle y should be 100'); done(); }, 20); }); // ====================================================== it('drag and drop layer', function (done) { var stage = addStage(); var layer = new Konva.Layer({ sceneFunc: function () { var context = this.getContext(); context.beginPath(); context.moveTo(200, 50); context.lineTo(420, 80); context.quadraticCurveTo(300, 100, 260, 170); context.closePath(); context.fillStyle = 'blue'; context.fill(context); }, draggable: true, }); var circle1 = new Konva.Circle({ x: stage.width() / 2, y: stage.height() / 2, radius: 70, fill: 'red', }); var circle2 = new Konva.Circle({ x: 400, y: stage.height() / 2, radius: 70, fill: 'green', }); layer.add(circle1); layer.add(circle2); stage.add(layer); /* * simulate drag and drop */ simulateMouseDown(stage, { x: 399, y: 96, }); setTimeout(function () { simulateMouseMove(stage, { x: 210, y: 109, }); simulateMouseUp(stage, { x: 210, y: 109, }); //console.log(layer.getPosition()) assert.equal(layer.x(), -189, 'layer x should be -189'); assert.equal(layer.y(), 13, 'layer y should be 13'); done(); }, 20); }); // ====================================================== it('drag and drop stage', function (done) { var stage = addStage({ draggable: true }); //stage.setDraggable(true); var layer = new Konva.Layer(); var circle = new Konva.Circle({ x: 100, y: 100, radius: 70, fill: 'red', }); layer.add(circle); stage.add(layer); assert.equal(stage.x(), 0); assert.equal(stage.y(), 0); /* * simulate drag and drop */ simulateMouseDown(stage, { x: 0, y: 100, }); setTimeout(function () { simulateMouseMove(stage, { x: 300, y: 110, }); simulateMouseUp(stage, { x: 300, y: 110, }); assert.equal(stage.x(), 300); assert.equal(stage.y(), 10); done(); }, 20); }); it('click should not start drag&drop', function () { var stage = addStage(); var layer = new Konva.Layer({ draggable: true, }); var circle = new Konva.Circle({ x: 70, y: 70, radius: 70, fill: 'green', stroke: 'black', strokeWidth: 4, name: 'myCircle', draggable: true, }); layer.add(circle); stage.add(layer); var dragstart = 0; circle.on('dragstart', function () { dragstart += 1; }); var dragmove = 0; circle.on('dragmove', function () { dragmove += 1; }); var dragend = 0; circle.on('dragend', function () { dragend += 1; }); var click = 0; circle.on('click', function () { click += 1; }); simulateMouseDown(stage, { x: 70, y: 70 }); simulateMouseUp(stage, { x: 70, y: 70 }); assert.equal(click, 1, 'click triggered'); assert.equal(dragstart, 0, 'dragstart not triggered'); assert.equal(dragmove, 0, 'dragmove not triggered'); assert.equal(dragend, 0, 'dragend not triggered'); }); it('drag&drop should not fire click', function () { var stage = addStage(); var layer = new Konva.Layer({ draggable: true, }); var circle = new Konva.Circle({ x: 70, y: 70, radius: 70, fill: 'green', stroke: 'black', strokeWidth: 4, name: 'myCircle', draggable: true, }); layer.add(circle); stage.add(layer); var dragstart = 0; circle.on('dragstart', function () { dragstart += 1; }); var dragmove = 0; circle.on('dragmove', function () { dragmove += 1; }); var dragend = 0; circle.on('dragend', function () { dragend += 1; }); var click = 0; circle.on('click', function () { click += 1; }); simulateMouseDown(stage, { x: 70, y: 70 }); simulateMouseMove(stage, { x: 80, y: 80 }); simulateMouseUp(stage, { x: 80, y: 80 }); assert.equal(click, 0, 'click triggered'); assert.equal(dragstart, 1, 'dragstart not triggered'); assert.equal(dragmove, 1, 'dragmove not triggered'); assert.equal(dragend, 1, 'dragend not triggered'); }); it('drag events should not trigger on a click even if we stop drag on dragstart', function () { var stage = addStage(); var layer = new Konva.Layer({ draggable: true, }); var circle = new Konva.Circle({ x: 70, y: 70, radius: 70, fill: 'green', stroke: 'black', strokeWidth: 4, name: 'myCircle', draggable: true, }); layer.add(circle); stage.add(layer); var dragstart = 0; circle.on('dragstart', function () { circle.stopDrag(); dragstart += 1; }); var dragmove = 0; circle.on('dragmove', function () { dragmove += 1; }); var dragend = 0; circle.on('dragend', function () { dragend += 1; }); var click = 0; circle.on('click', function () { click += 1; }); simulateMouseDown(stage, { x: 70, y: 70 }); simulateMouseMove(stage, { x: 75, y: 75 }); simulateMouseUp(stage, { x: 75, y: 75 }); assert.equal(click, 0, 'click triggered'); assert.equal(dragstart, 1, 'dragstart triggered'); assert.equal(dragmove, 0, 'dragmove not triggered'); assert.equal(dragend, 1, 'dragend triggered'); }); });
the_stack
import { UserColumn } from './userColumn'; import { GeoPackageDataType } from '../db/geoPackageDataType'; export class UserColumns<TColumn extends UserColumn> { /** * Table name, null when a pre-ordered subset of columns for a query */ _tableName: string; /** * Array of column names */ _columnNames: string[]; /** * List of columns */ _columns: TColumn[]; /** * Custom column specification flag (subset of table columns or different * ordering) */ _custom: boolean; /** * Mapping between (lower cased) column names and their index */ _nameToIndex: Map<string, number>; /** * Primary key column index */ _pkIndex: number = -1; /** * Constructor * @param tableName table name * @param columns columns * @param custom custom column specification */ protected constructor(tableName: string, columns: TColumn[], custom: boolean = false) { this._tableName = tableName; this._columns = columns; this._custom = custom; this._nameToIndex = new Map<string, number>(); this._columnNames = []; } /** * Copy the user columns * @return copied user columns */ copy(): UserColumns<TColumn> { const columns = []; this._columns.forEach(column => { columns.push(column.copy()); }); const copy = new UserColumns<TColumn>(this._tableName, columns, this._custom); copy._columnNames = Array.from(this._columnNames); copy._nameToIndex = new Map<string, number>(this._nameToIndex); copy._pkIndex = this._pkIndex; return copy; } /** * Update the table columns */ updateColumns() { this._nameToIndex.clear(); if (!this._custom) { const indices = new Set<number>(); // Check for missing indices and duplicates let needsIndex = []; this._columns.forEach(column => { if (column.hasIndex()) { const index = column.getIndex(); if (indices.has(index)) { throw new Error("Duplicate index: " + index + ", Table Name: " + this._tableName); } else { indices.add(index); } } else { needsIndex.push(column); } }); // Update columns that need an index let currentIndex = -1; needsIndex.forEach(column => { while (indices.has(++currentIndex)) { } column.setIndex(currentIndex); }); // Sort the columns by index this._columns.sort((a, b) => { return a.index - b.index; }); } this._pkIndex = -1; this._columnNames = []; for (let index = 0; index < this._columns.length; index++) { const column = this._columns[index]; const columnName = column.getName(); const lowerCaseColumnName = columnName.toLowerCase(); if (!this._custom) { if (column.getIndex() != index) { throw new Error("No column found at index: " + index + ", Table Name: " + this._tableName); } if (this._nameToIndex.has(lowerCaseColumnName)) { throw new Error( 'Duplicate column found at index: ' + index + ', Table Name: ' + this._tableName + ', Name: ' + columnName); } } if (column.isPrimaryKey()) { if (this._pkIndex != -1) { let error = 'More than one primary key column was found for '; if (this._custom) { error = error.concat('custom specified table columns'); } else { error = error.concat('table'); } error = error.concat('. table: ' + this._tableName + ', index1: ' + this._pkIndex + ', index2: ' + index); if (this._custom) { error = error.concat(', columns: ' + this._columnNames); } throw new Error(error); } this._pkIndex = index; } this._columnNames[index] = columnName; this._nameToIndex.set(lowerCaseColumnName, index); } } /** * Check for duplicate column names * * @param index index * @param previousIndex previous index * @param column column */ duplicateCheck(index: number, previousIndex: number, column: string) { if (previousIndex !== null && previousIndex !== undefined) { throw new Error('More than one ' + column + ' column was found for table \'' + this._tableName + '\'. Index ' + previousIndex + ' and ' + index); } } /** * Check for the expected data type * @param expected expected data type * @param column user column */ typeCheck(expected: GeoPackageDataType, column: TColumn) { const actual = column.getDataType(); if (actual === null || actual === undefined || actual !== expected) { throw new Error('Unexpected ' + column.getName() + ' column data type was found for table \'' + this._tableName + '\', expected: ' + GeoPackageDataType.nameFromType(expected) + ', actual: ' + (actual !== null && actual !== undefined ? GeoPackageDataType.nameFromType(actual) : 'null')); } } /** * Check for missing columns * @param index column index * @param column user column */ missingCheck(index: number, column: string) { if (index === null || index === undefined) { throw new Error('No ' + column + ' column was found for table \'' + this._tableName + '\''); } } /** * Get the column index of the column name * @param columnName column name * @return column index */ getColumnIndexForColumnName(columnName: string): number { return this.getColumnIndex(columnName, true); } /** * Get the column index of the column name * @param columnName column name * @param required column existence is required * @return column index */ getColumnIndex(columnName: string, required: boolean): number { let index = this._nameToIndex.get(columnName.toLowerCase()); if (required && (index === null || index === undefined)) { let error = 'Column does not exist in '; if (this._custom) { error = error.concat('custom specified table columns'); } else { error = error.concat('table'); } error = error.concat('. table: ' + this._tableName + ', column: ' + columnName); if (this._custom) { error = error.concat(', columns: ' + this._columnNames); } throw new Error(error); } return index; } /** * Get the array of column names * @return column names */ getColumnNames(): string[] { return this._columnNames; } /** * Get the column name at the index * @param index column index * @return column name */ getColumnName(index: number): string { return this._columnNames[index]; } /** * Get the list of columns * @return columns */ getColumns(): TColumn[] { return this._columns; } /** * Get the column at the index * @param index column index * @return column */ getColumnForIndex(index: number): TColumn { return this._columns[index]; } /** * Get the column of the column name * @param columnName column name * @return column */ getColumn(columnName: string): TColumn { return this.getColumnForIndex(this.getColumnIndexForColumnName(columnName)); } /** * Check if the table has the column * @param columnName column name * @return true if has the column */ hasColumn(columnName: string): boolean { return this._nameToIndex.has(columnName.toLowerCase()); } /** * Get the column count * @return column count */ columnCount(): number { return this._columns.length; } /** * Get the table name * @return table name */ getTableName(): string { return this._tableName; } /** * Set the table name * @param tableName table name */ setTableName(tableName: string) { this._tableName = tableName; } /** * Is custom column specification (partial and/or ordering) * @return custom flag */ isCustom(): boolean { return this._custom; } /** * Set the custom column specification flag * @param custom custom flag */ setCustom(custom: boolean) { this._custom = custom; } /** * Check if the table has a primary key column * @return true if has a primary key */ hasPkColumn(): boolean { return this._pkIndex >= 0; } /** * Get the primary key column index * @return primary key column index */ getPkColumnIndex(): number { return this._pkIndex; } /** * Get the primary key column * @return primary key column */ getPkColumn(): TColumn { let column = null; if (this.hasPkColumn()) { column = this._columns[this._pkIndex]; } return column; } /** * Get the primary key column name * @return primary key column name */ getPkColumnName(): string { return this.getPkColumn().getName(); } /** * Get the columns with the provided data type * @param type data type * @return columns */ columnsOfType(type: GeoPackageDataType): TColumn[] { return this._columns.filter(column => column.getDataType() === type); } /** * Add a new column * @param column new column */ addColumn(column: TColumn) { this._columns.push(column); this.updateColumns(); } /** * Rename a column * @param column column * @param newColumnName new column name */ renameColumn(column: TColumn, newColumnName: string) { this.renameColumnWithName(column.getName(), newColumnName); column.setName(newColumnName); } /** * Rename a column * @param columnName column name * @param newColumnName new column name */ renameColumnWithName(columnName: string, newColumnName: string) { this.renameColumnWithIndex(this.getColumnIndexForColumnName(columnName), newColumnName); } /** * Rename a column * @param index column index * @param newColumnName new column name */ renameColumnWithIndex(index: number, newColumnName: string) { this._columns[index].setName(newColumnName); this.updateColumns(); } /** * Drop a column * @param column column to drop */ dropColumn(column: TColumn) { this.dropColumnWithIndex(column.getIndex()); } /** * Drop a column * @param columnName column name */ dropColumnWithName(columnName: string) { this.dropColumnWithIndex(this.getColumnIndexForColumnName(columnName)); } /** * Drop a column * @param index column index */ dropColumnWithIndex(index: number) { this._columns.splice(index, 1); this._columns.forEach(column => column.resetIndex()); this.updateColumns(); } /** * Alter a column * @param column altered column */ alterColumn(column: TColumn) { let existingColumn = this.getColumn(column.getName()); const index = existingColumn.getIndex(); column.setIndex(index); this._columns[index] = column; } }
the_stack
import React, { FunctionComponent, useState, useEffect } from 'react'; import ReactFlow, { removeElements, addEdge, MiniMap, Controls, Background, isNode, } from 'react-flow-renderer'; import dagre from 'dagre'; import { Button, Menu, MenuItem } from '@material-ui/core/'; import { elements, recoilObj } from '../types'; import {useRecoilValue, useRecoilState} from 'recoil' import { checkChild, createNewObj } from '../FiberParsingAlgo'; import atoms from '../atoms'; // Component that displays list of atoms as buttons const AtomDisplay : FunctionComponent = (props: any) => { return ( <div> <MenuItem value={props.atom} onClick={props.getAtomToHighlight}> {props.atom} </MenuItem> </div> ) } // Component that displays list of selectors as buttons const SelectorDisplay : FunctionComponent = (props: any) => { return ( <div> <MenuItem value={props.selector} onClick={props.getSelectorToHighlight}> {props.selector} </MenuItem> </div> ) } // Component that displays component tree using React Flow const ComponentTree = () => { const nodeData = useRecoilValue(atoms.reactState) const logData: recoilObj = useRecoilValue(atoms.recoilObj) const [elements, setElements] = useState([]); const onElementsRemove = (elementsToRemove: any) => setElements((els: any) => removeElements(elementsToRemove, els)); const onConnect = (params: any) => setElements((els: any) => addEdge(params, els)); const flowStyles = { width: '100%', height: 700, border: 'solid 1px black' }; // Returns object with name of component and which atom/selector it is subscribed to const getSubscriptions = (arr: any[], components: any = []) => { arr?.forEach((obj: any) => { if(obj.recoilNode) { if (obj.recoilNode.atomSelector[0]) { const objOfRecoilStates: any = {}; objOfRecoilStates.component= obj.name; objOfRecoilStates.recoilState = createNewObj(obj.recoilNode.atomSelector); components.push(objOfRecoilStates) } } getSubscriptions(obj.children, components); }); return components; } const subscriptions = getSubscriptions([nodeData]); // Iterating through each atom/selector in subscriptions object and adding additional data: updated, isAtom, isSelector for (let i = 0; i < subscriptions.length; i += 1) { for (let j = 0; j < subscriptions[i].recoilState.length; j += 1) { const curAtomSelectorObject = subscriptions[i].recoilState[j] if (!curAtomSelectorObject.hasOwnProperty('updated')) { curAtomSelectorObject.updated = false; } if (logData.knownAtoms.includes(curAtomSelectorObject.key)) { curAtomSelectorObject.isAtom = true; } if (logData.knownSelectors.includes(curAtomSelectorObject.key)) { curAtomSelectorObject.isSelector = true; } logData.atomSelectorValuesNonDefault.forEach(el => { if(curAtomSelectorObject.key === el.key && el.updated) { curAtomSelectorObject.updated = true; } }) } } // Highlights which component is subscribed to the selected atom on button click const getAtomToHighlight = (e: any) => { subscriptions.forEach((obj: any) => { if(e.target.getAttribute("value")===obj.recoilState[0].key){ setElements((els: any) => els.map((el: any) => { if (el.data?.label===obj.component){ if (el.style?.background) el.style.background = '#EBDEF0'; } return el; }) ); } }); } // Highlights which component is subscribed to the selected selector on button click const getSelectorToHighlight = (e: any) => { subscriptions.forEach((obj: any) => { if(e.target.getAttribute("value")===obj.recoilState[0].key){ setElements((els: any) => els.map((el: any) => { if (el.data?.label===obj.component){ if (el.style?.background) el.style.background = '#FADBD8'; } return el; }) ); } }); } // Iterates through node data and creates elements for React Flow nodes const createNodes = (arr: any[], arrayOfElements: any = [], numOfComponents: any = [0]) => { arr?.forEach((obj) => { if (obj.name) { numOfComponents[0] += 1 const newElements: elements = { id: '', type: null, data: {}, position: {}, children: [], style: { background: '#fff', border: 'solid 1px #777', }, }; newElements.type = 'input'; newElements.id = numOfComponents[0].toString(); newElements.data = { label: obj.name, }; newElements.position = { x: 250, y: 50 * numOfComponents }; newElements.children.push(obj.children) arrayOfElements.push(newElements); } createNodes(obj.children, arrayOfElements, numOfComponents); }); return arrayOfElements; } // Iterates through node data and creates elements for React Flow edges const createEdges = (treeData: any) => { // Iterate through the tree data and make sure child is present before linking for (let i = treeData.length -1 ; i >= 0 ; i -= 1) { const curTreeNode = treeData[i]; // Assign a pointer to check all other components let j = i - 1; while (j >=0) { if (checkChild(curTreeNode, treeData[j]) ) { const newLink = { id: '', source: '', target: '', type: 'smoothstep', animated: true }; newLink.id = `e${j + 1}-${i + 1}`; newLink.source = treeData[j]?.id; newLink.target = curTreeNode?.id; components.push(newLink); break; } j -= 1 } } } // Call functions to create nodes and edges const components: any = createNodes([nodeData]); if(components) { createEdges(components); } // Use dagre to position component tree const nodeWidth = 172; const nodeHeight = 36; const dagreGraph = new dagre.graphlib.Graph(); dagreGraph.setDefaultEdgeLabel(() => ({})); // Set graph, nodes, and edges const getLayoutedElements = (elements: any, direction = 'TB') => { dagreGraph.setGraph({ rankdir: direction }); elements.forEach((el: any) => { if (isNode(el)) { dagreGraph.setNode(el.id, { width: nodeWidth, height: nodeHeight }); } else { dagreGraph.setEdge(el.source, el.target); } }); dagre.layout(dagreGraph); // Positioning vertically/top to bottom return elements.map((el: any) => { if (isNode(el)) { const nodeWithPosition = dagreGraph.node(el.id); el.targetPosition = 'top'; el.sourcePosition = 'bottom'; el.position = { x: nodeWithPosition.x - nodeWidth / 2 + Math.random() / 1000, y: nodeWithPosition.y - nodeHeight / 2, }; } return el; }); }; const layoutedElements = getLayoutedElements(components); // Set elements, run when nodeData changes from previous render useEffect(() => { setElements(layoutedElements) }, [nodeData]); // Set elements' border - highlight which component was updated, run when logdata changes from previous render useEffect(() => { for (let i = 0; i < subscriptions.length; i += 1) { for (let j = 0; j < subscriptions[i].recoilState.length; j += 1) { const curAtomSelectorObject = subscriptions[i].recoilState[j] if (curAtomSelectorObject.updated) { setElements((els) => els.map((el) => { if (el.data?.label===subscriptions[i].component) { el.style = { ...el.style, border: 'solid 2px red' }; } return el; }) ); } } } }, [logData]); const [atomAnchorEl, setAtomAnchorEl] = useState(null); const [selectorAnchorEl, setSelectorAnchorEl] = useState(null); const atomMenuHandleClick = (event) => { setAtomAnchorEl(event.target); }; const atomMenuHandleClose = () => { setAtomAnchorEl(null); }; const selectorMenuHandleClick = (event) => { setSelectorAnchorEl(event.target); }; const selectorMenuHandleClose = () => { setSelectorAnchorEl(null); }; // Iterate through knownAtoms array and push AtomDisplay component into displayAtoms array for every atom const displayAtoms: any = []; for (let i = 0; i < logData.knownAtoms?.length; i += 1) { displayAtoms.push(<AtomDisplay atom={logData.knownAtoms[i]} key={i} getAtomToHighlight={getAtomToHighlight}/>) } // Iterate through knownSelectors array and push AtomDisplay component into displaySelectors array for every selector const displaySelectors: any = []; for (let i = 0; i < logData.knownSelectors?.length; i += 1) { displaySelectors.push(<SelectorDisplay selector={logData.knownSelectors[i]} key={i} getSelectorToHighlight={getSelectorToHighlight}/>) } return ( <> <div id="flow-pad"> <div id='component-tree-tag'> <h3>Component Tree</h3> </div> {/* Atom/Selector Menu */} <div className="atomSelectMenus"> <Button aria-controls="simple-menu" aria-haspopup="true" onClick={atomMenuHandleClick}> Atoms </Button> <Menu id="atomMenu" anchorEl={atomAnchorEl} keepMounted open={Boolean(atomAnchorEl)} onClose={atomMenuHandleClose} > {displayAtoms} </Menu> <Button aria-controls="simple-menu" aria-haspopup="true" onClick={selectorMenuHandleClick}> Selectors </Button> <Menu id="selectorMenu" anchorEl={selectorAnchorEl} keepMounted open={Boolean(selectorAnchorEl)} onClose={selectorMenuHandleClose} > {displaySelectors} </Menu> </div> {/* React Flow component */} <ReactFlow elements={elements} onElementsRemove={onElementsRemove} onConnect={onConnect} snapToGrid snapGrid={[15, 15]} style={flowStyles} > {/* Mini Map Component */} <MiniMap nodeStrokeColor={(n: any) => { if (n.type === 'input') return '#0041d0'; if (n.type === 'output') return '#ff0072'; if (n.type === 'default') return '#1a192b'; return '#eee'; } } nodeColor={(n: any) => { if (n.style?.background) return n.style.background; return '#fff'; } } nodeBorderRadius={2} /> {/* Controls Component */} <Controls /> <Background color="#aaa" gap={16} /> </ReactFlow> </div> </> ); }; export default ComponentTree;
the_stack
import {Component, Injector, OnInit} from '@angular/core'; import {SideConfiguration} from 'projects/workspaces/src/lib/side-configuration'; import {ComponentPortal} from '@angular/cdk/portal'; import {IconFa} from 'projects/icon/src/lib/icon-fa'; import {faBell} from '@fortawesome/free-regular-svg-icons'; import {TabsConfiguration} from 'projects/workspaces/src/lib/tabs-configuration'; import {Tab} from 'projects/tabs/src/lib/tab'; import {HelpPanelComponent} from 'projects/help/src/lib/help-panel/help-panel.component'; import {faQuestionCircle} from '@fortawesome/free-regular-svg-icons/faQuestionCircle'; import {NotificationsTableComponent} from 'projects/notification/src/lib/notifications-table/notifications-table.component'; import {NotificationsTabHeaderComponent} from 'projects/notification/src/lib/notifications-tab-header/notifications-tab-header.component'; import {library} from '@fortawesome/fontawesome-svg-core'; import {transition, trigger, useAnimation} from '@angular/animations'; import {fadeInAnimation} from 'projects/commons/src/lib/animations'; import { STORAGE_CONTEXTUAL_MENU, STORAGE_TREE_LABEL, StorageTreeComponent } from 'projects/storage/src/lib/storage-tree/storage-tree/storage-tree.component'; import { STORAGE_EDITOR_README_NODE, StorageEditorComponent } from 'projects/storage/src/lib/storage-editor/storage-editor/storage-editor.component'; import {OpenHelpEvent} from 'projects/help/src/lib/help-panel/open-help-event'; import {OpenNotificationsEvent} from 'projects/notification/src/lib/open-notifications-event'; import {DEBUG_ICON, LOGS_ICON, PLAY_ICON} from 'projects/icon/src/lib/icons'; import {STORAGE_ROOT_NODE} from 'projects/storage/src/lib/storage-tree/storage-tree-data-source.service'; import {STORAGE_NODE_BUTTONS} from 'projects/storage/src/lib/storage-tree/storage-node/storage-node.component'; import {SimulationNodeButtonsComponent} from 'projects/gatling/src/app/simulations/simulation-node-buttons/simulation-node-buttons.component'; import {faCode} from '@fortawesome/free-solid-svg-icons/faCode'; import {faFile} from '@fortawesome/free-solid-svg-icons/faFile'; import {STORAGE_ID} from 'projects/storage/src/lib/storage-id'; import {SimulationContextualMenuComponent} from 'projects/gatling/src/app/simulations/simulation-contextual-menu/simulation-contextual-menu.component'; import {ResultsTableComponent} from 'projects/analysis/src/lib/results/results-table/results-table.component'; import {faPoll} from '@fortawesome/free-solid-svg-icons/faPoll'; import {OpenStorageTreeEvent} from 'projects/storage/src/lib/events/open-storage-tree-event'; import {GatlingConfigurationService} from 'projects/gatling/src/app/gatling-configuration.service'; import {DebugEntriesTableComponent} from 'projects/analysis/src/lib/results/debug/debug-entries-table/debug-entries-table.component'; import {OpenDebugEvent} from 'projects/analysis/src/lib/events/open-debug-event'; import {OpenResultsEvent} from 'projects/analysis/src/lib/events/open-results-event'; import {TasksTableComponent} from 'projects/runtime/src/lib/runtime-task/tasks-table/tasks-table.component'; import {RuntimeLogsPanelComponent} from 'projects/runtime/src/lib/runtime-log/runtime-logs-panel/runtime-logs-panel.component'; import {OpenLogsEvent} from 'projects/runtime/src/lib/events/open-logs-event'; import {faDocker} from '@fortawesome/free-brands-svg-icons/faDocker'; import {ContainersTableComponent} from 'projects/runtime/src/lib/runtime-task/containers-table/containers-table.component'; import {TaskSelectedEvent} from 'projects/runtime/src/lib/events/task-selected-event'; import {OpenTasksEvent} from 'projects/runtime/src/lib/events/open-tasks-event'; import {ROOT_NODE} from 'projects/storage/src/lib/entities/storage-node'; import {faCogs} from '@fortawesome/free-solid-svg-icons/faCogs'; import {GitProjectService} from 'projects/git/src/lib/git-project/git-project.service'; import {faGit} from '@fortawesome/free-brands-svg-icons/faGit'; import {GitCommandComponent} from 'projects/git/src/lib/git-command/git-command/git-command.component'; import {GitStatusComponent} from 'projects/git/src/lib/git-command/git-status/git-status.component'; import {faGitAlt} from '@fortawesome/free-brands-svg-icons/faGitAlt'; import {CurrentProjectService} from 'projects/git/src/lib/git-project/current-project/current-project.service'; import {GitStatusTabHeaderComponent} from 'projects/git/src/lib/git-command/git-status-tab-header/git-status-tab-header.component'; library.add(faCode, faQuestionCircle, faBell, faFile, faPoll, faDocker, faCogs, faGitAlt, faGit); @Component({ selector: 'app-workspace', templateUrl: './workspace.component.html', styleUrls: ['./workspace.component.scss'], animations: [ trigger('insertWorkspace', [ transition(':enter', useAnimation(fadeInAnimation, {params: {duration: '1s'}})) ]), ], }) export class WorkspaceComponent implements OnInit { left: SideConfiguration; right: SideConfiguration; bottom: SideConfiguration; center: ComponentPortal<StorageEditorComponent>; id: string; constructor(private injector: Injector, private gatlingConfiguration: GatlingConfigurationService, private gitProject: GitProjectService, private currentProject: CurrentProjectService) { } ngOnInit() { this.id = this.currentProject.currentProject.getValue().id; this.center = new ComponentPortal(StorageEditorComponent, null, Injector.create({ providers: [ {provide: STORAGE_EDITOR_README_NODE, useValue: {path: 'gatling/README.md', type: 'FILE', depth: 1}} ], parent: this.injector })); const simulationsTree = new ComponentPortal(StorageTreeComponent, null, Injector.create({ providers: [ {provide: STORAGE_ROOT_NODE, useValue: this.gatlingConfiguration.simulationsRootNode}, {provide: STORAGE_ID, useValue: `${this.id}-simulations-tree`}, {provide: STORAGE_TREE_LABEL, useValue: 'Simulations'}, {provide: STORAGE_NODE_BUTTONS, useValue: SimulationNodeButtonsComponent}, {provide: STORAGE_CONTEXTUAL_MENU, useValue: SimulationContextualMenuComponent}, ], parent: this.injector })); const configurationTree = new ComponentPortal(StorageTreeComponent, null, Injector.create({ providers: [ {provide: STORAGE_ROOT_NODE, useValue: ROOT_NODE}, {provide: STORAGE_ID, useValue: `${this.id}-gatling-files-tree`}, {provide: STORAGE_TREE_LABEL, useValue: 'Configuration'}, ], parent: this.injector })); const resourcesTree = new ComponentPortal(StorageTreeComponent, null, Injector.create({ providers: [ {provide: STORAGE_ROOT_NODE, useValue: this.gatlingConfiguration.resourcesRootNode}, {provide: STORAGE_ID, useValue: `${this.id}-resources-tree`}, {provide: STORAGE_TREE_LABEL, useValue: 'Resource Files'}, ], parent: this.injector })); this.left = new SideConfiguration( new TabsConfiguration( [ new Tab(configurationTree, 'Configuration', new IconFa(faCogs), 'GATLING_CONFIGURATION', false), new Tab(simulationsTree, 'Simulations', new IconFa(faCode), 'GATLING_SIMULATIONS', false, [OpenStorageTreeEvent.CHANNEL]), ], 1, 60, ), new TabsConfiguration( [new Tab(resourcesTree, 'Resources', new IconFa(faFile), 'GATLING_RESOURCES', false)], 0, 40, ), 25, ); this.right = new SideConfiguration( new TabsConfiguration( [ new Tab(new ComponentPortal(HelpPanelComponent), 'Help', new IconFa(faQuestionCircle, 'accent'), null, false, [OpenHelpEvent.CHANNEL]), new Tab(new ComponentPortal(ResultsTableComponent), 'Results', new IconFa(faPoll), 'GATLING_RESULTS_TABLE', false, [OpenResultsEvent.CHANNEL]), ], -1, 50 ), new TabsConfiguration( [ new Tab(new ComponentPortal(DebugEntriesTableComponent), 'Debug', DEBUG_ICON, 'GATLING_DEBUG_ENTRIES_TABLE', false, [OpenDebugEvent.CHANNEL]), ], -1, 50 ), 30 ); this.bottom = new SideConfiguration( new TabsConfiguration( [ new Tab( new ComponentPortal(TasksTableComponent), 'Tasks', PLAY_ICON, 'GATLING_TASKS_TABLE', true, [OpenTasksEvent.CHANNEL]), new Tab( new ComponentPortal(RuntimeLogsPanelComponent), 'Logs', LOGS_ICON, 'GATLING_LOGS', true, [OpenLogsEvent.CHANNEL]), // new Tab( // new ComponentPortal(GitCommandComponent), // 'Command', // new IconFa(faGit), // 'GIT_COMMAND', // false) ], 0, 60 ), new TabsConfiguration( [ // new Tab( // new ComponentPortal(GitStatusComponent), // 'Status', // new IconFa(faGitAlt), // 'GIT_STATUS', // false, // [], // GitStatusTabHeaderComponent), new Tab( new ComponentPortal(ContainersTableComponent), 'Containers', new IconFa(faDocker), 'GATLING_CONTAINERS_TABLE', true, [TaskSelectedEvent.CHANNEL]), new Tab(new ComponentPortal(NotificationsTableComponent), 'Notifications', new IconFa(faBell), null, false, [OpenNotificationsEvent.CHANNEL], NotificationsTabHeaderComponent), ], 2, 40 ), 30 ); } }
the_stack
namespace pixi_heaven.mesh { import GroupD8 = PIXI.GroupD8; /** * The Plane allows you to draw a texture across several points and them manipulate these points * *```js * for (let i = 0; i < 20; i++) { * points.push(new PIXI.Point(i * 50, 0)); * }; * let Plane = new PIXI.Plane(PIXI.Texture.fromImage("snake.png"), points); * ``` * * @class * @extends PIXI.mesh.Mesh * @memberof PIXI.mesh * */ export class Plane extends Mesh { _verticesX: number; _verticesY: number; _direction: number; _lastWidth: number; _lastHeight: number; _width: number; _height: number; /** * Version counter for verticesX/verticesY change * * @member {number} * @private */ _dimensionsID = 0; _lastDimensionsID = -1; /** * Version counter for vertices updates * * @member {number} * @private */ _verticesID = 0; _lastVerticesID = -1; /** * Version counter for uvs updates * * @member {number} * @private */ _uvsID = 0; _lastUvsID = -1; _anchor: PIXI.ObservablePoint; /** * reset the points on dimensions change * @member {boolean} * @default true */ autoResetVertices = true; calculatedVertices: Float32Array = null; /** * @param {PIXI.Texture} texture - The texture to use on the Plane. * @param {number} [verticesX=2] - The number of vertices in the x-axis * @param {number} [verticesY=2] - The number of vertices in the y-axis * @param {number} [direction=0] - Direction of the mesh. See {@link PIXI.GroupD8} for explanation */ constructor(texture: PIXI.Texture, verticesX: number = 2, verticesY: number = 2, direction = 0) { super(texture); this._verticesX = verticesX || 2; this._verticesY = verticesY || 2; this._direction = (direction || 0) & (~1); this._lastWidth = this._texture.orig.width; this._lastHeight = this._texture.orig.height; this._width = 0; this._height = 0; /** * anchor for a plane * * @member {PIXI.ObservablePoint} * @private */ this._anchor = new PIXI.ObservablePoint(this._onAnchorUpdate, this); this.drawMode = Mesh.DRAW_MODES.TRIANGLES; this.refresh(); } /** * The width of the sprite, setting this will actually modify the scale to achieve the value set * * @member {number} */ get verticesX() { return this._verticesX; } set verticesX(value) // eslint-disable-line require-jsdoc { if (this._verticesX === value) { return; } this._verticesX = value; this._dimensionsID++; } /** * The height of the TilingSprite, setting this will actually modify the scale to achieve the value set * * @member {number} */ get verticesY() { return this._verticesY; } set verticesY(value) // eslint-disable-line require-jsdoc { if (this._verticesY === value) { return; } this._verticesY = value; this._dimensionsID++; } /** * Direction of the mesh, see {@link PIXI.GroupD8} for explanation * * @param {number} [direction=0] - Direction of the mesh. */ get direction() { return this._direction; } set direction(value) // eslint-disable-line require-jsdoc { if (value % 2 !== 0) { throw new Error('plane does not support diamond shape yet'); } if (this._direction === value) { return; } this._direction = value; this._verticesID++; } /** * The width of the Plane, settings this wont modify the scale, but vertices will be cleared * * @member {number} */ get width() { return this._width || this.texture.orig.width; } set width(value) // eslint-disable-line require-jsdoc { if (this._width === value) { return; } this._width = value; this._verticesID++; } /** * The height of the Plane, settings this wont modify the scale, but vertices will be cleared * * @member {number} */ get height() { return this._height || this.texture.orig.height; } set height(value) // eslint-disable-line require-jsdoc { if (this._height === value) { return; } this._height = value; this._verticesID++; } /** * The anchor sets the origin point of the texture. * The default is 0,0 this means the texture's origin is the top left * Setting the anchor to 0.5,0.5 means the texture's origin is centered * Setting the anchor to 1,1 would mean the texture's origin point will be the bottom right corner * * @member {PIXI.ObservablePoint} */ get anchor() { return this._anchor; } set anchor(value) // eslint-disable-line require-jsdoc { this._anchor.copy(value); } /** * updates vertices after anchor changes * * @private */ _onAnchorUpdate() { this._verticesID++; } /** * Call when you updated some parameters manually */ invalidateVertices() { this._verticesID++; } /** * Call when you updated some parameters manually */ invalidateUvs() { this._uvsID++; } /** * Call when you updated some parameters manually */ invalidate() { this._verticesID++; this._uvsID++; } /** * Refreshes the plane mesh * * @param {boolean} [forceUpdate=false] if true, everything will be updated in any case */ refresh(forceUpdate = false) { this.refreshDimensions(forceUpdate); if (this._texture.noFrame) { return; } if (this._lastWidth !== this.width || this._lastHeight !== this.height) { this._lastWidth = this.width; this._lastHeight = this.height; if (this.autoResetVertices) { this._verticesID++; } } if (this._uvTransform.update(forceUpdate)) { this._uvsID++; } if (this._uvsID !== this._lastUvsID) { this._refreshUvs(); } this.refreshVertices(); } /** * Refreshes structure of the plane mesh * when its done, refreshes vertices and uvs too * * @param {boolean} [forceUpdate=false] if true, dimensions will be updated any case */ refreshDimensions(forceUpdate = false) { // won't be overwritten, that's why there's no private method if (!forceUpdate && this._lastDimensionsID === this._dimensionsID) { return; } this._lastDimensionsID = this._dimensionsID; this._verticesID++; this._uvsID++; const total = this._verticesX * this._verticesY; const segmentsX = this._verticesX - 1; const segmentsY = this._verticesY - 1; const indices = []; const totalSub = segmentsX * segmentsY; for (let i = 0; i < totalSub; i++) { const xpos = i % segmentsX; const ypos = (i / segmentsX) | 0; const value = (ypos * this._verticesX) + xpos; const value2 = (ypos * this._verticesX) + xpos + 1; const value3 = ((ypos + 1) * this._verticesX) + xpos; const value4 = ((ypos + 1) * this._verticesX) + xpos + 1; indices.push(value, value2, value3); indices.push(value2, value4, value3); } this.indices = new Uint16Array(indices); this.uvs = new Float32Array(total * 2); this.vertices = new Float32Array(total * 2); this.calculatedVertices = new Float32Array(total * 2); this.indexDirty++; if (this.colors) { this.colors = new Uint32Array(total * 2); for (let i = 0; i < total; i++) { this.colors[i * 2] = 0; this.colors[i * 2 + 1] = 0xffffffff; } } } /** * Refreshes plane vertices coords * by default, makes them uniformly distributed * * @param {boolean} [forceUpdate=false] if true, vertices will be updated any case */ refreshVertices(forceUpdate = false) { const texture = this._texture; if (texture.noFrame) { return; } if (forceUpdate || this._lastVerticesID !== this._verticesID) { this._lastVerticesID = this._verticesID; this._refreshVertices(); } } /** * Refreshes plane UV coordinates * */ _refreshUvs() { this._uvsID = this._lastUvsID; const total = this._verticesX * this._verticesY; const uvs = this.uvs; const direction = this._direction; const ux = GroupD8.uX(direction); const uy = GroupD8.uY(direction); const vx = GroupD8.vX(direction); const vy = GroupD8.vY(direction); const factorU = 1.0 / (this._verticesX - 1); const factorV = 1.0 / (this._verticesY - 1); for (let i = 0; i < total; i++) { let x = (i % this._verticesX); let y = ((i / this._verticesX) | 0); x = (x * factorU) - 0.5; y = (y * factorV) - 0.5; uvs[i * 2] = (ux * x) + (vx * y) + 0.5; uvs[(i * 2) + 1] = (uy * x) + (vy * y) + 0.5; } this.dirty++; this.multiplyUvs(); } /** * calculates supposed position of vertices */ calcVertices() { const total = this._verticesX * this._verticesY; const vertices = this.calculatedVertices; const width = this.width; const height = this.height; const direction = this._direction; let ux = GroupD8.uX(direction); let uy = GroupD8.uY(direction); let vx = GroupD8.vX(direction); let vy = GroupD8.vY(direction); const anchor = this._anchor as any; const offsetX = (0.5 * (1 - (ux + vx))) - anchor._x; const offsetY = (0.5 * (1 - (uy + vy))) - anchor._y; const factorU = 1.0 / (this._verticesX - 1); const factorV = 1.0 / (this._verticesY - 1); ux *= factorU; uy *= factorU; vx *= factorV; vy *= factorV; for (let i = 0; i < total; i++) { const x = (i % this._verticesX); const y = ((i / this._verticesX) | 0); vertices[i * 2] = ((ux * x) + (vx * y) + offsetX) * width; vertices[(i * 2) + 1] = ((uy * x) + (vy * y) + offsetY) * height; } } /** * calculates colors (if enabled) */ calcColors() { /* nothing */ } /** * Refreshes vertices of Plane mesh * by default, makes them uniformly distributed * * @private */ _refreshVertices() { this.calcVertices(); const vertices = this.vertices; const calculatedVertices = this.calculatedVertices; const len = vertices.length; for (let i = 0; i < len; i++) { vertices[i] = calculatedVertices[i]; } if (this.colors) { this.calcColors(); } } /** * resets everything to defaults */ reset() { if (!this.texture.noFrame) { this._refreshUvs(); this.refreshVertices(true); } } } }
the_stack
import '../../styles/edit.scss'; // import * as Clipboard from 'clipboard'; import * as React from 'react'; import * as ReactDOM from 'react-dom'; import axios from 'axios'; import * as Raven from 'raven-js'; import * as route from './route'; import { Editor } from '../editor/editor'; import { ProxyController } from './proxy'; import { ControllerImpl } from '../editor/controller'; import { WasmController, convertMarkdownToHtml, convertMarkdownToDoc } from '../editor/wasm'; import * as index from '../index'; import {FrontendCommand} from '../bindgen/edit_client'; import DEBUG from '../debug'; declare var CONFIG: any; // Check page configuration. if (!CONFIG.configured) { alert('The window.CONFIG variable was not configured by the server!') } function recentlyViewedPush(path: string) { let recent = recentlyViewed(); recent.splice(0, 0, {path}); recentlyViewedWrite(recent.slice(0, 100)); // Keep to >= 100 items. } function recentlyViewedWrite(input: Array<{path: string}>) { localStorage.setItem('v1:recently-viewed', JSON.stringify(input)); } function recentlyViewed(): Array<{path: string}> { try { let storage = JSON.parse(localStorage.getItem('v1:recently-viewed') || '[]'); let storageArray: Array<any> = Array.from(storage); for (let item of storageArray) { if (!('path' in item)) { throw new Error('Path not found in ' + JSON.stringify(item)); } if (typeof item.path != 'string') { throw new Error('Expected string path in ' + JSON.stringify(item)); } } // Filter out redundant items. var t: any; return storageArray.filter((t={},e=>!(t[e.path]=++t[e.path]|0))) ; } catch (e) { console.error('error loading "v1:recently-viewed" from localStorage:', e); return []; } } function UiElement( props: { editor: EditorFrame, }, element: any, i = Math.random(), ) { if ('Button' in element) { let button = element.Button; return ( <button key={i} onClick={ () => props.editor.client.sendCommand({ 'tag': 'Button', 'fields': { button: button[1], }, }) } className={button[2] ? 'active' : ''} >{button[0]}</button> ) } else if ('ButtonGroup' in element) { return ( <div className="menu-buttongroup" key={i}> {element.ButtonGroup.map((x: any, i: number) => UiElement(props, x, i))} </div> ) } return null; } function NativeButtons( props: { editor: EditorFrame, buttons: Array<any> }, ) { if (!props.buttons.length) { return ( <div id="native-buttons">Loading...</div> ); } return ( <div id="native-buttons">{ props.buttons.map((x, i) => UiElement(props, x, i)) }</div> ); } export function graphqlPage(id: string) { return axios.post( route.graphqlUrl(), { query: ` query ($id: String!) { page(id: $id) { markdown }} `, variables: { id, }, } ); } export function graphqlCreatePage(id: string, markdown: string) { return axios.post( route.graphqlUrl(), { query: ` mutation ($id: String!, $markdown: String!) { createPage(id: $id, markdown: $markdown) { __typename } } `, variables: { id, markdown, }, } ); } class MarkdownModal extends React.Component { props: { markdown: string, onModal: (modal: React.ReactNode) => void, }; state = { markdown: this.props.markdown, }; render() { let self = this; return ( <Modal> <h1>Markdown Import/Export</h1> <p>The document is displayed as Markdown in the textarea below. Feel free to copy it, or modify it and click "Import" to overwrite the current page with your changes.</p> <textarea value={self.state.markdown} onChange={(e) => { this.setState({ markdown: e.target.value, }); }} /> <div className="modal-buttons"> <button className="dismiss" onClick={() => self.props.onModal(null)}>Back</button> <div style={{flex: 1}} /> <button className="load" onClick={() => { graphqlCreatePage(route.pageId(), self.state.markdown) .then(req => { if (req.data.errors && req.data.errors.length) { console.log(req.data.errors); console.error('Error in markdown save.'); } else { console.log('Update success, reloading...'); setTimeout(() => { window.location.reload(); }, 500); } }) .catch(err => console.error(err)); }}>Import</button> </div> </Modal> ); } } class LocalButtons extends React.Component { props: { editor: any, onModal: (modal: React.ReactNode) => void, }; state = {}; onMarkdownClick() { let self = this; graphqlPage(route.pageId()) .then(res => { let graphql = res.data; let markdown = graphql.data.page.markdown; self.props.onModal( <MarkdownModal markdown={markdown} onModal={self.props.onModal} /> ); }) .catch(err => { console.error('onSaveMarkdown:', err); }) } toggleWidth() { document.body.classList.toggle('theme-column'); if (!document.body.classList.contains('theme-column')) { localStorage.setItem('edit-text:theme-wide', '1'); } else { localStorage.removeItem('edit-text:theme-wide'); } } render(): React.ReactNode { return ( <div className="menu-buttongroup" style={{marginRight: 0}}> <button onClick={() => this.onMarkdownClick()}>Load/Save</button> <button id="width" onClick={() => this.toggleWidth()}>Page Width</button> </div> ); } } function Modal(props: any) { return ( <div id="modal"> <div id="modal-dialog"> {props.children} </div> </div> ); } export type NoticeProps = { element: React.ReactNode, level: 'notice' | 'error', }; function FooterNotice(props: { onDismiss: () => void, children: React.ReactNode, level: string, }) { return ( <div className={`footer-bar ${props.level}`}> <div>{props.children}</div> <span onClick={props.onDismiss}>&times;</span> </div> ); } type EditorFrameProps = { client: ControllerImpl, body: string, }; // https://www.typescriptlang.org/docs/handbook/advanced-types.html function assertNever(x: never): never { throw new Error("Unexpected object: " + x); } // Initialize child editor. export class EditorFrame extends React.Component { props: EditorFrameProps; state: { body: string, buttons: any, editorID: string, modal: React.ReactNode, notices: Array<NoticeProps>, sidebarExpanded: boolean, }; KEY_WHITELIST: any; client: ControllerImpl; markdown: string; editor: Editor | null; constructor( props: EditorFrameProps, ) { super(props); this.KEY_WHITELIST = []; this.client = props.client; this.client.onMessage = this.onFrontendCommand.bind(this); // Background colors. // TODO make these actionable on this object right? this.client.onClose = function () { document.body.style.background = 'red'; console.error('!!! client close'); }; this.client.onError = (e: any) => { this.showNotification({ level: 'error', element: <div>edit-text encountered an exception. Please reload this page to continue. (Error thrown from WebAssembly)</div> }); }; // TODO need a better location to do this type of initialization // Push self editor into the recently viewed stack let match = window.location.pathname.match(/^\/([^\/]+)/); if (match) { let path = match[1]; recentlyViewedPush(path); } document.addEventListener('keydown', (e) => { if (e.keyCode == 27) { document.querySelector('#edit-sidebar')!.classList.toggle('expanded'); } }); // Update source code watcher to be notified of a newer browser version. // TODO This should really just be webpack's auto-reload functionality or // something equivalent. This version causes the file to just be reloaded // every two minutes. Impractical. // let cachedEtag: null | string = null; // let refreshNotification = false; // let intervalId = setInterval(() => { // fetch(new Request('/$/edit.js'), { // method: 'GET', // mode: 'same-origin', // cache: 'default', // }).then(res => { // if (res.ok) { // let etag = res.headers.get('etag'); // if (etag) { // if (!cachedEtag) { // cachedEtag = etag; // } else { // if (cachedEtag != etag) { // if (!refreshNotification) { // refreshNotification = true; // this.showNotification({ // level: 'notice', // element: <div>A newer version of edit-text is available. <button onClick={() => window.location.reload()}>Refresh the page</button></div>, // }); // } // clearInterval(intervalId); // } // } // } // } // }); // }, 3000); this.state = { body: this.props.body, buttons: [], editorID: '$$$$$$', modal: null, notices: [], sidebarExpanded: false, }; } showNotification(notice: NoticeProps) { this.setState({ notices: this.state.notices.slice().concat([notice]), }) } render(): React.ReactNode { let modalClass = this.state.modal == null ? '' : 'modal-active'; let editBoundary = null; return ( <div className="fullpage"> {this.state.modal} <div id="root-layout" className={modalClass}> <div id="toolbar"> <a href="/" id="logo" className={CONFIG.release_mode} onClick={(e) => { this.setState({ sidebarExpanded: !this.state.sidebarExpanded, }); e.preventDefault(); }} >{CONFIG.title}</a> <NativeButtons editor={this} buttons={this.state.buttons} /> <LocalButtons editor={this} onModal={(modal) => { this.setState({ modal }); }} /> </div> <div id="edit-layout"> <div id="edit-sidebar" className={this.state.sidebarExpanded ? 'expanded' : ''}> <div id="edit-sidebar-inner"> <div id="edit-sidebar-inner-inner"> <div id="recently-viewed"> <p><span id="edit-sidebar-new"><button onClick={_ => { window.location.href = '/?from='; // TODO this is a hack }}>New</button></span>Recently Viewed</p> <div id="recently-viewed-list">{ recentlyViewed().map((doc) => ( <div><a href={doc.path} title={'/' + doc.path}>{doc.path}</a></div> )) }</div> <div id="edit-sidebar-inner-inner"></div> </div> <div id="edit-sidebar-footer"> Read more at <a href="http://docs.edit.io">docs.edit.io</a>.<br />Or contribute to <a href="http://github.com/tcr/edit-text">edit-text on Github</a>. </div> </div> </div> </div> <div id="edit-outer"> <div id="edit-page" ref={r => editBoundary = r} onMouseDown={e => { this.editor!.onMouseDown(e as any); }} onMouseUp={e => { this.editor!.onMouseUp(e as any); }} onMouseMove={e => { this.editor!.onMouseMove(e as any); }} > <Editor controller={this.props.client} KEY_WHITELIST={this.KEY_WHITELIST} content={this.state.body} editorID={this.state.editorID} disabled={!!this.state.modal} ref={r => this.editor = r} /> </div> </div> </div> </div> <div id="footer"> <div id="debug-row"> <div id="debug-content" onClick={(e) => document.querySelector('#debug-content')!.classList.toggle('expanded')}> <div id="debug-button">🐞</div> <div id="debug-buttons"> <b>DEBUG</b> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span style={{background: '#6f9', borderRadius: '3px'}}> Client: <kbd tabIndex={0}>{this.state.editorID}</kbd> </span> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <span><button onClick={() => alert('good job')}>test alert()</button></span> </div> </div> </div> {this.state.notices.map((x, key) => { return ( <FooterNotice key={key} onDismiss={() => { let notices = this.state.notices.slice(); notices.splice(key, 1); this.setState({ notices, }); }} level={x.level} > {x.element} </FooterNotice> ); })} </div> </div> ); } // Controller has sent us (the frontend) a command. onFrontendCommand(command: FrontendCommand) { const editor = this; switch (command.tag) { // https://www.typescriptlang.org/docs/handbook/advanced-types.html default: assertNever(command); case 'Init': { let editorID = command.fields; this.setState({ editorID, }); console.info('Editor "%s" connected.', editorID); // Log the editor ID. Raven.setExtraContext({ editor_id: editorID, }); break; } case 'RenderDelta': { // Update page content // console.groupCollapsed('Parse Update'); // console.log(parse.Update); let programs = JSON.parse(command.fields[0]); programs.forEach((program: any) => { // console.log(program, '\n'); this.editor!._runProgram(program); // Corrections // while (true) { // let unjoinedSpans = document.querySelector('.edit-text span.Normie + span.Normie'); // if (unjoinedSpans === null) { // break; // } // let right = unjoinedSpans; // let left = right.previousSibling; // while (right.childNodes.length) { // left!.appendChild(right.firstChild!); // } // right!.parentNode!.removeChild(right); // left!.normalize(); // } // console.log(document.querySelector('.edit-text')!.innerHTML); }); // console.log(parse.Update[0]); // console.log(document.querySelector('.edit-text')!.innerHTML); // console.groupEnd(); // this.setState({ // body: JSON.stringify(parse.Update[0], null, ' '), // }); break; } case 'RenderFull': { DEBUG.measureTime('first-update'); this.editor!._setHTML(command.fields); // Update page content // this.setState({ // body: parse.RenderFull[0], // }); break; } case 'Controls': { // console.log('SETUP CONTROLS', parse.Controls); // Update the key list in-place. editor.KEY_WHITELIST.splice.apply(editor.KEY_WHITELIST, [0, 0].concat(command.fields.keys.map((x: any) => ({ keyCode: x[0], metaKey: x[1], shiftKey: x[2], }))) ); // Update buttons view this.setState({ buttons: command.fields.buttons, }); DEBUG.measureTime('interactive'); break; } case 'Error': { let unsafeHtmlMessage = command.fields; this.showNotification({ element: <div dangerouslySetInnerHTML={{__html: unsafeHtmlMessage}} />, level: 'error', }); break; } case 'ServerDisconnect': { this.showNotification({ element: <div>The editor has disconnected from the server. Sorry. This page will automatically reload, or you can manually <button onClick={(e) => { window.location.reload(); }}>Refresh the page</button></div>, level: 'error', }); // Start refresh poller. setTimeout(() => { setInterval(() => { graphqlPage('home').then(() => { // Can access server, continue window.location.reload(); }); }, 2000); }, 3000); break; } case 'ServerCommand': { throw new Error('Unexpected server command'); } case 'PromptString': { // unsure what these should do, if anything break; } } } } function multiConnect(client: ControllerImpl) { // Blur/Focus classes. window.addEventListener('focus', () => { document.body.classList.remove('blurred'); }); window.addEventListener('blur', () => { document.body.classList.add('blurred'); }); document.body.classList.add('blurred'); // Forward Monkey events. window.onmessage = (event) => { let editor = this; // Sanity check. if (typeof event.data != 'object') { return; } let msg = event.data; if ('Monkey' in msg) { // TODO reflect this in the app client.sendCommand({ 'tag': 'Monkey', 'fields': { enabled: msg.Monkey, }, }); } }; } // This is a prototype of a standalone edit-text React component. class EditText extends React.Component { props: { client: WasmController, markdown: string, onChange: Function | null, }; state = { content: convertMarkdownToHtml(this.props.markdown), whitelist: [], }; render() { return ( <Editor editorID={'$local'} disabled={false} controller={this.props.client} content={this.state.content} KEY_WHITELIST={this.state.whitelist} /> ); } componentDidMount() { this.props.client.onMessage = (parse: any) => { if (parse.Init) { // let editorID = parse.Init; // this.setState({ // editorID, // }); // console.info('Editor "%s" connected.', editorID); // // Log the editor ID. // Raven.setExtraContext({ // editor_id: editorID, // }); } else if (parse.Update) { // Update page content this.setState({ content: parse.Update[0], }); // TODO generate markdown from client now // if (this.props.onChange !== null) { // this.props.onChange(parse.Update[1]); // } } else if (parse.RenderFull) { // Update page content this.setState({ content: parse.RenderFull, }); // TODO generate markdown from client now // if (this.props.onChange !== null) { // this.props.onChange(parse.RenderFull[1]); // } } else if (parse.Controls) { // console.log('SETUP CONTROLS', parse.Controls); // Update the key list in-place. this.setState({ whitelist: parse.Controls.keys.map((x: any) => ({ keyCode: x[0], metaKey: x[1], shiftKey: x[2], })), }); } }; this.props.client .connect() .then(() => { console.log('Loading static editor.'); this.props.client.clientBindings.command(JSON.stringify({ ClientCommand: { Init: ["$local", convertMarkdownToDoc(this.props.markdown), 100], } })); }); } } // export function start() { export function start_standalone() { index.getWasmModule() .then(() => { let client = new WasmController(); // Create the editor frame. ReactDOM.render( <div style={{display: 'flex', height: '100%', width: '100%'}}> <div style={{flex: 1}}> <EditText client={client} markdown={"# Most of all\n\nThe world is a place where parts of wholes are perscribred"} onChange={(markdown: string) => { // TODO not visible until styles are encapsulated. // TODO edit-text needs a markdown viewer split pane :P. document.getElementById('mdpreview')!.innerText = markdown; }} /> </div> <div style={{background: '#fef', flex: 1, padding: '20px'}}> <pre id="mdpreview"></pre> </div> </div>, document.querySelector('#content')!, ); }); } export function start() { // export function start_app() { let client: ControllerImpl; // Wasm and Proxy implementations if (CONFIG.wasm) { client = new WasmController(); } else { client = new ProxyController(); } // Connect to parent window (if exists). if (window.parent != window) { multiConnect(client); } // TODO move this to a better logical location and manage local storage better if (localStorage.getItem('edit-text:theme-wide')) { document.body.classList.remove('theme-column'); } // TODO fix the adding of editing-blurred to the bdy // document.addEventListener('focus', () => { // // console.log('(page focus)'); // document.body.classList.remove('editing-blurred'); // }); // document.addEventListener('blur', () => { // // console.log('(page blur)'); // document.body.classList.add('editing-blurred'); // }); // document.body.classList.add('editing-blurred'); // Create the editor frame. let editorFrame: EditorFrame | null; ReactDOM.render( <EditorFrame client={client} body={document.querySelector('.edit-text')!.innerHTML} ref={c => editorFrame = c} />, document.querySelector('#content')!, () => { // Connect client. DEBUG.measureTime('connect-client'); client.connect(); } ); }
the_stack
import { IConnection } from "mysql"; import { AppPermissionQueries, AppQueries, DeploymentAppQueries, DeploymentPackageQueries, DeploymentQueries, UserQueries, } from "../queries"; import BaseDAO from "./BaseDAO"; import DeploymentDAO from "./DeploymentDAO"; import HistoryDAO from "./HistoryDAO"; import PackageDAO from "./PackageDAO"; import { AppDTO } from "../dto"; import Encryptor from "../Encryptor"; import { difference, findKey } from "lodash"; const OWNER = "Owner"; const COLLAB = "Collaborator"; export default class AppDAO extends BaseDAO { public static async createApp(connection: IConnection, app: AppDTO): Promise<AppDTO> { await AppDAO.beginTransaction(connection); const insertResults = await AppDAO.insertApp(connection, app.name); const appId = insertResults.insertId; const outgoing = new AppDTO(); outgoing.id = appId; outgoing.name = app.name; if (app.collaborators && Object.keys(app.collaborators).length > 0) { try { outgoing.collaborators = await AppDAO.createAppPermissions(connection, appId, app.collaborators); } catch (err) { AppDAO.rollback(connection); throw (err); } } else { AppDAO.rollback(connection); throw new Error("Expected app.collaborators to be provided"); } if (app.deployments && Object.keys(app.deployments).length > 0) { await Promise.all(Object.keys(app.deployments).map((deploymentName) => { return DeploymentDAO.addDeployment(connection, appId, app.deployments[deploymentName].name, { key: app.deployments[deploymentName].key, }); })); const deployments = await DeploymentDAO.getDeploymentsByApp(connection, appId); // outgoing app.deployments is expected to be an array of the deployment names outgoing.deployments = deployments.map((deployment) => deployment.name); } await AppDAO.commit(connection); return outgoing; } public static async appById(connection: IConnection, appId: number): Promise<AppDTO> { const appResults = await AppDAO.getAppById(connection, appId); if (appResults && appResults.length === 0) { throw new Error("App not found for app id [" + appId + "]"); } const outgoing = new AppDTO(); outgoing.id = appResults[0].id; outgoing.name = appResults[0].name; return outgoing; } public static async appsForCollaborator(connection: IConnection, email: string): Promise<AppDTO[]> { const appResults = await AppDAO.query(connection, AppPermissionQueries.getAppPermissionsByUserEmail, [Encryptor.instance.encrypt("user.email", email)]); const apps = new Array<AppDTO>(); let prevAppId; let appDTO = new AppDTO(); for (const appResult of appResults) { if (appResult.app_id !== prevAppId) { appDTO = new AppDTO(); appDTO.id = appResult.app_id; appDTO.name = appResult.app_name; appDTO.collaborators = {}; apps.push(appDTO); } appDTO.collaborators[appResult.sub_email] = { permission: appResult.sub_permission, }; prevAppId = appResult.app_id; } await Promise.all(apps.map((app) => AppDAO.populateAppDetails(connection, app))); return apps; } public static async appForCollaborator(connection: IConnection, email: string, name: string): Promise<AppDTO | undefined> { const appResults = await AppDAO.query(connection, AppQueries.getAppByAppNameAndCollaboratorEmail, [Encryptor.instance.encrypt("user.email", email), name]); if (!appResults || appResults.length === 0) { return undefined; } const outgoing = new AppDTO(); outgoing.id = appResults[0].id; outgoing.name = appResults[0].name; await AppDAO.populateAppDetails(connection, outgoing); return outgoing; } public static async appForDeploymentKey(connection: IConnection, deploymentKey: string): Promise<AppDTO> { const appResults = await AppDAO.query(connection, AppQueries.getAppByDeploymentKey, [deploymentKey]); if (!appResults || appResults.length === 0) { throw new Error("Not found; app not found for deployment key [" + deploymentKey + "]"); } const outgoing = new AppDTO(); outgoing.id = appResults[0].id; outgoing.name = appResults[0].name; await AppDAO.populateAppDetails(connection, outgoing); return outgoing; } public static async updateApp(connection: IConnection, appId: number, updateInfo: AppDTO): Promise<AppDTO> { /* This function handles these use cases. - rename an app - transfer ownership of an app - add a collaborator - remove a collaborator */ const existing = await AppDAO.appById(connection, appId); existing.collaborators = await AppDAO.getAppPermissionsByAppId(connection, appId) .then(AppDAO.transformOutgoingAppPermissions); // is the app getting renamed if (existing.name !== updateInfo.name) { const results = await AppDAO.updateAppName(connection, appId, updateInfo.name); existing.name = updateInfo.name; return existing; } // is the app transferring ownership const currentOwnerEmail = findKey(existing.collaborators, { permission: OWNER }); const updatedOwnerEmail = findKey(updateInfo.collaborators, { permission: OWNER }); if (currentOwnerEmail && updatedOwnerEmail && currentOwnerEmail !== updatedOwnerEmail) { const currentOwnerUser = await AppDAO.getUserByEmail(connection, currentOwnerEmail); const updateOwnerUser = await AppDAO.getUserByEmail(connection, updatedOwnerEmail); const updatePermissions = [{ permission: COLLAB, userId: currentOwnerUser[0].id, }, { permission: OWNER, userId: updateOwnerUser[0].id, }]; existing.collaborators = await AppDAO.updateAppPermissions(connection, appId, updatePermissions); return existing; } // is a collaborator being added const newCollaboratorsEmails = difference(Object.keys(updateInfo.collaborators), Object.keys(existing.collaborators)); if (newCollaboratorsEmails.length > 0) { const newPermissions = newCollaboratorsEmails.map((email: string) => { return { email, permission: COLLAB, }; }); existing.collaborators = await AppDAO.insertAppPermissions(connection, appId, newPermissions); return existing; } // is a collaborator being removed const remCollaboratorEmails = difference(Object.keys(existing.collaborators), Object.keys(updateInfo.collaborators)); if (remCollaboratorEmails.length > 0) { existing.collaborators = await AppDAO.removeAppPermissionsForUsers(connection, appId, remCollaboratorEmails); } return existing; } public static async removeApp(connection: IConnection, appId: number): Promise<void> { /* Need to remove - app - app_permission - deployment_app - deployment - package - deployment_package_history - package_diff - client_ratio */ await AppDAO.beginTransaction(connection); await AppDAO.deleteDeploymentRelated(connection, appId); await AppDAO.deleteAppRelated(connection, appId); await AppDAO.commit(connection); } private static async populateAppDetails(connection: IConnection, outgoing: AppDTO) { outgoing.collaborators = await AppDAO.getAppPermissionsByAppId(connection, outgoing.id) .then(AppDAO.transformOutgoingAppPermissions); const deployments = await DeploymentDAO.getDeploymentsByApp(connection, outgoing.id); // outgoing app.deployments is expected to be an array of the deployment keys outgoing.deployments = deployments.map((deployment) => deployment.name); } private static async getAppById(connection: IConnection, appId: number): Promise<any> { return AppDAO.query(connection, AppQueries.getAppById, [appId]); } /* private static async getAppByName(connection: IConnection, appName: string): Promise<any> { return AppDAO.query(connection, AppQueries.getAppByName, [appName]); } */ private static async insertApp(connection: IConnection, appName: string): Promise<any> { return AppDAO.query(connection, AppQueries.insertApp, [appName]); } private static async createAppPermissions(connection: IConnection, appId: number, collaborators: any): Promise<any> { return Promise.all(Object.keys(collaborators).map(async (collaboratorEmail) => { const userResults = await AppDAO.getUserByEmail(connection, collaboratorEmail); if (!userResults || userResults.length === 0) { throw new Error("User with email [" + collaboratorEmail + "] not found"); } const userId = userResults[0].id; await AppDAO.insertAppPermission(connection, appId, userId, collaborators[collaboratorEmail].permission); })).then(() => AppDAO.getAppPermissionsByAppId(connection, appId).then(AppDAO.transformOutgoingAppPermissions)); } /* private static async getUsersByEmails(connection: IConnection, emails: string[]): Promise<any> { return AppDAO.query(connection, UserQueries.getUsersByEmails, ["(" + emails.join(",") + ")"]); } */ private static async getUserByEmail(connection: IConnection, email: string): Promise<any> { return AppDAO.query(connection, UserQueries.getUserByEmail, [Encryptor.instance.encrypt("user.email", email)]); } private static async insertAppPermissions(connection: IConnection, appId: number, appPermissions: any[]): Promise<any> { return Promise.all(appPermissions.map((appPermission) => { return AppDAO.insertAppPermissionWithEmail(connection, appId, appPermission.email, appPermission.permission); })).then(() => AppDAO.getAppPermissionsByAppId(connection, appId).then(AppDAO.transformOutgoingAppPermissions)); } private static async insertAppPermissionWithEmail(connection: IConnection, appId: number, email: string, permission: string): Promise<any> { return AppDAO.query(connection, AppPermissionQueries.insertAppPermissionWithEmail, [appId, Encryptor.instance.encrypt("user.email", email), permission]); } private static async insertAppPermission(connection: IConnection, appId: number, userId: number, permission: string): Promise<any> { return AppDAO.query(connection, AppPermissionQueries.insertAppPermission, [appId, userId, permission]); } private static async getAppPermissionsByAppId(connection: IConnection, appId: number): Promise<any> { return AppDAO.query(connection, AppPermissionQueries.getAppPermissionsByAppId, [appId]); } private static transformOutgoingAppPermissions(permissions: any[]): any { // convert array to object with email as the key return permissions.reduce((obj, permission) => { obj[Encryptor.instance.decrypt("user.email", permission.email)] = { permission: permission.permission, }; return obj; }, {}); } private static async updateAppName(connection: IConnection, appId: number, name: string): Promise<any> { return AppDAO.query(connection, AppQueries.updateAppName, [name, appId]); } private static async updateAppPermissions(connection: IConnection, appId: number, appPermissions: any[]): Promise<any> { return Promise.all(appPermissions.map((appPermission) => { return AppDAO.updateAppPermission(connection, appId, appPermission.userId, appPermission.permission).then((updateResults) => { if (updateResults.affectedRows === 0) { return AppDAO.insertAppPermission(connection, appId, appPermission.userId, appPermission.permission); } }); })).then(() => AppDAO.getAppPermissionsByAppId(connection, appId).then(AppDAO.transformOutgoingAppPermissions)); } private static async updateAppPermission(connection: IConnection, appId: number, userId: number, permission: string): Promise<any> { return AppDAO.query(connection, AppPermissionQueries.updateAppPermission, [permission, appId, userId]); } private static async removeAppPermissionsForUsers(connection: IConnection, appId: number, emails: string[]): Promise<any> { return Promise.all(emails.map((email) => { return AppDAO.removeAppPermissionByEmail(connection, appId, email); })).then(() => AppDAO.getAppPermissionsByAppId(connection, appId).then(AppDAO.transformOutgoingAppPermissions)); } private static async removeAppPermissionByEmail(connection: IConnection, appId: number, email: string): Promise<any> { return AppDAO.query(connection, AppPermissionQueries.deleteAppPermissionByUserEmail, [appId, Encryptor.instance.encrypt("user.email", email)]); } private static async deleteAppRelated(connection: IConnection, appId: number): Promise<void> { // delete app_permission await AppDAO.query(connection, AppPermissionQueries.deleteAppPermissionByAppId, [appId]); // delete app record await AppDAO.query(connection, AppQueries.deleteApp, [appId]); } private static async deleteDeploymentRelated(connection: IConnection, appId: number): Promise<void> { const deployments = await DeploymentDAO.getDeploymentsByApp(connection, appId); await Promise.all(deployments.map(async (deployment) => { await AppDAO.deletePackageRelated(connection, deployment.id); // delete deployment_app await AppDAO.query(connection, DeploymentAppQueries.deleteDeploymentAppByDeploymentId, [deployment.id]); // delete deployment await AppDAO.query(connection, DeploymentQueries.deleteDeploymentById, [deployment.id]); })); } private static async deletePackageRelated(connection: IConnection, deploymentId: number): Promise<void> { const histories = await HistoryDAO.historyForDeployment(connection, deploymentId); await Promise.all( histories.map(async (history: any) => PackageDAO.removePackage(connection, history.package_id))); } }
the_stack
* This is an autogenerated file created by the Stencil compiler. * It contains typing information for all components that exist in this project. */ import { HTMLStencilElement, JSXBase } from "@stencil/core/internal"; import { ResizeEvent } from "./components/rp-resizable/rp-resizable"; import { ScreenSize } from "./components/ScreenSize"; export namespace Components { interface RpBrowserFrame { "backUrl"?: string; "browserTitle"?: string; "currentTab"?: number; "forwardUrl"?: string; "url"?: string; } interface RpClickOutside { } interface RpDemoViewer { "pattern"?: string; } interface RpHighlightCode { "source"?: string; } interface RpIconCode { } interface RpIconDesktop { } interface RpIconGithub { } interface RpIconLaptop { } interface RpIconLayout { "size"?: number; } interface RpIconList { } interface RpIconLive { } interface RpIconMobile { } interface RpIconNext { } interface RpIconPrevious { } interface RpIconRotate { } interface RpIconScreens { } interface RpIconTablet { } interface RpIndexPage { } interface RpLayout { } interface RpPatternPage { "pattern"?: string; } interface RpPatternSource { "pattern"?: string; } interface RpPatterns { } interface RpPulse { } interface RpResizable { } interface RpRoot { } interface RpScreens { } interface RpTooltip { "position": string; "tip"?: string; } } declare global { interface HTMLRpBrowserFrameElement extends Components.RpBrowserFrame, HTMLStencilElement { } var HTMLRpBrowserFrameElement: { prototype: HTMLRpBrowserFrameElement; new (): HTMLRpBrowserFrameElement; }; interface HTMLRpClickOutsideElement extends Components.RpClickOutside, HTMLStencilElement { } var HTMLRpClickOutsideElement: { prototype: HTMLRpClickOutsideElement; new (): HTMLRpClickOutsideElement; }; interface HTMLRpDemoViewerElement extends Components.RpDemoViewer, HTMLStencilElement { } var HTMLRpDemoViewerElement: { prototype: HTMLRpDemoViewerElement; new (): HTMLRpDemoViewerElement; }; interface HTMLRpHighlightCodeElement extends Components.RpHighlightCode, HTMLStencilElement { } var HTMLRpHighlightCodeElement: { prototype: HTMLRpHighlightCodeElement; new (): HTMLRpHighlightCodeElement; }; interface HTMLRpIconCodeElement extends Components.RpIconCode, HTMLStencilElement { } var HTMLRpIconCodeElement: { prototype: HTMLRpIconCodeElement; new (): HTMLRpIconCodeElement; }; interface HTMLRpIconDesktopElement extends Components.RpIconDesktop, HTMLStencilElement { } var HTMLRpIconDesktopElement: { prototype: HTMLRpIconDesktopElement; new (): HTMLRpIconDesktopElement; }; interface HTMLRpIconGithubElement extends Components.RpIconGithub, HTMLStencilElement { } var HTMLRpIconGithubElement: { prototype: HTMLRpIconGithubElement; new (): HTMLRpIconGithubElement; }; interface HTMLRpIconLaptopElement extends Components.RpIconLaptop, HTMLStencilElement { } var HTMLRpIconLaptopElement: { prototype: HTMLRpIconLaptopElement; new (): HTMLRpIconLaptopElement; }; interface HTMLRpIconLayoutElement extends Components.RpIconLayout, HTMLStencilElement { } var HTMLRpIconLayoutElement: { prototype: HTMLRpIconLayoutElement; new (): HTMLRpIconLayoutElement; }; interface HTMLRpIconListElement extends Components.RpIconList, HTMLStencilElement { } var HTMLRpIconListElement: { prototype: HTMLRpIconListElement; new (): HTMLRpIconListElement; }; interface HTMLRpIconLiveElement extends Components.RpIconLive, HTMLStencilElement { } var HTMLRpIconLiveElement: { prototype: HTMLRpIconLiveElement; new (): HTMLRpIconLiveElement; }; interface HTMLRpIconMobileElement extends Components.RpIconMobile, HTMLStencilElement { } var HTMLRpIconMobileElement: { prototype: HTMLRpIconMobileElement; new (): HTMLRpIconMobileElement; }; interface HTMLRpIconNextElement extends Components.RpIconNext, HTMLStencilElement { } var HTMLRpIconNextElement: { prototype: HTMLRpIconNextElement; new (): HTMLRpIconNextElement; }; interface HTMLRpIconPreviousElement extends Components.RpIconPrevious, HTMLStencilElement { } var HTMLRpIconPreviousElement: { prototype: HTMLRpIconPreviousElement; new (): HTMLRpIconPreviousElement; }; interface HTMLRpIconRotateElement extends Components.RpIconRotate, HTMLStencilElement { } var HTMLRpIconRotateElement: { prototype: HTMLRpIconRotateElement; new (): HTMLRpIconRotateElement; }; interface HTMLRpIconScreensElement extends Components.RpIconScreens, HTMLStencilElement { } var HTMLRpIconScreensElement: { prototype: HTMLRpIconScreensElement; new (): HTMLRpIconScreensElement; }; interface HTMLRpIconTabletElement extends Components.RpIconTablet, HTMLStencilElement { } var HTMLRpIconTabletElement: { prototype: HTMLRpIconTabletElement; new (): HTMLRpIconTabletElement; }; interface HTMLRpIndexPageElement extends Components.RpIndexPage, HTMLStencilElement { } var HTMLRpIndexPageElement: { prototype: HTMLRpIndexPageElement; new (): HTMLRpIndexPageElement; }; interface HTMLRpLayoutElement extends Components.RpLayout, HTMLStencilElement { } var HTMLRpLayoutElement: { prototype: HTMLRpLayoutElement; new (): HTMLRpLayoutElement; }; interface HTMLRpPatternPageElement extends Components.RpPatternPage, HTMLStencilElement { } var HTMLRpPatternPageElement: { prototype: HTMLRpPatternPageElement; new (): HTMLRpPatternPageElement; }; interface HTMLRpPatternSourceElement extends Components.RpPatternSource, HTMLStencilElement { } var HTMLRpPatternSourceElement: { prototype: HTMLRpPatternSourceElement; new (): HTMLRpPatternSourceElement; }; interface HTMLRpPatternsElement extends Components.RpPatterns, HTMLStencilElement { } var HTMLRpPatternsElement: { prototype: HTMLRpPatternsElement; new (): HTMLRpPatternsElement; }; interface HTMLRpPulseElement extends Components.RpPulse, HTMLStencilElement { } var HTMLRpPulseElement: { prototype: HTMLRpPulseElement; new (): HTMLRpPulseElement; }; interface HTMLRpResizableElement extends Components.RpResizable, HTMLStencilElement { } var HTMLRpResizableElement: { prototype: HTMLRpResizableElement; new (): HTMLRpResizableElement; }; interface HTMLRpRootElement extends Components.RpRoot, HTMLStencilElement { } var HTMLRpRootElement: { prototype: HTMLRpRootElement; new (): HTMLRpRootElement; }; interface HTMLRpScreensElement extends Components.RpScreens, HTMLStencilElement { } var HTMLRpScreensElement: { prototype: HTMLRpScreensElement; new (): HTMLRpScreensElement; }; interface HTMLRpTooltipElement extends Components.RpTooltip, HTMLStencilElement { } var HTMLRpTooltipElement: { prototype: HTMLRpTooltipElement; new (): HTMLRpTooltipElement; }; interface HTMLElementTagNameMap { "rp-browser-frame": HTMLRpBrowserFrameElement; "rp-click-outside": HTMLRpClickOutsideElement; "rp-demo-viewer": HTMLRpDemoViewerElement; "rp-highlight-code": HTMLRpHighlightCodeElement; "rp-icon-code": HTMLRpIconCodeElement; "rp-icon-desktop": HTMLRpIconDesktopElement; "rp-icon-github": HTMLRpIconGithubElement; "rp-icon-laptop": HTMLRpIconLaptopElement; "rp-icon-layout": HTMLRpIconLayoutElement; "rp-icon-list": HTMLRpIconListElement; "rp-icon-live": HTMLRpIconLiveElement; "rp-icon-mobile": HTMLRpIconMobileElement; "rp-icon-next": HTMLRpIconNextElement; "rp-icon-previous": HTMLRpIconPreviousElement; "rp-icon-rotate": HTMLRpIconRotateElement; "rp-icon-screens": HTMLRpIconScreensElement; "rp-icon-tablet": HTMLRpIconTabletElement; "rp-index-page": HTMLRpIndexPageElement; "rp-layout": HTMLRpLayoutElement; "rp-pattern-page": HTMLRpPatternPageElement; "rp-pattern-source": HTMLRpPatternSourceElement; "rp-patterns": HTMLRpPatternsElement; "rp-pulse": HTMLRpPulseElement; "rp-resizable": HTMLRpResizableElement; "rp-root": HTMLRpRootElement; "rp-screens": HTMLRpScreensElement; "rp-tooltip": HTMLRpTooltipElement; } } declare namespace LocalJSX { interface RpBrowserFrame { "backUrl"?: string; "browserTitle"?: string; "currentTab"?: number; "forwardUrl"?: string; "onActivateTabEvent"?: (event: CustomEvent<number>) => void; "onRotateEvent"?: (event: CustomEvent<any>) => void; "url"?: string; } interface RpClickOutside { "onClickOutSide"?: (event: CustomEvent<any>) => void; } interface RpDemoViewer { "pattern"?: string; } interface RpHighlightCode { "source"?: string; } interface RpIconCode { } interface RpIconDesktop { } interface RpIconGithub { } interface RpIconLaptop { } interface RpIconLayout { "size"?: number; } interface RpIconList { } interface RpIconLive { } interface RpIconMobile { } interface RpIconNext { } interface RpIconPrevious { } interface RpIconRotate { } interface RpIconScreens { } interface RpIconTablet { } interface RpIndexPage { } interface RpLayout { } interface RpPatternPage { "pattern"?: string; } interface RpPatternSource { "pattern"?: string; } interface RpPatterns { } interface RpPulse { } interface RpResizable { "onDidResizeEvent"?: (event: CustomEvent<ResizeEvent>) => void; "onResizeEvent"?: (event: CustomEvent<ResizeEvent>) => void; } interface RpRoot { } interface RpScreens { "onChooseScreenSizeEvent"?: (event: CustomEvent<ScreenSize>) => void; } interface RpTooltip { "position"?: string; "tip"?: string; } interface IntrinsicElements { "rp-browser-frame": RpBrowserFrame; "rp-click-outside": RpClickOutside; "rp-demo-viewer": RpDemoViewer; "rp-highlight-code": RpHighlightCode; "rp-icon-code": RpIconCode; "rp-icon-desktop": RpIconDesktop; "rp-icon-github": RpIconGithub; "rp-icon-laptop": RpIconLaptop; "rp-icon-layout": RpIconLayout; "rp-icon-list": RpIconList; "rp-icon-live": RpIconLive; "rp-icon-mobile": RpIconMobile; "rp-icon-next": RpIconNext; "rp-icon-previous": RpIconPrevious; "rp-icon-rotate": RpIconRotate; "rp-icon-screens": RpIconScreens; "rp-icon-tablet": RpIconTablet; "rp-index-page": RpIndexPage; "rp-layout": RpLayout; "rp-pattern-page": RpPatternPage; "rp-pattern-source": RpPatternSource; "rp-patterns": RpPatterns; "rp-pulse": RpPulse; "rp-resizable": RpResizable; "rp-root": RpRoot; "rp-screens": RpScreens; "rp-tooltip": RpTooltip; } } export { LocalJSX as JSX }; declare module "@stencil/core" { export namespace JSX { interface IntrinsicElements { "rp-browser-frame": LocalJSX.RpBrowserFrame & JSXBase.HTMLAttributes<HTMLRpBrowserFrameElement>; "rp-click-outside": LocalJSX.RpClickOutside & JSXBase.HTMLAttributes<HTMLRpClickOutsideElement>; "rp-demo-viewer": LocalJSX.RpDemoViewer & JSXBase.HTMLAttributes<HTMLRpDemoViewerElement>; "rp-highlight-code": LocalJSX.RpHighlightCode & JSXBase.HTMLAttributes<HTMLRpHighlightCodeElement>; "rp-icon-code": LocalJSX.RpIconCode & JSXBase.HTMLAttributes<HTMLRpIconCodeElement>; "rp-icon-desktop": LocalJSX.RpIconDesktop & JSXBase.HTMLAttributes<HTMLRpIconDesktopElement>; "rp-icon-github": LocalJSX.RpIconGithub & JSXBase.HTMLAttributes<HTMLRpIconGithubElement>; "rp-icon-laptop": LocalJSX.RpIconLaptop & JSXBase.HTMLAttributes<HTMLRpIconLaptopElement>; "rp-icon-layout": LocalJSX.RpIconLayout & JSXBase.HTMLAttributes<HTMLRpIconLayoutElement>; "rp-icon-list": LocalJSX.RpIconList & JSXBase.HTMLAttributes<HTMLRpIconListElement>; "rp-icon-live": LocalJSX.RpIconLive & JSXBase.HTMLAttributes<HTMLRpIconLiveElement>; "rp-icon-mobile": LocalJSX.RpIconMobile & JSXBase.HTMLAttributes<HTMLRpIconMobileElement>; "rp-icon-next": LocalJSX.RpIconNext & JSXBase.HTMLAttributes<HTMLRpIconNextElement>; "rp-icon-previous": LocalJSX.RpIconPrevious & JSXBase.HTMLAttributes<HTMLRpIconPreviousElement>; "rp-icon-rotate": LocalJSX.RpIconRotate & JSXBase.HTMLAttributes<HTMLRpIconRotateElement>; "rp-icon-screens": LocalJSX.RpIconScreens & JSXBase.HTMLAttributes<HTMLRpIconScreensElement>; "rp-icon-tablet": LocalJSX.RpIconTablet & JSXBase.HTMLAttributes<HTMLRpIconTabletElement>; "rp-index-page": LocalJSX.RpIndexPage & JSXBase.HTMLAttributes<HTMLRpIndexPageElement>; "rp-layout": LocalJSX.RpLayout & JSXBase.HTMLAttributes<HTMLRpLayoutElement>; "rp-pattern-page": LocalJSX.RpPatternPage & JSXBase.HTMLAttributes<HTMLRpPatternPageElement>; "rp-pattern-source": LocalJSX.RpPatternSource & JSXBase.HTMLAttributes<HTMLRpPatternSourceElement>; "rp-patterns": LocalJSX.RpPatterns & JSXBase.HTMLAttributes<HTMLRpPatternsElement>; "rp-pulse": LocalJSX.RpPulse & JSXBase.HTMLAttributes<HTMLRpPulseElement>; "rp-resizable": LocalJSX.RpResizable & JSXBase.HTMLAttributes<HTMLRpResizableElement>; "rp-root": LocalJSX.RpRoot & JSXBase.HTMLAttributes<HTMLRpRootElement>; "rp-screens": LocalJSX.RpScreens & JSXBase.HTMLAttributes<HTMLRpScreensElement>; "rp-tooltip": LocalJSX.RpTooltip & JSXBase.HTMLAttributes<HTMLRpTooltipElement>; } } }
the_stack
import {Oas20Document} from "../../models/2.0/document.model"; import {OasNode} from "../../models/node.model"; import {Oas20Parameter, Oas20ParameterBase, Oas20ParameterDefinition} from "../../models/2.0/parameter.model"; import {Oas20Items} from "../../models/2.0/items.model"; import {Oas20Response} from "../../models/2.0/response.model"; import {Oas20Header} from "../../models/2.0/header.model"; import {Oas20Tag} from "../../models/2.0/tag.model"; import {Oas20SecurityScheme} from "../../models/2.0/security-scheme.model"; import {OasValidationRule} from "./common.rule"; import {Oas30Document} from "../../models/3.0/document.model"; import {OasInfo} from "../../models/common/info.model"; import {OasLicense} from "../../models/common/license.model"; import {OasOperation} from "../../models/common/operation.model"; import {OasExternalDocumentation} from "../../models/common/external-documentation.model"; import {Oas30Parameter, Oas30ParameterBase, Oas30ParameterDefinition} from "../../models/3.0/parameter.model"; import {Oas30Response} from "../../models/3.0/response.model"; import {Oas30Tag} from "../../models/3.0/tag.model"; import {Oas30SecurityScheme} from "../../models/3.0/security-scheme.model"; import {Oas30Header} from "../../models/3.0/header.model"; import {Oas30Discriminator} from "../../models/3.0/discriminator.model"; import { Oas30AuthorizationCodeOAuthFlow, Oas30ClientCredentialsOAuthFlow, Oas30ImplicitOAuthFlow, Oas30OAuthFlow, Oas30PasswordOAuthFlow } from "../../models/3.0/oauth-flow.model"; import {Oas30RequestBody, Oas30RequestBodyDefinition} from "../../models/3.0/request-body.model"; import {Oas30Server} from "../../models/3.0/server.model"; import {Oas30ServerVariable} from "../../models/3.0/server-variable.model"; import {OasSchema} from "../../models/common/schema.model"; import { Oas30AdditionalPropertiesSchema, Oas30AllOfSchema, Oas30AnyOfSchema, Oas30ItemsSchema, Oas30NotSchema, Oas30OneOfSchema, Oas30PropertySchema, Oas30SchemaDefinition } from "../../models/3.0/schema.model"; /** * Base class for all Required Property rules. */ export abstract class OasRequiredPropertyValidationRule extends OasValidationRule { /** * Called when a required property is missing. * @param node * @param propertyName * @param messageProperties */ protected requireProperty(node: OasNode, propertyName: string, messageProperties?: any): void { let propertyValue: any = node[propertyName]; if (!this.isDefined(propertyValue)) { this.report(node, propertyName, messageProperties); } } /** * Called when a conditionally required property is missing. * @param node * @param propertyName * @param dependentPropertyName * @param dependentPropertyExpectedValue * @param messageProperties */ protected requirePropertyWhen(node: OasNode, propertyName: string, dependentPropertyName: string, dependentPropertyExpectedValue: any, messageProperties?: any): void { let dependentPropertyActualValue: any = node[dependentPropertyName]; if (dependentPropertyActualValue === dependentPropertyExpectedValue) { this.requireProperty(node, propertyName, messageProperties); } } } /** * Implements the Missing Property rule. */ export class OasMissingOpenApiPropertyRule extends OasRequiredPropertyValidationRule { public visitDocument(node: Oas20Document | Oas30Document): void { if (node.is2xDocument()) { this.requireProperty(node, "swagger"); } else { this.requireProperty(node, "openapi"); } } } /** * Implements the Missing Property rule. */ export class OasMissingApiInformationRule extends OasRequiredPropertyValidationRule { public visitDocument(node: Oas20Document | Oas30Document): void { this.requireProperty(node, "info"); } } /** * Implements the Missing Property rule. */ export class OasMissingApiPathsRule extends OasRequiredPropertyValidationRule { public visitDocument(node: Oas20Document | Oas30Document): void { this.requireProperty(node, "paths"); } } /** * Implements the Missing Property rule. */ export class OasMissingApiTitleRule extends OasRequiredPropertyValidationRule { public visitInfo(node: OasInfo): void { this.requireProperty(node, "title"); } } /** * Implements the Missing Property rule. */ export class OasMissingApiVersionRule extends OasRequiredPropertyValidationRule { public visitInfo(node: OasInfo): void { this.requireProperty(node, "version"); } } /** * Implements the Missing Property rule. */ export class OasMissingLicenseNameRule extends OasRequiredPropertyValidationRule { public visitLicense(node: OasLicense): void { this.requireProperty(node, "name"); } } /** * Implements the Missing Property rule. */ export class OasMissingOperationResponsesRule extends OasRequiredPropertyValidationRule { public visitOperation(node: OasOperation): void { this.requireProperty(node, "responses"); } } /** * Implements the Missing Property rule. */ export class OasMissingOperationIdRule extends OasRequiredPropertyValidationRule { public visitOperation(node: OasOperation): void { this.requireProperty(node, "operationId"); } } /** * Implements the Missing Property rule. */ export class OasMissingExternalDocumentationUrlRule extends OasRequiredPropertyValidationRule { public visitExternalDocumentation(node: OasExternalDocumentation): void { this.requireProperty(node, "url"); } } /** * Implements the Missing Property rule. */ export class OasMissingParameterNameRule extends OasRequiredPropertyValidationRule { private validateParameter(node: Oas20ParameterBase | Oas30ParameterBase): void { if (this.hasValue(node['$ref'])) { return; } this.requireProperty(node, "name"); } public visitParameter(node: Oas20Parameter | Oas30Parameter): void { this.validateParameter(node); } public visitParameterDefinition(node: Oas20ParameterDefinition | Oas30ParameterDefinition): void { this.validateParameter(node); } } /** * Implements the Missing Property rule. */ export class OasMissingParameterLocationRule extends OasRequiredPropertyValidationRule { private validateParameter(node: Oas20ParameterBase | Oas30ParameterBase): void { if (this.hasValue(node['$ref'])) { return; } this.requireProperty(node, "in"); } public visitParameter(node: Oas20Parameter | Oas30Parameter): void { this.validateParameter(node); } public visitParameterDefinition(node: Oas20ParameterDefinition | Oas30ParameterDefinition): void { this.validateParameter(node); } } /** * Implements the Missing Property rule. */ export class OasPathParamsMustBeRequiredRule extends OasRequiredPropertyValidationRule { private validateParameter(node: Oas20ParameterBase | Oas30ParameterBase): void { if (node.in === "path" && node.required !== true) { this.report(node, "required", { name: node.name }); } } public visitParameter(node: Oas20Parameter | Oas30Parameter): void { if (this.hasValue(node.$ref)) { return; } this.validateParameter(node); } public visitParameterDefinition(node: Oas20ParameterDefinition | Oas30ParameterDefinition): void { this.validateParameter(node); } } /** * Implements the Missing Property rule. */ export class OasMissingBodyParameterSchemaRule extends OasRequiredPropertyValidationRule { public visitParameter(node: Oas20Parameter): void { if (this.hasValue(node.$ref)) { return; } this.requirePropertyWhen(node, "schema", "in", "body"); } } /** * Implements the Missing Property rule. */ export class OasMissingParameterTypeRule extends OasRequiredPropertyValidationRule { public visitParameter(node: Oas20Parameter | Oas30Parameter): void { if (this.hasValue(node.$ref)) { return; } if (node.in !== "body") { this.requireProperty(node, "type", { name: node.name }); } } } /** * Implements the Missing Property rule. */ export class OasMissingParameterArrayTypeRule extends OasRequiredPropertyValidationRule { public visitParameter(node: Oas20Parameter): void { if (this.hasValue(node.$ref)) { return; } if (node.in !== "body" && node.type === "array") { this.requirePropertyWhen(node, "items", "type", "array", { name: node.name }); } } } /** * Implements the Missing Property rule. */ export class OasMissingItemsTypeRule extends OasRequiredPropertyValidationRule { public visitItems(node: Oas20Items): void { this.requireProperty(node, "type"); } } /** * Implements the Missing Property rule. */ export class OasMissingItemsArrayInformationRule extends OasRequiredPropertyValidationRule { public visitItems(node: Oas20Items): void { this.requirePropertyWhen(node, "items", "type", "array"); } } /** * Implements the Missing Property rule. */ export class OasMissingResponseDescriptionRule extends OasRequiredPropertyValidationRule { public visitResponse(node: Oas20Response | Oas30Response): void { if (this.hasValue(node.$ref)) { return; } this.requireProperty(node, "description", { statusCode: node.statusCode() }); } } /** * Implements the Missing Property rule. */ export class OasMissingHeaderTypeRule extends OasRequiredPropertyValidationRule { public visitHeader(node: Oas20Header | Oas30Header): void { if (this.hasValue(node['$ref'])) { return; } this.requireProperty(node, "type"); } } /** * Implements the Missing Property rule. */ export class OasMissingHeaderArrayInformationRule extends OasRequiredPropertyValidationRule { public visitHeader(node: Oas20Header): void { this.requirePropertyWhen(node, "items", "type", "array"); } } /** * Implements the Missing Property rule. */ export class OasMissingTagNameRule extends OasRequiredPropertyValidationRule { public visitTag(node: Oas20Tag | Oas30Tag): void { this.requireProperty(node, "name"); } } /** * Implements the Missing Property rule. */ export class OasMissingSecuritySchemeTypeRule extends OasRequiredPropertyValidationRule { public visitSecurityScheme(node: Oas20SecurityScheme | Oas30SecurityScheme): void { if (this.hasValue(node['$ref'])) { return; } this.requireProperty(node, "type"); } } /** * Implements the Missing Property rule. */ export class OasMissingApiKeySchemeParamNameRule extends OasRequiredPropertyValidationRule { public visitSecurityScheme(node: Oas20SecurityScheme | Oas30SecurityScheme): void { this.requirePropertyWhen(node, "name", "type", "apiKey"); } } /** * Implements the Missing Property rule. */ export class OasMissingApiKeySchemeParamLocationRule extends OasRequiredPropertyValidationRule { public visitSecurityScheme(node: Oas20SecurityScheme | Oas30SecurityScheme): void { this.requirePropertyWhen(node, "in", "type", "apiKey"); } } /** * Implements the Missing Property rule. */ export class OasMissingOAuthSchemeFlowTypeRule extends OasRequiredPropertyValidationRule { public visitSecurityScheme(node: Oas20SecurityScheme): void { this.requirePropertyWhen(node, "flow", "type", "oauth2"); } } /** * Implements the Missing Property rule. */ export class OasMissingOAuthSchemeAuthUrlRule extends OasRequiredPropertyValidationRule { public visitSecurityScheme(node: Oas20SecurityScheme): void { if (node.type === "oauth2") { if ((node.flow === "implicit" || node.flow === "accessCode") && !this.isDefined(node.authorizationUrl)) { this.report(node, "authorizationUrl"); } } } } /** * Implements the Missing Property rule. */ export class OasMissingOAuthSchemeTokenUrlRule extends OasRequiredPropertyValidationRule { public visitSecurityScheme(node: Oas20SecurityScheme): void { if (node.type === "oauth2") { if ((node.flow === "password" || node.flow === "application" || node.flow === "accessCode") && !this.isDefined(node.tokenUrl)) { this.report(node, "tokenUrl"); } } } } /** * Implements the Missing Property rule. */ export class OasMissingOAuthSchemeScopesRule extends OasRequiredPropertyValidationRule { public visitSecurityScheme(node: Oas20SecurityScheme): void { if (node.type === "oauth2") { this.requirePropertyWhen(node, "scopes", "type", "oauth2"); } } } /** * Implements the Missing Property rule. */ export class OasMissingDiscriminatorPropertyNameRule extends OasRequiredPropertyValidationRule { public visitDiscriminator(node: Oas30Discriminator): void { this.requireProperty(node, "propertyName"); } } /** * Implements the Missing Property rule. */ export class OasMissingOAuthFlowScopesRule extends OasRequiredPropertyValidationRule { private visitOAuthFlow(node: Oas30OAuthFlow): void { this.requireProperty(node, "scopes", ); } public visitImplicitOAuthFlow(node: Oas30ImplicitOAuthFlow): void { this.visitOAuthFlow(node); } public visitPasswordOAuthFlow(node: Oas30PasswordOAuthFlow): void { this.visitOAuthFlow(node); } public visitClientCredentialsOAuthFlow(node: Oas30ClientCredentialsOAuthFlow): void { this.visitOAuthFlow(node); } public visitAuthorizationCodeOAuthFlow(node: Oas30AuthorizationCodeOAuthFlow): void { this.visitOAuthFlow(node); } } /** * Implements the Missing Property rule. */ export class OasMissingOAuthFlowAuthUrlRule extends OasRequiredPropertyValidationRule { public visitImplicitOAuthFlow(node: Oas30ImplicitOAuthFlow): void { this.requireProperty(node, "authorizationUrl", { flowType: "Implicit" }); } public visitAuthorizationCodeOAuthFlow(node: Oas30AuthorizationCodeOAuthFlow): void { this.requireProperty(node, "authorizationUrl", { flowType: "Auth Code" }); } } /** * Implements the Missing Property rule. */ export class OasMissingOAuthFlowRokenUrlRule extends OasRequiredPropertyValidationRule { public visitPasswordOAuthFlow(node: Oas30PasswordOAuthFlow): void { this.requireProperty(node, "tokenUrl", { flowType: "Password" }); } public visitClientCredentialsOAuthFlow(node: Oas30ClientCredentialsOAuthFlow): void { this.requireProperty(node, "tokenUrl", { flowType: "Client Credentials" }); } public visitAuthorizationCodeOAuthFlow(node: Oas30AuthorizationCodeOAuthFlow): void { this.requireProperty(node, "tokenUrl", { flowType: "Auth Code" }); } } /** * Implements the Missing Property rule. */ export class OasMissingRequestBodyContentRule extends OasRequiredPropertyValidationRule { public visitRequestBody(node: Oas30RequestBody): void { this.requireProperty(node, "content"); } public visitRequestBodyDefinition(node: Oas30RequestBodyDefinition): void { this.visitRequestBody(node); } } /** * Implements the Missing Property rule. */ export class OasMissingServerTemplateUrlRule extends OasRequiredPropertyValidationRule { public visitServer(node: Oas30Server): void { this.requireProperty(node, "url"); } } /** * Implements the Missing Property rule. */ export class OasMissingHttpSecuritySchemeTypeRule extends OasRequiredPropertyValidationRule { public visitSecurityScheme(node: Oas30SecurityScheme): void { this.requirePropertyWhen(node, "scheme", "type", "http"); } } /** * Implements the Missing Property rule. */ export class OasMissingOAuthSecuritySchemeFlowsRule extends OasRequiredPropertyValidationRule { public visitSecurityScheme(node: Oas30SecurityScheme): void { this.requirePropertyWhen(node, "flows", "type", "oauth2"); } } /** * Implements the Missing Property rule. */ export class OasMissingOpenIdConnectSecuritySchemeConnectUrlRule extends OasRequiredPropertyValidationRule { public visitSecurityScheme(node: Oas30SecurityScheme): void { this.requirePropertyWhen(node, "openIdConnectUrl", "type", "openIdConnect"); } } /** * Implements the Missing Property rule. */ export class OasMissingServerVarDefaultValueRule extends OasRequiredPropertyValidationRule { public visitServerVariable(node: Oas30ServerVariable): void { this.requireProperty(node, "default", { name: node.name() }); } } /** * Implements the Missing Property rule. */ export class OasMissingSchemaArrayInformationRule extends OasRequiredPropertyValidationRule { public visitSchema(node: OasSchema): void { this.requirePropertyWhen(node, "items", "type", "array"); } public visitAllOfSchema(node: Oas30AllOfSchema): void { this.visitSchema(node); } public visitAnyOfSchema(node: Oas30AnyOfSchema): void { this.visitSchema(node); } public visitOneOfSchema(node: Oas30OneOfSchema): void { this.visitSchema(node); } public visitNotSchema(node: Oas30NotSchema): void { this.visitSchema(node); } public visitPropertySchema(node: Oas30PropertySchema): void { this.visitSchema(node); } public visitItemsSchema(node: Oas30ItemsSchema): void { this.visitSchema(node); } public visitAdditionalPropertiesSchema(node: Oas30AdditionalPropertiesSchema): void { this.visitSchema(node); } public visitSchemaDefinition(node: Oas30SchemaDefinition): void { this.visitSchema(node); } }
the_stack
import * as FS from "fs"; import * as Path from "path"; import { BuildApplicationMode, BuildLevel } from "../../ast/assembly"; import { cleanCommentsStringsFromFileContents, CodeFileInfo } from "../../ast/parser"; import { MIRAssembly, MIRInvokeDecl, MIRType, PackageConfig } from "../../compiler/mir_assembly"; import { MIREmitter, MIRKeyGenerator } from "../../compiler/mir_emitter"; import { MIRInvokeKey } from "../../compiler/mir_ops"; import { ICPPEmitter } from "../../tooling/icpp/transpiler/icppdecls_emitter"; import { TranspilerOptions } from "../../tooling/icpp/transpiler/icpp_assembly"; import { VerifierOptions } from "../../tooling/checker/smt_exp"; import { SMTEmitter } from "../../tooling/checker/smtdecls_emitter"; import { ResolvedType } from "../../ast/resolved_type"; import { ICPPTest, SMT_TIMEOUT, SMT_VOPTS_CHK, SMT_VOPTS_ERR, SymTest, SymTestInternalChkShouldFail, TestResultKind } from "./test_decls"; import { enqueueICPPTests } from "./icpp_runner"; import { enqueueSymTests } from "./sym_runner"; import * as chalk from "chalk"; type Verbosity = "std" | "extra" | "max"; type Category = "sym" | "icpp" | "err" | "chk" | "fuzz" | "symexec"; const bosque_dir: string = Path.join(__dirname, "../../../"); const icpppath: string = Path.join(bosque_dir, "/build/output/icpp" + (process.platform === "win32" ? ".exe" : "")); const smtruntime_path = Path.join(bosque_dir, "bin/tooling/checker/runtime/smtruntime.smt2"); const smtruntime = FS.readFileSync(smtruntime_path).toString(); const smtpath = Path.join(bosque_dir, "/build/output/chk" + (process.platform === "win32" ? ".exe" : "")); function workflowLoadCoreSrc(): CodeFileInfo[] | undefined { try { let code: CodeFileInfo[] = []; const coredir = Path.join(bosque_dir, "bin/core"); const corefiles = FS.readdirSync(coredir); for (let i = 0; i < corefiles.length; ++i) { const cfpath = Path.join(coredir, corefiles[i]); code.push({ srcpath: cfpath, filename: corefiles[i], contents: FS.readFileSync(cfpath).toString() }); } return code; } catch (ex) { return undefined; } } function generateMASMForICPP(buildlevel: BuildLevel, usercode: PackageConfig[], corecode: CodeFileInfo[], entrypoint: {filename: string, names: string[]}): { masm: MIRAssembly | undefined, errors: string[] } { const coreconfig = new PackageConfig(["EXEC_LIBS"], corecode); return MIREmitter.generateMASM(BuildApplicationMode.Executable, [coreconfig, ...usercode], buildlevel, entrypoint); } function generateICPPAssembly(srcCode: { fname: string, contents: string }[], masm: MIRAssembly, istestbuild: boolean, topts: TranspilerOptions, entrypoints: MIRInvokeKey[]): [boolean, any] { try { return [true, ICPPEmitter.generateICPPAssembly(srcCode, masm, istestbuild, topts, entrypoints)]; } catch(e: any) { return [false, e.toString()]; } } function generateMASMForSMT(usercode: PackageConfig[], corecode: CodeFileInfo[], buildlevel: BuildLevel, entrypoint: {filename: string, names: string[]}): { masm: MIRAssembly | undefined, errors: string[] } { const coreconfig = new PackageConfig(["CHECK_LIBS"], corecode); return MIREmitter.generateMASM(BuildApplicationMode.ModelChecker, [coreconfig, ...usercode], buildlevel, entrypoint); } function generateSMTPayload(masm: MIRAssembly, istestbuild: boolean, vopts: VerifierOptions, errorTrgtPos: { file: string, line: number, pos: number }, entrypoint: MIRInvokeKey): string | undefined { try { return SMTEmitter.generateSMTPayload(masm, istestbuild, smtruntime, vopts, errorTrgtPos, entrypoint); } catch(e) { return undefined; } } function generateCheckerPayload(masm: MIRAssembly, smtasm: string, timeout: number, entrypoint: MIRInvokeKey): any { return {smt2decl: smtasm, timeout: timeout, apimodule: masm.emitAPIInfo([entrypoint], true), "mainfunc": entrypoint}; } function runtestsICPP(buildlevel: BuildLevel, istestbuild: boolean, topts: TranspilerOptions, usercode: PackageConfig[], entrypoint: {filename: string, namespace: string, names: string[]}[], verbose: Verbosity, category: Category[], dirs: string[], cbpre: (test: ICPPTest) => void, cb: (result: "pass" | "fail" | "error", test: ICPPTest, start: Date, end: Date, icpptime: number, info?: string) => void, cbdone: (err: string | null) => void) { if(!category.includes("icpp")) { cbdone(null); return; } const corecode = workflowLoadCoreSrc(); let testsuites: {testfile: string, test: ICPPTest, apiinfo: any, icppasm: any}[] = []; //check directory is enabled const filteredentry = entrypoint.filter((testpoint) => { if(testpoint.names.length === 0) { return false; } return dirs.includes("*") || dirs.some((dname) => testpoint.filename.startsWith(dname)); }); for(let i = 0; i < filteredentry.length; ++i) { const {masm, errors} = generateMASMForICPP(buildlevel, usercode, corecode as CodeFileInfo[], filteredentry[i]); if(masm === undefined) { cbdone(errors.join("\n")); return; } const entrykeys = filteredentry[i].names.map((fname) => [fname, MIRKeyGenerator.generateFunctionKeyWNamespace(filteredentry[i].namespace, fname, new Map<string, ResolvedType>(), []).keyid]); const icppasm = generateICPPAssembly([], masm, istestbuild, topts, entrykeys.map((kp) => kp[1])); if(!icppasm[0]) { cbdone("Failed to generate ICPP assembly"); } const apiinfo = masm.emitAPIInfo(entrykeys.map((ekey) => ekey[1]), istestbuild); const runnableentries = entrykeys.filter((ekey) => { const idcl = masm.invokeDecls.get(ekey[1]); if(idcl === undefined) { return false; } //check test type is enabled if(idcl.attributes.includes("errtest") && !category.includes("err")) { return false; } if(idcl.attributes.includes("chktest") && !category.includes("chk")) { return false; } //check fuzz is enabled if(idcl.params.length !== 0 && !category.includes("fuzz")) { return false; } return true; }); const validtests = runnableentries.map((ekey) => { const idcl = masm.invokeDecls.get(ekey[1]) as MIRInvokeDecl; const rkind = idcl.attributes.includes("chktest") ? TestResultKind.ok : TestResultKind.errors; const fuzz = idcl.params.length !== 0; return { testfile: filteredentry[i].filename, test: new ICPPTest(rkind, fuzz, filteredentry[i].filename, filteredentry[i].namespace, ekey[0], ekey[1], idcl.params, masm.typeMap.get(idcl.resultType) as MIRType), apiinfo: apiinfo, icppasm: icppasm[1] }; }); validtests.forEach((tt) => { testsuites.push(tt); }); } if(testsuites.length === 0) { cbdone(null); } else { const tests = testsuites.map((ts) => { return {test: ts.test, apiinfo: ts.apiinfo, icppasm: ts.icppasm}; }); enqueueICPPTests(icpppath, tests, verbose === "max", cbpre, cb, () => cbdone(null)); } } function runtestsSMT(buildlevel: BuildLevel, istestbuild: boolean, usercode: PackageConfig[], entrypoint: {filename: string, namespace: string, names: string[]}[], verbose: Verbosity, category: Category[], dirs: string[], cbpre: (test: SymTest | SymTestInternalChkShouldFail) => void, cb: (result: "pass" | "passlimit" | "fail" | "error", test: SymTest | SymTestInternalChkShouldFail, start: Date, end: Date, smttime: number, info?: string) => void, cbdone: (err: string | null) => void) { if(!category.includes("sym")) { cbdone(null); return; } const corecode = workflowLoadCoreSrc(); let testsuites: {testfile: string, test: SymTest | SymTestInternalChkShouldFail, cpayload: any}[] = []; //check directory is enabled const filteredentry = entrypoint.filter((testpoint) => { if(testpoint.names.length === 0) { return false; } return dirs.includes("*") || dirs.some((dname) => testpoint.filename.startsWith(dname)); }); for(let i = 0; i < filteredentry.length; ++i) { const {masm, errors} = generateMASMForSMT(usercode, corecode as CodeFileInfo[], buildlevel, {filename: filteredentry[i].filename, names: filteredentry[i].names}); if(masm === undefined) { cbdone(errors.join("\n")); return; } const entrykeys = filteredentry[i].names.map((fname) => [fname, MIRKeyGenerator.generateFunctionKeyWNamespace(filteredentry[i].namespace, fname, new Map<string, ResolvedType>(), []).keyid]); const runnableentries = entrykeys.filter((ekey) => { const idcl = masm.invokeDecls.get(ekey[1]); if(idcl === undefined) { return false; } //check test type is enabled if(idcl.attributes.includes("errtest") && !category.includes("err")) { return false; } if(idcl.attributes.includes("chktest") && !category.includes("chk")) { return false; } //check symexec is enabled if(idcl.params.length === 0 && !category.includes("symexec")) { return false; } return true; }); const noerrorpos = {file: "[INGORE]", line: -1, pos: -1}; runnableentries.forEach((ekey) => { const idcl = masm.invokeDecls.get(ekey[1]) as MIRInvokeDecl; if(idcl.attributes.includes("__chktest")) { const smtasm = generateSMTPayload(masm, istestbuild, SMT_VOPTS_CHK, noerrorpos, ekey[1]); if(smtasm === undefined) { cbdone("Failed to generate SMT assembly"); } else { const smtpayload = generateCheckerPayload(masm, smtasm as string, SMT_TIMEOUT, ekey[1]); testsuites.push({ testfile: filteredentry[i].filename, test: new SymTestInternalChkShouldFail(filteredentry[i].filename, filteredentry[i].namespace, ekey[0], ekey[1], idcl.params, masm.typeMap.get(idcl.resultType) as MIRType), cpayload: smtpayload }); } } else { if(idcl.attributes.includes("chktest")) { const smtasm = generateSMTPayload(masm, istestbuild, SMT_VOPTS_CHK, noerrorpos, ekey[1]); if(smtasm === undefined) { cbdone("Failed to generate SMT assembly"); } else { const smtpayload = generateCheckerPayload(masm, smtasm as string, SMT_TIMEOUT, ekey[1]); testsuites.push({ testfile: filteredentry[i].filename, test: new SymTest(TestResultKind.ok, filteredentry[i].filename, filteredentry[i].namespace, ekey[0], ekey[1], idcl.params, masm.typeMap.get(idcl.resultType) as MIRType, smtasm, smtpayload, undefined), cpayload: smtpayload }); } } else { const errors = SMTEmitter.generateSMTAssemblyAllErrors(masm, istestbuild, SMT_VOPTS_ERR, ekey[1]); errors.forEach((errpos) => { const smtasm = generateSMTPayload(masm, istestbuild, SMT_VOPTS_ERR, errpos, ekey[1]); if(smtasm === undefined) { cbdone("Failed to generate SMT assembly"); } else { const smtpayload = generateCheckerPayload(masm, smtasm as string, SMT_TIMEOUT, ekey[1]); testsuites.push({ testfile: filteredentry[i].filename, test: new SymTest(TestResultKind.errors, filteredentry[i].filename, filteredentry[i].namespace, ekey[0], ekey[1], idcl.params, masm.typeMap.get(idcl.resultType) as MIRType, smtasm, smtpayload, errpos), cpayload: smtpayload }); } }); } } }); } if(testsuites.length === 0) { cbdone(null); } else { const tests = testsuites.map((ts) => { return {test: ts.test, cpayload: ts.cpayload}; }); enqueueSymTests(smtpath, tests, verbose === "max", cbpre, cb, () => cbdone(null)); } } function outputResultsAndExit(verbose: Verbosity, totaltime: number, totalicpp: number, failedicpp: {test: ICPPTest, info: string}[], erroricpp: {test: ICPPTest, info: string}[], totalsmt: number, passlimitsmt: number, failedsmt: {test: (SymTest | SymTestInternalChkShouldFail), info: string}[], errorsmt: {test: (SymTest | SymTestInternalChkShouldFail), info: string}[]) { if(verbose !== "std") { process.stdout.write("\n"); } process.stdout.write(`Ran ${totalicpp + totalsmt} tests in ${totaltime}s ...\n\n`); process.stdout.write(`Ran ${totalicpp} executable tests ...\n`); if (failedicpp.length === 0 && erroricpp.length === 0) { process.stdout.write(chalk.green(chalk.bold("All executable tests pass!\n\n"))); } else { if(failedicpp.length !== 0) { process.stdout.write(chalk.bold(`Suite had ${failedicpp.length}`) + " " + chalk.red("executable test failures") + "\n"); const rstr = failedicpp.map((tt) => `${tt.test.namespace}::${tt.test.fname} -- "${tt.info}"`).join("\n "); process.stdout.write(" " + rstr + "\n\n"); } if(erroricpp.length !== 0) { process.stdout.write(chalk.bold(`Suite had ${erroricpp.length}`) + " " + chalk.magenta("executable test errors") + "\n"); const rstr = erroricpp.map((tt) => `${tt.test.namespace}::${tt.test.fname} -- "${tt.info}"`).join("\n "); process.stdout.write(" " + rstr + "\n\n"); } } process.stdout.write(`Ran ${totalsmt} symbolic tests...\n`); if (failedsmt.length === 0 && errorsmt.length === 0) { if(passlimitsmt === 0) { process.stdout.write(chalk.green(chalk.bold("All symbolic tests pass!\n\n"))); } else { process.stdout.write(chalk.green(chalk.bold(`${totalsmt - passlimitsmt} symbolic tests pass!\n`))); process.stdout.write(chalk.blue(chalk.bold(`${passlimitsmt} symbolic tests report no error found in resource limit!\n\n`))); } } else { if(failedsmt.length !== 0) { process.stdout.write(chalk.bold(`Suite had ${failedsmt.length}`) + " " + chalk.red("symbolic test failures") + "\n"); const rstr = failedsmt.map((tt) => { let infostr = tt.info; try { infostr = JSON.stringify(JSON.parse(tt.info), undefined, 2); } catch (ex) { ; } const tname = chalk.bold(`${tt.test.namespace}::${tt.test.fname}`); return `---- ${tname} ----\n"${infostr}"`; }).join("\n"); process.stdout.write(rstr + "\n\n"); } if(errorsmt.length !== 0) { process.stdout.write(chalk.bold(`Suite had ${errorsmt.length}`) + " " + chalk.magenta("symbolic test errors") + "\n"); const rstr = errorsmt.map((tt) => { const tname = chalk.bold(`${tt.test.namespace}::${tt.test.fname}`); return`${tname} -- "${tt.info}"` }).join("\n "); process.stdout.write(rstr + "\n\n"); } } if(failedicpp.length !== 0 || erroricpp.length !== 0 || failedsmt.length !== 0 || errorsmt.length !== 0) { process.exit(1); } process.exit(0); } function loadUserPackageSrc(files: string[], macrodefs: string[], globalmacros: string[]): PackageConfig | undefined { try { let code: CodeFileInfo[] = []; for (let i = 0; i < files.length; ++i) { const realpath = Path.resolve(files[i]); code.push({ srcpath: realpath, filename: Path.basename(files[i]), contents: FS.readFileSync(realpath).toString() }); } return new PackageConfig([...macrodefs, ...globalmacros], code); } catch (ex) { return undefined; } } function loadEntryPointInfo(files: string[], istestbuild: boolean): {filename: string, namespace: string, names: string[]}[] | undefined { try { let epi: {filename: string, namespace: string, names: string[]}[] = []; for(let i = 0; i < files.length; ++i) { const contents = cleanCommentsStringsFromFileContents(FS.readFileSync(files[i]).toString()); const namespacere = /namespace([ \t]+)(?<nsstr>(([A-Z][_a-zA-Z0-9]+)::)*([A-Z][_a-zA-Z0-9]+));/; const entryre = /(entrypoint|chktest|errtest|__chktest)(\s+)function(\s+)(?<fname>([_a-z]|([_a-z][_a-zA-Z0-9]*[a-zA-Z0-9])))(\s*)\(/g; const ns = namespacere.exec(contents); if(ns === null || ns.groups === undefined || ns.groups.nsstr === undefined) { return undefined; } const nsstr = ns.groups.nsstr; let names: string[] = []; let mm: RegExpExecArray | null = null; entryre.lastIndex = 0; mm = entryre.exec(contents); while(mm !== null) { if(mm.groups === undefined || mm.groups.fname === undefined) { return undefined; } if(mm[0].startsWith("entrypoint") || istestbuild) { names.push(mm.groups.fname); } entryre.lastIndex += mm[0].length; mm = entryre.exec(contents); } epi.push({filename: files[i], namespace: nsstr, names: names}); } return epi; } catch (ex) { return undefined; } } function runtests(packageloads: {macros: string[], files: string[]}[], globalmacros: string[], entrypointfiles: string[], buildlevel: BuildLevel, istestbuild: boolean, topts: TranspilerOptions, verbose: Verbosity, category: Category[], dirs: string[]) { let totalicpp = 0; let failedicpp: {test: ICPPTest, info: string}[] = []; let erroricpp: {test: ICPPTest, info: string}[] = []; let totalsmt = 0; let passlimitsmt = 0; let failedsmt: {test: (SymTest | SymTestInternalChkShouldFail), info: string}[] = []; let errorsmt: {test: (SymTest | SymTestInternalChkShouldFail), info: string}[] = []; const start = new Date(); const usersrc = packageloads.map((psrc) => loadUserPackageSrc(psrc.files.map((src) => src), psrc.macros, globalmacros)); if(usersrc.includes(undefined)) { process.stdout.write(chalk.red("Failure loading user packages\n")); process.exit(1); } const entrypoints = loadEntryPointInfo(entrypointfiles, istestbuild); if(entrypoints === undefined) { process.stdout.write(chalk.red("Failure loading entrypoints\n")); process.exit(1); } const cbpre_smt = (tt: SymTest | SymTestInternalChkShouldFail) => { process.stdout.write(`Starting ${tt.namespace}::${tt.fname}...\n`); }; const cb_smt = (result: "pass" | "passlimit" | "fail" | "error", test: SymTest | SymTestInternalChkShouldFail, start: Date, end: Date, smtime: number, info?: string) => { totalsmt++; if(result === "pass") { ; } else if(result === "passlimit") { passlimitsmt++; } else if(result === "fail") { failedsmt.push({test: test, info: info || "[Missing Info]"}); } else { errorsmt.push({test: test, info: info || "[Missing Info]"}); } if(verbose !== "std") { let rstr = ""; if(result === "pass") { rstr = chalk.green("pass"); } else if(result === "passlimit") { rstr = chalk.blue("no error found"); } else if(result === "fail") { rstr = chalk.red("fail"); } else { rstr = chalk.magenta("error"); } if(test instanceof SymTestInternalChkShouldFail) { process.stdout.write(`Symbolic test ${test.namespace}::${test.fname} completed with ${rstr} in ${smtime}ms (${end.getTime() - start.getTime()}ms elapsed)\n`); } else { if(test.trgterror === undefined) { process.stdout.write(`Symbolic test ${test.namespace}::${test.fname} completed with ${rstr} in ${smtime}ms (${end.getTime() - start.getTime()}ms elapsed)\n`); } else { process.stdout.write(`Symbolic test completed with ${rstr} in ${smtime}ms (${end.getTime() - start.getTime()}ms elapsed)\n`); if(result === "fail") { process.stdout.write(` Error was ${test.trgterror.msg} in ${Path.basename(test.trgterror.file)}@${test.trgterror.line} from ${test.namespace}::${test.fname} entrypoint\n`); } } } } }; const cbdone_smt = (err: string | null) => { if(err !== null) { process.stdout.write(chalk.red("Hard failure loading Symbolic tests --\n")); process.stdout.write(" " + err + "\n"); process.exit(1); } else { const end = new Date(); const totaltime = (end.getTime() - start.getTime()) / 1000; outputResultsAndExit(verbose, totaltime, totalicpp, failedicpp, erroricpp, totalsmt, passlimitsmt, failedsmt, errorsmt); } }; const cbpre_icpp = (tt: ICPPTest) => { process.stdout.write(`Starting ${tt.namespace}::${tt.fname}...\n`); }; const cb_icpp = (result: "pass" | "fail" | "error", test: ICPPTest, start: Date, end: Date, icpptime: number, info?: string) => { totalicpp++; if(result === "pass") { ; } else if(result === "fail") { failedicpp.push({test: test, info: info || "[Missing Info]"}); } else { erroricpp.push({test: test, info: info || "[Missing Info]"}); } if(verbose !== "std") { let rstr = ""; if(result === "pass") { rstr = chalk.green("pass"); } else if(result === "fail") { rstr = chalk.red("fail"); } else { rstr = chalk.magenta("error"); } process.stdout.write(`Executable test ${test.namespace}::${test.fname} completed with ${rstr} in ${icpptime}ms (${end.getTime() - start.getTime()}ms elapsed)\n`); } }; const cbdone_icpp = (err: string | null) => { if(err !== null) { process.stdout.write(chalk.red("Hard failure loading ICPP tests --\n")); process.stdout.write(" " + err + "\n"); process.exit(1); } else { runtestsSMT(buildlevel, istestbuild, usersrc as PackageConfig[], entrypoints, verbose, category, dirs, cbpre_smt, cb_smt, cbdone_smt); } }; runtestsICPP(buildlevel, istestbuild, topts, usersrc as PackageConfig[], entrypoints, verbose, category, dirs, cbpre_icpp, cb_icpp, cbdone_icpp); } export { Verbosity, Category, runtests };
the_stack
import Item from './item'; import TweetTextParser, {TweetTextToken} from '../tweet_parser'; import {Twitter} from 'twit'; const shell = global.require('electron').shell; const re_normal_size = /normal(?=\.\w+$)/i; const re_size_part = /_normal(?=\.\w+$)/i; function truncateCount(count: number) { if (count >= 1000000) { return (Math.floor(count / 100000) / 10) + 'M'; } else if (count >= 1000) { return (Math.floor(count / 100) / 10) + 'K'; } else if (count === 0) { return ''; } else { return count.toString(); } } export class TwitterUser { constructor(public json: Twitter.User) {} get original_icon_url() { return this.json.profile_image_url.replace(re_size_part, ''); } get icon_url() { const url = this.json.profile_image_url; if (window.devicePixelRatio < 1.5) { return url; } else { return url.replace(re_normal_size, 'bigger'); } } get mini_icon_url() { if (window.devicePixelRatio < 1.5) { return this.icon_url_24x24; } else { return this.icon_url_48x48; } } get icon_url_73x73() { return this.json.profile_image_url.replace(re_normal_size, 'bigger'); } get icon_url_48x48() { return this.json.profile_image_url; } get icon_url_24x24() { return this.json.profile_image_url.replace(re_normal_size, 'mini'); } get screen_name() { return this.json.screen_name; } get protected() { return this.json.protected; } get name() { return this.json.name; } get id() { return this.json.id; } get max_size_banner_url() { if (!this.json.profile_banner_url) { return null; } // Note: Currently 1500x500 is biggest banner image. return this.json.profile_banner_url + '/1500x500'; } get big_banner_url() { return this.getBannerUrl('web'); } get mini_banner_url() { return this.getBannerUrl('mobile'); } get bg_color() { return this.json.profile_background_color; } get description() { return this.json.description; } get statuses_count() { return truncateCount(this.json.statuses_count); } get likes_count() { return truncateCount(this.json.favourites_count); } get followings_count() { return this.json.friends_count; } get followers_count() { return this.json.followers_count; } get link_color() { return this.json.profile_link_color; } get user_site_url(): Twitter.UrlEntity | null { if (this.json.entities && this.json.entities.url && this.json.entities.url.urls!.length > 0) { return this.json.entities.url.urls![0]; } else if (this.json.url) { // Note: fallback return { display_url: this.json.url, expanded_url: this.json.url, indices: null, url: this.json.url, }; } else { return null; } } get location() { return this.json.location; } followingPageUrl() { return `https://twitter.com/${this.json.screen_name}/following`; } followerPageUrl() { return `https://twitter.com/${this.json.screen_name}/followers`; } likePageUrl() { return `https://twitter.com/${this.json.screen_name}/likes`; } userPageUrl() { return `https://twitter.com/${this.json.screen_name}`; } openUserPageInBrowser() { shell.openExternal(this.userPageUrl()); } openWebsiteInBrowser() { const url = this.user_site_url; if (url === null) { return; } shell.openExternal(url.expanded_url); } private getBannerUrl(label: string) { if (!this.json.profile_banner_url) { return null; } const size = window.devicePixelRatio < 1.5 ? `/${label}` : `/${label}_retina`; return this.json.profile_banner_url + size; } } export default class Tweet implements Item { public user: TwitterUser; public related_statuses: Tweet[]; public in_reply_to_status: Tweet | null; private retweeted_status_memo: Tweet | null; private quoted_status_memo: Tweet | null; private parsed_tokens_memo: TweetTextToken[] | null; private created_at_memo: Date | null; constructor(public json: Twitter.Status) { this.user = new TwitterUser(json.user); this.retweeted_status_memo = null; this.quoted_status_memo = null; this.parsed_tokens_memo = null; this.created_at_memo = null; this.related_statuses = []; this.in_reply_to_status = null; } get id() { return this.json.id_str; } get created_at() { if (this.created_at_memo === null) { const created_at = this.json.created_at; if (created_at !== undefined) { this.created_at_memo = new Date(created_at); } } return this.created_at_memo!; } get retweeted() { return this.json.retweeted; } get favorited() { return this.json.favorited; } get retweeted_status() { if (!this.json.retweeted_status) { return null; } if (this.retweeted_status_memo === null) { this.retweeted_status_memo = new Tweet(this.json.retweeted_status); } return this.retweeted_status_memo; } get retweet_count() { if (this.json.retweeted_status) { return this.json.retweeted_status.retweet_count; } else { return this.json.retweet_count; } } get favorite_count() { if (this.json.retweeted_status) { return this.json.retweeted_status.favorite_count; } else { return this.json.favorite_count; } } get quoted_status() { if (!this.json.quoted_status) { return null; } if (this.quoted_status_memo === null) { this.quoted_status_memo = new Tweet(this.json.quoted_status); } return this.quoted_status_memo; } get parsed_tokens() { if (this.parsed_tokens_memo === null) { const parser = new TweetTextParser(this.json); this.parsed_tokens_memo = parser.parse(); this.json.text = parser.text; } return this.parsed_tokens_memo; } get in_reply_to_status_id() { return this.json.in_reply_to_status_id_str; } get in_reply_to_user_id() { return this.json.in_reply_to_user_id; } get text() { return this.json.text; } get urls() { const json = this.getMainJson(); if (!json.entities || !json.entities.urls) { return []; } return json.entities.urls; } get media() { if (!this.json.extended_entities) { return []; } if (!this.json.extended_entities.media) { return []; } return this.json.extended_entities.media; } get mentions() { if (!this.json.entities || !this.json.entities.user_mentions) { return []; } return this.json.entities.user_mentions; } get hashtags() { if (!this.json.entities || !this.json.entities.hashtags) { return []; } return this.json.entities.hashtags; } getMainStatus() { if (this.json.retweeted_status) { return this.retweeted_status!; } else { return this; } } getMainJson(): Twitter.Status { return this.json.retweeted_status || this.json; } isRetweet() { return !!this.json.retweeted_status; } isQuotedTweet() { return !!this.json.quoted_status; } getRetweetedUser() { if (!this.json.retweeted_status) { return null; } return this.user; } hasQuote() { return !!this.json.quoted_status; } hasInReplyTo() { return !!this.json.in_reply_to_status_id_str; } mentionsTo(user: TwitterUser) { const my_id = user.id; if (this.json.in_reply_to_user_id === my_id) { return true; } if (this.json.retweeted_status && this.json.retweeted_status.user.id === my_id) { return true; } if (this.json.quoted_status && this.json.quoted_status.user.id === my_id) { return true; } if (this.json.entities && this.json.entities.user_mentions) { for (const m of this.json.entities.user_mentions) { if (m.id === my_id) { return true; } } } return false; } getCreatedAtString() { const date = this.created_at; const hh = date.getHours(); const mm = date.getMinutes(); const m = date.getMonth(); const d = date.getDate(); const yyyy = date.getFullYear(); return `${('0' + hh).slice(-2)}:${('0' + mm).slice(-2)} ${m + 1}/${d} ${yyyy}`; } statusPageUrl() { return `https://twitter.com/${this.json.user.screen_name}/status/${this.getMainStatus().json.id_str}`; } openStatusPageInBrowser() { shell.openExternal(this.statusPageUrl()); } openAllLinksInBrowser() { for (const u of this.urls.map(u => u.expanded_url)) { shell.openExternal(u); } } getChainedRelatedStatuses() { const push = Array.prototype.push; let ret = [] as Tweet[]; for (const s of this.related_statuses) { push.apply(ret, s.getChainedRelatedStatuses()); } push.apply(ret, this.related_statuses); return ret.sort((l, r) => -l.compareId(r)); } // -1: lhs.id < rhs.id // 0: lhs.id == rhs.id // 1: lhs.id > rhs.id compareId(rhs: Tweet) { const s = Math.floor(this.json.id_str.length / 2); const lh = parseInt(this.json.id_str.slice(0, s), 10); const rh = parseInt(rhs.json.id_str.slice(0, s), 10); let v = lh - rh; if (v === 0) { const ll = parseInt(this.json.id_str.slice(s), 10); const rl = parseInt(rhs.json.id_str.slice(s), 10); v = ll - rl; } return v < 0 ? -1 : v > 0 ? 1 : 0; } clone() { const cloned = new Tweet(this.json); cloned.related_statuses = this.related_statuses; cloned.in_reply_to_status = this.in_reply_to_status; return cloned; } }
the_stack
import {absoluteFrom} from '@angular/compiler-cli/src/ngtsc/file_system'; import {runInEachFileSystem} from '@angular/compiler-cli/src/ngtsc/file_system/testing'; import {ɵParsedMessage, ɵSourceLocation} from '@angular/localize'; import {FormatOptions} from '../../../src/extract/translation_files/format_options'; import {Xliff2TranslationSerializer} from '../../../src/extract/translation_files/xliff2_translation_serializer'; import {location, mockMessage} from './mock_message'; import {toAttributes} from './utils'; runInEachFileSystem(() => { describe('Xliff2TranslationSerializer', () => { ([{}, {'xml:space': 'preserve'}] as FormatOptions[]).forEach(options => { [false, true].forEach(useLegacyIds => { describe(`renderFile() [using ${useLegacyIds ? 'legacy' : 'canonical'} ids]`, () => { it('should convert a set of parsed messages into an XML string', () => { const phLocation: ɵSourceLocation = { start: {line: 0, column: 10}, end: {line: 1, column: 15}, file: absoluteFrom('/project/file.ts'), text: 'placeholder + 1' }; const messagePartLocation: ɵSourceLocation = { start: {line: 0, column: 5}, end: {line: 0, column: 10}, file: absoluteFrom('/project/file.ts'), text: 'message part' }; const messages: ɵParsedMessage[] = [ mockMessage('12345', ['a', 'b', 'c'], ['PH', 'PH_1'], { meaning: 'some meaning', location: { file: absoluteFrom('/project/file.ts'), start: {line: 5, column: 0}, end: {line: 5, column: 3} }, legacyIds: ['1234567890ABCDEF1234567890ABCDEF12345678', '615790887472569365'], }), mockMessage('54321', ['a', 'b', 'c'], ['PH', 'PH_1'], { customId: 'someId', legacyIds: ['87654321FEDCBA0987654321FEDCBA0987654321', '563965274788097516'], messagePartLocations: [undefined, messagePartLocation, undefined], substitutionLocations: {'PH': phLocation, 'PH_1': undefined}, }), mockMessage('67890', ['a', '', 'c'], ['START_TAG_SPAN', 'CLOSE_TAG_SPAN'], { description: 'some description', location: { file: absoluteFrom('/project/file.ts'), start: {line: 2, column: 7}, end: {line: 3, column: 2} } }), mockMessage('location-only', ['a', '', 'c'], ['START_TAG_SPAN', 'CLOSE_TAG_SPAN'], { location: { file: absoluteFrom('/project/file.ts'), start: {line: 2, column: 7}, end: {line: 3, column: 2} } }), mockMessage('13579', ['', 'b', ''], ['START_BOLD_TEXT', 'CLOSE_BOLD_TEXT'], {}), mockMessage('24680', ['a'], [], {meaning: 'meaning', description: 'and description'}), mockMessage('80808', ['multi\nlines'], [], {}), mockMessage('90000', ['<escape', 'me>'], ['double-quotes-"'], {}), mockMessage( '100000', ['pre-ICU ', ' post-ICU'], ['ICU'], {associatedMessageIds: {ICU: 'SOME_ICU_ID'}}), mockMessage( 'SOME_ICU_ID', [ '{VAR_SELECT, select, a {a} b {{INTERPOLATION}} c {pre {INTERPOLATION_1} post}}' ], [], {}), mockMessage( '100001', [ '{VAR_PLURAL, plural, one {{START_BOLD_TEXT}something bold{CLOSE_BOLD_TEXT}} other {pre {START_TAG_SPAN}middle{CLOSE_TAG_SPAN} post}}' ], [], {}), ]; const serializer = new Xliff2TranslationSerializer( 'xx', absoluteFrom('/project'), useLegacyIds, options); const output = serializer.serialize(messages); expect(output.split(/\r?\n/)).toEqual([ `<?xml version="1.0" encoding="UTF-8" ?>`, `<xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0" srcLang="xx">`, ` <file id="ngi18n" original="ng.template"${toAttributes(options)}>`, ` <unit id="someId">`, ` <segment>`, ` <source>a<ph id="0" equiv="PH" disp="placeholder + 1"/>b<ph id="1" equiv="PH_1"/>c</source>`, ` </segment>`, ` </unit>`, ` <unit id="13579">`, ` <segment>`, ` <source><pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt">b</pc></source>`, ` </segment>`, ` </unit>`, ` <unit id="24680">`, ` <notes>`, ` <note category="description">and description</note>`, ` <note category="meaning">meaning</note>`, ` </notes>`, ` <segment>`, ` <source>a</source>`, ` </segment>`, ` </unit>`, ` <unit id="80808">`, ` <segment>`, ` <source>multi`, `lines</source>`, ` </segment>`, ` </unit>`, ` <unit id="90000">`, ` <segment>`, ` <source>&lt;escape<ph id="0" equiv="double-quotes-&quot;"/>me&gt;</source>`, ` </segment>`, ` </unit>`, ` <unit id="100000">`, ` <segment>`, ` <source>pre-ICU <ph id="0" equiv="ICU" subFlows="SOME_ICU_ID"/> post-ICU</source>`, ` </segment>`, ` </unit>`, ` <unit id="SOME_ICU_ID">`, ` <segment>`, ` <source>{VAR_SELECT, select, a {a} b {<ph id="0" equiv="INTERPOLATION"/>} c {pre <ph id="1" equiv="INTERPOLATION_1"/> post}}</source>`, ` </segment>`, ` </unit>`, ` <unit id="100001">`, ` <segment>`, ` <source>{VAR_PLURAL, plural, one {<pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt">something bold</pc>} other {pre <pc id="1" equivStart="START_TAG_SPAN" equivEnd="CLOSE_TAG_SPAN" type="other">middle</pc> post}}</source>`, ` </segment>`, ` </unit>`, ` <unit id="67890">`, ` <notes>`, ` <note category="location">file.ts:3,4</note>`, ` <note category="description">some description</note>`, ` </notes>`, ` <segment>`, ` <source>a<pc id="0" equivStart="START_TAG_SPAN" equivEnd="CLOSE_TAG_SPAN" type="other"></pc>c</source>`, ` </segment>`, ` </unit>`, ` <unit id="location-only">`, ` <notes>`, ` <note category="location">file.ts:3,4</note>`, ` </notes>`, ` <segment>`, ` <source>a<pc id="0" equivStart="START_TAG_SPAN" equivEnd="CLOSE_TAG_SPAN" type="other"></pc>c</source>`, ` </segment>`, ` </unit>`, ` <unit id="${useLegacyIds ? '615790887472569365' : '12345'}">`, ` <notes>`, ` <note category="location">file.ts:6</note>`, ` <note category="meaning">some meaning</note>`, ` </notes>`, ` <segment>`, ` <source>a<ph id="0" equiv="PH"/>b<ph id="1" equiv="PH_1"/>c</source>`, ` </segment>`, ` </unit>`, ` </file>`, `</xliff>`, ``, ]); }); it('should convert a set of parsed messages into an XML string', () => { const messageLocation1: ɵSourceLocation = { start: {line: 0, column: 5}, end: {line: 0, column: 10}, file: absoluteFrom('/project/file-1.ts'), text: 'message text' }; const messageLocation2: ɵSourceLocation = { start: {line: 3, column: 2}, end: {line: 4, column: 7}, file: absoluteFrom('/project/file-2.ts'), text: 'message text' }; const messageLocation3: ɵSourceLocation = { start: {line: 0, column: 5}, end: {line: 0, column: 10}, file: absoluteFrom('/project/file-3.ts'), text: 'message text' }; const messageLocation4: ɵSourceLocation = { start: {line: 3, column: 2}, end: {line: 4, column: 7}, file: absoluteFrom('/project/file-4.ts'), text: 'message text' }; const messages: ɵParsedMessage[] = [ mockMessage('1234', ['message text'], [], {location: messageLocation1}), mockMessage('1234', ['message text'], [], {location: messageLocation2}), mockMessage('1234', ['message text'], [], { location: messageLocation3, legacyIds: ['87654321FEDCBA0987654321FEDCBA0987654321', '563965274788097516'] }), mockMessage( '1234', ['message text'], [], {location: messageLocation4, customId: 'other'}), ]; const serializer = new Xliff2TranslationSerializer( 'xx', absoluteFrom('/project'), useLegacyIds, options); const output = serializer.serialize(messages); // Note that in this test the third message will match the first two if legacyIds is // false. Otherwise it will be a separate message on its own. expect(output).toEqual([ `<?xml version="1.0" encoding="UTF-8" ?>`, `<xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0" srcLang="xx">`, ` <file id="ngi18n" original="ng.template"${toAttributes(options)}>`, ` <unit id="1234">`, ` <notes>`, ` <note category="location">file-1.ts:1</note>`, ` <note category="location">file-2.ts:4,5</note>`, ...useLegacyIds ? [] : [' <note category="location">file-3.ts:1</note>'], ` </notes>`, ` <segment>`, ` <source>message text</source>`, ` </segment>`, ` </unit>`, ...useLegacyIds ? [ ` <unit id="563965274788097516">`, ` <notes>`, ` <note category="location">file-3.ts:1</note>`, ` </notes>`, ` <segment>`, ` <source>message text</source>`, ` </segment>`, ` </unit>`, ] : [], ` <unit id="other">`, ` <notes>`, ` <note category="location">file-4.ts:4,5</note>`, ` </notes>`, ` <segment>`, ` <source>message text</source>`, ` </segment>`, ` </unit>`, ` </file>`, `</xliff>\n`, ].join('\n')); }); it('should render the "type" for line breaks', () => { const serializer = new Xliff2TranslationSerializer( 'xx', absoluteFrom('/project'), useLegacyIds, options); const output = serializer.serialize([mockMessage('1', ['a', 'b'], ['LINE_BREAK'], {})]); expect(output).toContain( '<source>a<ph id="0" equiv="LINE_BREAK" type="fmt"/>b</source>', ); }); it('should render the "type" for images', () => { const serializer = new Xliff2TranslationSerializer( 'xx', absoluteFrom('/project'), useLegacyIds, options); const output = serializer.serialize([mockMessage('2', ['a', 'b'], ['TAG_IMG'], {})]); expect(output).toContain( '<source>a<ph id="0" equiv="TAG_IMG" type="image"/>b</source>', ); }); it('should render the "type" for bold elements', () => { const serializer = new Xliff2TranslationSerializer( 'xx', absoluteFrom('/project'), useLegacyIds, options); const output = serializer.serialize( [mockMessage('3', ['a', 'b', 'c'], ['START_BOLD_TEXT', 'CLOSE_BOLD_TEXT'], {})]); expect(output).toContain( '<source>a<pc id="0" equivStart="START_BOLD_TEXT" equivEnd="CLOSE_BOLD_TEXT" type="fmt">b</pc>c</source>', ); }); it('should render the "type" for heading elements', () => { const serializer = new Xliff2TranslationSerializer( 'xx', absoluteFrom('/project'), useLegacyIds, options); const output = serializer.serialize([mockMessage( '4', ['a', 'b', 'c'], ['START_HEADING_LEVEL1', 'CLOSE_HEADING_LEVEL1'], {})]); expect(output).toContain( '<source>a<pc id="0" equivStart="START_HEADING_LEVEL1" equivEnd="CLOSE_HEADING_LEVEL1" type="other">b</pc>c</source>', ); }); it('should render the "type" for span elements', () => { const serializer = new Xliff2TranslationSerializer( 'xx', absoluteFrom('/project'), useLegacyIds, options); const output = serializer.serialize( [mockMessage('5', ['a', 'b', 'c'], ['START_TAG_SPAN', 'CLOSE_TAG_SPAN'], {})]); expect(output).toContain( '<source>a<pc id="0" equivStart="START_TAG_SPAN" equivEnd="CLOSE_TAG_SPAN" type="other">b</pc>c</source>', ); }); it('should render the "type" for div elements', () => { const serializer = new Xliff2TranslationSerializer( 'xx', absoluteFrom('/project'), useLegacyIds, options); const output = serializer.serialize( [mockMessage('6', ['a', 'b', 'c'], ['START_TAG_DIV', 'CLOSE_TAG_DIV'], {})]); expect(output).toContain( '<source>a<pc id="0" equivStart="START_TAG_DIV" equivEnd="CLOSE_TAG_DIV" type="other">b</pc>c</source>', ); }); it('should render the "type" for link elements', () => { const serializer = new Xliff2TranslationSerializer( 'xx', absoluteFrom('/project'), useLegacyIds, options); const output = serializer.serialize( [mockMessage('6', ['a', 'b', 'c'], ['START_LINK', 'CLOSE_LINK'], {})]); expect(output).toContain( '<source>a<pc id="0" equivStart="START_LINK" equivEnd="CLOSE_LINK" type="link">b</pc>c</source>', ); }); it('should render generic close tag placeholders for additional elements', () => { const serializer = new Xliff2TranslationSerializer( 'xx', absoluteFrom('/project'), useLegacyIds, options); const output = serializer.serialize([mockMessage( '6', ['a', 'b', 'c', 'd', 'e'], ['START_LINK', 'CLOSE_LINK', 'START_LINK_1', 'CLOSE_LINK'], {})]); expect(output).toContain( '<source>a<pc id="0" equivStart="START_LINK" equivEnd="CLOSE_LINK" type="link">b</pc>c<pc id="1" equivStart="START_LINK_1" equivEnd="CLOSE_LINK" type="link">d</pc>e</source>', ); }); }); }); }); describe('renderFile()', () => { it('should consistently order serialized messages by location', () => { const messages: ɵParsedMessage[] = [ mockMessage('1', ['message-1'], [], {location: location('/root/c-1.ts', 5, 10, 5, 12)}), mockMessage('2', ['message-1'], [], {location: location('/root/c-2.ts', 5, 10, 5, 12)}), mockMessage('1', ['message-1'], [], {location: location('/root/b-1.ts', 8, 0, 10, 12)}), mockMessage('2', ['message-1'], [], {location: location('/root/b-2.ts', 8, 0, 10, 12)}), mockMessage('1', ['message-1'], [], {location: location('/root/a-1.ts', 5, 10, 5, 12)}), mockMessage('2', ['message-1'], [], {location: location('/root/a-2.ts', 5, 10, 5, 12)}), mockMessage('1', ['message-1'], [], {location: location('/root/b-1.ts', 5, 10, 5, 12)}), mockMessage('2', ['message-1'], [], {location: location('/root/b-2.ts', 5, 10, 5, 12)}), mockMessage('1', ['message-1'], [], {location: location('/root/b-1.ts', 5, 20, 5, 12)}), mockMessage('2', ['message-1'], [], {location: location('/root/b-2.ts', 5, 20, 5, 12)}), ]; const serializer = new Xliff2TranslationSerializer('xx', absoluteFrom('/root'), false, {}); const output = serializer.serialize(messages); expect(output.split('\n')).toEqual([ '<?xml version="1.0" encoding="UTF-8" ?>', '<xliff version="2.0" xmlns="urn:oasis:names:tc:xliff:document:2.0" srcLang="xx">', ' <file id="ngi18n" original="ng.template">', ' <unit id="1">', ' <notes>', ' <note category="location">a-1.ts:6</note>', ' <note category="location">b-1.ts:6</note>', ' <note category="location">b-1.ts:6</note>', ' <note category="location">b-1.ts:9,11</note>', ' <note category="location">c-1.ts:6</note>', ' </notes>', ' <segment>', ' <source>message-1</source>', ' </segment>', ' </unit>', ' <unit id="2">', ' <notes>', ' <note category="location">a-2.ts:6</note>', ' <note category="location">b-2.ts:6</note>', ' <note category="location">b-2.ts:6</note>', ' <note category="location">b-2.ts:9,11</note>', ' <note category="location">c-2.ts:6</note>', ' </notes>', ' <segment>', ' <source>message-1</source>', ' </segment>', ' </unit>', ' </file>', '</xliff>', '', ]); }); }); }); });
the_stack
import * as gax from 'google-gax'; import { Callback, CallOptions, Descriptors, ClientOptions, PaginationCallback, GaxCall, } from 'google-gax'; import {Transform} from 'stream'; import {RequestType} from 'google-gax/build/src/apitypes'; import * as protos from '../../protos/protos'; import jsonProtos = require('../../protos/protos.json'); /** * Client JSON configuration object, loaded from * `src/v1/cloud_scheduler_client_config.json`. * This file defines retry strategy and timeouts for all API methods in this library. */ import * as gapicConfig from './cloud_scheduler_client_config.json'; const version = require('../../../package.json').version; /** * The Cloud Scheduler API allows external entities to reliably * schedule asynchronous jobs. * @class * @memberof v1 */ export class CloudSchedulerClient { private _terminated = false; private _opts: ClientOptions; private _providedCustomServicePath: boolean; private _gaxModule: typeof gax | typeof gax.fallback; private _gaxGrpc: gax.GrpcClient | gax.fallback.GrpcClient; private _protos: {}; private _defaults: {[method: string]: gax.CallSettings}; auth: gax.GoogleAuth; descriptors: Descriptors = { page: {}, stream: {}, longrunning: {}, batching: {}, }; warn: (code: string, message: string, warnType?: string) => void; innerApiCalls: {[name: string]: Function}; pathTemplates: {[name: string]: gax.PathTemplate}; cloudSchedulerStub?: Promise<{[name: string]: Function}>; /** * Construct an instance of CloudSchedulerClient. * * @param {object} [options] - The configuration object. * The options accepted by the constructor are described in detail * in [this document](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#creating-the-client-instance). * The common options are: * @param {object} [options.credentials] - Credentials object. * @param {string} [options.credentials.client_email] * @param {string} [options.credentials.private_key] * @param {string} [options.email] - Account email address. Required when * using a .pem or .p12 keyFilename. * @param {string} [options.keyFilename] - Full path to the a .json, .pem, or * .p12 key downloaded from the Google Developers Console. If you provide * a path to a JSON file, the projectId option below is not necessary. * NOTE: .pem and .p12 require you to specify options.email as well. * @param {number} [options.port] - The port on which to connect to * the remote host. * @param {string} [options.projectId] - The project ID from the Google * Developer's Console, e.g. 'grape-spaceship-123'. We will also check * the environment variable GCLOUD_PROJECT for your project ID. If your * app is running in an environment which supports * {@link https://developers.google.com/identity/protocols/application-default-credentials Application Default Credentials}, * your project ID will be detected automatically. * @param {string} [options.apiEndpoint] - The domain name of the * API remote host. * @param {gax.ClientConfig} [options.clientConfig] - Client configuration override. * Follows the structure of {@link gapicConfig}. * @param {boolean} [options.fallback] - Use HTTP fallback mode. * In fallback mode, a special browser-compatible transport implementation is used * instead of gRPC transport. In browser context (if the `window` object is defined) * the fallback mode is enabled automatically; set `options.fallback` to `false` * if you need to override this behavior. */ constructor(opts?: ClientOptions) { // Ensure that options include all the required fields. const staticMembers = this.constructor as typeof CloudSchedulerClient; const servicePath = opts?.servicePath || opts?.apiEndpoint || staticMembers.servicePath; this._providedCustomServicePath = !!( opts?.servicePath || opts?.apiEndpoint ); const port = opts?.port || staticMembers.port; const clientConfig = opts?.clientConfig ?? {}; const fallback = opts?.fallback ?? (typeof window !== 'undefined' && typeof window?.fetch === 'function'); opts = Object.assign({servicePath, port, clientConfig, fallback}, opts); // If scopes are unset in options and we're connecting to a non-default endpoint, set scopes just in case. if (servicePath !== staticMembers.servicePath && !('scopes' in opts)) { opts['scopes'] = staticMembers.scopes; } // Choose either gRPC or proto-over-HTTP implementation of google-gax. this._gaxModule = opts.fallback ? gax.fallback : gax; // Create a `gaxGrpc` object, with any grpc-specific options sent to the client. this._gaxGrpc = new this._gaxModule.GrpcClient(opts); // Save options to use in initialize() method. this._opts = opts; // Save the auth object to the client, for use by other methods. this.auth = this._gaxGrpc.auth as gax.GoogleAuth; // Set useJWTAccessWithScope on the auth object. this.auth.useJWTAccessWithScope = true; // Set defaultServicePath on the auth object. this.auth.defaultServicePath = staticMembers.servicePath; // Set the default scopes in auth client if needed. if (servicePath === staticMembers.servicePath) { this.auth.defaultScopes = staticMembers.scopes; } // Determine the client header string. const clientHeader = [`gax/${this._gaxModule.version}`, `gapic/${version}`]; if (typeof process !== 'undefined' && 'versions' in process) { clientHeader.push(`gl-node/${process.versions.node}`); } else { clientHeader.push(`gl-web/${this._gaxModule.version}`); } if (!opts.fallback) { clientHeader.push(`grpc/${this._gaxGrpc.grpcVersion}`); } else if (opts.fallback === 'rest') { clientHeader.push(`rest/${this._gaxGrpc.grpcVersion}`); } if (opts.libName && opts.libVersion) { clientHeader.push(`${opts.libName}/${opts.libVersion}`); } // Load the applicable protos. this._protos = this._gaxGrpc.loadProtoJSON(jsonProtos); // This API contains "path templates"; forward-slash-separated // identifiers to uniquely identify resources within the API. // Create useful helper objects for these. this.pathTemplates = { jobPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/locations/{location}/jobs/{job}' ), locationPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}/locations/{location}' ), projectPathTemplate: new this._gaxModule.PathTemplate( 'projects/{project}' ), }; // Some of the methods on this service return "paged" results, // (e.g. 50 results at a time, with tokens to get subsequent // pages). Denote the keys used for pagination and results. this.descriptors.page = { listJobs: new this._gaxModule.PageDescriptor( 'pageToken', 'nextPageToken', 'jobs' ), }; // Put together the default options sent with requests. this._defaults = this._gaxGrpc.constructSettings( 'google.cloud.scheduler.v1.CloudScheduler', gapicConfig as gax.ClientConfig, opts.clientConfig || {}, {'x-goog-api-client': clientHeader.join(' ')} ); // Set up a dictionary of "inner API calls"; the core implementation // of calling the API is handled in `google-gax`, with this code // merely providing the destination and request information. this.innerApiCalls = {}; // Add a warn function to the client constructor so it can be easily tested. this.warn = gax.warn; } /** * Initialize the client. * Performs asynchronous operations (such as authentication) and prepares the client. * This function will be called automatically when any class method is called for the * first time, but if you need to initialize it before calling an actual method, * feel free to call initialize() directly. * * You can await on this method if you want to make sure the client is initialized. * * @returns {Promise} A promise that resolves to an authenticated service stub. */ initialize() { // If the client stub promise is already initialized, return immediately. if (this.cloudSchedulerStub) { return this.cloudSchedulerStub; } // Put together the "service stub" for // google.cloud.scheduler.v1.CloudScheduler. this.cloudSchedulerStub = this._gaxGrpc.createStub( this._opts.fallback ? (this._protos as protobuf.Root).lookupService( 'google.cloud.scheduler.v1.CloudScheduler' ) : // eslint-disable-next-line @typescript-eslint/no-explicit-any (this._protos as any).google.cloud.scheduler.v1.CloudScheduler, this._opts, this._providedCustomServicePath ) as Promise<{[method: string]: Function}>; // Iterate over each of the methods that the service provides // and create an API call method for each. const cloudSchedulerStubMethods = [ 'listJobs', 'getJob', 'createJob', 'updateJob', 'deleteJob', 'pauseJob', 'resumeJob', 'runJob', ]; for (const methodName of cloudSchedulerStubMethods) { const callPromise = this.cloudSchedulerStub.then( stub => (...args: Array<{}>) => { if (this._terminated) { return Promise.reject('The client has already been closed.'); } const func = stub[methodName]; return func.apply(stub, args); }, (err: Error | null | undefined) => () => { throw err; } ); const descriptor = this.descriptors.page[methodName] || undefined; const apiCall = this._gaxModule.createApiCall( callPromise, this._defaults[methodName], descriptor ); this.innerApiCalls[methodName] = apiCall; } return this.cloudSchedulerStub; } /** * The DNS address for this API service. * @returns {string} The DNS address for this service. */ static get servicePath() { return 'cloudscheduler.googleapis.com'; } /** * The DNS address for this API service - same as servicePath(), * exists for compatibility reasons. * @returns {string} The DNS address for this service. */ static get apiEndpoint() { return 'cloudscheduler.googleapis.com'; } /** * The port for this API service. * @returns {number} The default port for this service. */ static get port() { return 443; } /** * The scopes needed to make gRPC calls for every method defined * in this service. * @returns {string[]} List of default scopes. */ static get scopes() { return ['https://www.googleapis.com/auth/cloud-platform']; } getProjectId(): Promise<string>; getProjectId(callback: Callback<string, undefined, undefined>): void; /** * Return the project ID used by this class. * @returns {Promise} A promise that resolves to string containing the project ID. */ getProjectId( callback?: Callback<string, undefined, undefined> ): Promise<string> | void { if (callback) { this.auth.getProjectId(callback); return; } return this.auth.getProjectId(); } // ------------------- // -- Service calls -- // ------------------- /** * Gets a job. * * @param {Object} request * The request object that will be sent. * @param {string} request.name * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing [Job]{@link google.cloud.scheduler.v1.Job}. * Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) * for more details and examples. * @example <caption>include:samples/generated/v1/cloud_scheduler.get_job.js</caption> * region_tag:cloudscheduler_v1_generated_CloudScheduler_GetJob_async */ getJob( request?: protos.google.cloud.scheduler.v1.IGetJobRequest, options?: CallOptions ): Promise< [ protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.IGetJobRequest | undefined, {} | undefined ] >; getJob( request: protos.google.cloud.scheduler.v1.IGetJobRequest, options: CallOptions, callback: Callback< protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.IGetJobRequest | null | undefined, {} | null | undefined > ): void; getJob( request: protos.google.cloud.scheduler.v1.IGetJobRequest, callback: Callback< protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.IGetJobRequest | null | undefined, {} | null | undefined > ): void; getJob( request?: protos.google.cloud.scheduler.v1.IGetJobRequest, optionsOrCallback?: | CallOptions | Callback< protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.IGetJobRequest | null | undefined, {} | null | undefined >, callback?: Callback< protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.IGetJobRequest | null | undefined, {} | null | undefined > ): Promise< [ protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.IGetJobRequest | undefined, {} | undefined ] > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ name: request.name || '', }); this.initialize(); return this.innerApiCalls.getJob(request, options, callback); } /** * Creates a job. * * @param {Object} request * The request object that will be sent. * @param {string} request.parent * Required. The location name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID`. * @param {google.cloud.scheduler.v1.Job} request.job * Required. The job to add. The user can optionally specify a name for the * job in {@link google.cloud.scheduler.v1.Job.name|name}. {@link google.cloud.scheduler.v1.Job.name|name} cannot be the same as an * existing job. If a name is not specified then the system will * generate a random unique name that will be returned * ({@link google.cloud.scheduler.v1.Job.name|name}) in the response. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing [Job]{@link google.cloud.scheduler.v1.Job}. * Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) * for more details and examples. * @example <caption>include:samples/generated/v1/cloud_scheduler.create_job.js</caption> * region_tag:cloudscheduler_v1_generated_CloudScheduler_CreateJob_async */ createJob( request?: protos.google.cloud.scheduler.v1.ICreateJobRequest, options?: CallOptions ): Promise< [ protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.ICreateJobRequest | undefined, {} | undefined ] >; createJob( request: protos.google.cloud.scheduler.v1.ICreateJobRequest, options: CallOptions, callback: Callback< protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.ICreateJobRequest | null | undefined, {} | null | undefined > ): void; createJob( request: protos.google.cloud.scheduler.v1.ICreateJobRequest, callback: Callback< protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.ICreateJobRequest | null | undefined, {} | null | undefined > ): void; createJob( request?: protos.google.cloud.scheduler.v1.ICreateJobRequest, optionsOrCallback?: | CallOptions | Callback< protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.ICreateJobRequest | null | undefined, {} | null | undefined >, callback?: Callback< protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.ICreateJobRequest | null | undefined, {} | null | undefined > ): Promise< [ protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.ICreateJobRequest | undefined, {} | undefined ] > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ parent: request.parent || '', }); this.initialize(); return this.innerApiCalls.createJob(request, options, callback); } /** * Updates a job. * * If successful, the updated {@link google.cloud.scheduler.v1.Job|Job} is returned. If the job does * not exist, `NOT_FOUND` is returned. * * If UpdateJob does not successfully return, it is possible for the * job to be in an {@link google.cloud.scheduler.v1.Job.State.UPDATE_FAILED|Job.State.UPDATE_FAILED} state. A job in this state may * not be executed. If this happens, retry the UpdateJob request * until a successful response is received. * * @param {Object} request * The request object that will be sent. * @param {google.cloud.scheduler.v1.Job} request.job * Required. The new job properties. {@link google.cloud.scheduler.v1.Job.name|name} must be specified. * * Output only fields cannot be modified using UpdateJob. * Any value specified for an output only field will be ignored. * @param {google.protobuf.FieldMask} request.updateMask * A mask used to specify which fields of the job are being updated. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing [Job]{@link google.cloud.scheduler.v1.Job}. * Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) * for more details and examples. * @example <caption>include:samples/generated/v1/cloud_scheduler.update_job.js</caption> * region_tag:cloudscheduler_v1_generated_CloudScheduler_UpdateJob_async */ updateJob( request?: protos.google.cloud.scheduler.v1.IUpdateJobRequest, options?: CallOptions ): Promise< [ protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.IUpdateJobRequest | undefined, {} | undefined ] >; updateJob( request: protos.google.cloud.scheduler.v1.IUpdateJobRequest, options: CallOptions, callback: Callback< protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.IUpdateJobRequest | null | undefined, {} | null | undefined > ): void; updateJob( request: protos.google.cloud.scheduler.v1.IUpdateJobRequest, callback: Callback< protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.IUpdateJobRequest | null | undefined, {} | null | undefined > ): void; updateJob( request?: protos.google.cloud.scheduler.v1.IUpdateJobRequest, optionsOrCallback?: | CallOptions | Callback< protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.IUpdateJobRequest | null | undefined, {} | null | undefined >, callback?: Callback< protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.IUpdateJobRequest | null | undefined, {} | null | undefined > ): Promise< [ protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.IUpdateJobRequest | undefined, {} | undefined ] > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ 'job.name': request.job!.name || '', }); this.initialize(); return this.innerApiCalls.updateJob(request, options, callback); } /** * Deletes a job. * * @param {Object} request * The request object that will be sent. * @param {string} request.name * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing [Empty]{@link google.protobuf.Empty}. * Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) * for more details and examples. * @example <caption>include:samples/generated/v1/cloud_scheduler.delete_job.js</caption> * region_tag:cloudscheduler_v1_generated_CloudScheduler_DeleteJob_async */ deleteJob( request?: protos.google.cloud.scheduler.v1.IDeleteJobRequest, options?: CallOptions ): Promise< [ protos.google.protobuf.IEmpty, protos.google.cloud.scheduler.v1.IDeleteJobRequest | undefined, {} | undefined ] >; deleteJob( request: protos.google.cloud.scheduler.v1.IDeleteJobRequest, options: CallOptions, callback: Callback< protos.google.protobuf.IEmpty, protos.google.cloud.scheduler.v1.IDeleteJobRequest | null | undefined, {} | null | undefined > ): void; deleteJob( request: protos.google.cloud.scheduler.v1.IDeleteJobRequest, callback: Callback< protos.google.protobuf.IEmpty, protos.google.cloud.scheduler.v1.IDeleteJobRequest | null | undefined, {} | null | undefined > ): void; deleteJob( request?: protos.google.cloud.scheduler.v1.IDeleteJobRequest, optionsOrCallback?: | CallOptions | Callback< protos.google.protobuf.IEmpty, protos.google.cloud.scheduler.v1.IDeleteJobRequest | null | undefined, {} | null | undefined >, callback?: Callback< protos.google.protobuf.IEmpty, protos.google.cloud.scheduler.v1.IDeleteJobRequest | null | undefined, {} | null | undefined > ): Promise< [ protos.google.protobuf.IEmpty, protos.google.cloud.scheduler.v1.IDeleteJobRequest | undefined, {} | undefined ] > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ name: request.name || '', }); this.initialize(); return this.innerApiCalls.deleteJob(request, options, callback); } /** * Pauses a job. * * If a job is paused then the system will stop executing the job * until it is re-enabled via {@link google.cloud.scheduler.v1.CloudScheduler.ResumeJob|ResumeJob}. The * state of the job is stored in {@link google.cloud.scheduler.v1.Job.state|state}; if paused it * will be set to {@link google.cloud.scheduler.v1.Job.State.PAUSED|Job.State.PAUSED}. A job must be in {@link google.cloud.scheduler.v1.Job.State.ENABLED|Job.State.ENABLED} * to be paused. * * @param {Object} request * The request object that will be sent. * @param {string} request.name * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing [Job]{@link google.cloud.scheduler.v1.Job}. * Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) * for more details and examples. * @example <caption>include:samples/generated/v1/cloud_scheduler.pause_job.js</caption> * region_tag:cloudscheduler_v1_generated_CloudScheduler_PauseJob_async */ pauseJob( request?: protos.google.cloud.scheduler.v1.IPauseJobRequest, options?: CallOptions ): Promise< [ protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.IPauseJobRequest | undefined, {} | undefined ] >; pauseJob( request: protos.google.cloud.scheduler.v1.IPauseJobRequest, options: CallOptions, callback: Callback< protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.IPauseJobRequest | null | undefined, {} | null | undefined > ): void; pauseJob( request: protos.google.cloud.scheduler.v1.IPauseJobRequest, callback: Callback< protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.IPauseJobRequest | null | undefined, {} | null | undefined > ): void; pauseJob( request?: protos.google.cloud.scheduler.v1.IPauseJobRequest, optionsOrCallback?: | CallOptions | Callback< protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.IPauseJobRequest | null | undefined, {} | null | undefined >, callback?: Callback< protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.IPauseJobRequest | null | undefined, {} | null | undefined > ): Promise< [ protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.IPauseJobRequest | undefined, {} | undefined ] > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ name: request.name || '', }); this.initialize(); return this.innerApiCalls.pauseJob(request, options, callback); } /** * Resume a job. * * This method reenables a job after it has been {@link google.cloud.scheduler.v1.Job.State.PAUSED|Job.State.PAUSED}. The * state of a job is stored in {@link google.cloud.scheduler.v1.Job.state|Job.state}; after calling this method it * will be set to {@link google.cloud.scheduler.v1.Job.State.ENABLED|Job.State.ENABLED}. A job must be in * {@link google.cloud.scheduler.v1.Job.State.PAUSED|Job.State.PAUSED} to be resumed. * * @param {Object} request * The request object that will be sent. * @param {string} request.name * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing [Job]{@link google.cloud.scheduler.v1.Job}. * Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) * for more details and examples. * @example <caption>include:samples/generated/v1/cloud_scheduler.resume_job.js</caption> * region_tag:cloudscheduler_v1_generated_CloudScheduler_ResumeJob_async */ resumeJob( request?: protos.google.cloud.scheduler.v1.IResumeJobRequest, options?: CallOptions ): Promise< [ protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.IResumeJobRequest | undefined, {} | undefined ] >; resumeJob( request: protos.google.cloud.scheduler.v1.IResumeJobRequest, options: CallOptions, callback: Callback< protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.IResumeJobRequest | null | undefined, {} | null | undefined > ): void; resumeJob( request: protos.google.cloud.scheduler.v1.IResumeJobRequest, callback: Callback< protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.IResumeJobRequest | null | undefined, {} | null | undefined > ): void; resumeJob( request?: protos.google.cloud.scheduler.v1.IResumeJobRequest, optionsOrCallback?: | CallOptions | Callback< protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.IResumeJobRequest | null | undefined, {} | null | undefined >, callback?: Callback< protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.IResumeJobRequest | null | undefined, {} | null | undefined > ): Promise< [ protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.IResumeJobRequest | undefined, {} | undefined ] > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ name: request.name || '', }); this.initialize(); return this.innerApiCalls.resumeJob(request, options, callback); } /** * Forces a job to run now. * * When this method is called, Cloud Scheduler will dispatch the job, even * if the job is already running. * * @param {Object} request * The request object that will be sent. * @param {string} request.name * Required. The job name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID/jobs/JOB_ID`. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is an object representing [Job]{@link google.cloud.scheduler.v1.Job}. * Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#regular-methods) * for more details and examples. * @example <caption>include:samples/generated/v1/cloud_scheduler.run_job.js</caption> * region_tag:cloudscheduler_v1_generated_CloudScheduler_RunJob_async */ runJob( request?: protos.google.cloud.scheduler.v1.IRunJobRequest, options?: CallOptions ): Promise< [ protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.IRunJobRequest | undefined, {} | undefined ] >; runJob( request: protos.google.cloud.scheduler.v1.IRunJobRequest, options: CallOptions, callback: Callback< protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.IRunJobRequest | null | undefined, {} | null | undefined > ): void; runJob( request: protos.google.cloud.scheduler.v1.IRunJobRequest, callback: Callback< protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.IRunJobRequest | null | undefined, {} | null | undefined > ): void; runJob( request?: protos.google.cloud.scheduler.v1.IRunJobRequest, optionsOrCallback?: | CallOptions | Callback< protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.IRunJobRequest | null | undefined, {} | null | undefined >, callback?: Callback< protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.IRunJobRequest | null | undefined, {} | null | undefined > ): Promise< [ protos.google.cloud.scheduler.v1.IJob, protos.google.cloud.scheduler.v1.IRunJobRequest | undefined, {} | undefined ] > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ name: request.name || '', }); this.initialize(); return this.innerApiCalls.runJob(request, options, callback); } /** * Lists jobs. * * @param {Object} request * The request object that will be sent. * @param {string} request.parent * Required. The location name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID`. * @param {number} request.pageSize * Requested page size. * * The maximum page size is 500. If unspecified, the page size will * be the maximum. Fewer jobs than requested might be returned, * even if more jobs exist; use next_page_token to determine if more * jobs exist. * @param {string} request.pageToken * A token identifying a page of results the server will return. To * request the first page results, page_token must be empty. To * request the next page of results, page_token must be the value of * {@link google.cloud.scheduler.v1.ListJobsResponse.next_page_token|next_page_token} returned from * the previous call to {@link google.cloud.scheduler.v1.CloudScheduler.ListJobs|ListJobs}. It is an error to * switch the value of {@link google.cloud.scheduler.v1.ListJobsRequest.filter|filter} or * {@link google.cloud.scheduler.v1.ListJobsRequest.order_by|order_by} while iterating through pages. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Promise} - The promise which resolves to an array. * The first element of the array is Array of [Job]{@link google.cloud.scheduler.v1.Job}. * The client library will perform auto-pagination by default: it will call the API as many * times as needed and will merge results from all the pages into this array. * Note that it can affect your quota. * We recommend using `listJobsAsync()` * method described below for async iteration which you can stop as needed. * Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) * for more details and examples. */ listJobs( request?: protos.google.cloud.scheduler.v1.IListJobsRequest, options?: CallOptions ): Promise< [ protos.google.cloud.scheduler.v1.IJob[], protos.google.cloud.scheduler.v1.IListJobsRequest | null, protos.google.cloud.scheduler.v1.IListJobsResponse ] >; listJobs( request: protos.google.cloud.scheduler.v1.IListJobsRequest, options: CallOptions, callback: PaginationCallback< protos.google.cloud.scheduler.v1.IListJobsRequest, protos.google.cloud.scheduler.v1.IListJobsResponse | null | undefined, protos.google.cloud.scheduler.v1.IJob > ): void; listJobs( request: protos.google.cloud.scheduler.v1.IListJobsRequest, callback: PaginationCallback< protos.google.cloud.scheduler.v1.IListJobsRequest, protos.google.cloud.scheduler.v1.IListJobsResponse | null | undefined, protos.google.cloud.scheduler.v1.IJob > ): void; listJobs( request?: protos.google.cloud.scheduler.v1.IListJobsRequest, optionsOrCallback?: | CallOptions | PaginationCallback< protos.google.cloud.scheduler.v1.IListJobsRequest, protos.google.cloud.scheduler.v1.IListJobsResponse | null | undefined, protos.google.cloud.scheduler.v1.IJob >, callback?: PaginationCallback< protos.google.cloud.scheduler.v1.IListJobsRequest, protos.google.cloud.scheduler.v1.IListJobsResponse | null | undefined, protos.google.cloud.scheduler.v1.IJob > ): Promise< [ protos.google.cloud.scheduler.v1.IJob[], protos.google.cloud.scheduler.v1.IListJobsRequest | null, protos.google.cloud.scheduler.v1.IListJobsResponse ] > | void { request = request || {}; let options: CallOptions; if (typeof optionsOrCallback === 'function' && callback === undefined) { callback = optionsOrCallback; options = {}; } else { options = optionsOrCallback as CallOptions; } options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ parent: request.parent || '', }); this.initialize(); return this.innerApiCalls.listJobs(request, options, callback); } /** * Equivalent to `method.name.toCamelCase()`, but returns a NodeJS Stream object. * @param {Object} request * The request object that will be sent. * @param {string} request.parent * Required. The location name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID`. * @param {number} request.pageSize * Requested page size. * * The maximum page size is 500. If unspecified, the page size will * be the maximum. Fewer jobs than requested might be returned, * even if more jobs exist; use next_page_token to determine if more * jobs exist. * @param {string} request.pageToken * A token identifying a page of results the server will return. To * request the first page results, page_token must be empty. To * request the next page of results, page_token must be the value of * {@link google.cloud.scheduler.v1.ListJobsResponse.next_page_token|next_page_token} returned from * the previous call to {@link google.cloud.scheduler.v1.CloudScheduler.ListJobs|ListJobs}. It is an error to * switch the value of {@link google.cloud.scheduler.v1.ListJobsRequest.filter|filter} or * {@link google.cloud.scheduler.v1.ListJobsRequest.order_by|order_by} while iterating through pages. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Stream} * An object stream which emits an object representing [Job]{@link google.cloud.scheduler.v1.Job} on 'data' event. * The client library will perform auto-pagination by default: it will call the API as many * times as needed. Note that it can affect your quota. * We recommend using `listJobsAsync()` * method described below for async iteration which you can stop as needed. * Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) * for more details and examples. */ listJobsStream( request?: protos.google.cloud.scheduler.v1.IListJobsRequest, options?: CallOptions ): Transform { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ parent: request.parent || '', }); const defaultCallSettings = this._defaults['listJobs']; const callSettings = defaultCallSettings.merge(options); this.initialize(); return this.descriptors.page.listJobs.createStream( this.innerApiCalls.listJobs as gax.GaxCall, request, callSettings ); } /** * Equivalent to `listJobs`, but returns an iterable object. * * `for`-`await`-`of` syntax is used with the iterable to get response elements on-demand. * @param {Object} request * The request object that will be sent. * @param {string} request.parent * Required. The location name. For example: * `projects/PROJECT_ID/locations/LOCATION_ID`. * @param {number} request.pageSize * Requested page size. * * The maximum page size is 500. If unspecified, the page size will * be the maximum. Fewer jobs than requested might be returned, * even if more jobs exist; use next_page_token to determine if more * jobs exist. * @param {string} request.pageToken * A token identifying a page of results the server will return. To * request the first page results, page_token must be empty. To * request the next page of results, page_token must be the value of * {@link google.cloud.scheduler.v1.ListJobsResponse.next_page_token|next_page_token} returned from * the previous call to {@link google.cloud.scheduler.v1.CloudScheduler.ListJobs|ListJobs}. It is an error to * switch the value of {@link google.cloud.scheduler.v1.ListJobsRequest.filter|filter} or * {@link google.cloud.scheduler.v1.ListJobsRequest.order_by|order_by} while iterating through pages. * @param {object} [options] * Call options. See {@link https://googleapis.dev/nodejs/google-gax/latest/interfaces/CallOptions.html|CallOptions} for more details. * @returns {Object} * An iterable Object that allows [async iteration](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols). * When you iterate the returned iterable, each element will be an object representing * [Job]{@link google.cloud.scheduler.v1.Job}. The API will be called under the hood as needed, once per the page, * so you can stop the iteration when you don't need more results. * Please see the * [documentation](https://github.com/googleapis/gax-nodejs/blob/master/client-libraries.md#auto-pagination) * for more details and examples. * @example <caption>include:samples/generated/v1/cloud_scheduler.list_jobs.js</caption> * region_tag:cloudscheduler_v1_generated_CloudScheduler_ListJobs_async */ listJobsAsync( request?: protos.google.cloud.scheduler.v1.IListJobsRequest, options?: CallOptions ): AsyncIterable<protos.google.cloud.scheduler.v1.IJob> { request = request || {}; options = options || {}; options.otherArgs = options.otherArgs || {}; options.otherArgs.headers = options.otherArgs.headers || {}; options.otherArgs.headers['x-goog-request-params'] = gax.routingHeader.fromParams({ parent: request.parent || '', }); const defaultCallSettings = this._defaults['listJobs']; const callSettings = defaultCallSettings.merge(options); this.initialize(); return this.descriptors.page.listJobs.asyncIterate( this.innerApiCalls['listJobs'] as GaxCall, request as unknown as RequestType, callSettings ) as AsyncIterable<protos.google.cloud.scheduler.v1.IJob>; } // -------------------- // -- Path templates -- // -------------------- /** * Return a fully-qualified job resource name string. * * @param {string} project * @param {string} location * @param {string} job * @returns {string} Resource name string. */ jobPath(project: string, location: string, job: string) { return this.pathTemplates.jobPathTemplate.render({ project: project, location: location, job: job, }); } /** * Parse the project from Job resource. * * @param {string} jobName * A fully-qualified path representing Job resource. * @returns {string} A string representing the project. */ matchProjectFromJobName(jobName: string) { return this.pathTemplates.jobPathTemplate.match(jobName).project; } /** * Parse the location from Job resource. * * @param {string} jobName * A fully-qualified path representing Job resource. * @returns {string} A string representing the location. */ matchLocationFromJobName(jobName: string) { return this.pathTemplates.jobPathTemplate.match(jobName).location; } /** * Parse the job from Job resource. * * @param {string} jobName * A fully-qualified path representing Job resource. * @returns {string} A string representing the job. */ matchJobFromJobName(jobName: string) { return this.pathTemplates.jobPathTemplate.match(jobName).job; } /** * Return a fully-qualified location resource name string. * * @param {string} project * @param {string} location * @returns {string} Resource name string. */ locationPath(project: string, location: string) { return this.pathTemplates.locationPathTemplate.render({ project: project, location: location, }); } /** * Parse the project from Location resource. * * @param {string} locationName * A fully-qualified path representing Location resource. * @returns {string} A string representing the project. */ matchProjectFromLocationName(locationName: string) { return this.pathTemplates.locationPathTemplate.match(locationName).project; } /** * Parse the location from Location resource. * * @param {string} locationName * A fully-qualified path representing Location resource. * @returns {string} A string representing the location. */ matchLocationFromLocationName(locationName: string) { return this.pathTemplates.locationPathTemplate.match(locationName).location; } /** * Return a fully-qualified project resource name string. * * @param {string} project * @returns {string} Resource name string. */ projectPath(project: string) { return this.pathTemplates.projectPathTemplate.render({ project: project, }); } /** * Parse the project from Project resource. * * @param {string} projectName * A fully-qualified path representing Project resource. * @returns {string} A string representing the project. */ matchProjectFromProjectName(projectName: string) { return this.pathTemplates.projectPathTemplate.match(projectName).project; } /** * Terminate the gRPC channel and close the client. * * The client will no longer be usable and all future behavior is undefined. * @returns {Promise} A promise that resolves when the client is closed. */ close(): Promise<void> { this.initialize(); if (!this._terminated) { return this.cloudSchedulerStub!.then(stub => { this._terminated = true; stub.close(); }); } return Promise.resolve(); } }
the_stack
import { SharedWindow } from "../shared"; interface CRMAPIMessageInstance<T, TD> { id: CRM.GenericNodeId; tabId: TabId; tabIndex: TabIndex; type: T; data: TD; onFinish: any; lineNumber?: string; } interface LogListenerLine { id: CRM.GenericNodeId | string; tabId: TabId | string; tabInstanceIndex: TabIndex; nodeTitle?: string; tabTitle?: string; data?: LogLineData[]; val?: { type: 'success'; result: any; } | { type: 'error'; result: { stack: string; name: string; message: string; } }; logId?: number; lineNumber?: string; timestamp?: string; type?: string; isEval?: boolean; isError?: boolean; suggestions?: string[]; } interface LogLineData { code: string; result?: string; hasResult?: boolean; } /** * A log line listener */ type LogListener = (newLine: LogListenerLine) => void; /** * Data about an active listener */ interface LogListenerObject { /** * The listener itself */ listener: LogListener; /** * The node ID for which to show messages */ id: CRM.GenericNodeId | string; /** * The tab ID for which to show messages */ tab: TabId | string; /** * A function that can be used to update the filters etc */ update: (id: string | CRM.GenericNodeId, tab: string | TabId, tabIndex: TabIndex, textFilter: string) => LogListenerLine[]; /** * The text to filter for */ text: string; /** * The tab index to filter for */ index: TabIndex; } /** * An active tab */ interface TabData { /** * The ID of the tab */ id: TabId | 'background'; /** * The title of the tab */ title: string; } /** * The contextmenu items in tree form */ interface ContextMenuItemTreeItem { /** * The index of this item in its parent's children */ index: number; /** * The ID of this item */ id: string|number; /** * Whether this item is enabled */ enabled: boolean; /** * The associated CRM node */ node: CRM.DividerNode | CRM.MenuNode | CRM.LinkNode | CRM.StylesheetNode | CRM.ScriptNode; /** * The ID of the parent contextmenu item */ parentId: string|number; /** * The children of this leaf */ children: ContextMenuItemTreeItem[]; /** * The children of this node's parent */ parentTree: ContextMenuItemTreeItem[]; } interface BrowserTabsQueryInfo { active?: boolean, audible?: boolean, // unsupported: autoDiscardable?: boolean, cookieStoreId?: string, currentWindow?: boolean, discarded?: boolean, highlighted?: boolean, index?: number, muted?: boolean, lastFocusedWindow?: boolean, pinned?: boolean, status?: _browser.tabs.TabStatus, title?: string, url?: string|string[], windowId?: number, windowType?: _browser.tabs.WindowType, } interface EncodedContextData { clientX: number; clientY: number; offsetX: number; offsetY: number; pageX: number; pageY: number; screenX: number; screenY: number; which: number; x: number; y: number; srcElement: number; target: number; toElement: number; } interface GreaseMonkeyDataInfo { script: { author?: string; copyright?: string; description?: string; excludes?: string[]; homepage?: string; icon?: string; icon64?: string; includes?: string[]; lastUpdated: number; //Never updated matches?: string[]; isIncognito: boolean; downloadMode: string; name: string; namespace?: string; options: { awareOfChrome: boolean; compat_arrayleft: boolean; compat_foreach: boolean; compat_forvarin: boolean; compat_metadata: boolean; compat_prototypes: boolean; compat_uW_gmonkey: boolean; noframes?: string; override: { excludes: boolean; includes: boolean; orig_excludes?: string[]; orig_includes?: string[]; use_excludes: string[]; use_includes: string[]; } }, position: number; resources: CRM.Resource[]; "run-at": string; system: boolean; unwrap: boolean; version?: number; }; scriptMetaStr: string; scriptSource: string; scriptUpdateURL?: string; scriptWillUpdate: boolean; scriptHandler: string; version: string; } interface GreaseMonkeyData { info: GreaseMonkeyDataInfo; resources: CRM.CRMResources; } /** * Logging data for the loggingpage */ interface MessageLogging { /** * Logging by the node responsible for it */ [nodeId: number]: { /** * Any log messages */ logMessages: LogListenerLine[]; /** * Stored values */ values: any[]; /** * Data by tab ID */ [tabId: number]: any; }; /** * The active filter */ filter: { /** * The node ID for which to show logs */ id: CRM.GenericNodeId; /** * The tab ID for which to show logs */ tabId: TabId; }; } type BackgroundpageWindow = Window & SharedWindow & { logging?: MessageLogging; isDev: boolean; createHandlerFunction: (port: { postMessage: (message: Object) => void; }|_browser.runtime.Port) => (message: any) => Promise<void>; backgroundPageLog: (id: CRM.GenericNodeId, sourceData: [string, number], ...params: any[]) => void; filter: (nodeId: any, tabId: any) => void; _getCurrentTabIndex: (id: CRM.GenericNodeId, currentTab: TabId|'background', callback: (newTabIndexes: TabIndex[]) => void) => void; _getIdsAndTabs: (selectedId: CRM.GenericNodeId, selectedTab: TabId|'background', callback: (result: { ids: { id: string|CRM.GenericNodeId; title: string; }[]; tabs: TabData[]; }) => void) => void; _listenIds: (listener: (newIds: { id: CRM.GenericNodeId; title: string; }[]) => void) => void; _listenTabs: (listener: (newTabs: TabData[]) => void) => void; _listenLog: (listener: LogListener, callback: (result: LogListenerObject) => void) => LogListenerLine[]; XMLHttpRequest: any; setTimeout(callback: () => void, time: number): void; TextEncoder: any; getID: (name: string) => void; debugBackgroundScript(id: CRM.NodeId<CRM.ScriptNode>): void; debugNextScriptCall(id: CRM.NodeId<CRM.ScriptNode>): void; md5: (data: any) => string; ts: Typescript & typeof ts; less: { Parser(): { parse(code: string, callback: (err: Error, result: { toCSS(): string; }) => void): void; } }; stylus(code: string): { render(callback: (err: Error, str: string) => void): void; } TernFile: Tern.File; tern: Tern.Tern; module?: { exports?: any; } crypto: Crypto; WeakMap: typeof WeakMapPolyfill; log: typeof console.log; info: typeof console.log; logAsync: typeof console.log; infoAsync: typeof console.log; testLog?: typeof console.log; console: typeof console; } declare const enum SCRIPT_CONVERSION_TYPE { CHROME = 0, LOCAL_STORAGE = 1, BOTH = 2 } interface MatchPattern { scheme: string; host: string; path: string; invalid?: boolean; } /** * Storage data */ interface BGStorages { /** * All synced settings storage */ settingsStorage: CRM.SettingsStorage; /** * URLs that should be globally excluded (nothing runs on them) */ globalExcludes: (MatchPattern|'<all_urls>')[]; /** * Registered resources */ resourceKeys: { /** * The name of the resource */ name: string; /** * The URL the resource points to */ sourceUrl: string; /** * Hashes calculated over the content */ hashes: { /** * The algorithm used to calculate the hash */ algorithm: string; /** * The calculated hash */ hash: string; }[]; /** * The script that uses it */ scriptId: CRM.NodeId<CRM.ScriptNode>; }[]; /** * An object with URLs as keys and resources as values */ urlDataPairs: Map<string, { /** * The data in string form */ dataString: string; /** * All nodes that use this resource */ refs: CRM.GenericNodeId[]; /** * A data URI */ dataURI: string; }>; /** * The local storage data (not synced) */ storageLocal: CRM.StorageLocal; /** * Nodes' storage. Indexed by ID */ nodeStorage: Map<CRM.GenericNodeId, any>; /** * Nodes' storage. Indexed by ID */ nodeStorageSync: Map<CRM.GenericNodeId, any>; /** * Registered resources by the script ID */ resources: Map<CRM.GenericNodeId, CRM.CRMResources>; /** * Any messages about scripts trying to access permissions they don't have */ insufficientPermissions: string[]; /** * Tab lookups that failed as a result of inaccessible pages such as * chrome extension pages, file:// pages etc */ failedLookups: (TabId|string)[]; } interface SandboxWorkerInterface { worker: Worker; post(message: any): void; listen(callback: Function): void; terminate(): void; } /** * Data related to background pages */ interface BGBackground { /** * The background pages ordered by node ID */ byId: Map<CRM.GenericNodeId, SandboxWorkerInterface>; } /** * Data related to the CRM tree */ interface BGCRM { /** * The CRM tree */ crmTree: (CRM.DividerNode | CRM.MenuNode | CRM.LinkNode | CRM.StylesheetNode | CRM.ScriptNode)[] /** * CRM nodes ordered by ID */ crmById: CRMStore; /** * The CRM tree made safe (stripped of all sensitive data) */ safeTree: CRM.SafeNode[]; /** * Safe CRM nodes ordered by ID */ crmByIdSafe: SafeCRMStore; } interface ContextMenuCreateProperties { type?: _browser.contextMenus.ItemType, id?: string, title?: string, checked?: boolean, command?: "_execute_browser_action" | "_execute_page_action" | "_execute_sidebar_action", contexts?: _browser.contextMenus.ContextType[], onclick?: (info: _browser.contextMenus.OnClickData, tab: _browser.tabs.Tab) => void, parentId?: number|string, documentUrlPatterns?: string[], targetUrlPatterns?: string[], enabled?: boolean, } interface ContextMenuUpdateProperties { type?: _browser.contextMenus.ItemType, title?: string, checked?: boolean, contexts?: _browser.contextMenus.ContextType[], onclick?: (info: _browser.contextMenus.OnClickData, tab: _browser.tabs.Tab) => void, parentId?: number|string, documentUrlPatterns?: string[], targetUrlPatterns?: string[], enabled?: boolean, } interface ContextMenuSettings extends ContextMenuCreateProperties { generatedId?: number; } /** * Contextmenu nodes added by the user */ interface UserAddedContextMenu { /** * The node that created this contextmenu item */ sourceNodeId: CRM.GenericNodeId; /** * The properties that were used to create this contextmenu item */ createProperties: ContextMenuSettings; /** * The mapped id used to identify this item. Not the actual * id as that changes with every re-creation */ generatedId: string|number; /** * The actual contextmenu ID of this node */ actualId: string|number; /** * The parent of this node */ parent: UserAddedContextMenu; /** * The children of this node */ children: UserAddedContextMenu[]; } /** * Override settings for a contextmenu item */ interface ContextMenuOverrides { /** * The new type of the contextmenu item */ type?: CRM.ContextMenuItemType; /** * Whether this item should be checked */ checked?: boolean; /** * The content types on which this item should appear */ contentTypes?: CRM.ContentTypeString[]; /** * Whether this item is visible */ isVisible?: boolean; /** * Whether this item is disabled (greyed out) */ isDisabled?: boolean; /** * The overridden name of this item */ name?: string; } /** * Data related to the contextmenu and other on-page data */ interface BGCRMValues { /** * Tab-specific data */ tabData: Map<TabId, { /** * The nodes that are currently running on this tab by ID */ nodes: Map<CRM.GenericNodeId, { /** * The secret key for this CRM API instance */ secretKey: number[]; /** * The runtime.port object associated with it */ port?: _browser.runtime.Port | { postMessage(message: Object): void; }; /** * Whether this instance uses local storage */ usesLocalStorage: boolean; }[]>; /** * Any libraries that are active on the tab by name */ libraries: Map<string, boolean>; }>; /** * The ID of the root contextmenu item */ rootId: number|string; /** * Contextmenu IDs by the node ID that created them */ contextMenuIds: Map<CRM.GenericNodeId, string|number>; /** * All active instances of nodes by node ID */ nodeInstances: Map<CRM.GenericNodeId, /** * All instances of this node by their tab ID */ Map<TabId, { /** * Whether this instance has a handler associated with it yet */ hasHandler: boolean; }[]>>; /** * Info about a contextmenu item by contextmenu item ID */ contextMenuInfoById: Map<string|number, { /** * The path to this item as an array of numbers */ path: number[]; /** * The settings used to create this contextmenu item */ settings: ContextMenuSettings; /** * Whether this contextmenu item is enabled */ enabled: boolean; }>; /** * The contextmenu items in tree form */ contextMenuItemTree: ContextMenuItemTreeItem[]; /** * Contextmenu nodes added by the user */ userAddedContextMenus: UserAddedContextMenu[]; /** * Contextmenus added by the user sorted by their mapped ID */ userAddedContextMenusById: Map<string|number, UserAddedContextMenu>; /** * Contextmenu settings overrides for items on all tabs (global) by the node ID */ contextMenuGlobalOverrides: Map<CRM.GenericNodeId, ContextMenuOverrides>; /** * Data about on which pages to show or hide contextmenu items by ID */ hideNodesOnPagesData: Map<CRM.GenericNodeId, { /** * Whether to not show the node on given URL */ not: boolean; /** * The URL on which to show or not show the node */ url: string; }[]>; /** * Info about the status of a node on given tab by ID */ nodeTabStatuses: Map<CRM.GenericNodeId, { /** * Data by each tab the node is running in */ tabs: Map<TabId, { /** * Whether the checkbox is checked */ checked?: boolean; /** * Tab-specific contextmenu overrides */ overrides?: ContextMenuOverrides; }>; /** * The default checked status of the node */ defaultCheckedValue?: boolean; }>; } /** * A descriptor for a node that should execute on document start/end * basically a cut-down version of a CRM node */ interface ToExecuteNode { /** * The triggers for this node to run */ triggers: CRM.Trigger[]; /** * The ID of the node */ id: CRM.GenericNodeId; } interface ToExecuteListener { /** * The nodes to run on document start (before loading is done) */ documentStart: ToExecuteNode[]; /** * The nodes to run on document end (on contentscript load) */ documentEnd: ToExecuteNode[]; } /** * On what pages and when which nodes need to be executed */ interface BGToExecute { /** * Data about whether to show or to not show nodes on given URLs by node ID */ onUrl: ToExecuteListener; /** * Nodes that should always be executed */ always: ToExecuteListener; } /** * A function used to send a response as a callback to a page */ type SendCallbackMessage = (tabId: TabId, tabIndex: TabIndex, id: CRM.GenericNodeId, data: { err: boolean, errorMessage?: string; args?: any[]; callbackId: number; }) => void; interface Globals { /** * The last ID to be generated for a node */ latestId: number; /** * Storage data */ storages: BGStorages; /** * Data related to background pages */ background: BGBackground; /** * Data related to the CRM tree */ crm: BGCRM; /** * Permissions available to this extension */ availablePermissions: string[]; /** * Data related to the contextmenu and other on-page data */ crmValues: BGCRMValues; /** * On what pages and when which nodes need to be executed */ toExecuteNodes: BGToExecute; /** * A function used to send a response as a callback to a page */ sendCallbackMessage: SendCallbackMessage; /** * Global event listeners */ eventListeners: { /** * Event listeners for the browser.notifications API */ notificationListeners: Map<string|number, { /** * The ID of the node that created the notification */ id: CRM.GenericNodeId; /** * The ID of the tab from which a node created the notification */ tabId: TabId; /** * The index of the script on the tab that created it (if 3 instances * of the script are running, their tabIndexes are 0, 1 and 2 respectively) */ tabIndex: TabIndex; /** * The ID of the notification */ notificationId: number; /** * A callback ID for an onDone listener */ onDone: number; /** * A callback ID for an onClick listener */ onClick: number; }>; /** * Event listeners for the browser's keyboard shortcut API */ shortcutListeners: Map<string, { /** * The keyboard shortcut (as keys) */ shortcut: string; /** * The function to run when it's pressed */ callback(): void; }[]>; /** * A set of nodes that should be debugged when they next activate */ scriptDebugListeners: CRM.NodeId<CRM.ScriptNode>[]; }; /** * Data about script logging for the logging page */ logging: MessageLogging; /** * Any constant values */ constants: BGConstants; /** * Listeners for the logging page */ listeners: BGListeners; } interface CRMTemplates { mergeArrays<T extends T[] | U[], U>(this: CRMTemplates, mainArray: T, additionArray: T): T; mergeObjects<T extends { [key: string]: any; [key: number]: any; }, Y extends Partial<T>>(this: CRMTemplates, mainObject: T, additions: Y): T & Y; getDefaultNodeInfo(options?: Partial<CRM.NodeInfo>): CRM.NodeInfo; getDefaultLinkNode(options?: Partial<CRM.LinkNode>): CRM.LinkNode; getDefaultStylesheetValue(options?: Partial<CRM.StylesheetVal>): CRM.StylesheetVal; getDefaultScriptValue(options?: Partial<CRM.ScriptVal>): CRM.ScriptVal; getDefaultScriptNode(options?: CRM.PartialScriptNode): CRM.ScriptNode; getDefaultStylesheetNode(options?: CRM.PartialStylesheetNode): CRM.StylesheetNode; getDefaultDividerOrMenuNode(options: Partial<CRM.DividerNode> | Partial<CRM.MenuNode>, type: 'menu' | 'divider'): CRM.DividerNode | CRM.MenuNode; getDefaultDividerNode(options?: Partial<CRM.DividerNode>): CRM.DividerNode; getDefaultMenuNode(options?: Partial<CRM.MenuNode>): CRM.MenuNode; globalObjectWrapperCode(name: string, wrapperName: string, chromeVal: string, browserVal: string): string; } interface BGConstants { /** * The supported hashing functions */ supportedHashes: string[]; /** * Valid protocols */ validSchemes: string[]; /** * Templates used to generate new nodes */ templates: CRMTemplates; /** * A JSON function used to encode and decode functions as well */ specialJSON: SpecialJSON; /** * Valid permissions for this extension */ permissions: CRM.Permission[]; /** * Valid page contexts */ contexts: _browser.contextMenus.ContextType[]; /** * The extension IDs for the tampermonkey extensions (beta and normal) */ tamperMonkeyExtensions: string[]; /** * The extension IDs for the styish extensions */ stylishExtensions: string[]; } /** * Listeners for the logging page */ interface BGListeners { /** * The active node IDs and their titles */ idVals: { /** * The ID of this node */ id: CRM.GenericNodeId; /** * The name of this node */ title: string; }[]; /** * The active tabs */ tabVals: TabData[]; /** * A function that can be used to register an on ID update handler */ ids: ((updatedIds: { /** * The node ID */ id: CRM.GenericNodeId; /** * The name of the node */ title: string; }[]) => void)[]; /** * A function that can be used to register an on tab ID update handler */ tabs: ((updatedTabs: TabData[]) => void)[]; /** * Any log listeners and their filters */ log: LogListenerObject[]; } type UpgradeErrorHandler = (oldScriptErrors: CursorPosition[], newScriptErrors: CursorPosition[], parseError: boolean) => void; interface GlobalObject extends Partial<Window> { globals?: Globals; TransferFromOld?: { transferCRMFromOld(openInNewTab: boolean, storageSource?: { getItem(index: string | number): any; }, method?: SCRIPT_CONVERSION_TYPE): Promise<CRM.Tree>; LegacyScriptReplace: { generateScriptUpgradeErrorHandler(id: number): UpgradeErrorHandler } }; backgroundPageLoaded?: Promise<void>; HTMLElement?: any; JSON?: JSON; md5?: (input: any) => string; }
the_stack
import {useFormState} from 'react-use-form-state'; import tw, {css, styled} from 'twin.macro'; import React, {useState} from 'react'; import { EMPTY_STRING, isUndefined, isEmpty, isNull, get, } from '@abhijithvijayan/ts-utils'; import {useExtensionSettings} from '../contexts/extension-settings-context'; import {SHORTEN_URL} from '../Background/constants'; import messageUtil from '../util/mesageUtil'; import {getCurrentTab} from '../util/tabs'; import { RequestStatusActionTypes, useRequestStatus, } from '../contexts/request-status-context'; import {isValidUrl} from '../util/link'; import { SuccessfulShortenStatusProperties, ShortUrlActionBodyProperties, ApiErroredProperties, ApiBodyProperties, } from '../Background'; import Icon from '../components/Icon'; export enum CONSTANTS { DefaultDomainId = 'default', } const StyledValidateButton = styled.button` ${tw`focus:outline-none hover:text-gray-200 inline-flex items-center justify-center w-full px-3 py-1 mb-1 text-xs font-semibold text-center text-white duration-300 ease-in-out rounded shadow-lg`} background: linear-gradient(to right,rgb(126, 87, 194),rgb(98, 0, 234)); min-height: 36px; .create__icon { ${tw`inline-flex px-0 bg-transparent`} svg { ${tw`transition-transform duration-300 ease-in-out`} stroke: currentColor; stroke-width: 2; } } `; const Form: React.FC = () => { const extensionSettingsState = useExtensionSettings()[0]; const requestStatusDispatch = useRequestStatus()[1]; const [showPassword, setShowPassword] = useState<boolean>(false); const [isSubmitting, setIsSubmitting] = useState<boolean>(false); const { domainOptions, host: {hostDomain}, } = extensionSettingsState; const [ formState, { text: textProps, password: passwordProps, select: selectProps, label: labelProps, }, ] = useFormState<{ domain: string; customurl: string; password: string; }>( { domain: domainOptions .find(({id}) => { return id === CONSTANTS.DefaultDomainId; }) ?.value?.trim() || EMPTY_STRING, // empty string will map to disabled entry }, { withIds: true, // enable automatic creation of id and htmlFor props } ); const { errors: formStateErrors, validity: formStateValidity, setField: setFormStateField, setFieldError: setFormStateFieldError, } = formState; const isFormValid: boolean = ((isUndefined(formStateValidity.customurl) || formStateValidity.customurl) && (isUndefined(formStateValidity.password) || formStateValidity.password) && isUndefined(formStateErrors.customurl) && isUndefined(formStateErrors.password)) || false; async function handleFormSubmit({ customurl, password, domain, }: { domain: string; customurl: string; password: string; }): Promise<void> { // enable loading screen setIsSubmitting(true); // Get target link to shorten const tabs = await getCurrentTab(); const target: string | null = get(tabs, '[0].url', null); const shouldSubmit: boolean = !isNull(target) && isValidUrl(target); if (!shouldSubmit) { setIsSubmitting(false); requestStatusDispatch({ type: RequestStatusActionTypes.SET_REQUEST_STATUS, payload: { error: true, message: 'Not a valid URL', }, }); return; } const apiBody: ApiBodyProperties = { apikey: extensionSettingsState.apikey, target: target as unknown as string, ...(customurl.trim() !== EMPTY_STRING && {customurl: customurl.trim()}), // add key only if field is not empty ...(!isEmpty(password) && {password}), reuse: false, ...(domain.trim() !== EMPTY_STRING && {domain: domain.trim()}), }; const apiShortenUrlBody: ShortUrlActionBodyProperties = { apiBody, hostUrl: extensionSettingsState.host.hostUrl, }; // shorten url in the background const response: SuccessfulShortenStatusProperties | ApiErroredProperties = await messageUtil.send(SHORTEN_URL, apiShortenUrlBody); // disable spinner setIsSubmitting(false); if (!response.error) { const { data: {link}, } = response; // show shortened url requestStatusDispatch({ type: RequestStatusActionTypes.SET_REQUEST_STATUS, payload: { error: false, message: link, }, }); } else { // errored requestStatusDispatch({ type: RequestStatusActionTypes.SET_REQUEST_STATUS, payload: { error: true, message: response.message, }, }); } } function handleCustomUrlInputChange(url: string): void { setFormStateField('customurl', url); // ToDo: Remove special symbols if (url.length > 0 && url.length < 3) { setFormStateFieldError( 'customurl', 'Custom URL must be at-least 3 characters' ); } } function handlePasswordInputChange(password: string): void { setFormStateField('password', password); // ToDo: Remove special symbols if (password.length > 0 && password.length < 3) { setFormStateFieldError( 'password', 'Password must be at-least 3 characters' ); } } return ( <> <div tw="flex flex-col w-full max-w-sm p-4 mx-auto bg-white select-none"> <div tw="flex flex-col mb-4"> <label {...labelProps('domain')} tw="sm:text-sm mb-1 text-xs tracking-wide text-gray-600" > Domain </label> <div tw="relative"> <select {...selectProps('domain')} disabled={isSubmitting} css={[ tw`sm:text-base focus:border-indigo-400 focus:outline-none relative w-full px-2 py-2 text-sm placeholder-gray-400 bg-gray-200 border rounded`, ]} > {domainOptions.map(({id, option, value, disabled = false}) => { return ( <option tw="bg-gray-200 " value={value} disabled={disabled} key={id} > {option} </option> ); })} </select> </div> </div> <div tw="flex flex-col mb-3 relative"> <label {...labelProps('customurl')} tw="sm:text-sm absolute top-0 bottom-0 left-0 right-0 z-10 block text-xs tracking-wide text-gray-600 cursor-pointer" > <span>{hostDomain}/</span> </label> <input {...textProps('customurl')} onChange={({ target: {value}, }: React.ChangeEvent<HTMLInputElement>): void => { // NOTE: overriding onChange to show errors handleCustomUrlInputChange(value.trim()); }} disabled={isSubmitting} spellCheck="false" css={[ tw`focus:outline-none sm:text-base focus:border-indigo-400 w-full px-2 py-2 text-sm placeholder-gray-400 bg-gray-200 border rounded`, css` margin-top: 1.2rem; `, !isUndefined(formStateValidity.customurl) && !formStateValidity.customurl && tw`border-red-500`, ]} /> <span tw="flex items-center mt-1 ml-1 text-xs font-medium tracking-wide text-red-500"> {formStateErrors.customurl} </span> </div> <div tw="flex flex-col mb-3 relative"> <label {...labelProps('password')} tw="sm:text-sm absolute top-0 bottom-0 left-0 right-0 z-10 block text-xs tracking-wide text-gray-600 cursor-pointer" > <span>Password</span> </label> <div tw="relative"> <div css={[ tw`absolute top-0 right-0 flex w-10 mt-6 border border-transparent`, css` margin-top: 1.75rem; `, ]} > <Icon onClick={(): void => { if (!isSubmitting) { setShowPassword(!showPassword); } }} name={!showPassword ? 'eye-closed' : 'eye'} css={[ tw`z-10 flex items-center justify-center w-full h-full rounded-tl rounded-bl cursor-pointer`, css` color: rgb(187, 187, 187); `, ]} /> </div> <input {...passwordProps('password')} type={!showPassword ? 'password' : 'text'} spellCheck="false" onChange={({ target: {value}, }: React.ChangeEvent<HTMLInputElement>): void => { // NOTE: overriding onChange to show errors handlePasswordInputChange(value); }} disabled={isSubmitting} css={[ tw`focus:outline-none sm:text-base focus:border-indigo-400 w-full px-2 py-2 text-sm placeholder-gray-400 bg-gray-200 border rounded`, css` margin-top: 1.2rem; `, !isUndefined(formStateValidity.password) && !formStateValidity.password && tw`border-red-500`, ]} /> </div> <span tw="flex items-center mt-1 ml-1 text-xs font-medium tracking-wide text-red-500"> {formStateErrors.password} </span> </div> <StyledValidateButton type="submit" disabled={!isFormValid || isSubmitting} onClick={(): void => { handleFormSubmit(formState.values); }} > {!isSubmitting ? ( <span>Create</span> ) : ( <Icon className="icon create__icon" name="spinner" /> )} </StyledValidateButton> </div> </> ); }; export default Form;
the_stack
import { PayloadCodec } from '@temporalio/common'; import { Decoded, decodeOptional, decodeOptionalFailure, decodeOptionalMap, decodeOptionalSingle, Encoded, encodeMap, encodeOptional, encodeOptionalFailure, encodeOptionalSingle, noopDecodeMap, noopEncodeMap, } from '@temporalio/internal-non-workflow-common'; import { coresdk } from '@temporalio/proto'; type EncodedCompletion = Encoded<coresdk.workflow_completion.IWorkflowActivationCompletion>; type DecodedActivation = Decoded<coresdk.workflow_activation.IWorkflowActivation>; /** * Helper class for decoding Workflow activations and encoding Workflow completions. */ export class WorkflowCodecRunner { constructor(protected readonly codecs: PayloadCodec[]) {} /** * Run codec.decode on the Payloads in the Activation message. */ public async decodeActivation( activation: coresdk.workflow_activation.IWorkflowActivation ): Promise<DecodedActivation> { return { ...activation, jobs: activation.jobs ? await Promise.all( activation.jobs.map(async (job) => ({ ...job, startWorkflow: job.startWorkflow ? { ...job.startWorkflow, arguments: await decodeOptional(this.codecs, job.startWorkflow.arguments), headers: noopDecodeMap(job.startWorkflow.headers), continuedFailure: await decodeOptionalFailure(this.codecs, job.startWorkflow.continuedFailure), memo: { fields: await decodeOptionalMap(this.codecs, job.startWorkflow.memo?.fields), }, lastCompletionResult: { payloads: await decodeOptional(this.codecs, job.startWorkflow.lastCompletionResult?.payloads), }, searchAttributes: job.startWorkflow.searchAttributes ? { indexedFields: job.startWorkflow.searchAttributes.indexedFields ? noopDecodeMap(job.startWorkflow.searchAttributes?.indexedFields) : undefined, } : undefined, } : null, queryWorkflow: job.queryWorkflow ? { ...job.queryWorkflow, arguments: await decodeOptional(this.codecs, job.queryWorkflow.arguments), headers: noopDecodeMap(job.queryWorkflow.headers), } : null, cancelWorkflow: job.cancelWorkflow ? { ...job.cancelWorkflow, details: await decodeOptional(this.codecs, job.cancelWorkflow.details), } : null, signalWorkflow: job.signalWorkflow ? { ...job.signalWorkflow, input: await decodeOptional(this.codecs, job.signalWorkflow.input), headers: noopDecodeMap(job.signalWorkflow.headers), } : null, resolveActivity: job.resolveActivity ? { ...job.resolveActivity, result: job.resolveActivity.result ? { ...job.resolveActivity.result, completed: job.resolveActivity.result.completed ? { result: await decodeOptionalSingle( this.codecs, job.resolveActivity.result.completed.result ), } : null, failed: job.resolveActivity.result.failed ? { failure: await decodeOptionalFailure( this.codecs, job.resolveActivity.result.failed.failure ), } : null, cancelled: job.resolveActivity.result.cancelled ? { failure: await decodeOptionalFailure( this.codecs, job.resolveActivity.result.cancelled.failure ), } : null, } : null, } : null, resolveChildWorkflowExecution: job.resolveChildWorkflowExecution ? { ...job.resolveChildWorkflowExecution, result: job.resolveChildWorkflowExecution.result ? { ...job.resolveChildWorkflowExecution.result, completed: job.resolveChildWorkflowExecution.result.completed ? { result: await decodeOptionalSingle( this.codecs, job.resolveChildWorkflowExecution.result.completed.result ), } : null, failed: job.resolveChildWorkflowExecution.result.failed ? { failure: await decodeOptionalFailure( this.codecs, job.resolveChildWorkflowExecution.result.failed.failure ), } : null, cancelled: job.resolveChildWorkflowExecution.result.cancelled ? { failure: await decodeOptionalFailure( this.codecs, job.resolveChildWorkflowExecution.result.cancelled.failure ), } : null, } : null, } : null, resolveChildWorkflowExecutionStart: job.resolveChildWorkflowExecutionStart ? { ...job.resolveChildWorkflowExecutionStart, cancelled: job.resolveChildWorkflowExecutionStart.cancelled ? { failure: await decodeOptionalFailure( this.codecs, job.resolveChildWorkflowExecutionStart.cancelled.failure ), } : null, } : null, resolveSignalExternalWorkflow: job.resolveSignalExternalWorkflow ? { ...job.resolveSignalExternalWorkflow, failure: await decodeOptionalFailure(this.codecs, job.resolveSignalExternalWorkflow.failure), } : null, resolveRequestCancelExternalWorkflow: job.resolveRequestCancelExternalWorkflow ? { ...job.resolveRequestCancelExternalWorkflow, failure: await decodeOptionalFailure(this.codecs, job.resolveRequestCancelExternalWorkflow.failure), } : null, })) ) : null, }; } /** * Run codec.encode on the Payloads inside the Completion message. */ public async encodeCompletion(completionBytes: Uint8Array): Promise<Uint8Array> { const completion = coresdk.workflow_completion.WorkflowActivationCompletion.decodeDelimited(completionBytes); const encodedCompletion: EncodedCompletion = { ...completion, failed: completion.failed ? { failure: await encodeOptionalFailure(this.codecs, completion?.failed?.failure) } : null, successful: completion.successful ? { commands: completion.successful.commands ? await Promise.all( completion.successful.commands.map(async (command) => ({ ...command, scheduleActivity: command.scheduleActivity ? { ...command.scheduleActivity, arguments: await encodeOptional(this.codecs, command.scheduleActivity?.arguments), // don't encode headers headers: noopEncodeMap(command.scheduleActivity?.headers), } : undefined, upsertWorkflowSearchAttributesCommandAttributes: command.upsertWorkflowSearchAttributesCommandAttributes ? { ...command.upsertWorkflowSearchAttributesCommandAttributes, searchAttributes: noopEncodeMap( command.upsertWorkflowSearchAttributesCommandAttributes.searchAttributes ), } : undefined, respondToQuery: command.respondToQuery ? { ...command.respondToQuery, succeeded: { response: await encodeOptionalSingle( this.codecs, command.respondToQuery.succeeded?.response ), }, failed: await encodeOptionalFailure(this.codecs, command.respondToQuery.failed), } : undefined, completeWorkflowExecution: command.completeWorkflowExecution ? { ...command.completeWorkflowExecution, result: await encodeOptionalSingle(this.codecs, command.completeWorkflowExecution.result), } : undefined, failWorkflowExecution: command.failWorkflowExecution ? { ...command.failWorkflowExecution, failure: await encodeOptionalFailure(this.codecs, command.failWorkflowExecution.failure), } : undefined, continueAsNewWorkflowExecution: command.continueAsNewWorkflowExecution ? { ...command.continueAsNewWorkflowExecution, arguments: await encodeOptional( this.codecs, command.continueAsNewWorkflowExecution.arguments ), memo: await encodeMap(this.codecs, command.continueAsNewWorkflowExecution.memo), // don't encode headers headers: noopEncodeMap(command.continueAsNewWorkflowExecution.headers), // don't encode searchAttributes searchAttributes: noopEncodeMap(command.continueAsNewWorkflowExecution.searchAttributes), } : undefined, startChildWorkflowExecution: command.startChildWorkflowExecution ? { ...command.startChildWorkflowExecution, input: await encodeOptional(this.codecs, command.startChildWorkflowExecution.input), memo: await encodeMap(this.codecs, command.startChildWorkflowExecution.memo), // don't encode headers headers: noopEncodeMap(command.startChildWorkflowExecution.headers), // don't encode searchAttributes searchAttributes: noopEncodeMap(command.startChildWorkflowExecution.searchAttributes), } : undefined, signalExternalWorkflowExecution: command.signalExternalWorkflowExecution ? { ...command.signalExternalWorkflowExecution, args: await encodeOptional(this.codecs, command.signalExternalWorkflowExecution.args), headers: noopEncodeMap(command.signalExternalWorkflowExecution.headers), } : undefined, scheduleLocalActivity: command.scheduleLocalActivity ? { ...command.scheduleLocalActivity, arguments: await encodeOptional(this.codecs, command.scheduleLocalActivity.arguments), // don't encode headers headers: noopEncodeMap(command.scheduleLocalActivity.headers), } : undefined, })) ?? [] ) : null, } : null, }; return coresdk.workflow_completion.WorkflowActivationCompletion.encodeDelimited(encodedCompletion).finish(); } }
the_stack
import { inject, injectable, } from 'inversify'; import { ServiceIdentifiers } from '../../container/ServiceIdentifiers'; import * as estraverse from '@javascript-obfuscator/estraverse'; import * as ESTree from 'estree'; import { TDeadNodeInjectionCustomNodeFactory } from '../../types/container/custom-nodes/TDeadNodeInjectionCustomNodeFactory'; import { TInitialData } from '../../types/TInitialData'; import { TNodeWithStatements } from '../../types/node/TNodeWithStatements'; import { ICustomNode } from '../../interfaces/custom-nodes/ICustomNode'; import { IOptions } from '../../interfaces/options/IOptions'; import { IRandomGenerator } from '../../interfaces/utils/IRandomGenerator'; import { INodeTransformersRunner } from '../../interfaces/node-transformers/INodeTransformersRunner'; import { IVisitor } from '../../interfaces/node-transformers/IVisitor'; import { DeadCodeInjectionCustomNode } from '../../enums/custom-nodes/DeadCodeInjectionCustomNode'; import { NodeTransformer } from '../../enums/node-transformers/NodeTransformer'; import { NodeType } from '../../enums/node/NodeType'; import { NodeTransformationStage } from '../../enums/node-transformers/NodeTransformationStage'; import { AbstractNodeTransformer } from '../AbstractNodeTransformer'; import { BlockStatementDeadCodeInjectionNode } from '../../custom-nodes/dead-code-injection-nodes/BlockStatementDeadCodeInjectionNode'; import { NodeFactory } from '../../node/NodeFactory'; import { NodeGuards } from '../../node/NodeGuards'; import { NodeStatementUtils } from '../../node/NodeStatementUtils'; import { NodeUtils } from '../../node/NodeUtils'; @injectable() export class DeadCodeInjectionTransformer extends AbstractNodeTransformer { /** * @type {string} */ private static readonly deadCodeInjectionRootAstHostNodeName: string = 'deadCodeInjectionRootAstHostNode'; /** * @type {number} */ private static readonly maxNestedBlockStatementsCount: number = 4; /** * @type {number} */ private static readonly minCollectedBlockStatementsCount: number = 5; /** * @type {NodeTransformer[]} */ private static readonly transformersToRenameBlockScopeIdentifiers: NodeTransformer[] = [ NodeTransformer.DeadCodeInjectionIdentifiersTransformer, NodeTransformer.LabeledStatementTransformer, NodeTransformer.ScopeIdentifiersTransformer ]; /** * @type {NodeTransformer[]} */ public override readonly runAfter: NodeTransformer[] = [ NodeTransformer.ScopeIdentifiersTransformer ]; /** * @type {Set <BlockStatement>} */ private readonly deadCodeInjectionRootAstHostNodeSet: Set <ESTree.BlockStatement> = new Set(); /** * @type {ESTree.BlockStatement[]} */ private readonly collectedBlockStatements: ESTree.BlockStatement[] = []; /** * @type {number} */ private collectedBlockStatementsTotalLength: number = 0; /** * @type {TDeadNodeInjectionCustomNodeFactory} */ private readonly deadCodeInjectionCustomNodeFactory: TDeadNodeInjectionCustomNodeFactory; /** * @type {INodeTransformersRunner} */ private readonly transformersRunner: INodeTransformersRunner; /** * @param {TDeadNodeInjectionCustomNodeFactory} deadCodeInjectionCustomNodeFactory * @param {INodeTransformersRunner} transformersRunner * @param {IRandomGenerator} randomGenerator * @param {IOptions} options */ public constructor ( @inject(ServiceIdentifiers.Factory__IDeadCodeInjectionCustomNode) deadCodeInjectionCustomNodeFactory: TDeadNodeInjectionCustomNodeFactory, @inject(ServiceIdentifiers.INodeTransformersRunner) transformersRunner: INodeTransformersRunner, @inject(ServiceIdentifiers.IRandomGenerator) randomGenerator: IRandomGenerator, @inject(ServiceIdentifiers.IOptions) options: IOptions ) { super(randomGenerator, options); this.deadCodeInjectionCustomNodeFactory = deadCodeInjectionCustomNodeFactory; this.transformersRunner = transformersRunner; } /** * @param {Node} targetNode * @returns {boolean} */ private static isProhibitedNodeInsideCollectedBlockStatement (targetNode: ESTree.Node): boolean { return NodeGuards.isFunctionDeclarationNode(targetNode) // can break code on strict mode || NodeGuards.isBreakStatementNode(targetNode) || NodeGuards.isContinueStatementNode(targetNode) || NodeGuards.isAwaitExpressionNode(targetNode) || NodeGuards.isYieldExpressionNode(targetNode) || NodeGuards.isSuperNode(targetNode) || (NodeGuards.isForOfStatementNode(targetNode) && targetNode.await); } /** * @param {Node} targetNode * @returns {boolean} */ private static isScopeHoistingFunctionDeclaration (targetNode: ESTree.Node): boolean { if (!NodeGuards.isFunctionDeclarationNode(targetNode)) { return false; } const scopeNode: TNodeWithStatements = NodeStatementUtils.getScopeOfNode(targetNode); const scopeBody: ESTree.Statement[] = !NodeGuards.isSwitchCaseNode(scopeNode) ? <ESTree.Statement[]>scopeNode.body : scopeNode.consequent; const indexInScope: number = scopeBody.indexOf(targetNode); if (indexInScope === 0) { return false; } const slicedBody: ESTree.Statement[] = scopeBody.slice(0, indexInScope); const hostBlockStatementNode: ESTree.BlockStatement = NodeFactory.blockStatementNode(slicedBody); const functionDeclarationName: string = targetNode.id.name; let isScopeHoistedFunctionDeclaration: boolean = false; estraverse.traverse(hostBlockStatementNode, { enter: (node: ESTree.Node): estraverse.VisitorOption | void => { if (NodeGuards.isIdentifierNode(node) && node.name === functionDeclarationName) { isScopeHoistedFunctionDeclaration = true; return estraverse.VisitorOption.Break; } } }); return isScopeHoistedFunctionDeclaration; } /** * @param {BlockStatement} blockStatementNode * @returns {boolean} */ private static isValidCollectedBlockStatementNode (blockStatementNode: ESTree.BlockStatement): boolean { if (!blockStatementNode.body.length) { return false; } let nestedBlockStatementsCount: number = 0; let isValidBlockStatementNode: boolean = true; estraverse.traverse(blockStatementNode, { enter: (node: ESTree.Node): estraverse.VisitorOption | void => { if (NodeGuards.isBlockStatementNode(node)) { nestedBlockStatementsCount++; } if ( nestedBlockStatementsCount > DeadCodeInjectionTransformer.maxNestedBlockStatementsCount || DeadCodeInjectionTransformer.isProhibitedNodeInsideCollectedBlockStatement(node) || DeadCodeInjectionTransformer.isScopeHoistingFunctionDeclaration(node) ) { isValidBlockStatementNode = false; return estraverse.VisitorOption.Break; } } }); return isValidBlockStatementNode; } /** * @param {BlockStatement} blockStatementNode * @returns {boolean} */ private static isValidWrappedBlockStatementNode (blockStatementNode: ESTree.BlockStatement): boolean { if (!blockStatementNode.body.length) { return false; } let isValidBlockStatementNode: boolean = true; estraverse.traverse(blockStatementNode, { enter: (node: ESTree.Node): estraverse.VisitorOption | void => { if (DeadCodeInjectionTransformer.isScopeHoistingFunctionDeclaration(node)) { isValidBlockStatementNode = false; return estraverse.VisitorOption.Break; } } }); if (!isValidBlockStatementNode) { return false; } const parentNodeWithStatements: TNodeWithStatements = NodeStatementUtils .getParentNodeWithStatements(blockStatementNode); return parentNodeWithStatements.type !== NodeType.Program; } /** * @param {NodeTransformationStage} nodeTransformationStage * @returns {IVisitor | null} */ public getVisitor (nodeTransformationStage: NodeTransformationStage): IVisitor | null { switch (nodeTransformationStage) { case NodeTransformationStage.DeadCodeInjection: return { enter: (node: ESTree.Node, parentNode: ESTree.Node | null): ESTree.Node | undefined => { if (parentNode && NodeGuards.isProgramNode(node)) { this.prepareNode(node, parentNode); return node; } }, leave: ( node: ESTree.Node, parentNode: ESTree.Node | null ): ESTree.Node | estraverse.VisitorOption | undefined => { if (parentNode && NodeGuards.isBlockStatementNode(node)) { return this.transformNode(node, parentNode); } } }; case NodeTransformationStage.RenameIdentifiers: if (!this.deadCodeInjectionRootAstHostNodeSet.size) { return null; } return { enter: ( node: ESTree.Node, parentNode: ESTree.Node | null ): ESTree.Node | estraverse.VisitorOption |undefined => { if (parentNode && this.isDeadCodeInjectionRootAstHostNode(node)) { return this.restoreNode(node, parentNode); } } }; default: return null; } } /** * @param {NodeGuards} programNode * @param {NodeGuards} parentNode */ public prepareNode (programNode: ESTree.Node, parentNode: ESTree.Node): void { estraverse.traverse(programNode, { enter: (node: ESTree.Node): void => { if (!NodeGuards.isBlockStatementNode(node)) { return; } const clonedBlockStatementNode: ESTree.BlockStatement = NodeUtils.clone(node); if (!DeadCodeInjectionTransformer.isValidCollectedBlockStatementNode(clonedBlockStatementNode)) { return; } /** * We should transform identifiers in the dead code block statement to avoid conflicts with original code */ const transformedBlockStatementNode: ESTree.BlockStatement = this.makeClonedBlockStatementNodeUnique(clonedBlockStatementNode); this.collectedBlockStatements.push(transformedBlockStatementNode); } }); this.collectedBlockStatementsTotalLength = this.collectedBlockStatements.length; } /** * @param {BlockStatement} blockStatementNode * @param {NodeGuards} parentNode * @returns {NodeGuards | VisitorOption} */ public transformNode ( blockStatementNode: ESTree.BlockStatement, parentNode: ESTree.Node ): ESTree.Node | estraverse.VisitorOption { const canBreakTraverse: boolean = !this.collectedBlockStatements.length || this.collectedBlockStatementsTotalLength < DeadCodeInjectionTransformer.minCollectedBlockStatementsCount; if (canBreakTraverse) { return estraverse.VisitorOption.Break; } if ( this.randomGenerator.getMathRandom() > this.options.deadCodeInjectionThreshold || !DeadCodeInjectionTransformer.isValidWrappedBlockStatementNode(blockStatementNode) ) { return blockStatementNode; } const minInteger: number = 0; const maxInteger: number = this.collectedBlockStatements.length - 1; const randomIndex: number = this.randomGenerator.getRandomInteger(minInteger, maxInteger); const randomBlockStatementNode: ESTree.BlockStatement = this.collectedBlockStatements.splice(randomIndex, 1)[0]; const isDuplicateBlockStatementNodes: boolean = randomBlockStatementNode === blockStatementNode; if (isDuplicateBlockStatementNodes) { return blockStatementNode; } return this.replaceBlockStatementNode(blockStatementNode, randomBlockStatementNode, parentNode); } /** * @param {FunctionExpression} deadCodeInjectionRootAstHostNode * @param {Node} parentNode * @returns {Node} */ public restoreNode (deadCodeInjectionRootAstHostNode: ESTree.BlockStatement, parentNode: ESTree.Node): ESTree.Node { const hostNodeFirstStatement: ESTree.Statement = deadCodeInjectionRootAstHostNode.body[0]; if (!NodeGuards.isFunctionDeclarationNode(hostNodeFirstStatement)) { throw new Error('Wrong dead code injection root AST host node. Host node should contain `FunctionDeclaration` node'); } return hostNodeFirstStatement.body; } /** * @param {Node} node * @returns {boolean} */ private isDeadCodeInjectionRootAstHostNode (node: ESTree.Node): node is ESTree.BlockStatement { return NodeGuards.isBlockStatementNode(node) && this.deadCodeInjectionRootAstHostNodeSet.has(node); } /** * Make all identifiers in cloned block statement unique * * @param {BlockStatement} clonedBlockStatementNode * @returns {BlockStatement} */ private makeClonedBlockStatementNodeUnique (clonedBlockStatementNode: ESTree.BlockStatement): ESTree.BlockStatement { // should wrap cloned block statement node into function node for correct scope encapsulation const hostNode: ESTree.Program = NodeFactory.programNode([ NodeFactory.expressionStatementNode( NodeFactory.functionExpressionNode([], clonedBlockStatementNode) ) ]); NodeUtils.parentizeAst(hostNode); NodeUtils.parentizeNode(hostNode, hostNode); this.transformersRunner.transform( hostNode, DeadCodeInjectionTransformer.transformersToRenameBlockScopeIdentifiers, NodeTransformationStage.RenameIdentifiers ); return clonedBlockStatementNode; } /** * @param {BlockStatement} blockStatementNode * @param {BlockStatement} randomBlockStatementNode * @param {Node} parentNode * @returns {BlockStatement} */ private replaceBlockStatementNode ( blockStatementNode: ESTree.BlockStatement, randomBlockStatementNode: ESTree.BlockStatement, parentNode: ESTree.Node ): ESTree.BlockStatement { /** * Should wrap original random block statement node into the parent block statement node (ast root host node) * with function declaration node. This function declaration node will create block scope for all identifiers * inside random block statement node and this identifiers won't affect identifiers of the rest AST tree. */ const deadCodeInjectionRootAstHostNode: ESTree.BlockStatement = NodeFactory.blockStatementNode([ NodeFactory.functionDeclarationNode( DeadCodeInjectionTransformer.deadCodeInjectionRootAstHostNodeName, [], randomBlockStatementNode ) ]); /** * Should store that host node and then extract random block statement node on the `finalizing` stage */ this.deadCodeInjectionRootAstHostNodeSet.add(deadCodeInjectionRootAstHostNode); const blockStatementDeadCodeInjectionCustomNode: ICustomNode<TInitialData<BlockStatementDeadCodeInjectionNode>> = this.deadCodeInjectionCustomNodeFactory(DeadCodeInjectionCustomNode.BlockStatementDeadCodeInjectionNode); blockStatementDeadCodeInjectionCustomNode.initialize(blockStatementNode, deadCodeInjectionRootAstHostNode); const newBlockStatementNode: ESTree.BlockStatement = <ESTree.BlockStatement>blockStatementDeadCodeInjectionCustomNode.getNode()[0]; NodeUtils.parentizeNode(newBlockStatementNode, parentNode); return newBlockStatementNode; } }
the_stack
import { Construct } from 'constructs'; import { CfnElement } from './cfn-element'; import { IResolvable, IResolveContext } from './resolvable'; /** * @stability stable */ export interface CfnParameterProps { /** * The data type for the parameter (DataType). * * @default String * @stability stable */ readonly type?: string; /** * A value of the appropriate type for the template to use if no value is specified when a stack is created. * * If you define constraints for the parameter, you must specify * a value that adheres to those constraints. * * @default - No default value for parameter. * @stability stable */ readonly default?: any; /** * A regular expression that represents the patterns to allow for String types. * * @default - No constraints on patterns allowed for parameter. * @stability stable */ readonly allowedPattern?: string; /** * An array containing the list of values allowed for the parameter. * * @default - No constraints on values allowed for parameter. * @stability stable */ readonly allowedValues?: string[]; /** * A string that explains a constraint when the constraint is violated. * * For example, without a constraint description, a parameter that has an allowed * pattern of [A-Za-z0-9]+ displays the following error message when the user specifies * an invalid value: * * @default - No description with customized error message when user specifies invalid values. * @stability stable */ readonly constraintDescription?: string; /** * A string of up to 4000 characters that describes the parameter. * * @default - No description for the parameter. * @stability stable */ readonly description?: string; /** * An integer value that determines the largest number of characters you want to allow for String types. * * @default - None. * @stability stable */ readonly maxLength?: number; /** * A numeric value that determines the largest numeric value you want to allow for Number types. * * @default - None. * @stability stable */ readonly maxValue?: number; /** * An integer value that determines the smallest number of characters you want to allow for String types. * * @default - None. * @stability stable */ readonly minLength?: number; /** * A numeric value that determines the smallest numeric value you want to allow for Number types. * * @default - None. * @stability stable */ readonly minValue?: number; /** * Whether to mask the parameter value when anyone makes a call that describes the stack. * * If you set the value to ``true``, the parameter value is masked with asterisks (``*****``). * * @default - Parameter values are not masked. * @stability stable */ readonly noEcho?: boolean; } /** * A CloudFormation parameter. * * Use the optional Parameters section to customize your templates. * Parameters enable you to input custom values to your template each time you create or * update a stack. * * @stability stable */ export declare class CfnParameter extends CfnElement { private _type; private _default?; private _allowedPattern?; private _allowedValues?; private _constraintDescription?; private _description?; private _maxLength?; private _maxValue?; private _minLength?; private _minValue?; private _noEcho?; /** * Creates a parameter construct. * * Note that the name (logical ID) of the parameter will derive from it's `coname` and location * within the stack. Therefore, it is recommended that parameters are defined at the stack level. * * @param scope The parent construct. * @param props The parameter properties. * @stability stable */ constructor(scope: Construct, id: string, props?: CfnParameterProps); /** * The data type for the parameter (DataType). * * @default String * @stability stable */ get type(): string; /** * The data type for the parameter (DataType). * * @default String * @stability stable */ set type(type: string); /** * A value of the appropriate type for the template to use if no value is specified when a stack is created. * * If you define constraints for the parameter, you must specify * a value that adheres to those constraints. * * @default - No default value for parameter. * @stability stable */ get default(): any; /** * A value of the appropriate type for the template to use if no value is specified when a stack is created. * * If you define constraints for the parameter, you must specify * a value that adheres to those constraints. * * @default - No default value for parameter. * @stability stable */ set default(value: any); /** * A regular expression that represents the patterns to allow for String types. * * @default - No constraints on patterns allowed for parameter. * @stability stable */ get allowedPattern(): string | undefined; /** * A regular expression that represents the patterns to allow for String types. * * @default - No constraints on patterns allowed for parameter. * @stability stable */ set allowedPattern(pattern: string | undefined); /** * An array containing the list of values allowed for the parameter. * * @default - No constraints on values allowed for parameter. * @stability stable */ get allowedValues(): string[] | undefined; /** * An array containing the list of values allowed for the parameter. * * @default - No constraints on values allowed for parameter. * @stability stable */ set allowedValues(values: string[] | undefined); /** * A string that explains a constraint when the constraint is violated. * * For example, without a constraint description, a parameter that has an allowed * pattern of [A-Za-z0-9]+ displays the following error message when the user specifies * an invalid value: * * @default - No description with customized error message when user specifies invalid values. * @stability stable */ get constraintDescription(): string | undefined; /** * A string that explains a constraint when the constraint is violated. * * For example, without a constraint description, a parameter that has an allowed * pattern of [A-Za-z0-9]+ displays the following error message when the user specifies * an invalid value: * * @default - No description with customized error message when user specifies invalid values. * @stability stable */ set constraintDescription(desc: string | undefined); /** * A string of up to 4000 characters that describes the parameter. * * @default - No description for the parameter. * @stability stable */ get description(): string | undefined; /** * A string of up to 4000 characters that describes the parameter. * * @default - No description for the parameter. * @stability stable */ set description(desc: string | undefined); /** * An integer value that determines the largest number of characters you want to allow for String types. * * @default - None. * @stability stable */ get maxLength(): number | undefined; /** * An integer value that determines the largest number of characters you want to allow for String types. * * @default - None. * @stability stable */ set maxLength(len: number | undefined); /** * An integer value that determines the smallest number of characters you want to allow for String types. * * @default - None. * @stability stable */ get minLength(): number | undefined; /** * An integer value that determines the smallest number of characters you want to allow for String types. * * @default - None. * @stability stable */ set minLength(len: number | undefined); /** * A numeric value that determines the largest numeric value you want to allow for Number types. * * @default - None. * @stability stable */ get maxValue(): number | undefined; /** * A numeric value that determines the largest numeric value you want to allow for Number types. * * @default - None. * @stability stable */ set maxValue(len: number | undefined); /** * A numeric value that determines the smallest numeric value you want to allow for Number types. * * @default - None. * @stability stable */ get minValue(): number | undefined; /** * A numeric value that determines the smallest numeric value you want to allow for Number types. * * @default - None. * @stability stable */ set minValue(len: number | undefined); /** * Indicates if this parameter is configured with "NoEcho" enabled. * * @stability stable */ get noEcho(): boolean; /** * Indicates if this parameter is configured with "NoEcho" enabled. * * @stability stable */ set noEcho(echo: boolean); /** * The parameter value as a Token. * * @stability stable */ get value(): IResolvable; /** * The parameter value, if it represents a string. * * @stability stable */ get valueAsString(): string; /** * The parameter value, if it represents a string list. * * @stability stable */ get valueAsList(): string[]; /** * The parameter value, if it represents a number. * * @stability stable */ get valueAsNumber(): number; /** * @internal */ _toCloudFormation(): object; /** * @stability stable */ resolve(_context: IResolveContext): any; }
the_stack
import { createNanoEvents } from 'nanoevents' import type { CSSEntries, CSSObject, ExtractorContext, GenerateOptions, GenerateResult, ParsedUtil, PreflightContext, RawUtil, ResolvedConfig, Rule, RuleContext, RuleMeta, Shortcut, StringifiedUtil, UserConfig, UserConfigDefaults, UtilObject, Variant, VariantContext, VariantHandler, VariantMatchedResult } from '../types' import { resolveConfig } from '../config' import { CONTROL_SHORTCUT_NO_MERGE, TwoKeyMap, e, entriesToCss, expandVariantGroup, isRawUtil, isStaticShortcut, noop, normalizeCSSEntries, normalizeCSSValues, notNull, uniq, warnOnce } from '../utils' import { version } from '../../package.json' export class UnoGenerator { public version = version private _cache = new Map<string, StringifiedUtil[] | null>() public config: ResolvedConfig public blocked = new Set<string>() public parentOrders = new Map<string, number>() public events = createNanoEvents<{ config: (config: ResolvedConfig) => void }>() constructor( public userConfig: UserConfig = {}, public defaults: UserConfigDefaults = {}, ) { this.config = resolveConfig(userConfig, defaults) this.events.emit('config', this.config) } setConfig(userConfig?: UserConfig, defaults?: UserConfigDefaults) { if (!userConfig) return if (defaults) this.defaults = defaults this.userConfig = userConfig this.blocked.clear() this.parentOrders.clear() this._cache.clear() this.config = resolveConfig(userConfig, this.defaults) this.events.emit('config', this.config) } async applyExtractors(code: string, id?: string, set = new Set<string>()) { const context: ExtractorContext = { get original() { return code }, code, id, } for (const extractor of this.config.extractors) { const result = await extractor.extract(context) result?.forEach(t => set.add(t)) } return set } makeContext(raw: string, applied: VariantMatchedResult) { const context: RuleContext = { rawSelector: raw, currentSelector: applied[1], theme: this.config.theme, generator: this, variantHandlers: applied[2], constructCSS: (...args) => this.constructCustomCSS(context, ...args), variantMatch: applied, } return context } async parseToken(raw: string, alias?: string) { if (this.blocked.has(raw)) return const cacheKey = `${raw}${alias ? ` ${alias}` : ''}` // use caches if possible if (this._cache.has(cacheKey)) return this._cache.get(cacheKey) let current = raw for (const p of this.config.preprocess) current = p(raw)! if (this.isBlocked(current)) { this.blocked.add(raw) this._cache.set(cacheKey, null) return } const applied = this.matchVariants(raw, current) if (!applied || this.isBlocked(applied[1])) { this.blocked.add(raw) this._cache.set(cacheKey, null) return } const context = this.makeContext( raw, [alias || applied[0], applied[1], applied[2], applied[3]], ) if (this.config.details) context.variants = [...applied[3]] // expand shortcuts const expanded = this.expandShortcut(context.currentSelector, context) if (expanded) { const utils = await this.stringifyShortcuts(context.variantMatch, context, expanded[0], expanded[1]) if (utils?.length) { this._cache.set(cacheKey, utils) return utils } } // no shortcut else { const utils = (await this.parseUtil(context.variantMatch, context))?.map(i => this.stringifyUtil(i, context)).filter(notNull) if (utils?.length) { this._cache.set(cacheKey, utils) return utils } } // set null cache for unmatched result this._cache.set(cacheKey, null) } async generate( input: string | Set<string> = '', { id, scope, preflights = true, safelist = true, minify = false, }: GenerateOptions = {}, ): Promise<GenerateResult> { const tokens = typeof input === 'string' ? await this.applyExtractors(input, id) : input if (safelist) this.config.safelist.forEach(s => tokens.add(s)) const nl = minify ? '' : '\n' const layerSet = new Set<string>(['default']) const matched = new Set<string>() const sheet = new Map<string, StringifiedUtil[]>() await Promise.all(Array.from(tokens).map(async (raw) => { if (matched.has(raw)) return const payload = await this.parseToken(raw) if (payload == null) return matched.add(raw) for (const item of payload) { const parent = item[3] || '' if (!sheet.has(parent)) sheet.set(parent, []) sheet.get(parent)!.push(item) if (item[4]?.layer) layerSet.add(item[4].layer) } })) if (preflights) { this.config.preflights.forEach((i) => { if (i.layer) layerSet.add(i.layer) }) } const layerCache: Record<string, string> = {} const layers = this.config.sortLayers(Array .from(layerSet) .sort((a, b) => ((this.config.layers[a] ?? 0) - (this.config.layers[b] ?? 0)) || a.localeCompare(b)), ) let preflightsMap: Record<string, string> = {} if (preflights) { const preflightContext: PreflightContext = { generator: this, theme: this.config.theme, } preflightsMap = Object.fromEntries( await Promise.all(layers.map( async (layer) => { const preflights = await Promise.all( this.config.preflights .filter(i => (i.layer || 'default') === layer) .map(async i => await i.getCSS(preflightContext)), ) const css = preflights .filter(Boolean) .join(nl) return [layer, css] }, )), ) } const getLayer = (layer: string) => { if (layerCache[layer]) return layerCache[layer] let css = Array.from(sheet) .sort((a, b) => ((this.parentOrders.get(a[0]) ?? 0) - (this.parentOrders.get(b[0]) ?? 0)) || a[0]?.localeCompare(b[0] || '') || 0) .map(([parent, items]) => { const size = items.length const sorted = items .filter(i => (i[4]?.layer || 'default') === layer) .sort((a, b) => a[0] - b[0] || (a[4]?.sort || 0) - (b[4]?.sort || 0) || a[1]?.localeCompare(b[1] || '') || 0) .map(a => [a[1] ? applyScope(a[1], scope) : a[1], a[2], !!a[4]?.noMerge]) .map(a => [a[0] == null ? a[0] : [a[0]], a[1], a[2]]) as [string[] | undefined, string, boolean][] if (!sorted.length) return undefined const rules = sorted .reverse() .map(([selector, body, noMerge], idx) => { if (!noMerge && selector && this.config.mergeSelectors) { // search for rules that has exact same body, and merge them for (let i = idx + 1; i < size; i++) { const current = sorted[i] if (current && !current[2] && current[0] && current[1] === body) { current[0].push(...selector) return null } } } return selector ? `${[...new Set(selector)].join(`,${nl}`)}{${body}}` : body }) .filter(Boolean) .reverse() .join(nl) return parent ? `${parent}{${nl}${rules}${nl}}` : rules }) .filter(Boolean) .join(nl) if (preflights) { css = [preflightsMap[layer], css] .filter(Boolean) .join(nl) } return layerCache[layer] = !minify && css ? `/* layer: ${layer} */${nl}${css}` : css } const getLayers = (includes = layers, excludes?: string[]) => { return includes .filter(i => !excludes?.includes(i)) .map(i => getLayer(i) || '') .filter(Boolean) .join(nl) } return { get css() { return getLayers() }, layers, getLayers, getLayer, matched, } } matchVariants(raw: string, current?: string): VariantMatchedResult { // process variants const variants = new Set<Variant>() const handlers: VariantHandler[] = [] let processed = current || raw let applied = false const context: VariantContext = { rawSelector: raw, theme: this.config.theme, generator: this, } while (true) { applied = false for (const v of this.config.variants) { if (!v.multiPass && variants.has(v)) continue let handler = v.match(processed, context) if (!handler) continue if (typeof handler === 'string') handler = { matcher: handler } processed = handler.matcher if (Array.isArray(handler.parent)) this.parentOrders.set(handler.parent[0], handler.parent[1]) handlers.push(handler) variants.add(v) applied = true break } if (!applied) break if (handlers.length > 500) throw new Error(`Too many variants applied to "${raw}"`) } return [raw, processed, handlers, variants] } applyVariants(parsed: ParsedUtil, variantHandlers = parsed[4], raw = parsed[1]): UtilObject { const handlers = [...variantHandlers].sort((a, b) => (a.order || 0) - (b.order || 0)) const entries = handlers.reduce((p, v) => v.body?.(p) || p, parsed[2]) const obj: UtilObject = { selector: handlers.reduce((p, v) => v.selector?.(p, entries) || p, toEscapedSelector(raw)), entries, parent: handlers.reduce((p: string | undefined, v) => Array.isArray(v.parent) ? v.parent[0] : v.parent || p, undefined), layer: handlers.reduce((p: string | undefined, v) => v.layer || p, undefined), sort: handlers.reduce((p: number | undefined, v) => v.sort || p, undefined), } for (const p of this.config.postprocess) p(obj) return obj } constructCustomCSS(context: Readonly<RuleContext>, body: CSSObject | CSSEntries, overrideSelector?: string) { body = normalizeCSSEntries(body) const { selector, entries, parent } = this.applyVariants([0, overrideSelector || context.rawSelector, body, undefined, context.variantHandlers]) const cssBody = `${selector}{${entriesToCss(entries)}}` if (parent) return `${parent}{${cssBody}}` return cssBody } async parseUtil(input: string | VariantMatchedResult, context: RuleContext, internal = false): Promise<ParsedUtil[] | RawUtil[] | undefined> { const [raw, processed, variantHandlers] = typeof input === 'string' ? this.matchVariants(input) : input const recordRule = this.config.details ? (r: Rule) => { context.rules = context.rules ?? [] context.rules.push(r) } : noop // use map to for static rules const staticMatch = this.config.rulesStaticMap[processed] if (staticMatch) { if (staticMatch[1] && (internal || !staticMatch[2]?.internal)) { recordRule(staticMatch[3]) return [[staticMatch[0], raw, normalizeCSSEntries(staticMatch[1]), staticMatch[2], variantHandlers]] } } context.variantHandlers = variantHandlers const { rulesDynamic, rulesSize } = this.config // match rules, from last to first for (let i = rulesSize - 1; i >= 0; i--) { const rule = rulesDynamic[i] // static rules are omitted as undefined if (!rule) continue // ignore internal rules if (rule[2]?.internal && !internal) continue // dynamic rules const [matcher, handler, meta] = rule const match = processed.match(matcher) if (!match) continue const result = await handler(match, context) if (!result) continue recordRule(rule) if (typeof result === 'string') return [[i, result, meta]] const entries = normalizeCSSValues(result).filter(i => i.length) if (entries.length) return entries.map(e => [i, raw, e, meta, variantHandlers]) } } stringifyUtil(parsed?: ParsedUtil | RawUtil, context?: RuleContext): StringifiedUtil | undefined { if (!parsed) return if (isRawUtil(parsed)) return [parsed[0], undefined, parsed[1], undefined, parsed[2], this.config.details ? context : undefined] const { selector, entries, parent, layer: variantLayer, sort: variantSort } = this.applyVariants(parsed) const body = entriesToCss(entries) if (!body) return const { layer: metaLayer, sort: metaSort, ...meta } = parsed[3] ?? {} const ruleMeta = { ...meta, layer: variantLayer ?? metaLayer, sort: variantSort ?? metaSort, } return [parsed[0], selector, body, parent, ruleMeta, this.config.details ? context : undefined] } expandShortcut(processed: string, context: RuleContext, depth = 3): [string[], RuleMeta | undefined] | undefined { if (depth === 0) return const recordShortcut = this.config.details ? (s: Shortcut) => { context.shortcuts = context.shortcuts ?? [] context.shortcuts.push(s) } : noop let meta: RuleMeta | undefined let result: string | string[] | undefined for (const s of this.config.shortcuts) { if (isStaticShortcut(s)) { if (s[0] === processed) { meta = meta || s[2] result = s[1] recordShortcut(s) break } } else { const match = processed.match(s[0]) if (match) result = s[1](match, context) if (result) { meta = meta || s[2] recordShortcut(s) break } } } if (typeof result === 'string') result = expandVariantGroup(result).split(/\s+/g) if (!result) return return [ result .flatMap(r => this.expandShortcut(r, context, depth - 1)?.[0] || [r]) .filter(r => r !== ''), meta, ] } async stringifyShortcuts( parent: VariantMatchedResult, context: RuleContext, expanded: string[], meta: RuleMeta = { layer: this.config.shortcutsLayer }, ): Promise<StringifiedUtil[] | undefined> { const selectorMap = new TwoKeyMap<string, string | undefined, [[CSSEntries, boolean, number][], number]>() const parsed = ( await Promise.all(uniq(expanded) .map(async (i) => { const result = await this.parseUtil(i, context, true) if (!result) warnOnce(`unmatched utility "${i}" in shortcut "${parent[1]}"`) return (result || []) as ParsedUtil[] }))) .flat(1) .filter(Boolean) .sort((a, b) => a[0] - b[0]) const [raw, , parentVariants] = parent const rawStringfieldUtil: StringifiedUtil[] = [] for (const item of parsed) { if (isRawUtil(item)) { rawStringfieldUtil.push([item[0], undefined, item[1], undefined, item[2], context]) continue } const { selector, entries, parent, sort } = this.applyVariants(item, [...item[4], ...parentVariants], raw) // find existing selector/mediaQuery pair and merge const mapItem = selectorMap.getFallback(selector, parent, [[], item[0]]) // add entries mapItem[0].push([entries, !!item[3]?.noMerge, sort ?? 0]) } return rawStringfieldUtil.concat(selectorMap .map(([e, index], selector, mediaQuery) => { const stringify = (flatten: boolean, noMerge: boolean, entrySortPair: [CSSEntries, number][]): (StringifiedUtil | undefined)[] => { const maxSort = Math.max(...entrySortPair.map(e => e[1])) const entriesList = entrySortPair.map(e => e[0]) return (flatten ? [entriesList.flat(1)] : entriesList).map((entries: CSSEntries): StringifiedUtil | undefined => { const body = entriesToCss(entries) if (body) return [index, selector, body, mediaQuery, { ...meta, noMerge, sort: maxSort }, context] return undefined }) } const merges = [ [e.filter(([, noMerge]) => noMerge).map(([entries,, sort]) => [entries, sort]), true], [e.filter(([, noMerge]) => !noMerge).map(([entries,, sort]) => [entries, sort]), false], ] as [[CSSEntries, number][], boolean][] return merges.map(([e, noMerge]) => [ ...stringify(false, noMerge, e.filter(([entries]) => entries.some(entry => entry[0] === CONTROL_SHORTCUT_NO_MERGE))), ...stringify(true, noMerge, e.filter(([entries]) => entries.every(entry => entry[0] !== CONTROL_SHORTCUT_NO_MERGE))), ]) }) .flat(2) .filter(Boolean) as StringifiedUtil[]) } isBlocked(raw: string) { return !raw || this.config.blocklist.some(e => typeof e === 'string' ? e === raw : e.test(raw)) } } export function createGenerator(config?: UserConfig, defaults?: UserConfigDefaults) { return new UnoGenerator(config, defaults) } export const regexScopePlaceholder = / \$\$ / export const hasScopePlaceholder = (css: string) => css.match(regexScopePlaceholder) function applyScope(css: string, scope?: string) { if (hasScopePlaceholder(css)) return css.replace(regexScopePlaceholder, scope ? ` ${scope} ` : ' ') else return scope ? `${scope} ${css}` : css } const attributifyRe = /^\[(.+?)(~?=)"(.*)"\]$/ export function toEscapedSelector(raw: string) { if (attributifyRe.test(raw)) return raw.replace(attributifyRe, (_, n, s, i) => `[${e(n)}${s}"${e(i)}"]`) return `.${e(raw)}` }
the_stack
import { execSync } from 'child_process'; import { browser, ExpectedConditions as until } from 'protractor'; import { testName } from '@console/internal-integration-tests/protractor.conf'; import { detailViewAction as vmActions } from '../utils/shared-actions.view'; import { click, createResource, deleteResource, getDropdownOptions, selectDropdownOption, selectDropdownOptionById, waitForStringInElement, } from '../utils/shared-utils'; import { consoleTypeSelector, consoleTypeSelectorId, desktopClientTitle, launchRemoteDesktopButton, launchRemoteViewerButton, manualConnectionTitle, networkSelectorId, rdpManualConnectionTitles, rdpManualConnectionValues, rdpServiceNotConfiguredElem, } from '../views/consolesView'; import * as dashboardView from '../views/dashboard.view'; import * as vmView from '../views/virtualMachine.view'; import * as disksView from '../views/vm.disks.view'; import { getVMManifest, multusNAD } from './mocks/mocks'; import { VirtualMachine } from './models/virtualMachine'; import { GUEST_AGENT_FIELD_TIMEOUT_SECS, KUBEVIRT_SCRIPTS_PATH, PAGE_LOAD_TIMEOUT_SECS, SEC, VM_CREATE_AND_EDIT_AND_CLOUDINIT_TIMEOUT_SECS, VM_CREATE_AND_EDIT_TIMEOUT_SECS, VM_WITH_GA_CREATE_AND_EDIT_CLOUDINIT_TIMEOUT_SECS, } from './utils/constants/common'; import { ProvisionSource } from './utils/constants/enums/provisionSource'; import { VM_ACTION, VM_STATUS } from './utils/constants/vm'; import { getFakeWindowsVM } from './utils/templates/windowsVMForRDPL2'; const VM_LINUX_NAME = `${testName}-linux-vm`; const VM_WINDOWS_NAME = 'windows-rdp'; const VM_WINDOWS_IP = '123.123.123.123'; const environmentExpecScriptPath = `${KUBEVIRT_SCRIPTS_PATH}/guest-agent-login.sh`; const JASMINE_EXTENDED_TIMEOUT_INTERVAL = 3000 * 60 * 5; describe('Tests involving guest agent', () => { let vmLinux: VirtualMachine; let vmWindows: VirtualMachine; beforeAll(async () => { createResource(multusNAD); // create linux vm const cloudInit = '#cloud-config\nuser: cloud-user\npassword: atomic\nchpasswd: {expire: False}\nruncmd:\n- dnf install -y qemu-guest-agent\n- systemctl start qemu-guest-agent'; const testVM = getVMManifest(ProvisionSource.CONTAINER, testName, VM_LINUX_NAME, cloudInit); vmLinux = new VirtualMachine(testVM.metadata); createResource(testVM); await vmLinux.detailViewAction(VM_ACTION.Start, false); await browser.sleep(GUEST_AGENT_FIELD_TIMEOUT_SECS); await vmLinux.waitForStatus(VM_STATUS.Running, SEC * 600); execSync( `expect ${environmentExpecScriptPath} ${VM_LINUX_NAME} ${vmLinux.namespace} ${VM_LINUX_NAME}`, ); await browser.sleep(GUEST_AGENT_FIELD_TIMEOUT_SECS); await vmLinux.navigateToOverview(); // create windows VM execSync('kubectl create -f -', { input: getFakeWindowsVM({ name: VM_WINDOWS_NAME, networkName: multusNAD.metadata.name, vmIP: VM_WINDOWS_IP, }), }); vmWindows = new VirtualMachine({ name: VM_WINDOWS_NAME, namespace: testName }); }, VM_WITH_GA_CREATE_AND_EDIT_CLOUDINIT_TIMEOUT_SECS); afterAll(async () => { deleteResource(multusNAD); deleteResource(vmLinux.asResource()); deleteResource(vmWindows.asResource()); }); describe('Testing guest agent data', () => { jasmine.DEFAULT_TIMEOUT_INTERVAL = JASMINE_EXTENDED_TIMEOUT_INTERVAL; it('ID(CNV-5318) Displays guest agent data in Details tab', async () => { await vmLinux.navigateToDetail(); await browser.wait( until.presenceOf(vmView.vmDetailsActiveUsersList), GUEST_AGENT_FIELD_TIMEOUT_SECS, ); expect(vmView.vmDetailHostname(testName, VM_LINUX_NAME).getText()).toContain(VM_LINUX_NAME); expect(vmView.vmDetailTimeZone(testName, VM_LINUX_NAME).getText()).toEqual('UTC'); expect(vmView.vmDetailsActiveUsersList.getText()).toEqual('cloud-user'); }); it('ID(CNV-5319) Displays guest agent data in Overview tab', async () => { await vmLinux.navigateToOverview(); expect(dashboardView.vmDetailsHostname.getText()).toContain(VM_LINUX_NAME); expect(dashboardView.vmDetailsTZ.getText()).toContain('UTC'); expect(dashboardView.vmDetailsNumActiveUsersMsg.getText()).toEqual('1 user'); }); it('ID(CNV-5320) Displays guest agent data in Disks tab', async () => { await vmLinux.navigateToDisks(); await browser.wait( until.presenceOf(disksView.fileSystemsTableHeader), GUEST_AGENT_FIELD_TIMEOUT_SECS, ); expect(disksView.fileSystemsTable).toBeDefined(); }); it('ID(CNV-5472) Warn user when deleting a VM which has a logged in user ', async () => { await vmLinux.navigateToDetail(); await vmActions(VM_ACTION.Delete, false); await browser.wait(until.visibilityOf(vmView.vmDeleteAlert)); expect(vmView.vmDeleteAlert.getText()).toContain('1 User currently logged in to this VM'); }); }); describe('Testing console RDP connections', () => { it( 'ID(CNV-1721) connects via exposed service', async () => { await vmWindows.navigateToDetail(); await vmWindows.navigateToConsole(); await browser.wait(until.presenceOf(consoleTypeSelector)); await click(consoleTypeSelector); await browser.wait( waitForStringInElement(consoleTypeSelector, 'VNC Console'), PAGE_LOAD_TIMEOUT_SECS, ); const items = await getDropdownOptions(consoleTypeSelectorId); expect(items[0]).toBe('VNC Console'); expect(items[1]).toBe('Serial Console'); expect(items[2]).toBe('Desktop Viewer'); await click(consoleTypeSelector); // close before re-opening await selectDropdownOption(consoleTypeSelectorId, 'Desktop Viewer'); // no service is exposed atm, informative text should be rendered await browser.wait(until.presenceOf(rdpServiceNotConfiguredElem)); // the next command follows recommendation by documentation execSync( `virtctl expose virtualmachine ${vmWindows.name} --name ${vmWindows.name}-rdp --namespace=${testName} --port 4567 --target-port 3389 --type NodePort`, ); await browser.wait(until.presenceOf(desktopClientTitle)); await browser.wait( waitForStringInElement(desktopClientTitle, 'Desktop Client'), PAGE_LOAD_TIMEOUT_SECS, ); expect(launchRemoteViewerButton.isEnabled()).toBe(false); expect(launchRemoteDesktopButton.isEnabled()).toBe(true); // there should be just the single laucher-pod const hostIP = execSync( `kubectl get -n ${testName} pod $(kubectl get -n ${testName} pods -o name | grep ${vmWindows.name} | cut -d'/' -f 2) -o jsonpath='{.status.hostIP}'`, ) .toString() .trim(); const port = execSync( `kubectl get -n ${testName} service ${vmWindows.name}-rdp -o jsonpath='{.spec.ports[0].nodePort}'`, ) .toString() .trim(); expect(hostIP.length).toBeGreaterThan(0); expect(port.length).toBeGreaterThan(0); await browser.wait( until.textToBePresentInElement(manualConnectionTitle, 'Manual Connection'), ); const titles = rdpManualConnectionTitles; await browser.wait(until.presenceOf(titles)); expect(titles.first().getText()).toBe('RDP Address:'); expect(titles.last().getText()).toBe('RDP Port:'); const values = rdpManualConnectionValues; await browser.wait(until.presenceOf(values)); expect(values.first().getText()).toBe(hostIP); expect(values.last().getText()).toBe(port); // TODO: download the .rdp file and verify content // will require protractor configuration change: // https://stackoverflow.com/questions/21935696/protractor-e2e-test-case-for-downloading-pdf-file/26127745#26127745 }, VM_CREATE_AND_EDIT_TIMEOUT_SECS, ); // TODO: consider move this to Tier2 tests it( 'ID(CNV-1726) connects via L2 network', async () => { /* Pre-requisite: * - L2 network is configured on the cluster/node * - the Windows-VM has guest-agent installed * and so the Windows VM gets IP which is reported back to the VMI object among VMI.status.interfaces[]. * * We mimic this "final" state here. */ await vmWindows.navigateToDetail(); // Waiting for installation & start of the guest-agent and reporting the static IP back // It can take up to several minutes. await browser.wait( waitForStringInElement( vmView.vmDetailIP(vmWindows.namespace, vmWindows.name), VM_WINDOWS_IP, ), VM_CREATE_AND_EDIT_AND_CLOUDINIT_TIMEOUT_SECS, ); await vmWindows.navigateToConsole(); await browser.wait(until.presenceOf(consoleTypeSelector)); await click(consoleTypeSelector); await browser.wait( waitForStringInElement(consoleTypeSelector, 'VNC Console'), PAGE_LOAD_TIMEOUT_SECS, ); const items = await getDropdownOptions(consoleTypeSelectorId); expect(items[0]).toBe('VNC Console'); expect(items[1]).toBe('Serial Console'); expect(items[2]).toBe('Desktop Viewer'); await click(consoleTypeSelector); // close before re-opening await selectDropdownOption(consoleTypeSelectorId, 'Desktop Viewer'); await selectDropdownOptionById(networkSelectorId, 'nic-1-link'); await browser.wait( until.textToBePresentInElement(manualConnectionTitle, 'Manual Connection'), ); const titles = rdpManualConnectionTitles; await browser.wait(until.presenceOf(titles)); expect(titles.first().getText()).toBe('RDP Address:'); expect(titles.last().getText()).toBe('RDP Port:'); const values = rdpManualConnectionValues; await browser.wait(until.presenceOf(values)); expect(values.first().getText()).toBe(VM_WINDOWS_IP); expect(values.last().getText()).toBe('3389'); // TODO: download the .rdp file and verify content // will require protractor configuration change: https://stackoverflow.com/questions/21935696/protractor-e2e-test-case-for-downloading-pdf-file/26127745#26127745 }, VM_CREATE_AND_EDIT_AND_CLOUDINIT_TIMEOUT_SECS, ); }); });
the_stack
import get from 'lodash/get'; import createDebug from 'debug'; import { Context } from '../context'; import { UpdateItemInput, Converter, AttributeMap, Key, } from 'aws-sdk/clients/dynamodb'; import { getRootCollection, assemblePrimaryKeyValue, unwrap, assembleIndexedValue, findMatchingPath, transformTTLValue, } from '../base/util'; import { KeyPath } from '../base/access_pattern'; import { WrappedDocument, DocumentWithId } from '../base/common'; import { InvalidUpdatesException, InvalidUpdateValueException, IndexNotFoundException, } from '../base/exceptions'; import { Collection } from '../base/collection'; import { SecondaryIndexLayout } from '../base/layout'; import debugDynamo from '../debug/debugDynamo'; import { createNameMapper, createValueMapper, NameMapper, ValueMapper, } from '../base/mappers'; import { CompositeCondition } from '../base/conditions'; import { parseCompositeCondition } from '../base/conditions_parser'; import { isEqualKey } from './find'; /** @internal */ const debug = createDebug('dynaglue:operations:updateById'); /** * An update object, where the key paths are specified as keys and the values * as the new field values. * * Keep in mind, that although this is a partial update, you need to specify * all the keys for a composite key in an access pattern - it cannot partially * update composite index values. */ export type SetValuesDocument = { [path: string]: any; }; /** * A key path and value to set on a document as part * of an update operation. Specified as part of [[UpdateChangesDocument]], * this is a tuple in the form: * * `[key_path, new_value]` * * * *key_path* is the property path into the document to update (either * as a dotted string path e.g. `'profile.name'` or a [[KeyPath]]) * * *new_value* is the value to update the property path to (it cannot be * undefined -- if you want to clear the value, see [[DeleteChange]]) */ export type SetChange = [string | KeyPath, any]; /** * A property path to delete on a document as part of a [[UpdateChangesDocument]], * specified either as a dotted string path (e.g. `'profile.name'`) or a [[KeyPath]] */ export type DeleteChange = string | KeyPath; /** * A set of changes to perform in an [[updateById]] or [[updateChildById]] * operation as an object. Each property is optional, but at * least one change must be specified. */ export type UpdateChangesDocument = { /** * The list of key paths to set a value. This is a list * of tuples, in the form [key_path, new_value]. The * key paths can be specified in a string form e.g. `'profile.name'` * or array form e.g. `['profile', 'name']` */ $set?: SetChange[]; /** * The list of key paths to clear the value. Key paths * may be specified in string form e.g. `'profile.name'` or * array form e.g. `['profile', 'name']` */ $delete?: DeleteChange[]; }; /** * The set of updates to apply to a document. This can be * specified one of two ways: * * * an an object of key paths to values to set e.g. `{ 'profile.name': 'new name', 'status': 3 }` * * an operator object of changes to perform (see [[UpdateChangesDocument]]) */ export type Updates = SetValuesDocument | UpdateChangesDocument; const makeKeyPath = (pathOrPathArray: string | KeyPath): KeyPath => typeof pathOrPathArray === 'string' ? pathOrPathArray.split('.') : pathOrPathArray; /** @internal */ export type StrictSetChange = [KeyPath, any]; /** @internal */ export type StrictDeleteChange = KeyPath; /** @internal */ export type StrictChangesDocument = { $set: StrictSetChange[]; $delete: StrictDeleteChange[]; }; /** * @internal * Convert the Updates object to something normalised that * is simpler to process internally */ export const normaliseUpdates = ( updatesToPerform: Updates ): StrictChangesDocument => { if (updatesToPerform.$set || updatesToPerform.$delete) { const changesDocument = updatesToPerform as UpdateChangesDocument; return { $set: changesDocument.$set?.map((setUpdate) => [ makeKeyPath(setUpdate[0]), setUpdate[1], ]) ?? [], $delete: changesDocument.$delete?.map(makeKeyPath) ?? [], }; } else { const updatesDocument = updatesToPerform as Updates; return { $set: Object.entries(updatesDocument).map(([key, value]) => [ makeKeyPath(key), value, ]), $delete: [], }; } }; /** * @internal */ export const extractUpdateKeyPaths = ( changes: StrictChangesDocument ): KeyPath[] => [...changes.$set.map(([path]) => path), ...changes.$delete]; /** * @internal */ export const getValueForUpdatePath = ( matchingUpdatePath: KeyPath, keyPath: KeyPath, changes: StrictChangesDocument ): any => { // Work out if this was a $set update (in which case we get the index) or // a delete path (which we perform by deduction) const setPathIndex = changes.$set.findIndex(([setPath]) => isEqualKey(setPath, matchingUpdatePath) ); let value = setPathIndex >= 0 ? changes.$set[setPathIndex][1] : undefined; if (setPathIndex >= 0 && keyPath.length !== matchingUpdatePath.length) { const difference = keyPath.slice(matchingUpdatePath.length); value = get(value, difference); } return value; }; /** * @internal */ export const createUpdateActionForKey = ( collectionName: string, keyType: 'partition' | 'sort', keyPaths: KeyPath[], indexLayout: SecondaryIndexLayout, changes: StrictChangesDocument, separator?: string ): | { attributeName: string; value?: string; valueErasure: boolean } | undefined => { const updateKeyPaths = extractUpdateKeyPaths(changes); const matchingUpdatePaths = keyPaths.map((partitionKey) => findMatchingPath(updateKeyPaths, partitionKey) ); const attributeName = keyType === 'sort' ? (indexLayout.sortKey as string) : indexLayout.partitionKey; debug( 'createUpdateActionForKey: collection=%s keyType=%s keyPaths=%o attributeName=%s', collectionName, keyType, keyPaths, attributeName ); if ( matchingUpdatePaths.every((updatePath) => typeof updatePath === 'undefined') ) { debug( 'createUpdateActionForKey: no updates to %s key in collection %s', keyType, collectionName ); return undefined; } debug( 'createUpdateActionForKey: key to be updated matchingUpdatePaths=%o', matchingUpdatePaths ); const updateValues = keyPaths.map((keyPath, index) => { const matchingUpdatePath = matchingUpdatePaths[index]; if (!matchingUpdatePath) { return undefined; } return getValueForUpdatePath(matchingUpdatePath, keyPath, changes); }); return { attributeName, value: assembleIndexedValue( keyType, collectionName, updateValues, separator ), valueErasure: updateValues.every((value) => typeof value === 'undefined'), }; }; /** * @internal * * Create the update action for a TTL key path */ export const createUpdateActionForTTLKey = ( attributeName: string, keyPath: KeyPath, updates: StrictChangesDocument ): { attributeName: string; value?: number } | undefined => { const updateKeyPaths = extractUpdateKeyPaths(updates); const matchingUpdatePath = findMatchingPath(updateKeyPaths, keyPath); if (matchingUpdatePath) { const value = getValueForUpdatePath(matchingUpdatePath, keyPath, updates); return { attributeName, value: value ? transformTTLValue(value) : undefined, }; } return undefined; }; /** * @internal */ export const findCollectionIndex = ( collection: Collection, indexName: string ): SecondaryIndexLayout => { const layout = collection.layout.findKeys?.find( (fk) => fk.indexName === indexName ); if (!layout) { throw new IndexNotFoundException(indexName); } return layout; }; /** * @internal */ export type Action = { action: string; expressionAttributeValue: [string, any]; expressionAttributeNames: [string, string][]; }; /** * @internal * * Given the set of updates, create the SET and DELETE * actions for the access patterns that also have to be * changed. */ export const mapAccessPatterns = ( collection: Collection, { nameMapper, valueMapper, }: { nameMapper: NameMapper; valueMapper: ValueMapper }, changes: StrictChangesDocument ): { setActions: string[]; deleteActions: string[]; } => { const expressionSetActions: string[] = []; const expressionDeleteActions: string[] = []; const { accessPatterns = [], ttlKeyPath } = collection; for (const { indexName, partitionKeys, sortKeys } of accessPatterns) { let partitionKeyUpdateSet: boolean | undefined = undefined; let sortKeyUpdated = false; const layout = findCollectionIndex(collection, indexName); if (partitionKeys.length > 0) { const update = createUpdateActionForKey( collection.name, 'partition', partitionKeys, layout, changes, collection.layout.indexKeySeparator ); if (update) { partitionKeyUpdateSet = !update.valueErasure; debug( 'mapAccessPatterns: adding set/delete action for partition key in collection %s: %o', collection.name, update ); const nameMapping = nameMapper.map(update.attributeName); const valueMapping = valueMapper.map(update.value); expressionSetActions.push(`${nameMapping} = ${valueMapping}`); } } if (sortKeys && sortKeys.length > 0) { const update = createUpdateActionForKey( collection.name, 'sort', sortKeys, layout, changes, collection.layout.indexKeySeparator ); if (update) { debug( 'mapAccessPatterns: adding set/delete action for sort key in collection %s: %o', collection.name, update ); sortKeyUpdated = true; if (typeof update.value !== 'undefined') { const nameMapping = nameMapper.map(update.attributeName); const valueMapping = valueMapper.map(update.value); expressionSetActions.push(`${nameMapping} = ${valueMapping}`); } else { const nameMapping = nameMapper.map(update.attributeName); expressionDeleteActions.push(nameMapping); } } } else if (typeof partitionKeyUpdateSet !== 'undefined' && layout.sortKey) { // When only primary key has indexed paths (i.e. partitionKeys.length > 0, // sortKeys.length === 0, and we applied an update for the partitionKey) // make an empty update to the sort key to in-case it wasn't populated const nameMapping = nameMapper.map(layout.sortKey); if (partitionKeyUpdateSet) { const valueMapping = valueMapper.map( assembleIndexedValue( 'sort', collection.name, [], collection.layout.indexKeySeparator ) ); expressionSetActions.push(`${nameMapping} = ${valueMapping}`); } else { expressionDeleteActions.push(nameMapping); } } // In the case the sort key is updated but there is no indexed partition key // paths, make sure the partition key gets a value written if (sortKeyUpdated && (!partitionKeys || partitionKeys.length === 0)) { const nameMapping = nameMapper.map(layout.partitionKey); const valueMapping = valueMapper.map( assembleIndexedValue( 'partition', collection.name, [], collection.layout.indexKeySeparator ) ); expressionSetActions.push(`${nameMapping} = ${valueMapping}`); } } if (ttlKeyPath) { const updateAction = createUpdateActionForTTLKey( // eslint-disable-next-line @typescript-eslint/no-non-null-assertion collection.layout.ttlAttribute!, // we've already asserted this in context creation ttlKeyPath, changes ); if (updateAction) { const nameMapping = nameMapper.map(updateAction.attributeName); if (updateAction.value) { const valueMapping = valueMapper.map(updateAction.value); expressionSetActions.push(`${nameMapping} = ${valueMapping}`); } else { expressionDeleteActions.push(nameMapping); } } } return { setActions: expressionSetActions, deleteActions: expressionDeleteActions, }; }; /** * @internal * * Performs an update operation for the given collection and key * value. Shares most of the code between updateById and updateChildById * */ export async function updateInternal<DocumentType extends DocumentWithId>( ctx: Context, collection: Collection, key: Key, updatesToPerform: Updates, options: { condition?: CompositeCondition } ): Promise<DocumentType> { const changes = normaliseUpdates(updatesToPerform); if (changes.$set.length === 0 && changes.$delete.length === 0) { throw new InvalidUpdatesException( 'There must be at least one update path in the updates object' ); } const nameMapper = createNameMapper(); const valueMapper = createValueMapper(); let expressionSetActions: string[] = []; let expressionDeleteActions: string[] = []; for (const [path, newValue] of changes.$set.values()) { if (typeof newValue === 'undefined') { throw new InvalidUpdateValueException( path.join('.'), 'value must not be undefined' ); } const valueName = valueMapper.map(newValue); const expressionAttributeNameParts = [ nameMapper.map('value', '#value'), ...path.map((part) => nameMapper.map(part)), ]; expressionSetActions.push( `${expressionAttributeNameParts.join('.')} = ${valueName}` ); } for (const path of changes.$delete) { const expressionAttributeNameParts = [ nameMapper.map('value', '#value'), ...path.map((part) => nameMapper.map(part)), ]; expressionDeleteActions.push(`${expressionAttributeNameParts.join('.')}`); } const { setActions: additionalSetActions, deleteActions: additionalDeleteActions, } = mapAccessPatterns(collection, { nameMapper, valueMapper }, changes); expressionSetActions = [...expressionSetActions, ...additionalSetActions]; expressionDeleteActions = [ ...expressionDeleteActions, ...additionalDeleteActions, ]; let conditionExpression; if (options.condition) { conditionExpression = parseCompositeCondition(options.condition, { nameMapper, valueMapper, parsePath: [], }); } const expressionAttributeNames = nameMapper.get(); const expressionAttributeValues = valueMapper.get(); const updateExpression = (expressionSetActions.length ? ` SET ${expressionSetActions.join(', ')}` : '') + (expressionDeleteActions.length ? ` REMOVE ${expressionDeleteActions.join(', ')}` : ''); const updateItem: UpdateItemInput = { TableName: collection.layout.tableName, Key: key, ReturnValues: 'ALL_NEW', ExpressionAttributeNames: expressionAttributeNames, ExpressionAttributeValues: expressionAttributeValues, UpdateExpression: updateExpression.trim(), ConditionExpression: conditionExpression, }; debugDynamo('UpdateItem', updateItem); const result = await ctx.ddb.updateItem(updateItem).promise(); const unmarshalledAttributes = Converter.unmarshall( result.Attributes as AttributeMap ); const updatedDocument = unwrap( unmarshalledAttributes as WrappedDocument<DocumentType> ); return updatedDocument; } /** * Update a document using its `_id`. * * This operation allows you to do a partial update of a collection document i.e. without * specifying all the values (it uses DynamoDB`s `UpdateItem` operation). * * At this time, the `updates` value just updates specified key paths on the target document. * * If some of the update key paths are indexed values, the indexes will also be updated. Because * of this, you must specify all the key values in an access pattern to ensure indexes are * updated consistently. * * @param ctx the context * @param collectionName the collection to update * @param objectId the `_id` value of the object to update * @param updates the set of updates to apply. * @returns the updated object value in its entirety. * @throws {CollectionNotFoundException} collection not found * @throws {InvalidUpdatesException} thrown when the updates object is invalid or incomplete * @throws {InvalidUpdateValueException} thrown when one of the update values is an invalid type */ export async function updateById<DocumentType extends DocumentWithId>( ctx: Context, collectionName: string, objectId: string, updates: Updates, options: { condition?: CompositeCondition } = {} ): Promise<DocumentType> { const collection = getRootCollection(ctx, collectionName); const key = { [collection.layout.primaryKey.partitionKey]: { S: assemblePrimaryKeyValue( collectionName, objectId, collection.layout.indexKeySeparator ), }, [collection.layout.primaryKey.sortKey]: { S: assemblePrimaryKeyValue( collectionName, objectId, collection.layout.indexKeySeparator ), }, }; return updateInternal(ctx, collection, key, updates, options); }
the_stack
import type { Parser as FormulaParser } from "hot-formula-parser"; import * as Formula from "./formula"; import * as Matrix from "./matrix"; import * as Point from "./point"; import * as PointMap from "./point-map"; import * as PointRange from "./point-range"; import * as Types from "./types"; import * as util from "./util"; const EXAMPLE_INPUT_VALUE = "EXAMPLE_INPUT_VALUE"; const EXAMPLE_DATA_ROWS_COUNT = 2; const EXAMPLE_DATA_COLUMNS_COUNT = 2; const EXAMPLE_DATA = Matrix.createEmpty<Types.CellBase>( EXAMPLE_DATA_ROWS_COUNT, EXAMPLE_DATA_COLUMNS_COUNT ); const EXAMPLE_ROW_LABELS = ["Foo", "Bar", "Baz"]; const EXAMPLE_COLUMN_LABELS = ["Foo", "Bar", "Baz"]; const EXAMPLE_EXISTING_POINT = Point.ORIGIN; const EXAMPLE_NON_EXISTING_POINT: Point.Point = { row: EXAMPLE_DATA_ROWS_COUNT, column: EXAMPLE_DATA_COLUMNS_COUNT, }; const EXAMPLE_CELL_DIMENSIONS: Types.Dimensions = { height: 20, width: 200, top: 0, left: 0, }; const EXAMPLE_STATE: Types.StoreState = { active: null, mode: "view", rowDimensions: { 0: { height: EXAMPLE_CELL_DIMENSIONS.height, top: EXAMPLE_CELL_DIMENSIONS.top, }, 1: { height: EXAMPLE_CELL_DIMENSIONS.height, top: EXAMPLE_CELL_DIMENSIONS.top + EXAMPLE_CELL_DIMENSIONS.height, }, }, columnDimensions: { 0: { width: EXAMPLE_CELL_DIMENSIONS.width, left: EXAMPLE_CELL_DIMENSIONS.left, }, 1: { width: EXAMPLE_CELL_DIMENSIONS.width, left: EXAMPLE_CELL_DIMENSIONS.left + EXAMPLE_CELL_DIMENSIONS.width, }, }, lastChanged: null, hasPasted: false, cut: false, dragging: false, data: EXAMPLE_DATA, selected: null, copied: PointMap.from([]), bindings: PointMap.from([]), lastCommit: null, }; const EXAMPLE_STRING = "EXAMPLE_STRING"; const EXAMPLE_CELL: Types.CellBase = { value: "EXAMPLE_CELL_VALUE", }; const EXAMPLE_FORMULA_CELL: Types.CellBase = { value: "=TRUE()", }; const MOCK_PARSE = jest.fn(); const MOCK_FORMULA_PARSER = { parse: MOCK_PARSE, } as unknown as FormulaParser; const EXAMPLE_FORMULA_RESULT = true; const EXAMPLE_FORMULA_ERROR = "EXAMPLE_ERROR"; const EXAMPLE_EMPTY_COPIED = PointMap.from<Types.CellBase>([]); const EXAMPLE_COPIED = PointMap.from([[Point.ORIGIN, EXAMPLE_CELL]]); beforeEach(() => { jest.clearAllMocks(); jest.restoreAllMocks(); }); describe("moveCursorToEnd()", () => { test("moves cursor to the end", () => { const el = document.createElement("input"); el.value = EXAMPLE_INPUT_VALUE; util.moveCursorToEnd(el); expect(el.selectionStart).toBe(EXAMPLE_INPUT_VALUE.length); expect(el.selectionEnd).toBe(EXAMPLE_INPUT_VALUE.length); }); }); describe("range()", () => { test("basic use of range", () => { const end = 10; const start = 1; const step = 2; const res = util.range(end, start, step); expect(res).toEqual([1, 3, 5, 7, 9]); }); test("range with negative numbers", () => { const end = 10; const start = -10; const step = 2; const res = util.range(end, start, step); expect(res).toEqual([-10, -8, -6, -4, -2, 0, 2, 4, 6, 8]); }); test("range with larger start to return decreasing series", () => { const end = 1; const start = 5; const res = util.range(end, start); expect(res).toEqual([5, 4, 3, 2]); }); }); describe("calculateSpreadsheetSize()", () => { test("Returns the size of data if row labels and column labels are not defined", () => { expect(util.calculateSpreadsheetSize(EXAMPLE_DATA)).toStrictEqual({ rows: EXAMPLE_DATA_ROWS_COUNT, columns: EXAMPLE_DATA_COLUMNS_COUNT, }); }); test("Returns the size of row labels if row labels is longer than data rows", () => { expect( util.calculateSpreadsheetSize(EXAMPLE_DATA, EXAMPLE_ROW_LABELS) ).toStrictEqual({ rows: EXAMPLE_ROW_LABELS.length, columns: EXAMPLE_DATA_COLUMNS_COUNT, }); }); test("Returns the size of column labels if column labels is longer than data columns", () => { expect( util.calculateSpreadsheetSize( EXAMPLE_DATA, undefined, EXAMPLE_COLUMN_LABELS ) ).toStrictEqual({ rows: EXAMPLE_DATA_ROWS_COUNT, columns: EXAMPLE_COLUMN_LABELS.length, }); }); }); describe("getCellDimensions()", () => { const cases = [ [ "returns existing cell dimensions", EXAMPLE_EXISTING_POINT, EXAMPLE_CELL_DIMENSIONS, ], [ "returns undefined for non existing cell", EXAMPLE_NON_EXISTING_POINT, undefined, ], ] as const; test.each(cases)("%s", (name, point, expected) => { expect( util.getCellDimensions( point, EXAMPLE_STATE.rowDimensions, EXAMPLE_STATE.columnDimensions ) ).toEqual(expected); }); }); describe("getRangeDimensions()", () => { const cases = [ [ "returns undefined for non existing start", { start: EXAMPLE_NON_EXISTING_POINT, end: EXAMPLE_EXISTING_POINT }, undefined, ], [ "returns undefined for non existing end", { start: EXAMPLE_EXISTING_POINT, end: EXAMPLE_NON_EXISTING_POINT }, undefined, ], [ "returns undefined for non existing start and end", { start: EXAMPLE_NON_EXISTING_POINT, end: EXAMPLE_NON_EXISTING_POINT }, undefined, ], [ "returns dimensions of range of one cell", { start: EXAMPLE_EXISTING_POINT, end: EXAMPLE_EXISTING_POINT }, EXAMPLE_CELL_DIMENSIONS, ], [ "returns dimensions of range of two horizontal cells", { start: Point.ORIGIN, end: { row: 0, column: 1 } }, { ...EXAMPLE_CELL_DIMENSIONS, width: EXAMPLE_CELL_DIMENSIONS.width * 2, }, ], [ "returns dimensions of range of two vertical cells", { start: Point.ORIGIN, end: { row: 1, column: 0 } }, { ...EXAMPLE_CELL_DIMENSIONS, height: EXAMPLE_CELL_DIMENSIONS.height * 2, }, ], [ "returns dimensions of range of a square of cells", { start: Point.ORIGIN, end: { row: 1, column: 1 } }, { ...EXAMPLE_CELL_DIMENSIONS, width: EXAMPLE_CELL_DIMENSIONS.width * 2, height: EXAMPLE_CELL_DIMENSIONS.height * 2, }, ], ] as const; test.each(cases)("%s", (name, range, expected) => { expect( util.getRangeDimensions( EXAMPLE_STATE.rowDimensions, EXAMPLE_STATE.columnDimensions, range ) ).toEqual(expected); }); }); describe("isActive()", () => { const cases = [ ["returns false if active is null", null, EXAMPLE_EXISTING_POINT, false], [ "returns false if given point is not null", { row: 1, column: 1 }, EXAMPLE_EXISTING_POINT, false, ], [ "returns true if given point is active", EXAMPLE_EXISTING_POINT, EXAMPLE_EXISTING_POINT, true, ], ] as const; test.each(cases)("%s", (name, active, point, expected) => { expect(util.isActive(active, point)).toBe(expected); }); }); describe("writeTextToClipboard()", () => { const event = { clipboardData: { setData: jest.fn(), }, }; util.writeTextToClipboard(event as unknown as ClipboardEvent, EXAMPLE_STRING); expect(event.clipboardData.setData).toBeCalledTimes(1); expect(event.clipboardData.setData).toBeCalledWith( util.PLAIN_TEXT_MIME, EXAMPLE_STRING ); }); describe("getComputedValue()", () => { test("Returns null if cell is not defined", () => { expect( util.getComputedValue({ cell: undefined, formulaParser: MOCK_FORMULA_PARSER, }) ).toBe(null); expect(MOCK_FORMULA_PARSER.parse).toBeCalledTimes(0); }); test("Returns value if not formula", () => { expect( util.getComputedValue({ cell: EXAMPLE_CELL, formulaParser: MOCK_FORMULA_PARSER, }) ).toBe(EXAMPLE_CELL.value); expect(MOCK_FORMULA_PARSER.parse).toBeCalledTimes(0); }); test("Returns evaluated formula value", () => { MOCK_PARSE.mockImplementationOnce(() => ({ result: EXAMPLE_FORMULA_RESULT, error: null, })); expect( util.getComputedValue({ cell: EXAMPLE_FORMULA_CELL, formulaParser: MOCK_FORMULA_PARSER, }) ).toBe(EXAMPLE_FORMULA_RESULT); }); }); describe("getFormulaComputedValue()", () => { const cases = [ [ "Returns parsed formula result", EXAMPLE_FORMULA_RESULT, { result: EXAMPLE_FORMULA_RESULT, error: null }, ], [ "Returns parsed formula error", EXAMPLE_FORMULA_ERROR, { result: null, error: EXAMPLE_FORMULA_ERROR }, ], ] as const; test.each(cases)("%s", (name, expected, mockParseReturn) => { MOCK_PARSE.mockImplementationOnce(() => mockParseReturn); expect( util.getFormulaComputedValue({ cell: EXAMPLE_FORMULA_CELL, formulaParser: MOCK_FORMULA_PARSER, }) ).toBe(expected); expect(MOCK_FORMULA_PARSER.parse).toBeCalledTimes(1); expect(MOCK_FORMULA_PARSER.parse).toBeCalledWith( Formula.extractFormula(EXAMPLE_FORMULA_CELL.value) ); }); }); describe("isFormulaCell()", () => { const cases = [ ["Returns true for formula cell", EXAMPLE_FORMULA_CELL, true], ["Returns true for formula cell", EXAMPLE_CELL, false], ] as const; test.each(cases)("%s", (name, cell, expected) => { expect(util.isFormulaCell(cell)).toBe(expected); }); }); describe("getMatrixRange()", () => { test("Returns the point range of given matrix", () => { expect(util.getMatrixRange(EXAMPLE_DATA)).toEqual( PointRange.create(Point.ORIGIN, { row: EXAMPLE_DATA_COLUMNS_COUNT - 1, column: EXAMPLE_DATA_ROWS_COUNT - 1, }) ); }); }); describe("getCSV()", () => { test("Returns given data as CSV", () => { expect(util.getCSV(EXAMPLE_DATA)).toBe( Matrix.join( Matrix.createEmpty(EXAMPLE_DATA_ROWS_COUNT, EXAMPLE_DATA_COLUMNS_COUNT) ) ); }); }); describe("getSelectedCSV()", () => { test("Returns empty for no selected range", () => { expect(util.getSelectedCSV(null, EXAMPLE_DATA)).toBe(""); }); test("Returns CSV for selected range", () => { expect( util.getSelectedCSV( { start: Point.ORIGIN, end: { row: 1, column: 1 } }, EXAMPLE_DATA ) ).toEqual(Matrix.join(Matrix.createEmpty(2, 2))); }); }); describe("getOffsetRect()", () => { test("Returns object with the offsets of the given element", () => { const MOCK_ELEMENT = { offsetWidth: 42, offsetHeight: 42, offsetLeft: 42, offsetTop: 42, } as unknown as HTMLElement; expect(util.getOffsetRect(MOCK_ELEMENT)).toEqual({ width: MOCK_ELEMENT.offsetWidth, height: MOCK_ELEMENT.offsetHeight, left: MOCK_ELEMENT.offsetLeft, top: MOCK_ELEMENT.offsetTop, }); }); }); describe("readTextFromClipboard()", () => { test("Returns empty string if no text is defined", () => { const EXAMPLE_CLIPBOARD_EVENT = {} as ClipboardEvent; expect(util.readTextFromClipboard(EXAMPLE_CLIPBOARD_EVENT)).toEqual(""); }); test("Returns string from event", () => { const EXAMPLE_CLIPBOARD_EVENT = { clipboardData: { getData: jest.fn(() => EXAMPLE_STRING), }, } as unknown as ClipboardEvent; expect(util.readTextFromClipboard(EXAMPLE_CLIPBOARD_EVENT)).toEqual( EXAMPLE_STRING ); expect(EXAMPLE_CLIPBOARD_EVENT.clipboardData?.getData).toBeCalledTimes(1); expect(EXAMPLE_CLIPBOARD_EVENT.clipboardData?.getData).toBeCalledWith( util.PLAIN_TEXT_MIME ); }); test("Returns string from window", () => { const EXAMPLE_CLIPBOARD_EVENT = {} as ClipboardEvent; const MOCK_CLIPBOARD_DATA = { getData: jest.fn(() => EXAMPLE_STRING), }; // Define for the test as it is not a native JS-DOM property // @ts-ignore window.clipboardData = MOCK_CLIPBOARD_DATA; expect(util.readTextFromClipboard(EXAMPLE_CLIPBOARD_EVENT)).toBe( EXAMPLE_STRING ); // @ts-ignore expect(MOCK_CLIPBOARD_DATA.getData).toBeCalledTimes(1); expect(MOCK_CLIPBOARD_DATA.getData).toBeCalledWith("Text"); // Undefine as it is not a native JS-DOM property // @ts-ignore delete window.clipoardData; }); }); describe("normalizeSelected()", () => { test("Normalizes given selected range to given data", () => { const EXAMPLE_RANGE = PointRange.create(Point.ORIGIN, { row: EXAMPLE_DATA_ROWS_COUNT, column: EXAMPLE_DATA_COLUMNS_COUNT, }); expect(util.normalizeSelected(EXAMPLE_RANGE, EXAMPLE_DATA)).toEqual( PointRange.create(Point.ORIGIN, Matrix.maxPoint(EXAMPLE_DATA)) ); }); }); describe("getCopiedRange()", () => { const cases = [ [ "Returns range of copied cells", EXAMPLE_COPIED, false, PointRange.create(Point.ORIGIN, Point.ORIGIN), ], ["Returns null if none is copied", EXAMPLE_EMPTY_COPIED, false, null], ["Returns null if hasPasted is true", EXAMPLE_COPIED, true, null], ] as const; test.each(cases)("%s", (name, copied, hasPasted, expected) => { expect(util.getCopiedRange(copied, hasPasted)).toEqual(expected); }); }); describe("transformCoordToPoint()", () => { test("transforms coord to point", () => { expect( util.transformCoordToPoint({ row: { index: Point.ORIGIN.row }, column: { index: Point.ORIGIN.column }, }) ).toEqual(Point.ORIGIN); }); }); describe("getCellValue()", () => { expect( util.getCellValue(MOCK_FORMULA_PARSER, EXAMPLE_DATA, Point.ORIGIN) ).toEqual(null); }); describe("getCellRangeValue()", () => { expect( util.getCellRangeValue( MOCK_FORMULA_PARSER, EXAMPLE_DATA, Point.ORIGIN, Point.ORIGIN ) ).toEqual([null]); }); describe("shouldHandleClipboardEvent()", () => { const matchesMock = jest.fn(); const mockElement = { matches: matchesMock, } as unknown as Element; const cases = [ ["return false if root is null", null, false, "view" as Types.Mode, false], [ "return false if mode is not view", mockElement, false, "edit" as Types.Mode, false, ], [ "return true if root is focused within and mode is view", mockElement, true, "view" as Types.Mode, true, ], ] as const; beforeEach(() => { // Prevent accumulation return values matchesMock.mockReset(); }); test.each(cases)("%s", (name, root, focusedWithin, mode, expected) => { // Bound to implemnetation of isFocusedWithin() matchesMock.mockReturnValueOnce(focusedWithin); expect(util.shouldHandleClipboardEvent(root, mode)).toBe(expected); }); }); describe("isFocusedWithin()", () => { const matchesMock = jest.fn(); const mockElement = { matches: matchesMock, } as unknown as Element; const cases = [ ["matches selector", mockElement, true, true], ["does not match selector", mockElement, false, false], ] as const; test.each(cases)("%s", (name, element, matches, expected) => { matchesMock.mockReturnValueOnce(matches); expect(util.isFocusedWithin(element)).toBe(expected); expect(matchesMock).toBeCalledTimes(1); expect(matchesMock).toBeCalledWith(util.FOCUS_WITHIN_SELECTOR); }); });
the_stack
import { Version } from '@microsoft/sp-core-library'; import { BaseClientSideWebPart, IPropertyPaneConfiguration, IPropertyPaneDropdownOption, PropertyPaneDropdown, PropertyPaneToggle, PropertyPaneSlider } from '@microsoft/sp-webpart-base'; import { SPComponentLoader } from '@microsoft/sp-loader'; import { SPHttpClient } from '@microsoft/sp-http'; import { Environment, EnvironmentType } from '@microsoft/sp-core-library'; import { PropertyFieldColorPickerMini } from 'sp-client-custom-fields/lib/PropertyFieldColorPickerMini'; import * as jQuery from 'jquery'; import * as _ from "lodash"; import styles from './EmployeeSpotlight.module.scss'; import * as strings from 'employeeSpotlightStrings'; import { IEmployeeSpotlightWebPartProps } from './IEmployeeSpotlightWebPartProps'; import { SliderHelper } from './Helper'; /** * An interface to hold the key and value. */ export interface ResponceDetails { title: string; id: string; } /** * An interface to hold the ResponceDetails collection. */ export interface ResponceCollection { value: ResponceDetails[]; } /** * An interface to hold the SpotlightDetails. */ export interface SpotlightDetails { userDisplayName: string; userEmail: string; userProfilePic: string; description: string; designation?: string; } /** * A class that contains spotlight webpart operations and corresponding properties to hold the data. */ export default class EmployeeSpotlightWebPart extends BaseClientSideWebPart<IEmployeeSpotlightWebPartProps> { private spotlightListFieldOptions: IPropertyPaneDropdownOption[] = []; private spotlightListOptions: IPropertyPaneDropdownOption[] = []; private siteOptions: IPropertyPaneDropdownOption[] = []; private defaultProfileImageUrl: string = "/_layouts/15/userphoto.aspx?size=L"; private helper: SliderHelper = new SliderHelper(); private sliderControl: any = null; /** * Constructor of SpotlightWebpart class. */ public constructor() { super(); SPComponentLoader.loadScript('https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js', { globalExportsName: 'jQuery' }); // Next button functionality jQuery(document).on("click", "." + styles.next, (event) => { event.preventDefault(); //prevent default action of <a> this.helper.moveSlides(1); }); // Previous button functionality jQuery(document).on("click", "." + styles.prev, (event) => { event.preventDefault(); //prevent default action of <a> this.helper.moveSlides(-1); }); // start and stop slider on hover jQuery(document).ready(() => { jQuery(document).on('mouseenter', '.' + styles.containers, () => { if (this.properties.enabledSpotlightAutoPlay) clearInterval(this.sliderControl); }).on('mouseleave', '.' + styles.containers, () => { var carouselSpeed: number = this.properties.spotlightSliderSpeed * 1000; if (carouselSpeed && this.properties.enabledSpotlightAutoPlay) this.sliderControl = setInterval(this.helper.startAutoPlay, carouselSpeed); }); }); } /** * A starting point for application. */ public render(): void { this.domElement.innerHTML = `<div id="spListContainer" />`; this._renderSpotlightTemplateAsync(); this._renderSpotlightDataAsync(); } /** * Builds the spotlight details collection with necessary details. */ private _renderSpotlightTemplateAsync(): void { if (Environment.type == EnvironmentType.SharePoint || Environment.type == EnvironmentType.ClassicSharePoint) { this._getSiteCollectionRootWeb().then((response) => { this.properties.spotlightSiteCollectionURL = response['Url']; }); if (this.properties.spotlightSiteURL && this.properties.spotlightListName && this.properties.spotlightEmployeeEmailColumn && this.properties.spotlightDescriptionColumn) { let spotlightDataCollection: SpotlightDetails[] = []; this._getSpotlightListData(this.properties.spotlightSiteURL, this.properties.spotlightListName, this.properties.spotlightEmployeeExpirationDateColumn, this.properties.spotlightEmployeeEmailColumn, this.properties.spotlightDescriptionColumn) .then((listDataResponse) => { var spotlightListData = listDataResponse.value; if (spotlightListData) { debugger; for (var key in listDataResponse.value) { var email = listDataResponse.value[key][this.properties.spotlightEmployeeEmailColumn]["EMail"]; var id = listDataResponse.value[key]["ID"]; this._getUserImage(email) .then((response) => { spotlightListData.forEach((item: ResponceDetails) => { let userSpotlightDetails: SpotlightDetails = { userDisplayName: "", userEmail: "", userProfilePic: "", description: "" }; if (item[this.properties.spotlightEmployeeEmailColumn]["EMail"] == response["Email"]) { var userName = item[this.properties.spotlightEmployeeEmailColumn]; var description = item[this.properties.spotlightDescriptionColumn]; var userDescription = ""; try { userDescription = $(description).text(); } catch (err) { userDescription = description; } if (userDescription.length > 140) { var displayFormUrl = this.properties.spotlightSiteURL + '/Lists/' + this.properties.spotlightListName + '/DispForm.aspx?ID=' + id; userDescription = userDescription.substring(0, 140) + `&nbsp; <a href="${displayFormUrl}">ReadMore...</a>`; } var displayName = response["DisplayName"]; var designationProperty = _.filter(response["UserProfileProperties"], { Key: "SPS-JobTitle" })[0]; var designation = designationProperty["Value"] ? designationProperty["Value"] : ""; // uses default image if user image not exist var profilePicture = response["PictureUrl"] != null && response["PictureUrl"] != undefined ? (<string>response["PictureUrl"]).replace("MThumb", "LThumb") : this.defaultProfileImageUrl; // var profilePicture = response["PictureUrl"] != null && response["PictureUrl"] != undefined ? (<string>response["PictureUrl"]) : this.defaultProfileImageUrl; profilePicture = '/_layouts/15/userphoto.aspx?accountname=' + displayName + '&size=M&url=' + profilePicture.split("?")[0]; userSpotlightDetails = { userDisplayName: response["DisplayName"], userEmail: response["Email"], userProfilePic: profilePicture, description: userDescription, designation: designation }; spotlightDataCollection.push(userSpotlightDetails); } }); this._addSpotlightTemplateContent(spotlightDataCollection); if (this.sliderControl == null && this.properties && this.properties.enabledSpotlightAutoPlay) { setTimeout(this.helper.moveSlides(), 2000); this.sliderControl = setInterval(this.helper.startAutoPlay, this.properties.spotlightSliderSpeed * 1000); } }); } } }); } } } /** * Renders the webpart html with the given spotlight details collection. * @param spotlightDetails - a collection of spotlight details. */ private _addSpotlightTemplateContent(spotlightDetails: SpotlightDetails[]): void { this.domElement.innerHTML = ''; var innerContent: string = ''; for (let i: number = 0; i < spotlightDetails.length; i++) { innerContent += ` <div class="${styles.mySlides}"> <div style="width:100%;"> <div style="width:36%;float:left;padding:10% 0;"> <img style="border-radius:50%;width: 90px;" src="${spotlightDetails[i].userProfilePic}" /> </div> <div style="width:60%;float:left;text-align:left;"> <h5 style="margin-bottom:0; text-transform: uppercase;text-align:center;">${spotlightDetails[i].userDisplayName}</h5> <h6 style="text-align:center;">${spotlightDetails[i].designation}</h6> <p>${spotlightDetails[i].description}</p> </div> </div> </div>`; } this.domElement.innerHTML += `<div class="${styles.containers}" id="slideshow" style="background-color: ${this.properties.spotlightBGColor}; cursor:pointer; width: 100%!important; padding: 5px;border-radius: 15px;box-shadow: rgba(0,0,0,0.25) 0 0 20px 0;text-align:center;color:${this.properties.spotlightFontColor};"> ` + innerContent + ` <a class="${styles.prev}">&#10094;</a> <a class="${styles.next}">&#10095;</a> </div>`; } /** * A generic utility function to execute the rest api call and return the corresponding result as a promise. * @param url - The string containing api url. */ private _callAPI(url: string): Promise<ResponceCollection> { return this.context.spHttpClient.get(url, SPHttpClient.configurations.v1).then((response) => { return response.json(); }); } /** * Returns a promise that returns user image url and name. * @param email - The string containing user email id. */ private _getUserImage(email: string): Promise<ResponceCollection> { return this._callAPI(this.properties.spotlightSiteCollectionURL + "/_api/SP.UserProfiles.PeopleManager/GetPropertiesFor(accountName=@v)?@v='i:0%23.f|membership|" + email + "'"); } /** * Returns a promise that returns sitecollection rootweb url. */ private _getSiteCollectionRootWeb(): Promise<ResponceCollection> { return this._callAPI(this.context.pageContext.web.absoluteUrl + `/_api/Site/RootWeb?$select=Title,Url`); } /** * Returns a promise that returns all the subsite names from the given sitecollection. * @param spotlightSiteCollectionURL - The string containing user email id. */ private _getAllSubsites(spotlightSiteCollectionURL: string): Promise<ResponceCollection> { return this._callAPI(spotlightSiteCollectionURL + `/_api/web/webs?$select=Title,Url`); } /** * Returns a promise that returns all the list names in corresponding site. * @param siteUrl - The string containing site url. */ private _getAllLists(siteUrl: string): Promise<ResponceCollection> { if (siteUrl != "" && siteUrl != undefined) { return this._callAPI(siteUrl + `/_api/web/lists?$orderby=Id desc&$filter=Hidden eq false and BaseTemplate eq 100`); } } /** * Returns a promise that returns spotlight list field names. * @param siteUrl - The string containing site url. * @param spotlightListName - The string containing spotlight list name. */ private _getSpotlightListFields(siteUrl: string, spotlightListName: string): Promise<ResponceCollection> { if (siteUrl != "" && spotlightListName != "" && siteUrl != undefined && spotlightListName != undefined) { return this._callAPI(siteUrl + `/_api/web/lists/GetByTitle('${spotlightListName}')/Fields?$orderby=Id desc&$filter=Hidden eq false and ReadOnlyField eq false`); } } /** * Loads all the subsites in the current sitecollection and initiates the corresponding dropdown values loading. */ private _renderSpotlightDataAsync(): void { this._getSiteCollectionRootWeb() .then((response) => { this.properties.spotlightSiteCollectionURL = response['Url']; this._getAllSubsites(response['Url']) .then((sitesResponse) => { this.siteOptions = this._getDropDownCollection(sitesResponse, 'Url', 'Title'); this.context.propertyPane.refresh(); if (this.properties.spotlightSiteURL != "") { this._loadAllListsDropDown(this.properties.spotlightSiteURL); } if (this.properties.spotlightListName != "") { this._loadSpotlightListFieldsDropDown(this.properties.spotlightSiteURL, this.properties.spotlightListName); } }); }); } /** * Loads all the list names in the selected site for spotlight list dropdown. * @param siteUrl - The string containing site url. */ private _loadAllListsDropDown(siteUrl: string): void { this._getAllLists(siteUrl) .then((response) => { this.spotlightListOptions = this._getDropDownCollection(response, 'Title', 'Title'); this.context.propertyPane.refresh(); }); } /** * Loads the spotlight list fields for fields dropdown. * @param siteUrl - The string containing site url. * @param spotlightListName - The string containing spotlight list name. */ private _loadSpotlightListFieldsDropDown(siteUrl: string, spotlightListName: string): void { this._getSpotlightListFields(siteUrl, spotlightListName) .then((response) => { this.spotlightListFieldOptions = this._getDropDownCollection(response, 'Title', 'Title'); this.context.propertyPane.refresh(); }); } /** * Returns the dropdown key and values collection. * @param response - The collection containing keys and values. * @param key - The string containing key. * @param text - The string containing value. */ private _getDropDownCollection(response: ResponceCollection, key: string, text: string): IPropertyPaneDropdownOption[] { var dropdownOptions: IPropertyPaneDropdownOption[] = []; if (key == 'Url') dropdownOptions.push({ key: this.context.pageContext.web.absoluteUrl, text: 'This Site' }); for (var itemKey in response.value) { dropdownOptions.push({ key: response.value[itemKey][key], text: response.value[itemKey][text] }); } return dropdownOptions; } /** * Returns a promise that returns spotlight list items. * @param siteUrl - The string containing site url. * @param spotlightListName - The string containing spotlight list name. */ private _getSpotlightListData(siteUrl: string, spotlightListName: string, expiryDateColumn: string, emailColumn: string, descriptionColumn: string): Promise<ResponceCollection> { if (siteUrl != "" && spotlightListName != "") { var today: Date = new Date(); var dd: any = today.getDate(); var mm: any = today.getMonth() + 1; //January is 0! var yyyy: any = today.getFullYear(); dd = (dd < 10) ? '0' + dd : dd; mm = (mm < 10) ? '0' + mm : mm; var dateString: string = `${yyyy}-${mm}-${dd}`; emailColumn = emailColumn.replace(" ", "_x0020_"); descriptionColumn = descriptionColumn.replace(" ", "_x0020_"); expiryDateColumn = expiryDateColumn.replace(" ", "_x0020_"); return this._callAPI(siteUrl + `/_api/web/lists/GetByTitle('${spotlightListName}')/items?$select=ID,${descriptionColumn},${emailColumn}/EMail&$expand=${emailColumn}/Id&$orderby=Id desc&$filter=${expiryDateColumn} ge '${dateString}'`); } } /** * Validates the Property pane fields for null checks * @param value - The string value of the field to be validated. */ private _validateFiledValue(value: string): string { var validationMessage: string = ''; if (value === null || value.trim().length === 0) { validationMessage = 'Please select a value'; } return validationMessage; } protected get dataVersion(): Version { return Version.parse('1.0'); } /** * Builds the Propertypane with specific configurations. */ protected onPropertyPaneConfigurationStart(): void { // Stops execution, if the list values already exists if (this.spotlightListOptions.length > 0) return; // Calls function to append the list names to dropdown this._renderSpotlightTemplateAsync(); } /** * Triggers foreach Property pane value update and loads the corresponding details. * @param propertyPath - The string containing property path. * @param oldValue - The string containing old value of property. * @param newValue - The string containing new value of property. */ protected onPropertyPaneFieldChanged(propertyPath: string, oldValue: any, newValue: any): void { switch (propertyPath) { case "spotlightSiteURL": this.properties.spotlightListName = ""; this._loadAllListsDropDown(this.properties.spotlightSiteURL); break; case "spotlightListName": this.properties.spotlightEmployeeEmailColumn = ""; this.properties.spotlightDescriptionColumn = ""; this._loadSpotlightListFieldsDropDown(this.properties.spotlightSiteURL, this.properties.spotlightListName); break; default: break; } } /** * Retuns the property pane configuration. */ protected getPropertyPaneConfiguration(): IPropertyPaneConfiguration { return { pages: [ { groups: [ { groupName: strings.propertyPaneHeading, groupFields: [ PropertyPaneDropdown('spotlightSiteURL', { label: strings.selectSiteLableMessage, options: this.siteOptions, selectedKey: this._validateFiledValue.bind(this) }), PropertyPaneDropdown('spotlightListName', { label: strings.selectListLableMessage, options: this.spotlightListOptions, selectedKey: this._validateFiledValue.bind(this) }), PropertyPaneDropdown('spotlightEmployeeEmailColumn', { label: strings.employeeEmailcolumnLableMessage, options: this.spotlightListFieldOptions, selectedKey: this._validateFiledValue.bind(this) }), PropertyPaneDropdown('spotlightDescriptionColumn', { label: strings.descriptioncolumnLableMessage, options: this.spotlightListFieldOptions, selectedKey: this._validateFiledValue.bind(this) }), PropertyPaneDropdown('spotlightEmployeeExpirationDateColumn', { label: strings.expirationDateColumnLableMessage, options: this.spotlightListFieldOptions, selectedKey: this._validateFiledValue.bind(this) }) ] }, { groupName: strings.effectsGroupName, groupFields: [ PropertyFieldColorPickerMini('spotlightBGColor', { label: strings.spotlightBGColorLableMessage, initialColor: this.properties.spotlightBGColor, disabled: false, onPropertyChange: this.onPropertyPaneFieldChanged.bind(this), properties: this.properties, onGetErrorMessage: null, deferredValidationTime: 0, key: 'spotlightBGColorFieldId' }), PropertyFieldColorPickerMini('spotlightFontColor', { label: strings.spotlightFontColorLableMessage, initialColor: this.properties.spotlightFontColor, disabled: false, onPropertyChange: this.onPropertyPaneFieldChanged.bind(this), properties: this.properties, onGetErrorMessage: null, deferredValidationTime: 0, key: 'spotlightFontColorFieldId' }), PropertyPaneToggle('enabledSpotlightAutoPlay', { label: strings.enableAutoSlideLableMessage }), PropertyPaneSlider('spotlightSliderSpeed', { label: strings.carouselSpeedLableMessage, min: 0, max: 7, value: 3, showValue: true, step: 0.5 }) ] } ] } ] }; } }
the_stack
import { LPCore } from './core'; import { DateTime } from './datetime'; import { ILPConfiguration } from './interfaces'; import * as style from './scss/main.scss'; import { dateIsLocked, findNestedMonthItem } from './utils'; export class Calendar extends LPCore { constructor(options: ILPConfiguration) { super(options); // } protected render() { this.emit('before:render', this.ui); const mainBlock = document.createElement('div'); mainBlock.className = style.containerMain; const months = document.createElement('div'); months.className = style.containerMonths; if (style[`columns${this.options.numberOfColumns}`]) { months.classList.remove(style.columns2, style.columns3, style.columns4); months.classList.add(style[`columns${this.options.numberOfColumns}`]); } if (this.options.splitView) { months.classList.add(style.splitView); } if (this.options.showWeekNumbers) { months.classList.add(style.showWeekNumbers); } const startDate = this.calendars[0].clone(); const startMonthIdx = startDate.getMonth(); const totalMonths = startDate.getMonth() + this.options.numberOfMonths; let calendarIdx = 0; // tslint:disable-next-line: prefer-for-of for (let idx = startMonthIdx; idx < totalMonths; idx += 1) { let dateIterator = startDate.clone(); dateIterator.setDate(1); dateIterator.setHours(0, 0, 0, 0); if (this.options.splitView) { dateIterator = this.calendars[calendarIdx].clone(); } else { dateIterator.setMonth(idx); } months.appendChild(this.renderMonth(dateIterator, calendarIdx)); calendarIdx += 1; } this.ui.innerHTML = ''; mainBlock.appendChild(months); if (this.options.resetButton) { let resetButton; if (typeof this.options.resetButton === 'function') { resetButton = this.options.resetButton.call(this); } else { resetButton = document.createElement('button'); resetButton.type = 'button'; resetButton.className = style.resetButton; resetButton.innerHTML = this.options.buttonText.reset; } resetButton.addEventListener('click', (e) => { e.preventDefault(); // tslint:disable-next-line: no-string-literal this['clearSelection'](); }); mainBlock .querySelector(`.${style.monthItem}:last-child`) .querySelector(`.${style.monthItemHeader}`) .appendChild(resetButton); } this.ui.appendChild(mainBlock); if (!this.options.autoApply || this.options.footerHTML) { this.ui.appendChild(this.renderFooter()); } if (this.options.showTooltip) { this.ui.appendChild(this.renderTooltip()); } this.ui.dataset.plugins = (this.options.plugins || []).join('|'); this.emit('render', this.ui); } protected renderMonth(date: DateTime, calendarIdx: number) { const startDate = date.clone(); const totalDays = 32 - new Date(startDate.getFullYear(), startDate.getMonth(), 32).getDate(); const month = document.createElement('div'); month.className = style.monthItem; const monthHeader = document.createElement('div'); monthHeader.className = style.monthItemHeader; const monthAndYear = document.createElement('div'); if (this.options.dropdowns.months) { const selectMonths = document.createElement('select'); selectMonths.className = style.monthItemName; for (let x = 0; x < 12; x += 1) { const option = document.createElement('option'); // day 2 because iOS bug with `toLocaleString` // https://github.com/wakirin/Litepicker/issues/113 const monthName = new DateTime(new Date(date.getFullYear(), x, 2, 0, 0, 0)); const optionMonth = new DateTime(new Date(date.getFullYear(), x, 1, 0, 0, 0)); option.value = String(x); option.text = monthName.toLocaleString(this.options.lang, { month: 'long' }); option.disabled = (this.options.minDate && optionMonth.isBefore(new DateTime(this.options.minDate), 'month')) || (this.options.maxDate && optionMonth.isAfter(new DateTime(this.options.maxDate), 'month')); option.selected = optionMonth.getMonth() === date.getMonth(); selectMonths.appendChild(option); } selectMonths.addEventListener('change', (e) => { const target = e.target as HTMLSelectElement; let idx = 0; if (this.options.splitView) { const monthItem = target.closest(`.${style.monthItem}`); idx = findNestedMonthItem(monthItem); } this.calendars[idx].setMonth(Number(target.value)); this.render(); this.emit('change:month', this.calendars[idx], idx, e); }); monthAndYear.appendChild(selectMonths); } else { const monthName = document.createElement('strong'); monthName.className = style.monthItemName; monthName.innerHTML = date.toLocaleString(this.options.lang, { month: 'long' }); monthAndYear.appendChild(monthName); } if (this.options.dropdowns.years) { const selectYears = document.createElement('select'); selectYears.className = style.monthItemYear; const minYear = this.options.dropdowns.minYear; const maxYear = this.options.dropdowns.maxYear ? this.options.dropdowns.maxYear : (new Date()).getFullYear(); if (date.getFullYear() > maxYear) { const option = document.createElement('option'); option.value = String(date.getFullYear()); option.text = String(date.getFullYear()); option.selected = true; option.disabled = true; selectYears.appendChild(option); } for (let x = maxYear; x >= minYear; x -= 1) { const option = document.createElement('option'); const optionYear = new DateTime(new Date(x, 0, 1, 0, 0, 0)); option.value = String(x); option.text = String(x); option.disabled = (this.options.minDate && optionYear.isBefore(new DateTime(this.options.minDate), 'year')) || (this.options.maxDate && optionYear.isAfter(new DateTime(this.options.maxDate), 'year')); option.selected = date.getFullYear() === x; selectYears.appendChild(option); } if (date.getFullYear() < minYear) { const option = document.createElement('option'); option.value = String(date.getFullYear()); option.text = String(date.getFullYear()); option.selected = true; option.disabled = true; selectYears.appendChild(option); } if (this.options.dropdowns.years === 'asc') { const childs = Array.prototype.slice.call(selectYears.childNodes); const options = childs.reverse(); selectYears.innerHTML = ''; options.forEach((y) => { y.innerHTML = y.value; selectYears.appendChild(y); }); } selectYears.addEventListener('change', (e) => { const target = e.target as HTMLSelectElement; let idx = 0; if (this.options.splitView) { const monthItem = target.closest(`.${style.monthItem}`); idx = findNestedMonthItem(monthItem); } this.calendars[idx].setFullYear(Number(target.value)); this.render(); this.emit('change:year', this.calendars[idx], idx, e); }); monthAndYear.appendChild(selectYears); } else { const monthYear = document.createElement('span'); monthYear.className = style.monthItemYear; monthYear.innerHTML = String(date.getFullYear()); monthAndYear.appendChild(monthYear); } const previousMonthButton = document.createElement('button'); previousMonthButton.type = 'button'; previousMonthButton.className = style.buttonPreviousMonth; previousMonthButton.innerHTML = this.options.buttonText.previousMonth; const nextMonthButton = document.createElement('button'); nextMonthButton.type = 'button'; nextMonthButton.className = style.buttonNextMonth; nextMonthButton.innerHTML = this.options.buttonText.nextMonth; monthHeader.appendChild(previousMonthButton); monthHeader.appendChild(monthAndYear); monthHeader.appendChild(nextMonthButton); if (this.options.minDate && startDate.isSameOrBefore(new DateTime(this.options.minDate), 'month')) { month.classList.add(style.noPreviousMonth); } if (this.options.maxDate && startDate.isSameOrAfter(new DateTime(this.options.maxDate), 'month')) { month.classList.add(style.noNextMonth); } const weekdaysRow = document.createElement('div'); weekdaysRow.className = style.monthItemWeekdaysRow; if (this.options.showWeekNumbers) { weekdaysRow.innerHTML = '<div>W</div>'; } for (let w = 1; w <= 7; w += 1) { // 7 days, 4 is «Thursday» (new Date(1970, 0, 1, 12, 0, 0, 0)) const dayIdx = 7 - 4 + this.options.firstDay + w; const weekday = document.createElement('div'); weekday.innerHTML = this.weekdayName(dayIdx); weekday.title = this.weekdayName(dayIdx, 'long'); weekdaysRow.appendChild(weekday); } const days = document.createElement('div'); days.className = style.containerDays; const skipDays = this.calcSkipDays(startDate); if (this.options.showWeekNumbers && skipDays) { days.appendChild(this.renderWeekNumber(startDate)); } for (let idx = 0; idx < skipDays; idx += 1) { const dummy = document.createElement('div'); days.appendChild(dummy); } // tslint:disable-next-line: prefer-for-of for (let idx = 1; idx <= totalDays; idx += 1) { startDate.setDate(idx); if (this.options.showWeekNumbers && startDate.getDay() === this.options.firstDay) { days.appendChild(this.renderWeekNumber(startDate)); } days.appendChild(this.renderDay(startDate)); } month.appendChild(monthHeader); month.appendChild(weekdaysRow); month.appendChild(days); this.emit('render:month', month, date); return month; } protected renderDay(date: DateTime) { date.setHours(); const day = document.createElement('div'); day.className = style.dayItem; day.innerHTML = String(date.getDate()); day.dataset.time = String(date.getTime()); if (date.toDateString() === (new Date()).toDateString()) { day.classList.add(style.isToday); } if (this.datePicked.length) { if (this.datePicked[0].toDateString() === date.toDateString()) { day.classList.add(style.isStartDate); if (this.options.singleMode) { day.classList.add(style.isEndDate); } } if (this.datePicked.length === 2 && this.datePicked[1].toDateString() === date.toDateString()) { day.classList.add(style.isEndDate); } if (this.datePicked.length === 2) { if (date.isBetween(this.datePicked[0], this.datePicked[1])) { day.classList.add(style.isInRange); } } } else if (this.options.startDate) { const startDate = this.options.startDate as DateTime; const endDate = this.options.endDate as DateTime; if (startDate.toDateString() === date.toDateString()) { day.classList.add(style.isStartDate); if (this.options.singleMode) { day.classList.add(style.isEndDate); } } if (endDate && endDate.toDateString() === date.toDateString()) { day.classList.add(style.isEndDate); } if (startDate && endDate) { if (date.isBetween(startDate, endDate)) { day.classList.add(style.isInRange); } } } if (this.options.minDate && date.isBefore(new DateTime(this.options.minDate))) { day.classList.add(style.isLocked); } if (this.options.maxDate && date.isAfter(new DateTime(this.options.maxDate))) { day.classList.add(style.isLocked); } if (this.options.minDays > 1 && this.datePicked.length === 1) { const minDays = this.options.minDays - 1; // subtract selected day const left = this.datePicked[0].clone().subtract(minDays, 'day'); const right = this.datePicked[0].clone().add(minDays, 'day'); if (date.isBetween(left, this.datePicked[0], '(]')) { day.classList.add(style.isLocked); } if (date.isBetween(this.datePicked[0], right, '[)')) { day.classList.add(style.isLocked); } } if (this.options.maxDays && this.datePicked.length === 1) { const maxDays = this.options.maxDays; const left = this.datePicked[0].clone().subtract(maxDays, 'day'); const right = this.datePicked[0].clone().add(maxDays, 'day'); if (date.isSameOrBefore(left)) { day.classList.add(style.isLocked); } if (date.isSameOrAfter(right)) { day.classList.add(style.isLocked); } } if (this.options.selectForward && this.datePicked.length === 1 && date.isBefore(this.datePicked[0])) { day.classList.add(style.isLocked); } if (this.options.selectBackward && this.datePicked.length === 1 && date.isAfter(this.datePicked[0])) { day.classList.add(style.isLocked); } const locked = dateIsLocked(date, this.options, this.datePicked); if (locked) { day.classList.add(style.isLocked); } if (this.options.highlightedDays.length) { const isHighlighted = this.options.highlightedDays .filter((d) => { if (d instanceof Array) { return date.isBetween(d[0], d[1], '[]'); } return d.isSame(date, 'day'); }).length; if (isHighlighted) { day.classList.add(style.isHighlighted); } } // fix bug iOS 10-12 - https://github.com/wakirin/Litepicker/issues/124 day.tabIndex = !day.classList.contains('is-locked') ? 0 : -1; this.emit('render:day', day, date); return day; } protected renderFooter() { const footer = document.createElement('div'); footer.className = style.containerFooter; if (this.options.footerHTML) { footer.innerHTML = this.options.footerHTML; } else { footer.innerHTML = ` <span class="${style.previewDateRange}"></span> <button type="button" class="${style.buttonCancel}">${this.options.buttonText.cancel}</button> <button type="button" class="${style.buttonApply}">${this.options.buttonText.apply}</button> `; } if (this.options.singleMode) { if (this.datePicked.length === 1) { const startValue = this.datePicked[0].format(this.options.format, this.options.lang); footer.querySelector(`.${style.previewDateRange}`).innerHTML = startValue; } } else { if (this.datePicked.length === 1) { footer.querySelector(`.${style.buttonApply}`).setAttribute('disabled', ''); } if (this.datePicked.length === 2) { const startValue = this.datePicked[0].format(this.options.format, this.options.lang); const endValue = this.datePicked[1].format(this.options.format, this.options.lang); footer.querySelector(`.${style.previewDateRange}`) .innerHTML = `${startValue}${this.options.delimiter}${endValue}`; } } this.emit('render:footer', footer); return footer; } protected renderWeekNumber(date) { const wn = document.createElement('div'); const week = date.getWeek(this.options.firstDay); wn.className = style.weekNumber; wn.innerHTML = week === 53 && date.getMonth() === 0 ? '53 / 1' : week; return wn; } protected renderTooltip() { const t = document.createElement('div'); t.className = style.containerTooltip; return t; } private weekdayName(day, representation = 'short') { return new Date(1970, 0, day, 12, 0, 0, 0) .toLocaleString(this.options.lang, { weekday: representation }); } private calcSkipDays(date) { let total = date.getDay() - this.options.firstDay; if (total < 0) total += 7; return total; } }
the_stack
import * as FSE from 'fs-extra' import * as Path from 'path' import { GitProcess } from 'dugite' import { shell } from '../helpers/test-app-shell' import { setupEmptyRepository, setupFixtureRepository, } from '../helpers/repositories' import { GitStore } from '../../src/lib/stores' import { AppFileStatusKind } from '../../src/models/status' import { Repository } from '../../src/models/repository' import { Commit } from '../../src/models/commit' import { TipState, IValidBranch } from '../../src/models/tip' import { getCommit, getRemotes } from '../../src/lib/git' import { getStatusOrThrow } from '../helpers/status' import { makeCommit, switchTo, cloneLocalRepository, } from '../helpers/repository-scaffolding' import { BranchType } from '../../src/models/branch' import { StatsStore, StatsDatabase } from '../../src/lib/stats' import { UiActivityMonitor } from '../../src/ui/lib/ui-activity-monitor' describe('GitStore', () => { let statsStore: StatsStore beforeEach(() => { statsStore = new StatsStore( new StatsDatabase('test-StatsDatabase'), new UiActivityMonitor() ) }) describe('loadCommitBatch', () => { it('includes HEAD when loading commits', async () => { const path = await setupFixtureRepository('repository-with-105-commits') const repo = new Repository(path, -1, null, false) const gitStore = new GitStore(repo, shell, statsStore) const commits = await gitStore.loadCommitBatch('HEAD', 0) expect(commits).not.toBeNull() expect(commits).toHaveLength(100) expect(commits![0]).toEqual('708a46eac512c7b2486da2247f116d11a100b611') }) }) it('can discard changes from a repository', async () => { const repo = await setupEmptyRepository() const gitStore = new GitStore(repo, shell, statsStore) const readmeFile = 'README.md' const readmeFilePath = Path.join(repo.path, readmeFile) await FSE.writeFile(readmeFilePath, 'SOME WORDS GO HERE\n') const licenseFile = 'LICENSE.md' const licenseFilePath = Path.join(repo.path, licenseFile) await FSE.writeFile(licenseFilePath, 'SOME WORDS GO HERE\n') // commit the readme file but leave the license await GitProcess.exec(['add', readmeFile], repo.path) await GitProcess.exec(['commit', '-m', 'added readme file'], repo.path) await FSE.writeFile(readmeFilePath, 'WRITING SOME NEW WORDS\n') // setup requires knowing about the current tip await gitStore.loadStatus() let status = await getStatusOrThrow(repo) let files = status.workingDirectory.files expect(files).toHaveLength(2) expect(files[0].path).toEqual('README.md') expect(files[0].status.kind).toEqual(AppFileStatusKind.Modified) // discard the LICENSE.md file await gitStore.discardChanges([files[1]]) status = await getStatusOrThrow(repo) files = status.workingDirectory.files expect(files).toHaveLength(1) }) it('can discard a renamed file', async () => { const repo = await setupEmptyRepository() const gitStore = new GitStore(repo, shell, statsStore) const file = 'README.md' const renamedFile = 'NEW-README.md' const filePath = Path.join(repo.path, file) await FSE.writeFile(filePath, 'SOME WORDS GO HERE\n') // commit the file, and then rename it await GitProcess.exec(['add', file], repo.path) await GitProcess.exec(['commit', '-m', 'added file'], repo.path) await GitProcess.exec(['mv', file, renamedFile], repo.path) const statusBeforeDiscard = await getStatusOrThrow(repo) const filesToDiscard = statusBeforeDiscard.workingDirectory.files // discard the renamed file await gitStore.discardChanges(filesToDiscard) const status = await getStatusOrThrow(repo) const files = status.workingDirectory.files expect(files).toHaveLength(0) }) describe('undo first commit', () => { let repository: Repository let firstCommit: Commit | null = null const commitMessage = 'added file' beforeEach(async () => { repository = await setupEmptyRepository() const file = 'README.md' const filePath = Path.join(repository.path, file) await FSE.writeFile(filePath, 'SOME WORDS GO HERE\n') await GitProcess.exec(['add', file], repository.path) await GitProcess.exec(['commit', '-m', commitMessage], repository.path) firstCommit = await getCommit(repository, 'master') expect(firstCommit).not.toBeNull() expect(firstCommit!.parentSHAs).toHaveLength(0) }) it('reports the repository is unborn', async () => { const gitStore = new GitStore(repository, shell, statsStore) await gitStore.loadStatus() expect(gitStore.tip.kind).toEqual(TipState.Valid) await gitStore.undoCommit(firstCommit!) const after = await getStatusOrThrow(repository) expect(after.currentTip).toBeUndefined() }) it('pre-fills the commit message', async () => { const gitStore = new GitStore(repository, shell, statsStore) await gitStore.undoCommit(firstCommit!) const newCommitMessage = gitStore.commitMessage expect(newCommitMessage).not.toBeNull() expect(newCommitMessage!.summary).toEqual(commitMessage) }) it('clears the undo commit dialog', async () => { const gitStore = new GitStore(repository, shell, statsStore) await gitStore.loadStatus() const tip = gitStore.tip as IValidBranch await gitStore.loadLocalCommits(tip.branch) expect(gitStore.localCommitSHAs).toHaveLength(1) await gitStore.undoCommit(firstCommit!) await gitStore.loadStatus() expect(gitStore.tip.kind).toEqual(TipState.Unborn) await gitStore.loadLocalCommits(null) expect(gitStore.localCommitSHAs).toHaveLength(0) }) it('has no staged files', async () => { const gitStore = new GitStore(repository, shell, statsStore) await gitStore.loadStatus() const tip = gitStore.tip as IValidBranch await gitStore.loadLocalCommits(tip.branch) expect(gitStore.localCommitSHAs.length).toEqual(1) await gitStore.undoCommit(firstCommit!) // compare the index state to some other tree-ish // 4b825dc642cb6eb9a060e54bf8d69288fbee4904 is the magic empty tree // if nothing is staged, this should return no entries const result = await GitProcess.exec( [ 'diff-index', '--name-status', '-z', '4b825dc642cb6eb9a060e54bf8d69288fbee4904', ], repository.path ) expect(result.stdout.length).toEqual(0) }) }) describe('repository with HEAD file', () => { it('can discard modified change cleanly', async () => { const path = await setupFixtureRepository('repository-with-HEAD-file') const repo = new Repository(path, 1, null, false) const gitStore = new GitStore(repo, shell, statsStore) const file = 'README.md' const filePath = Path.join(repo.path, file) await FSE.writeFile(filePath, 'SOME WORDS GO HERE\n') let status = await getStatusOrThrow(repo!) let files = status.workingDirectory.files expect(files.length).toEqual(1) await gitStore.discardChanges([files[0]]) status = await getStatusOrThrow(repo) files = status.workingDirectory.files expect(files.length).toEqual(0) }) }) describe('loadBranches', () => { let upstream: Repository let repository: Repository beforeEach(async () => { upstream = await setupEmptyRepository() await makeCommit(upstream, { commitMessage: 'first commit', entries: [ { path: 'README.md', contents: 'some words go here', }, ], }) await makeCommit(upstream, { commitMessage: 'second commit', entries: [ { path: 'README.md', contents: 'some words go here\nand some more words', }, ], }) await switchTo(upstream, 'some-other-branch') await makeCommit(upstream, { commitMessage: 'branch commit', entries: [ { path: 'README.md', contents: 'changing some words', }, ], }) await makeCommit(upstream, { commitMessage: 'second branch commit', entries: [ { path: 'README.md', contents: 'and even more changing of words', }, ], }) // move this repository back to `master` before cloning await switchTo(upstream, 'master') repository = await cloneLocalRepository(upstream) }) it('has a remote defined', async () => { const remotes = await getRemotes(repository) expect(remotes).toHaveLength(1) }) it('will merge a local and remote branch when tracking branch set', async () => { const gitStore = new GitStore(repository, shell, statsStore) await gitStore.loadBranches() expect(gitStore.allBranches).toHaveLength(2) const defaultBranch = gitStore.allBranches.find(b => b.name === 'master') expect(defaultBranch!.upstream).toBe('origin/master') const remoteBranch = gitStore.allBranches.find( b => b.name === 'origin/some-other-branch' ) expect(remoteBranch!.type).toBe(BranchType.Remote) }) it('the tracking branch is not cleared when the remote branch is removed', async () => { // checkout the other branch after cloning await GitProcess.exec(['checkout', 'some-other-branch'], repository.path) const gitStore = new GitStore(repository, shell, statsStore) await gitStore.loadBranches() const currentBranchBefore = gitStore.allBranches.find( b => b.name === 'some-other-branch' ) expect(currentBranchBefore!.upstream).toBe('origin/some-other-branch') // delete the ref in the upstream branch await GitProcess.exec( ['branch', '-D', 'some-other-branch'], upstream.path ) // update the local repository state to remove the remote ref await GitProcess.exec(['fetch', '--prune', '--all'], repository.path) await gitStore.loadBranches() const currentBranchAfter = gitStore.allBranches.find( b => b.name === 'some-other-branch' ) // ensure the tracking information is unchanged expect(currentBranchAfter!.upstream).toBe('origin/some-other-branch') }) }) })
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://serviceuser.googleapis.com/$discovery/rest?version=v1 /// <reference types="gapi.client" /> declare namespace gapi.client { /** Load Google Service User API v1 */ function load(name: "serviceuser", version: "v1"): PromiseLike<void>; function load(name: "serviceuser", version: "v1", callback: () => any): void; const projects: serviceuser.ProjectsResource; const services: serviceuser.ServicesResource; namespace serviceuser { interface Api { /** The methods of this interface, in unspecified order. */ methods?: Method[]; /** Included interfaces. See Mixin. */ mixins?: Mixin[]; /** * The fully qualified name of this interface, including package name * followed by the interface's simple name. */ name?: string; /** Any metadata attached to the interface. */ options?: Option[]; /** * Source context for the protocol buffer service represented by this * message. */ sourceContext?: SourceContext; /** The source syntax of the service. */ syntax?: string; /** * A version string for this interface. If specified, must have the form * `major-version.minor-version`, as in `1.10`. If the minor version is * omitted, it defaults to zero. If the entire version field is empty, the * major version is derived from the package name, as outlined below. If the * field is not empty, the version in the package name will be verified to be * consistent with what is provided here. * * The versioning schema uses [semantic * versioning](http://semver.org) where the major version number * indicates a breaking change and the minor version an additive, * non-breaking change. Both version numbers are signals to users * what to expect from different versions, and should be carefully * chosen based on the product plan. * * The major version is also reflected in the package name of the * interface, which must end in `v<major-version>`, as in * `google.feature.v1`. For major versions 0 and 1, the suffix can * be omitted. Zero major versions must only be used for * experimental, non-GA interfaces. */ version?: string; } interface AuthProvider { /** * The list of JWT * [audiences](https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-4.1.3). * that are allowed to access. A JWT containing any of these audiences will * be accepted. When this setting is absent, only JWTs with audience * "https://Service_name/API_name" * will be accepted. For example, if no audiences are in the setting, * LibraryService API will only accept JWTs with the following audience * "https://library-example.googleapis.com/google.example.library.v1.LibraryService". * * Example: * * audiences: bookstore_android.apps.googleusercontent.com, * bookstore_web.apps.googleusercontent.com */ audiences?: string; /** * Redirect URL if JWT token is required but no present or is expired. * Implement authorizationUrl of securityDefinitions in OpenAPI spec. */ authorizationUrl?: string; /** * The unique identifier of the auth provider. It will be referred to by * `AuthRequirement.provider_id`. * * Example: "bookstore_auth". */ id?: string; /** * Identifies the principal that issued the JWT. See * https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-4.1.1 * Usually a URL or an email address. * * Example: https://securetoken.google.com * Example: 1234567-compute@developer.gserviceaccount.com */ issuer?: string; /** * URL of the provider's public key set to validate signature of the JWT. See * [OpenID Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderMetadata). * Optional if the key set document: * - can be retrieved from * [OpenID Discovery](https://openid.net/specs/openid-connect-discovery-1_0.html * of the issuer. * - can be inferred from the email domain of the issuer (e.g. a Google service account). * * Example: https://www.googleapis.com/oauth2/v1/certs */ jwksUri?: string; } interface AuthRequirement { /** * NOTE: This will be deprecated soon, once AuthProvider.audiences is * implemented and accepted in all the runtime components. * * The list of JWT * [audiences](https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-4.1.3). * that are allowed to access. A JWT containing any of these audiences will * be accepted. When this setting is absent, only JWTs with audience * "https://Service_name/API_name" * will be accepted. For example, if no audiences are in the setting, * LibraryService API will only accept JWTs with the following audience * "https://library-example.googleapis.com/google.example.library.v1.LibraryService". * * Example: * * audiences: bookstore_android.apps.googleusercontent.com, * bookstore_web.apps.googleusercontent.com */ audiences?: string; /** * id from authentication provider. * * Example: * * provider_id: bookstore_auth */ providerId?: string; } interface Authentication { /** Defines a set of authentication providers that a service supports. */ providers?: AuthProvider[]; /** * A list of authentication rules that apply to individual API methods. * * &#42;&#42;NOTE:&#42;&#42; All service configuration rules follow "last one wins" order. */ rules?: AuthenticationRule[]; } interface AuthenticationRule { /** * Whether to allow requests without a credential. The credential can be * an OAuth token, Google cookies (first-party auth) or EndUserCreds. * * For requests without credentials, if the service control environment is * specified, each incoming request &#42;&#42;must&#42;&#42; be associated with a service * consumer. This can be done by passing an API key that belongs to a consumer * project. */ allowWithoutCredential?: boolean; /** Configuration for custom authentication. */ customAuth?: CustomAuthRequirements; /** The requirements for OAuth credentials. */ oauth?: OAuthRequirements; /** Requirements for additional authentication providers. */ requirements?: AuthRequirement[]; /** * Selects the methods to which this rule applies. * * Refer to selector for syntax details. */ selector?: string; } interface AuthorizationConfig { /** * The name of the authorization provider, such as * firebaserules.googleapis.com. */ provider?: string; } interface Backend { /** * A list of API backend rules that apply to individual API methods. * * &#42;&#42;NOTE:&#42;&#42; All service configuration rules follow "last one wins" order. */ rules?: BackendRule[]; } interface BackendRule { /** The address of the API backend. */ address?: string; /** * The number of seconds to wait for a response from a request. The default * deadline for gRPC is infinite (no deadline) and HTTP requests is 5 seconds. */ deadline?: number; /** * Minimum deadline in seconds needed for this method. Calls having deadline * value lower than this will be rejected. */ minDeadline?: number; /** * Selects the methods to which this rule applies. * * Refer to selector for syntax details. */ selector?: string; } interface Billing { /** * Billing configurations for sending metrics to the consumer project. * There can be multiple consumer destinations per service, each one must have * a different monitored resource type. A metric can be used in at most * one consumer destination. */ consumerDestinations?: BillingDestination[]; } interface BillingDestination { /** * Names of the metrics to report to this billing destination. * Each name must be defined in Service.metrics section. */ metrics?: string[]; /** * The monitored resource type. The type must be defined in * Service.monitored_resources section. */ monitoredResource?: string; } interface Context { /** * A list of RPC context rules that apply to individual API methods. * * &#42;&#42;NOTE:&#42;&#42; All service configuration rules follow "last one wins" order. */ rules?: ContextRule[]; } interface ContextRule { /** A list of full type names of provided contexts. */ provided?: string[]; /** A list of full type names of requested contexts. */ requested?: string[]; /** * Selects the methods to which this rule applies. * * Refer to selector for syntax details. */ selector?: string; } interface Control { /** * The service control environment to use. If empty, no control plane * feature (like quota and billing) will be enabled. */ environment?: string; } interface CustomAuthRequirements { /** * A configuration string containing connection information for the * authentication provider, typically formatted as a SmartService string * (go/smartservice). */ provider?: string; } interface CustomError { /** * The list of custom error rules that apply to individual API messages. * * &#42;&#42;NOTE:&#42;&#42; All service configuration rules follow "last one wins" order. */ rules?: CustomErrorRule[]; /** The list of custom error detail types, e.g. 'google.foo.v1.CustomError'. */ types?: string[]; } interface CustomErrorRule { /** * Mark this message as possible payload in error response. Otherwise, * objects of this type will be filtered when they appear in error payload. */ isErrorType?: boolean; /** * Selects messages to which this rule applies. * * Refer to selector for syntax details. */ selector?: string; } interface CustomHttpPattern { /** The name of this custom HTTP verb. */ kind?: string; /** The path matched by this custom verb. */ path?: string; } interface Documentation { /** The URL to the root of documentation. */ documentationRootUrl?: string; /** * Declares a single overview page. For example: * <pre><code>documentation: * summary: ... * overview: &#40;== include overview.md ==&#41; * </code></pre> * This is a shortcut for the following declaration (using pages style): * <pre><code>documentation: * summary: ... * pages: * - name: Overview * content: &#40;== include overview.md ==&#41; * </code></pre> * Note: you cannot specify both `overview` field and `pages` field. */ overview?: string; /** The top level pages for the documentation set. */ pages?: Page[]; /** * A list of documentation rules that apply to individual API elements. * * &#42;&#42;NOTE:&#42;&#42; All service configuration rules follow "last one wins" order. */ rules?: DocumentationRule[]; /** * A short summary of what the service does. Can only be provided by * plain text. */ summary?: string; } interface DocumentationRule { /** * Deprecation description of the selected element(s). It can be provided if an * element is marked as `deprecated`. */ deprecationDescription?: string; /** Description of the selected API(s). */ description?: string; /** * The selector is a comma-separated list of patterns. Each pattern is a * qualified name of the element which may end in "&#42;", indicating a wildcard. * Wildcards are only allowed at the end and for a whole component of the * qualified name, i.e. "foo.&#42;" is ok, but not "foo.b&#42;" or "foo.&#42;.bar". To * specify a default for all applicable elements, the whole pattern "&#42;" * is used. */ selector?: string; } interface Endpoint { /** * DEPRECATED: This field is no longer supported. Instead of using aliases, * please specify multiple google.api.Endpoint for each of the intented * alias. * * Additional names that this endpoint will be hosted on. */ aliases?: string[]; /** * Allowing * [CORS](https://en.wikipedia.org/wiki/Cross-origin_resource_sharing), aka * cross-domain traffic, would allow the backends served from this endpoint to * receive and respond to HTTP OPTIONS requests. The response will be used by * the browser to determine whether the subsequent cross-origin request is * allowed to proceed. */ allowCors?: boolean; /** * The list of APIs served by this endpoint. * * If no APIs are specified this translates to "all APIs" exported by the * service, as defined in the top-level service configuration. */ apis?: string[]; /** The list of features enabled on this endpoint. */ features?: string[]; /** The canonical name of this endpoint. */ name?: string; /** * The specification of an Internet routable address of API frontend that will * handle requests to this [API Endpoint](https://cloud.google.com/apis/design/glossary). * It should be either a valid IPv4 address or a fully-qualified domain name. * For example, "8.8.8.8" or "myservice.appspot.com". */ target?: string; } interface Enum { /** Enum value definitions. */ enumvalue?: EnumValue[]; /** Enum type name. */ name?: string; /** Protocol buffer options. */ options?: Option[]; /** The source context. */ sourceContext?: SourceContext; /** The source syntax. */ syntax?: string; } interface EnumValue { /** Enum value name. */ name?: string; /** Enum value number. */ number?: number; /** Protocol buffer options. */ options?: Option[]; } interface Experimental { /** Authorization configuration. */ authorization?: AuthorizationConfig; } interface Field { /** The field cardinality. */ cardinality?: string; /** The string value of the default value of this field. Proto2 syntax only. */ defaultValue?: string; /** The field JSON name. */ jsonName?: string; /** The field type. */ kind?: string; /** The field name. */ name?: string; /** The field number. */ number?: number; /** * The index of the field type in `Type.oneofs`, for message or enumeration * types. The first type has index 1; zero means the type is not in the list. */ oneofIndex?: number; /** The protocol buffer options. */ options?: Option[]; /** Whether to use alternative packed wire representation. */ packed?: boolean; /** * The field type URL, without the scheme, for message or enumeration * types. Example: `"type.googleapis.com/google.protobuf.Timestamp"`. */ typeUrl?: string; } interface Http { /** * When set to true, URL path parmeters will be fully URI-decoded except in * cases of single segment matches in reserved expansion, where "%2F" will be * left encoded. * * The default behavior is to not decode RFC 6570 reserved characters in multi * segment matches. */ fullyDecodeReservedExpansion?: boolean; /** * A list of HTTP configuration rules that apply to individual API methods. * * &#42;&#42;NOTE:&#42;&#42; All service configuration rules follow "last one wins" order. */ rules?: HttpRule[]; } interface HttpRule { /** * Additional HTTP bindings for the selector. Nested bindings must * not contain an `additional_bindings` field themselves (that is, * the nesting may only be one level deep). */ additionalBindings?: HttpRule[]; /** * The name of the request field whose value is mapped to the HTTP body, or * `&#42;` for mapping all fields not captured by the path pattern to the HTTP * body. NOTE: the referred field must not be a repeated field and must be * present at the top-level of request message type. */ body?: string; /** * The custom pattern is used for specifying an HTTP method that is not * included in the `pattern` field, such as HEAD, or "&#42;" to leave the * HTTP method unspecified for this rule. The wild-card rule is useful * for services that provide content to Web (HTML) clients. */ custom?: CustomHttpPattern; /** Used for deleting a resource. */ delete?: string; /** Used for listing and getting information about resources. */ get?: string; /** * Use this only for Scotty Requests. Do not use this for bytestream methods. * For media support, add instead [][google.bytestream.RestByteStream] as an * API to your configuration. */ mediaDownload?: MediaDownload; /** * Use this only for Scotty Requests. Do not use this for media support using * Bytestream, add instead * [][google.bytestream.RestByteStream] as an API to your * configuration for Bytestream methods. */ mediaUpload?: MediaUpload; /** Used for updating a resource. */ patch?: string; /** Used for creating a resource. */ post?: string; /** Used for updating a resource. */ put?: string; /** * The name of the response field whose value is mapped to the HTTP body of * response. Other response fields are ignored. This field is optional. When * not set, the response message will be used as HTTP body of response. * NOTE: the referred field must be not a repeated field and must be present * at the top-level of response message type. */ responseBody?: string; /** * Selects methods to which this rule applies. * * Refer to selector for syntax details. */ selector?: string; } interface LabelDescriptor { /** A human-readable description for the label. */ description?: string; /** The label key. */ key?: string; /** The type of data that can be assigned to the label. */ valueType?: string; } interface ListEnabledServicesResponse { /** * Token that can be passed to `ListEnabledServices` to resume a paginated * query. */ nextPageToken?: string; /** Services enabled for the specified parent. */ services?: PublishedService[]; } interface LogDescriptor { /** * A human-readable description of this log. This information appears in * the documentation and can contain details. */ description?: string; /** * The human-readable name for this log. This information appears on * the user interface and should be concise. */ displayName?: string; /** * The set of labels that are available to describe a specific log entry. * Runtime requests that contain labels not specified here are * considered invalid. */ labels?: LabelDescriptor[]; /** * The name of the log. It must be less than 512 characters long and can * include the following characters: upper- and lower-case alphanumeric * characters [A-Za-z0-9], and punctuation characters including * slash, underscore, hyphen, period [/_-.]. */ name?: string; } interface Logging { /** * Logging configurations for sending logs to the consumer project. * There can be multiple consumer destinations, each one must have a * different monitored resource type. A log can be used in at most * one consumer destination. */ consumerDestinations?: LoggingDestination[]; /** * Logging configurations for sending logs to the producer project. * There can be multiple producer destinations, each one must have a * different monitored resource type. A log can be used in at most * one producer destination. */ producerDestinations?: LoggingDestination[]; } interface LoggingDestination { /** * Names of the logs to be sent to this destination. Each name must * be defined in the Service.logs section. If the log name is * not a domain scoped name, it will be automatically prefixed with * the service name followed by "/". */ logs?: string[]; /** * The monitored resource type. The type must be defined in the * Service.monitored_resources section. */ monitoredResource?: string; } interface MediaDownload { /** * A boolean that determines whether a notification for the completion of a * download should be sent to the backend. */ completeNotification?: boolean; /** * DO NOT USE FIELDS BELOW THIS LINE UNTIL THIS WARNING IS REMOVED. * * Specify name of the download service if one is used for download. */ downloadService?: string; /** Name of the Scotty dropzone to use for the current API. */ dropzone?: string; /** Whether download is enabled. */ enabled?: boolean; /** * Optional maximum acceptable size for direct download. * The size is specified in bytes. */ maxDirectDownloadSize?: string; /** * A boolean that determines if direct download from ESF should be used for * download of this media. */ useDirectDownload?: boolean; } interface MediaUpload { /** * A boolean that determines whether a notification for the completion of an * upload should be sent to the backend. These notifications will not be seen * by the client and will not consume quota. */ completeNotification?: boolean; /** Name of the Scotty dropzone to use for the current API. */ dropzone?: string; /** Whether upload is enabled. */ enabled?: boolean; /** * Optional maximum acceptable size for an upload. * The size is specified in bytes. */ maxSize?: string; /** * An array of mimetype patterns. Esf will only accept uploads that match one * of the given patterns. */ mimeTypes?: string[]; /** Whether to receive a notification for progress changes of media upload. */ progressNotification?: boolean; /** Whether to receive a notification on the start of media upload. */ startNotification?: boolean; /** * DO NOT USE FIELDS BELOW THIS LINE UNTIL THIS WARNING IS REMOVED. * * Specify name of the upload service if one is used for upload. */ uploadService?: string; } interface Method { /** The simple name of this method. */ name?: string; /** Any metadata attached to the method. */ options?: Option[]; /** If true, the request is streamed. */ requestStreaming?: boolean; /** A URL of the input message type. */ requestTypeUrl?: string; /** If true, the response is streamed. */ responseStreaming?: boolean; /** The URL of the output message type. */ responseTypeUrl?: string; /** The source syntax of this method. */ syntax?: string; } interface MetricDescriptor { /** A detailed description of the metric, which can be used in documentation. */ description?: string; /** * A concise name for the metric, which can be displayed in user interfaces. * Use sentence case without an ending period, for example "Request count". */ displayName?: string; /** * The set of labels that can be used to describe a specific * instance of this metric type. For example, the * `appengine.googleapis.com/http/server/response_latencies` metric * type has a label for the HTTP response code, `response_code`, so * you can look at latencies for successful responses or just * for responses that failed. */ labels?: LabelDescriptor[]; /** * Whether the metric records instantaneous values, changes to a value, etc. * Some combinations of `metric_kind` and `value_type` might not be supported. */ metricKind?: string; /** * The resource name of the metric descriptor. Depending on the * implementation, the name typically includes: (1) the parent resource name * that defines the scope of the metric type or of its data; and (2) the * metric's URL-encoded type, which also appears in the `type` field of this * descriptor. For example, following is the resource name of a custom * metric within the GCP project `my-project-id`: * * "projects/my-project-id/metricDescriptors/custom.googleapis.com%2Finvoice%2Fpaid%2Famount" */ name?: string; /** * The metric type, including its DNS name prefix. The type is not * URL-encoded. All user-defined custom metric types have the DNS name * `custom.googleapis.com`. Metric types should use a natural hierarchical * grouping. For example: * * "custom.googleapis.com/invoice/paid/amount" * "appengine.googleapis.com/http/server/response_latencies" */ type?: string; /** * The unit in which the metric value is reported. It is only applicable * if the `value_type` is `INT64`, `DOUBLE`, or `DISTRIBUTION`. The * supported units are a subset of [The Unified Code for Units of * Measure](http://unitsofmeasure.org/ucum.html) standard: * * &#42;&#42;Basic units (UNIT)&#42;&#42; * * &#42; `bit` bit * &#42; `By` byte * &#42; `s` second * &#42; `min` minute * &#42; `h` hour * &#42; `d` day * * &#42;&#42;Prefixes (PREFIX)&#42;&#42; * * &#42; `k` kilo (10&#42;&#42;3) * &#42; `M` mega (10&#42;&#42;6) * &#42; `G` giga (10&#42;&#42;9) * &#42; `T` tera (10&#42;&#42;12) * &#42; `P` peta (10&#42;&#42;15) * &#42; `E` exa (10&#42;&#42;18) * &#42; `Z` zetta (10&#42;&#42;21) * &#42; `Y` yotta (10&#42;&#42;24) * &#42; `m` milli (10&#42;&#42;-3) * &#42; `u` micro (10&#42;&#42;-6) * &#42; `n` nano (10&#42;&#42;-9) * &#42; `p` pico (10&#42;&#42;-12) * &#42; `f` femto (10&#42;&#42;-15) * &#42; `a` atto (10&#42;&#42;-18) * &#42; `z` zepto (10&#42;&#42;-21) * &#42; `y` yocto (10&#42;&#42;-24) * &#42; `Ki` kibi (2&#42;&#42;10) * &#42; `Mi` mebi (2&#42;&#42;20) * &#42; `Gi` gibi (2&#42;&#42;30) * &#42; `Ti` tebi (2&#42;&#42;40) * * &#42;&#42;Grammar&#42;&#42; * * The grammar includes the dimensionless unit `1`, such as `1/s`. * * The grammar also includes these connectors: * * &#42; `/` division (as an infix operator, e.g. `1/s`). * &#42; `.` multiplication (as an infix operator, e.g. `GBy.d`) * * The grammar for a unit is as follows: * * Expression = Component { "." Component } { "/" Component } ; * * Component = [ PREFIX ] UNIT [ Annotation ] * | Annotation * | "1" * ; * * Annotation = "{" NAME "}" ; * * Notes: * * &#42; `Annotation` is just a comment if it follows a `UNIT` and is * equivalent to `1` if it is used alone. For examples, * `{requests}/s == 1/s`, `By{transmitted}/s == By/s`. * &#42; `NAME` is a sequence of non-blank printable ASCII characters not * containing '{' or '}'. */ unit?: string; /** * Whether the measurement is an integer, a floating-point number, etc. * Some combinations of `metric_kind` and `value_type` might not be supported. */ valueType?: string; } interface MetricRule { /** * Metrics to update when the selected methods are called, and the associated * cost applied to each metric. * * The key of the map is the metric name, and the values are the amount * increased for the metric against which the quota limits are defined. * The value must not be negative. */ metricCosts?: Record<string, string>; /** * Selects the methods to which this rule applies. * * Refer to selector for syntax details. */ selector?: string; } interface Mixin { /** The fully qualified name of the interface which is included. */ name?: string; /** * If non-empty specifies a path under which inherited HTTP paths * are rooted. */ root?: string; } interface MonitoredResourceDescriptor { /** * Optional. A detailed description of the monitored resource type that might * be used in documentation. */ description?: string; /** * Optional. A concise name for the monitored resource type that might be * displayed in user interfaces. It should be a Title Cased Noun Phrase, * without any article or other determiners. For example, * `"Google Cloud SQL Database"`. */ displayName?: string; /** * Required. A set of labels used to describe instances of this monitored * resource type. For example, an individual Google Cloud SQL database is * identified by values for the labels `"database_id"` and `"zone"`. */ labels?: LabelDescriptor[]; /** * Optional. The resource name of the monitored resource descriptor: * `"projects/{project_id}/monitoredResourceDescriptors/{type}"` where * {type} is the value of the `type` field in this object and * {project_id} is a project ID that provides API-specific context for * accessing the type. APIs that do not use project information can use the * resource name format `"monitoredResourceDescriptors/{type}"`. */ name?: string; /** * Required. The monitored resource type. For example, the type * `"cloudsql_database"` represents databases in Google Cloud SQL. * The maximum length of this value is 256 characters. */ type?: string; } interface Monitoring { /** * Monitoring configurations for sending metrics to the consumer project. * There can be multiple consumer destinations, each one must have a * different monitored resource type. A metric can be used in at most * one consumer destination. */ consumerDestinations?: MonitoringDestination[]; /** * Monitoring configurations for sending metrics to the producer project. * There can be multiple producer destinations, each one must have a * different monitored resource type. A metric can be used in at most * one producer destination. */ producerDestinations?: MonitoringDestination[]; } interface MonitoringDestination { /** * Names of the metrics to report to this monitoring destination. * Each name must be defined in Service.metrics section. */ metrics?: string[]; /** * The monitored resource type. The type must be defined in * Service.monitored_resources section. */ monitoredResource?: string; } interface OAuthRequirements { /** * The list of publicly documented OAuth scopes that are allowed access. An * OAuth token containing any of these scopes will be accepted. * * Example: * * canonical_scopes: https://www.googleapis.com/auth/calendar, * https://www.googleapis.com/auth/calendar.read */ canonicalScopes?: string; } interface 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?: 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 OperationMetadata { /** Percentage of completion of this operation, ranging from 0 to 100. */ progressPercentage?: number; /** * The full name of the resources that this operation is directly * associated with. */ resourceNames?: string[]; /** The start time of the operation. */ startTime?: string; /** Detailed status information for each step. The order is undetermined. */ steps?: Step[]; } interface Option { /** * The option's name. For protobuf built-in options (options defined in * descriptor.proto), this is the short name. For example, `"map_entry"`. * For custom options, it should be the fully-qualified name. For example, * `"google.api.http"`. */ name?: string; /** * The option's value packed in an Any message. If the value is a primitive, * the corresponding wrapper type defined in google/protobuf/wrappers.proto * should be used. If the value is an enum, it should be stored as an int32 * value using the google.protobuf.Int32Value type. */ value?: Record<string, any>; } interface Page { /** * The Markdown content of the page. You can use <code>&#40;== include {path} ==&#41;</code> * to include content from a Markdown file. */ content?: string; /** * The name of the page. It will be used as an identity of the page to * generate URI of the page, text of the link to this page in navigation, * etc. The full page name (start from the root page name to this page * concatenated with `.`) can be used as reference to the page in your * documentation. For example: * <pre><code>pages: * - name: Tutorial * content: &#40;== include tutorial.md ==&#41; * subpages: * - name: Java * content: &#40;== include tutorial_java.md ==&#41; * </code></pre> * You can reference `Java` page using Markdown reference link syntax: * `Java`. */ name?: string; /** * Subpages of this page. The order of subpages specified here will be * honored in the generated docset. */ subpages?: Page[]; } interface PublishedService { /** * The resource name of the service. * * A valid name would be: * - services/serviceuser.googleapis.com */ name?: string; /** The service's published configuration. */ service?: Service; } interface Quota { /** List of `QuotaLimit` definitions for the service. */ limits?: QuotaLimit[]; /** * List of `MetricRule` definitions, each one mapping a selected method to one * or more metrics. */ metricRules?: MetricRule[]; } interface QuotaLimit { /** * Default number of tokens that can be consumed during the specified * duration. This is the number of tokens assigned when a client * application developer activates the service for their project. * * Specifying a value of 0 will block all requests. This can be used if you * are provisioning quota to selected consumers and blocking others. * Similarly, a value of -1 will indicate an unlimited quota. No other * negative values are allowed. * * Used by group-based quotas only. */ defaultLimit?: string; /** * Optional. User-visible, extended description for this quota limit. * Should be used only when more context is needed to understand this limit * than provided by the limit's display name (see: `display_name`). */ description?: string; /** * User-visible display name for this limit. * Optional. If not set, the UI will provide a default display name based on * the quota configuration. This field can be used to override the default * display name generated from the configuration. */ displayName?: string; /** * Duration of this limit in textual notation. Example: "100s", "24h", "1d". * For duration longer than a day, only multiple of days is supported. We * support only "100s" and "1d" for now. Additional support will be added in * the future. "0" indicates indefinite duration. * * Used by group-based quotas only. */ duration?: string; /** * Free tier value displayed in the Developers Console for this limit. * The free tier is the number of tokens that will be subtracted from the * billed amount when billing is enabled. * This field can only be set on a limit with duration "1d", in a billable * group; it is invalid on any other limit. If this field is not set, it * defaults to 0, indicating that there is no free tier for this service. * * Used by group-based quotas only. */ freeTier?: string; /** * Maximum number of tokens that can be consumed during the specified * duration. Client application developers can override the default limit up * to this maximum. If specified, this value cannot be set to a value less * than the default limit. If not specified, it is set to the default limit. * * To allow clients to apply overrides with no upper bound, set this to -1, * indicating unlimited maximum quota. * * Used by group-based quotas only. */ maxLimit?: string; /** * The name of the metric this quota limit applies to. The quota limits with * the same metric will be checked together during runtime. The metric must be * defined within the service config. * * Used by metric-based quotas only. */ metric?: string; /** * Name of the quota limit. The name is used to refer to the limit when * overriding the default limit on per-consumer basis. * * For metric-based quota limits, the name must be provided, and it must be * unique within the service. The name can only include alphanumeric * characters as well as '-'. * * The maximum length of the limit name is 64 characters. * * The name of a limit is used as a unique identifier for this limit. * Therefore, once a limit has been put into use, its name should be * immutable. You can use the display_name field to provide a user-friendly * name for the limit. The display name can be evolved over time without * affecting the identity of the limit. */ name?: string; /** * Specify the unit of the quota limit. It uses the same syntax as * Metric.unit. The supported unit kinds are determined by the quota * backend system. * * The [Google Service Control](https://cloud.google.com/service-control) * supports the following unit components: * &#42; One of the time intevals: * &#42; "/min" for quota every minute. * &#42; "/d" for quota every 24 hours, starting 00:00 US Pacific Time. * &#42; Otherwise the quota won't be reset by time, such as storage limit. * &#42; One and only one of the granted containers: * &#42; "/{project}" quota for a project * * Here are some examples: * &#42; "1/min/{project}" for quota per minute per project. * * Note: the order of unit components is insignificant. * The "1" at the beginning is required to follow the metric unit syntax. * * Used by metric-based quotas only. */ unit?: string; /** Tiered limit values, currently only STANDARD is supported. */ values?: Record<string, string>; } interface SearchServicesResponse { /** * Token that can be passed to `ListAvailableServices` to resume a paginated * query. */ nextPageToken?: string; /** Services available publicly or available to the authenticated caller. */ services?: PublishedService[]; } interface Service { /** * A list of API interfaces exported by this service. Only the `name` field * of the google.protobuf.Api needs to be provided by the configuration * author, as the remaining fields will be derived from the IDL during the * normalization process. It is an error to specify an API interface here * which cannot be resolved against the associated IDL files. */ apis?: Api[]; /** Auth configuration. */ authentication?: Authentication; /** API backend configuration. */ backend?: Backend; /** Billing configuration. */ billing?: Billing; /** * The semantic version of the service configuration. The config version * affects the interpretation of the service configuration. For example, * certain features are enabled by default for certain config versions. * The latest config version is `3`. */ configVersion?: number; /** Context configuration. */ context?: Context; /** Configuration for the service control plane. */ control?: Control; /** Custom error configuration. */ customError?: CustomError; /** Additional API documentation. */ documentation?: Documentation; /** * Configuration for network endpoints. If this is empty, then an endpoint * with the same name as the service is automatically generated to service all * defined APIs. */ endpoints?: Endpoint[]; /** * A list of all enum types included in this API service. Enums * referenced directly or indirectly by the `apis` are automatically * included. Enums which are not referenced but shall be included * should be listed here by name. Example: * * enums: * - name: google.someapi.v1.SomeEnum */ enums?: Enum[]; /** Experimental configuration. */ experimental?: Experimental; /** HTTP configuration. */ http?: Http; /** * A unique ID for a specific instance of this message, typically assigned * by the client for tracking purpose. If empty, the server may choose to * generate one instead. */ id?: string; /** Logging configuration. */ logging?: Logging; /** Defines the logs used by this service. */ logs?: LogDescriptor[]; /** Defines the metrics used by this service. */ metrics?: MetricDescriptor[]; /** * Defines the monitored resources used by this service. This is required * by the Service.monitoring and Service.logging configurations. */ monitoredResources?: MonitoredResourceDescriptor[]; /** Monitoring configuration. */ monitoring?: Monitoring; /** * The DNS address at which this service is available, * e.g. `calendar.googleapis.com`. */ name?: string; /** The Google project that owns this service. */ producerProjectId?: string; /** Quota configuration. */ quota?: Quota; /** Output only. The source information for this configuration if available. */ sourceInfo?: SourceInfo; /** System parameter configuration. */ systemParameters?: SystemParameters; /** * A list of all proto message types included in this API service. * It serves similar purpose as [google.api.Service.types], except that * these types are not needed by user-defined APIs. Therefore, they will not * show up in the generated discovery doc. This field should only be used * to define system APIs in ESF. */ systemTypes?: Type[]; /** The product title for this service. */ title?: string; /** * A list of all proto message types included in this API service. * Types referenced directly or indirectly by the `apis` are * automatically included. Messages which are not referenced but * shall be included, such as types used by the `google.protobuf.Any` type, * should be listed here by name. Example: * * types: * - name: google.protobuf.Int32 */ types?: Type[]; /** Configuration controlling usage of this service. */ usage?: Usage; /** API visibility configuration. */ visibility?: Visibility; } interface SourceContext { /** * The path-qualified name of the .proto file that contained the associated * protobuf element. For example: `"google/protobuf/source_context.proto"`. */ fileName?: string; } interface SourceInfo { /** All files used during config generation. */ sourceFiles?: Array<Record<string, any>>; } interface 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 Step { /** The short description of the step. */ description?: string; /** The status code. */ status?: string; } interface SystemParameter { /** * Define the HTTP header name to use for the parameter. It is case * insensitive. */ httpHeader?: string; /** Define the name of the parameter, such as "api_key" . It is case sensitive. */ name?: string; /** * Define the URL query parameter name to use for the parameter. It is case * sensitive. */ urlQueryParameter?: string; } interface SystemParameterRule { /** * Define parameters. Multiple names may be defined for a parameter. * For a given method call, only one of them should be used. If multiple * names are used the behavior is implementation-dependent. * If none of the specified names are present the behavior is * parameter-dependent. */ parameters?: SystemParameter[]; /** * Selects the methods to which this rule applies. Use '&#42;' to indicate all * methods in all APIs. * * Refer to selector for syntax details. */ selector?: string; } interface SystemParameters { /** * Define system parameters. * * The parameters defined here will override the default parameters * implemented by the system. If this field is missing from the service * config, default system parameters will be used. Default system parameters * and names is implementation-dependent. * * Example: define api key for all methods * * system_parameters * rules: * - selector: "&#42;" * parameters: * - name: api_key * url_query_parameter: api_key * * * Example: define 2 api key names for a specific method. * * system_parameters * rules: * - selector: "/ListShelves" * parameters: * - name: api_key * http_header: Api-Key1 * - name: api_key * http_header: Api-Key2 * * &#42;&#42;NOTE:&#42;&#42; All service configuration rules follow "last one wins" order. */ rules?: SystemParameterRule[]; } interface Type { /** The list of fields. */ fields?: Field[]; /** The fully qualified message name. */ name?: string; /** The list of types appearing in `oneof` definitions in this type. */ oneofs?: string[]; /** The protocol buffer options. */ options?: Option[]; /** The source context. */ sourceContext?: SourceContext; /** The source syntax. */ syntax?: string; } interface Usage { /** * The full resource name of a channel used for sending notifications to the * service producer. * * Google Service Management currently only supports * [Google Cloud Pub/Sub](https://cloud.google.com/pubsub) as a notification * channel. To use Google Cloud Pub/Sub as the channel, this must be the name * of a Cloud Pub/Sub topic that uses the Cloud Pub/Sub topic name format * documented in https://cloud.google.com/pubsub/docs/overview. */ producerNotificationChannel?: string; /** * Requirements that must be satisfied before a consumer project can use the * service. Each requirement is of the form <service.name>/<requirement-id>; * for example 'serviceusage.googleapis.com/billing-enabled'. */ requirements?: string[]; /** * A list of usage rules that apply to individual API methods. * * &#42;&#42;NOTE:&#42;&#42; All service configuration rules follow "last one wins" order. */ rules?: UsageRule[]; } interface UsageRule { /** True, if the method allows unregistered calls; false otherwise. */ allowUnregisteredCalls?: boolean; /** * Selects the methods to which this rule applies. Use '&#42;' to indicate all * methods in all APIs. * * Refer to selector for syntax details. */ selector?: string; /** * True, if the method should skip service control. If so, no control plane * feature (like quota and billing) will be enabled. */ skipServiceControl?: boolean; } interface Visibility { /** * A list of visibility rules that apply to individual API elements. * * &#42;&#42;NOTE:&#42;&#42; All service configuration rules follow "last one wins" order. */ rules?: VisibilityRule[]; } interface VisibilityRule { /** * A comma-separated list of visibility labels that apply to the `selector`. * Any of the listed labels can be used to grant the visibility. * * If a rule has multiple labels, removing one of the labels but not all of * them can break clients. * * Example: * * visibility: * rules: * - selector: google.calendar.Calendar.EnhancedSearch * restriction: GOOGLE_INTERNAL, TRUSTED_TESTER * * Removing GOOGLE_INTERNAL from this restriction will break clients that * rely on this method and only had access to it through GOOGLE_INTERNAL. */ restriction?: string; /** * Selects methods, messages, fields, enums, etc. to which this rule applies. * * Refer to selector for syntax details. */ selector?: string; } interface ServicesResource { /** * Disable a service so it can no longer be used with a * project. This prevents unintended usage that may cause unexpected billing * charges or security leaks. * * Operation<response: google.protobuf.Empty> */ disable(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; /** * Name of the consumer and the service to disable for that consumer. * * The Service User implementation accepts the following forms for consumer: * - "project:<project_id>" * * A valid path would be: * - /v1/projects/my-project/services/servicemanagement.googleapis.com:disable */ 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<Operation>; /** * Enable a service so it can be used with a project. * See [Cloud Auth Guide](https://cloud.google.com/docs/authentication) for * more information. * * Operation<response: google.protobuf.Empty> */ enable(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; /** * Name of the consumer and the service to enable for that consumer. * * A valid path would be: * - /v1/projects/my-project/services/servicemanagement.googleapis.com:enable */ 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<Operation>; /** List enabled services for the specified consumer. */ 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; /** Requested size of the next page of data. */ pageSize?: number; /** * Token identifying which result to start with; returned by a previous list * call. */ pageToken?: string; /** * List enabled services for the specified parent. * * An example valid parent would be: * - projects/my-project */ 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<ListEnabledServicesResponse>; } interface ProjectsResource { services: ServicesResource; } interface ServicesResource { /** * Search available services. * * When no filter is specified, returns all accessible services. For * authenticated users, also returns all services the calling user has * "servicemanagement.services.bind" permission for. */ search(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; /** Requested size of the next page of data. */ pageSize?: number; /** * Token identifying which result to start with; returned by a previous list * call. */ 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<SearchServicesResponse>; } } }
the_stack
import { validateText, hasWordCheck, calcTextInclusionRanges, _testMethods, HasWordOptions, ValidationOptions, } from './textValidator'; import { createCollection, getDictionary } from './SpellingDictionary'; import { createSpellingDictionary } from './SpellingDictionary/createSpellingDictionary'; import { FreqCounter } from './util/FreqCounter'; import * as Text from './util/text'; import { genSequence } from 'gensequence'; import { settingsToValidateOptions } from './validator'; const sToV = settingsToValidateOptions; // cspell:ignore whiteberry redmango lightbrown redberry describe('Validate textValidator functions', () => { test('tests hasWordCheck', async () => { // cspell:ignore redgreenblueyellow strawberrymangobanana redwhiteblue const dictCol = await getSpellingDictionaryCollection(); const opt: HasWordOptions = { useCompounds: true, ignoreCase: true, }; expect(hasWordCheck(dictCol, 'brown', opt)).toBe(true); expect(hasWordCheck(dictCol, 'white', opt)).toBe(true); expect(hasWordCheck(dictCol, 'berry', opt)).toBe(true); // compound words do not cross dictionary boundaries expect(hasWordCheck(dictCol, 'whiteberry', opt)).toBe(false); expect(hasWordCheck(dictCol, 'redmango', opt)).toBe(true); expect(hasWordCheck(dictCol, 'strawberrymangobanana', opt)).toBe(true); expect(hasWordCheck(dictCol, 'lightbrown', opt)).toBe(true); expect(hasWordCheck(dictCol, 'redgreenblueyellow', opt)).toBe(true); expect(hasWordCheck(dictCol, 'redwhiteblue', opt)).toBe(true); }); test('tests textValidator no word compounds', async () => { const dictCol = await getSpellingDictionaryCollection(); const result = validateText(sampleText, dictCol, sToV({})); const errors = result.map((wo) => wo.text).toArray(); expect(errors).toEqual(['giraffe', 'lightbrown', 'whiteberry', 'redberry']); }); test('tests textValidator with word compounds', async () => { const dictCol = await getSpellingDictionaryCollection(); const result = validateText(sampleText, dictCol, sToV({ allowCompoundWords: true })); const errors = result.map((wo) => wo.text).toArray(); expect(errors).toEqual(['giraffe', 'whiteberry']); }); // cSpell:ignore xxxkxxxx xxxbxxxx test('tests ignoring words that consist of a single repeated letter', async () => { const dictCol = await getSpellingDictionaryCollection(); const text = ' tttt gggg xxxxxxx jjjjj xxxkxxxx xxxbxxxx \n' + sampleText; const result = validateText(text, dictCol, sToV({ allowCompoundWords: true })); const errors = result .map((wo) => wo.text) .toArray() .sort(); expect(errors).toEqual(['giraffe', 'whiteberry', 'xxxbxxxx', 'xxxkxxxx']); }); test('tests trailing s, ed, ing, etc. are attached to the words', async () => { const dictEmpty = await createSpellingDictionary([], 'empty', 'test', {}); const text = 'We have PUBLISHed multiple FIXesToThePROBLEMs'; const result = validateText(text, dictEmpty, sToV({})).toArray(); const errors = result.map((wo) => wo.text); expect(errors).toEqual(['have', 'PUBLISHed', 'multiple', 'FIXes', 'PROBLEMs']); }); test('tests case in ignore words', async () => { const dict = await getDictionary({ words: ['=Sample', 'with', 'Issues'], ignoreWords: ['PUBLISHed', 'FIXesToThePROBLEMs'], // cspell:ignore fixestotheproblems }); const text = 'We have PUBLISHed published multiple FIXesToThePROBLEMs with Sample fixestotheproblems and issues.'; const options: ValidationOptions = { ignoreCase: false, }; const result = validateText(text, dict, options).toArray(); const errors = result.map((wo) => wo.text); expect(errors).toEqual(['have', 'published', 'multiple', 'fixestotheproblems', 'issues']); }); test('tests case in ignore words ignore case', async () => { const dict = await getDictionary({ words: ['=Sample', 'with', 'Issues'], ignoreWords: ['"PUBLISHed"', 'FIXesToThePROBLEMs'], // cspell:ignore fixestotheproblems }); const text = 'We have PUBLISHed published multiple FIXesToThePROBLEMs with Sample fixestotheproblems and issues.'; const options: ValidationOptions = { ignoreCase: true, }; const result = validateText(text, dict, options).toArray(); const errors = result.map((wo) => wo.text); expect(errors).toEqual(['have', 'published', 'multiple']); }); test('tests case sensitive word list', async () => { const wordList = ['PUBLISHed', 'FIXesToThePROBLEMs', 'multiple', 'VeryBadProblem', 'with'].concat( ['define', '_ERROR_CODE_42', 'NETWORK', '_ERROR42'], specialWords ); const flagWords = ['VeryBadProblem']; const dict = createSpellingDictionary(wordList, 'empty', 'test', { caseSensitive: true, }); const text = ` We have PUBLISHed published Multiple FIXesToThePROBLEMs. VeryBadProblem with the 4wheel of the Range8 in Amsterdam, Berlin, and paris. #define _ERROR_CODE_42 = NETWORK_ERROR42 `; const options: ValidationOptions = { allowCompoundWords: false, ignoreCase: false, flagWords, }; const result = validateText(text, dict, options).toArray(); const errors = result.map((wo) => wo.text); expect(errors).toEqual(['have', 'published', 'VeryBadProblem', 'paris']); }); test('tests trailing s, ed, ing, etc.', async () => { const dictWords = await getSpellingDictionaryCollection(); const text = 'We have PUBLISHed multiple FIXesToThePROBLEMs'; const result = validateText(text, dictWords, sToV({ allowCompoundWords: true })); const errors = result .map((wo) => wo.text) .toArray() .sort(); expect(errors).toEqual([]); }); test('contractions', async () => { const dictWords = await getSpellingDictionaryCollection(); // cspell:disable const text = `We should’ve done a better job, but we couldn\\'t have known.`; // cspell:enable const result = validateText(text, dictWords, sToV({ allowCompoundWords: false })); const errors = result .map((wo) => wo.text) .toArray() .sort(); expect(errors).toEqual([]); }); test('tests maxDuplicateProblems', async () => { const dict = await createSpellingDictionary([], 'empty', 'test', {}); const text = sampleText; const result = validateText( text, dict, sToV({ maxNumberOfProblems: 1000, maxDuplicateProblems: 1, }) ); const freq = FreqCounter.create(result.map((t) => t.text)); expect(freq.total).toBe(freq.counters.size); const words = freq.counters.keys(); const dict2 = await createSpellingDictionary(words, 'test', 'test', {}); const result2 = [...validateText(text, dict2, sToV({ maxNumberOfProblems: 1000, maxDuplicateProblems: 1 }))]; expect(result2.length).toBe(0); }); test('tests inclusion, no exclusions', () => { const result = calcTextInclusionRanges(sampleText, {}); expect(result.length).toBe(1); expect(result.map((a) => [a.startPos, a.endPos])).toEqual([[0, sampleText.length]]); }); test('tests inclusion, exclusion', () => { const result = calcTextInclusionRanges(sampleText, { ignoreRegExpList: [/The/g] }); expect(result.length).toBe(5); expect(result.map((a) => [a.startPos, a.endPos])).toEqual([ [0, 5], [8, 34], [37, 97], [100, 142], [145, 196], ]); }); test('tests words crossing exclude boundaries', async () => { const text = '_Test the _line_breaks___from __begin to end__ _eol_'; const inclusionRanges = calcTextInclusionRanges(text, { ignoreRegExpList: [/_/g] }); const mapper = _testMethods.mapWordsAgainstRanges(inclusionRanges); const results = Text.matchStringToTextOffset(/\w+/g, text).concatMap(mapper).toArray(); const words = results.map((r) => r.text); expect(words.join(' ')).toBe('Test the line breaks from begin to end eol'); }); test('tests words crossing exclude boundaries out of order', async () => { const text = '_Test the _line_breaks___from __begin to end__ _eol_'; const inclusionRanges = calcTextInclusionRanges(text, { ignoreRegExpList: [/_/g] }); const mapper = _testMethods.mapWordsAgainstRanges(inclusionRanges); // sort the texts by the word so it is out of order. const texts = [...Text.matchStringToTextOffset(/\w+/g, text)].sort((a, b) => a.text < b.text ? -1 : a.text > b.text ? 1 : 0 ); const results = genSequence(texts).concatMap(mapper).toArray(); const words = results.sort((a, b) => a.offset - b.offset).map((r) => r.text); expect(words.join(' ')).toBe('Test the line breaks from begin to end eol'); }); test.each` text | ignoreWords | flagWords | expected ${'red'} | ${[]} | ${undefined} | ${[]} ${'color'} | ${[]} | ${undefined} | ${[ov({ text: 'color', isFound: false })]} ${'colour'} | ${[]} | ${undefined} | ${[ov({ text: 'colour', isFlagged: true })]} ${'colour'} | ${['colour']} | ${undefined} | ${[]} ${'The ant ate the antelope.'} | ${[]} | ${['fbd']} | ${[]} ${'The ant ate the antelope.'} | ${[]} | ${['ate']} | ${[ov({ text: 'ate', isFlagged: true })]} ${'theANT_ateThe_antelope.'} | ${[]} | ${['ate']} | ${[ov({ text: 'ate', isFlagged: true })]} ${'The ant ate the antelope.'} | ${[]} | ${['antelope']} | ${[ov({ text: 'antelope', isFlagged: true })]} ${'This should be ok'} | ${[]} | ${[]} | ${[]} ${"This should've been ok"} | ${[]} | ${[]} | ${[]} ${"This should've not been ok"} | ${[]} | ${["should've"]} | ${[ov({ text: "should've", isFlagged: true })]} ${"They'll be allowed"} | ${[]} | ${[]} | ${[]} ${"They'll not be allowed"} | ${[]} | ${["they'll"]} | ${[ov({ text: "They'll", isFlagged: true })]} `('Validate forbidden words', ({ text, ignoreWords, expected, flagWords }) => { const dict = getSpellingDictionaryCollectionSync({ ignoreWords }); const result = [...validateText(text, dict, { ignoreCase: false, flagWords })]; expect(result).toEqual(expected); }); }); interface WithIgnoreWords { ignoreWords?: string[]; } async function getSpellingDictionaryCollection(options?: WithIgnoreWords) { return getSpellingDictionaryCollectionSync(options); } const colors = [ 'red', 'green', 'blue', 'black', 'white', 'orange', 'purple', 'yellow', 'gray', 'brown', 'light', 'dark', ]; const fruit = [ 'apple', 'banana', 'orange', 'pear', 'pineapple', 'mango', 'avocado', 'grape', 'strawberry', 'blueberry', 'blackberry', 'berry', 'red', ]; const animals = ['ape', 'lion', 'tiger', 'Elephant', 'monkey', 'gazelle', 'antelope', 'aardvark', 'hyena']; const insects = ['ant', 'snail', 'beetle', 'worm', 'stink bug', 'centipede', 'millipede', 'flea', 'fly']; const words = [ 'allowed', 'and', 'ate', 'be', 'been', 'better', 'big', 'dark', 'done', 'fixes', 'has', 'have', 'is', 'known', 'light', 'little', 'multiple', 'not', 'problems', 'published', 'should', 'the', 'they', 'this', 'to', 'we', "'ll", "couldn't", "should've", "shouldn't", "they'll", "they've", ]; const forbiddenWords = ['!colour', '!favour']; const specialWords = ['Range8', '4wheel', 'db2Admin', 'Amsterdam', 'Berlin', 'Paris']; const sampleText = ` The elephant and giraffe The lightbrown worm ate the apple, mango, and, strawberry. The little ant ate the big purple grape. The orange tiger ate the whiteberry and the redberry. `; function getSpellingDictionaryCollectionSync(options?: WithIgnoreWords) { const dicts = [ createSpellingDictionary(colors, 'colors', 'test', {}), createSpellingDictionary(fruit, 'fruit', 'test', {}), createSpellingDictionary(animals, 'animals', 'test', {}), createSpellingDictionary(insects, 'insects', 'test', {}), createSpellingDictionary(words, 'words', 'test', { repMap: [['’', "'"]] }), createSpellingDictionary(forbiddenWords, 'forbidden-words', 'test', {}), createSpellingDictionary(options?.ignoreWords || [], 'ignore-words', 'test', { caseSensitive: true, noSuggest: true, }), ]; return createCollection(dicts, 'collection'); } function ov<T>(t: Partial<T>, ...rest: Partial<T>[]): T { return expect.objectContaining(Object.assign({}, t, ...rest)); }
the_stack
import { Observable } from 'rxjs/Observable'; import { Subject } from 'rxjs/Subject'; import { errorIds } from './../shared/models/error-ids'; import { PortalResources } from './../shared/models/portal-resources'; import { LogCategories, ScenarioIds, ARM } from './../shared/models/constants'; import { Subscription } from './../shared/models/subscription'; import { ArmObj, ArmArrayResult } from './../shared/models/arm/arm-obj'; import { TreeNode, MutableCollection, Disposable, Refreshable } from './tree-node'; import { SideNavComponent } from '../side-nav/side-nav.component'; import { DashboardType } from './models/dashboard-type'; import { Site } from '../shared/models/arm/site'; import { AppNode } from './app-node'; import { BroadcastEvent } from '../shared/models/broadcast-event'; import { ArmUtil } from 'app/shared/Utilities/arm-utils'; import { UserService } from '../shared/services/user.service'; import { ScenarioService } from '../shared/services/scenario/scenario.service'; import { BroadcastService } from 'app/shared/services/broadcast.service'; import { ArmSiteDescriptor } from 'app/shared/resourceDescriptors'; interface SearchInfo { searchTerm: string; subscriptions: Subscription[]; } export class AppsNode extends TreeNode implements MutableCollection, Disposable, Refreshable { public title = this.sideNav.translateService.instant(PortalResources.functionApps); public dashboardType = DashboardType.AppsDashboard; public supportsRefresh = true; public resourceId = '/apps'; public isExpanded = true; private _exactAppSearchExp = '"(.+)"'; private _searchTerm: string; private _subscriptions: Subscription[]; private _searchInfo = new Subject<SearchInfo>(); private _broadcastService: BroadcastService; private _userService: UserService; private _scenarioService: ScenarioService; private _initialResourceId: string; constructor( sideNav: SideNavComponent, rootNode: TreeNode, private _subscriptionsStream: Subject<Subscription[]>, private _searchTermStream: Subject<string>, private _permanentResourceId: string ) { // Should only be used for when the iframe is open on a specific app super(sideNav, null, rootNode, '/apps/new/app'); this._initialResourceId = this._permanentResourceId; this.newDashboardType = null; this._userService = sideNav.injector.get(UserService); this._scenarioService = sideNav.injector.get(ScenarioService); this._userService.getStartupInfo().subscribe(info => { if (this._scenarioService.checkScenario(ScenarioIds.createApp).status === 'enabled') { if (info.subscriptions && info.subscriptions.length > 0) { this.newDashboardType = DashboardType.createApp; this.nodeClass += ' create-app'; } else { this.newDashboardType = null; } } else { this.newDashboardType = null; } }); this._broadcastService = sideNav.injector.get(BroadcastService); this.iconClass = 'tree-node-collection-icon'; this.iconUrl = 'image/BulletList.svg'; this.showExpandIcon = false; // Always listening for list update this._broadcastService.getEvents<AppNode[]>(BroadcastEvent.UpdateAppsList).subscribe(children => { this.children = children ? children : []; }); // Always listening for subscription changes this._subscriptionsStream.subscribe(subs => { this._subscriptions = subs; if (!this._initialized()) { return; } this._searchInfo.next({ searchTerm: this._searchTerm, subscriptions: subs, }); }); // Always listening for search term changes this._searchTermStream .distinctUntilChanged() .debounceTime(500) .subscribe(term => { this._searchTerm = term; if (!this._initialized()) { return; } this._searchInfo.next({ searchTerm: this._searchTerm, subscriptions: this._subscriptions, }); }); this._searchInfo .switchMap(result => { this._broadcastService.broadcastEvent<AppNode[]>(BroadcastEvent.UpdateAppsList, null); this.isLoading = true; this.supportsRefresh = false; this._subscriptions = result.subscriptions; return this._doSearch(<AppNode[]>this.children, result.searchTerm, result.subscriptions, 0, null); }) .do( () => { this.supportsRefresh = true; }, err => { this.sideNav.logService.error(LogCategories.SideNav, '/search-error', err); } ) .retry() .subscribe((result: { term: string; children: TreeNode[] }) => { try { if (!result) { this.isLoading = false; return; } const regex = new RegExp(this._exactAppSearchExp, 'i'); const exactSearchResult = regex.exec(result.term); if (exactSearchResult && exactSearchResult.length > 1) { this.supportsRefresh = false; const filteredChildren = result.children.filter(c => { if (c.title.toLowerCase() === exactSearchResult[1].toLowerCase()) { c.select(); return true; } return false; }); // Purposely don't update the stream with the filtered list of children. // This is because we only want the exact matching to affect the tree view, // not any other listeners. this._broadcastService.broadcastEvent<AppNode[]>(BroadcastEvent.UpdateAppsList, result.children as AppNode[]); this.children = filteredChildren; // Scoping to an app will cause the currently focused item in the tree to be // recreated. In that case, we'll just refocus on the root node. It's probably // not ideal but simple for us to do. this.treeView.setFocus(this); } else { this.supportsRefresh = true; } this.isLoading = false; } catch (err) { this.isLoading = false; this.sideNav.logService.error(LogCategories.SideNav, '/parse-search', err); } }); } public handleSelection(): Observable<any> { this.inSelectedTree = true; this.supportsRefresh = true; return Observable.of(null); } public handleDeselection() { // For now, we're just hiding the refresh icon if you're not currently on the apps node. The only reason // is because we're not properly handling the restoration of the selection properly if you're currently // selected on a node that's a few levels deep in the tree. If we fix that, then we just need to also // make sure that we check for dirty state before we allow someone to refresh. this.inSelectedTree = false; this.supportsRefresh = false; this._initialResourceId = ''; } public handleRefresh(): Observable<any> { this.sideNav.cacheService.clearArmIdCachePrefix(`/resources`); this.isLoading = true; this._searchInfo.next({ searchTerm: this._searchTerm, subscriptions: this._subscriptions, }); return Observable.of(null); } private _initialized() { return this._subscriptions && this._subscriptions.length > 0 && this._searchTerm !== undefined; } private _getFakeSitesArrayResult(children: AppNode[], subscriptions: Subscription[], term: string, exactSearch: boolean) { // Return a fake ArmArryResult containing a single fake site object corresponding to _permanentResourceId // Only add the fake site object to the fake result if all of the following are true: // - A child node corresonding to _permanentResourceId doesn't already exist. // - The subscription for _permanentResourceId matches one of the values in the subscriptions filter array. // - The site name for _permanentResourceId matches the filter term. const fakeArrayResult: ArmArrayResult<any> = { value: [], nextLink: null }; try { if (!!this._permanentResourceId) { const nodeIndex = children.findIndex( c => !!c.resourceId && c.resourceId.toLocaleLowerCase() === this._permanentResourceId.toLocaleLowerCase() ); const nodeAlreadyExists = nodeIndex !== -1; if (!nodeAlreadyExists) { const siteDescriptor = new ArmSiteDescriptor(this._permanentResourceId); const [siteName, siteSubscription] = [siteDescriptor.site, siteDescriptor.subscription]; const suscriptionMatches = subscriptions.findIndex(s => s.subscriptionId.toLowerCase() === siteSubscription.toLowerCase()) !== -1; if (suscriptionMatches) { const exactNameMatch = exactSearch && term.toLocaleLowerCase() === `"${siteName.toLocaleLowerCase()}"`; const nonExactNameMatch = !exactSearch && (!term || siteName.indexOf(term) !== -1); if (exactNameMatch || nonExactNameMatch) { fakeArrayResult.value.push({ id: this._permanentResourceId, kind: 'functionapp', location: '---', name: siteName, type: 'Microsoft.Web/sites', } as ArmObj<any>); } } } } } catch (e) {} return fakeArrayResult; } private _doSearch( children: AppNode[], term: string, subscriptions: Subscription[], subsIndex: number, nextLink: string ): Observable<{ term: string; children: TreeNode[] }> { let url: string = null; const regex = new RegExp(this._exactAppSearchExp, 'i'); const exactSearchResult = regex.exec(term); const exactSearch = !!exactSearchResult && exactSearchResult.length > 1; const subsBatch = subscriptions.slice(subsIndex, subsIndex + ARM.MaxSubscriptionBatchSize); // If the user wants an exact match, then we'll query everything and then filter to that // item. This would be slower for some scenario's where you do an exact search and there // is already a filtered list. But it will be much faster if the full list is already cached. if (!term || exactSearch) { url = this._getArmCacheUrl(subsBatch, nextLink, 'Microsoft.Web/sites'); } else { url = this._getArmSearchUrl(term, subsBatch, nextLink); } const sitesPromise = this.sideNav.cacheService .get(url, false, null, true) .map(r => { return !!r ? (r.json() as ArmArrayResult<any>) : null; }) .catch((e: any) => { const err = (e && e.json && e.json().error) || { message: 'Failed to query for resources.' }; this.sideNav.logService.error(LogCategories.SideNav, errorIds.failedToQueryArmResource, err); // The /resources API call failed, so we're going to fallback to a fake result object. const fakeArraryResult = this._getFakeSitesArrayResult(children, subscriptions, term, exactSearch); return Observable.of(fakeArraryResult); }); return sitesPromise .switchMap(result => { if (!result) { return Observable.of(null); } const nodes = result.value.filter(ArmUtil.isFunctionApp).map(armObj => { let newNode: AppNode; if (armObj.id === this.sideNav.selectedNode.resourceId) { newNode = <AppNode>this.sideNav.selectedNode; } else { newNode = new AppNode(this.sideNav, armObj, this, subscriptions); if (newNode.resourceId === this._initialResourceId) { newNode.select(); } } return newNode; }); children = children.concat(nodes); // Only update children if we're not doing an exact match. For exact matches, we // wait until everything is done loading and then show the final result if (!exactSearch) { this._broadcastService.broadcastEvent<AppNode[]>(BroadcastEvent.UpdateAppsList, children); } if (result.nextLink || subsIndex + ARM.MaxSubscriptionBatchSize < subscriptions.length) { return this._doSearch(children, term, subscriptions, subsIndex + ARM.MaxSubscriptionBatchSize, result.nextLink); } else { return Observable.of({ term: term, children: children, }); } }) .share(); } public addChild(childSiteObj: ArmObj<Site>) { const newNode = new AppNode(this.sideNav, childSiteObj, this, this._subscriptions); this._addChildAlphabetically(newNode); newNode.select(); } public removeChild(child: TreeNode, callRemoveOnChild?: boolean) { const removeIndex = this.children.findIndex((childNode: TreeNode) => { return childNode.resourceId === child.resourceId; }); this._removeHelper(removeIndex, callRemoveOnChild); this._broadcastService.broadcastEvent<AppNode[]>(BroadcastEvent.UpdateAppsList, this.children as AppNode[]); this.sideNav.cacheService.clearArmIdCachePrefix(`/resources`); } private _getArmCacheUrl(subs: Subscription[], nextLink: string, type1: string, type2?: string) { let url: string; if (nextLink) { url = nextLink; } else { url = `${this.sideNav.armService.armUrl}/resources?api-version=${this.sideNav.armService.armApiVersion}&$filter=(`; for (let i = 0; i < subs.length; i++) { url += `subscriptionId eq '${subs[i].subscriptionId}'`; if (i < subs.length - 1) { url += ` or `; } } url += `) and (resourceType eq '${type1}'`; if (type2) { url += ` or resourceType eq '${type2}'`; } url += `)`; } return url; } private _getArmSearchUrl(term: string, subs: Subscription[], nextLink: string) { let url: string; if (nextLink) { url = nextLink; } else { url = `${this.sideNav.armService.armUrl}/resources?api-version=${ this.sideNav.armService.armApiVersion }&$filter=(resourceType eq 'microsoft.web/sites') and (`; for (let i = 0; i < subs.length; i++) { url += `subscriptionId eq '${subs[i].subscriptionId}'`; if (i < subs.length - 1) { url += ` or `; } } url += `) and (substringof('${term}', name))`; } return url; } }
the_stack
import { Nullable } from "../../../../shared/types"; import * as React from "react"; import { ParticleSystem, FactorGradient, ColorGradient, IValueGradient, Color4, } from "babylonjs"; import { Inspector, IObjectInspectorProps } from "../../components/inspector"; import { InspectorButton } from "../../gui/inspector/fields/button"; import { InspectorSection } from "../../gui/inspector/fields/section"; import { AbstractInspector } from "../abstract-inspector"; import { ParticleSystemColorGradient } from "./color-gradient"; import { ParticleSystemFactorGradient } from "./factor-gradient"; export interface IParticleGradientInspectorState { /** * Defines the list of all available start size gradients. */ startSizeGradients: Nullable<FactorGradient[]>; /** * Defines the list of all available size gradients. */ sizeGradients: Nullable<FactorGradient[]>; /** * Defines the list of all available lifetime gradients. */ lifetimeGradients: Nullable<FactorGradient[]>; /** * Defines the list of all available velocity gradients; */ velocityGradients: Nullable<FactorGradient[]>; /** * Defines the list of all available angular speed gradients. */ angularSpeedGradients: Nullable<FactorGradient[]>; /** * Defines the list of all available color gradients. */ colorGradients: Nullable<ColorGradient[]>; } export interface IGradientCreator<T> { /** * Defines the title of the gradient category. */ title: string; /** * Defines the list of all available gradients to be edited. */ getGradients: () => Nullable<T[]>; /** * Called on the user wants to add a new gradient. */ onAdd: () => void; /** * Called on the user wants to remove a gradient. */ onRemove: (gradient: T) => void; /** * Defines the string used on the button to use gradients. */ useString: string; /** * Defines the string used on the button to add a new gradient. */ addString: string; /** * Defines the key in the state used when updating the state. */ stateKey: keyof IParticleGradientInspectorState; } export class ParticleSystemGradientsInspector extends AbstractInspector<ParticleSystem, IParticleGradientInspectorState> { /** * Constructor. * @param props defines the component's props. */ public constructor(props: IObjectInspectorProps) { super(props); this.state = { startSizeGradients: this._getNullableGradient(this.selectedObject.getStartSizeGradients()), sizeGradients: this._getNullableGradient(this.selectedObject.getSizeGradients()), lifetimeGradients: this._getNullableGradient(this.selectedObject.getLifeTimeGradients()), velocityGradients: this._getNullableGradient(this.selectedObject.getVelocityGradients()), angularSpeedGradients: this._getNullableGradient(this.selectedObject.getAngularSpeedGradients()), colorGradients: this._getNullableGradient(this.selectedObject.getColorGradients()), }; } /** * Renders the content of the inspector. */ public renderContent(): React.ReactNode { return ( <> {this.getFactorGradientInspector({ title: "Size", useString: "Use Size Gradients", addString: "Add Size Gradients", stateKey: "sizeGradients", getGradients: () => this.selectedObject.getSizeGradients(), onAdd: () => this.selectedObject.addSizeGradient(1, 1, 1), onRemove: (g) => this.selectedObject.removeSizeGradient(g.gradient), })} {this.getFactorGradientInspector({ title: "Lifetime", useString: "Use Lifetime Gradients", addString: "Add Lifetime Gradient", stateKey: "lifetimeGradients", getGradients: () => this.selectedObject.getLifeTimeGradients(), onAdd: () => this.selectedObject.addLifeTimeGradient(1, 1, 1), onRemove: (g) => this.selectedObject.removeLifeTimeGradient(g.gradient), })} {this.getFactorGradientInspector({ title: "Velocity", useString: "Use Velocity Gradients", addString: "Add Velocity Gradient", stateKey: "velocityGradients", getGradients: () => this.selectedObject.getVelocityGradients(), onAdd: () => this.selectedObject.addVelocityGradient(1, 1, 1), onRemove: (g) => this.selectedObject.removeVelocityGradient(g.gradient), })} {this.getFactorGradientInspector({ title: "Angular Speed", useString: "Use Angular Speed Gradients", addString: "Add Angular Speed Gradient", stateKey: "angularSpeedGradients", getGradients: () => this.selectedObject.getAngularSpeedGradients(), onAdd: () => this.selectedObject.addAngularSpeedGradient(1, 1, 1), onRemove: (g) => this.selectedObject.removeAngularSpeedGradient(g.gradient), })} {this.getColorGradientInspector({ title: "Color", useString: "Use Color Gradients", addString: "Add Color Gradient", stateKey: "colorGradients", getGradients: () => this.selectedObject.getColorGradients(), onAdd: () => this.selectedObject.addColorGradient(1, new Color4(1, 1, 1, 1), new Color4(1, 1, 1, 1)), onRemove: (g) => this.selectedObject.removeColorGradient(g.gradient), })} </> ); } /** * Returns the inspector used to configure the given factor gradients. * @param configuration defines the reference to the configuration of the gradient inspector. */ protected getFactorGradientInspector(configuration: IGradientCreator<FactorGradient>): React.ReactNode { const gradients = configuration.getGradients(); if (!gradients?.length) { return ( <InspectorSection title={configuration.title}> <InspectorButton label={configuration.useString} small={true} onClick={() => { configuration.onAdd(); this._updateGradientState(configuration); }} /> </InspectorSection> ); } return ( <InspectorSection title={configuration.title}> {gradients.map((g, index) => ( <ParticleSystemFactorGradient key={`${configuration.stateKey}-${index}-${g.gradient}`} index={index} particleSystem={this.selectedObject} gradient={g} onRemove={() => { configuration.onRemove(g); this._updateGradientState(configuration); }} onFinishChangeGradient={() => { if (!gradients) { return; } gradients.sort((a, b) => a.gradient - b.gradient); this._updateGradientState(configuration); }} /> ))} <InspectorButton label={configuration.addString} small={true} onClick={() => { configuration.onAdd(); this._updateGradientState(configuration); }} /> </InspectorSection> ); } /** * Returns the inspector used to configure the given color gradients. * @param configuration defines the reference to the configuration of the gradient inspector. */ protected getColorGradientInspector(configuration: IGradientCreator<ColorGradient>): React.ReactNode { const gradients = configuration.getGradients(); if (!gradients?.length) { return ( <InspectorSection title={configuration.title}> <InspectorButton label={configuration.useString} small={true} onClick={() => { configuration.onAdd(); this._updateGradientState(configuration); }} /> </InspectorSection> ); } return ( <InspectorSection title={configuration.title}> {gradients.map((g, index) => ( <ParticleSystemColorGradient key={`${configuration.stateKey}-${index}-${g.gradient}`} index={index} particleSystem={this.selectedObject} gradient={g} onRemove={() => { configuration.onRemove(g); this._updateGradientState(configuration); }} onFinishChangeGradient={() => { if (!gradients) { return; } gradients.sort((a, b) => a.gradient - b.gradient); this._updateGradientState(configuration); }} /> ))} <InspectorButton label={configuration.addString} small={true} onClick={() => { configuration.onAdd(); this._updateGradientState(configuration); }} /> </InspectorSection> ); } /** * Updates the given factor state using its configuration. */ private _updateGradientState(configuration: IGradientCreator<FactorGradient | ColorGradient>): void { this.setState({ [configuration.stateKey]: this._getNullableGradient(configuration.getGradients()) } as any); } /** * Returns a null value in case of 0 or null gradients. */ private _getNullableGradient<T extends IValueGradient>(gradients: Nullable<T[]>): Nullable<T[]> { if ((gradients?.length ?? 0) === 0) { return null; } return gradients!.slice(); } } Inspector.RegisterObjectInspector({ ctor: ParticleSystemGradientsInspector, ctorNames: ["ParticleSystem"], title: "Gradients", });
the_stack
import { JupyterFrontEnd } from '@jupyterlab/application'; import { ISessionContext, SessionContext, ToolbarButton } from '@jupyterlab/apputils'; import { ConsolePanel } from '@jupyterlab/console'; import { IChangedArgs } from '@jupyterlab/coreutils'; import { DocumentWidget } from '@jupyterlab/docregistry'; import { FileEditor } from '@jupyterlab/fileeditor'; import { NotebookPanel } from '@jupyterlab/notebook'; import { Kernel, Session } from '@jupyterlab/services'; import { bugIcon } from '@jupyterlab/ui-components'; import { DisposableSet } from '@lumino/disposable'; import { Debugger } from './debugger'; import { IDebugger } from './tokens'; import { ConsoleHandler } from './handlers/console'; import { FileHandler } from './handlers/file'; import { NotebookHandler } from './handlers/notebook'; /** * Add a button to the widget toolbar to enable and disable debugging. * * @param widget The widget to add the debug toolbar button to. * @param onClick The callback when the toolbar button is clicked. */ function updateToolbar( widget: DebuggerHandler.SessionWidget[DebuggerHandler.SessionType], onClick: () => void ): DisposableSet { const icon = new ToolbarButton({ className: 'jp-DebuggerBugButton', icon: bugIcon, tooltip: 'Enable / Disable Debugger', onClick }); widget.toolbar.addItem('debugger-icon', icon); const button = new ToolbarButton({ iconClass: 'jp-ToggleSwitch', tooltip: 'Enable / Disable Debugger', onClick }); widget.toolbar.addItem('debugger-button', button); const elements = new DisposableSet(); elements.add(icon); elements.add(button); return elements; } /** * A handler for debugging a widget. */ export class DebuggerHandler { /** * Instantiate a new DebuggerHandler. * * @param options The instantiation options for a DebuggerHandler. */ constructor(options: DebuggerHandler.IOptions) { this._type = options.type; this._shell = options.shell; this._service = options.service; } /** * Update a debug handler for the given widget, and * handle kernel changed events. * * @param widget The widget to update. * @param connection The session connection. */ async update( widget: DebuggerHandler.SessionWidget[DebuggerHandler.SessionType], connection: Session.ISessionConnection ): Promise<void> { if (!connection) { delete this._kernelChangedHandlers[widget.id]; delete this._statusChangedHandlers[widget.id]; return this._update(widget, connection); } const kernelChanged = (): void => { void this._update(widget, connection); }; const kernelChangedHandler = this._kernelChangedHandlers[widget.id]; if (kernelChangedHandler) { connection.kernelChanged.disconnect(kernelChangedHandler); } this._kernelChangedHandlers[widget.id] = kernelChanged; connection.kernelChanged.connect(kernelChanged); const statusChanged = ( _: Session.ISessionConnection, status: Kernel.Status ): void => { if (status.endsWith('restarting')) { void this._update(widget, connection); } }; const statusChangedHandler = this._statusChangedHandlers[widget.id]; if (statusChangedHandler) { connection.statusChanged.disconnect(statusChangedHandler); } connection.statusChanged.connect(statusChanged); this._statusChangedHandlers[widget.id] = statusChanged; return this._update(widget, connection); } /** * Update a debug handler for the given widget, and * handle connection kernel changed events. * * @param widget The widget to update. * @param sessionContext The session context. */ async updateContext( widget: DebuggerHandler.SessionWidget[DebuggerHandler.SessionType], sessionContext: ISessionContext ): Promise<void> { const connectionChanged = (): void => { const { session: connection } = sessionContext; void this.update(widget, connection); }; const contextKernelChangedHandlers = this._contextKernelChangedHandlers[ widget.id ]; if (contextKernelChangedHandlers) { sessionContext.kernelChanged.disconnect(contextKernelChangedHandlers); } this._contextKernelChangedHandlers[widget.id] = connectionChanged; sessionContext.kernelChanged.connect(connectionChanged); return this.update(widget, sessionContext.session); } /** * Update a debug handler for the given widget. * * @param widget The widget to update. * @param connection The session connection. */ private async _update( widget: DebuggerHandler.SessionWidget[DebuggerHandler.SessionType], connection: Session.ISessionConnection ): Promise<void> { if (!this._service.model) { return; } const hasFocus = (): boolean => { return this._shell.currentWidget && this._shell.currentWidget === widget; }; const updateAttribute = (): void => { if (!this._handlers[widget.id]) { widget.node.removeAttribute('data-jp-debugger'); return; } widget.node.setAttribute('data-jp-debugger', 'true'); }; const createHandler = (): void => { if (this._handlers[widget.id]) { return; } switch (this._type) { case 'notebook': this._handlers[widget.id] = new NotebookHandler({ debuggerService: this._service, widget: widget as NotebookPanel }); break; case 'console': this._handlers[widget.id] = new ConsoleHandler({ debuggerService: this._service, widget: widget as ConsolePanel }); break; case 'file': this._handlers[widget.id] = new FileHandler({ debuggerService: this._service, widget: widget as DocumentWidget<FileEditor> }); break; default: throw Error(`No handler for the type ${this._type}`); } updateAttribute(); }; const removeHandlers = (): void => { const handler = this._handlers[widget.id]; if (!handler) { return; } handler.dispose(); delete this._handlers[widget.id]; delete this._kernelChangedHandlers[widget.id]; delete this._statusChangedHandlers[widget.id]; delete this._contextKernelChangedHandlers[widget.id]; // Clear the model if the handler being removed corresponds // to the current active debug session, or if the connection // does not have a kernel. if ( this._service.session?.connection?.path === connection?.path || !this._service.session?.connection?.kernel ) { const model = this._service.model; model.clear(); } updateAttribute(); }; const addToolbarButton = (): void => { const button = this._buttons[widget.id]; if (button) { return; } const newButton = updateToolbar(widget, toggleDebugging); this._buttons[widget.id] = newButton; }; const removeToolbarButton = (): void => { const button = this._buttons[widget.id]; if (!button) { return; } button.dispose(); delete this._buttons[widget.id]; }; const toggleDebugging = async (): Promise<void> => { // bail if the widget doesn't have focus if (!hasFocus()) { return; } if ( this._service.isStarted && this._previousConnection.id === connection.id ) { this._service.session.connection = connection; await this._service.stop(); removeHandlers(); } else { this._service.session.connection = connection; this._previousConnection = connection; await this._service.restoreState(true); createHandler(); } }; const debuggingEnabled = await this._service.isAvailable(connection); if (!debuggingEnabled) { removeHandlers(); removeToolbarButton(); return; } // update the active debug session if (!this._service.session) { this._service.session = new Debugger.Session({ connection }); } else { this._previousConnection = this._service.session.connection.kernel ? this._service.session.connection : null; this._service.session.connection = connection; } addToolbarButton(); await this._service.restoreState(false); // check the state of the debug session if (!this._service.isStarted) { removeHandlers(); this._service.session.connection = this._previousConnection ?? connection; await this._service.restoreState(false); return; } // if the debugger is started but there is no handler, create a new one createHandler(); this._previousConnection = connection; // listen to the disposed signals widget.disposed.connect(removeHandlers); } private _type: DebuggerHandler.SessionType; private _shell: JupyterFrontEnd.IShell; private _service: IDebugger; private _previousConnection: Session.ISessionConnection; private _handlers: { [id: string]: DebuggerHandler.SessionHandler[DebuggerHandler.SessionType]; } = {}; private _contextKernelChangedHandlers: { [id: string]: ( sender: SessionContext, args: IChangedArgs< Kernel.IKernelConnection, Kernel.IKernelConnection, 'kernel' > ) => void; } = {}; private _kernelChangedHandlers: { [id: string]: ( sender: Session.ISessionConnection, args: IChangedArgs< Kernel.IKernelConnection, Kernel.IKernelConnection, 'kernel' > ) => void; } = {}; private _statusChangedHandlers: { [id: string]: ( sender: Session.ISessionConnection, status: Kernel.Status ) => void; } = {}; private _buttons: { [id: string]: DisposableSet } = {}; } /** * A namespace for DebuggerHandler `statics` */ export namespace DebuggerHandler { /** * Instantiation options for a DebuggerHandler. */ export interface IOptions { /** * The type of session. */ type: SessionType; /** * The application shell. */ shell: JupyterFrontEnd.IShell; /** * The debugger service. */ service: IDebugger; } /** * The types of sessions that can be debugged. */ export type SessionType = keyof SessionHandler; /** * The types of handlers. */ export type SessionHandler = { notebook: NotebookHandler; console: ConsoleHandler; file: FileHandler; }; /** * The types of widgets that can be debugged. */ export type SessionWidget = { notebook: NotebookPanel; console: ConsolePanel; file: DocumentWidget; }; }
the_stack
import EmberObject, { computed } from '@ember/object'; import { A } from '@ember/array'; import Service from '@ember/service'; import { task, Task } from '../-private/ember-scheduler'; import { microwait, rAF, afterRender, allSettled } from '..'; import Sprite from '../-private/sprite'; import ComputedProperty from '@ember/object/computed'; import Child from '../-private/child'; import { Transition } from '../-private/transition'; interface Animator extends EmberObject { beginStaticMeasurement(): void; endStaticMeasurement(): void; isAnimating: boolean; } export type OrphanObserver = ( removed: Sprite[], transition: Transition, duration: number, shouldAnimateRemoved: boolean, ) => void; type AnimationObserver = (args: { task: Promise<void>; duration: number; }) => void; type AncestorObserver = (state: Child['state']) => void; interface BaseComponentLike extends EmberObject { parentView: ComponentLike | undefined; } interface AnimatedListElement extends BaseComponentLike { isEmberAnimatedListElement: true; child: Child; } type ComponentLike = BaseComponentLike | AnimatedListElement; interface Measurement { fn: () => void; resolved: boolean; value: any; } interface Rendezvous { inserted: Sprite[]; kept: Sprite[]; removed: Sprite[]; matches: Map<Sprite, Sprite>; runAnimationTask: Promise<void>; otherTasks: Map<Promise<void>, true>; } export default class MotionService extends Service { _rendezvous: Rendezvous[] = []; _measurements: Measurement[] = []; _animators = A<Animator>(); _orphanObserver: OrphanObserver | null = null; _animationObservers: AnimationObserver[] = []; _descendantObservers: { component: ComponentLike; fn: AnimationObserver; }[] = []; _ancestorObservers: WeakMap< ComponentLike, Map<AncestorObserver, string> > = new WeakMap(); _beacons: { [name: string]: Sprite } | null = null; // === Notification System === // Ever animator should register and unregister itself so we know // when there are any animations running. Animators are required to // have: // - an isAnimating property // - beginStaticMeasurement and endStaticMeasurement methods register(animator: Animator) { this._animators.pushObject(animator); return this; } unregister(animator: Animator) { this._animators.removeObject(animator); return this; } // Register to receive any sprites that are orphaned by a destroyed // animator. observeOrphans(fn: OrphanObserver) { if (this._orphanObserver) { throw new Error( 'Only one animated-orphans component can be used at one time', ); } this._orphanObserver = fn; return this; } unobserveOrphans(fn: OrphanObserver) { if (this._orphanObserver === fn) { this._orphanObserver = null; } return this; } // Register to know when an animation is starting anywhere in the app. observeAnimations(fn: AnimationObserver) { this._animationObservers.push(fn); return this; } unobserveAnimations(fn: AnimationObserver) { let index = this._animationObservers.indexOf(fn); if (index !== -1) { this._animationObservers.splice(index, 1); } return this; } // Register to know when an animation is starting within the // descendants of the given component observeDescendantAnimations(component: ComponentLike, fn: AnimationObserver) { this._descendantObservers.push({ component, fn }); return this; } unobserveDescendantAnimations( component: ComponentLike, fn: AnimationObserver, ) { let entry = this._descendantObservers.find( e => e.component === component && e.fn === fn, ); if (entry) { this._descendantObservers.splice( this._descendantObservers.indexOf(entry), 1, ); } return this; } // Register to know when an animation is starting among the // ancestors of the given component. The fn will be told whether // component is going to be destroyed or not at the end of the // animation. observeAncestorAnimations(component: ComponentLike, fn: AncestorObserver) { let id; for (let ancestorComponent of ancestorsOf(component)) { // when we find an animated list element, we save its ID if ('isEmberAnimatedListElement' in ancestorComponent) { id = ancestorComponent.child.id; } else if (id != null) { // if we found an ID on the last loop, now we've got the list // element's parent which is the actual animator. let observers = this._ancestorObservers.get(ancestorComponent); if (!observers) { this._ancestorObservers.set( ancestorComponent, (observers = new Map()), ); } observers.set(fn, id); id = null; } } return this; } unobserveAncestorAnimations(component: ComponentLike, fn: AncestorObserver) { for (let ancestorComponent of ancestorsOf(component)) { let observers = this._ancestorObservers.get(ancestorComponent); if (observers) { observers.delete(fn); } } return this; } // This is a publicly visible property you can use to know if any animations // are running. It's timing is deliberately not synchronous, so that you can // bind it into a template without getting double-render errors. // // We have an un-observed dependency on an internal property *on purpose*, so // this lint rule needs to be disabled: // // eslint-disable-next-line ember/require-computed-property-dependencies @computed() get isAnimating() { return this.get('isAnimatingSync'); } // Synchronously updated version of isAnimating. If you try to // depend on this in a template you will get double-render errors // (because the act of rendering can cause animations to begin). @computed('_animators.@each.isAnimating') get isAnimatingSync() { return this.get('_animators').any(animator => animator.get('isAnimating')); } // Invalidation support for isAnimating @(task(function*(this: MotionService) { yield rAF(); this.notifyPropertyChange('isAnimating'); }).observes('isAnimatingSync')) _invalidateIsAnimating!: ComputedProperty<Task>; @task(function*(this: MotionService) { // we are idle if we experience two frames in a row with nothing // animating. while (true) { yield rAF(); if (!this.get('isAnimatingSync')) { yield rAF(); if (!this.get('isAnimatingSync')) { return; } } } }) waitUntilIdle!: ComputedProperty<Task>; matchDestroyed( removed: Sprite[], transition: Transition, duration: number, shouldAnimateRemoved: boolean, ) { if (this._orphanObserver && removed.length > 0) { // if these orphaned sprites may be capable of animating, // delegate them to the orphanObserver. It will do farMatching // for them. this._orphanObserver(removed, transition, duration, shouldAnimateRemoved); } else { // otherwise, we make them available for far matching but they // can't be animated. this.get('farMatch').perform(null, [], [], removed, true); } } @task(function*(this: MotionService, name: string, beacon: Sprite) { if (!this._beacons) { this._beacons = {}; } if (this._beacons[name]) { throw new Error(`There is more than one beacon named "${name}"`); } this._beacons[name] = beacon; // allows other farMatches to start yield microwait(); // allows other farMatches to finish yield microwait(); this._beacons = null; }) addBeacon!: ComputedProperty<Task>; @task(function*( this: MotionService, runAnimationTask: Promise<void>, inserted: Sprite[], kept: Sprite[], removed: Sprite[], longWait = false, ) { let matches = new Map() as Map<Sprite, Sprite>; let mine = { inserted, kept, removed, matches, runAnimationTask, otherTasks: new Map(), }; this._rendezvous.push(mine); yield microwait(); if (longWait) { // used by matchDestroyed because it gets called earlier in the // render cycle, so it needs to linger longer in order to // coincide with other farMatches. yield afterRender(); yield microwait(); yield microwait(); } if (this.get('farMatch').concurrency > 1) { this._rendezvous.forEach(target => { if (target === mine) { return; } performMatches(mine, target); performMatches(target, mine); }); } this._rendezvous.splice(this._rendezvous.indexOf(mine), 1); return { farMatches: matches, matchingAnimatorsFinished: allSettled([...mine.otherTasks.keys()]), beacons: this._beacons, }; }) farMatch!: ComputedProperty<Task>; willAnimate({ task, duration, component, children, }: { task: Promise<void>; duration: number; component: ComponentLike; children: Child[]; }) { let message = { task, duration }; // tell any of our ancestors who are observing their descendants let ancestors = [...ancestorsOf(component)]; for (let { component: observingComponent, fn } of this ._descendantObservers) { if (ancestors.indexOf(observingComponent) !== -1) { fn(message); } } // tell any of our descendants who are observing their ancestors let observers = this._ancestorObservers.get(component); if (observers) { for (let [fn, id] of observers.entries()) { let child = children.find(child => child.id === id); if (child) { fn(child.state); } // the else case here applies to descendants that are about // to be unrendered (not animated away -- immediately // dropped). They will still have an opportunity to animate // too, but they do it via their own willDestroyElement // hook, not the this early-warning hook. } } // tell anybody who is listening for all animations for (let fn of this._animationObservers) { fn(message); } } *staticMeasurement(fn: Measurement['fn']) { let measurement: Measurement = { fn, resolved: false, value: null }; this._measurements.push(measurement); try { // allow all concurrent animators to join in with our single // measurement step instead of having each trigger its own reflow. yield microwait(); if (!measurement.resolved) { // we are the first concurrent task to wake up, so we do the // actual resolution for everyone. let animators = this.get('_animators'); animators.forEach(animator => animator.beginStaticMeasurement()); this._measurements.forEach(m => { try { m.value = m.fn(); } catch (err) { setTimeout(function() { throw err; }, 0); } m.resolved = true; }); animators.forEach(animator => animator.endStaticMeasurement()); } return measurement.value; } finally { this._measurements.splice(this._measurements.indexOf(measurement), 1); } } } function performMatches(sink: Rendezvous, source: Rendezvous) { sink.inserted.concat(sink.kept).forEach(sprite => { let match = source.removed.find( // TODO: an OwnedSprite type could eliminate the need for these // non-nullable casts. mySprite => sprite.owner!.group == mySprite.owner!.group && sprite.owner!.id === mySprite.owner!.id, ); if (match) { sink.matches.set(sprite, match); sink.otherTasks.set(source.runAnimationTask, true); source.matches.set(match, sprite); source.otherTasks.set(sink.runAnimationTask, true); } }); } function* ancestorsOf(component: ComponentLike) { let pointer = component.parentView; while (pointer) { yield pointer; pointer = pointer.parentView; } } declare module '@ember/service' { interface Registry { '-ea-motion': MotionService; } }
the_stack
* @module Workspace */ import { createHash } from "crypto"; import * as fs from "fs-extra"; import { dirname, extname, join } from "path"; import { CloudSqlite, IModelJsNative, NativeLibrary } from "@bentley/imodeljs-native"; import { BeEvent, DbResult, OpenMode, Optional } from "@itwin/core-bentley"; import { IModelError, LocalDirName, LocalFileName } from "@itwin/core-common"; import { IModelJsFs } from "../IModelJsFs"; import { SQLiteDb } from "../SQLiteDb"; import { SqliteStatement } from "../SqliteStatement"; import { Settings, SettingsPriority } from "./Settings"; // cspell:ignore rowid /** The names of Settings used by Workspace * @beta */ enum WorkspaceSetting { ContainerAlias = "workspace/container/alias", } const workspaceDbFileExt = "itwin-workspace"; /** * The name of a WorkspaceContainer. This is the user-supplied name of a WorkspaceContainer, used to specify its *purpose* within a workspace. * WorkspaceContainerName can be "aliased" by `WorkspaceSetting.containerAlias` settings so that "resolved" [[WorkspaceContainerId]] that supplies * the actual WorkspaceContainer for a WorkspaceContainerName may vary. Also note that more than one WorkspaceContainerName may resolve to the same * WorkspaceContainerId, if multiple purposes are served by the same WorkspaceContainer. * @note there are no constraints on the contents or length of `WorkspaceContainerName`s, although short descriptive names are recommended. * However, when no alias exists in WorkspaceSetting.containerAlias for a WorkspaceContainerName, then the WorkspaceContainerName becomes * the WorkspaceContainerId, and the constraints on WorkspaceContainerId apply. * @beta */ export type WorkspaceContainerName = string; /** * The unique identifier of a WorkspaceContainer. This becomes the base name for the local directory holding the WorkspaceDbs from a WorkspaceContainer. * `WorkspaceContainerName`s are resolved to WorkspaceContainerId through `WorkspaceSetting.containerAlias` settings, * so users may not recognize the actual WorkspaceContainerId supplying resources for a WorkspaceDbName. * * `WorkspaceContainerId`s : * - may only contain lower case letters, numbers or dashes * - may not start or end with with a dash * - be shorter than 3 or longer than 63 characters * @beta */ export type WorkspaceContainerId = string; /** The name of a WorkspaceDb within a WorkspaceContainer. * @beta */ export type WorkspaceDbName = string; /** * The version name for a WorkspaceDb. More than one version of a WorkspaceDb may be stored in the same WorkspaceContainer. This * string identifies a specific version. * @beta */ export type WorkspaceDbVersion = string; /** * The name for identifying WorkspaceResources in a [[WorkspaceDb]]. * * `WorkspaceResourceName`s may not: * - be blank or start or end with a space * - be longer than 1024 characters * @note a single WorkspaceDb may hold WorkspaceResources of type 'blob', 'string' and 'file', all with the same WorkspaceResourceName. * @beta */ export type WorkspaceResourceName = string; /** supply either container name of id, not both * @beta */ export type ContainerNameOrId = { containerName: WorkspaceContainerName, containerId?: never } | { containerId: WorkspaceContainerId, containerName?: never }; /** * Properties that specify a WorkspaceContainer. * This can either be a WorkspaceContainerName or a WorkspaceContainerId. If id is supplied, * it is used directly. Otherwise name must be resolved via [[Workspace.resolveContainerId]]. * @beta */ export type WorkspaceContainerProps = ContainerNameOrId & { cloudProps?: CloudSqlite.TransferProps; }; /** Properties of a WorkspaceDb * @beta */ export type WorkspaceDbProps = WorkspaceContainerProps & { /** the name of the WorkspaceDb */ dbName: WorkspaceDbName; }; /** Properties that specify a WorkspaceResource within a WorkspaceDb. * @beta */ export type WorkspaceResourceProps = WorkspaceDbProps & { /** the name of the resource within [[db]] */ rscName: WorkspaceResourceName; }; /** * A WorkspaceDb holds workspace resources. `WorkspaceDb`s may just be local files, or they may be stored and * synchronized in WorkspaceContainers. Each `WorkspaceResource` in a WorkspaceDb is identified by a [[WorkspaceResourceName]]. * Resources of type `string` and `blob` may be loaded directly from the `WorkspaceDb`. Resources of type `file` are * copied from the WorkspaceDb into a temporary local file so they can be accessed directly. * @beta */ export interface WorkspaceDb { readonly container: WorkspaceContainer; /** The WorkspaceDbName of this WorkspaceDb. */ readonly dbName: WorkspaceDbName; /** event raised when this WorkspaceDb is closed. */ readonly onClosed: BeEvent<() => void>; /** The name of the local file for holding this WorkspaceDb. */ readonly localFile: LocalDirName; /** Get a string resource from this WorkspaceDb, if present. */ getString(rscName: WorkspaceResourceName): string | undefined; /** Get a blob resource from this WorkspaceDb, if present. */ getBlob(rscName: WorkspaceResourceName): Uint8Array | undefined; /** @internal */ getBlobReader(rscName: WorkspaceResourceName): IModelJsNative.BlobIO; /** Extract a local copy of a file resource from this WorkspaceDb, if present. * @param rscName The name of the file resource in the WorkspaceDb * @param targetFileName optional name for extracted file. Some applications require files in specific locations or filenames. If * you know the full path to use for the extracted file, you can supply it. Generally, it is best to *not* supply the filename and * keep the extracted files in the container filesDir. * @returns the full path to a file on the local filesystem. * @note The file is copied from the file into the local filesystem so it may be accessed directly. This happens only * as necessary, if the local file doesn't exist, or if it is out-of-date because it was updated in the file. * For this reason, you should not save the local file name, and instead call this method every time you access it, so its * content is always holds the correct version. * @note The filename will be a hash value, not the resource name. * @note Workspace resource files are set readonly as they are copied from the file. * To edit them, you must first copy them to another location. */ getFile(rscName: WorkspaceResourceName, targetFileName?: LocalFileName): LocalFileName | undefined; } /** * Options for constructing a [[Workspace]]. * @beta */ export interface WorkspaceOpts { /** The local directory for the WorkspaceDb files. The [[Workspace]] will (only) look in this directory * for files named `${this.containerId}/${this.dbId}.itwin-workspace`. * @note if not supplied, defaults to `iTwin/Workspace` in the user-local folder. */ containerDir?: LocalDirName; } /** * Settings and resources that customize an application for the current session. * See [Workspaces]($docs/learning/backend/Workspace) * @beta */ export interface Workspace { /** The local directory for the WorkspaceDb files with the name `${containerId}.itwin-workspace`. */ readonly containerDir: LocalDirName; /** The [[Settings]] for this Workspace */ readonly settings: Settings; getContainer(props: WorkspaceContainerProps): WorkspaceContainer; /** * Resolve a WorkspaceContainerProps to a WorkspaceContainerId. If props is an object with an `id` member, that value is returned unchanged. * If it is a string, then the highest priority [[WorkspaceSetting.containerAlias]] setting with an entry for the WorkspaceContainerName * is used. If no WorkspaceSetting.containerAlias entry for the WorkspaceContainerName can be found, the name is returned as the id. */ resolveContainerId(props: WorkspaceContainerProps): WorkspaceContainerId; /** * Get an open [[WorkspaceDb]]. If the WorkspaceDb is present but not open, it is opened first. * If `cloudProps` are supplied, and if container is not present or not up-to-date, it is downloaded first. * @returns a Promise that is resolved when the container is local, opened, and available for access. */ getWorkspaceDb(props: WorkspaceDbProps): Promise<WorkspaceDb>; /** Load a WorkspaceResource of type string, parse it, and add it to the current Settings for this Workspace. * @note settingsRsc must specify a resource holding a stringified JSON representation of a [[SettingDictionary]] * @returns a Promise that is resolved when the settings resource has been loaded. */ loadSettingsDictionary(settingRsc: WorkspaceResourceProps, priority: SettingsPriority): Promise<void>; /** Close this Workspace. All WorkspaceContainers are dropped. */ close(): void; } /** A WorkspaceContainer holds WorkspaceDbs. * @beta */ export interface WorkspaceContainer { readonly dirName: LocalDirName; /** the local directory where this WorkspaceContainer will store temporary files extracted for file-resources. */ readonly filesDir: LocalDirName; readonly id: WorkspaceContainerId; readonly workspace: Workspace; /** @internal */ addWorkspaceDb(toAdd: ITwinWorkspaceDb): void; getWorkspaceDb(props: Optional<WorkspaceDbProps, "containerName">): Promise<WorkspaceDb>; /** Close and remove a currently opened [[WorkspaceDb]] from this Workspace. */ dropWorkspaceDb(container: WorkspaceDb): void; /** Close this WorkspaceContainer. All currently opened WorkspaceDbs are dropped. */ close(): void; } /** @internal */ export class ITwinWorkspace implements Workspace { private _containers = new Map<WorkspaceContainerId, ITwinWorkspaceContainer>(); public readonly containerDir: LocalDirName; public readonly settings: Settings; public constructor(settings: Settings, opts?: WorkspaceOpts) { this.settings = settings; this.containerDir = opts?.containerDir ?? join(NativeLibrary.defaultLocalDir, "iTwin", "Workspace"); } public addContainer(toAdd: ITwinWorkspaceContainer) { if (undefined !== this._containers.get(toAdd.id)) throw new Error("container already exists in workspace"); this._containers.set(toAdd.id, toAdd); } public getContainer(props: WorkspaceContainerProps): WorkspaceContainer { const id = this.resolveContainerId(props); if (undefined === id) throw new Error(`can't resolve workspace container name [${props.containerName}]`); return this._containers.get(id) ?? new ITwinWorkspaceContainer(this, id); } public async getWorkspaceDb(props: WorkspaceDbProps): Promise<WorkspaceDb> { return this.getContainer(props).getWorkspaceDb(props); } public async loadSettingsDictionary(settingRsc: WorkspaceResourceProps, priority: SettingsPriority) { const db = await this.getWorkspaceDb(settingRsc); const setting = db.getString(settingRsc.rscName); if (undefined === setting) throw new Error(`could not load setting resource ${settingRsc.rscName}`); this.settings.addJson(`${db.container.id}/${db.dbName}/${settingRsc.rscName}`, priority, setting); } public close() { this.settings.close(); for (const [_id, container] of this._containers) container.close(); this._containers.clear(); } public resolveContainerId(props: WorkspaceContainerProps): WorkspaceContainerId { if (props.containerId) return props.containerId; // if the container id is supplied, just use it const id = this.settings.resolveSetting(WorkspaceSetting.ContainerAlias, (val) => { if (Array.isArray(val)) { for (const entry of val) { if (typeof entry === "object" && entry.name === props.containerName && typeof entry.id === "string") return entry.id; } } return undefined; // keep going through all settings dictionaries }, props.containerName); if (undefined === id) throw new Error("Unable to resolve container id."); return id; } } /** @internal */ export class ITwinWorkspaceContainer implements WorkspaceContainer { public readonly workspace: ITwinWorkspace; public readonly filesDir: LocalDirName; public readonly id: WorkspaceContainerId; private _wsDbs = new Map<WorkspaceDbName, ITwinWorkspaceDb>(); public get dirName() { return join(this.workspace.containerDir, this.id); } /** rules for ContainerIds (from Azure, see https://docs.microsoft.com/en-us/rest/api/storageservices/naming-and-referencing-containers--blobs--and-metadata) * - may only contain lower case letters, numbers or dashes * - may not start or end with with a dash nor have more than one dash in a row * - may not be shorter than 3 or longer than 63 characters */ private static validateContainerId(id: WorkspaceContainerId) { if (!/^(?=.{3,63}$)[a-z0-9]+(-[a-z0-9]+)*$/g.test(id)) throw new Error(`invalid containerId: [${id}]`); } public constructor(workspace: ITwinWorkspace, id: WorkspaceContainerId) { ITwinWorkspaceContainer.validateContainerId(id); this.workspace = workspace; this.id = id; workspace.addContainer(this); this.filesDir = join(this.dirName, "Files"); } public addWorkspaceDb(toAdd: ITwinWorkspaceDb) { if (undefined !== this._wsDbs.get(toAdd.dbName)) throw new Error("dbName already exists in workspace"); this._wsDbs.set(toAdd.dbName, toAdd); } public async getWorkspaceDb(props: Optional<WorkspaceDbProps, "containerName">): Promise<WorkspaceDb> { const db = this._wsDbs.get(props.dbName) ?? new ITwinWorkspaceDb(props.dbName, this); if (!db.isOpen) { if (props.cloudProps) await CloudSqlite.downloadDb({ ...db, ...props.cloudProps, containerId: this.id }); db.open(); } return db; } public dropWorkspaceDb(toDrop: WorkspaceDb): void { const name = toDrop.dbName; const wsDb = this._wsDbs.get(name); if (wsDb === toDrop) { wsDb.close(); this._wsDbs.delete(name); } } public close() { for (const [_name, db] of this._wsDbs) db.close(); this._wsDbs.clear(); } public purgeContainerFiles() { IModelJsFs.purgeDirSync(this.filesDir); } } /** * A local file holding a WorkspaceDb. * @beta */ export class ITwinWorkspaceDb implements WorkspaceDb { public readonly sqliteDb = new SQLiteDb(); // eslint-disable-line @typescript-eslint/naming-convention public readonly dbName: WorkspaceDbName; public readonly container: WorkspaceContainer; public localFile: LocalFileName; public readonly onClosed = new BeEvent<() => void>(); protected static noLeadingOrTrailingSpaces(name: string, msg: string) { if (name.trim() !== name) throw new Error(`${msg} [${name}] may not have leading or tailing spaces`); } private static validateDbName(dbName: WorkspaceDbName) { if (dbName === "" || dbName.length > 255 || /[#\.<>:"/\\"`'|?*\u0000-\u001F]/g.test(dbName) || /^(con|prn|aux|nul|com\d|lpt\d)$/i.test(dbName)) throw new Error(`invalid dbName: [${dbName}]`); this.noLeadingOrTrailingSpaces(dbName, "dbName"); } public get isOpen() { return this.sqliteDb.isOpen; } public queryFileResource(rscName: WorkspaceResourceName) { const info = this.sqliteDb.nativeDb.queryEmbeddedFile(rscName); if (undefined === info) return undefined; // since resource names can contain illegal characters, path separators, etc., we make the local file name from its hash, in hex. let localFileName = join(this.container.filesDir, createHash("sha1").update(rscName).digest("hex")); if (info.fileExt !== "") // since some applications may expect to see the extension, append it here if it was supplied. localFileName = `${localFileName}.${info.fileExt}`; return { localFileName, info }; } public constructor(dbName: WorkspaceDbName, container: WorkspaceContainer) { ITwinWorkspaceDb.validateDbName(dbName); this.dbName = dbName; this.container = container; this.localFile = join(container.dirName, `${dbName}.${workspaceDbFileExt}`); container.addWorkspaceDb(this); } public open(): void { this.sqliteDb.openDb(this.localFile, OpenMode.Readonly); } public close(): void { if (this.isOpen) { this.onClosed.raiseEvent(); this.sqliteDb.closeDb(); this.container.dropWorkspaceDb(this); } } public getString(rscName: WorkspaceResourceName): string | undefined { return this.sqliteDb.withSqliteStatement("SELECT value from strings WHERE id=?", (stmt) => { stmt.bindString(1, rscName); return DbResult.BE_SQLITE_ROW === stmt.step() ? stmt.getValueString(0) : undefined; }); } /** Get a BlobIO reader for a blob WorkspaceResource. * @note when finished, caller must call `close` on the BlobIO. */ public getBlobReader(rscName: WorkspaceResourceName): IModelJsNative.BlobIO { return this.sqliteDb.withSqliteStatement("SELECT rowid from blobs WHERE id=?", (stmt) => { stmt.bindString(1, rscName); const blobReader = new IModelJsNative.BlobIO(); blobReader.open(this.sqliteDb.nativeDb, { tableName: "blobs", columnName: "value", row: stmt.getValueInteger(0) }); return blobReader; }); } public getBlob(rscName: WorkspaceResourceName): Uint8Array | undefined { return this.sqliteDb.withSqliteStatement("SELECT value from blobs WHERE id=?", (stmt) => { stmt.bindString(1, rscName); return DbResult.BE_SQLITE_ROW === stmt.step() ? stmt.getValueBlob(0) : undefined; }); } public getFile(rscName: WorkspaceResourceName, targetFileName?: LocalFileName): LocalFileName | undefined { const file = this.queryFileResource(rscName); if (!file) return undefined; const info = file.info; const localFileName = targetFileName ?? file.localFileName; // check whether the file is already up to date. const stat = fs.existsSync(localFileName) && fs.statSync(localFileName); if (stat && Math.round(stat.mtimeMs) === info.date && stat.size === info.size) return localFileName; // yes, we're done // extractEmbeddedFile fails if the file exists or if the directory does not exist if (stat) fs.removeSync(localFileName); else IModelJsFs.recursiveMkDirSync(dirname(localFileName)); this.sqliteDb.nativeDb.extractEmbeddedFile({ name: rscName, localFileName }); const date = new Date(info.date); fs.utimesSync(localFileName, date, date); // set the last-modified date of the file to match date in container fs.chmodSync(localFileName, "0444"); // set file readonly return localFileName; } } /** * An editable [[WorkspaceDb]]. This is used by administrators for creating and modifying `WorkspaceDb`s. * For cloud-backed containers, the write token must be obtained before this class may be used. Only one user at at time * may be editing. * @beta */ export class EditableWorkspaceDb extends ITwinWorkspaceDb { private _isCloudOpen = false; private static validateResourceName(name: WorkspaceResourceName) { ITwinWorkspaceDb.noLeadingOrTrailingSpaces(name, "resource name"); if (name.length > 1024) throw new Error("resource name too long"); } private validateResourceSize(val: Uint8Array | string) { const len = typeof val === "string" ? val.length : val.byteLength; if (len > (1024 * 1024 * 1024)) // one gigabyte throw new Error("value is too large"); } public override open() { this.sqliteDb.openDb(this.localFile, OpenMode.ReadWrite); } public override close() { if (this._isCloudOpen) { // this.db.nativeDb.flushCloudUpload(); TODO: add back when available this._isCloudOpen = false; } super.close(); } private getFileModifiedTime(localFileName: LocalFileName): number { return Math.round(fs.statSync(localFileName).mtimeMs); } private performWriteSql(rscName: WorkspaceResourceName, sql: string, bind?: (stmt: SqliteStatement) => void) { this.sqliteDb.withSqliteStatement(sql, (stmt) => { stmt.bindString(1, rscName); bind?.(stmt); const rc = stmt.step(); if (DbResult.BE_SQLITE_DONE !== rc) throw new IModelError(rc, "workspace write error"); }); this.sqliteDb.saveChanges(); } /** Create a new, empty, EditableWorkspaceDb for importing Workspace resources. */ public create() { IModelJsFs.recursiveMkDirSync(dirname(this.localFile)); this.sqliteDb.createDb(this.localFile); this.sqliteDb.executeSQL("CREATE TABLE strings(id TEXT PRIMARY KEY NOT NULL,value TEXT)"); this.sqliteDb.executeSQL("CREATE TABLE blobs(id TEXT PRIMARY KEY NOT NULL,value BLOB)"); this.sqliteDb.saveChanges(); } public static async cloneVersion(oldVersion: WorkspaceDbVersion, newVersion: WorkspaceDbVersion, cloudProps: CloudSqlite.ContainerAccessProps) { return CloudSqlite.copyDb(oldVersion, newVersion, cloudProps); } public async upload(cloudProps: CloudSqlite.TransferProps) { return CloudSqlite.uploadDb({ ...cloudProps, ...this }); } /** Add a new string resource to this WorkspaceDb. * @param rscName The name of the string resource. * @param val The string to save. */ public addString(rscName: WorkspaceResourceName, val: string): void { EditableWorkspaceDb.validateResourceName(rscName); this.validateResourceSize(val); this.performWriteSql(rscName, "INSERT INTO strings(id,value) VALUES(?,?)", (stmt) => stmt.bindString(2, val)); } /** Update an existing string resource with a new value. * @param rscName The name of the string resource. * @param val The new value. * @throws if rscName does not exist */ public updateString(rscName: WorkspaceResourceName, val: string): void { this.validateResourceSize(val); this.performWriteSql(rscName, "UPDATE strings SET value=?2 WHERE id=?1", (stmt) => stmt.bindString(2, val)); } /** Remove a string resource. */ public removeString(rscName: WorkspaceResourceName): void { this.performWriteSql(rscName, "DELETE FROM strings WHERE id=?"); } /** Add a new blob resource to this WorkspaceDb. * @param rscName The name of the blob resource. * @param val The blob to save. */ public addBlob(rscName: WorkspaceResourceName, val: Uint8Array): void { EditableWorkspaceDb.validateResourceName(rscName); this.validateResourceSize(val); this.performWriteSql(rscName, "INSERT INTO blobs(id,value) VALUES(?,?)", (stmt) => stmt.bindBlob(2, val)); } /** Update an existing blob resource with a new value. * @param rscName The name of the blob resource. * @param val The new value. * @throws if rscName does not exist */ public updateBlob(rscName: WorkspaceResourceName, val: Uint8Array): void { this.validateResourceSize(val); this.performWriteSql(rscName, "UPDATE blobs SET value=?2 WHERE id=?1", (stmt) => stmt.bindBlob(2, val)); } /** Get a BlobIO writer for a previously-added blob WorkspaceResource. * @note after writing is complete, caller must call `close` on the BlobIO and must call `saveChanges` on the `db`. */ public getBlobWriter(rscName: WorkspaceResourceName): IModelJsNative.BlobIO { return this.sqliteDb.withSqliteStatement("SELECT rowid from blobs WHERE id=?", (stmt) => { stmt.bindString(1, rscName); const blobWriter = new IModelJsNative.BlobIO(); blobWriter.open(this.sqliteDb.nativeDb, { tableName: "blobs", columnName: "value", row: stmt.getValueInteger(0), writeable: true }); return blobWriter; }); } /** Remove a blob resource. */ public removeBlob(rscName: WorkspaceResourceName): void { this.performWriteSql(rscName, "DELETE FROM blobs WHERE id=?"); } /** Copy the contents of an existing local file into this WorkspaceDb as a file resource. * @param rscName The name of the file resource. * @param localFileName The name of a local file to be read. * @param fileExt The extension (do not include the leading ".") to be appended to the generated fileName * when this WorkspaceDb is extracted from the WorkspaceDb. By default the characters after the last "." in `localFileName` * are used. Pass this argument to override that. */ public addFile(rscName: WorkspaceResourceName, localFileName: LocalFileName, fileExt?: string): void { EditableWorkspaceDb.validateResourceName(rscName); fileExt = fileExt ?? extname(localFileName); if (fileExt?.[0] === ".") fileExt = fileExt.slice(1); this.sqliteDb.nativeDb.embedFile({ name: rscName, localFileName, date: this.getFileModifiedTime(localFileName), fileExt }); } /** Replace an existing file resource with the contents of a local file. * @param rscName The name of the file resource. * @param localFileName The name of a local file to be read. * @throws if rscName does not exist */ public updateFile(rscName: WorkspaceResourceName, localFileName: LocalFileName): void { this.queryFileResource(rscName); // throws if not present this.sqliteDb.nativeDb.replaceEmbeddedFile({ name: rscName, localFileName, date: this.getFileModifiedTime(localFileName) }); } /** Remove a file resource. */ public removeFile(rscName: WorkspaceResourceName): void { const file = this.queryFileResource(rscName); if (undefined === file) throw new Error(`file resource "${rscName}" does not exist`); if (file && fs.existsSync(file.localFileName)) fs.unlinkSync(file.localFileName); this.sqliteDb.nativeDb.removeEmbeddedFile(rscName); } }
the_stack
import {expect} from 'chai'; import * as Rx from '../../dist/cjs/Rx'; import marbleTestingSignature = require('../helpers/marble-testing'); // tslint:disable-line:no-require-imports declare const { asDiagram }; declare const hot: typeof marbleTestingSignature.hot; declare const cold: typeof marbleTestingSignature.cold; declare const expectObservable: typeof marbleTestingSignature.expectObservable; declare const expectSubscriptions: typeof marbleTestingSignature.expectSubscriptions; const Observable = Rx.Observable; const queueScheduler = Rx.Scheduler.queue; /** @test {switch} */ describe('Observable.prototype.switch', () => { asDiagram('switch')('should switch a hot observable of cold observables', () => { const x = cold( '--a---b--c---d--| '); const y = cold( '----e---f--g---|'); const e1 = hot( '--x------y-------| ', { x: x, y: y }); const expected = '----a---b----e---f--g---|'; expectObservable(e1.switch()).toBe(expected); }); it('should switch to each immediately-scheduled inner Observable', (done: MochaDone) => { const a = Observable.of<number>(1, 2, 3, queueScheduler); const b = Observable.of<number>(4, 5, 6, queueScheduler); const r = [1, 4, 5, 6]; let i = 0; Observable.of<Rx.Observable<number>>(a, b, queueScheduler) .switch() .subscribe((x: number) => { expect(x).to.equal(r[i++]); }, null, done); }); it('should unsub inner observables', () => { const unsubbed = []; Observable.of('a', 'b').map((x: string) => Observable.create((subscriber: Rx.Subscriber<string>) => { subscriber.complete(); return () => { unsubbed.push(x); }; })) .switch() .subscribe(); expect(unsubbed).to.deep.equal(['a', 'b']); }); it('should switch to each inner Observable', (done: MochaDone) => { const a = Observable.of(1, 2, 3); const b = Observable.of(4, 5, 6); const r = [1, 2, 3, 4, 5, 6]; let i = 0; Observable.of(a, b).switch().subscribe((x: number) => { expect(x).to.equal(r[i++]); }, null, done); }); it('should handle a hot observable of observables', () => { const x = cold( '--a---b---c--| '); const xsubs = ' ^ ! '; const y = cold( '---d--e---f---|'); const ysubs = ' ^ !'; const e1 = hot( '------x-------y------| ', { x: x, y: y }); const expected = '--------a---b----d--e---f---|'; expectObservable(e1.switch()).toBe(expected); expectSubscriptions(x.subscriptions).toBe(xsubs); expectSubscriptions(y.subscriptions).toBe(ysubs); }); it('should handle a hot observable of observables, outer is unsubscribed early', () => { const x = cold( '--a---b---c--| '); const xsubs = ' ^ ! '; const y = cold( '---d--e---f---|'); const ysubs = ' ^ ! '; const e1 = hot( '------x-------y------| ', { x: x, y: y }); const unsub = ' ! '; const expected = '--------a---b--- '; expectObservable(e1.switch(), unsub).toBe(expected); expectSubscriptions(x.subscriptions).toBe(xsubs); expectSubscriptions(y.subscriptions).toBe(ysubs); }); it('should not break unsubscription chains when result is unsubscribed explicitly', () => { const x = cold( '--a---b---c--| '); const xsubs = ' ^ ! '; const y = cold( '---d--e---f---|'); const ysubs = ' ^ ! '; const e1 = hot( '------x-------y------| ', { x: x, y: y }); const expected = '--------a---b---- '; const unsub = ' ! '; const result = (<any>e1) .mergeMap((x: string) => Observable.of(x)) .switch() .mergeMap((x: any) => Observable.of(x)); expectObservable(result, unsub).toBe(expected); expectSubscriptions(x.subscriptions).toBe(xsubs); expectSubscriptions(y.subscriptions).toBe(ysubs); }); it('should handle a hot observable of observables, inner never completes', () => { const x = cold( '--a---b---c--| '); const xsubs = ' ^ ! '; const y = cold( '---d--e---f-----'); const ysubs = ' ^ '; const e1 = hot( '------x-------y------| ', { x: x, y: y }); const expected = '--------a---b----d--e---f-----'; expectObservable(e1.switch()).toBe(expected); expectSubscriptions(x.subscriptions).toBe(xsubs); expectSubscriptions(y.subscriptions).toBe(ysubs); }); it('should handle a synchronous switch to the second inner observable', () => { const x = cold( '--a---b---c--| '); const xsubs = ' (^!) '; const y = cold( '---d--e---f---| '); const ysubs = ' ^ ! '; const e1 = hot( '------(xy)------------|', { x: x, y: y }); const expected = '---------d--e---f-----|'; expectObservable(e1.switch()).toBe(expected); expectSubscriptions(x.subscriptions).toBe(xsubs); expectSubscriptions(y.subscriptions).toBe(ysubs); }); it('should handle a hot observable of observables, one inner throws', () => { const x = cold( '--a---# '); const xsubs = ' ^ ! '; const y = cold( '---d--e---f---|'); const ysubs = []; const e1 = hot( '------x-------y------| ', { x: x, y: y }); const expected = '--------a---# '; expectObservable(e1.switch()).toBe(expected); expectSubscriptions(x.subscriptions).toBe(xsubs); expectSubscriptions(y.subscriptions).toBe(ysubs); }); it('should handle a hot observable of observables, outer throws', () => { const x = cold( '--a---b---c--| '); const xsubs = ' ^ ! '; const y = cold( '---d--e---f---|'); const ysubs = ' ^ ! '; const e1 = hot( '------x-------y-------# ', { x: x, y: y }); const expected = '--------a---b----d--e-# '; expectObservable(e1.switch()).toBe(expected); expectSubscriptions(x.subscriptions).toBe(xsubs); expectSubscriptions(y.subscriptions).toBe(ysubs); }); it('should handle an empty hot observable', () => { const e1 = hot('------|'); const e1subs = '^ !'; const expected = '------|'; expectObservable(e1.switch()).toBe(expected); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should handle a never hot observable', () => { const e1 = hot('-'); const e1subs = '^'; const expected = '-'; expectObservable(e1.switch()).toBe(expected); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should complete not before the outer completes', () => { const x = cold( '--a---b---c--| '); const xsubs = ' ^ ! '; const e1 = hot( '------x---------------|', { x: x }); const e1subs = '^ !'; const expected = '--------a---b---c-----|'; expectObservable(e1.switch()).toBe(expected); expectSubscriptions(x.subscriptions).toBe(xsubs); expectSubscriptions(e1.subscriptions).toBe(e1subs); }); it('should handle an observable of promises', (done: MochaDone) => { const expected = [3]; (<any>Observable.of(Promise.resolve(1), Promise.resolve(2), Promise.resolve(3))) .switch() .subscribe((x: number) => { expect(x).to.equal(expected.shift()); }, null, () => { expect(expected.length).to.equal(0); done(); }); }); it('should handle an observable of promises, where last rejects', (done: MochaDone) => { Observable.of<any>(Promise.resolve(1), Promise.resolve(2), Promise.reject(3)) .switch() .subscribe(() => { done(new Error('should not be called')); }, (err: any) => { expect(err).to.equal(3); done(); }, () => { done(new Error('should not be called')); }); }); it('should handle an observable with Arrays in it', () => { const expected = [1, 2, 3, 4]; let completed = false; Observable.of<any>(Observable.never(), Observable.never(), [1, 2, 3, 4]) .switch() .subscribe((x: number) => { expect(x).to.equal(expected.shift()); }, null, () => { completed = true; expect(expected.length).to.equal(0); }); expect(completed).to.be.true; }); it('should not leak when child completes before each switch (prevent memory leaks #2355)', () => { let iStream: Rx.Subject<number>; const oStreamControl = new Rx.Subject<number>(); const oStream = oStreamControl.map(() => { return (iStream = new Rx.Subject()); }); const switcher = oStream.switch(); const result = []; let sub = switcher.subscribe((x: number) => result.push(x)); [0, 1, 2, 3, 4].forEach((n) => { oStreamControl.next(n); // creates inner iStream.complete(); }); // Expect one child of switch(): The oStream expect( (<any>sub)._subscriptions[0]._subscriptions.length ).to.equal(1); sub.unsubscribe(); }); it('should not leak if we switch before child completes (prevent memory leaks #2355)', () => { const oStreamControl = new Rx.Subject<number>(); const oStream = oStreamControl.map(() => { return (new Rx.Subject()); }); const switcher = oStream.switch(); const result = []; let sub = switcher.subscribe((x: number) => result.push(x)); [0, 1, 2, 3, 4].forEach((n) => { oStreamControl.next(n); // creates inner }); // Expect two children of switch(): The oStream and the first inner expect( (<any>sub)._subscriptions[0]._subscriptions.length ).to.equal(2); sub.unsubscribe(); }); });
the_stack
import { ComponentFixture, fakeAsync, TestBed, tick } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { LocalStorageService, SessionStorageService } from 'ngx-webstorage'; import { DebugElement } from '@angular/core'; import { of, Subject } from 'rxjs'; import { ArtemisTestModule } from '../../test.module'; import { MockSyncStorage } from '../../helpers/mocks/service/mock-sync-storage.service'; import { MockParticipationWebsocketService } from '../../helpers/mocks/service/mock-participation-websocket.service'; import { ParticipationWebsocketService } from 'app/overview/participation-websocket.service'; import { Exercise } from 'app/entities/exercise.model'; import { ExerciseSubmissionState, ProgrammingSubmissionService, ProgrammingSubmissionState } from 'app/exercises/programming/participate/programming-submission.service'; import { ProgrammingExerciseInstructorSubmissionStateComponent } from 'app/exercises/programming/shared/actions/programming-exercise-instructor-submission-state.component'; import { triggerChanges } from '../../helpers/utils/general.utils'; import { BuildRunState, ProgrammingBuildRunService } from 'app/exercises/programming/participate/programming-build-run.service'; import { ProgrammingExercise } from 'app/entities/programming-exercise.model'; import { TranslatePipeMock } from '../../helpers/mocks/service/mock-translate.service'; import { MockDirective, MockPipe } from 'ng-mocks'; import { ProgrammingExerciseTriggerAllButtonComponent } from 'app/exercises/programming/shared/actions/programming-exercise-trigger-all-button.component'; import { NgbTooltip } from '@ng-bootstrap/ng-bootstrap'; import { ButtonComponent } from 'app/shared/components/button.component'; import { DurationPipe } from 'app/shared/pipes/duration.pipe'; import { FeatureToggleDirective } from 'app/shared/feature-toggle/feature-toggle.directive'; import { TranslateDirective } from 'app/shared/language/translate.directive'; import { FeatureToggleLinkDirective } from 'app/shared/feature-toggle/feature-toggle-link.directive'; describe('ProgrammingExerciseInstructorSubmissionStateComponent', () => { let comp: ProgrammingExerciseInstructorSubmissionStateComponent; let fixture: ComponentFixture<ProgrammingExerciseInstructorSubmissionStateComponent>; let debugElement: DebugElement; let submissionService: ProgrammingSubmissionService; let buildRunService: ProgrammingBuildRunService; let getExerciseSubmissionStateStub: jest.SpyInstance; let getExerciseSubmissionStateSubject: Subject<ExerciseSubmissionState>; let getBuildRunStateSubject: Subject<BuildRunState>; let triggerAllStub: jest.SpyInstance; const exercise = { id: 20 } as Exercise; const resultEtaId = '#result-eta'; const getResultEtaContainer = () => { return debugElement.query(By.css(resultEtaId)); }; beforeEach(() => { return TestBed.configureTestingModule({ imports: [ArtemisTestModule], declarations: [ ProgrammingExerciseInstructorSubmissionStateComponent, ProgrammingExerciseTriggerAllButtonComponent, ButtonComponent, FeatureToggleDirective, FeatureToggleLinkDirective, TranslatePipeMock, MockDirective(NgbTooltip), MockDirective(TranslateDirective), MockPipe(DurationPipe), ], providers: [ { provide: ParticipationWebsocketService, useClass: MockParticipationWebsocketService }, { provide: LocalStorageService, useClass: MockSyncStorage }, { provide: SessionStorageService, useClass: MockSyncStorage }, ], }) .compileComponents() .then(() => { fixture = TestBed.createComponent(ProgrammingExerciseInstructorSubmissionStateComponent); comp = fixture.componentInstance; debugElement = fixture.debugElement; submissionService = debugElement.injector.get(ProgrammingSubmissionService); buildRunService = debugElement.injector.get(ProgrammingBuildRunService); getExerciseSubmissionStateSubject = new Subject<ExerciseSubmissionState>(); getExerciseSubmissionStateStub = jest.spyOn(submissionService, 'getSubmissionStateOfExercise').mockReturnValue(getExerciseSubmissionStateSubject); getBuildRunStateSubject = new Subject<BuildRunState>(); jest.spyOn(buildRunService, 'getBuildRunUpdates').mockReturnValue(getBuildRunStateSubject); triggerAllStub = jest.spyOn(submissionService, 'triggerInstructorBuildForParticipationsOfExercise').mockReturnValue(of()); jest.spyOn(submissionService, 'triggerInstructorBuildForAllParticipationsOfExercise').mockReturnValue(of()); }); }); afterEach(() => { jest.restoreAllMocks(); }); const getTriggerAllButton = () => { const triggerButton = debugElement.query(By.css('#trigger-all-button button')); return triggerButton ? triggerButton.nativeElement : null; }; const getTriggerFailedButton = () => { const triggerButton = debugElement.query(By.css('#trigger-failed-button button')); return triggerButton ? triggerButton.nativeElement : null; }; const getBuildState = () => { const buildState = debugElement.query(By.css('#build-state')); return buildState ? buildState.nativeElement : null; }; it('should not show the component before the build summary is retrieved', () => { expect(getTriggerAllButton()).toBe(null); expect(getTriggerFailedButton()).toBe(null); expect(getBuildState()).toBe(null); }); it('should show the result eta if there is at least one building submission', fakeAsync(() => { const isBuildingSubmissionState = { 1: { submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION, submission: undefined, participationId: 4 }, 4: { submissionState: ProgrammingSubmissionState.IS_BUILDING_PENDING_SUBMISSION, submission: undefined, participationId: 5 }, } as ExerciseSubmissionState; comp.exercise = exercise as ProgrammingExercise; triggerChanges(comp, { property: 'exercise', currentValue: comp.exercise }); getExerciseSubmissionStateSubject.next(isBuildingSubmissionState); tick(500); fixture.detectChanges(); const resultEta = getResultEtaContainer(); expect(resultEta).not.toBe(null); })); it('should not show the result eta if there is no building submission', () => { const isNotBuildingSubmission = { 1: { submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION, submission: undefined, participationId: 4 }, 4: { submissionState: ProgrammingSubmissionState.HAS_FAILED_SUBMISSION, submission: undefined, participationId: 5 }, } as ExerciseSubmissionState; comp.exercise = exercise as ProgrammingExercise; triggerChanges(comp, { property: 'exercise', currentValue: comp.exercise }); getExerciseSubmissionStateSubject.next(isNotBuildingSubmission); fixture.detectChanges(); const resultEta = getResultEtaContainer(); expect(resultEta).toBe(null); }); it('should show & enable the trigger all button and the build state once the build summary is loaded', fakeAsync(() => { const noPendingSubmissionState = { 1: { submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION, submission: undefined, participationId: 4 }, 4: { submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION, submission: undefined, participationId: 5 }, } as ExerciseSubmissionState; const compressedSummary = { [ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION]: 2 }; comp.exercise = exercise as ProgrammingExercise; triggerChanges(comp, { property: 'exercise', currentValue: comp.exercise }); getExerciseSubmissionStateSubject.next(noPendingSubmissionState); // Wait for a second as the view is updated with a debounce. tick(500); fixture.detectChanges(); expect(getExerciseSubmissionStateStub).toHaveBeenCalledOnce(); expect(getExerciseSubmissionStateStub).toHaveBeenCalledWith(exercise.id); expect(comp.hasFailedSubmissions).toBeFalse(); expect(comp.isBuildingFailedSubmissions).toBeFalse(); expect(comp.buildingSummary).toEqual(compressedSummary); expect(getTriggerAllButton()).not.toBe(null); expect(getTriggerAllButton().disabled).toBeFalse(); expect(getTriggerFailedButton()).not.toBe(null); expect(getTriggerFailedButton().disabled).toBeTrue(); expect(getBuildState()).not.toBe(null); })); it('should show & enable both buttons and the build state once the build summary is loaded when a failed submission exists', fakeAsync(() => { const noPendingSubmissionState = { 1: { submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION, submission: undefined, participationId: 55 }, 4: { submissionState: ProgrammingSubmissionState.HAS_FAILED_SUBMISSION, submission: undefined, participationId: 76 }, 5: { submissionState: ProgrammingSubmissionState.IS_BUILDING_PENDING_SUBMISSION, submission: undefined, participationId: 76 }, } as ExerciseSubmissionState; const compressedSummary = { [ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION]: 1, [ProgrammingSubmissionState.HAS_FAILED_SUBMISSION]: 1, [ProgrammingSubmissionState.IS_BUILDING_PENDING_SUBMISSION]: 1, }; comp.exercise = exercise as ProgrammingExercise; triggerChanges(comp, { property: 'exercise', currentValue: comp.exercise }); getExerciseSubmissionStateSubject.next(noPendingSubmissionState); // Wait for a second as the view is updated with a debounce. tick(500); fixture.detectChanges(); expect(getExerciseSubmissionStateStub).toHaveBeenCalledWith(exercise.id); expect(comp.hasFailedSubmissions).toBeTrue(); expect(comp.isBuildingFailedSubmissions).toBeFalse(); expect(comp.buildingSummary).toEqual(compressedSummary); expect(getResultEtaContainer()).not.toBe(null); expect(getTriggerAllButton()).not.toBe(null); expect(getTriggerAllButton().disabled).toBeFalse(); expect(getTriggerFailedButton()).not.toBe(null); expect(getTriggerFailedButton().disabled).toBeFalse(); expect(getBuildState()).not.toBe(null); })); it('should trigger the appropriate service method on trigger failed and set the isBuildingFailedSubmissionsState until the request returns a response', () => { const failedSubmissionParticipationIds = [333]; const triggerInstructorBuildForParticipationsOfExerciseSubject = new Subject<void>(); triggerAllStub.mockReturnValue(triggerInstructorBuildForParticipationsOfExerciseSubject); const getFailedSubmissionParticipationsForExerciseStub = jest.spyOn(submissionService, 'getSubmissionCountByType').mockReturnValue(failedSubmissionParticipationIds); // Component must have at least one failed submission for the button to be enabled. comp.exercise = exercise as ProgrammingExercise; comp.buildingSummary = { [ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION]: 1, [ProgrammingSubmissionState.HAS_FAILED_SUBMISSION]: 1 }; comp.hasFailedSubmissions = true; fixture.detectChanges(); const triggerButton = getTriggerFailedButton(); expect(triggerButton).not.toBe(null); expect(triggerButton.disabled).toBeFalse(); // Button is clicked. triggerButton.click(); expect(comp.isBuildingFailedSubmissions).toBeTrue(); expect(getFailedSubmissionParticipationsForExerciseStub).toHaveBeenCalledWith(comp.exercise.id, ProgrammingSubmissionState.HAS_FAILED_SUBMISSION); expect(triggerAllStub).toHaveBeenCalledWith(comp.exercise.id, failedSubmissionParticipationIds); fixture.detectChanges(); // Now the request returns a response. triggerInstructorBuildForParticipationsOfExerciseSubject.next(undefined); fixture.detectChanges(); expect(comp.isBuildingFailedSubmissions).toBeFalse(); }); it('should disable the trigger all button while a build is running and re-enable it when it is complete', fakeAsync(() => { const isBuildingSubmissionState = { 1: { submissionState: ProgrammingSubmissionState.HAS_NO_PENDING_SUBMISSION, submission: undefined, participationId: 4 }, 4: { submissionState: ProgrammingSubmissionState.IS_BUILDING_PENDING_SUBMISSION, submission: undefined, participationId: 5 }, } as ExerciseSubmissionState; comp.exercise = exercise as ProgrammingExercise; triggerChanges(comp, { property: 'exercise', currentValue: comp.exercise }); getExerciseSubmissionStateSubject.next(isBuildingSubmissionState); // Wait for a second as the view is updated with a debounce. tick(500); fixture.detectChanges(); expect(getTriggerAllButton().disabled).toBeFalse(); getBuildRunStateSubject.next(BuildRunState.RUNNING); fixture.detectChanges(); expect(getTriggerAllButton().disabled).toBeTrue(); getBuildRunStateSubject.next(BuildRunState.COMPLETED); fixture.detectChanges(); expect(getTriggerAllButton().disabled).toBeFalse(); })); });
the_stack