text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import "./artificialIntelligence.component.scss" import debounce from "lodash.debounce" import { FilesSelectionSubscriber, FilesService } from "../../state/store/files/files.service" import { FileState } from "../../model/files/files" import { IRootScopeService } from "angular" import { buildCustomConfigFromState } from "../../util/customConfigBuilder" import { CustomConfigHelper } from "../../util/customConfigHelper" import { StoreService } from "../../state/store.service" import { klona } from "klona" import { CustomConfig, CustomConfigMapSelectionMode } from "../../model/customConfig/customConfig.api.model" import { pushSorted } from "../../util/nodeDecorator" import { BlacklistItem, BlacklistType, CodeMapNode, ColorRange, NodeType, State } from "../../codeCharta.model" import { hierarchy } from "d3-hierarchy" import { getVisibleFileStates } from "../../model/files/files.helper" import { metricThresholds } from "./artificialIntelligence.metricThresholds" import { defaultMapColors } from "../../state/store/appSettings/mapColors/mapColors.actions" import { ThreeOrbitControlsService } from "../codeMap/threeViewer/threeOrbitControlsService" import { ThreeCameraService } from "../codeMap/threeViewer/threeCameraService" import { BlacklistService, BlacklistSubscriber } from "../../state/store/fileSettings/blacklist/blacklist.service" import { isPathBlacklisted } from "../../util/codeMapHelper" interface MetricValues { [metric: string]: number[] } interface MetricAssessmentResults { suspiciousMetrics: Map<string, ColorRange> unsuspiciousMetrics: string[] outliersThresholds: Map<string, number> } interface MetricSuggestionParameters { metric: string from: number to: number generalCustomConfigId: string outlierCustomConfigId?: string } export class ArtificialIntelligenceController implements FilesSelectionSubscriber, BlacklistSubscriber { private _viewModel: { analyzedProgrammingLanguage: string suspiciousMetricSuggestionLinks: MetricSuggestionParameters[] unsuspiciousMetrics: string[] riskProfile: { lowRisk: number moderateRisk: number highRisk: number veryHighRisk: number } } = { analyzedProgrammingLanguage: undefined, suspiciousMetricSuggestionLinks: [], unsuspiciousMetrics: [], riskProfile: { lowRisk: 0, moderateRisk: 0, highRisk: 0, veryHighRisk: 0 } } private debounceCalculation: () => void private fileState: FileState private blacklist: BlacklistItem[] = [] constructor( private $rootScope: IRootScopeService, private storeService: StoreService, private threeOrbitControlsService: ThreeOrbitControlsService, private threeCameraService: ThreeCameraService ) { "ngInject" FilesService.subscribe(this.$rootScope, this) BlacklistService.subscribe(this.$rootScope, this) this.debounceCalculation = debounce(() => { this.calculate() }, 10) } applyCustomConfig(configId: string) { CustomConfigHelper.applyCustomConfig(configId, this.storeService, this.threeCameraService, this.threeOrbitControlsService) } onBlacklistChanged(blacklist: BlacklistItem[]) { this.blacklist = blacklist this.fileState = getVisibleFileStates(this.storeService.getState().files)[0] if (this.fileState !== undefined) { this.debounceCalculation() } } onFilesSelectionChanged(files: FileState[]) { const fileState = getVisibleFileStates(files)[0] if (fileState === undefined) { return } this.fileState = fileState this.debounceCalculation() } private calculate() { const mainProgrammingLanguage = this.getMostFrequentLanguage(this.fileState.file.map) this._viewModel.analyzedProgrammingLanguage = mainProgrammingLanguage this.clearRiskProfile() if (mainProgrammingLanguage !== undefined) { this.calculateRiskProfile(this.fileState, mainProgrammingLanguage, "mcc") this.createCustomConfigSuggestions(this.fileState, mainProgrammingLanguage) } } private clearRiskProfile() { this._viewModel.riskProfile = undefined } private calculateRiskProfile(fileState: FileState, programmingLanguage, metricName) { let totalRloc = 0 let numberOfRlocLowRisk = 0 let numberOfRlocModerateRisk = 0 let numberOfRlocHighRisk = 0 let numberOfRlocVeryHighRisk = 0 const languageSpecificThresholds = this.getAssociatedMetricThresholds(programmingLanguage) const thresholds = languageSpecificThresholds[metricName] for (const { data } of hierarchy(fileState.file.map)) { // TODO calculate risk profile only for focused or currently visible but not excluded files. if ( data.type !== NodeType.FILE || isPathBlacklisted(data.path, this.blacklist, BlacklistType.exclude) || data.attributes[metricName] === undefined || data.attributes["rloc"] === undefined || this.getFileExtension(data.name) !== programmingLanguage ) { continue } const nodeMetricValue = data.attributes[metricName] const nodeRlocValue = data.attributes["rloc"] totalRloc += nodeRlocValue // Idea: We could calculate risk profiles per directory in the future. if (nodeMetricValue <= thresholds.percentile70) { numberOfRlocLowRisk += nodeRlocValue } else if (nodeMetricValue <= thresholds.percentile80) { numberOfRlocModerateRisk += nodeRlocValue } else if (nodeMetricValue <= thresholds.percentile90) { numberOfRlocHighRisk += nodeRlocValue } else { numberOfRlocVeryHighRisk += nodeRlocValue } } if (totalRloc === 0) { return } this._viewModel.riskProfile = { lowRisk: Math.ceil((numberOfRlocLowRisk / totalRloc) * 100), moderateRisk: Math.ceil((numberOfRlocModerateRisk / totalRloc) * 100), highRisk: Math.ceil((numberOfRlocHighRisk / totalRloc) * 100), veryHighRisk: Math.ceil((numberOfRlocVeryHighRisk / totalRloc) * 100) } } private createCustomConfigSuggestions(fileState: FileState, programmingLanguage) { const metricValues = this.getSortedMetricValues(fileState, programmingLanguage) const metricAssessmentResults = this.findGoodAndBadMetrics(metricValues, programmingLanguage) const noticeableMetricSuggestionLinks = new Map<string, MetricSuggestionParameters>() const newCustomConfigs: CustomConfig[] = [] for (const [metricName, colorRange] of metricAssessmentResults.suspiciousMetrics) { const suspiciousMetricConfig = this.createOrUpdateCustomConfig( `Suspicious Files - Metric ${metricName.toUpperCase()} - (AI)`, this.prepareOverviewConfigState(metricName, colorRange.from, colorRange.to), fileState ) newCustomConfigs.push(suspiciousMetricConfig) noticeableMetricSuggestionLinks.set(metricName, { metric: metricName, ...colorRange, generalCustomConfigId: suspiciousMetricConfig.id }) const outlierThreshold = metricAssessmentResults.outliersThresholds.get(metricName) if (outlierThreshold > 0) { const highRiskMetricConfig = this.createOrUpdateCustomConfig( `Very High Risk Files - Metric ${metricName.toUpperCase()} - (AI)`, this.prepareOutlierConfigState(metricName, outlierThreshold - 1, outlierThreshold), fileState ) newCustomConfigs.push(highRiskMetricConfig) noticeableMetricSuggestionLinks.get(metricName).outlierCustomConfigId = highRiskMetricConfig.id } } CustomConfigHelper.addCustomConfigs(newCustomConfigs) this._viewModel.suspiciousMetricSuggestionLinks = [...noticeableMetricSuggestionLinks.values()] this._viewModel.unsuspiciousMetrics = metricAssessmentResults.unsuspiciousMetrics } private findGoodAndBadMetrics(metricValues, programmingLanguage): MetricAssessmentResults { const metricAssessmentResults: MetricAssessmentResults = { suspiciousMetrics: new Map<string, ColorRange>(), unsuspiciousMetrics: [], outliersThresholds: new Map<string, number>() } const languageSpecificMetricThresholds = this.getAssociatedMetricThresholds(programmingLanguage) for (const metricName of Object.keys(languageSpecificMetricThresholds)) { const valuesOfMetric = metricValues[metricName] if (valuesOfMetric === undefined) { continue } const thresholdConfig = languageSpecificMetricThresholds[metricName] const maxMetricValue = Math.max(...valuesOfMetric) if (maxMetricValue <= thresholdConfig.percentile70) { metricAssessmentResults.unsuspiciousMetrics.push(metricName) } else if (maxMetricValue > thresholdConfig.percentile70) { metricAssessmentResults.suspiciousMetrics.set(metricName, { from: thresholdConfig.percentile70, to: thresholdConfig.percentile80, max: 0, min: 0 }) if (maxMetricValue > thresholdConfig.percentile90) { metricAssessmentResults.outliersThresholds.set(metricName, thresholdConfig.percentile90) } } } return metricAssessmentResults } private createOrUpdateCustomConfig(configName: string, state: State, fileState: FileState) { const customConfig = CustomConfigHelper.getCustomConfigByName( CustomConfigMapSelectionMode.SINGLE, [fileState.file.fileMeta.fileName], configName ) // If it exists, create a fresh one with current thresholds if (customConfig !== null) { CustomConfigHelper.deleteCustomConfig(customConfig.id) } return buildCustomConfigFromState(configName, state) } private prepareOverviewConfigState(metricName: string, colorRangeFrom: number, colorRangeTo: number) { const state = klona(this.storeService.getState()) // just use rloc as area metric state.dynamicSettings.areaMetric = "rloc" // use bad metric as height and color metric state.dynamicSettings.heightMetric = metricName state.dynamicSettings.colorMetric = metricName //state.dynamicSettings.colorRange.from = bugOutlier.valueOf() / 2 //state.dynamicSettings.colorRange.to = bugOutlier.valueOf() state.dynamicSettings.colorRange.from = colorRangeFrom state.dynamicSettings.colorRange.to = colorRangeTo state.appSettings.mapColors.positive = defaultMapColors.positive state.appSettings.mapColors.neutral = defaultMapColors.neutral state.appSettings.mapColors.negative = defaultMapColors.negative return state } private prepareOutlierConfigState(metricName: string, colorRangeFrom: number, colorRangeTo: number) { const state = klona(this.storeService.getState()) // just use rloc as area metric state.dynamicSettings.areaMetric = "rloc" // use bad metric as height and color metric state.dynamicSettings.heightMetric = metricName state.dynamicSettings.colorMetric = metricName state.dynamicSettings.colorRange.to = colorRangeTo state.dynamicSettings.colorRange.from = colorRangeFrom state.appSettings.mapColors.positive = "#ffffff" state.appSettings.mapColors.neutral = "#ffffff" state.appSettings.mapColors.negative = "#A900C0" return state } private getSortedMetricValues(fileState: FileState, programmingLanguage): MetricValues { const metricValues: MetricValues = {} for (const { data } of hierarchy(fileState.file.map)) { if ( data.type !== NodeType.FILE || isPathBlacklisted(data.path, this.blacklist, BlacklistType.exclude) || this.getFileExtension(data.name) !== programmingLanguage ) { continue } for (const metricIndex of Object.keys(data.attributes)) { const value = data.attributes[metricIndex] if (value > 0) { if (metricValues[metricIndex] === undefined) { metricValues[metricIndex] = [] } pushSorted(metricValues[metricIndex], data.attributes[metricIndex]) } } } return metricValues } private getFileExtension(fileName: string) { return fileName.includes(".") ? fileName.slice(fileName.lastIndexOf(".") + 1) : undefined } private getMostFrequentLanguage(map: CodeMapNode) { const numberOfFilesPerLanguage = [] for (const { data } of hierarchy(map)) { if (!data.name.includes(".")) { continue } if (data.type === NodeType.FILE) { const fileExtension = data.name.slice(data.name.lastIndexOf(".") + 1) numberOfFilesPerLanguage[fileExtension] = numberOfFilesPerLanguage[fileExtension] + 1 || 1 } } if (Object.keys(numberOfFilesPerLanguage).length === 0) { return } return Object.keys(numberOfFilesPerLanguage).reduce((a, b) => { return numberOfFilesPerLanguage[a] > numberOfFilesPerLanguage[b] ? a : b }) } private getAssociatedMetricThresholds(programmingLanguage) { return programmingLanguage === "java" ? metricThresholds["java"] : metricThresholds["miscellaneous"] } } export const artificialIntelligenceComponent = { selector: "artificialIntelligenceComponent", template: require("./artificialIntelligence.component.html"), controller: ArtificialIntelligenceController }
the_stack
import { enableAppWillAutoExitFlag, getWin } from "./main"; import { autoUpdater } from "electron-updater"; import { log } from "@core/lib/utils/logger"; import { app, dialog } from "electron"; import { listVersionsGT, readReleaseNotesFromS3, } from "@infra/artifact-helpers"; import { ENVKEY_RELEASES_BUCKET, envkeyReleasesS3Creds, } from "@infra/stack-constants"; import { AvailableClientUpgrade, UpgradeProgress } from "@core/types/electron"; import * as R from "ramda"; import { downloadAndInstallCliTools, isLatestCliInstalled, isLatestEnvkeysourceInstalled, } from "./cli_tools"; const CHECK_INTERVAL = 10 * 60 * 1000; const CHECK_UPGRADE_TIMEOUT = 5000; const CHECK_UPGRADE_RETRIES = 3; // allow looping only once let loopInitialized = false; let desktopVersionDownloaded: string | undefined; let upgradeAvailable: AvailableClientUpgrade | undefined; let desktopDownloadComplete = false; let cliToolsInstallComplete = false; autoUpdater.logger = { debug: (...args) => log("autoUpdater:debug", { data: args }), info: (...args) => log("autoUpdater:info", { data: args }), warn: (...args) => log("autoUpdater:warn", { data: args }), error: (...args) => log("autoUpdater:error ", { data: args }), }; // forces releaseNotes to string[] autoUpdater.fullChangelog = true; autoUpdater.autoDownload = false; app.on("ready", () => { autoUpdater.on("download-progress", ({ transferred, total }) => { const progress: UpgradeProgress = { clientProject: "desktop", downloadedBytes: transferred, totalBytes: total, }; getWin()!.webContents.send("upgrade-progress", progress); }); }); let checkUpgradesInterval: number | undefined; export const runCheckUpgradesLoop = () => { log("init updates loop"); if (loopInitialized) { log("app update loop already initialized; refusing to start again."); return; } // not returned checkUpgrade().catch((err) => { log("checkUpdate failed", { err }); }); checkUpgradesInterval = setInterval(checkUpgrade, CHECK_INTERVAL); loopInitialized = true; log("app update loop initialized"); }; export const stopCheckUpgradesLoop = () => { if (checkUpgradesInterval) { clearInterval(checkUpgradesInterval); checkUpgradesInterval = undefined; } }; const resetUpgradesLoop = () => { if (checkUpgradesInterval) { clearInterval(checkUpgradesInterval); } checkUpgradesInterval = setInterval(checkUpgrade, CHECK_INTERVAL); }; let checkDesktopUpgradeTimeout: NodeJS.Timeout | undefined; export const checkUpgrade = async ( fromContextMenu = false, noDispatch = false, numRetry = 0 ): Promise<any> => { const currentDesktopVersion = app.getVersion(); let checkDesktopError = false; const [desktopRes, cliLatestInstalledRes, envkeysourceLatestInstalledRes] = await Promise.all([ autoUpdater.netSession .closeAllConnections() .then(() => { checkDesktopUpgradeTimeout = setTimeout(() => { autoUpdater.netSession.closeAllConnections(); }, CHECK_UPGRADE_TIMEOUT); return autoUpdater.checkForUpdates().then((res) => { if (checkDesktopUpgradeTimeout) { clearTimeout(checkDesktopUpgradeTimeout); } return res; }); }) .catch((err) => { if (checkDesktopUpgradeTimeout) { clearTimeout(checkDesktopUpgradeTimeout); } // error gets logged thanks to logger init at top checkDesktopError = true; }), isLatestCliInstalled().catch((err) => <const>true), isLatestEnvkeysourceInstalled().catch((err) => <const>true), ]); // the autoUpdater.on("error") handler will handle re-checking if (checkDesktopError) { if (numRetry < CHECK_UPGRADE_RETRIES) { return checkUpgrade(fromContextMenu, noDispatch, numRetry + 1); } else { return; } } const nextCliVersion = (cliLatestInstalledRes !== true && cliLatestInstalledRes[0]) || undefined; const currentCliVersion = (cliLatestInstalledRes !== true && cliLatestInstalledRes[1]) || undefined; const nextEnvkeysourceVersion = (envkeysourceLatestInstalledRes !== true && envkeysourceLatestInstalledRes[0]) || undefined; const currentEnvkeysourceVersion = (envkeysourceLatestInstalledRes !== true && envkeysourceLatestInstalledRes[1]) || undefined; const hasCliUpgrade = currentCliVersion && nextCliVersion && currentCliVersion != nextCliVersion; const hasEnvkeysourceUpgrade = currentEnvkeysourceVersion && nextEnvkeysourceVersion && currentEnvkeysourceVersion != nextEnvkeysourceVersion; const hasDesktopUpgrade = desktopRes?.updateInfo?.version && desktopRes.updateInfo.version !== currentDesktopVersion; const nextDesktopVersion = hasDesktopUpgrade && desktopRes ? desktopRes.updateInfo.version : undefined; const hasAnyUpgrade = hasDesktopUpgrade || hasCliUpgrade || hasEnvkeysourceUpgrade; log("finished checking updates", { hasDesktopUpgrade, hasCliUpgrade, hasEnvkeysourceUpgrade, }); if (!hasAnyUpgrade) { if (fromContextMenu) { return dialog.showMessageBox({ title: "EnvKey", message: `EnvKey is up to date.`, }); } return; } const [desktopNotes, cliNotes, envkeysourceNotes] = await Promise.all( ( [ [hasDesktopUpgrade, "desktop", currentDesktopVersion], [hasCliUpgrade, "cli", currentCliVersion], [hasEnvkeysourceUpgrade, "envkeysource", currentEnvkeysourceVersion], ] as [boolean, "desktop" | "cli" | "envkeysource", string | undefined][] ).map(([hasUpgrade, project, current]) => hasUpgrade && current ? listVersionsGT({ bucket: ENVKEY_RELEASES_BUCKET, creds: envkeyReleasesS3Creds, currentVersionNumber: current, tagPrefix: project, }).then((missedVersions) => Promise.all( missedVersions.map((version) => readReleaseNotesFromS3({ bucket: ENVKEY_RELEASES_BUCKET, creds: envkeyReleasesS3Creds, project, version, }).then((note) => [version, note] as [string, string]) ) ) ) : undefined ) ); upgradeAvailable = { desktop: hasDesktopUpgrade && nextDesktopVersion && desktopNotes ? { nextVersion: nextDesktopVersion, currentVersion: currentDesktopVersion, notes: R.fromPairs(desktopNotes), } : undefined, cli: hasCliUpgrade && currentCliVersion && nextCliVersion && cliNotes ? { nextVersion: nextCliVersion, currentVersion: currentCliVersion, notes: R.fromPairs(cliNotes), } : undefined, envkeysource: hasEnvkeysourceUpgrade && currentEnvkeysourceVersion && nextEnvkeysourceVersion && envkeysourceNotes ? { nextVersion: nextEnvkeysourceVersion, currentVersion: currentEnvkeysourceVersion, notes: R.fromPairs(envkeysourceNotes), } : undefined, }; log("client upgrade available", upgradeAvailable); if (!noDispatch) { getWin()!.webContents.send("upgrade-available", upgradeAvailable); } }; export const downloadAndInstallUpgrade = async () => { if (!upgradeAvailable) { throw new Error("No client upgrade is available"); } stopCheckUpgradesLoop(); // first ensure we are installing the latest upgrade // otherwise inform user that a newer upgrade is available const upgradeAvailableBeforeCheck = R.clone(upgradeAvailable); await checkUpgrade(false, true).catch((err) => { log("checkUpdate failed", { err }); }); if (!R.equals(upgradeAvailableBeforeCheck, upgradeAvailable)) { getWin()!.webContents.send("newer-upgrade-available", upgradeAvailable); resetUpgradesLoop(); return; } let error = false; await Promise.all([ upgradeAvailable.cli || upgradeAvailable.envkeysource ? downloadAndInstallCliTools(upgradeAvailable, "upgrade", (progress) => getWin()!.webContents.send("upgrade-progress", progress) ) .then(() => { log("CLI tools upgraded ok"); cliToolsInstallComplete = true; }) .catch((err) => { error = true; log("CLI tools upgrade failed", { err }); }) : undefined, upgradeAvailable.desktop ? autoUpdater .downloadUpdate() .then(() => { log("autoUpdater downloaded ok"); if (upgradeAvailable!.desktop) { desktopVersionDownloaded = upgradeAvailable!.desktop.nextVersion; } }) .catch((err) => { error = true; log("autoUpdater download failed", { err }); }) : undefined, ]); log("finished CLI tools install and/or autoUpdater download", { error }); if (error) { log("Sending upgrade-error to webContents"); getWin()!.webContents.send("upgrade-error"); checkUpgrade().catch((err) => { log("checkUpdate failed", { err }); }); resetUpgradesLoop(); } else if (!upgradeAvailable.desktop) { log("Sending upgrade-complete to webContents"); getWin()!.webContents.send("upgrade-complete"); upgradeAvailable = undefined; cliToolsInstallComplete = false; resetUpgradesLoop(); } else if ( upgradeAvailable.desktop && desktopDownloadComplete && (upgradeAvailable.cli || upgradeAvailable.envkeysource) ) { log("CLI tools upgrade finished after autoUpdater, now restarting"); restartWithLatestVersion(); } }; const restartWithLatestVersion = () => { log("Restarting with new version", { versionDownloaded: desktopVersionDownloaded, }); enableAppWillAutoExitFlag(); // quits the app and relaunches with latest version try { autoUpdater.quitAndInstall(true, true); } catch (err) { log("autoUpdater failed to quit and install", { err }); } }; autoUpdater.on("update-downloaded", () => { log("autoUpdater:update-downloaded"); desktopDownloadComplete = true; if ( upgradeAvailable && (!(upgradeAvailable.cli || upgradeAvailable.envkeysource) || cliToolsInstallComplete) ) { restartWithLatestVersion(); } else { log("Waiting for CLI tools download to finish before restarting"); } });
the_stack
import { buildSchema } from 'graphql'; import { plugin } from '../src/index'; describe('zod', () => { test.each([ [ 'non-null and defined', /* GraphQL */ ` input PrimitiveInput { a: ID! b: String! c: Boolean! d: Int! e: Float! } `, [ 'export function PrimitiveInputSchema(): z.ZodObject<Properties<PrimitiveInput>>', 'a: z.string()', 'b: z.string()', 'c: z.boolean()', 'd: z.number()', 'e: z.number()', ], ], [ 'nullish', /* GraphQL */ ` input PrimitiveInput { a: ID b: String c: Boolean d: Int e: Float z: String! # no defined check } `, [ 'export function PrimitiveInputSchema(): z.ZodObject<Properties<PrimitiveInput>>', // alphabet order 'a: z.string().nullish(),', 'b: z.string().nullish(),', 'c: z.boolean().nullish(),', 'd: z.number().nullish(),', 'e: z.number().nullish(),', ], ], [ 'array', /* GraphQL */ ` input ArrayInput { a: [String] b: [String!] c: [String!]! d: [[String]] e: [[String]!] f: [[String]!]! } `, [ 'export function ArrayInputSchema(): z.ZodObject<Properties<ArrayInput>>', 'a: z.array(z.string().nullable()).nullish(),', 'b: z.array(z.string()).nullish(),', 'c: z.array(z.string()),', 'd: z.array(z.array(z.string().nullable()).nullish()).nullish(),', 'e: z.array(z.array(z.string().nullable())).nullish(),', 'f: z.array(z.array(z.string().nullable()))', ], ], [ 'ref input object', /* GraphQL */ ` input AInput { b: BInput! } input BInput { c: CInput! } input CInput { a: AInput! } `, [ 'export function AInputSchema(): z.ZodObject<Properties<AInput>>', 'b: z.lazy(() => BInputSchema())', 'export function BInputSchema(): z.ZodObject<Properties<BInput>>', 'c: z.lazy(() => CInputSchema())', 'export function CInputSchema(): z.ZodObject<Properties<CInput>>', 'a: z.lazy(() => AInputSchema())', ], ], [ 'nested input object', /* GraphQL */ ` input NestedInput { child: NestedInput childrens: [NestedInput] } `, [ 'export function NestedInputSchema(): z.ZodObject<Properties<NestedInput>>', 'child: z.lazy(() => NestedInputSchema().nullish()),', 'childrens: z.array(z.lazy(() => NestedInputSchema().nullable())).nullish()', ], ], [ 'enum', /* GraphQL */ ` enum PageType { PUBLIC BASIC_AUTH } input PageInput { pageType: PageType! } `, [ 'export const PageTypeSchema = z.nativeEnum(PageType)', 'export function PageInputSchema(): z.ZodObject<Properties<PageInput>>', 'pageType: PageTypeSchema', ], ], [ 'camelcase', /* GraphQL */ ` input HTTPInput { method: HTTPMethod url: URL! } enum HTTPMethod { GET POST } scalar URL # unknown scalar, should be any (definedNonNullAnySchema) `, [ 'export function HttpInputSchema(): z.ZodObject<Properties<HttpInput>>', 'export const HttpMethodSchema = z.nativeEnum(HttpMethod)', 'method: HttpMethodSchema', 'url: definedNonNullAnySchema', ], ], ])('%s', async (_, textSchema, wantContains) => { const schema = buildSchema(textSchema); const result = await plugin(schema, [], { schema: 'zod' }, {}); expect(result.prepend).toContain("import { z } from 'zod'"); for (const wantContain of wantContains) { expect(result.content).toContain(wantContain); } }); it('with scalars', async () => { const schema = buildSchema(/* GraphQL */ ` input Say { phrase: Text! times: Count! } scalar Count scalar Text `); const result = await plugin( schema, [], { schema: 'zod', scalars: { Text: 'string', Count: 'number', }, }, {} ); expect(result.content).toContain('phrase: z.string()'); expect(result.content).toContain('times: z.number()'); }); it('with importFrom', async () => { const schema = buildSchema(/* GraphQL */ ` input Say { phrase: String! } `); const result = await plugin( schema, [], { schema: 'zod', importFrom: './types', }, {} ); expect(result.prepend).toContain("import { Say } from './types'"); expect(result.content).toContain('phrase: z.string()'); }); it('with enumsAsTypes', async () => { const schema = buildSchema(/* GraphQL */ ` enum PageType { PUBLIC BASIC_AUTH } `); const result = await plugin( schema, [], { schema: 'zod', enumsAsTypes: true, }, {} ); expect(result.content).toContain("export const PageTypeSchema = z.enum(['PUBLIC', 'BASIC_AUTH'])"); }); it('with notAllowEmptyString', async () => { const schema = buildSchema(/* GraphQL */ ` input PrimitiveInput { a: ID! b: String! c: Boolean! d: Int! e: Float! } `); const result = await plugin( schema, [], { schema: 'zod', notAllowEmptyString: true, }, {} ); const wantContains = [ 'export function PrimitiveInputSchema(): z.ZodObject<Properties<PrimitiveInput>>', 'a: z.string().min(1),', 'b: z.string().min(1),', 'c: z.boolean(),', 'd: z.number(),', 'e: z.number()', ]; for (const wantContain of wantContains) { expect(result.content).toContain(wantContain); } }); it('with scalarSchemas', async () => { const schema = buildSchema(/* GraphQL */ ` input ScalarsInput { date: Date! email: Email str: String! } scalar Date scalar Email `); const result = await plugin( schema, [], { schema: 'zod', scalarSchemas: { Date: 'z.date()', Email: 'z.string().email()', }, }, {} ); const wantContains = [ 'export function ScalarsInputSchema(): z.ZodObject<Properties<ScalarsInput>>', 'date: z.date(),', 'email: z.string().email().nullish(),', 'str: z.string()', ]; for (const wantContain of wantContains) { expect(result.content).toContain(wantContain); } }); it('with typesPrefix', async () => { const schema = buildSchema(/* GraphQL */ ` input Say { phrase: String! } `); const result = await plugin( schema, [], { schema: 'zod', typesPrefix: 'I', importFrom: './types', }, {} ); expect(result.prepend).toContain("import { ISay } from './types'"); expect(result.content).toContain('export function ISaySchema(): z.ZodObject<Properties<ISay>> {'); }); it('with typesSuffix', async () => { const schema = buildSchema(/* GraphQL */ ` input Say { phrase: String! } `); const result = await plugin( schema, [], { schema: 'zod', typesSuffix: 'I', importFrom: './types', }, {} ); expect(result.prepend).toContain("import { SayI } from './types'"); expect(result.content).toContain('export function SayISchema(): z.ZodObject<Properties<SayI>> {'); }); describe('issues #19', () => { it('string field', async () => { const schema = buildSchema(/* GraphQL */ ` input UserCreateInput { profile: String @constraint(minLength: 1, maxLength: 5000) } directive @constraint(minLength: Int!, maxLength: Int!) on INPUT_FIELD_DEFINITION `); const result = await plugin( schema, [], { schema: 'zod', directives: { constraint: { minLength: ['min', '$1', 'Please input more than $1'], maxLength: ['max', '$1', 'Please input less than $1'], }, }, }, {} ); const wantContains = [ 'export function UserCreateInputSchema(): z.ZodObject<Properties<UserCreateInput>>', 'profile: z.string().min(1, "Please input more than 1").max(5000, "Please input less than 5000").nullish()', ]; for (const wantContain of wantContains) { expect(result.content).toContain(wantContain); } }); it('not null field', async () => { const schema = buildSchema(/* GraphQL */ ` input UserCreateInput { profile: String! @constraint(minLength: 1, maxLength: 5000) } directive @constraint(minLength: Int!, maxLength: Int!) on INPUT_FIELD_DEFINITION `); const result = await plugin( schema, [], { schema: 'zod', directives: { constraint: { minLength: ['min', '$1', 'Please input more than $1'], maxLength: ['max', '$1', 'Please input less than $1'], }, }, }, {} ); const wantContains = [ 'export function UserCreateInputSchema(): z.ZodObject<Properties<UserCreateInput>>', 'profile: z.string().min(1, "Please input more than 1").max(5000, "Please input less than 5000")', ]; for (const wantContain of wantContains) { expect(result.content).toContain(wantContain); } }); it('list field', async () => { const schema = buildSchema(/* GraphQL */ ` input UserCreateInput { profile: [String] @constraint(minLength: 1, maxLength: 5000) } directive @constraint(minLength: Int!, maxLength: Int!) on INPUT_FIELD_DEFINITION `); const result = await plugin( schema, [], { schema: 'zod', directives: { constraint: { minLength: ['min', '$1', 'Please input more than $1'], maxLength: ['max', '$1', 'Please input less than $1'], }, }, }, {} ); const wantContains = [ 'export function UserCreateInputSchema(): z.ZodObject<Properties<UserCreateInput>>', 'profile: z.array(z.string().nullable()).min(1, "Please input more than 1").max(5000, "Please input less than 5000").nullish()', ]; for (const wantContain of wantContains) { expect(result.content).toContain(wantContain); } }); }); });
the_stack
import { color } from "d3"; // Canvas Handle Function function drawRectStroke(context:any, x:any, y:any, width:any, height:any, strokeColor:any="#bbb"){ context.beginPath(); context.strokeStyle = strokeColor; context.rect(x, y, width, height); context.stroke(); } function drawRect(context:any, x:any, y:any, width:any, height:any, fillColor:any="#fff", opacity:any=0.8){ context.fillStyle = fillColor; context.globalAlpha = opacity; context.fillRect(x, y, width, height); context.globalAlpha = 1.0; } function drawCircleStroke(context:any, color:any, radius:any, x:any, y:any, lineWidth:number){ context.lineWidth = lineWidth context.strokeStyle = color; context.beginPath(); context.arc(x, y, radius, 0, 2 * Math.PI, true); context.stroke(); } function drawCircle(context:any, color:any, radius:any, x:any, y:any, alpha:any=1){ let original_globalAlpha = context.globalAlpha; context.globalAlpha = alpha; context.beginPath(); context.arc(x, y, radius, 0, 2 * Math.PI, true); context.fillStyle = color; context.fill(); context.globalAlpha = original_globalAlpha; } function drawOnePie(context:any, color:any, radius:any, x:any, y:any, startAngle:any, endAngle:any, alpha:any=1){ let original_globalAlpha = context.globalAlpha; context.globalAlpha = alpha; context.beginPath(); context.moveTo(x,y); context.arc(x, y, radius, startAngle, endAngle); context.fillStyle = color; context.closePath(); context.fill(); context.globalAlpha = original_globalAlpha; } function drawOneArc(context:any, color:any, radius:any, x:any, y:any, startAngle:any, endAngle:any){ context.moveTo(x,y); context.beginPath(); context.arc(x, y, radius, startAngle, endAngle); context.strokeStyle = color; context.stroke(); } /* //Backup version function drawNodeGlyph(context:any, colorlist:any, inner_radius:any, radius:any, outer_radius:any, x:any, y:any, enableStroke:boolean=false){ drawCircle(context, colorlist[4], outer_radius, x, y); if(enableStroke){ drawCircleStroke(context, "#000", outer_radius, x, y, 2); } drawOnePie(context, colorlist[1], outer_radius, x, y, (-150)/180*Math.PI, (-30)/180*Math.PI); drawOnePie(context, colorlist[2], outer_radius, x, y, (-30)/180*Math.PI, (+90)/180*Math.PI); drawOnePie(context, colorlist[3], outer_radius, x, y, (+90)/180*Math.PI, (+210)/180*Math.PI); for(let i = 0; i<3; i++){ let angle = (-150+120*i)/180*Math.PI; let x1 = x + radius*Math.cos(angle); let y1 = y + radius*Math.sin(angle); let x2 = x + outer_radius*Math.cos(angle); let y2 = y + outer_radius*Math.sin(angle); // drawLine(context, "#ddd", x1, y1, x2 ,y2, 0.5); drawLine(context, colorlist[4], x1, y1, x2 ,y2, radius-inner_radius); } drawCircle(context, colorlist[4], radius, x, y); drawCircle(context, colorlist[0], inner_radius, x, y); }*/ /* function drawNodeGlyph(context:any, colorlist:any, inner_radius:any, radius:any, outer_radius:any, x:any, y:any, enableStroke:boolean=false, outer_arc_encoded_value:any=0.5, outer_arc_radius:any=2, enable_alpha_mode=true){ let value = outer_arc_encoded_value; //let original_globalAlpha = context.globalAlpha; if(value<0) value = 0; else if(value>1) value = 1; let alpha = 1; if(enable_alpha_mode){ alpha = value; } //context.globalAlpha = value; drawCircle(context, colorlist[4], outer_radius, x, y, alpha); if(enableStroke){ drawCircleStroke(context, "#000", outer_radius, x, y, 2); } drawOnePie(context, colorlist[1], outer_radius, x, y, (-150)/180*Math.PI, (-30)/180*Math.PI, alpha); drawOnePie(context, colorlist[2], outer_radius, x, y, (-30)/180*Math.PI, (+90)/180*Math.PI, alpha); drawOnePie(context, colorlist[3], outer_radius, x, y, (+90)/180*Math.PI, (+210)/180*Math.PI, alpha); for(let i = 0; i<3; i++){ let angle = (-150+120*i)/180*Math.PI; let x1 = x + radius*Math.cos(angle); let y1 = y + radius*Math.sin(angle); let x2 = x + outer_radius*Math.cos(angle); let y2 = y + outer_radius*Math.sin(angle); // drawLine(context, "#ddd", x1, y1, x2 ,y2, 0.5); drawLine(context, colorlist[4], x1, y1, x2 ,y2, radius-inner_radius, alpha); } drawCircle(context, colorlist[4], radius, x, y, alpha); drawCircle(context, colorlist[0], inner_radius, x, y, alpha); //context.globalAlpha = original_globalAlpha; //let degree = 360 * value - 90; //drawOneArc(context, colorlist[5], outer_arc_radius, x, y, (-90)/180*Math.PI, degree/180*Math.PI); } function drawNodeGlyph_v1(context:any, colorlist:any, inner_radius:any, radius:any, outer_radius:any, x:any, y:any, enableStroke:boolean=false, outer_arc_encoded_value:any=0.5, outer_arc_radius:any=2, enable_alpha_mode=true){ let value = outer_arc_encoded_value; if(value<0) value = 0; else if(value>1) value = 1; let alpha = 1; if(enable_alpha_mode){ alpha = value; } if(enableStroke){ drawCircleStroke(context, "#000", outer_radius, x, y, 2); } drawCircle(context, colorlist[0], outer_radius, x, y, alpha); } function drawNodeGlyph(context:any, colorlist:any, inner_radius:any, radius:any, outer_radius:any, x:any, y:any, enableStroke:boolean=false, outer_arc_encoded_value:any=0.5, outer_arc_radius:any=2, enable_alpha_mode=true){ let value = outer_arc_encoded_value; //let original_globalAlpha = context.globalAlpha; if(value<0) value = 0; else if(value>1) value = 1; let alpha = 1; if(enable_alpha_mode){ alpha = value; } //context.globalAlpha = value; // Background circle // Pie chart drawing let length_model = colorlist.length - 1; if(length_model > 0){ drawCircle(context, "#fff", outer_radius, x, y, alpha); if(enableStroke){ drawCircleStroke(context, "#000", outer_radius, x, y, 2); } let step_angle = 360 / length_model; let current_angle = -90 - step_angle / 2; for(let i = 1; i<colorlist.length; i++){ let start_angle = current_angle; let end_angle = start_angle + step_angle; drawOnePie(context, colorlist[i], outer_radius, x, y, (start_angle)/180*Math.PI, (end_angle)/180*Math.PI, alpha); current_angle = end_angle; } if(length_model > 1){ current_angle = -90 - step_angle / 2; for(let i = 1; i<colorlist.length; i++){ let angle = (current_angle)/180*Math.PI; let x1 = x + radius*Math.cos(angle); let y1 = y + radius*Math.sin(angle); let x2 = x + outer_radius*Math.cos(angle); let y2 = y + outer_radius*Math.sin(angle); // drawLine(context, "#ddd", x1, y1, x2 ,y2, 0.5); drawLine(context, "#fff", x1, y1, x2 ,y2, radius-inner_radius, alpha); current_angle = current_angle + step_angle; } } drawCircle(context, "#fff", radius, x, y, alpha); drawCircle(context, colorlist[0], inner_radius, x, y, alpha); }else{ drawCircle(context, colorlist[0], outer_radius, x, y, alpha); if(enableStroke){ drawCircleStroke(context, "#000", outer_radius, x, y, 2); } //drawCircle(context, colorlist[0], radius, x, y, alpha); //drawCircle(context, colorlist[0], inner_radius, x, y, alpha); } */ function drawNodeGlyph(context:any, colorlist:any, inner_radius:any, radius:any, outer_radius:any, x:any, y:any, enableStroke:boolean=false, outer_arc_encoded_value:any=0.5, outer_arc_radius:any=2, enable_alpha_mode=true){ let value = outer_arc_encoded_value; //let original_globalAlpha = context.globalAlpha; if(value<0) value = 0; else if(value>1) value = 1; let alpha = 1; if(enable_alpha_mode){ alpha = value; } //context.globalAlpha = value; // Background circle // Pie chart drawing let length_model = colorlist.length - 1; if(length_model > 0){ drawCircle(context, "#fff", outer_radius, x, y, alpha); if(enableStroke){ drawCircleStroke(context, "#000", outer_radius, x, y, 2); } let step_angle = 360 / length_model; let current_angle = -90 - step_angle / 2; for(let i = 1; i<colorlist.length; i++){ let start_angle = current_angle; let end_angle = start_angle + step_angle; drawOnePie(context, colorlist[i], outer_radius, x, y, (start_angle)/180*Math.PI, (end_angle)/180*Math.PI, alpha); current_angle = end_angle; } if(length_model > 1){ current_angle = -90 - step_angle / 2; for(let i = 1; i<colorlist.length; i++){ let angle = (current_angle)/180*Math.PI; let x1 = x + radius*Math.cos(angle); let y1 = y + radius*Math.sin(angle); let x2 = x + outer_radius*Math.cos(angle); let y2 = y + outer_radius*Math.sin(angle); // drawLine(context, "#ddd", x1, y1, x2 ,y2, 0.5); drawLine(context, "#fff", x1, y1, x2 ,y2, radius-inner_radius, alpha); current_angle = current_angle + step_angle; } } drawCircle(context, "#fff", radius, x, y, alpha); drawCircle(context, colorlist[0], inner_radius, x, y, alpha); }else{ drawCircle(context, colorlist[0], outer_radius, x, y, alpha); if(enableStroke){ drawCircleStroke(context, "#000", outer_radius, x, y, 2); } //drawCircle(context, colorlist[0], radius, x, y, alpha); //drawCircle(context, colorlist[0], inner_radius, x, y, alpha); } //context.globalAlpha = original_globalAlpha; //let degree = 360 * value - 90; //drawOneArc(context, colorlist[5], outer_arc_radius, x, y, (-90)/180*Math.PI, degree/180*Math.PI); } function drawLine(context:any, color:any, x1:any, y1:any, x2:any, y2:any, linewidth:any=null, weight:any=1){ let original_globalAlpha = context.globalAlpha; let value = weight; if(value<0) value = 0; else if(value>1) value = 1; context.globalAlpha = value; context.strokeStyle = color; if(linewidth){ context.lineWidth = linewidth; } context.beginPath(); context.moveTo(x1, y1); context.lineTo(x2, y2); context.stroke(); context.globalAlpha = original_globalAlpha; } export {drawRectStroke, drawRect, drawCircleStroke, drawCircle, drawOnePie, drawOneArc, drawNodeGlyph, drawLine }
the_stack
import * as ui from "../../ui"; import * as csx from "../../base/csx"; import * as React from "react"; import * as tab from "./tab"; import {server,cast} from "../../../socket/socketClient"; import * as commands from "../../commands/commands"; import * as utils from "../../../common/utils"; import * as d3 from "d3"; import * as $ from "jquery"; import * as styles from "../../styles/styles"; import * as onresize from "onresize"; import {ErrorMessage} from "../errorMessage"; import {Clipboard} from "../../components/clipboard"; import * as typestyle from "typestyle"; import {Types} from "../../../socket/socketContract"; export const noFocusOutlineClassName = typestyle.style(styles.noFocusOutlineBase as any); type NodeDisplay = Types.NodeDisplay; let EOL = '\n'; /** * The styles */ require('./astView.less'); export interface Props extends tab.TabProps { } export interface State { selectedNode?: Types.NodeDisplay; text?:string; error?: string; } export class ASTView extends ui.BaseComponent<Props, State> { constructor(props: Props) { super(props); let {protocol,filePath} = utils.getFilePathAndProtocolFromUrl(props.url); this.mode = protocol === 'ast' ? Types.ASTMode.visitor : Types.ASTMode.children; this.filePath = filePath; this.state = { }; } refs: { [string: string]: any; root: HTMLDivElement; graphRoot: HTMLDivElement; } filePath: string; mode: Types.ASTMode; astViewRenderer : ASTViewRenderer; componentDidMount() { const reloadData = () => { this.setState({ error: null }); server.openFile({ filePath: this.filePath }).then(res => { this.setState({ text: res.contents }); }); server.getAST({ mode: this.mode, filePath: this.filePath }) .then((res) => { this.astViewRenderer = new ASTViewRenderer({ rootNode: res.root, _mainContent: $(this.refs.graphRoot), display: this.display }) }) .catch((err) => { this.setState({ error: `Failed to get the AST details for the file ${this.filePath}. Make sure it is in the active project. Change project using Alt+Shift+P.` }); }); }; const reloadDataDebounced = utils.debounce(reloadData, 2000); reloadData(); this.disposible.add( cast.activeProjectConfigDetailsUpdated.on(()=>{ reloadDataDebounced(); }) ); this.disposible.add( commands.fileContentsChanged.on((res) => { if (res.filePath === this.filePath) { reloadDataDebounced(); } }) ); // Listen to tab events const api = this.props.api; this.disposible.add(api.resize.on(this.resize)); this.disposible.add(api.focus.on(this.focus)); this.disposible.add(api.save.on(this.save)); this.disposible.add(api.close.on(this.close)); this.disposible.add(api.gotoPosition.on(this.gotoPosition)); // Listen to search tab events this.disposible.add(api.search.doSearch.on(this.search.doSearch)); this.disposible.add(api.search.hideSearch.on(this.search.hideSearch)); this.disposible.add(api.search.findNext.on(this.search.findNext)); this.disposible.add(api.search.findPrevious.on(this.search.findPrevious)); this.disposible.add(api.search.replaceNext.on(this.search.replaceNext)); this.disposible.add(api.search.replacePrevious.on(this.search.replacePrevious)); this.disposible.add(api.search.replaceAll.on(this.search.replaceAll)); } render() { let node = this.state.selectedNode; var display = node ? ` ${node.kind} -------------------- AST -------------------- ${node.rawJson} -------------------- TEXT ------------------- ${this.state.text.substring(node.pos, node.end)} `.trim() : "The selected AST node details will go here"; const content = this.state.error ? <ErrorMessage text={this.state.error}/> : <div style={csx.extend(csx.flex,csx.horizontal, {maxWidth: '100%'})}> <div style={csx.extend(csx.flex,csx.scroll)} ref="graphRoot" className="ast-view"> { // The ast tree view goes here } </div> <div style={csx.extend(csx.flex,csx.flexRoot,csx.scroll,styles.padded1,{background:'white'})}> <pre style={csx.extend(csx.flex,{margin:'0px'})}> {display} </pre> </div> </div> return ( <div ref="root" tabIndex={0} className={noFocusOutlineClassName} style={csx.extend(csx.horizontal,csx.flex, styles.someChildWillScroll)}> {content} </div> ); } display = (node: Types.NodeDisplay)=>{ this.setState({selectedNode:node}) } /** * TAB implementation */ resize = () => { // This layout doesn't need it } focus = () => { this.refs.root.focus(); // if its not there its because an XHR is lagging and it will show up when that xhr completes anyways this.astViewRenderer && this.astViewRenderer.update(); } save = () => { } close = () => { } gotoPosition = (position: EditorPosition) => { } search = { doSearch: (options: FindOptions) => { // TODO }, hideSearch: () => { // TODO }, findNext: (options: FindOptions) => { }, findPrevious: (options: FindOptions) => { }, replaceNext: ({newText}: { newText: string }) => { }, replacePrevious: ({newText}: { newText: string }) => { }, replaceAll: ({newText}: { newText: string }) => { } } } class ASTViewRenderer { root: { dom: HTMLElement; jq: JQuery; }; // General D3 utlis tree = d3.layout.tree().nodeSize([0, 20]); diagonal = d3.svg.diagonal() .projection(function(d) { return [d.y, d.x]; }); // setup in Ctor rootNode: Types.NodeDisplay; svgRoot: d3.Selection<any>; graph: d3.Selection<any>; // vodoo i: number = 0; // layout constants margin = { top: 30, right: 20, bottom: 30, left: 20 }; barHeight = 30; duration = 400; constructor(public config:{rootNode: NodeDisplay, _mainContent: JQuery, display: (content: NodeDisplay) => void}) { config._mainContent.html(''); this.root ={ dom: config._mainContent[0], jq: config._mainContent }; this.rootNode = config.rootNode; this.svgRoot = d3.select(this.root.dom).append("svg"); this.graph = this.svgRoot.append("g") .attr("transform", "translate(" + this.margin.left + "," + this.margin.top + ")"); d3.select(this.root.dom).on("resize", this.update); // Kick off by selecting the root node this.select(this.rootNode); } selected: NodeDisplay; /** display details on click */ select = (node: NodeDisplay) => { this.config.display(node); this.selected = node; this.update(); } getWidth = () => this.root.jq.width() - this.margin.left - this.margin.right; update = () => { const width = this.getWidth(); // If width is less than 0 means its insignificant to render anyways. // Just return and way for update to be called again when it is significant if (width < 0) { return; } this.svgRoot.attr("width", width); const barWidth = width * .8; // Compute the flattened node list. TODO use d3.layout.hierarchy. var nodes:d3.layout.tree.Node[] = this.tree.nodes(this.rootNode); var height = Math.max(500, nodes.length * this.barHeight + this.margin.top + this.margin.bottom); this.svgRoot.transition() .duration(this.duration) .attr("height", height); d3.select(self.frameElement).transition() .duration(this.duration) .style("height", height + "px"); // Compute the "layout". nodes.forEach((n, i) => { n.x = i * this.barHeight; }); // Update the nodes… var node = this.graph.selectAll("g.node") .data(nodes, (d) => { return (d as any).id || ((d as any).id = ++this.i); }); var nodeEnter = node.enter().append("g") .attr("class", "node") .attr("transform", (d) => { return "translate(" + this.rootNode.depth + "," + this.rootNode.nodeIndex + ")"; }) .style("opacity", 1e-6); // Enter any new nodes at the parent's previous position. nodeEnter.append("rect") .attr("y", -this.barHeight / 2) .attr("height", this.barHeight) .attr("width", barWidth) .style("fill", this.color) .on("click", this.select); nodeEnter.append("text") .attr("dy", 3.5) .attr("dx", 5.5) .text(function(d: NodeDisplay) { return d.kind; }); // Transition nodes to their new position. nodeEnter.transition() .duration(this.duration) .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; }) .style("opacity", 1); node.transition() .duration(this.duration) .attr("transform", function(d) { return "translate(" + d.y + "," + d.x + ")"; }) .style("opacity", 1) .select("rect") .style("fill", this.color); // Transition exiting nodes to the parent's new position. node.exit().transition() .duration(this.duration) .attr("transform", function(d) { return "translate(" + this.rootNode.nodeIndex + "," + this.rootNode.depth + ")"; }) .style("opacity", 1e-6) .remove(); // Update the links… var link = this.graph.selectAll("path.link") .data(this.tree.links(nodes), function(d) { return (d.target as any).id; }); // Enter any new links at the parent's previous position. link.enter().insert("path", "g") .attr("class", "link") .attr("d", (d) => { var o = { x: this.rootNode.depth, y: this.rootNode.nodeIndex }; return (this.diagonal as any)({ source: o, target: o }); }) .transition() .duration(this.duration) .attr("d", this.diagonal); // Transition links to their new position. link.transition() .duration(this.duration) .attr("d", this.diagonal); // Transition exiting nodes to the parent's new position. link.exit().transition() .duration(this.duration) .attr("d", (d) => { var o = { x: this.rootNode.depth, y: this.rootNode.nodeIndex }; return (this.diagonal as any)({ source: o, target: o }); }).remove(); } color = (d: NodeDisplay) => { if (this.selected == d) { return "rgb(140, 0, 0)"; } return d.children ? "#000000" : "rgb(29, 166, 0)"; } }
the_stack
import { mat4, vec3 } from 'gl-matrix' import { Bsp } from '../Bsp' import { Camera } from './Camera' import { Context } from './Context' import { MainShader } from './WorldShader/WorldShader' import { RenderMode } from '../Parsers/BspEntityParser' import { Sprite, SpriteType } from '../Parsers/Sprite' import { isPowerOfTwo, nextPowerOfTwo, resizeTexture } from './Util' type FaceInfo = { offset: number length: number textureIndex: number } type ModelInfo = { origin: number[] offset: number length: number isTransparent: boolean faces: FaceInfo[] } type SceneInfo = { length: number data: Float32Array models: ModelInfo[] } export class WorldScene { static init(context: Context) { const shader = MainShader.init(context) if (!shader) { console.error('Failed to init MainShader') return null } shader.useProgram(context.gl) const buffer = context.gl.createBuffer() if (!buffer) { console.error('Failed to create WebGL buffer') return null } return new WorldScene({ buffer, context, shader }) } private buffer: WebGLBuffer private context: Context private shader: MainShader private modelMatrix: mat4 = mat4.create() private sceneInfo: SceneInfo = { length: 0, data: new Float32Array(0), models: [] } private bsp: Bsp | null = null private textures: { name: string width: number height: number data: Uint8Array handle: WebGLTexture }[] = [] private sprites: { [name: string]: Sprite } = {} private lightmap: { data: Uint8Array handle: WebGLTexture } | null = null private constructor(params: { context: Context buffer: WebGLBuffer shader: MainShader }) { this.buffer = params.buffer this.context = params.context this.shader = params.shader } changeMap(bsp: Bsp) { this.fillBuffer(bsp) this.loadTextures(bsp) this.loadSpriteTextures(bsp) this.loadLightmap(bsp) this.bsp = bsp } private fillBuffer(bsp: Bsp) { const gl = this.context.gl const models = bsp.models const INVISIBLE_TEXTURES = [ 'aaatrigger', 'clip', 'null', 'hint', 'nodraw', 'invisible', 'skip', 'trigger', 'sky', 'fog' ] // get total buffer size let size = 0 for (let i = 0; i < models.length; ++i) { const model = models[i] for (let j = 0; j < model.faces.length; ++j) { const texture = bsp.textures[model.faces[j].textureIndex] if (INVISIBLE_TEXTURES.indexOf(texture.name) > -1) { continue } size += model.faces[j].buffer.length } } // add 6 vertex for a single quad that will be used to render sprites size += 7 * 6 // init scene info structure and buffer with the appropriate size const sceneInfo: SceneInfo = { length: size, data: new Float32Array(size), models: [] } // fill the scene info structure let currentVertex = 0 for (let i = 0; i < bsp.models.length; ++i) { const model = bsp.models[i] const modelInfo: ModelInfo = { origin: model.origin, offset: currentVertex, length: 0, isTransparent: false, faces: [] } for (let j = 0; j < model.faces.length; ++j) { const texture = bsp.textures[model.faces[j].textureIndex] if (INVISIBLE_TEXTURES.indexOf(texture.name) > -1) { continue } const faceInfo: FaceInfo = { offset: currentVertex, length: 0, textureIndex: -1 } for (let k = 0; k < model.faces[j].buffer.length; ++k) { sceneInfo.data[currentVertex++] = model.faces[j].buffer[k] } if ( !modelInfo.isTransparent && bsp.textures[model.faces[j].textureIndex].name[0] === '{' ) { modelInfo.isTransparent = true } faceInfo.textureIndex = model.faces[j].textureIndex faceInfo.length = currentVertex - faceInfo.offset modelInfo.faces.push(faceInfo) } modelInfo.length = currentVertex - modelInfo.offset sceneInfo.models.push(modelInfo) } // set data of the last quad used for rendering sprites sceneInfo.models.push({ origin: [0, 0, 0], offset: currentVertex, length: 4, isTransparent: false, // unused faces: [ { offset: currentVertex, length: 4, textureIndex: 0 // unused } ] }) sceneInfo.data[currentVertex++] = -0.5 sceneInfo.data[currentVertex++] = 0 sceneInfo.data[currentVertex++] = -0.5 sceneInfo.data[currentVertex++] = 1 sceneInfo.data[currentVertex++] = 1 sceneInfo.data[currentVertex++] = 0 sceneInfo.data[currentVertex++] = 0 sceneInfo.data[currentVertex++] = 0.5 sceneInfo.data[currentVertex++] = 0 sceneInfo.data[currentVertex++] = 0.5 sceneInfo.data[currentVertex++] = 0 sceneInfo.data[currentVertex++] = 0 sceneInfo.data[currentVertex++] = 0 sceneInfo.data[currentVertex++] = 0 sceneInfo.data[currentVertex++] = -0.5 sceneInfo.data[currentVertex++] = 0 sceneInfo.data[currentVertex++] = 0.5 sceneInfo.data[currentVertex++] = 1 sceneInfo.data[currentVertex++] = 0 sceneInfo.data[currentVertex++] = 0 sceneInfo.data[currentVertex++] = 0 sceneInfo.data[currentVertex++] = -0.5 sceneInfo.data[currentVertex++] = 0 sceneInfo.data[currentVertex++] = -0.5 sceneInfo.data[currentVertex++] = 1 sceneInfo.data[currentVertex++] = 1 sceneInfo.data[currentVertex++] = 0 sceneInfo.data[currentVertex++] = 0 sceneInfo.data[currentVertex++] = 0.5 sceneInfo.data[currentVertex++] = 0 sceneInfo.data[currentVertex++] = -0.5 sceneInfo.data[currentVertex++] = 0 sceneInfo.data[currentVertex++] = 1 sceneInfo.data[currentVertex++] = 0 sceneInfo.data[currentVertex++] = 0 sceneInfo.data[currentVertex++] = 0.5 sceneInfo.data[currentVertex++] = 0 sceneInfo.data[currentVertex++] = 0.5 sceneInfo.data[currentVertex++] = 0 sceneInfo.data[currentVertex++] = 0 sceneInfo.data[currentVertex++] = 0 sceneInfo.data[currentVertex++] = 0 // sort each model's face in scene info structure by texture index // and merge faces with same texture to lower draw calls currentVertex = 0 const sortedSceneInfo: SceneInfo = { data: new Float32Array(sceneInfo.data), length: sceneInfo.length, models: sceneInfo.models.map(model => ({ origin: [...model.origin], offset: model.offset, length: model.length, isTransparent: model.isTransparent, faces: model.faces.map(face => ({ offset: face.offset, length: face.length, textureIndex: face.textureIndex })) })) } for (let i = 0; i < sortedSceneInfo.models.length; ++i) { const model = sortedSceneInfo.models[i] model.faces.sort((a, b) => a.textureIndex - b.textureIndex) for (let j = 0; j < model.faces.length; ++j) { const face = model.faces[j] const newOffset = currentVertex for (let k = 0; k < face.length; ++k) { sortedSceneInfo.data[currentVertex] = sceneInfo.data[face.offset + k] currentVertex += 1 } face.offset = newOffset } const newFaces: FaceInfo[] = [] let currentTextureIndex = -1 for (let j = 0; j < model.faces.length; ++j) { const face = model.faces[j] if (face.textureIndex === currentTextureIndex) { newFaces[newFaces.length - 1].length += face.length } else { // merge newFaces.push({ offset: face.offset, length: face.length, textureIndex: face.textureIndex }) currentTextureIndex = face.textureIndex } } model.faces = newFaces } this.sceneInfo = sortedSceneInfo gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer) gl.bufferData(gl.ARRAY_BUFFER, this.sceneInfo.data, gl.STATIC_DRAW) } private loadTextures(bsp: Bsp) { const gl = this.context.gl for (let i = 0; i < bsp.textures.length; ++i) { const glTexture = gl.createTexture() if (!glTexture) { // shouldnt happen // TODO: handle better throw new Error('fatal error') } const texture = bsp.textures[i] if (!isPowerOfTwo(texture.width) || !isPowerOfTwo(texture.height)) { const w = texture.width const h = texture.height const nw = nextPowerOfTwo(texture.width) const nh = nextPowerOfTwo(texture.height) texture.data = resizeTexture(texture.data, w, h, nw, nh) texture.width = nw texture.height = nh } gl.bindTexture(gl.TEXTURE_2D, glTexture) gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, texture.width, texture.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, texture.data ) gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR) gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR ) gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT) gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT) gl.generateMipmap(gl.TEXTURE_2D) const anisotropy = this.context.getAnisotropyExtension() if (anisotropy) { gl.texParameteri( gl.TEXTURE_2D, anisotropy.TEXTURE_MAX_ANISOTROPY_EXT, this.context.getMaxAnisotropy(anisotropy) ) } this.textures.push({ name: texture.name, width: texture.width, height: texture.height, data: texture.data, handle: glTexture }) } } private loadSpriteTextures(bsp: Bsp) { const gl = this.context.gl for (const [name, sprite] of Object.entries(bsp.sprites)) { const glTexture = gl.createTexture() if (!glTexture) { // shouldnt happen // TODO: handle better throw new Error('fatal error') } const texture = sprite.frames[0] if (!isPowerOfTwo(texture.width) || !isPowerOfTwo(texture.height)) { const w = texture.width const h = texture.height const nw = nextPowerOfTwo(texture.width) const nh = nextPowerOfTwo(texture.height) texture.data = resizeTexture(texture.data, w, h, nw, nh) texture.width = nw texture.height = nh } gl.bindTexture(gl.TEXTURE_2D, glTexture) gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, texture.width, texture.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, texture.data ) gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR) gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR ) gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT) gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT) gl.generateMipmap(gl.TEXTURE_2D) const anisotropy = this.context.getAnisotropyExtension() if (anisotropy) { gl.texParameteri( gl.TEXTURE_2D, anisotropy.TEXTURE_MAX_ANISOTROPY_EXT, this.context.getMaxAnisotropy(anisotropy) ) } this.textures.push({ name: name, width: texture.width, height: texture.height, data: texture.data, handle: glTexture }) this.sprites[name] = sprite } } private loadLightmap(bsp: Bsp) { const gl = this.context.gl const glLightmap = gl.createTexture() if (!glLightmap) { // shouldnt happen // TODO: handle better throw new Error('fatal error') } gl.bindTexture(gl.TEXTURE_2D, glLightmap) gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, bsp.lightmap.width, bsp.lightmap.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, bsp.lightmap.data ) gl.generateMipmap(gl.TEXTURE_2D) gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR) gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR ) this.lightmap = { data: bsp.lightmap.data, handle: glLightmap } } draw(camera: Camera, entities: any[]) { if (!this.bsp || !this.lightmap) { return } const gl = this.context.gl const shader = this.shader shader.useProgram(gl) camera.updateProjectionMatrix() camera.updateViewMatrix() shader.setViewMatrix(gl, camera.viewMatrix) shader.setProjectionMatrix(gl, camera.projectionMatrix) gl.bindBuffer(gl.ARRAY_BUFFER, this.buffer) shader.enableVertexAttribs(gl) shader.setVertexAttribPointers(gl) shader.setDiffuse(gl, 0) shader.setLightmap(gl, 1) gl.activeTexture(gl.TEXTURE1) gl.bindTexture(gl.TEXTURE_2D, this.lightmap.handle) gl.activeTexture(gl.TEXTURE0) const opaqueEntities = [] const transparentEntities = [] for (let i = 1; i < entities.length; ++i) { const e = entities[i] if (e.model) { if ( !e.rendermode || e.rendermode == RenderMode.Normal || e.rendermode == RenderMode.Solid ) { if (e.model[0] === '*') { const model = this.sceneInfo.models[parseInt(e.model.substr(1))] if (model.isTransparent) { transparentEntities.push(e) continue } } else if (e.model.indexOf('.spr') > -1) { transparentEntities.push(e) continue } opaqueEntities.push(e) } else if (e.rendermode == RenderMode.Additive) { transparentEntities.push(e) } else { transparentEntities.push(e) } } } shader.setOpacity(gl, 1.0) this.renderWorldSpawn() this.renderOpaqueEntities(camera, opaqueEntities) if (transparentEntities.length) { gl.depthMask(false) this.renderTransparentEntities(transparentEntities, camera) gl.depthMask(true) } } private renderWorldSpawn() { const model = this.sceneInfo.models[0] const gl = this.context.gl mat4.identity(this.modelMatrix) this.shader.setModelMatrix(gl, this.modelMatrix) for (let j = 0; j < model.faces.length; ++j) { const face = model.faces[j] gl.bindTexture(gl.TEXTURE_2D, this.textures[face.textureIndex].handle) gl.drawArrays(gl.TRIANGLES, face.offset / 7, face.length / 7) } } private renderOpaqueEntities(camera: Camera, entities: any[]) { const gl = this.context.gl const shader = this.shader const mmx = this.modelMatrix for (let i = 0; i < entities.length; ++i) { const entity = entities[i] const modelIndex = parseInt(entity.model.substr(1)) const model = this.sceneInfo.models[modelIndex] if (model) { const angles = entity.angles || [0, 0, 0] const origin = entity.origin ? vec3.fromValues( entity.origin[0], entity.origin[1], entity.origin[2] ) : vec3.create() vec3.add(origin, origin, model.origin) // TODO: this seems to work, but needs further research mat4.identity(mmx) mat4.translate(mmx, mmx, origin) // mat4.rotateY(mmx, mmx, (angles[0] * Math.PI) / 180) // dunno this mat4.rotateZ(mmx, mmx, (angles[1] * Math.PI) / 180) mat4.rotateX( this.modelMatrix, this.modelMatrix, (angles[2] * Math.PI) / 180 ) shader.setModelMatrix(gl, this.modelMatrix) for (let j = 0; j < model.faces.length; ++j) { const face = model.faces[j] gl.bindTexture(gl.TEXTURE_2D, this.textures[face.textureIndex].handle) gl.drawArrays(gl.TRIANGLES, face.offset / 7, face.length / 7) } } else if (entity.model.indexOf('.spr') > -1) { const texture = this.textures.find(a => a.name === entity.model) const sprite = this.sprites[entity.model] if (texture && sprite) { const origin = entity.origin ? vec3.fromValues( entity.origin[0], entity.origin[1], entity.origin[2] ) : vec3.create() const scale = vec3.fromValues(texture.width, 1, texture.height) const angles = entity.angles ? vec3.fromValues( entity.angles[0], entity.angles[2], entity.angles[1] ) : vec3.create() vec3.scale(scale, scale, entity.scale || 1) mat4.identity(mmx) mat4.translate(mmx, mmx, origin) switch (sprite.header.type) { case SpriteType.VP_PARALLEL_UPRIGHT: { // TODO: incorrect, but will do for now mat4.rotateZ(mmx, mmx, camera.rotation[1] + Math.PI / 2) break } case SpriteType.FACING_UPRIGHT: { // TODO: fix incorrect mat4.rotateZ(mmx, mmx, camera.rotation[1] + Math.PI / 2) break } case SpriteType.VP_PARALLEL: { mat4.rotateZ( mmx, mmx, Math.atan2( origin[1] - camera.position[1], origin[0] - camera.position[0] ) + Math.PI / 2 ) mat4.rotateX( mmx, mmx, Math.atan2( camera.position[2] - origin[2], Math.sqrt( Math.pow(camera.position[0] - origin[0], 2) + Math.pow(camera.position[1] - origin[1], 2) ) ) ) break } case SpriteType.ORIENTED: { mat4.rotateY(mmx, mmx, (angles[0] * Math.PI) / 180 + Math.PI) mat4.rotateZ(mmx, mmx, (angles[1] * Math.PI) / 180 + Math.PI) mat4.rotateX(mmx, mmx, (angles[2] * Math.PI) / 180 - Math.PI / 2) break } case SpriteType.VP_PARALLEL_ORIENTED: { mat4.rotateY(mmx, mmx, (angles[0] * Math.PI) / 180 + Math.PI) mat4.rotateZ(mmx, mmx, (angles[1] * Math.PI) / 180 + Math.PI) break } default: { throw new Error('Invalid sprite type') } } mat4.scale(mmx, mmx, scale) shader.setModelMatrix(gl, mmx) shader.setOpacity(gl, (entity.renderamt || 255) / 255) const renderMode = entity.rendermode || RenderMode.Normal switch (renderMode) { case RenderMode.Normal: { shader.setOpacity(gl, 1) gl.bindTexture(gl.TEXTURE_2D, texture.handle) gl.drawArrays( gl.TRIANGLES, this.sceneInfo.models[this.sceneInfo.models.length - 1].offset / 7, 6 ) break } case RenderMode.Color: { // TODO: not properly implemented shader.setOpacity(gl, (entity.renderamt || 255) / 255) gl.bindTexture(gl.TEXTURE_2D, texture.handle) gl.drawArrays( gl.TRIANGLES, this.sceneInfo.models[this.sceneInfo.models.length - 1].offset / 7, 6 ) break } case RenderMode.Texture: { shader.setOpacity(gl, (entity.renderamt || 255) / 255) gl.bindTexture(gl.TEXTURE_2D, texture.handle) gl.drawArrays( gl.TRIANGLES, this.sceneInfo.models[this.sceneInfo.models.length - 1].offset / 7, 6 ) break } case RenderMode.Glow: { // TODO: not properly implemented gl.blendFunc(gl.SRC_ALPHA, gl.DST_ALPHA) shader.setOpacity(gl, (entity.renderamt || 255) / 255) gl.bindTexture(gl.TEXTURE_2D, texture.handle) gl.drawArrays( gl.TRIANGLES, this.sceneInfo.models[this.sceneInfo.models.length - 1].offset / 7, 6 ) gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA) break } case RenderMode.Solid: { // TODO: not properly implemented shader.setOpacity(gl, (entity.renderamt || 255) / 255) gl.bindTexture(gl.TEXTURE_2D, texture.handle) gl.drawArrays( gl.TRIANGLES, this.sceneInfo.models[this.sceneInfo.models.length - 1].offset / 7, 6 ) break } case RenderMode.Additive: { gl.blendFunc(gl.SRC_ALPHA, gl.DST_ALPHA) shader.setOpacity(gl, (entity.renderamt || 255) / 255) gl.bindTexture(gl.TEXTURE_2D, texture.handle) gl.drawArrays( gl.TRIANGLES, this.sceneInfo.models[this.sceneInfo.models.length - 1].offset / 7, 6 ) gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA) break } } } } } } private renderTransparentEntities(entities: any[], camera: Camera) { const gl = this.context.gl const shader = this.shader const mmx = this.modelMatrix // distances of all entities from the camera const entityDistances: { index: number distance: number }[] = entities .map((e, i) => ({ index: i, distance: vec3.dist(camera.position, e.origin || [0, 0, 0]) })) .sort((a, b) => a.distance - b.distance) for (let i = 0; i < entityDistances.length; ++i) { const entity = entities[entityDistances[i].index] const modelIndex = parseInt(entity.model.substr(1)) const model = this.sceneInfo.models[modelIndex] if (model) { const angles = entity.angles || [0, 0, 0] const origin = entity.origin || [0, 0, 0] origin[0] += model.origin[0] origin[1] += model.origin[1] origin[2] += model.origin[2] // TODO: this seems to work, but needs further research mat4.identity(mmx) mat4.translate(mmx, mmx, origin) mat4.rotateZ(mmx, mmx, (angles[1] * Math.PI) / 180) // mat4.rotateY(mmx, mmx, (angles[2] * Math.PI) / 180) // dunno this mat4.rotateX( this.modelMatrix, this.modelMatrix, (angles[2] * Math.PI) / 180 ) shader.setModelMatrix(gl, this.modelMatrix) const renderMode = entity.rendermode || RenderMode.Normal switch (renderMode) { case RenderMode.Normal: { shader.setOpacity(gl, 1) for (let j = 0; j < model.faces.length; ++j) { const face = model.faces[j] gl.bindTexture( gl.TEXTURE_2D, this.textures[face.textureIndex].handle ) gl.drawArrays(gl.TRIANGLES, face.offset / 7, face.length / 7) } break } case RenderMode.Color: { // TODO: not properly implemented shader.setOpacity(gl, (entity.renderamt || 255) / 255) for (let j = 0; j < model.faces.length; ++j) { const face = model.faces[j] gl.bindTexture( gl.TEXTURE_2D, this.textures[face.textureIndex].handle ) gl.drawArrays(gl.TRIANGLES, face.offset / 7, face.length / 7) } break } case RenderMode.Texture: { shader.setOpacity(gl, (entity.renderamt || 255) / 255) for (let j = 0; j < model.faces.length; ++j) { const face = model.faces[j] gl.bindTexture( gl.TEXTURE_2D, this.textures[face.textureIndex].handle ) gl.drawArrays(gl.TRIANGLES, face.offset / 7, face.length / 7) } break } case RenderMode.Glow: { // TODO: not properly implemented shader.setOpacity(gl, (entity.renderamt || 255) / 255) for (let j = 0; j < model.faces.length; ++j) { const face = model.faces[j] gl.bindTexture( gl.TEXTURE_2D, this.textures[face.textureIndex].handle ) gl.drawArrays(gl.TRIANGLES, face.offset / 7, face.length / 7) } break } case RenderMode.Solid: { // TODO: not properly implemented shader.setOpacity(gl, (entity.renderamt || 255) / 255) for (let j = 0; j < model.faces.length; ++j) { const face = model.faces[j] gl.bindTexture( gl.TEXTURE_2D, this.textures[face.textureIndex].handle ) gl.drawArrays(gl.TRIANGLES, face.offset / 7, face.length / 7) } break } case RenderMode.Additive: { gl.blendFunc(gl.SRC_ALPHA, gl.DST_ALPHA) shader.setOpacity(gl, (entity.renderamt || 255) / 255) for (let j = 0; j < model.faces.length; ++j) { const face = model.faces[j] gl.bindTexture( gl.TEXTURE_2D, this.textures[face.textureIndex].handle ) gl.drawArrays(gl.TRIANGLES, face.offset / 7, face.length / 7) } gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA) break } } } else if (entity.model.indexOf('.spr') > -1) { const texture = this.textures.find(a => a.name === entity.model) const sprite = this.sprites[entity.model] if (texture && sprite) { const origin = entity.origin ? vec3.fromValues( entity.origin[0], entity.origin[1], entity.origin[2] ) : vec3.create() const scale = vec3.fromValues(texture.width, 1, texture.height) const angles = entity.angles ? vec3.fromValues( entity.angles[0], entity.angles[2], entity.angles[1] ) : vec3.create() vec3.scale(scale, scale, entity.scale || 1) mat4.identity(mmx) mat4.translate(mmx, mmx, origin) switch (sprite.header.type) { case SpriteType.VP_PARALLEL_UPRIGHT: { // TODO: incorrect, but will do for now mat4.rotateZ(mmx, mmx, camera.rotation[1] + Math.PI / 2) break } case SpriteType.FACING_UPRIGHT: { // TODO: fix incorrect mat4.rotateZ(mmx, mmx, camera.rotation[1] + Math.PI / 2) break } case SpriteType.VP_PARALLEL: { mat4.rotateZ( mmx, mmx, Math.atan2( origin[1] - camera.position[1], origin[0] - camera.position[0] ) + Math.PI / 2 ) mat4.rotateX( mmx, mmx, Math.atan2( camera.position[2] - origin[2], Math.sqrt( Math.pow(camera.position[0] - origin[0], 2) + Math.pow(camera.position[1] - origin[1], 2) ) ) ) break } case SpriteType.ORIENTED: { mat4.rotateY(mmx, mmx, (angles[0] * Math.PI) / 180 + Math.PI) mat4.rotateZ(mmx, mmx, (angles[1] * Math.PI) / 180 + Math.PI) mat4.rotateX(mmx, mmx, (angles[2] * Math.PI) / 180 - Math.PI / 2) break } case SpriteType.VP_PARALLEL_ORIENTED: { mat4.rotateY(mmx, mmx, (angles[0] * Math.PI) / 180 + Math.PI) mat4.rotateZ(mmx, mmx, (angles[1] * Math.PI) / 180 + Math.PI) break } default: { throw new Error('Invalid sprite type') } } mat4.scale(mmx, mmx, scale) shader.setModelMatrix(gl, mmx) shader.setOpacity(gl, (entity.renderamt || 255) / 255) const renderMode = entity.rendermode || RenderMode.Normal switch (renderMode) { case RenderMode.Normal: { shader.setOpacity(gl, 1) gl.bindTexture(gl.TEXTURE_2D, texture.handle) gl.drawArrays( gl.TRIANGLES, this.sceneInfo.models[this.sceneInfo.models.length - 1].offset / 7, 6 ) break } case RenderMode.Color: { // TODO: not properly implemented shader.setOpacity(gl, (entity.renderamt || 255) / 255) gl.bindTexture(gl.TEXTURE_2D, texture.handle) gl.drawArrays( gl.TRIANGLES, this.sceneInfo.models[this.sceneInfo.models.length - 1].offset / 7, 6 ) break } case RenderMode.Texture: { shader.setOpacity(gl, (entity.renderamt || 255) / 255) gl.bindTexture(gl.TEXTURE_2D, texture.handle) gl.drawArrays( gl.TRIANGLES, this.sceneInfo.models[this.sceneInfo.models.length - 1].offset / 7, 6 ) break } case RenderMode.Glow: { // TODO: not properly implemented gl.blendFunc(gl.SRC_ALPHA, gl.DST_ALPHA) shader.setOpacity(gl, (entity.renderamt || 255) / 255) gl.bindTexture(gl.TEXTURE_2D, texture.handle) gl.drawArrays( gl.TRIANGLES, this.sceneInfo.models[this.sceneInfo.models.length - 1].offset / 7, 6 ) gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA) break } case RenderMode.Solid: { // TODO: not properly implemented shader.setOpacity(gl, (entity.renderamt || 255) / 255) gl.bindTexture(gl.TEXTURE_2D, texture.handle) gl.drawArrays( gl.TRIANGLES, this.sceneInfo.models[this.sceneInfo.models.length - 1].offset / 7, 6 ) break } case RenderMode.Additive: { gl.blendFunc(gl.SRC_ALPHA, gl.DST_ALPHA) shader.setOpacity(gl, (entity.renderamt || 255) / 255) gl.bindTexture(gl.TEXTURE_2D, texture.handle) gl.drawArrays( gl.TRIANGLES, this.sceneInfo.models[this.sceneInfo.models.length - 1].offset / 7, 6 ) gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA) break } } } } } } }
the_stack
import * as diffpatch from 'jsondiffpatch'; import { Identifier, StixObject } from '../stix'; export interface ITrackedItem { name: string; diff: diffpatch.Delta; original: any; } export interface IDialogEventData { self: any; } const html_style = `<style> .jsondiffpatch-delta { font-family: 'Bitstream Vera Sans Mono', 'DejaVu Sans Mono', Monaco, Courier, monospace; font-size: 12px; margin: 0; padding: 0 0 0 12px; display: inline-block; } .jsondiffpatch-delta pre { font-family: 'Bitstream Vera Sans Mono', 'DejaVu Sans Mono', Monaco, Courier, monospace; font-size: 12px; margin: 0; padding: 0; display: inline-block; } ul.jsondiffpatch-delta { list-style-type: none; padding: 0 0 0 20px; margin: 0; } .jsondiffpatch-delta ul { list-style-type: none; padding: 0 0 0 20px; margin: 0; } .jsondiffpatch-added .jsondiffpatch-property-name, .jsondiffpatch-added .jsondiffpatch-value pre, .jsondiffpatch-modified .jsondiffpatch-right-value pre, .jsondiffpatch-textdiff-added { background: #bbffbb; } .jsondiffpatch-deleted .jsondiffpatch-property-name, .jsondiffpatch-deleted pre, .jsondiffpatch-modified .jsondiffpatch-left-value pre, .jsondiffpatch-textdiff-deleted { background: #ffbbbb; text-decoration: line-through; } .jsondiffpatch-unchanged, .jsondiffpatch-movedestination { color: gray; } .jsondiffpatch-unchanged, .jsondiffpatch-movedestination > .jsondiffpatch-value { transition: all 0.5s; -webkit-transition: all 0.5s; overflow-y: hidden; } .jsondiffpatch-unchanged-showing .jsondiffpatch-unchanged, .jsondiffpatch-unchanged-showing .jsondiffpatch-movedestination > .jsondiffpatch-value { max-height: 100px; } .jsondiffpatch-unchanged-hidden .jsondiffpatch-unchanged, .jsondiffpatch-unchanged-hidden .jsondiffpatch-movedestination > .jsondiffpatch-value { max-height: 0; } .jsondiffpatch-unchanged-hiding .jsondiffpatch-movedestination > .jsondiffpatch-value, .jsondiffpatch-unchanged-hidden .jsondiffpatch-movedestination > .jsondiffpatch-value { display: block; } .jsondiffpatch-unchanged-visible .jsondiffpatch-unchanged, .jsondiffpatch-unchanged-visible .jsondiffpatch-movedestination > .jsondiffpatch-value { max-height: 100px; } .jsondiffpatch-unchanged-hiding .jsondiffpatch-unchanged, .jsondiffpatch-unchanged-hiding .jsondiffpatch-movedestination > .jsondiffpatch-value { max-height: 0; } .jsondiffpatch-unchanged-showing .jsondiffpatch-arrow, .jsondiffpatch-unchanged-hiding .jsondiffpatch-arrow { display: none; } .jsondiffpatch-value { display: inline-block; } .jsondiffpatch-property-name { display: inline-block; padding-right: 5px; vertical-align: top; } .jsondiffpatch-property-name:after { content: ': '; } .jsondiffpatch-child-node-type-array > .jsondiffpatch-property-name:after { content: ': ['; } .jsondiffpatch-child-node-type-array:after { content: '],'; } div.jsondiffpatch-child-node-type-array:before { content: '['; } div.jsondiffpatch-child-node-type-array:after { content: ']'; } .jsondiffpatch-child-node-type-object > .jsondiffpatch-property-name:after { content: ': {'; } .jsondiffpatch-child-node-type-object:after { content: '},'; } div.jsondiffpatch-child-node-type-object:before { content: '{'; } div.jsondiffpatch-child-node-type-object:after { content: '}'; } .jsondiffpatch-value pre:after { content: ','; } li:last-child > .jsondiffpatch-value pre:after, .jsondiffpatch-modified > .jsondiffpatch-left-value pre:after { content: ''; } .jsondiffpatch-modified .jsondiffpatch-value { display: inline-block; } .jsondiffpatch-modified .jsondiffpatch-right-value { margin-left: 5px; } .jsondiffpatch-moved .jsondiffpatch-value { display: none; } .jsondiffpatch-moved .jsondiffpatch-moved-destination { display: inline-block; background: #ffffbb; color: #888; } .jsondiffpatch-moved .jsondiffpatch-moved-destination:before { content: ' => '; } ul.jsondiffpatch-textdiff { padding: 0; } .jsondiffpatch-textdiff-location { color: #bbb; display: inline-block; min-width: 60px; } .jsondiffpatch-textdiff-line { display: inline-block; } .jsondiffpatch-textdiff-line-number:after { content: ','; } .jsondiffpatch-error { background: red; color: white; font-weight: bold; } </style>`; export class DiffDialog { public html: string; public tracked: { [key: string]: ITrackedItem }; public diffpatcher: diffpatch.DiffPatcher; public config: diffpatch.Config; private _anchor: JQuery<HTMLElement>; private _header: string = `${html_style} <div id="diff-list">`; private _footer: string = "</div>"; // + this._createUpdateDBButton(); constructor(anchor: JQuery) { this._anchor = anchor; this.html = this._header; this.tracked = {}; this.config = { arrays: { detectMove: true, includeValueOnMove: false, }, propertyFilter: (name: string, _context: diffpatch.DiffContext) => { if (name.startsWith('@', 0)) { return false; } return true; }, }; this.diffpatcher = new diffpatch.DiffPatcher(this.config); } public addDiff(id: Identifier, dif: diffpatch.Delta, orig: StixObject, name?: string) { if (id in this.tracked) { if (dif !== this.tracked[id]) { this.tracked[id].diff = dif; } } else { this.tracked[id] = { name: name || "", diff: dif, original: orig }; } } public clearId(id: Identifier) { if (id in this.tracked) { delete (this.tracked[id]); this._buildHTML(); this._anchor.html(this.html); ($("input[type='radio']") as any).checkboxradio(); } } public reset() { this.html = ''; this._anchor.html(''); this.tracked = {}; } private _buildHTML() { this.html = this._header; for (const k in this.tracked) { if (this.tracked.hasOwnProperty(k)) { const name = this.tracked[k].name ? this.tracked[k].name : k; const type = k.split("--", 1)[0]; const formatted = diffpatch.formatters.html.format(this.tracked[k].diff, this.tracked[k].original); const radiobutton = this._createRadioButton(k); this.html += `<h3>${type}: ${name}</h3> <div x-diff-key="${k}"> <fieldset> <p>ID: ${k}</p> ${formatted} ${radiobutton} </fieldset> </div>`; } } this.html += this._footer; } private _deleteSelected(e: JQueryEventObject) { e.preventDefault(); e.stopPropagation(); const self = e.data.self; const diff_idx = e.target.parentElement.getAttribute('x-diff-key'); self.clearId(diff_idx); self._buildHTML(); self._anchor.html(self.html) ($("input[type='radio']") as any).checkboxradio(); } private _createRadioButton(index: string) { const but: string = `<fieldset> <label for="radio-local-${index}"> Keep Local </label> <input type="radio" name="radio-${index}" id="radio-local-${index}"> <label for="radio-db-${index}"> Use DB </label> <input type="radio" name="radio-${index}" id="radio-db-${index}"> </fieldset>`; return but; } public open() { this._anchor.empty(); this._buildHTML(); this._anchor.html(this.html); ($("input[type='radio']") as any).checkboxradio(); this._anchor.dialog({ autoOpen: false }); this._anchor.dialog("option", { width: '50%', // height: '75%', maxHeight: window.innerHeight - 100, maxWidth: window.innerWidth / 2, buttons: [{ text: "Commit", id: "diff-dialog-commit-btn", click: (e: JQueryEventObject) => { this._doUpdateAsSelected(e); }, }, { text: "Close", click: this._close, }], }); this._anchor.dialog("open"); } private _close(_e: JQueryEventObject) { $(this).dialog("close"); } private _createDeleteButton(id: string): string { const ret = `<button type="button" title="Remove Selected" class="ui-button ui-widget ui-corner-all ui-button-icon-only btn-diff-delete" id="btn-diff-delete" x-diff-key="${id}" > ret += '<span class="ui-icon ui-icon-close"></span></button>`; return ret; } private _createUpdateDBButton(): string { const ret = `<button type="button" title="Commit" class="ui-button ui-widget ui-corner-all ui-button-icon-only btn-diff-update" id="btn-diff-update"><span class="ui-icon ui-icon-check"></span>Commit</button>`; return ret; } private _doUpdateAsSelected(e: JQueryEventObject): void { e.stopPropagation(); e.preventDefault(); const ids: Identifier[] = []; let stix_id; $("input[type='radio']:checked").each((_index, ele) => { const name = ele.getAttribute('name'); const id = ele.getAttribute('id'); if (id.startsWith('radio-db-')) { stix_id = id.split('radio-db-')[1]; ids.push(stix_id); } else { stix_id = id.split('radio-local-')[1]; this.clearId(stix_id); } // tslint:disable-next-line:no-console console.log(name, id); }); this.updateNode(ids); this._anchor.dialog('close'); } private updateNode(ids: Identifier[]): void { let nodes: cytoscape.CollectionReturnValue; for (const stix_id of ids) { const diff = this.tracked[stix_id].original; nodes = window.cycore.getElementById(stix_id); if (nodes.length > 0) { nodes.each((n) => { n.data('raw_data', diff); n.data('saved', true); }); } this.clearId(stix_id); } } }
the_stack
import { FsApi, File, Credentials, Fs, filetype } from '../Fs'; import { Client as FtpClient, FileInfo, FTPResponse } from 'basic-ftp'; import * as fs from 'fs'; import { Transform, Readable, Writable } from 'stream'; import { EventEmitter } from 'events'; import * as nodePath from 'path'; import { isWin } from '../../utils/platform'; function serverPart(str: string, lowerCase = true): string { const info = new URL(str); return `${info.protocol}//${info.hostname}`; } function join(path1: string, path2: string): string { let prefix = ''; if (path1.match(/^ftp:\/\//)) { prefix = 'ftp://'; path1 = path1.replace('ftp://', ''); } // since under Windows path.join will use '\' as separator // we replace it with '/' if (isWin) { return prefix + nodePath.join(path1, path2).replace(/\\/g, '/'); } else { return prefix + nodePath.join(path1, path2); } } // eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/explicit-function-return-type function canTimeout(target: any, key: any, descriptor: any) { if (descriptor === undefined) { descriptor = Object.getOwnPropertyDescriptor(target, key); } const originalMethod = descriptor.value; // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-function-return-type descriptor.value = function decorator(...args: any) { console.log('canTimeout:', key, '()'); return originalMethod.apply(this, args).catch(async (err: Error) => { console.log('key', key); if (this.ftpClient.closed) { const isLogin = key === 'login'; console.warn('timeout detected: attempt to get a new client and reconnect'); // if we are in the login process, do not attempt to login again, only create a new client await this.getNewFtpClient(!isLogin); console.log('after new client', this.ftpClient, this.ftpClient.closed); // do not recall the login process otherwise we could end up in an infinite loop // in case internet is down or EPIPE error if (!isLogin) { console.log('calling decorator again'); return decorator.apply(this, args); } else { return Promise.reject(err); } } else { console.log('caught error but client not closed ?', err); return Promise.reject(err); } }); }; } class Client { static instances = new Array<Client>(); static getFreeClient(server: string, api: SimpleFtpApi, transferId = -1): Client { let instance = Client.instances.find( (client) => client.server === server && !client.api && client.transferId === transferId, ); if (!instance) { instance = new Client(server, api, transferId); Client.instances.push(instance); } else { instance.api = api; } return instance; } static freeClient(client: Client): void { const index = Client.instances.findIndex((c) => client === c); if (index > -1) { const removed = Client.instances.splice(index, 1); // remove ref to api to avoid memory leak removed[0].api = null; } } api: SimpleFtpApi; server: string; transferId: number; ftpClient: FtpClient; loginOptions: Credentials; connected: boolean; constructor(server: string, api: SimpleFtpApi, transferId = -1) { this.ftpClient = new FtpClient(); this.ftpClient.ftp.verbose = true; this.server = server; this.api = api; this.transferId = transferId; } isConnected(): boolean { return /*!this.ftpClient.closed && */ this.connected; } @canTimeout async login(server: string, loginOptions: Credentials): Promise<void> { const host = this.api.getHostname(server); const socketConnected = this.ftpClient.ftp.socket.bytesRead !== 0; console.log( 'canTimeout/login()', server, loginOptions, 'socketConnected', socketConnected, 'ftp.closed', this.ftpClient.closed, ); // WORKAROUND: FtpError 530 causes any subsequent call to access // to throw a ISCONN error, preventing any login to be successful. // To avoid that we detect that the client is already connected // and only call login()/useDefaultSettings() in that case if (!socketConnected) { await this.ftpClient.access(Object.assign(loginOptions, { host })); await this.onLoggedIn(server, loginOptions); } else { await this.ftpClient.login(loginOptions.user, loginOptions.password); await this.ftpClient.useDefaultSettings(); await this.onLoggedIn(server, loginOptions); } } onLoggedIn(server: string, loginOptions: Credentials) { this.loginOptions = loginOptions; this.connected = true; this.server = server; // problem: this cannot be called while a task (list/cd/...) is already in progress // this.scheduleNoOp(); } // scheduleNoOp() { // this.checkTimeout = window.setTimeout(() => { // this.checkConnection(); // }) // } // async checkConnection() { // try { // console.log('sending noop'); // await this.ftpClient.send('NOOP'); // this.scheduleNoOp(); // } catch (err) { // debugger; // // TODO: remove client from the list ? // } // } close(): void { // if (this.checkTimeout) { // window.clearInterval(this.checkTimeout); // this.checkTimeout = 0; // } // TODO: remove from the list too ? console.log('close'); } async getNewFtpClient(login = true): Promise<void> { console.log('creating new FtpClient'); this.ftpClient = new FtpClient(); this.ftpClient.ftp.verbose = true; if (login) { console.log('calling login'); return this.login(this.server, this.loginOptions); } } /* API mirror starts here */ @canTimeout list(): Promise<FileInfo[]> { console.log('Client.list()'); return this.ftpClient.list(); } @canTimeout cd(path: string): Promise<FTPResponse> { console.log('Client.cd()'); return this.ftpClient.cd(path); } @canTimeout getStream(path: string, writeStream: Writable): Promise<Readable> { this.ftpClient.download(writeStream, path); return Promise.resolve(this.ftpClient.ftp.dataSocket); } @canTimeout getFile(path: string, writeStream: Writable): Promise<FTPResponse> { return this.ftpClient.download(writeStream, path); } } class SimpleFtpApi implements FsApi { type = 1; master: Client; loginOptions: Credentials = null; server = ''; connected = false; // events eventList = new Array<string>(); emitter: EventEmitter; async getClient(transferId = -1): Promise<Client> { if (transferId > -1) { const client = Client.getFreeClient(this.server || this.master.server, this, transferId); await client.login(this.master.server, this.loginOptions || this.master.loginOptions); return client; } else { return this.master; } } constructor(serverUrl: string) { this.master = Client.getFreeClient(serverPart(serverUrl), this); // TODO: get master if available // and set connected to true *and* credentials this.emitter = new EventEmitter(); } public pathpart(path: string): string { // we have to encode any % character other they may be // lost when calling decodeURIComponent try { const info = new URL(path.replace(/%/g, '%25')); return decodeURIComponent(info.pathname); } catch (err) { console.error('error getting pathpart for', path); return ''; } // const pathPart = path.replace(ServerPart, ''); // return pathPart; } getHostname(str: string): string { const info = new URL(str); return info.hostname.toLowerCase(); } isDirectoryNameValid(dirName: string): boolean { debugger; console.log('SimpleFtpFs.isDirectoryNameValid'); return true; } resolve(newPath: string): string { return newPath; } join(path: string, path2: string): string { return join(path, path2); } isConnected(): boolean { if (!(this.master && this.master.isConnected())) { console.log('not connected'); } return this.master && this.master.isConnected(); } cd(path: string, transferId = -1): Promise<string> { return new Promise(async (resolve, reject) => { const newpath = this.pathpart(path); try { await this.getClient(transferId); await this.master.cd(newpath); // if (dir) { // dir = dir.replace(/\\/g, '/'); // } const joint = newpath === '/' ? join(path, newpath) : path; resolve(joint); } catch (err) { reject(err); } }); } size(source: string, files: string[], transferId = -1): Promise<number> { console.log('SimpleFtpFs.size'); return Promise.resolve(10); } login(server?: string, credentials?: Credentials): Promise<void> { if (!this.connected) { // TODO: use existing master ? const loginOptions = credentials || this.loginOptions; const newServer = server || this.server; console.log('connecting to', newServer, 'user=', loginOptions.user, 'password=', '***'); return this.master.login(newServer, loginOptions).then(() => { console.log('connected'); this.loginOptions = loginOptions; this.server = newServer; }); } } makedir(parent: string, dirName: string, transferId = -1): Promise<string> { console.log('FsSimpleFtp.makedir'); return Promise.resolve(''); } delete(src: string, files: File[], transferId = -1): Promise<number> { console.log('FsSimpleFtp.delete'); return Promise.resolve(files.length); } rename(source: string, file: File, newName: string, transferId = -1): Promise<string> { console.log('FsSimpleFtp.rename'); return Promise.resolve(newName); } isDir(path: string, transferId = -1): Promise<boolean> { console.log('FsSimpleFtp.isDir'); return Promise.resolve(true); } exists(path: string, transferId = -1): Promise<boolean> { console.log('FsSimpleFtp.exists'); return Promise.resolve(true); } async makeSymlink(targetPath: string, path: string, transferId?: number): Promise<boolean> { console.log('FsSimpleFtp.makeSymlink'); return true; } async stat(fullPath: string, transferId = -1): Promise<File> { return Promise.resolve({ dir: '', fullname: '', name: '', extension: '', cDate: new Date(), mDate: new Date(), length: 0, mode: 777, isDir: false, readonly: false, type: '', } as File); } list(path: string, watchDir = false, transferId = -1): Promise<File[]> { return new Promise(async (resolve, reject) => { const newpath = this.pathpart(path); try { const client = await this.getClient(transferId); const ftpFiles: FileInfo[] = await client.list(); const files = ftpFiles .filter((ftpFile) => !ftpFile.name.match(/^[\.]{1,2}$/)) .map((ftpFile) => { const format = nodePath.parse(ftpFile.name); const ext = format.ext.toLowerCase(); const mDate = new Date(ftpFile.date); const file: File = { dir: path, name: ftpFile.name, fullname: ftpFile.name, isDir: ftpFile.isDirectory, length: ftpFile.size, cDate: mDate, mDate: mDate, bDate: mDate, extension: '', mode: 0, readonly: false, type: (!ftpFile.isDirectory && filetype(0, 0, 0, ext)) || '', isSym: false, target: null, id: { ino: mDate.getTime(), dev: new Date().getTime(), }, }; return file; }); resolve(files); // if (appendParent && !this.isRoot(newpath)) { // const parent = { ...Parent, dir: path }; // resolve([parent].concat(files)); // } else { // resolve(files); // } } catch (err) { reject(err); } }); } isRoot(path: string): boolean { try { const parsed = new URL(path); return parsed.pathname === '/'; } catch (err) { return path === '/'; } } async getStream(path: string, file: string, transferId = -1): Promise<Readable> { try { // create a duplex stream const transform = new Transform({ transform(chunk, encoding, callback): void { callback(null, chunk); }, }); const joint = this.join(path, file); const client = await this.getClient(transferId); client.getStream(this.pathpart(joint), transform); return Promise.resolve(transform); } catch (err) { console.log('FsSimpleFtp.getStream error', err); return Promise.reject(err); } } async putStream( readStream: fs.ReadStream, dstPath: string, progress: (bytesRead: number) => void, transferId = -1, ): Promise<void> { debugger; return Promise.resolve(); } getParentTree(dir: string): Array<{ dir: string; fullname: string }> { console.error('TODO: implement me'); const numParts = dir.replace(/^\//, '').split('/').length; const folders = []; for (let i = 0; i < numParts; ++i) {} return []; } sanityze(path: string): string { return path; } // eslint-disable-next-line @typescript-eslint/no-explicit-any on(event: string, cb: (data: any) => void): void { if (this.eventList.indexOf(event) < 0) { this.eventList.push(event); } this.emitter.on(event, cb); } off(): void { console.log('*** off'); // remove all listeners for (const event of this.eventList) { this.emitter.removeAllListeners(event); } if (this.master) { this.master.api = null; // this.master.close(); } // TODO: save this.master + this.loginOptions // close any connections ? // this.master.close(); } } export const FsSimpleFtp: Fs = { icon: 'globe-network', name: 'simple-ftp', description: 'Fs that implements ft connection on top of simple-ftp', options: { needsRefresh: true, }, canread(str: string): boolean { const info = new URL(str); console.log('FsFtp.canread', str, info.protocol, info.protocol === 'ftp:'); return info.protocol === 'ftp:'; }, serverpart(str: string, lowerCase = true): string { const info = new URL(str); return `${info.protocol}//${info.hostname}`; }, credentials(str: string): Credentials { const info = new URL(str); return { port: parseInt(info.port, 10) || 21, password: info.password, user: info.username, }; }, displaypath(str: string): { shortPath: string; fullPath: string } { const info = new URL(str); const split = info.pathname.split('/'); return { fullPath: str, shortPath: split.slice(-1)[0] || '/', }; }, API: SimpleFtpApi, };
the_stack
import {WebGLRenderingContext} from "../../WebGL/WebGLRenderingContext"; export class WebGL2RenderingContextBase extends WebGLRenderingContext { /* Getting GL parameter information */ public get READ_BUFFER(): number { return 0x0C02; } public get UNPACK_ROW_LENGTH(): number { return 0x0CF2; } public get UNPACK_SKIP_ROWS(): number { return 0x0CF3; } public get UNPACK_SKIP_PIXELS(): number { return 0x0CF4; } public get PACK_ROW_LENGTH(): number { return 0x0D02; } public get PACK_SKIP_ROWS(): number { return 0x0D03; } public get PACK_SKIP_PIXELS(): number { return 0x0D04; } public get TEXTURE_BINDING_3D(): number { return 0x806A; } public get UNPACK_SKIP_IMAGES(): number { return 0x806D; } public get UNPACK_IMAGE_HEIGHT(): number { return 0x806E; } public get MAX_3D_TEXTURE_SIZE(): number { return 0x8073; } public get MAX_ELEMENTS_VERTICES(): number { return 0x80E8; } public get MAX_ELEMENTS_INDICES(): number { return 0x80E9; } public get MAX_TEXTURE_LOD_BIAS(): number { return 0x84FD; } public get MAX_FRAGMENT_UNIFORM_COMPONENTS(): number { return 0x8B49; } public get MAX_VERTEX_UNIFORM_COMPONENTS(): number { return 0x8B4A; } public get MAX_ARRAY_TEXTURE_LAYERS(): number { return 0x88FF; } public get MIN_PROGRAM_TEXEL_OFFSET(): number { return 0x8904; } public get MAX_PROGRAM_TEXEL_OFFSET(): number { return 0x8905; } public get MAX_VARYING_COMPONENTS(): number { return 0x8B4B; } public get FRAGMENT_SHADER_DERIVATIVE_HINT(): number { return 0x8B8B; } public get RASTERIZER_DISCARD(): number { return 0x8C89; } public get VERTEX_ARRAY_BINDING(): number { return 0x85B5; } public get MAX_VERTEX_OUTPUT_COMPONENTS(): number { return 0x9122; } public get MAX_FRAGMENT_INPUT_COMPONENTS(): number { return 0x9125; } public get MAX_SERVER_WAIT_TIMEOUT(): number { return 0x9111; } public get MAX_ELEMENT_INDEX(): number { return 0x8D6B; } public get RED(): number { return 0x1903; } public get RGB8(): number { return 0x8051; } public get RGBA8(): number { return 0x8058; } public get RGB10_A2(): number { return 0x8059; } public get TEXTURE_3D(): number { return 0x806F; } public get TEXTURE_WRAP_R(): number { return 0x8072; } public get TEXTURE_MIN_LOD(): number { return 0x813A; } public get TEXTURE_MAX_LOD(): number { return 0x813B; } public get TEXTURE_BASE_LEVEL(): number { return 0x813C; } public get TEXTURE_MAX_LEVEL(): number { return 0x813D; } public get TEXTURE_COMPARE_MODE(): number { return 0x884C; } public get TEXTURE_COMPARE_FUNC(): number { return 0x884D; } public get SRGB(): number { return 0x8C40; } public get SRGB8(): number { return 0x8C41; } public get SRGB8_ALPHA8(): number { return 0x8C43; } public get COMPARE_REF_TO_TEXTURE(): number { return 0x884E; } public get RGBA32F(): number { return 0x8814; } public get RGB32F(): number { return 0x8815; } public get RGBA16F(): number { return 0x881A; } public get RGB16F(): number { return 0x881B; } public get TEXTURE_2D_ARRAY(): number { return 0x8C1A; } public get TEXTURE_BINDING_2D_ARRAY(): number { return 0x8C1D; } public get R11F_G11F_B10F(): number { return 0x8C3A; } public get RGB9_E5(): number { return 0x8C3D; } public get RGBA32UI(): number { return 0x8D70; } public get RGB32UI(): number { return 0x8D71; } public get RGBA16UI(): number { return 0x8D76; } public get RGB16UI(): number { return 0x8D77; } public get RGBA8UI(): number { return 0x8D7C; } public get RGB8UI(): number { return 0x8D7D; } public get RGBA32I(): number { return 0x8D82; } public get RGB32I(): number { return 0x8D83; } public get RGBA16I(): number { return 0x8D88; } public get RGB16I(): number { return 0x8D89; } public get RGBA8I(): number { return 0x8D8E; } public get RGB8I(): number { return 0x8D8F; } public get RED_INTEGER(): number { return 0x8D94; } public get RGB_INTEGER(): number { return 0x8D98; } public get RGBA_INTEGER(): number { return 0x8D99; } public get R8(): number { return 0x8229; } public get RG8(): number { return 0x822B; } public get R16F(): number { return 0x822D; } public get R32F(): number { return 0x822E; } public get RG16F(): number { return 0x822F; } public get RG32F(): number { return 0x8230; } public get R8I(): number { return 0x8231; } public get R8UI(): number { return 0x8232; } public get R16I(): number { return 0x8233; } public get R16UI(): number { return 0x8234; } public get R32I(): number { return 0x8235; } public get R32UI(): number { return 0x8236; } public get RG8I(): number { return 0x8237; } public get RG8UI(): number { return 0x8238; } public get RG16I(): number { return 0x8239; } public get RG16UI(): number { return 0x823A; } public get RG32I(): number { return 0x823B; } public get RG32UI(): number { return 0x823C; } public get R8_SNORM(): number { return 0x8F94; } public get RG8_SNORM(): number { return 0x8F95; } public get RGB8_SNORM(): number { return 0x8F96; } public get RGBA8_SNORM(): number { return 0x8F97; } public get RGB10_A2UI(): number { return 0x906F; } public get TEXTURE_IMMUTABLE_FORMAT(): number { return 0x912F; } public get TEXTURE_IMMUTABLE_LEVELS(): number { return 0x82DF; } public get UNSIGNED_INT_2_10_10_10_REV(): number { return 0x8368; } public get UNSIGNED_INT_10F_11F_11F_REV(): number { return 0x8C3B; } public get UNSIGNED_INT_5_9_9_9_REV(): number { return 0x8C3E; } public get FLOAT_32_UNSIGNED_INT_24_8_REV(): number { return 0x8DAD; } public get UNSIGNED_INT_24_8(): number { return 0x84FA; } public get HALF_FLOAT(): number { return 0x140B; } public get RG(): number { return 0x8227; } public get RG_INTEGER(): number { return 0x8228; } public get INT_2_10_10_10_REV(): number { return 0x8D9F; } public get QUERY_RESULT_AVAILABLE(): number { return 0x8865; } public get QUERY_RESULT(): number { return 0x8866; } public get CURRENT_QUERY(): number { return 0x8867; } public get ANY_SAMPLES_PASSED(): number { return 0x8C2F; } public get ANY_SAMPLES_PASSED_CONSERVATIVE(): number { return 0x8D6A; } public get MAX_DRAW_BUFFERS(): number { return 0x8824; } public get DRAW_BUFFER0(): number { return 0x8825; } public get DRAW_BUFFER1(): number { return 0x8826; } public get DRAW_BUFFER2(): number { return 0x8827; } public get DRAW_BUFFER3(): number { return 0x8828; } public get DRAW_BUFFER4(): number { return 0x8829; } public get DRAW_BUFFER5(): number { return 0x882A; } public get DRAW_BUFFER6(): number { return 0x882B; } public get DRAW_BUFFER7(): number { return 0x882C; } public get DRAW_BUFFER8(): number { return 0x882D; } public get DRAW_BUFFER9(): number { return 0x882E; } public get DRAW_BUFFER10(): number { return 0x882F; } /* Getting GL parameter information */ /* Textures */ public get DRAW_BUFFER11(): number { return 0x8830; } public get DRAW_BUFFER12(): number { return 0x8831; } public get DRAW_BUFFER13(): number { return 0x8832; } public get DRAW_BUFFER14(): number { return 0x8833; } public get DRAW_BUFFER15(): number { return 0x8834; } public get MAX_COLOR_ATTACHMENTS(): number { return 0x8CDF; } public get COLOR_ATTACHMENT1(): number { return 0x8CE1; } public get COLOR_ATTACHMENT2(): number { return 0x8CE2; } public get COLOR_ATTACHMENT3(): number { return 0x8CE3; } public get COLOR_ATTACHMENT4(): number { return 0x8CE4; } public get COLOR_ATTACHMENT5(): number { return 0x8CE5; } public get COLOR_ATTACHMENT6(): number { return 0x8CE6; } public get COLOR_ATTACHMENT7(): number { return 0x8CE7; } public get COLOR_ATTACHMENT8(): number { return 0x8CE8; } public get COLOR_ATTACHMENT9(): number { return 0x8CE9; } public get COLOR_ATTACHMENT10(): number { return 0x8CEA; } public get COLOR_ATTACHMENT11(): number { return 0x8CEB; } public get COLOR_ATTACHMENT12(): number { return 0x8CEC; } public get COLOR_ATTACHMENT13(): number { return 0x8CED; } public get COLOR_ATTACHMENT14(): number { return 0x8CEE; } public get COLOR_ATTACHMENT15(): number { return 0x8CEF; } public get SAMPLER_3D(): number { return 0x8B5F; } public get SAMPLER_2D_SHADOW(): number { return 0x8B62; } public get SAMPLER_2D_ARRAY(): number { return 0x8DC1; } public get SAMPLER_2D_ARRAY_SHADOW(): number { return 0x8DC4; } public get SAMPLER_CUBE_SHADOW(): number { return 0x8DC5; } public get INT_SAMPLER_2D(): number { return 0x8DCA; } public get INT_SAMPLER_3D(): number { return 0x8DCB; } public get INT_SAMPLER_CUBE(): number { return 0x8DCC; } public get INT_SAMPLER_2D_ARRAY(): number { return 0x8DCF; } public get UNSIGNED_INT_SAMPLER_2D(): number { return 0x8DD2; } public get UNSIGNED_INT_SAMPLER_3D(): number { return 0x8DD3; } public get UNSIGNED_INT_SAMPLER_CUBE(): number { return 0x8DD4; } public get UNSIGNED_INT_SAMPLER_2D_ARRAY(): number { return 0x8DD7; } public get MAX_SAMPLES(): number { return 0x8D57; } public get SAMPLER_BINDING(): number { return 0x8919; } public get PIXEL_PACK_BUFFER(): number { return 0x88EB; } public get PIXEL_UNPACK_BUFFER(): number { return 0x88EC; } public get PIXEL_PACK_BUFFER_BINDING(): number { return 0x88ED; } public get PIXEL_UNPACK_BUFFER_BINDING(): number { return 0x88EF; } public get COPY_READ_BUFFER(): number { return 0x8F36; } public get COPY_WRITE_BUFFER(): number { return 0x8F37; } public get COPY_READ_BUFFER_BINDING(): number { return 0x8F36; } public get COPY_WRITE_BUFFER_BINDING(): number { return 0x8F37; } public get FLOAT_MAT2x3(): number { return 0x8B65; } public get FLOAT_MAT2x4(): number { return 0x8B66; } public get FLOAT_MAT3x2(): number { return 0x8B67; } public get FLOAT_MAT3x4(): number { return 0x8B68; } public get FLOAT_MAT4x2(): number { return 0x8B69; } public get FLOAT_MAT4x3(): number { return 0x8B6A; } public get UNSIGNED_INT_VEC2(): number { return 0x8DC6; } public get UNSIGNED_INT_VEC3(): number { return 0x8DC7; } public get UNSIGNED_INT_VEC4(): number { return 0x8DC8; } public get UNSIGNED_NORMALIZED(): number { return 0x8C17; } public get SIGNED_NORMALIZED(): number { return 0x8F9C; } /* Vertex attributes */ public get VERTEX_ATTRIB_ARRAY_INTEGER(): number { return 0x88FD; } public get VERTEX_ATTRIB_ARRAY_DIVISOR(): number { return 0x88FE; } public get TRANSFORM_FEEDBACK_BUFFER_MODE(): number { return 0x8C7F; } public get MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS(): number { return 0x8C80; } public get TRANSFORM_FEEDBACK_VARYINGS(): number { return 0x8C83; } public get TRANSFORM_FEEDBACK_BUFFER_START(): number { return 0x8C84; } public get TRANSFORM_FEEDBACK_BUFFER_SIZE(): number { return 0x8C85; } public get TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN(): number { return 0x8C88; } public get MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS(): number { return 0x8C8A; } /* Textures */ /* Pixel types */ public get MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS(): number { return 0x8C8B; } public get INTERLEAVED_ATTRIBS(): number { return 0x8C8C; } public get SEPARATE_ATTRIBS(): number { return 0x8C8D; } public get TRANSFORM_FEEDBACK_BUFFER(): number { return 0x8C8E; } public get TRANSFORM_FEEDBACK_BUFFER_BINDING(): number { return 0x8C8F; } public get TRANSFORM_FEEDBACK(): number { return 0x8E22; } public get TRANSFORM_FEEDBACK_PAUSED(): number { return 0x8E23; } public get TRANSFORM_FEEDBACK_ACTIVE(): number { return 0x8E24; } public get TRANSFORM_FEEDBACK_BINDING(): number { return 0x8E25; } /* Pixel types */ /* Queries */ public get FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING(): number { return 0x8210; } public get FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE(): number { return 0x8211; } public get FRAMEBUFFER_ATTACHMENT_RED_SIZE(): number { return 0x8212; } public get FRAMEBUFFER_ATTACHMENT_GREEN_SIZE(): number { return 0x8213; } public get FRAMEBUFFER_ATTACHMENT_BLUE_SIZE(): number { return 0x8214; } /* Queries */ /* Draw buffers */ public get FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE(): number { return 0x8215; } public get FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE(): number { return 0x8216; } public get FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE(): number { return 0x8217; } public get FRAMEBUFFER_DEFAULT(): number { return 0x8218; } public get DEPTH_STENCIL_ATTACHMENT(): number { return 0x821A; } public get DEPTH_STENCIL(): number { return 0x84F9; } public get DEPTH24_STENCIL8(): number { return 0x88F0; } public get DRAW_FRAMEBUFFER_BINDING(): number { return 0x8CA6; } public get READ_FRAMEBUFFER(): number { return 0x8CA8; } public get DRAW_FRAMEBUFFER(): number { return 0x8CA9; } public get READ_FRAMEBUFFER_BINDING(): number { return 0x8CAA; } public get RENDERBUFFER_SAMPLES(): number { return 0x8CAB; } public get FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER(): number { return 0x8CD4; } public get FRAMEBUFFER_INCOMPLETE_MULTISAMPLE(): number { return 0x8D56; } public get UNIFORM_BUFFER(): number { return 0x8A11; } public get UNIFORM_BUFFER_BINDING(): number { return 0x8A28; } public get UNIFORM_BUFFER_START(): number { return 0x8A29; } public get UNIFORM_BUFFER_SIZE(): number { return 0x8A2A; } public get MAX_VERTEX_UNIFORM_BLOCKS(): number { return 0x8A2B; } public get MAX_FRAGMENT_UNIFORM_BLOCKS(): number { return 0x8A2D; } public get MAX_COMBINED_UNIFORM_BLOCKS(): number { return 0x8A2E; } public get MAX_UNIFORM_BUFFER_BINDINGS(): number { return 0x8A2F; } public get MAX_UNIFORM_BLOCK_SIZE(): number { return 0x8A30; } public get MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS(): number { return 0x8A31; } public get MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS(): number { return 0x8A33; } public get UNIFORM_BUFFER_OFFSET_ALIGNMENT(): number { return 0x8A34; } public get ACTIVE_UNIFORM_BLOCKS(): number { return 0x8A36; } public get UNIFORM_TYPE(): number { return 0x8A37; } public get UNIFORM_SIZE(): number { return 0x8A38; } public get UNIFORM_BLOCK_INDEX(): number { return 0x8A3A; } public get UNIFORM_OFFSET(): number { return 0x8A3B; } public get UNIFORM_ARRAY_STRIDE(): number { return 0x8A3C; } public get UNIFORM_MATRIX_STRIDE(): number { return 0x8A3D; } /* Draw buffers */ /* Samplers */ public get UNIFORM_IS_ROW_MAJOR(): number { return 0x8A3E; } public get UNIFORM_BLOCK_BINDING(): number { return 0x8A3F; } public get UNIFORM_BLOCK_DATA_SIZE(): number { return 0x8A40; } public get UNIFORM_BLOCK_ACTIVE_UNIFORMS(): number { return 0x8A42; } public get UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES(): number { return 0x8A43; } public get UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER(): number { return 0x8A44; } public get UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER(): number { return 0x8A46; } public get OBJECT_TYPE(): number { return 0x9112; } public get SYNC_CONDITION(): number { return 0x9113; } public get SYNC_STATUS(): number { return 0x9114; } public get SYNC_FLAGS(): number { return 0x9115; } public get SYNC_FENCE(): number { return 0x9116; } public get SYNC_GPU_COMMANDS_COMPLETE(): number { return 0x9117; } public get UNSIGNALED(): number { return 0x9118; } public get SIGNALED(): number { return 0x9119; } /* Samplers */ /* Buffers */ public get ALREADY_SIGNALED(): number { return 0x911A; } public get TIMEOUT_EXPIRED(): number { return 0x911B; } public get CONDITION_SATISFIED(): number { return 0x911C; } public get WAIT_FAILED(): number { return 0x911D; } public get SYNC_FLUSH_COMMANDS_BIT(): number { return 0x00000001; } public get COLOR(): number { return 0x1800; } public get DEPTH(): number { return 0x1801; } public get STENCIL(): number { return 0x1802; } /* Buffers */ /* Data types */ public get MIN(): number { return 0x8007; } public get MAX(): number { return 0x8008; } public get DEPTH_COMPONENT24(): number { return 0x81A6; } public get STREAM_READ(): number { return 0x88E1; } public get STREAM_COPY(): number { return 0x88E2; } public get STATIC_READ(): number { return 0x88E5; } public get STATIC_COPY(): number { return 0x88E6; } public get DYNAMIC_READ(): number { return 0x88E9; } public get DYNAMIC_COPY(): number { return 0x88EA; } public get DEPTH_COMPONENT32F(): number { return 0x8CAC; } public get DEPTH32F_STENCIL8(): number { return 0x8CAD; } /* Data types */ public get INVALID_INDEX(): number { return 0xFFFFFFFF; } public get TIMEOUT_IGNORED(): number { return -1; } /* Vertex attributes */ /* Transform feedback */ public get MAX_CLIENT_WAIT_TIMEOUT_WEBGL(): number { return 0x9247; } }
the_stack
import { AbstractHistory, HistoryEntry, HistorySnapshot, getActiveHistoryEntryIndex, isHistoryEntryEqual, } from 'boring-router'; import Debug from 'debug'; const debug = Debug('boring-router:react:browser-history'); export type BrowserHistoryNavigateAwayHandler = (href: string) => void; const NAVIGATE_AWAY_HANDLER_DEFAULT: BrowserHistoryNavigateAwayHandler = href => { location.href = href; }; type BrowserHistoryEntry<TData> = HistoryEntry<number, TData>; type BrowserHistorySnapshot<TData> = HistorySnapshot<number, TData>; interface BrowserHistoryState<TData> { id: number; data: TData; } export interface BrowserHistoryOptions { /** * URL prefix, ignored if `hash` is enabled. */ prefix?: string; /** * Use hash (#) for location pathname and search. * * This is not a compatibility option and does not make it compatible with * obsolete browsers. */ hash?: boolean; } export class BrowserHistory<TData = any> extends AbstractHistory< number, TData > { protected snapshot: BrowserHistorySnapshot<TData>; private tracked: BrowserHistorySnapshot<TData>; private restoring = false; private restoringPromise = Promise.resolve(); private restoringPromiseResolver: (() => void) | undefined; private lastUsedId = 0; private prefix: string; private hash: boolean; constructor({prefix = '', hash = false}: BrowserHistoryOptions = {}) { super(); this.prefix = prefix; this.hash = hash; window.addEventListener('popstate', this.onPopState); let state = history.state as BrowserHistoryState<TData> | undefined; let id: number; let data: TData | undefined; if (state) { id = state.id; data = state.data; this.lastUsedId = id; } else { id = this.getNextId(); history.replaceState({id}, ''); } let entries: HistoryEntry<number, TData>[] = [ { id, ref: this.getRefByHRef(this.url), data, }, ]; this.snapshot = this.tracked = { entries, active: id, }; } get url(): string { return `${location.pathname}${location.search}${location.hash}`; } private get hashPrefix(): string { return `${location.pathname}${location.search}`; } getHRefByRef(ref: string): string { if (this.hash) { return `${this.hashPrefix}#${ref}`; } else { return `${this.prefix}${ref}`; } } getRefByHRef(href: string): string { if (this.hash) { let index = href.indexOf('#'); return (index >= 0 && href.slice(index + 1)) || '/'; } else { let prefix = this.prefix; return href.startsWith(prefix) ? href.slice(prefix.length) : href; } } async back(): Promise<void> { await this.restoringPromise; history.back(); } async forward(): Promise<void> { await this.restoringPromise; history.forward(); } async push(ref: string, data?: TData): Promise<void> { return this._push(ref, data, true); } async replace(ref: string, data?: TData): Promise<void> { await this.restoringPromise; let {active: id} = this.tracked; let snapshot = this.replaceEntry({ id, ref, data, }); debug('replace', snapshot); this.snapshot = snapshot; this.emitChange(snapshot); } async restore(snapshot: BrowserHistorySnapshot<TData>): Promise<void> { debug('restore', snapshot); this.snapshot = snapshot; if (this.restoring) { return; } debug('restore start'); this.restoring = true; let promise = new Promise<void>(resolve => { this.restoringPromiseResolver = resolve; }); this.restoringPromise = promise; this.stepRestoration(); await promise; } async navigate( href: string, navigateAwayHandler = NAVIGATE_AWAY_HANDLER_DEFAULT, ): Promise<void> { let originalHRef = href; let groups = /^([\w\d]+:)?\/\/([^/?]+)(.*)/.exec(href); if (groups) { let [, protocol, host, rest] = groups; if ( (protocol && protocol !== location.protocol) || host !== location.host ) { navigateAwayHandler(originalHRef); return; } href = rest.startsWith('/') ? rest : `/${rest}`; } let prefix = this.prefix; if (!href.startsWith(prefix)) { navigateAwayHandler(originalHRef); return; } let ref = href.slice(prefix.length); await this.push(ref); } private onPopState = (event: PopStateEvent): void => { let {entries: trackedEntries} = this.tracked; let state = event.state as BrowserHistoryState<TData> | null; // When using hash mode, entering a new hash directly in the browser will // also trigger popstate. And in that case state is null. if (!state) { void this._push(this.getRefByHRef(location.href), undefined, false); return; } let {id, data} = state; if (id > this.lastUsedId) { this.lastUsedId = id; } let entries = [...trackedEntries]; let index = entries.findIndex(entry => entry.id >= id); if (index < 0 || entries[index].id > id) { entries.splice(index < 0 ? entries.length : index, 0, { id, ref: this.getRefByHRef(this.url), data, }); } let snapshot: BrowserHistorySnapshot<TData> = { entries, active: id, }; this.tracked = snapshot; if (this.restoring) { this.stepRestoration(); return; } this.snapshot = snapshot; debug('pop', snapshot); this.emitChange(snapshot); }; private stepRestoration(): void { debug('step restoration'); debug('expected', this.snapshot); debug('tracked', this.tracked); this.restoreEntries(); } private restoreEntries(): void { let expected = this.snapshot; let tracked = this.tracked; let {entries: expectedEntries} = expected; let {entries: trackedEntries} = tracked; let lastExpectedIndex = expectedEntries.length - 1; let lastTrackedIndex = trackedEntries.length - 1; let trackedActiveIndex = getActiveHistoryEntryIndex(tracked); let minLength = Math.min(expectedEntries.length, trackedEntries.length); let firstMismatchedIndex = 0; for ( firstMismatchedIndex; firstMismatchedIndex < minLength; firstMismatchedIndex++ ) { let expectedEntry = expectedEntries[firstMismatchedIndex]; let trackedEntry = trackedEntries[firstMismatchedIndex]; if (!isHistoryEntryEqual(expectedEntry, trackedEntry)) { break; } } if ( firstMismatchedIndex > lastExpectedIndex && (lastExpectedIndex === lastTrackedIndex || lastExpectedIndex === 0) ) { // 1. Exactly identical. // 2. Not exactly identical but there's not much that can be done: // ``` // expected a // tracked a -> b // ^ mismatch // ``` // In this case we cannot remove the extra entries. this.restoreActive(); return; } if ( // expected a -> b -> c // tracked a -> d -> e // ^ mismatch // ^ active trackedActiveIndex > firstMismatchedIndex || // expected a -> b // tracked a -> b -> c // ^ mismatch // ^ active trackedActiveIndex > lastExpectedIndex || // expected a -> b // tracked a -> b -> c // ^ mismatch // ^ active // expected a -> b // tracked a -> c -> d // ^ mismatch // ^ active (trackedActiveIndex === lastExpectedIndex && trackedActiveIndex < lastTrackedIndex) ) { history.back(); return; } if (trackedActiveIndex === firstMismatchedIndex) { this.replaceEntry( expectedEntries[trackedActiveIndex], trackedActiveIndex, ); } for (let entry of expectedEntries.slice(trackedActiveIndex + 1)) { this.pushEntry(entry, true); } this.restoreActive(); } private restoreActive(): void { let expectedActiveIndex = getActiveHistoryEntryIndex(this.snapshot); let trackedActiveIndex = getActiveHistoryEntryIndex(this.tracked); if (trackedActiveIndex < expectedActiveIndex) { history.forward(); } else if (trackedActiveIndex > expectedActiveIndex) { history.back(); } else { this.completeRestoration(); } } private completeRestoration(): void { this.restoring = false; if (this.restoringPromiseResolver) { this.restoringPromiseResolver(); } this.restoringPromiseResolver = undefined; debug('restore end'); debug('expected', this.snapshot); debug('tracked', this.tracked); } private async _push( ref: string, data: TData | undefined, toPushState: boolean, ): Promise<void> { if (ref === this.ref) { return this.replace(ref, data); } await this.restoringPromise; let snapshot = this.pushEntry( { id: this.getNextId(), ref, data, }, toPushState, ); debug('push', snapshot); this.snapshot = snapshot; this.emitChange(snapshot); } private pushEntry( {id, ref, data}: BrowserHistoryEntry<TData>, toPushState: boolean, ): BrowserHistorySnapshot<TData> { let tracked = this.tracked; let {entries} = tracked; let activeIndex = getActiveHistoryEntryIndex(tracked); let snapshot: BrowserHistorySnapshot<TData> = { entries: [...entries.slice(0, activeIndex + 1), {id, ref, data}], active: id, }; this.tracked = snapshot; if (toPushState) { let href = this.getHRefByRef(ref); try { history.pushState({id, data}, '', href); } catch (error) { history.pushState({id}, '', href); } } return snapshot; } private replaceEntry( {id, ref, data}: BrowserHistoryEntry<TData>, index?: number, ): BrowserHistorySnapshot<TData> { let {entries} = this.tracked; if (index === undefined) { index = entries.findIndex(entry => entry.id === id); if (index < 0) { throw new Error(`Cannot find entry with id ${id} to replace`); } } let snapshot: BrowserHistorySnapshot<TData> = { entries: [ ...entries.slice(0, index), {id, ref, data}, ...entries.slice(index + 1), ], active: id, }; this.tracked = snapshot; let href = this.getHRefByRef(ref); try { history.replaceState({id, data}, '', href); } catch (error) { history.replaceState({id}, '', href); } return snapshot; } private getNextId(): number { return ++this.lastUsedId; } }
the_stack
import { EventEmitter } from 'events'; import MultiFormat from '@requestnetwork/multi-format'; import { AdvancedLogicTypes, RequestLogicTypes, TransactionTypes } from '@requestnetwork/types'; import Utils from '@requestnetwork/utils'; import { RequestLogic } from '../src/index'; import * as TestData from './unit/utils/test-data-generator'; import Version from '../src/version'; const CURRENT_VERSION = Version.currentVersion; const createParams: RequestLogicTypes.ICreateParameters = { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: TestData.arbitraryExpectedAmount, payee: TestData.payeeRaw.identity, payer: TestData.payerRaw.identity, timestamp: 1544426030, }; const unsignedAction: RequestLogicTypes.IUnsignedAction = { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: createParams, version: CURRENT_VERSION, }; const action = Utils.signature.sign(unsignedAction, TestData.payeeRaw.signatureParams); const requestId = MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(action)); const fakeTxHash = '01aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; const fakeMetaTransactionManager = { meta: { storageDataId: 'fakeDataId' }, result: { topics: [fakeTxHash] }, }; let fakeTransactionManager: TransactionTypes.ITransactionManager; /* eslint-disable @typescript-eslint/no-unused-expressions */ describe('index', () => { beforeEach(() => { fakeTransactionManager = { getChannelsByMultipleTopics: jest.fn() as any, getChannelsByTopic: jest.fn() as any, getTransactionsByChannelId: jest.fn() as any, persistTransaction: jest.fn(() => { const fakeMetaTransactionManagerWithEvent = Object.assign( new EventEmitter(), fakeMetaTransactionManager, ); setTimeout(() => { fakeMetaTransactionManagerWithEvent.emit( 'confirmed', { meta: { storageDataId: 'fakeDataId' }, result: { topics: [fakeTxHash] }, }, // eslint-disable-next-line no-magic-numbers 100, ); }); return fakeMetaTransactionManagerWithEvent; }) as any, // jest.fn().mockReturnValue(fakeMetaTransactionManager) as any, }; }); describe('createRequest', () => { it('cannot createRequest without signature provider', async () => { const requestLogic = new RequestLogic(fakeTransactionManager); await expect( requestLogic.createRequest(createParams, TestData.payeeRaw.identity), ).rejects.toThrowError('You must give a signature provider to create actions'); }); it('cannot createRequest if apply fails in the advanced request logic', async () => { const fakeAdvancedLogic: AdvancedLogicTypes.IAdvancedLogic = { applyActionToExtensions: (): RequestLogicTypes.IExtensionStates => { throw new Error('Expected throw'); }, extensions: {}, }; const requestLogic = new RequestLogic( fakeTransactionManager, TestData.fakeSignatureProvider, fakeAdvancedLogic, ); const createParamsWithExtensions: RequestLogicTypes.ICreateParameters = { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: TestData.arbitraryExpectedAmount, extensionsData: ['whatever'], payee: TestData.payeeRaw.identity, payer: TestData.payerRaw.identity, timestamp: 1544426030, }; await expect( requestLogic.createRequest(createParamsWithExtensions, TestData.payeeRaw.identity), ).rejects.toThrowError('Expected throw'); }); it('can createRequest', async () => { const requestLogic = new RequestLogic(fakeTransactionManager, TestData.fakeSignatureProvider); const ret = await requestLogic.createRequest(createParams, TestData.payeeRaw.identity); ret.on('confirmed', (resultConfirmed1) => { // 'result Confirmed wrong' expect(resultConfirmed1).toEqual({ meta: { transactionManagerMeta: { storageDataId: 'fakeDataId', }, }, result: { requestId: '010246b8aeb3aa72f4c7039284bf7307c3d543541ff309ee52e9361f4bd2c89c9c', }, }); }); // 'ret.result is wrong' expect(ret.result).toEqual({ requestId }); // 'ret.meta is wrong' expect(ret.meta).toEqual({ transactionManagerMeta: fakeMetaTransactionManager.meta, }); expect(fakeTransactionManager.persistTransaction).toHaveBeenCalledWith( JSON.stringify(action), requestId, [], ); }); it('can createRequest with topics', async () => { const requestLogic = new RequestLogic(fakeTransactionManager, TestData.fakeSignatureProvider); const ret = await requestLogic.createRequest(createParams, TestData.payeeRaw.identity, [ TestData.payeeRaw.identity, TestData.payerRaw.identity, ]); // 'ret.result is wrong' expect(ret.result).toEqual({ requestId }); // 'ret.meta is wrong' expect(ret.meta).toEqual({ transactionManagerMeta: fakeMetaTransactionManager.meta, }); expect(fakeTransactionManager.persistTransaction).toHaveBeenCalledWith( JSON.stringify(action), requestId, [ MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(TestData.payeeRaw.identity)), MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(TestData.payerRaw.identity)), ], ); }); it('can createRequest if persist emit error', async () => { jest.useFakeTimers('modern'); const fakeTransactionManagerEmittingError = Object.assign({}, fakeTransactionManager); fakeTransactionManagerEmittingError.persistTransaction = jest.fn((): any => { const fakeTransactionManagerWithEvent = Object.assign( new EventEmitter(), fakeMetaTransactionManager, ); setTimeout(() => { // eslint-disable-next-line no-magic-numbers fakeTransactionManagerWithEvent.emit('error', 'error for test purpose', 10); }); return fakeTransactionManagerWithEvent; }); const requestLogic = new RequestLogic( fakeTransactionManagerEmittingError, TestData.fakeSignatureProvider, ); const ret = await requestLogic.createRequest(createParams, TestData.payeeRaw.identity); // eslint-disable-next-line const handleError = jest.fn((error: any) => { // 'error wrong' expect(error).toEqual('error for test purpose'); }); ret.on('error', handleError); jest.advanceTimersByTime(11); expect(handleError).toHaveBeenCalled(); // 'ret.result is wrong' expect(ret.result).toEqual({ requestId }); // 'ret.meta is wrong' expect(ret.meta).toEqual({ transactionManagerMeta: fakeMetaTransactionManager.meta, }); expect(fakeTransactionManagerEmittingError.persistTransaction).toHaveBeenCalledWith( JSON.stringify(action), requestId, [], ); jest.useRealTimers(); }); }); describe('createEncryptedRequest', () => { it('cannot create encrypted request without signature provider', async () => { const requestLogic = new RequestLogic(fakeTransactionManager); await expect( requestLogic.createEncryptedRequest(createParams, TestData.payeeRaw.identity, [ TestData.payeeRaw.encryptionParams, TestData.payerRaw.encryptionParams, ]), ).rejects.toThrowError('You must give a signature provider to create actions'); }); it('cannot create an encrypted request if apply fails in the advanced request logic', async () => { const fakeAdvancedLogic: AdvancedLogicTypes.IAdvancedLogic = { applyActionToExtensions: (): RequestLogicTypes.IExtensionStates => { throw new Error('Expected throw'); }, extensions: {}, }; const requestLogic = new RequestLogic( fakeTransactionManager, TestData.fakeSignatureProvider, fakeAdvancedLogic, ); const createParamsWithExtensions: RequestLogicTypes.ICreateParameters = { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: TestData.arbitraryExpectedAmount, extensionsData: ['whatever'], payee: TestData.payeeRaw.identity, payer: TestData.payerRaw.identity, timestamp: 1544426030, }; await expect( requestLogic.createEncryptedRequest( createParamsWithExtensions, TestData.payeeRaw.identity, [TestData.payeeRaw.encryptionParams, TestData.payerRaw.encryptionParams], ), ).rejects.toThrowError('Expected throw'); }); it('can create en encrypted request', async () => { const requestLogic = new RequestLogic(fakeTransactionManager, TestData.fakeSignatureProvider); const ret = await requestLogic.createEncryptedRequest( createParams, TestData.payeeRaw.identity, [TestData.payeeRaw.encryptionParams, TestData.payerRaw.encryptionParams], ); ret.on('confirmed', (resultConfirmed1) => { // 'result Confirmed wrong' expect(resultConfirmed1).toEqual({ meta: { transactionManagerMeta: { storageDataId: 'fakeDataId', }, }, result: { requestId: '010246b8aeb3aa72f4c7039284bf7307c3d543541ff309ee52e9361f4bd2c89c9c', }, }); }); // 'ret.result is wrong' expect(ret.result).toEqual({ requestId }); // 'ret.meta is wrong' expect(ret.meta).toEqual({ transactionManagerMeta: fakeMetaTransactionManager.meta, }); expect(fakeTransactionManager.persistTransaction).toHaveBeenCalledWith( JSON.stringify(action), requestId, [], [TestData.payeeRaw.encryptionParams, TestData.payerRaw.encryptionParams], ); }); it('can create en encrypted request with topics', async () => { const requestLogic = new RequestLogic(fakeTransactionManager, TestData.fakeSignatureProvider); const ret = await requestLogic.createEncryptedRequest( createParams, TestData.payeeRaw.identity, [TestData.payeeRaw.encryptionParams, TestData.payerRaw.encryptionParams], [TestData.payeeRaw.identity, TestData.payerRaw.identity], ); // 'ret.result is wrong' expect(ret.result).toEqual({ requestId }); // 'ret.meta is wrong' expect(ret.meta).toEqual({ transactionManagerMeta: fakeMetaTransactionManager.meta, }); expect(fakeTransactionManager.persistTransaction).toHaveBeenCalledWith( JSON.stringify(action), requestId, [ MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(TestData.payeeRaw.identity)), MultiFormat.serialize(Utils.crypto.normalizeKeccak256Hash(TestData.payerRaw.identity)), ], [TestData.payeeRaw.encryptionParams, TestData.payerRaw.encryptionParams], ); }); it('cannot create en encrypted request without encryption parameters', async () => { const requestLogic = new RequestLogic(fakeTransactionManager, TestData.fakeSignatureProvider); await expect( requestLogic.createEncryptedRequest(createParams, TestData.payeeRaw.identity, []), ).rejects.toThrowError( 'You must give at least one encryption parameter to create an encrypted request', ); }); it('can createEncryptedRequest if persist emit error', async () => { jest.useFakeTimers('modern'); const fakeTransactionManagerEmittingError = Object.assign({}, fakeTransactionManager); fakeTransactionManagerEmittingError.persistTransaction = jest.fn((): any => { const fakeTransactionManagerWithEvent = Object.assign( new EventEmitter(), fakeMetaTransactionManager, ); setTimeout(() => { // eslint-disable-next-line no-magic-numbers fakeTransactionManagerWithEvent.emit('error', 'error for test purpose', 10); }); return fakeTransactionManagerWithEvent; }); const requestLogic = new RequestLogic( fakeTransactionManagerEmittingError, TestData.fakeSignatureProvider, ); const ret = await requestLogic.createEncryptedRequest( createParams, TestData.payeeRaw.identity, [TestData.payeeRaw.encryptionParams, TestData.payerRaw.encryptionParams], ); // eslint-disable-next-line const handleError = jest.fn((error: any) => { // 'error wrong' expect(error).toEqual('error for test purpose'); }); ret.on('error', handleError); jest.advanceTimersByTime(11); expect(handleError).toHaveBeenCalled(); // 'ret.result is wrong' expect(ret.result).toEqual({ requestId }); // 'ret.meta is wrong' expect(ret.meta).toEqual({ transactionManagerMeta: fakeMetaTransactionManager.meta, }); expect(fakeTransactionManagerEmittingError.persistTransaction).toHaveBeenCalledWith( JSON.stringify(action), requestId, [], [TestData.payeeRaw.encryptionParams, TestData.payerRaw.encryptionParams], ); jest.useRealTimers(); }); }); describe('computeRequestId', () => { it('cannot computeRequestId without signature provider', async () => { const requestLogic = new RequestLogic(fakeTransactionManager); await expect( requestLogic.computeRequestId(createParams, TestData.payeeRaw.identity), ).rejects.toThrowError('You must give a signature provider to create actions'); }); it('cannot compute request id if apply fails in the advanced request logic', async () => { const fakeAdvancedLogic: AdvancedLogicTypes.IAdvancedLogic = { applyActionToExtensions: (): RequestLogicTypes.IExtensionStates => { throw new Error('Expected throw'); }, extensions: {}, }; const requestLogic = new RequestLogic( fakeTransactionManager, TestData.fakeSignatureProvider, fakeAdvancedLogic, ); const createParamsWithExtensions: RequestLogicTypes.ICreateParameters = { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: TestData.arbitraryExpectedAmount, extensionsData: ['whatever'], payee: TestData.payeeRaw.identity, payer: TestData.payerRaw.identity, timestamp: 1544426030, }; await expect( requestLogic.computeRequestId(createParamsWithExtensions, TestData.payeeRaw.identity), ).rejects.toThrowError('Expected throw'); }); it('can computeRequestId', async () => { const requestLogic = new RequestLogic(fakeTransactionManager, TestData.fakeSignatureProvider); const generatedRequestId = await requestLogic.computeRequestId( createParams, TestData.payeeRaw.identity, ); expect(generatedRequestId).toBe(requestId); expect(fakeTransactionManager.persistTransaction).not.toHaveBeenCalled(); }); }); describe('acceptRequest', () => { it('can acceptRequest', async () => { const acceptParams = { requestId, }; const requestLogic = new RequestLogic(fakeTransactionManager, TestData.fakeSignatureProvider); const ret = await requestLogic.acceptRequest(acceptParams, TestData.payerRaw.identity); ret.on('confirmed', (resultConfirmed1) => { // 'result Confirmed wrong' expect(resultConfirmed1).toEqual({ meta: { transactionManagerMeta: { storageDataId: 'fakeDataId', }, }, }); }); // 'ret.result is wrong' expect(ret.result).toBeUndefined(); expect(ret.meta).toEqual({ transactionManagerMeta: fakeMetaTransactionManager.meta, }); const data = { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: acceptParams, version: CURRENT_VERSION, }; const actionExpected = TestData.fakeSignatureProvider.sign(data, TestData.payerRaw.identity); expect(fakeTransactionManager.persistTransaction).toHaveBeenCalledWith( JSON.stringify(actionExpected), requestId, ); }); it('cannot acceptRequest without signature provider', async () => { const requestLogic = new RequestLogic(fakeTransactionManager); const acceptParams = { requestId, }; await expect( requestLogic.acceptRequest(acceptParams, TestData.payeeRaw.identity), ).rejects.toThrowError('You must give a signature provider to create actions'); }); it('cannot accept as payee', async () => { const actionCreate = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: '123400000000000000', payee: TestData.payeeRaw.identity, payer: TestData.payerRaw.identity, timestamp: 1544426030, }, version: CURRENT_VERSION, }, TestData.payeeRaw.signatureParams, ); const transactionManager: TransactionTypes.ITransactionManager = { getChannelsByMultipleTopics: jest.fn() as any, getChannelsByTopic: jest.fn() as any, getTransactionsByChannelId: jest.fn().mockReturnValue( Promise.resolve({ meta: { ignoredTransactions: [] }, result: { transactions: [ { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 1, transaction: { data: JSON.stringify(actionCreate) }, }, ], }, }), ), persistTransaction: jest.fn() as any, }; const acceptParams = { requestId, }; const requestLogic = new RequestLogic(transactionManager, TestData.fakeSignatureProvider); await expect( requestLogic.acceptRequest(acceptParams, TestData.payeeRaw.identity, true), ).rejects.toThrowError('Signer must be the payer'); }); }); describe('cancelRequest', () => { it('can cancelRequest', async () => { const cancelRequest = { requestId, }; const requestLogic = new RequestLogic(fakeTransactionManager, TestData.fakeSignatureProvider); const ret = await requestLogic.cancelRequest(cancelRequest, TestData.payeeRaw.identity); ret.on('confirmed', (resultConfirmed1) => { // 'result Confirmed wrong' expect(resultConfirmed1).toEqual({ meta: { transactionManagerMeta: { storageDataId: 'fakeDataId', }, }, }); }); // 'ret.result is wrong' expect(ret.result).toBeUndefined(); expect(ret.meta).toEqual({ transactionManagerMeta: fakeMetaTransactionManager.meta, }); const data = { name: RequestLogicTypes.ACTION_NAME.CANCEL, parameters: cancelRequest, version: CURRENT_VERSION, }; const actionExpected = TestData.fakeSignatureProvider.sign(data, TestData.payeeRaw.identity); expect(fakeTransactionManager.persistTransaction).toHaveBeenCalledWith( JSON.stringify(actionExpected), requestId, ); }); it('cannot cancelRequest without signature provider', async () => { const requestLogic = new RequestLogic(fakeTransactionManager); const cancelParams = { requestId, }; await expect( requestLogic.cancelRequest(cancelParams, TestData.payeeRaw.identity), ).rejects.toThrowError('You must give a signature provider to create actions'); }); it('cannot cancel if not payee or payer', async () => { const actionCreate = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: '123400000000000000', payee: TestData.payeeRaw.identity, payer: TestData.payerRaw.identity, timestamp: 1544426030, }, version: CURRENT_VERSION, }, TestData.payeeRaw.signatureParams, ); const transactionManager: TransactionTypes.ITransactionManager = { getChannelsByMultipleTopics: jest.fn() as any, getChannelsByTopic: jest.fn() as any, getTransactionsByChannelId: jest.fn().mockReturnValue( Promise.resolve({ meta: { ignoredTransactions: [] }, result: { transactions: [ { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 1, transaction: { data: JSON.stringify(actionCreate) }, }, ], }, }), ), persistTransaction: jest.fn() as any, }; const cancelParams = { requestId, }; const requestLogic = new RequestLogic(transactionManager, TestData.fakeSignatureProvider); await expect( requestLogic.cancelRequest(cancelParams, TestData.otherIdRaw.identity, true), ).rejects.toThrowError('Signer must be the payer or the payee'); }); }); describe('increaseExpectedAmountRequest', () => { it('can increaseExpectedAmountRequest', async () => { const increaseRequest = { deltaAmount: '1000', requestId, }; const requestLogic = new RequestLogic(fakeTransactionManager, TestData.fakeSignatureProvider); const ret = await requestLogic.increaseExpectedAmountRequest( increaseRequest, TestData.payerRaw.identity, ); ret.on('confirmed', (resultConfirmed1) => { // 'result Confirmed wrong' expect(resultConfirmed1).toEqual({ meta: { transactionManagerMeta: { storageDataId: 'fakeDataId', }, }, }); }); // 'ret.result is wrong' expect(ret.result).toBeUndefined(); expect(ret.meta).toEqual({ transactionManagerMeta: fakeMetaTransactionManager.meta, }); const data = { name: RequestLogicTypes.ACTION_NAME.INCREASE_EXPECTED_AMOUNT, parameters: increaseRequest, version: CURRENT_VERSION, }; const actionExpected = TestData.fakeSignatureProvider.sign(data, TestData.payerRaw.identity); expect(fakeTransactionManager.persistTransaction).toHaveBeenCalledWith( JSON.stringify(actionExpected), requestId, ); }); it('cannot increaseExpectedAmountRequest without signature provider', async () => { const requestLogic = new RequestLogic(fakeTransactionManager); const increaseRequest = { deltaAmount: '1000', requestId, }; await expect( requestLogic.increaseExpectedAmountRequest(increaseRequest, TestData.payerRaw.identity), ).rejects.toThrowError('You must give a signature provider to create actions'); }); it('cannot increaseExpectedAmountRequest as payee', async () => { const actionCreate = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: '123400000000000000', payee: TestData.payeeRaw.identity, payer: TestData.payerRaw.identity, timestamp: 1544426030, }, version: CURRENT_VERSION, }, TestData.payeeRaw.signatureParams, ); const transactionManager: TransactionTypes.ITransactionManager = { getChannelsByMultipleTopics: jest.fn() as any, getChannelsByTopic: jest.fn() as any, getTransactionsByChannelId: jest.fn().mockReturnValue( Promise.resolve({ meta: { ignoredTransactions: [] }, result: { transactions: [ { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 1, transaction: { data: JSON.stringify(actionCreate) }, }, ], }, }), ), persistTransaction: jest.fn() as any, }; const increaseRequest = { deltaAmount: '1000', requestId, }; const requestLogic = new RequestLogic(transactionManager, TestData.fakeSignatureProvider); await expect( requestLogic.increaseExpectedAmountRequest( increaseRequest, TestData.payeeRaw.identity, true, ), ).rejects.toThrowError('signer must be the payer'); }); }); describe('reduceExpectedAmountRequest', () => { it('can reduceExpectedAmountRequest', async () => { const reduceRequest = { deltaAmount: '1000', requestId, }; const requestLogic = new RequestLogic(fakeTransactionManager, TestData.fakeSignatureProvider); const ret = await requestLogic.reduceExpectedAmountRequest( reduceRequest, TestData.payeeRaw.identity, ); ret.on('confirmed', (resultConfirmed1) => { // 'result Confirmed wrong' expect(resultConfirmed1).toEqual({ meta: { transactionManagerMeta: { storageDataId: 'fakeDataId', }, }, }); }); // 'ret.result is wrong' expect(ret.result).toBeUndefined(); expect(ret.meta).toEqual({ transactionManagerMeta: fakeMetaTransactionManager.meta, }); const data = { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: reduceRequest, version: CURRENT_VERSION, }; const actionExpected = TestData.fakeSignatureProvider.sign(data, TestData.payeeRaw.identity); expect(fakeTransactionManager.persistTransaction).toHaveBeenCalledWith( JSON.stringify(actionExpected), requestId, ); }); it('cannot reduceExpectedAmountRequest without signature provider', async () => { const requestLogic = new RequestLogic(fakeTransactionManager); const reduceRequest = { deltaAmount: '1000', requestId, }; await expect( requestLogic.reduceExpectedAmountRequest(reduceRequest, TestData.payeeRaw.identity), ).rejects.toThrowError('You must give a signature provider to create actions'); }); it('cannot reduceExpectedAmountRequest as payer', async () => { const actionCreate = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: '123400000000000000', payee: TestData.payeeRaw.identity, payer: TestData.payerRaw.identity, timestamp: 1544426030, }, version: CURRENT_VERSION, }, TestData.payeeRaw.signatureParams, ); const transactionManager: TransactionTypes.ITransactionManager = { getChannelsByMultipleTopics: jest.fn() as any, getChannelsByTopic: jest.fn() as any, getTransactionsByChannelId: jest.fn().mockReturnValue( Promise.resolve({ meta: { ignoredTransactions: [] }, result: { transactions: [ { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 1, transaction: { data: JSON.stringify(actionCreate) }, }, ], }, }), ), persistTransaction: jest.fn() as any, }; const increaseRequest = { deltaAmount: '1000', requestId, }; const requestLogic = new RequestLogic(transactionManager, TestData.fakeSignatureProvider); await expect( requestLogic.reduceExpectedAmountRequest(increaseRequest, TestData.payerRaw.identity, true), ).rejects.toThrowError('signer must be the payee'); }); }); describe('addExtensionsDataRequest', () => { it('can addExtensionsDataRequest', async () => { const addExtRequest = { extensionsData: TestData.oneExtension, requestId, }; const requestLogic = new RequestLogic(fakeTransactionManager, TestData.fakeSignatureProvider); const ret = await requestLogic.addExtensionsDataRequest( addExtRequest, TestData.payeeRaw.identity, ); ret.on('confirmed', (resultConfirmed1) => { // 'result Confirmed wrong' expect(resultConfirmed1).toEqual({ meta: { transactionManagerMeta: { storageDataId: 'fakeDataId', }, }, }); }); // 'ret.result is wrong' expect(ret.result).toBeUndefined(); expect(ret.meta).toEqual({ transactionManagerMeta: fakeMetaTransactionManager.meta, }); const data = { name: RequestLogicTypes.ACTION_NAME.ADD_EXTENSIONS_DATA, parameters: addExtRequest, version: CURRENT_VERSION, }; const actionExpected = TestData.fakeSignatureProvider.sign(data, TestData.payeeRaw.identity); expect(fakeTransactionManager.persistTransaction).toHaveBeenCalledWith( JSON.stringify(actionExpected), requestId, ); }); it('cannot addExtensionsDataRequest without signature provider', async () => { const requestLogic = new RequestLogic(fakeTransactionManager); const addExtRequest = { extensionsData: TestData.oneExtension, requestId, }; await expect( requestLogic.addExtensionsDataRequest(addExtRequest, TestData.payeeRaw.identity), ).rejects.toThrowError('You must give a signature provider to create actions'); }); it('cannot addExtension if apply fail in the advanced request logic', async () => { const fakeAdvancedLogic: AdvancedLogicTypes.IAdvancedLogic = { applyActionToExtensions: (): RequestLogicTypes.IExtensionStates => { throw new Error('Expected throw'); }, extensions: {}, }; const actionCreate = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: '123400000000000000', payee: TestData.payeeRaw.identity, payer: TestData.payerRaw.identity, timestamp: 1544426030, }, version: CURRENT_VERSION, }, TestData.payeeRaw.signatureParams, ); const transactionManager: TransactionTypes.ITransactionManager = { getChannelsByMultipleTopics: jest.fn() as any, getChannelsByTopic: jest.fn() as any, getTransactionsByChannelId: jest.fn().mockReturnValue( Promise.resolve({ meta: { ignoredTransactions: [] }, result: { transactions: [ { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 1, transaction: { data: JSON.stringify(actionCreate) }, }, ], }, }), ), persistTransaction: jest.fn() as any, }; const addExtensionParams = { extensionsData: ['whatever'], requestId, }; const requestLogic = new RequestLogic( transactionManager, TestData.fakeSignatureProvider, fakeAdvancedLogic, ); await expect( requestLogic.addExtensionsDataRequest(addExtensionParams, TestData.payeeRaw.identity, true), ).rejects.toThrowError('Expected throw'); }); }); describe('getRequestFromId', () => { it('can getRequestFromId', async () => { const actionCreate: RequestLogicTypes.IAction = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: '123400000000000000', payee: TestData.payeeRaw.identity, payer: TestData.payerRaw.identity, timestamp: 1544426030, }, version: CURRENT_VERSION, }, TestData.payeeRaw.signatureParams, ); const actionAccept: RequestLogicTypes.IAction = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { requestId, }, version: CURRENT_VERSION, }, TestData.payerRaw.signatureParams, ); const rxReduce: RequestLogicTypes.IAction = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { deltaAmount: '1000', requestId, }, version: CURRENT_VERSION, }, TestData.payeeRaw.signatureParams, ); const meta = { ignoredTransactions: [] }; const listActions: Promise<TransactionTypes.IReturnGetTransactions> = Promise.resolve({ meta, result: { transactions: [ { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 1, transaction: { data: JSON.stringify(actionCreate) }, }, { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 2, transaction: { data: JSON.stringify(actionAccept) }, }, { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 3, transaction: { data: JSON.stringify(rxReduce) }, }, ], }, }); const fakeTransactionManagerGet: TransactionTypes.ITransactionManager = { getChannelsByMultipleTopics: jest.fn() as any, getChannelsByTopic: jest.fn() as any, getTransactionsByChannelId: (): Promise<TransactionTypes.IReturnGetTransactions> => listActions, persistTransaction: jest.fn() as any, }; const requestLogic = new RequestLogic( fakeTransactionManagerGet, TestData.fakeSignatureProvider, ); const request = await requestLogic.getRequestFromId(requestId); // 'request result is wrong' expect(request).toEqual({ meta: { ignoredTransactions: [], transactionManagerMeta: meta, }, result: { pending: null, request: { creator: TestData.payeeRaw.identity, currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, events: [ { actionSigner: TestData.payeeRaw.identity, name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { expectedAmount: '123400000000000000', extensionsDataLength: 0, isSignedRequest: false, }, timestamp: 1, }, { actionSigner: TestData.payerRaw.identity, name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { extensionsDataLength: 0, }, timestamp: 2, }, { actionSigner: TestData.payeeRaw.identity, name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { deltaAmount: '1000', extensionsDataLength: 0, }, timestamp: 3, }, ], expectedAmount: '123399999999999000', extensions: {}, payee: TestData.payeeRaw.identity, payer: TestData.payerRaw.identity, requestId, state: RequestLogicTypes.STATE.ACCEPTED, timestamp: 1544426030, version: CURRENT_VERSION, }, }, }); }); it('can getRequestFromId ignore old pending transaction', async () => { const actionCreate: RequestLogicTypes.IAction = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: '123400000000000000', payee: TestData.payeeRaw.identity, payer: TestData.payerRaw.identity, timestamp: 1544426030, }, version: CURRENT_VERSION, }, TestData.payeeRaw.signatureParams, ); const actionAccept: RequestLogicTypes.IAction = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { requestId, }, version: CURRENT_VERSION, }, TestData.payerRaw.signatureParams, ); const rxReduce: RequestLogicTypes.IAction = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { deltaAmount: '1000', requestId, }, version: CURRENT_VERSION, }, TestData.payeeRaw.signatureParams, ); const meta = { ignoredTransactions: [] }; const listActions: Promise<TransactionTypes.IReturnGetTransactions> = Promise.resolve({ meta, result: { transactions: [ { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 1, transaction: { data: JSON.stringify(actionCreate) }, }, { state: TransactionTypes.TransactionState.PENDING, timestamp: 2, transaction: { data: JSON.stringify(actionAccept) }, }, { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 3, transaction: { data: JSON.stringify(rxReduce) }, }, ], }, }); const fakeTransactionManagerGet: TransactionTypes.ITransactionManager = { getChannelsByMultipleTopics: jest.fn() as any, getChannelsByTopic: jest.fn() as any, getTransactionsByChannelId: (): Promise<TransactionTypes.IReturnGetTransactions> => listActions, persistTransaction: jest.fn() as any, }; const requestLogic = new RequestLogic( fakeTransactionManagerGet, TestData.fakeSignatureProvider, ); const request = await requestLogic.getRequestFromId(requestId); // 'request result is wrong' expect(request).toEqual({ meta: { ignoredTransactions: [ { reason: 'Confirmed transaction newer than this pending transaction', transaction: { state: TransactionTypes.TransactionState.PENDING, timestamp: 2, transaction: { data: '{"data":{"name":"accept","parameters":{"requestId":"010246b8aeb3aa72f4c7039284bf7307c3d543541ff309ee52e9361f4bd2c89c9c"},"version":"2.0.3"},"signature":{"method":"ecdsa","value":"0xe53448080b32927c66827f3d946e988f18cfa4dfa640e15563eb4c266ab65e3932df94fdab3e3625da4f41b8ce8ef56c3ae39d89189859c3d3090ca4503247141b"}}', }, }, }, ], transactionManagerMeta: meta, }, result: { pending: null, request: { creator: TestData.payeeRaw.identity, currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, events: [ { actionSigner: TestData.payeeRaw.identity, name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { expectedAmount: '123400000000000000', extensionsDataLength: 0, isSignedRequest: false, }, timestamp: 1, }, { actionSigner: TestData.payeeRaw.identity, name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { deltaAmount: '1000', extensionsDataLength: 0, }, timestamp: 3, }, ], expectedAmount: '123399999999999000', extensions: {}, payee: TestData.payeeRaw.identity, payer: TestData.payerRaw.identity, requestId, state: RequestLogicTypes.STATE.CREATED, timestamp: 1544426030, version: CURRENT_VERSION, }, }, }); }); it('can getRequestFromId with pending transaction', async () => { const actionCreate: RequestLogicTypes.IAction = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: '123400000000000000', payee: TestData.payeeRaw.identity, payer: TestData.payerRaw.identity, timestamp: 1544426030, }, version: CURRENT_VERSION, }, TestData.payeeRaw.signatureParams, ); const actionAccept: RequestLogicTypes.IAction = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { requestId, }, version: CURRENT_VERSION, }, TestData.payerRaw.signatureParams, ); const rxReduce: RequestLogicTypes.IAction = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { deltaAmount: '1000', requestId, }, version: CURRENT_VERSION, }, TestData.payeeRaw.signatureParams, ); const meta = { ignoredTransactions: [] }; const listActions: Promise<TransactionTypes.IReturnGetTransactions> = Promise.resolve({ meta, result: { transactions: [ { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 1, transaction: { data: JSON.stringify(actionCreate) }, }, { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 2, transaction: { data: JSON.stringify(actionAccept) }, }, { state: TransactionTypes.TransactionState.PENDING, timestamp: 3, transaction: { data: JSON.stringify(rxReduce) }, }, ], }, }); const fakeTransactionManagerGet: TransactionTypes.ITransactionManager = { getChannelsByMultipleTopics: jest.fn() as any, getChannelsByTopic: jest.fn() as any, getTransactionsByChannelId: (): Promise<TransactionTypes.IReturnGetTransactions> => listActions, persistTransaction: jest.fn() as any, }; const requestLogic = new RequestLogic( fakeTransactionManagerGet, TestData.fakeSignatureProvider, ); const request = await requestLogic.getRequestFromId(requestId); // 'request result is wrong' expect(request).toEqual({ meta: { ignoredTransactions: [], transactionManagerMeta: meta, }, result: { pending: { events: [ { actionSigner: TestData.payeeRaw.identity, name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { deltaAmount: '1000', extensionsDataLength: 0, }, timestamp: 3, }, ], expectedAmount: '123399999999999000', }, request: { creator: TestData.payeeRaw.identity, currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, events: [ { actionSigner: TestData.payeeRaw.identity, name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { expectedAmount: '123400000000000000', extensionsDataLength: 0, isSignedRequest: false, }, timestamp: 1, }, { actionSigner: TestData.payerRaw.identity, name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { extensionsDataLength: 0, }, timestamp: 2, }, ], expectedAmount: '123400000000000000', extensions: {}, payee: TestData.payeeRaw.identity, payer: TestData.payerRaw.identity, requestId, state: RequestLogicTypes.STATE.ACCEPTED, timestamp: 1544426030, version: CURRENT_VERSION, }, }, }); }); it('can getRequestFromId ignore the same transactions even with different case', async () => { const actionCreate: RequestLogicTypes.IAction = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: '123400000000000000', payee: TestData.payeeRaw.identity, payer: TestData.payerRaw.identity, timestamp: 1544426030, }, version: CURRENT_VERSION, }, TestData.payeeRaw.signatureParams, ); const actionAccept: RequestLogicTypes.IAction = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { requestId, }, version: CURRENT_VERSION, }, TestData.payerRaw.signatureParams, ); const actionReduce: RequestLogicTypes.IAction = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { deltaAmount: '1000', requestId, }, version: CURRENT_VERSION, }, TestData.payeeRaw.signatureParams, ); const actionReduce2: RequestLogicTypes.IAction = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { deltaAmount: '1000', requestId: requestId.toUpperCase(), }, version: CURRENT_VERSION, }, TestData.payeeRaw.signatureParams, ); const meta = { ignoredTransactions: [] }; const listActions: Promise<TransactionTypes.IReturnGetTransactions> = Promise.resolve({ meta, result: { transactions: [ { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 1, transaction: { data: JSON.stringify(actionCreate) }, }, { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 2, transaction: { data: JSON.stringify(actionAccept) }, }, { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 3, transaction: { data: JSON.stringify(actionReduce) }, }, { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 4, transaction: { data: JSON.stringify(actionReduce2) }, }, ], }, }); const fakeTransactionManagerGet: TransactionTypes.ITransactionManager = { getChannelsByMultipleTopics: jest.fn() as any, getChannelsByTopic: jest.fn() as any, getTransactionsByChannelId: (): Promise<TransactionTypes.IReturnGetTransactions> => listActions, persistTransaction: jest.fn() as any, }; const requestLogic = new RequestLogic( fakeTransactionManagerGet, TestData.fakeSignatureProvider, ); const request = await requestLogic.getRequestFromId(requestId); // 'request result is wrong' expect(request).toEqual({ meta: { ignoredTransactions: [ { reason: 'Duplicated transaction', transaction: { action: actionReduce2, state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 4, }, }, ], transactionManagerMeta: meta, }, result: { pending: null, request: { creator: TestData.payeeRaw.identity, currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, events: [ { actionSigner: TestData.payeeRaw.identity, name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { expectedAmount: '123400000000000000', extensionsDataLength: 0, isSignedRequest: false, }, timestamp: 1, }, { actionSigner: TestData.payerRaw.identity, name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { extensionsDataLength: 0, }, timestamp: 2, }, { actionSigner: TestData.payeeRaw.identity, name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { deltaAmount: '1000', extensionsDataLength: 0, }, timestamp: 3, }, ], expectedAmount: '123399999999999000', extensions: {}, payee: TestData.payeeRaw.identity, payer: TestData.payerRaw.identity, requestId, state: RequestLogicTypes.STATE.ACCEPTED, timestamp: 1544426030, version: CURRENT_VERSION, }, }, }); }); it('can getRequestFromId do not ignore the same transactions if different nonces', async () => { const actionCreate: RequestLogicTypes.IAction = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: '123400000000000000', payee: TestData.payeeRaw.identity, payer: TestData.payerRaw.identity, timestamp: 1544426030, }, version: CURRENT_VERSION, }, TestData.payeeRaw.signatureParams, ); const actionAccept: RequestLogicTypes.IAction = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { requestId, }, version: CURRENT_VERSION, }, TestData.payerRaw.signatureParams, ); const actionReduce: RequestLogicTypes.IAction = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { deltaAmount: '1000', requestId, }, version: CURRENT_VERSION, }, TestData.payeeRaw.signatureParams, ); const actionReduce2: RequestLogicTypes.IAction = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { deltaAmount: '1000', nonce: 1, requestId: requestId.toUpperCase(), }, version: CURRENT_VERSION, }, TestData.payeeRaw.signatureParams, ); const meta = { ignoredTransactions: [] }; const listActions: Promise<TransactionTypes.IReturnGetTransactions> = Promise.resolve({ meta, result: { transactions: [ { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 1, transaction: { data: JSON.stringify(actionCreate) }, }, { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 2, transaction: { data: JSON.stringify(actionAccept) }, }, { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 3, transaction: { data: JSON.stringify(actionReduce) }, }, { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 4, transaction: { data: JSON.stringify(actionReduce2) }, }, ], }, }); const fakeTransactionManagerGet: TransactionTypes.ITransactionManager = { getChannelsByMultipleTopics: jest.fn() as any, getChannelsByTopic: jest.fn() as any, getTransactionsByChannelId: (): Promise<TransactionTypes.IReturnGetTransactions> => listActions, persistTransaction: jest.fn() as any, }; const requestLogic = new RequestLogic( fakeTransactionManagerGet, TestData.fakeSignatureProvider, ); const request = await requestLogic.getRequestFromId(requestId); // 'request result is wrong' expect(request).toEqual({ meta: { ignoredTransactions: [], transactionManagerMeta: meta, }, result: { pending: null, request: { creator: TestData.payeeRaw.identity, currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, events: [ { actionSigner: TestData.payeeRaw.identity, name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { expectedAmount: '123400000000000000', extensionsDataLength: 0, isSignedRequest: false, }, timestamp: 1, }, { actionSigner: TestData.payerRaw.identity, name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { extensionsDataLength: 0, }, timestamp: 2, }, { actionSigner: TestData.payeeRaw.identity, name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { deltaAmount: '1000', extensionsDataLength: 0, }, timestamp: 3, }, { actionSigner: TestData.payeeRaw.identity, name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { deltaAmount: '1000', extensionsDataLength: 0, }, timestamp: 4, }, ], expectedAmount: '123399999999998000', extensions: {}, payee: TestData.payeeRaw.identity, payer: TestData.payerRaw.identity, requestId, state: RequestLogicTypes.STATE.ACCEPTED, timestamp: 1544426030, version: CURRENT_VERSION, }, }, }); }); it('should ignored the corrupted data (not parsable JSON)', async () => { const transactionNotParsable = { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 2, transaction: { data: '{NOT parsable}' }, }; const listActions: Promise<TransactionTypes.IReturnGetTransactions> = Promise.resolve({ meta: { ignoredTransactions: [] }, result: { transactions: [transactionNotParsable], }, }); const fakeTransactionManagerGet: TransactionTypes.ITransactionManager = { getChannelsByMultipleTopics: jest.fn() as any, getChannelsByTopic: jest.fn() as any, getTransactionsByChannelId: (): Promise<TransactionTypes.IReturnGetTransactions> => listActions, persistTransaction: jest.fn() as any, }; const requestLogic = new RequestLogic( fakeTransactionManagerGet, TestData.fakeSignatureProvider, ); const request = await requestLogic.getRequestFromId(requestId); expect(request.meta.ignoredTransactions && request.meta.ignoredTransactions.length).toBe(1); expect(request.meta.ignoredTransactions && request.meta.ignoredTransactions[0]).toEqual({ reason: 'JSON parsing error', transaction: transactionNotParsable, }); // 'request should be null' expect(request.result.request).toBeNull(); }); it('should ignored the corrupted data (e.g: wrong properties)', async () => { const actionCorrupted: RequestLogicTypes.IAction = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: 'NOT A NUMBER', payee: TestData.payeeRaw.identity, payer: TestData.payerRaw.identity, timestamp: 1544426030, }, version: CURRENT_VERSION, }, TestData.payeeRaw.signatureParams, ); const listActions: Promise<TransactionTypes.IReturnGetTransactions> = Promise.resolve({ meta: { ignoredTransactions: [] }, result: { transactions: [ { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 2, transaction: { data: JSON.stringify(actionCorrupted) }, }, ], }, }); const fakeTransactionManagerGet: TransactionTypes.ITransactionManager = { getChannelsByMultipleTopics: jest.fn() as any, getChannelsByTopic: jest.fn() as any, getTransactionsByChannelId: (): Promise<TransactionTypes.IReturnGetTransactions> => listActions, persistTransaction: jest.fn() as any, }; const requestLogic = new RequestLogic( fakeTransactionManagerGet, TestData.fakeSignatureProvider, ); const request = await requestLogic.getRequestFromId(requestId); expect(request.meta.ignoredTransactions && request.meta.ignoredTransactions.length).toBe(1); expect(request.meta.ignoredTransactions && request.meta.ignoredTransactions[0]).toEqual({ reason: 'action.parameters.expectedAmount must be a string representing a positive integer', transaction: { action: actionCorrupted, state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 2, }, }); // 'request should be null' expect(request.result.request).toBeNull(); }); }); describe('getRequestsByTopic', () => { it('can getRequestsByTopic', async () => { const unsignedActionCreation = { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: '123400000000000000', payee: TestData.payeeRaw.identity, payer: TestData.payerRaw.identity, timestamp: 1544426030, }, version: CURRENT_VERSION, }; const actionCreate: RequestLogicTypes.IAction = Utils.signature.sign( unsignedActionCreation, TestData.payeeRaw.signatureParams, ); const newRequestId = MultiFormat.serialize( Utils.crypto.normalizeKeccak256Hash(unsignedActionCreation), ); const actionAccept: RequestLogicTypes.IAction = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { requestId: newRequestId, }, version: CURRENT_VERSION, }, TestData.payerRaw.signatureParams, ); const rxReduce: RequestLogicTypes.IAction = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { deltaAmount: '1000', requestId: newRequestId, }, version: CURRENT_VERSION, }, TestData.payeeRaw.signatureParams, ); const unsignedActionCreation2 = { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { currency: { type: RequestLogicTypes.CURRENCY.BTC, value: 'BTC', }, expectedAmount: '10', payee: TestData.payeeRaw.identity, payer: TestData.payerRaw.identity, timestamp: 1544411111, }, version: CURRENT_VERSION, }; const actionCreate2: RequestLogicTypes.IAction = Utils.signature.sign( unsignedActionCreation2, TestData.payeeRaw.signatureParams, ); const newRequestId2 = MultiFormat.serialize( Utils.crypto.normalizeKeccak256Hash(unsignedActionCreation2), ); const actionCancel2: RequestLogicTypes.IAction = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.CANCEL, parameters: { requestId: newRequestId2, }, version: CURRENT_VERSION, }, TestData.payerRaw.signatureParams, ); const unsignedActionCreation3 = { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { currency: { type: RequestLogicTypes.CURRENCY.BTC, value: 'BTC', }, expectedAmount: '666', payee: TestData.payeeRaw.identity, payer: TestData.payerRaw.identity, timestamp: 1544433333, }, version: CURRENT_VERSION, }; const actionCreate3: RequestLogicTypes.IAction = Utils.signature.sign( unsignedActionCreation3, TestData.payeeRaw.signatureParams, ); const newRequestId3 = MultiFormat.serialize( Utils.crypto.normalizeKeccak256Hash(unsignedActionCreation3), ); const meta = { dataAccessMeta: { [requestId]: [], [newRequestId2]: [], [newRequestId3]: [] }, ignoredTransactions: {}, }; const listAllActions: Promise<TransactionTypes.IReturnGetTransactionsByChannels> = Promise.resolve( { meta, result: { transactions: { [requestId]: [ { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 0, transaction: { data: JSON.stringify(actionCreate) }, }, { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 2, transaction: { data: JSON.stringify(actionAccept) }, }, { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 3, transaction: { data: JSON.stringify(rxReduce) }, }, ], [newRequestId2]: [ { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 1, transaction: { data: JSON.stringify(actionCreate2) }, }, { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 2, transaction: { data: JSON.stringify(actionCancel2) }, }, ], [newRequestId3]: [ { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 4, transaction: { data: JSON.stringify(actionCreate3) }, }, ], }, }, }, ); const fakeTransactionManagerGet: TransactionTypes.ITransactionManager = { getChannelsByMultipleTopics: jest.fn() as any, getChannelsByTopic: (): Promise<TransactionTypes.IReturnGetTransactionsByChannels> => { return listAllActions; }, getTransactionsByChannelId: jest.fn() as any, persistTransaction: jest.fn() as any, }; const requestLogic = new RequestLogic( fakeTransactionManagerGet, TestData.fakeSignatureProvider, ); const requests = await requestLogic.getRequestsByTopic('fakeTopicForAll'); // 'requests result is wrong' expect(requests.result.requests.length).toBe(3); }); it('can getRequestsByTopic with pending transactions', async () => { const unsignedActionCreation = { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: '123400000000000000', payee: TestData.payeeRaw.identity, payer: TestData.payerRaw.identity, timestamp: 1544426030, }, version: CURRENT_VERSION, }; const actionCreate: RequestLogicTypes.IAction = Utils.signature.sign( unsignedActionCreation, TestData.payeeRaw.signatureParams, ); const newRequestId = MultiFormat.serialize( Utils.crypto.normalizeKeccak256Hash(unsignedActionCreation), ); const actionAccept: RequestLogicTypes.IAction = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { requestId: newRequestId, }, version: CURRENT_VERSION, }, TestData.payerRaw.signatureParams, ); const rxReduce: RequestLogicTypes.IAction = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { deltaAmount: '1000', requestId: newRequestId, }, version: CURRENT_VERSION, }, TestData.payeeRaw.signatureParams, ); const unsignedActionCreation2 = { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { currency: { type: RequestLogicTypes.CURRENCY.BTC, value: 'BTC', }, expectedAmount: '10', payee: TestData.payeeRaw.identity, payer: TestData.payerRaw.identity, timestamp: 1544411111, }, version: CURRENT_VERSION, }; const actionCreate2: RequestLogicTypes.IAction = Utils.signature.sign( unsignedActionCreation2, TestData.payeeRaw.signatureParams, ); const newRequestId2 = MultiFormat.serialize( Utils.crypto.normalizeKeccak256Hash(unsignedActionCreation2), ); const actionCancel2: RequestLogicTypes.IAction = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.CANCEL, parameters: { requestId: newRequestId2, }, version: CURRENT_VERSION, }, TestData.payerRaw.signatureParams, ); const unsignedActionCreation3 = { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { currency: { type: RequestLogicTypes.CURRENCY.BTC, value: 'BTC', }, expectedAmount: '666', payee: TestData.payeeRaw.identity, payer: TestData.payerRaw.identity, timestamp: 1544433333, }, version: CURRENT_VERSION, }; const actionCreate3: RequestLogicTypes.IAction = Utils.signature.sign( unsignedActionCreation3, TestData.payeeRaw.signatureParams, ); const newRequestId3 = MultiFormat.serialize( Utils.crypto.normalizeKeccak256Hash(unsignedActionCreation3), ); const meta = { dataAccessMeta: { [requestId]: [], [newRequestId2]: [], [newRequestId3]: [] }, ignoredTransactions: {}, }; const listAllActions: Promise<TransactionTypes.IReturnGetTransactionsByChannels> = Promise.resolve( { meta, result: { transactions: { [requestId]: [ { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 0, transaction: { data: JSON.stringify(actionCreate) }, }, { state: TransactionTypes.TransactionState.PENDING, timestamp: 2, transaction: { data: JSON.stringify(actionAccept) }, }, { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 3, transaction: { data: JSON.stringify(rxReduce) }, }, ], [newRequestId2]: [ { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 1, transaction: { data: JSON.stringify(actionCreate2) }, }, { state: TransactionTypes.TransactionState.PENDING, timestamp: 2, transaction: { data: JSON.stringify(actionCancel2) }, }, ], [newRequestId3]: [ { state: TransactionTypes.TransactionState.PENDING, timestamp: 4, transaction: { data: JSON.stringify(actionCreate3) }, }, ], }, }, }, ); const fakeTransactionManagerGet: TransactionTypes.ITransactionManager = { getChannelsByMultipleTopics: jest.fn() as any, getChannelsByTopic: (): Promise<TransactionTypes.IReturnGetTransactionsByChannels> => { return listAllActions; }, getTransactionsByChannelId: jest.fn() as any, persistTransaction: jest.fn() as any, }; const requestLogic = new RequestLogic( fakeTransactionManagerGet, TestData.fakeSignatureProvider, ); const requests = await requestLogic.getRequestsByTopic('fakeTopicForAll'); // 'requests result is wrong' expect(requests.result.requests.length).toBe(3); const firstRequest = requests.result.requests[0]; // 'first pending wrong' expect(firstRequest.pending).toBeNull(); // 'first request expectedAmount wrong' expect(firstRequest.request!.expectedAmount).toEqual('123399999999999000'); // 'first request state wrong' expect(firstRequest.request!.state).toEqual(RequestLogicTypes.STATE.CREATED); const secondRequest = requests.result.requests[1]; // 'second pending wrong' expect(secondRequest.request!.state).toEqual(RequestLogicTypes.STATE.CREATED); // 'second pending wrong' expect(secondRequest.pending!.state).toEqual(RequestLogicTypes.STATE.CANCELED); const thirdRequest = requests.result.requests[2]; // 'third pending wrong' expect(thirdRequest.request).toBeNull(); // 'third pending wrong' expect(thirdRequest.pending!.state).toEqual(RequestLogicTypes.STATE.CREATED); }); it('should ignore the transaction none parsable and the rejected action', async () => { const actionCreate: RequestLogicTypes.IAction = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: '123400000000000000', payee: TestData.payeeRaw.identity, payer: TestData.payerRaw.identity, timestamp: 1544426030, }, version: CURRENT_VERSION, }, TestData.payeeRaw.signatureParams, ); const acceptNotValid: RequestLogicTypes.IAction = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { requestId, }, version: CURRENT_VERSION, }, TestData.payeeRaw.signatureParams, ); const meta = { dataAccessMeta: { [requestId]: [] }, ignoredTransactions: {}, }; const listActions: Promise<TransactionTypes.IReturnGetTransactionsByChannels> = Promise.resolve( { meta, result: { transactions: { [requestId]: [ { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 2, transaction: { data: JSON.stringify(actionCreate) }, }, { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 2, transaction: { data: 'Not a json' }, }, { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 2, transaction: { data: JSON.stringify(acceptNotValid) }, }, ], }, }, }, ); const fakeTransactionManagerGet: TransactionTypes.ITransactionManager = { getChannelsByMultipleTopics: jest.fn() as any, getChannelsByTopic: (): Promise<TransactionTypes.IReturnGetTransactionsByChannels> => { return listActions; }, getTransactionsByChannelId: jest.fn() as any, persistTransaction: jest.fn() as any, }; const requestLogic = new RequestLogic( fakeTransactionManagerGet, TestData.fakeSignatureProvider, ); const requests = await requestLogic.getRequestsByTopic('fakeTopicForAll'); // 'requests result is wrong' expect(requests.result.requests.length).toBe(1); }); }); describe('getRequestsByMultipleTopic', () => { it('can getRequestsByMultipleTopic', async () => { const unsignedActionCreation = { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { currency: { type: RequestLogicTypes.CURRENCY.ETH, value: 'ETH', }, expectedAmount: '123400000000000000', payee: TestData.payeeRaw.identity, payer: TestData.payerRaw.identity, timestamp: 1544426030, }, version: CURRENT_VERSION, }; const actionCreate: RequestLogicTypes.IAction = Utils.signature.sign( unsignedActionCreation, TestData.payeeRaw.signatureParams, ); const newRequestId = MultiFormat.serialize( Utils.crypto.normalizeKeccak256Hash(unsignedActionCreation), ); const actionAccept: RequestLogicTypes.IAction = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.ACCEPT, parameters: { requestId: newRequestId, }, version: CURRENT_VERSION, }, TestData.payerRaw.signatureParams, ); const rxReduce: RequestLogicTypes.IAction = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.REDUCE_EXPECTED_AMOUNT, parameters: { deltaAmount: '1000', requestId: newRequestId, }, version: CURRENT_VERSION, }, TestData.payeeRaw.signatureParams, ); const unsignedActionCreation2 = { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { currency: { type: RequestLogicTypes.CURRENCY.BTC, value: 'BTC', }, expectedAmount: '10', payee: TestData.payeeRaw.identity, payer: TestData.payerRaw.identity, timestamp: 1544411111, }, version: CURRENT_VERSION, }; const actionCreate2: RequestLogicTypes.IAction = Utils.signature.sign( unsignedActionCreation2, TestData.payeeRaw.signatureParams, ); const newRequestId2 = MultiFormat.serialize( Utils.crypto.normalizeKeccak256Hash(unsignedActionCreation2), ); const actionCancel2: RequestLogicTypes.IAction = Utils.signature.sign( { name: RequestLogicTypes.ACTION_NAME.CANCEL, parameters: { requestId: newRequestId2, }, version: CURRENT_VERSION, }, TestData.payerRaw.signatureParams, ); const unsignedActionCreation3 = { name: RequestLogicTypes.ACTION_NAME.CREATE, parameters: { currency: { type: RequestLogicTypes.CURRENCY.BTC, value: 'BTC', }, expectedAmount: '666', payee: TestData.payeeRaw.identity, payer: TestData.payerRaw.identity, timestamp: 1544433333, }, version: CURRENT_VERSION, }; const actionCreate3: RequestLogicTypes.IAction = Utils.signature.sign( unsignedActionCreation3, TestData.payeeRaw.signatureParams, ); const newRequestId3 = MultiFormat.serialize( Utils.crypto.normalizeKeccak256Hash(unsignedActionCreation3), ); const meta = { dataAccessMeta: { [requestId]: [], [newRequestId2]: [], [newRequestId3]: [] }, ignoredTransactions: {}, }; const listAllActions: Promise<TransactionTypes.IReturnGetTransactionsByChannels> = Promise.resolve( { meta, result: { transactions: { [requestId]: [ { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 0, transaction: { data: JSON.stringify(actionCreate) }, }, { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 2, transaction: { data: JSON.stringify(actionAccept) }, }, { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 3, transaction: { data: JSON.stringify(rxReduce) }, }, ], [newRequestId2]: [ { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 1, transaction: { data: JSON.stringify(actionCreate2) }, }, { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 2, transaction: { data: JSON.stringify(actionCancel2) }, }, ], [newRequestId3]: [ { state: TransactionTypes.TransactionState.CONFIRMED, timestamp: 4, transaction: { data: JSON.stringify(actionCreate3) }, }, ], }, }, }, ); const fakeTransactionManagerGet: TransactionTypes.ITransactionManager = { getChannelsByMultipleTopics: (): Promise< TransactionTypes.IReturnGetTransactionsByChannels > => { return listAllActions; }, getChannelsByTopic: jest.fn() as any, getTransactionsByChannelId: jest.fn() as any, persistTransaction: jest.fn() as any, }; const requestLogic = new RequestLogic( fakeTransactionManagerGet, TestData.fakeSignatureProvider, ); const requests = await requestLogic.getRequestsByMultipleTopics(['fakeTopicForAll']); // 'requests result is wrong' expect(requests.result.requests.length).toBe(3); }); }); });
the_stack
import classNames from "classnames"; import { Component, ChangeEvent, useCallback, useEffect, useMemo, useRef, useState, } from "react"; import { BoxScoreRow, BoxScoreWrapper, Confetti, PlayPauseNext, } from "../components"; import useTitleBar from "../hooks/useTitleBar"; import { helpers, processLiveGameEvents, toWorker } from "../util"; import type { View } from "../../common/types"; import { bySport, getPeriodName, isSport } from "../../common"; import useLocalStorageState from "use-local-storage-state"; type PlayerRowProps = { forceUpdate?: boolean; i: number; liveGameInProgress?: boolean; p: any; }; class PlayerRow extends Component<PlayerRowProps> { prevInGame: boolean | undefined; // Can't just switch to hooks and React.memo because p is mutated, so there is no way to access the previous value of inGame in the memo callback function override shouldComponentUpdate(nextProps: PlayerRowProps) { return bySport({ basketball: !!( this.prevInGame || nextProps.p.inGame || nextProps.forceUpdate ), football: true, hockey: !!( this.prevInGame || nextProps.p.inGame || nextProps.p.inPenaltyBox || nextProps.forceUpdate ), }); } override render() { const { p, ...props } = this.props; // Needed for shouldComponentUpdate because state is mutated so we need to explicitly store the last value this.prevInGame = p.inGame; const classes = bySport({ basketball: classNames({ "table-warning": p.inGame, }), football: undefined, hockey: classNames({ "table-warning": p.inGame, "table-danger": p.inPenaltyBox, }), }); return <BoxScoreRow className={classes} p={p} {...props} />; } } const updatePhaseAndLeagueTopBar = () => { // Send to worker, rather than doing `localActions.update({ liveGameInProgress: false });`, so it works in all tabs toWorker("main", "uiUpdateLocal", { liveGameInProgress: false }); }; const getSeconds = (time: string) => { const [min, sec] = time.split(":").map(x => parseInt(x)); return min * 60 + sec; }; const LiveGame = (props: View<"liveGame">) => { const [paused, setPaused] = useState(false); const pausedRef = useRef(paused); const [speed, setSpeed] = useLocalStorageState("live-game-speed", { defaultValue: "7", }); const speedRef = useRef(parseInt(speed)); const [playIndex, setPlayIndex] = useState(-1); const [started, setStarted] = useState(!!props.events); const [confetti, setConfetti] = useState<{ colors?: [string, string, string]; display: boolean; }>({ display: false, }); const boxScore = useRef<any>( props.initialBoxScore ? props.initialBoxScore : {}, ); const overtimes = useRef(0); const playByPlayDiv = useRef<HTMLDivElement | null>(null); const quarters = useRef(isSport("hockey") ? [1] : ["Q1"]); const possessionChange = useRef<boolean | undefined>(); const componentIsMounted = useRef(false); const events = useRef<any[] | undefined>(); // Make sure to call setPlayIndex after calling this! Can't be done inside because React is not always smart enough to batch renders const processToNextPause = useCallback( (force?: boolean): number => { if (!componentIsMounted.current || (pausedRef.current && !force)) { return 0; } const startSeconds = getSeconds(boxScore.current.time); if (!events.current) { throw new Error("events.current is undefined"); } const output = processLiveGameEvents({ boxScore: boxScore.current, events: events.current, overtimes: overtimes.current, quarters: quarters.current, }); const text = output.text; overtimes.current = output.overtimes; quarters.current = output.quarters; possessionChange.current = output.possessionChange; if (text !== undefined) { const p = document.createElement("p"); if (isSport("football") && text.startsWith("Penalty")) { p.innerHTML = text .replace("accepted", "<b>accepted</b>") .replace("declined", "<b>declined</b>") .replace("enforced", "<b>enforced</b>") .replace("overruled", "<b>overruled</b>") .replace("ABBREV0", boxScore.current.teams[1].abbrev) .replace("ABBREV1", boxScore.current.teams[0].abbrev); } else { const node = document.createTextNode(text); if ( text === "End of game" || text.startsWith("Start of") || (isSport("basketball") && text.startsWith("Elam Ending activated! First team to")) || (isSport("hockey") && (text.includes("Goal!") || text.includes("penalty"))) ) { const b = document.createElement("b"); b.appendChild(node); p.appendChild(b); } else { p.appendChild(node); } } if (playByPlayDiv.current) { playByPlayDiv.current.insertBefore( p, playByPlayDiv.current.firstChild, ); } } if (events.current && events.current.length > 0) { if (!pausedRef.current) { setTimeout(() => { processToNextPause(); setPlayIndex(prev => prev + 1); }, 4000 / 1.2 ** speedRef.current); } } else { boxScore.current.time = "0:00"; boxScore.current.gameOver = true; if (boxScore.current.scoringSummary) { for (const event of boxScore.current.scoringSummary) { event.hide = false; } } // Update team records with result of game // Keep in sync with liveGame.ts for (const t of boxScore.current.teams) { if (boxScore.current.playoffs) { if (t.playoffs) { if (boxScore.current.won.tid === t.tid) { t.playoffs.won += 1; if ( props.finals && t.playoffs.won >= boxScore.current.numGamesToWinSeries ) { setConfetti({ display: true, colors: t.colors, }); } } else if (boxScore.current.lost.tid === t.tid) { t.playoffs.lost += 1; } } } else { if (boxScore.current.won.pts === boxScore.current.lost.pts) { // Tied! if (t.tied !== undefined) { t.tied += 1; } } else if (boxScore.current.won.tid === t.tid) { t.won += 1; } else if (boxScore.current.lost.tid === t.tid) { if (boxScore.current.overtimes > 0 && props.otl) { t.otl += 1; } else { t.lost += 1; } } } } updatePhaseAndLeagueTopBar(); } const endSeconds = getSeconds(boxScore.current.time); // This is negative when rolling over to a new quarter const elapsedSeconds = startSeconds - endSeconds; return elapsedSeconds; }, [props.finals, props.otl], ); useEffect(() => { componentIsMounted.current = true; const setPlayByPlayDivHeight = () => { if (playByPlayDiv.current) { // Keep in sync with .live-game-affix if (window.matchMedia("(min-width:768px)").matches) { playByPlayDiv.current.style.height = `${window.innerHeight - 113}px`; } else if (playByPlayDiv.current.style.height !== "") { playByPlayDiv.current.style.removeProperty("height"); } } }; // Keep height of plays list equal to window setPlayByPlayDivHeight(); window.addEventListener("optimizedResize", setPlayByPlayDivHeight); return () => { componentIsMounted.current = false; window.removeEventListener("optimizedResize", setPlayByPlayDivHeight); updatePhaseAndLeagueTopBar(); }; }, []); const startLiveGame = useCallback( (events2: any[]) => { events.current = events2; processToNextPause(); setPlayIndex(prev => prev + 1); }, [processToNextPause], ); useEffect(() => { if (props.events && !started) { boxScore.current = props.initialBoxScore; setStarted(true); startLiveGame(props.events.slice()); } }, [props.events, props.initialBoxScore, started, startLiveGame]); const handleSpeedChange = (event: ChangeEvent<HTMLInputElement>) => { const speed = event.target.value; setSpeed(speed); speedRef.current = parseInt(speed); }; const handlePause = useCallback(() => { setPaused(true); pausedRef.current = true; }, []); const handlePlay = useCallback(() => { setPaused(false); pausedRef.current = false; processToNextPause(); setPlayIndex(prev => prev + 1); }, [processToNextPause]); const handleNextPlay = useCallback(() => { processToNextPause(true); setPlayIndex(prev => prev + 1); }, [processToNextPause]); const fastForwardMenuItems = useMemo(() => { // Plays up to `cutoffs` seconds, or until end of quarter const playSeconds = (cutoff: number) => { let seconds = 0; let numPlays = 0; while (seconds < cutoff && !boxScore.current.gameOver) { const elapsedSeconds = processToNextPause(true); numPlays += 1; if (elapsedSeconds > 0) { seconds += elapsedSeconds; } else if (elapsedSeconds < 0) { // End of quarter, always stop break; } } setPlayIndex(prev => prev + numPlays); }; const playUntilLastTwoMinutes = () => { const quartersToPlay = quarters.current.length >= boxScore.current.numPeriods ? 0 : boxScore.current.numPeriods - quarters.current.length; for (let i = 0; i < quartersToPlay; i++) { playSeconds(Infinity); } const currentSeconds = getSeconds(boxScore.current.time); const targetSeconds = 125; // 2 minutes plus 5 seconds, cause can't always be exact const secoundsToPlay = currentSeconds - targetSeconds; if (secoundsToPlay > 0) { playSeconds(secoundsToPlay); } }; const playUntilElamEnding = () => { let numPlays = 0; while ( boxScore.current.elamTarget === undefined && !boxScore.current.gameOver ) { processToNextPause(true); numPlays += 1; } setPlayIndex(prev => prev + numPlays); }; const playUntilNextScore = () => { const initialPts = boxScore.current.teams[0].pts + boxScore.current.teams[1].pts; let currentPts = initialPts; let numPlays = 0; while (initialPts === currentPts && !boxScore.current.gameOver) { processToNextPause(true); currentPts = boxScore.current.teams[0].pts + boxScore.current.teams[1].pts; numPlays += 1; } setPlayIndex(prev => prev + numPlays); }; const playUntilChangeOfPossession = () => { let numPlays = 0; // If currently on one, play through it if (possessionChange.current) { while (possessionChange.current && !boxScore.current.gameOver) { processToNextPause(true); numPlays += 1; } } // Find next one while (!possessionChange.current && !boxScore.current.gameOver) { processToNextPause(true); numPlays += 1; } setPlayIndex(prev => prev + numPlays); }; let skipMinutes = [ { minutes: 1, key: "O", }, { minutes: helpers.bound( Math.round(props.quarterLength / 4), 1, Infinity, ), key: "T", }, { minutes: helpers.bound( Math.round(props.quarterLength / 2), 1, Infinity, ), key: "S", }, ]; // Dedupe const skipMinutesValues = new Set(); skipMinutes = skipMinutes.filter(({ minutes }) => { if (skipMinutesValues.has(minutes)) { return false; } skipMinutesValues.add(minutes); return true; }); const menuItems = [ ...skipMinutes.map(({ minutes, key }) => ({ label: `${minutes} minute${minutes === 1 ? "" : "s"}`, key, onClick: () => { playSeconds(60 * minutes); }, })), { label: `End of ${ boxScore.current.elamTarget !== undefined ? "game" : boxScore.current.overtime ? "period" : getPeriodName(boxScore.current.numPeriods) }`, key: "Q", onClick: () => { playSeconds(Infinity); }, }, ]; if (!boxScore.current.elam) { menuItems.push({ label: "Until last 2 minutes", key: "U", onClick: () => { playUntilLastTwoMinutes(); }, }); } if ( bySport({ basketball: false, football: true, hockey: false, }) ) { menuItems.push({ label: "Until change of possession", key: "C", onClick: () => { playUntilChangeOfPossession(); }, }); } if ( bySport({ basketball: false, football: true, hockey: true, }) ) { menuItems.push({ label: `Until next ${bySport({ hockey: "goal", default: "score", })}`, key: "G", onClick: () => { playUntilNextScore(); }, }); } if (boxScore.current.elam && boxScore.current.elamTarget === undefined) { menuItems.push({ label: "Until Elam Ending", key: "U", onClick: () => { playUntilElamEnding(); }, }); } return menuItems; // eslint-disable-next-line react-hooks/exhaustive-deps }, [ boxScore.current.elam, boxScore.current.elamTarget, boxScore.current.overtime, processToNextPause, ]); // Needs to return actual div, not fragment, for AutoAffix!!! return ( <div> {confetti.display ? <Confetti colors={confetti.colors} /> : null} <p className="text-danger"> If you navigate away from this page, you won't be able to see these play-by-play results again because they are not stored anywhere. The results of this game are already final, though. </p> <div className="row"> <div className="col-md-9"> {boxScore.current.gid >= 0 ? ( <BoxScoreWrapper boxScore={boxScore.current} Row={PlayerRow} playIndex={playIndex} /> ) : ( <h2>Loading...</h2> )} </div> <div className="col-md-3"> <div className="live-game-affix"> {boxScore.current.gid >= 0 ? ( <div className="d-flex align-items-center mb-3"> <PlayPauseNext className="me-2" disabled={boxScore.current.gameOver} fastForwardAlignRight fastForwards={fastForwardMenuItems} onPlay={handlePlay} onPause={handlePause} onNext={handleNextPlay} paused={paused} titlePlay="Resume Simulation" titlePause="Pause Simulation" titleNext="Show Next Play" /> <div className="mb-3 flex-grow-1 mb-0"> <input type="range" className="form-range" disabled={boxScore.current.gameOver} min="1" max="33" step="1" value={speed} onChange={handleSpeedChange} title="Speed" /> </div> </div> ) : null} <div className="live-game-playbyplay" ref={c => { playByPlayDiv.current = c; }} /> </div> </div> </div> </div> ); }; const LiveGameWrapper = (props: View<"liveGame">) => { useTitleBar({ title: "Live Game Simulation", hideNewWindow: true }); return <LiveGame {...props} />; }; export default LiveGameWrapper;
the_stack
import { JSONPath } from 'jsonpath-plus'; import * as TezosRPCTypes from '../../types/tezos/TezosRPCResponseTypes' import { TezosRequestError } from '../../types/tezos/TezosErrorTypes'; import { TezosConstants } from '../../types/tezos/TezosConstants'; import FetchSelector from '../../utils/FetchSelector' import LogSelector from '../../utils/LoggerSelector'; const log = LogSelector.log; const fetch = FetchSelector.fetch; /** * Utility functions for interacting with a Tezos node. */ export namespace TezosNodeReader { /** * Send a GET request to a Tezos node. * * @param {string} server Tezos node to query * @param {string} command RPC route to invoke * @returns {Promise<object>} JSON-encoded response */ function performGetRequest(server: string, command: string): Promise<object> { const url = `${server}/${command}`; return fetch(url, { method: 'get' }) .then(response => { if (!response.ok) { log.error(`TezosNodeReader.performGetRequest error: ${response.status} for ${command} on ${server}`); throw new TezosRequestError(response.status, response.statusText, url, null); } return response; }) .then(response => { const json: any = response.json(); log.debug(`TezosNodeReader.performGetRequest response: ${json} for ${command} on ${server}`); return json; }); } /** * Gets the delegate for a smart contract or an implicit account. * * @param {string} server Tezos node to query * @param {string} accountHash The smart contract address or implicit account to query. * @returns The address of the delegate, or undefined if there was no delegate set. */ export async function getDelegate(server: string, accountHash: string): Promise<string | undefined> { const contractData = await getAccountForBlock(server, 'head', accountHash) return contractData.delegate; } /** * Gets a block for a given hash. * * @param {string} server Tezos node to query * @param {string} hash Hash of the given block, defaults to 'head' * @param {string} chainid Chain id, expected to be 'main' or 'test', defaults to main * @returns {Promise<TezosRPCTypes.TezosBlock>} Block */ export function getBlock(server: string, hash: string = 'head', chainid: string = 'main'): Promise<TezosRPCTypes.TezosBlock> { return performGetRequest(server, `chains/${chainid}/blocks/${hash}`).then(json => { return <TezosRPCTypes.TezosBlock>json }); } /** * Gets the top block. * * @param {string} server Tezos node to query * @returns {Promise<TezosRPCTypes.TezosBlock>} Block head */ export function getBlockHead(server: string): Promise<TezosRPCTypes.TezosBlock> { return getBlock(server); } /** * Returns a block at a given offset below head. * * @param {string} server Tezos node to query * @param {number} offset Number of blocks below head, must be positive, 0 = head * @param {string} chainid Chain id, expected to be 'main' or 'test', defaults to main */ export async function getBlockAtOffset(server: string, offset: number, chainid: string = 'main'): Promise<TezosRPCTypes.TezosBlock> { if (offset <= 0) { return getBlock(server); } const head = await getBlock(server); return performGetRequest(server, `chains/${chainid}/blocks/${Number(head['header']['level']) - offset}`).then(json => { return <TezosRPCTypes.TezosBlock>json }); } /** * Fetches a specific account for a given block. * * @param {string} server Tezos node to query * @param {string} blockHash Hash of given block * @param {string} accountHash Account address * @param {string} chainid Chain id, expected to be 'main' or 'test', defaults to main * @returns {Promise<Account>} The account */ export function getAccountForBlock(server: string, blockHash: string, accountHash: string, chainid: string = 'main'): Promise<TezosRPCTypes.Contract> { return performGetRequest(server, `chains/${chainid}/blocks/${blockHash}/context/contracts/${accountHash}`) .then(json => <TezosRPCTypes.Contract>json); } /** * Fetches the current counter for an account. * * @param {string} server Tezos node to query * @param {string} accountHash Account address * @param {string} chainid Chain id, expected to be 'main' or 'test', defaults to main * @returns {Promise<number>} Current account counter */ export async function getCounterForAccount(server: string, accountHash: string, chainid: string = 'main'): Promise<number> { const counter = await performGetRequest(server, `chains/${chainid}/blocks/head/context/contracts/${accountHash}/counter`) .then(r => r.toString()); return parseInt(counter.toString(), 10); } /** * Returns account balance as of the Head. Will return current balance or 0 if the account is marked as `spendable: false`. * Use `getAccountForBlock()` to get balance as of a specific block. Balance value is in utez. * * @param {string} server Tezos node to query * @param {string} accountHash Account address * @param chainid Chain id, expected to be 'main' or 'test', defaults to main */ export async function getSpendableBalanceForAccount(server: string, accountHash: string, chainid: string = 'main'): Promise<number> { const account = await performGetRequest(server, `chains/${chainid}/blocks/head/context/contracts/${accountHash}`) // TODO: get /balance .then(json => <TezosRPCTypes.Contract>json); return parseInt(account.balance.toString(), 10); } /** * Fetches the manager public key of a specific account for a given block. * * @param {string} server Tezos node to query * @param {string} block Hash of given block, will also accept block level and 'head' * @param {string} accountHash Account address * @param {string} chainid Chain id, expected to be 'main' or 'test', defaults to main. * @returns {Promise<string>} Manager public key */ export async function getAccountManagerForBlock(server: string, block: string, accountHash: string, chainid: string = 'main'): Promise<string> { const key = await performGetRequest(server, `chains/${chainid}/blocks/${block}/context/contracts/${accountHash}/manager_key`); return key ? key.toString() : ''; } /** * Indicates whether an account is implicit and empty. If true, transaction will burn 0.06425tz. * * @param {string} server Tezos node to connect to * @param {string} accountHash Account address * @returns {Promise<boolean>} Result */ export async function isImplicitAndEmpty(server: string, accountHash: string): Promise<boolean> { const account = await getAccountForBlock(server, 'head', accountHash); const isImplicit = accountHash.toLowerCase().startsWith('tz'); const isEmpty = Number(account.balance) === 0; return (isImplicit && isEmpty); } /** * Indicates whether a reveal operation has already been done for a given account. * * @param {string} server Tezos node to connect to * @param {string} accountHash Account address to delegate from * @returns {Promise<boolean>} Result */ export async function isManagerKeyRevealedForAccount(server: string, accountHash: string): Promise<boolean> { const managerKey = await getAccountManagerForBlock(server, 'head', accountHash); return managerKey.length > 0; } export function getContractStorage(server: string, accountHash: string, block: string = 'head', chainid: string = 'main'): Promise<any> { return performGetRequest(server, `chains/${chainid}/blocks/${block}/context/contracts/${accountHash}/storage`); } /** * Queries the node for a key of a big_map * * @param {string} server Tezos node to connect to * @param index big_map index to query * @param key encoded big_map key to get, see `TezosMessageUtils.encodeBigMapKey`, `TezosMessageUtils.writePackedData` * @param {string} block Block reference, level or hash, 'head' is default * @param {string} chainid Chain id, expected to be 'main' or 'test', defaults to main. */ export function getValueForBigMapKey(server: string, index: number, key: string, block: string = 'head', chainid: string = 'main'): Promise<any> { return performGetRequest(server, `chains/${chainid}/blocks/${block}/context/big_maps/${index}/${key}`); } /** * Queries the /mempool/pending_operations RPC and parses it looking for the provided operation group id. * * @param {string} server Tezos node to connect to * @param {string} operationGroupId * @param {string} chainid Chain id, expected to be 'main' or 'test', defaults to main. */ export async function getMempoolOperation(server: string, operationGroupId: string, chainid: string = 'main') { const mempoolContent: any = await performGetRequest(server, `chains/${chainid}/mempool/pending_operations`).catch(() => undefined); const jsonresult = JSONPath({ path: `$.applied[?(@.hash=='${operationGroupId}')]`, json: mempoolContent }); return jsonresult[0]; } /** * This method is meant to be used with the output of `getMempoolOperationsForAccount()` to estimate TTL of pending transactions. * * @param {string} server Tezos node to connect to. * @param {string} branch Branch field of the operation in question. * @param {string} chainid Chain id, expected to be 'main' or 'test', defaults to main. * @returns {Promise<number>} Number of blocks until the operation expires. */ export async function estimateBranchTimeout(server: string, branch: string, chainid: string = 'main'): Promise<number> { const refBlock = getBlock(server, branch, chainid); const headBlock = getBlock(server, 'head', chainid); var result = await Promise.all([refBlock, headBlock]).then(blocks => Number(blocks[1]['header']['level']) - Number(blocks[0]['header']['level'])); return TezosConstants.MaxBranchOffset - result; } /** * Queries the /mempool/pending_operations RPC and parses it looking for applied operations submitted by the provided account * * @param {string} server Tezos node to connect to. * @param accountHash * @param {string} chainid Chain id, expected to be 'main' or 'test', defaults to main. */ export async function getMempoolOperationsForAccount(server: string, accountHash: string, chainid: string = 'main') { const mempoolContent: any = await performGetRequest(server, `chains/${chainid}/mempool/pending_operations`).catch(() => undefined); const a = mempoolContent.applied.filter(g => g.contents.some(s => (s.source === accountHash || s.destination === accountHash))); const o = a.map(g => { g.contents = g.contents.filter(s => (s.source === accountHash || s.destination === accountHash)); return g; }); return o; } /** * Returns the current chain_id hash, for example, "NetXm8tYqnMWky1". This is not to be confused with the other chain id which is either "test" or "main". * * @param {string} server Tezos node to connect to. * @param {string} chainid Chain id, expected to be 'main' or 'test', defaults to main. */ export async function getChainId(server: string, chainid: string = 'main'): Promise<string> { return performGetRequest(server, `chains/${chainid}/chain_id`).then(r => r.toString()); } }
the_stack
describe('Selects', () => { before(() => { cy.visit('/selects'); cy.injectAxe(); cy.get('.page-loader').should('not.exist', { timeout: 20000 }); }); const shouldBeNotFocused = () => cy.get('.ngx-select-input-underline .underline-fill').should('have.css', 'width', '0px'); const shouldBeFocused = () => cy.get('.ngx-select-input-underline .underline-fill').should('not.have.css', 'width', '0px'); const shouldBeNotActive = () => cy.root().should('not.have.class', 'active'); const shouldBeActive = () => cy.root().should('have.class', 'active'); it('have no detectable a11y violations on load', () => { cy.get('ngx-select-input').withinEach($el => { cy.checkA11y($el, { rules: { 'color-contrast': { enabled: false }, // NOTE: to be evaluated by UIUX label: { enabled: false } // TODO: fix these } } as any); }); }); describe('Basic Input', () => { beforeEach(() => { cy.get('ngx-section').first().as('SUT'); cy.get('@SUT').find('ngx-select').first().as('CUT'); cy.get('@CUT').ngxClose(); cy.get('@CUT').clear(); }); it('has a label', () => { cy.get('@CUT').ngxFindLabel().should('contain.text', 'Attack Type'); }); it('selects and clears value', () => { cy.get('@CUT').ngxGetValue().should('equal', ''); const text = 'DDOS'; cy.get('@CUT').select(text).ngxGetValue().should('equal', text); cy.get('@CUT').clear().ngxGetValue().should('equal', ''); }); it('deselects on click', () => { cy.get('@CUT').ngxGetValue().should('equal', ''); const text = 'DDOS'; cy.get('@CUT').select(text).ngxGetValue().should('equal', text); cy.get('@CUT').ngxOpen(); cy.get('@CUT').find('.ngx-select-dropdown-option').contains(text).click(); cy.get('@CUT').ngxGetValue().should('equal', ''); }); it('selects and clears value twice', () => { cy.get('@CUT').ngxGetValue().should('equal', ''); const text = 'DDOS'; cy.get('@CUT').select(text).ngxGetValue().should('equal', text); cy.get('@CUT').clear().ngxGetValue().should('equal', ''); cy.get('@CUT').select(text).ngxGetValue().should('equal', text); cy.get('@CUT').clear().ngxGetValue().should('equal', ''); }); it('is keyboard accessible', () => { cy.get('@SUT').find('h4').contains('Basic').click(); cy.get('@CUT').within(() => { // Starts out not focused not open shouldBeNotFocused(); shouldBeNotActive(); // Tab into the select, now focused but still closed cy.realPress('Tab'); shouldBeFocused(); shouldBeNotActive(); // Down arrow to open and select first item cy.realPress('ArrowDown'); shouldBeFocused(); shouldBeActive(); cy.get('.ngx-select-dropdown-options li li').within(() => { cy.root().first().should('have.class', 'active'); // active cy.root().last().should('not.have.class', 'active'); // not active cy.realPress('ArrowDown').realPress('ArrowDown'); cy.root().first().should('not.have.class', 'active'); // not active cy.root().last().should('have.class', 'active'); // active }); // Escape to close list cy.realPress('Escape'); shouldBeFocused(); shouldBeNotActive(); // Arrow up to open and select last item cy.realPress('ArrowUp'); shouldBeFocused(); shouldBeActive(); // eslint-disable-next-line cypress/no-unnecessary-waiting cy.wait(10); // Needed for testing!!! cy.get('.ngx-select-dropdown-options li li').within(() => { cy.root().first().should('not.have.class', 'active'); // not active cy.root().last().should('have.class', 'active'); // active cy.realPress('ArrowUp'); // eslint-disable-next-line cypress/no-unnecessary-waiting cy.wait(10); // Needed for testing!!! cy.realPress('ArrowUp'); cy.root().first().should('have.class', 'active'); // active cy.root().last().should('not.have.class', 'active'); // not active }); // Enter selects an option and closes the list cy.realPress('Enter'); shouldBeFocused(); shouldBeNotActive(); cy.root().ngxGetValue().should('equal', 'Breach'); // Space opens cy.realPress('Space'); shouldBeFocused(); shouldBeActive(); // Space selects an option but leaves list open cy.realPress('ArrowDown'); cy.realPress('Space'); cy.root().ngxGetValue().should('equal', 'DDOS'); shouldBeFocused(); shouldBeActive(); // Can deselect cy.realPress('Space'); cy.root().ngxGetValue().should('equal', ''); shouldBeFocused(); shouldBeActive(); // Tab away cy.root().ngxClose(); cy.realPress('Tab'); shouldBeNotFocused(); shouldBeNotActive(); }); }); }); describe('Tagging', () => { beforeEach(() => { cy.get('ngx-section[data-cy=tagging]').as('SUT'); cy.get('@SUT').find('ngx-select').first().as('CUT'); cy.get('@CUT').ngxClose(); }); it('has a label', () => { cy.get('@CUT').ngxFindLabel().should('contain.text', 'Tagging'); }); it('selects and clears existing values', () => { cy.get('@CUT').ngxGetValue().should('equal', ''); const text = 'DDOS'; cy.get('@CUT').select(text).ngxGetValue().should('equal', text); // TODO(ngx-ui-testing): tagging should return an array of values cy.get('@CUT').clear().ngxGetValue().should('equal', ''); }); it('can add and clear a new value', () => { cy.get('@CUT').ngxGetValue().should('equal', ''); const text = 'Other'; // TODO(ngx-ui-testing): support ngxFill for tagging cy.get('@CUT').find('input').click().type(text).type('{enter}'); cy.get('@CUT').ngxGetValue().should('equal', text); cy.get('@CUT').clear().ngxGetValue().should('equal', ''); }); it('can add and clear multiple values', () => { cy.get('@CUT').ngxGetValue().should('equal', ''); cy.get('@CUT').select('DDOS').ngxGetValue().should('equal', 'DDOS'); cy.get('@CUT').find('input').click().type('Other').type('{enter}'); cy.get('@CUT').ngxGetValue().should('contain', 'DDOS').should('contain', 'Other'); cy.get('@CUT').find('.ngx-select-clear').first().click(); cy.get('@CUT').find('.ngx-select-clear').first().click(); }); it('is keyboard accessible', () => { cy.get('@SUT').find('h4').contains('Basic').click(); cy.get('@CUT').within(() => { // Starts out not focused not open shouldBeNotFocused(); shouldBeNotActive(); // Tab into the select, now focused and open cy.realPress('Tab'); shouldBeFocused(); shouldBeActive(); // eslint-disable-next-line cypress/no-unnecessary-waiting cy.wait(100); // Wait for element to refocus cy.focused().type('Other{enter}'); // Input should be focused cy.root().ngxGetValue().should('contain', 'Other'); // eslint-disable-next-line cypress/no-unnecessary-waiting cy.wait(100); // Wait for element to refocus // Down arrow to select second item, closes list, stays active cy.realPress('ArrowDown'); // eslint-disable-next-line cypress/no-unnecessary-waiting cy.wait(100); // Needed for testing!!! cy.realPress('Enter'); // eslint-disable-next-line cypress/no-unnecessary-waiting cy.wait(120); // Wait for element to refocus on input shouldBeFocused(); shouldBeActive(); cy.root().ngxGetValue().should('contain', 'Other').should('contain', 'DDOS'); // Clears with backspace cy.focused().type('{backspace}{backspace}{backspace}'); // For some reason needs three backspaces in testing }); }); }); describe('Input with AbstractControl', () => { beforeEach(() => { cy.getByName('formCtrl1').as('CUT'); cy.get('[data-cy=reactiveFormSelectToggleBtn]').as('reactiveFormSelectToggleBtn'); }); it('should be able to be disabled', () => { cy.get('@CUT').should('not.have.class', 'disabled'); cy.get('@reactiveFormSelectToggleBtn').click(); cy.get('@CUT').should('have.class', 'disabled'); }); it('should be able to get re-enabled', () => { cy.get('@reactiveFormSelectToggleBtn').click(); cy.get('@CUT').should('not.have.class', 'disabled'); }); }); describe('Input with AbstractControl disabled by default', () => { beforeEach(() => { cy.getByName('formCtrl2').as('CUT'); }); it('should be able to be disabled', () => { cy.get('@CUT').should('have.class', 'disabled'); }); }); describe('Filtering Input', () => { beforeEach(() => { cy.getByName('filtering').as('CUT'); }); it('has a label', () => { cy.get('@CUT').ngxFindLabel().should('contain.text', 'Attack Type'); }); it('selects and clears value', () => { const text = 'DDOS'; cy.get('@CUT').ngxFill(text).select(text).ngxGetValue().should('equal', text); cy.get('@CUT').clear().ngxGetValue().should('equal', ''); }); }); describe('Templates', () => { beforeEach(() => { cy.get('[data-cy=templates]').as('CUT'); }); it('selects and clears value', () => { cy.get('@CUT').ngxGetValue().should('equal', ''); const text = 'breach'; cy.get('@CUT').select(text).ngxGetValue().should('equal', text); cy.get('@CUT').clear().ngxGetValue().should('equal', ''); }); }); describe('Multiple Select', () => { beforeEach(() => { cy.get('section header h1').contains('Multi Select').closest('ngx-section').as('SUT'); cy.get('@SUT').find('ngx-select').first().as('CUT'); }); it('selects and clears value', () => { cy.get('@CUT').ngxGetValue().should('deep.equal', []); cy.get('@CUT').select('DDOS').ngxGetValue().should('deep.equal', ['DDOS']); cy.get('@CUT').select(['DDOS', 'Physical']).ngxGetValue().should('deep.equal', ['DDOS', 'Physical']); cy.get('@CUT').clear().ngxGetValue().should('deep.equal', []); }); it('is keyboard accessible', () => { cy.get('@SUT').find('h4').contains('Basic').click(); cy.get('@CUT').within(() => { // Starts out not focused not open shouldBeNotFocused(); shouldBeNotActive(); // Tab into the select, now focused but still closed cy.realPress('Tab'); shouldBeFocused(); shouldBeNotActive(); // Down arrow to open and select first item cy.realPress('ArrowDown'); shouldBeFocused(); shouldBeActive(); cy.get('.ngx-select-dropdown-options li li').within(() => { cy.root().first().should('have.class', 'active'); // active cy.root().last().should('not.have.class', 'active'); // not active cy.realPress('ArrowDown').realPress('ArrowDown'); cy.root().first().should('not.have.class', 'active'); // not active cy.root().last().should('have.class', 'active'); // active }); // Escape to close list cy.realPress('Escape'); shouldBeFocused(); shouldBeNotActive(); // Arrow up to open and select last item cy.realPress('ArrowUp'); shouldBeFocused(); shouldBeActive(); // eslint-disable-next-line cypress/no-unnecessary-waiting cy.wait(10); // Needed for testing!!! cy.get('.ngx-select-dropdown-options li li').within(() => { cy.root().first().should('not.have.class', 'active'); // not active cy.root().last().should('have.class', 'active'); // active cy.realPress('ArrowUp'); // eslint-disable-next-line cypress/no-unnecessary-waiting cy.wait(10); // Needed for testing!!! cy.realPress('ArrowUp'); cy.root().first().should('have.class', 'active'); // active cy.root().last().should('not.have.class', 'active'); // not active }); // Enter selects an option and leaves list open cy.realPress('Enter'); shouldBeFocused(); shouldBeActive(); cy.root().ngxGetValue().should('deep.equal', ['Breach']); // Space selects an option but leaves list open cy.realPress('ArrowDown'); cy.realPress('Space'); cy.root().ngxGetValue().should('deep.equal', ['Breach', 'DDOS']); shouldBeFocused(); shouldBeActive(); // Can deselect an option cy.realPress('ArrowUp'); cy.realPress('Space'); cy.root().ngxGetValue().should('deep.equal', ['DDOS']); shouldBeFocused(); shouldBeActive(); cy.root().ngxClose(); cy.realPress('Tab'); shouldBeNotFocused(); shouldBeNotActive(); }); }); }); describe('Native Select', () => { beforeEach(() => { cy.get('[sectiontitle="Native"] select').first().as('CUT'); }); it('selects value', () => { cy.get('@CUT').ngxGetValue().should('equal', 'Red'); cy.get('@CUT').select('Green').ngxGetValue().should('equal', 'Green'); }); }); describe('Native MultiSelect', () => { beforeEach(() => { cy.get('[sectiontitle="Native"] select').eq(1).as('CUT'); }); it('selects value', () => { cy.get('@CUT').ngxGetValue().should('deep.equal', []); cy.get('@CUT').select('Green').ngxGetValue().should('deep.equal', ['Green']); cy.get('@CUT').select(['Green', 'Red']).ngxGetValue().should('deep.equal', ['Red', 'Green']); }); }); describe('Async', () => { beforeEach(() => { cy.get('[sectiontitle="Async"] ngx-select').first().as('CUT').scrollIntoView(); cy.intercept(`https://jsonplaceholder.typicode.com/posts?q=*`, { delay: 600, body: [ { userId: 1, id: 4, title: 'eum et est occaecati', body: 'ullam et saepe reiciendis voluptatem adipisci\nsit amet autem assumenda provident rerum culpa\nquis hic commodi nesciunt rem tenetur doloremque ipsam iure\nquis sunt voluptatem rerum illo velit' }, { userId: 1, id: 6, title: 'dolorem eum magni eos aperiam quia', body: 'ut aspernatur corporis harum nihil quis provident sequi\nmollitia nobis aliquid molestiae\nperspiciatis et ea nemo ab reprehenderit accusantium quas\nvoluptate dolores velit et doloremque molestiae' }, { userId: 1, id: 8, title: 'dolorem dolore est ipsam', body: 'dignissimos aperiam dolorem qui eum\nfacilis quibusdam animi sint suscipit qui sint possimus cum\nquaerat magni maiores excepturi\nipsam ut commodi dolor voluptatum modi aut vitae' } ] }).as('api'); }); it('selects value', () => { cy.get('@CUT').ngxGetValue().should('deep.equal', ''); cy.get('@CUT').ngxOpen(); cy.get('@CUT').find('input').ngxFill('dolorem'); cy.wait('@api'); cy.get('@CUT').find('li.ngx-select-dropdown-option').should('have.length', 2); cy.get('@CUT').select('dolorem eum magni eos aperiam quia'); cy.get('@CUT').ngxGetValue().should('deep.equal', 'dolorem eum magni eos aperiam quia'); }); }); describe('Close on body click', () => { beforeEach(() => { cy.asAllDataCy(); }); it('should close on input click', () => { cy.get('@attackType').within(() => { cy.get('.ngx-select-dropdown-options').should('not.exist'); cy.get('.ngx-select-input-box').click(); cy.get('.ngx-select-dropdown-options').first().scrollIntoView(); cy.get('.ngx-select-dropdown-options').should('be.visible'); }); cy.get('@attackTypeRequired').within(() => { cy.get('.ngx-select-dropdown-options').should('not.exist'); cy.get('.ngx-select-input-box').click(); cy.get('.ngx-select-dropdown-options').first().scrollIntoView(); cy.get('.ngx-select-dropdown-options').should('be.visible'); }); // the current opened select should be closed cy.get('@attackType').find('.ngx-select-dropdown-options').should('not.exist'); }); it('should close on caret down click', () => { cy.get('@attackType').within(() => { cy.get('.ngx-select-dropdown-options').should('not.exist'); cy.get('.ngx-select-caret').click(); cy.get('.ngx-select-dropdown-options').first().scrollIntoView(); cy.get('.ngx-select-dropdown-options').should('be.visible'); }); cy.get('@attackTypeRequired').within(() => { cy.get('.ngx-select-dropdown-options').should('not.exist'); cy.get('.ngx-select-caret').click(); cy.get('.ngx-select-dropdown-options').first().scrollIntoView(); cy.get('.ngx-select-dropdown-options').should('be.visible'); }); // the current opened select should be closed cy.get('@attackType').find('.ngx-select-dropdown-options').should('not.exist'); }); }); });
the_stack
import * as fs from 'fs'; import * as path from 'path'; import * as hasOwnProp from 'has-own-prop'; import * as nopt from 'nopt'; import { WritableStream } from 'readable-stream'; import { Timezone, parseInterval, isDate } from 'chronoshift'; import { $, Expression, Datum, Dataset, PlywoodValue, TimeRange, External, DruidExternal, AttributeJSs, SQLParse, version, Set } from 'plywood'; import { properDruidRequesterFactory } from './requester'; import { executeSQLParseStream } from './plyql-executor'; import { getOutputTransform } from './output-transform'; import { getVariablesDataset } from './variables'; import { getStatusDataset } from './status'; import { addExternal, getTablesDataset, getColumnsDataset, getSchemataDataset } from './schema'; import { getCharacterSetsDataset, getCollationsDataset, getKeyColumnUsageDataset, getIndexDataset, getWarningsDataset } from "./datasets"; function loadOrParseJSON(json: string): any { if (typeof json === 'undefined') return null; if (typeof json !== 'string') throw new TypeError(`load or parse must get a string`); if (json[0] === '@') { try { json = fs.readFileSync(json.substr(1), 'utf-8'); } catch (e) { throw new Error(`can not load: ${json}`); } } try { return JSON.parse(json); } catch (e) { throw new Error(`can not parse: ${json}`); } } function printUsage() { console.log(` Usage: plyql [options] Examples: plyql -h 10.20.30.40 -q 'SHOW TABLES' plyql -h 10.20.30.40 -q 'DESCRIBE twitterstream' plyql -h 10.20.30.40 -q 'SELECT MAX(__time) AS maxTime FROM twitterstream' plyql -h 10.20.30.40 -s twitterstream -i P5D -q \\ 'SELECT SUM(tweet_length) as TotalTweetLength WHERE first_hashtag = "#imply"' Arguments: --help print this help message --version display the version number -v, --verbose display the queries that are being made -h, --host the host to connect to -s, --source use this source for the query (supersedes FROM clause) -i, --interval add (AND) a __time filter between NOW-INTERVAL and NOW -Z, --timezone the default timezone -o, --output the output format. Possible values: table (default), json, csv, tsv, flat, plywood, plywood-stream -t, --timeout the time before a query is timed out in ms (default: 180000) -r, --retry the number of tries a query should be attempted on error, 0 = unlimited, (default: 2) -c, --concurrent the limit of concurrent queries that could be made simultaneously, 0 = unlimited, (default: 2) --rollup use rollup mode [COUNT() -> SUM(count)] -q, --query the query to run --json-server the port on which to start the json server --experimental-mysql-gateway [Experimental] the port on which to start the MySQL gateway server --druid-version Assume this is the Druid version and do not query it --custom-aggregations A JSON string defining custom aggregations --custom-transforms A JSON string defining custom transforms --druid-context A JSON string representing the Druid context to use --skip-cache disable Druid caching --group-by-v2 Set groupByStrategy to 'v2' in the context to ensure use of the V2 GroupBy engine --introspection-strategy Druid introspection strategy Possible values: * segment-metadata-fallback - (default) use the segmentMetadata and fallback to GET route * segment-metadata-only - only use the segmentMetadata query * datasource-get - only use GET /druid/v2/datasources/DATASOURCE route --socks-host use this socks host to facilitate a Druid connection --socks-username the username for the socks proxy --socks-password the password for the socks proxy --force-time force a column to be interpreted as a time column --force-string force a column to be interpreted as a string column --force-boolean force a column to be interpreted as a boolean --force-number force a column to be interpreted as a number --force-unique force a column to be interpreted as a hyperLogLog uniques --force-theta force a column to be interpreted as a theta sketch --force-histogram force a column to be interpreted as an approximate histogram ` ) } function printVersion(): void { let cliPackageFilename = path.join(__dirname, '..', 'package.json'); let cliPackage: any; try { cliPackage = JSON.parse(fs.readFileSync(cliPackageFilename, 'utf8')); } catch (e) { console.log("could not read cli package", e.message); return; } console.log(`plyql version ${cliPackage.version} (plywood version ${version})`); } export interface CommandLineArguments { "host"?: string; "druid"?: string; "source"?: string; "data-source"?: string; "help"?: boolean; "query"?: string; "json-server"?: number; "experimental-mysql-gateway"?: number; "interval"?: string; "timezone"?: string; "version"?: boolean; "verbose"?: boolean; "timeout"?: number; "retry"?: number; "concurrent"?: number; "output"?: string; "force-time"?: string[]; "force-string"?: string[]; "force-boolean"?: string[]; "force-number"?: string[]; "force-unique"?: string[]; "force-theta"?: string[]; "force-histogram"?: string[]; "druid-version"?: string; "custom-aggregations"?: string; "custom-transforms"?: string; "druid-context"?: string; "druid-time-attribute"?: string; "rollup"?: boolean; "skip-cache"?: boolean; "group-by-v2"?: boolean; "introspection-strategy"?: string; "socks-host"?: string; "socks-user"?: string; "socks-username"?: string; "socks-password"?: string; argv?: any; } type Mode = 'query' | 'server' | 'gateway'; export function parseArguments(): CommandLineArguments { return <any>nopt( { "host": String, "druid": String, "source": String, "data-source": String, "help": Boolean, "query": String, "json-server": Number, "experimental-mysql-gateway": Number, "interval": String, "timezone": String, "version": Boolean, "verbose": Boolean, "timeout": Number, "retry": Number, "concurrent": Number, "output": String, "force-time": [String, Array], "force-string": [String, Array], "force-boolean": [String, Array], "force-number": [String, Array], "force-unique": [String, Array], "force-theta": [String, Array], "force-histogram": [String, Array], "druid-version": String, "custom-aggregations": String, "custom-transforms": String, "druid-context": String, "druid-time-attribute": String, "rollup": Boolean, "skip-cache": Boolean, "group-by-v2": Boolean, "introspection-strategy": String, "socks-host": String, "socks-user": String, "socks-username": String, "socks-password": String }, { "v": ["--verbose"], "h": ["--host"], "s": ["--source"], "i": ["--interval"], "Z": ["--timezone"], "o": ["--output"], "t": ["--timeout"], "r": ["--retry"], "c": ["--concurrent"], "q": ["--query"] }, process.argv ); } export async function run(parsed: CommandLineArguments): Promise<void> { if (parsed.argv.original.length === 0 || parsed.help) { printUsage(); return null; } if (parsed['version']) { printVersion(); return null; } let verbose: boolean = parsed['verbose']; if (verbose) printVersion(); // Get forced attribute overrides let attributeOverrides: AttributeJSs = []; let forceTime: string[] = parsed['force-time'] || []; for (let attributeName of forceTime) { attributeOverrides.push({ name: attributeName, type: 'TIME' }); } let forceString: string[] = parsed['force-string'] || []; for (let attributeName of forceString) { attributeOverrides.push({ name: attributeName, type: 'STRING' }); } let forceBoolean: string[] = parsed['force-boolean'] || []; for (let attributeName of forceBoolean) { attributeOverrides.push({ name: attributeName, type: 'BOOLEAN' }); } let forceNumber: string[] = parsed['force-number'] || []; for (let attributeName of forceNumber) { attributeOverrides.push({ name: attributeName, type: 'NUMBER' }); } let forceUnique: string[] = parsed['force-unique'] || []; for (let attributeName of forceUnique) { attributeOverrides.push({ name: attributeName, nativeType: 'hyperUnique' }); } let forceTheta: string[] = parsed['force-theta'] || []; for (let attributeName of forceTheta) { attributeOverrides.push({ name: attributeName, nativeType: 'thetaSketch' }); } let forceHistogram: string[] = parsed['force-histogram'] || []; for (let attributeName of forceHistogram) { attributeOverrides.push({ name: attributeName, nativeType: 'approximateHistogram' }); } // Get output let output: string = (parsed['output'] || 'table').toLowerCase(); if (output !== 'table' && output !== 'json' && output !== 'csv' && output !== 'tsv' && output !== 'flat' && output !== 'plywood-stream') { throw new Error(`output must be one of table, json, csv, tsv, flat, plywood, or plywood-stream (is ${output})`); } // Get host let host: string = parsed['druid'] || parsed['host']; if (!host) { throw new Error("must have a host"); } // Get version let druidVersion: string = parsed['druid-version']; let timezone = Timezone.UTC; if (parsed['timezone']) { timezone = Timezone.fromJS(parsed['timezone']); } let timeout: number = hasOwnProp(parsed, 'timeout') ? parsed['timeout'] : 180000; let retry: number = hasOwnProp(parsed, 'retry') ? parsed['retry'] : 2; let concurrent: number = hasOwnProp(parsed, 'concurrent') ? parsed['concurrent'] : 2; let customAggregations: any = loadOrParseJSON(parsed['custom-aggregations']); let customTransforms: any = loadOrParseJSON(parsed['custom-transforms']); // Druid Context --------------------------- let druidContext: Druid.Context = loadOrParseJSON(parsed['druid-context']) || {}; druidContext.timeout = timeout; if (parsed['skip-cache']) { druidContext.useCache = false; druidContext.populateCache = false; } if (parsed['group-by-v2']) { druidContext['groupByStrategy'] = 'v2'; } let timeAttribute = parsed['druid-time-attribute'] || '__time'; let filter: Expression = null; let intervalString: string = parsed['interval']; if (intervalString) { let interval: TimeRange; try { let { computedStart, computedEnd } = parseInterval(intervalString, timezone); interval = TimeRange.fromJS({ start: computedStart, end: computedEnd }); } catch (e) { throw new Error(`Could not parse interval: ${intervalString}`); } filter = $(timeAttribute).overlap(interval); } let masterSource = parsed['source'] || parsed['data-source'] || null; // Get SQL if (Number(!!parsed['query']) + Number(!!parsed['json-server']) + Number(!!parsed['experimental-mysql-gateway']) > 1) { throw new Error("must set exactly one of --query (-q), --json-server, or --experimental-mysql-gateway"); } let mode: Mode; let sqlParse: SQLParse; let serverPort: number; if (parsed['query']) { mode = 'query'; let query: string = parsed['query']; if (verbose) { console.log('Received query:'); console.log(query); console.log('---------------------------'); } try { sqlParse = Expression.parseSQL(query, timezone); } catch (e) { throw new Error(`Could not parse query: ${e.message}`); } if (sqlParse.verb && sqlParse.verb !== 'SELECT') { // DESCRIBE + SHOW get re-written throw new Error(`Unsupported SQL verb ${sqlParse.verb} must be SELECT, DESCRIBE, SHOW, or a raw expression`); } if (verbose && sqlParse.expression) { console.log('Parsed query as the following plywood expression (as JSON):'); console.log(JSON.stringify(sqlParse.expression, null, 2)); console.log('---------------------------'); } } else if (parsed['json-server']) { mode = 'server'; serverPort = parsed['json-server']; } else if (parsed['experimental-mysql-gateway']) { mode = 'gateway'; serverPort = parsed['experimental-mysql-gateway']; } else { throw new Error("must set one of --query (-q), --json-server, or --experimental-mysql-gateway"); } let socksHost = parsed['socks-host']; let socksUsername: string; let socksPassword: string; if (socksHost) { socksUsername = parsed['socks-username'] || parsed['socks-user']; socksPassword = parsed['socks-password']; } // ============== End parse =============== let requester = properDruidRequesterFactory({ druidHost: host, retry, timeout, verbose, concurrentLimit: concurrent, socksHost, socksUsername, socksPassword }); // ============== Do introspect =============== if (!druidVersion) { druidVersion = await DruidExternal.getVersion(requester); } let onlyDataSource = masterSource || (sqlParse ? sqlParse.table : null); let sources: string[]; if (onlyDataSource) { sources = [onlyDataSource]; } else { sources = await DruidExternal.getSourceList(requester); } if (verbose && !onlyDataSource) { console.log(`Found sources [${sources.join(',')}]`); } let context: Datum = {}; if (mode === 'gateway') { let variablesDataset = getVariablesDataset(); context['GLOBAL_VARIABLES'] = variablesDataset; context['SESSION_VARIABLES'] = variablesDataset; let statusDataset = getStatusDataset(); context['GLOBAL_STATUS'] = statusDataset; context['SESSION_STATUS'] = statusDataset; context['CHARACTER_SETS'] = getCharacterSetsDataset(); context['COLLATIONS'] = getCollationsDataset(); context['KEY_COLUMN_USAGE'] = getKeyColumnUsageDataset(); context['INDEX'] = getIndexDataset(); context['WARNINGS'] = getWarningsDataset(); } const introspectedExternals = await Promise.all(sources.map(source => { return External.fromJS({ engine: 'druid', version: druidVersion, source, rollup: parsed['rollup'], timeAttribute, allowEternity: true, allowSelectQueries: true, introspectionStrategy: parsed['introspection-strategy'], context: druidContext, customAggregations, customTransforms, filter, attributeOverrides }, requester).introspect() })); introspectedExternals.forEach((introspectedExternal) => { let source = introspectedExternal.source as string; context[source] = introspectedExternal; addExternal(source, introspectedExternal, mode === 'gateway'); }); context['SCHEMATA'] = getSchemataDataset(); context['TABLES'] = getTablesDataset(); context['COLUMNS'] = getColumnsDataset(); if (mode === 'query' && masterSource && !sqlParse.table && !sqlParse.rewrite) { context['data'] = context[masterSource]; } if (verbose) console.log(`introspection complete`); // Do query switch (mode) { case 'query': let valueStream = executeSQLParseStream(sqlParse, context, timezone); valueStream.on('error', (e: Error) => { console.error(`Could not compute query due to error: ${e.message}`); }); valueStream .pipe(getOutputTransform(output, timezone)) .pipe(process.stdout); return null; case 'gateway': require('./plyql-mysql-gateway').plyqlMySQLGateway(serverPort, context, timezone, null); return null; case 'server': require('./plyql-json-server').plyqlJSONServer(serverPort, context, timezone, null); return null; default: throw new Error(`unsupported mode ${mode}`); } }
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as Models from "../models"; import * as Mappers from "../models/tagsOperationsMappers"; import * as Parameters from "../models/parameters"; import { ResourceManagementClientContext } from "../resourceManagementClientContext"; /** Class representing a TagsOperations. */ export class TagsOperations { private readonly client: ResourceManagementClientContext; /** * Create a TagsOperations. * @param {ResourceManagementClientContext} client Reference to the service client. */ constructor(client: ResourceManagementClientContext) { this.client = client; } /** * This operation allows deleting a value from the list of predefined values for an existing * predefined tag name. The value being deleted must not be in use as a tag value for the given tag * name for any resource. * @summary Deletes a predefined tag value for a predefined tag name. * @param tagName The name of the tag. * @param tagValue The value of the tag to delete. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteValue(tagName: string, tagValue: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>; /** * @param tagName The name of the tag. * @param tagValue The value of the tag to delete. * @param callback The callback */ deleteValue(tagName: string, tagValue: string, callback: msRest.ServiceCallback<void>): void; /** * @param tagName The name of the tag. * @param tagValue The value of the tag to delete. * @param options The optional parameters * @param callback The callback */ deleteValue(tagName: string, tagValue: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void; deleteValue(tagName: string, tagValue: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> { return this.client.sendOperationRequest( { tagName, tagValue, options }, deleteValueOperationSpec, callback); } /** * This operation allows adding a value to the list of predefined values for an existing predefined * tag name. A tag value can have a maximum of 256 characters. * @summary Creates a predefined value for a predefined tag name. * @param tagName The name of the tag. * @param tagValue The value of the tag to create. * @param [options] The optional parameters * @returns Promise<Models.TagsCreateOrUpdateValueResponse> */ createOrUpdateValue(tagName: string, tagValue: string, options?: msRest.RequestOptionsBase): Promise<Models.TagsCreateOrUpdateValueResponse>; /** * @param tagName The name of the tag. * @param tagValue The value of the tag to create. * @param callback The callback */ createOrUpdateValue(tagName: string, tagValue: string, callback: msRest.ServiceCallback<Models.TagValue>): void; /** * @param tagName The name of the tag. * @param tagValue The value of the tag to create. * @param options The optional parameters * @param callback The callback */ createOrUpdateValue(tagName: string, tagValue: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.TagValue>): void; createOrUpdateValue(tagName: string, tagValue: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.TagValue>, callback?: msRest.ServiceCallback<Models.TagValue>): Promise<Models.TagsCreateOrUpdateValueResponse> { return this.client.sendOperationRequest( { tagName, tagValue, options }, createOrUpdateValueOperationSpec, callback) as Promise<Models.TagsCreateOrUpdateValueResponse>; } /** * This operation allows adding a name to the list of predefined tag names for the given * subscription. A tag name can have a maximum of 512 characters and is case-insensitive. Tag names * cannot have the following prefixes which are reserved for Azure use: 'microsoft', 'azure', * 'windows'. * @summary Creates a predefined tag name. * @param tagName The name of the tag to create. * @param [options] The optional parameters * @returns Promise<Models.TagsCreateOrUpdateResponse> */ createOrUpdate(tagName: string, options?: msRest.RequestOptionsBase): Promise<Models.TagsCreateOrUpdateResponse>; /** * @param tagName The name of the tag to create. * @param callback The callback */ createOrUpdate(tagName: string, callback: msRest.ServiceCallback<Models.TagDetails>): void; /** * @param tagName The name of the tag to create. * @param options The optional parameters * @param callback The callback */ createOrUpdate(tagName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.TagDetails>): void; createOrUpdate(tagName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.TagDetails>, callback?: msRest.ServiceCallback<Models.TagDetails>): Promise<Models.TagsCreateOrUpdateResponse> { return this.client.sendOperationRequest( { tagName, options }, createOrUpdateOperationSpec, callback) as Promise<Models.TagsCreateOrUpdateResponse>; } /** * This operation allows deleting a name from the list of predefined tag names for the given * subscription. The name being deleted must not be in use as a tag name for any resource. All * predefined values for the given name must have already been deleted. * @summary Deletes a predefined tag name. * @param tagName The name of the tag. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod(tagName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>; /** * @param tagName The name of the tag. * @param callback The callback */ deleteMethod(tagName: string, callback: msRest.ServiceCallback<void>): void; /** * @param tagName The name of the tag. * @param options The optional parameters * @param callback The callback */ deleteMethod(tagName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void; deleteMethod(tagName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> { return this.client.sendOperationRequest( { tagName, options }, deleteMethodOperationSpec, callback); } /** * This operation performs a union of predefined tags, resource tags, resource group tags and * subscription tags, and returns a summary of usage for each tag name and value under the given * subscription. In case of a large number of tags, this operation may return a previously cached * result. * @summary Gets a summary of tag usage under the subscription. * @param [options] The optional parameters * @returns Promise<Models.TagsListResponse> */ list(options?: msRest.RequestOptionsBase): Promise<Models.TagsListResponse>; /** * @param callback The callback */ list(callback: msRest.ServiceCallback<Models.TagsListResult>): void; /** * @param options The optional parameters * @param callback The callback */ list(options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.TagsListResult>): void; list(options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.TagsListResult>, callback?: msRest.ServiceCallback<Models.TagsListResult>): Promise<Models.TagsListResponse> { return this.client.sendOperationRequest( { options }, listOperationSpec, callback) as Promise<Models.TagsListResponse>; } /** * This operation allows adding or replacing the entire set of tags on the specified resource or * subscription. The specified entity can have a maximum of 50 tags. * @summary Creates or updates the entire set of tags on a resource or subscription. * @param scope The resource scope. * @param parameters * @param [options] The optional parameters * @returns Promise<Models.TagsCreateOrUpdateAtScopeResponse> */ createOrUpdateAtScope(scope: string, parameters: Models.TagsResource, options?: msRest.RequestOptionsBase): Promise<Models.TagsCreateOrUpdateAtScopeResponse>; /** * @param scope The resource scope. * @param parameters * @param callback The callback */ createOrUpdateAtScope(scope: string, parameters: Models.TagsResource, callback: msRest.ServiceCallback<Models.TagsResource>): void; /** * @param scope The resource scope. * @param parameters * @param options The optional parameters * @param callback The callback */ createOrUpdateAtScope(scope: string, parameters: Models.TagsResource, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.TagsResource>): void; createOrUpdateAtScope(scope: string, parameters: Models.TagsResource, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.TagsResource>, callback?: msRest.ServiceCallback<Models.TagsResource>): Promise<Models.TagsCreateOrUpdateAtScopeResponse> { return this.client.sendOperationRequest( { scope, parameters, options }, createOrUpdateAtScopeOperationSpec, callback) as Promise<Models.TagsCreateOrUpdateAtScopeResponse>; } /** * This operation allows replacing, merging or selectively deleting tags on the specified resource * or subscription. The specified entity can have a maximum of 50 tags at the end of the operation. * The 'replace' option replaces the entire set of existing tags with a new set. The 'merge' option * allows adding tags with new names and updating the values of tags with existing names. The * 'delete' option allows selectively deleting tags based on given names or name/value pairs. * @summary Selectively updates the set of tags on a resource or subscription. * @param scope The resource scope. * @param parameters * @param [options] The optional parameters * @returns Promise<Models.TagsUpdateAtScopeResponse> */ updateAtScope(scope: string, parameters: Models.TagsPatchResource, options?: msRest.RequestOptionsBase): Promise<Models.TagsUpdateAtScopeResponse>; /** * @param scope The resource scope. * @param parameters * @param callback The callback */ updateAtScope(scope: string, parameters: Models.TagsPatchResource, callback: msRest.ServiceCallback<Models.TagsResource>): void; /** * @param scope The resource scope. * @param parameters * @param options The optional parameters * @param callback The callback */ updateAtScope(scope: string, parameters: Models.TagsPatchResource, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.TagsResource>): void; updateAtScope(scope: string, parameters: Models.TagsPatchResource, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.TagsResource>, callback?: msRest.ServiceCallback<Models.TagsResource>): Promise<Models.TagsUpdateAtScopeResponse> { return this.client.sendOperationRequest( { scope, parameters, options }, updateAtScopeOperationSpec, callback) as Promise<Models.TagsUpdateAtScopeResponse>; } /** * @summary Gets the entire set of tags on a resource or subscription. * @param scope The resource scope. * @param [options] The optional parameters * @returns Promise<Models.TagsGetAtScopeResponse> */ getAtScope(scope: string, options?: msRest.RequestOptionsBase): Promise<Models.TagsGetAtScopeResponse>; /** * @param scope The resource scope. * @param callback The callback */ getAtScope(scope: string, callback: msRest.ServiceCallback<Models.TagsResource>): void; /** * @param scope The resource scope. * @param options The optional parameters * @param callback The callback */ getAtScope(scope: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.TagsResource>): void; getAtScope(scope: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.TagsResource>, callback?: msRest.ServiceCallback<Models.TagsResource>): Promise<Models.TagsGetAtScopeResponse> { return this.client.sendOperationRequest( { scope, options }, getAtScopeOperationSpec, callback) as Promise<Models.TagsGetAtScopeResponse>; } /** * @summary Deletes the entire set of tags on a resource or subscription. * @param scope The resource scope. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteAtScope(scope: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse>; /** * @param scope The resource scope. * @param callback The callback */ deleteAtScope(scope: string, callback: msRest.ServiceCallback<void>): void; /** * @param scope The resource scope. * @param options The optional parameters * @param callback The callback */ deleteAtScope(scope: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<void>): void; deleteAtScope(scope: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void>): Promise<msRest.RestResponse> { return this.client.sendOperationRequest( { scope, options }, deleteAtScopeOperationSpec, callback); } /** * This operation performs a union of predefined tags, resource tags, resource group tags and * subscription tags, and returns a summary of usage for each tag name and value under the given * subscription. In case of a large number of tags, this operation may return a previously cached * result. * @summary Gets a summary of tag usage under the subscription. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.TagsListNextResponse> */ listNext(nextPageLink: string, options?: msRest.RequestOptionsBase): Promise<Models.TagsListNextResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listNext(nextPageLink: string, callback: msRest.ServiceCallback<Models.TagsListResult>): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listNext(nextPageLink: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.TagsListResult>): void; listNext(nextPageLink: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.TagsListResult>, callback?: msRest.ServiceCallback<Models.TagsListResult>): Promise<Models.TagsListNextResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listNextOperationSpec, callback) as Promise<Models.TagsListNextResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const deleteValueOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/tagNames/{tagName}/tagValues/{tagValue}", urlParameters: [ Parameters.tagName, Parameters.tagValue, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const createOrUpdateValueOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/tagNames/{tagName}/tagValues/{tagValue}", urlParameters: [ Parameters.tagName, Parameters.tagValue, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.TagValue }, 201: { bodyMapper: Mappers.TagValue }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const createOrUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/tagNames/{tagName}", urlParameters: [ Parameters.tagName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.TagDetails }, 201: { bodyMapper: Mappers.TagDetails }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const deleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/tagNames/{tagName}", urlParameters: [ Parameters.tagName, Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/tagNames", urlParameters: [ Parameters.subscriptionId ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.TagsListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const createOrUpdateAtScopeOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "{scope}/providers/Microsoft.Resources/tags/default", urlParameters: [ Parameters.scope ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.TagsResource, required: true } }, responses: { 200: { bodyMapper: Mappers.TagsResource }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const updateAtScopeOperationSpec: msRest.OperationSpec = { httpMethod: "PATCH", path: "{scope}/providers/Microsoft.Resources/tags/default", urlParameters: [ Parameters.scope ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "parameters", mapper: { ...Mappers.TagsPatchResource, required: true } }, responses: { 200: { bodyMapper: Mappers.TagsResource }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const getAtScopeOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "{scope}/providers/Microsoft.Resources/tags/default", urlParameters: [ Parameters.scope ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.TagsResource }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const deleteAtScopeOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "{scope}/providers/Microsoft.Resources/tags/default", urlParameters: [ Parameters.scope ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, default: { bodyMapper: Mappers.CloudError } }, serializer }; const listNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "https://management.azure.com", path: "{nextLink}", urlParameters: [ Parameters.nextPageLink ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.TagsListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer };
the_stack
export interface AnalyzerModule { name: string, description: string, category: ModuleCategory algorithm: ModuleAlgorithm version: SupportedVersion visit: VisitFunction report: ReportFunction } // This version signifies the module support for Solidity version. // start will be minimum at 0.4.12 as since that version Solidity exports latest AST // end should be a version in which analysis feature got deprecated. // This will be helpful in version based analysis in future. export interface SupportedVersion { start: string end?: string } export interface ModuleAlgorithm { hasFalsePositives: boolean, hasFalseNegatives: boolean, id: string } export interface ModuleCategory { displayName: string, id: string } export interface ReportObj { warning: string, location: string, more?: string } // Regarding location, the source mappings inside the AST use the following notation: // s:l:f // Where, // s is the byte-offset to the start of the range in the source file, // l is the length of the source range in bytes and // f is the source index mentioned above. export interface AnalysisReportObj { warning: string, location?: string, more?: string error? : string } export type AnalysisReport = { name: string report: AnalysisReportObj[] } export interface CompilationResult { error?: CompilationError, /** not present if no errors/warnings were encountered */ errors?: CompilationError[] /** This contains the file-level outputs. In can be limited/filtered by the outputSelection settings */ sources?: { [contractName: string]: CompilationSource } /** This contains the contract-level outputs. It can be limited/filtered by the outputSelection settings */ contracts: CompiledContractObj /** If the language used has no contract names, this field should equal to an empty string. */ } export interface CompiledContractObj { [fileName: string]: { [contract: string]: CompiledContract } } export type VisitFunction = (node: any) => void export type ReportFunction = (compilationResult: CompilationResult) => ReportObj[] export interface ContractHLAst { node: ContractDefinitionAstNode, functions: FunctionHLAst[], relevantNodes: { referencedDeclaration: number, node: any }[], modifiers: ModifierHLAst[], inheritsFrom: string[], stateVariables: VariableDeclarationAstNode[] } export interface FunctionHLAst { node: FunctionDefinitionAstNode, relevantNodes: any[], modifierInvocations: ModifierInvocationAstNode[], localVariables: VariableDeclarationAstNode[], parameters: string[], returns: Record<string, string>[] } export interface ModifierHLAst { node: ModifierDefinitionAstNode, relevantNodes: any[], localVariables: VariableDeclarationAstNode[], parameters: string[], } export interface Context { callGraph: Record<string, ContractCallGraph> currentContract: ContractHLAst stateVariables: VariableDeclarationAstNode[] } export interface FunctionCallGraph { node: FunctionHLAst calls: string[] } export interface ContractCallGraph { contract: ContractHLAst functions: Record<string, FunctionCallGraph> } ///////////////////////////////////////////////////////////// ///////////// Specfic AST Nodes ///////////////////////////// ///////////////////////////////////////////////////////////// interface TypeDescription { typeIdentifier: string typeString: string } export interface SourceUnitAstNode { id: number nodeType: 'SourceUnit' src: string absolutePath: string exportedSymbols: object nodes: Array<AstNode> } export interface PragmaDirectiveAstNode { id: number nodeType: 'PragmaDirective' src: string literals?: Array<string> } interface SymbolAlias { foreign: IdentifierAstNode local: string | null } export interface ImportDirectiveAstNode { id: number nodeType: 'ImportDirective' src: string absolutePath: string file: string scope: number sourceUnit: number symbolAliases: Array<SymbolAlias> unitAlias: string } export interface ContractDefinitionAstNode { id: number nodeType: 'ContractDefinition' src: string name: string documentation: string | null contractKind: 'interface' | 'contract' | 'library' abstract: boolean fullyImplemented: boolean linearizedBaseContracts: Array<number> baseContracts: Array<InheritanceSpecifierAstNode> contractDependencies: Array<number> nodes: Array<any> scope: number } export interface InheritanceSpecifierAstNode { id: number nodeType: 'InheritanceSpecifier' src: string baseName: UserDefinedTypeNameAstNode arguments: LiteralAstNode | null } export interface UsingForDirectiveAstNode { id: number nodeType: 'UsingForDirective' src: string libraryName: UserDefinedTypeNameAstNode typeName: UserDefinedTypeNameAstNode | ElementaryTypeNameAstNode | null } export interface StructDefinitionAstNode { id: number nodeType: 'StructDefinition' src: string name: string visibility: string canonicalName: string members: Array<VariableDeclarationAstNode> scope: number } export interface EnumDefinitionAstNode { id: number nodeType: 'EnumDefinition' src: string name: string canonicalName: string members: Array<EnumValueAstNode> } export interface EnumValueAstNode { id: number nodeType: 'EnumValue' src: string name: string } export interface ParameterListAstNode { id: number nodeType: 'ParameterList' src: string parameters: Array<VariableDeclarationAstNode> } export interface OverrideSpecifierAstNode { id: number nodeType: 'OverrideSpecifier' src: string overrides: Array<UserDefinedTypeNameAstNode> } export interface FunctionDefinitionAstNode { id: number nodeType: 'FunctionDefinition' src: string name: string documentation: string | null kind: string stateMutability: 'pure' | 'view' | 'nonpayable' | 'payable' visibility: string virtual: boolean overrides: OverrideSpecifierAstNode | null parameters: ParameterListAstNode returnParameters: ParameterListAstNode modifiers: Array<ModifierInvocationAstNode> body: object | null implemented: boolean scope: number functionSelector?: string baseFunctions?: Array<number> } export interface VariableDeclarationAstNode { id: number nodeType: 'VariableDeclaration' src: string name: string typeName: ElementaryTypeNameAstNode | UserDefinedTypeNameAstNode constant: boolean stateVariable: boolean storageLocation: 'storage' | 'memory' | 'calldata' | 'default' overrides: OverrideSpecifierAstNode | null visibility: string value: string | null scope: number typeDescriptions: TypeDescription functionSelector?: string indexed?: boolean baseFunctions?: object } export interface ModifierDefinitionAstNode { id: number nodeType: 'ModifierDefinition' src: string name: string documentation: object | null visibility: string parameters: ParameterListAstNode virtual: boolean overrides: OverrideSpecifierAstNode | null body: BlockAstNode baseModifiers?: Array<number> } export interface ModifierInvocationAstNode { id: number nodeType: 'ModifierInvocation' src: string modifierName: IdentifierAstNode arguments: Array<LiteralAstNode> | null } export interface EventDefinitionAstNode { id: number nodeType: 'EventDefinition' src: string name: string documentation: object | null parameters: ParameterListAstNode anonymous: boolean } export interface ElementaryTypeNameAstNode { id: number nodeType: 'ElementaryTypeName' src: string name: string typeDescriptions: TypeDescription stateMutability?: 'pure' | 'view' | 'nonpayable' | 'payable' } export interface UserDefinedTypeNameAstNode { id: number nodeType: 'UserDefinedTypeName' src: string name: string referencedDeclaration: number contractScope: number | null typeDescriptions: TypeDescription } export interface FunctionTypeNameAstNode { id: number nodeType: 'FunctionTypeName' src: string name: string visibility: string stateMutability: 'pure' | 'view' | 'nonpayable' | 'payable' parameterTypes: ParameterListAstNode returnParameterTypes: ParameterListAstNode typeDescriptions: TypeDescription } export interface MappingAstNode { id: number nodeType: 'Mapping' src: string keyType: UserDefinedTypeNameAstNode | ElementaryTypeNameAstNode valueType: UserDefinedTypeNameAstNode | ElementaryTypeNameAstNode typeDescriptions: TypeDescription } export interface ArrayTypeNameAstNode { id: number nodeType: 'ArrayTypeName' src: string baseType: UserDefinedTypeNameAstNode | ElementaryTypeNameAstNode length: LiteralAstNode | null typeDescriptions: TypeDescription } interface externalReference { declaration: number isOffset: boolean isSlot: boolean src: string valueSize: number } export interface InlineAssemblyAstNode { id: number nodeType: 'InlineAssembly' src: string AST: YulBlockAstNode externalReferences: Array<externalReference> evmVersion: string } export interface BlockAstNode { id: number nodeType: 'Block' src: string statements: Array<any> } export interface PlaceholderStatementAstNode { id: number nodeType: 'PlaceholderStatement' src: string } export interface IfStatementAstNode { id: number nodeType: 'IfStatement' src: string condition: object trueBody: BlockAstNode | ExpressionStatementAstNode falseBody: BlockAstNode | ExpressionStatementAstNode } export interface TryCatchClauseAstNode { id: number nodeType: 'TryCatchClause' src: string errorName: string parameters: ParameterListAstNode block: BlockAstNode } export interface TryStatementAstNode { id: number nodeType: 'TryStatement' src: string externalCall: object clauses: Array<TryCatchClauseAstNode> } export interface WhileStatementAstNode { id: number nodeType: 'WhileStatement' | 'DoWhileStatement' src: string condition: any body: BlockAstNode | ExpressionStatementAstNode } export interface ForStatementAstNode { id: number nodeType: 'ForStatement' src: string initializationExpression: VariableDeclarationStatementAstNode condition: any loopExpression: ExpressionStatementAstNode body: BlockAstNode | ExpressionStatementAstNode } export interface ContinueAstNode { id: number nodeType: 'Continue' src: string } export interface BreakAstNode { id: number nodeType: 'Break' src: string } export interface ReturnAstNode { id: number nodeType: 'Return' src: string expression: object | null functionReturnParameters: number } export interface ThrowAstNode { id: number nodeType: 'Throw' src: string } export interface EmitStatementAstNode { id: number nodeType: 'EmitStatement' src: string eventCall: FunctionCallAstNode } export interface VariableDeclarationStatementAstNode { id: number nodeType: 'VariableDeclarationStatement' src: string assignments: Array<number> declarations: Array<object> initialValue: object } export interface ExpressionStatementAstNode { id: number nodeType: 'ExpressionStatement' src: string expression: any } interface ExpressionAttributes { typeDescriptions: TypeDescription isConstant: boolean isPure: boolean isLValue: boolean lValueRequested: boolean argumentTypes: Array<TypeDescription> | null } export interface ConditionalAstNode extends ExpressionAttributes { id: number nodeType: 'Conditional' src: string condition: object trueExpression: object falseExpression: object } export interface AssignmentAstNode extends ExpressionAttributes { id: number nodeType: 'Assignment' src: string operator: string leftHandSide: any rightHandSide: object } export interface TupleExpressionAstNode extends ExpressionAttributes { id: number nodeType: 'TupleExpression' src: string isInlineArray: boolean components: Array<object> } export interface UnaryOperationAstNode extends ExpressionAttributes { id: number nodeType: 'UnaryOperation' src: string prefix: boolean operator: string subExpression: any } export interface BinaryOperationAstNode extends ExpressionAttributes { id: number nodeType: 'BinaryOperation' src: string operator: string leftExpression: object rightExpression: object commonType: TypeDescription } export interface FunctionCallAstNode extends ExpressionAttributes { id: number nodeType: 'FunctionCall' src: string expression: any names: Array<any> arguments: object tryCall: boolean kind: 'functionCall' | 'typeConversion' | 'structConstructorCall' } export interface FunctionCallOptionsAstNode extends ExpressionAttributes { id: number nodeType: 'FunctionCallOptions' src: string expression: object names: Array<string> options: Array<object> } export interface NewExpressionAstNode extends ExpressionAttributes { id: number nodeType: 'NewExpression' src: string typeName: UserDefinedTypeNameAstNode | ElementaryTypeNameAstNode } export interface MemberAccessAstNode extends ExpressionAttributes { id: number nodeType: 'MemberAccess' src: string memberName: string expression: any referencedDeclaration: number | null } export interface IndexAccessAstNode extends ExpressionAttributes { id: number nodeType: 'IndexAccess' src: string baseExpression: object indexExpression: object } export interface IndexRangeAccessAstNode extends ExpressionAttributes { id: number nodeType: 'IndexRangeAccess' src: string baseExpression: object startExpression: object endExpression: object } export interface ElementaryTypeNameExpressionAstNode extends ExpressionAttributes { id: number nodeType: 'ElementaryTypeNameExpression' src: string typeName: ElementaryTypeNameAstNode } export interface LiteralAstNode extends ExpressionAttributes { id: number nodeType: 'Literal' src: string kind: 'number' | 'string' | 'bool' value: string hexValue: string subdenomination: 'wei' | 'szabo' | 'finney' | 'ether' | null } export interface IdentifierAstNode { id: number nodeType: 'Identifier' src: string name: string referencedDeclaration: number overloadedDeclarations: Array<any> typeDescriptions: TypeDescription argumentTypes: Array<TypeDescription> | null } export interface StructuredDocumentationAstNode { id: number nodeType: 'StructuredDocumentation' src: string text: string } export interface CommonAstNode { id: number nodeType: string src: string [x: string]: any } ///////////////////////////////////////////////////////// ///////////// YUL AST Nodes ///////////////////////////// ///////////////////////////////////////////////////////// export interface YulTypedNameAstNode { name: string nodeType: 'YulTypedName' src: string type: string } export interface YulIdentifierAstNode { name: string nodeType: 'YulIdentifier' src: string } export interface YulLiteralAstNode { kind: string nodeType: 'YulLiteral' src: string type: string value: string } export interface YulVariableDeclarationAstNode { nodeType: 'YulVariableDeclaration' src: string value: YulIdentifierAstNode | YulLiteralAstNode variables: Array<YulTypedNameAstNode> } export interface YulBlockAstNode { nodeType: 'YulBlock' src: string statements: Array<YulVariableDeclarationAstNode> } export interface CommonYulAstNode { nodeType: string src: string [x: string]: any } /////////// // ERROR // /////////// export interface CompilationError { /** Location within the source file */ sourceLocation?: { file: string start: number end: number } /** Error type */ type?: CompilationErrorType /** Component where the error originated, such as "general", "ewasm", etc. */ component?: 'general' | 'ewasm' | string severity?: 'error' | 'warning' message?: string mode?: 'panic' /** the message formatted with source location */ formattedMessage?: string } type CompilationErrorType = | 'JSONError' | 'IOError' | 'ParserError' | 'DocstringParsingError' | 'SyntaxError' | 'DeclarationError' | 'TypeError' | 'UnimplementedFeatureError' | 'InternalCompilerError' | 'Exception' | 'CompilerError' | 'FatalError' | 'Warning' //////////// // SOURCE // //////////// export interface CompilationSource { /** Identifier of the source (used in source maps) */ id: number /** The AST object */ ast: AstNode /** The legacy AST object */ legacyAST: AstNodeLegacy } ///////// // AST // ///////// export interface AstNode { absolutePath?: string exportedSymbols?: object id: number nodeType: string nodes?: Array<AstNode> src: string literals?: Array<string> file?: string scope?: number sourceUnit?: number symbolAliases?: Array<string> [x: string]: any } export interface AstNodeLegacy { id: number name: string src: string children?: Array<AstNodeLegacy> attributes?: AstNodeAtt } export interface AstNodeAtt { operator?: string string?: null type?: string value?: string constant?: boolean name?: string public?: boolean exportedSymbols?: object argumentTypes?: null absolutePath?: string [x: string]: any } ////////////// // CONTRACT // ////////////// export interface CompiledContract { /** The Ethereum Contract ABI. If empty, it is represented as an empty array. */ abi: ABIDescription[] // See the Metadata Output documentation (serialised JSON string) metadata: string /** User documentation (natural specification) */ userdoc: UserDocumentation /** Developer documentation (natural specification) */ devdoc: DeveloperDocumentation /** Intermediate representation (string) */ ir: string /** EVM-related outputs */ evm: { assembly: string legacyAssembly: {} /** Bytecode and related details. */ bytecode: BytecodeObject deployedBytecode: BytecodeObject /** The list of function hashes */ methodIdentifiers: { [functionIdentifier: string]: string } // Function gas estimates gasEstimates: { creation: { codeDepositCost: string executionCost: 'infinite' | string totalCost: 'infinite' | string } external: { [functionIdentifier: string]: string } internal: { [functionIdentifier: string]: 'infinite' | string } } } /** eWASM related outputs */ ewasm: { /** S-expressions format */ wast: string /** Binary format (hex string) */ wasm: string } } ///////// // ABI // ///////// export type ABIDescription = FunctionDescription | EventDescription export interface FunctionDescription { /** Type of the method. default is 'function' */ type?: 'function' | 'constructor' | 'fallback' | 'receive' /** The name of the function. Constructor and fallback function never have name */ name?: string /** List of parameters of the method. Fallback function doesn’t have inputs. */ inputs?: ABIParameter[] /** List of the outputs parameters for the method, if any */ outputs?: ABIParameter[] /** State mutability of the method */ stateMutability: 'pure' | 'view' | 'nonpayable' | 'payable' /** true if function accepts Ether, false otherwise. Default is false */ payable?: boolean /** true if function is either pure or view, false otherwise. Default is false */ constant?: boolean } export interface EventDescription { type: 'event' name: string inputs: ABIParameter & { /** true if the field is part of the log’s topics, false if it one of the log’s data segment. */ indexed: boolean }[] /** true if the event was declared as anonymous. */ anonymous: boolean } export interface ABIParameter { internalType: string /** The name of the parameter */ name: string /** The canonical type of the parameter */ type: ABITypeParameter /** Used for tuple types */ components?: ABIParameter[] } export type ABITypeParameter = | 'uint' | 'uint[]' // TODO : add <M> | 'int' | 'int[]' // TODO : add <M> | 'address' | 'address[]' | 'bool' | 'bool[]' | 'fixed' | 'fixed[]' // TODO : add <M> | 'ufixed' | 'ufixed[]' // TODO : add <M> | 'bytes' | 'bytes[]' // TODO : add <M> | 'function' | 'function[]' | 'tuple' | 'tuple[]' | string // Fallback /////////////////////////// // NATURAL SPECIFICATION // /////////////////////////// // Userdoc export interface UserDocumentation { methods: UserMethodList notice: string } export type UserMethodList = { [functionIdentifier: string]: UserMethodDoc } & { 'constructor'?: string } export interface UserMethodDoc { notice: string } // Devdoc export interface DeveloperDocumentation { author: string title: string details: string methods: DevMethodList } export interface DevMethodList { [functionIdentifier: string]: DevMethodDoc } export interface DevMethodDoc { author: string details: string return: string params: { [param: string]: string } } ////////////// // BYTECODE // ////////////// export interface BytecodeObject { /** The bytecode as a hex string. */ object: string /** Opcodes list */ opcodes: string /** The source mapping as a string. See the source mapping definition. */ sourceMap: string /** If given, this is an unlinked object. */ linkReferences?: { [contractName: string]: { /** Byte offsets into the bytecode. */ [library: string]: { start: number; length: number }[] } } }
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * Manages a Streaming Endpoint. * * ## Example Usage * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as azure from "@pulumi/azure"; * * const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"}); * const exampleAccount = new azure.storage.Account("exampleAccount", { * resourceGroupName: exampleResourceGroup.name, * location: exampleResourceGroup.location, * accountTier: "Standard", * accountReplicationType: "GRS", * }); * const exampleServiceAccount = new azure.media.ServiceAccount("exampleServiceAccount", { * location: exampleResourceGroup.location, * resourceGroupName: exampleResourceGroup.name, * storageAccounts: [{ * id: exampleAccount.id, * isPrimary: true, * }], * }); * const exampleStreamingEndpoint = new azure.media.StreamingEndpoint("exampleStreamingEndpoint", { * resourceGroupName: exampleResourceGroup.name, * location: exampleResourceGroup.location, * mediaServicesAccountName: exampleServiceAccount.name, * scaleUnits: 2, * }); * ``` * ### With Access Control * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as azure from "@pulumi/azure"; * * const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"}); * const exampleAccount = new azure.storage.Account("exampleAccount", { * resourceGroupName: exampleResourceGroup.name, * location: exampleResourceGroup.location, * accountTier: "Standard", * accountReplicationType: "GRS", * }); * const exampleServiceAccount = new azure.media.ServiceAccount("exampleServiceAccount", { * location: exampleResourceGroup.location, * resourceGroupName: exampleResourceGroup.name, * storageAccounts: [{ * id: exampleAccount.id, * isPrimary: true, * }], * }); * const exampleStreamingEndpoint = new azure.media.StreamingEndpoint("exampleStreamingEndpoint", { * resourceGroupName: exampleResourceGroup.name, * location: exampleResourceGroup.location, * mediaServicesAccountName: exampleServiceAccount.name, * scaleUnits: 2, * accessControl: { * ipAllows: [ * { * name: "AllowedIP", * address: "192.168.1.1", * }, * { * name: "AnotherIp", * address: "192.168.1.2", * }, * ], * akamaiSignatureHeaderAuthenticationKeys: [ * { * identifier: "id1", * expiration: "2030-12-31T16:00:00Z", * base64Key: "dGVzdGlkMQ==", * }, * { * identifier: "id2", * expiration: "2032-01-28T16:00:00Z", * base64Key: "dGVzdGlkMQ==", * }, * ], * }, * }); * ``` * * ## Import * * Streaming Endpoints can be imported using the `resource id`, e.g. * * ```sh * $ pulumi import azure:media/streamingEndpoint:StreamingEndpoint example /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/group1/mediaservices/service1/streamingendpoints/endpoint1 * ``` */ export class StreamingEndpoint extends pulumi.CustomResource { /** * Get an existing StreamingEndpoint 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?: StreamingEndpointState, opts?: pulumi.CustomResourceOptions): StreamingEndpoint { return new StreamingEndpoint(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'azure:media/streamingEndpoint:StreamingEndpoint'; /** * Returns true if the given object is an instance of StreamingEndpoint. 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 StreamingEndpoint { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === StreamingEndpoint.__pulumiType; } /** * A `accessControl` block as defined below. */ public readonly accessControl!: pulumi.Output<outputs.media.StreamingEndpointAccessControl | undefined>; /** * The flag indicates if the resource should be automatically started on creation. */ public readonly autoStartEnabled!: pulumi.Output<boolean>; /** * The CDN enabled flag. */ public readonly cdnEnabled!: pulumi.Output<boolean | undefined>; /** * The CDN profile name. */ public readonly cdnProfile!: pulumi.Output<string>; /** * The CDN provider name. Supported value are `StandardVerizon`,`PremiumVerizon` and `StandardAkamai` */ public readonly cdnProvider!: pulumi.Output<string>; /** * A `crossSiteAccessPolicy` block as defined below. */ public readonly crossSiteAccessPolicy!: pulumi.Output<outputs.media.StreamingEndpointCrossSiteAccessPolicy | undefined>; /** * The custom host names of the streaming endpoint. */ public readonly customHostNames!: pulumi.Output<string[] | undefined>; /** * The streaming endpoint description. */ public readonly description!: pulumi.Output<string | undefined>; /** * The host name of the Streaming Endpoint. */ public /*out*/ readonly hostName!: pulumi.Output<string>; /** * The Azure Region where the Streaming Endpoint should exist. Changing this forces a new Streaming Endpoint to be created. */ public readonly location!: pulumi.Output<string>; /** * Max cache age in seconds. */ public readonly maxCacheAgeSeconds!: pulumi.Output<number | undefined>; /** * The Media Services account name. Changing this forces a new Streaming Endpoint to be created. */ public readonly mediaServicesAccountName!: pulumi.Output<string>; /** * The name which should be used for this Streaming Endpoint maximum length is 24. Changing this forces a new Streaming Endpoint to be created. */ public readonly name!: pulumi.Output<string>; /** * The name of the Resource Group where the Streaming Endpoint should exist. Changing this forces a new Streaming Endpoint to be created. */ public readonly resourceGroupName!: pulumi.Output<string>; /** * The number of scale units. */ public readonly scaleUnits!: pulumi.Output<number>; /** * A mapping of tags which should be assigned to the Streaming Endpoint. */ public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>; /** * Create a StreamingEndpoint 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: StreamingEndpointArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: StreamingEndpointArgs | StreamingEndpointState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as StreamingEndpointState | undefined; inputs["accessControl"] = state ? state.accessControl : undefined; inputs["autoStartEnabled"] = state ? state.autoStartEnabled : undefined; inputs["cdnEnabled"] = state ? state.cdnEnabled : undefined; inputs["cdnProfile"] = state ? state.cdnProfile : undefined; inputs["cdnProvider"] = state ? state.cdnProvider : undefined; inputs["crossSiteAccessPolicy"] = state ? state.crossSiteAccessPolicy : undefined; inputs["customHostNames"] = state ? state.customHostNames : undefined; inputs["description"] = state ? state.description : undefined; inputs["hostName"] = state ? state.hostName : undefined; inputs["location"] = state ? state.location : undefined; inputs["maxCacheAgeSeconds"] = state ? state.maxCacheAgeSeconds : undefined; inputs["mediaServicesAccountName"] = state ? state.mediaServicesAccountName : undefined; inputs["name"] = state ? state.name : undefined; inputs["resourceGroupName"] = state ? state.resourceGroupName : undefined; inputs["scaleUnits"] = state ? state.scaleUnits : undefined; inputs["tags"] = state ? state.tags : undefined; } else { const args = argsOrState as StreamingEndpointArgs | undefined; if ((!args || args.mediaServicesAccountName === undefined) && !opts.urn) { throw new Error("Missing required property 'mediaServicesAccountName'"); } if ((!args || args.resourceGroupName === undefined) && !opts.urn) { throw new Error("Missing required property 'resourceGroupName'"); } if ((!args || args.scaleUnits === undefined) && !opts.urn) { throw new Error("Missing required property 'scaleUnits'"); } inputs["accessControl"] = args ? args.accessControl : undefined; inputs["autoStartEnabled"] = args ? args.autoStartEnabled : undefined; inputs["cdnEnabled"] = args ? args.cdnEnabled : undefined; inputs["cdnProfile"] = args ? args.cdnProfile : undefined; inputs["cdnProvider"] = args ? args.cdnProvider : undefined; inputs["crossSiteAccessPolicy"] = args ? args.crossSiteAccessPolicy : undefined; inputs["customHostNames"] = args ? args.customHostNames : undefined; inputs["description"] = args ? args.description : undefined; inputs["location"] = args ? args.location : undefined; inputs["maxCacheAgeSeconds"] = args ? args.maxCacheAgeSeconds : undefined; inputs["mediaServicesAccountName"] = args ? args.mediaServicesAccountName : undefined; inputs["name"] = args ? args.name : undefined; inputs["resourceGroupName"] = args ? args.resourceGroupName : undefined; inputs["scaleUnits"] = args ? args.scaleUnits : undefined; inputs["tags"] = args ? args.tags : undefined; inputs["hostName"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(StreamingEndpoint.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering StreamingEndpoint resources. */ export interface StreamingEndpointState { /** * A `accessControl` block as defined below. */ accessControl?: pulumi.Input<inputs.media.StreamingEndpointAccessControl>; /** * The flag indicates if the resource should be automatically started on creation. */ autoStartEnabled?: pulumi.Input<boolean>; /** * The CDN enabled flag. */ cdnEnabled?: pulumi.Input<boolean>; /** * The CDN profile name. */ cdnProfile?: pulumi.Input<string>; /** * The CDN provider name. Supported value are `StandardVerizon`,`PremiumVerizon` and `StandardAkamai` */ cdnProvider?: pulumi.Input<string>; /** * A `crossSiteAccessPolicy` block as defined below. */ crossSiteAccessPolicy?: pulumi.Input<inputs.media.StreamingEndpointCrossSiteAccessPolicy>; /** * The custom host names of the streaming endpoint. */ customHostNames?: pulumi.Input<pulumi.Input<string>[]>; /** * The streaming endpoint description. */ description?: pulumi.Input<string>; /** * The host name of the Streaming Endpoint. */ hostName?: pulumi.Input<string>; /** * The Azure Region where the Streaming Endpoint should exist. Changing this forces a new Streaming Endpoint to be created. */ location?: pulumi.Input<string>; /** * Max cache age in seconds. */ maxCacheAgeSeconds?: pulumi.Input<number>; /** * The Media Services account name. Changing this forces a new Streaming Endpoint to be created. */ mediaServicesAccountName?: pulumi.Input<string>; /** * The name which should be used for this Streaming Endpoint maximum length is 24. Changing this forces a new Streaming Endpoint to be created. */ name?: pulumi.Input<string>; /** * The name of the Resource Group where the Streaming Endpoint should exist. Changing this forces a new Streaming Endpoint to be created. */ resourceGroupName?: pulumi.Input<string>; /** * The number of scale units. */ scaleUnits?: pulumi.Input<number>; /** * A mapping of tags which should be assigned to the Streaming Endpoint. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; } /** * The set of arguments for constructing a StreamingEndpoint resource. */ export interface StreamingEndpointArgs { /** * A `accessControl` block as defined below. */ accessControl?: pulumi.Input<inputs.media.StreamingEndpointAccessControl>; /** * The flag indicates if the resource should be automatically started on creation. */ autoStartEnabled?: pulumi.Input<boolean>; /** * The CDN enabled flag. */ cdnEnabled?: pulumi.Input<boolean>; /** * The CDN profile name. */ cdnProfile?: pulumi.Input<string>; /** * The CDN provider name. Supported value are `StandardVerizon`,`PremiumVerizon` and `StandardAkamai` */ cdnProvider?: pulumi.Input<string>; /** * A `crossSiteAccessPolicy` block as defined below. */ crossSiteAccessPolicy?: pulumi.Input<inputs.media.StreamingEndpointCrossSiteAccessPolicy>; /** * The custom host names of the streaming endpoint. */ customHostNames?: pulumi.Input<pulumi.Input<string>[]>; /** * The streaming endpoint description. */ description?: pulumi.Input<string>; /** * The Azure Region where the Streaming Endpoint should exist. Changing this forces a new Streaming Endpoint to be created. */ location?: pulumi.Input<string>; /** * Max cache age in seconds. */ maxCacheAgeSeconds?: pulumi.Input<number>; /** * The Media Services account name. Changing this forces a new Streaming Endpoint to be created. */ mediaServicesAccountName: pulumi.Input<string>; /** * The name which should be used for this Streaming Endpoint maximum length is 24. Changing this forces a new Streaming Endpoint to be created. */ name?: pulumi.Input<string>; /** * The name of the Resource Group where the Streaming Endpoint should exist. Changing this forces a new Streaming Endpoint to be created. */ resourceGroupName: pulumi.Input<string>; /** * The number of scale units. */ scaleUnits: pulumi.Input<number>; /** * A mapping of tags which should be assigned to the Streaming Endpoint. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; }
the_stack
import { IDiagnosticLogger } from "../JavaScriptSDK.Interfaces/IDiagnosticLogger"; import { ICookieMgr, ICookieMgrConfig } from "../JavaScriptSDK.Interfaces/ICookieMgr"; import { _eInternalMessageId, eLoggingSeverity } from "../JavaScriptSDK.Enums/LoggingEnums"; import { dumpObj, getDocument, getLocation, getNavigator, isIE } from "./EnvUtils"; import { arrForEach, dateNow, getExceptionName, isFunction, isNotNullOrUndefined, isNullOrUndefined, isString, isTruthy, isUndefined, objForEachKey, setValue, strContains, strEndsWith, strTrim } from "./HelperFuncs"; import { IConfiguration } from "../JavaScriptSDK.Interfaces/IConfiguration"; import { IAppInsightsCore } from "../JavaScriptSDK.Interfaces/IAppInsightsCore"; import { strEmpty } from "./InternalConstants"; import { _throwInternal } from "./DiagnosticLogger"; const strToGMTString = "toGMTString"; const strToUTCString = "toUTCString"; const strCookie = "cookie"; const strExpires = "expires"; const strEnabled = "enabled"; const strIsCookieUseDisabled = "isCookieUseDisabled"; const strDisableCookiesUsage = "disableCookiesUsage"; const strConfigCookieMgr = "_ckMgr"; let _supportsCookies: boolean = null; let _allowUaSameSite: boolean = null; let _parsedCookieValue: string = null; let _doc = getDocument(); let _cookieCache = {}; let _globalCookieConfig = {}; /** * @ignore * DO NOT USE or export from the module, this is exposed as public to support backward compatibility of previous static utility methods only. * If you want to manager cookies either use the ICookieMgr available from the core instance via getCookieMgr() or create * your own instance of the CookieMgr and use that. * Using this directly for enabling / disabling cookie handling will not only affect your usage but EVERY user of cookies. * Example, if you are using a shared component that is also using Application Insights you will affect their cookie handling. * @param logger - The DiagnosticLogger to use for reporting errors. */ export function _gblCookieMgr(config?: IConfiguration, logger?: IDiagnosticLogger): ICookieMgr { // Stash the global instance against the BaseCookieMgr class let inst = createCookieMgr[strConfigCookieMgr] || _globalCookieConfig[strConfigCookieMgr]; if (!inst) { // Note: not using the getSetValue() helper as that would require always creating a temporary cookieMgr // that ultimately is never used inst = createCookieMgr[strConfigCookieMgr] = createCookieMgr(config, logger); _globalCookieConfig[strConfigCookieMgr] = inst; } return inst; } function _isMgrEnabled(cookieMgr: ICookieMgr) { if (cookieMgr) { return cookieMgr.isEnabled(); } return true; } function _createCookieMgrConfig(rootConfig: IConfiguration): ICookieMgrConfig { let cookieMgrCfg = rootConfig.cookieCfg = rootConfig.cookieCfg || {}; // Sets the values from the root config if not already present on the cookieMgrCfg setValue(cookieMgrCfg, "domain", rootConfig.cookieDomain, isNotNullOrUndefined, isNullOrUndefined); setValue(cookieMgrCfg, "path", rootConfig.cookiePath || "/", null, isNullOrUndefined); if (isNullOrUndefined(cookieMgrCfg[strEnabled])) { // Set the enabled from the provided setting or the legacy root values let cookieEnabled: boolean; if (!isUndefined(rootConfig[strIsCookieUseDisabled])) { cookieEnabled = !rootConfig[strIsCookieUseDisabled]; } if (!isUndefined(rootConfig[strDisableCookiesUsage])) { cookieEnabled = !rootConfig[strDisableCookiesUsage]; } cookieMgrCfg[strEnabled] = cookieEnabled; } return cookieMgrCfg; } /** * Helper to return the ICookieMgr from the core (if not null/undefined) or a default implementation * associated with the configuration or a legacy default. * @param core * @param config * @returns */ export function safeGetCookieMgr(core: IAppInsightsCore, config?: IConfiguration) { let cookieMgr: ICookieMgr; if (core) { // Always returns an instance cookieMgr = core.getCookieMgr(); } else if (config) { let cookieCfg = config.cookieCfg; if (cookieCfg[strConfigCookieMgr]) { cookieMgr = cookieCfg[strConfigCookieMgr]; } else { cookieMgr = createCookieMgr(config); } } if (!cookieMgr) { // Get or initialize the default global (legacy) cookie manager if we couldn't find one cookieMgr = _gblCookieMgr(config, (core || {} as any).logger); } return cookieMgr; } export function createCookieMgr(rootConfig?: IConfiguration, logger?: IDiagnosticLogger): ICookieMgr { let cookieMgrConfig = _createCookieMgrConfig(rootConfig || _globalCookieConfig); let _path = cookieMgrConfig.path || "/"; let _domain = cookieMgrConfig.domain; // Explicitly checking against false, so that setting to undefined will === true let _enabled = cookieMgrConfig[strEnabled] !== false; let cookieMgr: ICookieMgr = { isEnabled: () => { let enabled = _enabled && areCookiesSupported(logger); // Using an indirect lookup for any global cookie manager to support tree shaking for SDK's // that don't use the "applicationinsights-core" version of the default cookie function let gblManager = _globalCookieConfig[strConfigCookieMgr]; if (enabled && gblManager && cookieMgr !== gblManager) { // Make sure the GlobalCookie Manager instance (if not this instance) is also enabled. // As the global (deprecated) functions may have been called (for backward compatibility) enabled = _isMgrEnabled(gblManager); } return enabled; }, setEnabled: (value: boolean) => { // Explicitly checking against false, so that setting to undefined will === true _enabled = value !== false; }, set: (name: string, value: string, maxAgeSec?: number, domain?: string, path?: string) => { let result = false; if (_isMgrEnabled(cookieMgr)) { let values: any = {}; let theValue = strTrim(value || strEmpty); let idx = theValue.indexOf(";"); if (idx !== -1) { theValue = strTrim(value.substring(0, idx)); values = _extractParts(value.substring(idx + 1)); } // Only update domain if not already present (isUndefined) and the value is truthy (not null, undefined or empty string) setValue(values, "domain", domain || _domain, isTruthy, isUndefined); if (!isNullOrUndefined(maxAgeSec)) { const _isIE = isIE(); if (isUndefined(values[strExpires])) { const nowMs = dateNow(); // Only add expires if not already present let expireMs = nowMs + (maxAgeSec * 1000); // Sanity check, if zero or -ve then ignore if (expireMs > 0) { let expiry = new Date(); expiry.setTime(expireMs); setValue(values, strExpires, _formatDate(expiry, !_isIE ? strToUTCString : strToGMTString) || _formatDate(expiry, _isIE ? strToGMTString : strToUTCString) || strEmpty, isTruthy); } } if (!_isIE) { // Only replace if not already present setValue(values, "max-age", strEmpty + maxAgeSec, null, isUndefined); } } let location = getLocation(); if (location && location.protocol === "https:") { setValue(values, "secure", null, null, isUndefined); // Only set same site if not also secure if (_allowUaSameSite === null) { _allowUaSameSite = !uaDisallowsSameSiteNone((getNavigator() || {} as Navigator).userAgent); } if (_allowUaSameSite) { setValue(values, "SameSite", "None", null, isUndefined); } } setValue(values, "path", path || _path, null, isUndefined); let setCookieFn = cookieMgrConfig.setCookie || _setCookieValue; setCookieFn(name, _formatCookieValue(theValue, values)); result = true; } return result; }, get: (name: string): string => { let value = strEmpty if (_isMgrEnabled(cookieMgr)) { value = (cookieMgrConfig.getCookie || _getCookieValue)(name); } return value; }, del: (name: string, path?: string) => { let result = false; if (_isMgrEnabled(cookieMgr)) { // Only remove the cookie if the manager and cookie support has not been disabled result = cookieMgr.purge(name, path); } return result; }, purge: (name: string, path?: string) => { let result = false; if (areCookiesSupported(logger)) { // Setting the expiration date in the past immediately removes the cookie let values = { ["path"]: path ? path : "/", [strExpires]: "Thu, 01 Jan 1970 00:00:01 GMT" } if (!isIE()) { // Set max age to expire now values["max-age"] = "0" } let delCookie = cookieMgrConfig.delCookie || _setCookieValue; delCookie(name, _formatCookieValue(strEmpty, values)); result = true; } return result; } }; // Associated this cookie manager with the config cookieMgr[strConfigCookieMgr] = cookieMgr; return cookieMgr } /* * Helper method to tell if document.cookie object is supported by the runtime */ export function areCookiesSupported(logger?: IDiagnosticLogger): any { if (_supportsCookies === null) { _supportsCookies = false; try { let doc = _doc || {} as Document; _supportsCookies = doc[strCookie] !== undefined; } catch (e) { _throwInternal( logger, eLoggingSeverity.WARNING, _eInternalMessageId.CannotAccessCookie, "Cannot access document.cookie - " + getExceptionName(e), { exception: dumpObj(e) }); } } return _supportsCookies; } function _extractParts(theValue: string) { let values: { [key: string]: string } = {}; if (theValue && theValue.length) { let parts = strTrim(theValue).split(";"); arrForEach(parts, (thePart) => { thePart = strTrim(thePart || strEmpty); if (thePart) { let idx = thePart.indexOf("="); if (idx === -1) { values[thePart] = null; } else { values[strTrim(thePart.substring(0, idx))] = strTrim(thePart.substring(idx + 1)); } } }); } return values; } function _formatDate(theDate: Date, func: string) { if (isFunction(theDate[func])) { return theDate[func](); } return null; } function _formatCookieValue(value: string, values: any) { let cookieValue = value || strEmpty; objForEachKey(values, (name, theValue) => { cookieValue += "; " + name + (!isNullOrUndefined(theValue) ? "=" + theValue : strEmpty); }); return cookieValue; } function _getCookieValue(name: string) { let cookieValue = strEmpty; if (_doc) { let theCookie = _doc[strCookie] || strEmpty; if (_parsedCookieValue !== theCookie) { _cookieCache = _extractParts(theCookie); _parsedCookieValue = theCookie; } cookieValue = strTrim(_cookieCache[name] || strEmpty); } return cookieValue; } function _setCookieValue(name: string, cookieValue: string) { if (_doc) { _doc[strCookie] = name + "=" + cookieValue; } } export function uaDisallowsSameSiteNone(userAgent: string) { if (!isString(userAgent)) { return false; } // Cover all iOS based browsers here. This includes: // - Safari on iOS 12 for iPhone, iPod Touch, iPad // - WkWebview on iOS 12 for iPhone, iPod Touch, iPad // - Chrome on iOS 12 for iPhone, iPod Touch, iPad // All of which are broken by SameSite=None, because they use the iOS networking stack if (strContains(userAgent, "CPU iPhone OS 12") || strContains(userAgent, "iPad; CPU OS 12")) { return true; } // Cover Mac OS X based browsers that use the Mac OS networking stack. This includes: // - Safari on Mac OS X // This does not include: // - Internal browser on Mac OS X // - Chrome on Mac OS X // - Chromium on Mac OS X // Because they do not use the Mac OS networking stack. if (strContains(userAgent, "Macintosh; Intel Mac OS X 10_14") && strContains(userAgent, "Version/") && strContains(userAgent, "Safari")) { return true; } // Cover Mac OS X internal browsers that use the Mac OS networking stack. This includes: // - Internal browser on Mac OS X // This does not include: // - Safari on Mac OS X // - Chrome on Mac OS X // - Chromium on Mac OS X // Because they do not use the Mac OS networking stack. if (strContains(userAgent, "Macintosh; Intel Mac OS X 10_14") && strEndsWith(userAgent, "AppleWebKit/605.1.15 (KHTML, like Gecko)")) { return true; } // Cover Chrome 50-69, because some versions are broken by SameSite=None, and none in this range require it. // Note: this covers some pre-Chromium Edge versions, but pre-Chromim Edge does not require SameSite=None, so this is fine. // Note: this regex applies to Windows, Mac OS X, and Linux, deliberately. if (strContains(userAgent, "Chrome/5") || strContains(userAgent, "Chrome/6")) { return true; } // Unreal Engine runs Chromium 59, but does not advertise as Chrome until 4.23. Treat versions of Unreal // that don't specify their Chrome version as lacking support for SameSite=None. if (strContains(userAgent, "UnrealEngine") && !strContains(userAgent, "Chrome")) { return true; } // UCBrowser < 12.13.2 ignores Set-Cookie headers with SameSite=None // NB: this rule isn't complete - you need regex to make a complete rule. // See: https://www.chromium.org/updates/same-site/incompatible-clients if (strContains(userAgent, "UCBrowser/12") || strContains(userAgent, "UCBrowser/11")) { return true; } return false; }
the_stack
import { AfterViewChecked, AfterViewInit, ChangeDetectionStrategy, Component, ContentChildren, ElementRef, EventEmitter, Input, NgZone, OnDestroy, Output, QueryList, forwardRef, } from '@angular/core'; import { SohoAccordionHeaderComponent } from './soho-accordion-header.component'; import { SohoAccordionPaneComponent } from './soho-accordion-pane.component'; /** * Angular Wrapper for the Soho Accordion control. * * This component searches for an element, annotated with the `soho-accordion` attribute, * and then matches this component to it. * <br> * The characteristics of the component can be controlled using the set of inputs. * * The Accordion is a grouped set of collapsible panels used to navigate sections of * related content. Each panel consists of two levels: the top level identifies the * category or section header, and the second level provides the associated options. */ @Component({ selector: 'soho-accordion', templateUrl: 'soho-accordion.component.html', changeDetection: ChangeDetectionStrategy.OnPush }) export class SohoAccordionComponent implements AfterViewInit, AfterViewChecked, OnDestroy { // All headers. // eslint-disable-next-line @angular-eslint/no-forward-ref @ContentChildren(forwardRef(() => SohoAccordionHeaderComponent)) headers!: QueryList<SohoAccordionHeaderComponent>; // All panes. // eslint-disable-next-line @angular-eslint/no-forward-ref @ContentChildren(forwardRef(() => SohoAccordionPaneComponent)) panes!: QueryList<SohoAccordionPaneComponent>; // ------------------------------------------- // Options Block // ------------------------------------------- public options: SohoAccordionOptions = {}; // ------------------------------------------- // Private Member Data // ------------------------------------------- /** Reference to the jQuery selector. */ private jQueryElement!: JQuery; /** * References to the Soho control api. */ private accordion!: SohoAccordionStatic; /** * Used to call updated from the afterViewChecked lifecycle event. */ private updateRequired?: boolean; // ------------------------------------------- // Component Output // ------------------------------------------- /* eslint-disable @angular-eslint/no-output-rename */ @Output('beforeexpand') beforeexpandEvent = new EventEmitter<any>(); @Output('beforecollapse') beforecollapseEvent = new EventEmitter<any>(); @Output('beforeselect') beforeselectEvent = new EventEmitter<any>(); @Output('selected') selectedEvent = new EventEmitter<any>(); @Output('followlink') followlinkEvent = new EventEmitter<any>(); @Output('expand') expandEvent = new EventEmitter<any>(); @Output('afterexpand') afterexpandEvent = new EventEmitter<any>(); @Output('collapse') collapseEvent = new EventEmitter<any>(); @Output('aftercollapse') aftercollapseEvent = new EventEmitter<any>(); // ------------------------------------------- // Component Inputs // ------------------------------------------- /** * If an Accordion pane is open, and that pane contains sub-headers, only one * of the pane's sub-headers can be open at a time. * * Defaults to true. * * If set to true, allows only one pane of the accordion to be open at a time. */ @Input() public set allowOnePane(allowOnePane: boolean | undefined) { this.options.allowOnePane = typeof (allowOnePane) === 'boolean' && allowOnePane; if (this.accordion) { (this.accordion.settings as any).allowOnePane = this.options.allowOnePane; this.markForUpdate(); } } public get allowOnePane() { return this.options.allowOnePane; } /** * Displays a "Chevron" icon that sits off to the right-most side of a top-level accordion header. * Used in place of an Expander (+/-) if enabled. * * */ @Input() public set displayChevron(displayChevron: boolean | undefined) { this.options.displayChevron = typeof (displayChevron) === 'boolean' && displayChevron; if (this.accordion) { (this.accordion.settings as any).displayChevron = this.options.displayChevron; this.markForUpdate(); } } public get displayChevron() { return this.options.displayChevron; } /** * Changes the iconography used in accordion header expander buttons. */ @Input() public set expanderDisplay(expanderDisplay: SohoAccordionExpanderType | undefined) { this.options.expanderDisplay = expanderDisplay; if (this.accordion) { (this.accordion.settings as any).expanderDisplay = this.options.expanderDisplay; this.markForUpdate(); } } public get expanderDisplay() { return this.options.expanderDisplay; } /** * Can be set to false if routing is externally handled, otherwise * links are handled normally. * * */ @Input() public set rerouteOnLinkClick(rerouteOnLinkClick: boolean | undefined) { this.options.rerouteOnLinkClick = typeof (rerouteOnLinkClick) === 'boolean' && rerouteOnLinkClick; if (this.accordion) { (this.accordion.settings as any).rerouteOnLinkClick = this.options.rerouteOnLinkClick; this.markForUpdate(); } } public get rerouteOnLinkClick() { return this.options.rerouteOnLinkClick; } /** * Add a alert badge to the accordion header (used for App menu) */ @Input() public set notificationBadge(notificationBadge: boolean | undefined) { this.options.notificationBadge = typeof (notificationBadge) === 'boolean' && notificationBadge; if (this.accordion) { (this.accordion.settings as any).notificationBadge = this.options.notificationBadge; this.markForUpdate(); } } public get notificationBadge() { return this.options.notificationBadge; } /** * A callback function that when implemented provided a call back for "ajax loading" of tab contents on open. */ @Input() public set source(source: Function | undefined) { this.options.source = source; if (this.accordion) { (this.accordion.settings as any).source = this.options.source; this.markForUpdate(); } } public get source(): Function | undefined { return this.options.source; } /** * Display accordion with panels */ @Input() public set hasPanels(hasPanels: boolean | undefined) { this.options.hasPanels = hasPanels; if (this.accordion) { (this.accordion.settings as any).hasPanels = this.options.hasPanels; this.markForUpdate(); } } public get hasPanels(): boolean | undefined { return this.options.hasPanels; } /** * Set the color scheme to inverse */ @Input() public set inverse(inverse: boolean | undefined) { this.options.inverse = inverse; if (this.accordion) { (this.accordion.settings as any).inverse = this.options.inverse; this.markForUpdate(); } } public get inverse(): boolean | undefined { return this.options.inverse; } /** * Set the color scheme to alternate */ @Input() public set alternate(bool: boolean | undefined) { this.options.alternate = bool; if (this.accordion) { (this.accordion.settings as any).alternate = this.options.alternate; this.markForUpdate(); } } public get alternate(): boolean | undefined { return this.options.alternate; } /** * Enables tooltips for longer text that is handled with ellipsis */ @Input() public set enableTooltips(enableTooltips: boolean | undefined) { this.options.enableTooltips = enableTooltips; if (this.accordion) { (this.accordion.settings as any).enableTooltips = this.options.enableTooltips; this.markForUpdate(); } } public get enableTooltips(): boolean | undefined { return this.options.enableTooltips; } @Input() public hasSubheaderSeparators?: boolean; /** * Constructor. * * @param elementRef - the element matching the component's selector. * @param ngZone - zone access. */ constructor(private element: ElementRef, private ngZone: NgZone) { } // ------------------------------------------- // Public API // ------------------------------------------- /** * Get's the nth header from the accordion. * * @todo - how best to access the headers? * * @param index - the index of the accordion header. * @return the header at the given index. */ public getHeader(index: number): SohoAccordionHeaderComponent | undefined { if (!this.headers) { return undefined; } return this.headers.toArray()[index]; } /** * Expand the given Panel on the Accordion. * * @param header &nbsp;-&nbsp; the header component */ public expand(header: SohoAccordionHeaderComponent | string): void { if (this.accordion) { this.ngZone.runOutsideAngular(() => { return this.accordion.expand(typeof header === 'string' ? header : header['jQueryElement']); }); } } /** * Collapse the given Panel on the Accordion. * * @param header &nbsp;-&nbsp; the jquery header element */ public collapse(header: SohoAccordionHeaderComponent | string): void { if (this.accordion) { this.ngZone.runOutsideAngular(() => { return this.accordion.collapse(typeof header === 'string' ? header : header['jQueryElement']); }); } } /** * Expands all accordion headers, if possible. */ public expandAll(): void { if (this.accordion) { this.ngZone.runOutsideAngular(() => this.accordion.expandAll()); } } /** * Collapses all the expanded panels. * * */ public collapseAll(): void { if (this.accordion) { this.ngZone.runOutsideAngular(() => this.accordion.collapseAll()); } } /** * Disables the control. */ public disable() { if (this.accordion) { this.ngZone.runOutsideAngular(() => this.accordion.disable()); } } /** * Enables the control. */ public enable() { if (this.accordion) { this.ngZone.runOutsideAngular(() => this.accordion.enable()); } } /** * Returns true if the given header is currently disabled or the whole accordion * is disabled; otherwise false. * * @param header the accordion header panel to check. */ public isDisabled(header: SohoAccordionHeaderComponent): boolean { if (this.accordion) { return this.ngZone.runOutsideAngular(() => this.accordion.isDisabled(header.jQueryElement)); } return false; } /** * Returns true if the given header is currently expanded; otherwise * false. * * @param header the accordion header panel to check. */ public isExpanded(header: SohoAccordionHeaderComponent): boolean { if (this.accordion) { return this.ngZone.runOutsideAngular(() => this.accordion.isExpanded(header.jQueryElement)); } return false; } /** * Toggle the given Panel on the Accordion between expanded and collapsed * * @param header &nbsp;-&nbsp; the jquery header element */ public toggle(header: SohoAccordionHeaderComponent): void { if (this.accordion) { this.ngZone.runOutsideAngular(() => this.accordion.toggle(header.jQueryElement)); } } /** * Call to notify the accordion about any dom changes */ public updated(headers?: JQuery[], settings?: SohoAccordionOptions): void { if (settings) { this.options = Soho.utils.mergeSettings((this.element as any)[0], settings, this.options); } if (this.accordion) { this.ngZone.runOutsideAngular(() => this.accordion.updated(headers, this.options)); } } // ------------------------------------------ // Lifecycle Events // ------------------------------------------ ngAfterViewInit() { this.ngZone.runOutsideAngular(() => { // Wrap the element in a jQuery selector. this.jQueryElement = jQuery(this.element.nativeElement.childNodes[0]); // Initialise the event handlers. this.jQueryElement .on('beforeexpand', (event: SohoAccordionEvent, anchor) => this.ngZone.run(() => { event.anchor = anchor; this.beforeexpandEvent.emit(event); })) .on('beforecollapse', (event: SohoAccordionEvent, anchor) => this.ngZone.run(() => { event.anchor = anchor; this.beforecollapseEvent.emit(event); })) .on('beforeselect', (event: SohoAccordionEvent, anchor) => this.ngZone.run(() => { event.anchor = anchor; this.beforeselectEvent.emit(event); })) .on('selected', (event: SohoAccordionEvent, anchor) => this.ngZone.run(() => { event.anchor = anchor; this.selectedEvent.emit(event); })) .on('followlink', (event: SohoAccordionEvent, anchor) => this.ngZone.run(() => { event.anchor = anchor; this.followlinkEvent.emit(event); })) .on('expand', (event: SohoAccordionEvent, anchor) => this.ngZone.run(() => { event.anchor = anchor; this.expandEvent.emit(event); })) .on('afterexpand', (event: SohoAccordionEvent, anchor) => this.ngZone.run(() => { event.anchor = anchor; this.afterexpandEvent.emit(event); })) .on('collapse', (event: SohoAccordionEvent, anchor) => this.ngZone.run(() => { event.anchor = anchor; this.collapseEvent.emit(event); })) .on('aftercollapse', (event: SohoAccordionEvent, anchor) => this.ngZone.run(() => { event.anchor = anchor; this.aftercollapseEvent.emit(event); })); // Initialise the SohoXi Control this.jQueryElement.accordion(this.options); // Once the control is initialised, extract the control // plug-in from the element. The element name is // defined by the plug-in, but in this case it is 'accordion'. this.accordion = this.jQueryElement.data('accordion'); }); } ngAfterViewChecked() { if (this.updateRequired) { this.updated(); this.updateRequired = false; } } /** * Destructor. */ ngOnDestroy(): void { // call outside the angular zone so change detection isn't triggered by the soho component. this.ngZone.runOutsideAngular(() => { if (this.jQueryElement) { this.jQueryElement.off(); } if (this.accordion) { this.accordion?.destroy(); } }); } private markForUpdate(): void { this.updateRequired = true; } }
the_stack
import { test } from "@siteimprove/alfa-test"; import { Device } from "@siteimprove/alfa-device"; import { Node } from "../src"; const device = Device.standard(); test(`.from() constructs an accessible node from an element`, (t) => { const element = <button>Hello world</button>; t.deepEqual(Node.from(element, device).toJSON(), { type: "element", node: "/button[1]", role: "button", name: "Hello world", attributes: [], children: [ { type: "text", node: "/button[1]/text()[1]", name: "Hello world", children: [], }, ], }); }); test(`.from() gives precedence to aria-owns references`, (t) => { const header = ( <header aria-owns="bar"> <button id="foo" /> </header> ); const footer = ( <footer> <input id="bar" /> </footer> ); <div> {header} {footer} </div>; t.deepEqual(Node.from(header, device).toJSON(), { type: "element", node: "/div[1]/header[1]", role: "banner", name: null, attributes: [ { name: "aria-owns", value: "bar", }, ], children: [ { type: "element", node: "/div[1]/header[1]/button[1]", role: "button", name: null, attributes: [], children: [], }, { type: "element", node: "/div[1]/footer[1]/input[1]", role: "textbox", name: null, attributes: [ { name: "aria-checked", value: "false", }, ], children: [], }, ], }); t.deepEqual(Node.from(footer, device).toJSON(), { type: "element", node: "/div[1]/footer[1]", role: "contentinfo", name: null, attributes: [], children: [], }); }); test(`.from() correctly handles conflicting aria-owns claims`, (t) => { const header = ( <header aria-owns="bar"> <button id="foo" /> </header> ); const footer = ( <footer aria-owns="bar"> <input id="bar" /> </footer> ); <div> {header} {footer} </div>; t.deepEqual(Node.from(header, device).toJSON(), { type: "element", node: "/div[1]/header[1]", role: "banner", name: null, attributes: [ { name: "aria-owns", value: "bar", }, ], children: [ { type: "element", node: "/div[1]/header[1]/button[1]", role: "button", name: null, attributes: [], children: [], }, { type: "element", node: "/div[1]/footer[1]/input[1]", role: "textbox", name: null, attributes: [ { name: "aria-checked", value: "false", }, ], children: [], }, ], }); t.deepEqual(Node.from(footer, device).toJSON(), { type: "element", node: "/div[1]/footer[1]", role: "contentinfo", name: null, attributes: [ { name: "aria-owns", value: "bar", }, ], children: [], }); }); test(`.from() correctly handles reordered aria-owns references`, (t) => { const header = ( <header aria-owns="bar foo"> <button id="foo" /> </header> ); <div> {header} <input id="bar" /> </div>; t.deepEqual(Node.from(header, device).toJSON(), { type: "element", node: "/div[1]/header[1]", role: "banner", name: null, attributes: [ { name: "aria-owns", value: "bar foo", }, ], children: [ { type: "element", node: "/div[1]/input[1]", role: "textbox", name: null, attributes: [ { name: "aria-checked", value: "false", }, ], children: [], }, { type: "element", node: "/div[1]/header[1]/button[1]", role: "button", name: null, attributes: [], children: [], }, ], }); }); test(`.from() correctly handles self-referential aria-owns references`, (t) => { const div = <div id="foo" aria-owns="foo" />; t.deepEqual(Node.from(div, device).toJSON(), { type: "element", node: "/div[1]", role: null, name: null, attributes: [ { name: "aria-owns", value: "foo", }, ], children: [], }); }); test(`.from() correctly handles circular aria-owns references between siblings`, (t) => { const foo = <div id="foo" aria-owns="bar" />; const bar = <div id="bar" aria-owns="foo" />; <div> {foo} {bar} </div>; t.deepEqual(Node.from(foo, device).toJSON(), { type: "element", node: "/div[1]/div[1]", role: null, name: null, attributes: [ { name: "aria-owns", value: "bar", }, ], children: [ { type: "element", node: "/div[1]/div[2]", role: null, name: null, attributes: [ { name: "aria-owns", value: "foo", }, ], children: [], }, ], }); t.deepEqual(Node.from(bar, device).toJSON(), { type: "element", node: "/div[1]/div[2]", role: null, name: null, attributes: [ { name: "aria-owns", value: "foo", }, ], children: [], }); }); test(`.from() correctly handles circular aria-owns references between ancestors and descendants`, (t) => { const foo = <div id="foo" aria-owns="bar" />; const bar = <div id="bar">{foo}</div>; t.deepEqual(Node.from(foo, device).toJSON(), { type: "element", node: "/div[1]/div[1]", role: null, name: null, attributes: [ { name: "aria-owns", value: "bar", }, ], children: [], }); t.deepEqual(Node.from(bar, device).toJSON(), { type: "container", node: "/div[1]", children: [ { type: "element", node: "/div[1]/div[1]", role: null, name: null, attributes: [ { name: "aria-owns", value: "bar", }, ], children: [], }, ], }); }); test(".from() exposes elements if they have a role", (t) => { const foo = <button />; t.deepEqual(Node.from(foo, device).toJSON(), { type: "element", node: "/button[1]", role: "button", name: null, attributes: [], children: [], }); }); test(".from() exposes elements if they have ARIA attributes", (t) => { const foo = <div aria-label="foo" />; t.deepEqual(Node.from(foo, device).toJSON(), { type: "element", node: "/div[1]", role: null, name: "foo", attributes: [ { name: "aria-label", value: "foo", }, ], children: [], }); }); test(".from() exposes elements if they have a tabindex", (t) => { const foo = <div tabindex={0} />; t.deepEqual(Node.from(foo, device).toJSON(), { type: "element", node: "/div[1]", role: null, name: null, attributes: [], children: [], }); const iframe = <iframe />; // Focusable by default, and no role t.deepEqual(Node.from(iframe, device).toJSON(), { type: "element", node: "/iframe[1]", role: null, name: null, attributes: [], children: [], }); }); test(`.from() does not expose elements that have no role, ARIA attributes, nor tabindex`, (t) => { const foo = <div>Hello world</div>; t.deepEqual(Node.from(foo, device).toJSON(), { type: "container", node: "/div[1]", children: [ { type: "text", node: "/div[1]/text()[1]", name: "Hello world", children: [], }, ], }); }); test(`.from() does not expose text nodes of a parent element with \`visibility: hidden\``, (t) => { const foo = <div style={{ visibility: "hidden" }}>Hello world</div>; t.deepEqual(Node.from(foo, device).toJSON(), { type: "container", node: "/div[1]", children: [ { type: "inert", node: "/div[1]/text()[1]", children: [], }, ], }); }); test(`.from() exposes implicitly required children of a presentational element with an inherited presentational role`, (t) => { const ul = ( <ul role="presentation"> <li /> </ul> ); t.deepEqual(Node.from(ul, device).toJSON(), { type: "container", node: "/ul[1]", children: [ { type: "container", node: "/ul[1]/li[1]", children: [], }, ], }); }); test(`.from() doesn't inherit presentational roles into explicitly required children of a presentational element`, (t) => { const ul = ( <ul role="presentation"> <li role="listitem" /> </ul> ); t.deepEqual(Node.from(ul, device).toJSON(), { type: "container", node: "/ul[1]", children: [ { type: "element", node: "/ul[1]/li[1]", role: "listitem", name: null, attributes: [ { name: "aria-setsize", value: "1" }, { name: "aria-posinset", value: "1" }, ], children: [], }, ], }); }); test(`.from() doesn't inherit presentational roles into children of implicitly required children of a presentational element`, (t) => { const ul = ( <ul role="presentation"> <li> { // This element should _not_ inherit a presentational role as the // parent <li> element has no required children. } <button /> </li> </ul> ); t.deepEqual(Node.from(ul, device).toJSON(), { type: "container", node: "/ul[1]", children: [ { type: "container", node: "/ul[1]/li[1]", children: [ { type: "element", node: "/ul[1]/li[1]/button[1]", role: "button", name: null, attributes: [], children: [], }, ], }, ], }); }); test(`.from() doesn't expose children of elements with roles that designate their children as presentational`, (t) => { const button = ( <button> <img src="#" /> </button> ); t.deepEqual(Node.from(button, device).toJSON(), { type: "element", node: "/button[1]", role: "button", name: null, attributes: [], children: [ { type: "container", node: "/button[1]/img[1]", children: [], }, ], }); }); test(`.from() correctly sets \`aria-setsize\` and \`aria-posinset\``, (t) => { const items = [ <li>First</li>, <li>Second</li>, <li>Third</li>, <li>Fourth</li>, ]; <ul>{items}</ul>; for (let i = 0; i < items.length; i++) { const node = Node.from(items[i], device); t.equal(node.attribute("aria-setsize").get().value, `${items.length}`); t.equal(node.attribute("aria-posinset").get().value, `${i + 1}`); } }); test(`.from() behaves when encountering an element with global properties where the element should not be named by its subtree`, (t) => { const div = ( <div aria-hidden="false"> <label> Foo <input /> </label> </div> ); t.deepEqual(Node.from(div, device).toJSON(), { type: "element", node: "/div[1]", role: null, name: null, attributes: [ { name: "aria-hidden", value: "false", }, ], children: [ { type: "container", node: "/div[1]/label[1]", children: [ { type: "text", node: "/div[1]/label[1]/text()[1]", name: "Foo ", children: [], }, { type: "element", node: "/div[1]/label[1]/input[1]", role: "textbox", name: "Foo", attributes: [ { name: "aria-checked", value: "false", }, ], children: [], }, ], }, ], }); });
the_stack
"use strict"; import * as del from "del"; import * as fs from "fs"; import * as path from "path"; import * as url from "url"; import * as tl from "azure-pipelines-task-lib/task"; import * as tr from "azure-pipelines-task-lib/toolrunner"; import * as imageUtils from "./containerimageutils"; import AuthenticationToken from "./registryauthenticationprovider/registryauthenticationtoken" import * as fileutils from "./fileutils"; import * as os from "os"; tl.setResourcePath(path.join(__dirname, 'module.json'), true); export default class ContainerConnection { private dockerPath: string; protected hostUrl: string; protected certsDir: string; private caPath: string; private certPath: string; private keyPath: string; private registryAuth: { [key: string]: string }; private configurationDirPath: string; private oldDockerConfigContent: string; constructor(isDockerRequired: boolean = true) { this.dockerPath = tl.which("docker", isDockerRequired); } public createCommand(): tr.ToolRunner { var command = tl.tool(this.dockerPath); if (this.hostUrl) { command.arg(["-H", this.hostUrl]); command.arg("--tls"); command.arg("--tlscacert='" + this.caPath + "'"); command.arg("--tlscert='" + this.certPath + "'"); command.arg("--tlskey='" + this.keyPath + "'"); } return command; } public execCommand(command: tr.ToolRunner, options?: tr.IExecOptions) { let errlines = []; let dockerHostVar = tl.getVariable("DOCKER_HOST"); if (dockerHostVar) { tl.debug(tl.loc('ConnectingToDockerHost', dockerHostVar)); } command.on("errline", line => { errlines.push(line); }); return command.exec(options).fail(error => { if (dockerHostVar) { tl.warning(tl.loc('DockerHostVariableWarning', dockerHostVar)); } errlines.forEach(line => tl.error(line)); throw error; }); } public open(hostEndpoint?: string, authenticationToken?: AuthenticationToken, multipleLoginSupported?: boolean, doNotAddAuthToConfig?: boolean): void { this.openHostEndPoint(hostEndpoint); this.openRegistryEndpoint(authenticationToken, multipleLoginSupported, doNotAddAuthToConfig); } public getQualifiedImageNameIfRequired(imageName: string) { if (!imageUtils.hasRegistryComponent(imageName)) { imageName = this.getQualifiedImageName(imageName); } return imageName; } public getQualifiedImageName(repository: string, enforceDockerNamingConvention?: boolean): string { let imageName = repository ? repository : ""; if (repository && this.registryAuth) { imageName = this.prefixRegistryIfRequired(this.registryAuth["registry"], repository); } return enforceDockerNamingConvention ? imageUtils.generateValidImageName(imageName) : imageName; } public getQualifiedImageNamesFromConfig(repository: string, enforceDockerNamingConvention?: boolean) { let imageNames: string[] = []; if (repository) { let regUrls = this.getRegistryUrlsFromDockerConfig(); if (regUrls && regUrls.length > 0) { regUrls.forEach(regUrl => { let imageName = this.prefixRegistryIfRequired(regUrl, repository); if (enforceDockerNamingConvention) { imageName = imageUtils.generateValidImageName(imageName); } imageNames.push(imageName); }); } else { // in case there is no login information found and a repository is specified, the intention // might be to tag the image to refer locally. let imageName = repository; if (enforceDockerNamingConvention) { imageName = imageUtils.generateValidImageName(imageName); } imageNames.push(imageName); } } return imageNames; } public close(multipleLoginSupported?: boolean, command?: string): void { if (multipleLoginSupported) { if (this.isLogoutRequired(command)) { this.logout(); } } else { if (this.configurationDirPath && fs.existsSync(this.configurationDirPath)) { del.sync(this.configurationDirPath, {force: true}); } if (this.certsDir && fs.existsSync(this.certsDir)) { del.sync(this.certsDir); } } } public setDockerConfigEnvVariable() { if (this.configurationDirPath && fs.existsSync(this.configurationDirPath)) { tl.setVariable("DOCKER_CONFIG", this.configurationDirPath); } else { tl.error(tl.loc('DockerRegistryNotFound')); throw new Error(tl.loc('DockerRegistryNotFound')); } } public unsetDockerConfigEnvVariable() { var dockerConfigPath = tl.getVariable("DOCKER_CONFIG"); if (dockerConfigPath) { this.unsetEnvironmentVariable(); del.sync(dockerConfigPath, {force: true}); } } private logout() { // If registry info is present, remove auth for only that registry. (This can happen for any command - build, push, logout etc.) // Else, remove all auth data. (This would happen only in case of logout command. For other commands, logout is not called.) let registry = this.registryAuth ? this.registryAuth["registry"] : ""; if (registry) { tl.debug(tl.loc('LoggingOutFromRegistry', registry)); let existingConfigurationFile = this.getExistingDockerConfigFilePath(); if (existingConfigurationFile) { if (this.oldDockerConfigContent) { // restore the old docker config, cached in connection.open() tl.debug(tl.loc('RestoringOldLoginAuth', registry)); this.writeDockerConfigJson(this.oldDockerConfigContent, existingConfigurationFile); } else { let existingConfigJson = this.getDockerConfigJson(existingConfigurationFile); if (existingConfigJson && existingConfigJson.auths && existingConfigJson.auths[registry]) { if (Object.keys(existingConfigJson.auths).length > 1) { // if the config contains other auths, then delete only the auth entry for the registry tl.debug(tl.loc('FoundLoginsForOtherRegistries', registry)); delete existingConfigJson.auths[registry]; let dockerConfigContent = JSON.stringify(existingConfigJson); tl.debug(tl.loc('DeletingAuthDataFromDockerConfig', registry, dockerConfigContent)); this.writeDockerConfigJson(dockerConfigContent, existingConfigurationFile); } else { // if no other auth data is present, delete the config file and unset the DOCKER_CONFIG variable tl.debug(tl.loc('DeletingDockerConfigDirectory', existingConfigurationFile)); this.removeConfigDirAndUnsetEnvVariable(); } } else { // trying to logout from a registry where no login was done. Nothing to be done here. tl.debug(tl.loc('RegistryAuthNotPresentInConfig', registry)); } } } else { // should not come to this in a good case, since when registry is provided, we are adding docker config // to a temp directory and setting DOCKER_CONFIG variable to its path. tl.debug(tl.loc('CouldNotFindDockerConfig', this.configurationDirPath)); this.unsetEnvironmentVariable(); } } // unset the docker config env variable, and delete the docker config file (if present) else { tl.debug(tl.loc('LoggingOutWithNoRegistrySpecified')); this.removeConfigDirAndUnsetEnvVariable(); } } private removeConfigDirAndUnsetEnvVariable(): void { let dockerConfigDirPath = tl.getVariable("DOCKER_CONFIG"); if (dockerConfigDirPath && this.isPathInTempDirectory(dockerConfigDirPath) && fs.existsSync(dockerConfigDirPath)) { tl.debug(tl.loc('DeletingDockerConfigDirectory', dockerConfigDirPath)); del.sync(dockerConfigDirPath, {force: true}); } this.unsetEnvironmentVariable(); } private unsetEnvironmentVariable(): void { tl.setVariable("DOCKER_CONFIG", ""); } private isLogoutRequired(command: string): boolean { return command === "logout" || (this.registryAuth && !!this.registryAuth["registry"]); } private openHostEndPoint(hostEndpoint?: string): void { if (hostEndpoint) { this.hostUrl = tl.getEndpointUrl(hostEndpoint, false); if (this.hostUrl.charAt(this.hostUrl.length - 1) == "/") { this.hostUrl = this.hostUrl.substring(0, this.hostUrl.length - 1); } this.certsDir = path.join("", ".dockercerts"); if (!fs.existsSync(this.certsDir)) { fs.mkdirSync(this.certsDir); } var authDetails = tl.getEndpointAuthorization(hostEndpoint, false).parameters; this.caPath = path.join(this.certsDir, "ca.pem"); fs.writeFileSync(this.caPath, authDetails["cacert"]); this.certPath = path.join(this.certsDir, "cert.pem"); fs.writeFileSync(this.certPath, authDetails["cert"]); this.keyPath = path.join(this.certsDir, "key.pem"); fs.writeFileSync(this.keyPath, authDetails["key"]); } } protected openRegistryEndpoint(authenticationToken?: AuthenticationToken, multipleLoginSupported?: boolean, doNotAddAuthToConfig?: boolean): void { this.oldDockerConfigContent = null; if (authenticationToken) { this.registryAuth = {}; this.registryAuth["username"] = authenticationToken.getUsername(); this.registryAuth["password"] = authenticationToken.getPassword(); this.registryAuth["registry"] = authenticationToken.getLoginServerUrl(); // don't add auth data to config file if doNotAddAuthToConfig is true. // In this case we only need this.registryAuth to be populated correctly (to logout from this particular registry when close() is called) but we don't intend to login. if (this.registryAuth && !doNotAddAuthToConfig) { let existingConfigurationFile = this.getExistingDockerConfigFilePath(); if (multipleLoginSupported && existingConfigurationFile) { let existingConfigJson = this.getDockerConfigJson(existingConfigurationFile); if (existingConfigJson && existingConfigJson.auths) { let newAuth = authenticationToken.getDockerAuth(); let newAuthJson = JSON.parse(newAuth); // Think of json object as a dictionary and authJson looks like // "auths": { // "aj.azurecr.io": { // "auth": "***", // "email": "***" // } // } // key will be aj.azurecr.io // for (let registryName in newAuthJson) { // If auth is already present for the same registry, then cache it so that we can // preserve it back on logout. if (existingConfigJson.auths[registryName]) { this.oldDockerConfigContent = JSON.stringify(existingConfigJson); tl.debug(tl.loc('OldDockerConfigContent', this.oldDockerConfigContent)); } existingConfigJson.auths[registryName] = newAuthJson[registryName]; tl.debug(tl.loc('AddingNewAuthToExistingConfig', registryName)); } let dockerConfigContent = JSON.stringify(existingConfigJson); this.writeDockerConfigJson(dockerConfigContent, existingConfigurationFile); } } else { var json = authenticationToken.getDockerConfig(); this.writeDockerConfigJson(json); } } } } private getExistingDockerConfigFilePath(): string { this.configurationDirPath = tl.getVariable("DOCKER_CONFIG"); let configurationFilePath = this.configurationDirPath ? path.join(this.configurationDirPath, "config.json") : ""; if (this.configurationDirPath && this.isPathInTempDirectory(configurationFilePath) && fs.existsSync(configurationFilePath)) { return configurationFilePath; } return null; } private getDockerConfigJson(configurationFilePath : string): any { let configJson: any; let dockerConfig = fs.readFileSync(configurationFilePath, "utf-8"); tl.debug(tl.loc('FoundDockerConfigStoredInTempPath', configurationFilePath, dockerConfig)); try { configJson = JSON.parse(dockerConfig); } catch(err) { let errorMessage = tl.loc('ErrorParsingDockerConfig', err); throw new Error(errorMessage); } return configJson; } private writeDockerConfigJson(dockerConfigContent: string, configurationFilePath?: string): void { if (!configurationFilePath){ this.configurationDirPath = this.getDockerConfigDirPath(); process.env["DOCKER_CONFIG"] = this.configurationDirPath; configurationFilePath = path.join(this.configurationDirPath, "config.json"); } tl.debug(tl.loc('WritingDockerConfigToTempFile', configurationFilePath, dockerConfigContent)); if(fileutils.writeFileSync(configurationFilePath, dockerConfigContent) == 0) { tl.error(tl.loc('NoDataWrittenOnFile', configurationFilePath)); throw new Error(tl.loc('NoDataWrittenOnFile', configurationFilePath)); } } private getDockerConfigDirPath(): string { var configDir = path.join(this.getTempDirectory(), "DockerConfig_"+Date.now()); this.ensureDirExists(configDir); return configDir; } private ensureDirExists(dirPath : string) : void { if (!fs.existsSync(dirPath)) { fs.mkdirSync(dirPath); var privateKeyDir= path.join(dirPath, "trust", "private"); tl.mkdirP(privateKeyDir); } } private getTempDirectory(): string { return tl.getVariable('agent.tempDirectory') || os.tmpdir(); } private getRegistryUrlsFromDockerConfig(): string[] { let regUrls: string[] = []; let existingConfigurationFile = this.getExistingDockerConfigFilePath(); if (existingConfigurationFile) { let existingConfigJson = this.getDockerConfigJson(existingConfigurationFile); if (existingConfigJson && existingConfigJson.auths) { regUrls = Object.keys(existingConfigJson.auths); } else { tl.debug(tl.loc('NoAuthInfoFoundInDockerConfig')); } } else { tl.debug(tl.loc('CouldNotFindDockerConfig', this.configurationDirPath)); } return regUrls; } private isPathInTempDirectory(path): boolean { let tempDir = this.getTempDirectory(); let result = path && path.startsWith(tempDir); if (!result) { tl.debug(tl.loc('PathIsNotInTempDirectory', path, tempDir)); } return result; } private prefixRegistryIfRequired(registry: string, repository: string): string { let imageName = repository; if (registry) { let regUrl = url.parse(registry); let hostname = !regUrl.slashes ? regUrl.href : regUrl.host; // For docker hub, repository name is the qualified image name. Prepend hostname if the registry is not docker hub. if (hostname.toLowerCase() !== "index.docker.io") { imageName = hostname + "/" + repository; } } return imageName; } }
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * Manages a Key Vault Certificate. * * ## Example Usage * ### Importing a PFX * * > **Note:** this example assumed the PFX file is located in the same directory at `certificate-to-import.pfx`. * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as azure from "@pulumi/azure"; * import * from "fs"; * * const current = azure.core.getClientConfig({}); * const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"}); * const exampleKeyVault = new azure.keyvault.KeyVault("exampleKeyVault", { * location: exampleResourceGroup.location, * resourceGroupName: exampleResourceGroup.name, * tenantId: current.then(current => current.tenantId), * skuName: "premium", * accessPolicies: [{ * tenantId: current.then(current => current.tenantId), * objectId: current.then(current => current.objectId), * certificatePermissions: [ * "create", * "delete", * "deleteissuers", * "get", * "getissuers", * "import", * "list", * "listissuers", * "managecontacts", * "manageissuers", * "setissuers", * "update", * ], * keyPermissions: [ * "backup", * "create", * "decrypt", * "delete", * "encrypt", * "get", * "import", * "list", * "purge", * "recover", * "restore", * "sign", * "unwrapKey", * "update", * "verify", * "wrapKey", * ], * secretPermissions: [ * "backup", * "delete", * "get", * "list", * "purge", * "recover", * "restore", * "set", * ], * }], * }); * const exampleCertificate = new azure.keyvault.Certificate("exampleCertificate", { * keyVaultId: exampleKeyVault.id, * certificate: { * contents: Buffer.from(fs.readFileSync("certificate-to-import.pfx"), 'binary').toString('base64'), * password: "", * }, * }); * ``` * ### Generating a new certificate * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as azure from "@pulumi/azure"; * * const current = azure.core.getClientConfig({}); * const exampleResourceGroup = new azure.core.ResourceGroup("exampleResourceGroup", {location: "West Europe"}); * const exampleKeyVault = new azure.keyvault.KeyVault("exampleKeyVault", { * location: exampleResourceGroup.location, * resourceGroupName: exampleResourceGroup.name, * tenantId: current.then(current => current.tenantId), * skuName: "standard", * softDeleteRetentionDays: 7, * accessPolicies: [{ * tenantId: current.then(current => current.tenantId), * objectId: current.then(current => current.objectId), * certificatePermissions: [ * "create", * "delete", * "deleteissuers", * "get", * "getissuers", * "import", * "list", * "listissuers", * "managecontacts", * "manageissuers", * "purge", * "setissuers", * "update", * ], * keyPermissions: [ * "backup", * "create", * "decrypt", * "delete", * "encrypt", * "get", * "import", * "list", * "purge", * "recover", * "restore", * "sign", * "unwrapKey", * "update", * "verify", * "wrapKey", * ], * secretPermissions: [ * "backup", * "delete", * "get", * "list", * "purge", * "recover", * "restore", * "set", * ], * }], * }); * const exampleCertificate = new azure.keyvault.Certificate("exampleCertificate", { * keyVaultId: exampleKeyVault.id, * certificatePolicy: { * issuerParameters: { * name: "Self", * }, * keyProperties: { * exportable: true, * keySize: 2048, * keyType: "RSA", * reuseKey: true, * }, * lifetimeActions: [{ * action: { * actionType: "AutoRenew", * }, * trigger: { * daysBeforeExpiry: 30, * }, * }], * secretProperties: { * contentType: "application/x-pkcs12", * }, * x509CertificateProperties: { * extendedKeyUsages: ["1.3.6.1.5.5.7.3.1"], * keyUsages: [ * "cRLSign", * "dataEncipherment", * "digitalSignature", * "keyAgreement", * "keyCertSign", * "keyEncipherment", * ], * subjectAlternativeNames: { * dnsNames: [ * "internal.contoso.com", * "domain.hello.world", * ], * }, * subject: "CN=hello-world", * validityInMonths: 12, * }, * }, * }); * ``` * * ## Import * * Key Vault Certificates can be imported using the `resource id`, e.g. * * ```sh * $ pulumi import azure:keyvault/certifiate:Certifiate example "https://example-keyvault.vault.azure.net/certificates/example/fdf067c93bbb4b22bff4d8b7a9a56217" * ``` * * @deprecated azure.keyvault.Certifiate has been deprecated in favor of azure.keyvault.Certificate */ export class Certifiate extends pulumi.CustomResource { /** * Get an existing Certifiate 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?: CertifiateState, opts?: pulumi.CustomResourceOptions): Certifiate { pulumi.log.warn("Certifiate is deprecated: azure.keyvault.Certifiate has been deprecated in favor of azure.keyvault.Certificate") return new Certifiate(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'azure:keyvault/certifiate:Certifiate'; /** * Returns true if the given object is an instance of Certifiate. 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 Certifiate { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === Certifiate.__pulumiType; } /** * A `certificate` block as defined below, used to Import an existing certificate. */ public readonly certificate!: pulumi.Output<outputs.keyvault.CertifiateCertificate | undefined>; /** * A `certificateAttribute` block as defined below. */ public /*out*/ readonly certificateAttributes!: pulumi.Output<outputs.keyvault.CertifiateCertificateAttribute[]>; /** * The raw Key Vault Certificate data represented as a hexadecimal string. */ public /*out*/ readonly certificateData!: pulumi.Output<string>; /** * The Base64 encoded Key Vault Certificate data. */ public /*out*/ readonly certificateDataBase64!: pulumi.Output<string>; /** * A `certificatePolicy` block as defined below. */ public readonly certificatePolicy!: pulumi.Output<outputs.keyvault.CertifiateCertificatePolicy>; /** * The ID of the Key Vault where the Certificate should be created. */ public readonly keyVaultId!: pulumi.Output<string>; /** * Specifies the name of the Key Vault Certificate. Changing this forces a new resource to be created. */ public readonly name!: pulumi.Output<string>; /** * The ID of the associated Key Vault Secret. */ public /*out*/ readonly secretId!: pulumi.Output<string>; /** * A mapping of tags to assign to the resource. */ public readonly tags!: pulumi.Output<{[key: string]: string} | undefined>; /** * The X509 Thumbprint of the Key Vault Certificate represented as a hexadecimal string. */ public /*out*/ readonly thumbprint!: pulumi.Output<string>; /** * The current version of the Key Vault Certificate. */ public /*out*/ readonly version!: pulumi.Output<string>; /** * The Base ID of the Key Vault Certificate. */ public /*out*/ readonly versionlessId!: pulumi.Output<string>; /** * The Base ID of the Key Vault Secret. */ public /*out*/ readonly versionlessSecretId!: pulumi.Output<string>; /** * Create a Certifiate 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. */ /** @deprecated azure.keyvault.Certifiate has been deprecated in favor of azure.keyvault.Certificate */ constructor(name: string, args: CertifiateArgs, opts?: pulumi.CustomResourceOptions) /** @deprecated azure.keyvault.Certifiate has been deprecated in favor of azure.keyvault.Certificate */ constructor(name: string, argsOrState?: CertifiateArgs | CertifiateState, opts?: pulumi.CustomResourceOptions) { pulumi.log.warn("Certifiate is deprecated: azure.keyvault.Certifiate has been deprecated in favor of azure.keyvault.Certificate") let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as CertifiateState | undefined; inputs["certificate"] = state ? state.certificate : undefined; inputs["certificateAttributes"] = state ? state.certificateAttributes : undefined; inputs["certificateData"] = state ? state.certificateData : undefined; inputs["certificateDataBase64"] = state ? state.certificateDataBase64 : undefined; inputs["certificatePolicy"] = state ? state.certificatePolicy : undefined; inputs["keyVaultId"] = state ? state.keyVaultId : undefined; inputs["name"] = state ? state.name : undefined; inputs["secretId"] = state ? state.secretId : undefined; inputs["tags"] = state ? state.tags : undefined; inputs["thumbprint"] = state ? state.thumbprint : undefined; inputs["version"] = state ? state.version : undefined; inputs["versionlessId"] = state ? state.versionlessId : undefined; inputs["versionlessSecretId"] = state ? state.versionlessSecretId : undefined; } else { const args = argsOrState as CertifiateArgs | undefined; if ((!args || args.keyVaultId === undefined) && !opts.urn) { throw new Error("Missing required property 'keyVaultId'"); } inputs["certificate"] = args ? args.certificate : undefined; inputs["certificatePolicy"] = args ? args.certificatePolicy : undefined; inputs["keyVaultId"] = args ? args.keyVaultId : undefined; inputs["name"] = args ? args.name : undefined; inputs["tags"] = args ? args.tags : undefined; inputs["certificateAttributes"] = undefined /*out*/; inputs["certificateData"] = undefined /*out*/; inputs["certificateDataBase64"] = undefined /*out*/; inputs["secretId"] = undefined /*out*/; inputs["thumbprint"] = undefined /*out*/; inputs["version"] = undefined /*out*/; inputs["versionlessId"] = undefined /*out*/; inputs["versionlessSecretId"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(Certifiate.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering Certifiate resources. */ export interface CertifiateState { /** * A `certificate` block as defined below, used to Import an existing certificate. */ certificate?: pulumi.Input<inputs.keyvault.CertifiateCertificate>; /** * A `certificateAttribute` block as defined below. */ certificateAttributes?: pulumi.Input<pulumi.Input<inputs.keyvault.CertifiateCertificateAttribute>[]>; /** * The raw Key Vault Certificate data represented as a hexadecimal string. */ certificateData?: pulumi.Input<string>; /** * The Base64 encoded Key Vault Certificate data. */ certificateDataBase64?: pulumi.Input<string>; /** * A `certificatePolicy` block as defined below. */ certificatePolicy?: pulumi.Input<inputs.keyvault.CertifiateCertificatePolicy>; /** * The ID of the Key Vault where the Certificate should be created. */ keyVaultId?: pulumi.Input<string>; /** * Specifies the name of the Key Vault Certificate. Changing this forces a new resource to be created. */ name?: pulumi.Input<string>; /** * The ID of the associated Key Vault Secret. */ secretId?: pulumi.Input<string>; /** * A mapping of tags to assign to the resource. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; /** * The X509 Thumbprint of the Key Vault Certificate represented as a hexadecimal string. */ thumbprint?: pulumi.Input<string>; /** * The current version of the Key Vault Certificate. */ version?: pulumi.Input<string>; /** * The Base ID of the Key Vault Certificate. */ versionlessId?: pulumi.Input<string>; /** * The Base ID of the Key Vault Secret. */ versionlessSecretId?: pulumi.Input<string>; } /** * The set of arguments for constructing a Certifiate resource. */ export interface CertifiateArgs { /** * A `certificate` block as defined below, used to Import an existing certificate. */ certificate?: pulumi.Input<inputs.keyvault.CertifiateCertificate>; /** * A `certificatePolicy` block as defined below. */ certificatePolicy?: pulumi.Input<inputs.keyvault.CertifiateCertificatePolicy>; /** * The ID of the Key Vault where the Certificate should be created. */ keyVaultId: pulumi.Input<string>; /** * Specifies the name of the Key Vault Certificate. Changing this forces a new resource to be created. */ name?: pulumi.Input<string>; /** * A mapping of tags to assign to the resource. */ tags?: pulumi.Input<{[key: string]: pulumi.Input<string>}>; }
the_stack
import "../../support/polyfills/polyfills"; import test, { ExecutionContext } from "ava"; import Database from "../../../src/services/Database"; import { TestEnvironment, BrowserUserAgent } from "../../support/sdk/TestEnvironment"; import OneSignal from "../../../src/OneSignal"; import { InvalidArgumentError } from '../../../src/errors/InvalidArgumentError'; import nock from 'nock'; import Random from "../../support/tester/Random"; import { setUserAgent } from "../../support/tester/browser"; test.beforeEach(async _t => { await TestEnvironment.initialize(); TestEnvironment.mockInternalOneSignal(); await Database.put('Ids', { type: 'appId', id: OneSignal.context.appConfig.appId }); }); test("setEmail should reject an empty or invalid emails", async t => { try { await OneSignal.setEmail(undefined as any); t.fail('expected exception not caught'); } catch (e) { t.truthy(e instanceof InvalidArgumentError); } try { await OneSignal.setEmail(null as any); t.fail('expected exception not caught'); } catch (e) { t.truthy(e instanceof InvalidArgumentError); } try { await OneSignal.setEmail(null as any); t.fail('expected exception not caught'); } catch (e) { t.truthy(e instanceof InvalidArgumentError); } try { await OneSignal.setEmail("test@@example.com"); t.fail('expected exception not caught'); } catch (e) { t.truthy(e instanceof InvalidArgumentError); } }); test("setEmail should not accept an email auth SHA-256 hex hash not 64 characters long", async t => { try { await OneSignal.setEmail("test@example.com", { identifierAuthHash: "12345" }); t.fail('expected exception not caught'); } catch (e) { t.truthy(e instanceof InvalidArgumentError); } }); /* * Test Case | Description * ----------------------- * No push subscription, no email, first setEmail call * No push subscription, existing identical email, refreshing setEmail call * No push subscription, existing different email, updating email * Existing push subscription, no email, first setEmail call * Existing push subscription, existing identical email, refreshing setEmail call * Existing push subscription, existing different email, updating email * * --- * * ..., existing email (identical or not), identifierAuthHash --> makes a PUT call instead of POST */ async function expectEmailRecordCreationRequest( t: ExecutionContext, emailAddress: string, pushDevicePlayerId: string | null, identifierAuthHash: string | undefined | null, newCreatedEmailId: string ) { nock('https://onesignal.com') .post(`/api/v1/players`) .reply(200, (_uri: string, requestBody: any) => { const sameValues: {[key: string]: string | undefined } = { app_id: OneSignal.context.appConfig.appId, identifier: emailAddress, device_player_id: pushDevicePlayerId ? pushDevicePlayerId : undefined, identifier_auth_hash: identifierAuthHash ? identifierAuthHash : undefined }; const anyValues = [ "device_type", "language", "timezone", "timezone_id", "device_os", "sdk", "device_model" ]; const parsedRequestBody = JSON.parse(requestBody); for (const sameValueKey of Object.keys(sameValues)) { t.deepEqual(parsedRequestBody[sameValueKey], sameValues[sameValueKey]); } for (const anyValueKey of anyValues) { t.not(parsedRequestBody[anyValueKey], undefined); } return { success : true, id: newCreatedEmailId }; }); } async function expectEmailRecordUpdateRequest( t: ExecutionContext, emailId: string | null, emailAddress: string, pushDevicePlayerId: string | null, identifierAuthHash: string | undefined, newUpdatedEmailId: string ) { nock('https://onesignal.com') .put(`/api/v1/players/${emailId}`) .reply(200, (_uri: string, requestBody: any) => { const sameValues: {[key: string]: string | undefined } = { app_id: OneSignal.context.appConfig.appId, identifier: emailAddress, device_player_id: pushDevicePlayerId ? pushDevicePlayerId : undefined, identifier_auth_hash: identifierAuthHash ? identifierAuthHash : undefined }; const parsedRequestBody = JSON.parse(requestBody); for (const sameValueKey of Object.keys(sameValues)) { t.deepEqual(parsedRequestBody[sameValueKey], sameValues[sameValueKey]); } return { success : true, id : newUpdatedEmailId }; }); } async function expectPushRecordUpdateRequest( t: ExecutionContext, pushDevicePlayerId: string, newEmailId: string, emailAddress: string, newUpdatedPlayerId: string, externalUserIdAuth?: string | null ) { nock('https://onesignal.com') .put(`/api/v1/players/${pushDevicePlayerId}`) .reply(200, (_uri: string, requestBody: any) => { t.deepEqual( requestBody, JSON.stringify({ app_id: OneSignal.context.appConfig.appId, parent_player_id: newEmailId ? newEmailId : undefined, email: emailAddress, external_user_id_auth_hash: externalUserIdAuth }) ); return { success : true, id : newUpdatedPlayerId }; }); } interface SetEmailTestData { existingEmailAddress: string | null; newEmailAddress: string; /* Email address used for setEmail */ existingPushDeviceId: string | null; identifierAuthHash: string | undefined; existingEmailId: string | null; newEmailId: string; /* Returned by the create or update email record call */ externalUserIdAuthHash?: string | null; } async function setEmailTest( t: ExecutionContext, testData: SetEmailTestData ) { setUserAgent(BrowserUserAgent.FirefoxMacSupported); if (testData.existingEmailAddress) { const emailProfile = await Database.getEmailProfile(); emailProfile.identifier = testData.existingEmailAddress; await Database.setEmailProfile(emailProfile); } /* If an existing push device ID is set, create a fake one here */ if (testData.existingPushDeviceId) { const subscription = await Database.getSubscription(); subscription.deviceId = testData.existingPushDeviceId; await Database.setSubscription(subscription); } /* If test data has an email auth hash, fake the config parameter */ if (testData.identifierAuthHash) { const emailProfile = await Database.getEmailProfile(); emailProfile.identifierAuthHash = testData.identifierAuthHash; await Database.setEmailProfile(emailProfile); } if (testData.existingEmailId) { const emailProfile = await Database.getEmailProfile(); emailProfile.subscriptionId = testData.existingEmailId; await Database.setEmailProfile(emailProfile); } // Mock the one or two requests we expect to occur const isUpdateRequest = testData.existingEmailId; if (isUpdateRequest) { // Means we're making a PUT call to /players/<id> expectEmailRecordUpdateRequest( t, testData.existingEmailId, testData.newEmailAddress, testData.existingPushDeviceId, testData.identifierAuthHash, testData.newEmailId ); } else { // Means we're making a POST call to /players expectEmailRecordCreationRequest( t, testData.newEmailAddress, testData.existingPushDeviceId, testData.identifierAuthHash, testData.newEmailId ); } if ( testData.existingPushDeviceId && !( testData.existingEmailId === testData.newEmailId && testData.existingEmailAddress === testData.newEmailAddress ) ) { /* Expect a second call to be made if: - We're subscribed to web push (existing player ID) - The email ID or plain text email address changes from what we have saved, or if neither was ever saved */ expectPushRecordUpdateRequest( t, testData.existingPushDeviceId, testData.newEmailId, testData.newEmailAddress, Random.getRandomUuid(), testData.externalUserIdAuthHash ); } await OneSignal.setEmail( testData.newEmailAddress, testData.identifierAuthHash ? { identifierAuthHash: testData.identifierAuthHash } : undefined ); const { deviceId: finalPushDeviceId } = await Database.getSubscription(); const finalEmailProfile = await Database.getEmailProfile(); t.deepEqual(finalPushDeviceId, testData.existingPushDeviceId ? testData.existingPushDeviceId : null); t.deepEqual(finalEmailProfile.identifier, testData.newEmailAddress); t.deepEqual(finalEmailProfile.identifierAuthHash, testData.identifierAuthHash); t.deepEqual(finalEmailProfile.subscriptionId, testData.newEmailId); } test("No push subscription, no email, first setEmail call", async t => { const testData: SetEmailTestData = { existingEmailAddress: null, newEmailAddress: "test@example.com", existingPushDeviceId: null, identifierAuthHash: undefined, existingEmailId: null, newEmailId: Random.getRandomUuid() }; await setEmailTest(t, testData); }); test("No push subscription, no email, first setEmail call, test email id return", async t => { const fakeUuid = Random.getRandomUuid(); expectEmailRecordCreationRequest( t, "example@domain.com", null, null, fakeUuid ); setUserAgent(BrowserUserAgent.FirefoxMacSupported); t.is(await OneSignal.setEmail("example@domain.com"), fakeUuid); }); test("No push subscription, existing identical email, refreshing setEmail call", async t => { const emailId = Random.getRandomUuid(); const testData: SetEmailTestData = { existingEmailAddress: "test@example.com", newEmailAddress: "test@example.com", existingPushDeviceId: null, identifierAuthHash: undefined, existingEmailId: emailId, newEmailId: emailId }; await setEmailTest(t, testData); }); test("No push subscription, existing different email, updating setEmail call", async t => { const existingEmailId = Random.getRandomUuid(); const testData: SetEmailTestData = { existingEmailAddress: "existing-different-email-address@example.com", newEmailAddress: "test@example.com", existingPushDeviceId: null, identifierAuthHash: undefined, existingEmailId: existingEmailId, newEmailId: existingEmailId }; await setEmailTest(t, testData); }); test("Existing push subscription, no email, first setEmail call", async t => { const testData: SetEmailTestData = { existingEmailAddress: null, newEmailAddress: "test@example.com", existingPushDeviceId: Random.getRandomUuid(), identifierAuthHash: undefined, existingEmailId: null, newEmailId: Random.getRandomUuid(), externalUserIdAuthHash: null }; await setEmailTest(t, testData); }); test("Existing push subscription, existing identical email, refreshing setEmail call", async t => { const emailId = Random.getRandomUuid(); const testData = { existingEmailAddress: "test@example.com", newEmailAddress: "test@example.com", identifierAuthHash: undefined, existingEmailId: emailId, newEmailId: emailId } as SetEmailTestData; await setEmailTest(t, testData); }); test("Existing push subscription, existing different email, updating setEmail call", async t => { const existingEmailId = Random.getRandomUuid(); const testData = { existingEmailAddress: "existing-different-email@example.com", newEmailAddress: "test@example.com", identifierAuthHash: undefined, existingEmailId: existingEmailId, newEmailId: existingEmailId, externalUserIdAuthHash: null } as SetEmailTestData; await setEmailTest(t, testData); }); test( "Existing push subscription, existing identical email, with identifierAuthHash, refreshing setEmail call", async t => { const existingEmailId = Random.getRandomUuid(); const testData = { existingEmailAddress: "existing-different-email@example.com", newEmailAddress: "test@example.com", identifierAuthHash: "432B5BE752724550952437FAED4C8E2798E9D0AF7AACEFE73DEA923A14B94799", existingEmailId: existingEmailId, newEmailId: existingEmailId, externalUserIdAuthHash: null } as SetEmailTestData; await setEmailTest(t, testData); });
the_stack
import chai from "chai"; const should = chai.should(); import chaiAsPromised from "chai-as-promised"; chai.use(chaiAsPromised); import { ServiceBusMessage, delay, ProcessErrorArgs, isServiceBusError } from "../../src"; import { TestClientType, TestMessage } from "./utils/testUtils"; import { ServiceBusClientForTests, createServiceBusClientForTests, getRandomTestClientTypeWithSessions } from "./utils/testutils2"; import { ServiceBusSender } from "../../src"; import { ServiceBusSessionReceiver } from "../../src"; import { ServiceBusReceivedMessage } from "../../src"; describe("Session Lock Renewal", () => { let sender: ServiceBusSender; let receiver: ServiceBusSessionReceiver; let sessionId: string; let serviceBusClient: ServiceBusClientForTests; const testClientType = getRandomTestClientTypeWithSessions(); before(async () => { serviceBusClient = createServiceBusClientForTests(); }); after(async () => { await serviceBusClient.test.after(); }); async function beforeEachTest(maxAutoLockRenewalDurationInMs: number): Promise<void> { const entityNames = await serviceBusClient.test.createTestEntities(testClientType); sender = serviceBusClient.test.addToCleanup( serviceBusClient.createSender(entityNames.queue ?? entityNames.topic!) ); sessionId = Date.now().toString(); receiver = await serviceBusClient.test.acceptSessionWithPeekLock(entityNames, sessionId, { maxAutoLockRenewalDurationInMs }); // Observation - // Peeking into an empty session-enabled queue would run into either of the following errors.. // 1. OperationTimeoutError: Unable to create the amqp receiver 'unpartitioned-queue-sessions-794f89be-3282-8b48-8ae0-a8af43c3ce36' // on amqp session 'local-1_remote-1_connection-2' due to operation timeout. // 2. MessagingError: Received an incorrect sessionId 'undefined' while creating the receiver 'unpartitioned-queue-sessions-86662b2b-acdc-1045-8ad4-fa3ab8807871'. // getSenderReceiverClients creates brand new queues/topic-subscriptions. // Hence, commenting the following code since there is no need to purge/peek into a freshly created entity // await purge(receiver); // const peekedMsgs = await receiver.peekMessages(); // const receiverEntityType = receiver.entityType; // if (peekedMsgs.length) { // chai.assert.fail(`Please use an empty ${receiverEntityType} for integration testing`); // } } afterEach(() => { return serviceBusClient.test.afterEach(); }); it( testClientType + ": Batch Receiver: renewLock() resets lock duration each time", async function(): Promise<void> { await beforeEachTest(0); await testBatchReceiverManualLockRenewalHappyCase(); } ); it( testClientType + ": Batch Receiver: complete() after lock expiry with throws error", async function(): Promise<void> { await beforeEachTest(0); await testBatchReceiverManualLockRenewalErrorOnLockExpiry(testClientType); } ); it( testClientType + ": Streaming Receiver: renewLock() resets lock duration each time", async function(): Promise<void> { await beforeEachTest(0); await testStreamingReceiverManualLockRenewalHappyCase(); } ); it( testClientType + ": Streaming Receiver: complete() after lock expiry with auto-renewal disabled throws error", async function(): Promise<void> { const options: AutoLockRenewalTestOptions = { maxAutoRenewLockDurationInMs: 0, delayBeforeAttemptingToCompleteMessageInSeconds: 31, expectSessionLockLostErrorToBeThrown: true }; await beforeEachTest(options.maxAutoRenewLockDurationInMs); await testAutoLockRenewalConfigBehavior(options); } ); it( testClientType + ": Streaming Receiver: lock will not expire until configured time", async function(): Promise<void> { const options: AutoLockRenewalTestOptions = { maxAutoRenewLockDurationInMs: 38 * 1000, delayBeforeAttemptingToCompleteMessageInSeconds: 35, expectSessionLockLostErrorToBeThrown: false }; await beforeEachTest(options.maxAutoRenewLockDurationInMs); await testAutoLockRenewalConfigBehavior(options); } ); const lockDurationInMilliseconds = 30000; // const maxAutoRenewLockDurationInMs = 300*1000; let uncaughtErrorFromHandlers: Error | undefined; async function processError(args: ProcessErrorArgs): Promise<void> { uncaughtErrorFromHandlers = args.error; } /** * Test manual renewLock() using Batch Receiver, with autoLockRenewal disabled */ async function testBatchReceiverManualLockRenewalHappyCase(): Promise<void> { const testMessage = getTestMessage(); testMessage.body = `testBatchReceiverManualLockRenewalHappyCase-${Date.now().toString()}`; await sender.sendMessages(testMessage); const msgs = await receiver.receiveMessages(1); // Compute expected initial lock expiry time const expectedLockExpiryTimeUtc = new Date(); expectedLockExpiryTimeUtc.setSeconds( expectedLockExpiryTimeUtc.getSeconds() + lockDurationInMilliseconds / 1000 ); should.equal(Array.isArray(msgs), true, "`ReceivedMessages` is not an array"); should.equal(msgs.length, 1, "Unexpected number of messages"); should.equal(msgs[0].body, testMessage.body, "MessageBody is different than expected"); should.equal(msgs[0].messageId, testMessage.messageId, "MessageId is different than expected"); // Verify initial lock expiry time on the session assertTimestampsAreApproximatelyEqual( receiver.sessionLockedUntilUtc, expectedLockExpiryTimeUtc, "Initial" ); await delay(5000); await receiver.renewSessionLock(); // Compute expected lock expiry time after renewing lock after 5 seconds expectedLockExpiryTimeUtc.setSeconds(expectedLockExpiryTimeUtc.getSeconds() + 5); // Verify lock expiry time after renewLock() assertTimestampsAreApproximatelyEqual( receiver.sessionLockedUntilUtc, expectedLockExpiryTimeUtc, "After renewlock()" ); await receiver.completeMessage(msgs[0]); } /** * Test settling of message from Batch Receiver fails after session lock expires */ async function testBatchReceiverManualLockRenewalErrorOnLockExpiry( entityType: TestClientType ): Promise<void> { const testMessage = getTestMessage(); testMessage.body = `testBatchReceiverManualLockRenewalErrorOnLockExpiry-${Date.now().toString()}`; await sender.sendMessages(testMessage); const msgs = await receiver.receiveMessages(1); should.equal(Array.isArray(msgs), true, "`ReceivedMessages` is not an array"); should.equal(msgs.length, 1, "Expected message length does not match"); should.equal(msgs[0].body, testMessage.body, "MessageBody is different than expected"); should.equal(msgs[0].messageId, testMessage.messageId, "MessageId is different than expected"); await delay(lockDurationInMilliseconds + 1000); let errorWasThrown: boolean = false; await receiver.completeMessage(msgs[0]).catch((err) => { should.equal(err.code, "SessionLockLost", "Reason code is different than expected"); errorWasThrown = true; }); should.equal(errorWasThrown, true, "Error thrown flag must be true"); // Clean up the messages. await receiver.close(); const entityNames = serviceBusClient.test.getTestEntities(entityType); receiver = await serviceBusClient.test.acceptNextSessionWithPeekLock(entityNames); const unprocessedMsgsBatch = await receiver.receiveMessages(1); should.equal(unprocessedMsgsBatch[0].deliveryCount, 1, "Unexpected deliveryCount"); await receiver.completeMessage(unprocessedMsgsBatch[0]); } /** * Test manual renewLock() using Streaming Receiver with autoLockRenewal disabled */ async function testStreamingReceiverManualLockRenewalHappyCase(): Promise<void> { let numOfMessagesReceived = 0; const testMessage = getTestMessage(); testMessage.body = `testStreamingReceiverManualLockRenewalHappyCase-${Date.now().toString()}`; await sender.sendMessages(testMessage); async function processMessage(brokeredMessage: ServiceBusReceivedMessage): Promise<void> { if (numOfMessagesReceived < 1) { numOfMessagesReceived++; should.equal( brokeredMessage.body, testMessage.body, "MessageBody is different than expected" ); should.equal( brokeredMessage.messageId, testMessage.messageId, "MessageId is different than expected" ); // Compute expected initial lock expiry time const expectedLockExpiryTimeUtc = new Date(); expectedLockExpiryTimeUtc.setSeconds( expectedLockExpiryTimeUtc.getSeconds() + lockDurationInMilliseconds / 1000 ); // Verify initial expiry time on session assertTimestampsAreApproximatelyEqual( receiver.sessionLockedUntilUtc, expectedLockExpiryTimeUtc, "Initial" ); await delay(5000); await receiver.renewSessionLock(); // Compute expected lock expiry time after renewing lock after 5 seconds expectedLockExpiryTimeUtc.setSeconds(expectedLockExpiryTimeUtc.getSeconds() + 5); // Verify actual expiry time on session after renewal assertTimestampsAreApproximatelyEqual( receiver.sessionLockedUntilUtc, expectedLockExpiryTimeUtc, "After renewlock()" ); await receiver.completeMessage(brokeredMessage); } } receiver.subscribe( { processMessage, processError }, { autoCompleteMessages: false } ); await delay(10000); await receiver.close(); if (uncaughtErrorFromHandlers) { chai.assert.fail(uncaughtErrorFromHandlers.message); } should.equal(numOfMessagesReceived, 1, "Unexpected number of messages"); } interface AutoLockRenewalTestOptions { maxAutoRenewLockDurationInMs: number; delayBeforeAttemptingToCompleteMessageInSeconds: number; expectSessionLockLostErrorToBeThrown: boolean; } async function testAutoLockRenewalConfigBehavior( options: AutoLockRenewalTestOptions ): Promise<void> { let numOfMessagesReceived = 0; const testMessage = getTestMessage(); testMessage.body = `testAutoLockRenewalConfigBehavior-${Date.now().toString()}`; await sender.sendMessages(testMessage); let sessionLockLostErrorThrown = false; const messagesReceived: ServiceBusReceivedMessage[] = []; async function processMessage(brokeredMessage: ServiceBusReceivedMessage): Promise<void> { if (numOfMessagesReceived < 1) { numOfMessagesReceived++; should.equal( brokeredMessage.body, testMessage.body, "MessageBody is different than expected" ); should.equal( brokeredMessage.messageId, testMessage.messageId, "MessageId is different than expected" ); messagesReceived.push(brokeredMessage); // Sleeping... await delay(options.delayBeforeAttemptingToCompleteMessageInSeconds * 1000); } } receiver.subscribe( { processMessage, async processError(args: ProcessErrorArgs) { if (isServiceBusError(args.error) && args.error.code === "SessionLockLost") { sessionLockLostErrorThrown = true; } else { uncaughtErrorFromHandlers = args.error; } } }, { autoCompleteMessages: false } ); await delay(options.delayBeforeAttemptingToCompleteMessageInSeconds * 1000 + 2000); should.not.exist(uncaughtErrorFromHandlers?.message); should.equal( sessionLockLostErrorThrown, options.expectSessionLockLostErrorToBeThrown, "SessionLockLostErrorThrown flag must match" ); should.equal(messagesReceived.length, 1, "Mismatch in number of messages received"); let errorWasThrown: boolean = false; await receiver.completeMessage(messagesReceived[0]).catch((err) => { should.equal(err.code, "SessionLockLost", "Error code is different than expected"); errorWasThrown = true; }); should.equal( errorWasThrown, options.expectSessionLockLostErrorToBeThrown, "Error Thrown flag value mismatch" ); await receiver.close(); if (uncaughtErrorFromHandlers) { chai.assert.fail(uncaughtErrorFromHandlers.message); } } function assertTimestampsAreApproximatelyEqual( actualTimeInUTC: Date | undefined, expectedTimeInUTC: Date, label: string ): void { if (actualTimeInUTC) { should.equal( Math.pow((actualTimeInUTC.valueOf() - expectedTimeInUTC.valueOf()) / 1000, 2) < 100, // Within +/- 10 seconds true, `${label}: Actual time ${actualTimeInUTC} must be approximately equal to ${expectedTimeInUTC}` ); } } function getTestMessage(): ServiceBusMessage { const baseMessage = TestMessage.getSessionSample(); baseMessage.sessionId = sessionId; baseMessage.partitionKey = sessionId; return baseMessage; } });
the_stack
import { External } from "plywood"; import { PlywoodRequester } from "plywood-base-api"; import { DruidRequestDecorator } from "plywood-druid-requester"; import { Logger } from "../../../common/logger/logger"; import { Cluster } from "../../../common/models/cluster/cluster"; import { noop } from "../../../common/utils/functional/functional"; import { loadModule } from "../module-loader/module-loader"; import { DruidRequestDecoratorModule } from "../request-decorator/request-decorator"; import { properRequesterFactory } from "../requester/requester"; const CONNECTION_RETRY_TIMEOUT = 20000; const DRUID_REQUEST_DECORATOR_MODULE_VERSION = 1; // For each external we want to maintain its source and whether it should introspect at all export interface ManagedExternal { name: string; external: External; autoDiscovered?: boolean; suppressIntrospection?: boolean; } export interface ClusterManagerOptions { logger: Logger; verbose?: boolean; anchorPath: string; initialExternals?: ManagedExternal[]; onExternalChange?: (name: string, external: External) => Promise<void>; onExternalRemoved?: (name: string, external: External) => Promise<void>; generateExternalName?: (external: External) => string; } function emptyResolve(): Promise<void> { return Promise.resolve(null); } function getSourceFromExternal(external: External): string { return String(external.source); } function externalContainsSource(external: External, source: string): boolean { return Array.isArray(external.source) ? external.source.indexOf(source) > -1 : String(external.source) === source; } export class ClusterManager { public logger: Logger; public verbose: boolean; public anchorPath: string; public cluster: Cluster; public initialConnectionEstablished: boolean; public introspectedSources: Record<string, boolean>; public version: string; public managedExternals: ManagedExternal[] = []; public onExternalChange: (name: string, external: External) => Promise<void>; public onExternalRemoved: (name: string, external: External) => Promise<void>; public generateExternalName: (external: External) => string; private requester: PlywoodRequester<any>; private sourceListRefreshInterval = 0; private sourceListRefreshTimer: NodeJS.Timer = null; private sourceReintrospectInterval = 0; private sourceReintrospectTimer: NodeJS.Timer = null; private initialConnectionTimer: NodeJS.Timer = null; constructor(cluster: Cluster, options: ClusterManagerOptions) { if (!cluster) throw new Error("must have cluster"); this.logger = options.logger; this.verbose = Boolean(options.verbose); this.anchorPath = options.anchorPath; this.cluster = cluster; this.initialConnectionEstablished = false; this.introspectedSources = {}; this.version = cluster.version; this.managedExternals = options.initialExternals || []; this.onExternalChange = options.onExternalChange || emptyResolve; this.onExternalRemoved = options.onExternalRemoved || emptyResolve; this.generateExternalName = options.generateExternalName || getSourceFromExternal; this.requester = this.initRequester(); this.managedExternals.forEach(managedExternal => { managedExternal.external = managedExternal.external.attachRequester(this.requester); }); } // Do initialization public init(): Promise<void> { const { cluster, logger } = this; if (cluster.sourceListRefreshOnLoad) { logger.log(`Cluster '${cluster.name}' will refresh source list on load`); } if (cluster.sourceReintrospectOnLoad) { logger.log(`Cluster '${cluster.name}' will reintrospect sources on load`); } return this.establishInitialConnection() .then(() => this.introspectSources()) .then(() => this.scanSourceList()); } public destroy() { if (this.sourceListRefreshTimer) { clearInterval(this.sourceListRefreshTimer); this.sourceListRefreshTimer = null; } if (this.sourceReintrospectTimer) { clearInterval(this.sourceReintrospectTimer); this.sourceReintrospectTimer = null; } if (this.initialConnectionTimer) { clearTimeout(this.initialConnectionTimer); this.initialConnectionTimer = null; } } private addManagedExternal(managedExternal: ManagedExternal): Promise<void> { this.managedExternals.push(managedExternal); return this.onExternalChange(managedExternal.name, managedExternal.external); } private updateManagedExternal(managedExternal: ManagedExternal, newExternal: External): Promise<void> { if (managedExternal.external.equals(newExternal)) return null; managedExternal.external = newExternal; return this.onExternalChange(managedExternal.name, managedExternal.external); } private removeManagedExternal(managedExternal: ManagedExternal): Promise<void> { this.managedExternals = this.managedExternals.filter(ext => ext.external !== managedExternal.external); return this.onExternalRemoved(managedExternal.name, managedExternal.external); } private initRequester(): PlywoodRequester<any> { const { cluster } = this; const druidRequestDecorator = this.loadRequestDecorator(); return properRequesterFactory({ cluster, verbose: this.verbose, concurrentLimit: 5, druidRequestDecorator }); } private loadRequestDecorator(): DruidRequestDecorator | undefined { const { cluster, logger, anchorPath } = this; if (!cluster.requestDecorator) return undefined; try { logger.log(`Cluster ${cluster.name}: Loading requestDecorator`); const module = loadModule(cluster.requestDecorator.path, anchorPath) as DruidRequestDecoratorModule; if (module.version !== DRUID_REQUEST_DECORATOR_MODULE_VERSION) { logger.error(`Cluster ${cluster.name}: druidRequestDecorator module has incorrect version`); return undefined; } logger.log(`Cluster ${cluster.name} creating requestDecorator`); return module.druidRequestDecoratorFactory(logger.addPrefix("DruidRequestDecoratorFactory"), { options: cluster.requestDecorator.options, cluster }); } catch (e) { logger.error(`Cluster ${cluster.name}: Couldn't load druidRequestDecorator module: ${e.message}`); return undefined; } } private updateSourceListRefreshTimer() { const { logger, cluster } = this; if (this.sourceListRefreshInterval !== cluster.getSourceListRefreshInterval()) { this.sourceListRefreshInterval = cluster.getSourceListRefreshInterval(); if (this.sourceListRefreshTimer) { logger.log(`Clearing sourceListRefresh timer in cluster '${cluster.name}'`); clearInterval(this.sourceListRefreshTimer); this.sourceListRefreshTimer = null; } if (this.sourceListRefreshInterval && cluster.shouldScanSources()) { logger.log(`Setting up sourceListRefresh timer in cluster '${cluster.name}' (every ${this.sourceListRefreshInterval}ms)`); this.sourceListRefreshTimer = setInterval( () => { this.scanSourceList().catch(e => { logger.error(`Cluster '${cluster.name}' encountered and error during SourceListRefresh: ${e.message}`); }); }, this.sourceListRefreshInterval ); this.sourceListRefreshTimer.unref(); } } } private updateSourceReintrospectTimer() { const { logger, cluster } = this; if (this.sourceReintrospectInterval !== cluster.getSourceReintrospectInterval()) { this.sourceReintrospectInterval = cluster.getSourceReintrospectInterval(); if (this.sourceReintrospectTimer) { logger.log(`Clearing sourceReintrospect timer in cluster '${cluster.name}'`); clearInterval(this.sourceReintrospectTimer); this.sourceReintrospectTimer = null; } if (this.sourceReintrospectInterval) { logger.log(`Setting up sourceReintrospect timer in cluster '${cluster.name}' (every ${this.sourceReintrospectInterval}ms)`); this.sourceReintrospectTimer = setInterval( () => { this.introspectSources().catch(e => { logger.error(`Cluster '${cluster.name}' encountered and error during SourceReintrospect: ${e.message}`); }); }, this.sourceReintrospectInterval ); this.sourceReintrospectTimer.unref(); } } } private establishInitialConnection(): Promise<void> { const { logger, verbose, cluster } = this; return new Promise<void>(resolve => { let retryNumber = -1; let lastTryAt: number; const attemptConnection = () => { retryNumber++; if (retryNumber === 0) { if (verbose) logger.log(`Attempting to connect to cluster '${cluster.name}'`); } else { logger.log(`Re-attempting to connect to cluster '${cluster.name}' (retry ${retryNumber})`); } lastTryAt = Date.now(); (External.getConstructorFor(cluster.type) as any) .getVersion(this.requester) .then( (version: string) => { this.onConnectionEstablished(); this.internalizeVersion(version).then(() => resolve(null)); }, (e: Error) => { const msSinceLastTry = Date.now() - lastTryAt; const msToWait = Math.max(1, CONNECTION_RETRY_TIMEOUT - msSinceLastTry); logger.error(`Failed to connect to cluster '${cluster.name}' because: ${e.message} (will retry in ${msToWait}ms)`); this.initialConnectionTimer = setTimeout(attemptConnection, msToWait); } ); }; attemptConnection(); }); } private onConnectionEstablished(): void { const { logger, cluster } = this; logger.log(`Connected to cluster '${cluster.name}'`); this.initialConnectionEstablished = true; this.updateSourceListRefreshTimer(); this.updateSourceReintrospectTimer(); } private internalizeVersion(version: string): Promise<void> { // If there is a version already do nothing if (this.version) return Promise.resolve(null); const { logger, cluster } = this; logger.log(`Cluster '${cluster.name}' is running druid@${version}`); this.version = version; // Update all externals if needed const tasks: Array<Promise<void>> = this.managedExternals.map(managedExternal => { if (managedExternal.external.version) return Promise.resolve(null); return this.updateManagedExternal(managedExternal, managedExternal.external.changeVersion(version)); }); return Promise.all(tasks).then(noop); } private introspectManagedExternal(managedExternal: ManagedExternal): Promise<void> { const { logger, verbose, cluster } = this; if (managedExternal.suppressIntrospection) return Promise.resolve(null); if (verbose) logger.log(`Cluster '${cluster.name}' introspecting '${managedExternal.name}'`); return managedExternal.external.introspect() .then( introspectedExternal => { this.introspectedSources[String(introspectedExternal.source)] = true; return this.updateManagedExternal(managedExternal, introspectedExternal); }, (e: Error) => { logger.error(`Cluster '${cluster.name}' could not introspect '${managedExternal.name}' because: ${e.message}`); } ); } // See if any new sources were added to the cluster public scanSourceList = (): Promise<void> => { const { logger, cluster, verbose } = this; if (!cluster.shouldScanSources()) return Promise.resolve(null); logger.log(`Scanning cluster '${cluster.name}' for new sources`); return (External.getConstructorFor(cluster.type) as any).getSourceList(this.requester) .then( (sources: string[]) => { if (verbose) logger.log(`For cluster '${cluster.name}' got sources: [${sources.join(", ")}]`); // For every un-accounted source: make an external and add it to the managed list. let introspectionTasks: Array<Promise<void>> = []; this.managedExternals.forEach(ex => { if (sources.find(src => src === String(ex.external.source)) == null) { logger.log(`Missing source '${String(ex.external.source)}' + " for cluster '${cluster.name}', removing...`); introspectionTasks.push(this.removeManagedExternal(ex)); } }); sources.forEach(source => { const existingExternalsForSource = this.managedExternals.filter(managedExternal => externalContainsSource(managedExternal.external, source)); if (existingExternalsForSource.length) { if (verbose) logger.log(`Cluster '${cluster.name}' already has an external for '${source}' ('${existingExternalsForSource[0].name}')`); if (!this.introspectedSources[source]) { // If this source has never been introspected introspect all of its externals logger.log(`Cluster '${cluster.name}' has never seen '${source}' and will introspect '${existingExternalsForSource[0].name}'`); existingExternalsForSource.forEach(existingExternalForSource => { introspectionTasks.push(this.introspectManagedExternal(existingExternalForSource)); }); } } else { logger.log(`Cluster '${cluster.name}' making external for '${source}'`); const external = cluster.makeExternalFromSourceName(source, this.version).attachRequester(this.requester); const newManagedExternal: ManagedExternal = { name: this.generateExternalName(external), external, autoDiscovered: true }; introspectionTasks.push( this.addManagedExternal(newManagedExternal) .then(() => this.introspectManagedExternal(newManagedExternal)) ); } }); return Promise.all(introspectionTasks); }, (e: Error) => { logger.error(`Failed to get source list from cluster '${cluster.name}' because: ${e.message}`); } ); } // See if any new dimensions or measures were added to the existing externals public introspectSources = (): Promise<void> => { const { logger, cluster } = this; logger.log(`Introspecting all sources in cluster '${cluster.name}'`); return (External.getConstructorFor(cluster.type) as any).getSourceList(this.requester) .then( (sources: string[]) => { let introspectionTasks: Array<Promise<void>> = []; sources.forEach(source => { const existingExternalsForSource = this.managedExternals.filter(managedExternal => externalContainsSource(managedExternal.external, source)); if (existingExternalsForSource.length) { existingExternalsForSource.forEach(existingExternalForSource => { introspectionTasks.push(this.introspectManagedExternal(existingExternalForSource)); }); } }); return Promise.all(introspectionTasks); }, (e: Error) => { logger.error(`Failed to get source list from cluster '${cluster.name}' because: ${e.message}`); } ); } // Refresh the cluster now, will trigger onExternalUpdate and then return an empty promise when done public refresh(): Promise<void> { const { cluster, initialConnectionEstablished } = this; let process = Promise.resolve(null); if (!initialConnectionEstablished) return process; if (cluster.sourceReintrospectOnLoad) { process = process.then(() => this.introspectSources()); } if (cluster.sourceListRefreshOnLoad) { process = process.then(() => this.scanSourceList()); } return process; } }
the_stack
import * as vscode from 'vscode'; import { CSpellClient, CSpellUserSettings } from '../client'; import { extensionId } from '../constants'; import { catchErrors, logError, logErrors, showError } from '../util/errors'; import { toRegExp } from './evaluateRegExp'; import { PatternMatcherClient } from './patternMatcherClient'; import { RegexpOutlineItem, RegexpOutlineProvider } from './RegexpOutlineProvider'; import { NamedPattern, PatternMatch, PatternSettings } from './server'; import { format } from 'util'; interface DisposableLike { dispose(): any; } const MAX_HISTORY_LENGTH = 5; // this method is called when vs code is activated export function activate(context: vscode.ExtensionContext, clientSpellChecker: CSpellClient): void { const disposables = new Set<DisposableLike>(); const outline = new RegexpOutlineProvider(); let patternMatcherClient: PatternMatcherClient | undefined; vscode.window.registerTreeDataProvider('cSpellRegExpView', outline); let timeout: NodeJS.Timer | undefined = undefined; // create a decorator type that we use to decorate small numbers const decorationTypeExclude = vscode.window.createTextEditorDecorationType({ // borderWidth: '1px', // borderStyle: 'solid', overviewRulerColor: 'green', overviewRulerLane: vscode.OverviewRulerLane.Center, light: { // this color will be used in light color themes // borderColor: 'darkblue', backgroundColor: '#C0C0FFCC', }, dark: { // this color will be used in dark color themes // borderColor: 'lightblue', backgroundColor: '#347890CC', }, }); let isActive = fetchIsEnabledFromConfig(); let activeEditor = isActive ? vscode.window.activeTextEditor : undefined; let pattern: string | undefined = undefined; let history: string[] = []; const updateDecorations = catchErrors(_updateDecorations, 'updateDecorations', showError); async function _updateDecorations() { disposeCurrent(); if (!isActive || !activeEditor) { clearDecorations(); return; } const document = activeEditor.document; const version = document.version; const config = await clientSpellChecker.getConfigurationForDocument(document); const extractedPatterns = extractPatternsFromConfig(config.docSettings, history); const patterns = extractedPatterns.map((p) => p.pattern); const highlightIndex = pattern ? 0 : -1; const client = await getPatternMatcherClient(); const patternSettings: PatternSettings = { patterns: config.docSettings?.patterns || config.settings?.patterns || [], }; await client.matchPatternsInDocument(document, patterns, patternSettings).then((result) => { if (!vscode.window.activeTextEditor || document.version !== version || vscode.window.activeTextEditor?.document != document) { return; } if (result.message) { // @todo: show the message. return; } const byCategory: Map<string, PatternMatch[]> | undefined = result && new Map(); result?.patternMatches.forEach((m, i) => { const category = extractedPatterns[i].category; const matches = byCategory.get(category) || []; matches.push(m); byCategory.set(category, matches); }); outline.refresh(byCategory); const activeEditor = vscode.window.activeTextEditor; const flattenResults = result.patternMatches .filter((_, i) => i === highlightIndex) .map(mapPatternMatchToRangeMessage) .reduce((a, v) => a.concat(v), []); const decorations: vscode.DecorationOptions[] = flattenResults.map((match) => { const { range, message } = match; const startPos = activeEditor.document.positionAt(range[0]); const endPos = activeEditor.document.positionAt(range[1]); const decoration: vscode.DecorationOptions = { range: new vscode.Range(startPos, endPos), hoverMessage: message }; return decoration; }); activeEditor.setDecorations(decorationTypeExclude, decorations); }); } function mapPatternMatchToRangeMessage(match: PatternMatch) { const { name, defs } = match; return defs .map((d) => d.matches .map((range) => ({ range, elapsedTime: d.elapsedTime })) .map(({ range, elapsedTime }) => ({ range, message: createHoverMessage(name, elapsedTime) })) ) .reduce((a, m) => a.concat(m), []); } function clearDecorations() { activeEditor?.setDecorations(decorationTypeExclude, []); } function createHoverMessage(name: string, elapsedTime: number) { const r = new vscode.MarkdownString().appendText(name + ' ' + elapsedTime.toFixed(2) + 'ms'); return r; } function triggerUpdateDecorations() { if (timeout) { clearTimeout(timeout); timeout = undefined; } timeout = setTimeout(updateDecorations, 100); } if (activeEditor) { triggerUpdateDecorations(); } vscode.window.onDidChangeActiveTextEditor( (editor) => { if (isActive) { activeEditor = editor; if (editor) { triggerUpdateDecorations(); } } }, null, context.subscriptions ); vscode.workspace.onDidChangeTextDocument( (event) => { if (isActive && activeEditor && event.document === activeEditor.document) { triggerUpdateDecorations(); } }, null, context.subscriptions ); function disposeCurrent() { // current?.execResult?.dispose(); } function userTestRegExp(defaultRegexp?: string) { function validateInput(input: string) { try { toRegExp(input, 'g'); } catch (e) { return format(e); } } pattern = defaultRegexp || pattern; const p = vscode.window .showInputBox({ prompt: 'Enter a Regular Expression', placeHolder: 'Example: /\bw+/g', value: pattern?.toString(), validateInput, }) .then((value) => { pattern = value ? value : undefined; updateHistory(pattern); triggerUpdateDecorations(); }); return logErrors(p, 'userTestRegExp'); } function isNonEmptyString(s: string | undefined): s is string { return typeof s === 'string' && !!s; } function updateHistory(pattern?: string) { const unique = new Set([pattern].concat(history)); history = [...unique].filter(isNonEmptyString); history.length = Math.min(history.length, MAX_HISTORY_LENGTH); } function userSelectRegExp(selectedRegExp?: string) { if (pattern === selectedRegExp) { pattern = undefined; } else { pattern = selectedRegExp; } updateHistory(pattern); triggerUpdateDecorations(); } function editRegExp(item: { treeItem: RegexpOutlineItem } | undefined) { if (item?.treeItem?.pattern) { triggerUpdateDecorations(); const { defs, name } = item.treeItem.pattern; userTestRegExp(defs[0]?.regexp || name); } } function updateIsActive() { const currentIsActive = isActive; isActive = fetchIsEnabledFromConfig(); if (currentIsActive == isActive) { return; } if (isActive) { activeEditor = vscode.window.activeTextEditor; triggerUpdateDecorations(); } else { clearDecorations(); } } function getPatternMatcherClient(): Promise<PatternMatcherClient> { if (!patternMatcherClient) { patternMatcherClient = PatternMatcherClient.create(context); } const client = patternMatcherClient; return client.onReady().then(() => client); } function dispose() { disposeCurrent(); for (const d of disposables) { d.dispose(); } disposables.clear(); } context.subscriptions.push( { dispose }, vscode.commands.registerCommand('cSpellRegExpTester.testRegExp', catchErrors(userTestRegExp, 'testRegExp', logError)), vscode.commands.registerCommand('cSpellRegExpTester.selectRegExp', userSelectRegExp), vscode.commands.registerCommand('cSpellRegExpTester.editRegExp', editRegExp), vscode.workspace.onDidChangeConfiguration(updateIsActive) ); } interface ExtractedPattern { category: string; pattern: string | NamedPattern; } function extractPatternsFromConfig(config: CSpellUserSettings | undefined, userPatterns: string[]): ExtractedPattern[] { const extractedPatterns: ExtractedPattern[] = []; userPatterns.forEach((p) => extractedPatterns.push({ category: 'User Patterns', pattern: p })); config?.includeRegExpList?.forEach((p) => extractedPatterns.push({ category: 'Include Regexp List', pattern: p.toString() })); config?.ignoreRegExpList?.forEach((p) => extractedPatterns.push({ category: 'Exclude Regexp List', pattern: p.toString() })); config?.patterns?.forEach((p) => extractedPatterns.push({ category: 'Patterns', pattern: mapPatternDef(p) })); return extractedPatterns; } interface PatternDef { name: string; pattern: string | RegExp | (string | RegExp)[]; } function mapPatternDef(r: PatternDef): NamedPattern { const { name, pattern } = r; function cvtR(r: string | RegExp): string { return r.toString(); } function cvt(p: PatternDef['pattern']): string | string[] { if (Array.isArray(p)) { return p.map(cvtR); } return cvtR(p); } return { name, pattern: cvt(pattern), }; } function fetchIsEnabledFromConfig(): boolean { const cfg = vscode.workspace.getConfiguration(extensionId); return !!cfg?.get('experimental.enableRegexpView'); }
the_stack
import { assert, arrayEquals, baseType, CompositeType, entityTypeName, Field, FieldSelection, FragmentElement, FragmentSelection, isAbstractType, isCompositeType, isListType, isObjectType, isNamedType, ListType, NonNullType, ObjectType, Operation, OperationPath, sameOperationPaths, Schema, SchemaRootKind, Selection, SelectionSet, selectionSetOf, selectionSetOfPath, Type, UnionType, Variable, VariableDefinition, VariableDefinitions, newDebugLogger, selectionOfElement, selectionSetOfElement, NamedFragments, operationToDocument, MapWithCachedArrays, } from "@apollo/federation-internals"; import { advanceSimultaneousPathsWithOperation, Edge, emptyContext, ExcludedEdges, FieldCollection, QueryGraph, GraphPath, isPathContext, isRootPathTree, OpGraphPath, OpPathTree, OpRootPathTree, PathContext, PathTree, RootVertex, Vertex, isRootVertex, ExcludedConditions, advanceOptionsToString, ConditionResolution, unsatisfiedConditionsResolution, cachingConditionResolver, ConditionResolver, additionalKeyEdgeForRequireEdge, addConditionExclusion, SimultaneousPathsWithLazyIndirectPaths, simultaneousPathsToString, SimultaneousPaths, terminateWithNonRequestedTypenameField, } from "@apollo/query-graphs"; import { DocumentNode, stripIgnoredCharacters, print, GraphQLError, parse } from "graphql"; import { QueryPlan, ResponsePath, SequenceNode, PlanNode, ParallelNode, FetchNode, trimSelectionNodes } from "./QueryPlan"; const debug = newDebugLogger('plan'); // If a query can be resolved by more than this number of plans, we'll try to reduce the possible options we'll look // at to get it below this number to void query planning running forever. // Note that this number is a tad arbitrary: it's a nice round number that, on my laptop, ensure query planning don't // take more than a handful of seconds. // Note: exported so we can have a test that explicitly requires more than this number. export const MAX_COMPUTED_PLANS = 10000; function mapOptionsToSelections<RV extends Vertex>( selectionSet: SelectionSet, options: SimultaneousPathsWithLazyIndirectPaths<RV>[] ): [Selection, SimultaneousPathsWithLazyIndirectPaths<RV>[]][] { // We reverse the selections because we're going to pop from `openPaths` and this ensure we end up handling things in the query order. return selectionSet.selections(true).map(node => [node, options]); } class QueryPlanningTaversal<RV extends Vertex> { // The stack contains all states that aren't terminal. private bestPlan: [FetchDependencyGraph, OpPathTree<RV>, number] | undefined; private readonly isTopLevel: boolean; private conditionResolver: ConditionResolver; private stack: [Selection, SimultaneousPathsWithLazyIndirectPaths<RV>[]][]; private readonly closedBranches: SimultaneousPaths<RV>[][] = []; constructor( readonly supergraphSchema: Schema, readonly subgraphs: QueryGraph, selectionSet: SelectionSet, readonly variableDefinitions: VariableDefinitions, private readonly startVertex: RV, private readonly rootKind: SchemaRootKind, readonly costFunction: CostFunction, initialContext: PathContext, excludedEdges: ExcludedEdges = [], excludedConditions: ExcludedConditions = [], ) { this.isTopLevel = isRootVertex(startVertex); this.conditionResolver = cachingConditionResolver( subgraphs, (edge, context, excludedEdges, excludedConditions) => this.resolveConditionPlan(edge, context, excludedEdges, excludedConditions), ); const initialPath: OpGraphPath<RV> = GraphPath.create(subgraphs, startVertex); const initialOptions = [ new SimultaneousPathsWithLazyIndirectPaths([initialPath], initialContext, this.conditionResolver, excludedEdges, excludedConditions)]; this.stack = mapOptionsToSelections(selectionSet, initialOptions); } private debugStack() { if (this.isTopLevel && debug.enabled) { debug.group('Query planning open branches:'); for (const [selection, options] of this.stack) { debug.groupedValues(options, opt => `${simultaneousPathsToString(opt)}`, `${selection}:`); } debug.groupEnd(); } } findBestPlan(): [FetchDependencyGraph, OpPathTree<RV>, number] | undefined { while (this.stack.length > 0) { this.debugStack(); const [selection, options] = this.stack.pop()!; this.handleOpenBranch(selection, options); } this.computeBestPlanFromClosedBranches(); return this.bestPlan; } private handleOpenBranch(selection: Selection, options: SimultaneousPathsWithLazyIndirectPaths<RV>[]) { const operation = selection.element(); let newOptions: SimultaneousPathsWithLazyIndirectPaths<RV>[] = []; for (const option of options) { const followupForOption = advanceSimultaneousPathsWithOperation(this.supergraphSchema, option, operation); if (!followupForOption) { // There is no valid way to advance the current `operation` from this option, so this option is a dead branch // that cannot produce a valid query plan. So we simply ignore it and rely on other options. continue; } if (followupForOption.length === 0) { // This `operation` is valid from that option but is guarantee to yield no result (it's a type condition that, along // with prior condition, has no intersection). Given that (assuming the user do properly resolve all versions of a // given field the same way from all subgraphs) all options should return the same results, we know that operation // should return no result from all options (even if we can't provide it technically). // More concretely, this usually means the current operation is a type condition that has no intersection with the possible // current runtime types at this point, and this means whatever fields the type condition sub-selection selects, they // will never be part of the results. That said, we cannot completely ignore the type-condition/fragment or we'd end // up with the wrong results. Consider the example a sub-part of the query is : // { // foo { // ... on Bar { // field // } // } // } // and suppose that `... on Bar` can never match a concrete runtime type at this point. Because that's the only sub-selection // of `foo`, if we completely ignore it, we'll end up not querying this at all. Which means that, during execution, // we'd either return (for that sub-part of the query) `{ foo: null }` if `foo` happens to be nullable, or just `null` for // the whole sub-part otherwise. But what we *should* return (assuming foo doesn't actually return `null`) is `{ foo: {} }`. // Meaning, we have queried `foo` and it returned something, but it's simply not a `Bar` and so nothing was included. // Long story short, to avoid that situation, we replace the whole `... on Bar` section that can never match the runtime // type by simply getting the `__typename` of `foo`. This ensure we do query `foo` but don't end up including condiditions // that may not even make sense to the subgraph we're querying. // Do note that we'll only need that `__typename` if there is no other selections inside `foo`, and so we might include // it unecessarally in practice: it's a very minor inefficiency though. if (operation.kind === 'FragmentElement') { this.closedBranches.push([option.paths.map(p => terminateWithNonRequestedTypenameField(p))]); } return; } newOptions = newOptions.concat(followupForOption); } if (newOptions.length === 0) { // If we have no options, it means there is no way to build a plan for that branch, and // that means the whole query planning has no plan. // This should never happen for a top-level query planning (unless the supergraph has *not* been // validated), but can happen when computing sub-plans for a key condition. if (this.isTopLevel) { debug.log(`No valid options to advance ${selection} from ${advanceOptionsToString(options)}`); throw new Error(`Was not able to find any options for ${selection}: This shouldn't have happened.`); } else { // We clear both open branches and closed ones as a mean to terminate the plan computation with // no plan this.stack.splice(0, this.stack.length); this.closedBranches.splice(0, this.closedBranches.length); return; } } if (selection.selectionSet) { for (const branch of mapOptionsToSelections(selection.selectionSet, newOptions)) { this.stack.push(branch); } } else { const updated = this.maybeEliminateStrictlyMoreCostlyPaths(newOptions); this.closedBranches.push(updated); } } // This method should be applied to "final" paths, that is when the tail of the paths is a leaf field. // TODO: this method was added for cases where we had the following options: // 1) _ -[f1]-> T1(A) -[f2]-> T2(A) -[f3]-> T3(A) -[f4]-> Int(A) // 2) _ -[f1]-> T1(A) -[f2]-> T2(A) -[key]-> T2(B) -[f3]-> T3(B) -[f4] -> Int(B) // where clearly the 2nd option is not necessary (we're in A up to T2 in both case, so staying in A is never // going to be more expensive that going to B; note that if _other_ branches do jump to B after T2(A) for // other fieleds, the option 2 might well lead to a plan _as_ efficient as with option 1, but it will // not be _more_ efficient). // Anyway, while the implementation does handle this case, I believe it's a bit over-generic and can // eliminiate options we could want to keep. Double-check that and fix. private maybeEliminateStrictlyMoreCostlyPaths(options: SimultaneousPathsWithLazyIndirectPaths<RV>[]): SimultaneousPaths<RV>[] { if (options.length === 1) { return [options[0].paths]; } const singlePathOptions = options.filter(opt => opt.paths.length === 1); if (singlePathOptions.length === 0) { // we can't easily compare multi-path options return options.map(opt => opt.paths); } let minJumps = Number.MAX_SAFE_INTEGER; let withMinJumps: SimultaneousPaths<RV>[] = []; for (const option of singlePathOptions) { const jumps = option.paths[0].subgraphJumps(); if (jumps < minJumps) { minJumps = jumps; withMinJumps = [option.paths]; } else if (jumps === minJumps) { withMinJumps.push(option.paths); } } // We then look at multi-path options. We can exclude those if the path with the least amount of jumps is // more than our minJumps for (const option of singlePathOptions.filter(opt => opt.paths.length > 1)) { const jumps = option.paths.reduce((acc, p) => Math.min(acc, p.subgraphJumps()), Number.MAX_SAFE_INTEGER); if (jumps <= minJumps) { withMinJumps.push(option.paths); } } return withMinJumps; } private newDependencyGraph(): FetchDependencyGraph { return FetchDependencyGraph.create(this.subgraphs); } // Moves the first closed branch to after any branch having more options. // This method assumes that closed branches are sorted by decreasing number of options _except_ for the first element // which may be out of order, and this method restore that order. private reorderFirstBranch() { const firstBranch = this.closedBranches[0]; let i = 1; while (i < this.closedBranches.length && this.closedBranches[i].length > firstBranch.length) { i++; } // `i` is the smallest index of an element having the same number or less options than the first one, // so we switch that first branch with the element "before" `i` (which has more elements). this.closedBranches[0] = this.closedBranches[i - 1]; this.closedBranches[i - 1] = firstBranch; } private computeBestPlanFromClosedBranches() { if (this.closedBranches.length === 0) { return; } // We've computed all branches and need to compare all the possible plans to pick the best. // Note however that "all the possible plans" is essentially a cartesian product of all // the closed branches options, and if a lot of branches have multiple options, this can // exponentially explode. // So we first look at how many plans we'd have to generate, and if it's "too much", we // reduce it to something manageable by arbitrarilly throwing out options. This effectively // means that when a query has too many options, we give up on always finding the "best" // query plan in favor of an "ok" query plan. // TODO: currently, when we need to reduce options, we do so somewhat arbitrarilly. More // precisely, we reduce the branches with the most options first and then drop the last // option of the branch, repeating until we have a reasonable number of plans to consider. // However, there is likely ways to drop options in a more "intelligent" way. // We sort branches by those that have the most options first. this.closedBranches.sort((b1, b2) => b1.length > b2.length ? -1 : (b1.length < b2.length ? 1 : 0)); let planCount = possiblePlans(this.closedBranches); debug.log(() => `Query has ${planCount} possible plans`); let firstBranch = this.closedBranches[0]; while (planCount > MAX_COMPUTED_PLANS && firstBranch.length > 1) { // we remove the right-most option of the first branch, and them move that branch to it's new place. const prevSize = firstBranch.length; firstBranch.pop(); planCount -= planCount / prevSize; this.reorderFirstBranch(); // Note that if firstBranch is our only branch, it's fine, we'll continue to remove options from // it (but that is beyond unlikely). firstBranch = this.closedBranches[0]; debug.log(() => `Reduced plans to consider to ${planCount} plans`); } debug.log(() => `All branches:${this.closedBranches.map((opts, i) => `\n${i}:${opts.map((opt => `\n - ${simultaneousPathsToString(opt)}`))}`)}`); // Note that usually, we'll have a majority of branches with just one option. We can group them in // a PathTree first with no fuss. When then need to do a cartesian product between this created // tree an other branches however to build the possible plans and chose. let idxFirstOfLengthOne = 0; while (idxFirstOfLengthOne < this.closedBranches.length && this.closedBranches[idxFirstOfLengthOne].length > 1) { idxFirstOfLengthOne++; } let initialTree: OpPathTree<RV>; let initialDependencyGraph: FetchDependencyGraph; if (idxFirstOfLengthOne === this.closedBranches.length) { initialTree = PathTree.createOp(this.subgraphs, this.startVertex); initialDependencyGraph = this.newDependencyGraph(); } else { initialTree = PathTree.createFromOpPaths(this.subgraphs, this.startVertex, this.closedBranches.slice(idxFirstOfLengthOne).flat(2)); initialDependencyGraph = this.updatedDependencyGraph(this.newDependencyGraph(), initialTree); if (idxFirstOfLengthOne === 0) { // Well, we have the only possible plan; it's also the best. this.onNewPlan(initialDependencyGraph, initialTree); return; } } const otherTrees = this.closedBranches.slice(0, idxFirstOfLengthOne).map(b => b.map(opt => PathTree.createFromOpPaths(this.subgraphs, this.startVertex, opt))); this.generateAllPlans(initialDependencyGraph, initialTree, otherTrees); } generateAllPlans(initialDependencyGraph: FetchDependencyGraph, initialTree: OpPathTree<RV>, others: OpPathTree<RV>[][]) { // Track, for each element, at which index we are const eltIndexes = new Array<number>(others.length); let totalCombinations = 1; for (let i = 0; i < others.length; ++i) { const eltSize = others[i].length; assert(eltSize, "Got empty option: this shouldn't have happened"); if(!eltSize) { totalCombinations = 0; break; } eltIndexes[i] = 0; totalCombinations *= eltSize; } for (let i = 0; i < totalCombinations; ++i){ const dependencyGraph = initialDependencyGraph.clone(); let tree = initialTree; for (let j = 0; j < others.length; ++j) { const t = others[j][eltIndexes[j]]; this.updatedDependencyGraph(dependencyGraph, t); tree = tree.merge(t); } this.onNewPlan(dependencyGraph, tree); for (let idx = 0; idx < others.length; ++idx) { if (eltIndexes[idx] == others[idx].length - 1) { eltIndexes[idx] = 0; } else { eltIndexes[idx] += 1; break; } } } } private cost(dependencyGraph: FetchDependencyGraph): number { return this.costFunction.finalize(dependencyGraph.process(this.costFunction), true); } private updatedDependencyGraph(dependencyGraph: FetchDependencyGraph, tree: OpPathTree<RV>): FetchDependencyGraph { return isRootPathTree(tree) ? computeRootFetchGroups(dependencyGraph, tree, this.rootKind) : computeNonRootFetchGroups(dependencyGraph, tree, this.rootKind); } private resolveConditionPlan(edge: Edge, context: PathContext, excludedEdges: ExcludedEdges, excludedConditions: ExcludedConditions): ConditionResolution { const bestPlan = new QueryPlanningTaversal( this.supergraphSchema, this.subgraphs, edge.conditions!, this.variableDefinitions, edge.head, 'query', this.costFunction, context, excludedEdges, addConditionExclusion(excludedConditions, edge.conditions) ).findBestPlan(); // Note that we want to return 'null', not 'undefined', because it's the latter that means "I cannot resolve that // condition" within `advanceSimultaneousPathsWithOperation`. return bestPlan ? { satisfied: true, cost: bestPlan[2], pathTree: bestPlan[1] } : unsatisfiedConditionsResolution; } private onNewPlan(dependencyGraph: FetchDependencyGraph, tree: OpPathTree<RV>) { const cost = this.cost(dependencyGraph); //if (isTopLevel) { // console.log(`[PLAN] cost: ${cost}, path:\n${pathSet.toString('', true)}`); //} if (!this.bestPlan || cost < this.bestPlan[2]) { debug.log(() => this.bestPlan ? `Found better with cost ${cost} (previous had cost ${this.bestPlan[2]}): ${tree}`: `Computed plan with cost ${cost}: ${tree}`); this.bestPlan = [dependencyGraph, tree, cost]; } else { debug.log(() => `Ignoring plan with cost ${cost} (a better plan with cost ${this.bestPlan![2]} exists): ${tree}`); } } } function possiblePlans(closedBranches: SimultaneousPaths<any>[][]): number { let totalCombinations = 1; for (let i = 0; i < closedBranches.length; ++i){ const eltSize = closedBranches[i].length; if(!eltSize) { totalCombinations = 0; break; } totalCombinations *= eltSize; } return totalCombinations; } function sum(arr: number[]): number { return arr.reduce((a, b) => a + b, 0); } type CostFunction = FetchGroupProcessor<number, number[], number>; const fetchCost = 10000; const pipeliningCost = 100; const sameLevelFetchCost = 100; function selectionCost(selection?: SelectionSet, depth: number = 1): number { // The cost is essentially the number of elements in the selection, but we make deeped element cost a tiny bit more, mostly to make things a tad more // deterministic (typically, if we have an interface with a single implementation, then we can have a choice between a query plan that type-explode a // field of the interface and one that doesn't, and both will be almost identical, except that the type-exploded field will be a different depth; by // favoring lesser depth in that case, we favor not type-expoding). return selection ? selection.selections().reduce((prev, curr) => prev + depth + selectionCost(curr.selectionSet, depth + 1), 0) : 0; } const defaultCostFunction: CostFunction = { onFetchGroup: (group: FetchGroup) => selectionCost(group.selection), reduceParallel: (values: number[]) => values, // That math goes the following way: // - we add the costs in a sequence (the `acc + ...`) // - within a stage of the sequence, the groups are done in parallel, hence the `Math.max(...)` (but still, we prefer querying less services if // we can help it, hence the `+ (valueArray.length - 1) * sameLevelFetchCost`). // - but each group in a stage require a fetch, so we add a cost proportional to how many we have // - each group within a stage has its own cost plus a flat cost associated to doing that fetch (`fetchCost + s`). // - lastly, we also want to minimize the number of steps in the pipeline, so later stages are more costly (`idx * pipelineCost`) reduceSequence: (values: (number[] | number)[]) => values.reduceRight( (acc: number, value, idx) => { const valueArray = Array.isArray(value) ? value : [value]; return acc + ((idx + 1) * pipeliningCost) * (fetchCost * valueArray.length) * (Math.max(...valueArray) + (valueArray.length - 1) * sameLevelFetchCost) }, 0 ), finalize: (roots: number[], rootsAreParallel: boolean) => roots.length === 0 ? 0 : (rootsAreParallel ? (Math.max(...roots) + (roots.length - 1) * sameLevelFetchCost) : sum(roots)) }; function isIntrospectionSelection(selection: Selection): boolean { return selection.kind == 'FieldSelection' && selection.element().definition.isIntrospectionField(); } function withoutIntrospection(operation: Operation): Operation { // Note that, because we only apply this to the top-level selections, we skip all introspection, including // __typename. In general, we don't want o ignore __typename during query plans, but at top-level, we // can let the gateway execution deal with it rather than querying some service for that. if (!operation.selectionSet.selections().some(isIntrospectionSelection)) { return operation } const newSelections = operation.selectionSet.selections().filter(s => !isIntrospectionSelection(s)); return new Operation( operation.rootKind, new SelectionSet(operation.selectionSet.parentType).addAll(newSelections), operation.variableDefinitions, operation.name ); } export function computeQueryPlan(supergraphSchema: Schema, federatedQueryGraph: QueryGraph, operation: Operation): QueryPlan { if (operation.rootKind === 'subscription') { throw new GraphQLError( 'Query planning does not support subscriptions for now.', [parse(operation.toString())], ); } // We expand all fragments. This might merge a number of common branches and save us // some work, and we're going to expand everything during the algorithm anyway. operation = operation.expandAllFragments(); operation = withoutIntrospection(operation); debug.group(() => `Computing plan for\n${operation}`); if (operation.selectionSet.isEmpty()) { debug.groupEnd('Empty plan'); return { kind: 'QueryPlan' }; } const root = federatedQueryGraph.root(operation.rootKind); assert(root, () => `Shouldn't have a ${operation.rootKind} operation if the subgraphs don't have a ${operation.rootKind} root`); const processor = fetchGroupToPlanProcessor(operation.variableDefinitions, operation.selectionSet.fragments); if (operation.rootKind === 'mutation') { const dependencyGraphs = computeRootSerialDependencyGraph(supergraphSchema, operation, federatedQueryGraph, root); const rootNode = processor.finalize(dependencyGraphs.flatMap(g => g.process(processor)), false); debug.groupEnd('Mutation plan computed'); return { kind: 'QueryPlan', node: rootNode }; } else { const dependencyGraph = computeRootParallelDependencyGraph(supergraphSchema, operation, federatedQueryGraph, root); const rootNode = processor.finalize(dependencyGraph.process(processor), true); debug.groupEnd('Query plan computed'); return { kind: 'QueryPlan', node: rootNode }; } } function computeRootParallelDependencyGraph( supergraphSchema: Schema, operation: Operation, federatedQueryGraph: QueryGraph, root: RootVertex ): FetchDependencyGraph { return computeRootParallelBestPlan(supergraphSchema, operation.selectionSet, operation.variableDefinitions, federatedQueryGraph, root)[0]; } function computeRootParallelBestPlan( supergraphSchema: Schema, selection: SelectionSet, variables: VariableDefinitions, federatedQueryGraph: QueryGraph, root: RootVertex ): [FetchDependencyGraph, OpPathTree<RootVertex>, number] { const planningTraversal = new QueryPlanningTaversal( supergraphSchema, federatedQueryGraph, selection, variables, root, root.rootKind, defaultCostFunction, emptyContext ); const plan = planningTraversal.findBestPlan(); // Getting no plan means the query is essentially unsatisfiable (it's a valid query, but we can prove it will never return a result), // so we just return an empty plan. return plan ?? createEmptyPlan(federatedQueryGraph, root); } function createEmptyPlan( federatedQueryGraph: QueryGraph, root: RootVertex ): [FetchDependencyGraph, OpPathTree<RootVertex>, number] { return [ FetchDependencyGraph.create(federatedQueryGraph), PathTree.createOp(federatedQueryGraph, root), 0 ]; } function onlyRootSubgraph(graph: FetchDependencyGraph): string { const subgraphs = graph.rootSubgraphs(); assert(subgraphs.length === 1, () => `${graph} should have only one root, but has [${graph.rootSubgraphs()}]`); return subgraphs[0]; } function computeRootSerialDependencyGraph( supergraphSchema: Schema, operation: Operation, federatedQueryGraph: QueryGraph, root: RootVertex ): FetchDependencyGraph[] { // We have to serially compute a plan for each top-level selection. const splittedRoots = splitTopLevelFields(operation.selectionSet); const graphs: FetchDependencyGraph[] = []; let [prevDepGraph, prevPaths] = computeRootParallelBestPlan(supergraphSchema, splittedRoots[0], operation.variableDefinitions, federatedQueryGraph, root); let prevSubgraph = onlyRootSubgraph(prevDepGraph); for (let i = 1; i < splittedRoots.length; i++) { const [newDepGraph, newPaths] = computeRootParallelBestPlan(supergraphSchema, splittedRoots[i], operation.variableDefinitions, federatedQueryGraph, root); const newSubgraph = onlyRootSubgraph(newDepGraph); if (prevSubgraph === newSubgraph) { // The new operation (think 'mutation' operation) is on the same subgraph than the previous one, so we can conat them in a single fetch // and rely on the subgraph to enforce seriability. Do note that we need to `concat()` and not `merge()` because if we have // mutation Mut { // mut1 {...} // mut2 {...} // mut1 {...} // } // then we should _not_ merge the 2 `mut1` fields (contrarily to what happens on queried fields). prevPaths = prevPaths.concat(newPaths); prevDepGraph = computeRootFetchGroups(FetchDependencyGraph.create(federatedQueryGraph), prevPaths, root.rootKind); } else { graphs.push(prevDepGraph); [prevDepGraph, prevPaths, prevSubgraph] = [newDepGraph, newPaths, newSubgraph]; } } graphs.push(prevDepGraph); return graphs; } function splitTopLevelFields(selectionSet: SelectionSet): SelectionSet[] { return selectionSet.selections().flatMap(selection => { if (selection.kind === 'FieldSelection') { return [selectionSetOf(selectionSet.parentType, selection)]; } else { return splitTopLevelFields(selection.selectionSet).map(s => selectionSetOfElement(selection.element(), s)); } }); } function fetchGroupToPlanProcessor( variableDefinitions: VariableDefinitions, fragments?: NamedFragments ): FetchGroupProcessor<PlanNode, PlanNode, PlanNode | undefined> { return { onFetchGroup: (group: FetchGroup) => group.toPlanNode(variableDefinitions, fragments), reduceParallel: (values: PlanNode[]) => flatWrap('Parallel', values), reduceSequence: (values: PlanNode[]) => flatWrap('Sequence', values), finalize: (roots: PlanNode[], rootsAreParallel) => roots.length == 0 ? undefined : flatWrap(rootsAreParallel ? 'Parallel' : 'Sequence', roots) }; } function addToResponsePath(path: ResponsePath, responseName: string, type: Type) { path = path.concat(responseName); while (!isNamedType(type)) { if (isListType(type)) { path.push('@'); } type = type.ofType; } return path; } class LazySelectionSet { constructor( private _computed?: SelectionSet, private readonly _toCloneOnWrite?: SelectionSet ) { assert(_computed || _toCloneOnWrite, 'Should have one of the argument'); } forRead(): SelectionSet { return this._computed ? this._computed : this._toCloneOnWrite!; } forWrite(): SelectionSet { if (!this._computed) { this._computed = this._toCloneOnWrite!.clone(); } return this._computed; } clone(): LazySelectionSet { if (this._computed) { return new LazySelectionSet(undefined, this._computed); } else { return this; } } } class FetchGroup { private constructor( readonly dependencyGraph: FetchDependencyGraph, public index: number, readonly subgraphName: string, readonly rootKind: SchemaRootKind, readonly parentType: CompositeType, readonly isEntityFetch: boolean, private readonly _selection: LazySelectionSet, private readonly _inputs?: LazySelectionSet, readonly mergeAt?: ResponsePath, ) { } static create( dependencyGraph: FetchDependencyGraph, index: number, subgraphName: string, rootKind: SchemaRootKind, parentType: CompositeType, isEntityFetch: boolean, mergeAt?: ResponsePath, ): FetchGroup { return new FetchGroup( dependencyGraph, index, subgraphName, rootKind, parentType, isEntityFetch, new LazySelectionSet(new SelectionSet(parentType)), isEntityFetch ? new LazySelectionSet(new SelectionSet(parentType)) : undefined, mergeAt ); } clone(newDependencyGraph: FetchDependencyGraph): FetchGroup { return new FetchGroup( newDependencyGraph, this.index, this.subgraphName, this.rootKind, this.parentType, this.isEntityFetch, this._selection.clone(), this._inputs?.clone(), this.mergeAt ); } get isTopLevel(): boolean { return !this.mergeAt; } // It's important that the returned selection is never modified. Use the other modification methods of this method instead! get selection(): SelectionSet { return this._selection.forRead(); } // It's important that the returned selection is never modified. Use the other modification methods of this method instead! get inputs(): SelectionSet | undefined { return this._inputs?.forRead(); } clonedInputs(): LazySelectionSet | undefined { return this._inputs?.clone(); } addDependencyOn(groups: FetchGroup | FetchGroup[]) { this.dependencyGraph.addDependency(this, groups); } removeDependencyOn(groups: FetchGroup | FetchGroup[]) { this.dependencyGraph.removeDependency(this, groups); } addInputs(selection: Selection | SelectionSet) { assert(this._inputs, "Shouldn't try to add inputs to a root fetch group"); if (selection instanceof SelectionSet) { this._inputs.forWrite().mergeIn(selection); } else { this._inputs.forWrite().add(selection); } } addSelection(path: OperationPath) { this._selection.forWrite().addPath(path); } addSelections(selection: SelectionSet) { this._selection.forWrite().mergeIn(selection); } mergeIn(toMerge: FetchGroup, mergePath: OperationPath) { assert(!toMerge.isTopLevel, () => `Shouldn't merge top level group ${toMerge} into ${this}`); // Note that because toMerge is not top-level, the first "level" of it's selection is going to be a typeCast into the entity type // used to get to the group (because the entities() operation, which is called, returns the _Entity and _needs_ type-casting). // But when we merge-in, the type cast can be skipped. const selectionSet = selectionSetOfPath(mergePath, endOfPathSet => { assert(endOfPathSet, () => `Merge path ${mergePath} ends on a non-selectable type`); for (const typeCastSel of toMerge.selection.selections()) { assert(typeCastSel instanceof FragmentSelection, () => `Unexpected field selection ${typeCastSel} at top-level of ${toMerge} selection.`); endOfPathSet.mergeIn(typeCastSel.selectionSet); } }); this._selection.forWrite().mergeIn(selectionSet); this.dependencyGraph.onMergedIn(this, toMerge); } toPlanNode(variableDefinitions: VariableDefinitions, fragments?: NamedFragments) : PlanNode { addTypenameFieldForAbstractTypes(this.selection); this.selection.validate(); const inputs = this._inputs?.forRead(); if (inputs) { inputs.validate(); } const inputNodes = inputs ? inputs.toSelectionSetNode() : undefined; const operation = this.isEntityFetch ? operationForEntitiesFetch(this.dependencyGraph.subgraphSchemas.get(this.subgraphName)!, this.selection, variableDefinitions, fragments) : operationForQueryFetch(this.rootKind, this.selection, variableDefinitions, fragments); const fetchNode: FetchNode = { kind: 'Fetch', serviceName: this.subgraphName, requires: inputNodes ? trimSelectionNodes(inputNodes.selections) : undefined, variableUsages: this.selection.usedVariables().map(v => v.name), operation: stripIgnoredCharacters(print(operation)), }; return this.isTopLevel ? fetchNode : { kind: 'Flatten', path: this.mergeAt!, node: fetchNode, }; } toString(): string { return this.isTopLevel ? `[${this.index}]${this.subgraphName}[${this._selection}]` : `[${this.index}]${this.subgraphName}@(${this.mergeAt})[${this._inputs} => ${this._selection}]`; } } function removeInPlace<T>(value: T, array: T[]) { const idx = array.indexOf(value); if (idx >= 0) { array.splice(idx, 1); } } interface FetchGroupProcessor<G, P, F> { onFetchGroup(group: FetchGroup, isRootGroup: boolean): G; reduceParallel(values: G[]): P; reduceSequence(values: (G | P)[]): G; finalize(roots: G[], isParallel: boolean): F } type UnhandledGroups = [FetchGroup, UnhandledInEdges][]; type UnhandledInEdges = number[]; function sameMergeAt(m1: ResponsePath | undefined, m2: ResponsePath | undefined): boolean { if (!m1) { return !m2; } if (!m2) { return false; } return arrayEquals(m1, m2); } class FetchDependencyGraph { private isReduced: boolean = false; private constructor( readonly subgraphSchemas: ReadonlyMap<string, Schema>, readonly federatedQueryGraph: QueryGraph, private readonly rootGroups: MapWithCachedArrays<string, FetchGroup>, private readonly groups: FetchGroup[], private readonly adjacencies: number[][], private readonly inEdges: number[][], // For each groups, an optional path in its "unique" parent. If a group has more than one parent, then // this will be undefined. Even if the group has a unique parent, it's not guaranteed to be set. private readonly pathsInParents: (OperationPath | undefined)[] ) {} static create(federatedQueryGraph: QueryGraph) { return new FetchDependencyGraph( federatedQueryGraph.sources, federatedQueryGraph, new MapWithCachedArrays(), [], [], [], [] ); } clone(): FetchDependencyGraph { const cloned = new FetchDependencyGraph( this.subgraphSchemas, this.federatedQueryGraph, new MapWithCachedArrays<string, FetchGroup>(), new Array(this.groups.length), this.adjacencies.map(a => a.concat()), this.inEdges.map(a => a.concat()), this.pathsInParents.concat() ); for (let i = 0; i < this.groups.length; i++) { cloned.groups[i] = this.groups[i].clone(cloned); } for (const group of this.rootGroups.values()) { cloned.rootGroups.set(group.subgraphName, cloned.groups[group.index]); } return cloned; } getOrCreateRootFetchGroup(subgraphName: string, rootKind: SchemaRootKind, parentType: CompositeType): FetchGroup { let group = this.rootGroups.get(subgraphName); if (!group) { group = this.createRootFetchGroup(subgraphName, rootKind, parentType); this.rootGroups.set(subgraphName, group); } return group; } rootSubgraphs(): readonly string[] { return this.rootGroups.keys(); } createRootFetchGroup(subgraphName: string, rootKind: SchemaRootKind, parentType: CompositeType): FetchGroup { const group = this.newFetchGroup(subgraphName, parentType, false, rootKind); this.rootGroups.set(subgraphName, group); return group; } private newFetchGroup( subgraphName: string, parentType: CompositeType, isEntityFetch: boolean, rootKind: SchemaRootKind, // always "query" for entity fetches mergeAt?: ResponsePath, directParent?: FetchGroup, pathInParent?: OperationPath ): FetchGroup { this.onModification(); const newGroup = FetchGroup.create( this, this.groups.length, subgraphName, rootKind, parentType, isEntityFetch, mergeAt, ); this.groups.push(newGroup); this.adjacencies.push([]); this.inEdges.push([]); if (directParent) { this.addEdge(directParent.index, newGroup.index, pathInParent); } return newGroup; } getOrCreateKeyFetchGroup( subgraphName: string, mergeAt: ResponsePath, directParent: FetchGroup, pathInParent: OperationPath, conditionsGroups: FetchGroup[] ): FetchGroup { // Let's look if we can reuse a group we have, that is an existing dependent of the parent for // the same subgraph and same mergeAt and that is not part of our condition dependencies (the latter // meaning that we cannot reuse a group that fetched something we actually as input. for (const existing of this.dependents(directParent)) { if (existing.subgraphName === subgraphName && existing.mergeAt && sameMergeAt(existing.mergeAt, mergeAt) && !this.isDependedOn(existing, conditionsGroups) ) { const existingPathInParent = this.pathInParent(existing); if (pathInParent && existingPathInParent && !sameOperationPaths(existingPathInParent, pathInParent)) { this.pathsInParents[existing.index] = undefined; } return existing; } } const entityType = this.subgraphSchemas.get(subgraphName)!.type(entityTypeName)! as UnionType; return this.newFetchGroup(subgraphName, entityType, true, 'query', mergeAt, directParent, pathInParent); } newRootTypeFetchGroup( subgraphName: string, rootKind: SchemaRootKind, parentType: ObjectType, mergeAt: ResponsePath, directParent: FetchGroup, pathInParent: OperationPath, ): FetchGroup { return this.newFetchGroup(subgraphName, parentType, false, rootKind, mergeAt, directParent, pathInParent); } // Returns true if `toCheck` is either part of `conditions`, or is a dependency (potentially recursively) // of one of the gorup of conditions. private isDependedOn(toCheck: FetchGroup, conditions: FetchGroup[]): boolean { const stack = conditions.concat(); while (stack.length > 0) { const group = stack.pop()!; if (toCheck.index === group.index) { return true; } stack.push(...this.dependencies(group)); } return false; } newKeyFetchGroup( subgraphName: string, mergeAt: ResponsePath, ): FetchGroup { const entityType = this.subgraphSchemas.get(subgraphName)!.type(entityTypeName)! as UnionType; return this.newFetchGroup(subgraphName, entityType, true, 'query', mergeAt); } addDependency(dependentGroup: FetchGroup, dependentOn: FetchGroup | FetchGroup[]) { this.onModification(); const groups = Array.isArray(dependentOn) ? dependentOn : [ dependentOn ]; for (const group of groups) { this.addEdge(group.index, dependentGroup.index); } } removeDependency(dependentGroup: FetchGroup, dependentOn: FetchGroup | FetchGroup[]) { this.onModification(); const groups = Array.isArray(dependentOn) ? dependentOn : [ dependentOn ]; for (const group of groups) { this.removeEdge(group.index, dependentGroup.index); } } pathInParent(group: FetchGroup): OperationPath | undefined { return this.pathsInParents[group.index]; } private addEdge(from: number, to: number, pathInFrom?: OperationPath) { if (!this.adjacencies[from].includes(to)) { this.adjacencies[from].push(to); this.inEdges[to].push(from); const parentsCount = this.inEdges[to].length; if (pathInFrom && parentsCount === 1) { this.pathsInParents[to] = pathInFrom; } else if (parentsCount > 1) { this.pathsInParents[to] = undefined; } } } private removeEdge(from: number, to: number) { if (this.adjacencies[from].includes(to)) { removeInPlace(to, this.adjacencies[from]); removeInPlace(from, this.inEdges[to]); // If this was the only edge, we should erase the path. If it wasn't, we shouldn't have add a path in the // first place, so setting to undefined is harmless. this.pathsInParents[to] = undefined; } } onMergedIn(mergedInto: FetchGroup, merged: FetchGroup) { assert(!merged.isTopLevel, "Shouldn't remove top level groups"); this.onModification(); this.relocateDependentsOnMergedIn(mergedInto, merged.index); this.removeInternal(merged.index); } private relocateDependentsOnMergedIn(mergedInto: FetchGroup, mergedIndex: number) { for (const dependentIdx of this.adjacencies[mergedIndex]) { this.addEdge(mergedInto.index, dependentIdx); // While at it, we also remove the in-edge of the dependent to `merged` if it exists. const idxInIns = this.inEdges[dependentIdx].indexOf(mergedIndex); if (idxInIns >= 0) { this.inEdges[dependentIdx].splice(idxInIns, 1); } } } remove(group: FetchGroup) { this.onModification(); const dependents = this.dependents(group); const dependencies = this.dependencies(group); assert(dependents.length === 0, () => `Cannot remove group ${group} with dependents [${dependents}]`); assert(dependencies.length <= 1, () => `Cannot remove group ${group} with more/less than one dependency: [${dependencies}]`); this.removeInternal(group.index); } private removeInternal(mergedIndex: number) { // We remove `merged` from any it depends on for (const dependedIdx of this.inEdges[mergedIndex]) { const idxInAdj = this.adjacencies[dependedIdx].indexOf(mergedIndex); this.adjacencies[dependedIdx].splice(idxInAdj, 1); } // We then remove the entries for the merged group. this.groups.splice(mergedIndex, 1); this.adjacencies.splice(mergedIndex, 1); this.inEdges.splice(mergedIndex, 1); // But now, every group index above `merge.index` is one-off. this.groups.forEach(g => { if (g.index > mergedIndex) { --g.index; } }); this.adjacencies.forEach(adj => { adj.forEach((v, i) => { if (v > mergedIndex) { adj[i] = v - 1; } })}); this.inEdges.forEach(ins => { ins.forEach((v, i) => { if (v > mergedIndex) { ins[i] = v - 1; } })}); } private onModification() { this.isReduced = false; } // Do a transitive reduction (https://en.wikipedia.org/wiki/Transitive_reduction) of the graph // We keep it simple and do a DFS from each vertex. The complexity is not amazing, but dependency // graphs between fetch groups will almost surely never be huge and query planning performance // is not paramount so this is almost surely "good enough". // After the transitive reduction, we also do an additional traversals to check for: // 1) fetches with no selection: this can happen when we have a require if the only field requested // was the one with the require and that forced some dependencies. Those fetch should have // no dependents and we can just remove them. // 2) fetches that are made in parallel to the same subgraph and the same path, and merge those. private reduce() { if (this.isReduced) { return; } for (const group of this.groups) { for (const adjacent of this.adjacencies[group.index]) { this.dfsRemoveRedundantEdges(group.index, adjacent); } } for (const group of this.rootGroups.values()) { this.removeEmptyGroups(group); } for (const group of this.rootGroups.values()) { this.mergeDependentFetchesForSameSubgraphAndPath(group); } this.isReduced = true; } private removeEmptyGroups(group: FetchGroup) { const dependents = this.dependents(group); if (group.selection.isEmpty()) { assert(dependents.length === 0, () => `Empty group ${group} has dependents: ${dependents}`); this.remove(group); } for (const g of dependents) { this.removeEmptyGroups(g); } } private mergeDependentFetchesForSameSubgraphAndPath(group: FetchGroup) { const dependents = this.dependents(group); if (dependents.length > 1) { for (const g1 of dependents) { for (const g2 of dependents) { if (g1.index !== g2.index && g1.subgraphName === g2.subgraphName && sameMergeAt(g1.mergeAt, g2.mergeAt) && this.dependencies(g1).length === 1 && this.dependencies(g2).length === 1 ) { // We replace g1 by a new group that is the same except (possibly) for it's parentType ... // (that's why we don't use `newKeyFetchGroup`, it assigns the index while we reuse g1's one here) const merged = FetchGroup.create(this, g1.index, g1.subgraphName, g1.rootKind, g1.selection.parentType, g1.isEntityFetch, g1.mergeAt); // Erase the pathsInParents as it's now potentially invalid (we won't really use it from that point on, but better // safe than sorry). this.pathsInParents[g1.index] = undefined; if (g1.inputs) { merged.addInputs(g1.inputs); } merged.addSelections(g1.selection); this.groups[merged.index] = merged; // ... and then merge g2 into that. if (g2.inputs) { merged.addInputs(g2.inputs); } merged.addSelections(g2.selection); this.onMergedIn(merged, g2); // As we've just changed the dependency graph, our current iterations are kind of invalid anymore. So // we simply call ourselves back on the current group, which will retry the newly modified dependencies. this.mergeDependentFetchesForSameSubgraphAndPath(group); return; } } } } // Now recurse to the sub-groups. for (const g of dependents) { this.mergeDependentFetchesForSameSubgraphAndPath(g); } } dependencies(group: FetchGroup): FetchGroup[] { return this.inEdges[group.index].map(i => this.groups[i]); } dependents(group: FetchGroup): FetchGroup[] { return this.adjacencies[group.index].map(i => this.groups[i]); } private dfsRemoveRedundantEdges(parentVertex: number, startVertex: number) { const parentAdjacencies = this.adjacencies[parentVertex]; const stack = [ ...this.adjacencies[startVertex] ]; while (stack.length > 0) { const v = stack.pop()!; removeInPlace(v, parentAdjacencies); removeInPlace(parentVertex, this.inEdges[v]); stack.push(...this.adjacencies[v]); } } private outGroups(group: FetchGroup): FetchGroup[] { return this.adjacencies[group.index].map(i => this.groups[i]); } private inGroups(group: FetchGroup): FetchGroup[] { return this.inEdges[group.index].map(i => this.groups[i]); } private processGroup<G, P, F>( processor: FetchGroupProcessor<G, P, F>, group: FetchGroup, isRootGroup: boolean ): [G, UnhandledGroups] { const outGroups = this.outGroups(group); const processed = processor.onFetchGroup(group, isRootGroup); if (outGroups.length == 0) { return [processed, []]; } const allOutGroupsHaveThisAsIn = outGroups.every(g => this.inGroups(g).length === 1); if (allOutGroupsHaveThisAsIn) { const nodes: (G | P)[] = [processed]; let nextNodes = outGroups; let remainingNext: UnhandledGroups = []; while (nextNodes.length > 0) { const [node, toHandle, remaining] = this.processParallelGroups(processor, nextNodes, remainingNext); nodes.push(node); const [canHandle, newRemaining] = this.mergeRemainings(remainingNext, remaining); remainingNext = newRemaining; nextNodes = canHandle.concat(toHandle); } return [processor.reduceSequence(nodes), remainingNext]; } else { // We return just the group, with all other groups to be handled after, but remembering that // this group edge has been handled. return [processed, outGroups.map(g => [g, this.inEdges[g.index].filter(e => e !== group.index)])]; } } private processParallelGroups<G, P, F>( processor: FetchGroupProcessor<G, P, F>, groups: FetchGroup[], remaining: UnhandledGroups ): [P, FetchGroup[], UnhandledGroups] { const parallelNodes: G[] = []; let remainingNext = remaining; const toHandleNext: FetchGroup[] = []; for (const group of groups) { const [node, remaining] = this.processGroup(processor, group, false); parallelNodes.push(node); const [canHandle, newRemaining] = this.mergeRemainings(remainingNext, remaining); toHandleNext.push(...canHandle); remainingNext = newRemaining; } return [ processor.reduceParallel(parallelNodes), toHandleNext, remainingNext ]; } private mergeRemainings(r1: UnhandledGroups, r2: UnhandledGroups): [FetchGroup[], UnhandledGroups] { const unhandled: UnhandledGroups = []; const toHandle: FetchGroup[] = []; for (const [g, edges] of r1) { const newEdges = this.mergeRemaingsAndRemoveIfFound(g, edges, r2); if (newEdges.length == 0) { toHandle.push(g); } else { unhandled.push([g, newEdges]) } } unhandled.push(...r2); return [toHandle, unhandled]; } private mergeRemaingsAndRemoveIfFound(group: FetchGroup, inEdges: UnhandledInEdges, otherGroups: UnhandledGroups): UnhandledInEdges { const idx = otherGroups.findIndex(g => g[0].index === group.index); if (idx < 0) { return inEdges; } else { const otherEdges = otherGroups[idx][1]; otherGroups.splice(idx, 1); // The uhandled are the one that are unhandled on both side. return inEdges.filter(e => otherEdges.includes(e)) } } process<G, P>(processor: FetchGroupProcessor<G, P, any>): G[] { this.reduce(); const rootNodes: G[] = this.rootGroups.values().map(rootGroup => { const [node, remaining] = this.processGroup(processor, rootGroup, true); assert(remaining.length == 0, `A root group should have no remaining groups unhandled`); return node; }); return rootNodes; } dumpOnConsole() { console.log('Groups:'); for (const group of this.groups) { console.log(` ${group}`); } console.log('Adjacencies:'); for (const [i, adj] of this.adjacencies.entries()) { console.log(` ${i} => [${adj.join(', ')}]`); } console.log('In-Edges:'); for (const [i, ins] of this.inEdges.entries()) { console.log(` ${i} => [${ins.join(', ')}]`); } } toString() : string { return this.rootGroups.values().map(g => this.toStringInternal(g, "")).join('\n'); } toStringInternal(group: FetchGroup, indent: string): string { const groupDependents = this.adjacencies[group.index]; return [indent + group.subgraphName + ' <- ' + groupDependents.map(i => this.groups[i].subgraphName).join(', ')] .concat(groupDependents .flatMap(g => this.adjacencies[g].length == 0 ? [] : this.toStringInternal(this.groups[g], indent + " "))) .join('\n'); } } function computeRootFetchGroups(dependencyGraph: FetchDependencyGraph, pathTree: OpRootPathTree, rootKind: SchemaRootKind): FetchDependencyGraph { // The root of the pathTree is one of the "fake" root of the subgraphs graph, which belongs to no subgraph but points to each ones. // So we "unpack" the first level of the tree to find out our top level groups (and initialize our stack). // Note that we can safely ignore the triggers of that first level as it will all be free transition, and we know we cannot have conditions. for (const [edge, _trigger, _conditions, child] of pathTree.childElements()) { assert(edge !== null, `The root edge should not be null`); const source = edge.tail.source; // The edge tail type is one of the subgraph root type, so it has to be an ObjectType. const rootType = edge.tail.type as ObjectType; const group = dependencyGraph.getOrCreateRootFetchGroup(source, rootKind, rootType); computeGroupsForTree(dependencyGraph, child, group); } return dependencyGraph; } function computeNonRootFetchGroups(dependencyGraph: FetchDependencyGraph, pathTree: OpPathTree, rootKind: SchemaRootKind): FetchDependencyGraph { const source = pathTree.vertex.source; // The edge tail type is one of the subgraph root type, so it has to be an ObjectType. const rootType = pathTree.vertex.type; assert(isCompositeType(rootType), () => `Should not have condition on non-selectable type ${rootType}`); const group = dependencyGraph.getOrCreateRootFetchGroup(source, rootKind, rootType); computeGroupsForTree(dependencyGraph, pathTree, group); return dependencyGraph; } function createNewFetchSelectionContext(type: CompositeType, selections: SelectionSet | undefined, context: PathContext): [Selection, OperationPath] { const typeCast = new FragmentElement(type, type.name); let inputSelection = selectionOfElement(typeCast, selections); let path = [typeCast]; if (context.isEmpty()) { return [inputSelection, path]; } const schema = type.schema(); // We add the first include/skip to the current typeCast and then wrap in additional type-casts for the next ones // if necessary. Note that we use type-casts (... on <type>), but, outside of the first one, we could well also // use fragments with no type-condition. We do the former mostly to preverve older behavior, but doing the latter // would technically procude slightly small query plans. const [name0, ifs0] = context.directives[0]; typeCast.applyDirective(schema.directive(name0)!, { 'if': ifs0 }); for (let i = 1; i < context.directives.length; i++) { const [name, ifs] = context.directives[i]; const fragment = new FragmentElement(type, type.name); fragment.applyDirective(schema.directive(name)!, { 'if': ifs }); inputSelection = selectionOfElement(fragment, selectionSetOf(type, inputSelection)); path = [fragment].concat(path); } return [inputSelection, path]; } function computeGroupsForTree( dependencyGraph: FetchDependencyGraph, pathTree: OpPathTree<any>, startGroup: FetchGroup, initialMergeAt: ResponsePath = [], initialPath: OperationPath = [], ): FetchGroup[] { const stack: [OpPathTree, FetchGroup, ResponsePath, OperationPath][] = [[pathTree, startGroup, initialMergeAt, initialPath]]; const createdGroups = [ ]; while (stack.length > 0) { const [tree, group, mergeAt, path] = stack.pop()!; if (tree.isLeaf()) { group.addSelection(path); } else { // We want to preserve the order of the elements in the child, but the stack will reverse everything, so we iterate // in reverse order to counter-balance it. for (const [edge, operation, conditions, child] of tree.childElements(true)) { if (isPathContext(operation)) { // The only 3 cases where we can take edge not "driven" by an operation is either when we resolve a key, resolve // a query (switch subgraphs because the query root type is the type of a field), or at the root of subgraph graph. // The latter case has already be handled the beginning of `computeFetchGroups` so only the 2 former remains. assert(edge !== null, () => `Unexpected 'null' edge with no trigger at ${path}`); assert(edge.head.source !== edge.tail.source, () => `Key/Query edge ${edge} should change the underlying subgraph`); if (edge.transition.kind === 'KeyResolution') { assert(conditions, () => `Key edge ${edge} should have some conditions paths`); // First, we need to ensure we fetch the conditions from the current group. const groupsForConditions = computeGroupsForTree(dependencyGraph, conditions, group, mergeAt, path); // Then we can "take the edge", creating a new group. That group depends // on the condition ones. const newGroup = dependencyGraph.getOrCreateKeyFetchGroup(edge.tail.source, mergeAt, group, path, groupsForConditions); createdGroups.push(newGroup); // The new group depends on the current group but 'newKeyFetchGroup' already handled that. newGroup.addDependencyOn(groupsForConditions); const type = edge.tail.type as CompositeType; // We shouldn't have a key on a non-composite type const inputSelections = new SelectionSet(type); inputSelections.add(new FieldSelection(new Field(type.typenameField()!))); inputSelections.mergeIn(edge.conditions!); const [inputs, newPath] = createNewFetchSelectionContext(type, inputSelections, operation); newGroup.addInputs(inputs); // We also ensure to get the __typename of the current type in the "original" group. group.addSelection(path.concat(new Field((edge.head.type as CompositeType).typenameField()!))); stack.push([child, newGroup, mergeAt, newPath]); } else { assert(edge.transition.kind === 'RootTypeResolution', () => `Unexpected non-collecting edge ${edge}`); const rootKind = edge.transition.rootKind; assert(!conditions, () => `Root type resolution edge ${edge} should not have conditions`); assert(isObjectType(edge.head.type) && isObjectType(edge.tail.type), () => `Expected an objects for the vertices of ${edge}`); const type = edge.tail.type; assert(type === type.schema().schemaDefinition.rootType(rootKind), () => `Expected ${type} to be the root ${rootKind} type, but that is ${type.schema().schemaDefinition.rootType(rootKind)}`); // We're querying a field `q` of a subgraph, get one of the root type, and follow with a query on another // subgraph. But that mean that on the original subgraph, we may not have added _any_ selection for // type `q` and that make the query to the original subgraph invalid. To avoid this, we request the // __typename field. group.addSelection(path.concat(new Field((edge.head.type as CompositeType).typenameField()!))); // We take the edge, creating a new group. Note that we always create a new group because this // correspond to jumping subgraph after a field returned the query root type, and we want to // preserve this ordering somewhat (debatable, possibly). const newGroup = dependencyGraph.newRootTypeFetchGroup(edge.tail.source, rootKind, type, mergeAt, group, path); const newPath = createNewFetchSelectionContext(type, undefined, operation)[1]; stack.push([child, newGroup, mergeAt, newPath]); } } else if (edge === null) { // A null edge means that the operation does nothing but may contain directives to preserve. // If it does contains directives, we preserve the operation, otherwise, we just skip it // as a minor optimization (it makes the query slighly smaller, but on complex queries, it // might also deduplicate similar selections). const newPath = operation.appliedDirectives.length === 0 ? path : path.concat(operation); stack.push([child, group, mergeAt, newPath]); } else { assert(edge.head.source === edge.tail.source, () => `Collecting edge ${edge} for ${operation} should not change the underlying subgraph`) let updatedGroup = group; let updatedMergeAt = mergeAt; let updatedPath = path; if (conditions) { // We have some @requires. [updatedGroup, updatedMergeAt, updatedPath] = handleRequires( dependencyGraph, edge, conditions, group, mergeAt, path ); } const newMergeAt = operation.kind === 'Field' ? addToResponsePath(updatedMergeAt, operation.responseName(), (edge.transition as FieldCollection).definition.type!) : updatedMergeAt; stack.push([child, updatedGroup, newMergeAt, updatedPath.concat(operation)]); } } } } return createdGroups; } function addTypenameFieldForAbstractTypes(selectionSet: SelectionSet) { for (const selection of selectionSet.selections()) { if (selection.kind == 'FieldSelection') { const fieldBaseType = baseType(selection.field.definition.type!); if (isAbstractType(fieldBaseType)) { selection.selectionSet!.add(new FieldSelection(new Field(fieldBaseType.typenameField()!))); } if (selection.selectionSet) { addTypenameFieldForAbstractTypes(selection.selectionSet); } } else { addTypenameFieldForAbstractTypes(selection.selectionSet); } } } function handleRequires( dependencyGraph: FetchDependencyGraph, edge: Edge, requiresConditions: OpPathTree, group: FetchGroup, mergeAt: ResponsePath, path: OperationPath ): [FetchGroup, ResponsePath, OperationPath] { // @requires should be on an entity type, and we only support object types right now const entityType = edge.head.type as ObjectType; // In general, we should do like for an edge, and create a new group _for the current subgraph_ // that depends on the createdGroups and have the created groups depend on the current one. // However, we can be more efficient in general (and this is expected by the user) because // required fields will usually come just after a key edge (at the top of a fetch group). // In that case (when the path is exactly 1 typeCast), we can put the created groups directly // as dependency of the current group, avoiding to create a new one. Additionally, if the // group we're coming from is our "direct parent", we can merge it to said direct parent (which // effectively means that the parent group will collect the provides before taking the edge // to our current group). if (!group.isTopLevel && path.length == 1 && path[0].kind === 'FragmentElement') { // We start by computing the groups for the conditions. We do this using a copy of the current // group (with only the inputs) as that allows to modify this copy without modifying `group`. const originalInputs = group.clonedInputs()!; const newGroup = dependencyGraph.newKeyFetchGroup(group.subgraphName, group.mergeAt!); newGroup.addInputs(originalInputs.forRead()); const createdGroups = computeGroupsForTree(dependencyGraph, requiresConditions, newGroup, mergeAt, path); if (createdGroups.length == 0) { // All conditions were local. Just merge the newly created group back in the current group (we didn't need it) // and continue. group.mergeIn(newGroup, path); return [group, mergeAt, path]; } // We know the @require needs createdGroups. We do want to know however if any of the conditions was // fetched from our `newGroup`. If not, then this means that `createdGroup` don't really depend on // the current `group`, but can be dependencies of the parent (or even merged into this parent). // To know this, we check if `newGroup` inputs contains its inputs (meaning the fetch is // useless: we jump to it but didn't get anything new). Not that this isn't perfect because // in the case of multiple keys between `newGroup` and its parent, we could theoretically take a // different key on the way in that on the way back. In other words, `newGroup` selection may only // be fetching a key that happens to not be the one in its inputs, and in that case the code below // will not remove `newGroup` even though it would be more efficient to do so. Handling this properly // is more complex however and it's sufficiently unlikely to happpen that we ignore that "optimization" // for now. If someone run into this and notice, we can optimize then. // Note: it is to be sure this test is not poluted by other things in `group` that we created `newGroup`. const newGroupIsUseless = newGroup.inputs!.contains(newGroup.selection); const parents = dependencyGraph.dependencies(group); const pathInParent = dependencyGraph.pathInParent(group); const unmergedGroups = []; if (newGroupIsUseless) { // We can remove `newGroup` and attach `createdGroups` as dependencies of `group`'s parents. That said, // as we do so, we check if one/some of the created groups can be "merged" into the parent // directly (assuming we have only 1 parent, it's the same subgraph/mergeAt and we known the path in this parent). // If it can, that essentially means that the requires could have been fetched directly from the parent, // and that will likely be common. for (const created of createdGroups) { // Note that pathInParent != undefined implies that parents is of size 1 if (pathInParent && created.subgraphName === parents[0].subgraphName && sameMergeAt(created.mergeAt, group.mergeAt) ) { parents[0].mergeIn(created, pathInParent); } else { // We move created from depending on `newGroup` to depend on all of `group`'s parents. created.removeDependencyOn(newGroup); created.addDependencyOn(parents); unmergedGroups.push(created); } } // We know newGroup is useless and nothing should depend on it anymore, we can remove it. dependencyGraph.remove(newGroup); } else { // There is things in `newGroup`, let's merge them in `group` (no reason not to). This will // make the created groups depend on `group`, which we want. group.mergeIn(newGroup, path); // The created group depend on `group` and the dependency cannot be moved to the parent in // this case. However, we might still be able to merge some created group directly in the // parent. But for this to be true, we should essentially make sure that the dependency // on `group` is not a "true" dependency. That is, if the created group inputs are the same // as `group` inputs (and said created group is the same subgraph than then parent of // `group`, then it means we're only depending on value that are already in the parent and // we merge the group). for (const created of createdGroups) { // Note that pathInParent != undefined implies that parents is of size 1 if (pathInParent && created.subgraphName === parents[0].subgraphName && sameMergeAt(created.mergeAt, group.mergeAt) && originalInputs.forRead().contains(created.inputs!) ) { parents[0].mergeIn(created, pathInParent); } else { unmergedGroups.push(created); } } } // If we've merged all the created groups, the all provides are handled _before_ we get to the // current group, so we can "continue" with the current group (and we remove the useless `newGroup`). if (unmergedGroups.length == 0) { // We still need to add the stuffs we require though (but `group` already has a key in its inputs, // we don't need one). group.addInputs(inputsForRequire(dependencyGraph.federatedQueryGraph, entityType, edge, false)[0]); return [group, mergeAt, path]; } // If we get here, it means the @require needs the information from `createdGroups` _and_ those // rely on some information from the current `group`. So we need to create a new group that // depends on all the created groups and return that. const postRequireGroup = dependencyGraph.newKeyFetchGroup(group.subgraphName, group.mergeAt!); postRequireGroup.addDependencyOn(unmergedGroups); const [inputs, newPath] = inputsForRequire(dependencyGraph.federatedQueryGraph, entityType, edge); // The post-require group needs both the inputs from `group` (the key to `group` subgraph essentially, and the additional requires conditions) postRequireGroup.addInputs(inputs); return [postRequireGroup, mergeAt, newPath]; } else { const createdGroups = computeGroupsForTree(dependencyGraph, requiresConditions, group, mergeAt, path); // If we didn't created any group, that means the whole condition was fetched from the current group // and we're good. if (createdGroups.length == 0) { return [group, mergeAt, path]; } // We need to create a new group, on the same subgraph `group`, where we resume fetching the field for // which we handle the @requires _after_ we've delt with the `requiresConditionsGroups`. // Note that we know the conditions will include a key for our group so we can resume properly. const newGroup = dependencyGraph.newKeyFetchGroup(group.subgraphName, mergeAt); newGroup.addDependencyOn(createdGroups); const [inputs, newPath] = inputsForRequire(dependencyGraph.federatedQueryGraph, entityType, edge); newGroup.addInputs(inputs); return [newGroup, mergeAt, newPath]; } } function inputsForRequire(graph: QueryGraph, entityType: ObjectType, edge: Edge, includeKeyInputs: boolean = true): [Selection, OperationPath] { const typeCast = new FragmentElement(entityType, entityType.name); const fullSelectionSet = new SelectionSet(entityType); fullSelectionSet.add(new FieldSelection(new Field(entityType.typenameField()!))); fullSelectionSet.mergeIn(edge.conditions!); if (includeKeyInputs) { fullSelectionSet.mergeIn(additionalKeyEdgeForRequireEdge(graph, edge).conditions!); } return [selectionOfElement(typeCast, fullSelectionSet), [typeCast]]; } const representationsVariable = new Variable('representations'); function representationsVariableDefinition(schema: Schema): VariableDefinition { const anyType = schema.type('_Any'); assert(anyType, `Cannot find _Any type in schema`); const representationsType = new NonNullType(new ListType(new NonNullType(anyType))); return new VariableDefinition(schema, representationsVariable, representationsType); } function operationForEntitiesFetch( subgraphSchema: Schema, selectionSet: SelectionSet, allVariableDefinitions: VariableDefinitions, fragments?: NamedFragments ): DocumentNode { const variableDefinitions = new VariableDefinitions(); variableDefinitions.add(representationsVariableDefinition(subgraphSchema)); variableDefinitions.addAll(allVariableDefinitions.filter(selectionSet.usedVariables())); const queryType = subgraphSchema.schemaDefinition.rootType('query'); assert(queryType, `Subgraphs should always have a query root (they should at least provides _entities)`); const entities = queryType.field('_entities'); assert(entities, `Subgraphs should always have the _entities field`); const entitiesCall: SelectionSet = new SelectionSet(queryType); entitiesCall.add(new FieldSelection( new Field(entities, { 'representations': representationsVariable }, variableDefinitions), selectionSet )); return operationToDocument(new Operation('query', entitiesCall, variableDefinitions).optimize(fragments)); } // Wraps the given nodes in a ParallelNode or SequenceNode, unless there's only // one node, in which case it is returned directly. Any nodes of the same kind // in the given list have their sub-nodes flattened into the list: ie, // flatWrap('Sequence', [a, flatWrap('Sequence', b, c), d]) returns a SequenceNode // with four children. function flatWrap( kind: ParallelNode['kind'] | SequenceNode['kind'], nodes: PlanNode[], ): PlanNode { assert(nodes.length !== 0, 'programming error: should always be called with nodes'); if (nodes.length === 1) { return nodes[0]; } return { kind, nodes: nodes.flatMap(n => (n.kind === kind ? n.nodes : [n])), }; } function operationForQueryFetch( rootKind: SchemaRootKind, selectionSet: SelectionSet, allVariableDefinitions: VariableDefinitions, fragments?: NamedFragments ): DocumentNode { const operation = new Operation(rootKind, selectionSet, allVariableDefinitions.filter(selectionSet.usedVariables())).optimize(fragments); return operationToDocument(operation); }
the_stack
import { TestBed, fakeAsync, tick, flush } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { Component } from '@angular/core'; import { numbers } from '@material/dialog'; import { FOCUS_TRAP_DIRECTIVES } from '../focus-trap/mdc.focus-trap.directive'; import { DIALOG_DIRECTIVES, MdcDialogDirective } from './mdc.dialog.directive'; import { BUTTON_DIRECTIVES } from '../button/mdc.button.directive'; const templateWithDialog = ` <button id="open" mdcButton (click)="dialog.open()">Open Dialog</button> <div id="dialog" #dialog="mdcDialog" mdcDialog> <div mdcDialogContainer> <div id="surface" mdcDialogSurface> <h2 mdcDialogTitle>Modal Dialog</h2> <div mdcDialogContent> Dialog Body <div *ngIf="scrollable" style="height: 2000px;">&nbsp;</div> <input id="someInput"> <button mdcButton id="noTrigger">no mdcDialogTrigger</button> </div> <footer mdcDialogActions> <button *ngIf="cancelButton" id="cancel" mdcButton mdcDialogTrigger="close">Decline</button> <button *ngIf="acceptButton" id="accept" mdcButton mdcDialogTrigger="accept" mdcDialogDefault>Accept</button> </footer> </div> </div> <div mdcDialogScrim></div> </div> `; const tickTime = Math.max(numbers.DIALOG_ANIMATION_CLOSE_TIME_MS, numbers.DIALOG_ANIMATION_OPEN_TIME_MS); describe('MdcDialogDirective', () => { @Component({ template: templateWithDialog }) class TestComponent { scrollable = false; cancelButton = true; acceptButton = true; } function setup() { const fixture = TestBed.configureTestingModule({ declarations: [...DIALOG_DIRECTIVES, ...FOCUS_TRAP_DIRECTIVES, ...BUTTON_DIRECTIVES, TestComponent] }).createComponent(TestComponent); fixture.detectChanges(); return { fixture }; } it('accessibility and structure', fakeAsync(() => { const { fixture } = setup(); validateDom(fixture.nativeElement.querySelector('#dialog')); })); it('should only display the dialog when opened', fakeAsync(() => { const { fixture } = setup(); const button = fixture.nativeElement.querySelector('#open'); const dialog = fixture.nativeElement.querySelector('#dialog'); const mdcDialog = fixture.debugElement.query(By.directive(MdcDialogDirective)).injector.get(MdcDialogDirective); const cancel = fixture.nativeElement.querySelector('#cancel'); const accept = fixture.nativeElement.querySelector('#accept'); // open/close by button: expect(dialog.classList.contains('mdc-dialog--open')).toBe(false, 'dialog must be in closed state'); button.click(); tick(tickTime); flush(); expect(dialog.classList.contains('mdc-dialog--open')).toBe(true, 'dialog must be in opened state'); cancel.click(); tick(tickTime); flush(); expect(dialog.classList.contains('mdc-dialog--open')).toBe(false, 'dialog must be in closed state'); button.click(); tick(tickTime); flush(); expect(dialog.classList.contains('mdc-dialog--open')).toBe(true, 'dialog must be in opened state'); accept.click(); tick(tickTime); flush(); expect(dialog.classList.contains('mdc-dialog--open')).toBe(false, 'dialog must be in closed state'); // open/close with function calls: mdcDialog.open(); tick(tickTime); flush(); expect(dialog.classList.contains('mdc-dialog--open')).toBe(true, 'dialog must be in opened state'); mdcDialog.close('accept'); tick(tickTime); flush(); expect(dialog.classList.contains('mdc-dialog--open')).toBe(false, 'dialog must be in closed state'); })); it('should trap focus to the dialog when opened', fakeAsync(() => { const { fixture } = setup(); const button = fixture.nativeElement.querySelector('#open'); const dialog = fixture.nativeElement.querySelector('#dialog'); const accept = fixture.nativeElement.querySelector('#accept'); expect(dialog.classList.contains('mdc-dialog--open')).toBe(false, 'dialog must be in closed state'); // no sentinels means no focus trapping: expect([...fixture.nativeElement.querySelectorAll('.mdc-dom-focus-sentinel')].length).toBe(0); button.click(); tick(tickTime); flush(); // should now have focus trap sentinels: expect([...fixture.nativeElement.querySelectorAll('.mdc-dom-focus-sentinel')].length).toBe(2); accept.click(); tick(tickTime); flush(); // focus trap should be cleaned up: expect([...fixture.nativeElement.querySelectorAll('.mdc-dom-focus-sentinel')].length).toBe(0); })); it('should initially focus mdcDialogDefault', fakeAsync(() => { const { fixture } = setup(); const button = fixture.nativeElement.querySelector('#open'); const accept = fixture.nativeElement.querySelector('#accept'); button.click(); tick(tickTime); flush(); expect(document.activeElement).toBe(accept); })); it('should apply dialog button styling to buttons dynamically added', fakeAsync(() => { const { fixture } = setup(); const button = fixture.nativeElement.querySelector('#open'); const testComponent = fixture.debugElement.injector.get(TestComponent); testComponent.cancelButton = false; testComponent.acceptButton = false; fixture.detectChanges(); button.click(); tick(tickTime); flush(); expect(fixture.nativeElement.querySelector('#cancel')).toBeNull(); testComponent.cancelButton = true; testComponent.acceptButton = true; fixture.detectChanges(); const cancel = fixture.nativeElement.querySelector('#cancel'); expect(cancel.classList).toContain('mdc-dialog__button'); const accept = fixture.nativeElement.querySelector('#accept'); expect(accept.classList).toContain('mdc-dialog__button'); expect(cancel.classList).toContain('mdc-dialog__button'); })); it('should emit the accept event', fakeAsync(() => { const { fixture } = setup(); const button = fixture.nativeElement.querySelector('#open'); const mdcDialog = fixture.debugElement.query(By.directive(MdcDialogDirective)).injector.get(MdcDialogDirective); const accept = fixture.nativeElement.querySelector('#accept'); button.click(); tick(tickTime); flush(); let accepted = false; mdcDialog.accept.subscribe(() => { accepted = true; }); accept.click(); tick(tickTime); flush(); expect(accepted).toBe(true); })); it('should emit the cancel event', fakeAsync(() => { const { fixture } = setup(); const button = fixture.nativeElement.querySelector('#open'); const mdcDialog = fixture.debugElement.query(By.directive(MdcDialogDirective)).injector.get(MdcDialogDirective); const cancel = fixture.nativeElement.querySelector('#cancel'); button.click(); tick(tickTime); flush(); let canceled = false; mdcDialog.cancel.subscribe(() => { canceled = true; }); cancel.click(); tick(tickTime); flush(); expect(canceled).toBe(true); })); it('should style the body according to the scrollable property', fakeAsync(() => { const { fixture } = setup(); const button = fixture.nativeElement.querySelector('#open'); const dialog = fixture.nativeElement.querySelector('#dialog'); const testComponent = fixture.debugElement.injector.get(TestComponent); testComponent.scrollable = true; fixture.detectChanges(); button.click(); tick(tickTime); flush(); expect(dialog.classList.contains('mdc-dialog--scrollable')).toBe(true, 'dialog content must be scrollable'); })); it('button without mdcDialogTrigger should not close the dialog', fakeAsync(() => { const { fixture } = setup(); const button = fixture.nativeElement.querySelector('#open'); const dialog = fixture.nativeElement.querySelector('#dialog'); const noTrigger = fixture.nativeElement.querySelector('#noTrigger'); button.click(); tick(tickTime); flush(); expect(dialog.classList.contains('mdc-dialog--open')).toBe(true, 'dialog must be in opened state'); noTrigger.click(); tick(tickTime); flush(); expect(dialog.classList.contains('mdc-dialog--open')).toBe(true, 'dialog must be in opened state'); })); it('enter should trigger mdcDialogDefault', fakeAsync(() => { const { fixture } = setup(); const button = fixture.nativeElement.querySelector('#open'); const dialog = fixture.nativeElement.querySelector('#dialog'); const mdcDialog = fixture.debugElement.query(By.directive(MdcDialogDirective)).injector.get(MdcDialogDirective); const input = fixture.nativeElement.querySelector('#someInput'); let accepted = false; mdcDialog.accept.subscribe(() => { accepted = true; }); button.click(); tick(tickTime); flush(); expect(dialog.classList.contains('mdc-dialog--open')).toBe(true, 'dialog must be in opened state'); input.focus(); expect(document.activeElement).toBe(input); input.dispatchEvent(newKeydownEvent('Enter')); tick(tickTime); flush(); expect(dialog.classList.contains('mdc-dialog--open')).toBe(false, 'dialog must be in closed state'); expect(accepted).toBe(true); })); it('escape should trigger cancel', fakeAsync(() => { const { fixture } = setup(); const dialog = fixture.nativeElement.querySelector('#dialog'); const mdcDialog = fixture.debugElement.query(By.directive(MdcDialogDirective)).injector.get(MdcDialogDirective); let canceled = false; mdcDialog.cancel.subscribe(() => { canceled = true; }); mdcDialog.open(); tick(tickTime); flush(); expect(dialog.classList.contains('mdc-dialog--open')).toBe(true, 'dialog must be in opened state'); document.body.dispatchEvent(newKeydownEvent('Escape')); tick(tickTime); flush(); expect(dialog.classList.contains('mdc-dialog--open')).toBe(false, 'dialog must be in closed state'); expect(canceled).toBe(true); })); function validateDom(dialog) { expect(dialog.classList).toContain('mdc-dialog'); expect(dialog.children.length).toBe(2); const container = dialog.children[0]; const scrim = dialog.children[1]; expect(container.classList).toContain('mdc-dialog__container'); expect(container.children.length).toBe(1); const surface = container.children[0]; expect(surface.classList).toContain('mdc-dialog__surface'); expect(surface.getAttribute('role')).toBe('alertdialog'); expect(surface.getAttribute('aria-modal')).toBe('true'); const labelledBy = surface.getAttribute('aria-labelledby'); expect(labelledBy).toMatch(/[a-zA-Z0-9_-]+/); const describedBy = surface.getAttribute('aria-describedby'); expect(describedBy).toMatch(/[a-zA-Z0-9_-]+/); expect(surface.children.length).toBe(3); const title = surface.children[0]; const content = surface.children[1]; const footer: Element = surface.children[2]; expect(title.classList).toContain('mdc-dialog__title'); expect(title.id).toBe(labelledBy); expect(content.classList).toContain('mdc-dialog__content'); expect(content.id).toBe(describedBy); expect(footer.classList).toContain('mdc-dialog__actions'); const buttons = [].slice.call(footer.children); for (let button of buttons) { expect(button.classList).toContain('mdc-button'); expect(button.classList).toContain('mdc-dialog__button'); } expect(scrim.classList).toContain('mdc-dialog__scrim'); } function newKeydownEvent(key: string) { let event = new KeyboardEvent('keydown', {key}); event.initEvent('keydown', true, true); return event; } });
the_stack
namespace colibri.ui.ide { export class Workbench { private static _workbench: Workbench; static getWorkbench() { if (!Workbench._workbench) { Workbench._workbench = new Workbench(); } return this._workbench; } public eventPartDeactivated = new controls.ListenerList<Part>(); public eventPartActivated = new controls.ListenerList<Part>(); public eventEditorDeactivated = new controls.ListenerList<EditorPart>(); public eventEditorActivated = new controls.ListenerList<EditorPart>(); public eventBeforeOpenProject = new controls.ListenerList(); public eventProjectOpened = new controls.ListenerList(); public eventThemeChanged = new controls.ListenerList<ui.controls.ITheme>(); private _fileStringCache: core.io.FileStringCache; private _fileImageCache: ImageFileCache; private _fileImageSizeCache: ImageSizeFileCache; private _activeWindow: ide.WorkbenchWindow; private _contentType_icon_Map: Map<string, controls.IconDescriptor>; private _fileStorage: core.io.IFileStorage; private _contentTypeRegistry: core.ContentTypeRegistry; private _activePart: Part; private _activeEditor: EditorPart; private _activeElement: HTMLElement; private _editorRegistry: EditorRegistry; private _commandManager: commands.CommandManager; private _windows: WorkbenchWindow[]; private _globalPreferences: core.preferences.Preferences; private _projectPreferences: core.preferences.Preferences; private _editorSessionStateRegistry: Map<string, any>; private constructor() { this._editorRegistry = new EditorRegistry(); this._windows = []; this._activePart = null; this._activeEditor = null; this._activeElement = null; this._fileImageCache = new ImageFileCache(); this._fileImageSizeCache = new ImageSizeFileCache(); this._fileStorage = new core.io.FileStorage_HTTPServer(); this._fileStringCache = new core.io.FileStringCache(this._fileStorage); this._globalPreferences = new core.preferences.Preferences("__global__"); this._projectPreferences = null; this._editorSessionStateRegistry = new Map(); } getEditorSessionStateRegistry() { return this._editorSessionStateRegistry; } getGlobalPreferences() { return this._globalPreferences; } getProjectPreferences() { return this._projectPreferences; } showNotification(text: string) { const element = document.createElement("div"); element.classList.add("Notification"); element.innerHTML = text; document.body.appendChild(element); element.classList.add("FadeInEffect"); element.addEventListener("click", () => element.remove()); setTimeout(() => { element.classList.add("FadeOutEffect"); setTimeout(() => element.remove(), 4000); }, 4000); } async launch() { console.log("Workbench: starting."); controls.Controls.initEvents(); controls.Controls.preloadTheme(); { const plugins = Platform.getPlugins(); for (const plugin of plugins) { plugin.registerExtensions(Platform.getExtensionRegistry()); } for (const plugin of plugins) { console.log(`\tPlugin: starting %c${plugin.getId()}`, "color:blue"); await plugin.starting(); } } controls.Controls.restoreTheme(); console.log("Workbench: fetching UI icons."); await this.preloadPluginResources(); console.log("Workbench: hide splash"); this.hideSplash(); console.log("Workbench: registering content types."); this.registerContentTypes(); this.registerContentTypeIcons(); console.log("Workbench: initializing UI."); this.initCommands(); this.registerEditors(); this.registerWindows(); this.initEvents(); console.log("%cWorkbench: started.", "color:green"); for (const plugin of Platform.getPlugins()) { await plugin.started(); } } private hideSplash() { const splashElement = document.getElementById("splash-container"); if (splashElement) { splashElement.remove(); } } private resetCache() { this._fileStringCache.reset(); this._fileImageCache.reset(); this._fileImageSizeCache.reset(); this._contentTypeRegistry.resetCache(); this._editorSessionStateRegistry.clear(); } async openProject(monitor: controls.IProgressMonitor) { this.eventBeforeOpenProject.fire(""); this.resetCache(); console.log(`Workbench: opening project.`); await this._fileStorage.openProject(); const projectName =this._fileStorage.getRoot().getName(); console.log(`Workbench: project ${projectName} loaded.`); this._projectPreferences = new core.preferences.Preferences("__project__" + projectName); console.log("Workbench: fetching required project resources."); try { await this.preloadProjectResources(monitor); this.eventProjectOpened.fire(projectName); } catch (e) { console.log("Error loading project resources"); alert("Error: loading project resources. " + e.message); console.log(e.message); } } private async preloadProjectResources(monitor: controls.IProgressMonitor) { const extensions = Platform .getExtensions<PreloadProjectResourcesExtension>(PreloadProjectResourcesExtension.POINT_ID); let total = 0; for (const extension of extensions) { const n = await extension.computeTotal(); total += n; } monitor.addTotal(total); for (const extension of extensions) { try { await extension.preload(monitor); } catch (e) { console.log("Error with extension:") console.log(extension); console.error(e); alert(`[${extension.constructor.name}] Preload error: ${(e.message || e)}`); } } } private registerWindows() { const extensions = Platform.getExtensions<WindowExtension>(WindowExtension.POINT_ID); this._windows = extensions.map(extension => extension.createWindow()); if (this._windows.length === 0) { alert("No workbench window provided."); } else { for (const win of this._windows) { win.style.display = "none"; document.body.appendChild(win.getElement()); } } } getWindows() { return this._windows; } public activateWindow(id: string): WorkbenchWindow { const win = this._windows.find(w => w.getId() === id); if (win) { if (this._activeWindow) { this._activeWindow.style.display = "none"; } this._activeWindow = win; win.create(); win.style.display = "initial"; return win; } alert(`Window ${id} not found.`); return null; } private async preloadPluginResources() { const dlg = new controls.dialogs.ProgressDialog(); dlg.create(); dlg.setTitle("Loading Workbench"); dlg.setCloseWithEscapeKey(false); dlg.setProgress(0); let resCount = 0; // count icon extensions const icons: controls.IconImage[] = []; { const extensions = Platform .getExtensions<IconLoaderExtension>(IconLoaderExtension.POINT_ID); for (const extension of extensions) { icons.push(...extension.getIcons()); } resCount = icons.length; } // count resource extensions const resExtensions = Platform .getExtensions<PluginResourceLoaderExtension>(PluginResourceLoaderExtension.POINT_ID); resCount += resExtensions.length; let i = 0; for (const icon of icons) { await icon.preload(); i++; dlg.setProgress(i / resCount); } for (const resExt of resExtensions) { await resExt.preload(); i++; dlg.setProgress(i / resCount); } // resources dlg.close(); } private registerContentTypeIcons() { this._contentType_icon_Map = new Map(); const extensions = Platform.getExtensions<ContentTypeIconExtension>(ContentTypeIconExtension.POINT_ID); for (const extension of extensions) { for (const item of extension.getConfig()) { this._contentType_icon_Map.set(item.contentType, item.iconDescriptor); } } } private initCommands() { this._commandManager = new commands.CommandManager(); const extensions = Platform.getExtensions<commands.CommandExtension>(commands.CommandExtension.POINT_ID); for (const extension of extensions) { extension.getConfigurer()(this._commandManager); } } private initEvents() { window.addEventListener("mousedown", e => { this._activeElement = e.target as HTMLElement; const part = this.findPart(e.target as any); if (part) { this.setActivePart(part); } }); window.addEventListener("beforeunload", e => { const dirty = this.getEditors().find(editor => editor.isDirty()); if (dirty) { e.preventDefault(); e.returnValue = ""; Platform.onElectron(electron => { electron.sendMessage({ method: "ask-close-window" }); }); } }); } private registerEditors(): void { const extensions = Platform.getExtensions<EditorExtension>(EditorExtension.POINT_ID); for (const extension of extensions) { for (const factory of extension.getFactories()) { this._editorRegistry.registerFactory(factory); } } } getFileStringCache() { return this._fileStringCache; } getFileStorage() { return this._fileStorage; } getCommandManager() { return this._commandManager; } getActiveDialog() { return controls.dialogs.Dialog.getActiveDialog(); } getActiveWindow() { return this._activeWindow; } getActiveElement() { return this._activeElement; } getActivePart() { return this._activePart; } getActiveEditor() { return this._activeEditor; } setActiveEditor(editor: EditorPart) { if (editor === this._activeEditor) { return; } this._activeEditor = editor; this.eventEditorActivated.fire(editor); } /** * Users may not call this method. This is public only for convenience. */ setActivePart(part: Part): void { if (part !== this._activePart) { const old = this._activePart; this._activePart = part; if (old) { this.toggleActivePartClass(old); old.onPartDeactivated(); this.eventPartDeactivated.fire(old); } if (part) { this.toggleActivePartClass(part); part.onPartActivated(); } this.eventPartActivated.fire(part); } if (part instanceof EditorPart) { this.setActiveEditor(part as EditorPart); } } private toggleActivePartClass(part: Part) { const tabPane = this.findTabPane(part.getElement()); if (!tabPane) { // maybe the clicked part was closed return; } if (part.containsClass("activePart")) { part.removeClass("activePart"); tabPane.removeClass("activePart"); } else { part.addClass("activePart"); tabPane.addClass("activePart"); } } private findTabPane(element: HTMLElement) { if (element) { const control = controls.Control.getControlOf(element); if (control && control instanceof controls.TabPane) { return control; } return this.findTabPane(element.parentElement); } return null; } private registerContentTypes() { const extensions = Platform.getExtensions<core.ContentTypeExtension>(core.ContentTypeExtension.POINT_ID); this._contentTypeRegistry = new core.ContentTypeRegistry(); for (const extension of extensions) { for (const resolver of extension.getResolvers()) { this._contentTypeRegistry.registerResolver(resolver); } } } findPart(element: HTMLElement): Part { if (controls.TabPane.isTabCloseIcon(element)) { return null; } if (controls.TabPane.isTabLabel(element)) { element = controls.TabPane.getContentFromLabel(element).getElement(); } if (element["__part"]) { return element["__part"]; } const control = controls.Control.getControlOf(element); if (control && control instanceof controls.TabPane) { const tabPane = control as controls.TabPane; const content = tabPane.getSelectedTabContent(); if (content) { const elem2 = content.getElement(); if (elem2["__part"]) { return elem2["__part"]; } } } if (element.parentElement) { return this.findPart(element.parentElement); } return null; } getContentTypeRegistry() { return this._contentTypeRegistry; } getProjectRoot(): core.io.FilePath { return this._fileStorage.getRoot(); } getContentTypeIcon(contentType: string): controls.IImage { if (this._contentType_icon_Map.has(contentType)) { const iconDesc = this._contentType_icon_Map.get(contentType); if (iconDesc) { const icon = iconDesc.getIcon(); return icon; } } return null; } getFileImage(file: core.io.FilePath) { if (file === null) { return null; } return this._fileImageCache.getContent(file); } getFileImageSizeCache() { return this._fileImageSizeCache; } getWorkbenchIcon(name: string) { return ColibriPlugin.getInstance().getIcon(name); } getEditorRegistry() { return this._editorRegistry; } getEditors(): EditorPart[] { return this.getActiveWindow().getEditorArea().getEditors(); } getOpenEditorsWithInput(input: ui.ide.IEditorInput) { return this.getEditors().filter(editor => editor.getInput() === input); } makeEditor(input: IEditorInput, editorFactory?: EditorFactory): EditorPart { const factory = editorFactory || this._editorRegistry.getFactoryForInput(input); if (factory) { const editor = factory.createEditor(); editor.setInput(input); return editor; } else { console.error("No editor available for :" + input); alert("No editor available for the given input."); } return null; } createEditor(input: IEditorInput, editorFactory?: EditorFactory): EditorPart { const editorArea = this.getActiveWindow().getEditorArea(); const editor = this.makeEditor(input, editorFactory); if (editor) { editorArea.addPart(editor, true, false); } return editor; } getEditorInputExtension(input: IEditorInput) { return this.getEditorInputExtensionWithId(input.getEditorInputExtension()); } getEditorInputExtensionWithId(id: string) { return Platform.getExtensions<EditorInputExtension>(EditorInputExtension.POINT_ID) .find(e => e.getId() === id); } openEditor(input: IEditorInput, editorFactory?: EditorFactory): EditorPart { const editorArea = this.getActiveWindow().getEditorArea(); { const editors = this.getEditors(); // tslint:disable-next-line:no-shadowed-variable for (const editor of editors) { if (editor.getInput() === input) { if (editorFactory && editorFactory !== editor.getEditorFactory()) { continue; } editorArea.activateEditor(editor); this.setActivePart(editor); return editor; } } } const editor = this.createEditor(input, editorFactory); if (editor) { editorArea.activateEditor(editor); this.setActivePart(editor); } return editor; } } }
the_stack
import { GameAction } from '../../action/GameActionTypes'; import { SoundAsset } from '../../assets/AssetsTypes'; import { getAwardProp } from '../../awards/GameAwardsHelper'; import { BBoxProperty } from '../../boundingBoxes/GameBoundingBoxTypes'; import { Character } from '../../character/GameCharacterTypes'; import { GamePosition, GameSize, ItemId } from '../../commons/CommonTypes'; import { AssetKey } from '../../commons/CommonTypes'; import { Dialogue } from '../../dialogue/GameDialogueTypes'; import { displayMiniMessage } from '../../effects/MiniMessage'; import { displayNotification } from '../../effects/Notification'; import { promptWithChoices } from '../../effects/Prompt'; import { Layer } from '../../layer/GameLayerTypes'; import { AnyId, GameItemType, GameLocation, LocationId } from '../../location/GameMapTypes'; import { GameMode } from '../../mode/GameModeTypes'; import { ObjectProperty } from '../../objects/GameObjectTypes'; import { GamePhaseType } from '../../phase/GamePhaseTypes'; import { SettingsJson } from '../../save/GameSaveTypes'; import SourceAcademyGame from '../../SourceAcademyGame'; import { StateObserver, UserStateType } from '../../state/GameStateTypes'; import { courseId, mandatory } from '../../utils/GameUtils'; import GameManager from './GameManager'; /** * This class exposes all the public API's of managers * in the Game Manager scene. * * It allows managers to access services globally * through GameGlobalAPI.getInstance().function() without * having to keep a reference to the gameManager. */ class GameGlobalAPI { private gameManager: GameManager | undefined; static instance: GameGlobalAPI; private constructor() { this.gameManager = undefined; } static getInstance() { if (!GameGlobalAPI.instance) { GameGlobalAPI.instance = new GameGlobalAPI(); } return GameGlobalAPI.instance; } ///////////////////// // Game Manager // ///////////////////// public getGameManager = () => mandatory(this.gameManager); public setGameManager(gameManagerRef: GameManager): void { this.gameManager = gameManagerRef; } public getCurrLocId(): LocationId { return this.getGameManager().currentLocationId; } public getLocationAtId(locationId: LocationId): GameLocation { return this.getGameManager().getStateManager().getGameMap().getLocationAtId(locationId); } public async changeLocationTo(locationName: string) { await this.getGameManager().changeLocationTo(locationName); } ///////////////////// // Game Mode // ///////////////////// public getLocationModes(locationId: LocationId): GameMode[] { return this.getGameManager().getStateManager().getLocationModes(locationId); } public addLocationMode(locationId: LocationId, mode: GameMode): void { this.getGameManager().getStateManager().addLocationMode(locationId, mode); } public removeLocationMode(locationId: LocationId, mode: GameMode): void { this.getGameManager().getStateManager().removeLocationMode(locationId, mode); } ///////////////////// // Interaction // ///////////////////// public hasTriggeredInteraction(id: string): boolean | undefined { return this.getGameManager().getStateManager().hasTriggeredInteraction(id); } public triggerStateChangeAction(actionId: ItemId): void { this.getGameManager().getStateManager().triggerStateChangeAction(actionId); } public triggerInteraction(id: string): void { this.getGameManager().getStateManager().triggerInteraction(id); } ///////////////////// // Game Items // ///////////////////// public watchGameItemType(gameItemType: GameItemType, stateObserver: StateObserver) { this.getGameManager().getStateManager().watchGameItemType(gameItemType, stateObserver); } public getGameMap() { return this.getGameManager().getStateManager().getGameMap(); } public getGameItemsInLocation(gameItemType: GameItemType, locationId: LocationId): ItemId[] { return this.getGameManager().getStateManager().getGameItemsInLocation(gameItemType, locationId); } public addItem(gameItemType: GameItemType, locationId: LocationId, itemId: ItemId): void { this.getGameManager().getStateManager().addItem(gameItemType, locationId, itemId); } public removeItem(gameItemType: GameItemType, locationId: LocationId, itemId: ItemId): void { return this.getGameManager().getStateManager().removeItem(gameItemType, locationId, itemId); } ///////////////////// // Game Objects // ///////////////////// public makeObjectGlow(objectId: ItemId, turnOn: boolean) { this.getGameManager().getObjectManager().makeObjectGlow(objectId, turnOn); } public makeObjectBlink(objectId: ItemId, turnOn: boolean) { this.getGameManager().getObjectManager().makeObjectBlink(objectId, turnOn); } public setObjProperty(id: ItemId, newObjProp: ObjectProperty) { this.getGameManager().getStateManager().setObjProperty(id, newObjProp); } public renderObjectLayerContainer(locationId: LocationId) { this.getGameManager().getObjectManager().renderObjectsLayerContainer(locationId); } public getAllActivatables() { return [ ...this.getGameManager().getObjectManager().getActivatables(), ...this.getGameManager().getBBoxManager().getActivatables() ]; } ///////////////////// // Game BBox // ///////////////////// public setBBoxProperty(id: ItemId, newBBoxProp: BBoxProperty) { this.getGameManager().getStateManager().setBBoxProperty(id, newBBoxProp); } public renderBBoxLayerContainer(locationId: LocationId) { this.getGameManager().getBBoxManager().renderBBoxLayerContainer(locationId); } ///////////////////// // Game Objective // ///////////////////// public isAllComplete(): boolean { return this.getGameManager().getStateManager().isAllComplete(); } public isObjectiveComplete(key: string): boolean { return this.getGameManager().getStateManager().isObjectiveComplete(key); } public areObjectivesComplete(keys: string[]): boolean { return this.getGameManager().getStateManager().areObjectivesComplete(keys); } public completeObjective(key: string): void { this.getGameManager().getStateManager().completeObjective(key); } ///////////////////// // User State // ///////////////////// public addCollectible(id: string): void { SourceAcademyGame.getInstance().getUserStateManager().addCollectible(id); } public async isInUserState(userStateType: UserStateType, id: string): Promise<boolean> { return SourceAcademyGame.getInstance().getUserStateManager().isInUserState(userStateType, id); } ///////////////////// // Game Layer // ///////////////////// public clearSeveralLayers(layerTypes: Layer[]) { this.getGameManager().getLayerManager().clearSeveralLayers(layerTypes); } public addToLayer(layer: Layer, gameObj: Phaser.GameObjects.GameObject) { this.getGameManager().getLayerManager().addToLayer(layer, gameObj); } public showLayer(layer: Layer) { this.getGameManager().getLayerManager().showLayer(layer); } public hideLayer(layer: Layer) { this.getGameManager().getLayerManager().hideLayer(layer); } public async fadeInLayer(layer: Layer, fadeDuration?: number) { await this.getGameManager().getLayerManager().fadeInLayer(layer, fadeDuration); } public async fadeOutLayer(layer: Layer, fadeDuration?: number) { await this.getGameManager().getLayerManager().fadeOutLayer(layer, fadeDuration); } ///////////////////// // Location Notif // ///////////////////// public async bringUpUpdateNotif(message: string) { await displayNotification(this.getGameManager(), message); } ///////////////////// // Story Action // ///////////////////// public async processGameActions(actionIds: ItemId[] | undefined) { await this.getGameManager().getPhaseManager().pushPhase(GamePhaseType.Sequence); await this.getGameManager().getActionManager().processGameActions(actionIds); await this.getGameManager().getPhaseManager().popPhase(); } public async processGameActionsInSamePhase(actionIds: ItemId[] | undefined) { await this.getGameManager().getActionManager().processGameActions(actionIds); } ///////////////////// // Dialogue // ///////////////////// public async showDialogue(dialogueId: ItemId) { await this.getGameManager().getPhaseManager().pushPhase(GamePhaseType.Sequence); await this.getGameManager().getDialogueManager().showDialogue(dialogueId); await this.getGameManager().getPhaseManager().popPhase(); } public async showDialogueInSamePhase(dialogueId: ItemId) { await this.getGameManager().getDialogueManager().showDialogue(dialogueId); } ///////////////////// // Collectible // ///////////////////// public async obtainCollectible(collectibleId: string) { displayMiniMessage(this.getGameManager(), `Obtained ${getAwardProp(collectibleId).title}`); SourceAcademyGame.getInstance().getUserStateManager().addCollectible(collectibleId); } ///////////////////// // Pop Up // ///////////////////// public displayPopUp(itemId: ItemId, position: GamePosition, duration?: number, size?: GameSize) { this.getGameManager().getPopupManager().displayPopUp(itemId, position, duration, size); } public destroyAllPopUps() { this.getGameManager().getPopupManager().destroyAllPopUps(); } public async destroyPopUp(position: GamePosition) { this.getGameManager().getPopupManager().destroyPopUp(position); } ///////////////////// // Save Game // ///////////////////// public async saveGame() { await this.getGameManager().getSaveManager().saveGame(); } public async saveSettings(settingsJson: SettingsJson) { await this.getGameManager().getSaveManager().saveSettings(settingsJson); } public getLoadedUserState() { return this.getGameManager().getSaveManager().getLoadedUserState(); } ///////////////////// // Sound // ///////////////////// public getSoundManager() { return SourceAcademyGame.getInstance().getSoundManager(); } public playSound(soundKey: AssetKey) { SourceAcademyGame.getInstance().getSoundManager().playSound(soundKey); } public playBgMusic(soundKey: AssetKey) { SourceAcademyGame.getInstance().getSoundManager().playBgMusic(soundKey); } public async stopAllSound() { SourceAcademyGame.getInstance().getSoundManager().stopAllSound(); } public pauseCurrBgMusic() { SourceAcademyGame.getInstance().getSoundManager().pauseCurrBgMusic(); } public continueCurrBgMusic() { SourceAcademyGame.getInstance().getSoundManager().continueCurrBgMusic(); } public applySoundSettings(userSettings: SettingsJson) { SourceAcademyGame.getInstance().getSoundManager().applyUserSettings(userSettings); } public loadSounds(soundAssets: SoundAsset[]) { SourceAcademyGame.getInstance().getSoundManager().loadSounds(soundAssets); } ///////////////////// // Animations // ///////////////////// public startAnimation(id: AnyId, startFrame: number, frameRate: number) { const startImage = this.getAssetByKey(this.getGameMap().getAssetKeyFromId(id)); this.getGameManager().getAnimationManager().displayAnimation(startImage, startFrame, frameRate); } public stopAnimation(id: AnyId) { const stopImage = this.getAssetByKey(this.getGameMap().getAssetKeyFromId(id)); this.getGameManager().getAnimationManager().stopAnimation(stopImage); } ///////////////////// // Input // ///////////////////// public setDefaultCursor(cursor: string) { this.getGameManager().getInputManager().setDefaultCursor(cursor); } public enableKeyboardInput(active: boolean) { this.getGameManager().getInputManager().enableKeyboardInput(active); } public enableMouseInput(active: boolean) { this.getGameManager().getInputManager().enableMouseInput(active); } public enableSprite(gameObject: Phaser.GameObjects.GameObject, active: boolean) { active ? this.getGameManager().input.enable(gameObject) : this.getGameManager().input.disable(gameObject); } ///////////////////// // Phases // ///////////////////// public async popPhase() { await this.getGameManager().getPhaseManager().popPhase(); } public async pushPhase(gamePhaseType: GamePhaseType) { await this.getGameManager().getPhaseManager().pushPhase(gamePhaseType); } public async swapPhase(gamePhaseType: GamePhaseType) { await this.getGameManager().getPhaseManager().swapPhase(gamePhaseType); } public isCurrentPhase(gamePhaseType: GamePhaseType) { return this.getGameManager().getPhaseManager().isCurrentPhase(gamePhaseType); } ///////////////////// // Background // ///////////////////// public renderBackgroundLayerContainer(locationId: LocationId) { this.getGameManager().getBackgroundManager().renderBackgroundLayerContainer(locationId); } ///////////////////// // Assessment // ///////////////////// public async promptNavigateToAssessment(assessmentId: number) { const response = await promptWithChoices( GameGlobalAPI.getInstance().getGameManager(), `Are you ready for the challenge?`, ['Yes', 'No'] ); if (response === 0) { window.open(`/courses/${courseId()}/missions/${assessmentId}/0`, 'blank'); window.focus(); } } public async updateAssessmentState() { await SourceAcademyGame.getInstance().getUserStateManager().loadAssessments(); } ///////////////////// // Characters // ///////////////////// public createCharacterSprite( characterId: ItemId, overrideExpression?: string, overridePosition?: GamePosition ) { return this.getGameManager() .getCharacterManager() .createCharacterSprite(characterId, overrideExpression, overridePosition); } public moveCharacter(id: ItemId, newLocation: LocationId, newPosition: GamePosition) { this.getGameManager().getStateManager().moveCharacter(id, newLocation, newPosition); } public updateCharacter(id: ItemId, expression: string) { this.getGameManager().getStateManager().updateCharacter(id, expression); } ///////////////////// // Item retrieval // ///////////////////// public getDialogueById(dialogueId: ItemId): Dialogue { return mandatory(this.getGameMap().getDialogueMap().get(dialogueId)); } public getCharacterById(characterId: ItemId): Character { return mandatory(this.getGameMap().getCharacterMap().get(characterId)); } public getActionById(actionId: ItemId): GameAction { return mandatory(this.getGameMap().getActionMap().get(actionId)); } public getObjectById(objectId: ItemId): ObjectProperty { return mandatory(this.getGameMap().getObjectPropMap().get(objectId)); } public getBBoxById(bboxId: ItemId): BBoxProperty { return mandatory(this.getGameMap().getBBoxPropMap().get(bboxId)); } public getAssetByKey(assetKey: AssetKey) { return this.getGameMap().getAssetByKey(assetKey); } } export default GameGlobalAPI;
the_stack
import { Style } from '../public/core'; import { Context } from './context'; import { Box, BoxType } from './box'; export type VBoxElement = { box: Box; marginLeft?: number; marginRight?: number; classes?: string[]; style?: Style; }; export type VBoxElementAndShift = VBoxElement & { shift: number }; // A list of child or kern nodes to be stacked on top of each other (i.e. the // first element will be at the bottom, and the last at the top). export type VBoxChild = VBoxElement | number; type VBoxParam = | { // Each child contains how much it should be shifted downward. individualShift: VBoxElementAndShift[]; } | { // "top": The positionData specifies the topmost point of the vlist (note this // is expected to be a height, so positive values move up). top: number; children: VBoxChild[]; } | { // "bottom": The positionData specifies the bottommost point of the vlist (note // this is expected to be a depth, so positive values move down). bottom: number; children: VBoxChild[]; } | { // "shift": The vlist will be positioned such that its baseline is positionData // away from the baseline of the first child which MUST be an // "elem". Positive values move downwards. shift: number; children: VBoxChild[]; } | { // The vlist is positioned so that its baseline is aligned with the baseline // of the first child which MUST be an "elem". This is equivalent to "shift" // with positionData=0. firstBaseline: VBoxChild[]; }; // Computes the updated `children` list and the overall depth. function getVListChildrenAndDepth( params: VBoxParam ): [ children: null | (VBoxChild | VBoxElementAndShift)[] | VBoxChild[], depth: number ] { if ('individualShift' in params) { const oldChildren = params.individualShift; let prevChild = oldChildren[0]; const children: (VBoxChild | VBoxElementAndShift)[] = [prevChild]; // Add in kerns to the list of params.children to get each element to be // shifted to the correct specified shift const depth = -prevChild.shift - prevChild.box.depth; let currPos = depth; for (let i = 1; i < oldChildren.length; i++) { const child = oldChildren[i]; const diff = -child.shift - currPos - child.box.depth; const size = diff - (prevChild.box.height + prevChild.box.depth); currPos = currPos + diff; children.push(size); children.push(child); prevChild = child; } return [children, depth]; } if ('top' in params) { // We always start at the bottom, so calculate the bottom by adding up // all the sizes let bottom = params.top; for (const child of params.children) { bottom -= typeof child === 'number' ? child : child.box.height + child.box.depth; } return [params.children, bottom]; } else if ('bottom' in params) { return [params.children, -params.bottom]; } else if ('firstBaseline' in params) { const firstChild = params.firstBaseline[0]; if (typeof firstChild === 'number') { throw new Error('First child must be an element.'); } return [params.firstBaseline, -firstChild.box.depth]; } else if ('shift' in params) { const firstChild = params.children[0]; if (typeof firstChild === 'number') { throw new Error('First child must be an element.'); } return [params.children, -firstChild.box.depth - params.shift]; } return [null, 0]; } /** * Makes a vertical list by stacking elements and kerns on top of each other. * Allows for many different ways of specifying the positioning method. * * See VListParam documentation above. * * Return a single row if the stack is entirely above the baseline. * Otherwise return 2 rows, the second one representing depth below the baseline. * This is necessary to workaround a Safari... behavior (see vlist-s and vlist-t2) */ function makeRows( params: VBoxParam ): [rows: Box[], height: number, depth: number] { const [children, depth] = getVListChildrenAndDepth(params); if (!children) return [[], 0, 0]; // Create a strut that is taller than any list item. The strut is added to // each item, where it will determine the item's baseline. Since it has // `overflow:hidden`, the strut's top edge will sit on the item's line box's // top edge and the strut's bottom edge will sit on the item's baseline, // with no additional line-height spacing. This allows the item baseline to // be positioned precisely without worrying about font ascent and // line-height. let pstrutSize = 0; for (const child of children) { if (typeof child !== 'number') { const box = child.box; pstrutSize = Math.max(pstrutSize, box.maxFontSize, box.height); } } pstrutSize += 2; const pstrut = new Box(null, { classes: 'pstrut' }); pstrut.setStyle('height', pstrutSize, 'em'); // Create a new list of actual children at the correct offsets const realChildren: Box[] = []; let minPos = depth; let maxPos = depth; let currPos = depth; for (const child of children) { if (typeof child === 'number') { currPos += child; } else { const box = child.box; const classes = child.classes ?? []; const childWrap = new Box([pstrut, box], { classes: classes.join(' '), style: child.style, }); childWrap.setStyle('top', -pstrutSize - currPos - box.depth, 'em'); if (child.marginLeft) { childWrap.setStyle('margin-left', child.marginLeft, 'em'); } if (child.marginRight) { childWrap.setStyle('margin-right', child.marginRight, 'em'); } realChildren.push(childWrap); currPos += box.height + box.depth; } minPos = Math.min(minPos, currPos); maxPos = Math.max(maxPos, currPos); } // The vlist contents go in a table-cell with `vertical-align:bottom`. // This cell's bottom edge will determine the containing table's baseline // without overly expanding the containing line-box. const vlist = new Box(realChildren, { classes: 'vlist' }); vlist.setStyle('height', maxPos, 'em'); // A second row is used if necessary to represent the vlist's depth. let rows: Box[]; if (minPos < 0) { // We will define depth in an empty box with display: table-cell. // It should render with the height that we define. But Chrome, in // contenteditable mode only, treats that box as if it contains some // text content. And that min-height over-rides our desired height. // So we put another empty box inside the depth strut box. const depthStrut = new Box(new Box(null), { classes: 'vlist' }); depthStrut.setStyle('height', -minPos, 'em'); // Safari wants the first row to have inline content; otherwise it // puts the bottom of the *second* row on the baseline. const topStrut = new Box(0x200b, { classes: 'vlist-s', maxFontSize: 0, height: 0, depth: 0, }); rows = [ new Box([vlist, topStrut], { classes: 'vlist-r' }), new Box(depthStrut, { classes: 'vlist-r' }), ]; } else { rows = [new Box(vlist, { classes: 'vlist-r' })]; } return [rows, maxPos, -minPos]; } export class VBox extends Box { constructor( content: VBoxParam, options?: { classes?: string; type?: BoxType } ) { const [rows, height, depth] = makeRows(content); super(rows.length === 1 ? rows[0] : rows, { classes: (options?.classes ?? '') + ' vlist-t' + (rows.length === 2 ? ' vlist-t2' : ''), height, depth, type: options?.type, }); } } /* Combine a nucleus with an atom above and an atom below. Used to form * limits. * * @param context * @param nucleus The base over and under which the atoms will * be placed. * @param nucleusShift The vertical shift of the nucleus from * the baseline. * @param slant For operators that have a slant, such as \int, * indicate by how much to horizontally offset the above and below atoms */ export function makeLimitsStack( context: Context, options: { base: Box; baseShift?: number; slant?: number; above: Box | null; aboveShift?: number; below: Box | null; belowShift?: number; type?: BoxType; } ): Box { // If nothing above and nothing below, nothing to do. // if (!options.above && !options.below) { // return new Span(options.base, { type: options.boxType ?? 'mop' }).wrap( // context // ); // // return options.base; // } const metrics = context.metrics; // IE8 clips \int if it is in a display: inline-block. We wrap it // in a new box so it is an inline, and works. // @todo: revisit const base = new Box(options.base); const baseShift = options.baseShift ?? 0; const slant = options.slant ?? 0; let aboveShift = 0; let belowShift = 0; if (options.above) { aboveShift = options.aboveShift ?? Math.max( metrics.bigOpSpacing1, metrics.bigOpSpacing3 - options.above.depth ); } if (options.below) { belowShift = options.belowShift ?? Math.max( metrics.bigOpSpacing2, metrics.bigOpSpacing4 - options.below.height ); } let result: Box | null = null; if (options.below && options.above) { const bottom = metrics.bigOpSpacing5 + options.below.height + options.below.depth + belowShift + base.depth + baseShift; // Here, we shift the limits by the slant of the symbol. Note // that we are supposed to shift the limits by 1/2 of the slant, // but since we are centering the limits adding a full slant of // margin will shift by 1/2 that. result = new VBox({ bottom, children: [ metrics.bigOpSpacing5, { box: options.below, marginLeft: -slant, classes: ['ML__center'], }, belowShift, // We need to center the base to account for the case where the // above/below is wider { box: base, classes: ['ML__center'] }, aboveShift, { box: options.above, marginLeft: slant, classes: ['ML__center'], }, metrics.bigOpSpacing5, ], }).wrap(context); } else if (options.below && !options.above) { result = new VBox({ top: base.height - baseShift, children: [ metrics.bigOpSpacing5, { box: options.below, marginLeft: -slant, classes: ['ML__center'], }, belowShift, { box: base, classes: ['ML__center'] }, ], }).wrap(context); } else if (!options.below && options.above) { const bottom = base.depth + baseShift; result = new VBox({ bottom, children: [ { box: base, classes: ['ML__center'] }, aboveShift, { box: options.above, marginLeft: slant, classes: ['ML__center'], }, metrics.bigOpSpacing5, ], }).wrap(context); } else { const bottom = base.depth + baseShift; result = new VBox({ bottom, children: [{ box: base }, metrics.bigOpSpacing5], }).wrap(context); } console.assert(options.type !== undefined); return new Box(result, { type: options.type ?? 'mop' }); }
the_stack
import { checkBrowserType, isCorrectBrowserType } from './utils/BrowserTypes' import { ConcreteLaunchOptions, PlaywrightClient } from './driver/Playwright' import Test from './runtime/Test' import { EvaluatedScript } from './runtime/EvaluatedScript' import { TestObserver } from './runtime/test-observers/TestObserver' import { TestSettings } from './runtime/Settings' import { AsyncFactory } from './utils/Factory' import { CancellationToken } from './utils/CancellationToken' import { CustomConsole, IReporter, IterationResult, reportRunTest, Status, StepResult, } from '@flood/element-report' import { Looper } from './Looper' import chalk from 'chalk' import ms from 'ms' export interface TestCommander { on(event: 'rerun-test', listener: () => void): this } // eslint-disable-next-line @typescript-eslint/interface-name-prefix export interface IRunner { run(testScriptFactory: AsyncFactory<EvaluatedScript>): Promise<void> stop(): Promise<void> getSummaryIterations(): IterationResult[] } function delay(t: number, v?: any) { return new Promise(function (resolve) { setTimeout(resolve.bind(null, v), t) }) } export class Runner { protected looper: Looper running = true public client: PlaywrightClient | undefined public summaryIteration: IterationResult[] = [] private sendReport: (msg: string, type: string) => void constructor( private clientFactory: AsyncFactory<PlaywrightClient>, protected testCommander: TestCommander | undefined, private reporter: IReporter, private settingsFromConfig: TestSettings, private testSettingOverrides: TestSettings, private launchOptionOverrides: Partial<ConcreteLaunchOptions>, private testObserverFactory: (t: TestObserver) => TestObserver = (x) => x ) { if (reporter.sendReport) this.sendReport = reporter.sendReport } async stop(): Promise<void> { this.running = false if (this.looper) await this.looper.kill() if (this.client) await this.client.close() return } async runEvalScript(testScript: EvaluatedScript): Promise<void> { this.client = await this.launchClient(testScript) await this.runTestScript(testScript, this.client) } async run(testScriptFactory: AsyncFactory<EvaluatedScript>): Promise<void> { const testScript = await testScriptFactory() this.client = await this.launchClient(testScript) await this.runTestScript(testScript, this.client) } async launchClient(testScript: EvaluatedScript): Promise<PlaywrightClient> { let options: Partial<ConcreteLaunchOptions> = this.launchOptionOverrides const settings = { acceptDownloads: !!options.downloadsPath, ...this.settingsFromConfig, ...testScript.settings, ...this.testSettingOverrides, } options.ignoreHTTPSError = settings.ignoreHTTPSError if (settings.viewport) { options.viewport = settings.viewport settings.device = null } if (!options.browser && settings.browser) { options.browser = settings.browser checkBrowserType(options.browser) } if (settings.browserLaunchOptions) { options = { ...settings.browserLaunchOptions, ...options } } options.browser = options.browser && isCorrectBrowserType(options.browser) ? options.browser : 'chromium' if (options.args == null) options.args = [] if (Array.isArray(settings.launchArgs)) options.args.push(...settings.launchArgs) return this.clientFactory(options, settings) } async runTestScript(testScript: EvaluatedScript, client: PlaywrightClient): Promise<void> { if (!this.running) return let testToCancel: Test | undefined const reportTableData: number[][] = [] try { const test = new Test( client, testScript, this.reporter, this.settingsFromConfig, this.testSettingOverrides, this.testObserverFactory ) testToCancel = test const { settings } = test const { name, description, browser } = settings if (name) { console.info(` ************************************************************* * Loaded test plan: ${name} * ${description} ************************************************************* `) } if (browser === 'firefox' || browser === 'webkit') { const customConsole = global.console as CustomConsole customConsole.setGroupDepth(2) console.warn( `${chalk.yellow('> WARNING')} Running with ${browser .substring(0, 1) .toUpperCase() .concat( browser.substring(1) )}. The following APIs are not applicable: browser.clearBrowserCache()\n` ) } await test.beforeRun() const cancelToken = new CancellationToken() this.looper = new Looper(settings, this.running) this.looper.killer = () => cancelToken.cancel() let startTime = new Date() await this.looper.run(async (iteration: number, isRestart: boolean) => { const iterationName = this.getIterationName(iteration) const numOfIteration = this.looper.loopCount === -1 ? '' : `of ${this.looper.loopCount}` if (isRestart) { if (!this.reporter.worker) { console.log(`Restarting ${iterationName}`) } else { this.sendReport(`Restarting ${iterationName}`, 'action') } this.looper.restartLoopDone() } else { if (!this.reporter.worker) { if (iteration > 1) { console.log(chalk.grey('--------------------------------------------')) } startTime = new Date() this.reporter.report?.startAnimation( iterationName, `${iterationName} ${numOfIteration}`, 2 ) } else { this.sendReport( JSON.stringify({ iterationMsg: `${iterationName} ${numOfIteration}`, iteration, }), 'iteration' ) } } try { await test.runWithCancellation(iteration, cancelToken, this.looper) // eslint-disable-next-line no-empty } catch { } finally { if (!this.reporter.worker) { this.reporter.report?.endAnimation( iterationName, chalk.whiteBright(`${iterationName} ${numOfIteration}`), 2 ) } if (!this.looper.isRestart) { const summarizedData = this.summarizeIteration(test, iteration, startTime) reportTableData.push(summarizedData) } test.resetSummarizeStep() } }) if (!this.reporter.worker) { console.groupEnd() console.log(`Test completed after ${this.looper.loopCount} iterations`) } await test.runningBrowser?.close() } catch (err) { throw Error(err) } finally { if (!this.reporter.worker) { const table = reportRunTest(reportTableData) console.log(table) } } if (testToCancel !== undefined) { await testToCancel.cancel() } } getIterationName(iteration: number): string { return `Iteration ${iteration}` } summarizeIteration(test: Test, iteration: number, startTime: Date): number[] { let passedMessage = '', failedMessage = '', skippedMessage = '', unexecutedMessage = '' let passedNo = 0, failedNo = 0, skippedNo = 0, unexecutedNo = 0 const iterationName: string = this.getIterationName(iteration) const duration: number = new Date().valueOf() - startTime.valueOf() const stepResult: StepResult[] = test.summarizeStep() const iterationResult = { name: iterationName, duration: duration, stepResults: stepResult, } this.summaryIteration.push(iterationResult) stepResult.forEach((step) => { switch (step.status) { case Status.PASSED: passedNo += 1 passedMessage = chalk.green(`${passedNo}`, `${Status.PASSED}`) break case Status.FAILED: failedNo += 1 failedMessage = chalk.red(`${failedNo}`, `${Status.FAILED}`) break case Status.SKIPPED: skippedNo += 1 skippedMessage = chalk.yellow(`${skippedNo}`, `${Status.SKIPPED}`) if (this.reporter.worker) { this.sendReport( JSON.stringify({ name: 'skipped', value: skippedNo, iteration }), 'measurement' ) } break case Status.UNEXECUTED: unexecutedNo += 1 unexecutedMessage = chalk(`${unexecutedNo}`, `${Status.UNEXECUTED}`) if (this.reporter.worker) { this.sendReport( JSON.stringify({ name: 'unexecuted', value: unexecutedNo, iteration }), 'measurement' ) } break } }) const finallyMessage = chalk(passedMessage, failedMessage, skippedMessage, unexecutedMessage) if (!this.reporter.worker) { const customConsole = global.console as CustomConsole customConsole.setGroupDepth(2) console.log(`${iterationName} completed in ${ms(duration)} (walltime) ${finallyMessage}`) } return [iteration, passedNo, failedNo, skippedNo, unexecutedNo] } getSummaryIterations(): IterationResult[] { return this.summaryIteration } } export class PersistentRunner extends Runner { public testScriptFactory: AsyncFactory<EvaluatedScript> | undefined public client: PlaywrightClient | undefined private stopped = false constructor( clientFactory: AsyncFactory<PlaywrightClient>, testCommander: TestCommander | undefined, reporter: IReporter, testSettings: TestSettings, testSettingOverrides: TestSettings, launchOptionOverrides: Partial<ConcreteLaunchOptions>, testObserverFactory: (t: TestObserver) => TestObserver = (x) => x ) { super( clientFactory, testCommander, reporter, testSettings, testSettingOverrides, launchOptionOverrides, testObserverFactory ) if (this.testCommander !== undefined) { this.testCommander.on('rerun-test', async () => this.rerunTest()) } } rerunTest() { setImmediate(() => this.runNextTest()) } async runNextTest() { const { client, testScriptFactory } = this if (client === undefined) { return } if (testScriptFactory === undefined) { return } if (this.looper) { await this.looper.kill() } try { const evaluateScript = await testScriptFactory() this.client = await this.launchClient(evaluateScript) await this.runTestScript(evaluateScript, this.client) } catch (err) { console.error(err.message) } } async stop() { this.stopped = true this.running = false if (this.looper) this.looper.stop() } async waitUntilStopped(): Promise<void> { if (this.stopped) { return } else { await delay(1000) return this.waitUntilStopped() } } async run(testScriptFactory: AsyncFactory<EvaluatedScript>): Promise<void> { this.testScriptFactory = testScriptFactory // TODO detect changes in testScript settings affecting the client this.client = await this.launchClient(await testScriptFactory()) this.rerunTest() await this.waitUntilStopped() } }
the_stack
import { IExecuteFunctions, IHookFunctions, } from 'n8n-core'; import { IDataObject, ILoadOptionsFunctions, INodeExecutionData, INodeProperties, INodePropertyOptions, NodeApiError, } from 'n8n-workflow'; import { CustomField, GeneralAddress, Ref, } from './descriptions/Shared.interface'; import { capitalCase, } from 'change-case'; import { omit, pickBy, } from 'lodash'; import { OptionsWithUri, } from 'request'; import { DateFieldsUi, Option, QuickBooksOAuth2Credentials, TransactionReport, } from './types'; /** * Make an authenticated API request to QuickBooks. */ export async function quickBooksApiRequest( this: IHookFunctions | IExecuteFunctions | ILoadOptionsFunctions, method: string, endpoint: string, qs: IDataObject, body: IDataObject, option: IDataObject = {}, ): Promise<any> { // tslint:disable-line:no-any const resource = this.getNodeParameter('resource', 0) as string; const operation = this.getNodeParameter('operation', 0) as string; let isDownload = false; if (['estimate', 'invoice', 'payment'].includes(resource) && operation === 'get') { isDownload = this.getNodeParameter('download', 0) as boolean; } const productionUrl = 'https://quickbooks.api.intuit.com'; const sandboxUrl = 'https://sandbox-quickbooks.api.intuit.com'; const credentials = await this.getCredentials('quickBooksOAuth2Api') as QuickBooksOAuth2Credentials; const options: OptionsWithUri = { headers: { 'user-agent': 'n8n', }, method, uri: `${credentials.environment === 'sandbox' ? sandboxUrl : productionUrl}${endpoint}`, qs, body, json: !isDownload, }; if (!Object.keys(body).length) { delete options.body; } if (!Object.keys(qs).length) { delete options.qs; } if (Object.keys(option)) { Object.assign(options, option); } if (isDownload) { options.headers!['Accept'] = 'application/pdf'; } if (resource === 'invoice' && operation === 'send') { options.headers!['Content-Type'] = 'application/octet-stream'; } if ( (resource === 'invoice' && (operation === 'void' || operation === 'delete')) || (resource === 'payment' && (operation === 'void' || operation === 'delete')) ) { options.headers!['Content-Type'] = 'application/json'; } try { return await this.helpers.requestOAuth2!.call(this, 'quickBooksOAuth2Api', options); } catch (error) { throw new NodeApiError(this.getNode(), error); } } /** * Make an authenticated API request to QuickBooks and return all results. */ export async function quickBooksApiRequestAllItems( this: IHookFunctions | IExecuteFunctions | ILoadOptionsFunctions, method: string, endpoint: string, qs: IDataObject, body: IDataObject, resource: string, ): Promise<any> { // tslint:disable-line:no-any let responseData; let startPosition = 1; const maxResults = 1000; const returnData: IDataObject[] = []; const maxCount = await getCount.call(this, method, endpoint, qs); const originalQuery = qs.query as string; do { qs.query = `${originalQuery} MAXRESULTS ${maxResults} STARTPOSITION ${startPosition}`; responseData = await quickBooksApiRequest.call(this, method, endpoint, qs, body); try { const nonResource = originalQuery.split(' ')?.pop(); if (nonResource === 'CreditMemo' || nonResource === 'Term') { returnData.push(...responseData.QueryResponse[nonResource]); } else { returnData.push(...responseData.QueryResponse[capitalCase(resource)]); } } catch (error) { return []; } startPosition += maxResults; } while (maxCount > returnData.length); return returnData; } async function getCount( this: IHookFunctions | IExecuteFunctions | ILoadOptionsFunctions, method: string, endpoint: string, qs: IDataObject, ): Promise<any> { // tslint:disable-line:no-any const responseData = await quickBooksApiRequest.call(this, method, endpoint, qs, {}); return responseData.QueryResponse.totalCount; } /** * Handles a QuickBooks listing by returning all items or up to a limit. */ export async function handleListing( this: IExecuteFunctions, i: number, endpoint: string, resource: string, ): Promise<any> { // tslint:disable-line:no-any let responseData; const qs = { query: `SELECT * FROM ${resource}`, } as IDataObject; const returnAll = this.getNodeParameter('returnAll', i); const filters = this.getNodeParameter('filters', i) as IDataObject; if (filters.query) { qs.query += ` ${filters.query}`; } if (returnAll) { return await quickBooksApiRequestAllItems.call(this, 'GET', endpoint, qs, {}, resource); } else { const limit = this.getNodeParameter('limit', i) as number; qs.query += ` MAXRESULTS ${limit}`; responseData = await quickBooksApiRequest.call(this, 'GET', endpoint, qs, {}); responseData = responseData.QueryResponse[capitalCase(resource)]; return responseData; } } /** * Get the SyncToken required for delete and void operations in QuickBooks. */ export async function getSyncToken( this: IExecuteFunctions, i: number, companyId: string, resource: string, ) { const resourceId = this.getNodeParameter(`${resource}Id`, i); const getEndpoint = `/v3/company/${companyId}/${resource}/${resourceId}`; const propertyName = capitalCase(resource); const { [propertyName]: { SyncToken } } = await quickBooksApiRequest.call(this, 'GET', getEndpoint, {}, {}); return SyncToken; } /** * Get the reference and SyncToken required for update operations in QuickBooks. */ export async function getRefAndSyncToken( this: IExecuteFunctions, i: number, companyId: string, resource: string, ref: string, ) { const resourceId = this.getNodeParameter(`${resource}Id`, i); const endpoint = `/v3/company/${companyId}/${resource}/${resourceId}`; const responseData = await quickBooksApiRequest.call(this, 'GET', endpoint, {}, {}); return { ref: responseData[capitalCase(resource)][ref], syncToken: responseData[capitalCase(resource)].SyncToken, }; } /** * Populate node items with binary data. */ export async function handleBinaryData( this: IExecuteFunctions, items: INodeExecutionData[], i: number, companyId: string, resource: string, resourceId: string, ) { const binaryProperty = this.getNodeParameter('binaryProperty', i) as string; const fileName = this.getNodeParameter('fileName', i) as string; const endpoint = `/v3/company/${companyId}/${resource}/${resourceId}/pdf`; const data = await quickBooksApiRequest.call(this, 'GET', endpoint, {}, {}, { encoding: null }); items[i].binary = items[i].binary ?? {}; items[i].binary![binaryProperty] = await this.helpers.prepareBinaryData(data); items[i].binary![binaryProperty].fileName = fileName; items[i].binary![binaryProperty].fileExtension = 'pdf'; return items; } export async function loadResource( this: ILoadOptionsFunctions, resource: string, ) { const returnData: INodePropertyOptions[] = []; const qs = { query: `SELECT * FROM ${resource}`, } as IDataObject; const { oauthTokenData: { callbackQueryString: { realmId } } } = await this.getCredentials('quickBooksOAuth2Api') as { oauthTokenData: { callbackQueryString: { realmId: string } } }; const endpoint = `/v3/company/${realmId}/query`; const resourceItems = await quickBooksApiRequestAllItems.call(this, 'GET', endpoint, qs, {}, resource); if (resource === 'preferences') { const { SalesFormsPrefs: { CustomField } } = resourceItems[0]; const customFields = CustomField[1].CustomField; for (const customField of customFields) { const length = customField.Name.length; returnData.push({ name: customField.StringValue, value: customField.Name.charAt(length - 1), }); } return returnData; } resourceItems.forEach((resourceItem: { DisplayName: string, Name: string, Id: string }) => { returnData.push({ name: resourceItem.DisplayName || resourceItem.Name || `Memo ${resourceItem.Id}`, value: resourceItem.Id, }); }); return returnData; } /** * Populate the `Line` property in a request body. */ export function processLines( this: IExecuteFunctions, body: IDataObject, lines: IDataObject[], resource: string, ) { lines.forEach((line) => { if (resource === 'bill') { if (line.DetailType === 'AccountBasedExpenseLineDetail') { line.AccountBasedExpenseLineDetail = { AccountRef: { value: line.accountId, }, }; delete line.accountId; } else if (line.DetailType === 'ItemBasedExpenseLineDetail') { line.ItemBasedExpenseLineDetail = { ItemRef: { value: line.itemId, }, }; delete line.itemId; } } else if (resource === 'estimate') { if (line.DetailType === 'SalesItemLineDetail') { line.SalesItemLineDetail = { ItemRef: { value: line.itemId, }, }; delete line.itemId; } } else if (resource === 'invoice') { if (line.DetailType === 'SalesItemLineDetail') { line.SalesItemLineDetail = { ItemRef: { value: line.itemId, }, }; delete line.itemId; } } }); return lines; } /** * Populate update fields or additional fields into a request body. */ export function populateFields( this: IExecuteFunctions, body: IDataObject, fields: IDataObject, resource: string, ) { Object.entries(fields).forEach(([key, value]) => { if (resource === 'bill') { if (key.endsWith('Ref')) { const { details } = value as { details: Ref }; body[key] = { name: details.name, value: details.value, }; } else { body[key] = value; } } else if (['customer', 'employee', 'vendor'].includes(resource)) { if (key === 'BillAddr') { const { details } = value as { details: GeneralAddress }; body.BillAddr = pickBy(details, detail => detail !== ''); } else if (key === 'PrimaryEmailAddr') { body.PrimaryEmailAddr = { Address: value, }; } else if (key === 'PrimaryPhone') { body.PrimaryPhone = { FreeFormNumber: value, }; } else { body[key] = value; } } else if (resource === 'estimate' || resource === 'invoice') { if (key === 'BillAddr' || key === 'ShipAddr') { const { details } = value as { details: GeneralAddress }; body[key] = pickBy(details, detail => detail !== ''); } else if (key === 'BillEmail') { body.BillEmail = { Address: value, }; } else if (key === 'CustomFields') { const { Field } = value as { Field: CustomField[] }; body.CustomField = Field; const length = (body.CustomField as CustomField[]).length; for (let i = 0; i < length; i++) { //@ts-ignore body.CustomField[i]['Type'] = 'StringType'; } } else if (key === 'CustomerMemo') { body.CustomerMemo = { value, }; } else if (key.endsWith('Ref')) { const { details } = value as { details: Ref }; body[key] = { name: details.name, value: details.value, }; } else if (key === 'TotalTax') { body.TxnTaxDetail = { TotalTax: value, }; } else { body[key] = value; } } else if (resource === 'payment') { body[key] = value; } }); return body; } export const toOptions = (option: string) => ({ name: option, value: option }); export const toDisplayName = ({ name, value }: Option): INodePropertyOptions => { return { name: splitPascalCase(name), value }; }; export const splitPascalCase = (word: string) => { return word.match(/($[a-z])|[A-Z][^A-Z]+/g)!.join(' '); }; export function adjustTransactionDates( transactionFields: IDataObject & DateFieldsUi, ): IDataObject { const dateFieldKeys = [ 'dateRangeCustom', 'dateRangeDueCustom', 'dateRangeModificationCustom', 'dateRangeCreationCustom', ] as const; if (dateFieldKeys.every(dateField => !transactionFields[dateField])) { return transactionFields; } let adjusted = omit(transactionFields, dateFieldKeys) as IDataObject; dateFieldKeys.forEach(dateFieldKey => { const dateField = transactionFields[dateFieldKey]; if (dateField) { Object.entries(dateField[`${dateFieldKey}Properties`]).map(([key, value]) => dateField[`${dateFieldKey}Properties`][key] = value.split('T')[0], ); adjusted = { ...adjusted, ...dateField[`${dateFieldKey}Properties`], }; } }); return adjusted; } export function simplifyTransactionReport(transactionReport: TransactionReport) { const columns = transactionReport.Columns.Column.map((column) => column.ColType); const rows = transactionReport.Rows.Row.map((row) => row.ColData.map(i => i.value)); const simplified = []; for (const row of rows) { const transaction: { [key: string]: string } = {}; for (let i = 0; i < row.length; i++) { transaction[columns[i]] = row[i]; } simplified.push(transaction); } return simplified; }
the_stack
import { Packet } from "./Packet"; import { Server } from "../Server"; import { PacketType } from "./PacketType"; import { ByteReader } from "../ByteReader"; import { ByteWriter } from "../ByteWriter"; import * as Configurations from "../Configuration"; import { IKexAlgorithm } from "../KexAlgorithms/IKexAlgorithm"; import { DiffieHellmanGroup14SHA1 } from "../KexAlgorithms/DiffieHellmanGroup14SHA1"; import { IHostKeyAlgorithm } from "../HostKeyAlgorithms/IHostKeyAlgorithm"; import { SSHRSA } from "../HostKeyAlgorithms/SSHRSA"; import { ICipher } from "../Ciphers/ICipher"; import { TripleDESCBC } from "../Ciphers/TripleDESCBC"; import { IMACAlgorithm } from "../MACAlgorithms/IMACAlgorithm"; import { HMACSHA1 } from "../MACAlgorithms/HMACSHA1"; import { ICompression } from "../Compressions/ICompression"; import { NoCompression } from "../Compressions/NoCompression"; import * as Exceptions from "../SSHServerException"; import crypto = require('crypto'); let config: Configurations.Configuration = require("../sshserver.json"); export class KexInit extends Packet { public getPacketType(): PacketType { return PacketType.SSH_MSG_KEXINIT; } public cookie: Buffer = crypto.randomBytes(16); public kexAlgorithms: Array<string> = new Array<string>(); public serverHostKeyAlgorithms : Array<string> = new Array<string>(); public encryptionAlgorithmsClientToServer : Array<string> = new Array<string>(); public encryptionAlgorithmsServerToClient : Array<string> = new Array<string>(); public macAlgorithmsClientToServer : Array<string> = new Array<string>(); public macAlgorithmsServerToClient : Array<string> = new Array<string>(); public compressionAlgorithmsClientToServer : Array<string> = new Array<string>(); public compressionAlgorithmsServerToClient : Array<string> = new Array<string>(); public languagesClientToServer : Array<string> = new Array<string>(); public languagesServerToClient: Array<string> = new Array<string>(); public firstKexPacketFollows: boolean = false; protected internalGetBytes(writer: ByteWriter) { writer.writeRawBytes(this.cookie); writer.writeStringList(this.kexAlgorithms); writer.writeStringList(this.serverHostKeyAlgorithms); writer.writeStringList(this.encryptionAlgorithmsClientToServer); writer.writeStringList(this.encryptionAlgorithmsServerToClient); writer.writeStringList(this.macAlgorithmsClientToServer); writer.writeStringList(this.macAlgorithmsServerToClient); writer.writeStringList(this.compressionAlgorithmsClientToServer); writer.writeStringList(this.compressionAlgorithmsServerToClient); writer.writeStringList(this.languagesClientToServer); writer.writeStringList(this.languagesServerToClient); writer.writeByte(this.firstKexPacketFollows ? 0x01 : 0x00); writer.writeUInt32(0); } public load(reader: ByteReader) { this.cookie = reader.getBytes(16); this.kexAlgorithms = reader.getNameList(); this.serverHostKeyAlgorithms = reader.getNameList(); this.encryptionAlgorithmsClientToServer = reader.getNameList(); this.encryptionAlgorithmsServerToClient = reader.getNameList(); this.macAlgorithmsClientToServer = reader.getNameList(); this.macAlgorithmsServerToClient = reader.getNameList(); this.compressionAlgorithmsClientToServer = reader.getNameList(); this.compressionAlgorithmsServerToClient = reader.getNameList(); this.languagesClientToServer = reader.getNameList(); this.languagesServerToClient = reader.getNameList(); this.firstKexPacketFollows = reader.getBoolean(); // uint32 0 (reserved for future extension) reader.getUInt32(); } public pickKexAlgorithm(): IKexAlgorithm { for (let algo of this.kexAlgorithms) { if (Server.SupportedKexAlgorithms.find( (value: string, index: number, obj: Array<string>): boolean => { return (value === algo); })) { switch (algo) { case "diffie-hellman-group14-sha1": return new DiffieHellmanGroup14SHA1(); } } } // If no algorithm satisfying all these conditions can be found, the // connection fails, and both sides MUST disconnect. throw new Exceptions.SSHServerException( Exceptions.DisconnectReason.SSH_DISCONNECT_KEY_EXCHANGE_FAILED, "Could not find a shared Kex Algorithm"); } public pickHostKeyAlgorithm(): IHostKeyAlgorithm { for (let algo of this.serverHostKeyAlgorithms) { if (Server.SupportedHostKeyAlgorithms.find( (value: string, index: number, obj: Array<string>): boolean => { return (value === algo); })) { switch (algo) { case "ssh-rsa": { let configKey: Configurations.Key = config.keys.find((value: Configurations.Key, index: number, object: Configurations.Key[]) => { return (value.algorithm === algo) }); if (configKey === null) { throw new Exceptions.SSHServerException( Exceptions.DisconnectReason.SSH_DISCONNECT_KEY_EXCHANGE_FAILED, "Could not find a configuration for ssh-rsa."); } return new SSHRSA( configKey.key.pem, new Buffer(configKey.key.modulus, "base64"), new Buffer(configKey.key.exponent, "base64")); } } } } // If no algorithm satisfying all these conditions can be found, the // connection fails, and both sides MUST disconnect. throw new Exceptions.SSHServerException( Exceptions.DisconnectReason.SSH_DISCONNECT_KEY_EXCHANGE_FAILED, "Could not find a shared Host Key Algorithm"); } public pickCipherClientToServer(): ICipher { for (let algo of this.encryptionAlgorithmsClientToServer) { if (Server.SupportedCiphers.find( (value: string, index: number, obj: Array<string>): boolean => { return (value === algo); })) { switch (algo) { case "3des-cbc": return new TripleDESCBC(); } } } // If no algorithm satisfying all these conditions can be found, the // connection fails, and both sides MUST disconnect. throw new Exceptions.SSHServerException( Exceptions.DisconnectReason.SSH_DISCONNECT_KEY_EXCHANGE_FAILED, "Could not find a shared Client-To-Server Cipher Algorithm"); } public pickCipherServerToClient(): ICipher { for (let algo of this.encryptionAlgorithmsServerToClient) { if (Server.SupportedCiphers.find( (value: string, index: number, obj: Array<string>): boolean => { return (value === algo); })) { switch (algo) { case "3des-cbc": return new TripleDESCBC(); } } } // If no algorithm satisfying all these conditions can be found, the // connection fails, and both sides MUST disconnect. throw new Exceptions.SSHServerException( Exceptions.DisconnectReason.SSH_DISCONNECT_KEY_EXCHANGE_FAILED, "Could not find a shared Server-To-Client Cipher Algorithm"); } public pickMACAlgorithmClientToServer(): IMACAlgorithm { for (let algo of this.macAlgorithmsClientToServer) { if (Server.SupportedMACAlgorithms.find( (value: string, index: number, obj: Array<string>): boolean => { return (value === algo); })) { switch (algo) { case "hmac-sha1": return new HMACSHA1(); } } } // If no algorithm satisfying all these conditions can be found, the // connection fails, and both sides MUST disconnect. throw new Exceptions.SSHServerException( Exceptions.DisconnectReason.SSH_DISCONNECT_KEY_EXCHANGE_FAILED, "Could not find a shared Client-To-Server MAC Algorithm"); } public pickMACAlgorithmServerToClient(): IMACAlgorithm { for (let algo of this.macAlgorithmsServerToClient) { if (Server.SupportedMACAlgorithms.find( (value: string, index: number, obj: Array<string>): boolean => { return (value === algo); })) { switch (algo) { case "hmac-sha1": return new HMACSHA1(); } } } // If no algorithm satisfying all these conditions can be found, the // connection fails, and both sides MUST disconnect. throw new Exceptions.SSHServerException( Exceptions.DisconnectReason.SSH_DISCONNECT_KEY_EXCHANGE_FAILED, "Could not find a shared Server-To-Client MAC Algorithm"); } public pickCompressionAlgorithmClientToServer(): ICompression { for (let algo of this.compressionAlgorithmsClientToServer) { if (Server.SupportedCompressions.find( (value: string, index: number, obj: Array<string>): boolean => { return (value === algo); })) { switch (algo) { case "none": return new NoCompression(); } } } // If no algorithm satisfying all these conditions can be found, the // connection fails, and both sides MUST disconnect. throw new Exceptions.SSHServerException( Exceptions.DisconnectReason.SSH_DISCONNECT_KEY_EXCHANGE_FAILED, "Could not find a shared Client-To-Server Compression Algorithm"); } public pickCompressionAlgorithmServerToClient(): ICompression { for (let algo of this.compressionAlgorithmsServerToClient) { if (Server.SupportedCompressions.find( (value: string, index: number, obj: Array<string>): boolean => { return (value === algo); })) { switch (algo) { case "none": return new NoCompression(); } } } // If no algorithm satisfying all these conditions can be found, the // connection fails, and both sides MUST disconnect. throw new Exceptions.SSHServerException( Exceptions.DisconnectReason.SSH_DISCONNECT_KEY_EXCHANGE_FAILED, "Could not find a shared Server-To-Client Compresion Algorithm"); } }
the_stack
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types"; import { AmplifyBackendClient } from "./AmplifyBackendClient"; import { CloneBackendCommand, CloneBackendCommandInput, CloneBackendCommandOutput, } from "./commands/CloneBackendCommand"; import { CreateBackendAPICommand, CreateBackendAPICommandInput, CreateBackendAPICommandOutput, } from "./commands/CreateBackendAPICommand"; import { CreateBackendAuthCommand, CreateBackendAuthCommandInput, CreateBackendAuthCommandOutput, } from "./commands/CreateBackendAuthCommand"; import { CreateBackendCommand, CreateBackendCommandInput, CreateBackendCommandOutput, } from "./commands/CreateBackendCommand"; import { CreateBackendConfigCommand, CreateBackendConfigCommandInput, CreateBackendConfigCommandOutput, } from "./commands/CreateBackendConfigCommand"; import { CreateTokenCommand, CreateTokenCommandInput, CreateTokenCommandOutput } from "./commands/CreateTokenCommand"; import { DeleteBackendAPICommand, DeleteBackendAPICommandInput, DeleteBackendAPICommandOutput, } from "./commands/DeleteBackendAPICommand"; import { DeleteBackendAuthCommand, DeleteBackendAuthCommandInput, DeleteBackendAuthCommandOutput, } from "./commands/DeleteBackendAuthCommand"; import { DeleteBackendCommand, DeleteBackendCommandInput, DeleteBackendCommandOutput, } from "./commands/DeleteBackendCommand"; import { DeleteTokenCommand, DeleteTokenCommandInput, DeleteTokenCommandOutput } from "./commands/DeleteTokenCommand"; import { GenerateBackendAPIModelsCommand, GenerateBackendAPIModelsCommandInput, GenerateBackendAPIModelsCommandOutput, } from "./commands/GenerateBackendAPIModelsCommand"; import { GetBackendAPICommand, GetBackendAPICommandInput, GetBackendAPICommandOutput, } from "./commands/GetBackendAPICommand"; import { GetBackendAPIModelsCommand, GetBackendAPIModelsCommandInput, GetBackendAPIModelsCommandOutput, } from "./commands/GetBackendAPIModelsCommand"; import { GetBackendAuthCommand, GetBackendAuthCommandInput, GetBackendAuthCommandOutput, } from "./commands/GetBackendAuthCommand"; import { GetBackendCommand, GetBackendCommandInput, GetBackendCommandOutput } from "./commands/GetBackendCommand"; import { GetBackendJobCommand, GetBackendJobCommandInput, GetBackendJobCommandOutput, } from "./commands/GetBackendJobCommand"; import { GetTokenCommand, GetTokenCommandInput, GetTokenCommandOutput } from "./commands/GetTokenCommand"; import { ImportBackendAuthCommand, ImportBackendAuthCommandInput, ImportBackendAuthCommandOutput, } from "./commands/ImportBackendAuthCommand"; import { ListBackendJobsCommand, ListBackendJobsCommandInput, ListBackendJobsCommandOutput, } from "./commands/ListBackendJobsCommand"; import { RemoveAllBackendsCommand, RemoveAllBackendsCommandInput, RemoveAllBackendsCommandOutput, } from "./commands/RemoveAllBackendsCommand"; import { RemoveBackendConfigCommand, RemoveBackendConfigCommandInput, RemoveBackendConfigCommandOutput, } from "./commands/RemoveBackendConfigCommand"; import { UpdateBackendAPICommand, UpdateBackendAPICommandInput, UpdateBackendAPICommandOutput, } from "./commands/UpdateBackendAPICommand"; import { UpdateBackendAuthCommand, UpdateBackendAuthCommandInput, UpdateBackendAuthCommandOutput, } from "./commands/UpdateBackendAuthCommand"; import { UpdateBackendConfigCommand, UpdateBackendConfigCommandInput, UpdateBackendConfigCommandOutput, } from "./commands/UpdateBackendConfigCommand"; import { UpdateBackendJobCommand, UpdateBackendJobCommandInput, UpdateBackendJobCommandOutput, } from "./commands/UpdateBackendJobCommand"; /** * <p>AWS Amplify Admin API</p> */ export class AmplifyBackend extends AmplifyBackendClient { /** * <p>This operation clones an existing backend.</p> */ public cloneBackend( args: CloneBackendCommandInput, options?: __HttpHandlerOptions ): Promise<CloneBackendCommandOutput>; public cloneBackend(args: CloneBackendCommandInput, cb: (err: any, data?: CloneBackendCommandOutput) => void): void; public cloneBackend( args: CloneBackendCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CloneBackendCommandOutput) => void ): void; public cloneBackend( args: CloneBackendCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CloneBackendCommandOutput) => void), cb?: (err: any, data?: CloneBackendCommandOutput) => void ): Promise<CloneBackendCommandOutput> | void { const command = new CloneBackendCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>This operation creates a backend for an Amplify app. Backends are automatically created at the time of app creation.</p> */ public createBackend( args: CreateBackendCommandInput, options?: __HttpHandlerOptions ): Promise<CreateBackendCommandOutput>; public createBackend( args: CreateBackendCommandInput, cb: (err: any, data?: CreateBackendCommandOutput) => void ): void; public createBackend( args: CreateBackendCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateBackendCommandOutput) => void ): void; public createBackend( args: CreateBackendCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateBackendCommandOutput) => void), cb?: (err: any, data?: CreateBackendCommandOutput) => void ): Promise<CreateBackendCommandOutput> | void { const command = new CreateBackendCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a new backend API resource.</p> */ public createBackendAPI( args: CreateBackendAPICommandInput, options?: __HttpHandlerOptions ): Promise<CreateBackendAPICommandOutput>; public createBackendAPI( args: CreateBackendAPICommandInput, cb: (err: any, data?: CreateBackendAPICommandOutput) => void ): void; public createBackendAPI( args: CreateBackendAPICommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateBackendAPICommandOutput) => void ): void; public createBackendAPI( args: CreateBackendAPICommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateBackendAPICommandOutput) => void), cb?: (err: any, data?: CreateBackendAPICommandOutput) => void ): Promise<CreateBackendAPICommandOutput> | void { const command = new CreateBackendAPICommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a new backend authentication resource.</p> */ public createBackendAuth( args: CreateBackendAuthCommandInput, options?: __HttpHandlerOptions ): Promise<CreateBackendAuthCommandOutput>; public createBackendAuth( args: CreateBackendAuthCommandInput, cb: (err: any, data?: CreateBackendAuthCommandOutput) => void ): void; public createBackendAuth( args: CreateBackendAuthCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateBackendAuthCommandOutput) => void ): void; public createBackendAuth( args: CreateBackendAuthCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateBackendAuthCommandOutput) => void), cb?: (err: any, data?: CreateBackendAuthCommandOutput) => void ): Promise<CreateBackendAuthCommandOutput> | void { const command = new CreateBackendAuthCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a config object for a backend.</p> */ public createBackendConfig( args: CreateBackendConfigCommandInput, options?: __HttpHandlerOptions ): Promise<CreateBackendConfigCommandOutput>; public createBackendConfig( args: CreateBackendConfigCommandInput, cb: (err: any, data?: CreateBackendConfigCommandOutput) => void ): void; public createBackendConfig( args: CreateBackendConfigCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateBackendConfigCommandOutput) => void ): void; public createBackendConfig( args: CreateBackendConfigCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateBackendConfigCommandOutput) => void), cb?: (err: any, data?: CreateBackendConfigCommandOutput) => void ): Promise<CreateBackendConfigCommandOutput> | void { const command = new CreateBackendConfigCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Generates a one-time challenge code to authenticate a user into your Amplify Admin UI.</p> */ public createToken(args: CreateTokenCommandInput, options?: __HttpHandlerOptions): Promise<CreateTokenCommandOutput>; public createToken(args: CreateTokenCommandInput, cb: (err: any, data?: CreateTokenCommandOutput) => void): void; public createToken( args: CreateTokenCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateTokenCommandOutput) => void ): void; public createToken( args: CreateTokenCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateTokenCommandOutput) => void), cb?: (err: any, data?: CreateTokenCommandOutput) => void ): Promise<CreateTokenCommandOutput> | void { const command = new CreateTokenCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Removes an existing environment from your Amplify project.</p> */ public deleteBackend( args: DeleteBackendCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteBackendCommandOutput>; public deleteBackend( args: DeleteBackendCommandInput, cb: (err: any, data?: DeleteBackendCommandOutput) => void ): void; public deleteBackend( args: DeleteBackendCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteBackendCommandOutput) => void ): void; public deleteBackend( args: DeleteBackendCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteBackendCommandOutput) => void), cb?: (err: any, data?: DeleteBackendCommandOutput) => void ): Promise<DeleteBackendCommandOutput> | void { const command = new DeleteBackendCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes an existing backend API resource.</p> */ public deleteBackendAPI( args: DeleteBackendAPICommandInput, options?: __HttpHandlerOptions ): Promise<DeleteBackendAPICommandOutput>; public deleteBackendAPI( args: DeleteBackendAPICommandInput, cb: (err: any, data?: DeleteBackendAPICommandOutput) => void ): void; public deleteBackendAPI( args: DeleteBackendAPICommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteBackendAPICommandOutput) => void ): void; public deleteBackendAPI( args: DeleteBackendAPICommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteBackendAPICommandOutput) => void), cb?: (err: any, data?: DeleteBackendAPICommandOutput) => void ): Promise<DeleteBackendAPICommandOutput> | void { const command = new DeleteBackendAPICommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes an existing backend authentication resource.</p> */ public deleteBackendAuth( args: DeleteBackendAuthCommandInput, options?: __HttpHandlerOptions ): Promise<DeleteBackendAuthCommandOutput>; public deleteBackendAuth( args: DeleteBackendAuthCommandInput, cb: (err: any, data?: DeleteBackendAuthCommandOutput) => void ): void; public deleteBackendAuth( args: DeleteBackendAuthCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteBackendAuthCommandOutput) => void ): void; public deleteBackendAuth( args: DeleteBackendAuthCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteBackendAuthCommandOutput) => void), cb?: (err: any, data?: DeleteBackendAuthCommandOutput) => void ): Promise<DeleteBackendAuthCommandOutput> | void { const command = new DeleteBackendAuthCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes the challenge token based on the given appId and sessionId.</p> */ public deleteToken(args: DeleteTokenCommandInput, options?: __HttpHandlerOptions): Promise<DeleteTokenCommandOutput>; public deleteToken(args: DeleteTokenCommandInput, cb: (err: any, data?: DeleteTokenCommandOutput) => void): void; public deleteToken( args: DeleteTokenCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteTokenCommandOutput) => void ): void; public deleteToken( args: DeleteTokenCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteTokenCommandOutput) => void), cb?: (err: any, data?: DeleteTokenCommandOutput) => void ): Promise<DeleteTokenCommandOutput> | void { const command = new DeleteTokenCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Generates a model schema for an existing backend API resource.</p> */ public generateBackendAPIModels( args: GenerateBackendAPIModelsCommandInput, options?: __HttpHandlerOptions ): Promise<GenerateBackendAPIModelsCommandOutput>; public generateBackendAPIModels( args: GenerateBackendAPIModelsCommandInput, cb: (err: any, data?: GenerateBackendAPIModelsCommandOutput) => void ): void; public generateBackendAPIModels( args: GenerateBackendAPIModelsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GenerateBackendAPIModelsCommandOutput) => void ): void; public generateBackendAPIModels( args: GenerateBackendAPIModelsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GenerateBackendAPIModelsCommandOutput) => void), cb?: (err: any, data?: GenerateBackendAPIModelsCommandOutput) => void ): Promise<GenerateBackendAPIModelsCommandOutput> | void { const command = new GenerateBackendAPIModelsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Provides project-level details for your Amplify UI project.</p> */ public getBackend(args: GetBackendCommandInput, options?: __HttpHandlerOptions): Promise<GetBackendCommandOutput>; public getBackend(args: GetBackendCommandInput, cb: (err: any, data?: GetBackendCommandOutput) => void): void; public getBackend( args: GetBackendCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetBackendCommandOutput) => void ): void; public getBackend( args: GetBackendCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetBackendCommandOutput) => void), cb?: (err: any, data?: GetBackendCommandOutput) => void ): Promise<GetBackendCommandOutput> | void { const command = new GetBackendCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Gets the details for a backend API.</p> */ public getBackendAPI( args: GetBackendAPICommandInput, options?: __HttpHandlerOptions ): Promise<GetBackendAPICommandOutput>; public getBackendAPI( args: GetBackendAPICommandInput, cb: (err: any, data?: GetBackendAPICommandOutput) => void ): void; public getBackendAPI( args: GetBackendAPICommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetBackendAPICommandOutput) => void ): void; public getBackendAPI( args: GetBackendAPICommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetBackendAPICommandOutput) => void), cb?: (err: any, data?: GetBackendAPICommandOutput) => void ): Promise<GetBackendAPICommandOutput> | void { const command = new GetBackendAPICommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Generates a model schema for existing backend API resource.</p> */ public getBackendAPIModels( args: GetBackendAPIModelsCommandInput, options?: __HttpHandlerOptions ): Promise<GetBackendAPIModelsCommandOutput>; public getBackendAPIModels( args: GetBackendAPIModelsCommandInput, cb: (err: any, data?: GetBackendAPIModelsCommandOutput) => void ): void; public getBackendAPIModels( args: GetBackendAPIModelsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetBackendAPIModelsCommandOutput) => void ): void; public getBackendAPIModels( args: GetBackendAPIModelsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetBackendAPIModelsCommandOutput) => void), cb?: (err: any, data?: GetBackendAPIModelsCommandOutput) => void ): Promise<GetBackendAPIModelsCommandOutput> | void { const command = new GetBackendAPIModelsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Gets a backend auth details.</p> */ public getBackendAuth( args: GetBackendAuthCommandInput, options?: __HttpHandlerOptions ): Promise<GetBackendAuthCommandOutput>; public getBackendAuth( args: GetBackendAuthCommandInput, cb: (err: any, data?: GetBackendAuthCommandOutput) => void ): void; public getBackendAuth( args: GetBackendAuthCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetBackendAuthCommandOutput) => void ): void; public getBackendAuth( args: GetBackendAuthCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetBackendAuthCommandOutput) => void), cb?: (err: any, data?: GetBackendAuthCommandOutput) => void ): Promise<GetBackendAuthCommandOutput> | void { const command = new GetBackendAuthCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns information about a specific job.</p> */ public getBackendJob( args: GetBackendJobCommandInput, options?: __HttpHandlerOptions ): Promise<GetBackendJobCommandOutput>; public getBackendJob( args: GetBackendJobCommandInput, cb: (err: any, data?: GetBackendJobCommandOutput) => void ): void; public getBackendJob( args: GetBackendJobCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetBackendJobCommandOutput) => void ): void; public getBackendJob( args: GetBackendJobCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetBackendJobCommandOutput) => void), cb?: (err: any, data?: GetBackendJobCommandOutput) => void ): Promise<GetBackendJobCommandOutput> | void { const command = new GetBackendJobCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Gets the challenge token based on the given appId and sessionId.</p> */ public getToken(args: GetTokenCommandInput, options?: __HttpHandlerOptions): Promise<GetTokenCommandOutput>; public getToken(args: GetTokenCommandInput, cb: (err: any, data?: GetTokenCommandOutput) => void): void; public getToken( args: GetTokenCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetTokenCommandOutput) => void ): void; public getToken( args: GetTokenCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetTokenCommandOutput) => void), cb?: (err: any, data?: GetTokenCommandOutput) => void ): Promise<GetTokenCommandOutput> | void { const command = new GetTokenCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Imports an existing backend authentication resource.</p> */ public importBackendAuth( args: ImportBackendAuthCommandInput, options?: __HttpHandlerOptions ): Promise<ImportBackendAuthCommandOutput>; public importBackendAuth( args: ImportBackendAuthCommandInput, cb: (err: any, data?: ImportBackendAuthCommandOutput) => void ): void; public importBackendAuth( args: ImportBackendAuthCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ImportBackendAuthCommandOutput) => void ): void; public importBackendAuth( args: ImportBackendAuthCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ImportBackendAuthCommandOutput) => void), cb?: (err: any, data?: ImportBackendAuthCommandOutput) => void ): Promise<ImportBackendAuthCommandOutput> | void { const command = new ImportBackendAuthCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists the jobs for the backend of an Amplify app.</p> */ public listBackendJobs( args: ListBackendJobsCommandInput, options?: __HttpHandlerOptions ): Promise<ListBackendJobsCommandOutput>; public listBackendJobs( args: ListBackendJobsCommandInput, cb: (err: any, data?: ListBackendJobsCommandOutput) => void ): void; public listBackendJobs( args: ListBackendJobsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListBackendJobsCommandOutput) => void ): void; public listBackendJobs( args: ListBackendJobsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListBackendJobsCommandOutput) => void), cb?: (err: any, data?: ListBackendJobsCommandOutput) => void ): Promise<ListBackendJobsCommandOutput> | void { const command = new ListBackendJobsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Removes all backend environments from your Amplify project.</p> */ public removeAllBackends( args: RemoveAllBackendsCommandInput, options?: __HttpHandlerOptions ): Promise<RemoveAllBackendsCommandOutput>; public removeAllBackends( args: RemoveAllBackendsCommandInput, cb: (err: any, data?: RemoveAllBackendsCommandOutput) => void ): void; public removeAllBackends( args: RemoveAllBackendsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: RemoveAllBackendsCommandOutput) => void ): void; public removeAllBackends( args: RemoveAllBackendsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RemoveAllBackendsCommandOutput) => void), cb?: (err: any, data?: RemoveAllBackendsCommandOutput) => void ): Promise<RemoveAllBackendsCommandOutput> | void { const command = new RemoveAllBackendsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Removes the AWS resources required to access the Amplify Admin UI.</p> */ public removeBackendConfig( args: RemoveBackendConfigCommandInput, options?: __HttpHandlerOptions ): Promise<RemoveBackendConfigCommandOutput>; public removeBackendConfig( args: RemoveBackendConfigCommandInput, cb: (err: any, data?: RemoveBackendConfigCommandOutput) => void ): void; public removeBackendConfig( args: RemoveBackendConfigCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: RemoveBackendConfigCommandOutput) => void ): void; public removeBackendConfig( args: RemoveBackendConfigCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RemoveBackendConfigCommandOutput) => void), cb?: (err: any, data?: RemoveBackendConfigCommandOutput) => void ): Promise<RemoveBackendConfigCommandOutput> | void { const command = new RemoveBackendConfigCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Updates an existing backend API resource.</p> */ public updateBackendAPI( args: UpdateBackendAPICommandInput, options?: __HttpHandlerOptions ): Promise<UpdateBackendAPICommandOutput>; public updateBackendAPI( args: UpdateBackendAPICommandInput, cb: (err: any, data?: UpdateBackendAPICommandOutput) => void ): void; public updateBackendAPI( args: UpdateBackendAPICommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateBackendAPICommandOutput) => void ): void; public updateBackendAPI( args: UpdateBackendAPICommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateBackendAPICommandOutput) => void), cb?: (err: any, data?: UpdateBackendAPICommandOutput) => void ): Promise<UpdateBackendAPICommandOutput> | void { const command = new UpdateBackendAPICommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Updates an existing backend authentication resource.</p> */ public updateBackendAuth( args: UpdateBackendAuthCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateBackendAuthCommandOutput>; public updateBackendAuth( args: UpdateBackendAuthCommandInput, cb: (err: any, data?: UpdateBackendAuthCommandOutput) => void ): void; public updateBackendAuth( args: UpdateBackendAuthCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateBackendAuthCommandOutput) => void ): void; public updateBackendAuth( args: UpdateBackendAuthCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateBackendAuthCommandOutput) => void), cb?: (err: any, data?: UpdateBackendAuthCommandOutput) => void ): Promise<UpdateBackendAuthCommandOutput> | void { const command = new UpdateBackendAuthCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Updates the AWS resources required to access the Amplify Admin UI.</p> */ public updateBackendConfig( args: UpdateBackendConfigCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateBackendConfigCommandOutput>; public updateBackendConfig( args: UpdateBackendConfigCommandInput, cb: (err: any, data?: UpdateBackendConfigCommandOutput) => void ): void; public updateBackendConfig( args: UpdateBackendConfigCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateBackendConfigCommandOutput) => void ): void; public updateBackendConfig( args: UpdateBackendConfigCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateBackendConfigCommandOutput) => void), cb?: (err: any, data?: UpdateBackendConfigCommandOutput) => void ): Promise<UpdateBackendConfigCommandOutput> | void { const command = new UpdateBackendConfigCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Updates a specific job.</p> */ public updateBackendJob( args: UpdateBackendJobCommandInput, options?: __HttpHandlerOptions ): Promise<UpdateBackendJobCommandOutput>; public updateBackendJob( args: UpdateBackendJobCommandInput, cb: (err: any, data?: UpdateBackendJobCommandOutput) => void ): void; public updateBackendJob( args: UpdateBackendJobCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateBackendJobCommandOutput) => void ): void; public updateBackendJob( args: UpdateBackendJobCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateBackendJobCommandOutput) => void), cb?: (err: any, data?: UpdateBackendJobCommandOutput) => void ): Promise<UpdateBackendJobCommandOutput> | void { const command = new UpdateBackendJobCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } }
the_stack
import { useState, useMemo, useContext } from 'react'; import moment from 'moment'; import { message, Modal, Button, Tooltip } from 'antd'; import { SyncOutlined } from '@ant-design/icons'; import type { ColumnsType, FilterValue, SorterResult } from 'antd/lib/table/interface'; import SlidePane from '@/components/slidePane'; import context from '@/context'; import Api from '@/api'; import { TaskStatus, taskTypeText } from '@/utils/enums'; import { TASK_STATUS_FILTERS, RESTART_STATUS_ENUM, STATISTICS_TYPE_ENUM, TASK_STATUS, } from '@/constant'; import Sketch, { useSketchRef } from '@/components/sketch'; import TaskJobFlowView from '../taskJobFlowView'; import type { IScheduleTaskProps } from '../schedule'; import { getTodayTime, removePopUpMenu } from '@/utils'; import './detail.scss'; const { confirm, warning } = Modal; const yesterDay = moment().subtract(1, 'days'); // 任务类型 type ITableDataProps = IScheduleTaskProps; // 请求参数类型 interface IRequestParams { currentPage: number; pageSize: number; taskName: string; operatorId: number; cycStartDay: number; cycEndDay: number; jobStatusList: number[]; taskTypeList: string[]; execTimeSort: string | undefined; execStartSort: string | undefined; cycSort: string | undefined; businessDateSort: string | undefined; retryNumSort: string | undefined; fillId: number; } // 条件筛选表单类型 interface IFormFieldProps { name?: string; owner?: number; rangeDate?: [moment.Moment, moment.Moment]; } const disabledDate = (current: moment.Moment) => { return current && current.valueOf() > new Date().getTime(); }; export default () => { const { supportJobTypes } = useContext(context); const [fillId] = useState(() => Number(JSON.parse(sessionStorage.getItem('task-patch-data') || '{}').id), ); const [statistics, setStatistics] = useState<Record<string, number>>({}); const [selectedTask, setSelectedTask] = useState<ITableDataProps | null>(null); const [visibleSlidePane, setSlideVisible] = useState(false); const [btnStatus, setBtnStatus] = useState([false, false]); const actionRef = useSketchRef(); const loadJobStatics = (params: any) => { Api.queryJobStatics({ ...params, type: STATISTICS_TYPE_ENUM.FILL_DATA, fillTaskName: params.fillJobName, }).then((res) => { if (res.code === 1) { const data: { count: TASK_STATUS; statusKey: string }[] = res.data || []; const nextStat = data.reduce((pre, cur) => { const next = pre; next[cur.statusKey] = cur.count; return next; }, {} as Record<string, TASK_STATUS>); setStatistics(nextStat); } }); }; const showTask = (task: ITableDataProps) => { setSlideVisible(true); setSelectedTask(task); }; // 是否可以进行kill const canKill = (ids: React.Key[]) => { const tasks: ITableDataProps[] = actionRef.current?.getTableData() || []; if (ids && ids.length > 0) { for (let i = 0; i < ids.length; i += 1) { const id = ids[i]; const res = tasks.find((task) => task.jobId.toString() === id.toString()); if ( res && (res.status === TASK_STATUS.SUBMIT_FAILED || res.status === TASK_STATUS.RUN_FAILED || res.status === TASK_STATUS.PARENT_FAILD || res.status === TASK_STATUS.STOPED || res.status === TASK_STATUS.FINISHED) ) return false; } return true; } }; // 批量杀任务 const batchKillJobs = () => { const selected = actionRef.current?.selectedRowKeys; if (!selected || selected.length <= 0) { warning({ title: '提示', content: '您没有选择任何需要杀死的任务!', }); return; } if (canKill(selected)) { confirm({ title: '确认提示', content: '确定要杀死选择的任务?', onOk() { Api.batchStopJob({ jobIds: selected }).then((res) => { if (res.code === 1) { actionRef.current?.setSelectedKeys([]); actionRef.current?.submit(); message.success('已经成功杀死所选任务!'); } }); }, }); } else { warning({ title: '提示', content: ` “失败”、“取消”、“成功”状态和“已删除”的任务,不能被杀死 ! `, }); } }; const canReload = (ids: React.Key[]) => { // 未运行、成功、失败的任务可以reload const tasks: ITableDataProps[] = actionRef.current?.getTableData() || []; if (ids && ids.length > 0) { for (let i = 0; i < ids.length; i += 1) { const id = ids[i]; const task = tasks.find((item) => item.jobId.toString() === id.toString()); if ( task && task.status !== TASK_STATUS.WAIT_SUBMIT && task.status !== TASK_STATUS.FINISHED && task.status !== TASK_STATUS.RUN_FAILED && task.status !== TASK_STATUS.SUBMIT_FAILED && task.status !== TASK_STATUS.STOPED && task.status !== TASK_STATUS.KILLED && task.status !== TASK_STATUS.PARENT_FAILD ) return false; } return true; } }; const batchReloadJobs = () => { // 批量重跑 const selected = actionRef.current?.selectedRowKeys; if (!selected || selected.length <= 0) { warning({ title: '提示', content: '您没有选择任何需要重跑的任务!', }); return; } if (canReload(selected)) { confirm({ title: '确认提示', content: '确认需要重跑选择的任务?', onOk() { Api.batchRestartAndResume({ jobIds: selected, restartType: RESTART_STATUS_ENUM.DOWNSTREAM, }).then((res: any) => { if (res.code === 1) { message.success('已经成功重跑所选任务!'); actionRef.current?.setSelectedKeys([]); actionRef.current?.submit(); } }); }, }); } else { warning({ title: '提示', content: ` 只有“未运行、成功、失败、取消”状态下的任务可以进行重跑操作, 请您重新选择! `, }); } }; // 杀死所有实例 const killAllJobs = () => { Api.stopFillDataJobs({ fillId, }).then((res) => { if (res.code === 1) { actionRef.current?.submit(); message.success('已成功杀死所有实例!'); } }); }; const closeSlidePane = () => { setSlideVisible(false); setSelectedTask(null); removePopUpMenu(); }; const renderStatus = (list: typeof statusList) => { return list.map((item, index) => { const { className, children } = item; return ( <span key={index} className={className}> {children.map((childItem) => { return ( <span key={childItem.title}> {childItem.title}: {childItem.dataSource || 0} </span> ); })} </span> ); }); }; const statusList = useMemo(() => { const { ALL, RUNNING, UNSUBMIT, SUBMITTING, WAITENGINE, FINISHED, CANCELED, FROZEN, SUBMITFAILD, FAILED, PARENTFAILED, } = statistics; return [ { className: 'status_overview_count_font', children: [{ title: '总数', dataSource: ALL }], }, { className: 'status_overview_running_font', children: [{ title: '运行中', dataSource: RUNNING }], }, { className: 'status_overview_yellow_font', children: [ { title: '等待提交', dataSource: UNSUBMIT }, { title: '提交中', dataSource: SUBMITTING }, { title: '等待运行', dataSource: WAITENGINE }, ], }, { className: 'status_overview_finished_font', children: [{ title: '成功', dataSource: FINISHED }], }, { className: 'status_overview_grey_font', children: [ { title: '取消', dataSource: CANCELED }, { title: '冻结', dataSource: FROZEN }, ], }, { className: 'status_overview_fail_font', children: [ { title: '提交失败', dataSource: SUBMITFAILD }, { title: '运行失败', dataSource: FAILED }, { title: '上游失败', dataSource: PARENTFAILED }, ], }, ]; }, [statistics]); const columns = useMemo<ColumnsType<ITableDataProps>>(() => { return [ { title: '任务名称', dataIndex: 'jobName', key: 'jobName', width: 200, fixed: 'left', render: (_, record) => { const name = record.taskName; const originText = name; let showName: React.ReactNode; if ( record.retryNum && [TASK_STATUS.WAIT_RUN, TASK_STATUS.RUNNING].indexOf(record.status) > -1 ) { showName = ( <a onClick={() => { showTask(record); }} > {name}(重试) </a> ); } else { showName = ( <a onClick={() => { showTask(record); }} > {name} </a> ); } return <span title={originText}>{showName}</span>; }, }, { title: '状态', dataIndex: 'status', key: 'status', fixed: 'left', render: (text) => { return <TaskStatus value={text} />; }, width: '110px', filters: TASK_STATUS_FILTERS, filterMultiple: true, }, { title: '任务类型', dataIndex: 'taskType', key: 'taskType', width: '100px', render: (text) => { return taskTypeText(text); }, filters: supportJobTypes.map((t) => ({ text: t.value, value: t.key })), }, { title: '计划时间', dataIndex: 'cycTime', key: 'cycTime', width: '180px', sorter: true, }, { title: '开始时间', dataIndex: 'startExecTime', key: 'startExecTime', width: 160, sorter: true, }, { title: '结束时间', dataIndex: 'endExecTime', key: 'endExecTime', width: 160, sorter: true, }, { title: '运行时长', dataIndex: 'execTime', key: 'execTime', width: '150px', sorter: true, }, { title: '重试次数', dataIndex: 'retryNum', key: 'retryNum', width: '120px', sorter: true, }, { title: '操作人', dataIndex: 'operatorName', key: 'operatorName', width: '180px', }, ]; }, [supportJobTypes]); const convertToParams = (values: IFormFieldProps): Partial<IRequestParams> => { return { fillId: fillId || undefined, taskName: values.name, operatorId: values.owner, cycStartDay: values.rangeDate && getTodayTime(values.rangeDate[0])[0].unix(), cycEndDay: values.rangeDate && getTodayTime(values.rangeDate[1])[1].unix(), }; }; const handleSketchRequest = async ( values: IFormFieldProps, { current, pageSize }: { current: number; pageSize: number }, filters: Record<string, FilterValue | null>, sorter?: SorterResult<any>, ) => { const params = convertToParams(values); const { status = [], taskType = [] } = filters; const sortMapping: Record<string, string> = { execTime: 'execTimeSort', cycTime: 'cycSort', startExecTime: 'execStartSort', endExecTime: 'execTimeSort', retryNum: 'retryNumSort', }; const orderMapping = { descend: 'desc', ascend: 'asc', }; const { field = 'cycTime', order } = sorter || {}; const sortKey = sortMapping[field as string]; const sortValue = orderMapping[order || 'descend']; const queryParams: Partial<IRequestParams> = { ...params, currentPage: current, pageSize, jobStatusList: (status || []) as number[], taskTypeList: (taskType || []) as string[], [sortKey]: sortValue, }; loadJobStatics(queryParams); return Api.getFillDataDetail(queryParams).then((res) => { if (res.code === 1) { actionRef.current?.setSelectedKeys([]); return { polling: true, total: res.data.totalCount, data: res.data.data.fillDataJobVOLists || [], }; } }); }; const handleTableSelect = (_: any, rows: ITableDataProps[]) => { let haveFail = false; let haveNotRun = false; let haveSuccess = false; let haveRunning = false; const selectedRows = rows || []; for (let i = 0; i < selectedRows.length; i += 1) { const row = selectedRows[i]; switch (row.status) { case TASK_STATUS.RUN_FAILED: case TASK_STATUS.PARENT_FAILD: case TASK_STATUS.SUBMIT_FAILED: { haveFail = true; break; } case TASK_STATUS.RUNNING: case TASK_STATUS.SUBMITTING: case TASK_STATUS.WAIT_SUBMIT: case TASK_STATUS.WAIT_RUN: { haveRunning = true; break; } case TASK_STATUS.FINISHED: { haveSuccess = true; break; } default: { haveNotRun = true; break; } } } const couldKill = haveRunning && !haveFail && !haveNotRun && !haveFail; const couldReRun = !haveRunning && (haveSuccess || haveFail || haveNotRun || haveFail); setBtnStatus([couldKill, couldReRun]); }; const handleRefresh = () => { actionRef.current?.submit(); }; return ( <div className="dt-patch-data-detail"> <Sketch<ITableDataProps, IFormFieldProps> actionRef={actionRef} request={handleSketchRequest} onTableSelect={handleTableSelect} header={[ 'input', 'owner', { name: 'rangeDate', props: { formItemProps: { label: '计划时间', }, slotProps: { ranges: { 昨天: [moment().subtract(2, 'days'), yesterDay], 最近7天: [moment().subtract(8, 'days'), yesterDay], 最近30天: [moment().subtract(31, 'days'), yesterDay], }, disabledDate, }, }, }, ]} extra={ <Tooltip title="刷新数据"> <Button className="dt-refresh"> <SyncOutlined onClick={() => handleRefresh()} /> </Button> </Tooltip> } headerTitle={renderStatus(statusList)} headerTitleClassName="ope-statistics" columns={columns} tableProps={{ rowKey: 'jobId', rowClassName: (record) => { if (selectedTask && selectedTask.taskId === record.taskId) { return 'row-select'; } return ''; }, }} tableFooter={[ <Button disabled={!btnStatus[0]} key="kill" style={{ marginRight: 12 }} type="primary" onClick={batchKillJobs} > 批量杀任务 </Button>, <Button disabled={!btnStatus[1]} style={{ marginRight: 12 }} key="reload" type="primary" onClick={batchReloadJobs} > 重跑当前及下游任务 </Button>, <Button key="killAll" type="primary" onClick={killAllJobs}> 杀死所有实例 </Button>, ]} /> <SlidePane onClose={closeSlidePane} visible={visibleSlidePane} style={{ right: '0px', width: '60%', bottom: 0, minHeight: '400px', position: 'fixed', paddingTop: '64px', paddingBottom: 22, }} > <TaskJobFlowView taskJob={selectedTask} visibleSlidePane={visibleSlidePane} reload={() => actionRef.current?.submit()} /> </SlidePane> </div> ); };
the_stack
import { alt, any, optWhitespace, Parser, seq, string, succeed } from 'parsimmon'; import { Position, Range } from 'vscode'; import { ErrorCode, VimError } from '../error'; import { globalState } from '../state/globalState'; import { SearchState } from '../state/searchState'; import { VimState } from '../state/vimState'; import { numberParser } from './parserUtils'; import { Pattern, SearchDirection } from './pattern'; /** * Specifies the start or end of a line range. * See :help {address} */ type LineSpecifier = | { // {number} type: 'number'; num: number; } | { // . type: 'current_line'; } | { // $ type: 'last_line'; } | { // % type: 'entire_file'; } | { // * type: 'last_visual_range'; } | { // 't type: 'mark'; mark: string; } | { // /{pattern}[/] type: 'pattern_next'; pattern: Pattern; } | { // ?{pattern}[?] type: 'pattern_prev'; pattern: Pattern; } | { // \/ type: 'last_search_pattern_next'; } | { // \? type: 'last_search_pattern_prev'; } | { // \& type: 'last_substitute_pattern_next'; }; const lineSpecifierParser: Parser<LineSpecifier> = alt( numberParser.map((num) => { return { type: 'number', num }; }), string('.').result({ type: 'current_line' }), string('$').result({ type: 'last_line' }), string('%').result({ type: 'entire_file' }), string('*').result({ type: 'last_visual_range' }), string("'") .then(any) .map((mark) => { return { type: 'mark', mark }; }), string('/') .then(Pattern.parser({ direction: SearchDirection.Forward })) .map((pattern) => { return { type: 'pattern_next', pattern, }; }), string('?') .then(Pattern.parser({ direction: SearchDirection.Backward })) .map((pattern) => { return { type: 'pattern_prev', pattern, }; }), string('\\/').result({ type: 'last_search_pattern_next' }), string('\\?').result({ type: 'last_search_pattern_prev' }), string('\\&').result({ type: 'last_substitute_pattern_next' }) ); const offsetParser: Parser<number> = alt( string('+').then(numberParser.fallback(1)), string('-') .then(numberParser.fallback(1)) .map((num) => -num), numberParser ) .skip(optWhitespace) .atLeast(1) .map((nums) => nums.reduce((x, y) => x + y, 0)); export class Address { public readonly specifier: LineSpecifier; public readonly offset: number; constructor(specifier: LineSpecifier, offset?: number) { this.specifier = specifier; this.offset = offset ?? 0; } public static parser: Parser<Address> = alt( seq(lineSpecifierParser.skip(optWhitespace), offsetParser.fallback(0)), seq(succeed({ type: 'current_line' as const }), offsetParser) ).map(([specifier, offset]) => { return new Address(specifier, offset); }); public resolve(vimState: VimState, side: 'left' | 'right', boundsCheck = true): number { const line = (() => { switch (this.specifier.type) { case 'number': if (boundsCheck) { return this.specifier.num ? this.specifier.num - 1 : 0; } else { return this.specifier.num - 1; } case 'current_line': return vimState.cursorStopPosition.line; case 'last_line': return vimState.document.lineCount - 1; case 'entire_file': return vimState.document.lineCount - 1; case 'last_visual_range': const res = side === 'left' ? vimState.lastVisualSelection?.start.line : vimState.lastVisualSelection?.end.line; if (res === undefined) { throw VimError.fromCode(ErrorCode.MarkNotSet); } return res; case 'mark': const mark = vimState.historyTracker.getMark(this.specifier.mark); if (!mark || (mark.document && mark.document !== vimState.document)) { throw VimError.fromCode(ErrorCode.MarkNotSet); } return mark.position.line; case 'pattern_next': const m = this.specifier.pattern.nextMatch( vimState.document, vimState.cursorStopPosition ); if (m === undefined) { // TODO: throw proper errors for nowrapscan throw VimError.fromCode( ErrorCode.PatternNotFound, this.specifier.pattern.patternString ); } else { return m.start.line; } case 'pattern_prev': throw new Error('Using a backward pattern in a line range is not yet supported'); // TODO case 'last_search_pattern_next': if (!globalState.searchState) { throw VimError.fromCode(ErrorCode.NoPreviousRegularExpression); } const nextMatch = globalState.searchState.getNextSearchMatchPosition( vimState.editor, vimState.cursorStopPosition, SearchDirection.Forward ); if (nextMatch === undefined) { // TODO: throw proper errors for nowrapscan throw VimError.fromCode( ErrorCode.PatternNotFound, globalState.searchState.searchString ); } return nextMatch.pos.line; case 'last_search_pattern_prev': if (!globalState.searchState) { throw VimError.fromCode(ErrorCode.NoPreviousRegularExpression); } const prevMatch = globalState.searchState.getNextSearchMatchPosition( vimState.editor, vimState.cursorStopPosition, SearchDirection.Backward ); if (prevMatch === undefined) { // TODO: throw proper errors for nowrapscan throw VimError.fromCode( ErrorCode.PatternNotFound, globalState.searchState.searchString ); } return prevMatch.pos.line; case 'last_substitute_pattern_next': if (!globalState.substituteState) { throw VimError.fromCode(ErrorCode.NoPreviousSubstituteRegularExpression); } const searchState = globalState.substituteState.searchPattern ? new SearchState( SearchDirection.Forward, vimState.cursorStopPosition, globalState.substituteState.searchPattern.patternString, {}, vimState.currentMode ) : undefined; const match = searchState?.getNextSearchMatchPosition( vimState.editor, vimState.cursorStopPosition ); if (match === undefined) { // TODO: throw proper errors for nowrapscan throw VimError.fromCode(ErrorCode.PatternNotFound, searchState?.searchString); } return match.pos.line; default: const guard: never = this.specifier; throw new Error('Got unexpected LineSpecifier.type'); } })(); const result = line + this.offset; if (boundsCheck && (result < 0 || result > vimState.document.lineCount)) { throw VimError.fromCode(ErrorCode.InvalidRange); } return result; } public toString(): string { switch (this.specifier.type) { case 'number': return this.specifier.num.toString(); case 'current_line': return '.'; case 'last_line': return '$'; case 'entire_file': return '%'; case 'last_visual_range': return '*'; case 'mark': return `'${this.specifier.mark}`; case 'pattern_next': return `/${this.specifier.pattern}/`; case 'pattern_prev': return `?${this.specifier.pattern}?`; case 'last_search_pattern_next': return '\\/'; case 'last_search_pattern_prev': return '\\?'; case 'last_substitute_pattern_next': return '\\&'; default: const guard: never = this.specifier; throw new Error('Got unexpected LineSpecifier.type'); } } } export class LineRange { private readonly start: Address; private readonly end?: Address; public readonly separator?: ',' | ';'; constructor(start: Address, separator?: ',' | ';', end?: Address) { this.start = start; this.end = end; this.separator = separator; } public static parser: Parser<LineRange> = seq( Address.parser.skip(optWhitespace), seq( alt(string(','), string(';')).skip(optWhitespace), Address.parser.fallback(undefined) ).fallback(undefined) ).map(([start, sepEnd]) => { if (sepEnd) { const [sep, end] = sepEnd; return new LineRange(start, sep, end); } return new LineRange(start); }); public resolve(vimState: VimState): { start: number; end: number } { // TODO: *,4 is not a valid range const end = this.end ?? this.start; if (end.specifier.type === 'entire_file') { return { start: 0, end: vimState.document.lineCount - 1 }; } else if (end.specifier.type === 'last_visual_range') { if (vimState.lastVisualSelection === undefined) { throw VimError.fromCode(ErrorCode.MarkNotSet); } return { start: vimState.lastVisualSelection.start.line, end: vimState.lastVisualSelection.end.line, }; } const left = this.start.resolve(vimState, 'left'); if (this.separator === ';') { vimState.cursorStartPosition = vimState.cursorStopPosition = new Position(left, 0); } const right = end.resolve(vimState, 'right'); if (left > right) { // Reverse the range to keep start < end // NOTE: Vim generally makes you confirm before doing this, but we do it automatically. return { start: end.resolve(vimState, 'left'), end: this.start.resolve(vimState, 'right'), }; } else { return { start: this.start.resolve(vimState, 'left'), end: end.resolve(vimState, 'right'), }; } } public resolveToRange(vimState: VimState): Range { const { start, end } = this.resolve(vimState); return new Range(new Position(start, 0), new Position(end, 0).getLineEnd()); } public toString(): string { return `${this.start.toString()}${this.separator ?? ''}${this.end?.toString() ?? ''}`; } }
the_stack
import React, {useState, useEffect} from 'react'; import * as d3 from 'd3'; import {componentAtomTree, atom, selector} from '../../../types'; import {useAppSelector, useAppDispatch} from '../../state-management/hooks'; import { updateZoomState, selectZoomState, setDefaultZoom, } from '../../state-management/slices/ZoomSlice'; interface AtomComponentVisualProps { componentAtomTree: componentAtomTree; cleanedComponentAtomTree: componentAtomTree; selectedRecoilValue: string[]; atoms: atom; selectors: selector; setStr: React.Dispatch<React.SetStateAction<string[]>>; setSelectedRecoilValue: React.Dispatch<React.SetStateAction<string[]>>; } const AtomComponentVisual: React.FC<AtomComponentVisualProps> = ({ componentAtomTree, cleanedComponentAtomTree, selectedRecoilValue, atoms, selectors, setStr, setSelectedRecoilValue, }) => { const zoomSelector = useAppSelector(selectZoomState); const {x, y, k} = zoomSelector; const dispatch = useAppDispatch(); // set the heights and width of the tree to be passed into treeMap function let width: number = 0; let height: number = 0; // useState hook to update the toggle of displaying entire tree or cleaned tree const [rawToggle, setRawToggle] = useState<boolean>(false); // useState hook to update whether a suspense component will be shown on the component graph const [hasSuspense, setHasSuspense] = useState<boolean>(false); //declare hooks to render lists of atoms or selectors const [atomList, setAtomList] = useState(Object.keys(atoms)); const [selectorList, setSelectorList] = useState(Object.keys(selectors)); // need to create a hook for toggling const [showAtomMenu, setShowAtomMenu] = useState<boolean>(false); const [showSelectorMenu, setShowSelectorMenu] = useState<boolean>(false); // hook for selected button styles on the legend const [atomButtonClicked, setAtomButtonClicked] = useState<boolean>(false); const [selectorButtonClicked, setSelectorButtonClicked] = useState<boolean>( false, ); const [bothButtonClicked, setBothButtonClicked] = useState<boolean>(false); const [isDropDownItem, setIsDropDownItem] = useState<boolean>(false); useEffect(() => { height = document.querySelector('.Component').clientHeight; width = document.querySelector('.Component').clientWidth; document.getElementById('canvas').innerHTML = ''; // reset hasSuspense to false. This will get updated to true if the red borders are rendered on the component graph. setHasSuspense(false); // creating the main svg container for d3 elements const svgContainer = d3.select('#canvas'); // creating a pseudo-class for reusability const g = svgContainer .append('g') // .attr('transform', `translate(${x}, ${y}), scale(${k})`) .attr('id', 'componentGraph'); let i = 0; let duration: number = 750; let root: any; let path: string; // creating the tree map const treeMap = d3.tree().nodeSize([height, width]); if (!rawToggle) { root = d3.hierarchy( cleanedComponentAtomTree, function (d: componentAtomTree) { return d.children; }, ); } else { root = d3.hierarchy(componentAtomTree, function (d: componentAtomTree) { return d.children; }); } // Node distance from each other root.x0 = 10; root.y0 = width / 2; update(root); // d3 zoom functionality let zoom = d3.zoom().on('zoom', zoomed); svgContainer.call( zoom.transform, // Changes the initial view, (left, top) d3.zoomIdentity.translate(x, y).scale(k), ); // allows the canvas to be zoom-able svgContainer.call( d3 .zoom() .scaleExtent([0.05, 0.9]) // [zoomOut, zoomIn] .on('zoom', zoomed), ); // helper function that allows for zooming function zoomed() { g.attr('transform', d3.event.transform).on( 'mouseup', dispatch( updateZoomState(d3.zoomTransform(d3.select('#canvas').node())), ), ); } // Update function function update(source: any) { treeMap(root); let nodes = root.descendants(), links = root.descendants().slice(1); let node = g .selectAll('g.node') .attr('stroke-width', 5) .data(nodes, function (d: any): number { return d.id || (d.id = ++i); }); /* this tells node where to be placed and go to * adding a mouseOver event handler to each node * display the data in the node on hover * add mouseOut event handler that removes the popup text */ //add div that will hold info regarding atoms and/or selectors for each node const tooltip = d3 .select('.tooltipContainer') .append('div') .attr('class', 'hoverInfo') .style('opacity', 0); let nodeEnter = node .enter() .append('g') .attr('class', 'node') .attr('transform', function (): string { return `translate(${source.y0}, ${source.x0})`; }) .on('click', click) .on('mouseover', function (d: any, i: number): void { // atsel is an array of all the atoms and selectors const atsel: any = []; if (d.data.recoilNodes) { for (let x = 0; x < d.data.recoilNodes.length; x++) { // pushing all the atoms and selectors for the node into 'atsel' atsel.push(d.data.recoilNodes[x]); } // change the opacity of the node when the mouse is over d3.select(this).transition().duration('50').attr('opacity', '.85'); // created a str for hover div to have corrensponding info // let newStr = formatAtomSelectorText(atsel).join('<br>'); // newStr = newStr.replace(/,/g, '<br>'); // newStr = newStr.replace(/{/g, '<br>{'); // to make the info-windows more clear for the user, this iterates over the nodeData and returns a stringified html element that gets rendered by the tooltip const nodeData = formatAtomSelectorText(atsel)[0]; const genHTML = (obj: any): string => { let str = ''; let htmlStr = ''; for (let key in obj) { const curr = obj[key]; if (key === 'type') str += `${curr}: `; if (key === 'name') str += curr; if (key === 'info') { htmlStr += `<h3>${str}</h3>`; htmlStr += `<h5>Atomic Values</h5>`; if (typeof curr === 'string') htmlStr += `<p>title: ${curr}</p>`; else for (let prop in curr) { const title = prop; const data = curr[prop]; htmlStr += `<p>${title}: ${data}</p>`; } } } return `<div>${htmlStr}</div>`; }; // tooltip appear near your mouse when hover over a node tooltip .style('opacity', 1) .html(genHTML(nodeData)) .style('left', d3.event.pageX + 15 + 'px') // mouse position .style('top', d3.event.pageY - 20 + 'px'); } }) .on('mouseout', function (d: any, i: number): void { d3.select(this).transition().duration('50').attr('opacity', '1'); //change the opacity back //remove tooltip when the mouse is not on the node tooltip.style('opacity', 0); }); // determines shape/color/size of node nodeEnter .append('circle') .attr('class', 'node') .attr('r', determineSize) .attr('fill', colorComponents) .style('stroke', borderColor) .style('stroke-width', 15); // TO DO: Add attribute for border if it is a suspense component // for each node that got created, append a text element that displays the name of the node nodeEnter .append('text') .attr('dy', '.31em') .attr('y', (d: any): number => (d.data.recoilNodes ? 138 : -75)) .attr('text-anchor', function (d: any): string { return d.children || d._children ? 'middle' : 'middle'; }) .text((d: any): string => d.data.name) .style('font-size', `7.5rem`) .style('fill', 'white'); let nodeUpdate = nodeEnter.merge(node); // transition that makes it slide down to next spot nodeUpdate // .transition() // .duration(duration) .attr('transform', function (d: any): string { return `translate(${d.y}, ${d.x})`; }); // allows user to see hand pop out when clicking is available and maintains color/size nodeUpdate .select('circle.node') .attr('r', determineSize) .attr('fill', colorComponents) .attr('cursor', 'pointer') .style('stroke', borderColor) .style('stroke-width', 15); let nodeExit = node .exit() .transition() .duration(duration) .attr('transform', function (d: any): string { return `translate(${source.y}, ${source.x})`; }) .remove(); let link = g .attr('fill', 'none') .attr('stroke-width', 5) .selectAll('path.link') .data(links, function (d: any): number { return d.id; }); let linkEnter = link .enter() .insert('path', 'g') .attr('class', 'link') .attr('stroke', '#646464') .attr('stroke-width', 5) .attr('d', function (d: any): string { let o = {x: source.x0, y: source.y0}; return diagonal(o, o); }); let linkUpdate = linkEnter.merge(link); linkUpdate .transition() .duration(duration) .attr('stroke', '#646464') .attr('stroke-width', 5) .attr('d', function (d: any): string { return diagonal(d, d.parent); }); let linkExit = link .exit() .transition() .duration(duration) .attr('stroke', '#646464') .attr('stroke-width', 5) .attr('d', function (d: any): string { let o = {y: source.y, x: source.x}; return diagonal(o, o); }) .remove(); // makes next Node needed to appear from the previous and not the start nodes.forEach(function (d: any): void { d.x0 = d.x; d.y0 = d.y; }); function diagonal(s: any, d: any): string { path = `M ${s.y} ${s.x} C ${(s.y + d.y) / 2} ${s.x}, ${(s.y + d.y) / 2} ${d.x}, ${d.y} ${d.x}`; return path; } function click(d: any): void { if (d.children) { d._children = d.children; d.children = null; } else { d.children = d._children; d._children = null; } update(d); const atsel = []; if (d.data.recoilNodes) { for (let x = 0; x < d.data.recoilNodes.length; x++) { atsel.push(d.data.recoilNodes[x]); } setStr(formatAtomSelectorText(atsel)); } } // allows the canvas to be draggable node.call(d3.drag()); function formatMouseoverXValue(recoilValue: string): number { if (atoms.hasOwnProperty(recoilValue)) { return -30; } return -150; } // creates an array of objects with node data function formatAtomSelectorText(atomOrSelector: string[]): string[] { const recoilData: any = []; for (let i = 0; i < atomOrSelector.length; i++) { const data: any = {}; const curr = atomOrSelector[i]; data.type = atoms.hasOwnProperty(curr) ? 'atom' : 'selector'; data.name = curr; if (data.type === 'atom') { data.info = atoms[curr]; } else { data.info = selectors[curr]; } recoilData.push(data); } return recoilData; } function determineSize(d: any): number { if (d.data.recoilNodes && d.data.recoilNodes.length) { if (d.data.recoilNodes.includes(selectedRecoilValue[0])) { // Size when the atom/selector is clicked on from legend return 150; } // Size of atoms and selectors return 100; } // Size of regular nodes return 50; } function borderColor(d: any): string { if (d.data.wasSuspended) setHasSuspense(true); return d.data.wasSuspended ? '#FF0000' : 'none'; } function colorComponents(d: any): string { // if component node contains recoil atoms or selectors, make it orange red or yellow, otherwise keep node gray if (d.data.recoilNodes && d.data.recoilNodes.length) { if (d.data.recoilNodes.includes(selectedRecoilValue[0])) { // Color of atom or selector when clicked on in legend return 'yellow'; } let hasAtom = false; let hasSelector = false; for (let i = 0; i < d.data.recoilNodes.length; i++) { if (atoms.hasOwnProperty(d.data.recoilNodes[i])) { hasAtom = true; } if (selectors.hasOwnProperty(d.data.recoilNodes[i])) { hasSelector = true; } } if (hasAtom && hasSelector) { return 'springgreen'; } if (hasAtom) { return '#9580ff'; } else { return '#ff80bf'; } } return 'gray'; } } }, [componentAtomTree, rawToggle, selectedRecoilValue]); // setting the component's user interface state by checking if the dropdown menu is open or not function openDropdown(e: React.MouseEvent) { const target = e.target as Element; if (target.id === 'AtomP') { setAtomButtonClicked(true); setSelectorButtonClicked(false); setShowAtomMenu(!showAtomMenu); setShowSelectorMenu(false); } else { setAtomButtonClicked(false); setSelectorButtonClicked(true); setShowSelectorMenu(!showSelectorMenu); setShowAtomMenu(false); } } // resetting the component's user interface state when toggling between atoms & selectors const resetNodes = () => { setIsDropDownItem(false); setSelectedRecoilValue([]); setShowSelectorMenu(false); setShowAtomMenu(false); setAtomButtonClicked(false); setSelectorButtonClicked(false); }; return ( <div className="AtomComponentVisual"> <svg id="canvas"></svg> <button id="fixedButton" style={{ color: rawToggle ? '#E6E6E6' : '#989898', }} onClick={() => { setRawToggle(!rawToggle); dispatch(setDefaultZoom()); }}> <span>{rawToggle ? 'Collapse' : 'Expand'}</span> </button> <div className="AtomNetworkLegend"> <div className="AtomLegend" /> <button onClick={isDropDownItem ? resetNodes : openDropdown} id="AtomP" className={ atomButtonClicked ? 'AtomP atomSelected' : 'AtomP atomLegendDefault' }> ATOM </button> {showAtomMenu && ( <div id="atomDrop" className="AtomDropDown"> {atomList.map((atom, i) => ( <div className="dropDownButtonDiv"> <button id={`atom-drop${i}`} className="atom-class atomDropDown" key={i} onClick={event => { if ( !(event.target as HTMLInputElement).classList.contains( 'atomSelected', ) && (event.target as HTMLInputElement).classList.contains( 'atomNotSelected', ) ) { (event.target as HTMLInputElement).classList.replace( 'atomNotSelected', 'atomSelected', ); } else if ( !(event.target as HTMLInputElement).classList.contains( 'atomSelected', ) && !(event.target as HTMLInputElement).classList.contains( 'atomNotSelected', ) ) { (event.target as HTMLInputElement).classList.add( 'atomSelected', ); } document.querySelectorAll('.atom-class').forEach(item => { if ( item.id !== `atom-drop${i}` && item.classList.contains('atomSelected') ) { item.classList.replace( 'atomSelected', 'atomNotSelected', ); } else if ( item.id !== `atom-drop${i}` && !item.classList.contains('atomNotSelected') ) { item.classList.add('atomNotSelected'); } }); setSelectedRecoilValue([atom, 'atom']); setIsDropDownItem(true); }}> {atom} </button> </div> ))} </div> )} <div className="SelectorLegend"></div> <button onClick={isDropDownItem ? resetNodes : openDropdown} id="SelectorP" className={ selectorButtonClicked ? 'SelectorP selectorSelected' : 'SelectorP selectorLegendDefault' }> SELECTOR </button> {showSelectorMenu && ( <div id="selectorDrop" className="SelectorDropDown"> {selectorList.map((selector, i) => ( <div className="dropDownButtonDiv"> <button id={`selector-drop${i}`} className="selector-class selectorDropDown" key={i} onClick={event => { if ( !(event.target as HTMLInputElement).classList.contains( 'selectorSelected', ) && (event.target as HTMLInputElement).classList.contains( 'selectorNotSelected', ) ) { (event.target as HTMLInputElement).classList.replace( 'selectorNotSelected', 'selectorSelected', ); } else if ( !(event.target as HTMLInputElement).classList.contains( 'selectorSelected', ) && !(event.target as HTMLInputElement).classList.contains( 'selectorNotSelected', ) ) { (event.target as HTMLInputElement).classList.add( 'selectorSelected', ); } document .querySelectorAll('.selector-class') .forEach(item => { if ( item.id !== `selector-drop${i}` && item.classList.contains('selectorSelected') ) { item.classList.replace( 'selectorSelected', 'selectorNotSelected', ); } else if ( item.id !== `selector-drop${i}` && !item.classList.contains('selectorNotSelected') ) { item.classList.add('selectorNotSelected'); } }); setSelectedRecoilValue([selector, 'selector']); setIsDropDownItem(true); }}> {selector} </button> </div> ))} </div> )} <div className="bothLegend"></div> <button className="bothLegendDefault">BOTH</button> <div className={hasSuspense ? 'suspenseLegend' : ''}></div> <p>{hasSuspense ? 'SUSPENSE' : ''}</p> <div className="tooltipContainer"></div> </div> </div> ); }; export default AtomComponentVisual;
the_stack
declare module 'vsts-task-lib/taskcommand' { export class TaskCommand { constructor(command: any, properties: any, message: any); command: string; message: string; properties: { [key: string]: string; }; toString(): string; } export function commandFromString(commandLine: any): TaskCommand; } declare module 'vsts-task-lib/toolrunner' { import Q = require('q'); import events = require('events'); import stream = require('stream'); /** * Interface for exec options * * @param cwd optional working directory. defaults to current * @param env optional envvar dictionary. defaults to current processes env * @param silent optional. defaults to false * @param failOnStdErr optional. whether to fail if output to stderr. defaults to false * @param ignoreReturnCode optional. defaults to failing on non zero. ignore will not fail leaving it up to the caller */ export interface IExecOptions { cwd?: string; env?: { [key: string]: string; }; silent?: boolean; failOnStdErr?: boolean; ignoreReturnCode?: boolean; outStream?: stream.Writable; errStream?: stream.Writable; } /** * Interface for exec results returned from synchronous exec functions * * @param stdout standard output * @param stderr error output * @param code return code * @param error Error on failure */ export interface IExecResult { stdout: string; stderr: string; code: number; error: Error; } export function debug(message: any): void; export class ToolRunner extends events.EventEmitter { constructor(toolPath: any); toolPath: string; args: string[]; silent: boolean; private _debug(message); private _argStringToArray(argString); /** * Add argument * Append an argument or an array of arguments * * @param val string cmdline or array of strings * @returns void */ arg(val: string | string[]): void; /** * Append argument command line string * e.g. '"arg one" two -z' would append args[]=['arg one', 'two', '-z'] * * @param val string cmdline * @returns void */ argString(val: string): void; /** * Add path argument * Add path string to argument, path string should not contain double quoted * This will call arg(val, literal?) with literal equal 'true' * * @param val path argument string * @returns void */ pathArg(val: string): void; /** * Add argument(s) if a condition is met * Wraps arg(). See arg for details * * @param condition boolean condition * @param val string cmdline or array of strings * @returns void */ argIf(condition: any, val: any): void; /** * Exec a tool. * Output will be streamed to the live console. * Returns promise with return code * * @param tool path to tool to exec * @param options optional exec options. See IExecOptions * @returns number */ exec(options?: IExecOptions): Q.Promise<number>; /** * Exec a tool synchronously. * Output will be *not* be streamed to the live console. It will be returned after execution is complete. * Appropriate for short running tools * Returns IExecResult with output and return code * * @param tool path to tool to exec * @param options optionalexec options. See IExecOptions * @returns IExecResult */ execSync(options?: IExecOptions): IExecResult; } } declare module 'vsts-task-lib/vault' { export class Vault { constructor(); private _keyFile; private _store; initialize(): void; storeSecret(name: string, data: string): boolean; retrieveSecret(name: string): string; private getKey(); private genKey(); } } declare module 'vsts-task-lib/task' { /// <reference path="../typings/main.d.ts" /> import Q = require('q'); import fs = require('fs'); import trm = require('vsts-task-lib/toolrunner'); export enum TaskResult { Succeeded = 0, Failed = 1, } export var _outStream: any; export var _errStream: any; export function _writeError(str: string): void; export function _writeLine(str: string): void; export function setStdStream(stdStream: any): void; export function setErrStream(errStream: any): void; /** * Sets the result of the task. * If the result is Failed (1), then execution will halt. * * @param result TaskResult enum of Success or Failed. If the result is Failed (1), then execution will halt. * @param messages A message which will be logged and added as an issue if an failed * @returns void */ export function setResult(result: TaskResult, message: string): void; export function handlerError(errMsg: string, continueOnError: boolean): void; export function exitOnCodeIf(code: number, condition: boolean): void; export function exit(code: number): void; /** * Sets the location of the resources json. This is typically the task.json file. * Call once at the beginning of the script before any calls to loc. * * @param path Full path to the json. * @returns void */ export function setResourcePath(path: string): void; /** * Gets the localized string from the json resource file. Optionally formats with additional params. * * @param key key of the resources string in the resource file * @param param additional params for formatting the string * @returns string */ export function loc(key: string, ...param: any[]): string; /** * Gets a variables value which is defined on the build definition or set at runtime. * * @param name name of the variable to get * @returns string */ export function getVariable(name: string): string; /** * Sets a variables which will be available to subsequent tasks as well. * * @param name name of the variable to set * @param val value to set * @returns void */ export function setVariable(name: string, val: string): void; /** * Gets the value of an input. The value is also trimmed. * If required is true and the value is not set, the task will fail with an error. Execution halts. * * @param name name of the input to get * @param required whether input is required. optional, defaults to false * @returns string */ export function getInput(name: string, required?: boolean): string; /** * Gets the value of an input and converts to a bool. Convenience. * If required is true and the value is not set, the task will fail with an error. Execution halts. * * @param name name of the bool input to get * @param required whether input is required. optional, defaults to false * @returns string */ export function getBoolInput(name: string, required?: boolean): boolean; export function setEnvVar(name: string, val: string): void; /** * Gets the value of an input and splits the values by a delimiter (space, comma, etc...) * Useful for splitting an input with simple list of items like targets * IMPORTANT: Do not use for splitting additional args! Instead use arg() - it will split and handle * If required is true and the value is not set, the task will fail with an error. Execution halts. * * @param name name of the input to get * @param delim delimiter to split on * @param required whether input is required. optional, defaults to false * @returns string[] */ export function getDelimitedInput(name: string, delim: string, required?: boolean): string[]; /** * Checks whether a path inputs value was supplied by the user * File paths are relative with a picker, so an empty path is the root of the repo. * Useful if you need to condition work (like append an arg) if a value was supplied * * @param name name of the path input to check * @returns boolean */ export function filePathSupplied(name: string): boolean; /** * Gets the value of a path input * It will be quoted for you if it isn't already and contains spaces * If required is true and the value is not set, the task will fail with an error. Execution halts. * If check is true and the path does not exist, the task will fail with an error. Execution halts. * * @param name name of the input to get * @param required whether input is required. optional, defaults to false * @param check whether path is checked. optional, defaults to false * @returns string */ export function getPathInput(name: string, required?: boolean, check?: boolean): string; /** * Gets the url for a service endpoint * If the url was not set and is not optional, the task will fail with an error message. Execution will halt. * * @param id name of the service endpoint * @param optional whether the url is optional * @returns string */ export function getEndpointUrl(id: string, optional: boolean): string; export function getEndpointDataParameter(id: string, key: string, optional: boolean): string; /** * Gets the endpoint authorization scheme for a service endpoint * If the endpoint authorization scheme is not set and is not optional, the task will fail with an error message. Execution will halt. * * @param id name of the service endpoint * @param optional whether the endpoint authorization scheme is optional * @returns {string} value of the endpoint authorization scheme */ export function getEndpointAuthorizationScheme(id: string, optional: boolean): string; /** * Gets the endpoint authorization parameter value for a service endpoint with specified key * If the endpoint authorization parameter is not set and is not optional, the task will fail with an error message. Execution will halt. * * @param id name of the service endpoint * @param key key to find the endpoint authorization parameter * @param optional optional whether the endpoint authorization scheme is optional * @returns {string} value of the endpoint authorization parameter value */ export function getEndpointAuthorizationParameter(id: string, key: string, optional: boolean): string; /** * Interface for EndpointAuthorization * Contains a schema and a string/string dictionary of auth data * * @param parameters string string dictionary of auth data * @param scheme auth scheme such as OAuth or username/password etc... */ export interface EndpointAuthorization { parameters: { [key: string]: string; }; scheme: string; } /** * Gets the authorization details for a service endpoint * If the authorization was not set and is not optional, the task will fail with an error message. Execution will halt. * * @param id name of the service endpoint * @param optional whether the url is optional * @returns string */ export function getEndpointAuthorization(id: string, optional: boolean): EndpointAuthorization; /* * Gets the endpoint data parameter value with specified key for a service endpoint * If the endpoint data parameter was not set and is not optional, the task will fail with an error message. Execution will halt. * * @param id name of the service endpoint * @param key of the parameter * @param optional whether the endpoint data is optional * @returns {string} value of the endpoint data parameter */ export function getEndpointDataParameter(id: string, key: string, optional: boolean): string; /** * Gets the endpoint authorization scheme for a service endpoint * If the endpoint authorization scheme is not set and is not optional, the task will fail with an error message. Execution will halt. * * @param id name of the service endpoint * @param optional whether the endpoint authorization scheme is optional * @returns {string} value of the endpoint authorization scheme */ export function getEndpointAuthorizationScheme(id: string, optional: boolean): string; /** * Gets the endpoint authorization parameter value for a service endpoint with specified key * If the endpoint authorization parameter is not set and is not optional, the task will fail with an error message. Execution will halt. * * @param id name of the service endpoint * @param key key to find the endpoint authorization parameter * @param optional optional whether the endpoint authorization scheme is optional * @returns {string} value of the endpoint authorization parameter value */ export function getEndpointAuthorizationParameter(id: string, key: string, optional: boolean): string; export function command(command: string, properties: any, message: string): void; export function warning(message: string): void; export function error(message: string): void; export function debug(message: string): void; export interface FsStats extends fs.Stats { } /** * Get's stat on a path. * Useful for checking whether a file or directory. Also getting created, modified and accessed time. * see [fs.stat](https://nodejs.org/api/fs.html#fs_class_fs_stats) * * @param path path to check * @returns fsStat */ export function stats(path: string): FsStats; /** * Returns whether a path exists. * * @param path path to check * @returns boolean */ export function exist(path: string): boolean; /** * Interface to wrap file options */ export interface FsOptions {} /** * Synchronously writes data to a file, replacing the file if it already exists. * @param file * @param data * @param options */ export function writeFile(file: string, data:string|Buffer, options?:string|FsOptions); /** * Useful for determining the host operating system. * see [os.type](https://nodejs.org/api/os.html#os_os_type) * * @return the name of the operating system */ export function osType(): string; /** * Returns the process's current working directory. * see [process.cwd](https://nodejs.org/api/process.html#process_process_cwd) * * @return the path to the current working directory of the process */ export function cwd(): string; /** * Checks whether a path exists. * If the path does not exist, the task will fail with an error message. Execution will halt. * * @param p path to check * @param name name only used in error message to identify the path * @returns void */ export function checkPath(p: string, name: string): void; /** * Change working directory. * * @param path new working directory path * @returns void */ export function cd(path: string): void; /** * Change working directory and push it on the stack * * @param path new working directory path * @returns void */ export function pushd(path: string): void; /** * Change working directory back to previously pushed directory * * @returns void */ export function popd(): void; /** * Resolves a sequence of paths or path segments into an absolute path. * Calls node.js path.resolve() * Allows L0 testing with consistent path formats on Mac/Linux and Windows in the mock implementation * @param pathSegments * @returns {string} */ export function resolve(...pathSegments: any[]): string; /** * Make a directory. Creates the full path with folders in between * Returns whether it was successful or not * * @param p path to create * @returns boolean */ export function mkdirP(p: any): boolean; /** * Returns path of a tool had the tool actually been invoked. Resolves via paths. * If you check and the tool does not exist, the task will fail with an error message and halt execution. * * @param tool name of the tool * @param check whether to check if tool exists * @returns string */ export function which(tool: string, check?: boolean): string; /** * Returns array of files in the given path, or in current directory if no path provided. See shelljs.ls * @param {string} options Available options: -R (recursive), -A (all files, include files beginning with ., except for . and ..) * @param {string[]} paths Paths to search. * @return {string[]} An array of files in the given path(s). */ export function ls(options: string, paths: string[]): string[]; /** * Returns path of a tool had the tool actually been invoked. Resolves via paths. * If you check and the tool does not exist, the task will fail with an error message and halt execution. * Returns whether the copy was successful * * @param options string -r, -f or -rf for recursive and force * @param source source path * @param dest destination path * @param continueOnError optional. whether to continue on error * @returns boolean */ export function cp(options: any, source: string, dest: string, continueOnError?: boolean): boolean; /** * Moves a path. * Returns whether the copy was successful * * @param source source path * @param dest destination path * @param force whether to force and overwrite * @param continueOnError optional. whether to continue on error * @returns boolean */ export function mv(source: string, dest: string, force: boolean, continueOnError?: boolean): boolean; /** * Find all files under a give path * Returns an array of full paths * * @param findPath path to find files under * @returns string[] */ export function find(findPath: string): string[]; /** * Remove a path recursively with force * Returns whether it succeeds * * @param path path to remove * @param continueOnError optional. whether to continue on error * @returns string[] */ export function rmRF(path: string, continueOnError?: boolean): boolean; export function glob(pattern: string): string[]; export function globFirst(pattern: string): string; /** * Exec a tool. Convenience wrapper over ToolRunner to exec with args in one call. * Output will be streamed to the live console. * Returns promise with return code * * @param tool path to tool to exec * @param args an arg string or array of args * @param options optional exec options. See IExecOptions * @returns number */ export function exec(tool: string, args: any, options?: trm.IExecOptions): Q.Promise<number>; /** * Exec a tool synchronously. Convenience wrapper over ToolRunner to execSync with args in one call. * Output will be *not* be streamed to the live console. It will be returned after execution is complete. * Appropriate for short running tools * Returns IExecResult with output and return code * * @param tool path to tool to exec * @param args an arg string or array of args * @param options optionalexec options. See IExecOptions * @returns IExecResult */ export function execSync(tool: string, args: string | string[], options?: trm.IExecOptions): trm.IExecResult; /** * Convenience factory to create a ToolRunner. * * @param tool path to tool to exec * @returns ToolRunner */ export function createToolRunner(tool: string): trm.ToolRunner; /** * Convenience factory to create a ToolRunner. * * @param tool path to tool to exec * @returns ToolRunner */ export function tool(tool: string) : trm.ToolRunner; export function match(list: any, pattern: any, options: any): string[]; export function filter(pattern: any, options: any): (element: string, indexed: number, array: string[]) => boolean; export class TestPublisher { constructor(testRunner: any); testRunner: string; publish(resultFiles: any, mergeResults: any, platform: any, config: any, runTitle: any, publishRunAttachments: any): void; } export class CodeCoveragePublisher { constructor(); publish(codeCoverageTool: any, summaryFileLocation: any, reportDirectory: any, additionalCodeCoverageFiles: any): void; } export class CodeCoverageEnabler { private buildTool; private ccTool; constructor(buildTool: string, ccTool: string); enableCodeCoverage(buildProps: { [key: string]: string; }): void; } export function _loadData(): void; }
the_stack
import React, { useState, useEffect } from 'react' // eslint-disable-line import { ContractSelectionProps } from './types' import { PublishToStorage } from '@remix-ui/publish-to-storage' // eslint-disable-line import { TreeView, TreeViewItem } from '@remix-ui/tree-view' // eslint-disable-line import { CopyToClipboard } from '@remix-ui/clipboard' // eslint-disable-line import './css/style.css' export const ContractSelection = (props: ContractSelectionProps) => { const { contractMap, fileProvider, fileManager, contractsDetails, modal } = props const [contractList, setContractList] = useState([]) const [selectedContract, setSelectedContract] = useState('') const [storage, setStorage] = useState(null) useEffect(() => { const contractList = contractMap ? Object.keys(contractMap).map((key) => ({ name: key, file: getFileName(contractMap[key].file) })) : [] setContractList(contractList) if (contractList.length) setSelectedContract(contractList[0].name) }, [contractMap, contractsDetails]) const resetStorage = () => { setStorage('') } // Return the file name of a path: ex "browser/ballot.sol" -> "ballot.sol" const getFileName = (path) => { const part = path.split('/') return part[part.length - 1] } const handleContractChange = (contractName: string) => { setSelectedContract(contractName) } const handlePublishToStorage = (type) => { setStorage(type) } const copyABI = () => { return copyContractProperty('abi') } const copyContractProperty = (property) => { let content = getContractProperty(property) if (!content) { return } try { if (typeof content !== 'string') { content = JSON.stringify(content, null, '\t') } } catch (e) {} return content } const getContractProperty = (property) => { if (!selectedContract) throw new Error('No contract compiled yet') const contractProperties = contractsDetails[selectedContract] if (contractProperties && contractProperties[property]) return contractProperties[property] return null } const renderData = (item, key: string | number, keyPath: string) => { const data = extractData(item) const children = (data.children || []).map((child) => renderData(child.value, child.key, keyPath + '/' + child.key)) if (children && children.length > 0) { return ( <TreeViewItem id={`treeViewItem${key}`} key={keyPath} label={ <div className="d-flex mt-2 flex-row remixui_label_item"> <label className="small font-weight-bold pr-1 remixui_label_key">{ key }:</label> <label className="m-0 remixui_label_value">{ typeof data.self === 'boolean' ? `${data.self}` : data.self }</label> </div> }> <TreeView id={`treeView${key}`} key={keyPath}> {children} </TreeView> </TreeViewItem> ) } else { return <TreeViewItem id={key.toString()} key={keyPath} label={ <div className="d-flex mt-2 flex-row remixui_label_item"> <label className="small font-weight-bold pr-1 remixui_label_key">{ key }:</label> <label className="m-0 remixui_label_value">{ typeof data.self === 'boolean' ? `${data.self}` : data.self }</label> </div> } /> } } const extractData = (item) => { const ret = { children: null, self: null } if (item instanceof Array) { ret.children = item.map((item, index) => ({ key: index, value: item })) ret.self = '' } else if (item instanceof Object) { ret.children = Object.keys(item).map((key) => ({ key: key, value: item[key] })) ret.self = '' } else { ret.self = item ret.children = [] } return ret } const insertValue = (details, propertyName) => { let node if (propertyName === 'web3Deploy' || propertyName === 'name' || propertyName === 'Assembly') { node = <pre>{ details[propertyName] }</pre> } else if (propertyName === 'abi' || propertyName === 'metadata') { if (details[propertyName] !== '') { try { node = <div> { (typeof details[propertyName] === 'object') ? <TreeView id="treeView"> { Object.keys(details[propertyName]).map((innerkey) => renderData(details[propertyName][innerkey], innerkey, innerkey)) } </TreeView> : <TreeView id="treeView"> { Object.keys(JSON.parse(details[propertyName])).map((innerkey) => renderData(JSON.parse(details[propertyName])[innerkey], innerkey, innerkey)) } </TreeView> } </div> // catch in case the parsing fails. } catch (e) { node = <div>Unable to display "${propertyName}": ${e.message}</div> } } else { node = <div> - </div> } } else { node = <div>{JSON.stringify(details[propertyName], null, 4)}</div> } return <pre className="remixui_value">{node || ''}</pre> } const details = () => { if (!selectedContract) throw new Error('No contract compiled yet') const help = { Assembly: 'Assembly opcodes describing the contract including corresponding solidity source code', Opcodes: 'Assembly opcodes describing the contract', 'Runtime Bytecode': 'Bytecode storing the state and being executed during normal contract call', bytecode: 'Bytecode being executed during contract creation', functionHashes: 'List of declared function and their corresponding hash', gasEstimates: 'Gas estimation for each function call', metadata: 'Contains all informations related to the compilation', metadataHash: 'Hash representing all metadata information', abi: 'ABI: describing all the functions (input/output params, scope, ...)', name: 'Name of the compiled contract', swarmLocation: 'Swarm url where all metadata information can be found (contract needs to be published first)', web3Deploy: 'Copy/paste this code to any JavaScript/Web3 console to deploy this contract' } const contractProperties = contractsDetails[selectedContract] || {} const log = <div className="remixui_detailsJSON"> { Object.keys(contractProperties).map((propertyName, index) => { const copyDetails = <span className="remixui_copyDetails"><CopyToClipboard content={contractProperties[propertyName]} direction='top' /></span> const questionMark = <span className="remixui_questionMark"><i title={ help[propertyName] } className="fas fa-question-circle" aria-hidden="true"></i></span> return (<div className="remixui_log" key={index}> <div className="remixui_key">{ propertyName } { copyDetails } { questionMark }</div> { insertValue(contractProperties, propertyName) } </div>) }) } </div> modal(selectedContract, log, 'Close', null) } const copyBytecode = () => { return copyContractProperty('bytecode') } return ( // define swarm logo <> { contractList.length ? <section className="remixui_compilerSection pt-3"> {/* Select Compiler Version */} <div className="mb-3"> <label className="remixui_compilerLabel form-check-label" htmlFor="compiledContracts">Contract</label> <select onChange={(e) => handleContractChange(e.target.value)} value={selectedContract} data-id="compiledContracts" id="compiledContracts" className="custom-select"> { contractList.map(({ name, file }, index) => <option value={name} key={index}>{name} ({file})</option>)} </select> </div> <article className="mt-2 pb-0"> <button id="publishOnSwarm" className="btn btn-secondary btn-block" title="Publish on Swarm" onClick={() => { handlePublishToStorage('swarm') }}> <span>Publish on Swarm</span> <img id="swarmLogo" className="remixui_storageLogo ml-2" src="assets/img/swarm.webp" /> </button> <button id="publishOnIpfs" className="btn btn-secondary btn-block" title="Publish on Ipfs" onClick={() => { handlePublishToStorage('ipfs') }}> <span>Publish on Ipfs</span> <img id="ipfsLogo" className="remixui_storageLogo ml-2" src="assets/img/ipfs.webp" /> </button> <button data-id="compilation-details" className="btn btn-secondary btn-block" title="Display Contract Details" onClick={() => { details() }}> Compilation Details </button> {/* Copy to Clipboard */} <div className="remixui_contractHelperButtons"> <div className="input-group"> <div className="btn-group" role="group" aria-label="Copy to Clipboard"> <CopyToClipboard title="Copy ABI to clipboard" content={copyABI()} direction='top'> <button className="btn remixui_copyButton" title="Copy ABI to clipboard"> <i className="remixui_copyIcon far fa-copy" aria-hidden="true"></i> <span>ABI</span> </button> </CopyToClipboard> <CopyToClipboard title="Copy ABI to clipboard" content={copyBytecode()} direction='top'> <button className="btn remixui_copyButton" title="Copy Bytecode to clipboard"> <i className="remixui_copyIcon far fa-copy" aria-hidden="true"></i> <span>Bytecode</span> </button> </CopyToClipboard> </div> </div> </div> </article> </section> : <section className="remixui_container clearfix"><article className="px-2 mt-2 pb-0 d-flex w-100"> <span className="mt-2 mx-3 w-100 alert alert-warning" role="alert">No Contract Compiled Yet</span> </article></section> } <PublishToStorage storage={storage} fileManager={fileManager} fileProvider={fileProvider} contract={contractsDetails[selectedContract]} resetStorage={resetStorage} /> </> ) } export default ContractSelection
the_stack
declare module CANNON { export interface IAABBOptions { upperBound?: Vec3; lowerBound?: Vec3; } export class AABB { lowerBound: Vec3; upperBound: Vec3; constructor(options?: IAABBOptions); clone(): AABB; copy(aabb: AABB): void; extend(aabb: AABB): void; getCorners(a: Vec3, b: Vec3, c: Vec3, d: Vec3, e: Vec3, f: Vec3, g: Vec3, h: Vec3): void; overlaps(aabb: AABB): boolean; setFromPoints(points: Vec3[], position?: Vec3, quaternion?: Quaternion, skinSize?: number): AABB; toLocalFrame(frame: Transform, target: AABB): AABB; toWorldFrame(frame: Transform, target: AABB): AABB; } export class ArrayCollisionMatrix { matrix: Mat3[]; get(i: number, j: number): number; set(i: number, j: number, value: number): void; reset(): void; setNumObjects(n: number): void; } export class BroadPhase { world: World; useBoundingBoxes: boolean; dirty: boolean; collisionPairs(world: World, p1: Body[], p2: Body[]): void; needBroadphaseCollision(bodyA: Body, bodyB: Body): boolean; intersectionTest(bodyA: Body, bodyB: Body, pairs1: Body[], pairs2: Body[]): void; doBoundingSphereBroadphase(bodyA: Body, bodyB: Body, pairs1: Body[], pairs2: Body[]): void; doBoundingBoxBroadphase(bodyA: Body, bodyB: Body, pairs1: Body[], pairs2: Body[]): void; makePairsUnique(pairs1: Body[], pairs2: Body[]): void; setWorld(world: World): void; boundingSphereCheck(bodyA: Body, bodyB: Body): boolean; aabbQuery(world: World, aabb: AABB, result: Body[]): Body[]; } export class GridBroadphase extends BroadPhase { nx: number; ny: number; nz: number; aabbMin: Vec3; aabbMax: Vec3; bins: any[]; constructor(aabbMin?: Vec3, aabbMax?: Vec3, nx?: number, ny?: number, nz?: number); } export class NaiveBroadphase extends BroadPhase { } export class ObjectCollisionMatrix { matrix: number[]; get(i: number, j: number): number; set(i: number, j: number, value: number): void; reset(): void; setNumObjects(n: number): void; } export class Ray { from: Vec3; to: Vec3; precision: number; checkCollisionResponse: boolean; constructor(from?: Vec3, to?: Vec3); getAABB(result: RaycastResult): void; } export class RaycastResult { rayFromWorld: Vec3; rayToWorld: Vec3; hitNormalWorld: Vec3; hitPointWorld: Vec3; hasHit: boolean; shape: Shape; body: Body; distance: number; reset(): void; set(rayFromWorld: Vec3, rayToWorld: Vec3, hitNormalWorld: Vec3, hitPointWorld: Vec3, shape: Shape, body: Body, distance: number): void; } export class SAPBroadphase extends BroadPhase { static insertionSortX(a: any[]): any[]; static insertionSortY(a: any[]): any[]; static insertionSortZ(a: any[]): any[]; static checkBounds(bi: Body, bj: Body, axisIndex?: number): boolean; axisList: any[]; world: World; axisIndex: number; constructor(world?: World); autoDetectAxis(): void; aabbQuery(world: World, aabb: AABB, result?: Body[]): Body[]; } export interface IConstraintOptions { collideConnected?: boolean; wakeUpBodies?: boolean; } export class Constraint { equations: any[]; bodyA: Body; bodyB: Body; id: number; collideConnected: boolean; constructor(bodyA: Body, bodyB: Body, options?: IConstraintOptions); update(): void; disable(): void; enable(): void; } export class DistanceConstraint extends Constraint { constructor(bodyA: Body, bodyB: Body, distance: number, maxForce?: number); } export interface IHingeConstraintOptions { pivotA?: Vec3; axisA?: Vec3; pivotB?: Vec3; axisB?: Vec3; maxForce?: number; } export class HingeConstraint extends Constraint { motorEnabled: boolean; motorTargetVelocity: number; motorMinForce: number; motorMaxForce: number; motorEquation: RotationalMotorEquation; constructor(bodyA: Body, bodyB: Body, options?: IHingeConstraintOptions); enableMotor(): void; disableMotor(): void; } export class PointToPointConstraint extends Constraint { constructor(bodyA: Body, pivotA: Vec3, bodyB: Body, pivotB: Vec3, maxForce?: number); } export interface ILockConstraintOptions { maxForce?: number; } export class LockConstraint extends Constraint { constructor(bodyA: Body, bodyB: Body, options?: ILockConstraintOptions); } export interface IConeTwistConstraintOptions { pivotA?: Vec3; pivotB?: Vec3; axisA?: Vec3; axisB?: Vec3; maxForce?: number; } export class ConeTwistConstraint extends Constraint { constructor(bodyA: Body, bodyB: Body, options?: IConeTwistConstraintOptions); } export class Equation { id: number; minForce: number; maxForce: number; bi: Body; bj: Body; a: number; b: number; eps: number; jacobianElementA: JacobianElement; jacobianElementB: JacobianElement; enabled: boolean; constructor(bi: Body, bj: Body, minForce?: number, maxForce?: number); setSpookParams(stiffness: number, relaxation: number, timeStep: number): void; computeB(a: number, b: number, h: number): number; computeGq(): number; computeGW(): number; computeGWlamda(): number; computeGiMf(): number; computeGiMGt(): number; addToWlamda(deltalambda: number): number; computeC(): number; } export class FrictionEquation extends Equation { constructor(bi: Body, bj: Body, slipForce: number); } export class RotationalEquation extends Equation { ni: Vec3; nj: Vec3; nixnj: Vec3; njxni: Vec3; invIi: Mat3; invIj: Mat3; relVel: Vec3; relForce: Vec3; constructor(bodyA: Body, bodyB: Body); } export class RotationalMotorEquation extends Equation { axisA: Vec3; axisB: Vec3; invLi: Mat3; invIj: Mat3; targetVelocity: number; constructor(bodyA: Body, bodyB: Body, maxForce?: number); } export class ContactEquation extends Equation { restitution: number; ri: Vec3; rj: Vec3; penetrationVec: Vec3; ni: Vec3; rixn: Vec3; rjxn: Vec3; invIi: Mat3; invIj: Mat3; biInvInertiaTimesRixn: Vec3; bjInvInertiaTimesRjxn: Vec3; constructor(bi: Body, bj: Body); } export interface IContactMaterialOptions { friction?: number; restitution?: number; contactEquationStiffness?: number; contactEquationRelaxation?: number; frictionEquationStiffness?: number; frictionEquationRelaxation?: number; } export class ContactMaterial { id: number; materials: Material[]; friction: number; restitution: number; contactEquationStiffness: number; contactEquationRelaxation: number; frictionEquationStiffness: number; frictionEquationRelaxation: number; constructor(m1: Material, m2: Material, options?: IContactMaterialOptions); } export class Material { name: string; id: number; friction:number; restitution:number; constructor(name: string); } export class JacobianElement { spatial: Vec3; rotational: Vec3; multiplyElement(element: JacobianElement): number; multiplyVectors(spacial: Vec3, rotational: Vec3): number; } export class Mat3 { constructor(elements?: number[]); identity(): void; setZero(): void; setTrace(vec3: Vec3): void; getTrace(target: Vec3): void; vmult(v: Vec3, target?: Vec3): Vec3; smult(s: number): void; mmult(m: Mat3): Mat3; scale(v: Vec3, target?: Mat3): Mat3; solve(b: Vec3, target?: Vec3): Vec3; e(row: number, column: number, value?: number): number; copy(source: Mat3): Mat3; toString(): string; reverse(target?: Mat3): Mat3; setRotationFromQuaternion(q: Quaternion): Mat3; transpose(target?: Mat3): Mat3; } export class Quaternion { x: number; y: number; z: number; w: number; constructor(x?: number, y?: number, z?: number, w?: number); set(x: number, y: number, z: number, w: number): void; toString(): string; toArray(): number[]; setFromAxisAngle(axis: Vec3, angle: number): void; toAxisAngle(targetAxis?: Vec3): any[]; setFromVectors(u: Vec3, v: Vec3): void; mult(q: Quaternion, target?: Quaternion): Quaternion; inverse(target?: Quaternion): Quaternion; conjugate(target?: Quaternion): Quaternion; normalize(): void; normalizeFast(): void; vmult(v: Vec3, target?: Vec3): Vec3; copy(source: Quaternion): Quaternion; toEuler(target: Vec3, order?: string): void; setFromEuler(x: number, y: number, z: number, order?: string): Quaternion; clone(): Quaternion; } export class Transform { static pointToLocalFrame(position: Vec3, quaternion: Quaternion, worldPoint: Vec3, result?: Vec3): Vec3; static pointToWorldFrame(position: Vec3, quaternion: Quaternion, localPoint: Vec3, result?: Vec3): Vec3; position: Vec3; quaternion: Quaternion; vectorToWorldFrame(localVector: Vec3, result?: Vec3): Vec3; vectorToLocalFrame(position: Vec3, quaternion: Quaternion, worldVector: Vec3, result?: Vec3): Vec3; } export class Vec3 { static ZERO: Vec3; x: number; y: number; z: number; constructor(x?: number, y?: number, z?: number); cross(v: Vec3, target?: Vec3): Vec3; set(x: number, y: number, z: number): Vec3; setZero(): void; vadd(v: Vec3, target?: Vec3): Vec3; vsub(v: Vec3, target?: Vec3): Vec3; crossmat(): Mat3; normalize(): number; unit(target?: Vec3): Vec3; norm(): number; norm2(): number; distanceTo(p: Vec3): number; mult(scalar: number, target?: Vec3): Vec3; scale(scalar: number, target?: Vec3): Vec3; dot(v: Vec3): number; isZero(): boolean; negate(target?: Vec3): Vec3; tangents(t1: Vec3, t2: Vec3): void; toString(): string; toArray(): number[]; copy(source: Vec3): Vec3; lerp(v: Vec3, t: number, target?: Vec3): void; almostEquals(v: Vec3, precision?: number): boolean; almostZero(precision?: number): boolean; isAntiparallelTo(v: Vec3, prescision?: number): boolean; clone(): Vec3; } export interface IBodyOptions { position?: Vec3; velocity?: Vec3; angularVelocity?: Vec3; quaternion?: Quaternion; mass?: number; material?: Material; type?: number; linearDamping?: number; angularDamping?: number; allowSleep?: boolean; sleepSpeedLimit?: number; sleepTimeLimit?: number; collisionFilterGroup?: number; collisionFilterMask?: number; fixedRotation?: boolean; shape?: Shape; } export class Body extends EventTarget { static DYNAMIC: number; static STATIC: number; static KINEMATIC: number; static AWAKE: number; static SLEEPY: number; static SLEEPING: number; static sleepyEvent: IEvent; static sleepEvent: IEvent; id: number; world: World; preStep: Function; postStep: Function; vlambda: Vec3; collisionFilterGroup: number; collisionFilterMask: number; collisionResponse: boolean; position: Vec3; previousPosition: Vec3; initPosition: Vec3; velocity: Vec3; initVelocity: Vec3; force: Vec3; mass: number; invMass: number; material: Material; linearDamping: number; type: number; allowSleep: boolean; sleepState: number; sleepSpeedLimit: number; sleepTimeLimit: number; timeLastSleepy: number; torque: Vec3; quaternion: Quaternion; initQuaternion: Quaternion; angularVelocity: Vec3; initAngularVelocity: Vec3; interpolatedPosition: Vec3; interpolatedQuaternion: Quaternion; shapes: Shape[]; shapeOffsets: any[]; shapeOrientations: any[]; inertia: Vec3; invInertia: Vec3; invInertiaWorld: Mat3; invMassSolve: number; invInertiaSolve: Vec3; invInteriaWorldSolve: Mat3; fixedRotation: boolean; angularDamping: number; aabb: AABB; aabbNeedsUpdate: boolean; wlambda: Vec3; constructor(options?: IBodyOptions); wakeUp(): void; sleep(): void; sleepTick(time: number): void; updateSolveMassProperties(): void; pointToLocalFrame(worldPoint: Vec3, result?: Vec3): Vec3; pointToWorldFrame(localPoint: Vec3, result?: Vec3): Vec3; vectorToWorldFrame(localVector: Vec3, result?: Vec3): Vec3; addShape(shape: Shape, offset?: Vec3, orientation?: Quaternion): void; updateBoundingRadius(): void; computeAABB(): void; updateInertiaWorld(force: Vec3): void; applyForce(force: Vec3, worldPoint: Vec3): void; applyImpulse(impulse: Vec3, worldPoint: Vec3): void; applyLocalForce(force: Vec3, localPoint: Vec3): void; applyLocalImpulse(impulse: Vec3, localPoint: Vec3): void; updateMassProperties(): void; getVelocityAtWorldPoint(worldPoint: Vec3, result: Vec3): Vec3; } export interface IRaycastVehicleOptions { chassisBody?: Body; indexRightAxis?: number; indexLeftAxis?: number; indexUpAxis?: number; } export interface IWheelInfoOptions { chassisConnectionPointLocal?: Vec3; chassisConnectionPointWorld?: Vec3; directionLocal?: Vec3; directionWorld?: Vec3; axleLocal?: Vec3; axleWorld?: Vec3; suspensionRestLength?: number; suspensionMaxLength?: number; radius?: number; suspensionStiffness?: number; dampingCompression?: number; dampingRelaxation?: number; frictionSlip?: number; steering?: number; rotation?: number; deltaRotation?: number; rollInfluence?: number; maxSuspensionForce?: number; isFronmtWheel?: boolean; clippedInvContactDotSuspension?: number; suspensionRelativeVelocity?: number; suspensionForce?: number; skidInfo?: number; suspensionLength?: number; maxSuspensionTravel?: number; useCustomSlidingRotationalSpeed?: boolean; customSlidingRotationalSpeed?: number; position?: Vec3; direction?: Vec3; axis?: Vec3; body?: Body; } export class WheelInfo { maxSuspensionTravbel: number; customSlidingRotationalSpeed: number; useCustomSlidingRotationalSpeed: boolean; sliding: boolean; chassisConnectionPointLocal: Vec3; chassisConnectionPointWorld: Vec3; directionLocal: Vec3; directionWorld: Vec3; axleLocal: Vec3; axleWorld: Vec3; suspensionRestLength: number; suspensionMaxLength: number; radius: number; suspensionStiffness: number; dampingCompression: number; dampingRelaxation: number; frictionSlip: number; steering: number; rotation: number; deltaRotation: number; rollInfluence: number; maxSuspensionForce: number; engineForce: number; brake: number; isFrontWheel: boolean; clippedInvContactDotSuspension: number; suspensionRelativeVelocity: number; suspensionForce: number; skidInfo: number; suspensionLength: number; sideImpulse: number; forwardImpulse: number; raycastResult: RaycastResult; worldTransform: Transform; isInContact: boolean; constructor(options?: IWheelInfoOptions); } export class RaycastVehicle { chassisBody: Body; wheelInfos: IWheelInfoOptions[]; sliding: boolean; world: World; iindexRightAxis: number; indexForwardAxis: number; indexUpAxis: number; constructor(options?: IRaycastVehicleOptions); addWheel(options?: IWheelInfoOptions): void; setSteeringValue(value: number, wheelIndex: number): void; applyEngineForce(value: number, wheelIndex: number): void; setBrake(brake: number, wheelIndex: number): void; addToWorld(world: World): void; getVehicleAxisWorld(axisIndex: number, result: Vec3): Vec3; updateVehicle(timeStep: number): void; updateSuspension(deltaTime: number): void; removeFromWorld(world: World): void; getWheelTransformWorld(wheelIndex: number): Transform; } export interface IRigidVehicleOptions { chassisBody: Body; } export class RigidVehicle { wheelBodies: Body[]; coordinateSystem: Vec3; chassisBody: Body; constraints: Constraint[]; wheelAxes: Vec3[]; wheelForces: Vec3[]; constructor(options?: IRigidVehicleOptions); addWheel(options?: IWheelInfoOptions): Body; setSteeringValue(value: number, wheelIndex: number): void; setMotorSpeed(value: number, wheelIndex: number): void; disableMotor(wheelIndex: number): void; setWheelForce(value: number, wheelIndex: number): void; applyWheelForce(value: number, wheelIndex: number): void; addToWorld(world: World): void; removeFromWorld(world: World): void; getWheelSpeed(wheelIndex: number): number; } export class SPHSystem { particles: Particle[]; density: number; smoothingRadius: number; speedOfSound: number; viscosity: number; eps: number; pressures: number[]; densities: number[]; neighbors: number[]; add(particle: Particle): void; remove(particle: Particle): void; getNeighbors(particle: Particle, neighbors: Particle[]): void; update(): void; w(r: number): number; gradw(rVec: Vec3, resultVec: Vec3): void; nablaw(r: number): number; } export interface ISpringOptions { restLength?: number; stiffness?: number; damping?: number; worldAnchorA?: Vec3; worldAnchorB?: Vec3; localAnchorA?: Vec3; localAnchorB?: Vec3; } export class Spring { restLength: number; stffness: number; damping: number; bodyA: Body; bodyB: Body; localAnchorA: Vec3; localAnchorB: Vec3; constructor(options?: ISpringOptions); setWorldAnchorA(worldAnchorA: Vec3): void; setWorldAnchorB(worldAnchorB: Vec3): void; getWorldAnchorA(result: Vec3): void; getWorldAnchorB(result: Vec3): void; applyForce(): void; } export class Box extends Shape { static calculateIntertia(halfExtents: Vec3, mass: number, target: Vec3): void; boundingSphereRadius: number; collisionResponse: boolean; halfExtents: Vec3; convexPolyhedronRepresentation: ConvexPolyhedron; constructor(halfExtents: Vec3); updateConvexPolyhedronRepresentation(): void; calculateLocalInertia(mass: number, target?: Vec3): Vec3; getSideNormals(sixTargetVectors: boolean, quat?: Quaternion): Vec3[]; updateBoundingSphereRadius(): number; volume(): number; forEachWorldCorner(pos: Vec3, quat: Quaternion, callback: Function): void; } export class ConvexPolyhedron extends Shape { static computeNormal(va: Vec3, vb: Vec3, vc: Vec3, target: Vec3): void; static project(hull: ConvexPolyhedron, axis: Vec3, pos: Vec3, quat: Quaternion, result: number[]): void; vertices: Vec3[]; worldVertices: Vec3[]; worldVerticesNeedsUpdate: boolean; faces: number[][]; faceNormals: Vec3[]; uniqueEdges: Vec3[]; constructor(points?: Vec3[], faces?: number[]); computeEdges(): void; computeNormals(): void; getFaceNormal(i: number, target: Vec3): Vec3; clipAgainstHull(posA: Vec3, quatA: Quaternion, hullB: Vec3, quatB: Quaternion, separatingNormal: Vec3, minDist: number, maxDist: number, result: any[]): void; findSaparatingAxis(hullB: ConvexPolyhedron, posA: Vec3, quatA: Quaternion, posB: Vec3, quatB: Quaternion, target: Vec3, faceListA: any[], faceListB: any[]): boolean; testSepAxis(axis: Vec3, hullB: ConvexPolyhedron, posA: Vec3, quatA: Quaternion, posB: Vec3, quatB: Quaternion): number; getPlaneConstantOfFace(face_i: number): number; clipFaceAgainstHull(separatingNormal: Vec3, posA: Vec3, quatA: Quaternion, worldVertsB1: Vec3[], minDist: number, maxDist: number, result: any[]): void; clipFaceAgainstPlane(inVertices: Vec3[], outVertices: Vec3[], planeNormal: Vec3, planeConstant: number): Vec3; computeWorldVertices(position: Vec3, quat: Quaternion): void; computeLocalAABB(aabbmin: Vec3, aabbmax: Vec3): void; computeWorldFaceNormals(quat: Quaternion): void; calculateWorldAABB(pos: Vec3, quat: Quaternion, min: Vec3, max: Vec3): void; getAveragePointLocal(target: Vec3): Vec3; transformAllPoints(offset: Vec3, quat: Quaternion): void; pointIsInside(p: Vec3): boolean; } export class Cylinder extends Shape { constructor(radiusTop: number, radiusBottom: number, height: number, numSegments: number); } export interface IHightfield { minValue?: number; maxValue?: number; elementSize: number; } export class Heightfield extends Shape { data: number[][]; maxValue: number; minValue: number; elementSize: number; cacheEnabled: boolean; pillarConvex: ConvexPolyhedron; pillarOffset: Vec3; type: number; constructor(data: number[], options?: IHightfield); update(): void; updateMinValue(): void; updateMaxValue(): void; setHeightValueAtIndex(xi: number, yi: number, value: number): void; getRectMinMax(iMinX: number, iMinY: number, iMaxX: number, iMaxY: number, result: any[]): void; getIndexOfPosition(x: number, y: number, result: any[], clamp: boolean): boolean; getConvexTrianglePillar(xi: number, yi: number, getUpperTriangle: boolean): void; } export class Particle extends Shape { } export class Plane extends Shape { worldNormal: Vec3; worldNormalNeedsUpdate: boolean; boundingSphereRadius: number; computeWorldNormal(quat: Quaternion): void; calculateWorldAABB(pos: Vec3, quat: Quaternion, min: number, max: number): void; } export class Shape { static types: { SPHERE: number; PLANE: number; BOX: number; COMPOUND: number; CONVEXPOLYHEDRON: number; HEIGHTFIELD: number; PARTICLE: number; CYLINDER: number; } type: number; boundingSphereRadius: number; collisionResponse: boolean; updateBoundingSphereRadius(): number; volume(): number; calculateLocalInertia(mass: number, target: Vec3): Vec3; } export class Sphere extends Shape { radius: number; constructor(radius: number); } export class GSSolver extends Solver { iterations: number; tolerance: number; solve(dy: number, world: World): number; } export class Solver { iterations: number; equations: Equation[]; solve(dy: number, world: World): number; addEquation(eq: Equation): void; removeEquation(eq: Equation): void; removeAllEquations(): void; } export class SplitSolver extends Solver { subsolver: Solver; constructor(subsolver: Solver); solve(dy: number, world: World): number; } export class EventTarget { addEventListener(type: string, listener: Function): EventTarget; hasEventListener(type: string, listener: Function): boolean; removeEventListener(type: string, listener: Function): EventTarget; dispatchEvent(event: IEvent): IEvent; } export class Pool { objects: any[]; type: any[]; release(): any; get(): any; constructObject(): any; } export class TupleDictionary { data: { keys: any[]; }; get(i: number, j: number): number; set(i: number, j: number, value: number): void; reset(): void; } export class Utils { static defaults(options?: any, defaults?: any): any; } export class Vec3Pool extends Pool { type: any; constructObject(): Vec3; } export class NarrowPhase { contactPointPool: Pool[]; v3pool: Vec3Pool; } export class World extends EventTarget { iterations: number; dt: number; allowSleep: boolean; contacts: ContactEquation[]; frictionEquations: FrictionEquation[]; quatNormalizeSkip: number; quatNormalizeFast: boolean; time: number; stepnumber: number; default_dt: number; nextId: number; gravity: Vec3; broadphase: NaiveBroadphase; bodies: Body[]; solver: Solver; constraints: Constraint[]; narrowPhase: NarrowPhase; collisionMatrix: ArrayCollisionMatrix; collisionMatrixPrevious: ArrayCollisionMatrix; materials: Material[]; contactmaterials: ContactMaterial[]; contactMaterialTable: TupleDictionary; defaultMaterial: Material; defaultContactMaterial: ContactMaterial; doProfiling: boolean; profile: { solve: number; makeContactConstraints: number; broadphaser: number; integrate: number; narrowphase: number; }; subsystems: any[]; addBodyEvent: IBodyEvent; removeBodyEvent: IBodyEvent; getContactMaterial(m1: Material, m2: Material): ContactMaterial; numObjects(): number; collisionMatrixTick(): void; addBody(body: Body): void; addConstraint(c: Constraint): void; removeConstraint(c: Constraint): void; rayTest(from: Vec3, to: Vec3, result: RaycastResult): void; remove(body: Body): void; addMaterial(m: Material): void; addContactMaterial(cmat: ContactMaterial): void; step(dy: number, timeSinceLastCalled?: number, maxSubSteps?: number): void; } export interface IEvent { type: string; } export interface IBodyEvent extends IEvent { body: Body; } export interface ICollisionEvent extends IBodyEvent { contact: any; } } declare module "cannon" { export = CANNON; }
the_stack
import * as vscode from "vscode"; import { VSCExpress } from "vscode-express"; import { BadRequestError } from "../common/badRequestError"; import { ColorizedChannel } from "../common/colorizedChannel"; import { Configuration } from "../common/configuration"; import { Constants } from "../common/constants"; import { CredentialStore } from "../common/credentialStore"; import { ProcessError } from "../common/processError"; import { UserCancelledError } from "../common/userCancelledError"; import { Utility } from "../common/utility"; import { DeviceModelManager, ModelType } from "../deviceModel/deviceModelManager"; import { DigitalTwinConstants } from "../intelliSense/digitalTwinConstants"; import { ChoiceType, MessageType, UI } from "../view/ui"; import { UIConstants } from "../view/uiConstants"; import { ModelRepositoryClient } from "./modelRepositoryClient"; import { ModelRepositoryConnection } from "./modelRepositoryConnection"; import { GetResult, SearchResult } from "./modelRepositoryInterface"; import { TelemetryContext } from "../../../../telemetry"; /** * Repository type */ export enum RepositoryType { Public = "Public repository", Company = "Company repository" } /** * Repository info */ export interface RepositoryInfo { hostname: string; apiVersion: string; repositoryId?: string; accessToken?: string; } /** * Model file info */ export interface ModelFileInfo { id: string; type: ModelType; filePath: string; } /** * Submit options */ interface SubmitOptions { overwrite: boolean; } /** * Model repository manager */ export class ModelRepositoryManager { /** * create repository info * @param publicRepository identify if it is public repository */ private static async createRepositoryInfo(publicRepository: boolean): Promise<RepositoryInfo> { if (publicRepository) { // get public repository connection from configuration const url: string | undefined = Configuration.getProperty<string>(Constants.PUBLIC_REPOSITORY_URL); if (!url) { throw new Error(Constants.PUBLIC_REPOSITORY_URL_NOT_FOUND_MSG); } return { hostname: Utility.enforceHttps(url), apiVersion: Constants.MODEL_REPOSITORY_API_VERSION }; } else { // get company repository connection from credential store const connectionString: string | null = await CredentialStore.get(Constants.MODEL_REPOSITORY_CONNECTION_KEY); if (!connectionString) { throw new Error(Constants.CONNECTION_STRING_NOT_FOUND_MSG); } return ModelRepositoryManager.getCompanyRepositoryInfo(connectionString); } } /** * get available repository info, company repository is prior to public repository */ private static async getAvailableRepositoryInfo(): Promise<RepositoryInfo[]> { const repoInfos: RepositoryInfo[] = []; const connectionString: string | null = await CredentialStore.get(Constants.MODEL_REPOSITORY_CONNECTION_KEY); if (connectionString) { repoInfos.push(ModelRepositoryManager.getCompanyRepositoryInfo(connectionString)); } repoInfos.push(await ModelRepositoryManager.createRepositoryInfo(true)); return repoInfos; } /** * set up company model repository connection */ private static async setupConnection(): Promise<void> { let newConnection = false; let connectionString: string | null = await CredentialStore.get(Constants.MODEL_REPOSITORY_CONNECTION_KEY); if (!connectionString) { connectionString = await UI.inputConnectionString(UIConstants.INPUT_REPOSITORY_CONNECTION_STRING_LABEL); newConnection = true; } const repoInfo: RepositoryInfo = ModelRepositoryManager.getCompanyRepositoryInfo(connectionString); // test connection by calling searchModel await ModelRepositoryClient.searchModel(repoInfo, ModelType.Interface, Constants.EMPTY_STRING, 1, null); if (newConnection) { await CredentialStore.set(Constants.MODEL_REPOSITORY_CONNECTION_KEY, connectionString); } } /** * get company repository info * @param connectionString connection string */ private static getCompanyRepositoryInfo(connectionString: string): RepositoryInfo { const connection: ModelRepositoryConnection = ModelRepositoryConnection.parse(connectionString); return { hostname: Utility.enforceHttps(connection.hostName), apiVersion: Constants.MODEL_REPOSITORY_API_VERSION, repositoryId: connection.repositoryId, accessToken: connection.generateAccessToken() }; } /** * validate model id list * @param modelIds model id list */ private static validateModelIds(modelIds: string[]): void { if (!modelIds || !modelIds.length) { throw new BadRequestError(`modelIds ${Constants.NOT_EMPTY_MSG}`); } } private readonly express: VSCExpress; private readonly component: string; constructor(context: vscode.ExtensionContext, filePath: string, private readonly outputChannel: ColorizedChannel) { this.express = new VSCExpress(context, filePath); this.component = Constants.MODEL_REPOSITORY_COMPONENT; } /** * sign in model repository */ async signIn(): Promise<void> { const items: vscode.QuickPickItem[] = [{ label: RepositoryType.Public }, { label: RepositoryType.Company }]; const selected: vscode.QuickPickItem = await UI.showQuickPick(UIConstants.SELECT_REPOSITORY_LABEL, items); const operation = `Connect to ${selected.label}`; this.outputChannel.start(operation, this.component); if (selected.label === RepositoryType.Company) { try { await ModelRepositoryManager.setupConnection(); } catch (error) { if (error instanceof UserCancelledError) { throw error; } else { throw new ProcessError(operation, error, this.component); } } } // open web view const uri: string = selected.label === RepositoryType.Company ? Constants.COMPANY_REPOSITORY_PAGE : Constants.PUBLIC_REPOSITORY_PAGE; this.express.open(uri, UIConstants.MODEL_REPOSITORY_TITLE, vscode.ViewColumn.Two, { retainContextWhenHidden: true, enableScripts: true }); UI.showNotification(MessageType.Info, ColorizedChannel.formatMessage(operation)); this.outputChannel.end(operation, this.component); } /** * sign out model repository */ async signOut(): Promise<void> { const operation = "Sign out company repository"; this.outputChannel.start(operation, this.component); await CredentialStore.delete(Constants.MODEL_REPOSITORY_CONNECTION_KEY); // close web view if (this.express) { this.express.close(Constants.COMPANY_REPOSITORY_PAGE); } UI.showNotification(MessageType.Info, ColorizedChannel.formatMessage(operation)); this.outputChannel.end(operation, this.component); } /** * submit files to model repository * @param telemetryContext telemetry context */ async submitFiles(telemetryContext: TelemetryContext): Promise<void> { const files: string[] = await UI.selectModelFiles(UIConstants.SELECT_MODELS_LABEL); if (!files.length) { return; } // check unsaved files and save await UI.ensureFilesSaved(UIConstants.SAVE_FILE_CHANGE_LABEL, files); try { await ModelRepositoryManager.setupConnection(); } catch (error) { if (error instanceof UserCancelledError) { throw error; } else { throw new ProcessError(`Connect to ${RepositoryType.Company}`, error, this.component); } } try { const repoInfo: RepositoryInfo = await ModelRepositoryManager.createRepositoryInfo(false); await this.doSubmitLoopSilently(repoInfo, files, telemetryContext); } catch (error) { const operation = `Submit models to ${RepositoryType.Company}`; throw new ProcessError(operation, error, this.component); } } /** * search model from repository * @param type model type * @param publicRepository identify if it is public repository * @param keyword keyword * @param pageSize page size * @param continuationToken continuation token */ async searchModel( type: ModelType, publicRepository: boolean, keyword: string = Constants.EMPTY_STRING, pageSize: number = Constants.DEFAULT_PAGE_SIZE, continuationToken: string | null = null ): Promise<SearchResult> { if (pageSize <= 0) { throw new BadRequestError("pageSize should be greater than 0"); } // only show output when keyword is defined const showOutput: boolean = keyword ? true : false; const operation = `Search ${type} by keyword "${keyword}" from ${ publicRepository ? RepositoryType.Public : RepositoryType.Company }`; if (showOutput) { this.outputChannel.start(operation, this.component); } let result: SearchResult; try { const repoInfo: RepositoryInfo = await ModelRepositoryManager.createRepositoryInfo(publicRepository); result = await ModelRepositoryClient.searchModel(repoInfo, type, keyword, pageSize, continuationToken); } catch (error) { throw new ProcessError(operation, error, this.component); } if (showOutput) { this.outputChannel.end(operation, this.component); } return result; } /** * delete models from repository * @param publicRepository identify if it is public repository * @param modelIds model id list */ async deleteModels(publicRepository: boolean, modelIds: string[]): Promise<void> { if (publicRepository) { throw new BadRequestError(`${RepositoryType.Public} not support delete operation`); } ModelRepositoryManager.validateModelIds(modelIds); try { const repoInfo: RepositoryInfo = await ModelRepositoryManager.createRepositoryInfo(publicRepository); await this.doDeleteLoopSilently(repoInfo, modelIds); } catch (error) { const operation = `Delete models from ${RepositoryType.Company}`; throw new ProcessError(operation, error, this.component); } } /** * download models from repository * @param publicRepository identify if it is public repository * @param modelIds model id list */ async downloadModels(publicRepository: boolean, modelIds: string[]): Promise<void> { ModelRepositoryManager.validateModelIds(modelIds); const folder: string = await UI.selectRootFolder(UIConstants.SELECT_ROOT_FOLDER_LABEL); try { const repoInfo: RepositoryInfo = await ModelRepositoryManager.createRepositoryInfo(publicRepository); await this.doDownloadLoopSilently([repoInfo], modelIds, folder); } catch (error) { const operation = `Download models from ${publicRepository ? RepositoryType.Public : RepositoryType.Company}`; throw new ProcessError(operation, error, this.component); } } /** * download dependent interface of capability model, throw exception when interface not found * @param folder folder to download interface * @param capabilityModelFile capability model file path */ async downloadDependentInterface(folder: string, capabilityModelFile: string): Promise<void> { if (!folder || !capabilityModelFile) { throw new BadRequestError(`folder and capabilityModelFile ${Constants.NOT_EMPTY_MSG}`); } // get implemented interface of capability model const content = await Utility.getJsonContent(capabilityModelFile); const implementedInterface = content[DigitalTwinConstants.IMPLEMENTS]; if (!implementedInterface || !implementedInterface.length) { throw new BadRequestError("no implemented interface found in capability model"); } // get existing interface file in workspace const repoInfos: RepositoryInfo[] = await ModelRepositoryManager.getAvailableRepositoryInfo(); const fileInfos: ModelFileInfo[] = await UI.findModelFiles(ModelType.Interface); const exist = new Set<string>(fileInfos.map(f => f.id)); // eslint-disable-next-line @typescript-eslint/no-explicit-any let schema: any; let found: boolean; let message: string; for (const item of implementedInterface) { schema = item[DigitalTwinConstants.SCHEMA]; if (typeof schema !== "string" || exist.has(schema)) { continue; } found = await this.doDownloadModel(repoInfos, schema, folder); if (!found) { message = `interface ${schema} not found`; if (repoInfos.length === 1) { message = `${message}. ${Constants.NEED_OPEN_COMPANY_REPOSITORY_MSG}`; } throw new BadRequestError(message); } } } /** * download models silently, fault tolerant and don't throw exception * @param repoInfos repository info list * @param modelIds model id list * @param folder folder to download models */ private async doDownloadLoopSilently(repoInfos: RepositoryInfo[], modelIds: string[], folder: string): Promise<void> { for (const modelId of modelIds) { const operation = `Download model by id ${modelId}`; this.outputChannel.start(operation, this.component); try { await this.doDownloadModel(repoInfos, modelId, folder); this.outputChannel.end(operation, this.component); } catch (error) { this.outputChannel.error(operation, this.component, error); } } } /** * download model from repository, return false if model not found * @param repoInfos repository info list * @param modelId model id * @param folder folder to download model */ private async doDownloadModel(repoInfos: RepositoryInfo[], modelId: string, folder: string): Promise<boolean> { let result: GetResult | undefined; for (const repoInfo of repoInfos) { try { result = await ModelRepositoryClient.getModel(repoInfo, modelId, true); break; } catch (error) { if (error.statusCode === Constants.NOT_FOUND_CODE) { this.outputChannel.warn(`Model ${modelId} is not found from ${repoInfo.hostname}`); } else { this.outputChannel.error( `Fail to get model ${modelId} from ${repoInfo.hostname}, statusCode: ${error.statusCode}` ); } } } if (result) { await Utility.createModelFile(folder, result.modelId, result.content); return true; } return false; } /** * delete models silently, fault tolerant and don't throw exception * @param repoInfo repository info * @param modelIds model id list */ private async doDeleteLoopSilently(repoInfo: RepositoryInfo, modelIds: string[]): Promise<void> { for (const modelId of modelIds) { const operation = `Delete model by id ${modelId}`; this.outputChannel.start(operation, this.component); try { await ModelRepositoryClient.deleteModel(repoInfo, modelId); this.outputChannel.end(operation, this.component); } catch (error) { this.outputChannel.error(operation, this.component, error); } } } /** * submit model files silently, fault tolerant and don't throw exception * @param repoInfo repository info * @param files model file list * @param telemetryContext telemetry context */ private async doSubmitLoopSilently( repoInfo: RepositoryInfo, files: string[], telemetryContext: TelemetryContext ): Promise<void> { const usageData = new Map<ModelType, string[]>(); const options: SubmitOptions = { overwrite: false }; for (const file of files) { const operation = `Submit file ${file}`; this.outputChannel.start(operation, this.component); try { await this.doSubmitModel(repoInfo, file, options, usageData); this.outputChannel.end(operation, this.component); } catch (error) { this.outputChannel.error(operation, this.component, error); } } // set BI telemetry this.setTelemetryOfSubmitFiles(telemetryContext, usageData, files.length); } /** * submit model file to repository * @param repoInfo repository info * @param filePath model file path * @param options submit options * @param usageData usage data */ private async doSubmitModel( repoInfo: RepositoryInfo, filePath: string, option: SubmitOptions, usageData: Map<ModelType, string[]> ): Promise<void> { const content = await Utility.getJsonContent(filePath); const modelId: string = content[DigitalTwinConstants.ID]; const modelType: ModelType = DeviceModelManager.convertToModelType(content[DigitalTwinConstants.TYPE]); let result: GetResult | undefined; try { result = await ModelRepositoryClient.getModel(repoInfo, modelId, true); } catch (error) { // return 404 means it is a new model if (error.statusCode !== Constants.NOT_FOUND_CODE) { throw error; } } // ask user to overwrite if (result) { if (!option.overwrite) { const message = `Model ${modelId} already exist, ${UIConstants.ASK_TO_OVERWRITE_MSG}`; const choice: string | undefined = await vscode.window.showWarningMessage( message, ChoiceType.All, ChoiceType.Yes, ChoiceType.No ); if (!choice || choice === ChoiceType.No) { this.outputChannel.warn(`Skip overwrite model ${modelId}`); return; } else if (choice === ChoiceType.All) { option.overwrite = true; } } } await ModelRepositoryClient.updateModel(repoInfo, modelId, content); // record submitted model id let modelIds: string[] | undefined = usageData.get(modelType); if (!modelIds) { modelIds = []; usageData.set(modelType, modelIds); } modelIds.push(modelId); } /** * set telemetry context of submit files * @param telemetryContext telemetry context * @param usageData usage data * @param totalCount total count of submit files */ private setTelemetryOfSubmitFiles( telemetryContext: TelemetryContext, usageData: Map<ModelType, string[]>, totalCount: number ): void { let succeedCount = 0; let hashId: string; for (const [key, value] of usageData) { succeedCount += value.length; hashId = value.map(id => Utility.hash(id)).join(Constants.DEFAULT_SEPARATOR); switch (key) { case ModelType.Interface: telemetryContext.properties.interfaceId = hashId; break; case ModelType.CapabilityModel: telemetryContext.properties.capabilityModelId = hashId; break; default: } } telemetryContext.measurements.totalCount = totalCount; telemetryContext.measurements.succeedCount = succeedCount; } }
the_stack
import NetRegexes from '../../../../resources/netregexes'; import outputs from '../../../../resources/outputs'; import Util from '../../../../resources/util'; import ZoneId from '../../../../resources/zone_id'; import { RaidbossData } from '../../../../types/data'; import { LocaleText, TriggerSet } from '../../../../types/trigger'; const strikingDummyNames: LocaleText = { en: 'Striking Dummy', de: 'Trainingspuppe', ja: '木人', cn: '木人', ko: '나무인형', }; export interface Data extends RaidbossData { delayedDummyTimestampBefore: number; delayedDummyTimestampAfter: number; pokes: number; } const triggerSet: TriggerSet<Data> = { zoneId: ZoneId.MiddleLaNoscea, timelineFile: 'test.txt', // timeline here is additions to the timeline. They can // be strings, or arrays of strings, or functions that // take the same data object (including role and lang) // that triggers do. timeline: [ 'alerttext "Final Sting" before 4 "oh no final sting in 4"', 'alarmtext "Death" before 3', 'alertall "Long Castbar" before 1 speak "voice" "long"', (data) => { if (data.role !== 'tank' && data.role !== 'healer') return 'hideall "Super Tankbuster"'; return 'alarmtext "Super Tankbuster" before 2'; }, (data) => { if (data.role !== 'dps') return 'hideall "Pentacle Sac (DPS)"'; }, (data) => { if (data.role !== 'healer') return 'hideall "Almagest"'; return 'alarmtext "Almagest" before 0'; }, (data) => { return [ '40 "Death To ' + data.ShortName(data.me) + '!!"', 'hideall "Death"', ]; }, ], initData: () => { return { delayedDummyTimestampBefore: 0, delayedDummyTimestampAfter: 0, pokes: 0, }; }, timelineStyles: [ { regex: /^Death To/, style: { 'color': 'red', 'font-family': 'Impact', }, }, ], timelineTriggers: [ { id: 'Test Angry Dummy', regex: /Angry Dummy/, beforeSeconds: 2, infoText: (_data, _matches, output) => output.stack!(), tts: (_data, _matches, output) => output.stackTTS!(), outputStrings: { stack: { en: 'Stack for Angry Dummy', de: 'Sammeln für Wütender Dummy', fr: 'Packez-vous pour Mannequin en colère', ja: '怒る木人に集合', cn: '木人处集合', ko: '화난 나무인형에 집합', }, stackTTS: { en: 'Stack', de: 'Sammeln', fr: 'Packez-vous', ja: '集合', cn: '集合', ko: '집합', }, }, }, { id: 'Test Delayed Dummy', regex: /Angry Dummy/, beforeSeconds: 0, // Add in a huge delay to make it obvious the delay runs before promise. delaySeconds: 10, promise: (data) => { data.delayedDummyTimestampBefore = Date.now(); const p = new Promise<void>((res) => { window.setTimeout(() => { data.delayedDummyTimestampAfter = Date.now(); res(); }, 3000); }); return p; }, infoText: (data, _matches, output) => { const elapsed = data.delayedDummyTimestampAfter - data.delayedDummyTimestampBefore; return output.elapsed!({ elapsed: elapsed }); }, outputStrings: { elapsed: { en: 'Elapsed ms: ${elapsed}', de: 'Abgelaufene ms: ${elapsed}', fr: 'Expiré ms: ${elapsed}', ja: '経過時間:${elapsed}', cn: '经过时间:${elapsed}', ko: '경과 시간: ${elapsed}', }, }, }, ], triggers: [ { id: 'Test Poke', type: 'GameLog', netRegex: NetRegexes.gameNameLog({ line: 'You poke the striking dummy.*?', capture: false }), netRegexDe: NetRegexes.gameNameLog({ line: 'Du stupst die Trainingspuppe an.*?', capture: false }), netRegexFr: NetRegexes.gameNameLog({ line: 'Vous touchez légèrement le mannequin d\'entraînement du doigt.*?', capture: false }), netRegexJa: NetRegexes.gameNameLog({ line: '.*は木人をつついた.*?', capture: false }), netRegexCn: NetRegexes.gameNameLog({ line: '.*用手指戳向木人.*?', capture: false }), netRegexKo: NetRegexes.gameNameLog({ line: '.*나무인형을 쿡쿡 찌릅니다.*?', capture: false }), preRun: (data) => ++data.pokes, infoText: (data, _matches, output) => output.poke!({ numPokes: data.pokes }), outputStrings: { poke: { en: 'poke #${numPokes}', de: 'stups #${numPokes}', fr: 'poussée #${numPokes}', ja: 'つつく #${numPokes}', cn: '戳 #${numPokes}', ko: '${numPokes}번 찌름', }, }, }, { id: 'Test Psych', type: 'GameLog', netRegex: NetRegexes.gameNameLog({ line: 'You psych yourself up alongside the striking dummy.*?', capture: false }), netRegexDe: NetRegexes.gameNameLog({ line: 'Du willst wahren Kampfgeist in der Trainingspuppe entfachen.*?', capture: false }), netRegexFr: NetRegexes.gameNameLog({ line: 'Vous vous motivez devant le mannequin d\'entraînement.*?', capture: false }), netRegexJa: NetRegexes.gameNameLog({ line: '.*は木人に活を入れた.*?', capture: false }), netRegexCn: NetRegexes.gameNameLog({ line: '.*激励木人.*?', capture: false }), netRegexKo: NetRegexes.gameNameLog({ line: '.*나무인형에게 힘을 불어넣습니다.*?', capture: false }), alertText: (_data, _matches, output) => output.text!(), tts: { en: 'psych', de: 'auf gehts', fr: 'motivation', ja: '活を入れる', cn: '激励', ko: '힘내라!', }, outputStrings: { text: { en: 'PSYCH!!!', de: 'AUF GEHTS!!!', fr: 'MOTIVATION !!!', ja: '活を入れる!!', cn: '激励!!', ko: '힘내라!!', }, }, }, { id: 'Test Laugh', type: 'GameLog', netRegex: NetRegexes.gameNameLog({ line: 'You burst out laughing at the striking dummy.*?', capture: false }), netRegexDe: NetRegexes.gameNameLog({ line: 'Du lachst herzlich mit der Trainingspuppe.*?', capture: false }), netRegexFr: NetRegexes.gameNameLog({ line: 'Vous vous esclaffez devant le mannequin d\'entraînement.*?', capture: false }), netRegexJa: NetRegexes.gameNameLog({ line: '.*は木人のことを大笑いした.*?', capture: false }), netRegexCn: NetRegexes.gameNameLog({ line: '.*看着木人高声大笑.*?', capture: false }), netRegexKo: NetRegexes.gameNameLog({ line: '.*나무인형을 보고 폭소를 터뜨립니다.*?', capture: false }), suppressSeconds: 5, alarmText: (_data, _matches, output) => output.text!(), tts: { en: 'hahahahaha', de: 'hahahahaha', fr: 'hahahahaha', ja: 'ハハハハハ', cn: '哈哈哈哈哈哈', ko: '푸하하하하핳', }, outputStrings: { text: { en: 'hahahahaha', de: 'hahahahaha', fr: 'hahahahaha', ja: 'ハハハハハ', cn: '2333333333', ko: '푸하하하하핳', }, }, }, { id: 'Test Clap', type: 'GameLog', netRegex: NetRegexes.gameNameLog({ line: 'You clap for the striking dummy.*?', capture: false }), netRegexDe: NetRegexes.gameNameLog({ line: 'Du klatschst begeistert Beifall für die Trainingspuppe.*?', capture: false }), netRegexFr: NetRegexes.gameNameLog({ line: 'Vous applaudissez le mannequin d\'entraînement.*?', capture: false }), netRegexJa: NetRegexes.gameNameLog({ line: '.*は木人に拍手した.*?', capture: false }), netRegexCn: NetRegexes.gameNameLog({ line: '.*向木人送上掌声.*?', capture: false }), netRegexKo: NetRegexes.gameNameLog({ line: '.*나무인형에게 박수를 보냅니다.*?', capture: false }), sound: '../../resources/sounds/freesound/power_up.webm', soundVolume: 0.3, tts: (_data, _matches, output) => output.text!(), outputStrings: { text: { en: 'clapity clap', de: 'klatschen', fr: 'applaudissement', ja: '拍手', cn: '鼓掌', ko: '박수 짝짝짝', }, }, }, { id: 'Test Lang', type: 'GameLog', // In game: /echo cactbot lang netRegex: NetRegexes.echo({ line: 'cactbot lang.*?', capture: false }), netRegexDe: NetRegexes.echo({ line: 'cactbot sprache.*?', capture: false }), netRegexJa: NetRegexes.echo({ line: 'cactbot言語.*?', capture: false }), netRegexCn: NetRegexes.echo({ line: 'cactbot语言.*?', capture: false }), netRegexKo: NetRegexes.echo({ line: 'cactbot 언어.*?', capture: false }), infoText: (data, _matches, output) => output.text!({ lang: data.parserLang }), outputStrings: { text: { en: 'Language: ${lang}', de: 'Sprache: ${lang}', fr: 'Langage: ${lang}', ja: '言語:${lang}', cn: '语言: ${lang}', ko: '언어: ${lang}', }, }, }, { id: 'Test Response', type: 'GameLog', netRegex: NetRegexes.echo({ line: 'cactbot test response.*?', capture: false }), netRegexDe: NetRegexes.echo({ line: 'cactbot test antwort.*?', capture: false }), netRegexJa: NetRegexes.echo({ line: 'cactbotレスポンステスト.*?', capture: false }), netRegexCn: NetRegexes.echo({ line: 'cactbot响应测试.*?', capture: false }), netRegexKo: NetRegexes.echo({ line: 'cactbot 응답 테스트.*?', capture: false }), response: (_data, _matches, output) => { // cactbot-builtin-response output.responseOutputStrings = { alarmOne: outputs.num1, alertTwo: outputs.num2, infoThree: outputs.num3, ttsFour: outputs.num4, }; return { alarmText: output.alarmOne!(), alertText: output.alertTwo!(), infoText: output.infoThree!(), tts: output.ttsFour!(), }; }, }, { id: 'Test Watch', type: 'GameLog', netRegex: NetRegexes.echo({ line: 'cactbot test watch.*?', capture: false }), netRegexDe: NetRegexes.echo({ line: 'cactbot test beobachten.*?', capture: false }), netRegexJa: NetRegexes.echo({ line: 'cactbot探知テスト.*?', capture: false }), netRegexCn: NetRegexes.echo({ line: 'cactbot探测测试.*?', capture: false }), netRegexKo: NetRegexes.echo({ line: 'cactbot 탐지 테스트.*?', capture: false }), promise: (data) => Util.watchCombatant({ names: [ data.me, strikingDummyNames[data.lang] ?? strikingDummyNames['en'], ], // 50 seconds maxDuration: 50000, }, (ret) => { const me = ret.combatants.find((c) => c.Name === data.me); const dummyName = strikingDummyNames[data.lang] ?? strikingDummyNames['en']; const dummies = ret.combatants.filter((c) => c.Name === dummyName); if (me && dummies) { for (const dummy of dummies) { const distX = Math.abs(me.PosX - dummy.PosX); const distY = Math.abs(me.PosY - dummy.PosY); const dist = Math.hypot(distX, distY); console.log(`test watch: distX = ${distX}; distY = ${distY}; dist = ${dist}`); if (dist < 5) return true; } return false; } console.log(`test watch: me = ${me ? 'true' : 'false'}; no dummies`); return false; }), infoText: (_data, _matches, output) => output.close!(), outputStrings: { close: { en: 'Dummy close!', de: 'Puppe beendet!', ja: '木人に近すぎ!', cn: '靠近木人!', ko: '나무인형과 가까움!', }, }, }, ], timelineReplace: [ { locale: 'de', replaceSync: { 'You bid farewell to the striking dummy': 'Du winkst der Trainingspuppe zum Abschied zu', 'You bow courteously to the striking dummy': 'Du verbeugst dich hochachtungsvoll vor der Trainingspuppe', 'test sync': 'test sync', 'You burst out laughing at the striking dummy': 'Du lachst herzlich mit der Trainingspuppe', 'cactbot lang': 'cactbot sprache', 'cactbot test response': 'cactbot test antwort', 'cactbot test watch': 'cactbot test beobachten', 'You clap for the striking dummy': 'Du klatschst begeistert Beifall für die Trainingspuppe', 'You psych yourself up alongside the striking dummy': 'Du willst wahren Kampfgeist in der Trainingspuppe entfachen', 'You poke the striking dummy': 'Du stupst die Trainingspuppe an', }, replaceText: { 'Final Sting': 'Schlussstich', 'Almagest': 'Almagest', 'Angry Dummy': 'Wütender Dummy', 'Long Castbar': 'Langer Zauberbalken', 'Dummy Stands Still': 'Dummy still stehen', 'Death': 'Tot', 'Super Tankbuster': 'Super Tankbuster', 'Pentacle Sac': 'Pentacle Sac', 'Engage': 'Start!', }, }, { locale: 'fr', replaceSync: { 'You bid farewell to the striking dummy': 'Vous faites vos adieux au mannequin d\'entraînement', 'You bow courteously to the striking dummy': 'Vous vous inclinez devant le mannequin d\'entraînement', 'test sync': 'test sync', }, replaceText: { 'Almagest': 'Almageste', 'Angry Dummy': 'Mannequin en colère', 'Death': 'Mort', 'Death To': 'Mort sur', 'Dummy Stands Still': 'Mannequin immobile', 'Engage': 'À l\'attaque', 'Final Sting': 'Dard final', 'Long Castbar': 'Longue barre de lancement', 'Pentacle Sac': 'Pentacle Sac', 'Super Tankbuster': 'Super Tank buster', }, }, { locale: 'ja', replaceSync: { 'You bid farewell to the striking dummy': '.*は木人に別れの挨拶をした', 'You bow courteously to the striking dummy': '.*は木人にお辞儀した', 'test sync': 'test sync', }, replaceText: { 'Almagest': 'アルマゲスト', 'Angry Dummy': '怒る木人', 'Death': '死', 'Death To': '死の宣告', 'Dummy Stands Still': '木人はじっとしている', 'Engage': '戦闘開始', 'Final Sting': 'ファイナルスピア', 'Long Castbar': '長い長い詠唱バー', 'Pentacle Sac': 'ナイサイ', 'Super Tankbuster': 'スーパータンクバスター', }, }, { locale: 'cn', replaceSync: { 'You bid farewell to the striking dummy': '.*向木人告别', 'You bow courteously to the striking dummy': '.*恭敬地对木人行礼', 'test sync': 'test sync', 'You burst out laughing at the striking dummy': '.*看着木人高声大笑', 'cactbot lang': 'cactbot语言', 'cactbot test response': 'cactbot响应测试', 'cactbot test watch': 'cactbot探测测试', 'You clap for the striking dummy': '.*向木人送上掌声', 'You psych yourself up alongside the striking dummy': '.*激励木人', 'You poke the striking dummy': '.*用手指戳向木人', }, replaceText: { 'Final Sting': '终极针', 'Almagest': '至高无上', 'Angry Dummy': '愤怒的木人', 'Long Castbar': '长时间咏唱', 'Dummy Stands Still': '木人8动了', 'Super Tankbuster': '超级无敌转圈死刑', 'Death To': '嗝屁攻击:', 'Death': '嗝屁', 'Engage': '战斗开始', 'Pentacle Sac': '传毒', }, }, { locale: 'ko', replaceSync: { 'You bid farewell to the striking dummy': '.*나무인형에게 작별 인사를 합니다', 'You bow courteously to the striking dummy': '.*나무인형에게 공손하게 인사합니다', 'test sync': '테스트 싱크', 'You burst out laughing at the striking dummy': '.*나무인형을 보고 폭소를 터뜨립니다', 'cactbot lang': 'cactbot 언어', 'cactbot test response': 'cactbot 응답 테스트', 'cactbot test watch': 'cactbot 탐지 테스트', 'You clap for the striking dummy': '.*나무인형에게 박수를 보냅니다', 'You psych yourself up alongside the striking dummy': '.*나무인형에게 힘을 불어넣습니다', 'You poke the striking dummy': '.*나무인형을 쿡쿡 찌릅니다', }, replaceText: { 'Final Sting': '마지막 벌침', 'Almagest': '알마게스트', 'Angry Dummy': '화난 나무인형', 'Long Castbar': '긴 시전바', 'Dummy Stands Still': '나무인형이 아직 살아있다', 'Death': '데스', 'Super Tankbuster': '초강력 탱크버스터', 'Pentacle Sac': 'Pentacle Sac', 'Engage': '시작', }, }, ], }; export default triggerSet;
the_stack
import { HttpHandlerOptions as __HttpHandlerOptions } from "@aws-sdk/types"; import { CloudTrailClient } from "./CloudTrailClient"; import { AddTagsCommand, AddTagsCommandInput, AddTagsCommandOutput } from "./commands/AddTagsCommand"; import { CreateTrailCommand, CreateTrailCommandInput, CreateTrailCommandOutput } from "./commands/CreateTrailCommand"; import { DeleteTrailCommand, DeleteTrailCommandInput, DeleteTrailCommandOutput } from "./commands/DeleteTrailCommand"; import { DescribeTrailsCommand, DescribeTrailsCommandInput, DescribeTrailsCommandOutput, } from "./commands/DescribeTrailsCommand"; import { GetEventSelectorsCommand, GetEventSelectorsCommandInput, GetEventSelectorsCommandOutput, } from "./commands/GetEventSelectorsCommand"; import { GetInsightSelectorsCommand, GetInsightSelectorsCommandInput, GetInsightSelectorsCommandOutput, } from "./commands/GetInsightSelectorsCommand"; import { GetTrailCommand, GetTrailCommandInput, GetTrailCommandOutput } from "./commands/GetTrailCommand"; import { GetTrailStatusCommand, GetTrailStatusCommandInput, GetTrailStatusCommandOutput, } from "./commands/GetTrailStatusCommand"; import { ListPublicKeysCommand, ListPublicKeysCommandInput, ListPublicKeysCommandOutput, } from "./commands/ListPublicKeysCommand"; import { ListTagsCommand, ListTagsCommandInput, ListTagsCommandOutput } from "./commands/ListTagsCommand"; import { ListTrailsCommand, ListTrailsCommandInput, ListTrailsCommandOutput } from "./commands/ListTrailsCommand"; import { LookupEventsCommand, LookupEventsCommandInput, LookupEventsCommandOutput, } from "./commands/LookupEventsCommand"; import { PutEventSelectorsCommand, PutEventSelectorsCommandInput, PutEventSelectorsCommandOutput, } from "./commands/PutEventSelectorsCommand"; import { PutInsightSelectorsCommand, PutInsightSelectorsCommandInput, PutInsightSelectorsCommandOutput, } from "./commands/PutInsightSelectorsCommand"; import { RemoveTagsCommand, RemoveTagsCommandInput, RemoveTagsCommandOutput } from "./commands/RemoveTagsCommand"; import { StartLoggingCommand, StartLoggingCommandInput, StartLoggingCommandOutput, } from "./commands/StartLoggingCommand"; import { StopLoggingCommand, StopLoggingCommandInput, StopLoggingCommandOutput } from "./commands/StopLoggingCommand"; import { UpdateTrailCommand, UpdateTrailCommandInput, UpdateTrailCommandOutput } from "./commands/UpdateTrailCommand"; /** * <fullname>CloudTrail</fullname> * <p>This is the CloudTrail API Reference. It provides descriptions of actions, data types, common parameters, and common errors for CloudTrail.</p> * <p>CloudTrail is a web service that records Amazon Web Services API calls for your Amazon Web Services account and delivers log files to an Amazon S3 bucket. * The recorded information includes the identity of the user, the start time of the Amazon Web Services API call, the source IP address, the request parameters, and the response elements returned by the service.</p> * * <note> * <p>As an alternative to the API, * you can use one of the Amazon Web Services SDKs, which consist of libraries and sample code for various * programming languages and platforms (Java, Ruby, .NET, iOS, Android, etc.). The SDKs * provide programmatic access to CloudTrail. For example, the SDKs * handle cryptographically signing requests, managing errors, and retrying requests * automatically. For more information about the Amazon Web Services SDKs, including how to download and install * them, see <a href="http://aws.amazon.com/tools/">Tools to Build on Amazon Web Services</a>.</p> * </note> * <p>See the <a href="https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-user-guide.html">CloudTrail User * Guide</a> for information about the data that is included with each Amazon Web Services API call listed in the log files.</p> */ export class CloudTrail extends CloudTrailClient { /** * <p>Adds one or more tags to a trail, up to a limit of 50. Overwrites an existing tag's value when a new value is specified for an existing tag key. * Tag key names must be unique for a trail; you cannot have two keys with the same name but different values. * If you specify a key without a value, the tag will be created with the specified key and a value of null. * You can tag a trail that applies to all Amazon Web Services Regions only from the Region in which the trail was created (also known as its home region).</p> */ public addTags(args: AddTagsCommandInput, options?: __HttpHandlerOptions): Promise<AddTagsCommandOutput>; public addTags(args: AddTagsCommandInput, cb: (err: any, data?: AddTagsCommandOutput) => void): void; public addTags( args: AddTagsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: AddTagsCommandOutput) => void ): void; public addTags( args: AddTagsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: AddTagsCommandOutput) => void), cb?: (err: any, data?: AddTagsCommandOutput) => void ): Promise<AddTagsCommandOutput> | void { const command = new AddTagsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Creates a trail that specifies the settings for delivery of log data to an Amazon S3 bucket. * </p> */ public createTrail(args: CreateTrailCommandInput, options?: __HttpHandlerOptions): Promise<CreateTrailCommandOutput>; public createTrail(args: CreateTrailCommandInput, cb: (err: any, data?: CreateTrailCommandOutput) => void): void; public createTrail( args: CreateTrailCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: CreateTrailCommandOutput) => void ): void; public createTrail( args: CreateTrailCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: CreateTrailCommandOutput) => void), cb?: (err: any, data?: CreateTrailCommandOutput) => void ): Promise<CreateTrailCommandOutput> | void { const command = new CreateTrailCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Deletes a trail. This operation must be called from the region in which the trail was * created. <code>DeleteTrail</code> cannot be called on the shadow trails (replicated trails * in other regions) of a trail that is enabled in all regions.</p> */ public deleteTrail(args: DeleteTrailCommandInput, options?: __HttpHandlerOptions): Promise<DeleteTrailCommandOutput>; public deleteTrail(args: DeleteTrailCommandInput, cb: (err: any, data?: DeleteTrailCommandOutput) => void): void; public deleteTrail( args: DeleteTrailCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DeleteTrailCommandOutput) => void ): void; public deleteTrail( args: DeleteTrailCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DeleteTrailCommandOutput) => void), cb?: (err: any, data?: DeleteTrailCommandOutput) => void ): Promise<DeleteTrailCommandOutput> | void { const command = new DeleteTrailCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Retrieves settings for one or more trails associated with the current region for your account.</p> */ public describeTrails( args: DescribeTrailsCommandInput, options?: __HttpHandlerOptions ): Promise<DescribeTrailsCommandOutput>; public describeTrails( args: DescribeTrailsCommandInput, cb: (err: any, data?: DescribeTrailsCommandOutput) => void ): void; public describeTrails( args: DescribeTrailsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: DescribeTrailsCommandOutput) => void ): void; public describeTrails( args: DescribeTrailsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: DescribeTrailsCommandOutput) => void), cb?: (err: any, data?: DescribeTrailsCommandOutput) => void ): Promise<DescribeTrailsCommandOutput> | void { const command = new DescribeTrailsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Describes the settings for the event selectors that you configured for your trail. * The information returned for your event selectors includes the following:</p> * <ul> * <li> * <p>If your event selector includes read-only events, write-only events, or * all events. This applies to both management events and data events.</p> * </li> * <li> * <p>If your event selector includes management events.</p> * </li> * <li> * <p>If your event selector includes data events, the resources on which you are logging data * events.</p> * </li> * </ul> * <p>For more information, see <a href="https://docs.aws.amazon.com/awscloudtrail/latest/userguide/logging-management-and-data-events-with-cloudtrail.html">Logging Data and Management Events for Trails * </a> in the <i>CloudTrail User Guide</i>.</p> */ public getEventSelectors( args: GetEventSelectorsCommandInput, options?: __HttpHandlerOptions ): Promise<GetEventSelectorsCommandOutput>; public getEventSelectors( args: GetEventSelectorsCommandInput, cb: (err: any, data?: GetEventSelectorsCommandOutput) => void ): void; public getEventSelectors( args: GetEventSelectorsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetEventSelectorsCommandOutput) => void ): void; public getEventSelectors( args: GetEventSelectorsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetEventSelectorsCommandOutput) => void), cb?: (err: any, data?: GetEventSelectorsCommandOutput) => void ): Promise<GetEventSelectorsCommandOutput> | void { const command = new GetEventSelectorsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Describes the settings for the Insights event selectors that you configured for your trail. <code>GetInsightSelectors</code> shows * if CloudTrail Insights event logging is enabled on the trail, and if it is, which insight types are enabled. * If you run <code>GetInsightSelectors</code> on a trail that does not have Insights events enabled, the operation throws the exception * <code>InsightNotEnabledException</code> * </p> * <p>For more information, see <a href="https://docs.aws.amazon.com/awscloudtrail/latest/userguide/logging-insights-events-with-cloudtrail.html">Logging CloudTrail Insights Events for Trails * </a> in the <i>CloudTrail User Guide</i>.</p> */ public getInsightSelectors( args: GetInsightSelectorsCommandInput, options?: __HttpHandlerOptions ): Promise<GetInsightSelectorsCommandOutput>; public getInsightSelectors( args: GetInsightSelectorsCommandInput, cb: (err: any, data?: GetInsightSelectorsCommandOutput) => void ): void; public getInsightSelectors( args: GetInsightSelectorsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetInsightSelectorsCommandOutput) => void ): void; public getInsightSelectors( args: GetInsightSelectorsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetInsightSelectorsCommandOutput) => void), cb?: (err: any, data?: GetInsightSelectorsCommandOutput) => void ): Promise<GetInsightSelectorsCommandOutput> | void { const command = new GetInsightSelectorsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns settings information for a specified trail.</p> */ public getTrail(args: GetTrailCommandInput, options?: __HttpHandlerOptions): Promise<GetTrailCommandOutput>; public getTrail(args: GetTrailCommandInput, cb: (err: any, data?: GetTrailCommandOutput) => void): void; public getTrail( args: GetTrailCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetTrailCommandOutput) => void ): void; public getTrail( args: GetTrailCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetTrailCommandOutput) => void), cb?: (err: any, data?: GetTrailCommandOutput) => void ): Promise<GetTrailCommandOutput> | void { const command = new GetTrailCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns a JSON-formatted list of information about the specified trail. Fields include information on delivery errors, Amazon SNS and Amazon S3 errors, and start and stop logging times for each trail. This operation returns trail status from a single region. To return trail status from all regions, you must call the operation on each region.</p> */ public getTrailStatus( args: GetTrailStatusCommandInput, options?: __HttpHandlerOptions ): Promise<GetTrailStatusCommandOutput>; public getTrailStatus( args: GetTrailStatusCommandInput, cb: (err: any, data?: GetTrailStatusCommandOutput) => void ): void; public getTrailStatus( args: GetTrailStatusCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: GetTrailStatusCommandOutput) => void ): void; public getTrailStatus( args: GetTrailStatusCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: GetTrailStatusCommandOutput) => void), cb?: (err: any, data?: GetTrailStatusCommandOutput) => void ): Promise<GetTrailStatusCommandOutput> | void { const command = new GetTrailStatusCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Returns all public keys whose private keys were used to sign the digest files within the specified time range. The public key is needed to validate digest files that were signed with its corresponding private key.</p> * <note> * <p>CloudTrail uses different private and public key pairs per region. Each digest file is signed with a private key * unique to its region. When you validate a digest file from a specific region, you must look in the same region for its * corresponding public key.</p> * </note> */ public listPublicKeys( args: ListPublicKeysCommandInput, options?: __HttpHandlerOptions ): Promise<ListPublicKeysCommandOutput>; public listPublicKeys( args: ListPublicKeysCommandInput, cb: (err: any, data?: ListPublicKeysCommandOutput) => void ): void; public listPublicKeys( args: ListPublicKeysCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListPublicKeysCommandOutput) => void ): void; public listPublicKeys( args: ListPublicKeysCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListPublicKeysCommandOutput) => void), cb?: (err: any, data?: ListPublicKeysCommandOutput) => void ): Promise<ListPublicKeysCommandOutput> | void { const command = new ListPublicKeysCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists the tags for the trail in the current region.</p> */ public listTags(args: ListTagsCommandInput, options?: __HttpHandlerOptions): Promise<ListTagsCommandOutput>; public listTags(args: ListTagsCommandInput, cb: (err: any, data?: ListTagsCommandOutput) => void): void; public listTags( args: ListTagsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListTagsCommandOutput) => void ): void; public listTags( args: ListTagsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListTagsCommandOutput) => void), cb?: (err: any, data?: ListTagsCommandOutput) => void ): Promise<ListTagsCommandOutput> | void { const command = new ListTagsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lists trails that are in the current account.</p> */ public listTrails(args: ListTrailsCommandInput, options?: __HttpHandlerOptions): Promise<ListTrailsCommandOutput>; public listTrails(args: ListTrailsCommandInput, cb: (err: any, data?: ListTrailsCommandOutput) => void): void; public listTrails( args: ListTrailsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: ListTrailsCommandOutput) => void ): void; public listTrails( args: ListTrailsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: ListTrailsCommandOutput) => void), cb?: (err: any, data?: ListTrailsCommandOutput) => void ): Promise<ListTrailsCommandOutput> | void { const command = new ListTrailsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Looks up <a href="https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-concepts.html#cloudtrail-concepts-management-events">management events</a> or * <a href="https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-concepts.html#cloudtrail-concepts-insights-events">CloudTrail Insights events</a> that are captured by CloudTrail. * You can look up events that occurred in a region within the last 90 days. Lookup supports the following attributes for management events:</p> * <ul> * <li> * <p>Amazon Web Services access key</p> * </li> * <li> * <p>Event ID</p> * </li> * <li> * <p>Event name</p> * </li> * <li> * <p>Event source</p> * </li> * <li> * <p>Read only</p> * </li> * <li> * <p>Resource name</p> * </li> * <li> * <p>Resource type</p> * </li> * <li> * <p>User name</p> * </li> * </ul> * <p>Lookup supports the following attributes for Insights events:</p> * <ul> * <li> * <p>Event ID</p> * </li> * <li> * <p>Event name</p> * </li> * <li> * <p>Event source</p> * </li> * </ul> * <p>All attributes are optional. The default number of results returned is 50, with a * maximum of 50 possible. The response includes a token that you can use to get the next page * of results.</p> * <important> * <p>The rate of lookup requests is limited to two per second, per account, per region. If this * limit is exceeded, a throttling error occurs.</p> * </important> */ public lookupEvents( args: LookupEventsCommandInput, options?: __HttpHandlerOptions ): Promise<LookupEventsCommandOutput>; public lookupEvents(args: LookupEventsCommandInput, cb: (err: any, data?: LookupEventsCommandOutput) => void): void; public lookupEvents( args: LookupEventsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: LookupEventsCommandOutput) => void ): void; public lookupEvents( args: LookupEventsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: LookupEventsCommandOutput) => void), cb?: (err: any, data?: LookupEventsCommandOutput) => void ): Promise<LookupEventsCommandOutput> | void { const command = new LookupEventsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Configures an event selector or advanced event selectors for your trail. * Use event selectors or advanced event selectors to specify management and data event settings for your trail. By * default, trails created without specific event selectors are configured to log all read and * write management events, and no data events.</p> * <p>When an event occurs in your account, CloudTrail * evaluates the event selectors or advanced event selectors in all trails. For each trail, if the event matches * any event selector, the trail processes and logs the event. If the event doesn't match any event * selector, the trail doesn't log the event.</p> * <p>Example</p> * <ol> * <li> * <p>You create an event selector for a trail and specify that you want * write-only events.</p> * </li> * <li> * <p>The EC2 <code>GetConsoleOutput</code> and <code>RunInstances</code> API * operations occur in your account.</p> * </li> * <li> * <p>CloudTrail evaluates whether the events match your event * selectors.</p> * </li> * <li> * <p>The <code>RunInstances</code> is a write-only event and it matches your * event selector. The trail logs the event.</p> * </li> * <li> * <p>The <code>GetConsoleOutput</code> is a read-only event that doesn't * match your event selector. The trail doesn't log the event. * </p> * </li> * </ol> * <p>The <code>PutEventSelectors</code> operation must be called from the region in which * the trail was created; otherwise, an <code>InvalidHomeRegionException</code> exception is * thrown.</p> * <p>You can configure up to five event selectors for each trail. For more information, see <a href="https://docs.aws.amazon.com/awscloudtrail/latest/userguide/logging-management-and-data-events-with-cloudtrail.html">Logging data and management events for trails * </a> and <a href="https://docs.aws.amazon.com/awscloudtrail/latest/userguide/WhatIsCloudTrail-Limits.html">Quotas in CloudTrail</a> * in the <i>CloudTrail User Guide</i>.</p> * <p>You can add advanced event selectors, and conditions for your advanced * event selectors, up to a maximum of 500 values for all conditions and selectors on a trail. * You can use either <code>AdvancedEventSelectors</code> or <code>EventSelectors</code>, but not both. If you apply <code>AdvancedEventSelectors</code> * to a trail, any existing <code>EventSelectors</code> are overwritten. For more information about * advanced event selectors, see * <a href="https://docs.aws.amazon.com/awscloudtrail/latest/userguide/logging-data-events-with-cloudtrail.html">Logging * data events for trails</a> in the <i>CloudTrail User Guide</i>.</p> */ public putEventSelectors( args: PutEventSelectorsCommandInput, options?: __HttpHandlerOptions ): Promise<PutEventSelectorsCommandOutput>; public putEventSelectors( args: PutEventSelectorsCommandInput, cb: (err: any, data?: PutEventSelectorsCommandOutput) => void ): void; public putEventSelectors( args: PutEventSelectorsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: PutEventSelectorsCommandOutput) => void ): void; public putEventSelectors( args: PutEventSelectorsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PutEventSelectorsCommandOutput) => void), cb?: (err: any, data?: PutEventSelectorsCommandOutput) => void ): Promise<PutEventSelectorsCommandOutput> | void { const command = new PutEventSelectorsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Lets you enable Insights event logging by specifying the Insights * selectors that you want to enable on an existing trail. You also use * <code>PutInsightSelectors</code> to turn off Insights event logging, by passing an empty list of insight types. * The valid Insights event type in this release is <code>ApiCallRateInsight</code>.</p> */ public putInsightSelectors( args: PutInsightSelectorsCommandInput, options?: __HttpHandlerOptions ): Promise<PutInsightSelectorsCommandOutput>; public putInsightSelectors( args: PutInsightSelectorsCommandInput, cb: (err: any, data?: PutInsightSelectorsCommandOutput) => void ): void; public putInsightSelectors( args: PutInsightSelectorsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: PutInsightSelectorsCommandOutput) => void ): void; public putInsightSelectors( args: PutInsightSelectorsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: PutInsightSelectorsCommandOutput) => void), cb?: (err: any, data?: PutInsightSelectorsCommandOutput) => void ): Promise<PutInsightSelectorsCommandOutput> | void { const command = new PutInsightSelectorsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Removes the specified tags from a trail.</p> */ public removeTags(args: RemoveTagsCommandInput, options?: __HttpHandlerOptions): Promise<RemoveTagsCommandOutput>; public removeTags(args: RemoveTagsCommandInput, cb: (err: any, data?: RemoveTagsCommandOutput) => void): void; public removeTags( args: RemoveTagsCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: RemoveTagsCommandOutput) => void ): void; public removeTags( args: RemoveTagsCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: RemoveTagsCommandOutput) => void), cb?: (err: any, data?: RemoveTagsCommandOutput) => void ): Promise<RemoveTagsCommandOutput> | void { const command = new RemoveTagsCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Starts the recording of Amazon Web Services API calls and log file delivery for a trail. For a trail that is enabled in all regions, this operation must be called from the region in which the trail was created. This operation cannot be called on the shadow trails (replicated trails in other regions) of a trail that is enabled in all regions.</p> */ public startLogging( args: StartLoggingCommandInput, options?: __HttpHandlerOptions ): Promise<StartLoggingCommandOutput>; public startLogging(args: StartLoggingCommandInput, cb: (err: any, data?: StartLoggingCommandOutput) => void): void; public startLogging( args: StartLoggingCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: StartLoggingCommandOutput) => void ): void; public startLogging( args: StartLoggingCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: StartLoggingCommandOutput) => void), cb?: (err: any, data?: StartLoggingCommandOutput) => void ): Promise<StartLoggingCommandOutput> | void { const command = new StartLoggingCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Suspends the recording of Amazon Web Services API calls and log file delivery for the specified trail. * Under most circumstances, there is no need to use this action. You can update a trail * without stopping it first. This action is the only way to stop recording. For a trail * enabled in all regions, this operation must be called from the region in which the trail * was created, or an <code>InvalidHomeRegionException</code> will occur. This operation * cannot be called on the shadow trails (replicated trails in other regions) of a trail * enabled in all regions.</p> */ public stopLogging(args: StopLoggingCommandInput, options?: __HttpHandlerOptions): Promise<StopLoggingCommandOutput>; public stopLogging(args: StopLoggingCommandInput, cb: (err: any, data?: StopLoggingCommandOutput) => void): void; public stopLogging( args: StopLoggingCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: StopLoggingCommandOutput) => void ): void; public stopLogging( args: StopLoggingCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: StopLoggingCommandOutput) => void), cb?: (err: any, data?: StopLoggingCommandOutput) => void ): Promise<StopLoggingCommandOutput> | void { const command = new StopLoggingCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } /** * <p>Updates trail settings that control what events you are logging, and how to handle log files. Changes to a trail do not require * stopping the CloudTrail service. Use this action to designate an existing bucket for log * delivery. If the existing bucket has previously been a target for CloudTrail log files, * an IAM policy exists for the bucket. <code>UpdateTrail</code> must be called from the * region in which the trail was created; otherwise, an * <code>InvalidHomeRegionException</code> is thrown.</p> */ public updateTrail(args: UpdateTrailCommandInput, options?: __HttpHandlerOptions): Promise<UpdateTrailCommandOutput>; public updateTrail(args: UpdateTrailCommandInput, cb: (err: any, data?: UpdateTrailCommandOutput) => void): void; public updateTrail( args: UpdateTrailCommandInput, options: __HttpHandlerOptions, cb: (err: any, data?: UpdateTrailCommandOutput) => void ): void; public updateTrail( args: UpdateTrailCommandInput, optionsOrCb?: __HttpHandlerOptions | ((err: any, data?: UpdateTrailCommandOutput) => void), cb?: (err: any, data?: UpdateTrailCommandOutput) => void ): Promise<UpdateTrailCommandOutput> | void { const command = new UpdateTrailCommand(args); if (typeof optionsOrCb === "function") { this.send(command, optionsOrCb); } else if (typeof cb === "function") { if (typeof optionsOrCb !== "object") throw new Error(`Expect http options but get ${typeof optionsOrCb}`); this.send(command, optionsOrCb || {}, cb); } else { return this.send(command, optionsOrCb); } } }
the_stack
import { expect } from "chai"; import * as faker from "faker"; import { Guid, Id64 } from "@itwin/core-bentley"; import { IModelConnection, SnapshotConnection } from "@itwin/core-frontend"; import { ChildNodeSpecificationTypes, ContentSpecificationTypes, KeySet, Ruleset, RuleTypes } from "@itwin/presentation-common"; import { createRandomId } from "@itwin/presentation-common/lib/cjs/test"; import { Presentation, PresentationManager, RulesetVariablesManager } from "@itwin/presentation-frontend"; import { initialize, resetBackend, terminate } from "../IntegrationTests"; const RULESET: Ruleset = { id: "ruleset vars test", rules: [{ ruleType: RuleTypes.RootNodes, specifications: [{ specType: ChildNodeSpecificationTypes.CustomNode, type: "root", label: "root", }], }, { ruleType: RuleTypes.LabelOverride, condition: "ThisNode.Type = \"root\"", label: "GetVariableStringValue(\"variable_id\")", }], }; describe("Ruleset Variables", async () => { let variables: RulesetVariablesManager; beforeEach(async () => { await initialize(); variables = Presentation.presentation.vars(RULESET.id); }); afterEach(async () => { await terminate(); }); it("adds and modifies string variable", async () => { const value = faker.random.word(); const variableId = faker.random.word(); await variables.setString(variableId, value); const actualValue = await variables.getString(variableId); expect(actualValue).to.equal(value); }); it("adds and modifies boolean variable", async () => { let value = faker.random.boolean(); const variableId = faker.random.word(); await variables.setBool(variableId, value); let actualValue = await variables.getBool(variableId); expect(actualValue).to.equal(value); value = !value; await variables.setBool(variableId, value); actualValue = await variables.getBool(variableId); expect(actualValue).to.equal(value); }); it("adds and modifies integer variable", async () => { let value = faker.random.number(); const variableId = faker.random.word(); await variables.setInt(variableId, value); let actualValue = await variables.getInt(variableId); expect(actualValue).to.equal(value); value = faker.random.number(); await variables.setInt(variableId, value); actualValue = await variables.getInt(variableId); expect(actualValue).to.equal(value); }); it("adds and modifies int[] variable", async () => { let valueArray = [faker.random.number(), faker.random.number(), faker.random.number()]; const variableId = faker.random.word(); await variables.setInts(variableId, valueArray); let actualValueArray = await variables.getInts(variableId); expect(actualValueArray).to.deep.equal(valueArray); valueArray = [faker.random.number(), faker.random.number(), faker.random.number(), faker.random.number()]; await variables.setInts(variableId, valueArray); actualValueArray = await variables.getInts(variableId); expect(actualValueArray).to.deep.equal(valueArray); }); it("adds and modifies Id64 variable", async () => { let value = createRandomId(); const variableId = faker.random.word(); await variables.setId64(variableId, value); let actualValue = await variables.getId64(variableId); expect(actualValue).to.deep.equal(value); value = createRandomId(); await variables.setId64(variableId, value); actualValue = await variables.getId64(variableId); expect(actualValue).to.deep.equal(value); }); it("adds and modifies Id64[] variable", async () => { let valueArray = [ createRandomId(), createRandomId(), createRandomId(), ]; const variableId = faker.random.word(); await variables.setId64s(variableId, valueArray); let actualValueArray = await variables.getId64s(variableId); expect(actualValueArray).to.deep.equal(valueArray); valueArray = [ createRandomId(), createRandomId(), createRandomId(), createRandomId(), ]; await variables.setId64s(variableId, valueArray); actualValueArray = await variables.getId64s(variableId); expect(actualValueArray).to.deep.equal(valueArray); }); it("accessing int[] variable with different types", async () => { const valueArray = [faker.random.number(), faker.random.number(), faker.random.number(), faker.random.number()]; const variableId = faker.random.word(); await variables.setInts(variableId, valueArray); const boolValue = await variables.getBool(variableId); expect(boolValue).to.be.false; const id64ArrayValue = await variables.getId64s(variableId); expect(id64ArrayValue.length).to.equal(valueArray.length); for (const value of valueArray) { const id = Id64.fromLocalAndBriefcaseIds(value, 0); expect(id64ArrayValue.find((x) => x === (id))).to.not.be.equal(undefined); } const id64Value = await variables.getId64(variableId); expect(Id64.isValid(id64Value)).to.be.false; const intValue = await variables.getInt(variableId); expect(intValue).to.equal(0); const stringValue = await variables.getString(variableId); expect(stringValue).to.equal(""); }); it("accessing int variable with different types", async () => { const value = faker.random.number(); const variableId = faker.random.word(); await variables.setInt(variableId, value); const boolValue = await variables.getBool(variableId); expect(boolValue).to.eq(value !== 0); const id64ArrayValue = await variables.getId64s(variableId); expect(id64ArrayValue.length).to.equal(0); const id64Value = await variables.getId64(variableId); expect(id64Value).to.deep.eq(Id64.fromLocalAndBriefcaseIds(value, 0)); const intArrayValue = await variables.getInts(variableId); expect(intArrayValue.length).to.equal(0); const stringValue = await variables.getString(variableId); expect(stringValue).to.equal(""); }); it("accessing bool variable with different types", async () => { const value = faker.random.boolean(); const variableId = faker.random.word(); await variables.setBool(variableId, value); const id64ArrayValue = await variables.getId64s(variableId); expect(id64ArrayValue.length).to.equal(0); const id64Value = await variables.getId64(variableId); expect(id64Value).to.deep.eq(Id64.fromLocalAndBriefcaseIds(value ? 1 : 0, 0)); const intArrayValue = await variables.getInts(variableId); expect(intArrayValue.length).to.equal(0); const intValue = await variables.getInt(variableId); expect(intValue).to.equal(value ? 1 : 0); const stringValue = await variables.getString(variableId); expect(stringValue).to.equal(""); }); it("accessing string variable with different types", async () => { const value = faker.random.word(); const variableId = faker.random.word(); await variables.setString(variableId, value); const id64ArrayValue = await variables.getId64s(variableId); expect(id64ArrayValue.length).to.equal(0); const id64Value = await variables.getId64(variableId); expect(Id64.isValid(id64Value)).to.be.false; const intArrayValue = await variables.getInts(variableId); expect(intArrayValue.length).to.equal(0); const intValue = await variables.getInt(variableId); expect(intValue).to.equal(0); const boolValue = await variables.getBool(variableId); expect(boolValue).to.equal(false); }); it("accessing Id64 variable with different types", async () => { const value = createRandomId(); const variableId = faker.random.word(); await variables.setId64(variableId, value); const id64ArrayValue = await variables.getId64s(variableId); expect(id64ArrayValue.length).to.equal(0); const intArrayValue = await variables.getInts(variableId); expect(intArrayValue.length).to.equal(0); const stringValue = await variables.getString(variableId); expect(stringValue).to.equal(""); const boolValue = await variables.getBool(variableId); expect(boolValue).to.eq(Id64.isValid(value)); }); it("accessing Id64[] variable with different types", async () => { const valueArray = [ createRandomId(), createRandomId(), createRandomId(), createRandomId(), ]; const variableId = faker.random.word(); await variables.setId64s(variableId, valueArray); const boolValue = await variables.getBool(variableId); expect(boolValue).to.be.false; const intArrayValue = await variables.getInts(variableId); expect(intArrayValue.length).to.equal(valueArray.length); const id64Value = await variables.getId64(variableId); expect(Id64.isValid(id64Value)).to.be.false; const intValue = await variables.getInt(variableId); expect(intValue).to.equal(0); const stringValue = await variables.getString(variableId); expect(stringValue).to.equal(""); }); describe("Multiple frontends for one backend", async () => { let imodel: IModelConnection; let frontends: PresentationManager[]; beforeEach(async () => { const testIModelName = "assets/datasets/Properties_60InstancesWithUrl2.ibim"; imodel = await SnapshotConnection.openFile(testIModelName); frontends = [0, 1].map(() => PresentationManager.create()); }); afterEach(async () => { await imodel.close(); frontends.forEach((f) => f.dispose()); }); it("handles multiple simultaneous requests from different frontends with ruleset variables", async () => { for (let i = 0; i < 100; ++i) { frontends.forEach(async (f, fi) => f.vars(RULESET.id).setString("variable_id", `${i}_${fi}`)); const nodes = await Promise.all(frontends.map(async (f) => f.getNodes({ imodel, rulesetOrId: RULESET }))); frontends.forEach((_f, fi) => { expect(nodes[fi][0].label.displayValue).to.eq(`${i}_${fi}`); }); } }); }); describe("Multiple backends for one frontend", async () => { let imodel: IModelConnection; let frontend: PresentationManager; beforeEach(async () => { const testIModelName: string = "assets/datasets/Properties_60InstancesWithUrl2.ibim"; imodel = await SnapshotConnection.openFile(testIModelName); expect(imodel).is.not.null; frontend = PresentationManager.create(); }); afterEach(async () => { await imodel.close(); frontend.dispose(); }); it("can use the same frontend-registered ruleset variables after backend is reset", async () => { const vars = frontend.vars("AnyRulesetId"); const var1: [string, string] = [faker.random.uuid(), faker.random.words()]; const var2: [string, number] = [faker.random.uuid(), faker.random.number()]; await vars.setString(var1[0], var1[1]); expect(await vars.getString(var1[0])).to.eq(var1[1]); resetBackend(); expect(await vars.getString(var1[0])).to.eq(var1[1]); await vars.setInt(var2[0], var2[1]); expect(await vars.getInt(var2[0])).to.eq(var2[1]); resetBackend(); expect(await vars.getString(var1[0])).to.eq(var1[1]); expect(await vars.getInt(var2[0])).to.eq(var2[1]); }); }); describe("Using variables in rules", () => { let imodel: IModelConnection; beforeEach(async () => { imodel = await SnapshotConnection.openFile("assets/datasets/Properties_60InstancesWithUrl2.ibim"); }); afterEach(async () => { await imodel.close(); }); it("can specify lots of ids with Id64[] overload", async () => { const ruleset: Ruleset = { id: Guid.createValue(), rules: [{ ruleType: RuleTypes.Content, specifications: [{ specType: ContentSpecificationTypes.ContentInstancesOfSpecificClasses, classes: { schemaName: "PCJ_TestSchema", classNames: ["TestClass"] }, instanceFilter: `GetVariableIntValues("ids").AnyMatch(id => id = this.ECInstanceId)`, }], }], }; let content = await Presentation.presentation.getContent({ imodel, rulesetOrId: ruleset, keys: new KeySet(), descriptor: {} }); expect(content!.contentSet.length).to.eq(0); // https://www.sqlite.org/limits.html#max_variable_number const maxNumberOfSupportedBindParams = 32766; const largestECInstanceIdInTestDataset = 117; const ids = [...Array(maxNumberOfSupportedBindParams).keys()].map((key) => Id64.fromUint32Pair(key + largestECInstanceIdInTestDataset + 1, 0)); ids.push("0x61"); await Presentation.presentation.vars(ruleset.id).setId64s("ids", ids); content = await Presentation.presentation.getContent({ imodel, rulesetOrId: ruleset, keys: new KeySet(), descriptor: {} }); expect(content!.contentSet.length).to.eq(1); expect(content!.contentSet[0].primaryKeys[0]).to.deep.eq({ className: "PCJ_TestSchema:TestClass", id: "0x61" }); }); }); });
the_stack
import { bufferToHex, ensureLeading0x, hexToBuffer, NULL_ADDRESS, trimLeading0x, } from '@celo/base/lib/address' import { concurrentMap } from '@celo/base/lib/async' import { zeroRange, zip } from '@celo/base/lib/collections' import { Address, CeloTxPending, toTransactionObject } from '@celo/connect' import { fromFixed } from '@celo/utils/lib/fixidity' import BigNumber from 'bignumber.js' import { Governance } from '../generated/Governance' import { BaseWrapper, bufferToSolidityBytes, identity, proxyCall, proxySend, secondsToDurationString, solidityBytesToString, stringIdentity, tupleParser, unixSecondsTimestampToDateString, valueToBigNumber, valueToInt, valueToString, } from './BaseWrapper' export enum ProposalStage { None = 'None', Queued = 'Queued', Approval = 'Approval', Referendum = 'Referendum', Execution = 'Execution', Expiration = 'Expiration', } type StageDurations<V> = { [Stage in ProposalStage]: V } type DequeuedStageDurations = Pick< StageDurations<BigNumber>, ProposalStage.Approval | ProposalStage.Referendum | ProposalStage.Execution > export interface ParticipationParameters { baseline: BigNumber baselineFloor: BigNumber baselineUpdateFactor: BigNumber baselineQuorumFactor: BigNumber } export interface GovernanceConfig { concurrentProposals: BigNumber dequeueFrequency: BigNumber // seconds minDeposit: BigNumber queueExpiry: BigNumber stageDurations: DequeuedStageDurations participationParameters: ParticipationParameters } export interface ProposalMetadata { proposer: Address deposit: BigNumber timestamp: BigNumber transactionCount: number descriptionURL: string } export type ProposalParams = Parameters<Governance['methods']['propose']> export type ProposalTransaction = Pick<CeloTxPending, 'to' | 'input' | 'value'> export type Proposal = ProposalTransaction[] export const proposalToParams = (proposal: Proposal, descriptionURL: string): ProposalParams => { const data = proposal.map((tx) => hexToBuffer(tx.input)) return [ proposal.map((tx) => tx.value), proposal.map((tx) => tx.to!), bufferToSolidityBytes(Buffer.concat(data)), data.map((inp) => inp.length), descriptionURL, ] } interface ApprovalStatus { completion: string confirmations: string[] approvers: string[] } export interface ProposalRecord { metadata: ProposalMetadata proposal: Proposal stage: ProposalStage approved: boolean passed: boolean upvotes?: BigNumber approvals?: ApprovalStatus votes?: Votes } export interface UpvoteRecord { proposalID: BigNumber upvotes: BigNumber } export enum VoteValue { None = 'NONE', Abstain = 'Abstain', No = 'No', Yes = 'Yes', } export interface Votes { [VoteValue.Abstain]: BigNumber [VoteValue.No]: BigNumber [VoteValue.Yes]: BigNumber } export type HotfixParams = Parameters<Governance['methods']['executeHotfix']> export const hotfixToParams = (proposal: Proposal, salt: Buffer): HotfixParams => { const p = proposalToParams(proposal, '') // no description URL for hotfixes return [p[0], p[1], p[2], p[3], bufferToHex(salt)] } export interface HotfixRecord { approved: boolean executed: boolean preparedEpoch: BigNumber } export interface VoteRecord { proposalID: BigNumber votes: BigNumber value: VoteValue } export interface Voter { upvote: UpvoteRecord votes: VoteRecord[] refundedDeposits: BigNumber } const ZERO_BN = new BigNumber(0) /** * Contract managing voting for governance proposals. */ export class GovernanceWrapper extends BaseWrapper<Governance> { /** * Querying number of possible concurrent proposals. * @returns Current number of possible concurrent proposals. */ concurrentProposals = proxyCall( this.contract.methods.concurrentProposals, undefined, valueToBigNumber ) /** * Query time of last proposal dequeue * @returns Time of last dequeue */ lastDequeue = proxyCall(this.contract.methods.lastDequeue, undefined, valueToBigNumber) /** * Query proposal dequeue frequency. * @returns Current proposal dequeue frequency in seconds. */ dequeueFrequency = proxyCall(this.contract.methods.dequeueFrequency, undefined, valueToBigNumber) /** * Query minimum deposit required to make a proposal. * @returns Current minimum deposit. */ minDeposit = proxyCall(this.contract.methods.minDeposit, undefined, valueToBigNumber) /** * Query queue expiry parameter. * @return The number of seconds a proposal can stay in the queue before expiring. */ queueExpiry = proxyCall(this.contract.methods.queueExpiry, undefined, valueToBigNumber) /** * Query durations of different stages in proposal lifecycle. * @returns Durations for approval, referendum and execution stages in seconds. */ async stageDurations(): Promise<DequeuedStageDurations> { const res = await this.contract.methods.stageDurations().call() return { [ProposalStage.Approval]: valueToBigNumber(res[0]), [ProposalStage.Referendum]: valueToBigNumber(res[1]), [ProposalStage.Execution]: valueToBigNumber(res[2]), } } /** * Returns the required ratio of yes:no votes needed to exceed in order to pass the proposal transaction. * @param tx Transaction to determine the constitution for running. */ async getTransactionConstitution(tx: ProposalTransaction): Promise<BigNumber> { // Extract the leading four bytes of the call data, which specifies the function. const callSignature = ensureLeading0x(trimLeading0x(tx.input).slice(0, 8)) const value = await this.contract.methods .getConstitution(tx.to ?? NULL_ADDRESS, callSignature) .call() return fromFixed(new BigNumber(value)) } /** * Returns the required ratio of yes:no votes needed to exceed in order to pass the proposal. * @param proposal Proposal to determine the constitution for running. */ async getConstitution(proposal: Proposal): Promise<BigNumber> { let constitution = new BigNumber(0) for (const tx of proposal) { constitution = BigNumber.max(await this.getTransactionConstitution(tx), constitution) } return constitution } /** * Returns the participation parameters. * @returns The participation parameters. */ async getParticipationParameters(): Promise<ParticipationParameters> { const res = await this.contract.methods.getParticipationParameters().call() return { baseline: fromFixed(new BigNumber(res[0])), baselineFloor: fromFixed(new BigNumber(res[1])), baselineUpdateFactor: fromFixed(new BigNumber(res[2])), baselineQuorumFactor: fromFixed(new BigNumber(res[3])), } } // simulates proposal.getSupportWithQuorumPadding async getSupport(proposalID: BigNumber.Value) { const participation = await this.getParticipationParameters() const quorum = participation.baseline.times(participation.baselineQuorumFactor) const votes = await this.getVotes(proposalID) const total = votes.Yes.plus(votes.No).plus(votes.Abstain) const lockedGold = await this.kit.contracts.getLockedGold() // NOTE: this networkWeight is not as governance calculates it, // but we don't have access to proposal.networkWeight const networkWeight = await lockedGold.getTotalLockedGold() const required = networkWeight.times(quorum) const support = votes.Yes.div(votes.Yes.plus(votes.No)) return { support, required, total, } } /** * Returns whether or not a particular account is voting on proposals. * @param account The address of the account. * @returns Whether or not the account is voting on proposals. */ isVoting: (account: string) => Promise<boolean> = proxyCall(this.contract.methods.isVoting) /** * Returns current configuration parameters. */ async getConfig(): Promise<GovernanceConfig> { const res = await Promise.all([ this.concurrentProposals(), this.dequeueFrequency(), this.minDeposit(), this.queueExpiry(), this.stageDurations(), this.getParticipationParameters(), ]) return { concurrentProposals: res[0], dequeueFrequency: res[1], minDeposit: res[2], queueExpiry: res[3], stageDurations: res[4], participationParameters: res[5], } } /** * @dev Returns human readable configuration of the governance contract * @return GovernanceConfig object */ async getHumanReadableConfig() { const config = await this.getConfig() const stageDurations = { [ProposalStage.Approval]: secondsToDurationString( config.stageDurations[ProposalStage.Approval] ), [ProposalStage.Referendum]: secondsToDurationString( config.stageDurations[ProposalStage.Referendum] ), [ProposalStage.Execution]: secondsToDurationString( config.stageDurations[ProposalStage.Execution] ), } return { ...config, dequeueFrequency: secondsToDurationString(config.dequeueFrequency), queueExpiry: secondsToDurationString(config.queueExpiry), stageDurations, } } /** * Returns the metadata associated with a given proposal. * @param proposalID Governance proposal UUID */ getProposalMetadata: (proposalID: BigNumber.Value) => Promise<ProposalMetadata> = proxyCall( this.contract.methods.getProposal, tupleParser(valueToString), (res) => ({ proposer: res[0], deposit: valueToBigNumber(res[1]), timestamp: valueToBigNumber(res[2]), transactionCount: valueToInt(res[3]), descriptionURL: res[4], }) ) /** * Returns the human readable metadata associated with a given proposal. * @param proposalID Governance proposal UUID */ async getHumanReadableProposalMetadata(proposalID: BigNumber.Value) { const meta = await this.getProposalMetadata(proposalID) return { ...meta, timestamp: unixSecondsTimestampToDateString(meta.timestamp), } } /** * Returns the transaction at the given index associated with a given proposal. * @param proposalID Governance proposal UUID * @param txIndex Transaction index */ getProposalTransaction: ( proposalID: BigNumber.Value, txIndex: number ) => Promise<ProposalTransaction> = proxyCall( this.contract.methods.getProposalTransaction, tupleParser(valueToString, valueToString), (res) => ({ value: res[0], to: res[1], input: solidityBytesToString(res[2]), }) ) /** * Returns whether a given proposal is approved. * @param proposalID Governance proposal UUID */ isApproved: (proposalID: BigNumber.Value) => Promise<boolean> = proxyCall( this.contract.methods.isApproved, tupleParser(valueToString) ) /** * Returns whether a dequeued proposal is expired. * @param proposalID Governance proposal UUID */ isDequeuedProposalExpired: (proposalID: BigNumber.Value) => Promise<boolean> = proxyCall( this.contract.methods.isDequeuedProposalExpired, tupleParser(valueToString) ) /** * Returns whether a dequeued proposal is expired. * @param proposalID Governance proposal UUID */ isQueuedProposalExpired = proxyCall( this.contract.methods.isQueuedProposalExpired, tupleParser(valueToString) ) /** * Returns the approver address for proposals and hotfixes. */ getApprover = proxyCall(this.contract.methods.approver) /** * Returns the approver multisig contract for proposals and hotfixes. */ getApproverMultisig = () => this.getApprover().then((address) => this.kit.contracts.getMultiSig(address)) getProposalStage = async (proposalID: BigNumber.Value): Promise<ProposalStage> => { const queue = await this.getQueue() const existsInQueue = queue.find((u) => u.proposalID === proposalID) !== undefined if (existsInQueue) { const expired = await this.isQueuedProposalExpired(proposalID) return expired ? ProposalStage.Expiration : ProposalStage.Queued } const res = await this.contract.methods.getProposalStage(valueToString(proposalID)).call() return Object.keys(ProposalStage)[valueToInt(res)] as ProposalStage } async proposalSchedule(proposalID: BigNumber.Value): Promise<Partial<StageDurations<BigNumber>>> { const meta = await this.getProposalMetadata(proposalID) const stage = await this.getProposalStage(proposalID) if (stage === ProposalStage.Queued) { const queueExpiry = await this.queueExpiry() const queueExpiration = meta.timestamp.plus(queueExpiry) return { [ProposalStage.Queued]: meta.timestamp, [ProposalStage.Expiration]: queueExpiration, } } const durations = await this.stageDurations() const referendum = meta.timestamp.plus(durations.Approval) const execution = referendum.plus(durations.Referendum) const expiration = execution.plus(durations.Execution) return { [ProposalStage.Approval]: meta.timestamp, [ProposalStage.Referendum]: referendum, [ProposalStage.Execution]: execution, [ProposalStage.Expiration]: expiration, } } async humanReadableProposalSchedule(proposalID: BigNumber.Value) { const schedule = await this.proposalSchedule(proposalID) const dates: Partial<StageDurations<string>> = {} for (const stage of Object.keys(schedule) as Array<keyof StageDurations<any>>) { dates[stage] = unixSecondsTimestampToDateString(schedule[stage]!) } return dates } /** * Returns the proposal associated with a given id. * @param proposalID Governance proposal UUID */ async getProposal(proposalID: BigNumber.Value): Promise<Proposal> { const metadata = await this.getProposalMetadata(proposalID) const txIndices = zeroRange(metadata.transactionCount) return concurrentMap(4, txIndices, (idx) => this.getProposalTransaction(proposalID, idx)) } async getApprovalStatus(proposalID: BigNumber.Value): Promise<ApprovalStatus> { const multisig = await this.getApproverMultisig() const approveTx = await this.approve(proposalID) const multisigTxs = await multisig.getTransactionDataByContent(this.address, approveTx.txo) const confirmations = multisigTxs ? multisigTxs.confirmations : [] const approvers = await multisig.getOwners() return { completion: `${confirmations.length} / ${approvers.length}`, confirmations, approvers, } } /** * Returns the stage, metadata, upvotes, votes, and transactions associated with a given proposal. * @param proposalID Governance proposal UUID */ async getProposalRecord(proposalID: BigNumber.Value): Promise<ProposalRecord> { const metadata = await this.getProposalMetadata(proposalID) const proposal = await this.getProposal(proposalID) const stage = await this.getProposalStage(proposalID) const record: ProposalRecord = { proposal, metadata, stage, passed: false, approved: false, } if (stage === ProposalStage.Queued) { record.upvotes = await this.getUpvotes(proposalID) } else if (stage === ProposalStage.Approval) { record.approved = await this.isApproved(proposalID) record.approvals = await this.getApprovalStatus(proposalID) } else if (stage === ProposalStage.Referendum || stage === ProposalStage.Execution) { record.approved = true record.passed = await this.isProposalPassing(proposalID) record.votes = await this.getVotes(proposalID) } return record } /** * Returns whether a given proposal is passing relative to the constitution's threshold. * @param proposalID Governance proposal UUID */ isProposalPassing = proxyCall(this.contract.methods.isProposalPassing, tupleParser(valueToString)) /** * Withdraws refunded proposal deposits. */ withdraw = proxySend(this.kit, this.contract.methods.withdraw) /** * Submits a new governance proposal. * @param proposal Governance proposal * @param descriptionURL A URL where further information about the proposal can be viewed */ propose = proxySend(this.kit, this.contract.methods.propose, proposalToParams) /** * Returns whether a governance proposal exists with the given ID. * @param proposalID Governance proposal UUID */ proposalExists: (proposalID: BigNumber.Value) => Promise<boolean> = proxyCall( this.contract.methods.proposalExists, tupleParser(valueToString) ) /** * Returns the current upvoted governance proposal ID and applied vote weight (zeroes if none). * @param upvoter Address of upvoter */ getUpvoteRecord: (upvoter: Address) => Promise<UpvoteRecord> = proxyCall( this.contract.methods.getUpvoteRecord, tupleParser(identity), (o) => ({ proposalID: valueToBigNumber(o[0]), upvotes: valueToBigNumber(o[1]), }) ) async isUpvoting(upvoter: Address) { const upvote = await this.getUpvoteRecord(upvoter) return ( !upvote.proposalID.isZero() && (await this.isQueued(upvote.proposalID)) && !(await this.isQueuedProposalExpired(upvote.proposalID)) ) } /** * Returns the corresponding vote record * @param voter Address of voter * @param proposalID Governance proposal UUID */ async getVoteRecord(voter: Address, proposalID: BigNumber.Value): Promise<VoteRecord | null> { try { const proposalIndex = await this.getDequeueIndex(proposalID) const res = await this.contract.methods.getVoteRecord(voter, proposalIndex).call() return { proposalID: valueToBigNumber(res[0]), value: Object.keys(VoteValue)[valueToInt(res[1])] as VoteValue, votes: valueToBigNumber(res[2]), } } catch (_) { // The proposal ID may not be present in the dequeued list, or the voter may not have a vote // record for the proposal. return null } } /** * Returns whether a given proposal is queued. * @param proposalID Governance proposal UUID */ isQueued = proxyCall(this.contract.methods.isQueued, tupleParser(valueToString)) /** * Returns the value of proposal deposits that have been refunded. * @param proposer Governance proposer address. */ getRefundedDeposits = proxyCall( this.contract.methods.refundedDeposits, tupleParser(stringIdentity), valueToBigNumber ) /* * Returns the upvotes applied to a given proposal. * @param proposalID Governance proposal UUID */ getUpvotes = proxyCall( this.contract.methods.getUpvotes, tupleParser(valueToString), valueToBigNumber ) /** * Returns the yes, no, and abstain votes applied to a given proposal. * @param proposalID Governance proposal UUID */ getVotes = proxyCall( this.contract.methods.getVoteTotals, tupleParser(valueToString), (res): Votes => ({ [VoteValue.Yes]: valueToBigNumber(res[0]), [VoteValue.No]: valueToBigNumber(res[1]), [VoteValue.Abstain]: valueToBigNumber(res[2]), }) ) /** * Returns the proposal queue as list of upvote records. */ getQueue = proxyCall(this.contract.methods.getQueue, undefined, (arraysObject) => zip<string, string, UpvoteRecord>( (_id, _upvotes) => ({ proposalID: valueToBigNumber(_id), upvotes: valueToBigNumber(_upvotes), }), arraysObject[0], arraysObject[1] ) ) /** * Returns the (existing) proposal dequeue as list of proposal IDs. */ async getDequeue(filterZeroes = false) { const dequeue = await this.contract.methods.getDequeue().call() // filter non-zero as dequeued indices are reused and `deleteDequeuedProposal` zeroes const dequeueIds = dequeue.map(valueToBigNumber) return filterZeroes ? dequeueIds.filter((id) => !id.isZero()) : dequeueIds } /* * Returns the vote records for a given voter. */ async getVoteRecords(voter: Address): Promise<VoteRecord[]> { const dequeue = await this.getDequeue() const voteRecords = await Promise.all(dequeue.map((id) => this.getVoteRecord(voter, id))) return voteRecords.filter((record) => record != null) as VoteRecord[] } async isVotingReferendum(voter: Address) { const records = await this.getVoteRecords(voter) return records.length !== 0 } /* * Returns information pertaining to a voter in governance. */ async getVoter(account: Address): Promise<Voter> { const res = await Promise.all([ this.getUpvoteRecord(account), this.getVoteRecords(account), this.getRefundedDeposits(account), ]) return { upvote: res[0], votes: res[1], refundedDeposits: res[2], } } /** * Dequeues any queued proposals if `dequeueFrequency` seconds have elapsed since the last dequeue */ dequeueProposalsIfReady = proxySend(this.kit, this.contract.methods.dequeueProposalsIfReady) /** * Returns the number of votes that will be applied to a proposal for a given voter. * @param voter Address of voter */ async getVoteWeight(voter: Address) { const lockedGoldContract = await this.kit.contracts.getLockedGold() return lockedGoldContract.getAccountTotalLockedGold(voter) } private getIndex(id: BigNumber.Value, array: BigNumber[]) { const index = array.findIndex((bn) => bn.isEqualTo(id)) if (index === -1) { throw new Error(`ID ${id} not found in array ${array}`) } return index } private async getDequeueIndex(proposalID: BigNumber.Value, dequeue?: BigNumber[]) { if (!dequeue) { dequeue = await this.getDequeue() } return this.getIndex(proposalID, dequeue) } private async getQueueIndex(proposalID: BigNumber.Value, queue?: UpvoteRecord[]) { if (!queue) { queue = await this.getQueue() } return { index: this.getIndex( proposalID, queue.map((record) => record.proposalID) ), queue, } } private async lesserAndGreater(proposalID: BigNumber.Value, _queue?: UpvoteRecord[]) { const { index, queue } = await this.getQueueIndex(proposalID, _queue) return { lesserID: index === 0 ? ZERO_BN : queue[index - 1].proposalID, greaterID: index === queue.length - 1 ? ZERO_BN : queue[index + 1].proposalID, } } sortedQueue(queue: UpvoteRecord[]) { return queue.sort((a, b) => a.upvotes.comparedTo(b.upvotes)) } private async withUpvoteRevoked(upvoter: Address, _queue?: UpvoteRecord[]) { const upvoteRecord = await this.getUpvoteRecord(upvoter) const { index, queue } = await this.getQueueIndex(upvoteRecord.proposalID, _queue) queue[index].upvotes = queue[index].upvotes.minus(upvoteRecord.upvotes) return { queue: this.sortedQueue(queue), upvoteRecord, } } private async withUpvoteApplied( upvoter: Address, proposalID: BigNumber.Value, _queue?: UpvoteRecord[] ) { const { index, queue } = await this.getQueueIndex(proposalID, _queue) const weight = await this.getVoteWeight(upvoter) queue[index].upvotes = queue[index].upvotes.plus(weight) return this.sortedQueue(queue) } private async lesserAndGreaterAfterRevoke(upvoter: Address) { const { queue, upvoteRecord } = await this.withUpvoteRevoked(upvoter) return this.lesserAndGreater(upvoteRecord.proposalID, queue) } private async lesserAndGreaterAfterUpvote(upvoter: Address, proposalID: BigNumber.Value) { const upvoteRecord = await this.getUpvoteRecord(upvoter) const recordQueued = await this.isQueued(upvoteRecord.proposalID) // if existing upvote exists in queue, revoke it before applying new upvote const queue = recordQueued ? (await this.withUpvoteRevoked(upvoter)).queue : await this.getQueue() const upvoteQueue = await this.withUpvoteApplied(upvoter, proposalID, queue) return this.lesserAndGreater(proposalID, upvoteQueue) } /** * Applies provided upvoter's upvote to given proposal. * @param proposalID Governance proposal UUID * @param upvoter Address of upvoter */ async upvote(proposalID: BigNumber.Value, upvoter: Address) { const { lesserID, greaterID } = await this.lesserAndGreaterAfterUpvote(upvoter, proposalID) return toTransactionObject( this.kit.connection, this.contract.methods.upvote( valueToString(proposalID), valueToString(lesserID), valueToString(greaterID) ) ) } /** * Revokes provided upvoter's upvote. * @param upvoter Address of upvoter */ async revokeUpvote(upvoter: Address) { const { lesserID, greaterID } = await this.lesserAndGreaterAfterRevoke(upvoter) return toTransactionObject( this.kit.connection, this.contract.methods.revokeUpvote(valueToString(lesserID), valueToString(greaterID)) ) } /** * Approves given proposal, allowing it to later move to `referendum`. * @param proposalID Governance proposal UUID * @notice Only the `approver` address will succeed in sending this transaction */ async approve(proposalID: BigNumber.Value) { const proposalIndex = await this.getDequeueIndex(proposalID) return toTransactionObject( this.kit.connection, this.contract.methods.approve(valueToString(proposalID), proposalIndex) ) } /** * Applies `sender`'s vote choice to a given proposal. * @param proposalID Governance proposal UUID * @param vote Choice to apply (yes, no, abstain) */ async vote(proposalID: BigNumber.Value, vote: keyof typeof VoteValue) { const proposalIndex = await this.getDequeueIndex(proposalID) const voteNum = Object.keys(VoteValue).indexOf(vote) return toTransactionObject( this.kit.connection, this.contract.methods.vote(valueToString(proposalID), proposalIndex, voteNum) ) } revokeVotes = proxySend(this.kit, this.contract.methods.revokeVotes) /** * Returns `voter`'s vote choice on a given proposal. * @param proposalID Governance proposal UUID * @param voter Address of voter */ async getVoteValue(proposalID: BigNumber.Value, voter: Address) { const proposalIndex = await this.getDequeueIndex(proposalID) const res = await this.contract.methods.getVoteRecord(voter, proposalIndex).call() return Object.keys(VoteValue)[valueToInt(res[1])] as VoteValue } /** * Executes a given proposal's associated transactions. * @param proposalID Governance proposal UUID */ async execute(proposalID: BigNumber.Value) { const proposalIndex = await this.getDequeueIndex(proposalID) return toTransactionObject( this.kit.connection, this.contract.methods.execute(valueToString(proposalID), proposalIndex) ) } /** * Returns approved, executed, and prepared status associated with a given hotfix. * @param hash keccak256 hash of hotfix's associated abi encoded transactions */ async getHotfixRecord(hash: Buffer): Promise<HotfixRecord> { const res = await this.contract.methods.getHotfixRecord(bufferToHex(hash)).call() return { approved: res[0], executed: res[1], preparedEpoch: valueToBigNumber(res[2]), } } /** * Returns whether a given hotfix has been whitelisted by a given address. * @param hash keccak256 hash of hotfix's associated abi encoded transactions * @param whitelister address of whitelister */ isHotfixWhitelistedBy = proxyCall( this.contract.methods.isHotfixWhitelistedBy, tupleParser(bufferToHex, (s: Address) => identity<Address>(s)) ) /** * Returns whether a given hotfix can be passed. * @param hash keccak256 hash of hotfix's associated abi encoded transactions */ isHotfixPassing = proxyCall(this.contract.methods.isHotfixPassing, tupleParser(bufferToHex)) /** * Returns the number of validators required to reach a Byzantine quorum */ minQuorumSize = proxyCall( this.contract.methods.minQuorumSizeInCurrentSet, undefined, valueToBigNumber ) /** * Returns the number of validators that whitelisted the hotfix * @param hash keccak256 hash of hotfix's associated abi encoded transactions */ hotfixWhitelistValidatorTally = proxyCall( this.contract.methods.hotfixWhitelistValidatorTally, tupleParser(bufferToHex) ) /** * Marks the given hotfix whitelisted by `sender`. * @param hash keccak256 hash of hotfix's associated abi encoded transactions */ whitelistHotfix = proxySend( this.kit, this.contract.methods.whitelistHotfix, tupleParser(bufferToHex) ) /** * Marks the given hotfix approved by `sender`. * @param hash keccak256 hash of hotfix's associated abi encoded transactions * @notice Only the `approver` address will succeed in sending this transaction */ approveHotfix = proxySend(this.kit, this.contract.methods.approveHotfix, tupleParser(bufferToHex)) /** * Marks the given hotfix prepared for current epoch if quorum of validators have whitelisted it. * @param hash keccak256 hash of hotfix's associated abi encoded transactions */ prepareHotfix = proxySend(this.kit, this.contract.methods.prepareHotfix, tupleParser(bufferToHex)) /** * Executes a given sequence of transactions if the corresponding hash is prepared and approved. * @param hotfix Governance hotfix proposal * @param salt Secret which guarantees uniqueness of hash * @notice keccak256 hash of abi encoded transactions computed on-chain */ executeHotfix = proxySend(this.kit, this.contract.methods.executeHotfix, hotfixToParams) }
the_stack
import { extend, isNullOrUndefined } from '@syncfusion/ej2-base'; import { DataManager, Query } from '@syncfusion/ej2-data'; import { FreezeContentRender, FreezeRender } from './freeze-renderer'; import { ColumnFreezeContentRenderer } from './column-freeze-renderer'; import { IGrid, IRenderer, NotifyArgs, InterSection, IModelGenerator } from '../base/interface'; import { ServiceLocator } from '../services/service-locator'; import { VirtualContentRenderer, VirtualHeaderRenderer } from './virtual-content-renderer'; import { RowRenderer } from '../renderer/row-renderer'; import { FreezeRowModelGenerator } from '../services/freeze-row-model-generator'; import { RowModelGenerator } from '../services/row-model-generator'; import { RendererFactory } from '../services/renderer-factory'; import { RenderType, freezeTable } from '../base/enum'; import { ReturnType } from '../base/type'; import { InterSectionObserver } from '../services/intersection-observer'; import { Row } from '../models/row'; import { Cell } from '../models/cell'; import { Column } from '../models/column'; import * as events from '../base/constant'; import { splitFrozenRowObjectCells } from '../base/util'; import { ColumnWidthService } from '../services/width-controller'; import * as literals from '../base/string-literals'; /** * VirtualFreezeRenderer is used to render the virtual table within the frozen and movable content table * * @hidden */ export class VirtualFreezeRenderer extends FreezeContentRender implements IRenderer { protected serviceLoc: ServiceLocator; public rowModelGenerator: IModelGenerator<Column>; constructor(parent?: IGrid, locator?: ServiceLocator) { super(parent, locator); this.serviceLoc = locator; this.eventListener('on'); this.rowModelGenerator = new RowModelGenerator(this.parent); } protected freezeRowGenerator: FreezeRowModelGenerator; /** @hidden */ public virtualRenderer: VirtualContentRenderer; protected firstPageRecords: Object[]; protected scrollbar: HTMLElement; /** @hidden */ public frzRows: Row<Column>[] = []; /** @hidden */ public mvblRows: Row<Column>[] = []; /** @hidden */ public frRows: Row<Column>[] = []; public eventListener(action: string): void { this.parent[action](events.getVirtualData, this.getVirtualData, this); this.parent[action](events.setFreezeSelection, this.setFreezeSelection, this); this.parent[action](events.refreshVirtualFrozenRows, this.refreshVirtualFrozenRows, this); this.parent.addEventListener(events.actionComplete, this.actionComplete.bind(this)); } protected actionComplete(args: NotifyArgs): void { if (args.requestType === 'delete' && this.parent.frozenRows) { for (let i: number = 0; i < this.parent.frozenRows; i++) { setCache(this, i); } } } private refreshVirtualFrozenRows(args: NotifyArgs): void { const gObj: IGrid = this.parent; if (args.requestType === 'delete' && gObj.frozenRows) { args.isFrozenRowsRender = true; const query: Query = gObj.renderModule.data.generateQuery(true).clone(); query.page(1, gObj.pageSettings.pageSize); gObj.renderModule.data.getData({}, query).then((e: ReturnType) => { renderFrozenRows( args, e.result, gObj.getSelectedRowIndexes(), gObj, this.rowModelGenerator, this.serviceLoc, this.virtualRenderer, this ); }); } } private getVirtualData(data: { virtualData: Object, isAdd: boolean, isCancel: boolean, isScroll: boolean }): void { this.virtualRenderer.getVirtualData(data); } private setFreezeSelection(args: { uid: string, set: boolean, clearAll?: boolean }): void { setFreezeSelection(args, this.virtualRenderer); } /** * @returns {void} * @hidden */ public renderTable(): void { this.freezeRowGenerator = new FreezeRowModelGenerator(this.parent); this.virtualRenderer = new VirtualContentRenderer(this.parent, this.serviceLoc); this.virtualRenderer.header = (this.serviceLoc.getService<RendererFactory>('rendererFactory') .getRenderer(RenderType.Header) as VirtualFreezeHdrRenderer).virtualHdrRenderer; super.renderTable(); this.virtualRenderer.setPanel(this.parent.getContent()); this.scrollbar = this.parent.getContent().querySelector('.e-movablescrollbar'); const movableCont: Element = this.getMovableContent(); const minHeight: number = <number>this.parent.height; this.virtualRenderer.virtualEle.content = this.virtualRenderer.content = <HTMLElement>this.getPanel().querySelector('.' + literals.content); (this.virtualRenderer.virtualEle.content as HTMLElement).style.overflowX = 'hidden'; this.virtualRenderer.virtualEle.renderFrozenWrapper(minHeight); this.virtualRenderer.virtualEle.renderFrozenPlaceHolder(); if (this.parent.enableColumnVirtualization) { this.virtualRenderer.virtualEle.movableContent = this.virtualRenderer.movableContent = <HTMLElement>this.getPanel().querySelector('.' + literals.movableContent); this.virtualRenderer.virtualEle.renderMovableWrapper(minHeight); this.virtualRenderer.virtualEle.renderMovablePlaceHolder(); const tbl: HTMLElement = movableCont.querySelector('table'); this.virtualRenderer.virtualEle.movableTable = tbl; this.virtualRenderer.virtualEle.movableWrapper.appendChild(tbl); movableCont.appendChild(this.virtualRenderer.virtualEle.movableWrapper); movableCont.appendChild(this.virtualRenderer.virtualEle.movablePlaceholder); } this.virtualRenderer.virtualEle.wrapper.appendChild(this.getFrozenContent()); this.virtualRenderer.virtualEle.wrapper.appendChild(movableCont); this.virtualRenderer.virtualEle.table = <HTMLElement>this.getTable(); setDebounce(this.parent, this.virtualRenderer, this.scrollbar, this.getMovableContent()); } /** * @param {HTMLElement} target - specifies the target * @param {DocumentFragment} newChild - specifies the newChild * @param {NotifyArgs} e - specifies the notifyargs * @returns {void} * @hidden */ public appendContent(target: HTMLElement, newChild: DocumentFragment, e: NotifyArgs): void { appendContent(this.virtualRenderer, this.widthService, target, newChild, e); } /** * @param {Object[]} data - specifies the data * @param {NotifyArgs} notifyArgs - specifies the notifyargs * @returns {Row<Column>[]} returns the row * @hidden */ public generateRows(data: Object[], notifyArgs?: NotifyArgs): Row<Column>[] { if (!this.firstPageRecords) { this.firstPageRecords = data; } return generateRows(this.virtualRenderer, data, notifyArgs, this.freezeRowGenerator, this.parent); } /** * @param {number} index - specifies the index * @returns {Element} returns the element * @hidden */ public getRowByIndex(index: number): Element { return this.virtualRenderer.getRowByIndex(index); } /** * @param {number} index - specifies the index * @returns {Element} returns the element * @hidden */ public getMovableRowByIndex(index: number): Element { return this.virtualRenderer.getMovableVirtualRowByIndex(index); } private collectRows(tableName: freezeTable): Row<Column>[] { return collectRows(tableName, this.virtualRenderer, this.parent); } /** * @returns {HTMLCollection} returns the Htmlcollection * @hidden */ public getMovableRows(): Row<Column>[] | HTMLCollectionOf<HTMLTableRowElement> { return this.collectRows('movable'); } /** * @returns {HTMLCollectionOf<HTMLTableRowElement>} returns the html collection * @hidden */ public getRows(): Row<Column>[] | HTMLCollectionOf<HTMLTableRowElement> { return this.collectRows('frozen-left'); } /** * @returns {Element} returns the element * @hidden */ public getColGroup(): Element { const mCol: Element = this.parent.getMovableVirtualContent(); return this.isXaxis() ? mCol.querySelector(literals.colGroup) : this.colgroup; } /** * @param {NotifyArgs} args - specifies the args * @returns {Row<Column>[]} returns the row * @hidden */ public getReorderedFrozenRows(args: NotifyArgs): Row<Column>[] { return getReorderedFrozenRows(args, this.virtualRenderer, this.parent, this.freezeRowGenerator, this.firstPageRecords); } protected isXaxis(): boolean { return isXaxis(this.virtualRenderer); } protected getHeaderCells(): Element[] { return getHeaderCells(this.virtualRenderer, this.parent); } protected getVirtualFreezeHeader(): Element { return getVirtualFreezeHeader(this.virtualRenderer, this.parent); } protected ensureFrozenCols(columns: Column[]): Column[] { return ensureFrozenCols(columns, this.parent); } /** * @param {number} index - specifies the index * @returns {object} returns the object * @hidden */ public getRowObjectByIndex(index: number): Object { return this.virtualRenderer.getRowObjectByIndex(index); } /** * Set the header colgroup element * * @param {Element} colGroup - specifies the colgroup * @returns {Element} returns the element */ public setColGroup(colGroup: Element): Element { return setColGroup(colGroup, this.virtualRenderer, this); } } /** * VirtualFreezeHdrRenderer is used to render the virtual table within the frozen and movable header table * * @hidden */ export class VirtualFreezeHdrRenderer extends FreezeRender implements IRenderer { protected serviceLoc: ServiceLocator; constructor(parent?: IGrid, locator?: ServiceLocator) { super(parent, locator); this.serviceLoc = locator; } public virtualHdrRenderer: VirtualHeaderRenderer; /** * @returns {void} * @hidden */ public renderTable(): void { this.virtualHdrRenderer = new VirtualHeaderRenderer(this.parent, this.serviceLoc); this.virtualHdrRenderer.gen.refreshColOffsets(); this.parent.setColumnIndexesInView(this.virtualHdrRenderer.gen.getColumnIndexes(<HTMLElement>this.getPanel() .querySelector('.' + literals.headerContent))); this.virtualHdrRenderer.virtualEle.content = <HTMLElement>this.getPanel().querySelector('.' + literals.headerContent); this.virtualHdrRenderer.virtualEle.renderFrozenWrapper(); this.virtualHdrRenderer.virtualEle.renderFrozenPlaceHolder(); if (this.parent.enableColumnVirtualization) { this.virtualHdrRenderer.virtualEle.movableContent = <HTMLElement>this.getPanel().querySelector('.' + literals.movableHeader); this.virtualHdrRenderer.virtualEle.renderMovableWrapper(); this.virtualHdrRenderer.virtualEle.renderMovablePlaceHolder(); } super.renderTable(); this.virtualHdrRenderer.setPanel(this.parent.getHeaderContent()); } protected rfshMovable(): void { this.getFrozenHeader().appendChild(this.getTable()); this.virtualHdrRenderer.virtualEle.wrapper.appendChild(this.getFrozenHeader()); if (this.parent.enableColumnVirtualization) { this.virtualHdrRenderer.virtualEle.movableWrapper.appendChild(this.createHeader(undefined, 'movable')); } else { this.getMovableHeader().appendChild(this.createTable()); } this.virtualHdrRenderer.virtualEle.wrapper.appendChild(this.getMovableHeader()); } } /** * @param {NotifyArgs} args - specifies the args * @param {Object[]} data - specifies the data * @param {number[]}selectedIdx - specifies the selected index * @param {IGrid} parent - specifies the IGrid * @param {IModelGenerator} rowModelGenerator - specifies the rowModeGenerator * @param {ServiceLocator} locator - specifies the locator * @param {VirtualContentRenderer} virtualRenderer - specifies the virtual renderer * @param {VirtualFreezeRenderer} instance - specifies the instance * @returns {void} * @hidden */ export function renderFrozenRows( args: NotifyArgs, data: Object[], selectedIdx: number[], parent: IGrid, rowModelGenerator: IModelGenerator<Column>, locator: ServiceLocator, virtualRenderer: VirtualContentRenderer, instance: VirtualFreezeRenderer | ColumnVirtualFreezeRenderer ): void { parent.clearSelection(); (<{ startIndex?: number }>args).startIndex = 0; const rowRenderer: RowRenderer<Column> = new RowRenderer<Column>(locator, null, parent); let rows: Row<Column>[] = rowModelGenerator.generateRows(data, args); if (args.renderMovableContent) { virtualRenderer.vgenerator.movableCache[1] = rows; rows = parent.getMovableRowsObject(); } else if (!args.renderFrozenRightContent && !args.renderMovableContent) { virtualRenderer.vgenerator.cache[1] = rows; rows = parent.getRowsObject(); } else if (args.renderFrozenRightContent) { virtualRenderer.vgenerator.frozenRightCache[1] = rows; rows = parent.getFrozenRightRowsObject(); } const hdr: Element = !args.renderMovableContent && !args.renderFrozenRightContent ? parent.getHeaderContent().querySelector('.' + literals.frozenHeader).querySelector( literals.tbody) : args.renderMovableContent ? parent.getHeaderContent().querySelector('.' + literals.movableHeader).querySelector( literals.tbody) : parent.getHeaderContent().querySelector('.e-frozen-right-header').querySelector( literals.tbody); hdr.innerHTML = ''; for (let i: number = 0; i < parent.frozenRows; i++) { hdr.appendChild(rowRenderer.render(rows[i], parent.getColumns())); if (selectedIdx.indexOf(i) > -1) { rows[i].isSelected = true; for (let k: number = 0; k < rows[i].cells.length; k++) { rows[i].cells[k].isSelected = true; } } } if (args.renderMovableContent) { instance.mvblRows = virtualRenderer.vgenerator.movableCache[1]; } else if (!args.renderMovableContent && !args.renderFrozenRightContent) { instance.frzRows = virtualRenderer.vgenerator.cache[1]; } else if (args.renderFrozenRightContent) { instance.frRows = virtualRenderer.vgenerator.frozenRightCache[1]; } args.renderMovableContent = !args.renderMovableContent && !args.renderFrozenRightContent; args.renderFrozenRightContent = parent.getFrozenMode() === literals.leftRight && !args.renderMovableContent && !args.renderFrozenRightContent; if (args.renderMovableContent || args.renderFrozenRightContent) { renderFrozenRows(args, data, selectedIdx, parent, rowModelGenerator, locator, virtualRenderer, instance); if (!args.renderMovableContent && !args.renderFrozenRightContent) { args.isFrozenRowsRender = false; } } } /** * @param {Row<Column>[]} data - specifies the data * @param {freezeTable} tableName -specifies the table * @param {IGrid} parent - specifies the IGrid * @returns {Row<Column>[]} returns the row * @hidden */ export function splitCells(data: Row<Column>[], tableName: freezeTable, parent: IGrid): Row<Column>[] { const rows: Row<Column>[] = []; for (let i: number = 0; i < data.length; i++) { rows.push(extend({}, data[i]) as Row<Column>); rows[i].cells = splitFrozenRowObjectCells(parent, rows[i].cells, tableName); } return rows; } /** * @param {freezeTable} tableName - specifies the freeze tabel * @param {VirtualContentRenderer} virtualRenderer - specifies the virtual renderer * @param {IGrid} parent - specifies the IGrid * @returns {Row<Column>[]} returns the row * @hidden */ export function collectRows(tableName: freezeTable, virtualRenderer: VirtualContentRenderer, parent: IGrid): Row<Column>[] { let rows: Row<Column>[] = []; let cache: { [x: number]: Row<Column>[] }; if (tableName === literals.frozenLeft) { cache = virtualRenderer.vgenerator.cache; } else if (tableName === 'movable') { cache = virtualRenderer.vgenerator.movableCache; } else if (tableName === literals.frozenRight) { cache = parent.getFrozenMode() === 'Right' ? virtualRenderer.vgenerator.cache : virtualRenderer.vgenerator.frozenRightCache; } const keys: string[] = Object.keys(cache); for (let i: number = 0; i < keys.length; i++) { rows = [...rows, ...splitCells(cache[keys[i]], tableName, parent)]; } return rows; } /** * @param {object} args - specifies the args * @param {string} args.uid - specifirs the uid * @param {boolean} args.set - specifies the set * @param {boolean} args.clearAll - specifies the boolean to clearall * @param {VirtualContentRenderer} virtualRenderer - specifies the virtual renderer * @returns {void} * @hidden */ export function setFreezeSelection(args: { uid: string, set: boolean, clearAll?: boolean }, virtualRenderer: VirtualContentRenderer): void { const leftKeys: string[] = Object.keys(virtualRenderer.vgenerator.cache); const movableKeys: string[] = Object.keys(virtualRenderer.vgenerator.movableCache); const rightKeys: string[] = Object.keys(virtualRenderer.vgenerator.frozenRightCache); for (let i: number = 0; i < leftKeys.length; i++) { selectFreezeRows(args, virtualRenderer.vgenerator.cache[leftKeys[i]]); } for (let i: number = 0; i < movableKeys.length; i++) { selectFreezeRows(args, virtualRenderer.vgenerator.movableCache[movableKeys[i]]); } for (let i: number = 0; i < rightKeys.length; i++) { selectFreezeRows(args, virtualRenderer.vgenerator.frozenRightCache[rightKeys[i]]); } } /** * @param {Object} args - specifies the args * @param {string} args.uid - specifirs the uid * @param {boolean} args.set - specifies the set * @param {boolean} args.clearAll - specifies the boolean to clearall * @param {Row<Column>[]} cache - specifies the cache * @returns {void} * @hidden */ export function selectFreezeRows(args: { uid: string, set: boolean, clearAll?: boolean }, cache: Row<Column>[]): void { const rows: Row<Column>[] = cache.filter((row: Row<Column>) => args.clearAll || args.uid === row.uid); for (let j: number = 0; j < rows.length; j++) { rows[j].isSelected = args.set; const cells: Cell<Column>[] = rows[j].cells; for (let k: number = 0; k < cells.length; k++) { cells[k].isSelected = args.set; } } } /** * @param {VirtualContentRenderer} virtualRenderer - specifies the virtual renderer * @param {ColumnWidthService} widthService - specifies the width service * @param {HTMLElement} target - specifies the target * @param {DocumentFragment} newChild - specifies the newchild * @param {NotifyArgs} e - specifies the notifyargs * @returns {void} * @hidden */ export function appendContent( virtualRenderer: VirtualContentRenderer, widthService: ColumnWidthService, target: HTMLElement, newChild: DocumentFragment, e: NotifyArgs ): void { virtualRenderer.appendContent(target, newChild, e); widthService.refreshFrozenScrollbar(); } /** * @param {VirtualContentRenderer} virtualRenderer - specifies the virtual renderer * @param {object[]} data - specifies the data * @param {NotifyArgs} notifyArgs - specifies the notifyargs * @param {FreezeRowModelGenerator} freezeRowGenerator - specifies the freeze row generator * @param {IGrid} parent - specifies the IGrid * @returns {Row<Column>[]} returns the row * @hidden */ export function generateRows( virtualRenderer: VirtualContentRenderer, data: Object[], notifyArgs: NotifyArgs, freezeRowGenerator: FreezeRowModelGenerator, parent: IGrid ): Row<Column>[] { const virtualRows: Row<Column>[] = virtualRenderer.vgenerator.generateRows(data, notifyArgs); let arr: Row<Column>[] = []; arr = virtualRows.map((row: Row<Column>) => extend({}, row) as Row<Column>); let rows: Row<Column>[] = freezeRowGenerator.generateRows(data, notifyArgs, arr); if (parent.frozenRows && notifyArgs.requestType === 'delete' && parent.pageSettings.currentPage === 1) { rows = rows.slice(parent.frozenRows); } return rows; } /** * @param {NotifyArgs} args -specifies the args * @param {VirtualContentRenderer} virtualRenderer - specifies the virtual renderer * @param {IGrid} parent - specifies the IGrid * @param {FreezeRowModelGenerator} freezeRowGenerator - specifies the freezeRowGenerator * @param {Object[]} firstPageRecords - specifies the first page records * @returns {Row<Column>[]} returns the row * @hidden */ export function getReorderedFrozenRows( args: NotifyArgs, virtualRenderer: VirtualContentRenderer, parent: IGrid, freezeRowGenerator: FreezeRowModelGenerator, firstPageRecords: Object[] ): Row<Column>[] { const bIndex: number[] = args.virtualInfo.blockIndexes; const colIndex: number[] = args.virtualInfo.columnIndexes; const page: number = args.virtualInfo.page; args.virtualInfo.blockIndexes = [1, 2]; args.virtualInfo.page = 1; if (!args.renderMovableContent) { args.virtualInfo.columnIndexes = []; } const firstRecordslength: number = parent.getCurrentViewRecords().length; firstPageRecords = parent.renderModule.data.dataManager.dataSource.json.slice(0, firstRecordslength); const virtualRows: Row<Column>[] = virtualRenderer.vgenerator.generateRows(firstPageRecords, args); const rows: Row<Column>[] = splitReorderedRows(virtualRows, parent, args, freezeRowGenerator); args.virtualInfo.blockIndexes = bIndex; args.virtualInfo.columnIndexes = colIndex; args.virtualInfo.page = page; return rows.splice(0, parent.frozenRows); } /** * @param {Row<Column>[]} rows - specifies the row * @param {IGrid} parent - specifies the IGrid * @param {NotifyArgs} args - specifies the notify arguments * @param {FreezeRowModelGenerator} freezeRowGenerator - specifies the freezerowgenerator * @returns {Row<Column>[]} returns the row * @hidden */ export function splitReorderedRows( // eslint-disable-next-line @typescript-eslint/no-unused-vars rows: Row<Column>[], parent: IGrid, args: NotifyArgs, freezeRowGenerator: FreezeRowModelGenerator ): Row<Column>[] { let tableName: freezeTable; if (args.renderMovableContent) { tableName = 'movable'; } else if (args.renderFrozenRightContent) { tableName = 'frozen-right'; } else { tableName = 'frozen-left'; } for (let i: number = 0, len: number = rows.length; i < len; i++) { rows[i].cells = splitFrozenRowObjectCells(parent, rows[i].cells, tableName); } return rows; } /** * @param {VirtualContentRenderer} virtualRenderer - specifies the VirtualRenderer * @returns {boolean} returns the isXaxis * @hidden */ export function isXaxis(virtualRenderer: VirtualContentRenderer): boolean { let value: boolean = false; if (virtualRenderer) { value = virtualRenderer.requestType === 'virtualscroll' && virtualRenderer.currentInfo.sentinelInfo.axis === 'X'; } return value; } /** * @param {VirtualContentRenderer} virtualRenderer - specifies the virtualrenderer * @param {IGrid} parent - specifies the IGrid * @returns {Element[]} returns the element * @hidden */ export function getHeaderCells(virtualRenderer: VirtualContentRenderer, parent: IGrid): Element[] { const content: Element = isXaxis(virtualRenderer) ? parent.getMovableVirtualHeader() : parent.getHeaderContent(); return content ? [].slice.call(content.querySelectorAll('.e-headercell:not(.e-stackedheadercell)')) : []; } /** * @param {VirtualContentRenderer} virtualRenderer - specifies the virtual Renderer * @param {IGrid} parent - specifies the IGrid * @returns {Element} returns the element * @hidden */ export function getVirtualFreezeHeader(virtualRenderer: VirtualContentRenderer, parent: IGrid): Element { let headerTable: Element; if (isXaxis(virtualRenderer)) { headerTable = parent.getMovableVirtualHeader().querySelector('.' + literals.table); } else { headerTable = parent.getFrozenVirtualHeader().querySelector('.' + literals.table); } return headerTable; } /** * @param {Column[]} columns - specifies the columns * @param {IGrid} parent - specifies the IGrid * @returns {Column[]} returns the column[] * @hidden */ export function ensureFrozenCols(columns: Column[], parent: IGrid): Column[] { const frozenCols: Column[] = parent.columns.slice(0, parent.getFrozenColumns()) as Column[]; columns = frozenCols.concat(columns); return columns; } /** * @param {Element} colGroup - specifies the colGroup * @param {VirtualContentRenderer} virtualRenderer - specifies the virtual renderer * @param {ColumnVirtualFreezeRenderer} instance - specifies the instances * @returns {Element} returns the element * @hidden */ export function setColGroup( colGroup: Element, virtualRenderer: VirtualContentRenderer, instance: ColumnVirtualFreezeRenderer | VirtualFreezeRenderer ): Element { if (!isXaxis(virtualRenderer)) { if (!isNullOrUndefined(colGroup)) { colGroup.id = 'content-' + colGroup.id; } instance.colgroup = colGroup; } return instance.colgroup; } /** * @param {VirtualFreezeRenderer} instance - specifies the instance * @param {number} index - specifies the index * @returns {void} * @hidden */ export function setCache(instance: VirtualFreezeRenderer | ColumnVirtualFreezeRenderer, index: number): void { if (instance.virtualRenderer.vgenerator.cache[1]) { instance.virtualRenderer.vgenerator.cache[1][index] = instance.frzRows[index]; } else { instance.virtualRenderer.vgenerator.cache[1] = instance.frzRows; } if (instance.virtualRenderer.vgenerator.movableCache[1]) { instance.virtualRenderer.vgenerator.movableCache[1][index] = instance.mvblRows[index]; } else { instance.virtualRenderer.vgenerator.movableCache[1] = instance.mvblRows; } } /** * @param {IGrid} parent - specifies the IGrid * @param {VirtualContentRenderer} virtualRenderer - specifies the virtualRenderer * @param {Element} scrollbar - specifies the scrollbr * @param {Element} mCont - specifies the mCont * @returns {void} * @hidden */ export function setDebounce(parent: IGrid, virtualRenderer: VirtualContentRenderer, scrollbar: Element, mCont: Element): void { const debounceEvent: boolean = (parent.dataSource instanceof DataManager && !parent.dataSource.dataSource.offline); const opt: InterSection = { container: virtualRenderer.content, pageHeight: virtualRenderer.getBlockHeight() * 2, debounceEvent: debounceEvent, axes: parent.enableColumnVirtualization ? ['X', 'Y'] : ['Y'], scrollbar: scrollbar, movableContainer: mCont }; virtualRenderer.observer = new InterSectionObserver( virtualRenderer.virtualEle.wrapper, opt, virtualRenderer.virtualEle.movableWrapper ); } /** * ColumnVirtualFreezeRenderer is used to render the virtual table within the frozen and movable content table * * @hidden */ export class ColumnVirtualFreezeRenderer extends ColumnFreezeContentRenderer implements IRenderer { protected serviceLoc: ServiceLocator; public rowModelGenerator: IModelGenerator<Column>; constructor(parent?: IGrid, locator?: ServiceLocator) { super(parent, locator); this.serviceLoc = locator; this.eventListener('on'); this.rowModelGenerator = new RowModelGenerator(this.parent); } /** @hidden */ public virtualRenderer: VirtualContentRenderer; protected freezeRowGenerator: FreezeRowModelGenerator; protected firstPageRecords: Object[]; protected scrollbar: HTMLElement; /** @hidden */ public frRows: Row<Column>[] = []; /** @hidden */ public frzRows: Row<Column>[] = []; /** @hidden */ public mvblRows: Row<Column>[] = []; protected actionComplete(args: NotifyArgs): void { if (args.requestType === 'delete' && this.parent.frozenRows) { for (let i: number = 0; i < this.parent.frozenRows; i++) { if (this.virtualRenderer.vgenerator.frozenRightCache[1]) { this.virtualRenderer.vgenerator.frozenRightCache[1][i] = this.frRows.length ? this.frRows[i] : this.frzRows[i]; } else { this.virtualRenderer.vgenerator.frozenRightCache[1] = this.frRows.length ? this.frRows : this.frzRows; break; } setCache(this, i); } } } public eventListener(action: string): void { this.parent.addEventListener(events.actionComplete, this.actionComplete.bind(this)); this.parent[action](events.refreshVirtualFrozenRows, this.refreshVirtualFrozenRows, this); this.parent[action](events.getVirtualData, this.getVirtualData, this); this.parent[action](events.setFreezeSelection, this.setFreezeSelection, this); } private refreshVirtualFrozenRows(args: NotifyArgs): void { if (args.requestType === 'delete' && this.parent.frozenRows) { args.isFrozenRowsRender = true; const query: Query = this.parent.renderModule.data.generateQuery(true).clone(); query.page(1, this.parent.pageSettings.pageSize); const selectedIdx: number[] = this.parent.getSelectedRowIndexes(); this.parent.renderModule.data.getData({}, query).then((e: ReturnType) => { renderFrozenRows( args, e.result, selectedIdx, this.parent, this.rowModelGenerator, this.serviceLoc, this.virtualRenderer, this ); }); } } private setFreezeSelection(args: { uid: string, set: boolean, clearAll?: boolean }): void { setFreezeSelection(args, this.virtualRenderer); } private getVirtualData(data: { virtualData: Object, isAdd: boolean, isCancel: boolean, isScroll: boolean }): void { this.virtualRenderer.getVirtualData(data); } public renderNextFrozentPart(e: NotifyArgs, tableName: freezeTable): void { e.renderMovableContent = this.parent.getFrozenLeftCount() ? tableName === literals.frozenLeft : tableName === literals.frozenRight; e.renderFrozenRightContent = this.parent.getFrozenMode() === literals.leftRight && tableName === 'movable'; if (e.renderMovableContent || e.renderFrozenRightContent) { this.refreshContentRows(extend({}, e)); } } /** * @returns {void} * @hidden */ public renderTable(): void { this.virtualRenderer = new VirtualContentRenderer(this.parent, this.serviceLoc); this.virtualRenderer.header = (this.serviceLoc.getService<RendererFactory>('rendererFactory') .getRenderer(RenderType.Header) as VirtualFreezeHdrRenderer).virtualHdrRenderer; this.freezeRowGenerator = new FreezeRowModelGenerator(this.parent); super.renderTable(); this.virtualRenderer.setPanel(this.parent.getContent()); this.scrollbar = this.parent.getContent().querySelector('.e-movablescrollbar'); const frozenRightCont: Element = this.getFrozenRightContent(); let frzCont: Element = this.getFrozenContent(); const movableCont: Element = this.getMovableContent(); if (this.parent.getFrozenMode() === 'Right') { frzCont = frozenRightCont; } this.virtualRenderer.virtualEle.content = this.virtualRenderer.content = <HTMLElement>this.getPanel().querySelector('.' + literals.content); (this.virtualRenderer.virtualEle.content as HTMLElement).style.overflowX = 'hidden'; const minHeight: number = <number>this.parent.height; this.virtualRenderer.virtualEle.renderFrozenWrapper(minHeight); this.virtualRenderer.virtualEle.renderFrozenPlaceHolder(); this.renderVirtualFrozenLeft(frzCont, movableCont); this.renderVirtualFrozenRight(frzCont, movableCont); this.renderVirtualFrozenLeftRight(frzCont, movableCont, frozenRightCont); this.virtualRenderer.virtualEle.table = <HTMLElement>this.getTable(); setDebounce(this.parent, this.virtualRenderer, this.scrollbar, this.getMovableContent()); } private renderVirtualFrozenLeft(frzCont: Element, movableCont: Element): void { if (this.parent.getFrozenMode() === 'Left') { this.virtualRenderer.virtualEle.wrapper.appendChild(frzCont); this.virtualRenderer.virtualEle.wrapper.appendChild(movableCont); } } private renderVirtualFrozenRight(frzCont: Element, movableCont: Element): void { if (this.parent.getFrozenMode() === 'Right') { this.virtualRenderer.virtualEle.wrapper.appendChild(movableCont); this.virtualRenderer.virtualEle.wrapper.appendChild(frzCont); } } private renderVirtualFrozenLeftRight(frzCont: Element, movableCont: Element, frozenRightCont: Element): void { if (this.parent.getFrozenMode() === literals.leftRight) { this.virtualRenderer.virtualEle.wrapper.appendChild(frzCont); this.virtualRenderer.virtualEle.wrapper.appendChild(movableCont); this.virtualRenderer.virtualEle.wrapper.appendChild(frozenRightCont); } } /** * @param {HTMLElement} target - specifies the target * @param {DocumentFragment} newChild - specifies the newchild * @param {NotifyArgs} e - specifies the NotifyArgs * @returns {void} * @hidden */ public appendContent(target: HTMLElement, newChild: DocumentFragment, e: NotifyArgs): void { appendContent(this.virtualRenderer, this.widthService, target, newChild, e); this.refreshScrollOffset(); } /** * @param {Object[]} data - specifies the data * @param {NotifyArgs} e - specifies the notifyargs * @returns {Row<Column>[]} returns the row * @hidden */ public generateRows(data: Object[], e?: NotifyArgs): Row<Column>[] { if (!this.firstPageRecords) { this.firstPageRecords = data; } return generateRows(this.virtualRenderer, data, e, this.freezeRowGenerator, this.parent); } /** * @param {number} index - specifies the number * @returns {Element} returns the element * @hidden */ public getRowByIndex(index: number): Element { return this.virtualRenderer.getRowByIndex(index); } /** * @param {number} index - specifies the index * @returns {Element} - returns the element * @hidden */ public getFrozenRightRowByIndex(index: number): Element { return this.virtualRenderer.getFrozenRightVirtualRowByIndex(index); } private collectRows(tableName: freezeTable): Row<Column>[] { return collectRows(tableName, this.virtualRenderer, this.parent); } /** * @param {number} index - specifies the index * @returns {Element} returns the element * @hidden */ public getMovableRowByIndex(index: number): Element { return this.virtualRenderer.getMovableVirtualRowByIndex(index); } /** * @returns {Row<Column>[]} returns the row * @hidden */ public getFrozenRightRows(): Row<Column>[] | HTMLCollectionOf<HTMLTableRowElement> { return this.collectRows('frozen-right'); } /** * @returns {Row<Column>[]} returns the row * @hidden */ public getMovableRows(): Row<Column>[] | HTMLCollectionOf<HTMLTableRowElement> { return this.collectRows('movable'); } /** * @returns {Element} returns the element * @hidden */ public getColGroup(): Element { const mCol: Element = this.parent.getMovableVirtualContent(); return isXaxis(this.virtualRenderer) ? mCol.querySelector(literals.colGroup) : this.colgroup; } /** * @returns {Row<Column>[]} returns the row * @hidden */ public getRows(): Row<Column>[] | HTMLCollectionOf<HTMLTableRowElement> { return this.collectRows(this.parent.getFrozenMode() === 'Right' ? 'frozen-right' : 'frozen-left'); } /** * @param {NotifyArgs} args - specifies the args * @returns {Row<Column>[]} returns the row object * @hidden */ public getReorderedFrozenRows(args: NotifyArgs): Row<Column>[] { return getReorderedFrozenRows(args, this.virtualRenderer, this.parent, this.freezeRowGenerator, this.firstPageRecords); } protected getHeaderCells(): Element[] { return getHeaderCells(this.virtualRenderer, this.parent); } protected isXaxis(): boolean { return isXaxis(this.virtualRenderer); } protected getVirtualFreezeHeader(): Element { return getVirtualFreezeHeader(this.virtualRenderer, this.parent); } /** * @param {number} index - specifies the index * @returns {object} - returns the object * @hidden */ public getRowObjectByIndex(index: number): Object { return this.virtualRenderer.getRowObjectByIndex(index); } protected ensureFrozenCols(columns: Column[]): Column[] { return ensureFrozenCols(columns, this.parent); } /** * Set the header colgroup element * * @param {Element} colGroup - specifies the colgroup * @returns {Element} - returns the element */ public setColGroup(colGroup: Element): Element { return setColGroup(colGroup, this.virtualRenderer, this); } }
the_stack
import * as React from 'react'; import { mount as _mount, shallow as _shallow } from 'enzyme'; import { FieldEvent, FieldFeedbackType, FieldFeedbackValidation, FormWithConstraints, FormWithConstraintsChildContext, FormWithConstraintsProps } from 'react-form-with-constraints'; import { dBlock, error, formatHTML, key, warning, whenValid } from '../../react-form-with-constraints/src/formatHTML'; import { DisplayFields } from '.'; import { SignUp } from './SignUp'; // [d-inline](https://getbootstrap.com/docs/4.5/utilities/display/) const dInline = 'style="display: inline;"'; function mount(node: React.ReactElement<FormWithConstraintsProps>) { return _mount<FormWithConstraintsProps, Record<string, unknown>>(node); } function shallow(node: React.ReactElement, options: { context: FormWithConstraintsChildContext }) { return _shallow(node, options); } test('componentDidMount() componentWillUnmount()', () => { const form = new FormWithConstraints({}); const fieldsStoreAddListenerSpy = jest.spyOn(form.fieldsStore, 'addListener'); const fieldsStoreRemoveListenerSpy = jest.spyOn(form.fieldsStore, 'removeListener'); const wrapper = shallow(<DisplayFields />, { context: { form } }); const displayFields = wrapper.instance() as DisplayFields; expect(fieldsStoreAddListenerSpy).toHaveBeenCalledTimes(2); expect(fieldsStoreAddListenerSpy.mock.calls).toEqual([ [FieldEvent.Added, displayFields.reRender], [FieldEvent.Removed, displayFields.reRender] ]); expect(fieldsStoreRemoveListenerSpy).toHaveBeenCalledTimes(0); wrapper.unmount(); expect(fieldsStoreAddListenerSpy).toHaveBeenCalledTimes(2); expect(fieldsStoreRemoveListenerSpy).toHaveBeenCalledTimes(2); expect(fieldsStoreRemoveListenerSpy.mock.calls).toEqual([ [FieldEvent.Added, displayFields.reRender], [FieldEvent.Removed, displayFields.reRender] ]); }); describe('render()', () => { let form_username: FormWithConstraints; const validation_empty: FieldFeedbackValidation = { key: '0.0', type: FieldFeedbackType.Error, show: true }; beforeEach(() => { form_username = new FormWithConstraints({}); }); test('0 field', () => { const wrapper = shallow(<DisplayFields />, { context: { form: form_username } }); expect(wrapper.text()).toEqual('[]'); }); test('add field', () => { const wrapper = shallow(<DisplayFields />, { context: { form: form_username } }); form_username.fieldsStore.addField('username'); // https://airbnb.io/enzyme/docs/guides/migration-from-2-to-3.html#for-mount-updates-are-sometimes-required-when-they-werent-before wrapper.update(); expect(wrapper.text()).toEqual( `[ { name: "username", validations: [] } ]` ); form_username.fieldsStore.addField('password'); wrapper.update(); expect(wrapper.text()).toEqual( `[ { name: "username", validations: [] }, { name: "password", validations: [] } ]` ); }); test('remove field', () => { const wrapper = shallow(<DisplayFields />, { context: { form: form_username } }); form_username.fieldsStore.addField('username'); form_username.fieldsStore.addField('password'); wrapper.update(); expect(wrapper.text()).toEqual( `[ { name: "username", validations: [] }, { name: "password", validations: [] } ]` ); form_username.fieldsStore.removeField('password'); wrapper.update(); expect(wrapper.text()).toEqual( `[ { name: "username", validations: [] } ]` ); }); test('form.emitFieldDidValidateEvent()', () => { const wrapper = shallow(<DisplayFields />, { context: { form: form_username } }); form_username.fieldsStore.addField('username'); form_username.fieldsStore.addField('password'); const username = form_username.fieldsStore.getField('username')!; username.addOrReplaceValidation(validation_empty); form_username.emitFieldDidValidateEvent(username); // https://airbnb.io/enzyme/docs/guides/migration-from-2-to-3.html#for-mount-updates-are-sometimes-required-when-they-werent-before wrapper.update(); expect(wrapper.text()).toEqual( `[ { name: "username", validations: [ { key: "0.0", type: "error", show: true } ] }, { name: "password", validations: [] } ]` ); }); test('form.emitFieldDidResetEvent()', () => { const wrapper = shallow(<DisplayFields />, { context: { form: form_username } }); form_username.fieldsStore.addField('username'); form_username.fieldsStore.addField('password'); const username = form_username.fieldsStore.getField('username')!; username.addOrReplaceValidation(validation_empty); form_username.emitFieldDidValidateEvent(username); wrapper.update(); expect(wrapper.text()).toEqual( `[ { name: "username", validations: [ { key: "0.0", type: "error", show: true } ] }, { name: "password", validations: [] } ]` ); // Fails because "this.form.querySelectorAll()" does not work in shallow mode // form_username.resetFields(); username.clearValidations(); form_username.emitFieldDidResetEvent(username); wrapper.update(); expect(wrapper.text()).toEqual( `[ { name: "username", validations: [] }, { name: "password", validations: [] } ]` ); }); }); test('SignUp', async () => { const wrapper = mount(<SignUp />); const signUp = wrapper.instance() as SignUp; signUp.username!.value = 'john'; signUp.password!.value = '123456'; signUp.passwordConfirm!.value = '12345'; await signUp.form!.validateFields(); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="username"> <li>key="0" for="username" stop="first-error"</li> <ul> <li> <span style="text-decoration: line-through;">key="0.0" type="error"</span> </li> <li> <span style="text-decoration: line-through;">key="0.1" type="error"</span> </li> <li class="async"> <span style="">Async</span> <ul> <li> <span style="">key="0.3" type="error"</span> <span ${key}="0.3" ${error} ${dInline}>Username 'john' already taken, choose another</span> </li> </ul> </li> <li> <span style="text-decoration: line-through;">key="0.2" type="whenValid"</span> </li> </ul> <input type="password" name="password"> <li>key="1" for="password" stop="first-error"</li> <ul> <li> <span style="text-decoration: line-through;">key="1.0" type="error"</span> </li> <li> <span style="text-decoration: line-through;">key="1.1" type="error"</span> </li> <li> <span style="text-decoration: line-through;">key="1.2" type="warning"</span> </li> <li> <span style="">key="1.3" type="warning"</span> <span ${key}="1.3" ${warning} ${dInline}>Should contain small letters</span> </li> <li> <span style="">key="1.4" type="warning"</span> <span ${key}="1.4" ${warning} ${dInline}>Should contain capital letters</span> </li> <li> <span style="">key="1.5" type="warning"</span> <span ${key}="1.5" ${warning} ${dInline}>Should contain special characters</span> </li> <li> <span style="text-decoration: line-through;">key="1.6" type="whenValid"</span> <span ${key}="1.6" ${whenValid} ${dBlock}>Looks good!</span> </li> </ul> <input type="password" name="passwordConfirm"> <li>key="2" for="passwordConfirm" stop="first-error"</li> <ul> <li> <span style="">key="2.0" type="error"</span> <span ${key}="2.0" ${error} ${dInline}>Not the same password</span> </li> <li> <span style="text-decoration: line-through;">key="2.1" type="whenValid"</span> </li> </ul> </form>`); wrapper.unmount(); }); describe('Async', () => { test('then', async () => { const wrapper = mount(<SignUp />); const signUp = wrapper.instance() as SignUp; signUp.username!.value = 'jimmy'; signUp.password!.value = '12345'; signUp.passwordConfirm!.value = '12345'; await signUp.form!.validateFields(); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="username"> <li>key="0" for="username" stop="first-error"</li> <ul> <li> <span style="text-decoration: line-through;">key="0.0" type="error"</span> </li> <li> <span style="text-decoration: line-through;">key="0.1" type="error"</span> </li> <li class="async"> <span style="">Async</span> <ul> <li> <span style="">key="0.3" type="info"</span> <span ${key}="0.3" class="info" ${dInline}>Username 'jimmy' available</span> </li> </ul> </li> <li> <span style="text-decoration: line-through;">key="0.2" type="whenValid"</span> <span ${key}="0.2" ${whenValid} ${dBlock}>Looks good!</span> </li> </ul> <input type="password" name="password"> <li>key="1" for="password" stop="first-error"</li> <ul> <li> <span style="text-decoration: line-through;">key="1.0" type="error"</span> </li> <li> <span style="text-decoration: line-through;">key="1.1" type="error"</span> </li> <li> <span style="text-decoration: line-through;">key="1.2" type="warning"</span> </li> <li> <span style="">key="1.3" type="warning"</span> <span ${key}="1.3" ${warning} ${dInline}>Should contain small letters</span> </li> <li> <span style="">key="1.4" type="warning"</span> <span ${key}="1.4" ${warning} ${dInline}>Should contain capital letters</span> </li> <li> <span style="">key="1.5" type="warning"</span> <span ${key}="1.5" ${warning} ${dInline}>Should contain special characters</span> </li> <li> <span style="text-decoration: line-through;">key="1.6" type="whenValid"</span> <span ${key}="1.6" ${whenValid} ${dBlock}>Looks good!</span> </li> </ul> <input type="password" name="passwordConfirm"> <li>key="2" for="passwordConfirm" stop="first-error"</li> <ul> <li> <span style="text-decoration: line-through;">key="2.0" type="error"</span> </li> <li> <span style="text-decoration: line-through;">key="2.1" type="whenValid"</span> <span ${key}="2.1" ${whenValid} ${dBlock}>Looks good!</span> </li> </ul> </form>`); wrapper.unmount(); }); test('catch', async () => { const wrapper = mount(<SignUp />); const signUp = wrapper.instance() as SignUp; signUp.username!.value = 'error'; signUp.password!.value = '123456'; signUp.passwordConfirm!.value = '12345'; await signUp.form!.validateFields(); expect(formatHTML(wrapper.html(), ' ')).toEqual(`\ <form> <input name="username"> <li>key="0" for="username" stop="first-error"</li> <ul> <li> <span style="text-decoration: line-through;">key="0.0" type="error"</span> </li> <li> <span style="text-decoration: line-through;">key="0.1" type="error"</span> </li> <li class="async"> <span style="">Async</span> <ul> <li> <span style="">key="0.3" type="error"</span> <span ${key}="0.3" ${error} ${dInline}>Something wrong with username 'error'</span> </li> </ul> </li> <li> <span style="text-decoration: line-through;">key="0.2" type="whenValid"</span> </li> </ul> <input type="password" name="password"> <li>key="1" for="password" stop="first-error"</li> <ul> <li> <span style="text-decoration: line-through;">key="1.0" type="error"</span> </li> <li> <span style="text-decoration: line-through;">key="1.1" type="error"</span> </li> <li> <span style="text-decoration: line-through;">key="1.2" type="warning"</span> </li> <li> <span style="">key="1.3" type="warning"</span> <span ${key}="1.3" ${warning} ${dInline}>Should contain small letters</span> </li> <li> <span style="">key="1.4" type="warning"</span> <span ${key}="1.4" ${warning} ${dInline}>Should contain capital letters</span> </li> <li> <span style="">key="1.5" type="warning"</span> <span ${key}="1.5" ${warning} ${dInline}>Should contain special characters</span> </li> <li> <span style="text-decoration: line-through;">key="1.6" type="whenValid"</span> <span ${key}="1.6" ${whenValid} ${dBlock}>Looks good!</span> </li> </ul> <input type="password" name="passwordConfirm"> <li>key="2" for="passwordConfirm" stop="first-error"</li> <ul> <li> <span style="">key="2.0" type="error"</span> <span ${key}="2.0" ${error} ${dInline}>Not the same password</span> </li> <li> <span style="text-decoration: line-through;">key="2.1" type="whenValid"</span> </li> </ul> </form>`); wrapper.unmount(); }); });
the_stack
import {fixture} from '@open-wc/testing-helpers'; import {html} from 'lit'; import {SubmitRequirementResultInfo} from '../../../api/rest-api'; import {getAppContext} from '../../../services/app-context'; import '../../../test/common-test-setup-karma'; import { createAccountWithId, createChange, createSubmitRequirementExpressionInfo, createSubmitRequirementResultInfo, } from '../../../test/test-data-generators'; import {query, queryAndAssert, stubRestApi} from '../../../test/test-utils'; import { AccountId, BranchName, ChangeInfo, RepoName, TopicName, } from '../../../types/common'; import {StandardLabels} from '../../../utils/label-util'; import {GerritNav} from '../../core/gr-navigation/gr-navigation'; import {columnNames} from '../gr-change-list/gr-change-list'; import './gr-change-list-item'; import {GrChangeListItem, LabelCategory} from './gr-change-list-item'; const basicFixture = fixtureFromElement('gr-change-list-item'); suite('gr-change-list-item tests', () => { const account = createAccountWithId(); const change: ChangeInfo = { ...createChange(), internalHost: 'host', project: 'a/test/repo' as RepoName, topic: 'test-topic' as TopicName, branch: 'test-branch' as BranchName, }; let element: GrChangeListItem; setup(async () => { stubRestApi('getLoggedIn').returns(Promise.resolve(false)); element = basicFixture.instantiate(); await element.updateComplete; }); test('computeLabelCategory', () => { element.change = { ...change, labels: {}, }; assert.equal( element.computeLabelCategory('Verified'), LabelCategory.NOT_APPLICABLE ); element.change.labels = {Verified: {approved: account, value: 1}}; assert.equal( element.computeLabelCategory('Verified'), LabelCategory.APPROVED ); element.change.labels = {Verified: {rejected: account, value: -1}}; assert.equal( element.computeLabelCategory('Verified'), LabelCategory.REJECTED ); element.change.labels = {'Code-Review': {approved: account, value: 1}}; element.change.unresolved_comment_count = 1; assert.equal( element.computeLabelCategory('Code-Review'), LabelCategory.UNRESOLVED_COMMENTS ); element.change.labels = {'Code-Review': {value: 1}}; element.change.unresolved_comment_count = 0; assert.equal( element.computeLabelCategory('Code-Review'), LabelCategory.POSITIVE ); element.change.labels = {'Code-Review': {value: -1}}; assert.equal( element.computeLabelCategory('Code-Review'), LabelCategory.NEGATIVE ); element.change.labels = {'Code-Review': {value: -1}}; assert.equal( element.computeLabelCategory('Verified'), LabelCategory.NOT_APPLICABLE ); }); test('computeLabelClass', () => { element.change = { ...change, labels: {}, }; assert.equal( element.computeLabelClass('Verified'), 'cell label u-gray-background' ); element.change.labels = {Verified: {approved: account, value: 1}}; assert.equal(element.computeLabelClass('Verified'), 'cell label u-green'); element.change.labels = {Verified: {rejected: account, value: -1}}; assert.equal(element.computeLabelClass('Verified'), 'cell label u-red'); element.change.labels = {'Code-Review': {value: 1}}; assert.equal( element.computeLabelClass('Code-Review'), 'cell label u-green u-monospace' ); element.change.labels = {'Code-Review': {value: -1}}; assert.equal( element.computeLabelClass('Code-Review'), 'cell label u-monospace u-red' ); element.change.labels = {'Code-Review': {value: -1}}; assert.equal( element.computeLabelClass('Verified'), 'cell label u-gray-background' ); }); test('computeLabelTitle', () => { element.change = { ...change, labels: {}, }; assert.equal(element.computeLabelTitle('Verified'), 'Label not applicable'); element.change.labels = {Verified: {approved: {name: 'Diffy'}}}; assert.equal(element.computeLabelTitle('Verified'), 'Verified by Diffy'); element.change.labels = {Verified: {approved: {name: 'Diffy'}}}; assert.equal( element.computeLabelTitle('Code-Review'), 'Label not applicable' ); element.change.labels = {Verified: {rejected: {name: 'Diffy'}}}; assert.equal(element.computeLabelTitle('Verified'), 'Verified by Diffy'); element.change.labels = { 'Code-Review': {disliked: {name: 'Diffy'}, value: -1}, }; assert.equal( element.computeLabelTitle('Code-Review'), 'Code-Review by Diffy' ); element.change.labels = { 'Code-Review': {recommended: {name: 'Diffy'}, value: 1}, }; assert.equal( element.computeLabelTitle('Code-Review'), 'Code-Review by Diffy' ); element.change.labels = { 'Code-Review': {recommended: {name: 'Diffy'}, rejected: {name: 'Admin'}}, }; assert.equal( element.computeLabelTitle('Code-Review'), 'Code-Review by Admin' ); element.change.labels = { 'Code-Review': {approved: {name: 'Diffy'}, rejected: {name: 'Admin'}}, }; assert.equal( element.computeLabelTitle('Code-Review'), 'Code-Review by Admin' ); element.change.labels = { 'Code-Review': { recommended: {name: 'Diffy'}, disliked: {name: 'Admin'}, value: -1, }, }; assert.equal( element.computeLabelTitle('Code-Review'), 'Code-Review by Admin' ); element.change.labels = { 'Code-Review': { approved: {name: 'Diffy'}, disliked: {name: 'Admin'}, value: -1, }, }; assert.equal( element.computeLabelTitle('Code-Review'), 'Code-Review by Diffy' ); element.change.labels = {'Code-Review': {approved: account, value: 1}}; element.change.unresolved_comment_count = 1; assert.equal( element.computeLabelTitle('Code-Review'), '1 unresolved comment' ); element.change.labels = { 'Code-Review': {approved: {name: 'Diffy'}, value: 1}, }; element.change.unresolved_comment_count = 1; assert.equal( element.computeLabelTitle('Code-Review'), '1 unresolved comment,\nCode-Review by Diffy' ); element.change.labels = {'Code-Review': {approved: account, value: 1}}; element.change.unresolved_comment_count = 2; assert.equal( element.computeLabelTitle('Code-Review'), '2 unresolved comments' ); }); test('computeLabelIcon', () => { element.change = { ...change, labels: {}, }; assert.equal(element.computeLabelIcon('missingLabel'), ''); element.change.labels = {Verified: {approved: account, value: 1}}; assert.equal(element.computeLabelIcon('Verified'), 'gr-icons:check'); element.change.labels = {'Code-Review': {approved: account, value: 1}}; element.change.unresolved_comment_count = 1; assert.equal(element.computeLabelIcon('Code-Review'), 'gr-icons:comment'); }); test('computeLabelValue', () => { element.change = { ...change, labels: {}, }; assert.equal(element.computeLabelValue('Verified'), ''); element.change.labels = {Verified: {approved: account, value: 1}}; assert.equal(element.computeLabelValue('Verified'), '✓'); element.change.labels = {Verified: {value: 1}}; assert.equal(element.computeLabelValue('Verified'), '+1'); element.change.labels = {Verified: {value: -1}}; assert.equal(element.computeLabelValue('Verified'), '-1'); element.change.labels = {Verified: {approved: account}}; assert.equal(element.computeLabelValue('Verified'), '✓'); element.change.labels = {Verified: {rejected: account}}; assert.equal(element.computeLabelValue('Verified'), '✕'); }); test('no hidden columns', async () => { element.visibleChangeTableColumns = [ 'Subject', 'Status', 'Owner', 'Reviewers', 'Comments', 'Repo', 'Branch', 'Updated', 'Size', ' Status ', ]; await element.updateComplete; for (const column of columnNames) { const elementClass = '.' + column.trim().toLowerCase(); assert.isFalse( queryAndAssert(element, elementClass).hasAttribute('hidden') ); } }); test('repo column hidden', async () => { element.visibleChangeTableColumns = [ 'Subject', 'Status', 'Owner', 'Reviewers', 'Comments', 'Branch', 'Updated', 'Size', ' Status ', ]; await element.updateComplete; for (const column of columnNames) { const elementClass = '.' + column.trim().toLowerCase(); if (column === 'Repo') { assert.isNotOk(query(element, elementClass)); } else { assert.isOk(query(element, elementClass)); } } }); function checkComputeReviewers( userId: number | undefined, reviewerIds: number[], reviewerNames: (string | undefined)[], attSetIds: number[], expected: number[] ) { element.account = userId ? {_account_id: userId as AccountId} : null; element.change = { ...change, owner: { _account_id: 99 as AccountId, }, reviewers: { REVIEWER: [], }, attention_set: {}, }; for (let i = 0; i < reviewerIds.length; i++) { element.change!.reviewers.REVIEWER!.push({ _account_id: reviewerIds[i] as AccountId, name: reviewerNames[i], }); } attSetIds.forEach(id => (element.change!.attention_set![id] = {account})); const actual = element.computeReviewers().map(r => r._account_id); assert.deepEqual(actual, expected as AccountId[]); } test('compute reviewers', () => { checkComputeReviewers(undefined, [], [], [], []); checkComputeReviewers(1, [], [], [], []); checkComputeReviewers(1, [2], ['a'], [], [2]); checkComputeReviewers(1, [2, 3], [undefined, 'a'], [], [2, 3]); checkComputeReviewers(1, [2, 3], ['a', undefined], [], [3, 2]); checkComputeReviewers(1, [99], ['owner'], [], []); checkComputeReviewers( 1, [2, 3, 4, 5], ['b', 'a', 'd', 'c'], [3, 4], [3, 4, 2, 5] ); checkComputeReviewers( 1, [2, 3, 1, 4, 5], ['b', 'a', 'x', 'd', 'c'], [3, 4], [1, 3, 4, 2, 5] ); }); test('random column does not exist', async () => { element.visibleChangeTableColumns = ['Bad']; await element.updateComplete; const elementClass = '.bad'; assert.isNotOk(query(element, elementClass)); }); test('TShirt sizing tooltip', () => { element.change = { ...change, insertions: NaN, deletions: NaN, }; assert.equal(element.computeSizeTooltip(), 'Size unknown'); element.change = { ...change, insertions: 0, deletions: 0, }; assert.equal(element.computeSizeTooltip(), 'Size unknown'); element.change = { ...change, insertions: 1, deletions: 2, }; assert.equal(element.computeSizeTooltip(), 'added 1, removed 2 lines'); }); test('TShirt sizing', () => { element.change = { ...change, insertions: NaN, deletions: NaN, }; assert.equal(element.computeChangeSize(), null); element.change = { ...change, insertions: 1, deletions: 1, }; assert.equal(element.computeChangeSize(), 'XS'); element.change = { ...change, insertions: 9, deletions: 1, }; assert.equal(element.computeChangeSize(), 'S'); element.change = { ...change, insertions: 10, deletions: 200, }; assert.equal(element.computeChangeSize(), 'M'); element.change = { ...change, insertions: 99, deletions: 900, }; assert.equal(element.computeChangeSize(), 'L'); element.change = { ...change, insertions: 99, deletions: 999, }; assert.equal(element.computeChangeSize(), 'XL'); }); test('change params passed to gr-navigation', async () => { const navStub = sinon.stub(GerritNav); element.change = change; await element.updateComplete; assert.deepEqual(navStub.getUrlForChange.lastCall.args, [change]); assert.deepEqual(navStub.getUrlForProjectChanges.lastCall.args, [ change.project, true, change.internalHost, ]); assert.deepEqual(navStub.getUrlForBranch.lastCall.args, [ change.branch, change.project, undefined, change.internalHost, ]); assert.deepEqual(navStub.getUrlForTopic.lastCall.args, [ change.topic, change.internalHost, ]); }); test('computeRepoDisplay', () => { element.change = {...change}; assert.equal(element.computeRepoDisplay(), 'host/a/test/repo'); assert.equal(element.computeTruncatedRepoDisplay(), 'host/…/test/repo'); delete change.internalHost; element.change = {...change}; assert.equal(element.computeRepoDisplay(), 'a/test/repo'); assert.equal(element.computeTruncatedRepoDisplay(), '…/test/repo'); }); test('renders requirement with new submit requirements', async () => { sinon.stub(getAppContext().flagsService, 'isEnabled').returns(true); const submitRequirement: SubmitRequirementResultInfo = { ...createSubmitRequirementResultInfo(), name: StandardLabels.CODE_REVIEW, submittability_expression_result: { ...createSubmitRequirementExpressionInfo(), expression: 'label:Verified=MAX -label:Verified=MIN', }, }; const change: ChangeInfo = { ...createChange(), submit_requirements: [submitRequirement], unresolved_comment_count: 1, }; const element = await fixture<GrChangeListItem>( html`<gr-change-list-item .change=${change} .labelNames=${[StandardLabels.CODE_REVIEW]} ></gr-change-list-item>` ); const requirement = queryAndAssert(element, '.requirement'); expect(requirement).dom.to.equal(`<iron-icon class="check-circle-filled" icon="gr-icons:check-circle-filled"> </iron-icon>`); }); });
the_stack
import { EventEmitter } from 'events'; import { BN, stripHexPrefix } from 'ethereumjs-util'; import { Mutex } from 'async-mutex'; import { BaseController, BaseConfig, BaseState } from '../BaseController'; import type { PreferencesState } from '../user/PreferencesController'; import type { NetworkState, NetworkType } from '../network/NetworkController'; import { safelyExecute, handleFetch, toChecksumHexAddress, BNToHex, getFormattedIpfsUrl, } from '../util'; import { MAINNET, RINKEBY_CHAIN_ID, IPFS_DEFAULT_GATEWAY_URL, ERC721, ERC1155, } from '../constants'; import type { ApiCollectible, ApiCollectibleCreator, ApiCollectibleContract, ApiCollectibleLastSale, } from './CollectibleDetectionController'; import type { AssetsContractController } from './AssetsContractController'; import { compareCollectiblesMetadata } from './assetsUtil'; /** * @type Collectible * * Collectible representation * @property address - Hex address of a ERC721 contract * @property description - The collectible description * @property image - URI of custom collectible image associated with this tokenId * @property name - Name associated with this tokenId and contract address * @property tokenId - The collectible identifier * @property numberOfSales - Number of sales * @property backgroundColor - The background color to be displayed with the item * @property imagePreview - URI of a smaller image associated with this collectible * @property imageThumbnail - URI of a thumbnail image associated with this collectible * @property imageOriginal - URI of the original image associated with this collectible * @property animation - URI of a animation associated with this collectible * @property animationOriginal - URI of the original animation associated with this collectible * @property externalLink - External link containing additional information * @property creator - The collectible owner information object * @property isCurrentlyOwned - Boolean indicating whether the address/chainId combination where it's currently stored currently owns this collectible */ export interface Collectible extends CollectibleMetadata { tokenId: string; address: string; isCurrentlyOwned?: boolean; } /** * @type CollectibleContract * * Collectible contract information representation * @property name - Contract name * @property logo - Contract logo * @property address - Contract address * @property symbol - Contract symbol * @property description - Contract description * @property totalSupply - Total supply of collectibles * @property assetContractType - The collectible type, it could be `semi-fungible` or `non-fungible` * @property createdDate - Creation date * @property schemaName - The schema followed by the contract, it could be `ERC721` or `ERC1155` * @property externalLink - External link containing additional information */ export interface CollectibleContract { name?: string; logo?: string; address: string; symbol?: string; description?: string; totalSupply?: string; assetContractType?: string; createdDate?: string; schemaName?: string; externalLink?: string; } /** * @type CollectibleMetadata * * Collectible custom information * @property name - Collectible custom name * @property description - The collectible description * @property numberOfSales - Number of sales * @property backgroundColor - The background color to be displayed with the item * @property image - Image custom image URI * @property imagePreview - URI of a smaller image associated with this collectible * @property imageThumbnail - URI of a thumbnail image associated with this collectible * @property imageOriginal - URI of the original image associated with this collectible * @property animation - URI of a animation associated with this collectible * @property animationOriginal - URI of the original animation associated with this collectible * @property externalLink - External link containing additional information * @property creator - The collectible owner information object * @property standard - NFT standard name for the collectible, e.g., ERC-721 or ERC-1155 */ export interface CollectibleMetadata { name: string | null; description: string | null; image: string | null; standard: string | null; favorite?: boolean; numberOfSales?: number; backgroundColor?: string; imagePreview?: string; imageThumbnail?: string; imageOriginal?: string; animation?: string; animationOriginal?: string; externalLink?: string; creator?: ApiCollectibleCreator; lastSale?: ApiCollectibleLastSale; } interface DetectionParams { userAddress: string; chainId: string; } /** * @type CollectiblesConfig * * Collectibles controller configuration * @property networkType - Network ID as per net_version * @property selectedAddress - Vault selected address */ export interface CollectiblesConfig extends BaseConfig { networkType: NetworkType; selectedAddress: string; chainId: string; ipfsGateway: string; openSeaEnabled: boolean; useIPFSSubdomains: boolean; } /** * @type CollectiblesState * * Assets controller state * @property allCollectibleContracts - Object containing collectibles contract information * @property allCollectibles - Object containing collectibles per account and network * @property collectibleContracts - List of collectibles contracts associated with the active vault * @property collectibles - List of collectibles associated with the active vault * @property ignoredCollectibles - List of collectibles that should be ignored */ export interface CollectiblesState extends BaseState { allCollectibleContracts: { [key: string]: { [key: string]: CollectibleContract[] }; }; allCollectibles: { [key: string]: { [key: string]: Collectible[] } }; ignoredCollectibles: Collectible[]; } const ALL_COLLECTIBLES_STATE_KEY = 'allCollectibles'; const ALL_COLLECTIBLES_CONTRACTS_STATE_KEY = 'allCollectibleContracts'; /** * Controller that stores assets and exposes convenience methods */ export class CollectiblesController extends BaseController< CollectiblesConfig, CollectiblesState > { private mutex = new Mutex(); private getCollectibleApi(contractAddress: string, tokenId: string) { const { chainId } = this.config; switch (chainId) { case RINKEBY_CHAIN_ID: return `https://testnets-api.opensea.io/api/v1/asset/${contractAddress}/${tokenId}`; default: return `https://api.opensea.io/api/v1/asset/${contractAddress}/${tokenId}`; } } private getCollectibleContractInformationApi(contractAddress: string) { const { chainId } = this.config; switch (chainId) { case RINKEBY_CHAIN_ID: return `https://testnets-api.opensea.io/api/v1/asset_contract/${contractAddress}`; default: return `https://api.opensea.io/api/v1/asset_contract/${contractAddress}`; } } /** * Helper method to update nested state for allCollectibles and allCollectibleContracts. * * @param newCollection - the modified piece of state to update in the controller's store * @param baseStateKey - The root key in the store to update. * @param passedConfig - An object containing the selectedAddress and chainId that are passed through the auto-detection flow. * @param passedConfig.selectedAddress - the address passed through the collectible detection flow to ensure detected assets are stored to the correct account * @param passedConfig.chainId - the chainId passed through the collectible detection flow to ensure detected assets are stored to the correct account */ private updateNestedCollectibleState( newCollection: Collectible[] | CollectibleContract[], baseStateKey: 'allCollectibles' | 'allCollectibleContracts', passedConfig?: { selectedAddress: string; chainId: string }, ) { // We want to use the passedSelectedAddress and passedChainId when defined and not null // these values are passed through the collectible detection flow, meaning they may not // match as the currently configured values (which may be stale for this update) const address = passedConfig?.selectedAddress ?? this.config.selectedAddress; const chain = passedConfig?.chainId ?? this.config.chainId; const { [baseStateKey]: oldState } = this.state; const addressState = oldState[address]; const newAddressState = { ...addressState, ...{ [chain]: newCollection }, }; const newState = { ...oldState, ...{ [address]: newAddressState }, }; this.update({ [baseStateKey]: newState, }); } /** * Request individual collectible information from OpenSea API. * * @param contractAddress - Hex address of the collectible contract. * @param tokenId - The collectible identifier. * @returns Promise resolving to the current collectible name and image. */ private async getCollectibleInformationFromApi( contractAddress: string, tokenId: string, ): Promise<CollectibleMetadata> { const tokenURI = this.getCollectibleApi(contractAddress, tokenId); let collectibleInformation: ApiCollectible; /* istanbul ignore if */ if (this.openSeaApiKey) { collectibleInformation = await handleFetch(tokenURI, { headers: { 'X-API-KEY': this.openSeaApiKey }, }); } else { collectibleInformation = await handleFetch(tokenURI); } const { num_sales, background_color, image_url, image_preview_url, image_thumbnail_url, image_original_url, animation_url, animation_original_url, name, description, external_link, creator, last_sale, asset_contract: { schema_name }, } = collectibleInformation; /* istanbul ignore next */ const collectibleMetadata: CollectibleMetadata = Object.assign( {}, { name: name || null }, { description: description || null }, { image: image_url || null }, creator && { creator }, num_sales && { numberOfSales: num_sales }, background_color && { backgroundColor: background_color }, image_preview_url && { imagePreview: image_preview_url }, image_thumbnail_url && { imageThumbnail: image_thumbnail_url }, image_original_url && { imageOriginal: image_original_url }, animation_url && { animation: animation_url }, animation_original_url && { animationOriginal: animation_original_url, }, external_link && { externalLink: external_link }, last_sale && { lastSale: last_sale }, schema_name && { standard: schema_name }, ); return collectibleMetadata; } /** * Request individual collectible information from contracts that follows Metadata Interface. * * @param contractAddress - Hex address of the collectible contract. * @param tokenId - The collectible identifier. * @returns Promise resolving to the current collectible name and image. */ private async getCollectibleInformationFromTokenURI( contractAddress: string, tokenId: string, ): Promise<CollectibleMetadata> { const { ipfsGateway, useIPFSSubdomains } = this.config; const result = await this.getCollectibleURIAndStandard( contractAddress, tokenId, ); let tokenURI = result[0]; const standard = result[1]; if (tokenURI.startsWith('ipfs://')) { tokenURI = getFormattedIpfsUrl(ipfsGateway, tokenURI, useIPFSSubdomains); } try { const object = await handleFetch(tokenURI); // TODO: Check image_url existence. This is not part of EIP721 nor EIP1155 const image = Object.prototype.hasOwnProperty.call(object, 'image') ? 'image' : /* istanbul ignore next */ 'image_url'; return { image: object[image], name: object.name, description: object.description, standard, favorite: false, }; } catch { return { image: null, name: null, description: null, standard: standard || null, favorite: false, }; } } /** * Retrieve collectible uri with metadata. TODO Update method to use IPFS. * * @param contractAddress - Collectible contract address. * @param tokenId - Collectible token id. * @returns Promise resolving collectible uri and token standard. */ private async getCollectibleURIAndStandard( contractAddress: string, tokenId: string, ): Promise<[string, string]> { // try ERC721 uri try { const uri = await this.getCollectibleTokenURI(contractAddress, tokenId); return [uri, ERC721]; } catch { // Ignore error } // try ERC1155 uri try { const tokenURI = await this.uriERC1155Collectible( contractAddress, tokenId, ); /** * According to EIP1155 the URI value allows for ID substitution * in case the string `{id}` exists. * https://eips.ethereum.org/EIPS/eip-1155#metadata */ if (!tokenURI.includes('{id}')) { return [tokenURI, ERC1155]; } const hexTokenId = stripHexPrefix(BNToHex(new BN(tokenId))) .padStart(64, '0') .toLowerCase(); return [tokenURI.replace('{id}', hexTokenId), ERC1155]; } catch { // Ignore error } return ['', '']; } /** * Request individual collectible information (name, image url and description). * * @param contractAddress - Hex address of the collectible contract. * @param tokenId - The collectible identifier. * @returns Promise resolving to the current collectible name and image. */ private async getCollectibleInformation( contractAddress: string, tokenId: string, ): Promise<CollectibleMetadata> { const blockchainMetadata = await safelyExecute(async () => { return await this.getCollectibleInformationFromTokenURI( contractAddress, tokenId, ); }); let openSeaMetadata; if (this.config.openSeaEnabled) { openSeaMetadata = await safelyExecute(async () => { return await this.getCollectibleInformationFromApi( contractAddress, tokenId, ); }); } return { ...openSeaMetadata, name: blockchainMetadata.name ?? openSeaMetadata?.name ?? null, description: blockchainMetadata.description ?? openSeaMetadata?.description ?? null, image: blockchainMetadata.image ?? openSeaMetadata?.image ?? null, standard: blockchainMetadata.standard ?? openSeaMetadata?.standard ?? null, }; } /** * Request collectible contract information from OpenSea API. * * @param contractAddress - Hex address of the collectible contract. * @returns Promise resolving to the current collectible name and image. */ private async getCollectibleContractInformationFromApi( contractAddress: string, ): Promise<ApiCollectibleContract> { const api = this.getCollectibleContractInformationApi(contractAddress); let apiCollectibleContractObject: ApiCollectibleContract; /* istanbul ignore if */ if (this.openSeaApiKey) { apiCollectibleContractObject = await handleFetch(api, { headers: { 'X-API-KEY': this.openSeaApiKey }, }); } else { apiCollectibleContractObject = await handleFetch(api); } return apiCollectibleContractObject; } /** * Request collectible contract information from the contract itself. * * @param contractAddress - Hex address of the collectible contract. * @returns Promise resolving to the current collectible name and image. */ private async getCollectibleContractInformationFromContract( contractAddress: string, ): Promise< Partial<ApiCollectibleContract> & Pick<ApiCollectibleContract, 'address'> & Pick<ApiCollectibleContract, 'collection'> > { const name = await this.getAssetName(contractAddress); const symbol = await this.getAssetSymbol(contractAddress); return { collection: { name }, symbol, address: contractAddress, }; } /** * Request collectible contract information from OpenSea API. * * @param contractAddress - Hex address of the collectible contract. * @returns Promise resolving to the collectible contract name, image and description. */ private async getCollectibleContractInformation( contractAddress: string, ): Promise< Partial<ApiCollectibleContract> & Pick<ApiCollectibleContract, 'address'> & Pick<ApiCollectibleContract, 'collection'> > { const blockchainContractData: Partial<ApiCollectibleContract> & Pick<ApiCollectibleContract, 'address'> & Pick<ApiCollectibleContract, 'collection'> = await safelyExecute( async () => { return await this.getCollectibleContractInformationFromContract( contractAddress, ); }, ); let openSeaContractData: Partial<ApiCollectibleContract> | undefined; if (this.config.openSeaEnabled) { openSeaContractData = await safelyExecute(async () => { return await this.getCollectibleContractInformationFromApi( contractAddress, ); }); } if (blockchainContractData || openSeaContractData) { return { ...openSeaContractData, ...blockchainContractData, collection: { image_url: null, ...openSeaContractData?.collection, ...blockchainContractData?.collection, }, }; } /* istanbul ignore next */ return { address: contractAddress, asset_contract_type: null, created_date: null, schema_name: null, symbol: null, total_supply: null, description: null, external_link: null, collection: { name: null, image_url: null }, }; } /** * Adds an individual collectible to the stored collectible list. * * @param address - Hex address of the collectible contract. * @param tokenId - The collectible identifier. * @param collectibleMetadata - Collectible optional information (name, image and description). * @param detection - The chain ID and address of the currently selected network and account at the moment the collectible was detected. * @returns Promise resolving to the current collectible list. */ private async addIndividualCollectible( address: string, tokenId: string, collectibleMetadata: CollectibleMetadata, detection?: DetectionParams, ): Promise<Collectible[]> { // TODO: Remove unused return const releaseLock = await this.mutex.acquire(); try { address = toChecksumHexAddress(address); const { allCollectibles } = this.state; let chainId, selectedAddress; if (detection) { chainId = detection.chainId; selectedAddress = detection.userAddress; } else { chainId = this.config.chainId; selectedAddress = this.config.selectedAddress; } const collectibles = allCollectibles[selectedAddress]?.[chainId] || []; const existingEntry: Collectible | undefined = collectibles.find( (collectible) => collectible.address.toLowerCase() === address.toLowerCase() && collectible.tokenId === tokenId, ); if (existingEntry) { const differentMetadata = compareCollectiblesMetadata( collectibleMetadata, existingEntry, ); if (differentMetadata) { // TODO: Switch to indexToUpdate const indexToRemove = collectibles.findIndex( (collectible) => collectible.address.toLowerCase() === address.toLowerCase() && collectible.tokenId === tokenId, ); /* istanbul ignore next */ if (indexToRemove !== -1) { collectibles.splice(indexToRemove, 1); } } else { return collectibles; } } const newEntry: Collectible = { address, tokenId, favorite: existingEntry?.favorite || false, isCurrentlyOwned: true, ...collectibleMetadata, }; const newCollectibles = [...collectibles, newEntry]; this.updateNestedCollectibleState( newCollectibles, ALL_COLLECTIBLES_STATE_KEY, { chainId, selectedAddress }, ); return newCollectibles; } finally { releaseLock(); } } /** * Adds a collectible contract to the stored collectible contracts list. * * @param address - Hex address of the collectible contract. * @param detection - The chain ID and address of the currently selected network and account at the moment the collectible was detected. * @returns Promise resolving to the current collectible contracts list. */ private async addCollectibleContract( address: string, detection?: DetectionParams, ): Promise<CollectibleContract[]> { const releaseLock = await this.mutex.acquire(); try { address = toChecksumHexAddress(address); const { allCollectibleContracts } = this.state; let chainId, selectedAddress; if (detection) { chainId = detection.chainId; selectedAddress = detection.userAddress; } else { chainId = this.config.chainId; selectedAddress = this.config.selectedAddress; } const collectibleContracts = allCollectibleContracts[selectedAddress]?.[chainId] || []; const existingEntry = collectibleContracts.find( (collectibleContract) => collectibleContract.address.toLowerCase() === address.toLowerCase(), ); if (existingEntry) { return collectibleContracts; } const contractInformation = await this.getCollectibleContractInformation( address, ); const { asset_contract_type, created_date, schema_name, symbol, total_supply, description, external_link, collection: { name, image_url }, } = contractInformation; // If being auto-detected opensea information is expected // Otherwise at least name and symbol from contract is needed if ( (detection && !name) || Object.keys(contractInformation).length === 0 ) { return collectibleContracts; } /* istanbul ignore next */ const newEntry: CollectibleContract = Object.assign( {}, { address }, description && { description }, name && { name }, image_url && { logo: image_url }, symbol && { symbol }, total_supply !== null && typeof total_supply !== 'undefined' && { totalSupply: total_supply }, asset_contract_type && { assetContractType: asset_contract_type }, created_date && { createdDate: created_date }, schema_name && { schemaName: schema_name }, external_link && { externalLink: external_link }, ); const newCollectibleContracts = [...collectibleContracts, newEntry]; this.updateNestedCollectibleState( newCollectibleContracts, ALL_COLLECTIBLES_CONTRACTS_STATE_KEY, { chainId, selectedAddress }, ); return newCollectibleContracts; } finally { releaseLock(); } } /** * Removes an individual collectible from the stored token list and saves it in ignored collectibles list. * * @param address - Hex address of the collectible contract. * @param tokenId - Token identifier of the collectible. */ private removeAndIgnoreIndividualCollectible( address: string, tokenId: string, ) { address = toChecksumHexAddress(address); const { allCollectibles, ignoredCollectibles } = this.state; const { chainId, selectedAddress } = this.config; const newIgnoredCollectibles = [...ignoredCollectibles]; const collectibles = allCollectibles[selectedAddress]?.[chainId] || []; const newCollectibles = collectibles.filter((collectible) => { if ( collectible.address.toLowerCase() === address.toLowerCase() && collectible.tokenId === tokenId ) { const alreadyIgnored = newIgnoredCollectibles.find( (c) => c.address === address && c.tokenId === tokenId, ); !alreadyIgnored && newIgnoredCollectibles.push(collectible); return false; } return true; }); this.updateNestedCollectibleState( newCollectibles, ALL_COLLECTIBLES_STATE_KEY, ); this.update({ ignoredCollectibles: newIgnoredCollectibles, }); } /** * Removes an individual collectible from the stored token list. * * @param address - Hex address of the collectible contract. * @param tokenId - Token identifier of the collectible. */ private removeIndividualCollectible(address: string, tokenId: string) { address = toChecksumHexAddress(address); const { allCollectibles } = this.state; const { chainId, selectedAddress } = this.config; const collectibles = allCollectibles[selectedAddress]?.[chainId] || []; const newCollectibles = collectibles.filter( (collectible) => !( collectible.address.toLowerCase() === address.toLowerCase() && collectible.tokenId === tokenId ), ); this.updateNestedCollectibleState( newCollectibles, ALL_COLLECTIBLES_STATE_KEY, ); } /** * Removes a collectible contract to the stored collectible contracts list. * * @param address - Hex address of the collectible contract. * @returns Promise resolving to the current collectible contracts list. */ private removeCollectibleContract(address: string): CollectibleContract[] { address = toChecksumHexAddress(address); const { allCollectibleContracts } = this.state; const { chainId, selectedAddress } = this.config; const collectibleContracts = allCollectibleContracts[selectedAddress]?.[chainId] || []; const newCollectibleContracts = collectibleContracts.filter( (collectibleContract) => !(collectibleContract.address.toLowerCase() === address.toLowerCase()), ); this.updateNestedCollectibleState( newCollectibleContracts, ALL_COLLECTIBLES_CONTRACTS_STATE_KEY, ); return newCollectibleContracts; } /** * EventEmitter instance used to listen to specific EIP747 events */ hub = new EventEmitter(); /** * Optional API key to use with opensea */ openSeaApiKey?: string; /** * Name of this controller used during composition */ name = 'CollectiblesController'; private getAssetName: AssetsContractController['getAssetName']; private getAssetSymbol: AssetsContractController['getAssetSymbol']; private getCollectibleTokenURI: AssetsContractController['getCollectibleTokenURI']; private getOwnerOf: AssetsContractController['getOwnerOf']; private balanceOfERC1155Collectible: AssetsContractController['balanceOfERC1155Collectible']; private uriERC1155Collectible: AssetsContractController['uriERC1155Collectible']; /** * Creates a CollectiblesController instance. * * @param options - The controller options. * @param options.onPreferencesStateChange - Allows subscribing to preference controller state changes. * @param options.onNetworkStateChange - Allows subscribing to network controller state changes. * @param options.getAssetName - Gets the name of the asset at the given address. * @param options.getAssetSymbol - Gets the symbol of the asset at the given address. * @param options.getCollectibleTokenURI - Gets the URI of the ERC721 token at the given address, with the given ID. * @param options.getOwnerOf - Get the owner of a ERC-721 collectible. * @param options.balanceOfERC1155Collectible - Gets balance of a ERC-1155 collectible. * @param options.uriERC1155Collectible - Gets the URI of the ERC1155 token at the given address, with the given ID. * @param config - Initial options used to configure this controller. * @param state - Initial state to set on this controller. */ constructor( { onPreferencesStateChange, onNetworkStateChange, getAssetName, getAssetSymbol, getCollectibleTokenURI, getOwnerOf, balanceOfERC1155Collectible, uriERC1155Collectible, }: { onPreferencesStateChange: ( listener: (preferencesState: PreferencesState) => void, ) => void; onNetworkStateChange: ( listener: (networkState: NetworkState) => void, ) => void; getAssetName: AssetsContractController['getAssetName']; getAssetSymbol: AssetsContractController['getAssetSymbol']; getCollectibleTokenURI: AssetsContractController['getCollectibleTokenURI']; getOwnerOf: AssetsContractController['getOwnerOf']; balanceOfERC1155Collectible: AssetsContractController['balanceOfERC1155Collectible']; uriERC1155Collectible: AssetsContractController['uriERC1155Collectible']; }, config?: Partial<BaseConfig>, state?: Partial<CollectiblesState>, ) { super(config, state); this.defaultConfig = { networkType: MAINNET, selectedAddress: '', chainId: '', ipfsGateway: IPFS_DEFAULT_GATEWAY_URL, openSeaEnabled: false, useIPFSSubdomains: true, }; this.defaultState = { allCollectibleContracts: {}, allCollectibles: {}, ignoredCollectibles: [], }; this.initialize(); this.getAssetName = getAssetName; this.getAssetSymbol = getAssetSymbol; this.getCollectibleTokenURI = getCollectibleTokenURI; this.getOwnerOf = getOwnerOf; this.balanceOfERC1155Collectible = balanceOfERC1155Collectible; this.uriERC1155Collectible = uriERC1155Collectible; onPreferencesStateChange( ({ selectedAddress, ipfsGateway, openSeaEnabled }) => { this.configure({ selectedAddress, ipfsGateway, openSeaEnabled }); }, ); onNetworkStateChange(({ provider }) => { const { chainId } = provider; this.configure({ chainId }); }); } /** * Sets an OpenSea API key to retrieve collectible information. * * @param openSeaApiKey - OpenSea API key. */ setApiKey(openSeaApiKey: string) { this.openSeaApiKey = openSeaApiKey; } /** * Checks the ownership of a ERC-721 or ERC-1155 collectible for a given address. * * @param ownerAddress - User public address. * @param collectibleAddress - Collectible contract address. * @param collectibleId - Collectible token ID. * @returns Promise resolving the collectible ownership. */ async isCollectibleOwner( ownerAddress: string, collectibleAddress: string, collectibleId: string, ): Promise<boolean> { // Checks the ownership for ERC-721. try { const owner = await this.getOwnerOf(collectibleAddress, collectibleId); return ownerAddress.toLowerCase() === owner.toLowerCase(); // eslint-disable-next-line no-empty } catch { // Ignore ERC-721 contract error } // Checks the ownership for ERC-1155. try { const balance = await this.balanceOfERC1155Collectible( ownerAddress, collectibleAddress, collectibleId, ); return balance > 0; // eslint-disable-next-line no-empty } catch { // Ignore ERC-1155 contract error } throw new Error( 'Unable to verify ownership. Probably because the standard is not supported or the chain is incorrect.', ); } /** * Verifies currently selected address owns entered collectible address/tokenId combo and * adds the collectible and respective collectible contract to the stored collectible and collectible contracts lists. * * @param address - Hex address of the collectible contract. * @param tokenId - The collectible identifier. */ async addCollectibleVerifyOwnership(address: string, tokenId: string) { const { selectedAddress } = this.config; if (!(await this.isCollectibleOwner(selectedAddress, address, tokenId))) { throw new Error('This collectible is not owned by the user'); } await this.addCollectible(address, tokenId); } /** * Adds a collectible and respective collectible contract to the stored collectible and collectible contracts lists. * * @param address - Hex address of the collectible contract. * @param tokenId - The collectible identifier. * @param collectibleMetadata - Collectible optional metadata. * @param detection - The chain ID and address of the currently selected network and account at the moment the collectible was detected. * @returns Promise resolving to the current collectible list. */ async addCollectible( address: string, tokenId: string, collectibleMetadata?: CollectibleMetadata, detection?: DetectionParams, ) { address = toChecksumHexAddress(address); const newCollectibleContracts = await this.addCollectibleContract( address, detection, ); collectibleMetadata = collectibleMetadata || (await this.getCollectibleInformation(address, tokenId)); // If collectible contract was not added, do not add individual collectible const collectibleContract = newCollectibleContracts.find( (contract) => contract.address.toLowerCase() === address.toLowerCase(), ); // If collectible contract information, add individual collectible if (collectibleContract) { await this.addIndividualCollectible( address, tokenId, collectibleMetadata, detection, ); } } /** * Removes a collectible from the stored token list. * * @param address - Hex address of the collectible contract. * @param tokenId - Token identifier of the collectible. */ removeCollectible(address: string, tokenId: string) { address = toChecksumHexAddress(address); this.removeIndividualCollectible(address, tokenId); const { allCollectibles } = this.state; const { chainId, selectedAddress } = this.config; const collectibles = allCollectibles[selectedAddress]?.[chainId] || []; const remainingCollectible = collectibles.find( (collectible) => collectible.address.toLowerCase() === address.toLowerCase(), ); if (!remainingCollectible) { this.removeCollectibleContract(address); } } /** * Removes a collectible from the stored token list and saves it in ignored collectibles list. * * @param address - Hex address of the collectible contract. * @param tokenId - Token identifier of the collectible. */ removeAndIgnoreCollectible(address: string, tokenId: string) { address = toChecksumHexAddress(address); this.removeAndIgnoreIndividualCollectible(address, tokenId); const { allCollectibles } = this.state; const { chainId, selectedAddress } = this.config; const collectibles = allCollectibles[selectedAddress]?.[chainId] || []; const remainingCollectible = collectibles.find( (collectible) => collectible.address.toLowerCase() === address.toLowerCase(), ); if (!remainingCollectible) { this.removeCollectibleContract(address); } } /** * Removes all collectibles from the ignored list. */ clearIgnoredCollectibles() { this.update({ ignoredCollectibles: [] }); } /** * Checks whether input collectible is still owned by the user * And updates the isCurrentlyOwned value on the collectible object accordingly. * * @param collectible - The collectible object to check and update. * @param batch - A boolean indicating whether this method is being called as part of a batch or single update. * @returns the collectible with the updated isCurrentlyOwned value */ async checkAndUpdateSingleCollectibleOwnershipStatus( collectible: Collectible, batch: boolean, ) { const { allCollectibles } = this.state; const { selectedAddress, chainId } = this.config; const { address, tokenId } = collectible; let isOwned = collectible.isCurrentlyOwned; try { isOwned = await this.isCollectibleOwner( selectedAddress, address, tokenId, ); } catch (error) { if (!error.message.includes('Unable to verify ownership')) { throw error; } } collectible.isCurrentlyOwned = isOwned; if (batch === true) { return collectible; } // if this is not part of a batched update we update this one collectible in state const collectibles = allCollectibles[selectedAddress]?.[chainId] || []; const collectibleToUpdate = collectibles.find( (item) => item.tokenId === tokenId && item.address === address, ); if (collectibleToUpdate) { collectibleToUpdate.isCurrentlyOwned = isOwned; this.updateNestedCollectibleState( collectibles, ALL_COLLECTIBLES_STATE_KEY, ); } return collectible; } /** * Checks whether Collectibles associated with current selectedAddress/chainId combination are still owned by the user * And updates the isCurrentlyOwned value on each accordingly. */ async checkAndUpdateAllCollectiblesOwnershipStatus() { const { allCollectibles } = this.state; const { chainId, selectedAddress } = this.config; const collectibles = allCollectibles[selectedAddress]?.[chainId] || []; const updatedCollectibles = await Promise.all( collectibles.map(async (collectible) => { return ( (await this.checkAndUpdateSingleCollectibleOwnershipStatus( collectible, true, )) ?? collectible ); }), ); this.updateNestedCollectibleState( updatedCollectibles, ALL_COLLECTIBLES_STATE_KEY, ); } /** * Update collectible favorite status. * * @param address - Hex address of the collectible contract. * @param tokenId - Hex address of the collectible contract. * @param favorite - Collectible new favorite status. */ updateCollectibleFavoriteStatus( address: string, tokenId: string, favorite: boolean, ) { const { allCollectibles } = this.state; const { chainId, selectedAddress } = this.config; const collectibles = allCollectibles[selectedAddress]?.[chainId] || []; const index: number = collectibles.findIndex( (collectible) => collectible.address === address && collectible.tokenId === tokenId, ); if (index === -1) { return; } const updatedCollectible: Collectible = { ...collectibles[index], favorite, }; // Update Collectibles array collectibles[index] = updatedCollectible; this.updateNestedCollectibleState(collectibles, ALL_COLLECTIBLES_STATE_KEY); } } export default CollectiblesController;
the_stack
import Vector4 = BABYLON.Vector2; module ManipulationHelpers { import Vector2 = BABYLON.Vector2; import Vector3 = BABYLON.Vector3; import Matrix = BABYLON.Matrix; import Ray = BABYLON.Ray; import Plane = BABYLON.Plane; import Scene = BABYLON.Scene; import Node = BABYLON.Node; import AbstractMesh = BABYLON.AbstractMesh; import Quaternion = BABYLON.Quaternion; import EventState = BABYLON.EventState; import PointerInfo = BABYLON.PointerInfo; import PointerEventTypes = BABYLON.PointerEventTypes; /** * This class is used to manipulated a single node. * Right now only node of type AbstractMesh is support. * In the future, manipulation on multiple selection could be possible. * * A manipulation start when left clicking and moving the mouse. It can be cancelled if the right mouse button is clicked before releasing the left one (this feature is only possible if noPreventContextMenu is false). * Per default translation is peformed when manipulating the arrow (axis or cone) or the plane anchor. If you press the shift key it will switch to rotation manipulation. The Shift key can be toggle while manipulating, the current manipulation is accept and a new one starts. * * You can set the rotation/translationStep (in radian) to enable snapping. * * The current implementation of this class creates a radix with all the features selected. */ export class ManipulatorInteractionHelper { /** * Rotation Step in Radian to perform rotation with the given step instead of a smooth one. * Set back to null/undefined to disable */ rotationStep: number; /** * Translation Step in World unit to perform translation at the given step instread of a smooth one. * Set back to null/undefined to disable */ translationStep: number; /** * Set to true if you want the context menu to be displayed while manipulating. The manipulation cancel feature (which is triggered by a right click) won't work in this case. Default value is false (context menu is not showed when right clicking during manipulation) and this should fit most of the cases. */ noPreventContextMenu: boolean; /** * Attach a node to manipulate. Right now, only manipulation on a single node is supported, but this api will allow manipulation on a multiple selection in the future. * @param node */ attachManipulatedNode(node: Node) { this._manipulatedNode = node; this._radix.show(); } /** * Detach the node to manipulate. Right now, only manipulation on a single node is supported, but this api will allow manipulation on a multiple selection in the future. */ detachManipulatedNode(node: Node) { this._manipulatedNode = null; this._radix.hide(); } constructor(scene: Scene) { this.noPreventContextMenu = false; this._flags = 0; this._rotationFactor = 1; this._scene = scene; this._radix = new Radix(scene); this._shiftKeyState = false; this._scene.onBeforeRenderObservable.add((e, s) => this.onBeforeRender(e, s)); this._scene.onPointerObservable.add((e, s) => this.onPointer(e, s), -1, true); window.oncontextmenu = ev => { if (!this.noPreventContextMenu) { ev.preventDefault(); } }; } private onBeforeRender(scene: Scene, state: EventState) { this.renderManipulator(); } private onPointer(e: PointerInfo, state: EventState) { if (!this._manipulatedNode) { return; } var rayPos = this.getRayPosition(e.event); var shiftKeyState = e.event.shiftKey; // Detect Modifier Key changes for shift while manipulating: commit and start a new manipulation if (this.hasManFlags(ManFlags.DragMode) && shiftKeyState !== this._shiftKeyState) { this.beginDrag(rayPos, <PointerEvent>e.event); } // Mouse move if (e.type === PointerEventTypes.POINTERMOVE) { // Right button release while left is down => cancel the manipulation. only processed when the context menu is not showed during manipulation if (!this.noPreventContextMenu && e.event.button === 2 && e.event.buttons === 1) { this.setManipulatedNodeWorldMatrix(this._firstTransform); this.setManFlags(ManFlags.Exiting); } else if (this.hasManFlags(ManFlags.DragMode) && !this.hasManFlags(ManFlags.Exiting)) { state.skipNextObservers = true; if (shiftKeyState || this.hasManipulatedMode(RadixFeatures.Rotations)) { this.doRot(rayPos); } else { this.doPos(rayPos); } } else { this._radix.highlighted = this._radix.intersect(rayPos); } } // Left button down else if (e.type === PointerEventTypes.POINTERDOWN && e.event.button === 0) { this._manipulatedMode = this._radix.intersect(rayPos); if (this._manipulatedMode !== RadixFeatures.None) { state.skipNextObservers = true; this.beginDrag(rayPos, <PointerEvent>e.event); if (this.hasManipulatedMode(RadixFeatures.Rotations)) { this.doRot(rayPos); } else { this.doPos(rayPos); } } } else if (e.type === PointerEventTypes.POINTERUP) { if (this.hasManFlags(ManFlags.DragMode)) { state.skipNextObservers = true; } this._radix.highlighted = this._radix.intersect(rayPos); // Left up: end manipulation if (e.event.button === 0) { this.endDragMode(); } } } private beginDrag(rayPos: Vector2, event: PointerEvent) { this._firstMousePos = rayPos; this._prevMousePos = this._firstMousePos.clone(); this._shiftKeyState = event.shiftKey; var mtx = this.getManipulatedNodeWorldMatrix(); this._pos = mtx.getTranslation(); this._right = mtx.getRow(0).toVector3(); this._up = mtx.getRow(1).toVector3(); this._view = mtx.getRow(2).toVector3(); this._oldPos = this._pos.clone(); this._firstTransform = mtx.clone(); this._flags |= ManFlags.FirstHit | ManFlags.DragMode; } private endDragMode() { this.clearManFlags(ManFlags.DragMode | ManFlags.Exiting); } private doRot(rayPos: Vector2) { if (this.hasManFlags(ManFlags.FirstHit)) { this.clearManFlags(ManFlags.FirstHit); return; } var dx = rayPos.x - this._prevMousePos.x; var dy = rayPos.y - this._prevMousePos.y; var cr = this._scene.getEngine().getRenderingCanvasClientRect(); var ax = (dx / cr.width) * Math.PI * 2 * this._rotationFactor; var ay = (dy / cr.height) * Math.PI * 2 * this._rotationFactor; if (this.rotationStep) { var rem = ax % this.rotationStep; ax -= rem; rem = ay % this.rotationStep; ay -= rem; } var mtx = Matrix.Identity(); if (this.hasManipulatedMode(RadixFeatures.ArrowX | RadixFeatures.RotationX)) { mtx = Matrix.RotationX(ay); } else if (this.hasManipulatedMode(RadixFeatures.ArrowY | RadixFeatures.RotationY)) { mtx = Matrix.RotationY(ay); } else if (this.hasManipulatedMode(RadixFeatures.ArrowZ | RadixFeatures.RotationZ)) { mtx = Matrix.RotationZ(ay); } else { if (this.hasManipulatedMode(/*RadixFeatures.CenterSquare |*/ RadixFeatures.PlaneSelectionXY | RadixFeatures.PlaneSelectionXZ)) { mtx = mtx.multiply(Matrix.RotationX(ay)); } if (this.hasManipulatedMode(RadixFeatures.PlaneSelectionXY | RadixFeatures.PlaneSelectionYZ)) { mtx = mtx.multiply(Matrix.RotationY(ax)); } if (this.hasManipulatedMode(RadixFeatures.PlaneSelectionXZ)) { mtx = mtx.multiply(Matrix.RotationZ(ay)); } if (this.hasManipulatedMode(/*RadixFeatures.CenterSquare |*/ RadixFeatures.PlaneSelectionXZ)) { mtx = mtx.multiply(Matrix.RotationZ(ax)); } } var tmtx = mtx.multiply(this._firstTransform); this.setManipulatedNodeWorldMatrix(tmtx); } private doPos(rayPos: Vector2) { var v = Vector3.Zero(); var ray = this._scene.createPickingRay(rayPos.x, rayPos.y, Matrix.Identity(), this._scene.activeCamera); if (this.hasManipulatedMode(RadixFeatures.PlaneSelectionXY | RadixFeatures.PlaneSelectionXZ | RadixFeatures.PlaneSelectionYZ)) { var pl0: Plane; var hit: Vector3; if (this.hasManipulatedMode(RadixFeatures.PlaneSelectionXY)) { pl0 = Plane.FromPoints(this._pos, this._pos.add(this._right), this._pos.add(this._up)); } else if (this.hasManipulatedMode(RadixFeatures.PlaneSelectionXZ)) { pl0 = Plane.FromPoints(this._pos, this._pos.add(this._right), this._pos.add(this._view)); } else if (this.hasManipulatedMode(RadixFeatures.PlaneSelectionYZ)) { pl0 = Plane.FromPoints(this._pos, this._pos.add(this._up), this._pos.add(this._view)); } else { // TODO Exception } var clip = 0.06; //Check if the plane is too parallel to the ray if (Math.abs(Vector3.Dot(pl0.normal, ray.direction)) < clip) { return; } //Make the intersection let distance = ray.intersectsPlane(pl0); hit = ManipulatorInteractionHelper.ComputeRayHit(ray, distance); //Check if it's the first call if (this.hasManFlags(ManFlags.FirstHit)) { this._flags &= ~ManFlags.FirstHit; this._prevHit = hit; return; } //Compute the vector v = hit.subtract(this._prevHit); } else if ((this._manipulatedMode & (RadixFeatures.ArrowX | RadixFeatures.ArrowY | RadixFeatures.ArrowZ)) !== 0) { var pl0: Plane, pl1: Plane; var hit: Vector3; var s: number; if (this.hasManFlags(ManFlags.FirstHit)) { let res = this.setupIntersectionPlanes(this._manipulatedMode); pl0 = res.p0; pl1 = res.p1; if (Math.abs(Vector3.Dot(pl0.normal, ray.direction)) > Math.abs(Vector3.Dot(pl1.normal, ray.direction))) { let distance = ray.intersectsPlane(pl0); hit = ManipulatorInteractionHelper.ComputeRayHit(ray, distance); let number = ~ManFlags.Plane2; this._flags &= number; } else { let distance = ray.intersectsPlane(pl1); hit = ManipulatorInteractionHelper.ComputeRayHit(ray, distance); this._flags |= ManFlags.Plane2; } this._flags &= ~ManFlags.FirstHit; this._prevHit = hit; return; } else { var axis: Vector3; let res = this.setupIntersectionPlane(this._manipulatedMode, this.hasManFlags(ManFlags.Plane2)); pl0 = res.plane; axis = res.axis; let distance = ray.intersectsPlane(pl0); hit = ManipulatorInteractionHelper.ComputeRayHit(ray, distance); v = hit.subtract(this._prevHit); s = Vector3.Dot(axis, v); v = axis.multiplyByFloats(s, s, s); } } if (this.translationStep) { v.x -= v.x % this.translationStep; v.y -= v.y % this.translationStep; v.z -= v.z % this.translationStep; } var mtx = this._firstTransform.clone(); mtx.setTranslation(mtx.getTranslation().add(v)); this._pos = mtx.getTranslation(); this.setManipulatedNodeWorldMatrix(mtx); } private hasManipulatedMode(value: RadixFeatures): boolean { return (this._manipulatedMode & value) !== 0; } private hasManFlags(value: ManFlags): boolean { return (this._flags & value) !== 0; } private clearManFlags(values: ManFlags): ManFlags { this._flags &= ~values; return this._flags; } private setManFlags(values: ManFlags): ManFlags { this._flags |= values; return this._flags; } private static ComputeRayHit(ray: Ray, distance: number): Vector3 { return ray.origin.add(ray.direction.multiplyByFloats(distance, distance, distance)); } private setManipulatedNodeWorldMatrix(mtx: Matrix) { if (!this._manipulatedNode) { return; } if (this._manipulatedNode instanceof AbstractMesh) { var mesh = <AbstractMesh>this._manipulatedNode; if (mesh.parent) { mtx = mtx.multiply(mesh.parent.getWorldMatrix().clone().invert()); } var pos = Vector3.Zero(); var scale = Vector3.Zero(); var rot = new Quaternion(); mtx.decompose(scale, rot, pos); mesh.position = pos; mesh.rotationQuaternion = rot; mesh.scaling = scale; } } private getManipulatedNodeWorldMatrix(): Matrix { if (!this._manipulatedNode) { return null; } if (this._manipulatedNode instanceof AbstractMesh) { return this._manipulatedNode.getWorldMatrix(); } } private setupIntersectionPlane(mode: RadixFeatures, plane2: boolean): any { var res = this.setupIntersectionPlanes(mode); var pl = plane2 ? res.p1 : res.p0; var axis: Vector3; switch (mode) { case RadixFeatures.ArrowX: axis = this._right; break; case RadixFeatures.ArrowY: axis = this._up; break; case RadixFeatures.ArrowZ: axis = this._view; break; default: axis = Vector3.Zero(); break; } return { plane: pl, axis: axis }; } private setupIntersectionPlanes(mode: RadixFeatures): any { var p0: Plane, p1: Plane; switch (mode) { case RadixFeatures.ArrowX: p0 = Plane.FromPoints(this._pos, this._pos.add(this._view), this._pos.add(this._right)); p1 = Plane.FromPoints(this._pos, this._pos.add(this._right), this._pos.add(this._up)); break; case RadixFeatures.ArrowY: p0 = Plane.FromPoints(this._pos, this._pos.add(this._up), this._pos.add(this._right)); p1 = Plane.FromPoints(this._pos, this._pos.add(this._up), this._pos.add(this._view)); break; case RadixFeatures.ArrowZ: p0 = Plane.FromPoints(this._pos, this._pos.add(this._view), this._pos.add(this._right)); p1 = Plane.FromPoints(this._pos, this._pos.add(this._view), this._pos.add(this._up)); break; } return { p0: p0, p1: p1 }; } private getRayPosition(event: MouseEvent): Vector2 { var canvasRect = this._scene.getEngine().getRenderingCanvasClientRect(); var x = event.clientX - canvasRect.left; var y = event.clientY - canvasRect.top; return new Vector2(x, y); } private renderManipulator() { if (!this._manipulatedNode) { return; } if (this._manipulatedNode instanceof AbstractMesh) { var mesh = <AbstractMesh>this._manipulatedNode; var worldMtx = mesh.getWorldMatrix(); var l = Vector3.Distance(this._scene.activeCamera.position, worldMtx.getTranslation()); let vpWidth = this._scene.getEngine().getRenderWidth(); var s = this.fromScreenToWorld(vpWidth / 100, l) * 20; var scale = Vector3.Zero(); var position = Vector3.Zero(); var rotation = Quaternion.Identity(); var res = Matrix.Scaling(s, s, s).multiply(worldMtx); res.decompose(scale, rotation, position); this._radix.setWorld(position, rotation, scale); } } private fromScreenToWorld(l: number, z: number): number { let camera = this._scene.activeCamera; let r0 = this._scene.createPickingRay(0, 0, Matrix.Identity(), camera, true); let r1 = this._scene.createPickingRay(l, 0, Matrix.Identity(), camera, true); var p0 = ManipulatorInteractionHelper.evalPosition(r0, z); var p1 = ManipulatorInteractionHelper.evalPosition(r1, z); return p1.x - p0.x; } private static evalPosition(ray: Ray, u: number): Vector3 { return ray.origin.add(ray.direction.multiplyByFloats(u, u, u)); } private _flags: ManFlags; private _firstMousePos: Vector2; private _prevMousePos: Vector2; private _shiftKeyState: boolean; private _pos: Vector3; private _right: Vector3; private _up: Vector3; private _view: Vector3; private _oldPos: Vector3; private _prevHit: Vector3; private _firstTransform: Matrix; private _scene: Scene; private _manipulatedMode: RadixFeatures; private _rotationFactor: number; private _manipulatedNode: Node; private _radix: Radix; } const enum ManFlags { DragMode = 0x01, FirstHit = 0x02, Plane2 = 0x04, Exiting = 0x08 } }
the_stack
import { Cost } from './cost'; import { GameModel } from './gameModel'; import { Unit } from './units/unit'; import { Base } from './units/base'; import { Action } from './units/action'; import { TypeList } from './typeList'; export class World { static worldPrefix = new Array<World>() static worldTypes = new Array<World>() static worldSuffix = new Array<World>() keep = false id = "" public level = 1 constructor( public game: GameModel, public name: string, public description: string, public avaiableUnits: Base[], public prodMod: [Unit, decimal.Decimal][], public toUnlock: Cost[], public unitMod: [Unit, decimal.Decimal][] = [], public unitPrice: [Unit, decimal.Decimal][] = [], public unlockedUnits: [Base, decimal.Decimal][] = [], public experience = new Decimal(2.5), public toUnlockMax = new Array<Cost>(), ) { } static getBaseWorld(game: GameModel): World { const baseWorld = new World(game, "Home", "Nothing special.", [], [], [ new Cost(game.baseWorld.food, new Decimal(1E12)), new Cost(game.baseWorld.nestAnt, new Decimal(40)) ] ) baseWorld.experience = new Decimal(10) return baseWorld } static getRandomWorld(game: GameModel, worldPrefix: World = null, worldType: World = null, worldSuffix: World = null, level: number = -1 ): World { const worldRet = new World(game, "", "", [], [], []) worldRet.experience = new Decimal(0) if (!worldType) worldType = World.worldTypes[Math.floor(Math.random() * (World.worldTypes.length))] if (!worldPrefix) worldPrefix = World.worldPrefix[Math.floor(Math.random() * (World.worldPrefix.length))] if (!worldSuffix) worldSuffix = World.worldSuffix[Math.floor(Math.random() * (World.worldSuffix.length))] const worlds = [worldType, worldPrefix, worldSuffix, this.getBaseWorld(game)] worldRet.name = worldPrefix.name + " " + worldType.name + " " + worldSuffix.name worldRet.description = worldPrefix.description + (!!worldType.description ? '\n' + worldType.description : "") + (!!worldSuffix.description ? '\n' + worldSuffix.description : "") worlds.forEach(w => { w.prodMod.forEach(p => { const prod = worldRet.prodMod.find(p1 => p1[0].id === p[0].id) if (prod) prod[1] = prod[1].times(p[1]) else worldRet.prodMod.push([p[0], p[1]]) }) w.unitMod.forEach(p => { const prod = worldRet.unitMod.find(p1 => p1[0].id === p[0].id) if (prod) prod[1] = prod[1].times(p[1]) else worldRet.unitMod.push([p[0], p[1]]) }) w.unitPrice.forEach(p => { const prod = worldRet.unitPrice.find(p1 => p1[0].id === p[0].id) if (prod) prod[1] = prod[1].times(p[1]) else worldRet.unitPrice.push([p[0], p[1]]) }) w.toUnlock.forEach(p => { const toUnlock = worldRet.toUnlock.find(c => c.unit.id === p.unit.id) if (toUnlock) toUnlock.basePrice = toUnlock.basePrice.plus(p.basePrice) else worldRet.toUnlock.push(new Cost(p.unit, p.basePrice)) }) w.toUnlockMax.forEach(p => { const toUnlockMax = worldRet.toUnlockMax.find(c => c.unit.id === p.unit.id) if (toUnlockMax) toUnlockMax.basePrice = toUnlockMax.basePrice.plus(p.basePrice) else worldRet.toUnlockMax.push(new Cost(p.unit, p.basePrice)) }) w.unlockedUnits.forEach(p => { const unlockedUnits = worldRet.unlockedUnits.find(p1 => p1[0].id === p[0].id) if (unlockedUnits) unlockedUnits[1] = unlockedUnits[1].plus(p[1]) else worldRet.unlockedUnits.push([p[0], p[1]]) }) worldRet.experience = worldRet.experience.plus(w.experience) worldRet.avaiableUnits = worldRet.avaiableUnits.concat(w.avaiableUnits) }) // remove default stat worldRet.prodMod = worldRet.prodMod.filter(pm => pm[1].minus(1).abs().greaterThan(Number.EPSILON)) worldRet.unitMod = worldRet.unitMod.filter(pm => pm[1].minus(1).abs().greaterThan(Number.EPSILON)) worldRet.unitPrice = worldRet.unitPrice.filter(pm => pm[1].minus(1).abs().greaterThan(Number.EPSILON)) worldRet.avaiableUnits = Array.from(new Set(worldRet.avaiableUnits)) worldRet.experience = worldRet.experience.minus(7.5) if (!worldRet.unlockedUnits.map(p => p[0]).includes(game.infestation.poisonousPlant)) { worldRet.avaiableUnits = worldRet.avaiableUnits .filter(u => !game.infestation.listInfestation.map(u2 => u2 as Base).includes(u)) } // Scale the world level if (level < 0) { let min = game.minUser let max = game.maxUser if (!min) min = 0 if (!max) max = game.maxMax min = Math.min(game.minUser, game.maxMax) max = Math.min(game.maxUser, game.maxMax) worldRet.level = new Decimal(Math.random()).times(new Decimal(1 + max - min)).floor().plus(min).toNumber() } else { worldRet.level = Math.min(Math.max(level, 0), game.maxMax) } // worldRet.level = 1000 const linear = 1 / 4 const linearExp = 1 / 2 const toUnlockMultiplier = new Decimal(worldRet.level + 1 / linear).times(linear) // const toUnlockMultiplier = new Decimal(worldRet.level + 1 / linear) // .times(new Decimal(linear).div(Decimal.log(new Decimal(10).plus(new Decimal(worldRet.level).div(125))))) const expMultiplier = Decimal.pow(1.00138, worldRet.level).times(new Decimal(worldRet.level + 1 / linearExp).times(linearExp)) worldRet.toUnlock.forEach(t => t.basePrice = t.basePrice.times(toUnlockMultiplier).floor()) worldRet.unlockedUnits.forEach(t => t[1] = Decimal.max(t[1].times(toUnlockMultiplier.times(2)).floor(), 0)) worldRet.experience = worldRet.experience.times(expMultiplier).plus(0.5).floor() game.unitLists.splice(0, game.unitLists.length) // World better effect worldRet.prodMod.filter(pm => pm[1].greaterThan(0)) .forEach(pm2 => pm2[1] = pm2[1].times(game.prestige.worldBetter.quantity.times(0.5).plus(1))) worldRet.unitMod.filter(pm => pm[1].greaterThan(0)) .forEach(pm2 => pm2[1] = pm2[1].times(game.prestige.worldBetter.quantity.times(0.5).plus(1))) // game.isChanged = true worldRet.setDepartments() return worldRet } goTo(skip = false) { if (!skip) { const earned = this.game.world.experience this.game.prestige.experience.quantity = this.game.prestige.experience.quantity.plus(earned) this.game.maxLevel = this.game.maxLevel.plus(earned) this.game.prestigeDone = this.game.prestigeDone.plus(1) } this.game.setInitialStat() // const le = this.game.lifeEarning // const exp = this.game.prestige.experience.quantity.plus(this.game.getExperience()) // if (!skip) { // this.game.prestige.experience.quantity = exp // this.game.maxLevel = this.game.maxLevel.plus(exp) // this.game.prestigeDone = this.game.prestigeDone.plus(1) // } if (this.avaiableUnits) this.avaiableUnits.forEach(u => u.avabileThisWorld = true) if (this.unlockedUnits) { this.unlockedUnits.forEach(u => { u[0].avabileThisWorld = true u[0].quantity = u[1] }) this.game.unlockUnits(this.unlockedUnits.map(u => u[0]))() } if (this.prodMod) this.prodMod.forEach(p => p[0].worldProdModifiers = p[1]) if (this.unitMod) this.unitMod.forEach(p => p[0].worldEffModifiers = p[1]) if (this.unitPrice) this.unitPrice.forEach(p => p[0].worldBuyModifiers = p[1]) this.game.world = this this.game.all.forEach(u => u.reloadtAct()) // research fix this.game.resList.forEach(r => r.quantity = new Decimal(0)) this.game.worldTabAv = true this.game.homeTabAv = true this.game.expTabAv = true this.game.reloadProduction() this.game.unitLists = new Array<TypeList>() // this.game.reloadList() this.game.generateRandomWorld(true) this.game.isChanged = true } getData() { const data: any = {} data.n = this.name if (this.avaiableUnits) data.a = this.avaiableUnits.map(b => b.id) if (this.prodMod) data.p = this.prodMod.map(p => [p[0].id, p[1]]) data.t = this.toUnlock.map(c => c.getData()) data.m = this.toUnlockMax.map(c => c.getData()) data.um = this.unitMod.map(up => [up[0].id, up[1]]) data.up = this.unitPrice.map(up => [up[0].id, up[1]]) data.uu = this.unlockedUnits.map(up => [up[0].id, up[1]]) data.e = this.experience data.l = this.level data.keep = this.keep return data } restore(data: any, setDep: boolean = false) { this.name = data.n this.avaiableUnits = [] if (typeof data.a !== "undefined" && data.a != null && data.a.length > 0) this.avaiableUnits = data.a.map(a => this.game.allBase.find(u => u.id === a)) this.prodMod = [] if (typeof data.p !== "undefined" && data.p != null && data.p.length > 0) this.prodMod = data.p.map(p => [this.game.all.find(u => u.id === p[0]), new Decimal(p[1])]) this.toUnlock = [] if (typeof data.t !== "undefined" && data.t != null && data.t.length > 0) this.toUnlock = data.t.map(c => this.game.getCost(c)) this.toUnlockMax = [] if (typeof data.m !== "undefined" && data.m != null && data.m.length > 0) this.toUnlockMax = data.m.map(c => this.game.getCost(c)) this.unitMod = [] if (typeof data.um !== "undefined" && data.um != null && data.um.length > 0) this.unitMod = data.um.map(p => [this.game.all.find(u => u.id === p[0]), new Decimal(p[1])]) this.unitPrice = [] if (typeof data.up !== "undefined" && data.up != null && data.up.length > 0) this.unitPrice = data.up.map(p => [this.game.all.find(u => u.id === p[0]), new Decimal(p[1])]) this.unlockedUnits = [] if (typeof data.uu !== "undefined" && data.uu != null && data.uu.length > 0) this.unlockedUnits = data.uu.map(p => [this.game.allBase.find(u => u.id === p[0]), new Decimal(p[1])]) this.experience = new Decimal(10) if (data.e) this.experience = new Decimal(data.e) if (data.l) this.level = data.l if (data.keep) this.keep = true this.setDepartments(setDep) } setDepartments(assign: boolean = false) { for (let i = 0; i < this.game.engineers.listEnginer.length; i++) { const engineer = this.game.engineers.listEnginer[i] const dep = this.game.engineers.listDep[i] if (!engineer.avabileBaseWorld && !!this.avaiableUnits.find(u => u === engineer) && !this.avaiableUnits.find(u => u === dep)) { this.avaiableUnits.push(dep) if (assign) dep.avabileThisWorld = true } } } }
the_stack
import { describe, it, expect } from "@jest/globals"; import { DataFactory } from "n3"; import { Thing } from "../interfaces"; import { addUrl, addBoolean, addDatetime, addDate, addTime, addDecimal, addInteger, addStringEnglish, addStringWithLocale, addStringNoLocale, addNamedNode, addLiteral, addTerm, } from "./add"; import { mockThingFrom } from "./mock"; import { ValidPropertyUrlExpectedError, ValidValueUrlExpectedError, } from "./thing"; import { localNodeSkolemPrefix } from "../rdf.internal"; describe("addIri", () => { it("adds the given IRI value for the given predicate", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addUrl( thing, "https://some.vocab/predicate", "https://some.pod/other-resource#object" ); expect( updatedThing.predicates["https://some.vocab/predicate"] ).toStrictEqual({ namedNodes: ["https://some.pod/other-resource#object"], }); }); it("accepts values as Named Nodes", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addUrl( thing, "https://some.vocab/predicate", DataFactory.namedNode("https://some.pod/other-resource#object") ); expect( updatedThing.predicates["https://some.vocab/predicate"] ).toStrictEqual({ namedNodes: ["https://some.pod/other-resource#object"], }); }); it("accepts values as ThingPersisteds", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const targetThing = mockThingFrom("https://some.pod/other-resource#object"); const updatedThing = addUrl( thing, "https://some.vocab/predicate", targetThing ); expect( updatedThing.predicates["https://some.vocab/predicate"] ).toStrictEqual({ namedNodes: ["https://some.pod/other-resource#object"], }); }); it("accepts values as ThingLocals", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const thingLocal = mockThingFrom(`${localNodeSkolemPrefix}localObject`); const updatedThing = addUrl( thing, "https://some.vocab/predicate", thingLocal ); expect( updatedThing.predicates["https://some.vocab/predicate"] ).toStrictEqual({ namedNodes: [`${localNodeSkolemPrefix}localObject`], }); }); it("accepts Properties as Named Nodes", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addUrl( thing, DataFactory.namedNode("https://some.vocab/predicate"), "https://some.pod/other-resource#object" ); expect( updatedThing.predicates["https://some.vocab/predicate"] ).toStrictEqual({ namedNodes: ["https://some.pod/other-resource#object"], }); }); it("does not modify the input Thing", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addUrl( thing, "https://some.vocab/predicate", "https://some.pod/other-resource#object" ); expect(thing).not.toStrictEqual(updatedThing); expect(thing.predicates["https://some.vocab/predicate"]).toBeUndefined(); expect( updatedThing.predicates["https://some.vocab/predicate"] ).toStrictEqual({ namedNodes: ["https://some.pod/other-resource#object"], }); }); it("also works on ThingLocals", () => { const thingLocal = mockThingFrom( "https://arbitrary.pod/will-be-replaced-by-local-url" ); (thingLocal.url as string) = `${localNodeSkolemPrefix}arbitrary-subject-name`; const updatedThing = addUrl( thingLocal, "https://some.vocab/predicate", "https://some.pod/other-resource#object" ); expect( updatedThing.predicates["https://some.vocab/predicate"] ).toStrictEqual({ namedNodes: ["https://some.pod/other-resource#object"], }); }); it("preserves existing values for the same Predicate", () => { const thing: Thing = { type: "Subject", url: "https://some.pod/resource#subject", predicates: { "https://some.vocab/predicate": { namedNodes: ["https://some.pod/other-resource#object"], }, }, }; const updatedThing = addUrl( thing, "https://some.vocab/predicate", "https://some.pod/yet-another-resource#object" ); expect( updatedThing.predicates["https://some.vocab/predicate"] ).toStrictEqual({ namedNodes: [ "https://some.pod/other-resource#object", "https://some.pod/yet-another-resource#object", ], }); }); it("preserves existing Quads with different Predicates", () => { const thing: Thing = { type: "Subject", url: "https://some.pod/resource#subject", predicates: { "https://some-other.vocab/predicate": { namedNodes: ["https://some.pod/other-resource#object"], }, }, }; const updatedThing = addUrl( thing, "https://some.vocab/predicate", "https://some.pod/other-resource#object" ); expect(updatedThing.predicates).toStrictEqual({ "https://some-other.vocab/predicate": { namedNodes: ["https://some.pod/other-resource#object"], }, "https://some.vocab/predicate": { namedNodes: ["https://some.pod/other-resource#object"], }, }); }); it("throws an error when passed something other than a Thing", () => { expect(() => addUrl( null as unknown as Thing, "https://arbitrary.vocab/predicate", "https://arbitrary.url" ) ).toThrow("Expected a Thing, but received: [null]."); }); it("throws an error when passed an invalid property URL", () => { expect(() => addUrl( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", "https://arbitrary.url" ) ).toThrow( "Expected a valid URL to identify a property, but received: [not-a-url]." ); }); it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => { let thrownError; try { addUrl( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", "https://arbitrary.url" ); } catch (e) { thrownError = e; } expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError); }); it("throws an error when passed an invalid URL value", () => { expect(() => addUrl( mockThingFrom("https://arbitrary.pod/resource#thing"), "https://arbitrary.vocab/predicate", "not-a-url" ) ).toThrow("Expected a valid URL value, but received: [not-a-url]."); }); it("throws an instance of ValidValueUrlExpectedError when passed an invalid property URL", () => { let thrownError; try { addUrl( mockThingFrom("https://arbitrary.pod/resource#thing"), "https://arbitrary.vocab/predicate", "not-a-url" ); } catch (e) { thrownError = e; } expect(thrownError).toBeInstanceOf(ValidValueUrlExpectedError); }); }); describe("addBoolean", () => { it("adds the given boolean value for the given predicate", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addBoolean( thing, "https://some.vocab/predicate", true ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#boolean" ] ).toStrictEqual(["true"]); }); it("accepts Properties as Named Nodes", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addBoolean( thing, DataFactory.namedNode("https://some.vocab/predicate"), false ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#boolean" ] ).toStrictEqual(["false"]); }); it("does not modify the input Thing", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addBoolean( thing, "https://some.vocab/predicate", true ); expect(thing).not.toStrictEqual(updatedThing); expect(thing.predicates).toStrictEqual({}); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#boolean" ] ).toStrictEqual(["true"]); }); it("also works on ThingLocals", () => { const thingLocal = mockThingFrom( "https://arbitrary.pod/will-be-replaced-by-local-url" ); (thingLocal.url as string) = `${localNodeSkolemPrefix}localSubject`; const updatedThing = addBoolean( thingLocal, "https://some.vocab/predicate", true ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#boolean" ] ).toStrictEqual(["true"]); }); it("preserves existing values for the same Predicate", () => { const thing: Thing = { type: "Subject", url: "https://some.pod/resource#subject", predicates: { "https://some.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#boolean": ["false"] }, }, }, }; const updatedThing = addBoolean( thing, "https://some.vocab/predicate", true ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#boolean" ] ).toStrictEqual(["false", "true"]); }); it("preserves existing Quads with different Predicates", () => { const thing: Thing = { type: "Subject", url: "https://some.pod/resource#subject", predicates: { "https://some-other.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#boolean": ["false"] }, }, }, }; const updatedThing = addBoolean( thing, "https://some.vocab/predicate", true ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#boolean" ] ).toStrictEqual(["true"]); expect( updatedThing.predicates["https://some-other.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#boolean" ] ).toStrictEqual(["false"]); }); it("throws an error when passed something other than a Thing", () => { expect(() => addBoolean( null as unknown as Thing, "https://arbitrary.vocab/predicate", true ) ).toThrow("Expected a Thing, but received: [null]."); }); it("throws an error when passed an invalid property URL", () => { expect(() => addBoolean( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", true ) ).toThrow( "Expected a valid URL to identify a property, but received: [not-a-url]." ); }); it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => { let thrownError; try { addBoolean( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", true ); } catch (e) { thrownError = e; } expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError); }); }); describe("addDatetime", () => { it("adds the given datetime value for the given predicate", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addDatetime( thing, "https://some.vocab/predicate", new Date(Date.UTC(1990, 10, 12, 13, 37, 42, 0)) ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#dateTime" ] ).toStrictEqual(["1990-11-12T13:37:42.000Z"]); }); it("accepts Properties as Named Nodes", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addDatetime( thing, DataFactory.namedNode("https://some.vocab/predicate"), new Date(Date.UTC(1990, 10, 12, 13, 37, 42, 0)) ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#dateTime" ] ).toStrictEqual(["1990-11-12T13:37:42.000Z"]); }); it("does not modify the input Thing", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addDatetime( thing, "https://some.vocab/predicate", new Date(Date.UTC(1990, 10, 12, 13, 37, 42, 0)) ); expect(thing).not.toStrictEqual(updatedThing); expect(thing.predicates["https://some.vocab/predicate"]).toBeUndefined(); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#dateTime" ] ).toStrictEqual(["1990-11-12T13:37:42.000Z"]); }); it("also works on ThingLocals", () => { const thingLocal = mockThingFrom( "https://arbitrary.pod/will-be-replaced-by-local-url" ); (thingLocal.url as string) = `${localNodeSkolemPrefix}localSubject`; const updatedThing = addDatetime( thingLocal, "https://some.vocab/predicate", new Date(Date.UTC(1990, 10, 12, 13, 37, 42, 0)) ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#dateTime" ] ).toStrictEqual(["1990-11-12T13:37:42.000Z"]); }); it("preserves existing values for the same Predicate", () => { const thing: Thing = { type: "Subject", url: "https://some.pod/resource#subject", predicates: { "https://some.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#dateTime": [ "1955-06-08T13:37:42.000Z", ], }, }, }, }; const updatedThing = addDatetime( thing, "https://some.vocab/predicate", new Date(Date.UTC(1990, 10, 12, 13, 37, 42, 0)) ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#dateTime" ] ).toStrictEqual(["1955-06-08T13:37:42.000Z", "1990-11-12T13:37:42.000Z"]); }); it("preserves existing Quads with different Predicates", () => { const thing: Thing = { type: "Subject", url: "https://some.pod/resource#subject", predicates: { "https://some-other.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#string": ["Some other value"], }, }, }, }; const updatedThing = addDatetime( thing, "https://some.vocab/predicate", new Date(Date.UTC(1990, 10, 12, 13, 37, 42, 0)) ); expect( updatedThing.predicates["https://some-other.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#string" ] ).toStrictEqual(["Some other value"]); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#dateTime" ] ).toStrictEqual(["1990-11-12T13:37:42.000Z"]); }); it("throws an error when passed something other than a Thing", () => { expect(() => addDatetime( null as unknown as Thing, "https://arbitrary.vocab/predicate", new Date(Date.UTC(1990, 10, 12, 13, 37, 42, 0)) ) ).toThrow("Expected a Thing, but received: [null]."); }); it("throws an error when passed an invalid property URL", () => { expect(() => addDatetime( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", new Date(Date.UTC(1990, 10, 12, 13, 37, 42, 0)) ) ).toThrow( "Expected a valid URL to identify a property, but received: [not-a-url]." ); }); it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => { let thrownError; try { addDatetime( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", new Date(Date.UTC(1990, 10, 12, 13, 37, 42, 0)) ); } catch (e) { thrownError = e; } expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError); }); }); describe("addDate", () => { it("adds the given date value for the given predicate", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addDate( thing, "https://some.vocab/predicate", new Date(Date.UTC(1990, 10, 12)) ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#date" ] ).toStrictEqual(["1990-11-12Z"]); }); it("accepts Properties as Named Nodes", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addDate( thing, DataFactory.namedNode("https://some.vocab/predicate"), new Date(Date.UTC(1990, 10, 12)) ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#date" ] ).toStrictEqual(["1990-11-12Z"]); }); it("does not modify the input Thing", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addDate( thing, "https://some.vocab/predicate", new Date(Date.UTC(1990, 10, 12)) ); expect(thing).not.toStrictEqual(updatedThing); expect(thing.predicates["https://some.vocab/predicate"]).toBeUndefined(); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#date" ] ).toStrictEqual(["1990-11-12Z"]); }); it("also works on ThingLocals", () => { const thingLocal = mockThingFrom( "https://arbitrary.pod/will-be-replaced-by-local-url" ); (thingLocal.url as string) = `${localNodeSkolemPrefix}localSubject`; const updatedThing = addDate( thingLocal, "https://some.vocab/predicate", new Date(Date.UTC(1990, 10, 12)) ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#date" ] ).toStrictEqual(["1990-11-12Z"]); }); it("preserves existing values for the same Predicate", () => { const thing: Thing = { type: "Subject", url: "https://some.pod/resource#subject", predicates: { "https://some.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#date": ["1955-06-08Z"], }, }, }, }; const updatedThing = addDate( thing, "https://some.vocab/predicate", new Date(Date.UTC(1990, 10, 12)) ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#date" ] ).toStrictEqual(["1955-06-08Z", "1990-11-12Z"]); }); it("preserves existing Quads with different Predicates", () => { const thing: Thing = { type: "Subject", url: "https://some.pod/resource#subject", predicates: { "https://some-other.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#string": ["Some other value"], }, }, }, }; const updatedThing = addDate( thing, "https://some.vocab/predicate", new Date(Date.UTC(1990, 10, 12)) ); expect( updatedThing.predicates["https://some-other.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#string" ] ).toStrictEqual(["Some other value"]); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#date" ] ).toStrictEqual(["1990-11-12Z"]); }); it("throws an error when passed something other than a Thing", () => { expect(() => addDate( null as unknown as Thing, "https://arbitrary.vocab/predicate", new Date(Date.UTC(1990, 10, 12)) ) ).toThrow("Expected a Thing, but received: [null]."); }); it("throws an error when passed an invalid property URL", () => { expect(() => addDate( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", new Date(Date.UTC(1990, 10, 12)) ) ).toThrow( "Expected a valid URL to identify a property, but received: [not-a-url]." ); }); it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => { let thrownError; try { addDate( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", new Date(Date.UTC(1990, 10, 12)) ); } catch (e) { thrownError = e; } expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError); }); }); describe("addTime", () => { it("adds the given time value for the given predicate", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addTime(thing, "https://some.vocab/predicate", { hour: 13, minute: 37, second: 42, }); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#time" ] ).toStrictEqual(["13:37:42"]); }); it("accepts milliseconds", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addTime(thing, "https://some.vocab/predicate", { hour: 13, minute: 37, second: 42, millisecond: 367, }); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#time" ] ).toStrictEqual(["13:37:42.367"]); }); it("accepts Properties as Named Nodes", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addTime( thing, DataFactory.namedNode("https://some.vocab/predicate"), { hour: 13, minute: 37, second: 42, } ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#time" ] ).toStrictEqual(["13:37:42"]); }); it("does not modify the input Thing", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addTime(thing, "https://some.vocab/predicate", { hour: 13, minute: 37, second: 42, }); expect(thing).not.toStrictEqual(updatedThing); expect(thing.predicates["https://some.vocab/predicate"]).toBeUndefined(); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#time" ] ).toStrictEqual(["13:37:42"]); }); it("also works on ThingLocals", () => { const thingLocal = mockThingFrom( "https://arbitrary.pod/will-be-replaced-by-local-url" ); (thingLocal.url as string) = `${localNodeSkolemPrefix}localSubject`; const updatedThing = addTime(thingLocal, "https://some.vocab/predicate", { hour: 13, minute: 37, second: 42, }); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#time" ] ).toStrictEqual(["13:37:42"]); }); it("preserves existing values for the same Predicate", () => { const thing: Thing = { type: "Subject", url: "https://some.pod/resource#subject", predicates: { "https://some.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#time": ["13:37:42"], }, }, }, }; const updatedThing = addTime(thing, "https://some.vocab/predicate", { hour: 13, minute: 40, second: 42, }); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#time" ] ).toStrictEqual(["13:37:42", "13:40:42"]); }); it("preserves existing Quads with different Predicates", () => { const thing: Thing = { type: "Subject", url: "https://some.pod/resource#subject", predicates: { "https://some-other.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#string": ["Some other value"], }, }, }, }; const updatedThing = addTime(thing, "https://some.vocab/predicate", { hour: 13, minute: 37, second: 42, }); expect( updatedThing.predicates["https://some-other.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#string" ] ).toStrictEqual(["Some other value"]); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#time" ] ).toStrictEqual(["13:37:42"]); }); it("throws an error when passed something other than a Thing", () => { expect(() => addTime(null as unknown as Thing, "https://arbitrary.vocab/predicate", { hour: 13, minute: 37, second: 42, }) ).toThrow("Expected a Thing, but received: [null]."); }); it("throws an error when passed an invalid property URL", () => { expect(() => addTime( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", { hour: 13, minute: 37, second: 42, } ) ).toThrow( "Expected a valid URL to identify a property, but received: [not-a-url]." ); }); it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => { let thrownError; try { addTime( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", { hour: 13, minute: 37, second: 42, } ); } catch (e) { thrownError = e; } expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError); }); }); describe("addDecimal", () => { it("adds the given decimal value for the given predicate", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addDecimal( thing, "https://some.vocab/predicate", 13.37 ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#decimal" ] ).toStrictEqual(["13.37"]); }); it("accepts Properties as Named Nodes", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addDecimal( thing, DataFactory.namedNode("https://some.vocab/predicate"), 13.37 ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#decimal" ] ).toStrictEqual(["13.37"]); }); it("does not modify the input Thing", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addDecimal( thing, "https://some.vocab/predicate", 13.37 ); expect(thing).not.toStrictEqual(updatedThing); expect(thing.predicates).toStrictEqual({}); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#decimal" ] ).toStrictEqual(["13.37"]); }); it("also works on ThingLocals", () => { const thingLocal = mockThingFrom( "https://arbitrary.pod/will-be-replaced-by-local-url" ); (thingLocal.url as string) = `${localNodeSkolemPrefix}localSubject`; const updatedThing = addDecimal( thingLocal, "https://some.vocab/predicate", 13.37 ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#decimal" ] ).toStrictEqual(["13.37"]); }); it("preserves existing values for the same Predicate", () => { const thing: Thing = { type: "Subject", url: "https://some.pod/resource#subject", predicates: { "https://some.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#decimal": ["4.2"] }, }, }, }; const updatedThing = addDecimal( thing, "https://some.vocab/predicate", 13.37 ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#decimal" ] ).toStrictEqual(["4.2", "13.37"]); }); it("preserves existing Quads with different Predicates", () => { const thing: Thing = { type: "Subject", url: "https://some.pod/resource#subject", predicates: { "https://some-other.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#string": ["Some other value"], }, }, }, }; const updatedThing = addDecimal( thing, "https://some.vocab/predicate", 13.37 ); expect( updatedThing.predicates["https://some-other.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#string" ] ).toStrictEqual(["Some other value"]); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#decimal" ] ).toStrictEqual(["13.37"]); }); it("throws an error when passed something other than a Thing", () => { expect(() => addDecimal( null as unknown as Thing, "https://arbitrary.vocab/predicate", 13.37 ) ).toThrow("Expected a Thing, but received: [null]."); }); it("throws an error when passed an invalid property URL", () => { expect(() => addDecimal( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", 13.37 ) ).toThrow( "Expected a valid URL to identify a property, but received: [not-a-url]." ); }); it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => { let thrownError; try { addDecimal( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", 13.37 ); } catch (e) { thrownError = e; } expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError); }); }); describe("addInteger", () => { it("adds the given integer value for the given predicate", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addInteger(thing, "https://some.vocab/predicate", 42); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#integer" ] ).toStrictEqual(["42"]); }); it("accepts Properties as Named Nodes", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addInteger( thing, DataFactory.namedNode("https://some.vocab/predicate"), 42 ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#integer" ] ).toStrictEqual(["42"]); }); it("does not modify the input Thing", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addInteger(thing, "https://some.vocab/predicate", 42); expect(thing).not.toStrictEqual(updatedThing); expect(thing.predicates).toStrictEqual({}); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#integer" ] ).toStrictEqual(["42"]); }); it("also works on ThingLocals", () => { const thingLocal = mockThingFrom( "https://arbitrary.pod/will-be-replaced-by-local-url" ); (thingLocal.url as string) = `${localNodeSkolemPrefix}localSubject`; const updatedThing = addInteger( thingLocal, "https://some.vocab/predicate", 42 ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#integer" ] ).toStrictEqual(["42"]); }); it("preserves existing values for the same Predicate", () => { const thing: Thing = { type: "Subject", url: "https://some.pod/resource#subject", predicates: { "https://some.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#integer": ["1337"] }, }, }, }; const updatedThing = addInteger(thing, "https://some.vocab/predicate", 42); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#integer" ] ).toStrictEqual(["1337", "42"]); }); it("preserves existing Quads with different Predicates", () => { const thing: Thing = { type: "Subject", url: "https://some.pod/resource#subject", predicates: { "https://some-other.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#string": ["Some other value"], }, }, }, }; const updatedThing = addInteger(thing, "https://some.vocab/predicate", 42); expect( updatedThing.predicates["https://some-other.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#string" ] ).toStrictEqual(["Some other value"]); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#integer" ] ).toStrictEqual(["42"]); }); it("throws an error when passed something other than a Thing", () => { expect(() => addInteger( null as unknown as Thing, "https://arbitrary.vocab/predicate", 42 ) ).toThrow("Expected a Thing, but received: [null]."); }); it("throws an error when passed an invalid property URL", () => { expect(() => addInteger( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", 42 ) ).toThrow( "Expected a valid URL to identify a property, but received: [not-a-url]." ); }); it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => { let thrownError; try { addInteger( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", 42 ); } catch (e) { thrownError = e; } expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError); }); }); describe("addStringEnglish", () => { it("adds the given value as an English string for the given predicate", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addStringEnglish( thing, "https://some.vocab/predicate", "Some string" ); expect( updatedThing.predicates["https://some.vocab/predicate"].langStrings ).toStrictEqual({ en: ["Some string"], }); }); }); describe("addStringWithLocale", () => { it("adds the given localised string value for the given predicate", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addStringWithLocale( thing, "https://some.vocab/predicate", "Some string", "en-GB" ); expect( updatedThing.predicates["https://some.vocab/predicate"].langStrings ).toStrictEqual({ "en-gb": ["Some string"], }); }); it("accepts Properties as Named Nodes", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addStringWithLocale( thing, DataFactory.namedNode("https://some.vocab/predicate"), "Some string", "en-GB" ); expect( updatedThing.predicates["https://some.vocab/predicate"].langStrings ).toStrictEqual({ "en-gb": ["Some string"], }); }); it("does not modify the input Thing", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addStringWithLocale( thing, DataFactory.namedNode("https://some.vocab/predicate"), "Some string", "en-GB" ); expect(thing).not.toStrictEqual(updatedThing); expect(thing.predicates).toStrictEqual({}); expect( updatedThing.predicates["https://some.vocab/predicate"].langStrings ).toStrictEqual({ "en-gb": ["Some string"], }); }); it("also works on ThingLocals", () => { const thingLocal = mockThingFrom( "https://arbitrary.pod/will-be-replaced-by-local-url" ); (thingLocal.url as string) = `${localNodeSkolemPrefix}localSubject`; const updatedThing = addStringWithLocale( thingLocal, DataFactory.namedNode("https://some.vocab/predicate"), "Some string", "en-GB" ); expect( updatedThing.predicates["https://some.vocab/predicate"].langStrings ).toStrictEqual({ "en-gb": ["Some string"], }); }); it("preserves existing values for the same Predicate", () => { const thing: Thing = { type: "Subject", url: "https://some.pod/resource#subject", predicates: { "https://some.vocab/predicate": { langStrings: { "nl-nl": ["Some string"] }, }, }, }; const updatedThing = addStringWithLocale( thing, "https://some.vocab/predicate", "Some string", "en-GB" ); expect( updatedThing.predicates["https://some.vocab/predicate"].langStrings ).toStrictEqual({ "nl-nl": ["Some string"], "en-gb": ["Some string"], }); }); it("preserves existing values for the same Predicate and locale", () => { const thing: Thing = { type: "Subject", url: "https://some.pod/resource#subject", predicates: { "https://some.vocab/predicate": { langStrings: { "nl-nl": ["Some string"] }, }, }, }; const updatedThing = addStringWithLocale( thing, "https://some.vocab/predicate", "Some other string", "nl-nl" ); expect( updatedThing.predicates["https://some.vocab/predicate"].langStrings ).toStrictEqual({ "nl-nl": ["Some string", "Some other string"], }); }); it("preserves existing Quads with different Predicates", () => { const thing: Thing = { type: "Subject", url: "https://some.pod/resource#subject", predicates: { "https://some-other.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#string": ["Some other value"], }, }, }, }; const updatedThing = addStringWithLocale( thing, "https://some.vocab/predicate", "Some string", "en-GB" ); expect( updatedThing.predicates["https://some-other.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#string" ] ).toStrictEqual(["Some other value"]); expect( updatedThing.predicates["https://some.vocab/predicate"].langStrings ).toStrictEqual({ "en-gb": ["Some string"], }); }); it("throws an error when passed something other than a Thing", () => { expect(() => addStringWithLocale( null as unknown as Thing, "https://arbitrary.vocab/predicate", "Arbitrary string", "nl-NL" ) ).toThrow("Expected a Thing, but received: [null]."); }); it("throws an error when passed an invalid property URL", () => { expect(() => addStringWithLocale( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", "Arbitrary string", "nl-NL" ) ).toThrow( "Expected a valid URL to identify a property, but received: [not-a-url]." ); }); it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => { let thrownError; try { addStringWithLocale( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", "Arbitrary string", "nl-NL" ); } catch (e) { thrownError = e; } expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError); }); }); describe("addStringNoLocale", () => { it("adds the given unlocalised string value for the given predicate", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addStringNoLocale( thing, "https://some.vocab/predicate", "Some string value" ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#string" ] ).toStrictEqual(["Some string value"]); }); it("accepts Properties as Named Nodes", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addStringNoLocale( thing, DataFactory.namedNode("https://some.vocab/predicate"), "Some string value" ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#string" ] ).toStrictEqual(["Some string value"]); }); it("does not modify the input Thing", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addStringNoLocale( thing, "https://some.vocab/predicate", "Some string value" ); expect(thing).not.toStrictEqual(updatedThing); expect(thing.predicates).toStrictEqual({}); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#string" ] ).toStrictEqual(["Some string value"]); }); it("also works on ThingLocals", () => { const thingLocal = mockThingFrom( "https://arbitrary.pod/will-be-replaced-by-local-url" ); (thingLocal.url as string) = `${localNodeSkolemPrefix}localSubject`; const updatedThing = addStringNoLocale( thingLocal, "https://some.vocab/predicate", "Some string value" ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#string" ] ).toStrictEqual(["Some string value"]); }); it("preserves existing values for the same Predicate", () => { const thing: Thing = { type: "Subject", url: "https://some.pod/resource#subject", predicates: { "https://some.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#string": [ "Some other string value", ], }, }, }, }; const updatedThing = addStringNoLocale( thing, "https://some.vocab/predicate", "Some string value" ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#string" ] ).toStrictEqual(["Some other string value", "Some string value"]); }); it("preserves existing Quads with different Predicates", () => { const thing: Thing = { type: "Subject", url: "https://some.pod/resource#subject", predicates: { "https://some-other.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#integer": ["42"] }, }, }, }; const updatedThing = addStringNoLocale( thing, "https://some.vocab/predicate", "Some string value" ); expect( updatedThing.predicates["https://some-other.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#integer" ] ).toStrictEqual(["42"]); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#string" ] ).toStrictEqual(["Some string value"]); }); it("throws an error when passed something other than a Thing", () => { expect(() => addStringNoLocale( null as unknown as Thing, "https://arbitrary.vocab/predicate", "Arbitrary string" ) ).toThrow("Expected a Thing, but received: [null]."); }); it("throws an error when passed an invalid property URL", () => { expect(() => addStringNoLocale( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", "Arbitrary string" ) ).toThrow( "Expected a valid URL to identify a property, but received: [not-a-url]." ); }); it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => { let thrownError; try { addStringNoLocale( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", "Arbitrary string" ); } catch (e) { thrownError = e; } expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError); }); }); describe("addNamedNode", () => { it("adds the given NamedNode value for the given predicate", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addNamedNode( thing, "https://some.vocab/predicate", DataFactory.namedNode("https://some.pod/other-resource#object") ); expect( updatedThing.predicates["https://some.vocab/predicate"] ).toStrictEqual({ namedNodes: ["https://some.pod/other-resource#object"], }); }); it("accepts Properties as Named Nodes", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addNamedNode( thing, DataFactory.namedNode("https://some.vocab/predicate"), DataFactory.namedNode("https://some.pod/other-resource#object") ); expect( updatedThing.predicates["https://some.vocab/predicate"] ).toStrictEqual({ namedNodes: ["https://some.pod/other-resource#object"], }); }); it("does not modify the input Thing", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addNamedNode( thing, "https://some.vocab/predicate", DataFactory.namedNode("https://some.pod/other-resource#object") ); expect(thing).not.toStrictEqual(updatedThing); expect(thing.predicates).toStrictEqual({}); expect( updatedThing.predicates["https://some.vocab/predicate"] ).toStrictEqual({ namedNodes: ["https://some.pod/other-resource#object"], }); }); it("also works on ThingLocals", () => { const thingLocal = mockThingFrom( "https://arbitrary.pod/will-be-replaced-by-local-url" ); (thingLocal.url as string) = `${localNodeSkolemPrefix}localSubject`; const updatedThing = addNamedNode( thingLocal, "https://some.vocab/predicate", DataFactory.namedNode("https://some.pod/other-resource#object") ); expect( updatedThing.predicates["https://some.vocab/predicate"] ).toStrictEqual({ namedNodes: ["https://some.pod/other-resource#object"], }); }); it("preserves existing values for the same Predicate", () => { const thing: Thing = { type: "Subject", url: "https://some.pod/resource#subject", predicates: { "https://some.vocab/predicate": { namedNodes: ["https://some.pod/other-resource#object"], }, }, }; const updatedThing = addNamedNode( thing, "https://some.vocab/predicate", DataFactory.namedNode("https://some.pod/yet-another-resource#object") ); expect( updatedThing.predicates["https://some.vocab/predicate"] ).toStrictEqual({ namedNodes: [ "https://some.pod/other-resource#object", "https://some.pod/yet-another-resource#object", ], }); }); it("preserves existing Quads with different Predicates", () => { const thing: Thing = { type: "Subject", url: "https://some.pod/resource#subject", predicates: { "https://some-other.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#string": ["Some other value"], }, }, }, }; const updatedThing = addNamedNode( thing, "https://some.vocab/predicate", DataFactory.namedNode("https://some.pod/other-resource#object") ); expect( updatedThing.predicates["https://some-other.vocab/predicate"] ).toStrictEqual({ literals: { "http://www.w3.org/2001/XMLSchema#string": ["Some other value"], }, }); expect( updatedThing.predicates["https://some.vocab/predicate"] ).toStrictEqual({ namedNodes: ["https://some.pod/other-resource#object"], }); }); it("throws an error when passed something other than a Thing", () => { expect(() => addNamedNode( null as unknown as Thing, "https://arbitrary.vocab/predicate", DataFactory.namedNode("https://arbitrary.pod/resource#object") ) ).toThrow("Expected a Thing, but received: [null]."); }); it("throws an error when passed an invalid property URL", () => { expect(() => addNamedNode( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", DataFactory.namedNode("https://arbitrary.vocab/object") ) ).toThrow( "Expected a valid URL to identify a property, but received: [not-a-url]." ); }); it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => { let thrownError; try { addNamedNode( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", DataFactory.namedNode("https://arbitrary.vocab/object") ); } catch (e) { thrownError = e; } expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError); }); }); describe("addLiteral", () => { it("adds the given Literal value for the given predicate", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addLiteral( thing, "https://some.vocab/predicate", DataFactory.literal("Some string value") ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#string" ] ).toStrictEqual(["Some string value"]); }); it("adds the given langString Literal value for the given predicate", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addLiteral( thing, "https://some.vocab/predicate", DataFactory.literal("Some string value", "nl-nl") ); expect( updatedThing.predicates["https://some.vocab/predicate"].langStrings![ "nl-nl" ] ).toStrictEqual(["Some string value"]); }); it("accepts Properties as Named Nodes", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addLiteral( thing, DataFactory.namedNode("https://some.vocab/predicate"), DataFactory.literal("Some string value") ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#string" ] ).toStrictEqual(["Some string value"]); }); it("does not modify the input Thing", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addLiteral( thing, "https://some.vocab/predicate", DataFactory.literal("Some string value") ); expect(thing).not.toStrictEqual(updatedThing); expect(thing.predicates).toStrictEqual({}); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#string" ] ).toStrictEqual(["Some string value"]); }); it("also works on ThingLocals", () => { const thingLocal = mockThingFrom( "https://arbitrary.pod/will-be-replaced-by-local-url" ); (thingLocal.url as string) = `${localNodeSkolemPrefix}localSubject`; const updatedThing = addLiteral( thingLocal, "https://some.vocab/predicate", DataFactory.literal("Some string value") ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#string" ] ).toStrictEqual(["Some string value"]); }); it("preserves existing values for the same Predicate", () => { const thing: Thing = { type: "Subject", url: "https://some.pod/resource#subject", predicates: { "https://some.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#string": [ "Some other string value", ], }, }, }, }; const updatedThing = addLiteral( thing, "https://some.vocab/predicate", DataFactory.literal("Some string value") ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#string" ] ).toStrictEqual(["Some other string value", "Some string value"]); }); it("preserves existing Quads with different Predicates", () => { const thing: Thing = { type: "Subject", url: "https://some.pod/resource#subject", predicates: { "https://some-other.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#integer": ["42"] }, }, }, }; const updatedThing = addLiteral( thing, "https://some.vocab/predicate", DataFactory.literal("Some string value") ); expect( updatedThing.predicates["https://some-other.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#integer" ] ).toStrictEqual(["42"]); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#string" ] ).toStrictEqual(["Some string value"]); }); it("throws an error when passed something other than a Thing", () => { expect(() => addLiteral( null as unknown as Thing, "https://arbitrary.vocab/predicate", DataFactory.literal("Arbitrary string value") ) ).toThrow("Expected a Thing, but received: [null]."); }); it("throws an error when passed an invalid property URL", () => { expect(() => addLiteral( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", DataFactory.literal("Arbitrary string value") ) ).toThrow( "Expected a valid URL to identify a property, but received: [not-a-url]." ); }); it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => { let thrownError; try { addLiteral( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", DataFactory.literal("Arbitrary string value") ); } catch (e) { thrownError = e; } expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError); }); }); describe("addTerm", () => { it("adds the given NamedNode value for the given predicate", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addTerm( thing, "https://some.vocab/predicate", DataFactory.namedNode("https://some.pod/other-resource#object") ); expect( updatedThing.predicates["https://some.vocab/predicate"] ).toStrictEqual({ namedNodes: ["https://some.pod/other-resource#object"], }); }); it("adds the given Literal value for the given predicate", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addTerm( thing, "https://some.vocab/predicate", DataFactory.literal( "Some string", DataFactory.namedNode("http://www.w3.org/2001/XMLSchema#string") ) ); expect( updatedThing.predicates["https://some.vocab/predicate"].literals![ "http://www.w3.org/2001/XMLSchema#string" ] ).toStrictEqual(["Some string"]); }); it("adds the given Blank Node value for the given predicate", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addTerm( thing, "https://some.vocab/predicate", DataFactory.blankNode("some-blank-node-id") ); expect( updatedThing.predicates["https://some.vocab/predicate"].blankNodes ).toStrictEqual(["_:some-blank-node-id"]); }); it("accepts Properties as Named Nodes", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addTerm( thing, DataFactory.namedNode("https://some.vocab/predicate"), DataFactory.namedNode("https://some.pod/other-resource#object") ); expect( updatedThing.predicates["https://some.vocab/predicate"] ).toStrictEqual({ namedNodes: ["https://some.pod/other-resource#object"], }); }); it("does not modify the input Thing", () => { const thing = mockThingFrom("https://some.pod/resource#subject"); const updatedThing = addTerm( thing, "https://some.vocab/predicate", DataFactory.namedNode("https://some.pod/other-resource#object") ); expect(thing).not.toStrictEqual(updatedThing); expect(thing.predicates).toStrictEqual({}); expect( updatedThing.predicates["https://some.vocab/predicate"] ).toStrictEqual({ namedNodes: ["https://some.pod/other-resource#object"], }); }); it("also works on ThingLocals", () => { const thingLocal = mockThingFrom( "https://arbitrary.pod/will-be-replaced-by-local-url" ); (thingLocal.url as string) = `${localNodeSkolemPrefix}localSubject`; const updatedThing = addTerm( thingLocal, "https://some.vocab/predicate", DataFactory.namedNode("https://some.pod/other-resource#object") ); expect( updatedThing.predicates["https://some.vocab/predicate"] ).toStrictEqual({ namedNodes: ["https://some.pod/other-resource#object"], }); }); it("preserves existing values for the same Predicate", () => { const thing: Thing = { type: "Subject", url: "https://some.pod/resource#subject", predicates: { "https://some.vocab/predicate": { blankNodes: ["_:some-blank-node"], }, }, }; const updatedThing = addTerm( thing, "https://some.vocab/predicate", DataFactory.blankNode("some-other-blank-node") ); expect( updatedThing.predicates["https://some.vocab/predicate"] ).toStrictEqual({ blankNodes: ["_:some-blank-node", "_:some-other-blank-node"], }); }); it("preserves existing Quads with different Predicates", () => { const thing: Thing = { type: "Subject", url: "https://some.pod/resource#subject", predicates: { "https://some-other.vocab/predicate": { literals: { "http://www.w3.org/2001/XMLSchema#string": ["Some other value"], }, }, }, }; const updatedThing = addTerm( thing, "https://some.vocab/predicate", DataFactory.namedNode("https://some.pod/other-resource#object") ); expect( updatedThing.predicates["https://some-other.vocab/predicate"] ).toStrictEqual({ literals: { "http://www.w3.org/2001/XMLSchema#string": ["Some other value"], }, }); expect( updatedThing.predicates["https://some.vocab/predicate"] ).toStrictEqual({ namedNodes: ["https://some.pod/other-resource#object"], }); }); it("throws an error when passed something other than a Thing", () => { expect(() => addTerm( null as unknown as Thing, "https://arbitrary.vocab/predicate", DataFactory.namedNode("https://arbitrary.pod/resource#object") ) ).toThrow("Expected a Thing, but received: [null]."); }); it("throws an error when passed an invalid property URL", () => { expect(() => addTerm( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", DataFactory.blankNode() ) ).toThrow( "Expected a valid URL to identify a property, but received: [not-a-url]." ); }); it("throws an error when passed a value of a different type than we understand", () => { expect(() => addTerm( mockThingFrom("https://arbitrary.pod/resource#thing"), "https://arbitrary.vocab/predicate", { termType: "Unsupported term type", value: "Arbitrary value" } as any ) ).toThrow( "Term type [Unsupported term type] is not supported by @inrupt/solid-client." ); }); it("throws an instance of ValidPropertyUrlExpectedError when passed an invalid property URL", () => { let thrownError; try { addTerm( mockThingFrom("https://arbitrary.pod/resource#thing"), "not-a-url", DataFactory.namedNode("https://arbitrary.vocab/object") ); } catch (e) { thrownError = e; } expect(thrownError).toBeInstanceOf(ValidPropertyUrlExpectedError); }); });
the_stack
import WebSocket from 'ws' const fs = require('fs') import cuid from 'cuid' // userName 作为唯一识别码,这个Object 中获取不到微信号,比如能获取到李佳芮的是`qq512436430`,但是获取不到微信号 `ruirui_0914` export interface IpadContactRawPayload { big_head: string, // 'http://wx.qlogo.cn/mmhead/ver_1/y35kAtILvuLr7jntoxRJOnm5SbGjf4g3ALzUHNjK15QRG6hQsw8HBqFQpmKKDN4lIPvBgGscP22jXUruW3LBnA/0', bit_mask: number, // 4294967295, bit_value: number, // 1, chatroom_id: 0 // 0, chatroom_owner: '', // '' city: string, // 'Haidian' continue: number, // 1, country: string, // 'CN' id: number, // 0, img_flag: number, // 1 || 2, don't know why intro: string, // '', label: string, // '', level: number, // 5,7, don't know why max_member_count: number, // 0, // Tips: Only Room has this, Contact don't have [member] para. member?: string, // '[\'mengjunjun001\',\'wxid_6n6wxgvc6dqm22\',\'wxid_m1gvp4237gwl22\',\'a28221798\',\'wxid_ig0fbgf5k5th21\',\'wxid_tgvzoqe1c4612\']\n' member_count: number, // 0, msg_type: number, // 2: Contact Or Room whole content nickName: string, // '梦君君', Contact:用户昵称, Room: 群昵称 provincia: string, // 'Beijing', py_initial: string, // 'MJJ', quan_pin: string, // 'mengjunjun', remark: string, // '女儿', remark_py_initial: string, // 'nver', remark_quan_pin: string, // 'NE', sex: number, // 2 Female, 1 Male, 0 Not Known signature: string, // '且行且珍惜', small_head: string, // 'http://wx.qlogo.cn/mmhead/ver_1/feicWsQuUVrib0F69hXEkTiaMqsNKqurKGNFxOACN7jZZWM4CynGX0K3gK0OgKfCib8D8DUNrIfNRHWOF4pwYTRhLw/132', source: number, // 14, // 0, 14, don't know why status: number, // 1, don't know why stranger: string, // 'v1_0468f2cd3f0efe7ca2589d57c3f9ba952a3789e41b6e78ee00ed53d1e6096b88@stranger', uin: number, // 324216852, userName: string, // 'mengjunjun001' | 'qq512436430' Unique name } const userId = 'test' const msgId = 'abc231923912983' const init = { userId, msgId: cuid(), apiName: 'init', param: [], } const wXInitialize = { userId, msgId: cuid(), apiName: 'wXInitialize', param: [], } const wXGetQRCode = { userId, msgId: cuid(), apiName: 'wXGetQRCode', param: [], } const wXCheckQRCode = { userId, msgId: cuid(), apiName: 'wXCheckQRCode', param: [], } const wXHeartBeat = { userId, msgId: cuid(), apiName: 'wXHeartBeat', param: [], } const wXSyncContact = { userId, msgId: cuid(), apiName: 'wXSyncContact', param: [], } // 生成62 const wXGenerateWxDat = { userId, msgId: cuid(), apiName: 'wXGenerateWxDat', param: [], } // 加载62 const wXLoadWxDat = { userId, msgId: cuid(), apiName: 'wXLoadWxDat', param: [] as string[], } // 获取登陆token const wXGetLoginToken = { userId, msgId: cuid(), apiName: 'wXGetLoginToken', param: [], } // 断线重连 const wXAutoLogin = { userId, msgId: cuid(), apiName: 'wXAutoLogin', param: [] as string[], } // 二次登陆 const wXLoginRequest = { userId, msgId: cuid(), apiName: 'wXLoginRequest', param: [] as string[], } // 发送文本消息 const wXSendMsg = { userId, msgId: cuid(), apiName: 'wXSendMsg', param: [] as string[], } // 获取联系人信息 const wXGetContact = { userId, msgId: cuid(), apiName: 'wXGetContact', param: [], } // 获取联系人信息 const wXSearchContact = { userId, msgId: cuid(), apiName: 'wXSearchContact', param: [], } let botWs: WebSocket let userName: string let nickName: string let password: string let contactSync = false const autoData = { wxData: '', token: '', userName: '', nickName: '', } const ipadContactRawPayloadMap = new Map<string, IpadContactRawPayload>() const connect = async function () { await initConfig() botWs = new WebSocket('ws://101.132.129.155:9091/wx', { perMessageDeflate: true }) botWs.on('open', function open () { try { botWs.send(JSON.stringify(init)) console.log('SEND: ' + JSON.stringify(init)) botWs.send(JSON.stringify(wXInitialize)) console.log('SEND: ' + JSON.stringify(wXInitialize)) // 判断存62 的地方有没有62,如果有 wXLoadWxDat,加载,如果没有,就算了 if (autoData.wxData) { console.log(`$$$$$$$$$$ 发现的62数据 $$$$$$$$$$`) wXLoadWxDat.param = [encodeURIComponent(autoData.wxData)] botWs.send(JSON.stringify(wXLoadWxDat)) console.log('SEND: ' + JSON.stringify(wXLoadWxDat)) } if (autoData.token) { console.log(`$$$$$$$$$$ 发现${autoData.nickName} token $$$$$$$$$$`) // 断线重连 console.log('尝试断线重连') wXAutoLogin.param = [encodeURIComponent(autoData.token)] console.log(encodeURIComponent(autoData.token)) botWs.send(JSON.stringify(wXAutoLogin)) console.log('SEND: ' + JSON.stringify(wXAutoLogin)) } else { botWs.send(JSON.stringify(wXGetQRCode)) console.log('SEND: ' + JSON.stringify(wXGetQRCode)) } } catch (error) { console.error(error) throw (error) } }) botWs.on('message', async function incoming (data) { const allData = JSON.parse(String(data)) console.log('========== New Message ==========') console.log(allData) console.log(allData.apiName) console.log(decodeURIComponent(allData.data)) // 断线重连 if (allData.apiName === 'wXAutoLogin') { if (!allData.data) { console.log('获取wXAutoLogin 的data 是空') botWs.send(JSON.stringify(wXGetQRCode)) console.log('SEND: ' + JSON.stringify(wXGetQRCode)) return } const decodeData = JSON.parse(decodeURIComponent(allData.data)) if (decodeData.status === 0) { console.log(`${autoData.nickName} 断线重连成功`) userName = decodeData.userName // 登陆成功 loginSucceed() } else { // 二次登陆, token 有效 wXLoginRequest.param = [encodeURIComponent(autoData.token)] botWs.send(JSON.stringify(wXLoginRequest)) console.log('SEND: ' + JSON.stringify(wXLoginRequest)) } } if (allData.apiName === 'wXLoginRequest') { if (!allData.data) { console.log('no wXLoginRequest data, token 过期') botWs.send(JSON.stringify(wXGetQRCode)) console.log('SEND: ' + JSON.stringify(wXGetQRCode)) return } const decodeData = JSON.parse(decodeURIComponent(allData.data)) if (decodeData.status === 0) { // 判断是否点击确定登陆 console.log('二次登陆判断二维码状态') checkQrcode(allData) } else { botWs.send(JSON.stringify(wXGetQRCode)) console.log('SEND: ' + JSON.stringify(wXGetQRCode)) } } if (allData.apiName === 'wXGetQRCode') { if (!allData.data) { console.log('cannot get wXGetQRCode') botWs.send(JSON.stringify(wXInitialize)) console.log('SEND: ' + JSON.stringify(wXInitialize)) botWs.send(JSON.stringify(wXGetQRCode)) console.log('SEND: ' + JSON.stringify(wXGetQRCode)) return } const decodeData = decodeURIComponent(allData.data) const qrcode = JSON.parse(decodeData) console.log('get qrcode') checkQrcode(allData) fs.writeFile('demo.jpg', qrcode.qr_code, 'base64', async function (err: any) { if (err) throw err }) } // 判断扫码状态 if (allData.apiName === 'wXCheckQRCode') { const qrcodeStatus = JSON.parse(decodeURIComponent(allData.data)) if (qrcodeStatus.status === 0) { console.log('尚未扫码!') setTimeout(() => { botWs.send(JSON.stringify(wXCheckQRCode)) console.log('SEND: ' + JSON.stringify(wXCheckQRCode)) }, 3 * 1000) return } if (qrcodeStatus.status === 1) { console.log('已扫码,尚未登陆') setTimeout(() => { botWs.send(JSON.stringify(wXCheckQRCode)) console.log('SEND: ' + JSON.stringify(wXCheckQRCode)) }, 3 * 1000) return } if (qrcodeStatus.status === 2) { console.log('正在登陆中。。。') userName = qrcodeStatus.userName nickName = qrcodeStatus.nickName password = qrcodeStatus.password const wXQRCodeLogin = { userId, msgId, apiName: 'wXQRCodeLogin', param: [encodeURIComponent(userName), encodeURIComponent(password)], } botWs.send(JSON.stringify(wXQRCodeLogin)) console.log('SEND: ' + JSON.stringify(wXQRCodeLogin)) return } if (qrcodeStatus.status === 3) { console.log('超时') return } if (qrcodeStatus.status === 4) { console.log('取消操作了,重新获取二维码') return } } if (allData.apiName === 'wXGetLoginToken') { const tokenObj = JSON.parse(decodeURIComponent(allData.data)) if (tokenObj.token && tokenObj.status === 0) { console.log('录入token' + tokenObj.token) autoData.token = tokenObj.token } } if (allData.apiName === 'wXGenerateWxDat') { const wxDataObj = JSON.parse(decodeURIComponent(allData.data)) if (wxDataObj.data && wxDataObj.status === 0) { console.log('录入62数据' + wxDataObj.data) autoData.wxData = wxDataObj.data } } if (allData.apiName === 'wXQRCodeLogin') { const qrcodeStatus = JSON.parse(decodeURIComponent(allData.data)) // 还有其他的,看报错原因,比如-3是账号密码错误 if (qrcodeStatus.status === 0) { console.log('登陆成功!') userName = qrcodeStatus.userName nickName = qrcodeStatus.nickName // 登陆成功 loginSucceed() return } if (qrcodeStatus.status === -301) { console.log('301重定向') const wXQRCodeLogin = { userId, msgId, apiName: 'wXQRCodeLogin', param: [encodeURIComponent(userName), encodeURIComponent(password)], } botWs.send(JSON.stringify(wXQRCodeLogin)) console.log('SEND: ' + JSON.stringify(wXQRCodeLogin)) return } } // 循环调用 wXSyncContact if (allData.apiName === 'wXSyncContact' && contactSync === false) { if (!allData.data) { console.log('allData 没有data 了, 加载完成') contactSync = true wXSendMsg.param = [encodeURIComponent(userName), encodeURIComponent('通讯录同步完成'), ''] botWs.send(JSON.stringify(wXSendMsg)) console.log('SEND: ' + JSON.stringify(wXSendMsg)) return } const contactStatus = JSON.parse(decodeURIComponent(allData.data)) // msg_type: 2 才是通讯录消息,如果是其他的是文字消息、音频消息,同 MSG_TYPE if (Array.isArray(contactStatus)) { contactStatus.forEach(element => { if (element.continue === 0) { contactSync = true saveToJson(ipadContactRawPayloadMap) console.log('continue 为0 加载完成') wXSendMsg.param = [encodeURIComponent(userName), encodeURIComponent('通讯录同步完成'), ''] botWs.send(JSON.stringify(wXSendMsg)) console.log('SEND: ' + JSON.stringify(wXSendMsg)) return } if (element.continue === 1) { if (element.msg_type === 2) { ipadContactRawPayloadMap.set(element.userName, element as IpadContactRawPayload) } } }) console.log('############### 继续加载 ###############') setTimeout(function () { botWs.send(JSON.stringify(wXSyncContact)) console.log('SEND: ' + JSON.stringify(wXSyncContact)) }, 3 * 1000) } else { console.log('出错啦! contactStatus 不是数组') setTimeout(function () { botWs.send(JSON.stringify(wXSyncContact)) console.log('SEND: ' + JSON.stringify(wXSyncContact)) }, 3 * 1000) } } }) botWs.on('error', async (error) => { console.error('============= detect error =============') await connect() throw error }) botWs.on('close', async () => { console.error('============= detect close =============') await connect() }) } try { setTimeout(async () => { await connect() }, 1) } catch (error) { console.error('Connect to Ws occur error') throw(error) } async function initConfig () { // 获取62数据和token try { const tmpBuf = await fs.readFileSync('./config.json') const data = JSON.parse(String(tmpBuf)) autoData.wxData = data.wxData autoData.token = data.token console.log(`载入设备参数与自动登陆数据:%o + ${JSON.stringify(autoData)}`) } catch (e) { console.log('没有在本地发现设备登录参数或解析数据失败!如首次登录请忽略!') } } function checkQrcode (allData: any) { console.log('begin to checkQrcode') botWs.send(JSON.stringify(wXCheckQRCode)) console.log('SEND: ' + JSON.stringify(wXCheckQRCode)) if (allData.status === 0) { console.log('尚未扫码!') setTimeout(() => { botWs.send(JSON.stringify(wXCheckQRCode)) console.log('SEND: ' + JSON.stringify(wXCheckQRCode)) }, 1000) return } if (allData.status === 1) { console.log('已扫码,尚未登陆') setTimeout(() => { botWs.send(JSON.stringify(wXCheckQRCode)) console.log('SEND: ' + JSON.stringify(wXCheckQRCode)) }, 1000) return } if (allData.status === 2) { console.log('正在登陆中。。。') return } if (allData.status === 3) { return } if (allData.status === 4) { return } } function saveToJson (rawPayload: Map<string, IpadContactRawPayload>) { const rawPayloadJson = {} as { [idx: string]: any } rawPayload.forEach((value , key) => { rawPayloadJson[key] = value }) fs.writeFileSync('./contact.json', JSON.stringify(rawPayloadJson, null, 2)) console.log('已写入json file 中') } function saveConfig () { if (autoData.wxData && autoData.token) { fs.writeFileSync('./config.json', JSON.stringify(autoData, null, 2)) console.log('已写入config file 中') } else { console.log('数据不全,稍后重新录入') console.log(autoData) setTimeout(saveConfig, 2 * 1000) } } function loginSucceed () { // 设置心跳 botWs.send(JSON.stringify(wXHeartBeat)) console.log('SEND: ' + JSON.stringify(wXHeartBeat)) autoData.token = '' botWs.send(JSON.stringify(wXGetLoginToken)) console.log('SEND: ' + JSON.stringify(wXGetLoginToken)) wXSendMsg.param = [encodeURIComponent(userName), encodeURIComponent('ding'), ''] botWs.send(JSON.stringify(wXSendMsg)) console.log('SEND: ' + JSON.stringify(wXSendMsg)) // 判断是否有62,如果没有,就调用。 第一次调用的时候,在这里存62数据 if (!autoData.wxData || autoData.userName !== userName) { console.log('没有62数据,或者62数据和wxid 不符合') autoData.userName = userName autoData.nickName = nickName botWs.send(JSON.stringify(wXGenerateWxDat)) console.log('SEND: ' + JSON.stringify(wXGenerateWxDat)) } saveConfig() wXSendMsg.param = [encodeURIComponent(userName), encodeURIComponent('我上线了'), ''] botWs.send(JSON.stringify(wXSendMsg)) console.log('SEND: ' + JSON.stringify(wXSendMsg)) // 同步通讯录 botWs.send(JSON.stringify(wXSyncContact)) console.log('SEND: ' + JSON.stringify(wXSyncContact)) // console.log(' wXGetContact done !!!! qq512436430') // wXGetContact.param = [encodeURIComponent('qq512436430')] // botWs.send(JSON.stringify(wXGetContact)) // console.log('SEND: ' + JSON.stringify(wXGetContact)) // console.log(' wXGetContact done !!!! fake 11111') // wXGetContact.param = [encodeURIComponent('11111')] // botWs.send(JSON.stringify(wXGetContact)) // console.log('SEND: ' + JSON.stringify(wXGetContact)) // console.log(' wXSearchContact done !!!! qq512436430') // wXSearchContact.param = [encodeURIComponent('qq512436430')] // botWs.send(JSON.stringify(wXSearchContact)) // console.log('SEND: ' + JSON.stringify(wXSearchContact)) // console.log(' wXSearchContact done !!!! fake 11111') // wXSearchContact.param = [encodeURIComponent('11111')] // botWs.send(JSON.stringify(wXSearchContact)) // console.log('SEND: ' + JSON.stringify(wXSearchContact)) }
the_stack
import { OperationParameter, OperationURLParameter, OperationQueryParameter } from "@azure/core-client"; import { Profile as ProfileMapper, ProfileUpdateParameters as ProfileUpdateParametersMapper, Endpoint as EndpointMapper, EndpointUpdateParameters as EndpointUpdateParametersMapper, PurgeParameters as PurgeParametersMapper, LoadParameters as LoadParametersMapper, ValidateCustomDomainInput as ValidateCustomDomainInputMapper, Origin as OriginMapper, OriginUpdateParameters as OriginUpdateParametersMapper, OriginGroup as OriginGroupMapper, OriginGroupUpdateParameters as OriginGroupUpdateParametersMapper, CustomDomainParameters as CustomDomainParametersMapper, CustomDomainHttpsParameters as CustomDomainHttpsParametersMapper, CheckNameAvailabilityInput as CheckNameAvailabilityInputMapper, ValidateProbeInput as ValidateProbeInputMapper, AFDDomain as AFDDomainMapper, AFDDomainUpdateParameters as AFDDomainUpdateParametersMapper, AFDEndpoint as AFDEndpointMapper, AFDEndpointUpdateParameters as AFDEndpointUpdateParametersMapper, AfdPurgeParameters as AfdPurgeParametersMapper, AFDOriginGroup as AFDOriginGroupMapper, AFDOriginGroupUpdateParameters as AFDOriginGroupUpdateParametersMapper, AFDOrigin as AFDOriginMapper, AFDOriginUpdateParameters as AFDOriginUpdateParametersMapper, Route as RouteMapper, RouteUpdateParameters as RouteUpdateParametersMapper, Rule as RuleMapper, RuleUpdateParameters as RuleUpdateParametersMapper, SecurityPolicy as SecurityPolicyMapper, SecurityPolicyProperties as SecurityPolicyPropertiesMapper, Secret as SecretMapper, SecretProperties as SecretPropertiesMapper, ValidateSecretInput as ValidateSecretInputMapper, CdnWebApplicationFirewallPolicy as CdnWebApplicationFirewallPolicyMapper, CdnWebApplicationFirewallPolicyPatchParameters as CdnWebApplicationFirewallPolicyPatchParametersMapper } from "../models/mappers"; export const accept: OperationParameter = { parameterPath: "accept", mapper: { defaultValue: "application/json", isConstant: true, serializedName: "Accept", type: { name: "String" } } }; export const $host: OperationURLParameter = { parameterPath: "$host", mapper: { serializedName: "$host", required: true, type: { name: "String" } }, skipEncoding: true }; export const subscriptionId: OperationURLParameter = { parameterPath: "subscriptionId", mapper: { serializedName: "subscriptionId", required: true, type: { name: "String" } } }; export const apiVersion: OperationQueryParameter = { parameterPath: "apiVersion", mapper: { defaultValue: "2020-09-01", isConstant: true, serializedName: "api-version", type: { name: "String" } } }; export const resourceGroupName: OperationURLParameter = { parameterPath: "resourceGroupName", mapper: { constraints: { Pattern: new RegExp("^[-\\w\\._\\(\\)]+$"), MaxLength: 90, MinLength: 1 }, serializedName: "resourceGroupName", required: true, type: { name: "String" } } }; export const profileName: OperationURLParameter = { parameterPath: "profileName", mapper: { serializedName: "profileName", required: true, type: { name: "String" } } }; export const contentType: OperationParameter = { parameterPath: ["options", "contentType"], mapper: { defaultValue: "application/json", isConstant: true, serializedName: "Content-Type", type: { name: "String" } } }; export const profile: OperationParameter = { parameterPath: "profile", mapper: ProfileMapper }; export const profileUpdateParameters: OperationParameter = { parameterPath: "profileUpdateParameters", mapper: ProfileUpdateParametersMapper }; export const nextLink: OperationURLParameter = { parameterPath: "nextLink", mapper: { serializedName: "nextLink", required: true, type: { name: "String" } }, skipEncoding: true }; export const endpointName: OperationURLParameter = { parameterPath: "endpointName", mapper: { serializedName: "endpointName", required: true, type: { name: "String" } } }; export const endpoint: OperationParameter = { parameterPath: "endpoint", mapper: EndpointMapper }; export const endpointUpdateProperties: OperationParameter = { parameterPath: "endpointUpdateProperties", mapper: EndpointUpdateParametersMapper }; export const contentFilePaths: OperationParameter = { parameterPath: "contentFilePaths", mapper: PurgeParametersMapper }; export const contentFilePaths1: OperationParameter = { parameterPath: "contentFilePaths", mapper: LoadParametersMapper }; export const customDomainProperties: OperationParameter = { parameterPath: "customDomainProperties", mapper: ValidateCustomDomainInputMapper }; export const originName: OperationURLParameter = { parameterPath: "originName", mapper: { serializedName: "originName", required: true, type: { name: "String" } } }; export const origin: OperationParameter = { parameterPath: "origin", mapper: OriginMapper }; export const originUpdateProperties: OperationParameter = { parameterPath: "originUpdateProperties", mapper: OriginUpdateParametersMapper }; export const originGroupName: OperationURLParameter = { parameterPath: "originGroupName", mapper: { serializedName: "originGroupName", required: true, type: { name: "String" } } }; export const originGroup: OperationParameter = { parameterPath: "originGroup", mapper: OriginGroupMapper }; export const originGroupUpdateProperties: OperationParameter = { parameterPath: "originGroupUpdateProperties", mapper: OriginGroupUpdateParametersMapper }; export const customDomainName: OperationURLParameter = { parameterPath: "customDomainName", mapper: { serializedName: "customDomainName", required: true, type: { name: "String" } } }; export const customDomainProperties1: OperationParameter = { parameterPath: "customDomainProperties", mapper: CustomDomainParametersMapper }; export const customDomainHttpsParameters: OperationParameter = { parameterPath: ["options", "customDomainHttpsParameters"], mapper: CustomDomainHttpsParametersMapper }; export const checkNameAvailabilityInput: OperationParameter = { parameterPath: "checkNameAvailabilityInput", mapper: CheckNameAvailabilityInputMapper }; export const validateProbeInput: OperationParameter = { parameterPath: "validateProbeInput", mapper: ValidateProbeInputMapper }; export const checkHostNameAvailabilityInput: OperationParameter = { parameterPath: "checkHostNameAvailabilityInput", mapper: ValidateCustomDomainInputMapper }; export const customDomain: OperationParameter = { parameterPath: "customDomain", mapper: AFDDomainMapper }; export const customDomainUpdateProperties: OperationParameter = { parameterPath: "customDomainUpdateProperties", mapper: AFDDomainUpdateParametersMapper }; export const endpoint1: OperationParameter = { parameterPath: "endpoint", mapper: AFDEndpointMapper }; export const endpointUpdateProperties1: OperationParameter = { parameterPath: "endpointUpdateProperties", mapper: AFDEndpointUpdateParametersMapper }; export const contents: OperationParameter = { parameterPath: "contents", mapper: AfdPurgeParametersMapper }; export const originGroup1: OperationParameter = { parameterPath: "originGroup", mapper: AFDOriginGroupMapper }; export const originGroupUpdateProperties1: OperationParameter = { parameterPath: "originGroupUpdateProperties", mapper: AFDOriginGroupUpdateParametersMapper }; export const origin1: OperationParameter = { parameterPath: "origin", mapper: AFDOriginMapper }; export const originUpdateProperties1: OperationParameter = { parameterPath: "originUpdateProperties", mapper: AFDOriginUpdateParametersMapper }; export const routeName: OperationURLParameter = { parameterPath: "routeName", mapper: { serializedName: "routeName", required: true, type: { name: "String" } } }; export const route: OperationParameter = { parameterPath: "route", mapper: RouteMapper }; export const routeUpdateProperties: OperationParameter = { parameterPath: "routeUpdateProperties", mapper: RouteUpdateParametersMapper }; export const ruleSetName: OperationURLParameter = { parameterPath: "ruleSetName", mapper: { serializedName: "ruleSetName", required: true, type: { name: "String" } } }; export const ruleName: OperationURLParameter = { parameterPath: "ruleName", mapper: { serializedName: "ruleName", required: true, type: { name: "String" } } }; export const rule: OperationParameter = { parameterPath: "rule", mapper: RuleMapper }; export const ruleUpdateProperties: OperationParameter = { parameterPath: "ruleUpdateProperties", mapper: RuleUpdateParametersMapper }; export const securityPolicyName: OperationURLParameter = { parameterPath: "securityPolicyName", mapper: { serializedName: "securityPolicyName", required: true, type: { name: "String" } } }; export const securityPolicy: OperationParameter = { parameterPath: "securityPolicy", mapper: SecurityPolicyMapper }; export const securityPolicyProperties: OperationParameter = { parameterPath: "securityPolicyProperties", mapper: SecurityPolicyPropertiesMapper }; export const secretName: OperationURLParameter = { parameterPath: "secretName", mapper: { serializedName: "secretName", required: true, type: { name: "String" } } }; export const secret: OperationParameter = { parameterPath: "secret", mapper: SecretMapper }; export const secretProperties: OperationParameter = { parameterPath: "secretProperties", mapper: SecretPropertiesMapper }; export const validateSecretInput: OperationParameter = { parameterPath: "validateSecretInput", mapper: ValidateSecretInputMapper }; export const metrics: OperationQueryParameter = { parameterPath: "metrics", mapper: { serializedName: "metrics", required: true, type: { name: "Sequence", element: { type: { name: "String" } } } }, collectionFormat: "Multi" }; export const dateTimeBegin: OperationQueryParameter = { parameterPath: "dateTimeBegin", mapper: { serializedName: "dateTimeBegin", required: true, type: { name: "DateTime" } } }; export const dateTimeEnd: OperationQueryParameter = { parameterPath: "dateTimeEnd", mapper: { serializedName: "dateTimeEnd", required: true, type: { name: "DateTime" } } }; export const granularity: OperationQueryParameter = { parameterPath: "granularity", mapper: { serializedName: "granularity", required: true, type: { name: "String" } } }; export const groupBy: OperationQueryParameter = { parameterPath: ["options", "groupBy"], mapper: { serializedName: "groupBy", type: { name: "Sequence", element: { type: { name: "String" } } } }, collectionFormat: "Multi" }; export const continents: OperationQueryParameter = { parameterPath: ["options", "continents"], mapper: { serializedName: "continents", type: { name: "Sequence", element: { type: { name: "String" } } } }, collectionFormat: "Multi" }; export const countryOrRegions: OperationQueryParameter = { parameterPath: ["options", "countryOrRegions"], mapper: { serializedName: "countryOrRegions", type: { name: "Sequence", element: { type: { name: "String" } } } }, collectionFormat: "Multi" }; export const customDomains: OperationQueryParameter = { parameterPath: "customDomains", mapper: { serializedName: "customDomains", required: true, type: { name: "Sequence", element: { type: { name: "String" } } } }, collectionFormat: "Multi" }; export const protocols: OperationQueryParameter = { parameterPath: "protocols", mapper: { serializedName: "protocols", required: true, type: { name: "Sequence", element: { type: { name: "String" } } } }, collectionFormat: "Multi" }; export const rankings: OperationQueryParameter = { parameterPath: "rankings", mapper: { serializedName: "rankings", required: true, type: { name: "Sequence", element: { type: { name: "String" } } } }, collectionFormat: "Multi" }; export const metrics1: OperationQueryParameter = { parameterPath: "metrics", mapper: { serializedName: "metrics", required: true, type: { name: "Sequence", element: { type: { name: "String" } } } }, collectionFormat: "Multi" }; export const maxRanking: OperationQueryParameter = { parameterPath: "maxRanking", mapper: { serializedName: "maxRanking", required: true, type: { name: "Number" } } }; export const customDomains1: OperationQueryParameter = { parameterPath: ["options", "customDomains"], mapper: { serializedName: "customDomains", type: { name: "Sequence", element: { type: { name: "String" } } } }, collectionFormat: "Multi" }; export const metrics2: OperationQueryParameter = { parameterPath: "metrics", mapper: { serializedName: "metrics", required: true, type: { name: "Sequence", element: { type: { name: "String" } } } }, collectionFormat: "Multi" }; export const granularity1: OperationQueryParameter = { parameterPath: "granularity", mapper: { serializedName: "granularity", required: true, type: { name: "String" } } }; export const actions: OperationQueryParameter = { parameterPath: ["options", "actions"], mapper: { serializedName: "actions", type: { name: "Sequence", element: { type: { name: "String" } } } }, collectionFormat: "Multi" }; export const groupBy1: OperationQueryParameter = { parameterPath: ["options", "groupBy"], mapper: { serializedName: "groupBy", type: { name: "Sequence", element: { type: { name: "String" } } } }, collectionFormat: "Multi" }; export const ruleTypes: OperationQueryParameter = { parameterPath: ["options", "ruleTypes"], mapper: { serializedName: "ruleTypes", type: { name: "Sequence", element: { type: { name: "String" } } } }, collectionFormat: "Multi" }; export const rankings1: OperationQueryParameter = { parameterPath: "rankings", mapper: { serializedName: "rankings", required: true, type: { name: "Sequence", element: { type: { name: "String" } } } }, collectionFormat: "Multi" }; export const resourceGroupName1: OperationURLParameter = { parameterPath: "resourceGroupName", mapper: { constraints: { Pattern: new RegExp("^[a-zA-Z0-9_\\-\\(\\)\\.]*[^\\.]$"), MaxLength: 80, MinLength: 1 }, serializedName: "resourceGroupName", required: true, type: { name: "String" } } }; export const policyName: OperationURLParameter = { parameterPath: "policyName", mapper: { constraints: { MaxLength: 128 }, serializedName: "policyName", required: true, type: { name: "String" } } }; export const cdnWebApplicationFirewallPolicy: OperationParameter = { parameterPath: "cdnWebApplicationFirewallPolicy", mapper: CdnWebApplicationFirewallPolicyMapper }; export const cdnWebApplicationFirewallPolicyPatchParameters: OperationParameter = { parameterPath: "cdnWebApplicationFirewallPolicyPatchParameters", mapper: CdnWebApplicationFirewallPolicyPatchParametersMapper };
the_stack
import { EDITOR } from 'internal:constants'; import { builtinResMgr } from '../../core/builtin'; import { Material } from '../../core/assets'; import { AttributeName, Format, Attribute } from '../../core/gfx'; import { Mat4, Vec2, Vec3, Vec4, pseudoRandom, Quat } from '../../core/math'; import { RecyclePool } from '../../core/memop'; import { MaterialInstance, IMaterialInstanceInfo } from '../../core/renderer/core/material-instance'; import { MacroRecord } from '../../core/renderer/core/pass-utils'; import { AlignmentSpace, RenderMode, Space } from '../enum'; import { Particle, IParticleModule, PARTICLE_MODULE_ORDER } from '../particle'; import { ParticleSystemRendererBase } from './particle-system-renderer-base'; import { Component } from '../../core'; import { Camera } from '../../core/renderer/scene/camera'; const _tempAttribUV = new Vec3(); const _tempWorldTrans = new Mat4(); const _node_rot = new Quat(); const _node_euler = new Vec3(); const _anim_module = [ '_colorOverLifetimeModule', '_sizeOvertimeModule', '_velocityOvertimeModule', '_forceOvertimeModule', '_limitVelocityOvertimeModule', '_rotationOvertimeModule', '_textureAnimationModule', ]; const _uvs = [ 0, 0, // bottom-left 1, 0, // bottom-right 0, 1, // top-left 1, 1, // top-right ]; const CC_USE_WORLD_SPACE = 'CC_USE_WORLD_SPACE'; const CC_RENDER_MODE = 'CC_RENDER_MODE'; const ROTATION_OVER_TIME_MODULE_ENABLE = 'ROTATION_OVER_TIME_MODULE_ENABLE'; const RENDER_MODE_BILLBOARD = 0; const RENDER_MODE_STRETCHED_BILLBOARD = 1; const RENDER_MODE_HORIZONTAL_BILLBOARD = 2; const RENDER_MODE_VERTICAL_BILLBOARD = 3; const RENDER_MODE_MESH = 4; const _vertex_attrs = [ new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), // position new Attribute(AttributeName.ATTR_TEX_COORD, Format.RGB32F), // uv,frame idx new Attribute(AttributeName.ATTR_TEX_COORD1, Format.RGB32F), // size new Attribute(AttributeName.ATTR_TEX_COORD2, Format.RGB32F), // rotation new Attribute(AttributeName.ATTR_COLOR, Format.RGBA8, true), // color ]; const _vertex_attrs_stretch = [ new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), // position new Attribute(AttributeName.ATTR_TEX_COORD, Format.RGB32F), // uv,frame idx new Attribute(AttributeName.ATTR_TEX_COORD1, Format.RGB32F), // size new Attribute(AttributeName.ATTR_TEX_COORD2, Format.RGB32F), // rotation new Attribute(AttributeName.ATTR_COLOR, Format.RGBA8, true), // color new Attribute(AttributeName.ATTR_COLOR1, Format.RGB32F), // particle velocity ]; const _vertex_attrs_mesh = [ new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), // particle position new Attribute(AttributeName.ATTR_TEX_COORD, Format.RGB32F), // uv,frame idx new Attribute(AttributeName.ATTR_TEX_COORD1, Format.RGB32F), // size new Attribute(AttributeName.ATTR_TEX_COORD2, Format.RGB32F), // rotation new Attribute(AttributeName.ATTR_COLOR, Format.RGBA8, true), // particle color new Attribute(AttributeName.ATTR_TEX_COORD3, Format.RGB32F), // mesh position new Attribute(AttributeName.ATTR_NORMAL, Format.RGB32F), // mesh normal new Attribute(AttributeName.ATTR_COLOR1, Format.RGBA8, true), // mesh color ]; const _matInsInfo: IMaterialInstanceInfo = { parent: null!, owner: null!, subModelIdx: 0, }; export default class ParticleSystemRendererCPU extends ParticleSystemRendererBase { private _defines: MacroRecord; private _trailDefines: MacroRecord; private _frameTile_velLenScale: Vec4; private _tmp_velLenScale: Vec4; private _defaultMat: Material | null = null; private _node_scale: Vec4; private _attrs: any[]; private _particles: RecyclePool | null = null; private _defaultTrailMat: Material | null = null; private _updateList: Map<string, IParticleModule> = new Map<string, IParticleModule>(); private _animateList: Map<string, IParticleModule> = new Map<string, IParticleModule>(); private _runAnimateList: IParticleModule[] = new Array<IParticleModule>(); private _fillDataFunc: any = null; private _uScaleHandle = 0; private _uLenHandle = 0; private _uNodeRotHandle = 0; private _alignSpace = AlignmentSpace.View; private _inited = false; private _localMat: Mat4 = new Mat4(); private _gravity: Vec4 = new Vec4(); constructor (info: any) { super(info); this._model = null; this._frameTile_velLenScale = new Vec4(1, 1, 0, 0); this._tmp_velLenScale = this._frameTile_velLenScale.clone(); this._node_scale = new Vec4(); this._attrs = new Array(5); this._defines = { CC_USE_WORLD_SPACE: true, CC_USE_BILLBOARD: true, CC_USE_STRETCHED_BILLBOARD: false, CC_USE_HORIZONTAL_BILLBOARD: false, CC_USE_VERTICAL_BILLBOARD: false, }; this._trailDefines = { CC_USE_WORLD_SPACE: true, // CC_DRAW_WIRE_FRAME: true, // <wireframe debug> }; } public onInit (ps: Component) { super.onInit(ps); this._particles = new RecyclePool(() => new Particle(this), 16); this._setVertexAttrib(); this._setFillFunc(); this._initModuleList(); this._initModel(); this.updateMaterialParams(); this.updateTrailMaterial(); this.setVertexAttributes(); this._inited = true; } public clear () { super.clear(); this._particles!.reset(); if (this._particleSystem._trailModule) { this._particleSystem._trailModule.clear(); } this.updateRenderData(); this._model!.enabled = false; } public updateRenderMode () { this._setVertexAttrib(); this._setFillFunc(); this.updateMaterialParams(); this.setVertexAttributes(); } public getFreeParticle (): Particle | null { if (this._particles!.length >= this._particleSystem.capacity) { return null; } return this._particles!.add() as Particle; } public getDefaultTrailMaterial (): any { return this._defaultTrailMat; } public setNewParticle (p: Particle) { } private _initModuleList () { _anim_module.forEach((val) => { const pm = this._particleSystem[val]; if (pm && pm.enable) { if (pm.needUpdate) { this._updateList[pm.name] = pm; } if (pm.needAnimate) { this._animateList[pm.name] = pm; } } }); // reorder this._runAnimateList.length = 0; for (let i = 0, len = PARTICLE_MODULE_ORDER.length; i < len; i++) { const p = this._animateList[PARTICLE_MODULE_ORDER[i]]; if (p) { this._runAnimateList.push(p); } } } public enableModule (name: string, val: boolean, pm: IParticleModule) { if (val) { if (pm.needUpdate) { this._updateList[pm.name] = pm; } if (pm.needAnimate) { this._animateList[pm.name] = pm; } } else { delete this._animateList[name]; delete this._updateList[name]; } // reorder this._runAnimateList.length = 0; for (let i = 0, len = PARTICLE_MODULE_ORDER.length; i < len; i++) { const p = this._animateList[PARTICLE_MODULE_ORDER[i]]; if (p) { this._runAnimateList.push(p); } } this.updateMaterialParams(); } public updateAlignSpace (space) { this._alignSpace = space; } public updateParticles (dt: number) { const ps = this._particleSystem; if (!ps) { return this._particles!.length; } ps.node.getWorldMatrix(_tempWorldTrans); switch (ps.scaleSpace) { case Space.Local: ps.node.getScale(this._node_scale); break; case Space.World: ps.node.getWorldScale(this._node_scale); break; default: break; } const mat: Material | null = ps.getMaterialInstance(0) || this._defaultMat; const pass = mat!.passes[0]; pass.setUniform(this._uScaleHandle, this._node_scale); if (this._alignSpace === AlignmentSpace.Local) { this._particleSystem.node.getRotation(_node_rot); } else if (this._alignSpace === AlignmentSpace.World) { this._particleSystem.node.getWorldRotation(_node_rot); } else if (this._alignSpace === AlignmentSpace.View) { // Quat.fromEuler(_node_rot, 0.0, 0.0, 0.0); _node_rot.set(0.0, 0.0, 0.0, 1.0); const cameraLst: Camera[]|undefined = this._particleSystem.node.scene.renderScene?.cameras; if (cameraLst !== undefined) { for (let i = 0; i < cameraLst?.length; ++i) { const camera:Camera = cameraLst[i]; // eslint-disable-next-line max-len const checkCamera: boolean = !EDITOR ? (camera.visibility & this._particleSystem.node.layer) === this._particleSystem.node.layer : camera.name === 'Editor Camera'; if (checkCamera) { Quat.fromViewUp(_node_rot, camera.forward); break; } } } } else { _node_rot.set(0.0, 0.0, 0.0, 1.0); } pass.setUniform(this._uNodeRotHandle, _node_rot); this._updateList.forEach((value: IParticleModule, key: string) => { value.update(ps._simulationSpace, _tempWorldTrans); }); const trailModule = ps._trailModule; const trailEnable = trailModule && trailModule.enable; if (trailEnable) { trailModule.update(); } if (ps.simulationSpace === Space.Local) { const r:Quat = ps.node.getRotation(); Mat4.fromQuat(this._localMat, r); this._localMat.transpose(); // just consider rotation, use transpose as invert } for (let i = 0; i < this._particles!.length; ++i) { const p = this._particles!.data[i]; p.remainingLifetime -= dt; Vec3.set(p.animatedVelocity, 0, 0, 0); if (p.remainingLifetime < 0.0) { if (trailEnable) { trailModule.removeParticle(p); } this._particles!.removeAt(i); --i; continue; } if (ps.simulationSpace === Space.Local) { const gravityFactor = -ps.gravityModifier.evaluate(1 - p.remainingLifetime / p.startLifetime, pseudoRandom(p.randomSeed))! * 9.8 * dt; this._gravity.x = 0.0; this._gravity.y = gravityFactor; this._gravity.z = 0.0; this._gravity.w = 1.0; this._gravity = this._gravity.transformMat4(this._localMat); p.velocity.x += this._gravity.x; p.velocity.y += this._gravity.y; p.velocity.z += this._gravity.z; } else { // apply gravity. p.velocity.y -= ps.gravityModifier.evaluate(1 - p.remainingLifetime / p.startLifetime, pseudoRandom(p.randomSeed))! * 9.8 * dt; } Vec3.copy(p.ultimateVelocity, p.velocity); this._runAnimateList.forEach((value) => { value.animate(p, dt); }); Vec3.scaleAndAdd(p.position, p.position, p.ultimateVelocity, dt); // apply velocity. if (trailEnable) { trailModule.animate(p, dt); } } this._model!.enabled = this._particles!.length > 0; return this._particles!.length; } // internal function public updateRenderData () { // update vertex buffer let idx = 0; for (let i = 0; i < this._particles!.length; ++i) { const p = this._particles!.data[i]; let fi = 0; const textureModule = this._particleSystem._textureAnimationModule; if (textureModule && textureModule.enable) { fi = p.frameIndex; } idx = i * 4; this._fillDataFunc(p, idx, fi); } } public beforeRender () { // because we use index buffer, per particle index count = 6. this._model!.updateIA(this._particles!.length); } public getParticleCount (): number { return this._particles!.length; } public onMaterialModified (index: number, material: Material) { if (!this._inited) { return; } if (index === 0) { this.updateMaterialParams(); } else { this.updateTrailMaterial(); } } public onRebuildPSO (index: number, material: Material) { if (this._model && index === 0) { this._model.setSubModelMaterial(0, material); } const trailModule = this._particleSystem._trailModule; if (trailModule && trailModule._trailModel && index === 1) { trailModule._trailModel.setSubModelMaterial(0, material); } } private _setFillFunc () { if (this._renderInfo!.renderMode === RenderMode.Mesh) { this._fillDataFunc = this._fillMeshData; } else if (this._renderInfo!.renderMode === RenderMode.StrecthedBillboard) { this._fillDataFunc = this._fillStrecthedData; } else { this._fillDataFunc = this._fillNormalData; } } private _fillMeshData (p: Particle, idx: number, fi: number) { const i = idx / 4; this._attrs[0] = p.position; _tempAttribUV.z = fi; this._attrs[1] = _tempAttribUV; this._attrs[2] = p.size; this._attrs[3] = p.rotation; this._attrs[4] = p.color._val; this._model!.addParticleVertexData(i, this._attrs); } private _fillStrecthedData (p: Particle, idx: number, fi: number) { for (let j = 0; j < 4; ++j) { // four verts per particle. this._attrs[0] = p.position; _tempAttribUV.x = _uvs[2 * j]; _tempAttribUV.y = _uvs[2 * j + 1]; _tempAttribUV.z = fi; this._attrs[1] = _tempAttribUV; this._attrs[2] = p.size; this._attrs[3] = p.rotation; this._attrs[4] = p.color._val; this._attrs[5] = p.ultimateVelocity; this._attrs[6] = null; this._model!.addParticleVertexData(idx++, this._attrs); } } private _fillNormalData (p: Particle, idx: number, fi: number) { for (let j = 0; j < 4; ++j) { // four verts per particle. this._attrs[0] = p.position; _tempAttribUV.x = _uvs[2 * j]; _tempAttribUV.y = _uvs[2 * j + 1]; _tempAttribUV.z = fi; this._attrs[1] = _tempAttribUV; this._attrs[2] = p.size; this._attrs[3] = p.rotation; this._attrs[4] = p.color._val; this._attrs[5] = null; this._model!.addParticleVertexData(idx++, this._attrs); } } private _setVertexAttrib () { switch (this._renderInfo!.renderMode) { case RenderMode.StrecthedBillboard: this._vertAttrs = _vertex_attrs_stretch.slice(); break; case RenderMode.Mesh: this._vertAttrs = _vertex_attrs_mesh.slice(); break; default: this._vertAttrs = _vertex_attrs.slice(); } } public updateMaterialParams () { if (!this._particleSystem) { return; } const ps = this._particleSystem; const shareMaterial = ps.sharedMaterial; if (shareMaterial != null) { const effectName = shareMaterial._effectAsset._name; this._renderInfo!.mainTexture = shareMaterial.getProperty('mainTexture', 0); // reset material if (effectName.indexOf('particle') === -1 || effectName.indexOf('particle-gpu') !== -1) { ps.setMaterial(null, 0); } } if (ps.sharedMaterial == null && this._defaultMat == null) { _matInsInfo.parent = builtinResMgr.get<Material>('default-particle-material'); _matInsInfo.owner = this._particleSystem; _matInsInfo.subModelIdx = 0; this._defaultMat = new MaterialInstance(_matInsInfo); _matInsInfo.parent = null!; _matInsInfo.owner = null!; _matInsInfo.subModelIdx = 0; if (this._renderInfo!.mainTexture !== null) { this._defaultMat.setProperty('mainTexture', this._renderInfo!.mainTexture); } } const mat: Material = ps.getMaterialInstance(0) || this._defaultMat; if (ps._simulationSpace === Space.World) { this._defines[CC_USE_WORLD_SPACE] = true; } else { this._defines[CC_USE_WORLD_SPACE] = false; } const pass = mat.passes[0]; this._uScaleHandle = pass.getHandle('scale'); this._uLenHandle = pass.getHandle('frameTile_velLenScale'); this._uNodeRotHandle = pass.getHandle('nodeRotation'); const renderMode = this._renderInfo!.renderMode; const vlenScale = this._frameTile_velLenScale; if (renderMode === RenderMode.Billboard) { this._defines[CC_RENDER_MODE] = RENDER_MODE_BILLBOARD; } else if (renderMode === RenderMode.StrecthedBillboard) { this._defines[CC_RENDER_MODE] = RENDER_MODE_STRETCHED_BILLBOARD; vlenScale.z = this._renderInfo!.velocityScale; vlenScale.w = this._renderInfo!.lengthScale; } else if (renderMode === RenderMode.HorizontalBillboard) { this._defines[CC_RENDER_MODE] = RENDER_MODE_HORIZONTAL_BILLBOARD; } else if (renderMode === RenderMode.VerticalBillboard) { this._defines[CC_RENDER_MODE] = RENDER_MODE_VERTICAL_BILLBOARD; } else if (renderMode === RenderMode.Mesh) { this._defines[CC_RENDER_MODE] = RENDER_MODE_MESH; } else { console.warn(`particle system renderMode ${renderMode} not support.`); } const textureModule = ps._textureAnimationModule; if (textureModule && textureModule.enable) { Vec4.copy(this._tmp_velLenScale, vlenScale); // fix textureModule switch bug Vec2.set(this._tmp_velLenScale, textureModule.numTilesX, textureModule.numTilesY); pass.setUniform(this._uLenHandle, this._tmp_velLenScale); } else { pass.setUniform(this._uLenHandle, vlenScale); } let enable = false; const roationModule = this._particleSystem._rotationOvertimeModule; enable = roationModule && roationModule.enable; this._defines[ROTATION_OVER_TIME_MODULE_ENABLE] = enable; mat.recompileShaders(this._defines); if (this._model) { this._model.updateMaterial(mat); } } public updateTrailMaterial () { if (!this._particleSystem) { return; } const ps = this._particleSystem; const trailModule = ps._trailModule; if (trailModule && trailModule.enable) { if (ps.simulationSpace === Space.World || trailModule.space === Space.World) { this._trailDefines[CC_USE_WORLD_SPACE] = true; } else { this._trailDefines[CC_USE_WORLD_SPACE] = false; } let mat = ps.getMaterialInstance(1); if (mat === null && this._defaultTrailMat === null) { _matInsInfo.parent = builtinResMgr.get<Material>('default-trail-material'); _matInsInfo.owner = this._particleSystem; _matInsInfo.subModelIdx = 1; this._defaultTrailMat = new MaterialInstance(_matInsInfo); _matInsInfo.parent = null!; _matInsInfo.owner = null!; _matInsInfo.subModelIdx = 0; } mat = mat || this._defaultTrailMat; mat.recompileShaders(this._trailDefines); trailModule.updateMaterial(); } } }
the_stack
import * as Chance from 'chance'; import * as set from 'lodash.set'; import * as get from 'lodash.get'; import * as flatten from 'flat'; import { Schema, Document } from 'mongoose'; import ObjectId from 'bson-objectid'; import { factory } from './mocker'; import { FactoryOptions, GlobalOptions, MockerFieldOption, isStringFieldOptions, isPopulateWithFactory, isPopulateWithSchema } from './types'; export type GeneratorOptions = { options: MockerFieldOption, staticFields: Record<string, unknown>, globalOptions: GlobalOptions } const UNDEFINED_PROP_VIA_PARENT = Symbol('UndefinedPropFromParent'); const OBJECT_ID_STRINGIFY_BY_DEFAULT = true; const DECIMAL_128_STRINGIFY_BY_DEFAULT = true; const chance = new Chance(); function getTypeOf(type) { if (typeof type.name === 'string') { return type.name.toLowerCase(); } if (type.constructor.name === 'Schema') { return 'map_value_embedded'; } throw new Error('Unknown type'); } function getRandomInclusive(min, max) { return Math.floor(Math.random() * (max - min + 1) + min); } const generators = { string: (pathDef, { options }: GeneratorOptions) => { if (Array.isArray(pathDef.enumValues) && pathDef.enumValues.length) { return chance.pickone(pathDef.enumValues); } if (isStringFieldOptions(options)) { switch (options.type) { case 'email': return chance.email(); case 'firstname': return chance.first(); case 'lastname': return chance.last(); default: return chance.string(); } } return pathDef.lowercase ? chance.string().toLowerCase() : chance.string(); }, array: (pathDef, { options, staticFields, globalOptions }) => { const num = 2; if (typeof pathDef.caster === 'object') { const innerType = pathDef.caster.instance.toLowerCase(); const generator = generators[innerType]; return Array.from(Array(num)).map(() => generator(pathDef.caster, { options, globalOptions })); } if (typeof pathDef.caster === 'function') { // eslint-disable-next-line no-use-before-define return Array.from(Array(num)).map(() => generate(pathDef.schema, { options, staticFields, globalOptions })); } return null; }, objectid: (pathDef, { options, globalOptions }: GeneratorOptions) => { if ( isPopulateWithFactory(options)) { return options.populateWithFactory.generate() } else if (isPopulateWithSchema(options)) { const mockGen = factory(options.populateWithSchema) return mockGen.generate() } if (get(options, 'tostring', OBJECT_ID_STRINGIFY_BY_DEFAULT) === false || get(globalOptions, 'objectid.tostring', OBJECT_ID_STRINGIFY_BY_DEFAULT) === false) { return new ObjectId(); } return new ObjectId().toString(); }, number: (pathDef) => { if (pathDef.options && Array.isArray(pathDef.options.enum) && pathDef.options.enum.length) { return chance.pickone(pathDef.options.enum); } const numOpt = ['min', 'max'].reduce((opts, att) => { if (pathDef.options && pathDef.options[att]) { const attrValue = Array.isArray(pathDef.options[att]) ? pathDef.options[att][0] : pathDef.options[att]; return Object.assign(opts, { [att]: attrValue }); } return opts; }, {}); return chance.integer(numOpt); }, decimal128: (pathDef, { options, globalOptions }) => { if (get(options, 'tostring', DECIMAL_128_STRINGIFY_BY_DEFAULT) === false || get(globalOptions, 'decimal128.tostring', DECIMAL_128_STRINGIFY_BY_DEFAULT) === false) { return chance.floating(); } return `${chance.floating()}`; }, boolean: () => chance.pickone([true, false]), date: (pathDef) => { let max = 8640000000000000; let min = -8640000000000000; if (pathDef.options && (pathDef.options.min || pathDef.options.max)) { min = pathDef.options.min ? Date.parse(pathDef.options.min) : min; max = pathDef.options.max ? Date.parse(pathDef.options.max) : max; } const timestamp = getRandomInclusive(min, max); return new Date(timestamp); }, buffer: () => Buffer.alloc(1), mixed: (pathDef, { options, globalOptions }) => { const generatorName = chance.pickone(['boolean', 'date', 'number', 'string', 'objectid']); if (!generators[generatorName]) { throw new Error(`Type ${generatorName} not supported`); } return generators[generatorName](pathDef, { options, globalOptions }); }, embedded: (pathDef, { options, staticFields, globalOptions }) => { const { schema } = pathDef; // eslint-disable-next-line no-use-before-define return generate(schema, { options, staticFields, globalOptions }); }, map_value_embedded: (pathDef, { options, staticFields, globalOptions }) => { const schema = pathDef.options.of; // eslint-disable-next-line no-use-before-define return generate(schema, { options, staticFields, globalOptions }); }, map: (pathDef, { options, globalOptions }) => { const generatorName = pathDef.options.of ? getTypeOf(pathDef.options.of) : 'mixed'; if (!generators[generatorName]) { throw new Error(`Type ${generatorName} not supported`); } const generator = generators[generatorName]; const keyCount = chance.integer({ min: 1, max: 10 }); const keys = Array.from(new Array(keyCount)) .map(() => chance.string({ pool: 'abcdefghijklmnopqrstuvwxyz' })); const mock = keys.reduce( (obj, key) => Object.assign(obj, { [key]: generator(pathDef, { options, globalOptions }) }), {}, ); return mock; }, }; const getPropertyByPath = (object, path) => get(object, path); const getPropertyByName = (object, propName) => object[propName]; const propertyIsSkipped = (path, options) => { const fieldOptions = getPropertyByName(options, path) || getPropertyByPath(options, path) || {}; return fieldOptions.skip === true; }; const propertyParentIsSkipped = (path, options) => { const pathProps = path.split('.'); if (pathProps.length > 1) { let parentPath = ''; // eslint-disable-next-line no-restricted-syntax for (const pathProp of pathProps) { parentPath = parentPath.length === 0 ? pathProp : `${parentPath}.${pathProp}`; const parentObject = getPropertyByPath(options, parentPath) || getPropertyByName(options, parentPath) || {}; if (parentObject.skip === true) { return true; } } } return false; }; const shouldSkipProperty = (path, options) => propertyIsSkipped(path, options) || propertyParentIsSkipped(path, options); function populateField(mockObject, { schema, path, options, staticValue, indirectValues = {}, globalOptions = {}, }) { const fieldOptions = getPropertyByName(options, path) || getPropertyByPath(options, path) || {}; if (!shouldSkipProperty(path, options)) { let value; const pathDef = schema.path(path); const type = pathDef.instance.toLowerCase(); if (staticValue !== undefined) { value = staticValue; } else if (staticValue !== undefined && type === 'map') { value = staticValue; } else if (fieldOptions.value && typeof fieldOptions.value === 'function') { value = fieldOptions.value(mockObject); } else if (fieldOptions.value) { ({ value } = fieldOptions); } else if (indirectValues[path]) { value = indirectValues[path]; } else { if (!generators[type]) { throw new Error(`Type ${pathDef.instance} not supported`); } const generator = generators[type]; value = generator(pathDef, { options: fieldOptions, staticFields: staticValue, globalOptions }); } set(mockObject, path, value); } } const getOptionFromParentProperty = (path, options, optionName) => { const pathProps = path.split('.'); if (pathProps.length > 1) { let parentPath = ''; // eslint-disable-next-line no-restricted-syntax for (const pathProp of pathProps) { parentPath = parentPath.length === 0 ? pathProp : `${parentPath}.${pathProp}`; const parentObject = getPropertyByPath(options, parentPath) || getPropertyByName(options, parentPath) || {}; if (parentObject[optionName]) { return [parentPath, parentObject[optionName]]; } } } return UNDEFINED_PROP_VIA_PARENT; }; const setIndirectValues = (parentPath, rootValue, indirectVals) => { const rootValues = flatten(rootValue, { safe: true }); Object.entries(rootValues).forEach(([keyPath, value]) => { // eslint-disable-next-line no-param-reassign indirectVals[`${parentPath}.${keyPath}`] = value; }); return indirectVals; }; type GenerateOptions<T extends Document> = { options: FactoryOptions, staticFields: Record<string, unknown>, globalOptions: GlobalOptions } export function generate<T extends Document>(schema: Schema<T>, opts: GenerateOptions<T>): T { const { options, staticFields, globalOptions } = opts; const mockObject = {}; const fieldGeneration = []; const delayedFieldGeneration = []; const indirectValues = {}; const indirectValuesTasks = {}; schema.eachPath((path) => { if (!path.includes('$*')) { if (typeof get(options, `${path}.value`) === 'function' || typeof get(options, `['${path}'].value`, undefined) === 'function') { delayedFieldGeneration.push( () => populateField( mockObject, { schema, path, options, staticValue: get(staticFields, path, undefined), globalOptions, }, ), ); } else { const indirectVals = getOptionFromParentProperty(path, options, 'value'); if (indirectVals !== UNDEFINED_PROP_VIA_PARENT) { const [parentPath, value] = indirectVals; if (!indirectValuesTasks[parentPath]) { if (typeof value === 'function') { fieldGeneration.push(() => { const rootValue = value(mockObject); setIndirectValues(parentPath, rootValue, indirectValues); }); } else { const rootValue = value; setIndirectValues(parentPath, rootValue, indirectValues); } indirectValuesTasks[parentPath] = true; } } fieldGeneration.push(() => populateField( mockObject, { schema, path, options, staticValue: get(staticFields, path, undefined), indirectValues, globalOptions, }, )); } } }); [...fieldGeneration, ...delayedFieldGeneration].forEach((fn) => fn()); return mockObject as T; }
the_stack
* @packageDocumentation * @module material */ import { EffectAsset } from '../../assets/effect-asset'; import { SetIndex, IDescriptorSetLayoutInfo, globalDescriptorSetLayout, localDescriptorSetLayout } from '../../pipeline/define'; import { RenderPipeline } from '../../pipeline/render-pipeline'; import { genHandle, MacroRecord } from './pass-utils'; import { legacyCC } from '../../global-exports'; import { PipelineLayoutInfo, Device, Attribute, UniformBlock, ShaderInfo, Uniform, ShaderStage, DESCRIPTOR_SAMPLER_TYPE, DESCRIPTOR_BUFFER_TYPE, DescriptorSetLayout, DescriptorSetLayoutBinding, DescriptorSetLayoutInfo, DescriptorType, GetTypeSize, ShaderStageFlagBit, API, UniformSamplerTexture, PipelineLayout, Shader, UniformStorageBuffer, UniformStorageImage, UniformSampler, UniformTexture, UniformInputAttachment } from '../../gfx'; import { debug } from '../../platform/debug'; const _dsLayoutInfo = new DescriptorSetLayoutInfo(); interface IDefineRecord extends EffectAsset.IDefineInfo { _map: (value: any) => number; _offset: number; } export interface ITemplateInfo { gfxAttributes: Attribute[]; shaderInfo: ShaderInfo; blockSizes: number[]; setLayouts: DescriptorSetLayout[]; pipelineLayout: PipelineLayout; handleMap: Record<string, number>; bindings: DescriptorSetLayoutBinding[]; samplerStartBinding: number; } export interface IProgramInfo extends EffectAsset.IShaderInfo { effectName: string; defines: IDefineRecord[]; constantMacros: string; uber: boolean; // macro number exceeds default limits, will fallback to string hash } interface IMacroInfo { name: string; value: string; isDefault: boolean; } function getBitCount (cnt: number) { return Math.ceil(Math.log2(Math.max(cnt, 2))); } function mapDefine (info: EffectAsset.IDefineInfo, def: number | string | boolean) { switch (info.type) { case 'boolean': return typeof def === 'number' ? def.toString() : (def ? '1' : '0'); case 'string': return def !== undefined ? def as string : info.options![0]; case 'number': return def !== undefined ? def.toString() : info.range![0].toString(); default: console.warn(`unknown define type '${info.type}'`); return '-1'; // should neven happen } } function prepareDefines (defs: MacroRecord, tDefs: EffectAsset.IDefineInfo[]) { const macros: IMacroInfo[] = []; for (let i = 0; i < tDefs.length; i++) { const tmpl = tDefs[i]; const name = tmpl.name; const v = defs[name]; const value = mapDefine(tmpl, v); const isDefault = !v || v === '0'; macros.push({ name, value, isDefault }); } return macros; } function getShaderInstanceName (name: string, macros: IMacroInfo[]) { return name + macros.reduce((acc, cur) => (cur.isDefault ? acc : `${acc}|${cur.name}${cur.value}`), ''); } function insertBuiltinBindings ( tmpl: IProgramInfo, tmplInfo: ITemplateInfo, source: IDescriptorSetLayoutInfo, type: 'locals' | 'globals', outBindings?: DescriptorSetLayoutBinding[], ) { const target = tmpl.builtins[type]; const tempBlocks: UniformBlock[] = []; for (let i = 0; i < target.blocks.length; i++) { const b = target.blocks[i]; const info = source.layouts[b.name] as UniformBlock | undefined; const binding = info && source.bindings.find((bd) => bd.binding === info.binding); if (!info || !binding || !(binding.descriptorType & DESCRIPTOR_BUFFER_TYPE)) { console.warn(`builtin UBO '${b.name}' not available!`); continue; } tempBlocks.push(info); if (outBindings && !outBindings.includes(binding)) outBindings.push(binding); } Array.prototype.unshift.apply(tmplInfo.shaderInfo.blocks, tempBlocks); const tempSamplerTextures: UniformSamplerTexture[] = []; for (let i = 0; i < target.samplerTextures.length; i++) { const s = target.samplerTextures[i]; const info = source.layouts[s.name] as UniformSamplerTexture; const binding = info && source.bindings.find((bd) => bd.binding === info.binding); if (!info || !binding || !(binding.descriptorType & DESCRIPTOR_SAMPLER_TYPE)) { console.warn(`builtin samplerTexture '${s.name}' not available!`); continue; } tempSamplerTextures.push(info); if (outBindings && !outBindings.includes(binding)) outBindings.push(binding); } Array.prototype.unshift.apply(tmplInfo.shaderInfo.samplerTextures, tempSamplerTextures); if (outBindings) outBindings.sort((a, b) => a.binding - b.binding); } function getSize (block: EffectAsset.IBlockInfo) { return block.members.reduce((s, m) => s + GetTypeSize(m.type) * m.count, 0); } function genHandles (tmpl: IProgramInfo) { const handleMap: Record<string, number> = {}; // block member handles for (let i = 0; i < tmpl.blocks.length; i++) { const block = tmpl.blocks[i]; const members = block.members; let offset = 0; for (let j = 0; j < members.length; j++) { const uniform = members[j]; handleMap[uniform.name] = genHandle(block.binding, uniform.type, uniform.count, offset); offset += (GetTypeSize(uniform.type) >> 2) * uniform.count; // assumes no implicit padding, which is guaranteed by effect compiler } } // samplerTexture handles for (let i = 0; i < tmpl.samplerTextures.length; i++) { const samplerTexture = tmpl.samplerTextures[i]; handleMap[samplerTexture.name] = genHandle(samplerTexture.binding, samplerTexture.type, samplerTexture.count); } return handleMap; } function dependencyCheck (dependencies: string[], defines: MacroRecord) { for (let i = 0; i < dependencies.length; i++) { const d = dependencies[i]; if (d[0] === '!') { // negative dependency if (defines[d.slice(1)]) { return false; } } else if (!defines[d]) { return false; } } return true; } function getActiveAttributes (tmpl: IProgramInfo, tmplInfo: ITemplateInfo, defines: MacroRecord) { const out: Attribute[] = []; const attributes = tmpl.attributes; const gfxAttributes = tmplInfo.gfxAttributes; for (let i = 0; i < attributes.length; i++) { if (!dependencyCheck(attributes[i].defines, defines)) { continue; } out.push(gfxAttributes[i]); } return out; } /** * @en The global maintainer of all shader resources. * @zh 维护 shader 资源实例的全局管理器。 */ class ProgramLib { protected _templates: Record<string, IProgramInfo> = {}; // per shader protected _cache: Record<string, Shader> = {}; protected _templateInfos: Record<number, ITemplateInfo> = {}; public register (effect: EffectAsset) { for (let i = 0; i < effect.shaders.length; i++) { const tmpl = this.define(effect.shaders[i]); tmpl.effectName = effect.name; } } /** * @en Register the shader template with the given info * @zh 注册 shader 模板。 */ public define (shader: EffectAsset.IShaderInfo) { const curTmpl = this._templates[shader.name]; if (curTmpl && curTmpl.hash === shader.hash) { return curTmpl; } const tmpl = ({ ...shader }) as IProgramInfo; // calculate option mask offset let offset = 0; for (let i = 0; i < tmpl.defines.length; i++) { const def = tmpl.defines[i]; let cnt = 1; if (def.type === 'number') { const range = def.range!; cnt = getBitCount(range[1] - range[0] + 1); // inclusive on both ends def._map = (value: number) => value - range[0]; } else if (def.type === 'string') { cnt = getBitCount(def.options!.length); def._map = (value: any) => Math.max(0, def.options!.findIndex((s) => s === value)); } else if (def.type === 'boolean') { def._map = (value: any) => (value ? 1 : 0); } def._offset = offset; offset += cnt; } if (offset > 31) { tmpl.uber = true; } // generate constant macros tmpl.constantMacros = ''; for (const key in tmpl.builtins.statistics) { tmpl.constantMacros += `#define ${key} ${tmpl.builtins.statistics[key]}\n`; } // store it this._templates[shader.name] = tmpl; if (!this._templateInfos[tmpl.hash]) { const tmplInfo = {} as ITemplateInfo; // cache material-specific descriptor set layout tmplInfo.samplerStartBinding = tmpl.blocks.length; tmplInfo.shaderInfo = new ShaderInfo(); tmplInfo.blockSizes = []; tmplInfo.bindings = []; for (let i = 0; i < tmpl.blocks.length; i++) { const block = tmpl.blocks[i]; tmplInfo.blockSizes.push(getSize(block)); tmplInfo.bindings.push(new DescriptorSetLayoutBinding(block.binding, DescriptorType.UNIFORM_BUFFER, 1, block.stageFlags)); tmplInfo.shaderInfo.blocks.push(new UniformBlock(SetIndex.MATERIAL, block.binding, block.name, block.members.map((m) => new Uniform(m.name, m.type, m.count)), 1)); // effect compiler guarantees block count = 1 } for (let i = 0; i < tmpl.samplerTextures.length; i++) { const samplerTexture = tmpl.samplerTextures[i]; tmplInfo.bindings.push(new DescriptorSetLayoutBinding(samplerTexture.binding, DescriptorType.SAMPLER_TEXTURE, samplerTexture.count, samplerTexture.stageFlags)); tmplInfo.shaderInfo.samplerTextures.push(new UniformSamplerTexture( SetIndex.MATERIAL, samplerTexture.binding, samplerTexture.name, samplerTexture.type, samplerTexture.count, )); } for (let i = 0; i < tmpl.samplers.length; i++) { const sampler = tmpl.samplers[i]; tmplInfo.bindings.push(new DescriptorSetLayoutBinding(sampler.binding, DescriptorType.SAMPLER, sampler.count, sampler.stageFlags)); tmplInfo.shaderInfo.samplers.push(new UniformSampler( SetIndex.MATERIAL, sampler.binding, sampler.name, sampler.count, )); } for (let i = 0; i < tmpl.textures.length; i++) { const texture = tmpl.textures[i]; tmplInfo.bindings.push(new DescriptorSetLayoutBinding(texture.binding, DescriptorType.TEXTURE, texture.count, texture.stageFlags)); tmplInfo.shaderInfo.textures.push(new UniformTexture( SetIndex.MATERIAL, texture.binding, texture.name, texture.type, texture.count, )); } for (let i = 0; i < tmpl.buffers.length; i++) { const buffer = tmpl.buffers[i]; tmplInfo.bindings.push(new DescriptorSetLayoutBinding(buffer.binding, DescriptorType.STORAGE_BUFFER, 1, buffer.stageFlags)); tmplInfo.shaderInfo.buffers.push(new UniformStorageBuffer( SetIndex.MATERIAL, buffer.binding, buffer.name, 1, buffer.memoryAccess, )); // effect compiler guarantees buffer count = 1 } for (let i = 0; i < tmpl.images.length; i++) { const image = tmpl.images[i]; tmplInfo.bindings.push(new DescriptorSetLayoutBinding(image.binding, DescriptorType.STORAGE_IMAGE, image.count, image.stageFlags)); tmplInfo.shaderInfo.images.push(new UniformStorageImage( SetIndex.MATERIAL, image.binding, image.name, image.type, image.count, image.memoryAccess, )); } for (let i = 0; i < tmpl.subpassInputs.length; i++) { const subpassInput = tmpl.subpassInputs[i]; tmplInfo.bindings.push(new DescriptorSetLayoutBinding(subpassInput.binding, DescriptorType.INPUT_ATTACHMENT, subpassInput.count, subpassInput.stageFlags)); tmplInfo.shaderInfo.subpassInputs.push(new UniformInputAttachment( SetIndex.MATERIAL, subpassInput.binding, subpassInput.name, subpassInput.count, )); } tmplInfo.gfxAttributes = []; for (let i = 0; i < tmpl.attributes.length; i++) { const attr = tmpl.attributes[i]; tmplInfo.gfxAttributes.push(new Attribute(attr.name, attr.format, attr.isNormalized, 0, attr.isInstanced, attr.location)); } insertBuiltinBindings(tmpl, tmplInfo, localDescriptorSetLayout, 'locals'); tmplInfo.shaderInfo.stages.push(new ShaderStage(ShaderStageFlagBit.VERTEX, '')); tmplInfo.shaderInfo.stages.push(new ShaderStage(ShaderStageFlagBit.FRAGMENT, '')); tmplInfo.handleMap = genHandles(tmpl); tmplInfo.setLayouts = []; this._templateInfos[tmpl.hash] = tmplInfo; } return tmpl; } /** * @en Gets the shader template with its name * @zh 通过名字获取 Shader 模板 * @param name Target shader name */ public getTemplate (name: string) { return this._templates[name]; } /** * @en Gets the shader template info with its name * @zh 通过名字获取 Shader 模版信息 * @param name Target shader name */ public getTemplateInfo (name: string) { const hash = this._templates[name].hash; return this._templateInfos[hash]; } /** * @en Gets the pipeline layout of the shader template given its name * @zh 通过名字获取 Shader 模板相关联的管线布局 * @param name Target shader name */ public getDescriptorSetLayout (device: Device, name: string, isLocal = false) { const tmpl = this._templates[name]; const tmplInfo = this._templateInfos[tmpl.hash]; if (!tmplInfo.setLayouts.length) { _dsLayoutInfo.bindings = tmplInfo.bindings; tmplInfo.setLayouts[SetIndex.MATERIAL] = device.createDescriptorSetLayout(_dsLayoutInfo); _dsLayoutInfo.bindings = localDescriptorSetLayout.bindings; tmplInfo.setLayouts[SetIndex.LOCAL] = device.createDescriptorSetLayout(_dsLayoutInfo); } return tmplInfo.setLayouts[isLocal ? SetIndex.LOCAL : SetIndex.MATERIAL]; } /** * @en * Does this library has the specified program * @zh * 当前是否有已注册的指定名字的 shader * @param name Target shader name */ public hasProgram (name: string) { return this._templates[name] !== undefined; } /** * @en Gets the shader key with the name and a macro combination * @zh 根据 shader 名和预处理宏列表获取 shader key。 * @param name Target shader name * @param defines The combination of preprocess macros */ public getKey (name: string, defines: MacroRecord) { const tmpl = this._templates[name]; const tmplDefs = tmpl.defines; if (tmpl.uber) { let key = ''; for (let i = 0; i < tmplDefs.length; i++) { const tmplDef = tmplDefs[i]; const value = defines[tmplDef.name]; if (!value || !tmplDef._map) { continue; } const mapped = tmplDef._map(value); const offset = tmplDef._offset; key += `${offset}${mapped}|`; } return `${key}${tmpl.hash}`; } let key = 0; for (let i = 0; i < tmplDefs.length; i++) { const tmplDef = tmplDefs[i]; const value = defines[tmplDef.name]; if (!value || !tmplDef._map) { continue; } const mapped = tmplDef._map(value); const offset = tmplDef._offset; key |= mapped << offset; } return `${key.toString(16)}|${tmpl.hash}`; } /** * @en Destroy all shader instance match the preprocess macros * @zh 销毁所有完全满足指定预处理宏特征的 shader 实例。 * @param defines The preprocess macros as filter */ public destroyShaderByDefines (defines: MacroRecord) { const names = Object.keys(defines); if (!names.length) { return; } const regexes = names.map((cur) => { let val = defines[cur]; if (typeof val === 'boolean') { val = val ? '1' : '0'; } return new RegExp(`${cur}${val}`); }); const keys = Object.keys(this._cache).filter((k) => regexes.every((re) => re.test(this._cache[k].name))); for (let i = 0; i < keys.length; i++) { const k = keys[i]; const prog = this._cache[k]; debug(`destroyed shader ${prog.name}`); prog.destroy(); delete this._cache[k]; } } /** * @en Gets the shader resource instance with given information * @zh 获取指定 shader 的渲染资源实例 * @param name Shader name * @param defines Preprocess macros * @param pipeline The [[RenderPipeline]] which owns the render command * @param key The shader cache key, if already known */ public getGFXShader (device: Device, name: string, defines: MacroRecord, pipeline: RenderPipeline, key?: string) { Object.assign(defines, pipeline.macros); if (!key) key = this.getKey(name, defines); const res = this._cache[key]; if (res) { return res; } const tmpl = this._templates[name]; const tmplInfo = this._templateInfos[tmpl.hash]; if (!tmplInfo.pipelineLayout) { this.getDescriptorSetLayout(device, name); // ensure set layouts have been created insertBuiltinBindings(tmpl, tmplInfo, globalDescriptorSetLayout, 'globals'); tmplInfo.setLayouts[SetIndex.GLOBAL] = pipeline.descriptorSetLayout; tmplInfo.pipelineLayout = device.createPipelineLayout(new PipelineLayoutInfo(tmplInfo.setLayouts)); } const macroArray = prepareDefines(defines, tmpl.defines); const prefix = pipeline.constantMacros + tmpl.constantMacros + macroArray.reduce((acc, cur) => `${acc}#define ${cur.name} ${cur.value}\n`, ''); let src = tmpl.glsl3; const deviceShaderVersion = getDeviceShaderVersion(device); if (deviceShaderVersion) { src = tmpl[deviceShaderVersion]; } else { console.error('Invalid GFX API!'); } tmplInfo.shaderInfo.stages[0].source = prefix + src.vert; tmplInfo.shaderInfo.stages[1].source = prefix + src.frag; // strip out the active attributes only, instancing depend on this tmplInfo.shaderInfo.attributes = getActiveAttributes(tmpl, tmplInfo, defines); tmplInfo.shaderInfo.name = getShaderInstanceName(name, macroArray); return this._cache[key] = device.createShader(tmplInfo.shaderInfo); } } export function getDeviceShaderVersion (device: Device) { switch (device.gfxAPI) { case API.GLES2: case API.WEBGL: return 'glsl1'; case API.GLES3: case API.WEBGL2: return 'glsl3'; default: return 'glsl4'; } } export const programLib = new ProgramLib(); legacyCC.programLib = programLib;
the_stack
import * as ChildProcess from 'child_process' import * as fs from 'fs' import * as os from 'os' import * as path from 'path' import * as readline from 'readline' import * as Array from 'fp-ts/Array' import * as Option from 'fp-ts/Option' import { UnreachableCaseError } from 'ts-essentials' import * as vscode from 'vscode' import * as Constants from '@shared/constants' import { DisassemblyLineInformation, OutputAndEventsFiles } from '@shared/interfaces' import { ProjectConfiguration } from '@shared/project-configuration' import * as WorkspaceState from '@shared/workspace-state' import { getWorkspaceAddresses, populateAddresses } from './workspace-addresses' export enum ReoptMode { GenerateCFG, GenerateDisassembly, GenerateFunctions, GenerateLLVM, } export function replaceExtensionWith(replacement: string): (exe: string) => string { return (executablePath: string) => { const dir = path.dirname(executablePath) const executableWithoutExtension = path.basename( path.basename(executablePath), path.extname(executablePath), ) return `${dir}/${executableWithoutExtension}.${replacement}` } } const replaceExtensionWithCFG = replaceExtensionWith('cfg') const replaceExtensionWithDis = replaceExtensionWith('dis') const replaceExtensionWithFns = replaceExtensionWith('fns') const replaceExtensionWithLL = replaceExtensionWith('ll') function outputForReoptMode( projectConfiguration: ProjectConfiguration, reoptMode: ReoptMode, ): string { switch (reoptMode) { case ReoptMode.GenerateCFG: { return ( Option .getOrElse (() => replaceExtensionWithCFG(projectConfiguration.binaryFile)) (projectConfiguration.outputNameCFG) ) } case ReoptMode.GenerateDisassembly: { return ( Option.getOrElse (() => replaceExtensionWithDis(projectConfiguration.binaryFile)) (projectConfiguration.outputNameDisassemble) ) } case ReoptMode.GenerateFunctions: { return ( Option.getOrElse (() => replaceExtensionWithFns(projectConfiguration.binaryFile)) (projectConfiguration.outputNameFunctions) ) } case ReoptMode.GenerateLLVM: { return ( Option.getOrElse (() => replaceExtensionWithLL(projectConfiguration.binaryFile)) (projectConfiguration.outputNameLLVM) ) } default: { throw new UnreachableCaseError(reoptMode) } } } function argsForReoptMode( projectConfiguration: ProjectConfiguration, reoptMode: ReoptMode, ): [string, string] { const output = outputForReoptMode(projectConfiguration, reoptMode) switch (reoptMode) { case ReoptMode.GenerateCFG: { return ['export-cfg', output] } case ReoptMode.GenerateDisassembly: { return ['--export-object', output] } case ReoptMode.GenerateFunctions: { return ['export-fns', output] } case ReoptMode.GenerateLLVM: { return ['export-llvm', output] } default: { throw new UnreachableCaseError(reoptMode) } } } // TODO: get that schema from the Haskell side // type ReoptError = // [ // number, // number, // number, // string, // ] /** * Goes through the list of events obtained from a run of reopt, and displays * the errors as VSCode diagnostics over the disassembly file. * @param context - VSCode extension context * @param diagnosticCollection - Current diagnostic collection * @param disassemblyFile - Path to the disassembly file (assumed to have been * created) * @param eventsFile - Path to the events file (assumed to have been created) */ export async function displayReoptEventsAsDiagnostics( context: vscode.ExtensionContext, diagnosticCollection: vscode.DiagnosticCollection, disassemblyFile: fs.PathLike, eventsFile: fs.PathLike, ): Promise<void> { const addresses = await getOrGenerateAddresses(context) || [] const disassemblyUri = vscode.Uri.file(disassemblyFile.toLocaleString()) const textDocument = await vscode.workspace.openTextDocument(disassemblyUri) const textEditor = await vscode.window.showTextDocument(textDocument, { preview: false, }) const makeDiagnostic = makeDiagnosticBuilderForAddresses(addresses) // Highlight for the bytes in blocks that caused errors const bytesDecoration = vscode.window.createTextEditorDecorationType({ // backgroundColor: "#45383F", textDecoration: '#FF6464 wavy underline', }) const lineReader = readline.createInterface( fs.createReadStream(eventsFile) ) // The API for processing a file line-by-line is not of a very functional // nature, so we will populate a mutable array of ranges, and register all // those when reaching the end of file. const diagnostics = [] as vscode.Diagnostic[] let allBytesRanges = [] as vscode.Range[] lineReader.on('line', async (line) => { const { diagnostic, bytesRanges } = await makeDiagnostic(line) diagnostics.push(diagnostic) allBytesRanges = allBytesRanges.concat(bytesRanges) }) lineReader.on('close', () => { // Currently, diagnostics are created for a disassembly file that has // been created in a temporary directory, fresh for each new run of // reopt. As a result, the current [[disassemblyUri]] is not the same // as the one for the previous batch of diagnostics, so // [[diagnosticCollection.set]] will not overwrite the old ones. So we // clear the collection instead. diagnosticCollection.clear() diagnosticCollection.set( disassemblyUri, diagnostics, ) textEditor.setDecorations(bytesDecoration, allBytesRanges) }) } /** * Runs reopt in one of the supported modes and returns the absolute path to the * output file generated, if successful. * @param context - VSCode extension context * @param extraArgs - TODO * @param reoptMode - What mode to run reopt in * @returns Standard output, standard error */ export function runReopt( context: vscode.ExtensionContext, extraArgs: string[], reoptMode: ReoptMode, ): Promise<[string, string]> { const workspaceConfiguration = vscode.workspace.getConfiguration( Constants.reoptSectionKey, ) const projectConfiguration = WorkspaceState.readReoptProjectConfiguration(context) if (projectConfiguration === undefined) { vscode.window.showErrorMessage( 'Could not find a project configuration, have you opened a reopt project?' ) return Promise.reject() } const reoptExecutable = workspaceConfiguration.get<string>( Constants.reoptExecutableKey, ) if (reoptExecutable === undefined) { vscode.window.showErrorMessage( `Could not find key ${Constants.reoptExecutableKey} in your configuration, aborting.` ) return Promise.reject() } return new Promise((resolve, reject) => { const annotations = (reoptMode === ReoptMode.GenerateLLVM) ? Option.foldMap (Array.getMonoid<string>()) (a => [`--annotations=${a}`]) (projectConfiguration.annotations) : [] ChildProcess.execFile( reoptExecutable, ([] as string[]).concat( annotations, projectConfiguration.excludes.map(e => `--exclude=${e}`), projectConfiguration.headers.map(h => `--header=${h}`), projectConfiguration.includes.map(i => `--include=${i}`), extraArgs, [ projectConfiguration.binaryFile, ], ), { cwd: path.dirname(projectConfiguration.binaryFile), }, (err, stdout, stderr) => { // error events are now reported off-band, not sure this still // happens if (err) { return reject(err) } resolve([stdout, stderr]) }, ) }) } export async function runReoptToGenerateDisassembly( context: vscode.ExtensionContext, ): Promise<string> { const tempDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'temp-reopt-')) const disassemblyFile = `${tempDir}/disassemble` await runReopt( context, [ '--disassemble', `--output=${disassemblyFile}`, ], ReoptMode.GenerateDisassembly, ) populateAddresses(context, disassemblyFile) return disassemblyFile } export async function getProjectConfiguration( context: vscode.ExtensionContext, ): Promise<ProjectConfiguration> { const projectConfiguration = WorkspaceState.readReoptProjectConfiguration(context) if (projectConfiguration === undefined) { vscode.window.showErrorMessage( 'Could not find a project configuration, have you opened a reopt project?' ) return Promise.reject() } return projectConfiguration } export async function runReoptToGenerateFile( context: vscode.ExtensionContext, reoptMode: ReoptMode, ): Promise<OutputAndEventsFiles> { const tempDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'temp-crux-llvm-')) const eventsFile = `${tempDir}/events` // const outputFile = `${tempDir}/disassemble` const projectConfiguration = await getProjectConfiguration(context) const [flag, outputFile] = argsForReoptMode(projectConfiguration, reoptMode) await runReopt( context, [ `--${flag}=${outputFile}`, `--export-events=${eventsFile}`, ], reoptMode, ) return { outputFile, eventsFile } } // TODO: I would like this to be generated on the Haskell side using // aeson-typescript. type ReoptCFGError = [number, number, number, number, string] type DiagnosticAndBytesRanges = { diagnostic: vscode.Diagnostic bytesRanges: vscode.Range[] } /** * Given the information for addresses in the disassembly file, returns a * function that consumes a line of the reopt event log, and constructs the * corresponding diagnostic, alongside the byte ranges that the diagnostic * applies to. * The ranges correspond to chunks of lines in the disassembly file that contain * the bytes of the block, so that we can highlight the problematic bytes. * @param addresses - Information about addresses in the current disassembly * file. * @returns A function that, given a line of the reopt event log, constructs the * diagnostic and byte ranges. */ function makeDiagnosticBuilderForAddresses( addresses: DisassemblyLineInformation[], ): (line: string) => Promise<DiagnosticAndBytesRanges> { return async (line) => { // Ideally this would be synced with the ExportEvent datatype from // Reopt/Events/Export.hs const [, blockId, , blockSize, which] = JSON.parse(line) as ReoptCFGError const address = blockId.toString(16) const zero = new vscode.Position(0, 0) const zeroRange = new vscode.Range(zero, zero) // Look for the line information corresponding to this address const addressDisassemblyLineInfo = addresses.find(a => a.address === address) const range = addressDisassemblyLineInfo?.addressRange || zeroRange const diagnostic = new vscode.Diagnostic( range, `${which} (block ${address} of size ${blockSize})`, vscode.DiagnosticSeverity.Error, ) /** * The error comes with a block (defined by its first byte and block * size). We find all of our registered address ranges from the * disassembly file that are entirely contained in the block, so that * they can be highlighted. */ const blockFirstByte = BigInt(blockId) const blockLastByte = BigInt(blockId) + BigInt(blockSize) - BigInt(1) const bytesRanges = addresses .filter(a => blockFirstByte <= a.firstByteAddress && a.lastByteAddress <= blockLastByte ) .map(a => a.bytesRange) return { diagnostic, bytesRanges, } } } /** * We often need information about the addresses that appear in the disassembly * file of an executable. We try to compute this information only once. This * function returns it, if it exists, otherwise it first generates and registers * it. * @param context - VSCode extension context. * @returns Information about the addresses in the reopt disassembly file, if * any. */ async function getOrGenerateAddresses( context: vscode.ExtensionContext, ): Promise<DisassemblyLineInformation[] | undefined> { const addresses = getWorkspaceAddresses(context) if (addresses !== undefined) { return Promise.resolve(addresses) } /** * If addresses is undefined, we attempts to set it by running reopt in * generate disassembly mode. */ await runReoptToGenerateDisassembly(context) return getWorkspaceAddresses(context) }
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { class UserSettingsApi { /** * DynamicsCrm.DevKit UserSettingsApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Normal polling frequency used for address book synchronization in Microsoft Office Outlook. */ AddressBookSyncInterval: DevKit.WebApi.IntegerValue; /** Default mode, such as simple or detailed, for advanced find. */ AdvancedFindStartupMode: DevKit.WebApi.IntegerValue; /** AM designator to use in Microsoft Dynamics 365. */ AMDesignator: DevKit.WebApi.StringValue; /** Set user status for ADC Suggestions */ AutoCaptureUserStatus: DevKit.WebApi.IntegerValue; /** Auto-create contact on client promote */ AutoCreateContactOnPromote: DevKit.WebApi.IntegerValue; /** Unique identifier of the business unit with which the user is associated. */ BusinessUnitId: DevKit.WebApi.GuidValue; /** Calendar type for the system. Set to Gregorian US by default. */ CalendarType: DevKit.WebApi.IntegerValue; /** Unique identifier of the user who created the user settings. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the user settings object was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who created the usersettings. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Information about how currency symbols are placed in Microsoft Dynamics 365. */ CurrencyFormatCode: DevKit.WebApi.IntegerValue; /** Symbol used for currency in Microsoft Dynamics 365. */ CurrencySymbol: DevKit.WebApi.StringValue; /** Information that specifies the level of data validation in excel worksheets exported in a format suitable for import. */ DataValidationModeForExportToExcel: DevKit.WebApi.OptionSetValue; /** Information about how the date is displayed in Microsoft Dynamics 365. */ DateFormatCode: DevKit.WebApi.IntegerValue; /** String showing how the date is displayed throughout Microsoft 365. */ DateFormatString: DevKit.WebApi.StringValue; /** Character used to separate the month, the day, and the year in dates in Microsoft Dynamics 365. */ DateSeparator: DevKit.WebApi.StringValue; /** Symbol used for decimal in Microsoft Dynamics 365. */ DecimalSymbol: DevKit.WebApi.StringValue; /** Default calendar view for the user. */ DefaultCalendarView: DevKit.WebApi.IntegerValue; /** Text area to enter default country code. */ DefaultCountryCode: DevKit.WebApi.StringValue; /** Unique identifier of the default dashboard. */ DefaultDashboardId: DevKit.WebApi.GuidValue; /** Default search experience for the user. */ DefaultSearchExperience: DevKit.WebApi.OptionSetValue; /** Indicates the form mode to be used. */ EntityFormMode: DevKit.WebApi.OptionSetValue; /** Order in which names are to be displayed in Microsoft Dynamics 365. */ FullNameConventionCode: DevKit.WebApi.IntegerValue; /** Information that specifies whether the Get Started pane in lists is enabled. */ GetStartedPaneContentEnabled: DevKit.WebApi.BooleanValue; /** Unique identifier of the Help language. */ HelpLanguageId: DevKit.WebApi.IntegerValue; /** Web site home page for the user. */ HomepageArea: DevKit.WebApi.StringValue; /** Configuration of the home page layout. */ HomepageLayout: DevKit.WebApi.StringValue; /** Web site page for the user. */ HomepageSubarea: DevKit.WebApi.StringValue; /** Information that specifies whether a user account is to ignore unsolicited email (deprecated). */ IgnoreUnsolicitedEmail: DevKit.WebApi.BooleanValue; /** Incoming email filtering method. */ IncomingEmailFilteringMethod: DevKit.WebApi.OptionSetValue; /** Show or dismiss alert for Apps for 365. */ IsAppsForCrmAlertDismissed: DevKit.WebApi.BooleanValue; /** Indicates whether to use the Auto Capture feature enabled or not. */ IsAutoDataCaptureEnabled: DevKit.WebApi.BooleanValue; /** Enable or disable country code selection . */ IsDefaultCountryCodeCheckEnabled: DevKit.WebApi.BooleanValue; /** Indicates if duplicate detection is enabled when going online. */ IsDuplicateDetectionEnabledWhenGoingOnline: DevKit.WebApi.BooleanValue; /** Enable or disable email conversation view on timeline wall selection. */ IsEmailConversationViewEnabled: DevKit.WebApi.BooleanValue; /** Enable or disable guided help. */ IsGuidedHelpEnabled: DevKit.WebApi.BooleanValue; /** Indicates if the synchronization of user resource booking with Exchange is enabled at user level. */ IsResourceBookingExchangeSyncEnabled: DevKit.WebApi.BooleanValue; /** Indicates if send as other user privilege is enabled or not. */ IsSendAsAllowed: DevKit.WebApi.BooleanValue; /** Shows the last time when the traces were read from the database. */ LastAlertsViewedTime_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValue; /** Unique identifier of the user locale. */ LocaleId: DevKit.WebApi.IntegerValue; /** Information that specifies how Long Date is displayed throughout Microsoft 365. */ LongDateFormatCode: DevKit.WebApi.IntegerValue; /** Unique identifier of the user who last modified the user settings. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the user settings object was last modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Unique identifier of the delegate user who last modified the usersettings. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Information that specifies how negative currency numbers are displayed in Microsoft Dynamics 365. */ NegativeCurrencyFormatCode: DevKit.WebApi.IntegerValue; /** Information that specifies how negative numbers are displayed in Microsoft Dynamics 365. */ NegativeFormatCode: DevKit.WebApi.IntegerValue; /** Next tracking number. */ NextTrackingNumber: DevKit.WebApi.IntegerValue; /** Information that specifies how numbers are grouped in Microsoft Dynamics 365. */ NumberGroupFormat: DevKit.WebApi.StringValue; /** Symbol used for number separation in Microsoft Dynamics 365. */ NumberSeparator: DevKit.WebApi.StringValue; /** Normal polling frequency used for background offline synchronization in Microsoft Office Outlook. */ OfflineSyncInterval: DevKit.WebApi.IntegerValue; /** Normal polling frequency used for record synchronization in Microsoft Office Outlook. */ OutlookSyncInterval: DevKit.WebApi.IntegerValue; /** Information that specifies how many items to list on a page in list views. */ PagingLimit: DevKit.WebApi.IntegerValue; /** For internal use only. */ PersonalizationSettings: DevKit.WebApi.StringValue; /** PM designator to use in Microsoft Dynamics 365. */ PMDesignator: DevKit.WebApi.StringValue; /** Picklist for selecting the user preference for reporting scripting errors. */ ReportScriptErrors: DevKit.WebApi.OptionSetValue; /** The version number for resource booking synchronization with Exchange. */ ResourceBookingExchangeSyncVersion: DevKit.WebApi.BigIntValue; /** Store selected customer service hub dashboard saved filter id. */ SelectedGlobalFilterId: DevKit.WebApi.GuidValue; /** Information that specifies whether to display the week number in calendar displays in Microsoft Dynamics 365. */ ShowWeekNumber: DevKit.WebApi.BooleanValue; /** For Internal use only */ SplitViewState: DevKit.WebApi.BooleanValue; /** Indicates if the company field in Microsoft Office Outlook items are set during Outlook synchronization. */ SyncContactCompany: DevKit.WebApi.BooleanValue; /** Unique identifier of the user. */ SystemUserId: DevKit.WebApi.GuidValue; /** Information that specifies how the time is displayed in Microsoft Dynamics 365. */ TimeFormatCode: DevKit.WebApi.IntegerValue; /** Text for how time is displayed in Microsoft Dynamics 365. */ TimeFormatString: DevKit.WebApi.StringValue; /** Text for how time is displayed in Microsoft Dynamics 365. */ TimeSeparator: DevKit.WebApi.StringValue; /** Local time zone adjustment for the user. System calculated based on the time zone selected. */ TimeZoneBias: DevKit.WebApi.IntegerValue; /** Local time zone for the user. */ TimeZoneCode: DevKit.WebApi.IntegerValue; /** Local time zone daylight adjustment for the user. System calculated based on the time zone selected. */ TimeZoneDaylightBias: DevKit.WebApi.IntegerValue; /** Local time zone daylight day for the user. System calculated based on the time zone selected. */ TimeZoneDaylightDay: DevKit.WebApi.IntegerValue; /** Local time zone daylight day of week for the user. System calculated based on the time zone selected in Options. */ TimeZoneDaylightDayOfWeek: DevKit.WebApi.IntegerValue; /** Local time zone daylight hour for the user. System calculated based on the time zone selected. */ TimeZoneDaylightHour: DevKit.WebApi.IntegerValue; /** Local time zone daylight minute for the user. System calculated based on the time zone selected. */ TimeZoneDaylightMinute: DevKit.WebApi.IntegerValue; /** Local time zone daylight month for the user. System calculated based on the time zone selected. */ TimeZoneDaylightMonth: DevKit.WebApi.IntegerValue; /** Local time zone daylight second for the user. System calculated based on the time zone selected. */ TimeZoneDaylightSecond: DevKit.WebApi.IntegerValue; /** Local time zone daylight year for the user. System calculated based on the time zone selected. */ TimeZoneDaylightYear: DevKit.WebApi.IntegerValue; /** Local time zone standard time bias for the user. System calculated based on the time zone selected. */ TimeZoneStandardBias: DevKit.WebApi.IntegerValue; /** Local time zone standard day for the user. System calculated based on the time zone selected. */ TimeZoneStandardDay: DevKit.WebApi.IntegerValue; /** Local time zone standard day of week for the user. System calculated based on the time zone selected. */ TimeZoneStandardDayOfWeek: DevKit.WebApi.IntegerValue; /** Local time zone standard hour for the user. System calculated based on the time zone selected. */ TimeZoneStandardHour: DevKit.WebApi.IntegerValue; /** Local time zone standard minute for the user. System calculated based on the time zone selected. */ TimeZoneStandardMinute: DevKit.WebApi.IntegerValue; /** Local time zone standard month for the user. System calculated based on the time zone selected. */ TimeZoneStandardMonth: DevKit.WebApi.IntegerValue; /** Local time zone standard second for the user. System calculated based on the time zone selected. */ TimeZoneStandardSecond: DevKit.WebApi.IntegerValue; /** Local time zone standard year for the user. System calculated based on the time zone selected. */ TimeZoneStandardYear: DevKit.WebApi.IntegerValue; /** Tracking token ID. */ TrackingTokenId: DevKit.WebApi.IntegerValue; /** Unique identifier of the default currency of the user. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** Unique identifier of the language in which to view the user interface (UI). */ UILanguageId: DevKit.WebApi.IntegerValue; /** Indicates whether to use the Microsoft Dynamics 365 appointment form within Microsoft Office Outlook for creating new appointments. */ UseCrmFormForAppointment: DevKit.WebApi.BooleanValue; /** Indicates whether to use the Microsoft Dynamics 365 contact form within Microsoft Office Outlook for creating new contacts. */ UseCrmFormForContact: DevKit.WebApi.BooleanValue; /** Indicates whether to use the Microsoft Dynamics 365 email form within Microsoft Office Outlook for creating new emails. */ UseCrmFormForEmail: DevKit.WebApi.BooleanValue; /** Indicates whether to use the Microsoft Dynamics 365 task form within Microsoft Office Outlook for creating new tasks. */ UseCrmFormForTask: DevKit.WebApi.BooleanValue; /** Indicates whether image strips are used to render images. */ UseImageStrips: DevKit.WebApi.BooleanValue; /** Specifies user profile ids in comma separated list. */ UserProfile: DevKit.WebApi.StringValue; VersionNumber: DevKit.WebApi.BigIntValueReadonly; /** The layout of the visualization pane. */ VisualizationPaneLayout: DevKit.WebApi.OptionSetValue; /** Workday start time for the user. */ WorkdayStartTime: DevKit.WebApi.StringValue; /** Workday stop time for the user. */ WorkdayStopTime: DevKit.WebApi.StringValue; } } declare namespace OptionSet { namespace UserSettings { enum DataValidationModeForExportToExcel { /** 0 */ Full, /** 1 */ None } enum DefaultSearchExperience { /** 1 */ Categorized_search, /** 3 */ Custom_search, /** 0 */ Relevance_search, /** 2 */ Use_last_search } enum EntityFormMode { /** 2 */ Edit, /** 0 */ Organization_default, /** 1 */ Read_optimized } enum IncomingEmailFilteringMethod { /** 0 */ All_email_messages, /** 2 */ Email_messages_from_Dynamics_365_Leads_Contacts_and_Accounts, /** 3 */ Email_messages_from_Dynamics_365_records_that_are_email_enabled, /** 1 */ Email_messages_in_response_to_Dynamics_365_email, /** 4 */ No_email_messages } enum ReportScriptErrors { /** 1 */ Ask_me_for_permission_to_send_an_error_report_to_Microsoft, /** 2 */ Automatically_send_an_error_report_to_Microsoft_without_asking_me_for_permission, /** 3 */ Never_send_an_error_report_to_Microsoft_about_Microsoft_Dynamics_365 } enum VisualizationPaneLayout { /** 1 */ Side_by_side, /** 0 */ Top_bottom } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':[],'JsWebApi':true,'IsDebugForm':false,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import * as ta from "type-assertions"; import { addressNListToBIP32, slip44ByCoin } from "./utils"; import { BIP32Path, Coin, ExchangeType, HDWallet, HDWalletInfo, PathDescription } from "./wallet"; // GuardedUnion<T> will ensure a static typechecking error if any properties are set that aren't supposed // to be present on the specific union member being passed in. (This also helps the compiler with type inference.) type MakeFalsy<T> = T extends boolean ? false : undefined; type DistributiveKeyOf<T> = T extends any ? keyof T : never; type DistributiveFalsyValueOf<T, U> = T extends any ? (U extends keyof T ? MakeFalsy<T[U]> : never) : never; type FalsyValuesOfUnion<T> = { [Prop in DistributiveKeyOf<T>]?: DistributiveFalsyValueOf<T, Prop>; }; type OnlyNecessaryProps<T, U> = T & Omit<FalsyValuesOfUnion<U>, keyof T>; type GuardedUnionInner<T, U> = T extends any ? OnlyNecessaryProps<T, U> : never; type GuardedUnion<T> = GuardedUnionInner<T, T>; export type BTCGetAddress = { coin: Coin; addressNList: BIP32Path; scriptType?: BTCInputScriptType; // Defaults to BTCInputScriptType.SpendAddress showDisplay?: boolean; }; export interface BitcoinScriptSig { hex: string; } /** * Deserialized representation of an already-signed input of a transaction. */ interface BitcoinInputBase { sequence: number; } export type BitcoinInput = GuardedUnion< | (BitcoinInputBase & { coinbase: string }) | (BitcoinInputBase & { scriptSig: BitcoinScriptSig; txid: string; vout: number }) >; /** * Deserialized representation of an already-signed output of a transaction. */ export interface BitcoinOutput { value: string; // UGH, Insight scriptPubKey: BitcoinScriptSig; } /** * De-serialized representation of an already-signed transaction. */ export interface BitcoinTxBase { version: number; locktime: number; vin: Array<BitcoinInput>; vout: Array<BitcoinOutput>; } type BitcoinTxDIP2 = BitcoinTxBase & { type: number; extraPayload: string; }; export type BitcoinTx = GuardedUnion<BitcoinTxBase | BitcoinTxDIP2>; /** * Input for a transaction we're about to sign. */ type BTCSignTxInputBase = { vout: number; addressNList: BIP32Path; amount?: string; }; type BTCSignTxInputNativeBase = BTCSignTxInputBase & { txid: string; }; type BTCSignTxInputNativeSegwitBase = BTCSignTxInputNativeBase & { scriptType: BTCInputScriptType.SpendWitness | BTCInputScriptType.SpendP2SHWitness; }; type BTCSignTxInputNativeSegwitWithHex = BTCSignTxInputNativeSegwitBase & { hex: string; }; type BTCSignTxInputNativeSegwitWithTx = BTCSignTxInputNativeSegwitBase & { tx: BitcoinTx; vout: number; amount: string; }; type BTCSignTxInputNativeSegwit = BTCSignTxInputNativeSegwitWithHex | BTCSignTxInputNativeSegwitWithTx; type BTCSignTxInputNativeNonSegwit = BTCSignTxInputNativeBase & { scriptType: Exclude<BTCInputScriptType, BTCSignTxInputNativeSegwit["scriptType"]>; hex: string; }; type BTCSignTxInputNativeUnguarded = BTCSignTxInputNativeSegwit | BTCSignTxInputNativeNonSegwit; export type BTCSignTxInputNative = GuardedUnion<BTCSignTxInputNativeUnguarded>; type BTCSignTxInputKKBase = BTCSignTxInputBase & { txid: string; amount: string; sequence?: number; }; type BTCSignTxInputKKSegwit = BTCSignTxInputKKBase & { scriptType: BTCInputScriptType.SpendWitness | BTCInputScriptType.SpendP2SHWitness | BTCInputScriptType.External; hex?: string; }; type BTCSignTxInputKKNonSegwit = BTCSignTxInputKKBase & { scriptType: Exclude<BTCInputScriptType, BTCSignTxInputKKSegwit["scriptType"]>; } & ( | { tx: BitcoinTx; } | { hex: string; } ); type BTCSignTxInputKKUnguarded = BTCSignTxInputKKNonSegwit | BTCSignTxInputKKSegwit; export type BTCSignTxInputKK = GuardedUnion<BTCSignTxInputKKUnguarded>; export type BTCSignTxInputTrezor = BTCSignTxInputBase & { txid: string; amount: string; scriptType: BTCInputScriptType; }; export type BTCSignTxInputLedger = BTCSignTxInputBase & { addressNList: BIP32Path; scriptType: BTCInputScriptType; hex: string; }; export type BTCSignTxInput = BTCSignTxInputNative & BTCSignTxInputKK & BTCSignTxInputTrezor & BTCSignTxInputLedger; export type BTCSignTxInputUnguarded = BTCSignTxInputNativeUnguarded & BTCSignTxInputKKUnguarded & BTCSignTxInputTrezor & BTCSignTxInputLedger; // Stick to this common subset of input fields to avoid type hell. export type BTCSignTxInputSafe = { addressNList: BIP32Path; scriptType: BTCInputScriptType; hex: string; txid: string; amount: string; vout: number; }; ta.assert<ta.Extends<BTCSignTxInputSafe, BTCSignTxInput>>(); /** * Output for a transaction we're about to sign. */ export type BTCSignTxOutputSpend = { addressType?: BTCOutputAddressType.Spend; amount: string; address: string; }; // Will make address type more specific on TS version bump. export type BTCSignTxOutputSpendP2PKH = { addressType?: BTCOutputAddressType.Spend; amount: string; address: string; scriptType: BTCOutputScriptType.PayToAddress; }; export type BTCSignTxOutputSpendP2SH = { addressType?: BTCOutputAddressType.Spend; amount: string; address: string; scriptType: BTCOutputScriptType.PayToMultisig | BTCOutputScriptType.PayToP2SHWitness; }; export type BTCSignTxOutputSpendP2WPKH = { addressType?: BTCOutputAddressType.Spend; amount: string; address: string; scriptType: BTCOutputScriptType.PayToWitness; }; export type BTCSignTxOutputTransfer = { addressType: BTCOutputAddressType.Transfer; amount: string; /** bip32 path for destination (device must `btcSupportsSecureTransfer()`) */ addressNList: BIP32Path; scriptType: BTCOutputScriptType; }; export type BTCSignTxOutputChange = { addressType: BTCOutputAddressType.Change; amount: string; /** bip32 path for destination (device must `btcSupportsSecureTransfer()`) */ addressNList: BIP32Path; scriptType: BTCOutputScriptType; isChange: true; }; export type BTCSignTxOutputExchange = { /** * Device must `btcSupportsNativeShapeShift()` */ addressType: BTCOutputAddressType.Exchange; amount: string; exchangeType: ExchangeType; }; export type BTCSignTxOutputMemo = { addressType?: BTCOutputAddressType.Spend; amount?: "0"; opReturnData: string | Uint8Array; }; export type BTCSignTxOutput = GuardedUnion< | BTCSignTxOutputSpend | BTCSignTxOutputSpendP2PKH | BTCSignTxOutputSpendP2SH | BTCSignTxOutputSpendP2WPKH | BTCSignTxOutputTransfer | BTCSignTxOutputChange | BTCSignTxOutputExchange | BTCSignTxOutputMemo >; export interface BTCSignTx { coin: string; inputs: Array<BTCSignTxInput>; outputs: Array<BTCSignTxOutput>; version?: number; locktime?: number; opReturnData?: string; // TODO: dump this in favor of BTCSignTxOutputMemo above vaultAddress?: string; } export type BTCSignTxKK = Omit<BTCSignTx, "inputs"> & { inputs: Array<BTCSignTxInputKK> }; export type BTCSignTxNative = Omit<BTCSignTx, "inputs"> & { inputs: Array<BTCSignTxInputNative> }; export type BTCSignTxTrezor = Omit<BTCSignTx, "inputs"> & { inputs: Array<BTCSignTxInputTrezor> }; export type BTCSignTxLedger = Omit<BTCSignTx, "inputs"> & { inputs: Array<BTCSignTxInputLedger> }; export interface BTCSignedTx { signatures: Array<string>; /** hex string representation of the raw, signed transaction */ serializedTx: string; } // Bech32 info https://en.bitcoin.it/wiki/BIP_0173 export enum BTCInputScriptType { CashAddr = "cashaddr", // for Bitcoin Cash Bech32 = "bech32", SpendAddress = "p2pkh", SpendMultisig = "p2sh", External = "external", SpendWitness = "p2wpkh", SpendP2SHWitness = "p2sh-p2wpkh", } export enum BTCOutputScriptType { PayToAddress = "p2pkh", PayToMultisig = "p2sh", Bech32 = "bech32", PayToWitness = "p2wpkh", PayToP2SHWitness = "p2sh-p2wpkh", } export enum BTCOutputAddressType { Spend = "spend", Transfer = "transfer", Change = "change", Exchange = "exchange", } export interface BTCSignMessage { addressNList: BIP32Path; coin: Coin; scriptType?: BTCInputScriptType; message: string; } export interface BTCSignedMessage { address: string; signature: string; } export interface BTCVerifyMessage { address: string; message: string; signature: string; coin: Coin; } export interface BTCGetAccountPaths { coin: Coin; accountIdx: number; scriptType?: BTCInputScriptType; } export interface BTCAccountPath { coin: Coin; scriptType: BTCInputScriptType; addressNList: BIP32Path; } export interface BTCWalletInfo extends HDWalletInfo { readonly _supportsBTCInfo: boolean; /** * Does the device support the given UTXO coin? */ btcSupportsCoin(coin: Coin): Promise<boolean>; /** * Does the device support the given script type for the given coin? * Assumes that `btcSupportsCoin(coin)` for the given coin. */ btcSupportsScriptType(coin: Coin, scriptType?: BTCInputScriptType): Promise<boolean>; /** * Does the device support internal transfers without the user needing to * confirm the destination address? */ btcSupportsSecureTransfer(): Promise<boolean>; /** * Does the device support `/sendamountProto2` style ShapeShift trades? */ btcSupportsNativeShapeShift(): boolean; /** * Returns a list of bip32 paths for a given account index in preferred order * from most to least preferred. * * For forked coins, eg. BSV, this would return: ```plaintext p2pkh m/44'/236'/a' p2pkh m/44'/230'/a' p2pkh m/44'/0'/a' ``` * * For BTC it might return: ```plaintext p2sh-p2pkh m/49'/0'/a' p2pkh m/44'/0'/a' p2sh-p2wsh m/44'/0'/a' ``` */ btcGetAccountPaths(msg: BTCGetAccountPaths): Array<BTCAccountPath>; /** * Does the device support spending from the combined accounts? * The list is assumed to contain unique entries. */ btcIsSameAccount(msg: Array<BTCAccountPath>): boolean; /** * Returns the "next" account path, if any. */ btcNextAccountPath(msg: BTCAccountPath): BTCAccountPath | undefined; } export interface BTCWallet extends BTCWalletInfo, HDWallet { readonly _supportsBTC: boolean; btcGetAddress(msg: BTCGetAddress): Promise<string | null>; btcSignTx(msg: BTCSignTx): Promise<BTCSignedTx | null>; btcSignMessage(msg: BTCSignMessage): Promise<BTCSignedMessage | null>; btcVerifyMessage(msg: BTCVerifyMessage): Promise<boolean | null>; } export function unknownUTXOPath(path: BIP32Path, coin: Coin, scriptType?: BTCInputScriptType): PathDescription { return { verbose: addressNListToBIP32(path), coin, scriptType, isKnown: false, }; } export function describeUTXOPath(path: BIP32Path, coin: Coin, scriptType: BTCInputScriptType): PathDescription { const unknown = unknownUTXOPath(path, coin, scriptType); if (path.length !== 3 && path.length !== 5) return unknown; if ((path[0] & 0x80000000) >>> 0 !== 0x80000000) return unknown; let purpose = path[0] & 0x7fffffff; if (![44, 49, 84].includes(purpose)) return unknown; if (purpose === 44 && scriptType !== BTCInputScriptType.SpendAddress) return unknown; if (purpose === 49 && scriptType !== BTCInputScriptType.SpendP2SHWitness) return unknown; let wholeAccount = path.length === 3; let script = ( { [BTCInputScriptType.SpendAddress]: ["Legacy"], [BTCInputScriptType.SpendP2SHWitness]: [], [BTCInputScriptType.SpendWitness]: ["Segwit"], [BTCInputScriptType.Bech32]: ["Segwit Native"], } as Partial<Record<BTCInputScriptType, string[]>> )[scriptType]; let isPrefork = false; const slip44 = slip44ByCoin(coin); if (slip44 === undefined) return unknown; if (path[1] !== 0x80000000 + slip44) { switch (coin) { case "BitcoinCash": case "BitcoinGold": { if (path[1] === 0x80000000 + slip44ByCoin("Bitcoin")) { isPrefork = true; break; } return unknown; } case "BitcoinSV": { if (path[1] === 0x80000000 + slip44ByCoin("Bitcoin") || path[1] === 0x80000000 + slip44ByCoin("BitcoinCash")) { isPrefork = true; break; } return unknown; } default: return unknown; } } let attributes = isPrefork ? ["Prefork"] : []; switch (coin) { case "Bitcoin": case "Litecoin": case "BitcoinGold": case "Testnet": { if (script) attributes = attributes.concat(script); break; } default: break; } let attr = attributes.length ? ` (${attributes.join(", ")})` : ""; let accountIdx = path[2] & 0x7fffffff; if (wholeAccount) { return { coin, verbose: `${coin} Account #${accountIdx}${attr}`, accountIdx, wholeAccount: true, isKnown: true, scriptType, isPrefork, }; } else { let change = path[3] === 1 ? "Change " : ""; let addressIdx = path[4]; return { coin, verbose: `${coin} Account #${accountIdx}, ${change}Address #${addressIdx}${attr}`, accountIdx, addressIdx, wholeAccount: false, isKnown: true, isChange: path[3] === 1, scriptType, isPrefork, }; } } export function legacyAccount(coin: Coin, slip44: number, accountIdx: number): BTCAccountPath { return { coin, scriptType: BTCInputScriptType.SpendAddress, addressNList: [0x80000000 + 44, 0x80000000 + slip44, 0x80000000 + accountIdx], }; } export function segwitAccount(coin: Coin, slip44: number, accountIdx: number): BTCAccountPath { return { coin, scriptType: BTCInputScriptType.SpendP2SHWitness, addressNList: [0x80000000 + 49, 0x80000000 + slip44, 0x80000000 + accountIdx], }; } export function segwitNativeAccount(coin: Coin, slip44: number, accountIdx: number): BTCAccountPath { return { coin, scriptType: BTCInputScriptType.SpendWitness, addressNList: [0x80000000 + 84, 0x80000000 + slip44, 0x80000000 + accountIdx], }; }
the_stack
* ECharts option manager */ // import ComponentModel, { ComponentModelConstructor } from './Component'; import ExtensionAPI from '../core/ExtensionAPI'; import { OptionPreprocessor, MediaQuery, ECUnitOption, MediaUnit, ECBasicOption, SeriesOption } from '../util/types'; import GlobalModel, { InnerSetOptionOpts } from './Global'; import { normalizeToArray // , MappingExistingItem, setComponentTypeToKeyInfo, mappingToExists } from '../util/model'; import { each, clone, map, isTypedArray, setAsPrimitive, isArray, isObject // , HashMap , createHashMap, extend, merge, } from 'zrender/src/core/util'; import { DatasetOption } from '../component/dataset/install'; import { error } from '../util/log'; const QUERY_REG = /^(min|max)?(.+)$/; interface ParsedRawOption { baseOption: ECUnitOption; timelineOptions: ECUnitOption[]; mediaDefault: MediaUnit; mediaList: MediaUnit[]; } // Key: mainType // type FakeComponentsMap = HashMap<(MappingExistingItem & { subType: string })[]>; /** * TERM EXPLANATIONS: * See `ECOption` and `ECUnitOption` in `src/util/types.ts`. */ class OptionManager { private _api: ExtensionAPI; private _timelineOptions: ECUnitOption[] = []; private _mediaList: MediaUnit[] = []; private _mediaDefault: MediaUnit; /** * -1, means default. * empty means no media. */ private _currentMediaIndices: number[] = []; private _optionBackup: ParsedRawOption; // private _fakeCmptsMap: FakeComponentsMap; private _newBaseOption: ECUnitOption; // timeline.notMerge is not supported in ec3. Firstly there is rearly // case that notMerge is needed. Secondly supporting 'notMerge' requires // rawOption cloned and backuped when timeline changed, which does no // good to performance. What's more, that both timeline and setOption // method supply 'notMerge' brings complex and some problems. // Consider this case: // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false); // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false); constructor(api: ExtensionAPI) { this._api = api; } setOption( rawOption: ECBasicOption, optionPreprocessorFuncs: OptionPreprocessor[], opt: InnerSetOptionOpts ): void { if (rawOption) { // That set dat primitive is dangerous if user reuse the data when setOption again. each(normalizeToArray((rawOption as ECUnitOption).series), function (series: SeriesOption) { series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data); }); each(normalizeToArray((rawOption as ECUnitOption).dataset), function (dataset: DatasetOption) { dataset && dataset.source && isTypedArray(dataset.source) && setAsPrimitive(dataset.source); }); } // Caution: some series modify option data, if do not clone, // it should ensure that the repeat modify correctly // (create a new object when modify itself). rawOption = clone(rawOption); // FIXME // If some property is set in timeline options or media option but // not set in baseOption, a warning should be given. const optionBackup = this._optionBackup; const newParsedOption = parseRawOption( rawOption, optionPreprocessorFuncs, !optionBackup ); this._newBaseOption = newParsedOption.baseOption; // For setOption at second time (using merge mode); if (optionBackup) { // FIXME // the restore merge solution is essentially incorrect. // the mapping can not be 100% consistent with ecModel, which probably brings // potential bug! // The first merge is delayed, becuase in most cases, users do not call `setOption` twice. // let fakeCmptsMap = this._fakeCmptsMap; // if (!fakeCmptsMap) { // fakeCmptsMap = this._fakeCmptsMap = createHashMap(); // mergeToBackupOption(fakeCmptsMap, null, optionBackup.baseOption, null); // } // mergeToBackupOption( // fakeCmptsMap, optionBackup.baseOption, newParsedOption.baseOption, opt // ); // For simplicity, timeline options and media options do not support merge, // that is, if you `setOption` twice and both has timeline options, the latter // timeline opitons will not be merged to the formers, but just substitude them. if (newParsedOption.timelineOptions.length) { optionBackup.timelineOptions = newParsedOption.timelineOptions; } if (newParsedOption.mediaList.length) { optionBackup.mediaList = newParsedOption.mediaList; } if (newParsedOption.mediaDefault) { optionBackup.mediaDefault = newParsedOption.mediaDefault; } } else { this._optionBackup = newParsedOption; } } mountOption(isRecreate: boolean): ECUnitOption { const optionBackup = this._optionBackup; this._timelineOptions = optionBackup.timelineOptions; this._mediaList = optionBackup.mediaList; this._mediaDefault = optionBackup.mediaDefault; this._currentMediaIndices = []; return clone(isRecreate // this._optionBackup.baseOption, which is created at the first `setOption` // called, and is merged into every new option by inner method `mergeToBackupOption` // each time `setOption` called, can be only used in `isRecreate`, because // its reliability is under suspicion. In other cases option merge is // performed by `model.mergeOption`. ? optionBackup.baseOption : this._newBaseOption ); } getTimelineOption(ecModel: GlobalModel): ECUnitOption { let option; const timelineOptions = this._timelineOptions; if (timelineOptions.length) { // getTimelineOption can only be called after ecModel inited, // so we can get currentIndex from timelineModel. const timelineModel = ecModel.getComponent('timeline'); if (timelineModel) { option = clone( // FIXME:TS as TimelineModel or quivlant interface timelineOptions[(timelineModel as any).getCurrentIndex()] ); } } return option; } getMediaOption(ecModel: GlobalModel): ECUnitOption[] { const ecWidth = this._api.getWidth(); const ecHeight = this._api.getHeight(); const mediaList = this._mediaList; const mediaDefault = this._mediaDefault; let indices = []; let result: ECUnitOption[] = []; // No media defined. if (!mediaList.length && !mediaDefault) { return result; } // Multi media may be applied, the latter defined media has higher priority. for (let i = 0, len = mediaList.length; i < len; i++) { if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) { indices.push(i); } } // FIXME // Whether mediaDefault should force users to provide? Otherwise // the change by media query can not be recorvered. if (!indices.length && mediaDefault) { indices = [-1]; } if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) { result = map(indices, function (index) { return clone( index === -1 ? mediaDefault.option : mediaList[index].option ); }); } // Otherwise return nothing. this._currentMediaIndices = indices; return result; } } /** * [RAW_OPTION_PATTERNS] * (Note: "series: []" represents all other props in `ECUnitOption`) * * (1) No prop "baseOption" declared: * Root option is used as "baseOption" (except prop "options" and "media"). * ```js * option = { * series: [], * timeline: {}, * options: [], * }; * option = { * series: [], * media: {}, * }; * option = { * series: [], * timeline: {}, * options: [], * media: {}, * } * ``` * * (2) Prop "baseOption" declared: * If "baseOption" declared, `ECUnitOption` props can only be declared * inside "baseOption" except prop "timeline" (compat ec2). * ```js * option = { * baseOption: { * timeline: {}, * series: [], * }, * options: [] * }; * option = { * baseOption: { * series: [], * }, * media: [] * }; * option = { * baseOption: { * timeline: {}, * series: [], * }, * options: [] * media: [] * }; * option = { * // ec3 compat ec2: allow (only) `timeline` declared * // outside baseOption. Keep this setting for compat. * timeline: {}, * baseOption: { * series: [], * }, * options: [], * media: [] * }; * ``` */ function parseRawOption( // `rawOption` May be modified rawOption: ECBasicOption, optionPreprocessorFuncs: OptionPreprocessor[], isNew: boolean ): ParsedRawOption { const mediaList: MediaUnit[] = []; let mediaDefault: MediaUnit; let baseOption: ECUnitOption; const declaredBaseOption = rawOption.baseOption; // Compatible with ec2, [RAW_OPTION_PATTERNS] above. const timelineOnRoot = rawOption.timeline; const timelineOptionsOnRoot = rawOption.options; const mediaOnRoot = rawOption.media; const hasMedia = !!rawOption.media; const hasTimeline = !!( timelineOptionsOnRoot || timelineOnRoot || (declaredBaseOption && declaredBaseOption.timeline) ); if (declaredBaseOption) { baseOption = declaredBaseOption; // For merge option. if (!baseOption.timeline) { baseOption.timeline = timelineOnRoot; } } // For convenience, enable to use the root option as the `baseOption`: // `{ ...normalOptionProps, media: [{ ... }, { ... }] }` else { if (hasTimeline || hasMedia) { rawOption.options = rawOption.media = null; } baseOption = rawOption; } if (hasMedia) { if (isArray(mediaOnRoot)) { each(mediaOnRoot, function (singleMedia) { if (__DEV__) { // Real case of wrong config. if (singleMedia && !singleMedia.option && isObject(singleMedia.query) && isObject((singleMedia.query as any).option) ) { error('Illegal media option. Must be like { media: [ { query: {}, option: {} } ] }'); } } if (singleMedia && singleMedia.option) { if (singleMedia.query) { mediaList.push(singleMedia); } else if (!mediaDefault) { // Use the first media default. mediaDefault = singleMedia; } } }); } else { if (__DEV__) { // Real case of wrong config. error('Illegal media option. Must be an array. Like { media: [ {...}, {...} ] }'); } } } doPreprocess(baseOption); each(timelineOptionsOnRoot, option => doPreprocess(option)); each(mediaList, media => doPreprocess(media.option)); function doPreprocess(option: ECUnitOption) { each(optionPreprocessorFuncs, function (preProcess) { preProcess(option, isNew); }); } return { baseOption: baseOption, timelineOptions: timelineOptionsOnRoot || [], mediaDefault: mediaDefault, mediaList: mediaList }; } /** * @see <http://www.w3.org/TR/css3-mediaqueries/#media1> * Support: width, height, aspectRatio * Can use max or min as prefix. */ function applyMediaQuery(query: MediaQuery, ecWidth: number, ecHeight: number): boolean { const realMap = { width: ecWidth, height: ecHeight, aspectratio: ecWidth / ecHeight // lowser case for convenientce. }; let applicatable = true; each(query, function (value: number, attr) { const matched = attr.match(QUERY_REG); if (!matched || !matched[1] || !matched[2]) { return; } const operator = matched[1]; const realAttr = matched[2].toLowerCase(); if (!compare(realMap[realAttr as keyof typeof realMap], value, operator)) { applicatable = false; } }); return applicatable; } function compare(real: number, expect: number, operator: string): boolean { if (operator === 'min') { return real >= expect; } else if (operator === 'max') { return real <= expect; } else { // Equals return real === expect; } } function indicesEquals(indices1: number[], indices2: number[]): boolean { // indices is always order by asc and has only finite number. return indices1.join(',') === indices2.join(','); } /** * Consider case: * `chart.setOption(opt1);` * Then user do some interaction like dataZoom, dataView changing. * `chart.setOption(opt2);` * Then user press 'reset button' in toolbox. * * After doing that all of the interaction effects should be reset, the * chart should be the same as the result of invoke * `chart.setOption(opt1); chart.setOption(opt2);`. * * Although it is not able ensure that * `chart.setOption(opt1); chart.setOption(opt2);` is equivalents to * `chart.setOption(merge(opt1, opt2));` exactly, * this might be the only simple way to implement that feature. * * MEMO: We've considered some other approaches: * 1. Each model handle its self restoration but not uniform treatment. * (Too complex in logic and error-prone) * 2. Use a shadow ecModel. (Performace expensive) * * FIXME: A possible solution: * Add a extra level of model for each component model. The inheritance chain would be: * ecModel <- componentModel <- componentActionModel <- dataItemModel * And all of the actions can only modify the `componentActionModel` rather than * `componentModel`. `setOption` will only modify the `ecModel` and `componentModel`. * When "resotre" action triggered, model from `componentActionModel` will be discarded * instead of recreating the "ecModel" from the "_optionBackup". */ // function mergeToBackupOption( // fakeCmptsMap: FakeComponentsMap, // // `tarOption` Can be null/undefined, means init // tarOption: ECUnitOption, // newOption: ECUnitOption, // // Can be null/undefined // opt: InnerSetOptionOpts // ): void { // newOption = newOption || {} as ECUnitOption; // const notInit = !!tarOption; // each(newOption, function (newOptsInMainType, mainType) { // if (newOptsInMainType == null) { // return; // } // if (!ComponentModel.hasClass(mainType)) { // if (tarOption) { // tarOption[mainType] = merge(tarOption[mainType], newOptsInMainType, true); // } // } // else { // const oldTarOptsInMainType = notInit ? normalizeToArray(tarOption[mainType]) : null; // const oldFakeCmptsInMainType = fakeCmptsMap.get(mainType) || []; // const resultTarOptsInMainType = notInit ? (tarOption[mainType] = [] as ComponentOption[]) : null; // const resultFakeCmptsInMainType = fakeCmptsMap.set(mainType, []); // const mappingResult = mappingToExists( // oldFakeCmptsInMainType, // normalizeToArray(newOptsInMainType), // (opt && opt.replaceMergeMainTypeMap.get(mainType)) ? 'replaceMerge' : 'normalMerge' // ); // setComponentTypeToKeyInfo(mappingResult, mainType, ComponentModel as ComponentModelConstructor); // each(mappingResult, function (resultItem, index) { // // The same logic as `Global.ts#_mergeOption`. // let fakeCmpt = resultItem.existing; // const newOption = resultItem.newOption; // const keyInfo = resultItem.keyInfo; // let fakeCmptOpt; // if (!newOption) { // fakeCmptOpt = oldTarOptsInMainType[index]; // } // else { // if (fakeCmpt && fakeCmpt.subType === keyInfo.subType) { // fakeCmpt.name = keyInfo.name; // if (notInit) { // fakeCmptOpt = merge(oldTarOptsInMainType[index], newOption, true); // } // } // else { // fakeCmpt = extend({}, keyInfo); // if (notInit) { // fakeCmptOpt = clone(newOption); // } // } // } // if (fakeCmpt) { // notInit && resultTarOptsInMainType.push(fakeCmptOpt); // resultFakeCmptsInMainType.push(fakeCmpt); // } // else { // notInit && resultTarOptsInMainType.push(void 0); // resultFakeCmptsInMainType.push(void 0); // } // }); // } // }); // } export default OptionManager;
the_stack
import autobind from 'autobind-decorator'; import Vue from 'vue'; import { EventEmitter } from 'eventemitter3'; import * as uuid from 'uuid'; import initStore from './store'; import { apiUrl, version, locale } from './config'; import Progress from './common/scripts/loading'; import Err from './common/views/components/connect-failed.vue'; import Stream from './common/scripts/stream'; //#region api requests let spinner = null; let pending = 0; //#endregion /** * Misskey Operating System */ export default class MiOS extends EventEmitter { /** * Misskeyの /meta で取得できるメタ情報 */ private meta: { data: { [x: string]: any }; chachedAt: Date; }; public get instanceName() { return this.meta ? (this.meta.data.name || 'CMCC-SNS') : 'CMCC-SNS'; } private isMetaFetching = false; public app: Vue; /** * Whether is debug mode */ public get debug() { return this.store ? this.store.state.device.debug : false; } public store: ReturnType<typeof initStore>; /** * A connection manager of home stream */ public stream: Stream; /** * A registration of service worker */ private swRegistration: ServiceWorkerRegistration = null; /** * Whether should register ServiceWorker */ private shouldRegisterSw: boolean; /** * ウィンドウシステム */ public windows = new WindowSystem(); /** * MiOSインスタンスを作成します * @param shouldRegisterSw ServiceWorkerを登録するかどうか */ constructor(shouldRegisterSw = false) { super(); this.shouldRegisterSw = shouldRegisterSw; if (this.debug) { (window as any).os = this; } } @autobind public log(...args) { if (!this.debug) return; console.log.apply(null, args); } @autobind public logInfo(...args) { if (!this.debug) return; console.info.apply(null, args); } @autobind public logWarn(...args) { if (!this.debug) return; console.warn.apply(null, args); } @autobind public logError(...args) { if (!this.debug) return; console.error.apply(null, args); } @autobind public signout() { this.store.dispatch('logout'); location.href = '/'; } /** * Initialize MiOS (boot) * @param callback A function that call when initialized */ @autobind public async init(callback) { this.store = initStore(this); // ユーザーをフェッチしてコールバックする const fetchme = (token, cb) => { let me = null; // Return when not signed in if (token == null) { return done(); } // Fetch user fetch(`${apiUrl}/i`, { method: 'POST', body: JSON.stringify({ i: token }) }) // When success .then(res => { // When failed to authenticate user if (res.status !== 200 && res.status < 500) { return this.signout(); } // Parse response res.json().then(i => { me = i; me.token = token; done(); }); }) // When failure .catch(() => { // Render the error screen document.body.innerHTML = '<div id="err"></div>'; new Vue({ render: createEl => createEl(Err) }).$mount('#err'); Progress.done(); }); function done() { if (cb) cb(me); } }; // フェッチが完了したとき const fetched = () => { this.emit('signedin'); this.initStream(); // Finish init callback(); // Init service worker if (this.shouldRegisterSw) { // #4813 //this.getMeta().then(data => { // this.registerSw(data.swPublickey); //}); } }; // キャッシュがあったとき if (this.store.state.i != null) { if (this.store.state.i.token == null) { this.signout(); return; } // とりあえずキャッシュされたデータでお茶を濁して(?)おいて、 fetched(); // 後から新鮮なデータをフェッチ fetchme(this.store.state.i.token, freshData => { this.store.dispatch('mergeMe', freshData); }); } else { // Get token from cookie or localStorage const i = (document.cookie.match(/i=(\w+)/) || [null, null])[1] || localStorage.getItem('i'); fetchme(i, me => { if (me) { this.store.dispatch('login', me); fetched(); } else { this.initStream(); // Finish init callback(); } }); } } @autobind private initStream() { this.stream = new Stream(this); if (this.store.getters.isSignedIn) { const main = this.stream.useSharedConnection('main'); // 自分の情報が更新されたとき main.on('meUpdated', i => { this.store.dispatch('mergeMe', i); }); main.on('readAllNotifications', () => { this.store.dispatch('mergeMe', { hasUnreadNotification: false }); }); main.on('unreadNotification', () => { this.store.dispatch('mergeMe', { hasUnreadNotification: true }); }); main.on('readAllMessagingMessages', () => { this.store.dispatch('mergeMe', { hasUnreadMessagingMessage: false }); }); main.on('unreadMessagingMessage', () => { this.store.dispatch('mergeMe', { hasUnreadMessagingMessage: true }); }); main.on('unreadMention', () => { this.store.dispatch('mergeMe', { hasUnreadMentions: true }); }); main.on('readAllUnreadMentions', () => { this.store.dispatch('mergeMe', { hasUnreadMentions: false }); }); main.on('unreadSpecifiedNote', () => { this.store.dispatch('mergeMe', { hasUnreadSpecifiedNotes: true }); }); main.on('readAllUnreadSpecifiedNotes', () => { this.store.dispatch('mergeMe', { hasUnreadSpecifiedNotes: false }); }); main.on('clientSettingUpdated', x => { this.store.commit('settings/set', { key: x.key, value: x.value }); }); // トークンが再生成されたとき // このままではMisskeyが利用できないので強制的にサインアウトさせる main.on('myTokenRegenerated', () => { alert(locale['common']['my-token-regenerated']); this.signout(); }); } } /** * Register service worker */ @autobind private registerSw(swPublickey) { // Check whether service worker and push manager supported const isSwSupported = ('serviceWorker' in navigator) && ('PushManager' in window); // Reject when browser not service worker supported if (!isSwSupported) return; // Reject when not signed in to Misskey if (!this.store.getters.isSignedIn) return; // When service worker activated navigator.serviceWorker.ready.then(registration => { this.log('[sw] ready: ', registration); this.swRegistration = registration; // Options of pushManager.subscribe // SEE: https://developer.mozilla.org/en-US/docs/Web/API/PushManager/subscribe#Parameters const opts = { // A boolean indicating that the returned push subscription // will only be used for messages whose effect is made visible to the user. userVisibleOnly: true, // A public key your push server will use to send // messages to client apps via a push server. applicationServerKey: urlBase64ToUint8Array(swPublickey) }; // Subscribe push notification this.swRegistration.pushManager.subscribe(opts).then(subscription => { this.log('[sw] Subscribe OK:', subscription); function encode(buffer: ArrayBuffer) { return btoa(String.fromCharCode.apply(null, new Uint8Array(buffer))); } // Register this.api('sw/register', { endpoint: subscription.endpoint, auth: encode(subscription.getKey('auth')), publickey: encode(subscription.getKey('p256dh')) }); }) // When subscribe failed .catch(async (err: Error) => { this.logError('[sw] Subscribe Error:', err); // 通知が許可されていなかったとき if (err.name == 'NotAllowedError') { this.logError('[sw] Subscribe failed due to notification not allowed'); return; } // 違うapplicationServerKey (または gcm_sender_id)のサブスクリプションが // 既に存在していることが原因でエラーになった可能性があるので、 // そのサブスクリプションを解除しておく const subscription = await this.swRegistration.pushManager.getSubscription(); if (subscription) subscription.unsubscribe(); }); }); // The path of service worker script const sw = `/sw.${version}.js`; // Register service worker navigator.serviceWorker.register(sw).then(registration => { // 登録成功 this.logInfo('[sw] Registration successful with scope: ', registration.scope); }).catch(err => { // 登録失敗 :( this.logError('[sw] Registration failed: ', err); }); } public requests = []; /** * Misskey APIにリクエストします * @param endpoint エンドポイント名 * @param data パラメータ */ @autobind public api(endpoint: string, data: { [x: string]: any } = {}, silent = false): Promise<{ [x: string]: any }> { if (!silent) { if (++pending === 1) { spinner = document.createElement('div'); spinner.setAttribute('id', 'wait'); document.body.appendChild(spinner); } } const onFinally = () => { if (!silent) { if (--pending === 0) spinner.parentNode.removeChild(spinner); } }; const promise = new Promise((resolve, reject) => { // Append a credential if (this.store.getters.isSignedIn) (data as any).i = this.store.state.i.token; const req = { id: uuid(), date: new Date(), name: endpoint, data, res: null, status: null }; if (this.debug) { this.requests.push(req); } // Send request fetch(endpoint.indexOf('://') > -1 ? endpoint : `${apiUrl}/${endpoint}`, { method: 'POST', body: JSON.stringify(data), credentials: endpoint === 'signin' ? 'include' : 'omit', cache: 'no-cache' }).then(async (res) => { const body = res.status === 204 ? null : await res.json(); if (this.debug) { req.status = res.status; req.res = body; } if (res.status === 200) { resolve(body); } else if (res.status === 204) { resolve(); } else { reject(body.error); } }).catch(reject); }); promise.then(onFinally, onFinally); return promise; } /** * Misskeyのメタ情報を取得します */ @autobind public getMetaSync() { return this.meta ? this.meta.data : null; } /** * Misskeyのメタ情報を取得します * @param force キャッシュを無視するか否か */ @autobind public getMeta(force = false) { return new Promise<{ [x: string]: any }>(async (res, rej) => { if (this.isMetaFetching) { this.once('_meta_fetched_', () => { res(this.meta.data); }); return; } const expire = 1000 * 60; // 1min // forceが有効, meta情報を保持していない or 期限切れ if (force || this.meta == null || Date.now() - this.meta.chachedAt.getTime() > expire) { this.isMetaFetching = true; const meta = await this.api('meta', { detail: false }); this.meta = { data: meta, chachedAt: new Date() }; this.isMetaFetching = false; this.emit('_meta_fetched_'); res(meta); } else { res(this.meta.data); } }); } } class WindowSystem extends EventEmitter { public windows = new Set(); public add(window) { this.windows.add(window); this.emit('added', window); } public remove(window) { this.windows.delete(window); this.emit('removed', window); } public getAll() { return this.windows; } } /** * Convert the URL safe base64 string to a Uint8Array * @param base64String base64 string */ function urlBase64ToUint8Array(base64String: string): Uint8Array { const padding = '='.repeat((4 - base64String.length % 4) % 4); const base64 = (base64String + padding) .replace(/-/g, '+') .replace(/_/g, '/'); const rawData = window.atob(base64); const outputArray = new Uint8Array(rawData.length); for (let i = 0; i < rawData.length; ++i) { outputArray[i] = rawData.charCodeAt(i); } return outputArray; }
the_stack
import {Directive, ElementRef, EventEmitter, Input, NgModule, NgZone, OnDestroy, Output, Renderer2, TemplateRef, Type} from "@angular/core"; import {Subscription} from 'rxjs'; import { IPopupable, PopupDisposer, PopupInfo, PopupOptions, PopupPoint, PopupPositionType, PopupPositionValue, PopupService } from "../../service/popup.service"; import {AbstractJigsawViewBase} from "../../common"; import {CommonUtils} from "../../core/utils/common-utils"; import {AffixUtils} from "../../core/utils/internal-utils"; export enum DropDownTrigger { click, mouseenter, mouseleave, none, } export type FloatPosition = 'bottomLeft' | 'bottomRight' | 'topLeft' | 'topRight' | 'leftTop' | 'leftBottom' | 'rightTop' | 'rightBottom' | 'left' | 'right' | 'top' | 'bottom'; @Directive() export class JigsawFloatBase extends AbstractJigsawViewBase implements OnDestroy { protected _removeWindowClickHandler: Function; private _popupInfo: PopupInfo; private _originDisposer: PopupDisposer; private _removePopupClickHandler: Function; private _removeMouseOverHandler: Function; private _removeMouseOutHandler: Function; private _removeResizeHandler: Function; private _rollOutDenouncesTimer: any = null; private _rollInDenouncesTimer: any = null; /** * @internal */ public _jigsawFloatOpenDelay: number = 100; public get jigsawFloatOpenDelay(): number { return this._jigsawFloatOpenDelay; } public set jigsawFloatOpenDelay(value: number) { this._jigsawFloatOpenDelay = typeof value != 'number' ? parseInt(value) : value; } /** * @internal */ private _jigsawFloatCloseDelay: number = 400; public get jigsawFloatCloseDelay(): number { return this._jigsawFloatCloseDelay; } public set jigsawFloatCloseDelay(value: number) { this._jigsawFloatCloseDelay = typeof value != 'number' ? parseInt(value) : value; } public get popupElement(): HTMLElement { return this._popupInfo ? this._popupInfo.element : null; } public get popupInstance(): any { return this._popupInfo ? this._popupInfo.instance : null; } private _jigsawFloatArrowElement: HTMLElement; /** * @internal */ public get jigsawFloatArrowElement(): HTMLElement { return this._jigsawFloatArrowElement; } public set jigsawFloatArrowElement(el: HTMLElement) { this._jigsawFloatArrowElement = el; this._setArrow(this.popupElement); } private _jigsawFloatInitData: any; /** * @internal */ public get jigsawFloatInitData(): any { return this._jigsawFloatInitData; } public set jigsawFloatInitData(data: any) { this._jigsawFloatInitData = data; if (this.popupInstance && this.initialized) { this.popupInstance.initData = data; } } private _floatTarget: Type<IPopupable> | TemplateRef<any>; /** * @internal */ public get jigsawFloatTarget(): Type<IPopupable> | TemplateRef<any> { return this._floatTarget; } public set jigsawFloatTarget(value: Type<IPopupable> | TemplateRef<any>) { if (this._floatTarget == value) { return; } this._floatTarget = value; if (!this._opened) { return; } this._closeFloat(); this.callLater(() => { // 这里必须使用setTimeout来跳过第一次冒泡上来的window.click this._openFloat(); }); } /** * @internal */ public jigsawFloatOptions: PopupOptions; /** * @internal */ public jigsawFloatPosition: FloatPosition = 'bottomLeft'; private _opened: boolean = false; /** * @internal */ public get jigsawFloatOpen(): boolean { return this._opened; } public set jigsawFloatOpen(value: boolean) { value = !!value; if (value == this._opened) { return; } this.callLater(() => { // toggle open 外部控制时,用异步触发变更检查 // 初始化open,等待组件初始化后执行 // 这里必须使用setTimeout来跳过第一次冒泡上来的window.click if (value) { this.openFloat(); } else { this.closeFloat(); } }); } /** * @internal */ public jigsawFloatOpenChange: EventEmitter<boolean> = new EventEmitter<boolean>(); /** * @internal */ public jigsawFloatCloseTrigger: 'click' | 'mouseleave' | 'none' | DropDownTrigger; /** * @internal */ public jigsawFloatOpenTrigger: 'click' | 'mouseenter' | 'none' | DropDownTrigger; /** * @internal */ public jigsawFloatAnswer = new EventEmitter<any>(); constructor(protected _renderer: Renderer2, protected _elementRef: ElementRef, protected _popupService: PopupService, protected _zone: NgZone) { super(_zone); this._init(); } /** * 留给子类去覆盖 */ protected _init(): void { } protected _emitOpenChange(open: boolean): void { this._opened = open; this.jigsawFloatOpenChange.emit(open); } public openFloat(): void { if (this._popupInfo) { return; } this._openFloat(); this._emitOpenChange(true); } public closeFloat($event?: any): void { if (!this._popupInfo) { return; } this._closeFloat($event); this._emitOpenChange(false); } public ngOnDestroy() { super.ngOnDestroy(); this.jigsawFloatOpen = false; this._floatTarget = null; this._clearAllListeners(); this._disposePopup(); if (this._removeAnswerSubscriber) { this._removeAnswerSubscriber.unsubscribe(); this._removeAnswerSubscriber = null; } } /** * 弹出的视图在用户交互过程中,有可能发生尺寸变化,有可能造成位置错误 * 此时通过调用这个方法可以重新定位弹出视图的位置 */ public reposition(): void { if (this.popupElement) { this._popupService.setPosition(this._getPopupOption(), this.popupElement); this._setArrow(this.popupElement); } } /** * @internal */ public _$openByHover(event): void { this.clearCallLater(this._rollOutDenouncesTimer); if (this.jigsawFloatOpenTrigger != 'mouseenter') { return; } event.preventDefault(); event.stopPropagation(); this._rollInDenouncesTimer = this.callLater(() => { this.jigsawFloatOpen = true; }, this.jigsawFloatOpenDelay); } /** * @internal * @param event * @param offset 代表偏移,注册在float触发器上的mouseleave在计算element中的位置是要往前回退一个坐标, * 注册在弹出层上的mouseleave无需偏移 */ public _$closeByHover(event: any, offset: number = 0) { const popups = this._popupService.popups; this.clearCallLater(this._rollInDenouncesTimer); if (this.jigsawFloatCloseTrigger != 'mouseleave' || !popups || popups.length == 0) { return; } event.preventDefault(); event.stopPropagation(); let canClose = true; // currentIndex之后的弹层导致触发mouseleave不应关闭float const currentIndex = popups.indexOf(popups.find(p => p.element === this.popupElement)); for (let i = popups.length - 1; i > currentIndex - offset && i >= 0; i--) { if (canClose == false) { break; } if (i > currentIndex - offset) { canClose = !this._isChildOf(event.toElement, popups[i].element); } } // 弹出的全局遮盖jigsaw-block' 触发的mouseleave不应关闭float if (event.toElement && event.toElement.className !== 'jigsaw-block' && canClose) { this._rollOutDenouncesTimer = this.callLater(() => { this.closeFloat(event); }, this.jigsawFloatCloseDelay); } } /** * @internal */ public _$onHostClick() { if (this.jigsawFloatOpenTrigger == 'click' && !this.jigsawFloatOpen) { this.jigsawFloatOpen = true; } } private _isChildOf(child, parent): boolean { if (child && parent) { let parentNode = child; while (parentNode) { if (parent === parentNode) { return true; } parentNode = parentNode.parentNode; } } return false; } protected _onWindowClick(event: any): void { if (this.jigsawFloatCloseTrigger == 'none') { return; } if (event.target == this._elementRef.nativeElement) { return; } if (this._isChildOf(event.target, this._elementRef.nativeElement)) { return; } if (this._removeWindowClickHandler) { this._removeWindowClickHandler(); this._removeWindowClickHandler = null; } if (this._removeResizeHandler) { this._removeResizeHandler(); this._removeResizeHandler = null; } this.closeFloat(event); } protected _onPopupElementClick(event: any): void { event.stopPropagation(); event.preventDefault(); } protected _disposePopup() { if (!this._popupInfo || !this._originDisposer) { return; } this._originDisposer(); this._originDisposer = null; this._popupInfo = null; } private _removeAnswerSubscriber: Subscription; /** * 立即弹出下拉视图,请注意不要重复弹出,此方法没有做下拉重复弹出的保护 */ protected _openFloat(): PopupInfo { if (!this.jigsawFloatTarget || this._opened) { return; } this._opened = true; if (this._removeWindowClickHandler) { this._removeWindowClickHandler(); } // 点击window时,自动关闭,但当closeTrigger为none时无法关掉的 this._removeWindowClickHandler = this._renderer.listen('window', 'click', event => this._onWindowClick(event)); const option: PopupOptions = this._getPopupOption(); const popupInfo = this._popupService.popup(this.jigsawFloatTarget as any, option, this.jigsawFloatInitData); if (!popupInfo.element) { console.error('unable to popup drop down, unknown error!'); return popupInfo; } this._popupInfo = popupInfo; this._originDisposer = popupInfo.dispose; popupInfo.dispose = this.closeFloat.bind(this); if (this._removeAnswerSubscriber) { this._removeAnswerSubscriber.unsubscribe(); this._removeAnswerSubscriber = null; } if (popupInfo.answer) { this._removeAnswerSubscriber = popupInfo.answer.subscribe(data => { this.jigsawFloatAnswer.emit(data); }); } if (option.borderType == 'pointer') { this.runAfterMicrotasks(() => this._setArrow(this.popupElement)); } if (!this._removeMouseOverHandler) { this._removeMouseOverHandler = this._renderer.listen( popupInfo.element, 'mouseenter', () => this.clearCallLater(this._rollOutDenouncesTimer)); } if (this.jigsawFloatCloseTrigger == 'mouseleave' && !this._removeMouseOutHandler) { this._removeMouseOutHandler = this._renderer.listen( popupInfo.element, 'mouseleave', event => this._$closeByHover(event)); } // 阻止点击行为冒泡到window if (this._removePopupClickHandler) { this._removePopupClickHandler(); } this._removePopupClickHandler = this._renderer.listen( popupInfo.element, 'click', event => this._onPopupElementClick(event)); // 监听window的resize事件,自动更新位置 if (this._removeResizeHandler) { this._removeResizeHandler(); } this._removeResizeHandler = this._renderer.listen("window", "resize", () => { PopupService.instance.setPosition(this._getPopupOption(), popupInfo.element); if (option.borderType == 'pointer') { popupInfo.element.removeChild(popupInfo.element.children[popupInfo.element.children.length - 1]); this._setArrow(popupInfo.element); } }); return popupInfo; } private _getPos(): PopupPoint { let point = this._getElementPos(); const differ = this.jigsawFloatOptions && this.jigsawFloatOptions.borderType == 'pointer' ? 7 : 0; switch (this.jigsawFloatPosition) { case 'bottomLeft': point.y += this._elementRef.nativeElement.offsetHeight + differ; break; case 'bottomRight': point.x += this._elementRef.nativeElement.offsetWidth; point.y += this._elementRef.nativeElement.offsetHeight + differ; break; case 'topRight': point.x += this._elementRef.nativeElement.offsetWidth; break; case 'leftBottom': point.y += this._elementRef.nativeElement.offsetHeight; break; case 'rightTop': point.x += this._elementRef.nativeElement.offsetWidth + differ; break; case 'rightBottom': point.x += this._elementRef.nativeElement.offsetWidth + differ; point.y += this._elementRef.nativeElement.offsetHeight; break; case 'top': point.x += this._elementRef.nativeElement.offsetWidth / 2; break; case 'bottom': point.x += this._elementRef.nativeElement.offsetWidth / 2; point.y += this._elementRef.nativeElement.offsetHeight; break; case 'left': point.y += this._elementRef.nativeElement.offsetHeight / 2; break; case 'right': point.x += this._elementRef.nativeElement.offsetWidth; point.y += this._elementRef.nativeElement.offsetHeight / 2; } return point; } private _getElementPos(element?: HTMLElement) { element = element ? element : this._elementRef.nativeElement; let point = new PopupPoint(); if (this.jigsawFloatOptions && this.jigsawFloatOptions.posType == PopupPositionType.fixed) { // 获取触发点相对于视窗的位置 const tempRect = element.getBoundingClientRect(); point.y = tempRect.top; point.x = tempRect.left; } else { point.y = AffixUtils.offset(element).top; point.x = AffixUtils.offset(element).left; } return point; } // 被弹出的控件高度宽度,在弹出之前并不知道,故要再控件位置微调时加入进去 private _changePosByFloatPosition(pos: PopupPositionValue, popupElement: HTMLElement) { switch (this.jigsawFloatPosition) { case 'bottomRight': pos.left -= popupElement.offsetWidth; break; case 'topLeft': pos.top -= popupElement.offsetHeight; break; case 'topRight': pos.top -= popupElement.offsetHeight; pos.left -= popupElement.offsetWidth; break; case 'rightBottom': pos.top -= popupElement.offsetHeight; break; case 'leftTop': pos.left -= popupElement.offsetWidth; break; case 'leftBottom': pos.left -= popupElement.offsetWidth; pos.top -= popupElement.offsetHeight; break; case 'top': pos.left -= popupElement.offsetWidth / 2; pos.top -= popupElement.offsetHeight; break; case 'bottom': pos.left -= popupElement.offsetWidth / 2; break; case 'left': pos.left -= popupElement.offsetWidth; pos.top -= popupElement.offsetHeight / 2; break; case 'right': pos.top -= popupElement.offsetHeight / 2; break; } } /** * @internal */ public _getPopupOption(): PopupOptions { let option: any = {}; const calc: any = { pos: this._getPos(), posType: PopupPositionType.absolute, posReviser: (pos: PopupPositionValue, popupElement: HTMLElement): PopupPositionValue => { this._changePosByFloatPosition(pos, popupElement); this._positionReviser(pos, popupElement); return pos; }, size: { minWidth: this._elementRef.nativeElement.offsetWidth } }; Object.assign(option, calc); if (this.jigsawFloatOptions) { Object.assign(option, this.jigsawFloatOptions); if (CommonUtils.isDefined(this.jigsawFloatOptions.modal)) { console.warn('modal can not be set'); option.modal = false; } if (CommonUtils.isDefined(this.jigsawFloatOptions.pos)) { console.warn('pos can not be set'); option.pos = calc.pos; } if (CommonUtils.isDefined(this.jigsawFloatOptions.posReviser)) { option.posReviser = (pos: PopupPositionValue, popupElement: HTMLElement): PopupPositionValue => { this._changePosByFloatPosition(pos, popupElement); this.jigsawFloatOptions.posReviser(pos, popupElement); return pos; }; } } return option; } /* * 设置弹框是否有三角指向 */ private _setArrow(popupElement: HTMLElement) { const options = this._getPopupOption(); if (options.borderType != 'pointer' || !popupElement) { return; } const hostPosition = this._getElementPos(); const position: PopupPoint = {x: Math.round(hostPosition.x), y: Math.round(hostPosition.y)}; const arrowPosition = this._getElementPos(this.jigsawFloatArrowElement); const arrowPoint: PopupPoint = {x: Math.round(arrowPosition.x), y: Math.round(arrowPosition.y)}; const host = this.jigsawFloatArrowElement ? this.jigsawFloatArrowElement : this._elementRef.nativeElement; let ele = <HTMLElement>this.popupElement.querySelector('.jigsaw-float-arrow'); if (ele) { this._setArrowPosition(ele, popupElement, position, host, arrowPoint, options); } else { ele = document.createElement('div'); ele.setAttribute("class", "jigsaw-float-arrow"); // 根据tooltip尖角算出来大概在5√2,约为7px ele.style.width = '7px'; ele.style.height = '7px'; ele.style.position = 'absolute'; ele.style.transform = 'rotateZ(-45deg)'; ele.style.backgroundColor = 'inherit'; this._setArrowPosition(ele, popupElement, position, host, arrowPoint, options) popupElement.appendChild(ele); } } private _setArrowPosition(ele: HTMLElement, popupElement: HTMLElement, position: PopupPoint, host: HTMLElement, arrowPoint: PopupPoint, options: PopupOptions) { const arrowOffset = options.showBorder ? 7 / 2 + 1 : 7 / 2; const borderColor = options.borderColor ? options.borderColor : '#dcdcdc'; const popupEleTop = popupElement.offsetTop; const popupEleBottom = popupElement.offsetTop + popupElement.offsetHeight; const popupEleLeft = popupElement.offsetLeft; const popupEleRight = popupElement.offsetLeft + popupElement.offsetWidth; const hostTop = position.y; const hostBottom = position.y + host.offsetHeight; const hostRight = position.x + host.offsetWidth; const hostLeft = position.x; let adjustPopup = true; if (popupEleTop >= hostBottom) { _createTopArrow(); } else if (popupEleBottom <= hostTop) { _createBottomArrow(); } else if (popupEleLeft >= hostRight) { _createLeftArrow(); } else if (popupEleRight <= hostLeft) { _createRightArrow(); } else { // 覆盖在host上面,根据float配置渲染箭头位置 adjustPopup = false; if (this.jigsawFloatPosition.indexOf('bottom') !== -1) { _createTopArrow(); } else if (this.jigsawFloatPosition.indexOf('top') !== -1) { _createBottomArrow(); } else if (this.jigsawFloatPosition.indexOf('left') !== -1) { _createRightArrow(); } else if (this.jigsawFloatPosition.indexOf('right') !== -1) { _createLeftArrow(); } else { _createDefaultArrow(); } } /* 箭头在上 */ function _createTopArrow() { if (adjustPopup && (popupEleTop - hostBottom < 7)) { popupElement.style.top = 7 + hostBottom + 'px'; } ele.style.top = `-${arrowOffset}px`; ele.style.left = _getLeft(host, popupElement, arrowPoint) + 'px'; if (options.showBorder) { ele.style.borderTop = `1px solid ${borderColor}`; ele.style.borderRight = `1px solid ${borderColor}`; } } /* 箭头在下 */ function _createBottomArrow() { if (adjustPopup && (hostTop - popupEleBottom < 7)) { popupElement.style.top = hostTop - popupElement.offsetHeight - 7 + 'px'; } ele.style.bottom = `-${arrowOffset}px`; ele.style.left = _getLeft(host, popupElement, arrowPoint) + 'px'; if (options.showBorder) { ele.style.borderLeft = `1px solid ${borderColor}`; ele.style.borderBottom = `1px solid ${borderColor}`; } } /* 箭头在左 */ function _createLeftArrow() { if (adjustPopup && (popupEleLeft - hostRight < 7)) { popupElement.style.left = hostRight + 7 + 'px'; } ele.style.left = `-${arrowOffset}px`; ele.style.top = _getTop(host, popupElement, arrowPoint) + 'px'; if (options.showBorder) { ele.style.borderTop = `1px solid ${borderColor}`; ele.style.borderLeft = `1px solid ${borderColor}`; } } /* 箭头在右 */ function _createRightArrow() { if (adjustPopup && (hostLeft - popupEleRight < 7)) { popupElement.style.left = hostLeft - popupElement.offsetWidth - 7 + 'px'; } ele.style.right = `-${arrowOffset}px`; ele.style.top = _getTop(host, popupElement, arrowPoint) + 'px'; if (options.showBorder) { ele.style.borderRight = `1px solid ${borderColor}`; ele.style.borderBottom = `1px solid ${borderColor}`; } } /* 默认箭头 */ function _createDefaultArrow() { ele.style.left = '6px'; ele.style.bottom = `-${arrowOffset}px`; if (options.showBorder) { ele.style.borderLeft = `1px solid ${borderColor}`; ele.style.borderBottom = `1px solid ${borderColor}`; } } function _getLeft(host: HTMLElement, popupElement: HTMLElement, position: PopupPoint): number { let delta = position.x + host.offsetWidth / 2 - popupElement.offsetLeft - 7 / 2; if (delta < 4) { delta = 4; } else if (delta > popupElement.offsetWidth - 13) { delta = popupElement.offsetWidth - 13; } return delta; } function _getTop(host: HTMLElement, popupElement: HTMLElement, position: PopupPoint): number { let delta = position.y + host.offsetHeight / 2 - popupElement.offsetTop - 7 / 2; if (delta < 4) { delta = 4; } else if (delta > popupElement.offsetHeight - 13) { delta = popupElement.offsetHeight - 13; } return delta; } } /** * 计算弹层区域的位置,当指定的方向位置不够,且反向弹位置足够时,那么反向弹层 */ private _positionReviser(pos: PopupPositionValue, popupElement: HTMLElement): PopupPositionValue { const offsetWidth = this._elementRef.nativeElement.offsetWidth; const offsetHeight = this._elementRef.nativeElement.offsetHeight; const point = this._getElementPos(); const differ = this.jigsawFloatOptions && this.jigsawFloatOptions.borderType == 'pointer' ? 7 : 0; // 调整上下左右位置 if (this.jigsawFloatPosition === 'topLeft' || this.jigsawFloatPosition === 'topRight' || this.jigsawFloatPosition === 'bottomLeft' || this.jigsawFloatPosition === 'bottomRight') { const upDelta = offsetHeight + popupElement.offsetHeight + differ; pos = this._calPositionY(pos, upDelta, popupElement, point, offsetHeight); const leftDelta = popupElement.offsetWidth; pos = this._calPositionX(pos, leftDelta, popupElement, point, offsetWidth); } else if (this.jigsawFloatPosition === 'leftTop' || this.jigsawFloatPosition === 'rightTop' || this.jigsawFloatPosition === 'leftBottom' || this.jigsawFloatPosition === 'rightBottom') { const upDelta = popupElement.offsetHeight; pos = this._calPositionY(pos, upDelta, popupElement, point, offsetHeight); const leftDelta = popupElement.offsetWidth + offsetWidth + differ; pos = this._calPositionX(pos, leftDelta, popupElement, point, offsetWidth); } else if (this.jigsawFloatPosition === 'top' || this.jigsawFloatPosition === 'bottom') { pos.left = Math.max(8 /*安全边距*/, pos.left); const upDelta = offsetHeight + popupElement.offsetHeight + differ; pos = this._calPositionY(pos, upDelta, popupElement, point, offsetHeight); } else if (this.jigsawFloatPosition === 'left' || this.jigsawFloatPosition === 'right') { pos.top = Math.max(8 /*安全边距*/, pos.top); const leftDelta = popupElement.offsetWidth + offsetWidth + differ + 8 /*安全边距*/; pos = this._calPositionX(pos, leftDelta, popupElement, point, offsetWidth); } return pos; } private _calPositionX(pos, leftDelta, popupElement, point, offsetWidth) { if (document.body.clientWidth <= leftDelta) { // 可视区域比弹出的UI宽度还小就不要调整了 return pos; } const totalWidth = window.pageXOffset + document.body.clientWidth; // 宿主组件在可视范围外 const atLeft = this.jigsawFloatPosition == 'topLeft' || this.jigsawFloatPosition == 'bottomLeft' || this.jigsawFloatPosition == 'left'; const atRight = this.jigsawFloatPosition == 'topRight' || this.jigsawFloatPosition == 'bottomRight' || this.jigsawFloatPosition == 'right'; if (point.x < 0 && atLeft && leftDelta <= totalWidth - (offsetWidth + point.x)) { pos.left += offsetWidth; } else if (point.x + offsetWidth > totalWidth && atRight && point.x >= leftDelta) { pos.left -= offsetWidth; } if (pos.left < 0 && pos.left + leftDelta + popupElement.offsetWidth <= totalWidth) { // 左边位置不够且右边位置足够的时候才做调整 pos.left += leftDelta; } else if (pos.left + popupElement.offsetWidth > totalWidth && pos.left >= leftDelta) { // 右边位置不够且左边位置足够的时候才做调整 pos.left -= leftDelta; } return pos; } private _calPositionY(pos, upDelta, popupElement, point, offsetHeight) { if (document.body.clientHeight <= upDelta) { // 可视区域比弹出的UI高度还小就不要调整了 return pos; } const totalHeight = window.pageYOffset + document.body.clientHeight; // 宿主组件在可视范围外 const atTop = this.jigsawFloatPosition == 'leftTop' || this.jigsawFloatPosition == 'rightTop' || this.jigsawFloatPosition == 'top'; const atBottom = this.jigsawFloatPosition == 'leftBottom' || this.jigsawFloatPosition == 'rightBottom' || this.jigsawFloatPosition == 'bottom'; if (point.y < 0 && atTop && upDelta <= totalHeight - (offsetHeight + point.y)) { pos.top += offsetHeight; } else if (point.y + offsetHeight > totalHeight && atBottom && point.y >= upDelta) { pos.top -= offsetHeight; } if (pos.top < 0 && pos.top + upDelta + popupElement.offsetHeight <= totalHeight) { // 上位置不够且下方位置足够的时候才做调整 pos.top += upDelta; } else if (pos.top + popupElement.offsetHeight > totalHeight && pos.top >= upDelta) { // 下方位置不够且上方位置足够的时候才做调整 pos.top -= upDelta; } return pos; } /** * 立即关闭下拉视图 * @event 子类有用到 */ protected _closeFloat(event?: any): void { this._opened = false; this._disposePopup(); this._clearAllListeners(); } private _clearAllListeners() { if (this._removeWindowClickHandler) { this._removeWindowClickHandler(); this._removeWindowClickHandler = null; } if (this._removePopupClickHandler) { this._removePopupClickHandler(); this._removePopupClickHandler = null; } if (this._removeResizeHandler) { this._removeResizeHandler(); this._removeResizeHandler = null; } if (this._removeMouseOverHandler) { this._removeMouseOverHandler(); this._removeMouseOverHandler = null; } if (this._removeMouseOutHandler) { this._removeMouseOutHandler(); this._removeMouseOutHandler = null; } } } @Directive({ selector: '[jigsaw-float],[j-float],[jigsawFloat]', host: { '(mouseenter)': "_$openByHover($event)", '(mouseleave)': "_$closeByHover($event, 1)", '(click)': "_$onHostClick()" } }) export class JigsawFloat extends JigsawFloatBase implements OnDestroy { private _closeTrigger: 'click' | 'mouseleave' | 'none' = 'mouseleave'; /** * 打开下拉触发方式,默认值是'mouseleave' * $demo = float/trigger */ @Input() public get jigsawFloatCloseTrigger(): 'click' | 'mouseleave' | 'none' | DropDownTrigger { return this._closeTrigger; } public set jigsawFloatCloseTrigger(value: 'click' | 'mouseleave' | 'none' | DropDownTrigger) { // 从模板过来的值,不会受到类型的约束 switch (value as any) { case DropDownTrigger.none: case "none": this._closeTrigger = 'none'; break; case DropDownTrigger.click: case "click": this._closeTrigger = 'click'; break; case DropDownTrigger.mouseleave: case "mouseleave": this._closeTrigger = 'mouseleave'; break; } } private _openTrigger: 'click' | 'mouseenter' | 'none' = 'mouseenter'; /** * 打开下拉触发方式,默认值是'mouseenter' * $demo = float/trigger */ @Input() public get jigsawFloatOpenTrigger(): 'click' | 'mouseenter' | 'none' | DropDownTrigger { return this._openTrigger; } public set jigsawFloatOpenTrigger(value: 'click' | 'mouseenter' | 'none' | DropDownTrigger) { // 从模板过来的值,不会受到类型的约束 switch (value as any) { case DropDownTrigger.none: case "none": this._openTrigger = 'none'; break; case DropDownTrigger.click: case "click": this._openTrigger = 'click'; break; case DropDownTrigger.mouseenter: case "mouseenter": this._openTrigger = 'mouseenter'; break; } } @Input() public jigsawFloatArrowElement: any; @Input() public jigsawFloatInitData: any; @Input() public jigsawFloatOpen: boolean; @Input() public jigsawFloatOpenDelay: number = 100; @Input() public jigsawFloatCloseDelay: number = 400; /** * $demo = float/option */ @Input() public jigsawFloatOptions: PopupOptions; /** * 一共支持12个位置,其中第一个单词表示弹出视图在触发点的哪个位置,第二个单词控制弹出视图的哪个边缘与触发点对齐,比如'bottomLeft'表示在下面弹出来, * 并且视图左侧与触发点左侧对齐。注意,这个位置是应用给的理想位置,在弹出的时候,我们应该使用PopupService的位置修正函数来对理想位置坐修正, * 避免视图超时浏览器边界的情况 * $demo = float/position */ @Input() public jigsawFloatPosition: FloatPosition = 'bottomLeft'; /** * $demo = float/target */ @Input() public jigsawFloatTarget: Type<IPopupable> | TemplateRef<any>; @Output() public jigsawFloatOpenChange: EventEmitter<boolean> = new EventEmitter<boolean>(); @Output() public jigsawFloatAnswer = new EventEmitter<any>(); } @NgModule({ declarations: [JigsawFloat], exports: [JigsawFloat], providers: [PopupService] }) export class JigsawFloatModule { }
the_stack
* #%L * %% * Copyright (C) 2011 - 2017 BMW Car IT GmbH * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import PublicationManager from "../../../../../main/js/joynr/dispatching/subscription/PublicationManager"; import SubscriptionReply from "../../../../../main/js/joynr/dispatching/types/SubscriptionReply"; import SubscriptionRequest from "../../../../../main/js/joynr/dispatching/types/SubscriptionRequest"; import BroadcastSubscriptionRequest from "../../../../../main/js/joynr/dispatching/types/BroadcastSubscriptionRequest"; import MulticastSubscriptionRequest from "../../../../../main/js/joynr/dispatching/types/MulticastSubscriptionRequest"; import SubscriptionStop from "../../../../../main/js/joynr/dispatching/types/SubscriptionStop"; import * as ProviderAttribute from "../../../../../main/js/joynr/provider/ProviderAttribute"; import ProviderEvent from "../../../../../main/js/joynr/provider/ProviderEvent"; import PeriodicSubscriptionQos from "../../../../../main/js/joynr/proxy/PeriodicSubscriptionQos"; import SubscriptionQos from "../../../../../main/js/joynr/proxy/SubscriptionQos"; import OnChangeSubscriptionQos from "../../../../../main/js/joynr/proxy/OnChangeSubscriptionQos"; import OnChangeWithKeepAliveSubscriptionQos from "../../../../../main/js/joynr/proxy/OnChangeWithKeepAliveSubscriptionQos"; import ProviderQos from "../../../../../main/js/generated/joynr/types/ProviderQos"; import ProviderScope from "../../../../../main/js/generated/joynr/types/ProviderScope"; import * as SubscriptionPublication from "../../../../../main/js/joynr/dispatching/types/SubscriptionPublication"; import * as SubscriptionUtil from "../../../../../main/js/joynr/dispatching/subscription/util/SubscriptionUtil"; import SubscriptionException from "../../../../../main/js/joynr/exceptions/SubscriptionException"; import LongTimer from "../../../../../main/js/joynr/util/LongTimer"; import nanoid from "nanoid"; import testUtil = require("../../../testUtil"); describe("libjoynr-js.joynr.dispatching.subscription.PublicationManager", () => { let callbackDispatcher: any; let proxyId: any, providerId: any, publicationManager: PublicationManager, dispatcherSpy: any; let provider: any, asyncGetterCallDelay: number, fakeTime: any, intervalSubscriptionRequest: any; let onChangeSubscriptionRequest: any, mixedSubscriptionRequest: any, onChangeBroadcastSubscriptionRequest: any; let mixedSubscriptionRequestWithAsyncAttribute: any, testAttributeName: string; let asyncTestAttributeName: string, value: any, minIntervalMs: number, maxIntervalMs: number, maxNrOfTimes: any; let subscriptionLength: any, asyncTestAttribute: any, testAttribute: any, providerSettings: any; let testAttributeNotNotifiable: any, testAttributeNotNotifiableName: string; let testBroadcastName: string, testBroadcast: any; let testNonSelectiveBroadcastName: string, testNonSelectiveBroadcast: any; function createSubscriptionRequest( isAttribute: any, subscribeToName: string, periodMs: number | undefined, subscriptionLength: number, onChange?: boolean, minIntervalMs?: number ) { let qosSettings: any, request: any; const expiryDateMs = subscriptionLength === SubscriptionQos.NO_EXPIRY_DATE ? SubscriptionQos.NO_EXPIRY_DATE : Date.now() + subscriptionLength; if (onChange) { if (periodMs !== undefined) { qosSettings = new OnChangeWithKeepAliveSubscriptionQos({ minIntervalMs: minIntervalMs || 50, maxIntervalMs: periodMs, expiryDateMs, alertAfterIntervalMs: 0, publicationTtlMs: 1000 }); } else { qosSettings = new OnChangeSubscriptionQos({ minIntervalMs: minIntervalMs || 50, expiryDateMs, publicationTtlMs: 1000 }); } } else { qosSettings = new PeriodicSubscriptionQos({ periodMs, expiryDateMs, alertAfterIntervalMs: 0, publicationTtlMs: 1000 }); } if (isAttribute) { request = new SubscriptionRequest({ subscriptionId: `subscriptionId${nanoid()}`, subscribedToName: subscribeToName, qos: qosSettings }); } else { request = new BroadcastSubscriptionRequest({ subscriptionId: `subscriptionId${nanoid()}`, subscribedToName: subscribeToName, qos: qosSettings, filterParameters: {} as any }); } return request; } async function increaseFakeTime(timeMs: number): Promise<void> { fakeTime += timeMs; jest.advanceTimersByTime(timeMs); await testUtil.multipleSetImmediate(); } function stopSubscription(subscriptionInfo: any) { publicationManager.handleSubscriptionStop( new SubscriptionStop({ subscriptionId: subscriptionInfo.subscriptionId }) ); } function handleMulticastSubscriptionRequest() { const request = new MulticastSubscriptionRequest({ subscriptionId: `subscriptionId${nanoid()}`, multicastId: SubscriptionUtil.createMulticastId(providerId, testNonSelectiveBroadcastName, []), subscribedToName: testNonSelectiveBroadcastName, qos: new OnChangeSubscriptionQos() }); publicationManager.handleMulticastSubscriptionRequest(proxyId, providerId, request, callbackDispatcher); return request; } async function prepareTests() { callbackDispatcher = jest.fn(); proxyId = `proxy${nanoid()}`; providerId = `provider${nanoid()}`; fakeTime = 123456789; testAttributeName = "testAttribute"; testBroadcastName = "testBroadcast"; testNonSelectiveBroadcastName = "testNonSelectiveBroadcastName"; testAttributeNotNotifiableName = "testAttributeNotNotifiable"; asyncTestAttributeName = "asyncTestAttribute"; value = "the value"; minIntervalMs = 100; maxIntervalMs = 1000; maxNrOfTimes = 5; asyncGetterCallDelay = 10; subscriptionLength = (maxNrOfTimes + 1) * maxIntervalMs; dispatcherSpy = { sendPublication: jest.fn(), sendMulticastPublication: jest.fn() }; publicationManager = new PublicationManager(dispatcherSpy); provider = { registerOnChangeListener: jest.fn() }; providerSettings = { providerQos: new ProviderQos({ priority: 1234, scope: ProviderScope.GLOBAL } as any), dependencies: { publicationManager } }; testBroadcast = new ProviderEvent({ eventName: testBroadcastName, outputParameterProperties: [ { name: "param1", type: "String" } ], selective: true, filterSettings: { positionOfInterest: "reservedForTypeInfo" } }); testNonSelectiveBroadcast = new ProviderEvent({ eventName: testNonSelectiveBroadcastName, outputParameterProperties: [ { name: "param1", type: "String" } ], selective: false, filterSettings: undefined as any }); testAttribute = new ProviderAttribute.ProviderReadWriteNotifyAttribute( provider, providerSettings, testAttributeName, "Boolean" ); asyncTestAttribute = new ProviderAttribute.ProviderReadWriteNotifyAttribute( provider, providerSettings, asyncTestAttributeName, "Boolean" ); testAttributeNotNotifiable = new ProviderAttribute.ProviderReadWriteAttribute( provider, providerSettings, testAttributeNotNotifiableName, "Boolean" ); provider[testAttributeName] = testAttribute; provider[testBroadcastName] = testBroadcast; provider[testNonSelectiveBroadcastName] = testNonSelectiveBroadcast; provider[testAttributeNotNotifiableName] = testAttributeNotNotifiable; jest.spyOn(testAttribute, "get").mockImplementation(() => { return Promise.resolve("attributeValue"); }); jest.spyOn(testAttributeNotNotifiable, "get").mockImplementation(() => { return Promise.resolve("attributeValue"); }); provider[asyncTestAttributeName] = asyncTestAttribute; jest.spyOn(asyncTestAttribute, "get").mockImplementation(() => { /* eslint-disable no-unused-vars*/ return new Promise(resolve => { LongTimer.setTimeout(() => { resolve("asyncAttributeValue"); }, asyncGetterCallDelay); }); /* eslint-enable no-unused-vars*/ }); jest.useFakeTimers(); jest.spyOn(Date, "now").mockImplementation(() => { return fakeTime; }); intervalSubscriptionRequest = createSubscriptionRequest( true, testAttributeName, maxIntervalMs, subscriptionLength ); onChangeSubscriptionRequest = createSubscriptionRequest( true, testAttributeName, undefined, subscriptionLength, true ); mixedSubscriptionRequest = createSubscriptionRequest( true, testAttributeName, maxIntervalMs, subscriptionLength, true, minIntervalMs ); onChangeBroadcastSubscriptionRequest = createSubscriptionRequest( false, testBroadcastName, undefined, subscriptionLength, true ); mixedSubscriptionRequestWithAsyncAttribute = createSubscriptionRequest( true, asyncTestAttributeName, maxIntervalMs, subscriptionLength, true, minIntervalMs ); expect(publicationManager.hasSubscriptions()).toBe(false); } beforeEach(async () => { await prepareTests(); }); afterEach(() => { jest.useRealTimers(); }); it("is instantiable", () => { expect(publicationManager).toBeDefined(); expect(() => { // eslint-disable-next-line no-new new PublicationManager(dispatcherSpy); }).not.toThrow(); }); it("calls dispatcher with correct arguments", async () => { publicationManager.addPublicationProvider(providerId, provider); publicationManager.handleSubscriptionRequest( proxyId, providerId, onChangeSubscriptionRequest, callbackDispatcher ); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeTruthy(); await increaseFakeTime(1); // reset first publication testAttribute.get.mockClear(); dispatcherSpy.sendPublication.mockClear(); await increaseFakeTime(50); testAttribute.valueChanged(value); await testUtil.multipleSetImmediate(); expect(dispatcherSpy.sendPublication).toHaveBeenCalledWith( { from: providerId, to: proxyId, expiryDate: Date.now() + onChangeSubscriptionRequest.qos.publicationTtlMs }, SubscriptionPublication.create({ response: [value], subscriptionId: onChangeSubscriptionRequest.subscriptionId }) ); stopSubscription(onChangeSubscriptionRequest); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeFalsy(); }); it("publishes first value once immediately after subscription", async () => { publicationManager.addPublicationProvider(providerId, provider); expect(testAttribute.get).not.toHaveBeenCalled(); expect(dispatcherSpy.sendPublication).not.toHaveBeenCalled(); publicationManager.handleSubscriptionRequest( proxyId, providerId, onChangeSubscriptionRequest, callbackDispatcher ); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeTruthy(); await increaseFakeTime(1); expect(testAttribute.get.mock.calls.length).toEqual(1); expect(dispatcherSpy.sendPublication.mock.calls.length).toEqual(1); // cleanup stopSubscription(onChangeSubscriptionRequest); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeFalsy(); }); it("creates a working interval subscription", async () => { publicationManager.addPublicationProvider(providerId, provider); publicationManager.handleSubscriptionRequest( proxyId, providerId, intervalSubscriptionRequest, callbackDispatcher ); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeTruthy(); await increaseFakeTime(1); testAttribute.get.mockClear(); dispatcherSpy.sendPublication.mockClear(); for (let times = 1; times < maxNrOfTimes + 1; ++times) { // step the clock forward to 1 ms before the interval await increaseFakeTime(maxIntervalMs - 1); // 1 ms later the poll should happen await increaseFakeTime(1); expect(testAttribute.get.mock.calls.length).toEqual(times); expect(dispatcherSpy.sendPublication.mock.calls.length).toEqual(times); expect(dispatcherSpy.sendPublication.mock.calls.length).toEqual(times); } // cleanup stopSubscription(intervalSubscriptionRequest); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeFalsy(); }); it("does not publish when interval subscription has an endDate in the past", async () => { intervalSubscriptionRequest.qos.expiryDateMs = Date.now() - 1; publicationManager.addPublicationProvider(providerId, provider); publicationManager.handleSubscriptionRequest( proxyId, providerId, intervalSubscriptionRequest, callbackDispatcher ); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeFalsy(); // reset first publication testAttribute.get.mockClear(); dispatcherSpy.sendPublication.mockClear(); expect(testAttribute.get).not.toHaveBeenCalled(); expect(dispatcherSpy.sendPublication).not.toHaveBeenCalled(); await increaseFakeTime(subscriptionLength); expect(testAttribute.get).not.toHaveBeenCalled(); expect(dispatcherSpy.sendPublication).not.toHaveBeenCalled(); // cleanup stopSubscription(intervalSubscriptionRequest); }); it("removes an interval attribute subscription after endDate", async () => { publicationManager.addPublicationProvider(providerId, provider); publicationManager.handleSubscriptionRequest( proxyId, providerId, intervalSubscriptionRequest, callbackDispatcher ); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeTruthy(); await increaseFakeTime(1); // reset first publication testAttribute.get.mockClear(); dispatcherSpy.sendPublication.mockClear(); //increaseFakeTime(subscriptionLength); // // Do not increase by full subscriptionLength, because then // both the publication end timer and the timer for the current // interval period will become runnable at the same time. // Jasmine seems to call the end timer first (which should // cancel the other one), however the interval period timer // will still be run. Unfortunately it creates a new interval // period timer, which will run another publication after the // subscription has already expired which lets the test fail. // The following shorter increase of time will allow the // interval period timer to run first. Also note, that despite // the large time warp, only one publication will be // visible since Joynr has implemented interval timers by // a simple timer that retriggers itself after each interval // instead of using the Javascript setInterval(). await increaseFakeTime(subscriptionLength - 2); // The following increase of time will only trigger the end timer // while the interval period timer remains waiting. So it // can be cleared ok. await increaseFakeTime(2); expect(testAttribute.get).toHaveBeenCalled(); expect(dispatcherSpy.sendPublication).toHaveBeenCalled(); // after another interval, the methods should not have been called again // (ie subscription terminated) testAttribute.get.mockClear(); dispatcherSpy.sendPublication.mockClear(); await increaseFakeTime(maxIntervalMs); expect(testAttribute.get).not.toHaveBeenCalled(); expect(dispatcherSpy.sendPublication).not.toHaveBeenCalled(); stopSubscription(intervalSubscriptionRequest); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeFalsy(); }); it("removes an interval attribute subscription after subscription stop", async () => { publicationManager.addPublicationProvider(providerId, provider); publicationManager.handleSubscriptionRequest( proxyId, providerId, intervalSubscriptionRequest, callbackDispatcher ); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeTruthy(); // reset first publication testAttribute.get.mockClear(); dispatcherSpy.sendPublication.mockClear(); await increaseFakeTime(maxIntervalMs + asyncGetterCallDelay); expect(testAttribute.get).toHaveBeenCalled(); expect(dispatcherSpy.sendPublication).toHaveBeenCalled(); // after subscription stop, the methods should not have been called // again (ie subscription terminated) publicationManager.handleSubscriptionStop( new SubscriptionStop({ subscriptionId: intervalSubscriptionRequest.subscriptionId }) ); testAttribute.get.mockClear(); dispatcherSpy.sendPublication.mockClear(); await increaseFakeTime(maxIntervalMs + 1); expect(testAttribute.get).not.toHaveBeenCalled(); expect(dispatcherSpy.sendPublication).not.toHaveBeenCalled(); }); it("creates a working onChange subscription", () => { publicationManager.addPublicationProvider(providerId, provider); publicationManager.handleSubscriptionRequest( proxyId, providerId, onChangeSubscriptionRequest, callbackDispatcher ); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeTruthy(); // reset first publication testAttribute.get.mockClear(); dispatcherSpy.sendPublication.mockClear(); for (let times = 0; times < maxNrOfTimes; times++) { increaseFakeTime(50); testAttribute.valueChanged(value + times); expect(dispatcherSpy.sendPublication.mock.calls.length).toEqual(times + 1); } // cleanup stopSubscription(onChangeSubscriptionRequest); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeFalsy(); }); it("does not publish when an onChange subscription has an endDate in the past", async () => { onChangeSubscriptionRequest.qos.expiryDateMs = Date.now() - 1; publicationManager.addPublicationProvider(providerId, provider); publicationManager.handleSubscriptionRequest( proxyId, providerId, onChangeSubscriptionRequest, callbackDispatcher ); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeFalsy(); // reset first publication testAttribute.get.mockClear(); dispatcherSpy.sendPublication.mockClear(); testAttribute.valueChanged(`${value}someChange`); await increaseFakeTime(asyncGetterCallDelay); expect(dispatcherSpy.sendPublication).not.toHaveBeenCalled(); // cleanup stopSubscription(onChangeSubscriptionRequest); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeFalsy(); }); it("removes an onChange attribute subscription after endDate", async () => { publicationManager.addPublicationProvider(providerId, provider); publicationManager.handleSubscriptionRequest( proxyId, providerId, onChangeSubscriptionRequest, callbackDispatcher ); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeTruthy(); await increaseFakeTime(1); // reset first publication testAttribute.get.mockClear(); dispatcherSpy.sendPublication.mockClear(); await increaseFakeTime(50); testAttribute.valueChanged(value); expect(dispatcherSpy.sendPublication).toHaveBeenCalled(); // after another attribute change, the methods should not have been // called again (ie subscription terminated) await increaseFakeTime(subscriptionLength); dispatcherSpy.sendPublication.mockClear(); testAttribute.valueChanged(value); expect(dispatcherSpy.sendPublication).not.toHaveBeenCalled(); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeFalsy(); }); it("removes an onChange attribute subscription after subscription stop", async () => { publicationManager.addPublicationProvider(providerId, provider); publicationManager.handleSubscriptionRequest( proxyId, providerId, onChangeSubscriptionRequest, callbackDispatcher ); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeTruthy(); await increaseFakeTime(1); // reset first publication testAttribute.get.mockClear(); dispatcherSpy.sendPublication.mockClear(); await increaseFakeTime(50); testAttribute.valueChanged(value); expect(dispatcherSpy.sendPublication).toHaveBeenCalled(); // after subscription stop, the methods should not have been called // again (ie subscription terminated) publicationManager.handleSubscriptionStop( new SubscriptionStop({ subscriptionId: onChangeSubscriptionRequest.subscriptionId }) ); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeFalsy(); dispatcherSpy.sendPublication.mockClear(); testAttribute.valueChanged(value); await increaseFakeTime(1); expect(dispatcherSpy.sendPublication).not.toHaveBeenCalled(); }); it("creates a mixed subscription and does not send two publications within minintervalMs in case async getter calls and valueChanged occur at the same time", async () => { publicationManager.addPublicationProvider(providerId, provider); publicationManager.handleSubscriptionRequest( proxyId, providerId, mixedSubscriptionRequestWithAsyncAttribute, callbackDispatcher ); expect( publicationManager.hasSubscriptionsForProviderAttribute(providerId, asyncTestAttributeName) ).toBeTruthy(); // wait until the first publication occurs await increaseFakeTime(asyncGetterCallDelay); // reset first publication asyncTestAttribute.get.mockClear(); dispatcherSpy.sendPublication.mockClear(); // let the minIntervalMs exceed, so that new value changes // immediately lead to publications increaseFakeTime(minIntervalMs); expect(asyncTestAttribute.get).not.toHaveBeenCalled(); expect(dispatcherSpy.sendPublication).not.toHaveBeenCalled(); asyncTestAttribute.valueChanged(value); increaseFakeTime(5); // this should cause an async timer, which sends a publication // after minIntervalMs-5 asyncTestAttribute.valueChanged(value); // the getter has not been invoked so far expect(asyncTestAttribute.get).not.toHaveBeenCalled(); await testUtil.multipleSetImmediate(); expect(dispatcherSpy.sendPublication.mock.calls.length).toEqual(1); // now, lets increas the time until mininterval await increaseFakeTime(minIntervalMs - 5); // now, the async timer has exceeded, and the PublicationManager // invokes the get expect(asyncTestAttribute.get.mock.calls.length).toEqual(1); // now change the attribute value asyncTestAttribute.valueChanged(value); await testUtil.multipleSetImmediate(); expect(dispatcherSpy.sendPublication.mock.calls.length).toEqual(2); // lets exceed the async getter delay, causing the async getter // to resolve the promise object increaseFakeTime(asyncGetterCallDelay); // now change the attribute value asyncTestAttribute.valueChanged(value); // this shall not result in a new sendPublication, as // asyncGetterCallDelay<minIntervalMs and the time // delay between two publications must be at least minIntervalMs expect(dispatcherSpy.sendPublication.mock.calls.length).toEqual(2); await increaseFakeTime(minIntervalMs - asyncGetterCallDelay); expect(asyncTestAttribute.get.mock.calls.length).toEqual(2); await increaseFakeTime(asyncGetterCallDelay); expect(asyncTestAttribute.get.mock.calls.length).toEqual(2); expect(dispatcherSpy.sendPublication.mock.calls.length).toEqual(3); stopSubscription(mixedSubscriptionRequestWithAsyncAttribute); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, asyncTestAttributeName)).toBeFalsy(); }); it("creates a mixed subscription that publishes every maxIntervalMs", async () => { publicationManager.addPublicationProvider(providerId, provider); publicationManager.handleSubscriptionRequest(proxyId, providerId, mixedSubscriptionRequest, callbackDispatcher); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeTruthy(); await increaseFakeTime(1); // reset first publication testAttribute.get.mockClear(); dispatcherSpy.sendPublication.mockClear(); expect(testAttribute.get).not.toHaveBeenCalled(); expect(dispatcherSpy.sendPublication).not.toHaveBeenCalled(); for (let times = 0; times < maxNrOfTimes; ++times) { // step the clock forward to 1 ms before the interval await increaseFakeTime(maxIntervalMs - 1); // 1 ms later the poll should happen await increaseFakeTime(1); expect(testAttribute.get.mock.calls.length).toEqual(times + 1); expect(dispatcherSpy.sendPublication.mock.calls.length).toEqual(times + 1); } // cleanup stopSubscription(mixedSubscriptionRequest); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeFalsy(); }); it("creates a mixed subscription that publishes valueChanges that occur each minIntervalMs", async () => { publicationManager.addPublicationProvider(providerId, provider); publicationManager.handleSubscriptionRequest(proxyId, providerId, mixedSubscriptionRequest, callbackDispatcher); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeTruthy(); await increaseFakeTime(1); testAttribute.get.mockClear(); dispatcherSpy.sendPublication.mockClear(); for (let times = 0; times < maxNrOfTimes; times++) { await increaseFakeTime(mixedSubscriptionRequest.qos.minIntervalMs); testAttribute.valueChanged(value + times); await testUtil.multipleSetImmediate(); expect(testAttribute.get).not.toHaveBeenCalled(); expect(dispatcherSpy.sendPublication.mock.calls.length).toEqual(times + 1); } // cleanup stopSubscription(mixedSubscriptionRequest); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeFalsy(); }); it("creates a mixed subscription that publishes valueChanges that occur each maxIntervalMs-1", async () => { dispatcherSpy.sendPublication.mockClear(); publicationManager.addPublicationProvider(providerId, provider); publicationManager.handleSubscriptionRequest(proxyId, providerId, mixedSubscriptionRequest, callbackDispatcher); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeTruthy(); await increaseFakeTime(1); testAttribute.get.mockClear(); dispatcherSpy.sendPublication.mockClear(); for (let times = 0; times < maxNrOfTimes; times++) { await increaseFakeTime(mixedSubscriptionRequest.qos.maxIntervalMs - 2); testAttribute.valueChanged(value + times); await increaseFakeTime(1); expect(testAttribute.get).not.toHaveBeenCalled(); expect(dispatcherSpy.sendPublication.mock.calls.length).toEqual(times + 1); } // cleanup stopSubscription(mixedSubscriptionRequest); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeFalsy(); }); it("creates a mixed subscription that publishes many valueChanges within minIntervalMs only once", async () => { publicationManager.addPublicationProvider(providerId, provider); publicationManager.handleSubscriptionRequest(proxyId, providerId, mixedSubscriptionRequest, callbackDispatcher); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeTruthy(); await increaseFakeTime(1); // reset first publication testAttribute.get.mockClear(); dispatcherSpy.sendPublication.mockClear(); const shortInterval = Math.round((mixedSubscriptionRequest.qos.minIntervalMs - 2) / maxNrOfTimes); for (let times = 0; times < maxNrOfTimes; times++) { expect(testAttribute.get).not.toHaveBeenCalled(); expect(dispatcherSpy.sendPublication).not.toHaveBeenCalled(); await increaseFakeTime(shortInterval); testAttribute.valueChanged(value + times); } // after minIntervalMs the publication works again await increaseFakeTime(mixedSubscriptionRequest.qos.minIntervalMs - shortInterval * maxNrOfTimes); testAttribute.valueChanged(value); expect(testAttribute.get.mock.calls.length).toEqual(1); expect(dispatcherSpy.sendPublication.mock.calls.length).toEqual(1); // cleanup stopSubscription(mixedSubscriptionRequest); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeFalsy(); }); it("creates a periodic subscription without expiryDate and expects periodic publications", async () => { const periodMs = 400; const n = 10; const subscriptionRequestWithoutExpiryDate = createSubscriptionRequest( true, testAttributeName, periodMs, 0, false, minIntervalMs ); dispatcherSpy.sendPublication.mockClear(); publicationManager.addPublicationProvider(providerId, provider); publicationManager.handleSubscriptionRequest( proxyId, providerId, subscriptionRequestWithoutExpiryDate, callbackDispatcher ); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeTruthy(); await increaseFakeTime(1); expect(dispatcherSpy.sendPublication.mock.calls.length).toEqual(1); dispatcherSpy.sendPublication.mockClear(); for (let i = 0; i < n; i++) { await increaseFakeTime(periodMs); expect(dispatcherSpy.sendPublication.mock.calls.length).toEqual(1 + i); } // cleanup stopSubscription(subscriptionRequestWithoutExpiryDate); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeFalsy(); }); it("creates a mixed subscription that publishes correctly with all cases mixed", async () => { let i: any; publicationManager.addPublicationProvider(providerId, provider); publicationManager.handleSubscriptionRequest(proxyId, providerId, mixedSubscriptionRequest, callbackDispatcher); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeTruthy(); await increaseFakeTime(1); // reset first publication testAttribute.get.mockClear(); dispatcherSpy.sendPublication.mockClear(); // at time 0, a value change is not reported because value was // already published initially while // handling the subscription request testAttribute.valueChanged(value); expect(testAttribute.get).not.toHaveBeenCalled(); expect(dispatcherSpy.sendPublication).not.toHaveBeenCalled(); // minIntervalMs and a value change the value should be reported await increaseFakeTime(mixedSubscriptionRequest.qos.minIntervalMs); // due to minIntervalMs exceeded + valueChanged has been occured // within the minIntervalMs, the // PublicationManager // send the current attribute value to the subscriptions expect(testAttribute.get.mock.calls.length).toEqual(1); expect(dispatcherSpy.sendPublication.mock.calls.length).toEqual(1); testAttribute.get.mockClear(); dispatcherSpy.sendPublication.mockClear(); // minIntervalMs and no publication shall occur await increaseFakeTime(mixedSubscriptionRequest.qos.minIntervalMs); expect(testAttribute.get).not.toHaveBeenCalled(); expect(dispatcherSpy.sendPublication).not.toHaveBeenCalled(); // change value, and immediate publication shall occur testAttribute.valueChanged(value); expect(testAttribute.get).not.toHaveBeenCalled(); expect(dispatcherSpy.sendPublication.mock.calls.length).toEqual(1); // at time 1:maxNrOfTimes, a value change is reported => NO // publication is sent for (i = 0; i < maxNrOfTimes; ++i) { dispatcherSpy.sendPublication.mockClear(); await increaseFakeTime(1); testAttribute.valueChanged(value); expect(testAttribute.get).not.toHaveBeenCalled(); expect(dispatcherSpy.sendPublication).not.toHaveBeenCalled(); } // at time mixedSubscriptionRequest.qos.minIntervalMs the last // value of the test attribute is sent // to the subscribers as the publication timeout occurs dispatcherSpy.sendPublication.mockClear(); await increaseFakeTime(mixedSubscriptionRequest.qos.minIntervalMs - maxNrOfTimes); expect(testAttribute.get.mock.calls.length).toEqual(1); expect(dispatcherSpy.sendPublication.mock.calls.length).toEqual(1); // value change after mixedSubscriptionRequest.qos.maxInterval - 2=> publication sent dispatcherSpy.sendPublication.mockClear(); testAttribute.get.mockClear(); await increaseFakeTime(mixedSubscriptionRequest.qos.maxIntervalMs - 1); testAttribute.valueChanged(value); expect(testAttribute.get).not.toHaveBeenCalled(); expect(dispatcherSpy.sendPublication.mock.calls.length).toEqual(1); // after mixedSubscriptionRequest.qos.maxIntervalMs => interval // publication is sent dispatcherSpy.sendPublication.mockClear(); await increaseFakeTime(mixedSubscriptionRequest.qos.maxIntervalMs); expect(testAttribute.get.mock.calls.length).toEqual(1); expect(dispatcherSpy.sendPublication.mock.calls.length).toEqual(1); // after another mixedSubscriptionRequest.qos.maxIntervalMs => // interval publication is sent testAttribute.get.mockClear(); dispatcherSpy.sendPublication.mockClear(); await increaseFakeTime(mixedSubscriptionRequest.qos.maxIntervalMs); expect(testAttribute.get.mock.calls.length).toEqual(1); expect(dispatcherSpy.sendPublication.mock.calls.length).toEqual(1); // after subscription stop => NO publications are sent any more stopSubscription(mixedSubscriptionRequest); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeFalsy(); testAttribute.get.mockClear(); dispatcherSpy.sendPublication.mockClear(); await increaseFakeTime(mixedSubscriptionRequest.qos.minIntervalMs); testAttribute.valueChanged(value); expect(testAttribute.get).not.toHaveBeenCalled(); }); it("does not publish when mixed subscription has an endDate in the past", async () => { mixedSubscriptionRequest.qos.expiryDateMs = Date.now() - 1; publicationManager.addPublicationProvider(providerId, provider); publicationManager.handleSubscriptionRequest(proxyId, providerId, mixedSubscriptionRequest, callbackDispatcher); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeFalsy(); // reset first publication testAttribute.get.mockClear(); dispatcherSpy.sendPublication.mockClear(); testAttribute.valueChanged(value); await increaseFakeTime(subscriptionLength); expect(testAttribute.get).not.toHaveBeenCalled(); expect(dispatcherSpy.sendPublication).not.toHaveBeenCalled(); // cleanup stopSubscription(mixedSubscriptionRequest); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeFalsy(); }); it("removes a mixed attribute subscription after endDate", async () => { publicationManager.addPublicationProvider(providerId, provider); publicationManager.handleSubscriptionRequest(proxyId, providerId, mixedSubscriptionRequest, callbackDispatcher); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeTruthy(); await increaseFakeTime(1); // reset first publication testAttribute.get.mockClear(); dispatcherSpy.sendPublication.mockClear(); await increaseFakeTime(subscriptionLength); testAttribute.get.mockClear(); dispatcherSpy.sendPublication.mockClear(); expect(testAttribute.get).not.toHaveBeenCalled(); expect(dispatcherSpy.sendPublication).not.toHaveBeenCalled(); testAttribute.valueChanged(value); expect(testAttribute.get).not.toHaveBeenCalled(); expect(dispatcherSpy.sendPublication).not.toHaveBeenCalled(); stopSubscription(mixedSubscriptionRequest); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeFalsy(); }); it("removes a mixed broadcast subscription after subscription stop", async () => { const broadcastOutputParameters = testBroadcast.createBroadcastOutputParameters(); broadcastOutputParameters.setParam1("param1"); publicationManager.addPublicationProvider(providerId, provider); publicationManager.handleBroadcastSubscriptionRequest( proxyId, providerId, onChangeBroadcastSubscriptionRequest, callbackDispatcher ); expect(publicationManager.hasSubscriptionsForProviderEvent(providerId, testBroadcastName)).toBeTruthy(); await increaseFakeTime(1); testBroadcast.fire(broadcastOutputParameters); await increaseFakeTime(maxIntervalMs); // increase interval // reset first publication dispatcherSpy.sendPublication.mockClear(); // after subscription stop, the methods should not have been called // again (ie subscription // terminated) publicationManager.handleSubscriptionStop( new SubscriptionStop({ subscriptionId: onChangeBroadcastSubscriptionRequest.subscriptionId }) ); expect(publicationManager.hasSubscriptionsForProviderEvent(providerId, testBroadcastName)).toBeFalsy(); await increaseFakeTime(maxIntervalMs); // increase interval testBroadcast.fire(broadcastOutputParameters); await increaseFakeTime(maxIntervalMs); // increase interval await testUtil.multipleSetImmediate(); expect(dispatcherSpy.sendPublication).not.toHaveBeenCalled(); }); it("removes publication provider", async () => { jest.spyOn(testAttribute, "registerObserver"); jest.spyOn(testAttribute, "unregisterObserver"); publicationManager.addPublicationProvider(providerId, provider); expect(testAttribute.registerObserver).toHaveBeenCalled(); jest.spyOn(publicationManager, "handleSubscriptionStop"); expect(testAttribute.get).not.toHaveBeenCalled(); expect(dispatcherSpy.sendPublication).not.toHaveBeenCalled(); publicationManager.handleSubscriptionRequest( proxyId, providerId, intervalSubscriptionRequest, callbackDispatcher ); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeTruthy(); //increase the fake time to ensure proper async processing of the subscription request await increaseFakeTime(1); expect(testAttribute.get.mock.calls.length).toEqual(1); expect(dispatcherSpy.sendPublication.mock.calls.length).toEqual(1); expect(testAttribute.unregisterObserver).not.toHaveBeenCalled(); expect(publicationManager.handleSubscriptionStop).not.toHaveBeenCalled(); publicationManager.removePublicationProvider(providerId, provider); expect(testAttribute.unregisterObserver).toHaveBeenCalled(); expect(publicationManager.handleSubscriptionStop).toHaveBeenCalledWith( new SubscriptionStop({ subscriptionId: intervalSubscriptionRequest.subscriptionId }) ); // cleanup stopSubscription(intervalSubscriptionRequest); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeFalsy(); }); it("behaves correctly when resubscribing to a publication", async () => { jest.spyOn(testAttribute, "registerObserver"); jest.spyOn(testAttribute, "unregisterObserver"); publicationManager.addPublicationProvider(providerId, provider); expect(testAttribute.registerObserver).toHaveBeenCalled(); jest.spyOn(publicationManager, "handleSubscriptionStop"); publicationManager.handleSubscriptionRequest( proxyId, providerId, intervalSubscriptionRequest, callbackDispatcher ); await testUtil.multipleSetImmediate(); expect(testAttribute.get.mock.calls.length).toEqual(1); expect(dispatcherSpy.sendPublication.mock.calls.length).toEqual(1); expect(testAttribute.unregisterObserver).not.toHaveBeenCalled(); expect(publicationManager.handleSubscriptionStop).not.toHaveBeenCalled(); publicationManager.removePublicationProvider(providerId, provider); expect(testAttribute.unregisterObserver).toHaveBeenCalled(); expect(publicationManager.handleSubscriptionStop).toHaveBeenCalledWith( new SubscriptionStop({ subscriptionId: intervalSubscriptionRequest.subscriptionId }) ); expect(publicationManager.hasSubscriptions()).toBeFalsy(); callbackDispatcher.mockClear(); await increaseFakeTime(1000); publicationManager.addPublicationProvider(providerId, provider); publicationManager.handleSubscriptionRequest( proxyId, providerId, intervalSubscriptionRequest, callbackDispatcher ); expect(callbackDispatcher.mock.calls.length).toEqual(1); // cleanup stopSubscription(intervalSubscriptionRequest); expect(publicationManager.hasSubscriptionsForProviderAttribute(providerId, testAttributeName)).toBeFalsy(); }); it("rejects attribute subscription if expiryDateMs lies in the past", async () => { const request = new SubscriptionRequest({ subscriptionId: `subscriptionId${nanoid()}`, subscribedToName: testAttributeName, qos: new OnChangeSubscriptionQos({ expiryDateMs: Date.now() - 10000 }) }); publicationManager.addPublicationProvider(providerId, provider); publicationManager.handleSubscriptionRequest(proxyId, providerId, request, callbackDispatcher); await testUtil.multipleSetImmediate(); expect(callbackDispatcher).toHaveBeenCalled(); const error = callbackDispatcher.mock.calls.slice(-1)[0][1].error; expect(error).toBeDefined(); expect(error).toBeInstanceOf(SubscriptionException); expect(error.subscriptionId).toBeDefined(); expect(error.subscriptionId).toEqual(callbackDispatcher.mock.calls.slice(-1)[0][1].subscriptionId); expect(error.detailMessage).toMatch(/lies in the past/); }); it("rejects attribute subscription if attribute does not exist", async () => { const request = new SubscriptionRequest({ subscriptionId: `subscriptionId${nanoid()}`, subscribedToName: "nonExistingAttribute", qos: new OnChangeSubscriptionQos() }); publicationManager.addPublicationProvider(providerId, provider); publicationManager.handleSubscriptionRequest(proxyId, providerId, request, callbackDispatcher); await testUtil.multipleSetImmediate(); expect(callbackDispatcher).toHaveBeenCalled(); const error = callbackDispatcher.mock.calls.slice(-1)[0][1].error; expect(error).toBeDefined(); expect(error).toBeInstanceOf(SubscriptionException); expect(error.subscriptionId).toBeDefined(); expect(error.subscriptionId).toEqual(callbackDispatcher.mock.calls.slice(-1)[0][1].subscriptionId); expect(error.detailMessage).toMatch(/misses attribute/); }); it("rejects attribute subscription if attribute is not notifiable", async () => { const request = new SubscriptionRequest({ subscriptionId: `subscriptionId${nanoid()}`, subscribedToName: testAttributeNotNotifiableName, qos: new OnChangeSubscriptionQos() }); publicationManager.addPublicationProvider(providerId, provider); publicationManager.handleSubscriptionRequest(proxyId, providerId, request, callbackDispatcher); await testUtil.multipleSetImmediate(); expect(callbackDispatcher).toHaveBeenCalled(); const error = callbackDispatcher.mock.calls.slice(-1)[0][1].error; expect(error).toBeDefined(); expect(error).toBeInstanceOf(SubscriptionException); expect(error.subscriptionId).toBeDefined(); expect(error.subscriptionId).toEqual(callbackDispatcher.mock.calls.slice(-1)[0][1].subscriptionId); expect(error.detailMessage).toMatch(/is not notifiable/); await increaseFakeTime(1); }); it("rejects attribute subscription if periodMs is too small", async () => { const qosSettings = new PeriodicSubscriptionQos({ expiryDateMs: 0, alertAfterIntervalMs: 0, publicationTtlMs: 1000 }); // forcibly fake it! The constructor throws, if using this directly qosSettings.periodMs = PeriodicSubscriptionQos.MIN_PERIOD_MS - 1; const request = new SubscriptionRequest({ subscriptionId: `subscriptionId${nanoid()}`, subscribedToName: testAttributeName, qos: qosSettings }); publicationManager.addPublicationProvider(providerId, provider); publicationManager.handleSubscriptionRequest(proxyId, providerId, request, callbackDispatcher); await testUtil.multipleSetImmediate(); expect(callbackDispatcher).toHaveBeenCalled(); const error = callbackDispatcher.mock.calls.slice(-1)[0][1].error; expect(error).toBeDefined(); expect(error).toBeInstanceOf(SubscriptionException); expect(error.subscriptionId).toBeDefined(); expect(error.subscriptionId).toEqual(callbackDispatcher.mock.calls.slice(-1)[0][1].subscriptionId); expect(error.detailMessage).toMatch(/is smaller than PeriodicSubscriptionQos/); }); it("rejects broadcast subscription if expiryDateMs lies in the past", async () => { const request = new BroadcastSubscriptionRequest({ subscriptionId: `subscriptionId${nanoid()}`, subscribedToName: testBroadcastName, qos: new OnChangeSubscriptionQos({ expiryDateMs: Date.now() - 10000 }), filterParameters: {} as any }); publicationManager.addPublicationProvider(providerId, provider); publicationManager.handleBroadcastSubscriptionRequest(proxyId, providerId, request, callbackDispatcher); await testUtil.multipleSetImmediate(); expect(callbackDispatcher).toHaveBeenCalled(); const error = callbackDispatcher.mock.calls.slice(-1)[0][1].error; expect(error).toBeDefined(); expect(error).toBeInstanceOf(SubscriptionException); expect(error.subscriptionId).toBeDefined(); expect(error.subscriptionId).toEqual(callbackDispatcher.mock.calls.slice(-1)[0][1].subscriptionId); expect(error.detailMessage).toMatch(/lies in the past/); }); it("rejects broadcast subscription if filter parameters are wrong", async () => { const request = new BroadcastSubscriptionRequest({ subscriptionId: `subscriptionId${nanoid()}`, subscribedToName: testBroadcastName, qos: new OnChangeSubscriptionQos(), filterParameters: { filterParameters: { corruptFilterParameter: "value" } } as any }); publicationManager.addPublicationProvider(providerId, provider); publicationManager.handleBroadcastSubscriptionRequest(proxyId, providerId, request, callbackDispatcher); await testUtil.multipleSetImmediate(); expect(callbackDispatcher).toHaveBeenCalled(); const error = callbackDispatcher.mock.calls.slice(-1)[0][1].error; expect(error).toBeDefined(); expect(error).toBeInstanceOf(SubscriptionException); expect(error.subscriptionId).toBeDefined(); expect(error.subscriptionId).toEqual(callbackDispatcher.mock.calls.slice(-1)[0][1].subscriptionId); expect(error.detailMessage).toMatch(/Filter parameter positionOfInterest for broadcast/); }); it("registers multicast subscription", async () => { expect(publicationManager.hasMulticastSubscriptions()).toBe(false); publicationManager.addPublicationProvider(providerId, provider); const request = handleMulticastSubscriptionRequest(); await testUtil.multipleSetImmediate(); expect(callbackDispatcher).toHaveBeenCalled(); const response = callbackDispatcher.mock.calls.slice(-1)[0][1]; expect(response.error).toBeUndefined(); expect(response.subscriptionId).toEqual(request.subscriptionId); expect(publicationManager.hasMulticastSubscriptions()).toBe(true); }); it("registers and unregisters multicast subscription", () => { expect(publicationManager.hasMulticastSubscriptions()).toBe(false); publicationManager.addPublicationProvider(providerId, provider); const request = handleMulticastSubscriptionRequest(); expect(publicationManager.hasMulticastSubscriptions()).toBe(true); expect(publicationManager.hasSubscriptions()).toBe(true); publicationManager.handleSubscriptionStop({ subscriptionId: request.subscriptionId } as any); expect(publicationManager.hasMulticastSubscriptions()).toBe(false); expect(publicationManager.hasSubscriptions()).toBe(false); }); it("registers for multicast subscription and sends multicast publication", () => { const broadcastOutputParameters = testNonSelectiveBroadcast.createBroadcastOutputParameters(); broadcastOutputParameters.setParam1("param1"); expect(publicationManager.hasMulticastSubscriptions()).toBe(false); publicationManager.addPublicationProvider(providerId, provider); const request = handleMulticastSubscriptionRequest(); expect(publicationManager.hasMulticastSubscriptions()).toBe(true); testNonSelectiveBroadcast.fire(broadcastOutputParameters); expect(dispatcherSpy.sendMulticastPublication).toHaveBeenCalled(); const multicastPublication = dispatcherSpy.sendMulticastPublication.mock.calls[0][1]; expect(multicastPublication.multicastId).toEqual(request.multicastId); publicationManager.handleSubscriptionStop({ subscriptionId: request.subscriptionId } as any); expect(publicationManager.hasMulticastSubscriptions()).toBe(false); }); it("rejects broadcast subscription if broadcast does not exist", async () => { const request = new BroadcastSubscriptionRequest({ subscriptionId: `subscriptionId${nanoid()}`, subscribedToName: "nonExistingBroadcast", qos: new OnChangeSubscriptionQos(), filterParameters: {} as any }); publicationManager.addPublicationProvider(providerId, provider); publicationManager.handleBroadcastSubscriptionRequest(proxyId, providerId, request, callbackDispatcher); await testUtil.multipleSetImmediate(); expect(callbackDispatcher).toHaveBeenCalled(); const error = callbackDispatcher.mock.calls.slice(-1)[0][1].error; expect(error).toBeDefined(); expect(error).toBeInstanceOf(SubscriptionException); expect(error.subscriptionId).toBeDefined(); expect(error.subscriptionId).toEqual(callbackDispatcher.mock.calls.slice(-1)[0][1].subscriptionId); expect(error.detailMessage).toMatch(/misses event/); }); it(" throws exception when called while shut down", async () => { publicationManager.shutdown(); const callbackDispatcherSpy = jest.fn(); expect(() => { publicationManager.removePublicationProvider("providerParticipantId", {}); }).toThrow(); expect(() => { publicationManager.addPublicationProvider("providerParticipantId", {}); }).toThrow(); publicationManager.handleSubscriptionRequest( "proxyParticipantId", "providerParticipantId", { subscriptionId: "subscriptionId" } as any, callbackDispatcherSpy ); await increaseFakeTime(1); expect(callbackDispatcherSpy).toHaveBeenCalled(); expect(callbackDispatcherSpy.mock.calls[0][1]).toBeInstanceOf(SubscriptionReply); expect(callbackDispatcherSpy.mock.calls[0][1].error).toBeInstanceOf(SubscriptionException); callbackDispatcherSpy.mockClear(); publicationManager.handleBroadcastSubscriptionRequest( "proxyParticipantId", "providerParticipantId", { subscriptionId: "subscriptionId" } as any, callbackDispatcherSpy ); await increaseFakeTime(1); expect(callbackDispatcherSpy).toHaveBeenCalled(); expect(callbackDispatcherSpy.mock.calls[0][1]).toBeInstanceOf(SubscriptionReply); expect(callbackDispatcherSpy.mock.calls[0][1].error).toBeInstanceOf(SubscriptionException); }); });
the_stack
import { AABB, AvActionState, AvConstraint, AvModelInstance, AvNode, AvNodeTransform, AvNodeType, AvRenderer, AvSharedTextureInfo, AvVector, computeUniverseFromLine, EHand, emptyActionState, EndpointAddr, endpointAddrToString, EndpointType, ENodeFlags, EVolumeType, filterActionsForGadget, g_anim_Left_Pen, g_anim_Right_Pen, g_builtinModelCylinder, g_builtinModelError, g_builtinModelSkinnedHandLeft, g_builtinModelSkinnedHandRight, g_builtinModelSphere, InterfaceLockResult, lerpAvTransforms, MessageType, minIgnoringNulls, MsgInterfaceEnded, MsgInterfaceReceiveEvent, MsgInterfaceStarted, MsgInterfaceTransformUpdated, MsgResourceLoadFailed, MsgUpdateActionState, nodeTransformFromMat4, nodeTransformToMat4, scaleAxisToFit, scaleMat, vec3MultiplyAndAdd } from '@aardvarkxr/aardvark-shared'; import { mat4, vec3, vec4 } from '@tlaukkan/tsm'; import bind from 'bind-decorator'; import { EndpointAddrMap } from './endpoint_addr_map'; import { CInterfaceProcessor, InterfaceEntity, InterfaceProcessorCallbacks } from './interface_processor'; import { ipfsUtils } from './ipfs_utils'; import { modelCache, ModelInfo } from './model_cache'; import { textureCache, TextureInfo } from './texture_cache'; import { Traverser, TraverserCallbacks } from './traverser_interface'; import { fixupUrl, getHandVolumes, UrlType } from './traverser_utils'; import { TransformedVolume } from './volume_intersection'; const equal = require( 'fast-deep-equal' ); interface NodeData { lastModelUri?: string; lastFailedModelUri?: string; lastTextureUri?: string; lastFailedTextureUri?: string; lastAnimationSource?: string; modelInstance?: AvModelInstance; lastParentFromNode?: mat4; constraint?: AvConstraint; lastFlags?: ENodeFlags; lastFrameUsed: number; nodeType: AvNodeType; lastNode?: AvNode; transform0?: AvNodeTransform; transform0Time?: number; transform1?: AvNodeTransform; transform1Time?: number; graphParent?: EndpointAddr; lastVisible?: boolean; } interface TransformComputeFunction { ( universeFromParent: mat4[], parentFromNode: mat4 ): mat4; } class PendingTransform { private m_id: string; private m_needsUpdate = true; private m_parents: PendingTransform[] = null; private m_parentFromNode: mat4 = null; private m_universeFromNode: mat4 = null; private m_applyFunction: (universeFromNode: mat4) => void = null; private m_computeFunction: TransformComputeFunction = null; private m_currentlyResolving = false; private m_originPath: string = null; private m_constraint: AvConstraint = null; constructor( id: string ) { this.m_id = id; } public resolve() { if( this.m_universeFromNode ) { return; } if( this.m_needsUpdate ) { console.log( `Pending transform ${ this.m_id } needs an update in resolve` ); this.m_parentFromNode = mat4.identity; } if( this.m_currentlyResolving ) { throw "Loop in pending transform parents"; } this.m_currentlyResolving = true; let parentFromNode = this.m_parentFromNode ?? mat4.identity; if( this.m_parents ) { for( let parent of this.m_parents ) { parent.resolve(); } if( this.m_computeFunction ) { let universeFromParents = this.m_parents.map( ( parent ) => parent.getUniverseFromNode() ); this.m_universeFromNode = this.m_computeFunction( universeFromParents, this.m_parentFromNode ); } else { let universeFromParent = this.universeFromParentWithConstraint(); this.m_universeFromNode = new mat4; mat4.product( universeFromParent, parentFromNode, this.m_universeFromNode ); } } else { this.m_universeFromNode = parentFromNode; } this.m_currentlyResolving = false; if( this.m_applyFunction ) { this.m_applyFunction( this.m_universeFromNode ); } } private universeFromParentWithConstraint() { let universeFromFinalParent = this.m_parents[0].getUniverseFromNode(); if( !this.m_constraint || this.m_parents.length != 2 ) return universeFromFinalParent; // figure out how to get things into constraint space let universeFromConstraintParent = this.m_parents[1].getUniverseFromNode(); let constraintParentFromUniverse = new mat4( universeFromConstraintParent.all() ).inverse(); let constraintParentFromFinalParent = mat4.product( constraintParentFromUniverse, universeFromFinalParent, new mat4() ); // translation in constraint space let transConstraint = new vec3( constraintParentFromFinalParent.multiplyVec4( new vec4( [ 0, 0, 0, 1 ] ) ).xyz ); // apply the constraint let clamp = ( value: number, min?: number, max?: number ) => { return Math.max( min ?? Number.NEGATIVE_INFINITY, Math.min( max ?? Number.POSITIVE_INFINITY, value ) ); } transConstraint.x = clamp( transConstraint.x, this.m_constraint.minX, this.m_constraint.maxX ); transConstraint.y = clamp( transConstraint.y, this.m_constraint.minY, this.m_constraint.maxY ); transConstraint.z = clamp( transConstraint.z, this.m_constraint.minZ, this.m_constraint.maxZ ); // translation in universe space let trans = new vec3( universeFromConstraintParent.multiplyVec4( new vec4( [ transConstraint.x, transConstraint.y, transConstraint.z, 1 ] ) ).xyz ); let xBasis = new vec3( universeFromFinalParent.row( 0 ) as [ number, number, number ] ); let yBasis = new vec3( universeFromFinalParent.row( 1 ) as [ number, number, number ] ); let zBasis = new vec3( universeFromFinalParent.row( 2 ) as [ number, number, number ] ); // now apply gravity alignment, if necessary, which is in universe space (since the // universe is the only thing here's that's gravity-aligned. ) if( this.m_constraint.gravityAligned ) { // figure out basis vectors where Y is up let newYBasis = vec3.up; let newXBasis = vec3.cross( newYBasis, zBasis ).normalize(); let newZBasis = vec3.cross( newXBasis, newYBasis ).normalize(); // then replace the original basis vectors with those xBasis = newXBasis; yBasis = newYBasis; zBasis = newZBasis; } return new mat4( [ xBasis.x, xBasis.y, xBasis.z, 0, yBasis.x, yBasis.y, yBasis.z, 0, zBasis.x, zBasis.y, zBasis.z, 0, trans.x, trans.y, trans.z, 1, ] ); } public setOriginPath( originPath: string ) { this.m_originPath = originPath; } public getOriginPath(): string { if( this.m_originPath ) { return this.m_originPath; } else if( this.m_parents && this.m_parents.length > 0 ) { return this.m_parents[0].getOriginPath(); } else { return null; } } public getUniverseFromNode():mat4 { return this.m_universeFromNode; } public needsUpdate(): boolean { return this.m_needsUpdate; } public isResolved(): boolean { return this.m_universeFromNode != null; } public update( parents: PendingTransform[], parentFromNode: mat4, updateCallback?: ( universeFromNode:mat4 ) => void, computeCallback?: TransformComputeFunction ) { this.m_universeFromNode = undefined; // unresolve the transform if it's resolved this.m_needsUpdate = false; this.m_parents = parents; this.m_parentFromNode = parentFromNode ? parentFromNode : mat4.identity; this.m_applyFunction = updateCallback; this.m_computeFunction = computeCallback; this.checkForLoops(); } public set constraint( constraint: AvConstraint ) { this.m_constraint = constraint; } private checkForLoops() { if( !this.m_parents ) return; for( let test = this.m_parents[0]; test != null; test = test.m_parents ? test.m_parents[0] : null ) { if( test == this ) { throw "Somebody created a loop in transform parents"; } } } } enum AnchorState { Grabbed, Hooked, Parented, } interface NodeToNodeAnchor_t { state: AnchorState; parentGlobalId: EndpointAddr; handleGlobalId?: EndpointAddr; parentFromGrabbable: mat4; grabbableParentFromGrabbableOrigin?: mat4; anchorToRestore?: NodeToNodeAnchor_t; } interface AvNodeRoot { gadgetId: number; gadgetUrl: string; root: AvNode; handIsRelevant: Set<EHand>; wasGadgetDraggedLastFrame: boolean; origin: string; userAgent: string; } interface RemoteUniverse { uuid: string; remoteFromOrigin: { [originPath: string] : PendingTransform }; } function handFromOriginPath( originPath: string ) { if ( originPath?.startsWith( "/user/hand/left" ) ) { return EHand.Left; } else if ( originPath?.startsWith( "/user/hand/right" ) ) { return EHand.Right; } else { return EHand.Invalid; } } export class AvDefaultTraverser implements InterfaceProcessorCallbacks, Traverser { private m_inFrameTraversal = false; private m_handDeviceForNode: { [nodeGlobalId:string]:EHand } = {}; private m_currentHand = EHand.Invalid; private m_currentVisibility = true; private m_currentNodeByType: { [ nodeType: number] : AvNode[] } = {}; private m_universeFromNodeTransforms: { [ nodeGlobalId:string ]: PendingTransform } = {}; private m_nodeData: { [ nodeGlobalId:string ]: NodeData } = {}; private m_lastFrameUniverseFromNodeTransforms: { [ nodeGlobalId:string ]: mat4 } = {}; private m_roots: { [gadgetId:number] : AvNodeRoot } = {}; private m_currentRoot: AvNodeRoot = null; private m_renderList: AvModelInstance[] = []; private m_nodeToNodeAnchors: { [ nodeGlobalId: string ]: NodeToNodeAnchor_t } = {}; private m_frameNumber: number = 1; private m_actionState: { [ hand: number ] : AvActionState } = {}; private m_dirtyGadgetActions = new Set<number>(); private m_remoteUniverse: { [ universeUuid: string ]: RemoteUniverse } = {}; private m_interfaceProcessor = new CInterfaceProcessor( this, { verboseLogging: true } ); private m_interfaceEntities: AvNode[] = []; private m_entityParentTransforms = new EndpointAddrMap<PendingTransform >(); private m_callbacks: TraverserCallbacks; private m_renderer: AvRenderer; constructor( traverserCallbacks: TraverserCallbacks, renderer: AvRenderer ) { this.m_callbacks = traverserCallbacks; this.m_renderer = renderer; } public async init() { await ipfsUtils.init(); await modelCache.init( { negativeCaching: false, urlsToLoad: [ g_builtinModelSkinnedHandLeft, g_builtinModelSkinnedHandRight, g_anim_Left_Pen, g_anim_Right_Pen, ] } ); await textureCache.init( { negativeCaching: false, } ); } public forgetGadget( endpointId: number ) { // TODO: Clean up drags and such? delete this.m_roots[ endpointId ]; } public interfaceSendEvent( destEpa: EndpointAddr, peerEpa: EndpointAddr, iface: string, event: object ) { this.m_interfaceProcessor.interfaceEvent( destEpa, peerEpa, iface, event ); } public interfaceLock( transmitter: EndpointAddr, receiver: EndpointAddr, iface: string ) { return this.m_interfaceProcessor.lockInterface( transmitter, receiver, iface ); } public interfaceUnlock( transmitter: EndpointAddr, receiver: EndpointAddr, iface: string ) : [ InterfaceLockResult, () => void ] { return this.m_interfaceProcessor.unlockInterface( transmitter, receiver, iface ); } public interfaceRelock( transmitter: EndpointAddr, oldReceiverEpa: EndpointAddr, newReceiverEpa: EndpointAddr, iface: string ) { return this.m_interfaceProcessor.relockInterface( transmitter, oldReceiverEpa, newReceiverEpa, iface ); } interfaceStarted( transmitter: EndpointAddr, receiver: EndpointAddr, iface: string, transmitterFromReceiver: [mat4, vec3|null], params?: object, reason?: string ):void { const [ transform, pt ] = transmitterFromReceiver ?? [ null, null ]; let intersectionPoint:AvVector; if( pt ) { intersectionPoint = { x: pt.x, y: pt.y, z: pt.z }; } let transmitterRoot = this.m_roots[ transmitter.endpointId ]; let receiverRoot = this.m_roots[ receiver.endpointId ]; this.m_callbacks.sendMessage( MessageType.InterfaceStarted, { transmitter, transmitterOrigin: transmitterRoot?.origin, transmitterUserAgent: transmitterRoot?.userAgent, receiver, receiverOrigin: receiverRoot?.origin, receiverUserAgent: receiverRoot?.userAgent, iface, transmitterFromReceiver: nodeTransformFromMat4( transform ), intersectionPoint, params, reason, } as MsgInterfaceStarted ); } interfaceEnded( transmitter: EndpointAddr, receiver: EndpointAddr, iface: string, transmitterFromReceiver: [mat4, vec3|null], reason?: string ):void { const [ transform, pt ] = transmitterFromReceiver ?? [ undefined, null ]; let intersectionPoint:AvVector; if( pt ) { intersectionPoint = { x: pt.x, y: pt.y, z: pt.z }; } this.m_callbacks.sendMessage( MessageType.InterfaceEnded, { transmitter, receiver, iface, transmitterFromReceiver: nodeTransformFromMat4( transform ), intersectionPoint, reason, } as MsgInterfaceEnded ); } interfaceTransformUpdated( destination: EndpointAddr, peer: EndpointAddr, iface: string, destinationFromPeer: [mat4, vec3|null], reason?: string ): void { const [ transform, pt ] = destinationFromPeer; let intersectionPoint:AvVector; if( pt ) { intersectionPoint = { x: pt.x, y: pt.y, z: pt.z }; } this.m_callbacks.sendMessage( MessageType.InterfaceTransformUpdated, { destination, peer, iface, destinationFromPeer: nodeTransformFromMat4( transform ), intersectionPoint, reason, } as MsgInterfaceTransformUpdated ); } interfaceEvent( destination: EndpointAddr, peer: EndpointAddr, iface: string, event: object, destinationFromPeer: [mat4, vec3|null], reason?: string ): void { const [ transform, pt ] = destinationFromPeer; let intersectionPoint:AvVector; if( pt ) { intersectionPoint = { x: pt.x, y: pt.y, z: pt.z }; } this.m_callbacks.sendMessage( MessageType.InterfaceReceiveEvent, { destination, peer, iface, event, destinationFromPeer: nodeTransformFromMat4( transform ), intersectionPoint, reason, } as MsgInterfaceReceiveEvent ); } public updateSceneGraph( root: AvNode, gadgetUrl: string, origin: string, userAgent: string, gadgetId: number ) { this.updateGlobalIds( root, gadgetId ); let rootData = this.m_roots[ gadgetId ]; if( !rootData ) { rootData = this.m_roots[ gadgetId ] = { gadgetId, handIsRelevant: new Set<EHand>(), wasGadgetDraggedLastFrame: false, root: null, gadgetUrl, origin, userAgent, }; } rootData.root = root; } private updateGlobalIds( node: AvNode, gadgetId: number ) { node.globalId = { type: EndpointType.Node, endpointId: gadgetId, nodeId: node.id, } if( node.children ) { for( let child of node.children ) { this.updateGlobalIds( child, gadgetId ); } } } @bind public traverse() { if( !this.m_roots ) { return; } this.m_inFrameTraversal = true; this.m_currentHand = EHand.Invalid; this.m_currentVisibility = true; this.m_currentNodeByType = {}; this.m_universeFromNodeTransforms = {}; this.m_interfaceEntities = []; this.m_entityParentTransforms = new EndpointAddrMap<PendingTransform >(); // need to render the volumes from the previous frame because updateInterfaceProcessor // happens after we send off the render list. this.m_renderList = [ ...this.sphereVolumeModels ]; this.sphereVolumeSpares = [ ...this.sphereVolumeSpares, ...this.sphereVolumeModels ]; this.sphereVolumeModels = []; this.m_frameNumber++; for ( let gadgetId in this.m_roots ) { this.traverseSceneGraph( this.m_roots[ gadgetId ] ); } this.m_lastFrameUniverseFromNodeTransforms = {}; for ( let nodeGlobalId in this.m_universeFromNodeTransforms ) { let transform = this.m_universeFromNodeTransforms[ nodeGlobalId ]; transform.resolve(); this.m_lastFrameUniverseFromNodeTransforms[ nodeGlobalId] = transform.getUniverseFromNode(); } this.m_inFrameTraversal = false; this.m_renderer.renderList( this.m_renderList ); this.updateInput(); this.updateInterfaceProcessor(); for( let gadgetId of this.m_dirtyGadgetActions ) { this.sendUpdateActionState( gadgetId, EHand.Left ); this.sendUpdateActionState( gadgetId, EHand.Right ); } this.cleanupOldNodeData(); } private updateInput() { this.updateActionState( EHand.Left ); this.updateActionState( EHand.Right ); } private sendUpdateActionState( gadgetId: number, hand: EHand ) { if( this.m_inFrameTraversal ) { throw new Error( "sendUpdateActionState not valid during traversal" ); } let root = this.m_roots[ gadgetId ]; if( !root ) { return; } let actionState: AvActionState; if( /*root.wasGadgetDraggedLastFrame &&*/ root.handIsRelevant.has( hand ) ) { actionState = filterActionsForGadget( this.m_actionState[ hand ] ); } else { actionState = emptyActionState(); } let m: MsgUpdateActionState = { gadgetId, hand, actionState, } this.m_callbacks.sendMessage( MessageType.UpdateActionState, m ); } private updateActionState( hand: EHand ) { let newActionState = this.m_renderer.getActionState( hand ); let oldActionState = this.m_actionState[ hand ] if( !equal( newActionState, oldActionState ) ) { for( let gadgetId in this.m_roots ) { let root = this.m_roots[ gadgetId ]; if( !root.handIsRelevant.has( hand ) ) continue; this.m_dirtyGadgetActions.add( root.gadgetId ); } this.m_actionState[ hand ] = newActionState; } } private sphereVolumeModels: AvModelInstance[] = []; private sphereVolumeSpares: AvModelInstance[] = []; private showVolume( v: TransformedVolume ) { if( v.type != EVolumeType.Sphere ) { // we currently only know how to show spheres return; } let model = this.sphereVolumeSpares.shift(); if( !model ) { let sphereModel = modelCache.queueModelLoad( g_builtinModelSphere ); if( sphereModel ) { model = this.m_renderer.createModelInstance( g_builtinModelSphere, sphereModel.base64 ); } if( !model ) { // we'll have to catch this one next frame return; } } let universeFromVolume = new mat4( v.universeFromVolume.all() ); universeFromVolume.scale( new vec3( [ v.radius, v.radius, v.radius ] ) ); model.setUniverseFromModelTransform( universeFromVolume.all() ); this.sphereVolumeModels.push( model ); this.m_renderList.push( model ); } private updateInterfaceProcessor() { let handVolumeCache = new Map<string, TransformedVolume[]>(); let entities: InterfaceEntity[] = []; for( let entityNode of this.m_interfaceEntities ) { let universeFromEntity = this.getTransform( entityNode.globalId ); if( !universeFromEntity.isResolved() ) { console.log( "Refusing to process interface entity because it has an unresolved transform", endpointAddrToString( entityNode.globalId ) ); continue; } let entityData = this.getNodeData( entityNode ); let volumes: TransformedVolume[] = []; let bestSource: string; if( !entityData.lastVisible ) { bestSource = "not visible"; } else { bestSource = "empty list"; // compute the transform to universe for each volume for( let volume of entityNode.propVolumes ?? [] ) { if( volume.type == EVolumeType.Infinite ) { // infinite volumes don't care about the transform volumes.push( { ...volume, universeFromVolume: mat4.identity, } ); continue; } if( !universeFromEntity.getOriginPath() ) { bestSource = "No origin path"; continue; } if( volume.type == EVolumeType.Skeleton && volume.skeletonPath ) { let handVolumes: TransformedVolume[] = handVolumeCache.get( volume.skeletonPath ); if( !handVolumes ) { handVolumes = getHandVolumes( volume.skeletonPath ) ?? []; handVolumeCache.set( volume.skeletonPath, handVolumes ); } if( volume.visualize ) { for( let v of handVolumes ) { v.visualize = true; } } volumes = [ ...volumes, ...handVolumes, ]; continue; } let matScale = volume.scale ? scaleMat( new vec3( [ volume.scale, volume.scale, volume.scale ] ) ) : mat4.identity; let universeFromVolume = mat4.product( universeFromEntity.getUniverseFromNode(), mat4.product( matScale, nodeTransformToMat4( volume.nodeFromVolume ?? {} ), new mat4() ), new mat4() ); volumes.push( { ...volume, universeFromVolume, } ); } } for( let v of volumes ) { if( v.visualize ) { this.showVolume( v ); } } if( volumes.length == 0 ) { // if this entity doesn't have an origin path or isn't visible, forbid anything // from intersecting with it. It will still be able to participate in // existing locks or initial locks volumes.push( { type: EVolumeType.Empty, universeFromVolume: mat4.identity, source: bestSource, } ); } let initialLocks = entityNode.propInterfaceLocks ?? []; entities.push( { epa: entityNode.globalId, transmits: entityNode.propTransmits ?? [], receives: entityNode.propReceives ?? [], originPath: universeFromEntity.getOriginPath(), universeFromEntity: universeFromEntity.getUniverseFromNode(), wantsTransforms: 0 != ( entityNode.flags & ENodeFlags.NotifyOnTransformChange ), priority: entityNode.propPriority ?? 0, volumes, initialLocks, } ); } this.m_interfaceProcessor.processFrame( entities ); } getNodeData( node: AvNode ): NodeData { return this.getNodeDataByEpa( node.globalId, node.type ); } getNodeDataByEpa( nodeGlobalId: EndpointAddr, typeHint?: AvNodeType ): NodeData { if( !nodeGlobalId ) { return null; } if( typeHint === undefined ) { typeHint = AvNodeType.Invalid; } let nodeIdStr = endpointAddrToString( nodeGlobalId ); if( !this.m_nodeData.hasOwnProperty( nodeIdStr ) ) { let nodeData = { lastFrameUsed: this.m_frameNumber, nodeType: typeHint }; this.m_nodeData[ nodeIdStr] = nodeData; return nodeData; } else { let nodeData = this.m_nodeData[ nodeIdStr ]; nodeData.lastFrameUsed = this.m_frameNumber; return nodeData; } } cleanupOldNodeData() { let keys = Object.keys( this.m_nodeData ); let frameToDeleteBefore = this.m_frameNumber - 2; for( let nodeIdStr of keys ) { let nodeData = this.m_nodeData[ nodeIdStr ]; if( nodeData.lastFrameUsed < frameToDeleteBefore ) { delete this.m_nodeData[ nodeIdStr ]; } } } traverseSceneGraph( root: AvNodeRoot ): void { if( root.root ) { this.m_currentRoot = root; let oldRelevantHands = this.m_currentRoot.handIsRelevant; this.m_currentRoot.handIsRelevant = new Set<EHand>(); this.m_currentRoot.wasGadgetDraggedLastFrame = false; // get the ID for node 0. We're going to use that as the parent of // everything. let rootNode: AvNode; if( root.root.id == 0 ) { rootNode = root.root; } else { rootNode = { type: AvNodeType.Container, id: 0, flags: ENodeFlags.Visible, globalId: { type: EndpointType.Node, endpointId: root.root.globalId.endpointId, nodeId: 0 }, children: [ root.root ], } } this.traverseNode( rootNode, null, null ); // send empty action data for any hand that we don't care about anymore for( let hand of oldRelevantHands ) { if( hand == EHand.Invalid ) continue; if( !this.m_currentRoot.handIsRelevant.has( hand ) ) { this.m_dirtyGadgetActions.add( root.gadgetId ); } } // send the current action data for any hand that we don't care about anymore for( let hand of this.m_currentRoot.handIsRelevant ) { if( hand == EHand.Invalid ) continue; if( !oldRelevantHands.has( hand ) ) { this.m_dirtyGadgetActions.add( root.gadgetId ); } } this.m_currentRoot = null; } } private getRemoteUniverse( universeUuid?: string ): RemoteUniverse { if( !universeUuid ) return null; let remoteUniverse = this.m_remoteUniverse[ universeUuid ]; if( !remoteUniverse ) { remoteUniverse = { uuid: universeUuid, remoteFromOrigin: {}, }; this.m_remoteUniverse[ universeUuid ] = remoteUniverse; } return remoteUniverse; } private getRemoteOriginTransform( universeId: string, originPath: string ): PendingTransform { let universe = this.getRemoteUniverse( universeId ); let originTransform = universe.remoteFromOrigin[ originPath ]; if( !originTransform ) { originTransform = new PendingTransform( universeId + "/" + originPath ); universe.remoteFromOrigin[ originPath ] = originTransform; } return originTransform; } traverseNode( node: AvNode, defaultParent: PendingTransform, parentGlobalId?: EndpointAddr ): void { let handBefore = this.m_currentHand; let visibilityBefore = this.m_currentVisibility; let nodeData = this.getNodeData( node ); nodeData.graphParent = parentGlobalId; this.m_currentVisibility = ( 0 != ( node.flags & ENodeFlags.Visible ) ) && this.m_currentVisibility; switch ( node.type ) { case AvNodeType.Container: // nothing special to do here break; case AvNodeType.Origin: this.traverseOrigin( node, defaultParent ); break; case AvNodeType.Transform: this.traverseTransform( node, defaultParent ); break; case AvNodeType.Model: this.traverseModel( node, defaultParent ); break; case AvNodeType.Line: this.traverseLine( node, defaultParent ); break; case AvNodeType.ParentTransform: this.traverseParentTransform( node, defaultParent ); break; case AvNodeType.ModelTransform: this.traverseModelTransform( node, defaultParent ); break; case AvNodeType.WeightedTransform: this.traverseWeightedTransform( node, defaultParent ); break; case AvNodeType.HeadFacingTransform: this.traverseHeadFacingTransform( node, defaultParent ); break; case AvNodeType.Child: this.traverseChild( node, defaultParent ); break; case AvNodeType.InterfaceEntity: this.traverseInterfaceEntity( node, defaultParent ); break; default: throw "Invalid node type"; } if( !this.m_currentNodeByType[ node.type ] ) { this.m_currentNodeByType[ node.type ] = []; } this.m_currentNodeByType[ node.type ].push( node ); nodeData.lastFlags = node.flags; nodeData.lastNode = node; nodeData.lastVisible = this.m_currentVisibility; let thisNodeTransform = this.getTransform( node.globalId ); if ( thisNodeTransform.needsUpdate() ) { thisNodeTransform.update( defaultParent ? [ defaultParent ] : null, mat4.identity ); } this.m_handDeviceForNode[ endpointAddrToString( node.globalId ) ] = this.m_currentHand; if( node.children ) { for ( let child of node.children ) { this.traverseNode( child, thisNodeTransform, node.globalId ); } } this.m_currentNodeByType[ node.type ].pop(); // remember that we used this hand this.m_currentRoot.handIsRelevant.add( this.m_currentHand ); this.m_currentHand = handBefore; this.m_currentVisibility = visibilityBefore; } traverseOrigin( node: AvNode, defaultParent: PendingTransform ) { this.setHookOrigin( node.propOrigin, node ); } setHookOrigin( origin: string | EndpointAddr, node: AvNode, hookFromGrabbable?: AvNodeTransform ) { if( typeof origin === "string" ) { let parentFromOriginArray = this.m_renderer.getUniverseFromOriginTransform( origin ); if( parentFromOriginArray ) { let transform = this.updateTransform( node.globalId, null, new mat4( parentFromOriginArray ), null ); transform.setOriginPath( origin ); } this.m_currentHand = handFromOriginPath( origin ); } else if( origin != null ) { let grabberFromGrabbable = mat4.identity; if( hookFromGrabbable ) { grabberFromGrabbable = nodeTransformToMat4( hookFromGrabbable ); } this.m_nodeToNodeAnchors[ endpointAddrToString( node.globalId ) ] = { state: AnchorState.Hooked, parentGlobalId: origin, parentFromGrabbable: grabberFromGrabbable, } } } traverseTransform( node: AvNode, defaultParent: PendingTransform ) { let parent = defaultParent; if( node.propParentAddr ) { parent = this.getTransform( node.propParentAddr ); } if ( node.propTransform ) { let mat = nodeTransformToMat4( node.propTransform ); this.updateTransformWithConstraint( node.globalId, parent, defaultParent, node.propConstraint, mat, null ); } } traverseParentTransform( node: AvNode, defaultParent: PendingTransform ) { if( node.propParentAddr ) { let parentTransform = this.getTransform( node.propParentAddr ); this.updateTransformWithConstraint( node.globalId, parentTransform, defaultParent, node.propConstraint, null, null ) } } traverseModelTransform( node: AvNode, defaultParent: PendingTransform ) { let modelInfo = this.tryLoadModelForNode( node, node.propModelUri ); let parentFromNode = modelInfo?.getRootFromNode( node.propModelNodeId ); if( parentFromNode ) { this.updateTransform( node.globalId, defaultParent, parentFromNode, null ); } } traverseWeightedTransform( node: AvNode, defaultParent: PendingTransform ) { let myWeights = node.propWeightedParents; if( !myWeights || !myWeights.length ) { return; } let weightedTransforms: PendingTransform[] = []; let weights: number[] = []; for( let weight of myWeights ) { weightedTransforms.push( this.getTransform( weight.parent ) ); } this.updateTransformWithCompute( node.globalId, weightedTransforms, mat4.identity, null, ( universeFromParent: mat4[], parentFromNode: mat4 ): mat4 => { let weightSoFar = 0; let transformSoFar: AvNodeTransform = {}; for( let i = 0; i < universeFromParent.length; i++ ) { let thisWeight = myWeights[ i ].weight; weightSoFar += thisWeight; transformSoFar = lerpAvTransforms( transformSoFar, nodeTransformFromMat4( universeFromParent[ i ] ), thisWeight / weightSoFar ); } return nodeTransformToMat4( transformSoFar ); } ); } traverseHeadFacingTransform( node: AvNode, defaultParent: PendingTransform ) { let universeFromHead = new mat4( this.m_renderer.getUniverseFromOriginTransform( "/user/head" ) ); this.updateTransformWithCompute( node.globalId, [ defaultParent ], mat4.identity, null, ( universeFromParent: mat4[], parentFromNode ) => { let yAxisRough = new vec3( [ 0, 1, 0 ] ); let hmdUp = universeFromHead.multiplyVec3( new vec3( [ 0, 1, 0 ] ) ); if( vec3.dot( yAxisRough, hmdUp ) < 0.1 ) { yAxisRough = hmdUp; } let universeFromNodeTranslation = universeFromParent[0].multiply( parentFromNode ); let nodeTranslation = universeFromNodeTranslation.multiplyVec4( new vec4( [ 0, 0, 0, 1 ] ) ); let headTranslation = universeFromHead.multiplyVec4( new vec4( [ 0, 0, 0, 1 ] ) ); let zAxis = new vec3( headTranslation.subtract( nodeTranslation ).xyz ).normalize(); let xAxis = vec3.cross( yAxisRough, zAxis, new vec3() ).normalize(); let yAxis = vec3.cross( zAxis, xAxis ); let universeFromNode = new mat4( [ xAxis.x, xAxis.y, xAxis.z, 0, yAxis.x, yAxis.y, yAxis.z, 0, zAxis.x, zAxis.y, zAxis.z, 0, nodeTranslation.x, nodeTranslation.y, nodeTranslation.z, 1, ] ); return universeFromNode; } ); } @bind private getNodeField( nodeId: EndpointAddr, fieldName: string ): [ string, string ] { let nodeData = this.getNodeDataByEpa( nodeId ); if( nodeData && nodeData.lastNode ) { let fieldValue = ( nodeData.lastNode as any )[ fieldName ]; if( typeof fieldValue == "string" ) { return [ this.m_roots[ nodeId.endpointId ].gadgetUrl, fieldValue ]; } } return null; } private fixupUrlForCurrentNode( rawUrl: string ) : [ string, UrlType ] { return fixupUrl( this.m_currentRoot.gadgetUrl, rawUrl, this.getNodeField ); } traverseModel( node: AvNode, defaultParent: PendingTransform ) { let nodeData = this.getNodeData( node ); if ( nodeData.lastFailedModelUri != node.propModelUri ) { nodeData.lastFailedModelUri = null; } // we don't care about URL validity here because we want to fail once so the gadget gets its // URL load failed exception let foo = this.fixupUrlForCurrentNode( node.propModelUri ); const [ filteredUri, urlType ] = foo; let modelToLoad = nodeData.lastFailedModelUri ? g_builtinModelError : filteredUri if ( nodeData.lastModelUri != modelToLoad && nodeData.lastFailedModelUri != filteredUri ) { nodeData.modelInstance = null; } if ( !nodeData.modelInstance ) { let modelData = this.tryLoadModelForNode( node, modelToLoad) if( modelData ) { try { nodeData.modelInstance = this.m_renderer.createModelInstance( modelToLoad, modelData.base64 ); if ( nodeData.modelInstance ) { nodeData.lastModelUri = filteredUri; } } catch( e ) { nodeData.lastFailedModelUri = filteredUri; } } } if ( nodeData.modelInstance ) { if( node.propColor ) { let alpha = ( node.propColor.a == undefined ) ? 1 : node.propColor.a; nodeData.modelInstance.setBaseColor( [ node.propColor.r, node.propColor.g, node.propColor.b, alpha ] ); } if( typeof node.propOverlayOnly == "boolean" ) { nodeData.modelInstance.setOverlayOnly( node.propOverlayOnly ); } if( node.propAnimationSource && node.propAnimationSource != nodeData.lastAnimationSource ) { if( node.propAnimationSource.startsWith( "source:" ) ) { let trimmedSource = node.propAnimationSource.substr( 7 ); nodeData.modelInstance.setAnimationSource( trimmedSource ); nodeData.lastAnimationSource = node.propAnimationSource; } else { const [ animUri, urlType ] = this.fixupUrlForCurrentNode( node.propAnimationSource ); let animInfo = this.tryLoadModelForNode(node, animUri ); if( animInfo ) { try { nodeData.modelInstance.setAnimation( animUri, animInfo.base64 ); nodeData.lastAnimationSource = node.propAnimationSource; } catch( e ) { nodeData.lastFailedModelUri = animUri; } } } } if( node.propSharedTexture?.url ) { const [ filteredTextureUrl, urlType ] = this.fixupUrlForCurrentNode( node.propSharedTexture.url ); if( filteredTextureUrl != nodeData.lastTextureUri ) { let textureInfo = this.tryLoadTextureForNode( node, filteredTextureUrl ); if( textureInfo ) { let sharedTexture: AvSharedTextureInfo = { ...node.propSharedTexture, textureDataBase64: textureInfo.base64, }; try { nodeData.modelInstance.setOverrideTexture( sharedTexture ); nodeData.lastTextureUri = filteredTextureUrl; } catch( e ) { // just eat these and don't add the panel. Sometimes we find out about a panel // before we find out about its texture return; } } } } else { try { if( node.propSharedTexture ) { nodeData.modelInstance.setOverrideTexture( node.propSharedTexture ); } } catch( e ) { // just eat these and don't add the panel. Sometimes we find out about a panel // before we find out about its texture return; } } let internalScale = 1; if( node.propScaleToFit ) { let aabb: AABB = this.tryLoadModelForNode( node, modelToLoad ).aabb ?? null; if( !aabb ) { // if we were told to scale the model, but it isn't loaded at this point, // abort drawing it so we don't have one frame of a wrongly-scaled model // as it loads in. return; } let possibleScale = minIgnoringNulls( scaleAxisToFit( node.propScaleToFit.x, aabb.xMin, aabb.xMax ), scaleAxisToFit( node.propScaleToFit.y, aabb.yMin, aabb.yMax ), scaleAxisToFit( node.propScaleToFit.z, aabb.zMin, aabb.zMax ) ); if( possibleScale != null ) { internalScale = possibleScale; } } let showModel = this.m_currentVisibility; this.updateTransform( node.globalId, defaultParent, mat4.identity, ( universeFromNode: mat4 ) => { if( internalScale != 1 ) { let scaledNodeFromModel = scaleMat( new vec3( [ internalScale, internalScale, internalScale ] ) ); universeFromNode = new mat4( universeFromNode.all() ).multiply( scaledNodeFromModel ); } nodeData.modelInstance.setUniverseFromModelTransform( universeFromNode.all() ); if( showModel ) { this.m_renderList.push( nodeData.modelInstance ); } } ); } } getCurrentNodeOfType( type: AvNodeType ): AvNode { return this.m_currentNodeByType[ type ]?.[ this.m_currentNodeByType[ type ].length - 1 ]; } traverseLine( node: AvNode, defaultParent: PendingTransform ) { if( !node.propEndAddr ) { return; } // don't draw lines if we're not drawing at all if( !this.m_currentVisibility ) { return; } let lineEndTransform = this.getTransform( node.propEndAddr ); let thickness = node.propThickness === undefined ? 0.003 : node.propThickness; this.updateTransformWithCompute( node.globalId, [ defaultParent, lineEndTransform ], mat4.identity, null, ( [ universeFromStart, universeFromEnd ]: mat4[], unused: mat4) => { let nodeData = this.getNodeData( node ); if ( !nodeData.modelInstance ) { let cylinderModel = modelCache.queueModelLoad( g_builtinModelCylinder ); if( cylinderModel ) { nodeData.modelInstance = this.m_renderer.createModelInstance( g_builtinModelCylinder, cylinderModel.base64 ); if ( nodeData.modelInstance ) { nodeData.lastModelUri = g_builtinModelCylinder; } } } if ( nodeData.modelInstance ) { if( node.propColor ) { let alpha = ( node.propColor.a == undefined ) ? 1 : node.propColor.a; nodeData.modelInstance.setBaseColor( [ node.propColor.r, node.propColor.g, node.propColor.b, alpha ] ); } let startPos = new vec3( universeFromStart.multiplyVec4( new vec4( [ 0, 0, 0, 1 ] ) ).xyz ); let endPos = new vec3( universeFromEnd.multiplyVec4( new vec4( [ 0, 0, 0, 1 ] ) ).xyz ); let lineVector = new vec3( endPos.xyz ); lineVector.subtract( startPos ); let lineLength = lineVector.length(); lineVector.normalize(); let startGap = node.propStartGap ? node.propStartGap : 0; let endGap = node.propEndGap ? node.propEndGap : 0; if( startGap + endGap < lineLength ) { let actualStart = vec3MultiplyAndAdd( startPos, lineVector, startGap ); let actualEnd = vec3MultiplyAndAdd( endPos, lineVector, -endGap ); let universeFromLine = computeUniverseFromLine( actualStart, actualEnd, thickness ); nodeData.modelInstance.setUniverseFromModelTransform( universeFromLine.all() ); this.m_renderList.push( nodeData.modelInstance ); } } return new mat4(); } ); } traverseChild( node: AvNode, defaultParent: PendingTransform ) { if( node.propChildAddr ) { // TODO: Remember the ID of the parent entity and ignore child nodes that // don't match the parent specified on the child entity itself if( this.m_entityParentTransforms.has( node.propChildAddr ) ) { let oldTransform = this.m_entityParentTransforms.get( node.propChildAddr ); oldTransform.update( [ defaultParent ], mat4.identity ); } else { this.m_entityParentTransforms.set( node.propChildAddr, defaultParent ); } } } private tryLoadModelForNode( node: AvNode, modelUrl: string ): ModelInfo { try { return modelCache.queueModelLoad( modelUrl ); } catch( e ) { let nodeData = this.getNodeData( node ); if( nodeData.lastFailedModelUri != modelUrl ) { nodeData.lastFailedModelUri = modelUrl; let m: MsgResourceLoadFailed = { nodeId: node.globalId, resourceUri: modelUrl, error: e.message, }; this.m_callbacks.sendMessage( MessageType.ResourceLoadFailed, m ); } } } private tryLoadTextureForNode( node: AvNode, textureUrl: string ): TextureInfo { try { return textureCache.queueTextureLoad( textureUrl ); } catch( e ) { let nodeData = this.getNodeData( node ); if( nodeData.lastFailedTextureUri != textureUrl ) { nodeData.lastFailedTextureUri = textureUrl; let m: MsgResourceLoadFailed = { nodeId: node.globalId, resourceUri: textureUrl, error: e.message, }; this.m_callbacks.sendMessage( MessageType.ResourceLoadFailed, m ); } } } traverseInterfaceEntity( node: AvNode, defaultParent: PendingTransform ) { for( let volume of node.propVolumes ?? [] ) { if( volume.type == EVolumeType.ModelBox && !volume.aabb) { const [ modelUrl ] = this.fixupUrlForCurrentNode( volume.uri ); let model = this.tryLoadModelForNode( node, modelUrl ); // use the model box if we loaded one, otherwise use a 1cm cube. This keeps // things from completely breaking when the model doesn't load (or hasn't // loaded yet). volume.aabb = model?.aabb ?? { xMin: -0.005, xMax: 0.005, yMin: -0.005, yMax: 0.005, zMin: -0.005, zMax: 0.005, }; } } this.m_interfaceEntities.push( node ); if( node.propParentAddr ) { // TODO: Only look for parent transforms that match this node's propParent addr if( !this.m_entityParentTransforms.has( node.globalId ) ) { let newParent = new PendingTransform( endpointAddrToString( node.globalId ) + "_parent" ); this.m_entityParentTransforms.set( node.globalId, newParent ); } this.updateTransformWithConstraint( node.globalId, this.m_entityParentTransforms.get( node.globalId ), defaultParent, node.propConstraint, null, null ); } } getTransform( globalNodeId: EndpointAddr ): PendingTransform { let idStr = endpointAddrToString( globalNodeId ); if( idStr == "0" ) return null; if( !this.m_universeFromNodeTransforms.hasOwnProperty( idStr ) ) { this.m_universeFromNodeTransforms[ idStr ] = new PendingTransform( idStr ); } return this.m_universeFromNodeTransforms[ idStr ]; } // This is only useful in certain special circumstances where the fact that a // transform will be needed is known before the endpoint ID of the node that // will provide the transform is known. You probably want updateTransform(...) setTransform( globalNodeId: EndpointAddr, newTransform: PendingTransform ) { let idStr = endpointAddrToString( globalNodeId ); if( idStr != "0" ) if( !this.m_universeFromNodeTransforms.hasOwnProperty( idStr ) ) { this.m_universeFromNodeTransforms[ idStr ] = newTransform; } } updateTransform( globalNodeId: EndpointAddr, parent: PendingTransform, parentFromNode: mat4, applyFunction: ( universeFromNode: mat4 ) => void ) { let transform = this.getTransform( globalNodeId ); transform.update( parent ? [ parent ] : null, parentFromNode, applyFunction ); return transform; } updateTransformWithConstraint( globalNodeId: EndpointAddr, finalParent: PendingTransform, constraintParent: PendingTransform, constraint: AvConstraint, parentFromNode: mat4, applyFunction: ( universeFromNode: mat4 ) => void ) { let transform = this.getTransform( globalNodeId ); transform.update( [ finalParent, constraintParent ], parentFromNode, applyFunction ); transform.constraint = constraint; return transform; } updateTransformWithCompute( globalNodeId: EndpointAddr, parents: PendingTransform[], parentFromNode: mat4, applyFunction: ( universeFromNode: mat4 ) => void, computeFunction: TransformComputeFunction ) { let transform = this.getTransform( globalNodeId ); transform.update( parents, parentFromNode, applyFunction, computeFunction ); return transform; } public getHandForEpa( epa: EndpointAddr ): EHand { let transform = this.getTransform( epa ); return handFromOriginPath( transform?.getOriginPath() ); } }
the_stack
import { remote, ipcRenderer } from "electron"; import { join } from "path"; import { platform } from "os"; import { IPCResponses, IPCRequests } from "../../../shared/ipc"; import { Tools as BabylonTools, Engine, Scene, Node, Nullable, Camera, Mesh, Material } from "babylonjs"; import { ICommonMetadata, IEditorPreferences, IMaterialMetadata, IMeshMetadata, ITransformNodeMetadata } from "./types"; export class Tools { /** * Returns the current root path of the app. */ public static GetAppPath(): string { if (process.env.DEBUG) { return remote.app.getAppPath(); } if (process.env.DRIVEN_TESTS) { return process.env.DRIVEN_TESTS; } return join(remote.app.getAppPath(), "..", ".."); } /** * Normalizes the given path according to the current platform. * @param path defines the path to normalize according to the current platform. */ public static NormalizePathForCurrentPlatform(path: string): string { switch (platform()) { case "win32": return path.replace(/\//g, "\\"); default: return path; } } /** * Returns the name of the constructor of the given object. * @param object the object to return its constructor name. */ public static GetConstructorName(object: any): string { let name = (object && object.constructor) ? object.constructor.name : ""; if (name === "") { name = typeof(object); } return name; } /** * Returns the metadatas of the given node. * @param node defines the reference to the node to get its metadatas. */ public static GetNodeMetadata(node: Node): ICommonMetadata { node.metadata = node.metadata ?? { }; return node.metadata; } /** * Returns the metadatas of the given mesh. * @param mesh defines the reference to the mesh to get its metadatas. */ public static GetMeshMetadata(mesh: Mesh): IMeshMetadata { return this.GetNodeMetadata(mesh) as IMeshMetadata; } /** * Returns the metadatas of the given transform node. * @param transformNode defines the reference to the transform node to get its metadatas. */ public static GetTransformNodeMetadata(transformNode: Mesh): ITransformNodeMetadata { return this.GetNodeMetadata(transformNode) as ITransformNodeMetadata; } /** * Returns the metadatas of the given material. * @param material defines the reference to the material to get its metadatas. */ public static GetMaterialMetadata(material: Material): IMaterialMetadata { material.metadata = material.metadata ?? { }; return material.metadata; } /** * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523 * Be aware Math.random() could cause collisions, but: * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide" */ public static RandomId(): string { return BabylonTools.RandomId(); } /** * Returns all the scene nodes of the given scene. * @param scene the scene containing the nodes to get. */ public static getAllSceneNodes(scene: Scene): Node[] { return (scene.meshes as Node[]) .concat(scene.lights as Node[]) .concat(scene.cameras as Node[]) .concat(scene.transformNodes as Node[]); } /** * Returns wether or not the given element is a child (recursively) of the given parent. * @param element the element being possibily a child of the given parent. * @param parent the parent to check. */ public static IsElementChildOf(element: HTMLElement, parent: HTMLElement): boolean { while (element.parentElement) { if (element === parent) { return true; } element = element.parentElement; } return false; } /** * Waits until the given timeMs value is reached. * @param timeMs the time in milliseconds to wait. */ public static Wait(timeMs: number): Promise<void> { return new Promise<void>((resolve) => setTimeout(() => resolve(), timeMs)); } /** * Returns the given array by keeping only distinct values. * @param array the array to filter. */ public static Distinct<T>(array: T[]): T[] { const unique = (value: T, index: number, self: T[]) => self.indexOf(value) === index; return array.filter(unique); } /** * Sorts the given array alphabetically. * @param array defines the array containing the elements to sort alphabetically. * @param property in case of an array of objects, this property will be used to get the right value to sort. */ public static SortAlphabetically(array: any[], property?: string): any[] { array.sort((a, b) => { a = property ? a[property] : a; b = property ? b[property] : b; a = a.toUpperCase(); b = b.toUpperCase(); return (a < b) ? -1 : (a > b) ? 1 : 0; }); return array; } /** * Deeply clones the given object. * @param object the object reference to clone. * @warning take care of cycle dependencies! */ public static CloneObject<T>(object: T): T { if (!object) { return object; } return JSON.parse(JSON.stringify(object)); } /** * Returns the property of the given object at the given path.. * @param object defines the object reference containing the property to get. * @param path defines the path of the property to get; */ public static GetProperty<T>(object: any, path: string): T { const split = path.split("."); for (let i = 0; i < split.length; i++) { object = object[split[i]]; } return object; } /** * Returns the effective property of the given object at the given path.. * @param object defines the object reference containing the property to get. * @param path the path of the property to get. */ public static GetEffectiveProperty<T> (object: any, path: string): T { const split = path.split("."); for (let i = 0; i < split.length - 1; i++) { object = object[split[i]]; } return object; } /** * Returns the saved editor preferences (zoom, etc.). */ public static GetEditorPreferences(): IEditorPreferences { const settings = JSON.parse(localStorage.getItem("babylonjs-editor-preferences") ?? "{ }") as IEditorPreferences; return settings; } /** * Creates a screenshot of the current scene. * @param engine the engine used to render the scene to take as screenshot. * @param camera the camera that should be used for the screenshot. */ public static async CreateScreenshot(engine: Engine, camera: Camera): Promise<string> { return BabylonTools.CreateScreenshotAsync(engine, camera, { width: 3840, height: 2160, }, "image/png"); } /** * Shows the open file dialog and returns the selected file. */ public static async ShowNativeOpenFileDialog(): Promise<File> { const files = await this._ShowOpenFileDialog(false); return files[0]; } /** * Shows the open multiple files dialog and returns the selected files. */ public static async ShowNativeOpenMultipleFileDialog(): Promise<File[]> { return this._ShowOpenFileDialog(true); } /** * Shows the open file dialog. */ private static async _ShowOpenFileDialog(multiple: boolean): Promise<File[]> { return new Promise<File[]>((resolve, reject) => { const input = document.createElement("input"); input.type = "file"; input.multiple = multiple; input.addEventListener("change", () => { input.remove(); if (input.files?.length) { const files: File[] = []; for (let i = 0; i < input.files.length; i++) { files.push(input.files.item(i)!); } return resolve(files); } reject("User decided to not choose any files."); }); input.click(); }); } /** * Returns the extension attached to the given mime type. * @param mimeType the mitype to check. */ public static GetExtensionFromMimeType (mimeType: string): string { switch (mimeType.toLowerCase()) { case "image/png": return ".png"; case "image/jpg": return ".jpg"; case "image/jpeg": return ".jpeg"; case "image/bmp": return ".bmp"; default: return ".png"; } } /** * Reads the given file as array buffer. * @param file the file to read and return its content as array buffer. */ public static ReadFileAsArrayBuffer(file: File | Blob): Promise<ArrayBuffer> { return new Promise<ArrayBuffer>((resolve, reject) => { BabylonTools.ReadFile(file as File, (d) => resolve(d), undefined, true, (err) => reject(err)); }); } /** * Loads a file from a url. * @param url the file url to load. * @param useArrayBuffer defines a boolean indicating that date must be returned as ArrayBuffer. * @param onProgress callback called while file is loading (if the server supports this mode). */ public static async LoadFile<T = string | ArrayBuffer>(url: string, useArrayBuffer: boolean, onProgress?: (data: any) => void): Promise<T> { return new Promise<T>((resolve, reject) => { BabylonTools.LoadFile(url, (d) => resolve(d as unknown as T), onProgress, undefined, useArrayBuffer, (_, e) => reject(e)); }); } /** * Opens the save dialog and returns the selected path. * @param path optional path where to open the save dialog. */ public static async ShowSaveDialog(path: Nullable<string> = null): Promise<string> { return new Promise<string>((resolve, reject) => { ipcRenderer.once(IPCResponses.OpenDirectoryDialog, (_, path) => resolve(path)); ipcRenderer.once(IPCResponses.CancelOpenFileDialog, () => reject("User decided to not save any file.")); ipcRenderer.send(IPCRequests.OpenDirectoryDialog, "Open Babylon.JS Editor Project", path ?? ""); }); } /** * Opens the open-file dialog and returns the selected path. * @param path the path where to start the dialog. */ public static async ShowOpenFileDialog(title: string, path: Nullable<string> = null): Promise<string> { return new Promise<string>((resolve, reject) => { ipcRenderer.once(IPCResponses.OpenFileDialog, (_, path) => resolve(path)); ipcRenderer.once(IPCResponses.CancelOpenFileDialog, () => reject("User decided to not save any file.")); ipcRenderer.send(IPCRequests.OpenFileDialog, title, path ?? ""); }); } /** * Opens the save file dialog and returns the selected path. * @param title the title of the save file dialog. * @param path optional path where to open the save dialog. */ public static async ShowSaveFileDialog(title: Nullable<string>, path: Nullable<string> = null): Promise<string> { return new Promise<string>((resolve, reject) => { ipcRenderer.once(IPCResponses.SaveFileDialog, (_, path) => resolve(path)); ipcRenderer.once(IPCResponses.CancelSaveFileDialog, () => reject("User decided to not save any file.")); ipcRenderer.send(IPCRequests.SaveFileDialog, title ?? "Save File", path ?? ""); }); } }
the_stack
import { Component, OnInit, ViewChild, AfterViewInit, OnDestroy, Input, ChangeDetectorRef } from '@angular/core'; import { Router } from '@angular/router'; import { FormGroup } from '@angular/forms'; import { NbDialogRef, NbStepperComponent } from '@nebular/theme'; import { ICandidate, ICandidateInterview, IEmployee, IDateRange, ICandidatePersonalQualities, ICandidateTechnologies, IOrganization } from '@gauzy/contracts'; import { filter, tap } from 'rxjs/operators'; import { firstValueFrom } from 'rxjs'; import { UntilDestroy, untilDestroyed } from '@ngneat/until-destroy'; import { CandidateInterviewersService, CandidateInterviewService, CandidatePersonalQualitiesService, CandidatesService, CandidateStore, CandidateTechnologiesService, EmployeesService, ErrorHandlingService, Store } from '../../../@core/services'; import { CandidateCriterionsFormComponent } from './candidate-criterions-form/candidate-criterions-form.component'; import { CandidateInterviewFormComponent } from './candidate-interview-form/candidate-interview-form.component'; import { CandidateNotificationFormComponent } from './candidate-notification-form/candidate-notification-form.component'; @UntilDestroy({ checkProperties: true }) @Component({ selector: 'ga-candidate-interview-mutation', templateUrl: 'candidate-interview-mutation.component.html', styleUrls: ['candidate-interview-mutation.component.scss'] }) export class CandidateInterviewMutationComponent implements AfterViewInit, OnInit, OnDestroy { @Input() editData: ICandidateInterview; @Input() selectedCandidate: ICandidate = null; @Input() interviewId = null; @Input() isCalendar: boolean; /* * Getter & Setter for date range */ _selectedRangeCalendar: IDateRange; get selectedRangeCalendar(): IDateRange { return this._selectedRangeCalendar; } @Input() set selectedRangeCalendar(value: IDateRange) { this._selectedRangeCalendar = value; } /* * Getter & Setter for header title */ _headerTitle: string; get headerTitle(): string { return this._headerTitle; } @Input() set headerTitle(value: string) { this._headerTitle = value; } /* * Getter & Setter for interviews */ _interviews: ICandidateInterview[] = []; get interviews(): ICandidateInterview[] { return this._interviews; } @Input() set interviews(value: ICandidateInterview[]) { this._interviews = value; } @ViewChild('stepper') stepper: NbStepperComponent; @ViewChild('candidateCriterionsForm') candidateCriterionsForm: CandidateCriterionsFormComponent; @ViewChild('candidateInterviewForm') candidateInterviewForm: CandidateInterviewFormComponent; @ViewChild('candidateNotificationForm') candidateNotificationForm: CandidateNotificationFormComponent; form: FormGroup; candidateForm: FormGroup; interviewerForm: FormGroup; interview: any; employees: IEmployee[] = []; candidates: ICandidate[] = []; selectedInterviewers: string[] = []; criterionsId = null; isTitleExist = false; personalQualities: ICandidatePersonalQualities[] = null; technologies: ICandidateTechnologies[]; selectedCandidateId: string; organization: IOrganization; constructor( protected readonly dialogRef: NbDialogRef<CandidateInterviewMutationComponent>, protected readonly employeesService: EmployeesService, protected readonly store: Store, private readonly cdRef: ChangeDetectorRef, private readonly candidateInterviewService: CandidateInterviewService, protected readonly candidatesService: CandidatesService, private readonly errorHandler: ErrorHandlingService, private readonly candidateInterviewersService: CandidateInterviewersService, private readonly candidateTechnologiesService: CandidateTechnologiesService, private readonly candidatePersonalQualitiesService: CandidatePersonalQualitiesService, private readonly router: Router, private readonly candidateStore: CandidateStore ) {} async ngOnInit() { this.store.selectedOrganization$ .pipe( filter((organization: IOrganization) => !!organization), tap((organization: IOrganization) => this.organization = organization), tap(() => this.loadCandidates()), untilDestroyed(this) ) .subscribe(); } async loadCandidates() { const { tenantId } = this.store.user; const { id: organizationId } = this.organization; this.candidates = ( await firstValueFrom(this.candidatesService.getAll(['user'], { organizationId, tenantId }) ) ).items; } titleExist(value: boolean) { this.isTitleExist = value; } async ngAfterViewInit() { this.form = this.candidateInterviewForm.form; //if editing if (this.editData) { this.form.patchValue(this.editData); this.form.patchValue({ valid: true }); this.cdRef.detectChanges(); this.candidateInterviewForm.selectedRange.end = this.editData.endTime; this.candidateInterviewForm.selectedRange.start = this.editData.startTime; } if (this.selectedRangeCalendar) { this.candidateInterviewForm.selectedRange.end = this.selectedRangeCalendar.end; this.candidateInterviewForm.selectedRange.start = this.selectedRangeCalendar.start; } } next() { this.candidateInterviewForm.loadFormData(); const interviewForm = this.candidateInterviewForm.form.value; this.selectedInterviewers = interviewForm.interviewers; this.interview = { title: this.form.get('title').value, interviewers: interviewForm.interviewers, location: this.form.get('location').value, startTime: interviewForm.startTime, endTime: interviewForm.endTime, note: this.form.get('note').value }; // if editing if (interviewForm.interviewers === null) { interviewForm.interviewers = this.candidateInterviewForm.employeeIds; } this.getEmployees(interviewForm.interviewers); } async getEmployees(employeeIds: string[]) { const { tenantId } = this.store.user; const { id: organizationId } = this.organization; const { items } = await firstValueFrom(this.employeesService .getAll(['user'], { organizationId, tenantId }) ); const employeeList = items; employeeIds.forEach((id) => { employeeList.forEach((item) => { if (id === item.id) { this.employees.push(item); } }); }); } async save() { this.employees = []; const interview: ICandidateInterview = null; let createdInterview = null; if (this.interviewId !== null) { createdInterview = this.editInterview(); } else { createdInterview = await this.createInterview(interview); this.candidateStore.loadInterviews(createdInterview); } this.closeDialog(createdInterview); } async createInterview(interview: ICandidateInterview) { const { tenantId } = this.store.user; const { id: organizationId } = this.organization; const emptyInterview = { title: '', interviewers: null, startTime: null, endTime: null, criterions: null, note: '' }; interview = await this.candidateInterviewService.create({ ...emptyInterview, candidateId: this.selectedCandidate.id, organizationId, tenantId }); this.addInterviewers(interview.id, this.selectedInterviewers); this.candidateCriterionsForm.loadFormData(); const criterionsForm = this.candidateCriterionsForm.form.value; this.addCriterions( interview.id, criterionsForm.selectedTechnologies, criterionsForm.selectedQualities ); try { const createdInterview = await this.candidateInterviewService.update( interview.id, { title: this.interview.title, location: this.interview.location, startTime: this.interview.startTime, endTime: this.interview.endTime, note: this.interview.note } ); return createdInterview; } catch (error) { this.errorHandler.handleError(error); } } async addInterviewers(interviewId: string, employeeIds: string[]) { try { const { tenantId } = this.store.user; const { id: organizationId } = this.organization; await this.candidateInterviewersService.createBulk({ interviewId, employeeIds, organizationId, tenantId }); } catch (error) { this.errorHandler.handleError(error); } } async addCriterions(interviewId: string, tech?: string[], qual?: string[]) { try { this.technologies = await this.candidateTechnologiesService.createBulk( interviewId, tech ); this.personalQualities = await this.candidatePersonalQualitiesService.createBulk( interviewId, qual ); } catch (error) { this.errorHandler.handleError(error); } } async editInterview() { let deletedIds = []; let newIds = []; let updatedInterview; const oldIds = this.editData.interviewers.map( (item) => item.employeeId ); if (this.interview.interviewers) { deletedIds = oldIds.filter( (item) => !this.interview.interviewers.includes(item) ); newIds = this.interview.interviewers.filter( (item: string) => !oldIds.includes(item) ); } try { this.updateCriterions( this.editData.personalQualities, this.editData.technologies ); updatedInterview = await this.candidateInterviewService.update( this.interviewId, { title: this.interview.title, location: this.interview.location, startTime: this.interview.startTime, endTime: this.interview.endTime, note: this.interview.note } ); } catch (error) { this.errorHandler.handleError(error); } await this.candidateInterviewersService.deleteBulkByEmployeeId( deletedIds ); this.addInterviewers(this.interviewId, newIds); this.interviewId = null; return updatedInterview; } async updateCriterions( qual: ICandidatePersonalQualities[], tech: ICandidateTechnologies[] ) { this.candidateCriterionsForm.loadFormData(); const criterionsForm = this.candidateCriterionsForm.form.value; const techCriterions = this.setCriterions( tech, criterionsForm.selectedTechnologies ); const qualCriterions = this.setCriterions( qual, criterionsForm.selectedQualities ); //CREATE NEW if (techCriterions.createInput) { try { await this.candidateTechnologiesService.createBulk( this.editData.id, techCriterions.createInput ); } catch (error) { this.errorHandler.handleError(error); } } if (qualCriterions.createInput) { try { await this.candidatePersonalQualitiesService.createBulk( this.editData.id, qualCriterions.createInput ); } catch (error) { this.errorHandler.handleError(error); } } //DELETE OLD if (techCriterions.deleteInput.length > 0) { try { await this.candidateTechnologiesService.deleteBulkByInterviewId( this.editData.id, techCriterions.deleteInput ); } catch (error) { this.errorHandler.handleError(error); } } if (qualCriterions.deleteInput.length > 0) { try { await this.candidatePersonalQualitiesService.deleteBulkByInterviewId( this.editData.id, qualCriterions.deleteInput ); } catch (error) { this.errorHandler.handleError(error); } } } setCriterions( data: ICandidateTechnologies[] | ICandidatePersonalQualities[], selectedItems: string[] ) { const createInput = []; const deleteInput = []; const dataName = []; if (selectedItems) { data.forEach((item) => dataName.push(item.name)); selectedItems.forEach((item) => dataName.includes(item) ? item : createInput.push(item) ); data.forEach((item) => !selectedItems.includes(item.name) ? item : deleteInput.push(item) ); return { createInput: createInput, deleteInput: deleteInput }; } } async onCandidateSelected(id: string) { const candidate = await this.candidatesService.getCandidateById(id, [ 'user' ]); this.selectedCandidate = candidate; } closeDialog(interview: ICandidateInterview = null) { this.dialogRef.close(interview); } previous() { this.candidateInterviewForm.form.patchValue(this.interview); this.candidateInterviewForm.form.patchValue({ valid: true }); this.employees = []; } route() { this.dialogRef.close(); this.router.navigate([ '/pages/employees/candidates/interviews/criterion' ]); } ngOnDestroy() {} }
the_stack
import { Config } from '../config' import { OrgTypeEnum } from '../model/type/config.type' import { InfraRunner, InfraRunnerResultType } from './infra/InfraRunner.interface' import { AbstractInstance } from './Instance.abstract' interface OptionsType { tag?: string volumes?: string[] network?: string } export default class FabricInstance extends AbstractInstance { private orgAddress: string constructor (config: Config, infra: InfraRunner<InfraRunnerResultType>, orgAddress?: string) { super(config, infra) this.orgAddress = orgAddress || `${this.config.hostname}.${this.config.orgDomainName}` } private async infraRunCommand ( commands: string[], peerOrOrderer?: OrgTypeEnum, env?: string[], volumes?: string[], options?: OptionsType, ) { return await this.infra.runCommand({ image: 'hyperledger/fabric-tools', tag: options?.tag || this.config.fabricVersion.tools, network: this.config.networkName, volumes: options?.volumes || [`${this.hostPath}/${this.config.networkName}:${this.dockerPath}`].concat(volumes || []), envFile: `${this.hostPath}/${this.config.networkName}/env/${peerOrOrderer}-${this.orgAddress}.env`, env: env, commands: commands, }) } public async createChannel ( channelName: string, orderer: string, options?: OptionsType, ): Promise<InfraRunnerResultType> { return await this.infraRunCommand( [ 'peer', 'channel', 'create', '--channelID', channelName, '--file', `${this.dockerPath}/channel-artifacts/${channelName}/${channelName}.tx`, '--outputBlock', `${this.dockerPath}/channel-artifacts/${channelName}/${channelName}.block`, '--orderer', orderer, '--ordererTLSHostnameOverride', orderer.split(':')[0], '--tls', '--cafile', `${this.dockerPath}/tlsca/${orderer.split(':')[0]}/ca.crt`, ], OrgTypeEnum.PEER, undefined, undefined, options) } public async joinChannel ( channelName: string, options?: OptionsType, ): Promise<InfraRunnerResultType> { return await this.infraRunCommand( [ 'peer', 'channel', 'join', '--blockpath', `${this.dockerPath}/channel-artifacts/${channelName}/${channelName}.block`, ], OrgTypeEnum.PEER, undefined, undefined, options) } public async updateAnchorPeer ( channelName: string, orderer: string, orgName: string = this.config.orgName, options?: OptionsType, ): Promise<InfraRunnerResultType> { return await this.infraRunCommand( [ 'peer', 'channel', 'update', '--channelID', channelName, '--file', `${this.dockerPath}/channel-artifacts/${channelName}/${orgName}Anchors.tx`, '--orderer', orderer, '--ordererTLSHostnameOverride', orderer.split(':')[0], '--tls', '--cafile', `${this.dockerPath}/tlsca/${orderer.split(':')[0]}/ca.crt`, ], OrgTypeEnum.PEER, undefined, undefined, options) } // * get joined channel of a peer public async listJoinedChannel ( options?: OptionsType, ): Promise<InfraRunnerResultType> { return await this.infraRunCommand( [ 'peer', 'channel', 'list', ], OrgTypeEnum.PEER, undefined, undefined, options) } public async signConfigTx ( signType: OrgTypeEnum, channelName: string, input: string, options?: OptionsType, ): Promise<InfraRunnerResultType> { return await this.infraRunCommand( [ 'peer', 'channel', 'signconfigtx', '-f', `${this.dockerPath}/channel-artifacts/${channelName}/${input}.pb`, ], signType, undefined, undefined, options) } public async updateChannelConfig ( signType: OrgTypeEnum, orderer: string, channelName: string, input: string, options?: OptionsType, ): Promise<InfraRunnerResultType> { return await this.infraRunCommand( [ 'peer', 'channel', 'update', '-c', channelName, '-f', `${this.dockerPath}/channel-artifacts/${channelName}/${input}.pb`, '--orderer', orderer, '--ordererTLSHostnameOverride', orderer.split(':')[0], '--tls', '--cafile', `${this.dockerPath}/tlsca/${orderer.split(':')[0]}/ca.crt`, ], signType, undefined, undefined, options) } public async installChaincode ( chaincodeLabel: string, options?: OptionsType, ): Promise<InfraRunnerResultType> { return await this.infraRunCommand( [ 'peer', 'lifecycle', 'chaincode', 'install', `${this.dockerPath}/chaincode/${chaincodeLabel}.tar.gz`, ], OrgTypeEnum.PEER, undefined, undefined, options) } public async queryInstalledChaincode ( options?: OptionsType, ): Promise<InfraRunnerResultType> { return await this.infraRunCommand( [ 'peer', 'lifecycle', 'chaincode', 'queryinstalled', ], OrgTypeEnum.PEER, undefined, undefined, options) } public async approveChaincode ( channelName: string, chaincodeName: string, chaincodeVersion: number, packageId: string, initRequired: boolean, orderer: string, options?: OptionsType, ): Promise<InfraRunnerResultType> { return await this.infraRunCommand( [ 'peer', 'lifecycle', 'chaincode', 'approveformyorg', '--channelID', channelName, '--name', chaincodeName, '--version', chaincodeVersion.toString(), '--package-id', packageId, '--sequence', chaincodeVersion.toString(), '--orderer', orderer, '--ordererTLSHostnameOverride', orderer.split(':')[0], '--tls', '--cafile', `${this.dockerPath}/tlsca/${orderer.split(':')[0]}/ca.crt`, ] .concat(initRequired ? ['--init-required'] : []), OrgTypeEnum.PEER, undefined, undefined, options) } public async commitChaincode ( channelName: string, chaincodeName: string, chaincodeVersion: number, initRequired: boolean, orderer: string, peerAddresses: string[], options?: OptionsType, ): Promise<InfraRunnerResultType> { return await this.infraRunCommand( [ 'peer', 'lifecycle', 'chaincode', 'commit', '--channelID', channelName, '--name', chaincodeName, '--version', chaincodeVersion.toString(), '--sequence', chaincodeVersion.toString(), '--orderer', orderer, '--ordererTLSHostnameOverride', orderer.split(':')[0], '--tls', '--cafile', `${this.dockerPath}/tlsca/${orderer.split(':')[0]}/ca.crt`, ] .concat(initRequired ? ['--init-required'] : []).concat(...peerAddresses.map(peerAddress => ['--peerAddresses', peerAddress, '--tlsRootCertFiles', `${this.dockerPath}/tlsca/${peerAddress.split(':')[0]}/ca.crt`])), OrgTypeEnum.PEER, undefined, undefined, options) } public async invokeChaincode (channelName: string, chaincodeName: string, chaincodeFunction: string, args: string[], isInit: boolean, orderer: string, peerAddresses: string[], options?: OptionsType, ): Promise<InfraRunnerResultType> { return await this.infraRunCommand( [ 'peer', 'chaincode', 'invoke', '--channelID', channelName, '--name', chaincodeName, '--ctor', JSON.stringify({ function: chaincodeFunction, args: args.map(x => x.toString()) }), '--orderer', orderer, '--ordererTLSHostnameOverride', orderer.split(':')[0], '--tls', '--cafile', `${this.dockerPath}/tlsca/${orderer.split(':')[0]}/ca.crt`, '--waitForEvent', ] .concat(isInit ? ['--isInit'] : []) .concat(...peerAddresses.map(peerAddress => ['--peerAddresses', peerAddress, '--tlsRootCertFiles', `${this.dockerPath}/tlsca/${peerAddress.split(':')[0]}/ca.crt`])), OrgTypeEnum.PEER, undefined, undefined, options) } public async queryChaincode ( channelName: string, chaincodeName: string, chaincodeFunction: string, args: string[], options?: OptionsType, ): Promise<InfraRunnerResultType> { return await this.infraRunCommand( [ 'peer', 'chaincode', 'query', '--channelID', channelName, '--name', chaincodeName, '--ctor', JSON.stringify({ function: chaincodeFunction, args: args.map(x => x.toString()) }), ], OrgTypeEnum.PEER, undefined, undefined, options) } public async queryCommittedChaincode ( channelName: string, options?: OptionsType): Promise<InfraRunnerResultType> { return await this.infraRunCommand( [ 'peer', 'lifecycle', 'chaincode', 'querycommitted', '--channelID', channelName, ], OrgTypeEnum.PEER, undefined, undefined, options) } // * get AnchorPeers and Orderer of a channel public async fetchChannelConfig ( channelName: string, outputFileName: string, outputExtension: 'pb' | 'block' = 'block', orderer: string | undefined, signType: OrgTypeEnum, options?: OptionsType, ): Promise<InfraRunnerResultType> { return await this.infraRunCommand( [ 'peer', 'channel', 'fetch', 'config', `${this.dockerPath}/channel-artifacts/${channelName}/${outputFileName}.${outputExtension}`, '--channelID', channelName, ].concat( orderer ? [ '--orderer', orderer, '--ordererTLSHostnameOverride', orderer.split(':')[0], '--tls', '--cafile', `${this.dockerPath}/tlsca/${orderer.split(':')[0]}/ca.crt`, ] : [], ), signType, undefined, undefined, options) } // * get channel block 0 public async fetchChannelBlock0 ( channelName: string, fileName: string, outputExtension: 'pb' | 'block' = 'block', orderer: string | undefined, signType: OrgTypeEnum, options?: OptionsType): Promise<InfraRunnerResultType> { return await this.infraRunCommand( [ 'peer', 'channel', 'fetch', '0', `${this.dockerPath}/channel-artifacts/${channelName}/${fileName}.${outputExtension}`, '--channelID', channelName, ].concat( orderer ? [ '--orderer', orderer, '--ordererTLSHostnameOverride', orderer.split(':')[0], '--tls', '--cafile', `${this.dockerPath}/tlsca/${orderer.split(':')[0]}/ca.crt`, ] : [], ), signType, undefined, undefined, options) } // * fetch channel newest block public async fetchChannelNewestBlock ( channelName: string, fileName: string, outputExtension: 'pb' | 'block' = 'block', orderer: string | undefined, signType: OrgTypeEnum, options?: OptionsType): Promise<InfraRunnerResultType> { return await this.infraRunCommand( [ 'peer', 'channel', 'fetch', 'newest', `${this.dockerPath}/channel-artifacts/${channelName}/${fileName}.${outputExtension}`, '--channelID', channelName, ].concat( orderer ? [ '--orderer', orderer, '--ordererTLSHostnameOverride', orderer.split(':')[0], '--tls', '--cafile', `${this.dockerPath}/tlsca/${orderer.split(':')[0]}/ca.crt`, ] : [], ), signType, undefined, undefined, options) } }
the_stack
import { IExecuteFunctions, ILoadOptionsFunctions, } from 'n8n-core'; import { IDataObject, INodeExecutionData, INodePropertyOptions, INodeType, INodeTypeDescription, NodeOperationError, } from 'n8n-workflow'; import { clientFields, clientOperations, } from './ClientDescription'; import { contactFields, contactOperations, } from './ContactDescription'; import { companyOperations, } from './CompanyDescription'; import { estimateFields, estimateOperations, } from './EstimateDescription'; import { expenseFields, expenseOperations, } from './ExpenseDescription'; import { getAllResource, harvestApiRequest, } from './GenericFunctions'; import { invoiceFields, invoiceOperations, } from './InvoiceDescription'; import { projectFields, projectOperations, } from './ProjectDescription'; import { taskFields, taskOperations, } from './TaskDescription'; import { timeEntryFields, timeEntryOperations, } from './TimeEntryDescription'; import { userFields, userOperations, } from './UserDescription'; export class Harvest implements INodeType { description: INodeTypeDescription = { displayName: 'Harvest', name: 'harvest', icon: 'file:harvest.png', group: ['input'], version: 1, subtitle: '={{$parameter["operation"] + ": " + $parameter["resource"]}}', description: 'Access data on Harvest', defaults: { name: 'Harvest', }, inputs: ['main'], outputs: ['main'], credentials: [ { name: 'harvestApi', required: true, displayOptions: { show: { authentication: [ 'accessToken', ], }, }, }, { name: 'harvestOAuth2Api', required: true, displayOptions: { show: { authentication: [ 'oAuth2', ], }, }, }, ], properties: [ { displayName: 'Authentication', name: 'authentication', type: 'options', options: [ { name: 'Access Token', value: 'accessToken', }, { name: 'OAuth2', value: 'oAuth2', }, ], default: 'accessToken', description: 'Method of authentication.', }, { displayName: 'Resource', name: 'resource', type: 'options', options: [ { name: 'Client', value: 'client', }, { name: 'Company', value: 'company', }, { name: 'Contact', value: 'contact', }, { name: 'Estimate', value: 'estimate', }, { name: 'Expense', value: 'expense', }, { name: 'Invoice', value: 'invoice', }, { name: 'Project', value: 'project', }, { name: 'Task', value: 'task', }, { name: 'Time Entries', value: 'timeEntry', }, { name: 'User', value: 'user', }, ], default: 'task', description: 'The resource to operate on.', }, // operations ...clientOperations, ...companyOperations, ...contactOperations, ...estimateOperations, ...expenseOperations, ...invoiceOperations, ...projectOperations, ...taskOperations, ...timeEntryOperations, ...userOperations, { displayName: 'Account ID', name: 'accountId', type: 'options', required: true, typeOptions: { loadOptionsMethod: 'getAccounts', }, default: '', }, // fields ...clientFields, ...contactFields, ...estimateFields, ...expenseFields, ...invoiceFields, ...projectFields, ...taskFields, ...timeEntryFields, ...userFields, ], }; methods = { loadOptions: { // Get all the available accounts to display them to user so that he can // select them easily async getAccounts(this: ILoadOptionsFunctions): Promise<INodePropertyOptions[]> { const returnData: INodePropertyOptions[] = []; const { accounts } = await harvestApiRequest.call(this, 'GET', {}, '', {}, {}, 'https://id.getharvest.com/api/v2/accounts'); for (const account of accounts) { const accountName = account.name; const accountId = account.id; returnData.push({ name: accountName, value: accountId, }); } return returnData; }, }, }; async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> { const items = this.getInputData(); const returnData: IDataObject[] = []; const resource = this.getNodeParameter('resource', 0) as string; const operation = this.getNodeParameter('operation', 0) as string; let endpoint = ''; let requestMethod = ''; let body: IDataObject | Buffer; let qs: IDataObject; for (let i = 0; i < items.length; i++) { try { body = {}; qs = {}; if (resource === 'timeEntry') { if (operation === 'get') { // ---------------------------------- // get // ---------------------------------- requestMethod = 'GET'; const id = this.getNodeParameter('id', i) as string; endpoint = `time_entries/${id}`; const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint); returnData.push(responseData); } else if (operation === 'getAll') { // ---------------------------------- // getAll // ---------------------------------- const responseData: IDataObject[] = await getAllResource.call(this, 'time_entries', i); returnData.push.apply(returnData, responseData); } else if (operation === 'createByStartEnd') { // ---------------------------------- // createByStartEnd // ---------------------------------- requestMethod = 'POST'; endpoint = 'time_entries'; body.project_id = this.getNodeParameter('projectId', i) as string; body.task_id = this.getNodeParameter('taskId', i) as string; body.spent_date = this.getNodeParameter('spentDate', i) as string; const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; Object.assign(body, additionalFields); const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint, body); returnData.push(responseData); } else if (operation === 'createByDuration') { // ---------------------------------- // createByDuration // ---------------------------------- requestMethod = 'POST'; endpoint = 'time_entries'; body.project_id = this.getNodeParameter('projectId', i) as string; body.task_id = this.getNodeParameter('taskId', i) as string; body.spent_date = this.getNodeParameter('spentDate', i) as string; const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; Object.assign(body, additionalFields); const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint, body); returnData.push(responseData); } else if (operation === 'delete') { // ---------------------------------- // delete // ---------------------------------- requestMethod = 'DELETE'; const id = this.getNodeParameter('id', i) as string; endpoint = `time_entries/${id}`; const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint); returnData.push(responseData); } else if (operation === 'deleteExternal') { // ---------------------------------- // deleteExternal // ---------------------------------- requestMethod = 'DELETE'; const id = this.getNodeParameter('id', i) as string; endpoint = `time_entries/${id}/external_reference`; const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint); returnData.push(responseData); } else if (operation === 'restartTime') { // ---------------------------------- // restartTime // ---------------------------------- requestMethod = 'PATCH'; const id = this.getNodeParameter('id', i) as string; endpoint = `time_entries/${id}/restart`; const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint); returnData.push(responseData); } else if (operation === 'stopTime') { // ---------------------------------- // stopTime // ---------------------------------- requestMethod = 'PATCH'; const id = this.getNodeParameter('id', i) as string; endpoint = `time_entries/${id}/stop`; const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint); returnData.push(responseData); } else if (operation === 'update') { // ---------------------------------- // update // ---------------------------------- requestMethod = 'PATCH'; const id = this.getNodeParameter('id', i) as string; endpoint = `time_entries/${id}`; const updateFields = this.getNodeParameter('updateFields', i) as IDataObject; Object.assign(body, updateFields); const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint, body); returnData.push(responseData); } else { throw new NodeOperationError(this.getNode(), `The operation "${operation}" is not known!`); } } else if (resource === 'client') { if (operation === 'get') { // ---------------------------------- // get // ---------------------------------- requestMethod = 'GET'; const id = this.getNodeParameter('id', i) as string; endpoint = `clients/${id}`; const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint); returnData.push(responseData); } else if (operation === 'getAll') { // ---------------------------------- // getAll // ---------------------------------- const responseData: IDataObject[] = await getAllResource.call(this, 'clients', i); returnData.push.apply(returnData, responseData); } else if (operation === 'create') { // ---------------------------------- // create // ---------------------------------- requestMethod = 'POST'; endpoint = 'clients'; body.name = this.getNodeParameter('name', i) as string; const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; Object.assign(body, additionalFields); const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint, body); returnData.push(responseData); } else if (operation === 'update') { // ---------------------------------- // update // ---------------------------------- requestMethod = 'PATCH'; const id = this.getNodeParameter('id', i) as string; endpoint = `clients/${id}`; const updateFields = this.getNodeParameter('updateFields', i) as IDataObject; Object.assign(qs, updateFields); const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint, body); returnData.push(responseData); } else if (operation === 'delete') { // ---------------------------------- // delete // ---------------------------------- requestMethod = 'DELETE'; const id = this.getNodeParameter('id', i) as string; endpoint = `clients/${id}`; const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint); returnData.push(responseData); } else { throw new NodeOperationError(this.getNode(), `The resource "${resource}" is not known!`); } } else if (resource === 'project') { if (operation === 'get') { // ---------------------------------- // get // ---------------------------------- requestMethod = 'GET'; const id = this.getNodeParameter('id', i) as string; endpoint = `projects/${id}`; const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint); returnData.push(responseData); } else if (operation === 'getAll') { // ---------------------------------- // getAll // ---------------------------------- const responseData: IDataObject[] = await getAllResource.call(this, 'projects', i); returnData.push.apply(returnData, responseData); } else if (operation === 'create') { // ---------------------------------- // create // ---------------------------------- requestMethod = 'POST'; endpoint = 'projects'; body.client_id = this.getNodeParameter('clientId', i) as string; body.name = this.getNodeParameter('name', i) as string; body.is_billable = this.getNodeParameter('isBillable', i) as string; body.bill_by = this.getNodeParameter('billBy', i) as string; body.budget_by = this.getNodeParameter('budgetBy', i) as string; const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; Object.assign(body, additionalFields); const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint, body); returnData.push(responseData); } else if (operation === 'update') { // ---------------------------------- // update // ---------------------------------- requestMethod = 'PATCH'; const id = this.getNodeParameter('id', i) as string; endpoint = `projects/${id}`; const updateFields = this.getNodeParameter('updateFields', i) as IDataObject; Object.assign(body, updateFields); const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint, body); returnData.push(responseData); } else if (operation === 'delete') { // ---------------------------------- // delete // ---------------------------------- requestMethod = 'DELETE'; const id = this.getNodeParameter('id', i) as string; endpoint = `projects/${id}`; const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint); returnData.push(responseData); } else { throw new NodeOperationError(this.getNode(), `The resource "${resource}" is not known!`); } } else if (resource === 'user') { if (operation === 'get') { // ---------------------------------- // get // ---------------------------------- requestMethod = 'GET'; const id = this.getNodeParameter('id', i) as string; endpoint = `users/${id}`; const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint); returnData.push(responseData); } else if (operation === 'getAll') { // ---------------------------------- // getAll // ---------------------------------- const responseData: IDataObject[] = await getAllResource.call(this, 'users', i); returnData.push.apply(returnData, responseData); } else if (operation === 'me') { // ---------------------------------- // me // ---------------------------------- requestMethod = 'GET'; endpoint = `users/me`; const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint); returnData.push(responseData); } else if (operation === 'create') { // ---------------------------------- // create // ---------------------------------- requestMethod = 'POST'; endpoint = 'users'; body.first_name = this.getNodeParameter('firstName', i) as string; body.last_name = this.getNodeParameter('lastName', i) as string; body.email = this.getNodeParameter('email', i) as string; const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; Object.assign(body, additionalFields); const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint, body); returnData.push(responseData); } else if (operation === 'update') { // ---------------------------------- // update // ---------------------------------- requestMethod = 'PATCH'; const id = this.getNodeParameter('id', i) as string; endpoint = `users/${id}`; const updateFields = this.getNodeParameter('updateFields', i) as IDataObject; Object.assign(qs, updateFields); const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint, body); returnData.push(responseData); } else if (operation === 'delete') { // ---------------------------------- // delete // ---------------------------------- requestMethod = 'DELETE'; const id = this.getNodeParameter('id', i) as string; endpoint = `users/${id}`; const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint); returnData.push(responseData); } else { throw new NodeOperationError(this.getNode(), `The resource "${resource}" is not known!`); } } else if (resource === 'contact') { if (operation === 'get') { // ---------------------------------- // get // ---------------------------------- requestMethod = 'GET'; const id = this.getNodeParameter('id', i) as string; endpoint = `contacts/${id}`; const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint); returnData.push(responseData); } else if (operation === 'getAll') { // ---------------------------------- // getAll // ---------------------------------- const responseData: IDataObject[] = await getAllResource.call(this, 'contacts', i); returnData.push.apply(returnData, responseData); } else if (operation === 'create') { // ---------------------------------- // create // ---------------------------------- requestMethod = 'POST'; endpoint = 'contacts'; body.client_id = this.getNodeParameter('clientId', i) as string; body.first_name = this.getNodeParameter('firstName', i) as string; const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; Object.assign(body, additionalFields); const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint, body); returnData.push(responseData); } else if (operation === 'update') { // ---------------------------------- // update // ---------------------------------- requestMethod = 'PATCH'; const id = this.getNodeParameter('id', i) as string; endpoint = `contacts/${id}`; const updateFields = this.getNodeParameter('updateFields', i) as IDataObject; Object.assign(qs, updateFields); const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint, body); returnData.push(responseData); } else if (operation === 'delete') { // ---------------------------------- // delete // ---------------------------------- requestMethod = 'DELETE'; const id = this.getNodeParameter('id', i) as string; endpoint = `contacts/${id}`; const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint); returnData.push(responseData); } else { throw new NodeOperationError(this.getNode(), `The resource "${resource}" is not known!`); } } else if (resource === 'company') { if (operation === 'get') { // ---------------------------------- // get // ---------------------------------- requestMethod = 'GET'; endpoint = `company`; const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint); returnData.push(responseData); } else { throw new NodeOperationError(this.getNode(), `The resource "${resource}" is not known!`); } } else if (resource === 'task') { if (operation === 'get') { // ---------------------------------- // get // ---------------------------------- requestMethod = 'GET'; const id = this.getNodeParameter('id', i) as string; endpoint = `tasks/${id}`; const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint); returnData.push(responseData); } else if (operation === 'getAll') { // ---------------------------------- // getAll // ---------------------------------- const responseData: IDataObject[] = await getAllResource.call(this, 'tasks', i); returnData.push.apply(returnData, responseData); } else if (operation === 'create') { // ---------------------------------- // create // ---------------------------------- requestMethod = 'POST'; endpoint = 'tasks'; body.name = this.getNodeParameter('name', i) as string; const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; Object.assign(body, additionalFields); const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint, body); returnData.push(responseData); } else if (operation === 'update') { // ---------------------------------- // update // ---------------------------------- requestMethod = 'PATCH'; const id = this.getNodeParameter('id', i) as string; endpoint = `tasks/${id}`; const updateFields = this.getNodeParameter('updateFields', i) as IDataObject; Object.assign(qs, updateFields); const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint, body); returnData.push(responseData); } else if (operation === 'delete') { // ---------------------------------- // delete // ---------------------------------- requestMethod = 'DELETE'; const id = this.getNodeParameter('id', i) as string; endpoint = `tasks/${id}`; const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint); returnData.push(responseData); } else { throw new NodeOperationError(this.getNode(), `The resource "${resource}" is not known!`); } } else if (resource === 'invoice') { if (operation === 'get') { // ---------------------------------- // get // ---------------------------------- requestMethod = 'GET'; const id = this.getNodeParameter('id', i) as string; endpoint = `invoices/${id}`; const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint); returnData.push(responseData); } else if (operation === 'getAll') { // ---------------------------------- // getAll // ---------------------------------- const responseData: IDataObject[] = await getAllResource.call(this, 'invoices', i); returnData.push.apply(returnData, responseData); } else if (operation === 'create') { // ---------------------------------- // create // ---------------------------------- requestMethod = 'POST'; endpoint = 'invoices'; body.client_id = this.getNodeParameter('clientId', i) as string; const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; Object.assign(body, additionalFields); const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint, body); returnData.push(responseData); } else if (operation === 'update') { // ---------------------------------- // update // ---------------------------------- requestMethod = 'PATCH'; const id = this.getNodeParameter('id', i) as string; endpoint = `invoices/${id}`; const updateFields = this.getNodeParameter('updateFields', i) as IDataObject; Object.assign(qs, updateFields); const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint, body); returnData.push(responseData); } else if (operation === 'delete') { // ---------------------------------- // delete // ---------------------------------- requestMethod = 'DELETE'; const id = this.getNodeParameter('id', i) as string; endpoint = `invoices/${id}`; const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint); returnData.push(responseData); } else { throw new NodeOperationError(this.getNode(), `The resource "${resource}" is not known!`); } } else if (resource === 'expense') { if (operation === 'get') { // ---------------------------------- // get // ---------------------------------- requestMethod = 'GET'; const id = this.getNodeParameter('id', i) as string; endpoint = `expenses/${id}`; const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint); returnData.push(responseData); } else if (operation === 'getAll') { // ---------------------------------- // getAll // ---------------------------------- const responseData: IDataObject[] = await getAllResource.call(this, 'expenses', i); returnData.push.apply(returnData, responseData); } else if (operation === 'create') { // ---------------------------------- // create // ---------------------------------- requestMethod = 'POST'; endpoint = 'expenses'; body.project_id = this.getNodeParameter('projectId', i) as string; body.expense_category_id = this.getNodeParameter('expenseCategoryId', i) as string; body.spent_date = this.getNodeParameter('spentDate', i) as string; const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; Object.assign(body, additionalFields); const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint, body); returnData.push(responseData); } else if (operation === 'update') { // ---------------------------------- // update // ---------------------------------- requestMethod = 'PATCH'; const id = this.getNodeParameter('id', i) as string; endpoint = `expenses/${id}`; const updateFields = this.getNodeParameter('updateFields', i) as IDataObject; Object.assign(qs, updateFields); const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint, body); returnData.push(responseData); } else if (operation === 'delete') { // ---------------------------------- // delete // ---------------------------------- requestMethod = 'DELETE'; const id = this.getNodeParameter('id', i) as string; endpoint = `expenses/${id}`; const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint); returnData.push(responseData); } else { throw new NodeOperationError(this.getNode(), `The resource "${resource}" is not known!`); } } else if (resource === 'estimate') { if (operation === 'get') { // ---------------------------------- // get // ---------------------------------- requestMethod = 'GET'; const id = this.getNodeParameter('id', i) as string; endpoint = `estimates/${id}`; const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint); returnData.push(responseData); } else if (operation === 'getAll') { // ---------------------------------- // getAll // ---------------------------------- const responseData: IDataObject[] = await getAllResource.call(this, 'estimates', i); returnData.push.apply(returnData, responseData); } else if (operation === 'create') { // ---------------------------------- // create // ---------------------------------- requestMethod = 'POST'; endpoint = 'estimates'; body.client_id = this.getNodeParameter('clientId', i) as string; const additionalFields = this.getNodeParameter('additionalFields', i) as IDataObject; Object.assign(body, additionalFields); const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint, body); returnData.push(responseData); } else if (operation === 'update') { // ---------------------------------- // update // ---------------------------------- requestMethod = 'PATCH'; const id = this.getNodeParameter('id', i) as string; endpoint = `estimates/${id}`; const updateFields = this.getNodeParameter('updateFields', i) as IDataObject; Object.assign(qs, updateFields); const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint, body); returnData.push(responseData); } else if (operation === 'delete') { // ---------------------------------- // delete // ---------------------------------- requestMethod = 'DELETE'; const id = this.getNodeParameter('id', i) as string; endpoint = `estimates/${id}`; const responseData = await harvestApiRequest.call(this, requestMethod, qs, endpoint); returnData.push(responseData); } else { throw new NodeOperationError(this.getNode(), `The resource "${resource}" is not known!`); } } else { throw new NodeOperationError(this.getNode(), `The resource "${resource}" is not known!`); } } catch (error) { if (this.continueOnFail()) { returnData.push({ error: error.message }); continue; } throw error; } } return [this.helpers.returnJsonArray(returnData)]; } }
the_stack
import * as util from 'util'; import path = require('path'); import * as BBPromise from 'bluebird'; import * as _ from 'lodash'; // Local import { AsyncCreatable } from '@salesforce/kit'; import { Lifecycle, Logger, Messages, SfdxError, SfdxProject } from '@salesforce/core'; import { MdRetrieveApi } from '../mdapi/mdapiRetrieveApi'; import messagesApi = require('../messages'); import { createOutputDir, cleanupOutputDir } from './sourceUtil'; import * as ManifestCreateApi from './manifestCreateApi'; import SourceMetadataMemberRetrieveHelper = require('./sourceMetadataMemberRetrieveHelper'); import * as syncCommandHelper from './syncCommandHelper'; import MetadataRegistry = require('./metadataRegistry'); import { BundleMetadataType } from './metadataTypeImpl/bundleMetadataType'; import * as pathUtil from './sourcePathUtil'; import { SourceWorkspaceAdapter } from './sourceWorkspaceAdapter'; import { AggregateSourceElements } from './aggregateSourceElements'; import { SrcStatusApi } from './srcStatusApi'; import { RemoteSourceTrackingService } from './remoteSourceTrackingService'; import { WorkspaceElementObj } from './workspaceElement'; import { SourceLocations } from './sourceLocations'; import { SourceResult, MetadataResult } from './sourceHooks'; export class MdapiPullApi extends AsyncCreatable<MdapiPullApi.Options> { public smmHelper: SourceMetadataMemberRetrieveHelper; public remoteSourceTrackingService: RemoteSourceTrackingService; public obsoleteNames: any[]; public scratchOrg: any; public swa: SourceWorkspaceAdapter; private readonly messages: any; private logger!: Logger; private force: any; private statusApi!: SrcStatusApi; public constructor(options: MdapiPullApi.Options) { super(options); this.swa = options.adapter; if (this.swa) { this.smmHelper = new SourceMetadataMemberRetrieveHelper(this.swa); } this.scratchOrg = options.org; this.force = this.scratchOrg.force; this.messages = messagesApi(this.force.config.getLocale()); this.obsoleteNames = []; } protected async init(): Promise<void> { this.remoteSourceTrackingService = await RemoteSourceTrackingService.getInstance({ username: this.scratchOrg.name, }); this.logger = await Logger.child(this.constructor.name); if (!this.swa) { const options: SourceWorkspaceAdapter.Options = { org: this.scratchOrg, metadataRegistryImpl: MetadataRegistry, defaultPackagePath: this.force.getConfig().getAppConfig().defaultPackagePath, }; this.swa = await SourceWorkspaceAdapter.create(options); this.smmHelper = new SourceMetadataMemberRetrieveHelper(this.swa); } } async doPull(options) { // Remove this when pull has been modified to support the new mdapi wait functionality; if (isNaN(options.wait)) { options.wait = this.force.config.getConfigContent().defaultSrcWaitMinutes; } await this._checkForConflicts(options); // if no remote changes were made, quick exit if (this.statusApi && !this.statusApi.getRemoteChanges().length) { return []; } const packages = await this.smmHelper.getRevisionsAsPackage(this.obsoleteNames); const results = await BBPromise.mapSeries(Object.keys(packages), async (pkgName) => { SfdxProject.getInstance().setActivePackage(pkgName); const pkg = packages[pkgName]; const opts = Object.assign({}, options); this.logger.debug('Retrieving', pkgName); try { // Create a temp directory opts.retrievetargetdir = await createOutputDir('pull'); // Create a manifest (package.xml). const manifestOptions = Object.assign({}, opts, { outputdir: opts.retrievetargetdir, }); const manifest = await this._createPackageManifest(manifestOptions, pkg); this.logger.debug(util.inspect(manifest, { depth: 6 })); let result; if (manifest.empty) { if (this.obsoleteNames.length > 0) { result = { fileProperties: [], success: true, status: 'Succeeded' }; } } else { // Get default metadata retrieve options const retrieveOptions = Object.assign(MdRetrieveApi.getDefaultOptions(), { retrievetargetdir: opts.retrievetargetdir, unpackaged: manifest.file, wait: opts.wait, }); // Retrieve the metadata result = await new MdRetrieveApi(this.scratchOrg).retrieve(retrieveOptions).catch((err) => err.result); } this.logger.debug('Retrieve result:', result); // Update local metadata source. return await this._postRetrieve(result, opts); } finally { // Delete the output dir. await cleanupOutputDir(opts.retrievetargetdir); } }); return results; } // eslint-disable-next-line @typescript-eslint/require-await async _createPackageManifest(options, pkg) { if (pkg.isEmpty()) { return BBPromise.resolve({ empty: true }); } if (_.isNil(options.packageXml) || !options.debug) { const configSourceApiVersion = this.force.getConfig().getAppConfig().sourceApiVersion; const sourceApiVersion = !_.isNil(configSourceApiVersion) ? configSourceApiVersion : this.force.getConfig().getApiVersion(); pkg.setVersion(sourceApiVersion); return BBPromise.resolve( new ManifestCreateApi(this.force).createManifestForMdapiPackage(options, pkg, this.smmHelper.metadataRegistry) ); } else { return BBPromise.resolve({ file: options.packageXml }); } } static _didRetrieveSucceed(result) { return ( !_.isNil(result) && result.success && result.status === 'Succeeded' && _.isNil(result.messages) && !_.isNil(result.fileProperties) && Array.isArray(result.fileProperties) ); } async _postRetrieve(result, options) { let changedSourceElements: AggregateSourceElements; let inboundFiles: WorkspaceElementObj[]; if (MdapiPullApi._didRetrieveSucceed(result)) { changedSourceElements = await this._syncDownSource(result, options, this.swa); // NOTE: Even if no updates were made, we need to update source tracking for those elements // E.g., we pulled metadata but it's the same locally so it's not seen as a change. inboundFiles = changedSourceElements .getAllWorkspaceElements() .map((workspaceElement) => workspaceElement.toObject()); await SourceLocations.nonDecomposedElementsIndex.maybeRefreshIndex(inboundFiles); await this.remoteSourceTrackingService.sync(); } return this._processResults(result, inboundFiles); } async _syncDownSource(result, options, swa: SourceWorkspaceAdapter): Promise<AggregateSourceElements> { const changedSourceElements = new AggregateSourceElements(); // Each Aura bundle has a definition file that has one of the suffixes: .app, .cmp, .design, .evt, etc. // In order to associate each sub-component of an aura bundle (e.g. controller, style, etc.) with // its parent aura definition type, we must find its parent's file properties and pass those along // to processMdapiFileProperty. Similarly, for other BundleMetadataTypes. const bundleFileProperties = BundleMetadataType.getDefinitionProperties( result.fileProperties, this.swa.metadataRegistry ); const postRetrieveHookInfo: MetadataResult = {}; result.fileProperties.forEach((fileProperty) => { let { fullName, fileName } = fileProperty; if (fileProperty.type === 'Package') { return; } // After retrieving, switch back to path separators (for Windows) fileProperty.fullName = fullName = pathUtil.replaceForwardSlashes(fullName); fileProperty.fileName = fileName = pathUtil.replaceForwardSlashes(fileName); this.swa.processMdapiFileProperty( changedSourceElements, options.retrievetargetdir, fileProperty, bundleFileProperties ); if (!(typeof postRetrieveHookInfo[fullName] === 'object')) { postRetrieveHookInfo[fullName] = { mdapiFilePath: [], }; } postRetrieveHookInfo[fullName].mdapiFilePath = postRetrieveHookInfo[fullName].mdapiFilePath.concat( path.join(options.retrievetargetdir, fileName) ); }); // emit post retrieve event await Lifecycle.getInstance().emit('postretrieve', postRetrieveHookInfo); this.obsoleteNames.forEach((obsoleteName) => { this.swa.handleObsoleteSource(changedSourceElements, obsoleteName.fullName, obsoleteName.type); }); const sourcePromise = swa.updateSource( changedSourceElements, options.manifest, false /** check for duplicates **/, options.unsupportedMimeTypes, options.forceoverwrite ); return sourcePromise .then((updatedSource) => { // emit post source update event const postSourceUpdateHookInfo: SourceResult = {}; updatedSource.forEach((sourceElementMap) => { sourceElementMap.forEach((sourceElement) => { const fullName = sourceElement.aggregateFullName; if (!postSourceUpdateHookInfo[fullName]) { postSourceUpdateHookInfo[fullName] = { workspaceElements: [], }; } const hookInfo = postSourceUpdateHookInfo[fullName]; const newElements = hookInfo.workspaceElements.concat( sourceElement.workspaceElements.map((we) => we.toObject()) ); hookInfo.workspaceElements = [...newElements]; postSourceUpdateHookInfo[fullName] = hookInfo; }); }); Lifecycle.getInstance() .emit('postsourceupdate', postSourceUpdateHookInfo) // eslint-disable-next-line @typescript-eslint/no-empty-function .then(() => {}); }) .then(() => sourcePromise); } _processResults(result, inboundFiles: WorkspaceElementObj[]) { if (_.isNil(result)) { return; } else if (MdapiPullApi._didRetrieveSucceed(result)) { return { inboundFiles }; } else { const retrieveFailed = new Error(syncCommandHelper.getRetrieveFailureMessage(result, this.messages)); retrieveFailed.name = 'RetrieveFailed'; throw retrieveFailed; } } async _checkForConflicts(options) { if (options.forceoverwrite) { // do not check for conflicts when pull --forceoverwrite return []; } this.statusApi = await SrcStatusApi.create({ org: this.scratchOrg, adapter: this.swa }); return this.statusApi .doStatus({ local: true, remote: true }) // rely on status so that we centralize the logic .then(() => this.statusApi.getLocalConflicts()) .catch((err) => { const sfdxError = SfdxError.wrap(err); if (err.errorCode === 'INVALID_TYPE') { const messages: Messages = Messages.loadMessages('salesforce-alm', 'source_pull'); sfdxError.message = messages.getMessage('NonScratchOrgPull'); } else if (err.errorCode === 'INVALID_SESSION_ID') { sfdxError.actions = [this.messages.getMessage('invalidInstanceUrlForAccessTokenAction')]; } else { sfdxError.message = err.message; } throw sfdxError; }) .then((conflicts) => { if (conflicts.length > 0) { const error = new Error('Conflicts found during sync down'); error['name'] = 'SourceConflict'; error['sourceConflictElements'] = conflicts; throw error; } }); } } // eslint-disable-next-line no-redeclare export namespace MdapiPullApi { export interface Options { adapter?: SourceWorkspaceAdapter; org: any; } }
the_stack
import * as tape from 'tape'; import {TwingOperator, TwingOperatorType} from "../../../../../src/lib/operator"; import {TwingExtension} from "../../../../../src/lib/extension"; import {TwingExtensionSet} from "../../../../../src/lib/extension-set"; import {TwingTokenParserFilter} from "../../../../../src/lib/token-parser/filter"; import {TwingTest} from "../../../../../src/lib/test"; import {TwingFilter} from "../../../../../src/lib/filter"; import {TwingFunction} from "../../../../../src/lib/function"; import {TwingSourceMapNodeFactory} from "../../../../../src/lib/source-map/node-factory"; import {TwingTokenParser} from "../../../../../src/lib/token-parser"; import {Token} from "twig-lexer"; import {TwingNode} from "../../../../../src/lib/node"; import {TwingBaseNodeVisitor} from "../../../../../src/lib/base-node-visitor"; import {TwingEnvironment} from "../../../../../src/lib/environment"; class TwingTestExtensionSetExtension extends TwingExtension { getOperators() { return [ new TwingOperator('foo', TwingOperatorType.UNARY, 1, () => null), new TwingOperator('bar', TwingOperatorType.BINARY, 1, () => null) ]; } } class TwingTestExtensionSetTokenParser extends TwingTokenParser { getTag() { return 'foo'; } parse(token: Token): TwingNode { return null; } } class TwingTestExtensionSetNodeVisitor extends TwingBaseNodeVisitor { protected doEnterNode(node: TwingNode, env: TwingEnvironment): TwingNode { return undefined; } protected doLeaveNode(node: TwingNode, env: TwingEnvironment): TwingNode { return undefined; } getPriority(): number { return 0; } } tape('extension-set', (test) => { test.test('addExtension', (test) => { let extensionSet = new TwingExtensionSet(); extensionSet.addExtension(new TwingTestExtensionSetExtension(), 'TwingTestExtensionSetExtension'); test.true(extensionSet.hasExtension('TwingTestExtensionSetExtension')); test.test('initialized', (test) => { let extensionSet = new TwingExtensionSet(); // initialize the extension set extensionSet.getFunctions(); try { extensionSet.addExtension(new TwingTestExtensionSetExtension(), 'TwingTestExtensionSetExtension'); test.fail(); } catch (e) { test.same(e.message, 'Unable to register extension "TwingTestExtensionSetExtension" as extensions have already been initialized.'); } test.end(); }); test.end(); }); test.test('addTokenParser', (test) => { test.test('initialized', (test) => { let extensionSet = new TwingExtensionSet(); // initialize the extension set extensionSet.getFunctions(); try { extensionSet.addTokenParser(new TwingTestExtensionSetTokenParser()); test.fail(); } catch (e) { test.same(e.message, 'Unable to add token parser "foo" as extensions have already been initialized.'); } test.end(); }); test.end(); }); test.test('addNodeVisitor', (test) => { test.test('already registered', (test) => { let extensionSet = new TwingExtensionSet(); let parser = new TwingTokenParserFilter(); extensionSet.addTokenParser(parser); try { extensionSet.addTokenParser(new TwingTokenParserFilter()); test.fail(); } catch (e) { test.same(e.message, 'Tag "filter" is already registered.'); } test.end(); }); test.test('initialized', (test) => { let extensionSet = new TwingExtensionSet(); // initialize the extension set extensionSet.getFunctions(); try { extensionSet.addNodeVisitor(new TwingTestExtensionSetNodeVisitor()); test.fail(); } catch (e) { test.same(e.message, 'Unable to add a node visitor as extensions have already been initialized.'); } test.end(); }); test.end(); }); test.test('addTest', (test) => { test.test('already registered', (test) => { let extensionSet = new TwingExtensionSet(); let test_ = new TwingTest('foo', () => Promise.resolve(true), []); extensionSet.addTest(test_); try { extensionSet.addTest(test_); test.fail(); } catch (e) { test.same(e.message, 'Test "foo" is already registered.'); } test.end(); }); test.test('initialized', (test) => { let extensionSet = new TwingExtensionSet(); // initialize the extension set extensionSet.getTests(); try { extensionSet.addTest(new TwingTest('foo', () => Promise.resolve(true), [])); test.fail(); } catch (e) { test.same(e.message, 'Unable to add test "foo" as extensions have already been initialized.'); } test.end(); }); test.end(); }); test.test('getTests', (test) => { let extensionSet = new TwingExtensionSet(); extensionSet.getTests(); test.true(extensionSet.isInitialized()); test.end(); }); test.test('addFilter', (test) => { test.test('already registered', (test) => { let extensionSet = new TwingExtensionSet(); let filter = new TwingFilter('foo', () => Promise.resolve(), []); extensionSet.addFilter(filter); try { extensionSet.addFilter(filter); test.fail(); } catch (e) { test.same(e.message, 'Filter "foo" is already registered.'); } test.end(); }); test.test('initialized', (test) => { let extensionSet = new TwingExtensionSet(); // initialize the extension set extensionSet.getFilters(); try { extensionSet.addFilter(new TwingFilter('foo', () => Promise.resolve(), [])); test.fail(); } catch (e) { test.same(e.message, 'Unable to add filter "foo" as extensions have already been initialized.'); } test.end(); }); test.end(); }); test.test('getFilters', (test) => { let extensionSet = new TwingExtensionSet(); extensionSet.getFilters(); test.true(extensionSet.isInitialized()); test.end(); }); test.test('addTest', (test) => { test.test('initialized', (test) => { let extensionSet = new TwingExtensionSet(); // initialize the extension set extensionSet.getFunctions(); try { extensionSet.addTest(new TwingTest('foo', () => Promise.resolve(true), [])); test.fail(); } catch (e) { test.same(e.message, 'Unable to add test "foo" as extensions have already been initialized.'); } test.end(); }); test.end(); }); test.test('addFunction', (test) => { test.test('already registered', (test) => { let extensionSet = new TwingExtensionSet(); let function_ = new TwingFunction('foo', () => Promise.resolve(), []); extensionSet.addFunction(function_); try { extensionSet.addFunction(function_); test.fail(); } catch (e) { test.same(e.message, 'Function "foo" is already registered.'); } test.end(); }); test.test('initialized', (test) => { let extensionSet = new TwingExtensionSet(); // initialize the extension set extensionSet.getFunctions(); try { extensionSet.addFunction(new TwingFunction('foo', () => Promise.resolve(), [])); test.fail(); } catch (e) { test.same(e.message, 'Unable to add function "foo" as extensions have already been initialized.'); } test.end(); }); test.end(); }); test.test('getFunctions', (test) => { let extensionSet = new TwingExtensionSet(); extensionSet.getFunctions(); test.true(extensionSet.isInitialized()); test.end(); }); test.test('getUnaryOperators', (test) => { let extensionSet = new TwingExtensionSet(); let extension = new TwingTestExtensionSetExtension(); extensionSet.addExtension(extension, 'TwingTestExtensionSetExtension'); test.same(extensionSet.getUnaryOperators().size, 1); test.end(); }); test.test('getBinaryOperators', (test) => { let extensionSet = new TwingExtensionSet(); let extension = new TwingTestExtensionSetExtension(); extensionSet.addExtension(extension, 'TwingTestExtensionSetExtension'); test.same(extensionSet.getBinaryOperators().size, 1); test.end(); }); test.test('addOperator', (test) => { test.test('already registered', (test) => { let extensionSet = new TwingExtensionSet(); let operator = new TwingOperator('foo', TwingOperatorType.BINARY, 1, () => null); extensionSet.addOperator(operator); try { extensionSet.addOperator(operator); test.fail(); } catch (e) { test.same(e.message, 'Operator "foo" is already registered.'); } test.end(); }); test.test('initialized', (test) => { let extensionSet = new TwingExtensionSet(); let extension = new TwingTestExtensionSetExtension(); extensionSet.addExtension(extension, 'TwingTestExtensionSetExtension'); // initialize the extension set extensionSet.getUnaryOperators(); try { extensionSet.addOperator(new TwingOperator('foo', TwingOperatorType.BINARY, 1, () => null)); test.fail(); } catch (e) { test.same(e.message, 'Unable to add operator "foo" as extensions have already been initialized.'); } test.end(); }); test.end(); }); test.test('addSourceMapNodeFactory', (test) => { test.test('already registered', (test) => { let extensionSet = new TwingExtensionSet(); let factory = new TwingSourceMapNodeFactory('foo' as any); extensionSet.addSourceMapNodeFactory(factory); try { extensionSet.addSourceMapNodeFactory(factory); test.fail(); } catch (e) { test.same(e.message, 'Source-map node factory "foo" is already registered.'); } test.end(); }); test.test('initialized', (test) => { let extensionSet = new TwingExtensionSet(); // initialize the extension set extensionSet.getSourceMapNodeFactories(); try { extensionSet.addSourceMapNodeFactory(new TwingSourceMapNodeFactory('foo' as any)); test.fail(); } catch (e) { test.same(e.message, 'Unable to add source-map node factory "foo" as extensions have already been initialized.'); } test.end(); }); test.end(); }); test.test('getSourceMapNodeFactories', (test) => { let extensionSet = new TwingExtensionSet(); extensionSet.getSourceMapNodeFactories(); test.true(extensionSet.isInitialized()); test.end(); }); test.test('getSourceMapNodeFactory', (test) => { let extensionSet = new TwingExtensionSet(); let factory = new TwingSourceMapNodeFactory('foo' as any); extensionSet.addSourceMapNodeFactory(factory); test.same(extensionSet.getSourceMapNodeFactory('foo' as any), factory); test.end(); }); test.end(); });
the_stack
import * as ko from "knockout"; import { KeyCodes } from "../../../Common/Constants"; import { userContext } from "../../../UserContext"; import * as Constants from "../Constants"; import { getQuotedCqlIdentifier } from "../CqlUtilities"; import * as DataTableUtilities from "../DataTable/DataTableUtilities"; import TableEntityListViewModel from "../DataTable/TableEntityListViewModel"; import * as TableEntityProcessor from "../TableEntityProcessor"; import * as Utilities from "../Utilities"; import ClauseGroup from "./ClauseGroup"; import ClauseGroupViewModel from "./ClauseGroupViewModel"; import * as CustomTimestampHelper from "./CustomTimestampHelper"; import * as DateTimeUtilities from "./DateTimeUtilities"; import QueryClauseViewModel from "./QueryClauseViewModel"; import QueryViewModel from "./QueryViewModel"; export default class QueryBuilderViewModel { /* Labels */ public andLabel = "And/Or"; // localize public actionLabel = "Action"; // localize public fieldLabel = "Field"; // localize public dataTypeLabel = "Type"; // localize public operatorLabel = "Operator"; // localize public valueLabel = "Value"; // localize /* controls */ public addNewClauseLine = "Add new clause"; // localize public insertNewFilterLine = "Insert new filter line"; // localize public removeThisFilterLine = "Remove this filter line"; // localize public groupSelectedClauses = "Group selected clauses"; // localize public clauseArray = ko.observableArray<QueryClauseViewModel>(); // This is for storing the clauses in flattened form queryClauses for easier UI data binding. public queryClauses = new ClauseGroup(true, undefined); // The actual data structure containing the clause information. public columnOptions: ko.ObservableArray<string>; public canGroupClauses = ko.observable<boolean>(false); /* Observables */ public edmTypes = ko.observableArray([ Constants.TableType.String, Constants.TableType.Boolean, Constants.TableType.Binary, Constants.TableType.DateTime, Constants.TableType.Double, Constants.TableType.Guid, Constants.TableType.Int32, Constants.TableType.Int64, "", ]); public operators = ko.observableArray([ Constants.Operator.Equal, Constants.Operator.GreaterThan, Constants.Operator.GreaterThanOrEqualTo, Constants.Operator.LessThan, Constants.Operator.LessThanOrEqualTo, Constants.Operator.NotEqualTo, "", ]); public clauseRules = ko.observableArray([Constants.ClauseRule.And, Constants.ClauseRule.Or]); public timeOptions = ko.observableArray([ Constants.timeOptions.lastHour, Constants.timeOptions.last24Hours, Constants.timeOptions.last7Days, Constants.timeOptions.last31Days, Constants.timeOptions.last365Days, Constants.timeOptions.currentMonth, Constants.timeOptions.currentYear, //Constants.timeOptions.custom ]); public queryString = ko.observable<string>(); private _queryViewModel: QueryViewModel; public tableEntityListViewModel: TableEntityListViewModel; private scrollEventListener: boolean; constructor(queryViewModel: QueryViewModel, tableEntityListViewModel: TableEntityListViewModel) { if (userContext.apiType === "Cassandra") { this.edmTypes([ Constants.CassandraType.Text, Constants.CassandraType.Ascii, Constants.CassandraType.Bigint, Constants.CassandraType.Blob, Constants.CassandraType.Boolean, Constants.CassandraType.Decimal, Constants.CassandraType.Double, Constants.CassandraType.Float, Constants.CassandraType.Int, Constants.CassandraType.Uuid, Constants.CassandraType.Varchar, Constants.CassandraType.Varint, Constants.CassandraType.Inet, Constants.CassandraType.Smallint, Constants.CassandraType.Tinyint, ]); this.clauseRules([ Constants.ClauseRule.And, // OR is not supported in CQL ]); this.andLabel = "And"; } this.clauseArray(); this._queryViewModel = queryViewModel; this.tableEntityListViewModel = tableEntityListViewModel; this.columnOptions = ko.observableArray<string>(queryViewModel.columnOptions()); this.columnOptions.subscribe((newColumnOptions) => { queryViewModel.columnOptions(newColumnOptions); }); } public setExample() { const example1 = new QueryClauseViewModel( this, "", "PartitionKey", this.edmTypes()[0], Constants.Operator.Equal, this.tableEntityListViewModel.items()[0].PartitionKey._, false, "", "", "", //null, true ); const example2 = new QueryClauseViewModel( this, "And", "RowKey", this.edmTypes()[0], Constants.Operator.Equal, this.tableEntityListViewModel.items()[0].RowKey._, true, "", "", "", //null, true ); this.addClauseImpl(example1, 0); this.addClauseImpl(example2, 1); } public getODataFilterFromClauses = (): string => { let filterString = ""; const treeTraversal = (group: ClauseGroup): void => { for (let i = 0; i < group.children.length; i++) { const currentItem = group.children[i]; if (currentItem instanceof QueryClauseViewModel) { const clause = <QueryClauseViewModel>currentItem; this.timestampToValue(clause); filterString = filterString.concat( this.constructODataClause( filterString === "" ? "" : clause.and_or(), this.generateLeftParentheses(clause), clause.field(), clause.type(), clause.operator(), clause.value(), this.generateRightParentheses(clause) ) ); } if (currentItem instanceof ClauseGroup) { treeTraversal(<ClauseGroup>currentItem); } } }; treeTraversal(this.queryClauses); return filterString.trim(); }; public getSqlFilterFromClauses = (): string => { let filterString = "SELECT * FROM c"; if (this._queryViewModel.selectText() && this._queryViewModel.selectText().length > 0) { filterString = "SELECT"; const selectText = this._queryViewModel && this._queryViewModel.selectText && this._queryViewModel.selectText(); selectText && selectText.forEach((value: string) => { if (value === Constants.EntityKeyNames.PartitionKey) { value = `["${TableEntityProcessor.keyProperties.PartitionKey}"]`; filterString = filterString.concat(filterString === "SELECT" ? " c" : ", c"); } else if (value === Constants.EntityKeyNames.RowKey) { value = `["${TableEntityProcessor.keyProperties.Id}"]`; filterString = filterString.concat(filterString === "SELECT" ? " c" : ", c"); } else { if (value === Constants.EntityKeyNames.Timestamp) { value = TableEntityProcessor.keyProperties.Timestamp; } filterString = filterString.concat(filterString === "SELECT" ? " c." : ", c."); } filterString = filterString.concat(value); }); filterString = filterString.concat(" FROM c"); } if (this.queryClauses.children.length === 0) { return filterString; } filterString = filterString.concat(" WHERE"); let first = true; const treeTraversal = (group: ClauseGroup): void => { for (let i = 0; i < group.children.length; i++) { const currentItem = group.children[i]; if (currentItem instanceof QueryClauseViewModel) { const clause = <QueryClauseViewModel>currentItem; const timeStampValue: string = this.timestampToSqlValue(clause); let value = clause.value(); if (!clause.isValue()) { value = timeStampValue; } filterString = filterString.concat( this.constructSqlClause( first ? "" : clause.and_or(), this.generateLeftParentheses(clause), clause.field(), clause.type(), clause.operator(), value, this.generateRightParentheses(clause) ) ); first = false; } if (currentItem instanceof ClauseGroup) { treeTraversal(<ClauseGroup>currentItem); } } }; treeTraversal(this.queryClauses); return filterString.trim(); }; public getCqlFilterFromClauses = (): string => { const databaseId = this._queryViewModel.queryTablesTab.collection.databaseId; const collectionId = this._queryViewModel.queryTablesTab.collection.id(); const tableToQuery = `${getQuotedCqlIdentifier(databaseId)}.${getQuotedCqlIdentifier(collectionId)}`; let filterString = `SELECT * FROM ${tableToQuery}`; if (this._queryViewModel.selectText() && this._queryViewModel.selectText().length > 0) { filterString = "SELECT"; const selectText = this._queryViewModel && this._queryViewModel.selectText && this._queryViewModel.selectText(); selectText && selectText.forEach((value: string) => { filterString = filterString.concat(filterString === "SELECT" ? " " : ", "); filterString = filterString.concat(value); }); filterString = filterString.concat(` FROM ${tableToQuery}`); } if (this.queryClauses.children.length === 0) { return filterString; } filterString = filterString.concat(" WHERE"); let first = true; const treeTraversal = (group: ClauseGroup): void => { for (let i = 0; i < group.children.length; i++) { const currentItem = group.children[i]; if (currentItem instanceof QueryClauseViewModel) { const clause = <QueryClauseViewModel>currentItem; const timeStampValue = this.timestampToSqlValue(clause); let value = clause.value(); if (!clause.isValue()) { value = timeStampValue; } filterString = filterString.concat( this.constructCqlClause( first ? "" : clause.and_or(), this.generateLeftParentheses(clause), clause.field(), clause.type(), clause.operator(), value, this.generateRightParentheses(clause) ) ); first = false; } if (currentItem instanceof ClauseGroup) { treeTraversal(<ClauseGroup>currentItem); } } }; treeTraversal(this.queryClauses); return filterString.trim(); }; public updateColumnOptions = (): void => { // let originalHeaders = this.columnOptions(); const newHeaders = this.tableEntityListViewModel.headers; this.columnOptions(newHeaders.sort(DataTableUtilities.compareTableColumns)); }; private generateLeftParentheses(clause: QueryClauseViewModel): string { let result = ""; if (clause.clauseGroup.isRootGroup || clause.clauseGroup.children.indexOf(clause) !== 0) { return result; } else { result = result.concat("("); } let currentGroup: ClauseGroup = clause.clauseGroup; while ( !currentGroup.isRootGroup && !currentGroup.parentGroup.isRootGroup && currentGroup.parentGroup.children.indexOf(currentGroup) === 0 ) { result = result.concat("("); currentGroup = currentGroup.parentGroup; } return result; } private generateRightParentheses(clause: QueryClauseViewModel): string { let result = ""; if ( clause.clauseGroup.isRootGroup || clause.clauseGroup.children.indexOf(clause) !== clause.clauseGroup.children.length - 1 ) { return result; } else { result = result.concat(")"); } let currentGroup: ClauseGroup = clause.clauseGroup; while ( !currentGroup.isRootGroup && !currentGroup.parentGroup.isRootGroup && currentGroup.parentGroup.children.indexOf(currentGroup) === currentGroup.parentGroup.children.length - 1 ) { result = result.concat(")"); currentGroup = currentGroup.parentGroup; } return result; } private constructODataClause = ( clauseRule: string, leftParentheses: string, propertyName: string, type: string, operator: string, value: string, rightParentheses: string ): string => { switch (type) { case Constants.TableType.DateTime: return ` ${clauseRule.toLowerCase()} ${leftParentheses}${propertyName} ${this.operatorConverter( operator )} ${value}${rightParentheses}`; case Constants.TableType.String: return ` ${clauseRule.toLowerCase()} ${leftParentheses}${propertyName} ${this.operatorConverter( operator // eslint-disable-next-line no-useless-escape )} \'${value}\'${rightParentheses}`; case Constants.TableType.Guid: return ` ${clauseRule.toLowerCase()} ${leftParentheses}${propertyName} ${this.operatorConverter( operator // eslint-disable-next-line no-useless-escape )} guid\'${value}\'${rightParentheses}`; case Constants.TableType.Binary: return ` ${clauseRule.toLowerCase()} ${leftParentheses}${propertyName} ${this.operatorConverter( operator // eslint-disable-next-line no-useless-escape )} binary\'${value}\'${rightParentheses}`; default: return ` ${clauseRule.toLowerCase()} ${leftParentheses}${propertyName} ${this.operatorConverter( operator )} ${value}${rightParentheses}`; } }; private constructSqlClause = ( clauseRule: string, leftParentheses: string, propertyName: string, type: string, operator: string, value: string, rightParentheses: string ): string => { if (propertyName === Constants.EntityKeyNames.PartitionKey) { propertyName = TableEntityProcessor.keyProperties.PartitionKey; // eslint-disable-next-line no-useless-escape return ` ${clauseRule.toLowerCase()} ${leftParentheses}c["${propertyName}"] ${operator} \'${value}\'${rightParentheses}`; } else if (propertyName === Constants.EntityKeyNames.RowKey) { propertyName = TableEntityProcessor.keyProperties.Id; // eslint-disable-next-line no-useless-escape return ` ${clauseRule.toLowerCase()} ${leftParentheses}c.${propertyName} ${operator} \'${value}\'${rightParentheses}`; } else if (propertyName === Constants.EntityKeyNames.Timestamp) { propertyName = TableEntityProcessor.keyProperties.Timestamp; return ` ${clauseRule.toLowerCase()} ${leftParentheses}c.${propertyName} ${operator} ${DateTimeUtilities.convertJSDateToUnix( value )}${rightParentheses}`; } switch (type) { case Constants.TableType.DateTime: // eslint-disable-next-line no-useless-escape return ` ${clauseRule.toLowerCase()} ${leftParentheses}c.${propertyName}["$v"] ${operator} \'${DateTimeUtilities.convertJSDateToTicksWithPadding( value // eslint-disable-next-line no-useless-escape )}\'${rightParentheses}`; case Constants.TableType.Int64: // eslint-disable-next-line no-useless-escape return ` ${clauseRule.toLowerCase()} ${leftParentheses}c.${propertyName}["$v"] ${operator} \'${Utilities.padLongWithZeros( value // eslint-disable-next-line no-useless-escape )}\'${rightParentheses}`; case Constants.TableType.String: case Constants.TableType.Guid: case Constants.TableType.Binary: // eslint-disable-next-line no-useless-escape return ` ${clauseRule.toLowerCase()} ${leftParentheses}c.${propertyName}["$v"] ${operator} \'${value}\'${rightParentheses}`; default: return ` ${clauseRule.toLowerCase()} ${leftParentheses}c.${propertyName}["$v"] ${operator} ${value}${rightParentheses}`; } }; private constructCqlClause = ( clauseRule: string, leftParentheses: string, propertyName: string, type: string, operator: string, value: string, rightParentheses: string ): string => { if ( type === Constants.CassandraType.Text || type === Constants.CassandraType.Inet || type === Constants.CassandraType.Ascii || type === Constants.CassandraType.Varchar ) { // eslint-disable-next-line no-useless-escape return ` ${clauseRule.toLowerCase()} ${leftParentheses} ${propertyName} ${operator} \'${value}\'${rightParentheses}`; } return ` ${clauseRule.toLowerCase()} ${leftParentheses} ${propertyName} ${operator} ${value}${rightParentheses}`; }; private operatorConverter = (operator: string): string => { switch (operator) { case Constants.Operator.Equal: return Constants.ODataOperator.EqualTo; case Constants.Operator.GreaterThan: return Constants.ODataOperator.GreaterThan; case Constants.Operator.GreaterThanOrEqualTo: return Constants.ODataOperator.GreaterThanOrEqualTo; case Constants.Operator.LessThan: return Constants.ODataOperator.LessThan; case Constants.Operator.LessThanOrEqualTo: return Constants.ODataOperator.LessThanOrEqualTo; case Constants.Operator.NotEqualTo: return Constants.ODataOperator.NotEqualTo; } return undefined; }; public groupClauses = (): void => { this.queryClauses.groupSelectedItems(); this.updateClauseArray(); this.updateCanGroupClauses(); }; public addClauseIndex = (index: number): void => { if (index < 0) { index = 0; } const newClause = new QueryClauseViewModel( this, "And", "", this.edmTypes()[0], Constants.Operator.EqualTo, "", true, "", "", "", //null, true ); this.addClauseImpl(newClause, index); if (index === this.clauseArray().length - 1) { this.scrollToBottom(); } this.updateCanGroupClauses(); newClause.isAndOrFocused(true); $(window).resize(); }; // adds a new clause to the end of the array public addNewClause = (): void => { this.addClauseIndex(this.clauseArray().length); }; public onAddClauseKeyDown = (index: number, event: KeyboardEvent): boolean => { if (event.keyCode === KeyCodes.Enter || event.keyCode === KeyCodes.Space) { this.addClauseIndex(index); event.stopPropagation(); return false; } return true; }; public onAddNewClauseKeyDown = (event: KeyboardEvent): boolean => { if (event.keyCode === KeyCodes.Enter || event.keyCode === KeyCodes.Space) { this.addClauseIndex(this.clauseArray().length - 1); event.stopPropagation(); return false; } return true; }; public deleteClause = (index: number): void => { this.deleteClauseImpl(index); if (this.clauseArray().length !== 0) { this.clauseArray()[0].and_or(""); this.clauseArray()[0].canAnd(false); } this.updateCanGroupClauses(); $(window).resize(); }; public onDeleteClauseKeyDown = (index: number, event: KeyboardEvent): boolean => { if (event.keyCode === KeyCodes.Enter || event.keyCode === KeyCodes.Space) { this.deleteClause(index); event.stopPropagation(); return false; } return true; }; /** * Generates an array of ClauseGroupViewModel objects for UI to display group information for this clause. * All clauses have the same number of ClauseGroupViewModel objects, which is the depth of the clause tree. * If the current clause is not the deepest in the tree, then the array will be filled by either a placeholder * (transparent) or its parent group view models. */ public getClauseGroupViewModels = (clause: QueryClauseViewModel): ClauseGroupViewModel[] => { const placeHolderGroupViewModel = new ClauseGroupViewModel(this.queryClauses, false, this); const treeDepth = this.queryClauses.getTreeDepth(); const groupViewModels = new Array<ClauseGroupViewModel>(treeDepth); // Prefill the arry with placeholders. for (let i = 0; i < groupViewModels.length; i++) { groupViewModels[i] = placeHolderGroupViewModel; } let currentGroup = clause.clauseGroup; // This function determines whether the path from clause to the current group is on the left most. const isLeftMostPath = (): boolean => { let group = clause.clauseGroup; if (group.children.indexOf(clause) !== 0) { return false; } // eslint-disable-next-line no-constant-condition while (true) { if (group.getId() === currentGroup.getId()) { break; } if (group.parentGroup.children.indexOf(group) !== 0) { return false; } group = group.parentGroup; } return true; }; // This function determines whether the path from clause to the current group is on the right most. const isRightMostPath = (): boolean => { let group = clause.clauseGroup; if (group.children.indexOf(clause) !== group.children.length - 1) { return false; } // eslint-disable-next-line no-constant-condition while (true) { if (group.getId() === currentGroup.getId()) { break; } if (group.parentGroup.children.indexOf(group) !== group.parentGroup.children.length - 1) { return false; } group = group.parentGroup; } return true; }; let vmIndex = groupViewModels.length - 1; let skipIndex = -1; let lastDepth = clause.groupDepth; while (!currentGroup.isRootGroup) { // The current group will be rendered at least once, and if there are any sibling groups deeper // than the current group, we will repeat rendering the current group to fill up the gap between // current & deepest sibling. const deepestInSiblings = currentGroup.findDeepestGroupInChildren(skipIndex).getCurrentGroupDepth(); // Find out the depth difference between the deepest group under the siblings of currentGroup and // the deepest group under currentGroup. If the result n is a positive number, it means there are // deeper groups in siblings and we need to draw n + 1 group blocks on UI to fill up the depth // differences. If the result n is a negative number, it means current group contains the deepest // sub-group, we only need to draw the group block once. const repeatCount = Math.max(deepestInSiblings - lastDepth, 0); for (let i = 0; i <= repeatCount; i++) { const isLeftMost = isLeftMostPath(); const isRightMost = isRightMostPath(); const groupViewModel = new ClauseGroupViewModel(currentGroup, i === 0 && isLeftMost, this); groupViewModel.showTopBorder(isLeftMost); groupViewModel.showBottomBorder(isRightMost); groupViewModel.showLeftBorder(i === repeatCount); groupViewModels[vmIndex] = groupViewModel; vmIndex--; } skipIndex = currentGroup.parentGroup.children.indexOf(currentGroup); currentGroup = currentGroup.parentGroup; lastDepth = Math.max(deepestInSiblings, lastDepth); } return groupViewModels; }; public runQuery = (): DataTables.DataTable => { return this._queryViewModel.runQuery(); }; public addCustomRange(timestamp: CustomTimestampHelper.ITimestampQuery, clauseToAdd: QueryClauseViewModel): void { const index = this.clauseArray.peek().indexOf(clauseToAdd); const newClause = new QueryClauseViewModel( this, //this._tableEntityListViewModel.tableExplorerContext.hostProxy, "And", clauseToAdd.field(), "DateTime", Constants.Operator.LessThan, "", true, Constants.timeOptions.custom, timestamp.endTime, "range", //null, true ); newClause.isLocal = ko.observable(timestamp.timeZone === "local"); this.addClauseImpl(newClause, index + 1); if (index + 1 === this.clauseArray().length - 1) { this.scrollToBottom(); } } private scrollToBottom(): void { const scrollBox = document.getElementById("scroll"); if (!this.scrollEventListener) { scrollBox.addEventListener("scroll", function () { const translate = "translate(0," + this.scrollTop + "px)"; const allTh = <NodeListOf<HTMLElement>>this.querySelectorAll("thead td"); for (let i = 0; i < allTh.length; i++) { allTh[i].style.transform = translate; } }); this.scrollEventListener = true; } const isScrolledToBottom = scrollBox.scrollHeight - scrollBox.clientHeight <= scrollBox.scrollHeight + 1; if (isScrolledToBottom) { scrollBox.scrollTop = scrollBox.scrollHeight - scrollBox.clientHeight; } } private addClauseImpl(clause: QueryClauseViewModel, position: number): void { this.queryClauses.insertClauseBefore(clause, this.clauseArray()[position]); this.updateClauseArray(); } private deleteClauseImpl(index: number): void { const clause = this.clauseArray()[index]; const previousClause = index === 0 ? 0 : index - 1; this.queryClauses.deleteClause(clause); this.updateClauseArray(); if (this.clauseArray()[previousClause]) { this.clauseArray()[previousClause].isDeleteButtonFocused(true); } } public updateCanGroupClauses(): void { this.canGroupClauses(this.queryClauses.canGroupSelectedItems()); } public updateClauseArray(): void { if (this.clauseArray().length > 0) { this.clauseArray()[0].canAnd(true); } this.queryClauses.flattenClauses(this.clauseArray); if (this.clauseArray().length > 0) { this.clauseArray()[0].canAnd(false); } // Fix for 261924, forces the resize event so DataTableBindingManager will redo the calculation on table size. //DataTableUtilities.forceRecalculateTableSize(); } private timestampToValue(clause: QueryClauseViewModel): void { if (clause.isValue()) { return; } else if (clause.isTimestamp()) { this.getTimeStampToQuery(clause); // } else if (clause.isCustomLastTimestamp()) { // clause.value(`datetime'${CustomTimestampHelper._queryLastTime(clause.customLastTimestamp().lastNumber, clause.customLastTimestamp().lastTimeUnit)}'`); } else if (clause.isCustomRangeTimestamp()) { if (clause.isLocal()) { clause.value(`datetime'${DateTimeUtilities.getUTCDateTime(clause.customTimeValue())}'`); } else { clause.value(`datetime'${clause.customTimeValue()}Z'`); } } } private timestampToSqlValue(clause: QueryClauseViewModel): string { if (clause.isValue()) { return undefined; } else if (clause.isTimestamp()) { return this.getTimeStampToSqlQuery(clause); // } else if (clause.isCustomLastTimestamp()) { // clause.value(CustomTimestampHelper._queryLastTime(clause.customLastTimestamp().lastNumber, clause.customLastTimestamp().lastTimeUnit)); } else if (clause.isCustomRangeTimestamp()) { if (clause.isLocal()) { return DateTimeUtilities.getUTCDateTime(clause.customTimeValue()); } else { return clause.customTimeValue(); } } return undefined; } private getTimeStampToQuery(clause: QueryClauseViewModel): void { switch (clause.timeValue()) { case Constants.timeOptions.lastHour: clause.value(`datetime'${CustomTimestampHelper._queryLastDaysHours(0, 1)}'`); break; case Constants.timeOptions.last24Hours: clause.value(`datetime'${CustomTimestampHelper._queryLastDaysHours(0, 24)}'`); break; case Constants.timeOptions.last7Days: clause.value(`datetime'${CustomTimestampHelper._queryLastDaysHours(7, 0)}'`); break; case Constants.timeOptions.last31Days: clause.value(`datetime'${CustomTimestampHelper._queryLastDaysHours(31, 0)}'`); break; case Constants.timeOptions.last365Days: clause.value(`datetime'${CustomTimestampHelper._queryLastDaysHours(365, 0)}'`); break; case Constants.timeOptions.currentMonth: clause.value(`datetime'${CustomTimestampHelper._queryCurrentMonthLocal()}'`); break; case Constants.timeOptions.currentYear: clause.value(`datetime'${CustomTimestampHelper._queryCurrentYearLocal()}'`); break; } } private getTimeStampToSqlQuery(clause: QueryClauseViewModel): string { switch (clause.timeValue()) { case Constants.timeOptions.lastHour: return CustomTimestampHelper._queryLastDaysHours(0, 1); case Constants.timeOptions.last24Hours: return CustomTimestampHelper._queryLastDaysHours(0, 24); case Constants.timeOptions.last7Days: return CustomTimestampHelper._queryLastDaysHours(7, 0); case Constants.timeOptions.last31Days: return CustomTimestampHelper._queryLastDaysHours(31, 0); case Constants.timeOptions.last365Days: return CustomTimestampHelper._queryLastDaysHours(365, 0); case Constants.timeOptions.currentMonth: return CustomTimestampHelper._queryCurrentMonthLocal(); case Constants.timeOptions.currentYear: return CustomTimestampHelper._queryCurrentYearLocal(); } return undefined; } public checkIfClauseChanged(): void { this._queryViewModel.checkIfBuilderChanged(); } }
the_stack
import * as vscode from 'vscode'; import { JackBase } from './jack'; import { NodeTreeItem } from './nodeTree'; import { updateNodeLabelsScript } from './utils'; import { ext } from './extensionVariables'; import { SelectionFlows } from './selectionFlows'; export class NodeJack extends JackBase { constructor() { super('Node Jack', 'extension.jenkins-jack.node'); ext.context.subscriptions.push(vscode.commands.registerCommand('extension.jenkins-jack.node.setOffline', async (item?: any[] | NodeTreeItem, items?: NodeTreeItem[]) => { let result: any; if (item instanceof NodeTreeItem) { let nodes = !items ? [item.node] : items.map((item: any) => item.node); result = await this.setOffline(nodes); } else { result = await this.setOffline(item); } if (result) { ext.nodeTree.refresh(); } })); ext.context.subscriptions.push(vscode.commands.registerCommand('extension.jenkins-jack.node.setOnline', async (item?: any[] | NodeTreeItem, items?: NodeTreeItem[]) => { let result: any; if (item instanceof NodeTreeItem) { let nodes = !items ? [item.node] : items.map((item: any) => item.node); result = await this.setOnline(nodes); } else { result = await this.setOnline(item); } if (result) { ext.nodeTree.refresh(); } })); ext.context.subscriptions.push(vscode.commands.registerCommand('extension.jenkins-jack.node.disconnect', async (item?: any[] | NodeTreeItem, items?: NodeTreeItem[]) => { let result: any; if (item instanceof NodeTreeItem) { let nodes = !items ? [item.node] : items.map((item: any) => item.node); result = await this.disconnect(nodes); } else { result = await this.disconnect(item); } if (result) { ext.nodeTree.refresh(); } })); ext.context.subscriptions.push(vscode.commands.registerCommand('extension.jenkins-jack.node.updateLabels', async (item?: any[] | NodeTreeItem, items?: NodeTreeItem[]) => { let result: any; if (item instanceof NodeTreeItem) { let nodes = !items ? [item.node] : items.map((item: any) => item.node); result = await this.updateLabels(nodes); } else { result = await this.updateLabels(); } if (result) { ext.nodeTree.refresh(); } })); ext.context.subscriptions.push(vscode.commands.registerCommand('extension.jenkins-jack.node.open', async (item?: any | NodeTreeItem, items?: NodeTreeItem[]) => { let nodes = []; if (item instanceof NodeTreeItem) { nodes = items ? items.map((i: any) => i.node) : [item.node]; } else { nodes = await SelectionFlows.nodes(undefined, true, 'Select one or more nodes for opening in the browser'); if (undefined === nodes) { return false; } } for (let n of nodes) { ext.connectionsManager.host.openBrowserAtPath(`/computer/${n.displayName}`); } })); } public get commands(): any[] { return [ { label: "$(stop) Node: Set Offline", description: "Mark targeted nodes offline with a message.", target: () => vscode.commands.executeCommand('extension.jenkins-jack.node.setOffline') }, { label: "$(check) Node: Set Online", description: "Mark targeted nodes online.", target: () => vscode.commands.executeCommand('extension.jenkins-jack.node.setOnline') }, { label: "$(circle-slash) Node: Disconnect", description: "Disconnects targeted nodes from the host.", target: () => vscode.commands.executeCommand('extension.jenkins-jack.node.disconnect') }, { label: "$(list-flat) Node: Update Labels", description: "Update targeted nodes' assigned labels.", target: () => vscode.commands.executeCommand('extension.jenkins-jack.node.updateLabels') }, { label: "$(browser) Node: Open", description: "Opens the targeted nodes in the user's browser.", target: () => vscode.commands.executeCommand('extension.jenkins-jack.node.open') } ]; } /** * Allows the user to select multiple offline nodes to be * re-enabled. */ public async setOnline(nodes?: any[]) { nodes = nodes ? nodes : await SelectionFlows.nodes( (n: any) => n.displayName !== 'master' && n.offline, true, 'Select one or more offline nodes for re-enabling'); if (undefined === nodes) { return undefined; } return await this.actionOnNodes(nodes, async (node: any) => { await ext.connectionsManager.host.client.node.enable(node.displayName); return `Online command sent to "${node.displayName}"`; }); } /** * Allows the user to select multiple online nodes to * be set in a temporary offline status, with a message. */ public async setOffline(nodes?: any[], offlineMessage?: string) { if (!offlineMessage) { offlineMessage = await vscode.window.showInputBox({ prompt: 'Enter an offline message.' }); if (undefined === offlineMessage) { return undefined; } } nodes = nodes ? nodes : await SelectionFlows.nodes( (n: any) => n.displayName !== 'master' && !n.offline, true, 'Select one or more nodes for temporary offline'); if (undefined === nodes) { return undefined; } return await this.actionOnNodes(nodes, async (node: any) => { await ext.connectionsManager.host.client.node.disable(node.displayName, offlineMessage); return `Offline command sent to "${node.displayName}"`; }); } /** * Allows the user to select multiple nodes to be * disconnected from the server. */ public async disconnect(nodes?: any[]) { nodes = nodes ? nodes : await SelectionFlows.nodes( (n: any) => n.displayName !== 'master', true, 'Select one or more nodes for disconnect'); if (undefined === nodes) { return undefined; } return await this.actionOnNodes(nodes, async (node: any) => { await ext.connectionsManager.host.client.node.disconnect(node.displayName); return `Disconnect command sent to "${node.displayName}"`; }); } public async updateLabels(nodes?: any) { nodes = nodes ? nodes : await SelectionFlows.nodes( (n: any) => n.displayName !== 'master', true, 'Select one or more nodes for updating labels'); if (undefined === nodes) { return undefined; } // Pull the labels from the first node to use as a pre-filled value // for the input box. let node = nodes[0]; let labelList = node.assignedLabels.map((l: any) => l.name).filter( (l: string) => l.toUpperCase() !== node.displayName.toUpperCase() ); let labelString = await vscode.window.showInputBox({ prompt: 'Enter the labels you want assigned to the node.', value: labelList.join(' ') }); if (undefined === labelString) { return undefined; } let nodeNames = nodes.map((n: any) => n.displayName); let script = updateNodeLabelsScript(nodeNames, labelString.split(' ')); let result = await ext.connectionsManager.host.runConsoleScript(script, undefined); this.outputChannel.clear(); this.outputChannel.show(); this.outputChannel.appendLine(this.barrierLine); this.outputChannel.appendLine(`Nodes Updated: ${nodeNames.join(', ')}`); this.outputChannel.appendLine(`Script Output: ${result}`); this.outputChannel.appendLine(this.barrierLine); return true; } /** * Handles an input flow for performing and action on targeted nodes. * @param onNodeAction Async callback that runs an action on a node * label and returns output. * @param filter Optional filter on a jenkins API node. */ private async actionOnNodes( nodes: any[], onNodeAction: (node: string) => Promise<string>): Promise<any> { return vscode.window.withProgress({ location: vscode.ProgressLocation.Notification, title: `Node Jack Output(s)`, cancellable: true }, async (progress, token) => { token.onCancellationRequested(() => { this.showWarningMessage("User canceled node command."); }); // Builds a list of parallel actions across the list of targeted machines // and awaits across all. let tasks = []; progress.report({ increment: 50, message: "Executing on target machine(s)" }); for (let n of nodes) { let promise = new Promise(async (resolve) => { try { let output = await onNodeAction(n); return resolve({ node: n.displayName, output: output }); } catch (err) { return resolve({ node: n.displayName, output: err }); } }); tasks.push(promise); } let results = await Promise.all(tasks); // Iterate over the result list, printing the name of the // machine and it's output. this.outputChannel.clear(); this.outputChannel.show(); for (let r of results as any[]) { this.outputChannel.appendLine(this.barrierLine); this.outputChannel.appendLine(r.node); this.outputChannel.appendLine(''); this.outputChannel.appendLine(r.output); this.outputChannel.appendLine(this.barrierLine); } progress.report({ increment: 50, message: `Output retrieved. Displaying in OUTPUT channel...` }); return true; }); } }
the_stack
import "jest"; import {parseCSA as parse} from "../parsers"; /* tslint:disable:object-literal-sort-keys max-line-length */ function p(x, y) { return {x, y}; } describe("csa-parser V2", () => { let initial; beforeEach(() => { initial = { preset: "OTHER", data: { board: [ [{ color: 1, kind: "KY" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "KY" }], [{ color: 1, kind: "KE" }, { color: 1, kind: "KA" }, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, { color: 0, kind: "HI" }, { color: 0, kind: "KE" }], [{ color: 1, kind: "GI" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "GI" }], [{ color: 1, kind: "KI" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "KI" }], [{ color: 1, kind: "OU" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "OU" }], [{ color: 1, kind: "KI" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "KI" }], [{ color: 1, kind: "GI" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "GI" }], [{ color: 1, kind: "KE" }, { color: 1, kind: "HI" }, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, { color: 0, kind: "KA" }, { color: 0, kind: "KE" }], [{ color: 1, kind: "KY" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "KY" }], ], color: 0, hands: [ {FU: 0, KY: 0, KE: 0, GI: 0, KI: 0, KA: 0, HI: 0}, {FU: 0, KY: 0, KE: 0, GI: 0, KI: 0, KA: 0, HI: 0}, ], }, }; }); it("simple", () => { expect(parse("\ V2.2\n\ PI\n\ +\n\ +7776FU\n\ -3334FU\n\ +8822UM\n\ -3122GI\n\ +0045KA\n")).toEqual({ header: {}, initial, // normalizerがpresetを復元する moves: [ {}, {move: {from: p(7, 7), to: p(7, 6), piece: "FU"}}, {move: {from: p(3, 3), to: p(3, 4), piece: "FU"}}, {move: {from: p(8, 8), to: p(2, 2), piece: "UM"}}, {move: {from: p(3, 1), to: p(2, 2), piece: "GI"}}, {move: {to: p(4, 5), piece: "KA"}}, ], }); }); it("comment", () => { expect(parse("\ V2.2\n\ PI\n\ +\n\ '開始時コメント\n\ +7776FU\n\ '初手コメント\n\ '初手コメント2\n\ -3334FU\n\ +8822UM\n")).toEqual({ header: {}, initial, moves: [ {comments: ["開始時コメント"]}, {move: {from: p(7, 7), to: p(7, 6), piece: "FU"}, comments: ["初手コメント", "初手コメント2"]}, {move: {from: p(3, 3), to: p(3, 4), piece: "FU"}}, {move: {from: p(8, 8), to: p(2, 2), piece: "UM"}}, ], }); }); it("special", () => { expect(parse("\ V2.2\n\ PI\n\ +\n\ +7776FU\n\ -3334FU\n\ +7978GI\n\ -2288UM\n\ %TORYO\n")).toEqual({ header: {}, initial, moves: [ {}, {move: {from: p(7, 7), to: p(7, 6), piece: "FU"}}, {move: {from: p(3, 3), to: p(3, 4), piece: "FU"}}, {move: {from: p(7, 9), to: p(7, 8), piece: "GI"}}, {move: {from: p(2, 2), to: p(8, 8), piece: "UM"}}, {special: "TORYO"}, ], }); }); it("comma", () => { expect(parse("\ V2.2\n\ PI\n\ +\n\ +7776FU,T12,-3334FU,T2\n\ +8822UM,T100\n\ -3122GI,T1\n\ +0045KA,T0\n")).toEqual({ header: {}, initial, // normalizerがpresetを復元する moves: [ {}, {move: {from: p(7, 7), to: p(7, 6), piece: "FU"}, time: {now: {m: 0, s: 12}}}, // totalはnormalizerが復元 {move: {from: p(3, 3), to: p(3, 4), piece: "FU"}, time: {now: {m: 0, s: 2}}}, {move: {from: p(8, 8), to: p(2, 2), piece: "UM"}, time: {now: {m: 1, s: 40}}}, {move: {from: p(3, 1), to: p(2, 2), piece: "GI"}, time: {now: {m: 0, s: 1}}}, {move: {to: p(4, 5), piece: "KA"}, time: {now: {m: 0, s: 0}}}, ], }); }); it("time", () => { expect(parse("\ V2.2\n\ PI\n\ +\n\ +7776FU\n\ T12\n\ -3334FU\n\ T2\n\ +8822UM\n\ T100\n\ -3122GI\n\ T1\n\ +0045KA\n\ T0\n")).toEqual({ header: {}, initial, // normalizerがpresetを復元する moves: [ {}, {move: {from: p(7, 7), to: p(7, 6), piece: "FU"}, time: {now: {m: 0, s: 12}}}, // totalはnormalizerが復元 {move: {from: p(3, 3), to: p(3, 4), piece: "FU"}, time: {now: {m: 0, s: 2}}}, {move: {from: p(8, 8), to: p(2, 2), piece: "UM"}, time: {now: {m: 1, s: 40}}}, {move: {from: p(3, 1), to: p(2, 2), piece: "GI"}, time: {now: {m: 0, s: 1}}}, {move: {to: p(4, 5), piece: "KA"}, time: {now: {m: 0, s: 0}}}, ], }); }); describe("開始局面", () => { it("平手初期局面", () => { expect(parse("\ V2.2\n\ PI82HI22KA91KY81KE21KE11KY\n\ -\n\ -5142OU\n\ +7776FU\n\ -3122GI\n\ +8866KA\n\ -7182GI\n")).toEqual({ header: {}, initial: { preset: "OTHER", data: { board: [ [{ }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "KY" }], [{ }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, { color: 0, kind: "HI" }, { color: 0, kind: "KE" }], [{ color: 1, kind: "GI" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "GI" }], [{ color: 1, kind: "KI" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "KI" }], [{ color: 1, kind: "OU" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "OU" }], [{ color: 1, kind: "KI" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "KI" }], [{ color: 1, kind: "GI" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "GI" }], [{ }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, { color: 0, kind: "KA" }, { color: 0, kind: "KE" }], [{ }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "KY" }], ], color: 1, hands: [ {FU: 0, KY: 0, KE: 0, GI: 0, KI: 0, KA: 0, HI: 0}, {FU: 0, KY: 0, KE: 0, GI: 0, KI: 0, KA: 0, HI: 0}, ], }, }, moves: [ {}, {move: {from: p(5, 1), to: p(4, 2), piece: "OU"}}, {move: {from: p(7, 7), to: p(7, 6), piece: "FU"}}, {move: {from: p(3, 1), to: p(2, 2), piece: "GI"}}, {move: {from: p(8, 8), to: p(6, 6), piece: "KA"}}, {move: {from: p(7, 1), to: p(8, 2), piece: "GI"}}, ], }); }); it("一括表現", () => { expect(parse("\ V2.2\n\ P1 * * -GI-KI-OU-KI-GI * * \n\ P1 * * * * * * * * * \n\ P3-FU-FU-FU-FU-FU-FU-FU-FU-FU\n\ P1 * * * * * * * * * \n\ P1 * * * * * * * * * \n\ P1 * * * * * * * * * \n\ P3+FU+FU+FU+FU+FU+FU+FU+FU+FU\n\ P1 * +KA * * * * * +HI * \n\ P9+KY+KE+GI+KI+OU+KI+GI+KE+KY\n\ -\n\ -5142OU\n\ +7776FU\n\ -3122GI\n\ +8866KA\n\ -7182GI\n")).toEqual({ header: {}, initial: { preset: "OTHER", data: { board: [ [{ }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "KY" }], [{ }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, { color: 0, kind: "HI" }, { color: 0, kind: "KE" }], [{ color: 1, kind: "GI" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "GI" }], [{ color: 1, kind: "KI" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "KI" }], [{ color: 1, kind: "OU" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "OU" }], [{ color: 1, kind: "KI" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "KI" }], [{ color: 1, kind: "GI" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "GI" }], [{ }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, { color: 0, kind: "KA" }, { color: 0, kind: "KE" }], [{ }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "KY" }], ], color: 1, hands: [ {FU: 0, KY: 0, KE: 0, GI: 0, KI: 0, KA: 0, HI: 0}, {FU: 0, KY: 0, KE: 0, GI: 0, KI: 0, KA: 0, HI: 0}, ], }, }, moves: [ {}, {move: {from: p(5, 1), to: p(4, 2), piece: "OU"}}, {move: {from: p(7, 7), to: p(7, 6), piece: "FU"}}, {move: {from: p(3, 1), to: p(2, 2), piece: "GI"}}, {move: {from: p(8, 8), to: p(6, 6), piece: "KA"}}, {move: {from: p(7, 1), to: p(8, 2), piece: "GI"}}, ], }); }); it("駒別単独表現", () => { expect(parse("\ V2.2\n\ P-11OU21FU22FU23FU24FU25FU26FU27FU28FU29FU\n\ P+00HI00HI00KY00KY00KY00KY\n\ P-00GI00GI00GI00GI00KE00KE00KE00KE\n\ +\n\ +0013KY\n\ -0012KE\n\ +1312NY\n")).toEqual({ header: {}, initial: { preset: "OTHER", data: { board: [ [{color: 1, kind: "OU"}, {}, {}, {}, {}, {}, {}, {}, {}], [{color: 1, kind: "FU"}, {color: 1, kind: "FU"}, {color: 1, kind: "FU"}, {color: 1, kind: "FU"}, {color: 1, kind: "FU"}, {color: 1, kind: "FU"}, {color: 1, kind: "FU"}, {color: 1, kind: "FU"}, {color: 1, kind: "FU"}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], ], color: 0, hands: [ {FU: 0, KY: 4, KE: 0, GI: 0, KI: 0, KA: 0, HI: 2}, {FU: 0, KY: 0, KE: 4, GI: 4, KI: 0, KA: 0, HI: 0}, ], }, }, moves: [ {}, {move: {to: p(1, 3), piece: "KY"}}, {move: {to: p(1, 2), piece: "KE"}}, {move: {from: p(1, 3), to: p(1, 2), piece: "NY"}}, ], }); }); it("AL", () => { expect(parse("\ V2.2\n\ P+23FU\n\ P-11OU21KE\n\ P+00KI\n\ P-00AL\n\ +\n\ +0022KI\n\ %TSUMI\n")).toEqual({ header: {}, initial: { preset: "OTHER", data: { board: [ [{color: 1, kind: "OU"}, {}, {}, {}, {}, {}, {}, {}, {}], [{color: 1, kind: "KE"}, {}, {color: 0, kind: "FU"}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], ], color: 0, hands: [ {FU: 0, KY: 0, KE: 0, GI: 0, KI: 1, KA: 0, HI: 0}, {FU: 17, KY: 4, KE: 3, GI: 4, KI: 3, KA: 2, HI: 2}, ], }, }, moves: [ {}, {move: {to: p(2, 2), piece: "KI"}}, {special: "TSUMI"}, ], }); }); }); it("header", () => { expect(parse("\ V2.2\n\ N+sente\n\ N-gote\n\ $SITE:将棋会館\n\ $START_TIME:2015/08/04 13:00:00\n\ PI\n\ +\n\ +7776FU\n\ -3334FU\n\ +7978GI\n\ -2288UM\n\ %TORYO\n")).toEqual({ header: { 先手: "sente", 後手: "gote", 場所: "将棋会館", 開始日時: "2015/08/04 13:00:00", }, initial, moves: [ {}, {move: {from: p(7, 7), to: p(7, 6), piece: "FU"}}, {move: {from: p(3, 3), to: p(3, 4), piece: "FU"}}, {move: {from: p(7, 9), to: p(7, 8), piece: "GI"}}, {move: {from: p(2, 2), to: p(8, 8), piece: "UM"}}, {special: "TORYO"}, ], }); }); it.todo("separator -- csa file can contain multiple kifus"); }); describe("csa-parser V1", () => { let initial; beforeEach(() => { initial = { preset: "OTHER", data: { board: [ [{ color: 1, kind: "KY" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "KY" }], [{ color: 1, kind: "KE" }, { color: 1, kind: "KA" }, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, { color: 0, kind: "HI" }, { color: 0, kind: "KE" }], [{ color: 1, kind: "GI" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "GI" }], [{ color: 1, kind: "KI" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "KI" }], [{ color: 1, kind: "OU" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "OU" }], [{ color: 1, kind: "KI" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "KI" }], [{ color: 1, kind: "GI" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "GI" }], [{ color: 1, kind: "KE" }, { color: 1, kind: "HI" }, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, { color: 0, kind: "KA" }, { color: 0, kind: "KE" }], [{ color: 1, kind: "KY" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "KY" }], ], color: 0, hands: [ {FU: 0, KY: 0, KE: 0, GI: 0, KI: 0, KA: 0, HI: 0}, {FU: 0, KY: 0, KE: 0, GI: 0, KI: 0, KA: 0, HI: 0}, ], }, }; }); it("simple", () => { expect(parse("\ PI\n\ +\n\ +7776FU\n\ -3334FU\n\ +8822UM\n\ -3122GI\n\ +0045KA\n")).toEqual({ header: {}, initial, // normalizerがpresetを復元する moves: [ {}, {move: {from: p(7, 7), to: p(7, 6), piece: "FU"}}, {move: {from: p(3, 3), to: p(3, 4), piece: "FU"}}, {move: {from: p(8, 8), to: p(2, 2), piece: "UM"}}, {move: {from: p(3, 1), to: p(2, 2), piece: "GI"}}, {move: {to: p(4, 5), piece: "KA"}}, ], }); }); it("comment", () => { expect(parse("\ PI\n\ +\n\ '開始時コメント\n\ +7776FU\n\ '初手コメント\n\ '初手コメント2\n\ -3334FU\n\ +8822UM\n")).toEqual({ header: {}, initial, moves: [ {comments: ["開始時コメント"]}, {move: {from: p(7, 7), to: p(7, 6), piece: "FU"}, comments: ["初手コメント", "初手コメント2"]}, {move: {from: p(3, 3), to: p(3, 4), piece: "FU"}}, {move: {from: p(8, 8), to: p(2, 2), piece: "UM"}}, ], }); }); it("special", () => { expect(parse("\ PI\n\ +\n\ +7776FU\n\ -3334FU\n\ +7978GI\n\ -2288UM\n\ %TORYO\n")).toEqual({ header: {}, initial, moves: [ {}, {move: {from: p(7, 7), to: p(7, 6), piece: "FU"}}, {move: {from: p(3, 3), to: p(3, 4), piece: "FU"}}, {move: {from: p(7, 9), to: p(7, 8), piece: "GI"}}, {move: {from: p(2, 2), to: p(8, 8), piece: "UM"}}, {special: "TORYO"}, ], }); }); it("comma", () => { expect(parse("\ PI\n\ +\n\ +7776FU,T12,-3334FU,T2\n\ +8822UM,T100\n\ -3122GI,T1\n\ +0045KA,T0\n")).toEqual({ header: {}, initial, // normalizerがpresetを復元する moves: [ {}, {move: {from: p(7, 7), to: p(7, 6), piece: "FU"}, time: {now: {m: 0, s: 12}}}, // totalはnormalizerが復元 {move: {from: p(3, 3), to: p(3, 4), piece: "FU"}, time: {now: {m: 0, s: 2}}}, {move: {from: p(8, 8), to: p(2, 2), piece: "UM"}, time: {now: {m: 1, s: 40}}}, {move: {from: p(3, 1), to: p(2, 2), piece: "GI"}, time: {now: {m: 0, s: 1}}}, {move: {to: p(4, 5), piece: "KA"}, time: {now: {m: 0, s: 0}}}, ], }); }); it("time", () => { expect(parse("\ PI\n\ +\n\ +7776FU\n\ T12\n\ -3334FU\n\ T2\n\ +8822UM\n\ T100\n\ -3122GI\n\ T1\n\ +0045KA\n\ T0\n")).toEqual({ header: {}, initial, // normalizerがpresetを復元する moves: [ {}, {move: {from: p(7, 7), to: p(7, 6), piece: "FU"}, time: {now: {m: 0, s: 12}}}, // totalはnormalizerが復元 {move: {from: p(3, 3), to: p(3, 4), piece: "FU"}, time: {now: {m: 0, s: 2}}}, {move: {from: p(8, 8), to: p(2, 2), piece: "UM"}, time: {now: {m: 1, s: 40}}}, {move: {from: p(3, 1), to: p(2, 2), piece: "GI"}, time: {now: {m: 0, s: 1}}}, {move: {to: p(4, 5), piece: "KA"}, time: {now: {m: 0, s: 0}}}, ], }); }); describe("開始局面", () => { it("平手初期局面", () => { expect(parse("\ PI82HI22KA91KY81KE21KE11KY\n\ -\n\ -5142OU\n\ +7776FU\n\ -3122GI\n\ +8866KA\n\ -7182GI\n")).toEqual({ header: {}, initial: { preset: "OTHER", data: { board: [ [{ }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "KY" }], [{ }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, { color: 0, kind: "HI" }, { color: 0, kind: "KE" }], [{ color: 1, kind: "GI" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "GI" }], [{ color: 1, kind: "KI" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "KI" }], [{ color: 1, kind: "OU" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "OU" }], [{ color: 1, kind: "KI" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "KI" }], [{ color: 1, kind: "GI" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "GI" }], [{ }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, { color: 0, kind: "KA" }, { color: 0, kind: "KE" }], [{ }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "KY" }], ], color: 1, hands: [ {FU: 0, KY: 0, KE: 0, GI: 0, KI: 0, KA: 0, HI: 0}, {FU: 0, KY: 0, KE: 0, GI: 0, KI: 0, KA: 0, HI: 0}, ], }, }, moves: [ {}, {move: {from: p(5, 1), to: p(4, 2), piece: "OU"}}, {move: {from: p(7, 7), to: p(7, 6), piece: "FU"}}, {move: {from: p(3, 1), to: p(2, 2), piece: "GI"}}, {move: {from: p(8, 8), to: p(6, 6), piece: "KA"}}, {move: {from: p(7, 1), to: p(8, 2), piece: "GI"}}, ], }); }); it("一括表現", () => { expect(parse("\ P1 * * -GI-KI-OU-KI-GI * * \n\ P1 * * * * * * * * * \n\ P3-FU-FU-FU-FU-FU-FU-FU-FU-FU\n\ P1 * * * * * * * * * \n\ P1 * * * * * * * * * \n\ P1 * * * * * * * * * \n\ P3+FU+FU+FU+FU+FU+FU+FU+FU+FU\n\ P1 * +KA * * * * * +HI * \n\ P9+KY+KE+GI+KI+OU+KI+GI+KE+KY\n\ -\n\ -5142OU\n\ +7776FU\n\ -3122GI\n\ +8866KA\n\ -7182GI\n")).toEqual({ header: {}, initial: { preset: "OTHER", data: { board: [ [{ }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "KY" }], [{ }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, { color: 0, kind: "HI" }, { color: 0, kind: "KE" }], [{ color: 1, kind: "GI" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "GI" }], [{ color: 1, kind: "KI" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "KI" }], [{ color: 1, kind: "OU" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "OU" }], [{ color: 1, kind: "KI" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "KI" }], [{ color: 1, kind: "GI" }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "GI" }], [{ }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, { color: 0, kind: "KA" }, { color: 0, kind: "KE" }], [{ }, {}, { color: 1, kind: "FU" }, {}, {}, {}, { color: 0, kind: "FU" }, {}, { color: 0, kind: "KY" }], ], color: 1, hands: [ {FU: 0, KY: 0, KE: 0, GI: 0, KI: 0, KA: 0, HI: 0}, {FU: 0, KY: 0, KE: 0, GI: 0, KI: 0, KA: 0, HI: 0}, ], }, }, moves: [ {}, {move: {from: p(5, 1), to: p(4, 2), piece: "OU"}}, {move: {from: p(7, 7), to: p(7, 6), piece: "FU"}}, {move: {from: p(3, 1), to: p(2, 2), piece: "GI"}}, {move: {from: p(8, 8), to: p(6, 6), piece: "KA"}}, {move: {from: p(7, 1), to: p(8, 2), piece: "GI"}}, ], }); }); it("駒別単独表現", () => { expect(parse("\ P-11OU21FU22FU23FU24FU25FU26FU27FU28FU29FU\n\ P+00HI00HI00KY00KY00KY00KY\n\ P-00GI00GI00GI00GI00KE00KE00KE00KE\n\ +\n\ +0013KY\n\ -0012KE\n\ +1312NY\n")).toEqual({ header: {}, initial: { preset: "OTHER", data: { board: [ [{color: 1, kind: "OU"}, {}, {}, {}, {}, {}, {}, {}, {}], [{color: 1, kind: "FU"}, {color: 1, kind: "FU"}, {color: 1, kind: "FU"}, {color: 1, kind: "FU"}, {color: 1, kind: "FU"}, {color: 1, kind: "FU"}, {color: 1, kind: "FU"}, {color: 1, kind: "FU"}, {color: 1, kind: "FU"}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], ], color: 0, hands: [ {FU: 0, KY: 4, KE: 0, GI: 0, KI: 0, KA: 0, HI: 2}, {FU: 0, KY: 0, KE: 4, GI: 4, KI: 0, KA: 0, HI: 0}, ], }, }, moves: [ {}, {move: {to: p(1, 3), piece: "KY"}}, {move: {to: p(1, 2), piece: "KE"}}, {move: {from: p(1, 3), to: p(1, 2), piece: "NY"}}, ], }); }); it("AL", () => { expect(parse("\ V2.2\n\ P+23FU\n\ P-11OU21KE\n\ P+00KI\n\ P-00AL\n\ +\n\ +0022KI\n\ %TSUMI\n")).toEqual({ header: {}, initial: { preset: "OTHER", data: { board: [ [{color: 1, kind: "OU"}, {}, {}, {}, {}, {}, {}, {}, {}], [{color: 1, kind: "KE"}, {}, {color: 0, kind: "FU"}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], [{}, {}, {}, {}, {}, {}, {}, {}, {}], ], color: 0, hands: [ {FU: 0, KY: 0, KE: 0, GI: 0, KI: 1, KA: 0, HI: 0}, {FU: 17, KY: 4, KE: 3, GI: 4, KI: 3, KA: 2, HI: 2}, ], }, }, moves: [ {}, {move: {to: p(2, 2), piece: "KI"}}, {special: "TSUMI"}, ], }); }); }); it("header", () => { expect(parse("\ N+sente\n\ N-gote\n\ PI\n\ +\n\ +7776FU\n\ -3334FU\n\ +7978GI\n\ -2288UM\n\ %TORYO\n")).toEqual({ header: { 先手: "sente", 後手: "gote", }, initial, moves: [ {}, {move: {from: p(7, 7), to: p(7, 6), piece: "FU"}}, {move: {from: p(3, 3), to: p(3, 4), piece: "FU"}}, {move: {from: p(7, 9), to: p(7, 8), piece: "GI"}}, {move: {from: p(2, 2), to: p(8, 8), piece: "UM"}}, {special: "TORYO"}, ], }); }); });
the_stack
import { spacing } from "../variables"; import { Helperclass } from "../../types/helperclass"; /* DISCLAIMER: Do not change this file because it is core styling. Customizing core files will make updating Atlas much more difficult in the future. To customize any core styling, copy the part you want to customize to styles/native/app/ so the core styling is overwritten. */ //== Inner Spacing export const spacingInnerSmallest: Helperclass = { container: { padding: spacing.smallest, }, }; export const spacingInnerVerticalSmallest: Helperclass = { container: { paddingVertical: spacing.smallest, }, }; export const spacingInnerHorizontalSmallest: Helperclass = { container: { paddingHorizontal: spacing.smallest, }, }; export const spacingInnerTopSmallest: Helperclass = { container: { paddingTop: spacing.smallest, }, }; export const spacingInnerRightSmallest: Helperclass = { container: { paddingRight: spacing.smallest, }, }; export const spacingInnerLeftSmallest: Helperclass = { container: { paddingLeft: spacing.smallest, }, }; export const spacingInnerBottomSmallest: Helperclass = { container: { paddingBottom: spacing.smallest, }, }; export const spacingInnerSmaller: Helperclass = { container: { padding: spacing.smaller, }, }; export const spacingInnerVerticalSmaller: Helperclass = { container: { paddingVertical: spacing.smaller, }, }; export const spacingInnerHorizontalSmaller: Helperclass = { container: { paddingHorizontal: spacing.smaller, }, }; export const spacingInnerTopSmaller: Helperclass = { container: { paddingTop: spacing.smaller, }, }; export const spacingInnerRightSmaller: Helperclass = { container: { paddingRight: spacing.smaller, }, }; export const spacingInnerLeftSmaller: Helperclass = { container: { paddingLeft: spacing.smaller, }, }; export const spacingInnerBottomSmaller: Helperclass = { container: { paddingBottom: spacing.smaller, }, }; export const spacingInnerSmall: Helperclass = { container: { padding: spacing.small, }, }; export const spacingInnerVerticalSmall: Helperclass = { container: { paddingVertical: spacing.small, }, }; export const spacingInnerHorizontalSmall: Helperclass = { container: { paddingHorizontal: spacing.small, }, }; export const spacingInnerTopSmall: Helperclass = { container: { paddingTop: spacing.small, }, }; export const spacingInnerRightSmall: Helperclass = { container: { paddingRight: spacing.small, }, }; export const spacingInnerLeftSmall: Helperclass = { container: { paddingLeft: spacing.small, }, }; export const spacingInnerBottomSmall: Helperclass = { container: { paddingBottom: spacing.small, }, }; export const spacingInnerMedium: Helperclass = { container: { padding: spacing.regular, }, }; export const spacingInnerVerticalMedium: Helperclass = { container: { paddingVertical: spacing.regular, }, }; export const spacingInnerHorizontalMedium: Helperclass = { container: { paddingHorizontal: spacing.regular, }, }; export const spacingInnerTopMedium: Helperclass = { container: { paddingTop: spacing.regular, }, }; export const spacingInnerRightMedium: Helperclass = { container: { paddingRight: spacing.regular, }, }; export const spacingInnerLeftMedium: Helperclass = { container: { paddingLeft: spacing.regular, }, }; export const spacingInnerBottomMedium: Helperclass = { container: { paddingBottom: spacing.regular, }, }; export const spacingInnerLarge: Helperclass = { container: { padding: spacing.large, }, }; export const spacingInnerVerticalLarge: Helperclass = { container: { paddingVertical: spacing.large, }, }; export const spacingInnerHorizontalLarge: Helperclass = { container: { paddingHorizontal: spacing.large, }, }; export const spacingInnerTopLarge: Helperclass = { container: { paddingTop: spacing.large, }, }; export const spacingInnerRightLarge: Helperclass = { container: { paddingRight: spacing.large, }, }; export const spacingInnerLeftLarge: Helperclass = { container: { paddingLeft: spacing.large, }, }; export const spacingInnerBottomLarge: Helperclass = { container: { paddingBottom: spacing.large, }, }; export const spacingInnerLarger: Helperclass = { container: { padding: spacing.larger, }, }; export const spacingInnerVerticalLarger: Helperclass = { container: { paddingVertical: spacing.larger, }, }; export const spacingInnerHorizontalLarger: Helperclass = { container: { paddingHorizontal: spacing.larger, }, }; export const spacingInnerTopLarger: Helperclass = { container: { paddingTop: spacing.larger, }, }; export const spacingInnerRightLarger: Helperclass = { container: { paddingRight: spacing.larger, }, }; export const spacingInnerLeftLarger: Helperclass = { container: { paddingLeft: spacing.larger, }, }; export const spacingInnerBottomLarger: Helperclass = { container: { paddingBottom: spacing.larger, }, }; export const spacingInnerLargest: Helperclass = { container: { padding: spacing.largest, }, }; export const spacingInnerVerticalLargest: Helperclass = { container: { paddingVertical: spacing.largest, }, }; export const spacingInnerHorizontalLargest: Helperclass = { container: { paddingHorizontal: spacing.largest, }, }; export const spacingInnerTopLargest: Helperclass = { container: { paddingTop: spacing.largest, }, }; export const spacingInnerRightLargest: Helperclass = { container: { paddingRight: spacing.largest, }, }; export const spacingInnerLeftLargest: Helperclass = { container: { paddingLeft: spacing.largest, }, }; export const spacingInnerBottomLargest: Helperclass = { container: { paddingBottom: spacing.largest, }, }; // // //== Outer Spacing export const spacingOuterSmallest: Helperclass = { container: { margin: spacing.smallest, }, }; export const spacingOuterVerticalSmallest: Helperclass = { container: { marginVertical: spacing.smallest, }, }; export const spacingOuterHorizontalSmallest: Helperclass = { container: { marginHorizontal: spacing.smallest, }, }; export const spacingOuterTopSmallest: Helperclass = { container: { marginTop: spacing.smallest, }, }; export const spacingOuterRightSmallest: Helperclass = { container: { marginRight: spacing.smallest, }, }; export const spacingOuterLeftSmallest: Helperclass = { container: { marginLeft: spacing.smallest, }, }; export const spacingOuterBottomSmallest: Helperclass = { container: { marginBottom: spacing.smallest, }, }; export const spacingOuterSmaller: Helperclass = { container: { margin: spacing.smaller, }, }; export const spacingOuterVerticalSmaller: Helperclass = { container: { marginVertical: spacing.smaller, }, }; export const spacingOuterHorizontalSmaller: Helperclass = { container: { marginHorizontal: spacing.smaller, }, }; export const spacingOuterTopSmaller: Helperclass = { container: { marginTop: spacing.smaller, }, }; export const spacingOuterRightSmaller: Helperclass = { container: { marginRight: spacing.smaller, }, }; export const spacingOuterLeftSmaller: Helperclass = { container: { marginLeft: spacing.smaller, }, }; export const spacingOuterBottomSmaller: Helperclass = { container: { marginBottom: spacing.smaller, }, }; export const spacingOuterSmall: Helperclass = { container: { margin: spacing.small, }, }; export const spacingOuterVerticalSmall: Helperclass = { container: { marginVertical: spacing.small, }, }; export const spacingOuterHorizontalSmall: Helperclass = { container: { marginHorizontal: spacing.small, }, }; export const spacingOuterTopSmall: Helperclass = { container: { marginTop: spacing.small, }, }; export const spacingOuterRightSmall: Helperclass = { container: { marginRight: spacing.small, }, }; export const spacingOuterLeftSmall: Helperclass = { container: { marginLeft: spacing.small, }, }; export const spacingOuterBottomSmall: Helperclass = { container: { marginBottom: spacing.small, }, }; export const spacingOuterMedium: Helperclass = { container: { margin: spacing.regular, }, }; export const spacingOuterVerticalMedium: Helperclass = { container: { marginVertical: spacing.regular, }, }; export const spacingOuterHorizontalMedium: Helperclass = { container: { marginHorizontal: spacing.regular, }, }; export const spacingOuterTopMedium: Helperclass = { container: { marginTop: spacing.regular, }, }; export const spacingOuterRightMedium: Helperclass = { container: { marginRight: spacing.regular, }, }; export const spacingOuterLeftMedium: Helperclass = { container: { marginLeft: spacing.regular, }, }; export const spacingOuterBottomMedium: Helperclass = { container: { marginBottom: spacing.regular, }, }; export const spacingOuterLarge: Helperclass = { container: { margin: spacing.large, }, }; export const spacingOuterVerticalLarge: Helperclass = { container: { marginVertical: spacing.large, }, }; export const spacingOuterHorizontalLarge: Helperclass = { container: { marginHorizontal: spacing.large, }, }; export const spacingOuterTopLarge: Helperclass = { container: { marginTop: spacing.large, }, }; export const spacingOuterRightLarge: Helperclass = { container: { marginRight: spacing.large, }, }; export const spacingOuterLeftLarge: Helperclass = { container: { marginLeft: spacing.large, }, }; export const spacingOuterBottomLarge: Helperclass = { container: { marginBottom: spacing.large, }, }; export const spacingOuterLarger: Helperclass = { container: { margin: spacing.larger, }, }; export const spacingOuterVerticalLarger: Helperclass = { container: { marginVertical: spacing.larger, }, }; export const spacingOuterHorizontalLarger: Helperclass = { container: { marginHorizontal: spacing.larger, }, }; export const spacingOuterTopLarger: Helperclass = { container: { marginTop: spacing.larger, }, }; export const spacingOuterRightLarger: Helperclass = { container: { marginRight: spacing.larger, }, }; export const spacingOuterLeftLarger: Helperclass = { container: { marginLeft: spacing.larger, }, }; export const spacingOuterBottomLarger: Helperclass = { container: { marginBottom: spacing.larger, }, }; export const spacingOuterLargest: Helperclass = { container: { margin: spacing.largest, }, }; export const spacingOuterVerticalLargest: Helperclass = { container: { marginVertical: spacing.largest, }, }; export const spacingOuterHorizontalLargest: Helperclass = { container: { marginHorizontal: spacing.largest, }, }; export const spacingOuterTopLargest: Helperclass = { container: { marginTop: spacing.largest, }, }; export const spacingOuterRightLargest: Helperclass = { container: { marginRight: spacing.largest, }, }; export const spacingOuterLeftLargest: Helperclass = { container: { marginLeft: spacing.largest, }, }; export const spacingOuterBottomLargest: Helperclass = { container: { marginBottom: spacing.largest, }, };
the_stack
import { Color, Theme } from '@material-ui/core'; import amber from '@material-ui/core/colors/amber'; import deepOrange from '@material-ui/core/colors/deepOrange'; import lime from '@material-ui/core/colors/lime'; import orange from '@material-ui/core/colors/orange'; import red from '@material-ui/core/colors/red'; import React from 'react'; import API from '../api/API'; import { Channel, Group, VersionBreakdownEntry } from '../api/apiDataTypes'; export const SearchFilterClassifiers = [ { name: 'id', queryValue: 'id', }, { name: 'ip', queryValue: 'ip', }, { name: 'alias', queryValue: 'alias', }, { name: 'name', queryValue: 'alias', }, ]; // Indexes/keys for the architectures need to match the ones in // pkg/api/arches.go. export const ARCHES: { [key: number]: string; } = { 0: 'ALL', 1: 'AMD64', 2: 'ARM64', 3: 'X86', }; // Indexes/keys for the instancesFilter need to match the ones in // pkg/api/instances.go. export const InstanceSortFilters: { [key: string]: string; } = { id: '0', ip: '1', 'last-check': '2', }; export function getKeyByValue(object: { [key: string]: any }, value: any) { return Object.keys(object).find((key: any) => object[key] === value); } export const ERROR_STATUS_CODE = 3; const colors = makeColors(); export const timeIntervalsDefault = [ { displayValue: '30 days', queryValue: '30d', disabled: false }, { displayValue: '7 days', queryValue: '7d', disabled: false }, { displayValue: '1 day', queryValue: '1d', disabled: false }, { displayValue: '1 hour', queryValue: '1h', disabled: false }, ]; export const defaultTimeInterval = timeIntervalsDefault.filter( interval => interval.queryValue === '1d' )[0]; function makeColors() { const colors: string[] = []; const colorScheme = [lime, amber, orange, deepOrange, red]; // Create a color list for versions to pick from. colorScheme.forEach((color: Color) => { // We choose the shades beyond 300 because they should not be too // light (in order to improve contrast). for (let i = 3; i <= 9; i += 2) { //@ts-ignore colors.push(color[i * 100]); } }); return colors; } export function cleanSemverVersion(version: string) { let shortVersion = version; if (version.includes('+')) { shortVersion = version.split('+')[0]; } return shortVersion; } export function getMinuteDifference(date1: number, date2: number) { return (date1 - date2) / 1000 / 60; } export function makeLocaleTime( timestamp: string | Date | number, opts: { useDate?: boolean; showTime?: boolean; dateFormat?: Intl.DateTimeFormatOptions } = {} ) { const { useDate = true, showTime = true, dateFormat = {} } = opts; const date = new Date(timestamp); const formattedDate = date.toLocaleDateString('default', dateFormat); const timeFormat = date.toLocaleString('default', { hour: '2-digit', minute: '2-digit' }); if (useDate && showTime) { return `${formattedDate} ${timeFormat}`; } if (useDate) { return formattedDate; } return timeFormat; } export function makeColorsForVersions( theme: Theme, versions: string[], channel: Channel | null = null ) { const versionColors: { [key: string]: string } = {}; let colorIndex = 0; let latestVersion = null; if (channel && channel.package) { latestVersion = cleanSemverVersion(channel.package.version); } for (let i = versions.length - 1; i >= 0; i--) { const version = versions[i]; const cleanVersion = cleanSemverVersion(version); if (cleanVersion === latestVersion) { versionColors[cleanVersion] = theme.palette.primary.main; } else { versionColors[cleanVersion] = colors[colorIndex++ % colors.length]; } } return versionColors; } export function getInstanceStatus(statusID: number | null, version?: string) { const status: { [x: number]: { type: string; className: string; spinning: boolean; icon: string; description: string; status: string; explanation: string; textColor?: string; bgColor?: string; }; } = { 1: { type: 'InstanceStatusUndefined', className: '', spinning: false, icon: '', description: '', status: 'Undefined', explanation: '', }, 2: { type: 'InstanceStatusUpdateGranted', className: 'warning', spinning: true, icon: '', description: 'Updating: granted', textColor: '#061751', bgColor: 'rgba(6, 23, 81, 0.1)', status: 'Granted', explanation: 'The instance has received an update package -version ' + version + '- and the update process is about to start', }, 3: { type: 'InstanceStatusError', className: 'danger', spinning: false, icon: 'glyphicon glyphicon-remove', description: 'Error updating', bgColor: 'rgba(244, 67, 54, 0.1)', textColor: '#F44336', status: 'Error', explanation: 'The instance reported an error while updating to version ' + version, }, 4: { type: 'InstanceStatusComplete', className: 'success', spinning: false, icon: 'glyphicon glyphicon-ok', description: 'Update completed', status: 'Completed', textColor: '#26B640', bgColor: 'rgba(38, 182, 64, 0.1)', explanation: 'The instance has been updated successfully and is now running version ' + version, }, 5: { type: 'InstanceStatusInstalled', className: 'warning', spinning: true, icon: '', description: 'Updating: installed', status: 'Installed', explanation: 'The instance has installed the update package -version ' + version + '- but it isn’t using it yet', }, 6: { type: 'InstanceStatusDownloaded', className: 'warning', spinning: true, icon: '', description: 'Updating: downloaded', bgColor: 'rgba(44, 152, 240, 0.1)', textColor: '#195586', status: 'Downloaded', explanation: 'The instance has downloaded the update package -version ' + version + '- and will install it now', }, 7: { type: 'InstanceStatusDownloading', className: 'warning', spinning: true, icon: '', description: 'Updating: downloading', textColor: '#808080', bgColor: 'rgba(128, 128, 128, 0.1)', status: 'Downloading', explanation: 'The instance has just started downloading the update package -version ' + version + '-', }, 8: { type: 'InstanceStatusOnHold', className: 'default', spinning: false, icon: '', description: 'Waiting...', status: 'On hold', explanation: 'There was an update pending for the instance but it was put on hold because of the rollout policy', }, }; const statusDetails = statusID ? status[statusID] : status[1]; return statusDetails; } export function useGroupVersionBreakdown(group: Group) { const [versionBreakdown, setVersionBreakdown] = React.useState<VersionBreakdownEntry[]>([]); React.useEffect(() => { if (!group) { return; } API.getGroupVersionBreakdown(group.application_id, group.id) .then(versions => { setVersionBreakdown(versions); }) .catch(err => { console.error('Error getting version breakdown for group', group.id, '\nError:', err); }); }, [group]); return versionBreakdown; } // Keep in sync with https://github.com/flatcar-linux/update_engine/blob/flatcar-master/src/update_engine/action_processor.h#L25 const actionCodes: { [x: string]: string } = { '1': 'Error', '2': 'OmahaRequestError', '3': 'OmahaResponseHandlerError', '4': 'FilesystemCopierError', '5': 'PostinstallRunnerError', '6': 'SetBootableFlagError', '7': 'InstallDeviceOpenError', '8': 'KernelDeviceOpenError', '9': 'DownloadTransferError', '10': 'PayloadHashMismatchError', '11': 'PayloadSizeMismatchError', '12': 'DownloadPayloadVerificationError', '13': 'DownloadNewPartitionInfoError', '14': 'DownloadWriteError', '15': 'NewRootfsVerificationError', '16': 'NewKernelVerificationError', '17': 'SignedDeltaPayloadExpectedError', '18': 'DownloadPayloadPubKeyVerificationError', '19': 'PostinstallBootedFromFirmwareB', '20': 'DownloadStateInitializationError', '21': 'DownloadInvalidMetadataMagicString', '22': 'DownloadSignatureMissingInManifest', '23': 'DownloadManifestParseError', '24': 'DownloadMetadataSignatureError', '25': 'DownloadMetadataSignatureVerificationError', '26': 'DownloadMetadataSignatureMismatch', '27': 'DownloadOperationHashVerificationError', '28': 'DownloadOperationExecutionError', '29': 'DownloadOperationHashMismatch', '30': 'OmahaRequestEmptyResponseError', '31': 'OmahaRequestXMLParseError', '32': 'DownloadInvalidMetadataSize', '33': 'DownloadInvalidMetadataSignature', '34': 'OmahaResponseInvalid', '35': 'OmahaUpdateIgnoredPerPolicy', '36': 'OmahaUpdateDeferredPerPolicy', '37': 'OmahaErrorInHTTPResponse', '38': 'DownloadOperationHashMissingError', '39': 'DownloadMetadataSignatureMissingError', '40': 'OmahaUpdateDeferredForBackoff', '41': 'PostinstallPowerwashError', '42': 'NewPCRPolicyVerificationError', '43': 'NewPCRPolicyHTTPError', '44': 'RollbackError', '100': 'DownloadIncomplete', '2000': 'OmahaRequestHTTPResponseBase', }; const flagsCodes: { [x: number]: string } = { [Math.pow(2, 31)]: 'DevModeFlag', [Math.pow(2, 30)]: 'ResumedFlag', [Math.pow(2, 29)]: 'TestImageFlag', [Math.pow(2, 28)]: 'TestOmahaUrlFlag', }; export function getErrorAndFlags(errorCode: number) { const errorMessage = []; let errorCodeVal = errorCode; // Extract and remove flags from the error code var flags = []; for (const [flag, flagValue] of Object.entries(flagsCodes)) { if (errorCodeVal & parseInt(flag)) { errorCodeVal &= ~flag; flags.push(flagValue); } } if (actionCodes[errorCodeVal]) { errorMessage.push(actionCodes[errorCodeVal]); } else if (errorCodeVal > 2000 && errorCodeVal < 3000) { errorMessage.push(`Http error code(${errorCodeVal - 2000})`); } else { errorMessage.push(`Unknown Error ${errorCodeVal}`); } return [errorMessage, flags]; } export function prepareErrorMessage(errorMessages: string[], flags: string[]) { const enhancedErrorMessages = errorMessages.reduce((acc, val) => `${val} ${acc}`, ''); const enhancedFlags = flags.reduce((acc, val) => `${val} ${acc}`, ''); return `${enhancedErrorMessages} ${enhancedFlags.length > 0 ? ' with ' + enhancedFlags : ''}`; }
the_stack
import * as fse from 'fs-extra'; import test from 'ava'; import { join } from '../src/path'; import { Diff } from '../src/diff'; import { COMMIT_ORDER, Repository } from '../src/repository'; import { getRandomPath } from './helper'; import { Commit } from '../src/commit'; const sortPaths = require('sort-paths'); function writeFileAndCommit(repo: Repository, filename: string, message: string): Promise<Commit> { return fse.writeFile(join(repo.workdir(), filename), message) .then(() => { const index = repo.ensureMainIndex(); index.addFiles([filename]); return index.writeFiles(); }).then(() => { const index = repo.getFirstIndex(); return repo.createCommit(index, message); }); } function deleteFileAndCommit(repo: Repository, filename: string, message: string): Promise<Commit> { return fse.unlink(join(repo.workdir(), filename)) .then(() => { const index = repo.ensureMainIndex(); index.deleteFiles([filename]); return index.writeFiles(); }).then(() => { const index = repo.getFirstIndex(); return repo.createCommit(index, message); }); } test('Diff.basic', async (t) => { const repoPath = getRandomPath(); const repo = await Repository.initExt(repoPath); const commit0: Commit = repo.getAllCommits(COMMIT_ORDER.OLDEST_FIRST)[0]; // Commit 1: create a file fooA.txt const commit1: Commit = await writeFileAndCommit(repo, 'fooA.txt', 'some-random-content'); // Commit 2: modify fooA.txt const commit2: Commit = await writeFileAndCommit(repo, 'fooA.txt', 'another-random-content'); // Commit 3: create a file fooB.txt const commit3: Commit = await writeFileAndCommit(repo, 'fooB.txt', 'fooB-content'); // Commit 4: create a file fooB.txt const commit4: Commit = await deleteFileAndCommit(repo, 'fooB.txt', 'delete fooB.txt'); const test0 = () => { t.log('Compare initial commit with itself'); const diff = new Diff(commit0, commit0, { includeDirs: true }); const addedArray = Array.from(diff.added()); t.is(addedArray.length, 0, 'expected 0 elements'); const modifiedArray = Array.from(diff.modified()); t.is(modifiedArray.length, 0, 'expected 0 elements'); const nonModifiedArray = Array.from(diff.nonModified()); t.is(nonModifiedArray.length, 0, 'expected 0 elements'); const deletedArray = Array.from(diff.deleted()); t.is(deletedArray.length, 0, 'expected 0 elements'); }; const test1 = () => { t.log('Compare initial commit with first commit'); const diff = new Diff(commit1, commit0, { includeDirs: true }); const addedArray = Array.from(diff.added()); t.is(addedArray.length, 1, 'expected 1 element: fooA.txt'); t.is(addedArray[0].path, 'fooA.txt'); t.is(addedArray[0].hash, '43d18c0f9e453f787c9649a6532d5270ab9a180baa635944d9501ae8ffb44387'); const modifiedArray = Array.from(diff.modified()); t.is(modifiedArray.length, 0, 'expected 0 elements'); const nonModifiedArray = Array.from(diff.nonModified()); t.is(nonModifiedArray.length, 0, 'expected 0 elements'); const deletedArray = Array.from(diff.deleted()); t.is(deletedArray.length, 0, 'expected 0 elements'); }; const test2 = () => { t.log('Compare second commit with first commit'); const diff = new Diff(commit2, commit1, { includeDirs: true }); const addedArray = Array.from(diff.added()); t.is(addedArray.length, 0, 'expected 0 elements'); const modifiedArray = Array.from(diff.modified()); t.is(modifiedArray.length, 1, 'expected 1 element: fooA.txt'); t.is(modifiedArray[0].path, 'fooA.txt'); t.is(modifiedArray[0].hash, '0a81db0c8c27c03e00934e074da1423a1b621f447e22bd1c423b491ecd27ee31'); const nonModifiedArray = Array.from(diff.nonModified()); t.is(nonModifiedArray.length, 0, 'expected 0 elements'); const deletedArray = Array.from(diff.deleted()); t.is(deletedArray.length, 0, 'expected 0 elements'); }; const test3 = () => { t.log('Compare second commit with itself'); const diff = new Diff(commit2, commit2, { includeDirs: true }); const addedArray = Array.from(diff.added()); t.is(addedArray.length, 0, 'expected 0 elements'); const modifiedArray = Array.from(diff.modified()); t.is(modifiedArray.length, 0, 'expected 0 elements'); const nonModifiedArray = Array.from(diff.nonModified()); t.is(nonModifiedArray.length, 1, 'expected 1 element: fooA.txt'); t.is(nonModifiedArray[0].path, 'fooA.txt'); t.is(nonModifiedArray[0].hash, '0a81db0c8c27c03e00934e074da1423a1b621f447e22bd1c423b491ecd27ee31'); const deletedArray = Array.from(diff.deleted()); t.is(deletedArray.length, 0, 'expected 0 elements'); }; const test4 = () => { t.log('Compare 3rd commit with 2nd commit'); const diff = new Diff(commit3, commit2, { includeDirs: true }); const addedArray = Array.from(diff.added()); t.is(addedArray.length, 1, 'expected 1 element: fooA.txt'); t.is(addedArray[0].path, 'fooB.txt'); t.is(addedArray[0].hash, 'ca90917cccffe77b6c01bab4a3ebc77243d784e1874dda8f35e217a858ea05f2'); const modifiedArray = Array.from(diff.modified()); t.is(modifiedArray.length, 0, 'expected 0 elements'); const nonModifiedArray = Array.from(diff.nonModified()); t.is(nonModifiedArray.length, 1, 'expected 1 element: fooA.txt'); t.is(nonModifiedArray[0].path, 'fooA.txt'); t.is(nonModifiedArray[0].hash, '0a81db0c8c27c03e00934e074da1423a1b621f447e22bd1c423b491ecd27ee31'); const deletedArray = Array.from(diff.deleted()); t.is(deletedArray.length, 0, 'expected 0 elements'); }; const test5 = () => { t.log('Compare 4th commit with 3rd commit'); const diff = new Diff(commit4, commit3, { includeDirs: true }); const addedArray = Array.from(diff.added()); t.is(addedArray.length, 0, 'expected 0 elements'); const modifiedArray = Array.from(diff.modified()); t.is(modifiedArray.length, 0, 'expected 0 elements'); const nonModifiedArray = Array.from(diff.nonModified()); t.is(nonModifiedArray.length, 1, 'expected 1 element: fooA.txt'); t.is(nonModifiedArray[0].path, 'fooA.txt'); t.is(nonModifiedArray[0].hash, '0a81db0c8c27c03e00934e074da1423a1b621f447e22bd1c423b491ecd27ee31'); const deletedArray = Array.from(diff.deleted()); t.is(deletedArray.length, 1, 'expected 1 element: fooB.txt'); t.is(deletedArray[0].path, 'fooB.txt'); t.is(deletedArray[0].hash, 'ca90917cccffe77b6c01bab4a3ebc77243d784e1874dda8f35e217a858ea05f2'); }; const test6 = () => { t.log('Compare initial commit with 3rd commit'); const diff = new Diff(commit3, commit0, { includeDirs: true }); const addedArray = Array.from(diff.added()); t.is(addedArray.length, 2, 'expected 2 elements: fooA.txt, fooB.txt'); t.is(addedArray[0].path, 'fooA.txt'); t.is(addedArray[0].hash, '0a81db0c8c27c03e00934e074da1423a1b621f447e22bd1c423b491ecd27ee31'); t.is(addedArray[1].path, 'fooB.txt'); t.is(addedArray[1].hash, 'ca90917cccffe77b6c01bab4a3ebc77243d784e1874dda8f35e217a858ea05f2'); const modifiedArray = Array.from(diff.modified()); t.is(modifiedArray.length, 0, 'expected 0 elements'); const nonModifiedArray = Array.from(diff.nonModified()); t.is(nonModifiedArray.length, 0, 'expected 0 elements'); const deletedArray = Array.from(diff.deleted()); t.is(deletedArray.length, 0, 'expected 0 elements'); }; test0(); test1(); test2(); test3(); test4(); test5(); test6(); }); test('Diff with subdirectories', async (t) => { const repoPath = getRandomPath(); const repo = await Repository.initExt(repoPath); const commit0: Commit = repo.getAllCommits(COMMIT_ORDER.OLDEST_FIRST)[0]; fse.ensureDirSync(join(repo.workdir(), 'subdir1')); fse.ensureDirSync(join(repo.workdir(), 'subdir2')); // Commit 1: create various files and commit fse.writeFileSync(join(repo.workdir(), 'subdir1/fooA.txt'), 'content: subdir1/fooA.txt'); fse.writeFileSync(join(repo.workdir(), 'subdir1/fooB.txt'), 'content: subdir1/fooB.txt'); fse.writeFileSync(join(repo.workdir(), 'subdir1/fooC.txt'), 'content: subdir1/fooC.txt'); fse.writeFileSync(join(repo.workdir(), 'subdir1/fooD.txt'), 'content: subdir1/fooD.txt'); fse.writeFileSync(join(repo.workdir(), 'subdir2/fooA.txt'), 'content: subdir2/fooA.txt'); fse.writeFileSync(join(repo.workdir(), 'subdir2/fooB.txt'), 'content: subdir2/fooB.txt'); fse.writeFileSync(join(repo.workdir(), 'fooA.txt'), 'content: fooA'); let index = repo.ensureMainIndex(); index.addFiles([ 'subdir1/fooA.txt', 'subdir1/fooB.txt', 'subdir1/fooC.txt', 'subdir1/fooD.txt', 'subdir2/fooA.txt', 'subdir2/fooB.txt', 'fooA.txt', ]); await index.writeFiles(); const commit1 = await repo.createCommit(index, 'commit1'); fse.writeFileSync(join(repo.workdir(), 'subdir2/fooA.txt'), 'content: subdir2/fooA.txt modified'); index = repo.ensureMainIndex(); index.addFiles(['subdir2/fooA.txt']); await index.writeFiles(); const commit2 = await repo.createCommit(index, 'commit2'); const test0 = () => { t.log('Compare initial commit with first commit'); const diff = new Diff(commit1, commit0, { includeDirs: true }); const addedArray = Array.from(diff.added()); const sortedAddedArray = sortPaths(addedArray, (item) => item.path, '/'); t.is(sortedAddedArray.length, 9, 'expected 1 element: fooA.txt'); t.is(sortedAddedArray[0].path, 'fooA.txt'); t.is(sortedAddedArray[0].hash, 'fbb70f5f22a0f1040c9978351c8b3302fa0f77044e36d6ca0fdb0b646fc32611'); t.is(sortedAddedArray[1].path, 'subdir1'); t.is(sortedAddedArray[1].hash, '34f40a8f2533b51ed3cdc44d0913431f7b6642cea194eea982ff6aa268c85e48'); t.is(sortedAddedArray[2].path, 'subdir2'); t.is(sortedAddedArray[2].hash, '86aee0487e56510ef47d0c6c369f08ba5585e57a251d9c39461519430bc358d4'); t.is(sortedAddedArray[3].path, 'subdir1/fooA.txt'); t.is(sortedAddedArray[3].hash, 'eb4d879649dbc97e1bcc280c1abcd56c30d211da2a0f3ec7e6251124c7646edd'); t.is(sortedAddedArray[4].path, 'subdir1/fooB.txt'); t.is(sortedAddedArray[4].hash, '81a281150cd97e24ce7628d98f90b1789676fbad19f6bb7c50676d41144b813c'); t.is(sortedAddedArray[5].path, 'subdir1/fooC.txt'); t.is(sortedAddedArray[5].hash, '1911748a6284c23df9f9619151a364c0d0fd9d05b3386a1b808fa7773f90c2ad'); t.is(sortedAddedArray[6].path, 'subdir1/fooD.txt'); t.is(sortedAddedArray[6].hash, '1baf798eba71b480295794fadf3e929b97c36001a985ccddffdddad445b21aa4'); t.is(sortedAddedArray[7].path, 'subdir2/fooA.txt'); t.is(sortedAddedArray[7].hash, '61ec705e763af9e3b2e5c12deba78cb11f51e429f8a4aa4160922d9a926bba16'); t.is(sortedAddedArray[8].path, 'subdir2/fooB.txt'); t.is(sortedAddedArray[8].hash, '26a9e4753ef2791e012bca321f9f9cacba992b752d9e38710e157d05396af65a'); const modifiedArray = Array.from(diff.modified()); t.is(modifiedArray.length, 0, 'expected 0 elements'); const nonModifiedArray = Array.from(diff.nonModified()); t.is(nonModifiedArray.length, 0, 'expected 0 elements'); const deletedArray = Array.from(diff.deleted()); t.is(deletedArray.length, 0, 'expected 0 elements'); }; const test1 = () => { t.log('Compare 2nd commit with first commit'); const diff = new Diff(commit2, commit1, { includeDirs: true }); const addedArray = Array.from(diff.added()); t.is(addedArray.length, 0, 'expected 0 elements'); const modifiedArray = Array.from(diff.modified()); t.is(modifiedArray.length, 2, 'expected 1 element: fooA.txt'); t.is(modifiedArray[0].path, 'subdir2'); t.is(modifiedArray[0].hash, '694f3d7ec5fc89cf64dc1ada0b3117ed78dec08e0794328e5836edc7f4ca69ef'); t.is(modifiedArray[1].path, 'subdir2/fooA.txt'); t.is(modifiedArray[1].hash, '0c6611c83f11f7dc822c64c3f1e934907bef406b802e6d7be979171743b25da2'); const nonModifiedArray = Array.from(diff.nonModified()); const sortedNonModifiedArray = sortPaths(nonModifiedArray, (item) => item.path, '/'); t.is(sortedNonModifiedArray[0].path, 'fooA.txt'); t.is(sortedNonModifiedArray[0].hash, 'fbb70f5f22a0f1040c9978351c8b3302fa0f77044e36d6ca0fdb0b646fc32611'); t.is(sortedNonModifiedArray[1].path, 'subdir1'); t.is(sortedNonModifiedArray[1].hash, '34f40a8f2533b51ed3cdc44d0913431f7b6642cea194eea982ff6aa268c85e48'); t.is(sortedNonModifiedArray[2].path, 'subdir1/fooA.txt'); t.is(sortedNonModifiedArray[2].hash, 'eb4d879649dbc97e1bcc280c1abcd56c30d211da2a0f3ec7e6251124c7646edd'); t.is(sortedNonModifiedArray[3].path, 'subdir1/fooB.txt'); t.is(sortedNonModifiedArray[3].hash, '81a281150cd97e24ce7628d98f90b1789676fbad19f6bb7c50676d41144b813c'); t.is(sortedNonModifiedArray[4].path, 'subdir1/fooC.txt'); t.is(sortedNonModifiedArray[4].hash, '1911748a6284c23df9f9619151a364c0d0fd9d05b3386a1b808fa7773f90c2ad'); t.is(sortedNonModifiedArray[5].path, 'subdir1/fooD.txt'); t.is(sortedNonModifiedArray[5].hash, '1baf798eba71b480295794fadf3e929b97c36001a985ccddffdddad445b21aa4'); t.is(sortedNonModifiedArray[6].path, 'subdir2/fooB.txt'); t.is(sortedNonModifiedArray[6].hash, '26a9e4753ef2791e012bca321f9f9cacba992b752d9e38710e157d05396af65a'); const deletedArray = Array.from(diff.deleted()); t.is(deletedArray.length, 0, 'expected 0 elements'); }; test0(); test1(); });
the_stack
import { classHasOwnProperty, getArgumentNames, getClassProperties, getDeepestClass, getDefaultPrimitiveTypeValue, getMetadata, getMetadataKeys, hasMetadata, isClassIterable, isConstructorPrimitiveType, isIterableNoMapNoString, isSameConstructor, isSameConstructorOrExtensionOf, isSameConstructorOrExtensionOfNoObject, makeMetadataKeysWithContext, mapClassPropertyToVirtualProperty, mapVirtualPropertiesToClassProperties, mapVirtualPropertyToClassProperty, sortMappersByOrder } from '../util'; import { ClassType, ClassTypeWithDecoratorDefinitions, JsonAliasOptions, JsonAppendOptions, JsonClassTypeOptions, JsonDecoratorOptions, JsonDeserializeOptions, JsonIdentityInfoOptions, JsonIgnorePropertiesOptions, JsonInjectOptions, JsonManagedReferenceOptions, JsonNamingOptions, JsonParserContext, JsonParserTransformerContext, JsonPropertyOptions, JsonRootNameOptions, JsonSubTypesOptions, JsonTypeIdResolverOptions, JsonTypeInfoOptions, JsonViewOptions, InternalDecorators, JsonUnwrappedOptions, JsonCreatorOptions, JsonSetterOptions, JsonBackReferenceOptions, JsonAnySetterOptions, JsonGetterOptions } from '../@types'; import { JsonPropertyAccess, JsonTypeInfoAs, JsonTypeInfoId, PropertyNamingStrategy, defaultCreatorName, JsonCreatorMode, JsonSetterNulls } from '../decorators'; import {JacksonError} from './JacksonError'; import * as cloneDeep from 'lodash.clonedeep'; import * as clone from 'lodash.clone'; import {DefaultDeserializationFeatureValues} from '../databind'; /** * Json Parser Global Context used by {@link JsonParser.transform} to store global information. */ interface JsonParserGlobalContext { /** * Map used to restore object circular references defined by {@link JsonIdentityInfo}. */ globalValueAlreadySeen: Map<string, any>; /** * Map used to store unresolved object identities defined by {@link JsonIdentityInfo}. */ globalUnresolvedObjectIdentities: Set<string>; } /** * JsonParser provides functionality for reading JSON. * It is also highly customizable to work both with different styles of JSON content, * and to support more advanced Object concepts such as polymorphism and Object identity. */ export class JsonParser<T> { /** * Default context to use during deserialization. */ defaultContext: JsonParserContext = {}; /** * * @param defaultContext - Default context to use during deserialization. */ constructor(defaultContext: JsonParserContext = JsonParser.makeDefaultContext()) { this.defaultContext = defaultContext; } /** * Make a default {@link JsonParserContext}. */ static makeDefaultContext(): JsonParserContext { return { mainCreator: null, features: { deserialization: { ...DefaultDeserializationFeatureValues } }, deserializers: [], decoratorsEnabled: {}, withViews: null, forType: new Map(), withContextGroups: [], _internalDecorators: new Map(), _propertyParentCreator: null, injectableValues: {}, withCreatorName: null }; } /** * Merge multiple {@link JsonParserContext} into one. * Array direct properties will be concatenated, instead, Map and Object Literal direct properties will be merged. * All the other properties, such as {@link JsonParserContext.mainCreator}, will be completely replaced. * * @param contexts - list of contexts to be merged. */ static mergeContexts(contexts: JsonParserContext[]): JsonParserContext { const finalContext = JsonParser.makeDefaultContext(); for (const context of contexts) { if (context == null) { continue; } if (context.mainCreator != null) { finalContext.mainCreator = context.mainCreator; } if (context.decoratorsEnabled != null) { finalContext.decoratorsEnabled = { ...finalContext.decoratorsEnabled, ...context.decoratorsEnabled }; } if (context.withViews != null) { finalContext.withViews = context.withViews; } if (context.withContextGroups != null) { finalContext.withContextGroups = finalContext.withContextGroups.concat(context.withContextGroups); } if (context.deserializers != null) { finalContext.deserializers = finalContext.deserializers.concat(context.deserializers); } if (context.features != null && context.features.deserialization != null) { finalContext.features.deserialization = { ...finalContext.features.deserialization, ...context.features.deserialization }; } if (context.forType != null) { finalContext.forType = new Map([ ...finalContext.forType, ...context.forType] ); } if (context.injectableValues != null) { finalContext.injectableValues = { ...finalContext.injectableValues, ...context.injectableValues }; } if (context.withCreatorName != null) { finalContext.withCreatorName = context.withCreatorName; } if (context._internalDecorators != null) { finalContext._internalDecorators = new Map([ ...finalContext._internalDecorators, ...context._internalDecorators] ); } if (context._propertyParentCreator != null) { finalContext._propertyParentCreator = context._propertyParentCreator; } } finalContext.deserializers = sortMappersByOrder(finalContext.deserializers); return finalContext; } /** * Method for deserializing a JSON string into a JavaScript object or value. * * @param text - the JSON string to be deserialized. * @param context - the context to be used during deserialization. */ parse(text: string, context?: JsonParserContext): T { const value = JSON.parse(text); return this.transform(value, context); } /** * Method for applying json decorators to a JavaScript object/value parsed. * It returns a JavaScript object/value with json decorators applied. * * @param value - the JavaScript object or value to be postprocessed. * @param context - the context to be used during deserialization postprocessing. */ transform(value: any, context?: JsonParserContext): any { const globalContext: JsonParserGlobalContext = { globalValueAlreadySeen: new Map<string, any>(), globalUnresolvedObjectIdentities: new Set<string>() }; context = JsonParser.mergeContexts([this.defaultContext, context]); let newContext: JsonParserTransformerContext = this.convertParserContextToTransformerContext(context); newContext.mainCreator = (newContext.mainCreator && newContext.mainCreator[0] !== Object) ? newContext.mainCreator : [(value != null) ? value.constructor : Object]; newContext._propertyParentCreator = newContext.mainCreator[0]; newContext._internalDecorators = new Map(); newContext = cloneDeep(newContext); const postProcessedObj = this.deepTransform('', value, newContext, globalContext); if (globalContext.globalUnresolvedObjectIdentities.size > 0 && newContext.features.deserialization.FAIL_ON_UNRESOLVED_OBJECT_IDS) { throw new JacksonError(`Found unresolved Object Ids: ${[...globalContext.globalUnresolvedObjectIdentities].join(', ')}`); } return postProcessedObj; } /** * Recursive {@link JsonParser.transform}. * * @param key - key name representing the object property being postprocessed. * @param value - the JavaScript object or value to postprocessed. * @param context - the context to be used during deserialization postprocessing. * @param globalContext - the global context to be used during deserialization postprocessing. */ private deepTransform(key: string, value: any, context: JsonParserTransformerContext, globalContext: JsonParserGlobalContext): any { context = { withContextGroups: [], features: { deserialization: {} }, deserializers: [], injectableValues: {}, decoratorsEnabled: {}, _internalDecorators: new Map(), ...context }; context = cloneDeep(context); if (value != null && context._internalDecorators != null && context._internalDecorators.size > 0) { let target = context.mainCreator[0]; while (target.name && !context._internalDecorators.has(target)) { target = Object.getPrototypeOf(target); } if (context._internalDecorators.has(target)) { if (context._internalDecorators.get(target).depth === 0) { context._internalDecorators.delete(target); } else { context._internalDecorators.get(target).depth--; } } } if (context.forType && context.forType.has(context.mainCreator[0])) { context = { mainCreator: context.mainCreator, ...context, ...context.forType.get(context.mainCreator[0]) }; context = cloneDeep(context); } const currentMainCreator = context.mainCreator[0]; value = this.invokeCustomDeserializers(key, value, context); value = this.parseJsonDeserializeClass(value, context); if (value != null && context.features.deserialization.ALLOW_COERCION_OF_SCALARS) { if (value.constructor === String) { if (isSameConstructorOrExtensionOfNoObject(currentMainCreator, Number)) { value = +value; } else if (BigInt && isSameConstructorOrExtensionOfNoObject(currentMainCreator, BigInt)) { value = BigInt(+value); } else if (isSameConstructorOrExtensionOfNoObject(currentMainCreator, Boolean)) { if (value.toLowerCase() === 'true' || value === '1') { value = true; } else if (value.toLowerCase() === 'false' || value === '0') { value = false; } else { value = !!value; } } } else if (value.constructor === Number) { if (isSameConstructorOrExtensionOfNoObject(currentMainCreator, Boolean)) { value = !!value; } else if (BigInt && isSameConstructorOrExtensionOfNoObject(currentMainCreator, BigInt)) { value = BigInt(+value); } else if (isSameConstructorOrExtensionOfNoObject(currentMainCreator, String)) { // @ts-ignore value += ''; } } else if (value.constructor === Boolean) { if (isSameConstructorOrExtensionOfNoObject(currentMainCreator, Number)) { value = value ? 1 : 0; } else if (BigInt && isSameConstructorOrExtensionOfNoObject(currentMainCreator, BigInt)) { value = BigInt(value ? 1 : 0); } else if (isSameConstructorOrExtensionOfNoObject(currentMainCreator, String)) { // @ts-ignore value += ''; } } } if (value == null && isConstructorPrimitiveType(context.mainCreator[0])) { value = this.getDefaultValue(context); } if (value == null && context.features.deserialization.FAIL_ON_NULL_FOR_PRIMITIVES && isConstructorPrimitiveType(currentMainCreator)) { // eslint-disable-next-line max-len throw new JacksonError(`Cannot map "${value}" into primitive type ${(currentMainCreator as ObjectConstructor).name}` + ( (context._propertyParentCreator != null && context._propertyParentCreator !== Object && key !== '') ? ` for ${context._propertyParentCreator.name}["${key}"]` : (key !== '' ? ' for property ' + key : '') )); } if ( (value instanceof Array && value.length === 0 && context.features.deserialization.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT) || (value != null && value.constructor === String && value.length === 0 && context.features.deserialization.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT) ) { value = null; } // if (value != null && value.constructor === Number && // context.features.deserialization.ACCEPT_FLOAT_AS_INT && isFloat(value)) { // value = parseInt(value + '', 10); // } if (value != null) { let instance = this.getInstanceAlreadySeen(key, value, context, globalContext); if (instance !== undefined) { return instance; } value = this.parseJsonTypeInfo(value, context); if (isSameConstructorOrExtensionOfNoObject(currentMainCreator, Map) || (typeof value === 'object' && !isIterableNoMapNoString(value) && currentMainCreator === Object)) { return this.parseMapAndObjLiteral(key, value, context, globalContext); } else if (BigInt && isSameConstructorOrExtensionOfNoObject(currentMainCreator, BigInt)) { return (value != null && value.constructor === String && value.endsWith('n')) ? // @ts-ignore currentMainCreator(value.substring(0, value.length - 1)) : // @ts-ignore currentMainCreator(value); } else if (isSameConstructorOrExtensionOfNoObject(currentMainCreator, RegExp)) { // @ts-ignore return new currentMainCreator(value); } else if (isSameConstructorOrExtensionOfNoObject(currentMainCreator, Date)) { // @ts-ignore return new currentMainCreator(value); } else if (typeof value === 'object' && !isIterableNoMapNoString(value)) { if (this.parseJsonIgnoreType(context)) { return null; } let replacement = clone(value); replacement = this.parseJsonRootName(replacement, context); this.parseJsonUnwrapped(replacement, context); this.parseJsonVirtualPropertyAndJsonAlias(replacement, context); this.parseJsonNaming(replacement, context); let keys = Object.keys(replacement); if (context.features.deserialization.ACCEPT_CASE_INSENSITIVE_PROPERTIES) { const classProperties = getClassProperties(currentMainCreator, null, context); const caseInsesitiveKeys = keys.map((k) => k.toLowerCase()); for (const classProperty of classProperties) { const index = caseInsesitiveKeys.indexOf(classProperty.toLowerCase()); if (index >= 0) { replacement[classProperty] = replacement[keys[index]]; delete replacement[keys[index]]; keys[index] = classProperty; } } } keys = mapVirtualPropertiesToClassProperties(currentMainCreator, keys, context, {checkSetters: true}); const classPropertiesToBeExcluded: string[] = []; for (const k of keys) { if (classHasOwnProperty(currentMainCreator, k, replacement, context, {withSettersAsProperty: true})) { const jsonClass: JsonClassTypeOptions = getMetadata('JsonClassType', context.mainCreator[0], k, context); this.propagateDecorators(jsonClass, replacement, k, context); if (this.parseHasJsonIgnore(context, k) || !this.parseIsIncludedByJsonViewProperty(context, k)) { classPropertiesToBeExcluded.push(k); delete replacement[k]; } else { this.parseJsonRawValue(context, replacement, k); this.parseJsonDeserializeProperty(k, replacement, context); } } } instance = this.parseJsonCreator(context, globalContext, replacement, classPropertiesToBeExcluded); if (instance) { replacement = instance; } return replacement; } else if (isIterableNoMapNoString(value)) { const replacement = this.parseIterable(value, key, context, globalContext); return replacement; } } return value; } /** * * @param context */ private convertParserContextToTransformerContext(context: JsonParserContext): JsonParserTransformerContext { const newContext: JsonParserTransformerContext = { mainCreator: context.mainCreator ? context.mainCreator() : [Object] }; for (const key in context) { if (key !== 'mainCreator') { newContext[key] = context[key]; } } return newContext; } /** * * @param context */ private getDefaultValue(context: JsonParserTransformerContext): any | null { let defaultValue = null; const currentMainCreator = context.mainCreator[0]; if (currentMainCreator === String && (context.features.deserialization.SET_DEFAULT_VALUE_FOR_PRIMITIVES_ON_NULL || context.features.deserialization.SET_DEFAULT_VALUE_FOR_STRING_ON_NULL) ) { defaultValue = getDefaultPrimitiveTypeValue(String); } else if (currentMainCreator === Number && (context.features.deserialization.SET_DEFAULT_VALUE_FOR_PRIMITIVES_ON_NULL || context.features.deserialization.SET_DEFAULT_VALUE_FOR_NUMBER_ON_NULL) ) { defaultValue = getDefaultPrimitiveTypeValue(Number); } else if (currentMainCreator === Boolean && (context.features.deserialization.SET_DEFAULT_VALUE_FOR_PRIMITIVES_ON_NULL || context.features.deserialization.SET_DEFAULT_VALUE_FOR_BOOLEAN_ON_NULL) ) { defaultValue = getDefaultPrimitiveTypeValue(Boolean); } else if (BigInt && currentMainCreator === BigInt && (context.features.deserialization.SET_DEFAULT_VALUE_FOR_PRIMITIVES_ON_NULL || context.features.deserialization.SET_DEFAULT_VALUE_FOR_BIGINT_ON_NULL) ) { defaultValue = getDefaultPrimitiveTypeValue(BigInt); } return defaultValue; } /** * Propagate decorators to class properties or parameters, * only for the first level (depth) of recursion. * * Used, for example, in case of decorators applied on an iterable, such as an Array. * In this case, the decorators are applied to each item of the iterable and not on the iterable itself. * * @param jsonClass * @param key * @param context * @param methodName * @param argumentIndex */ private propagateDecorators(jsonClass: JsonClassTypeOptions, obj: any, key: string, context: JsonParserTransformerContext, methodName?: string, argumentIndex?: number): void { const currentMainCreator = context.mainCreator[0]; // Decorators list that can be propagated const metadataKeysForDeepestClass = [ 'JsonIgnoreProperties', 'JsonIgnorePropertiesParam:' + argumentIndex, 'JsonTypeInfo', 'JsonTypeInfoParam:' + argumentIndex, 'JsonSubTypes', 'JsonSubTypesParam:' + argumentIndex, 'JsonTypeIdResolver', 'JsonTypeIdResolverParam:' + argumentIndex, 'JsonIdentityInfo', 'JsonIdentityInfoParam:' + argumentIndex ]; const metadataKeysForFirstClass = [ 'JsonDeserializeParam:' + argumentIndex ]; let deepestClass = null; const decoratorsNameFoundForDeepestClass: string[] = []; const decoratorsToBeAppliedForDeepestClass: InternalDecorators = { depth: 1 }; let firstClass = null; const decoratorsNameFoundForFirstClass: string[] = []; const decoratorsToBeAppliedForFirstClass: InternalDecorators = { depth: 1 }; if (jsonClass) { firstClass = jsonClass.type()[0]; deepestClass = getDeepestClass(jsonClass.type()); } else { firstClass = (obj[key] != null) ? obj[key].constructor : Object; deepestClass = (obj[key] != null) ? obj[key].constructor : Object; } for (const metadataKey of metadataKeysForDeepestClass) { const jsonDecoratorOptions: JsonDecoratorOptions = (!metadataKey.includes('Param:')) ? getMetadata(metadataKey, currentMainCreator, key, context) : getMetadata(metadataKey, currentMainCreator, methodName, context); if (jsonDecoratorOptions) { if (metadataKey.includes('Param:') && deepestClass != null && methodName != null && argumentIndex != null) { const jsonClassParam: JsonClassTypeOptions = getMetadata('JsonClassTypeParam:' + argumentIndex, currentMainCreator, methodName, context); const metadataKeysWithContext = makeMetadataKeysWithContext(metadataKey.substring(0, metadataKey.indexOf('Param:')), {contextGroups: jsonDecoratorOptions.contextGroups}); for (const metadataKeyWithContext of metadataKeysWithContext) { decoratorsToBeAppliedForDeepestClass[metadataKeyWithContext] = jsonDecoratorOptions; } if (jsonClassParam == null) { deepestClass = null; } else { const jsonClassMetadataKeysWithContext = makeMetadataKeysWithContext('JsonClassType', {contextGroups: jsonClassParam.contextGroups}); for (const metadataKeyWithContext of jsonClassMetadataKeysWithContext) { decoratorsToBeAppliedForDeepestClass[metadataKeyWithContext] = jsonClassParam; } } decoratorsNameFoundForDeepestClass.push(metadataKey.substring(0, metadataKey.indexOf('Param:'))); } else { const metadataKeysWithContext = makeMetadataKeysWithContext(metadataKey, {contextGroups: jsonDecoratorOptions.contextGroups}); for (const metadataKeyWithContext of metadataKeysWithContext) { decoratorsToBeAppliedForDeepestClass[metadataKeyWithContext] = jsonDecoratorOptions; } decoratorsNameFoundForDeepestClass.push(metadataKey); } } } for (const metadataKey of metadataKeysForFirstClass) { const jsonDecoratorOptions: JsonDecoratorOptions = (!metadataKey.includes('Param:')) ? getMetadata(metadataKey, currentMainCreator, key, context) : getMetadata(metadataKey, currentMainCreator, methodName, context); if (jsonDecoratorOptions) { if (metadataKey.includes('Param:') && firstClass != null && methodName != null && argumentIndex != null) { const jsonClassParam: JsonClassTypeOptions = getMetadata('JsonClassTypeParam:' + argumentIndex, currentMainCreator, methodName, context); const metadataKeysWithContext = makeMetadataKeysWithContext(metadataKey.substring(0, metadataKey.indexOf('Param:')), {contextGroups: jsonDecoratorOptions.contextGroups}); for (const metadataKeyWithContext of metadataKeysWithContext) { decoratorsToBeAppliedForFirstClass[metadataKeyWithContext] = jsonDecoratorOptions; } if (jsonClassParam == null) { firstClass = null; } else { const jsonClassMetadataKeysWithContext = makeMetadataKeysWithContext('JsonClassType', {contextGroups: jsonClassParam.contextGroups}); for (const metadataKeyWithContext of jsonClassMetadataKeysWithContext) { decoratorsToBeAppliedForFirstClass[metadataKeyWithContext] = jsonClassParam; } } decoratorsNameFoundForFirstClass.push(metadataKey.substring(0, metadataKey.indexOf('Param:'))); } else { const metadataKeysWithContext = makeMetadataKeysWithContext(metadataKey, {contextGroups: jsonDecoratorOptions.contextGroups}); for (const metadataKeyWithContext of metadataKeysWithContext) { decoratorsNameFoundForFirstClass[metadataKeyWithContext] = jsonDecoratorOptions; } decoratorsNameFoundForFirstClass.push(metadataKey); } } } if (deepestClass != null && decoratorsNameFoundForDeepestClass.length > 0) { context._internalDecorators.set(deepestClass, decoratorsToBeAppliedForDeepestClass); } if (firstClass != null && decoratorsNameFoundForFirstClass.length > 0) { context._internalDecorators.set(firstClass, decoratorsToBeAppliedForFirstClass); } } /** * * @param key * @param value * @param context */ private invokeCustomDeserializers(key: string, value: any, context: JsonParserTransformerContext): any { if (context.deserializers) { const currentMainCreator = context.mainCreator[0]; for (const deserializer of context.deserializers) { if (deserializer.type != null) { const classType = deserializer.type(); if ( (value != null && typeof classType === 'string' && classType !== typeof value) || (typeof classType !== 'string' && currentMainCreator != null && !isSameConstructorOrExtensionOf(classType, currentMainCreator)) ) { continue; } } const virtualProperty = mapClassPropertyToVirtualProperty(currentMainCreator, key, context); value = deserializer.mapper(virtualProperty, value, context); } } return value; } /** * * @param key * @param value * @param context * @param globalContext */ private getInstanceAlreadySeen(key: string, value: any, context: JsonParserTransformerContext, globalContext: JsonParserGlobalContext): undefined | null | any { const currentMainCreator = context.mainCreator[0]; const jsonIdentityInfo: JsonIdentityInfoOptions = getMetadata('JsonIdentityInfo', currentMainCreator, null, context); if (jsonIdentityInfo) { const id: string = typeof value === 'object' ? value[jsonIdentityInfo.property] : value; const scope: string = jsonIdentityInfo.scope || ''; const scopedId = this.generateScopedId(scope, id); if (globalContext.globalValueAlreadySeen.has(scopedId)) { const instance = globalContext.globalValueAlreadySeen.get(scopedId); if (instance.constructor !== currentMainCreator) { throw new JacksonError(`Already had Class "${instance.constructor.name}" for id ${id}.`); } globalContext.globalUnresolvedObjectIdentities.delete(scopedId); return instance; } else if (typeof value !== 'object') { globalContext.globalUnresolvedObjectIdentities.add(scopedId); if (!context.features.deserialization.FAIL_ON_UNRESOLVED_OBJECT_IDS) { return null; } } } return undefined; } /** * * @param context * @param globalContext * @param obj * @param classPropertiesToBeExcluded */ private parseJsonCreator(context: JsonParserTransformerContext, globalContext: JsonParserGlobalContext, obj: any, classPropertiesToBeExcluded: string[]): any { if (obj != null) { const currentMainCreator = context.mainCreator[0]; context._propertyParentCreator = currentMainCreator; const withCreatorName = context.withCreatorName; const jsonCreatorMetadataKey = 'JsonCreator:' + ((withCreatorName != null) ? withCreatorName : defaultCreatorName); const hasJsonCreator = hasMetadata(jsonCreatorMetadataKey, currentMainCreator, null, context); const jsonCreator: JsonCreatorOptions | ClassType<any> = (hasJsonCreator) ? getMetadata(jsonCreatorMetadataKey, currentMainCreator, null, context) : currentMainCreator; const jsonIgnoreProperties: JsonIgnorePropertiesOptions = getMetadata('JsonIgnoreProperties', currentMainCreator, null, context); const method: any = (hasJsonCreator) ? (((jsonCreator as JsonCreatorOptions)._ctor) ? (jsonCreator as JsonCreatorOptions)._ctor : (jsonCreator as JsonCreatorOptions)._method) : jsonCreator; let args; let argNames; let argNamesAliasToBeExcluded; let instance; if (('mode' in jsonCreator && jsonCreator.mode === JsonCreatorMode.PROPERTIES) || !('mode' in jsonCreator)) { const methodName = ('_propertyKey' in jsonCreator && jsonCreator._propertyKey) ? jsonCreator._propertyKey : 'constructor'; const result = this.parseMethodArguments(methodName, method, obj, context, globalContext, null, true); args = result.args != null && result.args.length > 0 ? result.args : [obj]; argNames = result.argNames; argNamesAliasToBeExcluded = result.argNamesAliasToBeExcluded; instance = ('_method' in jsonCreator && jsonCreator._method) ? (method as Function)(...args) : new (method as ObjectConstructor)(...args); } else if ('mode' in jsonCreator) { switch (jsonCreator.mode) { case JsonCreatorMode.DELEGATING: instance = ('_method' in jsonCreator && jsonCreator._method) ? (method as Function)(obj) : new (method as ObjectConstructor)(obj); break; } } this.parseJsonIdentityInfo(instance, obj, context, globalContext); const jsonAppendAttributesToBeExcluded = []; const jsonAppend: JsonAppendOptions = getMetadata('JsonAppend', currentMainCreator, null, context); if (jsonAppend && jsonAppend.attrs && jsonAppend.attrs.length > 0) { for (const attr of jsonAppend.attrs) { if (attr.value) { jsonAppendAttributesToBeExcluded.push(attr.value); } if (attr.propName) { jsonAppendAttributesToBeExcluded.push(attr.propName); } } } if (('mode' in jsonCreator && jsonCreator.mode === JsonCreatorMode.PROPERTIES) || !('mode' in jsonCreator)) { const keysToBeExcluded = [...new Set([ ...argNames, ...argNamesAliasToBeExcluded, ...jsonAppendAttributesToBeExcluded, ...classPropertiesToBeExcluded ])]; const classKeys = getClassProperties(currentMainCreator, obj, context, { withSettersAsProperty: true }); const remainingKeys = classKeys.filter(k => Object.hasOwnProperty.call(obj, k) && !keysToBeExcluded.includes(k)); const hasJsonAnySetter = hasMetadata('JsonAnySetter', currentMainCreator, null, context); // add remaining properties and ignore the ones that are not part of "instance" for (const key of remainingKeys) { const jsonVirtualProperty: JsonPropertyOptions | JsonSetterOptions = getMetadata('JsonVirtualProperty:' + key, currentMainCreator, null, context); if (jsonVirtualProperty && jsonVirtualProperty._descriptor != null) { if (typeof jsonVirtualProperty._descriptor.value === 'function' || jsonVirtualProperty._descriptor.set != null || jsonVirtualProperty._descriptor.get == null) { this.parseJsonSetter(instance, obj, key, context, globalContext); } else { // if property has a descriptor but is not a function and doesn't have a setter, // then this property has only getter, so we can skip it. continue; } } else if ((Object.hasOwnProperty.call(obj, key) && classHasOwnProperty(currentMainCreator, key, null, context)) || currentMainCreator.name === 'Object') { instance[key] = this.parseJsonClassType(context, globalContext, obj, key); } else if (hasJsonAnySetter && Object.hasOwnProperty.call(obj, key)) { // for any other unrecognized properties found this.parseJsonAnySetter(instance, obj, key, context); } else if (!classHasOwnProperty(currentMainCreator, key, null, context) && ( (jsonIgnoreProperties == null && context.features.deserialization.FAIL_ON_UNKNOWN_PROPERTIES) || (jsonIgnoreProperties != null && !jsonIgnoreProperties.ignoreUnknown)) ) { // eslint-disable-next-line max-len throw new JacksonError(`Unknown property "${key}" for ${currentMainCreator.name} at [Source '${JSON.stringify(obj)}']`); } } } const classProperties = getClassProperties(currentMainCreator, null, context); for (const classProperty of classProperties) { /* if (!Object.hasOwnProperty.call(instance, classProperty) && !Object.getOwnPropertyDescriptor(currentMainCreator.prototype, classProperty)) { instance[classProperty] = undefined; // set to undefined all the missing class properties (but not descriptors!) } */ this.parseJsonInject(instance, obj, classProperty, context, globalContext); // if there is a reference, convert the reference property to the corresponding Class this.parseJsonManagedReference(instance, context, obj, classProperty); } return instance; } } /** * * @param replacement * @param obj * @param key * @param context * @param globalContext */ private parseJsonInject(replacement: any, obj: any, key: string, context: JsonParserTransformerContext, globalContext: JsonParserGlobalContext) { const currentMainCreator = context.mainCreator[0]; let propertySetter; let jsonInject: JsonInjectOptions = getMetadata('JsonInject', currentMainCreator, key, context); if (!jsonInject) { propertySetter = mapVirtualPropertyToClassProperty(currentMainCreator, key, context, {checkSetters: true}); jsonInject = getMetadata('JsonInject', currentMainCreator, propertySetter, context); } if ( jsonInject && (!jsonInject.useInput || (jsonInject.useInput && replacement[key] == null && obj[key] == null)) ) { const injectableValue = context.injectableValues[jsonInject.value]; if (propertySetter != null && typeof replacement[propertySetter] === 'function') { replacement[propertySetter](injectableValue); } else { replacement[key] = injectableValue; } } } /** * * @param replacement * @param obj * @param key * @param context * @param globalContext */ private parseJsonSetter(replacement: any, obj: any, key: string, context: JsonParserTransformerContext, globalContext: JsonParserGlobalContext) { const currentMainCreator = context.mainCreator[0]; const jsonVirtualProperty: JsonPropertyOptions | JsonSetterOptions = getMetadata('JsonVirtualProperty:' + key, currentMainCreator, null, context); if (('access' in jsonVirtualProperty && jsonVirtualProperty.access !== JsonPropertyAccess.READ_ONLY) || !('access' in jsonVirtualProperty)) { if ('required' in jsonVirtualProperty && jsonVirtualProperty.required && !Object.hasOwnProperty.call(obj, jsonVirtualProperty._propertyKey)) { // eslint-disable-next-line max-len throw new JacksonError(`Required value "${jsonVirtualProperty.value}" not found for ${currentMainCreator.name}.${key} at [Source '${JSON.stringify(obj)}']`); } let parsedValue; if (typeof jsonVirtualProperty._descriptor.value === 'function') { parsedValue = this.parseMethodArguments(key, null, obj, context, globalContext, [jsonVirtualProperty.value], false) .args[0]; } else { parsedValue = this.parseJsonClassType(context, globalContext, obj, key); } if ('nulls' in jsonVirtualProperty || 'contentNulls' in jsonVirtualProperty) { if (jsonVirtualProperty.nulls !== JsonSetterNulls.SET && parsedValue == null) { switch (jsonVirtualProperty.nulls) { case JsonSetterNulls.FAIL: // eslint-disable-next-line max-len throw new JacksonError(`"${parsedValue}" value found on ${jsonVirtualProperty.value} for ${currentMainCreator.name}.${key} at [Source '${JSON.stringify(obj)}']`); case JsonSetterNulls.SKIP: return; } } if (jsonVirtualProperty.contentNulls !== JsonSetterNulls.SET) { if (isIterableNoMapNoString(parsedValue)) { parsedValue = [...parsedValue]; const indexesToBeRemoved = []; for (let i = 0; i < parsedValue.length; i++) { const value = parsedValue[i]; if (value == null) { switch (jsonVirtualProperty.contentNulls) { case JsonSetterNulls.FAIL: // eslint-disable-next-line max-len throw new JacksonError(`"${value}" value found on ${jsonVirtualProperty.value} at index ${i} for ${currentMainCreator.name}.${key} at [Source '${JSON.stringify(obj)}']`); case JsonSetterNulls.SKIP: indexesToBeRemoved.push(i); break; } } } while (indexesToBeRemoved.length) { parsedValue.splice(indexesToBeRemoved.pop(), 1); } } else if (parsedValue instanceof Map || (parsedValue != null && parsedValue.constructor === Object)) { const entries = (parsedValue instanceof Map) ? [...parsedValue.entries()] : Object.entries(parsedValue); for (const [mapKey, mapValue] of entries) { if (mapValue == null) { switch (jsonVirtualProperty.contentNulls) { case JsonSetterNulls.FAIL: // eslint-disable-next-line max-len throw new JacksonError(`"${mapValue}" value found on ${jsonVirtualProperty.value} at key "${mapKey}" for ${currentMainCreator.name}.${key} at [Source '${JSON.stringify(obj)}']`); case JsonSetterNulls.SKIP: if (parsedValue instanceof Map) { parsedValue.delete(mapKey); } else { delete parsedValue[mapKey]; } break; } } } } } } if (typeof jsonVirtualProperty._descriptor.value === 'function') { replacement[key](parsedValue); } else { replacement[key] = parsedValue; } } } /** * * @param methodName * @param method * @param obj * @param context * @param globalContext * @param argNames * @param isJsonCreator */ private parseMethodArguments(methodName: string, method: any, obj: any, context: JsonParserTransformerContext, globalContext: JsonParserGlobalContext, argNames: string[], isJsonCreator: boolean): { args: Array<any>; argNames: Array<string>; argNamesAliasToBeExcluded: Array<string>; } { const currentMainCreator = context.mainCreator[0]; const args = []; argNames = (method) ? getArgumentNames(method) : argNames; if (context.features.deserialization.ACCEPT_CASE_INSENSITIVE_PROPERTIES) { const objKeys = Object.keys(obj); const caseInsesitiveObjKeys = objKeys.map((k) => k.toLowerCase()); for (const argName of argNames) { const index = caseInsesitiveObjKeys.indexOf(argName.toLowerCase()); if (index >= 0) { obj[argName] = obj[objKeys[index]]; delete obj[objKeys[index]]; objKeys[index] = argName; } } } argNames = mapVirtualPropertiesToClassProperties(currentMainCreator, argNames, context, {checkSetters: true}); const argNamesAliasToBeExcluded = []; for (let argIndex = 0; argIndex < argNames.length; argIndex++) { const key = argNames[argIndex]; const hasJsonIgnore = hasMetadata('JsonIgnoreParam:' + argIndex, currentMainCreator, methodName, context); const isIncludedByJsonView = this.parseIsIncludedByJsonViewParam(context, methodName, argIndex); if (hasJsonIgnore || !isIncludedByJsonView) { args.push(null); continue; } const jsonInject: JsonInjectOptions = getMetadata('JsonInjectParam:' + argIndex, currentMainCreator, methodName, context); if (!jsonInject || (jsonInject && jsonInject.useInput)) { const jsonProperty: JsonPropertyOptions = getMetadata('JsonPropertyParam:' + argIndex, currentMainCreator, methodName, context); let mappedKey: string = jsonProperty != null ? jsonProperty.value : null; if (!mappedKey) { const jsonAlias: JsonAliasOptions = getMetadata('JsonAliasParam:' + argIndex, currentMainCreator, methodName, context); if (jsonAlias && jsonAlias.values) { mappedKey = jsonAlias.values.find((alias) => Object.hasOwnProperty.call(obj, alias)); } } if (mappedKey && Object.hasOwnProperty.call(obj, mappedKey)) { args.push(this.parseJsonClassType(context, globalContext, obj, mappedKey, methodName, argIndex)); argNamesAliasToBeExcluded.push(mappedKey); } else if (mappedKey && jsonProperty.required) { // eslint-disable-next-line max-len throw new JacksonError(`Required property "${mappedKey}" not found on parameter at index ${argIndex} of ${currentMainCreator.name}.${methodName} at [Source '${JSON.stringify(obj)}']`); } else if (Object.hasOwnProperty.call(obj, key)) { args.push(this.parseJsonClassType(context, globalContext, obj, key, methodName, argIndex)); } else { if (isJsonCreator && context.features.deserialization.FAIL_ON_MISSING_CREATOR_PROPERTIES && (!jsonInject || (jsonInject && !(jsonInject.value in context.injectableValues)))) { // eslint-disable-next-line max-len throw new JacksonError(`Missing @JsonCreator() parameter at index ${argIndex} of ${currentMainCreator.name}.${methodName} at [Source '${JSON.stringify(obj)}']`); } args.push(jsonInject ? context.injectableValues[jsonInject.value] : null); } } else { // force argument value to use options.injectableValues args.push(jsonInject ? context.injectableValues[jsonInject.value] : null); } } if (isJsonCreator && context.features.deserialization.FAIL_ON_NULL_CREATOR_PROPERTIES) { const argsLength = args.length; for (let i = 0; i < argsLength; i++) { const arg = args[i]; if (arg == null) { // eslint-disable-next-line max-len throw new JacksonError(`Found "${arg}" value on @JsonCreator() parameter at index ${i} of ${currentMainCreator.name}.${methodName} at [Source '${JSON.stringify(obj)}']`); } } } return { args, argNames, argNamesAliasToBeExcluded }; } /** * * @param replacement * @param context */ private parseJsonVirtualPropertyAndJsonAlias(replacement: any, context: JsonParserTransformerContext): void { const currentMainCreator = context.mainCreator[0]; // convert JsonProperty to Class properties const creatorMetadataKeys = getMetadataKeys(currentMainCreator, context); for (const metadataKey of creatorMetadataKeys) { if (metadataKey.includes(':JsonVirtualProperty:') || metadataKey.includes(':JsonAlias:')) { const realKey = metadataKey.split( metadataKey.includes(':JsonVirtualProperty:') ? ':JsonVirtualProperty:' : ':JsonAlias:')[1]; const jsonVirtualProperty: JsonPropertyOptions | JsonSetterOptions = getMetadata(metadataKey, currentMainCreator, null, context); if (jsonVirtualProperty && jsonVirtualProperty._descriptor != null && typeof jsonVirtualProperty._descriptor.value === 'function' && jsonVirtualProperty._propertyKey.startsWith('get')) { continue; } const jsonAlias: JsonAliasOptions = getMetadata(metadataKey, currentMainCreator, null, context); const isIgnored = jsonVirtualProperty && 'access' in jsonVirtualProperty && jsonVirtualProperty.access === JsonPropertyAccess.READ_ONLY; if (jsonVirtualProperty && !isIgnored) { if (Object.hasOwnProperty.call(replacement, jsonVirtualProperty.value)) { replacement[realKey] = replacement[jsonVirtualProperty.value]; if (realKey !== jsonVirtualProperty.value) { delete replacement[jsonVirtualProperty.value]; } } else if ('required' in jsonVirtualProperty && jsonVirtualProperty.required) { // eslint-disable-next-line max-len throw new JacksonError(`Required property "${jsonVirtualProperty.value}" not found at [Source '${JSON.stringify(replacement)}']`); } } if (jsonAlias && jsonAlias.values && !isIgnored) { for (const alias of jsonAlias.values) { if (Object.hasOwnProperty.call(replacement, alias)) { replacement[realKey] = replacement[alias]; if (realKey !== alias) { delete replacement[alias]; } break; } } } if (isIgnored) { delete replacement[realKey]; } } } } /** * * @param context * @param replacement * @param key */ private parseJsonRawValue(context: JsonParserTransformerContext, replacement: any, key: string): void { const jsonRawValue = hasMetadata('JsonRawValue', context.mainCreator[0], key, context); if (jsonRawValue) { replacement[key] = JSON.stringify(replacement[key]); } } /** * * @param replacement * @param context */ private parseJsonRootName(replacement: any, context: JsonParserTransformerContext): any { if (context.features.deserialization.UNWRAP_ROOT_VALUE) { const jsonRootName: JsonRootNameOptions = getMetadata('JsonRootName', context.mainCreator[0], null, context); const wrapKey = (jsonRootName && jsonRootName.value) ? jsonRootName.value : context.mainCreator[0].constructor.name; if (!(wrapKey in replacement) || Object.keys(replacement).length !== 1) { // eslint-disable-next-line max-len throw new JacksonError(`No JSON Object with single property as root name "${wrapKey}" found to unwrap value at [Source "${JSON.stringify(replacement)}"]`); } return clone(replacement[wrapKey]); } return replacement; } /** * * @param context * @param globalContext * @param obj * @param key * @param methodName * @param argumentIndex */ private parseJsonClassType(context: JsonParserTransformerContext, globalContext: JsonParserGlobalContext, obj: any, key: string, methodName?: string, argumentIndex?: number): any { let jsonClass: JsonClassTypeOptions; if (methodName != null && argumentIndex != null) { jsonClass = getMetadata('JsonClassTypeParam:' + argumentIndex, context.mainCreator[0], methodName, context); } if (!jsonClass) { // if @JsonClass() is not found at parameter level, try to get it from the class properties jsonClass = getMetadata('JsonClassType', context.mainCreator[0], key, context); } this.propagateDecorators(jsonClass, obj, key, context, methodName, argumentIndex); const newContext = cloneDeep(context); if (jsonClass && jsonClass.type) { newContext.mainCreator = jsonClass.type(); this._addInternalDecoratorsFromJsonClass(newContext.mainCreator, newContext); } else { const newCreator = (obj[key] != null) ? obj[key].constructor : Object; newContext.mainCreator = [newCreator]; } return this.deepTransform(key, obj[key], newContext, globalContext); } /** * * @param mainCreator * @param context */ private _addInternalDecoratorsFromJsonClass(mainCreator: any[], context: JsonParserTransformerContext) { for (let i = 0; i < mainCreator.length; i++) { const ctor = mainCreator[i]; if (!(ctor instanceof Array)) { if (!ctor.name && typeof ctor === 'function') { const decoratorsToBeApplied = { depth: 1 }; const result = (ctor as ClassTypeWithDecoratorDefinitions)(); mainCreator[i] = result.target; const decorators = result.decorators; for (const decorator of decorators) { const metadataKeysWithContext = makeMetadataKeysWithContext(decorator.name, {contextGroups: decorator.options.contextGroups}); for (const metadataKeyWithContext of metadataKeysWithContext) { decoratorsToBeApplied[metadataKeyWithContext] = { enabled: true, ...decorator.options } as JsonDecoratorOptions; } } context._internalDecorators.set(result.target, decoratorsToBeApplied); } } else { this._addInternalDecoratorsFromJsonClass(ctor, context); } } } /** * * @param replacement * @param context * @param obj * @param key */ private parseJsonManagedReference(replacement: any, context: JsonParserTransformerContext, obj: any, key: string): void { const currentMainCreator = context.mainCreator[0]; let jsonManagedReference: JsonManagedReferenceOptions = getMetadata('JsonManagedReference', currentMainCreator, key, context); let jsonClassManagedReference: JsonClassTypeOptions = getMetadata('JsonClassType', currentMainCreator, key, context); if (!jsonManagedReference) { const propertySetter = mapVirtualPropertyToClassProperty(currentMainCreator, key, context, {checkSetters: true}); jsonManagedReference = getMetadata('JsonManagedReference', currentMainCreator, propertySetter, context); jsonClassManagedReference = getMetadata('JsonClassTypeParam:0', currentMainCreator, propertySetter, context); if (jsonManagedReference && !jsonClassManagedReference) { // eslint-disable-next-line max-len throw new JacksonError(`Missing mandatory @JsonClass() decorator for the parameter at index 0 of @JsonManagedReference() decorated ${replacement.constructor.name}.${propertySetter}() method at [Source '${JSON.stringify(obj)}']`); } } if (jsonManagedReference && jsonClassManagedReference) { const jsonClassConstructors = jsonClassManagedReference.type(); const childConstructor = jsonClassConstructors[0]; if (isClassIterable(childConstructor)) { const backReferenceConstructor = (jsonClassConstructors.length === 1) ? Object : ( (!isSameConstructorOrExtensionOfNoObject(childConstructor, Map)) ? jsonClassManagedReference.type()[1][0] : jsonClassManagedReference.type()[1][1] ); const jsonBackReference: JsonBackReferenceOptions = getMetadata('JsonBackReference:' + jsonManagedReference.value, backReferenceConstructor, null, context); if (jsonBackReference) { if (isSameConstructorOrExtensionOfNoObject(childConstructor, Map)) { for (const [k, value] of replacement[key]) { if (typeof value[jsonBackReference._propertyKey] === 'function') { value[jsonBackReference._propertyKey](replacement); } else { value[jsonBackReference._propertyKey] = replacement; } } } else { for (const value of replacement[key]) { if (typeof value[jsonBackReference._propertyKey] === 'function') { value[jsonBackReference._propertyKey](replacement); } else { value[jsonBackReference._propertyKey] = replacement; } } } } } else { const jsonBackReference: JsonBackReferenceOptions = getMetadata('JsonBackReference:' + jsonManagedReference.value, childConstructor, null, context); if (jsonBackReference) { if (typeof replacement[key][jsonBackReference._propertyKey] === 'function') { replacement[key][jsonBackReference._propertyKey](replacement); } else { replacement[key][jsonBackReference._propertyKey] = replacement; } } } } else if (jsonManagedReference && !jsonClassManagedReference) { // eslint-disable-next-line max-len throw new JacksonError(`Missing mandatory @JsonClass() decorator for the @JsonManagedReference() decorated ${replacement.constructor.name}["${key}"] field at [Source '${JSON.stringify(obj)}']`); } } /** * * @param replacement * @param obj * @param key * @param context */ private parseJsonAnySetter(replacement: any, obj: any, key: string, context: JsonParserTransformerContext): void { const jsonAnySetter: JsonAnySetterOptions = getMetadata('JsonAnySetter', replacement.constructor, null, context); if (jsonAnySetter && replacement[jsonAnySetter._propertyKey]) { if (typeof replacement[jsonAnySetter._propertyKey] === 'function') { replacement[jsonAnySetter._propertyKey](key, obj[key]); } else { replacement[jsonAnySetter._propertyKey][key] = obj[key]; } } } /** * * @param context * @param replacement */ private parseJsonDeserializeClass(replacement: any, context: JsonParserTransformerContext): any { const jsonDeserialize: JsonDeserializeOptions = getMetadata('JsonDeserialize', context.mainCreator[0], null, context); if (jsonDeserialize && jsonDeserialize.using) { return jsonDeserialize.using(replacement, context); } return replacement; } /** * * @param context * @param replacement * @param key */ private parseJsonDeserializeProperty(key: string, replacement: any, context: JsonParserTransformerContext): void { const currentMainCreator = context.mainCreator[0]; const jsonDeserialize: JsonDeserializeOptions = getMetadata('JsonDeserialize', currentMainCreator, key, context); if (jsonDeserialize && jsonDeserialize.using) { replacement[key] = jsonDeserialize.using(replacement[key], context); } } /** * * @param context * @param key */ private parseHasJsonIgnore(context: JsonParserTransformerContext, key: string): boolean { const currentMainCreator = context.mainCreator[0]; const hasJsonIgnore = hasMetadata('JsonIgnore', currentMainCreator, key, context); if (!hasJsonIgnore) { const jsonIgnoreProperties: JsonIgnorePropertiesOptions = getMetadata('JsonIgnoreProperties', currentMainCreator, null, context); if (jsonIgnoreProperties) { const jsonVirtualProperty: JsonPropertyOptions | JsonGetterOptions = getMetadata('JsonVirtualProperty:' + key, currentMainCreator, null, context); if (jsonVirtualProperty && jsonIgnoreProperties.value.includes(jsonVirtualProperty.value)) { if (jsonVirtualProperty._descriptor != null && typeof jsonVirtualProperty._descriptor.value === 'function' && jsonIgnoreProperties.allowSetters) { return false; } return true; } return jsonIgnoreProperties.value.includes(key); } } return hasJsonIgnore; } /** * * @param context */ private parseJsonIgnoreType(context: JsonParserTransformerContext): boolean { return hasMetadata('JsonIgnoreType', context.mainCreator[0], null, context); } /** * * @param obj * @param context */ private parseJsonTypeInfo(obj: any, context: JsonParserTransformerContext): any { const currentMainCreator = context.mainCreator[0]; const jsonTypeInfo: JsonTypeInfoOptions = getMetadata('JsonTypeInfo', currentMainCreator, null, context); if (jsonTypeInfo) { let jsonTypeCtor: ClassType<any>; let jsonTypeInfoProperty: string; let newObj = clone(obj); switch (jsonTypeInfo.include) { case JsonTypeInfoAs.PROPERTY: jsonTypeInfoProperty = newObj[jsonTypeInfo.property]; if (jsonTypeInfoProperty == null && context.features.deserialization.FAIL_ON_MISSING_TYPE_ID && context.features.deserialization.FAIL_ON_INVALID_SUBTYPE) { // eslint-disable-next-line max-len throw new JacksonError(`Missing type id when trying to resolve type or subtype of class ${currentMainCreator.name}: missing type id property '${jsonTypeInfo.property}' at [Source '${JSON.stringify(newObj)}']`); } else { delete newObj[jsonTypeInfo.property]; } break; case JsonTypeInfoAs.WRAPPER_OBJECT: if (!(newObj instanceof Object) || newObj instanceof Array) { // eslint-disable-next-line max-len throw new JacksonError(`Expected "Object", got "${newObj.constructor.name}": need JSON Object to contain JsonTypeInfoAs.WRAPPER_OBJECT type information for class "${currentMainCreator.name}" at [Source '${JSON.stringify(newObj)}']`); } jsonTypeInfoProperty = Object.keys(newObj)[0]; newObj = newObj[jsonTypeInfoProperty]; break; case JsonTypeInfoAs.WRAPPER_ARRAY: if (!(newObj instanceof Array)) { // eslint-disable-next-line max-len throw new JacksonError(`Expected "Array", got "${newObj.constructor.name}": need JSON Array to contain JsonTypeInfoAs.WRAPPER_ARRAY type information for class "${currentMainCreator.name}" at [Source '${JSON.stringify(newObj)}']`); } else if (newObj.length > 2 || newObj.length === 0) { // eslint-disable-next-line max-len throw new JacksonError(`Expected "Array" of length 1 or 2, got "Array" of length ${newObj.length}: need JSON Array of length 1 or 2 to contain JsonTypeInfoAs.WRAPPER_ARRAY type information for class "${currentMainCreator.name}" at [Source '${JSON.stringify(newObj)}']`); } else if (newObj[0] == null || newObj[0].constructor !== String) { // eslint-disable-next-line max-len throw new JacksonError(`Expected "String", got "${newObj[0] ? newObj[0].constructor.name : newObj[0]}": need JSON String that contains type id (for subtype of "${currentMainCreator.name}") at [Source '${JSON.stringify(newObj)}']`); } jsonTypeInfoProperty = newObj[0] as string; newObj = newObj[1]; break; } const jsonTypeIdResolver: JsonTypeIdResolverOptions = getMetadata('JsonTypeIdResolver', currentMainCreator, null, context); if (jsonTypeIdResolver && jsonTypeIdResolver.resolver) { jsonTypeCtor = jsonTypeIdResolver.resolver.typeFromId(jsonTypeInfoProperty, context); } const jsonSubTypes: JsonSubTypesOptions = getMetadata('JsonSubTypes', currentMainCreator, null, context); if (!jsonTypeCtor && jsonTypeInfoProperty != null) { if (jsonSubTypes && jsonSubTypes.types && jsonSubTypes.types.length > 0) { for (const subType of jsonSubTypes.types) { const subTypeClass = subType.class() as ObjectConstructor; if ( (subType.name != null && jsonTypeInfoProperty === subType.name) || jsonTypeInfoProperty === subTypeClass.name) { jsonTypeCtor = subTypeClass; } } if (!jsonTypeCtor && context.features.deserialization.FAIL_ON_INVALID_SUBTYPE) { const ids = [(currentMainCreator).name]; ids.push(...jsonSubTypes.types.map((subType) => (subType.name) ? subType.name : subType.class().name)); // eslint-disable-next-line max-len throw new JacksonError(`Could not resolve type id "${jsonTypeInfoProperty}" as a subtype of "${currentMainCreator.name}": known type ids = [${ids.join(', ')}] at [Source '${JSON.stringify(newObj)}']`); } } } if (!jsonTypeCtor) { switch (jsonTypeInfo.use) { case JsonTypeInfoId.NAME: if (jsonTypeInfoProperty != null && jsonTypeInfoProperty === currentMainCreator.name) { jsonTypeCtor = currentMainCreator; } break; } } if (!jsonTypeCtor && context.features.deserialization.FAIL_ON_INVALID_SUBTYPE && jsonTypeInfoProperty != null) { const ids = [(currentMainCreator).name]; if (jsonSubTypes && jsonSubTypes.types && jsonSubTypes.types.length > 0) { ids.push(...jsonSubTypes.types.map((subType) => (subType.name) ? subType.name : subType.class().name)); } // eslint-disable-next-line max-len throw new JacksonError(`Could not resolve type id "${jsonTypeInfoProperty}" as a subtype of "${currentMainCreator.name}": known type ids = [${ids.join(', ')}] at [Source '${JSON.stringify(newObj)}']`); } else if (!jsonTypeCtor) { jsonTypeCtor = currentMainCreator; } context.mainCreator = [jsonTypeCtor]; return newObj; } return obj; } /** * * @param context * @param key */ private parseIsIncludedByJsonViewProperty(context: JsonParserTransformerContext, key: string): boolean { const currentMainCreator = context.mainCreator[0]; if (context.withViews) { let jsonView: JsonViewOptions = getMetadata('JsonView', currentMainCreator, key, context); if (!jsonView) { jsonView = getMetadata('JsonView', currentMainCreator, null, context); } if (jsonView && jsonView.value) { return this.parseIsIncludedByJsonView(jsonView, context); } return context.features.deserialization.DEFAULT_VIEW_INCLUSION; } return true; } /** * * @param context * @param methodName * @param argumentIndex */ private parseIsIncludedByJsonViewParam(context: JsonParserTransformerContext, methodName: string, argumentIndex: number): boolean { const currentMainCreator = context.mainCreator[0]; if (context.withViews) { const jsonView: JsonViewOptions = getMetadata('JsonViewParam:' + argumentIndex, currentMainCreator, methodName, context); if (jsonView && jsonView.value) { return this.parseIsIncludedByJsonView(jsonView, context); } return context.features.deserialization.DEFAULT_VIEW_INCLUSION; } return true; } /** * * @param jsonView * @param context */ private parseIsIncludedByJsonView(jsonView: JsonViewOptions, context: JsonParserTransformerContext): boolean { const views = jsonView.value(); const withViews = context.withViews(); for (const view of views) { for (const withView of withViews) { if (isSameConstructorOrExtensionOf(view, withView)) { return true; } } } return false; } /** * * @param replacement * @param context */ private parseJsonUnwrapped(replacement: any, context: JsonParserTransformerContext): void { const currentMainCreator = context.mainCreator[0]; const metadataKeys: string[] = getMetadataKeys(currentMainCreator, context); for (const metadataKey of metadataKeys) { if (metadataKey.includes(':JsonUnwrapped:')) { const realKey = metadataKey.split(':JsonUnwrapped:')[1]; const jsonUnwrapped: JsonUnwrappedOptions = getMetadata(metadataKey, currentMainCreator, null, context); if (jsonUnwrapped._descriptor != null && typeof jsonUnwrapped._descriptor.value === 'function' && !realKey.startsWith('set')) { continue; } const jsonClass: JsonClassTypeOptions = getMetadata('JsonClassType', currentMainCreator, realKey, context); if (!jsonClass) { // eslint-disable-next-line max-len throw new JacksonError(`@JsonUnwrapped() requires use of @JsonClass() for deserialization at ${currentMainCreator.name}["${realKey}"])`); } const prefix = (jsonUnwrapped.prefix != null) ? jsonUnwrapped.prefix : ''; const suffix = (jsonUnwrapped.suffix != null) ? jsonUnwrapped.suffix : ''; replacement[realKey] = {}; const properties = getClassProperties(jsonClass.type()[0], null, context, { withJsonVirtualPropertyValues: true, withJsonAliases: true }); for (const k of properties) { const wrappedKey = prefix + k + suffix; if (Object.hasOwnProperty.call(replacement, wrappedKey)) { replacement[realKey][k] = replacement[wrappedKey]; delete replacement[wrappedKey]; } } } } } /** * * @param replacement * @param obj * @param context * @param globalContext */ private parseJsonIdentityInfo(replacement: any, obj: any, context: JsonParserTransformerContext, globalContext: JsonParserGlobalContext): void { const jsonIdentityInfo: JsonIdentityInfoOptions = getMetadata('JsonIdentityInfo', context.mainCreator[0], null, context); if (jsonIdentityInfo) { const id: string = obj[jsonIdentityInfo.property]; const scope: string = jsonIdentityInfo.scope || ''; const scopedId = this.generateScopedId(scope, id); if (!globalContext.globalValueAlreadySeen.has(scopedId)) { globalContext.globalValueAlreadySeen.set(scopedId, replacement); } delete obj[jsonIdentityInfo.property]; } } /** * * @param iterable * @param key * @param context * @param globalContext */ private parseIterable(iterable: any, key: string, context: JsonParserTransformerContext, globalContext: JsonParserGlobalContext): any { const jsonDeserialize: JsonDeserializeOptions = getMetadata('JsonDeserialize', context._propertyParentCreator, key, context); const currentCreators = context.mainCreator; const currentCreator = currentCreators[0]; let newIterable: any; const newContext = cloneDeep(context); if (currentCreators.length > 1 && currentCreators[1] instanceof Array) { newContext.mainCreator = currentCreators[1] as [ClassType<any>]; } else { newContext.mainCreator = [Object]; } if (isSameConstructorOrExtensionOfNoObject(currentCreator, Set)) { if (isSameConstructor(currentCreator, Set)) { newIterable = new Set(); } else { newIterable = new (currentCreator as ObjectConstructor)() as Set<any>; } for (let value of iterable) { if (newContext.mainCreator == null) { newContext.mainCreator = [(value != null) ? value.constructor : Object]; } if (jsonDeserialize && jsonDeserialize.contentUsing) { value = jsonDeserialize.contentUsing(value, newContext); } if (this.parseJsonIgnoreType(newContext)) { continue; } (newIterable as Set<any>).add(this.deepTransform(key, value, newContext, globalContext)); } } else { newIterable = []; for (let value of iterable) { if (newContext.mainCreator == null) { newContext.mainCreator = [(value != null) ? value.constructor : Object]; } if (jsonDeserialize && jsonDeserialize.contentUsing) { value = jsonDeserialize.contentUsing(value, newContext); } if (this.parseJsonIgnoreType(newContext)) { continue; } (newIterable as Array<any>).push(this.deepTransform(key, value, newContext, globalContext)); } if (!isSameConstructor(currentCreator, Array)) { // @ts-ignore newIterable = new currentCreator(...newIterable); } } return newIterable; } /** * * @param key * @param obj * @param context * @param globalContext */ private parseMapAndObjLiteral(key: string, obj: any, context: JsonParserTransformerContext, globalContext: JsonParserGlobalContext): Map<any, any> | Record<any, any> { const currentCreators = context.mainCreator; const currentCreator = currentCreators[0]; const jsonDeserialize: JsonDeserializeOptions = getMetadata('JsonDeserialize', context._propertyParentCreator, key, context); let map: Map<any, any> | Record<any, any>; const newContext = cloneDeep(context); if (currentCreators.length > 1 && currentCreators[1] instanceof Array) { newContext.mainCreator = currentCreators[1] as [ClassType<any>]; } else { newContext.mainCreator = [Object]; } if (isSameConstructorOrExtensionOfNoObject(currentCreator, Map)) { map = new (currentCreator as ObjectConstructor)() as Map<any, any>; } else { map = {}; } const mapCurrentCreators = newContext.mainCreator; const mapKeys = Object.keys(obj); for (let mapKey of mapKeys) { let mapValue = obj[mapKey]; const keyNewContext = cloneDeep(newContext); const valueNewContext = cloneDeep(newContext); if (mapCurrentCreators[0] instanceof Array) { keyNewContext.mainCreator = mapCurrentCreators[0] as [ClassType<any>]; } else { keyNewContext.mainCreator = [mapCurrentCreators[0]] as [ClassType<any>]; } if (keyNewContext.mainCreator[0] === Object) { keyNewContext.mainCreator[0] = mapKey.constructor; } if (mapCurrentCreators.length > 1) { if (mapCurrentCreators[1] instanceof Array) { valueNewContext.mainCreator = mapCurrentCreators[1] as [ClassType<any>]; } else { valueNewContext.mainCreator = [mapCurrentCreators[1]] as [ClassType<any>]; } } else { valueNewContext.mainCreator = [Object]; } if (mapValue != null && mapValue.constructor !== Object && valueNewContext.mainCreator[0] === Object) { valueNewContext.mainCreator[0] = mapValue.constructor; } if (jsonDeserialize && (jsonDeserialize.contentUsing || jsonDeserialize.keyUsing)) { mapKey = (jsonDeserialize.keyUsing) ? jsonDeserialize.keyUsing(mapKey, keyNewContext) : mapKey; mapValue = (jsonDeserialize.contentUsing) ? jsonDeserialize.contentUsing(mapValue, valueNewContext) : mapValue; if (mapKey != null && mapKey.constructor !== Object) { keyNewContext.mainCreator[0] = mapKey.constructor; } if (mapValue != null && mapValue.constructor !== Object) { valueNewContext.mainCreator[0] = mapValue.constructor; } } const mapKeyParsed = this.deepTransform('', mapKey, keyNewContext, globalContext); const mapValueParsed = this.deepTransform(mapKey, mapValue, valueNewContext, globalContext); if (map instanceof Map) { map.set(mapKeyParsed, mapValueParsed); } else { map[mapKeyParsed] = mapValueParsed; } } return map; } /** * * @param obj * @param context */ private parseJsonNaming(obj: any, context: JsonParserTransformerContext): void { const jsonNamingOptions: JsonNamingOptions = getMetadata('JsonNaming', context.mainCreator[0], null, context); if (jsonNamingOptions && jsonNamingOptions.strategy != null) { const keys = Object.keys(obj); const classProperties = new Set<string>(getClassProperties(context.mainCreator[0], null, context, { withSetterVirtualProperties: true })); const keysLength = keys.length; for (let i = 0; i < keysLength; i++) { const key = keys[i]; let oldKey = key; switch (jsonNamingOptions.strategy) { case PropertyNamingStrategy.KEBAB_CASE: oldKey = key.replace(/-/g, ''); break; case PropertyNamingStrategy.LOWER_DOT_CASE: oldKey = key.replace(/\./g, ''); break; case PropertyNamingStrategy.LOWER_CAMEL_CASE: case PropertyNamingStrategy.LOWER_CASE: case PropertyNamingStrategy.UPPER_CAMEL_CASE: break; } let propertyFound = false; classProperties.forEach((propertyKey) => { if (propertyKey.toLowerCase() === oldKey.toLowerCase()) { oldKey = propertyKey; propertyFound = true; return; } }); if (!propertyFound && jsonNamingOptions.strategy === PropertyNamingStrategy.SNAKE_CASE) { classProperties.forEach((propertyKey) => { const tokens = propertyKey.split(/(?=[A-Z])/); const tokensLength = tokens.length; let reconstructedKey = ''; for (let j = 0; j < tokensLength; j++) { const token = tokens[j].toLowerCase(); const separator = (j > 0 && tokens[j - 1].endsWith('_')) ? '' : '_'; reconstructedKey += (reconstructedKey !== '' && token.length > 1) ? separator + token : token; } if (key === reconstructedKey) { oldKey = propertyKey; return; } }); } classProperties.delete(oldKey); if (oldKey != null && oldKey !== key) { oldKey = mapVirtualPropertyToClassProperty(context.mainCreator[0], oldKey, context, {checkSetters: true}); obj[oldKey] = obj[key]; delete obj[key]; } } } } /** * * @param scope * @param id */ private generateScopedId(scope: string, id: string): string { return scope + ': ' + id; } }
the_stack
import { randomAsU8a, cryptoWaitReady, naclBoxPairFromSecret, naclOpen, naclSeal, randomAsHex, blake2AsU8a, blake2AsHex, encodeAddress, } from '@polkadot/util-crypto' import { Crypto, Keyring } from '@kiltprotocol/utils' import { IDidKeyDetails, KeyRelationship, KeyringPair, Keystore, KeystoreSigningData, NaclBoxCapable, RequestData, ResponseData, } from '@kiltprotocol/types' import { BlockchainUtils } from '@kiltprotocol/chain-helpers' import { KeypairType } from '@polkadot/util-crypto/types' import { u8aEq } from '@polkadot/util' import { getKiltDidFromIdentifier } from '../Did.utils' import { FullDidDetails, LightDidDetails } from '../DidDetails' import { DefaultResolver, DidUtils } from '..' import { INewPublicKey, PublicKeyRoleAssignment } from '../types' import { newFullDidDetailsfromKeys } from '../DidDetails/FullDidDetails.utils' export enum SigningAlgorithms { Ed25519 = 'ed25519', Sr25519 = 'sr25519', EcdsaSecp256k1 = 'ecdsa-secp256k1', } export enum EncryptionAlgorithms { NaclBox = 'x25519-xsalsa20-poly1305', } const supportedAlgs = { ...EncryptionAlgorithms, ...SigningAlgorithms } function signingSupported(alg: string): alg is SigningAlgorithms { return Object.values(SigningAlgorithms).some((i) => i === alg) } function encryptionSupported(alg: string): alg is EncryptionAlgorithms { return Object.values(EncryptionAlgorithms).some((i) => i === alg) } export interface KeyGenOpts<T extends string> { alg: RequestData<T>['alg'] seed?: string } export interface NaclKeypair { publicKey: Uint8Array secretKey: Uint8Array } export type KeyAddOpts<T extends string> = Pick<RequestData<T>, 'alg'> & NaclKeypair const KeypairTypeForAlg: Record<string, string> = { ed25519: 'ed25519', sr25519: 'sr25519', 'ecdsa-secp256k1': 'ecdsa', 'x25519-xsalsa20-poly1305': 'x25519', } /** * Unsafe Keystore for Demo Purposes. Do not use to store sensible key material! */ export class DemoKeystore implements Keystore<SigningAlgorithms, EncryptionAlgorithms>, NaclBoxCapable { private signingKeyring: Keyring = new Keyring() private encryptionKeypairs: Map<string, NaclKeypair> = new Map() private getSigningKeyPair(publicKey: Uint8Array, alg: string): KeyringPair { if (!signingSupported(alg)) throw new Error(`alg ${alg} is not supported for signing`) const keyType = DemoKeystore.getKeypairTypeForAlg(alg) try { const keypair = this.signingKeyring.getPair(publicKey) if (keypair && keyType === keypair.type) return keypair } catch { throw Error(`no key ${Crypto.u8aToHex(publicKey)} for alg ${alg}`) } throw Error(`no key ${Crypto.u8aToHex(publicKey)} for alg ${alg}`) } private getEncryptionKeyPair( publicKey: Uint8Array, alg: string ): NaclKeypair { if (!encryptionSupported(alg)) throw new Error(`alg ${alg} is not supported for encryption`) const publicKeyHex = Crypto.u8aToHex(publicKey) const keypair = this.encryptionKeypairs.get(publicKeyHex) if (!keypair) throw Error(`no key ${publicKeyHex} for alg ${alg}`) return keypair } private async generateSigningKeypair<T extends SigningAlgorithms>( opts: KeyGenOpts<T> ): Promise<{ publicKey: Uint8Array alg: T }> { const { seed, alg } = opts await cryptoWaitReady() const keypairType = DemoKeystore.getKeypairTypeForAlg(alg) const keypair = this.signingKeyring.addFromUri( seed || randomAsHex(32), {}, keypairType as KeypairType ) return { alg, publicKey: keypair.publicKey } } private async generateEncryptionKeypair<T extends EncryptionAlgorithms>( opts: KeyGenOpts<T> ): Promise<{ publicKey: Uint8Array alg: T }> { const { seed, alg } = opts const { secretKey, publicKey } = naclBoxPairFromSecret( seed ? blake2AsU8a(seed, 256) : randomAsU8a(32) ) return this.addEncryptionKeypair({ alg, secretKey, publicKey }) } public async generateKeypair< T extends SigningAlgorithms | EncryptionAlgorithms >({ alg, seed, }: KeyGenOpts<T>): Promise<{ publicKey: Uint8Array alg: T }> { if (signingSupported(alg)) { return this.generateSigningKeypair({ alg, seed }) } if (encryptionSupported(alg)) { return this.generateEncryptionKeypair({ alg, seed }) } throw new Error(`alg ${alg} is not supported`) } private async addSigningKeypair<T extends SigningAlgorithms>({ alg, publicKey, secretKey, }: KeyAddOpts<T>): Promise<{ publicKey: Uint8Array alg: T }> { await cryptoWaitReady() if (this.signingKeyring.publicKeys.some((i) => u8aEq(publicKey, i))) throw new Error('public key already stored') const keypairType = DemoKeystore.getKeypairTypeForAlg(alg) const keypair = this.signingKeyring.addFromPair( { publicKey, secretKey }, {}, keypairType ) return { alg, publicKey: keypair.publicKey } } private async addEncryptionKeypair<T extends EncryptionAlgorithms>({ alg, secretKey, }: KeyAddOpts<T>): Promise<{ publicKey: Uint8Array alg: T }> { const keypair = naclBoxPairFromSecret(secretKey) const { publicKey } = keypair const publicKeyHex = Crypto.u8aToHex(publicKey) if (this.encryptionKeypairs.has(publicKeyHex)) throw new Error('public key already used') this.encryptionKeypairs.set(publicKeyHex, keypair) return { alg, publicKey } } public async addKeypair<T extends SigningAlgorithms | EncryptionAlgorithms>({ alg, publicKey, secretKey, }: KeyAddOpts<T>): Promise<{ publicKey: Uint8Array alg: T }> { if (signingSupported(alg)) { return this.addSigningKeypair({ alg, publicKey, secretKey }) } if (encryptionSupported(alg)) { return this.addEncryptionKeypair({ alg, publicKey, secretKey }) } throw new Error(`alg ${alg} is not supported`) } public async sign<A extends SigningAlgorithms>({ publicKey, alg, data, }: KeystoreSigningData<A>): Promise<ResponseData<A>> { const keypair = this.getSigningKeyPair(publicKey, alg) const signature = keypair.sign(data, { withType: false }) return { alg, data: signature } } public async encrypt<A extends 'x25519-xsalsa20-poly1305'>({ data, alg, publicKey, peerPublicKey, }: RequestData<A> & { peerPublicKey: Uint8Array }): Promise< ResponseData<A> & { nonce: Uint8Array } > { const keypair = this.getEncryptionKeyPair(publicKey, alg) // this is an alias for tweetnacl nacl.box const { nonce, sealed } = naclSeal(data, keypair.secretKey, peerPublicKey) return { data: sealed, alg, nonce } } public async decrypt<A extends 'x25519-xsalsa20-poly1305'>({ publicKey, alg, data, peerPublicKey, nonce, }: RequestData<A> & { peerPublicKey: Uint8Array nonce: Uint8Array }): Promise<ResponseData<A>> { const keypair = this.getEncryptionKeyPair(publicKey, alg) // this is an alias for tweetnacl nacl.box.open const decrypted = naclOpen(data, nonce, peerPublicKey, keypair.secretKey) if (!decrypted) return Promise.reject(new Error('failed to decrypt with given key')) return { data: decrypted, alg } } // eslint-disable-next-line class-methods-use-this public async supportedAlgs(): Promise< Set<SigningAlgorithms | EncryptionAlgorithms> > { return new Set(Object.values(supportedAlgs)) } public async hasKeys( keys: Array<Pick<RequestData<string>, 'alg' | 'publicKey'>> ): Promise<boolean[]> { const knownKeys = [ ...this.signingKeyring.publicKeys, ...[...this.encryptionKeypairs.values()].map((i) => i.publicKey), ] return keys.map((key) => knownKeys.some((i) => u8aEq(key.publicKey, i))) } public static getKeypairTypeForAlg(alg: string): KeypairType { return KeypairTypeForAlg[alg.toLowerCase()] as KeypairType } } /** * Creates an instance of [[FullDidDetails]] for local use, e.g., in testing. Will not work on-chain because identifiers are generated ad-hoc. * * @param keystore The keystore to generate and store the DID private keys. * @param mnemonicOrHexSeed The mnemonic phrase or HEX seed for key generation. * @param signingKeyType One of the supported [[SigningAlgorithms]] to generate the DID authentication key. * * @returns A promise resolving to a [[FullDidDetails]] object. The resulting object is NOT stored on chain. */ export async function createLocalDemoDidFromSeed( keystore: DemoKeystore, mnemonicOrHexSeed: string, signingKeyType = SigningAlgorithms.Ed25519 ): Promise<FullDidDetails> { const did = getKiltDidFromIdentifier( encodeAddress(blake2AsU8a(mnemonicOrHexSeed, 256), 38), 'full' ) const generateKeypairForDid = async ( derivation: string, alg: string, keytype: string ): Promise<IDidKeyDetails> => { const seed = derivation ? `${mnemonicOrHexSeed}//${derivation}` : mnemonicOrHexSeed const keyId = `${did}#${blake2AsHex(seed, 64)}` const { publicKey } = await keystore.generateKeypair<any>({ alg, seed, }) return { id: keyId, controller: did, type: keytype, publicKeyHex: Crypto.u8aToHex(publicKey), } } return newFullDidDetailsfromKeys({ [KeyRelationship.authentication]: await generateKeypairForDid( '', signingKeyType, signingKeyType ), [KeyRelationship.assertionMethod]: await generateKeypairForDid( 'assertionMethod', signingKeyType, signingKeyType ), [KeyRelationship.capabilityDelegation]: await generateKeypairForDid( 'capabilityDelegation', signingKeyType, signingKeyType ), [KeyRelationship.keyAgreement]: await generateKeypairForDid( 'keyAgreement', EncryptionAlgorithms.NaclBox, 'x25519' ), }) } export async function createLightDidFromSeed( keystore: DemoKeystore, mnemonicOrHexSeed: string, signingKeyType = SigningAlgorithms.Sr25519 ): Promise<LightDidDetails> { const authenticationPublicKey = await keystore.generateKeypair({ alg: signingKeyType, seed: mnemonicOrHexSeed, }) return new LightDidDetails({ authenticationKey: { publicKey: authenticationPublicKey.publicKey, type: authenticationPublicKey.alg, }, }) } export async function createOnChainDidFromSeed( paymentAccount: KeyringPair, keystore: DemoKeystore, mnemonicOrHexSeed: string, signingKeyType = SigningAlgorithms.Ed25519 ): Promise<FullDidDetails> { const makeKey = ( seed: string, alg: SigningAlgorithms | EncryptionAlgorithms ): Promise<INewPublicKey> => keystore .generateKeypair({ alg, seed, }) .then((key) => ({ ...key, type: DemoKeystore.getKeypairTypeForAlg(alg) })) const keys: PublicKeyRoleAssignment = { [KeyRelationship.authentication]: await makeKey( mnemonicOrHexSeed, signingKeyType ), [KeyRelationship.assertionMethod]: await makeKey( `${mnemonicOrHexSeed}//assertionMethod`, signingKeyType ), [KeyRelationship.capabilityDelegation]: await makeKey( `${mnemonicOrHexSeed}//capabilityDelegation`, signingKeyType ), [KeyRelationship.keyAgreement]: await makeKey( `${mnemonicOrHexSeed}//keyAgreement`, EncryptionAlgorithms.NaclBox ), } const { extrinsic, did } = await DidUtils.writeDidFromPublicKeys( keystore, paymentAccount.address, keys ) await BlockchainUtils.signAndSubmitTx(extrinsic, paymentAccount, { reSign: true, resolveOn: BlockchainUtils.IS_IN_BLOCK, }) const queried = await DefaultResolver.resolveDoc(did) if (queried) { return queried.details as FullDidDetails } throw Error(`failed to write Did${did}`) }
the_stack
namespace JustinCredible.SampleApp.Controllers { export class DeveloperController extends BaseController<ViewModels.DeveloperViewModel> { //#region Injection public static ID = "DeveloperController"; public static get $inject(): string[] { return [ "$scope", "$rootScope", "$injector", "$window", Services.Plugins.ID, Services.Platform.ID, Services.UIHelper.ID, Services.FileUtilities.ID, Services.Logger.ID, Services.Preferences.ID, Services.Configuration.ID, Services.MockPlatformApis.ID ]; } constructor( $scope: ng.IScope, private $rootScope: ng.IRootScopeService, private $injector: ng.auto.IInjectorService, private $window: ng.IWindowService, private Plugins: Services.Plugins, private Platform: Services.Platform, private UIHelper: Services.UIHelper, private FileUtilities: Services.FileUtilities, private Logger: Services.Logger, private Preferences: Services.Preferences, private Configuration: Services.Configuration, private MockPlatformApis: Services.MockPlatformApis) { super($scope, ViewModels.DeveloperViewModel); } //#endregion //#region BaseController Overrides protected view_beforeEnter(event?: ng.IAngularEvent, eventArgs?: Interfaces.ViewEventArguments): void { super.view_beforeEnter(event, eventArgs); this.viewModel.mockApiRequests = this.Configuration.enableMockHttpCalls; this.viewModel.userId = this.Preferences.userId; this.viewModel.token = this.Preferences.token; this.viewModel.isWebPlatform = this.Platform.web; this.viewModel.isWebStandalone = this.Platform.webStandalone; this.viewModel.devicePlatform = this.Platform.device.platform; this.viewModel.deviceModel = this.Platform.device.model; this.viewModel.deviceOsVersion = this.Platform.device.version; this.viewModel.deviceUuid = this.Platform.device.uuid; this.viewModel.deviceCordovaVersion = this.Platform.device.cordova; this.viewModel.navigatorPlatform = this.$window.navigator.platform; this.viewModel.navigatorProduct = this.$window.navigator.product; this.viewModel.navigatorVendor = this.$window.navigator.vendor; this.viewModel.viewport = this.Platform.viewport; this.viewModel.userAgent = this.$window.navigator.userAgent; this.viewModel.defaultStoragePathId = this.FileUtilities.getDefaultRootPathId(); this.viewModel.defaultStoragePath = this.FileUtilities.getDefaultRootPath(); this.viewModel.apiUrl = this.Configuration.apiUrl; } //#endregion //#region Private Helper Methods private alertFileIoError(error: any) { if (error) { if (error.code) { this.UIHelper.alert(error.code); } else if (error.message) { this.UIHelper.alert(error.message); } else { this.UIHelper.alert(error); } } } //#endregion //#region Controller Methods protected help_click(helpMessage: string): void { this.UIHelper.alert(helpMessage, "Help"); } protected copyValue_click(value: any, name: string): void { this.UIHelper.confirm("Copy " + name + " to clipboard?").then((result: string) => { if (result === Constants.Buttons.Yes) { this.Plugins.clipboard.copy(value); this.Plugins.toast.showShortBottom(name + " copied to clipboard."); } }); } protected mockApiRequests_change(): void { this.Configuration.enableMockHttpCalls = this.viewModel.mockApiRequests; var message = "The application needs to be reloaded for changes to take effect.\n\nReload now?"; this.UIHelper.confirm(message, "Confirm Reload").then((result: string) => { if (result === Constants.Buttons.Yes) { document.location.href = "index.html"; } }); } protected apiUrl_click(): void { var message = "Here you can edit the API URL for this session."; this.UIHelper.prompt(message, "API URL", null, this.Configuration.apiUrl).then((result: Models.KeyValuePair<string, string>) => { if (result.key === Constants.Buttons.Cancel) { return; } this.Configuration.apiUrl = result.value; this.viewModel.apiUrl = result.value; this.Plugins.toast.showShortBottom("API URL changed for this session only."); }); } protected addServicesToGlobalScope_click(): void { /* tslint:disable:no-string-literal */ this.$window["__services"] = { $rootScope: this.$rootScope }; for (var key in Services) { if (!Services.hasOwnProperty(key)) { continue; } let serviceId = Services[key].ID; try { let service = this.$injector.get(serviceId); this.$window["__services"][key] = service; } catch (err) { /* tslint:disable:no-empty */ /* tslint:enable:no-empty */ } } /* tslint:enable:no-string-literal */ this.UIHelper.alert("Added services to the global variable __services."); } protected setRequirePinThreshold_click(): void { var message = `Enter the value (in minutes) for PIN prompt threshold? Current setting is ${this.Configuration.requirePinThreshold} minutes.`; this.UIHelper.prompt(message, "Require PIN Threshold", null, this.Configuration.requirePinThreshold.toString()).then((result: Models.KeyValuePair<string, string>) => { if (result.key !== Constants.Buttons.OK) { return; } if (isNaN(parseInt(result.value, 10))) { this.UIHelper.alert("Invalid value; a number is required."); return; } this.Configuration.requirePinThreshold = parseInt(result.value, 10); this.UIHelper.alert(`PIN prompt threshold is now set to ${result.value} minutes.`); }); } protected resetPinTimeout_click(): void { this.Configuration.lastPausedAt = moment("01-01-2000", "MM-DD-yyyy"); var message = "The PIN timeout has been set to more than 10 minutes ago. To see the PIN screen, terminate the application via the OS task manager (don't just background it), and then re-launch."; this.UIHelper.alert(message, "Reset PIN Timeout"); } protected reEnableOnboarding_click(): void { this.Configuration.hasCompletedOnboarding = false; this.UIHelper.alert("Onboarding has been enabled and will occur upon next app boot."); } protected testJsException_click(): void { /* tslint:disable:no-string-literal */ // Cause an exception by referencing an undefined variable. // We use defer so we can execute outside of the context of Angular. _.defer(function () { var x = window["____asdf"].blah(); }); /* tslint:enable:no-string-literal */ } protected testAngularException_click(): void { /* tslint:disable:no-string-literal */ // Cause an exception by referencing an undefined variable. var x = window["____asdf"].blah(); /* tslint:enable:no-string-literal */ } protected showFullScreenBlock_click(): void { this.Plugins.spinner.activityStart("Blocking..."); setTimeout(() => { this.Plugins.spinner.activityStop(); }, 4000); } protected showToast_top(): void { this.Plugins.toast.showShortTop("This is a test toast notification."); } protected showToast_center(): void { this.Plugins.toast.showShortCenter("This is a test toast notification."); } protected showToast_bottom(): void { this.Plugins.toast.showShortBottom("This is a test toast notification."); } protected clipboard_copy(): void { this.UIHelper.prompt("Enter a value to copy to the clipboard.").then((result: Models.KeyValuePair<string, string>) => { if (result.key !== Constants.Buttons.OK) { return; } this.Plugins.clipboard.copy(result.value, () => { this.UIHelper.alert("Copy OK!"); }, (err: Error) => { this.UIHelper.alert("Copy Failed!\n\n" + (err ? err.message : "Unknown Error")); }); }); } protected clipboard_paste(): void { this.Plugins.clipboard.paste((result: string) => { this.UIHelper.alert("Paste OK! Value retrieved is:\n\n" + result); }, (err: Error) => { this.UIHelper.alert("Paste Failed!\n\n" + (err ? err.message : "Unknown Error")); }); } protected startProgress_click(): void { NProgress.start(); } protected incrementProgress_click(): void { NProgress.inc(); } protected doneProgress_click(): void { NProgress.done(); } protected readFile_click(): void { this.UIHelper.prompt("Enter file name to read from", "File I/O Test", null, "/").then((result: Models.KeyValuePair<string, string>) => { if (result.key !== Constants.Buttons.OK) { return; } this.FileUtilities.readTextFile(result.value) .then((text: string) => { this.Logger.debug(DeveloperController.ID, "readFile_click", "Read OK.", text); this.UIHelper.alert(text); }, (err: Error) => { this.Logger.error(DeveloperController.ID, "readFile_click", "An error occurred.", err); this.alertFileIoError(err); }); }); } protected writeFile_click(): void { var path: string, contents: string; this.UIHelper.prompt("Enter file name to write to", "File I/O Test", null, "/").then((result: Models.KeyValuePair<string, string>) => { if (result.key !== Constants.Buttons.OK) { return; } path = result.value; this.UIHelper.prompt("Enter file contents").then((result: Models.KeyValuePair<string, string>) => { if (result.key !== Constants.Buttons.OK) { return; } contents = result.value; this.FileUtilities.writeTextFile(path, contents, false) .then(() => { this.Logger.debug(DeveloperController.ID, "writeFile_click", "Write OK.", { path: path, contents: contents }); this.UIHelper.alert("Write OK."); }, (err: Error) => { this.Logger.error(DeveloperController.ID, "writeFile_click", "An error occurred.", err); this.alertFileIoError(err); }); }); }); } protected appendFile_click(): void { var path: string, contents: string; this.UIHelper.prompt("Enter file name to write to", "File I/O Test", null, "/").then((result: Models.KeyValuePair<string, string>) => { if (result.key !== Constants.Buttons.OK) { return; } this.UIHelper.prompt("Enter file contents", "File I/O Test", null, " / ").then((result: Models.KeyValuePair<string, string>) => { if (result.key !== Constants.Buttons.OK) { return; } contents = result.value; this.FileUtilities.writeTextFile(path, contents, true) .then(() => { this.Logger.debug(DeveloperController.ID, "appendFile_click", "Append OK.", { path: path, contents: contents }); this.UIHelper.alert("Append OK."); }, (err: Error) => { this.Logger.error(DeveloperController.ID, "appendFile_click", "An error occurred.", err); this.alertFileIoError(err); }); }); }); } protected createDir_click(): void { var path: string; this.UIHelper.prompt("Enter dir name to create", "File I/O Test", null, "/").then((result: Models.KeyValuePair<string, string>) => { if (result.key !== Constants.Buttons.OK) { return; } path = result.value; this.FileUtilities.createDirectory(path) .then(() => { this.Logger.debug(DeveloperController.ID, "createDir_click", "Create directory OK.", path); this.UIHelper.alert("Create directory OK."); }, (err: Error) => { this.Logger.error(DeveloperController.ID, "createDir_click", "An error occurred.", err); this.alertFileIoError(err); }); }); } protected listFiles_click(): void { var path: string, list = ""; this.UIHelper.prompt("Enter path to list files", "File I/O Test", null, "/").then((result: Models.KeyValuePair<string, string>) => { if (result.key !== Constants.Buttons.OK) { return; } path = result.value; this.FileUtilities.getFilePaths(path) .then((files: any) => { this.Logger.debug(DeveloperController.ID, "listFiles_click", "Get file paths OK.", files); files.forEach((value: string) => { list += "\n" + value; }); this.UIHelper.alert(list); }, (err: Error) => { this.Logger.error(DeveloperController.ID, "listFiles_click", "An error occurred.", err); this.alertFileIoError(err); }); }); } protected listDirs_click(): void { var path: string, list = ""; this.UIHelper.prompt("Enter path to list dirs", "File I/O Test", null, "/").then((result: Models.KeyValuePair<string, string>) => { if (result.key !== Constants.Buttons.OK) { return; } path = result.value; this.FileUtilities.getDirectoryPaths(path) .then((dirs: any) => { this.Logger.debug(DeveloperController.ID, "listDirs_click", "Get directory paths OK.", dirs); dirs.forEach((value: string) => { list += "\n" + value; }); this.UIHelper.alert(list); }, (err: Error) => { this.Logger.error(DeveloperController.ID, "listDirs_click", "An error occurred.", err); this.alertFileIoError(err); }); }); } protected deleteFile_click(): void { var path: string; this.UIHelper.prompt("Enter path to delete file", "File I/O Test", null, "/").then((result: Models.KeyValuePair<string, string>) => { if (result.key !== Constants.Buttons.OK) { return; } path = result.value; this.FileUtilities.deleteFile(path) .then(() => { this.Logger.debug(DeveloperController.ID, "deleteFile_click", "Delete file OK.", path); this.UIHelper.alert("Delete file OK."); }, (err: Error) => { this.Logger.error(DeveloperController.ID, "deleteFile_click", "An error occurred.", err); this.alertFileIoError(err); }); }); } protected deleteDir_click(): void { var path: string; this.UIHelper.prompt("Enter path to delete dir", "File I/O Test", null, "/").then((result: Models.KeyValuePair<string, string>) => { if (result.key !== Constants.Buttons.OK) { return; } path = result.value; this.FileUtilities.deleteDirectory(path) .then(() => { this.Logger.debug(DeveloperController.ID, "deleteDir_click", "Delete directory OK.", path); this.UIHelper.alert("Delete directory OK"); }, (err: Error) => { this.Logger.error(DeveloperController.ID, "deleteDir_click", "An error occurred.", err); this.alertFileIoError(err); }); }); } //#endregion } }
the_stack
import * as React from 'react'; import './screencast.css'; // This implementation is heavily inspired by https://cs.chromium.org/chromium/src/third_party/blink/renderer/devtools/front_end/screencast/ScreencastView.js class Screencast extends React.Component<any, any> { private canvasRef: React.RefObject<HTMLCanvasElement>; private imageRef: React.RefObject<HTMLImageElement>; private canvasContext: CanvasRenderingContext2D | null; private frameId: number | null; private frame: string | null; private viewportMetadata: any; constructor(props: any) { super(props); this.canvasRef = React.createRef(); this.imageRef = React.createRef(); this.canvasContext = null; this.frameId = null; this.frame = props.frame; this.handleMouseEvent = this.handleMouseEvent.bind(this); this.handleKeyEvent = this.handleKeyEvent.bind(this); this.renderLoop = this.renderLoop.bind(this); this.state = { imageZoom: 1, screenOffsetTop: 0 }; } static getDerivedStateFromProps(nextProps: any, prevState: any) { if (nextProps.frame !== prevState.frame) { return { frame: nextProps.frame }; } else return null; } public componentDidUpdate(prevProps: any, prevState: any) { if (prevState.frame !== this.state.frame) { this.renderScreencastFrame(); } } public componentDidMount() { this.startLoop(); } public componentWillUnmount() { this.stopLoop(); } public startLoop() { if (!this.frameId) { this.frameId = window.requestAnimationFrame(this.renderLoop); } } public stopLoop() { if (this.frameId) { window.cancelAnimationFrame(this.frameId); } } public renderLoop() { this.renderFrame(); this.frameId = window.requestAnimationFrame(this.renderLoop); // Set up next iteration of the loop } public render() { let canvasStyle = { cursor: this.viewportMetadata ? this.viewportMetadata.cursor : 'auto' }; return ( <> <img ref={this.imageRef} className="img-hidden" /> <canvas className="screencast" style={canvasStyle} ref={this.canvasRef} onMouseDown={this.handleMouseEvent} onMouseUp={this.handleMouseEvent} onMouseMove={this.handleMouseEvent} onClick={this.handleMouseEvent} onWheel={this.handleMouseEvent} onKeyDown={this.handleKeyEvent} onKeyUp={this.handleKeyEvent} onKeyPress={this.handleKeyEvent} tabIndex={0} /> </> ); } private renderFrame() { if (!this.canvasRef.current || !this.imageRef.current) { return; } this.viewportMetadata = this.props.viewportMetadata; this.canvasContext = this.canvasRef.current.getContext('2d'); const canvasElement = this.canvasRef.current; const imageElement = this.imageRef.current; if (!this.canvasContext) { return; } this.canvasContext.imageSmoothingEnabled = false; const checkerboardPattern = this.getCheckerboardPattern(canvasElement, this.canvasContext); let devicePixelRatio = window.devicePixelRatio || 1; // Resize and scale canvas const canvasWidth = this.props.width; const canvasHeight = this.props.height; // TODO Move out to increase performance canvasElement.width = canvasWidth * devicePixelRatio; canvasElement.height = canvasHeight * devicePixelRatio; this.canvasContext.scale(devicePixelRatio, devicePixelRatio); // Render checkerboard this.canvasContext.save(); this.canvasContext.fillStyle = checkerboardPattern; this.canvasContext.fillRect(0, 0, canvasWidth, canvasHeight); this.canvasContext.restore(); // Render viewport frame let dy = this.state.screenOffsetTop * this.viewportMetadata.screenZoom; let dw = this.props.width; let dh = this.props.height; // Render screen frame this.canvasContext.save(); this.canvasContext.drawImage(imageElement, 0, dy, dw, dh); this.canvasContext.restore(); // Render element highlight if (this.props.viewportMetadata && this.props.viewportMetadata.highlightInfo) { let model = this.scaleBoxModelToViewport(this.props.viewportMetadata.highlightInfo); let config = { contentColor: 'rgba(111, 168, 220, .66)', paddingColor: 'rgba(147, 196, 125, .55)', borderColor: 'rgba(255, 229, 153, .66)', marginColor: 'rgba(246, 178, 107, .66)' }; this.canvasContext.save(); const quads = []; if (model.content) { quads.push({ quad: model.content, color: config.contentColor }); } if (model.padding) { quads.push({ quad: model.padding, color: config.paddingColor }); } if (model.border) { quads.push({ quad: model.border, color: config.borderColor }); } if (model.margin) { quads.push({ quad: model.margin, color: config.marginColor }); } for (let i = quads.length - 1; i > 0; --i) { this.canvasContext.save(); this.canvasContext.globalAlpha = 0.66; this.drawOutlinedQuadWithClip(this.canvasContext, quads[i].quad, quads[i - 1].quad, quads[i].color); this.canvasContext.restore(); } if (quads.length > 0) { this.canvasContext.save(); this.drawOutlinedQuad(this.canvasContext, quads[0].quad, quads[0].color); this.canvasContext.restore(); } this.canvasContext.restore(); } } public renderScreencastFrame() { const screencastFrame = this.props.frame; const imageElement = this.imageRef.current; if (imageElement && screencastFrame) { // const canvasWidth = this.props.width; // const canvasHeight = this.props.height; // const deviceSizeRatio = metadata.deviceHeight / metadata.deviceWidth; // let imageZoom = Math.min( // canvasWidth / metadata.deviceWidth, // canvasHeight / (metadata.deviceWidth * deviceSizeRatio) // ); // if (imageZoom < 1.01 / window.devicePixelRatio) { // imageZoom = 1 / window.devicePixelRatio; // } const metadata = screencastFrame.metadata; const format = this.props.format; this.setState({ screenOffsetTop: metadata.offsetTop, scrollOffsetX: metadata.scrollOffsetX, scrollOffsetY: metadata.scrollOffsetY }); imageElement.src = 'data:image/' + format + ';base64,' + screencastFrame.base64Data; } } private getCheckerboardPattern(canvas: HTMLCanvasElement, context: CanvasRenderingContext2D): CanvasPattern { const pattern = canvas; const size = 32; const pctx = pattern.getContext('2d'); // Pattern size pattern.width = size * 2; pattern.height = size * 2; if (pctx) { // Dark grey pctx.fillStyle = 'rgb(195, 195, 195)'; pctx.fillRect(0, 0, size * 2, size * 2); // Light grey pctx.fillStyle = 'rgb(225, 225, 225)'; pctx.fillRect(0, 0, size, size); pctx.fillRect(size, size, size, size); } let result = context.createPattern(pattern, 'repeat'); if (result) { return result; } else { return new CanvasPattern(); } } private handleMouseEvent(event: any) { if (this.props.isInspectEnabled) { if (event.type === 'click') { const position = this.convertIntoScreenSpace(event, this.state); this.props.onInspectElement({ position: position }); } else if (event.type === 'mousemove') { const position = this.convertIntoScreenSpace(event, this.state); this.props.onInspectHighlightRequested({ position: position }); } } else { this.dispatchMouseEvent(event.nativeEvent); } if (event.type === 'mousemove') { const position = this.convertIntoScreenSpace(event, this.state); this.props.onMouseMoved({ position: position }); } if (event.type === 'mousedown') { if (this.canvasRef.current) { this.canvasRef.current.focus(); } } } private convertIntoScreenSpace(event: any, state: any) { let screenOffsetTop = 0; if (this.canvasRef && this.canvasRef.current) { screenOffsetTop = this.canvasRef.current.getBoundingClientRect().top; } return { x: Math.round(event.clientX / this.viewportMetadata.screenZoom + this.state.scrollOffsetX), y: Math.round(event.clientY / this.viewportMetadata.screenZoom - screenOffsetTop + this.state.scrollOffsetY) }; } private quadToPath(context: any, quad: any) { context.beginPath(); context.moveTo(quad[0], quad[1]); context.lineTo(quad[2], quad[3]); context.lineTo(quad[4], quad[5]); context.lineTo(quad[6], quad[7]); context.closePath(); return context; } private drawOutlinedQuad(context: any, quad: any, fillColor: any) { context.lineWidth = 2; this.quadToPath(context, quad).clip(); context.fillStyle = fillColor; context.fill(); } private drawOutlinedQuadWithClip(context: any, quad: any, clipQuad: any, fillColor: any) { context.fillStyle = fillColor; context.lineWidth = 0; this.quadToPath(context, quad).fill(); context.globalCompositeOperation = 'destination-out'; context.fillStyle = 'red'; this.quadToPath(context, clipQuad).fill(); } private scaleBoxModelToViewport(model: any) { let zoomFactor = this.viewportMetadata.screenZoom; let offsetTop = this.state.screenOffsetTop; function scaleQuad(quad: any) { for (let i = 0; i < quad.length; i += 2) { quad[i] = quad[i] * zoomFactor; quad[i + 1] = (quad[i + 1] + offsetTop) * zoomFactor; } } scaleQuad.call(this, model.content); scaleQuad.call(this, model.padding); scaleQuad.call(this, model.border); scaleQuad.call(this, model.margin); return model; } private handleKeyEvent(event: any) { this.emitKeyEvent(event.nativeEvent); if (event.key === 'Tab') { event.preventDefault(); } if (this.canvasRef.current) { this.canvasRef.current.focus(); } } private modifiersForEvent(event: any) { return (event.altKey ? 1 : 0) | (event.ctrlKey ? 2 : 0) | (event.metaKey ? 4 : 0) | (event.shiftKey ? 8 : 0); } private emitKeyEvent(event: any) { let type; switch (event.type) { case 'keydown': type = 'keyDown'; break; case 'keyup': type = 'keyUp'; break; case 'keypress': type = 'char'; break; default: return; } const text = event.type === 'keypress' ? String.fromCharCode(event.charCode) : undefined; var params = { type: type, modifiers: this.modifiersForEvent(event), text: text, unmodifiedText: text ? text.toLowerCase() : undefined, keyIdentifier: event.keyIdentifier, code: event.code, key: event.key, windowsVirtualKeyCode: event.keyCode, nativeVirtualKeyCode: event.keyCode, autoRepeat: false, isKeypad: false, isSystemKey: false }; this.props.onInteraction('Input.dispatchKeyEvent', params); } private dispatchMouseEvent(event: any) { let clickCount = 0; const buttons = { 0: 'none', 1: 'left', 2: 'middle', 3: 'right' }; const types = { mousedown: 'mousePressed', mouseup: 'mouseReleased', mousemove: 'mouseMoved', wheel: 'mouseWheel' }; if (!(event.type in types)) { return; } let x = Math.round(event.offsetX / this.viewportMetadata.screenZoom); let y = Math.round(event.offsetY / this.viewportMetadata.screenZoom); let type = (types as any)[event.type]; if (type == 'mousePressed' || type == 'mouseReleased') { clickCount = 1; } const params = { type: type, x: x, y: y, modifiers: this.modifiersForEvent(event), button: (buttons as any)[event.which], clickCount: clickCount, deltaX: 0, deltaY: 0 }; if (type === 'mouseWheel') { params.deltaX = event.deltaX / this.viewportMetadata.screenZoom; params.deltaY = event.deltaY / this.viewportMetadata.screenZoom; } this.props.onInteraction('Input.dispatchMouseEvent', params); } } export default Screencast;
the_stack
type Maybe<T> = T | null; /** All built-in and custom scalars, mapped to their actual values */ export type Scalars = { ID: string; String: string; Boolean: boolean; Int: number; Float: number; /** A date string, such as 2007-12-03, compliant with the ISO 8601 standard for * representation of dates and times using the Gregorian calendar. */ Date: any; Ever_Date: any; Ever_Any: any; Ever_Void: any; }; export type Dependencies_2 = { name?: Maybe<Scalars['String']>; version?: Maybe<Scalars['String']>; }; export type DevDependencies_2 = { name?: Maybe<Scalars['String']>; version?: Maybe<Scalars['String']>; }; /** Node of type Directory */ export type Directory = Node & { /** The id of this node. */ id: Scalars['ID']; /** The parent of this node. */ parent?: Maybe<Node>; /** The children of this node. */ children?: Maybe<Array<Maybe<Node>>>; internal?: Maybe<Internal_9>; sourceInstanceName?: Maybe<Scalars['String']>; absolutePath?: Maybe<Scalars['String']>; relativePath?: Maybe<Scalars['String']>; extension?: Maybe<Scalars['String']>; size?: Maybe<Scalars['Int']>; prettySize?: Maybe<Scalars['String']>; modifiedTime?: Maybe<Scalars['Date']>; accessTime?: Maybe<Scalars['Date']>; changeTime?: Maybe<Scalars['Date']>; birthTime?: Maybe<Scalars['Date']>; root?: Maybe<Scalars['String']>; dir?: Maybe<Scalars['String']>; base?: Maybe<Scalars['String']>; ext?: Maybe<Scalars['String']>; name?: Maybe<Scalars['String']>; relativeDirectory?: Maybe<Scalars['String']>; dev?: Maybe<Scalars['Int']>; mode?: Maybe<Scalars['Int']>; nlink?: Maybe<Scalars['Int']>; uid?: Maybe<Scalars['Int']>; gid?: Maybe<Scalars['Int']>; rdev?: Maybe<Scalars['Int']>; ino?: Maybe<Scalars['Float']>; atimeMs?: Maybe<Scalars['Float']>; mtimeMs?: Maybe<Scalars['Float']>; ctimeMs?: Maybe<Scalars['Float']>; birthtimeMs?: Maybe<Scalars['Float']>; atime?: Maybe<Scalars['Date']>; mtime?: Maybe<Scalars['Date']>; ctime?: Maybe<Scalars['Date']>; birthtime?: Maybe<Scalars['Date']>; }; /** Node of type Directory */ export type DirectoryModifiedTimeArgs = { formatString?: Maybe<Scalars['String']>; fromNow?: Maybe<Scalars['Boolean']>; difference?: Maybe<Scalars['String']>; locale?: Maybe<Scalars['String']>; }; /** Node of type Directory */ export type DirectoryAccessTimeArgs = { formatString?: Maybe<Scalars['String']>; fromNow?: Maybe<Scalars['Boolean']>; difference?: Maybe<Scalars['String']>; locale?: Maybe<Scalars['String']>; }; /** Node of type Directory */ export type DirectoryChangeTimeArgs = { formatString?: Maybe<Scalars['String']>; fromNow?: Maybe<Scalars['Boolean']>; difference?: Maybe<Scalars['String']>; locale?: Maybe<Scalars['String']>; }; /** Node of type Directory */ export type DirectoryBirthTimeArgs = { formatString?: Maybe<Scalars['String']>; fromNow?: Maybe<Scalars['Boolean']>; difference?: Maybe<Scalars['String']>; locale?: Maybe<Scalars['String']>; }; /** Node of type Directory */ export type DirectoryAtimeArgs = { formatString?: Maybe<Scalars['String']>; fromNow?: Maybe<Scalars['Boolean']>; difference?: Maybe<Scalars['String']>; locale?: Maybe<Scalars['String']>; }; /** Node of type Directory */ export type DirectoryMtimeArgs = { formatString?: Maybe<Scalars['String']>; fromNow?: Maybe<Scalars['Boolean']>; difference?: Maybe<Scalars['String']>; locale?: Maybe<Scalars['String']>; }; /** Node of type Directory */ export type DirectoryCtimeArgs = { formatString?: Maybe<Scalars['String']>; fromNow?: Maybe<Scalars['Boolean']>; difference?: Maybe<Scalars['String']>; locale?: Maybe<Scalars['String']>; }; /** Node of type Directory */ export type DirectoryBirthtimeArgs = { formatString?: Maybe<Scalars['String']>; fromNow?: Maybe<Scalars['Boolean']>; difference?: Maybe<Scalars['String']>; locale?: Maybe<Scalars['String']>; }; export type DirectoryAbsolutePathQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryAccessTimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryAtimeMsQueryFloat_2 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type DirectoryAtimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryBaseQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryBirthtimeMsQueryFloat_2 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type DirectoryBirthtimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryBirthTimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryChangeTimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; /** A connection to a list of items. */ export type DirectoryConnection = { /** Information to aid in pagination. */ pageInfo: PageInfo; /** A list of edges. */ edges?: Maybe<Array<Maybe<DirectoryEdge>>>; totalCount?: Maybe<Scalars['Int']>; distinct?: Maybe<Array<Maybe<Scalars['String']>>>; group?: Maybe<Array<Maybe<DirectoryGroupConnectionConnection>>>; }; /** A connection to a list of items. */ export type DirectoryConnectionDistinctArgs = { field?: Maybe<DirectoryDistinctEnum>; }; /** A connection to a list of items. */ export type DirectoryConnectionGroupArgs = { skip?: Maybe<Scalars['Int']>; limit?: Maybe<Scalars['Int']>; field?: Maybe<DirectoryGroupEnum>; }; export type DirectoryConnectionAbsolutePathQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryConnectionAccessTimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryConnectionAtimeMsQueryFloat_2 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type DirectoryConnectionAtimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryConnectionBaseQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryConnectionBirthtimeMsQueryFloat_2 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type DirectoryConnectionBirthtimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryConnectionBirthTimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryConnectionChangeTimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryConnectionCtimeMsQueryFloat_2 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type DirectoryConnectionCtimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryConnectionDevQueryInteger_2 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type DirectoryConnectionDirQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryConnectionExtensionQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryConnectionExtQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryConnectionGidQueryInteger_2 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type DirectoryConnectionIdQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryConnectionInoQueryFloat_2 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type DirectoryConnectionInternalContentDigestQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryConnectionInternalDescriptionQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryConnectionInternalInputObject_2 = { contentDigest?: Maybe<DirectoryConnectionInternalContentDigestQueryString_2>; type?: Maybe<DirectoryConnectionInternalTypeQueryString_2>; description?: Maybe<DirectoryConnectionInternalDescriptionQueryString_2>; owner?: Maybe<DirectoryConnectionInternalOwnerQueryString_2>; }; export type DirectoryConnectionInternalOwnerQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryConnectionInternalTypeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryConnectionModeQueryInteger_2 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type DirectoryConnectionModifiedTimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryConnectionMtimeMsQueryFloat_2 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type DirectoryConnectionMtimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryConnectionNameQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryConnectionNlinkQueryInteger_2 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type DirectoryConnectionPrettySizeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryConnectionRdevQueryInteger_2 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type DirectoryConnectionRelativeDirectoryQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryConnectionRelativePathQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryConnectionRootQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryConnectionSizeQueryInteger_2 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type DirectoryConnectionSort = { fields: Array<Maybe<DirectoryConnectionSortByFieldsEnum>>; order?: Maybe<Array<Maybe<DirectoryConnectionSortOrderValues>>>; }; export enum DirectoryConnectionSortByFieldsEnum { Id = 'id', Internal___ContentDigest = 'internal___contentDigest', Internal___Type = 'internal___type', Internal___Description = 'internal___description', Internal___Owner = 'internal___owner', SourceInstanceName = 'sourceInstanceName', AbsolutePath = 'absolutePath', RelativePath = 'relativePath', Extension = 'extension', Size = 'size', PrettySize = 'prettySize', ModifiedTime = 'modifiedTime', AccessTime = 'accessTime', ChangeTime = 'changeTime', BirthTime = 'birthTime', Root = 'root', Dir = 'dir', Base = 'base', Ext = 'ext', Name = 'name', RelativeDirectory = 'relativeDirectory', Dev = 'dev', Mode = 'mode', Nlink = 'nlink', Uid = 'uid', Gid = 'gid', Rdev = 'rdev', Ino = 'ino', AtimeMs = 'atimeMs', MtimeMs = 'mtimeMs', CtimeMs = 'ctimeMs', BirthtimeMs = 'birthtimeMs', Atime = 'atime', Mtime = 'mtime', Ctime = 'ctime', Birthtime = 'birthtime', } export enum DirectoryConnectionSortOrderValues { Asc = 'ASC', Desc = 'DESC', } export type DirectoryConnectionSourceInstanceNameQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryConnectionUidQueryInteger_2 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type DirectoryCtimeMsQueryFloat_2 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type DirectoryCtimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryDevQueryInteger_2 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type DirectoryDirQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export enum DirectoryDistinctEnum { Id = 'id', Internal___ContentDigest = 'internal___contentDigest', Internal___Type = 'internal___type', Internal___Description = 'internal___description', Internal___Owner = 'internal___owner', SourceInstanceName = 'sourceInstanceName', AbsolutePath = 'absolutePath', RelativePath = 'relativePath', Extension = 'extension', Size = 'size', PrettySize = 'prettySize', ModifiedTime = 'modifiedTime', AccessTime = 'accessTime', ChangeTime = 'changeTime', BirthTime = 'birthTime', Root = 'root', Dir = 'dir', Base = 'base', Ext = 'ext', Name = 'name', RelativeDirectory = 'relativeDirectory', Dev = 'dev', Mode = 'mode', Nlink = 'nlink', Uid = 'uid', Gid = 'gid', Rdev = 'rdev', Ino = 'ino', AtimeMs = 'atimeMs', MtimeMs = 'mtimeMs', CtimeMs = 'ctimeMs', BirthtimeMs = 'birthtimeMs', Atime = 'atime', Mtime = 'mtime', Ctime = 'ctime', Birthtime = 'birthtime', } /** An edge in a connection. */ export type DirectoryEdge = { /** The item at the end of the edge */ node?: Maybe<Directory>; /** The next edge in the connection */ next?: Maybe<Directory>; /** The previous edge in the connection */ previous?: Maybe<Directory>; }; export type DirectoryExtensionQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryExtQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryGidQueryInteger_2 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; /** A connection to a list of items. */ export type DirectoryGroupConnectionConnection = { /** Information to aid in pagination. */ pageInfo: PageInfo; /** A list of edges. */ edges?: Maybe<Array<Maybe<DirectoryGroupConnectionEdge>>>; field?: Maybe<Scalars['String']>; fieldValue?: Maybe<Scalars['String']>; totalCount?: Maybe<Scalars['Int']>; }; /** An edge in a connection. */ export type DirectoryGroupConnectionEdge = { /** The item at the end of the edge */ node?: Maybe<Directory>; /** The next edge in the connection */ next?: Maybe<Directory>; /** The previous edge in the connection */ previous?: Maybe<Directory>; }; export enum DirectoryGroupEnum { Id = 'id', Internal___ContentDigest = 'internal___contentDigest', Internal___Type = 'internal___type', Internal___Description = 'internal___description', Internal___Owner = 'internal___owner', SourceInstanceName = 'sourceInstanceName', AbsolutePath = 'absolutePath', RelativePath = 'relativePath', Extension = 'extension', Size = 'size', PrettySize = 'prettySize', ModifiedTime = 'modifiedTime', AccessTime = 'accessTime', ChangeTime = 'changeTime', BirthTime = 'birthTime', Root = 'root', Dir = 'dir', Base = 'base', Ext = 'ext', Name = 'name', RelativeDirectory = 'relativeDirectory', Dev = 'dev', Mode = 'mode', Nlink = 'nlink', Uid = 'uid', Gid = 'gid', Rdev = 'rdev', Ino = 'ino', AtimeMs = 'atimeMs', MtimeMs = 'mtimeMs', CtimeMs = 'ctimeMs', BirthtimeMs = 'birthtimeMs', Atime = 'atime', Mtime = 'mtime', Ctime = 'ctime', Birthtime = 'birthtime', } export type DirectoryIdQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryInoQueryFloat_2 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type DirectoryInternalContentDigestQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryInternalDescriptionQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryInternalInputObject_2 = { contentDigest?: Maybe<DirectoryInternalContentDigestQueryString_2>; type?: Maybe<DirectoryInternalTypeQueryString_2>; description?: Maybe<DirectoryInternalDescriptionQueryString_2>; owner?: Maybe<DirectoryInternalOwnerQueryString_2>; }; export type DirectoryInternalOwnerQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryInternalTypeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryModeQueryInteger_2 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type DirectoryModifiedTimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryMtimeMsQueryFloat_2 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type DirectoryMtimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryNameQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryNlinkQueryInteger_2 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type DirectoryPrettySizeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryRdevQueryInteger_2 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type DirectoryRelativeDirectoryQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryRelativePathQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryRootQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectorySizeQueryInteger_2 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type DirectorySourceInstanceNameQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type DirectoryUidQueryInteger_2 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type DuotoneGradient = { highlight?: Maybe<Scalars['String']>; shadow?: Maybe<Scalars['String']>; opacity?: Maybe<Scalars['Int']>; }; export type Ever = { adminByEmail?: Maybe<Ever_Admin>; admin?: Maybe<Ever_Admin>; adminAuthenticated: Scalars['Boolean']; getCarrierByUsername?: Maybe<Ever_Carrier>; getCarrier?: Maybe<Ever_Carrier>; getCarriers: Array<Ever_Carrier>; getActiveCarriers: Array<Maybe<Ever_Carrier>>; getCountOfCarriers: Scalars['Int']; getCarrierOrders: Array<Ever_CarrierOrder>; getCarrierCurrentOrder?: Maybe<Ever_Order>; getCarrierOrdersHistory: Array<Maybe<Ever_Order>>; getCountOfCarrierOrdersHistory: Scalars['Int']; currencies?: Maybe<Array<Maybe<Ever_Currency>>>; clearAll: Scalars['Boolean']; device?: Maybe<Ever_Device>; devices: Array<Ever_Device>; geoLocationProducts?: Maybe<Array<Maybe<Ever_ProductInfo>>>; geoLocationProductsByPaging: Array<Maybe<Ever_ProductInfo>>; getCountOfGeoLocationProducts: Scalars['Int']; invite?: Maybe<Ever_Invite>; invites: Array<Ever_Invite>; getInviteByCode?: Maybe<Ever_Invite>; getInviteByLocation?: Maybe<Ever_Invite>; generate1000InvitesConnectedToInviteRequests?: Maybe<Scalars['Ever_Void']>; getCountOfInvites: Scalars['Int']; inviteRequest?: Maybe<Ever_InviteRequest>; invitesRequests?: Maybe<Array<Ever_InviteRequest>>; notifyAboutLaunch?: Maybe<Scalars['Ever_Void']>; generate1000InviteRequests?: Maybe<Scalars['Ever_Void']>; getCountOfInvitesRequests: Scalars['Int']; getOrder?: Maybe<Ever_Order>; orders: Array<Ever_Order>; getDashboardCompletedOrders: Array<Ever_DashboardCompletedOrder>; getDashboardCompletedOrdersToday: Array<Ever_Order>; getOrdersChartTotalOrders: Array<Ever_OrderChartPanel>; getCompletedOrdersInfo: Ever_CompletedOrderInfo; getOrderedUsersInfo: Array<Ever_OrderedUserInfo>; generateOrdersByCustomerId?: Maybe<Scalars['Ever_Void']>; addTakenOrders?: Maybe<Scalars['Ever_Void']>; addOrdersToTake?: Maybe<Scalars['Ever_Void']>; generateActiveAndAvailableOrdersPerCarrier?: Maybe<Scalars['Ever_Void']>; generatePastOrdersPerCarrier?: Maybe<Scalars['Ever_Void']>; getUsersOrdersCountInfo?: Maybe<Array<Maybe<Ever_OrderCountTnfo>>>; getMerchantsOrdersCountInfo?: Maybe<Array<Maybe<Ever_OrderCountTnfo>>>; generateRandomOrdersCurrentStore: Ever_GenerateOrdersResponse; product?: Maybe<Ever_Product>; products?: Maybe<Array<Ever_Product>>; getCountOfProducts: Scalars['Int']; user?: Maybe<Ever_User>; users: Array<Maybe<Ever_User>>; getOrders: Array<Ever_Order>; isUserExists: Scalars['Boolean']; getSocial?: Maybe<Ever_User>; isUserEmailExists: Scalars['Boolean']; generate1000Customers?: Maybe<Ever_ResponseGenerate1000Customers>; getCountOfUsers: Scalars['Int']; getCustomerMetrics?: Maybe<Ever_CustomerMetrics>; warehouse?: Maybe<Ever_Warehouse>; warehouses: Array<Maybe<Ever_Warehouse>>; nearbyStores: Array<Ever_Warehouse>; countStoreCustomers: Scalars['Int']; getAllActiveStores: Array<Ever_Warehouse>; getStoreCustomers: Array<Ever_User>; getStoreProducts: Array<Ever_WarehouseProduct>; getStoreAvailableProducts: Array<Ever_WarehouseProduct>; getCountExistingCustomers: Ever_ExistingCustomersByStores; getCountExistingCustomersToday: Ever_ExistingCustomersByStores; hasExistingStores: Scalars['Boolean']; getCountOfMerchants: Scalars['Int']; getAllStores: Array<Ever_Warehouse>; getMerchantsBuyName: Array<Maybe<Ever_Warehouse>>; getStoreCarriers?: Maybe<Array<Ever_Carrier>>; getStoreOrders: Array<Ever_Order>; getNextOrderNumber: Scalars['Int']; getDashboardOrdersChartOrders: Array<Ever_Order>; getMerchantsOrders?: Maybe<Array<Maybe<Ever_MerchantsOrders>>>; getStoreOrdersTableData: Ever_StoreOrdersTableData; getCountOfStoreOrders: Scalars['Int']; getOrdersInDelivery: Array<Maybe<Ever_Order>>; removeUserOrders?: Maybe<Ever_RemovedUserOrdersObj>; getProductsWithPagination?: Maybe<Array<Ever_WarehouseProduct>>; getProductsCount?: Maybe<Scalars['Int']>; getWarehouseProduct?: Maybe<Ever_WarehouseProduct>; getCoseMerchants: Array<Maybe<Ever_Warehouse>>; getOrderForWork?: Maybe<Ever_Order>; getOrdersForWork: Array<Maybe<Ever_Order>>; getCountOfOrdersForWork: Scalars['Int']; productsCategory?: Maybe<Ever_ProductsCategory>; productsCategories: Array<Ever_ProductsCategory>; temp__?: Maybe<Scalars['Boolean']>; }; export type EverAdminByEmailArgs = { email: Scalars['String']; }; export type EverAdminArgs = { id: Scalars['String']; }; export type EverGetCarrierByUsernameArgs = { username: Scalars['String']; }; export type EverGetCarrierArgs = { id: Scalars['String']; }; export type EverGetCarriersArgs = { carriersFindInput?: Maybe<Ever_CarriersFindInput>; pagingOptions?: Maybe<Ever_PagingOptionsInput>; }; export type EverGetCountOfCarriersArgs = { carriersFindInput?: Maybe<Ever_CarriersFindInput>; }; export type EverGetCarrierOrdersArgs = { carrierId: Scalars['String']; options?: Maybe<Ever_CarrierOrdersOptions>; }; export type EverGetCarrierCurrentOrderArgs = { carrierId: Scalars['String']; }; export type EverGetCarrierOrdersHistoryArgs = { carrierId: Scalars['String']; options?: Maybe<Ever_GeoLocationOrdersOptions>; }; export type EverGetCountOfCarrierOrdersHistoryArgs = { carrierId: Scalars['String']; }; export type EverDeviceArgs = { id?: Maybe<Scalars['String']>; }; export type EverDevicesArgs = { findInput?: Maybe<Ever_DeviceFindInput>; }; export type EverGeoLocationProductsArgs = { geoLocation: Ever_GeoLocationFindInput; }; export type EverGeoLocationProductsByPagingArgs = { geoLocation: Ever_GeoLocationFindInput; pagingOptions?: Maybe<Ever_PagingOptionsInput>; options?: Maybe<Ever_GetGeoLocationProductsOptions>; searchText?: Maybe<Scalars['String']>; }; export type EverGetCountOfGeoLocationProductsArgs = { geoLocation: Ever_GeoLocationFindInput; options?: Maybe<Ever_GetGeoLocationProductsOptions>; searchText?: Maybe<Scalars['String']>; }; export type EverInviteArgs = { id: Scalars['String']; }; export type EverInvitesArgs = { findInput?: Maybe<Ever_InvitesFindInput>; pagingOptions?: Maybe<Ever_PagingOptionsInput>; }; export type EverGetInviteByCodeArgs = { info: Ever_InviteByCodeInput; }; export type EverGetInviteByLocationArgs = { info?: Maybe<Ever_InviteByLocationInput>; }; export type EverGenerate1000InvitesConnectedToInviteRequestsArgs = { defaultLng: Scalars['Float']; defaultLat: Scalars['Float']; }; export type EverInviteRequestArgs = { id: Scalars['String']; }; export type EverInvitesRequestsArgs = { findInput?: Maybe<Ever_InvitesRequestsFindInput>; pagingOptions?: Maybe<Ever_PagingOptionsInput>; invited?: Maybe<Scalars['Boolean']>; }; export type EverNotifyAboutLaunchArgs = { invite?: Maybe<Ever_InviteInput>; devicesIds: Array<Scalars['String']>; }; export type EverGenerate1000InviteRequestsArgs = { defaultLng: Scalars['Float']; defaultLat: Scalars['Float']; }; export type EverGetCountOfInvitesRequestsArgs = { invited?: Maybe<Scalars['Boolean']>; }; export type EverGetOrderArgs = { id: Scalars['String']; }; export type EverOrdersArgs = { findInput?: Maybe<Ever_OrdersFindInput>; }; export type EverGetCompletedOrdersInfoArgs = { storeId?: Maybe<Scalars['String']>; }; export type EverGetOrderedUsersInfoArgs = { storeId: Scalars['String']; }; export type EverGenerateOrdersByCustomerIdArgs = { numberOfOrders: Scalars['Int']; customerId: Scalars['String']; }; export type EverAddTakenOrdersArgs = { carrierIds: Array<Scalars['String']>; }; export type EverGetUsersOrdersCountInfoArgs = { usersIds?: Maybe<Array<Scalars['String']>>; }; export type EverGetMerchantsOrdersCountInfoArgs = { merchantsIds?: Maybe<Array<Scalars['String']>>; }; export type EverGenerateRandomOrdersCurrentStoreArgs = { storeId: Scalars['String']; storeCreatedAt: Scalars['Ever_Date']; ordersLimit: Scalars['Int']; }; export type EverProductArgs = { id: Scalars['String']; }; export type EverProductsArgs = { findInput?: Maybe<Ever_ProductsFindInput>; pagingOptions?: Maybe<Ever_PagingOptionsInput>; existedProductsIds?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type EverGetCountOfProductsArgs = { existedProductsIds?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type EverUserArgs = { id: Scalars['String']; }; export type EverUsersArgs = { findInput?: Maybe<Ever_UserFindInput>; pagingOptions?: Maybe<Ever_PagingOptionsInput>; }; export type EverGetOrdersArgs = { userId: Scalars['String']; }; export type EverIsUserExistsArgs = { conditions: Ever_UserMemberInput; }; export type EverGetSocialArgs = { socialId: Scalars['String']; }; export type EverIsUserEmailExistsArgs = { email: Scalars['String']; }; export type EverGenerate1000CustomersArgs = { defaultLng: Scalars['Float']; defaultLat: Scalars['Float']; }; export type EverGetCustomerMetricsArgs = { id: Scalars['String']; }; export type EverWarehouseArgs = { id: Scalars['String']; }; export type EverWarehousesArgs = { findInput?: Maybe<Ever_WarehousesFindInput>; pagingOptions?: Maybe<Ever_PagingOptionsInput>; }; export type EverNearbyStoresArgs = { geoLocation: Ever_GeoLocationFindInput; }; export type EverCountStoreCustomersArgs = { storeId: Scalars['String']; }; export type EverGetAllActiveStoresArgs = { fullProducts: Scalars['Boolean']; }; export type EverGetStoreCustomersArgs = { storeId: Scalars['String']; }; export type EverGetStoreProductsArgs = { storeId: Scalars['String']; fullProducts: Scalars['Boolean']; }; export type EverGetStoreAvailableProductsArgs = { storeId: Scalars['String']; }; export type EverGetMerchantsBuyNameArgs = { searchName: Scalars['String']; geoLocation?: Maybe<Ever_GeoLocationFindInput>; }; export type EverGetStoreCarriersArgs = { storeId: Scalars['String']; }; export type EverGetStoreOrdersArgs = { storeId: Scalars['String']; }; export type EverGetNextOrderNumberArgs = { storeId: Scalars['String']; }; export type EverGetDashboardOrdersChartOrdersArgs = { storeId: Scalars['String']; }; export type EverGetStoreOrdersTableDataArgs = { storeId: Scalars['String']; pagingOptions?: Maybe<Ever_PagingOptionsInput>; status?: Maybe<Scalars['String']>; }; export type EverGetCountOfStoreOrdersArgs = { storeId: Scalars['String']; status: Scalars['String']; }; export type EverGetOrdersInDeliveryArgs = { storeId: Scalars['String']; }; export type EverRemoveUserOrdersArgs = { storeId: Scalars['String']; userId: Scalars['String']; }; export type EverGetProductsWithPaginationArgs = { id: Scalars['String']; pagingOptions?: Maybe<Ever_PagingOptionsInput>; }; export type EverGetProductsCountArgs = { id: Scalars['String']; }; export type EverGetWarehouseProductArgs = { warehouseId: Scalars['String']; warehouseProductId: Scalars['String']; }; export type EverGetCoseMerchantsArgs = { geoLocation: Ever_GeoLocationFindInput; }; export type EverGetOrderForWorkArgs = { geoLocation: Ever_GeoLocationFindInput; skippedOrderIds: Array<Scalars['String']>; options?: Maybe<Ever_GeoLocationOrdersOptions>; searchObj?: Maybe<Ever_SearchOrdersForWork>; }; export type EverGetOrdersForWorkArgs = { geoLocation: Ever_GeoLocationFindInput; skippedOrderIds: Array<Scalars['String']>; options?: Maybe<Ever_GeoLocationOrdersOptions>; searchObj?: Maybe<Ever_SearchOrdersForWork>; }; export type EverGetCountOfOrdersForWorkArgs = { geoLocation: Ever_GeoLocationFindInput; skippedOrderIds: Array<Scalars['String']>; searchObj?: Maybe<Ever_SearchOrdersForWork>; }; export type EverProductsCategoryArgs = { id: Scalars['String']; }; export type EverProductsCategoriesArgs = { findInput?: Maybe<Ever_ProductsCategoriesFindInput>; }; export type Ever_AdditionalUserRegistrationInfo = { email: Scalars['String']; password: Scalars['String']; firstName?: Maybe<Scalars['String']>; lastName?: Maybe<Scalars['String']>; phone?: Maybe<Scalars['String']>; }; export type Ever_Admin = { _id: Scalars['String']; id: Scalars['String']; name: Scalars['String']; email: Scalars['String']; pictureUrl: Scalars['String']; firstName?: Maybe<Scalars['String']>; lastName?: Maybe<Scalars['String']>; }; export type Ever_AdminCreateInput = { name: Scalars['String']; email: Scalars['String']; pictureUrl: Scalars['String']; firstName?: Maybe<Scalars['String']>; lastName?: Maybe<Scalars['String']>; }; export type Ever_AdminLoginInfo = { admin: Ever_Admin; token: Scalars['String']; }; export type Ever_AdminPasswordUpdateInput = { current: Scalars['String']; new: Scalars['String']; }; export type Ever_AdminRegisterInput = { admin: Ever_AdminCreateInput; password: Scalars['String']; }; export type Ever_AdminUpdateInput = { name?: Maybe<Scalars['String']>; email?: Maybe<Scalars['String']>; pictureUrl?: Maybe<Scalars['String']>; firstName?: Maybe<Scalars['String']>; lastName?: Maybe<Scalars['String']>; }; export type Ever_Carrier = { _id: Scalars['String']; id: Scalars['String']; firstName: Scalars['String']; lastName: Scalars['String']; username: Scalars['String']; phone: Scalars['String']; logo: Scalars['String']; email?: Maybe<Scalars['String']>; numberOfDeliveries: Scalars['Int']; skippedOrderIds?: Maybe<Array<Scalars['String']>>; status: Scalars['Int']; geoLocation: Ever_GeoLocation; devicesIds: Array<Scalars['String']>; apartment?: Maybe<Scalars['String']>; isActive?: Maybe<Scalars['Boolean']>; isSharedCarrier?: Maybe<Scalars['Boolean']>; devices: Array<Ever_Device>; isDeleted: Scalars['Boolean']; }; export type Ever_CarrierCreateInput = { email?: Maybe<Scalars['String']>; firstName: Scalars['String']; lastName: Scalars['String']; geoLocation: Ever_GeoLocationCreateInput; status?: Maybe<Scalars['Int']>; username: Scalars['String']; password: Scalars['String']; phone: Scalars['String']; logo: Scalars['String']; numberOfDeliveries?: Maybe<Scalars['Int']>; skippedOrderIds?: Maybe<Array<Scalars['String']>>; deliveriesCountToday?: Maybe<Scalars['Int']>; totalDistanceToday?: Maybe<Scalars['Float']>; isSharedCarrier?: Maybe<Scalars['Boolean']>; devicesIds?: Maybe<Array<Scalars['String']>>; isDeleted?: Maybe<Scalars['Boolean']>; }; export type Ever_CarrierLoginInfo = { carrier: Ever_Carrier; token: Scalars['String']; }; export type Ever_CarrierOrder = { _id: Scalars['String']; id: Scalars['String']; isConfirmed: Scalars['Boolean']; isCancelled: Scalars['Boolean']; isPaid: Scalars['Boolean']; warehouseStatus: Scalars['Int']; carrierStatus: Scalars['Int']; orderNumber: Scalars['Int']; _createdAt?: Maybe<Scalars['Ever_Date']>; user: Ever_CarrierOrderUser; warehouse: Ever_CarrierOrderWarehouse; carrier: Ever_CarrierOrderCarrier; products: Array<Ever_CarrierOrderProducts>; }; export type Ever_CarrierOrderCarrier = { id: Scalars['String']; }; export type Ever_CarrierOrderProducts = { count: Scalars['Int']; isManufacturing: Scalars['Boolean']; isCarrierRequired: Scalars['Boolean']; isDeliveryRequired: Scalars['Boolean']; isTakeaway?: Maybe<Scalars['Boolean']>; initialPrice: Scalars['Float']; price: Scalars['Float']; product: Ever_CarrierOrderProductsProduct; }; export type Ever_CarrierOrderProductsProduct = { _id: Scalars['String']; id: Scalars['String']; title: Array<Ever_TranslateType>; description: Array<Ever_TranslateType>; details: Array<Ever_TranslateType>; images: Array<Ever_ImageType>; categories?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type Ever_CarrierOrdersOptions = { populateWarehouse: Scalars['Boolean']; completion: Scalars['String']; }; export type Ever_CarrierOrderUser = { _id: Scalars['String']; firstName?: Maybe<Scalars['String']>; lastName?: Maybe<Scalars['String']>; geoLocation: Ever_GeoLocation; }; export type Ever_CarrierOrderWarehouse = { logo: Scalars['String']; name: Scalars['String']; geoLocation: Ever_GeoLocation; }; export type Ever_CarrierPasswordUpdateInput = { current: Scalars['String']; new: Scalars['String']; }; export type Ever_CarrierRegisterInput = { carrier: Ever_CarrierCreateInput; password: Scalars['String']; }; export type Ever_CarriersFindInput = { firstName?: Maybe<Scalars['String']>; lastName?: Maybe<Scalars['String']>; email?: Maybe<Scalars['String']>; phone?: Maybe<Scalars['String']>; isDeleted?: Maybe<Scalars['Boolean']>; status?: Maybe<Scalars['Int']>; isSharedCarrier?: Maybe<Scalars['Boolean']>; _id?: Maybe<Scalars['Ever_Any']>; }; export enum Ever_CarrierStatus { Online = 'Online', Offline = 'Offline', Blocked = 'Blocked', } export type Ever_CarrierUpdateInput = { firstName?: Maybe<Scalars['String']>; lastName?: Maybe<Scalars['String']>; geoLocation?: Maybe<Ever_GeoLocationUpdateInput>; status?: Maybe<Scalars['Int']>; username?: Maybe<Scalars['String']>; phone?: Maybe<Scalars['String']>; email?: Maybe<Scalars['String']>; logo?: Maybe<Scalars['String']>; numberOfDeliveries?: Maybe<Scalars['Int']>; skippedOrderIds?: Maybe<Array<Scalars['String']>>; deliveriesCountToday?: Maybe<Scalars['Int']>; totalDistanceToday?: Maybe<Scalars['Float']>; devicesIds?: Maybe<Array<Scalars['String']>>; isSharedCarrier?: Maybe<Scalars['Boolean']>; isActive?: Maybe<Scalars['Boolean']>; }; export type Ever_Category = { id?: Maybe<Scalars['String']>; name: Array<Ever_TranslateType>; }; export type Ever_CompletedOrderInfo = { totalOrders: Scalars['Int']; totalRevenue: Scalars['Float']; }; export type Ever_Currency = { _id: Scalars['String']; currencyCode: Scalars['String']; }; export type Ever_CurrencyCreateInput = { currencyCode: Scalars['String']; }; export type Ever_CustomerMetrics = { totalOrders?: Maybe<Scalars['Int']>; canceledOrders?: Maybe<Scalars['Int']>; completedOrdersTotalSum?: Maybe<Scalars['Float']>; }; export type Ever_CustomersByStore = { storeId: Scalars['String']; customersCount: Scalars['Int']; }; export type Ever_DashboardCompletedOrder = { warehouseId: Scalars['String']; totalPrice: Scalars['Float']; }; export type Ever_Device = { _id: Scalars['String']; id: Scalars['String']; channelId?: Maybe<Scalars['String']>; type: Scalars['String']; uuid: Scalars['String']; language?: Maybe<Scalars['String']>; }; export type Ever_DeviceCreateInput = { channelId: Scalars['String']; language?: Maybe<Scalars['String']>; type: Scalars['String']; uuid: Scalars['String']; }; export type Ever_DeviceFindInput = { channelId?: Maybe<Scalars['String']>; language?: Maybe<Scalars['String']>; type?: Maybe<Scalars['String']>; uuid?: Maybe<Scalars['String']>; }; export type Ever_DeviceUpdateInput = { channelId?: Maybe<Scalars['String']>; language?: Maybe<Scalars['String']>; type?: Maybe<Scalars['String']>; uuid?: Maybe<Scalars['String']>; }; export type Ever_ExistingCustomersByStores = { total: Scalars['Int']; perStore: Array<Ever_CustomersByStore>; }; export type Ever_GenerateOrdersResponse = { error: Scalars['Boolean']; message?: Maybe<Scalars['String']>; }; export type Ever_GeoLocation = { _id?: Maybe<Scalars['String']>; id?: Maybe<Scalars['String']>; _createdAt?: Maybe<Scalars['Ever_Date']>; createdAt?: Maybe<Scalars['Ever_Date']>; _updatedAt?: Maybe<Scalars['Ever_Date']>; updatedAt?: Maybe<Scalars['Ever_Date']>; countryId: Scalars['Int']; countryName?: Maybe<Scalars['String']>; city: Scalars['String']; streetAddress: Scalars['String']; house: Scalars['String']; postcode?: Maybe<Scalars['String']>; loc: Ever_Loc; coordinates: Ever_GeoLocationCoordinates; }; export type Ever_GeoLocationCoordinates = { lng: Scalars['Float']; lat: Scalars['Float']; }; export type Ever_GeoLocationCreateInput = { countryId: Scalars['Int']; city: Scalars['String']; streetAddress: Scalars['String']; house: Scalars['String']; postcode?: Maybe<Scalars['String']>; loc: Ever_LocInput; }; export type Ever_GeoLocationCreateObject = { loc: Ever_Location; countryId: Scalars['Int']; city: Scalars['String']; postcode: Scalars['String']; streetAddress: Scalars['String']; house: Scalars['String']; }; export type Ever_GeoLocationFindInput = { countryId?: Maybe<Scalars['Int']>; city?: Maybe<Scalars['String']>; streetAddress?: Maybe<Scalars['String']>; house?: Maybe<Scalars['String']>; postcode?: Maybe<Scalars['String']>; loc?: Maybe<Ever_LocInput>; }; export type Ever_GeoLocationInput = { countryId: Scalars['Int']; countryName?: Maybe<Scalars['String']>; city: Scalars['String']; streetAddress: Scalars['String']; house: Scalars['String']; postcode?: Maybe<Scalars['String']>; loc: Ever_Location; }; export type Ever_GeoLocationOrdersOptions = { sort?: Maybe<Scalars['String']>; limit?: Maybe<Scalars['Int']>; skip?: Maybe<Scalars['Int']>; }; export type Ever_GeoLocationUpdateInput = { countryId?: Maybe<Scalars['Int']>; city?: Maybe<Scalars['String']>; streetAddress?: Maybe<Scalars['String']>; house?: Maybe<Scalars['String']>; postcode?: Maybe<Scalars['String']>; loc?: Maybe<Ever_LocInput>; }; export type Ever_GeoLocationUpdateObjectInput = { loc: Ever_Location; }; export type Ever_GetGeoLocationProductsOptions = { isDeliveryRequired?: Maybe<Scalars['Boolean']>; isTakeaway?: Maybe<Scalars['Boolean']>; merchantIds?: Maybe<Array<Maybe<Scalars['String']>>>; imageOrientation?: Maybe<Scalars['Int']>; locale?: Maybe<Scalars['String']>; withoutCount?: Maybe<Scalars['Boolean']>; }; export type Ever_ImageInput = { locale: Scalars['String']; url: Scalars['String']; width: Scalars['Int']; height: Scalars['Int']; orientation: Scalars['Int']; }; export type Ever_ImageType = { locale: Scalars['String']; url: Scalars['String']; width: Scalars['Int']; height: Scalars['Int']; orientation: Scalars['Int']; }; export type Ever_Invite = { _id: Scalars['String']; id: Scalars['String']; code: Scalars['String']; apartment: Scalars['String']; geoLocation: Ever_GeoLocation; }; export type Ever_InviteByCodeInput = { location: Ever_Location; inviteCode: Scalars['String']; firstName?: Maybe<Scalars['String']>; lastName?: Maybe<Scalars['String']>; }; export type Ever_InviteByLocationInput = { countryId: Scalars['Int']; city: Scalars['String']; streetAddress: Scalars['String']; house: Scalars['String']; apartment: Scalars['String']; postcode?: Maybe<Scalars['String']>; }; export type Ever_InviteCreateInput = { code?: Maybe<Scalars['String']>; apartment: Scalars['String']; geoLocation: Ever_GeoLocationCreateInput; }; export type Ever_InviteInput = { code: Scalars['String']; apartment: Scalars['String']; geoLocation: Ever_GeoLocationInput; isDeleted: Scalars['Boolean']; }; export type Ever_InviteRequest = { _id: Scalars['String']; id: Scalars['String']; apartment: Scalars['String']; geoLocation: Ever_GeoLocation; isManual?: Maybe<Scalars['Boolean']>; isInvited?: Maybe<Scalars['Boolean']>; invitedDate?: Maybe<Scalars['Ever_Date']>; }; export type Ever_InviteRequestCreateInput = { apartment: Scalars['String']; geoLocation: Ever_GeoLocationCreateInput; isManual?: Maybe<Scalars['Boolean']>; invitedDate?: Maybe<Scalars['Ever_Date']>; isInvited?: Maybe<Scalars['Boolean']>; }; export type Ever_InviteRequestUpdateInput = { apartment?: Maybe<Scalars['String']>; geoLocation?: Maybe<Ever_GeoLocationUpdateInput>; isManual?: Maybe<Scalars['Boolean']>; invitedDate?: Maybe<Scalars['Ever_Date']>; isInvited?: Maybe<Scalars['Boolean']>; }; export type Ever_InvitesFindInput = { code?: Maybe<Scalars['String']>; apartment?: Maybe<Scalars['String']>; }; export type Ever_InvitesRequestsFindInput = { apartment?: Maybe<Scalars['String']>; isManual?: Maybe<Scalars['Boolean']>; isInvited?: Maybe<Scalars['Boolean']>; invitedDate?: Maybe<Scalars['Ever_Date']>; }; export type Ever_InviteUpdateInput = { code?: Maybe<Scalars['String']>; apartment?: Maybe<Scalars['String']>; geoLocation?: Maybe<Ever_GeoLocationUpdateInput>; }; export enum Ever_Language { He_Il = 'he_IL', En_Us = 'en_US', Ru_Ru = 'ru_RU', Bg_Bg = 'bg_BG', } export type Ever_Loc = { type: Scalars['String']; coordinates: Array<Scalars['Float']>; }; export type Ever_Location = { type: Scalars['String']; coordinates: Array<Scalars['Float']>; }; export type Ever_LocInput = { type: Scalars['String']; coordinates: Array<Scalars['Float']>; }; export type Ever_MerchantsOrders = { _id?: Maybe<Scalars['String']>; ordersCount?: Maybe<Scalars['Int']>; }; export type Ever_MutationResponse = { success: Scalars['Boolean']; message?: Maybe<Scalars['String']>; data?: Maybe<Ever_Currency>; }; export type Ever_Order = { _id: Scalars['String']; id: Scalars['String']; user: Ever_User; warehouse: Ever_Warehouse; warehouseId: Scalars['String']; carrier?: Maybe<Ever_Carrier>; carrierId?: Maybe<Scalars['String']>; products: Array<Ever_OrderProduct>; isConfirmed: Scalars['Boolean']; isCancelled: Scalars['Boolean']; isPaid: Scalars['Boolean']; isCompleted: Scalars['Boolean']; totalPrice: Scalars['Float']; orderType?: Maybe<Scalars['Int']>; deliveryTime?: Maybe<Scalars['Ever_Date']>; finishedProcessingTime?: Maybe<Scalars['Ever_Date']>; startDeliveryTime?: Maybe<Scalars['Ever_Date']>; deliveryTimeEstimate?: Maybe<Scalars['Int']>; warehouseStatus: Scalars['Int']; carrierStatus: Scalars['Int']; orderNumber: Scalars['Int']; carrierStatusText: Scalars['String']; warehouseStatusText: Scalars['String']; status?: Maybe<Scalars['Int']>; createdAt?: Maybe<Scalars['Ever_Date']>; _createdAt?: Maybe<Scalars['Ever_Date']>; updatedAt?: Maybe<Scalars['Ever_Date']>; _updatedAt?: Maybe<Scalars['Ever_Date']>; }; export enum Ever_OrderCarrierStatus { NoCarrier = 'NoCarrier', CarrierSelectedOrder = 'CarrierSelectedOrder', CarrierPickedUpOrder = 'CarrierPickedUpOrder', CarrierStartDelivery = 'CarrierStartDelivery', CarrierArrivedToCustomer = 'CarrierArrivedToCustomer', DeliveryCompleted = 'DeliveryCompleted', IssuesDuringDelivery = 'IssuesDuringDelivery', ClientRefuseTakingOrder = 'ClientRefuseTakingOrder', } export type Ever_OrderChartPanel = { isCancelled: Scalars['Boolean']; isCompleted: Scalars['Boolean']; totalPrice: Scalars['Float']; _createdAt: Scalars['Ever_Date']; }; export type Ever_OrderCountTnfo = { id?: Maybe<Scalars['String']>; ordersCount?: Maybe<Scalars['Int']>; }; export type Ever_OrderCreateInput = { userId: Scalars['String']; warehouseId: Scalars['String']; products: Array<Ever_OrderProductCreateInput>; options?: Maybe<Ever_WarehouseOrdersRouterCreateOptions>; }; export type Ever_OrderedUserInfo = { user: Ever_User; ordersCount: Scalars['Int']; totalPrice: Scalars['Float']; }; export type Ever_OrderProduct = { _id: Scalars['String']; count: Scalars['Int']; isManufacturing: Scalars['Boolean']; isCarrierRequired: Scalars['Boolean']; isDeliveryRequired: Scalars['Boolean']; isTakeaway?: Maybe<Scalars['Boolean']>; initialPrice: Scalars['Float']; price: Scalars['Float']; product: Ever_Product; }; export type Ever_OrderProductCreateInput = { count: Scalars['Int']; productId: Scalars['String']; }; export type Ever_OrdersFindInput = { user?: Maybe<Scalars['String']>; warehouse?: Maybe<Scalars['String']>; carrier?: Maybe<Scalars['String']>; isConfirmed?: Maybe<Scalars['Boolean']>; isCancelled?: Maybe<Scalars['Boolean']>; isPaid?: Maybe<Scalars['Boolean']>; warehouseStatus: Scalars['Int']; carrierStatus: Scalars['Int']; orderNumber?: Maybe<Scalars['Int']>; }; export enum Ever_OrderWarehouseStatus { NoStatus = 'NoStatus', ReadyForProcessing = 'ReadyForProcessing', WarehouseStartedProcessing = 'WarehouseStartedProcessing', AllocationStarted = 'AllocationStarted', AllocationFinished = 'AllocationFinished', PackagingStarted = 'PackagingStarted', PackagingFinished = 'PackagingFinished', GivenToCarrier = 'GivenToCarrier', AllocationFailed = 'AllocationFailed', PackagingFailed = 'PackagingFailed', } export type Ever_PagingOptionsInput = { sort?: Maybe<Ever_PagingSortInput>; limit?: Maybe<Scalars['Int']>; skip?: Maybe<Scalars['Int']>; }; export type Ever_PagingSortInput = { field: Scalars['String']; sortBy: Scalars['String']; }; export type Ever_Product = { _id: Scalars['String']; id: Scalars['String']; title: Array<Ever_TranslateType>; description: Array<Ever_TranslateType>; details: Array<Ever_TranslateType>; images: Array<Ever_ImageType>; categories?: Maybe<Array<Maybe<Scalars['String']>>>; detailsHTML: Array<Ever_TranslateType>; descriptionHTML: Array<Ever_TranslateType>; _createdAt?: Maybe<Scalars['Ever_Date']>; _updatedAt?: Maybe<Scalars['Ever_Date']>; }; export type Ever_ProductCreateInput = { title: Array<Ever_TranslateInput>; description: Array<Ever_TranslateInput>; details?: Maybe<Array<Ever_TranslateInput>>; images: Array<Ever_ImageInput>; categories?: Maybe<Array<Ever_ProductsCategoryInput>>; detailsHTML?: Maybe<Array<Ever_TranslateInput>>; descriptionHTML?: Maybe<Array<Ever_TranslateInput>>; }; export type Ever_ProductInfo = { warehouseProduct: Ever_WarehouseProduct; distance: Scalars['Float']; warehouseId: Scalars['String']; warehouseLogo: Scalars['String']; }; export type Ever_ProductSaveInput = { _id: Scalars['String']; id?: Maybe<Scalars['String']>; title: Array<Ever_TranslateInput>; description: Array<Ever_TranslateInput>; details?: Maybe<Array<Ever_TranslateInput>>; images: Array<Ever_ImageInput>; categories?: Maybe<Array<Ever_ProductsCategoryInput>>; detailsHTML?: Maybe<Array<Ever_TranslateInput>>; descriptionHTML?: Maybe<Array<Ever_TranslateInput>>; }; export type Ever_ProductsCategoriesCreateInput = { name: Array<Ever_TranslateInput>; image?: Maybe<Scalars['String']>; }; export type Ever_ProductsCategoriesFindInput = { noop?: Maybe<Scalars['Ever_Void']>; }; export type Ever_ProductsCategoriesUpdatenput = { name?: Maybe<Array<Ever_TranslateInput>>; }; export type Ever_ProductsCategory = { _id: Scalars['String']; id: Scalars['String']; name: Array<Ever_TranslateType>; image?: Maybe<Scalars['String']>; _createdAt?: Maybe<Scalars['Ever_Date']>; _updatedAt?: Maybe<Scalars['Ever_Date']>; }; export type Ever_ProductsCategoryInput = { _id: Scalars['String']; name?: Maybe<Array<Ever_TranslateInput>>; }; export type Ever_ProductsFindInput = { title?: Maybe<Ever_TranslateInput>; description?: Maybe<Ever_TranslateInput>; details?: Maybe<Ever_TranslateInput>; image?: Maybe<Ever_ImageInput>; }; export type Ever_QuantityUpdateInput = { change?: Maybe<Scalars['Int']>; to?: Maybe<Scalars['Int']>; }; export type Ever_Remove = { n?: Maybe<Scalars['Int']>; ok?: Maybe<Scalars['Int']>; }; export type Ever_RemovedUserOrdersObj = { number?: Maybe<Scalars['Int']>; modified?: Maybe<Scalars['Int']>; }; export type Ever_ResponseGenerate1000Customers = { success: Scalars['Boolean']; message?: Maybe<Scalars['String']>; }; export type Ever_SearchByRegex = { key: Scalars['String']; value: Scalars['String']; }; export type Ever_SearchOrdersForWork = { byRegex?: Maybe<Array<Maybe<Ever_SearchByRegex>>>; }; export type Ever_StoreOrdersTableData = { orders: Array<Maybe<Ever_Order>>; page: Scalars['Int']; }; export type Ever_TranslateInput = { locale: Scalars['String']; value: Scalars['String']; }; export type Ever_TranslateType = { locale: Scalars['String']; value: Scalars['String']; }; export type Ever_User = { _id: Scalars['String']; id: Scalars['String']; geoLocation: Ever_GeoLocation; apartment: Scalars['String']; firstName?: Maybe<Scalars['String']>; lastName?: Maybe<Scalars['String']>; email?: Maybe<Scalars['String']>; phone?: Maybe<Scalars['String']>; devicesIds: Array<Scalars['String']>; devices: Array<Ever_Device>; image?: Maybe<Scalars['String']>; fullAddress?: Maybe<Scalars['String']>; createdAt?: Maybe<Scalars['Ever_Date']>; isBanned: Scalars['Boolean']; }; export type Ever_UserCreateInput = { email?: Maybe<Scalars['String']>; firstName?: Maybe<Scalars['String']>; lastName?: Maybe<Scalars['String']>; phone?: Maybe<Scalars['String']>; image?: Maybe<Scalars['String']>; geoLocation: Ever_GeoLocationCreateInput; apartment: Scalars['String']; }; export type Ever_UserFindInput = { firstName?: Maybe<Scalars['String']>; lastName?: Maybe<Scalars['String']>; email?: Maybe<Scalars['String']>; phone?: Maybe<Scalars['String']>; apartment?: Maybe<Scalars['String']>; image?: Maybe<Scalars['String']>; }; export type Ever_UserLoginInfo = { user: Ever_User; token: Scalars['String']; }; export type Ever_UserMemberInput = { exceptCustomerId?: Maybe<Scalars['String']>; memberKey: Scalars['String']; memberValue: Scalars['String']; }; export type Ever_UserPasswordUpdateInput = { current: Scalars['String']; new: Scalars['String']; }; export type Ever_UserRegisterInput = { user: Ever_UserCreateInput; password?: Maybe<Scalars['String']>; }; export type Ever_UserUpdateObjectInput = { geoLocation: Ever_GeoLocationUpdateObjectInput; devicesIds?: Maybe<Array<Scalars['String']>>; apartment?: Maybe<Scalars['String']>; stripeCustomerId?: Maybe<Scalars['String']>; }; export type Ever_Warehouse = { _id: Scalars['String']; id: Scalars['String']; _createdAt: Scalars['Ever_Date']; isActive: Scalars['Boolean']; isPaymentEnabled?: Maybe<Scalars['Boolean']>; geoLocation: Ever_GeoLocation; name: Scalars['String']; logo: Scalars['String']; username: Scalars['String']; contactEmail?: Maybe<Scalars['String']>; contactPhone?: Maybe<Scalars['String']>; forwardOrdersUsing?: Maybe<Array<Scalars['Int']>>; ordersEmail?: Maybe<Scalars['String']>; ordersPhone?: Maybe<Scalars['String']>; isManufacturing?: Maybe<Scalars['Boolean']>; isCarrierRequired?: Maybe<Scalars['Boolean']>; devicesIds: Array<Scalars['String']>; devices: Array<Ever_Device>; orders: Array<Ever_Order>; users: Array<Ever_User>; hasRestrictedCarriers?: Maybe<Scalars['Boolean']>; carriersIds?: Maybe<Array<Scalars['String']>>; usedCarriersIds?: Maybe<Array<Scalars['String']>>; carriers?: Maybe<Array<Ever_Carrier>>; orderBarcodeType?: Maybe<Scalars['Int']>; }; export type Ever_WarehouseCreateInput = { geoLocation: Ever_GeoLocationCreateInput; name: Scalars['String']; logo: Scalars['String']; username: Scalars['String']; isActive?: Maybe<Scalars['Boolean']>; isPaymentEnabled?: Maybe<Scalars['Boolean']>; contactEmail?: Maybe<Scalars['String']>; contactPhone?: Maybe<Scalars['String']>; forwardOrdersUsing?: Maybe<Array<Scalars['Int']>>; ordersEmail?: Maybe<Scalars['String']>; ordersPhone?: Maybe<Scalars['String']>; isManufacturing?: Maybe<Scalars['Boolean']>; isCarrierRequired?: Maybe<Scalars['Boolean']>; hasRestrictedCarriers?: Maybe<Scalars['Boolean']>; carriersIds?: Maybe<Array<Scalars['String']>>; usedCarriersIds?: Maybe<Array<Scalars['String']>>; }; export type Ever_WarehouseLoginInfo = { warehouse: Ever_Warehouse; token: Scalars['String']; }; export type Ever_WarehouseOrdersRouterCreateOptions = { autoConfirm: Scalars['Boolean']; }; export type Ever_WarehousePasswordUpdateInput = { current: Scalars['String']; new: Scalars['String']; }; export type Ever_WarehouseProduct = { id: Scalars['String']; _id: Scalars['String']; price: Scalars['Int']; initialPrice: Scalars['Int']; count?: Maybe<Scalars['Int']>; soldCount: Scalars['Int']; product: Ever_Product; isManufacturing?: Maybe<Scalars['Boolean']>; isCarrierRequired?: Maybe<Scalars['Boolean']>; isDeliveryRequired?: Maybe<Scalars['Boolean']>; isTakeaway?: Maybe<Scalars['Boolean']>; deliveryTimeMin?: Maybe<Scalars['Int']>; deliveryTimeMax?: Maybe<Scalars['Int']>; }; export type Ever_WarehouseProductInput = { price: Scalars['Int']; initialPrice: Scalars['Int']; count?: Maybe<Scalars['Int']>; product: Scalars['String']; isManufacturing?: Maybe<Scalars['Boolean']>; isCarrierRequired?: Maybe<Scalars['Boolean']>; isDeliveryRequired?: Maybe<Scalars['Boolean']>; isTakeaway?: Maybe<Scalars['Boolean']>; deliveryTimeMin?: Maybe<Scalars['Int']>; deliveryTimeMax?: Maybe<Scalars['Int']>; }; export type Ever_WarehouseProductUpdateInput = { quantity?: Maybe<Ever_QuantityUpdateInput>; price?: Maybe<Scalars['Int']>; }; export type Ever_WarehouseRegisterInput = { warehouse: Ever_WarehouseCreateInput; password: Scalars['String']; }; export type Ever_WarehousesFindInput = { isActive?: Maybe<Scalars['Boolean']>; isPaymentEnabled?: Maybe<Scalars['Boolean']>; name?: Maybe<Scalars['String']>; logo?: Maybe<Scalars['String']>; username?: Maybe<Scalars['String']>; contactEmail?: Maybe<Scalars['String']>; contactPhone?: Maybe<Scalars['String']>; forwardOrdersUsing?: Maybe<Array<Maybe<Scalars['Int']>>>; ordersEmail?: Maybe<Scalars['String']>; ordersPhone?: Maybe<Scalars['String']>; isManufacturing?: Maybe<Scalars['Boolean']>; isCarrierRequired?: Maybe<Scalars['Boolean']>; hasRestrictedCarriers?: Maybe<Scalars['Boolean']>; carriersIds?: Maybe<Array<Scalars['String']>>; usedCarriersIds?: Maybe<Array<Scalars['String']>>; }; /** Node of type File */ export type File = Node & { /** The id of this node. */ id: Scalars['ID']; /** The parent of this node. */ parent?: Maybe<Node>; /** The children of this node. */ children?: Maybe<Array<Maybe<Node>>>; /** The child of this node of type imageSharp */ childImageSharp?: Maybe<ImageSharp>; internal?: Maybe<Internal_10>; sourceInstanceName?: Maybe<Scalars['String']>; absolutePath?: Maybe<Scalars['String']>; relativePath?: Maybe<Scalars['String']>; extension?: Maybe<Scalars['String']>; size?: Maybe<Scalars['Int']>; prettySize?: Maybe<Scalars['String']>; modifiedTime?: Maybe<Scalars['Date']>; accessTime?: Maybe<Scalars['Date']>; changeTime?: Maybe<Scalars['Date']>; birthTime?: Maybe<Scalars['Date']>; root?: Maybe<Scalars['String']>; dir?: Maybe<Scalars['String']>; base?: Maybe<Scalars['String']>; ext?: Maybe<Scalars['String']>; name?: Maybe<Scalars['String']>; relativeDirectory?: Maybe<Scalars['String']>; dev?: Maybe<Scalars['Int']>; mode?: Maybe<Scalars['Int']>; nlink?: Maybe<Scalars['Int']>; uid?: Maybe<Scalars['Int']>; gid?: Maybe<Scalars['Int']>; rdev?: Maybe<Scalars['Int']>; ino?: Maybe<Scalars['Float']>; atimeMs?: Maybe<Scalars['Float']>; mtimeMs?: Maybe<Scalars['Float']>; ctimeMs?: Maybe<Scalars['Float']>; birthtimeMs?: Maybe<Scalars['Float']>; atime?: Maybe<Scalars['Date']>; mtime?: Maybe<Scalars['Date']>; ctime?: Maybe<Scalars['Date']>; birthtime?: Maybe<Scalars['Date']>; /** Copy file to static directory and return public url to it */ publicURL?: Maybe<Scalars['String']>; }; /** Node of type File */ export type FileModifiedTimeArgs = { formatString?: Maybe<Scalars['String']>; fromNow?: Maybe<Scalars['Boolean']>; difference?: Maybe<Scalars['String']>; locale?: Maybe<Scalars['String']>; }; /** Node of type File */ export type FileAccessTimeArgs = { formatString?: Maybe<Scalars['String']>; fromNow?: Maybe<Scalars['Boolean']>; difference?: Maybe<Scalars['String']>; locale?: Maybe<Scalars['String']>; }; /** Node of type File */ export type FileChangeTimeArgs = { formatString?: Maybe<Scalars['String']>; fromNow?: Maybe<Scalars['Boolean']>; difference?: Maybe<Scalars['String']>; locale?: Maybe<Scalars['String']>; }; /** Node of type File */ export type FileBirthTimeArgs = { formatString?: Maybe<Scalars['String']>; fromNow?: Maybe<Scalars['Boolean']>; difference?: Maybe<Scalars['String']>; locale?: Maybe<Scalars['String']>; }; /** Node of type File */ export type FileAtimeArgs = { formatString?: Maybe<Scalars['String']>; fromNow?: Maybe<Scalars['Boolean']>; difference?: Maybe<Scalars['String']>; locale?: Maybe<Scalars['String']>; }; /** Node of type File */ export type FileMtimeArgs = { formatString?: Maybe<Scalars['String']>; fromNow?: Maybe<Scalars['Boolean']>; difference?: Maybe<Scalars['String']>; locale?: Maybe<Scalars['String']>; }; /** Node of type File */ export type FileCtimeArgs = { formatString?: Maybe<Scalars['String']>; fromNow?: Maybe<Scalars['Boolean']>; difference?: Maybe<Scalars['String']>; locale?: Maybe<Scalars['String']>; }; /** Node of type File */ export type FileBirthtimeArgs = { formatString?: Maybe<Scalars['String']>; fromNow?: Maybe<Scalars['Boolean']>; difference?: Maybe<Scalars['String']>; locale?: Maybe<Scalars['String']>; }; export type FileAbsolutePathQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileAccessTimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileAtimeMsQueryFloat_2 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type FileAtimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileBaseQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileBirthtimeMsQueryFloat_2 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type FileBirthtimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileBirthTimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileChangeTimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; /** A connection to a list of items. */ export type FileConnection = { /** Information to aid in pagination. */ pageInfo: PageInfo; /** A list of edges. */ edges?: Maybe<Array<Maybe<FileEdge>>>; totalCount?: Maybe<Scalars['Int']>; distinct?: Maybe<Array<Maybe<Scalars['String']>>>; group?: Maybe<Array<Maybe<FileGroupConnectionConnection>>>; }; /** A connection to a list of items. */ export type FileConnectionDistinctArgs = { field?: Maybe<FileDistinctEnum>; }; /** A connection to a list of items. */ export type FileConnectionGroupArgs = { skip?: Maybe<Scalars['Int']>; limit?: Maybe<Scalars['Int']>; field?: Maybe<FileGroupEnum>; }; export type FileConnectionAbsolutePathQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileConnectionAccessTimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileConnectionAtimeMsQueryFloat_2 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type FileConnectionAtimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileConnectionBaseQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileConnectionBirthtimeMsQueryFloat_2 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type FileConnectionBirthtimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileConnectionBirthTimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileConnectionChangeTimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileConnectionCtimeMsQueryFloat_2 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type FileConnectionCtimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileConnectionDevQueryInteger_2 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type FileConnectionDirQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileConnectionExtensionQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileConnectionExtQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileConnectionGidQueryInteger_2 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type FileConnectionIdQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileConnectionInoQueryFloat_2 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type FileConnectionInternalContentDigestQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileConnectionInternalDescriptionQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileConnectionInternalInputObject_2 = { contentDigest?: Maybe<FileConnectionInternalContentDigestQueryString_2>; type?: Maybe<FileConnectionInternalTypeQueryString_2>; mediaType?: Maybe<FileConnectionInternalMediaTypeQueryString_2>; description?: Maybe<FileConnectionInternalDescriptionQueryString_2>; owner?: Maybe<FileConnectionInternalOwnerQueryString_2>; }; export type FileConnectionInternalMediaTypeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileConnectionInternalOwnerQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileConnectionInternalTypeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileConnectionModeQueryInteger_2 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type FileConnectionModifiedTimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileConnectionMtimeMsQueryFloat_2 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type FileConnectionMtimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileConnectionNameQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileConnectionNlinkQueryInteger_2 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type FileConnectionPrettySizeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileConnectionRdevQueryInteger_2 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type FileConnectionRelativeDirectoryQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileConnectionRelativePathQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileConnectionRootQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileConnectionSizeQueryInteger_2 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type FileConnectionSort = { fields: Array<Maybe<FileConnectionSortByFieldsEnum>>; order?: Maybe<Array<Maybe<FileConnectionSortOrderValues>>>; }; export enum FileConnectionSortByFieldsEnum { Id = 'id', Children = 'children', Internal___ContentDigest = 'internal___contentDigest', Internal___Type = 'internal___type', Internal___MediaType = 'internal___mediaType', Internal___Description = 'internal___description', Internal___Owner = 'internal___owner', SourceInstanceName = 'sourceInstanceName', AbsolutePath = 'absolutePath', RelativePath = 'relativePath', Extension = 'extension', Size = 'size', PrettySize = 'prettySize', ModifiedTime = 'modifiedTime', AccessTime = 'accessTime', ChangeTime = 'changeTime', BirthTime = 'birthTime', Root = 'root', Dir = 'dir', Base = 'base', Ext = 'ext', Name = 'name', RelativeDirectory = 'relativeDirectory', Dev = 'dev', Mode = 'mode', Nlink = 'nlink', Uid = 'uid', Gid = 'gid', Rdev = 'rdev', Ino = 'ino', AtimeMs = 'atimeMs', MtimeMs = 'mtimeMs', CtimeMs = 'ctimeMs', BirthtimeMs = 'birthtimeMs', Atime = 'atime', Mtime = 'mtime', Ctime = 'ctime', Birthtime = 'birthtime', PublicUrl = 'publicURL', } export enum FileConnectionSortOrderValues { Asc = 'ASC', Desc = 'DESC', } export type FileConnectionSourceInstanceNameQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileConnectionUidQueryInteger_2 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type FileCtimeMsQueryFloat_2 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type FileCtimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileDevQueryInteger_2 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type FileDirQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export enum FileDistinctEnum { Id = 'id', Children = 'children', Internal___ContentDigest = 'internal___contentDigest', Internal___Type = 'internal___type', Internal___MediaType = 'internal___mediaType', Internal___Description = 'internal___description', Internal___Owner = 'internal___owner', SourceInstanceName = 'sourceInstanceName', AbsolutePath = 'absolutePath', RelativePath = 'relativePath', Extension = 'extension', Size = 'size', PrettySize = 'prettySize', ModifiedTime = 'modifiedTime', AccessTime = 'accessTime', ChangeTime = 'changeTime', BirthTime = 'birthTime', Root = 'root', Dir = 'dir', Base = 'base', Ext = 'ext', Name = 'name', RelativeDirectory = 'relativeDirectory', Dev = 'dev', Mode = 'mode', Nlink = 'nlink', Uid = 'uid', Gid = 'gid', Rdev = 'rdev', Ino = 'ino', AtimeMs = 'atimeMs', MtimeMs = 'mtimeMs', CtimeMs = 'ctimeMs', BirthtimeMs = 'birthtimeMs', Atime = 'atime', Mtime = 'mtime', Ctime = 'ctime', Birthtime = 'birthtime', } /** An edge in a connection. */ export type FileEdge = { /** The item at the end of the edge */ node?: Maybe<File>; /** The next edge in the connection */ next?: Maybe<File>; /** The previous edge in the connection */ previous?: Maybe<File>; }; export type FileExtensionQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileExtQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileGidQueryInteger_2 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; /** A connection to a list of items. */ export type FileGroupConnectionConnection = { /** Information to aid in pagination. */ pageInfo: PageInfo; /** A list of edges. */ edges?: Maybe<Array<Maybe<FileGroupConnectionEdge>>>; field?: Maybe<Scalars['String']>; fieldValue?: Maybe<Scalars['String']>; totalCount?: Maybe<Scalars['Int']>; }; /** An edge in a connection. */ export type FileGroupConnectionEdge = { /** The item at the end of the edge */ node?: Maybe<File>; /** The next edge in the connection */ next?: Maybe<File>; /** The previous edge in the connection */ previous?: Maybe<File>; }; export enum FileGroupEnum { Id = 'id', Children = 'children', Internal___ContentDigest = 'internal___contentDigest', Internal___Type = 'internal___type', Internal___MediaType = 'internal___mediaType', Internal___Description = 'internal___description', Internal___Owner = 'internal___owner', SourceInstanceName = 'sourceInstanceName', AbsolutePath = 'absolutePath', RelativePath = 'relativePath', Extension = 'extension', Size = 'size', PrettySize = 'prettySize', ModifiedTime = 'modifiedTime', AccessTime = 'accessTime', ChangeTime = 'changeTime', BirthTime = 'birthTime', Root = 'root', Dir = 'dir', Base = 'base', Ext = 'ext', Name = 'name', RelativeDirectory = 'relativeDirectory', Dev = 'dev', Mode = 'mode', Nlink = 'nlink', Uid = 'uid', Gid = 'gid', Rdev = 'rdev', Ino = 'ino', AtimeMs = 'atimeMs', MtimeMs = 'mtimeMs', CtimeMs = 'ctimeMs', BirthtimeMs = 'birthtimeMs', Atime = 'atime', Mtime = 'mtime', Ctime = 'ctime', Birthtime = 'birthtime', } export type FileIdQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileInoQueryFloat_2 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type FileInternalContentDigestQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileInternalDescriptionQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileInternalInputObject_2 = { contentDigest?: Maybe<FileInternalContentDigestQueryString_2>; type?: Maybe<FileInternalTypeQueryString_2>; mediaType?: Maybe<FileInternalMediaTypeQueryString_2>; description?: Maybe<FileInternalDescriptionQueryString_2>; owner?: Maybe<FileInternalOwnerQueryString_2>; }; export type FileInternalMediaTypeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileInternalOwnerQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileInternalTypeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileModeQueryInteger_2 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type FileModifiedTimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileMtimeMsQueryFloat_2 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type FileMtimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileNameQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileNlinkQueryInteger_2 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type FilePrettySizeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileRdevQueryInteger_2 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type FileRelativeDirectoryQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileRelativePathQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileRootQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileSizeQueryInteger_2 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type FileSourceInstanceNameQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FileUidQueryInteger_2 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; /** Filter connection on its fields */ export type FilterDirectory = { id?: Maybe<DirectoryConnectionIdQueryString_2>; internal?: Maybe<DirectoryConnectionInternalInputObject_2>; sourceInstanceName?: Maybe< DirectoryConnectionSourceInstanceNameQueryString_2 >; absolutePath?: Maybe<DirectoryConnectionAbsolutePathQueryString_2>; relativePath?: Maybe<DirectoryConnectionRelativePathQueryString_2>; extension?: Maybe<DirectoryConnectionExtensionQueryString_2>; size?: Maybe<DirectoryConnectionSizeQueryInteger_2>; prettySize?: Maybe<DirectoryConnectionPrettySizeQueryString_2>; modifiedTime?: Maybe<DirectoryConnectionModifiedTimeQueryString_2>; accessTime?: Maybe<DirectoryConnectionAccessTimeQueryString_2>; changeTime?: Maybe<DirectoryConnectionChangeTimeQueryString_2>; birthTime?: Maybe<DirectoryConnectionBirthTimeQueryString_2>; root?: Maybe<DirectoryConnectionRootQueryString_2>; dir?: Maybe<DirectoryConnectionDirQueryString_2>; base?: Maybe<DirectoryConnectionBaseQueryString_2>; ext?: Maybe<DirectoryConnectionExtQueryString_2>; name?: Maybe<DirectoryConnectionNameQueryString_2>; relativeDirectory?: Maybe<DirectoryConnectionRelativeDirectoryQueryString_2>; dev?: Maybe<DirectoryConnectionDevQueryInteger_2>; mode?: Maybe<DirectoryConnectionModeQueryInteger_2>; nlink?: Maybe<DirectoryConnectionNlinkQueryInteger_2>; uid?: Maybe<DirectoryConnectionUidQueryInteger_2>; gid?: Maybe<DirectoryConnectionGidQueryInteger_2>; rdev?: Maybe<DirectoryConnectionRdevQueryInteger_2>; ino?: Maybe<DirectoryConnectionInoQueryFloat_2>; atimeMs?: Maybe<DirectoryConnectionAtimeMsQueryFloat_2>; mtimeMs?: Maybe<DirectoryConnectionMtimeMsQueryFloat_2>; ctimeMs?: Maybe<DirectoryConnectionCtimeMsQueryFloat_2>; birthtimeMs?: Maybe<DirectoryConnectionBirthtimeMsQueryFloat_2>; atime?: Maybe<DirectoryConnectionAtimeQueryString_2>; mtime?: Maybe<DirectoryConnectionMtimeQueryString_2>; ctime?: Maybe<DirectoryConnectionCtimeQueryString_2>; birthtime?: Maybe<DirectoryConnectionBirthtimeQueryString_2>; }; /** Filter connection on its fields */ export type FilterFile = { id?: Maybe<FileConnectionIdQueryString_2>; internal?: Maybe<FileConnectionInternalInputObject_2>; sourceInstanceName?: Maybe<FileConnectionSourceInstanceNameQueryString_2>; absolutePath?: Maybe<FileConnectionAbsolutePathQueryString_2>; relativePath?: Maybe<FileConnectionRelativePathQueryString_2>; extension?: Maybe<FileConnectionExtensionQueryString_2>; size?: Maybe<FileConnectionSizeQueryInteger_2>; prettySize?: Maybe<FileConnectionPrettySizeQueryString_2>; modifiedTime?: Maybe<FileConnectionModifiedTimeQueryString_2>; accessTime?: Maybe<FileConnectionAccessTimeQueryString_2>; changeTime?: Maybe<FileConnectionChangeTimeQueryString_2>; birthTime?: Maybe<FileConnectionBirthTimeQueryString_2>; root?: Maybe<FileConnectionRootQueryString_2>; dir?: Maybe<FileConnectionDirQueryString_2>; base?: Maybe<FileConnectionBaseQueryString_2>; ext?: Maybe<FileConnectionExtQueryString_2>; name?: Maybe<FileConnectionNameQueryString_2>; relativeDirectory?: Maybe<FileConnectionRelativeDirectoryQueryString_2>; dev?: Maybe<FileConnectionDevQueryInteger_2>; mode?: Maybe<FileConnectionModeQueryInteger_2>; nlink?: Maybe<FileConnectionNlinkQueryInteger_2>; uid?: Maybe<FileConnectionUidQueryInteger_2>; gid?: Maybe<FileConnectionGidQueryInteger_2>; rdev?: Maybe<FileConnectionRdevQueryInteger_2>; ino?: Maybe<FileConnectionInoQueryFloat_2>; atimeMs?: Maybe<FileConnectionAtimeMsQueryFloat_2>; mtimeMs?: Maybe<FileConnectionMtimeMsQueryFloat_2>; ctimeMs?: Maybe<FileConnectionCtimeMsQueryFloat_2>; birthtimeMs?: Maybe<FileConnectionBirthtimeMsQueryFloat_2>; atime?: Maybe<FileConnectionAtimeQueryString_2>; mtime?: Maybe<FileConnectionMtimeQueryString_2>; ctime?: Maybe<FileConnectionCtimeQueryString_2>; birthtime?: Maybe<FileConnectionBirthtimeQueryString_2>; publicURL?: Maybe<PublicUrlQueryString_4>; }; /** Filter connection on its fields */ export type FilterImageSharp = { id?: Maybe<ImageSharpConnectionIdQueryString_2>; internal?: Maybe<ImageSharpConnectionInternalInputObject_2>; fixed?: Maybe<FixedTypeName_4>; resolutions?: Maybe<ResolutionsTypeName_4>; fluid?: Maybe<FluidTypeName_4>; sizes?: Maybe<SizesTypeName_4>; original?: Maybe<OriginalTypeName_4>; resize?: Maybe<ResizeTypeName_4>; }; /** Filter connection on its fields */ export type FilterSitePage = { jsonName?: Maybe<SitePageConnectionJsonNameQueryString>; internalComponentName?: Maybe< SitePageConnectionInternalComponentNameQueryString >; path?: Maybe<SitePageConnectionPathQueryString_2>; component?: Maybe<SitePageConnectionComponentQueryString>; componentChunkName?: Maybe<SitePageConnectionComponentChunkNameQueryString>; pluginCreator?: Maybe<SitePageConnectionPluginCreatorInputObject>; pluginCreatorId?: Maybe<SitePageConnectionPluginCreatorIdQueryString_2>; componentPath?: Maybe<SitePageConnectionComponentPathQueryString>; id?: Maybe<SitePageConnectionIdQueryString_2>; internal?: Maybe<SitePageConnectionInternalInputObject_2>; }; /** Filter connection on its fields */ export type FilterSitePlugin = { resolve?: Maybe<SitePluginConnectionResolveQueryString_2>; id?: Maybe<SitePluginConnectionIdQueryString_2>; name?: Maybe<SitePluginConnectionNameQueryString_2>; version?: Maybe<SitePluginConnectionVersionQueryString_2>; pluginOptions?: Maybe<SitePluginConnectionPluginOptionsInputObject_2>; nodeAPIs?: Maybe<SitePluginConnectionNodeApIsQueryList_2>; browserAPIs?: Maybe<SitePluginConnectionBrowserApIsQueryList_2>; ssrAPIs?: Maybe<SitePluginConnectionSsrApIsQueryList_2>; pluginFilepath?: Maybe<SitePluginConnectionPluginFilepathQueryString_2>; packageJson?: Maybe<SitePluginConnectionPackageJsonInputObject_2>; internal?: Maybe<SitePluginConnectionInternalInputObject_2>; }; export type FixedAspectRatioQueryFloat_3 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type FixedAspectRatioQueryFloat_4 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type FixedBase64QueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FixedBase64QueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FixedHeightQueryFloat_3 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type FixedHeightQueryFloat_4 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type FixedOriginalNameQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FixedOriginalNameQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FixedSrcQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FixedSrcQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FixedSrcSetQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FixedSrcSetQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FixedSrcSetWebpQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FixedSrcSetWebpQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FixedSrcWebpQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FixedSrcWebpQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FixedTracedSvgQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FixedTracedSvgQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FixedTypeName_3 = { base64?: Maybe<FixedBase64QueryString_3>; tracedSVG?: Maybe<FixedTracedSvgQueryString_3>; aspectRatio?: Maybe<FixedAspectRatioQueryFloat_3>; width?: Maybe<FixedWidthQueryFloat_3>; height?: Maybe<FixedHeightQueryFloat_3>; src?: Maybe<FixedSrcQueryString_3>; srcSet?: Maybe<FixedSrcSetQueryString_3>; srcWebp?: Maybe<FixedSrcWebpQueryString_3>; srcSetWebp?: Maybe<FixedSrcSetWebpQueryString_3>; originalName?: Maybe<FixedOriginalNameQueryString_3>; }; export type FixedTypeName_4 = { base64?: Maybe<FixedBase64QueryString_4>; tracedSVG?: Maybe<FixedTracedSvgQueryString_4>; aspectRatio?: Maybe<FixedAspectRatioQueryFloat_4>; width?: Maybe<FixedWidthQueryFloat_4>; height?: Maybe<FixedHeightQueryFloat_4>; src?: Maybe<FixedSrcQueryString_4>; srcSet?: Maybe<FixedSrcSetQueryString_4>; srcWebp?: Maybe<FixedSrcWebpQueryString_4>; srcSetWebp?: Maybe<FixedSrcSetWebpQueryString_4>; originalName?: Maybe<FixedOriginalNameQueryString_4>; }; export type FixedWidthQueryFloat_3 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type FixedWidthQueryFloat_4 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type FluidAspectRatioQueryFloat_3 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type FluidAspectRatioQueryFloat_4 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type FluidBase64QueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FluidBase64QueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FluidOriginalImgQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FluidOriginalImgQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FluidOriginalNameQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FluidOriginalNameQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FluidPresentationHeightQueryInt_3 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type FluidPresentationHeightQueryInt_4 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type FluidPresentationWidthQueryInt_3 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type FluidPresentationWidthQueryInt_4 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type FluidSizesQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FluidSizesQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FluidSrcQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FluidSrcQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FluidSrcSetQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FluidSrcSetQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FluidSrcSetWebpQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FluidSrcSetWebpQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FluidSrcWebpQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FluidSrcWebpQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FluidTracedSvgQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FluidTracedSvgQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type FluidTypeName_3 = { base64?: Maybe<FluidBase64QueryString_3>; tracedSVG?: Maybe<FluidTracedSvgQueryString_3>; aspectRatio?: Maybe<FluidAspectRatioQueryFloat_3>; src?: Maybe<FluidSrcQueryString_3>; srcSet?: Maybe<FluidSrcSetQueryString_3>; srcWebp?: Maybe<FluidSrcWebpQueryString_3>; srcSetWebp?: Maybe<FluidSrcSetWebpQueryString_3>; sizes?: Maybe<FluidSizesQueryString_3>; originalImg?: Maybe<FluidOriginalImgQueryString_3>; originalName?: Maybe<FluidOriginalNameQueryString_3>; presentationWidth?: Maybe<FluidPresentationWidthQueryInt_3>; presentationHeight?: Maybe<FluidPresentationHeightQueryInt_3>; }; export type FluidTypeName_4 = { base64?: Maybe<FluidBase64QueryString_4>; tracedSVG?: Maybe<FluidTracedSvgQueryString_4>; aspectRatio?: Maybe<FluidAspectRatioQueryFloat_4>; src?: Maybe<FluidSrcQueryString_4>; srcSet?: Maybe<FluidSrcSetQueryString_4>; srcWebp?: Maybe<FluidSrcWebpQueryString_4>; srcSetWebp?: Maybe<FluidSrcSetWebpQueryString_4>; sizes?: Maybe<FluidSizesQueryString_4>; originalImg?: Maybe<FluidOriginalImgQueryString_4>; originalName?: Maybe<FluidOriginalNameQueryString_4>; presentationWidth?: Maybe<FluidPresentationWidthQueryInt_4>; presentationHeight?: Maybe<FluidPresentationHeightQueryInt_4>; }; export enum ImageCropFocus { Center = 'CENTER', North = 'NORTH', Northeast = 'NORTHEAST', East = 'EAST', Southeast = 'SOUTHEAST', South = 'SOUTH', Southwest = 'SOUTHWEST', West = 'WEST', Northwest = 'NORTHWEST', Entropy = 'ENTROPY', Attention = 'ATTENTION', } export enum ImageFormat { No_Change = 'NO_CHANGE', Jpg = 'JPG', Png = 'PNG', Webp = 'WEBP', } /** Node of type ImageSharp */ export type ImageSharp = Node & { /** The id of this node. */ id: Scalars['ID']; /** The parent of this node. */ parent?: Maybe<Node>; /** The children of this node. */ children?: Maybe<Array<Maybe<Node>>>; internal?: Maybe<Internal_11>; fixed?: Maybe<ImageSharpFixed>; resolutions?: Maybe<ImageSharpResolutions>; fluid?: Maybe<ImageSharpFluid>; sizes?: Maybe<ImageSharpSizes>; original?: Maybe<ImageSharpOriginal>; resize?: Maybe<ImageSharpResize>; }; /** Node of type ImageSharp */ export type ImageSharpFixedArgs = { width?: Maybe<Scalars['Int']>; height?: Maybe<Scalars['Int']>; base64Width?: Maybe<Scalars['Int']>; jpegProgressive: Scalars['Boolean']; pngCompressionSpeed: Scalars['Int']; grayscale: Scalars['Boolean']; duotone?: Maybe<DuotoneGradient>; traceSVG?: Maybe<Potrace>; quality?: Maybe<Scalars['Int']>; toFormat?: Maybe<ImageFormat>; toFormatBase64?: Maybe<ImageFormat>; cropFocus?: Maybe<ImageCropFocus>; rotate: Scalars['Int']; }; /** Node of type ImageSharp */ export type ImageSharpResolutionsArgs = { width?: Maybe<Scalars['Int']>; height?: Maybe<Scalars['Int']>; base64Width?: Maybe<Scalars['Int']>; jpegProgressive: Scalars['Boolean']; pngCompressionSpeed: Scalars['Int']; grayscale: Scalars['Boolean']; duotone?: Maybe<DuotoneGradient>; traceSVG?: Maybe<Potrace>; quality?: Maybe<Scalars['Int']>; toFormat?: Maybe<ImageFormat>; toFormatBase64?: Maybe<ImageFormat>; cropFocus?: Maybe<ImageCropFocus>; rotate: Scalars['Int']; }; /** Node of type ImageSharp */ export type ImageSharpFluidArgs = { maxWidth?: Maybe<Scalars['Int']>; maxHeight?: Maybe<Scalars['Int']>; base64Width?: Maybe<Scalars['Int']>; grayscale: Scalars['Boolean']; jpegProgressive: Scalars['Boolean']; pngCompressionSpeed: Scalars['Int']; duotone?: Maybe<DuotoneGradient>; traceSVG?: Maybe<Potrace>; quality?: Maybe<Scalars['Int']>; toFormat?: Maybe<ImageFormat>; toFormatBase64?: Maybe<ImageFormat>; cropFocus?: Maybe<ImageCropFocus>; rotate: Scalars['Int']; sizes: Scalars['String']; srcSetBreakpoints: Array<Maybe<Scalars['Int']>>; }; /** Node of type ImageSharp */ export type ImageSharpSizesArgs = { maxWidth?: Maybe<Scalars['Int']>; maxHeight?: Maybe<Scalars['Int']>; base64Width?: Maybe<Scalars['Int']>; grayscale: Scalars['Boolean']; jpegProgressive: Scalars['Boolean']; pngCompressionSpeed: Scalars['Int']; duotone?: Maybe<DuotoneGradient>; traceSVG?: Maybe<Potrace>; quality?: Maybe<Scalars['Int']>; toFormat?: Maybe<ImageFormat>; toFormatBase64?: Maybe<ImageFormat>; cropFocus?: Maybe<ImageCropFocus>; rotate: Scalars['Int']; sizes: Scalars['String']; srcSetBreakpoints: Array<Maybe<Scalars['Int']>>; }; /** Node of type ImageSharp */ export type ImageSharpResizeArgs = { width?: Maybe<Scalars['Int']>; height?: Maybe<Scalars['Int']>; quality?: Maybe<Scalars['Int']>; jpegProgressive: Scalars['Boolean']; pngCompressionLevel: Scalars['Int']; pngCompressionSpeed: Scalars['Int']; grayscale: Scalars['Boolean']; duotone?: Maybe<DuotoneGradient>; base64: Scalars['Boolean']; traceSVG?: Maybe<Potrace>; toFormat?: Maybe<ImageFormat>; cropFocus?: Maybe<ImageCropFocus>; rotate: Scalars['Int']; }; /** A connection to a list of items. */ export type ImageSharpConnection = { /** Information to aid in pagination. */ pageInfo: PageInfo; /** A list of edges. */ edges?: Maybe<Array<Maybe<ImageSharpEdge>>>; totalCount?: Maybe<Scalars['Int']>; distinct?: Maybe<Array<Maybe<Scalars['String']>>>; group?: Maybe<Array<Maybe<ImageSharpGroupConnectionConnection>>>; }; /** A connection to a list of items. */ export type ImageSharpConnectionDistinctArgs = { field?: Maybe<ImageSharpDistinctEnum>; }; /** A connection to a list of items. */ export type ImageSharpConnectionGroupArgs = { skip?: Maybe<Scalars['Int']>; limit?: Maybe<Scalars['Int']>; field?: Maybe<ImageSharpGroupEnum>; }; export type ImageSharpConnectionIdQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type ImageSharpConnectionInternalContentDigestQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type ImageSharpConnectionInternalInputObject_2 = { contentDigest?: Maybe<ImageSharpConnectionInternalContentDigestQueryString_2>; type?: Maybe<ImageSharpConnectionInternalTypeQueryString_2>; owner?: Maybe<ImageSharpConnectionInternalOwnerQueryString_2>; }; export type ImageSharpConnectionInternalOwnerQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type ImageSharpConnectionInternalTypeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type ImageSharpConnectionSort = { fields: Array<Maybe<ImageSharpConnectionSortByFieldsEnum>>; order?: Maybe<Array<Maybe<ImageSharpConnectionSortOrderValues>>>; }; export enum ImageSharpConnectionSortByFieldsEnum { Id = 'id', Parent = 'parent', Internal___ContentDigest = 'internal___contentDigest', Internal___Type = 'internal___type', Internal___Owner = 'internal___owner', Fixed___Base64 = 'fixed___base64', Fixed___TracedSvg = 'fixed___tracedSVG', Fixed___AspectRatio = 'fixed___aspectRatio', Fixed___Width = 'fixed___width', Fixed___Height = 'fixed___height', Fixed___Src = 'fixed___src', Fixed___SrcSet = 'fixed___srcSet', Fixed___SrcWebp = 'fixed___srcWebp', Fixed___SrcSetWebp = 'fixed___srcSetWebp', Fixed___OriginalName = 'fixed___originalName', Resolutions___Base64 = 'resolutions___base64', Resolutions___TracedSvg = 'resolutions___tracedSVG', Resolutions___AspectRatio = 'resolutions___aspectRatio', Resolutions___Width = 'resolutions___width', Resolutions___Height = 'resolutions___height', Resolutions___Src = 'resolutions___src', Resolutions___SrcSet = 'resolutions___srcSet', Resolutions___SrcWebp = 'resolutions___srcWebp', Resolutions___SrcSetWebp = 'resolutions___srcSetWebp', Resolutions___OriginalName = 'resolutions___originalName', Fluid___Base64 = 'fluid___base64', Fluid___TracedSvg = 'fluid___tracedSVG', Fluid___AspectRatio = 'fluid___aspectRatio', Fluid___Src = 'fluid___src', Fluid___SrcSet = 'fluid___srcSet', Fluid___SrcWebp = 'fluid___srcWebp', Fluid___SrcSetWebp = 'fluid___srcSetWebp', Fluid___Sizes = 'fluid___sizes', Fluid___OriginalImg = 'fluid___originalImg', Fluid___OriginalName = 'fluid___originalName', Fluid___PresentationWidth = 'fluid___presentationWidth', Fluid___PresentationHeight = 'fluid___presentationHeight', Sizes___Base64 = 'sizes___base64', Sizes___TracedSvg = 'sizes___tracedSVG', Sizes___AspectRatio = 'sizes___aspectRatio', Sizes___Src = 'sizes___src', Sizes___SrcSet = 'sizes___srcSet', Sizes___SrcWebp = 'sizes___srcWebp', Sizes___SrcSetWebp = 'sizes___srcSetWebp', Sizes___Sizes = 'sizes___sizes', Sizes___OriginalImg = 'sizes___originalImg', Sizes___OriginalName = 'sizes___originalName', Sizes___PresentationWidth = 'sizes___presentationWidth', Sizes___PresentationHeight = 'sizes___presentationHeight', Original___Width = 'original___width', Original___Height = 'original___height', Original___Src = 'original___src', Resize___Src = 'resize___src', Resize___TracedSvg = 'resize___tracedSVG', Resize___Width = 'resize___width', Resize___Height = 'resize___height', Resize___AspectRatio = 'resize___aspectRatio', Resize___OriginalName = 'resize___originalName', } export enum ImageSharpConnectionSortOrderValues { Asc = 'ASC', Desc = 'DESC', } export enum ImageSharpDistinctEnum { Id = 'id', Parent = 'parent', Internal___ContentDigest = 'internal___contentDigest', Internal___Type = 'internal___type', Internal___Owner = 'internal___owner', } /** An edge in a connection. */ export type ImageSharpEdge = { /** The item at the end of the edge */ node?: Maybe<ImageSharp>; /** The next edge in the connection */ next?: Maybe<ImageSharp>; /** The previous edge in the connection */ previous?: Maybe<ImageSharp>; }; export type ImageSharpFixed = { base64?: Maybe<Scalars['String']>; tracedSVG?: Maybe<Scalars['String']>; aspectRatio?: Maybe<Scalars['Float']>; width?: Maybe<Scalars['Float']>; height?: Maybe<Scalars['Float']>; src?: Maybe<Scalars['String']>; srcSet?: Maybe<Scalars['String']>; srcWebp?: Maybe<Scalars['String']>; srcSetWebp?: Maybe<Scalars['String']>; originalName?: Maybe<Scalars['String']>; }; export type ImageSharpFluid = { base64?: Maybe<Scalars['String']>; tracedSVG?: Maybe<Scalars['String']>; aspectRatio?: Maybe<Scalars['Float']>; src?: Maybe<Scalars['String']>; srcSet?: Maybe<Scalars['String']>; srcWebp?: Maybe<Scalars['String']>; srcSetWebp?: Maybe<Scalars['String']>; sizes?: Maybe<Scalars['String']>; originalImg?: Maybe<Scalars['String']>; originalName?: Maybe<Scalars['String']>; presentationWidth?: Maybe<Scalars['Int']>; presentationHeight?: Maybe<Scalars['Int']>; }; /** A connection to a list of items. */ export type ImageSharpGroupConnectionConnection = { /** Information to aid in pagination. */ pageInfo: PageInfo; /** A list of edges. */ edges?: Maybe<Array<Maybe<ImageSharpGroupConnectionEdge>>>; field?: Maybe<Scalars['String']>; fieldValue?: Maybe<Scalars['String']>; totalCount?: Maybe<Scalars['Int']>; }; /** An edge in a connection. */ export type ImageSharpGroupConnectionEdge = { /** The item at the end of the edge */ node?: Maybe<ImageSharp>; /** The next edge in the connection */ next?: Maybe<ImageSharp>; /** The previous edge in the connection */ previous?: Maybe<ImageSharp>; }; export enum ImageSharpGroupEnum { Id = 'id', Parent = 'parent', Internal___ContentDigest = 'internal___contentDigest', Internal___Type = 'internal___type', Internal___Owner = 'internal___owner', } export type ImageSharpIdQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type ImageSharpInternalContentDigestQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type ImageSharpInternalInputObject_2 = { contentDigest?: Maybe<ImageSharpInternalContentDigestQueryString_2>; type?: Maybe<ImageSharpInternalTypeQueryString_2>; owner?: Maybe<ImageSharpInternalOwnerQueryString_2>; }; export type ImageSharpInternalOwnerQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type ImageSharpInternalTypeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type ImageSharpOriginal = { width?: Maybe<Scalars['Float']>; height?: Maybe<Scalars['Float']>; src?: Maybe<Scalars['String']>; }; export type ImageSharpResize = { src?: Maybe<Scalars['String']>; tracedSVG?: Maybe<Scalars['String']>; width?: Maybe<Scalars['Int']>; height?: Maybe<Scalars['Int']>; aspectRatio?: Maybe<Scalars['Float']>; originalName?: Maybe<Scalars['String']>; }; export type ImageSharpResolutions = { base64?: Maybe<Scalars['String']>; tracedSVG?: Maybe<Scalars['String']>; aspectRatio?: Maybe<Scalars['Float']>; width?: Maybe<Scalars['Float']>; height?: Maybe<Scalars['Float']>; src?: Maybe<Scalars['String']>; srcSet?: Maybe<Scalars['String']>; srcWebp?: Maybe<Scalars['String']>; srcSetWebp?: Maybe<Scalars['String']>; originalName?: Maybe<Scalars['String']>; }; export type ImageSharpSizes = { base64?: Maybe<Scalars['String']>; tracedSVG?: Maybe<Scalars['String']>; aspectRatio?: Maybe<Scalars['Float']>; src?: Maybe<Scalars['String']>; srcSet?: Maybe<Scalars['String']>; srcWebp?: Maybe<Scalars['String']>; srcSetWebp?: Maybe<Scalars['String']>; sizes?: Maybe<Scalars['String']>; originalImg?: Maybe<Scalars['String']>; originalName?: Maybe<Scalars['String']>; presentationWidth?: Maybe<Scalars['Int']>; presentationHeight?: Maybe<Scalars['Int']>; }; export type Internal_10 = { contentDigest?: Maybe<Scalars['String']>; type?: Maybe<Scalars['String']>; mediaType?: Maybe<Scalars['String']>; description?: Maybe<Scalars['String']>; owner?: Maybe<Scalars['String']>; }; export type Internal_11 = { contentDigest?: Maybe<Scalars['String']>; type?: Maybe<Scalars['String']>; owner?: Maybe<Scalars['String']>; }; export type Internal_12 = { contentDigest?: Maybe<Scalars['String']>; type?: Maybe<Scalars['String']>; owner?: Maybe<Scalars['String']>; }; export type Internal_7 = { type?: Maybe<Scalars['String']>; contentDigest?: Maybe<Scalars['String']>; description?: Maybe<Scalars['String']>; owner?: Maybe<Scalars['String']>; }; export type Internal_8 = { contentDigest?: Maybe<Scalars['String']>; type?: Maybe<Scalars['String']>; owner?: Maybe<Scalars['String']>; }; export type Internal_9 = { contentDigest?: Maybe<Scalars['String']>; type?: Maybe<Scalars['String']>; description?: Maybe<Scalars['String']>; owner?: Maybe<Scalars['String']>; }; /** An object with an id, parent, and children */ export type Node = { /** The id of the node. */ id: Scalars['ID']; /** The parent of this node. */ parent?: Maybe<Node>; /** The children of this node. */ children?: Maybe<Array<Maybe<Node>>>; }; export type OriginalHeightQueryFloat_3 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type OriginalHeightQueryFloat_4 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type OriginalSrcQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type OriginalSrcQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type OriginalTypeName_3 = { width?: Maybe<OriginalWidthQueryFloat_3>; height?: Maybe<OriginalHeightQueryFloat_3>; src?: Maybe<OriginalSrcQueryString_3>; }; export type OriginalTypeName_4 = { width?: Maybe<OriginalWidthQueryFloat_4>; height?: Maybe<OriginalHeightQueryFloat_4>; src?: Maybe<OriginalSrcQueryString_4>; }; export type OriginalWidthQueryFloat_3 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type OriginalWidthQueryFloat_4 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type PackageJson_2 = { name?: Maybe<Scalars['String']>; description?: Maybe<Scalars['String']>; version?: Maybe<Scalars['String']>; main?: Maybe<Scalars['String']>; author?: Maybe<Scalars['String']>; license?: Maybe<Scalars['String']>; dependencies?: Maybe<Array<Maybe<Dependencies_2>>>; devDependencies?: Maybe<Array<Maybe<DevDependencies_2>>>; peerDependencies?: Maybe<Array<Maybe<PeerDependencies_2>>>; keywords?: Maybe<Array<Maybe<Scalars['String']>>>; }; /** Information about pagination in a connection. */ export type PageInfo = { /** When paginating, are there more items? */ hasNextPage: Scalars['Boolean']; }; export type PeerDependencies_2 = { name?: Maybe<Scalars['String']>; version?: Maybe<Scalars['String']>; }; export type PluginOptions_2 = { typeName?: Maybe<Scalars['String']>; fieldName?: Maybe<Scalars['String']>; url?: Maybe<Scalars['String']>; name?: Maybe<Scalars['String']>; path?: Maybe<Scalars['String']>; short_name?: Maybe<Scalars['String']>; start_url?: Maybe<Scalars['String']>; background_color?: Maybe<Scalars['String']>; theme_color?: Maybe<Scalars['String']>; display?: Maybe<Scalars['String']>; icon?: Maybe<Scalars['String']>; pathCheck?: Maybe<Scalars['Boolean']>; }; export type Potrace = { turnPolicy?: Maybe<PotraceTurnPolicy>; turdSize?: Maybe<Scalars['Float']>; alphaMax?: Maybe<Scalars['Float']>; optCurve?: Maybe<Scalars['Boolean']>; optTolerance?: Maybe<Scalars['Float']>; threshold?: Maybe<Scalars['Int']>; blackOnWhite?: Maybe<Scalars['Boolean']>; color?: Maybe<Scalars['String']>; background?: Maybe<Scalars['String']>; }; export enum PotraceTurnPolicy { Turnpolicy_Black = 'TURNPOLICY_BLACK', Turnpolicy_White = 'TURNPOLICY_WHITE', Turnpolicy_Left = 'TURNPOLICY_LEFT', Turnpolicy_Right = 'TURNPOLICY_RIGHT', Turnpolicy_Minority = 'TURNPOLICY_MINORITY', Turnpolicy_Majority = 'TURNPOLICY_MAJORITY', } export type PublicUrlQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type PublicUrlQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type Query = { /** Connection to all SitePage nodes */ allSitePage?: Maybe<SitePageConnection>; /** Connection to all SitePlugin nodes */ allSitePlugin?: Maybe<SitePluginConnection>; /** Connection to all Directory nodes */ allDirectory?: Maybe<DirectoryConnection>; /** Connection to all File nodes */ allFile?: Maybe<FileConnection>; /** Connection to all ImageSharp nodes */ allImageSharp?: Maybe<ImageSharpConnection>; sitePage?: Maybe<SitePage>; sitePlugin?: Maybe<SitePlugin>; site?: Maybe<Site>; directory?: Maybe<Directory>; file?: Maybe<File>; imageSharp?: Maybe<ImageSharp>; ever?: Maybe<Ever>; }; export type QueryAllSitePageArgs = { skip?: Maybe<Scalars['Int']>; limit?: Maybe<Scalars['Int']>; sort?: Maybe<SitePageConnectionSort>; filter?: Maybe<FilterSitePage>; }; export type QueryAllSitePluginArgs = { skip?: Maybe<Scalars['Int']>; limit?: Maybe<Scalars['Int']>; sort?: Maybe<SitePluginConnectionSort>; filter?: Maybe<FilterSitePlugin>; }; export type QueryAllDirectoryArgs = { skip?: Maybe<Scalars['Int']>; limit?: Maybe<Scalars['Int']>; sort?: Maybe<DirectoryConnectionSort>; filter?: Maybe<FilterDirectory>; }; export type QueryAllFileArgs = { skip?: Maybe<Scalars['Int']>; limit?: Maybe<Scalars['Int']>; sort?: Maybe<FileConnectionSort>; filter?: Maybe<FilterFile>; }; export type QueryAllImageSharpArgs = { skip?: Maybe<Scalars['Int']>; limit?: Maybe<Scalars['Int']>; sort?: Maybe<ImageSharpConnectionSort>; filter?: Maybe<FilterImageSharp>; }; export type QuerySitePageArgs = { jsonName?: Maybe<SitePageJsonNameQueryString>; internalComponentName?: Maybe<SitePageInternalComponentNameQueryString>; path?: Maybe<SitePagePathQueryString_2>; component?: Maybe<SitePageComponentQueryString>; componentChunkName?: Maybe<SitePageComponentChunkNameQueryString>; pluginCreator?: Maybe<SitePagePluginCreatorInputObject>; pluginCreatorId?: Maybe<SitePagePluginCreatorIdQueryString_2>; componentPath?: Maybe<SitePageComponentPathQueryString>; id?: Maybe<SitePageIdQueryString_2>; internal?: Maybe<SitePageInternalInputObject_2>; }; export type QuerySitePluginArgs = { resolve?: Maybe<SitePluginResolveQueryString_2>; id?: Maybe<SitePluginIdQueryString_2>; name?: Maybe<SitePluginNameQueryString_2>; version?: Maybe<SitePluginVersionQueryString_2>; pluginOptions?: Maybe<SitePluginPluginOptionsInputObject_2>; nodeAPIs?: Maybe<SitePluginNodeApIsQueryList_2>; browserAPIs?: Maybe<SitePluginBrowserApIsQueryList_2>; ssrAPIs?: Maybe<SitePluginSsrApIsQueryList_2>; pluginFilepath?: Maybe<SitePluginPluginFilepathQueryString_2>; packageJson?: Maybe<SitePluginPackageJsonInputObject_2>; internal?: Maybe<SitePluginInternalInputObject_2>; }; export type QuerySiteArgs = { siteMetadata?: Maybe<SiteSiteMetadataInputObject_2>; port?: Maybe<SitePortQueryString_2>; host?: Maybe<SiteHostQueryString_2>; pathPrefix?: Maybe<SitePathPrefixQueryString_2>; polyfill?: Maybe<SitePolyfillQueryBoolean_2>; buildTime?: Maybe<SiteBuildTimeQueryString_2>; id?: Maybe<SiteIdQueryString_2>; internal?: Maybe<SiteInternalInputObject_2>; }; export type QueryDirectoryArgs = { id?: Maybe<DirectoryIdQueryString_2>; internal?: Maybe<DirectoryInternalInputObject_2>; sourceInstanceName?: Maybe<DirectorySourceInstanceNameQueryString_2>; absolutePath?: Maybe<DirectoryAbsolutePathQueryString_2>; relativePath?: Maybe<DirectoryRelativePathQueryString_2>; extension?: Maybe<DirectoryExtensionQueryString_2>; size?: Maybe<DirectorySizeQueryInteger_2>; prettySize?: Maybe<DirectoryPrettySizeQueryString_2>; modifiedTime?: Maybe<DirectoryModifiedTimeQueryString_2>; accessTime?: Maybe<DirectoryAccessTimeQueryString_2>; changeTime?: Maybe<DirectoryChangeTimeQueryString_2>; birthTime?: Maybe<DirectoryBirthTimeQueryString_2>; root?: Maybe<DirectoryRootQueryString_2>; dir?: Maybe<DirectoryDirQueryString_2>; base?: Maybe<DirectoryBaseQueryString_2>; ext?: Maybe<DirectoryExtQueryString_2>; name?: Maybe<DirectoryNameQueryString_2>; relativeDirectory?: Maybe<DirectoryRelativeDirectoryQueryString_2>; dev?: Maybe<DirectoryDevQueryInteger_2>; mode?: Maybe<DirectoryModeQueryInteger_2>; nlink?: Maybe<DirectoryNlinkQueryInteger_2>; uid?: Maybe<DirectoryUidQueryInteger_2>; gid?: Maybe<DirectoryGidQueryInteger_2>; rdev?: Maybe<DirectoryRdevQueryInteger_2>; ino?: Maybe<DirectoryInoQueryFloat_2>; atimeMs?: Maybe<DirectoryAtimeMsQueryFloat_2>; mtimeMs?: Maybe<DirectoryMtimeMsQueryFloat_2>; ctimeMs?: Maybe<DirectoryCtimeMsQueryFloat_2>; birthtimeMs?: Maybe<DirectoryBirthtimeMsQueryFloat_2>; atime?: Maybe<DirectoryAtimeQueryString_2>; mtime?: Maybe<DirectoryMtimeQueryString_2>; ctime?: Maybe<DirectoryCtimeQueryString_2>; birthtime?: Maybe<DirectoryBirthtimeQueryString_2>; }; export type QueryFileArgs = { id?: Maybe<FileIdQueryString_2>; internal?: Maybe<FileInternalInputObject_2>; sourceInstanceName?: Maybe<FileSourceInstanceNameQueryString_2>; absolutePath?: Maybe<FileAbsolutePathQueryString_2>; relativePath?: Maybe<FileRelativePathQueryString_2>; extension?: Maybe<FileExtensionQueryString_2>; size?: Maybe<FileSizeQueryInteger_2>; prettySize?: Maybe<FilePrettySizeQueryString_2>; modifiedTime?: Maybe<FileModifiedTimeQueryString_2>; accessTime?: Maybe<FileAccessTimeQueryString_2>; changeTime?: Maybe<FileChangeTimeQueryString_2>; birthTime?: Maybe<FileBirthTimeQueryString_2>; root?: Maybe<FileRootQueryString_2>; dir?: Maybe<FileDirQueryString_2>; base?: Maybe<FileBaseQueryString_2>; ext?: Maybe<FileExtQueryString_2>; name?: Maybe<FileNameQueryString_2>; relativeDirectory?: Maybe<FileRelativeDirectoryQueryString_2>; dev?: Maybe<FileDevQueryInteger_2>; mode?: Maybe<FileModeQueryInteger_2>; nlink?: Maybe<FileNlinkQueryInteger_2>; uid?: Maybe<FileUidQueryInteger_2>; gid?: Maybe<FileGidQueryInteger_2>; rdev?: Maybe<FileRdevQueryInteger_2>; ino?: Maybe<FileInoQueryFloat_2>; atimeMs?: Maybe<FileAtimeMsQueryFloat_2>; mtimeMs?: Maybe<FileMtimeMsQueryFloat_2>; ctimeMs?: Maybe<FileCtimeMsQueryFloat_2>; birthtimeMs?: Maybe<FileBirthtimeMsQueryFloat_2>; atime?: Maybe<FileAtimeQueryString_2>; mtime?: Maybe<FileMtimeQueryString_2>; ctime?: Maybe<FileCtimeQueryString_2>; birthtime?: Maybe<FileBirthtimeQueryString_2>; publicURL?: Maybe<PublicUrlQueryString_3>; }; export type QueryImageSharpArgs = { id?: Maybe<ImageSharpIdQueryString_2>; internal?: Maybe<ImageSharpInternalInputObject_2>; fixed?: Maybe<FixedTypeName_3>; resolutions?: Maybe<ResolutionsTypeName_3>; fluid?: Maybe<FluidTypeName_3>; sizes?: Maybe<SizesTypeName_3>; original?: Maybe<OriginalTypeName_3>; resize?: Maybe<ResizeTypeName_3>; }; export type ResizeAspectRatioQueryFloat_3 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type ResizeAspectRatioQueryFloat_4 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type ResizeHeightQueryInt_3 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type ResizeHeightQueryInt_4 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type ResizeOriginalNameQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type ResizeOriginalNameQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type ResizeSrcQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type ResizeSrcQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type ResizeTracedSvgQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type ResizeTracedSvgQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type ResizeTypeName_3 = { src?: Maybe<ResizeSrcQueryString_3>; tracedSVG?: Maybe<ResizeTracedSvgQueryString_3>; width?: Maybe<ResizeWidthQueryInt_3>; height?: Maybe<ResizeHeightQueryInt_3>; aspectRatio?: Maybe<ResizeAspectRatioQueryFloat_3>; originalName?: Maybe<ResizeOriginalNameQueryString_3>; }; export type ResizeTypeName_4 = { src?: Maybe<ResizeSrcQueryString_4>; tracedSVG?: Maybe<ResizeTracedSvgQueryString_4>; width?: Maybe<ResizeWidthQueryInt_4>; height?: Maybe<ResizeHeightQueryInt_4>; aspectRatio?: Maybe<ResizeAspectRatioQueryFloat_4>; originalName?: Maybe<ResizeOriginalNameQueryString_4>; }; export type ResizeWidthQueryInt_3 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type ResizeWidthQueryInt_4 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type ResolutionsAspectRatioQueryFloat_3 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type ResolutionsAspectRatioQueryFloat_4 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type ResolutionsBase64QueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type ResolutionsBase64QueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type ResolutionsHeightQueryFloat_3 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type ResolutionsHeightQueryFloat_4 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type ResolutionsOriginalNameQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type ResolutionsOriginalNameQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type ResolutionsSrcQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type ResolutionsSrcQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type ResolutionsSrcSetQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type ResolutionsSrcSetQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type ResolutionsSrcSetWebpQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type ResolutionsSrcSetWebpQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type ResolutionsSrcWebpQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type ResolutionsSrcWebpQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type ResolutionsTracedSvgQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type ResolutionsTracedSvgQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type ResolutionsTypeName_3 = { base64?: Maybe<ResolutionsBase64QueryString_3>; tracedSVG?: Maybe<ResolutionsTracedSvgQueryString_3>; aspectRatio?: Maybe<ResolutionsAspectRatioQueryFloat_3>; width?: Maybe<ResolutionsWidthQueryFloat_3>; height?: Maybe<ResolutionsHeightQueryFloat_3>; src?: Maybe<ResolutionsSrcQueryString_3>; srcSet?: Maybe<ResolutionsSrcSetQueryString_3>; srcWebp?: Maybe<ResolutionsSrcWebpQueryString_3>; srcSetWebp?: Maybe<ResolutionsSrcSetWebpQueryString_3>; originalName?: Maybe<ResolutionsOriginalNameQueryString_3>; }; export type ResolutionsTypeName_4 = { base64?: Maybe<ResolutionsBase64QueryString_4>; tracedSVG?: Maybe<ResolutionsTracedSvgQueryString_4>; aspectRatio?: Maybe<ResolutionsAspectRatioQueryFloat_4>; width?: Maybe<ResolutionsWidthQueryFloat_4>; height?: Maybe<ResolutionsHeightQueryFloat_4>; src?: Maybe<ResolutionsSrcQueryString_4>; srcSet?: Maybe<ResolutionsSrcSetQueryString_4>; srcWebp?: Maybe<ResolutionsSrcWebpQueryString_4>; srcSetWebp?: Maybe<ResolutionsSrcSetWebpQueryString_4>; originalName?: Maybe<ResolutionsOriginalNameQueryString_4>; }; export type ResolutionsWidthQueryFloat_3 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type ResolutionsWidthQueryFloat_4 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; /** Node of type Site */ export type Site = Node & { /** The id of this node. */ id: Scalars['ID']; /** The parent of this node. */ parent?: Maybe<Node>; /** The children of this node. */ children?: Maybe<Array<Maybe<Node>>>; siteMetadata?: Maybe<SiteMetadata_2>; port?: Maybe<Scalars['Date']>; host?: Maybe<Scalars['String']>; pathPrefix?: Maybe<Scalars['String']>; polyfill?: Maybe<Scalars['Boolean']>; buildTime?: Maybe<Scalars['Date']>; internal?: Maybe<Internal_12>; }; /** Node of type Site */ export type SitePortArgs = { formatString?: Maybe<Scalars['String']>; fromNow?: Maybe<Scalars['Boolean']>; difference?: Maybe<Scalars['String']>; locale?: Maybe<Scalars['String']>; }; /** Node of type Site */ export type SiteBuildTimeArgs = { formatString?: Maybe<Scalars['String']>; fromNow?: Maybe<Scalars['Boolean']>; difference?: Maybe<Scalars['String']>; locale?: Maybe<Scalars['String']>; }; export type SiteBuildTimeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SiteHostQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SiteIdQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SiteInternalContentDigestQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SiteInternalInputObject_2 = { contentDigest?: Maybe<SiteInternalContentDigestQueryString_2>; type?: Maybe<SiteInternalTypeQueryString_2>; owner?: Maybe<SiteInternalOwnerQueryString_2>; }; export type SiteInternalOwnerQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SiteInternalTypeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SiteMetadata_2 = { title?: Maybe<Scalars['String']>; description?: Maybe<Scalars['String']>; author?: Maybe<Scalars['String']>; }; /** Node of type SitePage */ export type SitePage = Node & { /** The id of this node. */ id: Scalars['ID']; /** The parent of this node. */ parent?: Maybe<Node>; /** The children of this node. */ children?: Maybe<Array<Maybe<Node>>>; jsonName?: Maybe<Scalars['String']>; internalComponentName?: Maybe<Scalars['String']>; path?: Maybe<Scalars['String']>; component?: Maybe<Scalars['String']>; componentChunkName?: Maybe<Scalars['String']>; pluginCreator?: Maybe<SitePlugin>; pluginCreatorId?: Maybe<Scalars['String']>; componentPath?: Maybe<Scalars['String']>; internal?: Maybe<Internal_7>; }; export type SitePageComponentChunkNameQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageComponentPathQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageComponentQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; /** A connection to a list of items. */ export type SitePageConnection = { /** Information to aid in pagination. */ pageInfo: PageInfo; /** A list of edges. */ edges?: Maybe<Array<Maybe<SitePageEdge>>>; totalCount?: Maybe<Scalars['Int']>; distinct?: Maybe<Array<Maybe<Scalars['String']>>>; group?: Maybe<Array<Maybe<SitePageGroupConnectionConnection>>>; }; /** A connection to a list of items. */ export type SitePageConnectionDistinctArgs = { field?: Maybe<SitePageDistinctEnum>; }; /** A connection to a list of items. */ export type SitePageConnectionGroupArgs = { skip?: Maybe<Scalars['Int']>; limit?: Maybe<Scalars['Int']>; field?: Maybe<SitePageGroupEnum>; }; export type SitePageConnectionComponentChunkNameQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionComponentPathQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionComponentQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionIdQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionInternalComponentNameQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionInternalContentDigestQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionInternalDescriptionQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionInternalInputObject_2 = { type?: Maybe<SitePageConnectionInternalTypeQueryString_2>; contentDigest?: Maybe<SitePageConnectionInternalContentDigestQueryString_2>; description?: Maybe<SitePageConnectionInternalDescriptionQueryString>; owner?: Maybe<SitePageConnectionInternalOwnerQueryString_2>; }; export type SitePageConnectionInternalOwnerQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionInternalTypeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionJsonNameQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPathQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorBrowserApIsQueryList = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorIdQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorIdQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorInputObject = { resolve?: Maybe<SitePageConnectionPluginCreatorResolveQueryString>; id?: Maybe<SitePageConnectionPluginCreatorIdQueryString>; name?: Maybe<SitePageConnectionPluginCreatorNameQueryString>; version?: Maybe<SitePageConnectionPluginCreatorVersionQueryString>; pluginOptions?: Maybe< SitePageConnectionPluginCreatorPluginOptionsInputObject >; nodeAPIs?: Maybe<SitePageConnectionPluginCreatorNodeApIsQueryList>; browserAPIs?: Maybe<SitePageConnectionPluginCreatorBrowserApIsQueryList>; ssrAPIs?: Maybe<SitePageConnectionPluginCreatorSsrApIsQueryList>; pluginFilepath?: Maybe< SitePageConnectionPluginCreatorPluginFilepathQueryString >; packageJson?: Maybe<SitePageConnectionPluginCreatorPackageJsonInputObject>; internal?: Maybe<SitePageConnectionPluginCreatorInternalInputObject>; }; export type SitePageConnectionPluginCreatorInternalContentDigestQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorInternalInputObject = { contentDigest?: Maybe< SitePageConnectionPluginCreatorInternalContentDigestQueryString >; type?: Maybe<SitePageConnectionPluginCreatorInternalTypeQueryString>; owner?: Maybe<SitePageConnectionPluginCreatorInternalOwnerQueryString>; }; export type SitePageConnectionPluginCreatorInternalOwnerQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorInternalTypeQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorNameQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorNodeApIsQueryList = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorPackageJsonAuthorQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorPackageJsonDependenciesInputObject = { name?: Maybe< SitePageConnectionPluginCreatorPackageJsonDependenciesNameQueryString >; version?: Maybe< SitePageConnectionPluginCreatorPackageJsonDependenciesVersionQueryString >; }; export type SitePageConnectionPluginCreatorPackageJsonDependenciesNameQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorPackageJsonDependenciesQueryList = { elemMatch?: Maybe< SitePageConnectionPluginCreatorPackageJsonDependenciesInputObject >; }; export type SitePageConnectionPluginCreatorPackageJsonDependenciesVersionQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorPackageJsonDescriptionQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorPackageJsonDevDependenciesInputObject = { name?: Maybe< SitePageConnectionPluginCreatorPackageJsonDevDependenciesNameQueryString >; version?: Maybe< SitePageConnectionPluginCreatorPackageJsonDevDependenciesVersionQueryString >; }; export type SitePageConnectionPluginCreatorPackageJsonDevDependenciesNameQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorPackageJsonDevDependenciesQueryList = { elemMatch?: Maybe< SitePageConnectionPluginCreatorPackageJsonDevDependenciesInputObject >; }; export type SitePageConnectionPluginCreatorPackageJsonDevDependenciesVersionQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorPackageJsonInputObject = { name?: Maybe<SitePageConnectionPluginCreatorPackageJsonNameQueryString>; description?: Maybe< SitePageConnectionPluginCreatorPackageJsonDescriptionQueryString >; version?: Maybe<SitePageConnectionPluginCreatorPackageJsonVersionQueryString>; main?: Maybe<SitePageConnectionPluginCreatorPackageJsonMainQueryString>; author?: Maybe<SitePageConnectionPluginCreatorPackageJsonAuthorQueryString>; license?: Maybe<SitePageConnectionPluginCreatorPackageJsonLicenseQueryString>; dependencies?: Maybe< SitePageConnectionPluginCreatorPackageJsonDependenciesQueryList >; devDependencies?: Maybe< SitePageConnectionPluginCreatorPackageJsonDevDependenciesQueryList >; peerDependencies?: Maybe< SitePageConnectionPluginCreatorPackageJsonPeerDependenciesQueryList >; keywords?: Maybe<SitePageConnectionPluginCreatorPackageJsonKeywordsQueryList>; }; export type SitePageConnectionPluginCreatorPackageJsonKeywordsQueryList = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorPackageJsonLicenseQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorPackageJsonMainQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorPackageJsonNameQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorPackageJsonPeerDependenciesInputObject = { name?: Maybe< SitePageConnectionPluginCreatorPackageJsonPeerDependenciesNameQueryString >; version?: Maybe< SitePageConnectionPluginCreatorPackageJsonPeerDependenciesVersionQueryString >; }; export type SitePageConnectionPluginCreatorPackageJsonPeerDependenciesNameQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorPackageJsonPeerDependenciesQueryList = { elemMatch?: Maybe< SitePageConnectionPluginCreatorPackageJsonPeerDependenciesInputObject >; }; export type SitePageConnectionPluginCreatorPackageJsonPeerDependenciesVersionQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorPackageJsonVersionQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorPluginFilepathQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorPluginOptionsBackgroundColorQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorPluginOptionsDisplayQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorPluginOptionsFieldNameQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorPluginOptionsIconQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorPluginOptionsInputObject = { typeName?: Maybe< SitePageConnectionPluginCreatorPluginOptionsTypeNameQueryString >; fieldName?: Maybe< SitePageConnectionPluginCreatorPluginOptionsFieldNameQueryString >; url?: Maybe<SitePageConnectionPluginCreatorPluginOptionsUrlQueryString>; name?: Maybe<SitePageConnectionPluginCreatorPluginOptionsNameQueryString>; path?: Maybe<SitePageConnectionPluginCreatorPluginOptionsPathQueryString>; short_name?: Maybe< SitePageConnectionPluginCreatorPluginOptionsShortNameQueryString >; start_url?: Maybe< SitePageConnectionPluginCreatorPluginOptionsStartUrlQueryString >; background_color?: Maybe< SitePageConnectionPluginCreatorPluginOptionsBackgroundColorQueryString >; theme_color?: Maybe< SitePageConnectionPluginCreatorPluginOptionsThemeColorQueryString >; display?: Maybe< SitePageConnectionPluginCreatorPluginOptionsDisplayQueryString >; icon?: Maybe<SitePageConnectionPluginCreatorPluginOptionsIconQueryString>; pathCheck?: Maybe< SitePageConnectionPluginCreatorPluginOptionsPathCheckQueryBoolean >; }; export type SitePageConnectionPluginCreatorPluginOptionsNameQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorPluginOptionsPathCheckQueryBoolean = { eq?: Maybe<Scalars['Boolean']>; ne?: Maybe<Scalars['Boolean']>; in?: Maybe<Array<Maybe<Scalars['Boolean']>>>; nin?: Maybe<Array<Maybe<Scalars['Boolean']>>>; }; export type SitePageConnectionPluginCreatorPluginOptionsPathQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorPluginOptionsShortNameQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorPluginOptionsStartUrlQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorPluginOptionsThemeColorQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorPluginOptionsTypeNameQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorPluginOptionsUrlQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorResolveQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorSsrApIsQueryList = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionPluginCreatorVersionQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageConnectionSort = { fields: Array<Maybe<SitePageConnectionSortByFieldsEnum>>; order?: Maybe<Array<Maybe<SitePageConnectionSortOrderValues>>>; }; export enum SitePageConnectionSortByFieldsEnum { JsonName = 'jsonName', InternalComponentName = 'internalComponentName', Path = 'path', Component = 'component', ComponentChunkName = 'componentChunkName', PluginCreator___Node = 'pluginCreator___NODE', PluginCreatorId = 'pluginCreatorId', ComponentPath = 'componentPath', Id = 'id', Internal___Type = 'internal___type', Internal___ContentDigest = 'internal___contentDigest', Internal___Description = 'internal___description', Internal___Owner = 'internal___owner', } export enum SitePageConnectionSortOrderValues { Asc = 'ASC', Desc = 'DESC', } export enum SitePageDistinctEnum { JsonName = 'jsonName', InternalComponentName = 'internalComponentName', Path = 'path', Component = 'component', ComponentChunkName = 'componentChunkName', PluginCreator___Node = 'pluginCreator___NODE', PluginCreatorId = 'pluginCreatorId', ComponentPath = 'componentPath', Id = 'id', Internal___Type = 'internal___type', Internal___ContentDigest = 'internal___contentDigest', Internal___Description = 'internal___description', Internal___Owner = 'internal___owner', } /** An edge in a connection. */ export type SitePageEdge = { /** The item at the end of the edge */ node?: Maybe<SitePage>; /** The next edge in the connection */ next?: Maybe<SitePage>; /** The previous edge in the connection */ previous?: Maybe<SitePage>; }; /** A connection to a list of items. */ export type SitePageGroupConnectionConnection = { /** Information to aid in pagination. */ pageInfo: PageInfo; /** A list of edges. */ edges?: Maybe<Array<Maybe<SitePageGroupConnectionEdge>>>; field?: Maybe<Scalars['String']>; fieldValue?: Maybe<Scalars['String']>; totalCount?: Maybe<Scalars['Int']>; }; /** An edge in a connection. */ export type SitePageGroupConnectionEdge = { /** The item at the end of the edge */ node?: Maybe<SitePage>; /** The next edge in the connection */ next?: Maybe<SitePage>; /** The previous edge in the connection */ previous?: Maybe<SitePage>; }; export enum SitePageGroupEnum { JsonName = 'jsonName', InternalComponentName = 'internalComponentName', Path = 'path', Component = 'component', ComponentChunkName = 'componentChunkName', PluginCreator___Node = 'pluginCreator___NODE', PluginCreatorId = 'pluginCreatorId', ComponentPath = 'componentPath', Id = 'id', Internal___Type = 'internal___type', Internal___ContentDigest = 'internal___contentDigest', Internal___Description = 'internal___description', Internal___Owner = 'internal___owner', } export type SitePageIdQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageInternalComponentNameQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageInternalContentDigestQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageInternalDescriptionQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageInternalInputObject_2 = { type?: Maybe<SitePageInternalTypeQueryString_2>; contentDigest?: Maybe<SitePageInternalContentDigestQueryString_2>; description?: Maybe<SitePageInternalDescriptionQueryString>; owner?: Maybe<SitePageInternalOwnerQueryString_2>; }; export type SitePageInternalOwnerQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageInternalTypeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePageJsonNameQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePathQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorBrowserApIsQueryList = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorIdQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorIdQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorInputObject = { resolve?: Maybe<SitePagePluginCreatorResolveQueryString>; id?: Maybe<SitePagePluginCreatorIdQueryString>; name?: Maybe<SitePagePluginCreatorNameQueryString>; version?: Maybe<SitePagePluginCreatorVersionQueryString>; pluginOptions?: Maybe<SitePagePluginCreatorPluginOptionsInputObject>; nodeAPIs?: Maybe<SitePagePluginCreatorNodeApIsQueryList>; browserAPIs?: Maybe<SitePagePluginCreatorBrowserApIsQueryList>; ssrAPIs?: Maybe<SitePagePluginCreatorSsrApIsQueryList>; pluginFilepath?: Maybe<SitePagePluginCreatorPluginFilepathQueryString>; packageJson?: Maybe<SitePagePluginCreatorPackageJsonInputObject>; internal?: Maybe<SitePagePluginCreatorInternalInputObject>; }; export type SitePagePluginCreatorInternalContentDigestQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorInternalInputObject = { contentDigest?: Maybe<SitePagePluginCreatorInternalContentDigestQueryString>; type?: Maybe<SitePagePluginCreatorInternalTypeQueryString>; owner?: Maybe<SitePagePluginCreatorInternalOwnerQueryString>; }; export type SitePagePluginCreatorInternalOwnerQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorInternalTypeQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorNameQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorNodeApIsQueryList = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorPackageJsonAuthorQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorPackageJsonDependenciesInputObject = { name?: Maybe<SitePagePluginCreatorPackageJsonDependenciesNameQueryString>; version?: Maybe< SitePagePluginCreatorPackageJsonDependenciesVersionQueryString >; }; export type SitePagePluginCreatorPackageJsonDependenciesNameQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorPackageJsonDependenciesQueryList = { elemMatch?: Maybe<SitePagePluginCreatorPackageJsonDependenciesInputObject>; }; export type SitePagePluginCreatorPackageJsonDependenciesVersionQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorPackageJsonDescriptionQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorPackageJsonDevDependenciesInputObject = { name?: Maybe<SitePagePluginCreatorPackageJsonDevDependenciesNameQueryString>; version?: Maybe< SitePagePluginCreatorPackageJsonDevDependenciesVersionQueryString >; }; export type SitePagePluginCreatorPackageJsonDevDependenciesNameQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorPackageJsonDevDependenciesQueryList = { elemMatch?: Maybe<SitePagePluginCreatorPackageJsonDevDependenciesInputObject>; }; export type SitePagePluginCreatorPackageJsonDevDependenciesVersionQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorPackageJsonInputObject = { name?: Maybe<SitePagePluginCreatorPackageJsonNameQueryString>; description?: Maybe<SitePagePluginCreatorPackageJsonDescriptionQueryString>; version?: Maybe<SitePagePluginCreatorPackageJsonVersionQueryString>; main?: Maybe<SitePagePluginCreatorPackageJsonMainQueryString>; author?: Maybe<SitePagePluginCreatorPackageJsonAuthorQueryString>; license?: Maybe<SitePagePluginCreatorPackageJsonLicenseQueryString>; dependencies?: Maybe<SitePagePluginCreatorPackageJsonDependenciesQueryList>; devDependencies?: Maybe< SitePagePluginCreatorPackageJsonDevDependenciesQueryList >; peerDependencies?: Maybe< SitePagePluginCreatorPackageJsonPeerDependenciesQueryList >; keywords?: Maybe<SitePagePluginCreatorPackageJsonKeywordsQueryList>; }; export type SitePagePluginCreatorPackageJsonKeywordsQueryList = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorPackageJsonLicenseQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorPackageJsonMainQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorPackageJsonNameQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorPackageJsonPeerDependenciesInputObject = { name?: Maybe<SitePagePluginCreatorPackageJsonPeerDependenciesNameQueryString>; version?: Maybe< SitePagePluginCreatorPackageJsonPeerDependenciesVersionQueryString >; }; export type SitePagePluginCreatorPackageJsonPeerDependenciesNameQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorPackageJsonPeerDependenciesQueryList = { elemMatch?: Maybe< SitePagePluginCreatorPackageJsonPeerDependenciesInputObject >; }; export type SitePagePluginCreatorPackageJsonPeerDependenciesVersionQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorPackageJsonVersionQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorPluginFilepathQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorPluginOptionsBackgroundColorQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorPluginOptionsDisplayQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorPluginOptionsFieldNameQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorPluginOptionsIconQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorPluginOptionsInputObject = { typeName?: Maybe<SitePagePluginCreatorPluginOptionsTypeNameQueryString>; fieldName?: Maybe<SitePagePluginCreatorPluginOptionsFieldNameQueryString>; url?: Maybe<SitePagePluginCreatorPluginOptionsUrlQueryString>; name?: Maybe<SitePagePluginCreatorPluginOptionsNameQueryString>; path?: Maybe<SitePagePluginCreatorPluginOptionsPathQueryString>; short_name?: Maybe<SitePagePluginCreatorPluginOptionsShortNameQueryString>; start_url?: Maybe<SitePagePluginCreatorPluginOptionsStartUrlQueryString>; background_color?: Maybe< SitePagePluginCreatorPluginOptionsBackgroundColorQueryString >; theme_color?: Maybe<SitePagePluginCreatorPluginOptionsThemeColorQueryString>; display?: Maybe<SitePagePluginCreatorPluginOptionsDisplayQueryString>; icon?: Maybe<SitePagePluginCreatorPluginOptionsIconQueryString>; pathCheck?: Maybe<SitePagePluginCreatorPluginOptionsPathCheckQueryBoolean>; }; export type SitePagePluginCreatorPluginOptionsNameQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorPluginOptionsPathCheckQueryBoolean = { eq?: Maybe<Scalars['Boolean']>; ne?: Maybe<Scalars['Boolean']>; in?: Maybe<Array<Maybe<Scalars['Boolean']>>>; nin?: Maybe<Array<Maybe<Scalars['Boolean']>>>; }; export type SitePagePluginCreatorPluginOptionsPathQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorPluginOptionsShortNameQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorPluginOptionsStartUrlQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorPluginOptionsThemeColorQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorPluginOptionsTypeNameQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorPluginOptionsUrlQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorResolveQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorSsrApIsQueryList = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePagePluginCreatorVersionQueryString = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePathPrefixQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; /** Node of type SitePlugin */ export type SitePlugin = Node & { /** The id of this node. */ id: Scalars['ID']; /** The parent of this node. */ parent?: Maybe<Node>; /** The children of this node. */ children?: Maybe<Array<Maybe<Node>>>; resolve?: Maybe<Scalars['String']>; name?: Maybe<Scalars['String']>; version?: Maybe<Scalars['String']>; pluginOptions?: Maybe<PluginOptions_2>; nodeAPIs?: Maybe<Array<Maybe<Scalars['String']>>>; browserAPIs?: Maybe<Array<Maybe<Scalars['String']>>>; ssrAPIs?: Maybe<Array<Maybe<Scalars['String']>>>; pluginFilepath?: Maybe<Scalars['String']>; packageJson?: Maybe<PackageJson_2>; internal?: Maybe<Internal_8>; }; export type SitePluginBrowserApIsQueryList_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; /** A connection to a list of items. */ export type SitePluginConnection = { /** Information to aid in pagination. */ pageInfo: PageInfo; /** A list of edges. */ edges?: Maybe<Array<Maybe<SitePluginEdge>>>; totalCount?: Maybe<Scalars['Int']>; distinct?: Maybe<Array<Maybe<Scalars['String']>>>; group?: Maybe<Array<Maybe<SitePluginGroupConnectionConnection>>>; }; /** A connection to a list of items. */ export type SitePluginConnectionDistinctArgs = { field?: Maybe<SitePluginDistinctEnum>; }; /** A connection to a list of items. */ export type SitePluginConnectionGroupArgs = { skip?: Maybe<Scalars['Int']>; limit?: Maybe<Scalars['Int']>; field?: Maybe<SitePluginGroupEnum>; }; export type SitePluginConnectionBrowserApIsQueryList_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionIdQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionInternalContentDigestQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionInternalInputObject_2 = { contentDigest?: Maybe<SitePluginConnectionInternalContentDigestQueryString_2>; type?: Maybe<SitePluginConnectionInternalTypeQueryString_2>; owner?: Maybe<SitePluginConnectionInternalOwnerQueryString_2>; }; export type SitePluginConnectionInternalOwnerQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionInternalTypeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionNameQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionNodeApIsQueryList_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionPackageJsonAuthorQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionPackageJsonDependenciesInputObject_2 = { name?: Maybe<SitePluginConnectionPackageJsonDependenciesNameQueryString_2>; version?: Maybe< SitePluginConnectionPackageJsonDependenciesVersionQueryString_2 >; }; export type SitePluginConnectionPackageJsonDependenciesNameQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionPackageJsonDependenciesQueryList_2 = { elemMatch?: Maybe<SitePluginConnectionPackageJsonDependenciesInputObject_2>; }; export type SitePluginConnectionPackageJsonDependenciesVersionQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionPackageJsonDescriptionQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionPackageJsonDevDependenciesInputObject_2 = { name?: Maybe<SitePluginConnectionPackageJsonDevDependenciesNameQueryString_2>; version?: Maybe< SitePluginConnectionPackageJsonDevDependenciesVersionQueryString_2 >; }; export type SitePluginConnectionPackageJsonDevDependenciesNameQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionPackageJsonDevDependenciesQueryList_2 = { elemMatch?: Maybe< SitePluginConnectionPackageJsonDevDependenciesInputObject_2 >; }; export type SitePluginConnectionPackageJsonDevDependenciesVersionQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionPackageJsonInputObject_2 = { name?: Maybe<SitePluginConnectionPackageJsonNameQueryString_2>; description?: Maybe<SitePluginConnectionPackageJsonDescriptionQueryString_2>; version?: Maybe<SitePluginConnectionPackageJsonVersionQueryString_2>; main?: Maybe<SitePluginConnectionPackageJsonMainQueryString_2>; author?: Maybe<SitePluginConnectionPackageJsonAuthorQueryString_2>; license?: Maybe<SitePluginConnectionPackageJsonLicenseQueryString_2>; dependencies?: Maybe<SitePluginConnectionPackageJsonDependenciesQueryList_2>; devDependencies?: Maybe< SitePluginConnectionPackageJsonDevDependenciesQueryList_2 >; peerDependencies?: Maybe< SitePluginConnectionPackageJsonPeerDependenciesQueryList_2 >; keywords?: Maybe<SitePluginConnectionPackageJsonKeywordsQueryList_2>; }; export type SitePluginConnectionPackageJsonKeywordsQueryList_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionPackageJsonLicenseQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionPackageJsonMainQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionPackageJsonNameQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionPackageJsonPeerDependenciesInputObject_2 = { name?: Maybe< SitePluginConnectionPackageJsonPeerDependenciesNameQueryString_2 >; version?: Maybe< SitePluginConnectionPackageJsonPeerDependenciesVersionQueryString_2 >; }; export type SitePluginConnectionPackageJsonPeerDependenciesNameQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionPackageJsonPeerDependenciesQueryList_2 = { elemMatch?: Maybe< SitePluginConnectionPackageJsonPeerDependenciesInputObject_2 >; }; export type SitePluginConnectionPackageJsonPeerDependenciesVersionQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionPackageJsonVersionQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionPluginFilepathQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionPluginOptionsBackgroundColorQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionPluginOptionsDisplayQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionPluginOptionsFieldNameQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionPluginOptionsIconQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionPluginOptionsInputObject_2 = { typeName?: Maybe<SitePluginConnectionPluginOptionsTypeNameQueryString_2>; fieldName?: Maybe<SitePluginConnectionPluginOptionsFieldNameQueryString_2>; url?: Maybe<SitePluginConnectionPluginOptionsUrlQueryString_2>; name?: Maybe<SitePluginConnectionPluginOptionsNameQueryString_2>; path?: Maybe<SitePluginConnectionPluginOptionsPathQueryString_2>; short_name?: Maybe<SitePluginConnectionPluginOptionsShortNameQueryString_2>; start_url?: Maybe<SitePluginConnectionPluginOptionsStartUrlQueryString_2>; background_color?: Maybe< SitePluginConnectionPluginOptionsBackgroundColorQueryString_2 >; theme_color?: Maybe<SitePluginConnectionPluginOptionsThemeColorQueryString_2>; display?: Maybe<SitePluginConnectionPluginOptionsDisplayQueryString_2>; icon?: Maybe<SitePluginConnectionPluginOptionsIconQueryString_2>; pathCheck?: Maybe<SitePluginConnectionPluginOptionsPathCheckQueryBoolean_2>; }; export type SitePluginConnectionPluginOptionsNameQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionPluginOptionsPathCheckQueryBoolean_2 = { eq?: Maybe<Scalars['Boolean']>; ne?: Maybe<Scalars['Boolean']>; in?: Maybe<Array<Maybe<Scalars['Boolean']>>>; nin?: Maybe<Array<Maybe<Scalars['Boolean']>>>; }; export type SitePluginConnectionPluginOptionsPathQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionPluginOptionsShortNameQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionPluginOptionsStartUrlQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionPluginOptionsThemeColorQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionPluginOptionsTypeNameQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionPluginOptionsUrlQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionResolveQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionSort = { fields: Array<Maybe<SitePluginConnectionSortByFieldsEnum>>; order?: Maybe<Array<Maybe<SitePluginConnectionSortOrderValues>>>; }; export enum SitePluginConnectionSortByFieldsEnum { Resolve = 'resolve', Id = 'id', Name = 'name', Version = 'version', PluginOptions___TypeName = 'pluginOptions___typeName', PluginOptions___FieldName = 'pluginOptions___fieldName', PluginOptions___Url = 'pluginOptions___url', PluginOptions___Name = 'pluginOptions___name', PluginOptions___Path = 'pluginOptions___path', PluginOptions___Short_Name = 'pluginOptions___short_name', PluginOptions___Start_Url = 'pluginOptions___start_url', PluginOptions___Background_Color = 'pluginOptions___background_color', PluginOptions___Theme_Color = 'pluginOptions___theme_color', PluginOptions___Display = 'pluginOptions___display', PluginOptions___Icon = 'pluginOptions___icon', PluginOptions___PathCheck = 'pluginOptions___pathCheck', NodeApIs = 'nodeAPIs', BrowserApIs = 'browserAPIs', SsrApIs = 'ssrAPIs', PluginFilepath = 'pluginFilepath', PackageJson___Name = 'packageJson___name', PackageJson___Description = 'packageJson___description', PackageJson___Version = 'packageJson___version', PackageJson___Main = 'packageJson___main', PackageJson___Author = 'packageJson___author', PackageJson___License = 'packageJson___license', PackageJson___Dependencies = 'packageJson___dependencies', PackageJson___DevDependencies = 'packageJson___devDependencies', PackageJson___PeerDependencies = 'packageJson___peerDependencies', PackageJson___Keywords = 'packageJson___keywords', Internal___ContentDigest = 'internal___contentDigest', Internal___Type = 'internal___type', Internal___Owner = 'internal___owner', } export enum SitePluginConnectionSortOrderValues { Asc = 'ASC', Desc = 'DESC', } export type SitePluginConnectionSsrApIsQueryList_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginConnectionVersionQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export enum SitePluginDistinctEnum { Resolve = 'resolve', Id = 'id', Name = 'name', Version = 'version', PluginOptions___TypeName = 'pluginOptions___typeName', PluginOptions___FieldName = 'pluginOptions___fieldName', PluginOptions___Url = 'pluginOptions___url', PluginOptions___Name = 'pluginOptions___name', PluginOptions___Path = 'pluginOptions___path', PluginOptions___Short_Name = 'pluginOptions___short_name', PluginOptions___Start_Url = 'pluginOptions___start_url', PluginOptions___Background_Color = 'pluginOptions___background_color', PluginOptions___Theme_Color = 'pluginOptions___theme_color', PluginOptions___Display = 'pluginOptions___display', PluginOptions___Icon = 'pluginOptions___icon', PluginOptions___PathCheck = 'pluginOptions___pathCheck', NodeApIs = 'nodeAPIs', BrowserApIs = 'browserAPIs', SsrApIs = 'ssrAPIs', PluginFilepath = 'pluginFilepath', PackageJson___Name = 'packageJson___name', PackageJson___Description = 'packageJson___description', PackageJson___Version = 'packageJson___version', PackageJson___Main = 'packageJson___main', PackageJson___Author = 'packageJson___author', PackageJson___License = 'packageJson___license', PackageJson___Dependencies = 'packageJson___dependencies', PackageJson___DevDependencies = 'packageJson___devDependencies', PackageJson___PeerDependencies = 'packageJson___peerDependencies', PackageJson___Keywords = 'packageJson___keywords', Internal___ContentDigest = 'internal___contentDigest', Internal___Type = 'internal___type', Internal___Owner = 'internal___owner', } /** An edge in a connection. */ export type SitePluginEdge = { /** The item at the end of the edge */ node?: Maybe<SitePlugin>; /** The next edge in the connection */ next?: Maybe<SitePlugin>; /** The previous edge in the connection */ previous?: Maybe<SitePlugin>; }; /** A connection to a list of items. */ export type SitePluginGroupConnectionConnection = { /** Information to aid in pagination. */ pageInfo: PageInfo; /** A list of edges. */ edges?: Maybe<Array<Maybe<SitePluginGroupConnectionEdge>>>; field?: Maybe<Scalars['String']>; fieldValue?: Maybe<Scalars['String']>; totalCount?: Maybe<Scalars['Int']>; }; /** An edge in a connection. */ export type SitePluginGroupConnectionEdge = { /** The item at the end of the edge */ node?: Maybe<SitePlugin>; /** The next edge in the connection */ next?: Maybe<SitePlugin>; /** The previous edge in the connection */ previous?: Maybe<SitePlugin>; }; export enum SitePluginGroupEnum { Resolve = 'resolve', Id = 'id', Name = 'name', Version = 'version', PluginOptions___TypeName = 'pluginOptions___typeName', PluginOptions___FieldName = 'pluginOptions___fieldName', PluginOptions___Url = 'pluginOptions___url', PluginOptions___Name = 'pluginOptions___name', PluginOptions___Path = 'pluginOptions___path', PluginOptions___Short_Name = 'pluginOptions___short_name', PluginOptions___Start_Url = 'pluginOptions___start_url', PluginOptions___Background_Color = 'pluginOptions___background_color', PluginOptions___Theme_Color = 'pluginOptions___theme_color', PluginOptions___Display = 'pluginOptions___display', PluginOptions___Icon = 'pluginOptions___icon', PluginOptions___PathCheck = 'pluginOptions___pathCheck', NodeApIs = 'nodeAPIs', BrowserApIs = 'browserAPIs', SsrApIs = 'ssrAPIs', PluginFilepath = 'pluginFilepath', PackageJson___Name = 'packageJson___name', PackageJson___Description = 'packageJson___description', PackageJson___Version = 'packageJson___version', PackageJson___Main = 'packageJson___main', PackageJson___Author = 'packageJson___author', PackageJson___License = 'packageJson___license', PackageJson___Dependencies = 'packageJson___dependencies', PackageJson___DevDependencies = 'packageJson___devDependencies', PackageJson___PeerDependencies = 'packageJson___peerDependencies', PackageJson___Keywords = 'packageJson___keywords', Internal___ContentDigest = 'internal___contentDigest', Internal___Type = 'internal___type', Internal___Owner = 'internal___owner', } export type SitePluginIdQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginInternalContentDigestQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginInternalInputObject_2 = { contentDigest?: Maybe<SitePluginInternalContentDigestQueryString_2>; type?: Maybe<SitePluginInternalTypeQueryString_2>; owner?: Maybe<SitePluginInternalOwnerQueryString_2>; }; export type SitePluginInternalOwnerQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginInternalTypeQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginNameQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginNodeApIsQueryList_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginPackageJsonAuthorQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginPackageJsonDependenciesInputObject_2 = { name?: Maybe<SitePluginPackageJsonDependenciesNameQueryString_2>; version?: Maybe<SitePluginPackageJsonDependenciesVersionQueryString_2>; }; export type SitePluginPackageJsonDependenciesNameQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginPackageJsonDependenciesQueryList_2 = { elemMatch?: Maybe<SitePluginPackageJsonDependenciesInputObject_2>; }; export type SitePluginPackageJsonDependenciesVersionQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginPackageJsonDescriptionQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginPackageJsonDevDependenciesInputObject_2 = { name?: Maybe<SitePluginPackageJsonDevDependenciesNameQueryString_2>; version?: Maybe<SitePluginPackageJsonDevDependenciesVersionQueryString_2>; }; export type SitePluginPackageJsonDevDependenciesNameQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginPackageJsonDevDependenciesQueryList_2 = { elemMatch?: Maybe<SitePluginPackageJsonDevDependenciesInputObject_2>; }; export type SitePluginPackageJsonDevDependenciesVersionQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginPackageJsonInputObject_2 = { name?: Maybe<SitePluginPackageJsonNameQueryString_2>; description?: Maybe<SitePluginPackageJsonDescriptionQueryString_2>; version?: Maybe<SitePluginPackageJsonVersionQueryString_2>; main?: Maybe<SitePluginPackageJsonMainQueryString_2>; author?: Maybe<SitePluginPackageJsonAuthorQueryString_2>; license?: Maybe<SitePluginPackageJsonLicenseQueryString_2>; dependencies?: Maybe<SitePluginPackageJsonDependenciesQueryList_2>; devDependencies?: Maybe<SitePluginPackageJsonDevDependenciesQueryList_2>; peerDependencies?: Maybe<SitePluginPackageJsonPeerDependenciesQueryList_2>; keywords?: Maybe<SitePluginPackageJsonKeywordsQueryList_2>; }; export type SitePluginPackageJsonKeywordsQueryList_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginPackageJsonLicenseQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginPackageJsonMainQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginPackageJsonNameQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginPackageJsonPeerDependenciesInputObject_2 = { name?: Maybe<SitePluginPackageJsonPeerDependenciesNameQueryString_2>; version?: Maybe<SitePluginPackageJsonPeerDependenciesVersionQueryString_2>; }; export type SitePluginPackageJsonPeerDependenciesNameQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginPackageJsonPeerDependenciesQueryList_2 = { elemMatch?: Maybe<SitePluginPackageJsonPeerDependenciesInputObject_2>; }; export type SitePluginPackageJsonPeerDependenciesVersionQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginPackageJsonVersionQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginPluginFilepathQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginPluginOptionsBackgroundColorQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginPluginOptionsDisplayQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginPluginOptionsFieldNameQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginPluginOptionsIconQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginPluginOptionsInputObject_2 = { typeName?: Maybe<SitePluginPluginOptionsTypeNameQueryString_2>; fieldName?: Maybe<SitePluginPluginOptionsFieldNameQueryString_2>; url?: Maybe<SitePluginPluginOptionsUrlQueryString_2>; name?: Maybe<SitePluginPluginOptionsNameQueryString_2>; path?: Maybe<SitePluginPluginOptionsPathQueryString_2>; short_name?: Maybe<SitePluginPluginOptionsShortNameQueryString_2>; start_url?: Maybe<SitePluginPluginOptionsStartUrlQueryString_2>; background_color?: Maybe<SitePluginPluginOptionsBackgroundColorQueryString_2>; theme_color?: Maybe<SitePluginPluginOptionsThemeColorQueryString_2>; display?: Maybe<SitePluginPluginOptionsDisplayQueryString_2>; icon?: Maybe<SitePluginPluginOptionsIconQueryString_2>; pathCheck?: Maybe<SitePluginPluginOptionsPathCheckQueryBoolean_2>; }; export type SitePluginPluginOptionsNameQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginPluginOptionsPathCheckQueryBoolean_2 = { eq?: Maybe<Scalars['Boolean']>; ne?: Maybe<Scalars['Boolean']>; in?: Maybe<Array<Maybe<Scalars['Boolean']>>>; nin?: Maybe<Array<Maybe<Scalars['Boolean']>>>; }; export type SitePluginPluginOptionsPathQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginPluginOptionsShortNameQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginPluginOptionsStartUrlQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginPluginOptionsThemeColorQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginPluginOptionsTypeNameQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginPluginOptionsUrlQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginResolveQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginSsrApIsQueryList_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePluginVersionQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SitePolyfillQueryBoolean_2 = { eq?: Maybe<Scalars['Boolean']>; ne?: Maybe<Scalars['Boolean']>; in?: Maybe<Array<Maybe<Scalars['Boolean']>>>; nin?: Maybe<Array<Maybe<Scalars['Boolean']>>>; }; export type SitePortQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SiteSiteMetadataAuthorQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SiteSiteMetadataDescriptionQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SiteSiteMetadataInputObject_2 = { title?: Maybe<SiteSiteMetadataTitleQueryString_2>; description?: Maybe<SiteSiteMetadataDescriptionQueryString_2>; author?: Maybe<SiteSiteMetadataAuthorQueryString_2>; }; export type SiteSiteMetadataTitleQueryString_2 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SizesAspectRatioQueryFloat_3 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type SizesAspectRatioQueryFloat_4 = { eq?: Maybe<Scalars['Float']>; ne?: Maybe<Scalars['Float']>; gt?: Maybe<Scalars['Float']>; gte?: Maybe<Scalars['Float']>; lt?: Maybe<Scalars['Float']>; lte?: Maybe<Scalars['Float']>; in?: Maybe<Array<Maybe<Scalars['Float']>>>; nin?: Maybe<Array<Maybe<Scalars['Float']>>>; }; export type SizesBase64QueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SizesBase64QueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SizesOriginalImgQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SizesOriginalImgQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SizesOriginalNameQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SizesOriginalNameQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SizesPresentationHeightQueryInt_3 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type SizesPresentationHeightQueryInt_4 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type SizesPresentationWidthQueryInt_3 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type SizesPresentationWidthQueryInt_4 = { eq?: Maybe<Scalars['Int']>; ne?: Maybe<Scalars['Int']>; gt?: Maybe<Scalars['Int']>; gte?: Maybe<Scalars['Int']>; lt?: Maybe<Scalars['Int']>; lte?: Maybe<Scalars['Int']>; in?: Maybe<Array<Maybe<Scalars['Int']>>>; nin?: Maybe<Array<Maybe<Scalars['Int']>>>; }; export type SizesSizesQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SizesSizesQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SizesSrcQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SizesSrcQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SizesSrcSetQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SizesSrcSetQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SizesSrcSetWebpQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SizesSrcSetWebpQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SizesSrcWebpQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SizesSrcWebpQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SizesTracedSvgQueryString_3 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SizesTracedSvgQueryString_4 = { eq?: Maybe<Scalars['String']>; ne?: Maybe<Scalars['String']>; regex?: Maybe<Scalars['String']>; glob?: Maybe<Scalars['String']>; in?: Maybe<Array<Maybe<Scalars['String']>>>; nin?: Maybe<Array<Maybe<Scalars['String']>>>; }; export type SizesTypeName_3 = { base64?: Maybe<SizesBase64QueryString_3>; tracedSVG?: Maybe<SizesTracedSvgQueryString_3>; aspectRatio?: Maybe<SizesAspectRatioQueryFloat_3>; src?: Maybe<SizesSrcQueryString_3>; srcSet?: Maybe<SizesSrcSetQueryString_3>; srcWebp?: Maybe<SizesSrcWebpQueryString_3>; srcSetWebp?: Maybe<SizesSrcSetWebpQueryString_3>; sizes?: Maybe<SizesSizesQueryString_3>; originalImg?: Maybe<SizesOriginalImgQueryString_3>; originalName?: Maybe<SizesOriginalNameQueryString_3>; presentationWidth?: Maybe<SizesPresentationWidthQueryInt_3>; presentationHeight?: Maybe<SizesPresentationHeightQueryInt_3>; }; export type SizesTypeName_4 = { base64?: Maybe<SizesBase64QueryString_4>; tracedSVG?: Maybe<SizesTracedSvgQueryString_4>; aspectRatio?: Maybe<SizesAspectRatioQueryFloat_4>; src?: Maybe<SizesSrcQueryString_4>; srcSet?: Maybe<SizesSrcSetQueryString_4>; srcWebp?: Maybe<SizesSrcWebpQueryString_4>; srcSetWebp?: Maybe<SizesSrcSetWebpQueryString_4>; sizes?: Maybe<SizesSizesQueryString_4>; originalImg?: Maybe<SizesOriginalImgQueryString_4>; originalName?: Maybe<SizesOriginalNameQueryString_4>; presentationWidth?: Maybe<SizesPresentationWidthQueryInt_4>; presentationHeight?: Maybe<SizesPresentationHeightQueryInt_4>; }; export type SiteTitleQueryQueryVariables = {}; export type SiteTitleQueryQuery = { __typename?: 'Query' } & { site: Maybe< { __typename?: 'Site' } & { siteMetadata: Maybe< { __typename?: 'siteMetadata_2' } & Pick<SiteMetadata_2, 'title'> >; } >; }; export type Unnamed_1_QueryVariables = {}; export type Unnamed_1_Query = { __typename?: 'Query' } & { site: Maybe< { __typename?: 'Site' } & { siteMetadata: Maybe< { __typename?: 'siteMetadata_2' } & Pick< SiteMetadata_2, 'title' | 'description' | 'author' > >; } >; };
the_stack
import { CloudErrorMapper, BaseResourceMapper } from "@azure/ms-rest-azure-js"; import * as msRest from "@azure/ms-rest-js"; export const CloudError = CloudErrorMapper; export const BaseResource = BaseResourceMapper; export const ErrorDetail: msRest.CompositeMapper = { serializedName: "ErrorDetail", type: { name: "Composite", className: "ErrorDetail", modelProperties: { code: { serializedName: "code", type: { name: "String" } }, message: { serializedName: "message", type: { name: "String" } }, target: { serializedName: "target", type: { name: "String" } } } } }; export const ErrorModel: msRest.CompositeMapper = { serializedName: "Error", type: { name: "Composite", className: "ErrorModel", modelProperties: { code: { serializedName: "code", type: { name: "String" } }, message: { serializedName: "message", type: { name: "String" } }, target: { serializedName: "target", type: { name: "String" } }, details: { serializedName: "details", type: { name: "Sequence", element: { type: { name: "Composite", className: "ErrorDetail" } } } } } } }; export const AzureSku: msRest.CompositeMapper = { serializedName: "AzureSku", type: { name: "Composite", className: "AzureSku", modelProperties: { name: { required: true, isConstant: true, serializedName: "name", defaultValue: 'S1', type: { name: "String" } }, tier: { required: true, isConstant: true, serializedName: "tier", defaultValue: 'Standard', type: { name: "String" } } } } }; export const WorkspaceCollection: msRest.CompositeMapper = { serializedName: "WorkspaceCollection", type: { name: "Composite", className: "WorkspaceCollection", modelProperties: { id: { serializedName: "id", type: { name: "String" } }, name: { serializedName: "name", type: { name: "String" } }, type: { serializedName: "type", type: { name: "String" } }, location: { serializedName: "location", type: { name: "String" } }, tags: { serializedName: "tags", type: { name: "Dictionary", value: { type: { name: "String" } } } }, sku: { isConstant: true, serializedName: "sku", defaultValue: {}, type: { name: "Composite", className: "AzureSku" } }, properties: { serializedName: "properties", type: { name: "Object" } } } } }; export const Workspace: msRest.CompositeMapper = { serializedName: "Workspace", type: { name: "Composite", className: "Workspace", modelProperties: { id: { serializedName: "id", type: { name: "String" } }, name: { serializedName: "name", type: { name: "String" } }, type: { serializedName: "type", type: { name: "String" } }, properties: { serializedName: "properties", type: { name: "Object" } } } } }; export const Display: msRest.CompositeMapper = { serializedName: "Display", type: { name: "Composite", className: "Display", modelProperties: { provider: { serializedName: "provider", type: { name: "String" } }, resource: { serializedName: "resource", type: { name: "String" } }, operation: { serializedName: "operation", type: { name: "String" } }, description: { serializedName: "description", type: { name: "String" } }, origin: { serializedName: "origin", type: { name: "String" } } } } }; export const Operation: msRest.CompositeMapper = { serializedName: "Operation", type: { name: "Composite", className: "Operation", modelProperties: { name: { serializedName: "name", type: { name: "String" } }, display: { serializedName: "display", type: { name: "Composite", className: "Display" } } } } }; export const OperationList: msRest.CompositeMapper = { serializedName: "OperationList", type: { name: "Composite", className: "OperationList", modelProperties: { value: { serializedName: "value", type: { name: "Sequence", element: { type: { name: "Composite", className: "Operation" } } } } } } }; export const WorkspaceCollectionAccessKeys: msRest.CompositeMapper = { serializedName: "WorkspaceCollectionAccessKeys", type: { name: "Composite", className: "WorkspaceCollectionAccessKeys", modelProperties: { key1: { serializedName: "key1", type: { name: "String" } }, key2: { serializedName: "key2", type: { name: "String" } } } } }; export const WorkspaceCollectionAccessKey: msRest.CompositeMapper = { serializedName: "WorkspaceCollectionAccessKey", type: { name: "Composite", className: "WorkspaceCollectionAccessKey", modelProperties: { keyName: { serializedName: "keyName", type: { name: "Enum", allowedValues: [ "key1", "key2" ] } } } } }; export const CreateWorkspaceCollectionRequest: msRest.CompositeMapper = { serializedName: "CreateWorkspaceCollectionRequest", type: { name: "Composite", className: "CreateWorkspaceCollectionRequest", modelProperties: { location: { serializedName: "location", type: { name: "String" } }, tags: { serializedName: "tags", type: { name: "Dictionary", value: { type: { name: "String" } } } }, sku: { isConstant: true, serializedName: "sku", defaultValue: {}, type: { name: "Composite", className: "AzureSku" } } } } }; export const UpdateWorkspaceCollectionRequest: msRest.CompositeMapper = { serializedName: "UpdateWorkspaceCollectionRequest", type: { name: "Composite", className: "UpdateWorkspaceCollectionRequest", modelProperties: { tags: { serializedName: "tags", type: { name: "Dictionary", value: { type: { name: "String" } } } }, sku: { isConstant: true, serializedName: "sku", defaultValue: {}, type: { name: "Composite", className: "AzureSku" } } } } }; export const CheckNameRequest: msRest.CompositeMapper = { serializedName: "CheckNameRequest", type: { name: "Composite", className: "CheckNameRequest", modelProperties: { name: { serializedName: "name", type: { name: "String" } }, type: { serializedName: "type", defaultValue: 'Microsoft.PowerBI/workspaceCollections', type: { name: "String" } } } } }; export const CheckNameResponse: msRest.CompositeMapper = { serializedName: "CheckNameResponse", type: { name: "Composite", className: "CheckNameResponse", modelProperties: { nameAvailable: { serializedName: "nameAvailable", type: { name: "Boolean" } }, reason: { serializedName: "reason", type: { name: "String" } }, message: { serializedName: "message", type: { name: "String" } } } } }; export const MigrateWorkspaceCollectionRequest: msRest.CompositeMapper = { serializedName: "MigrateWorkspaceCollectionRequest", type: { name: "Composite", className: "MigrateWorkspaceCollectionRequest", modelProperties: { targetResourceGroup: { serializedName: "targetResourceGroup", type: { name: "String" } }, resources: { serializedName: "resources", type: { name: "Sequence", element: { type: { name: "String" } } } } } } }; export const WorkspaceCollectionList: msRest.CompositeMapper = { serializedName: "WorkspaceCollectionList", type: { name: "Composite", className: "WorkspaceCollectionList", modelProperties: { value: { serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "WorkspaceCollection" } } } } } } }; export const WorkspaceList: msRest.CompositeMapper = { serializedName: "WorkspaceList", type: { name: "Composite", className: "WorkspaceList", modelProperties: { value: { serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "Workspace" } } } } } } };
the_stack
import { member } from "babyioc"; import { TimeCycles, Actor as ClassCyclrActor } from "classcyclr"; import { Actor as EightBittrActor, Actors as EightBittrActors } from "eightbittr"; import * as menugraphr from "menugraphr"; import * as timehandlr from "timehandlr"; import { FullScreenPokemon } from "../FullScreenPokemon"; import { WalkingInstructions } from "./actions/Walking"; import { Pokemon } from "./Battles"; import { Direction } from "./Constants"; import { WildPokemonSchema } from "./Maps"; import { Dialog, MenuSchema } from "./Menus"; import { StateSaveable } from "./Saves"; import { ActorNames } from "./actors/ActorNames"; /** * Actors keyed by their ids. */ export interface ActorsById { [i: string]: Actor; } /** * An in-game Actor with size, velocity, position, and other information. */ export interface Actor extends EightBittrActor, Omit<ClassCyclrActor, "onActorAdded">, StateSaveable { spriteCycleSynched: any; spriteCycle: any; flipHoriz?: boolean; flipVert?: boolean; /** * What to do when a Character, commonly a Player, activates this Actor. * * @param activator The Character activating this. * @param activated The Actor being activated. */ activate?(activator: Character, activated?: Actor): void; /** * The area this was spawned by. */ areaName: string; /** * Actors this is touching in each cardinal direction. */ bordering: [Actor | undefined, Actor | undefined, Actor | undefined, Actor | undefined]; /** * Whether this should be chosen over other Actors if it is one of multiple * potential Actor borders. */ borderPrimary?: boolean; /** * What to do when a Character collides with this Actor. * * @param actor The Character colliding with this Actor. * @param other This actor being collided by the Character. */ collide(actor: Character, other: Actor): boolean; /** * Animation cycles set by the ClassCyclr. */ cycles: TimeCycles; /** * Whether this has been killed. */ dead?: boolean; /** * What cardinal direction this is facing. */ direction: number; /** * Whether this is undergoing a "flicker" effect by toggling .hidden on an interval. */ flickering?: boolean; /** * The globally identifiable, potentially unique id of this Actor. */ id: string; /** * The name of the map that spawned this. */ mapName: string; /** * Whether this is barred from colliding with other Actors. */ nocollide?: boolean; /** * How many quadrants this is contained within. */ numquads: number; /** * A horizontal visual offset to shift by. */ offsetX: number; /** * A vertical visual offset to shift by. */ offsetY: number; /** * Whether to shift this to the "beginning" or "end" of its Actors group. */ position: string; /** * Whether this has been spawned into the game. */ spawned: boolean; /** * Bottom vertical tolerance for not colliding with another Actor. */ tolBottom: number; /** * Left vertical tolerance for not colliding with another Actor. */ tolLeft: number; /** * Right horizontal tolerance for not colliding with another Actor. */ tolRight: number; /** * Top vertical tolerance for not colliding with another Actor. */ tolTop: number; /** * Keying by a Direction gives the corresponding bounding box edge. */ [direction: number]: number; } /** * A Character Actor. * @todo This should be separated into its sub-classes the way FSM's Character is. */ export interface Character extends Actor { /** * For custom triggerable Characters, whether this may be used. */ active?: boolean; /** * An Actor that activated this character. */ collidedTrigger?: Detector; /** * A cutscene to activate when interacting with this Character. */ cutscene?: string; /** * A dialog to start when activating this Character. If dialogDirections is true, * it will be interpreted as a separate dialog for each direction of interaction. */ dialog?: menugraphr.MenuDialogRaw | menugraphr.MenuDialogRaw[]; /** * Whether dialog should definitely be treated as an Array of one Dialog each direction. */ dialogDirections?: number[]; /** * A single set of dialog (or dialog directions) to play after the primary dialog * is complete. */ dialogNext?: menugraphr.MenuDialogRaw | menugraphr.MenuDialogRaw[]; /** * A dialog to place after the primary dialog as a yes or no menu. * @todo If the need arises, this could be changed to any type of menu. */ dialogOptions?: Dialog; /** * A direction to always face after a dialog completes. */ directionPreferred?: number; /** * How far this will travel while walking, such as hopping over a ledge. */ distance: number; /** * A Character walking directly behind this as a follower. */ follower?: Character; /** * A Character this is walking directly behind as a follower. */ following?: Character; /** * An item to give after a dialog is first initiated. */ gift?: string; /** * A grass Scenery partially covering this while walking through a grass area. */ grass?: Grass; /** * A scratch variable for height, such as when behind grass. */ heightOld?: number; /** * Whether this is currently moving, generally from walking. */ isMoving: boolean; /** * A ledge this is hopping over. */ ledge?: Actor; /** * A direction to turn to when the current walking step is done. */ nextDirection?: Direction; /** * Whether this is allowed to be outside the QuadsKeepr quadrants area without getting pruned. */ outerOk?: boolean; /** * Whether this is a Player. */ player?: boolean; /** * Path to push the Player back on after a dialog, if any. */ pushSteps?: WalkingInstructions; /** * Whether this is sporadically walking in random directions. */ roaming?: boolean; /** * How far this can "see" a Player to walk forward and trigger a dialog. */ sight?: number; /** * The Detector stretching in front of this Actor as its sight. */ sightDetector?: SightDetector; /** * A shadow Actor for when this is hopping a ledge. */ shadow?: Actor; /** * How fast this moves. */ speed: number; /** * A scratch variable for speed. */ speedOld?: number; /** * Whether the player is currently surfing. */ surfing?: boolean; /** * Whether this should turn towards an activating Character when a dialog is triggered. */ switchDirectionOnDialog?: boolean; /** * Whether this is currently engaging in its activated dialog. */ talking?: boolean; /** * Whether this is a Pokemon trainer, to start a battle after its dialog. */ trainer?: boolean; /** * Whether this should transport an activating Character. */ transport?: string | TransportSchema; /** * Where this will turn to when its current walking step is complete. */ turning?: number; /** * Whether this is currently walking. */ walking?: boolean; /** * The class cycle for flipping back and forth while walking. */ walkingFlipping?: timehandlr.TimeEvent; /** * A direction to turn to when the current walking step is done. */ wantsToWalk?: boolean; } /** * A Character able to roam in random directions. */ export interface RoamingCharacter extends Character { /** * Whether this is roaming (always true in this type). */ roaming: true; /** * Directions this is allowed to roam. */ roamingDirections: number[]; /** * Distances this has roamed horizontally and vertically. */ roamingDistances: { horizontal: number; vertical: number; }; } /** * An Enemy Actor such as a trainer or wild Pokemon. */ export interface Enemy extends Character { /** * Actors this trainer will use in battle. */ actors: WildPokemonSchema[]; /** * Whether this trainer has already battled and shouldn't again. */ alreadyBattled?: boolean; /** * A badge to gift when this Enemy is defeated. */ badge?: string; /** * The name this will have in battle. */ battleName?: string; /** * The sprite this will display as in battle, if not its battleName. */ battleSprite?: string; /** * A gift to give after defeated in battle. */ giftAfterBattle?: string; /** * A cutscene to trigger after defeated in battle. */ nextCutscene?: string; /** * The title of the trainer before enabling the Joey's Rattata mod. */ previousTitle?: string; /** * A monetary reward to give after defeated in battle. */ reward: number; /** * Dialog to display after defeated in battle. */ textDefeat?: menugraphr.MenuDialogRaw; /** * Dialog to display after the battle is over. */ textAfterBattle?: menugraphr.MenuDialogRaw; /** * Text display upon victory. */ textVictory?: menugraphr.MenuDialogRaw; } /** * A Player Character. */ export interface Player extends Character { /** * Whether Detectors this collides with should consider walking to be an indication * of activation. This is useful for when the Player is following but needs to trigger * a Detector anyway. */ allowDirectionAsKeys?: boolean; /** * Whether the player is currently bicycling. */ cycling: boolean; /** * @returns A new descriptor container for key statuses. */ getKeys(): PlayerKeys; /** * A descriptor for a user's keys' statuses. */ keys: PlayerKeys; } /** * A descriptor for a user's keys' statuses. */ export interface PlayerKeys { /** * Whether the user is currently indicating a selection. */ a: boolean; /** * Whether the user is currently indicating a deselection. */ b: boolean; /** * Whether the user is currently indicating to go up. */ 0: boolean; /** * Whether the user is currently indicating to go to the right. */ 1: boolean; /** * Whether the user is currently indicating to go down. */ 2: boolean; /** * Whether the user is currently indicating to go to the left. */ 3: boolean; } /** * A Grass Actor. */ export interface Grass extends Actor { /** * How likely this is to trigger a grass encounter in the doesGrassEncounterHappen * equation, as a Number in [0, 187.5]. */ rarity: number; } /** * A Detector Actor. These are typically Solids. */ export interface Detector extends Actor { /** * Whether this is currently allowed to activate. */ active?: boolean; /** * A callback for when a Player activates this. * * @param actor The Player activating other, or other if a self-activation. * @param other The Detector being activated by actor. */ activate?(actor: Player | Detector, other?: Detector): void; /** * A cutscene to start when this is activated. */ cutscene?: string; /** * A dialog to start when activating this Character. If an Array, it will be interpreted * as a separate dialog for each cardinal direction of interaction. */ dialog?: menugraphr.MenuDialogRaw; /** * Whether this shouldn't be killed after activation (by default, false). */ keepAlive?: boolean; /** * Whether this requires a direction to be activated. */ requireDirection?: Direction; /** * Whether a Player needs to be fully within this Detector to trigger it. */ requireOverlap?: boolean; /** * A cutscene routine to start when this is activated. */ routine?: string; /** * Whether this should deactivate itself after a first use (by default, false). */ singleUse?: boolean; } /** * A Solid with a partyActivate callback Function. */ export interface HMCharacter extends Character { /** * The name of the move needed to interact with this HMCharacter. */ moveName: string; /** * The partyActivate Function used to interact with this HMCharacter. */ moveCallback(player: Player, pokemon: Pokemon): void; /** * The badge needed to activate this HMCharacter. */ requiredBadge: string; } /** * A WaterEdge object. */ export interface WaterEdge extends HMCharacter { /** * The direction the Player must go to leave the water. */ exitDirection: number; } /** * A Detector that adds an Area into the game. */ export interface AreaSpawner extends Detector { /** * The Area to add into the game. */ area: string; /** * The name of the Map to retrieve the Area within. */ map: string; } /** * A Detector that marks a player as spawning in a different Area. */ export interface AreaGate extends Detector { /** * The Area to now spawn within. */ area: string; /** * The Map to now spawn within. */ map: string; } /** * A gym statue. */ export interface GymDetector extends Detector { /** * The name of the gym. */ gym: string; /** * The name of the gym's leader. */ leader: string; } /** * A Detector that activates a menu dialog. */ export interface MenuTriggerer extends Detector { /** * The name of the menu, if not "GeneralText". */ menu?: string; /** * Custom attributes to apply to the menu. */ menuAttributes?: MenuSchema; /** * Path to push the Player back on after a dialog, if any. */ pushSteps?: WalkingInstructions; } /** * An Character's sight Detector. */ export interface SightDetector extends Detector { /** * The Character using this Detector as its sight. */ viewer: Character; } /** * A Detector to play an audio theme. */ export interface ThemeDetector extends Detector { /** * The audio theme to play. */ theme: string; } /** * A detector to transport to a new area. */ export interface Transporter extends Detector { transport: string | TransportSchema; } /** * A description of where to transport. */ export interface TransportSchema { /** * The name of the Map to transport to. */ map: string; /** * The name of the Location to transport to. */ location: string; } /** * A Pokeball containing some item or trigger. */ export interface Pokeball extends Detector { /** * The activation action, as "item", "cutscene", "pokedex", "dialog", or "yes/no". */ action: string; /** * How many of an item to give, if action is "item". */ amount?: number; /** * What dialog to say, if action is "dialog". */ dialog?: menugraphr.MenuDialogRaw; /** * What item to give, if action is "item". */ item?: string; /** * The title of the Pokemon to display, if action is "Pokedex". */ pokemon?: string[]; /** * What routine to play, if action is "cutscene". */ routine?: string; } /** * Adds and processes new Actors into the game. */ export class Actors<Game extends FullScreenPokemon> extends EightBittrActors<Game> { /** * Stores known names of Actors. */ @member(ActorNames) public readonly names: ActorNames; /** * Overriden Function to adds a new Actor to the game at a given position, * relative to the top left corner of the screen. * * @param actorRaw What type of Actor to add. This may be a String of * the class title, an Array containing the String * and an Object of settings, or an actual Actor. * @param left The horizontal point to place the Actor's left at (by * default, 0). * @param top The vertical point to place the Actor's top at (by default, 0). * @param useSavedInfo Whether an Area's saved info in StateHolder should be * applied to the Actor's position (by default, false). */ public add<TActor extends Actor = Actor>( actorRaw: string | Actor | [string, any], left = 0, top = 0, useSavedInfo?: boolean ): TActor { const actor: TActor = super.add(actorRaw, left, top) as TActor; if (useSavedInfo) { this.applySavedPosition(actor); } if (actor.id) { this.game.stateHolder.applyChanges(actor.id, actor); } if (typeof actor.direction !== "undefined") { this.game.actions.animateCharacterSetDirection(actor, actor.direction); } return actor; } /** * Slight addition to the parent actorProcess Function. The Actor's hit * check type is cached immediately, and a default id is assigned if an id * isn't already present. * * @param actor The Actor being processed. * @param title What type Actor this is (the name of the class). * @remarks This is generally called as the onMake call in an ObjectMakr. */ public process(actor: Actor, title: string): void { super.process(actor, title); // Sprite cycles let cycle: any; if ((cycle = actor.spriteCycle)) { this.game.classCycler.addClassCycle( actor, cycle[0], cycle[1] || undefined, cycle[2] || undefined ); } if ((cycle = actor.spriteCycleSynched)) { this.game.classCycler.addClassCycleSynched( actor, cycle[0], cycle[1] || undefined, cycle[2] || undefined ); } // Terrain and Scenery groups will never have collisions checked if (actor.groupType !== "Terrain" && actor.groupType !== "Scenery") { actor.bordering = [undefined, undefined, undefined, undefined]; } if (typeof actor.id === "undefined") { actor.id = [ this.game.areaSpawner.getMapName(), this.game.areaSpawner.getAreaName(), actor.title, actor.name || "Anonymous", ].join("::"); } } /** * Applies An Actor's stored xloc and yloc to its position. * * @param actor An Actor being placed in the game. */ public applySavedPosition(actor: Actor): void { const savedInfo: any = this.game.stateHolder.getChanges(actor.id); if (!savedInfo) { return; } if (savedInfo.xloc) { this.game.physics.setLeft(actor, this.game.mapScreener.left + savedInfo.xloc); } if (savedInfo.yloc) { this.game.physics.setTop(actor, this.game.mapScreener.top + savedInfo.yloc); } } }
the_stack
import { ExtensionPriority } from '@remirror/core-constants'; import { isNumber, isString, uniqueArray, uniqueId } from '@remirror/core-helpers'; import type { AcceptUndefined, CommandFunction, CommandFunctionProps, EditorState, EditorView, FromToProps, Handler, MakeRequired, Static, Transaction, } from '@remirror/core-types'; import { findNodeAtPosition, isNodeSelection } from '@remirror/core-utils'; import { Decoration, DecorationSet } from '@remirror/pm/view'; import { DelayedCommand, DelayedPromiseCreator } from '../commands'; import { extension, Helper, PlainExtension } from '../extension'; import type { CreateExtensionPlugin } from '../types'; import { command, helper } from './builtin-decorators'; export interface DecorationsOptions { /** * This setting is for adding a decoration to the selected text and can be * used to preserve the marker for the selection when the editor loses focus. * * You can set it as `'selection'` to match the default styles provided by * `@remirror/styles`. * * @default undefined */ persistentSelectionClass?: AcceptUndefined<string | boolean>; /** * Add custom decorations to the editor via `extension.addHandler`. This can * be used via the `useDecorations` hook available from `remirror/react`. */ decorations: Handler<(state: EditorState) => DecorationSet>; /** * The className that is added to all placeholder positions * * '@default 'placeholder' */ placeholderClassName?: Static<string>; /** * The default element that is used for all placeholders. * * @default 'span' */ placeholderNodeName?: Static<string>; } /** * Simplify the process of adding decorations to the editor. All the decorations * added to the document this way are automatically tracked which allows for * custom components to be nested inside decorations. * * @category Builtin Extension */ @extension<DecorationsOptions>({ defaultOptions: { persistentSelectionClass: undefined, placeholderClassName: 'placeholder', placeholderNodeName: 'span', }, staticKeys: ['placeholderClassName', 'placeholderNodeName'], handlerKeys: ['decorations'], handlerKeyOptions: { decorations: { reducer: { accumulator: (accumulated, latestValue, state) => { return accumulated.add(state.doc, latestValue.find()); }, getDefault: () => DecorationSet.empty, }, }, }, defaultPriority: ExtensionPriority.Low, }) export class DecorationsExtension extends PlainExtension<DecorationsOptions> { get name() { return 'decorations' as const; } /** * The placeholder decorations. */ private placeholders = DecorationSet.empty; /** * A map of the html elements to their decorations. */ private readonly placeholderWidgets = new Map<unknown, Decoration>(); onCreate(): void { this.store.setExtensionStore('createPlaceholderCommand', this.createPlaceholderCommand); } /** * Create the extension plugin for inserting decorations into the editor. */ createPlugin(): CreateExtensionPlugin { return { state: { init: () => {}, apply: (tr) => { // Get tracker updates from the meta data const { added, clearTrackers, removed, updated } = this.getMeta(tr); if (clearTrackers) { this.placeholders = DecorationSet.empty; for (const [, widget] of this.placeholderWidgets) { widget.spec.onDestroy?.(this.store.view, widget.spec.element); } this.placeholderWidgets.clear(); return; } this.placeholders = this.placeholders.map(tr.mapping, tr.doc, { onRemove: (spec) => { // Remove any removed widgets. const widget = this.placeholderWidgets.get(spec.id); if (widget) { widget.spec.onDestroy?.(this.store.view, widget.spec.element); } }, }); for (const [, widget] of this.placeholderWidgets) { widget.spec.onUpdate?.( this.store.view, widget.from, widget.spec.element, widget.spec.data, ); } // Update the decorations with any added position trackers. for (const placeholder of added) { if (placeholder.type === 'inline') { this.addInlinePlaceholder(placeholder as WithBase<InlinePlaceholder>, tr); continue; } if (placeholder.type === 'node') { this.addNodePlaceholder(placeholder as WithBase<NodePlaceholder>, tr); continue; } if (placeholder.type === 'widget') { this.addWidgetPlaceholder(placeholder as WithBase<WidgetPlaceholder>, tr); continue; } } for (const { id, data } of updated) { const widget = this.placeholderWidgets.get(id); // Only support updating widget decorations. if (!widget) { continue; } const updatedWidget = Decoration.widget(widget.from, widget.spec.element, { ...widget.spec, data, }); this.placeholders = this.placeholders.remove([widget]).add(tr.doc, [updatedWidget]); this.placeholderWidgets.set(id, updatedWidget); } for (const id of removed) { const found = this.placeholders.find( undefined, undefined, (spec) => spec.id === id && spec.__type === __type, ); const widget = this.placeholderWidgets.get(id); if (widget) { widget.spec.onDestroy?.(this.store.view, widget.spec.element); } this.placeholders = this.placeholders.remove(found); this.placeholderWidgets.delete(id); } }, }, props: { decorations: (state) => { let decorationSet = this.options.decorations(state); decorationSet = decorationSet.add(state.doc, this.placeholders.find()); for (const extension of this.store.extensions) { // Skip this extension when the method doesn't exist. if (!extension.createDecorations) { continue; } const decorations = extension.createDecorations(state).find(); decorationSet = decorationSet.add(state.doc, decorations); } return decorationSet; }, handleDOMEvents: { // Dispatch a transaction for focus/blur events so that the editor state // can be refreshed. // // https://discuss.prosemirror.net/t/handling-focus-in-plugins/1981/2 blur: (view) => { if (this.options.persistentSelectionClass) { view.dispatch(view.state.tr.setMeta(persistentSelectionFocusKey, false)); } return false; }, focus: (view) => { if (this.options.persistentSelectionClass) { view.dispatch(view.state.tr.setMeta(persistentSelectionFocusKey, true)); } return false; }, }, }, }; } @command() updateDecorations(): CommandFunction { return ({ tr, dispatch }) => (dispatch?.(tr), true); } /** * Command to dispatch a transaction adding the placeholder decoration to * be tracked. * * @param id - the value that is used to identify this tracker. This can * be any value. A promise, a function call, a string. * @param options - the options to call the tracked position with. You can * specify the range `{ from: number; to: number }` as well as the class * name. */ @command() addPlaceholder( id: unknown, placeholder: DecorationPlaceholder, deleteSelection?: boolean, ): CommandFunction { return ({ dispatch, tr }) => { return this.addPlaceholderTransaction(id, placeholder, tr, !dispatch) ? (dispatch?.(deleteSelection ? tr.deleteSelection() : tr), true) : false; }; } /** * A command to updated the placeholder decoration. * * To update multiple placeholders you can use chained commands. * * ```ts * let idsWithData: Array<{id: unknown, data: number}>; * * for (const { id, data } of idsWithData) { * chain.updatePlaceholder(id, data); * } * * chain.run(); * ``` */ @command() updatePlaceholder<Data = any>(id: unknown, data: Data): CommandFunction { return ({ dispatch, tr }) => { return this.updatePlaceholderTransaction({ id, data, tr, checkOnly: !dispatch }) ? (dispatch?.(tr), true) : false; }; } /** * A command to remove the specified placeholder decoration. */ @command() removePlaceholder(id: unknown): CommandFunction { return ({ dispatch, tr }) => { return this.removePlaceholderTransaction({ id, tr, checkOnly: !dispatch }) ? (dispatch?.(tr), true) : false; }; } /** * A command to remove all active placeholder decorations. */ @command() clearPlaceholders(): CommandFunction { return ({ tr, dispatch }) => { return this.clearPlaceholdersTransaction({ tr, checkOnly: !dispatch }) ? (dispatch?.(tr), true) : false; }; } /** * Find the position for the tracker with the ID specified. * * @param id - the unique position id which can be any type */ @helper() findPlaceholder(id: unknown): Helper<FromToProps | undefined> { return this.findAllPlaceholders().get(id); } /** * Find the positions of all the trackers in document. */ @helper() findAllPlaceholders(): Helper<Map<unknown, FromToProps>> { const trackers: Map<unknown, FromToProps> = new Map(); const found = this.placeholders.find(undefined, undefined, (spec) => spec.__type === __type); for (const decoration of found) { trackers.set(decoration.spec.id, { from: decoration.from, to: decoration.to }); } return trackers; } /** * Add some decorations based on the provided settings. */ createDecorations(state: EditorState): DecorationSet { const { persistentSelectionClass } = this.options; // Only show the selection decoration when the view doesn't have focus. // Notice that we need to listen to the focus/blur DOM events to make // it work since the focus state is not stored in `EditorState`. if ( !persistentSelectionClass || this.store.view?.hasFocus() || this.store.helpers.isInteracting?.() ) { return DecorationSet.empty; } // Add the selection decoration to the decorations array. return generatePersistentSelectionDecorations(state, DecorationSet.empty, { class: isString(persistentSelectionClass) ? persistentSelectionClass : 'selection', }); } /** * This stores all tracked positions in the editor and maps them via the * transaction updates. */ onApplyState(): void {} /** * Add a widget placeholder and track it as a widget placeholder. */ private addWidgetPlaceholder(placeholder: WithBase<WidgetPlaceholder>, tr: Transaction): void { const { pos, createElement, onDestroy, onUpdate, className, nodeName, id, type } = placeholder; const element = createElement?.(this.store.view, pos) ?? document.createElement(nodeName); element.classList.add(className); const decoration = Decoration.widget(pos, element, { // @ts-expect-error: TS types here don't allow us to set custom properties id, __type, type, element, onDestroy, onUpdate, }); this.placeholderWidgets.set(id, decoration); this.placeholders = this.placeholders.add(tr.doc, [decoration]); } /** * Add an inline placeholder. */ private addInlinePlaceholder(placeholder: WithBase<InlinePlaceholder>, tr: Transaction): void { const { from = tr.selection.from, to = tr.selection.to, className, nodeName, id, type, } = placeholder; let decoration: Decoration; if (from === to) { // Add this as a widget if the range is empty. const element = document.createElement(nodeName); element.classList.add(className); decoration = Decoration.widget(from, element, { // @ts-expect-error: TS types here don't allow us to set custom properties id, type, __type, widget: element, }); } else { // Make this span across nodes if the range is not empty. decoration = Decoration.inline( from, to, { nodeName, class: className }, { // @ts-expect-error: TS types here don't allow us to set custom properties id, __type, }, ); } this.placeholders = this.placeholders.add(tr.doc, [decoration]); } /** * Add a placeholder for nodes. */ private addNodePlaceholder(placeholder: WithBase<NodePlaceholder>, tr: Transaction): void { const { pos, className, nodeName, id } = placeholder; const $pos = isNumber(pos) ? tr.doc.resolve(pos) : tr.selection.$from; const found = isNumber(pos) ? $pos.nodeAfter ? { pos, end: $pos.nodeAfter.nodeSize } : undefined : findNodeAtPosition($pos); if (!found) { return; } const decoration = Decoration.node( found.pos, found.end, { nodeName, class: className }, { id, __type }, ); this.placeholders = this.placeholders.add(tr.doc, [decoration]); } /** * Add the node and class name to the placeholder object. */ private withRequiredBase<Type extends BasePlaceholder>( id: unknown, placeholder: Type, ): WithBase<Type> { const { placeholderNodeName, placeholderClassName } = this.options; const { nodeName = placeholderNodeName, className, ...rest } = placeholder; const classes = (className ? [placeholderClassName, className] : [placeholderClassName]).join( ' ', ); return { nodeName, className: classes, ...rest, id }; } /** * Get the command metadata. */ private getMeta(tr: Transaction): Required<DecorationPlaceholderMeta> { const meta = tr.getMeta(this.pluginKey) ?? {}; return { ...DEFAULT_PLACEHOLDER_META, ...meta }; } /** * Set the metadata for the command. */ private setMeta(tr: Transaction, update: DecorationPlaceholderMeta) { const meta = this.getMeta(tr); tr.setMeta(this.pluginKey, { ...meta, ...update }); } /** * Add a placeholder decoration with the specified params to the transaction * and return the transaction. * * It is up to you to dispatch the transaction or you can just use the * commands. */ private addPlaceholderTransaction( id: unknown, placeholder: DecorationPlaceholder, tr: Transaction, checkOnly = false, ): boolean { const existingPosition = this.findPlaceholder(id); if (existingPosition) { return false; } if (checkOnly) { return true; } const { added } = this.getMeta(tr); this.setMeta(tr, { added: [...added, this.withRequiredBase(id, placeholder)], }); return true; } /** * Update the data stored by a placeholder. * * This replaces the whole data value. */ private updatePlaceholderTransaction<Data = any>(props: { id: unknown; data: Data; tr: Transaction; checkOnly?: boolean; }): boolean { const { id, tr, checkOnly = false, data } = props; const existingPosition = this.findPlaceholder(id); if (!existingPosition) { return false; } if (checkOnly) { return true; } const { updated } = this.getMeta(tr); this.setMeta(tr, { updated: uniqueArray([...updated, { id, data }]) }); return true; } /** * Discards a previously defined tracker once not needed. * * This should be used to cleanup once the position is no longer needed. */ private removePlaceholderTransaction(props: { id: unknown; tr: Transaction; checkOnly?: boolean; }): boolean { const { id, tr, checkOnly = false } = props; const existingPosition = this.findPlaceholder(id); if (!existingPosition) { return false; } if (checkOnly) { return true; } const { removed } = this.getMeta(tr); this.setMeta(tr, { removed: uniqueArray([...removed, id]) }); return true; } /** * This helper returns a transaction that clears all position trackers when * any exist. * * Otherwise it returns undefined. */ private clearPlaceholdersTransaction(props: { tr: Transaction; checkOnly?: boolean }): boolean { const { tr, checkOnly = false } = props; const positionTrackerState = this.getPluginState(); if (positionTrackerState === DecorationSet.empty) { return false; } if (checkOnly) { return true; } this.setMeta(tr, { clearTrackers: true }); return true; } /** * Handles delayed commands which rely on the */ private readonly createPlaceholderCommand = <Value>( props: DelayedPlaceholderCommandProps<Value>, ): DelayedCommand<Value> => { const id = uniqueId(); const { promise, placeholder, onFailure, onSuccess } = props; return new DelayedCommand(promise) .validate((props) => { return this.addPlaceholder(id, placeholder)(props); }) .success((props) => { const { state, tr, dispatch, view, value } = props; const range = this.store.helpers.findPlaceholder(id); if (!range) { const error = new Error('The placeholder has been removed'); return onFailure?.({ error, state, tr, dispatch, view }) ?? false; } this.removePlaceholder(id)({ state, tr, view, dispatch: () => {} }); return onSuccess(value, range, { state, tr, dispatch, view }); }) .failure((props) => { this.removePlaceholder(id)({ ...props, dispatch: () => {} }); return onFailure?.(props) ?? false; }); }; } const DEFAULT_PLACEHOLDER_META: Required<DecorationPlaceholderMeta> = { added: [], updated: [], clearTrackers: false, removed: [], }; const __type = 'placeholderDecoration'; const persistentSelectionFocusKey = 'persistentSelectionFocus'; export interface DecorationPlaceholderMeta { /** * The trackers to add. */ added?: Array<WithBase<DecorationPlaceholder>>; /** * The trackers to update with new data. Data is an object and is used to * include properties like `progress` for progress indicators. Only `widget` * decorations can be updated in this way. */ updated?: Array<{ id: unknown; data: any }>; /** * The trackers to remove. */ removed?: unknown[]; /** * When set to true will delete all the active trackers. */ clearTrackers?: boolean; } interface BasePlaceholder { /** * A custom class name to use for the placeholder decoration. All the trackers * will automatically be given the class name `remirror-tracker-position` * * @default '' */ className?: string; /** * A custom html element or string for a created element tag name. * * @default 'tracker' */ nodeName?: string; } interface DataProps<Data = any> { /** * The data to store for this placeholder. */ data?: Data; } interface InlinePlaceholder<Data = any> extends BasePlaceholder, Partial<FromToProps>, DataProps<Data> { type: 'inline'; } interface NodePlaceholder<Data = any> extends BasePlaceholder, DataProps<Data> { /** * Set this as a node tracker. */ type: 'node'; /** * If provided the The `pos` must be directly before the node in order to be * valid. If not provided it will select the parent node of the current * selection. */ pos: number | null; } export interface WidgetPlaceholder<Data = any> extends BasePlaceholder, DataProps<Data> { /** * Declare this as a widget tracker. * * Widget trackers support adding custom components to the created dom * element. */ type: 'widget'; /** * Widget trackers only support fixed positions. */ pos: number; /** * Called the first time this widget decoration is added to the dom. */ createElement?(view: EditorView, pos: number): HTMLElement; /** * Called whenever the position tracker updates with the new position. */ onUpdate?(view: EditorView, pos: number, element: HTMLElement, data: any): void; /** * Called when the widget decoration is removed from the dom. */ onDestroy?(view: EditorView, element: HTMLElement): void; } type WithBase<Type extends BasePlaceholder> = MakeRequired<Type, keyof BasePlaceholder> & { id: unknown; }; export type DecorationPlaceholder = WidgetPlaceholder | NodePlaceholder | InlinePlaceholder; /** * Generate the persistent selection decoration for when the editor loses focus. */ function generatePersistentSelectionDecorations( state: EditorState, decorationSet: DecorationSet, attrs: { class: string }, ): DecorationSet { const { selection, doc } = state; if (selection.empty) { return decorationSet; } const { from, to } = selection; const decoration = isNodeSelection(selection) ? Decoration.node(from, to, attrs) : Decoration.inline(from, to, attrs); return decorationSet.add(doc, [decoration]); } export interface DelayedPlaceholderCommandProps<Value> { /** * A function that returns a promise. */ promise: DelayedPromiseCreator<Value>; /** * The placeholder configuration. */ placeholder: DecorationPlaceholder; /** * Called when the promise succeeds and the placeholder still exists. If no * placeholder can be found (for example, the user has deleted the entire * document) then the failure handler is called instead. */ onSuccess: (value: Value, range: FromToProps, commandProps: CommandFunctionProps) => boolean; /** * Called when a failure is encountered. */ onFailure?: CommandFunction<{ error: any }>; } declare global { namespace Remirror { interface ExtensionStore { /** * Create delayed command which automatically adds a placeholder to the * document while the delayed command is being run and also automatically * removes it once it has completed. */ createPlaceholderCommand<Value = any>( props: DelayedPlaceholderCommandProps<Value>, ): DelayedCommand<Value>; } interface BaseExtension { /** * Create a decoration set which adds decorations to your editor. The * first parameter is the `EditorState`. * * This can be used in combination with the `onApplyState` handler which * can map the decoration. * * @param state - the editor state which was passed in. */ createDecorations?(state: EditorState): DecorationSet; } interface AllExtensions { decorations: DecorationsExtension; } } }
the_stack
import type Hls from 'hls.js'; import { PropertyValues } from 'lit'; import { property } from 'lit/decorators.js'; import { VdsEvent, vdsEvent } from '../../base/events'; import { DEV_MODE } from '../../global/env'; import { CanPlay, MediaType } from '../../media'; import { preconnect, ScriptLoader } from '../../utils/network'; import { isNonNativeHlsStreamingPossible } from '../../utils/support'; import { isFunction, isNil, isString, isUndefined } from '../../utils/unit'; import { VideoElement } from '../video'; export const HLS_ELEMENT_TAG_NAME = 'vds-hls'; export const HLS_EXTENSIONS = /\.(m3u8)($|\?)/i; export const HLS_TYPES = new Set([ 'application/x-mpegURL', 'application/vnd.apple.mpegurl' ]); export type HlsConstructor = typeof Hls; const HLS_LIB_CACHE = new Map<string, HlsConstructor>(); /** * Embeds video content into documents via the native `<video>` element. It may contain * one or more video sources, represented using the `src` attribute or the `<source>` element: the * browser will choose the most suitable one. * * In addition, this element introduces support for HLS streaming via the popular `hls.js` library. * HLS streaming is either [supported natively](https://caniuse.com/?search=hls) (generally * on iOS), or in environments that [support the Media Stream API](https://caniuse.com/?search=mediastream). * * 💡 This element contains the exact same interface as the `<video>` element. It redispatches * all the native events if needed, but prefer the `vds-*` variants (eg: `vds-play`) as they * iron out any browser issues. It also dispatches all the `hls.js` events. * * ## Dynamically Loaded * * ### CDN * * Simply point the `hlsLibrary` property or `hls-library` attribute to a script on a CDN * containing the library. For example, you could use the following URL * `https://cdn.jsdelivr.net/npm/hls.js@0.14.7/dist/hls.js`. Swap `hls.js` for `hls.min.js` in * production. * * We recommended using either [JSDelivr](https://jsdelivr.com) or [UNPKG](https://unpkg.com). * * ```html * <vds-hls * src="https://stream.mux.com/dGTf2M5TBA5ZhXvwEIOziAHBhF2Rn00jk79SZ4gAFPn8.m3u8" * hls-library="https://cdn.jsdelivr.net/npm/hls.js@0.14.7/dist/hls.js" * ></vds-hls> * ``` * * ### Dynamic Import * * If you'd like to serve your own copy and control when the library is downloaded, simply * use [dynamic imports](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports) * and update the `hlsLibrary` property when ready. You must pass in the `hls.js` class constructor. * * ## Locally Bundled (not recommended) * * You'll need to install `hls.js`... * * ```bash * $: npm install hls.js@^0.14.0 @types/hls.js@^0.13.3 * ``` * * Finally, import it and pass it as a property to `<vds-hls>`... * * ```ts * import '@vidstack/elements/providers/hls/define'; * * import { html, LitElement } from 'lit'; * import Hls from 'hls.js'; * * class MyElement extends LitElement { * render() { * return html`<vds-hls src="..." .hlsLibrary=${Hls}></vds-hls>`; * } * } * ``` * * @tagname vds-hls * @slot Used to pass in `<source>` and `<track>` elements to the underlying HTML5 media player. * @slot ui - Used to pass in `<vds-ui>` to customize the player user interface. * @csspart media - The video element (`<video>`). * @csspart video - Alias for `media` part. * @example * ```html * <vds-hls src="/media/index.m3u8" poster="/media/poster.png"> * <!-- Additional media resources here. --> * </vds-hls> * ``` * @example * ```html * <vds-hls src="/media/index.m3u8" poster="/media/poster.png"> * <track default kind="subtitles" src="/media/subs/en.vtt" srclang="en" label="English" /> * </vds-hls> * ``` */ export class HlsElement extends VideoElement { // ------------------------------------------------------------------------------------------- // Properties // ------------------------------------------------------------------------------------------- /** * The `hls.js` configuration object. */ @property({ type: Object, attribute: 'hls-config' }) hlsConfig: Partial<Hls.Config | undefined> = {}; /** * The `hls.js` constructor or a URL of where it can be found. Only version `^0.13.3` * (note the `^`) is supported at the moment. Important to note that by default this is * `undefined` so you can freely optimize when the best possible time is to load the library. */ @property({ attribute: 'hls-library' }) hlsLibrary: HlsConstructor | string | undefined; protected _Hls: HlsConstructor | undefined; /** * The `hls.js` constructor. */ get Hls() { return this._Hls; } protected _hlsEngine: Hls | undefined; protected _isHlsEngineAttached = false; /** * The current `hls.js` instance. */ get hlsEngine() { return this._hlsEngine; } /** * Whether the `hls.js` instance has mounted the `HtmlMediaElement`. * * @default false */ get isHlsEngineAttached() { return this._isHlsEngineAttached; } override get currentSrc() { return this.isHlsStream && !this.shouldUseNativeHlsSupport ? this.src : this.videoEngine?.currentSrc ?? ''; } // ------------------------------------------------------------------------------------------- // Lifecycle // ------------------------------------------------------------------------------------------- override connectedCallback() { super.connectedCallback(); this._initiateHlsLibraryDownloadConnection(); } protected override async update(changedProperties: PropertyValues) { super.update(changedProperties); if ( changedProperties.has('hlsLibrary') && this.hasUpdated && !this.shouldUseNativeHlsSupport ) { this._initiateHlsLibraryDownloadConnection(); await this._buildHlsEngine(true); this._attachHlsEngine(); this._loadSrcOnHlsEngine(); } } protected override firstUpdated(changedProperties: PropertyValues) { super.firstUpdated(changedProperties); // TODO(mihar-22): Add a lazy load option to wait until in viewport. // Wait a frame to ensure the browser has had a chance to reach first-contentful-paint. window.requestAnimationFrame(() => { this._handleMediaSrcChange(); }); /** * We can't actually determine whether there is native HLS support until the undlerying * `<video>` element has rendered, since we rely on calling `canPlayType` on it. Thus we retry * this getter here, and if it returns `true` we request an update so the `src` is set * on the `<video>` element (determined by `_shouldSetVideoSrcAttr()` method). */ if (this.shouldUseNativeHlsSupport) { this.requestUpdate(); } } override disconnectedCallback() { this._destroyHlsEngine(); super.disconnectedCallback(); } // ------------------------------------------------------------------------------------------- // Methods // ------------------------------------------------------------------------------------------- /** * Attempts to preconnect to the `hls.js` remote source given via `hlsLibrary`. This is * assuming `hls.js` is not bundled and `hlsLibrary` is a URL string pointing to where it * can be found. */ protected _initiateHlsLibraryDownloadConnection() { if (!isString(this.hlsLibrary) || HLS_LIB_CACHE.has(this.hlsLibrary)) { return; } /* c8 ignore start */ if (DEV_MODE) { this._logger .infoGroup('preconnect to `hls.js` download') .appendWithLabel('URL', this.hlsLibrary) .end(); } /* c8 ignore stop */ preconnect(this.hlsLibrary); } override canPlayType(type: string): CanPlay { if (HLS_TYPES.has(type)) { this.isHlsSupported ? CanPlay.Probably : CanPlay.No; } return super.canPlayType(type); } /** * Whether HLS streaming is supported in this environment. */ get isHlsSupported(): boolean { return ( (this.Hls?.isSupported() ?? isNonNativeHlsStreamingPossible()) || this.hasNativeHlsSupport ); } /** * Whether the current src is using HLS. * * @default false */ get isHlsStream(): boolean { return HLS_EXTENSIONS.test(this.src); } /** * Whether the browser natively supports HLS, mostly only true in Safari. Only call this method * after the provider has connected to the DOM (wait for `MediaProviderConnectEvent`). */ get hasNativeHlsSupport(): boolean { /** * We need to call this directly on `HTMLMediaElement`, calling `this.shouldPlayType(...)` * won't work here because it'll use the `CanPlayType` result from this provider override * which will incorrectly indicate that HLS can natively played due to `hls.js` support. */ const canPlayType = super.canPlayType('application/vnd.apple.mpegurl'); /* c8 ignore start */ if (DEV_MODE) { this._logger .debugGroup('checking for native HLS support') .appendWithLabel('Can play type', canPlayType) .end(); } /* c8 ignore stop */ return canPlayType === CanPlay.Maybe || canPlayType === CanPlay.Probably; } /** * Whether native HLS support is available and whether it should be used. Generally defaults * to `false` as long as `window.MediaSource` is defined to enforce consistency by * using `hls.js` where ever possible. * * @default false */ get shouldUseNativeHlsSupport(): boolean { /** * // TODO: stage-2 we'll need to rework this line and determine when to "upgrade" to `hls.js`. * * @see https://github.com/vidstack/elements/issues/376 */ if (isNonNativeHlsStreamingPossible()) return false; return this.hasNativeHlsSupport; } /** * Notifies the `VideoElement` whether the `src` attribute should be set on the rendered * `<video>` element. If we're using `hls.js` we don't want to override the `blob`. */ protected override _shouldSetVideoSrcAttr(): boolean { return this.shouldUseNativeHlsSupport || !this.isHlsStream; } /** * Loads `hls.js` from a remote source found at the `hlsLibrary` URL (if a string). */ protected async _loadHlsLibrary(): Promise<void> { if (!isString(this.hlsLibrary) || HLS_LIB_CACHE.has(this.hlsLibrary)) { return; } const HlsConstructor = await this._loadHlsScript(); // Loading failed. if (isUndefined(HlsConstructor)) return; HLS_LIB_CACHE.set(this.hlsLibrary, HlsConstructor); this.dispatchEvent( vdsEvent('vds-hls-load', { detail: HlsConstructor }) ); } /** * Loads `hls.js` from the remote source given via `hlsLibrary` into the window namespace. This * is because `hls.js` in 2021 still doesn't provide a ESM export. This method will return * `undefined` if it fails to load the script. Listen to `HlsLoadErrorEvent` to be notified * of any failures. */ protected async _loadHlsScript(): Promise<HlsConstructor | undefined> { if (!isString(this.hlsLibrary)) return undefined; /* c8 ignore start */ if (DEV_MODE) { this._logger.infoGroup('Starting to load `hls.js`'); } /* c8 ignore stop */ try { await ScriptLoader.load(this.hlsLibrary); if (!isFunction(window.Hls)) { throw Error( '[vds]: Failed loading `hls.js`. Could not find a valid constructor at `window.Hls`.' ); } /* c8 ignore start */ if (DEV_MODE) { this._logger .infoGroup('Loaded `hls.js`') .appendWithLabel('URL', this.hlsLibrary) .appendWithLabel('Library', window.Hls) .end(); } /* c8 ignore stop */ return window.Hls; } catch (err) { /* c8 ignore start */ if (DEV_MODE) { this._logger .warnGroup('Failed to load `hls.js`') .appendWithLabel('URL', this.hlsLibrary) .end(); } /* c8 ignore stop */ this.dispatchEvent( vdsEvent('vds-hls-load-error', { detail: err as Error }) ); } return undefined; } protected async _buildHlsEngine(forceRebuild = false): Promise<void> { // Need to mount on `<video>`. if ( isNil(this.videoEngine) && !forceRebuild && !isUndefined(this.hlsEngine) ) { return; } /* c8 ignore start */ if (DEV_MODE) { this._logger.info('🏗️ Building HLS engine'); } /* c8 ignore stop */ // Destroy old engine. if (!isUndefined(this.hlsEngine)) { this._destroyHlsEngine(); } if (isString(this.hlsLibrary)) { await this._loadHlsLibrary(); } // Either a remote source and we cached the `hls.js` constructor, or it was bundled directly. // The previous `loadHlsLibrary()` called would've populated the cache if it was remote. this._Hls = isString(this.hlsLibrary) ? HLS_LIB_CACHE.get(this.hlsLibrary) : this.hlsLibrary; if (!this.Hls?.isSupported()) { /* c8 ignore start */ if (DEV_MODE) { this._logger.warn('`hls.js` is not supported in this environment'); } /* c8 ignore stop */ this.dispatchEvent(vdsEvent('vds-hls-no-support')); return; } this._hlsEngine = new this.Hls(this.hlsConfig ?? {}); /* c8 ignore start */ if (DEV_MODE) { this._logger .infoGroup('🏗️ HLS engine built') .appendWithLabel('HLS Engine', this._hlsEngine) .appendWithLabel('Video Engine', this.videoEngine) .end(); } /* c8 ignore stop */ this.dispatchEvent(vdsEvent('vds-hls-build', { detail: this.hlsEngine })); this._listenToHlsEngine(); } protected _destroyHlsEngine(): void { this.hlsEngine?.destroy(); this._prevHlsEngineSrc = ''; this._hlsEngine = undefined; this._isHlsEngineAttached = false; this._softResetMediaContext(); /* c8 ignore start */ if (DEV_MODE) { this._logger.info('🏗️ Destroyed HLS engine'); } /* c8 ignore stop */ } protected _prevHlsEngineSrc = ''; // Let `Html5MediaElement` know we're taking over ready events. protected override _willAnotherEngineAttach(): boolean { return this.isHlsStream && !this.shouldUseNativeHlsSupport; } protected _attachHlsEngine(): void { if ( this.isHlsEngineAttached || isUndefined(this.hlsEngine) || isNil(this.videoEngine) ) { return; } this.hlsEngine.attachMedia(this.videoEngine); this._isHlsEngineAttached = true; /* c8 ignore start */ if (DEV_MODE) { this._logger .infoGroup('🏗️ attached HLS engine') .appendWithLabel('HLS Engine', this._hlsEngine) .appendWithLabel('Video Engine', this.videoEngine) .end(); } /* c8 ignore stop */ this.dispatchEvent(vdsEvent('vds-hls-attach', { detail: this.hlsEngine })); } protected _detachHlsEngine(): void { if (!this.isHlsEngineAttached) return; this.hlsEngine?.detachMedia(); this._isHlsEngineAttached = false; this._prevHlsEngineSrc = ''; /* c8 ignore start */ if (DEV_MODE) { this._logger .infoGroup('🏗️ detached HLS engine') .appendWithLabel('Video Engine', this.videoEngine) .end(); } /* c8 ignore stop */ this.dispatchEvent(vdsEvent('vds-hls-detach', { detail: this.hlsEngine })); } protected _loadSrcOnHlsEngine(): void { if ( isNil(this.hlsEngine) || !this.isHlsStream || this.shouldUseNativeHlsSupport || this.src === this._prevHlsEngineSrc ) { return; } /* c8 ignore start */ if (DEV_MODE) { this._logger .infoGroup(`📼 loading src \`${this.src}\``) .appendWithLabel('Src', this.src) .appendWithLabel('HLS Engine', this._hlsEngine) .appendWithLabel('Video Engine', this.videoEngine) .end(); } /* c8 ignore stop */ this.hlsEngine.loadSource(this.src); this._prevHlsEngineSrc = this.src; } protected override _getMediaType(): MediaType { if (this.ctx.mediaType === MediaType.LiveVideo) { return MediaType.LiveVideo; } if (this.isHlsStream) { return MediaType.Video; } return super._getMediaType(); } // ------------------------------------------------------------------------------------------- // Events // ------------------------------------------------------------------------------------------- protected override _handleLoadedMetadata(event: Event) { super._handleLoadedMetadata(event); // iOS doesn't fire `canplay` event when loading HLS videos natively. if (this.shouldUseNativeHlsSupport && this.isHlsStream) { this._handleCanPlay(event); } } protected override async _handleMediaSrcChange() { super._handleMediaSrcChange(); // We don't want to load `hls.js` until the browser has had a chance to paint. if (!this.hasUpdated) return; this.ctx.canPlay = false; if (!this.isHlsStream) { this._detachHlsEngine(); return; } // Need to wait for `src` attribute on `<video>` to clear if last `src` was not using HLS engine. await this.updateComplete; if (isNil(this.hlsLibrary) || this.shouldUseNativeHlsSupport) return; if (isUndefined(this.hlsEngine)) { await this._buildHlsEngine(); } /* c8 ignore start */ if (DEV_MODE) { this._logger.debug(`📼 detected src change \`${this.src}\``); } /* c8 ignore stop */ this._attachHlsEngine(); this._loadSrcOnHlsEngine(); } protected _listenToHlsEngine(): void { if (isUndefined(this.hlsEngine) || isUndefined(this.Hls)) return; // TODO: Bind all events. this.hlsEngine.on( this.Hls.Events.LEVEL_LOADED, this._handleHlsLevelLoaded.bind(this) ); this.hlsEngine.on(this.Hls.Events.ERROR, this._handleHlsError.bind(this)); } protected _handleHlsError(eventType: string, data: Hls.errorData): void { if (isUndefined(this.Hls)) return; this.ctx.error = data; /* c8 ignore start */ if (DEV_MODE) { this._logger .errorGroup(`HLS error \`${eventType}\``) .appendWithLabel('Event type', eventType) .appendWithLabel('Data', data) .appendWithLabel('Src', this.src) .appendWithLabel('Context', this.mediaState) .appendWithLabel('HLS Engine', this._hlsEngine) .appendWithLabel('Video Engine', this.videoEngine) .end(); } /* c8 ignore stop */ if (data.fatal) { switch (data.type) { case this.Hls.ErrorTypes.NETWORK_ERROR: this._handleHlsNetworkError(eventType, data); break; case this.Hls.ErrorTypes.MEDIA_ERROR: this._handleHlsMediaError(eventType, data); break; default: this._handleHlsIrrecoverableError(eventType, data); break; } } this.dispatchEvent( vdsEvent('vds-error', { originalEvent: new VdsEvent(eventType, { detail: data }) }) ); } protected _handleHlsNetworkError( eventType: string, data: Hls.errorData ): void { this.hlsEngine?.startLoad(); } protected _handleHlsMediaError(eventType: string, data: Hls.errorData): void { this.hlsEngine?.recoverMediaError(); } protected _handleHlsIrrecoverableError( eventType: string, data: Hls.errorData ): void { this._destroyHlsEngine(); } protected _handleHlsLevelLoaded( eventType: string, data: Hls.levelLoadedData ): void { if (this.ctx.canPlay) return; this._handleHlsMediaReady(eventType, data); } protected _handleHlsMediaReady( eventType: string, data: Hls.levelLoadedData ): void { const { live, totalduration: duration } = data.details; const event = new VdsEvent(eventType, { detail: data }); const mediaType = live ? MediaType.LiveVideo : MediaType.Video; if (this.ctx.mediaType !== mediaType) { this.ctx.mediaType = mediaType; this.dispatchEvent( vdsEvent('vds-media-type-change', { detail: mediaType, originalEvent: event }) ); } if (this.ctx.duration !== duration) { this.ctx.duration = duration; this.dispatchEvent( vdsEvent('vds-duration-change', { detail: duration, originalEvent: event }) ); } this._handleMediaReady(event); } }
the_stack
import * as React from 'react'; import { cloneDeep } from '@microsoft/sp-lodash-subset'; import { Text } from '@microsoft/sp-core-library'; import { isEmpty } from '@microsoft/sp-lodash-subset'; import { Spinner, Button, ButtonType, Label } from 'office-ui-fabric-react'; import { QueryFilter } from '../QueryFilter/QueryFilter'; import { IQueryFilter } from '../QueryFilter/IQueryFilter'; import { QueryFilterOperator } from '../QueryFilter/QueryFilterOperator'; import { QueryFilterJoin } from '../QueryFilter/QueryFilterJoin'; import { IQueryFilterField } from '../QueryFilter/IQueryFilterField'; import { IQueryFilterPanelProps } from './IQueryFilterPanelProps'; import { IQueryFilterPanelState } from './IQueryFilterPanelState'; import styles from './QueryFilterPanel.module.scss'; export class QueryFilterPanel extends React.Component<IQueryFilterPanelProps, IQueryFilterPanelState> { /************************************************************************************* * Component's constructor * @param props * @param state *************************************************************************************/ constructor(props: IQueryFilterPanelProps, state: IQueryFilterPanelState) { super(props); this.state = { loading: true, fields: [], filters: this.getDefaultFilters(), error: null }; this.getDefaultFilters = this.getDefaultFilters.bind(this); this.loadFields = this.loadFields.bind(this); } /************************************************************************************* * Returns a default array with an empty filter *************************************************************************************/ private getDefaultFilters():IQueryFilter[] { if(this.props.filters != null && this.props.filters.length > 0) { return this.sortFiltersByIndex(this.props.filters); } let defaultFilters:IQueryFilter[] = [ { index: 0, field: null, operator: QueryFilterOperator.Eq, join: QueryFilterJoin.Or, value: '' } ]; return defaultFilters; } /************************************************************************************* * Called once after initial rendering *************************************************************************************/ public componentDidMount(): void { this.loadFields(); } /************************************************************************************* * Called immediately after updating occurs *************************************************************************************/ public componentDidUpdate(prevProps: IQueryFilterPanelProps, prevState: IQueryFilterPanelState): void { if (this.props.disabled !== prevProps.disabled || this.props.stateKey !== prevProps.stateKey) { this.loadFields(); } } /************************************************************************************* * Loads the available fields asynchronously *************************************************************************************/ private loadFields(): void { this.setState((prevState: IQueryFilterPanelState, props: IQueryFilterPanelProps): IQueryFilterPanelState => { prevState.loading = true; prevState.error = null; return prevState; }); this.props.loadFields().then((fields: IQueryFilterField[]) => { this.setState((prevState: IQueryFilterPanelState, props: IQueryFilterPanelProps): IQueryFilterPanelState => { prevState.loading = false; prevState.fields = fields; prevState.filters = this.getDefaultFilters(); return prevState; }); }) .catch((error: any) => { this.setState((prevState: IQueryFilterPanelState, props: IQueryFilterPanelProps): IQueryFilterPanelState => { prevState.loading = false; prevState.error = error; return prevState; }); }); } /************************************************************************************* * When one of the filter changes *************************************************************************************/ private onFilterChanged(filter:IQueryFilter): void { // Makes sure the parent is not notified for no reason if the modified filter was (and still is) considered empty let isWorthNotifyingParent = true; let oldFilter = this.state.filters.filter((i) => { return i.index == filter.index; })[0]; let oldFilterIndex = this.state.filters.indexOf(oldFilter); if(this.props.trimEmptyFiltersOnChange && this.isFilterEmpty(oldFilter) && this.isFilterEmpty(filter)) { isWorthNotifyingParent = false; } // Updates the modified filter in the state this.state.filters[oldFilterIndex] = cloneDeep(filter); this.setState((prevState: IQueryFilterPanelState, props: IQueryFilterPanelProps): IQueryFilterPanelState => { prevState.filters = this.state.filters; return prevState; }); // Notifies the parent with the updated filters if(isWorthNotifyingParent) { let filters:IQueryFilter[] = this.props.trimEmptyFiltersOnChange ? this.state.filters.filter((f) => { return !this.isFilterEmpty(f); }) : this.state.filters; this.props.onChanged(filters); } } /************************************************************************************* * Returns whether the specified filter is empty or not * @param filter : The filter that needs to be checked *************************************************************************************/ private isFilterEmpty(filter:IQueryFilter) { let isFilterEmpty = false; // If the filter has no field if(filter.field == null) { isFilterEmpty = true; } // If the filter has a null or empty value if(filter.value == null || isEmpty(filter.value.toString())) { // And has no date time expression if(isEmpty(filter.expression)) { // And isn't a [Me] switch if(!filter.me) { // And isn't a <IsNull /> or <IsNotNull /> operator if(filter.operator != QueryFilterOperator.IsNull && filter.operator != QueryFilterOperator.IsNotNull) { isFilterEmpty = true; } } } } return isFilterEmpty; } /************************************************************************************* * When the 'Add filter' button is clicked *************************************************************************************/ private onAddFilterClick(): void { // Updates the state with an all fresh new filter let nextAvailableFilterIndex = this.state.filters[this.state.filters.length-1].index + 1; let newFilter:IQueryFilter = { index: nextAvailableFilterIndex, field: null, operator: QueryFilterOperator.Eq, join: QueryFilterJoin.Or, value: '' }; this.state.filters.push(newFilter); this.setState((prevState: IQueryFilterPanelState, props: IQueryFilterPanelProps): IQueryFilterPanelState => { prevState.filters = this.state.filters; return prevState; }); } private sortFiltersByIndex(filters:IQueryFilter[]): IQueryFilter[] { return filters.sort((a, b) => { return a.index - b.index; }); } /************************************************************************************* * Renders the the QueryFilter component *************************************************************************************/ public render() { const loading = this.state.loading ? <Spinner label={this.props.strings.loadingFieldsLabel} /> : <div />; const error = this.state.error != null ? <div className="ms-TextField-errorMessage ms-u-slideDownIn20">{ Text.format(this.props.strings.loadingFieldsErrorLabel, this.state.error) }</div> : <div />; const filters = this.state.filters.map((filter, index) => <div className={styles.queryFilterPanelItem} key={index}> <QueryFilter fields={this.state.fields} filter={filter} disabled={this.props.disabled} onLoadTaxonomyPickerSuggestions={this.props.onLoadTaxonomyPickerSuggestions} onLoadPeoplePickerSuggestions={this.props.onLoadPeoplePickerSuggestions} onChanged={this.onFilterChanged.bind(this)} strings={this.props.strings.queryFilterStrings} key={index} /> </div> ); return ( <div className={styles.queryFilterPanel}> <Label>{this.props.strings.filtersLabel}</Label> {loading} { !this.state.loading && <div className={styles.queryFilterPanelItems}>{filters}</div> } { !this.state.loading && <Button buttonType={ButtonType.primary} onClick={this.onAddFilterClick.bind(this)} disabled={this.props.disabled} icon='Add'>{this.props.strings.addFilterLabel}</Button> } {error} </div> ); } }
the_stack
import Link from 'next/link'; import { useRouter } from 'next/router'; import { FormEvent, useEffect, useState } from 'react'; import { mutate } from 'swr'; import { ArrowLeftIcon, CheckCircleIcon, ExclamationCircleIcon } from '@heroicons/react/outline'; import { Modal } from '@supabase/ui'; /** * Edit view will have extra fields (showOnlyInEditView: true) * to render parsed metadata and other attributes. * All fields are editable unless they have `editable` set to false. * All fields are required unless they have `required` or `requiredInEditView` set to false. */ const fieldCatalog = [ { key: 'name', label: 'Name', type: 'text', placeholder: 'MyApp', attributes: { required: false, requiredInEditView: false }, }, { key: 'description', label: 'Description', type: 'text', placeholder: 'A short description not more than 100 characters', attributes: { maxLength: 100, required: false, requiredInEditView: false }, // not required in create/edit view }, { key: 'tenant', label: 'Tenant', type: 'text', placeholder: 'acme.com', attributes: { editable: false }, }, { key: 'product', label: 'Product', type: 'text', placeholder: 'demo', attributes: { editable: false }, }, { key: 'redirectUrl', label: 'Allowed redirect URLs (newline separated)', type: 'textarea', placeholder: 'http://localhost:3366', attributes: { isArray: true, rows: 3 }, }, { key: 'defaultRedirectUrl', label: 'Default redirect URL', type: 'url', placeholder: 'http://localhost:3366/login/saml', attributes: {}, }, { key: 'rawMetadata', label: 'Raw IdP XML', type: 'textarea', placeholder: 'Paste the raw XML here', attributes: { rows: 5, requiredInEditView: false, //not required in edit view labelInEditView: 'Raw IdP XML (fully replaces the current one)', }, }, { key: 'idpMetadata', label: 'IDP Metadata', type: 'pre', attributes: { rows: 10, editable: false, showOnlyInEditView: true, formatForDisplay: (value) => JSON.stringify(value, null, 2), }, }, { key: 'clientID', label: 'Client ID', type: 'text', attributes: { showOnlyInEditView: true }, }, { key: 'clientSecret', label: 'Client Secret', type: 'password', attributes: { showOnlyInEditView: true }, }, ]; function getFieldList(isEditView) { return isEditView ? fieldCatalog : fieldCatalog.filter(({ attributes: { showOnlyInEditView } }) => !showOnlyInEditView); // filtered list for add view } function getInitialState(samlConfig, isEditView) { const _state = {}; const _fieldCatalog = getFieldList(isEditView); _fieldCatalog.forEach(({ key, attributes }) => { _state[key] = samlConfig?.[key] ? attributes.isArray ? samlConfig[key].join('\r\n') // render list of items on newline eg:- redirect URLs : samlConfig[key] : ''; }); return _state; } type AddEditProps = { samlConfig?: Record<string, any>; }; const AddEdit = ({ samlConfig }: AddEditProps) => { const router = useRouter(); const isEditView = !!samlConfig; // FORM LOGIC: SUBMIT const [{ status }, setSaveStatus] = useState<{ status: 'UNKNOWN' | 'SUCCESS' | 'ERROR' }>({ status: 'UNKNOWN', }); const saveSAMLConfiguration = async (event) => { event.preventDefault(); const { rawMetadata, redirectUrl, ...rest } = formObj; const encodedRawMetadata = btoa(rawMetadata || ''); const redirectUrlList = redirectUrl.split(/\r\n|\r|\n/); const res = await fetch('/api/admin/saml/config', { method: isEditView ? 'PATCH' : 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ ...rest, encodedRawMetadata, redirectUrl: JSON.stringify(redirectUrlList) }), }); if (res.ok) { if (!isEditView) { router.replace('/admin/saml/config'); } else { setSaveStatus({ status: 'SUCCESS' }); // revalidate on save mutate(`/api/admin/saml/config/${router.query.id}`); setTimeout(() => setSaveStatus({ status: 'UNKNOWN' }), 2000); } } else { // save failed setSaveStatus({ status: 'ERROR' }); setTimeout(() => setSaveStatus({ status: 'UNKNOWN' }), 2000); } }; // LOGIC: DELETE const [delModalVisible, setDelModalVisible] = useState(false); const toggleDelConfirm = () => setDelModalVisible(!delModalVisible); const [userNameEntry, setUserNameEntry] = useState(''); const deleteConfiguration = async () => { await fetch('/api/admin/saml/config', { method: 'DELETE', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ clientID: samlConfig?.clientID, clientSecret: samlConfig?.clientSecret }), }); toggleDelConfirm(); await mutate('/api/admin/saml/config'); router.replace('/admin/saml/config'); }; // STATE: FORM const [formObj, setFormObj] = useState<Record<string, string>>(() => getInitialState(samlConfig, isEditView) ); // Resync form state on save useEffect(() => { const _state = getInitialState(samlConfig, isEditView); setFormObj(_state); }, [samlConfig, isEditView]); function handleChange(event: FormEvent) { const target = event.target as HTMLInputElement | HTMLTextAreaElement; setFormObj((cur) => ({ ...cur, [target.id]: target.value })); } return ( <> {/* Or use router.back() */} <Link href='/admin/saml/config'> <a className='link-primary'> <ArrowLeftIcon aria-hidden className='h-4 w-4' /> <span className='ml-2'>Back</span> </a> </Link> <div> <h2 className='mt-2 mb-4 text-3xl font-bold text-primary dark:text-white'> {isEditView ? 'Edit Configuration' : 'New Configuration'} </h2> <form onSubmit={saveSAMLConfiguration}> <div className='min-w-[28rem] rounded-xl border border-gray-200 bg-white p-6 dark:border-gray-700 dark:bg-gray-800 md:w-3/4 md:max-w-lg'> {fieldCatalog .filter(({ attributes: { showOnlyInEditView } }) => (isEditView ? true : !showOnlyInEditView)) .map( ({ key, placeholder, label, type, attributes: { isArray, rows, formatForDisplay, editable, requiredInEditView = true, // by default all fields are required unless explicitly set to false labelInEditView, maxLength, required = true, // by default all fields are required unless explicitly set to false }, }) => { const readOnly = isEditView && editable === false; const _required = isEditView ? !!requiredInEditView : !!required; const _label = isEditView && labelInEditView ? labelInEditView : label; const value = readOnly && typeof formatForDisplay === 'function' ? formatForDisplay(formObj[key]) : formObj[key]; return ( <div className='mb-6 ' key={key}> <label htmlFor={key} className='mb-2 block text-sm font-medium text-gray-900 dark:text-gray-300'> {_label} </label> {type === 'pre' ? ( <pre className='block w-full overflow-auto rounded-lg border border-gray-300 bg-gray-50 p-2 text-sm text-gray-900 focus:border-blue-500 focus:ring-blue-500 dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400 dark:focus:border-blue-500 dark:focus:ring-blue-500'> {value} </pre> ) : type === 'textarea' ? ( <textarea id={key} placeholder={placeholder} value={value} required={_required} readOnly={readOnly} maxLength={maxLength} onChange={handleChange} className={`block w-full rounded-lg border border-gray-300 bg-gray-50 p-2 text-sm text-gray-900 focus:border-blue-500 focus:ring-blue-500 dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400 dark:focus:border-blue-500 dark:focus:ring-blue-500 ${ isArray ? 'whitespace-pre' : '' }`} rows={rows} /> ) : ( <input id={key} type={type} placeholder={placeholder} value={value} required={_required} readOnly={readOnly} maxLength={maxLength} onChange={handleChange} className='block w-full rounded-lg border border-gray-300 bg-gray-50 p-2.5 text-sm text-gray-900 focus:border-blue-500 focus:ring-blue-500 dark:border-gray-600 dark:bg-gray-700 dark:text-white dark:placeholder-gray-400 dark:focus:border-blue-500 dark:focus:ring-blue-500' /> )} </div> ); } )} <div className='flex'> <button type='submit' className='btn-primary'> Save Changes </button> <p role='status' className={`ml-2 inline-flex items-center ${ status === 'SUCCESS' || status === 'ERROR' ? 'opacity-100' : 'opacity-0' } transition-opacity motion-reduce:transition-none`}> {status === 'SUCCESS' && ( <span className='inline-flex items-center text-primary'> <CheckCircleIcon aria-hidden className='mr-1 h-5 w-5'></CheckCircleIcon> Saved </span> )} {/* TODO: also display error message once we standardise the response format */} {status === 'ERROR' && ( <span className='inline-flex items-center text-red-900'> <ExclamationCircleIcon aria-hidden className='mr-1 h-5 w-5'></ExclamationCircleIcon> ERROR </span> )} </p> </div> </div> {samlConfig?.clientID && samlConfig.clientSecret && ( <section className='mt-10 flex items-center rounded bg-red-100 p-6 text-red-900'> <div className='flex-1'> <h6 className='mb-1 font-medium'>Delete this configuration</h6> <p className='font-light'>All your apps using this configuration will stop working.</p> </div> <button type='button' className='inline-block rounded bg-red-700 px-4 py-2 text-sm font-bold leading-6 text-white hover:bg-red-800' onClick={toggleDelConfirm} data-modal-toggle='popup-modal'> Delete </button> </section> )} </form> <Modal closable title='Are you absolutely sure ?' description='This action cannot be undone. This will permanently delete the SAML config.' visible={delModalVisible} onCancel={toggleDelConfirm} customFooter={ <div className='ml-auto inline-flex'> <button type='button' onClick={toggleDelConfirm} className='inline-block rounded border-2 bg-gray-200 px-4 py-2 text-sm font-bold leading-6 text-secondary/90 hover:bg-gray-300'> Cancel </button> <button type='button' disabled={userNameEntry !== samlConfig?.product} onClick={deleteConfiguration} className='ml-1.5 inline-block rounded bg-red-700 py-2 px-4 text-sm font-bold leading-6 text-white hover:bg-red-800 disabled:bg-slate-400'> Delete </button> </div> }> <p className='text-slate-600'> Please type in the name of the product &apos; {samlConfig?.product && <strong>{samlConfig.product}</strong>}&apos; to confirm. </p> <label htmlFor='nameOfProd' className='font-medium text-slate-900'> Name * </label> <input id='nameOfProd' required className='dark:white d block w-full rounded-lg border border-gray-300 bg-gray-50 p-2.5 text-sm text-gray-900 focus:border-blue-500 focus:ring-blue-500 dark:border-gray-600 dark:placeholder-gray-400 dark:focus:border-blue-500 dark:focus:ring-blue-500' value={userNameEntry} onChange={({ target }) => { setUserNameEntry(target.value); }}></input> </Modal> </div> </> ); }; export default AddEdit;
the_stack
import { AsnParser } from "@peculiar/asn1-schema"; import * as native from "native"; import { Convert } from "pvtsutils"; import * as core from "webcrypto-core"; import { CryptoKey, CryptoKeyStorage } from "../../keys"; import { getOidByNamedCurve } from "./helper"; import { EcPrivateKey } from "./private_key"; import { EcPublicKey } from "./public_key"; function buf_pad(buf: Buffer, padSize: number = 0) { if (padSize && Buffer.length < padSize) { const pad = Buffer.from(new Uint8Array(padSize - buf.length).map((v) => 0)); return Buffer.concat([pad, buf]); } return buf; } export class EcCrypto { public static publicKeyUsages = ["verify"]; public static privateKeyUsages = ["sign", "deriveKey", "deriveBits"]; public static async generateKey(algorithm: EcKeyGenParams, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKeyPair> { return new Promise((resolve, reject) => { const alg = algorithm as EcKeyGenParams; const namedCurve = this.getNamedCurve(alg.namedCurve); native.Key.generateEc(namedCurve, (err, key) => { if (err) { reject(err); } else { const prvUsages = ["sign", "deriveKey", "deriveBits"] .filter((usage) => keyUsages.some((keyUsage) => keyUsage === usage)) as KeyUsage[]; const pubUsages = ["verify"] .filter((usage) => keyUsages.some((keyUsage) => keyUsage === usage)) as KeyUsage[]; const privateKey = EcPrivateKey.create(algorithm, "private", extractable, prvUsages); const publicKey = EcPublicKey.create(algorithm, "public", true, pubUsages); publicKey.native = privateKey.native = key; resolve({ privateKey: CryptoKeyStorage.setItem(privateKey), publicKey: CryptoKeyStorage.setItem(publicKey), }); } }); }); } public static async exportKey(format: KeyFormat, key: core.NativeCryptoKey): Promise<JsonWebKey | ArrayBuffer> { return new Promise((resolve, reject) => { const nativeKey = CryptoKeyStorage.getItem(key).native as native.Key; const type = key.type === "public" ? native.KeyType.PUBLIC : native.KeyType.PRIVATE; switch (format.toLocaleLowerCase()) { case "jwk": nativeKey.exportJwk(type, (err, data) => { if (err) { throw new core.CryptoError(`Cannot export JWK key\n${err}`); } try { const jwk: JsonWebKey = { kty: "EC", ext: true }; jwk.crv = (key.algorithm as EcKeyAlgorithm).namedCurve; jwk.key_ops = key.usages; let padSize = 0; switch (jwk.crv) { case "P-256": case "K-256": padSize = 32; break; case "P-384": padSize = 48; break; case "P-521": padSize = 66; break; default: throw new Error(`Unsupported named curve '${jwk.crv}'`); } jwk.x = Convert.ToBase64Url(buf_pad(data.x, padSize)); jwk.y = Convert.ToBase64Url(buf_pad(data.y, padSize)); if (key.type === "private") { jwk.d = Convert.ToBase64Url(buf_pad(data.d, padSize)); } resolve(jwk); } catch (e) { reject(e); } }); break; case "spki": nativeKey.exportSpki((err, raw) => { if (err) { reject(err); } else { resolve(core.BufferSourceConverter.toArrayBuffer(raw)); } }); break; case "pkcs8": nativeKey.exportPkcs8((err, raw) => { if (err) { reject(err); } else { resolve(core.BufferSourceConverter.toArrayBuffer(raw)); } }); break; case "raw": nativeKey.exportJwk(type, (err, data) => { if (err) { reject(err); } else { let padSize = 0; const crv = (key.algorithm as any).namedCurve; switch (crv) { case "P-256": case "K-256": padSize = 32; break; case "P-384": padSize = 48; break; case "P-521": padSize = 66; break; default: throw new Error(`Unsupported named curve '${crv}'`); } const x = buf_pad(data.x, padSize); const y = buf_pad(data.y, padSize); const rawKey = new Uint8Array(1 + x.length + y.length); rawKey.set([4]); rawKey.set(x, 1); rawKey.set(y, 1 + x.length); resolve(core.BufferSourceConverter.toArrayBuffer(rawKey)); } }); break; default: throw new core.CryptoError(`ExportKey: Unknown export format '${format}'`); } }); } public static async importKey(format: KeyFormat, keyData: JsonWebKey | ArrayBuffer, algorithm: EcKeyImportParams, extractable: boolean, keyUsages: KeyUsage[]): Promise<core.CryptoKey> { return new Promise((resolve, reject) => { const formatLC = format.toLocaleLowerCase(); const data: { [key: string]: Buffer } = {}; let keyType = native.KeyType.PUBLIC; switch (formatLC) { case "raw": { let keyLength = 0; const rawData = Buffer.from(keyData); if (rawData.byteLength === 65) { // P-256 // Key length 32 Byte keyLength = 32; } else if (rawData.byteLength === 97) { // P-384 // Key length 48 Byte keyLength = 48; } else if (rawData.byteLength === 133) { // P-521 // Key length: 521/= 65,125 => 66 Byte keyLength = 66; } const x = Buffer.from(rawData).slice(1, keyLength + 1); const y = Buffer.from(rawData).slice(keyLength + 1, (keyLength * 2) + 1); data["kty"] = Buffer.from("EC", "utf-8"); data["crv"] = this.getNamedCurve(algorithm.namedCurve.toUpperCase()); data["x"] = buf_pad(x, keyLength); data["y"] = buf_pad(y, keyLength); native.Key.importJwk(data, keyType, (err, key) => { try { if (err) { reject(new core.CryptoError(`ImportKey: Cannot import key from JWK\n${err}`)); } else { const ecKey = EcPublicKey.create(algorithm, "public", extractable, keyUsages); ecKey.native = key; resolve(CryptoKeyStorage.setItem(ecKey)); } } catch (e) { reject(e); } }); break; } case "jwk": { const jwk = keyData as JsonWebKey; // prepare data data["kty"] = jwk.kty as any; data["crv"] = this.getNamedCurve(jwk.crv!); data["x"] = Buffer.from(Convert.FromBase64Url(jwk.x!)); data["y"] = Buffer.from(Convert.FromBase64Url(jwk.y!)); if (jwk.d) { keyType = native.KeyType.PRIVATE; data["d"] = Buffer.from(Convert.FromBase64Url(jwk.d!)); } native.Key.importJwk(data, keyType, (err, key) => { try { if (err) { reject(new core.CryptoError(`ImportKey: Cannot import key from JWK\n${err}`)); } else { const Key: typeof CryptoKey = jwk.d ? EcPrivateKey : EcPublicKey; const ecKey = Key.create(algorithm, jwk.d ? "private" : "public", extractable, keyUsages); ecKey.native = key; resolve(CryptoKeyStorage.setItem(ecKey)); } } catch (e) { reject(e); } }); break; } case "pkcs8": case "spki": { let importFunction = native.Key.importPkcs8; if (formatLC === "spki") { importFunction = native.Key.importSpki; } const rawData = Buffer.from(keyData); importFunction(rawData, (err, key) => { try { if (err) { reject(new core.CryptoError(`ImportKey: Can not import key for ${format}\n${err.message}`)); } else { let parameters: core.asn1.ParametersType | undefined; if (formatLC === "spki") { // spki const keyInfo = AsnParser.parse(new Uint8Array(keyData as ArrayBuffer), core.asn1.PublicKeyInfo); parameters = keyInfo.publicKeyAlgorithm.parameters; } else { // pkcs8 const keyInfo = AsnParser.parse(new Uint8Array(keyData as ArrayBuffer), core.asn1.PrivateKeyInfo); parameters = keyInfo.privateKeyAlgorithm.parameters; } if (!parameters) { throw new core.CryptoError("Key info doesn't have required parameters"); } let namedCurveIdentifier = ""; try { namedCurveIdentifier = AsnParser.parse(parameters, core.asn1.ObjectIdentifier).value; } catch (e) { throw new core.CryptoError("Cannot read key info parameters"); } if (getOidByNamedCurve(algorithm.namedCurve) !== namedCurveIdentifier) { throw new core.CryptoError("Key info parameter doesn't match to named curve"); } const Key: typeof CryptoKey = formatLC === "pkcs8" ? EcPrivateKey : EcPublicKey; const ecKey = Key.create(algorithm, formatLC === "pkcs8" ? "private" : "public", extractable, keyUsages); ecKey.native = key; resolve(CryptoKeyStorage.setItem(ecKey)); } } catch (e) { reject(e); } }); break; } default: throw new core.CryptoError(`ImportKey: Wrong format value '${format}'`); } }); } public static checkCryptoKey(key: any): asserts key is EcPublicKey | EcPrivateKey { if (!(key instanceof EcPrivateKey || key instanceof EcPublicKey)) { throw new TypeError("key: Is not EC CryptoKey"); } } private static getNamedCurve(namedCurve: string) { switch (namedCurve.toUpperCase()) { case "P-192": namedCurve = "secp192r1"; break; case "P-256": namedCurve = "secp256r1"; break; case "P-384": namedCurve = "secp384r1"; break; case "P-521": namedCurve = "secp521r1"; break; case "K-256": namedCurve = "secp256k1"; break; default: throw new core.CryptoError("Unsupported namedCurve in use"); } return (native.EcNamedCurves as any)[namedCurve]; } }
the_stack
import {LogMessage} from "../backends/elasticsearch/Elasticsearch" import {CopyHelper} from "../helpers/CopyHelper" import {escape} from "he" import {Query} from "./Query" import {Filter} from "../components/App" import moment from "moment" import {TimeZone} from "./Prefs" export type FieldsConfig = { timestamp?: string disableTimestampNano?: boolean secondaryIndex?: string collapsedFormatting: ILogRule[] expandedFormatting?: ILogRule[] collapsedIgnore?: string[] contextFilters?: ContextFilter[] elasticsearch?: { // Fields to search when a user does not specify a field queryStringFields?: string[] } } export type ContextFilter = { title: string keep?: string[] icon?: string } export interface ILogRule { field: string transforms: string[] | object[] } interface CollapsedFormatField { // Original string value before formatting readonly original: string // Formatted value, modified by the transformer, maybe be HTML. current: string // Classes to apply to the formatted value classes: string[], // The entire entry. This should not be modified by the transform. readonly entry: any, // Hex color value to apply to the formatted value color: string, // Tooltip to show on hover tooltip: string, } export interface ExpandedFormatField { readonly original: any, current: string readonly indent: string, readonly query: () => Query copyBag: any[] } /** * Transform is a function that transforms a log record field for formatting. It * returns the transformed field. It may transform its input in-place. */ type CollapsedTransform = (input: CollapsedFormatField) => CollapsedFormatField type ExpandedTransform = (input: ExpandedFormatField) => ExpandedFormatField export type QueryManipulator = { getQuery: () => Query changeQuery: (newQuery: Query) => void getFilters: () => Filter[] } export class LogFormatter { private readonly copyHelper: CopyHelper private templateContent: DocumentFragment private config: FieldsConfig private _queryManipulator: QueryManipulator private readonly tz: TimeZone constructor(config: FieldsConfig, tz: TimeZone) { if (config === undefined) { // tslint:disable-next-line:no-console console.warn("fieldsConfig is not set") // @ts-ignore config = {} } config.collapsedFormatting = config.collapsedFormatting || [] config.collapsedIgnore = config.collapsedIgnore || [] config.expandedFormatting = config.expandedFormatting || [] this.config = config this.copyHelper = new CopyHelper() this.tz = tz } public getTimeZone() { return this.tz } set queryManipulator(qm: QueryManipulator) { this._queryManipulator = qm } setTemplate(templateContent: DocumentFragment) { this.templateContent = templateContent return this } // Clean a log entry for display. private cleanLog(entry: LogMessage): any { const out: LogMessage = {...entry} delete out.__cursor return out } private safeHTML(entry: any, recursive: boolean): any { if (typeof entry === "string") { return escape(entry) } if (!recursive) { return entry } if (Array.isArray(entry)) { return entry.map(e => this.safeHTML(e, true)) } if (typeof entry === "object") { entry = {...entry} for (const key of Object.keys(entry)) { entry[key] = this.safeHTML(entry[key], true) } return entry } return entry } buildSnippet(snippetEl: HTMLElement, full: any) { full = this.cleanLog(full) full = this.safeHTML(full, true) for (const rule of this.config.collapsedFormatting) { delete (full[rule.field]) } for (const field of this.config.collapsedIgnore) { delete (full[field]) } if (Object.keys(full).length > 0) { snippetEl.innerHTML = LogFormatter.toLogfmt(full) } } build(entry: LogMessage): DocumentFragment { const cursor = entry.__cursor entry = this.cleanLog(entry) // Make shallow copy here before we mangle entry (we only modify top-level fields). const origEntry: LogMessage = {...entry} // The expanded part is lazily rendered. let isExpandedRendered = false const fragment = document.importNode(this.templateContent, true) const el = fragment.firstElementChild as HTMLElement el.dataset.cursor = JSON.stringify(cursor) el.dataset.ts = entry[this.config.timestamp] el.dataset.id = entry._id const snippetEl = fragment.querySelector(".text") as HTMLElement if (origEntry._full) { origEntry._full.then((logMessage) => this.buildSnippet(snippetEl, logMessage)) } else { this.buildSnippet(snippetEl, origEntry) } fragment.querySelector(".fields").innerHTML = this.renderUnexpanded(entry) let visible = false const expanded = fragment.querySelector(".expanded") const hover = fragment.querySelector('.hover') as HTMLElement fragment.querySelector('.unexpanded').addEventListener('click', async () => { if (window.getSelection().toString()) { // Abort click because user is selecting return } visible = !visible if (!visible) { expanded.classList.add('is-hidden') return } if (!isExpandedRendered) { let full: LogMessage if (origEntry._full) { full = await origEntry._full } else { full = origEntry } // Grab bag of references to use for the copy button, that gets filled in by the // rendering code const copyBag = [] expanded.innerHTML = this.renderExpandedRecursively(this.cleanLog(full), copyBag, undefined, 0, cursor) this.valueHover(expanded, hover) expanded.addEventListener('click', (e) => this.handleExpandedClick(e, full, copyBag)) isExpandedRendered = true } expanded.classList.remove('is-hidden') }) fragment.querySelector('.expanded').addEventListener('click', (e) => { const target = e.target as HTMLElement if (target.classList.contains('show-nested')) { target.nextElementSibling.classList.remove('is-hidden') target.classList.add('is-hidden') } else if (target.classList.contains('hide-nested')) { target.parentElement.previousElementSibling.classList.remove('is-hidden') target.parentElement.classList.add('is-hidden') } }) return fragment } private handleExpandedClick(e, full: LogMessage, copyBag: any[]) { // Doing some fancy event delegation here since there could be many nested nodes const target = e.target as HTMLElement const oldTooltip = target.dataset.tooltip const data = copyBag[parseInt(target.dataset.copy, 10)] const {getQuery, getFilters, changeQuery} = this._queryManipulator const copied = () => { target.dataset.tooltip = "Copied!" setTimeout(() => target.dataset.tooltip = oldTooltip, 1000) e.stopPropagation() } if (target.classList.contains('copy-button')) { let v: string if (isObject(data) || Array.isArray(data)) { v = JSON.stringify(data, null, 2) } else { v = data.toString() } this.copyHelper.copy(v) copied() } else if (target.classList.contains('link-button')) { const sharedQuery = getQuery() .withFocus(full._id, JSON.stringify(data)) .withFixedTimeRange() const w = window.location this.copyHelper.copy(`${w.protocol}//${w.host}${w.pathname}?${sharedQuery.toURL()}`) copied() } else if (target.classList.contains('show-context-button')) { // We're hijacking the a href when the user left clicks, so that the page doesn't reload. // This will also allow middle clicks to new tabs. const parent = target.parentNode as HTMLAnchorElement changeQuery(Query.load(getFilters(), {urlQuery: parent.href})) e.stopPropagation() e.preventDefault() } } private valueHover(expanded: Element, hover: HTMLElement) { const value = expanded.querySelectorAll(".value") let lastFocus: HTMLElement | undefined let currentFocus: HTMLElement | undefined let hovering = false let unhoverTimer hover.querySelector(".add-to-query").addEventListener('click', () => { // Add to query, for when the user left clicks const key = lastFocus.dataset.key const obj = unescape(lastFocus.dataset.obj) const {changeQuery} = this._queryManipulator changeQuery(this.getAddQuery(key, obj)) }) hover.querySelector(".exclude-from-query").addEventListener('click', () => { // Exclude from query, for when the user left clicks const key = lastFocus.dataset.key const obj = unescape(lastFocus.dataset.obj) const {changeQuery} = this._queryManipulator changeQuery(this.getAddQuery(`-${key}`, obj)) }) hover.addEventListener('mouseenter', () => { hovering = true lastFocus?.classList.add('focused') }) hover.addEventListener('mouseleave', () => { hovering = false clearTimeout(unhoverTimer) hover.style.visibility = 'hidden' lastFocus?.classList.remove('focused') hover.classList.remove('tooltip') }) value.forEach(el => el.addEventListener('mouseenter', (e) => { const target = e.target as HTMLElement currentFocus?.classList.remove("focused") currentFocus = target lastFocus = currentFocus const key = lastFocus.dataset.key const obj = unescape(lastFocus.dataset.obj) hover.style.visibility = 'visible' hover.style.left = `${target.offsetLeft + 5}px` hover.style.top = `${target.offsetTop - 5}px` target.classList.add('focused') // Add to query, for when the user middle clicks const query = this.getAddQuery(key, obj) const addToQuery = hover.querySelector(".add-to-query") as HTMLAnchorElement addToQuery.href = `?${query.toURL()}` // Exclude from query, for when the user middle clicks const excludeQuery = this.getAddQuery(`-${key}`, obj) const excludeFromQuery = hover.querySelector(".exclude-from-query") as HTMLAnchorElement excludeFromQuery.href = `?${excludeQuery.toURL()}` // Copy // https://stackoverflow.com/a/19470348/11125 let copy = hover.querySelector(".copy-to-clipboard") as HTMLAnchorElement copy.parentNode.replaceChild(copy.cloneNode(true), copy) copy = hover.querySelector(".copy-to-clipboard") as HTMLAnchorElement copy.addEventListener("click", () => { this.copyHelper.copy(JSON.parse(obj).toString()) hover.classList.add('tooltip') hover.classList.add('has-tooltip-active') hover.dataset.tooltip = 'Copied!' setTimeout(() => { hover.classList.remove('tooltip') }, 1000) }) hover.querySelectorAll(".extra").forEach(n => n.remove()) this.config.expandedFormatting .filter(f => f.field === key) .flatMap(f => f.transforms as object[]) .flatMap(tf => (tf as any).link as LinkConfig) .forEach(lnk => { const re = new RegExp(lnk.match) const val = JSON.parse(obj) if (typeof val !== "string") { return } const url = val.replace(re, lnk.href) const html = `<a class="extra tooltip is-tooltip-right" data-tooltip="${lnk.title}" href="${url}"><i class="mdi ${lnk.icon}"></i></a>` hover.innerHTML += html }) })) value.forEach(el => el.addEventListener('mouseleave', (e) => { const target = e.target as HTMLElement target.classList.remove('focused') currentFocus = undefined clearTimeout(unhoverTimer) // Give some time for the mouse to move from the value text to the hover, // otherwise this mouseleave happens before hover's mouseenter and vanishes immediately. unhoverTimer = setTimeout(() => { if (currentFocus) { return } if (hovering) { return } hover.style.visibility = 'hidden' }, 50) })) } private getAddQuery(key, obj) { return this._queryManipulator.getQuery().withAddTerms(`${key}:${obj}`) } private renderUnexpanded(entry: LogMessage) { let fields = '' for (const rule of this.config.collapsedFormatting) { const value = entry[rule.field] if (value === undefined) { continue } let format: CollapsedFormatField = { original: value, current: value, classes: [], color: null, entry, tooltip: null, } rule.transforms = rule.transforms || [] for (const transform of rule.transforms) { const {funcName, data} = this.getTransformData(transform) const ctf = collapsedTransformers[funcName] if (!ctf) { // throw Error(`Could not find collapsed transformer named '${funcName}'`) } const tf = ctf(this, data) format = tf(format) } if (format.tooltip) { format.classes.push("tooltip is-tooltip-bottom") } const tooltip = format.tooltip ? `data-tooltip="${format.tooltip}"` : '' const clazz = format.classes.length > 0 ? 'class="' + format.classes.join(' ') + '"' : '' const color = format.color ? `style="color:${format.color}"` : '' if (format.current && format.current !== "") { fields += `<div ${clazz} ${color} ${tooltip}>${escape(format.current)}</div>&nbsp;` } } return fields } private getTransformData(transform: string | object) { let funcName let data if (typeof transform === "string") { funcName = transform data = {} } else { funcName = Object.keys(transform)[0] data = transform[funcName] } return {funcName, data} } renderExpandedRecursively(obj: any, copyBag: any[], path: string[] = [], level = 0, cursor?: any): string { const indent = makeIndent(level + 1) const lastIndent = makeIndent(level) const pathStr = path.join('.') const originalObj = obj obj = this.safeHTML(obj, false) let current = obj this.config.expandedFormatting.forEach(rule => { if (rule.field !== pathStr) { return undefined } rule.transforms.forEach(transform => { const {funcName, data} = this.getTransformData(transform) const func = expandedTransformers[funcName](data) const r = func({ original: obj, current, indent, query: this._queryManipulator.getQuery, copyBag, }) current = r.current }) }) if (current !== obj) { return current } if (Array.isArray(obj)) { if (obj.length === 0) { return '[]' } const collapse = path.length !== 0 let ret = '[' + copyToClipboardButton(obj, copyBag) obj.forEach(val => { ret += `\n${indent}` ret += this.renderExpandedRecursively(val, copyBag, path, level + 1) }) ret += `\n${lastIndent}]` if (collapse) { ret = nestedCollapseTemplate('[…]', ret) } return ret } if (isObject(obj)) { const keys = Object.keys(obj).sort() if (keys.length === 0) { return '{}' } const collapse = path.length !== 0 let ret = '{' + copyToClipboardButton(obj, copyBag) if (level === 0) { ret += linkToClipboardButton(cursor, copyBag) ret += this.showContextButtons(cursor, obj) } keys.forEach((k) => { const val = obj[k] ret += `\n${indent}${k}: ` ret += this.renderExpandedRecursively(val, copyBag, path.concat([k]), level + 1) }) ret += `\n${lastIndent}}` if (collapse) { ret = nestedCollapseTemplate('{…}', ret) } return ret } let v: string if (typeof obj === 'string') { obj = obj.trimRight() if (obj.includes('\n')) { v = `\n${indent}` + obj.split('\n').join(`\n${indent}`) } else { v = obj } } else { v = JSON.stringify(obj) } v = `<span class="strong value" data-key="${escape(pathStr)}" data-obj="${escape(JSON.stringify(originalObj))}">${v}</span>` return v } static toLogfmt(entry: any): string { const parts = [] const keys = Object.keys(entry).sort() for (const k of keys) { let v = entry[k] if (v === null) { continue } if (isObject(v) || Array.isArray(v)) { v = JSON.stringify(v) } if (v.length > 100) { // Skip values that are too long. They slow rendering, and won't fit on the screen anyways. continue } parts.push(`${k}=${v}`) } return parts.join(' ') } private showContextButtons(cursor: any, obj: any) { if (!this.config.contextFilters) { return [] } return this.config.contextFilters.map(f => showContextButton(f, obj, cursor, this._queryManipulator)).join("") } } function timestamp(logFormatter): CollapsedTransform { return (input: CollapsedFormatField): CollapsedFormatField => { if (!input.original) { return input } let m = moment(input.original) if (logFormatter.getTimeZone() === TimeZone.UTC) { m = m.utc() } input.current = m.format("YYYY-MM-DD HH:mm:ss.SSSZZ") return input } } function showIfDifferent(_: LogFormatter, field: string): CollapsedTransform { return (input: CollapsedFormatField): CollapsedFormatField => { const other = input.entry[field] if (input.original === other) { input.current = null } return input } } type ReplaceTransform = { search: string replace: string } function replace(_: LogFormatter, rt: ReplaceTransform): CollapsedTransform { const re = new RegExp(rt.search) return (input: CollapsedFormatField) => { input.current = String(input.current).replace(re, rt.replace) return input } } function mapValue(_: LogFormatter, mapping: Record<string, string>): CollapsedTransform { return (input: CollapsedFormatField) => { const lookup = mapping[input.current] if (lookup !== undefined) { input.current = lookup } return input } } function mapClass(_: LogFormatter, mapping: Record<string, string>): CollapsedTransform { return (input: CollapsedFormatField) => { const lookup = mapping[input.current] if (lookup !== undefined) { input.classes.push(lookup) } return input } } function addClass(_: LogFormatter, c: string): CollapsedTransform { return (input: CollapsedFormatField) => { input.classes.push(c) return input } } function upperCase(): CollapsedTransform { return (input: CollapsedFormatField): CollapsedFormatField => { if (!input?.current) { return input } input.current = input.current.toUpperCase() return input } } function randomStableColor(): CollapsedTransform { return (field: CollapsedFormatField): CollapsedFormatField => { if (!field.original) { return field } const RAINBOW_RANGE = 20 const idx = simpleHash(field.original) % RAINBOW_RANGE field.classes.push(`rainbow-${idx}`) return field } } // https://stackoverflow.com/a/8831937/11125 function simpleHash(str: string): number { let hash = 0 if (str.length === 0) { return 0 } // tslint:disable-next-line:no-bitwise for (let i = 0; i < str.length; i++) { const chr = str.charCodeAt(i) // tslint:disable-next-line:no-bitwise hash = ((hash << 5) - hash) + chr // tslint:disable-next-line:no-bitwise hash |= 0 // Convert to 32bit integer } return Math.abs(hash) } function isObject(obj: any): boolean { return obj === Object(obj) } function makeIndent(level: number): string { let ret = '' for (let i = 0; i < level; i++) { ret += ' ' } return ret } function nestedCollapseTemplate(placeholder: string, collapsed: string): string { return `<span class="show-nested toggle">${placeholder}</span><span class="is-hidden"><span class="hide-nested toggle">[collapse]</span> ${collapsed}</span>` } export function copyToClipboardButton(v: any, copyBag: any[]): string { // Save the reference to the value to the next index in the array, and track index in "data-copy" copyBag.push(v) return `<a><span class="icon context-button copy-button tooltip is-tooltip-right" data-tooltip="Copy value to clipboard" data-copy="${copyBag.length - 1}"><i class="mdi mdi-content-copy"></i></span></a>` } export function linkToClipboardButton(cursor: any, copyBag: any[]): string { copyBag.push(cursor) return `<a><span class="icon context-button link-button tooltip is-tooltip-right" data-tooltip="Copy sharable link to clipboard" data-copy="${copyBag.length - 1}"><i class="mdi mdi-link"></i></span></a>` } // https://stackoverflow.com/a/13218838/11125 // Modified to include elasticsearch "searchable" replacement key function flatten(obj) { const res = {}; (function recurse(o, current, currentNonIndexKey) { for (const key of Object.keys(o)) { // XXX: Sometimes key is an index of an array, rather than a key of an object. // XXX: This number will have to be stripped when filtering in ES. const value = o[key] const newKey = (current ? current + "." + key : key) // joined key with dot let newNonIndexKey if (Array.isArray(o)) { newNonIndexKey = (currentNonIndexKey ? currentNonIndexKey : "") } else { newNonIndexKey = (currentNonIndexKey ? currentNonIndexKey + `.${key}` : key) } if (value && typeof value === "object") { recurse(value, newKey, newNonIndexKey) // it's a nested object, so do it again } else { res[newKey] = { value, searchableKey: newNonIndexKey, } } } })(obj) return res } export function showContextButton(filter: ContextFilter, obj: any, cursor: any, qm: QueryManipulator): string { const flatObj = flatten(obj) const matchField = (field: string, keep: string) => { if (keep.startsWith("/") && keep.endsWith("/")) { keep = keep.substr(1, keep.length - 2) return field.match(new RegExp(keep)) } else { return field === keep } } // Search for key specified in context filter. const newTerms = (filter.keep || []) .map(k => Object.keys(flatObj).find(field => matchField(field, k) ? k : undefined)) .filter(k => k) .map(k => `${flatObj[k].searchableKey}:${JSON.stringify(flatObj[k].value)}`) .join(" ") // Only create a link when the context field is in the log entry, // or in the case that "keep" is empty, we always want to show link to clear out terms. if (!newTerms && filter.keep) { return undefined } const contextQuery = qm.getQuery() .withFocus(obj._id, JSON.stringify(cursor)) .withFixedTimeRange() .withNewTerms(newTerms) const url = `?${contextQuery.toURL()}` const icon = filter.icon || "mdi-filter-variant-remove" return `<a href="${url}"><span class="icon context-button show-context-button tooltip is-tooltip-right" data-tooltip="${filter.title}"><i class="mdi ${icon}"></i></span></a>` } interface JavaExceptionMatch { // If a fqcn has this prefix, it will turn into a link. fqcnMatch: string // The link generated for a matched fqcn href: string } interface JavaExceptionConfig { matches: JavaExceptionMatch[] } function javaException(config: JavaExceptionConfig): ExpandedTransform { return (field: ExpandedFormatField): ExpandedFormatField => { const indent = field.indent const lines = field.current.split('\n') const formatted = [] for (const line of lines) { if (!/\s/.test(line[0])) { formatted.push(`<span class="has-text-danger">${line}</span>`) } else { const match = line.match(/^(\s+)at (.*)\((.*?)(:\d+)?\)$/) if (!match) { formatted.push(line) continue } const [, space, fqcn, file, lineno] = match let right = `${fqcn}(${file}${lineno || ""})` const exceptionMatch = config.matches.find(m => fqcn.match(new RegExp(m.fqcnMatch))) if (exceptionMatch) { const parts = fqcn.split('.') const firstCapital = parts.findIndex((i: string) => i[0].toLowerCase() !== i[0]) const path = parts.slice(0, firstCapital).join('/') const href = exceptionMatch.href .replace("${fqcn}", fqcn) .replace("${path}", path) .replace("${file}", file) .replace("${lineno}", lineno) right = `<a target="_blank" class="filter-link" href="${href}">${right}</a>` } formatted.push(`${space}at ${right}`) } } field.current = `${copyToClipboardButton(field.original, field.copyBag)}\n${indent}` + formatted.join(`\n${indent}`) return field } } function shortenJavaFqcn(): CollapsedTransform { return (field: CollapsedFormatField): CollapsedFormatField => { if (!/^\w+(\.\w+)+$/.test(field.original)) { // Only format Java class names return field } const parts = field.original.split('.') field.current = parts .map((p, idx) => (p.length > 1 && idx !== parts.length - 1) ? p[0] : p) .join('.') field.tooltip = field.original return field } } type LinkConfig = { title: string match: string href: string icon: string } // This is just a placeholder. The actual functionality is in valueHover. function link(_: LinkConfig): ExpandedTransform { return (field: ExpandedFormatField): ExpandedFormatField => { return field } } export const collapsedTransformers: { [key: string]: (lf: LogFormatter, _: any) => CollapsedTransform } = { timestamp, upperCase, mapValue, mapClass, addClass, replace, randomStableColor, shortenJavaFqcn, showIfDifferent, } export const expandedTransformers: { [key: string]: (_: any) => ExpandedTransform } = { javaException, link, }
the_stack
import {AfterViewInit, Directive, ElementRef, EventEmitter, Input, NgZone, Output, Renderer2, OnDestroy} from "@angular/core"; import {CommonUtils} from "../../core/utils/common-utils"; import {AbstractJigsawViewBase} from "../../common"; type Style = { left?: string | number, right?: string | number, top?: string | number, bottom?: string | number, width?: string, height?: string, }; type Position = { host: Style, badge?: Style }; @Directive({ selector: '[jigsawBadge], [jigsaw-badge]' }) export class JigsawBadgeDirective extends AbstractJigsawViewBase implements AfterViewInit, OnDestroy { private _badge: HTMLElement; private _removeBadgeClickHandler: Function; private _jigsawBadgeValue: string | number | 'dot'; /** * @NoMarkForCheckRequired */ @Input() public get jigsawBadgeValue(): string | number | "dot" { return this._jigsawBadgeValue; } public set jigsawBadgeValue(value: string | number | "dot") { if (this._jigsawBadgeValue != value) { this._jigsawBadgeValue = value; this._addBadge(); } } /** * @NoMarkForCheckRequired */ @Input() public jigsawBadgeSize: 'large' | 'normal' | 'small' = 'normal'; /** * @NoMarkForCheckRequired */ @Input() public jigsawBadgeStatus: 'normal' | 'success' | 'warn' | 'error' | 'critical' = 'critical'; /** * @NoMarkForCheckRequired */ @Input() public jigsawBadgeMaxValue: number; /** * @NoMarkForCheckRequired */ @Input() public jigsawBadgeMask: "none" | "dark" | "light" = "none"; /** * @NoMarkForCheckRequired */ @Input() public jigsawBadgeStyle: "solid" | "border" | "none" = "solid" private _hOffset: number = 0; /** * @NoMarkForCheckRequired */ @Input() public get jigsawBadgeHorizontalOffset(): number { return this._hOffset; } public set jigsawBadgeHorizontalOffset(value: number) { value = Number(value); if (this._hOffset == value) { return; } this._hOffset = value; this._addBadge(); } /** * @NoMarkForCheckRequired */ @Input() public jigsawBadgeTitle: string; /** * @NoMarkForCheckRequired */ @Input() public jigsawBadgePointerCursor: boolean; /** * @NoMarkForCheckRequired */ @Input() public jigsawBadgePosition: 'leftTop' | 'rightTop' | 'leftBottom' | 'rightBottom' | 'left' | 'right' = 'rightTop'; @Output() public jigsawBadgeClick: EventEmitter<string | number | "dot"> = new EventEmitter<string | number | "dot">(); constructor(private _elementRef: ElementRef, protected _zone: NgZone, private _render: Renderer2) { super(); } ngAfterViewInit(): void { this._addBadge(); } ngOnDestroy(): void { if (this._removeBadgeClickHandler) { this._removeBadgeClickHandler(); } } private _addBadge(): void { if (!this.initialized) { return; } if (this._badge) { this._elementRef.nativeElement.removeChild(this._badge); this._badge = null; } this._setHostStyle(); this._badge = window.document.createElement('div'); this._badge.classList.add("jigsaw-badge-host"); const realBadge = this._getRealBadge(); const classPre = this.jigsawBadgeValue == 'dot' ? "jigsaw-badge-dot" : "jigsaw-badge"; const position: Position = this._calPosition(); // 设置徽标顶层元素的位置和尺寸 this._render.setStyle(this._badge, 'left', position.host.left); this._render.setStyle(this._badge, 'right', position.host.right); this._render.setStyle(this._badge, 'top', position.host.top); this._render.setStyle(this._badge, 'bottom', position.host.bottom); this._render.setStyle(this._badge, 'width', position.host.width); this._render.setStyle(this._badge, 'height', position.host.height); // 徽标自身的位置 const positionStr = `left:${position.badge.left}; top:${position.badge.top}; right:${position.badge.right}; bottom:${position.badge.bottom}`; const title = this.jigsawBadgeTitle ? this.jigsawBadgeTitle : ''; this._badge.innerHTML = this.jigsawBadgeValue == 'dot' ? `<div style="${positionStr}" title="${title}"></div>` : `<div style="display: ${!!realBadge ? 'flex' : 'none'};${positionStr}; white-space: nowrap; align-items: center; justify-content: center;" title="${title}">${realBadge}</div>`; this._badge.children[0].classList.add(classPre); this._badge.children[0].classList.add(`${classPre}-size-${this.jigsawBadgeSize}`); let badgeStyle = '-dot'; if (this.jigsawBadgeValue != 'dot') { badgeStyle = this.jigsawBadgeStyle == 'none' ? '' : `-${this.jigsawBadgeStyle}`; } if (this.jigsawBadgeMask != "none") { const calibrateSize = this._calibrateMaskSize(); const maskStyle = calibrateSize != 0 ? `border-width: ${calibrateSize}px` : ''; this._badge.innerHTML += `<div style="${maskStyle}"></div>`; const classMaskPre = "jigsaw-badge-mask"; const backgroundClass = `${classMaskPre}-${this.jigsawBadgeMask}`; let maskPos = <string>this.jigsawBadgePosition; if ((/(right.+)|(left.+)/).test(this.jigsawBadgePosition)) { maskPos = this.jigsawBadgePosition.toLowerCase().replace(/(right)/, "$1-").replace(/(left)/, "$1-"); } const positionClass = `${classMaskPre}-${maskPos}`; const maskSizeClass = `${classMaskPre}-${this.jigsawBadgeSize}`; this._badge.children[1].classList.add(classMaskPre); this._badge.children[1].classList.add(backgroundClass); this._badge.children[1].classList.add(positionClass); this._badge.children[1].classList.add(maskSizeClass); if (this.jigsawBadgePosition == "right" || this.jigsawBadgePosition == "left") { this._badge.children[1].classList.add(`${classMaskPre}-background-${this.jigsawBadgeMask}`); } if (this.jigsawBadgeValue == "dot") { this._badge.children[0].classList.add(`jigsaw-badge-${this.jigsawBadgeStatus == 'critical' ? 'error' : this.jigsawBadgeStatus}`); } badgeStyle = this.jigsawBadgeValue == 'dot' ? badgeStyle : ''; } this._badge.children[0].classList.add(`jigsaw-badge${badgeStyle}-${this.jigsawBadgeStatus == 'critical' ? 'error' : this.jigsawBadgeStatus}`); if (this.jigsawBadgePointerCursor) { this._badge.children[0].classList.add(`jigsaw-badge-cursor`); } else { this._badge.children[0].classList.add(`jigsaw-badge-cursor-default`); } if (this._removeBadgeClickHandler) { this._removeBadgeClickHandler(); } this._removeBadgeClickHandler = this._render.listen(this._badge.children[0], 'click', (event) => { event.preventDefault(); event.stopPropagation(); this.jigsawBadgeClick.emit(this.jigsawBadgeValue); }); this._elementRef.nativeElement.insertAdjacentElement("afterbegin", this._badge); } // 设置宿主的样式,徽标本身采用absolute布局,所以需要考虑宿主的position和overflow private _setHostStyle(): void { const hostStyle = getComputedStyle(this._elementRef.nativeElement); if (["absolute", "relative", "fixed", "sticky"].findIndex(item => item == hostStyle.position) == -1) { this._elementRef.nativeElement.style.position = "relative"; } if (hostStyle.overflow == 'hidden' || hostStyle.overflow == 'scroll') { this._elementRef.nativeElement.style.overflow = "visible"; } } // 判断是否需要限定mask的尺寸,最大不能超过当前宿主的宽高 private _calibrateMaskSize(): number { const hostStyle = getComputedStyle(this._elementRef.nativeElement); const width = parseInt(hostStyle.width); const height = parseInt(hostStyle.height); const compareSize = Math.floor(Math.min(width, height) / 2); const maskSize = this.jigsawBadgeSize == 'small' ? 20 : (this.jigsawBadgeSize == 'large' ? 28 : 24); return compareSize != 0 && maskSize > compareSize ? compareSize : 0; } private _getRealBadge(): string { if (this._jigsawBadgeValue == 'dot' || CommonUtils.isUndefined(this._jigsawBadgeValue)) { return ''; } const badgeStr = this._jigsawBadgeValue.toString(); const num = parseInt(badgeStr); if (isNaN(num)) { return (/(^fa\s+fa-.+$)|(^iconfont\s+iconfont-.+$)/).test(badgeStr) ? `<span class="${badgeStr}"></span>` : this._jigsawBadgeValue.toString(); } else { return CommonUtils.isDefined(this.jigsawBadgeMaxValue) && num > this.jigsawBadgeMaxValue ? `${this.jigsawBadgeMaxValue}+` : num.toString(); } } private _calPosition(): Position { if (this.jigsawBadgeMask != "none") { return this._calMaskPosition(); } const differ = this._getDiffer(); switch (this.jigsawBadgePosition) { case "left": const left: Position = { host: {left: 0, top: `50%`} }; if (this.jigsawBadgeValue == 'dot') { left.badge = { left: `${-(differ + this._hOffset)}px`, top: `calc(50% - ${differ}px)` } } else { left.badge = { right: `calc( 100% - ${differ + 2 + this._hOffset}px )`, top: `calc( 50% - ${differ}px )` } } return left; case "leftBottom": return { host: {left: 0, top: '100%'}, badge: {left: `${-(differ + this._hOffset)}px`, top: `calc( 100% - ${differ}px)`} }; case "leftTop": return { host: {left: 0, top: 0}, badge: {left: `${-(differ + this._hOffset)}px`, top: `${-differ}px`} }; case "right": const right: Position = { host: {right: 0, top: `50%`} }; if (this.jigsawBadgeValue == 'dot') { right.badge = { right: `${-(differ + this._hOffset)}px`, top: `calc(50% - ${differ}px)` }; } else { right.badge = { left: `calc( 100% - ${differ + 2 + this._hOffset}px)`, top: `calc(50% - ${differ}px)` }; } return right; case "rightBottom": return { host: {right: 0, top: '100%'}, badge: {right: `${-(differ + this._hOffset)}px`, top: `calc( 100% - ${differ}px)`} }; case "rightTop": return { host: {right: 0, top: 0}, badge: {right: `${-(differ + this._hOffset)}px`, top: `${-differ}px`} }; } } private _calMaskPosition(): Position { const calibrateSize = this._calibrateMaskSize() / 2; const differ = this._getDiffer(); switch (this.jigsawBadgePosition) { case "left": return { host: {left: 0, top: 0, width: '30%', height: '100%'}, badge: {left: `calc(50% - ${differ}px)`, top: `calc(50% - ${differ}px)`} }; case "leftBottom": return this._getBottomPosition('left', differ, calibrateSize); case "leftTop": return this._getTopPosition('left', differ, calibrateSize); case "right": return { host: {right: 0, top: 0, width: '30%', height: '100%'}, badge: {top: `calc(50% - ${differ}px)`, right: `calc(50% - ${differ}px)`} }; case "rightBottom": return this._getBottomPosition('right', differ, calibrateSize); case "rightTop": return this._getTopPosition('right', differ, calibrateSize); } } private _getDiffer(): number { let differ = 0; if (this.jigsawBadgeValue == 'dot') { if (this.jigsawBadgeSize == "large") { differ = 8; } else if (this.jigsawBadgeSize == "normal") { differ = 6; } else { differ = 4; } } else { if (this.jigsawBadgeSize == "large") { differ = 12; } else if (this.jigsawBadgeSize == "normal") { differ = 10; } else { differ = 8; } } return differ; } // 计算上面两侧位置 private _getTopPosition(pos: 'right' | 'left', differ: number, calibrateSize: number): Position { const position: Position = { host: {top: 0} }; position.host[pos] = 0; const offset = this.jigsawBadgeValue == 'dot' ? 10 : (this.jigsawBadgeSize == "large" ? 6 : 4); differ = calibrateSize == 0 ? offset : calibrateSize - (differ - 1); position.badge = {top: `${differ}px`}; position.badge[pos] = `${differ}px`; return position; } // 计算下面两侧位置 private _getBottomPosition(pos: 'right' | 'left', differ: number, calibrateSize: number): Position { const position: Position = { host: {top: '100%'} }; position.host[pos] = 0; let left = 0, right = 0; if (this.jigsawBadgeValue == 'dot') { if (this.jigsawBadgeSize == "large") { left = calibrateSize == 0 ? 24 : calibrateSize + (differ + 2); } else if (this.jigsawBadgeSize == "normal") { left = calibrateSize == 0 ? 20 : calibrateSize + (differ + 2); } else { left = calibrateSize == 0 ? 18 : calibrateSize + (differ + 2); } right = calibrateSize == 0 ? 8 : calibrateSize - (differ - 1); } else { left = calibrateSize == 0 ? (3 * differ) - 5 : calibrateSize + (differ + 2); right = calibrateSize == 0 ? differ - 5 : calibrateSize - (differ - 1); } position.badge = {top: `${-left}px`}; position.badge[pos] = `${right}px`; return position; } }
the_stack
import { DeepPartial } from '../utils/DeepPartial'; import { deepMerge } from '../utils/DeepMerge'; import { genID } from '../utils'; import { deepCopy } from '../utils/DeepCopy'; import { Logger } from '../Logger'; import { Match } from '../Match'; import { Station, BOT_DIR } from '../Station'; import { MissingFilesError } from '../DimensionError'; import { Design } from '../Design'; import { Tournament } from '../Tournament'; import { Plugin } from '../Plugin'; import { Database } from '../Plugin/Database'; import { Storage } from '../Plugin/Storage'; import { existsSync, mkdirSync } from 'fs'; import { Agent } from '../Agent'; import { AgentClassTypeGuards } from '../utils/TypeGuards'; /** * Some standard database type strings */ export enum DatabaseType { /** * Represents no database used */ NONE = 'none', /** * Represents mongodb database used */ MONGO = 'mongo', /** * Firestore DB is used */ FIRESTORE = 'firestore', } export enum StorageType { /** * Represents no storage used, all files stored locally on devide */ NONE = 'none', /** * Represents gcloud storage used */ GCLOUD = 'gcloud', /** Using local file system for storage*/ FS = 'fs-storage', } /** * An id generated using nanoid */ export type NanoID = string; /** * Dimension configurations */ export interface DimensionConfigs { /** Name of the dimension */ name: string; /** * Whether or not to activate the Station * @default `true` */ activateStation: boolean; /** * Whether the station should observe this Dimension * @default `true` */ observe: boolean; /** The logging level for this Dimension */ loggingLevel: Logger.LEVEL; /** The default match configurations to use when creating matches using this Dimension */ defaultMatchConfigs: DeepPartial<Match.Configs>; /** An overriding ID to use for the dimension instead of generating a new one */ id: NanoID; /** * Whether to run Dimension in a more secure environment. * Requires rbash and setting up users beforehand and running dimensions in sudo mode * @default `false` */ secureMode: boolean; /** * String denoting what kind of backing database is being used * @default {@link DatabaseType.NONE} */ backingDatabase: string | DatabaseType; /** * String denoting what kind of backing storage is being used * @default {@link DatabaseType.NONE} */ backingStorage: string | StorageType; /** * Station configs to use */ stationConfigs: DeepPartial<Station.Configs>; /** * Whether to create a local temp bot folder. Default True. Required if you are letting Dimensions handle bot downloading, uploading etc. * @default `true` */ createBotDirectories: boolean; } /** * The Dimension framework for intiating a {@link Design} to then run instances of a {@link Match} or * {@link Tournament} on. */ export class Dimension { /** * A map of the matches running in this Dimension */ public matches: Map<NanoID, Match> = new Map(); /** * A map of the tournaments in this Dimension. */ public tournaments: Map<NanoID, Tournament> = new Map(); /** * This Dimension's name */ public name: string; /** * This dimension's ID. It is always a 6 character NanoID unless overrided through the {@link DimensionConfigs} */ public id: NanoID; /** * Logger */ public log = new Logger(); /** * The database plugin being used. Allows Dimensions to interact with a database and store {@link Match}, * {@link Tournament}, and user data, allowing for data persistance across instances. */ public databasePlugin: Database; /** * The storage plugin being used. Allows Dimensions to interact with a storage service and store user object data, * particuarly bot file uploads */ public storagePlugin: Storage; /** * The Station associated with this Dimension and current node instance */ public static Station: Station = null; /** * Stats */ public statistics = { tournamentsCreated: 0, matchesCreated: 0, }; /** * Dimension configs. Set to defaults */ public configs: DimensionConfigs = { name: '', activateStation: true, observe: true, loggingLevel: Logger.LEVEL.INFO, defaultMatchConfigs: { secureMode: false, }, secureMode: false, backingDatabase: DatabaseType.NONE, backingStorage: StorageType.NONE, id: 'oLBptg', stationConfigs: {}, createBotDirectories: true, }; /** * Indicator of whether cleanup was called already or not */ private cleaningUp: Promise<any> = null; constructor( public design: Design, configs: DeepPartial<DimensionConfigs> = {} ) { // override configs with user provided configs this.configs = deepMerge(this.configs, configs); // generate ID if not provided if (!configs.id) { this.id = Dimension.genDimensionID(); } else { this.id = configs.id; } this.log.level = this.configs.loggingLevel; if (this.configs.stationConfigs.loggingLevel === undefined) { this.configs.stationConfigs.loggingLevel = this.configs.loggingLevel; } // open up a new station for the current node process if it hasn't been opened yet and there is a dimension that // is asking for a station to be initiated if (this.configs.activateStation === true && Dimension.Station == null) { Dimension.Station = new Station( 'Station', [], this.configs.stationConfigs ); } // default match log level and design log level is the same as passed into the dimension this.configs.defaultMatchConfigs.loggingLevel = this.configs.loggingLevel; this.design.setLogLevel(this.configs.loggingLevel); // set name if (this.configs.name) { this.name = this.configs.name; } else { this.name = `dimension_${this.id}`; } this.log.identifier = `${this.name} Log`; // log important messages regarding security if (this.configs.secureMode) { this.setupSecurity(); } else { this.log.warn( `WARNING: Running in non-secure mode. You will not be protected against malicious bots` ); } // setting securemode in dimension config also sets it for default match configs this.configs.defaultMatchConfigs.secureMode = this.configs.secureMode; // set up cleanup functions process.on('exit', async () => { try { await this.cleanup(); } catch (err) { console.error(err); } process.exit(); }); process.on('SIGINT', async () => { try { await this.cleanup(); } catch (err) { console.error(err); } process.exit(); }); // make the station observe this dimension when this dimension is created if (this.configs.observe === true && Dimension.Station != null) Dimension.Station.observe(this); this.log.info(`Created Dimension - ID: ${this.id}, Name: ${this.name}`); this.log.detail('Dimension Configs', this.configs); // create bot directories if (!existsSync(BOT_DIR) && this.configs.createBotDirectories) { mkdirSync(BOT_DIR, { recursive: true }); } } /** * Create a match with the given files and any optional {@link Match.Configs}. Resolves with the initialized * {@link Match} object as specified by the {@link Design} of this {@link Dimension} * * Rejects if an error occurs. * * @param files - List of files or objects to use to generate agents and use for a new match * @param matchOptions - Options for the created match * @param configs - Configurations that are {@link Design} dependent */ public async createMatch( files: | Agent.GenerationMetaData_FilesOnly | Agent.GenerationMetaData_CreateMatch, configs?: DeepPartial<Match.Configs> ): Promise<Match> { if (!files.length) { throw new MissingFilesError('No files provided for match'); } // override dimension defaults with provided configs let matchConfigs = deepCopy(this.configs.defaultMatchConfigs); matchConfigs = deepMerge(matchConfigs, configs); // create new match let match: Match; if (AgentClassTypeGuards.isGenerationMetaData_FilesOnly(files)) { match = new Match(this.design, files, matchConfigs, this); } else { match = new Match(this.design, files, matchConfigs, this); } this.statistics.matchesCreated++; // store match into dimension this.matches.set(match.id, match); // Initialize match and return it await match.initialize(); return match; } /** * Runs a match with the given files and any optional {@link Match.Configs}. It rejects if an error occurs. Some * errors include {@link MatchDestroyedError} which happens when {@link Match.destroy} is called. * * This also automatically stores matches into the {@link Database} if database is active and configured to save * * Resolves with the results of the match as specified by the {@link Design} of this {@link Dimension} * * @param files - List of files or objects to use to generate agents and use for a new match * @param matchOptions - Options for the created match * @param configs - Configurations that are `Design` dependent. These configs are passed into `Design.initialize` * `Design.update` and `Design.storeResults` */ public async runMatch( files: | Agent.GenerationMetaData_FilesOnly | Agent.GenerationMetaData_CreateMatch, configs?: DeepPartial<Match.Configs> ): Promise<any> { const match = await this.createMatch(files, configs); // Get results const results = await match.run(); // if database plugin is active and saveMatches is set to true, store match if (this.hasDatabase()) { if (this.databasePlugin.configs.saveMatches) { this.databasePlugin.storeMatch(match, this.id); } } // Return the results return results; } /** * Create a tournament * * @param files - The initial files to make competitors in this tournament. Can also specify the name and an * existingID, which is the playerID. If database is used, this existingID is used to find the assocciated user with * this ID. * * @param configs - Configuration for the tournament * * @see {@link Tournament} for the different tournament types * @returns a Tournament of the specified type */ public createTournament( files: | Array<string> | Array<{ file: string; name: string; existingId?: string }>, configs: Tournament.TournamentConfigsBase ): Tournament { const id = Tournament.genTournamentClassID(); let newTourney: Tournament; if (configs.loggingLevel === undefined) { // set default logging level to that of the dimension configs.loggingLevel = this.log.level; } // merge default match configs from dimension const dimensionDefaultMatchConfigs = deepCopy( this.configs.defaultMatchConfigs ); configs = deepMerge( { defaultMatchConfigs: dimensionDefaultMatchConfigs }, configs ); switch (configs.type) { case Tournament.Type.LADDER: newTourney = new Tournament.Ladder( this.design, files, configs, id, this ); break; case Tournament.Type.ELIMINATION: newTourney = new Tournament.Elimination( this.design, files, configs, id, this ); break; } this.statistics.tournamentsCreated++; this.tournaments.set(newTourney.id, newTourney); return newTourney; } // TODO give option to directly create a Ladder/Elimination ... tourney with createLadderTournament etc. /** * Get the station */ getStation(): Station { return Dimension.Station; } /** * Removes a match by id. Returns true if removed, false if nothing was removed */ public async removeMatch(matchID: NanoID): Promise<boolean> { if (this.matches.has(matchID)) { const match = this.matches.get(matchID); await match.destroy(); return this.matches.delete(matchID); } return false; } /** * Sets up necessary security and checks if everything is in place */ private setupSecurity() { // } /** * Generates a 6 character nanoID string for identifying dimensions */ public static genDimensionID(): string { return genID(6); } /** * Uses a particular plugin in the dimensions framework. * * @param plugin - the plugin */ public async use(plugin: Plugin): Promise<void> { switch (plugin.type) { case Plugin.Type.DATABASE: this.log.info('Attaching Database Plugin ' + plugin.name); // set to unknown to tell dimensions that there is some kind of database, we dont what it is yet this.configs.backingDatabase = 'unknown'; this.databasePlugin = <Database>plugin; await this.databasePlugin.initialize(this); break; case Plugin.Type.STORAGE: this.log.info('Attaching Storage Plugin ' + plugin.name); this.configs.backingStorage = 'unknown;'; this.storagePlugin = <Storage>plugin; await this.storagePlugin.initialize(this); break; default: break; } await plugin.manipulate(this); } /** * Returns true if dimension has a database backing it */ public hasDatabase(): boolean { return ( this.databasePlugin !== undefined && this.configs.backingDatabase !== DatabaseType.NONE ); } /** * Returns true if dimension has a storage plugin backing it */ public hasStorage(): boolean { return ( this.storagePlugin && this.configs.backingStorage !== StorageType.NONE ); } /** * Cleanup function that cleans up any resources used and related to this dimension. For use right before * process exits and during testing. */ async cleanup(): Promise<void> { if (this.cleaningUp) { return this.cleaningUp; } this.log.info('Cleaning up'); const cleanUpPromises: Array<Promise<any>> = []; cleanUpPromises.push(this.cleanupMatches()); cleanUpPromises.push(this.cleanupTournaments()); if (this.getStation()) { cleanUpPromises.push(this.getStation().stop()); } this.cleaningUp = Promise.all(cleanUpPromises); await this.cleaningUp; } async cleanupMatches(): Promise<Array<void>> { const cleanUpPromises: Array<Promise<void>> = []; this.matches.forEach((match) => { cleanUpPromises.push(match.destroy()); }); return Promise.all(cleanUpPromises); } async cleanupTournaments(): Promise<Array<void>> { const cleanUpPromises: Array<Promise<void>> = []; this.tournaments.forEach((tournament) => { cleanUpPromises.push(tournament.destroy()); }); return Promise.all(cleanUpPromises); } } /** * Creates a dimension for use to start matches, run tournaments, etc. * @param design - the design to use * @param configs - optional configurations for the dimension */ export function create( design: Design, configs?: DeepPartial<DimensionConfigs> ): Dimension { return new Dimension(design, configs); }
the_stack
import { SerializableHash } from "@stablelib/hash"; import { readUint32BE, writeUint32BE } from "@stablelib/binary"; import { wipe } from "@stablelib/wipe"; export const DIGEST_LENGTH = 64; export const BLOCK_SIZE = 128; /** * SHA-2-512 cryptographic hash algorithm. */ export class SHA512 implements SerializableHash { /** Length of hash output */ readonly digestLength: number = DIGEST_LENGTH; /** Block size */ readonly blockSize: number = BLOCK_SIZE; // Note: Int32Array is used instead of Uint32Array for performance reasons. protected _stateHi = new Int32Array(8); // hash state, high bytes protected _stateLo = new Int32Array(8); // hash state, low bytes private _tempHi = new Int32Array(16); // temporary state, high bytes private _tempLo = new Int32Array(16); // temporary state, low bytes private _buffer = new Uint8Array(256); // buffer for data to hash private _bufferLength = 0; // number of bytes in buffer private _bytesHashed = 0; // number of total bytes hashed private _finished = false; // indicates whether the hash was finalized constructor() { this.reset(); } protected _initState() { this._stateHi[0] = 0x6a09e667; this._stateHi[1] = 0xbb67ae85; this._stateHi[2] = 0x3c6ef372; this._stateHi[3] = 0xa54ff53a; this._stateHi[4] = 0x510e527f; this._stateHi[5] = 0x9b05688c; this._stateHi[6] = 0x1f83d9ab; this._stateHi[7] = 0x5be0cd19; this._stateLo[0] = 0xf3bcc908; this._stateLo[1] = 0x84caa73b; this._stateLo[2] = 0xfe94f82b; this._stateLo[3] = 0x5f1d36f1; this._stateLo[4] = 0xade682d1; this._stateLo[5] = 0x2b3e6c1f; this._stateLo[6] = 0xfb41bd6b; this._stateLo[7] = 0x137e2179; } /** * Resets hash state making it possible * to re-use this instance to hash other data. */ reset(): this { this._initState(); this._bufferLength = 0; this._bytesHashed = 0; this._finished = false; return this; } /** * Cleans internal buffers and resets hash state. */ clean() { wipe(this._buffer); wipe(this._tempHi); wipe(this._tempLo); this.reset(); } /** * Updates hash state with the given data. * * Throws error when trying to update already finalized hash: * instance must be reset to update it again. */ update(data: Uint8Array, dataLength: number = data.length): this { if (this._finished) { throw new Error("SHA512: can't update because hash was finished."); } let dataPos = 0; this._bytesHashed += dataLength; if (this._bufferLength > 0) { while (this._bufferLength < BLOCK_SIZE && dataLength > 0) { this._buffer[this._bufferLength++] = data[dataPos++]; dataLength--; } if (this._bufferLength === this.blockSize) { hashBlocks(this._tempHi, this._tempLo, this._stateHi, this._stateLo, this._buffer, 0, this.blockSize); this._bufferLength = 0; } } if (dataLength >= this.blockSize) { dataPos = hashBlocks(this._tempHi, this._tempLo, this._stateHi, this._stateLo, data, dataPos, dataLength); dataLength %= this.blockSize; } while (dataLength > 0) { this._buffer[this._bufferLength++] = data[dataPos++]; dataLength--; } return this; } /** * Finalizes hash state and puts hash into out. * If hash was already finalized, puts the same value. */ finish(out: Uint8Array): this { if (!this._finished) { const bytesHashed = this._bytesHashed; const left = this._bufferLength; const bitLenHi = (bytesHashed / 0x20000000) | 0; const bitLenLo = bytesHashed << 3; const padLength = (bytesHashed % 128 < 112) ? 128 : 256; this._buffer[left] = 0x80; for (let i = left + 1; i < padLength - 8; i++) { this._buffer[i] = 0; } writeUint32BE(bitLenHi, this._buffer, padLength - 8); writeUint32BE(bitLenLo, this._buffer, padLength - 4); hashBlocks(this._tempHi, this._tempLo, this._stateHi, this._stateLo, this._buffer, 0, padLength); this._finished = true; } for (let i = 0; i < this.digestLength / 8; i++) { writeUint32BE(this._stateHi[i], out, i * 8); writeUint32BE(this._stateLo[i], out, i * 8 + 4); } return this; } /** * Returns the final hash digest. */ digest(): Uint8Array { const out = new Uint8Array(this.digestLength); this.finish(out); return out; } /** * Function useful for HMAC/PBKDF2 optimization. Returns hash state to be * used with restoreState(). Only chain value is saved, not buffers or * other state variables. */ saveState(): SavedState { if (this._finished) { throw new Error("SHA256: cannot save finished state"); } return { stateHi: new Int32Array(this._stateHi), stateLo: new Int32Array(this._stateLo), buffer: this._bufferLength > 0 ? new Uint8Array(this._buffer) : undefined, bufferLength: this._bufferLength, bytesHashed: this._bytesHashed }; } /** * Function useful for HMAC/PBKDF2 optimization. Restores state saved by * saveState() and sets bytesHashed to the given value. */ restoreState(savedState: SavedState): this { this._stateHi.set(savedState.stateHi); this._stateLo.set(savedState.stateLo); this._bufferLength = savedState.bufferLength; if (savedState.buffer) { this._buffer.set(savedState.buffer); } this._bytesHashed = savedState.bytesHashed; this._finished = false; return this; } /** * Cleans state returned by saveState(). */ cleanSavedState(savedState: SavedState) { wipe(savedState.stateHi); wipe(savedState.stateLo); if (savedState.buffer) { wipe(savedState.buffer); } savedState.bufferLength = 0; savedState.bytesHashed = 0; } } export type SavedState = { stateHi: Int32Array; stateLo: Int32Array; buffer: Uint8Array | undefined; bufferLength: number; bytesHashed: number; }; // Constants const K = new Int32Array([ 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 ]); function hashBlocks(wh: Int32Array, wl: Int32Array, hh: Int32Array, hl: Int32Array, m: Uint8Array, pos: number, len: number): number { let ah0 = hh[0], ah1 = hh[1], ah2 = hh[2], ah3 = hh[3], ah4 = hh[4], ah5 = hh[5], ah6 = hh[6], ah7 = hh[7], al0 = hl[0], al1 = hl[1], al2 = hl[2], al3 = hl[3], al4 = hl[4], al5 = hl[5], al6 = hl[6], al7 = hl[7]; let h: number, l: number; let th: number, tl: number; let a: number, b: number, c: number, d: number; while (len >= 128) { for (let i = 0; i < 16; i++) { const j = 8 * i + pos; wh[i] = readUint32BE(m, j); wl[i] = readUint32BE(m, j + 4); } for (let i = 0; i < 80; i++) { let bh0 = ah0; let bh1 = ah1; let bh2 = ah2; let bh3 = ah3; let bh4 = ah4; let bh5 = ah5; let bh6 = ah6; let bh7 = ah7; let bl0 = al0; let bl1 = al1; let bl2 = al2; let bl3 = al3; let bl4 = al4; let bl5 = al5; let bl6 = al6; let bl7 = al7; // add h = ah7; l = al7; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; // Sigma1 h = ((ah4 >>> 14) | (al4 << (32 - 14))) ^ ((ah4 >>> 18) | (al4 << (32 - 18))) ^ ((al4 >>> (41 - 32)) | (ah4 << (32 - (41 - 32)))); l = ((al4 >>> 14) | (ah4 << (32 - 14))) ^ ((al4 >>> 18) | (ah4 << (32 - 18))) ^ ((ah4 >>> (41 - 32)) | (al4 << (32 - (41 - 32)))); a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; // Ch h = (ah4 & ah5) ^ (~ah4 & ah6); l = (al4 & al5) ^ (~al4 & al6); a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; // K h = K[i * 2]; l = K[i * 2 + 1]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; // w h = wh[i % 16]; l = wl[i % 16]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; th = c & 0xffff | d << 16; tl = a & 0xffff | b << 16; // add h = th; l = tl; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; // Sigma0 h = ((ah0 >>> 28) | (al0 << (32 - 28))) ^ ((al0 >>> (34 - 32)) | (ah0 << (32 - (34 - 32)))) ^ ((al0 >>> (39 - 32)) | (ah0 << (32 - (39 - 32)))); l = ((al0 >>> 28) | (ah0 << (32 - 28))) ^ ((ah0 >>> (34 - 32)) | (al0 << (32 - (34 - 32)))) ^ ((ah0 >>> (39 - 32)) | (al0 << (32 - (39 - 32)))); a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; // Maj h = (ah0 & ah1) ^ (ah0 & ah2) ^ (ah1 & ah2); l = (al0 & al1) ^ (al0 & al2) ^ (al1 & al2); a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; bh7 = (c & 0xffff) | (d << 16); bl7 = (a & 0xffff) | (b << 16); // add h = bh3; l = bl3; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = th; l = tl; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; bh3 = (c & 0xffff) | (d << 16); bl3 = (a & 0xffff) | (b << 16); ah1 = bh0; ah2 = bh1; ah3 = bh2; ah4 = bh3; ah5 = bh4; ah6 = bh5; ah7 = bh6; ah0 = bh7; al1 = bl0; al2 = bl1; al3 = bl2; al4 = bl3; al5 = bl4; al6 = bl5; al7 = bl6; al0 = bl7; if (i % 16 === 15) { for (let j = 0; j < 16; j++) { // add h = wh[j]; l = wl[j]; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = wh[(j + 9) % 16]; l = wl[(j + 9) % 16]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; // sigma0 th = wh[(j + 1) % 16]; tl = wl[(j + 1) % 16]; h = ((th >>> 1) | (tl << (32 - 1))) ^ ((th >>> 8) | (tl << (32 - 8))) ^ (th >>> 7); l = ((tl >>> 1) | (th << (32 - 1))) ^ ((tl >>> 8) | (th << (32 - 8))) ^ ((tl >>> 7) | (th << (32 - 7))); a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; // sigma1 th = wh[(j + 14) % 16]; tl = wl[(j + 14) % 16]; h = ((th >>> 19) | (tl << (32 - 19))) ^ ((tl >>> (61 - 32)) | (th << (32 - (61 - 32)))) ^ (th >>> 6); l = ((tl >>> 19) | (th << (32 - 19))) ^ ((th >>> (61 - 32)) | (tl << (32 - (61 - 32)))) ^ ((tl >>> 6) | (th << (32 - 6))); a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; wh[j] = (c & 0xffff) | (d << 16); wl[j] = (a & 0xffff) | (b << 16); } } } // add h = ah0; l = al0; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[0]; l = hl[0]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[0] = ah0 = (c & 0xffff) | (d << 16); hl[0] = al0 = (a & 0xffff) | (b << 16); h = ah1; l = al1; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[1]; l = hl[1]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[1] = ah1 = (c & 0xffff) | (d << 16); hl[1] = al1 = (a & 0xffff) | (b << 16); h = ah2; l = al2; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[2]; l = hl[2]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[2] = ah2 = (c & 0xffff) | (d << 16); hl[2] = al2 = (a & 0xffff) | (b << 16); h = ah3; l = al3; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[3]; l = hl[3]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[3] = ah3 = (c & 0xffff) | (d << 16); hl[3] = al3 = (a & 0xffff) | (b << 16); h = ah4; l = al4; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[4]; l = hl[4]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[4] = ah4 = (c & 0xffff) | (d << 16); hl[4] = al4 = (a & 0xffff) | (b << 16); h = ah5; l = al5; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[5]; l = hl[5]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[5] = ah5 = (c & 0xffff) | (d << 16); hl[5] = al5 = (a & 0xffff) | (b << 16); h = ah6; l = al6; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[6]; l = hl[6]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[6] = ah6 = (c & 0xffff) | (d << 16); hl[6] = al6 = (a & 0xffff) | (b << 16); h = ah7; l = al7; a = l & 0xffff; b = l >>> 16; c = h & 0xffff; d = h >>> 16; h = hh[7]; l = hl[7]; a += l & 0xffff; b += l >>> 16; c += h & 0xffff; d += h >>> 16; b += a >>> 16; c += b >>> 16; d += c >>> 16; hh[7] = ah7 = (c & 0xffff) | (d << 16); hl[7] = al7 = (a & 0xffff) | (b << 16); pos += 128; len -= 128; } return pos; } export function hash(data: Uint8Array): Uint8Array { const h = new SHA512(); h.update(data); const digest = h.digest(); h.clean(); return digest; }
the_stack
import { MappedDataSource } from "./MappedDataSource"; import { singularize } from "inflection"; import { SingleSourceQueryOperationResolver } from "./SingleSourceQueryOperationResolver"; import { getTypeAccessorError } from "./utils/errors"; import { MappedSingleSourceOperation } from "./MappedSingleSourceOperation"; import { isBoolean, isPlainObject, transform } from "lodash"; import _debug from "debug"; import * as Knex from "knex"; import { indexBy, MemoizeGetter } from "./utils/utils"; import { isString, isFunction } from "util"; import { TypeGuard, Dict, PartialDeep } from "./utils/util-types"; import { AliasHierarchyVisitor } from "./AliasHierarchyVisitor"; import { assertType } from "./utils/assertions"; import { AssociationMappingRT, AssociationMapping, AssociationPreFetchConfig, MappedForeignOperation, AssociationPostFetchConfig, AssociationJoinConfig, JoinTypeId, } from "./AssociationMapping"; import { MappedSingleSourceQueryOperation } from "./MappedSingleSourceQueryOperation"; import { createJoinBuilder } from "./utils/JoinBuilder"; import { SourceAwareResolverContext } from "./SourceAwareResolverContext"; const debug = _debug("greldal:MappedAssociation"); /** * A mapped association represents an association among multiple data sources and encapsulates the knowledge of how to fetch a connected * data source while resolving an operation in another data source. * * @api-category MapperClass */ export class MappedAssociation<TSrc extends MappedDataSource = any, TTgt extends MappedDataSource = any> { constructor(public dataSource: TSrc, public mappedName: string, private mapping: AssociationMapping<TSrc, TTgt>) { assertType( AssociationMappingRT, mapping, `Association mapping configuration:\nDataSource<${dataSource}>[associations][${mappedName}]`, ); } /** * If the association will resolve to at most one associated entity */ @MemoizeGetter get singular() { if (isBoolean(this.mapping.singular)) { return this.mapping.singular; } return singularize(this.mappedName) === this.mappedName; } /** * If the association will be exposed through GraphQL API */ get exposed() { return this.mapping.exposed !== false; } /** * Linked data source */ get target(): TTgt { return this.mapping.target.apply(this); } /** * Association description made available through the GraphQL API */ get description() { return this.mapping.description; } /** * If the association supports paginated response */ get isPaginated() { return !!this.mapping.paginate; } /** * For a given operation, identify one of the (potentially) many many fetch configurations specified * using the fetchThrough mapping property. */ getFetchConfig< TCtx extends SourceAwareResolverContext<TMappedOperation, TRootSrc, TGQLArgs, TGQLSource, TGQLContext>, TRootSrc extends MappedDataSource<any>, TMappedOperation extends MappedSingleSourceQueryOperation<TRootSrc, TGQLArgs>, TGQLArgs extends {}, TGQLSource = any, TGQLContext = any, TResolved = any >(operation: SingleSourceQueryOperationResolver<TCtx, TRootSrc, TMappedOperation, TGQLArgs, TResolved>) { for (const config of this.mapping.fetchThrough) { if ( !config.useIf || config.useIf.call< MappedAssociation<TSrc, TTgt>, [SingleSourceQueryOperationResolver<TCtx, TRootSrc, TMappedOperation, TGQLArgs, TResolved>], boolean >(this, operation) ) { return config; } } return null; } /** * Start Side loading associated entities before the parent entity has been fetched */ preFetch< TCtx extends SourceAwareResolverContext<TMappedOperation, TRootSrc, TGQLArgs, TGQLSource, TGQLContext>, TRootSrc extends MappedDataSource<any>, TMappedOperation extends MappedSingleSourceQueryOperation<TRootSrc, TGQLArgs>, TGQLArgs extends {}, TGQLSource = any, TGQLContext = any, TResolved = any >( preFetchConfig: AssociationPreFetchConfig<TSrc, TTgt>, operation: SingleSourceQueryOperationResolver<TCtx, TRootSrc, TMappedOperation, TGQLArgs, TResolved>, ) { return preFetchConfig.preFetch.call< MappedAssociation<TSrc, TTgt>, [SingleSourceQueryOperationResolver<TCtx, TRootSrc, TMappedOperation, TGQLArgs, TResolved>], MappedForeignOperation<MappedSingleSourceOperation<TTgt, any>> >(this, operation); } /** * Side-load associated entities after parent entity has been fetched */ postFetch< TCtx extends SourceAwareResolverContext<TMappedOperation, TRootSrc, TGQLArgs, TGQLSource, TGQLContext>, TRootSrc extends MappedDataSource<any>, TMappedOperation extends MappedSingleSourceQueryOperation<TRootSrc, TGQLArgs>, TGQLArgs extends {}, TGQLSource = any, TGQLContext = any, TResolved = any >( postFetchConfig: AssociationPostFetchConfig<TSrc, TTgt>, operation: SingleSourceQueryOperationResolver<TCtx, TRootSrc, TMappedOperation, TGQLArgs, TResolved>, parents: PartialDeep<TSrc["EntityType"]>[], ) { return postFetchConfig.postFetch.call< MappedAssociation<TSrc, TTgt>, [ SingleSourceQueryOperationResolver<TCtx, TRootSrc, TMappedOperation, TGQLArgs, TResolved>, PartialDeep<TSrc["EntityType"]>[], ], MappedForeignOperation<MappedSingleSourceOperation<TTgt, any>> >(this, operation, parents); } join( joinConfig: AssociationJoinConfig<TSrc, TTgt>, queryBuilder: Knex.QueryBuilder, aliasHierarchyVisitor: AliasHierarchyVisitor, ): AliasHierarchyVisitor { if ((isFunction as TypeGuard<Function>)(joinConfig.join)) { return joinConfig.join(createJoinBuilder(queryBuilder, aliasHierarchyVisitor)).aliasHierarchyVisitor; } if ((isString as TypeGuard<JoinTypeId>)(joinConfig.join) && isPlainObject(this.associatorColumns)) { const { storedName } = this.target; const sourceAlias = aliasHierarchyVisitor.alias; const nextAliasHierarchyVisitor = aliasHierarchyVisitor.visit(this.mappedName)!; const { alias } = nextAliasHierarchyVisitor; queryBuilder[joinConfig.join]( `${storedName} as ${alias}`, `${sourceAlias}.${this.associatorColumns!.inSource}`, `${alias}.${this.associatorColumns!.inRelated}`, ); return nextAliasHierarchyVisitor; } throw new Error(`Not enough information to autoJoin association. Specify a join function`); } isAutoJoinable(joinConfig: AssociationJoinConfig<TSrc, TTgt>) { return isString(joinConfig.join) && isPlainObject(this.associatorColumns); } /** * Associates side loaded entities with parent entity. */ associateResultsWithParents( fetchConfig: AssociationPreFetchConfig<TSrc, TTgt> | AssociationPostFetchConfig<TSrc, TTgt>, ) { return (parents: PartialDeep<TSrc["EntityType"]>[], results: PartialDeep<TTgt["EntityType"]>[]) => { if (fetchConfig.associateResultsWithParents) { return fetchConfig.associateResultsWithParents.call(this, parents, results); } debug("associating results with parents -- parents: %O, results: %O", parents, results); if (!this.mapping.associatorColumns) { throw new Error("Either associatorColumns or associateResultsWithParents must be specified"); } const { inRelated, inSource } = this.mapping.associatorColumns!; const parentsIndex = indexBy(parents, inSource); results.forEach(result => { const pkey = result[inRelated] as any; if (!pkey) return; const parent = parentsIndex[pkey] as any; if (!parent) return; if (this.mapping.singular) { parent[this.mappedName] = result; } else { parent[this.mappedName] = parent[this.mappedName] || []; parent[this.mappedName].push(result); } }); }; } /** * Columns used to link the data sources at the persistence layer */ get associatorColumns() { return this.mapping.associatorColumns; } /** * Getter to obtain the type of source DataSource. * * This is expected to be used only in mapped typescript types. Invoking the getter directly * at runtime will throw. */ get DataSourceType(): TSrc { throw getTypeAccessorError("DataSourceType", "MappedAssociation"); } /** * Getter to obtain the type of associated DataSource. * * This is expected to be used only in mapped typescript types. Invoking the getter directly * at runtime will throw. */ get AssociatedDataSourceType(): TTgt { throw getTypeAccessorError("AssociatedDataSourceType", "MappedAssociation"); } /** * Getter to obtain the type of entity from source DataSource. * * This is expected to be used only in mapped typescript types. Invoking the getter directly * at runtime will throw. */ get SourceEntityType(): TSrc["EntityType"] { throw getTypeAccessorError("SourceEntityType", "MappedAssociation"); } /** * Getter to obtain the type of entity from associated DataSource. * * This is expected to be used only in mapped typescript types. Invoking the getter directly * at runtime will throw. */ get AssociatedEntityType(): TTgt["EntityType"] { throw getTypeAccessorError("AssociatedEntityType", "MappedAssociation"); } } type AssociationMappingResult< TMapping extends Dict<AssociationMapping<any, MappedDataSource>>, TSrc extends MappedDataSource > = { [K in keyof TMapping]: MappedAssociation<TSrc, ReturnType<TMapping[K]["target"]>>; }; /** * Used to define an association between two data sources. * * Make sure you have gone through the [Association Mapping](guide:mapping-associations) guide first which elaborates on * the concepts behind association mapping. * * Association mapping determines how two data sources can be linked (through joins, or auxiliary queries) so * that operations can be performed over multiple data sources. * * Accepts an [AssociationMapping](api:AssociationMapping) configuration. * * @api-category PrimaryAPI * @param associations */ export const mapAssociations = <TMapping extends Dict<AssociationMapping<any, MappedDataSource>>>( associations: TMapping, ) => <TSrc extends MappedDataSource>(dataSource: TSrc): AssociationMappingResult<TMapping, TSrc> => transform( associations, (result: Dict, associationMapping, name) => { result[name] = new MappedAssociation(dataSource, name, associationMapping); }, {}, ) as any;
the_stack
import { assert } from "chai"; import { BentleyError, LoggingMetaData } from "../BentleyError"; import { using } from "../Disposable"; import { Logger, LogLevel, PerfLogger } from "../Logger"; import { BeDuration } from "../Time"; let outerr: any[]; let outwarn: any[]; let outinfo: any[]; let outtrace: any[]; /* eslint-disable no-template-curly-in-string, @typescript-eslint/naming-convention */ function callLoggerConfigLevels(cfg: any, expectRejection: boolean) { try { Logger.configureLevels(cfg); assert.isFalse(expectRejection, "should have rejected config as invalid"); } catch (err) { assert.isTrue(expectRejection, "should not have rejected config as invalid"); } } function checkOutlet(outlet: any[], expected: any[] | undefined) { if (outlet.length === 0) { assert.isTrue(expected === undefined || expected.length === 0); return; } assert.isTrue(expected !== undefined); if (expected === undefined) return; assert.isArray(expected); assert.deepEqual(outlet.slice(0, 2), expected.slice(0, 2)); if (expected.length === 3) { assert.isTrue(outlet.length === 3, "message is expected to have metaData"); if (outlet.length === 3) { if (expected[2] === undefined) assert.isUndefined(outlet[2], "did not expect message to have a metaData function"); } else { assert.isTrue(expected[2] !== undefined, "expected a metaData function"); assert.deepEqual(outlet[2](), expected[2]()); } } else { assert.isTrue(outlet.length === 2 || outlet[2] === undefined, "message is not expected to have metaData"); } } function checkOutlets(e: any[] | undefined, w: any[] | undefined, i: any[] | undefined, t: any[] | undefined) { checkOutlet(outerr, e); checkOutlet(outwarn, w); checkOutlet(outinfo, i); checkOutlet(outtrace, t); clearOutlets(); } function clearOutlets() { outerr = []; outwarn = []; outinfo = []; outtrace = []; } type FunctionReturningAny = () => any; describe("Logger", () => { it("log without initializing", () => { // logging messages in the components must not cause failures if the app hasn't initialized logging. Logger.logError("test", "An error occurred"); Logger.logWarning("test", "A warning occurred"); Logger.logInfo("test", "An info message"); Logger.logTrace("test", "An trace message"); assert.isFalse(Logger.isEnabled("test", LogLevel.Error)); assert.isFalse(Logger.isEnabled("test", LogLevel.Warning)); assert.isFalse(Logger.isEnabled("test", LogLevel.Info)); assert.isFalse(Logger.isEnabled("test", LogLevel.Trace)); }); it("static logger metadata", () => { const aProps = `"a":"hello"`; const meta1Props = `"prop1":"test1","prop2":"test2","prop3":"test3"`; const meta2Props = `"value2":"v2"`; let out = Logger.stringifyMetaData({ a: "hello" }); assert.equal(out, `{${aProps}}`); // use a function for static metadata Logger.staticMetaData.set("meta1", () => ({ prop1: "test1", prop2: "test2", prop3: "test3" })); out = Logger.stringifyMetaData({ a: "hello" }); assert.equal(out, `{${meta1Props},${aProps}}`); // use an object for static metadata Logger.staticMetaData.set("meta2", { value2: "v2" }); // metadata from an object out = Logger.stringifyMetaData({ a: "hello" }); assert.equal(out, `{${meta1Props},${meta2Props},${aProps}}`); // metadata from a function out = Logger.stringifyMetaData(() => ({ a: "hello" })); assert.equal(out, `{${meta1Props},${meta2Props},${aProps}}`); // even if there's no metadata, you should still get static metadata out = Logger.stringifyMetaData(); assert.equal(out, `{${meta1Props},${meta2Props}}`); // delete static metadata Logger.staticMetaData.delete("meta1"); out = Logger.stringifyMetaData({ a: "hello" }); assert.equal(out, `{${meta2Props},${aProps}}`, "meta2 still exists"); Logger.staticMetaData.delete("meta2"); out = Logger.stringifyMetaData({ a: "hello" }); // no static metadata assert.equal(out, `{${aProps}}`); // no metadata at all out = Logger.stringifyMetaData(); assert.equal(out, ""); }); it("levels", () => { Logger.initialize( (c, m, d) => outerr = [c, m, d], (c, m, d) => outwarn = [c, m, d], (c, m, d) => outinfo = [c, m, d], (c, m, d) => outtrace = [c, m, d]); const c1msg: [string, string, FunctionReturningAny | undefined] = ["c1", "message1", () => "metaData1"]; const c2msg: [string, string, FunctionReturningAny | undefined] = ["c2", "message2", undefined]; const c3msg: [string, string, FunctionReturningAny | undefined] = ["c3", "message3", undefined]; const c4msg: [string, string, FunctionReturningAny | undefined] = ["c4", "message4", () => 4]; clearOutlets(); // By default all categories are off (at any level) Logger.logTrace.apply(null, c1msg); checkOutlets([], [], [], []); Logger.logInfo.apply(null, c1msg); checkOutlets([], [], [], []); Logger.logWarning.apply(null, c1msg); checkOutlets([], [], [], []); Logger.logError.apply(null, c1msg); checkOutlets([], [], [], []); Logger.logTrace.apply(null, c2msg); checkOutlets([], [], [], []); Logger.logInfo.apply(null, c2msg); checkOutlets([], [], [], []); Logger.logWarning.apply(null, c2msg); checkOutlets([], [], [], []); Logger.logError.apply(null, c2msg); checkOutlets([], [], [], []); // Now, turn the categories on at various levels // c1 logs at the highest level Logger.setLevel("c1", LogLevel.Error); Logger.logTrace.apply(null, c1msg); checkOutlets([], [], [], []); Logger.logInfo.apply(null, c1msg); checkOutlets([], [], [], []); Logger.logWarning.apply(null, c1msg); checkOutlets([], [], [], []); Logger.logError.apply(null, c1msg); checkOutlets(c1msg, [], [], []); // c2 logs at the warning level and up Logger.setLevel("c2", LogLevel.Warning); Logger.logTrace.apply(null, c2msg); checkOutlets([], [], [], []); Logger.logInfo.apply(null, c2msg); checkOutlets([], [], [], []); Logger.logWarning.apply(null, c2msg); checkOutlets([], c2msg, [], []); Logger.logError.apply(null, c2msg); checkOutlets(c2msg, [], [], []); // c3 logs at the info level and up Logger.setLevel("c3", LogLevel.Info); Logger.logTrace.apply(null, c3msg); checkOutlets([], [], [], []); Logger.logInfo.apply(null, c3msg); checkOutlets([], [], c3msg, []); Logger.logWarning.apply(null, c3msg); checkOutlets([], c3msg, [], []); Logger.logError.apply(null, c3msg); checkOutlets(c3msg, [], [], []); // c4 logs at the trace level and up Logger.setLevel("c4", LogLevel.Trace); Logger.logTrace.apply(null, c4msg); checkOutlets([], [], [], c4msg); Logger.logInfo.apply(null, c4msg); checkOutlets([], [], c4msg, []); Logger.logWarning.apply(null, c4msg); checkOutlets([], c4msg, [], []); Logger.logError.apply(null, c4msg); checkOutlets(c4msg, [], [], []); // Now remove the error logging function. Nothing should log at that level. We should still see messages at other levels. Logger.initialize( undefined, (c, m, d) => outwarn = [c, m, d], (c, m, d) => outinfo = [c, m, d], (c, m, d) => outtrace = [c, m, d]); Logger.setLevel("c1", LogLevel.Warning); Logger.logError.apply(null, c1msg); checkOutlets([], [], [], []); Logger.logWarning.apply(null, c1msg); checkOutlets([], c1msg, [], []); Logger.logTrace.apply(null, c4msg); checkOutlets([], [], [], []); // c4 is not turned on at all // Set a default level Logger.initialize( (c, m, d) => outerr = [c, m, d], (c, m, d) => outwarn = [c, m, d], (c, m, d) => outinfo = [c, m, d], (c, m, d) => outtrace = [c, m, d]); Logger.setLevelDefault(LogLevel.Info); Logger.setLevel("c1", LogLevel.Warning); Logger.logTrace.apply(null, c4msg); checkOutlets([], [], [], []); // c4 should still not come out at the Trace level Logger.logInfo.apply(null, c4msg); checkOutlets([], [], c4msg, []); // ... but it should come out at the default Info level, even though we never turned on c4, since Info is the default level that applies to all categories. Logger.logWarning.apply(null, c1msg); checkOutlets([], c1msg, [], []); // c1 should still come out at the warning level Logger.logInfo.apply(null, c1msg); checkOutlets([], [], [], []); // ... but not at the Info level, even though that's the default level, because c1 has a specific level setting // ... now turn c4 off. Logger.setLevel("c4", LogLevel.None); Logger.logInfo.apply(null, c4msg); checkOutlets([], [], [], []); // Even though the default log level is Info, c4 should not come out at any level. Logger.logWarning.apply(null, c4msg); checkOutlets([], [], [], []); // Even though the default log level is Info, c4 should not come out at any level. Logger.logError.apply(null, c4msg); checkOutlets([], [], [], []); // Even though the default log level is Info, c4 should not come out at any level. // parent.child Logger.initialize( (c, m, d) => outerr = [c, m, d], (c, m, d) => outwarn = [c, m, d], (c, m, d) => outinfo = [c, m, d], (c, m, d) => outtrace = [c, m, d]); Logger.setLevel("g1", LogLevel.Trace); Logger.setLevel("g2", LogLevel.Error); Logger.logWarning("g1.m1", "g1.m1's message"); checkOutlets([], ["g1.m1", "g1.m1's message"], [], []); Logger.logWarning("g2.m2", "g2.m2's message"); checkOutlets([], [], [], []); Logger.logError("g2.m2", "g2.m2's message"); checkOutlets(["g2.m2", "g2.m2's message"], [], [], []); // Multi-level parent.parent.child Logger.initialize( (c, m, d) => outerr = [c, m, d], (c, m, d) => outwarn = [c, m, d], (c, m, d) => outinfo = [c, m, d], (c, m, d) => outtrace = [c, m, d]); Logger.setLevel("g1", LogLevel.Trace); Logger.setLevel("g1.p1", LogLevel.Error); Logger.logWarning("g1.p1.c1", "unexpected"); checkOutlets([], [], [], []); // Since the immediate parent's level is error, then warnings on the child should not appear Logger.logError("g1.p1.c1", "expected"); checkOutlets(["g1.p1.c1", "expected"], [], [], []); // Since the immediate parent's level is error, then warnings on the child should not appear Logger.logWarning("g1.p2.c2", "expected"); checkOutlets([], ["g1.p2.c2", "expected"], [], []); // Since the grandparent's level is trace and there is no level specified for the parent, then warnings on the grandchild should appear }); it("turn on levels using config object", () => { Logger.initialize( (c, m, d) => outerr = [c, m, d], (c, m, d) => outwarn = [c, m, d], (c, m, d) => outinfo = [c, m, d], (c, m, d) => outtrace = [c, m, d]); const c1msg: [string, string, FunctionReturningAny | undefined] = ["c1", "message1", () => "metaData1"]; const c2msg: [string, string, FunctionReturningAny | undefined] = ["c2", "message2", undefined]; clearOutlets(); Logger.configureLevels({ categoryLevels: [ { category: "c1", logLevel: "Error" }, ], }); Logger.logError.apply(null, c1msg); Logger.logInfo.apply(null, c2msg); checkOutlets(c1msg, [], [], []); clearOutlets(); clearOutlets(); Logger.turnOffCategories(); Logger.turnOffLevelDefault(); Logger.configureLevels({ categoryLevels: [ { category: "c2", logLevel: "Warning" }, ], }); Logger.logError.apply(null, c1msg); Logger.logInfo.apply(null, c2msg); checkOutlets([], [], [], []); clearOutlets(); Logger.logError.apply(null, c1msg); Logger.logWarning.apply(null, c2msg); checkOutlets([], c2msg, [], []); clearOutlets(); Logger.turnOffCategories(); Logger.turnOffLevelDefault(); Logger.configureLevels({ defaultLevel: "Trace", categoryLevels: [ { category: "c1", logLevel: "Error" }, ], }); Logger.logError.apply(null, c1msg); Logger.logWarning.apply(null, c2msg); checkOutlets(c1msg, c2msg, [], []); clearOutlets(); }); it("Catch invalid config object", () => { Logger.initialize( (c, m, d) => outerr = [c, m, d], (c, m, d) => outwarn = [c, m, d], (c, m, d) => outinfo = [c, m, d], (c, m, d) => outtrace = [c, m, d]); callLoggerConfigLevels({ categoryLevels: { stuff: 0 } }, true); callLoggerConfigLevels({ xcategoryLevels: [{ category: "c1", logLevel: "Error" }] }, true); callLoggerConfigLevels({ categoryLevels: [{ xcategory: "c1", logLevel: "Error" }] }, true); callLoggerConfigLevels({ categoryLevels: [{ category: "c1", xlogLevel: "Error" }] }, true); callLoggerConfigLevels({ categoryLevels: [{ category: "c1", xlogLevel: "Error" }] }, true); callLoggerConfigLevels({ categoryLevels: [{ category: "c1", logLevel: "XError" }] }, true); callLoggerConfigLevels({ xdefaultLevel: 0 }, true); callLoggerConfigLevels({ defaultLevel: "XError" }, true); }); it("turn on logging for a few categories", () => { Logger.initialize( (c, m, d) => outerr = [c, m, d], (c, m, d) => outwarn = [c, m, d], (c, m, d) => outinfo = [c, m, d], (c, m, d) => outtrace = [c, m, d]); const c1msg: [string, string, FunctionReturningAny | undefined] = ["c1", "message1", () => "metaData1"]; const c2msg: [string, string, FunctionReturningAny | undefined] = ["c2", "message2", undefined]; clearOutlets(); Logger.setLevel("c1", LogLevel.Info); Logger.logError.apply(null, c1msg); Logger.logInfo.apply(null, c2msg); checkOutlets(c1msg, [], [], []); clearOutlets(); Logger.setLevelDefault(LogLevel.Trace); Logger.logError.apply(null, c1msg); Logger.logInfo.apply(null, c2msg); checkOutlets(c1msg, [], c2msg, []); clearOutlets(); Logger.turnOffLevelDefault(); Logger.logError.apply(null, c1msg); Logger.logInfo.apply(null, c2msg); checkOutlets(c1msg, [], [], []); clearOutlets(); Logger.turnOffCategories(); Logger.logError.apply(null, c1msg); Logger.logInfo.apply(null, c2msg); checkOutlets([], [], [], []); clearOutlets(); Logger.setLevelDefault(LogLevel.Trace); Logger.logError.apply(null, c1msg); Logger.logInfo.apply(null, c2msg); checkOutlets(c1msg, [], c2msg, []); clearOutlets(); }); it("Performance logger", async () => { const perfMessages = new Array<string>(); const perfData = new Array<any>(); Logger.initialize(undefined, undefined, (category, message, metadata?: LoggingMetaData) => { if (category === "Performance") { perfMessages.push(message); const data = metadata ? BentleyError.getMetaData(metadata) : {}; perfData.push(data); } }, undefined); await using(new PerfLogger("mytestroutine"), async (_r) => { await BeDuration.wait(10); }); assert.isEmpty(perfMessages); Logger.setLevel("Performance", LogLevel.Info); await using(new PerfLogger("mytestroutine2"), async (_r) => { await BeDuration.wait(10); }); assert.equal(perfMessages.length, 2); assert.equal(perfMessages[0], "mytestroutine2,START"); assert.equal(perfMessages[1], "mytestroutine2,END"); assert.isDefined(perfData[1].TimeElapsed); assert.isAbove(perfData[1].TimeElapsed, 8); perfMessages.pop(); perfMessages.pop(); const outerPerf = new PerfLogger("outer call"); const innerPerf = new PerfLogger("inner call"); for (let i = 0; i < 1000; i++) { if (i % 2 === 0) continue; } innerPerf.dispose(); for (let i = 0; i < 1000; i++) { if (i % 2 === 0) continue; } outerPerf.dispose(); assert.equal(perfMessages.length, 4); assert.equal(perfMessages[0], "outer call,START"); assert.equal(perfMessages[1], "inner call,START"); assert.equal(perfMessages[2], "inner call,END"); assert.equal(perfMessages[3], "outer call,END"); }); it("should log exceptions", () => { Logger.initialize( (c, m, d) => outerr = [c, m, BentleyError.getMetaData(d)], (c, m, d) => outwarn = [c, m, BentleyError.getMetaData(d)], (c, m, d) => outinfo = [c, m, BentleyError.getMetaData(d)], (c, m, d) => outtrace = [c, m, BentleyError.getMetaData(d)]); Logger.setLevel("testcat", LogLevel.Error); clearOutlets(); try { throw new Error("error message"); } catch (err: any) { Logger.logException("testcat", err); } checkOutlets(["testcat", "Error: error message", { ExceptionType: "Error" }], [], [], []); }); });
the_stack
import { map, range, uniqBy } from 'lodash'; import * as Random from 'random-js'; import { IMlModel, Type1DMatrix, Type2DMatrix } from '../types'; import { validateFitInputs, validateMatrix2D } from '../utils/validation'; /** * Question used by decision tree algorithm to determine whether to split branch or not * @ignore */ export class Question { private features = []; private column = null; private value = null; constructor(features = null, column, value) { this.features = features; this.column = column; this.value = value; } public match(example): boolean { const val = example[this.column]; if (typeof val === 'number') { return val >= this.value; } else { return val === this.value; } } public toString(): string { if (!this.features) { throw Error('You must provide feature labels in order to render toString!'); } const condition = typeof this.value === 'number' ? '>=' : '=='; return `Is ${this.features[this.column]} ${condition} ${this.value}`; } } /** * According to the given targets array, count occurrences into an object. * @param {any[]} targets - list of class: count * @returns {} * @ignore */ export function classCounts(targets: any[]): {} { const result = {}; for (let i = 0; i < targets.length; i++) { const target = targets[i]; const count = result[target]; // the current if (typeof count === 'number' && count > 0) { result[target] = { value: target, count: count + 1, }; } else { result[target] = { value: target, count: 1, }; } } return result; } /** * A leaf node that classifies data. * @ignore */ export class Leaf { public prediction = null; constructor(y) { const counts = classCounts(y); const keys = Object.keys(counts); // Retrieving the keys for looping // Variable holders let maxCount = 0; let maxValue = null; // Finding the max count key(actual prediction value) for (let i = 0; i < keys.length; i++) { const key = keys[i]; const count = counts[key].count; const value = counts[key].value; if (count > maxCount) { maxValue = value; maxCount = count; } } this.prediction = maxValue; } } /** * It holds a reference to the question, and to the two children nodes * @ignore */ export class DecisionNode { public question = null; public trueBranch = null; public falseBranch = null; constructor(question, trueBranch, falseBranch) { this.question = question; this.trueBranch = trueBranch; this.falseBranch = falseBranch; } } export interface Options { featureLabels?: null | any[]; verbose?: boolean; } /** * A decision tree classifier. * * @example * import { DecisionTreeClassifier } from 'machinelearn/tree'; * const features = ['color', 'diameter', 'label']; * const decision = new DecisionTreeClassifier({ featureLabels: features }); * * const X = [['Green', 3], ['Yellow', 3], ['Red', 1], ['Red', 1], ['Yellow', 3]]; * const y = ['Apple', 'Apple', 'Grape', 'Grape', 'Lemon']; * decision.fit({ X, y }); * decision.printTree(); // try it out yourself! =) * * decision.predict({ X: [['Green', 3]] }); // [ 'Apple' ] * decision.predict({ X }); // [ [ 'Apple' ], [ 'Apple', 'Lemon' ], [ 'Grape', 'Grape' ], [ 'Grape', 'Grape' ], [ 'Apple', 'Lemon' ] ] * * @example * import { DecisionTreeClassifier } from 'machinelearn/tree'; * const decision = new DecisionTreeClassifier({ featureLabels: null }); * * const X = [[0, 0], [1, 1]]; * const Y = [0, 1]; * decision.fit({ X, y }); * decision2.predict({ row: [[2, 2]] }); // [ 1 ] */ export class DecisionTreeClassifier implements IMlModel<string | boolean | number> { private featureLabels = null; private tree = null; private verbose = true; private randomState = null; private randomEngine = null; /** * * @param featureLabels - Literal names for each feature to be used while printing the tree out as a string * @param verbose - Logs the progress of the tree construction as console.info * @param random_state - A seed value for the random engine */ constructor( { featureLabels = null, verbose = false, random_state = null, }: { featureLabels?: any[]; verbose?: boolean; random_state?: number; } = { featureLabels: null, verbose: false, random_state: null, }, ) { this.featureLabels = featureLabels; this.verbose = verbose; this.randomState = random_state; if (!Number.isInteger(random_state)) { this.randomEngine = Random.engines.mt19937().autoSeed(); } else { this.randomEngine = Random.engines.mt19937().seed(random_state); } } /** * Fit date, which builds a tree * @param {any} X - 2D Matrix of training * @param {any} y - 1D Vector of target * @returns {Leaf | DecisionNode} */ public fit( X: Type2DMatrix<string | number | boolean> = null, y: Type1DMatrix<string | number | boolean> = null, ): void { validateFitInputs(X, y); this.tree = this.buildTree({ X, y }); } /** * Predict multiple rows * * @param X - 2D Matrix of testing data */ public predict(X: Type2DMatrix<string | boolean | number> = []): any[] { validateMatrix2D(X); const result = []; for (let i = 0; i < X.length; i++) { const row = X[i]; result.push(this._predict({ row, node: this.tree })); } return result; } /** * Returns the model checkpoint * @returns {{featureLabels: string[]; tree: any; verbose: boolean}} */ public toJSON(): { /** * Literal names for each feature to be used while printing the tree out as a string */ featureLabels: string[]; /** * The model's state */ tree: any; // TODO: fix this type /** * Logs the progress of the tree construction as console.info */ verbose: boolean; /** * A seed value for the random engine */ random_state: number; } { return { featureLabels: this.featureLabels, tree: this.tree, verbose: this.verbose, random_state: this.randomState, }; } /** * Restores the model from a checkpoint * @param {string[]} featureLabels - Literal names for each feature to be used while printing the tree out as a string * @param {any} tree - The model's state * @param {boolean} verbose - Logs the progress of the tree construction as console.info * @param {number} random_state - A seed value for the random engine */ public fromJSON({ featureLabels = null, tree = null, verbose = false, random_state = null, }: { featureLabels: string[]; tree: any; verbose: boolean; random_state: number; }): void { this.featureLabels = featureLabels; this.tree = tree; this.verbose = verbose; this.randomState = random_state; } /** * Recursively print the tree into console * @param {string} spacing - Spacing used when printing the tree into the terminal */ public printTree(spacing: string = ''): void { if (!this.tree) { throw new Error('You cannot print an empty tree'); } this._printTree({ node: this.tree, spacing }); } /** * Partition X and y into true and false branches * @param X * @param y * @param {Question} question * @returns {{trueX: Array<any>; trueY: Array<any>; falseX: Array<any>; falseY: Array<any>}} */ private partition( X, y, question: Question, ): { trueX: any[]; trueY: any[]; falseX: any[]; falseY: any[]; } { const trueX = []; const trueY = []; const falseX = []; const falseY = []; for (let i = 0; i < X.length; i++) { const row = X[i]; if (question.match(row)) { trueX.push(X[i]); trueY.push(y[i]); } else { falseX.push(X[i]); falseY.push(y[i]); } } return { trueX, trueY, falseX, falseY }; } /** * Calculate the gini impurity of rows * Checkout: https://en.wikipedia.org/wiki/Decision_tree_learning#Gini_impurity * @param targets * @returns {number} */ private gini(targets): number { const counts = classCounts(targets); let impurity = 1; const keys = Object.keys(counts); for (let i = 0; i < keys.length; i++) { const key = keys[i]; const count = counts[key].count; if (count === null || count === undefined) { throw Error('Invalid class count detected!'); } const probOfClass = count / targets.length; impurity -= Math.pow(probOfClass, 2); } return impurity; } /** * Information Gain. * * The uncertainty of the starting node, minus the weighted impurity of * two child nodes. * @param left * @param right * @param uncertainty * @returns {number} */ private infoGain(left, right, uncertainty): number { const p = left.length / (left.length + right.length); return uncertainty - p * this.gini(left) - (1 - p) * this.gini(right); } /** * Find the best split for the current X and y. * @param X * @param y * @returns {{bestGain: number; bestQuestion: any}} */ private findBestSplit(X, y): { bestGain: number; bestQuestion: Question } { const uncertainty = this.gini(y); const nFeatures = X[0].length; let bestGain = 0; let bestQuestion = null; let featureIndex = []; if (Number.isInteger(this.randomState)) { // method 1: Randomly selecting features while (featureIndex.length <= nFeatures) { const index = Random.integer(0, nFeatures)(this.randomEngine); featureIndex.push(index); } } else { featureIndex = range(0, X[0].length); } for (let i = 0; i < featureIndex.length; i++) { const col = featureIndex[i]; const uniqFeatureValues = uniqBy(map(X, (row) => row[col]), (x) => x); for (let j = 0; j < uniqFeatureValues.length; j++) { const feature = uniqFeatureValues[j]; // featureLabels is for the model interoperability const question = new Question(this.featureLabels, col, feature); // Try splitting the dataset const { trueY, falseY } = this.partition(X, y, question); // Skip this dataset if it does not divide if (trueY.length === 0 || falseY.length === 0) { continue; } // Calculate information gained from this split const gain = this.infoGain(trueY, falseY, uncertainty); if (this.verbose) { console.info(`fn: ${col} fval: ${feature} gini: ${gain}`); } if (gain >= bestGain) { bestGain = gain; bestQuestion = question; } } } return { bestGain, bestQuestion }; } /** * Interactively build tree until it reaches the terminal nodes * @param {any} X * @param {any} y * @returns {any} */ private buildTree({ X, y }): DecisionNode | Leaf { const { bestGain, bestQuestion } = this.findBestSplit(X, y); if (bestGain === 0) { return new Leaf(y); } // Partition the current passed in X ,y const { trueX, trueY, falseX, falseY } = this.partition(X, y, bestQuestion); // Recursively build the true branch const trueBranch = this.buildTree({ X: trueX, y: trueY }); // Recursively build the false branch const falseBranch = this.buildTree({ X: falseX, y: falseY }); return new DecisionNode(bestQuestion, trueBranch, falseBranch); } /** * Internal predict method separated out for recursion purpose * @param {any} row * @param {any} node * @returns {any} * @private */ private _predict({ row, node }): any[] { if (node instanceof Leaf) { // Just return the highest voted return node.prediction; } if (node.question.match(row)) { return this._predict({ row, node: node.trueBranch }); } else { return this._predict({ row, node: node.falseBranch }); } } /** * Private method for printing tree; required for recursion * @param {any} node * @param {any} spacing */ private _printTree({ node, spacing = '' }): void { if (node instanceof Leaf) { console.info(spacing + '' + node.prediction); return; } // Print the question of the node console.info(spacing + node.question.toString()); // Call this function recursively for true branch console.info(spacing, '--> True'); this._printTree({ node: node.trueBranch, spacing: spacing + ' ' }); // Call this function recursively for false branch console.info(spacing, '--> False'); this._printTree({ node: node.falseBranch, spacing: spacing + ' ' }); } }
the_stack
import {IModelConstructor} from 'mobx-collection-store'; import ParamArrayType from './enums/ParamArrayType'; import IDictionary from './interfaces/IDictionary'; import IFilters from './interfaces/IFilters'; import IHeaders from './interfaces/IHeaders'; import IRawResponse from './interfaces/IRawResponse'; import IRequestOptions from './interfaces/IRequestOptions'; import IResponseHeaders from './interfaces/IResponseHeaders'; import * as JsonApi from './interfaces/JsonApi'; import {Record} from './Record'; import {Response as LibResponse} from './Response'; import {Store} from './Store'; import {assign, getValue, isBrowser, objectForEach} from './utils'; export type FetchType = ( method: string, url: string, body?: object, requestHeaders?: IHeaders, ) => Promise<IRawResponse>; export interface IStoreFetchOpts { url: string; options?: IRequestOptions; data?: object; method: string; store: Store; } export type StoreFetchType = (options: IStoreFetchOpts) => Promise<LibResponse>; export interface IConfigType { baseFetch: FetchType; baseUrl: string; defaultHeaders: IHeaders; defaultFetchOptions: IDictionary<any>; fetchReference: Function; paramArrayType: ParamArrayType; storeFetch: StoreFetchType; transformRequest: (options: IStoreFetchOpts) => IStoreFetchOpts; transformResponse: (response: IRawResponse) => IRawResponse; } export const config: IConfigType = { /** Base URL for all API calls */ baseUrl: '/', /** Default headers that will be sent to the server */ defaultHeaders: { 'content-type': 'application/vnd.api+json', }, /* Default options that will be passed to fetchReference */ defaultFetchOptions: {}, /** Reference of the fetch method that should be used */ /* istanbul ignore next */ fetchReference: isBrowser && window.fetch && window.fetch.bind(window), /** Determines how will the request param arrays be stringified */ paramArrayType: ParamArrayType.COMMA_SEPARATED, // As recommended by the spec /** * Base implementation of the fetch function (can be overridden) * * @param {string} method API call method * @param {string} url API call URL * @param {object} [body] API call body * @param {IHeaders} [requestHeaders] Headers that will be sent * @returns {Promise<IRawResponse>} Resolves with a raw response object */ baseFetch( method: string, url: string, body?: object, requestHeaders?: IHeaders, ): Promise<IRawResponse> { let data: JsonApi.IResponse; let status: number; let headers: IResponseHeaders; const request: Promise<void> = Promise.resolve(); const uppercaseMethod = method.toUpperCase(); const isBodySupported = uppercaseMethod !== 'GET' && uppercaseMethod !== 'HEAD'; return request .then(() => { const reqHeaders: IHeaders = assign({}, config.defaultHeaders, requestHeaders) as IHeaders; const options = assign({}, config.defaultFetchOptions, { body: isBodySupported && JSON.stringify(body) || undefined, headers: reqHeaders, method, }); return this.fetchReference(url, options); }) .then((response: Response) => { status = response.status; headers = response.headers; return response.json(); }) .catch((e: Error) => { if (status === 204) { return null; } throw e; }) .then((responseData: JsonApi.IResponse) => { data = responseData; if (status >= 400) { throw { message: `Invalid HTTP status: ${status}`, status, }; } return {data, headers, requestHeaders, status}; }) .catch((error) => { return {data, error, headers, requestHeaders, status}; }); }, /** * Base implementation of the stateful fetch function (can be overridden) * * @param {IStoreFetchOpts} reqOptions API request options * @returns {Promise<Response>} Resolves with a response object */ storeFetch(reqOptions: IStoreFetchOpts): Promise<LibResponse> { const { url, options, data, method = 'GET', store, } = config.transformRequest(reqOptions); return config.baseFetch(method, url, data, options && options.headers) .then((response: IRawResponse) => { const storeResponse = assign(response, {store}); return new LibResponse(config.transformResponse(storeResponse), store, options); }); }, transformRequest(options: IStoreFetchOpts): IStoreFetchOpts { return options; }, transformResponse(response: IRawResponse): IRawResponse { return response; }, }; export function fetch(options: IStoreFetchOpts) { return config.storeFetch(options); } /** * API call used to get data from the server * * @export * @param {Store} store Related Store * @param {string} url API call URL * @param {IHeaders} [headers] Headers to be sent * @param {IRequestOptions} [options] Server options * @returns {Promise<Response>} Resolves with a Response object */ export function read( store: Store, url: string, headers?: IHeaders, options?: IRequestOptions, ): Promise<LibResponse> { return config.storeFetch({ data: null, method: 'GET', options: {...options, headers}, store, url, }); } /** * API call used to create data on the server * * @export * @param {Store} store Related Store * @param {string} url API call URL * @param {object} [data] Request body * @param {IHeaders} [headers] Headers to be sent * @param {IRequestOptions} [options] Server options * @returns {Promise<Response>} Resolves with a Response object */ export function create( store: Store, url: string, data?: object, headers?: IHeaders, options?: IRequestOptions, ): Promise<LibResponse> { return config.storeFetch({ data, method: 'POST', options: {...options, headers}, store, url, }); } /** * API call used to update data on the server * * @export * @param {Store} store Related Store * @param {string} url API call URL * @param {object} [data] Request body * @param {IHeaders} [headers] Headers to be sent * @param {IRequestOptions} [options] Server options * @returns {Promise<Response>} Resolves with a Response object */ export function update( store: Store, url: string, data?: object, headers?: IHeaders, options?: IRequestOptions, ): Promise<LibResponse> { return config.storeFetch({ data, method: 'PATCH', options: {...options, headers}, store, url, }); } /** * API call used to remove data from the server * * @export * @param {Store} store Related Store * @param {string} url API call URL * @param {IHeaders} [headers] Headers to be sent * @param {IRequestOptions} [options] Server options * @returns {Promise<Response>} Resolves with a Response object */ export function remove( store: Store, url: string, headers?: IHeaders, options?: IRequestOptions, ): Promise<LibResponse> { return config.storeFetch({ data: null, method: 'DELETE', options: {...options, headers}, store, url, }); } /** * Fetch a link from the server * * @export * @param {JsonApi.ILink} link Link URL or a link object * @param {Store} store Store that will be used to save the response * @param {IDictionary<string>} [requestHeaders] Request headers * @param {IRequestOptions} [options] Server options * @returns {Promise<LibResponse>} Response promise */ export function fetchLink( link: JsonApi.ILink, store: Store, requestHeaders?: IDictionary<string>, options?: IRequestOptions, ): Promise<LibResponse> { if (link) { const href: string = typeof link === 'object' ? link.href : link; /* istanbul ignore else */ if (href) { return read(store, href, requestHeaders, options); } } return Promise.resolve(new LibResponse({data: null}, store)); } export function handleResponse(record: Record, prop?: string): (response: LibResponse) => Record { return (response: LibResponse): Record => { /* istanbul ignore if */ if (response.error) { throw response.error; } if (response.status === 204) { record['__persisted'] = true; return record as Record; } else if (response.status === 202) { (response.data as Record).update({ __prop__: prop, __queue__: true, __related__: record, } as Object); return response.data as Record; } else { record['__persisted'] = true; return response.replaceData(record).data as Record; } }; } function __prepareFilters(filters: IFilters): Array<string> { return __parametrize(filters).map((item) => `filter[${item.key}]=${item.value}`); } function __prepareSort(sort?: string|Array<string>): Array<string> { return sort ? [`sort=${sort}`] : []; } function __prepareIncludes(include?: string|Array<string>): Array<string> { return include ? [`include=${include}`] : []; } function __prepareFields(fields: IDictionary<string|Array<string>>): Array<string> { const list = []; objectForEach(fields, (key: string) => { list.push(`fields[${key}]=${fields[key]}`); }); return list; } function __prepareRawParams(params: Array<{key: string, value: string}|string>): Array<string> { return params.map((param) => { if (typeof param === 'string') { return param; } return `${param.key}=${param.value}`; }); } export function prefixUrl(url) { return `${config.baseUrl}${url}`; } function __appendParams(url: string, params: Array<string>): string { if (params.length) { url += '?' + params.join('&'); } return url; } function __parametrize(params: object, scope: string = ''): Array<{key: string, value: string}> { const list = []; objectForEach(params, (key: string) => { if (params[key] instanceof Array) { if (config.paramArrayType === ParamArrayType.OBJECT_PATH) { list.push(...__parametrize(params[key], `${key}.`)); } else if (config.paramArrayType === ParamArrayType.COMMA_SEPARATED) { list.push({key: `${scope}${key}`, value: params[key].join(',')}); } else if (config.paramArrayType === ParamArrayType.MULTIPLE_PARAMS) { list.push(...params[key].map((param) => ({key: `${scope}${key}`, value: param}))); } else if (config.paramArrayType === ParamArrayType.PARAM_ARRAY) { list.push(...params[key].map((param) => ({key: `${scope}${key}][`, value: param}))); } } else if (typeof params[key] === 'object') { list.push(...__parametrize(params[key], `${key}.`)); } else { list.push({key: `${scope}${key}`, value: params[key]}); } }); return list; } export function buildUrl( type: number|string, id?: number|string, model?: IModelConstructor, options?: IRequestOptions, ) { const path: string = model ? (getValue<string>(model['endpoint']) || model['baseUrl'] || model.type) : type; const url: string = id ? `${path}/${id}` : `${path}`; const params: Array<string> = [ ...__prepareFilters((options && options.filter) || {}), ...__prepareSort(options && options.sort), ...__prepareIncludes(options && options.include), ...__prepareFields((options && options.fields) || {}), ...__prepareRawParams((options && options.params) || []), ]; return __appendParams(prefixUrl(url), params); }
the_stack
import { Objects, Types } from '../utils'; import { Parser, StructuredTypeFieldConfig, StructuredTypeConfig, OptionsHelper, NONE_PARSER, StructuredTypeFieldOptions, Options, } from '../types'; import { ODataEnumTypeParser } from './enum-type'; import { COMPUTED } from '../constants'; import { ODataAnnotation } from '../schema/annotation'; import { raw } from '../resources/builder'; import { ODataParserOptions } from '../options'; // JSON SCHEMA type JsonSchemaSelect<T> = Array<keyof T>; type JsonSchemaCustom<T> = { [P in keyof T]?: ( schema: any, field: ODataStructuredTypeFieldParser<T[P]> ) => any; }; type JsonSchemaExpand<T> = { [P in keyof T]?: JsonSchemaOptions<T[P]> }; type JsonSchemaRequired<T> = { [P in keyof T]?: boolean }; export type JsonSchemaOptions<T> = { select?: JsonSchemaSelect<T>; custom?: JsonSchemaCustom<T>; expand?: JsonSchemaExpand<T>; required?: JsonSchemaRequired<T>; }; export class ODataEntityTypeKey { name: string; alias?: string; constructor({ name, alias }: { name: string; alias?: string }) { this.name = name; this.alias = alias; } } export class ODataReferential { property: string; referencedProperty: string; constructor({ property, referencedProperty, }: { property: string; referencedProperty: string; }) { this.property = property; this.referencedProperty = referencedProperty; } } export class ODataStructuredTypeFieldParser<T> implements Parser<T> { name: string; private structuredType: ODataStructuredTypeParser<any>; type: string; private parser: Parser<T>; default?: any; maxLength?: number; collection: boolean; nullable: boolean; navigation: boolean; precision?: number; scale?: number; referentials: ODataReferential[]; annotations: ODataAnnotation[]; optionsHelper?: OptionsHelper; constructor( name: string, structuredType: ODataStructuredTypeParser<any>, field: StructuredTypeFieldConfig ) { this.name = name; this.structuredType = structuredType; this.type = field.type; this.parser = NONE_PARSER; this.annotations = (field.annotations || []).map( (annot) => new ODataAnnotation(annot) ); this.referentials = (field.referentials || []).map( (referential) => new ODataReferential(referential) ); this.default = field.default; this.maxLength = field.maxLength; this.collection = field.collection !== undefined ? field.collection : false; this.nullable = field.nullable !== undefined ? field.nullable : true; this.navigation = field.navigation !== undefined ? field.navigation : false; this.precision = field.precision; this.scale = field.scale; } /** * Find an annotation inside the structured field type. * @param predicate Function that returns true if the annotation match. * @returns The annotation that matches the predicate. */ findAnnotation(predicate: (annot: ODataAnnotation) => boolean) { return this.annotations.find(predicate); } validate( value: any, { method, navigation = false, }: { method?: 'create' | 'update' | 'modify'; navigation?: boolean; } = {} ): | { [name: string]: any } | { [name: string]: any }[] | string[] | undefined { let errors; if (this.collection && Array.isArray(value)) { errors = value.map((v) => this.validate(v, { method, navigation })) as { [name: string]: any[]; }[]; } else if ( (this.isStructuredType() && typeof value === 'object' && value !== null) || (this.navigation && value !== undefined) ) { errors = this.structured().validate(value, { method, navigation }) || ({} as { [name: string]: any[] }); } else if ( this.isEnumType() && (typeof value === 'string' || typeof value === 'number') ) { errors = this.enum().validate(value, { method, navigation }); } else { // IsEdmType const computed = this.findAnnotation((a) => a.term === COMPUTED); errors = []; if ( !this.nullable && (value === null || (value === undefined && method !== 'modify')) && // Is null or undefined without patch? !(computed?.bool && method === 'create') // Not (Is Computed field and create) ? ) { errors.push(`required`); } if ( this.maxLength !== undefined && typeof value === 'string' && value.length > this.maxLength ) { errors.push(`maxlength`); } } return !Types.isEmpty(errors) ? errors : undefined; } //#region Deserialize private parse( parser: ODataStructuredTypeParser<T>, value: any, options?: OptionsHelper ): any { const type = Types.isPlainObject(value) ? options?.helper.type(value) : undefined; if (type !== undefined) { return parser .childParser((c) => c.isTypeOf(type)) .deserialize(value, options); } return parser.deserialize(value, options); } deserialize(value: any, options?: Options): T { const parserOptions = options !== undefined ? new ODataParserOptions(options) : this.optionsHelper; if (this.parser instanceof ODataStructuredTypeParser) { const parser = this.parser as ODataStructuredTypeParser<T>; return Array.isArray(value) ? value.map((v) => this.parse(parser, v, parserOptions)) : this.parse(parser, value, parserOptions); } return this.parser.deserialize(value, { field: this, ...parserOptions, } as StructuredTypeFieldOptions); } //#endregion //#region Serialize private toJson( parser: ODataStructuredTypeParser<T>, value: any, options?: OptionsHelper ): any { const type = Types.isPlainObject(value) ? options?.helper.type(value) : undefined; if (type !== undefined) { return parser .childParser((c) => c.isTypeOf(type)) .serialize(value, options); } return parser.serialize(value, options); } serialize(value: T, options?: Options): any { const parserOptions = options !== undefined ? new ODataParserOptions(options) : this.optionsHelper; if (this.parser instanceof ODataStructuredTypeParser) { const parser = this.parser as ODataStructuredTypeParser<T>; return Array.isArray(value) ? (value as any[]).map((v) => this.toJson(parser, v, parserOptions)) : this.toJson(parser, value, parserOptions); } return this.parser.serialize(value, { field: this, ...parserOptions, } as StructuredTypeFieldOptions); } //#endregion //#region Encode encode(value: T, options?: Options): string { const parserOptions = options !== undefined ? new ODataParserOptions(options) : this.optionsHelper; return this.parser.encode(value, { field: this, ...parserOptions, } as StructuredTypeFieldOptions); } //#endregion configure({ parserForType, options, }: { parserForType: (type: string) => Parser<any>; options: OptionsHelper; }) { this.optionsHelper = options; this.parser = parserForType(this.type); if (this.default !== undefined) this.default = this.deserialize(this.default, options); } //#region Json Schema // https://json-schema.org/ toJsonSchema(options: JsonSchemaOptions<T> = {}) { let schema: any = this.parser instanceof ODataStructuredTypeFieldParser || this.parser instanceof ODataStructuredTypeParser || this.parser instanceof ODataEnumTypeParser ? this.parser.toJsonSchema(options) : ({ title: this.name, type: 'object' } as any); if ( [ 'Edm.String', 'Edm.Date', 'Edm.TimeOfDay', 'Edm.DateTimeOffset', 'Edm.Guid', 'Edm.Binary', ].indexOf(this.type) !== -1 ) { schema.type = 'string'; if (this.type === 'Edm.Date') schema.format = 'date'; else if (this.type === 'Edm.TimeOfDay') schema.format = 'time'; else if (this.type === 'Edm.DateTimeOffset') schema.format = 'date-time'; else if (this.type === 'Edm.Guid') schema.pattern = '^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$'; else if (this.type === 'Edm.Binary') schema.contentEncoding = 'base64'; else if (this.type === 'Edm.String' && this.maxLength) schema.maxLength = this.maxLength; } else if ( ['Edm.Int64', 'Edm.Int32', 'Edm.Int16', 'Edm.Byte', 'Edm.SByte'].indexOf( this.type ) !== -1 ) { //TODO: Range schema.type = 'integer'; } else if (['Edm.Decimal', 'Edm.Double'].indexOf(this.type) !== -1) { schema.type = 'number'; } else if (['Edm.Boolean'].indexOf(this.type) !== -1) { schema.type = 'boolean'; } if (this.default) schema.default = this.default; if (this.nullable) schema.type = [schema.type, 'null']; if (this.collection) schema = { type: 'array', items: schema, additionalItems: false, }; return schema; } //#endregion isKey() { return ( this.structuredType.keys?.find((k) => k.name === this.name) !== undefined ); } hasReferentials() { return this.referentials.length !== 0; } isEdmType() { return this.type.startsWith('Edm.'); } isEnumType() { return this.parser instanceof ODataEnumTypeParser; } enum() { if (!this.isEnumType()) throw new Error('Field are not EnumType'); return this.parser as ODataEnumTypeParser<T>; } isStructuredType() { return this.parser instanceof ODataStructuredTypeParser; } structured() { if (!this.isStructuredType()) throw new Error('Field are not StrucuturedType'); return this.parser as ODataStructuredTypeParser<T>; } } export class ODataStructuredTypeParser<T> implements Parser<T> { name: string; namespace: string; open: boolean; children: ODataStructuredTypeParser<any>[] = []; alias?: string; base?: string; parent?: ODataStructuredTypeParser<any>; keys?: ODataEntityTypeKey[]; fields: ODataStructuredTypeFieldParser<any>[]; optionsHelper?: OptionsHelper; constructor( config: StructuredTypeConfig<T>, namespace: string, alias?: string ) { this.name = config.name; this.base = config.base; this.open = config.open || false; this.namespace = namespace; this.alias = alias; if (Array.isArray(config.keys)) this.keys = config.keys.map((key) => new ODataEntityTypeKey(key)); this.fields = Object.entries<StructuredTypeFieldConfig>( config.fields as { [P in keyof T]: StructuredTypeFieldConfig } ).map( ([name, config]) => new ODataStructuredTypeFieldParser(name, this, config) ); } isTypeOf(type: string) { var names = [`${this.namespace}.${this.name}`]; if (this.alias) names.push(`${this.alias}.${this.name}`); return names.indexOf(type) !== -1; } typeFor(name: string): string | undefined { const field = this.fields.find((f) => f.name === name); if (field === undefined && this.parent !== undefined) return this.parent.typeFor(name); return field !== undefined ? field.type : undefined; } findChildParser( predicate: (p: ODataStructuredTypeParser<any>) => boolean ): ODataStructuredTypeParser<any> | undefined { if (predicate(this)) return this; let match: ODataStructuredTypeParser<any> | undefined; for (let ch of this.children) { match = ch.findChildParser(predicate); if (match !== undefined) break; } return match; } childParser( predicate: (p: ODataStructuredTypeParser<any>) => boolean ): Parser<any> { return this.findChildParser(predicate) || NONE_PARSER; } // Deserialize deserialize(value: any, options?: Options): T { const parserOptions = options !== undefined ? new ODataParserOptions(options) : this.optionsHelper; if (this.parent !== undefined) value = this.parent.deserialize(value, parserOptions); const fields = this.fields.filter( (f) => f.name in value && value[f.name] !== undefined && value[f.name] !== null ); return { ...value, ...fields.reduce( (acc, f) => ({ ...acc, [f.name]: f.deserialize(value[f.name], parserOptions), }), {} ), }; } // Serialize serialize(value: T, options?: Options): any { const parserOptions = options !== undefined ? new ODataParserOptions(options) : this.optionsHelper; if (this.parent !== undefined) value = this.parent.serialize(value, parserOptions); const fields = this.fields.filter( (f) => f.name in value && (value as any)[f.name] !== undefined && (value as any)[f.name] !== null ); return { ...value, ...fields.reduce( (acc, f) => ({ ...acc, [f.name]: f.serialize((value as any)[f.name], parserOptions), }), {} ), }; } // Encode encode(value: T, options?: Options): any { const parserOptions = options !== undefined ? new ODataParserOptions(options) : this.optionsHelper; return raw(JSON.stringify(this.serialize(value, parserOptions))); } configure({ parserForType, options, }: { parserForType: (type: string) => Parser<any>; options: OptionsHelper; }) { this.optionsHelper = options; if (this.base) { const parent = parserForType(this.base) as ODataStructuredTypeParser<any>; parent.children.push(this); this.parent = parent; } this.fields.forEach((f) => f.configure({ parserForType, options })); } resolveKey(value: any): any { let key = this.parent?.resolveKey(value) || {}; if (Array.isArray(this.keys) && this.keys.length > 0) { for (var k of this.keys) { let v = value as any; let structured = this as ODataStructuredTypeParser<any> | undefined; let field: ODataStructuredTypeFieldParser<any> | undefined; for (let name of k.name.split('/')) { if (structured === undefined) break; field = structured.fields.find((f) => f.name === name); if (field !== undefined) { v = Types.isPlainObject(v) ? v[field.name] : v; structured = field.isStructuredType() ? field.structured() : undefined; } } if (field !== undefined && v !== undefined) { key[k.alias || field.name] = field.encode(v); } } } if (Types.isEmpty(key)) return undefined; return Objects.resolveKey(key); } defaults(): { [name: string]: any } { let value = this.parent?.defaults() || {}; let fields = this.fields.filter( (f) => f.default !== undefined || f.isStructuredType() ); return { ...value, ...fields.reduce((acc, f) => { let value = f.isStructuredType() ? f.structured().defaults() : f.default; return Types.isEmpty(value) ? acc : { ...acc, [f.name]: value }; }, {}), }; } // Json Schema toJsonSchema(options: JsonSchemaOptions<T> = {}) { let schema: any = this.parent?.toJsonSchema(options) || { $schema: 'http://json-schema.org/draft-07/schema#', $id: `${this.namespace}.${this.name}`, title: this.name, type: 'object', properties: {}, required: [], }; const fields = this.fields.filter( (f) => (!f.navigation || (options.expand && f.name in options.expand)) && (!options.select || (<string[]>options.select).indexOf(f.name) !== -1) ); schema.properties = Object.assign( {}, schema.properties, fields .map((f) => { let expand = options.expand && f.name in options.expand ? (options.expand as any)[f.name] : undefined; let schema = f.toJsonSchema(expand); if (options.custom && f.name in options.custom) schema = ( options.custom[f.name as keyof T] as ( schema: any, field: ODataStructuredTypeFieldParser<any> ) => any )(schema, f); return { [f.name]: schema }; }) .reduce((acc, v) => Object.assign(acc, v), {}) ); schema.required = [ ...schema.required, ...fields .filter((f) => options.required && f.name in options.required ? options.required[f.name as keyof T] : !f.nullable ) .map((f) => f.name), ]; return schema; } validate( attrs: any, { method, navigation = false, }: { create?: boolean; method?: 'create' | 'update' | 'modify'; navigation?: boolean; } = {} ): { [name: string]: any } | undefined { const errors = (this.parent?.validate(attrs, { method, navigation }) || {}) as { [name: string]: any }; const fields = this.fields.filter((f) => !f.navigation || navigation); for (var field of fields) { const value = attrs[field.name as keyof T]; const errs = field.validate(value, { method, navigation }); if (errs !== undefined) { errors[field.name] = errs; } } return !Types.isEmpty(errors) ? errors : undefined; } }
the_stack