text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
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 CheckServiceProviderAvailabilityInput: msRest.CompositeMapper = { serializedName: "CheckServiceProviderAvailabilityInput", type: { name: "Composite", className: "CheckServiceProviderAvailabilityInput", modelProperties: { peeringServiceLocation: { serializedName: "peeringServiceLocation", type: { name: "String" } }, peeringServiceProvider: { serializedName: "peeringServiceProvider", type: { name: "String" } } } } }; export const PeeringSku: msRest.CompositeMapper = { serializedName: "PeeringSku", type: { name: "Composite", className: "PeeringSku", modelProperties: { name: { serializedName: "name", type: { name: "String" } }, tier: { serializedName: "tier", type: { name: "String" } }, family: { serializedName: "family", type: { name: "String" } }, size: { serializedName: "size", type: { name: "String" } } } } }; export const BgpSession: msRest.CompositeMapper = { serializedName: "BgpSession", type: { name: "Composite", className: "BgpSession", modelProperties: { sessionPrefixV4: { serializedName: "sessionPrefixV4", type: { name: "String" } }, sessionPrefixV6: { serializedName: "sessionPrefixV6", type: { name: "String" } }, microsoftSessionIPv4Address: { readOnly: true, serializedName: "microsoftSessionIPv4Address", type: { name: "String" } }, microsoftSessionIPv6Address: { readOnly: true, serializedName: "microsoftSessionIPv6Address", type: { name: "String" } }, peerSessionIPv4Address: { serializedName: "peerSessionIPv4Address", type: { name: "String" } }, peerSessionIPv6Address: { serializedName: "peerSessionIPv6Address", type: { name: "String" } }, sessionStateV4: { readOnly: true, serializedName: "sessionStateV4", type: { name: "String" } }, sessionStateV6: { readOnly: true, serializedName: "sessionStateV6", type: { name: "String" } }, maxPrefixesAdvertisedV4: { serializedName: "maxPrefixesAdvertisedV4", type: { name: "Number" } }, maxPrefixesAdvertisedV6: { serializedName: "maxPrefixesAdvertisedV6", type: { name: "Number" } }, md5AuthenticationKey: { serializedName: "md5AuthenticationKey", type: { name: "String" } } } } }; export const DirectConnection: msRest.CompositeMapper = { serializedName: "DirectConnection", type: { name: "Composite", className: "DirectConnection", modelProperties: { bandwidthInMbps: { serializedName: "bandwidthInMbps", type: { name: "Number" } }, provisionedBandwidthInMbps: { serializedName: "provisionedBandwidthInMbps", type: { name: "Number" } }, sessionAddressProvider: { serializedName: "sessionAddressProvider", type: { name: "String" } }, useForPeeringService: { serializedName: "useForPeeringService", type: { name: "Boolean" } }, peeringDBFacilityId: { serializedName: "peeringDBFacilityId", type: { name: "Number" } }, connectionState: { readOnly: true, serializedName: "connectionState", type: { name: "String" } }, bgpSession: { serializedName: "bgpSession", type: { name: "Composite", className: "BgpSession" } }, connectionIdentifier: { serializedName: "connectionIdentifier", type: { name: "String" } } } } }; export const SubResource: msRest.CompositeMapper = { serializedName: "SubResource", type: { name: "Composite", className: "SubResource", modelProperties: { id: { serializedName: "id", type: { name: "String" } } } } }; export const PeeringPropertiesDirect: msRest.CompositeMapper = { serializedName: "PeeringPropertiesDirect", type: { name: "Composite", className: "PeeringPropertiesDirect", modelProperties: { connections: { serializedName: "connections", type: { name: "Sequence", element: { type: { name: "Composite", className: "DirectConnection" } } } }, useForPeeringService: { serializedName: "useForPeeringService", type: { name: "Boolean" } }, peerAsn: { serializedName: "peerAsn", type: { name: "Composite", className: "SubResource" } }, directPeeringType: { serializedName: "directPeeringType", type: { name: "String" } } } } }; export const ExchangeConnection: msRest.CompositeMapper = { serializedName: "ExchangeConnection", type: { name: "Composite", className: "ExchangeConnection", modelProperties: { peeringDBFacilityId: { serializedName: "peeringDBFacilityId", type: { name: "Number" } }, connectionState: { readOnly: true, serializedName: "connectionState", type: { name: "String" } }, bgpSession: { serializedName: "bgpSession", type: { name: "Composite", className: "BgpSession" } }, connectionIdentifier: { serializedName: "connectionIdentifier", type: { name: "String" } } } } }; export const PeeringPropertiesExchange: msRest.CompositeMapper = { serializedName: "PeeringPropertiesExchange", type: { name: "Composite", className: "PeeringPropertiesExchange", modelProperties: { connections: { serializedName: "connections", type: { name: "Sequence", element: { type: { name: "Composite", className: "ExchangeConnection" } } } }, peerAsn: { serializedName: "peerAsn", type: { name: "Composite", className: "SubResource" } } } } }; export const Resource: msRest.CompositeMapper = { serializedName: "Resource", type: { name: "Composite", className: "Resource", modelProperties: { name: { readOnly: true, serializedName: "name", type: { name: "String" } }, id: { readOnly: true, serializedName: "id", type: { name: "String" } }, type: { readOnly: true, serializedName: "type", type: { name: "String" } } } } }; export const Peering: msRest.CompositeMapper = { serializedName: "Peering", type: { name: "Composite", className: "Peering", modelProperties: { ...Resource.type.modelProperties, sku: { required: true, serializedName: "sku", type: { name: "Composite", className: "PeeringSku" } }, kind: { required: true, serializedName: "kind", type: { name: "String" } }, direct: { serializedName: "properties.direct", type: { name: "Composite", className: "PeeringPropertiesDirect" } }, exchange: { serializedName: "properties.exchange", type: { name: "Composite", className: "PeeringPropertiesExchange" } }, peeringLocation: { serializedName: "properties.peeringLocation", type: { name: "String" } }, provisioningState: { readOnly: true, serializedName: "properties.provisioningState", type: { name: "String" } }, location: { required: true, serializedName: "location", type: { name: "String" } }, tags: { serializedName: "tags", type: { name: "Dictionary", value: { type: { name: "String" } } } } } } }; export const OperationDisplayInfo: msRest.CompositeMapper = { serializedName: "OperationDisplayInfo", type: { name: "Composite", className: "OperationDisplayInfo", modelProperties: { provider: { readOnly: true, serializedName: "provider", type: { name: "String" } }, resource: { readOnly: true, serializedName: "resource", type: { name: "String" } }, operation: { readOnly: true, serializedName: "operation", type: { name: "String" } }, description: { readOnly: true, serializedName: "description", type: { name: "String" } } } } }; export const Operation: msRest.CompositeMapper = { serializedName: "Operation", type: { name: "Composite", className: "Operation", modelProperties: { name: { readOnly: true, serializedName: "name", type: { name: "String" } }, display: { readOnly: true, serializedName: "display", type: { name: "Composite", className: "OperationDisplayInfo" } }, isDataAction: { readOnly: true, serializedName: "isDataAction", type: { name: "Boolean" } } } } }; export const ContactInfo: msRest.CompositeMapper = { serializedName: "ContactInfo", type: { name: "Composite", className: "ContactInfo", modelProperties: { emails: { serializedName: "emails", type: { name: "Sequence", element: { type: { name: "String" } } } }, phone: { serializedName: "phone", type: { name: "Sequence", element: { type: { name: "String" } } } } } } }; export const PeerAsn: msRest.CompositeMapper = { serializedName: "PeerAsn", type: { name: "Composite", className: "PeerAsn", modelProperties: { ...Resource.type.modelProperties, peerAsn: { serializedName: "properties.peerAsn", type: { name: "Number" } }, peerContactInfo: { serializedName: "properties.peerContactInfo", type: { name: "Composite", className: "ContactInfo" } }, peerName: { serializedName: "properties.peerName", type: { name: "String" } }, validationState: { serializedName: "properties.validationState", type: { name: "String" } } } } }; export const DirectPeeringFacility: msRest.CompositeMapper = { serializedName: "DirectPeeringFacility", type: { name: "Composite", className: "DirectPeeringFacility", modelProperties: { address: { serializedName: "address", type: { name: "String" } }, directPeeringType: { serializedName: "directPeeringType", type: { name: "String" } }, peeringDBFacilityId: { serializedName: "peeringDBFacilityId", type: { name: "Number" } }, peeringDBFacilityLink: { serializedName: "peeringDBFacilityLink", type: { name: "String" } } } } }; export const PeeringBandwidthOffer: msRest.CompositeMapper = { serializedName: "PeeringBandwidthOffer", type: { name: "Composite", className: "PeeringBandwidthOffer", modelProperties: { offerName: { serializedName: "offerName", type: { name: "String" } }, valueInMbps: { serializedName: "valueInMbps", type: { name: "Number" } } } } }; export const PeeringLocationPropertiesDirect: msRest.CompositeMapper = { serializedName: "PeeringLocationPropertiesDirect", type: { name: "Composite", className: "PeeringLocationPropertiesDirect", modelProperties: { peeringFacilities: { serializedName: "peeringFacilities", type: { name: "Sequence", element: { type: { name: "Composite", className: "DirectPeeringFacility" } } } }, bandwidthOffers: { serializedName: "bandwidthOffers", type: { name: "Sequence", element: { type: { name: "Composite", className: "PeeringBandwidthOffer" } } } } } } }; export const ExchangePeeringFacility: msRest.CompositeMapper = { serializedName: "ExchangePeeringFacility", type: { name: "Composite", className: "ExchangePeeringFacility", modelProperties: { exchangeName: { serializedName: "exchangeName", type: { name: "String" } }, bandwidthInMbps: { serializedName: "bandwidthInMbps", type: { name: "Number" } }, microsoftIPv4Address: { serializedName: "microsoftIPv4Address", type: { name: "String" } }, microsoftIPv6Address: { serializedName: "microsoftIPv6Address", type: { name: "String" } }, facilityIPv4Prefix: { serializedName: "facilityIPv4Prefix", type: { name: "String" } }, facilityIPv6Prefix: { serializedName: "facilityIPv6Prefix", type: { name: "String" } }, peeringDBFacilityId: { serializedName: "peeringDBFacilityId", type: { name: "Number" } }, peeringDBFacilityLink: { serializedName: "peeringDBFacilityLink", type: { name: "String" } } } } }; export const PeeringLocationPropertiesExchange: msRest.CompositeMapper = { serializedName: "PeeringLocationPropertiesExchange", type: { name: "Composite", className: "PeeringLocationPropertiesExchange", modelProperties: { peeringFacilities: { serializedName: "peeringFacilities", type: { name: "Sequence", element: { type: { name: "Composite", className: "ExchangePeeringFacility" } } } } } } }; export const PeeringLocation: msRest.CompositeMapper = { serializedName: "PeeringLocation", type: { name: "Composite", className: "PeeringLocation", modelProperties: { ...Resource.type.modelProperties, kind: { serializedName: "kind", type: { name: "String" } }, direct: { serializedName: "properties.direct", type: { name: "Composite", className: "PeeringLocationPropertiesDirect" } }, exchange: { serializedName: "properties.exchange", type: { name: "Composite", className: "PeeringLocationPropertiesExchange" } }, peeringLocation: { serializedName: "properties.peeringLocation", type: { name: "String" } }, country: { serializedName: "properties.country", type: { name: "String" } }, azureRegion: { serializedName: "properties.azureRegion", type: { name: "String" } } } } }; export const ResourceTags: msRest.CompositeMapper = { serializedName: "ResourceTags", type: { name: "Composite", className: "ResourceTags", modelProperties: { tags: { serializedName: "tags", type: { name: "Dictionary", value: { type: { name: "String" } } } } } } }; export const PeeringServiceLocation: msRest.CompositeMapper = { serializedName: "PeeringServiceLocation", type: { name: "Composite", className: "PeeringServiceLocation", modelProperties: { ...Resource.type.modelProperties, country: { serializedName: "properties.country", type: { name: "String" } }, state: { serializedName: "properties.state", type: { name: "String" } }, azureRegion: { serializedName: "properties.azureRegion", type: { name: "String" } } } } }; export const PeeringServicePrefix: msRest.CompositeMapper = { serializedName: "PeeringServicePrefix", type: { name: "Composite", className: "PeeringServicePrefix", modelProperties: { ...Resource.type.modelProperties, prefix: { serializedName: "properties.prefix", type: { name: "String" } }, prefixValidationState: { serializedName: "properties.prefixValidationState", type: { name: "String" } }, learnedType: { serializedName: "properties.learnedType", type: { name: "String" } }, provisioningState: { readOnly: true, serializedName: "properties.provisioningState", type: { name: "String" } } } } }; export const PeeringServiceProvider: msRest.CompositeMapper = { serializedName: "PeeringServiceProvider", type: { name: "Composite", className: "PeeringServiceProvider", modelProperties: { ...Resource.type.modelProperties, serviceProviderName: { serializedName: "properties.serviceProviderName", type: { name: "String" } } } } }; export const PeeringService: msRest.CompositeMapper = { serializedName: "PeeringService", type: { name: "Composite", className: "PeeringService", modelProperties: { ...Resource.type.modelProperties, peeringServiceLocation: { serializedName: "properties.peeringServiceLocation", type: { name: "String" } }, peeringServiceProvider: { serializedName: "properties.peeringServiceProvider", type: { name: "String" } }, provisioningState: { readOnly: true, serializedName: "properties.provisioningState", type: { name: "String" } }, location: { required: true, serializedName: "location", type: { name: "String" } }, tags: { serializedName: "tags", type: { name: "Dictionary", value: { type: { name: "String" } } } } } } }; export const ErrorResponse: msRest.CompositeMapper = { serializedName: "ErrorResponse", type: { name: "Composite", className: "ErrorResponse", modelProperties: { code: { readOnly: true, serializedName: "code", type: { name: "String" } }, message: { readOnly: true, serializedName: "message", type: { name: "String" } } } } }; export const PeeringListResult: msRest.CompositeMapper = { serializedName: "PeeringListResult", type: { name: "Composite", className: "PeeringListResult", modelProperties: { value: { serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "Peering" } } } }, nextLink: { serializedName: "nextLink", type: { name: "String" } } } } }; export const OperationListResult: msRest.CompositeMapper = { serializedName: "OperationListResult", type: { name: "Composite", className: "OperationListResult", modelProperties: { value: { serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "Operation" } } } }, nextLink: { serializedName: "nextLink", type: { name: "String" } } } } }; export const PeerAsnListResult: msRest.CompositeMapper = { serializedName: "PeerAsnListResult", type: { name: "Composite", className: "PeerAsnListResult", modelProperties: { value: { serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "PeerAsn" } } } }, nextLink: { serializedName: "nextLink", type: { name: "String" } } } } }; export const PeeringLocationListResult: msRest.CompositeMapper = { serializedName: "PeeringLocationListResult", type: { name: "Composite", className: "PeeringLocationListResult", modelProperties: { value: { serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "PeeringLocation" } } } }, nextLink: { serializedName: "nextLink", type: { name: "String" } } } } }; export const PeeringServiceLocationListResult: msRest.CompositeMapper = { serializedName: "PeeringServiceLocationListResult", type: { name: "Composite", className: "PeeringServiceLocationListResult", modelProperties: { value: { serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "PeeringServiceLocation" } } } }, nextLink: { serializedName: "nextLink", type: { name: "String" } } } } }; export const PeeringServicePrefixListResult: msRest.CompositeMapper = { serializedName: "PeeringServicePrefixListResult", type: { name: "Composite", className: "PeeringServicePrefixListResult", modelProperties: { value: { serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "PeeringServicePrefix" } } } }, nextLink: { serializedName: "nextLink", type: { name: "String" } } } } }; export const PeeringServiceProviderListResult: msRest.CompositeMapper = { serializedName: "PeeringServiceProviderListResult", type: { name: "Composite", className: "PeeringServiceProviderListResult", modelProperties: { value: { serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "PeeringServiceProvider" } } } }, nextLink: { serializedName: "nextLink", type: { name: "String" } } } } }; export const PeeringServiceListResult: msRest.CompositeMapper = { serializedName: "PeeringServiceListResult", type: { name: "Composite", className: "PeeringServiceListResult", modelProperties: { value: { serializedName: "", type: { name: "Sequence", element: { type: { name: "Composite", className: "PeeringService" } } } }, nextLink: { serializedName: "nextLink", type: { name: "String" } } } } };
the_stack
import { Api, Client, Graph, Model } from "@core/types"; import { BaseArgs, DetectedApp } from "./types"; import path from "path"; import fs from "fs"; import os from "os"; import dotenv from "dotenv"; import { sha256 } from "@core/lib/crypto/utils"; import { getCoreProcAuthToken } from "@core/lib/client_store/key_store"; import { alwaysWriteError } from "./lib/console_io"; import { fetchState } from "@core/lib/core_proc"; import { getEnvironmentName, getEnvironmentsByEnvParentId, graphTypes, } from "@core/lib/graph"; import { dispatch } from "./lib/core"; import chalk from "chalk"; export const argIsEnvironment = ( graph: Graph.Graph, appId: string, firstArg?: string ): boolean => { return Boolean( getEnvironmentsByEnvParentId(graph)?.[appId]?.find((env) => [getEnvironmentName(graph, env.id).toLowerCase(), env.id].includes( firstArg?.toLowerCase() || "" ) ) ); }; // returns true if successfully performed override on account. You MUST re-exec (or at least re-auth). export const tryApplyDetectedAppOverride = ( userId: string, argv: BaseArgs ): boolean => { const hasNoAccountArgv = !argv["account"] && // important: infinite loop protection due to passing --account !argv["cli-envkey"] && !argv["org"]; const hasOverride = Boolean( argv["detectedApp"] && argv["detectedApp"].accountId !== userId ); const canReExec = hasNoAccountArgv && hasOverride; if (canReExec) { argv["account"] = argv["detectedApp"]!.accountId; logDetectedAccount(argv["detectedApp"]!); return true; } return false; }; // Precedence: look in environment vars, then local directory up for .env file, // then a directory up, and so on export const detectApp = async ( state: Client.State, argv: BaseArgs, workingDir: string ): Promise<DetectedApp | undefined> => { if (process.env.ENVKEY) { return envkeyToDetectedApp( state, argv, process.env.ENVKEY, undefined, undefined ); } return findEnvkeyOrConfigRecursive(state, argv, workingDir); }; const findEnvkeyOrConfigRecursive = async ( state: Client.State, argv: BaseArgs, presentDir: string ): Promise<DetectedApp | undefined> => { try { const detected = await dotEnvkeyFileToDetectedApp(state, argv, presentDir); if (detected) { return detected; } } catch (ignored) { logVerbose(argv, "detect app warning:", ignored.toString()); } const dotenvFile = path.join(presentDir, ".env"); try { logVerbose(argv, "detect app: checking for .env:", presentDir); const envBuf = await fs.promises.readFile(dotenvFile).catch((err) => { if (err.code === "ENOENT") { return undefined; } }); if (envBuf) { logVerbose(argv, "detect app: found .env:", dotenvFile); const vars = dotenv.parse(envBuf); if (vars.ENVKEY) { logVerbose( argv, "detect app: found ENVKEY:", vars.ENVKEY.substring(0, 6) + "****" ); return envkeyToDetectedApp( state, argv, vars.ENVKEY, dotenvFile, undefined ); } } } catch (ignored) { logVerbose(argv, "detect app warning:", ignored.toString()); } // bump one up const nextDir = path.resolve(presentDir, "../"); // up one // resolve won't recurse past "C:\\" or "/" and keep returning the same if ( !nextDir || // top of posix fs nextDir === "/" || // top of win32 without mount letter nextDir.slice(1) === ":\\" ) { return; } return findEnvkeyOrConfigRecursive(state, argv, nextDir); }; const dotEnvkeyFileToDetectedApp = async ( state: Client.State, argv: BaseArgs, presentDir: string ): Promise<DetectedApp | undefined> => { const dotenvkeyFile = path.join(presentDir, ".envkey"); let appId: string | undefined; let orgId: string | undefined; try { logVerbose(argv, "detect app: checking for .envkey:", dotenvkeyFile); const buf = await fs.promises.readFile(dotenvkeyFile).catch((err) => { if (err.code === "ENOENT") { return undefined; } }); if (buf) { logVerbose(argv, "detect app: found .envkey:", dotenvkeyFile); ({ appId, orgId } = JSON.parse(buf.toString()) as { orgId: string; appId: string; }); logVerbose(argv, "detect app: appId->", appId, " orgId->", orgId); } } catch (ignored) { logVerbose(argv, "detect app warning:", ignored.toString()); } if (!(appId && orgId)) { return; } // see if an envkey has been generated for this app const envkeyFile = path.join(os.homedir(), ".envkey", "apps", appId + ".env"); try { const envBuf = await fs.promises.readFile(envkeyFile); if (envBuf) { const vars = dotenv.parse(envBuf); if (vars.ENVKEY) { return envkeyToDetectedApp( state, argv, vars.ENVKEY, undefined, dotenvkeyFile, appId, orgId ); } } } catch (ignored) { logVerbose(argv, "detect app warning:", ignored.toString()); } const account = Object.values(state.orgUserAccounts).find( (acct) => acct && acct.orgId == orgId ); if (!account) { logVerbose(argv, "account not found for orgId->", orgId); return undefined; } const encryptedAuthToken = await getCoreProcAuthToken(); let updatedState = await fetchState(account.userId, encryptedAuthToken); if (account.token) { if (!updatedState.graphUpdatedAt) { const res = await dispatch({ type: Client.ActionType.GET_SESSION, }); if (!res.success) { logVerbose( argv, "account found for orgId->", orgId, "but couldn't load graph" ); return undefined; } updatedState = res.state; } } return { appId, appName: (updatedState.graph[appId] as Model.App)?.name ?? "", orgName: account.orgName, accountId: account.userId, dotenvFile: undefined, dotenvkeyFile: dotenvkeyFile, environmentId: undefined, localKeyId: undefined, foundEnvkey: undefined, envkeyFromEnvironment: false, }; }; const envkeyToDetectedApp = async ( state: Client.State, argv: BaseArgs, foundEnvkey: string, dotenvFile: string | undefined, dotenvkeyFile: string | undefined, appIdArg?: string, orgIdArg?: string ): Promise<DetectedApp | undefined> => { let appId = appIdArg; let orgId = orgIdArg; // lookup the envkey locally const envkeyParts = foundEnvkey.split("-"); const envkeyIdPart = envkeyParts[0]; const possibleEnvkeyHost = envkeyParts.slice(2).join("-"); const envkeyIdPartHash = sha256(envkeyIdPart); const accountIds = Object.keys(state.orgUserAccounts); const encryptedAuthToken = await getCoreProcAuthToken(); let updatedState: Client.State; let matchedEnvkey: Model.GeneratedEnvkey | undefined; logVerbose(argv, "detect app: searching for id part hash", envkeyIdPartHash); for (let accountId of accountIds) { const account = state.orgUserAccounts[accountId]!; if (!account.token) { continue; } updatedState = await fetchState(accountId, encryptedAuthToken); if (!updatedState.graphUpdatedAt) { const res = await dispatch({ type: Client.ActionType.GET_SESSION, }); if (!res.success) { logVerbose( argv, "account found for orgId->", orgId, "but couldn't load graph" ); continue; } updatedState = res.state; } matchedEnvkey = graphTypes(updatedState.graph).generatedEnvkeys.find( (key) => { logVerbose( argv, "detect app: checking key id hash", key.envkeyIdPartHash ); return key.envkeyIdPartHash === envkeyIdPartHash; } ); if (!matchedEnvkey) { logVerbose(argv, "detect app: not in accountId", accountId); continue; } appId = matchedEnvkey.appId; orgId = account.orgId; const out: DetectedApp = { appId: matchedEnvkey.appId!, appName: (updatedState.graph[matchedEnvkey.appId] as Model.App)?.name ?? "", orgName: account.orgName, accountId, dotenvFile, dotenvkeyFile, environmentId: matchedEnvkey.environmentId, localKeyId: matchedEnvkey.keyableParentId, foundEnvkey, envkeyFromEnvironment: !dotenvFile && !dotenvkeyFile, }; logVerbose(argv, "detect app: matched", out); return out; } logVerbose( argv, "detect app: did not find account, now looking up external", possibleEnvkeyHost ); if (!(appId && orgId)) { try { const res = await dispatch( { type: Api.ActionType.CHECK_ENVKEY, payload: { envkeyIdPart, }, }, undefined, possibleEnvkeyHost ); if (!res.success) { logVerbose( argv, "detect app: failed external lookup", res.resultAction ?? res ); return; } ({ appId, orgId } = (res.resultAction as any)?.payload ?? {}); if (appId && orgId) { logVerbose(argv, "detect app: fetch envkey attrs", { appId, orgId, }); } } catch (err) { logVerbose(argv, "detect app: fetch crash", err); return; } } if (!appId || !orgId) { return; } const account = Object.values(state.orgUserAccounts).find( (a) => a?.orgId === orgId ) as Client.ClientUserAuth | undefined; if (!account?.userId) { console.log( `Detected ENVKEY ${foundEnvkey.substring(0, 4)}***** from ${ dotenvFile || "environment" }, but there is no corresponding local account.` ); return; } if (!account.token) { return { accountId: account.userId, appId, appName: "", orgName: account!.orgName, dotenvFile, foundEnvkey, envkeyFromEnvironment: !dotenvFile && !dotenvkeyFile, dotenvkeyFile, environmentId: undefined, localKeyId: undefined, }; } updatedState = await fetchState(account.userId, encryptedAuthToken); if (!updatedState.graphUpdatedAt) { const res = await dispatch({ type: Client.ActionType.GET_SESSION, }); if (!res.success) { logVerbose( argv, "account found for orgId->", orgId, "but couldn't load graph" ); return undefined; } updatedState = res.state; } matchedEnvkey = graphTypes(updatedState.graph).generatedEnvkeys.find( (key) => { logVerbose( argv, "detect app: checking key id hash", key.envkeyIdPartHash ); return key.envkeyIdPartHash === envkeyIdPartHash; } ); if (!matchedEnvkey) { return; } const out: DetectedApp = { accountId: account.userId, appId, appName: (updatedState.graph[appId] as Model.App)?.name ?? "", orgName: account!.orgName, dotenvFile, foundEnvkey, envkeyFromEnvironment: !dotenvFile && !dotenvkeyFile, dotenvkeyFile, environmentId: matchedEnvkey.environmentId, localKeyId: matchedEnvkey.keyableParentId, }; logVerbose(argv, "detect app: matched externally", out); return out; }; const logDetectedAccount = (detected: DetectedApp): void => { if (detected.dotenvkeyFile) { console.log( `Detected account ${chalk.bold( detected.orgName )} from .envkey file at ${chalk.bold(detected.dotenvFile)}` ); } else { console.log( `Detected account ${chalk.bold( detected.orgName )} from ENVKEY ${chalk.bold( detected.foundEnvkey!.substring(0, 6) )}****** set in ${ detected.envkeyFromEnvironment ? "environment" : ".env file at " + chalk.bold(detected.dotenvFile) }` ); } }; const logVerbose = (argv: BaseArgs, ...args: any) => { if (argv["verbose"]) { console.error(...args); } };
the_stack
import { PacketMap } from '@realmlib/net'; import { EventEmitter } from 'events'; import { createWriteStream, WriteStream } from 'fs'; import { isIP } from 'net'; import { Client, LibraryManager, ResourceManager } from '../core'; import { Account, Server } from '../models'; import { ACCOUNT_IN_USE, AccountInUseError } from '../models/account-in-use-error'; import { AccountService, censorGuid, DefaultLogger, FileLogger, Logger, LogLevel, Updater } from '../services'; import { delay } from '../util/misc-util'; import { Environment } from './environment'; import { Versions } from './versions'; /** * An object which can be provided to the runtime when running. */ interface Arguments { [argName: string]: unknown; } /** * An account which was initially added, but failed for some reason. */ interface FailedAccount { /** * The account which failed to load. */ account: Account; /** * The number of times this account has tried to be loaded. */ retryCount: number; /** * The number of seconds to wait before trying to load this account again. */ timeout: number; } /** * The runtime manages clients, resources, plugins and any other services * which are used by an nrelay project. */ export class Runtime extends EventEmitter { /** * The environment of this runtime. */ readonly env: Environment; /** * The updater used by this runtime. */ readonly updater: Updater; /** * The account service used by this runtime. */ readonly accountService: AccountService; /** * The resource manager used by this runtime. */ readonly resources: ResourceManager; /** * The library manager used by this runtime. */ readonly libraryManager: LibraryManager; /** * A bidirectional map of packet ids. */ packetMap: PacketMap; /** * The build version to use when creating new clients. */ buildVersion: string; /** * The client token to use when connecting to a server. */ clientToken: string; /** * The last arguments which were passed to this runtime. * * Note that this may be `undefined`, and it may also contain arguments which * were not passed by the user (such as the `update` and `plugin-path` args). */ args: Arguments; /** * A WriteStream which is used for the log file. */ private logStream: WriteStream; /** * The clients which are managed by this runtime. */ private readonly clients: Map<string, Client>; constructor(environment: Environment) { super(); this.env = environment; this.updater = new Updater(this.env); this.accountService = new AccountService(this.env); this.resources = new ResourceManager(this.env); this.libraryManager = new LibraryManager(this); this.clients = new Map(); } /** * Starts this runtime. * @param args The arguments to start the runtime with. */ async run(args: Arguments): Promise<void> { this.args = args; // set up the logging. let minLevel = LogLevel.Info; if (args.debug) { minLevel = LogLevel.Debug; } Logger.addLogger(new DefaultLogger(minLevel)); // set up the log file if we have the flag enabled. if (args.log) { Logger.log('Runtime', 'Creating a log file.', LogLevel.Info); this.createLog(); Logger.addLogger(new FileLogger(this.logStream)); } // force an update. if (args['force-update'] === true) { try { await this.updater.performUpdate({ needAssetUpdate: true, needClientUpdate: true }); Logger.log('Runtime', 'Finished updating!', LogLevel.Success); } catch (err) { Logger.log('Runtime', `Error while updating: ${err.message}`, LogLevel.Error); } } else { // just check for updates normally (as long as --no-update wasn't included). if (args.update !== false) { try { Logger.log('Runtime', 'Checking for updates...', LogLevel.Info); const updateInfo = await this.updater.checkForUpdates(); await this.updater.performUpdate(updateInfo); } catch (err) { Logger.log('Runtime', `Error while updating: ${err.message}`, LogLevel.Error); } } } // load the resources. try { this.resources.loadAllResources(); } catch (error) { Logger.log('Runtime', 'Error while loading resources.', LogLevel.Error); Logger.log('Runtime', error.message, LogLevel.Error); process.exit(1); } // load the packets const packets: PacketMap = this.env.readJSON('packets.json'); if (!packets) { Logger.log('Runtime', 'Cannot load packets.json', LogLevel.Error); process.exit(1); } else { this.packetMap = packets; // the length is divided by 2 because the map is bidirectional. const size = Object.keys(this.packetMap).length / 2; Logger.log('Runtime', `Mapped ${size} packet ids.`, LogLevel.Info); } // load the version info. const versions = this.env.readJSON<Versions>('versions.json'); if (versions !== undefined) { if (versions.buildVersion) { this.buildVersion = versions.buildVersion; Logger.log('Runtime', `Using build version "${this.buildVersion}"`, LogLevel.Info); } else { Logger.log('Runtime', 'Cannot load buildVersion. Clients may not be able to connect.', LogLevel.Warning); } if (versions.clientToken) { this.clientToken = versions.clientToken; Logger.log('Runtime', `Using client token "${this.clientToken}"`, LogLevel.Info); } else { Logger.log('Runtime', 'Cannot load clientToken. Inserting the default value.', LogLevel.Warning); this.clientToken = 'XTeP7hERdchV5jrBZEYNebAqDPU6tKU6'; this.env.updateJSON<Versions>({ clientToken: this.clientToken }, 'versions.json'); } } else { Logger.log('Runtime', 'Cannot load versions.json', LogLevel.Error); process.exit(1); } // load the client hooks. this.libraryManager.loadClientHooks(); // if plugin loading is enabled. if (args.plugins !== false) { // load the plugins. The default is to load plugins from `lib/`, but we can change that with an arg. let pluginFolder = 'lib'; if (args.pluginPath && typeof args.pluginPath === 'string') { pluginFolder = args.pluginPath; Logger.log('Runtime', `Loading plugins from "${pluginFolder}"`, LogLevel.Debug); } this.libraryManager.loadPlugins(pluginFolder); } else { Logger.log('Runtime', 'Plugin loading disabled.', LogLevel.Info); } // finally, load any accounts. const accounts = this.env.readJSON<Account[]>('accounts.json'); if (accounts) { const failures: FailedAccount[] = []; for (const account of accounts) { try { await this.addClient(account); } catch (err) { Logger.log('Runtime', `Error adding account "${account.alias}": ${err.message}`, LogLevel.Error); const failure = { account, retryCount: 1, timeout: 1, }; if (err.name === ACCOUNT_IN_USE) { failure.timeout = (err as AccountInUseError).timeout; } failures.push(failure); } } // try to load the failed accounts. for (const failure of failures) { // perform the work in a promise so it doesn't block. new Promise(async (resolve, reject) => { while (failure.retryCount <= 10) { Logger.log( 'Runtime', `Retrying "${failure.account.alias}" in ${failure.timeout} seconds. (${failure.retryCount}/10)`, LogLevel.Info, ); // wait for the timeout then try to add the client. await delay(failure.timeout * 1000); try { await this.addClient(failure.account); resolve(); } catch (err) { // if it failed, increase the timeout on a logarithmic scale. Logger.log('Runtime', `Error adding account "${failure.account.alias}": ${err.message}`, LogLevel.Error); if (err.name === ACCOUNT_IN_USE) { failure.timeout = (err as AccountInUseError).timeout; } else { failure.timeout = Math.floor(Math.log10(1 + failure.retryCount) / 2 * 100); } failure.retryCount++; } } reject(); }).catch(() => { Logger.log( 'Runtime', `Failed to load "${failure.account.alias}" after 10 retries. Not retrying.`, LogLevel.Error, ); }); } } } /** * Creates a new client which uses the provided account. * @param account The account to login to. */ addClient(account: Account): Promise<Client> { // make sure the client has an alias. if (!account.alias) { account.alias = censorGuid(account.guid); } // make sure it's not already part of this runtime. if (this.clients.has(account.guid)) { return Promise.reject(new Error(`This account is already managed by this runtime.`)); } Logger.log('Runtime', `Loading ${account.alias}...`); // get the server list and char info. return Promise.all([ this.accountService.getServerList(), this.accountService.getCharacterInfo(account.guid, account.password, account.proxy), ]).then(([servers, charInfo]) => { account.charInfo = charInfo; // make sure the server exists. let server: Server; if (servers[account.serverPref]) { server = servers[account.serverPref]; } else { if (isIP(account.serverPref) !== 0) { server = { address: account.serverPref, name: `IP: ${account.serverPref}`, }; } else { const keys = Object.keys(servers); if (keys.length === 0) { throw new Error('Server list is empty.'); } server = servers[keys[Math.floor(Math.random() * keys.length)]]; Logger.log(account.alias, `Preferred server not found. Using ${server.name} instead.`, LogLevel.Warning); } } Logger.log('Runtime', `Loaded ${account.alias}!`, LogLevel.Success); const client = new Client(this, server, account); this.clients.set(client.guid, client); return client; }); } /** * Removes the client with the given `guid` from this runtime. * @param guid The guid of the client to remove. */ removeClient(guid: string): void { // make sure the client is actually in this runtime. if (this.clients.has(guid)) { const alias = this.clients.get(guid).alias; this.clients.get(guid).destroy(); this.clients.delete(guid); Logger.log('Runtime', `Removed ${alias}!`, LogLevel.Success); } else { Logger.log( 'Runtime', `The client ${censorGuid(guid)} is not part of this runtime.`, LogLevel.Warning, ); } } /** * Gets a copy of the clients in this runtime. * Modifying this list will not affect the runtime. */ getClients(): Client[] { return [...this.clients.values()]; } /** * Updates the build version stored in the versions.json file. * @param buildVersion The new build version to store. */ updateBuildVersion(buildVersion: string): void { this.env.updateJSON<Versions>({ buildVersion }, 'versions.json'); } /** * Creates a log file for this runtime. */ private createLog(): void { const nrelayVersion = require('../../package.json').version; this.logStream = createWriteStream(this.env.pathTo('nrelay-log.log')); const watermark = [ 'INFO', '----', `date :: ${(new Date()).toString()}`, `nrelay version :: v${nrelayVersion}`, `node version :: ${process.version}`, '', 'LOG', '----', ].join('\n'); this.logStream.write(`${watermark}\n`); } }
the_stack
import { Renderer2 } from '@angular/core'; import { Axis } from './axis.model'; import { Layout, RowSpec, MarkerSpec } from './i-timeline'; import { Marker } from './marker.model'; import { Row } from './row.model'; export namespace Timeline { const YEAR_LEN = 31536000000; function clearChildNodes(elt: Node, fromIdx?: number) { if (! elt) return; for (let i = elt.childNodes.length - 1; i >= (fromIdx || 0); i--) { elt.removeChild(elt.childNodes[i]); } } function addElementContent(elt, content) { if (typeof content === 'string') { elt.appendChild(document.createTextNode(content)); } else if (elt) { elt.appendChild(content); } } function setElementContent(elt, content) { if (typeof content === 'string') { elt.innerHTML = content; } else if (Array.isArray(content)) { elt.innerHTML = ''; for (const part of content) { addElementContent(elt, part); } } } export function parseDate(date: string | Date) { let result: Date = null; if (typeof date === 'string') { result = new Date(date); } else { result = date; } if (result && isNaN(result.getTime())) { result = null; } return result; } function offsetDate(date: Date, offset: number) { const time = date.getTime() + (offset || 0); const d = new Date(); d.setTime(time); return d; } export class TimelineView { _elts: {[key: string]: HTMLElement} = { container: null, controlsOuter: null, controlsInner: null, axisOuter: null, rowsOuter: null, }; _axis: Axis; _layout: Layout = {}; _lastLayout: Layout; _nextLayout: Layout; _gestureStartLayout: Layout; _markers: Marker[] = []; _rendered = false; _renderer: Renderer2; _resetRange: {start: Date, end: Date}; _rows: Row[] = []; _redrawTimer: number; _updateTimer: number; _shortDateMarkers: Marker[]; constructor(container: HTMLElement, layout: Layout, renderer: Renderer2) { this._elts.container = container; this._layout = layout || {}; this._renderer = renderer; } get container() { return this._elts.container; } get rows() { return this._rows; } setRows(vals: RowSpec[]) { this._rows = (vals || []).map(val => new Row(val)); this.redraw(); } setMarkers(vals: MarkerSpec[]) { this._markers = (vals || []).map(val => new Marker(val)); this.redraw(); } setShortDateMarkers(vals: MarkerSpec[]) { this._shortDateMarkers = (vals || []).map(val => new Marker(val)); this.redraw(); } setRange(start: string | Date, end: string | Date, relative?: boolean) { let startDate = parseDate(start); let endDate = parseDate(end); if (startDate && endDate && endDate.getTime() < startDate.getTime()) { // swap if in wrong order const dt = startDate; startDate = endDate; endDate = dt; } const layout = Object.assign({}, this._layout); layout.start = startDate; layout.end = endDate; if (!relative) this._resetRange = {start: startDate, end: endDate} this.setLayout(layout); } moveRange(delta, layout?: Layout) { if (! layout) layout = this._layout; if (layout.start && layout.end) { let startTime = layout.start.getTime(); const diff = layout.end.getTime() - startTime; startTime -= Math.round(diff * delta / 300); const start = new Date(); start.setTime(startTime); const end = offsetDate(start, diff); this.setRange(start, end, true); } } scaleRange(delta, layout?: Layout) { if (! layout) layout = this._layout; if (layout.start && layout.end) { const startTime = layout.start.getTime(); const diff = layout.end.getTime() - startTime; let offs = Math.round(diff * delta); if (diff + offs * 2 > YEAR_LEN * 200) { offs = (YEAR_LEN * 200 - diff) / 2; } const start = offsetDate(layout.start, -offs); const end = offsetDate(layout.end, +offs); this.setRange(start, end, true); } } resetRange() { if (this._resetRange) { const layout = Object.assign({}, this._layout); layout.start = this._resetRange.start; layout.end = this._resetRange.end; this.setLayout(layout); } } get layout() { return this._layout; } setLayout(newLayout: Layout) { if (! newLayout) return; if (this._layout && ! newLayout.noAnimate && this._rendered && newLayout.start && newLayout.end && this._layout.start && this._layout.end) { if (! newLayout.time) { newLayout.time = new Date().getTime() + 200; } this._lastLayout = this._layout; this._lastLayout.time = new Date().getTime(); this._nextLayout = newLayout; this.update(); } else { newLayout.time = new Date().getTime(); this._lastLayout = this._layout; this._layout = newLayout; this._nextLayout = null; this.redraw(); } } handleEvent(evt) { if (evt.type === 'mousewheel') { if (evt.ctrlKey) { if (evt.deltaY) { const delta = evt.deltaY * 0.01; this.scaleRange(delta); evt.preventDefault(); } } else { if (Math.abs(evt.deltaX) > Math.abs(evt.deltaY)) { let delta = - evt.deltaX * 2; delta = Math.sign(delta) * Math.min(Math.abs(delta), 50); this.moveRange(delta); evt.preventDefault(); } } } else if (evt.type === 'gesturestart') { evt.preventDefault(); evt.stopPropagation(); this._gestureStartLayout = Object.assign({}, this._layout); } else if (evt.type === 'gesturechange') { evt.preventDefault(); evt.stopPropagation(); if (evt.scale) { this.scaleRange(- evt.scale, this._gestureStartLayout); } } else if (evt.type === 'gestureend') { evt.preventDefault(); this._gestureStartLayout = null; } } handleControl(evt) { let tgt = evt.target; while (tgt && ! tgt.name && tgt.parentNode && tgt.parentNode !== window) { tgt = tgt.parentNode; } const evtName = tgt && tgt.name; if (evtName == 'zoomin') { this.scaleRange(-0.1); } else if (evtName == 'zoomout') { this.scaleRange(0.1); } else if (evtName == 'prev') { this.moveRange(10); } else if (evtName == 'fastprev') { this.moveRange(100); } else if (evtName == 'next') { this.moveRange(-10); } else if (evtName == 'fastnext') { this.moveRange(-100); } else if (evtName == 'reset') { this.resetRange(); } } render() { const rdr = this._renderer; const elts = this._elts; if (rdr && ! this._rendered) { if (! elts.container) { elts.container = rdr.createElement('div'); } const handler = this.handleEvent.bind(this); rdr.listen(elts.container, 'mousewheel', handler); rdr.listen(elts.container, 'gesturestart', handler); rdr.listen(elts.container, 'gesturechange', handler); rdr.listen(elts.container, 'gestureend', handler); // disable forward/back gesture in Chrome rdr.listen(elts.container, 'pointermove', handler); rdr.addClass(elts.container, 'timeline-outer'); elts.controlsOuter = rdr.createElement('div'); rdr.addClass(elts.controlsOuter, 'controls-outer'); rdr.addClass(elts.controlsOuter, 'row'); elts.controlsInner = rdr.createElement('div'); rdr.addClass(elts.controlsInner, 'controls-inner'); rdr.addClass(elts.controlsInner, 'col'); rdr.addClass(elts.controlsInner, 'text-center'); elts.controlsOuter.appendChild(elts.controlsInner); this.renderControls(); elts.rowsOuter = rdr.createElement('div'); rdr.addClass(elts.rowsOuter, 'rows-outer'); elts.axisOuter = rdr.createElement('div'); rdr.addClass(elts.axisOuter, 'axis-outer'); this._axis = new Axis(); this._axis.setRange(this._layout.start, this._layout.end); elts.axisOuter.appendChild(this._axis.render(rdr)); this._rendered = true; this.redraw(); } return elts.container; } renderControls() { const groups = [ ['fastprev', 'prev'], ['zoomout', 'zoomin'], ['reset'], ['next', 'fastnext'], ]; const icons = { fastprev: 'fa-angle-double-left', prev: 'fa-angle-left', zoomin: 'fa-search-plus', zoomout: 'fa-search-minus', reset: 'fa-undo', next: 'fa-angle-right', fastnext: 'fa-angle-double-right', }; const rdr = this._renderer; for (const btns of groups) { const grp = rdr.createElement('div'); rdr.addClass(grp, 'btn-group'); grp.setAttribute('role', 'group'); for (const btn of btns) { const elt = rdr.createElement('button'); elt.setAttribute('type', 'button'); rdr.addClass(elt, 'btn'); rdr.addClass(elt, 'btn-sm'); rdr.addClass(elt, 'btn-secondary'); elt.name = btn; elt.tabIndex = 0; const icon = rdr.createElement('span'); rdr.addClass(icon, 'fa'); rdr.addClass(icon, icons[btn]); elt.appendChild(icon); grp.appendChild(elt); rdr.listen(elt, 'click', this.handleControl.bind(this)); } this._elts.controlsInner.appendChild(grp); this._elts.controlsInner.appendChild(document.createTextNode(' ')); } } redraw() { if (! this._rendered) return; clearTimeout(this._updateTimer); this._updateTimer = null; if (this._redrawTimer) return; this._redrawTimer = requestAnimationFrame(this._performRedraw.bind(this)); } _performRedraw() { const container = this._elts.container; const first = container.childNodes[0]; const body = [this._elts.controlsOuter, this._elts.rowsOuter, this._elts.axisOuter]; for (const elt of body) { container.insertBefore(elt, first); } clearChildNodes(container, body.length); const rowFirst = this._elts.rowsOuter.childNodes[0]; let zIndex = 40; let clearPos = 0; for (const mark of this._markers) { const elt = !mark.link ? mark.render(this._renderer, false) : mark.render(this._renderer, true); this._elts.rowsOuter.insertBefore(elt, rowFirst); // elt.style.zIndex = '' + Math.max(0, zIndex); clearPos ++; } for (const row of this._rows) { const elt = row.render(this._renderer); this._elts.rowsOuter.insertBefore(elt, rowFirst); elt.style.zIndex = '' + Math.max(0, zIndex--); clearPos ++; } clearChildNodes(this._elts.rowsOuter, clearPos); this._performUpdate(); } update() { if (this._updateTimer) return; this._updateTimer = requestAnimationFrame(this._performUpdate.bind(this)); } _updateLayout() { if (this._nextLayout) { const now = new Date().getTime(); if (this._nextLayout.time <= now) { this._nextLayout.time = now; this._layout = this._nextLayout; this._nextLayout = null; } else { // move closer to layout const startTime = this._lastLayout.time; const diff = this._nextLayout.time - startTime; const scale = (now - startTime) / diff; if (this._nextLayout.start != this._lastLayout.start) { this._layout.start = offsetDate(this._lastLayout.start, diff * scale); } if (this._nextLayout.end != this._lastLayout.end) { this._layout.end = offsetDate(this._lastLayout.end, diff * scale); } return false; } } return true; } _performUpdate() { clearTimeout(this._updateTimer); this._updateTimer = null; const reUp = ! this._updateLayout(); if (this._elts.container) { const width = this._elts.container.clientWidth; // reposition slots const rowsWidth = this._elts.rowsOuter.clientWidth; for (const row of this._rows) { row.setRange(this._layout.start, this._layout.end); row.update(rowsWidth); } // redraw axis const axisWidth = this._elts.axisOuter.clientWidth; this._axis.setRange(this._layout.start, this._layout.end); this._axis.update(axisWidth); // reposition markers for (const mark of this._markers) { mark.setRange(this._layout.start, this._layout.end); mark.update(rowsWidth); } } if (reUp) { this.update(); } } } }
the_stack
import chalk from 'chalk'; import { flags } from '@oclif/command'; import { Listr, ListrDefaultRendererOptions, ListrTask, ListrTaskWrapper, } from 'listr2'; import figures from 'figures'; import BaseCommand from '../base-command'; import { transformTagsFlagToFilterList, configureAWS } from '../util'; import { TrickRegistry } from '../tricks/trick.registry'; import { TrickInterface } from '../types/trick.interface'; import { ShutdownEC2InstancesTrick } from '../tricks/shutdown-ec2-instances.trick'; import { StopFargateEcsServicesTrick } from '../tricks/stop-fargate-ecs-services.trick'; import { StopRdsDatabaseInstancesTrick } from '../tricks/stop-rds-database-instances.trick'; import { DecreaseDynamoDBProvisionedRcuWcuTrick } from '../tricks/decrease-dynamodb-provisioned-rcu-wcu.trick'; import { RemoveNatGatewaysTrick } from '../tricks/remove-nat-gateways.trick'; import { SnapshotRemoveElasticacheRedisTrick } from '../tricks/snapshot-remove-elasticache-redis.trick'; import { DecreaseKinesisStreamsShardsTrick } from '../tricks/decrease-kinesis-streams-shards.trick'; import { StopRdsDatabaseClustersTrick } from '../tricks/stop-rds-database-clusters.trick'; import { ScaledownAutoScalingGroupsTrick } from '../tricks/scaledown-auto-scaling-groups.trick'; import { SuspendAutoScalingGroupsTrick } from '../tricks/suspend-auto-scaling-groups.trick'; import { RootState } from '../types/root-state'; import { RootContext } from '../types/root-context'; import { TrickOptionsInterface } from '../types/trick-options.interface'; import { TrickContext } from '../types/trick-context'; export default class Conserve extends BaseCommand { static tricksEnabledByDefault: readonly string[] = [ ShutdownEC2InstancesTrick.machineName, StopFargateEcsServicesTrick.machineName, StopRdsDatabaseInstancesTrick.machineName, DecreaseDynamoDBProvisionedRcuWcuTrick.machineName, DecreaseKinesisStreamsShardsTrick.machineName, StopRdsDatabaseClustersTrick.machineName, SuspendAutoScalingGroupsTrick.machineName, ]; static tricksDisabledByDefault: readonly string[] = [ // Removing NAT gateways can confuse IaC like terraform RemoveNatGatewaysTrick.machineName, // This is an experimental trick, plus removing and recreating ElastiCache clusters takes a long time SnapshotRemoveElasticacheRedisTrick.machineName, // Scaling-down an ASG will cause all instances to be terminated and lose their temporary volumes ScaledownAutoScalingGroupsTrick.machineName, ]; static description = [ `This command uses various tricks to conserve as much money as possible.`, `To restore, this command will create a \`aws-cost-saver.json\` file to be use by "restore".`, `\nThese tricks are ${chalk.bold('enabled')} by default: ${chalk.green( `\n\t- ${Conserve.tricksEnabledByDefault.join('\n\t- ')}`, )}`, `\nThese tricks are ${chalk.bold('disabled')} by default: ${chalk.redBright( `\n\t- ${Conserve.tricksDisabledByDefault.join('\n\t- ')}`, )}`, ].join('\n'); static examples = [ `$ aws-cost-saver conserve`, `$ aws-cost-saver conserve ${chalk.yellow('--dry-run')}`, `$ aws-cost-saver conserve ${chalk.yellow('--no-state-file')}`, `$ aws-cost-saver conserve ${chalk.yellow('--only-summary')}`, `$ aws-cost-saver conserve ${chalk.yellow('-d -n -m -t Team=Tacos')}`, `$ aws-cost-saver conserve ${chalk.yellow( `--use-trick ${chalk.bold( SnapshotRemoveElasticacheRedisTrick.machineName, )}`, )}`, `$ aws-cost-saver conserve ${chalk.yellow( `--ignore-trick ${chalk.bold(StopRdsDatabaseInstancesTrick.machineName)}`, )}`, `$ aws-cost-saver conserve ${chalk.yellow( `--no-default-tricks --use-trick ${chalk.bold( StopFargateEcsServicesTrick.machineName, )}`, )}`, `$ aws-cost-saver conserve ${chalk.yellow( `--region ${chalk.bold(`eu-central-1`)} --profile ${chalk.bold( `my-aws-profile`, )}`, )}`, `$ aws-cost-saver conserve ${chalk.yellow( `--state-file ${chalk.bold(`new-path.json`)}`, )}`, ]; static flags = { help: flags.help({ char: 'h' }), region: flags.string({ char: 'r', default: 'eu-central-1' }), profile: flags.string({ char: 'p', default: 'default' }), 'dry-run': flags.boolean({ char: 'd', description: 'Only list actions and do not actually execute them.', }), 'state-file': flags.string({ char: 's', default: 'aws-cost-saver.json', description: 'Where to keep original state of stopped/decreased resources to restore later.', }), 'no-state-file': flags.boolean({ char: 'n', default: false, description: 'Ignore saving current state, useful when want to only conserve as much money as possible.', }), 'overwrite-state-file': flags.boolean({ char: 'w', default: false, description: 'Overwrite state-file if it exists. WARNING: Use with caution as this might overwrite non-restored state-file.', }), 'use-trick': flags.string({ char: 'u', multiple: true, description: 'Enables an individual trick. Useful for tricks that are disabled by default.', }), 'ignore-trick': flags.string({ char: 'i', multiple: true, description: 'Disables an individual trick. Useful when you do not like to use a specific trick.', }), 'no-default-tricks': flags.boolean({ default: false, description: 'Disables all default tricks. Useful alongside --use-trick when you only want a set of specific tricks to execute.', }), 'only-summary': flags.boolean({ char: 'm', default: false, description: 'Do not render live progress. Only print final summary in a clean format.', }), tag: flags.string({ char: 't', multiple: true, required: false, description: 'Resource tags to narrow down affected resources. Multiple provided tags will be AND-ed.', }), }; static args = []; async run() { const { flags } = this.parse(Conserve); const awsConfig = await configureAWS(flags.profile, flags.region); await this.validateStateFilePath(flags); this.printBanner(awsConfig, flags); const tricks = this.getEnabledTricks(flags); const rootContext: RootContext = {}; const rootState: RootState = {}; const rootTaskList: ListrTask[] = []; const options: TrickOptionsInterface = { dryRun: flags['dry-run'], tags: flags.tag && transformTagsFlagToFilterList(flags.tag), }; for (const trick of tricks) { rootTaskList.push({ title: `${chalk.dim(`conserve:`)} ${trick.getMachineName()}`, task: (ctx, task) => { rootContext[trick.getMachineName()] = {}; rootState[trick.getMachineName()] = []; return this.createTrickListr({ trickTask: task, trickContext: rootContext[trick.getMachineName()], trickState: rootState[trick.getMachineName()], trickInstance: trick, trickOptions: options, }); }, }); } const listr = new Listr(rootTaskList, { renderer: flags['only-summary'] ? 'silent' : 'default', concurrent: true, exitOnError: false, rendererOptions: { collapse: true, showTimer: true, showSubtasks: true, clearOutput: true, }, } as ListrDefaultRendererOptions<any>); await listr.run(rootContext); this.renderSummary(listr.tasks); if (!flags['no-state-file']) { await this.writeStateFile(flags['state-file'], rootState); this.log( ` ${chalk.green(figures.pointer)} wrote state to ${chalk.green( flags['state-file'], )}`, ); } const errors = this.collectErrors(listr.tasks); if (errors && errors.length > 0) { if (errors.length < listr.tasks.length) { this.log( `\n${chalk.yellow(figures.tick)} partially finished, with ${chalk.red( `${errors.length} failed tricks out of ${listr.tasks.length}`, )}.`, ); throw new Error('ConservePartialFailure'); } else { this.log( `\n${chalk.yellow(figures.cross)} All ${ listr.tasks.length } tricks failed.`, ); throw new Error(`ConserveFailure`); } } else if (flags['dry-run']) { this.log( `\n${chalk.yellow( ` ${figures.warning} skipped conserve due to dry-run.`, )}`, ); } else { this.log(`\n ${chalk.green(figures.tick)} successfully conserved.`); } } private createTrickListr(cfg: { trickTask: ListrTaskWrapper<any, any>; trickContext: TrickContext; trickState: Record<string, any>[]; trickInstance: TrickInterface<any>; trickOptions: TrickOptionsInterface; }): Listr<any, any, any> { return cfg.trickTask.newListr( [ { title: 'prepare tags', task: (ctx, task) => cfg.trickInstance.prepareTags( task, cfg.trickContext, cfg.trickOptions, ), }, { title: 'fetch current state', task: (ctx, task) => cfg.trickInstance.getCurrentState( task, cfg.trickContext, cfg.trickState, cfg.trickOptions, ), }, { title: 'conserve resources', task: (ctx, task) => cfg.trickInstance.conserve(task, cfg.trickState, cfg.trickOptions), }, ], { concurrent: false, exitOnError: false, rendererOptions: { collapse: true, }, }, ); } private getEnabledTricks(flags: Record<string, any>): TrickInterface<any>[] { const tricksRegistry = TrickRegistry.initialize(); const tricks = tricksRegistry.all(); let enabledTricks: string[] = flags['no-default-tricks'] ? [] : ([] as string[]).concat(...Conserve.tricksEnabledByDefault); if (flags['use-trick'] && flags['use-trick'].length > 0) { enabledTricks.push(...flags['use-trick']); } if (flags['ignore-trick'] && flags['ignore-trick'].length > 0) { enabledTricks = enabledTricks.filter( trickName => !flags['ignore-trick'].includes(trickName), ); } return enabledTricks.map(trickName => { const trick = tricks.find(trick => trick.getMachineName() === trickName); if (!trick) { this.log(`could not find a trick named ${chalk.yellow(trickName)}`); this.log( `run ${chalk.yellow( 'aws-cost-saver conserve --help', )} to get a list of available tricks.\n`, ); throw new Error('TrickNotFound'); } return trick; }); } }
the_stack
import KoaApplication = require('koa'); import { Logger, EggConsoleLogger } from 'egg-logger'; import depd = require('depd'); type EggType = 'application' | 'agent'; interface PlainObject<T = any> { [key: string]: T; } export interface EggCoreOptions { /** egg type, application or agent */ type?: EggType; /** the directory of application */ baseDir?: EggAppInfo['baseDir']; /** server scope */ serverScope?: string; /** custom plugins */ plugins?: Plugins; } export interface EggLoaderOptions { /** Application instance */ app: EggCore; /** the directory of application */ baseDir: EggAppInfo['baseDir']; /** egg logger */ logger: Logger; /** server scope */ serverScope?: string; /** custom plugins */ plugins?: Plugins; } export interface PluginInfo { /** the plugin name, it can be used in `dep` */ name: string; /** the package name of plugin */ package: string; /** whether enabled */ enable: boolean; /** the directory of the plugin package */ path: string; /** the dependent plugins, you can use the plugin name */ dependencies: string[]; /** the optional dependent plugins. */ optionalDependencies: string[]; /** specify the serverEnv that only enable the plugin in it */ env: string[]; /** the file plugin config in. */ from: string; } export interface Plugins extends PlainObject<PluginInfo> { } export interface EggCoreBase<Config> extends KoaApplication { /** * Whether `application` or `agent` * @member {String} * @since 1.0.0 */ type: EggType; /** * The current directory of application * @member {String} * @see {@link EggAppInfo#baseDir} * @since 1.0.0 */ baseDir: EggAppInfo['baseDir']; /** * The name of application * @member {String} * @see {@link EggAppInfo#name} * @since 1.0.0 */ name: EggAppInfo['name']; /** * Convert a generator function to a promisable one. * * Notice: for other kinds of functions, it directly returns you what it is. * * @param {Function} fn The inputted function. * @return {AsyncFunction} An async promise-based function. * @example * ```javascript * const fn = function* (arg) { return arg; }; const wrapped = app.toAsyncFunction(fn); wrapped(true).then((value) => console.log(value)); * ``` */ toAsyncFunction<T = any>(fn: (...args: any[]) => IterableIterator<T>): (...args: any[]) => Promise<T>; /** * Convert an object with generator functions to a Promisable one. * @param {Mixed} obj The inputted object. * @return {Promise} A Promisable result. * @example * ```javascript * const fn = function* (arg) { return arg; }; const arr = [ fn(1), fn(2) ]; const promise = app.toPromise(arr); promise.then(res => console.log(res)); * ``` */ toPromise<T = any>(obj: any): Promise<T>; /** * register an callback function that will be invoked when application is ready. * @see https://github.com/node-modules/ready * @since 1.0.0 * @param {boolean|Error|Function} flagOrFunction - * @return {Promise|null} return promise when argument is undefined * @example * const app = new Application(...); * app.ready(err => { * if (err) throw err; * console.log('done'); * }); */ ready(fn?: (err?: Error) => void): any; /** * Close all, it wil close * - callbacks registered by beforeClose * - emit `close` event * - remove add listeners * * If error is thrown when it's closing, the promise will reject. * It will also reject after following call. * @return {Promise} promise * @since 1.0.0 */ close(): Promise<any>; /** * If a client starts asynchronously, you can register `readyCallback`, * then the application will wait for the callback to ready * * It will log when the callback is not invoked after 10s * * Recommend to use {@link EggCore#beforeStart} * @since 1.0.0 * * @param {String} name - readyCallback task name * @param {object} opts - * - {Number} [timeout=10000] - emit `ready_timeout` when it doesn't finish but reach the timeout * - {Boolean} [isWeakDep=false] - whether it's a weak dependency * @return {Function} - a callback * @example * const done = app.readyCallback('mysql'); * mysql.ready(done); */ readyCallback(name: string, opts?: { timeout?: number; isWeakDep?: boolean }): () => void; /** * The loader instance, the default class is {@link EggLoader}. * If you want define * @member {EggLoader} EggCore#loader * @since 1.0.0 */ loader: EggLoader<this, Config>; /** * The configuration of application * @member {Config} * @since 1.0.0 */ config: Config; /** * Retrieve enabled plugins * @member {Object} * @since 1.0.0 */ plugins: Plugins; /** * Register a function that will be called when app close */ beforeClose(fn: () => void): void; /** * Execute scope after loaded and before app start */ beforeStart(scope: () => void): void; /** * Alias to {@link https://npmjs.com/package/depd} * @member {Function} * @since 1.0.0 */ deprecate: depd.Deprecate; } export interface EggCore<Config = PlainObject> extends EggCoreBase<Config> { Controller: typeof BaseContextClass; Service: typeof BaseContextClass; } export class EggCore { /** * @constructor * @param {Object} options - options * @param {String} [options.baseDir=process.cwd()] - the directory of application * @param {String} [options.type=application|agent] - whether it's running in app worker or agent worker * @param {Object} [options.plugins] - custom plugins * @since 1.0.0 */ constructor(options?: EggCoreOptions); } /** * egg app info * @example * ```js * // config/config.default.ts * import { EggAppInfo } from 'egg'; * * export default (appInfo: EggAppInfo) => { * return { * keys: appInfo.name + '123456', * }; * } * ``` */ export interface EggAppInfo { /** package.json */ pkg: PlainObject; /** the application name from package.json */ name: string; /** current directory of application */ baseDir: string; /** equals to serverEnv */ env: string; /** home directory of the OS */ HOME: string; /** baseDir when local and unittest, HOME when other environment */ root: string; } /** * BaseContextClass is a base class that can be extended, * it's instantiated in context level, * {@link Helper}, {@link Service} is extending it. */ export class BaseContextClass< Context = any, Application = any, EggAppConfig = any, Service = any > { constructor(ctx: Context); /** request context */ protected ctx: Context; /** Application */ protected app: Application; /** Application config object */ protected config: EggAppConfig; /** service */ protected service: Service; } export interface FileLoaderOption { /** directories to be loaded */ directory: string | string[]; /** attach the target object from loaded files */ target: object; /** match the files when load, support glob, default to all js files */ match?: string | string[]; /** ignore the files when load, support glob */ ignore?: string | string[]; /** custom file exports, receive two parameters, first is the inject object(if not js file, will be content buffer), second is an `options` object that contain `path` */ initializer?(obj: object, options: { path: string; pathName: string; }): any; /** determine whether invoke when exports is function */ call?: boolean; /** determine whether override the property when get the same name */ override?: boolean; /** an object that be the argument when invoke the function */ inject?: object; /** a function that filter the exports which can be loaded */ filter?(obj: object): boolean; /** set property's case when converting a filepath to property list. */ caseStyle?: string | ((str: string) => string[]); } export interface ContextLoaderOption extends Partial<FileLoaderOption> { /** directories to be loaded */ directory: string | string[]; /** required inject */ inject: object; /** property name defined to target */ property: string; /** determine the field name of inject object. */ fieldClass?: string; } declare interface FileLoaderBase { /** * attach items to target object. Mapping the directory to properties. * `app/controller/group/repository.js` => `target.group.repository` * @return {Object} target * @since 1.0.0 */ load(): object; /** * Parse files from given directories, then return an items list, each item contains properties and exports. * * For example, parse `app/controller/group/repository.js` * * ```js * module.exports = app => { * return class RepositoryController extends app.Controller {}; * } * ``` * * It returns a item * * ```js * { * properties: [ 'group', 'repository' ], * exports: app => { ... }, * } * ``` * * `Properties` is an array that contains the directory of a filepath. * * `Exports` depends on type, if exports is a function, it will be called. if initializer is specified, it will be called with exports for customizing. * @return {Array} items * @since 1.0.0 */ parse(): Array<{ fullpath: string; properties: string[]; exports: any; }>; } declare interface ContextLoaderBase extends FileLoaderBase {} export interface FileLoader { /** * Load files from directory to target object. * @since 1.0.0 */ new (options: FileLoaderOption): FileLoaderBase; } export interface ContextLoader { /** * Same as {@link FileLoader}, but it will attach file to `inject[fieldClass]`. The exports will be lazy loaded, such as `ctx.group.repository`. * @extends FileLoader * @since 1.0.0 */ new (options: ContextLoaderOption): ContextLoaderBase; } export class EggLoader<T = EggCore, Config = any> { app: T; eggPaths: string[]; pkg: PlainObject; appInfo: EggAppInfo; serverScope: string; plugins: Plugins; config: Config; /** * @constructor * @param {Object} options - options * @param {String} options.baseDir - the directory of application * @param {EggCore} options.app - Application instance * @param {Logger} options.logger - logger * @param {Object} [options.plugins] - custom plugins * @since 1.0.0 */ constructor(options: EggLoaderOptions); /** * Get home directory * @return {String} home directory * @since 3.4.0 */ getHomedir(): EggAppInfo['HOME']; /** * Get app info * @return {EggAppInfo} appInfo * @since 1.0.0 */ getAppInfo(): EggAppInfo; // Low Level API /** * Load single file, will invoke when export is function * * @param {String} filepath - fullpath * @param {Array} arguments - pass rest arguments into the function when invoke * @return {Object} exports * @example * ```js * app.loader.loadFile(path.join(app.options.baseDir, 'config/router.js')); * ``` * @since 1.0.0 */ loadFile<T = any>(filepath: string, ...inject: any[]): T; /** * Get all loadUnit * * loadUnit is a directory that can be loaded by EggLoader, it has the same structure. * loadUnit has a path and a type(app, framework, plugin). * * The order of the loadUnits: * * 1. plugin * 2. framework * 3. app * * @return {Array} loadUnits * @since 1.0.0 */ getLoadUnits(): Array<{ path: string; type: string; }>; /** * Load files using {@link FileLoader}, inject to {@link Application} * @param {String|Array} directory - see {@link FileLoader} * @param {String} property - see {@link FileLoader} * @param {Object} opt - see {@link FileLoader} * @since 1.0.0 */ loadToApp(directory: string | string[], property: string, opt?: Partial<FileLoaderOption>): void; /** * Load files using {@link ContextLoader} * @param {String|Array} directory - see {@link ContextLoader} * @param {String} property - see {@link ContextLoader} * @param {Object} opt - see {@link ContextLoader} * @since 1.0.0 */ loadToContext(directory: string | string[], property: string, opt?: Partial<ContextLoaderOption>): void; getTypeFiles(filename: string): string[]; resolveModule(filepath: string): string | undefined; FileLoader: FileLoader; ContextLoader: ContextLoader; // load methods protected loadConfig(): void; protected loadController(opt?: Partial<FileLoaderOption>): void; protected loadCustomLoader(): void; protected loadCustomApp(): void; protected loadCustomAgent(): void; protected loadAgentExtend(): void; protected loadApplicationExtend(): void; protected loadRequestExtend(): void; protected loadResponseExtend(): void; protected loadContextExtend(): void; protected loadHelperExtend(): void; protected loadMiddleware(opt?: Partial<FileLoaderOption>): void; protected loadPlugin(): void; protected loadRouter(): void; protected loadService(opt?: Partial<ContextLoaderOption>): void; }
the_stack
import { forRemoteCluster, KubeApi } from "../kube-api"; import { KubeJsonApi } from "../kube-json-api"; import { KubeObject } from "../kube-object"; import AbortController from "abort-controller"; import { delay } from "../../utils/delay"; import { PassThrough } from "stream"; import { ApiManager } from "../api-manager"; import type { FetchMock } from "jest-fetch-mock/types"; import { DeploymentApi, Ingress, IngressApi, Pod, PodApi } from "../endpoints"; import { getDiForUnitTesting } from "../../../renderer/getDiForUnitTesting"; import apiManagerInjectable from "../api-manager/manager.injectable"; import autoRegistrationInjectable from "../api-manager/auto-registration.injectable"; jest.mock("../api-manager"); const mockFetch = fetch as FetchMock; describe("forRemoteCluster", () => { let apiManager: jest.Mocked<ApiManager>; beforeEach(() => { const di = getDiForUnitTesting({ doGeneralOverrides: true }); apiManager = new ApiManager() as jest.Mocked<ApiManager>; di.override(apiManagerInjectable, () => apiManager); }); it("builds api client for KubeObject", async () => { const api = forRemoteCluster({ cluster: { server: "https://127.0.0.1:6443", }, user: { token: "daa", }, }, Pod); expect(api).toBeInstanceOf(KubeApi); }); it("builds api client for given KubeApi", async () => { const api = forRemoteCluster({ cluster: { server: "https://127.0.0.1:6443", }, user: { token: "daa", }, }, Pod, PodApi); expect(api).toBeInstanceOf(PodApi); }); it("calls right api endpoint", async () => { const api = forRemoteCluster({ cluster: { server: "https://127.0.0.1:6443", }, user: { token: "daa", }, }, Pod); mockFetch.mockResponse(async (request: any) => { expect(request.url).toEqual("https://127.0.0.1:6443/api/v1/pods"); return { body: "hello", }; }); expect.hasAssertions(); await api.list(); }); }); describe("KubeApi", () => { let request: KubeJsonApi; let apiManager: jest.Mocked<ApiManager>; beforeEach(() => { const di = getDiForUnitTesting({ doGeneralOverrides: true }); request = new KubeJsonApi({ serverAddress: `http://127.0.0.1:9999`, apiBase: "/api-kube", }); apiManager = new ApiManager() as jest.Mocked<ApiManager>; di.override(apiManagerInjectable, () => apiManager); di.inject(autoRegistrationInjectable); }); it("uses url from apiBase if apiBase contains the resource", async () => { mockFetch.mockResponse(async (request: any) => { if (request.url === "http://127.0.0.1:9999/api-kube/apis/networking.k8s.io/v1") { return { body: JSON.stringify({ resources: [{ name: "ingresses", }], }), }; } else if (request.url === "http://127.0.0.1:9999/api-kube/apis/extensions/v1beta1") { // Even if the old API contains ingresses, KubeApi should prefer the apiBase url return { body: JSON.stringify({ resources: [{ name: "ingresses", }], }), }; } else { return { body: JSON.stringify({ resources: [], }), }; } }); const apiBase = "/apis/networking.k8s.io/v1/ingresses"; const fallbackApiBase = "/apis/extensions/v1beta1/ingresses"; const kubeApi = new IngressApi({ request, objectConstructor: Ingress, apiBase, fallbackApiBases: [fallbackApiBase], checkPreferredVersion: true, }); await kubeApi.get({ name: "foo", namespace: "default", }); expect(kubeApi.apiPrefix).toEqual("/apis"); expect(kubeApi.apiGroup).toEqual("networking.k8s.io"); }); it("uses url from fallbackApiBases if apiBase lacks the resource", async () => { mockFetch.mockResponse(async (request: any) => { if (request.url === "http://127.0.0.1:9999/api-kube/apis/networking.k8s.io/v1") { return { body: JSON.stringify({ resources: [], }), }; } else if (request.url === "http://127.0.0.1:9999/api-kube/apis/extensions/v1beta1") { return { body: JSON.stringify({ resources: [{ name: "ingresses", }], }), }; } else { return { body: JSON.stringify({ resources: [], }), }; } }); const apiBase = "apis/networking.k8s.io/v1/ingresses"; const fallbackApiBase = "/apis/extensions/v1beta1/ingresses"; const kubeApi = new IngressApi({ request, objectConstructor: Object.assign(KubeObject, { apiBase }), kind: "Ingress", fallbackApiBases: [fallbackApiBase], checkPreferredVersion: true, }); await kubeApi.get({ name: "foo", namespace: "default", }); expect(kubeApi.apiPrefix).toEqual("/apis"); expect(kubeApi.apiGroup).toEqual("extensions"); }); describe("checkPreferredVersion", () => { it("registers with apiManager if checkPreferredVersion changes apiVersionPreferred", async () => { expect.hasAssertions(); const api = new IngressApi({ objectConstructor: Ingress, checkPreferredVersion: true, fallbackApiBases: ["/apis/extensions/v1beta1/ingresses"], request: { get: jest.fn() .mockImplementation((path: string) => { switch (path) { case "/apis/networking.k8s.io/v1": throw new Error("no"); case "/apis/extensions/v1beta1": return { resources: [ { name: "ingresses", }, ], }; case "/apis/extensions": return { preferredVersion: { version: "v1beta1", }, }; default: throw new Error("unknown path"); } }), } as Partial<KubeJsonApi> as KubeJsonApi, }); await (api as any).checkPreferredVersion(); expect(api.apiVersionPreferred).toBe("v1beta1"); expect(apiManager.registerApi).toBeCalledWith(api); }); it("registers with apiManager if checkPreferredVersion changes apiVersionPreferred with non-grouped apis", async () => { expect.hasAssertions(); const api = new PodApi({ objectConstructor: Pod, checkPreferredVersion: true, fallbackApiBases: ["/api/v1beta1/pods"], request: { get: jest.fn() .mockImplementation((path: string) => { switch (path) { case "/api/v1": throw new Error("no"); case "/api/v1beta1": return { resources: [ { name: "pods", }, ], }; case "/api": return { preferredVersion: { version: "v1beta1", }, }; default: throw new Error("unknown path"); } }), } as Partial<KubeJsonApi> as KubeJsonApi, }); await (api as any).checkPreferredVersion(); expect(api.apiVersionPreferred).toBe("v1beta1"); expect(apiManager.registerApi).toBeCalledWith(api); }); }); describe("patch", () => { let api: DeploymentApi; beforeEach(() => { api = new DeploymentApi({ request, }); }); it("sends strategic patch by default", async () => { expect.hasAssertions(); mockFetch.mockResponse(async request => { expect(request.method).toEqual("PATCH"); expect(request.headers.get("content-type")).toMatch("strategic-merge-patch"); expect(request.body?.toString()).toEqual(JSON.stringify({ spec: { replicas: 2 }})); return {}; }); await api.patch({ name: "test", namespace: "default" }, { spec: { replicas: 2 }, }); }); it("allows to use merge patch", async () => { expect.hasAssertions(); mockFetch.mockResponse(async request => { expect(request.method).toEqual("PATCH"); expect(request.headers.get("content-type")).toMatch("merge-patch"); expect(request.body?.toString()).toEqual(JSON.stringify({ spec: { replicas: 2 }})); return {}; }); await api.patch({ name: "test", namespace: "default" }, { spec: { replicas: 2 }, }, "merge"); }); it("allows to use json patch", async () => { expect.hasAssertions(); mockFetch.mockResponse(async request => { expect(request.method).toEqual("PATCH"); expect(request.headers.get("content-type")).toMatch("json-patch"); expect(request.body?.toString()).toEqual(JSON.stringify([{ op: "replace", path: "/spec/replicas", value: 2 }])); return {}; }); await api.patch({ name: "test", namespace: "default" }, [ { op: "replace", path: "/spec/replicas", value: 2 }, ], "json"); }); it("allows deep partial patch", async () => { expect.hasAssertions(); mockFetch.mockResponse(async request => { expect(request.method).toEqual("PATCH"); expect(request.headers.get("content-type")).toMatch("merge-patch"); expect(request.body?.toString()).toEqual(JSON.stringify({ metadata: { annotations: { provisioned: "true" }}})); return {}; }); await api.patch( { name: "test", namespace: "default" }, { metadata: { annotations: { provisioned: "true" }}}, "merge", ); }); }); describe("delete", () => { let api: PodApi; beforeEach(() => { api = new PodApi({ request, objectConstructor: Pod, }); }); it("sends correct request with empty namespace", async () => { expect.hasAssertions(); mockFetch.mockResponse(async request => { expect(request.method).toEqual("DELETE"); expect(request.url).toEqual("http://127.0.0.1:9999/api-kube/api/v1/pods/foo?propagationPolicy=Background"); return {}; }); await api.delete({ name: "foo", namespace: "" }); }); it("sends correct request without namespace", async () => { expect.hasAssertions(); mockFetch.mockResponse(async request => { expect(request.method).toEqual("DELETE"); expect(request.url).toEqual("http://127.0.0.1:9999/api-kube/api/v1/namespaces/default/pods/foo?propagationPolicy=Background"); return {}; }); await api.delete({ name: "foo" }); }); it("sends correct request with namespace", async () => { expect.hasAssertions(); mockFetch.mockResponse(async request => { expect(request.method).toEqual("DELETE"); expect(request.url).toEqual("http://127.0.0.1:9999/api-kube/api/v1/namespaces/kube-system/pods/foo?propagationPolicy=Background"); return {}; }); await api.delete({ name: "foo", namespace: "kube-system" }); }); it("allows to change propagationPolicy", async () => { expect.hasAssertions(); mockFetch.mockResponse(async request => { expect(request.method).toEqual("DELETE"); expect(request.url).toMatch("propagationPolicy=Orphan"); return {}; }); await api.delete({ name: "foo", namespace: "default", propagationPolicy: "Orphan" }); }); }); describe("watch", () => { let api: PodApi; let stream: PassThrough; beforeEach(() => { api = new PodApi({ request, objectConstructor: Pod, }); stream = new PassThrough(); }); afterEach(() => { stream.end(); stream.destroy(); }); it("sends a valid watch request", () => { const spy = jest.spyOn(request, "getResponse"); mockFetch.mockResponse(async () => { return { // needed for https://github.com/jefflau/jest-fetch-mock/issues/218 body: stream as unknown as string, }; }); api.watch({ namespace: "kube-system" }); expect(spy).toHaveBeenCalledWith("/api/v1/namespaces/kube-system/pods?watch=1&resourceVersion=", expect.anything(), expect.anything()); }); it("sends timeout as a query parameter", async () => { const spy = jest.spyOn(request, "getResponse"); mockFetch.mockResponse(async () => { return { // needed for https://github.com/jefflau/jest-fetch-mock/issues/218 body: stream as unknown as string, }; }); api.watch({ namespace: "kube-system", timeout: 60 }); expect(spy).toHaveBeenCalledWith("/api/v1/namespaces/kube-system/pods?watch=1&resourceVersion=", { query: { timeoutSeconds: 60 }}, expect.anything()); }); it("aborts watch using abortController", async (done) => { const spy = jest.spyOn(request, "getResponse"); mockFetch.mockResponse(async request => { request.signal.addEventListener("abort", () => { done(); }); return { // needed for https://github.com/jefflau/jest-fetch-mock/issues/218 body: stream as unknown as string, }; }); const abortController = new AbortController(); api.watch({ namespace: "kube-system", timeout: 60, abortController, }); expect(spy).toHaveBeenCalledWith("/api/v1/namespaces/kube-system/pods?watch=1&resourceVersion=", { query: { timeoutSeconds: 60 }}, expect.anything()); await delay(100); abortController.abort(); }); describe("retries", () => { it("if request ended", (done) => { const spy = jest.spyOn(request, "getResponse"); jest.spyOn(stream, "on").mockImplementation((event: string | symbol, callback: Function) => { // End the request in 100ms. if (event === "end") { setTimeout(() => { callback(); }, 100); } return stream; }); // we need to mock using jest as jest-fetch-mock doesn't support mocking the body completely jest.spyOn(global, "fetch").mockImplementation(async () => { return { ok: true, body: stream as never, } as Partial<Response> as Response; }); api.watch({ namespace: "kube-system", }); expect(spy).toHaveBeenCalledTimes(1); setTimeout(() => { expect(spy).toHaveBeenCalledTimes(2); done(); }, 2000); }); it("if request not closed after timeout", (done) => { const spy = jest.spyOn(request, "getResponse"); mockFetch.mockResponse(async () => { return { // needed for https://github.com/jefflau/jest-fetch-mock/issues/218 body: stream as unknown as string, }; }); const timeoutSeconds = 1; api.watch({ namespace: "kube-system", timeout: timeoutSeconds, }); expect(spy).toHaveBeenCalledTimes(1); setTimeout(() => { expect(spy).toHaveBeenCalledTimes(2); done(); }, timeoutSeconds * 1000 * 1.2); }); it("retries only once if request ends and timeout is set", (done) => { const spy = jest.spyOn(request, "getResponse"); jest.spyOn(stream, "on").mockImplementation((event: string | symbol, callback: Function) => { // End the request in 100ms. if (event === "end") { setTimeout(() => { callback(); }, 100); } return stream; }); // we need to mock using jest as jest-fetch-mock doesn't support mocking the body completely jest.spyOn(global, "fetch").mockImplementation(async () => { return { ok: true, body: stream as never, } as Partial<Response> as Response; }); const timeoutSeconds = 0.5; api.watch({ namespace: "kube-system", timeout: timeoutSeconds, }); expect(spy).toHaveBeenCalledTimes(1); setTimeout(() => { expect(spy).toHaveBeenCalledTimes(2); done(); }, 2000); }); afterEach(() => { jest.clearAllMocks(); }); }); }); describe("create", () => { let api: PodApi; beforeEach(() => { api = new PodApi({ request, objectConstructor: Pod, }); }); it("should add kind and apiVersion", async () => { expect.hasAssertions(); mockFetch.mockResponse(async request => { expect(request.method).toEqual("POST"); expect(JSON.parse(String(request.body))).toEqual({ kind: "Pod", apiVersion: "v1", metadata: { name: "foobar", namespace: "default", }, spec: { containers: [ { name: "web", image: "nginx", ports: [ { name: "web", containerPort: 80, protocol: "TCP", }, ], }, ], }, }); return {}; }); await api.create({ name: "foobar", namespace: "default", }, { spec: { containers: [ { name: "web", image: "nginx", ports: [ { name: "web", containerPort: 80, protocol: "TCP", }, ], }, ], }, }); }); it("doesn't override metadata.labels", async () => { expect.hasAssertions(); mockFetch.mockResponse(async request => { expect(request.method).toEqual("POST"); expect(JSON.parse(String(request.body))).toEqual({ kind: "Pod", apiVersion: "v1", metadata: { name: "foobar", namespace: "default", labels: { foo: "bar", }, }, }); return {}; }); await api.create({ name: "foobar", namespace: "default", }, { metadata: { labels: { foo: "bar", }, }, }); }); }); describe("update", () => { let api: PodApi; beforeEach(() => { api = new PodApi({ request, objectConstructor: Pod, }); }); it("doesn't override metadata.labels", async () => { expect.hasAssertions(); mockFetch.mockResponse(async request => { expect(request.method).toEqual("PUT"); expect(JSON.parse(String(request.body))).toEqual({ metadata: { name: "foobar", namespace: "default", labels: { foo: "bar", }, }, }); return {}; }); await api.update({ name: "foobar", namespace: "default", }, { metadata: { labels: { foo: "bar", }, }, }); }); }); });
the_stack
/** * @license Copyright © 2013 onwards, Andrew Whewell * All rights reserved. * * Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @fileoverview Abstracts away details of a report's criteria. */ namespace VRS { /* * Global options */ export var globalOptions: GlobalOptions = VRS.globalOptions || {}; VRS.globalOptions.reportMaximumCriteria = VRS.globalOptions.reportMaximumCriteria !== undefined ? VRS.globalOptions.reportMaximumCriteria : 15; // The maximum number of criteria that can be passed to a report. VRS.globalOptions.reportFindAllPermutationsOfCallsign = VRS.globalOptions.reportFindAllPermutationsOfCallsign !== undefined ? VRS.globalOptions.reportFindAllPermutationsOfCallsign : false; // True if all permutations of a callsign should be found. /** * The settings to use when creating new instances of ReportFilterPropertyHandler */ export interface ReportFilterPropertyHandler_Settings extends FilterPropertyHandler_Settings { property: ReportFilterPropertyEnum; } /** * The filter property handler to use when requesting reports. */ export class ReportFilterPropertyHandler extends FilterPropertyHandler { constructor(settings: ReportFilterPropertyHandler_Settings) { super($.extend({ propertyEnumObject: VRS.ReportFilterProperty }, settings)); } } /* * Report filters */ export var reportFilterPropertyHandlers: { [index: string /* ReportFilterPropertyEnum */]: ReportFilterPropertyHandler } = VRS.reportFilterPropertyHandlers || {}; VRS.reportFilterPropertyHandlers[VRS.ReportFilterProperty.Callsign] = new VRS.ReportFilterPropertyHandler({ property: VRS.ReportFilterProperty.Callsign, type: VRS.FilterPropertyType.TextMatch, labelKey: 'Callsign', serverFilterName: 'call-', inputWidth: VRS.InputWidth.NineChar, defaultCondition: VRS.FilterCondition.Equals }); VRS.reportFilterPropertyHandlers[VRS.ReportFilterProperty.Country] = new VRS.ReportFilterPropertyHandler({ property: VRS.ReportFilterProperty.Country, type: VRS.FilterPropertyType.TextMatch, labelKey: 'Country', serverFilterName: 'cou-', inputWidth: VRS.InputWidth.Long, defaultCondition: VRS.FilterCondition.Equals }); VRS.reportFilterPropertyHandlers[VRS.ReportFilterProperty.Date] = new VRS.ReportFilterPropertyHandler({ property: VRS.ReportFilterProperty.Date, type: VRS.FilterPropertyType.DateRange, labelKey: 'Date', serverFilterName: 'date-', inputWidth: VRS.InputWidth.EightChar }); VRS.reportFilterPropertyHandlers[VRS.ReportFilterProperty.HadEmergency] = new VRS.ReportFilterPropertyHandler({ property: VRS.ReportFilterProperty.HadEmergency, type: VRS.FilterPropertyType.OnOff, labelKey: 'HadEmergency', serverFilterName: 'emg-' }); VRS.reportFilterPropertyHandlers[VRS.ReportFilterProperty.FirstAltitude] = new VRS.ReportFilterPropertyHandler({ property: VRS.ReportFilterProperty.FirstAltitude, type: VRS.FilterPropertyType.NumberRange, labelKey: 'FirstAltitude', serverFilterName: 'falt-' }); VRS.reportFilterPropertyHandlers[VRS.ReportFilterProperty.Icao] = new VRS.ReportFilterPropertyHandler({ property: VRS.ReportFilterProperty.Icao, type: VRS.FilterPropertyType.TextMatch, labelKey: 'Icao', serverFilterName: 'icao-', inputWidth: VRS.InputWidth.SixChar, defaultCondition: VRS.FilterCondition.Equals }); VRS.reportFilterPropertyHandlers[VRS.ReportFilterProperty.IsMilitary] = new VRS.ReportFilterPropertyHandler({ property: VRS.ReportFilterProperty.IsMilitary, type: VRS.FilterPropertyType.OnOff, labelKey: 'IsMilitary', serverFilterName: 'mil-' }); VRS.reportFilterPropertyHandlers[VRS.ReportFilterProperty.LastAltitude] = new VRS.ReportFilterPropertyHandler({ property: VRS.ReportFilterProperty.LastAltitude, type: VRS.FilterPropertyType.NumberRange, labelKey: 'LastAltitude', serverFilterName: 'lalt-' }); VRS.reportFilterPropertyHandlers[VRS.ReportFilterProperty.ModelIcao] = new VRS.ReportFilterPropertyHandler({ property: VRS.ReportFilterProperty.ModelIcao, type: VRS.FilterPropertyType.TextMatch, labelKey: 'ModelIcao', serverFilterName: 'typ-', inputWidth: VRS.InputWidth.SixChar, defaultCondition: VRS.FilterCondition.Equals }); VRS.reportFilterPropertyHandlers[VRS.ReportFilterProperty.Operator] = new VRS.ReportFilterPropertyHandler({ property: VRS.ReportFilterProperty.Operator, type: VRS.FilterPropertyType.TextMatch, labelKey: 'Operator', serverFilterName: 'op-', inputWidth: VRS.InputWidth.Long, defaultCondition: VRS.FilterCondition.Contains }); VRS.reportFilterPropertyHandlers[VRS.ReportFilterProperty.Registration] = new VRS.ReportFilterPropertyHandler({ property: VRS.ReportFilterProperty.Registration, type: VRS.FilterPropertyType.TextMatch, labelKey: 'Registration', serverFilterName: 'reg-', inputWidth: VRS.InputWidth.SixChar, defaultCondition: VRS.FilterCondition.Equals }); VRS.reportFilterPropertyHandlers[VRS.ReportFilterProperty.Species] = new VRS.ReportFilterPropertyHandler({ property: VRS.ReportFilterProperty.Species, type: VRS.FilterPropertyType.EnumMatch, getEnumValues: function() { return [ new VRS.ValueText({ value: VRS.Species.Amphibian, textKey: 'Amphibian' }), new VRS.ValueText({ value: VRS.Species.Gyrocopter, textKey: 'Gyrocopter' }), new VRS.ValueText({ value: VRS.Species.Helicopter, textKey: 'Helicopter' }), new VRS.ValueText({ value: VRS.Species.LandPlane, textKey: 'LandPlane' }), new VRS.ValueText({ value: VRS.Species.SeaPlane, textKey: 'SeaPlane' }), new VRS.ValueText({ value: VRS.Species.Tiltwing, textKey: 'Tiltwing' }), new VRS.ValueText({ value: VRS.Species.GroundVehicle, textKey: 'GroundVehicle' }), new VRS.ValueText({ value: VRS.Species.Tower, textKey: 'RadioMast' }) ]; }, labelKey: 'Species', serverFilterName: 'spc-' }); VRS.reportFilterPropertyHandlers[VRS.ReportFilterProperty.WakeTurbulenceCategory] = new VRS.ReportFilterPropertyHandler({ property: VRS.ReportFilterProperty.WakeTurbulenceCategory, type: VRS.FilterPropertyType.EnumMatch, getEnumValues: function () { return [ new VRS.ValueText({ value: VRS.WakeTurbulenceCategory.Light, textKey: 'WtcLight' }), new VRS.ValueText({ value: VRS.WakeTurbulenceCategory.Medium, textKey: 'WtcMedium' }), new VRS.ValueText({ value: VRS.WakeTurbulenceCategory.Heavy, textKey: 'WtcHeavy' }) ]; }, labelKey: 'WakeTurbulenceCategory', serverFilterName: 'wtc-' }); /** * Brings together a report filter property and a value/condition object to describe a criteria in the report. */ export class ReportFilter extends Filter { constructor(reportFilterProperty: ReportFilterPropertyEnum, valueCondition: ValueCondition) { super({ property: reportFilterProperty, valueCondition: valueCondition, propertyEnumObject: VRS.ReportFilterProperty, filterPropertyHandlers: VRS.reportFilterPropertyHandlers, cloneCallback: function(property, valueCondition) { return new VRS.ReportFilter(property, valueCondition); } }); } } /** * A helper class that can ease the tedium of creating report filter objects, serialising them etc. */ export class ReportFilterHelper extends FilterHelper { constructor() { super({ propertyEnumObject: VRS.ReportFilterProperty, filterPropertyHandlers: VRS.reportFilterPropertyHandlers, createFilterCallback: function(propertyHandler, valueCondition) { return new VRS.ReportFilter(propertyHandler.property, valueCondition); } }); } } export var reportFilterHelper = new VRS.ReportFilterHelper(); /** * The settings to use when creating a new instance of ReportCriteria. */ export interface ReportCriteria_Settings { /** * A unique name that distinguishes this object from other instances of the same class. */ name: string; /** * The unit display preferences to use when applying criteria. */ unitDisplayPreferences?: UnitDisplayPreferences; } /** * The settings that a ReportCriteria object can persist between sessions. */ export interface ReportCriteria_SaveState { findAllPermutationsOfCallsign: boolean; } /** * Collects together a bunch of report filters which together describe all of the criteria for a report. */ export class ReportCriteria implements ISelfPersist<ReportCriteria_SaveState> { private _Dispatcher = new VRS.EventHandler({ name: 'VRS.ReportCriteria' }); private _Events = { criteriaChanged: 'criteriaChanged' }; private _Settings: ReportCriteria_Settings; private _Filters: ReportFilter[] = []; // The list of report filters that represent each of the criteria to apply to the report. private _FindAllPermutationsOfCallsign: boolean = VRS.globalOptions.reportFindAllPermutationsOfCallsign; constructor(settings: ReportCriteria_Settings) { if(!settings) throw 'You must supply a settings object'; if(!settings.name) throw 'You must supply a name'; this._Settings = settings; } /** * Returns the name of the criteria. */ getName() : string { return this._Settings.name; } /** * Gets a value indicating that the server should search for all permutations of a callsign supplied as criteria. */ getFindAllPermutationsOfCallsign() : boolean { return this._FindAllPermutationsOfCallsign; } setFindAllPermutationsOfCallsign(value: boolean) { this._FindAllPermutationsOfCallsign = value; } /** * Gets a value indicating that some criteria has been entered for the report. */ hasCriteria() : boolean { return !!this._Filters.length; } /** * Returns true if the criteria constrains the report to displaying flights for a single aircraft. */ isForSingleAircraft() : boolean { var result = false; var length = this._Filters.length; for(var i = 0;!result && i < length;++i) { var filter = this._Filters[i]; switch(filter.getProperty()) { case VRS.ReportFilterProperty.Registration: case VRS.ReportFilterProperty.Icao: // Neither of these are 100% guaranteed to identify a single aircraft - an aircraft can be // reregistered so more than one aircraft can have the same registration or ICAO over their // lifetimes. But for our purposes it'll be fine. result = filter.getValueCondition().getCondition() === VRS.FilterCondition.Equals; if(result) { result = !!(<OneValueCondition>filter.getValueCondition()).getValue(); } break; } } return result; } /** * Raised when new criteria are added or removed. Is **NOT** raised when the criteria values are changed. So basically, * gets raised when they click 'Add Criteria' or 'Remove Criteria', not when they change the value for an altitude * criteria (or any other kind). */ hookCriteriaChanged(callback: () => void, forceThis?: Object) : IEventHandle { return this._Dispatcher.hook(this._Events.criteriaChanged, callback, forceThis); } unhook(hookResult: IEventHandle) { this._Dispatcher.unhook(hookResult); } /** * Saves the current state of the object. */ saveState() { VRS.configStorage.save(this.persistenceKey(), this.createSettings()); } /** * Loads the previously saved state of the object or the current state if it's never been saved. */ loadState() : ReportCriteria_SaveState { var savedSettings = VRS.configStorage.load(this.persistenceKey(), {}); return $.extend(this.createSettings(), savedSettings); } /** * Applies a previously saved state to the object. */ applyState(settings: ReportCriteria_SaveState) { this.setFindAllPermutationsOfCallsign(settings.findAllPermutationsOfCallsign); } /** * Loads and then applies a previousy saved state to the object. */ loadAndApplyState() { this.applyState(this.loadState()); } /** * Returns the key under which the state will be saved. */ private persistenceKey() : string { return 'vrsReportCriteria-' + this.getName(); } /** * Creates the saved state object. */ private createSettings() : ReportCriteria_SaveState { return { findAllPermutationsOfCallsign: this.getFindAllPermutationsOfCallsign() }; } /** * Creates the option pane that the user can employ to build up the criteria for the report. */ createOptionPane(displayOrder: number) : OptionPane { var pane = new VRS.OptionPane({ name: 'reportFilterOptionPane', titleKey: 'Criteria', displayOrder: displayOrder }); pane.addField(new VRS.OptionFieldCheckBox({ name: 'findAllPermutations', labelKey: 'FindAllPermutationsOfCallsign', getValue: () => this._FindAllPermutationsOfCallsign, setValue: (value) => this._FindAllPermutationsOfCallsign = value, saveState: () => this.saveState() })); var panesTypeSettings = VRS.reportFilterHelper.addConfigureFiltersListToPane({ pane: pane, filters: this._Filters, saveState: $.noop, maxFilters: VRS.globalOptions.reportMaximumCriteria, allowableProperties: VRS.enumHelper.getEnumValues(VRS.ReportFilterProperty), addFilter: (newFilter, paneField) => { var filter = this.addFilter(newFilter); if(filter) { paneField.addPane(filter.createOptionPane($.noop)); } }, addFilterButtonLabel: 'AddCriteria', onlyUniqueFilters: true, isAlreadyInUse: (reportFilterProperty) => { return VRS.reportFilterHelper.isFilterInUse(this._Filters, reportFilterProperty); } }); panesTypeSettings.hookPaneRemoved(this.filterPaneRemoved, this); return pane; } /** * Adds a new filter to the object. * @param {VRS.ReportFilter|VRS.ReportFilterProperty} filterOrPropertyId Either a filter or a VRS.ReportFilterProperty property name. * @returns {VRS.ReportFilter} Either the filter passed in or the filter built from the property name. */ addFilter(filterOrPropertyId: ReportFilter | ReportFilterPropertyEnum) : ReportFilter { var filter = <ReportFilter>filterOrPropertyId; if(!(filter instanceof VRS.ReportFilter)) { filter = VRS.reportFilterHelper.createFilter(<string>filterOrPropertyId); } if(VRS.reportFilterHelper.isFilterInUse(this._Filters, filter.getProperty())) { filter = null; } else { this._Filters.push(filter); this._Dispatcher.raise(this._Events.criteriaChanged); } return filter; } /** * Removes the filter at the index passed across. */ private filterPaneRemoved(pane: OptionPane, index: number) { this.removeFilterAt(index); } /** * Removes the filter at the index passed across. */ removeFilterAt(index: number) { this._Filters.splice(index, 1); this._Dispatcher.raise(this._Events.criteriaChanged); } /** * Constructs the list of filters held by the object from parameters passed across on the query string. */ populateFromQueryString() { this._Filters = []; var pageUrl = $.url(); $.each(VRS.reportFilterPropertyHandlers, (propertyIdx, propertyHandler) => { var typeHandler = propertyHandler.getFilterPropertyTypeHandler(); if(typeHandler && propertyHandler.serverFilterName) { $.each(typeHandler.getConditions(), (typeIdx, condition) => { this.extractFilterFromQueryString(pageUrl, propertyHandler, typeHandler, condition.condition, condition.reverseCondition); }); } }); var allCallsignPermutations = pageUrl.param('callPerms'); if(allCallsignPermutations) { this.setFindAllPermutationsOfCallsign(allCallsignPermutations !== '0'); } } /** * Constructs a query string object for the list of filters held by the object. The query string can be used to * create a link to a report, it is the encoding of filters that can be decoded by populateFromQueryString. */ createQueryString(useRelativeDates: boolean) : Object { var result = {}; var now = new Date(); var today = new Date(now.getFullYear(), now.getMonth(), now.getDate()); var getRelativeDate = function(dateValue) { return !dateValue ? undefined : Math.floor((dateValue.getTime() - today.getTime()) / 86400000); }; if(this._Filters.length) { $.each(this._Filters, (idx, filter) => { var valueCondition = filter.getValueCondition(); var oneValueCondition = <OneValueCondition>valueCondition; var twoValueCondition = <TwoValueCondition>valueCondition; switch(valueCondition.getCondition()) { case VRS.FilterCondition.Contains: this.doAddQueryStringFromFilter(result, filter, oneValueCondition.getValue(), 'C'); break; case VRS.FilterCondition.Ends: this.doAddQueryStringFromFilter(result, filter, oneValueCondition.getValue(), 'E'); break; case VRS.FilterCondition.Equals: this.doAddQueryStringFromFilter(result, filter, oneValueCondition.getValue(), 'Q'); break; case VRS.FilterCondition.Starts: this.doAddQueryStringFromFilter(result, filter, oneValueCondition.getValue(), 'S'); break; case VRS.FilterCondition.Between: var low = twoValueCondition.getValue1(); var high = twoValueCondition.getValue2(); var valueIsString = filter.getProperty() === VRS.ReportFilterProperty.Date && useRelativeDates; if(valueIsString) { low = getRelativeDate(low); high = getRelativeDate(high); } if(low !== undefined) this.doAddQueryStringFromFilter(result, filter, low, 'L', valueIsString); if(high !== undefined) this.doAddQueryStringFromFilter(result, filter, high, 'U', valueIsString); break; default: throw 'Not implemented ' + valueCondition.getCondition(); } }); } return result; } /** * Searches for a query string for the property and condition passed across and, if one is present, parses the * criteria into a filter and returns it. If there is no query string parameter for the property and condition * then null is returned. */ private extractFilterFromQueryString(pageUrl: purl.Url, propertyHandler: ReportFilterPropertyHandler, typeHandler: FilterPropertyTypeHandler, condition: FilterConditionEnum, reverseCondition: boolean) { switch(condition) { case VRS.FilterCondition.Contains: this.doExtractFilterFromQueryString(null, pageUrl, propertyHandler, typeHandler, condition, reverseCondition, 'C'); break; case VRS.FilterCondition.Ends: this.doExtractFilterFromQueryString(null, pageUrl, propertyHandler, typeHandler, condition, reverseCondition, 'E'); break; case VRS.FilterCondition.Equals: this.doExtractFilterFromQueryString(null, pageUrl, propertyHandler, typeHandler, condition, reverseCondition, 'Q'); break; case VRS.FilterCondition.Starts: this.doExtractFilterFromQueryString(null, pageUrl, propertyHandler, typeHandler, condition, reverseCondition, 'S'); break; case VRS.FilterCondition.Between: var filter = this.doExtractFilterFromQueryString(null, pageUrl, propertyHandler, typeHandler, condition, reverseCondition, 'L'); this.doExtractFilterFromQueryString(filter, pageUrl, propertyHandler, typeHandler, condition, reverseCondition, 'U'); break; default: throw 'Not implemented ' + condition; } } /** * Builds the name of the query string parameter, fetches its value and parses it into a filter. */ private doExtractFilterFromQueryString( filter: ReportFilter, pageUrl: purl.Url, propertyHandler: ReportFilterPropertyHandler, typeHandler: FilterPropertyTypeHandler, condition: FilterConditionEnum, reverseCondition: boolean, nameSuffix: string ) : ReportFilter { var result = filter; var name = this.getFilterName(propertyHandler, nameSuffix, reverseCondition); var text = pageUrl.param(name); var value = typeHandler.parseString(text); if(value !== undefined ) { if(!result) { result = VRS.reportFilterHelper.createFilter(propertyHandler.property); this._Filters.push(result); this._Dispatcher.raise(this._Events.criteriaChanged); } var valueCondition = result.getValueCondition(); valueCondition.setCondition(condition); valueCondition.setReverseCondition(reverseCondition); switch(condition) { case VRS.FilterCondition.Between: switch(nameSuffix) { case 'L': (<TwoValueCondition>valueCondition).setValue1(value); break; case 'U': (<TwoValueCondition>valueCondition).setValue2(value); break; default: throw 'Not implemented ' + nameSuffix; } break; default: (<OneValueCondition>valueCondition).setValue(value); break; } } return result; } /** * Adds the value for a filter to the queryStringParams object passed across. */ private doAddQueryStringFromFilter(queryStringParams: Object, filter: ReportFilter, value: any, nameSuffix: string, valueIsString?: boolean) { var condition = filter.getValueCondition(); var propertyHandler = filter.getPropertyHandler(); var typeHandler = propertyHandler.getFilterPropertyTypeHandler(); var reverseCondition = condition.getReverseCondition(); var name = this.getFilterName(propertyHandler, nameSuffix, reverseCondition); var stringValue = valueIsString ? value : typeHandler.toQueryString(value); queryStringParams[name] = stringValue; } /** * Returns the name of a query string field. * @param {VRS.ReportFilterPropertyHandler} propertyHandler * @param {string} nameSuffix * @param {boolean} reverseCondition * @returns {string} */ private getFilterName(propertyHandler: ReportFilterPropertyHandler, nameSuffix: string, reverseCondition: boolean) : string { return propertyHandler.serverFilterName + nameSuffix + (reverseCondition ? 'N' : ''); } /** * Extends the parameters object that is passed to the server when a page of the report is fetched. */ addToQueryParameters(params: any) { VRS.reportFilterHelper.addToQueryParameters(this._Filters, params, this._Settings.unitDisplayPreferences); if(this.getFindAllPermutationsOfCallsign()) { params.altCall = 1; } } } }
the_stack
import * as elasticsearch from 'elasticsearch'; import type * as cloudformation from '@aws-cdk/aws-cloudformation'; import type * as es from '@aws-cdk/aws-elasticsearch'; import type * as iam from '@aws-cdk/aws-iam'; import type * as cdk from '@aws-cdk/core'; import { any, AnyShape, array, boolean, Enum, integer, isOptional, map, Mapper, Meta, number, optional, Shape, ShapeGuards, string, StringShape, Type, TypeShape, Value } from '@punchcard/shape'; import { Json } from '@punchcard/shape-json'; import { call, DataSourceBindCallback, DataSourceType, VExpression } from '../appsync'; import { VTL, vtl } from '../appsync/lang/vtl'; import { VList, VNothing, VObject, VString, VUnion } from '../appsync/lang/vtl-object'; import { Dependency } from '../core'; import { Build } from '../core/build'; import { CDK } from '../core/cdk'; import { Construct, Scope } from '../core/construct'; import { Resource } from '../core/resource'; import { Run } from '../core/run'; import * as Lambda from '../lambda'; import { sink } from '../util'; import { Domain } from './es-domain'; export class IndexSettings extends Type({ number_of_shards: integer, number_of_replicas: optional(integer), auto_expand_replicas: optional(boolean) }) {} export class IndexResourceProps extends Type({ IndexName: string, Mappings: any, Settings: IndexSettings }) {} export const ResourceRequestType = Enum({ Create: 'Create', Delete: 'Delete', Update: 'Update', }); export class IndexResourceRequest extends Type({ ServiceToken: string, /** * A required custom resource provider-defined physical ID that is unique for that provider. */ PhysicalResourceId: string, /** * Type of Request (`Create`, `Update`, `Delete`). */ RequestType: ResourceRequestType, /** * A unique ID for the request. */ RequestId: string, /** * The response URL identifies a presigned S3 bucket that receives responses from the custom resource provider to AWS CloudFormation. */ ResponseURL: string, /** * The template developer-chosen resource type of the custom resource in the AWS CloudFormation template. Custom resource type names can be up to 60 characters long and can include alphanumeric and the following characters: _@-. */ ResourceType: string, /** * The template developer-chosen name (logical ID) of the custom resource in the AWS CloudFormation template. */ LogicalResourceId: string, /** * The Amazon Resource Name (ARN) that identifies the stack that contains the custom resource. */ StackId: string, /** * The new resource property values that are declared by the template developer in the updated AWS CloudFormation template. */ ResourceProperties: IndexResourceProps, /** * The resource property values that were previously declared by the template developer in the AWS CloudFormation template. * * Only populated during an `Update`. */ OldResourceProperties: optional(IndexResourceProps) }) {} export class IndexResourceResponse extends Type({ indexName: string }) {} export type _ID<T extends TypeShape> = { [k in keyof T['Members']]: T['Members'] extends StringShape ? k : never }[keyof T['Members']]; export interface IndexProps<T extends TypeShape, ID extends keyof T['Members']> { indexName: string, mappings: T, _id: ID, settings: IndexSettings; } export class Index<T extends TypeShape, ID extends keyof T['Members']> implements Resource<cloudformation.CustomResource> { public readonly resource: Build<cloudformation.CustomResource>; public readonly indexName: string; public readonly mappings: T; public readonly _id: ID; constructor(scope: Scope, id: string, public readonly domain: Domain, props: IndexProps<T, ID>) { this.indexName = props.indexName; this.mappings = props.mappings; this._id = props._id; this.resource = Build.concat(Scope.resolve(scope), CDK, domain.indexResourceProvider).map(([scope, cdk, provider]) => new cdk.cloudformation.CustomResource(scope, id, { provider, resourceType: 'Custom::ElasticSearchIndex', properties: { IndexName: props.indexName, Mappings: toMappings(props.mappings), Settings: props.settings } })) ; } public readWriteAccess(): Dependency<IndexClient<T, ID>> { return this.access({ actions: [...readActions, ...writeActions], }); } public readAccess(): Dependency<IndexClient<T, ID>> { return this.access({ actions: readActions, }); } public writeAccess(): Dependency<IndexClient<T, ID>> { return this.access({ actions: writeActions, }); } private access(props: { actions: string[]; paths?: string[] }): Dependency<IndexClient<T, ID>> { const access = this.domain.access(props); return { install: access.install, bootstrap: access.bootstrap.map(bootstrap => async (namespace, cache) => new IndexClient<T, ID>( await bootstrap(namespace, cache), this.indexName, this.mappings, this._id )) }; } public *search(body: any): VTL<{ scrollID: VUnion<VString | VNothing> hits: VList<VObject.Of<T>> }> { const request = VObject.fromExpr(any, VExpression.json({ version: '2017-02-28', operation: 'GET', path: `/${this.indexName}/_search`, params: { body } })); /* Type({ _index: string, _type: string, _id: string, _score: number, _source: this.mappings }) */ class SearchResponse extends Type({ _scroll_id: optional(string), hits: Type({ hits: array(map(any)) }) }) {} const response = yield* call( this.dataSourceProps(CDK.map(({iam}) => (domain, role) => { role.addToPolicy(new iam.PolicyStatement({ actions: readActions, effect: iam.Effect.ALLOW, resources: [ `${domain.attrArn}/${this.indexName}/*` ] })); })), request, SearchResponse ); const mappings = this.mappings; const hits = yield* vtl(array(this.mappings))`[]`; yield* response.hits.hits.forEach(function*(item) { yield* hits.push(item.get('_source').as(mappings) as any); }); return { scrollID: response._scroll_id, hits }; } /** * Return an AppSync DataSource for this Table. * @param props */ public dataSourceProps(grant: Build<(domain: es.CfnDomain, role: iam.IRole) => void>, props?: { description?: string; serviceRole?: Build<iam.Role>; }): Build<DataSourceBindCallback> { return Build.concat( CDK, this.domain.resource, props?.serviceRole || Build.of(undefined), grant ).map(([cdk, domain, serviceRole, grant]) => (scope: cdk.Construct, id: string) => { const role = serviceRole || new cdk.iam.Role(scope, `${id}:Role`, { assumedBy: new cdk.iam.ServicePrincipal('appsync') }); grant(domain, role); return { type: DataSourceType.AMAZON_ELASTICSEARCH, elasticsearchConfig: { awsRegion: domain.stack.region, endpoint: `https://${domain.getAtt('DomainEndpoint').toString()}`, }, description: props?.description, // TODO: are we sure we want to auto-create an IAM Role? serviceRoleArn: role.roleArn }; }); } } const readActions = [ 'es:ESHttpGet', 'es:ESHttpPost', ]; const writeActions = [ 'es:ESHttpDelete', 'es:ESHttpPost', 'es:ESHttpPut', ]; export class IndexClient<T extends TypeShape, ID extends keyof T['Members']> { public readonly mapper: Mapper<Value.Of<T>, Json.Of<T>>; constructor( public readonly client: elasticsearch.Client, public readonly indexName: string, public readonly mappings: T, public readonly _id: ID ) { this.mapper = Json.mapper(this.mappings, { // options? }); } /** * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html */ public async search(props: SearchRequest): Promise<SearchResponse<Value.Of<T>>> { const response: elasticsearch.SearchResponse<Json.Of<T>> = await this.client.search({ scroll: props.scroll, body: props.body }); return this.parseHits(response); } public async scroll(request: ScrollRequest): Promise<SearchResponse<Value.Of<T>>> { const response: elasticsearch.SearchResponse<Json.Of<T>> = await this.client.scroll({ scrollId: request.scrollId, scroll: request.scroll }); return this.parseHits(response); } private parseHits(response: elasticsearch.SearchResponse<Json.Of<T>>) { if (!response.timed_out) { return { hits: response.hits.hits.map((hit: any) => { console.log('hit', hit); const value = this.mapper.read(hit._source); console.log('hit-value', value); return value; }) as Value.Of<T>[], scrollId: response._scroll_id }; } else { const error = new Error('response timed out'); console.error(error); throw error; } } public async index(...values: Value.Of<T>[]): Promise<void> { const body = values.map(value => { const json = this.mapper.write(value) as any; let _id: string | undefined = json[this._id]; _id = json[this._id]; if (typeof _id !== 'string') { console.error('_id', this._id, json); throw new Error(`_id '${this._id}' field must be a string, was '${typeof _id}'.`); } return [{ index: { _index: this.indexName, _id } }, json]; }).reduce((a, b) => a.concat(b)); return await sink(body, async (values) => { const response: BulkResponse = await this.client.bulk({ refresh: 'wait_for', body }); if (response.errors) { return response.items.map((item, i) => { console.error(item); return body[i]; }); // need to redrive erros } return []; }, { retry: { attemptsLeft: 3, backoffMs: 100, maxBackoffMs: 10000 }, strictOrdering: false }, 10000); } } export interface ScrollRequest { scroll: string; scrollId: string; } export interface SearchRequest { scroll?: string; body: any; } export interface SearchResponse<T> { scrollId?: string; hits: Value.Of<T>[]; } /** * The bulk API’s response contains the individual results of each operation in the request, * returned in the order submitted. The success or failure of an individual operation does * not affect other operations in the request. * * @see https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-bulk.html */ interface BulkResponse { /** * How long, in milliseconds, it took to process the bulk request. */ took: number; /** * If true, one or more of the operations in the bulk request did not complete successfully */ errors: boolean; items: { /** * The parameter name is an action associated with the operation. Possible values are * `create`, `delete`, `index`, and `update`. * * The parameter value is an object that contains information for the associated operation. */ [action: string]: { /** * The index name or alias associated with the operation. */ _index: string; /** * The document type associated with the operation. Elasticsearch indices now support a * single document type: _doc. See Removal of mapping types. */ _type: string; /** * The document ID associated with the operation. */ _id: number; /** * The document version associated with the operation. The document version is incremented * each time the document is updated. * * This parameter is only returned for successful actions */ _version: number; /** * Result of the operation. Successful values are `created`, `deleted`, and `updated`. * * This parameter is only returned for successful operations. */ result: 'created' | 'deleted' | 'updated'; /** * Contains shard information for the operation. * * This parameter is only returned for successful operations. */ _shards: { /** * Number of shards the operation attempted to execute on. */ total: number; /** * Number of shards the operation succeeded on. */ successful: number; /** * Number of shards the operation attempted to execute on but failed */ failed: number; }; /** * The sequence number assigned to the document for the operation. Sequence numbers are * used to ensure an older version of a document doesn’t overwrite a newer version. See * [Optimistic concurrency control](https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html#optimistic-concurrency-control-index). * * This parameter is only returned for successful operations. */ _seq_no: number; /** * The primary term assigned to the document for the operation. See * [Optimistic concurrency control](https://www.elastic.co/guide/en/elasticsearch/reference/current/docs-index_.html#optimistic-concurrency-control-index). * * This parameter is only returned for successful operations. */ _primary_term: number; /** * HTTP status code returned for the operation. */ status: number; /** * Contains additional information about the failed operation. * * The parameter is only returned for failed operations. */ error: { /** * Error type for the operation. */ type: string; /** * Reason for the failed operation. */ reason: string; /** * The universally unique identifier (UUID) of the index associated with the failed operation. */ index_uuid: string; /** * ID of the shard associated with the failed operation. */ shard: string; /** * The index name or alias associated with the failed operation */ index: string; }; } }[] } function toMappings<S extends Shape>(shape: S): any { const {esMappings} = Meta.get(shape, ['esMappings']); if (esMappings) { return esMappings; } if (ShapeGuards.isUnionShape(shape)) { if (!isOptional(shape)) { throw new Error(`union types are not currently supported`); } if (ShapeGuards.isNothingShape(shape.Items[0])) { return toMappings(shape.Items[1]); } else { return toMappings(shape.Items[0]); } } else if (ShapeGuards.isRecordShape(shape)) { return { properties: Object.entries(shape.Members).map(([name, shape]) => ({ [name]: toMappings(shape) })).reduce((a, b) => ({...a, ...b})) }; } else if (ShapeGuards.isArrayShape(shape)) { return toMappings(shape.Items); } else if (ShapeGuards.isNumberShape(shape)) { const {numberType} = Meta.get(shape, ['numberType']); return { type: typeof numberType === 'string' ? numberType : 'double', }; } else if (ShapeGuards.isStringShape(shape)) { return { type: 'text' }; } else if (ShapeGuards.isBoolShape(shape)) { return { type: 'boolean' }; } else if (ShapeGuards.isTimestampShape(shape)) { return { type: 'date' }; } else if (ShapeGuards.isBinaryShape(shape)) { return { type: 'binary' }; } else if (ShapeGuards.isEnumShape(shape)) { return { type: 'keyword' }; } throw new Error(`unsupported type: ${shape.Kind}`); }
the_stack
* 数据质量相关接口 * Data Quality Interface Define * Author: jiejieli */ // 信息总览质量事件数据 export interface IQualityInfoOverview { errors: any; message: string; code: string; data: IOverviewData; result: boolean; } export interface IOverviewData { eventNotifiedCount: number; eventCount: number; } // 信息总览审核规则数据 export interface IQualityAuditRule { errors: any; message: string; code: string; data: IAuditRuleData; result: boolean; } // 规则数据 export interface IAuditRuleData { runningRuleCount: number; ruleCount: number; waitingRuleCount: number; failedRuleCount: number; } // 审核规则表格数据 export interface IQualityAuditRuleTable { errors: any; message: string; code: string; data: Array<IAuditRuleTableData>; result: boolean; } // 规则表格数据 export interface IAuditRuleTableData { updatedBy: string; ruleTemplate: string; updatedAt: string; ruleName: string; event: IEvent; ruleConfig: IRuleConfig; auditTaskStatus: string; createdAt: string; createdBy: string; ruleConfigAlias: string; ruleId: number; } // 规则配置 export interface IRuleConfig { input: Array<IInput>; rule: IRule; output: IOutput; } // 规则配置输出接口 export interface IOutput { eventSubType: string; eventType: string; tags: Array<string>; eventId: string; eventName: string; eventAlias: string; eventCurrency: number; } export interface IRule { function: IFunction; } // 规则函数接口 export interface IFunction { functionType: string; functionParams: Array<IFunctionParams>; functionName: string; } // 函数参数接口 export interface IFunctionParams { eventId: string; paramType: string; } // 函数输入接口 export interface IInput { eventId: string; inputType: string; } export interface IEvent { eventName: string; eventAlias: string; } // 质量事件统计信息 export interface IQualityEventInfo { errors: any; message: string; code: string; data: IEventData; result: boolean; } // Event Data Interface export interface IEventData { trend: ITrend; totalEvents: number; summary: ISummary; } export interface ISummary { invalidData: IInvalidData; customEvent1: ICustomEvent1; dataInterrupt: IDataInterrupt; dataLoss: IDataLoss; } // Trend Data Interface export interface ITrend { invalidData: IInvalidData; customEvent1: ICustomEvent1; dataInterrupt: IDataInterrupt; dataLoss: IDataLoss; } export interface IDataLoss { count: Array<number>; alias: string; times: Array<string>; } export interface IDataInterrupt { count: Array<number>; alias: string; times: Array<string>; } export interface ICustomEvent1 { count: Array<number>; alias: string; times: Array<string>; } export interface IInvalidData { count: Array<number>; alias: string; times: Array<string>; } // 质量事件表格信息 export interface IQualityEventTableData { errors: any; message: string; code: string; data: Array<IData>; result: boolean; } // 质量事件表格的数据接口 export interface IData { timer: any; isExpand: boolean; notifyWays: Array<string>; inEffect: boolean; eventSubType: string; description: string; receivers: string; eventId: string; sensitivity: string; eventPolarity: string; rule: IEventRule; updatedAt: string; createdBy: string; eventAlias: string; updatedBy: string; eventCurrency: number; createdAt: string; eventInstances: Array<IEventInstances>; eventType: string; expandTable: Array<IEventInstances>; } // Event Instances Interface export interface IEventInstances { eventDetail: string; eventStatusAlias: string; eventTime: string; } export interface IEventRule { ruleName: string; ruleConfigAlias: string; ruleId: string; } // 告警通知方式 export interface INotifyWayList { errors: any; message: string; code: string; data: Array<INotifyWayData>; result: boolean; } export interface INotifyWayData { description: string; notifyWayAlias: string; active: boolean; notifyWay: string; notifyWayName: string; icon: string; } // 规则配置函数列表 export interface IQualityRuleFunc { errors: any; message: string; code: string; data: Array<IRuleFuncData>; result: boolean; } export interface IRuleFuncData { functionAlias: string; updatedBy: any; createdAt: string; description: string; updatedAt: any; createdBy: string; functionType: string; functionConfigs: any; functionLogic: any; active: boolean; id: number; functionName: string; } // 规则配置指标 export interface IQualityRuleIndex { errors: any; message: string; code: string; data: Array<IRuleIndexData>; result: boolean; } export interface IRuleIndexData { id: number; metricName: string; metricAlias: string; metricType: string; metricUnit: string; sensitivity: string; metricOrigin: string; metricConfig: string; active: boolean; createdBy: string; createdAt: string; updatedBy: any; updatedAt: any; description: string; } // 规则配置模板 export interface IQualityRuleTemplate { errors: any; message: string; code: string; data: Array<IRuleTemplateData>; result: boolean; } export interface IRuleTemplateData { updatedBy: any; templateName: string; createdAt: string; templateAlias: string; createdBy: string; updatedAt: any; templateConfig: ITemplateConfig; active: boolean; id: number; description: string; } export interface ITemplateConfig { rule: ITemplateRule; } export interface ITemplateRule { function: ITemplateFunction; } export interface ITemplateFunction { functionType: string; functionParams: Array<ITemplateFunctionParams>; functionName: string; } export interface ITemplateFunctionParams { paramType: string; metricName: string; metricField: string; } // 新建规则 export interface IQualityCreateRule { errors: any; message: string; code: string; data: Array<ICreateRuleData>; result: boolean; } export interface ICreateRuleData { updatedBy: string; ruleTemplate: string; updatedAt: string; ruleName: string; event: ICreateEvent; ruleConfig: ICreateRuleConfig; auditTaskStatus: string; createdAt: string; createdBy: string; ruleConfigAlias: string; ruleId: number; } export interface ICreateRuleConfig { input: Array<ICreateInput>; rule: ICreateRule; output: ICreateOutput; } export interface ICreateOutput { eventSubType: string; eventType: string; tags: Array<string>; eventId: string; eventName: string; eventAlias: string; eventCurrency: number; } export interface ICreateRule { function: ICreateFunction; } export interface ICreateFunction { functionType: string; functionParams: Array<ICreateFunctionParams>; functionName: string; } export interface ICreateFunctionParams { eventId: string; paramType: string; } export interface ICreateInput { eventId: string; inputType: string; } export interface ICreateEvent { eventName: string; eventAlias: string; } // 结果表字段 export interface IRtFieldsList { message: string; code: string; data: Array<IRtFieldsData>; result: boolean; } export interface IRtFieldsData { fieldType: string; fieldAlias: string; description: any; roles: IRoles; createdAt: string; isDimension: boolean; createdBy: string; updatedAt: string; origins: any; fieldName: string; id: number; fieldIndex: number; updatedBy: string; } export interface IRoles { eventTime: boolean; } // 新建规则配置字段 export interface IRuleConfigFields { data_set_id: string; rule_name: string; rule_description: string; rule_template_id: string; rule_config: Array<ICreateRuleConfigField>; event_name: string; event_alias: string; event_description: string; event_type: string; event_sub_type: string; event_polarity: string; event_currency: string; sensitivity: string; event_detail_template: string; notify_ways: Array<any>; receivers: string[]; convergence_config: IConvergenceConfig; rule_id: string; audit_task_status: string; rule_config_alias: string; } export interface IConvergenceConfig { duration: number; alert_threshold: number; mask_time: number; } export interface ICreateRuleConfigField { metric: IMetric; function: string; constant: IConstant; operation: string; } export interface IConstant { constant_type: string; constant_value: number; } export interface IMetric { metric_type: string; metric_name: string; } // 质量事件查看指标接口 export interface IQualityIndex { message: string; code: string; data: IQualityIndexData; result: boolean; } export interface IQualityIndexData { F1NullRate: IF1NullRate; } export interface IF1NullRate { metricField: string; lastDay: Array<ILastDay>; lastWeek: Array<ILastWeek>; metricType: string; metricAlias: string; today: Array<IToday>; metricName: string; } export interface IToday { nullRate: number; time: number; } export interface ILastWeek { nullRate: number; time: number; } export interface ILastDay { nullRate: number; time: number; } // 数据审核事件模板变量列表 export interface IAuditEventTemp { errors: any; message: string; code: string; data: Array<IAuditEventTempData>; result: boolean; } export interface IAuditEventTempData { id: number; varName: string; varAlias: string; varExample: string; active: boolean; createdBy: string; createdAt: string; updatedBy: any; updatedAt: any; description: string; } // 数据质量事件子类型字典表 export interface IQualityEventTypes { errors: any; message: string; code: string; data: Array<IQualityEventTypesData>; result: boolean; } export interface IQualityEventTypesData { eventTypeName: string; id: number; eventTypeAlias: string; seqIndex: number; parentTypeName: string; active: boolean; createdBy: string; createdAt: string; updatedBy: any; updatedAt: any; description: string; } // 查询修正规则配置 export interface IQualityFixRuleConfig { errors: any; message: string; code: string; result: boolean; data: Array<IQualityFixRuleConfigData>; } export interface IQualityFixRuleConfigData { correctConfigId: number; dataSetId: string; bkBizId: number; flowId: number; nodeId: number; sourceSql: string; correctSql: string; generateType: string; correctConfigs: Array<ICorrectConfigs>; createdBy: string; createdAt: string; updatedBy: string; updatedAt: string; description: string; } export interface ICorrectConfigs { correctConfigItemId: number; field: string; correctConfigDetail: ICorrectConfigDetail; correctConfigAlias: string; createdBy: string; createdAt: string; updatedBy: string; updatedAt: string; } export interface ICorrectConfigDetail { rules: Array<IRules>; output: IQualityFixRuleConfigOutput; } export interface IQualityFixRuleConfigOutput { generateNewField: boolean; newField: string; } export interface IRules { condition: ICondition; filling: IFilling; } export interface IFilling { fillingName: string; fillingType: string; fillingValueType: string; fillingValue: number; } export interface ICondition { conditionName: string; conditionType: string; conditionValue: string; }
the_stack
import { View as TNSView, Frame as TNSFrame, Page as TNSPage, ViewBase as TNSViewBase, FormattedString as TNSFormattedString, Span as TNSSpan, ActionBar as TNSActionBar, ActionItem as TNSActionItem, NavigationButton as TNSNavigationButton, Tabs as TNSTabs, TabView as TNSTabView, TabViewItem as TNSTabViewItem, TabStrip as TNSTabStrip, TabStripItem as TNSTabStripItem, Label as TNSLabel, Image as TNSImage, BottomNavigation as TNSBottomNavigation, TabContentItem as TNSTabContentItem, NavigationContext as TNSNavigationContext, NavigationEntry as TNSNavigationEntry, BackstackEntry as TNSBackstackEntry, } from '@nativescript/core'; import { NSVElement, NSVViewFlags } from './nodes' import { __unstable__forwardNavOpts } from "./navigation"; import { RNSNavigationOptions } from "./navigation"; // import { actionBarNodeOps } from './components/ActionBar' // import { warn } from '@vue/runtime-core' import { warn } from "../../shared/Logger"; export type NSVElementResolver = () => TNSViewBase export type NSVModelDescriptor = { prop: string event: string } export interface NSVViewMeta { viewFlags: NSVViewFlags stackDepth?: number; nodeOps?: { insert(child: NSVElement, parent: NSVElement, atIndex?: number): void remove(child: NSVElement, parent: NSVElement): void } model?: NSVModelDescriptor overwriteExisting?: boolean } export interface NSVElementDescriptor { meta: NSVViewMeta resolver?: NSVElementResolver } export let defaultViewMeta: NSVViewMeta = { viewFlags: NSVViewFlags.NONE, } let elementMap: Record<string, NSVElementDescriptor> = {} export function getViewMeta(elementName: string): NSVViewMeta { // console.log(`->getViewMeta(${elementName})`) const normalizedName = normalizeElementName(elementName) const entry = elementMap[normalizedName] if (!entry) { throw new Error(`No known component for element ${elementName}.`) } return entry.meta } export function getViewClass(elementName: string): any { // console.log(`->getViewClass(${elementName})`) const normalizedName = normalizeElementName(elementName) const entry = elementMap[normalizedName] if (!entry) { throw new Error(`No known component for element ${elementName}.`) } try { return entry.resolver!() } catch (e) { throw new Error(`Could not load view for: ${elementName}. ${e}`) } } export function normalizeElementName(elementName: string): string { return elementName.replace(/-/g, '').toLowerCase() } export function registerElement( elementName: string, resolver?: NSVElementResolver, meta?: Partial<NSVViewMeta> ) { const normalizedName = normalizeElementName(elementName) const mergedMeta = Object.assign({}, defaultViewMeta, meta) if (elementMap[normalizedName] && !mergedMeta.overwriteExisting) { throw new Error( `Element for ${elementName} already registered.\n` + `If this is intentional set 'overwriteExisting: true' in 'meta'` ) } elementMap[normalizedName] = { meta: mergedMeta, resolver, } // console.log(`->registerElement(${elementName})`) } export function isKnownView(elementName: string): boolean { return elementMap.hasOwnProperty(normalizeElementName(elementName)) } type TNSFramePrivate = { _navigationQueue: TNSNavigationContext[], _backStack: TNSBackstackEntry[], // backStack just returns a copy. _currentEntry: TNSBackstackEntry|undefined, isCurrent: (entry: TNSBackstackEntry) => boolean, _removeEntry: (entry: TNSBackstackEntry) => void, }; // register built in elements // prettier-ignore if (!__TEST__) { // layouts registerElement( 'absoluteLayout', () => require('@nativescript/core').AbsoluteLayout, { viewFlags: NSVViewFlags.LAYOUT_VIEW } ) registerElement( 'dockLayout', () => require('@nativescript/core').DockLayout, { viewFlags: NSVViewFlags.LAYOUT_VIEW } ) registerElement( 'flexboxLayout', () => require('@nativescript/core').FlexboxLayout, { viewFlags: NSVViewFlags.LAYOUT_VIEW } ) registerElement( 'gridLayout', () => require('@nativescript/core').GridLayout, { viewFlags: NSVViewFlags.LAYOUT_VIEW } ) registerElement( 'stackLayout', () => require('@nativescript/core').StackLayout, { viewFlags: NSVViewFlags.LAYOUT_VIEW } ) registerElement( 'wrapLayout', () => require('@nativescript/core').WrapLayout, { viewFlags: NSVViewFlags.LAYOUT_VIEW } ) // ContentViews registerElement( 'contentView', () => require('@nativescript/core').ContentView, { viewFlags: NSVViewFlags.CONTENT_VIEW } ) registerElement( 'scrollView', () => require('@nativescript/core').ScrollView, { viewFlags: NSVViewFlags.CONTENT_VIEW } ) registerElement( 'actionBar', () => require('@nativescript/core').ActionBar, { nodeOps: { insert(child: NSVElement, parent: NSVElement<TNSActionBar>, atIndex?: number): void { const actionBar = parent.nativeView; if(child.nodeRole === "navigationButton"){ if(child.nativeView instanceof TNSNavigationButton){ actionBar.navigationButton = child.nativeView; } else { if (__DEV__) { warn( `Unable to add child "${child.nativeView.constructor.name}" as the navigationButton of <actionBar> as it is not an instance of NavigationButton.` ); } } } else if(child.nodeRole === "actionItems"){ if(child.nativeView instanceof TNSActionItem === false){ if (__DEV__) { warn( `Unable to add child "${child.nativeView.constructor.name}" to the actionItems of <actionBar> as it is not an instance of ActionItem.` ); }; return; } /** * The implementation shows that getItems() returns a clone of the array, conforming to Array. * @see action-bar-common.js */ const existingItems: TNSActionItem[] = actionBar.actionItems.getItems(); if(typeof atIndex === "undefined" || atIndex === existingItems.length){ /** * The implementation shows that addItem() acts as Array.prototype.push(). * @see action-bar-common.js */ actionBar.actionItems.addItem(child.nativeView as TNSActionItem); } else { /** * actionBar.actionItems doesn't publicly expose a splice() API, so we'll have to do things the hard way. */ const updatedItems: TNSActionItem[] = actionBar.actionItems.getItems(); updatedItems.splice( atIndex, 0, child.nativeView as TNSActionItem ); existingItems.forEach(actionItem => actionBar.actionItems.removeItem(actionItem)); updatedItems.forEach(actionItem => actionBar.actionItems.addItem(actionItem)); } } else if(child.nodeRole === "actionItem"){ if (__DEV__) { warn( `Unable to add child "${child.nativeView.constructor.name}" to <actionBar> as it had the nodeRole "actionItem"; please correct it to "actionItems".` ); } } else if(child.nodeRole === "titleView"){ actionBar.titleView = child.nativeView as TNSView; } else { if (__DEV__) { warn( `Unable to add child "${child.nativeView.constructor.name}" to <actionBar> as it does not have a nodeRole specified; ` + `please set a nodeRole of "navigationButton", "actionItems", or "titleView".` ) } } }, remove(child: NSVElement, parent: NSVElement<TNSActionBar>): void { const actionBar = parent.nativeView as TNSActionBar; if(child.nodeRole === "navigationButton"){ actionBar.navigationButton = null; // Anything falsy should work. } else if(child.nodeRole === "actionItems"){ actionBar.actionItems.removeItem(child.nativeView as TNSActionItem); } else if(child.nodeRole === "actionItem"){ if (__DEV__) { warn( `Unable to remove child "${child.nativeView.constructor.name}" from <actionBar> as it had the nodeRole "actionItem"; please correct it to "actionItems".` ); } } else if(child.nodeRole === "titleView"){ actionBar.titleView = null; // Anything falsy should work. } else { if (__DEV__) { warn( `Unable to add child "${child.nativeView.constructor.name}" to <actionBar> as it does not have a nodeRole specified; ` + `please set a nodeRole of "navigationButton", "actionItems", or "titleView".` ) } } } } } ) registerElement( 'actionItem', () => require('@nativescript/core').ActionItem // _addChildFromBuilder and removeChild both refer to actionView, so no strict need for nodeOps here. ) registerElement( 'navigationButton', () => require('@nativescript/core').NavigationButton // _addChildFromBuilder and removeChild both refer to actionView, so no strict need for nodeOps here. ) // navigation registerElement( 'frame', () => require('@nativescript/core').Frame, { stackDepth: 0, // todo: move into Frame.ts when we end up creating a component for Frame nodeOps: { insert(child: NSVElement, parent: NSVElement<TNSFrame>, atIndex?: number): void { const frame = parent.nativeView; const page = child.nativeView as TNSPage; if (child.nativeView instanceof TNSPage) { if(typeof atIndex === "undefined"){ const stackDepth = parent.meta.stackDepth; const resolvedNavOpts: RNSNavigationOptions = Object.assign( {}, __unstable__forwardNavOpts.defaultOptions, { animated: stackDepth > -1, clearHistory: stackDepth === -1, backstackVisible: true, }, __unstable__forwardNavOpts.pop() || {}, ); // console.log(`[frame.insert] [${parent} > ${child} @${atIndex}] => [${parent.childNodes}] via ${parent}.navigate(${child}) (clearHistory ${resolvedNavOpts.clearHistory}); stackDepth ${stackDepth} -> ${stackDepth + 1}`); // console.log(`[frame.insert.pending] backstack is now: [${(frame as unknown as TNSFramePrivate)._backStack.map(entry => entry.resolvedPage)}]`); frame.navigate({ ...resolvedNavOpts, create() { return child.nativeView as TNSView } }); // At least on forward navigations, need to wait for the animation to complete before the backstack will reflect the update. // setTimeout(() => { // console.log(`[frame.insert.done] backstack is now: [${(frame as unknown as TNSFramePrivate)._backStack.map(entry => entry.resolvedPage)}]`); // }, 1000); parent.meta.stackDepth++; return; } else { if (__DEV__) { warn(`NativeScript Core does not support splicing pages into frames. Can't add page to index ${atIndex}.`); } } } else { if (__DEV__) { warn( `<frame> must only contain <page> elements - ` + `got <${child.nativeView.constructor.name}> instead.` ) } } }, /** * This is a best-of-a-bad-job. NativeScript Core implements push & pop, and * replacement (but only of the topmost, currentEntry of the stack). The latter * was only implemented for HMR purposes. * * We can splice frame._backStack (belonging to frame-common.ts), but it doesn't * update the logic of the frame.ios.ts and frame.android.ts native implementations. */ remove(child: NSVElement, parent: NSVElement<TNSFrame>): void { // console.log(`[frame.remove] ${parent}.childNodes updating to: [${parent.childNodes}]`); const frame = parent.nativeView; const page = child.nativeView as TNSPage; if((frame as unknown as TNSFramePrivate)._currentEntry?.resolvedPage === page){ if(frame.canGoBack()){ // console.log(`[frame.remove] [${parent} x ${child}] => [${parent.childNodes}] via ${parent}.goBack() on currentEntry page; stackDepth ${parent.meta.stackDepth} -> ${Math.max(0, parent.meta.stackDepth - 1)}`); // console.log(`[frame.remove.pending] backstack is now: [${(frame as unknown as TNSFramePrivate)._backStack.map(entry => entry.resolvedPage)}]`); /** { animated: false } is ignored even if you pass in a backStackEntry that explicitly specifies it. */ frame.goBack(); // console.log(`[frame.remove.done] backstack is now: [${(frame as unknown as TNSFramePrivate)._backStack.map(entry => entry.resolvedPage)}]`); parent.meta.stackDepth = Math.max(0, parent.meta.stackDepth - 1); } else { /** * NativeScript Core does not support transitioning a Frame back to Pageless state. * It's simply not possible, whether by `frame.removeEntry()`, `frame._updateBackstack()`, * or `frame.setCurrent()`. * * ... So the best we can do is indicate that the stack is conceptually empty. * This means that, on next navigation, we should call clearHistory. */ // console.log(`[frame.remove] [${parent} x ${child}] = [${parent.childNodes}] via no-op on currentEntry page; stackDepth ${parent.meta.stackDepth} -> -1`); // console.log(`[frame.remove.done] backstack is now: [${(frame as unknown as TNSFramePrivate)._backStack.map(entry => entry.resolvedPage)}]`); parent.meta.stackDepth = -1; } } else { // console.log(`[frame.remove] ${parent} x ${child}, but child isn't the currentEntry (which is ${frame._currentEntry?.resolvedPage}). May involve a splice or a no-op.`); /** * When React Navigation pops back to the top, it removes from the root of the stack rather than the face. This has some sense, as * it avoids rendering and animating every pop on the way, but it's very problematic for NativeScript Core, which cannot splice * Pages from the Frame's stack. * */ let indexOfBackstackEntry: number = -1; const backstackEntry: TNSBackstackEntry | undefined = (frame as unknown as TNSFramePrivate)._backStack.find((entry, i) => { if(entry.resolvedPage === page){ indexOfBackstackEntry = i; return true; } return false; }); if(backstackEntry){ // console.log(`[frame.remove] Found backStackEntry for ${child} at index ${indexOfBackstackEntry}, so it's a splice.`); // const backStackLengthBefore = (frame as unknown as TNSFramePrivate)._backStack.length; // console.log(`[frame.remove] [${parent} x ${child}] = [${parent.childNodes}] via splice@${indexOfBackstackEntry} of non-currentEntry page; stackDepth ${parent.meta.stackDepth} -> ${Math.max(0, parent.meta.stackDepth - 1)}`); // console.log(`[frame.remove.pending] backstack is now: [${(frame as unknown as TNSFramePrivate)._backStack.map(entry => entry.resolvedPage)}]`); (frame as unknown as TNSFramePrivate)._removeEntry(backstackEntry); (frame as unknown as TNSFramePrivate)._backStack.splice(indexOfBackstackEntry, 1); // console.log(`[frame.remove] backStackLengthBefore ${backStackLengthBefore} => backStackLengthAfter ${(frame as unknown as TNSFramePrivate)._backStack.length}`); // console.log(`[frame.remove.done] backstack is now: [${(frame as unknown as TNSFramePrivate)._backStack.map(entry => entry.resolvedPage)}]`); } else { /* There's actually valid reason to no-op here: * We might simply be trying to pop a child page in response to a native pop having occurred. */ // console.log(`[frame.remove] Didn't find a backStackEntry for ${child} at so it must have been handled by Core already. No-op. `); // console.log(`[frame.remove] [${parent} x ${child}] = [${parent.childNodes}] via no-op on non-currentEntry page; stackDepth ${parent.meta.stackDepth} -> ${Math.max(0, parent.meta.stackDepth - 1)}`); // console.log(`[frame.remove.done] backstack is now: [${(frame as unknown as TNSFramePrivate)._backStack.map(entry => entry.resolvedPage)}]`); } parent.meta.stackDepth = Math.max(0, parent.meta.stackDepth - 1); return; } } } } ) registerElement( 'page', () => require('@nativescript/core').Page, { viewFlags: NSVViewFlags.CONTENT_VIEW, nodeOps: { insert(child: NSVElement, parent: NSVElement<TNSPage>, atIndex?: number): void { const page = parent.nativeView; if(typeof atIndex === "number" && atIndex > 0){ if (__DEV__) { warn( `Cannot add child "${child.nativeView.constructor.name}" to Page, as Page only accepts a single child. ` + `If you wish to add more than one child to a Page, wrap them in a LayoutBase like <stackLayout>.` ) } return; } if (child.nodeRole === "actionBar" || child.nativeView instanceof TNSActionBar) { page.actionBar = child.nativeView as TNSActionBar; } else { page.content = child.nativeView as TNSView; } }, remove(child: NSVElement, parent: NSVElement<TNSPage>): void { const page = parent.nativeView; if (child.nodeRole === "actionBar" || child.nativeView instanceof TNSActionBar) { /* Well we could technically do this, but it'd be better to just teach good practices. */ // page.actionBar = new TNSActionBar(); if (__DEV__) { warn( `Unable to remove ActionBar from Page; not supported by NativeScript Core. ` + `You may prefer to set page.actionBarHidden = true instead.` ) } } else { page.content = null; } } } } ) // html registerElement( 'htmlView', () => require('@nativescript/core').HtmlView ) registerElement( 'webView', () => require('@nativescript/core').WebView ) // components registerElement( 'activityIndicator', () => require('@nativescript/core').ActivityIndicator ) registerElement( 'button', () => require('@nativescript/core').Button ) registerElement( 'datePicker', () => require('@nativescript/core').DatePicker, { model: { prop: 'date', event: 'dateChange' } } ) registerElement( 'formattedString', () => require('@nativescript/core').FormattedString, { // todo: move into FormattedString.ts when we end up creating a component for FormattedString /** * The default parentView._addChildFromBuilder() seems to handle the case of pushing a new child in. * It might even handle the case of splicing a child into place. I wasn't able to check. */ nodeOps: { insert(child: NSVElement, parent: NSVElement, atIndex?: number): void { const formattedString = parent.nativeView as TNSFormattedString if (child.nativeView instanceof TNSSpan) { const spansLength: number = formattedString.spans.length; formattedString.spans.splice( typeof atIndex === "undefined" ? spansLength : atIndex, 0, child.nativeView ); } else { if (__DEV__) { warn( `<formattedString> must only contain <span> elements - ` + `got <${child.nativeView.constructor.name}> instead.` ) } } }, /** * The default parentView._removeView() crashes upon removing a span. * This implementation addresses that. */ remove(child: NSVElement, parent: NSVElement): void { const formattedString = parent.nativeView as TNSFormattedString if (child.nativeView instanceof TNSSpan) { const childIndex: number = formattedString.spans.indexOf(child.nativeView); formattedString.spans.splice(childIndex, 1); } else { if (__DEV__) { warn( `<formattedString> must only contain <span> elements - ` + `got <${child.nativeView.constructor.name}> instead.` ) } } } } } ) registerElement( 'image', () => require('@nativescript/core').Image ) registerElement( 'label', () => require('@nativescript/core').Label ) registerElement( 'listPicker', () => require('@nativescript/core').ListPicker, { model: { prop: 'selectedIndex', event: 'selectedIndexChange' } } ) registerElement( 'listView', () => require('@nativescript/core').ListView, { viewFlags: NSVViewFlags.NO_CHILDREN } ) registerElement( 'placeholder', () => require('@nativescript/core').Placeholder, ) registerElement( 'progress', () => require('@nativescript/core').Progress ) registerElement( 'searchBar', () => require('@nativescript/core').SearchBar, { model: { prop: 'text', event: 'textChange', } } ) registerElement( 'segmentedBar', () => require('@nativescript/core').SegmentedBar, { model: { prop: 'selectedIndex', event: 'selectedIndexChange', } } ) registerElement( 'segmentedBarItem', () => require('@nativescript/core').SegmentedBarItem, ) registerElement( 'slider', () => require('@nativescript/core').Slider, { model: { prop: 'value', event: 'valueChange', } } ) registerElement( 'span', () => require('@nativescript/core').Span, ) registerElement( 'switch', () => require('@nativescript/core').Switch, { model: { prop: 'checked', event: 'checkedChange', } } ) registerElement( 'textField', () => require('@nativescript/core').TextField, { model: { prop: 'text', event: 'textChange', } } ) registerElement( 'textView', () => require('@nativescript/core').TextView, { model: { prop: 'text', event: 'textChange', }, } ) registerElement( 'timePicker', () => require('@nativescript/core').TimePicker, { model: { prop: 'time', event: 'timeChange', }, } ) registerElement( 'tabView', () => require('@nativescript/core').TabView, { nodeOps: { insert(child: NSVElement, parent: NSVElement<TNSTabView>, atIndex?: number): void { const tabView = parent.nativeView; if(child.nodeRole === "items"){ if(child.nativeView instanceof TNSTabViewItem === false){ if (__DEV__) { warn( `Unable to add child "${child.nativeView.constructor.name}" to the items of <tabView> as it is not an instance of TabViewItem.` ); }; return; } const items = tabView.items || []; // Annoyingly, it's the consumer's responsibility to ensure there's an array there! if(typeof atIndex === "undefined" || atIndex === items.length){ tabView.items = items.concat(child.nativeView as TNSTabViewItem); } else { tabView.items = items.slice().splice( atIndex, 0, child.nativeView as TNSTabViewItem ); } } else if(child.nodeRole === "item"){ if (__DEV__) { warn( `Unable to add child "${child.nativeView.constructor.name}" to <tabView> as it had the nodeRole "item"; please correct it to "items".` ); } } else { if (__DEV__) { warn( `Unable to add child "${child.nativeView.constructor.name}" to <tabView> as it does not have a nodeRole specified; ` + `please set a nodeRole of "items".` ) } } }, remove(child: NSVElement, parent: NSVElement<TNSTabView>): void { const tabView = parent.nativeView; if(child.nodeRole === "items"){ tabView.items = (tabView.items || []).filter(i => i !== child.nativeView); } else if(child.nodeRole === "item"){ if (__DEV__) { warn( `Unable to remove child "${child.nativeView.constructor.name}" from <tabView> as it had the nodeRole "item"; please correct it to "items".` ); } } else { if (__DEV__) { warn( `Unable to add child "${child.nativeView.constructor.name}" to <tabView> as it does not have a nodeRole specified; ` + `please set a nodeRole of "items"` ) } } } } } ) registerElement( 'tabViewItem', () => require('@nativescript/core').TabViewItem, { nodeOps: { insert(child: NSVElement, parent: NSVElement<TNSTabViewItem>, atIndex?: number): void { const tabViewItem = parent.nativeView; if(child.nativeView instanceof TNSView){ tabViewItem.view = child.nativeView; } else { if (__DEV__) { warn( `Unable to add child "${child.nativeView.constructor.name}" as the view of <tabViewItem> as it is not an instance of View.` ); } } }, remove(child: NSVElement, parent: NSVElement<TNSTabViewItem>): void { const tabViewItem = parent.nativeView; // tabViewItem.view = null; // Anything falsy should work. if (__DEV__) { warn( `Unable to remove child "${child.nativeView.constructor.name}" from <tabViewItem> as NativeScript Core does not support it; ` + `please re-use and modify the existing TabViewItem instead.` ) } } } } ) registerElement( 'tabStrip', () => require('@nativescript/core').TabStrip, { nodeOps: { insert(child: NSVElement, parent: NSVElement<TNSTabStrip>, atIndex?: number): void { const tabStrip = parent.nativeView; if(child.nodeRole === "items"){ if(child.nativeView instanceof TNSTabStripItem === false){ if (__DEV__) { warn( `Unable to add child "${child.nativeView.constructor.name}" to the items of <tabStrip> as it is not an instance of TabStripItem.` ); }; return; } // console.log(`[tabStrip.insert] 1 [${parent} > ${child} @${atIndex}] => [${parent.childNodes}]`); const items = tabStrip.items || []; // Annoyingly, it's the consumer's responsibility to ensure there's an array there! if(typeof atIndex === "undefined" || atIndex === items.length){ // console.log(`[tabStrip.insert] 2a [${parent} > ${child} @${atIndex}] => [${parent.childNodes}]`); tabStrip.items = items.concat(child.nativeView as TNSTabStripItem); } else { // console.log(`[tabStrip.insert] 2b [${parent} > ${child} @${atIndex}] => [${parent.childNodes}]`); tabStrip.items = items.slice().splice( atIndex, 0, child.nativeView as TNSTabStripItem ); } } else if(child.nodeRole === "item"){ if (__DEV__) { warn( `Unable to add child "${child.nativeView.constructor.name}" to <tabStrip> as it had the nodeRole "item"; please correct it to "items".` ); } } else { if (__DEV__) { warn( `Unable to add child "${child.nativeView.constructor.name}" to <tabStrip> as it does not have a nodeRole specified; ` + `please set a nodeRole of "tabStrip", or "items".` ) } } }, remove(child: NSVElement, parent: NSVElement<TNSTabStrip>): void { const tabs = parent.nativeView; if(child.nodeRole === "items"){ tabs.items = (tabs.items || []).filter(i => i !== child.nativeView); } else if(child.nodeRole === "item"){ if (__DEV__) { warn( `Unable to remove child "${child.nativeView.constructor.name}" from <tabStrip> as it had the nodeRole "item"; please correct it to "items".` ); } } else { if (__DEV__) { warn( `Unable to remove child "${child.nativeView.constructor.name}" from <tabStrip> as it does not have a nodeRole specified; ` + `please set a nodeRole of "tabStrip", or "items"` ) } } } } } ) registerElement( 'tabStripItem', () => require('@nativescript/core').TabStripItem, { nodeOps: { insert(child: NSVElement, parent: NSVElement<TNSTabStripItem>, atIndex?: number): void { const tabStripItem = parent.nativeView; // Note: The instanceof check, and nodeRole check, is technically redundant if you look at the implementation, but I'll // keep these good practices in case it's ever refactored. if(child.nodeRole === "label"){ console.log(`[tabStrip.insert] LABEL [${parent} > ${child} @${atIndex}] => [${parent.childNodes}]`); if(child.nativeView instanceof TNSLabel === false){ if (__DEV__) { warn( `Unable to add child "${child.nativeView.constructor.name}" to the items of <tabStripItem> as it is not an instance of Label.` ); }; return; } tabStripItem.label = child.nativeView as TNSLabel; } else if(child.nodeRole === "image"){ console.log(`[tabStrip.insert] IMAGE [${parent} > ${child} @${atIndex}] => [${parent.childNodes}]`); if(child.nativeView instanceof TNSImage === false){ if (__DEV__) { warn( `Unable to add child "${child.nativeView.constructor.name}" to the items of <tabStripItem> as it is not an instance of Image.` ); }; return; } tabStripItem.image = child.nativeView as TNSImage; } else { console.log(`[tabStrip.insert] OTHER [${parent} > ${child} @${atIndex}] => [${parent.childNodes}]`); if (__DEV__) { warn( `Unable to add child "${child.nativeView.constructor.name}" to <tabStripItem> as it does not have a nodeRole specified; ` + `please set a nodeRole of "label", or "image".` ) } } }, remove(child: NSVElement, parent: NSVElement<TNSTabStripItem>): void { const tabStripItem = parent.nativeView; if(child.nodeRole === "label"){ // WARNING: It is not evident from the implementation that TabStripItem supports removing label at all! tabStripItem.label = null; } else if(child.nodeRole === "image"){ // WARNING: It is not evident from the implementation that TabStripItem supports removing image at all! tabStripItem.image = null; } else { if (__DEV__) { warn( `Unable to remove child "${child.nativeView.constructor.name}" from <tabStripItem> as it does not have a nodeRole specified; ` + `please set a nodeRole of "label", or "image"` ) } } } } } ) registerElement( 'tabs', () => require('@nativescript/core').Tabs, { // TODO: share the same NodeOps for both BottomNavigation and Tabs; they're identical as they both extend TabNavigationBase. nodeOps: { insert(child: NSVElement, parent: NSVElement<TNSTabs>, atIndex?: number): void { const tabs = parent.nativeView; if(child.nodeRole === "tabStrip"){ if(child.nativeView instanceof TNSTabStrip){ tabs.tabStrip = child.nativeView; } else { if (__DEV__) { warn( `Unable to add child "${child.nativeView.constructor.name}" as the tabStrip of <tabs> as it is not an instance of TabStrip.` ); } } } else if(child.nodeRole === "items"){ if(child.nativeView instanceof TNSTabContentItem === false){ if (__DEV__) { warn( `Unable to add child "${child.nativeView.constructor.name}" to the items of <tabs> as it is not an instance of TabContentItem.` ); }; return; } const items = tabs.items || []; // Annoyingly, it's the consumer's responsibility to ensure there's an array there! if(typeof atIndex === "undefined" || atIndex === items.length){ tabs.items = items.concat(child.nativeView as TNSTabContentItem); } else { tabs.items = items.slice().splice( atIndex, 0, child.nativeView as TNSTabContentItem ); } } else if(child.nodeRole === "item"){ if (__DEV__) { warn( `Unable to add child "${child.nativeView.constructor.name}" to <tabs> as it had the nodeRole "item"; please correct it to "items".` ); } } else { if (__DEV__) { warn( `Unable to add child "${child.nativeView.constructor.name}" to <tabs> as it does not have a nodeRole specified; ` + `please set a nodeRole of "tabStrip", or "items".` ) } } }, remove(child: NSVElement, parent: NSVElement): void { const tabs = parent.nativeView as TNSTabs; if(child.nodeRole === "tabStrip"){ tabs.tabStrip = null; // Anything falsy should work. } else if(child.nodeRole === "items"){ tabs.items = (tabs.items || []).filter(i => i !== child.nativeView); } else if(child.nodeRole === "item"){ if (__DEV__) { warn( `Unable to remove child "${child.nativeView.constructor.name}" from <tabs> as it had the nodeRole "item"; please correct it to "items".` ); } } else { if (__DEV__) { warn( `Unable to remove child "${child.nativeView.constructor.name}" from <tabs> as it does not have a nodeRole specified; ` + `please set a nodeRole of "tabStrip", or "items"` ) } } } } } ) registerElement( 'tabContentItem', () => require('@nativescript/core').TabContentItem, { viewFlags: NSVViewFlags.CONTENT_VIEW } ) registerElement( 'bottomNavigation', () => require('@nativescript/core').BottomNavigation, { // TODO: share the same NodeOps for both BottomNavigation and Tabs; they're identical as they both extend TabNavigationBase. nodeOps: { insert(child: NSVElement, parent: NSVElement<TNSBottomNavigation>, atIndex?: number): void { const bottomNavigation = parent.nativeView; if(child.nodeRole === "tabStrip"){ if(child.nativeView instanceof TNSTabStrip){ bottomNavigation.tabStrip = child.nativeView; } else { if (__DEV__) { warn( `Unable to add child "${child.nativeView.constructor.name}" as the tabStrip of <bottomNavigation> as it is not an instance of TabStrip.` ); } } } else if(child.nodeRole === "items"){ if(child.nativeView instanceof TNSTabContentItem === false){ if (__DEV__) { warn( `Unable to add child "${child.nativeView.constructor.name}" to the items of <bottomNavigation> as it is not an instance of TabContentItem.` ); }; return; } const items = bottomNavigation.items || []; // Annoyingly, it's the consumer's responsibility to ensure there's an array there! if(typeof atIndex === "undefined" || atIndex === items.length){ bottomNavigation.items = items.concat(child.nativeView as TNSTabContentItem); } else { bottomNavigation.items = items.slice().splice( atIndex, 0, child.nativeView as TNSTabContentItem ); } } else if(child.nodeRole === "item"){ if (__DEV__) { warn( `Unable to add child "${child.nativeView.constructor.name}" to <bottomNavigation> as it had the nodeRole "item"; please correct it to "items".` ); } } else { if (__DEV__) { warn( `Unable to add child "${child.nativeView.constructor.name}" to <bottomNavigation> as it does not have a nodeRole specified; ` + `please set a nodeRole of "tabStrip", or "items".` ) } } }, remove(child: NSVElement, parent: NSVElement<TNSTabs>): void { const tabs = parent.nativeView; if(child.nodeRole === "tabStrip"){ tabs.tabStrip = null; // Anything falsy should work. } else if(child.nodeRole === "items"){ tabs.items = (tabs.items || []).filter(i => i !== child.nativeView); } else if(child.nodeRole === "item"){ if (__DEV__) { warn( `Unable to remove child "${child.nativeView.constructor.name}" from <bottomNavigation> as it had the nodeRole "item"; please correct it to "items".` ); } } else { if (__DEV__) { warn( `Unable to remove child "${child.nativeView.constructor.name}" from <bottomNavigation> as it does not have a nodeRole specified; ` + `please set a nodeRole of "tabStrip", or "items"` ) } } } } } ) } // todo: more
the_stack
import { Injectable, Inject, Optional } from '@angular/core'; import { Http, Response } from '@angular/http'; import { BaseLoopBackApi } from '../core/base.service'; import { LoopBackConfig } from '../../lb.config'; import { LoopBackAuth } from '../core/auth.service'; import { LoopBackFilter, SDKToken, AccessToken } from '../../models/BaseModels'; import { JSONSearchParams } from '../core/search.params'; import { ErrorHandler } from '../core/error.service'; import { Subject } from 'rxjs/Subject'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import { User } from '../../models/User'; // Making Sure EventSource Type is available to avoid compilation issues. declare var EventSource: any; /** * Api services for the `User` model. */ @Injectable() export class UserApi extends BaseLoopBackApi { constructor( @Inject(Http) http: Http, @Inject(LoopBackAuth) protected auth: LoopBackAuth, @Inject(JSONSearchParams) protected searchParams: JSONSearchParams, @Optional() @Inject(ErrorHandler) errorHandler: ErrorHandler ) { super(http, auth, searchParams, errorHandler); } /** * Find a related item by id for accessTokens. * * @param any id User id * * @param any fk Foreign key for accessTokens * * @returns object An empty reference that will be * populated with the actual data once the response is returned * from the server. * * <em> * (The remote method definition does not provide any description. * This usually means the response is a `User` object.) * </em> */ public findByIdAccessTokens(id: any, fk: any): Observable<any> { let method: string = "GET"; let url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + "/Users/:id/accessTokens/:fk"; let routeParams: any = { id: id, fk: fk }; let postBody: any = {}; let urlParams: any = {}; let result = this.request(method, url, routeParams, urlParams, postBody); return result; } /** * Delete a related item by id for accessTokens. * * @param any id User id * * @param any fk Foreign key for accessTokens * * @returns object An empty reference that will be * populated with the actual data once the response is returned * from the server. * * This method returns no data. */ public destroyByIdAccessTokens(id: any, fk: any): Observable<any> { let method: string = "DELETE"; let url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + "/Users/:id/accessTokens/:fk"; let routeParams: any = { id: id, fk: fk }; let postBody: any = {}; let urlParams: any = {}; let result = this.request(method, url, routeParams, urlParams, postBody); return result; } /** * Update a related item by id for accessTokens. * * @param any id User id * * @param any fk Foreign key for accessTokens * * @param object data Request data. * * This method expects a subset of model properties as request parameters. * * @returns object An empty reference that will be * populated with the actual data once the response is returned * from the server. * * <em> * (The remote method definition does not provide any description. * This usually means the response is a `User` object.) * </em> */ public updateByIdAccessTokens(id: any, fk: any, data: any = undefined): Observable<any> { let method: string = "PUT"; let url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + "/Users/:id/accessTokens/:fk"; let routeParams: any = { id: id, fk: fk }; let postBody: any = { data: data }; let urlParams: any = {}; let result = this.request(method, url, routeParams, urlParams, postBody); return result; } /** * Queries accessTokens of User. * * @param any id User id * * @param object filter * * @returns object[] An empty reference that will be * populated with the actual data once the response is returned * from the server. * * <em> * (The remote method definition does not provide any description. * This usually means the response is a `User` object.) * </em> */ public getAccessTokens(id: any, filter: LoopBackFilter = undefined): Observable<any> { let method: string = "GET"; let url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + "/Users/:id/accessTokens"; let routeParams: any = { id: id }; let postBody: any = {}; let urlParams: any = {}; if (filter) urlParams.filter = filter; let result = this.request(method, url, routeParams, urlParams, postBody); return result; } /** * Creates a new instance in accessTokens of this model. * * @param any id User id * * @param object data Request data. * * This method expects a subset of model properties as request parameters. * * @returns object An empty reference that will be * populated with the actual data once the response is returned * from the server. * * <em> * (The remote method definition does not provide any description. * This usually means the response is a `User` object.) * </em> */ public createAccessTokens(id: any, data: any = undefined): Observable<any> { let method: string = "POST"; let url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + "/Users/:id/accessTokens"; let routeParams: any = { id: id }; let postBody: any = { data: data }; let urlParams: any = {}; let result = this.request(method, url, routeParams, urlParams, postBody); return result; } /** * Deletes all accessTokens of this model. * * @param any id User id * * @returns object An empty reference that will be * populated with the actual data once the response is returned * from the server. * * This method returns no data. */ public deleteAccessTokens(id: any): Observable<any> { let method: string = "DELETE"; let url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + "/Users/:id/accessTokens"; let routeParams: any = { id: id }; let postBody: any = {}; let urlParams: any = {}; let result = this.request(method, url, routeParams, urlParams, postBody); return result; } /** * Counts accessTokens of User. * * @param any id User id * * @param object where Criteria to match model instances * * @returns object An empty reference that will be * populated with the actual data once the response is returned * from the server. * * Data properties: * * - `count` – `{number}` - */ public countAccessTokens(id: any, where: any = undefined): Observable<any> { let method: string = "GET"; let url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + "/Users/:id/accessTokens/count"; let routeParams: any = { id: id }; let postBody: any = {}; let urlParams: any = {}; if (where) urlParams.where = where; let result = this.request(method, url, routeParams, urlParams, postBody); return result; } /** * Create a new instance of the model and persist it into the data source. * * @param object data Request data. * * This method expects a subset of model properties as request parameters. * * @returns object An empty reference that will be * populated with the actual data once the response is returned * from the server. * * <em> * (The remote method definition does not provide any description. * This usually means the response is a `User` object.) * </em> */ public create(data: any = undefined): Observable<User> { let method: string = "POST"; let url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + "/Users"; let routeParams: any = {}; let postBody: any = { data: data }; let urlParams: any = {}; let result = this.request(method, url, routeParams, urlParams, postBody); return result.map((instance: User) => new User(instance)); } /** * Patch an existing model instance or insert a new one into the data source. * * @param object data Request data. * * This method expects a subset of model properties as request parameters. * * @returns object An empty reference that will be * populated with the actual data once the response is returned * from the server. * * <em> * (The remote method definition does not provide any description. * This usually means the response is a `User` object.) * </em> */ public upsert(data: any = undefined): Observable<User> { let method: string = "PUT"; let url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + "/Users"; let routeParams: any = {}; let postBody: any = { data: data }; let urlParams: any = {}; let result = this.request(method, url, routeParams, urlParams, postBody); return result.map((instance: User) => new User(instance)); } /** * Replace an existing model instance or insert a new one into the data source. * * @param object data Request data. * * This method expects a subset of model properties as request parameters. * * @returns object An empty reference that will be * populated with the actual data once the response is returned * from the server. * * <em> * (The remote method definition does not provide any description. * This usually means the response is a `User` object.) * </em> */ public replaceOrCreate(data: any = undefined): Observable<any> { let method: string = "POST"; let url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + "/Users/replaceOrCreate"; let routeParams: any = {}; let postBody: any = { data: data }; let urlParams: any = {}; let result = this.request(method, url, routeParams, urlParams, postBody); return result; } /** * Update an existing model instance or insert a new one into the data source based on the where criteria. * * @param object where Criteria to match model instances * * @param object data Request data. * * This method expects a subset of model properties as request parameters. * * @returns object An empty reference that will be * populated with the actual data once the response is returned * from the server. * * <em> * (The remote method definition does not provide any description. * This usually means the response is a `User` object.) * </em> */ public upsertWithWhere(where: any = undefined, data: any = undefined): Observable<User> { let method: string = "POST"; let url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + "/Users/upsertWithWhere"; let routeParams: any = {}; let postBody: any = { data: data }; let urlParams: any = {}; if (where) urlParams.where = where; let result = this.request(method, url, routeParams, urlParams, postBody); return result.map((instance: User) => new User(instance)); } /** * Check whether a model instance exists in the data source. * * @param any id Model id * * @returns object An empty reference that will be * populated with the actual data once the response is returned * from the server. * * Data properties: * * - `exists` – `{boolean}` - */ public exists(id: any): Observable<any> { let method: string = "GET"; let url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + "/Users/:id/exists"; let routeParams: any = { id: id }; let postBody: any = {}; let urlParams: any = {}; let result = this.request(method, url, routeParams, urlParams, postBody); return result; } /** * Find a model instance by {{id}} from the data source. * * @param any id Model id * * @param object filter Filter defining fields and include * * @returns object An empty reference that will be * populated with the actual data once the response is returned * from the server. * * <em> * (The remote method definition does not provide any description. * This usually means the response is a `User` object.) * </em> */ public findById(id: any, filter: LoopBackFilter = undefined): Observable<User> { let method: string = "GET"; let url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + "/Users/:id"; let routeParams: any = { id: id }; let postBody: any = {}; let urlParams: any = {}; if (filter) urlParams.filter = filter; let result = this.request(method, url, routeParams, urlParams, postBody); return result.map((instance: User) => new User(instance)); } /** * Replace attributes for a model instance and persist it into the data source. * * @param any id Model id * * @param object data Request data. * * This method expects a subset of model properties as request parameters. * * @returns object An empty reference that will be * populated with the actual data once the response is returned * from the server. * * <em> * (The remote method definition does not provide any description. * This usually means the response is a `User` object.) * </em> */ public replaceById(id: any, data: any = undefined): Observable<any> { let method: string = "POST"; let url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + "/Users/:id/replace"; let routeParams: any = { id: id }; let postBody: any = { data: data }; let urlParams: any = {}; let result = this.request(method, url, routeParams, urlParams, postBody); return result; } /** * Find all instances of the model matched by filter from the data source. * * @param object filter Filter defining fields, where, include, order, offset, and limit * * @returns object[] An empty reference that will be * populated with the actual data once the response is returned * from the server. * * <em> * (The remote method definition does not provide any description. * This usually means the response is a `User` object.) * </em> */ public find(filter: LoopBackFilter = undefined): Observable<Array<User>> { let method: string = "GET"; let url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + "/Users"; let routeParams: any = {}; let postBody: any = {}; let urlParams: any = {}; if (filter) urlParams.filter = filter; let result = this.request(method, url, routeParams, urlParams, postBody); return result.map((instances: Array<User>) => instances.map((instance: User) => new User(instance)) ); } /** * Find first instance of the model matched by filter from the data source. * * @param object filter Filter defining fields, where, include, order, offset, and limit * * @returns object An empty reference that will be * populated with the actual data once the response is returned * from the server. * * <em> * (The remote method definition does not provide any description. * This usually means the response is a `User` object.) * </em> */ public findOne(filter: LoopBackFilter = undefined): Observable<User> { let method: string = "GET"; let url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + "/Users/findOne"; let routeParams: any = {}; let postBody: any = {}; let urlParams: any = {}; if (filter) urlParams.filter = filter; let result = this.request(method, url, routeParams, urlParams, postBody); return result.map((instance: User) => new User(instance)); } /** * Update instances of the model matched by {{where}} from the data source. * * @param object where Criteria to match model instances * * @param object data Request data. * * This method expects a subset of model properties as request parameters. * * @returns object An empty reference that will be * populated with the actual data once the response is returned * from the server. * * Information related to the outcome of the operation */ public updateAll(where: any = undefined, data: any = undefined): Observable<any> { let method: string = "POST"; let url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + "/Users/update"; let routeParams: any = {}; let postBody: any = { data: data }; let urlParams: any = {}; if (where) urlParams.where = where; let result = this.request(method, url, routeParams, urlParams, postBody); return result; } /** * Delete a model instance by {{id}} from the data source. * * @param any id Model id * * @returns object An empty reference that will be * populated with the actual data once the response is returned * from the server. * * <em> * (The remote method definition does not provide any description. * This usually means the response is a `User` object.) * </em> */ public deleteById(id: any): Observable<any> { let method: string = "DELETE"; let url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + "/Users/:id"; let routeParams: any = { id: id }; let postBody: any = {}; let urlParams: any = {}; let result = this.request(method, url, routeParams, urlParams, postBody); return result; } /** * Count instances of the model matched by where from the data source. * * @param object where Criteria to match model instances * * @returns object An empty reference that will be * populated with the actual data once the response is returned * from the server. * * Data properties: * * - `count` – `{number}` - */ public count(where: any = undefined): Observable<any> { let method: string = "GET"; let url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + "/Users/count"; let routeParams: any = {}; let postBody: any = {}; let urlParams: any = {}; if (where) urlParams.where = where; let result = this.request(method, url, routeParams, urlParams, postBody); return result; } /** * Patch attributes for a model instance and persist it into the data source. * * @param any id User id * * @param object data Request data. * * This method expects a subset of model properties as request parameters. * * @returns object An empty reference that will be * populated with the actual data once the response is returned * from the server. * * <em> * (The remote method definition does not provide any description. * This usually means the response is a `User` object.) * </em> */ public updateAttributes(id: any, data: any = undefined): Observable<any> { let method: string = "PUT"; let url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + "/Users/:id"; let routeParams: any = { id: id }; let postBody: any = { data: data }; let urlParams: any = {}; let result = this.request(method, url, routeParams, urlParams, postBody); return result; } /** * Create a change stream. * * @param object data Request data. * * - `options` – `{object}` - * * @returns object An empty reference that will be * populated with the actual data once the response is returned * from the server. * * Data properties: * * - `changes` – `{ReadableStream}` - */ public createChangeStream(): Observable<any> { let url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + "/Users/change-stream"; let subject = new Subject(); if (typeof EventSource !== 'undefined') { let emit = (msg: any) => subject.next(JSON.parse(msg.data)); var source = new EventSource(url); source.addEventListener('data', emit); source.onerror = emit; } else { console.warn('SDK Builder: EventSource is not supported'); } return subject.asObservable(); } /** * Login a user with username/email and password. * * @param string include Related objects to include in the response. See the description of return value for more details. * Default value: `user`. * * - `rememberMe` - `boolean` - Whether the authentication credentials * should be remembered in localStorage across app/browser restarts. * Default: `true`. * * @param object data Request data. * * This method expects a subset of model properties as request parameters. * * @returns object An empty reference that will be * populated with the actual data once the response is returned * from the server. * * The response body contains properties of the AccessToken created on login. * Depending on the value of `include` parameter, the body may contain additional properties: * * - `user` - `U+007BUserU+007D` - Data of the currently logged in user. (`include=user`) * * */ public login(credentials: any, include: any = 'user', rememberMe: boolean = true): Observable<any> { let method: string = "POST"; let url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + "/Users/login"; let routeParams: any = {}; let postBody: any = { credentials: credentials }; let urlParams: any = {}; if (include) urlParams.include = include; let result = this.request(method, url, routeParams, urlParams, postBody) .map( (response: SDKToken) => { response.rememberMe = rememberMe; this.auth.setUser(response); this.auth.save(); return response; } ); return result; } /** * Logout a user with access token. * * @param object data Request data. * * - `access_token` – `{string}` - Do not supply this argument, it is automatically extracted from request headers. * * @returns object An empty reference that will be * populated with the actual data once the response is returned * from the server. * * This method returns no data. */ public logout(): Observable<any> { let method: string = "POST"; let url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + "/Users/logout"; let routeParams: any = {}; let postBody: any = {}; let urlParams: any = {}; urlParams.access_token = this.auth.getAccessTokenId(); this.auth.clear(); let result = this.request(method, url, routeParams, urlParams, postBody); return result; } /** * Confirm a user registration with email verification token. * * @param string uid * * @param string token * * @param string redirect * * @returns object An empty reference that will be * populated with the actual data once the response is returned * from the server. * * This method returns no data. */ public confirm(uid: any, token: any, redirect: any = undefined): Observable<any> { let method: string = "GET"; let url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + "/Users/confirm"; let routeParams: any = {}; let postBody: any = {}; let urlParams: any = {}; if (uid) urlParams.uid = uid; if (token) urlParams.token = token; if (redirect) urlParams.redirect = redirect; let result = this.request(method, url, routeParams, urlParams, postBody); return result; } /** * Reset password for a user with email. * * @param object data Request data. * * This method expects a subset of model properties as request parameters. * * @returns object An empty reference that will be * populated with the actual data once the response is returned * from the server. * * This method returns no data. */ public resetPassword(options: any): Observable<any> { let method: string = "POST"; let url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + "/Users/reset"; let routeParams: any = {}; let postBody: any = { options: options }; let urlParams: any = {}; let result = this.request(method, url, routeParams, urlParams, postBody); return result; } /** * Creates a new instance in accessTokens of this model. * * @param any id User id * * @param object data Request data. * * This method expects a subset of model properties as request parameters. * * @returns object[] An empty reference that will be * populated with the actual data once the response is returned * from the server. * * <em> * (The remote method definition does not provide any description. * This usually means the response is a `User` object.) * </em> */ public createManyAccessTokens(id: any, data: Array<any> = undefined): Observable<any> { let method: string = "POST"; let url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + "/Users/:id/accessTokens"; let routeParams: any = { id: id }; let postBody: any = { data: data }; let urlParams: any = {}; let result = this.request(method, url, routeParams, urlParams, postBody); return result; } /** * Create a new instance of the model and persist it into the data source. * * @param object data Request data. * * This method expects a subset of model properties as request parameters. * * @returns object[] An empty reference that will be * populated with the actual data once the response is returned * from the server. * * <em> * (The remote method definition does not provide any description. * This usually means the response is a `User` object.) * </em> */ public createMany(data: Array<any> = undefined): Observable<Array<User>> { let method: string = "POST"; let url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + "/Users"; let routeParams: any = {}; let postBody: any = { data: data }; let urlParams: any = {}; let result = this.request(method, url, routeParams, urlParams, postBody); return result.map((instances: Array<User>) => instances.map((instance: User) => new User(instance)) ); } /** * @ngdoc method * @name sdk.User#getCurrent * @methodOf sdk.User * * @description * * Get data of the currently logged user. Fail with HTTP result 401 * when there is no user logged in. * * @returns object An empty reference that will be * populated with the actual data once the response is returned * from the server. */ public getCurrent(): any { let method: string = "GET"; let url: string = LoopBackConfig.getPath() + "/" + LoopBackConfig.getApiVersion() + "/Users" + "/:id"; let id: any = this.auth.getCurrentUserId(); if (id == null) id = '__anonymous__'; let routeParams: any = { id: id }; let urlParams: any = {}; let postBody: any = {}; return this.request(method, url, routeParams, urlParams, postBody); } /** * Get data of the currently logged user that was returned by the last * call to {@link sdk.User#login} or * {@link sdk.User#getCurrent}. Return null when there * is no user logged in or the data of the current user were not fetched * yet. * * @returns object An Account instance. */ public getCachedCurrent() { return this.auth.getCurrentUserData(); } /** * Get data of the currently logged access tokern that was returned by the last * call to {@link sdk.User#login} * * @returns object An AccessToken instance. */ public getCurrentToken(): AccessToken { return this.auth.getToken(); } /** * @name sdk.User#isAuthenticated * * @returns {boolean} True if the current user is authenticated (logged in). */ public isAuthenticated() { return !(this.getCurrentId() === '' || this.getCurrentId() == null || this.getCurrentId() == 'null'); } /** * @name sdk.User#getCurrentId * * @returns object Id of the currently logged-in user or null. */ public getCurrentId() { return this.auth.getCurrentUserId(); } /** * The name of the model represented by this $resource, * i.e. `User`. */ public getModelName() { return "User"; } }
the_stack
export namespace ImageEvents { // Default Application export interface Application {} // Class /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * An alias in the file system */ export interface Alias { /** * the OSType identifying the application that created the alias */ creatorType(): any; /** * the application that will launch if the alias is opened */ defaultApplication(): any; /** * the OSType identifying the type of data contained in the alias */ fileType(): any; /** * The kind of alias, as shown in Finder */ kind(): string; /** * the version of the product (visible at the top of the "Get Info" window) */ productVersion(): string; /** * the short version of the application bundle referenced by the alias */ shortVersion(): string; /** * Is the alias a stationery pad? */ stationery(): boolean; /** * The type identifier of the alias */ typeIdentifier(): string; /** * the version of the application bundle referenced by the alias (visible at the bottom of the "Get Info" window) */ version(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The Classic domain in the file system */ export interface ClassicDomainObject { /** * The Apple Menu Items folder */ appleMenuFolder(): any; /** * The Control Panels folder */ controlPanelsFolder(): any; /** * The Control Strip Modules folder */ controlStripModulesFolder(): any; /** * The Classic Desktop folder */ desktopFolder(): any; /** * The Extensions folder */ extensionsFolder(): any; /** * The Fonts folder */ fontsFolder(): any; /** * The Launcher Items folder */ launcherItemsFolder(): any; /** * The Classic Preferences folder */ preferencesFolder(): any; /** * The Shutdown Items folder */ shutdownFolder(): any; /** * The StartupItems folder */ startupItemsFolder(): any; /** * The System folder */ systemFolder(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A disk in the file system */ export interface Disk { /** * the total number of bytes (free or used) on the disk */ capacity(): number; /** * Can the media be ejected (floppies, CD's, and so on)? */ ejectable(): boolean; /** * the file system format of this disk */ format(): any; /** * the number of free bytes left on the disk */ freeSpace(): number; /** * Ignore permissions on this disk? */ ignorePrivileges(): boolean; /** * Is the media a local volume (as opposed to a file server)? */ localVolume(): boolean; /** * the server on which the disk resides, AFP volumes only */ server(): any; /** * Is this disk the boot disk? */ startup(): boolean; /** * the zone in which the disk's server resides, AFP volumes only */ zone(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * An item stored in the file system */ export interface DiskItem { /** * Is the disk item busy? */ busyStatus(): boolean; /** * the folder or disk which has this disk item as an element */ container(): any; /** * the date on which the disk item was created */ creationDate(): any; /** * the name of the disk item as displayed in the User Interface */ displayedName(): string; /** * the unique ID of the disk item */ id(): string; /** * the date on which the disk item was last modified */ modificationDate(): any; /** * the name of the disk item */ name(): string; /** * the extension portion of the name */ nameExtension(): string; /** * Is the disk item a package? */ packageFolder(): boolean; /** * the file system path of the disk item */ path(): string; /** * the actual space used by the disk item on disk */ physicalSize(): number; /** * the POSIX file system path of the disk item */ POSIXPath(): string; /** * the logical size of the disk item */ size(): number; /** * the URL of the disk item */ URL(): string; /** * Is the disk item visible? */ visible(): boolean; /** * the volume on which the disk item resides */ volume(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A domain in the file system */ export interface Domain { /** * The Application Support folder */ applicationSupportFolder(): any; /** * The Applications folder */ applicationsFolder(): any; /** * The Desktop Pictures folder */ desktopPicturesFolder(): any; /** * The Folder Action Scripts folder */ folderActionScriptsFolder(): any; /** * The Fonts folder */ fontsFolder(): any; /** * the unique identifier of the domain */ id(): string; /** * The Library folder */ libraryFolder(): any; /** * the name of the domain */ name(): string; /** * The Preferences folder */ preferencesFolder(): any; /** * The Scripting Additions folder */ scriptingAdditionsFolder(): any; /** * The Scripts folder */ scriptsFolder(): any; /** * The Shared Documents folder */ sharedDocumentsFolder(): any; /** * The Speakable Items folder */ speakableItemsFolder(): any; /** * The Utilities folder */ utilitiesFolder(): any; /** * The Automator Workflows folder */ workflowsFolder(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A file in the file system */ export interface File { /** * the OSType identifying the application that created the file */ creatorType(): any; /** * the application that will launch if the file is opened */ defaultApplication(): any; /** * the OSType identifying the type of data contained in the file */ fileType(): any; /** * The kind of file, as shown in Finder */ kind(): string; /** * the version of the product (visible at the top of the "Get Info" window) */ productVersion(): string; /** * the short version of the file */ shortVersion(): string; /** * Is the file a stationery pad? */ stationery(): boolean; /** * The type identifier of the file */ typeIdentifier(): string; /** * the version of the file (visible at the bottom of the "Get Info" window) */ version(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A file package in the file system */ export interface FilePackage {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A folder in the file system */ export interface Folder {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The local domain in the file system */ export interface LocalDomainObject {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The network domain in the file system */ export interface NetworkDomainObject {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The system domain in the file system */ export interface SystemDomainObject {} /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The user domain in the file system */ export interface UserDomainObject { /** * The user's Desktop folder */ desktopFolder(): any; /** * The user's Documents folder */ documentsFolder(): any; /** * The user's Downloads folder */ downloadsFolder(): any; /** * The user's Favorites folder */ favoritesFolder(): any; /** * The user's Home folder */ homeFolder(): any; /** * The user's Movies folder */ moviesFolder(): any; /** * The user's Music folder */ musicFolder(): any; /** * The user's Pictures folder */ picturesFolder(): any; /** * The user's Public folder */ publicFolder(): any; /** * The user's Sites folder */ sitesFolder(): any; /** * The Temporary Items folder */ temporaryItemsFolder(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A monitor connected to the computer */ export interface Display { /** * the number of the display */ displayNumber(): number; /** * the profile for the display */ displayProfile(): any; /** * the name of the display */ name(): string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * An image contained in a file */ export interface Image { /** * bit depth of the image's color representation */ bitDepth(): any; /** * color space of the image's color representation */ colorSpace(): any; /** * the width and height of the image, respectively, in pixels */ dimensions(): any; /** * the profile, if any, embedded in the image */ embeddedProfile(): any; /** * file type of the image's file */ fileType(): any; /** * the file that contains the image */ imageFile(): any; /** * the folder or disk that encloses the file that contains the image */ location(): any; /** * the name of the image */ name(): string; /** * the horizontal and vertical pixel density of the image, respectively, in dots per inch */ resolution(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A metadata tag: EXIF, IPTC, etc. */ export interface MetadataTag { /** * the description of the tag's function */ description(): string; /** * the name of the tag */ name(): string; /** * the current setting of the tag */ value(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * A ColorSync ICC profile. */ export interface Profile { /** * the color space of the profile */ colorSpace(): any; /** * the connection space of the profile */ connectionSpace(): any; /** * the creation date of the profile */ creationDate(): any; /** * the creator type of the profile */ creator(): string; /** * the device class of the profile */ deviceClass(): any; /** * the device manufacturer of the profile */ deviceManufacturer(): string; /** * the device model of the profile */ deviceModel(): number; /** * the file location of the profile */ location(): any; /** * the description text of the profile */ name(): string; /** * the intended platform of the profile */ platform(): string; /** * the preferred CMM of the profile */ preferredCMM(): string; /** * the quality of the profile */ quality(): any; /** * the rendering intent of the profile */ renderingIntent(): any; /** * the size of the profile in bytes */ size(): number; /** * the version number of the profile */ version(): string; } // CLass Extension /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The Disk-Folder-File specific extensions to the application */ export interface Application { /** * The Application Support folder */ applicationSupportFolder(): any; /** * The user's Applications folder */ applicationsFolder(): any; /** * the collection of folders belonging to the Classic System */ classicDomain(): any; /** * The user's Desktop folder */ desktopFolder(): any; /** * The Desktop Pictures folder */ desktopPicturesFolder(): any; /** * The user's Documents folder */ documentsFolder(): any; /** * The user's Downloads folder */ downloadsFolder(): any; /** * The user's Favorites folder */ favoritesFolder(): any; /** * The user's Folder Action Scripts folder */ folderActionScriptsFolder(): any; /** * The Fonts folder */ fontsFolder(): any; /** * The Home folder of the currently logged in user */ homeFolder(): any; /** * The Library folder */ libraryFolder(): any; /** * the collection of folders residing on the Local machine */ localDomain(): any; /** * The user's Movies folder */ moviesFolder(): any; /** * The user's Music folder */ musicFolder(): any; /** * the collection of folders residing on the Network */ networkDomain(): any; /** * The user's Pictures folder */ picturesFolder(): any; /** * The user's Preferences folder */ preferencesFolder(): any; /** * The user's Public folder */ publicFolder(): any; /** * The Scripting Additions folder */ scriptingAdditionsFolder(): any; /** * The user's Scripts folder */ scriptsFolder(): any; /** * The Shared Documents folder */ sharedDocumentsFolder(): any; /** * The user's Sites folder */ sitesFolder(): any; /** * The Speakable Items folder */ speakableItemsFolder(): any; /** * the disk from which Mac OS X was loaded */ startupDisk(): any; /** * the collection of folders belonging to the System */ systemDomain(): any; /** * The Temporary Items folder */ temporaryItemsFolder(): any; /** * The user's Trash folder */ trash(): any; /** * the collection of folders belonging to the User */ userDomain(): any; /** * The Utilities folder */ utilitiesFolder(): any; /** * The Automator Workflows folder */ workflowsFolder(): any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ /** * The Image Events application */ export interface Application { /** * the default CMYK profile */ defaultCMYKProfile(): any; /** * the default CMYK profile location */ defaultCMYKProfileLocation(): any; /** * the default Gray profile */ defaultGrayProfile(): any; /** * the default Gray profile location */ defaultGrayProfileLocation(): any; /** * the default Lab profile */ defaultLabProfile(): any; /** * the default Lab profile location */ defaultLabProfileLocation(): any; /** * the default RGB profile */ defaultRGBProfile(): any; /** * the default RGB profile location */ defaultRGBProfileLocation(): any; /** * the default XYZ profile */ defaultXYZProfile(): any; /** * the default XYZ profile location */ defaultXYZProfileLocation(): any; /** * specifies preferred Color Management Module to use, or "automatic" */ preferredCMM(): string; /** * the ColorSync profile folder */ profileFolder(): any; /** * the time in seconds the application will idle before quitting; if set to zero, idle time will not cause the application to quit */ quitDelay(): number; /** * the default system profile */ systemProfile(): any; /** * the default system profile location */ systemProfileLocation(): any; } // Records // Function options /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface MoveOptionalParameter { /** * The new location for the disk item(s). */ to: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface CloseOptionalParameter { /** * Specifies whether changes should be saved before closing. */ saving?: any; /** * The file in which to save the image. */ savingIn?: string; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface CropOptionalParameter { /** * the width and height of the new image, respectively, in pixels, as a pair of integers */ toDimensions: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface EmbedOptionalParameter { /** * the profile to embed in the image */ withSource: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface FlipOptionalParameter { /** * flip horizontally */ horizontal?: boolean; /** * flip vertically */ vertical?: boolean; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface MatchOptionalParameter { /** * the destination profile for the match */ toDestination: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface PadOptionalParameter { /** * the width and height of the new image, respectively, in pixels, as a pair of integers */ toDimensions: any; /** * the RGB color values with which to pad the new image, as a list of integers */ withPadColor?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface RotateOptionalParameter { /** * rotate using an angle */ toAngle: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface SaveOptionalParameter { /** * file type in which to save the image ( default is to make no change ) */ as?: any; /** * Shall an icon be added? ( default is false ) */ icon?: boolean; /** * file path in which to save the image, in HFS or POSIX form */ in?: string; /** * Are the bytes to be compressed with PackBits? ( default is false, applies only to TIFF ) */ packBits?: boolean; /** * specifies the compression level of the resultant file ( applies only to JPEG ) */ withCompressionLevel?: any; } /** * This file was automatically generated by json-schema-to-typescript. * DO NOT MODIFY IT BY HAND. Instead, modify the source JSONSchema file, * and run json-schema-to-typescript to regenerate this file. */ export interface ScaleOptionalParameter { /** * scale using a scalefactor */ byFactor?: any; /** * scale using a max width/length */ toSize?: number; } } export interface ImageEvents extends ImageEvents.Application { // Functions /** * Delete disk item(s). * @param directParameter The disk item(s) to be deleted. * */ delete(directParameter: ImageEvents.DiskItem, ): void; /** * Move disk item(s) to a new location. * @param directParameter The disk item(s) to be moved. * @param option * @return undefined */ move(directParameter: {}, option?: ImageEvents.MoveOptionalParameter): void; /** * Open disk item(s) with the appropriate application. * @param directParameter The disk item(s) to be opened. * @return undefined */ open(directParameter: {}, ): ImageEvents.File; /** * Close an image * @param directParameter the object for the command * @param option * */ close(directParameter: any, option?: ImageEvents.CloseOptionalParameter): void; /** * Crop an image * @param directParameter the object for the command * @param option * */ crop(directParameter: any, option?: ImageEvents.CropOptionalParameter): void; /** * Embed an image with an ICC profile * @param directParameter the object for the command * @param option * */ embed(directParameter: any, option?: ImageEvents.EmbedOptionalParameter): void; /** * Flip an image * @param directParameter the object for the command * @param option * */ flip(directParameter: any, option?: ImageEvents.FlipOptionalParameter): void; /** * Match an image * @param directParameter the object for the command * @param option * */ match(directParameter: any, option?: ImageEvents.MatchOptionalParameter): void; /** * Pad an image * @param directParameter the object for the command * @param option * */ pad(directParameter: any, option?: ImageEvents.PadOptionalParameter): void; /** * Rotate an image * @param directParameter the object for the command * @param option * */ rotate(directParameter: any, option?: ImageEvents.RotateOptionalParameter): void; /** * Save an image to a file in one of various formats * @param directParameter the object for the command * @param option * @return undefined */ save(directParameter: any, option?: ImageEvents.SaveOptionalParameter): ImageEvents.Alias; /** * Scale an image * @param directParameter the object for the command * @param option * */ scale(directParameter: any, option?: ImageEvents.ScaleOptionalParameter): void; /** * Remove any embedded ICC profiles from an image * @param directParameter the object for the command * */ unembed(directParameter: any, ): void; }
the_stack
import jsplumb from 'jsplumb' import {GanttTask} from '../../core/logic/task/task.factory' export default function (GanttDependency, GanttDependenciesEvents, GanttDependencyTaskMouseHandler) { 'ngInject' let DependenciesManager = function (gantt, pluginScope, api) { let self = this this.gantt = gantt this.pluginScope = pluginScope this.api = api this.api.registerEvent('dependencies', 'add') this.api.registerEvent('dependencies', 'change') this.api.registerEvent('dependencies', 'remove') this.plumb = jsplumb.jsPlumb ? jsplumb.jsPlumb.getInstance() : jsplumb.getInstance() // Workaround for build issue. this.plumb.importDefaults(this.pluginScope.jsPlumbDefaults) this.dependenciesFrom = {} this.dependenciesTo = {} this.tasksList = [] this.tasks = {} this.events = new GanttDependenciesEvents(this) this.pluginScope.$watch('enabled', function (newValue, oldValue) { if (newValue !== oldValue) { self.refresh() } }) this.pluginScope.$watch('readOnly', function (newValue, oldValue) { if (newValue !== oldValue) { self.setTasks(self.tasksList) self.refresh() } }) this.pluginScope.$watch('jsPlumbDefaults', function (newValue, oldValue) { if (newValue !== oldValue) { self.plumb.importDefaults(newValue) self.refresh() } }, true) /** * Add all dependencies defined from a task. Dependencies will be added only if plugin is enabled. * * @param task * @param allowPartial if true, dependency linking to a missing task will still be added. */ this.addDependenciesFromTask = function (task, allowPartial) { if (this.pluginScope.enabled) { let taskDependencies = task.model.dependencies if (taskDependencies !== undefined && taskDependencies) { if (!Array.isArray(taskDependencies)) { taskDependencies = [taskDependencies] task.model.dependencies = taskDependencies } // tslint:disable:one-variable-per-declaration for (let i = 0, l = taskDependencies.length; i < l; i++) { let dependency = self.addDependency(task, taskDependencies[i], allowPartial) if (dependency) { dependency.connect() } } } } } /** * Remove all dependencies defined for a task. * * @param task * @param keepConnection if true, dependency will not be disconnected. */ this.removeDependenciesFromTask = function (task, keepConnection) { let dependencies = this.getTaskDependencies(task) if (dependencies) { for (let dependency of dependencies) { if (!keepConnection) { dependency.disconnect() } self.removeDependency(dependency) } } } /** * Add definition of a dependency. * * @param task Task defining the dependency. * @param model Model object for the dependency. * @param allowPartial if true, dependency linking to a missing task will still be added. */ this.addDependency = function (task, model, allowPartial) { let dependency = new GanttDependency(this, task, model) let fromTaskId = dependency.getFromTaskId() let fromTask = dependency.getFromTask() let toTaskId = dependency.getToTaskId() let toTask = dependency.getToTask() let manager = dependency.manager if (!(fromTaskId in this.dependenciesFrom)) { this.dependenciesFrom[fromTaskId] = [] } if (!(toTaskId in this.dependenciesTo)) { this.dependenciesTo[toTaskId] = [] } if (!allowPartial && (!toTask || !fromTask)) { // Partial dependency is not allowed, remove it. this.removeDependency(dependency, true) manager.api.dependencies.raise.remove(dependency) return null } else { if (fromTaskId) { this.dependenciesFrom[fromTaskId].push(dependency) } if (toTaskId) { this.dependenciesTo[toTaskId].push(dependency) } } return dependency } /** * Remove definition of a dependency * * @param dependency Dependency object * @param keepConnection if true, dependency will not be disconnected. */ this.removeDependency = function (dependency, keepConnection) { let fromDependencies = this.dependenciesFrom[dependency.getFromTaskId()] let fromRemove = [] let i if (fromDependencies) { for (i = 0; i < fromDependencies.length; i++) { if (dependency === fromDependencies[i]) { fromRemove.push(dependency) } } } let toDependencies = this.dependenciesTo[dependency.getToTaskId()] let toRemove = [] if (toDependencies) { for (i = 0; i < toDependencies.length; i++) { if (dependency === toDependencies[i]) { toRemove.push(dependency) } } } for (i = 0; i < fromRemove.length; i++) { if (!keepConnection) { fromRemove[i].disconnect() } fromDependencies.splice(fromDependencies.indexOf(dependency), 1) } for (i = 0; i < toRemove.length; i++) { if (!keepConnection) { toRemove[i].disconnect() } toDependencies.splice(toDependencies.indexOf(dependency), 1) } if (this.dependenciesFrom[dependency.getFromTaskId()] && this.dependenciesFrom[dependency.getFromTaskId()].length === 0) { delete this.dependenciesFrom[dependency.getFromTaskId()] } if (this.dependenciesTo[dependency.getToTaskId()] && this.dependenciesTo[dependency.getToTaskId()].length === 0) { delete this.dependenciesTo[dependency.getToTaskId()] } } this.getTaskDependencies = function (task: GanttTask) { let dependencies = [] let fromDependencies = self.dependenciesFrom[task.model.id] if (fromDependencies) { dependencies = dependencies.concat(fromDependencies) } let toDependencies = self.dependenciesTo[task.model.id] if (toDependencies) { dependencies = dependencies.concat(toDependencies) } return dependencies } this.setDraggingConnection = function (connection) { if (connection) { self.draggingConnection = connection for (let taskId in self.tasks) { let task = self.tasks[taskId] task.dependencies.mouseHandler.release() } } else { self.draggingConnection = undefined for (let taskId in self.tasks) { let task = self.tasks[taskId] task.dependencies.mouseHandler.install() } } } let isTaskEnabled = function (task) { let rowDependencies = task.row.model.dependencies if (rowDependencies !== undefined) { return rowDependencies !== false } let taskDependencies = task.model.dependencies if (taskDependencies !== undefined) { return taskDependencies !== false } return true } let addTaskEndpoints = function (task) { if (!task.dependencies) { task.dependencies = {} } task.dependencies.endpoints = [] if (self.pluginScope.endpoints && task.$element) { for (let endpoint of self.pluginScope.endpoints) { let endpointObject = self.plumb.addEndpoint(task.$element, endpoint) endpointObject.setVisible(false, true, true) // hide endpoint endpointObject.$task = task task.dependencies.endpoints.push(endpointObject) } } } let removeTaskEndpoint = function (task) { if (task.dependencies.endpoints) { for (let endpointObject of task.dependencies.endpoints) { self.plumb.deleteEndpoint(endpointObject) endpointObject.$task = undefined } task.dependencies.endpoints = undefined } } let addTaskMouseHandler = function (task) { if (!task.dependencies) { task.dependencies = {} } if (!self.pluginScope.readOnly) { task.dependencies.mouseHandler = new GanttDependencyTaskMouseHandler(self, task) task.dependencies.mouseHandler.install() } } let removeTaskMouseHandler = function (task) { if (task.dependencies.mouseHandler) { task.dependencies.mouseHandler.release() task.dependencies.mouseHandler = undefined } } /** * Set tasks objects that can be used to display dependencies. * * @param tasks */ this.setTasks = function (tasks: GanttTask[]) { for (let taskId in self.tasks) { let task = self.tasks[taskId] removeTaskMouseHandler(task) removeTaskEndpoint(task) } let newTasks = {} let tasksList = [] for (let task of tasks) { if (isTaskEnabled(task)) { newTasks[task.model.id] = task tasksList.push(task) addTaskEndpoints(task) addTaskMouseHandler(task) } } self.tasks = newTasks self.tasksList = tasks } let disconnectTaskDependencies = function (task) { let dependencies = self.getTaskDependencies(task) if (dependencies) { for (let dependency of dependencies) { dependency.disconnect() } } return dependencies } let connectTaskDependencies = function (task) { let dependencies = self.getTaskDependencies(task) if (dependencies) { for (let dependency of dependencies) { dependency.connect() } } return dependencies } /** * Set task object in replacement of an existing with the same id. * * @param task */ this.setTask = function (task) { self.plumb.setSuspendDrawing(true) try { let oldTask = self.tasks[task.model.id] if (oldTask !== undefined) { disconnectTaskDependencies(oldTask) removeTaskMouseHandler(oldTask) removeTaskEndpoint(oldTask) } if (isTaskEnabled(task)) { self.tasks[task.model.id] = task addTaskEndpoints(task) addTaskMouseHandler(task) connectTaskDependencies(task) } } finally { self.plumb.setSuspendDrawing(false, true) } } /** * Retrieve the task from it's id. * * @param taskId id of the task element to retrieve. * @returns {*} */ this.getTask = function (taskId) { return self.tasks[taskId] } let getSourceEndpoints = function (task) { return task.dependencies.endpoints.filter(function (endpoint) { return endpoint.isSource }) } let getTargetEndpoints = function (task) { return task.dependencies.endpoints.filter(function (endpoint) { return endpoint.isTarget }) } /** * Connects two tasks together using source endpoint from fromTask and target endpoint from toTask. * * @param fromTask * @param toTask * @param model * @returns connection object */ this.connect = function (fromTask, toTask, model) { let sourceEndpoints = getSourceEndpoints(fromTask) let targetEndpoints = getTargetEndpoints(toTask) if (sourceEndpoints && targetEndpoints) { let sourceEndpoint let targetEndpoint if (model.connectParameters && model.connectParameters.sourceEndpointIndex) { sourceEndpoint = sourceEndpoints[model.connectParameters.sourceEndpointIndex] } else { sourceEndpoint = sourceEndpoints[0] } if (model.connectParameters && model.connectParameters.targetEndpointIndex) { targetEndpoint = targetEndpoints[model.connectParameters.targetEndpointIndex] } else { targetEndpoint = targetEndpoints[0] } let connection = self.plumb.connect({ source: sourceEndpoint, target: targetEndpoint, parameters: { from: fromTask, to: toTask } // cssClass: 'gantt-endpoint start-endpoint target-endpoint connect-' + fromTask.model.id + '-' + toTask.model.id, }, model.connectParameters) connection.canvas.setAttribute('data-fromId', fromTask.model.id) connection.canvas.setAttribute('data-toId', toTask.model.id) return connection } } /** * Get all defined dependencies. * * @returns {Array} */ this.getDependencies = function () { let allDependencies = [] for (let fromId in this.dependenciesFrom) { let dependencies = this.dependenciesFrom[fromId] for (let dependency of dependencies) { if (!(dependency in allDependencies)) { allDependencies.push(dependency) } } } return allDependencies } /** * Refresh jsplumb status based on tasks dependencies models. */ this.refresh = function (tasks) { self.plumb.setSuspendDrawing(true) try { let tasksDependencies let i if (tasks && !Array.isArray(tasks)) { tasks = [tasks] } if (tasks === undefined) { tasks = this.tasks tasksDependencies = this.getDependencies() } else { tasksDependencies = [] for (let task of tasks) { let taskDependencies = self.getTaskDependencies(task) for (let taskDependency of taskDependencies) { if (!(taskDependency in tasksDependencies)) { tasksDependencies.push(taskDependency) } } } } for (i = 0; i < tasksDependencies.length; i++) { self.removeDependency(tasksDependencies[i]) } for (let taskId in tasks) { let task = tasks[taskId] self.addDependenciesFromTask(task) } } finally { self.plumb.setSuspendDrawing(false, true) } } this.api.registerMethod('dependencies', 'refresh', this.refresh, this) } return DependenciesManager }
the_stack
import { Injectable, Type } from '@angular/core'; import { CoreDelegate, CoreDelegateHandler } from '@classes/delegate'; import { CoreWSFile } from '@services/ws'; import { makeSingleton } from '@singletons'; import { CoreQuestionDefaultHandler } from './handlers/default-question'; import { CoreQuestionQuestionParsed, CoreQuestionsAnswers } from './question'; /** * Interface that all question type handlers must implement. */ export interface CoreQuestionHandler extends CoreDelegateHandler { /** * Type of the question the handler supports. E.g. 'qtype_calculated'. */ type: string; /** * Return the Component to use to display the question. * It's recommended to return the class of the component, but you can also return an instance of the component. * * @param question The question to render. * @return The component (or promise resolved with component) to use, undefined if not found. */ getComponent(question: CoreQuestionQuestionParsed): undefined | Type<unknown> | Promise<Type<unknown>>; /** * Return the name of the behaviour to use for the question. * If the question should use the default behaviour you shouldn't implement this function. * * @param question The question. * @param behaviour The default behaviour. * @return The behaviour to use. */ getBehaviour?(question: CoreQuestionQuestionParsed, behaviour: string): string; /** * Check if a question can be submitted. * If a question cannot be submitted it should return a message explaining why (translated or not). * * @param question The question. * @return Prevent submit message. Undefined or empty if can be submitted. */ getPreventSubmitMessage?(question: CoreQuestionQuestionParsed): string | undefined; /** * Check if there's a validation error with the offline data. * * @param question The question. * @param answers Object with the question offline answers (without prefix). * @param onlineError Online validation error. * @param component The component the question is related to. * @param componentId Component ID. * @return Error message if there's a validation error, undefined otherwise. */ getValidationError?( question: CoreQuestionQuestionParsed, answers: CoreQuestionsAnswers, onlineError: string | undefined, component: string, componentId: string | number, ): string | undefined; /** * Check if a response is complete. * * @param question The question. * @param answers Object with the question answers (without prefix). * @param component The component the question is related to. * @param componentId Component ID. * @return 1 if complete, 0 if not complete, -1 if cannot determine. */ isCompleteResponse?( question: CoreQuestionQuestionParsed, answers: CoreQuestionsAnswers, component: string, componentId: string | number, ): number; /** * Check if a student has provided enough of an answer for the question to be graded automatically, * or whether it must be considered aborted. * * @param question The question. * @param answers Object with the question answers (without prefix). * @param component The component the question is related to. * @param componentId Component ID. * @return 1 if gradable, 0 if not gradable, -1 if cannot determine. */ isGradableResponse?( question: CoreQuestionQuestionParsed, answers: CoreQuestionsAnswers, component: string, componentId: string | number, ): number; /** * Check if two responses are the same. * * @param question Question. * @param prevAnswers Object with the previous question answers. * @param newAnswers Object with the new question answers. * @return Whether they're the same. */ isSameResponse?( question: CoreQuestionQuestionParsed, prevAnswers: CoreQuestionsAnswers, newAnswers: CoreQuestionsAnswers, component: string, componentId: string | number, ): boolean; /** * Prepare and add to answers the data to send to server based in the input. Return promise if async. * * @param question Question. * @param answers The answers retrieved from the form. Prepared answers must be stored in this object. * @param offline Whether the data should be saved in offline. * @param component The component the question is related to. * @param componentId Component ID. * @param siteId Site ID. If not defined, current site. * @return Return a promise resolved when done if async, void if sync. */ prepareAnswers?( question: CoreQuestionQuestionParsed, answers: CoreQuestionsAnswers, offline: boolean, component: string, componentId: string | number, siteId?: string, ): void | Promise<void>; /** * Validate if an offline sequencecheck is valid compared with the online one. * This function only needs to be implemented if a specific compare is required. * * @param question The question. * @param offlineSequenceCheck Sequence check stored in offline. * @return Whether sequencecheck is valid. */ validateSequenceCheck?(question: CoreQuestionQuestionParsed, offlineSequenceCheck: string): boolean; /** * Get the list of files that needs to be downloaded in addition to the files embedded in the HTML. * * @param question Question. * @param usageId Usage ID. * @return List of files or URLs. */ getAdditionalDownloadableFiles?(question: CoreQuestionQuestionParsed, usageId?: number): CoreWSFile[]; /** * Clear temporary data after the data has been saved. * * @param question Question. * @param component The component the question is related to. * @param componentId Component ID. * @return If async, promise resolved when done. */ clearTmpData?(question: CoreQuestionQuestionParsed, component: string, componentId: string | number): void | Promise<void>; /** * Delete any stored data for the question. * * @param question Question. * @param component The component the question is related to. * @param componentId Component ID. * @param siteId Site ID. If not defined, current site. * @return If async, promise resolved when done. */ deleteOfflineData?( question: CoreQuestionQuestionParsed, component: string, componentId: string | number, siteId?: string, ): void | Promise<void>; /** * Prepare data to send when performing a synchronization. * * @param question Question. * @param answers Answers of the question, without the prefix. * @param component The component the question is related to. * @param componentId Component ID. * @param siteId Site ID. If not defined, current site. * @return If async, promise resolved when done. */ prepareSyncData?( question: CoreQuestionQuestionParsed, answers: CoreQuestionsAnswers, component: string, componentId: string | number, siteId?: string, ): void | Promise<void>; } /** * Delegate to register question handlers. */ @Injectable({ providedIn: 'root' }) export class CoreQuestionDelegateService extends CoreDelegate<CoreQuestionHandler> { protected handlerNameProperty = 'type'; constructor(protected defaultHandler: CoreQuestionDefaultHandler) { super('CoreQuestionDelegate', true); } /** * Get the behaviour to use for a certain question type. * E.g. 'qtype_essay' uses 'manualgraded'. * * @param question The question. * @param behaviour The default behaviour. * @return The behaviour to use. */ getBehaviourForQuestion(question: CoreQuestionQuestionParsed, behaviour: string): string { const type = this.getTypeName(question); const questionBehaviour = this.executeFunctionOnEnabled<string>(type, 'getBehaviour', [question, behaviour]); return questionBehaviour || behaviour; } /** * Get the directive to use for a certain question type. * * @param question The question to render. * @return Promise resolved with component to use, undefined if not found. */ async getComponentForQuestion(question: CoreQuestionQuestionParsed): Promise<Type<unknown> | undefined> { const type = this.getTypeName(question); return this.executeFunctionOnEnabled(type, 'getComponent', [question]); } /** * Check if a question can be submitted. * If a question cannot be submitted it should return a message explaining why (translated or not). * * @param question Question. * @return Prevent submit message. Undefined or empty if can be submitted. */ getPreventSubmitMessage(question: CoreQuestionQuestionParsed): string | undefined { const type = this.getTypeName(question); return this.executeFunctionOnEnabled<string>(type, 'getPreventSubmitMessage', [question]); } /** * Given a type name, return the full name of that type. E.g. 'calculated' -> 'qtype_calculated'. * * @param type Type to treat. * @return Type full name. */ protected getFullTypeName(type: string): string { return 'qtype_' + type; } /** * Given a question, return the full name of its question type. * * @param question Question. * @return Type name. */ protected getTypeName(question: CoreQuestionQuestionParsed): string { return this.getFullTypeName(question.type); } /** * Check if a response is complete. * * @param question The question. * @param answers Object with the question answers (without prefix). * @param component The component the question is related to. * @param componentId Component ID. * @return 1 if complete, 0 if not complete, -1 if cannot determine. */ isCompleteResponse( question: CoreQuestionQuestionParsed, answers: CoreQuestionsAnswers, component: string, componentId: string | number, ): number { const type = this.getTypeName(question); const isComplete = this.executeFunctionOnEnabled<number>( type, 'isCompleteResponse', [question, answers, component, componentId], ); return isComplete ?? -1; } /** * Check if a student has provided enough of an answer for the question to be graded automatically, * or whether it must be considered aborted. * * @param question The question. * @param answers Object with the question answers (without prefix). * @param component The component the question is related to. * @param componentId Component ID. * @return 1 if gradable, 0 if not gradable, -1 if cannot determine. */ isGradableResponse( question: CoreQuestionQuestionParsed, answers: CoreQuestionsAnswers, component: string, componentId: string | number, ): number { const type = this.getTypeName(question); const isGradable = this.executeFunctionOnEnabled<number>( type, 'isGradableResponse', [question, answers, component, componentId], ); return isGradable ?? -1; } /** * Check if two responses are the same. * * @param question Question. * @param prevAnswers Object with the previous question answers. * @param newAnswers Object with the new question answers. * @return Whether they're the same. */ isSameResponse( question: CoreQuestionQuestionParsed, prevAnswers: CoreQuestionsAnswers, newAnswers: CoreQuestionsAnswers, component: string, componentId: string | number, ): boolean { const type = this.getTypeName(question); return !!this.executeFunctionOnEnabled(type, 'isSameResponse', [question, prevAnswers, newAnswers, component, componentId]); } /** * Check if a question type is supported. * * @param type Question type. * @return Whether it's supported. */ isQuestionSupported(type: string): boolean { return this.hasHandler(this.getFullTypeName(type), true); } /** * Prepare the answers for a certain question. * * @param question Question. * @param answers The answers retrieved from the form. Prepared answers must be stored in this object. * @param offline Whether the data should be saved in offline. * @param component The component the question is related to. * @param componentId Component ID. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when data has been prepared. */ async prepareAnswersForQuestion( question: CoreQuestionQuestionParsed, answers: CoreQuestionsAnswers, offline: boolean, component: string, componentId: string | number, siteId?: string, ): Promise<void> { const type = this.getTypeName(question); await this.executeFunctionOnEnabled( type, 'prepareAnswers', [question, answers, offline, component, componentId, siteId], ); } /** * Validate if an offline sequencecheck is valid compared with the online one. * * @param question The question. * @param offlineSequenceCheck Sequence check stored in offline. * @return Whether sequencecheck is valid. */ validateSequenceCheck(question: CoreQuestionQuestionParsed, offlineSequenceCheck: string): boolean { const type = this.getTypeName(question); return !!this.executeFunctionOnEnabled(type, 'validateSequenceCheck', [question, offlineSequenceCheck]); } /** * Get the list of files that needs to be downloaded in addition to the files embedded in the HTML. * * @param question Question. * @param usageId Usage ID. * @return List of files or URLs. */ getAdditionalDownloadableFiles(question: CoreQuestionQuestionParsed, usageId?: number): CoreWSFile[] { const type = this.getTypeName(question); return this.executeFunctionOnEnabled(type, 'getAdditionalDownloadableFiles', [question, usageId]) || []; } /** * Clear temporary data after the data has been saved. * * @param question Question. * @param component The component the question is related to. * @param componentId Component ID. * @return If async, promise resolved when done. */ clearTmpData(question: CoreQuestionQuestionParsed, component: string, componentId: string | number): void | Promise<void> { const type = this.getTypeName(question); return this.executeFunctionOnEnabled(type, 'clearTmpData', [question, component, componentId]); } /** * Clear temporary data after the data has been saved. * * @param question Question. * @param component The component the question is related to. * @param componentId Component ID. * @param siteId Site ID. If not defined, current site. * @return If async, promise resolved when done. */ async deleteOfflineData( question: CoreQuestionQuestionParsed, component: string, componentId: string | number, siteId?: string, ): Promise<void> { const type = this.getTypeName(question); await this.executeFunctionOnEnabled(type, 'deleteOfflineData', [question, component, componentId, siteId]); } /** * Prepare data to send when performing a synchronization. * * @param question Question. * @param answers Answers of the question, without the prefix. * @param component The component the question is related to. * @param componentId Component ID. * @param siteId Site ID. If not defined, current site. * @return If async, promise resolved when done. */ async prepareSyncData( question: CoreQuestionQuestionParsed, answers: CoreQuestionsAnswers, component: string, componentId: string | number, siteId?: string, ): Promise<void> { const type = this.getTypeName(question); await this.executeFunctionOnEnabled(type, 'prepareSyncData', [question, answers, component, componentId, siteId]); } /** * Check if there's a validation error with the offline data. * * @param question The question. * @param answers Object with the question offline answers (without prefix). * @param onlineError Online validation error. * @param component The component the question is related to. * @param componentId Component ID. * @return Error message if there's a validation error, undefined otherwise. */ getValidationError( question: CoreQuestionQuestionParsed, answers: CoreQuestionsAnswers, onlineError: string | undefined, component: string, componentId: string | number, ): string | undefined { const type = this.getTypeName(question); return this.executeFunctionOnEnabled(type, 'getValidationError', [question, answers, onlineError, component, componentId]); } } export const CoreQuestionDelegate = makeSingleton(CoreQuestionDelegateService);
the_stack
import React, { Component } from 'react' import { StyleSheet, Text, View, Image, Dimensions, TouchableNativeFeedback, TextInput, AsyncStorage, Linking, Animated, Keyboard, Platform } from 'react-native' import Ionicons from 'react-native-vector-icons/Ionicons' import { standardColor, accentColor } from '../../constant/colorConfig' import { safeLogin, registURL } from '../../dao/login' import { fetchUser } from '../../dao' declare var global class Login extends Component<any, any> { constructor(props) { super(props) this.state = { psnid: '', password: '', accountMarginTop: new Animated.Value(0), passwordMarginTop: new Animated.Value(0), avoidKeyboardMarginTop: new Animated.Value(0), addIcon: false } } _pressButton = () => { this.props.navigation.goBack() } login = async () => { const { psnid, password } = this.state if (psnid === '' || password === '') { global.toast && global.toast('账号或密码未输入', 2000) return } let { text: data, isOK }: any = await safeLogin(psnid, password) if (isOK) { await AsyncStorage.setItem('@psnid', psnid) const user = await fetchUser(psnid) await AsyncStorage.setItem('@userInfo', JSON.stringify(user)) global.toast && global.toast(`登录成功`, 2000) this.props.navigation.state.params.setLogin(psnid, user) this.props.navigation.goBack() } else { await AsyncStorage.removeItem('@psnid') await AsyncStorage.getItem('@psnid') global.toast && global.toast(`登录失败: ${data}`, 2000) } } regist = () => { Linking.canOpenURL(registURL).then(supported => { if (supported) Linking.openURL(registURL) else global.toast && global.toast(`未找到浏览器, 如果您使用了冰箱, 请先解冻浏览器`, 2000) }).catch(() => {}) } keyboardDidShowListener: any = false keyboardDidHideListener: any = false async componentWillMount() { this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', () => { Animated.spring(this.state.avoidKeyboardMarginTop, { toValue: 1, friction: 10, useNativeDriver: true }).start() }) this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', () => { Animated.spring(this.state.avoidKeyboardMarginTop, { toValue: 0, friction: 10, useNativeDriver: true }).start() }) const source = await Ionicons.getImageSource('ios-add', 24, '#fff') this.setState({ addIcon: source }) } componentWillUnmount() { this.keyboardDidHideListener.remove() this.keyboardDidShowListener.remove() } accountTextInput: any = false passwordTextInput: any = false onAccountTextFocus = () => { let text = this.accountTextInput._lastNativeText if (typeof text !== 'undefined' && text !== '') return Animated.spring(this.state.accountMarginTop, { toValue: 1, friction: 10 // useNativeDriver: true }).start() } onAccountTextBlur = () => { let text = this.accountTextInput._lastNativeText if (typeof text !== 'undefined' && text !== '') return Animated.spring(this.state.accountMarginTop, { toValue: 0, friction: 10 // useNativeDriver: true }).start() } onPasswordTextFocus = () => { let text = this.passwordTextInput._lastNativeText if (typeof text !== 'undefined' && text !== '') return Animated.spring(this.state.passwordMarginTop, { toValue: 1, friction: 10 // useNativeDriver: true }).start() } onPasswordTextBlur = () => { let text = this.passwordTextInput._lastNativeText if (typeof text !== 'undefined' && text !== '') return Animated.spring(this.state.passwordMarginTop, { toValue: 0, friction: 10 // useNativeDriver: true }).start() } onSubmit = () => { this.login() } focusNextField = (nextField) => { this[nextField].focus() } render() { // console.log('Loggin.js rendered'); let marginLeft = 40 const { modeInfo } = this.props.screenProps const { width: SCREEN_WIDTH, height: SCREEN_HEIGHT } = Dimensions.get('window') let avoidKeyboardStyle = { bottom: marginLeft * 1.5, top: SCREEN_HEIGHT / 10 * 4 - marginLeft * 1.5, transform: [{ translateY: this.state.avoidKeyboardMarginTop.interpolate({ inputRange: [0, 1], outputRange: [0, marginLeft - (SCREEN_HEIGHT / 10 * 4 - marginLeft * 1.5)] }) }] } let accountTextStyle = { transform: [{ translateY: this.state.accountMarginTop.interpolate({ inputRange: [0, 1], outputRange: [40, 10] }) }], // top: this.state.accountMarginTop.interpolate({ // inputRange: [0, 1], // outputRange: [40, 15] // }), color: this.state.accountMarginTop.interpolate({ inputRange: [0, 1], outputRange: [modeInfo.standardTextColor, modeInfo.standardColor] }), fontSize: this.state.accountMarginTop.interpolate({ inputRange: [0, 1], outputRange: [15, 12] }) } let passwordTextStyle = { transform: [{ translateY: this.state.passwordMarginTop.interpolate({ inputRange: [0, 1], outputRange: [40, 10] }) }], // top: this.state.passwordMarginTop.interpolate({ // inputRange: [0, 1], // outputRange: [40, 15] // }), color: this.state.passwordMarginTop.interpolate({ inputRange: [0, 1], outputRange: [modeInfo.standardTextColor, modeInfo.standardColor] }), fontSize: this.state.passwordMarginTop.interpolate({ inputRange: [0, 1], outputRange: [15, 12] }) } return ( <View style={{ flex: 1, backgroundColor: modeInfo.standardColor }}> <Animated.View collapsable={true} style={{ width: 56, height: 56, borderRadius: 30, backgroundColor: modeInfo.accentColor, position: 'absolute', /*top: this.state.avoidKeyboardMarginTop.interpolate({ inputRange: [0, 1], outputRange: [SCREEN_HEIGHT / 10 * 4 - marginLeft + 28, marginLeft + 28] }),*/ transform: [{ translateY: this.state.avoidKeyboardMarginTop.interpolate({ inputRange: [0, 1], outputRange: [(SCREEN_HEIGHT / 10 * 4 - marginLeft + 28), 28 + marginLeft * 1.5] }) }], right: 12, elevation: 6, zIndex: 1 }}> <TouchableNativeFeedback onPress={this.regist} background={TouchableNativeFeedback.SelectableBackgroundBorderless()} style={{ width: 56, height: 56, borderRadius: 30, flex: 1, zIndex: 1, backgroundColor: modeInfo.accentColor }}> <View style={{ borderRadius: 30 }}> {this.state.addIcon && (<Image source={this.state.addIcon} style={{ marginLeft: 16, marginTop: 16, width: 24, height: 24 }} />)} </View> </TouchableNativeFeedback> </Animated.View> <Animated.View style={[{ backgroundColor: modeInfo.backgroundColor, position: 'absolute', width: SCREEN_WIDTH - marginLeft * 2, height: 384, marginLeft: marginLeft, bottom: marginLeft, borderRadius: 5, elevation: 6 }, avoidKeyboardStyle]}> <View style={[styles.loginTextView, { marginLeft: marginLeft / 2 * 1.5, marginTop: 27 }]}> <Text style={[styles.mainFont, { fontSize: 30, marginLeft: 0, marginBottom: 0, color: modeInfo.accentColor }]}>登录</Text> </View> <View style={[styles.KeyboardAvoidingView, { width: SCREEN_WIDTH - marginLeft * 3 }]} > <View style={[styles.accountView, { marginTop: 5 }]}> <Animated.Text style={[{ color: modeInfo.standardTextColor, marginLeft: 5 }, accountTextStyle ]}> {'PSN ID'} </Animated.Text> <TextInput underlineColorAndroid={modeInfo.accentColor} onChange={({ nativeEvent }) => { this.setState({ psnid: nativeEvent.text }) }} ref={ref => this.accountTextInput = ref} onFocus={this.onAccountTextFocus} onBlur={this.onAccountTextBlur} blurOnSubmit={false} returnKeyType='next' onSubmitEditing={() => this.focusNextField('passwordTextInput')} style={[styles.textInput, { color: modeInfo.standardTextColor }]} placeholderTextColor={modeInfo.standardTextColor} /> </View> <View style={[styles.passwordView, { marginTop: 5 }]}> <Animated.Text style={[{ color: modeInfo.standardTextColor, marginLeft: 5 }, passwordTextStyle ]}> {'密码'} </Animated.Text> <TextInput underlineColorAndroid={modeInfo.accentColor} secureTextEntry={true} onChange={({ nativeEvent }) => { this.setState({ password: nativeEvent.text }) }} ref={ref => this.passwordTextInput = ref} onFocus={this.onPasswordTextFocus} onBlur={this.onPasswordTextBlur} onSubmitEditing={this.onSubmit} style={[styles.textInput, { color: modeInfo.standardTextColor }]} placeholderTextColor={modeInfo.standardTextColor} /> <Text style={[styles.openURL, { marginTop: 10, color: modeInfo.standardColor }]}>忘记密码</Text> </View> </View> <View style={[styles.customView, { width: SCREEN_WIDTH - marginLeft * 3 }]}> <View style={styles.submit}> <TouchableNativeFeedback onPress={this.login} > <View style={[styles.submitButton, {backgroundColor: modeInfo.accentColor}]}> <Text style={[styles.textInput, { color: modeInfo.backgroundColor, padding: 12 }]}>提交</Text> </View> </TouchableNativeFeedback> </View> {Platform.OS === 'ios' && <View style={styles.submit}> <TouchableNativeFeedback onPress={() => { this.props.navigation.goBack() }} > <View style={[styles.submitButton, { backgroundColor: undefined }]}> <Text style={[styles.textInput, { color: modeInfo.backgroundColor, padding: 12, color: modeInfo.accentColor }]}>返回</Text> </View> </TouchableNativeFeedback> </View> } </View> </Animated.View> </View> ) } } const width = Dimensions.get('window').width const styles = StyleSheet.create({ toolbar: { backgroundColor: standardColor, height: 56, elevation: 4 }, mainFont: { fontSize: 15, color: accentColor }, textInput: { fontSize: 15, minHeight: 40 }, customView: { flex: -1, marginTop: -20, width: width - 40, alignSelf: 'center', justifyContent: 'center', flexDirection: 'column' }, KeyboardAvoidingView: { flex: -1, marginTop: 0, width: width - 40, alignSelf: 'center', justifyContent: 'space-between', flexDirection: 'column' }, loginTextView: { flexDirection: 'column', justifyContent: 'space-between', margin: 10, marginTop: 20, marginBottom: 0 }, accountView: { flexDirection: 'column', justifyContent: 'space-between', marginLeft: 10, marginRight: 10, marginTop: 20 }, passwordView: { flexDirection: 'column', marginLeft: 10, marginRight: 10, marginTop: 20, marginBottom: 20 }, submit: { flex: -1, height: 30, margin: 10, marginTop: 40, marginBottom: 20 }, submitButton: { backgroundColor: accentColor, height: 40, alignItems: 'center', justifyContent: 'center' }, regist: { flex: 1, flexDirection: 'row', marginTop: 20, margin: 10 }, openURL: { color: accentColor, textDecorationLine: 'underline' } }) export default Login
the_stack
import { Credentials } from '@aws-amplify/core'; import { LocationClient, SearchPlaceIndexForTextCommand, SearchPlaceIndexForPositionCommand, } from '@aws-sdk/client-location'; import { AmazonLocationServiceProvider } from '../../src/Providers/AmazonLocationServiceProvider'; import { credentials, awsConfig, TestPlacePascalCase, testPlaceCamelCase, validGeofences, batchGeofencesCamelcaseResults, validGeometry, clockwiseGeofence, } from '../testData'; import { createGeofenceInputArray, mockBatchPutGeofenceCommand, mockGetGeofenceCommand, mockListGeofencesCommand, mockDeleteGeofencesCommand, } from '../testUtils'; import { SearchByTextOptions, SearchByCoordinatesOptions, Coordinates, AmazonLocationServiceGeofence, } from '../../src/types'; LocationClient.prototype.send = jest.fn(async command => { if ( command instanceof SearchPlaceIndexForTextCommand || command instanceof SearchPlaceIndexForPositionCommand ) { return { Results: [ { Place: TestPlacePascalCase, }, ], }; } }); describe('AmazonLocationServiceProvider', () => { afterEach(() => { jest.restoreAllMocks(); jest.clearAllMocks(); }); describe('constructor', () => { test('happy case', () => { const provider = new AmazonLocationServiceProvider(); }); }); describe('getCategory', () => { test('should return "Geo" when asked for category', () => { const geo = new AmazonLocationServiceProvider(); expect(geo.getCategory()).toBe('Geo'); }); }); describe('getProviderName', () => { test('should return "AmazonLocationService" when asked for Provider', () => { const geo = new AmazonLocationServiceProvider(); expect(geo.getProviderName()).toBe('AmazonLocationService'); }); }); describe('configure', () => { test('should return a blank config object when none is passed in', () => { const geo = new AmazonLocationServiceProvider(); const config = geo.configure(); expect(config).toEqual({}); }); test('should return standard configuration given when passing to `geo.configure`', () => { const geo = new AmazonLocationServiceProvider(); const config = geo.configure(awsConfig.geo.amazon_location_service); expect(config).toEqual(awsConfig.geo.amazon_location_service); }); }); describe('get map resources', () => { test('should tell you if there are no available map resources', () => { const provider = new AmazonLocationServiceProvider(); provider.configure(); expect(() => provider.getAvailableMaps()).toThrow( "No map resources found in amplify config, run 'amplify add geo' to create one and run `amplify push` after" ); }); test('should get all available map resources', () => { const provider = new AmazonLocationServiceProvider(); provider.configure(awsConfig.geo.amazon_location_service); const maps = []; const availableMaps = awsConfig.geo.amazon_location_service.maps.items; const region = awsConfig.geo.amazon_location_service.region; for (const mapName in availableMaps) { const style = availableMaps[mapName].style; maps.push({ mapName, style, region }); } expect(provider.getAvailableMaps()).toEqual(maps); }); test('should tell you if there is no map resources available when calling getDefaultMap', () => { const provider = new AmazonLocationServiceProvider(); provider.configure(); expect(() => provider.getDefaultMap()).toThrow( "No map resources found in amplify config, run 'amplify add geo' to create one and run `amplify push` after" ); }); test('should tell you if there is no default map resource', () => { const provider = new AmazonLocationServiceProvider(); provider.configure({ maps: { testMap: { style: 'teststyle' } }, }); expect(() => provider.getDefaultMap()).toThrow( "No default map resource found in amplify config, run 'amplify add geo' to create one and run `amplify push` after" ); }); test('should get the default map resource', () => { const provider = new AmazonLocationServiceProvider(); provider.configure(awsConfig.geo.amazon_location_service); const mapName = awsConfig.geo.amazon_location_service.maps.default; const style = awsConfig.geo.amazon_location_service.maps.items[mapName].style; const region = awsConfig.geo.amazon_location_service.region; const testMap = { mapName, style, region }; const defaultMapsResource = provider.getDefaultMap(); expect(defaultMapsResource).toEqual(testMap); }); }); describe('searchByText', () => { const testString = 'starbucks'; test('should search with just text input', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(credentials); }); const locationProvider = new AmazonLocationServiceProvider(); locationProvider.configure(awsConfig.geo.amazon_location_service); const results = await locationProvider.searchByText(testString); expect(results).toEqual([testPlaceCamelCase]); const spyon = jest.spyOn(LocationClient.prototype, 'send'); const input = spyon.mock.calls[0][0].input; expect(input).toEqual({ Text: testString, IndexName: awsConfig.geo.amazon_location_service.search_indices.default, }); }); test('should use biasPosition when given', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(credentials); }); const locationProvider = new AmazonLocationServiceProvider(); locationProvider.configure(awsConfig.geo.amazon_location_service); const searchOptions: SearchByTextOptions = { countries: ['USA'], maxResults: 40, searchIndexName: 'geoJSSearchCustomExample', biasPosition: [12345, 67890], }; const results = await locationProvider.searchByText( testString, searchOptions ); expect(results).toEqual([testPlaceCamelCase]); const spyon = jest.spyOn(LocationClient.prototype, 'send'); const input = spyon.mock.calls[0][0].input; expect(input).toEqual({ Text: testString, IndexName: searchOptions.searchIndexName, BiasPosition: searchOptions.biasPosition, FilterCountries: searchOptions.countries, MaxResults: searchOptions.maxResults, }); }); test('should use searchAreaConstraints when given', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(credentials); }); const locationProvider = new AmazonLocationServiceProvider(); locationProvider.configure(awsConfig.geo.amazon_location_service); const searchOptions: SearchByTextOptions = { countries: ['USA'], maxResults: 40, searchIndexName: 'geoJSSearchCustomExample', searchAreaConstraints: [123, 456, 789, 321], }; const resultsWithConstraints = await locationProvider.searchByText( testString, searchOptions ); expect(resultsWithConstraints).toEqual([testPlaceCamelCase]); const spyon = jest.spyOn(LocationClient.prototype, 'send'); const input = spyon.mock.calls[0][0].input; expect(input).toEqual({ Text: testString, IndexName: searchOptions.searchIndexName, FilterBBox: searchOptions.searchAreaConstraints, FilterCountries: searchOptions.countries, MaxResults: searchOptions.maxResults, }); }); test('should throw an error if both BiasPosition and SearchAreaConstraints are given in the options', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(credentials); }); const locationProvider = new AmazonLocationServiceProvider(); locationProvider.configure(awsConfig.geo.amazon_location_service); const searchOptions: SearchByTextOptions = { countries: ['USA'], maxResults: 40, searchIndexName: 'geoJSSearchCustomExample', biasPosition: [12345, 67890], searchAreaConstraints: [123, 456, 789, 321], }; await expect( locationProvider.searchByText(testString, searchOptions) ).rejects.toThrow( 'BiasPosition and SearchAreaConstraints are mutually exclusive, please remove one or the other from the options object' ); }); test('should fail if credentials are invalid', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(); }); const locationProvider = new AmazonLocationServiceProvider(); await expect(locationProvider.searchByText(testString)).rejects.toThrow( 'No credentials' ); }); test('should fail if _getCredentials fails ', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.reject(); }); const locationProvider = new AmazonLocationServiceProvider(); await expect(locationProvider.searchByText(testString)).rejects.toThrow( 'No credentials' ); }); test('should fail if there are no search index resources', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(credentials); }); const locationProvider = new AmazonLocationServiceProvider(); locationProvider.configure({}); expect(locationProvider.searchByText(testString)).rejects.toThrow( 'No Search Index found in amplify config, please run `amplify add geo` to create one and run `amplify push` after.' ); }); }); describe('searchByCoordinates', () => { const testCoordinates: Coordinates = [45, 90]; test('should search with just text input', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(credentials); }); const locationProvider = new AmazonLocationServiceProvider(); locationProvider.configure(awsConfig.geo.amazon_location_service); const results = await locationProvider.searchByCoordinates( testCoordinates ); expect(results).toEqual(testPlaceCamelCase); const spyon = jest.spyOn(LocationClient.prototype, 'send'); const input = spyon.mock.calls[0][0].input; expect(input).toEqual({ Position: testCoordinates, IndexName: awsConfig.geo.amazon_location_service.search_indices.default, }); }); test('should use options when given', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(credentials); }); const locationProvider = new AmazonLocationServiceProvider(); locationProvider.configure(awsConfig.geo.amazon_location_service); const searchOptions: SearchByCoordinatesOptions = { maxResults: 40, searchIndexName: 'geoJSSearchCustomExample', }; const results = await locationProvider.searchByCoordinates( testCoordinates, searchOptions ); expect(results).toEqual(testPlaceCamelCase); const spyon = jest.spyOn(LocationClient.prototype, 'send'); const input = spyon.mock.calls[0][0].input; expect(input).toEqual({ Position: testCoordinates, IndexName: searchOptions.searchIndexName, MaxResults: searchOptions.maxResults, }); }); test('should fail if credentials resolve to invalid', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(); }); const locationProvider = new AmazonLocationServiceProvider(); await expect( locationProvider.searchByCoordinates(testCoordinates) ).rejects.toThrow('No credentials'); }); test('should fail if _getCredentials fails ', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.reject(); }); const locationProvider = new AmazonLocationServiceProvider(); await expect( locationProvider.searchByCoordinates(testCoordinates) ).rejects.toThrow('No credentials'); }); test('should fail if there are no search index resources', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(credentials); }); const locationProvider = new AmazonLocationServiceProvider(); locationProvider.configure({}); await expect( locationProvider.searchByCoordinates(testCoordinates) ).rejects.toThrow( 'No Search Index found in amplify config, please run `amplify add geo` to create one and run `amplify push` after.' ); }); }); describe('saveGeofences', () => { test('saveGeofences with multiple geofences', async () => { jest.spyOn(Credentials, 'get').mockImplementation(() => { return Promise.resolve(credentials); }); LocationClient.prototype.send = jest .fn() .mockImplementation(mockBatchPutGeofenceCommand); const locationProvider = new AmazonLocationServiceProvider(); locationProvider.configure(awsConfig.geo.amazon_location_service); const results = await locationProvider.saveGeofences(validGeofences); expect(results).toEqual(batchGeofencesCamelcaseResults); }); test('saveGeofences calls batchPutGeofences in batches of 10 from input', async () => { jest.spyOn(Credentials, 'get').mockImplementation(() => { return Promise.resolve(credentials); }); const locationProvider = new AmazonLocationServiceProvider(); locationProvider.configure(awsConfig.geo.amazon_location_service); const numberOfGeofences = 44; const input = createGeofenceInputArray(numberOfGeofences); const spyonProvider = jest.spyOn(locationProvider, 'saveGeofences'); const spyonClient = jest.spyOn(LocationClient.prototype, 'send'); const results = await locationProvider.saveGeofences(input); const expected = { successes: input.map(({ geofenceId }) => { return { geofenceId, createTime: '2020-04-01T21:00:00.000Z', updateTime: '2020-04-01T21:00:00.000Z', }; }), errors: [], }; expect(results).toEqual(expected); const spyProviderInput = spyonProvider.mock.calls[0][0]; const spyClientInput = spyonClient.mock.calls; expect(spyClientInput.length).toEqual( Math.ceil(spyProviderInput.length / 10) ); }); test('saveGeofences properly handles errors with bad network calls', async () => { jest.spyOn(Credentials, 'get').mockImplementation(() => { return Promise.resolve(credentials); }); const locationProvider = new AmazonLocationServiceProvider(); locationProvider.configure(awsConfig.geo.amazon_location_service); const input = createGeofenceInputArray(44); input[22].geofenceId = 'badId'; const validEntries = [...input.slice(0, 20), ...input.slice(30, 44)]; const spyonClient = jest.spyOn(LocationClient.prototype, 'send'); spyonClient.mockImplementation(geofenceInput => { const entries = geofenceInput.input as any; if (entries.Entries.some(entry => entry.GeofenceId === 'badId')) { return Promise.reject(new Error('Bad network call')); } const resolution = { Successes: entries.Entries.map(({ GeofenceId }) => { return { GeofenceId, CreateTime: '2020-04-01T21:00:00.000Z', UpdateTime: '2020-04-01T21:00:00.000Z', }; }), Errors: [], }; return Promise.resolve(resolution); }); const results = await locationProvider.saveGeofences(input); const badResults = input.slice(20, 30).map(input => { return { error: { code: 'APIConnectionError', message: 'Bad network call', }, geofenceId: input.geofenceId, }; }); const expected = { successes: validEntries.map(({ geofenceId }) => { return { geofenceId, createTime: '2020-04-01T21:00:00.000Z', updateTime: '2020-04-01T21:00:00.000Z', }; }), errors: badResults, }; expect(results).toEqual(expected); }); test('should error if a geofence is wound clockwise', async () => { jest.spyOn(Credentials, 'get').mockImplementation(() => { return Promise.resolve(credentials); }); LocationClient.prototype.send = jest .fn() .mockImplementation(mockBatchPutGeofenceCommand); const locationProvider = new AmazonLocationServiceProvider(); locationProvider.configure(awsConfig.geo.amazon_location_service); await expect( locationProvider.saveGeofences([clockwiseGeofence]) ).rejects.toThrow( 'geofenceWithClockwiseGeofence: LinearRing coordinates must be wound counterclockwise' ); }); test('should error if input is empty array', async () => { jest.spyOn(Credentials, 'get').mockImplementation(() => { return Promise.resolve(credentials); }); LocationClient.prototype.send = jest .fn() .mockImplementation(mockBatchPutGeofenceCommand); const locationProvider = new AmazonLocationServiceProvider(); locationProvider.configure(awsConfig.geo.amazon_location_service); await expect(locationProvider.saveGeofences([])).rejects.toThrow( 'Geofence input array is empty' ); }); test('should error if there are no geofenceCollections in config', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(credentials); }); const locationProvider = new AmazonLocationServiceProvider(); locationProvider.configure({}); await expect( locationProvider.saveGeofences(validGeofences) ).rejects.toThrow( 'No Geofence Collections found, please run `amplify add geo` to create one and run `amplify push` after.' ); }); }); describe('getGeofence', () => { test('getGeofence returns the right geofence', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(credentials); }); LocationClient.prototype.send = jest .fn() .mockImplementation(mockGetGeofenceCommand); const locationProvider = new AmazonLocationServiceProvider(); locationProvider.configure(awsConfig.geo.amazon_location_service); const results: AmazonLocationServiceGeofence = await locationProvider.getGeofence('geofenceId'); const expected = { geofenceId: 'geofenceId', geometry: validGeometry, createTime: '2020-04-01T21:00:00.000Z', updateTime: '2020-04-01T21:00:00.000Z', status: 'ACTIVE', }; await expect(results).toEqual(expected); }); test('getGeofence errors when a bad geofenceId is given', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(credentials); }); LocationClient.prototype.send = jest .fn() .mockImplementationOnce(mockGetGeofenceCommand); const locationProvider = new AmazonLocationServiceProvider(); locationProvider.configure(awsConfig.geo.amazon_location_service); const badGeofenceId = 't|-|!$ !$ N()T V@|_!D'; await expect(locationProvider.getGeofence(badGeofenceId)).rejects.toThrow( `Invalid geofenceId: '${badGeofenceId}' - IDs can only contain alphanumeric characters, hyphens, underscores and periods.` ); }); test('should error if there are no geofenceCollections in config', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(credentials); }); const locationProvider = new AmazonLocationServiceProvider(); locationProvider.configure({}); await expect(locationProvider.getGeofence('geofenceId')).rejects.toThrow( 'No Geofence Collections found, please run `amplify add geo` to create one and run `amplify push` after.' ); }); }); describe('listGeofences', () => { test('listGeofences gets the first 100 geofences when no arguments are given', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(credentials); }); LocationClient.prototype.send = jest .fn() .mockImplementation(mockListGeofencesCommand); const locationProvider = new AmazonLocationServiceProvider(); locationProvider.configure(awsConfig.geo.amazon_location_service); const geofences = await locationProvider.listGeofences(); expect(geofences.entries.length).toEqual(100); }); test('listGeofences gets the second 100 geofences when nextToken is passed', async () => { jest.spyOn(Credentials, 'get').mockImplementation(() => { return Promise.resolve(credentials); }); LocationClient.prototype.send = jest .fn() .mockImplementation(mockListGeofencesCommand); const locationProvider = new AmazonLocationServiceProvider(); locationProvider.configure(awsConfig.geo.amazon_location_service); const first100Geofences = await locationProvider.listGeofences(); const second100Geofences = await locationProvider.listGeofences({ nextToken: first100Geofences.nextToken, }); expect(second100Geofences.entries.length).toEqual(100); expect(second100Geofences.entries[0].geofenceId).toEqual( 'validGeofenceId100' ); expect(second100Geofences.entries[99].geofenceId).toEqual( 'validGeofenceId199' ); }); test('should error if there are no geofenceCollections in config', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(credentials); }); const locationProvider = new AmazonLocationServiceProvider(); locationProvider.configure({}); await expect(locationProvider.listGeofences()).rejects.toThrow( 'No Geofence Collections found, please run `amplify add geo` to create one and run `amplify push` after.' ); }); }); describe('deleteGeofences', () => { test('deleteGeofences deletes given geofences successfully', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(credentials); }); LocationClient.prototype.send = jest .fn() .mockImplementation(mockDeleteGeofencesCommand); const locationProvider = new AmazonLocationServiceProvider(); locationProvider.configure(awsConfig.geo.amazon_location_service); const geofenceIds = validGeofences.map(({ geofenceId }) => geofenceId); const results = await locationProvider.deleteGeofences(geofenceIds); const expected = { successes: geofenceIds, errors: [], }; expect(results).toEqual(expected); }); test('deleteGeofences calls batchDeleteGeofences in batches of 10 from input', async () => { jest.spyOn(Credentials, 'get').mockImplementation(() => { return Promise.resolve(credentials); }); const locationProvider = new AmazonLocationServiceProvider(); locationProvider.configure(awsConfig.geo.amazon_location_service); const geofenceIds = validGeofences.map(({ geofenceId }) => geofenceId); const spyonProvider = jest.spyOn(locationProvider, 'deleteGeofences'); const spyonClient = jest.spyOn(LocationClient.prototype, 'send'); spyonClient.mockImplementation(mockDeleteGeofencesCommand); const results = await locationProvider.deleteGeofences(geofenceIds); const expected = { successes: geofenceIds, errors: [], }; expect(results).toEqual(expected); const spyProviderInput = spyonProvider.mock.calls[0][0]; const spyClientInput = spyonClient.mock.calls; expect(spyClientInput.length).toEqual( Math.ceil(spyProviderInput.length / 10) ); }); test('deleteGeofences properly handles errors with bad network calls', async () => { jest.spyOn(Credentials, 'get').mockImplementation(() => { return Promise.resolve(credentials); }); const locationProvider = new AmazonLocationServiceProvider(); locationProvider.configure(awsConfig.geo.amazon_location_service); const input = createGeofenceInputArray(44).map( ({ geofenceId }) => geofenceId ); input[22] = 'badId'; const validEntries = [...input.slice(0, 20), ...input.slice(30, 44)]; const spyonClient = jest.spyOn(LocationClient.prototype, 'send'); spyonClient.mockImplementation(geofenceInput => { const entries = geofenceInput.input as any; if (entries.GeofenceIds.some(entry => entry === 'badId')) { return Promise.reject(new Error('ResourceDoesNotExist')); } const resolution = { Errors: [ { Error: { Code: 'ResourceDoesNotExist', Message: 'Resource does not exist', }, GeofenceId: 'badId', }, ], }; return Promise.resolve(resolution); }); const results = await locationProvider.deleteGeofences(input); const badResults = input.slice(20, 30).map(geofenceId => { return { error: { code: 'ResourceDoesNotExist', message: 'ResourceDoesNotExist', }, geofenceId, }; }); const expected = { successes: validEntries, errors: badResults, }; expect(results).toEqual(expected); }); test('should error if there is a bad geofence in the input', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(credentials); }); const locationProvider = new AmazonLocationServiceProvider(); locationProvider.configure(awsConfig.geo.amazon_location_service); await expect( locationProvider.deleteGeofences([ 'thisIsAGoodId', 't|-|!$ !$ N()T V@|_!D', '#2 t|-|!$ !$ N()T V@|_!D', ]) ).rejects.toThrow( `Invalid geofence ids: t|-|!$ !$ N()T V@|_!D, #2 t|-|!$ !$ N()T V@|_!D` ); }); test('should error if input array is empty', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(credentials); }); const locationProvider = new AmazonLocationServiceProvider(); locationProvider.configure(awsConfig.geo.amazon_location_service); await expect(locationProvider.deleteGeofences([])).rejects.toThrow( `GeofenceId input array is empty` ); }); test('should error if there are no geofenceCollections in config', async () => { jest.spyOn(Credentials, 'get').mockImplementationOnce(() => { return Promise.resolve(credentials); }); const locationProvider = new AmazonLocationServiceProvider(); locationProvider.configure({}); const geofenceIds = validGeofences.map(({ geofenceId }) => geofenceId); await expect( locationProvider.deleteGeofences(geofenceIds) ).rejects.toThrow( 'No Geofence Collections found, please run `amplify add geo` to create one and run `amplify push` after.' ); }); }); });
the_stack
import { Nodes } from '../nodes'; import { PositionCapableError } from '../NodeError'; import { walkPreOrder } from '../walker'; import { TokenError, IToken } from 'ebnf'; import { parser } from '../../grammar'; import { ParsingContext } from '../ParsingContext'; import { annotations } from '../annotations'; /// --- PARSING PHASE --- const process = walkPreOrder((token: IToken, parsingContext: ParsingContext) => { if (token.errors && token.errors.length) { token.errors.forEach(($: TokenError) => { if ($) { parsingContext.messageCollector.error(new PositionCapableError($.message, token as any)); } }); } }); const setModuleName = (moduleName: string) => walkPreOrder((token: any) => { token.moduleName = moduleName; }); const parsingCache = new Map<string /** hash */, IToken>(); function DJB2(input: string) { let hash = 5381; for (let i = 0; i < input.length; i++) { hash = (hash << 5) + hash + input.charCodeAt(i); } return hash; } function getParsingTree(moduleName: string, content: string, parsingContext: ParsingContext) { const hash = moduleName + '+' + content.length.toString(16) + '_' + DJB2(content).toString(16); let ret = parsingCache.get(hash); if (!ret) { ret = parser.getAST(content, 'Document'); parsingCache.set(hash, ret); setModuleName(moduleName)(ret as any, parsingContext); } return (ret as any) as Nodes.ASTNode; } /// --- CANONICAL --- function binaryOpVisitor(astNode: Nodes.ASTNode) { let ret = visit(astNode.children[0]) as | Nodes.BinaryExpressionNode | Nodes.AsExpressionNode | Nodes.IsExpressionNode | Nodes.AssignmentNode; for (let i = 1; i < astNode.children.length; i += 2) { const oldRet = ret; const opertator = astNode.children[i].text; const lhs = oldRet; const rhs = visit(astNode.children[i + 1]); if (opertator === 'as') { ret = new Nodes.AsExpressionNode(astNode, lhs, rhs); } else if (opertator === 'is') { ret = new Nodes.IsExpressionNode(astNode, lhs, rhs); } else if (opertator === '=') { ret = new Nodes.AssignmentNode(astNode, lhs, rhs); } else { const operator = new Nodes.NameIdentifierNode(astNode.children[i], opertator); ret = new Nodes.BinaryExpressionNode(astNode, operator, lhs, rhs); } } return ret; } const visitor = { ImportDirective(astNode: Nodes.ASTNode) { const module = visitChildTypeOrNull(astNode, 'QName') as Nodes.QNameNode; const ret = new Nodes.ImportDirectiveNode(astNode, module); ret.alias = visitChildTypeOrNull(astNode, 'NameIdentifier') as Nodes.NameIdentifierNode; return ret; }, VarDirective(astNode: Nodes.ASTNode) { const decl = visit(findChildrenTypeOrFail(astNode, 'VarDeclaration')); const ret = new Nodes.VarDirectiveNode(astNode, decl); ret.isPublic = !findChildrenType(astNode, 'PrivateModifier'); return ret; }, ValDirective(astNode: Nodes.ASTNode) { const decl = visit(findChildrenTypeOrFail(astNode, 'ValDeclaration')); const ret = new Nodes.VarDirectiveNode(astNode, decl); ret.isPublic = !findChildrenType(astNode, 'PrivateModifier'); return ret; }, EffectDirective(astNode: Nodes.ASTNode) { const ret = new Nodes.EffectDirectiveNode(astNode); ret.isPublic = !findChildrenType(astNode, 'PrivateModifier'); ret.effect = visit(findChildrenTypeOrFail(astNode, 'EffectDeclaration')); return ret; }, ImplDirective(astNode: Nodes.ASTNode) { const references = astNode.children.filter(($) => $.type === 'Reference'); // the last Reference is the target const target = visit(references.pop()!); const directivesNode = findChildrenType(astNode, 'NamespaceElementList'); let directives: Nodes.DirectiveNode[] = directivesNode ? (directivesNode.children.map(visit) as Nodes.DirectiveNode[]) : []; // TODO: warn const ret = new Nodes.ImplDirective(astNode, target, directives); if (references.length) { ret.baseImpl = visit(references.pop()!); } ret.isPublic = !findChildrenType(astNode, 'PrivateModifier'); return ret; }, EffectDeclaration(astNode: Nodes.ASTNode) { const name = visit(findChildrenTypeOrFail(astNode, 'NameIdentifier', 'A name is required')); const ret = new Nodes.EffectDeclarationNode(astNode, name); const list = findChildrenType(astNode, 'EffectElementList'); if (list) { ret.elements = list.children.map(($) => visit($)); } else { // TODO: warn } return ret; }, EffectMemberDeclaration(astNode: Nodes.ASTNode) { const ret = new Nodes.EffectMemberDeclarationNode(astNode); ret.name = visit(findChildrenTypeOrFail(astNode, 'NameIdentifier')); const params = findChildrenType(astNode, 'FunctionParamsList'); if (!params) { throw new PositionCapableError('Missing param list in function declaration', astNode); } ret.parameters = params.children.map(($) => visit($)); return ret; }, VarDeclaration(astNode: Nodes.ASTNode) { const variableName = visit(findChildrenTypeOrFail(astNode, 'NameIdentifier')); const value = visitLastChild(astNode); const ret = new Nodes.VarDeclarationNode(astNode, variableName, value); ret.variableName.annotate(new annotations.MutableDeclaration()); const type = findChildrenType(astNode, 'Type'); if (type) { ret.variableType = visit(type); } else { // TODO: warn } return ret; }, ValDeclaration(astNode: Nodes.ASTNode) { const variableName = visit(findChildrenTypeOrFail(astNode, 'NameIdentifier')); const value = visitLastChild(astNode); const ret = new Nodes.VarDeclarationNode(astNode, variableName, value); const type = findChildrenType(astNode, 'Type'); if (type) { ret.variableType = visit(type); } else { // TODO: warn } return ret; }, TypeDirective(astNode: Nodes.ASTNode) { const children = astNode.children.slice(); let isPublic = true; let child = children.shift()!; if (child.type === 'PrivateModifier') { isPublic = false; child = children.shift()!; } const variableName = visit(child); console.assert(!!variableName, 'missing variable name'); const ret = new Nodes.TypeDirectiveNode(astNode, variableName); ret.isPublic = isPublic; if (children.length) { ret.valueType = visitLastChild(astNode) as Nodes.TypeNode; } return ret; }, EnumDirective(astNode: Nodes.ASTNode) { const children = astNode.children.slice(); let child = children.shift()!; let isPublic = true; if (child.type === 'PrivateModifier') { isPublic = false; child = children.shift()!; } const variableName = visit(child); const typeDeclElements = findChildrenType(astNode, 'TypeDeclElements'); const declarations = typeDeclElements ? typeDeclElements.children.map(($) => visit($)) : []; const ret = new Nodes.EnumDirectiveNode(astNode, variableName, declarations); ret.isPublic = isPublic; return ret; }, TraitDirective(astNode: Nodes.ASTNode) { const children = astNode.children.slice(); let child = children.shift()!; let isPublic = true; if (child.type === 'PrivateModifier') { isPublic = false; child = children.shift()!; } const variableName = visit(child); const typeDeclElements = findChildrenType(astNode, 'TraitDeclElements'); const declarations = typeDeclElements ? typeDeclElements.children.map(($) => visit($)) : []; declarations.forEach(($) => { if ($ instanceof Nodes.FunDirectiveNode && !$.functionNode.body) { $.functionNode.annotate(new annotations.SignatureDeclaration()); } }); const ret = new Nodes.TraitDirectiveNode(astNode, variableName, declarations); ret.isPublic = isPublic; return ret; }, FunDeclaration(astNode: Nodes.ASTNode) { const functionName = visit( findChildrenTypeOrFail(astNode, 'FunctionName', 'A function name is required').children[0] ); const fun = new Nodes.FunctionNode(astNode, functionName); const retType = findChildrenType(astNode, 'Type'); if (retType) { fun.functionReturnType = visit(retType); } else { // TODO: warn } const params = findChildrenType(astNode, 'FunctionParamsList'); if (!params) { throw new PositionCapableError('Missing param list in function declaration', astNode); } fun.parameters = params.children.map(($) => visit($)); const body = findChildrenType(astNode, 'FunAssignExpression'); if (body) { fun.body = visitLastChild(body); } return fun; }, Decorator(astNode: Nodes.ASTNode) { const children = astNode.children.slice(); const name = children.shift(); if (!name) { throw new PositionCapableError('Missing decorator name', astNode); } const decoratorName = visit(name); const args = children.map(visit) as Nodes.LiteralNode<any>[]; const ret = new Nodes.DecoratorNode(astNode, decoratorName, args); return ret; }, FunctionDirective(astNode: Nodes.ASTNode) { const decoratorsNode = findChildrenType(astNode, 'Decorators'); const decorators = decoratorsNode ? (decoratorsNode.children.map(visit) as Nodes.DecoratorNode[]) : []; const functionNode = visit(findChildrenTypeOrFail(astNode, 'FunDeclaration')) as Nodes.FunctionNode; const ret = new Nodes.FunDirectiveNode(astNode, functionNode, decorators); ret.isPublic = !findChildrenType(astNode, 'PrivateModifier'); return ret; }, CodeBlock(astNode: Nodes.ASTNode) { const statements = astNode.children.map(($) => visit($)).filter(($) => !!$); return new Nodes.BlockNode(astNode, statements); }, Parameter(astNode: Nodes.ASTNode) { const parameterName = visit(findChildrenTypeOrFail(astNode, 'NameIdentifier', 'A parameter name is required')); const ret = new Nodes.ParameterNode(astNode, parameterName); const type = findChildrenType(astNode, 'Type'); if (type) { ret.parameterType = visit(type); } else { // TODO: warn } return ret; }, AssignExpression: binaryOpVisitor, AddExpression: binaryOpVisitor, OrExpression: binaryOpVisitor, AndExpression: binaryOpVisitor, BitOrExpression: binaryOpVisitor, BitXorExpression: binaryOpVisitor, BitAndExpression: binaryOpVisitor, AsExpression: binaryOpVisitor, IsExpression: binaryOpVisitor, RelExpression: binaryOpVisitor, EqExpression: binaryOpVisitor, ShiftExpression: binaryOpVisitor, MulExpression: binaryOpVisitor, ParenExpression(astNode: Nodes.ASTNode) { const ret = visitLastChild(astNode); ret.hasParentheses = true; return ret; }, AtomicExpression(astNode: Nodes.ASTNode) { let ret = visit(astNode.children[0]); for (let currentChildren = 1; currentChildren < astNode.children.length; currentChildren++) { const currentNode = astNode.children[currentChildren]; const doesItHaveCallArguments = currentNode && currentNode.type === 'CallArguments'; const doesItHaveIndexExpression = currentNode && currentNode.type === 'IndexExpression'; const doesItHaveMemberExpression = currentNode && currentNode.type === 'MemberExpression'; if (doesItHaveCallArguments) { const argumentsNode = currentNode.children.map(($) => visit($)); const fnCall = new Nodes.FunctionCallNode(currentNode, ret, argumentsNode); fnCall.isInfix = true; ret = fnCall; } else if (doesItHaveIndexExpression) { const argument = visit(currentNode.children[0]); const indexSelector = new Nodes.BinaryExpressionNode( currentNode, Nodes.NameIdentifierNode.fromString('[]', currentNode), ret, argument ); ret = indexSelector; } else if (doesItHaveMemberExpression) { ret = new Nodes.MemberNode(astNode, ret, currentNode.children[0].text, visit(currentNode.children[1])); } else { if (currentNode) { throw new PositionCapableError("Don't know what to do with " + currentNode.type, currentNode); } } } return ret; }, MatchExpression(astNode: Nodes.ASTNode) { const lhs = visit(astNode.children[0]); const matchingSet = astNode.children[1].children.map(($) => visit($)); return new Nodes.PatternMatcherNode(astNode, lhs, matchingSet); }, Reference(astNode: Nodes.ASTNode) { return new Nodes.ReferenceNode(astNode, visit(astNode.children[0])); }, FunOperator(astNode: Nodes.ASTNode) { return new Nodes.NameIdentifierNode(astNode, astNode.text.trim()); }, NameIdentifier(astNode: Nodes.ASTNode) { return new Nodes.NameIdentifierNode(astNode, astNode.text.trim()); }, QName(astNode: Nodes.ASTNode) { const names = astNode.children.map(visit) as any; return new Nodes.QNameNode(astNode, names); }, FunctionTypeParameter(astNode: Nodes.ASTNode) { const type = visitChildTypeOrFail(astNode, 'Type') as Nodes.TypeNode; const ret = new Nodes.SignatureParameterNode(astNode, type); ret.parameterName = visitChildTypeOrNull(astNode, 'NameIdentifier') as Nodes.NameIdentifierNode; return ret; }, FunctionTypeLiteral(child: Nodes.ASTNode) { const parametersNode = findChildrenType(child, 'FunctionTypeParameters'); const ret = new Nodes.FunctionTypeNode(child, parametersNode ? parametersNode.children.map(($) => visit($)) : []); ret.returnType = visitChildTypeOrNull(child, 'Type') as Nodes.TypeNode; return ret; }, Type(astNode: Nodes.ASTNode) { const ret = visit(astNode.children[0]); if (false === ret instanceof Nodes.TypeNode && false === ret instanceof Nodes.ReferenceNode) { console.error('Node ' + astNode.type + ' did not yield a type node'); console.log(ret); } return ret; }, CaseLiteral(x: Nodes.ASTNode) { const literal = visit(x.children[0]); const rhs = visit(x.children[1]); return new Nodes.MatchLiteralNode(x, literal, rhs); }, CaseCondition(x: Nodes.ASTNode) { const condition = visit(x.children[1]); const rhs = visit(x.children[2]); const ret = new Nodes.MatchConditionNode(x, condition, rhs); ret.declaredName = visit(x.children[0]) as Nodes.NameIdentifierNode; return ret; }, CaseIs(x: Nodes.ASTNode) { const rhs = visitLastChild(x); const typeReference = visitChildTypeOrFail(x, 'Reference') as Nodes.ReferenceNode; const ret = new Nodes.MatchCaseIsNode(x, typeReference, rhs); ret.declaredName = visitChildTypeOrNull(x, 'NameIdentifier') as Nodes.NameIdentifierNode; const deconstruct = findChildrenType(x, 'DeconstructStruct'); if (deconstruct) { ret.deconstructorNames = deconstruct.children.map(($) => visit($)); } return ret; }, CaseElse(x: Nodes.ASTNode) { return new Nodes.MatchDefaultNode(x, visit(x.children[0])); }, LoopExpression(x: Nodes.ASTNode) { return new Nodes.LoopNode(x, visit(x.children[0])); }, ContinueStatement(x: Nodes.ASTNode) { return new Nodes.ContinueNode(x); }, BreakStatement(x: Nodes.ASTNode) { return new Nodes.BreakNode(x); }, PostfixNumber(x: Nodes.ASTNode) { const literal = visit(x.children[0]) as Nodes.IntegerLiteral | Nodes.HexLiteral | Nodes.FloatLiteral; literal.suffixReference = visit(x.children[1]); return literal; }, NumberLiteral(x: Nodes.ASTNode) { if (x.text.includes('.') || x.text.includes('E') || x.text.includes('e')) { return new Nodes.FloatLiteral(x, 'f32'); } else { let type = 'i64'; // tslint:disable-next-line:radix const intValue = parseInt(x.text); if (intValue >= -2147483648 && intValue <= 4294967295) { type = 'i32'; } return new Nodes.IntegerLiteral(x, type); } }, NegNumberLiteral(x: Nodes.ASTNode) { if (x.text.includes('.') || x.text.includes('E') || x.text.includes('e')) { return new Nodes.FloatLiteral(x, 'f32'); } else { return new Nodes.IntegerLiteral(x, 'i32'); } }, HexLiteral(x: Nodes.ASTNode) { const typeName = x.text.length > '0x00000000'.length ? 'u64' : 'u32'; return new Nodes.HexLiteral(x, typeName); }, StringLiteral(x: Nodes.ASTNode) { try { const ret = new Nodes.StringLiteral(x, 'string'); ret.value = JSON.parse(x.text); return ret; } catch (e) { const err = 'Cannot parse string: ' + x.text; console.log(err); return new PositionCapableError(err, x); } }, BinNegExpression(x: Nodes.ASTNode) { return new Nodes.UnaryExpressionNode(x, Nodes.NameIdentifierNode.fromString('~', x), visit(x.children[0])); }, NegExpression(x: Nodes.ASTNode) { return new Nodes.UnaryExpressionNode(x, Nodes.NameIdentifierNode.fromString('!', x), visit(x.children[0])); }, UnaryMinus(x: Nodes.ASTNode) { return new Nodes.UnaryExpressionNode(x, Nodes.NameIdentifierNode.fromString('-', x), visit(x.children[0])); }, BooleanLiteral(x: Nodes.ASTNode) { return new Nodes.BooleanLiteral(x, 'boolean'); }, Document(astNode: Nodes.ASTNode) { const doc = new Nodes.DocumentNode(astNode); astNode.children.forEach(($) => doc.directives.push(visit($))); return doc; }, IfExpression(astNode: Nodes.ASTNode) { const condition = visit(astNode.children[0]); const truePart = visit(astNode.children[1]); if (astNode.children[2]) { const falsePart = visit(astNode.children[2]); return new Nodes.IfNode(astNode, condition, truePart, falsePart); } else { return new Nodes.IfNode(astNode, condition, truePart); } }, SyntaxError(node: Nodes.ASTNode) { return new PositionCapableError(node.errors[0].message, node); }, StructDirective(astNode: Nodes.ASTNode) { const children = astNode.children.slice(); let child = children[0]; let isPublic = true; if (child.type === 'PrivateModifier') { isPublic = false; child = children.shift()!; } const ret = visit(child) as Nodes.StructDeclarationNode; ret.isPublic = isPublic; return ret; }, UnknownExpression(astNode: Nodes.ASTNode) { return new Nodes.UnknownExpressionNode(astNode); }, StructLiteral(astNode: Nodes.ASTNode) { const parametersNode = findChildrenTypeOrFail(astNode, 'StructParamsList'); const parameters = parametersNode.children.filter(($) => $.type === 'Parameter').map(($) => visit($)); return new Nodes.StructTypeNode(astNode, parameters); }, StackLiteral(astNode: Nodes.ASTNode) { const ret = new Nodes.StackTypeNode(astNode); ret.metadata = Object.create(null); for (let namePair of astNode.children) { ret.metadata[namePair.children[0].text] = visit(namePair.children[1]); } return ret; }, InjectedLiteral(astNode: Nodes.ASTNode) { const ret = new Nodes.InjectedTypeNode(astNode); return ret; }, StructDeclaration(astNode: Nodes.ASTNode) { const declaredName = visitChildTypeOrNull(astNode, 'NameIdentifier') as Nodes.NameIdentifierNode; const params = findChildrenType(astNode, 'FunctionParamsList'); return new Nodes.StructDeclarationNode(astNode, declaredName, params ? params.children.map(($) => visit($)) : []); }, UnionType(astNode: Nodes.ASTNode) { const ret = new Nodes.UnionTypeNode(astNode); ret.of = astNode.children.map(($) => visit($)); return ret; }, IntersectionType(astNode: Nodes.ASTNode) { const ret = new Nodes.IntersectionTypeNode(astNode); ret.of = astNode.children.map(($) => visit($)); return ret; }, TypeParen(astNode: Nodes.ASTNode) { const ret = visit(astNode.children[0]); ret.hasParentheses = true; return ret; }, WasmExpression(astNode: Nodes.ASTNode) { const atoms = astNode.children.map(($) => visit($)); return new Nodes.WasmExpressionNode(astNode, atoms); }, SExpression(astNode: Nodes.ASTNode) { const children = astNode.children.slice(); const symbol = children.shift() as any; const newChildren = children.map(($) => visit($) as Nodes.ExpressionNode); const ret = new Nodes.WasmAtomNode(astNode, symbol.text, newChildren); if ( ret.symbol === 'call' || ret.symbol === 'global.get' || ret.symbol === 'global.set' || ret.symbol === 'get_global' || ret.symbol === 'set_global' ) { if (ret.args[0] instanceof Nodes.QNameNode) { const qname = ret.args[0] as Nodes.QNameNode; const varRef = new Nodes.ReferenceNode(ret.args[0].astNode, qname); if (qname.names[0].name.startsWith('$')) { // TODO: fix horrible hack $ qname.names[0].name = qname.names[0].name.replace(/^\$/, ''); } ret.args[0] = varRef; } } return ret; }, }; function visit<T extends Nodes.Node>(astNode: Nodes.ASTNode): T & any { if (!astNode) { console.trace(); throw new Error('astNode is null'); } if ((visitor as any)[astNode.type]) { const x = (visitor as any)[astNode.type](astNode); if (!x) { throw new PositionCapableError('Error visiting node ' + astNode.type, astNode); } return x; } else { throw new PositionCapableError(`Visitor not implemented for ${astNode.type}`, astNode); } } function findChildrenTypeOrFail(token: Nodes.ASTNode, type: string, message?: string) { const ret = token.children.find(($) => $.type === type); if (!ret) throw new PositionCapableError(message || `Cannot find child node of type ${type}`, token); return ret; } function findChildrenType(token: Nodes.ASTNode, type: string) { return token.children.find(($) => $.type === type); } function visitChildTypeOrNull(token: Nodes.ASTNode, type: string) { const child = findChildrenType(token, type); if (!child) return null; return visit(child); } function visitChildTypeOrFail(token: Nodes.ASTNode, type: string) { const child = findChildrenTypeOrFail(token, type); return visit(child); } function visitLastChild(token: Nodes.ASTNode) { return visit(token.children[token.children.length - 1]); } export function getAST(fileName: string, moduleName: string, content: string, parsingContext: ParsingContext) { const parsingTree = getParsingTree(moduleName, content, parsingContext); if (!parsingTree) { throw new Error('parsing phase did not run or failed'); } process(parsingTree as any, parsingContext); try { let document = visit(parsingTree) as Nodes.DocumentNode; document.moduleName = moduleName; document.fileName = fileName; document.content = content; parsingContext.modulesInContext.set(moduleName, document); return document; } catch (e) { if (e instanceof PositionCapableError) { let document = new Nodes.DocumentNode(parsingTree); document.moduleName = moduleName; document.fileName = fileName; document.content = content; parsingContext.modulesInContext.set(moduleName, document); parsingContext.messageCollector.error(e); return document; } throw e; } }
the_stack
///<reference path="../rpos.d.ts"/> import { Utils } from './utils'; import { writeFileSync, readFileSync } from 'fs'; var stringifyBool = (v: boolean) => { return v ? "1" : "0"; } var utils = Utils.utils; export module v4l2ctl { export enum Pixelformat { YU12 = 0, // 4:2:0, packed YUV YUYV = 1, // 4:2:2, packed, YUYV RGB3 = 2, // RGB24 (LE) JPEG = 3, // JPEG H264 = 4, // H264 MJPG = 5, // MJPEG YVYU = 6, // 4:2:2, packed, YVYU VYUY = 7, // 4:2:2, packed, VYUY UYVY = 8, // 4:2:2, packed, UYVY NV12 = 9, // 4:2:0, packed, NV12 BGR3 = 10,// RGB24 (BE) YV12 = 11,// 4:2:0, packed YVU NV21 = 12,// 4:2:0, packed, NV21 BGR4 = 13,// RGB32 (BE) } export enum ProcessPriority { background = 1, interactive = 2, record = 3 } export class UserControl<T extends Object> { private typeConstructor: TypeConstructor; private dirty: boolean; private _value: T; private options: UserControlOptions<T>; constructor(value: T, options: UserControlOptions<T>) { if (value === undefined || value === null) throw "'value' is required"; this.typeConstructor = <TypeConstructor>value.constructor; this.dirty = false; this._value = value === undefined ? null : value; this.options = options || {}; this.options.stringify = this.options.stringify || (value => value.toString()); } get value(): T { return this._value; }; set value(value: T) { var val: any = value; if (this.typeConstructor.name == "Boolean") { val = (val === true || val === 1 || (<string>val) + "".toLowerCase() === "true" || val === "1"); } else if (this.typeConstructor.name != "Object") val = this.typeConstructor(val); if (val !== null && val !== undefined) { if (this.hasRange && (val < this.options.range.min || val > this.options.range.max) && (<number>val !== 0 || !this.options.range.allowZero)) throw (`value: ${val} not in range: ${this.options.range.min} - ${this.options.range.max}`); if (this.hasSet && this.options.lookupSet.map(ls=> ls.value).indexOf(val) == -1) throw (`value: ${val} not in set: ${this.options.lookupSet.map(ls=> `{ value:${ls.value} desc:${ls.desc} }`).join() }`); } if (this.hasRange && this.options.range.step && <number>(val) % <number>(<any>this.options.range.step) !== 0) val = Math.round(<number>val / <number>(<any>this.options.range.step)) * <number>(<any>this.options.range.step); if (val !== this._value) this.dirty = true; this._value = val; } get desc():string{ if (this.hasSet) // search the lookup set for this.value and return desc for (var l of this.options.lookupSet) { if (l.value === this.value) return l.desc; } throw "'lookup value' not in lookup set"; } get type(): string { return this.typeConstructor.name; } get hasSet(): boolean { return (this.options.lookupSet || []).length > 0; }; getLookupSet(): UserControlsLookupSet<T> { var result = new Array<UserControlsLookup<T>>(0); for (var l of this.options.lookupSet) { result.push({ value: l.value, desc: l.desc }) } return result; }; get hasRange(): boolean { return !!this.options.range; }; getRange() { if (this.hasRange) return { min: this.options.range.min, max: this.options.range.max }; return null; } get isDirty(): boolean { return this.dirty; }; reset() { this.dirty = false; }; toString(): string { return this.options.stringify(this._value); } } export var Controls = { UserControls: { // min=0 max=100 step=1 default=50 value=50 flags=slider brightness: new UserControl(50, { range: { min: 0, max: 100 } }), // min=-100 max=100 step=1 default=0 value=0 flags=slider contrast: new UserControl(0, { range: { min: -100, max: 100 } }), // min=-100 max=100 step=1 default=0 value=0 flags=slider saturation: new UserControl(0, { range: { min: -100, max: 100 } }), // min=1 max=7999 step=1 default=1000 value=1000 flags=slider red_balance: new UserControl(1000, { range: { min: 1, max: 7999 } }), // min=1 max=7999 step=1 default=1000 value=1000 flags=slider blue_balance: new UserControl(1000, { range: { min: 1, max: 7999 } }), // default=0 value=0 horizontal_flip: new UserControl(false, { stringify: stringifyBool }), // default=0 value=0 vertical_flip: new UserControl(false, { stringify: stringifyBool }), // min=0 max=3 default=1 value=1 | 0: Disabled,1: 50 Hz,2: 60 Hz,3: Auto power_line_frequency: new UserControl(1, { lookupSet: [{ value: 0, desc: 'Disabled' }, { value: 1, desc: '50 Hz' }, { value: 2, desc: '60 Hz' }, { value: 3, desc: 'Auto' }] }), // min=-100 max=100 step=1 default=0 value=0 flags=slider sharpness: new UserControl(0, { range: { min: -100, max: 100 } }), // min=0 max=15 default=0 value=0 | 0: None,1: Black & White,2: Sepia,3: Negative,4: Emboss,5: Sketch,6: Sky Blue,7: Grass Green,8: Skin Whiten,9: Vivid,10: Aqua,11: Art Freeze,12: Silhouette,13: Solarization,14: Antique,15: Set Cb/Cr color_effects: new UserControl(0, { lookupSet: [{ value: 0, desc: 'None' }, { value: 1, desc: 'Black & White' }, { value: 2, desc: 'Sepia' }, { value: 3, desc: 'Negative' }, { value: 4, desc: 'Emboss' }, { value: 5, desc: 'Sketch' }, { value: 6, desc: 'Sky Blue' }, { value: 7, desc: 'Grass Green' }, { value: 8, desc: 'Skin Whiten' }, { value: 9, desc: 'Vivid' }, { value: 10, desc: 'Aqua' }, { value: 11, desc: 'Art Freeze' }, { value: 12, desc: 'Silhouette' }, { value: 13, desc: 'Solarization' }, { value: 14, desc: 'Antique' }, { value: 15, desc: 'Set Cb/Cr' }] }), // min=0 max=360 step=90 default=0 value=0 rotate: new UserControl(0, { range: { min: 0, max: 360 } }), // min=0 max=65535 step=1 default=32896 value=32896 color_effects_cbcr: new UserControl(32896, { range: { min: 0, max: 65535 } }), }, CodecControls: { // min=0 max=1 default=0 value=0 flags=update | 0: Variable Bitrate,1: Constant Bitrate video_bitrate_mode: new UserControl(0, { lookupSet: [{ value: 0, desc: 'Variable Bitrate' }, { value: 1, desc: 'Constant Bitrate' }] }), // min=25000 max=25000000 step=25000 default=10000000 value=10000000 video_bitrate: new UserControl(10000000, { range: { min: 25000, max: 25000000, step: 25000, allowZero: true } }), // default=0 value=0 repeat_sequence_header: new UserControl(false, { stringify: stringifyBool }), // min=0 max=2147483647 step=1 default=60 value=60 h264_i_frame_period: new UserControl(60, { range: { min: 0, max: 2147483647 } }), // min=0 max=11 default=11 value=11 | 0:1,1:1b,2:1.1,3:1.2,4:1.3,5:2,6:2.1,7:2.2,8:3,9:3.1,10:3.2,11:4 h264_level: new UserControl(11, { lookupSet: [{ value: 0, desc: '1' }, { value: 1, desc: '1b' }, { value: 2, desc: '1.1' }, { value: 3, desc: '1.2' }, { value: 4, desc: '1.3' }, { value: 5, desc: '2' }, { value: 6, desc: '2.1' }, { value: 7, desc: '2.2' }, { value: 8, desc: '3' }, { value: 9, desc: '3.1' }, { value: 10, desc: '3.2' }, { value: 11, desc: '4' }] }), // min=0 max=4 default=4 value=4 | 0:Baseline,1:Constrained Baseline,2:Main,4:High h264_profile: new UserControl(4, { lookupSet: [{ value: 0, desc: 'Baseline' }, { value: 1, desc: 'Constrained Baseline' }, { value: 2, desc: 'Main' }, { value: 4, desc: 'High' }] }) }, CameraControls: { // min=0 max=3 default=0 value=0 auto_exposure: new UserControl(false, { stringify: stringifyBool }), // min=1 max=10000 step=1 default=1000 value=1000 exposure_time_absolute: new UserControl(1000, { range: { min: 0, max: 10000 } }), // default=0 value=0 exposure_dynamic_framerate: new UserControl(false, { stringify: stringifyBool }), // min=0 max=24 default=12 value=12 auto_exposure_bias: new UserControl(12, { range: { min: 0, max: 24 } }), // min=0 max=9 default=1 value=1 | 0:Manual,1:Auto,2:Incandescent,3:Fluorescent,4:Fluorescent,5:Horizon,6:Daylight,7:Flash,8:Cloudy,9:Shade white_balance_auto_preset: new UserControl(1, { lookupSet: [{ value: 0, desc: 'Manual' }, { value: 1, desc: 'Auto' }, { value: 2, desc: 'Incandescent' }, { value: 3, desc: 'Fluorescent' }, { value: 4, desc: 'Fluorescent' }, { value: 5, desc: 'Horizon' }, { value: 6, desc: 'Daylight' }, { value: 7, desc: 'Flash' }, { value: 8, desc: 'Cloudy' }, { value: 9, desc: 'Shade' }] }), // default=0 value=0 image_stabilization: new UserControl(false, { stringify: stringifyBool }), // min=0 max=4 default=0 value=0 | 0: 0,1: 100,2: 200,3: 400,4: 800, iso_sensitivity: new UserControl(0, { lookupSet: [{ value: 0, desc: '0' }, { value: 1, desc: '100' }, { value: 2, desc: '200' }, { value: 3, desc: '400' }, { value: 4, desc: '800' }] }), // min=0 max=2 default=0 value=0 | 0: Average,1: Center Weighted,2: Spot, exposure_metering_mode: new UserControl(0, { lookupSet: [{ value: 0, desc: 'Average' }, { value: 1, desc: 'Center Weighted' }, { value: 2, desc: 'Spot' }] }), // min=0 max=13 default=0 value=0 | 0: None,8: Night,11: Sports scene_mode: new UserControl(0, { lookupSet: [{ value: 0, desc: 'None' }, { value: 8, desc: 'Night' }, { value: 11, desc: 'Sport' }] }) }, JPEGCompressionControls: { // min=1 max=100 step=1 default=30 value=30 compression_quality: new UserControl(30, { range: { min: 1, max: 100 } }) } }; function execV4l2(cmd: string): string { try { return utils.execSync(`v4l2-ctl ${cmd}`).toString(); } catch (err) { return ''; } } export function ApplyControls() { var usercontrols = Controls.UserControls; var codeccontrols = Controls.CodecControls; var cameracontrols = Controls.CameraControls; var jpgcontrols = Controls.JPEGCompressionControls; var getChanges = function(controls: {}) { var changes = []; for (var c in controls) { var control = <UserControl<any>>controls[c]; if (!control.isDirty) continue; changes.push([c, "=", control].join('')); control.reset(); } return changes; }; var changedcontrols = getChanges(usercontrols) .concat(getChanges(codeccontrols)) .concat(getChanges(cameracontrols)) .concat(getChanges(jpgcontrols)); if (changedcontrols.length > 0) { execV4l2(`--set-ctrl ${changedcontrols.join(',') }`); WriteToFile(); } } export function WriteToFile() { var data = {}; for (var ct in Controls) { data[ct] = {}; for (var k in Controls[ct]) { var uc = <UserControl<any>>Controls[ct][k]; data[ct][k] = uc.value; } } var json = JSON.stringify(data); json = json.replace(/{"/g,"{\n\"").replace(/:{/g, ":\n{").replace(/,"/g, ",\n\"").replace(/}/g,"}\n"); writeFileSync("v4l2ctl.json", json); } export function ReadFromFile() { try { var data = JSON.parse(readFileSync("v4l2ctl.json").toString()); for (var ct in data) { for (var k in data[ct]) { var uc = <UserControl<any>>Controls[ct][k]; uc.value = data[ct][k]; } } } catch (ex) { utils.log.error("v4l2ctl.json does not exist yet or invalid.") } } export function ReadControls() { var settings = execV4l2("-l"); var regexPart = "\\s.*value=([0-9]*)"; var getControls = function(controls) { for (var c in controls) { var control = controls[c]; var value = settings.match(new RegExp([c, regexPart].join(''))); if (!value || (value.length > 1 && value[1] === "" && c == "auto_exposure")) //-- fix for typo in camera driver! value = settings.match(new RegExp([c.substr(0, c.length - 1), regexPart].join(''))); if (value && value.length > 1) { utils.log.debug("Controlvalue '%s' : %s", c, value[1]); try { control.value = value[1]; control.reset(); } catch (ex) { utils.log.error(ex); } } else { utils.log.error("Could not retrieve Controlvalue '%s'", c); } } }; var usercontrols = Controls.UserControls; var codeccontrols = Controls.CodecControls; var cameracontrols = Controls.CameraControls; var jpgcontrols = Controls.JPEGCompressionControls; getControls(usercontrols); getControls(codeccontrols); getControls(cameracontrols); getControls(jpgcontrols); WriteToFile(); } export function SetFrameRate(framerate: number) { execV4l2(`--set-parm=${framerate}`); } export function SetResolution(resolution: Resolution) { execV4l2(`--set-fmt-video=width=${resolution.Width},height=${resolution.Height}`); } export function SetPixelFormat(pixelformat: Pixelformat) { execV4l2(`--set-fmt-video=pixelformat=${pixelformat}`); } export function SetPriority(priority: ProcessPriority) { execV4l2(`--set-priority=${priority}`); } export function SetBrightness(brightness: number) { execV4l2(`--set-ctrl brightness=${brightness}`); } }
the_stack
import 'chrome://resources/cr_elements/cr_action_menu/cr_action_menu.js'; import 'chrome://resources/cr_elements/cr_icon_button/cr_icon_button.m.js'; import 'chrome://resources/cr_elements/cr_radio_group/cr_radio_group.m.js'; import 'chrome://resources/cr_elements/cr_radio_button/cr_radio_button.m.js'; import 'chrome://resources/cr_elements/icons.m.js'; import 'chrome://resources/cr_elements/shared_style_css.m.js'; import 'chrome://resources/cr_elements/shared_vars_css.m.js'; import 'chrome://resources/js/action_link.js'; import 'chrome://resources/cr_elements/action_link_css.m.js'; import 'chrome://resources/cr_elements/md_select_css.m.js'; import 'chrome://resources/polymer/v3_0/iron-icon/iron-icon.js'; import './runtime_hosts_dialog.js'; import './shared_style.js'; import './strings.m.js'; import {CrActionMenuElement} from 'chrome://resources/cr_elements/cr_action_menu/cr_action_menu.js'; import {assert} from 'chrome://resources/js/assert.m.js'; import {focusWithoutInk} from 'chrome://resources/js/cr/ui/focus_without_ink.m.js'; import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; import {html, PolymerElement} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {ItemDelegate} from './item.js'; /** Event interface for dom-repeat. */ interface RepeaterEvent extends CustomEvent { model: { item: string, }; } interface ExtensionsRuntimeHostPermissionsElement { $: { hostActionMenu: CrActionMenuElement, 'host-access': HTMLSelectElement, }; } class ExtensionsRuntimeHostPermissionsElement extends PolymerElement { static get is() { return 'extensions-runtime-host-permissions'; } static get template() { return html`{__html_template__}`; } static get properties() { return { /** * The underlying permissions data. */ permissions: Object, itemId: String, delegate: Object, /** * Whether the dialog to add a new host permission is shown. */ showHostDialog_: Boolean, /** * The current site of the entry that the host dialog is editing, if the * dialog is open for editing. */ hostDialogModel_: { type: String, value: null, }, /** * The element to return focus to once the host dialog closes. */ hostDialogAnchorElement_: { type: Object, value: null, }, /** * If the action menu is open, the site of the entry it is open for. * Otherwise null. */ actionMenuModel_: { type: String, value: null, }, /** * The element that triggered the action menu, so that the page will * return focus once the action menu (or dialog) closes. */ actionMenuAnchorElement_: { type: Object, value: null, }, /** * The old host access setting; used when we don't immediately commit the * change to host access so that we can reset it if the user cancels. */ oldHostAccess_: { type: String, value: null, }, /** * Indicator to track if an onHostAccessChange_ event is coming from the * setting being automatically reverted to the previous value, after a * change to a new value was canceled. */ revertingHostAccess_: { type: Boolean, value: false, }, /** * Proxying the enum to be used easily by the html template. */ HostAccess_: { type: Object, value: chrome.developerPrivate.HostAccess, }, /** * Whether the new site access menu should be shown. */ extensionsMenuAccessControlEnabled_: { type: Boolean, value: () => loadTimeData.getBoolean('extensionsMenuAccessControlEnabled'), }, }; } permissions: chrome.developerPrivate.RuntimeHostPermissions; itemId: string; delegate: ItemDelegate; private showHostDialog_: boolean; private hostDialogModel_: string|null; private hostDialogAnchorElement_: HTMLElement|null; private actionMenuModel_: string|null; private actionMenuAnchorElement_: HTMLElement|null; private oldHostAccess_: string|null; private revertingHostAccess_: boolean; private extensionsMenuAccessControlEnabled_: boolean; private onHostAccessChange_() { const selectMenu = this.$['host-access']; const access = selectMenu.value as chrome.developerPrivate.HostAccess; // Log a user action when the host access selection is changed by the user, // but not when reverting from a canceled change to another setting. if (!this.revertingHostAccess_) { switch (access) { case chrome.developerPrivate.HostAccess.ON_CLICK: chrome.metricsPrivate.recordUserAction( 'Extensions.Settings.Hosts.OnClickSelected'); break; case chrome.developerPrivate.HostAccess.ON_SPECIFIC_SITES: chrome.metricsPrivate.recordUserAction( 'Extensions.Settings.Hosts.OnSpecificSitesSelected'); break; case chrome.developerPrivate.HostAccess.ON_ALL_SITES: chrome.metricsPrivate.recordUserAction( 'Extensions.Settings.Hosts.OnAllSitesSelected'); break; } } if (access === chrome.developerPrivate.HostAccess.ON_SPECIFIC_SITES && this.permissions.hostAccess !== chrome.developerPrivate.HostAccess.ON_SPECIFIC_SITES) { // If the user is transitioning to the "on specific sites" option, show // the "add host" dialog. This serves two purposes: // - The user is prompted to add a host immediately, since otherwise // "on specific sites" is meaningless, and // - The way the C++ code differentiates between "on click" and "on // specific sites" is by checking if there are any specific sites. // This ensures there will be at least one, so that the host access // is properly calculated. this.oldHostAccess_ = this.permissions.hostAccess; this.doShowHostDialog_(selectMenu, null); } else { this.delegate.setItemHostAccess(this.itemId, access); } } private getHostPermissionsHeading_(): string { return loadTimeData.getString( this.extensionsMenuAccessControlEnabled_ ? 'newHostPermissionsHeading' : 'hostPermissionsHeading'); } private showSpecificSites_(): boolean { // TODO(crbug.com/1253673): Show a different "customize for each site" menu // for the new site access menu. return !this.extensionsMenuAccessControlEnabled_ && this.permissions.hostAccess === chrome.developerPrivate.HostAccess.ON_SPECIFIC_SITES; } /** * @return The granted host permissions as a sorted set of strings. */ private getRuntimeHosts_(): string[] { if (!this.permissions.hosts) { return []; } // Only show granted hosts in the list. // TODO(devlin): For extensions that request a finite set of hosts, // display them in a toggle list. https://crbug.com/891803. return this.permissions.hosts.filter(control => control.granted) .map(control => control.host) .sort(); } private onAddHostClick_(e: Event) { chrome.metricsPrivate.recordUserAction( 'Extensions.Settings.Hosts.AddHostActivated'); this.doShowHostDialog_(e.target as HTMLElement, null); } /** * @param anchorElement The element to return focus to once the dialog closes. * @param currentSite The site entry currently being edited, or null if this * is to add a new entry. */ private doShowHostDialog_( anchorElement: HTMLElement, currentSite: string|null) { this.hostDialogAnchorElement_ = anchorElement; this.hostDialogModel_ = currentSite; this.showHostDialog_ = true; } private onHostDialogClose_() { this.hostDialogModel_ = null; this.showHostDialog_ = false; focusWithoutInk(assert(this.hostDialogAnchorElement_!, 'Host Anchor')); this.hostDialogAnchorElement_ = null; this.oldHostAccess_ = null; } private onHostDialogCancel_() { // The user canceled the dialog. Set host-access back to the old value, // if the dialog was shown when just transitioning to a new state. chrome.metricsPrivate.recordUserAction( 'Extensions.Settings.Hosts.AddHostDialogCanceled'); if (this.oldHostAccess_) { assert(this.permissions.hostAccess === this.oldHostAccess_); this.revertingHostAccess_ = true; this.$['host-access'].value = this.oldHostAccess_; this.revertingHostAccess_ = false; this.oldHostAccess_ = null; } } private dialogShouldUpdateHostAccess_(): boolean { return !!this.oldHostAccess_; } private onEditHostClick_(e: RepeaterEvent) { chrome.metricsPrivate.recordUserAction( 'Extensions.Settings.Hosts.ActionMenuOpened'); this.actionMenuModel_ = e.model.item; this.actionMenuAnchorElement_ = e.target as HTMLElement; this.$.hostActionMenu.showAt(e.target as HTMLElement); } private onActionMenuEditClick_() { chrome.metricsPrivate.recordUserAction( 'Extensions.Settings.Hosts.ActionMenuEditActivated'); // Cache the site before closing the action menu, since it's cleared. const site = this.actionMenuModel_; // Cache and reset actionMenuAnchorElement_ so focus is not returned // to the action menu's trigger (since the dialog will be shown next). // Instead, curry the element to the dialog, so once it closes, focus // will be returned. const anchorElement = assert(this.actionMenuAnchorElement_!, 'Menu Anchor'); this.actionMenuAnchorElement_ = null; this.closeActionMenu_(); this.doShowHostDialog_(anchorElement, site); } private onActionMenuRemoveClick_() { chrome.metricsPrivate.recordUserAction( 'Extensions.Settings.Hosts.ActionMenuRemoveActivated'); this.delegate.removeRuntimeHostPermission( this.itemId, assert(this.actionMenuModel_!, 'Action Menu Model')); this.closeActionMenu_(); } private closeActionMenu_() { const menu = this.$.hostActionMenu; assert(menu.open); menu.close(); } private onLearnMoreClick_() { chrome.metricsPrivate.recordUserAction( 'Extensions.Settings.Hosts.LearnMoreActivated'); } } customElements.define( ExtensionsRuntimeHostPermissionsElement.is, ExtensionsRuntimeHostPermissionsElement);
the_stack
import * as nls from 'vs/nls'; import * as dom from 'vs/base/browser/dom'; import { Action, IAction } from 'vs/base/common/actions'; import { IConfigurationService } from 'vs/platform/configuration/common/configuration'; import { IContextMenuService, IContextViewService } from 'vs/platform/contextview/browser/contextView'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IThemeService, IColorTheme, registerThemingParticipant, ICssStyleCollector, ThemeIcon, Themable } from 'vs/platform/theme/common/themeService'; import { switchTerminalActionViewItemSeparator, switchTerminalShowTabsTitle } from 'vs/workbench/contrib/terminal/browser/terminalActions'; import { TERMINAL_BACKGROUND_COLOR, TERMINAL_BORDER_COLOR, TERMINAL_DRAG_AND_DROP_BACKGROUND, TERMINAL_TAB_ACTIVE_BORDER } from 'vs/workbench/contrib/terminal/common/terminalColorRegistry'; import { INotificationService, IPromptChoice, Severity } from 'vs/platform/notification/common/notification'; import { ICreateTerminalOptions, ITerminalGroupService, ITerminalInstance, ITerminalService, TerminalConnectionState, TerminalDataTransfers } from 'vs/workbench/contrib/terminal/browser/terminal'; import { ViewPane, IViewPaneOptions } from 'vs/workbench/browser/parts/views/viewPane'; import { IKeybindingService } from 'vs/platform/keybinding/common/keybinding'; import { IContextKey, IContextKeyService } from 'vs/platform/contextkey/common/contextkey'; import { IViewDescriptorService } from 'vs/workbench/common/views'; import { IOpenerService } from 'vs/platform/opener/common/opener'; import { PANEL_BACKGROUND, SIDE_BAR_BACKGROUND, EDITOR_DRAG_AND_DROP_BACKGROUND } from 'vs/workbench/common/theme'; import { IMenu, IMenuService, MenuId, MenuItemAction } from 'vs/platform/actions/common/actions'; import { ITerminalProfileResolverService, ITerminalProfileService, TerminalCommandId } from 'vs/workbench/contrib/terminal/common/terminal'; import { TerminalSettingId, ITerminalProfile, TerminalLocation } from 'vs/platform/terminal/common/terminal'; import { ActionViewItem, SelectActionViewItem } from 'vs/base/browser/ui/actionbar/actionViewItems'; import { attachSelectBoxStyler, attachStylerCallback } from 'vs/platform/theme/common/styler'; import { selectBorder } from 'vs/platform/theme/common/colorRegistry'; import { ISelectOptionItem } from 'vs/base/browser/ui/selectBox/selectBox'; import { IActionViewItem } from 'vs/base/browser/ui/actionbar/actionbar'; import { TerminalTabbedView } from 'vs/workbench/contrib/terminal/browser/terminalTabbedView'; import { Codicon } from 'vs/base/common/codicons'; import { ICommandService } from 'vs/platform/commands/common/commands'; import { renderLabelWithIcons } from 'vs/base/browser/ui/iconLabel/iconLabels'; import { getColorForSeverity } from 'vs/workbench/contrib/terminal/browser/terminalStatusList'; import { createAndFillInContextMenuActions, MenuEntryActionViewItem } from 'vs/platform/actions/browser/menuEntryActionViewItem'; import { DropdownWithPrimaryActionViewItem } from 'vs/platform/actions/browser/dropdownWithPrimaryActionViewItem'; import { dispose, IDisposable, toDisposable } from 'vs/base/common/lifecycle'; import { URI } from 'vs/base/common/uri'; import { ColorScheme } from 'vs/platform/theme/common/theme'; import { getColorClass, getUriClasses } from 'vs/workbench/contrib/terminal/browser/terminalIcon'; import { terminalStrings } from 'vs/workbench/contrib/terminal/common/terminalStrings'; import { withNullAsUndefined } from 'vs/base/common/types'; import { getTerminalActionBarArgs } from 'vs/workbench/contrib/terminal/browser/terminalMenus'; import { TerminalContextKeys } from 'vs/workbench/contrib/terminal/common/terminalContextKey'; import { getShellIntegrationTooltip } from 'vs/workbench/contrib/terminal/browser/terminalTooltip'; export class TerminalViewPane extends ViewPane { private _actions: IAction[] | undefined; private _fontStyleElement: HTMLElement | undefined; private _parentDomElement: HTMLElement | undefined; private _terminalTabbedView?: TerminalTabbedView; get terminalTabbedView(): TerminalTabbedView | undefined { return this._terminalTabbedView; } private _terminalsInitialized = false; private _isWelcomeShowing: boolean = false; private _tabButtons: DropdownWithPrimaryActionViewItem | undefined; private readonly _dropdownMenu: IMenu; private readonly _singleTabMenu: IMenu; private _viewShowing: IContextKey<boolean>; constructor( options: IViewPaneOptions, @IKeybindingService keybindingService: IKeybindingService, @IContextKeyService private readonly _contextKeyService: IContextKeyService, @IViewDescriptorService viewDescriptorService: IViewDescriptorService, @IConfigurationService configurationService: IConfigurationService, @IContextMenuService private readonly _contextMenuService: IContextMenuService, @IInstantiationService private readonly _instantiationService: IInstantiationService, @ITerminalService private readonly _terminalService: ITerminalService, @ITerminalGroupService private readonly _terminalGroupService: ITerminalGroupService, @IThemeService themeService: IThemeService, @ITelemetryService telemetryService: ITelemetryService, @INotificationService private readonly _notificationService: INotificationService, @IKeybindingService private readonly _keybindingService: IKeybindingService, @IOpenerService openerService: IOpenerService, @IMenuService private readonly _menuService: IMenuService, @ICommandService private readonly _commandService: ICommandService, @ITerminalProfileService private readonly _terminalProfileService: ITerminalProfileService, @ITerminalProfileResolverService private readonly _terminalProfileResolverService: ITerminalProfileResolverService, @IThemeService private readonly _themeService: IThemeService ) { super(options, keybindingService, _contextMenuService, configurationService, _contextKeyService, viewDescriptorService, _instantiationService, openerService, themeService, telemetryService); this._register(this._terminalService.onDidRegisterProcessSupport(() => { if (this._actions) { for (const action of this._actions) { action.enabled = true; } } this._onDidChangeViewWelcomeState.fire(); })); this._register(this._terminalService.onDidChangeInstances(() => { if (!this._isWelcomeShowing) { return; } this._isWelcomeShowing = true; this._onDidChangeViewWelcomeState.fire(); if (!this._terminalTabbedView && this._parentDomElement) { this._createTabsView(); this.layoutBody(this._parentDomElement.offsetHeight, this._parentDomElement.offsetWidth); } })); this._dropdownMenu = this._register(this._menuService.createMenu(MenuId.TerminalNewDropdownContext, this._contextKeyService)); this._singleTabMenu = this._register(this._menuService.createMenu(MenuId.TerminalInlineTabContext, this._contextKeyService)); this._register(this._terminalProfileService.onDidChangeAvailableProfiles(profiles => this._updateTabActionBar(profiles))); this._viewShowing = TerminalContextKeys.viewShowing.bindTo(this._contextKeyService); this._register(this.onDidChangeBodyVisibility(e => { if (e) { this._terminalTabbedView?.rerenderTabs(); } })); configurationService.onDidChangeConfiguration(e => { if ((e.affectsConfiguration(TerminalSettingId.ShellIntegrationDecorationsEnabled) && !configurationService.getValue(TerminalSettingId.ShellIntegrationDecorationsEnabled)) || (e.affectsConfiguration(TerminalSettingId.ShellIntegrationEnabled) && !configurationService.getValue(TerminalSettingId.ShellIntegrationEnabled))) { this._parentDomElement?.classList.remove('shell-integration'); } else if (configurationService.getValue(TerminalSettingId.ShellIntegrationDecorationsEnabled) && configurationService.getValue(TerminalSettingId.ShellIntegrationEnabled)) { this._parentDomElement?.classList.add('shell-integration'); } }); if (configurationService.getValue(TerminalSettingId.ShellIntegrationDecorationsEnabled) && configurationService.getValue(TerminalSettingId.ShellIntegrationEnabled)) { this._parentDomElement?.classList.add('shell-integration'); } } override renderBody(container: HTMLElement): void { super.renderBody(container); this._parentDomElement = container; this._parentDomElement.classList.add('integrated-terminal'); this._fontStyleElement = document.createElement('style'); this._instantiationService.createInstance(TerminalThemeIconStyle, this._parentDomElement); if (!this.shouldShowWelcome()) { this._createTabsView(); } this._parentDomElement.appendChild(this._fontStyleElement); this._register(this.configurationService.onDidChangeConfiguration(e => { if (e.affectsConfiguration(TerminalSettingId.FontFamily) || e.affectsConfiguration('editor.fontFamily')) { const configHelper = this._terminalService.configHelper; if (!configHelper.configFontIsMonospace()) { const choices: IPromptChoice[] = [{ label: nls.localize('terminal.useMonospace', "Use 'monospace'"), run: () => this.configurationService.updateValue(TerminalSettingId.FontFamily, 'monospace'), }]; this._notificationService.prompt(Severity.Warning, nls.localize('terminal.monospaceOnly', "The terminal only supports monospace fonts. Be sure to restart VS Code if this is a newly installed font."), choices); } } })); this._register(this.onDidChangeBodyVisibility(visible => { this._viewShowing.set(visible); if (visible) { const hadTerminals = !!this._terminalGroupService.groups.length; if (this._terminalService.isProcessSupportRegistered) { if (this._terminalsInitialized) { if (!hadTerminals) { this._terminalService.createTerminal({ location: TerminalLocation.Panel }); } } else { this._terminalsInitialized = true; this._terminalService.initializeTerminals(); } } else { this._onDidChangeViewWelcomeState.fire(); } // we don't know here whether or not it should be focused, so // defer focusing the panel to the focus() call // to prevent overriding preserveFocus for extensions this._terminalGroupService.showPanel(false); } else { for (const instance of this._terminalGroupService.instances) { instance.resetFocusContextKey(); } } this._terminalGroupService.updateVisibility(); })); this.layoutBody(this._parentDomElement.offsetHeight, this._parentDomElement.offsetWidth); } private _createTabsView(): void { if (!this._parentDomElement) { return; } this._terminalTabbedView = this.instantiationService.createInstance(TerminalTabbedView, this._parentDomElement); } // eslint-disable-next-line @typescript-eslint/naming-convention protected override layoutBody(height: number, width: number): void { super.layoutBody(height, width); this._terminalTabbedView?.layout(width, height); } override getActionViewItem(action: Action): IActionViewItem | undefined { switch (action.id) { case TerminalCommandId.Split: { // Split needs to be special cased to force splitting within the panel, not the editor const panelOnlySplitAction: IAction = { id: action.id, checked: action.checked, class: action.class, enabled: action.enabled, label: action.label, dispose: action.dispose.bind(action), tooltip: action.tooltip, run: async () => { const instance = this._terminalGroupService.activeInstance; if (instance) { const newInstance = await this._terminalService.createTerminal({ location: { parentTerminal: instance } }); return newInstance?.focusWhenReady(); } return; } }; return new ActionViewItem(action, panelOnlySplitAction, { icon: true, label: false, keybinding: this._getKeybindingLabel(action) }); } case TerminalCommandId.SwitchTerminal: { return this._instantiationService.createInstance(SwitchTerminalActionViewItem, action); } case TerminalCommandId.Focus: { const actions: IAction[] = []; createAndFillInContextMenuActions(this._singleTabMenu, undefined, actions); return this._instantiationService.createInstance(SingleTerminalTabActionViewItem, action, actions); } case TerminalCommandId.CreateWithProfileButton: { if (this._tabButtons) { this._tabButtons.dispose(); } const actions = getTerminalActionBarArgs(TerminalLocation.Panel, this._terminalProfileService.availableProfiles, this._getDefaultProfileName(), this._terminalProfileService.contributedProfiles, this._instantiationService, this._terminalService, this._contextKeyService, this._commandService, this._dropdownMenu); this._tabButtons = new DropdownWithPrimaryActionViewItem(actions.primaryAction, actions.dropdownAction, actions.dropdownMenuActions, actions.className, this._contextMenuService, {}, this._keybindingService, this._notificationService, this._contextKeyService, this._themeService); this._updateTabActionBar(this._terminalProfileService.availableProfiles); return this._tabButtons; } } return super.getActionViewItem(action); } private _getDefaultProfileName(): string { let defaultProfileName; try { defaultProfileName = this._terminalProfileService.getDefaultProfileName(); } catch (e) { defaultProfileName = this._terminalProfileResolverService.defaultProfileName; } return defaultProfileName!; } private _getKeybindingLabel(action: IAction): string | undefined { return withNullAsUndefined(this._keybindingService.lookupKeybinding(action.id)?.getLabel()); } private _updateTabActionBar(profiles: ITerminalProfile[]): void { const actions = getTerminalActionBarArgs(TerminalLocation.Panel, profiles, this._getDefaultProfileName(), this._terminalProfileService.contributedProfiles, this._instantiationService, this._terminalService, this._contextKeyService, this._commandService, this._dropdownMenu); this._tabButtons?.update(actions.dropdownAction, actions.dropdownMenuActions); } override focus() { if (this._terminalService.connectionState === TerminalConnectionState.Connecting) { // If the terminal is waiting to reconnect to remote terminals, then there is no TerminalInstance yet that can // be focused. So wait for connection to finish, then focus. const activeElement = document.activeElement; this._register(this._terminalService.onDidChangeConnectionState(() => { // Only focus the terminal if the activeElement has not changed since focus() was called // TODO hack if (document.activeElement === activeElement) { this._terminalGroupService.showPanel(true); } })); return; } this._terminalGroupService.showPanel(true); } override shouldShowWelcome(): boolean { this._isWelcomeShowing = !this._terminalService.isProcessSupportRegistered && this._terminalService.instances.length === 0; return this._isWelcomeShowing; } } registerThemingParticipant((theme: IColorTheme, collector: ICssStyleCollector) => { const panelBackgroundColor = theme.getColor(TERMINAL_BACKGROUND_COLOR) || theme.getColor(PANEL_BACKGROUND); collector.addRule(`.monaco-workbench .part.panel .pane-body.integrated-terminal .terminal-outer-container { background-color: ${panelBackgroundColor ? panelBackgroundColor.toString() : ''}; }`); const sidebarBackgroundColor = theme.getColor(TERMINAL_BACKGROUND_COLOR) || theme.getColor(SIDE_BAR_BACKGROUND); collector.addRule(`.monaco-workbench .part.sidebar .pane-body.integrated-terminal .terminal-outer-container { background-color: ${sidebarBackgroundColor ? sidebarBackgroundColor.toString() : ''}; }`); collector.addRule(`.monaco-workbench .part.auxiliarybar .pane-body.integrated-terminal .terminal-outer-container { background-color: ${sidebarBackgroundColor ? sidebarBackgroundColor.toString() : ''}; }`); const borderColor = theme.getColor(TERMINAL_BORDER_COLOR); if (borderColor) { collector.addRule(`.monaco-workbench .pane-body.integrated-terminal .split-view-view:not(:first-child) { border-color: ${borderColor.toString()}; }`); collector.addRule(`.monaco-workbench .pane-body.integrated-terminal .tabs-container { border-color: ${borderColor.toString()}; }`); } const dndBackgroundColor = theme.getColor(TERMINAL_DRAG_AND_DROP_BACKGROUND) || theme.getColor(EDITOR_DRAG_AND_DROP_BACKGROUND); if (dndBackgroundColor) { collector.addRule(`.monaco-workbench .pane-body.integrated-terminal .terminal-drop-overlay { background-color: ${dndBackgroundColor.toString()}; }`); } const activeTabBorderColor = theme.getColor(TERMINAL_TAB_ACTIVE_BORDER); if (activeTabBorderColor) { collector.addRule(`.monaco-workbench .pane-body.integrated-terminal .terminal-tabs-entry.is-active::before { background-color: ${activeTabBorderColor.toString()}; }`); } }); class SwitchTerminalActionViewItem extends SelectActionViewItem { constructor( action: IAction, @ITerminalService private readonly _terminalService: ITerminalService, @ITerminalGroupService private readonly _terminalGroupService: ITerminalGroupService, @IThemeService private readonly _themeService: IThemeService, @IContextViewService contextViewService: IContextViewService, @ITerminalProfileService terminalProfileService: ITerminalProfileService ) { super(null, action, getTerminalSelectOpenItems(_terminalService, _terminalGroupService), _terminalGroupService.activeGroupIndex, contextViewService, { ariaLabel: nls.localize('terminals', 'Open Terminals.'), optionsAsChildren: true }); this._register(_terminalService.onDidChangeInstances(() => this._updateItems(), this)); this._register(_terminalService.onDidChangeActiveGroup(() => this._updateItems(), this)); this._register(_terminalService.onDidChangeActiveInstance(() => this._updateItems(), this)); this._register(_terminalService.onDidChangeInstanceTitle(() => this._updateItems(), this)); this._register(_terminalGroupService.onDidChangeGroups(() => this._updateItems(), this)); this._register(_terminalService.onDidChangeConnectionState(() => this._updateItems(), this)); this._register(terminalProfileService.onDidChangeAvailableProfiles(() => this._updateItems(), this)); this._register(_terminalService.onDidChangeInstancePrimaryStatus(() => this._updateItems(), this)); this._register(attachSelectBoxStyler(this.selectBox, this._themeService)); } override render(container: HTMLElement): void { super.render(container); container.classList.add('switch-terminal'); this._register(attachStylerCallback(this._themeService, { selectBorder }, colors => { container.style.borderColor = colors.selectBorder ? `${colors.selectBorder}` : ''; })); } private _updateItems(): void { const options = getTerminalSelectOpenItems(this._terminalService, this._terminalGroupService); this.setOptions(options, this._terminalGroupService.activeGroupIndex); } } function getTerminalSelectOpenItems(terminalService: ITerminalService, terminalGroupService: ITerminalGroupService): ISelectOptionItem[] { let items: ISelectOptionItem[]; if (terminalService.connectionState === TerminalConnectionState.Connected) { items = terminalGroupService.getGroupLabels().map(label => { return { text: label }; }); } else { items = [{ text: nls.localize('terminalConnectingLabel', "Starting...") }]; } items.push({ text: switchTerminalActionViewItemSeparator, isDisabled: true }); items.push({ text: switchTerminalShowTabsTitle }); return items; } class SingleTerminalTabActionViewItem extends MenuEntryActionViewItem { private _color: string | undefined; private _altCommand: string | undefined; private _class: string | undefined; private readonly _elementDisposables: IDisposable[] = []; constructor( action: IAction, private readonly _actions: IAction[], @IKeybindingService keybindingService: IKeybindingService, @INotificationService notificationService: INotificationService, @IContextKeyService contextKeyService: IContextKeyService, @IThemeService themeService: IThemeService, @ITerminalService private readonly _terminalService: ITerminalService, @ITerminalGroupService private readonly _terminalGroupService: ITerminalGroupService, @IContextMenuService private readonly _contextMenuService: IContextMenuService, @ICommandService private readonly _commandService: ICommandService, @IConfigurationService configurationService: IConfigurationService ) { super(new MenuItemAction( { id: action.id, title: getSingleTabLabel(_terminalGroupService.activeInstance, _terminalService.configHelper.config.tabs.separator), tooltip: getSingleTabTooltip(_terminalGroupService.activeInstance, _terminalService.configHelper.config.tabs.separator, configurationService) }, { id: TerminalCommandId.Split, title: terminalStrings.split.value, icon: Codicon.splitHorizontal }, undefined, contextKeyService, _commandService ), { draggable: true }, keybindingService, notificationService, contextKeyService, themeService); // Register listeners to update the tab this._register(this._terminalService.onDidChangeInstancePrimaryStatus(e => this.updateLabel(e))); this._register(this._terminalGroupService.onDidChangeActiveInstance(() => this.updateLabel())); this._register(this._terminalService.onDidChangeInstanceIcon(e => this.updateLabel(e))); this._register(this._terminalService.onDidChangeInstanceColor(e => this.updateLabel(e))); this._register(this._terminalService.onDidChangeInstanceTitle(e => { if (e === this._terminalGroupService.activeInstance) { this._action.tooltip = getSingleTabTooltip(e, this._terminalService.configHelper.config.tabs.separator, configurationService); this.updateLabel(); } })); this._register(this._terminalService.onDidChangeInstanceCapability(e => { this._action.tooltip = getSingleTabTooltip(e, this._terminalService.configHelper.config.tabs.separator, configurationService); this.updateLabel(e); })); // Clean up on dispose this._register(toDisposable(() => dispose(this._elementDisposables))); } override async onClick(event: MouseEvent): Promise<void> { if (event.altKey && this._menuItemAction.alt) { this._commandService.executeCommand(this._menuItemAction.alt.id, { target: TerminalLocation.Panel } as ICreateTerminalOptions); } else { this._openContextMenu(); } } override updateLabel(e?: ITerminalInstance): void { // Only update if it's the active instance if (e && e !== this._terminalGroupService.activeInstance) { return; } if (this._elementDisposables.length === 0 && this.element && this.label) { // Right click opens context menu this._elementDisposables.push(dom.addDisposableListener(this.element, dom.EventType.CONTEXT_MENU, e => { if (e.button === 2) { this._openContextMenu(); e.preventDefault(); } })); // Middle click kills this._elementDisposables.push(dom.addDisposableListener(this.element, dom.EventType.AUXCLICK, e => { if (e.button === 1) { const instance = this._terminalGroupService.activeInstance; if (instance) { this._terminalService.safeDisposeTerminal(instance); } e.preventDefault(); } })); // Drag and drop this._elementDisposables.push(dom.addDisposableListener(this.element, dom.EventType.DRAG_START, e => { const instance = this._terminalGroupService.activeInstance; if (e.dataTransfer && instance) { e.dataTransfer.setData(TerminalDataTransfers.Terminals, JSON.stringify([instance.resource.toString()])); } })); } if (this.label) { const label = this.label; const instance = this._terminalGroupService.activeInstance; if (!instance) { dom.reset(label, ''); return; } label.classList.add('single-terminal-tab'); let colorStyle = ''; const primaryStatus = instance.statusList.primary; if (primaryStatus) { const colorKey = getColorForSeverity(primaryStatus.severity); this._themeService.getColorTheme(); const foundColor = this._themeService.getColorTheme().getColor(colorKey); if (foundColor) { colorStyle = foundColor.toString(); } } label.style.color = colorStyle; dom.reset(label, ...renderLabelWithIcons(getSingleTabLabel(instance, this._terminalService.configHelper.config.tabs.separator, ThemeIcon.isThemeIcon(this._commandAction.item.icon) ? this._commandAction.item.icon : undefined))); if (this._altCommand) { label.classList.remove(this._altCommand); this._altCommand = undefined; } if (this._color) { label.classList.remove(this._color); this._color = undefined; } if (this._class) { label.classList.remove(this._class); label.classList.remove('terminal-uri-icon'); this._class = undefined; } const colorClass = getColorClass(instance); if (colorClass) { this._color = colorClass; label.classList.add(colorClass); } const uriClasses = getUriClasses(instance, this._themeService.getColorTheme().type); if (uriClasses) { this._class = uriClasses?.[0]; label.classList.add(...uriClasses); } if (this._commandAction.item.icon) { this._altCommand = `alt-command`; label.classList.add(this._altCommand); } this.updateTooltip(); } } private _openContextMenu() { this._contextMenuService.showContextMenu({ getAnchor: () => this.element!, getActions: () => this._actions, getActionsContext: () => this.label }); } } function getSingleTabLabel(instance: ITerminalInstance | undefined, separator: string, icon?: ThemeIcon) { // Don't even show the icon if there is no title as the icon would shift around when the title // is added if (!instance || !instance.title) { return ''; } const iconClass = ThemeIcon.isThemeIcon(instance.icon) ? instance.icon?.id : Codicon.terminal.id; const label = `$(${icon?.id || iconClass}) ${getSingleTabTitle(instance, separator)}`; const primaryStatus = instance.statusList.primary; if (!primaryStatus?.icon) { return label; } return `${label} $(${primaryStatus.icon.id})`; } function getSingleTabTooltip(instance: ITerminalInstance | undefined, separator: string, configurationService: IConfigurationService): string { if (!instance) { return ''; } const shellIntegrationString = getShellIntegrationTooltip(instance, false, configurationService); const title = getSingleTabTitle(instance, separator); return shellIntegrationString ? title + shellIntegrationString : title; } function getSingleTabTitle(instance: ITerminalInstance | undefined, separator: string): string { if (!instance) { return ''; } return !instance.description ? instance.title : `${instance.title} ${separator} ${instance.description}`; } class TerminalThemeIconStyle extends Themable { private _styleElement: HTMLElement; constructor( container: HTMLElement, @IThemeService private readonly _themeService: IThemeService, @ITerminalService private readonly _terminalService: ITerminalService, @ITerminalGroupService private readonly _terminalGroupService: ITerminalGroupService ) { super(_themeService); this._registerListeners(); this._styleElement = document.createElement('style'); container.appendChild(this._styleElement); this._register(toDisposable(() => container.removeChild(this._styleElement))); this.updateStyles(); } private _registerListeners(): void { this._register(this._terminalService.onDidChangeInstanceIcon(() => this.updateStyles())); this._register(this._terminalService.onDidChangeInstanceColor(() => this.updateStyles())); this._register(this._terminalService.onDidChangeInstances(() => this.updateStyles())); this._register(this._terminalGroupService.onDidChangeGroups(() => this.updateStyles())); } override updateStyles(): void { super.updateStyles(); const colorTheme = this._themeService.getColorTheme(); // TODO: add a rule collector to avoid duplication let css = ''; // Add icons for (const instance of this._terminalService.instances) { const icon = instance.icon; if (!icon) { continue; } let uri = undefined; if (icon instanceof URI) { uri = icon; } else if (icon instanceof Object && 'light' in icon && 'dark' in icon) { uri = colorTheme.type === ColorScheme.LIGHT ? icon.light : icon.dark; } const iconClasses = getUriClasses(instance, colorTheme.type); if (uri instanceof URI && iconClasses && iconClasses.length > 1) { css += ( `.monaco-workbench .${iconClasses[0]} .monaco-highlighted-label .codicon, .monaco-action-bar .terminal-uri-icon.single-terminal-tab.action-label:not(.alt-command) .codicon` + `{background-image: ${dom.asCSSUrl(uri)};}` ); } } // Add colors for (const instance of this._terminalService.instances) { const colorClass = getColorClass(instance); if (!colorClass || !instance.color) { continue; } const color = colorTheme.getColor(instance.color); if (color) { // exclude status icons (file-icon) and inline action icons (trashcan and horizontalSplit) css += ( `.monaco-workbench .${colorClass} .codicon:first-child:not(.codicon-split-horizontal):not(.codicon-trashcan):not(.file-icon)` + `{ color: ${color} !important; }` ); } } this._styleElement.textContent = css; } }
the_stack
import * as Joi from '@hapi/joi'; /** * Helpers */ type ArrayType<T> = T extends (infer U)[] ? U : never; declare module '@hapi/joi' { /** * Allow extend() to use Joi types by default */ export function extend( extension: Extension | Extension[], ...extensions: Array<Extension | Extension[]> ): typeof Joi; /** * Field requirements interface */ interface Box<T, R extends boolean> { /** Type the schema holds */ T: T; /** If this attribute is required when inside an object */ R: R; } // Operators type BoxType<B, nT> = B extends Box<infer oT, infer oR> ? Box<nT, oR> : B; type BoxUnion<B, nT> = B extends Box<infer oT, infer oR> ? Box<oT | nT, oR> : B; type BoxIntersection<B, nT> = B extends Box<infer oT, infer oR> ? Box<oT & nT, oR> : B; type BoxReq<B, nR extends boolean> = B extends Box<infer oT, infer oR> ? Box<oT, nR> : B; type BoxSchema = Box<any, boolean>; /** * Every Schema that implements the Box to allow the extraction */ type BoxedPrimitive<T extends BoxSchema = any> = | BoxAnySchema<T> | BoxStringSchema<T> | BoxNumberSchema<T> | BoxBooleanSchema<T> | BoxDateSchema<T> | BoxFunctionSchema<T> | BoxArraySchema<T> | BoxObjectSchema<T> | BoxAlternativesSchema<T>; // Base types type primitiveType = string | number | boolean | Function | Date | undefined | null | void; export type mappedSchema = SchemaLike | BoxedPrimitive; export type mappedSchemaMap = { [K: string]: mappedSchema }; export type extendsGuard<T, S> = S extends T ? S : T; /** * Validation: extraction decorated methods */ export function validate<T, S extends mappedSchemaMap>( value: T, schema: S ): ValidationResult<extendsGuard<T, extractType<S>>>; export function validate<T, S extends mappedSchemaMap>( value: T, schema: S, options: ValidationOptions ): ValidationResult<extendsGuard<T, extractType<S>>>; export function validate<T, R, S extends mappedSchemaMap>( value: T, schema: S, options: ValidationOptions, callback: (err: ValidationError, value: extendsGuard<T, extractType<S>>) => R ): R; export function validate<T, R, S extends mappedSchemaMap>( value: T, schema: S, callback: (err: ValidationError, value: extendsGuard<T, extractType<S>>) => R ): R; // TODO: concat // concat(schema: this): this; // TODO: when // when(ref: string, options: WhenOptions): BoxAlternativesSchema; // when(ref: Reference, options: WhenOptions): BoxAlternativesSchema; // when(ref: Schema, options: WhenSchemaOptions): BoxAlternativesSchema; // TODO: see if .default union makes sense; export interface BoxAnySchema<N extends Box<any, boolean>> extends AnySchema { __schemaTypeLiteral: 'BoxAnySchema'; default<T>( value: T, description?: string ): this extends BoxAnySchema<infer B> ? BoxAnySchema<BoxUnion<B, T>> : never; default(value: any, description?: string): this; default(): this; allow<T>( ...values: T[] ): this extends BoxAnySchema<infer B> ? BoxAnySchema<BoxUnion<B, T>> : never; allow<T>( values: T[] ): this extends BoxAnySchema<infer B> ? BoxAnySchema<BoxUnion<B, T>> : never; allow(...values: any[]): this; allow(values: any[]): this; valid<T>( ...values: T[] ): this extends BoxAnySchema<infer B> ? BoxAnySchema<BoxType<B, T>> : never; valid<T>(values: T[]): this extends BoxAnySchema<infer B> ? BoxAnySchema<BoxType<B, T>> : never; valid(...values: any[]): this; valid(values: any[]): this; required(): this extends BoxAnySchema<infer B> ? BoxAnySchema<BoxReq<B, true>> : never; required(): this; exist(): this extends BoxAnySchema<infer B> ? BoxAnySchema<BoxReq<B, true>> : never; exist(): this; optional(): this extends BoxAnySchema<infer B> ? BoxAnySchema<BoxReq<B, false>> : never; optional(): this; } /** * String: extraction decorated schema */ export interface BoxStringSchema<N extends BoxSchema> extends StringSchema { __schemaTypeLiteral: 'BoxStringSchema'; default<T extends string>( value: T, description?: string ): this extends BoxStringSchema<infer B> ? BoxStringSchema<BoxUnion<B, T>> : never; default(value: any, description?: string): this; default(): this; allow<T>( ...values: T[] ): this extends BoxStringSchema<infer B> ? BoxStringSchema<BoxUnion<B, T>> : never; allow<T>( values: T[] ): this extends BoxStringSchema<infer B> ? BoxStringSchema<BoxUnion<B, T>> : never; allow(...values: any[]): this; allow(values: any[]): this; valid<T extends string>( ...values: T[] ): this extends BoxStringSchema<infer B> ? BoxStringSchema<BoxType<B, T>> : never; valid<T extends string>( values: T[] ): this extends BoxStringSchema<infer B> ? BoxStringSchema<BoxType<B, T>> : never; valid(...values: any[]): this; valid(values: any[]): this; required(): this extends BoxStringSchema<infer B> ? BoxStringSchema<BoxReq<B, true>> : never; required(): this; exist(): this extends BoxStringSchema<infer B> ? BoxStringSchema<BoxReq<B, true>> : never; exist(): this; optional(): this extends BoxStringSchema<infer B> ? BoxStringSchema<BoxReq<B, false>> : never; optional(): this; } /** * Number: extraction decorated schema */ export interface BoxNumberSchema<N extends BoxSchema> extends NumberSchema { __schemaTypeLiteral: 'BoxNumberSchema'; default<T extends number>( value: T, description?: string ): this extends BoxNumberSchema<infer B> ? BoxNumberSchema<BoxUnion<B, T>> : never; default(value: any, description?: string): this; default(): this; allow<T>( ...values: T[] ): this extends BoxNumberSchema<infer B> ? BoxNumberSchema<BoxUnion<B, T>> : never; allow<T>( values: T[] ): this extends BoxNumberSchema<infer B> ? BoxNumberSchema<BoxUnion<B, T>> : never; allow(...values: any[]): this; allow(values: any[]): this; valid<T extends string>( ...values: T[] ): this extends BoxNumberSchema<infer B> ? BoxNumberSchema<BoxType<B, T>> : never; valid<T extends string>( values: T[] ): this extends BoxNumberSchema<infer B> ? BoxNumberSchema<BoxType<B, T>> : never; valid(...values: any[]): this; valid(values: any[]): this; required(): this extends BoxNumberSchema<infer B> ? BoxNumberSchema<BoxReq<B, true>> : never; required(): this; exist(): this extends BoxNumberSchema<infer B> ? BoxNumberSchema<BoxReq<B, true>> : never; exist(): this; optional(): this extends BoxNumberSchema<infer B> ? BoxNumberSchema<BoxReq<B, false>> : never; optional(): this; } /** * Boolean: extraction decorated schema */ export interface BoxBooleanSchema<N extends BoxSchema> extends BooleanSchema { __schemaTypeLiteral: 'BoxBooleanSchema'; default<T extends boolean>( value: T, description?: string ): this extends BoxBooleanSchema<infer B> ? BoxBooleanSchema<BoxUnion<B, T>> : never; default(value: any, description?: string): this; default(): this; allow<T>( ...values: T[] ): this extends BoxBooleanSchema<infer B> ? BoxBooleanSchema<BoxUnion<B, T>> : never; allow<T>( values: T[] ): this extends BoxBooleanSchema<infer B> ? BoxBooleanSchema<BoxUnion<B, T>> : never; allow(...values: any[]): this; allow(values: any[]): this; valid<T extends string>( ...values: T[] ): this extends BoxBooleanSchema<infer B> ? BoxBooleanSchema<BoxType<B, T>> : never; valid<T extends string>( values: T[] ): this extends BoxBooleanSchema<infer B> ? BoxBooleanSchema<BoxType<B, T>> : never; valid(...values: any[]): this; valid(values: any[]): this; required(): this extends BoxBooleanSchema<infer B> ? BoxBooleanSchema<BoxReq<B, true>> : never; required(): this; exist(): this extends BoxBooleanSchema<infer B> ? BoxBooleanSchema<BoxReq<B, true>> : never; exist(): this; optional(): this extends BoxBooleanSchema<infer B> ? BoxBooleanSchema<BoxReq<B, false>> : never; optional(): this; } /** * Date: extraction decorated schema */ export interface BoxDateSchema<N extends BoxSchema> extends DateSchema { __schemaTypeLiteral: 'BoxDateSchema'; default<T extends Date>( value: T, description?: string ): this extends BoxDateSchema<infer B> ? BoxDateSchema<BoxUnion<B, T>> : never; default(value: any, description?: string): this; default(): this; allow<T>( ...values: T[] ): this extends BoxDateSchema<infer B> ? BoxDateSchema<BoxUnion<B, T>> : never; allow<T>( values: T[] ): this extends BoxDateSchema<infer B> ? BoxDateSchema<BoxUnion<B, T>> : never; allow(...values: any[]): this; allow(values: any[]): this; valid<T extends string>( ...values: T[] ): this extends BoxDateSchema<infer B> ? BoxDateSchema<BoxType<B, T>> : never; valid<T extends string>( values: T[] ): this extends BoxDateSchema<infer B> ? BoxDateSchema<BoxType<B, T>> : never; valid(...values: any[]): this; valid(values: any[]): this; required(): this extends BoxDateSchema<infer B> ? BoxDateSchema<BoxReq<B, true>> : never; required(): this; exist(): this extends BoxDateSchema<infer B> ? BoxDateSchema<BoxReq<B, true>> : never; exist(): this; optional(): this extends BoxDateSchema<infer B> ? BoxDateSchema<BoxReq<B, false>> : never; optional(): this; } /** * Function: extraction decorated schema */ export interface BoxFunctionSchema<N extends BoxSchema> extends FunctionSchema { __schemaTypeLiteral: 'BoxFunctionSchema'; allow<T>( ...values: T[] ): this extends BoxFunctionSchema<infer B> ? BoxFunctionSchema<BoxUnion<B, T>> : never; allow<T>( values: T[] ): this extends BoxFunctionSchema<infer B> ? BoxFunctionSchema<BoxUnion<B, T>> : never; allow(...values: any[]): this; allow(values: any[]): this; required(): this extends BoxFunctionSchema<infer B> ? BoxFunctionSchema<BoxReq<B, true>> : never; required(): this; exist(): this extends BoxFunctionSchema<infer B> ? BoxFunctionSchema<BoxReq<B, true>> : never; exist(): this; optional(): this extends BoxFunctionSchema<infer B> ? BoxFunctionSchema<BoxReq<B, false>> : never; optional(): this; } /** * Array: extraction decorated schema */ export interface BoxArraySchema<N extends BoxSchema> extends ArraySchema { __schemaTypeLiteral: 'BoxArraySchema'; default<T extends any[]>( value: T, description?: string ): this extends BoxArraySchema<infer B> ? BoxArraySchema<BoxUnion<B, ArrayType<T>>> : never; default(value: any, description?: string): this; default(): this; allow<T>( ...values: T[] ): this extends BoxArraySchema<infer B> ? BoxArraySchema<BoxUnion<B, T>> : never; allow<T>( values: T[] ): this extends BoxArraySchema<infer B> ? BoxArraySchema<BoxUnion<B, T>> : never; allow(...values: any[]): this; allow(values: any[]): this; items<T extends mappedSchema>( type: T ): this extends BoxArraySchema<infer B> ? BoxArraySchema<BoxUnion<B, extractType<T>>> : never; items(...types: SchemaLike[]): this; items(types: SchemaLike[]): this; required(): this extends BoxArraySchema<infer B> ? BoxArraySchema<BoxReq<B, true>> : never; required(): this; exist(): this extends BoxArraySchema<infer B> ? BoxArraySchema<BoxReq<B, true>> : never; exist(): this; optional(): this extends BoxArraySchema<infer B> ? BoxArraySchema<BoxReq<B, false>> : never; optional(): this; } /** * Object: extraction decorated schema */ export interface BoxObjectSchema<N extends BoxSchema> extends ObjectSchema { __schemaTypeLiteral: 'BoxObjectSchema'; default<T extends mappedSchemaMap>( value: T, description?: string ): this extends BoxObjectSchema<infer B> ? BoxObjectSchema<BoxUnion<B, extractType<T>>> : never; default(value: any, description?: string): this; default(): this; allow<T>( ...values: T[] ): this extends BoxObjectSchema<infer B> ? BoxObjectSchema<BoxUnion<B, T>> : never; allow<T>( values: T[] ): this extends BoxObjectSchema<infer B> ? BoxObjectSchema<BoxUnion<B, T>> : never; allow(...values: any[]): this; allow(values: any[]): this; keys<T extends mappedSchemaMap>( schema: T ): this extends BoxObjectSchema<infer B> ? BoxObjectSchema<BoxIntersection<B, extractMap<T>>> : never; keys(schema?: SchemaMap): this; append<T extends mappedSchemaMap>( schema: T ): this extends BoxObjectSchema<infer B> ? BoxObjectSchema<BoxIntersection<B, extractMap<T>>> : never; append(schema?: SchemaMap): this; pattern<S extends BoxStringSchema<any>, T extends mappedSchema>( pattern: S, schema: T ): this extends BoxObjectSchema<infer B> ? BoxObjectSchema<BoxIntersection<B, extractMap<{ [key in extractType<S>]: T }>>> : never; pattern<T extends mappedSchema>( pattern: RegExp, schema: T ): this extends BoxObjectSchema<infer B> ? BoxObjectSchema<BoxIntersection<B, extractMap<{ [key: string]: T }>>> : never; pattern(pattern: RegExp | SchemaLike, schema: SchemaLike): this; required(): this extends BoxObjectSchema<infer B> ? BoxObjectSchema<BoxReq<B, true>> : never; required(): this; exist(): this extends BoxObjectSchema<infer B> ? BoxObjectSchema<BoxReq<B, true>> : never; exist(): this; optional(): this extends BoxObjectSchema<infer B> ? BoxObjectSchema<BoxReq<B, false>> : never; optional(): this; } /** * Alternatives: extraction decorated schema */ export interface BoxAlternativesSchema<N extends BoxSchema> extends AlternativesSchema { __schemaTypeLiteral: 'BoxAlternativesSchema'; allow<T>( ...values: T[] ): this extends BoxAlternativesSchema<infer B> ? BoxAlternativesSchema<BoxUnion<B, T>> : never; allow<T>( values: T[] ): this extends BoxAlternativesSchema<infer B> ? BoxAlternativesSchema<BoxUnion<B, T>> : never; allow(...values: any[]): this; allow(values: any[]): this; try<T extends mappedSchema[]>( ...values: T ): this extends BoxAlternativesSchema<infer O> ? O extends Box<infer oT, infer oR> ? BoxAlternativesSchema<BoxType<O, oT | extractType<T>>> : BoxAlternativesSchema<Box<extractType<T>, false>> : BoxAlternativesSchema<Box<extractType<T>, false>>; try<T extends mappedSchema[]>( values: T ): this extends BoxAlternativesSchema<infer O> ? O extends Box<infer oT, infer oR> ? BoxAlternativesSchema<BoxType<O, oT | extractType<T>>> : BoxAlternativesSchema<Box<extractType<T>, false>> : BoxAlternativesSchema<Box<extractType<T>, false>>; try(...types: SchemaLike[]): this; try(types: SchemaLike[]): this; required(): this extends BoxAlternativesSchema<infer B> ? BoxAlternativesSchema<BoxReq<B, true>> : never; required(): this; exist(): this extends BoxAlternativesSchema<infer B> ? BoxAlternativesSchema<BoxReq<B, true>> : never; exist(): this; optional(): this extends BoxAlternativesSchema<infer B> ? BoxAlternativesSchema<BoxReq<B, false>> : never; optional(): this; when< R, T1 extends mappedSchema, T2 extends mappedSchema, T extends { then: T1; otherwise: T2 } >( ref: R, defs: T ): this extends BoxAlternativesSchema<infer O> ? O extends Box<infer oT, infer oR> ? BoxAlternativesSchema< BoxType<O, oT | extractType<T['then']> | extractType<T['otherwise']>> > : BoxAlternativesSchema<Box<extractType<T['then']> | extractType<T['otherwise']>, false>> : BoxAlternativesSchema<Box<extractType<T['then']> | extractType<T['otherwise']>, false>>; when(ref: string | Reference, options: WhenOptions): this; when(ref: Schema, options: WhenSchemaOptions): this; } // Factory methods. export function any<T extends any>(): BoxAnySchema<Box<T, false>>; export function string<T extends string>(): BoxStringSchema<Box<T, false>>; export function number<T extends number>(): BoxNumberSchema<Box<T, false>>; export function boolean<T extends boolean>(): BoxBooleanSchema<Box<T, false>>; export function date<T extends Date>(): BoxDateSchema<Box<T, false>>; export function func<T extends Function>(): BoxFunctionSchema<Box<T, false>>; export function array(): BoxArraySchema<Box<never, false>>; export function object<T extends mappedSchemaMap>( schema?: T ): BoxObjectSchema<Box<extractMap<T>, false>>; export function alternatives<T extends mappedSchema[]>( ...alts: T ): BoxAlternativesSchema<Box<extractType<typeof alts[number]>, false>>; export function alternatives<T extends mappedSchema[]>( alts: T ): BoxAlternativesSchema<Box<extractType<typeof alts[number]>, false>>; export function alt<T extends mappedSchema[]>( ...alts: T ): BoxAlternativesSchema<Box<extractType<typeof alts[number]>, false>>; export function alt<T extends mappedSchema[]>( alts: T ): BoxAlternativesSchema<Box<extractType<typeof alts[number]>, false>>; // Required | Optional properties engine // prettier-ignore type Required<T, K = keyof T> = { [j in K extends keyof T ? T[K] extends BoxedPrimitive<infer B> ? B['R'] extends true ? K : never : never : never]: true }; // prettier-ignore type Optional<T, K = keyof T> = { [j in K extends keyof T ? T[K] extends BoxedPrimitive<infer B> ? B['R'] extends false ? K : never : never : never]: true }; // prettier-ignore type extractMap<T extends mappedSchemaMap> = { [K in keyof Optional<T>]?: extractType<T[K]> } & { [K in keyof Required<T>]: extractType<T[K]> }; type maybeExtractBox<T> = T extends Box<infer O, infer R> ? O : T; // prettier-ignore type extractOne<T extends mappedSchema> = /** Primitive types */ T extends primitiveType ? T : /** Holds the extracted type */ T extends BoxAnySchema<infer O> ? maybeExtractBox<O> : T extends BoxBooleanSchema<infer O> ? maybeExtractBox<O> : T extends BoxStringSchema<infer O> ? maybeExtractBox<O> : T extends BoxNumberSchema<infer O> ? maybeExtractBox<O> : T extends BoxDateSchema<infer O> ? maybeExtractBox<O> : T extends BoxFunctionSchema<infer O> ? maybeExtractBox<O> : T extends BoxArraySchema<infer O> ? maybeExtractBox<O>[] : T extends BoxObjectSchema<infer O> ? maybeExtractBox<O> : T extends BoxAlternativesSchema<infer O> ? maybeExtractBox<O> : T extends AnySchema ? any : any; // prettier-ignore export type extractType<T extends mappedSchema> = /** * Hack to support [Schema1, Schema2, ...N] alternatives notation * Can't use extractType directly here because of cycles: * ``` * T extends Array<infer O> ? extractType<O> : * ^ cycle * ``` */ T extends Array<infer O> ? ( O extends SchemaLike ? extractOne<O> : O extends BoxedPrimitive ? extractOne<O> : O ) : /** * Handle Objects as schemas, without Joi.object at the root. * It needs to come first than mappedSchema. * It is difficult to avoid it to be inferred from extends clause. */ T extends mappedSchemaMap ? extractMap<T> : /** * This is the base case for every schema implemented */ T extends SchemaLike ? extractOne<T> : T extends BoxedPrimitive ? extractOne<T> : /** * Default case to handle primitives and schemas */ extractOne<T>; }
the_stack
import React from "react"; import styled from "styled-components"; import Tooltip from "./Tooltip"; import { Button } from "../src/components/Button"; import { useDispatch, useSelector, shallowEqual } from "react-redux"; import { setCurrentReview, setCreatePullRequest } from "@codestream/webview/store/context/actions"; import { useDidMount } from "@codestream/webview/utilities/hooks"; import { HostApi } from ".."; import { fetchReview } from "@codestream/webview/store/reviews/actions"; import { CodeStreamState } from "../store"; import { getReview } from "../store/reviews/reducer"; import { MinimumWidthCard, Meta, BigTitle, Header } from "./Codemark/BaseCodemark"; import { markItemRead, setReviewStatus } from "./actions"; import { ReviewCloseDiffRequestType } from "../ipc/host.protocol.review"; import Icon from "./Icon"; import { confirmPopup } from "./Confirm"; import { setUserPreference } from "./actions"; import { Dispatch } from "../store/common"; import { Review, BaseReviewMenu, BaseReviewHeader, ExpandedAuthor, Description } from "./Review"; import ScrollBox from "./ScrollBox"; import { TourTip } from "../src/components/TourTip"; import { Modal } from "./Modal"; import KeystrokeDispatcher from "../utilities/keystroke-dispatcher"; import { getReviewChangeRequests } from "../store/codemarks/reducer"; import { ReviewForm } from "./ReviewForm"; import { openPanel } from "../store/context/actions"; import { WebviewPanels } from "@codestream/protocols/webview"; import { isFeatureEnabled } from "../store/apiVersioning/reducer"; import { getPRLabel } from "../store/providers/reducer"; import { getSidebarLocation } from "../store/editorContext/reducer"; const NavHeader = styled.div` // flex-grow: 0; // flex-shrink: 0; // display: flex; // align-items: flex-start; padding: 35px 10px 10px 15px; // justify-content: center; width: 100%; ${Header} { margin-bottom: 0; } ${BigTitle} { font-size: 16px; } `; const Nav = styled.div` white-space: nowrap; margin-left: auto; margin: 15px 0 5px 20px; z-index: 50; &.pulse { opacity: 1 !important; } .btn-group { display: inline-block; margin-left: 8px; transition: transform 0.1s; transform-origin: 50% 0%; &:last-child { transform-origin: 100% 0%; } button { margin-left: 10px; &:first-child { margin-left: 0; } .narrow-icon { // display: none; margin-right: 5px; } } } `; const ClearModal = styled.div` position: absolute; z-index: 51; width: 100%; height: 100%; top: 0; left: 0; `; const Root = styled.div` max-height: 100%; display: flex; flex-direction: column; &.tour-on { ${Nav}, ${Meta}, ${Description}, ${ExpandedAuthor}, ${Header}, .replies-to-review { opacity: 0.25; } } #changed-files { transition: opacity 0.2s; } .pulse #changed-files { opacity: 1; box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2); background: var(--app-background-color-hover); } .scroll-container { flex-grow: 1; width: 100%; overflow: auto; zindex: 1; } // prefer icons to text @media only screen and (max-width: 430px) { .btn-group { button { .narrow-icon { display: block; margin: 0; } padding: 3px 5px; line-height: 1em; } } .wide-text { display: none; } } `; const Subtext = styled.div` padding-top: 5px; font-size: smaller; color: var(--text-color-subtle); `; export const ComposeArea = styled.div<{ side: "right" | "left" }>` width: 35px; height: 100%; position: fixed; left: ${props => (props.side === "right" ? "-36px" : "auto")}; right: ${props => (props.side === "left" ? "-36px" : "auto")}; top: 0; transition: left 0.1s; // background: var(--base-background-color); // border-right: 1px solid var(--base-border-color); background: var(--button-background-color); &.pulse { left: ${props => (props.side === "right" ? "0" : "auto")}; right: ${props => (props.side === "left" ? "0" : "auto")}; z-index: 5; } `; export const StyledReview = styled.div``; const Tip = styled.div` display: flex; button { margin-top: 10px; float: right; } b { display: block; clear: both; } `; export const Step = styled.div` display: flex; flex-shrink: 0; align-items: center; justify-content: center; font-size: 20px; width: 40px; height: 40px; border-radius: 50%; margin: 0 10px 10px 0; font-weight: bold; background: var(--button-background-color); color: var(--button-foreground-color); // background: var(--text-color-highlight); // color: var(--base-background-color); `; const modifier = navigator.appVersion.includes("Macintosh") ? "^ /" : "Ctrl-Shift-/"; export type Props = React.PropsWithChildren<{ reviewId: string; composeOpen: boolean }>; export function ReviewNav(props: Props) { const dispatch = useDispatch<Dispatch>(); const derivedState = useSelector((state: CodeStreamState) => { const { scmInfo } = state.editorContext; const filePath = scmInfo && scmInfo.scm ? scmInfo.scm.file : ""; const review = getReview(state.reviews, props.reviewId); const changeRequests = useSelector((state: CodeStreamState) => review ? getReviewChangeRequests(state, review) : [] ); const currentUserId = state.session.userId || ""; const approvedBy = (review && review.approvedBy) || {}; return { review, changeRequests, editorContext: state.editorContext, filePath, hideReviewInstructions: state.preferences.hideReviewInstructions, currentCodemarkId: state.context.currentCodemarkId, isInVscode: state.ide.name === "VSC", approvedByMe: approvedBy[currentUserId] ? true : false, isMine: currentUserId === (review ? review.creatorId : ""), cr2prEnabled: isFeatureEnabled(state, "cr2pr"), sidebarLocation: getSidebarLocation(state), prLabel: getPRLabel(state) }; }, shallowEqual); const [isEditing, setIsEditing] = React.useState(false); const [isAmending, setIsAmending] = React.useState(false); const [isApproving, setIsApproving] = React.useState(false); const [notFound, setNotFound] = React.useState(false); const [hoverButton, setHoverButton] = React.useState( derivedState.hideReviewInstructions ? "" : "files" ); const { review } = derivedState; const exit = async () => { // clear out the current review (set to blank) in the webview await dispatch(setCurrentReview()); // tell the extension to close the diff panel in the editor HostApi.instance.send(ReviewCloseDiffRequestType, {}); }; const showReview = async () => { await dispatch(setCurrentReview(review && review.id)); }; const unreadEnabled = useSelector((state: CodeStreamState) => isFeatureEnabled(state, "readItem") ); const markRead = () => { // @ts-ignore if (review && unreadEnabled) dispatch(markItemRead(review.id, review.numReplies || 0)); }; useDidMount(() => { let isValid = true; if (review == null) { dispatch(fetchReview(props.reviewId)).then(result => { if (!isValid) return; if (result == null) setNotFound(true); markRead(); }); } else { markRead(); } // Kind of a HACK leaving this here, BUT... // since <CancelButton /> uses the OLD version of Button.js // and not Button.tsx (below), there's no way to keep the style. // if Buttons can be consolidated, this could go away const disposable = KeystrokeDispatcher.onKeyDown( "Escape", event => { if (event.key === "Escape" && event.target.id !== "input-div") exit(); }, { source: "ReviewNav.tsx", level: -1 } ); return () => { disposable && disposable.dispose(); isValid = false; }; }); const approve = async () => { const numOpenChangeRequests = derivedState.changeRequests.filter(r => r.status !== "closed") .length; if (numOpenChangeRequests > 0) { confirmPopup({ title: "Are you sure?", message: "This review has open change requests.", centered: true, buttons: [ { label: "Cancel", className: "control-button" }, { label: "Approve Anyway", className: "success", wait: true, action: () => { dispatch(setReviewStatus(review!.id, "approved")); showReview(); } } ] }); } else { setIsApproving(true); await dispatch(setReviewStatus(review!.id, "approved")); showReview(); setIsApproving(false); } }; const reject = () => { confirmPopup({ title: "Are you sure?", message: "Author will be notified you are requesting this code be re-worked.", buttons: [ { label: "Go Back", className: "control-button" }, { label: "Request Changes", wait: true, action: rejectConfirm, className: "delete" } ] }); }; const rejectConfirm = () => { dispatch(setReviewStatus(review!.id, "rejected")); showReview(); }; const reopen = () => { dispatch(setReviewStatus(review!.id, "open")); }; const amend = () => { if (review!.status !== "open") reopen(); setIsAmending(true); }; const pr = async () => { await dispatch(setCreatePullRequest(props.reviewId)); await dispatch(setCurrentReview("")); dispatch(openPanel(WebviewPanels.NewPullRequest)); }; const highlightChanges = () => { const $changeDiv = document.getElementById("change-requests"); if ($changeDiv) { $changeDiv.classList.add("highlight-pulse"); setTimeout(() => { $changeDiv.classList.remove("highlight-pulse"); }, 1000); } }; const statusButtons = () => { if (!review) return null; const { approvedByMe, isMine } = derivedState; const numOpenChangeRequests = derivedState.changeRequests.filter(r => r.status !== "closed") .length; switch (review.status) { case "open": return ( <div className={hoverButton == "actions" ? "btn-group pulse" : "btn-group"}> {numOpenChangeRequests > 0 && !approvedByMe && ( <Tooltip title={ <> {numOpenChangeRequests} Pending Change Request {numOpenChangeRequests > 1 ? "s" : ""} </> } placement="top" > <Button variant="primary" onClick={highlightChanges}> <div className="narrow-icon" style={{ display: "inline-block", height: "16px", minWidth: "16px", lineHeight: "16px", textAlign: "center" }} > {numOpenChangeRequests} </div> <span className="wide-text">Pending</span> </Button> </Tooltip> )} {isMine && ( <Tooltip title="Amend Review (add code)" placement="top"> <Button onClick={amend}> <Icon className="narrow-icon" name="plus" /> <span className="wide-text">Amend</span> </Button> </Tooltip> )} {approvedByMe && ( <Tooltip title={ <div> You have approved this review. <br /> Click to withdraw approval. </div> } placement="top" > <Button variant="secondary" onClick={reopen}> <Icon className="narrow-icon" name="diff-removed" /> <span className="wide-text">Withdraw</span> </Button> </Tooltip> )} {numOpenChangeRequests === 0 && !approvedByMe && ( <Tooltip title="Approve Feedback Request" placement="top"> <Button variant="success" onClick={approve} isLoading={isApproving}> <Icon className="narrow-icon" name="thumbsup" /> <span className="wide-text">Approve</span> </Button> </Tooltip> )} <Tooltip title="Request Changes" placement="top"> <Button variant="destructive" onClick={reject}> <Icon className="narrow-icon" name="sync" /> <span className="wide-text">Request Changes</span> </Button> </Tooltip> <Tooltip title="More actions" placement="top"> <Button variant="secondary"> <BaseReviewMenu review={review} setIsEditing={setIsEditing} setIsAmending={setIsAmending} /> </Button> </Tooltip> </div> ); // case "closed": case "approved": case "rejected": return ( <div className={hoverButton == "actions" ? "btn-group pulse" : "btn-group"}> {derivedState.cr2prEnabled && isMine && review.pullRequestUrl == null && review.status === "approved" && ( <Tooltip title={`Create a ${derivedState.prLabel.PR}`} placement="top"> <Button onClick={pr}> <Icon className="narrow-icon" name="pull-request" /> <span className="wide-text">Create {derivedState.prLabel.PR}</span> </Button> </Tooltip> )} {isMine && review.pullRequestUrl == null && ( <Tooltip title="Reopen & Amend Review (add code)" placement="top"> <Button onClick={amend}> <Icon className="narrow-icon" name="plus" /> <span className="wide-text">Amend</span> </Button> </Tooltip> )} {review.pullRequestUrl == null && ( <Tooltip title="Reopen Review" placement="top"> <Button variant="secondary" onClick={reopen}> <Icon className="narrow-icon" name="reopen" /> <span className="wide-text">Reopen</span> </Button> </Tooltip> )} <Tooltip title="More actions" placement="top"> <Button variant="secondary"> <BaseReviewMenu review={review} setIsEditing={setIsEditing} setIsAmending={setIsAmending} /> </Button> </Tooltip> </div> ); default: return null; } return null; }; const toggleInstructions = () => { dispatch(setUserPreference(["hideReviewInstructions"], !derivedState.hideReviewInstructions)); }; if (notFound || !review) return ( <Modal verticallyCenter={true} onClose={exit}> <MinimumWidthCard> This review was not found. Perhaps it was deleted by the author, or you don't have permission to view it. <br /> <br /> <Button onClick={exit}>Exit</Button> </MinimumWidthCard> </Modal> ); if (derivedState.currentCodemarkId) return null; const tourDone = () => { setHoverButton(""); toggleInstructions(); }; const filesTip = hoverButton === "files" ? ( <Tip> <Step>1</Step> <div> Step through the changes of the review <Subtext>By clicking on filenames in any order</Subtext> <Button onClick={() => setHoverButton("comment")}>Next &gt;</Button> </div> </Tip> ) : ( undefined ); const commentTip = hoverButton === "comment" ? ( <Tip> <Step>2</Step> <div> Comment by selecting code in the right side of the diff <Subtext>You can also comment on related code as part of the review</Subtext> <Button onClick={() => { const el = document.getElementById("nav-header"); if (el) el.scrollIntoView(true); setHoverButton("actions"); }} > Next &gt; </Button> </div> </Tip> ) : ( undefined ); const actionsTip = hoverButton === "actions" ? ( <Tip> <Step>3</Step> <div> Approve or reject the review when finished <Subtext>Or pause to come back to it later</Subtext> <Button onClick={tourDone}>Done</Button> </div> </Tip> ) : ( undefined ); if (isEditing) { return <ReviewForm isEditing editingReview={review} onClose={() => setIsEditing(false)} />; } const { sidebarLocation } = derivedState; return ( <Root className={derivedState.hideReviewInstructions ? "" : "tour-on"}> {!derivedState.hideReviewInstructions && <ClearModal onClick={() => tourDone()} />} <NavHeader id="nav-header"> <BaseReviewHeader review={review} collapsed={false} setIsEditing={setIsEditing} setIsAmending={setIsAmending} > <></> </BaseReviewHeader> <Nav className={hoverButton == "actions" ? "pulse" : ""}> <TourTip title={actionsTip} placement="bottomLeft"> {statusButtons()} </TourTip> </Nav> </NavHeader> {props.composeOpen ? null : ( <div className="scroll-container"> <ScrollBox> <div className="vscroll" id="review-container" style={{ padding: "0 20px 60px 40px", width: "100%" }} > <StyledReview className={hoverButton == "files" ? "pulse" : ""}> <Review review={review} isAmending={isAmending} setIsAmending={setIsAmending} filesTip={filesTip} /> </StyledReview> {derivedState.hideReviewInstructions && ( <div style={{ marginTop: "50px", float: "right", cursor: "pointer", fontSize: "smaller", opacity: 0.5 }} > <span onClick={() => { const el = document.getElementById("changed-files"); if (el) el.scrollIntoView(true); setHoverButton("files"); toggleInstructions(); }} > Show Instructions </span> </div> )} </div> </ScrollBox> </div> )} <TourTip title={commentTip} placement={sidebarLocation === "right" ? "right" : "left"}> <ComposeArea side={sidebarLocation === "right" ? "right" : "left"} className={hoverButton == "comment" ? "pulse" : ""} /> </TourTip> </Root> ); }
the_stack
import { contactAction } from '../actions'; import { ContactStore } from '../stores/contact.store'; import { contactInit } from '../model'; import { mainAction } from '../../main/actions'; import { chatAction } from '../../chat/actions'; import { Util } from '../../../services/util'; import { global } from '../../../services/common'; export const contactReducer = (state: ContactStore = contactInit, { type, payload }) => { state.actionType = type; switch (type) { // 初始化state case contactAction.init: state = Util.deepCopyObj(contactInit); break; // 获取好友列表 case chatAction.getFriendList: if (payload === 'first') { state.groupLoading = true; } break; // 传递群列表 case chatAction.dispatchGroupList: state.groupList = Util.sortByLetter(payload); state.groupLoading = false; break; // 切换联系人或者会话的tab case mainAction.changeListTab: state.listTab = payload; changeListTab(state, payload); break; // 切换联系人中的tab case contactAction.changeTab: state.tab = payload; if (payload === 0) { updateUnreadNum(state); } break; // 添加好友邀请事件 case chatAction.friendInvitationEventSuccess: friendVerify(state, payload); break; // 自己拒绝添加好友 case contactAction.refuseAddFriendSuccess: isAgreeAddFriend(state, payload); break; // 自己同意添加好友 case contactAction.agreeAddFriendSuccess: isAgreeAddFriend(state, payload); break; // 自己同意添加好友失败 case contactAction.addFriendError: isAgreeAddFriend(state, payload); break; // 获取群组列表 case contactAction.getGroupList: if (payload === 'first') { state.friendLoading = true; } break; // 传递好友列表的数据 case chatAction.dispatchFriendList: state.friendList = Util.sortByLetter(payload); state.friendLoading = false; break; // 添加好友的应答事件 case chatAction.friendReplyEventSuccess: friendReply(state, payload); break; // 发送给好友验证信息 case chatAction.addFriendConfirm: waitReply(state, payload); break; // 添加好友同步事件 case chatAction.addFriendSyncEvent: addFriendSyncEvent(state, payload); break; // 传递收到进入邀请的事件 case chatAction.dispatchReceiveGroupInvitationEvent: filterVerifyGroupList(state, payload); break; // 同意或者拒绝入群成功 case contactAction.isAgreeEnterGroupSuccess: updateVerifyGroupList(state, payload); break; // 同意或者拒绝入群失败 case contactAction.isAgreeEnterGroupError: updateVerifyGroupList(state, payload); break; // 传递被拒绝入群的事件 case chatAction.dispatchReceiveGroupRefuseEvent: filterReceiveGroupRefuse(state, payload); break; // 切换验证信息的tab case contactAction.changeVerifyTab: state.verifyTab = payload; updateUnreadNum(state); break; default: } return state; }; // 切换左侧tab function changeListTab(state: ContactStore, payload) { if (payload === 1) { if (state.tab === 0) { if (state.verifyTab === 0) { state.singleVerifyUnreadNum = 0; } else if (state.verifyTab === 1) { state.groupVerifyUnreadNum = 0; } state.verifyUnreadNum = state.groupVerifyUnreadNum + state.singleVerifyUnreadNum; state.contactUnreadNum = state.verifyUnreadNum; } } } // 更新验证信息未读数 function updateUnreadNum(state: ContactStore) { if (state.verifyTab === 0) { state.singleVerifyUnreadNum = 0; state.verifyUnreadNum = state.groupVerifyUnreadNum; state.contactUnreadNum = state.verifyUnreadNum; changeFriendFirstOne(state); } else if (state.verifyTab === 1) { state.groupVerifyUnreadNum = 0; state.verifyUnreadNum = state.singleVerifyUnreadNum; state.contactUnreadNum = state.verifyUnreadNum; changeGroupFirstOne(state); } } // 多端在线同意好友请求事件 function addFriendSyncEvent(state: ContactStore, payload) { for (let user of payload.to_usernames) { for (let verifyMessage of state.verifyMessageList) { if (verifyMessage.stateType === 0 && verifyMessage.name === user.username) { verifyMessage.stateType = 4; break; } } } } // 等待好友验证 function waitReply(state: ContactStore, payload) { let verifyMessage = { name: payload.name, nickName: payload.nickName, avatarUrl: payload.avatarUrl, stateType: 6, type: 3, ctime_ms: new Date().getTime() }; /** * 对方同意 对方拒绝 已同意 已拒绝 * 这些验证消息在消息列表中是永远不会被覆盖的 */ for (let i = 0; i < state.verifyMessageList.length; i++) { const stateType = state.verifyMessageList[i].stateType; const canBeCover = stateType !== 3 && stateType !== 4 && stateType !== 5 && stateType !== 7; if (payload.name === state.verifyMessageList[i].name && canBeCover) { state.verifyMessageList.splice(i, 1); break; } } state.verifyMessageList.unshift(verifyMessage); } // 好友应答 function friendReply(state: ContactStore, payload) { payload.name = payload.from_username; let verifyMessage = { name: payload.from_username, nickName: payload.from_nickname, description: payload.description, avatarUrl: payload.avatarUrl, extra: payload.extra, eventId: payload.event_id, stateType: 0, type: 3, ctime_ms: payload.ctime_ms }; if (payload.return_code === 0) { verifyMessage.stateType = 5; } else { verifyMessage.stateType = 7; } for (let i = 0; i < state.verifyMessageList.length; i++) { const stateType = state.verifyMessageList[i].stateType; const canBeCover = stateType !== 3 && stateType !== 4 && stateType !== 5 && stateType !== 7; if (state.verifyMessageList[i].name === payload.from_username && canBeCover) { state.verifyMessageList.splice(i, 1); break; } } if (state.tab !== 0 || state.listTab !== 1 || (state.tab === 0 && state.verifyTab !== 0)) { state.singleVerifyUnreadNum++; state.verifyUnreadNum = state.groupVerifyUnreadNum + state.singleVerifyUnreadNum; state.contactUnreadNum = state.verifyUnreadNum; } state.verifyMessageList.unshift(verifyMessage); } // 标识好友验证消息已读 function changeFriendFirstOne(state: ContactStore) { for (let verifyMessage of state.verifyMessageList) { verifyMessage.isFriendFirstOne = false; } } // 标识群组验证信息已读 function changeGroupFirstOne(state: ContactStore) { for (let verifyMessage of state.verifyGroupList) { verifyMessage.isGroupFirstOne = false; } } // 同意或者拒绝好友请求 function isAgreeAddFriend(state: ContactStore, payload) { for (let verifyMessage of state.verifyMessageList) { if (verifyMessage.eventId === payload.eventId) { verifyMessage.stateType = payload.stateType; break; } } } // 邀请加好友 function friendVerify(state: ContactStore, payload) { let verifyMessage = { name: payload.from_username, nickName: payload.from_nickname, description: payload.description, avatarUrl: payload.avatarUrl, extra: payload.extra, eventId: payload.event_id, stateType: 0, type: 3, ctime_ms: payload.ctime_ms, isFriendFirstOne: false }; /** * verifyUnreadNum 用来标识验证信息的的未读数量 * contactUnreadNum 用来标识联系人的未读数量 * isFriendFirstOne 用来标识是否是同一用户的好友邀请的第一条消息(在未读状态),因为未读状态的第一条会显示数量,此后就不再增加未读数量 */ let flag = false; for (let i = 0; i < state.verifyMessageList.length; i++) { let message = state.verifyMessageList[i]; const stateType = message.stateType; const canBeCover = stateType !== 3 && stateType !== 4 && stateType !== 5 && stateType !== 7; if (message.name === verifyMessage.name && canBeCover) { if (message.stateType === 0) { if (message.isFriendFirstOne) { flag = true; } } state.verifyMessageList.splice(i, 1); break; } } if ((state.tab !== 0 || state.listTab !== 1 || (state.tab === 0 && state.verifyTab !== 0))) { if (!flag) { state.singleVerifyUnreadNum++; state.verifyUnreadNum = state.groupVerifyUnreadNum + state.singleVerifyUnreadNum; state.contactUnreadNum = state.verifyUnreadNum; } verifyMessage.isFriendFirstOne = true; } state.verifyMessageList.unshift(verifyMessage); } // 收到群组验证信息 function filterVerifyGroupList(state: ContactStore, payload) { payload.stateType = 0; payload.isGroupFirstOne = false; for (let user of payload.to_usernames) { let newPayload = Util.deepCopyObj(payload); newPayload.to_usernames = [user]; let flag = false; for (let i = 0; i < state.verifyGroupList.length; i++) { let verifyGroupList = state.verifyGroupList[i]; if ((verifyGroupList.stateType === 0 || verifyGroupList.stateType === 1 || verifyGroupList.stateType === 2) && verifyGroupList.from_gid === payload.from_gid && verifyGroupList.to_usernames[0].username === user.username) { if (verifyGroupList.isGroupFirstOne) { flag = true; } state.verifyGroupList.splice(i, 1); break; } } if (state.tab !== 0 || state.listTab !== 1 || (state.tab === 0 && state.verifyTab !== 1)) { if (!flag) { state.groupVerifyUnreadNum++; state.verifyUnreadNum = state.groupVerifyUnreadNum + state.singleVerifyUnreadNum; state.contactUnreadNum = state.verifyUnreadNum; } newPayload.isGroupFirstOne = true; } state.verifyGroupList.unshift(newPayload); } } // 更新群组验证信息 function updateVerifyGroupList(state: ContactStore, payload) { for (let verifyGroup of state.verifyGroupList) { if (verifyGroup.event_id === payload.event_id && verifyGroup.to_usernames[0].username === payload.to_usernames[0].username) { verifyGroup.stateType = payload.stateType; break; } } } // 收到入群被拒绝的事件 function filterReceiveGroupRefuse(state: ContactStore, payload) { if (payload.to_usernames[0].username === global.user) { payload.stateType = 5; } else { payload.stateType = 6; } if (state.tab !== 0 || state.listTab !== 1 || (state.tab === 0 && state.verifyTab !== 1)) { state.groupVerifyUnreadNum++; state.verifyUnreadNum = state.groupVerifyUnreadNum + state.singleVerifyUnreadNum; state.contactUnreadNum = state.verifyUnreadNum; } state.verifyGroupList.unshift(payload); }
the_stack
import { ApiContactComponent } from './pages/api/api-contact/api-contact.component'; import { ApiDocumentationComponent } from './pages/api/api-documentation/api-documentation.component'; import { ApiGeneralComponent } from './pages/api/api-general/api-general.component'; import { ApiHomepageResolver } from './resolvers/api-homepage.resolver'; import { ApiInformationsResolver } from './resolvers/api-informations.resolver'; import { ApiResolver } from './resolvers/api.resolver'; import { ApiSubscribeComponent } from './pages/api/api-subscribe/api-subscribe.component'; import { AuthGuardService } from './services/auth-guard.service'; import { CatalogSearchComponent } from './pages/catalog/search/catalog-search.component'; import { CategoriesComponent } from './pages/catalog/categories/categories.component'; import { FilterApiQuery } from '../../projects/portal-webclient-sdk/src/lib'; import { DashboardComponent } from './pages/dashboard/dashboard.component'; import { DocumentationComponent } from './pages/documentation/documentation.component'; import { FeatureEnum } from './model/feature.enum'; import { FeatureGuardService } from './services/feature-guard.service'; import { FilteredCatalogComponent } from './pages/catalog/filtered-catalog/filtered-catalog.component'; import { GvHeaderItemComponent } from './components/gv-header-item/gv-header-item.component'; import { GvSearchApiComponent } from './components/gv-search-api/gv-search-api.component'; import { HomepageComponent } from './pages/homepage/homepage.component'; import { LoginComponent } from './pages/login/login.component'; import { LogoutComponent } from './pages/logout/logout.component'; import { marker as i18n } from '@biesbjerg/ngx-translate-extract-marker'; import { NgModule } from '@angular/core'; import { NotFoundComponent } from './pages/not-found/not-found.component'; import { RegistrationComponent } from './pages/registration/registration.component'; import { RegistrationConfirmationComponent } from './pages/registration/registration-confirmation/registration-confirmation.component'; import { ResetPasswordComponent } from './pages/reset-password/reset-password.component'; import { ResetPasswordConfirmationComponent } from './pages/reset-password/reset-password-confirmation/reset-password-confirmation.component'; import { Role } from './model/role.enum'; import { RouterModule, Routes } from '@angular/router'; import { SinglePageComponent } from './pages/single-page/single-page.component'; import { SubscribeGuardService } from './services/subscribe-guard.service'; import { UserAccountComponent } from './pages/user/user-account/user-account.component'; import { UserContactComponent } from './pages/user/user-contact/user-contact.component'; import { UserNotificationComponent } from './pages/user/user-notification/user-notification.component'; import { CookiesComponent } from './pages/cookies/cookies.component'; import { CategoryResolver } from './resolvers/category.resolver'; import { PermissionsResolver } from './resolvers/permissions-resolver.service'; import { PermissionGuardService } from './services/permission-guard.service'; import { TicketsHistoryComponent } from './components/gv-tickets-history/tickets-history.component'; export const routes: Routes = [ { path: '', component: HomepageComponent, data: { title: i18n('route.homepage'), menu: false, animation: { type: 'fade' } } }, { path: 'dashboard', component: DashboardComponent, data: { title: i18n('route.dashboard'), expectedRole: Role.AUTH_USER, animation: { type: 'fade' }, menu: {} }, canActivate: [AuthGuardService], }, { path: 'catalog', data: { title: i18n('route.catalog'), menu: { hiddenPaths: ['categories/:categoryId', 'api/'] }, fallbackRedirectTo: 'catalog/all', }, children: [ { path: '', redirectTo: 'categories', pathMatch: 'full' }, { path: 'search', component: CatalogSearchComponent }, { path: 'api/:apiId', data: { menu: { slots: { top: GvHeaderItemComponent }, hiddenPaths: ['subscribe'] }, }, resolve: { api: ApiResolver, apiInformations: ApiInformationsResolver, permissions: PermissionsResolver, }, children: [ { path: '', component: ApiGeneralComponent, data: { menu: { slots: { 'right-transition': GvSearchApiComponent } }, icon: 'general:clipboard', title: i18n('route.catalogApi'), animation: { type: 'slide', group: 'api', index: 1 }, }, resolve: { apiHomepage: ApiHomepageResolver, }, }, { path: 'doc', component: ApiDocumentationComponent, data: { menu: { slots: { 'right-transition': GvSearchApiComponent } }, icon: 'home:library', title: i18n('route.catalogApiDocumentation'), animation: { type: 'fade' }, }, }, { path: 'contact', component: ApiContactComponent, canActivate: [AuthGuardService, FeatureGuardService], data: { menu: { slots: { 'right-transition': GvSearchApiComponent } }, icon: 'communication:contact#1', title: i18n('route.catalogApiContact'), expectedFeature: FeatureEnum.contact, expectedRole: Role.AUTH_USER, animation: { type: 'slide', group: 'api', index: 3 }, }, }, { path: 'tickets', component: TicketsHistoryComponent, data: { title: i18n('route.tickets'), icon: 'communication:snoozed-mail', expectedFeature: FeatureEnum.contact, expectedRole: Role.AUTH_USER, animation: { type: 'slide', group: 'user', index: 4 }, }, }, { path: 'subscribe', component: ApiSubscribeComponent, canActivate: [SubscribeGuardService], data: { title: i18n('route.catalogApiSubscribe'), }, }, ], }, { path: 'categories', component: CategoriesComponent, canActivate: [FeatureGuardService], data: { expectedFeature: FeatureEnum.categoryMode, title: i18n('route.catalogCategories'), icon: 'layout:layout-arrange', menu: { slots: { 'right-transition': GvSearchApiComponent } }, animation: { type: 'slide', group: 'catalog', index: 1 }, }, }, { path: 'categories/:categoryId', component: FilteredCatalogComponent, resolve: { category: CategoryResolver }, data: { title: i18n('route.catalogCategory'), menu: { hide: true, slots: { top: GvHeaderItemComponent, 'right-transition': GvSearchApiComponent } }, }, }, { path: 'all', component: FilteredCatalogComponent, data: { title: i18n('route.catalogAll'), icon: 'code:git#2', menu: { slots: { 'right-transition': GvSearchApiComponent } }, filterApiQuery: FilterApiQuery.ALL, animation: { type: 'slide', group: 'catalog', index: 2 }, }, }, { path: 'featured', component: FilteredCatalogComponent, data: { title: i18n('route.catalogFeatured'), icon: 'home:flower#2', menu: { slots: { 'right-transition': GvSearchApiComponent } }, filterApiQuery: FilterApiQuery.FEATURED, animation: { type: 'slide', group: 'catalog', index: 3 }, }, }, { path: 'starred', component: FilteredCatalogComponent, canActivate: [FeatureGuardService], data: { title: i18n('route.catalogStarred'), icon: 'general:star', menu: { slots: { 'right-transition': GvSearchApiComponent } }, filterApiQuery: FilterApiQuery.STARRED, expectedFeature: FeatureEnum.rating, animation: { type: 'slide', group: 'catalog', index: 4 }, }, }, { path: 'trendings', component: FilteredCatalogComponent, data: { title: i18n('route.catalogTrending'), icon: 'home:fireplace', menu: { slots: { 'right-transition': GvSearchApiComponent } }, filterApiQuery: FilterApiQuery.TRENDINGS, animation: { type: 'slide', group: 'catalog', index: 5 }, }, }, ], }, { path: 'user', data: { menu: { hiddenPaths: ['login', 'logout'] } }, children: [ { path: 'login', component: LoginComponent, canActivate: [AuthGuardService], data: { title: i18n('route.login'), expectedRole: Role.GUEST, animation: { type: 'fade' }, }, }, { path: 'account', component: UserAccountComponent, canActivate: [AuthGuardService], data: { title: i18n('route.user'), icon: 'general:user', expectedRole: Role.AUTH_USER, animation: { type: 'slide', group: 'user', index: 1 }, }, }, { path: 'contact', component: UserContactComponent, canActivate: [AuthGuardService, FeatureGuardService], data: { title: i18n('route.contact'), icon: 'communication:contact#1', expectedFeature: FeatureEnum.contact, expectedRole: Role.AUTH_USER, animation: { type: 'slide', group: 'user', index: 2 }, }, }, { path: 'tickets', component: TicketsHistoryComponent, canActivate: [AuthGuardService, FeatureGuardService], data: { title: i18n('route.tickets'), icon: 'communication:snoozed-mail', expectedFeature: FeatureEnum.contact, expectedRole: Role.AUTH_USER, animation: { type: 'slide', group: 'user', index: 3 }, }, }, { path: 'notifications', component: UserNotificationComponent, canActivate: [AuthGuardService, FeatureGuardService], data: { title: i18n('route.notifications'), icon: 'general:notifications#2', expectedRole: Role.AUTH_USER, animation: { type: 'slide', group: 'user', index: 4 }, }, }, { path: 'logout', component: LogoutComponent, canActivate: [AuthGuardService], data: { title: i18n('route.logout'), separator: true, icon: 'home:door-open', expectedRole: Role.AUTH_USER, }, }, { path: 'registration', component: RegistrationComponent, canActivate: [AuthGuardService], data: { expectedRole: Role.GUEST, animation: { type: 'fade' } }, }, { path: 'registration/confirm/:token', component: RegistrationConfirmationComponent, canActivate: [AuthGuardService], data: { expectedRole: Role.GUEST, animation: { type: 'fade' } }, }, { path: 'resetPassword', component: ResetPasswordComponent, canActivate: [AuthGuardService], data: { expectedRole: Role.GUEST, animation: { type: 'fade' } }, }, { path: 'resetPassword/confirm/:token', component: ResetPasswordConfirmationComponent, canActivate: [AuthGuardService], data: { expectedRole: Role.GUEST, animation: { type: 'fade' } }, }, ], }, { path: 'documentation', children: [ { path: '', redirectTo: 'root', pathMatch: 'full' }, { path: ':rootDir', component: DocumentationComponent, data: { animation: { type: 'fade' } } }, ], }, { path: 'pages/:pageId', component: SinglePageComponent }, { path: 'applications', loadChildren: () => import('./pages/applications/applications.module').then((m) => m.ApplicationsModule), canActivate: [AuthGuardService, PermissionGuardService], data: { title: i18n('route.applications'), menu: { hiddenPaths: ['creation'] }, expectedRole: Role.AUTH_USER, animation: {}, expectedPermissions: ['APPLICATION-R'], }, }, { path: 'cookies', component: CookiesComponent, data: { title: i18n('route.cookies') } }, { path: '**', component: NotFoundComponent, data: { title: i18n('route.notFound') } }, ]; @NgModule({ imports: [ RouterModule.forRoot(routes, { scrollPositionRestoration: 'disabled', }), ], exports: [RouterModule], }) export class AppRoutingModule {}
the_stack
/* eslint-disable @typescript-eslint/class-name-casing */ /* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable @typescript-eslint/no-empty-interface */ /* eslint-disable @typescript-eslint/no-namespace */ /* eslint-disable no-irregular-whitespace */ import { OAuth2Client, JWT, Compute, UserRefreshClient, BaseExternalAccountClient, GaxiosPromise, GoogleConfigurable, createAPIRequest, MethodOptions, StreamMethodOptions, GlobalOptions, GoogleAuth, BodyResponseCallback, APIRequestContext, } from 'googleapis-common'; import {Readable} from 'stream'; export namespace essentialcontacts_v1 { export interface Options extends GlobalOptions { version: 'v1'; } interface StandardParameters { /** * Auth client or API Key for the request */ auth?: | string | OAuth2Client | JWT | Compute | UserRefreshClient | BaseExternalAccountClient | GoogleAuth; /** * V1 error format. */ '$.xgafv'?: string; /** * OAuth access token. */ access_token?: string; /** * Data format for response. */ alt?: string; /** * JSONP */ callback?: string; /** * Selector specifying which fields to include in a partial response. */ fields?: string; /** * API key. Your API key identifies your project and provides you with API access, quota, and reports. Required unless you provide an OAuth 2.0 token. */ key?: string; /** * OAuth 2.0 token for the current user. */ oauth_token?: string; /** * Returns response with indentations and line breaks. */ prettyPrint?: boolean; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string assigned to a user, but should not exceed 40 characters. */ quotaUser?: string; /** * Legacy upload protocol for media (e.g. "media", "multipart"). */ uploadType?: string; /** * Upload protocol for media (e.g. "raw", "multipart"). */ upload_protocol?: string; } /** * Essential Contacts API * * * * @example * ```js * const {google} = require('googleapis'); * const essentialcontacts = google.essentialcontacts('v1'); * ``` */ export class Essentialcontacts { context: APIRequestContext; folders: Resource$Folders; organizations: Resource$Organizations; projects: Resource$Projects; constructor(options: GlobalOptions, google?: GoogleConfigurable) { this.context = { _options: options || {}, google, }; this.folders = new Resource$Folders(this.context); this.organizations = new Resource$Organizations(this.context); this.projects = new Resource$Projects(this.context); } } /** * Response message for the ComputeContacts method. */ export interface Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse { /** * All contacts for the resource that are subscribed to the specified notification categories, including contacts inherited from any parent resources. */ contacts?: Schema$GoogleCloudEssentialcontactsV1Contact[]; /** * If there are more results than those appearing in this response, then `next_page_token` is included. To get the next set of results, call this method again using the value of `next_page_token` as `page_token` and the rest of the parameters the same as the original request. */ nextPageToken?: string | null; } /** * A contact that will receive notifications from Google Cloud. */ export interface Schema$GoogleCloudEssentialcontactsV1Contact { /** * Required. The email address to send notifications to. This does not need to be a Google account. */ email?: string | null; /** * The preferred language for notifications, as a ISO 639-1 language code. See [Supported languages](https://cloud.google.com/resource-manager/docs/managing-notification-contacts#supported-languages) for a list of supported languages. */ languageTag?: string | null; /** * The identifier for the contact. Format: {resource_type\}/{resource_id\}/contacts/{contact_id\} */ name?: string | null; /** * The categories of notifications that the contact will receive communications for. */ notificationCategorySubscriptions?: string[] | null; /** * The last time the validation_state was updated, either manually or automatically. A contact is considered stale if its validation state was updated more than 1 year ago. */ validateTime?: string | null; /** * The validity of the contact. A contact is considered valid if it is the correct recipient for notifications for a particular resource. */ validationState?: string | null; } /** * Response message for the ListContacts method. */ export interface Schema$GoogleCloudEssentialcontactsV1ListContactsResponse { /** * The contacts for the specified resource. */ contacts?: Schema$GoogleCloudEssentialcontactsV1Contact[]; /** * If there are more results than those appearing in this response, then `next_page_token` is included. To get the next set of results, call this method again using the value of `next_page_token` as `page_token` and the rest of the parameters the same as the original request. */ nextPageToken?: string | null; } /** * Request message for the SendTestMessage method. */ export interface Schema$GoogleCloudEssentialcontactsV1SendTestMessageRequest { /** * Required. The list of names of the contacts to send a test message to. Format: organizations/{organization_id\}/contacts/{contact_id\}, folders/{folder_id\}/contacts/{contact_id\} or projects/{project_id\}/contacts/{contact_id\} */ contacts?: string[] | null; /** * Required. The notification category to send the test message for. All contacts must be subscribed to this category. */ notificationCategory?: string | null; } /** * A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A typical example is to use it as the request or the response type of an API method. For instance: service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); \} The JSON representation for `Empty` is empty JSON object `{\}`. */ export interface Schema$GoogleProtobufEmpty {} export class Resource$Folders { context: APIRequestContext; contacts: Resource$Folders$Contacts; constructor(context: APIRequestContext) { this.context = context; this.contacts = new Resource$Folders$Contacts(this.context); } } export class Resource$Folders$Contacts { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Lists all contacts for the resource that are subscribed to the specified notification categories, including contacts inherited from any parent resources. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/essentialcontacts.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const essentialcontacts = google.essentialcontacts('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await essentialcontacts.folders.contacts.compute({ * // The categories of notifications to compute contacts for. If ALL is included in this list, contacts subscribed to any notification category will be returned. * notificationCategories: 'placeholder-value', * // Optional. The maximum number of results to return from this request. Non-positive values are ignored. The presence of `next_page_token` in the response indicates that more results might be available. If not specified, the default page_size is 100. * pageSize: 'placeholder-value', * // Optional. If present, retrieves the next batch of results from the preceding call to this method. `page_token` must be the value of `next_page_token` from the previous response. The values of other method parameters should be identical to those in the previous call. * pageToken: 'placeholder-value', * // Required. The name of the resource to compute contacts for. Format: organizations/{organization_id\}, folders/{folder_id\} or projects/{project_id\} * parent: 'folders/my-folder', * }); * console.log(res.data); * * // Example response * // { * // "contacts": [], * // "nextPageToken": "my_nextPageToken" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ compute( params: Params$Resource$Folders$Contacts$Compute, options: StreamMethodOptions ): GaxiosPromise<Readable>; compute( params?: Params$Resource$Folders$Contacts$Compute, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse>; compute( params: Params$Resource$Folders$Contacts$Compute, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; compute( params: Params$Resource$Folders$Contacts$Compute, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse>, callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse> ): void; compute( params: Params$Resource$Folders$Contacts$Compute, callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse> ): void; compute( callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse> ): void; compute( paramsOrCallback?: | Params$Resource$Folders$Contacts$Compute | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Folders$Contacts$Compute; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Folders$Contacts$Compute; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://essentialcontacts.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+parent}/contacts:compute').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse>( parameters ); } } /** * Adds a new contact for a resource. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/essentialcontacts.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const essentialcontacts = google.essentialcontacts('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await essentialcontacts.folders.contacts.create({ * // Required. The resource to save this contact for. Format: organizations/{organization_id\}, folders/{folder_id\} or projects/{project_id\} * parent: 'folders/my-folder', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "email": "my_email", * // "languageTag": "my_languageTag", * // "name": "my_name", * // "notificationCategorySubscriptions": [], * // "validateTime": "my_validateTime", * // "validationState": "my_validationState" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "email": "my_email", * // "languageTag": "my_languageTag", * // "name": "my_name", * // "notificationCategorySubscriptions": [], * // "validateTime": "my_validateTime", * // "validationState": "my_validationState" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ create( params: Params$Resource$Folders$Contacts$Create, options: StreamMethodOptions ): GaxiosPromise<Readable>; create( params?: Params$Resource$Folders$Contacts$Create, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudEssentialcontactsV1Contact>; create( params: Params$Resource$Folders$Contacts$Create, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; create( params: Params$Resource$Folders$Contacts$Create, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact>, callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> ): void; create( params: Params$Resource$Folders$Contacts$Create, callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> ): void; create( callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> ): void; create( paramsOrCallback?: | Params$Resource$Folders$Contacts$Create | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudEssentialcontactsV1Contact> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Folders$Contacts$Create; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Folders$Contacts$Create; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://essentialcontacts.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+parent}/contacts').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudEssentialcontactsV1Contact>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudEssentialcontactsV1Contact>( parameters ); } } /** * Deletes a contact. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/essentialcontacts.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const essentialcontacts = google.essentialcontacts('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await essentialcontacts.folders.contacts.delete({ * // Required. The name of the contact to delete. Format: organizations/{organization_id\}/contacts/{contact_id\}, folders/{folder_id\}/contacts/{contact_id\} or projects/{project_id\}/contacts/{contact_id\} * name: 'folders/my-folder/contacts/my-contact', * }); * console.log(res.data); * * // Example response * // {} * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ delete( params: Params$Resource$Folders$Contacts$Delete, options: StreamMethodOptions ): GaxiosPromise<Readable>; delete( params?: Params$Resource$Folders$Contacts$Delete, options?: MethodOptions ): GaxiosPromise<Schema$GoogleProtobufEmpty>; delete( params: Params$Resource$Folders$Contacts$Delete, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; delete( params: Params$Resource$Folders$Contacts$Delete, options: MethodOptions | BodyResponseCallback<Schema$GoogleProtobufEmpty>, callback: BodyResponseCallback<Schema$GoogleProtobufEmpty> ): void; delete( params: Params$Resource$Folders$Contacts$Delete, callback: BodyResponseCallback<Schema$GoogleProtobufEmpty> ): void; delete(callback: BodyResponseCallback<Schema$GoogleProtobufEmpty>): void; delete( paramsOrCallback?: | Params$Resource$Folders$Contacts$Delete | BodyResponseCallback<Schema$GoogleProtobufEmpty> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleProtobufEmpty> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleProtobufEmpty> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleProtobufEmpty> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Folders$Contacts$Delete; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Folders$Contacts$Delete; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://essentialcontacts.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'DELETE', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleProtobufEmpty>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleProtobufEmpty>(parameters); } } /** * Gets a single contact. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/essentialcontacts.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const essentialcontacts = google.essentialcontacts('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await essentialcontacts.folders.contacts.get({ * // Required. The name of the contact to retrieve. Format: organizations/{organization_id\}/contacts/{contact_id\}, folders/{folder_id\}/contacts/{contact_id\} or projects/{project_id\}/contacts/{contact_id\} * name: 'folders/my-folder/contacts/my-contact', * }); * console.log(res.data); * * // Example response * // { * // "email": "my_email", * // "languageTag": "my_languageTag", * // "name": "my_name", * // "notificationCategorySubscriptions": [], * // "validateTime": "my_validateTime", * // "validationState": "my_validationState" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Folders$Contacts$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Folders$Contacts$Get, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudEssentialcontactsV1Contact>; get( params: Params$Resource$Folders$Contacts$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Folders$Contacts$Get, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact>, callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> ): void; get( params: Params$Resource$Folders$Contacts$Get, callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> ): void; get( callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> ): void; get( paramsOrCallback?: | Params$Resource$Folders$Contacts$Get | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudEssentialcontactsV1Contact> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Folders$Contacts$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Folders$Contacts$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://essentialcontacts.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudEssentialcontactsV1Contact>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudEssentialcontactsV1Contact>( parameters ); } } /** * Lists the contacts that have been set on a resource. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/essentialcontacts.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const essentialcontacts = google.essentialcontacts('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await essentialcontacts.folders.contacts.list({ * // Optional. The maximum number of results to return from this request. Non-positive values are ignored. The presence of `next_page_token` in the response indicates that more results might be available. If not specified, the default page_size is 100. * pageSize: 'placeholder-value', * // Optional. If present, retrieves the next batch of results from the preceding call to this method. `page_token` must be the value of `next_page_token` from the previous response. The values of other method parameters should be identical to those in the previous call. * pageToken: 'placeholder-value', * // Required. The parent resource name. Format: organizations/{organization_id\}, folders/{folder_id\} or projects/{project_id\} * parent: 'folders/my-folder', * }); * console.log(res.data); * * // Example response * // { * // "contacts": [], * // "nextPageToken": "my_nextPageToken" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Folders$Contacts$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Folders$Contacts$List, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse>; list( params: Params$Resource$Folders$Contacts$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Folders$Contacts$List, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse>, callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse> ): void; list( params: Params$Resource$Folders$Contacts$List, callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse> ): void; list( callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse> ): void; list( paramsOrCallback?: | Params$Resource$Folders$Contacts$List | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Folders$Contacts$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Folders$Contacts$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://essentialcontacts.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+parent}/contacts').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse>( parameters ); } } /** * Updates a contact. Note: A contact's email address cannot be changed. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/essentialcontacts.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const essentialcontacts = google.essentialcontacts('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await essentialcontacts.folders.contacts.patch({ * // The identifier for the contact. Format: {resource_type\}/{resource_id\}/contacts/{contact_id\} * name: 'folders/my-folder/contacts/my-contact', * // Optional. The update mask applied to the resource. For the `FieldMask` definition, see https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask * updateMask: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "email": "my_email", * // "languageTag": "my_languageTag", * // "name": "my_name", * // "notificationCategorySubscriptions": [], * // "validateTime": "my_validateTime", * // "validationState": "my_validationState" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "email": "my_email", * // "languageTag": "my_languageTag", * // "name": "my_name", * // "notificationCategorySubscriptions": [], * // "validateTime": "my_validateTime", * // "validationState": "my_validationState" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ patch( params: Params$Resource$Folders$Contacts$Patch, options: StreamMethodOptions ): GaxiosPromise<Readable>; patch( params?: Params$Resource$Folders$Contacts$Patch, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudEssentialcontactsV1Contact>; patch( params: Params$Resource$Folders$Contacts$Patch, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; patch( params: Params$Resource$Folders$Contacts$Patch, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact>, callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> ): void; patch( params: Params$Resource$Folders$Contacts$Patch, callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> ): void; patch( callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> ): void; patch( paramsOrCallback?: | Params$Resource$Folders$Contacts$Patch | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudEssentialcontactsV1Contact> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Folders$Contacts$Patch; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Folders$Contacts$Patch; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://essentialcontacts.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'PATCH', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudEssentialcontactsV1Contact>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudEssentialcontactsV1Contact>( parameters ); } } /** * Allows a contact admin to send a test message to contact to verify that it has been configured correctly. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/essentialcontacts.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const essentialcontacts = google.essentialcontacts('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await essentialcontacts.folders.contacts.sendTestMessage({ * // Required. The name of the resource to send the test message for. All contacts must either be set directly on this resource or inherited from another resource that is an ancestor of this one. Format: organizations/{organization_id\}, folders/{folder_id\} or projects/{project_id\} * resource: 'folders/my-folder', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "contacts": [], * // "notificationCategory": "my_notificationCategory" * // } * }, * }); * console.log(res.data); * * // Example response * // {} * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ sendTestMessage( params: Params$Resource$Folders$Contacts$Sendtestmessage, options: StreamMethodOptions ): GaxiosPromise<Readable>; sendTestMessage( params?: Params$Resource$Folders$Contacts$Sendtestmessage, options?: MethodOptions ): GaxiosPromise<Schema$GoogleProtobufEmpty>; sendTestMessage( params: Params$Resource$Folders$Contacts$Sendtestmessage, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; sendTestMessage( params: Params$Resource$Folders$Contacts$Sendtestmessage, options: MethodOptions | BodyResponseCallback<Schema$GoogleProtobufEmpty>, callback: BodyResponseCallback<Schema$GoogleProtobufEmpty> ): void; sendTestMessage( params: Params$Resource$Folders$Contacts$Sendtestmessage, callback: BodyResponseCallback<Schema$GoogleProtobufEmpty> ): void; sendTestMessage( callback: BodyResponseCallback<Schema$GoogleProtobufEmpty> ): void; sendTestMessage( paramsOrCallback?: | Params$Resource$Folders$Contacts$Sendtestmessage | BodyResponseCallback<Schema$GoogleProtobufEmpty> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleProtobufEmpty> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleProtobufEmpty> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleProtobufEmpty> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Folders$Contacts$Sendtestmessage; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Folders$Contacts$Sendtestmessage; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://essentialcontacts.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+resource}/contacts:sendTestMessage').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['resource'], pathParams: ['resource'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleProtobufEmpty>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleProtobufEmpty>(parameters); } } } export interface Params$Resource$Folders$Contacts$Compute extends StandardParameters { /** * The categories of notifications to compute contacts for. If ALL is included in this list, contacts subscribed to any notification category will be returned. */ notificationCategories?: string[]; /** * Optional. The maximum number of results to return from this request. Non-positive values are ignored. The presence of `next_page_token` in the response indicates that more results might be available. If not specified, the default page_size is 100. */ pageSize?: number; /** * Optional. If present, retrieves the next batch of results from the preceding call to this method. `page_token` must be the value of `next_page_token` from the previous response. The values of other method parameters should be identical to those in the previous call. */ pageToken?: string; /** * Required. The name of the resource to compute contacts for. Format: organizations/{organization_id\}, folders/{folder_id\} or projects/{project_id\} */ parent?: string; } export interface Params$Resource$Folders$Contacts$Create extends StandardParameters { /** * Required. The resource to save this contact for. Format: organizations/{organization_id\}, folders/{folder_id\} or projects/{project_id\} */ parent?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudEssentialcontactsV1Contact; } export interface Params$Resource$Folders$Contacts$Delete extends StandardParameters { /** * Required. The name of the contact to delete. Format: organizations/{organization_id\}/contacts/{contact_id\}, folders/{folder_id\}/contacts/{contact_id\} or projects/{project_id\}/contacts/{contact_id\} */ name?: string; } export interface Params$Resource$Folders$Contacts$Get extends StandardParameters { /** * Required. The name of the contact to retrieve. Format: organizations/{organization_id\}/contacts/{contact_id\}, folders/{folder_id\}/contacts/{contact_id\} or projects/{project_id\}/contacts/{contact_id\} */ name?: string; } export interface Params$Resource$Folders$Contacts$List extends StandardParameters { /** * Optional. The maximum number of results to return from this request. Non-positive values are ignored. The presence of `next_page_token` in the response indicates that more results might be available. If not specified, the default page_size is 100. */ pageSize?: number; /** * Optional. If present, retrieves the next batch of results from the preceding call to this method. `page_token` must be the value of `next_page_token` from the previous response. The values of other method parameters should be identical to those in the previous call. */ pageToken?: string; /** * Required. The parent resource name. Format: organizations/{organization_id\}, folders/{folder_id\} or projects/{project_id\} */ parent?: string; } export interface Params$Resource$Folders$Contacts$Patch extends StandardParameters { /** * The identifier for the contact. Format: {resource_type\}/{resource_id\}/contacts/{contact_id\} */ name?: string; /** * Optional. The update mask applied to the resource. For the `FieldMask` definition, see https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask */ updateMask?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudEssentialcontactsV1Contact; } export interface Params$Resource$Folders$Contacts$Sendtestmessage extends StandardParameters { /** * Required. The name of the resource to send the test message for. All contacts must either be set directly on this resource or inherited from another resource that is an ancestor of this one. Format: organizations/{organization_id\}, folders/{folder_id\} or projects/{project_id\} */ resource?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudEssentialcontactsV1SendTestMessageRequest; } export class Resource$Organizations { context: APIRequestContext; contacts: Resource$Organizations$Contacts; constructor(context: APIRequestContext) { this.context = context; this.contacts = new Resource$Organizations$Contacts(this.context); } } export class Resource$Organizations$Contacts { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Lists all contacts for the resource that are subscribed to the specified notification categories, including contacts inherited from any parent resources. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/essentialcontacts.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const essentialcontacts = google.essentialcontacts('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await essentialcontacts.organizations.contacts.compute({ * // The categories of notifications to compute contacts for. If ALL is included in this list, contacts subscribed to any notification category will be returned. * notificationCategories: 'placeholder-value', * // Optional. The maximum number of results to return from this request. Non-positive values are ignored. The presence of `next_page_token` in the response indicates that more results might be available. If not specified, the default page_size is 100. * pageSize: 'placeholder-value', * // Optional. If present, retrieves the next batch of results from the preceding call to this method. `page_token` must be the value of `next_page_token` from the previous response. The values of other method parameters should be identical to those in the previous call. * pageToken: 'placeholder-value', * // Required. The name of the resource to compute contacts for. Format: organizations/{organization_id\}, folders/{folder_id\} or projects/{project_id\} * parent: 'organizations/my-organization', * }); * console.log(res.data); * * // Example response * // { * // "contacts": [], * // "nextPageToken": "my_nextPageToken" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ compute( params: Params$Resource$Organizations$Contacts$Compute, options: StreamMethodOptions ): GaxiosPromise<Readable>; compute( params?: Params$Resource$Organizations$Contacts$Compute, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse>; compute( params: Params$Resource$Organizations$Contacts$Compute, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; compute( params: Params$Resource$Organizations$Contacts$Compute, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse>, callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse> ): void; compute( params: Params$Resource$Organizations$Contacts$Compute, callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse> ): void; compute( callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse> ): void; compute( paramsOrCallback?: | Params$Resource$Organizations$Contacts$Compute | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Organizations$Contacts$Compute; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Organizations$Contacts$Compute; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://essentialcontacts.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+parent}/contacts:compute').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse>( parameters ); } } /** * Adds a new contact for a resource. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/essentialcontacts.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const essentialcontacts = google.essentialcontacts('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await essentialcontacts.organizations.contacts.create({ * // Required. The resource to save this contact for. Format: organizations/{organization_id\}, folders/{folder_id\} or projects/{project_id\} * parent: 'organizations/my-organization', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "email": "my_email", * // "languageTag": "my_languageTag", * // "name": "my_name", * // "notificationCategorySubscriptions": [], * // "validateTime": "my_validateTime", * // "validationState": "my_validationState" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "email": "my_email", * // "languageTag": "my_languageTag", * // "name": "my_name", * // "notificationCategorySubscriptions": [], * // "validateTime": "my_validateTime", * // "validationState": "my_validationState" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ create( params: Params$Resource$Organizations$Contacts$Create, options: StreamMethodOptions ): GaxiosPromise<Readable>; create( params?: Params$Resource$Organizations$Contacts$Create, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudEssentialcontactsV1Contact>; create( params: Params$Resource$Organizations$Contacts$Create, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; create( params: Params$Resource$Organizations$Contacts$Create, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact>, callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> ): void; create( params: Params$Resource$Organizations$Contacts$Create, callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> ): void; create( callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> ): void; create( paramsOrCallback?: | Params$Resource$Organizations$Contacts$Create | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudEssentialcontactsV1Contact> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Organizations$Contacts$Create; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Organizations$Contacts$Create; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://essentialcontacts.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+parent}/contacts').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudEssentialcontactsV1Contact>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudEssentialcontactsV1Contact>( parameters ); } } /** * Deletes a contact. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/essentialcontacts.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const essentialcontacts = google.essentialcontacts('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await essentialcontacts.organizations.contacts.delete({ * // Required. The name of the contact to delete. Format: organizations/{organization_id\}/contacts/{contact_id\}, folders/{folder_id\}/contacts/{contact_id\} or projects/{project_id\}/contacts/{contact_id\} * name: 'organizations/my-organization/contacts/my-contact', * }); * console.log(res.data); * * // Example response * // {} * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ delete( params: Params$Resource$Organizations$Contacts$Delete, options: StreamMethodOptions ): GaxiosPromise<Readable>; delete( params?: Params$Resource$Organizations$Contacts$Delete, options?: MethodOptions ): GaxiosPromise<Schema$GoogleProtobufEmpty>; delete( params: Params$Resource$Organizations$Contacts$Delete, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; delete( params: Params$Resource$Organizations$Contacts$Delete, options: MethodOptions | BodyResponseCallback<Schema$GoogleProtobufEmpty>, callback: BodyResponseCallback<Schema$GoogleProtobufEmpty> ): void; delete( params: Params$Resource$Organizations$Contacts$Delete, callback: BodyResponseCallback<Schema$GoogleProtobufEmpty> ): void; delete(callback: BodyResponseCallback<Schema$GoogleProtobufEmpty>): void; delete( paramsOrCallback?: | Params$Resource$Organizations$Contacts$Delete | BodyResponseCallback<Schema$GoogleProtobufEmpty> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleProtobufEmpty> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleProtobufEmpty> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleProtobufEmpty> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Organizations$Contacts$Delete; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Organizations$Contacts$Delete; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://essentialcontacts.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'DELETE', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleProtobufEmpty>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleProtobufEmpty>(parameters); } } /** * Gets a single contact. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/essentialcontacts.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const essentialcontacts = google.essentialcontacts('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await essentialcontacts.organizations.contacts.get({ * // Required. The name of the contact to retrieve. Format: organizations/{organization_id\}/contacts/{contact_id\}, folders/{folder_id\}/contacts/{contact_id\} or projects/{project_id\}/contacts/{contact_id\} * name: 'organizations/my-organization/contacts/my-contact', * }); * console.log(res.data); * * // Example response * // { * // "email": "my_email", * // "languageTag": "my_languageTag", * // "name": "my_name", * // "notificationCategorySubscriptions": [], * // "validateTime": "my_validateTime", * // "validationState": "my_validationState" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Organizations$Contacts$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Organizations$Contacts$Get, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudEssentialcontactsV1Contact>; get( params: Params$Resource$Organizations$Contacts$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Organizations$Contacts$Get, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact>, callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> ): void; get( params: Params$Resource$Organizations$Contacts$Get, callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> ): void; get( callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> ): void; get( paramsOrCallback?: | Params$Resource$Organizations$Contacts$Get | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudEssentialcontactsV1Contact> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Organizations$Contacts$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Organizations$Contacts$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://essentialcontacts.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudEssentialcontactsV1Contact>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudEssentialcontactsV1Contact>( parameters ); } } /** * Lists the contacts that have been set on a resource. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/essentialcontacts.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const essentialcontacts = google.essentialcontacts('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await essentialcontacts.organizations.contacts.list({ * // Optional. The maximum number of results to return from this request. Non-positive values are ignored. The presence of `next_page_token` in the response indicates that more results might be available. If not specified, the default page_size is 100. * pageSize: 'placeholder-value', * // Optional. If present, retrieves the next batch of results from the preceding call to this method. `page_token` must be the value of `next_page_token` from the previous response. The values of other method parameters should be identical to those in the previous call. * pageToken: 'placeholder-value', * // Required. The parent resource name. Format: organizations/{organization_id\}, folders/{folder_id\} or projects/{project_id\} * parent: 'organizations/my-organization', * }); * console.log(res.data); * * // Example response * // { * // "contacts": [], * // "nextPageToken": "my_nextPageToken" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Organizations$Contacts$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Organizations$Contacts$List, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse>; list( params: Params$Resource$Organizations$Contacts$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Organizations$Contacts$List, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse>, callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse> ): void; list( params: Params$Resource$Organizations$Contacts$List, callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse> ): void; list( callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse> ): void; list( paramsOrCallback?: | Params$Resource$Organizations$Contacts$List | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Organizations$Contacts$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Organizations$Contacts$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://essentialcontacts.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+parent}/contacts').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse>( parameters ); } } /** * Updates a contact. Note: A contact's email address cannot be changed. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/essentialcontacts.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const essentialcontacts = google.essentialcontacts('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await essentialcontacts.organizations.contacts.patch({ * // The identifier for the contact. Format: {resource_type\}/{resource_id\}/contacts/{contact_id\} * name: 'organizations/my-organization/contacts/my-contact', * // Optional. The update mask applied to the resource. For the `FieldMask` definition, see https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask * updateMask: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "email": "my_email", * // "languageTag": "my_languageTag", * // "name": "my_name", * // "notificationCategorySubscriptions": [], * // "validateTime": "my_validateTime", * // "validationState": "my_validationState" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "email": "my_email", * // "languageTag": "my_languageTag", * // "name": "my_name", * // "notificationCategorySubscriptions": [], * // "validateTime": "my_validateTime", * // "validationState": "my_validationState" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ patch( params: Params$Resource$Organizations$Contacts$Patch, options: StreamMethodOptions ): GaxiosPromise<Readable>; patch( params?: Params$Resource$Organizations$Contacts$Patch, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudEssentialcontactsV1Contact>; patch( params: Params$Resource$Organizations$Contacts$Patch, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; patch( params: Params$Resource$Organizations$Contacts$Patch, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact>, callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> ): void; patch( params: Params$Resource$Organizations$Contacts$Patch, callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> ): void; patch( callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> ): void; patch( paramsOrCallback?: | Params$Resource$Organizations$Contacts$Patch | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudEssentialcontactsV1Contact> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Organizations$Contacts$Patch; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Organizations$Contacts$Patch; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://essentialcontacts.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'PATCH', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudEssentialcontactsV1Contact>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudEssentialcontactsV1Contact>( parameters ); } } /** * Allows a contact admin to send a test message to contact to verify that it has been configured correctly. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/essentialcontacts.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const essentialcontacts = google.essentialcontacts('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await essentialcontacts.organizations.contacts.sendTestMessage({ * // Required. The name of the resource to send the test message for. All contacts must either be set directly on this resource or inherited from another resource that is an ancestor of this one. Format: organizations/{organization_id\}, folders/{folder_id\} or projects/{project_id\} * resource: 'organizations/my-organization', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "contacts": [], * // "notificationCategory": "my_notificationCategory" * // } * }, * }); * console.log(res.data); * * // Example response * // {} * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ sendTestMessage( params: Params$Resource$Organizations$Contacts$Sendtestmessage, options: StreamMethodOptions ): GaxiosPromise<Readable>; sendTestMessage( params?: Params$Resource$Organizations$Contacts$Sendtestmessage, options?: MethodOptions ): GaxiosPromise<Schema$GoogleProtobufEmpty>; sendTestMessage( params: Params$Resource$Organizations$Contacts$Sendtestmessage, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; sendTestMessage( params: Params$Resource$Organizations$Contacts$Sendtestmessage, options: MethodOptions | BodyResponseCallback<Schema$GoogleProtobufEmpty>, callback: BodyResponseCallback<Schema$GoogleProtobufEmpty> ): void; sendTestMessage( params: Params$Resource$Organizations$Contacts$Sendtestmessage, callback: BodyResponseCallback<Schema$GoogleProtobufEmpty> ): void; sendTestMessage( callback: BodyResponseCallback<Schema$GoogleProtobufEmpty> ): void; sendTestMessage( paramsOrCallback?: | Params$Resource$Organizations$Contacts$Sendtestmessage | BodyResponseCallback<Schema$GoogleProtobufEmpty> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleProtobufEmpty> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleProtobufEmpty> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleProtobufEmpty> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Organizations$Contacts$Sendtestmessage; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Organizations$Contacts$Sendtestmessage; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://essentialcontacts.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+resource}/contacts:sendTestMessage').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['resource'], pathParams: ['resource'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleProtobufEmpty>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleProtobufEmpty>(parameters); } } } export interface Params$Resource$Organizations$Contacts$Compute extends StandardParameters { /** * The categories of notifications to compute contacts for. If ALL is included in this list, contacts subscribed to any notification category will be returned. */ notificationCategories?: string[]; /** * Optional. The maximum number of results to return from this request. Non-positive values are ignored. The presence of `next_page_token` in the response indicates that more results might be available. If not specified, the default page_size is 100. */ pageSize?: number; /** * Optional. If present, retrieves the next batch of results from the preceding call to this method. `page_token` must be the value of `next_page_token` from the previous response. The values of other method parameters should be identical to those in the previous call. */ pageToken?: string; /** * Required. The name of the resource to compute contacts for. Format: organizations/{organization_id\}, folders/{folder_id\} or projects/{project_id\} */ parent?: string; } export interface Params$Resource$Organizations$Contacts$Create extends StandardParameters { /** * Required. The resource to save this contact for. Format: organizations/{organization_id\}, folders/{folder_id\} or projects/{project_id\} */ parent?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudEssentialcontactsV1Contact; } export interface Params$Resource$Organizations$Contacts$Delete extends StandardParameters { /** * Required. The name of the contact to delete. Format: organizations/{organization_id\}/contacts/{contact_id\}, folders/{folder_id\}/contacts/{contact_id\} or projects/{project_id\}/contacts/{contact_id\} */ name?: string; } export interface Params$Resource$Organizations$Contacts$Get extends StandardParameters { /** * Required. The name of the contact to retrieve. Format: organizations/{organization_id\}/contacts/{contact_id\}, folders/{folder_id\}/contacts/{contact_id\} or projects/{project_id\}/contacts/{contact_id\} */ name?: string; } export interface Params$Resource$Organizations$Contacts$List extends StandardParameters { /** * Optional. The maximum number of results to return from this request. Non-positive values are ignored. The presence of `next_page_token` in the response indicates that more results might be available. If not specified, the default page_size is 100. */ pageSize?: number; /** * Optional. If present, retrieves the next batch of results from the preceding call to this method. `page_token` must be the value of `next_page_token` from the previous response. The values of other method parameters should be identical to those in the previous call. */ pageToken?: string; /** * Required. The parent resource name. Format: organizations/{organization_id\}, folders/{folder_id\} or projects/{project_id\} */ parent?: string; } export interface Params$Resource$Organizations$Contacts$Patch extends StandardParameters { /** * The identifier for the contact. Format: {resource_type\}/{resource_id\}/contacts/{contact_id\} */ name?: string; /** * Optional. The update mask applied to the resource. For the `FieldMask` definition, see https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask */ updateMask?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudEssentialcontactsV1Contact; } export interface Params$Resource$Organizations$Contacts$Sendtestmessage extends StandardParameters { /** * Required. The name of the resource to send the test message for. All contacts must either be set directly on this resource or inherited from another resource that is an ancestor of this one. Format: organizations/{organization_id\}, folders/{folder_id\} or projects/{project_id\} */ resource?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudEssentialcontactsV1SendTestMessageRequest; } export class Resource$Projects { context: APIRequestContext; contacts: Resource$Projects$Contacts; constructor(context: APIRequestContext) { this.context = context; this.contacts = new Resource$Projects$Contacts(this.context); } } export class Resource$Projects$Contacts { context: APIRequestContext; constructor(context: APIRequestContext) { this.context = context; } /** * Lists all contacts for the resource that are subscribed to the specified notification categories, including contacts inherited from any parent resources. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/essentialcontacts.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const essentialcontacts = google.essentialcontacts('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await essentialcontacts.projects.contacts.compute({ * // The categories of notifications to compute contacts for. If ALL is included in this list, contacts subscribed to any notification category will be returned. * notificationCategories: 'placeholder-value', * // Optional. The maximum number of results to return from this request. Non-positive values are ignored. The presence of `next_page_token` in the response indicates that more results might be available. If not specified, the default page_size is 100. * pageSize: 'placeholder-value', * // Optional. If present, retrieves the next batch of results from the preceding call to this method. `page_token` must be the value of `next_page_token` from the previous response. The values of other method parameters should be identical to those in the previous call. * pageToken: 'placeholder-value', * // Required. The name of the resource to compute contacts for. Format: organizations/{organization_id\}, folders/{folder_id\} or projects/{project_id\} * parent: 'projects/my-project', * }); * console.log(res.data); * * // Example response * // { * // "contacts": [], * // "nextPageToken": "my_nextPageToken" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ compute( params: Params$Resource$Projects$Contacts$Compute, options: StreamMethodOptions ): GaxiosPromise<Readable>; compute( params?: Params$Resource$Projects$Contacts$Compute, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse>; compute( params: Params$Resource$Projects$Contacts$Compute, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; compute( params: Params$Resource$Projects$Contacts$Compute, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse>, callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse> ): void; compute( params: Params$Resource$Projects$Contacts$Compute, callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse> ): void; compute( callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse> ): void; compute( paramsOrCallback?: | Params$Resource$Projects$Contacts$Compute | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Contacts$Compute; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Contacts$Compute; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://essentialcontacts.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+parent}/contacts:compute').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudEssentialcontactsV1ComputeContactsResponse>( parameters ); } } /** * Adds a new contact for a resource. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/essentialcontacts.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const essentialcontacts = google.essentialcontacts('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await essentialcontacts.projects.contacts.create({ * // Required. The resource to save this contact for. Format: organizations/{organization_id\}, folders/{folder_id\} or projects/{project_id\} * parent: 'projects/my-project', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "email": "my_email", * // "languageTag": "my_languageTag", * // "name": "my_name", * // "notificationCategorySubscriptions": [], * // "validateTime": "my_validateTime", * // "validationState": "my_validationState" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "email": "my_email", * // "languageTag": "my_languageTag", * // "name": "my_name", * // "notificationCategorySubscriptions": [], * // "validateTime": "my_validateTime", * // "validationState": "my_validationState" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ create( params: Params$Resource$Projects$Contacts$Create, options: StreamMethodOptions ): GaxiosPromise<Readable>; create( params?: Params$Resource$Projects$Contacts$Create, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudEssentialcontactsV1Contact>; create( params: Params$Resource$Projects$Contacts$Create, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; create( params: Params$Resource$Projects$Contacts$Create, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact>, callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> ): void; create( params: Params$Resource$Projects$Contacts$Create, callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> ): void; create( callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> ): void; create( paramsOrCallback?: | Params$Resource$Projects$Contacts$Create | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudEssentialcontactsV1Contact> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Contacts$Create; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Contacts$Create; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://essentialcontacts.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+parent}/contacts').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudEssentialcontactsV1Contact>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudEssentialcontactsV1Contact>( parameters ); } } /** * Deletes a contact. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/essentialcontacts.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const essentialcontacts = google.essentialcontacts('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await essentialcontacts.projects.contacts.delete({ * // Required. The name of the contact to delete. Format: organizations/{organization_id\}/contacts/{contact_id\}, folders/{folder_id\}/contacts/{contact_id\} or projects/{project_id\}/contacts/{contact_id\} * name: 'projects/my-project/contacts/my-contact', * }); * console.log(res.data); * * // Example response * // {} * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ delete( params: Params$Resource$Projects$Contacts$Delete, options: StreamMethodOptions ): GaxiosPromise<Readable>; delete( params?: Params$Resource$Projects$Contacts$Delete, options?: MethodOptions ): GaxiosPromise<Schema$GoogleProtobufEmpty>; delete( params: Params$Resource$Projects$Contacts$Delete, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; delete( params: Params$Resource$Projects$Contacts$Delete, options: MethodOptions | BodyResponseCallback<Schema$GoogleProtobufEmpty>, callback: BodyResponseCallback<Schema$GoogleProtobufEmpty> ): void; delete( params: Params$Resource$Projects$Contacts$Delete, callback: BodyResponseCallback<Schema$GoogleProtobufEmpty> ): void; delete(callback: BodyResponseCallback<Schema$GoogleProtobufEmpty>): void; delete( paramsOrCallback?: | Params$Resource$Projects$Contacts$Delete | BodyResponseCallback<Schema$GoogleProtobufEmpty> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleProtobufEmpty> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleProtobufEmpty> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleProtobufEmpty> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Contacts$Delete; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Contacts$Delete; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://essentialcontacts.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'DELETE', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleProtobufEmpty>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleProtobufEmpty>(parameters); } } /** * Gets a single contact. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/essentialcontacts.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const essentialcontacts = google.essentialcontacts('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await essentialcontacts.projects.contacts.get({ * // Required. The name of the contact to retrieve. Format: organizations/{organization_id\}/contacts/{contact_id\}, folders/{folder_id\}/contacts/{contact_id\} or projects/{project_id\}/contacts/{contact_id\} * name: 'projects/my-project/contacts/my-contact', * }); * console.log(res.data); * * // Example response * // { * // "email": "my_email", * // "languageTag": "my_languageTag", * // "name": "my_name", * // "notificationCategorySubscriptions": [], * // "validateTime": "my_validateTime", * // "validationState": "my_validationState" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ get( params: Params$Resource$Projects$Contacts$Get, options: StreamMethodOptions ): GaxiosPromise<Readable>; get( params?: Params$Resource$Projects$Contacts$Get, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudEssentialcontactsV1Contact>; get( params: Params$Resource$Projects$Contacts$Get, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; get( params: Params$Resource$Projects$Contacts$Get, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact>, callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> ): void; get( params: Params$Resource$Projects$Contacts$Get, callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> ): void; get( callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> ): void; get( paramsOrCallback?: | Params$Resource$Projects$Contacts$Get | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudEssentialcontactsV1Contact> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Contacts$Get; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Contacts$Get; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://essentialcontacts.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'GET', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudEssentialcontactsV1Contact>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudEssentialcontactsV1Contact>( parameters ); } } /** * Lists the contacts that have been set on a resource. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/essentialcontacts.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const essentialcontacts = google.essentialcontacts('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await essentialcontacts.projects.contacts.list({ * // Optional. The maximum number of results to return from this request. Non-positive values are ignored. The presence of `next_page_token` in the response indicates that more results might be available. If not specified, the default page_size is 100. * pageSize: 'placeholder-value', * // Optional. If present, retrieves the next batch of results from the preceding call to this method. `page_token` must be the value of `next_page_token` from the previous response. The values of other method parameters should be identical to those in the previous call. * pageToken: 'placeholder-value', * // Required. The parent resource name. Format: organizations/{organization_id\}, folders/{folder_id\} or projects/{project_id\} * parent: 'projects/my-project', * }); * console.log(res.data); * * // Example response * // { * // "contacts": [], * // "nextPageToken": "my_nextPageToken" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ list( params: Params$Resource$Projects$Contacts$List, options: StreamMethodOptions ): GaxiosPromise<Readable>; list( params?: Params$Resource$Projects$Contacts$List, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse>; list( params: Params$Resource$Projects$Contacts$List, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; list( params: Params$Resource$Projects$Contacts$List, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse>, callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse> ): void; list( params: Params$Resource$Projects$Contacts$List, callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse> ): void; list( callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse> ): void; list( paramsOrCallback?: | Params$Resource$Projects$Contacts$List | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Contacts$List; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Contacts$List; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://essentialcontacts.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+parent}/contacts').replace( /([^:]\/)\/+/g, '$1' ), method: 'GET', }, options ), params, requiredParams: ['parent'], pathParams: ['parent'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudEssentialcontactsV1ListContactsResponse>( parameters ); } } /** * Updates a contact. Note: A contact's email address cannot be changed. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/essentialcontacts.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const essentialcontacts = google.essentialcontacts('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await essentialcontacts.projects.contacts.patch({ * // The identifier for the contact. Format: {resource_type\}/{resource_id\}/contacts/{contact_id\} * name: 'projects/my-project/contacts/my-contact', * // Optional. The update mask applied to the resource. For the `FieldMask` definition, see https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask * updateMask: 'placeholder-value', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "email": "my_email", * // "languageTag": "my_languageTag", * // "name": "my_name", * // "notificationCategorySubscriptions": [], * // "validateTime": "my_validateTime", * // "validationState": "my_validationState" * // } * }, * }); * console.log(res.data); * * // Example response * // { * // "email": "my_email", * // "languageTag": "my_languageTag", * // "name": "my_name", * // "notificationCategorySubscriptions": [], * // "validateTime": "my_validateTime", * // "validationState": "my_validationState" * // } * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ patch( params: Params$Resource$Projects$Contacts$Patch, options: StreamMethodOptions ): GaxiosPromise<Readable>; patch( params?: Params$Resource$Projects$Contacts$Patch, options?: MethodOptions ): GaxiosPromise<Schema$GoogleCloudEssentialcontactsV1Contact>; patch( params: Params$Resource$Projects$Contacts$Patch, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; patch( params: Params$Resource$Projects$Contacts$Patch, options: | MethodOptions | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact>, callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> ): void; patch( params: Params$Resource$Projects$Contacts$Patch, callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> ): void; patch( callback: BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> ): void; patch( paramsOrCallback?: | Params$Resource$Projects$Contacts$Patch | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleCloudEssentialcontactsV1Contact> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleCloudEssentialcontactsV1Contact> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Contacts$Patch; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Contacts$Patch; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://essentialcontacts.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+name}').replace(/([^:]\/)\/+/g, '$1'), method: 'PATCH', }, options ), params, requiredParams: ['name'], pathParams: ['name'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleCloudEssentialcontactsV1Contact>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleCloudEssentialcontactsV1Contact>( parameters ); } } /** * Allows a contact admin to send a test message to contact to verify that it has been configured correctly. * @example * ```js * // Before running the sample: * // - Enable the API at: * // https://console.developers.google.com/apis/api/essentialcontacts.googleapis.com * // - Login into gcloud by running: * // `$ gcloud auth application-default login` * // - Install the npm module by running: * // `$ npm install googleapis` * * const {google} = require('googleapis'); * const essentialcontacts = google.essentialcontacts('v1'); * * async function main() { * const auth = new google.auth.GoogleAuth({ * // Scopes can be specified either as an array or as a single, space-delimited string. * scopes: ['https://www.googleapis.com/auth/cloud-platform'], * }); * * // Acquire an auth client, and bind it to all future calls * const authClient = await auth.getClient(); * google.options({auth: authClient}); * * // Do the magic * const res = await essentialcontacts.projects.contacts.sendTestMessage({ * // Required. The name of the resource to send the test message for. All contacts must either be set directly on this resource or inherited from another resource that is an ancestor of this one. Format: organizations/{organization_id\}, folders/{folder_id\} or projects/{project_id\} * resource: 'projects/my-project', * * // Request body metadata * requestBody: { * // request body parameters * // { * // "contacts": [], * // "notificationCategory": "my_notificationCategory" * // } * }, * }); * console.log(res.data); * * // Example response * // {} * } * * main().catch(e => { * console.error(e); * throw e; * }); * * ``` * * @param params - Parameters for request * @param options - Optionally override request options, such as `url`, `method`, and `encoding`. * @param callback - Optional callback that handles the response. * @returns A promise if used with async/await, or void if used with a callback. */ sendTestMessage( params: Params$Resource$Projects$Contacts$Sendtestmessage, options: StreamMethodOptions ): GaxiosPromise<Readable>; sendTestMessage( params?: Params$Resource$Projects$Contacts$Sendtestmessage, options?: MethodOptions ): GaxiosPromise<Schema$GoogleProtobufEmpty>; sendTestMessage( params: Params$Resource$Projects$Contacts$Sendtestmessage, options: StreamMethodOptions | BodyResponseCallback<Readable>, callback: BodyResponseCallback<Readable> ): void; sendTestMessage( params: Params$Resource$Projects$Contacts$Sendtestmessage, options: MethodOptions | BodyResponseCallback<Schema$GoogleProtobufEmpty>, callback: BodyResponseCallback<Schema$GoogleProtobufEmpty> ): void; sendTestMessage( params: Params$Resource$Projects$Contacts$Sendtestmessage, callback: BodyResponseCallback<Schema$GoogleProtobufEmpty> ): void; sendTestMessage( callback: BodyResponseCallback<Schema$GoogleProtobufEmpty> ): void; sendTestMessage( paramsOrCallback?: | Params$Resource$Projects$Contacts$Sendtestmessage | BodyResponseCallback<Schema$GoogleProtobufEmpty> | BodyResponseCallback<Readable>, optionsOrCallback?: | MethodOptions | StreamMethodOptions | BodyResponseCallback<Schema$GoogleProtobufEmpty> | BodyResponseCallback<Readable>, callback?: | BodyResponseCallback<Schema$GoogleProtobufEmpty> | BodyResponseCallback<Readable> ): | void | GaxiosPromise<Schema$GoogleProtobufEmpty> | GaxiosPromise<Readable> { let params = (paramsOrCallback || {}) as Params$Resource$Projects$Contacts$Sendtestmessage; let options = (optionsOrCallback || {}) as MethodOptions; if (typeof paramsOrCallback === 'function') { callback = paramsOrCallback; params = {} as Params$Resource$Projects$Contacts$Sendtestmessage; options = {}; } if (typeof optionsOrCallback === 'function') { callback = optionsOrCallback; options = {}; } const rootUrl = options.rootUrl || 'https://essentialcontacts.googleapis.com/'; const parameters = { options: Object.assign( { url: (rootUrl + '/v1/{+resource}/contacts:sendTestMessage').replace( /([^:]\/)\/+/g, '$1' ), method: 'POST', }, options ), params, requiredParams: ['resource'], pathParams: ['resource'], context: this.context, }; if (callback) { createAPIRequest<Schema$GoogleProtobufEmpty>( parameters, callback as BodyResponseCallback<unknown> ); } else { return createAPIRequest<Schema$GoogleProtobufEmpty>(parameters); } } } export interface Params$Resource$Projects$Contacts$Compute extends StandardParameters { /** * The categories of notifications to compute contacts for. If ALL is included in this list, contacts subscribed to any notification category will be returned. */ notificationCategories?: string[]; /** * Optional. The maximum number of results to return from this request. Non-positive values are ignored. The presence of `next_page_token` in the response indicates that more results might be available. If not specified, the default page_size is 100. */ pageSize?: number; /** * Optional. If present, retrieves the next batch of results from the preceding call to this method. `page_token` must be the value of `next_page_token` from the previous response. The values of other method parameters should be identical to those in the previous call. */ pageToken?: string; /** * Required. The name of the resource to compute contacts for. Format: organizations/{organization_id\}, folders/{folder_id\} or projects/{project_id\} */ parent?: string; } export interface Params$Resource$Projects$Contacts$Create extends StandardParameters { /** * Required. The resource to save this contact for. Format: organizations/{organization_id\}, folders/{folder_id\} or projects/{project_id\} */ parent?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudEssentialcontactsV1Contact; } export interface Params$Resource$Projects$Contacts$Delete extends StandardParameters { /** * Required. The name of the contact to delete. Format: organizations/{organization_id\}/contacts/{contact_id\}, folders/{folder_id\}/contacts/{contact_id\} or projects/{project_id\}/contacts/{contact_id\} */ name?: string; } export interface Params$Resource$Projects$Contacts$Get extends StandardParameters { /** * Required. The name of the contact to retrieve. Format: organizations/{organization_id\}/contacts/{contact_id\}, folders/{folder_id\}/contacts/{contact_id\} or projects/{project_id\}/contacts/{contact_id\} */ name?: string; } export interface Params$Resource$Projects$Contacts$List extends StandardParameters { /** * Optional. The maximum number of results to return from this request. Non-positive values are ignored. The presence of `next_page_token` in the response indicates that more results might be available. If not specified, the default page_size is 100. */ pageSize?: number; /** * Optional. If present, retrieves the next batch of results from the preceding call to this method. `page_token` must be the value of `next_page_token` from the previous response. The values of other method parameters should be identical to those in the previous call. */ pageToken?: string; /** * Required. The parent resource name. Format: organizations/{organization_id\}, folders/{folder_id\} or projects/{project_id\} */ parent?: string; } export interface Params$Resource$Projects$Contacts$Patch extends StandardParameters { /** * The identifier for the contact. Format: {resource_type\}/{resource_id\}/contacts/{contact_id\} */ name?: string; /** * Optional. The update mask applied to the resource. For the `FieldMask` definition, see https://developers.google.com/protocol-buffers/docs/reference/google.protobuf#fieldmask */ updateMask?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudEssentialcontactsV1Contact; } export interface Params$Resource$Projects$Contacts$Sendtestmessage extends StandardParameters { /** * Required. The name of the resource to send the test message for. All contacts must either be set directly on this resource or inherited from another resource that is an ancestor of this one. Format: organizations/{organization_id\}, folders/{folder_id\} or projects/{project_id\} */ resource?: string; /** * Request body metadata */ requestBody?: Schema$GoogleCloudEssentialcontactsV1SendTestMessageRequest; } }
the_stack
import * as vscode from 'vscode'; import * as path from 'path'; import * as fs from 'fs-extra'; import { YeomanUtil } from '../../util/YeomanUtil'; import { FabricEnvironmentRegistry, FabricEnvironmentRegistryEntry, EnvironmentType, OutputAdapter, FileSystemUtil, FileConfigurations, LogType, MicrofabEnvironment, ConsoleOutputAdapter, FabricNode, FabricNodeType } from 'ibm-blockchain-platform-common'; import { SettingConfigurations } from '../../configurations'; import * as loghose from 'docker-loghose'; import * as through from 'through2'; import stripAnsi = require('strip-ansi'); import { FabricRuntimeState } from '../FabricRuntimeState'; import { CommandUtil } from '../../util/CommandUtil'; import { TimerUtil } from '../../util/TimerUtil'; import { UserInputUtil } from '../../commands/UserInputUtil'; export class LocalMicroEnvironment extends MicrofabEnvironment { public ourLoghose: any; public port: number; public numberOfOrgs: number; public fabricCapabilities: string; protected busy: boolean; protected state: FabricRuntimeState; protected isRunningPromise: Promise<boolean>; protected lh: any; private dockerName: string; constructor(name: string, port: number, numberOfOrgs: number, fabricCapabilities: string) { const extDir: string = SettingConfigurations.getExtensionDir(); const resolvedExtDir: string = FileSystemUtil.getDirPath(extDir); const envPath: string = path.join(resolvedExtDir, FileConfigurations.FABRIC_ENVIRONMENTS, name); const url: string = `http://console.127-0-0-1.nip.io:${port}`; super(name, envPath, url); const dockerName: string = name.replace(/[^A-Za-z0-9]/g, ''); // Filter out invalid characters this.dockerName = dockerName; this.port = port; this.numberOfOrgs = numberOfOrgs; this.fabricCapabilities = fabricCapabilities; } public async create(): Promise<void> { // Delete any existing runtime directory, and then recreate it. await FabricEnvironmentRegistry.instance().delete(this.name, true); const settings: any = vscode.workspace.getConfiguration().get(SettingConfigurations.FABRIC_RUNTIME, vscode.ConfigurationTarget.Global); const port: any = settings[this.name]; if (port) { if (!this.port || (port !== this.port)) { // If the port has changed in the user setting, then regenerate using the new port. this.port = port; } } this.url = `console.127-0-0-1.nip.io:${this.port}`; this.setClient(this.url); if (!this.fabricCapabilities) { // If the user has migrated from a previous v2-beta, assume the channel has V2 capabilities. this.fabricCapabilities = UserInputUtil.V2_0; } const registryEntry: FabricEnvironmentRegistryEntry = new FabricEnvironmentRegistryEntry({ name: this.name, managedRuntime: true, environmentType: EnvironmentType.LOCAL_MICROFAB_ENVIRONMENT, environmentDirectory: path.join(this.path), numberOfOrgs: this.numberOfOrgs, url: this.url, fabricCapabilities: this.fabricCapabilities }); await FabricEnvironmentRegistry.instance().add(registryEntry); // Use Yeoman to generate a new network configuration. await YeomanUtil.run('fabric:network', { destination: this.path, name: this.name, dockerName: this.dockerName, numOrganizations: this.numberOfOrgs, port: this.port, fabricCapabilities: this.fabricCapabilities }); } public async start(outputAdapter?: OutputAdapter): Promise<void> { try { // check if isgenerated const created: boolean = await this.isCreated(); if (!created) { await this.create(); } this.setBusy(true); this.setState(FabricRuntimeState.STARTING); await this.startInner(outputAdapter); } finally { this.setBusy(false); const running: boolean = await this.isRunning(); if (running) { this.setState(FabricRuntimeState.STARTED); } else { this.setState(FabricRuntimeState.STOPPED); } } } public async stop(outputAdapter?: OutputAdapter): Promise<void> { try { this.setBusy(true); this.setState(FabricRuntimeState.STOPPING); await this.stopInner(outputAdapter); } finally { this.setBusy(false); const running: boolean = await this.isRunning(); if (running) { this.setState(FabricRuntimeState.STARTED); } else { this.setState(FabricRuntimeState.STOPPED); } } } public async restart(outputAdapter?: OutputAdapter): Promise<void> { try { this.setBusy(true); this.setState(FabricRuntimeState.RESTARTING); await this.stopInner(outputAdapter); await this.startInner(outputAdapter); } finally { this.setBusy(false); const running: boolean = await this.isRunning(); if (running) { this.setState(FabricRuntimeState.STARTED); } else { this.setState(FabricRuntimeState.STOPPED); } } } /** * Wait for environment to be alive and ready to interact with. * @param attempts {number} The number of attempts to check if the environment is alive * @param interval {number} The interval in seconds in which to check if the environment is alive * @returns {Promise<boolean>} */ public async waitFor(attempts: number = 10, interval: number = 2): Promise<boolean> { let isAlive: boolean = await this.isAlive(); if (!isAlive) { for (let currentAttempt: number = 1; currentAttempt <= attempts; currentAttempt++) { isAlive = await this.isAlive(); if (isAlive) { break; } else { await TimerUtil.sleep(interval * 1000); } } } return isAlive; } public getState(): FabricRuntimeState { return this.state; } public isBusy(): boolean { return this.busy; } public async isCreated(): Promise<boolean> { // We should check the start file exists, as we might get in a state where the entry is in the registry but the generated files don't exist. let entry: FabricEnvironmentRegistryEntry; try { entry = await FabricEnvironmentRegistry.instance().get(this.name); } catch (err) { // Entry doesn't exist. return false; } const startFilePath: string = path.join(entry.environmentDirectory, 'start.sh'); const startFileExists: boolean = await fs.pathExists(startFilePath); // We know the entry exists at this point, so determining whether the microfab environment is created depends on if the start file exists. return startFileExists; } public async teardown(outputAdapter?: OutputAdapter): Promise<void> { try { await this.teardownInner(outputAdapter); await this.create(); } finally { await this.setTeardownState(); } } public async delete(outputAdapter?: OutputAdapter): Promise<void> { try { await this.teardownInner(outputAdapter); } finally { await this.setTeardownState(); } } public async updateUserSettings(name: string): Promise<void> { const _settings: any = vscode.workspace.getConfiguration().get(SettingConfigurations.FABRIC_RUNTIME, vscode.ConfigurationTarget.Global); const settings: any = JSON.parse(JSON.stringify(_settings)); settings[name] = this.port; await vscode.workspace.getConfiguration().update(SettingConfigurations.FABRIC_RUNTIME, settings, vscode.ConfigurationTarget.Global); } public async killChaincode(args?: string[], outputAdapter?: OutputAdapter): Promise<void> { await this.killChaincodeInner(args, outputAdapter); } public startLogs(outputAdapter: OutputAdapter): void { const opts: any = { newline: true }; const lh: any = this.getLoghose(opts); lh.pipe(through.obj((chunk: any, _enc: any, cb: any) => { const name: string = chunk.name; const line: string = stripAnsi(chunk.line); outputAdapter.log(LogType.INFO, undefined, `${name}|${line}`); cb(); })); this.lh = lh; } public stopLogs(): void { if (this.lh) { this.lh.destroy(); } this.lh = null; } public getLoghose(opts: any): any { // This makes the startLogs testable return loghose(opts); } public setBusy(busy: boolean): void { this.busy = busy; this.emit('busy', busy); } public setState(state: FabricRuntimeState): void { this.state = state; } public async execute(script: string, args: string[] = [], outputAdapter?: OutputAdapter): Promise<void> { if (!outputAdapter) { outputAdapter = ConsoleOutputAdapter.instance(); } const env: any = Object.assign({}, process.env, { CORE_CHAINCODE_MODE: 'dev' }); if (process.platform === 'win32') { await CommandUtil.sendCommandWithOutput('cmd', ['/c', `${script}.cmd`, ...args], this.path, env, outputAdapter); } else { await CommandUtil.sendCommandWithOutput('/bin/sh', [`${script}.sh`, ...args], this.path, env, outputAdapter); } } public isRunning(args?: string[]): Promise<boolean> { if (this.isRunningPromise) { return this.isRunningPromise; } this.isRunningPromise = this.isRunningInner(args).then((result: boolean) => { this.isRunningPromise = undefined; return result; }); return this.isRunningPromise; } public async getPeerChaincodeURL(orgName?: string): Promise<string> { let nodes: FabricNode[] = await this.getNodes(); if (orgName) { nodes = nodes.filter((node: FabricNode) => { // Can either check the wallet, or check that the node.name includes the orgName. return node.wallet === orgName; }); } const peer: FabricNode = nodes.find((node: FabricNode) => node.type === FabricNodeType.PEER); if (!peer) { throw new Error('There are no Fabric peer nodes'); } return peer.chaincode_url; } protected async setTeardownState(): Promise<void> { this.setBusy(false); const running: boolean = await this.isRunning(); if (running) { this.setState(FabricRuntimeState.STARTED); } else { this.setState(FabricRuntimeState.STOPPED); } } protected async isRunningInner(args?: string[]): Promise<boolean> { const created: boolean = await this.isCreated(); if (!created) { return false; } try { await this.execute('is_running', args); return true; } catch (error) { return false; } } protected async teardownInner(outputAdapter?: OutputAdapter): Promise<void> { this.setBusy(true); this.setState(FabricRuntimeState.STOPPING); this.stopLogs(); await this.execute('teardown', [], outputAdapter); } protected async stopInner(outputAdapter?: OutputAdapter): Promise<void> { this.stopLogs(); await this.execute('stop', [], outputAdapter); } private async startInner(outputAdapter?: OutputAdapter): Promise<void> { const startArgs: string[] = []; const enableCustomImage: boolean = vscode.workspace.getConfiguration().get(SettingConfigurations.EXTENSION_ENABLE_CUSTOM_LOCAL_ENVIRONMENT_START_IMAGE); if (enableCustomImage) { const image: string = vscode.workspace.getConfiguration().get(SettingConfigurations.EXTENSION_CUSTOM_LOCAL_ENVIRONMENT_START_IMAGE_VALUE); startArgs.push(image); } await this.execute('start', startArgs, outputAdapter); } private async killChaincodeInner(args: string[], outputAdapter?: OutputAdapter): Promise<void> { await this.execute('kill_chaincode', args, outputAdapter); } }
the_stack
import sql from 'sql-template-strings' import { MatchmakingCompletion, MatchmakingType } from '../../../common/matchmaking' import { SbUserId } from '../../../common/users/user-info' import db, { DbClient } from '../db' import { Dbify } from '../db/types' export interface MatchmakingRating { userId: SbUserId matchmakingType: MatchmakingType /** The user's current MMR. */ rating: number /** * The user's current K value, used for determining the magnitude of MMR changes. In the range * [24, 40], starting out at 40 for the first 25 games. */ kFactor: number /** * The amount of uncertainty in the user's current rating, used to determine the range to search * for opponents within. In the range [80, 600], starting at 200 for a new player. */ uncertainty: number /** * How many games in a row have had unexpected outcomes (either a loss with P > 0.5, or a win * with P < 0.5). Should be a value in the range [0, 2] (values higher than that apply extra * change to the K value and reset the streak to 0). */ unexpectedStreak: number /** * The number of matchmaking games this user has played, used to determine how the K value * changes. */ numGamesPlayed: number /** * The date of the last game this user has played (or when its results were tabulated). This is * used to determine when users are inactive. */ lastPlayedDate: Date /** The number of games this user has won in this matchmaking type. */ wins: number /** The number of games this user has lost in this matchmaking type. */ losses: number } export const DEFAULT_MATCHMAKING_RATING: Readonly< Omit<MatchmakingRating, 'userId' | 'matchmakingType'> > = { rating: 1500, kFactor: 40, uncertainty: 200, unexpectedStreak: 0, numGamesPlayed: 0, lastPlayedDate: new Date(0), wins: 0, losses: 0, } type DbMatchmakingRating = Dbify<MatchmakingRating> function fromDbMatchmakingRating(result: Readonly<DbMatchmakingRating>): MatchmakingRating { return { userId: result.user_id, matchmakingType: result.matchmaking_type, rating: result.rating, kFactor: result.k_factor, uncertainty: result.uncertainty, unexpectedStreak: result.unexpected_streak, numGamesPlayed: result.num_games_played, lastPlayedDate: result.last_played_date, wins: result.wins, losses: result.losses, } } /** * Retrieves the current `MatchmakingRating` for a user, or `undefined` if the user has no MMR. This * information will be up-to-date as of currently submitted game results. */ export async function getMatchmakingRating( userId: SbUserId, matchmakingType: MatchmakingType, ): Promise<MatchmakingRating | undefined> { const { client, done } = await db() try { const result = await client.query<DbMatchmakingRating>(sql` SELECT * FROM matchmaking_ratings WHERE user_id = ${userId} AND matchmaking_type = ${matchmakingType}; `) return result.rowCount > 0 ? fromDbMatchmakingRating(result.rows[0]) : undefined } finally { done() } } /** * Creates an initial matchmaking rating entry for a player, before they've played any games in that * matchmaking type. This should only be used when we have some lock on this player for that * matchmaking type (for instance, they have been put in the game activity registry). */ export async function createInitialMatchmakingRating( userId: SbUserId, matchmakingType: MatchmakingType, mmr = DEFAULT_MATCHMAKING_RATING, ): Promise<MatchmakingRating> { const { client, done } = await db() try { const result = await client.query<DbMatchmakingRating>(sql` INSERT INTO matchmaking_ratings (user_id, matchmaking_type, rating, k_factor, uncertainty, unexpected_streak, num_games_played, last_played_date, wins, losses) VALUES (${userId}, ${matchmakingType}, ${mmr.rating}, ${mmr.kFactor}, ${mmr.uncertainty}, ${mmr.unexpectedStreak}, ${mmr.numGamesPlayed}, ${mmr.lastPlayedDate}, ${mmr.wins}, ${mmr.losses}) RETURNING * `) return fromDbMatchmakingRating(result.rows[0]) } finally { done() } } /** * Retrieves matchmaking ratings for multiple users at once, locking all of their rows from being * updated by other transactions until this one completes. */ export async function getMatchmakingRatingsWithLock( client: DbClient, userIds: SbUserId[], matchmakingType: MatchmakingType, ): Promise<MatchmakingRating[]> { const result = await client.query<DbMatchmakingRating>(sql` SELECT * FROM matchmaking_ratings WHERE user_id = ANY(${userIds}) AND matchmaking_type = ${matchmakingType} FOR UPDATE; `) return result.rows.map(r => fromDbMatchmakingRating(r)) } /** * Updates the matchmaking rating for a particular user. This should only really be used in cases * where we either have an explicit lock on the row (see `getMatchmakingRatingsWithLock`) due to the * dependencies on data in other tables and order of operations. */ export async function updateMatchmakingRating( client: DbClient, mmr: Readonly<MatchmakingRating>, ): Promise<void> { await client.query(sql` UPDATE matchmaking_ratings SET rating = ${mmr.rating}, k_factor = ${mmr.kFactor}, uncertainty = ${mmr.uncertainty}, unexpected_streak = ${mmr.unexpectedStreak}, num_games_played = ${mmr.numGamesPlayed}, last_played_date = ${mmr.lastPlayedDate}, wins = ${mmr.wins}, losses = ${mmr.losses} WHERE user_id = ${mmr.userId} AND matchmaking_type = ${mmr.matchmakingType}; `) } // TODO(tec27): Remove username from this and get user data in another query export interface GetRankingsResult { rank: number userId: SbUserId username: string rating: number wins: number losses: number lastPlayedDate: Date } type DbGetRankingsResult = Dbify<GetRankingsResult> function fromDbGetRankingsResult(r: DbGetRankingsResult) { return { // NOTE(tec27): RANK() is a bigint so this is actually a string rank: Number(r.rank), userId: r.user_id, username: r.username, rating: r.rating, wins: r.wins, losses: r.losses, lastPlayedDate: r.last_played_date, } } /** * Returns a list of players sorted by rank for a particular matchmaking type. */ export async function getRankings(matchmakingType: MatchmakingType): Promise<GetRankingsResult[]> { const { client, done } = await db() try { const result = await client.query<Dbify<GetRankingsResult>>(sql` SELECT r.rank, u.name AS username, r.user_id, r.rating, r.wins, r.losses, r.last_played_date FROM ranked_matchmaking_ratings_view r JOIN users u ON r.user_id = u.id ORDER BY r.rank; `) return result.rows.map(r => fromDbGetRankingsResult(r)) } finally { done() } } export async function getRankForUser( userId: SbUserId, matchmakingType: MatchmakingType, ): Promise<GetRankingsResult | undefined> { const { client, done } = await db() try { const result = await client.query<Dbify<GetRankingsResult>>(sql` SELECT r.rank, u.name AS username, r.user_id, r.rating, r.wins, r.losses, r.last_played_date FROM ranked_matchmaking_ratings_view r JOIN users u ON r.user_id = u.id WHERE r.user_id = ${userId}; `) return result.rows.length > 0 ? fromDbGetRankingsResult(result.rows[0]) : undefined } finally { done() } } /** * Triggers an updated to the pre-ranked view of matchmaking ratings. This should be run * periodically to make fresh data available to `getRankings` calls. */ export async function refreshRankings(matchmakingType: MatchmakingType): Promise<void> { const { client, done } = await db() try { // TODO(tec27): Store the refresh time so we can display it to clients await client.query(sql` REFRESH MATERIALIZED VIEW CONCURRENTLY ranked_matchmaking_ratings_view `) } finally { done() } } export type MatchmakingResult = 'loss' | 'win' export interface MatchmakingRatingChange { userId: SbUserId matchmakingType: MatchmakingType gameId: string /** The date when the change took place. This is used for sorting the changes. */ changeDate: Date /** Whether the game was a loss or a win. */ outcome: MatchmakingResult /** The final rating after the change took place. */ rating: number /** The change that was applied to the rating for this game. */ ratingChange: number /** The final K value after the change took place. */ kFactor: number /** The change that was applied to the K value for this game. */ kFactorChange: number /** The final uncertainty value after the change took place. */ uncertainty: number /** The change that was applied to the uncertainty value for this game. */ uncertaintyChange: number /** * The probability value (P) of this player winning the game. In the range [0, 1], with a value * of 0.5 meaning there is an equal probability of losing or winning. */ probability: number /** * How many games in a row have had unexpected outcomes (either a loss with P > 0.5, or a win * with P < 0.5). Should be a value in the range [0, 2] (values higher than that apply extra * change to the K value and reset the streak to 0). */ unexpectedStreak: number } type DbMatchmakingRatingChange = Dbify<MatchmakingRatingChange> // eslint-disable-next-line @typescript-eslint/no-unused-vars function fromDbMatchmakingRatingChange( result: Readonly<DbMatchmakingRatingChange>, ): MatchmakingRatingChange { return { userId: result.user_id, matchmakingType: result.matchmaking_type, gameId: result.game_id, changeDate: result.change_date, outcome: result.outcome, rating: result.rating, ratingChange: result.rating_change, kFactor: result.k_factor, kFactorChange: result.k_factor_change, uncertainty: result.uncertainty, uncertaintyChange: result.uncertainty_change, probability: result.probability, unexpectedStreak: result.unexpected_streak, } } export async function insertMatchmakingRatingChange( client: DbClient, mmrChange: Readonly<MatchmakingRatingChange>, ): Promise<void> { const c = mmrChange await client.query(sql` INSERT INTO matchmaking_rating_changes (user_id, matchmaking_type, game_id, change_date, outcome, rating, rating_change, k_factor, k_factor_change, uncertainty, uncertainty_change, probability, unexpected_streak) VALUES (${c.userId}, ${c.matchmakingType}, ${c.gameId}, ${c.changeDate}, ${c.outcome}, ${c.rating}, ${c.ratingChange}, ${c.kFactor}, ${c.kFactorChange}, ${c.uncertainty}, ${c.uncertaintyChange}, ${c.probability}, ${c.unexpectedStreak}); `) } type DbMatchmakingCompletion = Dbify<MatchmakingCompletion> function fromDbMatchmakingCompletion( result: Readonly<DbMatchmakingCompletion>, ): MatchmakingCompletion { return { id: result.id, userId: result.user_id, matchmakingType: result.matchmaking_type, completionType: result.completion_type, searchTimeMillis: result.search_time_millis, completionTime: result.completion_time, } } export async function insertMatchmakingCompletion( completion: Omit<MatchmakingCompletion, 'id'>, ): Promise<MatchmakingCompletion> { const { userId, matchmakingType, completionType, searchTimeMillis, completionTime } = completion const { client, done } = await db() try { const result = await client.query<DbMatchmakingCompletion>(sql` INSERT INTO matchmaking_completions (user_id, matchmaking_type, completion_type, search_time_millis, completion_time) VALUES (${userId}, ${matchmakingType}, ${completionType}, ${searchTimeMillis}, ${completionTime}) RETURNING * `) return fromDbMatchmakingCompletion(result.rows[0]) } finally { done() } }
the_stack
import { enginesVersion } from '@prisma/engines' import { getSchemaPathAndPrint } from '@prisma/migrate' import type { Command, Generator } from '@prisma/sdk' import { arg, format, getCommandWithExecutor, getGenerators, getGeneratorSuccessMessage, HelpError, highlightTS, isError, link, loadEnvFile, logger, missingGeneratorMessage, parseEnvValue, } from '@prisma/sdk' import chalk from 'chalk' import fs from 'fs' import logUpdate from 'log-update' import path from 'path' import resolvePkg from 'resolve-pkg' import { breakingChangesMessage } from './utils/breakingChanges' import { simpleDebounce } from './utils/simpleDebounce' const pkg = eval(`require('../package.json')`) /** * $ prisma generate */ export class Generate implements Command { public static new(): Generate { return new Generate() } private static help = format(` Generate artifacts (e.g. Prisma Client) ${chalk.bold('Usage')} ${chalk.dim('$')} prisma generate [options] ${chalk.bold('Options')} -h, --help Display this help message --schema Custom path to your Prisma schema --watch Watch the Prisma schema and rerun after a change ${chalk.bold('Examples')} With an existing Prisma schema ${chalk.dim('$')} prisma generate Or specify a schema ${chalk.dim('$')} prisma generate --schema=./schema.prisma Watch Prisma schema file and rerun after each change ${chalk.dim('$')} prisma generate --watch `) private logText = '' private hasGeneratorErrored = false private runGenerate = simpleDebounce(async ({ generators }: { generators: Generator[] }) => { const message: string[] = [] for (const generator of generators) { const before = Date.now() try { await generator.generate() const after = Date.now() message.push(getGeneratorSuccessMessage(generator, after - before) + '\n') generator.stop() } catch (err) { this.hasGeneratorErrored = true generator.stop() // This is an error received when the the client < 2.20 and the cli >= 2.20, This was caused by a breaking change in the generators if (err.message.includes('outputDir.endsWith is not a function')) { message.push( `This combination of Prisma CLI (>= 2.20) and Prisma Client (< 2.20) is not supported. Please update \`@prisma/client\` to ${pkg.version} \n\n`, ) } else { message.push(`${err.message}\n\n`) } } } this.logText += message.join('\n') }) public async parse(argv: string[]): Promise<string | Error> { const args = arg(argv, { '--help': Boolean, '-h': '--help', '--watch': Boolean, '--schema': String, // Only used for checkpoint information '--postinstall': String, '--telemetry-information': String, }) const isPostinstall = process.env.PRISMA_GENERATE_IN_POSTINSTALL let cwd = process.cwd() if (isPostinstall && isPostinstall !== 'true') { cwd = isPostinstall } if (isError(args)) { return this.help(args.message) } if (args['--help']) { return this.help() } const watchMode = args['--watch'] || false loadEnvFile(args['--schema'], true) const schemaPath = await getSchemaPathAndPrint(args['--schema'], cwd) if (!schemaPath) return '' // TODO Extract logic from here let hasJsClient let generators: Generator[] | undefined let clientGeneratorVersion: string | null = null try { generators = await getGenerators({ schemaPath, printDownloadProgress: !watchMode, version: enginesVersion, cliVersion: pkg.version, }) if (!generators || generators.length === 0) { this.logText += `${missingGeneratorMessage}\n` } else { // Only used for CLI output, ie Go client doesn't want JS example output const jsClient = generators.find( (g) => g.options && parseEnvValue(g.options.generator.provider) === 'prisma-client-js', ) clientGeneratorVersion = jsClient?.manifest?.version ?? null hasJsClient = Boolean(jsClient) try { await this.runGenerate({ generators }) } catch (errRunGenerate) { this.logText += `${errRunGenerate.message}\n\n` } } } catch (errGetGenerators) { if (isPostinstall) { console.error(`${chalk.blueBright( 'info', )} The postinstall script automatically ran \`prisma generate\`, which failed. The postinstall script still succeeds but won't generate the Prisma Client. Please run \`${getCommandWithExecutor('prisma generate')}\` to see the errors.`) return '' } if (watchMode) { this.logText += `${errGetGenerators.message}\n\n` } else { throw errGetGenerators } } let printBreakingChangesMessage = false if (hasJsClient) { try { const clientVersionBeforeGenerate = getCurrentClientVersion() if (clientVersionBeforeGenerate && typeof clientVersionBeforeGenerate === 'string') { const [major, minor] = clientVersionBeforeGenerate.split('.') if (parseInt(major) == 2 && parseInt(minor) < 12) { printBreakingChangesMessage = true } } } catch (e) { // } } if (isPostinstall && printBreakingChangesMessage && logger.should.warn) { // skipping generate return `There have been breaking changes in Prisma Client since you updated last time. Please run \`prisma generate\` manually.` } const watchingText = `\n${chalk.green('Watching...')} ${chalk.dim(schemaPath)}\n` if (!watchMode) { const prismaClientJSGenerator = generators?.find( (g) => g.options?.generator.provider && parseEnvValue(g.options?.generator.provider) === 'prisma-client-js', ) let hint = '' if (prismaClientJSGenerator) { const importPath = prismaClientJSGenerator.options?.generator?.isCustomOutput ? prefixRelativePathIfNecessary( path.relative(process.cwd(), parseEnvValue(prismaClientJSGenerator.options.generator.output!)), ) : '@prisma/client' const breakingChangesStr = printBreakingChangesMessage ? ` ${breakingChangesMessage}` : '' const versionsOutOfSync = clientGeneratorVersion && pkg.version !== clientGeneratorVersion const versionsWarning = versionsOutOfSync && logger.should.warn ? `\n\n${chalk.yellow.bold('warn')} Versions of ${chalk.bold(`prisma@${pkg.version}`)} and ${chalk.bold( `@prisma/client@${clientGeneratorVersion}`, )} don't match. This might lead to unexpected behavior. Please make sure they have the same version.` : '' hint = `You can now start using Prisma Client in your code. Reference: ${link('https://pris.ly/d/client')} ${chalk.dim('```')} ${highlightTS(`\ import { PrismaClient } from '${importPath}' const prisma = new PrismaClient()`)} ${chalk.dim('```')}${breakingChangesStr}${versionsWarning}` } const message = '\n' + this.logText + (hasJsClient && !this.hasGeneratorErrored ? hint : '') if (this.hasGeneratorErrored) { if (isPostinstall) { logger.info(`The postinstall script automatically ran \`prisma generate\`, which failed. The postinstall script still succeeds but won't generate the Prisma Client. Please run \`${getCommandWithExecutor('prisma generate')}\` to see the errors.`) return '' } throw new Error(message) } else { return message } } else { logUpdate(watchingText + '\n' + this.logText) fs.watch(schemaPath, async (eventType) => { if (eventType === 'change') { let generatorsWatch: Generator[] | undefined try { generatorsWatch = await getGenerators({ schemaPath, printDownloadProgress: !watchMode, version: enginesVersion, cliVersion: pkg.version, }) if (!generatorsWatch || generatorsWatch.length === 0) { this.logText += `${missingGeneratorMessage}\n` } else { logUpdate(`\n${chalk.green('Building...')}\n\n${this.logText}`) try { await this.runGenerate({ generators: generatorsWatch, }) logUpdate(watchingText + '\n' + this.logText) } catch (errRunGenerate) { this.logText += `${errRunGenerate.message}\n\n` logUpdate(watchingText + '\n' + this.logText) } } // logUpdate(watchingText + '\n' + this.logText) } catch (errGetGenerators) { this.logText += `${errGetGenerators.message}\n\n` logUpdate(watchingText + '\n' + this.logText) } } }) await new Promise((_) => null) // eslint-disable-line @typescript-eslint/no-unused-vars } return '' } // help message public help(error?: string): string | HelpError { if (error) { return new HelpError(`\n${chalk.bold.red(`!`)} ${error}\n${Generate.help}`) } return Generate.help } } function prefixRelativePathIfNecessary(relativePath: string): string { if (relativePath.startsWith('..')) { return relativePath } return `./${relativePath}` } function getCurrentClientVersion(): string | null { try { let pkgPath = resolvePkg('.prisma/client', { cwd: process.cwd() }) if (!pkgPath) { const potentialPkgPath = path.join(process.cwd(), 'node_modules/.prisma/client') if (fs.existsSync(potentialPkgPath)) { pkgPath = potentialPkgPath } } if (pkgPath) { const indexPath = path.join(pkgPath, 'index.js') if (fs.existsSync(indexPath)) { const program = require(indexPath) return program?.prismaVersion?.client ?? program?.Prisma?.prismaVersion?.client } } } catch (e) { // return null } return null }
the_stack
import { Overlay, Placement, TriggerBoundyAdjustMode, overlayConstraints } from '../../../../../components/core/JsInterop/modules/components/overlay'; import { infoHelper } from '../../../../../components/core/JsInterop/modules/dom/infoHelper'; import * as domInit from '../../domInit' import { resizeObserver } from '../../../../../components/core/JsInterop/ObservableApi/resizeObserver' import { mutationObserver } from '../../../../../components/core/JsInterop/ObservableApi/mutationObserver' //test imports const itParam = require('mocha-param').itParam; import { expect } from 'chai'; import * as sinon from 'sinon'; import * as rewire from 'rewire' import { domInfo } from '../../../../../components/core/JsInterop/modules/dom/types'; import exp = require('constants'); import { domInfoHelper, domTypes } from '../../../../../components/core/JsInterop/modules/dom/exports'; const domInfoDefaults: domInfo = { offsetTop: 0, offsetLeft: 0, offsetWidth: 0, offsetHeight: 0, scrollHeight: 0, scrollWidth: 0, scrollLeft: 0, scrollTop: 0, clientTop: 0, clientLeft: 0, clientHeight: 0, clientWidth: 0, selectionStart: 0, absoluteTop: 0, absoluteLeft: 0 } type cooridnates = { top: number, bottom: number, left: number, right: number } describe ('Overlay maps test', () => { const rewModule = rewire('../../../../../components/core/JsInterop/modules/components/overlay'); const rewClass = rewModule.__get__('Overlay'); it ('appliedStylePositionMap correct', function () { var placement = Placement.Bottom; var actual = rewClass.appliedStylePositionMap.get(placement); expect(actual.horizontal).to.equal("left"); expect(actual.vertical).to.equal("top"); }); it ('reverseVerticalPlacementMap correct (position ignored)', function () { var placement = Placement.Bottom; var actual = rewClass.reverseVerticalPlacementMap.get(placement)("top"); expect(actual).to.equal(Placement.Top); }); it ('reverseVerticalPlacementMap correct (position evaluated)', function () { var placement = Placement.Left; var actual = rewClass.reverseVerticalPlacementMap.get(placement)("top"); expect(actual).to.equal(Placement.LeftBottom); }); it ('reverseHorizontalPlacementMap correct (position ignored)', function () { var placement = Placement.LeftTop; var actual = rewClass.reverseHorizontalPlacementMap.get(placement)("top"); expect(actual).to.equal(Placement.RightTop); }); it ('reverseHorizontalPlacementMap correct (position evaluated)', function () { var placement = Placement.Bottom; var actual = rewClass.reverseHorizontalPlacementMap.get(placement)("right"); expect(actual).to.equal(Placement.BottomLeft); }); }); type positionCalculationTheory = { coversPlacementScenarios: string, placement: Placement, trigger: { startingPosition?: number, height?: number, width?: number, domInfoResult: domInfo }, overlay: { height?: number, width?: number }, position: "top" | "bottom" | "left" | "right", container: domInfo, overlayConstraints: overlayConstraints, expected: { position1: number, position2: number } }; const overlayConstraintsDefaults: overlayConstraints = { arrowPointAtCenter: false, verticalOffset: 4, horizontalOffset: 4 }; const theoryVerticalCalculationData: Array<positionCalculationTheory> = [ { coversPlacementScenarios: "LeftTop & RightTop", placement: Placement.LeftTop, position: "top", trigger: { startingPosition: 22, height: 19, domInfoResult: { ...domInfoDefaults, absoluteTop: 22, clientHeight: 0, offsetHeight: 19 } }, overlayConstraints: overlayConstraintsDefaults, container: domInfoDefaults, overlay: { height: 100 }, expected: { position1: 22, position2: -122 } }, { coversPlacementScenarios: "All Bottom", placement: Placement.Bottom, position: "top", trigger: { startingPosition: 22, height: 19, domInfoResult: { ...domInfoDefaults, absoluteTop: 22, clientHeight: 0, offsetHeight: 19 } }, overlayConstraints: overlayConstraintsDefaults, container: domInfoDefaults, overlay: { height: 100 }, expected: { position1: 45, position2: -145 } }, { coversPlacementScenarios: "Left & Right", placement: Placement.Left, position: "top", trigger: { startingPosition: 22, height: 19, domInfoResult: { ...domInfoDefaults, absoluteTop: 22, clientHeight: 0, offsetHeight: 19 } }, overlayConstraints: overlayConstraintsDefaults, container: domInfoDefaults, overlay: { height: 100 }, expected: { position1: -18.5, position2: -81.5 } }, { coversPlacementScenarios: "All Top", placement: Placement.Top, position: "bottom", trigger: { startingPosition: -41, height: 19, domInfoResult: { ...domInfoDefaults, absoluteTop: 22, clientHeight: 0, offsetHeight: 19 } }, overlayConstraints: overlayConstraintsDefaults, container: domInfoDefaults, overlay: { height: 100 }, expected: { position1: -82, position2: -18 } }, { coversPlacementScenarios: "LeftBottom & RightBottom", placement: Placement.LeftBottom, position: "bottom", trigger: { startingPosition: -41, height: 19, domInfoResult: { ...domInfoDefaults, absoluteTop: 22, clientHeight: 0, offsetHeight: 19 } }, overlayConstraints: overlayConstraintsDefaults, container: domInfoDefaults, overlay: { height: 100 }, expected: { position1: -59, position2: -41 } } ]; const theoryHorizontalCalculationData: Array<positionCalculationTheory> = [ { coversPlacementScenarios: "TopLeft & BottomLeft", placement: Placement.TopLeft, position: "left", trigger: { startingPosition: 790, width: 157, domInfoResult: { ...domInfoDefaults, absoluteLeft: 790, clientWidth: 0, offsetWidth: 157 } }, overlayConstraints: overlayConstraintsDefaults, container: domInfoDefaults, overlay: { width: 100 }, expected: { position1: 790, position2: -890 } }, { coversPlacementScenarios: "All Right", placement: Placement.Right, position: "left", trigger: { startingPosition: 790, width: 157, domInfoResult: { ...domInfoDefaults, absoluteLeft: 790, clientWidth: 0, offsetWidth: 157 } }, overlayConstraints: overlayConstraintsDefaults, container: domInfoDefaults, overlay: { width: 100 }, expected: { position1: 951, position2: -1051 } }, { coversPlacementScenarios: "TopCenter & Top & BottomCenter & Bottom", placement: Placement.TopCenter, position: "left", trigger: { startingPosition: 790, width: 157, domInfoResult: { ...domInfoDefaults, absoluteLeft: 790, clientWidth: 0, offsetWidth: 157 } }, overlayConstraints: overlayConstraintsDefaults, container: domInfoDefaults, overlay: { width: 100 }, expected: { position1: 818.5, position2: -918.5 } }, { coversPlacementScenarios: "TopRight & BottomRight", placement: Placement.TopRight, position: "right", trigger: { startingPosition: -947, width: 157, domInfoResult: { ...domInfoDefaults, absoluteLeft: 790, clientWidth: 0, offsetWidth: 157 } }, overlayConstraints: overlayConstraintsDefaults, container: domInfoDefaults, overlay: { width: 100 }, expected: { position1: 847, position2: -947 } }, { coversPlacementScenarios: "Left & LeftTop & LeftBottom ", placement: Placement.Left, position: "right", trigger: { startingPosition: -947, width: 157, domInfoResult: { ...domInfoDefaults, absoluteLeft: 790, clientWidth: 0, offsetWidth: 157 } }, overlayConstraints: overlayConstraintsDefaults, container: domInfoDefaults, overlay: { width: 100 }, expected: { position1: 686, position2: -786 } } ]; describe ('Overlay calculation functions', () => { const rewModule = rewire('../../../../../components/core/JsInterop/modules/components/overlay'); const rewClass = rewModule.__get__('Overlay'); itParam("setVerticalCalculation for position: '${value.position}', placement: ${value.coversPlacementScenarios}", theoryVerticalCalculationData, (testData: positionCalculationTheory) => { var fn = rewClass.setVerticalCalculation(testData.placement, testData.position); const actual = fn(testData.trigger.startingPosition, testData.trigger.height, testData.container, testData.trigger.domInfoResult, testData.overlay.height, testData.overlayConstraints); expect(actual.top).to.equal(testData.expected.position1); expect(actual.bottom).to.equal(testData.expected.position2); }); itParam("setHorizontalCalculation for position: '${value.position}', placement: ${value.coversPlacementScenarios}", theoryHorizontalCalculationData, (testData: positionCalculationTheory) => { var fn = rewClass.setHorizontalCalculation(testData.placement, testData.position); const actual = fn(testData.trigger.startingPosition, testData.trigger.width, testData.container, testData.trigger.domInfoResult, testData.overlay.width, testData.overlayConstraints); expect(actual.left).to.equal(testData.expected.position1); expect(actual.right).to.equal(testData.expected.position2); }); }); type positionTheory = { theoryName: string, trigger: { triggerBoundyAdjustMode: TriggerBoundyAdjustMode }, overlay: { placement: Placement }, window: { innerHeight: number, innerWidth: number, pageXOffset: number, pageYOffset: number}, documentElement: { clientHeight: number, clientWidth: number }, getInfo: { [elementId: string]: { absoluteTop?: number, absoluteLeft?: number, clientLeft?: number, clientTop?: number clientHeight?: number, clientWidth?: number, offsetHeight?: number, offsetWidth?: number, scrollLeft?: number, scrollTop?: number, scrollHeight?: number, scrollWidth?: number}}, containerParentElement?: { clientHeight?: number, clientWidth?: number, scrollLeft?: number, scrollTop?: number, zIndex?: number }, expected: cooridnates expectedCorrected: cooridnates & { placement?: Placement } }; const theoryPositionData: Array<positionTheory> = [ { theoryName: "scenario 1", trigger: { triggerBoundyAdjustMode: TriggerBoundyAdjustMode.InView }, overlay: { placement: Placement.BottomLeft }, window: { innerWidth: 1920, innerHeight: 955, pageXOffset: 0, pageYOffset: 0}, documentElement: { clientHeight: 955, clientWidth: 1920 }, getInfo: { "body": { absoluteTop: 0, absoluteLeft: 0, clientLeft: 0, clientTop: 0, scrollLeft: 0, scrollTop: 0, scrollHeight: 955, scrollWidth: 1920}, "trigger": { absoluteTop: 834, absoluteLeft: 33, clientHeight: 0, clientWidth: 0, offsetHeight: 19, offsetWidth: 157}, "overlay": { clientHeight: 808, clientWidth: 372 }, }, expected: { top: 857, bottom: -710, left: 33, right: 1515 }, expectedCorrected: { top: null, bottom: 125, left: 33, right: null, placement: Placement.TopLeft } }, { theoryName: "scenario 2", trigger: { triggerBoundyAdjustMode: TriggerBoundyAdjustMode.InView }, overlay: { placement: Placement.BottomLeft }, window: { innerWidth: 1920, innerHeight: 955, pageXOffset: 0, pageYOffset: 0}, documentElement: { clientHeight: 955, clientWidth: 1920 }, getInfo: { "body": { absoluteTop: 0, absoluteLeft: 0, clientLeft: 0, clientTop: 0, scrollLeft: 0, scrollTop: 0, scrollHeight: 955, scrollWidth: 1920}, "trigger": { absoluteTop: 42, absoluteLeft: 1738, clientHeight: 0, clientWidth: 0, offsetHeight: 19, offsetWidth: 157}, "overlay": { clientHeight: 808, clientWidth: 372 }, }, expected: { top: 65, bottom: 82, left: 1738, right: -190 }, expectedCorrected: { top: 65, bottom: null, left: null, right: 25, placement: Placement.BottomRight } }, { theoryName: "scenario 3", trigger: { triggerBoundyAdjustMode: TriggerBoundyAdjustMode.InView }, overlay: { placement: Placement.BottomLeft }, window: { innerWidth: 1920, innerHeight: 955, pageXOffset: 0, pageYOffset: 0}, documentElement: { clientHeight: 955, clientWidth: 1920 }, getInfo: { "body": { absoluteTop: 0, absoluteLeft: 0, clientLeft: 0, clientTop: 0, scrollLeft: 0, scrollTop: 0, scrollHeight: 955, scrollWidth: 1920}, "trigger": { absoluteTop: 438, absoluteLeft: 1738, clientHeight: 0, clientWidth: 0, offsetHeight: 19, offsetWidth: 157}, "overlay": { clientHeight: 808, clientWidth: 372 }, }, expected: { top: 461, bottom: -314, left: 1738, right: -190 }, expectedCorrected: { top: 461, bottom: null, left: null, right: 25, placement: Placement.BottomRight } }, { theoryName: "scenario 4", trigger: { triggerBoundyAdjustMode: TriggerBoundyAdjustMode.InView }, overlay: { placement: Placement.BottomLeft }, window: { innerWidth: 1920, innerHeight: 955, pageXOffset: 1920, pageYOffset: 955}, documentElement: { clientHeight: 0, clientWidth: 0 }, getInfo: { "body": { absoluteTop: 0, absoluteLeft: 0, clientLeft: 0, clientTop: 0, scrollLeft: 0, scrollTop: 0, scrollHeight: 2883, scrollWidth: 5816}, "trigger": { absoluteTop: 1386, absoluteLeft: 2785, clientHeight: 0, clientWidth: 0, offsetHeight: 22, offsetWidth: 74}, "overlay": { clientHeight: 744, clientWidth: 372 }, }, expected: { top: 1412, bottom: 727, left: 2785, right: 2659 }, expectedCorrected: { top: 1412, bottom: null, left: 2785, right: null, placement: Placement.BottomLeft } }, { theoryName: "scenario 5", trigger: { triggerBoundyAdjustMode: TriggerBoundyAdjustMode.InView }, overlay: { placement: Placement.BottomLeft }, window: { innerWidth: 1920, innerHeight: 955, pageXOffset: 64, pageYOffset: 41}, documentElement: { clientHeight: 938, clientWidth: 1903 }, getInfo: { "body": { absoluteTop: 0, absoluteLeft: 0, clientLeft: 0, clientTop: 0, clientHeight: 2865, clientWidth: 5760, offsetHeight: 2865, offsetWidth: 5760, scrollLeft: 0, scrollTop: 0, scrollHeight: 2883, scrollWidth: 5816}, "trigger": { absoluteTop: 966, absoluteLeft: 1940, clientHeight: 0, clientWidth: 0, offsetHeight: 22, offsetWidth: 74}, "overlay": { clientHeight: 744, clientWidth: 372 }, }, expected: { top: 992, bottom: 1147, left: 1940, right: 3504 }, expectedCorrected: { top: null, bottom: -24, left: null, right: -111, placement: Placement.TopRight } }, { theoryName: "scenario 6", trigger: { triggerBoundyAdjustMode: TriggerBoundyAdjustMode.InView }, overlay: { placement: Placement.Left }, window: { innerWidth: 1920, innerHeight: 955, pageXOffset: 0, pageYOffset: 0}, documentElement: { clientHeight: 955, clientWidth: 1920 }, getInfo: { "body": { absoluteTop: 0, absoluteLeft: 0, clientLeft: 0, clientTop: 0, clientHeight: 955, clientWidth: 1920, offsetHeight: 955, offsetWidth: 1920, scrollLeft: 0, scrollTop: 0, scrollHeight: 955, scrollWidth: 1920}, "trigger": { absoluteTop: 810, absoluteLeft: 885, clientHeight: 0, clientWidth: 0, offsetHeight: 22, offsetWidth: 74}, "overlay": { clientHeight: 744, clientWidth: 372 }, }, expected: { top: 449, bottom: -238, left: 509, right: 1039 }, expectedCorrected: { top: null, bottom: 123, left: null, right: 1039, placement: Placement.LeftBottom } }, { theoryName: "scenario 7 tooltip left", trigger: { triggerBoundyAdjustMode: TriggerBoundyAdjustMode.InView }, overlay: { placement: Placement.Left }, window: { innerWidth: 1920, innerHeight: 955, pageXOffset: 0, pageYOffset: 0}, documentElement: { clientHeight: 955, clientWidth: 1920 }, getInfo: { "body": { absoluteTop: 0, absoluteLeft: 0, clientLeft: 0, clientTop: 0, clientHeight: 955, clientWidth: 1920, offsetHeight: 955, offsetWidth: 1920, scrollLeft: 0, scrollTop: 0, scrollHeight: 955, scrollWidth: 1920}, "trigger": { absoluteTop: 138, absoluteLeft: 282, clientHeight: 32, clientWidth: 55, offsetHeight: 32, offsetWidth: 55}, "overlay": { clientHeight: 34, clientWidth: 97 }, }, expected: { top: 137, bottom: 784, left: 181, right: 1642 }, expectedCorrected: { top: 137, bottom: null, left: null, right: 1642, placement: Placement.Left } }, { theoryName: "scenario 8 dropDown button BottomRight", trigger: { triggerBoundyAdjustMode: TriggerBoundyAdjustMode.InView }, overlay: { placement: Placement.BottomRight }, window: { innerWidth: 1903, innerHeight: 955, pageXOffset: 0, pageYOffset: 0}, documentElement: { clientHeight: 955, clientWidth: 1903 }, getInfo: { "body": { absoluteTop: 0, absoluteLeft: 0, clientLeft: 0, clientTop: 0, clientHeight: 955, clientWidth: 1903, offsetHeight: 955, offsetWidth: 1903, scrollLeft: 0, scrollTop: 0, scrollHeight: 5559, scrollWidth: 1903}, "trigger": { absoluteTop: 705, absoluteLeft: 1318, clientHeight: 30, clientWidth: 108, offsetHeight: 32, offsetWidth: 110}, "overlay": { clientHeight: 104, clientWidth: 118 }, }, expected: { top: 741, bottom: 4714, left: 1310, right: 475 }, expectedCorrected: { top: 741, bottom: null, left: null, right: 475, placement: Placement.BottomRight } }, { theoryName: "scenario 9 container topRight", trigger: { triggerBoundyAdjustMode: TriggerBoundyAdjustMode.InView }, overlay: { placement: Placement.TopRight }, window: { innerWidth: 1920, innerHeight: 955, pageXOffset: 0, pageYOffset: 1836}, documentElement: { clientHeight: 955, clientWidth: 1903 }, getInfo: { "container": { absoluteTop: 2018, absoluteLeft: 416, clientLeft: 0, clientTop: 0, clientHeight: 1000, clientWidth: 581, offsetHeight: 1000, offsetWidth: 581, scrollLeft: 0, scrollTop: 0, scrollHeight: 1000, scrollWidth: 581}, "trigger": { absoluteTop: 2150, absoluteLeft: 696, clientHeight: 30, clientWidth: 84, offsetHeight: 32, offsetWidth: 86}, "overlay": { clientHeight: 104, clientWidth: 118 }, }, containerParentElement: { clientWidth: 581, clientHeight: 183, scrollLeft: 0, scrollTop: 114 }, expected: { top: 24, bottom: 872, left: 248, right: 215 }, expectedCorrected: { top: 168, bottom: null, left: null, right: 215, placement: Placement.BottomRight } }, { theoryName: "popup in container (based on autocomplete)", trigger: { triggerBoundyAdjustMode: TriggerBoundyAdjustMode.InView }, overlay: { placement: Placement.BottomLeft }, window: { innerWidth: 1920, innerHeight: 955, pageXOffset: 0, pageYOffset: 1137.5999755859375}, documentElement: { clientHeight: 955, clientWidth: 1903 }, getInfo: { "container": { absoluteTop: 1701, absoluteLeft: 416, clientLeft: 0, clientTop: 0, clientHeight: 1000, clientWidth: 581, offsetHeight: 1000, offsetWidth: 581, scrollLeft: 0, scrollTop: 0, scrollHeight: 1000, scrollWidth: 581}, "trigger": { absoluteTop: 1801, absoluteLeft: 516, clientHeight: 30, clientWidth: 379, offsetHeight: 32, offsetWidth: 381}, "overlay": { clientHeight: 200, clientWidth: 379 }, }, containerParentElement: { clientWidth: 581, clientHeight: 183, scrollLeft: 0, scrollTop: 0 }, expected: { top: 136, bottom: 664, left: 100, right: 102 }, expectedCorrected: { top: null, bottom: 904, left: 100, right: null, placement: Placement.TopLeft } }, { theoryName: "scenario 11 trigger not in viewport (tooltip)", trigger: { triggerBoundyAdjustMode: TriggerBoundyAdjustMode.InView }, overlay: { placement: Placement.Top }, window: { innerWidth: 1920, innerHeight: 955, pageXOffset: 0, pageYOffset: 0}, documentElement: { clientHeight: 955, clientWidth: 1903 }, getInfo: { "body": { absoluteTop: 0, absoluteLeft: 0, clientLeft: 0, clientTop: 0, scrollLeft: 0, scrollTop: 0, scrollHeight: 3983, scrollWidth: 1903}, "trigger": { absoluteTop: 1588, absoluteLeft: 559, clientHeight: 10, clientWidth: 10, offsetHeight: 14, offsetWidth: 14}, "overlay": { clientHeight: 42, clientWidth: 32 }, }, expected: { top: 1542, bottom: 2399, left: 550, right: 1321 }, expectedCorrected: { top: null, bottom: -629, left: 550, right: null, placement: Placement.Top } }, { theoryName: "trigger scrolled parttially out of screen", trigger: { triggerBoundyAdjustMode: TriggerBoundyAdjustMode.InView }, overlay: { placement: Placement.BottomLeft }, window: { innerWidth: 1920, innerHeight: 955, pageXOffset: 0, pageYOffset: 934}, documentElement: { clientHeight: 955, clientWidth: 1903 }, getInfo: { "body": { absoluteTop: 0, absoluteLeft: 0, clientLeft: 0, clientTop: 0, scrollLeft: 0, scrollTop: 0, scrollHeight: 9505, scrollWidth: 1903}, "trigger": { absoluteTop: 869, absoluteLeft: 406, clientHeight: 30, clientWidth: 136, offsetHeight: 32, offsetWidth: 138}, "overlay": { clientHeight: 309, clientWidth: 280 }, }, expected: { top: 905, bottom: 8291, left: 406, right: 1217 }, expectedCorrected: { top: 905, bottom: null, left: 406, right: null, placement: Placement.BottomLeft } } ]; type scrollTheory = positionTheory & { scrollSteps: Array<{x?: number, y?: number, expectedAfterScroll: cooridnates & { placement?: Placement } }>, } const theoryScrollData: Array<scrollTheory> = [ { theoryName: "trigger scrolled parttially out of screen", trigger: { triggerBoundyAdjustMode: TriggerBoundyAdjustMode.InView }, overlay: { placement: Placement.BottomLeft }, window: { innerWidth: 1920, innerHeight: 955, pageXOffset: 0, pageYOffset: 0}, documentElement: { clientHeight: 955, clientWidth: 1903 }, getInfo: { "body": { absoluteTop: 0, absoluteLeft: 0, clientLeft: 0, clientTop: 0, scrollLeft: 0, scrollTop: 0, scrollHeight: 9505, scrollWidth: 1903}, "trigger": { absoluteTop: 439, absoluteLeft: 406, clientHeight: 30, clientWidth: 136, offsetHeight: 32, offsetWidth: 138}, "overlay": { clientHeight: 309, clientWidth: 280 }, }, expected: { top: 475, bottom: 8721, left: 406, right: 1217 }, expectedCorrected: { top: 475, bottom: null, left: 406, right: null, placement: Placement.BottomLeft }, scrollSteps: [ { y: 476, expectedAfterScroll: { top: 475, bottom: null, left: 406, right: null, placement: Placement.BottomLeft } }, { y: 477, expectedAfterScroll: { top: 475, bottom: null, left: 406, right: null, placement: Placement.BottomLeft } }, { y:0, expectedAfterScroll: { top: 475, bottom: null, left: 406, right: null, placement: Placement.BottomLeft } } ] } ] const theoryModalPositionData: Array<positionTheory> = [ { theoryName: "scenario 1 container is modal", trigger: { triggerBoundyAdjustMode: TriggerBoundyAdjustMode.InView }, overlay: { placement: Placement.BottomLeft }, window: { innerWidth: 1920, innerHeight: 955, pageXOffset: 0, pageYOffset: 2346}, documentElement: { clientHeight: 955, clientWidth: 1920 }, getInfo: { "container": { absoluteTop: 2346, absoluteLeft: 0, clientLeft: 0, clientTop: 0, clientHeight: 955, clientWidth: 1920, offsetHeight: 955, offsetWidth: 1920, scrollLeft: 0, scrollTop: 0, scrollHeight: 955, scrollWidth: 1920}, "trigger": { absoluteTop: 2667, absoluteLeft: 724, clientHeight: 0, clientWidth: 0, offsetHeight: 19, offsetWidth: 74}, "overlay": { clientHeight: 40, clientWidth: 113 }, }, containerParentElement: { clientWidth: 1903, clientHeight: 0, scrollLeft: 0, scrollTop: 0, zIndex: 1000 }, expected: { top: 344, bottom: 571, left: 724, right: 1083 }, expectedCorrected: { top: 344, bottom: null, left: 724, right: null, placement: Placement.BottomLeft } }, { theoryName: "modal on page top with overlay fitting better abover trigger but not fitting in body", trigger: { triggerBoundyAdjustMode: TriggerBoundyAdjustMode.InView }, overlay: { placement: Placement.BottomLeft }, window: { innerWidth: 1920, innerHeight: 955, pageXOffset: 0, pageYOffset: 0}, documentElement: { clientHeight: 955, clientWidth: 1920 }, getInfo: { "container": { absoluteTop: 100, absoluteLeft: 700, clientLeft: 0, clientTop: 0, clientHeight: 279, clientWidth: 520, offsetHeight: 279, offsetWidth: 520, scrollLeft: 0, scrollTop: 0, scrollHeight: 279, scrollWidth: 520}, "trigger": { absoluteTop: 250, absoluteLeft: 803, clientHeight: 22, clientWidth: 128, offsetHeight: 24, offsetWidth: 130}, "overlay": { clientHeight: 311, clientWidth: 280 }, }, containerParentElement: { clientWidth: 520, clientHeight: 303, scrollLeft: 0, scrollTop: 0, zIndex: 1000 }, expected: { top: 178, bottom: -210, left: 103, right: 137 }, expectedCorrected: { top: 178, bottom: null, left: 103, right: null, placement: Placement.BottomLeft } }, ]; describe('Overlay position functions', () => { const rewModule = rewire('../../../../../components/core/JsInterop/modules/components/overlay'); const rewClass = rewModule.__get__('Overlay'); let sandbox; before(() => sandbox = sinon.createSandbox()); afterEach(() => sandbox.restore()); itParam("getVerticalPosition & getHorizontalPosition: ${value.theoryName}", theoryPositionData, (testData: positionTheory) => { //arrange let container; let containerParent; let triggerElement; const triggerElementHtml = '<div id="trigger">TriggerElement</div>'; if (testData.getInfo.hasOwnProperty("body")) { container = document.body; triggerElement = domInit.addElementToBody(triggerElementHtml); } else { let containerHtml: string = '<div id="container"></div>' if (testData.containerParentElement) { containerHtml = `<div id="containerParent">${containerHtml}</div>` containerParent = domInit.addElementToBody(containerHtml) container = containerParent.firstChild; const c1 = sandbox.stub(container, 'parentElement').get(() => testData.containerParentElement); } else { container = domInit.addElementToBody(containerHtml) } container.insertAdjacentHTML("afterbegin", triggerElementHtml); triggerElement = container.firstChild; } const overlayElement = domInit.addElementToBody('<div id="overlay" style="position:absolute"></div>') as HTMLDivElement; //discard variable names const w1 = sandbox.stub(window, 'innerHeight').get(() => testData.window.innerHeight); const w2 = sandbox.stub(window, 'innerWidth').get(() => testData.window.innerWidth); const w3 = sandbox.stub(window, 'pageXOffset').get(() => testData.window.pageXOffset); const w4 = sandbox.stub(window, 'pageYOffset').get(() => testData.window.pageYOffset); const d1 = sandbox.stub(document.documentElement, 'clientHeight').get(() => testData.documentElement.clientHeight); const d2 = sandbox.stub(document.documentElement, 'clientWidth').get(() => testData.documentElement.clientWidth); const o1 = sandbox.stub(resizeObserver, 'create').callsFake((key, invoker, isDotNetInvoker: boolean) => null); const o2 = sandbox.stub(mutationObserver, 'create').callsFake((key, invoker, isDotNetInvoker: boolean) => null); const s = sandbox.stub(infoHelper, "getInfo").callsFake((element: HTMLElement) => { let elementId = element.getAttribute("id"); if (!elementId && element === document.body) { elementId = "body"; } return testData.getInfo[elementId]; }); //act let overlay = new rewClass("testId", overlayElement, container, triggerElement, testData.overlay.placement, testData.trigger.triggerBoundyAdjustMode, false, '', overlayConstraintsDefaults); overlay.getKeyElementDimensions(); let verticalPosition = overlay.getVerticalPosition(); let horizontalPosition = overlay.getHorizontalPosition(); //assert expect(verticalPosition.top).to.eq(testData.expected.top); expect(verticalPosition.bottom).to.eq(testData.expected.bottom); expect(horizontalPosition.left).to.eq(testData.expected.left); expect(horizontalPosition.right).to.eq(testData.expected.right); }); }); describe('Overlay calculation', () => { let sandbox; before(() => sandbox = sinon.createSandbox()); afterEach(() => sandbox.restore()); itParam("should contain calculated values: ${value.theoryName}", theoryPositionData, (testData: positionTheory) => { //arrange let container; let containerParent; let triggerElement; const triggerElementHtml = '<div id="trigger">TriggerElement</div>'; if (testData.getInfo.hasOwnProperty("body")) { container = document.body; triggerElement = domInit.addElementToBody(triggerElementHtml); } else { let containerHtml: string = '<div id="container"></div>' if (testData.containerParentElement) { containerHtml = `<div id="containerParent">${containerHtml}</div>` containerParent = domInit.addElementToBody(containerHtml) container = containerParent.firstChild; const c1 = sandbox.stub(container.parentElement, 'clientHeight').get(() => testData.containerParentElement.clientHeight); const c2 = sandbox.stub(container.parentElement, 'clientWidth').get(() => testData.containerParentElement.clientWidth); const c3 = sandbox.stub(container.parentElement, 'scrollLeft').get(() => testData.containerParentElement.scrollLeft); const c4 = sandbox.stub(container.parentElement, 'scrollTop').get(() => testData.containerParentElement.scrollTop); const c5 = sandbox.stub(infoHelper, 'findAncestorWithZIndex').callsFake((element: HTMLElement) => testData.containerParentElement.zIndex); } else { container = domInit.addElementToBody(containerHtml) } container.insertAdjacentHTML("afterbegin", triggerElementHtml); triggerElement = container.firstChild; } const overlayElement = domInit.addElementToBody('<div id="overlay" style="position:absolute"></div>') as HTMLDivElement; //discard variable names const w1 = sandbox.stub(window, 'innerHeight').get(() => testData.window.innerHeight); const w2 = sandbox.stub(window, 'innerWidth').get(() => testData.window.innerWidth); const w3 = sandbox.stub(window, 'pageXOffset').get(() => testData.window.pageXOffset); const w4 = sandbox.stub(window, 'pageYOffset').get(() => testData.window.pageYOffset); const w6 = sandbox.stub(triggerElement, 'offsetParent').get(() => 1); const d1 = sandbox.stub(document.documentElement, 'clientHeight').get(() => testData.documentElement.clientHeight); const d2 = sandbox.stub(document.documentElement, 'clientWidth').get(() => testData.documentElement.clientWidth); const o1 = sandbox.stub(resizeObserver, 'create').callsFake((key, invoker, isDotNetInvoker: boolean) => null); const o2 = sandbox.stub(mutationObserver, 'create').callsFake((key, invoker, isDotNetInvoker: boolean) => null); const s7 = sandbox.stub(infoHelper, "getInfo").callsFake((element: HTMLElement) => { let elementId = element.getAttribute("id"); if (!elementId && element === document.body) { elementId = "body"; } return testData.getInfo[elementId]; }); //act let overlay = new Overlay("testId", overlayElement, container, triggerElement, testData.overlay.placement, testData.trigger.triggerBoundyAdjustMode, false, '', overlayConstraintsDefaults); overlay.calculatePosition(false, true); //assert if (testData.expectedCorrected.top !== null) { expect(overlay.sanitizedPosition.top).to.eq(testData.expectedCorrected.top); expect(overlay.sanitizedPosition.bottom).to.eq(null); } else { expect(overlay.sanitizedPosition.bottom).to.eq(testData.expectedCorrected.bottom); expect(overlay.sanitizedPosition.top).to.eq(null); } if (testData.expectedCorrected.left !== null) { expect(overlay.sanitizedPosition.left).to.eq(testData.expectedCorrected.left); expect(overlay.sanitizedPosition.right).to.eq(null); } else { expect(overlay.sanitizedPosition.right).to.eq(testData.expectedCorrected.right); expect(overlay.sanitizedPosition.left).to.eq(null); } expect(overlay.sanitizedPosition.placement).to.eq(testData.expectedCorrected.placement); }); itParam("(modal) should contain calculated values: ${value.theoryName}", theoryModalPositionData, (testData: positionTheory) => { //arrange let container; let containerParent; let triggerElement; const triggerElementHtml = '<div id="trigger">TriggerElement</div>'; let containerHtml: string = '<div id="container" class="ant-modal-wrap"></div>' containerHtml = `<div id="containerParent" class="ant-modal-root">${containerHtml}</div>` containerParent = domInit.addElementToBody(containerHtml) container = containerParent.firstChild; const c1 = sandbox.stub(container.parentElement, 'clientHeight').get(() => testData.containerParentElement.clientHeight); const c2 = sandbox.stub(container.parentElement, 'clientWidth').get(() => testData.containerParentElement.clientWidth); const c3 = sandbox.stub(container.parentElement, 'scrollLeft').get(() => testData.containerParentElement.scrollLeft); const c4 = sandbox.stub(container.parentElement, 'scrollTop').get(() => testData.containerParentElement.scrollTop); const c5 = sandbox.stub(infoHelper, 'findAncestorWithZIndex').callsFake((element: HTMLElement) => testData.containerParentElement.zIndex); container.insertAdjacentHTML("afterbegin", triggerElementHtml); triggerElement = container.firstChild; const overlayElement = domInit.addElementToBody('<div id="overlay" style="position:absolute"></div>') as HTMLDivElement; //discard variable names const w1 = sandbox.stub(window, 'innerHeight').get(() => testData.window.innerHeight); const w2 = sandbox.stub(window, 'innerWidth').get(() => testData.window.innerWidth); const w3 = sandbox.stub(window, 'pageXOffset').get(() => testData.window.pageXOffset); const w4 = sandbox.stub(window, 'pageYOffset').get(() => testData.window.pageYOffset); const w6 = sandbox.stub(triggerElement, 'offsetParent').get(() => 1); const d1 = sandbox.stub(document.documentElement, 'clientHeight').get(() => testData.documentElement.clientHeight); const d2 = sandbox.stub(document.documentElement, 'clientWidth').get(() => testData.documentElement.clientWidth); const o1 = sandbox.stub(resizeObserver, 'create').callsFake((key, invoker, isDotNetInvoker: boolean) => null); const o2 = sandbox.stub(mutationObserver, 'create').callsFake((key, invoker, isDotNetInvoker: boolean) => null); const s7 = sandbox.stub(infoHelper, "getInfo").callsFake((element: HTMLElement) => { let elementId = element.getAttribute("id"); if (!elementId && element === document.body) { elementId = "body"; } return testData.getInfo[elementId]; }); //act let overlay = new Overlay("testId", overlayElement, container, triggerElement, testData.overlay.placement, testData.trigger.triggerBoundyAdjustMode, false, '', overlayConstraintsDefaults); overlay.calculatePosition(false, true); //assert if (testData.expectedCorrected.top !== null) { expect(overlay.sanitizedPosition.top).to.eq(testData.expectedCorrected.top); expect(overlay.sanitizedPosition.bottom).to.eq(null); } else { expect(overlay.sanitizedPosition.bottom).to.eq(testData.expectedCorrected.bottom); expect(overlay.sanitizedPosition.top).to.eq(null); } if (testData.expectedCorrected.left !== null) { expect(overlay.sanitizedPosition.left).to.eq(testData.expectedCorrected.left); expect(overlay.sanitizedPosition.right).to.eq(null); } else { expect(overlay.sanitizedPosition.right).to.eq(testData.expectedCorrected.right); expect(overlay.sanitizedPosition.left).to.eq(null); } expect(overlay.sanitizedPosition.placement).to.eq(testData.expectedCorrected.placement); }) itParam("scrollScenarios: ${value.theoryName}", theoryScrollData, (testData: scrollTheory) => { //arrange let container; let containerParent; let triggerElement; const triggerElementHtml = '<div id="trigger">TriggerElement</div>'; if (testData.getInfo.hasOwnProperty("body")) { container = document.body; triggerElement = domInit.addElementToBody(triggerElementHtml); } else { let containerHtml: string = '<div id="container"></div>' if (testData.containerParentElement) { containerHtml = `<div id="containerParent">${containerHtml}</div>` containerParent = domInit.addElementToBody(containerHtml) container = containerParent.firstChild; const c1 = sandbox.stub(container.parentElement, 'clientHeight').get(() => testData.containerParentElement.clientHeight); const c2 = sandbox.stub(container.parentElement, 'clientWidth').get(() => testData.containerParentElement.clientWidth); const c3 = sandbox.stub(container.parentElement, 'scrollLeft').get(() => testData.containerParentElement.scrollLeft); const c4 = sandbox.stub(container.parentElement, 'scrollTop').get(() => testData.containerParentElement.scrollTop); } else { container = domInit.addElementToBody(containerHtml) } container.insertAdjacentHTML("afterbegin", triggerElementHtml); triggerElement = container.firstChild; } const overlayElement = domInit.addElementToBody('<div id="overlay" style="position:absolute"></div>') as HTMLDivElement; let pageXOffset = testData.window.pageXOffset; let pageYOffset = testData.window.pageYOffset; //discard variable names const w1 = sandbox.stub(window, 'innerHeight').get(() => testData.window.innerHeight); const w2 = sandbox.stub(window, 'innerWidth').get(() => testData.window.innerWidth); const w3 = sandbox.stub(window, 'pageXOffset').get(() => pageXOffset); const w4 = sandbox.stub(window, 'pageYOffset').get(() => pageYOffset); const w5 = sandbox.stub(overlayElement, 'offsetParent').get(() => 1); //not null and > 0 is needed const w6 = sandbox.stub(triggerElement, 'offsetParent').get(() => 1); const d1 = sandbox.stub(document.documentElement, 'clientHeight').get(() => testData.documentElement.clientHeight); const d2 = sandbox.stub(document.documentElement, 'clientWidth').get(() => testData.documentElement.clientWidth); const o1 = sandbox.stub(resizeObserver, 'create').callsFake((key, invoker, isDotNetInvoker: boolean) => null); const o2 = sandbox.stub(mutationObserver, 'create').callsFake((key, invoker, isDotNetInvoker: boolean) => null); const s7 = sandbox.stub(infoHelper, "getInfo").callsFake((element: HTMLElement) => { let elementId = element.getAttribute("id"); if (!elementId && element === document.body) { elementId = "body"; } return testData.getInfo[elementId]; }); //act let overlay = new Overlay("testId", overlayElement, container, triggerElement, testData.overlay.placement, testData.trigger.triggerBoundyAdjustMode, false, '', overlayConstraintsDefaults); overlay.calculatePosition(false, true); //assert if (testData.expectedCorrected.top !== null) { expect(overlay.sanitizedPosition.top).to.eq(testData.expectedCorrected.top); expect(overlay.sanitizedPosition.bottom).to.eq(null); } else { expect(overlay.sanitizedPosition.bottom).to.eq(testData.expectedCorrected.bottom); expect(overlay.sanitizedPosition.top).to.eq(null); } if (testData.expectedCorrected.left !== null) { expect(overlay.sanitizedPosition.left).to.eq(testData.expectedCorrected.left); expect(overlay.sanitizedPosition.right).to.eq(null); } else { expect(overlay.sanitizedPosition.right).to.eq(testData.expectedCorrected.right); expect(overlay.sanitizedPosition.left).to.eq(null); } expect(overlay.sanitizedPosition.placement).to.eq(testData.expectedCorrected.placement); for(let i = 0; i < testData.scrollSteps.length; i++) { let scrollStep = testData.scrollSteps[i]; pageXOffset = scrollStep.x ?? pageXOffset; pageYOffset = scrollStep.y ?? pageYOffset; overlay.calculatePosition(true, false, null); if (scrollStep.expectedAfterScroll.top !== null) { expect(overlay.sanitizedPosition.top).to.eq(scrollStep.expectedAfterScroll.top); expect(overlay.sanitizedPosition.bottom).to.eq(null); } else { expect(overlay.sanitizedPosition.bottom).to.eq(scrollStep.expectedAfterScroll.bottom); expect(overlay.sanitizedPosition.top).to.eq(null); } if (scrollStep.expectedAfterScroll.left !== null) { expect(overlay.sanitizedPosition.left).to.eq(scrollStep.expectedAfterScroll.left); expect(overlay.sanitizedPosition.right).to.eq(null); } else { expect(overlay.sanitizedPosition.right).to.eq(scrollStep.expectedAfterScroll.right); expect(overlay.sanitizedPosition.left).to.eq(null); } expect(overlay.sanitizedPosition.placement).to.eq(scrollStep.expectedAfterScroll.placement); } }); }); type resizeTheory = positionTheory & { contentRect: { height: number, width: number } } const theoryResizeData: Array<resizeTheory> = [ { theoryName: "scenario 1", trigger: { triggerBoundyAdjustMode: TriggerBoundyAdjustMode.InView }, overlay: { placement: Placement.BottomLeft }, window: { innerWidth: 1920, innerHeight: 955, pageXOffset: 0, pageYOffset: 0}, documentElement: { clientHeight: 900, clientWidth: 1000 }, getInfo: { "body": { absoluteTop: 0, absoluteLeft: 0, clientLeft: 0, clientTop: 0, scrollLeft: 0, scrollTop: 0, scrollHeight: 955, scrollWidth: 1920}, "trigger": { absoluteTop: 22, absoluteLeft: 790, clientHeight: 0, clientWidth: 0, offsetHeight: 19, offsetWidth: 157}, "overlay": { clientHeight: 808, clientWidth: 372 }, }, contentRect: {height: 900, width: 1000}, expected: { top: null, left: null, right: null, bottom: null }, expectedCorrected: { top: 45, left: null, right: 53, bottom: null, placement: Placement.BottomRight } } ]; describe('Overlay recalculation on container resize', () => { let sandbox; before(() => sandbox = sinon.createSandbox()); afterEach(() => sandbox.restore()); itParam("resize observer should calculate new position", theoryResizeData, (testData: resizeTheory) => { //arrange const triggerElement = domInit.addElementToBody('<div id="trigger">TriggerElement</div>'); const overlayElement = domInit.addElementToBody('<div id="overlay" style="position:absolute"></div>') as HTMLDivElement; const container = document.body; //discard variable names let inResize = false; const w1 = sandbox.stub(window, 'innerHeight').get(() => testData.window.innerHeight); const w2 = sandbox.stub(window, 'innerWidth').get(() => testData.window.innerWidth); const w3 = sandbox.stub(window, 'pageXOffset').get(() => testData.window.pageXOffset); const w4 = sandbox.stub(window, 'pageYOffset').get(() => testData.window.pageYOffset); const w5 = sandbox.stub(overlayElement, 'offsetParent').get(() => 1); //not null and > 0 is needed const w6 = sandbox.stub(triggerElement, 'offsetParent').get(() => 1); const d1 = sandbox.stub(document.documentElement, 'clientHeight').get(() => testData.documentElement.clientHeight); const d2 = sandbox.stub(document.documentElement, 'clientWidth').get(() => testData.documentElement.clientWidth); let resizeCallback; let mutationCallback; const o1 = sandbox.stub(resizeObserver, 'create').callsFake((key, invoker, isDotNetInvoker: boolean) => { resizeCallback = invoker; return; }); const o2 = sandbox.stub(mutationObserver, 'create').callsFake((key, invoker, isDotNetInvoker: boolean) => { mutationCallback = invoker; return; }); const s7 = sandbox.stub(infoHelper, "getInfo").callsFake((element: HTMLElement) => { let elementId = element.getAttribute("id"); if (!elementId && element === document.body) { elementId = "body"; } return testData.getInfo[elementId]; }); //act let overlay = new Overlay("testId", overlayElement, container, triggerElement, testData.overlay.placement, testData.trigger.triggerBoundyAdjustMode, false, '', overlayConstraintsDefaults); overlay.calculatePosition(false, true); resizeCallback(null, null); //reset Overlay.duringInit; //change test data for stubs testData.window.innerHeight = testData.contentRect.height; testData.window.innerWidth = testData.contentRect.width; testData.getInfo["body"].scrollHeight = testData.contentRect.height; testData.getInfo["body"].scrollWidth = testData.contentRect.width; resizeCallback(testData.contentRect, null); //assert if (testData.expectedCorrected.top !== null) { expect(overlay.sanitizedPosition.top).to.eq(testData.expectedCorrected.top); expect(overlay.sanitizedPosition.bottom).to.eq(null); } else { expect(overlay.sanitizedPosition.bottom).to.eq(testData.expectedCorrected.bottom); expect(overlay.sanitizedPosition.top).to.eq(null); } if (testData.expectedCorrected.left !== null) { expect(overlay.sanitizedPosition.left).to.eq(testData.expectedCorrected.left); expect(overlay.sanitizedPosition.right).to.eq(null); } else { expect(overlay.sanitizedPosition.right).to.eq(testData.expectedCorrected.right); expect(overlay.sanitizedPosition.left).to.eq(null); } expect(overlay.sanitizedPosition.placement).to.eq(testData.expectedCorrected.placement); }); it("should not reposition when submenu's parent is hidden", () => { //arrange const triggerElement = domInit.addElementToBody('<div id="trigger">TriggerElement</div>'); const overlayElement = domInit.addElementToBody('<div id="overlay" style="position:absolute"></div>') as HTMLDivElement; const container = document.body; //discard variable names let offsetParent = 1; let inResize = false; const w1 = sandbox.stub(window, 'innerHeight').get(() => 955); const w2 = sandbox.stub(window, 'innerWidth').get(() => 1920); const w3 = sandbox.stub(window, 'pageXOffset').get(() => 0); const w4 = sandbox.stub(window, 'pageYOffset').get(() => 1020); const w5 = sandbox.stub(overlayElement, 'offsetParent').get(() => 1); //not null and > 0 is needed const w6 = sandbox.stub(triggerElement, 'offsetParent').get(() => offsetParent); const d1 = sandbox.stub(document.documentElement, 'clientHeight').get(() => 955); const d2 = sandbox.stub(document.documentElement, 'clientWidth').get(() => 1903); let resizeCallback; let mutationCallback; const o1 = sandbox.stub(resizeObserver, 'create').callsFake((key, invoker, isDotNetInvoker: boolean) => { resizeCallback = invoker; return; }); const o2 = sandbox.stub(mutationObserver, 'create').callsFake((key, invoker, isDotNetInvoker: boolean) => { mutationCallback = invoker; return; }); let triggerInfo: domInfo = { ...domInfoDefaults, absoluteTop: 1577, absoluteLeft: 406, clientHeight: 32, clientWidth: 175, offsetHeight: 32, offsetWidth: 175 } const s7 = sandbox.stub(infoHelper, "getInfo").callsFake((element: HTMLElement) => { let elementId = element.getAttribute("id"); if (!elementId && element === document.body) { elementId = "body"; } let domInfo = domInfoDefaults; switch (elementId) { case "body": domInfo = { ...domInfoDefaults, absoluteTop: 0, absoluteLeft: 0, clientLeft: 0, clientTop: 0, scrollLeft: 0, scrollTop: 0, scrollHeight: 5560, scrollWidth: 1903 } break; case "trigger": domInfo = triggerInfo; break; case "overlay": domInfo = { ...domInfoDefaults, clientHeight: 80, clientWidth: 123 } break; } return domInfo; }); //act let overlay = new Overlay("testId", overlayElement, container, triggerElement, Placement.RightTop, TriggerBoundyAdjustMode.None, false, '', overlayConstraintsDefaults); overlay.calculatePosition(false, true); resizeCallback(null, null); //reset Overlay.duringInit; //change test data for stubs offsetParent = null; triggerInfo = { ...domInfoDefaults, absoluteTop: 1020 }; resizeCallback({height: 900, width: 1000}, null); //assert expect(overlay.sanitizedPosition.top).to.eq(1577); expect(overlay.sanitizedPosition.left).to.eq(585); expect(overlay.sanitizedPosition.right).to.eq(null); expect(overlay.sanitizedPosition.bottom).to.eq(null); expect(overlay.sanitizedPosition.placement).to.eq(Placement.RightTop); }); });
the_stack
import { html, TemplateResult } from 'lit-html'; import { Suggestion } from '../components/auto_complete'; import { TestVariant } from '../services/resultdb'; import { parseProtoDuration } from './time_utils'; const SPECIAL_QUERY_RE = /^(-?)([a-zA-Z]+):(.+)$/; export type TestVariantFilter = (v: TestVariant) => boolean; export function parseSearchQuery(searchQuery: string): TestVariantFilter { const filters = searchQuery.split(' ').map((query) => { const match = query.match(SPECIAL_QUERY_RE); const [, neg, type, value] = match || ['', '', '', query]; const valueUpper = value.toUpperCase(); const negate = neg === '-'; switch (type.toUpperCase()) { // Whether the test ID or test name contains the query as a substring // (case insensitive). case '': { return (v: TestVariant) => { const matched = v.testId.toUpperCase().includes(valueUpper) || v.testMetadata?.name?.toUpperCase().includes(valueUpper); return negate !== Boolean(matched); }; } // Whether the test variant has the specified status. case 'STATUS': { const statuses = valueUpper.split(','); return (v: TestVariant) => negate !== statuses.includes(v.status); } // Whether there's at least one a test result of the specified status. case 'RSTATUS': { const statuses = valueUpper.split(','); return (v: TestVariant) => negate !== (v.results || []).some((r) => statuses.includes(r.result.status)); } // Whether the test ID contains the query as a substring (case // insensitive). case 'ID': { return (v: TestVariant) => negate !== v.testId.toUpperCase().includes(valueUpper); } // Whether the test ID matches the specified ID (case sensitive). case 'EXACTID': { return (v: TestVariant) => negate !== (v.testId === value); } // Whether the test variant has a matching variant key-value pair. case 'V': { // Don't use String.split here because then vValue can't contain '='. const [, vKey, vValue] = value.match(/^([^=]*)(?:=(.*))?$/)!; // If the variant value is unspecified, accept any value. // Otherwise, the value must match the specified value (case sensitive). return vValue === undefined ? (v: TestVariant) => negate !== (v.variant?.def?.[vKey] !== undefined) : (v: TestVariant) => negate !== (v.variant?.def?.[vKey] === vValue); } // Whether the test variant has the specified variant hash. case 'VHASH': { return (v: TestVariant) => negate !== (v.variantHash.toUpperCase() === valueUpper); } // Whether the test name contains the query as a substring (case // insensitive). case 'NAME': { return (v: TestVariant) => negate !== (v.testMetadata?.name || '').toUpperCase().includes(valueUpper); } // Whether the test name matches the specified name (case sensitive). case 'EXACTNAME': { return (v: TestVariant) => negate !== (v.testMetadata?.name === value); } // Whether the test has a run with a matching tag (case sensitive). case 'TAG': { // Don't use String.split here because then vValue can't contain '='. const [, tKey, tValue] = value.match(/^([^=]*)(?:=(.*))?$/)!; if (tValue) { return (v: TestVariant) => negate === !v.results?.some((r) => r.result.tags?.some((t) => t.key === tKey && t.value === tValue)); } else { return (v: TestVariant) => negate === !v.results?.some((r) => r.result.tags?.some((t) => t.key === tKey)); } } // Whether the test has at least one run with a duration in the specified // range. case 'DURATION': { const match = value.match(/^(\d+(?:\.\d+)?)-(\d+(?:\.\d+)?)?$/); if (!match) { throw new Error(`invalid duration range: ${value}`); } const [, minDurationStr, maxDurationStr] = match; const minDuration = Number(minDurationStr) * 1000; const maxDuration = maxDurationStr ? Number(maxDurationStr || '0') * 1000 : Infinity; return (v: TestVariant) => negate === !v.results?.some((r) => { if (!r.result.duration) { return false; } const durationMs = parseProtoDuration(r.result.duration); return durationMs >= minDuration && durationMs <= maxDuration; }); } default: { throw new Error(`invalid query type: ${type}`); } } }); return (v) => filters.every((f) => f(v)); } // Queries with predefined value. const QUERY_SUGGESTIONS = [ { value: 'Status:UNEXPECTED', explanation: 'Include only tests with unexpected status' }, { value: '-Status:UNEXPECTED', explanation: 'Exclude tests with unexpected status' }, { value: 'Status:UNEXPECTEDLY_SKIPPED', explanation: 'Include only tests with unexpectedly skipped status' }, { value: '-Status:UNEXPECTEDLY_SKIPPED', explanation: 'Exclude tests with unexpectedly skipped status' }, { value: 'Status:FLAKY', explanation: 'Include only tests with flaky status' }, { value: '-Status:FLAKY', explanation: 'Exclude tests with flaky status' }, { value: 'Status:EXONERATED', explanation: 'Include only tests with exonerated status' }, { value: '-Status:EXONERATED', explanation: 'Exclude tests with exonerated status' }, { value: 'Status:EXPECTED', explanation: 'Include only tests with expected status' }, { value: '-Status:EXPECTED', explanation: 'Exclude tests with expected status' }, { value: 'RStatus:Pass', explanation: 'Include only tests with at least one passed run' }, { value: '-RStatus:Pass', explanation: 'Exclude tests with at least one passed run' }, { value: 'RStatus:Fail', explanation: 'Include only tests with at least one failed run' }, { value: '-RStatus:Fail', explanation: 'Exclude tests with at least one failed run' }, { value: 'RStatus:Crash', explanation: 'Include only tests with at least one crashed run' }, { value: '-RStatus:Crash', explanation: 'Exclude tests with at least one crashed run' }, { value: 'RStatus:Abort', explanation: 'Include only tests with at least one aborted run' }, { value: '-RStatus:Abort', explanation: 'Exclude tests with at least one aborted run' }, { value: 'RStatus:Skip', explanation: 'Include only tests with at least one skipped run' }, { value: '-RStatus:Skip', explanation: 'Exclude tests with at least one skipped run' }, ]; // Queries with arbitrary value. const QUERY_TYPE_SUGGESTIONS = [ { type: 'V:', explanation: 'Include only tests with a matching variant key-value pair (case sensitive)' }, { type: '-V:', explanation: 'Exclude tests with a matching variant key-value pair (case sensitive)' }, { type: 'Tag:', explanation: 'Include only tests with a run that has a matching tag key-value pair (case sensitive)', }, { type: '-Tag:', explanation: 'Exclude tests with a run that has a matching tag key-value pair (case sensitive)', }, { type: 'ID:', explanation: 'Include only tests with the specified substring in their ID (case insensitive)' }, { type: '-ID:', explanation: 'Exclude tests with the specified substring in their ID (case insensitive)' }, { type: 'Name:', explanation: 'Include only tests with the specified substring in their Name (case insensitive)' }, { type: '-Name:', explanation: 'Exclude tests with the specified substring in their Name (case insensitive)' }, { type: 'ExactID:', explanation: 'Include only tests with the specified ID (case sensitive)' }, { type: '-ExactID:', explanation: 'Exclude tests with the specified ID (case sensitive)' }, { type: 'Duration:', explanation: 'Include only tests with a run that has a duration in the specified range' }, { type: '-Duration:', explanation: 'Exclude tests with a run that has a duration in the specified range' }, { type: 'ExactName:', explanation: 'Include only tests with the specified name (case sensitive)' }, { type: '-ExactName:', explanation: 'Exclude tests with the specified name (case sensitive)' }, { type: 'VHash:', explanation: 'Include only tests with the specified variant hash' }, { type: '-VHash:', explanation: 'Exclude tests with the specified variant hash' }, ]; /** * Return a lit-html template that highlight the substring (case-insensitive) * in the given fullString. */ function highlight(fullString: string, subString: string): TemplateResult { const matchStart = fullString.toUpperCase().search(subString.toUpperCase()); const prefix = fullString.slice(0, matchStart); const matched = fullString.slice(matchStart, matchStart + subString.length); const suffix = fullString.slice(matchStart + subString.length); return html`${prefix}<strong>${matched}</strong>${suffix}`; } export function suggestSearchQuery(query: string): readonly Suggestion[] { if (query === '') { // Return some example queries when the query is empty. return [ { isHeader: true, display: html`<strong>Advanced Syntax</strong>`, }, { value: '-Status:EXPECTED', explanation: "Use '-' prefix to negate the filter", }, { value: 'Status:UNEXPECTED -RStatus:Skipped', explanation: 'Use space to separate filters. Filters are logically joined with AND', }, // Put this section behind `Advanced Syntax` so `Advanced Syntax` won't // be hidden after the size of supported filter types grows. { isHeader: true, display: html`<strong>Supported Filter Types</strong>`, }, { value: 'test-id-substr', explanation: 'Include only tests with the specified substring in their ID or name (case insensitive)', }, { value: 'V:variant-key=variant-value', explanation: 'Include only tests with a matching test variant key-value pair (case sensitive)', }, { value: 'V:variant-key', explanation: 'Include only tests with the specified variant key (case sensitive)', }, { value: 'Tag:tag-key=tag-value', explanation: 'Include only tests with a run that has a matching tag key-value pair (case sensitive)', }, { value: 'Tag:tag-key', explanation: 'Include only tests with a run that has the specified tag key (case sensitive)', }, { value: 'ID:test-id-substr', explanation: 'Include only tests with the specified substring in their ID (case insensitive)', }, { value: 'Status:UNEXPECTED,UNEXPECTEDLY_SKIPPED,FLAKY,EXONERATED,EXPECTED', explanation: 'Include only tests with the specified status', }, { value: 'RStatus:Pass,Fail,Crash,Abort,Skip', explanation: 'Include only tests with at least one run of the specified status', }, { value: 'Name:test-name-substr', explanation: 'Include only tests with the specified substring in their name (case insensitive)', }, { value: 'Duration:0.05-15', explanation: 'Include only tests with a run that has a duration in the specified range (in seconds)', }, { value: 'Duration:0.05-', explanation: 'Max duration can be omitted', }, { value: 'ExactID:test-id', explanation: 'Include only tests with the specified test ID (case sensitive)', }, { value: 'ExactName:test-name', explanation: 'Include only tests with the specified name (case sensitive)', }, { value: 'VHash:2660cde9da304c42', explanation: 'Include only tests with the specified variant hash', }, ]; } const subQuery = query.split(' ').pop()!; if (subQuery === '') { return []; } const suggestions: Suggestion[] = []; // Suggest queries with predefined value. const subQueryUpper = subQuery.toUpperCase(); suggestions.push(...QUERY_SUGGESTIONS.filter(({ value }) => value.toUpperCase().includes(subQueryUpper))); // Suggest queries with arbitrary value. const match = subQuery.match(/^([^:]*:?)(.*)$/); if (match) { const [, subQueryType, subQueryValue] = match as [string, string, string]; const typeUpper = subQueryType.toUpperCase(); suggestions.push( ...QUERY_TYPE_SUGGESTIONS.flatMap(({ type, explanation }) => { if (type.toUpperCase().includes(typeUpper)) { return [{ value: type + subQueryValue, explanation }]; } if (subQueryValue === '') { return [{ value: type + subQueryType, explanation }]; } return []; }) ); } return suggestions.map((s) => ({ ...s, display: s.display || highlight(s.value!, subQuery) })); }
the_stack
import { KeyCode, KeyMod } from 'vs/base/common/keyCodes'; import { EditorContextKeys } from 'vs/editor/common/editorContextKeys'; import { localize } from 'vs/nls'; import { registerAction2 } from 'vs/platform/actions/common/actions'; import { Extensions as ConfigurationExtensions, IConfigurationRegistry } from 'vs/platform/configuration/common/configurationRegistry'; import { ContextKeyExpr } from 'vs/platform/contextkey/common/contextkey'; import { InputFocusedContextKey } from 'vs/platform/contextkey/common/contextkeys'; import { ServicesAccessor } from 'vs/platform/instantiation/common/instantiation'; import { KeybindingWeight } from 'vs/platform/keybinding/common/keybindingsRegistry'; import { Registry } from 'vs/platform/registry/common/platform'; import { INotebookActionContext, INotebookCellActionContext, NotebookAction, NotebookCellAction, NOTEBOOK_EDITOR_WIDGET_ACTION_WEIGHT } from 'vs/workbench/contrib/notebook/browser/controller/coreActions'; import { NOTEBOOK_CELL_HAS_OUTPUTS, NOTEBOOK_CELL_MARKDOWN_EDIT_MODE, NOTEBOOK_CELL_TYPE, NOTEBOOK_CURSOR_NAVIGATION_MODE, NOTEBOOK_EDITOR_FOCUSED, NOTEBOOK_OUTPUT_FOCUSED } from 'vs/workbench/contrib/notebook/common/notebookContextKeys'; import { CellEditState } from 'vs/workbench/contrib/notebook/browser/notebookBrowser'; import { CellKind, NOTEBOOK_EDITOR_CURSOR_BOUNDARY } from 'vs/workbench/contrib/notebook/common/notebookCommon'; import { EditorExtensionsRegistry } from 'vs/editor/browser/editorExtensions'; const NOTEBOOK_FOCUS_TOP = 'notebook.focusTop'; const NOTEBOOK_FOCUS_BOTTOM = 'notebook.focusBottom'; const NOTEBOOK_FOCUS_PREVIOUS_EDITOR = 'notebook.focusPreviousEditor'; const NOTEBOOK_FOCUS_NEXT_EDITOR = 'notebook.focusNextEditor'; const FOCUS_IN_OUTPUT_COMMAND_ID = 'notebook.cell.focusInOutput'; const FOCUS_OUT_OUTPUT_COMMAND_ID = 'notebook.cell.focusOutOutput'; export const CENTER_ACTIVE_CELL = 'notebook.centerActiveCell'; const NOTEBOOK_CURSOR_PAGEUP_COMMAND_ID = 'notebook.cell.cursorPageUp'; const NOTEBOOK_CURSOR_PAGEUP_SELECT_COMMAND_ID = 'notebook.cell.cursorPageUpSelect'; const NOTEBOOK_CURSOR_PAGEDOWN_COMMAND_ID = 'notebook.cell.cursorPageDown'; const NOTEBOOK_CURSOR_PAGEDOWN_SELECT_COMMAND_ID = 'notebook.cell.cursorPageDownSelect'; registerAction2(class FocusNextCellAction extends NotebookCellAction { constructor() { super({ id: NOTEBOOK_FOCUS_NEXT_EDITOR, title: localize('cursorMoveDown', 'Focus Next Cell Editor'), keybinding: [ { when: ContextKeyExpr.and( NOTEBOOK_EDITOR_FOCUSED, ContextKeyExpr.equals('config.notebook.navigation.allowNavigateToSurroundingCells', true), ContextKeyExpr.or( ContextKeyExpr.and( ContextKeyExpr.has(InputFocusedContextKey), EditorContextKeys.editorTextFocus, NOTEBOOK_EDITOR_CURSOR_BOUNDARY.notEqualsTo('top'), NOTEBOOK_EDITOR_CURSOR_BOUNDARY.notEqualsTo('none'), ), ContextKeyExpr.and( NOTEBOOK_CELL_TYPE.isEqualTo('markup'), NOTEBOOK_CELL_MARKDOWN_EDIT_MODE.isEqualTo(false), NOTEBOOK_CURSOR_NAVIGATION_MODE ) ) ), primary: KeyCode.DownArrow, weight: KeybindingWeight.WorkbenchContrib, }, { when: ContextKeyExpr.and(NOTEBOOK_EDITOR_FOCUSED, NOTEBOOK_OUTPUT_FOCUSED), primary: KeyMod.CtrlCmd | KeyCode.DownArrow, mac: { primary: KeyMod.WinCtrl | KeyMod.CtrlCmd | KeyCode.DownArrow, }, weight: KeybindingWeight.WorkbenchContrib } ] }); } async runWithContext(accessor: ServicesAccessor, context: INotebookCellActionContext): Promise<void> { const editor = context.notebookEditor; const activeCell = context.cell; const idx = editor.getCellIndex(activeCell); if (typeof idx !== 'number') { return; } if (idx >= editor.getLength() - 1) { // last one return; } const newCell = editor.cellAt(idx + 1); const newFocusMode = newCell.cellKind === CellKind.Markup && newCell.getEditState() === CellEditState.Preview ? 'container' : 'editor'; await editor.focusNotebookCell(newCell, newFocusMode, { focusEditorLine: 1 }); } }); registerAction2(class FocusPreviousCellAction extends NotebookCellAction { constructor() { super({ id: NOTEBOOK_FOCUS_PREVIOUS_EDITOR, title: localize('cursorMoveUp', 'Focus Previous Cell Editor'), keybinding: { when: ContextKeyExpr.and( NOTEBOOK_EDITOR_FOCUSED, ContextKeyExpr.equals('config.notebook.navigation.allowNavigateToSurroundingCells', true), ContextKeyExpr.or( ContextKeyExpr.and( ContextKeyExpr.has(InputFocusedContextKey), EditorContextKeys.editorTextFocus, NOTEBOOK_EDITOR_CURSOR_BOUNDARY.notEqualsTo('bottom'), NOTEBOOK_EDITOR_CURSOR_BOUNDARY.notEqualsTo('none'), ), ContextKeyExpr.and( NOTEBOOK_CELL_TYPE.isEqualTo('markup'), NOTEBOOK_CELL_MARKDOWN_EDIT_MODE.isEqualTo(false), NOTEBOOK_CURSOR_NAVIGATION_MODE ) ) ), primary: KeyCode.UpArrow, weight: KeybindingWeight.WorkbenchContrib, }, }); } async runWithContext(accessor: ServicesAccessor, context: INotebookCellActionContext): Promise<void> { const editor = context.notebookEditor; const activeCell = context.cell; const idx = editor.getCellIndex(activeCell); if (typeof idx !== 'number') { return; } if (idx < 1 || editor.getLength() === 0) { // we don't do loop return; } const newCell = editor.cellAt(idx - 1); const newFocusMode = newCell.cellKind === CellKind.Markup && newCell.getEditState() === CellEditState.Preview ? 'container' : 'editor'; await editor.focusNotebookCell(newCell, newFocusMode, { focusEditorLine: newCell.textBuffer.getLineCount() }); } }); registerAction2(class extends NotebookAction { constructor() { super({ id: NOTEBOOK_FOCUS_TOP, title: localize('focusFirstCell', 'Focus First Cell'), keybinding: { when: ContextKeyExpr.and(NOTEBOOK_EDITOR_FOCUSED, ContextKeyExpr.not(InputFocusedContextKey)), primary: KeyMod.CtrlCmd | KeyCode.Home, mac: { primary: KeyMod.CtrlCmd | KeyCode.UpArrow }, weight: KeybindingWeight.WorkbenchContrib }, }); } async runWithContext(accessor: ServicesAccessor, context: INotebookActionContext): Promise<void> { const editor = context.notebookEditor; if (editor.getLength() === 0) { return; } const firstCell = editor.cellAt(0); await editor.focusNotebookCell(firstCell, 'container'); } }); registerAction2(class extends NotebookAction { constructor() { super({ id: NOTEBOOK_FOCUS_BOTTOM, title: localize('focusLastCell', 'Focus Last Cell'), keybinding: { when: ContextKeyExpr.and(NOTEBOOK_EDITOR_FOCUSED, ContextKeyExpr.not(InputFocusedContextKey)), primary: KeyMod.CtrlCmd | KeyCode.End, mac: { primary: KeyMod.CtrlCmd | KeyCode.DownArrow }, weight: KeybindingWeight.WorkbenchContrib }, }); } async runWithContext(accessor: ServicesAccessor, context: INotebookActionContext): Promise<void> { const editor = context.notebookEditor; if (!editor.hasModel() || editor.getLength() === 0) { return; } const lastIdx = editor.getLength() - 1; const lastVisibleIdx = editor.getPreviousVisibleCellIndex(lastIdx); if (lastVisibleIdx) { const cell = editor.cellAt(lastVisibleIdx); await editor.focusNotebookCell(cell, 'container'); } } }); registerAction2(class extends NotebookCellAction { constructor() { super({ id: FOCUS_IN_OUTPUT_COMMAND_ID, title: localize('focusOutput', 'Focus In Active Cell Output'), keybinding: { when: ContextKeyExpr.and(NOTEBOOK_EDITOR_FOCUSED, NOTEBOOK_CELL_HAS_OUTPUTS), primary: KeyMod.CtrlCmd | KeyCode.DownArrow, mac: { primary: KeyMod.WinCtrl | KeyMod.CtrlCmd | KeyCode.DownArrow, }, weight: KeybindingWeight.WorkbenchContrib }, }); } async runWithContext(accessor: ServicesAccessor, context: INotebookCellActionContext): Promise<void> { const editor = context.notebookEditor; const activeCell = context.cell; await editor.focusNotebookCell(activeCell, 'output'); } }); registerAction2(class extends NotebookCellAction { constructor() { super({ id: FOCUS_OUT_OUTPUT_COMMAND_ID, title: localize('focusOutputOut', 'Focus Out Active Cell Output'), keybinding: { when: NOTEBOOK_EDITOR_FOCUSED, primary: KeyMod.CtrlCmd | KeyCode.UpArrow, mac: { primary: KeyMod.WinCtrl | KeyMod.CtrlCmd | KeyCode.UpArrow, }, weight: KeybindingWeight.WorkbenchContrib }, }); } async runWithContext(accessor: ServicesAccessor, context: INotebookCellActionContext): Promise<void> { const editor = context.notebookEditor; const activeCell = context.cell; await editor.focusNotebookCell(activeCell, 'editor'); } }); registerAction2(class CenterActiveCellAction extends NotebookCellAction { constructor() { super({ id: CENTER_ACTIVE_CELL, title: localize('notebookActions.centerActiveCell', "Center Active Cell"), keybinding: { when: NOTEBOOK_EDITOR_FOCUSED, primary: KeyMod.CtrlCmd | KeyCode.KeyL, mac: { primary: KeyMod.WinCtrl | KeyCode.KeyL, }, weight: KeybindingWeight.WorkbenchContrib }, }); } async runWithContext(accessor: ServicesAccessor, context: INotebookCellActionContext): Promise<void> { return context.notebookEditor.revealInCenter(context.cell); } }); registerAction2(class extends NotebookCellAction { constructor() { super({ id: NOTEBOOK_CURSOR_PAGEUP_COMMAND_ID, title: localize('cursorPageUp', "Cell Cursor Page Up"), keybinding: [ { when: ContextKeyExpr.and( NOTEBOOK_EDITOR_FOCUSED, ContextKeyExpr.has(InputFocusedContextKey), EditorContextKeys.editorTextFocus, ), primary: KeyCode.PageUp, weight: NOTEBOOK_EDITOR_WIDGET_ACTION_WEIGHT } ] }); } async runWithContext(accessor: ServicesAccessor, context: INotebookCellActionContext): Promise<void> { EditorExtensionsRegistry.getEditorCommand('cursorPageUp').runCommand(accessor, { pageSize: getPageSize(context) }); } }); registerAction2(class extends NotebookCellAction { constructor() { super({ id: NOTEBOOK_CURSOR_PAGEUP_SELECT_COMMAND_ID, title: localize('cursorPageUpSelect', "Cell Cursor Page Up Select"), keybinding: [ { when: ContextKeyExpr.and( NOTEBOOK_EDITOR_FOCUSED, ContextKeyExpr.has(InputFocusedContextKey), EditorContextKeys.editorTextFocus, ), primary: KeyMod.Shift | KeyCode.PageUp, weight: NOTEBOOK_EDITOR_WIDGET_ACTION_WEIGHT } ] }); } async runWithContext(accessor: ServicesAccessor, context: INotebookCellActionContext): Promise<void> { EditorExtensionsRegistry.getEditorCommand('cursorPageUpSelect').runCommand(accessor, { pageSize: getPageSize(context) }); } }); registerAction2(class extends NotebookCellAction { constructor() { super({ id: NOTEBOOK_CURSOR_PAGEDOWN_COMMAND_ID, title: localize('cursorPageDown', "Cell Cursor Page Down"), keybinding: [ { when: ContextKeyExpr.and( NOTEBOOK_EDITOR_FOCUSED, ContextKeyExpr.has(InputFocusedContextKey), EditorContextKeys.editorTextFocus, ), primary: KeyCode.PageDown, weight: NOTEBOOK_EDITOR_WIDGET_ACTION_WEIGHT } ] }); } async runWithContext(accessor: ServicesAccessor, context: INotebookCellActionContext): Promise<void> { EditorExtensionsRegistry.getEditorCommand('cursorPageDown').runCommand(accessor, { pageSize: getPageSize(context) }); } }); registerAction2(class extends NotebookCellAction { constructor() { super({ id: NOTEBOOK_CURSOR_PAGEDOWN_SELECT_COMMAND_ID, title: localize('cursorPageDownSelect', "Cell Cursor Page Down Select"), keybinding: [ { when: ContextKeyExpr.and( NOTEBOOK_EDITOR_FOCUSED, ContextKeyExpr.has(InputFocusedContextKey), EditorContextKeys.editorTextFocus, ), primary: KeyMod.Shift | KeyCode.PageDown, weight: NOTEBOOK_EDITOR_WIDGET_ACTION_WEIGHT } ] }); } async runWithContext(accessor: ServicesAccessor, context: INotebookCellActionContext): Promise<void> { EditorExtensionsRegistry.getEditorCommand('cursorPageDownSelect').runCommand(accessor, { pageSize: getPageSize(context) }); } }); function getPageSize(context: INotebookCellActionContext) { const editor = context.notebookEditor; const layoutInfo = editor._getViewModel().layoutInfo; const lineHeight = layoutInfo?.fontInfo.lineHeight || 17; return Math.max(1, Math.floor((layoutInfo?.height || 0) / lineHeight) - 2); } Registry.as<IConfigurationRegistry>(ConfigurationExtensions.Configuration).registerConfiguration({ id: 'notebook', order: 100, type: 'object', 'properties': { 'notebook.navigation.allowNavigateToSurroundingCells': { type: 'boolean', default: true, markdownDescription: localize('notebook.navigation.allowNavigateToSurroundingCells', "When enabled cursor can navigate to the next/previous cell when the current cursor in the cell editor is at the first/last line.") } } });
the_stack
import { getLogger } from "../logging"; import { illegalCharactersRegex} from "./BridgedClient"; import { IrcClientConfig } from "../models/IrcClientConfig"; import { renderTemplate } from "../util/Template"; const log = getLogger("IrcServer"); const GROUP_ID_REGEX = /^\+\S+:\S+$/ export type MembershipSyncKind = "incremental"|"initial"; export interface IrcServerConfig { // These are determined to be always defined or possibly undefined // by the existence of the keys in IrcServer.DEFAULT_CONFIG. name?: string; port?: number; icon?: string; ca?: string; networkId?: string; ssl?: boolean; sslselfsign?: boolean; sasl?: boolean; tlsOptions?: Record<string, unknown>; password?: string; allowExpiredCerts?: boolean; additionalAddresses?: string[]; onlyAdditionalAddresses: boolean; dynamicChannels: { enabled: boolean; published: boolean; useHomeserverDirectory: boolean; createAlias: boolean; joinRule: "public"|"invite"; federate: boolean; aliasTemplate: string; whitelist: string[]; exclude: string[]; roomVersion?: string; groupId?: string; }; quitDebounce: { enabled: boolean; quitsPerSecond: number; delayMinMs: number; delayMaxMs: number; }; mappings: { [channel: string]: { roomIds: string[]; key?: string; }; }; modePowerMap?: {[mode: string]: number}; sendConnectionMessages: boolean; botConfig: { nick: string; joinChannelsIfNoUsers: boolean; enabled: boolean; password?: string; username: string; }; privateMessages: { enabled: boolean; exclude: string[]; federate: boolean; }; matrixClients: { userTemplate: string; displayName: string; joinAttempts: number; }; ircClients: { nickTemplate: string; maxClients: number; idleTimeout: number; reconnectIntervalMs: number; concurrentReconnectLimit: number; allowNickChanges: boolean; ipv6: { only: boolean; prefix?: string; }; lineLimit: number; userModes?: string; realnameFormat?: "mxid"|"reverse-mxid"; pingTimeoutMs: number; pingRateMs: number; kickOn: { channelJoinFailure: boolean; ircConnectionFailure: boolean; userQuit: boolean; } }; excludedUsers: Array< { regex: string; kickReason?: string; } >; membershipLists: { enabled: boolean; floodDelayMs: number; ignoreIdleOnStartup?: { enabled: true; idleForHours: number; exclude: string; }; global: { ircToMatrix: { initial: boolean; incremental: boolean; requireMatrixJoined: boolean; }; matrixToIrc: { initial: boolean; incremental: boolean; }; }; channels: { channel: string; ircToMatrix: { initial: boolean; incremental: boolean; requireMatrixJoined: boolean; }; }[]; rooms: { room: string; matrixToIrc: { initial: boolean; incremental: boolean; }; }[]; }; } /* * Represents a single IRC server from config.yaml */ export class IrcServer { private addresses: string[] = []; private groupIdValid = false; private excludedUsers: { regex: RegExp; kickReason?: string }[] = []; private idleUsersStartupExcludeRegex?: RegExp; private enforceReconnectInterval = true; /** * Construct a new IRC Server. * @constructor * @param {string} domain : The IRC network address * @param {Object} serverConfig : The config options for this network. * @param {string} homeserverDomain : The domain of the homeserver * e.g "matrix.org" * @param {number} expiryTimeSeconds : How old a matrix message can be * before it is considered 'expired' and not sent to IRC. If 0, messages * will never expire. */ constructor(public domain: string, public config: IrcServerConfig, private homeserverDomain: string, private expiryTimeSeconds: number = 0) { this.reconfigure(config, expiryTimeSeconds); } /** * Get how old a matrix message can be (in seconds) before it is considered * 'expired' and not sent to IRC. * @return {Number} The number of seconds. If 0, they never expire. */ public getExpiryTimeSeconds() { return this.expiryTimeSeconds; } /** * Get a string that represents the human-readable name for a server. * @return {string} this.config.name if truthy, otherwise it will return * an empty string. */ public getReadableName() { return this.config.name || ""; } /** * Get an icon to represent the network * The icon URL, if configured. */ public getIcon(): string|undefined { return this.config.icon; } /** * Return a randomised server domain from the default and additional addresses. * @return {string} */ public randomDomain() { return this.addresses[ Math.floor((Math.random() * 1000) % this.addresses.length) ]; } /** * Returns the network ID of this server, which should be unique across all * IrcServers on the bridge. Defaults to the domain of this IrcServer. * @return {string} this.config.networkId || this.domain */ public getNetworkId() { return this.config.networkId || this.domain; } /** * Returns whether the server is configured to wait getQuitDebounceDelayMs before * parting a user that has disconnected due to a net-split. * @return {Boolean} this.config.quitDebounce.enabled. */ public shouldDebounceQuits() { return this.config.quitDebounce.enabled; } /** * Get a random interval to delay a quits for when debouncing. Will be between * `delayMinMs` and `delayMaxMs` */ public getQuitDebounceDelay(): number { const { delayMaxMs, delayMinMs } = this.config.quitDebounce; return delayMinMs + ( delayMaxMs - delayMinMs ) * Math.random(); } /** * Get the rate of maximum quits received per second before a net-split is * detected. If the rate of quits received becomes higher that this value, * a net split is considered ongoing. * @return {number} */ public getDebounceQuitsPerSecond() { return this.config.quitDebounce.quitsPerSecond; } /** * Get a map that converts IRC user modes to Matrix power levels. * @return {Object} */ public getModePowerMap() { return this.config.modePowerMap || {}; } public getHardCodedRoomIds() { const roomIds = new Set<string>(); const channels = Object.keys(this.config.mappings); channels.forEach((chan) => { this.config.mappings[chan].roomIds.forEach((roomId) => { roomIds.add(roomId); }); }); return Array.from(roomIds.keys()); } public getChannelKey(channel: string) { return this.config.mappings[channel]?.key; } public shouldSendConnectionNotices() { return this.config.sendConnectionMessages; } public isBotEnabled() { return this.config.botConfig.enabled; } public getUserModes() { return this.config.ircClients.userModes || ""; } public getRealNameFormat(): "mxid"|"reverse-mxid" { return this.config.ircClients.realnameFormat || "mxid"; } public getJoinRule() { return this.config.dynamicChannels.joinRule; } public areGroupsEnabled() { return this.groupIdValid; } public getGroupId() { return this.config.dynamicChannels.groupId; } public shouldFederatePMs() { return this.config.privateMessages.federate; } public getMemberListFloodDelayMs() { return this.config.membershipLists.floodDelayMs; } public shouldFederate() { return this.config.dynamicChannels.federate; } public forceRoomVersion() { return this.config.dynamicChannels.roomVersion; } public getPort() { return this.config.port; } public isInWhitelist(userId: string) { return this.config.dynamicChannels.whitelist.includes(userId); } public getSecureOptions() { // Return an empty object here if not defined, as a falsy secure opts will disable SSL. return this.config.tlsOptions ?? {}; } public useSsl() { return Boolean(this.config.ssl); } public useSslSelfSigned() { return Boolean(this.config.sslselfsign); } public useSasl() { return Boolean(this.config.sasl); } public allowExpiredCerts() { return Boolean(this.config.allowExpiredCerts); } public getIdleTimeout() { return this.config.ircClients.idleTimeout; } public toggleReconnectInterval(enable: boolean) { this.enforceReconnectInterval = enable; } public getReconnectIntervalMs() { return this.enforceReconnectInterval ? this.config.ircClients.reconnectIntervalMs : 0; } public getConcurrentReconnectLimit() { return this.config.ircClients.concurrentReconnectLimit; } public getMaxClients() { return this.config.ircClients.maxClients; } public shouldPublishRooms() { return this.config.dynamicChannels.published; } public shouldPublishRoomsToHomeserverDirectory() { return this.config.dynamicChannels.useHomeserverDirectory; } public allowsNickChanges() { return this.config.ircClients.allowNickChanges; } public getBotNickname() { return this.config.botConfig.nick; } public createBotIrcClientConfig() { return IrcClientConfig.newConfig( null, this.domain, this.config.botConfig.nick, this.config.botConfig.username, this.config.botConfig.password ); } public getIpv6Prefix() { return this.config.ircClients.ipv6.prefix; } public getIpv6Only() { return this.config.ircClients.ipv6.only; } public getLineLimit() { return this.config.ircClients.lineLimit; } public getJoinAttempts() { return this.config.matrixClients.joinAttempts; } public isExcludedChannel(channel: string) { return this.config.dynamicChannels.exclude.includes(channel); } public isExcludedUser(userId: string) { return this.excludedUsers.find((exclusion) => { return exclusion.regex.exec(userId) !== null; }); } public get ignoreIdleUsersOnStartup() { return this.config.membershipLists.ignoreIdleOnStartup?.enabled; } public get ignoreIdleUsersOnStartupAfterMs() { return (this.config.membershipLists.ignoreIdleOnStartup?.idleForHours || 0) * 1000 * 60 * 60; } public get ignoreIdleUsersOnStartupExcludeRegex() { return this.idleUsersStartupExcludeRegex; } public get aliasTemplateHasHashPrefix() { return this.config.dynamicChannels.aliasTemplate.startsWith("#"); } /** * The amount of time to allow for inactivty on the connection, before considering the connection * dead. This usually happens if the IRCd doesn't ping us. */ public get pingTimeout() { return this.config.ircClients.pingTimeoutMs; } /** * The rate at which to send pings to the IRCd if the client is being quiet for a while. * Whilst the IRCd *should* be sending pings to us to keep the connection alive, it appears * that sometimes they don't get around to it and end up ping timing us out. */ public get pingRateMs() { return this.config.ircClients.pingRateMs; } public canJoinRooms(userId: string) { return ( this.config.dynamicChannels.enabled && (this.getJoinRule() === "public" || this.isInWhitelist(userId)) ); } // check if this server dynamically create rooms with aliases. public createsDynamicAliases() { return ( this.config.dynamicChannels.enabled && this.config.dynamicChannels.createAlias ); } // check if this server dynamically creates rooms which are joinable via an alias only. public createsPublicAliases() { return ( this.createsDynamicAliases() && this.getJoinRule() === "public" ); } public allowsPms() { return this.config.privateMessages.enabled; } public shouldSyncMembershipToIrc(kind: MembershipSyncKind, roomId?: string) { return this.shouldSyncMembership(kind, roomId, true); } public shouldSyncMembershipToMatrix(kind: MembershipSyncKind, channel: string) { return this.shouldSyncMembership(kind, channel, false); } private shouldSyncMembership(kind: MembershipSyncKind, identifier: string|undefined, toIrc: boolean) { if (!["incremental", "initial"].includes(kind)) { throw new Error("Bad kind: " + kind); } if (!this.config.membershipLists.enabled) { return false; } let shouldSync = this.config.membershipLists.global[ toIrc ? "matrixToIrc" : "ircToMatrix" ][kind]; if (!identifier) { return shouldSync; } // check for specific rules for the room id / channel if (toIrc) { // room rules clobber global rules this.config.membershipLists.rooms.forEach(function(r) { if (r.room === identifier && r.matrixToIrc) { shouldSync = r.matrixToIrc[kind]; } }); } else { // channel rules clobber global rules this.config.membershipLists.channels.forEach(function(chan) { if (chan.channel === identifier && chan.ircToMatrix) { shouldSync = chan.ircToMatrix[kind]; } }); } return shouldSync; } /** * Does the server/channel require all Matrix users to be joined? * @param channel The IRC channel. * @returns True if the server requires all Matrix users to be joined. */ public shouldRequireMatrixUserJoined(channel: string) { let shouldSync = this.config.membershipLists.global.ircToMatrix.requireMatrixJoined; this.config.membershipLists.channels.find((chan) => { if (chan.channel === channel) { if (typeof chan.ircToMatrix?.requireMatrixJoined === "boolean") { shouldSync = chan.ircToMatrix.requireMatrixJoined; } return true; } return false; }); return shouldSync; } public shouldJoinChannelsIfNoUsers() { return this.config.botConfig.joinChannelsIfNoUsers; } public isMembershipListsEnabled() { return this.config.membershipLists.enabled; } public getUserLocalpart(nick: string) { // the template is just a literal string with special vars; so find/replace // the vars and strip the @ return renderTemplate(this.config.matrixClients.userTemplate, { server: this.domain, nick, }).substring(1); // the first character is guaranteed by config schema to be '@' } public claimsUserId(userId: string) { // the server claims the given user ID if the ID matches the user ID template. const regex = IrcServer.templateToRegex( this.config.matrixClients.userTemplate, { "$SERVER": this.domain }, { "$NICK": "(.*)" }, ":" + IrcServer.escapeRegExp(this.homeserverDomain) ); return new RegExp(regex).test(userId); } public getNickFromUserId(userId: string) { // extract the nick from the given user ID const regex = IrcServer.templateToRegex( this.config.matrixClients.userTemplate, { "$SERVER": this.domain }, { "$NICK": "(.*?)" }, ":" + IrcServer.escapeRegExp(this.homeserverDomain) ); const match = new RegExp(regex).exec(userId); if (!match) { return null; } return match[1]; } public getUserIdFromNick(nick: string) { const template = this.config.matrixClients.userTemplate; return template.replace(/\$NICK/g, nick).replace(/\$SERVER/g, this.domain) + ":" + this.homeserverDomain; } public getDisplayNameFromNick(nick: string) { const template = this.config.matrixClients.displayName; let displayName = template.replace(/\$NICK/g, nick); displayName = displayName.replace(/\$SERVER/g, this.domain); return displayName; } public claimsAlias(alias: string) { // the server claims the given alias if the alias matches the alias template const regex = IrcServer.templateToRegex( this.config.dynamicChannels.aliasTemplate, { "$SERVER": this.domain }, { "$CHANNEL": "#(.*)" }, ":" + IrcServer.escapeRegExp(this.homeserverDomain) ); return new RegExp(regex).test(alias); } public getChannelFromAlias(alias: string) { // extract the channel from the given alias const regex = IrcServer.templateToRegex( this.config.dynamicChannels.aliasTemplate, { "$SERVER": this.domain }, { "$CHANNEL": "([^:]*)" }, ":" + IrcServer.escapeRegExp(this.homeserverDomain) ); const match = new RegExp(regex).exec(alias); if (!match) { return null; } log.info("getChannelFromAlias -> %s -> %s -> %s", alias, regex, match[1]); return match[1]; } public getAliasFromChannel(channel: string) { if (!channel.startsWith("#") && !this.aliasTemplateHasHashPrefix) { throw Error('Cannot get an alias for a channel not starting with a hash'); } const alias = renderTemplate(this.config.dynamicChannels.aliasTemplate, { channel, server: this.domain, }); return alias + ":" + this.homeserverDomain; } public getNick(userId: string, displayName?: string) { let localpart = userId.substring(1).split(":")[0]; localpart = localpart.replace(illegalCharactersRegex, ""); displayName = displayName ? displayName.replace(illegalCharactersRegex, "") : undefined; const display = [displayName, localpart].find((n) => Boolean(n)); if (!display) { throw new Error("Could not get nick for user, all characters were invalid"); } return renderTemplate(this.config.ircClients.nickTemplate, { userId, localpart, display }); } public getAliasRegex() { return IrcServer.templateToRegex( this.config.dynamicChannels.aliasTemplate, { "$SERVER": this.domain // find/replace $server }, { "$CHANNEL": ".*" // the nick is unknown, so replace with a wildcard }, // Only match the domain of the HS ":" + IrcServer.escapeRegExp(this.homeserverDomain) ); } public getUserRegex() { return IrcServer.templateToRegex( this.config.matrixClients.userTemplate, { "$SERVER": this.domain // find/replace $server }, { "$NICK": ".*" // the nick is unknown, so replace with a wildcard }, // Only match the domain of the HS ":" + IrcServer.escapeRegExp(this.homeserverDomain) ); } public static get DEFAULT_CONFIG(): IrcServerConfig { return { sendConnectionMessages: true, onlyAdditionalAddresses: false, quitDebounce: { enabled: false, quitsPerSecond: 5, delayMinMs: 3600000, // 1h delayMaxMs: 7200000, // 2h }, botConfig: { nick: "appservicebot", username: "matrixbot", joinChannelsIfNoUsers: true, enabled: true }, privateMessages: { enabled: true, exclude: [], federate: true }, dynamicChannels: { enabled: false, published: true, useHomeserverDirectory: false, createAlias: true, joinRule: "public", federate: true, aliasTemplate: "#irc_$SERVER_$CHANNEL", whitelist: [], exclude: [] }, mappings: {}, excludedUsers: [], matrixClients: { userTemplate: "@$SERVER_$NICK", displayName: "$NICK (IRC)", joinAttempts: -1, }, ircClients: { nickTemplate: "M-$DISPLAY", maxClients: 30, idleTimeout: 172800, reconnectIntervalMs: 5000, concurrentReconnectLimit: 50, allowNickChanges: false, ipv6: { only: false }, lineLimit: 3, pingTimeoutMs: 1000 * 60 * 10, pingRateMs: 1000 * 60, kickOn: { ircConnectionFailure: true, channelJoinFailure: true, userQuit: true } }, membershipLists: { enabled: false, floodDelayMs: 10000, // 10s global: { ircToMatrix: { initial: false, incremental: false, requireMatrixJoined: false, }, matrixToIrc: { initial: false, incremental: false } }, channels: [], rooms: [] } } } public reconfigure(config: IrcServerConfig, expiryTimeSeconds = 0) { log.info(`Reconfiguring ${this.domain}`); if (config.ca) { log.warn("** The IrcServer.ca is now deprecated, please use tlsOptions.ca. **"); config.tlsOptions = { ...config.tlsOptions, ca: config.ca, }; } this.config = config; this.expiryTimeSeconds = expiryTimeSeconds; // This ensures that legacy mappings still work, but we prod the user to update. const stringMappings = Object.entries(config.mappings || {}).filter(([, data]) => { return Array.isArray(data); }) as unknown as [string, string[]][]; if (stringMappings.length) { log.warn("** The IrcServer.mappings config schema has changed, allowing legacy format for now. **"); log.warn("See https://github.com/matrix-org/matrix-appservice-irc/blob/master/CHANGELOG.md for details"); for (const [channelId, roomIds] of stringMappings) { config.mappings[channelId] = { roomIds: roomIds } } } if (!this.aliasTemplateHasHashPrefix) { if (this.config.dynamicChannels.aliasTemplate !== "$CHANNEL") { throw Error( "If no hash prefix is given in 'aliasTemplate', then the aliasTemplate must be exactly '$CHANNEL'" ); } log.warn("You have configured your aliasTemplate to not include a prefix hash. This means that only " + "channels starting with a hash are supported by the bridge.") } this.addresses = config.additionalAddresses || []; // Don't include the original domain if not configured to. if (!config.onlyAdditionalAddresses) { this.addresses.push(this.domain); } else if (this.addresses.length === 0) { throw Error("onlyAdditionalAddresses is true, but no additional addresses are provided in the config"); } this.excludedUsers = config.excludedUsers.map((excluded) => { return { ...excluded, regex: new RegExp(excluded.regex) } }); if (config.dynamicChannels.groupId !== undefined && config.dynamicChannels.groupId.trim() !== "") { this.groupIdValid = GROUP_ID_REGEX.test(config.dynamicChannels.groupId); if (!this.groupIdValid) { log.warn( `${this.domain} has an incorrectly configured groupId for dynamicChannels and will not set groups.` ); } } else { this.groupIdValid = false; } this.idleUsersStartupExcludeRegex = this.config.membershipLists.ignoreIdleOnStartup?.exclude ? new RegExp(this.config.membershipLists.ignoreIdleOnStartup.exclude) : undefined; } private static templateToRegex(template: string, literalVars: {[key: string]: string}, regexVars: {[key: string]: string}, suffix: string) { // The 'template' is a literal string with some special variables which need // to be find/replaced. let regex = template; Object.keys(literalVars).forEach(function(varPlaceholder) { regex = regex.replace( new RegExp(IrcServer.escapeRegExp(varPlaceholder), 'g'), literalVars[varPlaceholder] ); }); // at this point the template is still a literal string, so escape it before // applying the regex vars. regex = IrcServer.escapeRegExp(regex); // apply regex vars Object.keys(regexVars).forEach(function(varPlaceholder) { regex = regex.replace( // double escape, because we bluntly escaped the entire string before // so our match is now escaped. new RegExp(IrcServer.escapeRegExp(IrcServer.escapeRegExp(varPlaceholder)), 'g'), regexVars[varPlaceholder] ); }); suffix = suffix || ""; return regex + suffix; } private static escapeRegExp(s: string) { // https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } }
the_stack
import { loggerSpy } from '../testhelpers/loggerSpy'; import { importSingleText } from '../testhelpers/importSingleText'; import { assertAddElementRule, assertAssignmentRule, assertBindingRule, assertCardRule, assertCaretValueRule, assertContainsRule, assertFlagRule, assertInsertRule, assertObeysRule, assertOnlyRule } from '../testhelpers'; import { FshCode } from '../../src/fshtypes'; import { leftAlign } from '../utils/leftAlign'; import { importText, RawFSH } from '../../src/import'; describe('FSHImporter', () => { beforeEach(() => loggerSpy.reset()); describe('Logical', () => { describe('#sdMetadata', () => { it('should parse the simplest possible logical model', () => { const input = ` Logical: MyLogicalModel `; const result = importSingleText(input, 'Simple.fsh'); expect(result.logicals.size).toBe(1); const logical = result.logicals.get('MyLogicalModel'); expect(logical.name).toBe('MyLogicalModel'); expect(logical.parent).toBe('Base'); // if no id is explicitly set, should default to name expect(logical.id).toBe('MyLogicalModel'); expect(logical.sourceInfo.location).toEqual({ startLine: 2, startColumn: 9, endLine: 2, endColumn: 31 }); expect(logical.sourceInfo.file).toBe('Simple.fsh'); }); it('should parse logical model with name matching various possible tokens recognized as name', () => { // This basically exercises all the tokens we accept for name: // SEQUENCE | NUMBER | KW_MS | KW_SU | KW_TU | KW_NORMATIVE | KW_DRAFT | KW_CODES | KW_VSREFERENCE | KW_SYSTEM | KW_UNITS; // Since we'll do the same thing over and over (and over), create a function for it const testToken = (token: string) => { const input = leftAlign(` Logical: ${token} Parent: BaseObservationModel * value[x] only boolean `); const result = importSingleText(input); expect(loggerSpy.getAllLogs('error')).toHaveLength(0); expect(result).toBeDefined(); expect(result.logicals.size).toBe(1); const logical = result.logicals.get(token); expect(logical).toBeDefined(); expect(logical.name).toBe(token); }; testToken('MyLogical'); // SEQUENCE testToken('123'); // NUMBER testToken('MS'); // KW_MS testToken('SU'); // KW_SU testToken('TU'); // KW_TU testToken('N'); // KW_NORMATIVE testToken('D'); // KW_DRAFT testToken('codes'); // KW_CODES testToken('valueset'); // KW_VSREFERENCE testToken('system'); // KW_SYSTEM testToken('units'); // KW_UNITS }); it('should log an error when encountering the mixins metadata attribute', () => { const input = ` Logical: TestWithMixins Mixins: Mixin1 and Mixin2 and Mixin3 and Mixin4 `; importSingleText(input, 'TestWithMixins.fsh'); expect(loggerSpy.getLastMessage('error')).toMatch(/File: TestWithMixins\.fsh.*Line: 3\D*/s); }); it('should parse logical model with additional metadata properties', () => { const input = ` Logical: MyObservationModel Parent: BaseObservationModel Id: observation-model Title: "An Observation-based Logical Model" Description: "A logical model based on Observation" `; const result = importSingleText(input); expect(result.logicals.size).toBe(1); const logical = result.logicals.get('MyObservationModel'); expect(logical.name).toBe('MyObservationModel'); expect(logical.parent).toBe('BaseObservationModel'); expect(logical.id).toBe('observation-model'); expect(logical.title).toBe('An Observation-based Logical Model'); expect(logical.description).toBe('A logical model based on Observation'); expect(logical.sourceInfo.location).toEqual({ startLine: 2, startColumn: 9, endLine: 6, endColumn: 59 }); }); it('should parse logical model with numeric name, parent, and id', () => { const input = ` Logical: 123 Parent: 456 Id: 789 `; const result = importSingleText(input); expect(result.logicals.size).toBe(1); const logical = result.logicals.get('123'); expect(logical.name).toBe('123'); expect(logical.parent).toBe('456'); expect(logical.id).toBe('789'); }); it('should properly parse a multi-string description', () => { const input = ` Logical: MyObservationModel Parent: BaseObservationModel Description: """ This is a multi-string description with a couple of paragraphs. This is the second paragraph. It has bullet points w/ indentation: * Bullet 1 * Bullet A * Bullet B * Bullet i * Bullet C * Bullet 2 """ `; const result = importSingleText(input); expect(result.logicals.size).toBe(1); const logical = result.logicals.get('MyObservationModel'); const expectedDescriptionLines = [ 'This is a multi-string description', 'with a couple of paragraphs.', '', 'This is the second paragraph. It has bullet points w/ indentation:', '', '* Bullet 1', ' * Bullet A', ' * Bullet B', ' * Bullet i', ' * Bullet C', '* Bullet 2' ]; expect(logical.description).toBe(expectedDescriptionLines.join('\n')); }); it('should accept and translate an alias for the parent', () => { const input = ` Alias: OBS = http://example.com/fhir/StructureDefinition/BaseObservationModel Logical: MyObservationModel Parent: OBS `; const result = importSingleText(input); expect(result.logicals.size).toBe(1); const logical = result.logicals.get('MyObservationModel'); expect(logical.name).toBe('MyObservationModel'); expect(logical.parent).toBe( 'http://example.com/fhir/StructureDefinition/BaseObservationModel' ); }); it('should only apply each metadata attribute the first time it is declared', () => { const input = ` Logical: MyObservationModel Parent: BaseObservationModel Id: observation-model Title: "An Observation-based Logical Model" Description: "A logical model based on Observation" Parent: DuplicateBaseObservationModel Id: duplicate-observation-model Title: "Duplicate Observation-based Logical Model" Description: "Duplicate logical model based on Observation" `; const result = importSingleText(input); expect(result.logicals.size).toBe(1); const logical = result.logicals.get('MyObservationModel'); expect(logical.name).toBe('MyObservationModel'); expect(logical.parent).toBe('BaseObservationModel'); expect(logical.id).toBe('observation-model'); expect(logical.title).toBe('An Observation-based Logical Model'); expect(logical.description).toBe('A logical model based on Observation'); }); it('should log an error when encountering a duplicate metadata attribute', () => { const input = ` Logical: MyObservationModel Parent: BaseObservationModel Id: observation-model Title: "An Observation-based Logical Model" Description: "A logical model based on Observation" Parent: DuplicateBaseObservationModel Id: duplicate-observation-model Title: "Duplicate Observation-based Logical Model" Description: "Duplicate logical model based on Observation" `; importSingleText(input, 'Dupe.fsh'); expect(loggerSpy.getMessageAtIndex(-4, 'error')).toMatch(/File: Dupe\.fsh.*Line: 7\D*/s); expect(loggerSpy.getMessageAtIndex(-3, 'error')).toMatch(/File: Dupe\.fsh.*Line: 8\D*/s); expect(loggerSpy.getMessageAtIndex(-2, 'error')).toMatch(/File: Dupe\.fsh.*Line: 9\D*/s); expect(loggerSpy.getLastMessage('error')).toMatch(/File: Dupe\.fsh.*Line: 10\D*/s); }); it('should log an error and skip the logical model when encountering a logical model with a name used by another logical model', () => { const input = ` Logical: MyObservationModel Parent: BaseObservationModel Title: "An Observation-based Logical Model" Logical: MyObservationModel Parent: BaseObservationModel Title: "Second Observation-based Logical Model" `; const result = importSingleText(input, 'SameName.fsh'); expect(result.logicals.size).toBe(1); const logical = result.logicals.get('MyObservationModel'); expect(logical.title).toBe('An Observation-based Logical Model'); expect(loggerSpy.getLastMessage('error')).toMatch( /Logical Model named MyObservationModel already exists/s ); expect(loggerSpy.getLastMessage('error')).toMatch(/File: SameName\.fsh.*Line: 6 - 8\D*/s); }); it('should log an error and skip the logical when encountering an logical with a name used by another logical in another file', () => { const input1 = ` Logical: MyObservationModel Parent: BaseObservationModel Title: "An Observation-based Logical Model" `; const input2 = ` Logical: MyObservationModel Parent: BaseObservationModel Title: "Second Observation-based Logical Model" `; const result = importText([ new RawFSH(input1, 'File1.fsh'), new RawFSH(input2, 'File2.fsh') ]); expect(result.reduce((sum, d2) => sum + d2.logicals.size, 0)).toBe(1); const l = result[0].logicals.get('MyObservationModel'); expect(l.title).toBe('An Observation-based Logical Model'); expect(loggerSpy.getLastMessage('error')).toMatch( /Logical Model named MyObservationModel already exists/s ); expect(loggerSpy.getLastMessage('error')).toMatch(/File: File2\.fsh.*Line: 2 - 4\D*/s); }); }); // Tests for all supported rules are in FSHImporter.SDRules.test.ts // Since Logicals use the same rule parsing code as other StructureDefinitions, only do minimal tests of rules describe('#cardRule', () => { it('should parse simple card rules', () => { const input = ` Logical: LogicalModel * category 1..5 * value[x] 1..1 * component 2..* `; const result = importSingleText(input); const logical = result.logicals.get('LogicalModel'); expect(logical.rules).toHaveLength(3); assertCardRule(logical.rules[0], 'category', 1, 5); assertCardRule(logical.rules[1], 'value[x]', 1, 1); assertCardRule(logical.rules[2], 'component', 2, '*'); }); it('should parse card rules w/ multiple flags', () => { const input = ` Logical: LogicalModel * category 1..5 MS ?! TU * value[x] 1..1 ?! SU N * component 2..* SU MS D `; const result = importSingleText(input); const logical = result.logicals.get('LogicalModel'); expect(logical.rules).toHaveLength(6); assertCardRule(logical.rules[0], 'category', 1, 5); assertFlagRule( logical.rules[1], 'category', true, undefined, true, true, undefined, undefined ); assertCardRule(logical.rules[2], 'value[x]', 1, 1); assertFlagRule( logical.rules[3], 'value[x]', undefined, true, true, undefined, true, undefined ); assertCardRule(logical.rules[4], 'component', 2, '*'); assertFlagRule( logical.rules[5], 'component', true, true, undefined, undefined, undefined, true ); }); }); describe('#flagRule', () => { it('should parse single-path single-value flag rules', () => { const input = ` Logical: LogicalModel * category MS * value[x] ?! * component SU * interpretation TU * note N * bodySite D `; const result = importSingleText(input); const logical = result.logicals.get('LogicalModel'); expect(logical.rules).toHaveLength(6); assertFlagRule( logical.rules[0], 'category', true, undefined, undefined, undefined, undefined, undefined ); assertFlagRule( logical.rules[1], 'value[x]', undefined, undefined, true, undefined, undefined, undefined ); assertFlagRule( logical.rules[2], 'component', undefined, true, undefined, undefined, undefined, undefined ); assertFlagRule( logical.rules[3], 'interpretation', undefined, undefined, undefined, true, undefined, undefined ); assertFlagRule( logical.rules[4], 'note', undefined, undefined, undefined, undefined, true, undefined ); assertFlagRule( logical.rules[5], 'bodySite', undefined, undefined, undefined, undefined, undefined, true ); }); }); describe('#BindingRule', () => { it('should parse value set rules w/ names and strengths', () => { const input = ` Logical: LogicalModel * category from CategoryValueSet (required) * code from CodeValueSet (extensible) * valueCodeableConcept from ValueValueSet (preferred) * component.code from ComponentCodeValueSet (example) `; const result = importSingleText(input); const logical = result.logicals.get('LogicalModel'); expect(logical.rules).toHaveLength(4); assertBindingRule(logical.rules[0], 'category', 'CategoryValueSet', 'required'); assertBindingRule(logical.rules[1], 'code', 'CodeValueSet', 'extensible'); assertBindingRule(logical.rules[2], 'valueCodeableConcept', 'ValueValueSet', 'preferred'); assertBindingRule(logical.rules[3], 'component.code', 'ComponentCodeValueSet', 'example'); }); }); describe('#assignmentRule', () => { it('should parse assigned value boolean rule', () => { const input = ` Logical: LogicalModel * valueBoolean = true `; const result = importSingleText(input); const logical = result.logicals.get('LogicalModel'); expect(logical.rules).toHaveLength(1); assertAssignmentRule(logical.rules[0], 'valueBoolean', true); }); it('should parse assigned value boolean rule with (exactly) modifier', () => { const input = ` Logical: LogicalModel * valueBoolean = true (exactly) `; const result = importSingleText(input); const logical = result.logicals.get('LogicalModel'); expect(logical.rules).toHaveLength(1); assertAssignmentRule(logical.rules[0], 'valueBoolean', true, true); }); }); describe('#onlyRule', () => { it('should parse an only rule with one type', () => { const input = ` Logical: LogicalModel * value[x] only Quantity `; const result = importSingleText(input); const logical = result.logicals.get('LogicalModel'); expect(logical.rules).toHaveLength(1); assertOnlyRule(logical.rules[0], 'value[x]', { type: 'Quantity' }); }); }); describe('#containsRule', () => { it('should parse contains rule with one item', () => { const input = ` Logical: LogicalModel * component contains SystolicBP 1..1 `; const result = importSingleText(input); const logical = result.logicals.get('LogicalModel'); expect(logical.rules).toHaveLength(2); assertContainsRule(logical.rules[0], 'component', 'SystolicBP'); assertCardRule(logical.rules[1], 'component[SystolicBP]', 1, 1); }); it('should parse contains rule with one item declaring an aliased type', () => { const input = ` Alias: OffsetExtension = http://hl7.org/fhir/StructureDefinition/observation-timeOffset Logical: LogicalModel * component.extension contains OffsetExtension named offset 0..1 `; const result = importSingleText(input); const logical = result.logicals.get('LogicalModel'); expect(logical.rules).toHaveLength(2); assertContainsRule(logical.rules[0], 'component.extension', { name: 'offset', type: 'http://hl7.org/fhir/StructureDefinition/observation-timeOffset' }); assertCardRule(logical.rules[1], 'component.extension[offset]', 0, 1); }); }); describe('#caretValueRule', () => { it('should parse caret value rules with a path', () => { const input = ` Logical: LogicalModel * status ^short = "foo" * status ^sliceIsConstraining = false * status ^code[0] = foo#bar "baz" `; const result = importSingleText(input); const logical = result.logicals.get('LogicalModel'); assertCaretValueRule(logical.rules[0], 'status', 'short', 'foo', false); assertCaretValueRule(logical.rules[1], 'status', 'sliceIsConstraining', false, false); assertCaretValueRule( logical.rules[2], 'status', 'code[0]', new FshCode('bar', 'foo', 'baz').withLocation([5, 29, 5, 41]).withFile(''), false ); }); }); describe('#obeysRule', () => { it('should parse an obeys rule with multiple invariants and a path', () => { const input = ` Logical: LogicalModel * category obeys SomeInvariant and ThisInvariant and ThatInvariant `; const result = importSingleText(input, 'Obeys.fsh'); const logical = result.logicals.get('LogicalModel'); expect(logical.rules).toHaveLength(3); assertObeysRule(logical.rules[0], 'category', 'SomeInvariant'); assertObeysRule(logical.rules[1], 'category', 'ThisInvariant'); assertObeysRule(logical.rules[2], 'category', 'ThatInvariant'); }); }); describe('#insertRule', () => { it('should parse an insert rule with a single RuleSet', () => { const input = ` Logical: LogicalModel * insert MyRuleSet `; const result = importSingleText(input, 'Insert.fsh'); const logical = result.logicals.get('LogicalModel'); expect(logical.rules).toHaveLength(1); assertInsertRule(logical.rules[0], '', 'MyRuleSet'); }); }); describe('#addElementRule', () => { it('should parse complete add element rules', () => { const input = ` Logical: LogicalModel * isValid 1..1 MS boolean "is it valid?" * stuff 0..* string "just stuff" "a list of some stuff" * address 1..* Address `; const result = importSingleText(input); const logical = result.logicals.get('LogicalModel'); expect(logical.rules).toHaveLength(3); assertAddElementRule(logical.rules[0], 'isValid', { card: { min: 1, max: '1' }, flags: { mustSupport: true }, types: [{ type: 'boolean' }], defs: { short: 'is it valid?' } }); assertAddElementRule(logical.rules[1], 'stuff', { card: { min: 0, max: '*' }, types: [{ type: 'string' }], defs: { short: 'just stuff', definition: 'a list of some stuff' } }); assertAddElementRule(logical.rules[2], 'address', { card: { min: 1, max: '*' }, types: [{ type: 'Address' }] }); }); it('should log a warning when a data type is defined with a flag value', () => { const input = ` Logical: LogicalModel * isValid 1..1 MS boolean "is it valid?" * stuff 0..* N "just stuff" "a list of some stuff" * address 1..* Address `; const result = importSingleText(input, 'WarnDataType.fsh'); const logical = result.logicals.get('LogicalModel'); expect(logical.rules).toHaveLength(3); assertAddElementRule(logical.rules[0], 'isValid', { card: { min: 1, max: '1' }, flags: { mustSupport: true }, types: [{ type: 'boolean' }], defs: { short: 'is it valid?' } }); assertAddElementRule(logical.rules[1], 'stuff', { card: { min: 0, max: '*' }, types: [{ type: 'N' }], defs: { short: 'just stuff', definition: 'a list of some stuff' } }); assertAddElementRule(logical.rules[2], 'address', { card: { min: 1, max: '*' }, types: [{ type: 'Address' }] }); expect(loggerSpy.getLastMessage('warn')).toMatch( /The targetType 'N' appears to be a flag value rather than a valid target data type./s ); }); }); }); });
the_stack
namespace gdjs { declare var admob: any; export namespace adMob { export enum AdSizeType { BANNER, LARGE_BANNER, MEDIUM_RECTANGLE, FULL_BANNER, LEADERBOARD, SMART_BANNER, } // Banner let bannerAndroidId = ''; let bannerIosId = ''; let bannerPosition: 'top' | 'bottom' = 'top'; let bannerRequestedAdSizeType: AdSizeType = AdSizeType.SMART_BANNER; let bannerLoading = false; let bannerErrored = false; let bannerShowing = false; // Interstitial let interstitialLoading = false; let interstitialReady = false; let interstitialErrored = false; let interstitialShowing = false; // Reward video let videoLoading = false; let videoReady = false; let videoErrored = false; let videoShowing = false; let videoRewardReceived = false; let npaValue = '0'; // TODO: expose an API to change this and also an automatic way using the consent SDK. /** * Activate or deactivate the test mode ("development" mode). * When activated, tests ads will be served instead of real ones. * * It is important to enable test ads during development so that you can click on them without * charging advertisers. If you click on too many ads without being in test mode, you risk your * account being flagged for invalid activity. */ export const setTestMode = (enable: boolean) => { if (typeof admob === 'undefined') { return; } admob.setDevMode(enable); }; // Banner /** Check if a banner is loading. */ export const isBannerLoading = () => { return bannerLoading; }; /** Check if a banner is being shown on screen. */ export const isBannerShowing = () => { return bannerShowing; }; /** Check if the banner had an error while loading it. */ export const isBannerErrored = () => { return bannerErrored; }; /** * Set up a banner that can then be displayed by calling `showBanner`. */ export const setupBanner = function (androidID, iosID, atTop) { if (typeof admob === 'undefined') { return; } bannerAndroidId = androidID; bannerIosId = iosID; bannerPosition = atTop ? 'top' : 'bottom'; }; /** * Set the size of the banner to be shown when `showBanner` is called. * @param bannerAdSizeType The type of the banner to displayed */ export const setBannerAdSizeType = ( bannerAdSizeType: | 'BANNER' | 'LARGE_BANNER' | 'MEDIUM_RECTANGLE' | 'FULL_BANNER' | 'LEADERBOARD' | 'SMART_BANNER' ) => { const adSizeTypes = { BANNER: AdSizeType.BANNER, LARGE_BANNER: AdSizeType.LARGE_BANNER, MEDIUM_RECTANGLE: AdSizeType.MEDIUM_RECTANGLE, FULL_BANNER: AdSizeType.FULL_BANNER, LEADERBOARD: AdSizeType.LEADERBOARD, SMART_BANNER: AdSizeType.SMART_BANNER, }; bannerRequestedAdSizeType = adSizeTypes[bannerAdSizeType] || AdSizeType.SMART_BANNER; }; /** * Display the banner that was set up with `loadBanner` (and `setBannerAdSizeType`). */ export const showBanner = () => { if (typeof admob === 'undefined') { return; } bannerLoading = true; bannerShowing = false; bannerErrored = false; admob.banner .show({ id: { android: bannerAndroidId, ios: bannerIosId, }, position: bannerPosition, size: bannerRequestedAdSizeType, }) .then( () => { bannerShowing = true; bannerLoading = false; console.info('AdMob banner successfully shown.'); }, (error) => { bannerShowing = false; bannerLoading = false; bannerErrored = true; console.error('Error while showing an AdMob banner:', error); } ); }; /** Hide the banner shown on screen. */ export const hideBanner = () => { if (typeof admob === 'undefined') { return; } bannerShowing = false; admob.banner.hide({ android: bannerAndroidId, ios: bannerIosId, }); }; // Interstitial /** Check if the interstitial is loading. */ export const isInterstitialLoading = () => { return interstitialLoading; }; /** Check if the interstitial is ready to display. */ export const isInterstitialReady = () => { return interstitialReady; }; /** Check if the interstitial is shown on screen. */ export const isInterstitialShowing = () => { return interstitialShowing; }; /** Check if the interstitial had an error while loading it. */ export const isInterstitialErrored = () => { return interstitialErrored; }; /** Load an interstitial. */ export const loadInterstitial = (androidID, iosID, displayWhenLoaded) => { if (typeof admob === 'undefined') { return; } if (interstitialLoading || interstitialReady || interstitialShowing) { return; } interstitialLoading = true; interstitialReady = false; interstitialErrored = false; admob.interstitial .load({ id: { android: androidID, ios: iosID, }, npa: npaValue, }) .then( () => { console.info('AdMob interstitial successfully loaded.'); if (displayWhenLoaded) showInterstitial(); }, (error) => { interstitialLoading = false; interstitialReady = false; interstitialErrored = true; console.error('Error while loading a interstitial:', error); } ); }; /** Show the loaded interstitial. */ export const showInterstitial = () => { if (typeof admob === 'undefined') { return; } admob.interstitial.show().then( () => { // Interstitial will be shown and // `interstitialShowing` will be updated thanks to events // (but it's too early to change it now). }, (error) => { interstitialShowing = false; interstitialErrored = true; console.error('Error while trying to show an interstitial:', error); } ); }; // Reward video /** Check if the video is loading. */ export const isVideoLoading = () => { return videoLoading; }; /** Check if the video is ready to display. */ export const isVideoReady = () => { return videoReady; }; /** Check if the video is shown on screen. */ export const isVideoShowing = () => { return videoShowing; }; /** Check if the video had an error while loading it. */ export const isVideoErrored = () => { return videoErrored; }; /** Check if the reward of the video was received. */ export const wasVideoRewardReceived = function (markAsClaimed) { const reward = videoRewardReceived; if (markAsClaimed) { videoRewardReceived = false; } return reward; }; /** Load a reward video. */ export const loadVideo = function (androidID, iosID, displayWhenLoaded) { if (typeof admob === 'undefined') { return; } if (videoLoading || videoReady || videoShowing) { return; } videoLoading = true; videoReady = false; videoErrored = false; admob.rewardVideo .load({ id: { android: androidID, ios: iosID, }, npa: npaValue, }) .then( () => { console.info('AdMob reward video successfully loaded.'); if (displayWhenLoaded) showVideo(); }, (error) => { videoLoading = false; videoReady = false; videoErrored = true; console.error('Error while loading a reward video:', error); } ); }; /** Show the loaded reward video. */ export const showVideo = () => { if (typeof admob === 'undefined') { return; } admob.rewardVideo.show().then( () => { // Video will be shown and // `videoShowing` will be updated thanks to events // (but it's too early to change it now). }, (error) => { videoShowing = false; videoErrored = true; console.error('Error while trying to show a reward video:', error); } ); }; /** Mark the reward of the video as claimed. */ export const markVideoRewardAsClaimed = () => { videoRewardReceived = false; }; // Banner event listeners: document.addEventListener('admob.banner.load', () => { bannerShowing = true; bannerLoading = false; }); document.addEventListener('admob.banner.load_fail', () => { bannerLoading = false; }); document.addEventListener('admob.banner.open', () => { // Not implemented. }); document.addEventListener('admob.banner.exit_app', () => { // Not implemented. }); document.addEventListener('admob.banner.close', () => { // Not implemented. }); // Interstitial event listeners document.addEventListener('admob.interstitial.load', () => { interstitialReady = true; interstitialLoading = false; }); document.addEventListener('admob.interstitial.load_fail', () => { interstitialLoading = false; }); document.addEventListener('admob.interstitial.open', () => { interstitialShowing = true; interstitialReady = false; }); document.addEventListener('admob.interstitial.close', () => { interstitialShowing = false; }); document.addEventListener('admob.interstitial.exit_app', () => { // Not implemented. }); // Reward video event listeners document.addEventListener('admob.reward_video.load', () => { videoReady = true; videoLoading = false; }); document.addEventListener('admob.reward_video.load_fail', () => { videoLoading = false; }); document.addEventListener('admob.reward_video.open', () => { videoShowing = true; videoReady = false; }); document.addEventListener('admob.reward_video.close', () => { videoShowing = false; }); document.addEventListener('admob.reward_video.start', () => { // Not implemented. }); document.addEventListener('admob.reward_video.complete', () => { // Not implemented. }); document.addEventListener('admob.reward_video.reward', () => { videoRewardReceived = true; }); document.addEventListener('admob.reward_video.exit_app', () => { // Not implemented. }); } }
the_stack
import { CfnResource, IConstruct } from '@aws-cdk/core'; import { NagPack, NagMessageLevel, NagPackProps } from '../nag-pack'; import { APIGWCacheEnabledAndEncrypted, APIGWExecutionLoggingEnabled, APIGWSSLEnabled, APIGWXrayEnabled, } from '../rules/apigw'; import { AutoScalingGroupELBHealthCheckRequired, AutoScalingLaunchConfigPublicIpDisabled, } from '../rules/autoscaling'; import { CloudTrailCloudWatchLogsEnabled, CloudTrailEncryptionEnabled, CloudTrailLogFileValidationEnabled, } from '../rules/cloudtrail'; import { CloudWatchAlarmAction, CloudWatchLogGroupEncrypted, CloudWatchLogGroupRetentionPeriod, } from '../rules/cloudwatch'; import { CodeBuildProjectEnvVarAwsCred, CodeBuildProjectSourceRepoUrl, } from '../rules/codebuild'; import { DMSReplicationNotPublic } from '../rules/dms'; import { DynamoDBAutoScalingEnabled, DynamoDBInBackupPlan, DynamoDBPITREnabled, } from '../rules/dynamodb'; import { EC2EBSInBackupPlan, EC2EBSOptimizedInstance, EC2InstanceDetailedMonitoringEnabled, EC2InstanceNoPublicIp, EC2InstanceProfileAttached, EC2InstancesInVPC, EC2RestrictedCommonPorts, EC2RestrictedSSH, } from '../rules/ec2'; import { ECSTaskDefinitionUserForHostMode } from '../rules/ecs'; import { EFSEncrypted, EFSInBackupPlan } from '../rules/efs'; import { ElastiCacheRedisClusterAutomaticBackup } from '../rules/elasticache'; import { ElasticBeanstalkEnhancedHealthReportingEnabled, ElasticBeanstalkManagedUpdatesEnabled, } from '../rules/elasticbeanstalk'; import { ALBHttpDropInvalidHeaderEnabled, ALBHttpToHttpsRedirection, ELBACMCertificateRequired, ELBCrossZoneLoadBalancingEnabled, ELBDeletionProtectionEnabled, ELBLoggingEnabled, ELBTlsHttpsListenersOnly, ELBv2ACMCertificateRequired, } from '../rules/elb'; import { EMRKerberosEnabled } from '../rules/emr'; import { IAMGroupHasUsers, IAMNoInlinePolicy, IAMPolicyNoStatementsWithAdminAccess, IAMPolicyNoStatementsWithFullAccess, IAMUserGroupMembership, IAMUserNoPolicies, } from '../rules/iam'; import { LambdaConcurrency, LambdaDLQ, LambdaInsideVPC } from '../rules/lambda'; import { OpenSearchEncryptedAtRest, OpenSearchErrorLogsToCloudWatch, OpenSearchInVPCOnly, OpenSearchNodeToNodeEncryption, } from '../rules/opensearch'; import { RDSAutomaticMinorVersionUpgradeEnabled, RDSEnhancedMonitoringEnabled, RDSInBackupPlan, RDSInstanceBackupEnabled, RDSInstanceDeletionProtectionEnabled, RDSMultiAZSupport, RDSInstancePublicAccess, RDSLoggingEnabled, RDSStorageEncrypted, } from '../rules/rds'; import { RedshiftBackupEnabled, RedshiftClusterConfiguration, RedshiftClusterMaintenanceSettings, RedshiftClusterPublicAccess, RedshiftEnhancedVPCRoutingEnabled, RedshiftRequireTlsSSL, } from '../rules/redshift'; import { S3BucketLevelPublicAccessProhibited, S3BucketLoggingEnabled, S3BucketPublicReadProhibited, S3BucketPublicWriteProhibited, S3BucketReplicationEnabled, S3BucketServerSideEncryptionEnabled, S3BucketSSLRequestsOnly, S3BucketVersioningEnabled, S3DefaultEncryptionKMS, } from '../rules/s3'; import { SageMakerEndpointConfigurationKMSKeyConfigured, SageMakerNotebookInstanceKMSKeyConfigured, SageMakerNotebookNoDirectInternetAccess, } from '../rules/sagemaker'; import { SecretsManagerRotationEnabled, SecretsManagerUsingKMSKey, } from '../rules/secretsmanager'; import { SNSEncryptedKMS } from '../rules/sns'; import { VPCDefaultSecurityGroupClosed, VPCFlowLogsEnabled, VPCNoUnrestrictedRouteToIGW, VPCSubnetAutoAssignPublicIpDisabled, } from '../rules/vpc'; import { WAFv2LoggingEnabled } from '../rules/waf'; /** * Check for HIPAA Security compliance. * Based on the HIPAA Security AWS operational best practices: https://docs.aws.amazon.com/config/latest/developerguide/operational-best-practices-for-hipaa_security.html */ export class HIPAASecurityChecks extends NagPack { constructor(props?: NagPackProps) { super(props); this.packName = 'HIPAA.Security'; } public visit(node: IConstruct): void { if (node instanceof CfnResource) { this.checkAPIGW(node); this.checkAutoScaling(node); this.checkCloudTrail(node); this.checkCloudWatch(node); this.checkCodeBuild(node); this.checkDMS(node); this.checkDynamoDB(node); this.checkEC2(node); this.checkECS(node); this.checkEFS(node); this.checkElastiCache(node); this.checkElasticBeanstalk(node); this.checkELB(node); this.checkEMR(node); this.checkIAM(node); this.checkLambda(node); this.checkOpenSearch(node); this.checkRDS(node); this.checkRedshift(node); this.checkS3(node); this.checkSageMaker(node); this.checkSecretsManager(node); this.checkSNS(node); this.checkVPC(node); this.checkWAF(node); } } /** * Check API Gateway Resources * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkAPIGW(node: CfnResource): void { this.applyRule({ info: 'The API Gateway stage does not have caching enabled and encrypted for all methods - (Control IDs: 164.312(a)(2)(iv), 164.312(e)(2)(ii)).', explanation: "To help protect data at rest, ensure encryption is enabled for your API Gateway stage's cache. Because sensitive data can be captured for the API method, enable encryption at rest to help protect that data.", level: NagMessageLevel.ERROR, rule: APIGWCacheEnabledAndEncrypted, node: node, }); this.applyRule({ info: 'The API Gateway stage does not have execution logging enabled for all methods - (Control ID: 164.312(b)).', explanation: 'API Gateway logging displays detailed views of users who accessed the API and the way they accessed the API. This insight enables visibility of user activities.', level: NagMessageLevel.ERROR, rule: APIGWExecutionLoggingEnabled, node: node, }); this.applyRule({ info: 'The API Gateway REST API stage is not configured with SSL certificates - (Control IDs: 164.312(a)(2)(iv), 164.312(e)(1), 164.312(e)(2)(i), 164.312(e)(2)(ii)).', explanation: 'Ensure Amazon API Gateway REST API stages are configured with SSL certificates to allow backend systems to authenticate that requests originate from API Gateway.', level: NagMessageLevel.ERROR, rule: APIGWSSLEnabled, node: node, }); this.applyRule({ info: 'The API Gateway REST API stage does not have X-Ray enabled - (Control ID: 164.312(b)).', explanation: 'AWS X-Ray collects data about requests that your application serves, and provides tools you can use to view, filter, and gain insights into that data to identify issues and opportunities for optimization. Ensure X-Ray is enables so you can see detailed information not only about the request and response, but also about calls that your application makes to downstream AWS resources, microservices, databases and HTTP web APIs.', level: NagMessageLevel.ERROR, rule: APIGWXrayEnabled, node: node, }); } /** * Check Auto Scaling Resources * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkAutoScaling(node: CfnResource): void { this.applyRule({ info: 'The Auto Scaling group utilizes a load balancer and does not have an ELB health check configured - (Control ID: 164.312(b)).', explanation: 'The Elastic Load Balancer (ELB) health checks for Amazon Elastic Compute Cloud (Amazon EC2) Auto Scaling groups support maintenance of adequate capacity and availability. The load balancer periodically sends pings, attempts connections, or sends requests to test Amazon EC2 instances health in an auto-scaling group. If an instance is not reporting back, traffic is sent to a new Amazon EC2 instance.', level: NagMessageLevel.ERROR, rule: AutoScalingGroupELBHealthCheckRequired, node: node, }); this.applyRule({ info: 'The Auto Scaling launch configuration does not have public IP addresses disabled - (Control IDs: 164.308(a)(3)(i), 164.308(a)(3)(ii)(B), 164.308(a)(4)(ii)(A), 164.308(a)(4)(ii)(C), 164.312(a)(1), 164.312(e)(1)).', explanation: 'If you configure your Network Interfaces with a public IP address, then the associated resources to those Network Interfaces are reachable from the internet. EC2 resources should not be publicly accessible, as this may allow unintended access to your applications or servers.', level: NagMessageLevel.ERROR, rule: AutoScalingLaunchConfigPublicIpDisabled, node: node, }); } /** * Check CloudTrail Resources * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkCloudTrail(node: CfnResource): void { this.applyRule({ info: 'The trail does not have CloudWatch logs enabled - (Control IDs: 164.308(a)(3)(ii)(A), 164.312(b)).', explanation: 'Use Amazon CloudWatch to centrally collect and manage log event activity. Inclusion of AWS CloudTrail data provides details of API call activity within your AWS account.', level: NagMessageLevel.ERROR, rule: CloudTrailCloudWatchLogsEnabled, node: node, }); this.applyRule({ info: 'The trail does not have a KMS key ID or have encryption enabled - (Control ID: 164.312(a)(2)(iv), 164.312(e)(2)(ii)).', explanation: 'Because sensitive data may exist and to help protect data at rest, ensure encryption is enabled for your AWS CloudTrail trails.', level: NagMessageLevel.ERROR, rule: CloudTrailEncryptionEnabled, node: node, }); this.applyRule({ info: 'The trail does not have log file validation enabled - (Control ID: 164.312(c)(1), 164.312(c)(2)).', explanation: 'Utilize AWS CloudTrail log file validation to check the integrity of CloudTrail logs. Log file validation helps determine if a log file was modified or deleted or unchanged after CloudTrail delivered it. This feature is built using industry standard algorithms: SHA-256 for hashing and SHA-256 with RSA for digital signing. This makes it computationally infeasible to modify, delete or forge CloudTrail log files without detection.', level: NagMessageLevel.ERROR, rule: CloudTrailLogFileValidationEnabled, node: node, }); } /** * Check CloudWatch Resources * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkCloudWatch(node: CfnResource): void { this.applyRule({ info: 'The CloudWatch alarm does not have at least one alarm action, one INSUFFICIENT_DATA action, or one OK action enabled - (Control ID: 164.312(b)).', explanation: 'Amazon CloudWatch alarms alert when a metric breaches the threshold for a specified number of evaluation periods. The alarm performs one or more actions based on the value of the metric or expression relative to a threshold over a number of time periods.', level: NagMessageLevel.ERROR, rule: CloudWatchAlarmAction, node: node, }); this.applyRule({ info: 'The CloudWatch Log Group is not encrypted with an AWS KMS key - (Control IDs: 164.312(a)(2)(iv), 164.312(e)(2)(ii)).', explanation: 'To help protect sensitive data at rest, ensure encryption is enabled for your Amazon CloudWatch Log Groups.', level: NagMessageLevel.ERROR, rule: CloudWatchLogGroupEncrypted, node: node, }); this.applyRule({ info: 'The CloudWatch Log Group does not have an explicit retention period configured - (Control ID: 164.312(b)).', explanation: 'Ensure a minimum duration of event log data is retained for your log groups to help with troubleshooting and forensics investigations. The lack of available past event log data makes it difficult to reconstruct and identify potentially malicious events.', level: NagMessageLevel.ERROR, rule: CloudWatchLogGroupRetentionPeriod, node: node, }); } /** * Check CodeBuild Resources * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkCodeBuild(node: CfnResource): void { this.applyRule({ info: 'The CodeBuild environment stores sensitive credentials (such as AWS_ACCESS_KEY_ID and/or AWS_SECRET_ACCESS_KEY) as plaintext environment variables - (Control IDs: 164.308(a)(3)(i), 164.308(a)(4)(ii)(A), 164.308(a)(4)(ii)(C), 164.312(a)(1)).', explanation: 'Do not store these variables in clear text. Storing these variables in clear text leads to unintended data exposure and unauthorized access.', level: NagMessageLevel.ERROR, rule: CodeBuildProjectEnvVarAwsCred, node: node, }); this.applyRule({ info: 'The CodeBuild project which utilizes either a GitHub or BitBucket source repository does not utilize OAUTH - (Control IDs: 164.308(a)(3)(i), 164.308(a)(4)(ii)(A), 164.308(a)(4)(ii)(C), 164.312(a)(1)).', explanation: 'OAUTH is the most secure method of authenticating your CodeBuild application. Use OAuth instead of personal access tokens or a user name and password to grant authorization for accessing GitHub or Bitbucket repositories.', level: NagMessageLevel.ERROR, rule: CodeBuildProjectSourceRepoUrl, node: node, }); } /** * Check DMS Resources * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkDMS(node: CfnResource) { this.applyRule({ info: 'The DMS replication instance is public - (Control IDs: 164.308(a)(3)(i), 164.308(a)(4)(ii)(A), 164.308(a)(4)(ii)(C), 164.312(a)(1), 164.312(e)(1)).', explanation: 'DMS replication instances can contain sensitive information and access control is required for such accounts.', level: NagMessageLevel.ERROR, rule: DMSReplicationNotPublic, node: node, }); } /** * Check DynamoDB Resources * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkDynamoDB(node: CfnResource) { this.applyRule({ info: "The provisioned capacity DynamoDB table does not have Auto Scaling enabled on it's indexes - (Control IDs: 164.308(a)(7)(i), 164.308(a)(7)(ii)(C)).", explanation: 'Amazon DynamoDB auto scaling uses the AWS Application Auto Scaling service to adjust provisioned throughput capacity that automatically responds to actual traffic patterns. This enables a table or a global secondary index to increase its provisioned read/write capacity to handle sudden increases in traffic, without throttling.', level: NagMessageLevel.ERROR, rule: DynamoDBAutoScalingEnabled, node: node, }); this.applyRule({ info: 'The DynamoDB table is not in an AWS Backup plan - (Control IDs: 164.308(a)(7)(i), 164.308(a)(7)(ii)(A), 164.308(a)(7)(ii)(B)).', explanation: 'To help with data back-up processes, ensure your Amazon DynamoDB tables are a part of an AWS Backup plan. AWS Backup is a fully managed backup service with a policy-based backup solution. This solution simplifies your backup management and enables you to meet your business and regulatory backup compliance requirements.', level: NagMessageLevel.ERROR, rule: DynamoDBInBackupPlan, node: node, }); this.applyRule({ info: 'The DynamoDB table does not have Point-in-time Recovery enabled - (Control IDs: 164.308(a)(7)(i), 164.308(a)(7)(ii)(A), 164.308(a)(7)(ii)(B)).', explanation: 'The recovery maintains continuous backups of your table for the last 35 days.', level: NagMessageLevel.ERROR, rule: DynamoDBPITREnabled, node: node, }); } /** * Check EC2 Resources * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkEC2(node: CfnResource): void { this.applyRule({ info: 'The EBS volume is not in an AWS Backup plan - (Control IDs: 164.308(a)(7)(i), 164.308(a)(7)(ii)(A), 164.308(a)(7)(ii)(B)).', explanation: 'To help with data back-up processes, ensure your Amazon Elastic Block Store (Amazon EBS) volumes are a part of an AWS Backup plan. AWS Backup is a fully managed backup service with a policy-based backup solution. This solution simplifies your backup management and enables you to meet your business and regulatory backup compliance requirements.', level: NagMessageLevel.ERROR, rule: EC2EBSInBackupPlan, node: node, }); this.applyRule({ info: "The EC2 instance type 'supports' EBS optimization and does not have EBS optimization enabled - (Control ID: 164.308(a)(7)(i)).", explanation: 'An optimized instance in Amazon Elastic Block Store (Amazon EBS) provides additional, dedicated capacity for Amazon EBS I/O operations. This optimization provides the most efficient performance for your EBS volumes by minimizing contention between Amazon EBS I/O operations and other traffic from your instance.', level: NagMessageLevel.ERROR, rule: EC2EBSOptimizedInstance, node: node, }); this.applyRule({ info: 'The EC2 instance does not have detailed monitoring enabled - (Control IDs: 164.312(b)).', explanation: 'Detailed monitoring provides additional monitoring information (such as 1-minute period graphs) on the AWS console.', level: NagMessageLevel.ERROR, rule: EC2InstanceDetailedMonitoringEnabled, node: node, }); this.applyRule({ info: 'The EC2 instance is associated with a public IP address - (Control IDs: 164.308(a)(3)(i), 164.308(a)(4)(ii)(A), 164.308(a)(4)(ii)(C), 164.312(a)(1), 164.312(e)(1)).', explanation: 'Amazon EC2 instances can contain sensitive information and access control is required for such resources.', level: NagMessageLevel.ERROR, rule: EC2InstanceNoPublicIp, node: node, }); this.applyRule({ info: 'The EC2 instance does not have an instance profile attached - (Control IDs: 164.308(a)(3)(i), 164.308(a)(3)(ii)(A), 164.308(a)(4)(ii)(A), 164.308(a)(4)(ii)(B), 164.308(a)(4)(ii)(C), 164.312(a)(1)).', explanation: 'EC2 instance profiles pass an IAM role to an EC2 instance. Attaching an instance profile to your instances can assist with least privilege and permissions management.', level: NagMessageLevel.ERROR, rule: EC2InstanceProfileAttached, node: node, }); this.applyRule({ info: 'The EC2 instance is not within a VPC - (Control IDs: 164.308(a)(3)(i), 164.308(a)(4)(ii)(A), 164.308(a)(4)(ii)(C), 164.312(a)(1), 164.312(e)(1)).', explanation: 'Because of their logical isolation, domains that reside within an Amazon VPC have an extra layer of security when compared to domains that use public endpoints.', level: NagMessageLevel.ERROR, rule: EC2InstancesInVPC, node: node, }); this.applyRule({ info: 'The EC2 instance allows unrestricted inbound IPv4 TCP traffic on common ports (20, 21, 3389, 3306, 4333) - (Control IDs: 164.308(a)(3)(i), 164.308(a)(3)(ii)(B), 164.308(a)(4)(i), 164.308(a)(4)(ii)(A), 164.308(a)(4)(ii)(B), 164.308(a)(4)(ii)(C), 164.312(a)(1), 164.312(e)(1)).', explanation: 'Not restricting access to ports to trusted sources can lead to attacks against the availability, integrity and confidentiality of systems. By default, common ports which should be restricted include port numbers 20, 21, 3389, 3306, and 4333.', level: NagMessageLevel.ERROR, rule: EC2RestrictedCommonPorts, node: node, }); this.applyRule({ info: 'The Security Group allows unrestricted SSH access - (Control IDs: 164.308(a)(3)(i), 164.308(a)(3)(ii)(B), 164.308(a)(4)(i), 164.308(a)(4)(ii)(A), 164.308(a)(4)(ii)(B), 164.308(a)(4)(ii)(C), 164.312(a)(1), 164.312(e)(1).', explanation: 'Not allowing ingress (or remote) traffic from 0.0.0.0/0 or ::/0 to port 22 on your resources helps to restrict remote access.', level: NagMessageLevel.ERROR, rule: EC2RestrictedSSH, node: node, }); } /** * Check ECS Resources * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkECS(node: CfnResource): void { this.applyRule({ info: "The ECS task definition is configured for host networking and has at least one container with definitions with 'privileged' set to false or empty or 'user' set to root or empty - (Control IDs: 164.308(a)(3)(i), 164.308(a)(3)(ii)(A), 164.308(a)(4)(ii)(A), 164.308(a)(4)(ii)(C), 164.312(a)(1)).", explanation: 'If a task definition has elevated privileges it is because you have specifically opted-in to those configurations. This rule checks for unexpected privilege escalation when a task definition has host networking enabled but the customer has not opted-in to elevated privileges.', level: NagMessageLevel.ERROR, rule: ECSTaskDefinitionUserForHostMode, node: node, }); } /** * Check EFS Resources * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkEFS(node: CfnResource) { this.applyRule({ info: 'The EFS is not in an AWS Backup plan - (Control IDs: 164.308(a)(7)(i), 164.308(a)(7)(ii)(A), 164.308(a)(7)(ii)(B)).', explanation: 'To help with data back-up processes, ensure your Amazon Elastic File System (Amazon EFS) file systems are a part of an AWS Backup plan. AWS Backup is a fully managed backup service with a policy-based backup solution. This solution simplifies your backup management and enables you to meet your business and regulatory backup compliance requirements.', level: NagMessageLevel.ERROR, rule: EFSInBackupPlan, node: node, }); this.applyRule({ info: 'The EFS does not have encryption at rest enabled - (Control IDs: 164.312(a)(2)(iv), 164.312(e)(2)(ii)).', explanation: 'Because sensitive data can exist and to help protect data at rest, ensure encryption is enabled for your Amazon Elastic File System (EFS).', level: NagMessageLevel.ERROR, rule: EFSEncrypted, node: node, }); } /** * Check ElastiCache Resources * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkElastiCache(node: CfnResource) { this.applyRule({ info: 'The ElastiCache Redis cluster does not retain automatic backups for at least 15 days - (Control IDs: 164.308(a)(7)(i), 164.308(a)(7)(ii)(A), 164.308(a)(7)(ii)(B)).', explanation: 'Automatic backups can help guard against data loss. If a failure occurs, you can create a new cluster, which restores your data from the most recent backup.', level: NagMessageLevel.ERROR, rule: ElastiCacheRedisClusterAutomaticBackup, node: node, }); } /** * Check Elastic Beanstalk Resources * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkElasticBeanstalk(node: CfnResource): void { this.applyRule({ info: 'The Elastic Beanstalk environment does not have enhanced health reporting enabled - (Control ID: 164.312(b)).', explanation: 'AWS Elastic Beanstalk enhanced health reporting enables a more rapid response to changes in the health of the underlying infrastructure. These changes could result in a lack of availability of the application. Elastic Beanstalk enhanced health reporting provides a status descriptor to gauge the severity of the identified issues and identify possible causes to investigate.', level: NagMessageLevel.ERROR, rule: ElasticBeanstalkEnhancedHealthReportingEnabled, node: node, }); this.applyRule({ info: 'The Elastic Beanstalk environment does not have managed updates enabled - (Control ID: 164.308(a)(5)(ii)(A)).', explanation: 'Enabling managed platform updates for an Amazon Elastic Beanstalk environment ensures that the latest available platform fixes, updates, and features for the environment are installed. Keeping up to date with patch installation is a best practice in securing systems.', level: NagMessageLevel.ERROR, rule: ElasticBeanstalkManagedUpdatesEnabled, node: node, }); } /** * Check Elastic Load Balancer Resources * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkELB(node: CfnResource): void { this.applyRule({ info: 'The ALB does not have invalid HTTP header dropping enabled - (Control IDs: 164.312(a)(2)(iv), 164.312(e)(1), 164.312(e)(2)(i), 164.312(e)(2)(ii)).', explanation: 'Ensure that your Application Load Balancers (ALB) are configured to drop http headers. Because sensitive data can exist, enable encryption in transit to help protect that data.', level: NagMessageLevel.ERROR, rule: ALBHttpDropInvalidHeaderEnabled, node: node, }); this.applyRule({ info: "The ALB's HTTP listeners are not configured to redirect to HTTPS - (Control IDs: 164.312(a)(2)(iv), 164.312(e)(1), 164.312(e)(2)(i), 164.312(e)(2)(ii)).", explanation: 'To help protect data in transit, ensure that your Application Load Balancer automatically redirects unencrypted HTTP requests to HTTPS. Because sensitive data can exist, enable encryption in transit to help protect that data.', level: NagMessageLevel.ERROR, rule: ALBHttpToHttpsRedirection, node: node, }); this.applyRule({ info: 'The CLB does not utilize an SSL certificate provided by ACM (Amazon Certificate Manager) - (Control IDs: 164.312(a)(2)(iv), 164.312(e)(1), 164.312(e)(2)(i), 164.312(e)(2)(ii)).', explanation: 'Because sensitive data can exist and to help protect data at transit, ensure encryption is enabled for your Elastic Load Balancing. Use AWS Certificate Manager to manage, provision and deploy public and private SSL/TLS certificates with AWS services and internal resources.', level: NagMessageLevel.ERROR, rule: ELBACMCertificateRequired, node: node, }); this.applyRule({ info: 'The CLB does not balance traffic between at least 2 Availability Zones - (Control IDs: 164.308(a)(7)(i), 164.308(a)(7)(ii)(C)).', explanation: 'The cross-zone load balancing reduces the need to maintain equivalent numbers of instances in each enabled availability zone.', level: NagMessageLevel.ERROR, rule: ELBCrossZoneLoadBalancingEnabled, node: node, }); this.applyRule({ info: 'The ALB, NLB, or GLB does not have deletion protection enabled - (Control IDs: 164.308(a)(7)(i), 164.308(a)(7)(ii)(C)).', explanation: 'Use this feature to prevent your load balancer from being accidentally or maliciously deleted, which can lead to loss of availability for your applications.', level: NagMessageLevel.ERROR, rule: ELBDeletionProtectionEnabled, node: node, }); this.applyRule({ info: 'The ELB does not have logging enabled - (Control ID: 164.312(b)).', explanation: "Elastic Load Balancing activity is a central point of communication within an environment. Ensure ELB logging is enabled. The collected data provides detailed information about requests sent to The ELB. Each log contains information such as the time the request was received, the client's IP address, latencies, request paths, and server responses.", level: NagMessageLevel.ERROR, rule: ELBLoggingEnabled, node: node, }); this.applyRule({ info: 'The CLB does not restrict its listeners to only the SSL and HTTPS protocols - (Control IDs: 164.312(a)(2)(iv), 164.312(e)(1), 164.312(e)(2)(i), 164.312(e)(2)(ii)).', explanation: 'Because sensitive data can exist, enable encryption in transit to help protect that data.', level: NagMessageLevel.ERROR, rule: ELBTlsHttpsListenersOnly, node: node, }); this.applyRule({ info: 'The ALB, NLB, or GLB listener does not utilize an SSL certificate provided by ACM (Amazon Certificate Manager) - (Control IDs: 164.312(a)(2)(iv), 164.312(e)(2)(ii)).', explanation: 'Because sensitive data can exist and to help protect data at transit, ensure encryption is enabled for your Elastic Load Balancing. Use AWS Certificate Manager to manage, provision and deploy public and private SSL/TLS certificates with AWS services and internal resources.', level: NagMessageLevel.ERROR, rule: ELBv2ACMCertificateRequired, node: node, }); } /** * Check EMR Resources * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkEMR(node: CfnResource) { this.applyRule({ info: 'The EMR cluster does not have Kerberos enabled - (Control IDs: 164.308(a)(3)(i), 164.308(a)(3)(ii)(A), 164.308(a)(3)(ii)(B), 164.308(a)(4)(i), 164.308(a)(4)(ii)(A), 164.308(a)(4)(ii)(B), 164.308(a)(4)(ii)(C), 164.312(a)(1)).', explanation: 'The access permissions and authorizations can be managed and incorporated with the principles of least privilege and separation of duties, by enabling Kerberos for Amazon EMR clusters.', level: NagMessageLevel.ERROR, rule: EMRKerberosEnabled, node: node, }); } /** * Check IAM Resources * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkIAM(node: CfnResource): void { this.applyRule({ info: 'The IAM Group does not have at least one IAM User - (Control IDs: 164.308(a)(3)(i), 164.308(a)(3)(ii)(A), 164.308(a)(3)(ii)(B), 164.308(a)(4)(i), 164.308(a)(4)(ii)(A), 164.308(a)(4)(ii)(B), 164.308(a)(4)(ii)(C), 164.312(a)(1)).', explanation: 'AWS Identity and Access Management (IAM) can help you incorporate the principles of least privilege and separation of duties with access permissions and authorizations, by ensuring that IAM groups have at least one IAM user. Placing IAM users in groups based on their associated permissions or job function is one way to incorporate least privilege.', level: NagMessageLevel.ERROR, rule: IAMGroupHasUsers, node: node, }); this.applyRule({ info: 'The IAM Group, User, or Role contains an inline policy - (Control IDs: 164.308(a)(3)(i), 164.308(a)(3)(ii)(A), 164.308(a)(3)(ii)(B), 164.308(a)(4)(i), 164.308(a)(4)(ii)(A), 164.308(a)(4)(ii)(B), 164.308(a)(4)(ii)(C), 164.312(a)(1)).', explanation: 'AWS recommends to use managed policies instead of inline policies. The managed policies allow reusability, versioning and rolling back, and delegating permissions management.', level: NagMessageLevel.ERROR, rule: IAMNoInlinePolicy, node: node, }); this.applyRule({ info: 'The IAM policy grants admin access - (Control IDs: 164.308(a)(3)(i), 164.308(a)(3)(ii)(A), 164.308(a)(3)(ii)(B), 164.308(a)(4)(i), 164.308(a)(4)(ii)(A), 164.308(a)(4)(ii)(B), 164.308(a)(4)(ii)(C), 164.312(a)(1)).', explanation: 'AWS Identity and Access Management (IAM) can help you incorporate the principles of least privilege and separation of duties with access permissions and authorizations, restricting policies from containing "Effect": "Allow" with "Action": "*" over "Resource": "*". Allowing users to have more privileges than needed to complete a task may violate the principle of least privilege and separation of duties.', level: NagMessageLevel.ERROR, rule: IAMPolicyNoStatementsWithAdminAccess, node: node, }); this.applyRule({ info: 'The IAM policy grants full access - (Control IDs: 164.308(a)(3)(i), 164.308(a)(3)(ii)(A), 164.308(a)(3)(ii)(B), 164.308(a)(4)(i), 164.308(a)(4)(ii)(A), 164.308(a)(4)(ii)(B), 164.308(a)(4)(ii)(C), 164.312(a)(1)).', explanation: 'Ensure IAM Actions are restricted to only those actions that are needed. Allowing users to have more privileges than needed to complete a task may violate the principle of least privilege and separation of duties.', level: NagMessageLevel.ERROR, rule: IAMPolicyNoStatementsWithFullAccess, node: node, }); this.applyRule({ info: 'The IAM user does not belong to any group(s) - (Control IDs: 164.308(a)(3)(i), 164.308(a)(3)(ii)(A), 164.308(a)(3)(ii)(B), 164.308(a)(4)(i), 164.308(a)(4)(ii)(A), 164.308(a)(4)(ii)(B), 164.308(a)(4)(ii)(C), 164.312(a)(1)).', explanation: 'AWS Identity and Access Management (IAM) can help you restrict access permissions and authorizations, by ensuring IAM users are members of at least one group. Allowing users more privileges than needed to complete a task may violate the principle of least privilege and separation of duties.', level: NagMessageLevel.ERROR, rule: IAMUserGroupMembership, node: node, }); this.applyRule({ info: 'The IAM policy is attached at the user level - (Control IDs: 164.308(a)(3)(i), 164.308(a)(3)(ii)(A), 164.308(a)(3)(ii)(B), 164.308(a)(4)(i), 164.308(a)(4)(ii)(A), 164.308(a)(4)(ii)(B), 164.308(a)(4)(ii)(C), 164.312(a)(1)).', explanation: 'Assigning privileges at the group or the role level helps to reduce opportunity for an identity to receive or retain excessive privileges.', level: NagMessageLevel.ERROR, rule: IAMUserNoPolicies, node: node, }); } /** * Check Lambda Resources * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkLambda(node: CfnResource) { this.applyRule({ info: 'The Lambda function is not configured with function-level concurrent execution limits - (Control ID: 164.312(b)).', explanation: "Ensure that a Lambda function's concurrency high and low limits are established. This can assist in baselining the number of requests that your function is serving at any given time.", level: NagMessageLevel.ERROR, rule: LambdaConcurrency, node: node, }); this.applyRule({ info: 'The Lambda function is not configured with a dead-letter configuration - (Control ID: 164.312(b)).', explanation: 'Notify the appropriate personnel through Amazon Simple Queue Service (Amazon SQS) or Amazon Simple Notification Service (Amazon SNS) when a function has failed.', level: NagMessageLevel.ERROR, rule: LambdaDLQ, node: node, }); this.applyRule({ info: 'The Lambda function is not VPC enabled - (Control IDs: 164.308(a)(3)(i), 164.308(a)(4)(ii)(A), 164.308(a)(4)(ii)(C), 164.312(a)(1), 164.312(e)(1)).', explanation: 'Because of their logical isolation, domains that reside within an Amazon VPC have an extra layer of security when compared to domains that use public endpoints.', level: NagMessageLevel.ERROR, rule: LambdaInsideVPC, node: node, }); } /** * Check OpenSearch Resources * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkOpenSearch(node: CfnResource) { this.applyRule({ info: 'The OpenSearch Service domain does not have encryption at rest enabled - (Control IDs: 164.312(a)(2)(iv), 164.312(e)(2)(ii)).', explanation: 'Because sensitive data can exist and to help protect data at rest, ensure encryption is enabled for your Amazon OpenSearch Service (OpenSearch Service) domains.', level: NagMessageLevel.ERROR, rule: OpenSearchEncryptedAtRest, node: node, }); this.applyRule({ info: 'The OpenSearch Service domain is not running within a VPC - (Control IDs: 164.308(a)(3)(i), 164.308(a)(4)(ii)(A), 164.308(a)(4)(ii)(C), 164.312(a)(1), 164.312(e)(1)).', explanation: 'VPCs help secure your AWS resources and provide an extra layer of protection.', level: NagMessageLevel.ERROR, rule: OpenSearchInVPCOnly, node: node, }); this.applyRule({ info: 'The OpenSearch Service domain does not stream error logs (ES_APPLICATION_LOGS) to CloudWatch Logs - (Control IDs: 164.308(a)(3)(ii)(A), 164.312(b)).', explanation: 'Ensure Amazon OpenSearch Service domains have error logs enabled and streamed to Amazon CloudWatch Logs for retention and response. Domain error logs can assist with security and access audits, and can help to diagnose availability issues.', level: NagMessageLevel.ERROR, rule: OpenSearchErrorLogsToCloudWatch, node: node, }); this.applyRule({ info: 'The OpenSearch Service domain does not have node-to-node encryption enabled - (Control IDs: 164.312(a)(2)(iv), 164.312(e)(1), 164.312(e)(2)(i), 164.312(e)(2)(ii)).', explanation: 'Because sensitive data can exist, enable encryption in transit to help protect that data within your Amazon OpenSearch Service (OpenSearch Service) domains.', level: NagMessageLevel.ERROR, rule: OpenSearchNodeToNodeEncryption, node: node, }); } /** * Check RDS Resources * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkRDS(node: CfnResource): void { this.applyRule({ info: 'The RDS DB instance does not have automatic minor version upgrades enabled - (Control ID: 164.308(a)(5)(ii)(A)).', explanation: 'Enable automatic minor version upgrades on your Amazon Relational Database Service (RDS) instances to ensure the latest minor version updates to the Relational Database Management System (RDBMS) are installed, which may include security patches and bug fixes.', level: NagMessageLevel.ERROR, rule: RDSAutomaticMinorVersionUpgradeEnabled, node: node, }); this.applyRule({ info: 'The RDS DB instance does not enhanced monitoring enabled - (Control ID: 164.312(b)).', explanation: 'Enable enhanced monitoring to help monitor Amazon RDS availability. This provides detailed visibility into the health of your Amazon RDS database instances.', level: NagMessageLevel.ERROR, rule: RDSEnhancedMonitoringEnabled, node: node, }); this.applyRule({ info: 'The RDS DB instance is not in an AWS Backup plan - (Control IDs: 164.308(a)(7)(i), 164.308(a)(7)(ii)(A), 164.308(a)(7)(ii)(B)).', explanation: 'To help with data back-up processes, ensure your Amazon Relational Database Service (Amazon RDS) instances are a part of an AWS Backup plan. AWS Backup is a fully managed backup service with a policy-based backup solution. This solution simplifies your backup management and enables you to meet your business and regulatory backup compliance requirements.', level: NagMessageLevel.ERROR, rule: RDSInBackupPlan, node: node, }); this.applyRule({ info: 'The RDS DB instance does not have backups enabled - (Control IDs: 164.308(a)(7)(i), 164.308(a)(7)(ii)(A), 164.308(a)(7)(ii)(B)).', explanation: 'The backup feature of Amazon RDS creates backups of your databases and transaction logs.', level: NagMessageLevel.ERROR, rule: RDSInstanceBackupEnabled, node: node, }); this.applyRule({ info: 'The RDS DB instance or Aurora DB cluster does not have deletion protection enabled - (Control IDs: 164.308(a)(7)(i), 164.308(a)(7)(ii)(C)).', explanation: 'Ensure Amazon Relational Database Service (Amazon RDS) instances and clusters have deletion protection enabled. Use deletion protection to prevent your Amazon RDS DB instances and clusters from being accidentally or maliciously deleted, which can lead to loss of availability for your applications.', level: NagMessageLevel.ERROR, rule: RDSInstanceDeletionProtectionEnabled, node: node, }); this.applyRule({ info: 'The non-Aurora RDS DB instance does not have multi-AZ support enabled - (Control IDs: 164.308(a)(7)(i), 164.308(a)(7)(ii)(C)).', explanation: 'Multi-AZ support in Amazon Relational Database Service (Amazon RDS) provides enhanced availability and durability for database instances. When you provision a Multi-AZ database instance, Amazon RDS automatically creates a primary database instance, and synchronously replicates the data to a standby instance in a different Availability Zone. In case of an infrastructure failure, Amazon RDS performs an automatic failover to the standby so that you can resume database operations as soon as the failover is complete.', level: NagMessageLevel.ERROR, rule: RDSMultiAZSupport, node: node, }); this.applyRule({ info: 'The RDS DB instance allows public access - (Control IDs: 164.308(a)(3)(i), 164.308(a)(4)(ii)(A), 164.308(a)(4)(ii)(C), 164.312(a)(1), 164.312(e)(1)).', explanation: 'Amazon RDS database instances can contain sensitive information, and principles and access control is required for such accounts.', level: NagMessageLevel.ERROR, rule: RDSInstancePublicAccess, node: node, }); this.applyRule({ info: 'The RDS DB instance does not have all CloudWatch log types exported - (Control IDs: 164.308(a)(3)(ii)(A), 164.308(a)(5)(ii)(C)).', explanation: 'To help with logging and monitoring within your environment, ensure Amazon Relational Database Service (Amazon RDS) logging is enabled. With Amazon RDS logging, you can capture events such as connections, disconnections, queries, or tables queried.', level: NagMessageLevel.ERROR, rule: RDSLoggingEnabled, node: node, }); this.applyRule({ info: 'The RDS DB instance or Aurora DB cluster does not have storage encrypted - (Control IDs: 164.312(a)(2)(iv), 164.312(e)(2)(ii)).', explanation: 'Because sensitive data can exist at rest in Amazon RDS DB instances and clusters, enable encryption at rest to help protect that data.', level: NagMessageLevel.ERROR, rule: RDSStorageEncrypted, node: node, }); } /** * Check Redshift Resources * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkRedshift(node: CfnResource): void { this.applyRule({ info: 'The Redshift cluster does not have automated snapshots enabled or the retention period is not between 1 and 35 days - (Control IDs: 164.308(a)(7)(i), 164.308(a)(7)(ii)(A), 164.308(a)(7)(ii)(B)).', explanation: 'To help with data back-up processes, ensure your Amazon Redshift clusters have automated snapshots. When automated snapshots are enabled for a cluster, Redshift periodically takes snapshots of that cluster. By default, Redshift takes a snapshot every eight hours or every 5 GB per node of data changes, or whichever comes first.', level: NagMessageLevel.ERROR, rule: RedshiftBackupEnabled, node: node, }); this.applyRule({ info: 'The Redshift cluster does not have encryption or audit logging enabled - (Control IDs: 164.312(a)(2)(iv), 164.312(b), 164.312(e)(2)(ii)).', explanation: 'To protect data at rest, ensure that encryption is enabled for your Amazon Redshift clusters. You must also ensure that required configurations are deployed on Amazon Redshift clusters. The audit logging should be enabled to provide information about connections and user activities in the database.', level: NagMessageLevel.ERROR, rule: RedshiftClusterConfiguration, node: node, }); this.applyRule({ info: 'The Redshift cluster does not have version upgrades enabled, automated snapshot retention periods enabled, and an explicit maintenance window configured - (Control IDs: 164.308(a)(5)(ii)(A), 164.308(a)(7)(ii)(A)).', explanation: 'Ensure that Amazon Redshift clusters have the preferred settings for your organization. Specifically, that they have preferred maintenance windows and automated snapshot retention periods for the database.', level: NagMessageLevel.ERROR, rule: RedshiftClusterMaintenanceSettings, node: node, }); this.applyRule({ info: 'The Redshift cluster allows public access - (Control IDs: 164.308(a)(3)(i), 164.308(a)(4)(ii)(A), 164.308(a)(4)(ii)(C), 164.312(a)(1), 164.312(e)(1)).', explanation: 'Amazon Redshift clusters can contain sensitive information and principles and access control is required for such accounts.', level: NagMessageLevel.ERROR, rule: RedshiftClusterPublicAccess, node: node, }); this.applyRule({ info: 'The Redshift cluster does not have enhanced VPC routing enabled - (Control IDs: 164.312(e)(1)).', explanation: 'Enhanced VPC routing forces all COPY and UNLOAD traffic between the cluster and data repositories to go through your Amazon VPC. You can then use VPC features such as security groups and network access control lists to secure network traffic. You can also use VPC flow logs to monitor network traffic.', level: NagMessageLevel.ERROR, rule: RedshiftEnhancedVPCRoutingEnabled, node: node, }); this.applyRule({ info: 'The Redshift cluster does not require TLS/SSL encryption - (Control IDs: 164.312(a)(2)(iv), 164.312(e)(1), 164.312(e)(2)(i), 164.312(e)(2)(ii)).', explanation: 'Ensure that your Amazon Redshift clusters require TLS/SSL encryption to connect to SQL clients. Because sensitive data can exist, enable encryption in transit to help protect that data.', level: NagMessageLevel.ERROR, rule: RedshiftRequireTlsSSL, node: node, }); } /** * Check Amazon S3 Resources * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkS3(node: CfnResource): void { this.applyRule({ info: 'The S3 bucket does not prohibit public access through bucket level settings - (Control IDs: 164.308(a)(3)(i), 164.308(a)(4)(ii)(A), 164.308(a)(4)(ii)(C), 164.312(a)(1), 164.312(e)(1)).', explanation: 'Keep sensitive data safe from unauthorized remote users by preventing public access at the bucket level.', level: NagMessageLevel.ERROR, rule: S3BucketLevelPublicAccessProhibited, node: node, }); this.applyRule({ info: 'The S3 Bucket does not have server access logs enabled - (Control IDs: 164.308(a)(3)(ii)(A), 164.312(b)).', explanation: 'Amazon Simple Storage Service (Amazon S3) server access logging provides a method to monitor the network for potential cybersecurity events. The events are monitored by capturing detailed records for the requests that are made to an Amazon S3 bucket. Each access log record provides details about a single access request. The details include the requester, bucket name, request time, request action, response status, and an error code, if relevant.', level: NagMessageLevel.ERROR, rule: S3BucketLoggingEnabled, node: node, }); this.applyRule({ info: 'The S3 Bucket does not prohibit public read access through its Block Public Access configurations and bucket ACLs - (Control IDs: 164.308(a)(3)(i), 164.308(a)(4)(ii)(A), 164.308(a)(4)(ii)(C), 164.312(a)(1), 164.312(e)(1)).', explanation: 'The management of access should be consistent with the classification of the data.', level: NagMessageLevel.ERROR, rule: S3BucketPublicReadProhibited, node: node, }); this.applyRule({ info: 'The S3 Bucket does not prohibit public write access through its Block Public Access configurations and bucket ACLs - (Control IDs: 164.308(a)(3)(i), 164.308(a)(4)(ii)(A), 164.308(a)(4)(ii)(C), 164.312(a)(1), 164.312(e)(1)).', explanation: 'The management of access should be consistent with the classification of the data.', level: NagMessageLevel.ERROR, rule: S3BucketPublicWriteProhibited, node: node, }); this.applyRule({ info: 'The S3 Bucket does not have replication enabled - (Control IDs: 164.308(a)(7)(i), 164.308(a)(7)(ii)(A), 164.308(a)(7)(ii)(B)).', explanation: 'Amazon Simple Storage Service (Amazon S3) Cross-Region Replication (CRR) supports maintaining adequate capacity and availability. CRR enables automatic, asynchronous copying of objects across Amazon S3 buckets to help ensure that data availability is maintained.', level: NagMessageLevel.ERROR, rule: S3BucketReplicationEnabled, node: node, }); this.applyRule({ info: 'The S3 Bucket does not have default server-side encryption enabled - (Control IDs: 164.312(a)(2)(iv), 164.312(c)(2), 164.312(e)(2)(ii)).', explanation: 'Because sensitive data can exist at rest in Amazon S3 buckets, enable encryption to help protect that data.', level: NagMessageLevel.ERROR, rule: S3BucketServerSideEncryptionEnabled, node: node, }); this.applyRule({ info: 'The S3 Bucket does not require requests to use SSL - (Control IDs: 164.312(a)(2)(iv), 164.312(c)(2), 164.312(e)(1), 164.312(e)(2)(i), 164.312(e)(2)(ii)).', explanation: 'To help protect data in transit, ensure that your Amazon Simple Storage Service (Amazon S3) buckets require requests to use Secure Socket Layer (SSL). Because sensitive data can exist, enable encryption in transit to help protect that data.', level: NagMessageLevel.ERROR, rule: S3BucketSSLRequestsOnly, node: node, }); this.applyRule({ info: 'The S3 Bucket does not have versioning enabled - (Control IDs: 164.308(a)(7)(i), 164.308(a)(7)(ii)(A), 164.308(a)(7)(ii)(B), 164.312(c)(1), 164.312(c)(2)).', explanation: 'Use versioning to preserve, retrieve, and restore every version of every object stored in your Amazon S3 bucket. Versioning helps you to easily recover from unintended user actions and application failures.', level: NagMessageLevel.ERROR, rule: S3BucketVersioningEnabled, node: node, }); this.applyRule({ info: 'The S3 Bucket is not encrypted with a KMS Key by default - (Control IDs: 164.312(a)(2)(iv), 164.312(e)(2)(ii)).', explanation: 'Ensure that encryption is enabled for your Amazon Simple Storage Service (Amazon S3) buckets. Because sensitive data can exist at rest in an Amazon S3 bucket, enable encryption at rest to help protect that data.', level: NagMessageLevel.ERROR, rule: S3DefaultEncryptionKMS, node: node, }); } /** * Check SageMaker Resources * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkSageMaker(node: CfnResource) { this.applyRule({ info: 'The SageMaker endpoint is not encrypted with a KMS key - (Control IDs: 164.312(a)(2)(iv), 164.312(e)(2)(ii)).', explanation: 'Because sensitive data can exist at rest in SageMaker endpoint, enable encryption at rest to help protect that data.', level: NagMessageLevel.ERROR, rule: SageMakerEndpointConfigurationKMSKeyConfigured, node: node, }); this.applyRule({ info: 'The SageMaker notebook is not encrypted with a KMS key - (Control IDs: 164.312(a)(2)(iv), 164.312(e)(2)(ii)).', explanation: 'Because sensitive data can exist at rest in SageMaker notebook, enable encryption at rest to help protect that data.', level: NagMessageLevel.ERROR, rule: SageMakerNotebookInstanceKMSKeyConfigured, node: node, }); this.applyRule({ info: 'The SageMaker notebook does not disable direct internet access - (Control IDs: 164.308(a)(3)(i), 164.308(a)(4)(ii)(A), 164.308(a)(4)(ii)(C), 164.312(a)(1), 164.312(e)(1)).', explanation: 'By preventing direct internet access, you can keep sensitive data from being accessed by unauthorized users.', level: NagMessageLevel.ERROR, rule: SageMakerNotebookNoDirectInternetAccess, node: node, }); } /** * Check Secrets Manager Resources * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkSecretsManager(node: CfnResource): void { this.applyRule({ info: 'The secret does not have automatic rotation scheduled - (Control ID: 164.308(a)(4)(ii)(B)).', explanation: 'Rotating secrets on a regular schedule can shorten the period a secret is active, and potentially reduce the business impact if the secret is compromised.', level: NagMessageLevel.ERROR, rule: SecretsManagerRotationEnabled, node: node, }); this.applyRule({ info: 'The secret is not encrypted with a KMS Customer managed key - (Control IDs: 164.312(a)(2)(iv), 164.312(e)(2)(ii)).', explanation: 'To help protect data at rest, ensure encryption with AWS Key Management Service (AWS KMS) is enabled for AWS Secrets Manager secrets. Because sensitive data can exist at rest in Secrets Manager secrets, enable encryption at rest to help protect that data.', level: NagMessageLevel.ERROR, rule: SecretsManagerUsingKMSKey, node: node, }); } /** * Check Amazon SNS Resources * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkSNS(node: CfnResource): void { this.applyRule({ info: 'The SNS topic does not have KMS encryption enabled - (Control IDs: 164.312(a)(2)(iv), 164.312(e)(2)(ii)).', explanation: 'Because sensitive data can exist at rest in published messages, enable encryption at rest to help protect that data.', level: NagMessageLevel.ERROR, rule: SNSEncryptedKMS, node: node, }); } /** * Check VPC Resources * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkVPC(node: CfnResource): void { this.applyRule({ info: "The VPC's default security group allows inbound or outbound traffic - (Control ID: 164.312(e)(1)).", explanation: 'When creating a VPC through CloudFormation, the default security group will always be open. Therefore it is important to always close the default security group after stack creation whenever a VPC is created. Restricting all the traffic on the default security group helps in restricting remote access to your AWS resources.', level: NagMessageLevel.WARN, rule: VPCDefaultSecurityGroupClosed, node: node, }); this.applyRule({ info: 'The VPC does not have an associated Flow Log - (Control IDs: 164.308(a)(3)(ii)(A), 164.312(b)).', explanation: 'The VPC flow logs provide detailed records for information about the IP traffic going to and from network interfaces in your Amazon Virtual Private Cloud (Amazon VPC). By default, the flow log record includes values for the different components of the IP flow, including the source, destination, and protocol.', level: NagMessageLevel.ERROR, rule: VPCFlowLogsEnabled, node: node, }); this.applyRule({ info: "The route table may contain one or more unrestricted route(s) to an IGW ('0.0.0.0/0' or '::/0') - (Control ID: 164.312(e)(1)).", explanation: 'Ensure Amazon EC2 route tables do not have unrestricted routes to an internet gateway. Removing or limiting the access to the internet for workloads within Amazon VPCs can reduce unintended access within your environment.', level: NagMessageLevel.ERROR, rule: VPCNoUnrestrictedRouteToIGW, node: node, }); this.applyRule({ info: 'The subnet auto-assigns public IP addresses - (Control IDs: 164.308(a)(3)(i), 164.308(a)(4)(ii)(A), 164.308(a)(4)(ii)(C), 164.312(a)(1), 164.312(e)(1)).', explanation: 'Manage access to the AWS Cloud by ensuring Amazon Virtual Private Cloud (VPC) subnets are not automatically assigned a public IP address. Amazon Elastic Compute Cloud (EC2) instances that are launched into subnets that have this attribute enabled have a public IP address assigned to their primary network interface.', level: NagMessageLevel.ERROR, rule: VPCSubnetAutoAssignPublicIpDisabled, node: node, }); } /** * Check WAF Resources * @param node the CfnResource to check * @param ignores list of ignores for the resource */ private checkWAF(node: CfnResource): void { this.applyRule({ info: 'The WAFv2 web ACL does not have logging enabled - (Control ID: 164.312(b)).', explanation: 'AWS WAF logging provides detailed information about the traffic that is analyzed by your web ACL. The logs record the time that AWS WAF received the request from your AWS resource, information about the request, and an action for the rule that each request matched.', level: NagMessageLevel.ERROR, rule: WAFv2LoggingEnabled, node: node, }); } }
the_stack
import * as Common from '../common/common.js'; import * as i18n from '../i18n/i18n.js'; import * as Root from '../root/root.js'; import type * as ProtocolProxyApi from '../../generated/protocol-proxy-api.js'; import * as Protocol from '../../generated/protocol.js'; import {DebuggerModel, Events as DebuggerModelEvents} from './DebuggerModel.js'; import type {DOMNode} from './DOMModel.js'; import {DeferredDOMNode, DOMModel, Events as DOMModelEvents} from './DOMModel.js'; import {OverlayPersistentHighlighter} from './OverlayPersistentHighlighter.js'; import type {RemoteObject} from './RemoteObject.js'; import type {Target} from './Target.js'; import {Capability} from './Target.js'; import {SDKModel} from './SDKModel.js'; import {TargetManager} from './TargetManager.js'; const UIStrings = { /** *@description Text in Overlay Model */ pausedInDebugger: 'Paused in debugger', }; const str_ = i18n.i18n.registerUIStrings('core/sdk/OverlayModel.ts', UIStrings); const i18nString = i18n.i18n.getLocalizedString.bind(undefined, str_); export interface HighlightColor { r: number; g: number; b: number; a: number; } export interface HighlightRect { x: number; y: number; width: number; height: number; color: HighlightColor; outlineColor: HighlightColor; } export interface Hinge { width: number; height: number; x: number; y: number; contentColor: HighlightColor; outlineColor: HighlightColor; } export class OverlayModel extends SDKModel<EventTypes> implements ProtocolProxyApi.OverlayDispatcher { readonly #domModel: DOMModel; overlayAgent: ProtocolProxyApi.OverlayApi; readonly #debuggerModel: DebuggerModel|null; #inspectModeEnabledInternal: boolean; #hideHighlightTimeout: number|null; #defaultHighlighter: Highlighter; #highlighter: Highlighter; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any #showPaintRectsSetting: Common.Settings.Setting<any>; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any #showLayoutShiftRegionsSetting: Common.Settings.Setting<any>; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any #showAdHighlightsSetting: Common.Settings.Setting<any>; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any #showDebugBordersSetting: Common.Settings.Setting<any>; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any #showFPSCounterSetting: Common.Settings.Setting<any>; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any #showScrollBottleneckRectsSetting: Common.Settings.Setting<any>; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any #showHitTestBordersSetting: Common.Settings.Setting<any>; // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any #showWebVitalsSetting: Common.Settings.Setting<any>; #registeredListeners: Common.EventTarget.EventDescriptor[]; #showViewportSizeOnResize: boolean; #persistentHighlighter: OverlayPersistentHighlighter|null; readonly #sourceOrderHighlighter: SourceOrderHighlighter; #sourceOrderModeActiveInternal: boolean; constructor(target: Target) { super(target); this.#domModel = (target.model(DOMModel) as DOMModel); target.registerOverlayDispatcher(this); this.overlayAgent = target.overlayAgent(); this.#debuggerModel = target.model(DebuggerModel); if (this.#debuggerModel) { Common.Settings.Settings.instance() .moduleSetting('disablePausedStateOverlay') .addChangeListener(this.updatePausedInDebuggerMessage, this); this.#debuggerModel.addEventListener( DebuggerModelEvents.DebuggerPaused, this.updatePausedInDebuggerMessage, this); this.#debuggerModel.addEventListener( DebuggerModelEvents.DebuggerResumed, this.updatePausedInDebuggerMessage, this); // TODO(dgozman): we should get DebuggerResumed on navigations instead of listening to GlobalObjectCleared. this.#debuggerModel.addEventListener( DebuggerModelEvents.GlobalObjectCleared, this.updatePausedInDebuggerMessage, this); } this.#inspectModeEnabledInternal = false; this.#hideHighlightTimeout = null; this.#defaultHighlighter = new DefaultHighlighter(this); this.#highlighter = this.#defaultHighlighter; this.#showPaintRectsSetting = Common.Settings.Settings.instance().moduleSetting('showPaintRects'); this.#showLayoutShiftRegionsSetting = Common.Settings.Settings.instance().moduleSetting('showLayoutShiftRegions'); this.#showAdHighlightsSetting = Common.Settings.Settings.instance().moduleSetting('showAdHighlights'); this.#showDebugBordersSetting = Common.Settings.Settings.instance().moduleSetting('showDebugBorders'); this.#showFPSCounterSetting = Common.Settings.Settings.instance().moduleSetting('showFPSCounter'); this.#showScrollBottleneckRectsSetting = Common.Settings.Settings.instance().moduleSetting('showScrollBottleneckRects'); this.#showHitTestBordersSetting = Common.Settings.Settings.instance().moduleSetting('showHitTestBorders'); this.#showWebVitalsSetting = Common.Settings.Settings.instance().moduleSetting('showWebVitals'); this.#registeredListeners = []; this.#showViewportSizeOnResize = true; if (!target.suspended()) { this.overlayAgent.invoke_enable(); this.wireAgentToSettings(); } this.#persistentHighlighter = new OverlayPersistentHighlighter(this); this.#domModel.addEventListener(DOMModelEvents.NodeRemoved, () => { this.#persistentHighlighter && this.#persistentHighlighter.refreshHighlights(); }); this.#domModel.addEventListener(DOMModelEvents.DocumentUpdated, () => { this.#persistentHighlighter && this.#persistentHighlighter.hideAllInOverlay(); }); this.#sourceOrderHighlighter = new SourceOrderHighlighter(this); this.#sourceOrderModeActiveInternal = false; } static highlightObjectAsDOMNode(object: RemoteObject): void { const domModel = object.runtimeModel().target().model(DOMModel); if (domModel) { domModel.overlayModel().highlightInOverlay({object, selectorList: undefined}); } } static hideDOMNodeHighlight(): void { for (const overlayModel of TargetManager.instance().models(OverlayModel)) { overlayModel.delayedHideHighlight(0); } } static async muteHighlight(): Promise<void[]> { return Promise.all(TargetManager.instance().models(OverlayModel).map(model => model.suspendModel())); } static async unmuteHighlight(): Promise<void[]> { return Promise.all(TargetManager.instance().models(OverlayModel).map(model => model.resumeModel())); } static highlightRect(rect: HighlightRect): void { for (const overlayModel of TargetManager.instance().models(OverlayModel)) { overlayModel.highlightRect(rect); } } static clearHighlight(): void { for (const overlayModel of TargetManager.instance().models(OverlayModel)) { overlayModel.clearHighlight(); } } getDOMModel(): DOMModel { return this.#domModel; } // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any highlightRect({x, y, width, height, color, outlineColor}: HighlightRect): Promise<any> { const highlightColor = color || {r: 255, g: 0, b: 255, a: 0.3}; const highlightOutlineColor = outlineColor || {r: 255, g: 0, b: 255, a: 0.5}; return this.overlayAgent.invoke_highlightRect( {x, y, width, height, color: highlightColor, outlineColor: highlightOutlineColor}); } // TODO(crbug.com/1172300) Ignored during the jsdoc to ts migration // eslint-disable-next-line @typescript-eslint/no-explicit-any clearHighlight(): Promise<any> { return this.overlayAgent.invoke_hideHighlight(); } private async wireAgentToSettings(): Promise<void> { this.#registeredListeners = [ this.#showPaintRectsSetting.addChangeListener( () => this.overlayAgent.invoke_setShowPaintRects({result: this.#showPaintRectsSetting.get()})), this.#showLayoutShiftRegionsSetting.addChangeListener( () => this.overlayAgent.invoke_setShowLayoutShiftRegions({result: this.#showLayoutShiftRegionsSetting.get()})), this.#showAdHighlightsSetting.addChangeListener( () => this.overlayAgent.invoke_setShowAdHighlights({show: this.#showAdHighlightsSetting.get()})), this.#showDebugBordersSetting.addChangeListener( () => this.overlayAgent.invoke_setShowDebugBorders({show: this.#showDebugBordersSetting.get()})), this.#showFPSCounterSetting.addChangeListener( () => this.overlayAgent.invoke_setShowFPSCounter({show: this.#showFPSCounterSetting.get()})), this.#showScrollBottleneckRectsSetting.addChangeListener( () => this.overlayAgent.invoke_setShowScrollBottleneckRects( {show: this.#showScrollBottleneckRectsSetting.get()})), this.#showHitTestBordersSetting.addChangeListener( () => this.overlayAgent.invoke_setShowHitTestBorders({show: this.#showHitTestBordersSetting.get()})), this.#showWebVitalsSetting.addChangeListener( () => this.overlayAgent.invoke_setShowWebVitals({show: this.#showWebVitalsSetting.get()})), ]; if (this.#showPaintRectsSetting.get()) { this.overlayAgent.invoke_setShowPaintRects({result: true}); } if (this.#showLayoutShiftRegionsSetting.get()) { this.overlayAgent.invoke_setShowLayoutShiftRegions({result: true}); } if (this.#showAdHighlightsSetting.get()) { this.overlayAgent.invoke_setShowAdHighlights({show: true}); } if (this.#showDebugBordersSetting.get()) { this.overlayAgent.invoke_setShowDebugBorders({show: true}); } if (this.#showFPSCounterSetting.get()) { this.overlayAgent.invoke_setShowFPSCounter({show: true}); } if (this.#showScrollBottleneckRectsSetting.get()) { this.overlayAgent.invoke_setShowScrollBottleneckRects({show: true}); } if (this.#showHitTestBordersSetting.get()) { this.overlayAgent.invoke_setShowHitTestBorders({show: true}); } if (this.#showWebVitalsSetting.get()) { this.overlayAgent.invoke_setShowWebVitals({show: true}); } if (this.#debuggerModel && this.#debuggerModel.isPaused()) { this.updatePausedInDebuggerMessage(); } await this.overlayAgent.invoke_setShowViewportSizeOnResize({show: this.#showViewportSizeOnResize}); } async suspendModel(): Promise<void> { Common.EventTarget.removeEventListeners(this.#registeredListeners); await this.overlayAgent.invoke_disable(); } async resumeModel(): Promise<void> { await Promise.all([this.overlayAgent.invoke_enable(), this.wireAgentToSettings()]); } setShowViewportSizeOnResize(show: boolean): void { if (this.#showViewportSizeOnResize === show) { return; } this.#showViewportSizeOnResize = show; if (this.target().suspended()) { return; } this.overlayAgent.invoke_setShowViewportSizeOnResize({show}); } private updatePausedInDebuggerMessage(): void { if (this.target().suspended()) { return; } const message = this.#debuggerModel && this.#debuggerModel.isPaused() && !Common.Settings.Settings.instance().moduleSetting('disablePausedStateOverlay').get() ? i18nString(UIStrings.pausedInDebugger) : undefined; this.overlayAgent.invoke_setPausedInDebuggerMessage({message}); } setHighlighter(highlighter: Highlighter|null): void { this.#highlighter = highlighter || this.#defaultHighlighter; } async setInspectMode(mode: Protocol.Overlay.InspectMode, showDetailedTooltip: boolean|undefined = true): Promise<void> { await this.#domModel.requestDocument(); this.#inspectModeEnabledInternal = mode !== Protocol.Overlay.InspectMode.None; this.dispatchEventToListeners(Events.InspectModeWillBeToggled, this); this.#highlighter.setInspectMode(mode, this.buildHighlightConfig('all', showDetailedTooltip)); } inspectModeEnabled(): boolean { return this.#inspectModeEnabledInternal; } highlightInOverlay(data: HighlightData, mode?: string, showInfo?: boolean): void { if (this.#sourceOrderModeActiveInternal) { // Return early if the source order is currently being shown the in the // overlay, so that it is not cleared by the highlight return; } if (this.#hideHighlightTimeout) { clearTimeout(this.#hideHighlightTimeout); this.#hideHighlightTimeout = null; } const highlightConfig = this.buildHighlightConfig(mode); if (typeof showInfo !== 'undefined') { highlightConfig.showInfo = showInfo; } this.#highlighter.highlightInOverlay(data, highlightConfig); } highlightInOverlayForTwoSeconds(data: HighlightData): void { this.highlightInOverlay(data); this.delayedHideHighlight(2000); } highlightGridInPersistentOverlay(nodeId: Protocol.DOM.NodeId): void { if (!this.#persistentHighlighter) { return; } this.#persistentHighlighter.highlightGridInOverlay(nodeId); this.dispatchEventToListeners(Events.PersistentGridOverlayStateChanged, {nodeId, enabled: true}); } isHighlightedGridInPersistentOverlay(nodeId: Protocol.DOM.NodeId): boolean { if (!this.#persistentHighlighter) { return false; } return this.#persistentHighlighter.isGridHighlighted(nodeId); } hideGridInPersistentOverlay(nodeId: Protocol.DOM.NodeId): void { if (!this.#persistentHighlighter) { return; } this.#persistentHighlighter.hideGridInOverlay(nodeId); this.dispatchEventToListeners(Events.PersistentGridOverlayStateChanged, {nodeId, enabled: false}); } highlightScrollSnapInPersistentOverlay(nodeId: Protocol.DOM.NodeId): void { if (!this.#persistentHighlighter) { return; } this.#persistentHighlighter.highlightScrollSnapInOverlay(nodeId); this.dispatchEventToListeners(Events.PersistentScrollSnapOverlayStateChanged, {nodeId, enabled: true}); } isHighlightedScrollSnapInPersistentOverlay(nodeId: Protocol.DOM.NodeId): boolean { if (!this.#persistentHighlighter) { return false; } return this.#persistentHighlighter.isScrollSnapHighlighted(nodeId); } hideScrollSnapInPersistentOverlay(nodeId: Protocol.DOM.NodeId): void { if (!this.#persistentHighlighter) { return; } this.#persistentHighlighter.hideScrollSnapInOverlay(nodeId); this.dispatchEventToListeners(Events.PersistentScrollSnapOverlayStateChanged, {nodeId, enabled: false}); } highlightFlexContainerInPersistentOverlay(nodeId: Protocol.DOM.NodeId): void { if (!this.#persistentHighlighter) { return; } this.#persistentHighlighter.highlightFlexInOverlay(nodeId); this.dispatchEventToListeners(Events.PersistentFlexContainerOverlayStateChanged, {nodeId, enabled: true}); } isHighlightedFlexContainerInPersistentOverlay(nodeId: Protocol.DOM.NodeId): boolean { if (!this.#persistentHighlighter) { return false; } return this.#persistentHighlighter.isFlexHighlighted(nodeId); } hideFlexContainerInPersistentOverlay(nodeId: Protocol.DOM.NodeId): void { if (!this.#persistentHighlighter) { return; } this.#persistentHighlighter.hideFlexInOverlay(nodeId); this.dispatchEventToListeners(Events.PersistentFlexContainerOverlayStateChanged, {nodeId, enabled: false}); } highlightContainerQueryInPersistentOverlay(nodeId: Protocol.DOM.NodeId): void { if (!this.#persistentHighlighter) { return; } this.#persistentHighlighter.highlightContainerQueryInOverlay(nodeId); this.dispatchEventToListeners(Events.PersistentContainerQueryOverlayStateChanged, {nodeId, enabled: true}); } isHighlightedContainerQueryInPersistentOverlay(nodeId: Protocol.DOM.NodeId): boolean { if (!this.#persistentHighlighter) { return false; } return this.#persistentHighlighter.isContainerQueryHighlighted(nodeId); } hideContainerQueryInPersistentOverlay(nodeId: Protocol.DOM.NodeId): void { if (!this.#persistentHighlighter) { return; } this.#persistentHighlighter.hideContainerQueryInOverlay(nodeId); this.dispatchEventToListeners(Events.PersistentContainerQueryOverlayStateChanged, {nodeId, enabled: false}); } highlightSourceOrderInOverlay(node: DOMNode): void { const sourceOrderConfig = { parentOutlineColor: Common.Color.SourceOrderHighlight.ParentOutline.toProtocolRGBA(), childOutlineColor: Common.Color.SourceOrderHighlight.ChildOutline.toProtocolRGBA(), }; this.#sourceOrderHighlighter.highlightSourceOrderInOverlay(node, sourceOrderConfig); } colorOfGridInPersistentOverlay(nodeId: Protocol.DOM.NodeId): string|null { if (!this.#persistentHighlighter) { return null; } return this.#persistentHighlighter.colorOfGrid(nodeId).asString(Common.Color.Format.HEX); } setColorOfGridInPersistentOverlay(nodeId: Protocol.DOM.NodeId, colorStr: string): void { if (!this.#persistentHighlighter) { return; } const color = Common.Color.Color.parse(colorStr); if (!color) { return; } this.#persistentHighlighter.setColorOfGrid(nodeId, color); this.#persistentHighlighter.resetOverlay(); } colorOfFlexInPersistentOverlay(nodeId: Protocol.DOM.NodeId): string|null { if (!this.#persistentHighlighter) { return null; } return this.#persistentHighlighter.colorOfFlex(nodeId).asString(Common.Color.Format.HEX); } setColorOfFlexInPersistentOverlay(nodeId: Protocol.DOM.NodeId, colorStr: string): void { if (!this.#persistentHighlighter) { return; } const color = Common.Color.Color.parse(colorStr); if (!color) { return; } this.#persistentHighlighter.setColorOfFlex(nodeId, color); this.#persistentHighlighter.resetOverlay(); } hideSourceOrderInOverlay(): void { this.#sourceOrderHighlighter.hideSourceOrderHighlight(); } setSourceOrderActive(isActive: boolean): void { this.#sourceOrderModeActiveInternal = isActive; } sourceOrderModeActive(): boolean { return this.#sourceOrderModeActiveInternal; } highlightIsolatedElementInPersistentOverlay(nodeId: Protocol.DOM.NodeId): void { if (!this.#persistentHighlighter) { return; } this.#persistentHighlighter.highlightIsolatedElementInOverlay(nodeId); } hideIsolatedElementInPersistentOverlay(nodeId: Protocol.DOM.NodeId): void { if (!this.#persistentHighlighter) { return; } this.#persistentHighlighter.hideIsolatedElementInOverlay(nodeId); } isHighlightedIsolatedElementInPersistentOverlay(nodeId: Protocol.DOM.NodeId): boolean { if (!this.#persistentHighlighter) { return false; } return this.#persistentHighlighter.isIsolatedElementHighlighted(nodeId); } private delayedHideHighlight(delay: number): void { if (this.#hideHighlightTimeout === null) { this.#hideHighlightTimeout = window.setTimeout(() => this.highlightInOverlay({clear: true}), delay); } } highlightFrame(frameId: Protocol.Page.FrameId): void { if (this.#hideHighlightTimeout) { clearTimeout(this.#hideHighlightTimeout); this.#hideHighlightTimeout = null; } this.#highlighter.highlightFrame(frameId); } showHingeForDualScreen(hinge: Hinge|null): void { if (hinge) { const {x, y, width, height, contentColor, outlineColor} = hinge; this.overlayAgent.invoke_setShowHinge({ hingeConfig: {rect: {x: x, y: y, width: width, height: height}, contentColor: contentColor, outlineColor: outlineColor}, }); } else { this.overlayAgent.invoke_setShowHinge({}); } } private buildHighlightConfig(mode: string|undefined = 'all', showDetailedToolip: boolean|undefined = false): Protocol.Overlay.HighlightConfig { const showRulers = Common.Settings.Settings.instance().moduleSetting('showMetricsRulers').get(); const colorFormat = Common.Settings.Settings.instance().moduleSetting('colorFormat').get(); const highlightConfig: Protocol.Overlay.HighlightConfig = { showInfo: mode === 'all' || mode === 'container-outline', showRulers: showRulers, showStyles: showDetailedToolip, showAccessibilityInfo: showDetailedToolip, showExtensionLines: showRulers, gridHighlightConfig: {}, flexContainerHighlightConfig: {}, flexItemHighlightConfig: {}, contrastAlgorithm: Root.Runtime.experiments.isEnabled('APCA') ? Protocol.Overlay.ContrastAlgorithm.Apca : Protocol.Overlay.ContrastAlgorithm.Aa, }; if (mode === 'all' || mode === 'content') { highlightConfig.contentColor = Common.Color.PageHighlight.Content.toProtocolRGBA(); } if (mode === 'all' || mode === 'padding') { highlightConfig.paddingColor = Common.Color.PageHighlight.Padding.toProtocolRGBA(); } if (mode === 'all' || mode === 'border') { highlightConfig.borderColor = Common.Color.PageHighlight.Border.toProtocolRGBA(); } if (mode === 'all' || mode === 'margin') { highlightConfig.marginColor = Common.Color.PageHighlight.Margin.toProtocolRGBA(); } if (mode === 'all') { highlightConfig.eventTargetColor = Common.Color.PageHighlight.EventTarget.toProtocolRGBA(); highlightConfig.shapeColor = Common.Color.PageHighlight.Shape.toProtocolRGBA(); highlightConfig.shapeMarginColor = Common.Color.PageHighlight.ShapeMargin.toProtocolRGBA(); highlightConfig.gridHighlightConfig = { rowGapColor: Common.Color.PageHighlight.GapBackground.toProtocolRGBA(), rowHatchColor: Common.Color.PageHighlight.GapHatch.toProtocolRGBA(), columnGapColor: Common.Color.PageHighlight.GapBackground.toProtocolRGBA(), columnHatchColor: Common.Color.PageHighlight.GapHatch.toProtocolRGBA(), rowLineColor: Common.Color.PageHighlight.LayoutLine.toProtocolRGBA(), columnLineColor: Common.Color.PageHighlight.LayoutLine.toProtocolRGBA(), rowLineDash: true, columnLineDash: true, }; highlightConfig.flexContainerHighlightConfig = { containerBorder: { color: Common.Color.PageHighlight.LayoutLine.toProtocolRGBA(), pattern: Protocol.Overlay.LineStylePattern.Dashed, }, itemSeparator: { color: Common.Color.PageHighlight.LayoutLine.toProtocolRGBA(), pattern: Protocol.Overlay.LineStylePattern.Dotted, }, lineSeparator: { color: Common.Color.PageHighlight.LayoutLine.toProtocolRGBA(), pattern: Protocol.Overlay.LineStylePattern.Dashed, }, mainDistributedSpace: { hatchColor: Common.Color.PageHighlight.GapHatch.toProtocolRGBA(), fillColor: Common.Color.PageHighlight.GapBackground.toProtocolRGBA(), }, crossDistributedSpace: { hatchColor: Common.Color.PageHighlight.GapHatch.toProtocolRGBA(), fillColor: Common.Color.PageHighlight.GapBackground.toProtocolRGBA(), }, rowGapSpace: { hatchColor: Common.Color.PageHighlight.GapHatch.toProtocolRGBA(), fillColor: Common.Color.PageHighlight.GapBackground.toProtocolRGBA(), }, columnGapSpace: { hatchColor: Common.Color.PageHighlight.GapHatch.toProtocolRGBA(), fillColor: Common.Color.PageHighlight.GapBackground.toProtocolRGBA(), }, }; highlightConfig.flexItemHighlightConfig = { baseSizeBox: { hatchColor: Common.Color.PageHighlight.GapHatch.toProtocolRGBA(), }, baseSizeBorder: { color: Common.Color.PageHighlight.LayoutLine.toProtocolRGBA(), pattern: Protocol.Overlay.LineStylePattern.Dotted, }, flexibilityArrow: { color: Common.Color.PageHighlight.LayoutLine.toProtocolRGBA(), }, }; } if (mode.endsWith('gap')) { highlightConfig.gridHighlightConfig = { gridBorderColor: Common.Color.PageHighlight.GridBorder.toProtocolRGBA(), gridBorderDash: true, }; if (mode === 'gap' || mode === 'row-gap') { highlightConfig.gridHighlightConfig.rowGapColor = Common.Color.PageHighlight.GapBackground.toProtocolRGBA(); highlightConfig.gridHighlightConfig.rowHatchColor = Common.Color.PageHighlight.GapHatch.toProtocolRGBA(); } if (mode === 'gap' || mode === 'column-gap') { highlightConfig.gridHighlightConfig.columnGapColor = Common.Color.PageHighlight.GapBackground.toProtocolRGBA(); highlightConfig.gridHighlightConfig.columnHatchColor = Common.Color.PageHighlight.GapHatch.toProtocolRGBA(); } } if (mode.endsWith('gap')) { highlightConfig.flexContainerHighlightConfig = { containerBorder: { color: Common.Color.PageHighlight.LayoutLine.toProtocolRGBA(), pattern: Protocol.Overlay.LineStylePattern.Dashed, }, }; if (mode === 'gap' || mode === 'row-gap') { highlightConfig.flexContainerHighlightConfig.rowGapSpace = { hatchColor: Common.Color.PageHighlight.GapHatch.toProtocolRGBA(), fillColor: Common.Color.PageHighlight.GapBackground.toProtocolRGBA(), }; } if (mode === 'gap' || mode === 'column-gap') { highlightConfig.flexContainerHighlightConfig.columnGapSpace = { hatchColor: Common.Color.PageHighlight.GapHatch.toProtocolRGBA(), fillColor: Common.Color.PageHighlight.GapBackground.toProtocolRGBA(), }; } } if (mode === 'grid-areas') { highlightConfig.gridHighlightConfig = { rowLineColor: Common.Color.PageHighlight.LayoutLine.toProtocolRGBA(), columnLineColor: Common.Color.PageHighlight.LayoutLine.toProtocolRGBA(), rowLineDash: true, columnLineDash: true, showAreaNames: true, areaBorderColor: Common.Color.PageHighlight.GridAreaBorder.toProtocolRGBA(), }; } if (mode === 'grid-template-columns') { highlightConfig.contentColor = Common.Color.PageHighlight.Content.toProtocolRGBA(); highlightConfig.gridHighlightConfig = { columnLineColor: Common.Color.PageHighlight.LayoutLine.toProtocolRGBA(), columnLineDash: true, }; } if (mode === 'grid-template-rows') { highlightConfig.contentColor = Common.Color.PageHighlight.Content.toProtocolRGBA(); highlightConfig.gridHighlightConfig = { rowLineColor: Common.Color.PageHighlight.LayoutLine.toProtocolRGBA(), rowLineDash: true, }; } if (mode === 'justify-content') { highlightConfig.flexContainerHighlightConfig = { containerBorder: { color: Common.Color.PageHighlight.LayoutLine.toProtocolRGBA(), pattern: Protocol.Overlay.LineStylePattern.Dashed, }, mainDistributedSpace: { hatchColor: Common.Color.PageHighlight.GapHatch.toProtocolRGBA(), fillColor: Common.Color.PageHighlight.GapBackground.toProtocolRGBA(), }, }; } if (mode === 'align-content') { highlightConfig.flexContainerHighlightConfig = { containerBorder: { color: Common.Color.PageHighlight.LayoutLine.toProtocolRGBA(), pattern: Protocol.Overlay.LineStylePattern.Dashed, }, crossDistributedSpace: { hatchColor: Common.Color.PageHighlight.GapHatch.toProtocolRGBA(), fillColor: Common.Color.PageHighlight.GapBackground.toProtocolRGBA(), }, }; } if (mode === 'align-items') { highlightConfig.flexContainerHighlightConfig = { containerBorder: { color: Common.Color.PageHighlight.LayoutLine.toProtocolRGBA(), pattern: Protocol.Overlay.LineStylePattern.Dashed, }, lineSeparator: { color: Common.Color.PageHighlight.LayoutLine.toProtocolRGBA(), pattern: Protocol.Overlay.LineStylePattern.Dashed, }, crossAlignment: {color: Common.Color.PageHighlight.LayoutLine.toProtocolRGBA()}, }; } if (mode === 'flexibility') { highlightConfig.flexItemHighlightConfig = { baseSizeBox: { hatchColor: Common.Color.PageHighlight.GapHatch.toProtocolRGBA(), }, baseSizeBorder: { color: Common.Color.PageHighlight.LayoutLine.toProtocolRGBA(), pattern: Protocol.Overlay.LineStylePattern.Dotted, }, flexibilityArrow: { color: Common.Color.PageHighlight.LayoutLine.toProtocolRGBA(), }, }; } if (mode === 'container-outline') { highlightConfig.containerQueryContainerHighlightConfig = { containerBorder: { color: Common.Color.PageHighlight.LayoutLine.toProtocolRGBA(), pattern: Protocol.Overlay.LineStylePattern.Dashed, }, }; } // the backend does not support the 'original' format because // it currently cannot retrieve the original format using computed styles const supportedColorFormats = new Set(['rgb', 'hsl', 'hex']); if (supportedColorFormats.has(colorFormat)) { highlightConfig.colorFormat = colorFormat; } return highlightConfig; } nodeHighlightRequested({nodeId}: Protocol.Overlay.NodeHighlightRequestedEvent): void { const node = this.#domModel.nodeForId(nodeId); if (node) { this.dispatchEventToListeners(Events.HighlightNodeRequested, node); } } static setInspectNodeHandler(handler: (arg0: DOMNode) => void): void { OverlayModel.inspectNodeHandler = handler; } inspectNodeRequested({backendNodeId}: Protocol.Overlay.InspectNodeRequestedEvent): void { const deferredNode = new DeferredDOMNode(this.target(), backendNodeId); if (OverlayModel.inspectNodeHandler) { deferredNode.resolvePromise().then(node => { if (node && OverlayModel.inspectNodeHandler) { OverlayModel.inspectNodeHandler(node); } }); } else { Common.Revealer.reveal(deferredNode); } this.dispatchEventToListeners(Events.ExitedInspectMode); } screenshotRequested({viewport}: Protocol.Overlay.ScreenshotRequestedEvent): void { this.dispatchEventToListeners(Events.ScreenshotRequested, viewport); this.dispatchEventToListeners(Events.ExitedInspectMode); } inspectModeCanceled(): void { this.dispatchEventToListeners(Events.ExitedInspectMode); } static inspectNodeHandler: ((node: DOMNode) => void)|null = null; getOverlayAgent(): ProtocolProxyApi.OverlayApi { return this.overlayAgent; } } // TODO(crbug.com/1167717): Make this a const enum again // eslint-disable-next-line rulesdir/const_enum export enum Events { InspectModeWillBeToggled = 'InspectModeWillBeToggled', ExitedInspectMode = 'InspectModeExited', HighlightNodeRequested = 'HighlightNodeRequested', ScreenshotRequested = 'ScreenshotRequested', PersistentGridOverlayStateChanged = 'PersistentGridOverlayStateChanged', PersistentFlexContainerOverlayStateChanged = 'PersistentFlexContainerOverlayStateChanged', PersistentScrollSnapOverlayStateChanged = 'PersistentScrollSnapOverlayStateChanged', PersistentContainerQueryOverlayStateChanged = 'PersistentContainerQueryOverlayStateChanged', } export interface ChangedNodeId { nodeId: number; enabled: boolean; } export type EventTypes = { [Events.InspectModeWillBeToggled]: OverlayModel, [Events.ExitedInspectMode]: void, [Events.HighlightNodeRequested]: DOMNode, [Events.ScreenshotRequested]: Protocol.Page.Viewport, [Events.PersistentGridOverlayStateChanged]: ChangedNodeId, [Events.PersistentFlexContainerOverlayStateChanged]: ChangedNodeId, [Events.PersistentScrollSnapOverlayStateChanged]: ChangedNodeId, [Events.PersistentContainerQueryOverlayStateChanged]: ChangedNodeId, }; export interface Highlighter { highlightInOverlay(data: HighlightData, config: Protocol.Overlay.HighlightConfig): void; setInspectMode(mode: Protocol.Overlay.InspectMode, config: Protocol.Overlay.HighlightConfig): Promise<void>; highlightFrame(frameId: Protocol.Page.FrameId): void; } class DefaultHighlighter implements Highlighter { readonly #model: OverlayModel; constructor(model: OverlayModel) { this.#model = model; } highlightInOverlay(data: HighlightData, highlightConfig: Protocol.Overlay.HighlightConfig): void { const {node, deferredNode, object, selectorList} = {node: undefined, deferredNode: undefined, object: undefined, selectorList: undefined, ...data}; const nodeId = node ? node.id : undefined; const backendNodeId = deferredNode ? deferredNode.backendNodeId() : undefined; const objectId = object ? object.objectId : undefined; if (nodeId || backendNodeId || objectId) { this.#model.target().overlayAgent().invoke_highlightNode( {highlightConfig, nodeId, backendNodeId, objectId, selector: selectorList}); } else { this.#model.target().overlayAgent().invoke_hideHighlight(); } } async setInspectMode(mode: Protocol.Overlay.InspectMode, highlightConfig: Protocol.Overlay.HighlightConfig): Promise<void> { await this.#model.target().overlayAgent().invoke_setInspectMode({mode, highlightConfig}); } highlightFrame(frameId: Protocol.Page.FrameId): void { this.#model.target().overlayAgent().invoke_highlightFrame({ frameId, contentColor: Common.Color.PageHighlight.Content.toProtocolRGBA(), contentOutlineColor: Common.Color.PageHighlight.ContentOutline.toProtocolRGBA(), }); } } export class SourceOrderHighlighter { readonly #model: OverlayModel; constructor(model: OverlayModel) { this.#model = model; } highlightSourceOrderInOverlay(node: DOMNode, sourceOrderConfig: Protocol.Overlay.SourceOrderConfig): void { this.#model.setSourceOrderActive(true); this.#model.setShowViewportSizeOnResize(false); this.#model.getOverlayAgent().invoke_highlightSourceOrder({sourceOrderConfig, nodeId: node.id}); } hideSourceOrderHighlight(): void { this.#model.setSourceOrderActive(false); this.#model.setShowViewportSizeOnResize(true); this.#model.clearHighlight(); } } SDKModel.register(OverlayModel, {capabilities: Capability.DOM, autostart: true}); export interface HighlightNodeData { node: DOMNode; selectorList?: string; } export interface HighlightDeferredNode { deferredNode: DeferredDOMNode; } export interface HighlightObjectData { object: RemoteObject; selectorList?: string; } export type HighlightData = HighlightNodeData|HighlightDeferredNode|HighlightObjectData|{clear: boolean};
the_stack
import * as path from "path"; import * as vscode from "vscode"; import getFrameworkSDKPathWithFallbacks from "./getFrameworkSDKPathWithFallbacks"; import BaseAsconfigTaskProvider from "./BaseAsconfigTaskProvider"; const ASCONFIG_JSON = "asconfig.json"; const FIELD_AIR_OPTIONS = "airOptions"; const FIELD_TARGET = "target"; const PLATFORM_IOS = "ios"; const PLATFORM_IOS_SIMULATOR = "ios_simulator"; const PLATFORM_ANDROID = "android"; const PLATFORM_AIR = "air"; const PLATFORM_WINDOWS = "windows"; const PLATFORM_MAC = "mac"; const TARGET_AIR = "air"; const TARGET_BUNDLE = "bundle"; const TARGET_NATIVE = "native"; const MATCHER = []; const TASK_TYPE_ACTIONSCRIPT = "actionscript"; const TASK_SOURCE_ACTIONSCRIPT = "ActionScript"; const TASK_SOURCE_AIR = "Adobe AIR"; const TASK_NAME_COMPILE_DEBUG = "compile debug"; const TASK_NAME_COMPILE_RELEASE = "compile release"; const TASK_NAME_CLEAN = "clean"; const TASK_NAME_PACKAGE_IOS_DEBUG = "package iOS debug"; const TASK_NAME_PACKAGE_IOS_RELEASE = "package iOS release"; const TASK_NAME_PACKAGE_IOS_SIMULATOR_DEBUG = "package iOS simulator debug"; const TASK_NAME_PACKAGE_IOS_SIMULATOR_RELEASE = "package iOS simulator release"; const TASK_NAME_PACKAGE_ANDROID_DEBUG = "package Android debug"; const TASK_NAME_PACKAGE_ANDROID_RELEASE = "package Android release"; const TASK_NAME_PACKAGE_DESKTOP_SHARED_DEBUG = "package desktop debug (shared runtime)"; const TASK_NAME_PACKAGE_DESKTOP_SHARED_RELEASE = "package desktop release (shared runtime)"; const TASK_NAME_PACKAGE_WINDOWS_SHARED_DEBUG = "package Windows debug (shared runtime)"; const TASK_NAME_PACKAGE_WINDOWS_SHARED_RELEASE = "package Windows release (shared runtime)"; const TASK_NAME_PACKAGE_MAC_SHARED_DEBUG = "package macOS debug (shared runtime)"; const TASK_NAME_PACKAGE_MAC_SHARED_RELEASE = "package macOS release (shared runtime)"; const TASK_NAME_PACKAGE_WINDOWS_CAPTIVE = "package Windows release (captive runtime)"; const TASK_NAME_PACKAGE_MAC_CAPTIVE = "package macOS release (captive runtime)"; const TASK_NAME_PACKAGE_WINDOWS_NATIVE = "package Windows release (native installer)"; const TASK_NAME_PACKAGE_MAC_NATIVE = "package macOS release (native installer)"; interface ActionScriptTaskDefinition extends vscode.TaskDefinition { type: typeof TASK_TYPE_ACTIONSCRIPT; debug?: boolean; air?: string; asconfig?: string; clean?: boolean; } export default class ActionScriptTaskProvider extends BaseAsconfigTaskProvider implements vscode.TaskProvider { protected provideTasksForASConfigJSON( jsonURI: vscode.Uri, workspaceFolder: vscode.WorkspaceFolder, result: vscode.Task[] ) { let isAnimate = false; let isAIRMobile = false; let isAIRDesktop = false; let isSharedOverride = false; let isRootTargetShared = false; let isRootTargetEmpty = false; let isRootTargetBundle = false; let isRootTargetNativeInstaller = false; let isWindowsOverrideBundle = false; let isMacOverrideBundle = false; let isWindowsOverrideNativeInstaller = false; let isMacOverrideNativeInstaller = false; let isWindowsOverrideShared = false; let isMacOverrideShared = false; let asconfigJson = this.readASConfigJSON(jsonURI); if (asconfigJson !== null) { isAnimate = this.isAnimate(asconfigJson); isAIRMobile = this.isAIRMobile(asconfigJson); if (!isAIRMobile) { isAIRDesktop = this.isAIRDesktop(asconfigJson); } if (isAIRDesktop) { isSharedOverride = this.isSharedOverride(asconfigJson); isRootTargetEmpty = this.isRootTargetEmpty(asconfigJson); isRootTargetShared = this.isRootTargetShared(asconfigJson); isRootTargetBundle = this.isRootTargetBundle(asconfigJson); isRootTargetNativeInstaller = this.isRootTargetNativeInstaller( asconfigJson ); isWindowsOverrideShared = this.isWindowsOverrideShared(asconfigJson); isMacOverrideShared = this.isMacOverrideShared(asconfigJson); isWindowsOverrideBundle = this.isWindowsOverrideBundle(asconfigJson); isMacOverrideBundle = this.isMacOverrideBundle(asconfigJson); isWindowsOverrideNativeInstaller = this.isWindowsOverrideNativeInstaller( asconfigJson ); isMacOverrideNativeInstaller = this.isMacOverrideNativeInstaller( asconfigJson ); } } let frameworkSDK = getFrameworkSDKPathWithFallbacks(); if (frameworkSDK === null) { //we don't have a valid SDK return; } let command = this.getCommand(workspaceFolder); if (isAnimate) { //handled by the Animate task provider return; } let taskNameSuffix = this.getTaskNameSuffix(jsonURI, workspaceFolder); //compile SWF or Royale JS with asconfigc result.push( this.getTask( `${TASK_NAME_COMPILE_DEBUG} - ${taskNameSuffix}`, jsonURI, workspaceFolder, command, frameworkSDK, true, null, isAIRDesktop || isAIRMobile ) ); result.push( this.getTask( `${TASK_NAME_COMPILE_RELEASE} - ${taskNameSuffix}`, jsonURI, workspaceFolder, command, frameworkSDK, false, null, false ) ); result.push( this.getCleanTask( `${TASK_NAME_CLEAN} - ${taskNameSuffix}`, jsonURI, workspaceFolder, command, frameworkSDK ) ); //package mobile AIR application if (isAIRMobile) { result.push( this.getTask( `${TASK_NAME_PACKAGE_IOS_DEBUG} - ${taskNameSuffix}`, jsonURI, workspaceFolder, command, frameworkSDK, true, PLATFORM_IOS, false ) ); result.push( this.getTask( `${TASK_NAME_PACKAGE_IOS_RELEASE} - ${taskNameSuffix}`, jsonURI, workspaceFolder, command, frameworkSDK, false, PLATFORM_IOS, false ) ); result.push( this.getTask( `${TASK_NAME_PACKAGE_IOS_SIMULATOR_DEBUG} - ${taskNameSuffix}`, jsonURI, workspaceFolder, command, frameworkSDK, true, PLATFORM_IOS_SIMULATOR, false ) ); result.push( this.getTask( `${TASK_NAME_PACKAGE_IOS_SIMULATOR_RELEASE} - ${taskNameSuffix}`, jsonURI, workspaceFolder, command, frameworkSDK, false, PLATFORM_IOS_SIMULATOR, false ) ); result.push( this.getTask( `${TASK_NAME_PACKAGE_ANDROID_DEBUG} - ${taskNameSuffix}`, jsonURI, workspaceFolder, command, frameworkSDK, true, PLATFORM_ANDROID, false ) ); result.push( this.getTask( `${TASK_NAME_PACKAGE_ANDROID_RELEASE} - ${taskNameSuffix}`, jsonURI, workspaceFolder, command, frameworkSDK, false, PLATFORM_ANDROID, false ) ); } //desktop platform targets are a little trickier because some can only //be built on certain platforms. windows can't package for mac, and mac //can't package for windows, for instance. //if the windows or mac section exists, we need to check its target //to determine what to display in the list of tasks. //captive runtime if (isWindowsOverrideBundle) { result.push( this.getTask( `${TASK_NAME_PACKAGE_WINDOWS_CAPTIVE} - ${taskNameSuffix}`, jsonURI, workspaceFolder, command, frameworkSDK, false, PLATFORM_WINDOWS, false ) ); } else if (isMacOverrideBundle) { result.push( this.getTask( `${TASK_NAME_PACKAGE_MAC_CAPTIVE} - ${taskNameSuffix}`, jsonURI, workspaceFolder, command, frameworkSDK, false, PLATFORM_MAC, false ) ); } //shared runtime with platform overrides else if (isWindowsOverrideShared) { result.push( this.getTask( `${TASK_NAME_PACKAGE_WINDOWS_SHARED_DEBUG} - ${taskNameSuffix}`, jsonURI, workspaceFolder, command, frameworkSDK, true, PLATFORM_WINDOWS, false ) ); result.push( this.getTask( `${TASK_NAME_PACKAGE_WINDOWS_SHARED_RELEASE} - ${taskNameSuffix}`, jsonURI, workspaceFolder, command, frameworkSDK, false, PLATFORM_WINDOWS, false ) ); } else if (isMacOverrideShared) { result.push( this.getTask( `${TASK_NAME_PACKAGE_MAC_SHARED_DEBUG} - ${taskNameSuffix}`, jsonURI, workspaceFolder, command, frameworkSDK, false, PLATFORM_MAC, false ) ); result.push( this.getTask( `${TASK_NAME_PACKAGE_MAC_SHARED_RELEASE} - ${taskNameSuffix}`, jsonURI, workspaceFolder, command, frameworkSDK, true, PLATFORM_MAC, false ) ); } //native installers else if (isWindowsOverrideNativeInstaller) { result.push( this.getTask( `${TASK_NAME_PACKAGE_WINDOWS_NATIVE} - ${taskNameSuffix}`, jsonURI, workspaceFolder, command, frameworkSDK, false, PLATFORM_WINDOWS, false ) ); } else if (isMacOverrideNativeInstaller) { result.push( this.getTask( `${TASK_NAME_PACKAGE_MAC_NATIVE} - ${taskNameSuffix}`, jsonURI, workspaceFolder, command, frameworkSDK, false, PLATFORM_MAC, false ) ); } //--- root target in airOptions //the root target is used if it hasn't been overridden for the current //desktop platform. if it is overridden, it should be skipped to avoid //duplicate items in the list. const isWindows = process.platform === "win32"; if ( isRootTargetNativeInstaller && ((isWindows && !isWindowsOverrideNativeInstaller) || (!isWindows && !isMacOverrideNativeInstaller)) ) { let taskName = isWindows ? TASK_NAME_PACKAGE_WINDOWS_NATIVE : TASK_NAME_PACKAGE_MAC_NATIVE; result.push( this.getTask( `${taskName} - ${taskNameSuffix}`, jsonURI, workspaceFolder, command, frameworkSDK, false, PLATFORM_AIR, false ) ); } if ( (isRootTargetBundle || isRootTargetEmpty) && ((isWindows && !isWindowsOverrideBundle) || (!isWindows && !isMacOverrideBundle)) ) { let taskName = isWindows ? TASK_NAME_PACKAGE_WINDOWS_CAPTIVE : TASK_NAME_PACKAGE_MAC_CAPTIVE; let airPlatform = PLATFORM_AIR; if (isRootTargetEmpty) { //this forces bundle airPlatform = isWindows ? PLATFORM_WINDOWS : PLATFORM_MAC; } result.push( this.getTask( `${taskName} - ${taskNameSuffix}`, jsonURI, workspaceFolder, command, frameworkSDK, false, airPlatform, false ) ); } if ( (isRootTargetShared || isRootTargetEmpty) && ((isWindows && !isWindowsOverrideShared) || (!isWindows && !isMacOverrideShared)) ) { result.push( this.getTask( `${TASK_NAME_PACKAGE_DESKTOP_SHARED_DEBUG} - ${taskNameSuffix}`, jsonURI, workspaceFolder, command, frameworkSDK, true, PLATFORM_AIR, false ) ); result.push( this.getTask( `${TASK_NAME_PACKAGE_DESKTOP_SHARED_RELEASE} - ${taskNameSuffix}`, jsonURI, workspaceFolder, command, frameworkSDK, false, PLATFORM_AIR, false ) ); } } private getTaskNameSuffix( jsonURI: vscode.Uri, workspaceFolder: vscode.WorkspaceFolder ): string { let suffix = ""; let workspaceFolders = vscode.workspace.workspaceFolders; if (workspaceFolders && workspaceFolders.length > 1) { suffix += workspaceFolder.name + "/"; } if (jsonURI) { suffix += jsonURI .toString() .substr(workspaceFolder.uri.toString().length + 1); } else { suffix += ASCONFIG_JSON; } return suffix; } private getTask( description: string, jsonURI: vscode.Uri, workspaceFolder: vscode.WorkspaceFolder, command: string[], sdk: string, debug: boolean, airPlatform: string, unpackageANEs: boolean ): vscode.Task { let asconfig: string = this.getASConfigValue(jsonURI, workspaceFolder.uri); let definition: ActionScriptTaskDefinition = { type: TASK_TYPE_ACTIONSCRIPT, debug, asconfig, }; if (airPlatform) { definition.air = airPlatform; } let options = ["--sdk", sdk]; if (debug) { options.push("--debug=true"); } else { options.push("--debug=false"); } if (jsonURI) { options.push("--project", jsonURI.fsPath); } if (airPlatform) { options.push("--air", airPlatform); } if (unpackageANEs) { options.push("--unpackage-anes=true"); } if ( vscode.workspace .getConfiguration("as3mxml") .get("asconfigc.verboseOutput") ) { options.push("--verbose=true"); } let jvmargs = vscode.workspace .getConfiguration("as3mxml") .get("asconfigc.jvmargs"); if (typeof jvmargs === "string") { options.push(`--jvmargs="${jvmargs}"`); } if (command.length > 1) { options.unshift(...command.slice(1)); } let source = airPlatform === null ? TASK_SOURCE_ACTIONSCRIPT : TASK_SOURCE_AIR; let execution = new vscode.ProcessExecution(command[0], options); let task = new vscode.Task( definition, workspaceFolder, description, source, execution, MATCHER ); task.group = vscode.TaskGroup.Build; return task; } private getCleanTask( description: string, jsonURI: vscode.Uri, workspaceFolder: vscode.WorkspaceFolder, command: string[], sdk: string ): vscode.Task { let asconfig: string = undefined; if (jsonURI) { let rootJSON = path.resolve(workspaceFolder.uri.fsPath, ASCONFIG_JSON); if (rootJSON !== jsonURI.fsPath) { //the asconfig field should remain empty if it's the root //asconfig.json in the workspace. //this is different than TypeScript because we didn't originally //create tasks for additional asconfig files in the workspace, and //we don't want to break old tasks.json files that already existed //before this feature was added. //ideally, we'd be able to use resolveTask() to populate the //asconfig field, but that function never seems to be called. asconfig = jsonURI .toString() .substr(workspaceFolder.uri.toString().length + 1); } } let definition: ActionScriptTaskDefinition = { type: TASK_TYPE_ACTIONSCRIPT, asconfig, clean: true, }; let options = ["--sdk", sdk, "--clean=true"]; if (jsonURI) { options.push("--project", jsonURI.fsPath); } if (command.length > 1) { options.unshift(...command.slice(1)); } let execution = new vscode.ProcessExecution(command[0], options); let task = new vscode.Task( definition, workspaceFolder, description, "ActionScript", execution, MATCHER ); task.group = vscode.TaskGroup.Build; return task; } private isWindowsOverrideShared(asconfigJson: any): boolean { if (process.platform !== "win32") { return false; } if (!(FIELD_AIR_OPTIONS in asconfigJson)) { return false; } let airOptions = asconfigJson[FIELD_AIR_OPTIONS]; if (!(PLATFORM_WINDOWS in airOptions)) { return false; } let windows = airOptions[PLATFORM_WINDOWS]; if (!(FIELD_TARGET in windows)) { //if target is omitted, defaults to bundle return false; } let target = windows[FIELD_TARGET]; return target === TARGET_AIR; } private isMacOverrideShared(asconfigJson: any): boolean { if (process.platform !== "darwin") { return false; } if (!(FIELD_AIR_OPTIONS in asconfigJson)) { return false; } let airOptions = asconfigJson[FIELD_AIR_OPTIONS]; if (!(PLATFORM_MAC in airOptions)) { return false; } let mac = airOptions[PLATFORM_MAC]; if (!(FIELD_TARGET in mac)) { //if target is omitted, defaults to bundle return false; } let target = mac[FIELD_TARGET]; return target === TARGET_AIR; } private isWindowsOverrideNativeInstaller(asconfigJson: any): boolean { if (process.platform !== "win32") { return false; } if (!(FIELD_AIR_OPTIONS in asconfigJson)) { return false; } let airOptions = asconfigJson[FIELD_AIR_OPTIONS]; if (!(PLATFORM_WINDOWS in airOptions)) { return false; } let windows = airOptions[PLATFORM_WINDOWS]; if (!(FIELD_TARGET in windows)) { //if target is omitted, defaults to bundle return false; } let target = windows[FIELD_TARGET]; return target === TARGET_NATIVE; } private isMacOverrideNativeInstaller(asconfigJson: any): boolean { if (process.platform !== "darwin") { return false; } if (!(FIELD_AIR_OPTIONS in asconfigJson)) { return false; } let airOptions = asconfigJson[FIELD_AIR_OPTIONS]; if (!(PLATFORM_MAC in airOptions)) { return false; } let mac = airOptions[PLATFORM_MAC]; if (!(FIELD_TARGET in mac)) { //if target is omitted, defaults to bundle return false; } let target = mac[FIELD_TARGET]; return target === TARGET_NATIVE; } private isSharedOverride(asconfigJson: any): boolean { if (!(FIELD_AIR_OPTIONS in asconfigJson)) { return false; } let airOptions = asconfigJson[FIELD_AIR_OPTIONS]; return PLATFORM_AIR in airOptions; } private isWindowsOverrideBundle(asconfigJson: any): boolean { if (process.platform !== "win32") { return false; } if (!(FIELD_AIR_OPTIONS in asconfigJson)) { return false; } let airOptions = asconfigJson[FIELD_AIR_OPTIONS]; if (!(PLATFORM_WINDOWS in airOptions)) { return false; } let windows = airOptions[PLATFORM_WINDOWS]; if (!(FIELD_TARGET in windows)) { //if target is omitted, default to bundle return true; } let target = windows[FIELD_TARGET]; return target === TARGET_BUNDLE; } private isMacOverrideBundle(asconfigJson: any): boolean { if (process.platform !== "darwin") { return false; } if (!(FIELD_AIR_OPTIONS in asconfigJson)) { return false; } let airOptions = asconfigJson[FIELD_AIR_OPTIONS]; if (!(PLATFORM_MAC in airOptions)) { return false; } let mac = airOptions[PLATFORM_MAC]; if (!(FIELD_TARGET in mac)) { //if target is omitted, default to bundle return true; } let target = mac[FIELD_TARGET]; return target === TARGET_BUNDLE; } private isRootTargetShared(asconfigJson: any): boolean { if (!(FIELD_AIR_OPTIONS in asconfigJson)) { //if no airOptions are specified at all, consider it shared runtime return this.isAIRDesktop(asconfigJson); } let airOptions = asconfigJson[FIELD_AIR_OPTIONS]; if (!(FIELD_TARGET in airOptions)) { //special case for mobile if (this.isAIRMobile(asconfigJson)) { return false; } //if target is omitted, defaults to air/shared return true; } let target = airOptions[FIELD_TARGET]; return target === TARGET_AIR; } private isRootTargetEmpty(asconfigJson: any): boolean { if (!(FIELD_AIR_OPTIONS in asconfigJson)) { //if no airOptions are specified at all, consider it shared runtime return this.isAIRDesktop(asconfigJson); } let airOptions = asconfigJson[FIELD_AIR_OPTIONS]; return !(FIELD_TARGET in airOptions); } private isRootTargetBundle(asconfigJson: any): boolean { if (!(FIELD_AIR_OPTIONS in asconfigJson)) { return false; } let airOptions = asconfigJson[FIELD_AIR_OPTIONS]; if (!(FIELD_TARGET in airOptions)) { //if target is omitted, defaults to air/shared return false; } let target = airOptions[FIELD_TARGET]; return target === TARGET_BUNDLE; } private isRootTargetNativeInstaller(asconfigJson: any): boolean { if (!(FIELD_AIR_OPTIONS in asconfigJson)) { return false; } let airOptions = asconfigJson[FIELD_AIR_OPTIONS]; if (!(FIELD_TARGET in airOptions)) { //if target is omitted, defaults to air/shared return false; } let target = airOptions[FIELD_TARGET]; return target === TARGET_NATIVE; } }
the_stack
import {Destination, DestinationConnectionStatus, DestinationOrigin, DestinationType, DuplexMode, MarginsType, PrinterType, PrintPreviewModelElement, PrintTicket, ScalingType, Size} from 'chrome://print/print_preview.js'; // <if expr="chromeos_ash or chromeos_lacros"> import {GooglePromotedDestinationId} from 'chrome://print/print_preview.js'; // </if> import {assert} from 'chrome://resources/js/assert.m.js'; // <if expr="chromeos_ash or chromeos_lacros"> import {loadTimeData} from 'chrome://resources/js/load_time_data.m.js'; // </if> import {flush} from 'chrome://resources/polymer/v3_0/polymer/polymer_bundled.min.js'; import {assertDeepEquals, assertEquals, assertFalse, assertNotEquals, assertTrue} from 'chrome://webui-test/chai_assert.js'; import {eventToPromise} from 'chrome://webui-test/test_util.js'; import {getCddTemplateWithAdvancedSettings} from './print_preview_test_utils.js'; const model_test = { suiteName: 'ModelTest', TestNames: { SetStickySettings: 'set sticky settings', SetPolicySettings: 'set policy settings', GetPrintTicket: 'get print ticket', GetCloudPrintTicket: 'get cloud print ticket', ChangeDestination: 'change destination', PrintToGoogleDriveCros: 'print to google drive cros', CddResetToDefault: 'CDD reset_to_default property', }, }; Object.assign(window, {model_test: model_test}); suite(model_test.suiteName, function() { let model: PrintPreviewModelElement; setup(function() { document.body.innerHTML = ''; model = document.createElement('print-preview-model'); document.body.appendChild(model); }); /** * Tests state restoration with all boolean settings set to true, scaling = * 90, dpi = 100, custom square paper, and custom margins. */ test(assert(model_test.TestNames.SetStickySettings), function() { // Default state of the model. const stickySettingsDefault: {[key: string]: any} = { version: 2, recentDestinations: [], dpi: {}, mediaSize: {}, marginsType: 0, /* default */ scaling: '100', scalingType: ScalingType.DEFAULT, scalingTypePdf: ScalingType.DEFAULT, isHeaderFooterEnabled: true, isCssBackgroundEnabled: false, isCollateEnabled: true, isDuplexEnabled: true, isDuplexShortEdge: false, isLandscapeEnabled: false, isColorEnabled: true, vendorOptions: {}, // <if expr="chromeos_ash or chromeos_lacros"> isPinEnabled: false, pinValue: '', // </if> }; // Non-default state const stickySettingsChange: {[key: string]: any} = { version: 2, recentDestinations: [], dpi: {horizontal_dpi: 1000, vertical_dpi: 500}, mediaSize: {width_microns: 43180, height_microns: 21590}, marginsType: 2, /* none */ scaling: '85', scalingType: ScalingType.CUSTOM, scalingTypePdf: ScalingType.FIT_TO_PAGE, isHeaderFooterEnabled: false, isCssBackgroundEnabled: true, isCollateEnabled: false, isDuplexEnabled: false, isDuplexShortEdge: true, isLandscapeEnabled: true, isColorEnabled: false, vendorOptions: { paperType: 1, printArea: 6, }, // <if expr="chromeos_ash or chromeos_lacros"> isPinEnabled: true, pinValue: '0000', // </if> }; const settingsSet = ['version']; /** * @param setting The name of the setting to check. * @param field The name of the field in the serialized state * corresponding to the setting. * @return Promise that resolves when the setting has been set, * the saved string has been validated, and the setting has been * reset to its default value. */ const testStickySetting = function( setting: string, field: string): Promise<void> { const promise = eventToPromise('sticky-setting-changed', model); model.setSetting(setting, stickySettingsChange[field]); settingsSet.push(field); return promise.then( /** * @param e Event containing the serialized settings * @return Promise that resolves when setting is reset. */ function(e: CustomEvent<string>): Promise<void> { const settings = JSON.parse(e.detail); Object.keys(stickySettingsDefault).forEach(settingName => { const set = settingsSet.includes(settingName); assertEquals(set, settings[settingName] !== undefined); if (set) { const toCompare = settingName === field ? stickySettingsChange : stickySettingsDefault; assertDeepEquals(toCompare[settingName], settings[settingName]); } }); const restorePromise = eventToPromise('sticky-setting-changed', model); model.setSetting(setting, stickySettingsDefault[field]); return restorePromise; }); }; model.applyStickySettings(); let promise = testStickySetting('collate', 'isCollateEnabled') .then(() => testStickySetting('color', 'isColorEnabled')) .then( () => testStickySetting( 'cssBackground', 'isCssBackgroundEnabled')) .then(() => testStickySetting('dpi', 'dpi')) .then(() => testStickySetting('duplex', 'isDuplexEnabled')) .then( () => testStickySetting('duplexShortEdge', 'isDuplexShortEdge')) .then( () => testStickySetting('headerFooter', 'isHeaderFooterEnabled')) .then(() => testStickySetting('layout', 'isLandscapeEnabled')) .then(() => testStickySetting('margins', 'marginsType')) .then(() => testStickySetting('mediaSize', 'mediaSize')) .then(() => testStickySetting('scaling', 'scaling')) .then(() => testStickySetting('scalingType', 'scalingType')) .then(() => testStickySetting('scalingTypePdf', 'scalingTypePdf')) .then(() => testStickySetting('vendorItems', 'vendorOptions')); // <if expr="chromeos_ash or chromeos_lacros"> promise = promise.then(() => testStickySetting('pin', 'isPinEnabled')) .then(() => testStickySetting('pinValue', 'pinValue')); // </if> return promise; }); /** * Tests that setSetting() won't change the value if there is already a * policy for that setting. */ test(assert(model_test.TestNames.SetPolicySettings), function() { model.setSetting('headerFooter', false); assertFalse(model.settings.headerFooter.value as boolean); // Sets to true, but doesn't mark as controlled by a policy. model.setPolicySettings({headerFooter: {defaultMode: true}}); model.setStickySettings(JSON.stringify({ version: 2, headerFooter: false, })); model.applyStickySettings(); assertTrue(model.settings.headerFooter.value as boolean); model.setSetting('headerFooter', false); assertFalse(model.settings.headerFooter.value as boolean); model.setPolicySettings({headerFooter: {allowedMode: true}}); model.applyStickySettings(); assertTrue(model.settings.headerFooter.value as boolean); model.setSetting('headerFooter', false); // The value didn't change after setSetting(), because the policy takes // priority. assertTrue(model.settings.headerFooter.value as boolean); }); function toggleSettings(testDestination: Destination) { const settingsChange: {[key: string]: any} = { pages: [2], copies: 2, collate: false, layout: true, color: false, mediaSize: testDestination.capabilities!.printer!.media_size!.option[1]!, margins: MarginsType.CUSTOM, customMargins: { marginTop: 100, marginRight: 200, marginBottom: 300, marginLeft: 400, }, dpi: { horizontal_dpi: 100, vertical_dpi: 100, }, scaling: '90', scalingType: ScalingType.CUSTOM, scalingTypePdf: ScalingType.CUSTOM, duplex: true, duplexShortEdge: true, cssBackground: true, selectionOnly: true, headerFooter: false, rasterize: true, vendorItems: { printArea: 6, paperType: 1, }, ranges: [{from: 2, to: 2}], // <if expr="chromeos_ash or chromeos_lacros"> pin: true, pinValue: '0000', // </if> }; // Update settings Object.keys(settingsChange).forEach(setting => { model.set(`settings.${setting}.value`, settingsChange[setting]); }); } function initializeModel() { model.documentSettings = { hasCssMediaStyles: false, hasSelection: true, isModifiable: true, isScalingDisabled: false, fitToPageScaling: 100, pageCount: 3, isFromArc: false, title: 'title', }; model.pageSize = new Size(612, 792); // Update pages accordingly. model.set('settings.pages.value', [1, 2, 3]); // Initialize some settings that don't have defaults to the destination // defaults. model.set('settings.dpi.value', {horizontal_dpi: 200, vertical_dpi: 200}); model.set('settings.vendorItems.value', {paperType: 0, printArea: 4}); // Set rasterize available so that it can be tested. model.set('settings.rasterize.available', true); } /** * Tests that toggling each setting results in the expected change to the * print ticket. */ test(assert(model_test.TestNames.GetPrintTicket), function() { // <if expr="chromeos_ash or chromeos_lacros"> const origin = DestinationOrigin.CROS; // </if> // <if expr="not chromeos and not lacros"> const origin = DestinationOrigin.LOCAL; // </if> const testDestination = new Destination( 'FooDevice', DestinationType.LOCAL, origin, 'FooName', DestinationConnectionStatus.ONLINE); testDestination.capabilities = getCddTemplateWithAdvancedSettings(2, 'FooDevice').capabilities; // <if expr="chromeos_ash or chromeos_lacros"> // Make device managed. It's used for testing pin setting behavior. loadTimeData.overrideValues({isEnterpriseManaged: true}); // </if> initializeModel(); model.destination = testDestination; const defaultTicket = model.createPrintTicket(testDestination, false, false); const expectedDefaultTicketObject: PrintTicket = { mediaSize: testDestination.capabilities!.printer!.media_size!.option[0]!, pageCount: 3, landscape: false, color: testDestination.getNativeColorModel(true), headerFooterEnabled: false, // Only used in print preview marginsType: MarginsType.DEFAULT, duplex: DuplexMode.SIMPLEX, copies: 1, collate: true, shouldPrintBackgrounds: false, shouldPrintSelectionOnly: false, previewModifiable: true, printToGoogleDrive: false, printerType: PrinterType.LOCAL_PRINTER, rasterizePDF: false, scaleFactor: 100, scalingType: ScalingType.DEFAULT, pagesPerSheet: 1, dpiHorizontal: 200, dpiVertical: 200, dpiDefault: true, deviceName: 'FooDevice', pageWidth: 612, pageHeight: 792, showSystemDialog: false, }; // <if expr="chromeos_ash or chromeos_lacros"> expectedDefaultTicketObject.advancedSettings = { printArea: 4, paperType: 0, }; // </if> assertEquals(JSON.stringify(expectedDefaultTicketObject), defaultTicket); // Toggle all the values and create a new print ticket. toggleSettings(testDestination); const newTicket = model.createPrintTicket(testDestination, false, false); const expectedNewTicketObject: PrintTicket = { mediaSize: testDestination.capabilities!.printer!.media_size!.option[1]!, pageCount: 1, landscape: true, color: testDestination.getNativeColorModel(false), headerFooterEnabled: false, marginsType: MarginsType.CUSTOM, duplex: DuplexMode.SHORT_EDGE, copies: 2, collate: false, shouldPrintBackgrounds: true, shouldPrintSelectionOnly: false, // Only for Print Preview. previewModifiable: true, printToGoogleDrive: false, printerType: PrinterType.LOCAL_PRINTER, rasterizePDF: true, scaleFactor: 90, scalingType: ScalingType.CUSTOM, pagesPerSheet: 1, dpiHorizontal: 100, dpiVertical: 100, dpiDefault: false, deviceName: 'FooDevice', pageWidth: 612, pageHeight: 792, showSystemDialog: false, marginsCustom: { marginTop: 100, marginRight: 200, marginBottom: 300, marginLeft: 400, }, }; // <if expr="chromeos_ash or chromeos_lacros"> expectedNewTicketObject.pinValue = '0000'; expectedNewTicketObject.advancedSettings = { printArea: 6, paperType: 1, }; // </if> assertEquals(JSON.stringify(expectedNewTicketObject), newTicket); }); /** * Tests that toggling each setting results in the expected change to the * cloud job print ticket. */ test(assert(model_test.TestNames.GetCloudPrintTicket), function() { initializeModel(); // Create a test cloud destination. const testDestination = new Destination( 'FooCloudDevice', DestinationType.GOOGLE, DestinationOrigin.COOKIES, 'FooCloudName', DestinationConnectionStatus.ONLINE); testDestination.capabilities = getCddTemplateWithAdvancedSettings(2, 'FooDevice').capabilities; model.destination = testDestination; const defaultTicket = model.createCloudJobTicket(testDestination); const expectedDefaultTicket = JSON.stringify({ version: '1.0', print: { collate: {collate: true}, color: { type: testDestination.getSelectedColorOption(true)!.type, }, copies: {copies: 1}, duplex: {type: 'NO_DUPLEX'}, media_size: { width_microns: 215900, height_microns: 279400, }, page_orientation: {type: 'PORTRAIT'}, dpi: { horizontal_dpi: 200, vertical_dpi: 200, }, vendor_ticket_item: [ {id: 'printArea', value: 4}, {id: 'paperType', value: 0}, ], }, }); assertEquals(expectedDefaultTicket, defaultTicket); // Toggle all the values and create a new cloud job ticket. toggleSettings(testDestination); const newTicket = model.createCloudJobTicket(testDestination); const expectedNewTicket = JSON.stringify({ version: '1.0', print: { collate: {collate: false}, color: { type: testDestination.getSelectedColorOption(false)!.type, }, copies: {copies: 2}, duplex: {type: 'SHORT_EDGE'}, media_size: { width_microns: 215900, height_microns: 215900, }, page_orientation: {type: 'LANDSCAPE'}, dpi: { horizontal_dpi: 100, vertical_dpi: 100, }, vendor_ticket_item: [ {id: 'printArea', value: 6}, {id: 'paperType', value: 1}, ], }, }); assertEquals(expectedNewTicket, newTicket); }); test(assert(model_test.TestNames.ChangeDestination), function() { const testDestination = new Destination( 'FooDevice', DestinationType.LOCAL, DestinationOrigin.LOCAL, 'FooName', DestinationConnectionStatus.ONLINE); testDestination.capabilities = getCddTemplateWithAdvancedSettings(2, 'FooDevice').capabilities; // Make black and white printing the default. testDestination.capabilities!.printer!.color = { option: [ {type: 'STANDARD_COLOR'}, {type: 'STANDARD_MONOCHROME', is_default: true} ] }; const testDestination2 = new Destination( 'BarDevice', DestinationType.LOCAL, DestinationOrigin.LOCAL, 'BarName', DestinationConnectionStatus.ONLINE); testDestination2.capabilities = Object.assign({}, testDestination.capabilities); // Initialize initializeModel(); model.destination = testDestination; model.applyStickySettings(); // Confirm some defaults. assertEquals(false, model.getSettingValue('color')); assertEquals('NA_LETTER', model.getSettingValue('mediaSize').name); assertEquals(200, model.getSettingValue('dpi').horizontal_dpi); assertEquals(false, model.getSettingValue('duplex')); // Toggle some printer specified settings. model.setSetting('duplex', true); model.setSetting( 'mediaSize', testDestination.capabilities!.printer!.media_size!.option[1]!); model.setSetting('color', true); model.setSetting( 'dpi', testDestination.capabilities!.printer!.dpi!.option[1]!); // Confirm toggles. assertEquals(true, model.getSettingValue('color')); assertEquals('CUSTOM', model.getSettingValue('mediaSize').name); assertEquals(100, model.getSettingValue('dpi').horizontal_dpi); assertEquals(true, model.getSettingValue('duplex')); // Set to a new destination with the same capabilities. Confirm that // everything stays the same. const oldSettings = JSON.stringify(model.settings); model.destination = testDestination2; const newSettings = JSON.stringify(model.settings); // Should be the same (same printer capabilities). assertEquals(oldSettings, newSettings); // Create a printer with different capabilities. const testDestination3 = new Destination( 'Device1', DestinationType.LOCAL, DestinationOrigin.LOCAL, 'One', DestinationConnectionStatus.ONLINE); testDestination3.capabilities = Object.assign({}, testDestination.capabilities); testDestination3.capabilities!.printer!.media_size = { option: [ { name: 'ISO_A4', width_microns: 210000, height_microns: 297000, custom_display_name: 'A4', is_default: true, }, ] }; testDestination3.capabilities!.printer!.color = { option: [ {type: 'STANDARD_MONOCHROME', is_default: true}, ] }; testDestination3.capabilities!.printer!.duplex = { option: [ {type: 'NO_DUPLEX', is_default: true}, ] }; testDestination3.capabilities!.printer!.dpi = { option: [ {horizontal_dpi: 400, vertical_dpi: 400, is_default: true}, {horizontal_dpi: 800, vertical_dpi: 800}, ] }; model.destination = testDestination3; flush(); // Verify things changed. const updatedSettings = JSON.stringify(model.settings); assertNotEquals(oldSettings, updatedSettings); assertEquals(false, model.getSettingValue('color')); assertEquals('ISO_A4', model.getSettingValue('mediaSize').name); assertEquals(400, model.getSettingValue('dpi').horizontal_dpi); assertEquals(false, model.getSettingValue('duplex')); }); // <if expr="chromeos_ash or chromeos_lacros"> // Tests that printToGoogleDrive is set correctly on the print ticket for Save // to Drive CrOS. test(assert(model_test.TestNames.PrintToGoogleDriveCros), function() { const driveDestination = new Destination( GooglePromotedDestinationId.SAVE_TO_DRIVE_CROS, DestinationType.LOCAL, DestinationOrigin.LOCAL, 'Save to Google Drive', DestinationConnectionStatus.ONLINE); initializeModel(); model.destination = driveDestination; const ticket = model.createPrintTicket(driveDestination, false, false); assertTrue(JSON.parse(ticket).printToGoogleDrive); }); // </if> /** * Tests the behaviour of the CDD attribute `reset_to_default`, specifically * that when a setting has a default value in CDD and the user selects another * value in the UI: * - if `reset_to_default`=true, the value of the setting will always be reset * to the CDD default. * - if `reset_to_default`=false, the value of the setting will always be read * from the sticky settings. */ test(assert(model_test.TestNames.CddResetToDefault), function() { const cddColorEnabled = true; const stickyColorEnabled = false; const cddDuplexEnabled = false; const stickyDuplexEnabled = true; const cddDpi = 200; const stickyDpi = 100; const cddMediaSizeDisplayName = 'CDD_NAME'; const stickyMediaSizeDisplayName = 'STICKY_NAME'; /** * Returns the CDD description of a destination with default values * specified for color, dpi, duplex and media size. * @param resetToDefault Whether the settings should * always reset to their default value or not. */ const getTestCapabilities = (resetToDefault: boolean) => { return { version: '1.0', printer: { color: { option: [ {type: 'STANDARD_COLOR', is_default: true}, {type: 'STANDARD_MONOCHROME'} ], reset_to_default: resetToDefault }, duplex: { option: [ {type: 'NO_DUPLEX', is_default: true}, {type: 'LONG_EDGE'}, {type: 'SHORT_EDGE'} ], reset_to_default: resetToDefault }, dpi: { option: [ { horizontal_dpi: cddDpi, vertical_dpi: cddDpi, is_default: true, }, {horizontal_dpi: stickyDpi, vertical_dpi: stickyDpi}, ], reset_to_default: resetToDefault }, media_size: { option: [ { name: 'NA_LETTER', width_microns: 215900, height_microns: 279400, is_default: true, custom_display_name: cddMediaSizeDisplayName, }, { name: 'CUSTOM', width_microns: 215900, height_microns: 215900, custom_display_name: stickyMediaSizeDisplayName, } ], reset_to_default: resetToDefault } } }; }; // Sticky settings that contain different values from the default values // returned by `getTestCapabilities`. const stickySettings = { version: 2, isColorEnabled: stickyColorEnabled, isDuplexEnabled: stickyDuplexEnabled, dpi: {horizontal_dpi: stickyDpi, vertical_dpi: stickyDpi}, mediaSize: { name: 'CUSTOM', width_microns: 215900, height_microns: 215900, custom_display_name: stickyMediaSizeDisplayName, }, }; const testDestination = new Destination( 'FooDevice', DestinationType.LOCAL, DestinationOrigin.EXTENSION, 'FooName', DestinationConnectionStatus.ONLINE); testDestination.capabilities = getTestCapabilities(/*resetToDefault=*/ true); initializeModel(); model.destination = testDestination; model.setStickySettings(JSON.stringify(stickySettings)); model.applyStickySettings(); assertEquals(model.settings.color.value, cddColorEnabled); assertEquals(model.settings.duplex.value, cddDuplexEnabled); assertEquals(model.settings.dpi.value.horizontal_dpi, cddDpi); assertEquals( model.settings.mediaSize.value.custom_display_name, cddMediaSizeDisplayName); testDestination.capabilities = getTestCapabilities(/*resetToDefault=*/ false); model.destination = testDestination; model.setStickySettings(JSON.stringify(stickySettings)); model.applyStickySettings(); assertEquals(model.settings.color.value, stickyColorEnabled); assertEquals(model.settings.duplex.value, stickyDuplexEnabled); assertEquals(model.settings.dpi.value.horizontal_dpi, stickyDpi); assertEquals( model.settings.mediaSize.value.custom_display_name, stickyMediaSizeDisplayName); const testDestination2 = new Destination( 'FooDevice2', DestinationType.LOCAL, DestinationOrigin.EXTENSION, 'FooName2', DestinationConnectionStatus.ONLINE); testDestination2.capabilities = getTestCapabilities(/*resetToDefault=*/ true); // Remove the `is_default` attribute from all the settings. delete testDestination2.capabilities!.printer!.color!.option[0]!.is_default; delete testDestination2.capabilities!.printer!.duplex!.option[0]! .is_default; delete testDestination2.capabilities!.printer!.media_size!.option[0]! .is_default; delete testDestination2.capabilities!.printer!.dpi!.option[0]!.is_default; model.destination = testDestination2; // Even if `reset_to_default` is true for all options, the model settings // should have values from the sticky settings because the CDD doesn't // specify default values to reset to. model.setStickySettings(JSON.stringify(stickySettings)); model.applyStickySettings(); assertEquals(model.settings.color.value, stickyColorEnabled); assertEquals(model.settings.duplex.value, stickyDuplexEnabled); assertEquals(model.settings.dpi.value.horizontal_dpi, stickyDpi); assertEquals( model.settings.mediaSize.value.custom_display_name, stickyMediaSizeDisplayName); }); });
the_stack
import * as assert from 'assert' import { waitTimeout } from './cli' import * as Selectors from './selectors' import { keys as Keys } from './keys' import { expectArray, expectText, getValueFromMonaco, expectYAMLSubset } from './util' import { AppAndCount, blockAfter } from './repl-expect' export const open = async (res: AppAndCount) => { await res.app.client .$(Selectors.SIDECAR(res.count, res.splitIndex)) .then(_ => _.waitForDisplayed({ timeout: waitTimeout })) return res } /** Same as open(), but in the block proceding the given block */ export function openInBlockAfter(res: AppAndCount, delta = 1) { return open(blockAfter(res, delta)) } export const notOpen = async (res: AppAndCount) => { await res.app.client .$(Selectors.SIDECAR(res.count, res.splitIndex)) .then(_ => _.waitForDisplayed({ timeout: waitTimeout, reverse: true })) return res } export const openWithFailure = async (res: AppAndCount) => { return res.app.client .$(Selectors.SIDECAR_WITH_FAILURE(res.count, res.splitIndex)) .then(_ => _.waitForDisplayed({ timeout: waitTimeout })) .then(() => res) } /** fully closed, not just minimized */ export const fullyClosed = async (res: AppAndCount) => { return res.app.client .$(Selectors.SIDECAR_FULLY_CLOSED(res.count, res.splitIndex)) .then(_ => _.waitForExist()) .then(() => res) } /** either minimized or fully closed */ export const closed = async (res: AppAndCount) => { return fullyClosed(res) } /** close the sidecar by ESCAPE key */ export const keyToClose = async (res: AppAndCount) => { await res.app.client.keys(Keys.ESCAPE) return closed(res) } /** Expect the given badge to exist in the sidecar header */ export const badge = (title: string, css?: string, absent = false) => async (res: AppAndCount) => { let iter = 0 await res.app.client.waitUntil( async () => { const badges = css ? await res.app.client.$(`${Selectors.SIDECAR_BADGES(res.count, res.splitIndex)} .${css}`) : await res.app.client.$(Selectors.SIDECAR_BADGES(res.count, res.splitIndex)) const badgeLabels = await badges.getText() const idx = badgeLabels.indexOf(title) if (++iter > 5) { console.error(`still waiting for sidebar badge title='${title}' actualBadges=${badgeLabels} idx=${idx}`) } return !absent ? idx >= 0 : idx < 0 }, { timeout: waitTimeout } ) return res } export const button = (button: { mode: string; label?: string }) => async (res: AppAndCount) => { await res.app.client .$(Selectors.SIDECAR_MODE_BUTTON(res.count, button.mode, res.splitIndex)) .then(_ => _.waitForDisplayed({ timeout: waitTimeout })) return res } export const mode = (expectedMode: string) => async (res: AppAndCount) => { await res.app.client.waitUntil( async () => { await res.app.client .$(`${Selectors.SIDECAR_MODE_BUTTON_SELECTED(res.count, expectedMode, res.splitIndex)}`) .then(_ => _.isDisplayed()) return true }, { timeout: waitTimeout } ) return res } export const toolbarText = (expect: { type: string; text: string; exact?: boolean; timeout?: number }) => async ( res: AppAndCount ) => { await expectText( res.app, expect.text, expect.exact || false, expect.timeout )(Selectors.SIDECAR_TOOLBAR_TEXT(res.count, expect.type, res.splitIndex)) return res } export const toolbarAlert = (expect: { type: string; text: string; exact?: boolean }) => async (res: AppAndCount) => { await expectText(res.app, expect.text, expect.exact)(Selectors.SIDECAR_ALERT(res.count, expect.type, res.splitIndex)) return res } const show = (expected: string, selector: string) => async (res: AppAndCount): Promise<AppAndCount> => { await res.app.client.waitUntil( async () => { return res.app.client .$(selector) .then(elt => elt.getText()) .then(text => text === expected) }, { timeout: waitTimeout } ) return res } export const name = (count: number, expectedName: string) => show(expectedName, Selectors.SIDECAR_TITLE(count)) export const heroName = (count: number, expectedName: string) => show(expectedName, Selectors.SIDECAR_HERO_TITLE(count)) export const namehash = (count: number, expectedNameHash: string) => show(expectedNameHash, Selectors.SIDECAR_ACTIVATION_TITLE(count)) export const namespace = (expectedNamespace: string) => async (res: AppAndCount) => show(expectedNamespace, Selectors.SIDECAR_PACKAGE_NAME_TITLE(res.count))(res) export const kind = (expectedKind: string) => async (res: AppAndCount) => show(expectedKind, Selectors.SIDECAR_KIND(res.count, res.splitIndex))(res) // expect sidecar tabs have correct `mode` and `label` export const modes = (expected: { mode: string; label?: string; dafaultMode?: boolean }[]) => async ( res: AppAndCount ) => Promise.all( expected.map(async _ => { await res.app.client.waitUntil( async () => { const actualModeSelector = `${Selectors.SIDECAR_MODE_BUTTON(res.count, _.mode, res.splitIndex)}` const actualMode = await res.app.client.$(actualModeSelector) await actualMode.waitForExist() if (_.label && (await actualMode.isDisplayed())) { const actualLabel = await actualMode.getText() return actualLabel.toLowerCase() === _.label.toLowerCase() } else { return true } }, { timeout: waitTimeout } ) }) ).then(() => res) // expect sidecar tab has the correct default tab export const defaultMode = (expected: { mode: string; label?: string }) => async (res: AppAndCount) => { await res.app.client.waitUntil( async () => { const actualModeSelector = `${Selectors.SIDECAR_MODE_BUTTON_SELECTED(res.count, expected.mode, res.splitIndex)}` const actualMode = await res.app.client.$(actualModeSelector) await actualMode.waitForDisplayed() if (expected.label) { const actualLabel = await actualMode.getText() return actualLabel.toLowerCase() === expected.label.toLowerCase() } else { return true } }, { timeout: waitTimeout } ) return res } export const textPlainContent = (content: string) => async (res: AppAndCount) => { await expectText(res.app, content)(Selectors.SIDECAR_CUSTOM_CONTENT(res.count, res.splitIndex)) return res } export const textPlainContentFromMonaco = (expectedText: string, exact = true) => async (res: AppAndCount) => { let idx = 0 await res.app.client.waitUntil( async () => { const actualText = await getValueFromMonaco(res) if (++idx > 5) { console.error(`still waiting for plain text from monaco actualText=${actualText} expectedText=${expectedText}`) } if (exact) { return actualText === expectedText } else { return actualText.indexOf(expectedText) >= 0 } }, { timeout: waitTimeout } ) return res } export async function tableContent(res: AppAndCount, nRows: number, nCells: number) { const rows = await res.app.client.$$(`${Selectors.SIDECAR_CUSTOM_CONTENT} tr`) assert.strictEqual(nRows, rows.length, 'nRows must match') const cells = await res.app.client.$$(`${Selectors.SIDECAR_CUSTOM_CONTENT} td`) assert.strictEqual(nCells, cells.length, 'nCells must match') } export const yaml = (content: object) => async (res: AppAndCount) => { await res.app.client.waitUntil( async () => { const ok: boolean = await getValueFromMonaco(res).then(expectYAMLSubset(content, false)) return ok }, { timeout: waitTimeout } ) return res } export async function popupTitle(res: AppAndCount, expectedTitle: string) { return res.app.client.waitUntil( async () => { const actualTitle = await res.app.client .$(Selectors.SIDECAR_POPUP_HERO_TITLE(res.count, res.splitIndex)) .then(_ => _.getText()) return actualTitle === expectedTitle }, { timeout: waitTimeout } ) } /** expect a form in the sidecar content */ export function form(form: Record<string, string>, idPrefix = 'kui-form') { return async (res: AppAndCount) => { await Promise.all( Object.keys(form).map(key => { return res.app.client.waitUntil( async () => { const expectedValue = form[key] const actualValue = await res.app.client .$(`${Selectors.SIDECAR_TAB_CONTENT} #${idPrefix}-${key}`) .then(_ => _.getValue()) return actualValue === expectedValue }, { timeout: waitTimeout } ) }) ) return res } } export const showing = ( expectedName: string, expectedActivationId?: string, expectSubstringMatchOnName?: boolean, expectedPackageName?: string, expectType?: string, waitThisLong?: number, which?: 'leftnav' | 'topnav', clickable?: boolean ) => async (res: AppAndCount): Promise<AppAndCount> => { await res.app.client.waitUntil( async () => { // check selected name in sidecar const sidecarSelector = `${Selectors.SIDECAR(res.count, res.splitIndex)}${ !expectType ? '' : '.entity-is-' + expectType }` await res.app.client.$(sidecarSelector).then(_ => _.waitForDisplayed({ timeout: waitThisLong || waitTimeout })) // either 'leftnav' or 'topnav' if (!which) { which = (await res.app.client.$(sidecarSelector).then(_ => _.getAttribute('data-view'))) as 'leftnav' | 'topnav' } const titleSelector = which === 'topnav' ? Selectors.SIDECAR_TITLE(res.count, res.splitIndex, clickable) : Selectors.SIDECAR_LEFTNAV_TITLE(res.count, res.splitIndex) return res.app.client .$(titleSelector) .then(_ => _.getText()) .then(name => { const nameMatches = expectSubstringMatchOnName ? name.indexOf(expectedName) >= 0 || expectedName.indexOf(name) >= 0 : name === expectedName if (nameMatches) { if (expectedPackageName) { return res.app.client .$(Selectors.SIDECAR_PACKAGE_NAME_TITLE(res.count, res.splitIndex)) .then(_ => _.getText()) .then(name => expectSubstringMatchOnName ? name.search(new RegExp(expectedPackageName, 'i')) >= 0 : name.toLowerCase() === expectedPackageName.toLowerCase() ) } else { return true } } }) }, { timeout: waitThisLong || waitTimeout, timeoutMsg: `expect action name ${expectedName} in sidecar substringOk? ${expectSubstringMatchOnName}` } ) if (expectedActivationId) { await res.app.client.waitUntil( async () => { try { const actualId = await res.app.client .$(Selectors.SIDECAR_ACTIVATION_TITLE(res.count, res.splitIndex)) .then(_ => _.getText()) if (actualId === expectedActivationId) { return true } else { console.error(`still waiting for nameHash; currently "${actualId}"; expecting "${expectedActivationId}"`) } } catch (err) { console.error(`error waiting for nameHash ${err.message}`, err) } }, { timeout: waitTimeout, timeoutMsg: `expect activation id ${expectedActivationId} in sidecar` } ) } return res } export const showingNotClickable = (expectedName: string, expectedPackageName?: string) => showing(expectedName, undefined, undefined, expectedPackageName, undefined, undefined, undefined, false) export const showingTopNav = (expectedName: string) => showing(expectedName, undefined, undefined, undefined, undefined, undefined, 'topnav') export const showingLeftNav = (expectedName: string) => showing(expectedName, undefined, undefined, undefined, undefined, undefined, 'leftnav') export function breadcrumbs(breadcrumbs: string[]) { return async (res: AppAndCount) => { const elts = await res.app.client.$$(Selectors.SIDECAR_BREADCRUMBS(res.count, res.splitIndex)) await Promise.all( elts.map(async elt => { await elt.waitForDisplayed() return elt.getText() }) ).then(expectArray(breadcrumbs)) return res } } /** Expect DescriptionList content in the current tab */ export const descriptionList = (content: Record<string, number | boolean | string>) => async (res: AppAndCount) => { const container = res.splitIndex !== undefined ? `${Selectors.PROMPT_BLOCK_N_FOR_SPLIT(res.count, res.splitIndex)} .kui--tab-content:not([hidden])` : `${Selectors.PROMPT_BLOCK_N(res.count)} .kui--tab-content:not([hidden])` for (const term in content) { let idx = 0 await res.app.client.waitUntil( async () => { const expectedDescription = content[term].toString() // the actualDescription will come as a string const actualDescription = await res.app.client .$(`${container} ${Selectors.DLIST_DESCRIPTION_FOR(term)}`) .then(_ => _.getText()) if (actualDescription !== expectedDescription) { if (++idx > 5) { console.error( `Still waiting for expectedDescription=${expectedDescription} actualDescription=${actualDescription} ` ) } return false } else { return true } }, { timeout: waitTimeout } ) } return res }
the_stack
import {Request} from '../lib/request'; import {Response} from '../lib/response'; import {AWSError} from '../lib/error'; import {Service} from '../lib/service'; import {ServiceConfigurationOptions} from '../lib/service'; import {ConfigBase as Config} from '../lib/config-base'; interface Blob {} declare class SSOAdmin extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: SSOAdmin.Types.ClientConfiguration) config: Config & SSOAdmin.Types.ClientConfiguration; /** * Attaches an IAM managed policy ARN to a permission set. If the permission set is already referenced by one or more account assignments, you will need to call ProvisionPermissionSet after this operation. Calling ProvisionPermissionSet applies the corresponding IAM policy updates to all assigned accounts. */ attachManagedPolicyToPermissionSet(params: SSOAdmin.Types.AttachManagedPolicyToPermissionSetRequest, callback?: (err: AWSError, data: SSOAdmin.Types.AttachManagedPolicyToPermissionSetResponse) => void): Request<SSOAdmin.Types.AttachManagedPolicyToPermissionSetResponse, AWSError>; /** * Attaches an IAM managed policy ARN to a permission set. If the permission set is already referenced by one or more account assignments, you will need to call ProvisionPermissionSet after this operation. Calling ProvisionPermissionSet applies the corresponding IAM policy updates to all assigned accounts. */ attachManagedPolicyToPermissionSet(callback?: (err: AWSError, data: SSOAdmin.Types.AttachManagedPolicyToPermissionSetResponse) => void): Request<SSOAdmin.Types.AttachManagedPolicyToPermissionSetResponse, AWSError>; /** * Assigns access to a principal for a specified Amazon Web Services account using a specified permission set. The term principal here refers to a user or group that is defined in Amazon Web Services SSO. As part of a successful CreateAccountAssignment call, the specified permission set will automatically be provisioned to the account in the form of an IAM policy. That policy is attached to the SSO-created IAM role. If the permission set is subsequently updated, the corresponding IAM policies attached to roles in your accounts will not be updated automatically. In this case, you must call ProvisionPermissionSet to make these updates. */ createAccountAssignment(params: SSOAdmin.Types.CreateAccountAssignmentRequest, callback?: (err: AWSError, data: SSOAdmin.Types.CreateAccountAssignmentResponse) => void): Request<SSOAdmin.Types.CreateAccountAssignmentResponse, AWSError>; /** * Assigns access to a principal for a specified Amazon Web Services account using a specified permission set. The term principal here refers to a user or group that is defined in Amazon Web Services SSO. As part of a successful CreateAccountAssignment call, the specified permission set will automatically be provisioned to the account in the form of an IAM policy. That policy is attached to the SSO-created IAM role. If the permission set is subsequently updated, the corresponding IAM policies attached to roles in your accounts will not be updated automatically. In this case, you must call ProvisionPermissionSet to make these updates. */ createAccountAssignment(callback?: (err: AWSError, data: SSOAdmin.Types.CreateAccountAssignmentResponse) => void): Request<SSOAdmin.Types.CreateAccountAssignmentResponse, AWSError>; /** * Enables the attributes-based access control (ABAC) feature for the specified Amazon Web Services SSO instance. You can also specify new attributes to add to your ABAC configuration during the enabling process. For more information about ABAC, see Attribute-Based Access Control in the Amazon Web Services SSO User Guide. */ createInstanceAccessControlAttributeConfiguration(params: SSOAdmin.Types.CreateInstanceAccessControlAttributeConfigurationRequest, callback?: (err: AWSError, data: SSOAdmin.Types.CreateInstanceAccessControlAttributeConfigurationResponse) => void): Request<SSOAdmin.Types.CreateInstanceAccessControlAttributeConfigurationResponse, AWSError>; /** * Enables the attributes-based access control (ABAC) feature for the specified Amazon Web Services SSO instance. You can also specify new attributes to add to your ABAC configuration during the enabling process. For more information about ABAC, see Attribute-Based Access Control in the Amazon Web Services SSO User Guide. */ createInstanceAccessControlAttributeConfiguration(callback?: (err: AWSError, data: SSOAdmin.Types.CreateInstanceAccessControlAttributeConfigurationResponse) => void): Request<SSOAdmin.Types.CreateInstanceAccessControlAttributeConfigurationResponse, AWSError>; /** * Creates a permission set within a specified SSO instance. To grant users and groups access to Amazon Web Services account resources, use CreateAccountAssignment . */ createPermissionSet(params: SSOAdmin.Types.CreatePermissionSetRequest, callback?: (err: AWSError, data: SSOAdmin.Types.CreatePermissionSetResponse) => void): Request<SSOAdmin.Types.CreatePermissionSetResponse, AWSError>; /** * Creates a permission set within a specified SSO instance. To grant users and groups access to Amazon Web Services account resources, use CreateAccountAssignment . */ createPermissionSet(callback?: (err: AWSError, data: SSOAdmin.Types.CreatePermissionSetResponse) => void): Request<SSOAdmin.Types.CreatePermissionSetResponse, AWSError>; /** * Deletes a principal's access from a specified Amazon Web Services account using a specified permission set. */ deleteAccountAssignment(params: SSOAdmin.Types.DeleteAccountAssignmentRequest, callback?: (err: AWSError, data: SSOAdmin.Types.DeleteAccountAssignmentResponse) => void): Request<SSOAdmin.Types.DeleteAccountAssignmentResponse, AWSError>; /** * Deletes a principal's access from a specified Amazon Web Services account using a specified permission set. */ deleteAccountAssignment(callback?: (err: AWSError, data: SSOAdmin.Types.DeleteAccountAssignmentResponse) => void): Request<SSOAdmin.Types.DeleteAccountAssignmentResponse, AWSError>; /** * Deletes the inline policy from a specified permission set. */ deleteInlinePolicyFromPermissionSet(params: SSOAdmin.Types.DeleteInlinePolicyFromPermissionSetRequest, callback?: (err: AWSError, data: SSOAdmin.Types.DeleteInlinePolicyFromPermissionSetResponse) => void): Request<SSOAdmin.Types.DeleteInlinePolicyFromPermissionSetResponse, AWSError>; /** * Deletes the inline policy from a specified permission set. */ deleteInlinePolicyFromPermissionSet(callback?: (err: AWSError, data: SSOAdmin.Types.DeleteInlinePolicyFromPermissionSetResponse) => void): Request<SSOAdmin.Types.DeleteInlinePolicyFromPermissionSetResponse, AWSError>; /** * Disables the attributes-based access control (ABAC) feature for the specified Amazon Web Services SSO instance and deletes all of the attribute mappings that have been configured. Once deleted, any attributes that are received from an identity source and any custom attributes you have previously configured will not be passed. For more information about ABAC, see Attribute-Based Access Control in the Amazon Web Services SSO User Guide. */ deleteInstanceAccessControlAttributeConfiguration(params: SSOAdmin.Types.DeleteInstanceAccessControlAttributeConfigurationRequest, callback?: (err: AWSError, data: SSOAdmin.Types.DeleteInstanceAccessControlAttributeConfigurationResponse) => void): Request<SSOAdmin.Types.DeleteInstanceAccessControlAttributeConfigurationResponse, AWSError>; /** * Disables the attributes-based access control (ABAC) feature for the specified Amazon Web Services SSO instance and deletes all of the attribute mappings that have been configured. Once deleted, any attributes that are received from an identity source and any custom attributes you have previously configured will not be passed. For more information about ABAC, see Attribute-Based Access Control in the Amazon Web Services SSO User Guide. */ deleteInstanceAccessControlAttributeConfiguration(callback?: (err: AWSError, data: SSOAdmin.Types.DeleteInstanceAccessControlAttributeConfigurationResponse) => void): Request<SSOAdmin.Types.DeleteInstanceAccessControlAttributeConfigurationResponse, AWSError>; /** * Deletes the specified permission set. */ deletePermissionSet(params: SSOAdmin.Types.DeletePermissionSetRequest, callback?: (err: AWSError, data: SSOAdmin.Types.DeletePermissionSetResponse) => void): Request<SSOAdmin.Types.DeletePermissionSetResponse, AWSError>; /** * Deletes the specified permission set. */ deletePermissionSet(callback?: (err: AWSError, data: SSOAdmin.Types.DeletePermissionSetResponse) => void): Request<SSOAdmin.Types.DeletePermissionSetResponse, AWSError>; /** * Describes the status of the assignment creation request. */ describeAccountAssignmentCreationStatus(params: SSOAdmin.Types.DescribeAccountAssignmentCreationStatusRequest, callback?: (err: AWSError, data: SSOAdmin.Types.DescribeAccountAssignmentCreationStatusResponse) => void): Request<SSOAdmin.Types.DescribeAccountAssignmentCreationStatusResponse, AWSError>; /** * Describes the status of the assignment creation request. */ describeAccountAssignmentCreationStatus(callback?: (err: AWSError, data: SSOAdmin.Types.DescribeAccountAssignmentCreationStatusResponse) => void): Request<SSOAdmin.Types.DescribeAccountAssignmentCreationStatusResponse, AWSError>; /** * Describes the status of the assignment deletion request. */ describeAccountAssignmentDeletionStatus(params: SSOAdmin.Types.DescribeAccountAssignmentDeletionStatusRequest, callback?: (err: AWSError, data: SSOAdmin.Types.DescribeAccountAssignmentDeletionStatusResponse) => void): Request<SSOAdmin.Types.DescribeAccountAssignmentDeletionStatusResponse, AWSError>; /** * Describes the status of the assignment deletion request. */ describeAccountAssignmentDeletionStatus(callback?: (err: AWSError, data: SSOAdmin.Types.DescribeAccountAssignmentDeletionStatusResponse) => void): Request<SSOAdmin.Types.DescribeAccountAssignmentDeletionStatusResponse, AWSError>; /** * Returns the list of Amazon Web Services SSO identity store attributes that have been configured to work with attributes-based access control (ABAC) for the specified Amazon Web Services SSO instance. This will not return attributes configured and sent by an external identity provider. For more information about ABAC, see Attribute-Based Access Control in the Amazon Web Services SSO User Guide. */ describeInstanceAccessControlAttributeConfiguration(params: SSOAdmin.Types.DescribeInstanceAccessControlAttributeConfigurationRequest, callback?: (err: AWSError, data: SSOAdmin.Types.DescribeInstanceAccessControlAttributeConfigurationResponse) => void): Request<SSOAdmin.Types.DescribeInstanceAccessControlAttributeConfigurationResponse, AWSError>; /** * Returns the list of Amazon Web Services SSO identity store attributes that have been configured to work with attributes-based access control (ABAC) for the specified Amazon Web Services SSO instance. This will not return attributes configured and sent by an external identity provider. For more information about ABAC, see Attribute-Based Access Control in the Amazon Web Services SSO User Guide. */ describeInstanceAccessControlAttributeConfiguration(callback?: (err: AWSError, data: SSOAdmin.Types.DescribeInstanceAccessControlAttributeConfigurationResponse) => void): Request<SSOAdmin.Types.DescribeInstanceAccessControlAttributeConfigurationResponse, AWSError>; /** * Gets the details of the permission set. */ describePermissionSet(params: SSOAdmin.Types.DescribePermissionSetRequest, callback?: (err: AWSError, data: SSOAdmin.Types.DescribePermissionSetResponse) => void): Request<SSOAdmin.Types.DescribePermissionSetResponse, AWSError>; /** * Gets the details of the permission set. */ describePermissionSet(callback?: (err: AWSError, data: SSOAdmin.Types.DescribePermissionSetResponse) => void): Request<SSOAdmin.Types.DescribePermissionSetResponse, AWSError>; /** * Describes the status for the given permission set provisioning request. */ describePermissionSetProvisioningStatus(params: SSOAdmin.Types.DescribePermissionSetProvisioningStatusRequest, callback?: (err: AWSError, data: SSOAdmin.Types.DescribePermissionSetProvisioningStatusResponse) => void): Request<SSOAdmin.Types.DescribePermissionSetProvisioningStatusResponse, AWSError>; /** * Describes the status for the given permission set provisioning request. */ describePermissionSetProvisioningStatus(callback?: (err: AWSError, data: SSOAdmin.Types.DescribePermissionSetProvisioningStatusResponse) => void): Request<SSOAdmin.Types.DescribePermissionSetProvisioningStatusResponse, AWSError>; /** * Detaches the attached IAM managed policy ARN from the specified permission set. */ detachManagedPolicyFromPermissionSet(params: SSOAdmin.Types.DetachManagedPolicyFromPermissionSetRequest, callback?: (err: AWSError, data: SSOAdmin.Types.DetachManagedPolicyFromPermissionSetResponse) => void): Request<SSOAdmin.Types.DetachManagedPolicyFromPermissionSetResponse, AWSError>; /** * Detaches the attached IAM managed policy ARN from the specified permission set. */ detachManagedPolicyFromPermissionSet(callback?: (err: AWSError, data: SSOAdmin.Types.DetachManagedPolicyFromPermissionSetResponse) => void): Request<SSOAdmin.Types.DetachManagedPolicyFromPermissionSetResponse, AWSError>; /** * Obtains the inline policy assigned to the permission set. */ getInlinePolicyForPermissionSet(params: SSOAdmin.Types.GetInlinePolicyForPermissionSetRequest, callback?: (err: AWSError, data: SSOAdmin.Types.GetInlinePolicyForPermissionSetResponse) => void): Request<SSOAdmin.Types.GetInlinePolicyForPermissionSetResponse, AWSError>; /** * Obtains the inline policy assigned to the permission set. */ getInlinePolicyForPermissionSet(callback?: (err: AWSError, data: SSOAdmin.Types.GetInlinePolicyForPermissionSetResponse) => void): Request<SSOAdmin.Types.GetInlinePolicyForPermissionSetResponse, AWSError>; /** * Lists the status of the Amazon Web Services account assignment creation requests for a specified SSO instance. */ listAccountAssignmentCreationStatus(params: SSOAdmin.Types.ListAccountAssignmentCreationStatusRequest, callback?: (err: AWSError, data: SSOAdmin.Types.ListAccountAssignmentCreationStatusResponse) => void): Request<SSOAdmin.Types.ListAccountAssignmentCreationStatusResponse, AWSError>; /** * Lists the status of the Amazon Web Services account assignment creation requests for a specified SSO instance. */ listAccountAssignmentCreationStatus(callback?: (err: AWSError, data: SSOAdmin.Types.ListAccountAssignmentCreationStatusResponse) => void): Request<SSOAdmin.Types.ListAccountAssignmentCreationStatusResponse, AWSError>; /** * Lists the status of the Amazon Web Services account assignment deletion requests for a specified SSO instance. */ listAccountAssignmentDeletionStatus(params: SSOAdmin.Types.ListAccountAssignmentDeletionStatusRequest, callback?: (err: AWSError, data: SSOAdmin.Types.ListAccountAssignmentDeletionStatusResponse) => void): Request<SSOAdmin.Types.ListAccountAssignmentDeletionStatusResponse, AWSError>; /** * Lists the status of the Amazon Web Services account assignment deletion requests for a specified SSO instance. */ listAccountAssignmentDeletionStatus(callback?: (err: AWSError, data: SSOAdmin.Types.ListAccountAssignmentDeletionStatusResponse) => void): Request<SSOAdmin.Types.ListAccountAssignmentDeletionStatusResponse, AWSError>; /** * Lists the assignee of the specified Amazon Web Services account with the specified permission set. */ listAccountAssignments(params: SSOAdmin.Types.ListAccountAssignmentsRequest, callback?: (err: AWSError, data: SSOAdmin.Types.ListAccountAssignmentsResponse) => void): Request<SSOAdmin.Types.ListAccountAssignmentsResponse, AWSError>; /** * Lists the assignee of the specified Amazon Web Services account with the specified permission set. */ listAccountAssignments(callback?: (err: AWSError, data: SSOAdmin.Types.ListAccountAssignmentsResponse) => void): Request<SSOAdmin.Types.ListAccountAssignmentsResponse, AWSError>; /** * Lists all the Amazon Web Services accounts where the specified permission set is provisioned. */ listAccountsForProvisionedPermissionSet(params: SSOAdmin.Types.ListAccountsForProvisionedPermissionSetRequest, callback?: (err: AWSError, data: SSOAdmin.Types.ListAccountsForProvisionedPermissionSetResponse) => void): Request<SSOAdmin.Types.ListAccountsForProvisionedPermissionSetResponse, AWSError>; /** * Lists all the Amazon Web Services accounts where the specified permission set is provisioned. */ listAccountsForProvisionedPermissionSet(callback?: (err: AWSError, data: SSOAdmin.Types.ListAccountsForProvisionedPermissionSetResponse) => void): Request<SSOAdmin.Types.ListAccountsForProvisionedPermissionSetResponse, AWSError>; /** * Lists the SSO instances that the caller has access to. */ listInstances(params: SSOAdmin.Types.ListInstancesRequest, callback?: (err: AWSError, data: SSOAdmin.Types.ListInstancesResponse) => void): Request<SSOAdmin.Types.ListInstancesResponse, AWSError>; /** * Lists the SSO instances that the caller has access to. */ listInstances(callback?: (err: AWSError, data: SSOAdmin.Types.ListInstancesResponse) => void): Request<SSOAdmin.Types.ListInstancesResponse, AWSError>; /** * Lists the IAM managed policy that is attached to a specified permission set. */ listManagedPoliciesInPermissionSet(params: SSOAdmin.Types.ListManagedPoliciesInPermissionSetRequest, callback?: (err: AWSError, data: SSOAdmin.Types.ListManagedPoliciesInPermissionSetResponse) => void): Request<SSOAdmin.Types.ListManagedPoliciesInPermissionSetResponse, AWSError>; /** * Lists the IAM managed policy that is attached to a specified permission set. */ listManagedPoliciesInPermissionSet(callback?: (err: AWSError, data: SSOAdmin.Types.ListManagedPoliciesInPermissionSetResponse) => void): Request<SSOAdmin.Types.ListManagedPoliciesInPermissionSetResponse, AWSError>; /** * Lists the status of the permission set provisioning requests for a specified SSO instance. */ listPermissionSetProvisioningStatus(params: SSOAdmin.Types.ListPermissionSetProvisioningStatusRequest, callback?: (err: AWSError, data: SSOAdmin.Types.ListPermissionSetProvisioningStatusResponse) => void): Request<SSOAdmin.Types.ListPermissionSetProvisioningStatusResponse, AWSError>; /** * Lists the status of the permission set provisioning requests for a specified SSO instance. */ listPermissionSetProvisioningStatus(callback?: (err: AWSError, data: SSOAdmin.Types.ListPermissionSetProvisioningStatusResponse) => void): Request<SSOAdmin.Types.ListPermissionSetProvisioningStatusResponse, AWSError>; /** * Lists the PermissionSets in an SSO instance. */ listPermissionSets(params: SSOAdmin.Types.ListPermissionSetsRequest, callback?: (err: AWSError, data: SSOAdmin.Types.ListPermissionSetsResponse) => void): Request<SSOAdmin.Types.ListPermissionSetsResponse, AWSError>; /** * Lists the PermissionSets in an SSO instance. */ listPermissionSets(callback?: (err: AWSError, data: SSOAdmin.Types.ListPermissionSetsResponse) => void): Request<SSOAdmin.Types.ListPermissionSetsResponse, AWSError>; /** * Lists all the permission sets that are provisioned to a specified Amazon Web Services account. */ listPermissionSetsProvisionedToAccount(params: SSOAdmin.Types.ListPermissionSetsProvisionedToAccountRequest, callback?: (err: AWSError, data: SSOAdmin.Types.ListPermissionSetsProvisionedToAccountResponse) => void): Request<SSOAdmin.Types.ListPermissionSetsProvisionedToAccountResponse, AWSError>; /** * Lists all the permission sets that are provisioned to a specified Amazon Web Services account. */ listPermissionSetsProvisionedToAccount(callback?: (err: AWSError, data: SSOAdmin.Types.ListPermissionSetsProvisionedToAccountResponse) => void): Request<SSOAdmin.Types.ListPermissionSetsProvisionedToAccountResponse, AWSError>; /** * Lists the tags that are attached to a specified resource. */ listTagsForResource(params: SSOAdmin.Types.ListTagsForResourceRequest, callback?: (err: AWSError, data: SSOAdmin.Types.ListTagsForResourceResponse) => void): Request<SSOAdmin.Types.ListTagsForResourceResponse, AWSError>; /** * Lists the tags that are attached to a specified resource. */ listTagsForResource(callback?: (err: AWSError, data: SSOAdmin.Types.ListTagsForResourceResponse) => void): Request<SSOAdmin.Types.ListTagsForResourceResponse, AWSError>; /** * The process by which a specified permission set is provisioned to the specified target. */ provisionPermissionSet(params: SSOAdmin.Types.ProvisionPermissionSetRequest, callback?: (err: AWSError, data: SSOAdmin.Types.ProvisionPermissionSetResponse) => void): Request<SSOAdmin.Types.ProvisionPermissionSetResponse, AWSError>; /** * The process by which a specified permission set is provisioned to the specified target. */ provisionPermissionSet(callback?: (err: AWSError, data: SSOAdmin.Types.ProvisionPermissionSetResponse) => void): Request<SSOAdmin.Types.ProvisionPermissionSetResponse, AWSError>; /** * Attaches an IAM inline policy to a permission set. If the permission set is already referenced by one or more account assignments, you will need to call ProvisionPermissionSet after this action to apply the corresponding IAM policy updates to all assigned accounts. */ putInlinePolicyToPermissionSet(params: SSOAdmin.Types.PutInlinePolicyToPermissionSetRequest, callback?: (err: AWSError, data: SSOAdmin.Types.PutInlinePolicyToPermissionSetResponse) => void): Request<SSOAdmin.Types.PutInlinePolicyToPermissionSetResponse, AWSError>; /** * Attaches an IAM inline policy to a permission set. If the permission set is already referenced by one or more account assignments, you will need to call ProvisionPermissionSet after this action to apply the corresponding IAM policy updates to all assigned accounts. */ putInlinePolicyToPermissionSet(callback?: (err: AWSError, data: SSOAdmin.Types.PutInlinePolicyToPermissionSetResponse) => void): Request<SSOAdmin.Types.PutInlinePolicyToPermissionSetResponse, AWSError>; /** * Associates a set of tags with a specified resource. */ tagResource(params: SSOAdmin.Types.TagResourceRequest, callback?: (err: AWSError, data: SSOAdmin.Types.TagResourceResponse) => void): Request<SSOAdmin.Types.TagResourceResponse, AWSError>; /** * Associates a set of tags with a specified resource. */ tagResource(callback?: (err: AWSError, data: SSOAdmin.Types.TagResourceResponse) => void): Request<SSOAdmin.Types.TagResourceResponse, AWSError>; /** * Disassociates a set of tags from a specified resource. */ untagResource(params: SSOAdmin.Types.UntagResourceRequest, callback?: (err: AWSError, data: SSOAdmin.Types.UntagResourceResponse) => void): Request<SSOAdmin.Types.UntagResourceResponse, AWSError>; /** * Disassociates a set of tags from a specified resource. */ untagResource(callback?: (err: AWSError, data: SSOAdmin.Types.UntagResourceResponse) => void): Request<SSOAdmin.Types.UntagResourceResponse, AWSError>; /** * Updates the Amazon Web Services SSO identity store attributes that you can use with the Amazon Web Services SSO instance for attributes-based access control (ABAC). When using an external identity provider as an identity source, you can pass attributes through the SAML assertion as an alternative to configuring attributes from the Amazon Web Services SSO identity store. If a SAML assertion passes any of these attributes, Amazon Web Services SSO replaces the attribute value with the value from the Amazon Web Services SSO identity store. For more information about ABAC, see Attribute-Based Access Control in the Amazon Web Services SSO User Guide. */ updateInstanceAccessControlAttributeConfiguration(params: SSOAdmin.Types.UpdateInstanceAccessControlAttributeConfigurationRequest, callback?: (err: AWSError, data: SSOAdmin.Types.UpdateInstanceAccessControlAttributeConfigurationResponse) => void): Request<SSOAdmin.Types.UpdateInstanceAccessControlAttributeConfigurationResponse, AWSError>; /** * Updates the Amazon Web Services SSO identity store attributes that you can use with the Amazon Web Services SSO instance for attributes-based access control (ABAC). When using an external identity provider as an identity source, you can pass attributes through the SAML assertion as an alternative to configuring attributes from the Amazon Web Services SSO identity store. If a SAML assertion passes any of these attributes, Amazon Web Services SSO replaces the attribute value with the value from the Amazon Web Services SSO identity store. For more information about ABAC, see Attribute-Based Access Control in the Amazon Web Services SSO User Guide. */ updateInstanceAccessControlAttributeConfiguration(callback?: (err: AWSError, data: SSOAdmin.Types.UpdateInstanceAccessControlAttributeConfigurationResponse) => void): Request<SSOAdmin.Types.UpdateInstanceAccessControlAttributeConfigurationResponse, AWSError>; /** * Updates an existing permission set. */ updatePermissionSet(params: SSOAdmin.Types.UpdatePermissionSetRequest, callback?: (err: AWSError, data: SSOAdmin.Types.UpdatePermissionSetResponse) => void): Request<SSOAdmin.Types.UpdatePermissionSetResponse, AWSError>; /** * Updates an existing permission set. */ updatePermissionSet(callback?: (err: AWSError, data: SSOAdmin.Types.UpdatePermissionSetResponse) => void): Request<SSOAdmin.Types.UpdatePermissionSetResponse, AWSError>; } declare namespace SSOAdmin { export interface AccessControlAttribute { /** * The name of the attribute associated with your identities in your identity source. This is used to map a specified attribute in your identity source with an attribute in Amazon Web Services SSO. */ Key: AccessControlAttributeKey; /** * The value used for mapping a specified attribute to an identity source. */ Value: AccessControlAttributeValue; } export type AccessControlAttributeKey = string; export type AccessControlAttributeList = AccessControlAttribute[]; export interface AccessControlAttributeValue { /** * The identity source to use when mapping a specified attribute to Amazon Web Services SSO. */ Source: AccessControlAttributeValueSourceList; } export type AccessControlAttributeValueSource = string; export type AccessControlAttributeValueSourceList = AccessControlAttributeValueSource[]; export interface AccountAssignment { /** * The identifier of the Amazon Web Services account. */ AccountId?: AccountId; /** * The ARN of the permission set. For more information about ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces in the Amazon Web Services General Reference. */ PermissionSetArn?: PermissionSetArn; /** * The entity type for which the assignment will be created. */ PrincipalType?: PrincipalType; /** * An identifier for an object in Amazon Web Services SSO, such as a user or group. PrincipalIds are GUIDs (For example, f81d4fae-7dec-11d0-a765-00a0c91e6bf6). For more information about PrincipalIds in Amazon Web Services SSO, see the Amazon Web Services SSO Identity Store API Reference. */ PrincipalId?: PrincipalId; } export type AccountAssignmentList = AccountAssignment[]; export interface AccountAssignmentOperationStatus { /** * The status of the permission set provisioning process. */ Status?: StatusValues; /** * The identifier for tracking the request operation that is generated by the universally unique identifier (UUID) workflow. */ RequestId?: UUId; /** * The message that contains an error or exception in case of an operation failure. */ FailureReason?: Reason; /** * TargetID is an Amazon Web Services account identifier, typically a 10-12 digit string (For example, 123456789012). */ TargetId?: TargetId; /** * The entity type for which the assignment will be created. */ TargetType?: TargetType; /** * The ARN of the permission set. For more information about ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces in the Amazon Web Services General Reference. */ PermissionSetArn?: PermissionSetArn; /** * The entity type for which the assignment will be created. */ PrincipalType?: PrincipalType; /** * An identifier for an object in Amazon Web Services SSO, such as a user or group. PrincipalIds are GUIDs (For example, f81d4fae-7dec-11d0-a765-00a0c91e6bf6). For more information about PrincipalIds in Amazon Web Services SSO, see the Amazon Web Services SSO Identity Store API Reference. */ PrincipalId?: PrincipalId; /** * The date that the permission set was created. */ CreatedDate?: _Date; } export type AccountAssignmentOperationStatusList = AccountAssignmentOperationStatusMetadata[]; export interface AccountAssignmentOperationStatusMetadata { /** * The status of the permission set provisioning process. */ Status?: StatusValues; /** * The identifier for tracking the request operation that is generated by the universally unique identifier (UUID) workflow. */ RequestId?: UUId; /** * The date that the permission set was created. */ CreatedDate?: _Date; } export type AccountId = string; export type AccountList = AccountId[]; export interface AttachManagedPolicyToPermissionSetRequest { /** * The ARN of the SSO instance under which the operation will be executed. For more information about ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces in the Amazon Web Services General Reference. */ InstanceArn: InstanceArn; /** * The ARN of the PermissionSet that the managed policy should be attached to. */ PermissionSetArn: PermissionSetArn; /** * The IAM managed policy ARN to be attached to a permission set. */ ManagedPolicyArn: ManagedPolicyArn; } export interface AttachManagedPolicyToPermissionSetResponse { } export interface AttachedManagedPolicy { /** * The name of the IAM managed policy. */ Name?: Name; /** * The ARN of the IAM managed policy. For more information about ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces in the Amazon Web Services General Reference. */ Arn?: ManagedPolicyArn; } export type AttachedManagedPolicyList = AttachedManagedPolicy[]; export interface CreateAccountAssignmentRequest { /** * The ARN of the SSO instance under which the operation will be executed. For more information about ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces in the Amazon Web Services General Reference. */ InstanceArn: InstanceArn; /** * TargetID is an Amazon Web Services account identifier, typically a 10-12 digit string (For example, 123456789012). */ TargetId: TargetId; /** * The entity type for which the assignment will be created. */ TargetType: TargetType; /** * The ARN of the permission set that the admin wants to grant the principal access to. */ PermissionSetArn: PermissionSetArn; /** * The entity type for which the assignment will be created. */ PrincipalType: PrincipalType; /** * An identifier for an object in Amazon Web Services SSO, such as a user or group. PrincipalIds are GUIDs (For example, f81d4fae-7dec-11d0-a765-00a0c91e6bf6). For more information about PrincipalIds in Amazon Web Services SSO, see the Amazon Web Services SSO Identity Store API Reference. */ PrincipalId: PrincipalId; } export interface CreateAccountAssignmentResponse { /** * The status object for the account assignment creation operation. */ AccountAssignmentCreationStatus?: AccountAssignmentOperationStatus; } export interface CreateInstanceAccessControlAttributeConfigurationRequest { /** * The ARN of the SSO instance under which the operation will be executed. */ InstanceArn: InstanceArn; /** * Specifies the Amazon Web Services SSO identity store attributes to add to your ABAC configuration. When using an external identity provider as an identity source, you can pass attributes through the SAML assertion. Doing so provides an alternative to configuring attributes from the Amazon Web Services SSO identity store. If a SAML assertion passes any of these attributes, Amazon Web Services SSO will replace the attribute value with the value from the Amazon Web Services SSO identity store. */ InstanceAccessControlAttributeConfiguration: InstanceAccessControlAttributeConfiguration; } export interface CreateInstanceAccessControlAttributeConfigurationResponse { } export interface CreatePermissionSetRequest { /** * The name of the PermissionSet. */ Name: PermissionSetName; /** * The description of the PermissionSet. */ Description?: PermissionSetDescription; /** * The ARN of the SSO instance under which the operation will be executed. For more information about ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces in the Amazon Web Services General Reference. */ InstanceArn: InstanceArn; /** * The length of time that the application user sessions are valid in the ISO-8601 standard. */ SessionDuration?: Duration; /** * Used to redirect users within the application during the federation authentication process. */ RelayState?: RelayState; /** * The tags to attach to the new PermissionSet. */ Tags?: TagList; } export interface CreatePermissionSetResponse { /** * Defines the level of access on an Amazon Web Services account. */ PermissionSet?: PermissionSet; } export type _Date = Date; export interface DeleteAccountAssignmentRequest { /** * The ARN of the SSO instance under which the operation will be executed. For more information about ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces in the Amazon Web Services General Reference. */ InstanceArn: InstanceArn; /** * TargetID is an Amazon Web Services account identifier, typically a 10-12 digit string (For example, 123456789012). */ TargetId: TargetId; /** * The entity type for which the assignment will be deleted. */ TargetType: TargetType; /** * The ARN of the permission set that will be used to remove access. */ PermissionSetArn: PermissionSetArn; /** * The entity type for which the assignment will be deleted. */ PrincipalType: PrincipalType; /** * An identifier for an object in Amazon Web Services SSO, such as a user or group. PrincipalIds are GUIDs (For example, f81d4fae-7dec-11d0-a765-00a0c91e6bf6). For more information about PrincipalIds in Amazon Web Services SSO, see the Amazon Web Services SSO Identity Store API Reference. */ PrincipalId: PrincipalId; } export interface DeleteAccountAssignmentResponse { /** * The status object for the account assignment deletion operation. */ AccountAssignmentDeletionStatus?: AccountAssignmentOperationStatus; } export interface DeleteInlinePolicyFromPermissionSetRequest { /** * The ARN of the SSO instance under which the operation will be executed. For more information about ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces in the Amazon Web Services General Reference. */ InstanceArn: InstanceArn; /** * The ARN of the permission set that will be used to remove access. */ PermissionSetArn: PermissionSetArn; } export interface DeleteInlinePolicyFromPermissionSetResponse { } export interface DeleteInstanceAccessControlAttributeConfigurationRequest { /** * The ARN of the SSO instance under which the operation will be executed. */ InstanceArn: InstanceArn; } export interface DeleteInstanceAccessControlAttributeConfigurationResponse { } export interface DeletePermissionSetRequest { /** * The ARN of the SSO instance under which the operation will be executed. For more information about ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces in the Amazon Web Services General Reference. */ InstanceArn: InstanceArn; /** * The ARN of the permission set that should be deleted. */ PermissionSetArn: PermissionSetArn; } export interface DeletePermissionSetResponse { } export interface DescribeAccountAssignmentCreationStatusRequest { /** * The ARN of the SSO instance under which the operation will be executed. For more information about ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces in the Amazon Web Services General Reference. */ InstanceArn: InstanceArn; /** * The identifier that is used to track the request operation progress. */ AccountAssignmentCreationRequestId: UUId; } export interface DescribeAccountAssignmentCreationStatusResponse { /** * The status object for the account assignment creation operation. */ AccountAssignmentCreationStatus?: AccountAssignmentOperationStatus; } export interface DescribeAccountAssignmentDeletionStatusRequest { /** * The ARN of the SSO instance under which the operation will be executed. For more information about ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces in the Amazon Web Services General Reference. */ InstanceArn: InstanceArn; /** * The identifier that is used to track the request operation progress. */ AccountAssignmentDeletionRequestId: UUId; } export interface DescribeAccountAssignmentDeletionStatusResponse { /** * The status object for the account assignment deletion operation. */ AccountAssignmentDeletionStatus?: AccountAssignmentOperationStatus; } export interface DescribeInstanceAccessControlAttributeConfigurationRequest { /** * The ARN of the SSO instance under which the operation will be executed. */ InstanceArn: InstanceArn; } export interface DescribeInstanceAccessControlAttributeConfigurationResponse { /** * The status of the attribute configuration process. */ Status?: InstanceAccessControlAttributeConfigurationStatus; /** * Provides more details about the current status of the specified attribute. */ StatusReason?: InstanceAccessControlAttributeConfigurationStatusReason; /** * Gets the list of Amazon Web Services SSO identity store attributes that have been added to your ABAC configuration. */ InstanceAccessControlAttributeConfiguration?: InstanceAccessControlAttributeConfiguration; } export interface DescribePermissionSetProvisioningStatusRequest { /** * The ARN of the SSO instance under which the operation will be executed. For more information about ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces in the Amazon Web Services General Reference. */ InstanceArn: InstanceArn; /** * The identifier that is provided by the ProvisionPermissionSet call to retrieve the current status of the provisioning workflow. */ ProvisionPermissionSetRequestId: UUId; } export interface DescribePermissionSetProvisioningStatusResponse { /** * The status object for the permission set provisioning operation. */ PermissionSetProvisioningStatus?: PermissionSetProvisioningStatus; } export interface DescribePermissionSetRequest { /** * The ARN of the SSO instance under which the operation will be executed. For more information about ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces in the Amazon Web Services General Reference. */ InstanceArn: InstanceArn; /** * The ARN of the permission set. */ PermissionSetArn: PermissionSetArn; } export interface DescribePermissionSetResponse { /** * Describes the level of access on an Amazon Web Services account. */ PermissionSet?: PermissionSet; } export interface DetachManagedPolicyFromPermissionSetRequest { /** * The ARN of the SSO instance under which the operation will be executed. For more information about ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces in the Amazon Web Services General Reference. */ InstanceArn: InstanceArn; /** * The ARN of the PermissionSet from which the policy should be detached. */ PermissionSetArn: PermissionSetArn; /** * The IAM managed policy ARN to be attached to a permission set. */ ManagedPolicyArn: ManagedPolicyArn; } export interface DetachManagedPolicyFromPermissionSetResponse { } export type Duration = string; export type GeneralArn = string; export interface GetInlinePolicyForPermissionSetRequest { /** * The ARN of the SSO instance under which the operation will be executed. For more information about ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces in the Amazon Web Services General Reference. */ InstanceArn: InstanceArn; /** * The ARN of the permission set. */ PermissionSetArn: PermissionSetArn; } export interface GetInlinePolicyForPermissionSetResponse { /** * The IAM inline policy that is attached to the permission set. */ InlinePolicy?: PermissionSetPolicyDocument; } export type Id = string; export interface InstanceAccessControlAttributeConfiguration { /** * Lists the attributes that are configured for ABAC in the specified Amazon Web Services SSO instance. */ AccessControlAttributes: AccessControlAttributeList; } export type InstanceAccessControlAttributeConfigurationStatus = "ENABLED"|"CREATION_IN_PROGRESS"|"CREATION_FAILED"|string; export type InstanceAccessControlAttributeConfigurationStatusReason = string; export type InstanceArn = string; export type InstanceList = InstanceMetadata[]; export interface InstanceMetadata { /** * The ARN of the SSO instance under which the operation will be executed. For more information about ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces in the Amazon Web Services General Reference. */ InstanceArn?: InstanceArn; /** * The identifier of the identity store that is connected to the SSO instance. */ IdentityStoreId?: Id; } export interface ListAccountAssignmentCreationStatusRequest { /** * The ARN of the SSO instance under which the operation will be executed. For more information about ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces in the Amazon Web Services General Reference. */ InstanceArn: InstanceArn; /** * The maximum number of results to display for the assignment. */ MaxResults?: MaxResults; /** * The pagination token for the list API. Initially the value is null. Use the output of previous API calls to make subsequent calls. */ NextToken?: Token; /** * Filters results based on the passed attribute value. */ Filter?: OperationStatusFilter; } export interface ListAccountAssignmentCreationStatusResponse { /** * The status object for the account assignment creation operation. */ AccountAssignmentsCreationStatus?: AccountAssignmentOperationStatusList; /** * The pagination token for the list API. Initially the value is null. Use the output of previous API calls to make subsequent calls. */ NextToken?: Token; } export interface ListAccountAssignmentDeletionStatusRequest { /** * The ARN of the SSO instance under which the operation will be executed. For more information about ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces in the Amazon Web Services General Reference. */ InstanceArn: InstanceArn; /** * The maximum number of results to display for the assignment. */ MaxResults?: MaxResults; /** * The pagination token for the list API. Initially the value is null. Use the output of previous API calls to make subsequent calls. */ NextToken?: Token; /** * Filters results based on the passed attribute value. */ Filter?: OperationStatusFilter; } export interface ListAccountAssignmentDeletionStatusResponse { /** * The status object for the account assignment deletion operation. */ AccountAssignmentsDeletionStatus?: AccountAssignmentOperationStatusList; /** * The pagination token for the list API. Initially the value is null. Use the output of previous API calls to make subsequent calls. */ NextToken?: Token; } export interface ListAccountAssignmentsRequest { /** * The ARN of the SSO instance under which the operation will be executed. For more information about ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces in the Amazon Web Services General Reference. */ InstanceArn: InstanceArn; /** * The identifier of the Amazon Web Services account from which to list the assignments. */ AccountId: TargetId; /** * The ARN of the permission set from which to list assignments. */ PermissionSetArn: PermissionSetArn; /** * The maximum number of results to display for the assignment. */ MaxResults?: MaxResults; /** * The pagination token for the list API. Initially the value is null. Use the output of previous API calls to make subsequent calls. */ NextToken?: Token; } export interface ListAccountAssignmentsResponse { /** * The list of assignments that match the input Amazon Web Services account and permission set. */ AccountAssignments?: AccountAssignmentList; /** * The pagination token for the list API. Initially the value is null. Use the output of previous API calls to make subsequent calls. */ NextToken?: Token; } export interface ListAccountsForProvisionedPermissionSetRequest { /** * The ARN of the SSO instance under which the operation will be executed. For more information about ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces in the Amazon Web Services General Reference. */ InstanceArn: InstanceArn; /** * The ARN of the PermissionSet from which the associated Amazon Web Services accounts will be listed. */ PermissionSetArn: PermissionSetArn; /** * The permission set provisioning status for an Amazon Web Services account. */ ProvisioningStatus?: ProvisioningStatus; /** * The maximum number of results to display for the PermissionSet. */ MaxResults?: MaxResults; /** * The pagination token for the list API. Initially the value is null. Use the output of previous API calls to make subsequent calls. */ NextToken?: Token; } export interface ListAccountsForProvisionedPermissionSetResponse { /** * The list of Amazon Web Services AccountIds. */ AccountIds?: AccountList; /** * The pagination token for the list API. Initially the value is null. Use the output of previous API calls to make subsequent calls. */ NextToken?: Token; } export interface ListInstancesRequest { /** * The maximum number of results to display for the instance. */ MaxResults?: MaxResults; /** * The pagination token for the list API. Initially the value is null. Use the output of previous API calls to make subsequent calls. */ NextToken?: Token; } export interface ListInstancesResponse { /** * Lists the SSO instances that the caller has access to. */ Instances?: InstanceList; /** * The pagination token for the list API. Initially the value is null. Use the output of previous API calls to make subsequent calls. */ NextToken?: Token; } export interface ListManagedPoliciesInPermissionSetRequest { /** * The ARN of the SSO instance under which the operation will be executed. For more information about ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces in the Amazon Web Services General Reference. */ InstanceArn: InstanceArn; /** * The ARN of the PermissionSet whose managed policies will be listed. */ PermissionSetArn: PermissionSetArn; /** * The maximum number of results to display for the PermissionSet. */ MaxResults?: MaxResults; /** * The pagination token for the list API. Initially the value is null. Use the output of previous API calls to make subsequent calls. */ NextToken?: Token; } export interface ListManagedPoliciesInPermissionSetResponse { /** * The array of the AttachedManagedPolicy data type object. */ AttachedManagedPolicies?: AttachedManagedPolicyList; /** * The pagination token for the list API. Initially the value is null. Use the output of previous API calls to make subsequent calls. */ NextToken?: Token; } export interface ListPermissionSetProvisioningStatusRequest { /** * The ARN of the SSO instance under which the operation will be executed. For more information about ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces in the Amazon Web Services General Reference. */ InstanceArn: InstanceArn; /** * The maximum number of results to display for the assignment. */ MaxResults?: MaxResults; /** * The pagination token for the list API. Initially the value is null. Use the output of previous API calls to make subsequent calls. */ NextToken?: Token; /** * Filters results based on the passed attribute value. */ Filter?: OperationStatusFilter; } export interface ListPermissionSetProvisioningStatusResponse { /** * The status object for the permission set provisioning operation. */ PermissionSetsProvisioningStatus?: PermissionSetProvisioningStatusList; /** * The pagination token for the list API. Initially the value is null. Use the output of previous API calls to make subsequent calls. */ NextToken?: Token; } export interface ListPermissionSetsProvisionedToAccountRequest { /** * The ARN of the SSO instance under which the operation will be executed. For more information about ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces in the Amazon Web Services General Reference. */ InstanceArn: InstanceArn; /** * The identifier of the Amazon Web Services account from which to list the assignments. */ AccountId: AccountId; /** * The status object for the permission set provisioning operation. */ ProvisioningStatus?: ProvisioningStatus; /** * The maximum number of results to display for the assignment. */ MaxResults?: MaxResults; /** * The pagination token for the list API. Initially the value is null. Use the output of previous API calls to make subsequent calls. */ NextToken?: Token; } export interface ListPermissionSetsProvisionedToAccountResponse { /** * The pagination token for the list API. Initially the value is null. Use the output of previous API calls to make subsequent calls. */ NextToken?: Token; /** * Defines the level of access that an Amazon Web Services account has. */ PermissionSets?: PermissionSetList; } export interface ListPermissionSetsRequest { /** * The ARN of the SSO instance under which the operation will be executed. For more information about ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces in the Amazon Web Services General Reference. */ InstanceArn: InstanceArn; /** * The pagination token for the list API. Initially the value is null. Use the output of previous API calls to make subsequent calls. */ NextToken?: Token; /** * The maximum number of results to display for the assignment. */ MaxResults?: MaxResults; } export interface ListPermissionSetsResponse { /** * Defines the level of access on an Amazon Web Services account. */ PermissionSets?: PermissionSetList; /** * The pagination token for the list API. Initially the value is null. Use the output of previous API calls to make subsequent calls. */ NextToken?: Token; } export interface ListTagsForResourceRequest { /** * The ARN of the SSO instance under which the operation will be executed. For more information about ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces in the Amazon Web Services General Reference. */ InstanceArn: InstanceArn; /** * The ARN of the resource with the tags to be listed. */ ResourceArn: GeneralArn; /** * The pagination token for the list API. Initially the value is null. Use the output of previous API calls to make subsequent calls. */ NextToken?: Token; } export interface ListTagsForResourceResponse { /** * A set of key-value pairs that are used to manage the resource. */ Tags?: TagList; /** * The pagination token for the list API. Initially the value is null. Use the output of previous API calls to make subsequent calls. */ NextToken?: Token; } export type ManagedPolicyArn = string; export type MaxResults = number; export type Name = string; export interface OperationStatusFilter { /** * Filters the list operations result based on the status attribute. */ Status?: StatusValues; } export interface PermissionSet { /** * The name of the permission set. */ Name?: PermissionSetName; /** * The ARN of the permission set. For more information about ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces in the Amazon Web Services General Reference. */ PermissionSetArn?: PermissionSetArn; /** * The description of the PermissionSet. */ Description?: PermissionSetDescription; /** * The date that the permission set was created. */ CreatedDate?: _Date; /** * The length of time that the application user sessions are valid for in the ISO-8601 standard. */ SessionDuration?: Duration; /** * Used to redirect users within the application during the federation authentication process. */ RelayState?: RelayState; } export type PermissionSetArn = string; export type PermissionSetDescription = string; export type PermissionSetList = PermissionSetArn[]; export type PermissionSetName = string; export type PermissionSetPolicyDocument = string; export interface PermissionSetProvisioningStatus { /** * The status of the permission set provisioning process. */ Status?: StatusValues; /** * The identifier for tracking the request operation that is generated by the universally unique identifier (UUID) workflow. */ RequestId?: UUId; /** * The identifier of the Amazon Web Services account from which to list the assignments. */ AccountId?: AccountId; /** * The ARN of the permission set that is being provisioned. For more information about ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces in the Amazon Web Services General Reference. */ PermissionSetArn?: PermissionSetArn; /** * The message that contains an error or exception in case of an operation failure. */ FailureReason?: Reason; /** * The date that the permission set was created. */ CreatedDate?: _Date; } export type PermissionSetProvisioningStatusList = PermissionSetProvisioningStatusMetadata[]; export interface PermissionSetProvisioningStatusMetadata { /** * The status of the permission set provisioning process. */ Status?: StatusValues; /** * The identifier for tracking the request operation that is generated by the universally unique identifier (UUID) workflow. */ RequestId?: UUId; /** * The date that the permission set was created. */ CreatedDate?: _Date; } export type PrincipalId = string; export type PrincipalType = "USER"|"GROUP"|string; export interface ProvisionPermissionSetRequest { /** * The ARN of the SSO instance under which the operation will be executed. For more information about ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces in the Amazon Web Services General Reference. */ InstanceArn: InstanceArn; /** * The ARN of the permission set. */ PermissionSetArn: PermissionSetArn; /** * TargetID is an Amazon Web Services account identifier, typically a 10-12 digit string (For example, 123456789012). */ TargetId?: TargetId; /** * The entity type for which the assignment will be created. */ TargetType: ProvisionTargetType; } export interface ProvisionPermissionSetResponse { /** * The status object for the permission set provisioning operation. */ PermissionSetProvisioningStatus?: PermissionSetProvisioningStatus; } export type ProvisionTargetType = "AWS_ACCOUNT"|"ALL_PROVISIONED_ACCOUNTS"|string; export type ProvisioningStatus = "LATEST_PERMISSION_SET_PROVISIONED"|"LATEST_PERMISSION_SET_NOT_PROVISIONED"|string; export interface PutInlinePolicyToPermissionSetRequest { /** * The ARN of the SSO instance under which the operation will be executed. For more information about ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces in the Amazon Web Services General Reference. */ InstanceArn: InstanceArn; /** * The ARN of the permission set. */ PermissionSetArn: PermissionSetArn; /** * The IAM inline policy to attach to a PermissionSet. */ InlinePolicy: PermissionSetPolicyDocument; } export interface PutInlinePolicyToPermissionSetResponse { } export type Reason = string; export type RelayState = string; export type StatusValues = "IN_PROGRESS"|"FAILED"|"SUCCEEDED"|string; export interface Tag { /** * The key for the tag. */ Key?: TagKey; /** * The value of the tag. */ Value?: TagValue; } export type TagKey = string; export type TagKeyList = TagKey[]; export type TagList = Tag[]; export interface TagResourceRequest { /** * The ARN of the SSO instance under which the operation will be executed. For more information about ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces in the Amazon Web Services General Reference. */ InstanceArn: InstanceArn; /** * The ARN of the resource with the tags to be listed. */ ResourceArn: GeneralArn; /** * A set of key-value pairs that are used to manage the resource. */ Tags: TagList; } export interface TagResourceResponse { } export type TagValue = string; export type TargetId = string; export type TargetType = "AWS_ACCOUNT"|string; export type Token = string; export type UUId = string; export interface UntagResourceRequest { /** * The ARN of the SSO instance under which the operation will be executed. For more information about ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces in the Amazon Web Services General Reference. */ InstanceArn: InstanceArn; /** * The ARN of the resource with the tags to be listed. */ ResourceArn: GeneralArn; /** * The keys of tags that are attached to the resource. */ TagKeys: TagKeyList; } export interface UntagResourceResponse { } export interface UpdateInstanceAccessControlAttributeConfigurationRequest { /** * The ARN of the SSO instance under which the operation will be executed. */ InstanceArn: InstanceArn; /** * Updates the attributes for your ABAC configuration. */ InstanceAccessControlAttributeConfiguration: InstanceAccessControlAttributeConfiguration; } export interface UpdateInstanceAccessControlAttributeConfigurationResponse { } export interface UpdatePermissionSetRequest { /** * The ARN of the SSO instance under which the operation will be executed. For more information about ARNs, see Amazon Resource Names (ARNs) and Amazon Web Services Service Namespaces in the Amazon Web Services General Reference. */ InstanceArn: InstanceArn; /** * The ARN of the permission set. */ PermissionSetArn: PermissionSetArn; /** * The description of the PermissionSet. */ Description?: PermissionSetDescription; /** * The length of time that the application user sessions are valid for in the ISO-8601 standard. */ SessionDuration?: Duration; /** * Used to redirect users within the application during the federation authentication process. */ RelayState?: RelayState; } export interface UpdatePermissionSetResponse { } /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ export type apiVersion = "2020-07-20"|"latest"|string; export interface ClientApiVersions { /** * A string in YYYY-MM-DD format that represents the latest possible API version that can be used in this service. Specify 'latest' to use the latest possible version. */ apiVersion?: apiVersion; } export type ClientConfiguration = ServiceConfigurationOptions & ClientApiVersions; /** * Contains interfaces for use with the SSOAdmin client. */ export import Types = SSOAdmin; } export = SSOAdmin;
the_stack
import {Style} from 'maplibre-gl'; import * as constants from '../data/constants'; import {FlagContainer} from '../contexts/FlagContext'; // *********** BASE MAP SOURCES *************** const imageSuffix = constants.isMobile ? '' : '@2x'; // Original "light" Base layer // Additional layers found here: https://carto.com/help/building-maps/basemap-list/#carto-vector-basemaps const cartoLightBaseLayer = { noLabels: [ `https://a.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}${imageSuffix}.png`, `https://b.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}${imageSuffix}.png`, `https://c.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}${imageSuffix}.png`, `https://d.basemaps.cartocdn.com/light_nolabels/{z}/{x}/{y}${imageSuffix}.png`, ], labelsOnly: [ `https://cartodb-basemaps-a.global.ssl.fastly.net/light_only_labels/{z}/{x}/{y}${imageSuffix}.png`, `https://cartodb-basemaps-b.global.ssl.fastly.net/light_only_labels/{z}/{x}/{y}${imageSuffix}.png`, `https://cartodb-basemaps-c.global.ssl.fastly.net/light_only_labels/{z}/{x}/{y}${imageSuffix}.png`, `https://cartodb-basemaps-d.global.ssl.fastly.net/light_only_labels/{z}/{x}/{y}${imageSuffix}.png`, ], }; // MapTiler base map source // Todo: move API key to .env const getMapTilerBaseLayer = (name:string, API_KEY='KMA4bawPDNtR6zNIAfUH') => { return [ `https://api.maptiler.com/maps/${name}/{z}/{x}/{y}${imageSuffix}.png?key=${API_KEY}`, ]; }; // Utility function to make map styles according to JSON spec of MapBox // https://docs.mapbox.com/mapbox-gl-js/style-spec/ export const makeMapStyle = (flagContainer: FlagContainer) : Style => { // Add flags for various types of MapTiler base maps: const getBaseMapLayer = () => { if ('mt-streets' in flagContainer) { return getMapTilerBaseLayer('streets'); } else if ('mt-bright' in flagContainer) { return getMapTilerBaseLayer('bright'); } else if ('mt-voyager' in flagContainer) { return getMapTilerBaseLayer('voyager'); } else if ('mt-osm' in flagContainer) { return getMapTilerBaseLayer('osm-standard'); } else { return cartoLightBaseLayer.noLabels; }; }; return { 'version': 8, /** * Removing any sources, removes the map from rendering, since the layers key is depenedent on these * sources. * * - base map source: This source control the base map. * - geo: currently not being used * - high zoom source: comes from our tile server for high zoom tiles * - low zoom source: comes from our tile server for low zoom tiles * - labels source: currently using carto's label-only source * */ 'sources': { /** * The base map source source allows us to define where the tiles can be fetched from. * Currently we are evaluating carto, MapTiler, Geoampify and MapBox for viable base maps. */ [constants.BASE_MAP_SOURCE_NAME]: { 'type': 'raster', 'tiles': getBaseMapLayer(), /** * Attempting to place a direct call to mapbox URL: */ // 'type': 'raster', // 'tiles': [`mapbox://styles/mapbox/streets-v11`], /** * This MapBox Raster seems to work, however the tileset curently available in MapBox * is the "satellite" tileset. Messaged Mikel on more options. */ // 'type': 'raster', // 'tiles': [ // `https://api.mapbox.com/v4/mapbox.satellite/{z}/{x}/{y}.png?access_token=pk.eyJ1IjoianVzdGljZTQwIiwiYSI6ImNreGF1Z3loNjB0N3oybm9jdGpxeDZ4b3kifQ.76tMHU7C8wwn0HGsF6azjA`, // ], /** * This MapBox Vector does not work, attempting to place this in the main component as * a <Source> and <Layer> component also did not work. */ // 'type': 'vector', // 'tiles': [ // `https://api.mapbox.com/v4/mapbox.mapbox-streets-v8/{z}/{x}/{y}.vector.pbf?access_token=pk.eyJ1IjoianVzdGljZTQwIiwiYSI6ImNreGF1Z3loNjB0N3oybm9jdGpxeDZ4b3kifQ.76tMHU7C8wwn0HGsF6azjA`, // ], 'minzoom': constants.GLOBAL_MIN_ZOOM, 'maxzoom': constants.GLOBAL_MAX_ZOOM, }, // In the layer (below) where the geo source is used, the layer is invisible 'geo': { 'type': 'raster', 'tiles': [ 'https://mt0.google.com/vt/lyrs=p&hl=en&x={x}&y={y}&z={z}', ], 'minzoom': constants.GLOBAL_MIN_ZOOM, 'maxzoom': constants.GLOBAL_MAX_ZOOM, }, // The High zoom source: [constants.HIGH_ZOOM_SOURCE_NAME]: { // It is only shown at high zoom levels to avoid performance issues at lower zooms 'type': 'vector', // Our current tippecanoe command does not set an id. // The below line promotes the GEOID10 property to the ID 'promoteId': constants.GEOID_PROPERTY, 'tiles': [ 'high_tiles' in flagContainer ? constants.featureURLForTilesetName(flagContainer['high_tiles']) : constants.FEATURE_TILE_HIGH_ZOOM_URL, ], // Setting maxzoom here enables 'overzooming' // e.g. continued zooming beyond the max bounds. // More here: https://docs.mapbox.com/help/glossary/overzoom/ 'minzoom': constants.GLOBAL_MIN_ZOOM_HIGH, 'maxzoom': constants.GLOBAL_MAX_ZOOM_HIGH, }, // The Low zoom source: [constants.LOW_ZOOM_SOURCE_NAME]: { // "Score-low" represents a tileset at the level of bucketed tracts. // census block group information is `dissolve`d into tracts, then // each tract is `dissolve`d into one of ten buckets. It is meant // to give us a favorable tradeoff between performance and fidelity. 'type': 'vector', 'promoteId': constants.GEOID_PROPERTY, 'tiles': [ 'low_tiles' in flagContainer ? constants.featureURLForTilesetName(flagContainer['low_tiles']) : constants.FEATURE_TILE_LOW_ZOOM_URL, // For local development, use: // 'http://localhost:8080/data/tl_2010_bg_with_data/{z}/{x}/{y}.pbf', ], 'minzoom': constants.GLOBAL_MIN_ZOOM_LOW, 'maxzoom': constants.GLOBAL_MAX_ZOOM_LOW, }, // The labels source: 'labels': { 'type': 'raster', 'tiles': cartoLightBaseLayer.labelsOnly, }, }, /** * Each object in the layers array references it's source via the source key. * Each layer stacks upon the previous layer in the array of layers. * * - baseMapLayer: the base layer without labels * - geo: a geographical layer that is not being used * - high zoom layer - non-prioritized features only * - high zoom layer - prioritized features only * - low zoom layer - prioritized features only * - labels only layer */ 'layers': [ // The baseMapLayer { 'id': constants.BASE_MAP_LAYER_ID, 'source': constants.BASE_MAP_SOURCE_NAME, 'type': 'raster', 'minzoom': constants.GLOBAL_MIN_ZOOM, 'maxzoom': constants.GLOBAL_MAX_ZOOM, }, // The Geo layer adds a geographical layer like mountains and rivers { 'id': 'geo', 'source': 'geo', 'type': 'raster', 'layout': { // Place visibility behind flag: 'visibility': 'geo' in flagContainer ? 'visible' : 'none', }, 'minzoom': constants.GLOBAL_MIN_ZOOM, 'maxzoom': constants.GLOBAL_MAX_ZOOM, }, /** * High zoom layer - non-prioritized features only */ { 'id': constants.HIGH_ZOOM_LAYER_ID, 'source': constants.HIGH_ZOOM_SOURCE_NAME, 'source-layer': constants.SCORE_SOURCE_LAYER, /** * This shows features where the high score < score boundary threshold. * In other words, this filter out prioritized features */ 'filter': ['all', ['<', constants.SCORE_PROPERTY_HIGH, constants.SCORE_BOUNDARY_THRESHOLD], ], 'type': 'fill', 'paint': { 'fill-opacity': constants.NON_PRIORITIZED_FEATURE_FILL_OPACITY, }, 'minzoom': constants.GLOBAL_MIN_ZOOM_HIGH, }, /** * High zoom layer - prioritized features only */ { 'id': constants.PRIORITIZED_HIGH_ZOOM_LAYER_ID, 'source': constants.HIGH_ZOOM_SOURCE_NAME, 'source-layer': constants.SCORE_SOURCE_LAYER, /** * This shows features where the high score > score boundary threshold. * In other words, this filter out non-prioritized features */ 'filter': ['all', ['>', constants.SCORE_PROPERTY_HIGH, constants.SCORE_BOUNDARY_THRESHOLD], ], 'type': 'fill', 'paint': { 'fill-color': constants.PRIORITIZED_FEATURE_FILL_COLOR, 'fill-opacity': constants.PRIORITIZED_FEATURE_FILL_OPACITY, }, 'minzoom': constants.GLOBAL_MIN_ZOOM_HIGH, }, /** * Low zoom layer - prioritized features only */ { 'id': constants.LOW_ZOOM_LAYER_ID, 'source': constants.LOW_ZOOM_SOURCE_NAME, 'source-layer': constants.SCORE_SOURCE_LAYER, /** * This shows features where the low score > score boundary threshold. * In other words, this filter out non-prioritized features */ 'filter': ['all', ['>', constants.SCORE_PROPERTY_LOW, constants.SCORE_BOUNDARY_THRESHOLD], ], 'type': 'fill', 'paint': { 'fill-color': constants.PRIORITIZED_FEATURE_FILL_COLOR, 'fill-opacity': constants.PRIORITIZED_FEATURE_FILL_OPACITY, }, 'minzoom': constants.GLOBAL_MIN_ZOOM_LOW, 'maxzoom': constants.GLOBAL_MAX_ZOOM_LOW, }, // A layer for labels only { 'id': 'labels-only-layer', 'source': 'labels', 'type': 'raster', 'layout': { 'visibility': 'remove-label-layer' in flagContainer ? 'none' : 'visible', }, 'minzoom': constants.GLOBAL_MIN_ZOOM, 'maxzoom': constants.GLOBAL_MAX_ZOOM, }, ], }; };
the_stack
import * as guiStateModel from 'guiState.model'; import * as guiStateController from 'guiState.controller'; import * as notificationModel from 'notification.model'; import * as comm from 'comm'; import * as $ from 'jquery'; const fadingDuration = 400; const notificationElement = $('#releaseInfo'); const notificationElementTitle = notificationElement.children('#releaseInfoTitle'); const notificationElementDescription = notificationElement.children('#releaseInfoContent'); const $notificationForm = $('#notificationForm'); const $notificationFileUpload = $('#notificationFileUpload'); const $notificationFileDownload = $('#notificationFileDownload'); const defaultElementMarkerTime = 5 * 60 * 1000; const defaultPopupTime = 20 * 1000; const defaultStartScreenTime = undefined; let activeNotifications: NotificationProcessor[] = []; function loadAndInitNotifications() { notificationModel.getNotifications((result) => { activeNotifications = initNotifications(result.notifications); }); } export function init() { initNotificationModal(); loadAndInitNotifications(); comm.onNotificationsAvailableCallback(reloadNotifications); } export function reloadNotifications() { removeNotifications(); loadAndInitNotifications(); } /*----------- NOTIFICATION MODAL -----------*/ export function showNotificationModal() { notificationModel.getNotifications(function (result) { setFileDownloadContent(result.notifications); $('#modal-notifications').modal('show'); }); } function showAlertInNotificationModal(context, content, time?) { time = time || 6 * 1000; const $alert = $('#notification-modal-alert'); $alert .html(content) .removeClass() .addClass('alert') .addClass('alert-' + context) .slideDown() .delay(time) .slideUp(); } function initNotificationModal() { $notificationForm.onWrap('submit', (e) => { e.preventDefault(); readFileInputField((fileContent) => { notificationModel.postNotifications(fileContent, function (restResponse) { if (restResponse.rc === 'ok' && restResponse.message === 'ORA_NOTIFICATION_SUCCESS') { $notificationForm.trigger('reset'); showAlertInNotificationModal('success', 'The notifications were transmitted successfully'); setFileDownloadContent(JSON.parse(fileContent)); } else { const errorCode = restResponse.cause; const exceptionMessage = restResponse.parameters && restResponse.parameters.MESSAGE ? ':' + restResponse.parameters.MESSAGE : ''; const content = errorCode + exceptionMessage; showAlertInNotificationModal('danger', content, 60 * 1000); } }); }); }); } function readFileInputField(readyFn) { let uploadedFiles = $notificationFileUpload.prop('files'); if (uploadedFiles.length > 0) { readFile(uploadedFiles[0], readyFn); } } function readFile(file, readyFn) { const fileReader = new FileReader(); fileReader.onload = () => readyFn(fileReader.result); fileReader.readAsText(file); } function setFileDownloadContent(jsonContent) { const data = 'text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(jsonContent, null, '\t')); $notificationFileDownload.attr('href', 'data:' + data); } /*----------- NOTIFICATION HANDLING -----------*/ function removeNotifications() { activeNotifications.forEach((notification) => { notification.removeTriggers(); notification.hideNotification(); }); activeNotifications = []; } function initNotifications(notificationSpecifications): NotificationProcessor[] { return notificationSpecifications.map((specification) => new NotificationProcessor(specification)); } class EventHandler { private $element; private readonly selector; private readonly elementIsPresent: boolean; private readonly fn; private readonly event: string; public addTriggers() { if (this.elementIsPresent) { // Use direct event handler if element is present this.$element.on(this.event, this.fn); } else { // Use delegate event handler if element is not yet present $(document).on(this.event, this.selector, this.fn); } } public removeTriggers() { if (this.elementIsPresent) { this.$element.off(this.event, this.fn); } else { $(document).off(this.event, this.selector, this.fn); } } constructor(selector, event, fn) { this.selector = selector; this.event = event; this.fn = fn; this.$element = $(selector); this.elementIsPresent = this.$element.length; } } class NotificationProcessor { private specification: any; private activeEventHandler: EventHandler[] = []; private notificationHandlers: NotificationState[] = []; private setupNotificationHandlers() { this.specification.handlers.forEach((handlerSpecification) => { if (handlerSpecification.popupNotification) { const popup = new PopupNotificationState(handlerSpecification.popupNotification); this.notificationHandlers.push(popup); } if (handlerSpecification.elementMarker) { const elementMarker = new ElementMarkerState(handlerSpecification.elementMarker); this.notificationHandlers.push(elementMarker); } if (handlerSpecification.startScreen) { const startScreen = new StartScreenNotificationState(handlerSpecification.startScreen); this.notificationHandlers.push(startScreen); } }); } public showNotification() { if (this.specification.once) { this.removeTriggers(); } this.notificationHandlers.forEach((notification) => notification.show()); } public hideNotification() { this.notificationHandlers.forEach((notification) => notification.hide()); } private evaluateConditionsAndShowNotification(specificCondition?: any) { const { condition: generalConditions, ignoreDate } = this.specification; if (NotificationProcessor.evaluateCondition(specificCondition, ignoreDate) && NotificationProcessor.evaluateCondition(generalConditions, ignoreDate)) { this.showNotification(); } } private static evaluateCondition(conditions: any, ignoreDate?: boolean): boolean { if (conditions === undefined) { return true; } return conditions.every((condition) => { if (condition.guiModel) { const { anyOf, equals, notEquals } = condition; const element = guiStateModel.gui[condition.guiModel]; if (anyOf && Array.isArray(anyOf)) { return anyOf.some((each) => element === each); } if (equals) { return element === equals; } if (notEquals) { if (!Array.isArray(notEquals)) { return element !== notEquals; } return notEquals.every((each) => element !== each); } } const selector = parseSelector(condition); if (condition.hasClass && selector) { return $(selector).hasClass(condition.hasClass); } if (!ignoreDate) { if (condition.endTime) { let endTimeDate = parseDateStringWithTimezone(condition.endTime); let now = new Date(); return endTimeDate >= now; } if (condition.startTime) { let startTimeDate = parseDateStringWithTimezone(condition.startTime); let now = new Date(); return startTimeDate <= now; } } return true; }); } private addEventHandler(selector: string, event, fn: () => void) { const eventHandler = new EventHandler(selector, event, fn); eventHandler.addTriggers(); this.activeEventHandler.push(eventHandler); } public addTriggers() { if (!this.specification.triggers || this.specification.triggers > 0) { // Directly run notification if conditions are met this.evaluateConditionsAndShowNotification(); return; } this.specification.triggers.forEach((trigger) => { const { event, addClass, removeClass, conditions } = trigger; const selector = parseSelector(trigger); if (!selector) return; // "Normal" event listeners if (event) { this.addEventHandler(selector, event, () => { this.evaluateConditionsAndShowNotification(conditions); }); } // Class changed event listeners if (addClass || removeClass) { this.addEventHandler(selector, 'classChange', () => { if (addClass && $(selector).hasClass(addClass)) { this.evaluateConditionsAndShowNotification(conditions); } if (removeClass && !$(selector).hasClass(removeClass)) { this.evaluateConditionsAndShowNotification(conditions); } }); } }); } public removeTriggers() { this.activeEventHandler.forEach((eventHandler) => eventHandler.removeTriggers()); this.activeEventHandler = []; } constructor(specification: any) { this.specification = specification; this.setupNotificationHandlers(); this.addTriggers(); } } interface Selector { htmlId?: string; htmlSelector?: string; } interface ElementMarkerSpec extends Selector { time?: number; content: string; } interface StartScreenSpec { time?: number; content: string; } interface PopupNotificationSpec { time?: number; title: string; content: string; } abstract class NotificationState { private active = false; private timer; private readonly time: number; private clearTimerIfExists() { if (this.timer) { clearTimeout(this.timer); } } private setOrResetTimer() { if (this.time) { this.clearTimerIfExists(); this.timer = setTimeout(() => this.hide(), this.time); } } public show() { this.setOrResetTimer(); if (!this.active) { this.showAction(); this.active = true; } } public hide() { if (this.active) { this.clearTimerIfExists(); this.hideAction(); this.active = false; } } protected abstract showAction(); protected abstract hideAction(); protected constructor(time: number) { this.time = time; } } class PopupNotificationState extends NotificationState { private readonly _title: any; private readonly _content: any; protected hideAction() { if (notificationElementTitle.html() === this._title && notificationElementDescription.html() === this._content) { notificationElement.fadeOut(fadingDuration); } } protected showAction() { notificationElementTitle.html(this._title); notificationElementDescription.html(this._content); notificationElement.fadeIn(fadingDuration); } public constructor(popupNotification: PopupNotificationSpec) { super(popupNotification.time || defaultPopupTime); this._title = parseLocalized(popupNotification.title); this._content = parseLocalized(popupNotification.content); } } class ElementMarkerState extends NotificationState { private readonly _content: any; private $badge: any; private $element: any; constructor(elementMarker: ElementMarkerSpec) { super(elementMarker.time || defaultElementMarkerTime); this._content = parseLocalized(elementMarker.content); this.$element = $(parseSelector(elementMarker)); this.$badge = $("<span class='badge badge-primary' style='display:none;'>" + this._content + '</span>'); } protected hideAction() { if (this.$element.length) { this.$badge.fadeOut(fadingDuration).queue(function () { $(this).remove(); }); } } protected showAction() { if (this.$element.length) { this.$badge.appendTo(this.$element).fadeIn(fadingDuration); } } } class StartScreenNotificationState extends NotificationState { private readonly content: string; private $element; private $startupMessage = $('#startup-message-statustext'); constructor(startScreen: StartScreenSpec) { super(startScreen.time || defaultStartScreenTime); this.content = parseLocalized(startScreen.content); this.$element = $('<h4 style="display: none">' + this.content + '</h4>'); } protected showAction() { this.$element.appendTo(this.$startupMessage).slideDown(fadingDuration); } protected hideAction() { this.$element.slideUp(fadingDuration).queue(function () { $(this).remove(); }); } } function parseSelector(element: Selector): string { if (element.htmlId) { return '#' + element.htmlId; } if (element.htmlSelector) { return element.htmlSelector; } return undefined; } function parseLocalized(object: any): string { let localizedDescription = object[guiStateController.getLanguage()]; return localizedDescription || object['en']; } /** * Parse date from a datestring * The parameter must match the format "YYYY-MM-DD HH:mm" * This automatically adds the German Timezone (+0200) * @param str datestring */ function parseDateStringWithTimezone(str) { return new Date(str + ' +0200'); }
the_stack
import { derived, Readable, writable, Writable } from "svelte/store"; import { maybeDerived, unwrapStoreNonNull } from "../utils"; /* _____ _______ _______ ______ _________ _______ ______ _____ / ____|__ __|/\|__ __| ____| |__ __\ \ / / __ \| ____|/ ____| | (___ | | / \ | | | |__ | | \ \_/ /| |__) | |__ | (___ \___ \ | | / /\ \ | | | __| | | \ / | ___/| __| \___ \ ____) | | |/ ____ \| | | |____ | | | | | | | |____ ____) | |_____/ |_/_/ \_\_| |______| |_| |_| |_| |______|_____/ */ type Discriminator<TYPE extends "root" | "branch"> = { type: TYPE; } type RootType = Discriminator<"root">; type BranchType = Discriminator<"branch">; type State_Base<DISCRIMINATOR extends Discriminator<any>, RD, BD, RM, BM, > = DISCRIMINATOR & { children: Record<number, StoreSafeDecorated_DecoratedState_Branch<RD, BD, RM, BM>>; hiddenChildren: Record<number, StoreSafeDecorated_DecoratedState_Branch<RD, BD, RM, BM>>; selectedChild: number | null; lastSelected: number | null; nextChildIndex: number; }; type State_Root<RD, BD, RM, BM> = State_Base<RootType, RD, BD, RM, BM> & { path: [] }; type State_Branch<RD, BD, RM, BM> = State_Base<BranchType, RD, BD, RM, BM> & { path: number[]; } type State_Either<RD, BD, RM, BM> = State_Root<RD, BD, RM, BM> | State_Branch<RD, BD, RM, BM>; type DefaultStateDecoration<RD, BD, RM, BM> = { selectedByParent: boolean; wasLastSelectedByParent: boolean; onSelectedPath: boolean; }; type StateDecoration_Root<RD, BD, RM, BM> = DefaultStateDecoration<RD, BD, RM, BM> & RD; type StateDecoration_Branch<RD, BD, RM, BM> = DefaultStateDecoration<RD, BD, RM, BM> & BD; type StateDecoration_Either<RD, BD, RM, BM> = StateDecoration_Root<RD, BD, RM, BM> | StateDecoration_Branch<RD, BD, RM, BM>; type DecoratedState_Root<RD, BD, RM, BM> = State_Root<RD, BD, RM, BM> & StateDecoration_Root<RD, BD, RM, BM>; type DecoratedState_Branch<RD, BD, RM, BM> = State_Branch<RD, BD, RM, BM> & StateDecoration_Branch<RD, BD, RM, BM>; type DecoratedState_Either<RD, BD, RM, BM> = DecoratedState_Root<RD, BD, RM, BM> | DecoratedState_Branch<RD, BD, RM, BM>; type DefaultStoreDecoration_Base<RD, BD, RM, BM, TYPE extends "root" | "branch"> = Discriminator<TYPE> & { /** * Adds a child to the store at the next available index. * The child's decoration is derived from the parent's state using the provided function */ addChild: (stateDecorationStore: Readable<BD>, storeDecorationSupplier: StoreDecorationSupplier_Branch<RD, BD, RM, BM>) => Promise<StoreSafeDecorated_DecoratedState_Branch<RD, BD, RM, BM>>; /** * Deletes the child a the given index. * The selected/last selected child becomes null if it is deleted */ deleteChild: (childIdx: number) => Promise<StoreSafeDecorated_DecoratedState_Branch<RD, BD, RM, BM> | null>; hideChild: (childIdx: number) => Promise<StoreSafeDecorated_DecoratedState_Branch<RD, BD, RM, BM> | null>; showChild: (childIdx: number) => Promise<StoreSafeDecorated_DecoratedState_Branch<RD, BD, RM, BM> | null>; selectedChildStore_2: StoreSafe_SelectedStore<RD, BD, RM, BM>; numberOfLeavesStore: Readable<number>; resetNextChildIndex: () => void; } type DefaultStoreDecoration_Root<RD, BD, RM, BM> = DefaultStoreDecoration_Base<RD, BD, RM, BM, "root"> & { /** * Selects the node at the given path under this one * Returns the actual path that was selected */ select: (path: number[]) => void; selectedStore_2: StoreSafe_SelectedStore<RD, BD, RM, BM>; } type DefaultStoreDecoration_Branch<RD, BD, RM, BM> = DefaultStoreDecoration_Base<RD, BD, RM, BM, "branch"> & { /** * Selects the node at the given path under this one * Returns the actual path that was selected */ internalSelect: (path: number[]) => void; } type DefaultStoreDecoration_Either<RD, BD, RM, BM> = DefaultStoreDecoration_Root<RD, BD, RM, BM> | DefaultStoreDecoration_Branch<RD, BD, RM, BM>; type StoreDecoration_Root<RD, BD, RM, BM> = DefaultStoreDecoration_Root<RD, BD, RM, BM> & RM; type StoreDecoration_Branch<RD, BD, RM, BM> = DefaultStoreDecoration_Branch<RD, BD, RM, BM> & BM; type StoreDecoration_Either<RD, BD, RM, BM> = StoreDecoration_Root<RD, BD, RM, BM> | StoreDecoration_Branch<RD, BD, RM, BM>; /* _____ _______ ____ _____ ______ _________ _______ ______ _____ / ____|__ __/ __ \| __ \| ____| |__ __\ \ / / __ \| ____|/ ____| | (___ | | | | | | |__) | |__ | | \ \_/ /| |__) | |__ | (___ \___ \ | | | | | | _ /| __| | | \ / | ___/| __| \___ \ ____) | | | | |__| | | \ \| |____ | | | | | | | |____ ____) | |_____/ |_| \____/|_| \_\______| |_| |_| |_| |______|_____/ */ type StoreUnsafePlain_State_Root<RD, BD, RM, BM> = Writable<State_Root<RD, BD, RM, BM>>; type StoreUnsafePlain_State_Branch<RD, BD, RM, BM> = Writable<State_Branch<RD, BD, RM, BM>>; type StoreUnsafePlain_State_Either<RD, BD, RM, BM> = StoreUnsafePlain_State_Branch<RD, BD, RM, BM> | StoreUnsafePlain_State_Root<RD, BD, RM, BM>; type StoreSafePlain_DecoratedState_Root<RD, BD, RM, BM> = Readable<DecoratedState_Root<RD, BD, RM, BM>>; type StoreSafePlain_DecoratedState_Branch<RD, BD, RM, BM> = Readable<DecoratedState_Branch<RD, BD, RM, BM>>; type StoreSafePlain_DecoratedState_Either<RD, BD, RM, BM> = StoreSafePlain_DecoratedState_Root<RD, BD, RM, BM> | StoreSafePlain_DecoratedState_Branch<RD, BD, RM, BM>; export type StoreSafePartDecorated_DecoratedState_Root<RD, BD, RM, BM> = DefaultStoreDecoration_Root<RD, BD, RM, BM> & StoreSafePlain_DecoratedState_Root<RD, BD, RM, BM>; export type StoreSafePartDecorated_DecoratedState_Branch<RD, BD, RM, BM> = DefaultStoreDecoration_Branch<RD, BD, RM, BM> & StoreSafePlain_DecoratedState_Branch<RD, BD, RM, BM>; export type StoreSafeDecorated_DecoratedState_Root<RD, BD, RM, BM> = StoreDecoration_Root<RD, BD, RM, BM> & StoreSafePlain_DecoratedState_Root<RD, BD, RM, BM>; export type StoreSafeDecorated_DecoratedState_Branch<RD, BD, RM, BM> = StoreDecoration_Branch<RD, BD, RM, BM> & StoreSafePlain_DecoratedState_Branch<RD, BD, RM, BM>; type StoreUnsafe_SelectedStore<RD, BD, RM, BM> = Writable<null | StoreSafeDecorated_DecoratedState_Branch<RD, BD, RM, BM>>; type StoreSafe_SelectedStore<RD, BD, RM, BM> = Readable<null | StoreSafeDecorated_DecoratedState_Branch<RD, BD, RM, BM>>; type StoreSafe_DefaultStateDecoration<RD, BD, RM, BM> = Readable<DefaultStateDecoration<RD, BD, RM, BM>>; export type StoreDecorationSupplier_Root<RD, BD, RM, BM> = (partDecoratedStore: StoreSafePartDecorated_DecoratedState_Root<RD, BD, RM, BM>) => RM; export type StoreDecorationSupplier_Branch<RD, BD, RM, BM> = (partDecoratedStore: StoreSafePartDecorated_DecoratedState_Branch<RD, BD, RM, BM>) => BM; function rootSelect<RD, BD, RM, BM>( unsafeMutableStore: StoreUnsafePlain_State_Root<RD, BD, RM, BM>, selectedStore: StoreUnsafe_SelectedStore<RD, BD, RM, BM>, path: number[] ): void { if (path.length === 0) { unsafeMutableStore.update((state: State_Root<RD, BD, RM, BM>) => { selectedStore.set(null); return { ...state, selectedChild: null, lastSelected: state.selectedChild } }); return; } unsafeMutableStore.update((state: State_Root<RD, BD, RM, BM>) => { const newSelectedChild = state.children[path[0]]; if (newSelectedChild === undefined) { selectedStore.set(null); return ({ ...state, selectedChild: null, lastSelected: state.selectedChild }) } const pathForChild = [...path]; pathForChild.shift(); newSelectedChild.internalSelect(pathForChild); return ({ ...state, selectedChild: path[0], lastSelected: state.selectedChild }); }); } function branchSelect<RD, BD, RM, BM>( unsafeMutableStore: StoreUnsafePlain_State_Branch<RD, BD, RM, BM>, select: () => void, path: number[] ): void { if (path.length === 0) { unsafeMutableStore.update((state: State_Branch<RD, BD, RM, BM>) => { select(); return { ...state, selectedChild: null, lastSelected: state.selectedChild } }); return; } unsafeMutableStore.update((state: State_Branch<RD, BD, RM, BM>) => { const newSelectedChild = state.children[path[0]]; if (newSelectedChild === undefined) { select(); return ({ ...state, selectedChild: null, lastSelected: state.selectedChild }) } const pathForChild = [...path]; pathForChild.shift(); newSelectedChild.internalSelect(pathForChild); return ({ ...state, selectedChild: path[0], lastSelected: state.selectedChild }); }); } async function addChild<RD, BD, RM, BM, STATE extends State_Either<RD, BD, RM, BM>>( internalStore: Writable<STATE>, decoratedStore: StoreSafePlain_DecoratedState_Either<RD, BD, RM, BM>, selectedStore: StoreUnsafe_SelectedStore<RD, BD, RM, BM>, stateDecorationStore: Readable<BD>, storeDecorationSupplier: StoreDecorationSupplier_Branch<RD, BD, RM, BM> ): Promise<StoreSafeDecorated_DecoratedState_Branch<RD, BD, RM, BM>> { return await new Promise(resolve => { internalStore.update((state: STATE) => { const childIndex = state.nextChildIndex; const selectionInfoStore: StoreSafe_DefaultStateDecoration<RD, BD, RM, BM> = maybeDerived(decoratedStore, ($parentTotal: DecoratedState_Either<RD, BD, RM, BM>) => ({ selectedByParent: $parentTotal.selectedChild === childIndex, wasLastSelectedByParent: $parentTotal.lastSelected === childIndex, onSelectedPath: $parentTotal.onSelectedPath && $parentTotal.selectedChild === childIndex }), { selectedByParent: false, wasLastSelectedByParent: false, onSelectedPath: false }, (a, b) => a.selectedByParent === b.selectedByParent && a.wasLastSelectedByParent === b.wasLastSelectedByParent && a.onSelectedPath === b.onSelectedPath); const newChild: StoreSafeDecorated_DecoratedState_Branch<RD, BD, RM, BM> = createBranchStore([...state.path, childIndex], stateDecorationStore, storeDecorationSupplier, selectionInfoStore, selectedStore); resolve(newChild); const children: Record<number, StoreSafeDecorated_DecoratedState_Branch<RD, BD, RM, BM>> = { ...state.children }; children[state.nextChildIndex] = newChild; return { ...state, children, nextChildIndex: childIndex + 1 } }) }) } async function rootDeleteChild<RD, BD, RM, BM>( internalStore: StoreUnsafePlain_State_Root<RD, BD, RM, BM>, selectedStore: StoreUnsafe_SelectedStore<RD, BD, RM, BM>, childIdx: number ): Promise<StoreSafeDecorated_DecoratedState_Branch<RD, BD, RM, BM> | null> { return await new Promise(resolve => internalStore.update((state: State_Root<RD, BD, RM, BM>) => { const removedChild: StoreSafeDecorated_DecoratedState_Branch<RD, BD, RM, BM> | undefined = state.children[childIdx]; if (removedChild === undefined) { resolve(null); return state; } const newChildren = { ...state.children }; delete newChildren[childIdx]; const newState = { ...state, children: newChildren }; if (state.selectedChild === childIdx) { newState.selectedChild = null; selectedStore.set(null); } if (state.lastSelected === childIdx) { newState.lastSelected = null; } resolve(removedChild); return newState; }) ) } async function rootShowChild<RD, BD, RM, BM>( internalStore: StoreUnsafePlain_State_Root<RD, BD, RM, BM>, childIdx: number ): Promise<StoreSafeDecorated_DecoratedState_Branch<RD, BD, RM, BM> | null> { return await new Promise(resolve => internalStore.update((state: State_Root<RD, BD, RM, BM>) => { const child: StoreSafeDecorated_DecoratedState_Branch<RD, BD, RM, BM> | undefined = state.hiddenChildren[childIdx]; if (child === undefined) { resolve(null); return state; } const newChildren = { ...state.children }; const newHiddenChildren = { ...state.hiddenChildren }; newChildren[childIdx] = child; delete newHiddenChildren[childIdx]; const newState = { ...state, children: newChildren, hiddenChildren: newHiddenChildren }; resolve(child); return newState; }) ) } async function rootHideChild<RD, BD, RM, BM>( internalStore: StoreUnsafePlain_State_Root<RD, BD, RM, BM>, selectedStore: StoreUnsafe_SelectedStore<RD, BD, RM, BM>, childIdx: number ): Promise<StoreSafeDecorated_DecoratedState_Branch<RD, BD, RM, BM> | null> { return await new Promise(resolve => internalStore.update((state: State_Root<RD, BD, RM, BM>) => { const child: StoreSafeDecorated_DecoratedState_Branch<RD, BD, RM, BM> | undefined = state.children[childIdx]; if (child === undefined) { resolve(null); return state; } const newChildren = { ...state.children }; const newHiddenChildren = { ...state.hiddenChildren }; newHiddenChildren[childIdx] = child; delete newChildren[childIdx]; const newState = { ...state, children: newChildren, hiddenChildren: newHiddenChildren }; if (state.selectedChild === childIdx) { newState.selectedChild = null; selectedStore.set(null); } if (state.lastSelected === childIdx) { newState.lastSelected = null; } resolve(child); return newState; }) ) } async function branchDeleteChild<RD, BD, RM, BM>( internalStore: StoreUnsafePlain_State_Branch<RD, BD, RM, BM>, select: () => void, childIdx: number ): Promise<StoreSafeDecorated_DecoratedState_Branch<RD, BD, RM, BM> | null> { return await new Promise(resolve => internalStore.update((state: State_Branch<RD, BD, RM, BM>) => { const removedChild: StoreSafeDecorated_DecoratedState_Branch<RD, BD, RM, BM> | undefined = state.children[childIdx]; if (removedChild === undefined) { resolve(null); return state; } const newChildren = { ...state.children }; delete newChildren[childIdx]; const newState = { ...state, children: newChildren }; if (state.selectedChild === childIdx) { newState.selectedChild = null; select(); } if (state.lastSelected === childIdx) { newState.lastSelected = null; } resolve(removedChild); return newState; }) ) } async function branchShowChild<RD, BD, RM, BM>( internalStore: StoreUnsafePlain_State_Branch<RD, BD, RM, BM>, childIdx: number ): Promise<StoreSafeDecorated_DecoratedState_Branch<RD, BD, RM, BM> | null> { return await new Promise(resolve => internalStore.update((state: State_Branch<RD, BD, RM, BM>) => { const child: StoreSafeDecorated_DecoratedState_Branch<RD, BD, RM, BM> | undefined = state.hiddenChildren[childIdx]; if (child === undefined) { resolve(null); return state; } const newChildren = { ...state.children }; const newHiddenChildren = { ...state.hiddenChildren }; newChildren[childIdx] = child; delete newHiddenChildren[childIdx]; const newState = { ...state, children: newChildren, hiddenChildren: newHiddenChildren }; resolve(child); return newState; }) ) } async function branchHideChild<RD, BD, RM, BM>( internalStore: StoreUnsafePlain_State_Branch<RD, BD, RM, BM>, select: () => void, childIdx: number ): Promise<StoreSafeDecorated_DecoratedState_Branch<RD, BD, RM, BM> | null> { return await new Promise(resolve => internalStore.update((state: State_Branch<RD, BD, RM, BM>) => { const child: StoreSafeDecorated_DecoratedState_Branch<RD, BD, RM, BM> | undefined = state.children[childIdx]; if (child === undefined) { resolve(null); return state; } const newChildren = { ...state.children }; const newHiddenChildren = { ...state.hiddenChildren }; newHiddenChildren[childIdx] = child; delete newChildren[childIdx]; const newState = { ...state, children: newChildren, hiddenChildren: newHiddenChildren }; if (state.selectedChild === childIdx) { newState.selectedChild = null; select(); } if (state.lastSelected === childIdx) { newState.lastSelected = null; } resolve(child); return newState; }) ) } function nodeResetNextChildIdx<RD, BD, RM, BM>(store: StoreUnsafePlain_State_Either<RD, BD, RM, BM>): void { //TODO statically type this, probably by splitting into 2 funcs store.update((state: any) => ({ ...state, nextChildIndex: Math.max(...Object.keys(state.children).map(str => parseInt(str)), 0) + 1 })); } function createRootStore<RD, BD, RM, BM>(stateDecorationStore: Readable<RD>, storeDecorationSupplier_Root: StoreDecorationSupplier_Root<RD, BD, RM, BM>): StoreSafeDecorated_DecoratedState_Root<RD, BD, RM, BM> { const initialState: State_Root<RD, BD, RM, BM> = { type: "root", children: {}, hiddenChildren: {}, nextChildIndex: 1, selectedChild: null, lastSelected: null, path: [], }; const internalStore: StoreUnsafePlain_State_Root<RD, BD, RM, BM> = writable(initialState); const selectionInfoStore: StoreSafe_DefaultStateDecoration<RD, BD, RM, BM> = writable({ selectedByParent: true, wasLastSelectedByParent: false, onSelectedPath: true }); const decoratedStateStore: StoreSafePlain_DecoratedState_Root<RD, BD, RM, BM> = derived( [internalStore, stateDecorationStore, selectionInfoStore], ([$internalStore, $decorationStore, $selectionInfoStore]) => ({ ...$internalStore, ...$decorationStore, ...$selectionInfoStore })); const mutableSelectedStore: StoreUnsafe_SelectedStore<RD, BD, RM, BM> = writable(null); let partDecorated: StoreSafePartDecorated_DecoratedState_Root<RD, BD, RM, BM>; partDecorated = { type: "root" as const, ...decoratedStateStore, selectedChildStore_2: deriveSelectedChildStore(decoratedStateStore), numberOfLeavesStore: deriveNumberOfLeavesStore(decoratedStateStore), addChild: (stateDecorationStore: Readable<BD>, storeDecorationSupplier: StoreDecorationSupplier_Branch<RD, BD, RM, BM>) => addChild(internalStore, decoratedStateStore, mutableSelectedStore, stateDecorationStore, storeDecorationSupplier), select: (path: number[]) => rootSelect(internalStore, mutableSelectedStore, path), deleteChild: (childIdx: number) => rootDeleteChild(internalStore, mutableSelectedStore, childIdx), showChild: (childIdx: number) => rootShowChild(internalStore, childIdx), hideChild: (childIdx: number) => rootHideChild(internalStore, mutableSelectedStore, childIdx), resetNextChildIndex: () => nodeResetNextChildIdx(internalStore), selectedStore_2: mutableSelectedStore }; return { ...partDecorated, ...storeDecorationSupplier_Root(partDecorated) } } function createBranchStore<RD, BD, RM, BM>(path: number[], decorationStore: Readable<BD>, storeDecorationSupplier: StoreDecorationSupplier_Branch<RD, BD, RM, BM>, selectionInfoStore: StoreSafe_DefaultStateDecoration<RD, BD, RM, BM>, selectedStore: StoreUnsafe_SelectedStore<RD, BD, RM, BM>): StoreSafeDecorated_DecoratedState_Branch<RD, BD, RM, BM> { const initialState: State_Branch<RD, BD, RM, BM> = { type: "branch", nextChildIndex: 1, children: {}, hiddenChildren: {}, selectedChild: null, lastSelected: null, path }; const internalStore: StoreUnsafePlain_State_Branch<RD, BD, RM, BM> = writable(initialState); const decoratedStateStore: StoreSafePlain_DecoratedState_Branch<RD, BD, RM, BM> = derived( [internalStore, decorationStore, selectionInfoStore], ([$internalStore, $decorationStore, $selectionInfoStore]) => ({ ...$internalStore, ...$decorationStore, ...$selectionInfoStore })); let partDecorated: StoreSafePartDecorated_DecoratedState_Branch<RD, BD, RM, BM>; let fullyDecorated: StoreSafeDecorated_DecoratedState_Branch<RD, BD, RM, BM>; const select = () => { selectedStore.set(fullyDecorated) }; partDecorated = { type: "branch" as const, ...decoratedStateStore, selectedChildStore_2: deriveSelectedChildStore(decoratedStateStore), numberOfLeavesStore: deriveNumberOfLeavesStore(decoratedStateStore), internalSelect: (path: number[]) => branchSelect(internalStore, select, path), addChild: (stateDecorationStore: Readable<BD>, storeDecorationSupplier: StoreDecorationSupplier_Branch<RD, BD, RM, BM>) => addChild(internalStore, decoratedStateStore, selectedStore, stateDecorationStore, storeDecorationSupplier), deleteChild: (childIdx: number) => branchDeleteChild(internalStore, select, childIdx), showChild: (childIdx: number) => branchShowChild(internalStore, childIdx), hideChild: (childIdx: number) => branchHideChild(internalStore, select, childIdx), resetNextChildIndex: () => nodeResetNextChildIdx(internalStore) }; fullyDecorated = { ...partDecorated, ...storeDecorationSupplier(partDecorated) }; return fullyDecorated; } function deriveSelectedChildStore<RD, BD, RM, BM>(parentStore: StoreSafePlain_DecoratedState_Either<RD, BD, RM, BM>): StoreSafe_SelectedStore<RD, BD, RM, BM> { return maybeDerived(parentStore, $parentStore => { let idx = $parentStore.selectedChild; if (idx === null) return null; const selected: StoreSafeDecorated_DecoratedState_Branch<RD, BD, RM, BM> | undefined = $parentStore.children[idx]; return selected === undefined ? null : selected; }, null); } function deriveNumberOfLeavesStore(decoratedStateStore: StoreSafePlain_DecoratedState_Root<any, any, any, any>): Readable<number> { const summed: Readable<Readable<number>> = derived(decoratedStateStore, (state: State_Base<any, any, any, any, any>) => { const internalStores: StoreSafeDecorated_DecoratedState_Branch<any, any, any, any>[] = Object.values(state.children).map((child: StoreSafeDecorated_DecoratedState_Branch<any, any, any, any>) => child.numberOfLeavesStore) if (internalStores.length === 0) return writable(1); return derived(internalStores as [Readable<number>, ...Readable<number>[]], (numbers: number[]) => { if (numbers.length === 0) return 1; return numbers.reduce((a, b) => a + b, 0); }) }); return unwrapStoreNonNull<number, Readable<number>>(summed, 1); } export const createTree = createRootStore;
the_stack
import { AfterViewInit, Component, QueryList, ViewChild, ViewChildren } from '@angular/core'; import { ExtensionService } from './classes/extension.service'; import { Card, CardOutput } from 'neuron-ipe-types'; import { RegexService } from './classes/regex.service'; /** * Manages the entire app in the Output Panel. */ @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'], host: { '(window:resize)': 'onWindowResize()' } }) export class AppComponent implements AfterViewInit { /** * Array of all Cards. */ cards: Card[] = []; /** * Status of Selecting. True if user is selecting (in Select Mode). */ isSelecting = false; /** * Set of Selected Cards. */ selectedCards = new Set<Card>(); /** * Map of Cards and there visibility. */ visibleCards = new Map<Card, boolean>(); /** * Search query in search box. */ searchQuery = ''; /** * Status of Filters */ typeFilters = { text: true, rich: true, error: true }; /** * Indicates if the Undo Snackbar is displayed. */ showingUndoButton: boolean = false; /** * String to be displayed on Undo Snackbar */ undoContent: string = 'Card deleted'; /** * Timer for Undo Snackbar */ undoButtonTimer = null; constructor(private extension: ExtensionService, private regexService: RegexService) { extension.onAddCard.subscribe(card => { this.addCard(card); }); } /** * Displays the Undo Snackbar for 10 seconds when a card is deleted. * @param cards Number of deleted cards */ showUndoButton(cards: number) { if (cards == 1) { this.undoContent = `Card deleted` } else { this.undoContent = `${cards} cards deleted` } this.showingUndoButton = true; if (this.undoButtonTimer) { clearTimeout(this.undoButtonTimer); } this.undoButtonTimer = setTimeout(() => { this.undoButtonTimer = null; this.showingUndoButton = false; }, 10000); } /** * Updates selected filters and calls checkVisible to updates visible cards. * @param filters typeFilters */ updateFilters(filters: any): void { this.typeFilters = filters; this.checkVisible(); } /** * Updates search query and calls checkVisible to updates visible cards. * @param search SearchQuery */ updateSearch(search: string): void { this.searchQuery = search; this.checkVisible(); } /** * Checks if the card title/sourceCode has any characters matching the search query * @param card Card to investigate * @returns Returns true if title/source code of card matches regex/normal search */ cardMatchesSearchQuery(card: Card): boolean { if (this.searchQuery === '') { return true; } let regexResult = this.regexService.regexQuery(this.searchQuery); // Regex search if (regexResult) { if (regexResult.test(card.title) || regexResult.test(card.sourceCode)) { return true; } } // Normal search else { let pattern = this.searchQuery.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/gi, '\\$&'); if (new RegExp(pattern, 'gi').test(card.title) || new RegExp(pattern, 'gi').test(card.sourceCode)) { return true; } } return false; } /** * Checks if card has matching output to user selected filter * @param card Card to investigate * @returns Returns true if any of the card output matches any of the filters */ cardMatchesFilter(card: Card): boolean { if (card.outputs && card.outputs.length === 0) return this.typeFilters.text; for (let output of card.outputs) { // plain text if (output.type == 'stdout' || output.type == 'text/plain') { if (this.typeFilters.text) return true; // code errors } else if (output.type == 'error') { if (this.typeFilters.error) return true; // anything else is rich output (e.g. graphs) } else { if (this.typeFilters.rich) return true; } } return false; } /** * Updates the map visibleCards so that only cards matching searcg and filters are displayed. */ checkVisible() { for (let card of this.cards) { this.visibleCards.set(card, this.cardMatchesFilter(card) && this.cardMatchesSearchQuery(card)); } } /** * Toggles a cards selected state and updates the set of selectedCards. * @param card Selected Card */ cardSelected(card: Card) { if (this.selectedCards.has(card)) { this.selectedCards.delete(card); } else { this.selectedCards.add(card); } } /** * Toggles isSelecting (Selection Mode). * Resets selectedCards if toggling off. */ updateSelecting() { this.isSelecting = !this.isSelecting; if (!this.isSelecting) { this.selectedCards = new Set<Card>(); } } /** * Deletes cards in the selectedCards set. */ deleteSelectedCards() { let indexes = [] this.selectedCards.forEach(value => { const index: number = this.cards.indexOf(value); if (index > -1) { indexes.push(index) this.cards.splice(index, 1); } }) this.extension.deleteSelectedCards(indexes); // Informs backend of card deletion this.showUndoButton(indexes.length); } /** * Selects all cards and adds them to selectedCards. * If selectedCards already includes all cards then selectedCards is reset. */ selectAll() { if (this.selectedCards.size == this.cards.length) { this.selectedCards = new Set<Card>(); } else { this.selectedCards = new Set<Card>(this.cards); } } /** * Moves card in direction. * @param card Card being moved * @param direction "up" or "down" */ cardMoved(card: Card, direction: string) { if (direction === "up") this.moveUp(card); else if (direction === "down") this.moveDown(card); } /** * Moves card position up on display. * @param card Card being moved */ moveUp(card: Card) { const index: number = this.cards.indexOf(card, 1); if (index > -1) { const tmp: Card = this.cards[index - 1]; this.cards[index - 1] = this.cards[index]; this.cards[index] = tmp; this.extension.moveCardUp(index); } } /** * Moves card position down on display. * @param card Card being moved */ moveDown(card: Card) { const index: number = this.cards.indexOf(card); if (index > -1 && index < this.cards.length - 1) { const tmp: Card = this.cards[index + 1]; this.cards[index + 1] = this.cards[index]; this.cards[index] = tmp; this.extension.moveCardDown(index); } } /** * Exports cards. * If isSelecting is true only exports cards in selectedCards. */ export() { let indexes = null; if (this.isSelecting) { indexes = this.cards .filter(card => this.selectedCards.has(card)) .map((card, index) => index); } this.extension.jupyterExport(indexes); } /** * Save pdf output. * @param pdf PDF file encoded in base64. */ savePdf(pdf: string) { this.extension.savePdf(pdf); } /** * Opens card in broswer. * @param card Card to be viewed */ openBrowser(card: Card) { const index: number = this.cards.indexOf(card); this.extension.openInBrowser(index); } /** * Creates a new card at the bottom of the Output Pane and scrolls to it. * @param card */ addCard(card: Card) { this.cards.push(card); this.scrollToBottom(); } /** * Deletes the specified card. * @param card Card to be deleted */ deleteCard(card: Card) { const index: number = this.cards.indexOf(card); if (index > -1) { this.cards.splice(index, 1); this.extension.deleteCard(index); this.showUndoButton(1); } } /* Backend Communication */ /** * Tell the backend that the outputCollapsed property of a card has changed. */ collapseOutput(card: Card, value: boolean) { const index: number = this.cards.indexOf(card); this.extension.collapseOutput(index, value); } /** * Tell the backend that the codeCollapsed property of a card has changed. */ collapseCode(card: Card, value: boolean) { const index: number = this.cards.indexOf(card); this.extension.collapseCode(index, value); } /** * Tell the backend that the collapsed property of a card has changed. */ collapseCard(card: Card, value: boolean) { const index: number = this.cards.indexOf(card); this.extension.collapseCard(index, value); } /** * Tell the backend that the title property of a card has changed. */ changeTitle(card: Card, newTitle: string) { const index: number = this.cards.indexOf(card); this.extension.changeCardTitle(index, newTitle); } /** * Sync an entire card with the backend by sending its contents in full. * This is useful when editing markdown cards from the frontend, for example. */ editCustomCard(card: Card) { const index: number = this.cards.indexOf(card); this.extension.editCustomCard(index, card); } /** * Tell the backend that the undo button was clicked. */ undoClicked() { this.extension.undoClicked(); this.showingUndoButton = false; } private windowResizeThrottle; /** * Called when the onresize DOM event is fired. * It reloads plotly graphs to make sure that they resize appropriately. */ onWindowResize() { // make sure all scripted HTML fragments are re-sized appropriately. // this can be a bit inefficient, but it's only executed on window resize, // which doesn't happen very often anyway clearTimeout(this.windowResizeThrottle); this.windowResizeThrottle = setTimeout(() => { for (let card of this.cards) { for (let output of card.outputs) { if (output.type == 'text/html' || output.type == 'application/vnd.plotly.v1+json') { const o = output.output; output.output = ''; setTimeout(() => { output.output = o; }); } } } }, 400); } /** * Creates a blank markdown-only card and appends it to the array */ newMarkdownCard() { let markdownCard = new Card(0, '', '*Click to edit markdown*', [], {}, ''); markdownCard.isCustomMarkdown = true; this.cards.push(markdownCard); this.extension.addCustomCard(markdownCard); this.scrollToBottom(); } @ViewChild('scrollingList') scrollContainer; /** * Scroll the cards list to the bottom. */ scrollToBottom() { setTimeout(() => { try { this.scrollContainer.nativeElement.scrollTop = this.scrollContainer.nativeElement.scrollHeight; } catch (err) { } }, 0); } ngAfterViewInit() { this.scrollToBottom(); } }
the_stack
import { expect } from "chai"; import * as moq from "typemoq"; import { ECSqlStatement, ECSqlValue, IModelDb } from "@itwin/core-backend"; import { DbResult, Id64 } from "@itwin/core-bentley"; import { Content, PresentationError, PropertyValueFormat } from "@itwin/presentation-common"; import { createTestCategoryDescription, createTestContentDescriptor, createTestContentItem, createTestECClassInfo, createTestECInstanceKey, createTestNestedContentField, createTestSimpleContentField, } from "@itwin/presentation-common/lib/cjs/test"; import { buildElementsProperties, getElementsCount, iterateElementIds } from "../presentation-backend/ElementPropertiesHelper"; describe("buildElementsProperties", () => { it("returns empty array when given undefined content", () => { expect(buildElementsProperties(undefined)).to.be.empty; }); it("returns empty array when given content with no items", () => { expect(buildElementsProperties(new Content( createTestContentDescriptor({ fields: [] }), [], ))).to.be.empty; }); it("sets class label", () => { expect(buildElementsProperties(new Content( createTestContentDescriptor({ fields: [] }), [ createTestContentItem({ classInfo: createTestECClassInfo({ label: "Test label" }), values: {}, displayValues: {}, }), ], ))).to.containSubset([{ class: "Test label" }]); }); it("sets element label", () => { expect(buildElementsProperties(new Content( createTestContentDescriptor({ fields: [] }), [ createTestContentItem({ label: "Test label", values: {}, displayValues: {}, }), ], ))).to.containSubset([{ label: "Test label" }]); }); it("sets invalid element id when content item has not primary keys", () => { expect(buildElementsProperties(new Content( createTestContentDescriptor({ fields: [] }), [ createTestContentItem({ primaryKeys: [], values: {}, displayValues: {}, }), ], ))).to.containSubset([{ id: Id64.invalid }]); }); it("sets element id", () => { expect(buildElementsProperties(new Content( createTestContentDescriptor({ fields: [] }), [ createTestContentItem({ primaryKeys: [createTestECInstanceKey({ id: "0x123" })], values: {}, displayValues: {}, }), ], ))).to.containSubset([{ id: "0x123" }]); }); it("categorizes properties", () => { const parentCategory = createTestCategoryDescription({ name: "cat1", label: "Parent Category" }); const childCategory = createTestCategoryDescription({ name: "cat2", label: "Child Category", parent: parentCategory }); expect(buildElementsProperties(new Content( createTestContentDescriptor({ categories: [parentCategory, childCategory], fields: [ createTestSimpleContentField({ name: "prop1", label: "Prop One", category: parentCategory }), createTestSimpleContentField({ name: "prop2", label: "Prop Two", category: childCategory }), ], }), [ createTestContentItem({ values: { prop1: "value1", prop2: "value2", }, displayValues: { prop1: "Value One", prop2: "Value Two", }, }), ], ))).to.deep.eq([{ class: "", id: "0x1", label: "", items: { ["Parent Category"]: { type: "category", items: { ["Child Category"]: { type: "category", items: { ["Prop Two"]: { type: "primitive", value: "Value Two", }, }, }, ["Prop One"]: { type: "primitive", value: "Value One", }, }, }, }, }]); }); it("sets primitive property value to empty string when it's not set", () => { const category = createTestCategoryDescription({ label: "Test Category" }); expect(buildElementsProperties(new Content( createTestContentDescriptor({ categories: [category], fields: [ createTestSimpleContentField({ name: "emptyProp", label: "EmptyProp", category }), createTestSimpleContentField({ name: "undefinedProps", label: "UndefinedProp", category }), createTestSimpleContentField({ name: "prop", label: "Prop", category }), ], }), [ createTestContentItem({ values: { emptyProp: undefined, undefinedProps: undefined, prop: "valid value", }, displayValues: { emptyProp: "", undefinedProps: undefined, prop: "valid value", }, }), ], ))).to.deep.eq([{ class: "", id: "0x1", label: "", items: { ["Test Category"]: { type: "category", items: { ["EmptyProp"]: { type: "primitive", value: "", }, ["UndefinedProp"]: { type: "primitive", value: "", }, ["Prop"]: { type: "primitive", value: "valid value", }, }, }, }, }]); }); it("does not include category if it only has nested content field without values", () => { const category = createTestCategoryDescription({ label: "Test Category" }); expect(buildElementsProperties(new Content( createTestContentDescriptor({ categories: [category], fields: [ createTestNestedContentField({ name: "nestedField", category, nestedFields: [createTestSimpleContentField({ name: "primitiveField" })] }), ], }), [ createTestContentItem({ values: { nestedField: [], }, displayValues: { nestedField: [], }, }), ], ))).to.deep.eq([{ class: "", id: "0x1", label: "", items: {}, }]); }); it("sets property value to empty string when it's merged", () => { const category = createTestCategoryDescription({ label: "Test Category" }); expect(buildElementsProperties(new Content( createTestContentDescriptor({ categories: [category], fields: [ createTestSimpleContentField({ name: "prop", label: "Prop", category }), ], }), [ createTestContentItem({ values: { prop: "anything", }, displayValues: { prop: "anything", }, mergedFieldNames: ["prop"], }), ], ))).to.deep.eq([{ class: "", id: "0x1", label: "", items: { ["Test Category"]: { type: "category", items: { ["Prop"]: { type: "primitive", value: "", }, }, }, }, }]); }); it("handles struct properties", () => { const category = createTestCategoryDescription({ label: "Test Category" }); expect(buildElementsProperties(new Content( createTestContentDescriptor({ categories: [category], fields: [ createTestSimpleContentField({ name: "prop", label: "Prop", category, type: { valueFormat: PropertyValueFormat.Struct, typeName: "Test Struct", members: [{ name: "member1", label: "Member One", type: { valueFormat: PropertyValueFormat.Primitive, typeName: "Primitive One", }, }, { name: "member2", label: "Member Two", type: { valueFormat: PropertyValueFormat.Primitive, typeName: "Primitive Two", }, }], }, }), ], }), [ createTestContentItem({ values: { prop: { member1: "value1", member2: "value2", }, }, displayValues: { prop: { member1: "Value One", member2: "Value Two", }, }, }), ], ))).to.deep.eq([{ class: "", id: "0x1", label: "", items: { ["Test Category"]: { type: "category", items: { ["Prop"]: { type: "struct", members: { ["Member One"]: { type: "primitive", value: "Value One", }, ["Member Two"]: { type: "primitive", value: "Value Two", }, }, }, }, }, }, }]); }); it("handles primitive array properties", () => { const category = createTestCategoryDescription({ label: "Test Category" }); expect(buildElementsProperties(new Content( createTestContentDescriptor({ categories: [category], fields: [ createTestSimpleContentField({ name: "prop", label: "Prop", category, type: { valueFormat: PropertyValueFormat.Array, typeName: "Test Array", memberType: { valueFormat: PropertyValueFormat.Primitive, typeName: "Test Primitive", }, }, }), ], }), [ createTestContentItem({ values: { prop: ["value1", "value2"], }, displayValues: { prop: ["Value One", "Value Two"], }, }), ], ))).to.deep.eq([{ class: "", id: "0x1", label: "", items: { ["Test Category"]: { type: "category", items: { ["Prop"]: { type: "array", valueType: "primitive", values: ["Value One", "Value Two"], }, }, }, }, }]); }); it("handles struct array properties", () => { const category = createTestCategoryDescription({ label: "Test Category" }); expect(buildElementsProperties(new Content( createTestContentDescriptor({ categories: [category], fields: [ createTestSimpleContentField({ name: "prop", label: "Prop", category, type: { valueFormat: PropertyValueFormat.Array, typeName: "Test Array", memberType: { valueFormat: PropertyValueFormat.Struct, typeName: "Test Struct", members: [{ name: "member", label: "Test Member", type: { valueFormat: PropertyValueFormat.Primitive, typeName: "Test Primitive", }, }], }, }, }), ], }), [ createTestContentItem({ values: { prop: [{ member: "value1", }, { member: "value2", }], }, displayValues: { prop: [{ member: "Value One", }, { member: "Value Two", }], }, }), ], ))).to.deep.eq([{ class: "", id: "0x1", label: "", items: { ["Test Category"]: { type: "category", items: { ["Prop"]: { type: "array", valueType: "struct", values: [{ ["Test Member"]: { type: "primitive", value: "Value One", }, }, { ["Test Member"]: { type: "primitive", value: "Value Two", }, }], }, }, }, }, }]); }); }); describe("getElementsCount", () => { const imodelMock = moq.Mock.ofType<IModelDb>(); beforeEach(() => { imodelMock.reset(); }); it("returns 0 when statement has no rows", () => { imodelMock.setup((x) => x.withPreparedStatement(moq.It.isAnyString(), moq.It.isAny())).returns((_q, cb) => { const statementMock = moq.Mock.ofType<ECSqlStatement>(); statementMock.setup((x) => x.step()).returns(() => DbResult.BE_SQLITE_DONE); return cb(statementMock.object); }); expect(getElementsCount(imodelMock.object)).to.be.eq(0); }); it("returns count when statement has row", () => { const elementCount = 3; imodelMock.setup((x) => x.withPreparedStatement(moq.It.isAnyString(), moq.It.isAny())).returns((_q, cb) => { const valueMock = moq.Mock.ofType<ECSqlValue>(); valueMock.setup((x) => x.getInteger()).returns(() => elementCount); const statementMock = moq.Mock.ofType<ECSqlStatement>(); statementMock.setup((x) => x.step()).returns(() => DbResult.BE_SQLITE_ROW); statementMock.setup((x) => x.getValue(0)).returns(() => valueMock.object); return cb(statementMock.object); }); expect(getElementsCount(imodelMock.object)).to.be.eq(elementCount); }); it("adds WHERE clause when class list is defined and not empty", () => { imodelMock.setup((x) => x.withPreparedStatement(moq.It.is((query) => query.includes("WHERE")), moq.It.isAny())) .returns(() => 0).verifiable(); getElementsCount(imodelMock.object, ["TestSchema:TestClass"]); imodelMock.verifyAll(); }); it("throws if class list contains invalid class name", () => { expect(() => getElementsCount(imodelMock.object, ["'TestSchema:TestClass'"])).to.throw(PresentationError); expect(() => getElementsCount(imodelMock.object, ["%TestSchema:TestClass%"])).to.throw(PresentationError); expect(() => getElementsCount(imodelMock.object, ["TestSchema:TestClass "])).to.throw(PresentationError); }); }); describe("iterateElementIds", () => { const imodelMock = moq.Mock.ofType<IModelDb>(); beforeEach(() => { imodelMock.reset(); }); function collectResults<T>(generator: Generator<T>) { const results = []; for (const entry of generator) { results.push(entry); } return results; } it("returns empty map when statement has no rows", () => { imodelMock.setup((x) => x.withPreparedStatement(moq.It.isAnyString(), moq.It.isAny())).returns((_q, cb) => { const statementMock = moq.Mock.ofType<ECSqlStatement>(); statementMock.setup((x) => x.step()).returns(() => DbResult.BE_SQLITE_DONE); return cb(statementMock.object); }); expect(collectResults(iterateElementIds(imodelMock.object))).to.be.deep.eq([new Map<string, string[]>()]); }); it("returns ids grouped by class when statement has rows", () => { const elements = [ { className: "TestSchema:TestClass", id: "0x1" }, { className: "TestSchema:TestClass", id: "0x2" }, { className: "TestSchema:TestClass2", id: "0x3" }, { className: "TestSchema:TestClass", id: "0x4" }, ]; imodelMock.setup((x) => x.withPreparedStatement(moq.It.isAnyString(), moq.It.isAny())).returns((_q, cb) => { const statementMock = moq.Mock.ofType<ECSqlStatement>(); for (const element of elements) { statementMock.setup((x) => x.step()).returns(() => DbResult.BE_SQLITE_ROW); statementMock.setup((x) => x.getRow()).returns(() => ({ elId: element.id, elClassName: element.className })); } statementMock.setup((x) => x.step()).returns(() => DbResult.BE_SQLITE_DONE); return cb(statementMock.object); }); const expectedResult = [new Map<string, string[]>([ ["TestSchema:TestClass", ["0x1", "0x2", "0x4"]], ["TestSchema:TestClass2", ["0x3"]], ])]; expect(collectResults(iterateElementIds(imodelMock.object))).to.be.deep.eq(expectedResult); }); it("skips rows without class name or id", () => { const elements = [ { className: undefined, id: "0x1" }, { className: "TestSchema:TestClass", id: undefined }, { className: "TestSchema:TestClass", id: "0x2" }, ]; imodelMock.setup((x) => x.withPreparedStatement(moq.It.isAnyString(), moq.It.isAny())).returns((_q, cb) => { const statementMock = moq.Mock.ofType<ECSqlStatement>(); for (const element of elements) { statementMock.setup((x) => x.step()).returns(() => DbResult.BE_SQLITE_ROW); statementMock.setup((x) => x.getRow()).returns(() => ({ elId: element.id, elClassName: element.className })); } statementMock.setup((x) => x.step()).returns(() => DbResult.BE_SQLITE_DONE); return cb(statementMock.object); }); const expectedResult = [ new Map<string, string[]>([ ["TestSchema:TestClass", ["0x2"]], ])]; expect(collectResults(iterateElementIds(imodelMock.object))).to.be.deep.eq(expectedResult); }); it("adds WHERE clause when class list is defined and not empty", () => { imodelMock.setup((x) => x.withPreparedStatement(moq.It.is((query) => query.includes("WHERE") && query.includes("IS (TestSchema:TestClass)")), moq.It.isAny())) .returns((_q, cb) => { const statementMock = moq.Mock.ofType<ECSqlStatement>(); statementMock.setup((x) => x.step()).returns(() => DbResult.BE_SQLITE_DONE); return cb(statementMock.object); }) .verifiable(); collectResults(iterateElementIds(imodelMock.object, ["TestSchema:TestClass"])); imodelMock.verifyAll(); }); it("queries ids in pages", () => { imodelMock.setup((x) => x.withPreparedStatement(moq.It.is((query) => !query.includes("WHERE")), moq.It.isAny())) .returns((_q, cb) => { const statementMock = moq.Mock.ofType<ECSqlStatement>(); statementMock.setup((x) => x.step()).returns(() => DbResult.BE_SQLITE_ROW); statementMock.setup((x) => x.getRow()).returns(() => ({ elId: "0x1", elClassName: "TestClass" })); return cb(statementMock.object); }) .verifiable(); imodelMock.setup((x) => x.withPreparedStatement(moq.It.is((query) => query.includes("ECInstanceId > ?")), moq.It.isAny())) .returns((_q, cb) => { const statementMock = moq.Mock.ofType<ECSqlStatement>(); statementMock.setup((x) => x.bindId(1, "0x1")).verifiable(); statementMock.setup((x) => x.step()).returns(() => DbResult.BE_SQLITE_DONE); return cb(statementMock.object); }) .verifiable(); collectResults(iterateElementIds(imodelMock.object, undefined, 1)); imodelMock.verifyAll(); }); it("queries ids in pages with class filter", () => { imodelMock.setup((x) => x.withPreparedStatement(moq.It.is((query) => query.includes("IS (TestSchema:TestClass)") && !query.includes("ECInstanceId > ?")), moq.It.isAny())) .returns((_q, cb) => { const statementMock = moq.Mock.ofType<ECSqlStatement>(); statementMock.setup((x) => x.step()).returns(() => DbResult.BE_SQLITE_ROW); statementMock.setup((x) => x.getRow()).returns(() => ({ elId: "0x1", elClassName: "TestClass" })); return cb(statementMock.object); }) .verifiable(); imodelMock.setup((x) => x.withPreparedStatement(moq.It.is((query) => query.includes("IS (TestSchema:TestClass)") && query.includes("ECInstanceId > ?")), moq.It.isAny())) .returns((_q, cb) => { const statementMock = moq.Mock.ofType<ECSqlStatement>(); statementMock.setup((x) => x.bindId(1, "0x1")).verifiable(); statementMock.setup((x) => x.step()).returns(() => DbResult.BE_SQLITE_DONE); return cb(statementMock.object); }) .verifiable(); collectResults(iterateElementIds(imodelMock.object, ["TestSchema:TestClass"], 1)); imodelMock.verifyAll(); }); it("throws if class list contains invalid class name", () => { expect(() => collectResults(iterateElementIds(imodelMock.object, ["'TestSchema:TestClass'"]))).to.throw(PresentationError); expect(() => collectResults(iterateElementIds(imodelMock.object, ["%TestSchema:TestClass%"]))).to.throw(PresentationError); expect(() => collectResults(iterateElementIds(imodelMock.object, ["TestSchema:TestClass "]))).to.throw(PresentationError); }); });
the_stack
import { Module, Configuration } from '@nuxt/types' import { NuxtRouteConfig } from '@nuxt/types/config/router' import fs from 'fs-extra' import path from 'path' import execa from 'execa' import { URL } from 'url' import { EOL } from 'os' import { moduleKey, laravelAppEnv, nuxtOutputEnv } from './constants' import { logger, addBadgeMessage, getModuleOptions } from './utils' import { getConfiguration, Options } from './options' const laravelModule: Module<Options> = function (overwrites) { const config = getConfiguration(this.options, overwrites) /** GLOBAL CONTEXT **/ /* Validation */ // Fail with a warning if we are not in 'spa' mode if (this.options.mode !== 'spa') { logger.warn(`nuxt-laravel currently only supports 'spa' mode`) addBadgeMessage(this.options, false) return } // Fail with error if laravelRoot is invalid if (!fs.existsSync(path.join(config.laravel.root, 'artisan'))) { logger.error( `Unable to find 'artisan' executable in Laravel path: ${config.laravel.root}` ) addBadgeMessage(this.options, false) return } // Fail with error if publicDir cannot be found if (!fs.existsSync(config.laravel.public)) { logger.error(`Unable to find Laravel public dir: ${config.laravel.public}`) addBadgeMessage(this.options, false) return } /* Implementation */ // Optional cache module if (config.cache) { const pwa = getModuleOptions(this.options, '@nuxtjs/pwa') const routingExtensions = (pwa && pwa.workbox && pwa.workbox.routingExtensions) || [] const { dst } = this.addTemplate({ src: path.join(__dirname, 'templates', 'workbox.cache.ejs'), options: config.cache, fileName: config.cache.fileName, }) this.options.pwa = { ...pwa, workbox: { ...(pwa && pwa.workbox), routingExtensions: [ ...(typeof routingExtensions === 'string' ? [routingExtensions] : routingExtensions), path.join(this.options.buildDir!, dst), ], }, } this.requireModule('@nuxtjs/pwa') } /** DEV behavior **/ if (this.options.dev) { /* Validation */ // Fail with warning if server is not configured if (!config.laravel.server) { logger.warn('Laravel test server is disabled') addBadgeMessage(this.options, false) return } // Fail with error if nuxt dev server is not configured if (!this.options.server) { logger.warn('Nuxt dev server is disabled') addBadgeMessage(this.options, false) return } /* Implementation */ // resolve pertinent config parameters const laravelUrl = new URL( `http://${config.laravel.server.host || 'localhost'}:${ config.laravel.server.port }` ) this.options.axios = { ...(this.options.axios || {}), proxy: true, } this.options.proxy = [ ...(this.options.proxy || []), [ [ '**', `!${config.nuxt.urlPath}`, `!${path.posix.join(config.routerBase, '_loading')}/**`, ], { target: laravelUrl.origin, ws: false, logLevel: 'debug', }, ], ] // configure proxy this.requireModule('@nuxtjs/axios') // extend routes to provide an endpoint for Laravel this.extendRoutes((routes: NuxtRouteConfig[]) => { let index = routes.find( // First, check if there is an unnamed route // Then, check if there's a route at / // Finally, check for a name with first segment index (route) => route.name === '' || route.path === '/' || !!(route.name && route.name.match(/^index(-\w+)?$/)) ) // If we were unable to resolve the index route, // but modules are present if (!index && this.options.modules) { const i18nOptions = getModuleOptions(this.options, 'nuxt-i18n') // if i18n module is present, we try to find the translated index route if (i18nOptions && i18nOptions.defaultLocale) { const separator = i18nOptions.routesNameSeparator || '___' index = routes.find( (route) => !!( route.name && route.name.match( new RegExp(`^index${separator}${i18nOptions.defaultLocale}`) ) ) ) } } // Fail with error if index route cannot be resolved if (!index) { logger.error('Unable to resolve index route') addBadgeMessage(this.options, false) return } // add a copy of the index route // on the specified render path routes.push({ ...index, name: moduleKey, path: config.nuxt.routerPath, }) }) // start Laravel test server on render:before let _serverInitialized = false this.nuxt.hook( 'render:before', async ({ options }: { options: Configuration }) => { /* istanbul ignore next */ if (_serverInitialized) { return } _serverInitialized = true const nuxtServer = options.server! if ( fs.existsSync(config.output.dest) && config.output.dest.replace(config.laravel.public, '').length > 1 ) { logger.warn( `Removing production build from: ${config.output.dest} to avoid conflicts with dev server` ) fs.removeSync(config.output.dest) } const nuxtHost = ['0.0.0.0', '127.0.0.1'].includes(`${nuxtServer.host}`) ? 'localhost' : nuxtServer.host // retrieve dev server URL const nuxtUrl = new URL( config.nuxt.urlPath, `http${!!nuxtServer.https ? 's' : ''}://${nuxtHost}:${ nuxtServer.port }` ) // try to start artisan server from Laravel path logger.debug(`Nuxt url: ${nuxtUrl.href}`) logger.debug(`Laravel url: ${laravelUrl.href}`) try { const server = execa( 'php', [ 'artisan', 'serve', `--host=${ laravelUrl.hostname === 'localhost' ? '127.0.0.1' : laravelUrl.hostname }`, `--port=${laravelUrl.port}`, ], { cwd: config.laravel.root, // forward render path and baseUrl as env variables env: { ...process.env, [laravelAppEnv]: nuxtUrl.origin, [nuxtOutputEnv]: nuxtUrl.href, }, stderr: process.stderr, stdout: process.stdout, } ) /* istanbul ignore next */ server.on('error', () => { logger.error(`Laravel server failed`) if (server && !server.killed) { server.kill('SIGKILL') } }) } catch (error) { logger.error(`Failed to start Laravel server`) addBadgeMessage(options, false) return } addBadgeMessage(options) } ) return } // PROD behavior // configure generation this.options.generate = { ...this.options.generate, dir: config.output.src, exclude: [/.*/], fallback: config.output.fallback, } this.nuxt.hook('generate:done', async ({ nuxt }: { nuxt: any }) => { // generate assets logger.info('Generating SPA assets...') if (config.output.dest.replace(config.laravel.public, '').length > 1) { fs.ensureDirSync(config.output.dest) fs.moveSync(config.output.src, config.output.dest, { overwrite: true }) } else { fs.copySync(config.output.src, config.output.dest) fs.removeSync(config.output.src) } logger.success(`SPA assets generated in: ${config.output.dest}`) const defaultOutput = path.join(config.output.dest, config.output.fallback) if (config.output.additional) { if (defaultOutput === config.output.additional) { logger.info( 'Skipping index file output, because output path corresponds to default location' ) } else { const indexPath = config.output.additional // render index route logger.info('Rendering additional output file...') try { const { html, error } = await nuxt.server.renderRoute('/') /* istanbul ignore if */ if (error) { throw error } fs.ensureDirSync(path.dirname(indexPath)) fs.writeFileSync(indexPath, html, 'utf-8') logger.success(`SPA index file rendered to: ${indexPath}`) } catch (error) { logger.error('Failed to render index route:', error) return } } } // write to .env file if (config.options.dotEnvExport) { const envPath = path.join(config.laravel.root, '.env') if (fs.existsSync(envPath)) { const indexPath = config.output.additional || defaultOutput const envInput = fs.readFileSync(envPath).toString() const envOutputPrefix = `${EOL}# Added by 'nuxt-laravel' module${EOL}${nuxtOutputEnv}` const envOutput = `${envOutputPrefix}=${indexPath}` fs.writeFileSync( envPath, envInput.includes(envOutputPrefix) ? envInput.replace(new RegExp(`${envOutputPrefix}.*`), envOutput) : envInput.includes(nuxtOutputEnv) ? envInput.replace(new RegExp(`${nuxtOutputEnv}.*`), envOutput) : envInput.concat(envOutput) ) } } }) logger.info('Generation configured for Laravel SPA.') } declare module '@nuxt/types' { interface Configuration { laravel?: Options } } export { Options, moduleKey, laravelAppEnv, nuxtOutputEnv } export default laravelModule export const meta = require('../package.json')
the_stack
import * as sentryNode from '@sentry/node'; import * as sentryReact from '@sentry/react'; import { serialize } from 'cookie'; import type { GetServerSidePropsContext } from 'next'; import { FALLBACK_LANGUAGE, SESSION_COOKIE_NAME } from '../../../src/constants'; import type { Namespace } from '../../../src/constants'; import { createNextApiRequestMock, createServerResponseMock, } from '../../../testUtils/api'; import { i18nCache } from '../../../testUtils/i18n'; import { createMockScope } from '../../../testUtils/sentry'; import * as cookieUtils from '../../server/auth/cookie'; import * as sentryUtils from '../../utils/sentry/client'; import * as sentryUtilsServer from '../../utils/sentry/server'; import { TEMPORARY_REDIRECT } from '../../utils/statusCodes'; import type { User } from '../context/AuthContext/types'; import { getServerSideProps, withKarmaSSRProps, createGetServerSideProps, } from '../karma/getServerSideProps'; import * as i18n from '../karma/i18n'; const mockCtx: GetServerSidePropsContext = { query: {}, req: createNextApiRequestMock(), res: createServerResponseMock({ end: jest.fn(), writeHead: jest.fn(), }), resolvedUrl: '', }; const setupSpies = () => { const getSessionSpy = jest .spyOn(cookieUtils, 'getSession') .mockReturnValueOnce(null); const getI18nSpy = jest .spyOn(i18n, 'getI18n') .mockImplementationOnce((language, { namespaces } = {}) => { if (Array.isArray(namespaces) && namespaces.length > 0) { return Promise.resolve({ [language]: Object.fromEntries( namespaces.map((namespace) => [ namespace, i18nCache[language][namespace], ]) ), }); } return Promise.resolve({ [language]: i18nCache[language] }); }); const attachInitialContextSpy = jest.spyOn( sentryUtils, 'attachInitialContext' ); const attachLambdaContextSpy = jest.spyOn( sentryUtilsServer, 'attachLambdaContext' ); const setContextSpy = jest.fn(); const setExtraSpy = jest.fn(); const configureScopeSpy = jest .spyOn(sentryReact, 'configureScope') // eslint-disable-next-line promise/prefer-await-to-callbacks .mockImplementationOnce((callback) => { // eslint-disable-next-line promise/prefer-await-to-callbacks callback( createMockScope({ setContext: setContextSpy, setExtra: setExtraSpy }) ); }); return { attachInitialContextSpy, attachLambdaContextSpy, configureScopeSpy, getI18nSpy, getSessionSpy, setContextSpy, setExtraSpy, }; }; const setup = async ( ctx = mockCtx, options?: Parameters<typeof getServerSideProps>[1] ) => { const spies = setupSpies(); const result = await getServerSideProps(ctx ?? mockCtx, options); return { result, ...spies, }; }; describe('getServerSideProps', () => { test('attaches initial context', async () => { const mockSession: User = { id: '', name: '' }; const headers = { cookie: serialize(SESSION_COOKIE_NAME, JSON.stringify(mockSession)), }; const mockCtx: GetServerSidePropsContext = { query: {}, req: createNextApiRequestMock({ headers }), res: createServerResponseMock(), resolvedUrl: '', }; jest.spyOn(cookieUtils, 'getSession').mockReturnValueOnce(mockSession); const { attachInitialContextSpy, setContextSpy, setExtraSpy, configureScopeSpy, } = await setup(mockCtx); expect(attachInitialContextSpy).toHaveBeenCalledWith( expect.objectContaining({ locale: FALLBACK_LANGUAGE, req: mockCtx.req, session: mockSession, }) ); expect(configureScopeSpy).toHaveBeenCalledTimes(1); expect(setExtraSpy).toHaveBeenCalledWith('locale', FALLBACK_LANGUAGE); expect(setContextSpy).toHaveBeenCalledWith('headers', headers); expect(setContextSpy).toHaveBeenCalledWith('session', mockSession); }); test('attaches lambda context', async () => { const setContextSpy = jest.fn(); const setTagSpy = jest.fn(); const configureScopeSpy = jest .spyOn(sentryNode, 'configureScope') // eslint-disable-next-line promise/prefer-await-to-callbacks .mockImplementationOnce((callback) => { // eslint-disable-next-line promise/prefer-await-to-callbacks callback( createMockScope({ setContext: setContextSpy, setTag: setTagSpy }) ); }); const { attachLambdaContextSpy } = await setup(); expect(attachLambdaContextSpy).toHaveBeenCalledWith(mockCtx.req); expect(configureScopeSpy).toHaveBeenCalledTimes(1); expect(setContextSpy).toHaveBeenCalledWith('headers', expect.any(Object)); expect(setTagSpy).toHaveBeenCalledWith('host', expect.any(String)); expect(setTagSpy).toHaveBeenCalledWith('url', expect.any(String)); expect(setTagSpy).toHaveBeenCalledWith('method', expect.any(String)); }); describe('auth', () => { test('loads session', async () => { const { getSessionSpy } = await setup(); expect(getSessionSpy).toHaveBeenCalledWith(mockCtx.req); }); describe('given no session and options.auth.redirectDestinationIfUnauthenticated', () => { test('redirects serverside', async () => { const url = '/foo'; const { result } = await setup(mockCtx, { auth: { redirectDestinationIfUnauthenticated: url }, i18n: {}, }); expect(mockCtx.res.writeHead).toHaveBeenCalledTimes(1); expect(mockCtx.res.writeHead).toHaveBeenCalledWith( TEMPORARY_REDIRECT, expect.objectContaining({ Location: url, }) ); expect(mockCtx.res.end).toHaveBeenCalledTimes(1); expect(result).toStrictEqual({ props: { karma: { auth: { redirectDestinationIfUnauthenticated: url, session: null, }, i18n: { locale: FALLBACK_LANGUAGE, resources: {}, }, }, }, }); }); test('forwards url for client side redirect given a referrer', async () => { const url = '/foo'; const req = createNextApiRequestMock({ headers: { referer: '/', }, }); const { result } = await setup( { ...mockCtx, req }, { auth: { redirectDestinationIfUnauthenticated: url }, i18n: {}, } ); expect(mockCtx.res.writeHead).not.toHaveBeenCalledTimes(1); expect(mockCtx.res.end).not.toHaveBeenCalledTimes(1); expect(result).toStrictEqual({ props: { karma: { auth: { redirectDestinationIfUnauthenticated: url, session: null, }, i18n: { locale: FALLBACK_LANGUAGE, resources: {}, }, }, }, }); }); }); }); describe('i18n', () => { test('loads i18n resources', async () => { const { getI18nSpy } = await setup(); expect(getI18nSpy).toHaveBeenCalledWith(FALLBACK_LANGUAGE, { namespaces: undefined, }); }); }); test('matches expected shape', async () => { const { result } = await setup(); expect(result).toStrictEqual({ props: { karma: { auth: { session: null, }, cookies: '', i18n: { locale: FALLBACK_LANGUAGE, resources: { [FALLBACK_LANGUAGE]: i18nCache[FALLBACK_LANGUAGE], }, }, }, }, }); }); }); describe('createGetServerSideProps', () => { const namespaces: Namespace[] = ['serviceWorker']; describe('i18n', () => { test('forwards namespaces onto getI18n', async () => { const { getI18nSpy } = setupSpies(); await createGetServerSideProps({ i18n: { namespaces: [], }, })(mockCtx); expect(getI18nSpy).toHaveBeenCalledWith( FALLBACK_LANGUAGE, expect.objectContaining({ namespaces: [], }) ); }); test('given empty namespaces, loads all namespaces', async () => { setupSpies(); const result = await createGetServerSideProps({ i18n: { namespaces: [], }, })(mockCtx); expect(result.props.karma.i18n.resources).toMatchObject({ [FALLBACK_LANGUAGE]: i18nCache[FALLBACK_LANGUAGE], }); }); test('given a single namespace, loads only that one', async () => { setupSpies(); const result = await createGetServerSideProps({ i18n: { namespaces } })( mockCtx ); expect(result.props.karma.i18n.resources).toStrictEqual({ [FALLBACK_LANGUAGE]: { [namespaces[0]]: expect.any(Object), }, }); }); }); }); describe('withServerSideKarmaProps', () => { const mockProps = { foo: 1 }; test('executes given handler, forwarding context', async () => { setupSpies(); const mockHandler = jest.fn().mockResolvedValueOnce({ props: mockProps }); const getServerSideProps = withKarmaSSRProps(mockHandler); await getServerSideProps(mockCtx); expect(mockHandler).toHaveBeenCalledWith(mockCtx); }); test('bubbles errors', async () => { setupSpies(); const mockError = new Error('error'); const mockHandler = jest.fn().mockImplementationOnce(() => { throw mockError; }); const getServerSideProps = withKarmaSSRProps(mockHandler); const errorHandler = jest.fn(); try { await getServerSideProps(mockCtx); } catch (error) { errorHandler(error); } expect(errorHandler).toHaveBeenCalledTimes(1); expect(errorHandler).toHaveBeenCalledWith(mockError); }); test('merges karma getServerSideProps with handlers result', async () => { setupSpies(); const mockHandler = jest.fn().mockResolvedValueOnce({ props: mockProps }); const getServerSideProps = withKarmaSSRProps(mockHandler); const result = await getServerSideProps(mockCtx); expect(result).toStrictEqual({ props: { karma: { auth: { session: null, }, cookies: '', i18n: { locale: FALLBACK_LANGUAGE, resources: { [FALLBACK_LANGUAGE]: i18nCache[FALLBACK_LANGUAGE], }, }, }, ...mockProps, }, }); }); });
the_stack
///<reference types="winrt"/> declare namespace PlayerFramework { // Enumerations enum AdvertisingState { /** * No ad is loading or playing. **/ none = 0, /** * An ad is loading. **/ loading = 1, /** * A linear ad is playing. **/ linear = 2, /** * A non-linear ad is playing. **/ nonLinear = 3 } enum AutohideBehavior { /** * No behaviors are applied to the autohide feature. **/ none = 0, /** * Autohide is allowed during media playback only. **/ allowDuringPlaybackOnly = 1, /** * Autohide is prevented when the pointer is over interactive components such as the control panel. **/ preventDuringInteractiveHover = 2, /** * All behaviors are applied to the autohide feature. **/ all = 3 } enum InteractionType { /** * Indicates no interaction. **/ none = 0, /** * Indicates a "soft" interaction such as mouse movement or a timeout occurring. **/ soft = 1, /** * Indicates a "hard" interaction such as a tap, click, or a key is pressed. **/ hard = 2, /** * Indicates both "soft" and "hard" interactions. **/ all = 3 } enum NetworkState { /** * The player has not yet initialized any audio/video. **/ empty = 0, /** * The player has active audio/video and has selected a resource, but is not using the network. **/ idle = 1, /** * The player is downloading data. **/ loading = 2, /** * The player has no audio/video source. **/ noSource = 3 } enum MediaQuality { /** * Typically indicates less than 720p media quality. **/ standardDefinition = 0, /** * Typically indicates greater than or equal to 720p media quality. **/ highDefinition = 1 } enum PlayerState { /** * The player is unloaded and no media source is set. **/ unloaded = 0, /** * The media source is set and the player is waiting to load the media (e.g. autoload is false). **/ pending = 1, /** * The media source is set, but the player is still executing loading operations. **/ loading = 2, /** * The media has finished loading, but has not been opened yet. **/ loaded = 3, /** * The media can be played. **/ opened = 4, /** * The media has been told to start playing, but the player is still executing starting operations. **/ starting = 5, /** * The media has been started and the player is either playing or paused. **/ started = 6, /** * The media has finished, but the player is still executing ending operations. **/ ending = 7, /** * The media has ended. **/ ended = 8, /** * The media has failed and the player must be reloaded. **/ failed = 9, } enum ReadyState { /** * The player has no information for the audio/video **/ nothing = 0, /** * The player has metadata for the audio/video. **/ metadata = 1, /** * The player has data for the current playback position, but not enough data to play the next frame. **/ currentData = 2, /** * The player has data for the current playback position and at least the next frame. **/ futureData = 3, /** * The player has enough data available to start playing. **/ enoughData = 4 } enum MediaErrorCode { /** * An unknown media error occurred. **/ unknown = 0, /** * Media playback was aborted. **/ aborted = 1, /** * Media download failed due to a network error. **/ network = 2, /** * Media playback was aborted due to a corruption problem or because unsupported features were used. **/ decode = 3, /** * Media source could not be loaded either because the server or network failed or because the format is not supported. **/ notSupported = 4 } enum ImageErrorCode { /** * An unknown image error occurred. **/ unknown = 0, /** * Image download was aborted. **/ aborted = 1 } class TextTrackMode { /** * The track is disabled. **/ static off: string; /** * The track is active, but the player is not actively displaying cues. **/ static hidden: string; /** * The track is active and the player is actively displaying cues. **/ static showing: string; } enum TextTrackDisplayMode { /** * Indicates tracks should not be displayed. */ none = 0, /** * Indicates tracks should be displayed using custom UI. */ custom = 1, /** * Indicates tracks should be displayed using native UI. */ native = 2, /** * Indicates tracks should be displayed using both custom and native UI. This is useful for debugging. */ all = 3 } enum TextTrackReadyState { /** * The track is unloaded. */ none = 0, /** * The track is currently loading. */ loading = 1, /** * The track is loaded. */ loaded = 2, /** * The track failed to load. */ error = 3 } enum ViewModelState { /** * No media is loaded. */ unloaded = 0, /** * The media is loading. */ loading = 1, /** * The media is paused. */ paused = 2, /** * The media is playing. */ playing = 3 } interface PlaylistItem { src: string; tracks?: Array<any>; //TODO } class PluginBase { isEnabled: boolean; isLoaded: boolean; isActive: boolean; mediaPlayer: MediaPlayer; currentMediaSource: MediaSource; load(): void; unload(): void; update(mediaSource: MediaSource): void; } namespace Plugins { class TrackingPluginBase extends PluginBase { trackingEvents: Array<any>; } class BufferingPlugin extends PluginBase { hide(): void; show(): void; } class ControlPlugin extends PluginBase { compactThresholdInInches(): number; hide(): void; isCompact(): boolean; orientation(): string; show(): void; } class ErrorPlugin extends PluginBase { hide(): void; show(): void; } class LoaderPlugin extends PluginBase { hide(): void; show(): void; } /** * **/ class PlaylistPlugin extends PluginBase { /** * **/ autoAdvance: boolean; /** * **/ currentPlaylistItem: PlaylistItem; /** * **/ currentPlaylistItemIndex: number; /** * **/ playlist: Array<PlaylistItem>; /** * **/ startupPlaylistItemIndex: number; /** * **/ skipBackThreshold: number; // Methods goToPreviousPlaylistItem(): void; goToNextPlaylistItem(): void; canGoToPreviousPlaylistItem(): boolean; canGoToNextPlaylistItem(): boolean; } class PlayTimeTrackingPlugin extends PluginBase { playTime: number; playTimePercentage: number; } class PositionTrackingPlugin extends PluginBase { evaluateOnForwardOnly: boolean; position: number; positionPercentage: number; } class SystemTransportControlsPlugin extends PluginBase { isPreviousTrackEnabled: boolean; isNextTrackEnabled: boolean; nextTrackExists: boolean; previousTrackExists: boolean; } class ChaptersPlugin extends PluginBase { defaultChapterCount: number; autoCreateDefaultChapters: boolean; autoCreateChaptersFromTextTracks: boolean; visualMarkerClass: string; } class DisplayRequestPlugin extends PluginBase { isRequestActive: boolean; } class CaptionSelectorPlugin extends PluginBase { hide(): void; show(): void; /** * Not available in phone. **/ alignment: string; /** * Not available in phone. **/ anchor: HTMLElement; /** * Not available in phone. **/ placement: string; } class AudioSelectorPlugin extends PluginBase { hide(): void; show(): void; /** * Not available in phone. **/ alignment: string; /** * Not available in phone. **/ anchor: HTMLElement; /** * Not available in phone. **/ placement: string; } } /** * **/ class InteractiveViewModel { /** * TODO **/ state: ViewModelState; /** * TODO **/ startTime: number; /** * TODO **/ maxTime: number; /** * TODO **/ endTime: number; /** * TODO **/ currentItem: number; /** * TODO **/ bufferedPercentage: number; /** * TODO **/ playPouseIcon: string; /** * TODO **/ playPauseLabel: string; /** * TODO **/ playPauseTooltip: string; /** * TODO **/ isPlayPauseDisabled: boolean; /** * TODO **/ isPlayPauseHidden: boolean; /** * TODO **/ playResumeIcon: string; /** * TODO **/ playResumeLabel: string; /** * TODO **/ playResumeTooltip: string; /** * TODO **/ isPlayResumeDisabled: boolean; /** * TODO **/ isPlayResumeHidden: boolean; /** * TODO **/ pauseIcon: string; /** * TODO **/ pauseLabel: string; /** * TODO **/ pauseTooltip: string; /** * TODO **/ isPauseDisabled: boolean; /** * TODO **/ isPauseHidden: boolean; /** * TODO **/ replayIcon: string; /** * TODO **/ replayLabel: string; /** * TODO **/ replayTooltip: string; /** * TODO **/ isReplayDisabled: boolean; /** * TODO **/ isReplayHidden: boolean; /** * TODO **/ rewindIcon: string; /** * TODO **/ rewindLabel: string; /** * TODO **/ rewindTooltip: string; /** * TODO **/ isRewindDisabled: boolean; /** * TODO **/ isRewindHidden: boolean; /** * TODO **/ fastForwardIcon: string; /** * TODO **/ fastForwardLabel: string; /** * TODO **/ fastForwardTooltip: string; /** * TODO **/ isFastForwardDisabled: boolean; /** * TODO **/ isFastForwardHidden: boolean; /** * TODO **/ slowMotionIcon: string; /** * TODO **/ slowMotionLabel: string; /** * TODO **/ slowMotionTooltip: string; /** * TODO **/ isSlowMotionDisabled: boolean; /** * TODO **/ isSlowMotionHidden: boolean; /** * TODO **/ skipPreviousIcon: string; /** * TODO **/ skipPreviousLabel: string; /** * TODO **/ skipPreviousTooltip: string; /** * TODO **/ isSkipPreviousDisabled: boolean; /** * TODO **/ isSkipPreviousHidden: boolean; /** * TODO **/ skipNextIcon: string; /** * TODO **/ skipNextLabel: string; /** * TODO **/ skipNextTooltip: string; /** * TODO **/ isSkipNextDisabled: boolean; /** * TODO **/ isSkipNextHidden: boolean; /** * TODO **/ skipBackIcon: string; /** * TODO **/ skipBackLabel: string; /** * TODO **/ skipBackTooltip: string; /** * TODO **/ isSkipBackDisabled: boolean; /** * TODO **/ isSkipBackHidden: boolean; /** * TODO **/ skipAheadIcon: string; /** * TODO **/ skipAheadLabel: string; /** * TODO **/ skipAheadTooltip: string; /** * TODO **/ isSkipAheadDisabled: boolean; /** * TODO **/ isSkipAheadHidden: boolean; /** * TODO **/ elapsedTime: number; /** * TODO **/ elapsedTimeText: string; /** * TODO **/ elapsedTimeLabel: string; /** * TODO **/ elapsedTimeTooltip: string; /** * TODO **/ isElapsedTimeDisabled: boolean; /** * TODO **/ isElapsedTimeHidden: boolean; /** * TODO **/ remainingTime: number; /** * TODO **/ remainingTimeText: string; /** * TODO **/ remainingTimeLabel: string; /** * TODO **/ remainingTimeTooltip: string; /** * TODO **/ isRemainingTimeDisabled: boolean; /** * TODO **/ isRemainingTimeHidden: boolean; /** * TODO **/ totalTime: number; /** * TODO **/ totalTimeText: string; /** * TODO **/ totalTimeLabel: string; /** * TODO **/ totalTimeTooltip: string; /** * TODO **/ isTotalTimeDisabled: boolean; /** * TODO **/ isTotalTimeHidden: boolean; /** * TODO **/ timelineLabel: string; /** * TODO **/ timelineTooltip: string; /** * TODO **/ isTimelineDisabled: boolean; /** * TODO **/ isTimelineHidden: boolean; /** * TODO **/ goLiveText: string; /** * TODO **/ goLiveLabel: string; /** * TODO **/ goLiveTooltip: string; /** * TODO **/ isGoLiveDisabled: boolean; /** * TODO **/ isGoLiveHidden: boolean; /** * TODO **/ captionsIcon: string; /** * TODO **/ captionsLabel: string; /** * TODO **/ captionsTooltip: string; /** * TODO **/ isCaptionsDisabled: boolean; /** * TODO **/ audioIcon: string; /** * TODO **/ audioLabel: string; /** * TODO **/ audioTooltip: string; /** * TODO **/ isAudioDisabled: boolean; /** * TODO **/ isAudioHidden: boolean; /** * TODO **/ volume: number; /** * TODO **/ volumeMuteIcon: string; /** * TODO **/ volumeMuteLabel: string; /** * TODO **/ volumeMuteTooltip: string; /** * TODO **/ isVolumeMuteDisabled: boolean; /** * TODO **/ isVolumeMuteHidden: boolean; /** * TODO **/ volumeIcon: string; /** * TODO **/ volumeLabel: string; /** * TODO **/ volumeTooltip: string; /** * TODO **/ isVolumeDisabled: boolean; /** * TODO **/ isVolumeHidden: boolean; /** * TODO **/ muteIcon: string; /** * TODO **/ muteLabel: string; /** * TODO **/ muteTooltip: string; /** * TODO **/ isMuteDisabled: boolean; /** * TODO **/ isMuteHidden: boolean; /** * TODO **/ fullScreenIcon: string; /** * TODO **/ fullScreenLabel: string; /** * TODO **/ fullScreenTooltip: string; /** * TODO **/ isFullScreenDisabled: boolean; /** * TODO **/ isFullScreenHidden: boolean; /** * TODO **/ stopIcon: string; /** * TODO **/ stopLabel: string; /** * TODO **/ stopTooltip: string; /** * TODO **/ isStopDisabled: boolean; /** * TODO **/ isStopHidden: boolean; /** * TODO **/ infoIcon: string; /** * TODO **/ infoLabel: string; /** * TODO **/ infoTooltip: string; /** * TODO **/ isInfoDisabled: boolean; /** * TODO **/ isInfoHidden: boolean; /** * TODO **/ moreIcon: string; /** * TODO **/ moreLabel: string; /** * TODO **/ moreTooltip: string; /** * TODO **/ isMoreDisabled: boolean; /** * TODO **/ isMoreHidden: boolean; /** * TODO **/ zoomIcon: string; /** * TODO **/ zoomLabel: string; /** * TODO **/ zoomTooltip: string; /** * TODO **/ isZoomDisabled: boolean; /** * TODO **/ isZoomHidden: boolean; /** * TODO **/ signalStrength: number; /** * TODO **/ signalStrengthLabel: string; /** * TODO **/ signalStrengthTooltip: string; /** * TODO **/ isSignalStrengthDisabled: boolean; /** * TODO **/ isSignalStrengthHidden: boolean; /** * TODO **/ mediaQuality: MediaQuality; /** * TODO **/ mediaQualityLabel: string; /** * TODO **/ mediaQualityTooltip: string; /** * TODO **/ isMediaQualityDisabled: boolean; /** * TODO **/ isMediaQualityHidden: boolean; /** * TODO **/ visualMarkers: Array<any>; /** * TODO **/ thumbnailImageSrc: string; /** * TODO **/ isThumbnailVisible: boolean; /** * TODO **/ mediaMetadata: Object; uninitialize(): void; playPause(e?: any): void; playResume(): void; pause(): void; replay(): void; rewind(): void; fastForward(): void; slowMotion(): void; skipPrevious(): void; skipNext(): void; skipBack(): void; skipAhead(): void; startScrub(time: number): void; updateScrub(time: number): void; completeScrub(time: number): void; goLive(): void; setVolume(volume: number): void; toggleMutted(): void; toggleFullScreen(): void; stop(): void; info(): void; more(): void; toggleZoom(): void; captions(): void; audio(): void; onTimelineSliderStart(e: any): void; onTimelineSliderUpdate(e: any): void; onTimelineSliderComplete(e: any): void; onTimelineSliderSkipToMarker(e: any): void; onVolumeSliderUpdate(e: any): void; onVolumeMuteClick(e: any): void; onVolumeMuteFocus(e: any): void; onVolumeMuteSliderUpdate(e: any): void; onVolumeMuteSliderFocusIn(e: any): void; onVolumeMuteSliderFocusOut(e: any): void; onVolumeMuteSliderMSPointerOver(e: any): void; onVolumeMuteSliderMSPointerOut(e: any): void; onVolumeMuteSliderTransitionEnd(e: any): void; } /** * **/ class MediaPlayer { constructor(element: HTMLElement, options?: any); /** * Gets or sets the current advertising state of the player. **/ advertisingState: AdvertisingState; /** * Gets the audio tracks for the current media source. **/ audioTracks: Array<any>; /** * Gets or sets a value that indicates whether to automatically start buffering the current media source. **/ autobuffer: boolean; /** * Gets or sets a value that specifies whether interactive elements(e.g.the control panel) will be hidden automatically. **/ autohide: boolean; /** * Gets or sets the behavior of the autohide feature. **/ autohideBehavior: AutohideBehavior; /** * Gets or sets the amount of time (in seconds) before interactive elements(e.g.the control panel) will be hidden automatically. **/ autohideTime: number; /** * Gets or sets a value that specifies whether to start loading the current media source automatically. **/ autoload: boolean; /** * Gets or sets a value that specifies whether to automatically start playing the current media source. **/ autoplay: boolean; /** * Gets the buffered time ranges for the current media source. **/ buffered: Array<any>; //TODO: (type: TimeRanges, read - only) /** * Gets the caption and subtitle tracks for the current media source. **/ captionTracks: Array<any>; /** * Gets or sets a value that specifies whether to display the native controls for the current media source. **/ controls: boolean; /** * Gets or sets the current audio track. **/ currentAudioTrack: any; //TODO: (type: AudioTrack, read / write) /** * Gets or sets the current caption / subtitle track. **/ currentCaptionTrack: any; //TODO: (type: TextTrack, read / write) /** * Gets the URL of the current media source. **/ currentSrc: string; /** * Gets or sets the current playback position (in seconds). **/ currentTime: number; /** * Gets the view model that will be restored following a temporary change to the current interactive view model(e.g.during an ad). **/ defaultInteractiveViewModel: InteractiveViewModel; /** * Gets or sets the playback rate to use when play is resumed. **/ defaultPlaybackRate: number; /** * Gets the duration (in seconds) of the current media source. **/ duration: number; /** * Gets the host element for the control. **/ element: HTMLElement; /** * Gets a value that specifies whether playback has ended. **/ ended: boolean; /** * Gets or sets the end time (in seconds) of the current media source.This is useful in live streaming scenarios. **/ endTime: number; /** * Gets the current error state of the player. **/ error: MediaError; /** * Gets or sets the height of the host element. **/ height: string; /** * Gets the earliest possible position (in seconds) that playback can begin. **/ initialTime: number; /** * Gets or sets the type of interactions that will cause interactive elements(e.g.the control panel) to be shown. **/ interactiveActivationMode: InteractionType; /** * Gets or sets the type of interactions that will cause interactive elements(e.g.the control panel) to be hidden. **/ interactiveDeactivationMode: InteractionType; /** * Gets or sets the view model that interactive elements are bound to(e.g.the control panel). **/ interactiveViewModel: InteractiveViewModel; /** * Gets a value that specifies whether interaction with the audio control is allowed based on the current state of the player. **/ isAudioAllowed: boolean; /** * Gets or sets a value that specifies whether the audio control is enabled. **/ isAudioEnabled: boolean; /** * Gets or sets a value that specifies whether the audio control is visible. **/ isAudioVisible: boolean; /** * Gets a value that specifies whether interaction with the captions control is allowed based on the current state of the player. **/ isCaptionsAllowed: boolean; /** * Gets or sets a value that specifies whether the captions control is enabled. **/ isCaptionsEnabled: boolean; //TODO: READ-ONLY /** * Gets or sets a value that specifies whether the captions control is visible. **/ isCaptionsVisible: boolean; /** * Gets a value that specifies whether the current playback position is "live". **/ isCurrentTimeLive: boolean; /** * Gets a value that specifies whether interaction with the elapsed time control is allowed based on the current state of the player. **/ isElapsedTimeAllowed: boolean; /** * Gets or sets a value that specifies whether the elapsed time control is enabled. **/ isElapsedTimeEnabled: boolean; /** * Gets or sets a value that specifies whether the elapsed time control is visible. **/ isElapsedTimeVisible: boolean; /** * Gets a value that specifies whether interaction with the fast forward control is allowed based on the current state of the player. **/ isFastForwardAllowed: boolean; /** * Gets or sets a value that specifies whether the fast forward control is enabled. **/ isFastForwardEnabled: boolean; /** * Gets or sets a value that specifies whether the fast forward control is visible. **/ isFastForwardVisible: boolean; /** * Gets or sets a value that specifies whether the player is in full screen mode. **/ isFullScreen: boolean; /** * Gets a value that specifies whether interaction with the full screen control is allowed based on the current state of the player. **/ isFullScreenAllowed: boolean; /** * Gets or sets a value that specifies whether the full screen control is enabled. **/ isFullScreenEnabled: boolean; /** * Gets or sets a value that specifies whether the full screen control is visible. **/ isFullScreenVisible: boolean; /** * Gets a value that specifies whether interaction with the go live control is allowed based on the current state of the player. **/ isGoLiveAllowed: boolean; /** * Gets or sets a value that specifies whether the go live control is enabled. **/ isGoLiveEnabled: boolean; /** * Gets or sets a value that specifies whether the go live control is visible. **/ isGoLiveVisible: boolean; /** * Gets or sets a value that specifies whether the player is currently in interactive mode(e.g.showing the control panel). **/ isInteractive: boolean; /** * Gets a value that specifies whether the current media source is a live stream. **/ isLive: boolean; /** * Gets a value that specifies whether interaction with the media quality control is allowed based on the current state of the player. **/ isMediaQualityAllowed: boolean; /** * Gets or sets a value that specifies whether the media quality control is enabled. **/ isMediaQualityEnabled: boolean; /** * Gets or sets a value that specifies whether the media quality control is visible. **/ isMediaQualityVisible: boolean; /** * Gets a value that specifies whether interaction with the mute control is allowed based on the current state of the player. **/ isMuteAllowed: boolean; /** * Gets or sets a value that specifies whether the mute control is enabled. **/ isMuteEnabled: boolean; /** * Gets or sets a value that specifies whether the mute control is visible. **/ isMuteVisible: boolean; /** * Gets a value that specifies whether interaction with the pause control is allowed based on the current state of the player. **/ isPauseAllowed: boolean; /** * Gets or sets a value that specifies whether the pause control is enabled. **/ isPauseEnabled: boolean; /** * Gets or sets a value that specifies whether the pause control is visible. **/ isPauseVisible: boolean; /** * Gets a value that specifies whether interaction with the play / pause control is allowed based on the current state of the player. **/ isPlayPauseAllowed: boolean; /** * Gets or sets a value that specifies whether the play / pause control is enabled. **/ isPlayPauseEnabled: boolean; /** * Gets or sets a value that specifies whether the play / pause control is visible. **/ isPlayPauseVisible: boolean; /** * Gets a value that specifies whether interaction with the play / resume control is allowed based on the current state of the player. **/ isPlayResumeAllowed: boolean; /** * Gets or sets a value that specifies whether the play / resume control is enabled. **/ isPlayResumeEnabled: boolean; /** * Gets or sets a value that specifies whether the play / resume control is visible. **/ isPlayResumeVisible: boolean; /** * Gets a value that specifies whether interaction with the remaining time control is allowed based on the current state of the player. **/ isRemainingTimeAllowed: boolean; /** * Gets or sets a value that specifies whether the remaining time control is enabled. **/ isRemainingTimeEnabled: boolean; /** * Gets or sets a value that specifies whether the remaining time control is visible. **/ isRemainingTimeVisible: boolean; /** * Gets a value that specifies whether interaction with the replay control is allowed based on the current state of the player. **/ isReplayAllowed: boolean; /** * Gets or sets a value that specifies whether the replay control is enabled. **/ isReplayEnabled: boolean; /** * Gets or sets a value that specifies whether the replay control is visible. **/ isReplayVisible: boolean; /** * Gets a value that specifies whether interaction with the rewind control is allowed based on the current state of the player. **/ isRewindAllowed: boolean; /** * Gets or sets a value that specifies whether the rewind control is enabled. **/ isRewindEnabled: boolean; /** * Gets or sets a value that specifies whether the rewind control is visible. **/ isRewindVisible: boolean; /** * Gets a value that specifies whether interaction with the signal strength control is allowed based on the current state of the player. **/ isSignalStrengthAllowed: boolean; /** * Gets or sets a value that specifies whether the signal strength control is enabled. **/ isSignalStrengthEnabled: boolean; /** * Gets or sets a value that specifies whether the signal strength control is visible. **/ isSignalStrengthVisible: boolean; /** * Gets a value that specifies whether interaction with the skip ahead control is allowed based on the current state of the player. **/ isSkipAheadAllowed: boolean; /** * Gets or sets a value that specifies whether the skip ahead control is enabled. **/ isSkipAheadEnabled: boolean; /** * Gets or sets a value that specifies whether the skip ahead control is visible. **/ isSkipAheadVisible: boolean; /** * Gets a value that specifies whether interaction with the skip back control is allowed based on the current state of the player. **/ isSkipBackAllowed: boolean; /** * Gets or sets a value that specifies whether the skip back control is enabled. **/ isSkipBackEnabled: boolean; /** * Gets or sets a value that specifies whether the skip back control is visible. **/ isSkipBackVisible: boolean; /** * Gets a value that specifies whether interaction with the skip next control is allowed based on the current state of the player. **/ isSkipNextAllowed: boolean; /** * Gets or sets a value that specifies whether the skip next control is enabled. **/ isSkipNextEnabled: boolean; /** * Gets or sets a value that specifies whether the skip next control is visible. **/ isSkipNextVisible: boolean; /** * Gets a value that specifies whether interaction with the skip previous control is allowed based on the current state of the player. **/ isSkipPreviousAllowed: boolean; /** * Gets or sets a value that specifies whether the skip previous control is enabled. **/ isSkipPreviousEnabled: boolean; /** * Gets or sets a value that specifies whether the skip previous control is visible. **/ isSkipPreviousVisible: boolean; /** * Gets or sets a value that specifies whether the player is playing in slow motion. **/ isSlowMotion: boolean; /** * Gets a value that specifies whether interaction with the slow motion control is allowed based on the current state of the player. **/ isSlowMotionAllowed: boolean; /** * Gets or sets a value that specifies whether the slow motion control is enabled. **/ isSlowMotionEnabled: boolean; /** * Gets or sets a value that specifies whether the slow motion control is visible. **/ isSlowMotionVisible: boolean; /** * Gets or sets a value that specifies whether the start time is offset. **/ isStartTimeOffset: boolean; /** * Gets a value that specifies whether interaction with the timeline control is allowed based on the current state of the player. **/ isTimelineAllowed: boolean; /** * Gets or sets a value that specifies whether the timeline control is enabled. **/ isTimelineEnabled: boolean; /** * Gets or sets a value that specifies whether the timeline control is visible. **/ isTimelineVisible: boolean; /** * Gets a value that specifies whether interaction with the volume control is allowed based on the current state of the player. **/ isVolumeAllowed: boolean; /** * Gets or sets a value that specifies whether the volume control is enabled. **/ isVolumeEnabled: boolean; /** * Gets a value that specifies whether interaction with the volume / mute control is allowed based on the current state of the player. **/ isVolumeMuteAllowed: boolean; /** * Gets or sets a value that specifies whether the volume / mute control is enabled. **/ isVolumeMuteEnabled: boolean; /** * Gets or sets a value that specifies whether the volume / mute control is visible. **/ isVolumeMuteVisible: boolean; /** * Gets or sets a value that specifies whether the volume control is visible. **/ isVolumeVisible: boolean; /** * Gets or sets the live position (in seconds). **/ liveTime: number; /** * Gets or sets the live buffer time (in seconds) for the current playback position to be considered "live". **/ liveTimeBuffer: number; /** * Gets or sets a value that specifies whether playback should be restarted after it ends. **/ loop: boolean; /** * Gets the media element associated with the player. **/ mediaElement: HTMLMediaElement; /** * Gets or sets the media extension manager to be used by the player and its plugins.A new instance will be created on first use if one is not already set. **/ mediaExtensionManager: Windows.Media.MediaExtensionManager; /** * Gets or sets the quality of the current media source. **/ mediaQuality: MediaQuality; /** * Gets or sets a value that specifies the purpose of the media, such as background audio or alerts. **/ msAudioCategory: string; /** * Gets or sets a value that specifies the output device ID that the audio will be sent to. **/ msAudioDeviceType: string; /** * Gets or sets a value that specifies whether the media is flipped horizontally. **/ msHorizontalMirror: boolean; /** * Gets a value that specifies whether the media can be rendered more efficiently. **/ msIsLayoutOptimalForPlayback: boolean; /** * Gets a value that specifies whether the system considers the media to be stereo 3D. **/ msIsStereo3D: boolean; /** * Gets or sets a value that specifies whether the DLNA PlayTo device is available. **/ msPlayToDisabled: boolean; /** * Gets or sets the primary DLNA PlayTo device. **/ msPlayToPrimary: boolean; /** * Gets the media source for use by the PlayToManager. **/ msPlayToSource: Object; /** * Gets or sets a value that specifies whether or not to enable low - latency playback. **/ msRealTime: boolean; /** * Gets or sets the frame - packing mode for stereo 3D video content. **/ msStereo3DPackingMode: string; /** * Gets or sets a value that specifies whether the system display is set to stereo display. **/ msStereo3DRenderMode: string; /** * Gets or sets a value that specifies whether the video frame is trimmed to fit the display. **/ msZoom: boolean; /** * Gets or sets a value that indicates whether the audio is muted. **/ muted: boolean; /** * Gets the current network state for the player. **/ networkState: NetworkState; /** * Gets a value that specifies whether playback is paused. **/ paused: boolean; /** * Gets or sets the playback rate for the current media source. **/ playbackRate: number; /** * Gets the played time ranges for the current media source. **/ played: Array<any>; //TODO: (type: TimeRanges, read - only) /** * Gets the playlist plugin. **/ playlistPlugin: Plugins.PlaylistPlugin; /** * Gets or sets the current state of the player. **/ playerState: PlayerState; /* * Gets the plugins associated with the player. **/ plugins: Array<any>; //TODO: (type: ?, read - only) /* * Gets or sets the URL of an image to display while the current media source is loading. **/ poster: string; /** ** Gets or sets a hint to how much buffering is advisable for the current media source. **/ preload: string; /** * Gets the current readiness state of the player. **/ readyState: ReadyState; /** * Gets or sets the amount of time (in seconds) to offset the current playback position during replay. **/ replayOffset: number; /** * Gets a value that specifies whether the player is currently moving to a new playback position due to a scrub operation. **/ scrubbing: boolean; //TODO: (type: Boolean, read - only) /** * Gets the seekable time ranges of the current media source. **/ seekable: any; //TODO: (type: TimeRanges, read - only) /** * Gets a value that specifies whether the player is currently moving to a new playback position due to a seek operation. **/ seeking: boolean; //TODO: (type: Boolean, read - only) /** * Gets or sets a value that specifies whether the current video frame should be updated during a scrub operation. **/ seekWhileScrubbing: boolean; /** * Gets or sets the signal strength of the current media source.This is useful in adaptive streaming scenarios. **/ signalStrength: number; /** * Gets or sets the amount of time (in seconds) that the skip ahead control will seek forward. **/ skipAheadInterval: number; /** * Gets or sets the amount of time (in seconds) that the skip back control will seek backward. **/ skipBackInterval: number; /** * Gets or sets the playback rate to use when in slow motion. **/ slowMotionPlaybackRate: number; /** * Gets or sets the media sources to be considered. **/ sources: Array<any>; //TODO: (type: Array, read / write) /** * Gets or sets the URL of the current media source to be considered. **/ src: string; /** * Gets or sets the start time (in seconds) of the current media source.This is useful in live streaming scenarios. **/ startTime: number; /** * Gets or sets the position (in seconds) where playback should start.This is useful for resuming a video where the user left off in a previous session. **/ startupTime: number; /** * Gets or sets whether a test for the media feature pack should be performed prior to allowing content to be laoded.This is useful to enable if Windows 8 N / KN users will be using this app. **/ testForMediaPack: boolean; /** * Gets the text tracks for the current media source. **/ textTracks: any; // TODO: (type: TextTrackList, read - only) /** * Gets or sets the tracks for the player. **/ tracks: Array<any>; // TODO: (type: Array, read / write) /** * Gets the intrinsic height of the current video (in pixels). **/ videoHeight: number; /** * Gets the intrinsic width of the current video (in pixels). **/ videoWidth: number; /** * Gets or sets the volume level(from 0 to 1) for the audio portions of media playback. **/ volume: number; /** * Gets or sets the width of the host element. **/ width: string; /* Methods */ /** * Adds the specified CSS class to the host element. * @param name The name of the class to add. Multiple classes can be added using space-delimited names. **/ addClass(name: string): void; /** * Adds an event listener for the MediaPlayer events. * //TODO * @param type The type (name) of the event. You can use any of the following: "". * @param listener The listener to invoke when the event is raised. * @param capture true to initiate capture, otherwise false. **/ addEventListener(type: string, listener: Function, capture?: boolean): void; /** * Create a new TextTrack object to add to an HTML5 video. * @param kind String The type of text track * @param label String A user readable title for a text track * @param language String The BCP47 language tag of the track. For example "en" for English or "fr" for French **/ addTextTrack(kind: string, label?: string, language?: string): void; /** * Raises the audioinvoked event used to indicate that an audio selection dialog should be presented to the user (usually in the form of a flyout). **/ audio(): void; /** * Returns a value that specifies whether the player can play a given media type. * @param type The type of media to be played. * @returns One of the following values: "probably", "maybe", or an empty string if the media cannot be rendered. **/ canPlayType(type: string): string; /** * Raises the captionsinvoked event used to indicate that closed options should be toggled on/off or that a caption selection dialog should be presented to the user (usually in the form of a flyout). **/ captions(): void; /** * Decreases the current playback rate by a factor of two.After the rate reaches 1(normal speed), it will flip to - 1, and then begins to rewind. **/ decreasePlaybackRate(): void; /** * Shuts down and releases all resources. **/ dispose(): void; /** * Gives focus to the host element. **/ focus(): void; /** * Increases the current playback rate by a factor of two.After the rate reaches - 1, it flips to 1(normal speed), and then begins to fast forward. **/ increasePlaybackRate(): void; /** * Raises the infoinvoked event used to indicate that more information about the current media should be displayed to the user. **/ info(): void; /** * Reloads the current media source. **/ load(): void; /** * Raises the moreinvoked event typically used to indicate that more options that were unable to fit in the control panel should be presented to the user (usually in the form of a flyout). **/ more(): void; /** * Clears all effects from the media pipeline. **/ msClearEffects(): void; /** * Steps the video forward or backward by one frame. * @param forward If true, the video is stepped forward, otherwise the video is stepped backward. **/ msFrameStep(forward: boolean): void; /** * Inserts the specified audio effect into the media pipeline. * @param activatableClassId The audio effects class. * @param effectRequired * @param config **/ msInsertAudioEffect(activatableClassId: string, effectRequired: boolean, config: Object): void; /** * Inserts the specified video effect into the media pipeline. * @param activatableClassId The video effects class. * @param effectRequired * @param config **/ msInsertVideoEffect(activatableClassId: string, effectRequired: boolean, config: Object): void /** * Sets the MSMediaKeys to be used for decrypting media data. * @param mediaKeys The media keys to use for decrypting media data. **/ msSetMediaKeys(mediaKeys: MSMediaKeys): void; /** * Sets the media protection manager for a given media pipeline. * @param mediaProtectionManager **/ msSetMediaProtectionManager(mediaProtectionManager: Windows.Media.Protection.MediaProtectionManager): void; /** * Sets the dimensions of a sub - rectangle within a video. * @param left The left position of the rectangle. * @param top The top position of the rectangle. * @param right The right position of the rectangle. * @param bottom The bottom position of the rectangle. **/ msSetVideoRectangle(left: number, top: number, right: number, bottom: number): void; /** * Pauses playback of the current media source. **/ pause(): void; /** * Loads and starts playback of the current media source. **/ play(): void; /** * Resets the playback rate and resumes playing the current media source. **/ playResume(): void; /** * Removes the specified CSS class from the host element. * @param name The name of the class to remove. Multiple classes can be removed using space-delimited names. **/ removeClass(name: string): void; /** * Removes an event listener from the media player control. * @param type The type (name) of the event. You can use any of the following: "". //TODO * @param eventHandler The listener to remove. **/ removeEventListener(eventName: string, eventHandler: Function): void; /** * Supports instant replay by applying an offset to the current playback position. **/ replay(): void; /** * Reloads the current media source and resumes where playback was left off. **/ retry(): void; /** * Stops playback and raises the stopped event. **/ stop(): void; /** * Updates the player and its plugins with the specified media source(e.g.the current playlist item). * @param mediaSource A JSON object containing the set of options that represent a media source. **/ update(mediaSource: Object): void; } class DynamicTextTrack { stream: any; label: string; language: string; augmentPayload(payload: any, startTime: number, endTime: number): void; } namespace UI { class Button { element: HTMLElement; type: string; content: string; hoverContent: string; label: string; tooltip: string; disabled: boolean; hidden: boolean; flyout: Element; } class ControlPanel { element: HTMLElement; hidden: boolean; isPlayPauseHidden: boolean; isPlayResumeHidden: boolean; isPauseHidden: boolean; isReplayHidden: boolean; isRewindHidden: boolean; isFastForwardHidden: boolean; isSlowMotionHidden: boolean; isSkipPreviousHidden: boolean; isSkipNextHidden: boolean; isSkipBackHidden: boolean; isSkipAheadHidden: boolean; isElapsedTimeHidden: boolean; isRemainingTimeHidden: boolean; isTotalTimeHidden: boolean; isTimelineHidden: boolean; isGoLiveHidden: boolean; isCaptionsHidden: boolean; isAudioHidden: boolean; isVolumeMuteHidden: boolean; isVolumeHidden: boolean; isMuteHidden: boolean; isFullScreenHidden: boolean; isStopHidden: boolean; isInfoHidden: boolean; isMoreHidden: boolean; isZoomHidden: boolean; isSignalStrengthHidden: boolean; isMediaQualityHidden: boolean; flyoutContainerElement: HTMLElement; } class Indicator { element: HTMLElement; value: string; label: string; tooltip: string; disabled: boolean; hidden: boolean; } class Meter { element: HTMLElement; value: number; label: string; tooltip: string; disabled: boolean; hidden: boolean; } class Slider { element: HTMLElement; min: number; max: number; value: number; progress: number; step: number; altStep1: number; altStep2: number; altStep3: number; label: string; tooltip: string; vertical: boolean; disabled: boolean; hidden: boolean; markers: Array<any>; thumbnailImageSrc: string; isThumbnailVisible: boolean; } } } declare namespace PlayerFramework.Advertising { interface AdvertisementBase { source: any; } class PrerollAdvertisement implements AdvertisementBase { source: any; } class MidrollAdvertisement implements AdvertisementBase { source: any; time: number; timePercentage: number; } } declare namespace Microsoft.VideoAdvertising { class VastAdPayloadHandler { static adType: string; } class Extensions { static defaultUserAgent: string; } } declare namespace Microsoft.PlayerFramework.Js.Advertising { /** * Provides an ad source that requires a Url to be downloaded and turned into a stream before passing to the ad handler. **/ class RemoteAdSource { } }
the_stack
import * as coreHttp from "@azure/core-http"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { AzureDigitalTwinsAPI } from "../azureDigitalTwinsAPI"; import { DigitalTwinsGetByIdOptionalParams, DigitalTwinsGetByIdResponse, DigitalTwinsAddOptionalParams, DigitalTwinsAddResponse, DigitalTwinsDeleteOptionalParams, DigitalTwinsUpdateOptionalParams, DigitalTwinsUpdateResponse, DigitalTwinsGetRelationshipByIdOptionalParams, DigitalTwinsGetRelationshipByIdResponse, DigitalTwinsAddRelationshipOptionalParams, DigitalTwinsAddRelationshipResponse, DigitalTwinsDeleteRelationshipOptionalParams, DigitalTwinsUpdateRelationshipOptionalParams, DigitalTwinsUpdateRelationshipResponse, DigitalTwinsListRelationshipsOptionalParams, DigitalTwinsListRelationshipsResponse, DigitalTwinsListIncomingRelationshipsOptionalParams, DigitalTwinsListIncomingRelationshipsResponse, DigitalTwinsSendTelemetryOptionalParams, DigitalTwinsSendComponentTelemetryOptionalParams, DigitalTwinsGetComponentOptionalParams, DigitalTwinsGetComponentResponse, DigitalTwinsUpdateComponentOptionalParams, DigitalTwinsUpdateComponentResponse, DigitalTwinsListRelationshipsNextOptionalParams, DigitalTwinsListRelationshipsNextResponse, DigitalTwinsListIncomingRelationshipsNextOptionalParams, DigitalTwinsListIncomingRelationshipsNextResponse } from "../models"; /** * Class representing a DigitalTwins. */ export class DigitalTwins { private readonly client: AzureDigitalTwinsAPI; /** * Initialize a new instance of the class DigitalTwins class. * @param client Reference to the service client */ constructor(client: AzureDigitalTwinsAPI) { this.client = client; } /** * Retrieves a digital twin. * Status codes: * * 200 OK * * 400 Bad Request * * InvalidArgument - The digital twin id is invalid. * * 404 Not Found * * DigitalTwinNotFound - The digital twin was not found. * @param id The id of the digital twin. The id is unique within the service and case sensitive. * @param options The options parameters. */ getById( id: string, options?: DigitalTwinsGetByIdOptionalParams ): Promise<DigitalTwinsGetByIdResponse> { const operationOptions: coreHttp.RequestOptionsBase = coreHttp.operationOptionsToRequestOptionsBase( options || {} ); return this.client.sendOperationRequest( { id, options: operationOptions }, getByIdOperationSpec ) as Promise<DigitalTwinsGetByIdResponse>; } /** * Adds or replaces a digital twin. * Status codes: * * 200 OK * * 400 Bad Request * * InvalidArgument - The digital twin id or payload is invalid. * * ModelDecommissioned - The model for the digital twin is decommissioned. * * TwinLimitReached - The maximum number of digital twins allowed has been reached. * * ValidationFailed - The digital twin payload is not valid. * * 412 Precondition Failed * * PreconditionFailed - The precondition check (If-Match or If-None-Match) failed. * @param id The id of the digital twin. The id is unique within the service and case sensitive. * @param twin The digital twin instance being added. If provided, the $dtId property is ignored. * @param options The options parameters. */ add( id: string, twin: any, options?: DigitalTwinsAddOptionalParams ): Promise<DigitalTwinsAddResponse> { const operationOptions: coreHttp.RequestOptionsBase = coreHttp.operationOptionsToRequestOptionsBase( options || {} ); return this.client.sendOperationRequest( { id, twin, options: operationOptions }, addOperationSpec ) as Promise<DigitalTwinsAddResponse>; } /** * Deletes a digital twin. All relationships referencing the digital twin must already be deleted. * Status codes: * * 204 No Content * * 400 Bad Request * * InvalidArgument - The digital twin id is invalid. * * RelationshipsNotDeleted - The digital twin contains relationships. * * 404 Not Found * * DigitalTwinNotFound - The digital twin was not found. * * 412 Precondition Failed * * PreconditionFailed - The precondition check (If-Match or If-None-Match) failed. * @param id The id of the digital twin. The id is unique within the service and case sensitive. * @param options The options parameters. */ delete( id: string, options?: DigitalTwinsDeleteOptionalParams ): Promise<coreHttp.RestResponse> { const operationOptions: coreHttp.RequestOptionsBase = coreHttp.operationOptionsToRequestOptionsBase( options || {} ); return this.client.sendOperationRequest( { id, options: operationOptions }, deleteOperationSpec ) as Promise<coreHttp.RestResponse>; } /** * Updates a digital twin. * Status codes: * * 204 No Content * * 400 Bad Request * * InvalidArgument - The digital twin id or payload is invalid. * * JsonPatchInvalid - The JSON Patch provided is invalid. * * ValidationFailed - Applying the patch results in an invalid digital twin. * * 404 Not Found * * DigitalTwinNotFound - The digital twin was not found. * * 412 Precondition Failed * * PreconditionFailed - The precondition check (If-Match or If-None-Match) failed. * @param id The id of the digital twin. The id is unique within the service and case sensitive. * @param patchDocument An update specification described by JSON Patch. Updates to property values and * $model elements may happen in the same request. Operations are limited to add, replace and remove. * @param options The options parameters. */ update( id: string, patchDocument: any[], options?: DigitalTwinsUpdateOptionalParams ): Promise<DigitalTwinsUpdateResponse> { const operationOptions: coreHttp.RequestOptionsBase = coreHttp.operationOptionsToRequestOptionsBase( options || {} ); return this.client.sendOperationRequest( { id, patchDocument, options: operationOptions }, updateOperationSpec ) as Promise<DigitalTwinsUpdateResponse>; } /** * Retrieves a relationship between two digital twins. * Status codes: * * 200 OK * * 400 Bad Request * * InvalidArgument - The digital twin id or relationship id is invalid. * * 404 Not Found * * DigitalTwinNotFound - The digital twin was not found. * * RelationshipNotFound - The relationship was not found. * @param id The id of the digital twin. The id is unique within the service and case sensitive. * @param relationshipId The id of the relationship. The id is unique within the digital twin and case * sensitive. * @param options The options parameters. */ getRelationshipById( id: string, relationshipId: string, options?: DigitalTwinsGetRelationshipByIdOptionalParams ): Promise<DigitalTwinsGetRelationshipByIdResponse> { const operationOptions: coreHttp.RequestOptionsBase = coreHttp.operationOptionsToRequestOptionsBase( options || {} ); return this.client.sendOperationRequest( { id, relationshipId, options: operationOptions }, getRelationshipByIdOperationSpec ) as Promise<DigitalTwinsGetRelationshipByIdResponse>; } /** * Adds a relationship between two digital twins. * Status codes: * * 200 OK * * 400 Bad Request * * InvalidArgument - The digital twin id, relationship id, or payload is invalid. * * InvalidRelationship - The relationship is invalid. * * OperationNotAllowed - The relationship cannot connect to the same digital twin. * * ValidationFailed - The relationship content is invalid. * * 404 Not Found * * DigitalTwinNotFound - The digital twin was not found. * * TargetTwinNotFound - The digital twin target of the relationship was not found. * * 412 Precondition Failed * * PreconditionFailed - The precondition check (If-Match or If-None-Match) failed. * @param id The id of the digital twin. The id is unique within the service and case sensitive. * @param relationshipId The id of the relationship. The id is unique within the digital twin and case * sensitive. * @param relationship The data for the relationship. * @param options The options parameters. */ addRelationship( id: string, relationshipId: string, relationship: any, options?: DigitalTwinsAddRelationshipOptionalParams ): Promise<DigitalTwinsAddRelationshipResponse> { const operationOptions: coreHttp.RequestOptionsBase = coreHttp.operationOptionsToRequestOptionsBase( options || {} ); return this.client.sendOperationRequest( { id, relationshipId, relationship, options: operationOptions }, addRelationshipOperationSpec ) as Promise<DigitalTwinsAddRelationshipResponse>; } /** * Deletes a relationship between two digital twins. * Status codes: * * 204 No Content * * 400 Bad Request * * InvalidArgument - The digital twin id or relationship id is invalid. * * 404 Not Found * * DigitalTwinNotFound - The digital twin was not found. * * RelationshipNotFound - The relationship was not found. * * 412 Precondition Failed * * PreconditionFailed - The precondition check (If-Match or If-None-Match) failed. * @param id The id of the digital twin. The id is unique within the service and case sensitive. * @param relationshipId The id of the relationship. The id is unique within the digital twin and case * sensitive. * @param options The options parameters. */ deleteRelationship( id: string, relationshipId: string, options?: DigitalTwinsDeleteRelationshipOptionalParams ): Promise<coreHttp.RestResponse> { const operationOptions: coreHttp.RequestOptionsBase = coreHttp.operationOptionsToRequestOptionsBase( options || {} ); return this.client.sendOperationRequest( { id, relationshipId, options: operationOptions }, deleteRelationshipOperationSpec ) as Promise<coreHttp.RestResponse>; } /** * Updates the properties on a relationship between two digital twins. * Status codes: * * 204 No Content * * 400 Bad Request * * InvalidArgument - The digital twin id or relationship id is invalid. * * InvalidRelationship - The relationship is invalid. * * JsonPatchInvalid - The JSON Patch provided is invalid. * * ValidationFailed - The relationship content is invalid. * * 404 Not Found * * DigitalTwinNotFound - The digital twin was not found. * * RelationshipNotFound - The relationship was not found. * * 409 Conflict * * RelationshipAlreadyExists - The relationship already exists. * * 412 Precondition Failed * * PreconditionFailed - The precondition check (If-Match or If-None-Match) failed. * @param id The id of the digital twin. The id is unique within the service and case sensitive. * @param relationshipId The id of the relationship. The id is unique within the digital twin and case * sensitive. * @param patchDocument JSON Patch description of the update to the relationship properties. * @param options The options parameters. */ updateRelationship( id: string, relationshipId: string, patchDocument: any[], options?: DigitalTwinsUpdateRelationshipOptionalParams ): Promise<DigitalTwinsUpdateRelationshipResponse> { const operationOptions: coreHttp.RequestOptionsBase = coreHttp.operationOptionsToRequestOptionsBase( options || {} ); return this.client.sendOperationRequest( { id, relationshipId, patchDocument, options: operationOptions }, updateRelationshipOperationSpec ) as Promise<DigitalTwinsUpdateRelationshipResponse>; } /** * Retrieves the relationships from a digital twin. * Status codes: * * 200 OK * * 400 Bad Request * * InvalidArgument - The digital twin id is invalid. * * 404 Not Found * * DigitalTwinNotFound - The digital twin was not found. * @param id The id of the digital twin. The id is unique within the service and case sensitive. * @param options The options parameters. */ listRelationships( id: string, options?: DigitalTwinsListRelationshipsOptionalParams ): Promise<DigitalTwinsListRelationshipsResponse> { const operationOptions: coreHttp.RequestOptionsBase = coreHttp.operationOptionsToRequestOptionsBase( options || {} ); return this.client.sendOperationRequest( { id, options: operationOptions }, listRelationshipsOperationSpec ) as Promise<DigitalTwinsListRelationshipsResponse>; } /** * Retrieves all incoming relationship for a digital twin. * Status codes: * * 200 OK * * 400 Bad Request * * InvalidArgument - The digital twin id is invalid. * * 404 Not Found * * DigitalTwinNotFound - The digital twin was not found. * @param id The id of the digital twin. The id is unique within the service and case sensitive. * @param options The options parameters. */ listIncomingRelationships( id: string, options?: DigitalTwinsListIncomingRelationshipsOptionalParams ): Promise<DigitalTwinsListIncomingRelationshipsResponse> { const operationOptions: coreHttp.RequestOptionsBase = coreHttp.operationOptionsToRequestOptionsBase( options || {} ); return this.client.sendOperationRequest( { id, options: operationOptions }, listIncomingRelationshipsOperationSpec ) as Promise<DigitalTwinsListIncomingRelationshipsResponse>; } /** * Sends telemetry on behalf of a digital twin. * Status codes: * * 204 No Content * * 400 Bad Request * * InvalidArgument - The digital twin id or message id is invalid. * * ValidationFailed - The telemetry content is invalid. * * 404 Not Found * * DigitalTwinNotFound - The digital twin was not found. * @param id The id of the digital twin. The id is unique within the service and case sensitive. * @param messageId A unique message identifier (in the scope of the digital twin id) that is commonly * used for de-duplicating messages. * @param telemetry The telemetry measurements to send from the digital twin. * @param options The options parameters. */ sendTelemetry( id: string, messageId: string, telemetry: any, options?: DigitalTwinsSendTelemetryOptionalParams ): Promise<coreHttp.RestResponse> { const operationOptions: coreHttp.RequestOptionsBase = coreHttp.operationOptionsToRequestOptionsBase( options || {} ); return this.client.sendOperationRequest( { id, messageId, telemetry, options: operationOptions }, sendTelemetryOperationSpec ) as Promise<coreHttp.RestResponse>; } /** * Sends telemetry on behalf of a component in a digital twin. * Status codes: * * 204 No Content * * 400 Bad Request * * InvalidArgument - The digital twin id, message id, or component path is invalid. * * ValidationFailed - The telemetry content is invalid. * * 404 Not Found * * DigitalTwinNotFound - The digital twin was not found. * * ComponentNotFound - The component path was not found. * @param id The id of the digital twin. The id is unique within the service and case sensitive. * @param componentPath The name of the DTDL component. * @param messageId A unique message identifier (in the scope of the digital twin id) that is commonly * used for de-duplicating messages. * @param telemetry The telemetry measurements to send from the digital twin's component. * @param options The options parameters. */ sendComponentTelemetry( id: string, componentPath: string, messageId: string, telemetry: any, options?: DigitalTwinsSendComponentTelemetryOptionalParams ): Promise<coreHttp.RestResponse> { const operationOptions: coreHttp.RequestOptionsBase = coreHttp.operationOptionsToRequestOptionsBase( options || {} ); return this.client.sendOperationRequest( { id, componentPath, messageId, telemetry, options: operationOptions }, sendComponentTelemetryOperationSpec ) as Promise<coreHttp.RestResponse>; } /** * Retrieves a component from a digital twin. * Status codes: * * 200 OK * * 400 Bad Request * * InvalidArgument - The digital twin id or component path is invalid. * * 404 Not Found * * DigitalTwinNotFound - The digital twin was not found. * * ComponentNotFound - The component path was not found. * @param id The id of the digital twin. The id is unique within the service and case sensitive. * @param componentPath The name of the DTDL component. * @param options The options parameters. */ getComponent( id: string, componentPath: string, options?: DigitalTwinsGetComponentOptionalParams ): Promise<DigitalTwinsGetComponentResponse> { const operationOptions: coreHttp.RequestOptionsBase = coreHttp.operationOptionsToRequestOptionsBase( options || {} ); return this.client.sendOperationRequest( { id, componentPath, options: operationOptions }, getComponentOperationSpec ) as Promise<DigitalTwinsGetComponentResponse>; } /** * Updates a component on a digital twin. * Status codes: * * 204 No Content * * 400 Bad Request * * InvalidArgument - The digital twin id, component path, or payload is invalid. * * JsonPatchInvalid - The JSON Patch provided is invalid. * * ValidationFailed - Applying the patch results in an invalid digital twin. * * 404 Not Found * * DigitalTwinNotFound - The digital twin was not found. * * 412 Precondition Failed * * PreconditionFailed - The precondition check (If-Match or If-None-Match) failed. * @param id The id of the digital twin. The id is unique within the service and case sensitive. * @param componentPath The name of the DTDL component. * @param patchDocument An update specification described by JSON Patch. Updates to property values and * $model elements may happen in the same request. Operations are limited to add, replace and remove. * @param options The options parameters. */ updateComponent( id: string, componentPath: string, patchDocument: any[], options?: DigitalTwinsUpdateComponentOptionalParams ): Promise<DigitalTwinsUpdateComponentResponse> { const operationOptions: coreHttp.RequestOptionsBase = coreHttp.operationOptionsToRequestOptionsBase( options || {} ); return this.client.sendOperationRequest( { id, componentPath, patchDocument, options: operationOptions }, updateComponentOperationSpec ) as Promise<DigitalTwinsUpdateComponentResponse>; } /** * ListRelationshipsNext * @param id The id of the digital twin. The id is unique within the service and case sensitive. * @param nextLink The nextLink from the previous successful call to the ListRelationships method. * @param options The options parameters. */ listRelationshipsNext( id: string, nextLink: string, options?: DigitalTwinsListRelationshipsNextOptionalParams ): Promise<DigitalTwinsListRelationshipsNextResponse> { const operationOptions: coreHttp.RequestOptionsBase = coreHttp.operationOptionsToRequestOptionsBase( options || {} ); return this.client.sendOperationRequest( { id, nextLink, options: operationOptions }, listRelationshipsNextOperationSpec ) as Promise<DigitalTwinsListRelationshipsNextResponse>; } /** * ListIncomingRelationshipsNext * @param id The id of the digital twin. The id is unique within the service and case sensitive. * @param nextLink The nextLink from the previous successful call to the ListIncomingRelationships * method. * @param options The options parameters. */ listIncomingRelationshipsNext( id: string, nextLink: string, options?: DigitalTwinsListIncomingRelationshipsNextOptionalParams ): Promise<DigitalTwinsListIncomingRelationshipsNextResponse> { const operationOptions: coreHttp.RequestOptionsBase = coreHttp.operationOptionsToRequestOptionsBase( options || {} ); return this.client.sendOperationRequest( { id, nextLink, options: operationOptions }, listIncomingRelationshipsNextOperationSpec ) as Promise<DigitalTwinsListIncomingRelationshipsNextResponse>; } } // Operation Specifications const serializer = new coreHttp.Serializer(Mappers, /* isXml */ false); const getByIdOperationSpec: coreHttp.OperationSpec = { path: "/digitaltwins/{id}", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "any" } }, headersMapper: Mappers.DigitalTwinsGetByIdHeaders }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.id], headerParameters: [Parameters.traceparent, Parameters.tracestate], serializer }; const addOperationSpec: coreHttp.OperationSpec = { path: "/digitaltwins/{id}", httpMethod: "PUT", responses: { 200: { bodyMapper: { type: { name: "any" } }, headersMapper: Mappers.DigitalTwinsAddHeaders }, 202: {}, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.twin, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.id], headerParameters: [ Parameters.contentType, Parameters.traceparent, Parameters.tracestate, Parameters.ifNoneMatch ], mediaType: "json", serializer }; const deleteOperationSpec: coreHttp.OperationSpec = { path: "/digitaltwins/{id}", httpMethod: "DELETE", responses: { 204: {}, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.id], headerParameters: [ Parameters.traceparent, Parameters.tracestate, Parameters.ifMatch ], serializer }; const updateOperationSpec: coreHttp.OperationSpec = { path: "/digitaltwins/{id}", httpMethod: "PATCH", responses: { 202: {}, 204: { headersMapper: Mappers.DigitalTwinsUpdateHeaders }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.patchDocument, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.id], headerParameters: [ Parameters.traceparent, Parameters.tracestate, Parameters.contentType1, Parameters.ifMatch ], mediaType: "json", serializer }; const getRelationshipByIdOperationSpec: coreHttp.OperationSpec = { path: "/digitaltwins/{id}/relationships/{relationshipId}", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "any" } }, headersMapper: Mappers.DigitalTwinsGetRelationshipByIdHeaders }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.id, Parameters.relationshipId], headerParameters: [Parameters.traceparent, Parameters.tracestate], serializer }; const addRelationshipOperationSpec: coreHttp.OperationSpec = { path: "/digitaltwins/{id}/relationships/{relationshipId}", httpMethod: "PUT", responses: { 200: { bodyMapper: { type: { name: "any" } }, headersMapper: Mappers.DigitalTwinsAddRelationshipHeaders }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.relationship, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.id, Parameters.relationshipId], headerParameters: [ Parameters.contentType, Parameters.traceparent, Parameters.tracestate, Parameters.ifNoneMatch ], mediaType: "json", serializer }; const deleteRelationshipOperationSpec: coreHttp.OperationSpec = { path: "/digitaltwins/{id}/relationships/{relationshipId}", httpMethod: "DELETE", responses: { 204: {}, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.id, Parameters.relationshipId], headerParameters: [ Parameters.traceparent, Parameters.tracestate, Parameters.ifMatch ], serializer }; const updateRelationshipOperationSpec: coreHttp.OperationSpec = { path: "/digitaltwins/{id}/relationships/{relationshipId}", httpMethod: "PATCH", responses: { 204: { headersMapper: Mappers.DigitalTwinsUpdateRelationshipHeaders }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.patchDocument, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.id, Parameters.relationshipId], headerParameters: [ Parameters.traceparent, Parameters.tracestate, Parameters.contentType1, Parameters.ifMatch ], mediaType: "json", serializer }; const listRelationshipsOperationSpec: coreHttp.OperationSpec = { path: "/digitaltwins/{id}/relationships", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.RelationshipCollection }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion, Parameters.relationshipName], urlParameters: [Parameters.$host, Parameters.id], headerParameters: [Parameters.traceparent, Parameters.tracestate], serializer }; const listIncomingRelationshipsOperationSpec: coreHttp.OperationSpec = { path: "/digitaltwins/{id}/incomingrelationships", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.IncomingRelationshipCollection }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.id], headerParameters: [Parameters.traceparent, Parameters.tracestate], serializer }; const sendTelemetryOperationSpec: coreHttp.OperationSpec = { path: "/digitaltwins/{id}/telemetry", httpMethod: "POST", responses: { 204: {}, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.telemetry, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.id], headerParameters: [ Parameters.contentType, Parameters.traceparent, Parameters.tracestate, Parameters.messageId, Parameters.telemetrySourceTime ], mediaType: "json", serializer }; const sendComponentTelemetryOperationSpec: coreHttp.OperationSpec = { path: "/digitaltwins/{id}/components/{componentPath}/telemetry", httpMethod: "POST", responses: { 204: {}, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.telemetry, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.id, Parameters.componentPath], headerParameters: [ Parameters.contentType, Parameters.traceparent, Parameters.tracestate, Parameters.messageId, Parameters.telemetrySourceTime ], mediaType: "json", serializer }; const getComponentOperationSpec: coreHttp.OperationSpec = { path: "/digitaltwins/{id}/components/{componentPath}", httpMethod: "GET", responses: { 200: { bodyMapper: { type: { name: "any" } }, headersMapper: Mappers.DigitalTwinsGetComponentHeaders }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.id, Parameters.componentPath], headerParameters: [Parameters.traceparent, Parameters.tracestate], serializer }; const updateComponentOperationSpec: coreHttp.OperationSpec = { path: "/digitaltwins/{id}/components/{componentPath}", httpMethod: "PATCH", responses: { 202: {}, 204: { headersMapper: Mappers.DigitalTwinsUpdateComponentHeaders }, default: { bodyMapper: Mappers.ErrorResponse } }, requestBody: Parameters.patchDocument, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.id, Parameters.componentPath], headerParameters: [ Parameters.traceparent, Parameters.tracestate, Parameters.contentType1, Parameters.ifMatch ], mediaType: "json", serializer }; const listRelationshipsNextOperationSpec: coreHttp.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.RelationshipCollection }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion, Parameters.relationshipName], urlParameters: [Parameters.$host, Parameters.id, Parameters.nextLink], headerParameters: [Parameters.traceparent, Parameters.tracestate], serializer }; const listIncomingRelationshipsNextOperationSpec: coreHttp.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.IncomingRelationshipCollection }, default: { bodyMapper: Mappers.ErrorResponse } }, queryParameters: [Parameters.apiVersion], urlParameters: [Parameters.$host, Parameters.id, Parameters.nextLink], headerParameters: [Parameters.traceparent, Parameters.tracestate], serializer };
the_stack
import { select, event } from 'd3-selection'; import { getBrowser } from './browser-util'; import { polyfillMouseEvents } from './customPolyfills'; import { setHighContrastListener } from './accessibilityUtils'; import { createLabel, createGroupLabel } from './altTextGenerator'; const keyCodes = { parent: 27, // ESCAPE child: 13, // ENTER select: 32, // SPACEBAR nextSibling: 39, // RIGHT ARROW previousSibling: 37, // LEFT ARROW nextCousin: 40, // DOWN ARROW previousCousin: 38, // UP ARROW nextCousinAlternate: 190, // PERIOD previousCousinAlternate: 188, // COMMA shift: 16, // SHIFT tab: 9 // TAB }; const browser = getBrowser(); const isIE11 = browser === 'IE'; // ua.includes('rv:11.0'); const isIEEdge = browser === 'Edge'; // ua.includes('Edge'); const rootSVGRole = 'application'; // !isIE11 ? 'region' : 'application'; const staticGeometryRole = 'img'; // 'menuitem'; // !(isIE11 || isIEEdge) ? 'img' : 'treeitem'; const interactiveGeometryRole = 'button'; // 'menuitem'; // !(isIE11 || isIEEdge) ? 'button' : 'treeitem'; const controllerPrefix = 'node-'; let fired = false; let shiftFired = false; if (isIE11) { polyfillMouseEvents(window); } export const setAccessibilityController = ({ node, chartTag, title, description, uniqueID, geomType, includeKeyNames, dataKeys, groupKeys, nested, groupName, groupAccessor, recursive, disableKeyNav }: { node: any; chartTag: string; title: string; description: string; uniqueID: string; geomType: string; includeKeyNames: boolean; dataKeys: any; groupKeys?: any; nested?: string; groupName?: string; groupAccessor?: string; recursive?: boolean; disableKeyNav?: boolean; }) => { const svg = select(node); const sameGroupCousinKey = groupAccessor && (chartTag === 'bar-chart' || chartTag === 'world-map') ? groupAccessor : ''; svg .attr('role', 'presentation') .attr('focusable', false) .attr('tabindex', -1) .style('overflow', 'hidden') .on( 'focus', !disableKeyNav ? () => { focusTarget( select(parent) .select('.VCL-controller') .node() ); // removeKeyboardHighlight(n[i].firstElementChild, true) } : null ); const parent = node.parentNode; let controller = select(parent).select('.VCL-controller'); const getRootAriaLabel = () => { const titleText = `${title}. `; const subtitle = description ? description + '. ' : ''; const descText = `${subtitle} Navigate into the chart area by pressing ENTER. ID: ${uniqueID}`; return titleText + descText; }; if (!controller.size()) { select(parent).style('position', 'relative'); controller = select(parent).insert('div', ':first-child'); controller .attr('class', 'VCL-controller') .style('position', 'absolute') .style('top', 0) .style('left', 0) .style('opacity', 0) .style('pointer-events', 'none'); } const bounds = node.getBoundingClientRect(); controller .style('width', `${bounds.width}px`) .style('height', `${bounds.height}px`) .attr('id', 'chart-area-' + uniqueID) .attr('data-sgck', sameGroupCousinKey || null) .attr('data-group', groupAccessor) .attr('aria-label', !disableKeyNav ? getRootAriaLabel() : null) .text(!disableKeyNav ? `Interactive ${chartTag}.` : '') .attr('role', !disableKeyNav ? rootSVGRole : 'presentation') .attr('tabindex', !disableKeyNav ? '0' : '-1') .on( 'keyup', !disableKeyNav ? () => { const e = event; const keyCode = e.keyCode || e.which; keyUpHandler(keyCode); } : null ) .on( 'focus', !disableKeyNav ? (_, i, n) => { select(n[i]) .selectAll('[tabindex]') .attr('tabindex', -1); drawKeyboardFocusClone(n[i], recursive); const bounds = node.getBoundingClientRect(); controller .style('width', `${bounds.width}px`) .style('height', `${bounds.height}px`) .attr('aria-label', getRootAriaLabel()); } : null ) .on( 'blur', !disableKeyNav ? (_, i, n) => { removeKeyboardHighlight( select(n[i].parentNode) .select('svg :first-child') .node(), true ); controller.attr('aria-label', `Interactive ${chartTag}. ID: ${uniqueID}`); } : null ) .on( 'keydown', !disableKeyNav ? () => { const e = event; const keyCode = event.keyCode || event.which; const eventType = validKeyCode(keyCode); if (eventType && !fired) { fired = true; e.stopPropagation(); const targetChild = enterChartArea(e); if (targetChild) { prepareControllerNodes({ rootNode: controller.node(), nodeID: targetChild.id, geomType, includeKeyNames, dataKeys, groupKeys, nested, groupName, groupAccessor, recursive, sameGroupCousinKey }); } } } : null ); const controllerChildID = controller.attr('aria-activedescendant'); if (controllerChildID && !disableKeyNav) { const child = document.getElementById(controllerChildID.substring(5)); if (child) { setActiveChild(child); } else { controller.attr('aria-activedescendant', null); } } else { controller.attr('aria-activedescendant', null); } const rootNode = controller.node(); if (disableKeyNav && rootNode.children && rootNode.children.length) { let childrenToRemove = rootNode.children.length; while (childrenToRemove) { rootNode.removeChild(rootNode.children[0]); childrenToRemove--; } } setHighContrastListener(node, uniqueID); // 'chart-area-' + chartTag + }; export const setElementFocusHandler = ({ node, geomType, includeKeyNames, dataKeys, groupKeys, nested, recursive, groupName, uniqueID, disableKeyNav }: { node: any; geomType: string; includeKeyNames: boolean; dataKeys: any; groupKeys?: any; nested?: string; recursive?: boolean; groupName?: string; uniqueID?: string; disableKeyNav?: boolean; }) => { select(node).on( 'focus', !disableKeyNav ? (_, i, n) => { const idOfTarget = n[i].id; if (idOfTarget) { const rootNode = document.getElementById('chart-area-' + uniqueID); const sameGroupCousinKey = select(rootNode).attr('data-sgck'); const groupAccessor = select(rootNode).attr('data-group'); prepareControllerNodes({ rootNode, nodeID: idOfTarget, geomType, includeKeyNames, dataKeys, groupKeys, nested, groupName, groupAccessor, recursive, sameGroupCousinKey, deleteControllers: false }); hideKeyboardHighlight(n[i]); } } : null ); }; export const setElementInteractionAccessState = (node: any, selected: boolean, selectable: boolean) => { const targetID = '#' + controllerPrefix + select(node).attr('id'); select(node) .attr('data-aria-pressed', selectable ? selected : null) .attr('data-role', selectable ? interactiveGeometryRole : staticGeometryRole); select(targetID) .attr('aria-pressed', selectable ? selected : null) .attr('role', selectable ? interactiveGeometryRole : staticGeometryRole); }; export const setElementAccessID = ({ node, uniqueID }: { node: any; uniqueID?: string }) => { select(node).attr('id', () => { if (!node.id) { return generateRandomStringID(uniqueID); } return node.id; }); }; export const checkAccessFocus = parentGNode => !!select(parentGNode) .select('.vcl-accessibility-focus-source') .size(); export const retainAccessFocus = ({ parentGNode, focusDidExist, recursive }: { parentGNode: any; focusDidExist?: boolean; recursive?: boolean; }) => { const primaryG = select(parentGNode); if (primaryG.select('.vcl-accessibility-focus-source').size()) { const target = primaryG.select('.vcl-accessibility-focus-source').node(); const previouslyHidden = primaryG.select('.vcl-accessibility-focus-indicator').classed('hidden'); drawKeyboardFocusClone(target, recursive); if (previouslyHidden) { hideKeyboardHighlight(target); } } else if (focusDidExist) { // if there is no focus source, we will put the user back at the start of the current group they are on let target; primaryG.selectAll('[tabindex]').each((_, i, n) => { if (!target && select(n[i]).attr('tabindex') !== null) { target = n[i]; } }); if (!target) { // if there is not a valid target in the group, we must find a valid target const root = findSVGRoot(parentGNode); // if there are no tabindex children target = select(root) .select('[tabindex]') .node() || root; } focusTarget(target); drawKeyboardFocusClone(target, recursive); } }; const validKeyCode = keyCode => { return ( keyCode === keyCodes.select || keyCode === keyCodes.child || keyCode === keyCodes.parent || keyCode === keyCodes.nextSibling || keyCode === keyCodes.previousSibling || keyCode === keyCodes.nextCousin || keyCode === keyCodes.previousCousin || keyCode === keyCodes.nextCousinAlternate || keyCode === keyCodes.previousCousinAlternate ); }; const prepareControllerNodes = ({ rootNode, nodeID, geomType, includeKeyNames, dataKeys, groupKeys, nested, groupName, groupAccessor, recursive, sameGroupCousinKey, deleteControllers }: { rootNode: any; nodeID: any; geomType: string; includeKeyNames: boolean; dataKeys: any; groupKeys?: any; nested?: string; groupName?: string; groupAccessor?: string; recursive?: boolean; sameGroupCousinKey?: string; deleteControllers?: boolean; }) => { if (isIE11 || isIEEdge) { fired = false; } let drawCount = 0; if (!deleteControllers) { // find tab back node, append const tabBackNode = findTabBackwardNode(nodeID, recursive); if (tabBackNode && tabBackNode.id) { drawCount++; createControllerNode({ rootNode, nodeID: tabBackNode.id, isTarget: false, geomType, includeKeyNames, dataKeys, groupKeys, nested, recursive, groupName, groupAccessor, direction: 'backward', sourceID: nodeID, sameGroupCousinKey }); } const controllerNodeAlreadyExists = document.getElementById(controllerPrefix + nodeID); if (!controllerNodeAlreadyExists) { drawCount++; createControllerNode({ rootNode, nodeID, isTarget: true, geomType, includeKeyNames, dataKeys, groupKeys, nested, recursive, groupName, groupAccessor, sameGroupCousinKey }); } else { drawCount++; rootNode.appendChild(controllerNodeAlreadyExists.parentNode); const sourceNode = document.getElementById(nodeID); // now we get bounds for height/width/top/left after populating content const bounds = sourceNode.getBoundingClientRect(); const parentBounds = rootNode.getBoundingClientRect(); select(controllerNodeAlreadyExists) .on('focus', () => {}) .style('position', 'absolute') .style('padding', 0) .style('margin', 0) .style('overflow', 'visible') .style('left', `${bounds.left - parentBounds.left}px`) .style('top', `${bounds.top - parentBounds.top}px`) .style('width', `${bounds.width}px`) .style('height', `${bounds.height}px`); } const tabForwardNode = findTabForwardNode(nodeID, recursive); if (tabForwardNode && tabForwardNode.id) { drawCount++; createControllerNode({ rootNode, nodeID: tabForwardNode.id, isTarget: false, geomType, includeKeyNames, dataKeys, groupKeys, nested, recursive, groupName, groupAccessor, direction: 'forward', sourceID: nodeID, sameGroupCousinKey }); } } // focus controller node and add keyboard focus indication to chart element simulateFocus(nodeID, recursive, deleteControllers); // remove old nodes let childrenToRemove = rootNode.children.length - drawCount; while (childrenToRemove) { rootNode.removeChild(rootNode.children[0]); childrenToRemove--; } }; const simulateFocus = (nodeID, recursive, directID?) => { const id = !directID ? controllerPrefix + nodeID : nodeID; const targetControllerElement = document.getElementById(id); const targetChartElement = document.getElementById(nodeID); simulateBlur(!directID ? targetControllerElement.parentNode.parentNode : targetControllerElement); focusTarget(targetControllerElement); if (!directID) { select(targetControllerElement).classed('VCL-controller-focused', true); focusAsMouseover(targetChartElement, recursive, false); setActiveChild(targetChartElement); } else { removeActiveChild(targetChartElement, true); } drawKeyboardFocusClone(targetChartElement, recursive); }; const simulateBlur = controllerRoot => { const controllerToBlur = select(controllerRoot).select('.VCL-controller-focused'); if (controllerToBlur.size()) { controllerToBlur.classed('VCL-controller-focused', false); const targetNode = document.getElementById(controllerToBlur.node().id.substring(5)); controllerBlurToMouseout(targetNode); } }; const createControllerNode = ({ rootNode, nodeID, isTarget, geomType, includeKeyNames, dataKeys, groupKeys, nested, recursive, groupName, groupAccessor, direction, sourceID, sameGroupCousinKey }: { rootNode: any; nodeID: any; isTarget: boolean; geomType: string; includeKeyNames: boolean; dataKeys: any; groupKeys?: any; nested?: string; recursive?: boolean; groupName?: string; groupAccessor?: string; direction?: string; sourceID?: string; sameGroupCousinKey?: string; }) => { const sourceNode = document.getElementById(nodeID); const isOffsetGroup = select(sourceNode).attr('data-offset-group'); const isGroup = sourceNode.nodeName === 'g' || isOffsetGroup; let nodeType = 'div'; let nodeRole = 'img'; let nodeCanBePressed = null; if (!isGroup) { nodeRole = select(sourceNode).attr('data-role'); nodeCanBePressed = select(sourceNode).attr('data-aria-pressed'); nodeType = nodeCanBePressed ? 'button' : 'div'; } // now we get bounds for height/width/top/left after populating content const bounds = sourceNode.getBoundingClientRect(); const parentBounds = rootNode.getBoundingClientRect(); select(rootNode) .append(!isIEEdge ? 'figure' : 'div') .attr('role', 'figure') .append(nodeType) .style('position', 'absolute') .style('padding', 0) .style('margin', 0) .style('overflow', 'visible') .attr('role', nodeRole) .attr('id', controllerPrefix + nodeID) .attr('tabindex', -1) .on('keydown', () => { const e = event; e.stopPropagation(); const result = getInteractionResult(nodeID, e, isGroup, recursive, sameGroupCousinKey); if (result) { if (result.clicked) { // we will "click" the element now const resultTarget = document.getElementById(result.id); hideKeyboardHighlight(resultTarget.parentNode); const evt = new MouseEvent('click', { bubbles: false, cancelable: true }); resultTarget.dispatchEvent(evt); // focus controller node and add keyboard focus indication to chart element simulateFocus(nodeID, recursive); } else if (result.focused) { // this will prepare the controller's nodes and then focus the result.id const idOfTarget = result.id || rootNode.id; prepareControllerNodes({ rootNode, nodeID: idOfTarget, geomType, includeKeyNames, dataKeys, groupKeys, nested, groupName, groupAccessor, recursive, sameGroupCousinKey, deleteControllers: idOfTarget === rootNode.id }); } } }) .on('keyup', () => { fired = false; }) .on( 'focus', !isTarget ? () => { let id = nodeID; if (direction) { const node = direction === 'backward' ? findTabBackwardNode(sourceID, recursive) : findTabForwardNode(sourceID, recursive); id = node ? node.id : ''; } if (id) { prepareControllerNodes({ rootNode, nodeID: id, geomType, includeKeyNames, dataKeys, groupKeys, nested, groupName, groupAccessor, recursive, sameGroupCousinKey }); } } : null ) .on('blur', () => { const node = document.getElementById(nodeID); controllerBlurToMouseout(node); }) .attr('aria-label', (_, i, n) => { let label = ''; const capitalizedGeomType = geomType[0].toUpperCase() + geomType.substring(1); const capitalizedGroupName = groupName ? groupName[0].toUpperCase() + groupName.substring(1) : ''; const targetNode = !recursive ? sourceNode : sourceNode.parentNode; const siblings = !recursive ? targetNode.parentNode.childNodes : findValidRecursiveSiblings(sourceNode); const index = Array.prototype.indexOf.call(siblings, sourceNode); const element = select(targetNode); const d = targetNode['__data__'] || element.data()[0]; if (isGroup) { label = createGroupLabel({ d, targetNode, index, groupAccessor, groupKeys, siblings, isOffsetGroup, includeKeyNames, capitalizedGroupName, capitalizedGeomType, geomType }); } else { label = createLabel({ d, i: index, n: siblings, capitalizedGeomType, capitalizedGroupName, includeKeyNames, dataKeys, groupKeys, nested, recursive }); } select(n[i]).text(label); if (nodeCanBePressed) { select(n[i]).attr('aria-pressed', nodeCanBePressed); } return label; }) .style('left', `${bounds.left - parentBounds.left}px`) .style('top', `${bounds.top - parentBounds.top}px`) .style('width', `${bounds.width}px`) .style('height', `${bounds.height}px`) .style('pointer-events', 'none'); }; const findFirstOffsetValidChild = node => { const i = Array.prototype.indexOf.call(node.parentNode.childNodes, node); return node.parentNode.nextSibling.childNodes[i] ? node.parentNode.nextSibling.childNodes[i].childNodes[0] : undefined; }; const findOffsetParent = (node, direction?) => { const parent = direction === 'next' ? 'target' : 'source'; const i = direction ? node.__data__[parent].index : Array.prototype.indexOf.call(node.parentNode.parentNode.childNodes, node.parentNode); return node.parentNode.parentNode.previousSibling.childNodes[i]; }; const generateRandomStringID = (lead: string) => { return ( lead + '-' + Math.round(Math.random() * 1000000) + '-' + Math.round(Math.random() * 1000000) + '-' + Math.round(Math.random() * 1000000) ); }; const findTabForwardNode = (elementID: string, recursive?: boolean, siblingsOnly?: boolean) => { const target = elementID === '' ? null : document.getElementById(elementID); if (!target || target.tagName === 'svg') { return null; } else if (!recursive && target.nextElementSibling) { if (select(target.nextElementSibling).attr('tabindex') !== null) { return target.nextElementSibling; } else { return findTabForwardNode(target.nextElementSibling.id, recursive); } } else if (recursive && findValidCousin(target, 'next', true)) { return findValidCousin(target, 'next', true); } else if (!siblingsOnly) { const parent = findValidParent(target, recursive); const parentSibling = !recursive ? parent.nextElementSibling : parent ? findValidCousin(parent, 'next', true) : null; if (parentSibling) { if (select(parentSibling).attr('tabindex') !== null) { return parentSibling; } else if (parentSibling.id) { return findTabForwardNode(parentSibling.id, recursive, true); } } } return null; }; const findTabBackwardNode = (elementID: string, recursive?: boolean) => { const target = elementID === '' ? null : document.getElementById(elementID); if (!target || target.tagName === 'svg') { return null; } else if (!recursive && target.previousElementSibling) { if (select(target.previousElementSibling).attr('tabindex') !== null) { return target.previousElementSibling; } else { return findTabBackwardNode(target.previousElementSibling.id, recursive); } } else if (recursive && findValidCousin(target, 'previous', true)) { return findValidCousin(target, 'previous', true); } else if (target.tagName === 'g') { return null; } return findValidParent(target, recursive); }; const setActiveChild = (node: any) => { const rootSVG = findSVGRoot(node); if (!(rootSVG === document.body) && rootSVGRole === 'application') { const targetRoot = rootSVG.parentNode.firstElementChild; targetRoot.setAttribute('aria-activedescendant', controllerPrefix + node.id); } }; const removeActiveChild = (node, isTheRoot?) => { const rootSVG = !isTheRoot ? findSVGRoot(node) : node; if (!(rootSVG === document.body) && rootSVGRole === 'application') { const targetRoot = !isTheRoot ? rootSVG.parentNode.firstElementChild : node; targetRoot.setAttribute('aria-activedescendant', null); } }; const focusTarget = target => { // set the target focus state if (isIE11) { // https://mkyong.com/javascript/focus-is-not-working-in-ie-solution/ // IE has lazy focusing, so it must be wrapped in a timeout setTimeout(function() { target.focus(); // target.dispatchEvent(new Event('focus')); // .focus() is not working in jsdom dispatch for testing instead }, 10); // HTMLElement.prototype.focus.apply(target); } /* else if (isIEEdge) { FocusableForeignObject(target); }*/ else { target.focus(); // target.dispatchEvent(new Event('focus')); // .focus() is not working in jsdom dispatch for testing instead } }; const controllerBlurToMouseout = target => { if (!target) { return; } // remove the target focus state removeActiveChild(target); blurAsMouseout(target); removeKeyboardHighlight(target); }; const findValidSibling = (currentTarget: any, direction: string) => { const sibling = direction + 'Sibling'; const loopSibling = (direction === 'next' ? 'first' : 'last') + 'ElementChild'; const loopSiblingElement = () => direction === 'next' ? currentTarget.parentNode.firstElementChild : findValidFinalSibling(currentTarget); const siblingElement = currentTarget[sibling] && select(currentTarget[sibling]).attr('tabindex') !== null ? currentTarget[sibling] : null; const target = !siblingElement ? loopSiblingElement() : currentTarget[sibling]; return target || target.parentNode[loopSibling]; }; const findValidFinalSibling = node => { if (select(node.parentNode.lastElementChild).attr('tabindex') !== null) { return node.parentNode.lastElementChild; } let target = null; let index = node.parentNode.childNodes.length - 2; while (!target && index >= 0) { const currentChild = node.parentNode.childNodes[index]; if (select(currentChild).attr('tabindex') !== null) { target = currentChild; } index--; } return target; }; const findValidParent = (currentTarget: any, recursive?: boolean, requireTabIndex?: boolean) => { if (!recursive) { if (requireTabIndex && select(currentTarget.parentNode).attr('tabindex') !== null) { return currentTarget.parentNode; } return findSVGRoot(currentTarget); } if ( currentTarget.parentNode && currentTarget.parentNode.parentNode && currentTarget.parentNode.parentNode.firstElementChild ) { return ( findValidChildTarget(currentTarget.parentNode.parentNode.firstElementChild, true) || findSVGRoot(currentTarget) ); } return findSVGRoot(currentTarget); }; const findSVGRoot = node => { if (node.ownerSVGElement) { return node.ownerSVGElement; } if (node.parentNode.nodeName === 'svg' || node.parentNode === document.body) { return node.parentNode; } else { return findSVGRoot(node.parentNode); } }; const enterChartArea = (_event: any) => { const currentTarget: any = _event.target; const keyCode = _event.keyCode || _event.which; if (keyCode === keyCodes.child || keyCode === keyCodes.select) { // we will allow ENTER or SPACEBAR to enter the chart area _event.preventDefault(); return select(currentTarget.parentNode) .select('svg') .select('[tabindex]') .node(); } }; const keyUpHandler = code => { fired = false; if (code === keyCodes.shift) { shiftFired = false; } }; const findFirstValidChild = (currentTarget: any, recursive?: boolean) => { // recursive by default until it finds something with a tab index? const target = !recursive ? currentTarget : findValidSiblingTarget(currentTarget); return target && target.firstElementChild ? findValidChildTarget(target.firstElementChild, true) : null; }; const findValidRecursiveSiblings = node => { const parentOfParent = node.parentNode.parentNode; const parents = parentOfParent.childNodes; const siblings = []; Array.prototype.forEach.call(parents, parent => { if (parent.tagName === 'g' && !parent.classList.contains('.vcl-accessibility-focus-highlight')) { siblings.push(parent.firstElementChild); } }); return siblings; }; const findValidCousin = (currentTarget: any, direction: string, returnEarly?: boolean) => { let parentSiblingChildren; let target; const currentParentIdx = getElementIndex(currentTarget.parentNode); let currentIdx = select(currentTarget).attr('data-index') ? +select(currentTarget).attr('data-index') : getElementIndex(currentTarget); const _parent = currentTarget.parentNode.parentNode; const parentsSiblings = []; // const parentsSiblings = _parent.querySelectorAll('g:not(.vcl-accessibility-focus-highlight)') Array.prototype.forEach.call(_parent.childNodes, child => { if (child.tagName === 'g' && !child.classList.contains('vcl-accessibility-focus-highlight')) { parentsSiblings.push(child); } }); const childrenCount = parentsSiblings.length; if (!childrenCount) { return null; } if (direction === 'previous') { // up if (returnEarly && currentParentIdx === 0) { return null; } parentSiblingChildren = currentParentIdx !== 0 ? parentsSiblings[currentParentIdx - 1].childNodes : parentsSiblings[childrenCount - 1].childNodes; } else if (direction === 'next') { // down if (returnEarly && currentParentIdx === childrenCount - 1) { return null; } parentSiblingChildren = currentParentIdx !== childrenCount - 1 ? parentsSiblings[currentParentIdx + 1].childNodes : parentsSiblings[0].childNodes; } // set target -- this does assume that currentIdx and data-index are interchangable/reconciled target = select(currentTarget).attr('data-index') ? Array.prototype.filter.call(parentSiblingChildren, el => currentIdx === +select(el).attr('data-index'))[0] : parentSiblingChildren[currentIdx]; // ensure that target is actually something, will check backwards across groups if group sizes don't match while (!target && currentIdx > -1) { target = select(currentTarget).attr('data-index') ? Array.prototype.filter.call(parentSiblingChildren, el => currentIdx === +select(el).attr('data-index'))[0] : parentSiblingChildren[currentIdx]; // if we don't find anything going back, then just assign the first cousin of parent's sibling if (currentIdx === 0 && !target && select(currentTarget).attr('data-index')) { target = parentSiblingChildren[currentIdx]; } currentIdx--; } return !(currentTarget === target) ? target : null; }; const findValidSameGroupCousin = (currentTarget: any, direction: string, sameGroupCousinKey: string) => { const currentData = select(currentTarget).data()[0]; const targetGroup = currentData[sameGroupCousinKey]; let target; const cousins = []; let targetIndex = -1; let found = 0; select(currentTarget.parentNode) .selectAll('*') .each((d, i, n) => { if (d && d[sameGroupCousinKey] === targetGroup) { cousins.push(n[i]); found++; } if (targetIndex < 0 && currentTarget === n[i]) { // same reference means we know our index targetIndex = found - 1; } }); if (found && targetIndex > -1) { // we have results and a starting point if (direction === 'previous') { // return either the previous or last cousin target = cousins[targetIndex - 1] || cousins[cousins.length - 1]; } else if (direction === 'next') { // return either the next or first cousin target = cousins[targetIndex + 1] || cousins[0]; } } return target; }; const getElementIndex = el => { let i = 0; const originalNodeName = el.nodeName; while (el.previousSibling) { if ( originalNodeName === el.previousSibling.nodeName && !select(el.previousSibling).classed('vcl-accessibility-focus-hover') ) { i++; } el = el.previousSibling; } return i; }; const getInteractionResult = ( nodeID: string, _event: any, isGroup: boolean, recursive?: boolean, sameGroupCousinKey?: string ) => { let target: any; let result = { clicked: false, focused: false, id: '' }; const currentTarget: any = document.getElementById(nodeID); const keyCode = _event.keyCode || _event.which; const direction = keyCode === keyCodes.nextSibling || keyCode === keyCodes.nextCousin || keyCode === keyCodes.nextCousinAlternate ? 'next' : keyCode === keyCodes.previousSibling || keyCode === keyCodes.previousCousin || keyCode === keyCodes.previousCousinAlternate ? 'previous' : keyCode === keyCodes.parent ? 'up' : keyCode === keyCodes.child ? 'down' : ''; if (direction || keyCode === keyCodes.select) { _event.preventDefault(); } if (keyCode === keyCodes.shift && !shiftFired) { shiftFired = true; } if (!fired) { fired = true; if (keyCode === keyCodes.select) { // a selection has happened result.clicked = true; result.id = nodeID; } else if ((keyCode === keyCodes.nextSibling || keyCode === keyCodes.previousSibling) && !recursive) { // we are moving among siblings target = findValidSibling(currentTarget, direction); } else if ( (!recursive && (keyCode === keyCodes.nextCousin || keyCode === keyCodes.nextCousinAlternate || keyCode === keyCodes.previousCousin || keyCode === keyCodes.previousCousinAlternate)) || ((keyCode === keyCodes.nextSibling || keyCode === keyCodes.previousSibling) && recursive) ) { // we are moving among cousins (which are siblings if the chart is recursive) if (sameGroupCousinKey && !isGroup) { // the cousin is in the same tree and must be found among siblings target = findValidSameGroupCousin(currentTarget, direction, sameGroupCousinKey); } else if (!isGroup) { // the dom is structured in a hierarchy, so we navigate accordingly const isOffset = select(currentTarget).attr('data-offset-element'); target = !isOffset ? findValidCousin(currentTarget, direction) : findOffsetParent(currentTarget, direction); } } else if ( direction === 'down' || (recursive && (keyCode === keyCodes.nextCousin || keyCode === keyCodes.nextCousinAlternate)) ) { // we are moving down if (isGroup || recursive) { const isOffset = select(currentTarget).attr('data-offset-group'); target = !isOffset ? findFirstValidChild(currentTarget, recursive) : findFirstOffsetValidChild(currentTarget); } } else if ( direction === 'up' || (recursive && (keyCode === keyCodes.previousCousin || keyCode === keyCodes.previousCousinAlternate)) ) { // we are moving up if (isGroup) { target = findSVGRoot(currentTarget); } else { const isOffset = select(currentTarget).attr('data-offset-element'); target = !isOffset ? findValidParent(currentTarget, recursive, true) : findOffsetParent(currentTarget); } } } if (target && select(target).attr('tabindex')) { result.focused = true; result.id = target.id; } return result; }; const removeKeyboardHighlight = (parent: any, rootOnly?: boolean) => { const className = !rootOnly ? 'vcl-accessibility-focus' : 'vcl-accessibility-focus-root'; select(parent.ownerSVGElement) .selectAll('.' + className + '-source') .classed(className + '-source', false); select(parent.ownerSVGElement) .selectAll('.' + className + '-indicator') .remove(); }; const hideKeyboardHighlight = (parent: any) => { select(parent.ownerSVGElement) .selectAll('.vcl-accessibility-focus-indicator') .classed('hidden', true) .style('opacity', 0) .attr('opacity', 0); }; const drawKeyboardFocusClone = (inputElement: any, recursive?: boolean) => { let source = inputElement.tagName !== 'DIV' ? inputElement : select(inputElement.parentNode) .select('svg') .node(); let shouldDeleteSource = false; const className = !(source.tagName === 'svg') ? 'vcl-accessibility-focus' : 'vcl-accessibility-focus-root'; const isNotAGeometry = source.tagName === 'g' || source.tagName === 'svg'; if (isNotAGeometry) { const bbox = source.getBBox(); const width = source.tagName === 'svg' ? Math.max(+source.getAttribute('width') - 10, 0) : +bbox.width + 10; const height = source.tagName === 'svg' ? Math.max(+source.getAttribute('height') - 10, 0) : +bbox.height + 10; const x = source.tagName === 'svg' ? 5 : +bbox.x - 5; const y = source.tagName === 'svg' ? 5 : +bbox.y - 5; const newSource = select(!(source.tagName === 'svg') ? source.parentNode : source) .append('rect') .attr('x', x) .attr('y', y) .attr('width', width) .attr('height', height) .attr('transform', select(source).attr('transform') || null) .attr('fill', 'none') .style('fill', 'none'); source = newSource.node(); shouldDeleteSource = true; } else { const shouldHideOutline = select(source) .style('outline') .includes('auto'); if (shouldHideOutline) { select(source) .style('outline-width', '0px') .style('outline-offset', '0px') .style('outline-color', 'none'); } } const parent = source.parentNode; removeKeyboardHighlight(parent.tagName !== 'svg' ? parent : parent.firstElementChild); select(source).classed(className + '-source', true); const hasWidth = select(source).attr('width'); const highlightCopy = source.cloneNode(false); const haloCopy = source.cloneNode(false); const copy = source.cloneNode(false); if ((!recursive && !shouldDeleteSource) || (recursive && isNotAGeometry)) { const elevateParentLevel = !isNotAGeometry && (!(select(source.parentNode).attr('tabindex') === null) || select(source.parentNode).classed('offset-target')); const targetAppendLocation = !elevateParentLevel ? parent : parent.parentNode; const parentCopy = parent.cloneNode(false); parentCopy.appendChild(haloCopy); parentCopy.appendChild(highlightCopy); parentCopy.appendChild(copy); targetAppendLocation.appendChild(parentCopy); applyDefaults(select(parentCopy), className); select(parentCopy).attr('filter', null); } else { if (recursive) { // NOTE: below chunk assumes recursive === a circle SVG primitive // this is true for now, with circle-packing as the only current recursive chart // future hierarchical charts will need special treatment const baseRadius = +select(copy).attr('r'); parent.parentNode.appendChild(haloCopy); select(haloCopy) .attr('r', baseRadius + 6) .attr('stroke-width', 0); parent.parentNode.appendChild(highlightCopy); select(highlightCopy) .attr('r', baseRadius + 3) .attr('stroke-width', 0); // NOTE ALSO: recursive elements do not need to copy+append themselves, // they only need to append their halo + highlight elements } else { const isOffsetGroup = !!select(inputElement).attr('data-offset-group'); if (!isOffsetGroup) { if (source.nextSibling) { parent.insertBefore(copy, source.nextSibling); parent.insertBefore(highlightCopy, source.nextSibling); parent.insertBefore(haloCopy, source.nextSibling); } else { parent.appendChild(haloCopy); parent.appendChild(highlightCopy); parent.appendChild(copy); } } else { const offsetTarget = parent.nextSibling.nextSibling; parent.parentNode.insertBefore(haloCopy, offsetTarget); parent.parentNode.insertBefore(highlightCopy, offsetTarget); parent.parentNode.insertBefore(copy, offsetTarget); } } } const copyStyle = select(copy) .style('opacity', !isNotAGeometry ? 1 : 0) .attr('opacity', !isNotAGeometry ? 1 : 0) .style('stroke-opacity', !isNotAGeometry ? 1 : 0) .attr('stroke-opacity', !isNotAGeometry ? 1 : 0); if ((!recursive && !isNotAGeometry && hasWidth) || isNotAGeometry) { copyStyle.style('fill-opacity', 0).attr('fill-opacity', 0); } applyDefaults(copyStyle, className); const isAlluvial = select(source).data() && select(source).data()[0] && select(source).data()[0].source && select(source).data()[0].target && (select(source).data()[0].y0 || select(source).data()[0].y0 === 0); const highlightStyle = select(highlightCopy); applyDefaults(highlightStyle, className); applyOutlineOverride( highlightStyle, !isNotAGeometry && !recursive && !hasWidth ? 10 : 6, '#ffffff', isAlluvial ? select(source).data()[0] : undefined ); if (!recursive && !isNotAGeometry && hasWidth) { applySizeOverride(highlightStyle, 3); } highlightStyle.style('opacity', 1).attr('opacity', 1); const haloStyle = select(haloCopy); applyDefaults(haloStyle, className); applyOutlineOverride( haloStyle, !isNotAGeometry && !recursive && !hasWidth ? 14 : !isNotAGeometry ? 2 : 10, '#000000', isAlluvial ? select(source).data()[0] : undefined ); if (!recursive && !isNotAGeometry && hasWidth) { applySizeOverride(haloStyle, 7); } haloStyle.style('opacity', 1).attr('opacity', 1); if (shouldDeleteSource) { select(source).remove(); } }; const applyDefaults = (selection, className) => { if (selection.attr('d') && selection.attr('filter') && !selection.attr('marker-start')) { selection.attr('filter', null); } selection .attr('id', null) .attr('class', className + '-highlight ' + className + '-indicator') .attr('focusable', false) .attr('aria-label', null) .attr('aria-hidden', true) .attr('role', null) .style('pointer-events', 'none') .attr('tabindex', null) .attr('mix-blend-mode', null) .style('mix-blend-mode', null) .attr('r', (_, i, n) => { const r = parseFloat(select(n[i]).attr('r')); return r || 1; }); }; const applySizeOverride = (selection, offset) => { selection .attr('width', (_, i, n) => { const width = parseFloat(select(n[i]).attr('width')); return width + offset * 2; }) .attr('height', (_, i, n) => { const height = parseFloat(select(n[i]).attr('height')); return height + offset * 2; }) .attr('x', (_, i, n) => { const x = parseFloat(select(n[i]).attr('x')); return x - offset; }) .attr('y', (_, i, n) => { const y = parseFloat(select(n[i]).attr('y')); return y - offset; }); }; const applyOutlineOverride = (selection, extraStrokeWidth, strokeColor, d?) => { selection .style('stroke-dasharray', '') .attr('stroke-dasharray', null) .style('outline-offset', '0px') .style('outline-color', 'none') .style('outline-width', '0px') .attr('filter', null) .style('stroke-linecap', !d ? 'round' : 'butt') .style('fill', 'none') .style('stroke-opacity', 1) .style('stroke', strokeColor) .style('stroke-width', (_, i, n) => { const width = select(n[i]).style('stroke') !== 'none' ? parseFloat(select(n[i]).style('stroke-width')) || 0 : 0; const scaleIndex = select(n[i]).attr('transform') ? select(n[i]) .attr('transform') .indexOf('scale') : -1; let scale = 1; if (scaleIndex > -1) { const scaleSubstring = select(n[i]) .attr('transform') .substring(scaleIndex + 6); const endSubstring = scaleSubstring.indexOf(',') < scaleSubstring.indexOf(')') && scaleSubstring.indexOf(',') !== -1 ? scaleSubstring.indexOf(',') : scaleSubstring.indexOf(')'); scale = +scaleSubstring.substring(0, endSubstring); } let bonus = 0; const me = select(n[i]); if (me.attr('d') && d) { const originalPath = me.attr('d').substr(1); const offsetStart = `M ${d.source.x1 - extraStrokeWidth / 2} ${d.y0} L`; const offsetEnd = `L ${d.target.x0 + extraStrokeWidth / 2} ${d.y1}`; me.attr('d', offsetStart + originalPath + offsetEnd); } else if (me.attr('marker-start') && me.attr('data-centerX1') && me.attr('d')) { const x1 = me.attr('data-centerX1'); const y1 = me.attr('data-centerY1'); const x2 = me.attr('data-centerX2'); const y2 = me.attr('data-centerY2'); me.attr('d', `M ${x1} ${y1} L ${x2} ${y2}`); bonus = +me.attr('data-barSize') + 6; } me.attr('marker-start', null); me.attr('marker-end', null); return (width + extraStrokeWidth + bonus) / scale + 'px'; }); }; const findValidSiblingTarget = element => { return !element.nextElementSibling ? null : element.nextElementSibling.nodeName === 'g' ? element.nextElementSibling : findValidSiblingTarget(element.nextElementSibling); }; const findValidChildTarget = (element, requireTabIndex) => { if ( (!requireTabIndex || (requireTabIndex && select(element).attr('tabindex') !== null)) && !select(element).classed('vcl-accessibility-focus-highlight') ) { return element; } if (element.nextElementSibling) { return findValidChildTarget(element.nextElementSibling, requireTabIndex); } else { return null; } }; const getOffset = (el: any) => { const bounds = el.getBoundingClientRect(); // bounds.top // ie11 includes scroll already in pageX/Y, other tested browsers do not do this const left = bounds.left + (isIE11 ? 0 : document.body.scrollLeft + document.documentElement.scrollLeft); const top = bounds.top + (isIE11 ? 0 : document.body.scrollTop + document.documentElement.scrollTop); return { top, left }; }; const blurAsMouseout = (node: any) => { removeKeyboardHighlight(node.parentNode); const evt = new MouseEvent('mouseout', { bubbles: false, cancelable: true }); node.dispatchEvent(evt); }; const focusAsMouseover = (node, recursive: boolean, drawClone: boolean) => { const leftPos = getOffset(node).left; const topPos = getOffset(node).top; const evt = new MouseEvent('mouseover', { bubbles: false, cancelable: true, clientX: leftPos, clientY: topPos }); if (drawClone) { drawKeyboardFocusClone(node, recursive); } node.dispatchEvent(evt); };
the_stack
export const cloudFormMock = { 'id': 'form-b661635a-dc3e-4557-914a-3498ed47189c', 'name': 'form-with-all-fields', 'description': '', 'version': 0, 'tabs': [], 'fields': [ { 'fieldType': 'ContainerRepresentation', 'id': '26b10e64-0403-4686-a75b-0d45279ce3a8', 'name': 'Label', 'type': 'container', 'tab': null, 'numberOfColumns': 2, 'fields': { '1': [ { 'fieldType': 'FormFieldRepresentation', 'id': 'text1', 'name': 'Text1', 'type': 'text', 'value': null, 'required': false, 'readOnly': true, 'overrideId': false, 'colspan': 1, 'placeholder': null, 'minLength': 0, 'maxLength': 0, 'minValue': null, 'maxValue': null, 'regexPattern': null, 'visibilityCondition': null, 'params': { 'existingColspan': 1, 'maxColspan': 2 } } ], '2': [ { 'fieldType': 'FormFieldRepresentation', 'id': 'text2', 'name': 'Text2', 'type': 'text', 'value': null, 'required': false, 'readOnly': true, 'overrideId': false, 'colspan': 1, 'placeholder': null, 'minLength': 0, 'maxLength': 0, 'minValue': null, 'maxValue': null, 'regexPattern': null, 'visibilityCondition': null, 'params': { 'existingColspan': 1, 'maxColspan': 2 } } ] } }, { 'fieldType': 'ContainerRepresentation', 'id': '69c1390a-8d8d-423c-8efb-8e43401efa42', 'name': 'Label', 'type': 'container', 'tab': null, 'numberOfColumns': 2, 'fields': { '1': [ { 'fieldType': 'FormFieldRepresentation', 'id': 'multilinetext1', 'name': 'Multiline text1', 'type': 'multi-line-text', 'overrideId': false, 'colspan': 1, 'placeholder': null, 'minLength': 0, 'maxLength': 0, 'regexPattern': null, 'required': false, 'readOnly': true, 'visibilityCondition': null, 'params': { 'existingColspan': 1, 'maxColspan': 2 } } ], '2': [ { 'fieldType': 'FormFieldRepresentation', 'id': 'multilinetext2', 'name': 'Multiline text2', 'type': 'multi-line-text', 'overrideId': false, 'colspan': 1, 'placeholder': null, 'minLength': 0, 'maxLength': 0, 'regexPattern': null, 'required': false, 'readOnly': true, 'visibilityCondition': null, 'params': { 'existingColspan': 1, 'maxColspan': 2 } } ] } }, { 'fieldType': 'ContainerRepresentation', 'id': 'df046463-2d65-4388-9ee1-0e1517985215', 'name': 'Label', 'type': 'container', 'tab': null, 'numberOfColumns': 2, 'fields': { '1': [ { 'fieldType': 'FormFieldRepresentation', 'id': 'number1', 'overrideId': false, 'name': 'Number1', 'type': 'integer', 'colspan': 1, 'placeholder': null, 'readOnly': true, 'minValue': null, 'maxValue': null, 'required': false, 'visibilityCondition': null, 'params': { 'existingColspan': 1, 'maxColspan': 2 } } ], '2': [ { 'fieldType': 'FormFieldRepresentation', 'id': 'number2', 'overrideId': false, 'name': 'Number2', 'type': 'integer', 'colspan': 1, 'placeholder': null, 'readOnly': true, 'minValue': null, 'maxValue': null, 'required': false, 'visibilityCondition': null, 'params': { 'existingColspan': 1, 'maxColspan': 2 } } ] } }, { 'fieldType': 'ContainerRepresentation', 'id': '9672cc7b-1959-49c9-96be-3816e57bdfc1', 'name': 'Label', 'type': 'container', 'tab': null, 'numberOfColumns': 2, 'fields': { '1': [ { 'fieldType': 'FormFieldRepresentation', 'id': 'checkbox1', 'name': 'Checkbox1', 'type': 'boolean', 'required': false, 'readOnly': true, 'colspan': 1, 'overrideId': false, 'visibilityCondition': null, 'params': { 'existingColspan': 1, 'maxColspan': 2 } } ], '2': [ { 'fieldType': 'FormFieldRepresentation', 'id': 'checkbox2', 'name': 'Checkbox2', 'type': 'boolean', 'required': false, 'readOnly': true, 'colspan': 1, 'overrideId': false, 'visibilityCondition': null, 'params': { 'existingColspan': 1, 'maxColspan': 2 } } ] } }, { 'fieldType': 'ContainerRepresentation', 'id': '054d193e-a899-4494-9a3e-b489315b7d57', 'name': 'Label', 'type': 'container', 'tab': null, 'numberOfColumns': 2, 'fields': { '1': [ { 'fieldType': 'FormFieldRepresentation', 'id': 'dropdown1', 'name': 'Dropdown1', 'type': 'dropdown', 'value': null, 'required': false, 'readOnly': true, 'overrideId': false, 'colspan': 1, 'placeholder': null, 'optionType': 'manual', 'options': [], 'endpoint': null, 'requestHeaders': null, 'restUrl': null, 'restResponsePath': null, 'restIdProperty': null, 'restLabelProperty': null, 'visibilityCondition': null, 'params': { 'existingColspan': 1, 'maxColspan': 2 } } ], '2': [ { 'fieldType': 'FormFieldRepresentation', 'id': 'dropdown2', 'name': 'Dropdown2', 'type': 'dropdown', 'value': null, 'required': false, 'readOnly': true, 'overrideId': false, 'colspan': 1, 'placeholder': null, 'optionType': 'manual', 'options': [], 'endpoint': null, 'requestHeaders': null, 'restUrl': null, 'restResponsePath': null, 'restIdProperty': null, 'restLabelProperty': null, 'visibilityCondition': null, 'params': { 'existingColspan': 1, 'maxColspan': 2 } } ] } }, { 'fieldType': 'ContainerRepresentation', 'id': '1f8f0b66-e022-4667-91b4-bbbf2ddc36fb', 'name': 'Label', 'type': 'container', 'tab': null, 'numberOfColumns': 2, 'fields': { '1': [ { 'fieldType': 'FormFieldRepresentation', 'id': 'amount1', 'name': 'Amount1', 'type': 'amount', 'value': null, 'required': false, 'readOnly': true, 'overrideId': false, 'colspan': 1, 'placeholder': '123', 'minValue': null, 'maxValue': null, 'visibilityCondition': null, 'params': { 'existingColspan': 1, 'maxColspan': 2 }, 'enableFractions': false, 'currency': '$' } ], '2': [ { 'fieldType': 'FormFieldRepresentation', 'id': 'amount2', 'name': 'Amount2', 'type': 'amount', 'value': null, 'required': false, 'readOnly': true, 'overrideId': false, 'colspan': 1, 'placeholder': '123', 'minValue': null, 'maxValue': null, 'visibilityCondition': null, 'params': { 'existingColspan': 1, 'maxColspan': 2 }, 'enableFractions': false, 'currency': '$' } ] } }, { 'fieldType': 'ContainerRepresentation', 'id': '541a368b-67ee-4a7c-ae7e-232c050b9e24', 'name': 'Label', 'type': 'container', 'tab': null, 'numberOfColumns': 2, 'fields': { '1': [ { 'fieldType': 'FormFieldRepresentation', 'id': 'date1', 'name': 'Date1', 'type': 'date', 'overrideId': false, 'required': false, 'readOnly': true, 'colspan': 1, 'placeholder': null, 'minValue': null, 'maxValue': null, 'visibilityCondition': null, 'params': { 'existingColspan': 1, 'maxColspan': 2 }, 'dateDisplayFormat': 'D-M-YYYY' } ], '2': [ { 'fieldType': 'FormFieldRepresentation', 'id': 'date2', 'name': 'Date2', 'type': 'date', 'overrideId': false, 'required': false, 'readOnly': true, 'colspan': 1, 'placeholder': null, 'minValue': null, 'maxValue': null, 'visibilityCondition': null, 'params': { 'existingColspan': 1, 'maxColspan': 2 }, 'dateDisplayFormat': 'D-M-YYYY' } ] } }, { 'fieldType': 'ContainerRepresentation', 'id': 'e79cb7e2-3dc1-4c79-8158-28662c28a9f3', 'name': 'Label', 'type': 'container', 'tab': null, 'numberOfColumns': 2, 'fields': { '1': [ { 'fieldType': 'FormFieldRepresentation', 'id': 'radiobuttons1', 'name': 'Radio buttons1', 'type': 'radio-buttons', 'value': null, 'required': false, 'readOnly': true, 'overrideId': false, 'colspan': 1, 'placeholder': null, 'optionType': 'manual', 'options': [ { 'id': 'option_1', 'name': 'Option 1' }, { 'id': 'option_2', 'name': 'Option 2' } ], 'endpoint': null, 'requestHeaders': null, 'restUrl': null, 'restResponsePath': null, 'restIdProperty': null, 'restLabelProperty': null, 'visibilityCondition': null, 'params': { 'existingColspan': 1, 'maxColspan': 2 } } ], '2': [ { 'fieldType': 'FormFieldRepresentation', 'id': 'radiobuttons2', 'name': 'Radio buttons2', 'type': 'radio-buttons', 'value': null, 'required': false, 'readOnly': true, 'overrideId': false, 'colspan': 1, 'placeholder': null, 'optionType': 'manual', 'options': [ { 'id': 'option_1', 'name': 'Option 1' }, { 'id': 'option_2', 'name': 'Option 2' } ], 'endpoint': null, 'requestHeaders': null, 'restUrl': null, 'restResponsePath': null, 'restIdProperty': null, 'restLabelProperty': null, 'visibilityCondition': null, 'params': { 'existingColspan': 1, 'maxColspan': 2 } } ] } }, { 'fieldType': 'ContainerRepresentation', 'id': '7c01ed35-be86-4be7-9c28-ed640a5a2ae1', 'name': 'Label', 'type': 'container', 'tab': null, 'numberOfColumns': 2, 'fields': { '1': [ { 'fieldType': 'AttachFileFieldRepresentation', 'id': 'attachfile1', 'name': 'Attach file1', 'type': 'upload', 'value': null, 'required': false, 'readOnly': true, 'overrideId': false, 'colspan': 1, 'placeholder': null, 'visibilityCondition': null, 'params': { 'existingColspan': 1, 'maxColspan': 2, 'fileSource': { 'serviceId': 'all-file-sources', 'name': 'All file sources' }, 'multiple': false, 'link': false } } ], '2': [ { 'fieldType': 'AttachFileFieldRepresentation', 'id': 'attachfile2', 'name': 'Attach file2', 'type': 'upload', 'value': null, 'required': false, 'readOnly': true, 'overrideId': false, 'colspan': 1, 'placeholder': null, 'visibilityCondition': null, 'params': { 'existingColspan': 1, 'maxColspan': 2, 'fileSource': { 'serviceId': 'all-file-sources', 'name': 'All file sources' }, 'multiple': false, 'link': false } } ] } }, { 'fieldType': 'ContainerRepresentation', 'id': '07b13b96-d469-4a1e-8a9a-9bb957c68869', 'name': 'Label', 'type': 'container', 'tab': null, 'numberOfColumns': 2, 'fields': { '1': [ { 'fieldType': 'FormFieldRepresentation', 'id': 'displayvalue1', 'name': 'Display value1', 'type': 'readonly', 'value': 'No field selected', 'readOnly': true, 'required': false, 'overrideId': false, 'colspan': 1, 'visibilityCondition': null, 'params': { 'existingColspan': 1, 'maxColspan': 2, 'field': { 'id': 'displayvalue', 'name': 'Display value', 'type': 'text', 'responseVariable': true } } } ], '2': [ { 'fieldType': 'FormFieldRepresentation', 'id': 'displayvalue2', 'name': 'Display value2', 'type': 'readonly', 'value': 'No field selected', 'readOnly': true, 'required': false, 'overrideId': false, 'colspan': 1, 'visibilityCondition': null, 'params': { 'existingColspan': 1, 'maxColspan': 2, 'field': { 'id': 'displayvalue', 'name': 'Display value', 'type': 'text', 'responseVariable': true } } } ] } }, { 'fieldType': 'ContainerRepresentation', 'id': '1576ef25-c842-494c-ab84-265a1e3bf68d', 'name': 'Label', 'type': 'container', 'tab': null, 'numberOfColumns': 2, 'fields': { '1': [ { 'fieldType': 'FormFieldRepresentation', 'id': 'displaytext1', 'name': 'Display text1', 'type': 'readonly-text', 'value': 'Display text as part of the form', 'readOnly': true, 'required': false, 'overrideId': false, 'colspan': 1, 'visibilityCondition': null, 'params': { 'existingColspan': 1, 'maxColspan': 2 } } ], '2': [ { 'fieldType': 'FormFieldRepresentation', 'id': 'displaytext2', 'name': 'Display text2', 'type': 'readonly-text', 'value': 'Display text as part of the form', 'readOnly': true, 'required': false, 'overrideId': false, 'colspan': 1, 'visibilityCondition': null, 'params': { 'existingColspan': 1, 'maxColspan': 2 } } ] } } ], 'outcomes': [], 'metadata': {}, 'variables': [ { 'name': 'FormVarStr', 'type': 'string', 'value': '' }, { 'name': 'FormVarInt', 'type': 'integer', 'value': '' }, { 'name': 'FormVarBool', 'type': 'boolean', 'value': '' }, { 'name': 'FormVarDate', 'type': 'date', 'value': '' }, { 'name': 'NewVar', 'type': 'string', 'value': '' } ] }; export let fakeCloudForm = { 'formRepresentation': { 'id': 'form-de8895be-d0d7-4434-beef-559b15305d72', 'name': 'StartEventForm', 'description': '', 'version': 0, 'formDefinition': { 'tabs': [], 'fields': [ { 'type': 'container', 'id': '5a6b24c1-db2b-45e9-9aff-142395433d23', 'name': 'Label', 'tab': null, 'fields': { '1': [ { 'type': 'text', 'id': 'firstName', 'name': 'firstName', 'colspan': 1, 'params': { 'existingColspan': 1, 'maxColspan': 2 }, 'visibilityCondition': null, 'placeholder': null, 'value': null, 'required': false, 'minLength': 0, 'maxLength': 0, 'regexPattern': null } ], '2': [ { 'type': 'text', 'id': 'lastName', 'name': 'lastName', 'colspan': 1, 'params': { 'existingColspan': 1, 'maxColspan': 2 }, 'visibilityCondition': null, 'placeholder': null, 'value': null, 'required': false, 'minLength': 0, 'maxLength': 0, 'regexPattern': null } ] }, 'numberOfColumns': 2 } ], 'outcomes': [], 'metadata': {}, 'variables': [] } } }; export const emptyFormRepresentationJSON = { 'description': '', 'fields': [], 'id': 'form-3de070b6-63df-4058-8028-ac82283d64fa', 'metadata': {}, 'name': 'form', 'outcomes': [], 'length': 0, 'processDefinitionId': 'ed4a6233-0ad8-11ea-8616-e6267bbdb057', 'processInstanceId': 'ec921948-0ad9-11ea-8616-e6267bbdb057', 'processVariables': [], 'standAlone': true, 'tabs': [], 'taskId': 'ec92194b-0ad9-11ea-8616-e6267bbdb057', 'taskName': null, 'variables': [], 'version': 0 }; export const conditionalUploadWidgetsMock: any = { 'formRepresentation': { 'id': 'form-fb7858f7-5cf6-4afe-b462-c15a5dc0c34c', 'name': 'AttachVisibility', 'description': '', 'version': 0, 'formDefinition': { 'tabs': [], 'fields': [ { 'id': '1dc63387-aa9d-4f06-adfa-37817e8fd394', 'name': 'Label', 'type': 'container', 'tab': null, 'numberOfColumns': 2, 'fields': { '1': [ { 'id': 'Text0xlk8n', 'name': 'Text', 'type': 'text', 'required': false, 'colspan': 1, 'placeholder': null, 'minLength': 0, 'maxLength': 0, 'regexPattern': null, 'visibilityCondition': null, 'params': { 'existingColspan': 1, 'maxColspan': 2 } } ], '2': [ { 'id': 'Attachfile0h9fr1', 'name': 'Attach file', 'type': 'upload', 'required': false, 'colspan': 1, 'visibilityCondition': { 'leftFormFieldId': 'Text0xlk8n', 'leftRestResponseId': '', 'operator': '==', 'rightValue': 'Attach', 'rightType': null, 'rightFormFieldId': '', 'rightRestResponseId': '', 'nextConditionOperator': '', 'nextCondition': null }, 'params': { 'existingColspan': 1, 'maxColspan': 2, 'fileSource': { 'serviceId': 'alfresco-content', 'name': 'Alfresco Content' }, 'multiple': false, 'link': false } } ] } } ], 'outcomes': [ { 'id': '5f2f1c2d-5a79-4ed1-a262-4fef190d41eb', 'name': 'Custom Outcome', 'visibilityCondition': { 'leftType': 'field', 'leftValue': 'Text0xlk8n', 'operator': '==', 'rightValue': 'hi', 'rightType': 'value', 'nextConditionOperator': '', 'nextCondition': null } } ], 'metadata': {}, 'variables': [] } } }; export const multilingualForm: any = { 'formRepresentation': { 'id': 'form-2aaaf20e-43d3-46bf-89be-859d5f512dd2', 'name': 'multilingualform', 'description': '', 'version': 0, 'formDefinition': { 'tabs': [], 'fields': [ { 'id': '451e2235-3310-4c2d-9b4a-08b53ae1640c', 'name': 'Label', 'type': 'container', 'tab': null, 'numberOfColumns': 2, 'fields': { '1': [ { 'id': 'textField', 'name': 'TEXT_FIELD.TITLE', 'type': 'text', 'required': false, 'colspan': 1, 'placeholder': null, 'minLength': 0, 'maxLength': 0, 'regexPattern': null, 'visibilityCondition': null, 'params': { 'existingColspan': 1, 'maxColspan': 2 } } ], '2': [] } }, { 'id': '1c87df6c-514e-45a7-96bc-508562683bb3', 'name': 'Label', 'type': 'container', 'tab': null, 'numberOfColumns': 2, 'fields': { '1': [ { 'id': 'fildUploadField', 'name': 'FILE_UPLOAD_FIELD.TITLE', 'type': 'multi-line-text', 'colspan': 1, 'placeholder': null, 'minLength': 0, 'maxLength': 0, 'regexPattern': null, 'required': false, 'visibilityCondition': null, 'params': { 'existingColspan': 1, 'maxColspan': 2 } } ], '2': [ { 'id': 'amountField', 'name': 'AMOUNT_FIELD.TITLE', 'type': 'amount', 'required': false, 'colspan': 1, 'placeholder': '123', 'minValue': null, 'maxValue': null, 'visibilityCondition': null, 'params': { 'existingColspan': 1, 'maxColspan': 2 }, 'enableFractions': false, 'currency': '$' } ] } }, { 'id': '33138eea-130f-4bba-b5a5-29ea60f31786', 'name': 'Label', 'type': 'container', 'tab': null, 'numberOfColumns': 2, 'fields': { '1': [ { 'id': 'dateField', 'name': 'DATE_FIELD.TITLE', 'type': 'date', 'required': false, 'colspan': 1, 'placeholder': null, 'minValue': null, 'maxValue': null, 'visibilityCondition': null, 'params': { 'existingColspan': 1, 'maxColspan': 2 }, 'dateDisplayFormat': 'D-M-YYYY' } ], '2': [] } } ], 'outcomes': [], 'metadata': {}, 'variables': [] } } }; export let fakeMetadataForm = { 'id': 'form-de8895be-d0d7-4434-beef-559b15305d72', 'name': 'StartEventForm', 'description': '', 'version': 0, 'formDefinition': { 'tabs': [], 'fields': [ { 'type': 'container', 'id': '5a6b24c1-db2b-45e9-9aff-142395433d23', 'name': 'Label', 'tab': null, 'fields': { '1': [ { 'type': 'text', 'id': 'pfx_property_one', 'name': 'pfx_property_one', 'colspan': 1, 'params': { 'existingColspan': 1, 'maxColspan': 2 }, 'visibilityCondition': null, 'placeholder': null, 'value': null, 'required': false, 'minLength': 0, 'maxLength': 0, 'regexPattern': null } ], '2': [ { 'type': 'boolean', 'id': 'pfx_property_two', 'name': 'pfx_property_two', 'colspan': 1, 'params': { 'existingColspan': 1, 'maxColspan': 2 }, 'visibilityCondition': null, 'placeholder': null, 'value': null, 'required': false, 'minLength': 0, 'maxLength': 0, 'regexPattern': null } ], '3': [ { 'id': 'content_form_nodes', 'name': 'Nodes', 'type': 'upload', 'readOnly': false, 'required': true, 'colspan': 1, 'visibilityCondition': null, 'params': { 'existingColspan': 1, 'maxColspan': 2, 'fileSource': { 'serviceId': 'alfresco-content', 'name': 'Alfresco Content', 'metadataAllowed': true }, 'multiple': true, 'menuOptions': { 'show': true, 'download': true, 'retrieveMetadata': true, 'remove': true }, 'link': false } } ], '4': [ { 'id': 'pfx_property_three', 'name': 'pfx_property_three', 'required': false, 'readOnly': false, 'colspan': 1, 'params': { 'existingColspan': 1, 'maxColspan': 2 }, 'visibilityCondition': null, 'type': 'dropdown', 'optionType': 'manual', 'options': [ { 'id': 'empty', 'name': 'Choose one...' }, { 'id': 'opt_1', 'name': 'Option 1' }, { 'id': 'opt_2', 'name': 'Option 2' } ], 'value': 'empty', 'restUrl': null, 'restResponsePath': null, 'restIdProperty': null, 'restLabelProperty': null } ], '5': [ { 'id': 'pfx_property_four', 'name': 'pfx_property_four', 'required': false, 'readOnly': false, 'colspan': 1, 'params': { 'existingColspan': 1, 'maxColspan': 2 }, 'visibilityCondition': null, 'type': 'dropdown', 'optionType': 'manual', 'options': [ { 'id': 'empty', 'name': 'Choose one...' }, { 'id': 'option_1', 'name': 'Option: 1' }, { 'id': 'option_2', 'name': 'Option: 2' } ], 'value': 'empty', 'restUrl': null, 'restResponsePath': null, 'restIdProperty': null, 'restLabelProperty': null } ], '6': [ { 'id': 'pfx_property_five', 'name': 'pfx_property_five', 'required': false, 'readOnly': false, 'colspan': 1, 'params': { 'existingColspan': 1, 'maxColspan': 2 }, 'visibilityCondition': null, 'type': 'dropdown', 'optionType': 'manual', 'options': [ { 'id': 'empty', 'name': 'Choose one...' }, { 'id': 'green', 'name': 'Colour green' }, { 'id': 'orange', 'name': 'Colour orange' } ], 'value': 'empty', 'restUrl': null, 'restResponsePath': null, 'restIdProperty': null, 'restLabelProperty': null } ], '7': [ { 'id': 'cmfb85b2a7295ba41209750bca176ccaf9a', 'name': 'File viewer', 'type': 'file-viewer', 'readOnly': false, 'required': false, 'colspan': 1, 'visibilityCondition': null, 'params': { 'existingColspan': 1, 'maxColspan': 2, 'uploadWidget': 'content_form_nodes' } } ], '8': [ { 'type': 'text', 'id': 'pfx_property_six', 'name': 'pfx_property_six', 'colspan': 1, 'params': { 'existingColspan': 1, 'maxColspan': 2 }, 'visibilityCondition': null, 'placeholder': null, 'value': null, 'required': false, 'minLength': 0, 'maxLength': 0, 'regexPattern': null } ], '9': [ { 'type': 'text', 'id': 'pfx_property_seven', 'name': 'pfx_property_seven', 'colspan': 1, 'params': { 'existingColspan': 1, 'maxColspan': 2 }, 'visibilityCondition': null, 'placeholder': null, 'value': null, 'required': false, 'minLength': 0, 'maxLength': 0, 'regexPattern': null } ], '10': [ { 'type': 'text', 'id': 'pfx_property_eight', 'name': 'pfx_property_eight', 'colspan': 1, 'params': { 'existingColspan': 1, 'maxColspan': 2 }, 'visibilityCondition': null, 'placeholder': null, 'value': null, 'required': false, 'minLength': 0, 'maxLength': 0, 'regexPattern': null } ] }, 'numberOfColumns': 2 } ], 'outcomes': [], 'metadata': {}, 'variables': [] } }; export let fakeViewerForm = { 'id': 'form-de8895be-d0d7-4434-beef-559b15305d72', 'name': 'StartEventForm', 'description': '', 'version': 0, 'formDefinition': { 'tabs': [], 'fields': [ { 'type': 'container', 'id': '5a6b24c1-db2b-45e9-9aff-142395433d23', 'name': 'Label', 'tab': null, 'fields': { '1': [ { 'id': 'content_form_nodes', 'name': 'Nodes', 'type': 'upload', 'readOnly': false, 'required': true, 'colspan': 1, 'visibilityCondition': null, 'params': { 'existingColspan': 1, 'maxColspan': 2, 'fileSource': { 'serviceId': 'alfresco-content', 'name': 'Alfresco Content', 'metadataAllowed': true }, 'multiple': true, 'menuOptions': { 'show': true, 'download': true, 'retrieveMetadata': true, 'remove': true }, 'link': false } } ], '2': [ { 'id': 'upload_widget', 'name': 'Nodes', 'type': 'upload', 'readOnly': false, 'required': true, 'colspan': 1, 'visibilityCondition': null, 'params': { 'existingColspan': 1, 'maxColspan': 2, 'fileSource': { 'serviceId': 'alfresco-content', 'name': 'Alfresco Content', 'metadataAllowed': true }, 'multiple': true, 'menuOptions': { 'show': true, 'download': true, 'retrieveMetadata': true, 'remove': true }, 'link': false } } ], '3': [ { 'id': 'cmfb85b2a7295ba41209750bca176ccaf9a', 'name': 'File viewer', 'type': 'file-viewer', 'readOnly': false, 'required': false, 'colspan': 1, 'visibilityCondition': null, 'params': { 'existingColspan': 1, 'maxColspan': 2, 'uploadWidget': 'content_form_nodes' } } ] }, 'numberOfColumns': 2 } ], 'outcomes': [], 'metadata': {}, 'variables': [] } };
the_stack
import { all, alt, optWhitespace, Parser, regexp, seq, string, succeed } from 'parsimmon'; import { AsciiCommand } from '../cmd_line/commands/ascii'; import { BangCommand } from '../cmd_line/commands/bang'; import { BufferDeleteCommand } from '../cmd_line/commands/bufferDelete'; import { CloseCommand } from '../cmd_line/commands/close'; import { CopyCommand } from '../cmd_line/commands/copy'; import { DeleteRangeCommand } from '../cmd_line/commands/deleteRange'; import { DigraphsCommand } from '../cmd_line/commands/digraph'; import { FileCommand } from '../cmd_line/commands/file'; import { FileInfoCommand } from '../cmd_line/commands/fileInfo'; import { GotoCommand } from '../cmd_line/commands/goto'; import { GotoLineCommand } from '../cmd_line/commands/gotoLine'; import { HistoryCommand } from '../cmd_line/commands/history'; import { ClearJumpsCommand, JumpsCommand } from '../cmd_line/commands/jumps'; import { CenterCommand, LeftCommand, RightCommand } from '../cmd_line/commands/leftRightCenter'; import { DeleteMarksCommand, MarksCommand } from '../cmd_line/commands/marks'; import { NohlCommand } from '../cmd_line/commands/nohl'; import { OnlyCommand } from '../cmd_line/commands/only'; import { PrintCommand } from '../cmd_line/commands/print'; import { PutExCommand } from '../cmd_line/commands/put'; import { QuitCommand } from '../cmd_line/commands/quit'; import { ReadCommand } from '../cmd_line/commands/read'; import { RegisterCommand } from '../cmd_line/commands/register'; import { SetOptionsCommand } from '../cmd_line/commands/setoptions'; import { ShCommand } from '../cmd_line/commands/sh'; import { SmileCommand } from '../cmd_line/commands/smile'; import { SortCommand } from '../cmd_line/commands/sort'; import { SubstituteCommand } from '../cmd_line/commands/substitute'; import { TabCommand } from '../cmd_line/commands/tab'; import { TerminalCommand } from '../cmd_line/commands/terminal'; import { UndoCommand } from '../cmd_line/commands/undo'; import { VsCodeCommand } from '../cmd_line/commands/vscode'; import { WallCommand } from '../cmd_line/commands/wall'; import { WriteCommand } from '../cmd_line/commands/write'; import { WriteQuitCommand } from '../cmd_line/commands/writequit'; import { WriteQuitAllCommand } from '../cmd_line/commands/writequitall'; import { YankCommand } from '../cmd_line/commands/yank'; import { ErrorCode, VimError } from '../error'; import { VimState } from '../state/vimState'; import { StatusBar } from '../statusBar'; import { ExCommand } from './exCommand'; import { LineRange } from './lineRange'; import { nameAbbrevParser } from './parserUtils'; type ArgParser = Parser<ExCommand>; /** * A list of all builtin ex commands and their argument parsers * Each element is [[abbrev, rest], argParser] * If argParser is undefined, it's yet to be implemented (PRs are welcome!) * * This list comes directly from nvim's `:help index` (except a few additions, which are commented) */ export const builtinExCommands: ReadonlyArray<[[string, string], ArgParser | undefined]> = [ [['', ''], succeed(new GotoLineCommand())], [['!', ''], BangCommand.argParser], [['#', ''], PrintCommand.argParser({ printNumbers: true, printText: true })], // TODO: Ignore #! (shebang) [['&', ''], undefined], [['*', ''], undefined], [['<', ''], undefined], [['=', ''], PrintCommand.argParser({ printNumbers: true, printText: false })], [['>', ''], undefined], [['@', ''], undefined], [['@@', ''], undefined], [['N', 'ext'], undefined], [['a', 'ppend'], undefined], [['ab', 'breviate'], undefined], [['abc', 'lear'], undefined], [['abo', 'veleft'], undefined], [['al', 'l'], undefined], [['am', 'enu'], undefined], [['an', 'oremenu'], undefined], [['ar', 'gs'], undefined], [['arga', 'dd'], undefined], [['argd', 'elete'], undefined], [['argdo', ''], undefined], [['arge', 'dit'], undefined], [['argg', 'lobal'], undefined], [['argl', 'ocal'], undefined], [['argu', 'ment'], undefined], [['as', 'cii'], succeed(new AsciiCommand())], [['au', 'tocmd'], undefined], [['aug', 'roup'], undefined], [['aun', 'menu'], undefined], [['b', 'uffer'], undefined], [['bN', 'ext'], TabCommand.argParsers.bprev], [['ba', 'll'], undefined], [['bad', 'd'], undefined], [['balt', ''], undefined], [['bd', 'elete'], BufferDeleteCommand.argParser], [['be', 'have'], undefined], [['bel', 'owright'], undefined], [['bf', 'irst'], undefined], [['bl', 'ast'], undefined], [['bm', 'odified'], undefined], [['bn', 'ext'], TabCommand.argParsers.bnext], [['bo', 'tright'], undefined], [['bp', 'revious'], TabCommand.argParsers.bprev], [['br', 'ewind'], undefined], [['brea', 'k'], undefined], [['breaka', 'dd'], undefined], [['breakd', 'el'], undefined], [['breakl', 'ist'], undefined], [['bro', 'wse'], undefined], [['bufdo', ''], undefined], [['buffers', ''], undefined], [['bun', 'load'], undefined], [['bw', 'ipeout'], undefined], [['c', 'hange'], undefined], [['cN', 'ext'], undefined], [['cNf', 'ile'], undefined], [['ca', 'bbrev'], undefined], [['cabc', 'lear'], undefined], [['cabo', 've'], undefined], [['cad', 'dbuffer'], undefined], [['cadde', 'xpr'], undefined], [['caddf', 'ile'], undefined], [['caf', 'ter'], undefined], [['cal', 'l'], undefined], [['cat', 'ch'], undefined], [['cb', 'uffer'], undefined], [['cbef', 'ore'], undefined], [['cbel', 'ow'], undefined], [['cbo', 'ttom'], undefined], [['cc', ''], undefined], [['ccl', 'ose'], undefined], [['cd', ''], undefined], [['cdo', ''], undefined], [['ce', 'nter'], CenterCommand.argParser], [['cex', 'pr'], undefined], [['cf', 'ile'], undefined], [['cfd', 'o'], undefined], [['cfir', 'st'], undefined], [['cg', 'etfile'], undefined], [['cgetb', 'uffer'], undefined], [['cgete', 'xpr'], undefined], [['changes', ''], undefined], [['chd', 'ir'], undefined], [['che', 'ckpath'], undefined], [['checkh', 'ealth'], undefined], [['checkt', 'ime'], undefined], [['chi', 'story'], undefined], [['cl', 'ist'], undefined], [['cla', 'st'], undefined], [['cle', 'arjumps'], succeed(new ClearJumpsCommand())], [['clo', 'se'], CloseCommand.argParser], [['cm', 'ap'], undefined], [['cmapc', 'lear'], undefined], [['cme', 'nu'], undefined], [['cn', 'ext'], undefined], [['cnew', 'er'], undefined], [['cnf', 'ile'], undefined], [['cno', 'remap'], undefined], [['cnorea', 'bbrev'], undefined], [['cnoreme', 'nu'], undefined], [['co', 'py'], CopyCommand.argParser], [['col', 'der'], undefined], [['colo', 'rscheme'], undefined], [['com', 'mand'], undefined], [['comc', 'lear'], undefined], [['comp', 'iler'], undefined], [['con', 'tinue'], undefined], [['conf', 'irm'], undefined], [['cons', 't'], undefined], [['cope', 'n'], undefined], [['cp', 'revious'], undefined], [['cpf', 'ile'], undefined], [['cq', 'uit'], undefined], [['cr', 'ewind'], undefined], [['cs', 'cope'], undefined], [['cst', 'ag'], undefined], [['cu', 'nmap'], undefined], [['cuna', 'bbrev'], undefined], [['cunme', 'nu'], undefined], [['cw', 'indow'], undefined], [['d', 'elete'], DeleteRangeCommand.argParser], [['deb', 'ug'], undefined], [['debugg', 'reedy'], undefined], [['delc', 'ommand'], undefined], [['delf', 'unction'], undefined], [['delm', 'arks'], DeleteMarksCommand.argParser], [['di', 'splay'], RegisterCommand.argParser], [['dif', 'fupdate'], undefined], [['diffg', 'et'], undefined], [['diffo', 'ff'], undefined], [['diffp', 'atch'], undefined], [['diffpu', 't'], undefined], [['diffs', 'plit'], undefined], [['diffthis', ''], undefined], [['dig', 'raphs'], DigraphsCommand.argParser], [['dj', 'ump'], undefined], [['dl', ''], undefined], [['dli', 'st'], undefined], [['do', 'autocmd'], undefined], [['doautoa', 'll'], undefined], [['dr', 'op'], undefined], [['ds', 'earch'], undefined], [['dsp', 'lit'], undefined], [['e', 'dit'], FileCommand.argParsers.edit], [['ea', 'rlier'], undefined], [['ec', 'ho'], undefined], [['echoe', 'rr'], undefined], [['echoh', 'l'], undefined], [['echom', 'sg'], undefined], [['echon', ''], undefined], [['el', 'se'], undefined], [['elsei', 'f'], undefined], [['em', 'enu'], undefined], [['en', 'dif'], undefined], [['endf', 'unction'], undefined], [['endfo', 'r'], undefined], [['endt', 'ry'], undefined], [['endw', 'hile'], undefined], [['ene', 'w'], FileCommand.argParsers.enew], [['ev', 'al'], undefined], [['ex', ''], FileCommand.argParsers.edit], [['exe', 'cute'], undefined], [['exi', 't'], WriteQuitCommand.argParser], [['exu', 'sage'], undefined], [['f', 'ile'], FileInfoCommand.argParser], [['files', ''], undefined], [['filet', 'ype'], undefined], [['filt', 'er'], undefined], [['fin', 'd'], undefined], [['fina', 'lly'], undefined], [['fini', 'sh'], undefined], [['fir', 'st'], undefined], [['fo', 'ld'], undefined], [['foldc', 'lose'], undefined], [['foldd', 'oopen'], undefined], [['folddoc', 'losed'], undefined], [['foldo', 'pen'], undefined], [['for', ''], undefined], [['fu', 'nction'], undefined], [['g', 'lobal'], undefined], [['go', 'to'], GotoCommand.argParser], [['gr', 'ep'], undefined], [['grepa', 'dd'], undefined], [['gu', 'i'], undefined], [['gv', 'im'], undefined], [['h', 'elp'], undefined], [['ha', 'rdcopy'], undefined], [['helpc', 'lose'], undefined], [['helpg', 'rep'], undefined], [['helpt', 'ags'], undefined], [['hi', 'ghlight'], undefined], [['hid', 'e'], undefined], [['his', 'tory'], HistoryCommand.argParser], [['i', 'nsert'], undefined], [['ia', 'bbrev'], undefined], [['iabc', 'lear'], undefined], [['if', ''], undefined], [['ij', 'ump'], undefined], [['il', 'ist'], undefined], [['im', 'ap'], undefined], [['imapc', 'lear'], undefined], [['ime', 'nu'], undefined], [['ino', 'remap'], undefined], [['inorea', 'bbrev'], undefined], [['inoreme', 'nu'], undefined], [['int', 'ro'], undefined], [['is', 'earch'], undefined], [['isp', 'lit'], undefined], [['iu', 'nmap'], undefined], [['iuna', 'bbrev'], undefined], [['iunme', 'nu'], undefined], [['j', 'oin'], undefined], [['ju', 'mps'], succeed(new JumpsCommand())], [['k', ''], undefined], [['kee', 'pmarks'], undefined], [['keepa', 'lt'], undefined], [['keepj', 'umps'], undefined], [['keepp', 'atterns'], undefined], [['l', 'ist'], PrintCommand.argParser({ printNumbers: false, printText: true })], [['lN', 'ext'], undefined], [['lNf', 'ile'], undefined], [['la', 'st'], undefined], [['lab', 'ove'], undefined], [['lad', 'dexpr'], undefined], [['laddb', 'uffer'], undefined], [['laddf', 'ile'], undefined], [['laf', 'ter'], undefined], [['lan', 'guage'], undefined], [['lat', 'er'], undefined], [['lb', 'uffer'], undefined], [['lbef', 'ore'], undefined], [['lbel', 'ow'], undefined], [['lbo', 'ttom'], undefined], [['lc', 'd'], undefined], [['lch', 'dir'], undefined], [['lcl', 'ose'], undefined], [['lcs', 'cope'], undefined], [['ld', 'o'], undefined], [['le', 'ft'], LeftCommand.argParser], [['lefta', 'bove'], undefined], [['let', ''], undefined], [['lex', 'pr'], undefined], [['lf', 'ile'], undefined], [['lfd', 'o'], undefined], [['lfir', 'st'], undefined], [['lg', 'etfile'], undefined], [['lgetb', 'uffer'], undefined], [['lgete', 'xpr'], undefined], [['lgr', 'ep'], undefined], [['lgrepa', 'dd'], undefined], [['lh', 'elpgrep'], undefined], [['lhi', 'story'], undefined], [['ll', ''], undefined], [['lla', 'st'], undefined], [['lli', 'st'], undefined], [['lm', 'ap'], undefined], [['lmak', 'e'], undefined], [['lmapc', 'lear'], undefined], [['ln', 'oremap'], undefined], [['lne', 'xt'], undefined], [['lnew', 'er'], undefined], [['lnf', 'ile'], undefined], [['lo', 'adview'], undefined], [['loadk', 'eymap'], undefined], [['loc', 'kmarks'], undefined], [['lockv', 'ar'], undefined], [['lol', 'der'], undefined], [['lope', 'n'], undefined], [['lp', 'revious'], undefined], [['lpf', 'ile'], undefined], [['lr', 'ewind'], undefined], [['ls', ''], undefined], [['lt', 'ag'], undefined], [['lu', 'nmap'], undefined], [['lua', ''], undefined], [['luad', 'o'], undefined], [['luaf', 'ile'], undefined], [['lv', 'imgrep'], undefined], [['lvimgrepa', 'dd'], undefined], [['lw', 'indow'], undefined], [['m', 'ove'], undefined], [['ma', 'rk'], undefined], [['mak', 'e'], undefined], [['map', ''], undefined], [['mapc', 'lear'], undefined], [['marks', ''], MarksCommand.argParser], [['mat', 'ch'], undefined], [['me', 'nu'], undefined], [['menut', 'ranslate'], undefined], [['mes', 'sages'], undefined], [['mk', 'exrc'], undefined], [['mks', 'ession'], undefined], [['mksp', 'ell'], undefined], [['mkv', 'imrc'], undefined], [['mkvie', 'w'], undefined], [['mod', 'e'], undefined], [['n', 'ext'], undefined], [['new', ''], FileCommand.argParsers.new], [['nm', 'ap'], undefined], [['nmapc', 'lear'], undefined], [['nme', 'nu'], undefined], [['nn', 'oremap'], undefined], [['nnoreme', 'nu'], undefined], [['no', 'remap'], undefined], [['noa', 'utocmd'], undefined], [['noh', 'lsearch'], succeed(new NohlCommand())], [['norea', 'bbrev'], undefined], [['noreme', 'nu'], undefined], [['norm', 'al'], undefined], [['nos', 'wapfile'], undefined], [['nu', 'mber'], PrintCommand.argParser({ printNumbers: true, printText: true })], [['nun', 'map'], undefined], [['nunme', 'nu'], undefined], [['ol', 'dfiles'], undefined], [['om', 'ap'], undefined], [['omapc', 'lear'], undefined], [['ome', 'nu'], undefined], [['on', 'ly'], succeed(new OnlyCommand())], [['ono', 'remap'], undefined], [['onoreme', 'nu'], undefined], [['opt', 'ions'], undefined], [['ou', 'nmap'], undefined], [['ounme', 'nu'], undefined], [['ow', 'nsyntax'], undefined], [['p', 'rint'], PrintCommand.argParser({ printNumbers: false, printText: true })], [['pa', 'ckadd'], undefined], [['packl', 'oadall'], undefined], [['pc', 'lose'], undefined], [['pe', 'rl'], undefined], [['ped', 'it'], undefined], [['perld', 'o'], undefined], [['perlf', 'ile'], undefined], [['po', 'p'], undefined], [['popu', 'p'], undefined], [['pp', 'op'], undefined], [['pre', 'serve'], undefined], [['prev', 'ious'], undefined], [['prof', 'ile'], undefined], [['profd', 'el'], undefined], [['ps', 'earch'], undefined], [['pt', 'ag'], undefined], [['ptN', 'ext'], undefined], [['ptf', 'irst'], undefined], [['ptj', 'ump'], undefined], [['ptl', 'ast'], undefined], [['ptn', 'ext'], undefined], [['ptp', 'revious'], undefined], [['ptr', 'ewind'], undefined], [['pts', 'elect'], undefined], [['pu', 't'], PutExCommand.argParser], [['pw', 'd'], undefined], [['py', 'thon'], undefined], [['py3', ''], undefined], [['py3d', 'o'], undefined], [['py3f', 'ile'], undefined], [['pyd', 'o'], undefined], [['pyf', 'ile'], undefined], [['python3', ''], undefined], [['pythonx', ''], undefined], [['pyx', ''], undefined], [['pyxd', 'o'], undefined], [['pyxf', 'ile'], undefined], [['q', 'uit'], QuitCommand.argParser(false)], [['qa', 'll'], QuitCommand.argParser(true)], [['quita', 'll'], QuitCommand.argParser(true)], [['r', 'ead'], ReadCommand.argParser], [['rec', 'over'], undefined], [['red', 'o'], undefined], [['redi', 'r'], undefined], [['redr', 'aw'], undefined], [['redraws', 'tatus'], undefined], [['redrawt', 'abline'], undefined], [['reg', 'isters'], RegisterCommand.argParser], [['res', 'ize'], undefined], [['ret', 'ab'], undefined], [['retu', 'rn'], undefined], [['rew', 'ind'], undefined], [['ri', 'ght'], RightCommand.argParser], [['rightb', 'elow'], undefined], [['rsh', 'ada'], undefined], [['ru', 'ntime'], undefined], [['rub', 'y'], undefined], [['rubyd', 'o'], undefined], [['rubyf', 'ile'], undefined], [['rund', 'o'], undefined], [['s', 'ubstitute'], SubstituteCommand.argParser], [['sN', 'ext'], undefined], [['sa', 'rgument'], undefined], [['sal', 'l'], undefined], [['san', 'dbox'], undefined], [['sav', 'eas'], undefined], [['sb', 'uffer'], undefined], [['sbN', 'ext'], undefined], [['sba', 'll'], undefined], [['sbf', 'irst'], undefined], [['sbl', 'ast'], undefined], [['sbm', 'odified'], undefined], [['sbn', 'ext'], undefined], [['sbp', 'revious'], undefined], [['sbr', 'ewind'], undefined], [['scr', 'iptnames'], undefined], [['scripte', 'ncoding'], undefined], [['scs', 'cope'], undefined], [['se', 't'], SetOptionsCommand.argParser], [['setf', 'iletype'], undefined], [['setg', 'lobal'], undefined], [['setl', 'ocal'], undefined], [['sf', 'ind'], undefined], [['sfir', 'st'], undefined], [['sh', 'ell'], succeed(new ShCommand())], // Taken from Vim; not in nvim [['sig', 'n'], undefined], [['sil', 'ent'], undefined], [['sl', 'eep'], undefined], [['sla', 'st'], undefined], [['sm', 'agic'], undefined], [['smap', ''], undefined], [['smapc', 'lear'], undefined], [['sme', 'nu'], undefined], [['smile', ''], succeed(new SmileCommand())], // Taken from Vim; not in nvim [['sn', 'ext'], undefined], [['sno', 'magic'], undefined], [['snor', 'emap'], undefined], [['snoreme', 'nu'], undefined], [['so', 'urce'], undefined], [['sor', 't'], SortCommand.argParser], [['sp', 'lit'], FileCommand.argParsers.split], [['spe', 'llgood'], undefined], [['spelld', 'ump'], undefined], [['spelli', 'nfo'], undefined], [['spellr', 'epall'], undefined], [['spellra', 're'], undefined], [['spellu', 'ndo'], undefined], [['spellw', 'rong'], undefined], [['spr', 'evious'], undefined], [['sre', 'wind'], undefined], [['st', 'op'], undefined], [['sta', 'g'], undefined], [['star', 'tinsert'], undefined], [['startg', 'replace'], undefined], [['startr', 'eplace'], undefined], [['stj', 'ump'], undefined], [['stopi', 'nsert'], undefined], [['sts', 'elect'], undefined], [['sun', 'hide'], undefined], [['sunm', 'ap'], undefined], [['sunme', 'nu'], undefined], [['sus', 'pend'], undefined], [['sv', 'iew'], undefined], [['sw', 'apname'], undefined], [['sy', 'ntax'], undefined], [['sync', 'bind'], undefined], [['synti', 'me'], undefined], [['t', ''], CopyCommand.argParser], [['tN', 'ext'], undefined], [['ta', 'g'], undefined], [['tab', ''], undefined], [['tabN', 'ext'], TabCommand.argParsers.bprev], [['tabc', 'lose'], TabCommand.argParsers.tabclose], [['tabdo', ''], undefined], [['tabe', 'dit'], TabCommand.argParsers.tabnew], [['tabf', 'ind'], undefined], [['tabfir', 'st'], TabCommand.argParsers.bfirst], [['tabl', 'ast'], TabCommand.argParsers.blast], [['tabm', 'ove'], TabCommand.argParsers.tabmove], [['tabn', 'ext'], TabCommand.argParsers.bnext], [['tabnew', ''], TabCommand.argParsers.tabnew], [['tabo', 'nly'], TabCommand.argParsers.tabonly], [['tabp', 'revious'], TabCommand.argParsers.bprev], [['tabr', 'ewind'], undefined], [['tabs', ''], undefined], [['tags', ''], undefined], [['tc', 'd'], undefined], [['tch', 'dir'], undefined], [['te', 'rminal'], TerminalCommand.argParser], [['tf', 'irst'], undefined], [['th', 'row'], undefined], [['tj', 'ump'], undefined], [['tl', 'ast'], undefined], [['tm', 'enu'], undefined], [['tma', 'p'], undefined], [['tmapc', 'lear'], undefined], [['tn', 'ext'], undefined], [['tno', 'remap'], undefined], [['to', 'pleft'], undefined], [['tp', 'revious'], undefined], [['tr', 'ewind'], undefined], [['try', ''], undefined], [['ts', 'elect'], undefined], [['tu', 'nmenu'], undefined], [['tunma', 'p'], undefined], [['u', 'ndo'], UndoCommand.argParser], [['una', 'bbreviate'], undefined], [['undoj', 'oin'], undefined], [['undol', 'ist'], undefined], [['unh', 'ide'], undefined], [['unl', 'et'], undefined], [['unlo', 'ckvar'], undefined], [['unm', 'ap'], undefined], [['unme', 'nu'], undefined], [['uns', 'ilent'], undefined], [['up', 'date'], WriteCommand.argParser], [['v', 'global'], undefined], [['ve', 'rsion'], undefined], [['verb', 'ose'], undefined], [['vert', 'ical'], undefined], [['vi', 'sual'], undefined], [['vie', 'w'], undefined], [['vim', 'grep'], undefined], [['vimgrepa', 'dd'], undefined], [['viu', 'sage'], undefined], [['vm', 'ap'], undefined], [['vmapc', 'lear'], undefined], [['vme', 'nu'], undefined], [['vn', 'oremap'], undefined], [['vne', 'w'], FileCommand.argParsers.vnew], [['vnoreme', 'nu'], undefined], [['vs', 'plit'], FileCommand.argParsers.vsplit], [['vsc', 'ode'], VsCodeCommand.argParser], // Special: run VS Code command [['vu', 'nmap'], undefined], [['vunme', 'nu'], undefined], [['w', 'rite'], WriteCommand.argParser], [['wN', 'ext'], undefined], [['wa', 'll'], WallCommand.argParser], [['wh', 'ile'], undefined], [['wi', 'nsize'], undefined], [['winc', 'md'], undefined], [['windo', ''], undefined], [['winp', 'os'], undefined], [['wn', 'ext'], undefined], [['wp', 'revious'], undefined], [['wq', ''], WriteQuitCommand.argParser], [['wqa', 'll'], WriteQuitAllCommand.argParser], [['wsh', 'ada'], undefined], [['wu', 'ndo'], undefined], [['x', 'it'], WriteQuitCommand.argParser], [['xa', 'll'], WriteQuitAllCommand.argParser], [['xm', 'ap'], undefined], [['xmapc', 'lear'], undefined], [['xme', 'nu'], undefined], [['xn', 'oremap'], undefined], [['xnoreme', 'nu'], undefined], [['xu', 'nmap'], undefined], [['xunme', 'nu'], undefined], [['y', 'ank'], YankCommand.argParser], [['z', ''], undefined], [['~', ''], undefined], ]; class UnimplementedCommand extends ExCommand { name: string; public override neovimCapable(): boolean { // If the user has neovim integration enabled, don't stop them from using these commands return true; } constructor(name: string) { super(); this.name = name; } async execute(vimState: VimState): Promise<void> { StatusBar.setText( vimState, `Command :${this.name} is not yet implemented (PRs are welcome!)`, true ); } override async executeWithRange(vimState: VimState, range: LineRange): Promise<void> { await this.execute(vimState); } } function nameParser( name: [string, string], argParser: ArgParser | undefined ): Parser<Parser<ExCommand>> { argParser ??= succeed(new UnimplementedCommand(name[1] ? `${name[0]}[${name[1]}]` : name[0])); const fullName = name[0] + name[1]; const p = nameAbbrevParser(name[0], name[1]).result(argParser); return fullName === '' || /[a-z]$/i.test(fullName) ? p.notFollowedBy(regexp(/[a-z]/i)) : p; } export const commandNameParser: Parser<Parser<ExCommand> | undefined> = alt( ...[...builtinExCommands] .reverse() .map(([name, argParser]) => nameParser(name, argParser?.skip(optWhitespace))) ); export const exCommandParser: Parser<{ lineRange: LineRange | undefined; command: ExCommand }> = optWhitespace .then(string(':').skip(optWhitespace).many()) .then( seq( LineRange.parser.fallback(undefined), optWhitespace, commandNameParser.fallback(undefined), all ) ) .map(([lineRange, whitespace, parseArgs, args]) => { if (parseArgs === undefined) { throw VimError.fromCode( ErrorCode.NotAnEditorCommand, `${lineRange?.toString() ?? ''}${whitespace}${args}` ); } const result = seq(parseArgs, optWhitespace.then(all)).parse(args); if (result.status === false || result.value[1]) { // TODO: All possible parsing errors are lumped into "trailing characters", which is wrong // TODO: Implement `:help :bar` // TODO: Implement `:help :comment` throw VimError.fromCode(ErrorCode.TrailingCharacters); } return { lineRange, command: result.value[0] }; });
the_stack
declare class Secret { /** * Converts a Latin-1 string to a Secret object. * @param {string} str Latin-1 string. * @returns {Secret} Secret object. */ static fromLatin1(str: string): Secret; /** * Converts an UTF-8 string to a Secret object. * @param {string} str UTF-8 string. * @returns {Secret} Secret object. */ static fromUTF8(str: string): Secret; /** * Converts a base32 string to a Secret object. * @param {string} str Base32 string. * @returns {Secret} Secret object. */ static fromBase32(str: string): Secret; /** * Converts a hexadecimal string to a Secret object. * @param {string} str Hexadecimal string. * @returns {Secret} Secret object. */ static fromHex(str: string): Secret; /** * Creates a secret key object. * @param {Object} [config] Configuration options. * @param {ArrayBuffer} [config.buffer=randomBytes] Secret key. * @param {number} [config.size=20] Number of random bytes to generate, ignored if 'buffer' is provided. */ constructor({ buffer, size }?: { buffer?: ArrayBuffer | undefined; size?: number | undefined; } | undefined); /** * Secret key. * @type {ArrayBuffer} */ buffer: ArrayBuffer; /** * Latin-1 string representation of secret key. * @type {string} */ get latin1(): string; /** * UTF-8 string representation of secret key. * @type {string} */ get utf8(): string; /** * Base32 string representation of secret key. * @type {string} */ get base32(): string; /** * Hexadecimal string representation of secret key. * @type {string} */ get hex(): string; } /** * HOTP: An HMAC-based One-time Password Algorithm. * {@link https://tools.ietf.org/html/rfc4226|RFC 4226} */ declare class HOTP { /** * Default configuration. * @type {{ * issuer: string, * label: string, * algorithm: string, * digits: number, * counter: number * window: number * }} */ static get defaults(): { issuer: string; label: string; algorithm: string; digits: number; counter: number; window: number; }; /** * Generates an HOTP token. * @param {Object} config Configuration options. * @param {Secret} config.secret Secret key. * @param {string} [config.algorithm='SHA1'] HMAC hashing algorithm. * @param {number} [config.digits=6] Token length. * @param {number} [config.counter=0] Counter value. * @returns {string} Token. */ static generate({ secret, algorithm, digits, counter, }: { secret: Secret; algorithm?: string | undefined; digits?: number | undefined; counter?: number | undefined; }): string; /** * Validates an HOTP token. * @param {Object} config Configuration options. * @param {string} config.token Token value. * @param {Secret} config.secret Secret key. * @param {string} [config.algorithm='SHA1'] HMAC hashing algorithm. * @param {number} config.digits Token length. * @param {number} [config.counter=0] Counter value. * @param {number} [config.window=1] Window of counter values to test. * @returns {number|null} Token delta, or null if the token is not found. */ static validate({ token, secret, algorithm, digits, counter, window, }: { token: string; secret: Secret; algorithm?: string | undefined; digits: number; counter?: number | undefined; window?: number | undefined; }): number | null; /** * Creates an HOTP object. * @param {Object} [config] Configuration options. * @param {string} [config.issuer=''] Account provider. * @param {string} [config.label='OTPAuth'] Account label. * @param {Secret|string} [config.secret=Secret] Secret key. * @param {string} [config.algorithm='SHA1'] HMAC hashing algorithm. * @param {number} [config.digits=6] Token length. * @param {number} [config.counter=0] Initial counter value. */ constructor({ issuer, label, secret, algorithm, digits, counter, }?: { issuer?: string | undefined; label?: string | undefined; secret?: string | Secret | undefined; algorithm?: string | undefined; digits?: number | undefined; counter?: number | undefined; } | undefined); /** * Account provider. * @type {string} */ issuer: string; /** * Account label. * @type {string} */ label: string; /** * Secret key. * @type {Secret} */ secret: Secret; /** * HMAC hashing algorithm. * @type {string} */ algorithm: string; /** * Token length. * @type {number} */ digits: number; /** * Initial counter value. * @type {number} */ counter: number; /** * Generates an HOTP token. * @param {Object} [config] Configuration options. * @param {number} [config.counter=this.counter++] Counter value. * @returns {string} Token. */ generate({ counter }?: { counter?: number | undefined; } | undefined): string; /** * Validates an HOTP token. * @param {Object} config Configuration options. * @param {string} config.token Token value. * @param {number} [config.counter=this.counter] Counter value. * @param {number} [config.window=1] Window of counter values to test. * @returns {number|null} Token delta, or null if the token is not found. */ validate({ token, counter, window }: { token: string; counter?: number | undefined; window?: number | undefined; }): number | null; /** * Returns a Google Authenticator key URI. * @returns {string} URI. */ toString(): string; } /** * TOTP: Time-Based One-Time Password Algorithm. * {@link https://tools.ietf.org/html/rfc6238|RFC 6238} */ declare class TOTP { /** * Default configuration. * @type {{ * issuer: string, * label: string, * algorithm: string, * digits: number, * period: number * window: number * }} */ static get defaults(): { issuer: string; label: string; algorithm: string; digits: number; period: number; window: number; }; /** * Generates a TOTP token. * @param {Object} config Configuration options. * @param {Secret} config.secret Secret key. * @param {string} [config.algorithm='SHA1'] HMAC hashing algorithm. * @param {number} [config.digits=6] Token length. * @param {number} [config.period=30] Token time-step duration. * @param {number} [config.timestamp=Date.now] Timestamp value in milliseconds. * @returns {string} Token. */ static generate({ secret, algorithm, digits, period, timestamp, }: { secret: Secret; algorithm?: string | undefined; digits?: number | undefined; period?: number | undefined; timestamp?: number | undefined; }): string; /** * Validates a TOTP token. * @param {Object} config Configuration options. * @param {string} config.token Token value. * @param {Secret} config.secret Secret key. * @param {string} [config.algorithm='SHA1'] HMAC hashing algorithm. * @param {number} config.digits Token length. * @param {number} [config.period=30] Token time-step duration. * @param {number} [config.timestamp=Date.now] Timestamp value in milliseconds. * @param {number} [config.window=1] Window of counter values to test. * @returns {number|null} Token delta, or null if the token is not found. */ static validate({ token, secret, algorithm, digits, period, timestamp, window, }: { token: string; secret: Secret; algorithm?: string | undefined; digits: number; period?: number | undefined; timestamp?: number | undefined; window?: number | undefined; }): number | null; /** * Creates a TOTP object. * @param {Object} [config] Configuration options. * @param {string} [config.issuer=''] Account provider. * @param {string} [config.label='OTPAuth'] Account label. * @param {Secret|string} [config.secret=Secret] Secret key. * @param {string} [config.algorithm='SHA1'] HMAC hashing algorithm. * @param {number} [config.digits=6] Token length. * @param {number} [config.period=30] Token time-step duration. */ constructor({ issuer, label, secret, algorithm, digits, period, }?: { issuer?: string | undefined; label?: string | undefined; secret?: string | Secret | undefined; algorithm?: string | undefined; digits?: number | undefined; period?: number | undefined; } | undefined); /** * Account provider. * @type {string} */ issuer: string; /** * Account label. * @type {string} */ label: string; /** * Secret key. * @type {Secret} */ secret: Secret; /** * HMAC hashing algorithm. * @type {string} */ algorithm: string; /** * Token length. * @type {number} */ digits: number; /** * Token time-step duration. * @type {number} */ period: number; /** * Generates a TOTP token. * @param {Object} [config] Configuration options. * @param {number} [config.timestamp=Date.now] Timestamp value in milliseconds. * @returns {string} Token. */ generate({ timestamp }?: { timestamp?: number | undefined; } | undefined): string; /** * Validates a TOTP token. * @param {Object} config Configuration options. * @param {string} config.token Token value. * @param {number} [config.timestamp=Date.now] Timestamp value in milliseconds. * @param {number} [config.window=1] Window of counter values to test. * @returns {number|null} Token delta, or null if the token is not found. */ validate({ token, timestamp, window }: { token: string; timestamp?: number | undefined; window?: number | undefined; }): number | null; /** * Returns a Google Authenticator key URI. * @returns {string} URI. */ toString(): string; } /** * HOTP/TOTP object/string conversion. * {@link https://github.com/google/google-authenticator/wiki/Key-Uri-Format|Key URI Format} */ declare class URI { /** * Parses a Google Authenticator key URI and returns an HOTP/TOTP object. * @param {string} uri Google Authenticator Key URI. * @returns {HOTP|TOTP} HOTP/TOTP object. */ static parse(uri: string): HOTP | TOTP; /** * Converts an HOTP/TOTP object to a Google Authenticator key URI. * @param {HOTP|TOTP} otp HOTP/TOTP object. * @returns {string} Google Authenticator Key URI. */ static stringify(otp: HOTP | TOTP): string; } /** * Library version. * @type {string} */ declare const version: string; export { HOTP, Secret, TOTP, URI, version };
the_stack
namespace annie { /** * Stage 表示显示 canvas 内容的整个区域,所有显示对象的顶级显示容器 * @class annie.Stage * @extends annie.Sprite * @public * @since 1.0.0 */ export class Stage extends Sprite { /** * annie.Stage舞台初始化完成后会触发的事件 * @event annie.Event.ON_INIT_STAGE * @since 1.0.0 */ /** * annie引擎暂停或者恢复暂停时触发,这个事件只能在annie.globalDispatcher中监听 * @event annie.Event.ON_RUN_CHANGED * @since 1.0.0 */ /** * annie.Stage 的多点触碰事件。这个事件只能在annie.Stage对象上侦听 * @event annie.TouchEvent.ON_MULTI_TOUCH * @type {string} */ /** * 当前stage所使用的渲染器 * 渲染器有两种,一种是canvas 一种是webGl * @property renderObj * @public * @since 1.0.0 * @type {IRender} * @default null */ public renderObj: IRender = null; /** * 渲染模式值 只读 CANVAS:0, webGl: 1 * @property renderType * @readonly * @public * @since 1.0.0 * @type {number} * @default 0 * @readonly */ public renderType = 0; /** * 是否暂停 * @property pause * @static * @type {boolean} * @public * @since 1.0.0 * @default false */ static get pause(): boolean { return Stage._pause; } static set pause(value: boolean) { let s: any = Stage; if (value != s._pause) { s._pause = value; if (value) { //停止声音 Sound.stopAllSounds(); } else { //恢复声音 Sound.resumePlaySounds(); } //触发事件 globalDispatcher.dispatchEvent("onRunChanged", {pause: value}); } } private static _pause: boolean = false; private static stage: Stage = null; private _viewRect: Rectangle = new Rectangle(); /** * 开启或关闭多点手势事件 目前仅支持两点 旋转 缩放 * @property isMultiTouch * @since 1.0.3 * @type {boolean} */ public isMultiTouch: boolean = false; /** * 开启或关闭多个手指的鼠标事件 * @property isMultiMouse * @since 1.1.3 * @type {boolean} */ public isMultiMouse: boolean = false; /** * <h4><font color="red">小游戏不支持 小程序不支持</font></h4> * 当设备尺寸更新,或者旋转后是否自动更新舞台方向 * 默认不开启 * @property autoSteering * @public * @since 1.0.0 * @type {boolean} * @default false */ public autoSteering: boolean = false; /** * <h4><font color="red">小游戏不支持 小程序不支持</font></h4> * 当设备尺寸更新,或者旋转后是否自动更新舞台尺寸 * 默认不开启 * @property autoResize * @public * @since 1.0.0 * @type {boolean} * @default false */ public autoResize: boolean = false; /** * 舞台的尺寸宽,也就是我们常说的设计尺寸 * @property desWidth * @public * @since 1.0.0 * @default 320 * @type {number} * @readonly */ public desWidth: number = 0; /** * 舞台的尺寸高,也就是我们常说的设计尺寸 * @property desHeight * @public * @since 1.0.0 * @default 240 * @type {number} * @readonly */ public desHeight: number = 0; /** * 舞台在当前设备中的真实高 * @property divHeight * @public * @since 1.0.0 * @default 320 * @type {number} * @readonly */ public divHeight: number = 0; /** * 舞台在当前设备中的真实宽 * @property divWidth * @public * @since 1.0.0 * @default 240 * @readonly * @type {number} */ public divWidth: number = 0; /** * 舞台的背景色 * 默认为""就是透明背景 * 可能设置一个颜色值改变舞台背景 * @property bgColor * @public * @since 1.0.0 * @type {string} #FFFFFF" 或 RGB(255,255,255) 或 RGBA(255,255,255,255) */ public bgColor: string = ""; /** * 舞台的缩放模式 * 默认为空就是无缩放的真实大小 * "noBorder" 无边框模式 * ”showAll" 显示所有内容 * “fixedWidth" 固定宽 * ”fixedHeight" 固定高 * @property scaleMode * @public * @since 1.0.0 * @default "onScale" * @type {string} * @example * //动态更改stage的对齐方式示例 * //以下代码放到一个舞台的显示对象的构造函数中 * let s=this; * s.addEventListener(annie.Event.ADD_TO_STAGE,function(e){ * let i=0; * s.stage.addEventListener(annie.MouseEvent.CLICK,function(e){ * let aList=[annie.StageScaleMode.EXACT_FIT,annie.StageScaleMode.NO_BORDER,annie.StageScaleMode.NO_SCALE,annie.StageScaleMode.SHOW_ALL,annie.StageScaleMode.FIXED_WIDTH,annie.StageScaleMode.FIXED_HEIGHT] * let state=e.currentTarget; * state.scaleMode=aList[i]; * if(i>5){i=0;} * } * } * */ get scaleMode(): string { return this._scaleMode; } set scaleMode(value: string) { let s = this; if (value != s._scaleMode) { s._scaleMode = value; s.setAlign(); } } private _scaleMode: string = "onScale"; //原始为60的刷新速度时的计数器 public static _FPS: number = 30; private _lastDpList: any = {}; /** * 显示对象入口函数 * @method Stage * @param {Object} canvas * @param {number} desW 舞台宽 * @param {number} desH 舞台高 * @param {number} fps 刷新率 * @param {string} scaleMode 缩放模式 StageScaleMode * @param {number} renderType 渲染模式0:canvas 1:webGl 2:dom * @public * @since 1.0.0 */ public constructor(canvas: any, desW: number = 640, desH: number = 1040, frameRate: number = 30, scaleMode: string = "fixedHeight", renderType: number = 0) { super(); let s: any = this; s.a2x_ua = true; s.a2x_um = true; s._instanceType = "annie.Stage"; s.stage = s; s._isOnStage = true; s.name = "rootStage"; s.renderType = renderType; s.desWidth = desW; s.desHeight = desH; s.setFrameRate(frameRate); s._scaleMode = scaleMode; s.anchorX = desW >> 1; s.anchorY = desH >> 1; s.mouseEvent = s._onMouseEvent.bind(s); if (annie.isSharedCanvas) { annie.CanvasRender.rootContainer = annie.app.getSharedCanvas(); annie.globalDispatcher.addEventListener("onMainStageMsg", function (e: any) { switch (e.data.type) { case annie.MouseEvent.CLICK: case annie.MouseEvent.MOUSE_MOVE: case annie.MouseEvent.MOUSE_UP: case annie.MouseEvent.MOUSE_DOWN: case annie.MouseEvent.MOUSE_OVER: case annie.MouseEvent.MOUSE_OUT: let event: MouseEvent = new MouseEvent(e.data.type); event.reset(e.data.type, s); event.clientX = event.stageX = event.localX = e.data.x; event.clientY = event.stageY = event.localY = e.data.y; s.dispatchEvent(event); break; default: } }); } else { let sysInfo = annie.app.getSystemInfoSync(); let canvas=annie.app.createCanvas(); canvas.width=sysInfo.windowWidth*sysInfo.pixelRatio; canvas.height=sysInfo.windowHeight*sysInfo.pixelRatio; annie.CanvasRender.rootContainer= canvas; annie.app.onTouchStart(function (e: any) { if(e.type==undefined){ e.type="touchstart"; } s.mouseEvent(e); }); annie.app.onTouchMove(function (e: any) { if(e.type==undefined){ e.type="touchmove"; } s.mouseEvent(e); }); annie.app.onTouchEnd(function (e: any) { if(e.type==undefined){ e.type="touchend"; } s.mouseEvent(e); }); // annie.app.onTouchCancel(function (e: any) { // if(e.type==undefined){ // e.type="touchcancel"; // } // s.mouseEvent(e); // }); } annie.OffCanvasRender.rootContainer= annie.app.createCanvas(); //webgl 直到对2d的支持非常成熟了再考虑开启 if (renderType == 0) { //canvas s.renderObj = new CanvasRender(s); } else { //webgl //s.renderObj = new WebGLRender(s); } s.renderObj.init(); //同时添加到主更新循环中 Stage.addUpdateObj(s); Stage.stage = s; //这里需要做个延时,方便init事件捕捉 setTimeout(() => { Stage.flushAll(); }, 0); } private _touchEvent: annie.TouchEvent; public _render(renderObj: IRender): void { renderObj.begin(this.bgColor); super._render(renderObj); renderObj.end(); } //这个是鼠标事件的MouseEvent对象池,因为如果用户有监听鼠标事件,如果不建立对象池,那每一秒将会new Fps个数的事件对象,影响性能 private _ml: any = []; //这个是事件中用到的Point对象池,以提高性能 private _mp: any = []; //刷新mouse或者touch事件 private _initMouseEvent(event: any, cp: Point, sp: Point, identifier: number, timeStamp: number): void { event._pd = false; event.clientX = cp.x; event.clientY = cp.y; event.stageX = sp.x; event.stageY = sp.y; event.timeStamp = timeStamp; event.identifier = identifier; } // 鼠标按下事件的对象池 private _mouseDownPoint: any = {}; //循环刷新页面的函数 private flush(): void { let s = this; //看看是否有resize s.resize(); s._onUpdateFrame(1); s._updateMatrix(); s._render(s.renderObj); } /** * 引擎的刷新率,就是一秒中执行多少次刷新 * @method setFrameRate * @param {number} fps 最好是60的倍数如 1 2 3 6 10 12 15 20 30 60 * @since 1.0.0 * @public * @return {void} */ public setFrameRate(fps: number): void { Stage._FPS=fps; Stage._flushTime=1000/fps; } /** * 引擎的刷新率,就是一秒中执行多少次刷新 * @method getFrameRate * @since 1.0.0 * @public * @return {number} */ public getFrameRate(): number { return Stage._FPS; } //html的鼠标或单点触摸对应的引擎事件类型名 private _mouseEventTypes: any = { mousedown: "onMouseDown", mouseup: "onMouseUp", mousemove: "onMouseMove", touchstart: "onMouseDown", touchmove: "onMouseMove", touchend: "onMouseUp", ontouchstart: "onMouseDown", ontouchmove: "onMouseMove", ontouchend: "onMouseUp" }; //stageMousePoint private sp: Point = new annie.Point(); //localPoint; private lp: Point = new annie.Point(); private muliPoints: Array<any> = []; //当document有鼠标或触摸事件时调用 private _mP1: Point = new Point(); //当document有鼠标或触摸事件时调用 private _mP2: Point = new Point(); public static _dragDisplay: annie.DisplayObject = null; public static _dragBounds: annie.Rectangle = new annie.Rectangle(); public static _lastDragPoint: annie.Point = new annie.Point(); public static _isDragCenter: boolean = false; private _onMouseEvent(e: any): void { //检查是否有 let s: any = this, offSetX = 0, offSetY = 0; let sd: any = Stage._dragDisplay; if (s.isMultiTouch && e.changedTouches.length > 1) { if (e.changedTouches.length == 2) { //求角度和距离 s._mP1.x = e.changedTouches[0].clientX - offSetX; s._mP1.y = e.changedTouches[0].clientY - offSetY; s._mP2.x = e.changedTouches[1].clientX - offSetX; s._mP2.y = e.changedTouches[1].clientY - offSetY; let angle = Math.atan2(s._mP1.y - s._mP2.y, s._mP1.x - s._mP2.x) / Math.PI * 180; let dis = annie.Point.distance(s._mP1, s._mP2); s.muliPoints.push({p1: s._mP1, p2: s._mP2, angle: angle, dis: dis}); if (s.muliPoints.length >= 2) { //如果有事件,抛事件 if (!(s._touchEvent instanceof annie.TouchEvent)) { s._touchEvent = new annie.TouchEvent(annie.TouchEvent.ON_MULTI_TOUCH); s._touchEvent.target = s; } let len = s.muliPoints.length; s._touchEvent.rotate = (s.muliPoints[len - 1].angle - s.muliPoints[len - 2].angle) * 2; s._touchEvent.scale = (s.muliPoints[len - 1].dis - s.muliPoints[len - 2].dis) / (s.divHeight > s.divWidth ? s.desWidth : s.desHeight) * 4; s._touchEvent.clientPoint1.x = s.muliPoints[len - 1].p1.x * annie.devicePixelRatio; s._touchEvent.clientPoint2.x = s.muliPoints[len - 1].p2.x * annie.devicePixelRatio; s._touchEvent.clientPoint1.y = s.muliPoints[len - 1].p1.y * annie.devicePixelRatio; s._touchEvent.clientPoint2.y = s.muliPoints[len - 1].p2.y * annie.devicePixelRatio; s.dispatchEvent(s._touchEvent); s.muliPoints.shift(); } } else { s.muliPoints.length = 0; } s._mouseDownPoint = {}; s._lastDpList = {}; if (sd) { Stage._lastDragPoint.x = Number.MAX_VALUE; Stage._lastDragPoint.y = Number.MAX_VALUE; } } else { if (s.muliPoints.length > 0) { s._touchEvent.rotate = 0; s._touchEvent.scale = 0; s._touchEvent.clientPoint1.x = 0; s._touchEvent.clientPoint2.x = 0; s._touchEvent.clientPoint1.y = 0; s._touchEvent.clientPoint2.y = 0; s.dispatchEvent(s._touchEvent); s.muliPoints.length = 0; } //检查mouse或touch事件是否有,如果有的话,就触发事件函数 if (EventDispatcher._totalMEC > 0) { let points: any; let item = s._mouseEventTypes[e.type]; let events: any = []; let event: any; //clientPoint let cp: Point; //事件个数 let eLen: number; let identifier: any; if (s.isMultiMouse) { points = e.changedTouches; } else { let fp = e.changedTouches[0]; if ((s._lastDpList[fp.identifier] != void 0) || (item == "onMouseDown" && !s._lastDpList.isStart)) { s._lastDpList.isStart = true; points = [fp]; } else { return; } } let pLen = points.length; for (let o = 0; o < pLen; o++) { eLen = 0; events.length = 0; identifier = points[o].identifier; if (s._mp.length > 0) { cp = s._mp.shift(); } else { cp = new Point(); } cp.x = (points[o].clientX - offSetX) * devicePixelRatio; cp.y = (points[o].clientY - offSetY) * devicePixelRatio; s.globalToLocal(cp, s.sp); if (sd && sd.stage && sd.parent) { let x1 = sd.x, y1 = sd.y; sd.parent.globalToLocal(cp, s.lp); if (!Stage._isDragCenter) { if (Stage._lastDragPoint.x != Number.MAX_VALUE) { x1 += s.lp.x - Stage._lastDragPoint.x; y1 += s.lp.y - Stage._lastDragPoint.y; } Stage._lastDragPoint.x = s.lp.x; Stage._lastDragPoint.y = s.lp.y; } else { x1 = s.lp.x; y1 = s.lp.y; } s.lp.x = x1; s.lp.y = y1; if (Stage._dragBounds.width != Number.MIN_VALUE) { if (x1 < Stage._dragBounds.x) { x1 = Stage._dragBounds.x; } else if (x1 > Stage._dragBounds.x + Stage._dragBounds.width) { x1 = Stage._dragBounds.x + Stage._dragBounds.width; } if (y1 < Stage._dragBounds.y) { y1 = Stage._dragBounds.y; } else if (y1 > Stage._dragBounds.y + Stage._dragBounds.height) { y1 = Stage._dragBounds.y + Stage._dragBounds.height; } } sd.x = x1; sd.y = y1; } if (s._ml[eLen] instanceof annie.MouseEvent) { event = s._ml[eLen]; event.type = item; } else { event = new MouseEvent(item); s._ml[eLen] = event; } events[events.length] = event; s._initMouseEvent(event, cp, s.sp, identifier, e.timeStamp); eLen++; if (item == "onMouseDown") { s._mouseDownPoint[identifier] = cp; //清空上次存在的显示列表 } else if (item == "onMouseUp") { if (s._mouseDownPoint[identifier] instanceof annie.Point) { if (annie.Point.distance(s._mouseDownPoint[identifier], cp) < 20) { //click事件 //这个地方检查是所有显示对象列表里是否有添加对应的事件 if (EventDispatcher.getMouseEventCount("onMouseClick") > 0) { if (s._ml[eLen] instanceof annie.MouseEvent) { event = s._ml[eLen]; event.type = "onMouseClick"; } else { event = new MouseEvent("onMouseClick"); s._ml[eLen] = event; } events[events.length] = event; s._initMouseEvent(event, cp, s.sp, identifier); eLen++; } } } } if (eLen > 0) { //证明有事件那么就开始遍历显示列表。就算有多个事件也不怕,因为坐标点相同,所以只需要遍历一次 let d: any = s.hitTestPoint(cp, true); let displayList: Array<DisplayObject> = []; if (d instanceof annie.DisplayObject) { //证明有点击到事件,然后从最底层追上来,看看一路是否有人添加过mouse或touch事件,还要考虑mousechildren和阻止事件方法 //找出真正的target,因为有些父级可能会mouseChildren=false; do { if (d instanceof annie.Sprite && d.mouseChildren == false) { //丢掉之前的层级,因为根本没用了 displayList.length = 0; } displayList[displayList.length] = d; d = d.parent; } while (d instanceof annie.DisplayObject) } else { displayList[0] = s; } let len: number = displayList.length; for (let i = len - 1; i >= 0; i--) { d = displayList[i]; for (let j = 0; j < eLen; j++) { if (!events[j]._pd && d.hasEventListener(events[j].type)) { events[j].currentTarget = d; events[j].target = displayList[0]; d.globalToLocal(cp, s.lp); events[j].localX = s.lp.x; events[j].localY = s.lp.y; d.dispatchEvent(events[j]); } } } //这里一定要反转一下,因为会影响mouseOut mouseOver displayList.reverse(); for (let i = len - 1; i >= 0; i--) { d = displayList[i]; for (let j = 0; j < eLen; j++) { if (!events[j]._pd && d.hasEventListener(events[j].type, false)) { events[j].currentTarget = d; events[j].target = displayList[eLen - 1]; d.globalToLocal(cp, s.lp); events[j].localX = s.lp.x; events[j].localY = s.lp.y; d.dispatchEvent(events[j], null, false); } } } //最后要和上一次的遍历者对比下,如果不相同则要触发onMouseOver和onMouseOut if (item != "onMouseDown") { if (EventDispatcher.getMouseEventCount("onMouseOver") > 0 || EventDispatcher.getMouseEventCount("onMouseOut") > 0) { if (s._lastDpList[identifier] instanceof Array) { //从第二个开始,因为第一个对象始终是stage顶级对象 let len1 = s._lastDpList[identifier].length; let len2 = displayList.length; len = len1 > len2 ? len1 : len2; let isDiff = false; let overEvent: any; let outEvent: any; for (let i = 1; i < len; i++) { if (!isDiff) { if (s._lastDpList[identifier][i] != displayList[i]) { //好就是这里,需要确定哪些有onMouseOver,哪些有onMouseOut isDiff = true; if (s._ml[eLen] instanceof annie.MouseEvent) { overEvent = s._ml[eLen]; overEvent.type = "onMouseOver"; } else { overEvent = new MouseEvent("onMouseOver"); s._ml[eLen] = overEvent; } s._initMouseEvent(overEvent, cp, s.sp, identifier); eLen++; if (s._ml[eLen] instanceof annie.MouseEvent) { outEvent = s._ml[eLen]; outEvent.type = "onMouseOut"; } else { outEvent = new MouseEvent("onMouseOut"); s._ml[eLen] = outEvent; } s._initMouseEvent(outEvent, cp, s.sp, identifier); } } if (isDiff) { if (s._lastDpList[identifier][i]) { //触发onMouseOut事件 d = s._lastDpList[identifier][i]; if (!outEvent._pd && d.hasEventListener("onMouseOut")) { outEvent.currentTarget = d; outEvent.target = s._lastDpList[identifier][len1 - 1]; d.globalToLocal(cp, s.lp); outEvent.localX = s.lp.x; outEvent.localY = s.lp.y; d.dispatchEvent(outEvent); } } d = displayList[i]; if (d instanceof annie.DisplayObject) { //触发onMouseOver事件 if (!overEvent._pd && d.hasEventListener("onMouseOver")) { overEvent.currentTarget = d; overEvent.target = displayList[len2 - 1]; d.globalToLocal(cp, s.lp); overEvent.localX = s.lp.x; overEvent.localY = s.lp.y; d.dispatchEvent(overEvent); } } } } } } s._mp[s._mp.length] = cp; } if (item == "onMouseUp") { delete s._mouseDownPoint[identifier]; delete s._lastDpList[identifier]; s._lastDpList.isStart = false; if (sd) { Stage._lastDragPoint.x = Number.MAX_VALUE; Stage._lastDragPoint.y = Number.MAX_VALUE; } } else { s._lastDpList[identifier] = displayList; } } } } } }; //设置舞台的对齐模式 private setAlign(): void { let s = this; let divH = s.divHeight; let divW = s.divWidth; let desH = s.desHeight; let desW = s.desWidth; s.anchorX = desW >> 1; s.anchorY = desH >> 1; //设备是否为竖屏 let isDivH = divH >= divW; //内容是否为竖屏内容 let isDesH = desH >= desW; let scaleY = 1; let scaleX = 1; s.x = (divW - desW) >> 1; s.y = (divH - desH) >> 1; if (s.autoSteering) { if (isDesH != isDivH) { let d = divH; divH = divW; divW = d; } } if (s._scaleMode != "noScale") { scaleY = divH / desH; scaleX = divW / desW; switch (s._scaleMode) { case "noBorder": if (scaleX > scaleY) { scaleY = scaleX; } else { scaleX = scaleY; } break; case "showAll": if (scaleX < scaleY) { scaleY = scaleX; } else { scaleX = scaleY; } break; case "fixedWidth": scaleY = scaleX; break; case "fixedHeight": scaleX = scaleY; break; } } s.scaleX = scaleX; s.scaleY = scaleY; if (s.autoSteering) { if (isDesH == isDivH) { s.rotation = 0; } else { if (desH > desW) { s.rotation = -90; } else { s.rotation = 90; } } } else { s.rotation = 0; } s._viewRect.x = (desW - divW / scaleX) >> 1; s._viewRect.y = (desH - divH / scaleY) >> 1; s._viewRect.width = desW - s._viewRect.x * 2; s._viewRect.height = desH - s._viewRect.y * 2; }; /** * 当舞台尺寸发生改变时,如果stage autoResize 为 true,则此方法会自己调用; * 如果设置stage autoResize 为 false 你需要手动调用此方法以更新界面. * 不管autoResize 的状态是什么,你只要侦听 了stage 的 annie.Event.RESIZE 事件 * 都可以接收到舞台变化的通知。 * @method resize * @public * @since 1.0.0 * @return {void} */ public resize = function (): void { let s: Stage = this; let w = CanvasRender.rootContainer.width; let h = CanvasRender.rootContainer.height; if (s.divWidth == 0 || s.divHeight == 0) { s.a2x_um = true; s.divWidth = w; s.divHeight = h; s.renderObj.reSize(w, h); s.setAlign(); s.dispatchEvent("onInitStage"); } else if (s.autoResize) { if (s.divWidth != w || s.divHeight != h) { s.a2x_um = true; s.divHeight = h; s.divWidth = w; s.renderObj.reSize(w, h); s.setAlign(); s.dispatchEvent("onResize"); } } }; /** * 舞台在设备里截取后的可见区域,有些时候知道可见区域是非常重要的,因为这样你就可以根据舞台的可见区域做自适应了。 * @property viewRect * @public * @readonly * @since 1.0.0 * @type {annie.Rectangle} * @default {x:0,y:0,width:0,height:0} * @readonly * @example * //始终让一个对象顶对齐,或者 */ public get viewRect(): Rectangle { return this._viewRect; } /** * 要循环调用 flush 函数对象列表 * @method allUpdateObjList * @static * @since 1.0.0 * @type {Array} */ private static allUpdateObjList: Array<any> = []; //刷新所有定时器 private static _flushTime:number=0; private static _lastFluashTime:number=0; private static flushAll(): void { let nowTime:number=new Date().getTime(); if(Stage._flushTime-nowTime+Stage._lastFluashTime<Stage._flushTime*0.1){ Stage._lastFluashTime=nowTime; if (!Stage._pause) { let len = Stage.allUpdateObjList.length; for (let i = len - 1; i >= 0; i--) { Stage.allUpdateObjList[i] && Stage.allUpdateObjList[i].flush(); } } } requestAnimationFrame(Stage.flushAll); } /** * 添加一个刷新对象,这个对象里一定要有一个 flush 函数。 * 因为一但添加,这个对象的 flush 函数会以stage的fps间隔调用 * 如,你的stage是30fps 那么你这个对象的 flush 函数1秒会调用30次。 * @method addUpdateObj * @param target 要循化调用 flush 函数的对象 * @public * @static * @since * @return {void} */ public static addUpdateObj(target: any): void { let isHave: boolean = false; let len = Stage.allUpdateObjList.length; for (let i = 0; i < len; i++) { if (Stage.allUpdateObjList[i] == target) { isHave = true; break; } } if (!isHave) { Stage.allUpdateObjList.unshift(target); } } /** * 移除掉已经添加的循环刷新对象 * @method removeUpdateObj * @param target * @public * @static * @since 1.0.0 * @return {void} */ public static removeUpdateObj(target: any): void { let len = Stage.allUpdateObjList.length; for (let i = 0; i < len; i++) { if (Stage.allUpdateObjList[i] == target) { Stage.allUpdateObjList.splice(i, 1); break; } } } public destroy(): void { super.destroy(); let s = this; Stage.removeUpdateObj(s); s.renderObj.destroy(); s.renderObj = null; } } }
the_stack
declare module "@math.gl/core/lib/assert" { export default function assert(condition: any, message: any): void; } declare module "@math.gl/core/lib/common" { const config: {}; export { config }; export function configure(options?: {}): {}; export function formatValue( value: any, { precision, }?: { precision?: any; } ): string; export function isArray(value: any): boolean; export function clone(array: any): any; export function toRadians(degrees: any): any; export function toDegrees(radians: any): any; export function radians(degrees: any, result: any): any; export function degrees(radians: any, result: any): any; export function sin(radians: any): any; export function cos(radians: any): any; export function tan(radians: any): any; export function asin(radians: any): any; export function acos(radians: any): any; export function atan(radians: any): any; export function clamp(value: any, min: any, max: any): any; export function lerp(a: any, b: any, t: any): any; export function equals(a: any, b: any, epsilon: any): any; export function exactEquals(a: any, b: any): any; export function withEpsilon(EPSILON: any, func: any): any; } declare module "@math.gl/core/classes/base/math-array" { export default class MathArray extends Array { clone(): any; from(arrayOrObject: any): any; fromArray(array: any, offset?: number): this; to(arrayOrObject: any): any; toTarget(target: any): any; toArray(array?: any[], offset?: number): any[]; toFloat32Array(): Float32Array; toString(): string; formatString(opts: any): string; equals(array: any): boolean; exactEquals(array: any): boolean; negate(): this; lerp(a: any, b: any, t: any): this; min(vector: any): this; max(vector: any): this; clamp(minVector: any, maxVector: any): this; add(...vectors: any[]): this; subtract(...vectors: any[]): this; scale(scale: any): any; sub(a: any): this; setScalar(a: any): this; addScalar(a: any): this; subScalar(a: any): this; multiplyScalar(scalar: any): this; divideScalar(a: any): any; clampScalar(min: any, max: any): this; multiplyByScalar(scalar: any): any; get elements(): this; check(): this; validate(): boolean; } } declare module "@math.gl/core/lib/validators" { export function validateVector(v: any, length: any): boolean; export function checkNumber(value: any): any; export function checkVector(v: any, length: any, callerName: any): any; export function deprecated(method: any, version: any): void; } declare module "@math.gl/core/classes/base/vector" { import MathArray from "@math.gl/core/classes/base/math-array"; export default class Vector extends MathArray { get x(): any; set x(value: any); get y(): any; set y(value: any); len(): number; magnitude(): number; lengthSquared(): number; magnitudeSquared(): number; distance(mathArray: any): number; distanceSquared(mathArray: any): any; dot(mathArray: any): any; normalize(): this; multiply(...vectors: any[]): this; divide(...vectors: any[]): this; lengthSq(): number; distanceTo(vector: any): number; distanceToSquared(vector: any): any; getComponent(i: any): any; setComponent(i: any, value: any): this; addVectors(a: any, b: any): any; subVectors(a: any, b: any): any; multiplyVectors(a: any, b: any): any; addScaledVector(a: any, b: any): this; } } declare module "@math.gl/core/lib/gl-matrix-extras" { export function vec2_transformMat4AsVector(out: any, a: any, m: any): any; export function vec3_transformMat4AsVector(out: any, a: any, m: any): any; export function vec3_transformMat2(out: any, a: any, m: any): any; export function vec4_transformMat2(out: any, a: any, m: any): any; export function vec4_transformMat3(out: any, a: any, m: any): any; } declare module "@math.gl/core/classes/vector2" { import Vector from "@math.gl/core/classes/base/vector"; export default class Vector2 extends Vector { constructor(x?: number, y?: number); set(x: any, y: any, z: any): this; copy(array: any): this; fromObject(object: any): this; toObject(object: any): any; get ELEMENTS(): number; horizontalAngle(): number; verticalAngle(): number; transform(matrix4: any): this; transformAsPoint(matrix4: any): this; transformAsVector(matrix4: any): this; transformByMatrix3(matrix3: any): this; transformByMatrix2x3(matrix2x3: any): this; transformByMatrix2(matrix2: any): this; } } declare module "@math.gl/core/classes/vector3" { import Vector from "@math.gl/core/classes/base/vector"; export default class Vector3 extends Vector { constructor(x?: number, y?: number, z?: number); set(x: any, y: any, z: any): this; copy(array: any): this; fromObject(object: any): this; toObject(object: any): any; get ELEMENTS(): number; get z(): any; set z(value: any); angle(vector: any): any; cross(vector: any): this; rotateX({ radians, origin }: { radians: any; origin?: number[] }): this; rotateY({ radians, origin }: { radians: any; origin?: number[] }): this; rotateZ({ radians, origin }: { radians: any; origin?: number[] }): this; transform(matrix4: any): this; transformAsPoint(matrix4: any): this; transformAsVector(matrix4: any): this; transformByMatrix3(matrix3: any): this; transformByMatrix2(matrix2: any): this; transformByQuaternion(quaternion: any): this; } } declare module "@math.gl/core/classes/vector4" { import Vector from "@math.gl/core/classes/base/vector"; export default class Vector4 extends Vector { constructor(x?: number, y?: number, z?: number, w?: number); set(x: any, y: any, z: any, w: any): this; copy(array: any): this; fromObject(object: any): this; toObject(object: any): any; get ELEMENTS(): number; get z(): any; set z(value: any); get w(): any; set w(value: any); transform(matrix4: any): this; transformByMatrix3(matrix3: any): this; transformByMatrix2(matrix2: any): this; transformByQuaternion(quaternion: any): this; applyMatrix4(m: any): this; } } declare module "@math.gl/core/classes/base/matrix" { import MathArray from "@math.gl/core/classes/base/math-array"; export default class Matrix extends MathArray { toString(): string; getElementIndex(row: any, col: any): any; getElement(row: any, col: any): any; setElement(row: any, col: any, value: any): this; getColumn(columnIndex: any, result?: any[]): any[]; setColumn(columnIndex: any, columnVector: any): this; } } declare module "@math.gl/core/classes/matrix3" { import Matrix from "@math.gl/core/classes/base/matrix"; export default class Matrix3 extends Matrix { static get IDENTITY(): any; static get ZERO(): any; get ELEMENTS(): number; get RANK(): number; get INDICES(): Readonly<{ COL0ROW0: number; COL0ROW1: number; COL0ROW2: number; COL1ROW0: number; COL1ROW1: number; COL1ROW2: number; COL2ROW0: number; COL2ROW1: number; COL2ROW2: number; }>; constructor(array: any); copy(array: any): this; set( m00: any, m10: any, m20: any, m01: any, m11: any, m21: any, m02: any, m12: any, m22: any ): this; setRowMajor( m00: any, m01: any, m02: any, m10: any, m11: any, m12: any, m20: any, m21: any, m22: any ): this; determinant(): any; identity(): this; fromQuaternion(q: any): this; transpose(): this; invert(): this; multiplyLeft(a: any): this; multiplyRight(a: any): this; rotate(radians: any): this; scale(factor: any): this; translate(vec: any): this; transform(vector: any, result: any): any; transformVector(vector: any, result: any): any; transformVector2(vector: any, result: any): any; transformVector3(vector: any, result: any): any; } } declare module "@math.gl/core/classes/matrix4" { import Matrix from "@math.gl/core/classes/base/matrix"; export default class Matrix4 extends Matrix { static get IDENTITY(): any; static get ZERO(): any; get INDICES(): Readonly<{ COL0ROW0: number; COL0ROW1: number; COL0ROW2: number; COL0ROW3: number; COL1ROW0: number; COL1ROW1: number; COL1ROW2: number; COL1ROW3: number; COL2ROW0: number; COL2ROW1: number; COL2ROW2: number; COL2ROW3: number; COL3ROW0: number; COL3ROW1: number; COL3ROW2: number; COL3ROW3: number; }>; get ELEMENTS(): number; get RANK(): number; constructor(array: any); copy(array: any): this; set( m00: any, m10: any, m20: any, m30: any, m01: any, m11: any, m21: any, m31: any, m02: any, m12: any, m22: any, m32: any, m03: any, m13: any, m23: any, m33: any ): this; setRowMajor( m00: any, m01: any, m02: any, m03: any, m10: any, m11: any, m12: any, m13: any, m20: any, m21: any, m22: any, m23: any, m30: any, m31: any, m32: any, m33: any ): this; toRowMajor(result: any): any; identity(): this; fromQuaternion(q: any): this; frustum({ left, right, bottom, top, near, far, }: { left: any; right: any; bottom: any; top: any; near: any; far: any; }): this; static _computeInfinitePerspectiveOffCenter( result: any, left: any, right: any, bottom: any, top: any, near: any ): any; lookAt(eye: any, center: any, up: any): this; ortho({ left, right, bottom, top, near, far, }: { left: any; right: any; bottom: any; top: any; near?: number; far?: number; }): this; orthographic({ fovy, aspect, focalDistance, near, far, }: { fovy?: number; aspect?: number; focalDistance?: number; near?: number; far?: number; }): any; perspective({ fovy, fov, // DEPRECATED aspect, near, far, }?: { fovy: any; fov?: number; aspect?: number; near?: number; far?: number; }): this; determinant(): any; getScale(result?: number[]): number[]; getTranslation(result?: number[]): number[]; getRotation(result?: number[], scaleResult?: any): number[]; getRotationMatrix3(result?: number[], scaleResult?: any): number[]; transpose(): this; invert(): this; multiplyLeft(a: any): this; multiplyRight(a: any): this; rotateX(radians: any): this; rotateY(radians: any): this; rotateZ(radians: any): this; rotateXYZ([rx, ry, rz]: [any, any, any]): this; rotateAxis(radians: any, axis: any): this; scale(factor: any): this; translate(vec: any): this; transform(vector: any, result: any): any; transformAsPoint(vector: any, result: any): any; transformAsVector(vector: any, result: any): any; makeRotationX(radians: any): this; makeTranslation(x: any, y: any, z: any): this; transformPoint(vector: any, result: any): any; transformVector(vector: any, result: any): any; transformDirection(vector: any, result: any): any; } } declare module "@math.gl/core/classes/quaternion" { import MathArray from "@math.gl/core/classes/base/math-array"; export default class Quaternion extends MathArray { constructor(x?: number, y?: number, z?: number, w?: number); copy(array: any): this; set(x: any, y: any, z: any, w: any): this; fromMatrix3(m: any): this; identity(): this; fromAxisRotation(axis: any, rad: any): this; setAxisAngle(axis: any, rad: any): this; get ELEMENTS(): number; get x(): any; set x(value: any); get y(): any; set y(value: any); get z(): any; set z(value: any); get w(): any; set w(value: any); len(): any; lengthSquared(a: any): any; dot(a: any, b: any): any; rotationTo(vectorA: any, vectorB: any): this; add(a: any, b: any): this; calculateW(): this; conjugate(): this; invert(): this; lerp(a: any, b: any, t: any): this; multiplyRight(a: any, b: any): this; multiplyLeft(a: any, b: any): this; normalize(): this; rotateX(rad: any): this; rotateY(rad: any): this; rotateZ(rad: any): this; scale(b: any): this; slerp(start: any, target: any, ratio: any): this; transformVector4(vector: any, result?: any): any; lengthSq(): any; setFromAxisAngle(axis: any, rad: any): this; premultiply(a: any, b: any): this; multiply(a: any, b: any): this; } } declare module "@math.gl/core/lib/math-utils" { const _default: { EPSILON1: number; EPSILON2: number; EPSILON3: number; EPSILON4: number; EPSILON5: number; EPSILON6: number; EPSILON7: number; EPSILON8: number; EPSILON9: number; EPSILON10: number; EPSILON11: number; EPSILON12: number; EPSILON13: number; EPSILON14: number; EPSILON15: number; EPSILON16: number; EPSILON17: number; EPSILON18: number; EPSILON19: number; EPSILON20: number; PI_OVER_TWO: number; PI_OVER_FOUR: number; PI_OVER_SIX: number; TWO_PI: number; }; export default _default; } declare module "@math.gl/core/classes/spherical-coordinates" { import Vector3 from "@math.gl/core/classes/vector3"; export default class SphericalCoordinates { /** * Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system * The poles (phi) are at the positive and negative y axis. * The equator starts at positive z. * @class * @param {Number} phi=0 - rotation around X (latitude) * @param {Number} theta=0 - rotation around Y (longitude) * @param {Number} radius=1 - Distance from center */ constructor({ phi, theta, radius, bearing, pitch, altitude, radiusScale, }?: { phi: any; theta: any; radius: any; bearing: any; pitch: any; altitude: any; radiusScale?: number; }); toString(): any; formatString({ printTypes, printDegrees, }: { printTypes: any; printDegrees: any; }): string; equals(other: any): any; exactEquals(other: any): boolean; get bearing(): number; set bearing(v: number); get pitch(): any; set pitch(v: any); get longitude(): any; get latitude(): any; get lng(): any; get lat(): any; get z(): number; set(radius: any, phi: any, theta: any): this; clone(): any; copy(other: any): this; fromLngLatZ([lng, lat, z]: [any, any, any]): void; fromVector3(v: any): this; toVector3(): Vector3; makeSafe(): void; check(): this; } } declare module "@math.gl/core/classes/euler" { import MathArray from "@math.gl/core/classes/base/math-array"; import Quaternion from "@math.gl/core/classes/quaternion"; export default class Euler extends MathArray { static get ZYX(): number; static get YXZ(): number; static get XZY(): number; static get ZXY(): number; static get YZX(): number; static get XYZ(): number; static get RollPitchYaw(): number; static get DefaultOrder(): number; static get RotationOrders(): string[]; static rotationOrder(order: any): string; get ELEMENTS(): number; constructor(x?: number, y?: number, z?: number, order?: number); fromQuaternion(quaternion: any): Euler; copy(array: any): this; set(x: number, y: number, z: number, order: any): this; validate(): boolean; toArray(array?: any[], offset?: number): any[]; toArray4(array?: any[], offset?: number): any[]; toVector3(result?: number[]): number[]; get x(): any; set x(value: any); get y(): any; set y(value: any); get z(): any; set z(value: any); get alpha(): any; set alpha(value: any); get beta(): any; set beta(value: any); get gamma(): any; set gamma(value: any); get phi(): any; set phi(value: any); get theta(): any; set theta(value: any); get psi(): any; set psi(value: any); get roll(): any; set roll(value: any); get pitch(): any; set pitch(value: any); get yaw(): any; set yaw(value: any); get order(): any; set order(value: any); fromVector3(v: any, order: any): this; fromArray(array: any, offset?: number): this; fromRollPitchYaw(roll: any, pitch: any, yaw: any): this; fromRotationMatrix(m: any, order?: number): this; getRotationMatrix(m: any): any; getQuaternion(): Quaternion; _fromRotationMatrix(m: any, order?: number): this; _getRotationMatrix(result: any): any; toQuaternion(): Quaternion; } } declare module "@math.gl/core/classes/pose" { export default class Pose { /** * A pose contains both rotation and rotations. * Note that every single pose defines its own coordinate system * (with the position of the pose in the origin, and zero rotations). * These "pose relative" coordinate will be centered on the defining * pose's position and with with the defining pose's orientation * aligned with axis. */ constructor({ x, y, z, roll, pitch, yaw, position, orientation, }?: { x?: number; y?: number; z?: number; roll?: number; pitch?: number; yaw?: number; position: any; orientation: any; }); get x(): any; set x(value: any); get y(): any; set y(value: any); get z(): any; set z(value: any); get roll(): any; set roll(value: any); get pitch(): any; set pitch(value: any); get yaw(): any; set yaw(value: any); getPosition(): any; getOrientation(): any; equals(pose: any): any; exactEquals(pose: any): any; getTransformationMatrix(): any; getTransformationMatrixFromPose(pose: any): any; getTransformationMatrixToPose(pose: any): any; } } declare module "@math.gl/core/addons/polygon" { export default class Polygon { constructor(points: any); getSignedArea(): number; getArea(): number; getWindingDirection(): number; forEachSegment(visitor: any): void; } } declare module "@math.gl/core" { export { default as Vector2 } from "@math.gl/core/classes/vector2"; export { default as Vector3 } from "@math.gl/core/classes/vector3"; export { default as Vector4 } from "@math.gl/core/classes/vector4"; export { default as Matrix3 } from "@math.gl/core/classes/matrix3"; export { default as Matrix4 } from "@math.gl/core/classes/matrix4"; export { default as Quaternion } from "@math.gl/core/classes/quaternion"; export { config, configure, formatValue, isArray, clone, equals, exactEquals, toRadians, toDegrees, radians, degrees, sin, cos, tan, asin, acos, atan, clamp, lerp, withEpsilon as _withEpsilon, } from "@math.gl/core/lib/common"; export { checkNumber } from "@math.gl/core/lib/validators"; export { default as _MathUtils } from "@math.gl/core/lib/math-utils"; export { default as _SphericalCoordinates } from "@math.gl/core/classes/spherical-coordinates"; export { default as _Pose } from "@math.gl/core/classes/pose"; export { default as _Euler } from "@math.gl/core/classes/euler"; export { default as _Polygon } from "@math.gl/core/addons/polygon"; export { default as assert } from "@math.gl/core/lib/assert"; }
the_stack
import { vec3, vec4 } from "../math"; import { Mesh, bufferView, Accessor } from "../mesh/mesh"; import { Texture } from "../texture"; import { Entity, EntityMgr } from "../ECS/entityMgr"; import { Material } from "../material/material"; import { Shader } from "../shader"; import { glsl } from "../glsl"; import { MeshRenderer } from "../meshRenderer"; import { Screen } from "../webgl2/screen"; import { Transform } from "../transform"; export class AABB { max: Float32Array = vec3.fromValues(-Infinity, -Infinity, -Infinity); min: Float32Array = vec3.fromValues(Infinity, Infinity, Infinity); private _center: Float32Array = vec3.create(); get center() { if(this.isDirty) this.updateCenter(); return this._center; } private isDirty = false; private updateCenter() { this._center[0] = this.min[0] + (this.max[0] - this.min[0]) * 0.5; this._center[1] = this.min[1] + (this.max[1] - this.min[1]) * 0.5; this._center[2] = this.min[2] + (this.max[2] - this.min[2]) * 0.5; this.isDirty = false; } update(p: Float32Array) { this.isDirty = true; this.max[0] = Math.max(this.max[0], p[0]); this.max[1] = Math.max(this.max[1], p[1]); this.max[2] = Math.max(this.max[2], p[2]); this.min[0] = Math.min(this.min[0], p[0]); this.min[1] = Math.min(this.min[1], p[1]); this.min[2] = Math.min(this.min[2], p[2]); } private _isVisible = false; root: Entity; agent: Entity; screen: Screen; get visible() { return this._isVisible; } static mat = new Material(new Shader(glsl.line.vs, glsl.line.fs)); set visible(status) { this._isVisible = status; if(status) { if(!this.agent) { this.agent = this.root.appendChild(EntityMgr.create('aabb')); const mesh = this.createMesh(); const mr = new MeshRenderer(this.screen, mesh, AABB.mat); this.agent.addComponent(mr); } } } createMesh() { const x = this.max[0]; const y = this.max[1]; const z = this.max[2]; const x2 = this.min[0]; const y2 = this.min[1]; const z2 = this.min[2]; let meshVBO = new Float32Array([ //x x // \/\ // x x x, y, z, // 0 x, y2, z, // 1 x, y, z2, // 2 x, y2, z2, // 3 x2, y, z, // 4 x2, y2, z, // 5 x2, y, z2, // 6 x2, y2, z2, // 7 ]); let meshEBO = new Uint16Array([ 0, 1, 5, 4, 0, 2, 6, 4, 4, 5, 7, 6, 7, 3, 1, 3, 2 ]); let vbo = new bufferView(meshVBO.buffer, { byteOffset: meshVBO.byteOffset, byteLength: meshVBO.byteLength, byteStride: 3*4, target: WebGL2RenderingContext.ARRAY_BUFFER }); let ebo = new bufferView(meshEBO.buffer, { byteOffset: meshEBO.byteOffset, byteLength: meshEBO.byteLength, byteStride: 0, target: WebGL2RenderingContext.ELEMENT_ARRAY_BUFFER }); let position = new Accessor({ bufferView: vbo, componentType: WebGL2RenderingContext.FLOAT, byteOffset: 0, type: "VEC3", count: 8 }, 'POSITION'); let indices = new Accessor({ bufferView: ebo, componentType: WebGL2RenderingContext.UNSIGNED_SHORT, byteOffset: 0, type: "SCALAR", count: meshEBO.length }); // return new Mesh([position], indices); return new Mesh([position], indices, WebGL2RenderingContext.LINE_LOOP); } } class BVHNode { bounds = new AABB(); right: BVHNode; left: BVHNode; isLeaf = false; index: number = -1; mat: number = -1; length: number; get raw() { return new Float32Array(6); } static hitable(ray, bounds: AABB) { } } class trianglePrimitive { bounds = new AABB(); index: number; mat: number; } class DataTexture { raw: Float32Array; chunks: Float32Array[]; tex: Texture; constructor(texSize = 2048, chunkTexels = 1) { const totalTexel = texSize * texSize; const totalChunks = totalTexel / chunkTexels; const chunkOffset = chunkTexels * 4; const raw = new Float32Array(totalTexel * 4); const chunks: Float32Array[] = []; for(let i = 0; i < totalChunks; i++) { chunks[i] = raw.subarray(i * chunkOffset, (i + 1) * chunkOffset); } const tex = new Texture(null, { magFilter: WebGL2RenderingContext.LINEAR, minFilter: WebGL2RenderingContext.LINEAR, wrapS: WebGL2RenderingContext.CLAMP_TO_EDGE, wrapT: WebGL2RenderingContext.CLAMP_TO_EDGE, }); tex.data = raw; tex.height = texSize; tex.width = texSize; tex.format = WebGL2RenderingContext.RGBA; tex.internalformat = WebGL2RenderingContext.RGBA32F; tex.type = WebGL2RenderingContext.FLOAT; tex.isDirty = true; this.raw = raw; this.chunks = chunks; this.tex = tex; } } export class BVHManager { nodeList: BVHNode[] = []; primitives: Float32Array; meshes: Mesh[]; root: BVHNode; LBVH: Float32Array; LBVH_nodes: Float32Array[]; trianglesTex: DataTexture; LBVHTexture: DataTexture; matMap: Map<string, [number, Material]> = new Map(); matConfig; constructor(texSize = 2048) { // const LBVHTexture = BVHManager.createDataTex(texSize, 2); this.LBVHTexture = new DataTexture(texSize, 2); this.LBVH = this.LBVHTexture.raw; this.LBVH_nodes = this.LBVHTexture.chunks; // R-G-B-A-R-G-B-A // X-Y-Z-_-X-Y-Z-P } // Generate bounds of triangles, mind GC! genBounds(triangles: Float32Array[], size = triangles.length, materialOffset) { const boxList: trianglePrimitive[] = []; // [[x, y, z] * 3, ...] let anchor = 0; for(let i = 0; i < size;) { // [offset, index] if(anchor < materialOffset.length - 1 && i >= materialOffset[anchor+1][0]) { anchor++; } const box = new trianglePrimitive(); box.mat = materialOffset[anchor][1]; // Count From 0 box.index = i*2; // Offset of the first vertex // box.index = i; // Offset of the first vertex box.bounds.update(triangles[i++]); box.bounds.update(triangles[i++]); box.bounds.update(triangles[i++]); boxList.push(box); } return boxList; } // TODO: Texture packer materialsHandler(mats: Map<string, [number, Material]>) { let params = ''; let route = ` if(mat < -.5) { continue; }`; const max = 16 - 5; let tasks = []; for(const [name, [i,mt]] of mats) { // Textures const tex = mt.textures; // baseColorTexture let abledo = 'sRGBtoLINEAR(texture(ground, iuv * 40.)).rgb'; if (name == 'Logo1') { abledo = 'vec3(.3, .5, 1)' } else if (name == 'Logo2') { abledo = 'vec3(.9, .7, .12)' } let base = ` // float scale = 100.; // float fact = step(.0, sin(iuv.x * scale)*sin(iuv.y * scale)); // albedo = vec3(1) * clamp(fact, .2, 1.); // albedo = sRGBtoLINEAR(texture(ground, iuv * .3)).rgb; albedo = ${abledo}; `; if(tex.has('baseColorTexture') && tasks.length < max) { params += ` uniform sampler2D baseColorTexture_${i}; `; base = `albedo = sRGBtoLINEAR(texture(baseColorTexture_${i}, iuv)).rgb;`; tasks.push(m => { Material.setTexture(m, `baseColorTexture_${i}`, tex.get('baseColorTexture')[1]); }); } // metallicRoughnessTexture let rm = ` vec3 rm = vec3(0, .01, .12); metal = clamp(rm.b, 0.0, 1.0); roughness = clamp(1. - rm.g, 0.04, 1.0); `; if(tex.has('metallicRoughnessTexture') && tasks.length < max) { params += ` uniform sampler2D metallicRoughnessTexture_${i}; `; rm = ` vec3 rm = texture(metallicRoughnessTexture_${i}, iuv).rgb; metal = clamp(rm.b, 0.0, 1.0); roughness = clamp(rm.g, 0.04, 1.0); `; tasks.push(m => { Material.setTexture(m, `metallicRoughnessTexture_${i}`, tex.get('metallicRoughnessTexture')[1]); }); } // emissiveTexture let em = ''; if(tex.has('emissiveTexture') && tasks.length < max) { params += ` uniform sampler2D emissiveTexture_${i}; `; em = ` vec3 em = sRGBtoLINEAR(texture(emissiveTexture_${i}, iuv)).rgb; if(dot(em, em) > .01) return em; `; tasks.push(m => { Material.setTexture(m, `emissiveTexture_${i}`, tex.get('emissiveTexture')[1]); }); } route += ` else if(mat < ${i}.5) { // NOTE: ${name} ${base} ${rm} ${em} }`; } const init = m => { for(let t of tasks) t(m); } return {params, route, init}; } buildBVH(meshes: Mesh[]) { console.time('Build BVH'); let materialList = []; // ? x-y-z-x y-z-x-y z-x const triangleTexture = new DataTexture(2048, 2); let offset = 0; // Reduce GC const wpos = vec3.create(); // World position const wnor = vec4.create(); // World position for(let m of meshes) { // Collect materials const mt = m['entity'].components.Material as Material; let mtIndex = -1; if(this.matMap.has(mt.name)) { [mtIndex] = this.matMap.get(mt.name); } else { // New material mtIndex = this.matMap.size; this.matMap.set(mt.name, [this.matMap.size, mt]); } materialList.push([offset, mtIndex]); let trans = m['entity'].components.Transform as Transform; let data: any = m.data; let pos: Float32Array[] = data.POSITION; let normal: Float32Array[] = data.NORMAL; let uv: Float32Array[] = data.TEXCOORD_0; let face = m.indices.data; for(let i = 0; i < face.length; i++) { // Per vertex // R G B A - R G B A - R G B A - R G B A - R G B A - R G B A //[x y z u 1 n n n v] [x y z u 2 n n n v] [x y z u 3 n n n v] const cur = triangleTexture.chunks[offset++]; const vertex = pos[face[i]]; vec3.transformMat4(wpos, vertex, trans.worldMatrix); cur.set(wpos); // cur[3] = 1; if(normal) { const n = normal[face[i]]; vec4.set(wnor, n[0], n[1], n[2], 0); vec4.transformMat4(wnor, wnor, trans.worldNormalMatrix); vec3.normalize(wnor, wnor); cur.set(wnor, 4); } if(uv) { cur[3] = uv[face[i]][0]; cur[7] = uv[face[i]][1]; } } } const primitives = this.genBounds(triangleTexture.chunks, offset, materialList); const root = this.root = this.splitBVH(primitives); const LBVH = this.fillLBVH(root, this.LBVHTexture); const matHandler = this.materialsHandler(this.matMap); console.timeEnd('Build BVH'); return {LBVH, triangleTexture, primitives, matHandler}; } private _size = vec3.create(); splitBVH(prim: trianglePrimitive[]) { if(prim.length == 0) // Empty branch return null; const node = new BVHNode(); // Calculate current AABB for(let p of prim) { node.bounds.update(p.bounds.max); node.bounds.update(p.bounds.min); } // TODO: if(prim.length < 2) { node.isLeaf = true; node.index = prim[0].index; node.mat = prim[0].mat; return node; } // Compare and find the longest axis const size = this._size; vec3.sub(size, node.bounds.max, node.bounds.min); let axis = size.indexOf(Math.max(size[0], size[1], size[2])); // if(size[axis] > 0) {} let left: trianglePrimitive[] = []; let right: trianglePrimitive[] = []; let c = 3; while(c-- && (left.length == 0 || right.length == 0)) { // const middle = node.bounds.min[axis] + size[axis] / 2; // const middle = node.bounds.min[axis%3] + size[axis%3] / 2; const middle = node.bounds.center[axis%3]; // Reset left = []; right = []; // FIXME: for(let p of prim) { if(p.bounds.center[axis] < middle) { left.push(p); } else { right.push(p); } } axis++; if(c == 0) { // FIXME: const m = Math.ceil(prim.length / 2); // if(m < 6) { // left = prim.slice(0, 1); // right = prim.slice(m, m+1); // } else { left = prim.slice(0, m); right = prim.slice(m); // } // left = [prim[0]]; // right = [prim[1]]; } } if(left.length == 0 && right.length == 0) { // Impossible, unless prim is empty debugger } if(left.length == 0) { // Make sure left branch is allways exist, even one of them is empty const cache = left; // [] left = right; right = cache; } node.left = this.splitBVH(left); node.right = this.splitBVH(right); return node; } // Test static createTree(deep) { let root = new BVHNode(); if(deep--) { root.left = this.createTree(deep); root.right = this.createTree(deep); } else { root.isLeaf = true; } return root; } fillLBVH(root: BVHNode, LBVH: DataTexture) { LBVH.raw.fill(0); BVHManager.fillLinearNode(root, LBVH.chunks); return LBVH; } // Create LBVH static fillLinearNode(root: BVHNode, mem: Float32Array[], index = 0) { let right = root.right ? index + 1 // (*)incase right branch is exist but left is null : -1; // right branch is empty if(root.left) { // Append left branch behind current node right = this.fillLinearNode(root.left, mem, index+1); } // Fill curretn node // root.index = right; // mem[index++] = [root, right, root.isLeaf]; mem[index].set(root.bounds.min); mem[index].set(root.bounds.max, 4); // TODO: Obj if(root.isLeaf) { // Leaf node mem[index][3] = root.mat; } else { mem[index][3] = right; } mem[index][7] = root.index; index++; if(root.right) { // Append right branch index = this.fillLinearNode(root.right, mem, right); } return index; } }
the_stack
interface MenuItemOptions extends Electron.MenuItemOptions {} import * as _ from "lodash"; import * as assert from "assert"; import { app, Menu } from "electron"; import * as shell from "./shell"; const menuTemplate: MenuItemOptions[] = []; export const ERR_NOT_FOUND = "NOTFOUND"; app.on("browser-window-focus", function () { _refreshMenu(); }); app.on("browser-window-blur", function () { _refreshMenu(); }); let currentShortcuts: { [accelerator: string]: string } = {}; function registerShortcuts(win: Electron.BrowserWindow, menuItem: MenuItemOptions) { if (menuItem.accelerator && menuItem.id) { currentShortcuts[menuItem.accelerator] = menuItem.id; } if (Array.isArray(menuItem.submenu)) { menuItem.submenu.forEach((i) => registerShortcuts(win, i)); } } const __refreshMenu = _.debounce(function () { Menu.setApplicationMenu(Menu.buildFromTemplate(_.cloneDeep(menuTemplate))); const mainWindow = shell.getMainWindow(); if (mainWindow.isFocused()) { currentShortcuts = {}; menuTemplate.forEach((menuItem) => registerShortcuts(mainWindow, menuItem)); mainWindow.webContents.send("updateShortcuts", JSON.stringify(currentShortcuts)); } }, 100); function _refreshMenu(callback?: () => void) { __refreshMenu(); if (callback) { process.nextTick(callback); } } function _findMenuItemPosition( id: string, where: MenuItemOptions[] = menuTemplate, whereId: string = "" ): [string, number] | null { const result = _.find(where, { id }); if (result) { return [whereId, _.findIndex(where, { id })]; } const results = _.compact(where.map(function (menuItem) { return menuItem.submenu ? _findMenuItemPosition(id, menuItem.submenu as MenuItemOptions[], menuItem.id) : null; })); return results.length > 0 ? results[0] : null; } function _deleteMenuItemById(id: string, where: MenuItemOptions[] = menuTemplate): boolean { const result = _.findIndex(where, { id }); if (result !== -1) { where.splice(result, 1); return true; } const deleted = where.map(function (menuItem) { return menuItem.submenu ? _deleteMenuItemById(id, menuItem.submenu as MenuItemOptions[]) : null; }).filter((x) => x === true); return deleted.length > 0 ? true : false; } function _findMenuItemById(id: string, where: MenuItemOptions[] = menuTemplate): MenuItemOptions | null { const result = _.find(where, { id }); if (result) { return result; } const results = _.compact(where.map(function (menuItem) { return menuItem.submenu ? _findMenuItemById(id, menuItem.submenu as MenuItemOptions[]) : null; })); return results.length > 0 ? results[0] : null; } function _addToPosition( obj: MenuItemOptions, target: MenuItemOptions[], position: string, relativeId: string | null ): string | null { let retVal: string | null = null; if (position === "first") { target.unshift(obj); } else if (position === "last") { target.push(obj); } else if ( position === "before" || position === "after" || position === "firstInSection" || position === "lastInSection" ) { let idx = _.findIndex(target, {id: relativeId}); let idxSection: number; if (idx === -1) { // NOTE: original behaviour - if relativeId wasn't found // menu should be put to the end of the list console.warn("menu item with id: " + relativeId + " was not found, adding entry to the end of the list"); retVal = ERR_NOT_FOUND; idx = target.length; } if (position === "firstInSection") { idxSection = _.findLastIndex(target, (o: MenuItemOptions, i: number) => { return i < idx && o.type === "separator"; }); idx = idxSection + 1; } if (position === "lastInSection") { idxSection = _.findIndex(target, (o: MenuItemOptions, i: number) => { return i >= idx && o.type === "separator"; }); idx = idxSection === -1 ? target.length : idxSection; } if (position === "after") { idx++; } target.splice(idx, 0, obj); } else { throw new Error("position not implemented in _addToPosition: " + position); } return retVal; } function _fixBracketsKeyboardShortcut(shortcut: string): string { if (shortcut.trim() === "") { return ""; } shortcut = shortcut.replace(/-/g, "+"); shortcut = shortcut.replace(/\+$/g, "Plus"); shortcut = shortcut.replace(/\u2190/g, "Left"); shortcut = shortcut.replace(/\u2191/g, "Up"); shortcut = shortcut.replace(/\u2192/g, "Right"); shortcut = shortcut.replace(/\u2193/g, "Down"); shortcut = shortcut.replace(/\u2212/g, "-"); if (!shortcut.match(/^[\x00-\x7F]+$/)) { console.error("Non ASCII keyboard shortcut used: " + shortcut); return ""; } return shortcut; } export function addMenu(title: string, id: string, position: string, relativeId: string, callback: () => void) { assert(title && typeof title === "string", "title must be a string"); assert(id && typeof id === "string", "id must be a string"); assert(!position || position && typeof position === "string", "position must be a string"); assert(!relativeId || relativeId && typeof relativeId === "string", "relativeId must be a string"); assert(typeof callback === "function", "callback must be a function"); process.nextTick(function () { const newObj = { id, label: title }; const err = _addToPosition(newObj, menuTemplate, position || "last", relativeId); _refreshMenu(callback.bind(null, err)); }); } export function addMenuItem( parentId: string, title: string, id: string, key: string | null, displayStr: string | null, position: string | null, relativeId: string | null, callback: (err?: string | null) => void ) { assert(parentId && typeof parentId === "string", "parentId must be a string"); assert(title && typeof title === "string", "title must be a string"); assert(id && typeof id === "string", "id must be a string"); assert(!key || key && typeof key === "string", "key must be a string"); assert(!displayStr || displayStr && typeof displayStr === "string", "displayStr must be a string"); assert(!position || position && typeof position === "string", "position must be a string"); assert(!relativeId || relativeId && typeof relativeId === "string", "relativeId must be a string"); assert(typeof callback === "function", "callback must be a function"); process.nextTick(function () { if (typeof key === "string") { key = _fixBracketsKeyboardShortcut(key); } const isSeparator = title === "---"; const newObj: MenuItemOptions = { type: isSeparator ? "separator" : "normal", id, label: title, click: () => shell.getMainWindow().webContents.send("executeCommand", id) }; if (key) { newObj.accelerator = key; } const parentObj = _findMenuItemById(parentId); if (!parentObj) { return process.nextTick(function () { callback(ERR_NOT_FOUND); }); } if (!parentObj.submenu) { parentObj.submenu = []; } const err = _addToPosition(newObj, parentObj.submenu as MenuItemOptions[], position || "last", relativeId); _refreshMenu(callback.bind(null, err)); }); } export function getMenuItemState( commandId: string, callback: (err?: string | null, enabled?: boolean, checked?: boolean) => void ) { assert(commandId && typeof commandId === "string", "commandId must be a string"); process.nextTick(function () { const obj = _findMenuItemById(commandId); if (!obj) { return callback(ERR_NOT_FOUND); } callback(null, obj.enabled === true, obj.checked === true); }); } export function getMenuPosition( commandId: string, callback: (err?: string | null, parentId?: string, position?: number) => void ) { assert(commandId && typeof commandId === "string", "commandId must be a string"); process.nextTick(function () { const res = _findMenuItemPosition(commandId); return res ? callback(null, res[0], res[1]) : callback(null); }); } export function getMenuTitle(commandId: string, callback: (err?: string | null, title?: string) => void) { assert(commandId && typeof commandId === "string", "commandId must be a string"); process.nextTick(function () { const obj = _findMenuItemById(commandId); if (!obj) { return callback(ERR_NOT_FOUND); } callback(null, obj.label); }); } export function removeMenu(commandId: string, callback: (err?: string | null, deleted?: boolean) => void) { assert(commandId && typeof commandId === "string", "commandId must be a string"); process.nextTick(function () { const deleted = _deleteMenuItemById(commandId); _refreshMenu(callback.bind(null, deleted ? null : ERR_NOT_FOUND)); }); } export function removeMenuItem(commandId: string, callback: (err?: string | null, deleted?: boolean) => void) { assert(commandId && typeof commandId === "string", "commandId must be a string"); process.nextTick(function () { const deleted = _deleteMenuItemById(commandId); _refreshMenu(callback.bind(null, deleted ? null : ERR_NOT_FOUND)); }); } export function setMenuItemShortcut( commandId: string, shortcut: string, displayStr: string, callback: (err?: string | null) => void ) { assert(commandId && typeof commandId === "string", "commandId must be a string"); assert(shortcut && typeof shortcut === "string", "shortcut must be a string"); process.nextTick(function () { shortcut = _fixBracketsKeyboardShortcut(shortcut); const obj = _findMenuItemById(commandId); if (!obj) { return callback(ERR_NOT_FOUND); } if (shortcut) { obj.accelerator = shortcut; } else { delete obj.accelerator; } _refreshMenu(callback.bind(null, null)); }); } export function setMenuItemState( commandId: string, enabled: boolean, checked: boolean, callback: (err?: string | null) => void ) { assert(typeof enabled === "boolean", "enabled must be a boolean"); assert(typeof checked === "boolean", "checked must be a boolean"); process.nextTick(function () { const obj = _findMenuItemById(commandId); if (!obj) { return callback(ERR_NOT_FOUND); } obj.enabled = enabled; obj.checked = checked; if (checked) { // TODO: Change addMenuItem to set the type (checkbox, radio, ... submenu) obj.type = "checkbox"; } _refreshMenu(callback.bind(null, null)); }); } export function setMenuTitle( commandId: string, title: string, callback: (err?: string | null) => void ) { assert(commandId && typeof commandId === "string", "commandId must be a string"); assert(title && typeof title === "string", "title must be a string"); process.nextTick(function () { const obj = _findMenuItemById(commandId); if (!obj) { return callback(ERR_NOT_FOUND); } obj.label = title; _refreshMenu(callback.bind(null, null)); }); }
the_stack
import * as pulumi from "@pulumi/pulumi"; import { input as inputs, output as outputs } from "../types"; import * as utilities from "../utilities"; /** * A Dialogflow CX conversation (session) can be described and visualized as a state machine. The states of a CX session are represented by pages. * * To get more information about Page, see: * * * [API documentation](https://cloud.google.com/dialogflow/cx/docs/reference/rest/v3/projects.locations.agents.flows.pages) * * How-to Guides * * [Official Documentation](https://cloud.google.com/dialogflow/cx/docs) * * ## Example Usage * ### Dialogflowcx Page Full * * ```typescript * import * as pulumi from "@pulumi/pulumi"; * import * as gcp from "@pulumi/gcp"; * * const agent = new gcp.diagflow.CxAgent("agent", { * displayName: "dialogflowcx-agent", * location: "global", * defaultLanguageCode: "en", * supportedLanguageCodes: [ * "fr", * "de", * "es", * ], * timeZone: "America/New_York", * description: "Example description.", * avatarUri: "https://cloud.google.com/_static/images/cloud/icons/favicons/onecloud/super_cloud.png", * enableStackdriverLogging: true, * enableSpellCorrection: true, * speechToTextSettings: { * enableSpeechAdaptation: true, * }, * }); * const myPage2 = new gcp.diagflow.CxPage("myPage2", { * parent: agent.startFlow, * displayName: "MyPage2", * }); * const basicPage = new gcp.diagflow.CxPage("basicPage", { * parent: agent.startFlow, * displayName: "MyPage", * entryFulfillment: { * messages: [{ * text: { * texts: ["Welcome to page"], * }, * }], * }, * form: { * parameters: [{ * displayName: "param1", * entityType: "projects/-/locations/-/agents/-/entityTypes/sys.date", * fillBehavior: { * initialPromptFulfillment: { * messages: [{ * text: { * texts: ["Please provide param1"], * }, * }], * }, * }, * required: "true", * redact: "true", * }], * }, * transitionRoutes: [{ * condition: `$page.params.status = 'FINAL'`, * triggerFulfillment: { * messages: [{ * text: { * texts: ["information completed, navigating to page 2"], * }, * }], * }, * targetPage: myPage2.id, * }], * }); * ``` * * ## Import * * Page can be imported using any of these accepted formats * * ```sh * $ pulumi import gcp:diagflow/cxPage:CxPage default {{parent}}/pages/{{name}} * ``` * * ```sh * $ pulumi import gcp:diagflow/cxPage:CxPage default {{parent}}/{{name}} * ``` */ export class CxPage extends pulumi.CustomResource { /** * Get an existing CxPage 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?: CxPageState, opts?: pulumi.CustomResourceOptions): CxPage { return new CxPage(name, <any>state, { ...opts, id: id }); } /** @internal */ public static readonly __pulumiType = 'gcp:diagflow/cxPage:CxPage'; /** * Returns true if the given object is an instance of CxPage. 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 CxPage { if (obj === undefined || obj === null) { return false; } return obj['__pulumiType'] === CxPage.__pulumiType; } /** * The human-readable name of the parameter, unique within the form. */ public readonly displayName!: pulumi.Output<string>; /** * The fulfillment to call when the session is entering the page. * Structure is documented below. */ public readonly entryFulfillment!: pulumi.Output<outputs.diagflow.CxPageEntryFulfillment | undefined>; /** * Handlers associated with the page to handle events such as webhook errors, no match or no input. * Structure is documented below. */ public readonly eventHandlers!: pulumi.Output<outputs.diagflow.CxPageEventHandler[] | undefined>; /** * The form associated with the page, used for collecting parameters relevant to the page. * Structure is documented below. */ public readonly form!: pulumi.Output<outputs.diagflow.CxPageForm | undefined>; /** * The language of the following fields in page: * Page.entry_fulfillment.messages * Page.entry_fulfillment.conditional_cases * Page.event_handlers.trigger_fulfillment.messages * Page.event_handlers.trigger_fulfillment.conditional_cases * Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages * Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases * Page.form.parameters.fill_behavior.reprompt_event_handlers.messages * Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases * Page.transition_routes.trigger_fulfillment.messages * Page.transition_routes.trigger_fulfillment.conditional_cases * If not specified, the agent's default language is used. Many languages are supported. Note: languages must be enabled in the agent before they can be used. */ public readonly languageCode!: pulumi.Output<string | undefined>; /** * - * The unique identifier of this event handler. */ public /*out*/ readonly name!: pulumi.Output<string>; /** * The flow to create a page for. * Format: projects/<Project ID>/locations/<Location ID>/agents/<Agent ID>/flows/<Flow ID>. */ public readonly parent!: pulumi.Output<string | undefined>; /** * Ordered list of TransitionRouteGroups associated with the page. Transition route groups must be unique within a page. * If multiple transition routes within a page scope refer to the same intent, then the precedence order is: page's transition route > page's transition route group > flow's transition routes. * If multiple transition route groups within a page contain the same intent, then the first group in the ordered list takes precedence. * Format:projects/<Project ID>/locations/<Location ID>/agents/<Agent ID>/flows/<Flow ID>/transitionRouteGroups/<TransitionRouteGroup ID>. */ public readonly transitionRouteGroups!: pulumi.Output<string[] | undefined>; /** * A list of transitions for the transition rules of this page. They route the conversation to another page in the same flow, or another flow. * When we are in a certain page, the TransitionRoutes are evalauted in the following order: * TransitionRoutes defined in the page with intent specified. * TransitionRoutes defined in the transition route groups with intent specified. * TransitionRoutes defined in flow with intent specified. * TransitionRoutes defined in the transition route groups with intent specified. * TransitionRoutes defined in the page with only condition specified. * TransitionRoutes defined in the transition route groups with only condition specified. * Structure is documented below. */ public readonly transitionRoutes!: pulumi.Output<outputs.diagflow.CxPageTransitionRoute[] | undefined>; /** * Create a CxPage 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: CxPageArgs, opts?: pulumi.CustomResourceOptions) constructor(name: string, argsOrState?: CxPageArgs | CxPageState, opts?: pulumi.CustomResourceOptions) { let inputs: pulumi.Inputs = {}; opts = opts || {}; if (opts.id) { const state = argsOrState as CxPageState | undefined; inputs["displayName"] = state ? state.displayName : undefined; inputs["entryFulfillment"] = state ? state.entryFulfillment : undefined; inputs["eventHandlers"] = state ? state.eventHandlers : undefined; inputs["form"] = state ? state.form : undefined; inputs["languageCode"] = state ? state.languageCode : undefined; inputs["name"] = state ? state.name : undefined; inputs["parent"] = state ? state.parent : undefined; inputs["transitionRouteGroups"] = state ? state.transitionRouteGroups : undefined; inputs["transitionRoutes"] = state ? state.transitionRoutes : undefined; } else { const args = argsOrState as CxPageArgs | undefined; if ((!args || args.displayName === undefined) && !opts.urn) { throw new Error("Missing required property 'displayName'"); } inputs["displayName"] = args ? args.displayName : undefined; inputs["entryFulfillment"] = args ? args.entryFulfillment : undefined; inputs["eventHandlers"] = args ? args.eventHandlers : undefined; inputs["form"] = args ? args.form : undefined; inputs["languageCode"] = args ? args.languageCode : undefined; inputs["parent"] = args ? args.parent : undefined; inputs["transitionRouteGroups"] = args ? args.transitionRouteGroups : undefined; inputs["transitionRoutes"] = args ? args.transitionRoutes : undefined; inputs["name"] = undefined /*out*/; } if (!opts.version) { opts = pulumi.mergeOptions(opts, { version: utilities.getVersion()}); } super(CxPage.__pulumiType, name, inputs, opts); } } /** * Input properties used for looking up and filtering CxPage resources. */ export interface CxPageState { /** * The human-readable name of the parameter, unique within the form. */ displayName?: pulumi.Input<string>; /** * The fulfillment to call when the session is entering the page. * Structure is documented below. */ entryFulfillment?: pulumi.Input<inputs.diagflow.CxPageEntryFulfillment>; /** * Handlers associated with the page to handle events such as webhook errors, no match or no input. * Structure is documented below. */ eventHandlers?: pulumi.Input<pulumi.Input<inputs.diagflow.CxPageEventHandler>[]>; /** * The form associated with the page, used for collecting parameters relevant to the page. * Structure is documented below. */ form?: pulumi.Input<inputs.diagflow.CxPageForm>; /** * The language of the following fields in page: * Page.entry_fulfillment.messages * Page.entry_fulfillment.conditional_cases * Page.event_handlers.trigger_fulfillment.messages * Page.event_handlers.trigger_fulfillment.conditional_cases * Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages * Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases * Page.form.parameters.fill_behavior.reprompt_event_handlers.messages * Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases * Page.transition_routes.trigger_fulfillment.messages * Page.transition_routes.trigger_fulfillment.conditional_cases * If not specified, the agent's default language is used. Many languages are supported. Note: languages must be enabled in the agent before they can be used. */ languageCode?: pulumi.Input<string>; /** * - * The unique identifier of this event handler. */ name?: pulumi.Input<string>; /** * The flow to create a page for. * Format: projects/<Project ID>/locations/<Location ID>/agents/<Agent ID>/flows/<Flow ID>. */ parent?: pulumi.Input<string>; /** * Ordered list of TransitionRouteGroups associated with the page. Transition route groups must be unique within a page. * If multiple transition routes within a page scope refer to the same intent, then the precedence order is: page's transition route > page's transition route group > flow's transition routes. * If multiple transition route groups within a page contain the same intent, then the first group in the ordered list takes precedence. * Format:projects/<Project ID>/locations/<Location ID>/agents/<Agent ID>/flows/<Flow ID>/transitionRouteGroups/<TransitionRouteGroup ID>. */ transitionRouteGroups?: pulumi.Input<pulumi.Input<string>[]>; /** * A list of transitions for the transition rules of this page. They route the conversation to another page in the same flow, or another flow. * When we are in a certain page, the TransitionRoutes are evalauted in the following order: * TransitionRoutes defined in the page with intent specified. * TransitionRoutes defined in the transition route groups with intent specified. * TransitionRoutes defined in flow with intent specified. * TransitionRoutes defined in the transition route groups with intent specified. * TransitionRoutes defined in the page with only condition specified. * TransitionRoutes defined in the transition route groups with only condition specified. * Structure is documented below. */ transitionRoutes?: pulumi.Input<pulumi.Input<inputs.diagflow.CxPageTransitionRoute>[]>; } /** * The set of arguments for constructing a CxPage resource. */ export interface CxPageArgs { /** * The human-readable name of the parameter, unique within the form. */ displayName: pulumi.Input<string>; /** * The fulfillment to call when the session is entering the page. * Structure is documented below. */ entryFulfillment?: pulumi.Input<inputs.diagflow.CxPageEntryFulfillment>; /** * Handlers associated with the page to handle events such as webhook errors, no match or no input. * Structure is documented below. */ eventHandlers?: pulumi.Input<pulumi.Input<inputs.diagflow.CxPageEventHandler>[]>; /** * The form associated with the page, used for collecting parameters relevant to the page. * Structure is documented below. */ form?: pulumi.Input<inputs.diagflow.CxPageForm>; /** * The language of the following fields in page: * Page.entry_fulfillment.messages * Page.entry_fulfillment.conditional_cases * Page.event_handlers.trigger_fulfillment.messages * Page.event_handlers.trigger_fulfillment.conditional_cases * Page.form.parameters.fill_behavior.initial_prompt_fulfillment.messages * Page.form.parameters.fill_behavior.initial_prompt_fulfillment.conditional_cases * Page.form.parameters.fill_behavior.reprompt_event_handlers.messages * Page.form.parameters.fill_behavior.reprompt_event_handlers.conditional_cases * Page.transition_routes.trigger_fulfillment.messages * Page.transition_routes.trigger_fulfillment.conditional_cases * If not specified, the agent's default language is used. Many languages are supported. Note: languages must be enabled in the agent before they can be used. */ languageCode?: pulumi.Input<string>; /** * The flow to create a page for. * Format: projects/<Project ID>/locations/<Location ID>/agents/<Agent ID>/flows/<Flow ID>. */ parent?: pulumi.Input<string>; /** * Ordered list of TransitionRouteGroups associated with the page. Transition route groups must be unique within a page. * If multiple transition routes within a page scope refer to the same intent, then the precedence order is: page's transition route > page's transition route group > flow's transition routes. * If multiple transition route groups within a page contain the same intent, then the first group in the ordered list takes precedence. * Format:projects/<Project ID>/locations/<Location ID>/agents/<Agent ID>/flows/<Flow ID>/transitionRouteGroups/<TransitionRouteGroup ID>. */ transitionRouteGroups?: pulumi.Input<pulumi.Input<string>[]>; /** * A list of transitions for the transition rules of this page. They route the conversation to another page in the same flow, or another flow. * When we are in a certain page, the TransitionRoutes are evalauted in the following order: * TransitionRoutes defined in the page with intent specified. * TransitionRoutes defined in the transition route groups with intent specified. * TransitionRoutes defined in flow with intent specified. * TransitionRoutes defined in the transition route groups with intent specified. * TransitionRoutes defined in the page with only condition specified. * TransitionRoutes defined in the transition route groups with only condition specified. * Structure is documented below. */ transitionRoutes?: pulumi.Input<pulumi.Input<inputs.diagflow.CxPageTransitionRoute>[]>; }
the_stack
import 'mocha' import { BigNumber } from 'bignumber.js' import { assert } from 'chai' import { XrpUtils, XrplNetwork, XrpClient } from '../../../src' import XrpTestUtils from '../../XRP/helpers/xrp-test-utils' import bigInt from 'big-integer' describe('xrp-drops-conversion', function (): void { // randomWalletFromFaucet it('randomWalletFromFaucet - success', async function (): Promise<void> { // GIVEN a new, randomly generated wallet that is funded by the Testnet faucet const wallet = await XrpTestUtils.randomWalletFromFaucet() // WHEN the wallet is examined // THEN it exists assert.isNotNull(wallet) // AND it has a non-zero balance const xrpClient = new XrpClient( 'test.xrp.xpring.io:50051', XrplNetwork.Test, ) const balance = await xrpClient.getBalance(wallet.getAddress()) assert.isTrue(balance > bigInt('0')) }) // xrpToDrops and dropsToXrp tests it('dropsToXrp() - works with a typical amount', function (): void { // GIVEN a typical, valid drops value, WHEN converted to xrp const xrp = XrpUtils.dropsToXrp('2000000') // THEN the conversion is as expected assert.strictEqual(xrp, '2', '2 million drops equals 2 XRP') }) it('dropsToXrp() - works with fractions', function (): void { // GIVEN drops amounts that convert to fractional xrp amounts // WHEN converted to xrp THEN the conversion is as expected let xrp = XrpUtils.dropsToXrp('3456789') assert.strictEqual(xrp, '3.456789', '3,456,789 drops equals 3.456789 XRP') xrp = XrpUtils.dropsToXrp('3400000') assert.strictEqual(xrp, '3.4', '3,400,000 drops equals 3.4 XRP') xrp = XrpUtils.dropsToXrp('1') assert.strictEqual(xrp, '0.000001', '1 drop equals 0.000001 XRP') xrp = XrpUtils.dropsToXrp('1.0') assert.strictEqual(xrp, '0.000001', '1.0 drops equals 0.000001 XRP') xrp = XrpUtils.dropsToXrp('1.00') assert.strictEqual(xrp, '0.000001', '1.00 drops equals 0.000001 XRP') }) it('dropsToXrp() - works with zero', function (): void { // GIVEN several equivalent representations of zero // WHEN converted to xrp, THEN the result is zero let xrp = XrpUtils.dropsToXrp('0') assert.strictEqual(xrp, '0', '0 drops equals 0 XRP') // negative zero is equivalent to zero xrp = XrpUtils.dropsToXrp('-0') assert.strictEqual(xrp, '0', '-0 drops equals 0 XRP') xrp = XrpUtils.dropsToXrp('0.00') assert.strictEqual(xrp, '0', '0.00 drops equals 0 XRP') xrp = XrpUtils.dropsToXrp('000000000') assert.strictEqual(xrp, '0', '000000000 drops equals 0 XRP') }) it('dropsToXrp() - works with a negative value', function (): void { // GIVEN a negative drops amount // WHEN converted to xrp const xrp = XrpUtils.dropsToXrp('-2000000') // THEN the conversion is also negative assert.strictEqual(xrp, '-2', '-2 million drops equals -2 XRP') }) it('dropsToXrp() - works with a value ending with a decimal point', function (): void { // GIVEN a positive or negative drops amount that ends with a decimal point // WHEN converted to xrp THEN the conversion is successful and correct let xrp = XrpUtils.dropsToXrp('2000000.') assert.strictEqual(xrp, '2', '2000000. drops equals 2 XRP') xrp = XrpUtils.dropsToXrp('-2000000.') assert.strictEqual(xrp, '-2', '-2000000. drops equals -2 XRP') }) it('dropsToXrp() - works with BigNumber objects', function (): void { // GIVEN drops amounts represented as BigNumber objects // WHEN converted to xrp THEN the conversions are correct and successful let xrp = XrpUtils.dropsToXrp(new BigNumber(2000000)) assert.strictEqual(xrp, '2', '(BigNumber) 2 million drops equals 2 XRP') xrp = XrpUtils.dropsToXrp(new BigNumber(-2000000)) assert.strictEqual(xrp, '-2', '(BigNumber) -2 million drops equals -2 XRP') xrp = XrpUtils.dropsToXrp(new BigNumber(2345678)) assert.strictEqual( xrp, '2.345678', '(BigNumber) 2,345,678 drops equals 2.345678 XRP', ) xrp = XrpUtils.dropsToXrp(new BigNumber(-2345678)) assert.strictEqual( xrp, '-2.345678', '(BigNumber) -2,345,678 drops equals -2.345678 XRP', ) }) it('dropsToXrp() - works with a number', function (): void { // This is not recommended. Use strings or BigNumber objects to avoid precision errors. // GIVEN a drops amount represented as a positive or negative number // WHEN converted to xrp THEN the conversion is correct and successful let xrp = XrpUtils.dropsToXrp(2000000) assert.strictEqual(xrp, '2', '(number) 2 million drops equals 2 XRP') xrp = XrpUtils.dropsToXrp(-2000000) assert.strictEqual(xrp, '-2', '(number) -2 million drops equals -2 XRP') }) it('dropsToXrp() - throws with an amount with too many decimal places', function (): void { assert.throws(() => { XrpUtils.dropsToXrp('1.2') }, /has too many decimal places/u) assert.throws(() => { XrpUtils.dropsToXrp('0.10') }, /has too many decimal places/u) }) it('dropsToXrp() - throws with an invalid value', function (): void { // GIVEN invalid drops values, WHEN converted to xrp, THEN an error is thrown assert.throws(() => { XrpUtils.dropsToXrp('FOO') }, /invalid value/u) assert.throws(() => { XrpUtils.dropsToXrp('1e-7') }, /invalid value/u) assert.throws(() => { XrpUtils.dropsToXrp('2,0') }, /invalid value/u) assert.throws(() => { XrpUtils.dropsToXrp('.') }, /dropsToXrp: invalid value '\.', should be a BigNumber or string-encoded number\./u) }) it('dropsToXrp() - throws with an amount more than one decimal point', function (): void { // GIVEN invalid drops values that contain more than one decimal point // WHEN converted to xrp THEN an error is thrown assert.throws(() => { XrpUtils.dropsToXrp('1.0.0') }, /dropsToXrp: invalid value '1\.0\.0'/u) assert.throws(() => { XrpUtils.dropsToXrp('...') }, /dropsToXrp: invalid value '\.\.\.'/u) }) it('xrpToDrops() - works with a typical amount', function (): void { // GIVEN an xrp amoun that is typical and valid // WHEN converted to drops const drops = XrpUtils.xrpToDrops('2') // THEN the conversion is successful and correct assert.strictEqual(drops, '2000000', '2 XRP equals 2 million drops') }) it('xrpToDrops() - works with fractions', function (): void { // GIVEN xrp amounts that are fractional // WHEN converted to drops THEN the conversions are successful and correct let drops = XrpUtils.xrpToDrops('3.456789') assert.strictEqual(drops, '3456789', '3.456789 XRP equals 3,456,789 drops') drops = XrpUtils.xrpToDrops('3.400000') assert.strictEqual(drops, '3400000', '3.400000 XRP equals 3,400,000 drops') drops = XrpUtils.xrpToDrops('0.000001') assert.strictEqual(drops, '1', '0.000001 XRP equals 1 drop') drops = XrpUtils.xrpToDrops('0.0000010') assert.strictEqual(drops, '1', '0.0000010 XRP equals 1 drop') }) it('xrpToDrops() - works with zero', function (): void { // GIVEN xrp amounts that are various equivalent representations of zero // WHEN converted to drops THEN the conversions are equal to zero let drops = XrpUtils.xrpToDrops('0') assert.strictEqual(drops, '0', '0 XRP equals 0 drops') // Negative zero is equivalent to zero drops = XrpUtils.xrpToDrops('-0') assert.strictEqual(drops, '0', '-0 XRP equals 0 drops') drops = XrpUtils.xrpToDrops('0.000000') assert.strictEqual(drops, '0', '0.000000 XRP equals 0 drops') drops = XrpUtils.xrpToDrops('0.0000000') assert.strictEqual(drops, '0', '0.0000000 XRP equals 0 drops') }) it('xrpToDrops() - works with a negative value', function (): void { // GIVEN a negative xrp amount // WHEN converted to drops THEN the conversion is also negative const drops = XrpUtils.xrpToDrops('-2') assert.strictEqual(drops, '-2000000', '-2 XRP equals -2 million drops') }) it('xrpToDrops() - works with a value ending with a decimal point', function (): void { // GIVEN an xrp amount that ends with a decimal point // WHEN converted to drops THEN the conversion is correct and successful let drops = XrpUtils.xrpToDrops('2.') assert.strictEqual(drops, '2000000', '2. XRP equals 2000000 drops') drops = XrpUtils.xrpToDrops('-2.') assert.strictEqual(drops, '-2000000', '-2. XRP equals -2000000 drops') }) it('xrpToDrops() - works with BigNumber objects', function (): void { // GIVEN an xrp amount represented as a BigNumber object // WHEN converted to drops THEN the conversion is correct and successful let drops = XrpUtils.xrpToDrops(new BigNumber(2)) assert.strictEqual( drops, '2000000', '(BigNumber) 2 XRP equals 2 million drops', ) drops = XrpUtils.xrpToDrops(new BigNumber(-2)) assert.strictEqual( drops, '-2000000', '(BigNumber) -2 XRP equals -2 million drops', ) }) it('xrpToDrops() - works with a number', function (): void { // This is not recommended. Use strings or BigNumber objects to avoid precision errors. // GIVEN an xrp amounts represented as a number (positive and negative) // WHEN converted to drops THEN the conversions are successful and correct let drops = XrpUtils.xrpToDrops(2) assert.strictEqual( drops, '2000000', '(number) 2 XRP equals 2 million drops', ) drops = XrpUtils.xrpToDrops(-2) assert.strictEqual( drops, '-2000000', '(number) -2 XRP equals -2 million drops', ) }) it('xrpToDrops() - throws with an amount with too many decimal places', function (): void { // GIVEN an xrp amount with too many decimal places // WHEN converted to a drops amount THEN an error is thrown assert.throws(() => { XrpUtils.xrpToDrops('1.1234567') }, /has too many decimal places/u) assert.throws(() => { XrpUtils.xrpToDrops('0.0000001') }, /has too many decimal places/u) }) it('xrpToDrops() - throws with an invalid value', function (): void { // GIVEN xrp amounts represented as various invalid values // WHEN converted to drops THEN an error is thrown assert.throws(() => { XrpUtils.xrpToDrops('FOO') }, /invalid value/u) assert.throws(() => { XrpUtils.xrpToDrops('1e-7') }, /invalid value/u) assert.throws(() => { XrpUtils.xrpToDrops('2,0') }, /invalid value/u) assert.throws(() => { XrpUtils.xrpToDrops('.') }, /xrpToDrops: invalid value '\.', should be a BigNumber or string-encoded number\./u) }) it('xrpToDrops() - throws with an amount more than one decimal point', function (): void { // GIVEN an xrp amount with more than one decimal point, or all decimal points // WHEN converted to drops THEN an error is thrown assert.throws(() => { XrpUtils.xrpToDrops('1.0.0') }, /xrpToDrops: invalid value '1\.0\.0'/u) assert.throws(() => { XrpUtils.xrpToDrops('...') }, /xrpToDrops: invalid value '\.\.\.'/u) }) })
the_stack
import { join, resolve } from 'path'; import { accessSync, readJSONSync, statSync } from 'fs-extra'; import { Logger } from '../logger/logger'; import { BuildContext, TaskInfo } from './interfaces'; import { getBooleanPropertyValue, objectAssign } from './helpers'; import { FileCache } from './file-cache'; import * as Constants from './constants'; /** * Create a context object which is used by all the build tasks. * Filling the config data uses the following hierarchy, which will * keep going down the list until it, or if it, finds data. * * 1) Get from the passed in context variable * 2) Get from the config file set using the command-line args * 3) Get from environment variable * 4) Get from package.json config property * 5) Get environment variables * * Lastly, Ionic's default configs will always fill in any data * which is missing from the user's data. */ export function generateContext(context?: BuildContext): BuildContext { if (!context) { context = {}; } if (!context.fileCache) { context.fileCache = new FileCache(); } context.isProd = [ context.isProd, hasArg('--prod') ].find(val => typeof val === 'boolean'); setProcessEnvVar(Constants.ENV_VAR_IONIC_ENV, (context.isProd ? Constants.ENV_VAR_PROD : Constants.ENV_VAR_DEV)); // If context is prod then the following flags must be set to true context.runAot = [ context.runAot, context.isProd || hasArg('--aot'), ].find(val => typeof val === 'boolean'); context.runMinifyJs = [ context.runMinifyJs, context.isProd || hasArg('--minifyJs') ].find(val => typeof val === 'boolean'); context.runMinifyCss = [ context.runMinifyCss, context.isProd || hasArg('--minifyCss') ].find(val => typeof val === 'boolean'); context.optimizeJs = [ context.optimizeJs, context.isProd || hasArg('--optimizeJs') ].find(val => typeof val === 'boolean'); if (typeof context.isWatch !== 'boolean') { context.isWatch = hasArg('--watch'); } setProcessEnvVar(Constants.ENV_VAR_IONIC_AOT, `${context.runAot}`); Logger.debug(`${Constants.ENV_VAR_IONIC_AOT} set to ${context.runAot}`); setProcessEnvVar(Constants.ENV_VAR_IONIC_MINIFY_JS, `${context.runMinifyJs}`); Logger.debug(`${Constants.ENV_VAR_IONIC_MINIFY_JS} set to ${context.runMinifyJs}`); setProcessEnvVar(Constants.ENV_VAR_IONIC_MINIFY_CSS, `${context.runMinifyCss}`); Logger.debug(`${Constants.ENV_VAR_IONIC_MINIFY_CSS} set to ${context.runMinifyCss}`); setProcessEnvVar(Constants.ENV_VAR_IONIC_OPTIMIZE_JS, `${context.optimizeJs}`); Logger.debug(`${Constants.ENV_VAR_IONIC_OPTIMIZE_JS} set to ${context.optimizeJs}`); setProcessEnvVar(Constants.ENV_VAR_IONIC_MINIFY_JS, `${context.runMinifyJs}`); Logger.debug(`${Constants.ENV_VAR_IONIC_MINIFY_JS} set to ${context.runMinifyJs}`); context.rootDir = resolve(context.rootDir || getConfigValue(context, '--rootDir', null, Constants.ENV_VAR_ROOT_DIR, Constants.ENV_VAR_ROOT_DIR.toLowerCase(), processCwd)); setProcessEnvVar(Constants.ENV_VAR_ROOT_DIR, context.rootDir); Logger.debug(`rootDir set to ${context.rootDir}`); context.tmpDir = resolve(context.tmpDir || getConfigValue(context, '--tmpDir', null, Constants.ENV_VAR_TMP_DIR, Constants.ENV_VAR_TMP_DIR.toLowerCase(), join(context.rootDir, Constants.TMP_DIR))); setProcessEnvVar(Constants.ENV_VAR_TMP_DIR, context.tmpDir); Logger.debug(`tmpDir set to ${context.tmpDir}`); context.srcDir = resolve(context.srcDir || getConfigValue(context, '--srcDir', null, Constants.ENV_VAR_SRC_DIR, Constants.ENV_VAR_SRC_DIR.toLowerCase(), join(context.rootDir, Constants.SRC_DIR))); setProcessEnvVar(Constants.ENV_VAR_SRC_DIR, context.srcDir); Logger.debug(`srcDir set to ${context.srcDir}`); const deepLinksDir = resolve(getConfigValue(context, '--deepLinksDir', null, Constants.ENV_VAR_DEEPLINKS_DIR, Constants.ENV_VAR_DEEPLINKS_DIR.toLowerCase(), context.srcDir)); setProcessEnvVar(Constants.ENV_VAR_DEEPLINKS_DIR, deepLinksDir); Logger.debug(`deepLinksDir set to ${deepLinksDir}`); context.wwwDir = resolve(context.wwwDir || getConfigValue(context, '--wwwDir', null, Constants.ENV_VAR_WWW_DIR, Constants.ENV_VAR_WWW_DIR.toLowerCase(), join(context.rootDir, Constants.WWW_DIR))); setProcessEnvVar(Constants.ENV_VAR_WWW_DIR, context.wwwDir); Logger.debug(`wwwDir set to ${context.wwwDir}`); context.wwwIndex = getConfigValue(context, '--wwwIndex', null, Constants.ENV_VAR_HTML_TO_SERVE, Constants.ENV_VAR_HTML_TO_SERVE.toLowerCase(), 'index.html'); setProcessEnvVar(Constants.ENV_VAR_HTML_TO_SERVE, context.wwwIndex); Logger.debug(`wwwIndex set to ${context.wwwIndex}`); context.buildDir = resolve(context.buildDir || getConfigValue(context, '--buildDir', null, Constants.ENV_VAR_BUILD_DIR, Constants.ENV_VAR_BUILD_DIR.toLowerCase(), join(context.wwwDir, Constants.BUILD_DIR))); setProcessEnvVar(Constants.ENV_VAR_BUILD_DIR, context.buildDir); Logger.debug(`buildDir set to ${context.buildDir}`); const fontsDir = resolve(getConfigValue(context, '--fontsDir', null, Constants.ENV_VAR_FONTS_DIR, Constants.ENV_VAR_FONTS_DIR.toLowerCase(), join(context.wwwDir, 'assets', 'fonts'))); setProcessEnvVar(Constants.ENV_VAR_FONTS_DIR, fontsDir); Logger.debug(`fontsDir set to ${fontsDir}`); context.sourcemapDir = resolve(context.sourcemapDir || getConfigValue(context, '--sourcemapDir', null, Constants.ENV_VAR_SOURCEMAP_DIR, Constants.ENV_VAR_SOURCEMAP_DIR.toLowerCase(), Constants.SOURCEMAP_DIR)); setProcessEnvVar(Constants.ENV_VAR_SOURCEMAP_DIR, context.sourcemapDir); Logger.debug(`sourcemapDir set to ${context.sourcemapDir}`); context.pagesDir = resolve(context.pagesDir || getConfigValue(context, '--pagesDir', null, Constants.ENV_VAR_PAGES_DIR, Constants.ENV_VAR_PAGES_DIR.toLowerCase(), join(context.srcDir, 'pages'))); setProcessEnvVar(Constants.ENV_VAR_PAGES_DIR, context.pagesDir); Logger.debug(`pagesDir set to ${context.pagesDir}`); context.componentsDir = resolve(context.componentsDir || getConfigValue(context, '--componentsDir', null, Constants.ENV_VAR_COMPONENTS_DIR, Constants.ENV_VAR_COMPONENTS_DIR.toLowerCase(), join(context.srcDir, 'components'))); setProcessEnvVar(Constants.ENV_VAR_COMPONENTS_DIR, context.componentsDir); Logger.debug(`componentsDir set to ${context.componentsDir}`); context.directivesDir = resolve(context.directivesDir || getConfigValue(context, '--directivesDir', null, Constants.ENV_VAR_DIRECTIVES_DIR, Constants.ENV_VAR_DIRECTIVES_DIR.toLowerCase(), join(context.srcDir, 'directives'))); setProcessEnvVar(Constants.ENV_VAR_DIRECTIVES_DIR, context.directivesDir); Logger.debug(`directivesDir set to ${context.directivesDir}`); context.pipesDir = resolve(context.pipesDir || getConfigValue(context, '--pipesDir', null, Constants.ENV_VAR_PIPES_DIR, Constants.ENV_VAR_PIPES_DIR.toLowerCase(), join(context.srcDir, 'pipes'))); setProcessEnvVar(Constants.ENV_VAR_PIPES_DIR, context.pipesDir); Logger.debug(`pipesDir set to ${context.pipesDir}`); context.providersDir = resolve(context.providersDir || getConfigValue(context, '--providersDir', null, Constants.ENV_VAR_PROVIDERS_DIR, Constants.ENV_VAR_PROVIDERS_DIR.toLowerCase(), join(context.srcDir, 'providers'))); setProcessEnvVar(Constants.ENV_VAR_PROVIDERS_DIR, context.providersDir); Logger.debug(`providersDir set to ${context.providersDir}`); context.nodeModulesDir = join(context.rootDir, Constants.NODE_MODULES); setProcessEnvVar(Constants.ENV_VAR_NODE_MODULES_DIR, context.nodeModulesDir); Logger.debug(`nodeModulesDir set to ${context.nodeModulesDir}`); context.ionicAngularDir = resolve(context.ionicAngularDir || getConfigValue(context, '--ionicAngularDir', null, Constants.ENV_VAR_IONIC_ANGULAR_DIR, Constants.ENV_VAR_IONIC_ANGULAR_DIR.toLowerCase(), join(context.nodeModulesDir, Constants.IONIC_ANGULAR))); setProcessEnvVar(Constants.ENV_VAR_IONIC_ANGULAR_DIR, context.ionicAngularDir); Logger.debug(`ionicAngularDir set to ${context.ionicAngularDir}`); const angularDir = resolve(getConfigValue(context, '--angularDir', null, Constants.ENV_VAR_ANGULAR_CORE_DIR, Constants.ENV_VAR_ANGULAR_CORE_DIR.toLowerCase(), join(context.nodeModulesDir, Constants.AT_ANGULAR, 'core'))); setProcessEnvVar(Constants.ENV_VAR_ANGULAR_CORE_DIR, angularDir); Logger.debug(`angularDir set to ${angularDir}`); context.angularCoreDir = angularDir; const typescriptDir = resolve(getConfigValue(context, '--typescriptDir', null, Constants.ENV_VAR_TYPESCRIPT_DIR, Constants.ENV_VAR_TYPESCRIPT_DIR.toLowerCase(), join(context.nodeModulesDir, Constants.TYPESCRIPT))); setProcessEnvVar(Constants.ENV_VAR_TYPESCRIPT_DIR, typescriptDir); Logger.debug(`typescriptDir set to ${typescriptDir}`); context.typescriptDir = typescriptDir; const defaultCoreCompilerFilePath = join(context.ionicAngularDir, 'compiler'); context.coreCompilerFilePath = resolve(context.coreCompilerFilePath || getConfigValue(context, '--coreCompilerFilePath', null, Constants.ENV_VAR_CORE_COMPILER_FILE_PATH, Constants.ENV_VAR_CORE_COMPILER_FILE_PATH.toLowerCase(), defaultCoreCompilerFilePath)); setProcessEnvVar(Constants.ENV_VAR_CORE_COMPILER_FILE_PATH, context.coreCompilerFilePath); Logger.debug(`coreCompilerFilePath set to ${context.coreCompilerFilePath}`); const defaultCoreDir = context.ionicAngularDir; context.coreDir = resolve(context.coreDir || getConfigValue(context, '--coreDir', null, Constants.ENV_VAR_CORE_DIR, Constants.ENV_VAR_CORE_DIR.toLowerCase(), defaultCoreDir)); setProcessEnvVar(Constants.ENV_VAR_CORE_DIR, context.coreDir); Logger.debug(`coreDir set to ${context.coreDir}`); const rxjsDir = resolve(getConfigValue(context, '--rxjsDir', null, Constants.ENV_VAR_RXJS_DIR, Constants.ENV_VAR_RXJS_DIR.toLowerCase(), join(context.nodeModulesDir, Constants.RXJS))); setProcessEnvVar(Constants.ENV_VAR_RXJS_DIR, rxjsDir); Logger.debug(`rxjsDir set to ${rxjsDir}`); const ionicAngularTemplatesDir = join(context.ionicAngularDir, 'templates'); setProcessEnvVar(Constants.ENV_VAR_IONIC_ANGULAR_TEMPLATE_DIR, ionicAngularTemplatesDir); Logger.debug(`ionicAngularTemplatesDir set to ${ionicAngularTemplatesDir}`); context.platform = getConfigValue(context, '--platform', null, Constants.ENV_VAR_PLATFORM, null, null); setProcessEnvVar(Constants.ENV_VAR_PLATFORM, context.platform); Logger.debug(`platform set to ${context.platform}`); context.target = getConfigValue(context, '--target', null, Constants.ENV_VAR_TARGET, null, null); setProcessEnvVar(Constants.ENV_VAR_TARGET, context.target); Logger.debug(`target set to ${context.target}`); const ionicAngularEntryPoint = resolve(getConfigValue(context, '--ionicAngularEntryPoint', null, Constants.ENV_VAR_IONIC_ANGULAR_ENTRY_POINT, Constants.ENV_VAR_IONIC_ANGULAR_ENTRY_POINT.toLowerCase(), join(context.ionicAngularDir, 'index.js'))); setProcessEnvVar(Constants.ENV_VAR_IONIC_ANGULAR_ENTRY_POINT, ionicAngularEntryPoint); Logger.debug(`ionicAngularEntryPoint set to ${ionicAngularEntryPoint}`); const appScriptsDir = join(__dirname, '..', '..'); setProcessEnvVar(Constants.ENV_VAR_APP_SCRIPTS_DIR, appScriptsDir); Logger.debug(`appScriptsDir set to ${appScriptsDir}`); const generateSourceMap = getConfigValue(context, '--generateSourceMap', null, Constants.ENV_VAR_GENERATE_SOURCE_MAP, Constants.ENV_VAR_GENERATE_SOURCE_MAP.toLowerCase(), context.isProd || context.runMinifyJs ? null : 'true'); setProcessEnvVar(Constants.ENV_VAR_GENERATE_SOURCE_MAP, generateSourceMap); Logger.debug(`generateSourceMap set to ${generateSourceMap}`); const sourceMapTypeValue = getConfigValue(context, '--sourceMapType', null, Constants.ENV_VAR_SOURCE_MAP_TYPE, Constants.ENV_VAR_SOURCE_MAP_TYPE.toLowerCase(), Constants.SOURCE_MAP_TYPE_EXPENSIVE); setProcessEnvVar(Constants.ENV_VAR_SOURCE_MAP_TYPE, sourceMapTypeValue); Logger.debug(`sourceMapType set to ${sourceMapTypeValue}`); const moveSourceMaps = getConfigValue(context, '--moveSourceMaps', null, Constants.ENV_VAR_MOVE_SOURCE_MAPS, Constants.ENV_VAR_MOVE_SOURCE_MAPS.toLowerCase(), 'true'); setProcessEnvVar(Constants.ENV_VAR_MOVE_SOURCE_MAPS, moveSourceMaps); Logger.debug(`moveSourceMaps set to ${moveSourceMaps}`); const tsConfigPathValue = resolve(getConfigValue(context, '--tsconfig', null, Constants.ENV_TS_CONFIG, Constants.ENV_TS_CONFIG.toLowerCase(), join(context.rootDir, 'tsconfig.json'))); setProcessEnvVar(Constants.ENV_TS_CONFIG, tsConfigPathValue); Logger.debug(`tsconfig set to ${tsConfigPathValue}`); const readConfigJson = getConfigValue(context, '--readConfigJson', null, Constants.ENV_READ_CONFIG_JSON, Constants.ENV_READ_CONFIG_JSON.toLowerCase(), 'true'); setProcessEnvVar(Constants.ENV_READ_CONFIG_JSON, readConfigJson); Logger.debug(`readConfigJson set to ${readConfigJson}`); const appEntryPointPathValue = resolve(getConfigValue(context, '--appEntryPoint', null, Constants.ENV_APP_ENTRY_POINT, Constants.ENV_APP_ENTRY_POINT.toLowerCase(), join(context.srcDir, 'app', 'main.ts'))); setProcessEnvVar(Constants.ENV_APP_ENTRY_POINT, appEntryPointPathValue); Logger.debug(`appEntryPoint set to ${appEntryPointPathValue}`); context.appNgModulePath = resolve(getConfigValue(context, '--appNgModulePath', null, Constants.ENV_APP_NG_MODULE_PATH, Constants.ENV_APP_NG_MODULE_PATH.toLowerCase(), join(context.srcDir, 'app', 'app.module.ts'))); setProcessEnvVar(Constants.ENV_APP_NG_MODULE_PATH, context.appNgModulePath); Logger.debug(`appNgModulePath set to ${context.appNgModulePath}`); context.componentsNgModulePath = resolve(getConfigValue(context, '--componentsNgModulePath', null, Constants.ENV_COMPONENTS_NG_MODULE_PATH, Constants.ENV_COMPONENTS_NG_MODULE_PATH.toLowerCase(), join(context.srcDir, 'components', 'components.module.ts'))); setProcessEnvVar(Constants.ENV_COMPONENTS_NG_MODULE_PATH, context.componentsNgModulePath); Logger.debug(`componentsNgModulePath set to ${context.componentsNgModulePath}`); context.pipesNgModulePath = resolve(getConfigValue(context, '--pipesNgModulePath', null, Constants.ENV_PIPES_NG_MODULE_PATH, Constants.ENV_PIPES_NG_MODULE_PATH.toLowerCase(), join(context.srcDir, 'pipes', 'pipes.module.ts'))); setProcessEnvVar(Constants.ENV_PIPES_NG_MODULE_PATH, context.pipesNgModulePath); Logger.debug(`pipesNgModulePath set to ${context.pipesNgModulePath}`); context.directivesNgModulePath = resolve(getConfigValue(context, '--directivesNgModulePath', null, Constants.ENV_DIRECTIVES_NG_MODULE_PATH, Constants.ENV_DIRECTIVES_NG_MODULE_PATH.toLowerCase(), join(context.srcDir, 'directives', 'directives.module.ts'))); setProcessEnvVar(Constants.ENV_DIRECTIVES_NG_MODULE_PATH, context.directivesNgModulePath); Logger.debug(`directivesNgModulePath set to ${context.directivesNgModulePath}`); const appNgModuleClass = getConfigValue(context, '--appNgModuleClass', null, Constants.ENV_APP_NG_MODULE_CLASS, Constants.ENV_APP_NG_MODULE_CLASS.toLowerCase(), 'AppModule'); setProcessEnvVar(Constants.ENV_APP_NG_MODULE_CLASS, appNgModuleClass); Logger.debug(`appNgModuleClass set to ${appNgModuleClass}`); const pathToGlobUtil = join(getProcessEnvVar(Constants.ENV_VAR_APP_SCRIPTS_DIR), 'dist', 'util', 'glob-util.js'); setProcessEnvVar(Constants.ENV_GLOB_UTIL, pathToGlobUtil); Logger.debug(`pathToGlobUtil set to ${pathToGlobUtil}`); const cleanBeforeCopy = getConfigValue(context, '--cleanBeforeCopy', null, Constants.ENV_CLEAN_BEFORE_COPY, Constants.ENV_CLEAN_BEFORE_COPY.toLowerCase(), null); setProcessEnvVar(Constants.ENV_CLEAN_BEFORE_COPY, cleanBeforeCopy); Logger.debug(`cleanBeforeCopy set to ${cleanBeforeCopy}`); context.outputJsFileName = getConfigValue(context, '--outputJsFileName', null, Constants.ENV_OUTPUT_JS_FILE_NAME, Constants.ENV_OUTPUT_JS_FILE_NAME.toLowerCase(), 'main.js'); setProcessEnvVar(Constants.ENV_OUTPUT_JS_FILE_NAME, context.outputJsFileName); Logger.debug(`outputJsFileName set to ${context.outputJsFileName}`); context.outputCssFileName = getConfigValue(context, '--outputCssFileName', null, Constants.ENV_OUTPUT_CSS_FILE_NAME, Constants.ENV_OUTPUT_CSS_FILE_NAME.toLowerCase(), 'main.css'); setProcessEnvVar(Constants.ENV_OUTPUT_CSS_FILE_NAME, context.outputCssFileName); Logger.debug(`outputCssFileName set to ${context.outputCssFileName}`); const webpackFactoryPath = join(getProcessEnvVar(Constants.ENV_VAR_APP_SCRIPTS_DIR), 'dist', 'webpack', 'ionic-webpack-factory.js'); setProcessEnvVar(Constants.ENV_WEBPACK_FACTORY, webpackFactoryPath); Logger.debug(`webpackFactoryPath set to ${webpackFactoryPath}`); const webpackLoaderPath = join(getProcessEnvVar(Constants.ENV_VAR_APP_SCRIPTS_DIR), 'dist', 'webpack', 'loader.js'); setProcessEnvVar(Constants.ENV_WEBPACK_LOADER, webpackLoaderPath); Logger.debug(`webpackLoaderPath set to ${webpackLoaderPath}`); const cacheLoaderPath = join(getProcessEnvVar(Constants.ENV_VAR_APP_SCRIPTS_DIR), 'dist', 'webpack', 'cache-loader.js'); setProcessEnvVar(Constants.ENV_CACHE_LOADER, cacheLoaderPath); Logger.debug(`cacheLoaderPath set to ${cacheLoaderPath}`); const aotWriteToDisk = getConfigValue(context, '--aotWriteToDisk', null, Constants.ENV_AOT_WRITE_TO_DISK, Constants.ENV_AOT_WRITE_TO_DISK.toLowerCase(), null); setProcessEnvVar(Constants.ENV_AOT_WRITE_TO_DISK, aotWriteToDisk); Logger.debug(`aotWriteToDisk set to ${aotWriteToDisk}`); const printWebpackDependencyTree = getConfigValue(context, '--printWebpackDependencyTree', null, Constants.ENV_PRINT_WEBPACK_DEPENDENCY_TREE, Constants.ENV_PRINT_WEBPACK_DEPENDENCY_TREE.toLowerCase(), null); setProcessEnvVar(Constants.ENV_PRINT_WEBPACK_DEPENDENCY_TREE, printWebpackDependencyTree); Logger.debug(`printWebpackDependencyTree set to ${printWebpackDependencyTree}`); const typeCheckOnLint = getConfigValue(context, '--typeCheckOnLint', null, Constants.ENV_TYPE_CHECK_ON_LINT, Constants.ENV_TYPE_CHECK_ON_LINT.toLowerCase(), null); setProcessEnvVar(Constants.ENV_TYPE_CHECK_ON_LINT, typeCheckOnLint); Logger.debug(`typeCheckOnLint set to ${typeCheckOnLint}`); const bailOnLintError = getConfigValue(context, '--bailOnLintError', null, Constants.ENV_BAIL_ON_LINT_ERROR, Constants.ENV_BAIL_ON_LINT_ERROR.toLowerCase(), null); setProcessEnvVar(Constants.ENV_BAIL_ON_LINT_ERROR, bailOnLintError); Logger.debug(`bailOnLintError set to ${bailOnLintError}`); const enableLint = getConfigValue(context, '--enableLint', null, Constants.ENV_ENABLE_LINT, Constants.ENV_ENABLE_LINT.toLowerCase(), 'true'); setProcessEnvVar(Constants.ENV_ENABLE_LINT, enableLint); Logger.debug(`enableLint set to ${enableLint}`); const disableLogging = getConfigValue(context, '--disableLogging', null, Constants.ENV_DISABLE_LOGGING, Constants.ENV_DISABLE_LOGGING.toLowerCase(), null); setProcessEnvVar(Constants.ENV_DISABLE_LOGGING, disableLogging); Logger.debug(`disableLogging set to ${disableLogging}`); const startWatchTimeout = getConfigValue(context, '--startWatchTimeout', null, Constants.ENV_START_WATCH_TIMEOUT, Constants.ENV_START_WATCH_TIMEOUT.toLowerCase(), '3000'); setProcessEnvVar(Constants.ENV_START_WATCH_TIMEOUT, startWatchTimeout); Logger.debug(`startWatchTimeout set to ${startWatchTimeout}`); const ngModuleFileNameSuffix = getConfigValue(context, '--ngModuleFileNameSuffix', null, Constants.ENV_NG_MODULE_FILE_NAME_SUFFIX, Constants.ENV_NG_MODULE_FILE_NAME_SUFFIX.toLowerCase(), '.module.ts'); setProcessEnvVar(Constants.ENV_NG_MODULE_FILE_NAME_SUFFIX, ngModuleFileNameSuffix); Logger.debug(`ngModuleFileNameSuffix set to ${ngModuleFileNameSuffix}`); const polyfillName = getConfigValue(context, '--polyfillFileName', null, Constants.ENV_POLYFILL_FILE_NAME, Constants.ENV_POLYFILL_FILE_NAME.toLowerCase(), 'polyfills.js'); setProcessEnvVar(Constants.ENV_POLYFILL_FILE_NAME, polyfillName); Logger.debug(`polyfillName set to ${polyfillName}`); const purgeUnusedFonts = getConfigValue(context, '--purgeUnusedFonts', null, Constants.ENV_PURGE_UNUSED_FONTS, Constants.ENV_PURGE_UNUSED_FONTS.toLowerCase(), 'true'); setProcessEnvVar(Constants.ENV_PURGE_UNUSED_FONTS, purgeUnusedFonts); Logger.debug(`purgeUnusedFonts set to ${purgeUnusedFonts}`); /* Provider Path Stuff */ setProcessEnvVar(Constants.ENV_ACTION_SHEET_CONTROLLER_CLASSNAME, 'ActionSheetController'); setProcessEnvVar(Constants.ENV_ACTION_SHEET_CONTROLLER_PATH, join(context.ionicAngularDir, 'components', 'action-sheet', 'action-sheet-controller.js')); setProcessEnvVar(Constants.ENV_ACTION_SHEET_VIEW_CONTROLLER_PATH, join(context.ionicAngularDir, 'components', 'action-sheet', 'action-sheet.js')); setProcessEnvVar(Constants.ENV_ACTION_SHEET_COMPONENT_PATH, join(context.ionicAngularDir, 'components', 'action-sheet', 'action-sheet-component.js')); setProcessEnvVar(Constants.ENV_ACTION_SHEET_COMPONENT_FACTORY_PATH, join(context.ionicAngularDir, 'components', 'action-sheet', 'action-sheet-component.ngfactory.js')); setProcessEnvVar(Constants.ENV_ALERT_CONTROLLER_CLASSNAME, 'AlertController'); setProcessEnvVar(Constants.ENV_ALERT_CONTROLLER_PATH, join(context.ionicAngularDir, 'components', 'alert', 'alert-controller.js')); setProcessEnvVar(Constants.ENV_ALERT_VIEW_CONTROLLER_PATH, join(context.ionicAngularDir, 'components', 'alert', 'alert.js')); setProcessEnvVar(Constants.ENV_ALERT_COMPONENT_PATH, join(context.ionicAngularDir, 'components', 'alert', 'alert-component.js')); setProcessEnvVar(Constants.ENV_ALERT_COMPONENT_FACTORY_PATH, join(context.ionicAngularDir, 'components', 'alert', 'alert-component.ngfactory.js')); setProcessEnvVar(Constants.ENV_APP_ROOT_COMPONENT_PATH, join(context.ionicAngularDir, 'components', 'app', 'app-root.js')); setProcessEnvVar(Constants.ENV_LOADING_CONTROLLER_CLASSNAME, 'LoadingController'); setProcessEnvVar(Constants.ENV_LOADING_CONTROLLER_PATH, join(context.ionicAngularDir, 'components', 'loading', 'loading-controller.js')); setProcessEnvVar(Constants.ENV_LOADING_VIEW_CONTROLLER_PATH, join(context.ionicAngularDir, 'components', 'loading', 'loading.js')); setProcessEnvVar(Constants.ENV_LOADING_COMPONENT_PATH, join(context.ionicAngularDir, 'components', 'loading', 'loading-component.js')); setProcessEnvVar(Constants.ENV_LOADING_COMPONENT_FACTORY_PATH, join(context.ionicAngularDir, 'components', 'loading', 'loading-component.ngfactory.js')); setProcessEnvVar(Constants.ENV_MODAL_CONTROLLER_CLASSNAME, 'ModalController'); setProcessEnvVar(Constants.ENV_MODAL_CONTROLLER_PATH, join(context.ionicAngularDir, 'components', 'modal', 'modal-controller.js')); setProcessEnvVar(Constants.ENV_MODAL_VIEW_CONTROLLER_PATH, join(context.ionicAngularDir, 'components', 'modal', 'modal.js')); setProcessEnvVar(Constants.ENV_MODAL_COMPONENT_PATH, join(context.ionicAngularDir, 'components', 'modal', 'modal-component.js')); setProcessEnvVar(Constants.ENV_MODAL_COMPONENT_FACTORY_PATH, join(context.ionicAngularDir, 'components', 'modal', 'modal-component.ngfactory.js')); setProcessEnvVar(Constants.ENV_PICKER_CONTROLLER_CLASSNAME, 'PickerController'); setProcessEnvVar(Constants.ENV_PICKER_CONTROLLER_PATH, join(context.ionicAngularDir, 'components', 'picker', 'picker-controller.js')); setProcessEnvVar(Constants.ENV_PICKER_VIEW_CONTROLLER_PATH, join(context.ionicAngularDir, 'components', 'picker', 'picker.js')); setProcessEnvVar(Constants.ENV_PICKER_COMPONENT_PATH, join(context.ionicAngularDir, 'components', 'picker', 'picker-component.js')); setProcessEnvVar(Constants.ENV_PICKER_COMPONENT_FACTORY_PATH, join(context.ionicAngularDir, 'components', 'picker', 'picker-component.ngfactory.js')); setProcessEnvVar(Constants.ENV_POPOVER_CONTROLLER_CLASSNAME, 'PopoverController'); setProcessEnvVar(Constants.ENV_POPOVER_CONTROLLER_PATH, join(context.ionicAngularDir, 'components', 'popover', 'popover-controller.js')); setProcessEnvVar(Constants.ENV_POPOVER_VIEW_CONTROLLER_PATH, join(context.ionicAngularDir, 'components', 'popover', 'popover.js')); setProcessEnvVar(Constants.ENV_POPOVER_COMPONENT_PATH, join(context.ionicAngularDir, 'components', 'popover', 'popover-component.js')); setProcessEnvVar(Constants.ENV_POPOVER_COMPONENT_FACTORY_PATH, join(context.ionicAngularDir, 'components', 'popover', 'popover-component.ngfactory.js')); setProcessEnvVar(Constants.ENV_SELECT_POPOVER_CLASSNAME, 'SelectPopover'); setProcessEnvVar(Constants.ENV_SELECT_POPOVER_COMPONENT_PATH, join(context.ionicAngularDir, 'components', 'select', 'select-popover-component.js')); setProcessEnvVar(Constants.ENV_SELECT_POPOVER_COMPONENT_FACTORY_PATH, join(context.ionicAngularDir, 'components', 'select', 'select-popover-component.ngfactory.js')); setProcessEnvVar(Constants.ENV_TOAST_CONTROLLER_CLASSNAME, 'ToastController'); setProcessEnvVar(Constants.ENV_TOAST_CONTROLLER_PATH, join(context.ionicAngularDir, 'components', 'toast', 'toast-controller.js')); setProcessEnvVar(Constants.ENV_TOAST_VIEW_CONTROLLER_PATH, join(context.ionicAngularDir, 'components', 'toast', 'toast.js')); setProcessEnvVar(Constants.ENV_TOAST_COMPONENT_PATH, join(context.ionicAngularDir, 'components', 'toast', 'toast-component.js')); setProcessEnvVar(Constants.ENV_TOAST_COMPONENT_FACTORY_PATH, join(context.ionicAngularDir, 'components', 'toast', 'toast-component.ngfactory.js')); const parseDeepLinks = getConfigValue(context, '--parseDeepLinks', null, Constants.ENV_PARSE_DEEPLINKS, Constants.ENV_PARSE_DEEPLINKS.toLowerCase(), 'true'); setProcessEnvVar(Constants.ENV_PARSE_DEEPLINKS, parseDeepLinks); Logger.debug(`parseDeepLinks set to ${parseDeepLinks}`); const skipReadIonicAngular = getConfigValue(context, '--skipIonicAngularVersion', null, Constants.ENV_SKIP_IONIC_ANGULAR_VERSION, Constants.ENV_SKIP_IONIC_ANGULAR_VERSION.toLowerCase(), 'false'); setProcessEnvVar(Constants.ENV_SKIP_IONIC_ANGULAR_VERSION, skipReadIonicAngular); Logger.debug(`skipReadIonicAngular set to ${skipReadIonicAngular}`); if (!isValidBundler(context.bundler)) { context.bundler = bundlerStrategy(context); Logger.debug(`bundler set to ${context.bundler}`); } context.inlineTemplates = true; checkDebugMode(); if (getBooleanPropertyValue(Constants.ENV_DISABLE_LOGGING)) { console.debug = () => { }; console.error = () => { }; console.info = () => { }; console.log = () => { }; console.trace = () => { }; console.warn = () => { }; } return context; } export function getUserConfigFile(context: BuildContext, task: TaskInfo, userConfigFile: string) { if (!context) { context = generateContext(context); } if (userConfigFile) { return resolve(userConfigFile); } const defaultConfig = getConfigValue(context, task.fullArg, task.shortArg, task.envVar, task.packageConfig, null); if (defaultConfig) { return join(context.rootDir, defaultConfig); } return null; } export function fillConfigDefaults(userConfigFile: string, defaultConfigFile: string): any { let userConfig: any = null; if (userConfigFile) { try { // check if exists first, so we can print a more specific error message // since required config could also throw MODULE_NOT_FOUND statSync(userConfigFile); // create a fresh copy of the config each time userConfig = require(userConfigFile); // if user config returns a function call it to determine proper object if (typeof userConfig === 'function') { userConfig = userConfig(); } } catch (e) { if (e.code === 'ENOENT') { console.error(`Config file "${userConfigFile}" not found. Using defaults instead.`); } else { console.error(`There was an error in config file "${userConfigFile}". Using defaults instead.`); console.error(e); } } } const defaultConfig = require(join('..', '..', 'config', defaultConfigFile)); // create a fresh copy of the config each time // always assign any default values which were not already supplied by the user return objectAssign({}, defaultConfig, userConfig); } export function bundlerStrategy(context: BuildContext): string { return Constants.BUNDLER_WEBPACK; } function isValidBundler(bundler: any) { return bundler === Constants.BUNDLER_WEBPACK; } export function getConfigValue(context: BuildContext, argFullName: string, argShortName: string, envVarName: string, packageConfigProp: string, defaultValue: string) { if (!context) { context = generateContext(context); } // first see if the value was set in the command-line args const argVal = getArgValue(argFullName, argShortName); if (argVal !== null) { return argVal; } // next see if it was set in the environment variables // which also checks if it was set in the package.json config property const envVar = getProcessEnvVar(envVarName); if (envVar !== null) { return envVar; } const packageConfig = getPackageJsonConfig(context, packageConfigProp); if (packageConfig !== null) { return packageConfig; } // return the default if nothing above was found return defaultValue; } function getArgValue(fullName: string, shortName: string): string { for (var i = 2; i < processArgv.length; i++) { var arg = processArgv[i]; if (arg === fullName || (shortName && arg === shortName)) { var val = processArgv[i + 1]; if (val !== undefined && val !== '') { return val; } } } return null; } export function hasConfigValue(context: BuildContext, argFullName: string, argShortName: string, envVarName: string, defaultValue: boolean) { if (!context) { context = generateContext(context); } if (hasArg(argFullName, argShortName)) { return true; } // next see if it was set in the environment variables // which also checks if it was set in the package.json config property const envVar = getProcessEnvVar(envVarName); if (envVar !== null) { return true; } const packageConfig = getPackageJsonConfig(context, envVarName); if (packageConfig !== null) { return true; } // return the default if nothing above was found return defaultValue; } export function hasArg(fullName: string, shortName: string = null): boolean { return !!(processArgv.some(a => a.toLowerCase() === fullName.toLowerCase()) || (shortName !== null && processArgv.some(a => a.toLowerCase() === shortName.toLowerCase()))); } export function replacePathVars(context: BuildContext, filePath: string | string[] | { [key: string]: any }): any { if (Array.isArray(filePath)) { return filePath.map(f => replacePathVars(context, f)); } if (typeof filePath === 'object') { const clonedFilePaths = Object.assign({}, filePath); for (let key in clonedFilePaths) { clonedFilePaths[key] = replacePathVars(context, clonedFilePaths[key]); } return clonedFilePaths; } return filePath.replace('{{SRC}}', context.srcDir) .replace('{{WWW}}', context.wwwDir) .replace('{{TMP}}', context.tmpDir) .replace('{{ROOT}}', context.rootDir) .replace('{{BUILD}}', context.buildDir); } export function getNodeBinExecutable(context: BuildContext, cmd: string) { let cmdPath = join(context.rootDir, 'node_modules', '.bin', cmd); try { accessSync(cmdPath); } catch (e) { cmdPath = null; } return cmdPath; } let checkedDebug = false; function checkDebugMode() { if (!checkedDebug) { if (hasArg('--debug') || getProcessEnvVar('ionic_debug_mode') === 'true') { processEnv.ionic_debug_mode = 'true'; } checkedDebug = true; } } export function isDebugMode() { return (processEnv.ionic_debug_mode === 'true'); } let processArgv: string[]; export function setProcessArgs(argv: string[]) { processArgv = argv; } setProcessArgs(process.argv); export function addArgv(value: string) { processArgv.push(value); } let processEnv: any; export function setProcessEnv(env: any) { processEnv = env; } setProcessEnv(process.env); export function setProcessEnvVar(key: string, value: any) { if (key && value) { processEnv[key] = value; } } export function getProcessEnvVar(key: string): any { const val = processEnv[key]; if (val !== undefined) { if (val === 'true') { return true; } if (val === 'false') { return false; } return val; } return null; } let processCwd: string; export function setCwd(cwd: string) { processCwd = cwd; } setCwd(process.cwd()); export function getPackageJsonConfig(context: BuildContext, key: string): any { const packageJsonData = getAppPackageJsonData(context); if (packageJsonData && packageJsonData.config) { const val = packageJsonData.config[key]; if (val !== undefined) { if (val === 'true') { return true; } if (val === 'false') { return false; } return val; } } return null; } let appPackageJsonData: any = null; export function setAppPackageJsonData(data: any) { appPackageJsonData = data; } function getAppPackageJsonData(context: BuildContext) { if (!appPackageJsonData) { try { appPackageJsonData = readJSONSync(join(context.rootDir, 'package.json')); } catch (e) {} } return appPackageJsonData; }
the_stack
import { DataTexture, LuminanceFormat, UnsignedByteType, ClampToEdgeWrapping } from "three"; import { LinearFilter } from "three/src/constants"; import Channel from "./Channel"; import { FuseChannel } from "./types"; // This is the owner of the fused RGBA volume texture atlas, and the mask texture atlas. // This module is responsible for updating the fused texture, given the read-only volume channel data. export default class FusedChannelData { private width: number; private height: number; private fused: Uint8ClampedArray; // todo: make private? public fusedTexture: DataTexture; public maskTexture: DataTexture; private maskChannelLoaded: boolean; private maskChannelIndex: number; private useSingleThread: boolean; private fuseWorkersWorking: number; private isFusing: boolean; private workers: Worker[]; private workersCount: number; private fuseRequested: FuseChannel[] | null; private fuseMethodRequested: string; private channelsDataToFuse: Channel[]; constructor(atlasX: number, atlasY: number) { // allow for resizing this.width = atlasX; this.height = atlasY; // cpu memory buffer with the combined rgba texture atlas for display this.fused = new Uint8ClampedArray(this.width * this.height * 4); // webgl texture with the rgba texture atlas for display this.fusedTexture = new DataTexture(this.fused, this.width, this.height); this.fusedTexture.generateMipmaps = false; this.fusedTexture.magFilter = LinearFilter; this.fusedTexture.minFilter = LinearFilter; this.fusedTexture.wrapS = ClampToEdgeWrapping; this.fusedTexture.wrapT = ClampToEdgeWrapping; this.maskTexture = new DataTexture( new Uint8ClampedArray(this.width * this.height), this.width, this.height, LuminanceFormat, UnsignedByteType ); this.maskTexture.generateMipmaps = false; this.maskTexture.magFilter = LinearFilter; this.maskTexture.minFilter = LinearFilter; this.maskTexture.wrapS = ClampToEdgeWrapping; this.maskTexture.wrapT = ClampToEdgeWrapping; // for single-channel tightly packed array data: this.maskTexture.unpackAlignment = 1; this.maskChannelLoaded = false; this.maskChannelIndex = 0; // force single threaded use even if webworkers are available this.useSingleThread = true; // thread control this.fuseWorkersWorking = 0; this.isFusing = false; this.fuseRequested = null; this.fuseMethodRequested = ""; this.channelsDataToFuse = []; this.workers = []; this.workersCount = 0; this.setupWorkers(); } static onFuseComplete(): void { // no op } static setOnFuseComplete(onFuseComplete: () => void): void { FusedChannelData.onFuseComplete = onFuseComplete; } public cleanup(): void { if (this.workers && this.workers.length > 0) { for (let i = 0; i < this.workers.length; ++i) { this.workers[i].onmessage = null; this.workers[i].terminate(); } } this.workers = []; this.workersCount = 0; this.fusedTexture.dispose(); this.maskTexture.dispose(); } private setupWorkers(): void { if (this.useSingleThread || !window.Worker) { this.workersCount = 0; return; } // We will break up the image into one piece for each web-worker // can we assert that npx is a perfect multiple of workersCount?? const npx = this.height * this.width; this.workersCount = 4; this.fuseWorkersWorking = 0; // var segmentLength = npx / workersCount; // This is the length of array sent to the worker // var blockSize = this.height / workersCount; // Height of the picture chunk for every worker // Function called when a job is finished const onWorkEnded = (e) => { this.fuseWorkersWorking++; // copy e.data.data into fused this.fused.set(e.data.data, Math.floor(e.data.workerindex * (npx / this.workersCount)) * 4); if (this.fuseWorkersWorking === this.workersCount) { this.fusedTexture.image = { data: this.fused, width: this.width, height: this.height }; this.fusedTexture.needsUpdate = true; this.fuseWorkersWorking = 0; if (FusedChannelData.onFuseComplete) { FusedChannelData.onFuseComplete(); } // if there are any fusion requests in queue, execute the next one now. this.isFusing = false; if (this.fuseRequested) { this.fuse(this.fuseRequested, this.fuseMethodRequested, this.channelsDataToFuse); } this.fuseRequested = null; this.channelsDataToFuse = []; } }; this.workers = []; for (let index = 0; index < this.workersCount; index++) { const worker = new Worker(new URL("./FuseWorker.js", import.meta.url)); worker.onmessage = onWorkEnded; worker.onerror = function (e) { alert("Error: Line " + e.lineno + " in " + e.filename + ": " + e.message); }; this.workers.push(worker); } } // batch is array containing which channels were just loaded // channels is the array containing the channel data. public onChannelLoaded(batch: number[], channels: Channel[]): void { if (this.useSingleThread || !window.Worker) { return; } const npx = this.height * this.width; // pass channel data to workers for (let i = 0; i < this.workersCount; ++i) { for (let j = 0; j < batch.length; ++j) { const channelIndex = batch[j]; // chop up the arrays. this is a copy operation! const arr = channels[channelIndex].imgData.data.buffer.slice( Math.floor(i * (npx / this.workersCount)), Math.floor((i + 1) * (npx / this.workersCount) - 1) ); //console.log(arr.byteLength); const workerData = { msgtype: "channeldata", channelindex: channelIndex, workerindex: i, w: this.width, h: this.height, data: arr, }; //console.log("POST channeldata worker " + i + ", channel "+ channelIndex); // hand the data arrays to each worker. they will assume ownership. this.workers[i].postMessage(workerData, [workerData.data]); } } } fuse(combination: FuseChannel[], fuseMethod: string, channels: Channel[]): void { fuseMethod = fuseMethod || "m"; // we can fuse if we have any loaded channels that are showing. // actually, we can fuse if no channels are showing (but they are loaded), too. let canFuse = false; for (let i = 0; i < combination.length; ++i) { const c = combination[i]; const idx = c.chIndex; if (channels[idx].loaded) { // set the lut in this fuse combination. // can optimize by calling combineLuts more lazily c.lut = channels[idx].combineLuts(c.rgbColor, c.lut); canFuse = true; //break; } } if (!canFuse) { return; } // If workers are not supported // Perform all calculations in current thread as usual if (this.useSingleThread || !window.Worker) { // console.log("SINGLE THREADED"); this.singleThreadedFuse(combination, channels); if (FusedChannelData.onFuseComplete) { FusedChannelData.onFuseComplete(); } return; } // Keep a queue of a maximum of 1 fuse request at a time. // if 1 fuse is already happening, queue the next one // if 1 is queued, replace it with the latest. if (this.isFusing) { this.fuseRequested = combination; this.channelsDataToFuse = channels; this.fuseMethodRequested = fuseMethod; return; } // We will break up the image into one piece for each web-worker // can we assert that npx is a perfect multiple of workersCount?? this.fuseWorkersWorking = 0; this.isFusing = true; // var segmentLength = npx / workersCount; // This is the length of array sent to the worker // var blockSize = this.height / workersCount; // Height of the picture chunk for every worker // Launching every worker //console.log("BEGIN FUSE"); for (let index = 0; index < this.workersCount; index++) { this.workers[index].postMessage({ msgtype: "fuse", combination: combination, fuseMethod: fuseMethod, }); } } // sum over [{chIndex, rgbColor}] private singleThreadedFuse(combination, channels): void { //console.log("BEGIN"); // explore some faster ways to fuse here... let ar, ag, ab, aa, c, lr, lg, lb, la, opacity, channeldata; let cx, fx, idx; const cl = combination.length; const npx4 = this.height * this.width * 4; const npx = this.height * this.width; const fused = this.fused; // init the rgba image for (let x = 0; x < npx4; x += 4) { fused[x + 0] = 0; fused[x + 1] = 0; fused[x + 2] = 0; fused[x + 3] = 255; } let value = 0; for (let i = 0; i < cl; ++i) { c = combination[i]; idx = c.chIndex; if (!channels[idx].loaded) { continue; } if (c.rgbColor) { channeldata = channels[idx].imgData.data; for (cx = 0, fx = 0; cx < npx; cx += 1, fx += 4) { value = channeldata[cx]; lr = c.lut[value * 4 + 0]; lg = c.lut[value * 4 + 1]; lb = c.lut[value * 4 + 2]; la = c.lut[value * 4 + 3]; opacity = la / 255.0; // what if rgb*opacity > 255? ar = fused[fx + 0]; fused[fx + 0] = Math.max(ar, lr * opacity); ag = fused[fx + 1]; fused[fx + 1] = Math.max(ag, lg * opacity); ab = fused[fx + 2]; fused[fx + 2] = Math.max(ab, lb * opacity); aa = fused[fx + 3]; fused[fx + 3] = Math.max(aa, la); } } } // clamp the rgba image: ensure not over 255. for (let x = 0; x < npx4; x += 4) { fused[x + 0] = Math.min(fused[x + 0], 255); fused[x + 1] = Math.min(fused[x + 1], 255); fused[x + 2] = Math.min(fused[x + 2], 255); } this.fusedTexture.image = { data: this.fused, width: this.width, height: this.height, }; this.fusedTexture.needsUpdate = true; //console.log("END"); } // currently only one channel can be selected to participate as a mask public setChannelAsMask(idx: number, channel: Channel): boolean { if (!channel || !channel.loaded) { return false; } const datacopy = channel.imgData.data.buffer.slice(0); const maskData = { data: new Uint8ClampedArray(datacopy), width: this.width, height: this.height, }; this.maskTexture.image = maskData; this.maskTexture.needsUpdate = true; this.maskChannelLoaded = true; this.maskChannelIndex = idx; return true; } }
the_stack
* @module Properties */ // cspell:ignore BBGGRR pushable DDTHH /** Interface used to provide a custom Date Time formatter and optional parser * for use by `DatePickerPopup`. If a parseData function is not implemented * then string to date parsing will not be possible when a `DateFormatter` is used. * @public */ export interface DateFormatter { formateDate: (day: Date) => string; parseDate?: (dateString: string) => Date | undefined; } /** Alternate Data Formats that can be provide by javascript. Can be used by Date TypeConverter and TypeEditor. * @public */ export enum AlternateDateFormats { None = 0, // YYYY-MM-DD IsoShort = 1, // YYYY-MM-DDTHH:mm:ss.sssZ IsoDateTime, // dd Mmm yyyy UtcShort, // dd Mmm yyyy hh:mm:ss GMT UtcDateTime, // Www, dd Mmm yyyy UtcShortWithDay, // Www, dd Mmm yyyy hh:mm:ss GMT UtcDateTimeWithDay, } /** Enum that defines supported time formats. * @public */ export enum TimeDisplay { // 12 hour with minutes and cycle(AM/PM) H12MC = "hh:mm aa", // 12 hour with minutes, seconds and cycle(AM/PM) H12MSC = "hh:mm:ss aa", // 24 hour with minutes H24M = "hh:mm", // 24 hour with minutes and seconds H24MS = "hh:mm:ss", } /** * Enum for Property Editor Param Types * @public */ export enum PropertyEditorParamTypes { ButtonGroupData = "UiAbstract-ButtonGroupData", CheckBoxIcons = "UiAbstract-CheckBoxIcons", Icon = "UiAbstract-Icon", InputEditorSize = "UiAbstract-InputEditorSize", ColorData = "UiAbstract-ColorData", CustomFormattedNumber = "UiAbstract-CustomFormattedNumber", IconListData = "UiAbstract-IconListData", // JSON = "UiAbstract-JSON", MultilineText = "UiAbstract-MultilineText", Range = "UiAbstract-Range", Slider = "UiAbstract-Slider", // SuppressUnitLabel = "UiAbstract-SuppressUnitLabel", SuppressEditorLabel = "UiAbstract-SuppressEditorLabel", CheckBoxImages = "UiAbstract-CheckBoxImages", } /** * [[BasePropertyEditorParams]] Base interface for Property Editor Params * @public */ export interface BasePropertyEditorParams { type: string; } /** * Parameters used by PropertyEditors that use HTML <input> element. * @public */ /** [[InputEditorSizeParams]] type guard. * @public */ export interface InputEditorSizeParams extends BasePropertyEditorParams { type: PropertyEditorParamTypes.InputEditorSize; /** Optionally define the width in characters. */ size?: number; /** Optionally define the maximum number of characters allowed. */ maxLength?: number; } /** InputEditorSizeParams type guard. * @public */ export const isInputEditorSizeParams = (item: BasePropertyEditorParams): item is InputEditorSizeParams => { return item.type === PropertyEditorParamTypes.InputEditorSize; }; /** * [[ColorEditorParams]] Parameters used to populate color type editor with a specific set of colors. If not specified the Color * Editor will show a default palette of 16 colors. * @public */ export interface ColorEditorParams extends BasePropertyEditorParams { type: PropertyEditorParamTypes.ColorData; /** array of color values to show in color picker popup. Use [[ColorByName]] enum values. Values should be 32-bit integer in the form 0xBBGGRR. */ colorValues: number[]; /** number of columns to show in color picker popup. The value of 4 is used if not defined. */ numColumns?: number; } /** ColorEditorParams type guard. * @public */ export const isColorEditorParams = (item: BasePropertyEditorParams): item is ColorEditorParams => { return item.type === PropertyEditorParamTypes.ColorData; }; /** * [[IconListEditorParams]] Parameters used to populate icon type editor with a specific set of icons. * @public */ export interface IconListEditorParams extends BasePropertyEditorParams { type: PropertyEditorParamTypes.IconListData; /** active icon shown in the button */ iconValue: string; /** array of icon (svg) names to show in icon picker popup. */ iconValues: string[]; /** number of columns to show in icon picker popup. The value of 4 is used if not defined. */ numColumns?: number; } /** IconListEditorParams type guard. * @public */ export const isIconListEditorParams = (item: BasePropertyEditorParams): item is IconListEditorParams => { return item.type === PropertyEditorParamTypes.IconListData; }; /** * [[IconDefinition]] Information about an icon displayed next to a property editor. * @public */ export interface IconDefinition { /** Icon specification. The value is the name of an icon WebFont entry, or if specifying an imported SVG symbol use "webSvg:" prefix . */ iconSpec: string; /** Function to determine if the item is enabled. */ isEnabledFunction?: () => boolean; } /** * [[ButtonGroupEditorParams]] Parameters used by EnumButtonGroupEditor to define icons in button group. * @public */ export interface ButtonGroupEditorParams extends BasePropertyEditorParams { type: PropertyEditorParamTypes.ButtonGroupData; buttons: IconDefinition[]; } /** ButtonGroupEditorParams type guard. * @public */ export const isButtonGroupEditorParams = (item: BasePropertyEditorParams): item is ButtonGroupEditorParams => { return item.type === PropertyEditorParamTypes.ButtonGroupData; }; /** * [[SuppressLabelEditorParams]] Parameters used to suppress the label for a type editor in the ToolSettings widget. * @public */ export interface SuppressLabelEditorParams extends BasePropertyEditorParams { type: PropertyEditorParamTypes.SuppressEditorLabel; /** if false then an empty placeholder label is created. This is sometimes necessary to align editor in proper column */ suppressLabelPlaceholder?: boolean; } /** SuppressLabelEditorParams type guard. * @public */ export const isSuppressLabelEditorParams = (item: BasePropertyEditorParams): item is SuppressLabelEditorParams => { return item.type === PropertyEditorParamTypes.SuppressEditorLabel; }; // /** // * Parameters used by PropertyEditors that support JSON. // * @alpha // */ // export interface JsonEditorParams extends BasePropertyEditorParams { // type: PropertyEditorParamTypes.JSON; // json: any; // } /** * Parameters used by PropertyEditors that support defining a minimum and maximum value. * @public */ export interface RangeEditorParams extends BasePropertyEditorParams { type: PropertyEditorParamTypes.Range; /** Defines the minimum value. Default is Number.MIN_SAFE_INTEGER. */ minimum?: number; /** Defines the maximum value. Default is Number.MAX_SAFE_INTEGER. */ maximum?: number; /** Defines the step value. Default is 1. */ step?: number; /** Defines the precision. Default is 0. */ precision?: number; } /** * Parameters used to indicate that a Slider should be presented for the property * and to specify the values needed by the slider. * @public */ export interface SliderEditorParams extends BasePropertyEditorParams { type: PropertyEditorParamTypes.Slider; /** Defines the minimum value. */ minimum: number; /** Defines the maximum value. */ maximum: number; /** Optionally define the width in pixels. */ size?: number; /** Step value. Default is 0.1. */ step?: number; /** The interaction mode. Default is 1. Possible values: * 1 - allows handles to cross each other. * 2 - keeps the sliders from crossing and separated by a step. */ mode?: number; /** Indicates whether the display of the Slider values is reversed. */ reversed?: boolean; /** Indicates whether to show tooltip with the value. The tooltip will be positioned above the Slider, by default. */ showTooltip?: boolean; /** Indicates whether the tooltip should show below the Slider instead of above. */ tooltipBelow?: boolean; /** Format a value for the tooltip */ formatTooltip?: (value: number) => string; /** Indicates whether to show min & max values to the left & right of the Slider. */ showMinMax?: boolean; /** Image to show for min. */ minIconSpec?: string; /** Image to show for max. */ maxIconSpec?: string; /** Indicates whether to show tick marks under the Slider. */ showTicks?: boolean; /** Indicates whether to show tick labels under the tick marks. */ showTickLabels?: boolean; /** Format a tick mark value */ formatTick?: (tick: number) => string; /** Function to get the tick count. The default tick count is 10. */ getTickCount?: () => number; /** Function to get the tick values. This overrides the tick count from getTickCount. * Use this prop if you want to specify your own tick values instead of ticks generated by the slider. * The numbers should be valid numbers in the domain and correspond to the step value. * Invalid values will be coerced to the closet matching value in the domain. */ getTickValues?: () => number[]; } /** * Parameter that is used to indicate that a multiline text editor should be created. * The number of rows specified will determine the height of the editor control. * @public */ export interface MultilineTextEditorParams extends BasePropertyEditorParams { type: PropertyEditorParamTypes.MultilineText; rows: number; } /** * Parameters used to display an icon next to property editor. * @public */ export interface IconEditorParams extends BasePropertyEditorParams { type: PropertyEditorParamTypes.Icon; definition: IconDefinition; } /** * Parameters for ImageCheckBoxEditor * @public */ export interface ImageCheckBoxParams extends BasePropertyEditorParams { type: PropertyEditorParamTypes.CheckBoxImages; imageOn: string; imageOff: string; } // /** // * Parameter used to suppress Unit labels // * @alpha // */ // export interface SuppressUnitLabelEditorParams extends BasePropertyEditorParams { // type: PropertyEditorParamTypes.SuppressUnitLabel; // } /** * defines Results of parsing a string input by a user into its desired value type * @public */ export interface ParseResults { value?: string | number | boolean | {} | string[] | Date | [] | undefined; parseError?: string; } /** * Parameters used with properties that want to control parsing and formatting. * @public */ export interface CustomFormattedNumberParams extends BasePropertyEditorParams { type: PropertyEditorParamTypes.CustomFormattedNumber; formatFunction: (numberValue: number) => string; parseFunction: (stringValue: string) => ParseResults; } /** CustomFormattedNumberParams type guard. * @public */ export const isCustomFormattedNumberParams = (item: BasePropertyEditorParams): item is CustomFormattedNumberParams => { return item.type === PropertyEditorParamTypes.CustomFormattedNumber; }; /** * Type definition for Property Editor params * @public */ export type PropertyEditorParams = BasePropertyEditorParams;
the_stack
import { SVErrorLevel, SVType } from 'pytea/backend/sharpValues'; import { ExecutionPath, ExecutionPathStatus } from 'pytea/service/executionPaths'; import { defaultOptions, PyteaLogLevel, PyteaOptions } from 'pytea/service/pyteaOptions'; import { PyteaService } from 'pytea/service/pyteaService'; import { buildPyteaOption } from 'pytea/service/pyteaUtils'; import { inspect } from 'util'; import { CancellationTokenSource } from 'vscode'; import { CancellationToken, ConfigurationItem, Connection, createConnection, Diagnostic, DiagnosticRelatedInformation, DiagnosticSeverity, DiagnosticTag, ExecuteCommandParams, InitializeParams, InitializeResult, Location, MarkupKind, WorkDoneProgressReporter, WorkspaceFolder, } from 'vscode-languageserver/node'; import { TextDocumentSyncKind } from 'vscode-languageserver-protocol'; import { AnalysisResults } from 'pyright-internal/analyzer/analysis'; import { isPythonBinary } from 'pyright-internal/analyzer/pythonPathUtils'; import { AnalyzerService } from 'pyright-internal/analyzer/service'; import { CancelAfter } from 'pyright-internal/common/cancellationUtils'; import { getNestedProperty } from 'pyright-internal/common/collectionUtils'; import { ConsoleInterface, ConsoleWithLogLevel, LogLevel, NullConsole } from 'pyright-internal/common/console'; import { isString } from 'pyright-internal/common/core'; import { createDeferred } from 'pyright-internal/common/deferred'; import { Diagnostic as AnalyzerDiagnostic, DiagnosticCategory } from 'pyright-internal/common/diagnostic'; import { createFromRealFileSystem, FileSystem } from 'pyright-internal/common/fileSystem'; import { convertPathToUri, convertUriToPath, resolvePaths } from 'pyright-internal/common/pathUtils'; import { ServerOptions, ServerSettings } from 'pyright-internal/languageServerBase'; import { AnalyzerServiceExecutor } from 'pyright-internal/languageService/analyzerServiceExecutor'; import { Localizer } from 'pyright-internal/localization/localize'; import { PyteaCommandController } from './commandController'; import { PyteaWorkspaceInstance, PyteaWorkspaceMap } from './workspaceMap'; export interface PyteaServerSettings { pyrightSettings: ServerSettings; pyteaOptions: PyteaOptions; } export class PyteaServer { protected _connection: Connection; protected _workspaceMap: PyteaWorkspaceMap; protected _hasConfigurationCapability = false; protected _hasWorkspaceFoldersCapability = false; protected _hoverContentFormat: MarkupKind = MarkupKind.PlainText; protected _defaultClientConfig: any; private _serverOptions: ServerOptions; private _controller: PyteaCommandController; private _pendingCommandCancellationSource: CancellationTokenSource | undefined; private _selectedWorkspace?: PyteaWorkspaceInstance; // Global root path - the basis for all global settings. rootPath = ''; fs: FileSystem; readonly console: ConsoleInterface; constructor() { this._connection = createConnection(); // eslint-disable-next-line @typescript-eslint/no-var-requires const version = require('../package.json').version || ''; // When executed from CLI command (pyright-langserver), __rootDirectory is // already defined. When executed from VSCode extension, rootDirectory should // be __dirname. const rootDirectory = (global as any).__rootDirectory || __dirname; this.console = new ConsoleWithLogLevel(this._connection.console); this.console.info(`Pytea language server ${version && version + ' '}starting`); this.fs = createFromRealFileSystem(this.console); // Set the working directory to a known location within // the extension directory. Otherwise the execution of // python can have unintended and surprising results. const moduleDirectory = this.fs.getModulePath(); if (moduleDirectory) { this.fs.chdir(moduleDirectory); } this._serverOptions = { productName: 'Pytea', rootDirectory, version, }; // Stash the base directory into a global variable. (global as any).__rootDirectory = rootDirectory; this.console.info(`Server root directory: ${rootDirectory}`); // Create workspace map. this._workspaceMap = new PyteaWorkspaceMap(this); // Set up callbacks. this.setupConnection(); // Connect command controller. this._controller = new PyteaCommandController(this); // Listen on the connection. this._connection.listen(); } // Creates a service instance that's used for analyzing a // program within a workspace. createAnalyzerService(name: string): AnalyzerService { this.console.log(`Starting service instance "${name}"`); // ignore original pyright output. const output = new NullConsole(); const service = new AnalyzerService(name, this.fs, output); service.setCompletionCallback((results) => this.onAnalysisCompletedHandler(results)); return service; } updateSettingsForAllWorkspaces(): void { this._workspaceMap.forEach((workspace) => { this.updateSettingsForWorkspace(workspace).catch(() => { // ignore errors }); }); } async analyze(entryPath: string) { this.console.info(`analyzing ${entryPath}...`); const workspace = this._workspaceMap.getWorkspaceForFile(entryPath); this._selectedWorkspace = workspace; const baseOptions = workspace.pyteaOptions; baseOptions.entryPath = resolvePaths( workspace.rootPath, this.expandPathVariables(workspace.rootPath, entryPath) ); const options = buildPyteaOption(undefined, workspace.rootPath, baseOptions); if (typeof options === 'string') { this.console.error(`Found error while setting Pytea options: ${options}`); return; } workspace.pyteaOptions = options; const pyteaService = workspace.pyteaService; pyteaService.setOptions(options); this.console.info(`options: ${inspect(options)}`); if (!pyteaService.validate()) { return; } const errMsg = pyteaService.translateAll(baseOptions.entryPath); if (errMsg) { this.console.error(`Found error while translating Python scripts: ${errMsg}`); return; } try { // TODO: remove global reference PyteaService.setGlobalService(pyteaService); // TODO: resolve rejected const result = await pyteaService.analyze(); const success = result.getList(); const stopped = result.getStopped(); const failed = result.getFailed(); this.console.info( `Analyzing completed. Found ${success?.count() ?? 0} success paths / ${ failed?.count() ?? 0 } failed paths` ); if (result) { const executionPaths: ExecutionPath[] = []; let id = 0; success?.forEach((p) => { const path = new ExecutionPath( p, id, this.rootPath, ExecutionPathStatus.Success, pyteaService.getPathStore() ); executionPaths.push(path); id++; }); stopped?.forEach((p) => { const path = new ExecutionPath( p, id, this.rootPath, ExecutionPathStatus.Stopped, pyteaService.getPathStore() ); executionPaths.push(path); id++; }); failed?.forEach((p) => { const path = new ExecutionPath( p, id, this.rootPath, ExecutionPathStatus.Failed, pyteaService.getPathStore() ); executionPaths.push(path); id++; }); setTimeout(() => { // async print log pyteaService.printLog(result); }, 10); workspace.paths = executionPaths; return executionPaths.map((p) => p.props); } else { this.console.error('Analyzer returned undefined'); } } catch (e) { this.console.error(`Found error while analyzing ${options.entryPath}\n ${e}`); } } selectPath(pathId: number): void { const service = this._selectedWorkspace?.pyteaService; const paths = this._selectedWorkspace?.paths; if (!(service && paths && paths[pathId])) { return; } const currPath = paths[pathId]; const currProps = currPath.props; const ctx = currPath.ctx; const diagMap: Map<string, AnalyzerDiagnostic[]> = new Map(); function severityMap(level: SVErrorLevel): DiagnosticCategory { switch (level) { case SVErrorLevel.Error: return DiagnosticCategory.Error; case SVErrorLevel.Warning: return DiagnosticCategory.Warning; case SVErrorLevel.Log: return DiagnosticCategory.Information; } } ctx.logs.forEach((log) => { if (log.type === SVType.Error) { const sourceRange = service.getSourceRange(log.source); if (sourceRange) { const [filePath, range] = sourceRange; if (!diagMap.has(filePath)) { diagMap.set(filePath, []); } const diagnostics = diagMap.get(filePath)!; diagnostics.push(new AnalyzerDiagnostic(severityMap(log.level), log.reason, range)); } } }); if (currProps.status === ExecutionPathStatus.Stopped || currProps.status === ExecutionPathStatus.Failed) { const retVal = ctx.retVal; if (typeof retVal === 'object') { const sourceRange = service.getSourceRange(retVal.source); if (sourceRange) { const [filePath, range] = sourceRange; if (!diagMap.has(filePath)) { diagMap.set(filePath, []); } const diagnostics = diagMap.get(filePath)!; const reason = retVal.type === SVType.Error ? retVal.reason : 'unknown error'; diagnostics.push(new AnalyzerDiagnostic(DiagnosticCategory.Error, reason, range)); } } } diagMap.forEach((diagnostics, filePath) => { this._connection.sendDiagnostics({ uri: convertPathToUri(filePath), diagnostics: this._convertDiagnostics(diagnostics), }); }); } restart() { // TODO: clear diagnostics and messages this._workspaceMap.forEach((workspace) => { workspace.serviceInstance.restart(); }); } async getWorkspaceForFile(filePath: string): Promise<PyteaWorkspaceInstance> { const workspace = this._workspaceMap.getWorkspaceForFile(filePath); await workspace.isInitialized.promise; return workspace; } async getSettings(workspace: PyteaWorkspaceInstance): Promise<PyteaServerSettings> { const pyrightSettings: ServerSettings = { watchForSourceChanges: true, watchForLibraryChanges: false, openFilesOnly: true, useLibraryCodeForTypes: false, disableLanguageServices: true, disableOrganizeImports: true, typeCheckingMode: 'basic', diagnosticSeverityOverrides: {}, logLevel: LogLevel.Log, autoImportCompletions: false, }; const pyteaOptions: PyteaOptions = { ...defaultOptions, logLevel: 'result-only', }; try { const pythonSection = await this.getConfiguration(workspace.rootUri, 'python'); if (pythonSection) { const pythonPath = pythonSection.pythonPath; if (pythonPath && isString(pythonPath) && !isPythonBinary(pythonPath)) { pyrightSettings.pythonPath = resolvePaths( workspace.rootPath, this.expandPathVariables(workspace.rootPath, pythonPath) ); } const venvPath = pythonSection.venvPath; if (venvPath && isString(venvPath)) { pyrightSettings.venvPath = resolvePaths( workspace.rootPath, this.expandPathVariables(workspace.rootPath, venvPath) ); } } const pythonPyteaSection = await this.getConfiguration(workspace.rootUri, 'python.pytea'); if (pythonPyteaSection) { const configPath = pythonPyteaSection.configPath; if (configPath && typeof configPath === 'string') { pyteaOptions.configPath = resolvePaths( workspace.rootPath, this.expandPathVariables(workspace.rootPath, configPath) ); } const pyteaLibPath = pythonPyteaSection.pyteaLibraryPath; if (pyteaLibPath && typeof pyteaLibPath === 'string') { pyteaOptions.pyteaLibPath = resolvePaths( workspace.rootPath, this.expandPathVariables(workspace.rootPath, pyteaLibPath) ); } const pythonCmdArgs = pythonPyteaSection.pythonCommandLineArguments; if (pythonCmdArgs && typeof pythonCmdArgs === 'object') { pyteaOptions.pythonCmdArgs = pythonCmdArgs; } const pythonSubcommand = pythonPyteaSection.pythonSubcommand; if (pythonSubcommand && typeof pythonSubcommand === 'string') { pyteaOptions.pythonSubcommand = pythonSubcommand; } const immediateConstraintCheck = pythonPyteaSection.immediateConstraintCheck; if (immediateConstraintCheck !== undefined) { pyteaOptions.immediateConstraintCheck = !!immediateConstraintCheck; } const ignoreAssert = pythonPyteaSection.ignoreAssert; if (ignoreAssert !== undefined) { pyteaOptions.ignoreAssert = !!ignoreAssert; } const variableRange = pythonPyteaSection.variableRange; if (variableRange && typeof variableRange === 'object') { pyteaOptions.variableRange = variableRange; } const logLevel = pythonPyteaSection.logLevel; const validLevels = ['none', 'result-only', 'reduced', 'full']; if (logLevel && typeof logLevel === 'string' && validLevels.includes(logLevel)) { pyteaOptions.logLevel = logLevel as PyteaLogLevel; } } } catch (error) { this.console.error(`Error reading settings: ${error}`); } return { pyrightSettings, pyteaOptions, }; } async updateSettingsForWorkspace( workspace: PyteaWorkspaceInstance, serverSettings?: PyteaServerSettings ): Promise<void> { serverSettings = serverSettings ?? (await this.getSettings(workspace)); const pyrightSettings = serverSettings.pyrightSettings; // Set logging level first. (this.console as ConsoleWithLogLevel).level = pyrightSettings.logLevel ?? LogLevel.Info; AnalyzerServiceExecutor.runWithOptions(this.rootPath, workspace, pyrightSettings); workspace.disableLanguageServices = !!pyrightSettings.disableLanguageServices; workspace.disableOrganizeImports = !!pyrightSettings.disableOrganizeImports; workspace.pyteaOptions = serverSettings.pyteaOptions; this.console.info(`setting options to ${inspect(serverSettings.pyteaOptions)}`); // The workspace is now open for business. workspace.isInitialized.resolve(true); } protected executeCommand(params: ExecuteCommandParams, token: CancellationToken): Promise<any> { this.console.info(`got ${params.command}`); return this._controller.execute(params, token); } protected setupConnection(): void { // After the server has started the client sends an initialize request. The server receives // in the passed params the rootPath of the workspace plus the client capabilities. this._connection.onInitialize((params) => this.initialize(params)); this._connection.onDidChangeConfiguration((params) => { this.console.log(`Received updated settings`); if (params?.settings) { this._defaultClientConfig = params?.settings; } this.updateSettingsForAllWorkspaces(); }); this._connection.onInitialized(() => { if (this._hasWorkspaceFoldersCapability) { this._connection.workspace.onDidChangeWorkspaceFolders((event) => { event.removed.forEach((workspace) => { const rootPath = convertUriToPath(workspace.uri); this._workspaceMap.delete(rootPath); }); event.added.forEach(async (workspace) => { const rootPath = convertUriToPath(workspace.uri); const newWorkspace = this.createWorkspaceServiceInstance(workspace, rootPath); this._workspaceMap.set(rootPath, newWorkspace); await this.updateSettingsForWorkspace(newWorkspace); }); }); } }); this._connection.onExecuteCommand(async (params, token, reporter) => { // Cancel running command if there is one. if (this._pendingCommandCancellationSource) { this._pendingCommandCancellationSource.cancel(); this._pendingCommandCancellationSource = undefined; } // Create a progress dialog for long-running commands. const progress = await this._getProgressReporter( params.workDoneToken, reporter, Localizer.CodeAction.executingCommand() ); const source = CancelAfter(token, progress.token); this._pendingCommandCancellationSource = source; try { return this.executeCommand(params, token); } finally { progress.reporter.done(); source.dispose(); } }); } protected initialize(params: InitializeParams): InitializeResult { this.rootPath = params.rootPath || ''; const capabilities = params.capabilities; this._hasWorkspaceFoldersCapability = !!capabilities.workspace?.workspaceFolders; // Create a service instance for each of the workspace folders. if (params.workspaceFolders) { params.workspaceFolders.forEach((folder) => { const path = convertUriToPath(folder.uri); this.console.info(`create ${path}`); this._workspaceMap.set(path, this.createWorkspaceServiceInstance(folder, path)); }); } else if (params.rootPath) { this.console.info(`create root path ${params.rootPath}`); this._workspaceMap.set(params.rootPath, this.createWorkspaceServiceInstance(undefined, params.rootPath)); } const result: InitializeResult = { capabilities: { textDocumentSync: TextDocumentSyncKind.Incremental, executeCommandProvider: { commands: [], workDoneProgress: true, }, }, }; return result; } protected convertLogLevel(logLevelValue?: string): LogLevel { if (!logLevelValue) { return LogLevel.Info; } switch (logLevelValue.toLowerCase()) { case 'error': return LogLevel.Error; case 'warning': return LogLevel.Warn; case 'information': return LogLevel.Info; case 'trace': return LogLevel.Log; default: return LogLevel.Info; } } protected createWorkspaceServiceInstance( workspace: WorkspaceFolder | undefined, rootPath: string ): PyteaWorkspaceInstance { const pyrightService = this.createAnalyzerService(workspace?.name ?? rootPath); const pyteaService = new PyteaService(pyrightService, undefined, this.console); return { workspaceName: workspace?.name ?? '', rootPath, rootUri: workspace?.uri ?? '', serviceInstance: pyrightService, pyteaService: pyteaService, pyteaOptions: defaultOptions, disableLanguageServices: true, disableOrganizeImports: true, isInitialized: createDeferred<boolean>(), selectedPath: 0, paths: [], }; } protected onAnalysisCompletedHandler(results: AnalysisResults): void { // TODO: Set Diagnostic // Send the computed diagnostics to the client. // results.diagnostics.forEach((fileDiag) => { // this._connection.sendDiagnostics({ // uri: convertPathToUri(fileDiag.filePath), // diagnostics: this._convertDiagnostics(fileDiag.diagnostics), // }); // }); this.console.info(`pyright analysis finished`); } protected async getConfiguration(scopeUri: string | undefined, section: string) { if (this._hasConfigurationCapability) { const item: ConfigurationItem = { scopeUri, section, }; return this._connection.workspace.getConfiguration(item); } if (this._defaultClientConfig) { return getNestedProperty(this._defaultClientConfig, section); } return undefined; } // Expands certain predefined variables supported within VS Code settings. // Ideally, VS Code would provide an API for doing this expansion, but // it doesn't. We'll handle the most common variables here as a convenience. protected expandPathVariables(rootPath: string, value: string): string { const regexp = /\$\{(.*?)\}/g; return value.replace(regexp, (match: string, name: string) => { const trimmedName = name.trim(); if (trimmedName === 'workspaceFolder') { return rootPath; } if (trimmedName === 'env:HOME' && process.env.HOME !== undefined) { return process.env.HOME; } return match; }); } protected getDocumentationUrlForDiagnosticRule(rule: string): string | undefined { // For now, return the same URL for all rules. We can separate these // in the future. return 'https://github.com/microsoft/pyright/blob/master/docs/configuration.md'; } private _getCompatibleMarkupKind(clientSupportedFormats: MarkupKind[] | undefined) { const serverSupportedFormats = [MarkupKind.PlainText, MarkupKind.Markdown]; for (const format of clientSupportedFormats ?? []) { if (serverSupportedFormats.includes(format)) { return format; } } return MarkupKind.PlainText; } private _convertDiagnostics(diags: AnalyzerDiagnostic[]): Diagnostic[] { const convertedDiags: Diagnostic[] = []; diags.forEach((diag) => { const severity = convertCategoryToSeverity(diag.category); const rule = diag.getRule(); const vsDiag = Diagnostic.create(diag.range, diag.message, severity, rule, this._serverOptions.productName); if (diag.category === DiagnosticCategory.UnusedCode) { vsDiag.tags = [DiagnosticTag.Unnecessary]; vsDiag.severity = DiagnosticSeverity.Hint; } if (rule) { const ruleDocUrl = this.getDocumentationUrlForDiagnosticRule(rule); if (ruleDocUrl) { vsDiag.codeDescription = { href: ruleDocUrl, }; } } const relatedInfo = diag.getRelatedInfo(); if (relatedInfo.length > 0) { vsDiag.relatedInformation = relatedInfo.map((info) => { return DiagnosticRelatedInformation.create( Location.create(convertPathToUri(info.filePath), info.range), info.message ); }); } convertedDiags.push(vsDiag); }); function convertCategoryToSeverity(category: DiagnosticCategory) { switch (category) { case DiagnosticCategory.Error: return DiagnosticSeverity.Error; case DiagnosticCategory.Warning: return DiagnosticSeverity.Warning; case DiagnosticCategory.Information: return DiagnosticSeverity.Information; case DiagnosticCategory.UnusedCode: return DiagnosticSeverity.Hint; } } return convertedDiags; } private async _getProgressReporter( workDoneToken: string | number | undefined, clientReporter: WorkDoneProgressReporter, title: string ) { if (workDoneToken) { return { reporter: clientReporter, token: CancellationToken.None }; } const serverInitiatedReporter = await this._connection.window.createWorkDoneProgress(); serverInitiatedReporter.begin(title, undefined, undefined, true); return { reporter: serverInitiatedReporter, token: serverInitiatedReporter.token, }; } } export function main() { if (process.env.NODE_ENV === 'production') { // eslint-disable-next-line @typescript-eslint/no-var-requires require('source-map-support').install(); } new PyteaServer(); } // run this extension main();
the_stack
import { ReactElement } from 'react'; import { EventEmitter } from 'events'; import { obx, computed, autorun, makeObservable, runInAction, wrapWithEventSwitch, action } from '@alilc/lowcode-editor-core'; import { isDOMText, isJSExpression, NodeSchema, PropsMap, PropsList, NodeData, I18nData, SlotSchema, PageSchema, ComponentSchema, NodeStatus, CompositeValue, GlobalEvent, ComponentAction, } from '@alilc/lowcode-types'; import { compatStage } from '@alilc/lowcode-utils'; import { SettingTopEntry } from '@alilc/lowcode-designer'; import { Node as ShellNode } from '@alilc/lowcode-shell'; import { Props, getConvertedExtraKey } from './props/props'; import { DocumentModel } from '../document-model'; import { NodeChildren } from './node-children'; import { Prop } from './props/prop'; import { ComponentMeta } from '../../component-meta'; import { ExclusiveGroup, isExclusiveGroup } from './exclusive-group'; import { TransformStage } from './transform-stage'; import { includeSlot, removeSlot } from '../../utils/slot'; import { foreachReverse } from '../../utils/tree'; import { NodeRemoveOptions } from '../../types'; /** * 基础节点 * * [Node Properties] * componentName: Page/Block/Component * props * children * * [Directives] * loop * loopArgs * condition * ------- addition support ----- * conditionGroup use for condition, for exclusive * title display on outline * ignored ignore this node will not publish to render, but will store * isLocked can not select/hover/ item on canvas and outline * hidden not visible on canvas * slotArgs like loopArgs, for slot node * * 根容器节点 * * [Node Properties] * componentName: Page/Block/Component * props * children * * [Root Container Extra Properties] * fileName * meta * state * defaultProps * dataSource * lifeCycles * methods * css * * [Directives **not used**] * loop * loopArgs * condition * ------- future support ----- * conditionGroup * title * ignored * isLocked * hidden */ export class Node<Schema extends NodeSchema = NodeSchema> { private emitter: EventEmitter; /** * 是节点实例 */ readonly isNode = true; /** * 节点 id */ readonly id: string; /** * 节点组件类型 * 特殊节点: * * Page 页面 * * Block 区块 * * Component 组件/元件 * * Fragment 碎片节点,无 props,有指令 * * Leaf 文字节点 | 表达式节点,无 props,无指令? * * Slot 插槽节点,无 props,正常 children,有 slotArgs,有指令 */ readonly componentName: string; /** * 属性抽象 */ props: Props; protected _children?: NodeChildren; /** * @deprecated */ private _addons: { [key: string]: { exportData: () => any; isProp: boolean } } = {}; @obx.ref private _parent: ParentalNode | null = null; /** * 父级节点 */ get parent(): ParentalNode | null { return this._parent; } /** * 当前节点子集 */ get children(): NodeChildren | null { return this._children || null; } /** * 当前节点深度 */ @computed get zLevel(): number { if (this._parent) { return this._parent.zLevel + 1; } return 0; } @computed get title(): string | I18nData | ReactElement { let t = this.getExtraProp('title'); // TODO: 暂时走不到这个分支 // if (!t && this.componentMeta.descriptor) { // t = this.getProp(this.componentMeta.descriptor, false); // } if (t) { const v = t.getAsString(); if (v) { return v; } } return this.componentMeta.title; } get icon() { return this.componentMeta.icon; } isInited = false; constructor(readonly document: DocumentModel, nodeSchema: Schema, options: any = {}) { makeObservable(this); const { componentName, id, children, props, ...extras } = nodeSchema; this.id = document.nextId(id); this.componentName = componentName; if (this.componentName === 'Leaf') { this.props = new Props(this, { children: isDOMText(children) || isJSExpression(children) ? children : '', }); } else { this.props = new Props(this, props, extras); this._children = new NodeChildren(this as ParentalNode, this.initialChildren(children)); this._children.internalInitParent(); this.props.merge( this.upgradeProps(this.initProps(props || {})), this.upgradeProps(extras), ); this.setupAutoruns(); } this.initBuiltinProps(); this.isInited = true; this.emitter = new EventEmitter(); } _settingEntry: SettingTopEntry; get settingEntry(): SettingTopEntry { if (this._settingEntry) return this._settingEntry; this._settingEntry = this.document.designer.createSettingEntry([this]); return this._settingEntry; } /** * 节点初始化期间就把内置的一些 prop 初始化好,避免后续不断构造实例导致 reaction 执行多次 */ @action private initBuiltinProps() { this.props.has(getConvertedExtraKey('hidden')) || this.props.add(false, getConvertedExtraKey('hidden')); this.props.has(getConvertedExtraKey('title')) || this.props.add('', getConvertedExtraKey('title')); this.props.has(getConvertedExtraKey('isLocked')) || this.props.add(false, getConvertedExtraKey('isLocked')); this.props.has(getConvertedExtraKey('condition')) || this.props.add(true, getConvertedExtraKey('condition')); this.props.has(getConvertedExtraKey('conditionGroup')) || this.props.add('', getConvertedExtraKey('conditionGroup')); this.props.has(getConvertedExtraKey('loop')) || this.props.add(undefined, getConvertedExtraKey('loop')); } @action private initProps(props: any): any { return this.document.designer.transformProps(props, this, TransformStage.Init); } @action private upgradeProps(props: any): any { return this.document.designer.transformProps(props, this, TransformStage.Upgrade); } private autoruns?: Array<() => void>; private setupAutoruns() { const autoruns = this.componentMeta.getMetadata().configure.advanced?.autoruns; if (!autoruns || autoruns.length < 1) { return; } this.autoruns = autoruns.map((item) => { return autorun(() => { item.autorun(this.props.get(item.name, true) as any); }); }); } private initialChildren(children: any): NodeData[] { // FIXME! this is dirty code if (children == null) { const initialChildren = this.componentMeta.getMetadata().configure.advanced?.initialChildren; if (initialChildren) { if (typeof initialChildren === 'function') { return initialChildren(this as any) || []; } return initialChildren; } } return children || []; } private _isRGLContainer = false; set isRGLContainer(status: boolean) { this._isRGLContainer = status; } get isRGLContainer(): boolean { return !!this._isRGLContainer; } isContainer(): boolean { return this.isParental() && this.componentMeta.isContainer; } isModal(): boolean { return this.componentMeta.isModal; } isRoot(): boolean { return this.document.rootNode === (this as any); } isPage(): boolean { return this.isRoot() && this.componentName === 'Page'; } isComponent(): boolean { return this.isRoot() && this.componentName === 'Component'; } isSlot(): boolean { return this._slotFor != null && this.componentName === 'Slot'; } /** * 是否一个父亲类节点 */ isParental(): this is ParentalNode { return !this.isLeaf(); } /** * 终端节点,内容一般为 文字 或者 表达式 */ isLeaf(): this is LeafNode { return this.componentName === 'Leaf'; } internalSetWillPurge() { this.internalSetParent(null); this.document.addWillPurge(this); } private didDropIn(dragment: Node) { const callbacks = this.componentMeta.getMetadata().configure.advanced?.callbacks; if (callbacks?.onNodeAdd) { const cbThis = this.internalToShellNode(); callbacks?.onNodeAdd.call(cbThis, dragment.internalToShellNode(), cbThis); } if (this._parent) { this._parent.didDropIn(dragment); } } private didDropOut(dragment: Node) { const callbacks = this.componentMeta.getMetadata().configure.advanced?.callbacks; if (callbacks?.onNodeRemove) { const cbThis = this.internalToShellNode(); callbacks?.onNodeRemove.call(cbThis, dragment.internalToShellNode(), cbThis); } if (this._parent) { this._parent.didDropOut(dragment); } } /** * 内部方法,请勿使用 * @param useMutator 是否触发联动逻辑 */ internalSetParent(parent: ParentalNode | null, useMutator = false) { if (this._parent === parent) { return; } // 解除老的父子关系,但不需要真的删除节点 if (this._parent) { if (this.isSlot()) { this._parent.unlinkSlot(this); } else { this._parent.children.unlinkChild(this); } } if (useMutator) { this._parent?.didDropOut(this); } if (parent) { // 建立新的父子关系,尤其注意:对于 parent 为 null 的场景,不会赋值,因为 subtreeModified 等事件可能需要知道该 node 被删除前的父子关系 this._parent = parent; this.document.removeWillPurge(this); /* istanbul ignore next */ if (!this.conditionGroup) { // initial conditionGroup const grp = this.getExtraProp('conditionGroup', false)?.getAsString(); if (grp) { this.setConditionGroup(grp); } } if (useMutator) { parent.didDropIn(this); } } } private _slotFor?: Prop | null = null; internalSetSlotFor(slotFor: Prop | null | undefined) { this._slotFor = slotFor; } internalToShellNode(): ShellNode | null { return ShellNode.create(this); } /** * 关联属性 */ get slotFor() { return this._slotFor; } /** * 移除当前节点 */ remove( useMutator = true, purge = true, options: NodeRemoveOptions = { suppressRemoveEvent: false }, ) { if (this.parent) { if (!options.suppressRemoveEvent) { this.document.designer.editor?.emit('node.remove.topLevel', { node: this, index: this.parent?.children?.indexOf(this), }); } if (this.isSlot()) { this.parent.removeSlot(this, purge); this.parent.children.delete(this, purge, useMutator, { suppressRemoveEvent: true }); } else { this.parent.children.delete(this, purge, useMutator, { suppressRemoveEvent: true }); } } } /** * 锁住当前节点 */ lock(flag = true) { this.setExtraProp('isLocked', flag); } /** * 获取当前节点的锁定状态 */ get isLocked(): boolean { return !!this.getExtraProp('isLocked')?.getValue(); } /** * 选择当前节点 */ select() { this.document.selection.select(this.id); } /** * 悬停高亮 */ hover(flag = true) { if (flag) { this.document.designer.detecting.capture(this); } else { this.document.designer.detecting.release(this); } } /** * 节点组件描述 */ @computed get componentMeta(): ComponentMeta { return this.document.getComponentMeta(this.componentName); } @computed get propsData(): PropsMap | PropsList | null { if (!this.isParental() || this.componentName === 'Fragment') { return null; } return this.props.export(TransformStage.Serilize).props || null; } @obx.shallow _slots: Node[] = []; hasSlots() { return this._slots.length > 0; } get slots() { return this._slots; } /* istanbul ignore next */ @obx.ref private _conditionGroup: ExclusiveGroup | null = null; /* istanbul ignore next */ get conditionGroup(): ExclusiveGroup | null { return this._conditionGroup; } /* istanbul ignore next */ setConditionGroup(grp: ExclusiveGroup | string | null) { if (!grp) { this.getExtraProp('conditionGroup', false)?.remove(); if (this._conditionGroup) { this._conditionGroup.remove(this); this._conditionGroup = null; } return; } if (!isExclusiveGroup(grp)) { if (this.prevSibling?.conditionGroup?.name === grp) { grp = this.prevSibling.conditionGroup; } else if (this.nextSibling?.conditionGroup?.name === grp) { grp = this.nextSibling.conditionGroup; } else { grp = new ExclusiveGroup(grp); } } if (this._conditionGroup !== grp) { this.getExtraProp('conditionGroup', true)?.setValue(grp.name); if (this._conditionGroup) { this._conditionGroup.remove(this); } this._conditionGroup = grp; grp.add(this); } } /* istanbul ignore next */ isConditionalVisible(): boolean | undefined { return this._conditionGroup?.isVisible(this); } /* istanbul ignore next */ setConditionalVisible() { this._conditionGroup?.setVisible(this); } hasCondition() { const v = this.getExtraProp('condition', false)?.getValue(); return v != null && v !== '' && v !== true; } /** * has loop when 1. loop is validArray with length > 1 ; OR 2. loop is variable object * @return boolean, has loop config or not */ hasLoop() { const value = this.getExtraProp('loop', false)?.getValue(); if (value === undefined || value === null) { return false; } if (Array.isArray(value)) { return true; } if (isJSExpression(value)) { return true; } return false; } /* istanbul ignore next */ wrapWith(schema: Schema) { const wrappedNode = this.replaceWith({ ...schema, children: [this.export()] }); return wrappedNode.children!.get(0); } replaceWith(schema: Schema, migrate = false): any { // reuse the same id? or replaceSelection schema = Object.assign({}, migrate ? this.export() : {}, schema); return this.parent?.replaceChild(this, schema); } /** * 替换子节点 * * @param {Node} node * @param {object} data */ replaceChild(node: Node, data: any): Node { if (this.children?.has(node)) { const selected = this.document.selection.has(node.id); delete data.id; const newNode = this.document.createNode(data); this.insertBefore(newNode, node, false); node.remove(false); if (selected) { this.document.selection.select(newNode.id); } return newNode; } return node; } setVisible(flag: boolean): void { this.getExtraProp('hidden')?.setValue(!flag); this.emitter.emit('visibleChange', flag); } getVisible(): boolean { return !this.getExtraProp('hidden')?.getValue(); } onVisibleChange(func: (flag: boolean) => any): () => void { const wrappedFunc = wrapWithEventSwitch(func); this.emitter.on('visibleChange', wrappedFunc); return () => { this.emitter.removeListener('visibleChange', wrappedFunc); }; } getProp(path: string, createIfNone = true): Prop | null { return this.props.query(path, createIfNone) || null; } getExtraProp(key: string, createIfNone = true): Prop | null { return this.props.get(getConvertedExtraKey(key), createIfNone) || null; } setExtraProp(key: string, value: CompositeValue) { this.getProp(getConvertedExtraKey(key), true)?.setValue(value); } /** * 获取单个属性值 */ getPropValue(path: string): any { return this.getProp(path, false)?.value; } /** * 设置单个属性值 */ setPropValue(path: string, value: any) { this.getProp(path, true)!.setValue(value); } /** * 清除已设置的值 */ clearPropValue(path: string): void { this.getProp(path, false)?.unset(); } /** * 设置多个属性值,和原有值合并 */ mergeProps(props: PropsMap) { this.props.merge(props); } /** * 设置多个属性值,替换原有值 */ setProps(props?: PropsMap | PropsList | Props | null) { if (props instanceof Props) { this.props = props; return; } this.props.import(props); } /** * 获取节点在父容器中的索引 */ @computed get index(): number { if (!this.parent) { return -1; } return this.parent.children.indexOf(this); } /** * 获取下一个兄弟节点 */ get nextSibling(): Node | null { if (!this.parent) { return null; } const { index } = this; if (index < 0) { return null; } return this.parent.children.get(index + 1); } /** * 获取上一个兄弟节点 */ get prevSibling(): Node | null { if (!this.parent) { return null; } const { index } = this; if (index < 1) { return null; } return this.parent.children.get(index - 1); } /** * 获取符合搭建协议-节点 schema 结构 */ get schema(): Schema { return this.export(TransformStage.Save); } set schema(data: Schema) { runInAction(() => this.import(data)); } import(data: Schema, checkId = false) { const { componentName, id, children, props, ...extras } = data; if (this.isSlot()) { foreachReverse( this.children!, (subNode: Node) => { subNode.remove(true, true); }, (iterable, idx) => (iterable as NodeChildren).get(idx), ); } if (this.isParental()) { this.props.import(props, extras); (this._children as NodeChildren).import(children, checkId); } else { this.props .get('children', true)! .setValue(isDOMText(children) || isJSExpression(children) ? children : ''); } } toData() { return this.export(); } /** * 导出 schema */ export(stage: TransformStage = TransformStage.Save, options: any = {}): Schema { stage = compatStage(stage); const baseSchema: any = { componentName: this.componentName, }; if (stage !== TransformStage.Clone) { baseSchema.id = this.id; } if (stage === TransformStage.Render) { baseSchema.docId = this.document.id; } if (this.isLeaf()) { if (!options.bypassChildren) { baseSchema.children = this.props.get('children')?.export(stage); } return baseSchema; } const { props = {}, extras } = this.props.export(stage) || {}; const _extras_: { [key: string]: any } = { ...extras, }; /* istanbul ignore next */ Object.keys(this._addons).forEach((key) => { const addon = this._addons[key]; if (addon) { if (addon.isProp) { (props as any)[getConvertedExtraKey(key)] = addon.exportData(); } else { _extras_[key] = addon.exportData(); } } }); const schema: any = { ...baseSchema, props: this.document.designer.transformProps(props, this, stage), ...this.document.designer.transformProps(_extras_, this, stage), }; if (this.isParental() && this.children.size > 0 && !options.bypassChildren) { schema.children = this.children.export(stage); } return schema; } /** * 判断是否包含特定节点 */ contains(node: Node): boolean { return contains(this, node); } /** * 获取特定深度的父亲节点 */ getZLevelTop(zLevel: number): Node | null { return getZLevelTop(this, zLevel); } /** * 判断与其它节点的位置关系 * * 16 thisNode contains otherNode * 8 thisNode contained_by otherNode * 2 thisNode before or after otherNode * 0 thisNode same as otherNode */ comparePosition(otherNode: Node): PositionNO { return comparePosition(this, otherNode); } unlinkSlot(slotNode: Node) { const i = this._slots.indexOf(slotNode); if (i < 0) { return false; } this._slots.splice(i, 1); } /** * 删除一个Slot节点 */ removeSlot(slotNode: Node, purge = false): boolean { // if (purge) { // // should set parent null // slotNode?.internalSetParent(null, false); // slotNode?.purge(); // } // this.document.unlinkNode(slotNode); // this.document.selection.remove(slotNode.id); const i = this._slots.indexOf(slotNode); if (i < 0) { return false; } this._slots.splice(i, 1); return false; } addSlot(slotNode: Node) { const slotName = slotNode?.getExtraProp('name')?.getAsString(); // 一个组件下的所有 slot,相同 slotName 的 slot 应该是唯一的 if (includeSlot(this, slotName)) { removeSlot(this, slotName); } slotNode.internalSetParent(this as ParentalNode, true); this._slots.push(slotNode); } /** * 当前node对应组件是否已注册可用 */ isValidComponent() { const allComponents = this.document?.designer?.componentsMap; if (allComponents && allComponents[this.componentName]) { return true; } return false; } /** * 删除一个节点 * @param node */ removeChild(node: Node) { this.children?.delete(node); } private purged = false; /** * 是否已销毁 */ get isPurged() { return this.purged; } /** * 销毁 */ purge() { if (this.purged) { return; } this.purged = true; this.autoruns?.forEach((dispose) => dispose()); this.props.purge(); this.settingEntry?.purge(); // this.document.destroyNode(this); } private purging: boolean = false; internalPurgeStart() { this.purging = true; } /** * 是否正在销毁 */ get isPurging() { return this.purging; } /** * 是否可执行某action */ canPerformAction(actionName: string): boolean { const availableActions = this.componentMeta?.availableActions?.filter((action: ComponentAction) => { const { condition } = action; return typeof condition === 'function' ? condition(this) !== false : condition !== false; }) .map((action: ComponentAction) => action.name) || []; return availableActions.indexOf(actionName) >= 0; } // ======= compatible apis ==== isEmpty(): boolean { return this.children ? this.children.isEmpty() : true; } getChildren() { return this.children; } getComponentName() { return this.componentName; } insert(node: Node, ref?: Node, useMutator = true) { this.insertAfter(node, ref, useMutator); } insertBefore(node: Node, ref?: Node, useMutator = true) { const nodeInstance = ensureNode(node, this.document); this.children?.insert(nodeInstance, ref ? ref.index : null, useMutator); } insertAfter(node: any, ref?: Node, useMutator = true) { const nodeInstance = ensureNode(node, this.document); this.children?.insert(nodeInstance, ref ? ref.index + 1 : null, useMutator); } getParent() { return this.parent; } getId() { return this.id; } getIndex() { return this.index; } getNode() { return this; } getRoot() { return this.document.rootNode; } getProps() { return this.props; } onChildrenChange(fn: (param?: { type: string; node: Node }) => void): (() => void) | undefined { const wrappedFunc = wrapWithEventSwitch(fn); return this.children?.onChange(wrappedFunc); } mergeChildren( remover: () => any, adder: (children: Node[]) => NodeData[] | null, sorter: () => any, ) { this.children?.mergeChildren(remover, adder, sorter); } @obx.shallow status: NodeStatus = { inPlaceEditing: false, locking: false, pseudo: false, }; /** * @deprecated */ getStatus(field?: keyof NodeStatus) { if (field && this.status[field] != null) { return this.status[field]; } return this.status; } /** * @deprecated */ setStatus(field: keyof NodeStatus, flag: boolean) { if (!this.status.hasOwnProperty(field)) { return; } if (flag !== this.status[field]) { this.status[field] = flag; } } /** * @deprecated */ getDOMNode(): any { const instance = this.document.simulator?.getComponentInstances(this)?.[0]; if (!instance) { return; } return this.document.simulator?.findDOMNodes(instance)?.[0]; } /** * @deprecated */ getPage() { console.warn('getPage is deprecated, use document instead'); return this.document; } /** * 获取磁贴相关信息 */ getRGL() { const isContainerNode = this.isContainer(); const isEmptyNode = this.isEmpty(); const isRGLContainerNode = this.isRGLContainer; const isRGLNode = this.getParent()?.isRGLContainer; const isRGL = isRGLContainerNode || (isRGLNode && (!isContainerNode || !isEmptyNode)); let rglNode = isRGLContainerNode ? this : isRGL ? this?.getParent() : {}; return { isContainerNode, isEmptyNode, isRGLContainerNode, isRGLNode, isRGL, rglNode }; } /** * @deprecated */ getSuitablePlace(node: Node, ref: any): any { const focusNode = this.document?.focusNode; // 如果节点是模态框,插入到根节点下 if (node?.componentMeta?.isModal) { return { container: focusNode, ref }; } if (!ref && this.contains(focusNode)) { const rootCanDropIn = focusNode.componentMeta?.prototype?.options?.canDropIn; if ( rootCanDropIn === undefined || rootCanDropIn === true || (typeof rootCanDropIn === 'function' && rootCanDropIn(node)) ) { return { container: focusNode }; } return null; } if (this.isRoot() && this.children) { const dropElement = this.children.filter((c) => { if (!c.isContainer()) { return false; } const canDropIn = c.componentMeta?.prototype?.options?.canDropIn; if ( canDropIn === undefined || canDropIn === true || (typeof canDropIn === 'function' && canDropIn(node)) ) { return true; } return false; })[0]; if (dropElement) { return { container: dropElement, ref }; } const rootCanDropIn = this.componentMeta?.prototype?.options?.canDropIn; if ( rootCanDropIn === undefined || rootCanDropIn === true || (typeof rootCanDropIn === 'function' && rootCanDropIn(node)) ) { return { container: this, ref }; } return null; } const canDropIn = this.componentMeta?.prototype?.options?.canDropIn; if (this.isContainer()) { if ( canDropIn === undefined || (typeof canDropIn === 'boolean' && canDropIn) || (typeof canDropIn === 'function' && canDropIn(node)) ) { return { container: this, ref }; } } if (this.parent) { return this.parent.getSuitablePlace(node, { index: this.index }); } return null; } /** * @deprecated */ getAddonData(key: string) { const addon = this._addons[key]; if (addon) { return addon.exportData(); } return this.getExtraProp(key)?.getValue(); } /** * @deprecated */ registerAddon(key: string, exportData: () => any, isProp = false) { this._addons[key] = { exportData, isProp }; } getRect(): DOMRect | null { if (this.isRoot()) { return this.document.simulator?.viewport.contentBounds || null; } return this.document.simulator?.computeRect(this) || null; } /** * @deprecated */ getPrototype() { return this.componentMeta.prototype; } /** * @deprecated */ setPrototype(proto: any) { this.componentMeta.prototype = proto; } getIcon() { return this.icon; } toString() { return this.id; } emitPropChange(val: PropChangeOptions) { this.emitter?.emit('propChange', val); } onPropChange(func: (info: PropChangeOptions) => void): Function { const wrappedFunc = wrapWithEventSwitch(func); this.emitter.on('propChange', wrappedFunc); return () => { this.emitter.removeListener('propChange', wrappedFunc); }; } } function ensureNode(node: any, document: DocumentModel): Node { let nodeInstance = node; if (!isNode(node)) { if (node.getComponentName) { nodeInstance = document.createNode({ componentName: node.getComponentName(), }); } else { nodeInstance = document.createNode(node); } } return nodeInstance; } export interface ParentalNode<T extends NodeSchema = NodeSchema> extends Node<T> { readonly children: NodeChildren; } export interface LeafNode extends Node { readonly children: null; } export type PropChangeOptions = Omit<GlobalEvent.Node.Prop.ChangeOptions, 'node'>; export type SlotNode = ParentalNode<SlotSchema>; export type PageNode = ParentalNode<PageSchema>; export type ComponentNode = ParentalNode<ComponentSchema>; export type RootNode = PageNode | ComponentNode; export function isNode(node: any): node is Node { return node && node.isNode; } export function isRootNode(node: Node): node is RootNode { return node && node.isRoot(); } export function isLowCodeComponent(node: Node): boolean { return node.componentMeta?.getMetadata().devMode === 'lowCode'; } export function getZLevelTop(child: Node, zLevel: number): Node | null { let l = child.zLevel; if (l < zLevel || zLevel < 0) { return null; } if (l === zLevel) { return child; } let r: any = child; while (r && l-- > zLevel) { r = r.parent; } return r; } /** * 测试两个节点是否为包含关系 * @param node1 测试的父节点 * @param node2 测试的被包含节点 * @returns 是否包含 */ export function contains(node1: Node, node2: Node): boolean { if (node1 === node2) { return true; } if (!node1.isParental() || !node2.parent) { return false; } const p = getZLevelTop(node2, node1.zLevel); if (!p) { return false; } return node1 === p; } // 16 node1 contains node2 // 8 node1 contained_by node2 // 2 node1 before or after node2 // 0 node1 same as node2 export enum PositionNO { Contains = 16, ContainedBy = 8, BeforeOrAfter = 2, TheSame = 0, } export function comparePosition(node1: Node, node2: Node): PositionNO { if (node1 === node2) { return PositionNO.TheSame; } const l1 = node1.zLevel; const l2 = node2.zLevel; if (l1 === l2) { return PositionNO.BeforeOrAfter; } let p: any; if (l1 < l2) { p = getZLevelTop(node2, l1); if (p && p === node1) { return PositionNO.Contains; } return PositionNO.BeforeOrAfter; } p = getZLevelTop(node1, l2); if (p && p === node2) { return PositionNO.ContainedBy; } return PositionNO.BeforeOrAfter; } export function insertChild( container: ParentalNode, thing: Node | NodeData, at?: number | null, copy?: boolean, ): Node { let node: Node; if (isNode(thing) && (copy || thing.isSlot())) { thing = thing.export(TransformStage.Clone); } if (isNode(thing)) { node = thing; } else { node = container.document.createNode(thing); } container.children.insert(node, at); return node; } export function insertChildren( container: ParentalNode, nodes: Node[] | NodeData[], at?: number | null, copy?: boolean, ): Node[] { let index = at; let node: any; const results: Node[] = []; // eslint-disable-next-line no-cond-assign while ((node = nodes.pop())) { node = insertChild(container, node, index, copy); results.push(node); index = node.index; } return results; }
the_stack
import { ABIParameter, Action, AddressString, ContractEventDescriptorClient, ContractMethodDescriptorClient, Event, ForwardOptions, GetOptions, Hash256String, InvokeReceipt, InvokeSendUnsafeReceiveTransactionOptions, Log, NetworkType, Param, RawAction, RawInvokeReceipt, Return, ScriptBuilderParam, SmartContractDefinition, SmartContractIterOptions, SmartContractNetworkDefinition, TransactionResult, Transfer, } from '@neo-one/client-common'; import { utils } from '@neo-one/utils'; import { AsyncIterableX } from '@reactivex/ix-es2015-cjs/asynciterable/asynciterablex'; import { filter } from '@reactivex/ix-es2015-cjs/asynciterable/pipe/filter'; import { map } from '@reactivex/ix-es2015-cjs/asynciterable/pipe/map'; import * as argAssertions from '../args'; import { Client } from '../Client'; import { NoContractDeployedError } from '../errors'; import { events as traceEvents } from '../trace'; import { SmartContractAny } from '../types'; import * as common from './common'; interface ParamAndOptionsResults { // tslint:disable-next-line:no-any readonly requiredArgs: readonly any[]; // tslint:disable-next-line:no-any readonly options: any; readonly forwardOptions: ForwardOptions | undefined; readonly transfer: Transfer | undefined; readonly hash: Hash256String | undefined; } export const getParamAndOptionsResults = ({ parameters, args, }: { readonly parameters: readonly ABIParameter[]; // tslint:disable-next-line no-any readonly args: readonly any[]; }): ParamAndOptionsResults => { const hasRest = parameters.length > 0 && parameters[parameters.length - 1].rest; const hasForwardValueOptions = hasRest && parameters[parameters.length - 1].type === 'ForwardValue'; return args.reduceRight<ParamAndOptionsResults>( (acc, right) => { if (hasForwardValueOptions && acc.forwardOptions === undefined && common.isForwardValueOptions(right)) { return { ...acc, forwardOptions: right, }; } if (common.isTransactionOptions(right) && acc.options === undefined) { return { ...acc, options: right, }; } // TODO: this block can almost definitely be removed. also remove transfer return likely if (acc.transfer === undefined) { try { const maybeTransfer = argAssertions.assertTransfer('transfer', right); return { ...acc, transfer: maybeTransfer, }; } catch { // } } // TODO: this block can almost definitely be removed. also remove hash return likely if (acc.hash === undefined) { try { const maybeHash = argAssertions.assertHash256('hash', right); return { ...acc, hash: maybeHash, }; } catch { // } } return { ...acc, requiredArgs: [right].concat(acc.requiredArgs), }; }, { requiredArgs: [], options: undefined, forwardOptions: undefined, transfer: undefined, hash: undefined, }, ); }; export const getParamsAndOptions = ({ definition: { networks }, parameters, args, receive, client, }: { readonly definition: SmartContractDefinition; readonly parameters: readonly ABIParameter[]; // tslint:disable-next-line no-any readonly args: readonly any[]; readonly receive: boolean; readonly client: Client; }): { readonly params: ReadonlyArray<ScriptBuilderParam | undefined>; readonly paramsZipped: ReadonlyArray<readonly [string, Param | undefined]>; readonly options: InvokeSendUnsafeReceiveTransactionOptions; readonly forwardOptions: ForwardOptions; readonly network: NetworkType; readonly address: AddressString; readonly transfer?: Transfer; readonly hash?: Hash256String; } => { const { requiredArgs, forwardOptions, options: optionsIn, transfer, hash, } = getParamAndOptionsResults({ parameters, args, }); const currentAccount = client.getCurrentUserAccount(); const options = (optionsIn === undefined || optionsIn.from === undefined) && currentAccount !== undefined ? { ...optionsIn, from: currentAccount.id, } : { ...optionsIn, }; const network = options.network === undefined ? options.from === undefined ? client.getCurrentNetwork() : options.from.network : options.network; const contractNetwork = networks[network] as SmartContractNetworkDefinition | undefined; if (contractNetwork === undefined) { throw new NoContractDeployedError(network); } // TODO: may need to add another check here depending on if we keep @receive decorator // if (options.sendTo !== undefined && !receive) { // throw new CannotSendToContractError(contractNetwork.address); // } const { converted, zipped } = common.convertParams({ params: requiredArgs, parameters, senderAddress: currentAccount === undefined ? undefined : currentAccount.id.address, }); return { params: converted, paramsZipped: zipped, options, forwardOptions: forwardOptions === undefined ? {} : forwardOptions, network, address: contractNetwork.address, transfer, hash, }; }; const createCall = ({ definition, client, func: { name, parameters = [], returnType, receive = false }, isNEOONEContract, }: { readonly definition: SmartContractDefinition; readonly client: Client; readonly func: ContractMethodDescriptorClient; readonly isNEOONEContract: boolean; }) => // tslint:disable-next-line no-any async (...args: any[]): Promise<Return | undefined> => { const { params, network, address } = getParamsAndOptions({ definition, parameters, args, receive, client, }); // For NEO•ONE contracts we need to add method name as the first param. This should be fixed const paramsIn = [name, ...params]; const receipt = await client.__call(network, address, name, isNEOONEContract ? paramsIn : params); return common.convertCallResult({ returnType, result: receipt.result, actions: receipt.actions, sourceMaps: definition.sourceMaps, }); }; const createInvoke = ({ definition, client, func: { name, parameters = [], returnType, receive = false }, isNEOONEContract, }: { readonly definition: SmartContractDefinition; readonly client: Client; readonly func: ContractMethodDescriptorClient; readonly isNEOONEContract: boolean; }) => { const invoke = async ( // tslint:disable-next-line no-any ...args: any[] ): Promise<TransactionResult<InvokeReceipt> | TransactionResult> => { const { params, paramsZipped, options, forwardOptions, address } = getParamsAndOptions({ definition, parameters, args, receive, client, }); // For NEO•ONE contracts we need to add method name as the first param. This should be fixed const paramsIn = [name, ...params]; const result: TransactionResult<RawInvokeReceipt> = await client.__invoke( address, name, isNEOONEContract ? paramsIn : params, paramsZipped, receive, options, definition.sourceMaps, ); return { transaction: result.transaction, confirmed: async (getOptions?): Promise<InvokeReceipt> => { const receipt = await result.confirmed(getOptions); const { events = [] } = definition.manifest.abi; const { events: forwardEvents = [] } = forwardOptions; const actions = common.convertActions({ actions: receipt.actions, events: events.concat(forwardEvents), }); const invocationResult = await common.convertInvocationResult({ returnType, result: receipt.result, actions: receipt.actions, sourceMaps: definition.sourceMaps, }); return { blockIndex: receipt.blockIndex, blockHash: receipt.blockHash, globalIndex: receipt.globalIndex, transactionIndex: receipt.transactionIndex, result: invocationResult, events: common.filterEvents(actions), logs: common.filterLogs(actions), raw: receipt, }; }, }; }; // tslint:disable-next-line no-any no-object-mutation (invoke as any).confirmed = async (...args: any[]) => { // tslint:disable-next-line no-any const finalArg = args[args.length - 1]; let options: GetOptions | undefined; if (common.isOptionsBase(finalArg)) { options = finalArg; } const result = await invoke(...args); const receipt = await result.confirmed(options); return { ...receipt, transaction: result.transaction }; }; return invoke; }; export const createSmartContract = ({ definition, client, isNEOONEContract, }: { readonly definition: SmartContractDefinition; readonly client: Client; readonly isNEOONEContract: boolean; }): SmartContractAny => { const { manifest: { abi: { events: abiEvents = [] }, }, } = definition; const events = traceEvents.concat(abiEvents).reduce<{ [key: string]: ContractEventDescriptorClient }>( (acc, event) => ({ ...acc, [event.name]: event, }), {}, ); const iterActionsRaw = ({ network = client.getCurrentNetwork(), ...iterOptions }: SmartContractIterOptions = {}): AsyncIterable<RawAction> => AsyncIterableX.from(client.__iterActionsRaw(network, iterOptions)).pipe<RawAction>( filter((action) => action.address === definition.networks[network].address), ); const convertAction = (action: RawAction): Action | undefined => { const converted = common.convertAction({ action, events }); return typeof converted === 'string' ? undefined : converted; }; const iterActions = (options?: SmartContractIterOptions): AsyncIterable<Action> => AsyncIterableX.from(iterActionsRaw(options)).pipe(map(convertAction), filter(utils.notNull)); const iterEvents = (options?: SmartContractIterOptions): AsyncIterable<Event> => AsyncIterableX.from(iterActions(options)).pipe( map((action) => { if (action.type === 'Log') { return undefined; } return action; }), filter(utils.notNull), filter<Event>(Boolean), ); const iterLogs = (options?: SmartContractIterOptions): AsyncIterable<Log> => AsyncIterableX.from(iterActions(options)).pipe( map((action) => { if (action.type === 'Event') { return undefined; } return action; }), filter(utils.notNull), filter<Log>(Boolean), ); return definition.manifest.abi.methods.reduce<SmartContractAny>( (acc, func) => common.addForward(func, abiEvents, { ...acc, [func.name]: func.constant === true ? createCall({ definition, client, func, isNEOONEContract, }) : createInvoke({ definition, client, func, isNEOONEContract, }), }), { client, iterEvents, iterLogs, iterActions, convertAction, definition, }, ); };
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as msRestAzure from "@azure/ms-rest-azure-js"; import * as Models from "../models"; import * as Mappers from "../models/aDCCatalogsMappers"; import * as Parameters from "../models/parameters"; import { DataCatalogRestClientContext } from "../dataCatalogRestClientContext"; /** Class representing a ADCCatalogs. */ export class ADCCatalogs { private readonly client: DataCatalogRestClientContext; /** * Create a ADCCatalogs. * @param {DataCatalogRestClientContext} client Reference to the service client. */ constructor(client: DataCatalogRestClientContext) { this.client = client; } /** * The List catalogs in Resource Group operation lists all the Azure Data Catalogs available under * the given resource group. * @summary List catalogs in Resource Group (GET Resources) * @param resourceGroupName The name of the resource group within the user's subscription. The name * is case insensitive. * @param [options] The optional parameters * @returns Promise<Models.ADCCatalogsListtByResourceGroupResponse> */ listtByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.ADCCatalogsListtByResourceGroupResponse>; /** * @param resourceGroupName The name of the resource group within the user's subscription. The name * is case insensitive. * @param callback The callback */ listtByResourceGroup(resourceGroupName: string, callback: msRest.ServiceCallback<Models.ADCCatalogsListResult>): void; /** * @param resourceGroupName The name of the resource group within the user's subscription. The name * is case insensitive. * @param options The optional parameters * @param callback The callback */ listtByResourceGroup(resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ADCCatalogsListResult>): void; listtByResourceGroup(resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ADCCatalogsListResult>, callback?: msRest.ServiceCallback<Models.ADCCatalogsListResult>): Promise<Models.ADCCatalogsListtByResourceGroupResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, listtByResourceGroupOperationSpec, callback) as Promise<Models.ADCCatalogsListtByResourceGroupResponse>; } /** * The Create Azure Data Catalog service operation creates a new data catalog service with the * specified parameters. If the specific service already exists, then any patchable properties will * be updated and any immutable properties will remain unchanged. * @summary Create or Update Azure Data Catalog service (PUT Resource) * @param resourceGroupName The name of the resource group within the user's subscription. The name * is case insensitive. * @param properties Properties supplied to the Create or Update a data catalog. * @param [options] The optional parameters * @returns Promise<Models.ADCCatalogsCreateOrUpdateResponse> */ createOrUpdate(resourceGroupName: string, properties: Models.ADCCatalog, options?: msRest.RequestOptionsBase): Promise<Models.ADCCatalogsCreateOrUpdateResponse>; /** * @param resourceGroupName The name of the resource group within the user's subscription. The name * is case insensitive. * @param properties Properties supplied to the Create or Update a data catalog. * @param callback The callback */ createOrUpdate(resourceGroupName: string, properties: Models.ADCCatalog, callback: msRest.ServiceCallback<Models.ADCCatalog>): void; /** * @param resourceGroupName The name of the resource group within the user's subscription. The name * is case insensitive. * @param properties Properties supplied to the Create or Update a data catalog. * @param options The optional parameters * @param callback The callback */ createOrUpdate(resourceGroupName: string, properties: Models.ADCCatalog, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ADCCatalog>): void; createOrUpdate(resourceGroupName: string, properties: Models.ADCCatalog, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ADCCatalog>, callback?: msRest.ServiceCallback<Models.ADCCatalog>): Promise<Models.ADCCatalogsCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, properties, options }, createOrUpdateOperationSpec, callback) as Promise<Models.ADCCatalogsCreateOrUpdateResponse>; } /** * The Get Azure Data Catalog Service operation retrieves a json representation of the data * catalog. * @summary Get Azure Data Catalog service (GET Resources) * @param resourceGroupName The name of the resource group within the user's subscription. The name * is case insensitive. * @param [options] The optional parameters * @returns Promise<Models.ADCCatalogsGetResponse> */ get(resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<Models.ADCCatalogsGetResponse>; /** * @param resourceGroupName The name of the resource group within the user's subscription. The name * is case insensitive. * @param callback The callback */ get(resourceGroupName: string, callback: msRest.ServiceCallback<Models.ADCCatalog>): void; /** * @param resourceGroupName The name of the resource group within the user's subscription. The name * is case insensitive. * @param options The optional parameters * @param callback The callback */ get(resourceGroupName: string, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ADCCatalog>): void; get(resourceGroupName: string, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ADCCatalog>, callback?: msRest.ServiceCallback<Models.ADCCatalog>): Promise<Models.ADCCatalogsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, options }, getOperationSpec, callback) as Promise<Models.ADCCatalogsGetResponse>; } /** * The Delete Azure Data Catalog Service operation deletes an existing data catalog. * @summary Delete Azure Data Catalog Service (DELETE Resource) * @param resourceGroupName The name of the resource group within the user's subscription. The name * is case insensitive. * @param [options] The optional parameters * @returns Promise<msRest.RestResponse> */ deleteMethod(resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<msRest.RestResponse> { return this.beginDeleteMethod(resourceGroupName,options) .then(lroPoller => lroPoller.pollUntilFinished()); } /** * The Update Azure Data Catalog Service operation can be used to update the existing deployment. * The update call only supports the properties listed in the PATCH body. * @summary Update Azure Data Catalog Service (PATCH Resource) * @param resourceGroupName The name of the resource group within the user's subscription. The name * is case insensitive. * @param properties Properties supplied to the Update a data catalog. * @param [options] The optional parameters * @returns Promise<Models.ADCCatalogsUpdateResponse> */ update(resourceGroupName: string, properties: Models.ADCCatalog, options?: msRest.RequestOptionsBase): Promise<Models.ADCCatalogsUpdateResponse>; /** * @param resourceGroupName The name of the resource group within the user's subscription. The name * is case insensitive. * @param properties Properties supplied to the Update a data catalog. * @param callback The callback */ update(resourceGroupName: string, properties: Models.ADCCatalog, callback: msRest.ServiceCallback<Models.ADCCatalog>): void; /** * @param resourceGroupName The name of the resource group within the user's subscription. The name * is case insensitive. * @param properties Properties supplied to the Update a data catalog. * @param options The optional parameters * @param callback The callback */ update(resourceGroupName: string, properties: Models.ADCCatalog, options: msRest.RequestOptionsBase, callback: msRest.ServiceCallback<Models.ADCCatalog>): void; update(resourceGroupName: string, properties: Models.ADCCatalog, options?: msRest.RequestOptionsBase | msRest.ServiceCallback<Models.ADCCatalog>, callback?: msRest.ServiceCallback<Models.ADCCatalog>): Promise<Models.ADCCatalogsUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, properties, options }, updateOperationSpec, callback) as Promise<Models.ADCCatalogsUpdateResponse>; } /** * The Delete Azure Data Catalog Service operation deletes an existing data catalog. * @summary Delete Azure Data Catalog Service (DELETE Resource) * @param resourceGroupName The name of the resource group within the user's subscription. The name * is case insensitive. * @param [options] The optional parameters * @returns Promise<msRestAzure.LROPoller> */ beginDeleteMethod(resourceGroupName: string, options?: msRest.RequestOptionsBase): Promise<msRestAzure.LROPoller> { return this.client.sendLRORequest( { resourceGroupName, options }, beginDeleteMethodOperationSpec, options); } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const listtByResourceGroupOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataCatalog/catalogs", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ADCCatalogsListResult }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const createOrUpdateOperationSpec: msRest.OperationSpec = { httpMethod: "PUT", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataCatalog/catalogs/{catalogName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.catalogName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "properties", mapper: { ...Mappers.ADCCatalog, required: true } }, responses: { 200: { bodyMapper: Mappers.ADCCatalog }, 201: { bodyMapper: Mappers.ADCCatalog }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const getOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataCatalog/catalogs/{catalogName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.catalogName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: { bodyMapper: Mappers.ADCCatalog }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const updateOperationSpec: msRest.OperationSpec = { httpMethod: "PATCH", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataCatalog/catalogs/{catalogName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.catalogName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], requestBody: { parameterPath: "properties", mapper: { ...Mappers.ADCCatalog, required: true } }, responses: { 200: { bodyMapper: Mappers.ADCCatalog }, default: { bodyMapper: Mappers.CloudError } }, serializer }; const beginDeleteMethodOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataCatalog/catalogs/{catalogName}", urlParameters: [ Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.catalogName ], queryParameters: [ Parameters.apiVersion ], headerParameters: [ Parameters.acceptLanguage ], responses: { 200: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, serializer };
the_stack
"use strict"; import { getGlobal, strShimUndefined, strShimObject, strShimPrototype } from "@microsoft/applicationinsights-shims"; import { isString, isUndefined, strContains } from "./HelperFuncs"; // TypeScript removed this interface so we need to declare the global so we can check for it's existence. declare var XDomainRequest: any; /** * This file exists to hold environment utilities that are required to check and * validate the current operating environment. Unless otherwise required, please * only use defined methods (functions) in this class so that users of these * functions/properties only need to include those that are used within their own modules. */ const strWindow = "window"; const strDocument = "document"; const strNavigator = "navigator"; const strHistory = "history"; const strLocation = "location"; const strConsole = "console"; const strPerformance = "performance"; const strJSON = "JSON"; const strCrypto = "crypto"; const strMsCrypto = "msCrypto"; const strReactNative = "ReactNative"; const strMsie = "msie"; const strTrident = "trident/"; let _isTrident: boolean = null; let _navUserAgentCheck: string = null; let _enableMocks = false; let _useXDomainRequest: boolean | null = null; let _beaconsSupported: boolean | null = null; function _hasProperty(theClass: any, property: string) { let supported = false; if (theClass) { try { supported = property in theClass; if (!supported) { let proto = theClass[strShimPrototype]; if (proto) { supported = property in proto; } } } catch (e) { // Do Nothing } if (!supported) { try { let tmp = new theClass(); supported = !isUndefined(tmp[property]); } catch (e) { // Do Nothing } } } return supported; } /** * Enable the lookup of test mock objects if requested * @param enabled */ export function setEnableEnvMocks(enabled: boolean) { _enableMocks = enabled; } /** * Return the named global object if available, will return null if the object is not available. * @param name The globally named object */ export function getGlobalInst<T>(name:string): T { let gbl = getGlobal(); if (gbl && gbl[name]) { return gbl[name] as T; } // Test workaround, for environments where <global>.window (when global == window) doesn't return the base window if (name === strWindow && hasWindow()) { // tslint:disable-next-line: no-angle-bracket-type-assertion return <any>window as T; } return null; } /** * Checks if window object is available, this is required as we support the API running without a * window /document (eg. Node server, electron webworkers) and if we attempt to assign a window * object to a local variable or pass as an argument an "Uncaught ReferenceError: window is not defined" * exception will be thrown. * Defined as a function to support lazy / late binding environments. */ export function hasWindow(): boolean { return Boolean(typeof window === strShimObject && window); } /** * Returns the global window object if it is present otherwise null. * This helper is used to access the window object without causing an exception * "Uncaught ReferenceError: window is not defined" */ export function getWindow(): Window | null { if (hasWindow()) { return window; } // Return the global instance or null return getGlobalInst(strWindow); } /** * Checks if document object is available, this is required as we support the API running without a * window /document (eg. Node server, electron webworkers) and if we attempt to assign a document * object to a local variable or pass as an argument an "Uncaught ReferenceError: document is not defined" * exception will be thrown. * Defined as a function to support lazy / late binding environments. */ export function hasDocument(): boolean { return Boolean(typeof document === strShimObject && document); } /** * Returns the global document object if it is present otherwise null. * This helper is used to access the document object without causing an exception * "Uncaught ReferenceError: document is not defined" */ export function getDocument(): Document | null { if (hasDocument()) { return document; } return getGlobalInst(strDocument); } /** * Checks if navigator object is available, this is required as we support the API running without a * window /document (eg. Node server, electron webworkers) and if we attempt to assign a navigator * object to a local variable or pass as an argument an "Uncaught ReferenceError: navigator is not defined" * exception will be thrown. * Defined as a function to support lazy / late binding environments. */ export function hasNavigator(): boolean { return Boolean(typeof navigator === strShimObject && navigator); } /** * Returns the global navigator object if it is present otherwise null. * This helper is used to access the navigator object without causing an exception * "Uncaught ReferenceError: navigator is not defined" */ export function getNavigator(): Navigator | null { if (hasNavigator()) { return navigator; } return getGlobalInst(strNavigator); } /** * Checks if history object is available, this is required as we support the API running without a * window /document (eg. Node server, electron webworkers) and if we attempt to assign a history * object to a local variable or pass as an argument an "Uncaught ReferenceError: history is not defined" * exception will be thrown. * Defined as a function to support lazy / late binding environments. */ export function hasHistory(): boolean { return Boolean(typeof history === strShimObject && history); } /** * Returns the global history object if it is present otherwise null. * This helper is used to access the history object without causing an exception * "Uncaught ReferenceError: history is not defined" */ export function getHistory(): History | null { if (hasHistory()) { return history; } return getGlobalInst(strHistory); } /** * Returns the global location object if it is present otherwise null. * This helper is used to access the location object without causing an exception * "Uncaught ReferenceError: location is not defined" */ export function getLocation(checkForMock?: boolean): Location | null { if (checkForMock && _enableMocks) { let mockLocation = getGlobalInst("__mockLocation") as Location; if (mockLocation) { return mockLocation; } } if (typeof location === strShimObject && location) { return location; } return getGlobalInst(strLocation); } /** * Returns the global console object */ export function getConsole(): Console | null { if (typeof console !== strShimUndefined) { return console; } return getGlobalInst(strConsole); } /** * Returns the performance object if it is present otherwise null. * This helper is used to access the performance object from the current * global instance which could be window or globalThis for a web worker */ export function getPerformance(): Performance | null { return getGlobalInst(strPerformance); } /** * Checks if JSON object is available, this is required as we support the API running without a * window /document (eg. Node server, electron webworkers) and if we attempt to assign a history * object to a local variable or pass as an argument an "Uncaught ReferenceError: JSON is not defined" * exception will be thrown. * Defined as a function to support lazy / late binding environments. */ export function hasJSON(): boolean { return Boolean((typeof JSON === strShimObject && JSON) || getGlobalInst(strJSON) !== null); } /** * Returns the global JSON object if it is present otherwise null. * This helper is used to access the JSON object without causing an exception * "Uncaught ReferenceError: JSON is not defined" */ export function getJSON(): JSON | null { if (hasJSON()) { return JSON || getGlobalInst(strJSON); } return null; } /** * Returns the crypto object if it is present otherwise null. * This helper is used to access the crypto object from the current * global instance which could be window or globalThis for a web worker */ export function getCrypto(): Crypto | null { return getGlobalInst(strCrypto); } /** * Returns the crypto object if it is present otherwise null. * This helper is used to access the crypto object from the current * global instance which could be window or globalThis for a web worker */ export function getMsCrypto(): Crypto | null { return getGlobalInst(strMsCrypto); } /** * Returns whether the environment is reporting that we are running in a React Native Environment */ export function isReactNative(): boolean { // If running in React Native, navigator.product will be populated var nav = getNavigator(); if (nav && nav.product) { return nav.product === strReactNative; } return false; } /** * Identifies whether the current environment appears to be IE */ export function isIE() { let nav = getNavigator(); if (nav && (nav.userAgent !== _navUserAgentCheck || _isTrident === null)) { // Added to support test mocking of the user agent _navUserAgentCheck = nav.userAgent; let userAgent = (_navUserAgentCheck || "").toLowerCase(); _isTrident = (strContains(userAgent, strMsie) || strContains(userAgent, strTrident)); } return _isTrident; } /** * Gets IE version returning the document emulation mode if we are running on IE, or null otherwise */ export function getIEVersion(userAgentStr: string = null): number { if (!userAgentStr) { let navigator = getNavigator() || ({} as Navigator); userAgentStr = navigator ? (navigator.userAgent || "").toLowerCase() : ""; } var ua = (userAgentStr || "").toLowerCase(); if (strContains(ua, strMsie)) { return parseInt(ua.split(strMsie)[1]); } else if (strContains(ua, strTrident)) { let tridentVer = parseInt(ua.split(strTrident)[1]); if (tridentVer) { return tridentVer + 4; } } return null; } /** * Returns string representation of an object suitable for diagnostics logging. */ export function dumpObj(object: any): string { const objectTypeDump: string = Object[strShimPrototype].toString.call(object); let propertyValueDump: string = ""; if (objectTypeDump === "[object Error]") { propertyValueDump = "{ stack: '" + object.stack + "', message: '" + object.message + "', name: '" + object.name + "'"; } else if (hasJSON()) { propertyValueDump = getJSON().stringify(object); } return objectTypeDump + propertyValueDump; } export function isSafari(userAgentStr ?: string) { if (!userAgentStr || !isString(userAgentStr)) { let navigator = getNavigator() || ({} as Navigator); userAgentStr = navigator ? (navigator.userAgent || "").toLowerCase() : ""; } var ua = (userAgentStr || "").toLowerCase(); return (ua.indexOf("safari") >= 0); } /** * Checks if HTML5 Beacons are supported in the current environment. * @returns True if supported, false otherwise. */ export function isBeaconsSupported(): boolean { if (_beaconsSupported === null) { _beaconsSupported = hasNavigator() && Boolean(getNavigator().sendBeacon); } return _beaconsSupported; } /** * Checks if the Fetch API is supported in the current environment. * @param withKeepAlive - [Optional] If True, check if fetch is available and it supports the keepalive feature, otherwise only check if fetch is supported * @returns True if supported, otherwise false */ export function isFetchSupported(withKeepAlive?: boolean): boolean { let isSupported = false; try { const fetchApi = getGlobalInst("fetch"); isSupported = !!fetchApi; const request = getGlobalInst("Request"); if (isSupported && withKeepAlive && request) { isSupported = _hasProperty(request, "keepalive"); } } catch (e) { // Just Swallow any failure during availability checks } return isSupported; } export function useXDomainRequest(): boolean | undefined { if (_useXDomainRequest === null) { _useXDomainRequest = (typeof XDomainRequest !== undefined); if (_useXDomainRequest && isXhrSupported()) { _useXDomainRequest = _useXDomainRequest && !_hasProperty(getGlobalInst("XMLHttpRequest"), "withCredentials"); } } return _useXDomainRequest; } /** * Checks if XMLHttpRequest is supported * @returns True if supported, otherwise false */ export function isXhrSupported(): boolean { let isSupported = false; try { const xmlHttpRequest = getGlobalInst("XMLHttpRequest"); isSupported = !!xmlHttpRequest; } catch (e) { // Just Swallow any failure during availability checks } return isSupported; }
the_stack
import {LOCALE_ID} from '@angular/core'; import {TestBed, waitForAsync} from '@angular/core/testing'; import {DateAdapter, MAT_DATE_LOCALE} from '@angular/material/core'; import {DateTime} from 'luxon'; import {LuxonDateModule} from './index'; import {MAT_LUXON_DATE_ADAPTER_OPTIONS} from './luxon-date-adapter'; const JAN = 1, FEB = 2, MAR = 3, DEC = 12; describe('LuxonDateAdapter', () => { let adapter: DateAdapter<DateTime>; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [LuxonDateModule], }).compileComponents(); adapter = TestBed.inject(DateAdapter); adapter.setLocale('en-US'); })); it('should get year', () => { expect(adapter.getYear(DateTime.local(2017, JAN, 1))).toBe(2017); }); it('should get month', () => { expect(adapter.getMonth(DateTime.local(2017, JAN, 1))).toBe(0); }); it('should get date', () => { expect(adapter.getDate(DateTime.local(2017, JAN, 1))).toBe(1); }); it('should get day of week', () => { expect(adapter.getDayOfWeek(DateTime.local(2017, JAN, 1))).toBe(7); }); it('should get long month names', () => { expect(adapter.getMonthNames('long')).toEqual([ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ]); }); it('should get short month names', () => { expect(adapter.getMonthNames('short')).toEqual([ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', ]); }); it('should get narrow month names', () => { expect(adapter.getMonthNames('narrow')).toEqual([ 'J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D', ]); }); it('should get month names in a czech locale', () => { adapter.setLocale('cs-CZ'); expect(adapter.getMonthNames('long')).toEqual([ 'leden', 'únor', 'březen', 'duben', 'květen', 'červen', 'červenec', 'srpen', 'září', 'říjen', 'listopad', 'prosinec', ]); }); it('should get month names in a different locale', () => { adapter.setLocale('da-DK'); expect(adapter.getMonthNames('long')).toEqual([ 'januar', 'februar', 'marts', 'april', 'maj', 'juni', 'juli', 'august', 'september', 'oktober', 'november', 'december', ]); }); it('should get date names', () => { expect(adapter.getDateNames()).toEqual([ '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', ]); }); it('should get date names in a different locale', () => { adapter.setLocale('ja-JP'); expect(adapter.getDateNames()).toEqual([ '1日', '2日', '3日', '4日', '5日', '6日', '7日', '8日', '9日', '10日', '11日', '12日', '13日', '14日', '15日', '16日', '17日', '18日', '19日', '20日', '21日', '22日', '23日', '24日', '25日', '26日', '27日', '28日', '29日', '30日', '31日', ]); }); it('should get long day of week names', () => { expect(adapter.getDayOfWeekNames('long')).toEqual([ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', ]); }); it('should get short day of week names', () => { expect(adapter.getDayOfWeekNames('short')).toEqual([ 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', ]); }); it('should get narrow day of week names', () => { expect(adapter.getDayOfWeekNames('narrow')).toEqual(['S', 'M', 'T', 'W', 'T', 'F', 'S']); }); it('should get day of week names in a different locale', () => { adapter.setLocale('ja-JP'); expect(adapter.getDayOfWeekNames('long')).toEqual([ '日曜日', '月曜日', '火曜日', '水曜日', '木曜日', '金曜日', '土曜日', ]); }); it('should get year name', () => { expect(adapter.getYearName(DateTime.local(2017, JAN, 1))).toBe('2017'); }); it('should get year name in a different locale', () => { adapter.setLocale('ja-JP'); expect(adapter.getYearName(DateTime.local(2017, JAN, 1))).toBe('2017'); }); it('should get first day of week', () => { expect(adapter.getFirstDayOfWeek()).toBe(0); }); it('should create Luxon date', () => { expect(adapter.createDate(2017, JAN, 1) instanceof DateTime).toBe(true); }); it('should not create Luxon date with month over/under-flow', () => { expect(() => adapter.createDate(2017, 12, 1)).toThrow(); expect(() => adapter.createDate(2017, -1, 1)).toThrow(); }); it('should not create Luxon date with date over/under-flow', () => { expect(() => adapter.createDate(2017, JAN, 32)).toThrow(); expect(() => adapter.createDate(2017, JAN, 0)).toThrow(); }); it("should get today's date", () => { expect(adapter.sameDate(adapter.today(), DateTime.local())) .withContext("should be equal to today's date") .toBe(true); }); it('should parse string according to given format', () => { expect(adapter.parse('1/2/2017', 'L/d/yyyy')!.toISO()).toEqual( DateTime.local(2017, JAN, 2).toISO(), ); expect(adapter.parse('1/2/2017', 'd/L/yyyy')!.toISO()).toEqual( DateTime.local(2017, FEB, 1).toISO(), ); }); it('should parse string according to first matching format', () => { expect(adapter.parse('1/2/2017', ['L/d/yyyy', 'yyyy/d/L'])!.toISO()).toEqual( DateTime.local(2017, JAN, 2).toISO(), ); expect(adapter.parse('1/2/2017', ['yyyy/d/L', 'L/d/yyyy'])!.toISO()).toEqual( DateTime.local(2017, JAN, 2).toISO(), ); }); it('should throw if parse formats are an empty array', () => { expect(() => adapter.parse('1/2/2017', [])).toThrowError('Formats array must not be empty.'); }); it('should parse number', () => { let timestamp = new Date().getTime(); expect(adapter.parse(timestamp, 'LL/dd/yyyy')!.toISO()).toEqual( DateTime.fromMillis(timestamp).toISO(), ); }); it('should parse Date', () => { let date = new Date(2017, JAN, 1); expect(adapter.parse(date, 'LL/dd/yyyy')!.toISO()).toEqual(DateTime.fromJSDate(date).toISO()); }); it('should parse DateTime', () => { let date = DateTime.local(2017, JAN, 1); expect(adapter.parse(date, 'LL/dd/yyyy')!.toISO()).toEqual(date.toISO()); }); it('should parse empty string as null', () => { expect(adapter.parse('', 'LL/dd/yyyy')).toBeNull(); }); it('should parse invalid value as invalid', () => { let d = adapter.parse('hello', 'LL/dd/yyyy'); expect(d).not.toBeNull(); expect(adapter.isDateInstance(d)).toBe(true); expect(adapter.isValid(d as DateTime)) .withContext('Expected to parse as "invalid date" object') .toBe(false); }); it('should format date according to given format', () => { expect(adapter.format(DateTime.local(2017, JAN, 2), 'LL/dd/yyyy')).toEqual('01/02/2017'); }); it('should format with a different locale', () => { let date = adapter.format(DateTime.local(2017, JAN, 2), 'DD'); expect(date).toEqual('Jan 2, 2017'); adapter.setLocale('da-DK'); date = adapter.format(DateTime.local(2017, JAN, 2), 'DD'); expect(date).toEqual('2. jan. 2017'); }); it('should throw when attempting to format invalid date', () => { expect(() => adapter.format(DateTime.fromMillis(NaN), 'LL/dd/yyyy')).toThrowError( /LuxonDateAdapter: Cannot format invalid date\./, ); }); it('should add years', () => { expect(adapter.addCalendarYears(DateTime.local(2017, JAN, 1), 1).toISO()).toEqual( DateTime.local(2018, JAN, 1).toISO(), ); expect(adapter.addCalendarYears(DateTime.local(2017, JAN, 1), -1).toISO()).toEqual( DateTime.local(2016, JAN, 1).toISO(), ); }); it('should respect leap years when adding years', () => { expect(adapter.addCalendarYears(DateTime.local(2016, FEB, 29), 1).toISO()).toEqual( DateTime.local(2017, FEB, 28).toISO(), ); expect(adapter.addCalendarYears(DateTime.local(2016, FEB, 29), -1).toISO()).toEqual( DateTime.local(2015, FEB, 28).toISO(), ); }); it('should add months', () => { expect(adapter.addCalendarMonths(DateTime.local(2017, JAN, 1), 1).toISO()).toEqual( DateTime.local(2017, FEB, 1).toISO(), ); expect(adapter.addCalendarMonths(DateTime.local(2017, JAN, 1), -1).toISO()).toEqual( DateTime.local(2016, DEC, 1).toISO(), ); }); it('should respect month length differences when adding months', () => { expect(adapter.addCalendarMonths(DateTime.local(2017, JAN, 31), 1).toISO()).toEqual( DateTime.local(2017, FEB, 28).toISO(), ); expect(adapter.addCalendarMonths(DateTime.local(2017, MAR, 31), -1).toISO()).toEqual( DateTime.local(2017, FEB, 28).toISO(), ); }); it('should add days', () => { expect(adapter.addCalendarDays(DateTime.local(2017, JAN, 1), 1).toISO()).toEqual( DateTime.local(2017, JAN, 2).toISO(), ); expect(adapter.addCalendarDays(DateTime.local(2017, JAN, 1), -1).toISO()).toEqual( DateTime.local(2016, DEC, 31).toISO(), ); }); it('should clone', () => { let date = DateTime.local(2017, JAN, 1); let clone = adapter.clone(date); expect(clone).not.toBe(date); expect(clone.toISO()).toEqual(date.toISO()); }); it('should compare dates', () => { expect( adapter.compareDate(DateTime.local(2017, JAN, 1), DateTime.local(2017, JAN, 2)), ).toBeLessThan(0); expect( adapter.compareDate(DateTime.local(2017, JAN, 1), DateTime.local(2017, FEB, 1)), ).toBeLessThan(0); expect( adapter.compareDate(DateTime.local(2017, JAN, 1), DateTime.local(2018, JAN, 1)), ).toBeLessThan(0); expect(adapter.compareDate(DateTime.local(2017, JAN, 1), DateTime.local(2017, JAN, 1))).toBe(0); expect( adapter.compareDate(DateTime.local(2018, JAN, 1), DateTime.local(2017, JAN, 1)), ).toBeGreaterThan(0); expect( adapter.compareDate(DateTime.local(2017, FEB, 1), DateTime.local(2017, JAN, 1)), ).toBeGreaterThan(0); expect( adapter.compareDate(DateTime.local(2017, JAN, 2), DateTime.local(2017, JAN, 1)), ).toBeGreaterThan(0); }); it('should clamp date at lower bound', () => { expect( adapter.clampDate( DateTime.local(2017, JAN, 1), DateTime.local(2018, JAN, 1), DateTime.local(2019, JAN, 1), ), ).toEqual(DateTime.local(2018, JAN, 1)); }); it('should clamp date at upper bound', () => { expect( adapter.clampDate( DateTime.local(2020, JAN, 1), DateTime.local(2018, JAN, 1), DateTime.local(2019, JAN, 1), ), ).toEqual(DateTime.local(2019, JAN, 1)); }); it('should clamp date already within bounds', () => { expect( adapter.clampDate( DateTime.local(2018, FEB, 1), DateTime.local(2018, JAN, 1), DateTime.local(2019, JAN, 1), ), ).toEqual(DateTime.local(2018, FEB, 1)); }); it('should count today as a valid date instance', () => { let d = DateTime.local(); expect(adapter.isValid(d)).toBe(true); expect(adapter.isDateInstance(d)).toBe(true); }); it('should count an invalid date as an invalid date instance', () => { let d = DateTime.fromMillis(NaN); expect(adapter.isValid(d)).toBe(false); expect(adapter.isDateInstance(d)).toBe(true); }); it('should count a string as not a date instance', () => { let d = '1/1/2017'; expect(adapter.isDateInstance(d)).toBe(false); }); it('should count a Date as not a date instance', () => { let d = new Date(); expect(adapter.isDateInstance(d)).toBe(false); }); it('should create valid dates from valid ISO strings', () => { assertValidDate(adapter, adapter.deserialize('1985-04-12T23:20:50.52Z'), true); assertValidDate(adapter, adapter.deserialize('1996-12-19T16:39:57-08:00'), true); assertValidDate(adapter, adapter.deserialize('1937-01-01T12:00:27.87+00:20'), true); assertValidDate(adapter, adapter.deserialize('1990-13-31T23:59:00Z'), false); assertValidDate(adapter, adapter.deserialize('1/1/2017'), false); expect(adapter.deserialize('')).toBeNull(); expect(adapter.deserialize(null)).toBeNull(); assertValidDate(adapter, adapter.deserialize(new Date()), true); assertValidDate(adapter, adapter.deserialize(new Date(NaN)), false); assertValidDate(adapter, adapter.deserialize(DateTime.local()), true); assertValidDate(adapter, adapter.deserialize(DateTime.invalid('Not valid')), false); }); it('returned dates should have correct locale', () => { adapter.setLocale('ja-JP'); expect(adapter.createDate(2017, JAN, 1).locale).toBe('ja-JP'); expect(adapter.today().locale).toBe('ja-JP'); expect(adapter.parse('1/1/2017', 'L/d/yyyy')!.locale).toBe('ja-JP'); expect(adapter.addCalendarDays(DateTime.local(), 1).locale).toBe('ja-JP'); expect(adapter.addCalendarMonths(DateTime.local(), 1).locale).toBe('ja-JP'); expect(adapter.addCalendarYears(DateTime.local(), 1).locale).toBe('ja-JP'); }); it('should not change locale of DateTime passed as param', () => { const date = DateTime.local(); const initialLocale = date.locale; expect(initialLocale).toBeTruthy(); adapter.setLocale('ja-JP'); adapter.getYear(date); adapter.getMonth(date); adapter.getDate(date); adapter.getDayOfWeek(date); adapter.getYearName(date); adapter.getNumDaysInMonth(date); adapter.clone(date); adapter.parse(date, 'LL/dd/yyyy'); adapter.format(date, 'LL/dd/yyyy'); adapter.addCalendarDays(date, 1); adapter.addCalendarMonths(date, 1); adapter.addCalendarYears(date, 1); adapter.toIso8601(date); adapter.isDateInstance(date); adapter.isValid(date); expect(date.locale).toBe(initialLocale); }); it('should create invalid date', () => { assertValidDate(adapter, adapter.invalid(), false); }); }); describe('LuxonDateAdapter with MAT_DATE_LOCALE override', () => { let adapter: DateAdapter<DateTime>; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [LuxonDateModule], providers: [{provide: MAT_DATE_LOCALE, useValue: 'da-DK'}], }).compileComponents(); adapter = TestBed.inject(DateAdapter); })); it('should take the default locale id from the MAT_DATE_LOCALE injection token', () => { const date = adapter.format(DateTime.local(2017, JAN, 2), 'DD'); expect(date).toEqual('2. jan. 2017'); }); }); describe('LuxonDateAdapter with LOCALE_ID override', () => { let adapter: DateAdapter<DateTime>; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [LuxonDateModule], providers: [{provide: LOCALE_ID, useValue: 'fr-FR'}], }).compileComponents(); adapter = TestBed.inject(DateAdapter); })); it('should take the default locale id from the LOCALE_ID injection token', () => { const date = adapter.format(DateTime.local(2017, JAN, 2), 'DD'); expect(date).toEqual('2 janv. 2017'); }); }); describe('LuxonDateAdapter with MAT_LUXON_DATE_ADAPTER_OPTIONS override', () => { let adapter: DateAdapter<DateTime>; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ imports: [LuxonDateModule], providers: [ { provide: MAT_LUXON_DATE_ADAPTER_OPTIONS, useValue: {useUtc: true, firstDayOfWeek: 1}, }, ], }).compileComponents(); adapter = TestBed.inject(DateAdapter); })); describe('use UTC', () => { it('should create Luxon date in UTC', () => { // Use 0 since createDate takes 0-indexed months. expect(adapter.createDate(2017, 0, 5).toISO()).toBe(DateTime.utc(2017, JAN, 5).toISO()); }); it('should get first day of week', () => { expect(adapter.getFirstDayOfWeek()).toBe(1); }); it('should create today in UTC', () => { const today = adapter.today(); expect(today.toISO()).toBe(today.toUTC().toISO()); }); it('should parse dates to UTC', () => { const date = adapter.parse('1/2/2017', 'LL/dd/yyyy')!; expect(date.toISO()).toBe(date.toUTC().toISO()); }); it('should return UTC date when deserializing', () => { const date = adapter.deserialize('1985-04-12T23:20:50.52Z')!; expect(date.toISO()).toBe(date.toUTC().toISO()); }); }); }); function assertValidDate(adapter: DateAdapter<DateTime>, d: DateTime | null, valid: boolean) { expect(adapter.isDateInstance(d)) .not.withContext(`Expected ${d} to be a date instance`) .toBeNull(); expect(adapter.isValid(d!)) .withContext( `Expected ${d} to be ${valid ? 'valid' : 'invalid'},` + ` but was ${valid ? 'invalid' : 'valid'}`, ) .toBe(valid); }
the_stack
namespace pxt.py { export enum TokenType { Id, Op, Keyword, Number, String, NewLine, Comment, Indent, Dedent, EOF, Error } export interface Token { type: TokenType; value: string; auxValue?: any; quoted?: string; stringPrefix?: string; startPos: number; endPos: number; } export const keywords: Map<boolean> = { "False": true, "None": true, "True": true, "and": true, "as": true, "assert": true, "async": true, "await": true, "break": true, "class": true, "continue": true, "def": true, "del": true, "elif": true, "else": true, "except": true, "finally": true, "for": true, "from": true, "global": true, "if": true, "import": true, "in": true, "is": true, "lambda": true, "nonlocal": true, "not": true, "or": true, "pass": true, "raise": true, "return": true, "try": true, "while": true, "with": true, "yield": true, } let asciiParse: (() => void)[] = [] let allOps: Map<string> let revOps: Map<string> const eqOps: Map<string> = { "%": "Mod", "&": "BitAnd", "*": "Mult", "**": "Pow", "+": "Add", "-": "Sub", "/": "Div", "//": "FloorDiv", "<<": "LShift", ">>": "RShift", "@": "MatMult", "^": "BitXor", "|": "BitOr", } const nonEqOps: Map<string> = { "!": "Bang", // not really a token, but needed by the lexer "!=": "NotEq", "(": "LParen", ")": "RParen", ",": "Comma", "->": "Arrow", ".": "Dot", ":": "Colon", ";": "Semicolon", "<": "Lt", "<=": "LtE", "=": "Assign", "==": "Eq", ">": "Gt", ">=": "GtE", "[": "LSquare", "]": "RSquare", "{": "LBracket", "}": "RBracket", "~": "Invert", } const numBases: Map<RegExp> = { "b": /^[_0-1]$/, "B": /^[_0-1]$/, "o": /^[_0-7]$/, "O": /^[_0-7]$/, "x": /^[_0-9a-fA-F]$/, "X": /^[_0-9a-fA-F]$/, } const numBasesRadix: Map<number> = { "b": 2, "B": 2, "o": 8, "O": 8, "x": 16, "X": 16, } // resettable lexer state let res: Token[] let source: string let pos = 0, pos0 = 0 export function position(startPos: number, source: string) { let lineno = 0 let lastnl = 0 for (let i = 0; i < startPos; ++i) { if (source.charCodeAt(i) == 10) { lineno++ lastnl = i } } return { line: lineno, column: startPos - lastnl - 1 } } export function patchPosition(d: pxtc.KsDiagnostic, src: string) { if (!d.start && !d.length) { d.start = 0 d.length = 0 d.line = 0 d.column = 0 return } let p = position(d.start!, src) d.line = p.line d.column = p.column if (d.length! > 0) { p = position(d.start! + d.length! - 1, src) d.endLine = p.line d.endColumn = p.column + 2 // not sure where the +2 is coming from, but it works out in monaco } } export function tokenToString(t: Token) { switch (t.type) { case TokenType.Id: return `id(${t.value})` case TokenType.Op: return "'" + revOps[t.value] + "'" case TokenType.Keyword: return t.value case TokenType.Number: return `num(${t.value})` case TokenType.String: return t.stringPrefix + JSON.stringify(t.value) case TokenType.NewLine: return `<nl>` case TokenType.Comment: return `/* ${t.value} */` case TokenType.Indent: return "indent" + t.value case TokenType.Dedent: return "dedent" case TokenType.Error: return `[ERR: ${t.value}]` case TokenType.EOF: return "End of file" default: return "???" } } export function friendlyTokenToString(t: Token, source: string) { let len = t.endPos - t.startPos let s = "" if (len == 0) { s = tokenToString(t) } else if (len > 20) { s = "`" + source.slice(t.startPos, t.startPos + 20) + "`..." } else { s = "`" + source.slice(t.startPos, t.endPos) + "`" } s = s.replace(/\r/g, "") .replace(/\n/g, "\\n") .replace(/\t/g, "\\t") return s } export function tokensToString(ts: Token[]) { let r = "" let lineLen = 0 for (let t of ts) { let tmp = tokenToString(t) if (lineLen + tmp.length > 70) { lineLen = 0 r += "\n" } if (lineLen != 0) r += " " r += tmp lineLen += tmp.length if (t.type == TokenType.NewLine || t.type == TokenType.Comment) { lineLen = 0 r += "\n" } } return r } export function lex(_source: string) { if (asciiParse.length == 0) initAsciiParse() // these can't be local, since we capture lambdas from the first execution source = _source res = [] pos = 0 pos0 = 0 checkIndent() while (pos < source.length) { pos0 = pos const ch = source.charCodeAt(pos++) if (ch < 128) { asciiParse[ch]() } else if (rx.isIdentifierStart(ch)) { parseId(); } else if (rx.isSpace(ch)) { // skip } else if (rx.isNewline(ch)) { singleNewline() } else { invalidToken() } } pos0 = pos singleNewline() addToken(TokenType.EOF, "") return res function addToken(type: TokenType, val: string, aux?: any) { let t: Token = { type: type, value: val, startPos: pos0, endPos: pos, auxValue: aux } res.push(t) return t } function addError(msg: string) { addToken(TokenType.Error, msg) } function parseId() { while (rx.isIdentifierChar(source.charCodeAt(pos))) pos++ let id = source.slice(pos0, pos) let ch = source.charCodeAt(pos) if (keywords.hasOwnProperty(id)) addToken(TokenType.Keyword, id) else if (ch == 34 || ch == 39) parseStringPref(id) else addToken(TokenType.Id, id) } function singleOp(name: string) { addToken(TokenType.Op, name) } function multiOp(name: string) { let ch2 = source.slice(pos0, pos + 1) if (ch2.length == 2 && allOps.hasOwnProperty(ch2)) { let ch3 = source.slice(pos0, pos + 2) if (ch3.length == 3 && allOps.hasOwnProperty(ch3)) { pos += 2 name = allOps[ch3] } else { pos++ name = allOps[ch2] } } singleOp(name) } function asciiEsc(code: number) { switch (code) { case 97: return 7 // \a case 98: return 8 // \b case 102: return 12 // \f case 110: return 10 // \n case 114: return 13 // \r case 116: return 9 // \t case 118: return 11 // \v default: return 0 } } function unicode(c: number) { return ("0000" + c.toString(16)).slice(-4) } function parseStringPref(pref: string) { const delim = source.charCodeAt(pos++) let tripleMode = false if (source.charCodeAt(pos) == delim && source.charCodeAt(pos + 1) == delim) { pos += 2 tripleMode = true } pref = pref.toLowerCase() let rawMode = pref.indexOf("r") >= 0 let value = "" let quoted = "" while (true) { const ch = source.charCodeAt(pos++) if (ch == delim) { if (tripleMode) { if (source.charCodeAt(pos) == delim && source.charCodeAt(pos + 1) == delim) { pos += 2 break } else { quoted += "\\" + String.fromCharCode(delim) value += String.fromCharCode(delim) } } else { break } } else if (ch == 92) { let ch2 = source.charCodeAt(pos++) if (ch2 == 13 && source.charCodeAt(pos) == 10) { ch2 = 10 pos++ } if (ch2 == 34 || ch2 == 39 || ch2 == 92) { if (rawMode) { quoted += "\\" value += "\\" } quoted += "\\" + String.fromCharCode(ch2) value += String.fromCharCode(ch2) } else if (!rawMode && asciiEsc(ch2)) { quoted += "\\" + String.fromCharCode(ch2) value += String.fromCharCode(asciiEsc(ch2)) } else if (rx.isNewline(ch2)) { if (rawMode) { value += "\\" + String.fromCharCode(ch2) quoted += "\\\\" if (ch2 == 10) quoted += "\\n" else quoted += "\\u" + unicode(ch2) } else { // skip } } else if (!rawMode && ch2 == 48) { // handle \0 as special case quoted += "\\\\x00" value += "\x00" } else if (!rawMode && (ch2 == 117 || ch2 == 120)) { // We pass as is // TODO add support for octal (\123) let len = ch2 == 117 ? 4 : 2 let num = source.slice(pos, pos + len) pos += len let v = parseInt(num, 16) if (isNaN(v)) addError(U.lf("invalid unicode or hex escape")) quoted += "\\" + String.fromCharCode(ch2) + num value += String.fromCharCode(v) } else { quoted += "\\\\" + String.fromCharCode(ch2) value += "\\" + String.fromCharCode(ch2) } } else if (isNaN(ch)) { addError(U.lf("end of file in a string")) break } else { if (rx.isNewline(ch)) { if (!tripleMode) { addError(U.lf("new line in a string")) break } } value += String.fromCharCode(ch) quoted += String.fromCharCode(ch) } } let t = addToken(TokenType.String, value) t.quoted = quoted t.stringPrefix = pref } function parseString() { pos-- parseStringPref("") } function singleNewline() { addToken(TokenType.NewLine, "") checkIndent() } function checkIndent() { let ind = 0 while (true) { const ch = source.charCodeAt(pos) if (ch == 9) { // addError(U.lf("TAB indentaion not supported")) ind = (ind + 8) & ~7 pos++ continue } if (ch != 32) break ind++ pos++ } addToken(TokenType.Indent, "" + ind) } function parseBackslash() { let ch2 = source.charCodeAt(pos) if (rx.isNewline(ch2)) { pos++ if (ch2 == 13 && source.charCodeAt(pos) == 10) pos++ } else { addError(U.lf("unexpected character after line continuation character")) } } function parseComment() { addToken(TokenType.NewLine, "") while (pos < source.length) { if (rx.isNewline(source.charCodeAt(pos))) break pos++ } addToken(TokenType.Comment, source.slice(pos0 + 1, pos)) if (source.charCodeAt(pos) == 13 && source.charCodeAt(pos + 1) == 10) pos++ pos++ // skip newline checkIndent() } function parseNumber() { let c1 = source[pos0] let num = "" // TypeScript supports 0x, 0o, 0b, as well as _ in numbers, // so we just pass them as is if (c1 == "0") { let c2 = source[pos] const rx = numBases[c2] if (rx) { pos++ while (true) { const ch = source[pos] if (!rx.test(ch)) break num += ch pos++ } if (num) { let p = parseInt(num, numBasesRadix[c2]) if (isNaN(p)) addError(U.lf("invalid number")) addToken(TokenType.Number, c1 + c2 + num, p) } else addError(U.lf("expecting numbers to follow 0b, 0o, 0x")) return } } // decimal, possibly float let seenDot = false let seenE = false let minusAllowed = false pos = pos0 while (true) { const ch = source.charCodeAt(pos) if (minusAllowed && (ch == 43 || ch == 45)) { // ok } else { minusAllowed = false if (ch == 95 || isDigit(ch)) { // OK } else if (!seenE && !seenDot && ch == 46) { seenDot = true } else if (!seenE && (ch == 69 || ch == 101)) { seenE = true minusAllowed = true } else { break } } num += String.fromCharCode(ch) pos++ } if (!seenDot && !seenE && c1 == "0" && num.length > 1 && !/^0+/.test(num)) addError(U.lf("unexpected leading zero")) let p = parseFloat(num) if (isNaN(p)) addError(U.lf("invalid number")) addToken(TokenType.Number, num, p) } function parseDot() { if (isDigit(source.charCodeAt(pos))) parseNumber() else addToken(TokenType.Op, "Dot") } function isDigit(ch: number) { return (48 <= ch && ch <= 57) } function invalidToken() { addError(U.lf("invalid token")) } function initAsciiParse() { const specialParse: Map<() => void> = { "\"": parseString, "'": parseString, "#": parseComment, "\\": parseBackslash, ".": parseDot, } allOps = U.clone(nonEqOps) for (let k of Object.keys(eqOps)) { allOps[k] = eqOps[k] allOps[k + "="] = eqOps[k] + "Assign" } revOps = {} for (let k of Object.keys(allOps)) { revOps[allOps[k]] = k } for (let i = 0; i < 128; ++i) { if (rx.isIdentifierStart(i)) asciiParse[i] = parseId else { let s = String.fromCharCode(i) if (specialParse.hasOwnProperty(s)) { asciiParse[i] = specialParse[s] } else if (allOps.hasOwnProperty(s)) { let canBeLengthened = false let op = allOps[s] for (let kk of Object.keys(allOps)) { if (kk != s && kk.startsWith(s)) { canBeLengthened = true } } if (canBeLengthened) { asciiParse[i] = () => multiOp(op) } else { asciiParse[i] = () => singleOp(op) } } else if (rx.isSpace(i)) { asciiParse[i] = () => { } } else if (i == 13) { asciiParse[i] = () => { if (source.charCodeAt(pos) == 10) pos++ singleNewline() } } else if (rx.isNewline(i)) { asciiParse[i] = singleNewline } else if (isDigit(i)) { asciiParse[i] = parseNumber } else { asciiParse[i] = invalidToken } } } } } }
the_stack
import * as $protobuf from "protobufjs"; /** Properties of a ClientServerMessage. */ export interface IClientServerMessage { /** ClientServerMessage compression */ compression?: (Compression|null); /** ClientServerMessage uncompressedSize */ uncompressedSize?: (number|null); /** ClientServerMessage compressedData */ compressedData?: (Uint8Array|null); /** ClientServerMessage data */ data?: (IClientServer|null); } /** Represents a ClientServerMessage. */ export class ClientServerMessage implements IClientServerMessage { /** * Constructs a new ClientServerMessage. * @param [properties] Properties to set */ constructor(properties?: IClientServerMessage); /** ClientServerMessage compression. */ public compression: Compression; /** ClientServerMessage uncompressedSize. */ public uncompressedSize: number; /** ClientServerMessage compressedData. */ public compressedData: Uint8Array; /** ClientServerMessage data. */ public data?: (IClientServer|null); /** ClientServerMessage message. */ public message?: ("compressedData"|"data"); /** * Creates a new ClientServerMessage instance using the specified properties. * @param [properties] Properties to set * @returns ClientServerMessage instance */ public static create(properties?: IClientServerMessage): ClientServerMessage; /** * Encodes the specified ClientServerMessage message. Does not implicitly {@link ClientServerMessage.verify|verify} messages. * @param message ClientServerMessage message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IClientServerMessage, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ClientServerMessage message, length delimited. Does not implicitly {@link ClientServerMessage.verify|verify} messages. * @param message ClientServerMessage message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IClientServerMessage, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ClientServerMessage message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ClientServerMessage * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ClientServerMessage; /** * Decodes a ClientServerMessage message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ClientServerMessage * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ClientServerMessage; /** * Verifies a ClientServerMessage message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ClientServerMessage message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ClientServerMessage */ public static fromObject(object: { [k: string]: any }): ClientServerMessage; /** * Creates a plain object from a ClientServerMessage message. Also converts values to other types if specified. * @param message ClientServerMessage * @param [options] Conversion options * @returns Plain object */ public static toObject(message: ClientServerMessage, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ClientServerMessage to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ClientServer. */ export interface IClientServer { /** ClientServer messageType */ messageType?: (ClientServer.MessageType|null); /** ClientServer handshake */ handshake?: (IClientHandshake|null); /** ClientServer ping */ ping?: (IPing|null); /** ClientServer player */ player?: (IPlayer|null); /** ClientServer authenticate */ authenticate?: (IAuthenticate|null); /** ClientServer playerData */ playerData?: (IPlayerData|null); /** ClientServer metaData */ metaData?: (IMetaData|null); /** ClientServer chat */ chat?: (IChat|null); } /** Represents a ClientServer. */ export class ClientServer implements IClientServer { /** * Constructs a new ClientServer. * @param [properties] Properties to set */ constructor(properties?: IClientServer); /** ClientServer messageType. */ public messageType: ClientServer.MessageType; /** ClientServer handshake. */ public handshake?: (IClientHandshake|null); /** ClientServer ping. */ public ping?: (IPing|null); /** ClientServer player. */ public player?: (IPlayer|null); /** ClientServer authenticate. */ public authenticate?: (IAuthenticate|null); /** ClientServer playerData. */ public playerData?: (IPlayerData|null); /** ClientServer metaData. */ public metaData?: (IMetaData|null); /** ClientServer chat. */ public chat?: (IChat|null); /** ClientServer message. */ public message?: ("handshake"|"ping"|"player"|"authenticate"|"playerData"|"metaData"|"chat"); /** * Creates a new ClientServer instance using the specified properties. * @param [properties] Properties to set * @returns ClientServer instance */ public static create(properties?: IClientServer): ClientServer; /** * Encodes the specified ClientServer message. Does not implicitly {@link ClientServer.verify|verify} messages. * @param message ClientServer message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IClientServer, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ClientServer message, length delimited. Does not implicitly {@link ClientServer.verify|verify} messages. * @param message ClientServer message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IClientServer, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ClientServer message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ClientServer * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ClientServer; /** * Decodes a ClientServer message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ClientServer * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ClientServer; /** * Verifies a ClientServer message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ClientServer message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ClientServer */ public static fromObject(object: { [k: string]: any }): ClientServer; /** * Creates a plain object from a ClientServer message. Also converts values to other types if specified. * @param message ClientServer * @param [options] Conversion options * @returns Plain object */ public static toObject(message: ClientServer, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ClientServer to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } export namespace ClientServer { /** MessageType enum. */ enum MessageType { UNKNOWN = 0, HANDSHAKE = 2, PING = 3, PLAYER_UPDATE = 6, AUTHENTICATE = 7, PLAYER_DATA = 128, META_DATA = 129, CHAT = 130 } } /** Properties of a ClientHandshake. */ export interface IClientHandshake { /** ClientHandshake major */ major?: (number|null); /** ClientHandshake minor */ minor?: (number|null); /** ClientHandshake characterId */ characterId?: (number|null); /** ClientHandshake username */ username?: (string|null); } /** Represents a ClientHandshake. */ export class ClientHandshake implements IClientHandshake { /** * Constructs a new ClientHandshake. * @param [properties] Properties to set */ constructor(properties?: IClientHandshake); /** ClientHandshake major. */ public major: number; /** ClientHandshake minor. */ public minor: number; /** ClientHandshake characterId. */ public characterId: number; /** ClientHandshake username. */ public username: string; /** * Creates a new ClientHandshake instance using the specified properties. * @param [properties] Properties to set * @returns ClientHandshake instance */ public static create(properties?: IClientHandshake): ClientHandshake; /** * Encodes the specified ClientHandshake message. Does not implicitly {@link ClientHandshake.verify|verify} messages. * @param message ClientHandshake message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IClientHandshake, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ClientHandshake message, length delimited. Does not implicitly {@link ClientHandshake.verify|verify} messages. * @param message ClientHandshake message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IClientHandshake, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ClientHandshake message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ClientHandshake * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ClientHandshake; /** * Decodes a ClientHandshake message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ClientHandshake * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ClientHandshake; /** * Verifies a ClientHandshake message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ClientHandshake message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ClientHandshake */ public static fromObject(object: { [k: string]: any }): ClientHandshake; /** * Creates a plain object from a ClientHandshake message. Also converts values to other types if specified. * @param message ClientHandshake * @param [options] Conversion options * @returns Plain object */ public static toObject(message: ClientHandshake, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ClientHandshake to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Ping. */ export interface IPing { } /** Represents a Ping. */ export class Ping implements IPing { /** * Constructs a new Ping. * @param [properties] Properties to set */ constructor(properties?: IPing); /** * Creates a new Ping instance using the specified properties. * @param [properties] Properties to set * @returns Ping instance */ public static create(properties?: IPing): Ping; /** * Encodes the specified Ping message. Does not implicitly {@link Ping.verify|verify} messages. * @param message Ping message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IPing, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Ping message, length delimited. Does not implicitly {@link Ping.verify|verify} messages. * @param message Ping message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IPing, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Ping message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Ping * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): Ping; /** * Decodes a Ping message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Ping * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): Ping; /** * Verifies a Ping message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Ping message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Ping */ public static fromObject(object: { [k: string]: any }): Ping; /** * Creates a plain object from a Ping message. Also converts values to other types if specified. * @param message Ping * @param [options] Conversion options * @returns Plain object */ public static toObject(message: Ping, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Ping to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Player. */ export interface IPlayer { /** Player username */ username?: (string|null); /** Player characterId */ characterId?: (number|null); } /** Represents a Player. */ export class Player implements IPlayer { /** * Constructs a new Player. * @param [properties] Properties to set */ constructor(properties?: IPlayer); /** Player username. */ public username: string; /** Player characterId. */ public characterId: number; /** * Creates a new Player instance using the specified properties. * @param [properties] Properties to set * @returns Player instance */ public static create(properties?: IPlayer): Player; /** * Encodes the specified Player message. Does not implicitly {@link Player.verify|verify} messages. * @param message Player message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IPlayer, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Player message, length delimited. Does not implicitly {@link Player.verify|verify} messages. * @param message Player message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IPlayer, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Player message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Player * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): Player; /** * Decodes a Player message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Player * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): Player; /** * Verifies a Player message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Player message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Player */ public static fromObject(object: { [k: string]: any }): Player; /** * Creates a plain object from a Player message. Also converts values to other types if specified. * @param message Player * @param [options] Conversion options * @returns Plain object */ public static toObject(message: Player, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Player to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of an Authenticate. */ export interface IAuthenticate { /** Authenticate password */ password?: (string|null); } /** Represents an Authenticate. */ export class Authenticate implements IAuthenticate { /** * Constructs a new Authenticate. * @param [properties] Properties to set */ constructor(properties?: IAuthenticate); /** Authenticate password. */ public password: string; /** * Creates a new Authenticate instance using the specified properties. * @param [properties] Properties to set * @returns Authenticate instance */ public static create(properties?: IAuthenticate): Authenticate; /** * Encodes the specified Authenticate message. Does not implicitly {@link Authenticate.verify|verify} messages. * @param message Authenticate message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IAuthenticate, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Authenticate message, length delimited. Does not implicitly {@link Authenticate.verify|verify} messages. * @param message Authenticate message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IAuthenticate, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes an Authenticate message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Authenticate * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): Authenticate; /** * Decodes an Authenticate message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Authenticate * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): Authenticate; /** * Verifies an Authenticate message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates an Authenticate message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Authenticate */ public static fromObject(object: { [k: string]: any }): Authenticate; /** * Creates a plain object from an Authenticate message. Also converts values to other types if specified. * @param message Authenticate * @param [options] Conversion options * @returns Plain object */ public static toObject(message: Authenticate, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Authenticate to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a PlayerData. */ export interface IPlayerData { /** PlayerData dataLength */ dataLength?: (number|null); /** PlayerData playerBytes */ playerBytes?: (IPlayerBytes[]|null); } /** Represents a PlayerData. */ export class PlayerData implements IPlayerData { /** * Constructs a new PlayerData. * @param [properties] Properties to set */ constructor(properties?: IPlayerData); /** PlayerData dataLength. */ public dataLength: number; /** PlayerData playerBytes. */ public playerBytes: IPlayerBytes[]; /** * Creates a new PlayerData instance using the specified properties. * @param [properties] Properties to set * @returns PlayerData instance */ public static create(properties?: IPlayerData): PlayerData; /** * Encodes the specified PlayerData message. Does not implicitly {@link PlayerData.verify|verify} messages. * @param message PlayerData message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IPlayerData, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified PlayerData message, length delimited. Does not implicitly {@link PlayerData.verify|verify} messages. * @param message PlayerData message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IPlayerData, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a PlayerData message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns PlayerData * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): PlayerData; /** * Decodes a PlayerData message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns PlayerData * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): PlayerData; /** * Verifies a PlayerData message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a PlayerData message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns PlayerData */ public static fromObject(object: { [k: string]: any }): PlayerData; /** * Creates a plain object from a PlayerData message. Also converts values to other types if specified. * @param message PlayerData * @param [options] Conversion options * @returns Plain object */ public static toObject(message: PlayerData, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this PlayerData to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a PlayerBytes. */ export interface IPlayerBytes { /** PlayerBytes playerId */ playerId?: (number|null); /** PlayerBytes playerData */ playerData?: (Uint8Array|null); } /** Represents a PlayerBytes. */ export class PlayerBytes implements IPlayerBytes { /** * Constructs a new PlayerBytes. * @param [properties] Properties to set */ constructor(properties?: IPlayerBytes); /** PlayerBytes playerId. */ public playerId: number; /** PlayerBytes playerData. */ public playerData: Uint8Array; /** * Creates a new PlayerBytes instance using the specified properties. * @param [properties] Properties to set * @returns PlayerBytes instance */ public static create(properties?: IPlayerBytes): PlayerBytes; /** * Encodes the specified PlayerBytes message. Does not implicitly {@link PlayerBytes.verify|verify} messages. * @param message PlayerBytes message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IPlayerBytes, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified PlayerBytes message, length delimited. Does not implicitly {@link PlayerBytes.verify|verify} messages. * @param message PlayerBytes message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IPlayerBytes, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a PlayerBytes message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns PlayerBytes * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): PlayerBytes; /** * Decodes a PlayerBytes message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns PlayerBytes * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): PlayerBytes; /** * Verifies a PlayerBytes message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a PlayerBytes message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns PlayerBytes */ public static fromObject(object: { [k: string]: any }): PlayerBytes; /** * Creates a plain object from a PlayerBytes message. Also converts values to other types if specified. * @param message PlayerBytes * @param [options] Conversion options * @returns Plain object */ public static toObject(message: PlayerBytes, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this PlayerBytes to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Meta. */ export interface IMeta { /** Meta length */ length?: (number|null); /** Meta address */ address?: (number|null); /** Meta data */ data?: (Uint8Array|null); } /** Represents a Meta. */ export class Meta implements IMeta { /** * Constructs a new Meta. * @param [properties] Properties to set */ constructor(properties?: IMeta); /** Meta length. */ public length: number; /** Meta address. */ public address: number; /** Meta data. */ public data: Uint8Array; /** * Creates a new Meta instance using the specified properties. * @param [properties] Properties to set * @returns Meta instance */ public static create(properties?: IMeta): Meta; /** * Encodes the specified Meta message. Does not implicitly {@link Meta.verify|verify} messages. * @param message Meta message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IMeta, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Meta message, length delimited. Does not implicitly {@link Meta.verify|verify} messages. * @param message Meta message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IMeta, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Meta message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Meta * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): Meta; /** * Decodes a Meta message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Meta * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): Meta; /** * Verifies a Meta message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Meta message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Meta */ public static fromObject(object: { [k: string]: any }): Meta; /** * Creates a plain object from a Meta message. Also converts values to other types if specified. * @param message Meta * @param [options] Conversion options * @returns Plain object */ public static toObject(message: Meta, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Meta to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a MetaData. */ export interface IMetaData { /** MetaData metaData */ metaData?: (IMeta[]|null); } /** Represents a MetaData. */ export class MetaData implements IMetaData { /** * Constructs a new MetaData. * @param [properties] Properties to set */ constructor(properties?: IMetaData); /** MetaData metaData. */ public metaData: IMeta[]; /** * Creates a new MetaData instance using the specified properties. * @param [properties] Properties to set * @returns MetaData instance */ public static create(properties?: IMetaData): MetaData; /** * Encodes the specified MetaData message. Does not implicitly {@link MetaData.verify|verify} messages. * @param message MetaData message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IMetaData, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified MetaData message, length delimited. Does not implicitly {@link MetaData.verify|verify} messages. * @param message MetaData message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IMetaData, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a MetaData message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns MetaData * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): MetaData; /** * Decodes a MetaData message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns MetaData * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): MetaData; /** * Verifies a MetaData message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a MetaData message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns MetaData */ public static fromObject(object: { [k: string]: any }): MetaData; /** * Creates a plain object from a MetaData message. Also converts values to other types if specified. * @param message MetaData * @param [options] Conversion options * @returns Plain object */ public static toObject(message: MetaData, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this MetaData to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a Chat. */ export interface IChat { /** Chat chatType */ chatType?: (Chat.ChatType|null); /** Chat senderId */ senderId?: (number|null); /** Chat message */ message?: (string|null); /** Chat global */ global?: (IChatGlobal|null); /** Chat private */ "private"?: (IChatPrivate|null); /** Chat command */ command?: (IChatCommand|null); } /** Represents a Chat. */ export class Chat implements IChat { /** * Constructs a new Chat. * @param [properties] Properties to set */ constructor(properties?: IChat); /** Chat chatType. */ public chatType: Chat.ChatType; /** Chat senderId. */ public senderId: number; /** Chat message. */ public message: string; /** Chat global. */ public global?: (IChatGlobal|null); /** Chat private. */ public private?: (IChatPrivate|null); /** Chat command. */ public command?: (IChatCommand|null); /** Chat messageType. */ public messageType?: ("global"|"private"|"command"); /** * Creates a new Chat instance using the specified properties. * @param [properties] Properties to set * @returns Chat instance */ public static create(properties?: IChat): Chat; /** * Encodes the specified Chat message. Does not implicitly {@link Chat.verify|verify} messages. * @param message Chat message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IChat, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified Chat message, length delimited. Does not implicitly {@link Chat.verify|verify} messages. * @param message Chat message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IChat, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a Chat message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns Chat * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): Chat; /** * Decodes a Chat message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns Chat * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): Chat; /** * Verifies a Chat message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a Chat message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns Chat */ public static fromObject(object: { [k: string]: any }): Chat; /** * Creates a plain object from a Chat message. Also converts values to other types if specified. * @param message Chat * @param [options] Conversion options * @returns Plain object */ public static toObject(message: Chat, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this Chat to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } export namespace Chat { /** ChatType enum. */ enum ChatType { GLOBAL = 0, PRIVATE = 1, COMMAND = 255 } } /** Properties of a ChatGlobal. */ export interface IChatGlobal { } /** Represents a ChatGlobal. */ export class ChatGlobal implements IChatGlobal { /** * Constructs a new ChatGlobal. * @param [properties] Properties to set */ constructor(properties?: IChatGlobal); /** * Creates a new ChatGlobal instance using the specified properties. * @param [properties] Properties to set * @returns ChatGlobal instance */ public static create(properties?: IChatGlobal): ChatGlobal; /** * Encodes the specified ChatGlobal message. Does not implicitly {@link ChatGlobal.verify|verify} messages. * @param message ChatGlobal message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IChatGlobal, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ChatGlobal message, length delimited. Does not implicitly {@link ChatGlobal.verify|verify} messages. * @param message ChatGlobal message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IChatGlobal, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ChatGlobal message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ChatGlobal * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ChatGlobal; /** * Decodes a ChatGlobal message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ChatGlobal * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ChatGlobal; /** * Verifies a ChatGlobal message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ChatGlobal message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ChatGlobal */ public static fromObject(object: { [k: string]: any }): ChatGlobal; /** * Creates a plain object from a ChatGlobal message. Also converts values to other types if specified. * @param message ChatGlobal * @param [options] Conversion options * @returns Plain object */ public static toObject(message: ChatGlobal, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ChatGlobal to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ChatPrivate. */ export interface IChatPrivate { /** ChatPrivate receiverId */ receiverId?: (number|null); } /** Represents a ChatPrivate. */ export class ChatPrivate implements IChatPrivate { /** * Constructs a new ChatPrivate. * @param [properties] Properties to set */ constructor(properties?: IChatPrivate); /** ChatPrivate receiverId. */ public receiverId: number; /** * Creates a new ChatPrivate instance using the specified properties. * @param [properties] Properties to set * @returns ChatPrivate instance */ public static create(properties?: IChatPrivate): ChatPrivate; /** * Encodes the specified ChatPrivate message. Does not implicitly {@link ChatPrivate.verify|verify} messages. * @param message ChatPrivate message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IChatPrivate, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ChatPrivate message, length delimited. Does not implicitly {@link ChatPrivate.verify|verify} messages. * @param message ChatPrivate message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IChatPrivate, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ChatPrivate message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ChatPrivate * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ChatPrivate; /** * Decodes a ChatPrivate message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ChatPrivate * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ChatPrivate; /** * Verifies a ChatPrivate message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ChatPrivate message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ChatPrivate */ public static fromObject(object: { [k: string]: any }): ChatPrivate; /** * Creates a plain object from a ChatPrivate message. Also converts values to other types if specified. * @param message ChatPrivate * @param [options] Conversion options * @returns Plain object */ public static toObject(message: ChatPrivate, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ChatPrivate to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Properties of a ChatCommand. */ export interface IChatCommand { /** ChatCommand arguments */ "arguments"?: (string[]|null); } /** Represents a ChatCommand. */ export class ChatCommand implements IChatCommand { /** * Constructs a new ChatCommand. * @param [properties] Properties to set */ constructor(properties?: IChatCommand); /** ChatCommand arguments. */ public arguments: string[]; /** * Creates a new ChatCommand instance using the specified properties. * @param [properties] Properties to set * @returns ChatCommand instance */ public static create(properties?: IChatCommand): ChatCommand; /** * Encodes the specified ChatCommand message. Does not implicitly {@link ChatCommand.verify|verify} messages. * @param message ChatCommand message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encode(message: IChatCommand, writer?: $protobuf.Writer): $protobuf.Writer; /** * Encodes the specified ChatCommand message, length delimited. Does not implicitly {@link ChatCommand.verify|verify} messages. * @param message ChatCommand message or plain object to encode * @param [writer] Writer to encode to * @returns Writer */ public static encodeDelimited(message: IChatCommand, writer?: $protobuf.Writer): $protobuf.Writer; /** * Decodes a ChatCommand message from the specified reader or buffer. * @param reader Reader or buffer to decode from * @param [length] Message length if known beforehand * @returns ChatCommand * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decode(reader: ($protobuf.Reader|Uint8Array), length?: number): ChatCommand; /** * Decodes a ChatCommand message from the specified reader or buffer, length delimited. * @param reader Reader or buffer to decode from * @returns ChatCommand * @throws {Error} If the payload is not a reader or valid buffer * @throws {$protobuf.util.ProtocolError} If required fields are missing */ public static decodeDelimited(reader: ($protobuf.Reader|Uint8Array)): ChatCommand; /** * Verifies a ChatCommand message. * @param message Plain object to verify * @returns `null` if valid, otherwise the reason why it is not */ public static verify(message: { [k: string]: any }): (string|null); /** * Creates a ChatCommand message from a plain object. Also converts values to their respective internal types. * @param object Plain object * @returns ChatCommand */ public static fromObject(object: { [k: string]: any }): ChatCommand; /** * Creates a plain object from a ChatCommand message. Also converts values to other types if specified. * @param message ChatCommand * @param [options] Conversion options * @returns Plain object */ public static toObject(message: ChatCommand, options?: $protobuf.IConversionOptions): { [k: string]: any }; /** * Converts this ChatCommand to JSON. * @returns JSON object */ public toJSON(): { [k: string]: any }; } /** Compression enum. */ export enum Compression { NONE = 0, ZSTD = 1, GZIP = 2 }
the_stack
import invariant from "invariant"; import { BigNumber } from "bignumber.js"; import { Observable, defer, from } from "rxjs"; import { reduce, filter, map } from "rxjs/operators"; import flatMap from "lodash/flatMap"; import omit from "lodash/omit"; import { InvalidAddress, RecipientRequired } from "@ledgerhq/errors"; import type { Account, Transaction, AccountBridge, SyncConfig, DatasetTest, CurrenciesData, CryptoCurrency, AccountLike, SubAccount, AccountRawLike, } from "../../types"; import { fromAccountRaw, toAccountRaw, decodeAccountId, encodeAccountId, flattenAccounts, isAccountBalanceUnconfirmed, } from "../../account"; import { getCryptoCurrencyById } from "../../currencies"; import { getOperationAmountNumber } from "../../operation"; import { fromTransactionRaw, toTransactionRaw, toTransactionStatusRaw, } from "../../transaction"; import { getBalanceHistoryJS, getRanges } from "../../portfolio"; import { getAccountBridge, getCurrencyBridge } from "../../bridge"; import { mockDeviceWithAPDUs, releaseMockDevice } from "./mockDevice"; import { implicitMigration } from "../../migrations/accounts"; const warnDev = process.env.CI ? (..._args) => {} : (...msg) => console.warn(...msg); // FIXME move out into DatasetTest to be defined in const blacklistOpsSumEq = { currencies: ["ripple", "ethereum"], impls: ["mock"], }; function expectBalanceIsOpsSum(a) { expect(a.balance).toEqual( a.operations.reduce( (sum, op) => sum.plus(getOperationAmountNumber(op)), new BigNumber(0) ) ); } const defaultSyncConfig = { paginationConfig: {}, blacklistedTokenIds: ["ethereum/erc20/ampleforth", "ethereum/erc20/steth"], }; export function syncAccount<T extends Transaction>( bridge: AccountBridge<T>, account: Account, syncConfig: SyncConfig = defaultSyncConfig ): Promise<Account> { return bridge .sync(account, syncConfig) .pipe(reduce((a, f: (arg0: Account) => Account) => f(a), account)) .toPromise(); } export function testBridge<T extends Transaction>( family: string, data: DatasetTest<T> ) { // covers all bridges through many different accounts // to test the common shared properties of bridges. const accountsRelated: Array<{ account: Account; currencyData: CurrenciesData<T>; accountData: any; impl: string; }> = []; const currenciesRelated: Array<{ currencyData: CurrenciesData<T>; currency: CryptoCurrency; }> = []; const { implementations, currencies } = data; Object.keys(currencies).forEach((currencyId) => { const currencyData = currencies[currencyId]; const currency = getCryptoCurrencyById(currencyId); currenciesRelated.push({ currencyData, currency, }); const accounts = currencyData.accounts || []; accounts.forEach((accountData) => implementations.forEach((impl) => { if ( accountData.implementations && !accountData.implementations.includes(impl) ) { return; } const account = fromAccountRaw({ ...accountData.raw, id: encodeAccountId({ ...decodeAccountId(accountData.raw.id), type: impl, }), }); accountsRelated.push({ currencyData, accountData, account, impl, }); }) ); }); const accountsFoundInScanAccountsMap = {}; const preloadObservables: Array<Observable<any>> = []; currenciesRelated.map(({ currencyData, currency }) => { const bridge = getCurrencyBridge(currency); const scanAccounts = async (apdus) => { const deviceId = await mockDeviceWithAPDUs(apdus); try { const accounts = await bridge .scanAccounts({ currency, deviceId, syncConfig: defaultSyncConfig, }) .pipe( filter((e) => e.type === "discovered"), map((e) => e.account), reduce((all, a) => all.concat(a), [] as Account[]) ) .toPromise(); return implicitMigration(accounts); } finally { releaseMockDevice(deviceId); } }; const scanAccountsCaches = {}; const scanAccountsCached = (apdus) => scanAccountsCaches[apdus] || (scanAccountsCaches[apdus] = scanAccounts(apdus)); describe(currency.id + " currency bridge", () => { const { scanAccounts, FIXME_ignoreAccountFields, FIXME_ignoreOperationFields, } = currencyData; test("functions are defined", () => { expect(typeof bridge.scanAccounts).toBe("function"); expect(typeof bridge.preload).toBe("function"); expect(typeof bridge.hydrate).toBe("function"); }); test("preload and rehydrate", async () => { const data1 = await bridge.preload(currency); bridge.hydrate(data1, currency); if (data1) { const serialized1 = JSON.parse(JSON.stringify(data1)); bridge.hydrate(serialized1, currency); expect(serialized1).toBeDefined(); const data2 = await bridge.preload(currency); if (data2) { bridge.hydrate(data2, currency); expect(data1).toMatchObject(data2); const serialized2 = JSON.parse(JSON.stringify(data2)); expect(serialized1).toMatchObject(serialized2); bridge.hydrate(serialized2, currency); } } }); if (scanAccounts) { if (FIXME_ignoreOperationFields) { warnDev( currency.id + " is ignoring operation fields: " + FIXME_ignoreOperationFields.join(", ") ); } if (FIXME_ignoreAccountFields) { warnDev( currency.id + " is ignoring account fields: " + FIXME_ignoreAccountFields.join(", ") ); } describe("scanAccounts", () => { scanAccounts.forEach((sa) => { // we start running the scan accounts in parallel! preloadObservables.push( defer(() => from( scanAccountsCached(sa.apdus).then( () => null, () => {} ) ) ) ); test(sa.name, async () => { const accounts = await scanAccountsCached(sa.apdus); accounts.forEach((a) => { accountsFoundInScanAccountsMap[a.id] = a; }); if (!sa.unstableAccounts) { const raws: AccountRawLike[] = flatMap(accounts, (a) => { const main = toAccountRaw(a); if (!main.subAccounts) return [main]; return [ { ...main, subAccounts: [] }, ...main.subAccounts, ] as AccountRawLike[]; }); const heads = raws.map((a) => { const copy = omit( a, [ "operations", "lastSyncDate", "creationDate", "blockHeight", "balanceHistory", "balanceHistoryCache", ].concat(FIXME_ignoreAccountFields || []) ); return copy; }); const ops = raws.map(({ operations }) => operations .slice(0) .sort((a, b) => a.id.localeCompare(b.id)) .map((op) => { const copy = omit( op, ["date"].concat(FIXME_ignoreOperationFields || []) ); return copy; }) ); expect(heads).toMatchSnapshot(); expect(ops).toMatchSnapshot(); } const testFn = sa.test; if (testFn) { await testFn(expect, accounts, bridge); } }); test("estimateMaxSpendable is between 0 and account balance", async () => { const accounts = await scanAccountsCached(sa.apdus); for (const account of accounts) { const accountBridge = getAccountBridge(account); const estimation = await accountBridge.estimateMaxSpendable({ account, }); expect(estimation.gte(0)).toBe(true); expect(estimation.lte(account.spendableBalance)).toBe(true); for (const sub of account.subAccounts || []) { const estimation = await accountBridge.estimateMaxSpendable({ parentAccount: account, account: sub, }); expect(estimation.gte(0)).toBe(true); expect(estimation.lte(sub.balance)).toBe(true); } } }); test("no unconfirmed account", async () => { const accounts = await scanAccountsCached(sa.apdus); for (const account of flattenAccounts(accounts)) { expect({ id: account.id, unconfirmed: isAccountBalanceUnconfirmed(account), }).toEqual({ id: account.id, unconfirmed: false, }); } }); test("creationDate is correct", async () => { const accounts = await scanAccountsCached(sa.apdus); for (const account of flattenAccounts(accounts)) { if (account.operations.length) { const op = account.operations[account.operations.length - 1]; if (account.creationDate.getTime() > op.date.getTime()) { warnDev( `OP ${ op.id } have date=${op.date.toISOString()} older than account.creationDate=${account.creationDate.toISOString()}` ); } expect(account.creationDate.getTime()).not.toBeGreaterThan( op.date.getTime() ); } } }); }); }); } const currencyDataTest = currencyData.test; if (currencyDataTest) { test(currency.id + " specific test", () => currencyDataTest(expect, bridge) ); } }); const accounts = currencyData.accounts || []; if (accounts.length) { const accountsInScan: string[] = []; const accountsNotInScan: string[] = []; accounts.forEach(({ raw }) => { if (accountsFoundInScanAccountsMap[raw.id]) { accountsInScan.push(raw.id); } else { accountsNotInScan.push(raw.id); } }); if (accountsInScan.length === 0) { warnDev( `/!\\ CURRENCY '${currency.id}' define accounts that are NOT in scanAccounts. please add at least one account that is from scanAccounts. This helps testing scanned accounts are fine and it also help performance.` ); } if (accountsNotInScan.length === 0) { warnDev( `/!\\ CURRENCY '${currency.id}' define accounts that are ONLY in scanAccounts. please add one account that is NOT from scanAccounts. This helps covering the "recovering from xpub" mecanism.` ); } } }); accountsRelated .map(({ account, ...rest }) => { const bridge = getAccountBridge(account, null); if (!bridge) throw new Error("no bridge for " + account.id); let accountSyncedPromise; // lazy eval so we don't run this yet const getSynced = () => accountSyncedPromise || (accountSyncedPromise = syncAccount(bridge, account)); return { getSynced, bridge, initialAccount: account, ...rest, }; }) .forEach((arg) => { const { getSynced, bridge, initialAccount, accountData, impl } = arg; const makeTest = (name, fn) => { if ( accountData.FIXME_tests && accountData.FIXME_tests.some((r) => name.match(r)) ) { warnDev( "FIXME test was skipped. " + name + " for " + initialAccount.name ); return; } test(name, fn); }; describe(impl + " bridge on account " + initialAccount.name, () => { describe("sync", () => { makeTest("succeed", async () => { const account = await getSynced(); const [account2] = implicitMigration([account]); expect(fromAccountRaw(toAccountRaw(account2))).toBeDefined(); }); if (impl !== "mock") { const accFromScanAccounts = accountsFoundInScanAccountsMap[initialAccount.id]; if (accFromScanAccounts) { makeTest( "matches the same account from scanAccounts", async () => { const acc = await getSynced(); expect(acc).toMatchObject(accFromScanAccounts); } ); } } makeTest("bridge ref equality", async () => { const account = await getSynced(); expect(bridge).toBe(getAccountBridge(account, null)); }); makeTest("account have no NaN values", async () => { const account = await getSynced(); [account, ...(account.subAccounts || [])].forEach((a) => { expect(a.balance.isNaN()).toBe(false); expect(a.operations.find((op) => op.value.isNaN())).toBe( undefined ); expect(a.operations.find((op) => op.fee.isNaN())).toBe(undefined); }); }); if ( !blacklistOpsSumEq.currencies.includes( initialAccount.currency.id ) && !blacklistOpsSumEq.impls.includes(impl) ) { makeTest("balance is sum of ops", async () => { const account = await getSynced(); expectBalanceIsOpsSum(account); if (account.subAccounts) { account.subAccounts.forEach(expectBalanceIsOpsSum); } }); makeTest("balance and spendableBalance boundaries", async () => { const account = await getSynced(); expect(account.balance).toBeInstanceOf(BigNumber); expect(account.spendableBalance).toBeInstanceOf(BigNumber); expect(account.balance.lt(0)).toBe(false); expect(account.spendableBalance.lt(0)).toBe(false); expect(account.spendableBalance.lte(account.balance)).toBe(true); }); } makeTest( "existing operations object refs are preserved", async () => { const account = await getSynced(); const count = Math.floor(account.operations.length / 2); const operations = account.operations.slice(count); const copy = { ...account, operations, blockHeight: 0, }; const synced = await syncAccount(bridge, copy); expect(synced.operations.length).toBe(account.operations.length); // same ops are restored expect(synced.operations).toEqual(account.operations); if (initialAccount.id.startsWith("ethereumjs")) return; // ethereumjs seems to have a bug on this, we ignore because the impl will be dropped. // existing ops are keeping refs synced.operations.slice(count).forEach((op, i) => { expect(op).toBe(operations[i]); }); } ); makeTest("pendingOperations are cleaned up", async () => { const account = await getSynced(); if (account.operations.length) { const operations = account.operations.slice(1); const pendingOperations = [account.operations[0]]; const copy = { ...account, operations, pendingOperations, blockHeight: 0, }; const synced = await syncAccount(bridge, copy); // same ops are restored expect(synced.operations).toEqual(account.operations); // pendingOperations is empty expect(synced.pendingOperations).toEqual([]); } }); makeTest("there are no Operation dups (by id)", async () => { const account = await getSynced(); const seen = {}; account.operations.forEach((op) => { expect(seen[op.id]).toBeUndefined(); seen[op.id] = op.id; }); }); }); makeTest( "account balanceHistory (when exists) matches getBalanceHistoryJS", async () => { const account = await getSynced(); getRanges().forEach((range) => { const balanceHistory = account.balanceHistory && account.balanceHistory[range]; if (!balanceHistory) return; const history = getBalanceHistoryJS(account, range); expect(balanceHistory.map((b) => b.value)).toEqual( history.map((b) => b.value) ); }); } ); describe("createTransaction", () => { makeTest( "empty transaction is an object with empty recipient and zero amount", () => { expect(bridge.createTransaction(initialAccount)).toMatchObject({ amount: new BigNumber(0), recipient: "", }); } ); makeTest("empty transaction is equals to itself", () => { expect(bridge.createTransaction(initialAccount)).toEqual( bridge.createTransaction(initialAccount) ); }); makeTest("empty transaction correctly serialize", () => { const t = bridge.createTransaction(initialAccount); expect(fromTransactionRaw(toTransactionRaw(t))).toEqual(t); }); makeTest( "transaction with amount and recipient correctly serialize", async () => { const account = await getSynced(); const t = { ...bridge.createTransaction(account), amount: new BigNumber(1000), recipient: account.freshAddress, }; expect(fromTransactionRaw(toTransactionRaw(t))).toEqual(t); } ); }); describe("prepareTransaction", () => { // stability: function called twice will return the same object reference (=== convergence so we can stop looping, typically because transaction will be a hook effect dependency of prepareTransaction) async function expectStability(account, t) { const t2 = await bridge.prepareTransaction(account, t); const t3 = await bridge.prepareTransaction(account, t2); expect(t2).toStrictEqual(t3); } makeTest("ref stability on empty transaction", async () => { const account = await getSynced(); await expectStability(account, bridge.createTransaction(account)); }); makeTest("ref stability on self transaction", async () => { const account = await getSynced(); await expectStability(account, { ...bridge.createTransaction(account), amount: new BigNumber(1000), recipient: account.freshAddress, }); }); makeTest( "can be run in parallel and all yield same results", async () => { const account = await getSynced(); const t = { ...bridge.createTransaction(account), amount: new BigNumber(1000), recipient: account.freshAddress, }; const stable = await bridge.prepareTransaction(account, t); const first = await bridge.prepareTransaction(account, stable); const concur = await Promise.all( Array(3) .fill(null) .map(() => bridge.prepareTransaction(account, stable)) ); concur.forEach((r) => { expect(r).toEqual(first); }); } ); }); describe("getTransactionStatus", () => { makeTest("can be called on an empty transaction", async () => { const account = await getSynced(); const t = bridge.createTransaction(account); const s = await bridge.getTransactionStatus(account, t); expect(s).toBeDefined(); expect(s.errors).toHaveProperty("recipient"); expect(s).toHaveProperty("totalSpent"); expect(s.totalSpent).toBeInstanceOf(BigNumber); expect(s).toHaveProperty("estimatedFees"); expect(s.estimatedFees).toBeInstanceOf(BigNumber); expect(s).toHaveProperty("amount"); expect(s.amount).toBeInstanceOf(BigNumber); expect(s.amount).toEqual(new BigNumber(0)); }); makeTest( "can be called on an empty prepared transaction", async () => { const account = await getSynced(); const t = await bridge.prepareTransaction( account, bridge.createTransaction(account) ); const s = await bridge.getTransactionStatus(account, t); expect(s).toBeDefined(); // FIXME i'm not sure if we can establish more shared properties } ); makeTest( "Default empty recipient have a recipientError", async () => { const account = await getSynced(); const t = { ...bridge.createTransaction(account) }; const status = await bridge.getTransactionStatus(account, t); expect(status.errors.recipient).toBeInstanceOf(RecipientRequired); } ); makeTest("invalid recipient have a recipientError", async () => { const account = await getSynced(); const t = { ...bridge.createTransaction(account), recipient: "invalidADDRESS", }; const status = await bridge.getTransactionStatus(account, t); expect(status.errors.recipient).toBeInstanceOf(InvalidAddress); }); const accountDataTest = accountData.test; if (accountDataTest) { makeTest("account specific test", async () => accountDataTest(expect, await getSynced(), bridge) ); } (accountData.transactions || []).forEach( ({ name, transaction, expectedStatus, apdus, testSignedOperation, test: testFn, }) => { makeTest("transaction " + name, async () => { const account: Account = await getSynced(); let t = typeof transaction === "function" ? transaction( bridge.createTransaction(account), account, bridge ) : transaction; t = await bridge.prepareTransaction(account, t); const s = await bridge.getTransactionStatus(account, t); if (expectedStatus) { const es = typeof expectedStatus === "function" ? expectedStatus(account, t, s) : expectedStatus; const { errors, warnings } = es; // we match errors and warnings errors && expect(s.errors).toMatchObject(errors); warnings && expect(s.warnings).toMatchObject(warnings); // now we match rest of fields but using the raw version for better readability const restRaw: Record<string, any> = toTransactionStatusRaw({ ...s, ...es, }); delete restRaw.errors; delete restRaw.warnings; for (const k in restRaw) { if (!(k in es)) { delete restRaw[k]; } } expect(toTransactionStatusRaw(s)).toMatchObject(restRaw); } if (testFn) { await testFn(expect, t, s, bridge); } if (Object.keys(s.errors).length === 0) { const { subAccountId } = t; const { subAccounts } = account; const inferSubAccount = () => { invariant(subAccounts, "sub accounts available"); const a = (subAccounts as SubAccount[]).find( (a) => a.id === subAccountId ); invariant(a, "sub account not found"); return a; }; const obj = subAccountId ? { transaction: t as Transaction, account: inferSubAccount() as AccountLike, parentAccount: account, } : { transaction: t as Transaction, account: account as AccountLike, }; if (typeof t.mode !== "string" || t.mode === "send") { const estimation = await bridge.estimateMaxSpendable(obj); expect(estimation.gte(0)).toBe(true); expect(estimation.lte(obj.account.balance)).toBe(true); if (t.useAllAmount) { expect(estimation.toString()).toBe(s.amount.toString()); } } } if (apdus && impl !== "mock") { const deviceId = await mockDeviceWithAPDUs(apdus); try { const signedOperation = await bridge .signOperation({ account, deviceId, transaction: t, }) .pipe( filter((e) => e.type === "signed"), map((e: any) => e.signedOperation) ) .toPromise(); if (testSignedOperation) { await testSignedOperation( expect, signedOperation, account, t, s, bridge ); } } finally { releaseMockDevice(deviceId); } } }); } ); }); describe("signOperation and broadcast", () => { makeTest("method is available on bridge", async () => { expect(typeof bridge.signOperation).toBe("function"); expect(typeof bridge.broadcast).toBe("function"); }); // NB for now we are not going farther because most is covered by bash tests }); }); }); return { preloadObservables, }; }
the_stack
import { ChannelTypeEnum, INotificationTemplate } from '@notifire/shared'; describe('Notifications Creator', function () { beforeEach(function () { cy.initializeSession().as('session'); }); it('should not reset data when switching channel types', function () { cy.visit('/templates/create'); cy.getByTestId('inAppSelector').click({ force: true }); cy.getByTestId('in-app-editor-content-input').type('{{firstName}} someone assigned you to {{taskName}}', { parseSpecialCharSequences: false, }); cy.getByTestId('emailSelector').click({ force: true }); cy.getByTestId('editable-text-content').clear().type('This text is written from a test {{firstName}}', { parseSpecialCharSequences: false, }); cy.getByTestId('emailSubject').type('this is email subject'); cy.getByTestId('inAppSelector').click({ force: true }); cy.getByTestId('in-app-editor-content-input').contains('someone assigned you to'); cy.getByTestId('emailSelector').click({ force: true }); cy.getByTestId('editable-text-content').contains('This text is written from a test'); cy.getByTestId('emailSubject').should('have.value', 'this is email subject'); }); it('should create in-app notification', function () { cy.visit('/templates/create'); cy.getByTestId('title').type('Test Notification Title'); cy.getByTestId('description').type('This is a test description for a test title'); cy.getByTestId('tags').type('General {enter}'); cy.getByTestId('tags').type('Tasks {enter}'); cy.get('body').click(); cy.getByTestId('trigger-code-snippet').should('not.exist'); cy.getByTestId('groupSelector').contains('General'); cy.getByTestId('inAppSelector').click({ force: true }); cy.getByTestId('inAppRedirect').type('/example/test'); cy.getByTestId('in-app-editor-content-input').type('{{firstName}} someone assigned you to {{taskName}}', { parseSpecialCharSequences: false, }); cy.getByTestId('submit-btn').click(); cy.getByTestId('success-trigger-modal').should('be.visible'); cy.getByTestId('success-trigger-modal').getByTestId('trigger-code-snippet').contains('test-notification'); cy.getByTestId('success-trigger-modal') .getByTestId('trigger-code-snippet') .contains("import { Notifire } from '@notifire/node'"); cy.get('.ant-tabs-tab-btn').contains('Curl').click(); cy.getByTestId('success-trigger-modal') .getByTestId('trigger-curl-snippet') .contains("--header 'Authorization: ApiKey"); cy.getByTestId('success-trigger-modal').getByTestId('trigger-curl-snippet').contains('taskName'); cy.get('.ant-modal-footer .ant-btn.ant-btn-primary').click(); cy.location('pathname').should('equal', '/templates'); }); it('should create email notification', function () { cy.visit('/templates/create'); cy.getByTestId('title').type('Test Notification Title'); cy.getByTestId('description').type('This is a test description for a test title'); cy.getByTestId('tags').type('General {enter}'); cy.getByTestId('tags').type('Tasks {enter}'); cy.get('body').click(); cy.getByTestId('emailSelector').click({ force: true }); cy.getByTestId('email-editor').getByTestId('editor-row').click(); cy.getByTestId('control-add').click({ force: true }); cy.getByTestId('add-btn-block').click(); cy.getByTestId('button-block-wrapper').should('be.visible'); cy.getByTestId('button-block-wrapper').find('button').click(); cy.getByTestId('button-text-input').clear().type('Example Text Of {{ctaName}}', { parseSpecialCharSequences: false, }); cy.getByTestId('button-block-wrapper').find('button').contains('Example Text Of {{ctaName}}'); cy.getByTestId('editable-text-content').clear().type('This text is written from a test {{firstName}}', { parseSpecialCharSequences: false, }); cy.getByTestId('email-editor').getByTestId('editor-row').eq(1).click(); cy.getByTestId('control-add').click({ force: true }); cy.getByTestId('add-text-block').click(); cy.getByTestId('editable-text-content').eq(1).clear().type('This another text will be {{customVariable}}', { parseSpecialCharSequences: false, }); cy.getByTestId('editable-text-content').eq(1).click(); cy.getByTestId('settings-row-btn').eq(1).invoke('show').click(); cy.getByTestId('remove-row-btn').click(); cy.getByTestId('button-block-wrapper').should('not.exist'); cy.getByTestId('emailSubject').type('this is email subject'); cy.getByTestId('submit-btn').click(); cy.getByTestId('success-trigger-modal').should('be.visible'); cy.getByTestId('success-trigger-modal').getByTestId('trigger-code-snippet').contains('test-notification'); cy.getByTestId('success-trigger-modal').getByTestId('trigger-code-snippet').contains('firstName:'); cy.getByTestId('success-trigger-modal').getByTestId('trigger-code-snippet').contains('customVariable:'); }); it('should create and edit group id', function () { const template = this.session.templates[0]; cy.visit('/templates/edit/' + template._id); cy.getByTestId('groupSelector').click(); cy.getByTestId('category-text-input').type('New Test Category'); cy.getByTestId('submit-category-btn').click(); cy.getByTestId('groupSelector').contains('New Test Category'); cy.getByTestId('submit-btn').click(); cy.getByTestId('template-edit-link'); cy.visit('/templates/edit/' + template._id); cy.getByTestId('groupSelector').contains('New Test Category'); }); it('should edit notification', function () { const template = this.session.templates[0]; cy.visit('/templates/edit/' + template._id); cy.getByTestId('inAppSelector').click({ force: true }); cy.getByTestId('title').get('input').should('have.value', template.name); cy.getByTestId('in-app-editor-content-input') .getByTestId('in-app-editor-content-input') .contains('Test content for {{firstName}}'); cy.getByTestId('title').type(' This is the new notification title'); cy.getByTestId('in-app-editor-content-input').clear().type('new content for notification'); cy.getByTestId('submit-btn').click(); cy.getByTestId('template-edit-link'); cy.getByTestId('notifications-template').get('tbody tr td').contains('This is the new notification title', { matchCase: false, }); }); it('should update notification active status', function () { const template = this.session.templates[0]; cy.visit('/templates/edit/' + template._id); cy.getByTestId('active-toggle-switch').contains('Active'); cy.getByTestId('active-toggle-switch').click(); cy.getByTestId('active-toggle-switch').contains('Disabled'); cy.visit('/templates/edit/' + template._id); cy.getByTestId('active-toggle-switch').contains('Disabled'); }); it('should toggle active states of channels', function () { cy.visit('/templates/create'); // Enable email from button click cy.getByTestId('emailSelector').click({ force: true }); cy.getByTestId('emailSelector').find('.ant-switch-checked').should('exist'); cy.getByTestId('emailSelector').find('.ant-switch').click({ force: true }); // should hide when switch clicked cy.getByTestId('email-editor-wrapper').should('not.visible'); // enable email selector cy.getByTestId('emailSelector').click(); // enable in app without changing select item cy.getByTestId('inAppSelector').find('.ant-switch').click({ force: true }); cy.getByTestId('inAppSelector').find('.ant-switch-checked').should('exist'); cy.getByTestId('email-editor-wrapper').should('exist'); // when hiding current selector, should navigate to closest available cy.getByTestId('emailSelector').find('.ant-switch').click({ force: true }); cy.getByTestId('in-app-editor-wrapper').should('be.visible'); }); it('should show trigger snippet block when editing', function () { const template = this.session.templates[0]; cy.visit('/templates/edit/' + template._id); cy.getByTestId('trigger-code-snippet').contains('test-event'); }); it('should handle multiple email messages', function () { cy.visit('/templates/create'); cy.getByTestId('emailSelector').click({ force: true }); cy.getByTestId('emailSubject').eq(1).should('not.exist'); cy.getByTestId('add-message-button').click(); cy.getByTestId('emailSubject').eq(1).click(); cy.getByTestId('emailSubject').eq(1).should('be.visible'); cy.getByTestId('emailSubject').eq(1).type('this is email subject 2'); cy.getByTestId('emailSubject').eq(0).should('not.be.visible'); cy.getByTestId('message-header-title').eq(0).click(); cy.getByTestId('emailSubject').eq(0).should('be.visible'); cy.getByTestId('emailSubject').eq(1).should('not.be.visible'); cy.getByTestId('emailSubject').eq(0).type('this is email subject 1'); cy.getByTestId('message-header-title').eq(1).find('.ant-typography-edit').click(); cy.getByTestId('message-header-title').eq(1).find('textarea').type(' editing message name {enter}'); cy.getByTestId('message-header-title').eq(1).contains('editing message name'); cy.getByTestId('AddRule').eq(0).click(); cy.getByTestId('filters-builder').eq(0).find('[title="Select your option"]').click(); cy.get('.ant-select-item-option-content').contains('First Name').click(); cy.getByTestId('filter-builder-row').find('input[type="text"]').type('First Value'); cy.getByTestId('AddRule').eq(0).click(); cy.getByTestId('filter-builder-row').eq(1).find('[title="Select your option"]').click(); cy.getByTestId('remove-message-template-btn').eq(0).click(); cy.get('.ant-popover-placement-bottom button').contains('Yes').click(); cy.getByTestId('emailSubject').eq(1).should('not.exist'); cy.getByTestId('emailSubject').should('have.value', 'this is email subject 2'); }); describe('Email Filters', function () { beforeEach(function () { cy.initializeSession({ partialTemplate: { messages: [ { type: ChannelTypeEnum.EMAIL, subject: 'Test', name: 'Test Name of message', content: [ { type: 'button', content: 'Test button', }, ], filters: [ { type: 'GROUP', value: 'OR', children: [ { field: 'firstName', value: 'Test', operator: 'EQUAL', }, ], }, ], }, { type: ChannelTypeEnum.EMAIL, subject: 'Test 2', name: 'Test Name of message 2', content: [ { type: 'button', content: 'Test button 2', }, ], filters: [ { type: 'GROUP', value: 'OR', children: [ { field: 'firstName', value: 'Test 2', operator: 'EQUAL', }, ], }, ], }, ], } as Partial<INotificationTemplate>, }).as('session'); }); it('should prefill saved multiple email messages and filters', function () { const template = this.session.templates[0]; cy.visit('/templates/edit/' + template._id); cy.getByTestId('message-header-title').eq(0).contains('Test Name of message'); cy.getByTestId('message-header-title').eq(1).contains('Test Name of message 2'); cy.getByTestId('filter-builder-row').eq(1).find('input[type=text]').should('have.value', 'Test 2'); cy.getByTestId('filter-builder-row').eq(1).find('.ant-select-selection-item').contains('First Name'); }); }); it('should validate form inputs', function () { cy.visit('/templates/create'); cy.getByTestId('submit-btn').click(); cy.getByTestId('title').should('have.class', 'ant-form-item-has-error'); cy.getByTestId('inAppSelector').click({ force: true }); cy.getByTestId('submit-btn').click(); cy.getByTestId('in-app-content-form-item').should('have.class', 'ant-form-item-has-error'); }); it('should allow uploading a logo from email editor', function () { cy.intercept(/.*applications\/me.*/, (r) => { r.continue((res) => { if (res.body) { delete res.body.data.branding.logo; } res.send({ body: res.body }); }); }); cy.visit('/templates/create'); cy.getByTestId('emailSelector').click({ force: true }); cy.getByTestId('logo-upload-button').click(); cy.get('.ant-popconfirm button').contains('Yes').click(); cy.location('pathname').should('equal', '/settings/widget'); }); it('should show the brand logo on main page', function () { cy.visit('/templates/create'); cy.getByTestId('emailSelector').click({ force: true }); cy.getByTestId('email-editor') .getByTestId('brand-logo') .should('have.attr', 'src', 'https://notifire.co/img/logo.png'); }); it('should support RTL text content', function () { cy.visit('/templates/create'); cy.getByTestId('emailSelector').click({ force: true }); cy.getByTestId('settings-row-btn').eq(0).invoke('show').click(); cy.getByTestId('editable-text-content').should('have.css', 'direction', 'ltr'); cy.getByTestId('style-setting-row-btn-drawer').click(); cy.getByTestId('text-direction-input').get('.ant-radio-button-wrapper').contains('RTL').click(); cy.getByTestId('drawer-submit-btn').click(); cy.getByTestId('editable-text-content').should('have.css', 'direction', 'rtl'); }); it('should create an SMS channel message', function () { cy.visit('/templates/create'); cy.getByTestId('title').type('Test SMS Notification Title'); cy.getByTestId('description').type('This is a SMS test description for a test title'); cy.getByTestId('smsSelector').click({ force: true }); cy.getByTestId('smsNotificationContent').type('{{firstName}} someone assigned you to {{taskName}}', { parseSpecialCharSequences: false, }); cy.getByTestId('submit-btn').click(); cy.getByTestId('success-trigger-modal').should('be.visible'); cy.getByTestId('success-trigger-modal').getByTestId('trigger-code-snippet').contains('test-sms-notification'); cy.getByTestId('success-trigger-modal') .getByTestId('trigger-code-snippet') .contains("import { Notifire } from '@notifire/node'"); cy.getByTestId('success-trigger-modal').getByTestId('trigger-code-snippet').contains('taskName'); cy.getByTestId('success-trigger-modal').getByTestId('trigger-code-snippet').contains('firstName'); cy.get('.ant-modal-footer .ant-btn.ant-btn-primary').click(); cy.location('pathname').should('equal', '/templates'); }); it('should prompt for filling sms settings before accessing the data', function () { cy.intercept(/.*applications\/me.*/, (r) => { r.continue((res) => { delete res.body.data.channels.sms; res.send({ body: res.body }); }); }); cy.visit('/templates/create'); cy.getByTestId('configure-sms-button').click(); cy.get('.ant-popover button').contains('Yes').click(); cy.url().should('include', '/settings/widget'); }); it('should save HTML template email', function () { cy.visit('/templates/create'); cy.getByTestId('title').type('Custom Code HTML Notification Title'); cy.getByTestId('emailSelector').click({ force: true }); cy.getByTestId('emailSubject').type('this is email subject'); cy.getByTestId('editor-type-selector').find('label').contains('Custom Code', { matchCase: false }).click(); cy.get('#codeEditor').type('Hello world code {{name}} <div>Test', { parseSpecialCharSequences: false }); cy.getByTestId('submit-btn').click(); cy.get('.ant-modal-footer .ant-btn.ant-btn-primary').click(); cy.get('tbody').contains('Custom Code HTML Notification').parent('tr').find('button').click(); cy.get('#codeEditor').contains('Hello world code {{name}} <div>Test</div>'); }); });
the_stack
'use strict'; import * as assert from 'assert'; import {EventEmitter} from 'events'; import * as extend from 'extend'; import * as proxyquire from 'proxyquire'; import * as sinon from 'sinon'; import {util} from '@google-cloud/common'; import * as pfy from '@google-cloud/promisify'; import {before, beforeEach, afterEach, describe, it} from 'mocha'; import {Instance, Spanner} from '../src'; import * as bu from '../src/backup'; import {GetMetadataResponse} from '../src/backup'; import {grpc} from 'google-gax'; import {CLOUD_RESOURCE_HEADER} from '../src/common'; import {google} from '../protos/protos'; import EncryptionType = google.spanner.admin.database.v1.CreateBackupEncryptionConfig.EncryptionType; let promisified = false; // let callbackified = false; const fakePfy = extend({}, pfy, { promisifyAll(klass, options) { if (klass.name !== 'Backup') { return; } promisified = true; assert.deepStrictEqual(options.exclude, [ 'getState', 'getExpireTime', 'exists', ]); }, }); class FakeGrpcServiceObject extends EventEmitter { // eslint-disable-next-line @typescript-eslint/no-explicit-any calledWith_: any[]; // eslint-disable-next-line @typescript-eslint/no-explicit-any constructor(...args: any[]) { super(); this.calledWith_ = args; } } // eslint-disable-next-line @typescript-eslint/no-explicit-any const fakeCodec: any = { encode: util.noop, Int() {}, Float() {}, SpannerDate() {}, }; describe('Backup', () => { const sandbox = sinon.createSandbox(); // tslint:disable-next-line variable-name let Backup: typeof bu.Backup; const INSTANCE = { request: util.noop, requestStream: util.noop, formattedName_: 'instance-name', databases_: new Map(), } as {} as Instance; const BACKUP_NAME = 'backup-name'; const DATABASE_NAME = 'database-name'; const DATABASE_FORMATTED_NAME = INSTANCE.formattedName_ + '/databases/' + DATABASE_NAME; const BACKUP_FORMATTED_NAME = INSTANCE.formattedName_ + '/backups/' + BACKUP_NAME; const BACKUP_EXPIRE_TIME = '2019-02-08T10:34:29.481145231Z'; const EXP_BACKUP_EXPIRE_TIME = Spanner.timestamp(BACKUP_EXPIRE_TIME); const BACKUP_VERSION_TIME = '2019-02-07T10:34:29.481145231Z'; const EXP_BACKUP_VERSION_TIME = Spanner.timestamp(BACKUP_VERSION_TIME); let backup: bu.Backup; before(() => { Backup = proxyquire('../src/backup.js', { '@google-cloud/common-grpc': { ServiceObject: FakeGrpcServiceObject, }, '@google-cloud/promisify': fakePfy, }).Backup; }); beforeEach(() => { fakeCodec.encode = util.noop; backup = new Backup(INSTANCE, BACKUP_NAME); }); afterEach(() => sandbox.restore()); describe('instantiation', () => { it('should promisify all the things', () => { assert(promisified); }); it('should localize the request function', () => { assert.strictEqual(backup.request, INSTANCE.request); }); it('should localize the formatted instance name', () => { assert.strictEqual( backup.instanceFormattedName_, INSTANCE.formattedName_ ); }); it('should format the name', () => { const formatName_ = Backup.formatName_; const formattedName = 'formatted-name'; Backup.formatName_ = (instanceName, name) => { Backup.formatName_ = formatName_; assert.strictEqual(instanceName, INSTANCE.formattedName_); assert.strictEqual(name, BACKUP_NAME); return formattedName; }; const backup = new Backup(INSTANCE, BACKUP_NAME); assert(backup.formattedName_, formattedName); }); it('should set the backup id', () => { assert.strictEqual(backup.id, BACKUP_NAME); }); it('should set the resourceHeader_', () => { assert.deepStrictEqual(backup.resourceHeader_, { [CLOUD_RESOURCE_HEADER]: backup.instanceFormattedName_, }); }); }); describe('create', () => { const INSTANCE_NAME = 'instance-name'; const BACKUP_NAME = 'backup-name'; it('should make the correct request', done => { const QUERY = {}; const ORIGINAL_QUERY = extend({}, QUERY); const expectedReqOpts = extend({}, QUERY, { parent: INSTANCE_NAME, backupId: BACKUP_NAME, backup: { name: BACKUP_FORMATTED_NAME, database: DATABASE_FORMATTED_NAME, expireTime: EXP_BACKUP_EXPIRE_TIME.toStruct(), }, }); backup.request = config => { assert.strictEqual(config.client, 'DatabaseAdminClient'); assert.strictEqual(config.method, 'createBackup'); assert.deepStrictEqual(config.reqOpts, expectedReqOpts); assert.notStrictEqual(config.reqOpts, QUERY); assert.deepStrictEqual(QUERY, ORIGINAL_QUERY); assert.deepStrictEqual(config.headers, backup.resourceHeader_); done(); }; backup.create( { databasePath: DATABASE_FORMATTED_NAME, expireTime: BACKUP_EXPIRE_TIME, }, assert.ifError ); }); it('should accept gaxOptions and a callback', done => { const gaxOptions = { timeout: 1000, }; backup.request = config => { assert.strictEqual(config.gaxOpts, gaxOptions); done(); }; backup.create( { databasePath: DATABASE_FORMATTED_NAME, expireTime: BACKUP_EXPIRE_TIME, gaxOptions, }, assert.ifError ); }); it('should accept an encryption config', done => { const encryptionConfig = { encryptionType: EncryptionType.CUSTOMER_MANAGED_ENCRYPTION, kmsKeyName: 'some/key/path', }; backup.request = config => { assert.strictEqual(config.reqOpts.encryptionConfig, encryptionConfig); done(); }; backup.create( { databasePath: DATABASE_FORMATTED_NAME, expireTime: BACKUP_EXPIRE_TIME, encryptionConfig, }, assert.ifError ); }); it('should call Spanner.timestamp() with expireTime', done => { const spanner_timestamp_ = Spanner.timestamp; Spanner.timestamp = timestamp => { Spanner.timestamp = spanner_timestamp_; assert.deepStrictEqual(timestamp, BACKUP_EXPIRE_TIME); return EXP_BACKUP_EXPIRE_TIME; }; backup.request = config => { assert.deepStrictEqual( config.reqOpts.backup.expireTime, EXP_BACKUP_EXPIRE_TIME.toStruct() ); done(); }; backup.create( { databasePath: DATABASE_FORMATTED_NAME, expireTime: BACKUP_EXPIRE_TIME, }, assert.ifError ); }); it('versionTime should not be set by default', done => { backup.request = config => { assert.strictEqual(config.reqOpts.backup.versionTime, undefined); done(); }; backup.create( { databasePath: DATABASE_FORMATTED_NAME, expireTime: BACKUP_EXPIRE_TIME, }, assert.ifError ); }); it('should make request with versionTime when provided', done => { backup.request = config => { assert.deepStrictEqual( config.reqOpts.backup.versionTime, EXP_BACKUP_VERSION_TIME.toStruct() ); done(); }; backup.create( { databasePath: DATABASE_FORMATTED_NAME, expireTime: BACKUP_EXPIRE_TIME, versionTime: BACKUP_VERSION_TIME, }, assert.ifError ); }); describe('error', () => { const API_RESPONSE = {}; const REQUEST_RESPONSE_ARGS = [new Error('Error.'), null, API_RESPONSE]; beforeEach(() => { backup.request = (config, callback: Function) => { callback(...REQUEST_RESPONSE_ARGS); }; }); it('should execute callback with original arguments', done => { backup.create( { databasePath: DATABASE_FORMATTED_NAME, expireTime: BACKUP_EXPIRE_TIME, }, (err, bk, op, resp) => { assert.deepStrictEqual(err, REQUEST_RESPONSE_ARGS[0]); assert.strictEqual(bk, null); assert.strictEqual(op, null); assert.deepStrictEqual(resp, API_RESPONSE); done(); } ); }); }); describe('success', () => { const OPERATION = {}; const API_RESPONSE = {}; beforeEach(() => { backup.request = (config, callback: Function) => { callback(null, OPERATION, API_RESPONSE); }; }); it('should execute callback with a Backup and Operation', done => { backup.create( { databasePath: DATABASE_FORMATTED_NAME, expireTime: BACKUP_EXPIRE_TIME, }, (err, bk, op, resp) => { assert.ifError(err); assert.strictEqual(bk, backup); assert.strictEqual(op, OPERATION); assert.strictEqual(resp, API_RESPONSE); done(); } ); }); }); }); describe('getMetadata', () => { const BACKUP_NAME = 'backup-name'; it('should make the correct request', done => { const QUERY = {}; const ORIGINAL_QUERY = extend({}, QUERY); const expectedReqOpts = extend({}, QUERY, { name: BACKUP_FORMATTED_NAME, }); backup.request = config => { assert.strictEqual(config.client, 'DatabaseAdminClient'); assert.strictEqual(config.method, 'getBackup'); assert.deepStrictEqual(config.reqOpts, expectedReqOpts); assert.notStrictEqual(config.reqOpts, QUERY); assert.deepStrictEqual(QUERY, ORIGINAL_QUERY); assert.deepStrictEqual(config.headers, backup.resourceHeader_); done(); }; backup.getMetadata(assert.ifError); }); it('should accept gaxOpts', done => { const gaxOptions = { timeout: 1000, }; backup.request = config => { assert.strictEqual(config.gaxOpts, gaxOptions); done(); }; backup.getMetadata(gaxOptions, assert.ifError); }); it('should get backup info', done => { const INFO = { name: 'backup-name', database: 'database-name', expireTime: BACKUP_EXPIRE_TIME, }; const fakeInfo = { name: BACKUP_NAME, database: DATABASE_NAME, expireTime: BACKUP_EXPIRE_TIME, }; // eslint-disable-next-line @typescript-eslint/no-explicit-any const REQUEST_RESPONSE_ARGS: any = [null, INFO, {}]; backup.request = (config, callback: Function) => { callback(...REQUEST_RESPONSE_ARGS); }; backup.getMetadata((...args) => { assert.ifError(args[0]); assert.strictEqual(args[0], REQUEST_RESPONSE_ARGS[0]); const backupInfo = args[1]; assert.deepStrictEqual(backupInfo, fakeInfo); done(); }); }); it('should update metadata', done => { const metadata = {}; backup.request = (config: {}, callback: Function) => { callback(null, metadata); }; backup.getMetadata(() => { assert.strictEqual(backup.metadata, metadata); done(); }); }); it('should call callback with error', done => { const error = new Error('Error'); backup.request = (config: {}, callback: Function) => { callback(error); }; backup.getMetadata(err => { assert.strictEqual(err, error); done(); }); }); }); describe('getState', () => { it('should return the state from backup info', async () => { const BACKUP_INFO_RESPONSE: GetMetadataResponse = [ { state: 'CREATING', }, ]; backup.getMetadata = async () => BACKUP_INFO_RESPONSE; const result = await backup.getState(); assert.strictEqual(result, 'CREATING'); }); it('should throw errors', async () => { const err = {code: grpc.status.INTERNAL}; backup.getMetadata = async () => { throw err; }; try { await backup.getState(); assert.fail('Should have rethrown error'); } catch (thrown) { assert.deepStrictEqual(thrown, err); } }); it('should accept callback and return state', done => { const BACKUP_INFO_RESPONSE: GetMetadataResponse = [ { state: 'CREATING', }, ]; backup.getMetadata = async () => BACKUP_INFO_RESPONSE; backup.getState((err, state) => { if (err) { assert.ifError(err); } assert.strictEqual(state, 'CREATING'); done(); }); }); it('should accept callback and return errors', done => { const err = {code: grpc.status.INTERNAL}; backup.getMetadata = async () => { throw err; }; backup.getState(error => { assert.strictEqual(error, err); done(); }); }); }); describe('getExpireTime', () => { it('should return the expire time from backup info', async () => { const BACKUP_INFO_RESPONSE: GetMetadataResponse = [ { expireTime: EXP_BACKUP_EXPIRE_TIME.toStruct(), }, ]; backup.getMetadata = async () => BACKUP_INFO_RESPONSE; const result = await backup.getExpireTime(); assert.deepStrictEqual(result, EXP_BACKUP_EXPIRE_TIME); }); it('should throw errors', async () => { const err = {code: grpc.status.INTERNAL}; backup.getMetadata = async () => { throw err; }; try { await backup.getExpireTime(); assert.fail('Should have rethrown error'); } catch (thrown) { assert.deepStrictEqual(thrown, err); } }); it('should accept callback and return the expire time from backup info', done => { const BACKUP_INFO_RESPONSE: GetMetadataResponse = [ { expireTime: EXP_BACKUP_EXPIRE_TIME.toStruct(), }, ]; backup.getMetadata = async () => BACKUP_INFO_RESPONSE; backup.getExpireTime((err, result) => { assert.deepStrictEqual(result, EXP_BACKUP_EXPIRE_TIME); done(); }); }); it('should accept callback and return errors', done => { const err = {code: grpc.status.INTERNAL}; backup.getMetadata = async () => { throw err; }; backup.getExpireTime(error => { assert.deepStrictEqual(error, err); done(); }); }); }); describe('exists', () => { it('should return true when backup info indicates backup exists', async () => { const BACKUP_INFO_RESPONSE: GetMetadataResponse = [{}]; backup.getMetadata = async () => BACKUP_INFO_RESPONSE; const result = await backup.exists(); assert.strictEqual(result, true); }); it('should return false when backup does not exist', async () => { backup.getMetadata = async () => { throw {code: grpc.status.NOT_FOUND}; }; const result = await backup.exists(); assert.strictEqual(result, false); }); it('should rethrow other errors', async () => { const err = {code: grpc.status.INTERNAL}; backup.getMetadata = async () => { throw err; }; try { await backup.exists(); assert.fail('Should have rethrown error'); } catch (thrown) { assert.deepStrictEqual(thrown, err); } }); it('should accept backup and return true when backup info indicates backup exists', done => { const BACKUP_INFO_RESPONSE: GetMetadataResponse = [{}]; backup.getMetadata = async () => BACKUP_INFO_RESPONSE; backup.exists((err, result) => { if (err) { assert.ifError(err); } assert.strictEqual(result, true); done(); }); }); it('should accept callback and return false when backup does not exist', done => { backup.getMetadata = async () => { throw {code: grpc.status.NOT_FOUND}; }; backup.exists((err, result) => { if (err) { assert.ifError(err); } assert.strictEqual(result, false); done(); }); }); it('should accept callback and return other errors', done => { const err = {code: grpc.status.INTERNAL}; backup.getMetadata = async () => { throw err; }; backup.exists(error => { assert.strictEqual(error, err); done(); }); }); }); describe('updateExpireTime', () => { const NEW_EXPIRE_TIME = '2019-03-08T10:34:29.481145231Z'; const EXP_NEW_EXPIRE_TIME = Spanner.timestamp(NEW_EXPIRE_TIME); it('should make the correct request', done => { const QUERY = {}; const ORIGINAL_QUERY = extend({}, QUERY); const expectedReqOpts = extend({}, QUERY, { backup: { name: BACKUP_FORMATTED_NAME, expireTime: EXP_NEW_EXPIRE_TIME.toStruct(), }, updateMask: { paths: ['expire_time'], }, }); backup.request = config => { assert.strictEqual(config.client, 'DatabaseAdminClient'); assert.strictEqual(config.method, 'updateBackup'); assert.deepStrictEqual(config.reqOpts, expectedReqOpts); assert.notStrictEqual(config.reqOpts, QUERY); assert.deepStrictEqual(QUERY, ORIGINAL_QUERY); assert.deepStrictEqual(config.headers, backup.resourceHeader_); done(); }; backup.updateExpireTime(NEW_EXPIRE_TIME, assert.ifError); }); it('should accept gaxOpts', done => { const gaxOpts = { timeout: 1000, }; backup.request = config => { assert.deepStrictEqual(config.gaxOpts, gaxOpts); done(); }; backup.updateExpireTime(NEW_EXPIRE_TIME, gaxOpts, assert.ifError); }); it('should execute callback with the API resonse', done => { const API_RESPONSE = { name: 'backup-name', database: 'database-name', expireTime: EXP_NEW_EXPIRE_TIME, }; backup.request = (config, callback: Function) => { callback(null, API_RESPONSE); }; backup.updateExpireTime(NEW_EXPIRE_TIME, (err, resp) => { assert.ifError(err); assert.strictEqual(resp, API_RESPONSE); done(); }); }); }); describe('delete', () => { it('should make the correct request', done => { const QUERY = {}; const ORIGINAL_QUERY = extend({}, QUERY); const expectedReqOpts = extend({}, QUERY, { name: BACKUP_FORMATTED_NAME, }); backup.request = config => { assert.strictEqual(config.client, 'DatabaseAdminClient'); assert.strictEqual(config.method, 'deleteBackup'); assert.deepStrictEqual(config.reqOpts, expectedReqOpts); assert.notStrictEqual(config.reqOpts, QUERY); assert.deepStrictEqual(QUERY, ORIGINAL_QUERY); assert.deepStrictEqual(config.headers, backup.resourceHeader_); done(); }; backup.delete(); }); it('should accept gaxOpts', done => { const gaxOpts = { timeout: 1000, }; backup.request = config => { assert.deepStrictEqual(config.gaxOpts, gaxOpts); done(); }; backup.delete(gaxOpts, assert.ifError); }); it('should execute callback with original arguments', done => { const REQUEST_RESPONSE_ARGS = [new Error('Error.')]; backup.request = (config, callback: Function) => { callback(...REQUEST_RESPONSE_ARGS); }; backup.delete(err => { assert.deepStrictEqual(err, REQUEST_RESPONSE_ARGS[0]); done(); }); }); }); describe('formatName_', () => { it('should return the name if already formatted', () => { assert.strictEqual( Backup.formatName_(INSTANCE.formattedName_, BACKUP_FORMATTED_NAME), BACKUP_FORMATTED_NAME ); }); it('should format the name', () => { const formattedName_ = Backup.formatName_( INSTANCE.formattedName_, BACKUP_NAME ); assert.strictEqual(formattedName_, BACKUP_FORMATTED_NAME); }); }); });
the_stack
import * as vscode from 'vscode'; import * as path from 'path'; import * as fs from 'fs'; import * as stripJsonComments from 'strip-json-comments'; import * as cheerio from 'cheerio'; import * as ini from 'ini'; import * as nls from 'vscode-nls'; import { languageClient } from './extension'; import { EnvSection, ServerItem } from './serverItemProvider'; import { Authorization, CompileKey } from './compileKey/compileKey'; import { changeSettings } from './server/languageServerSettings'; import { IRpoToken } from './rpoToken'; //import { sendRpoToken } from './protocolMessages'; const homedir = require('os').homedir(); const localize = nls.loadMessageBundle(); export enum MESSAGETYPE { /** * Type for informative and resumed messages * i.e.: Inform only the begining and the end of a compilation process. */ Info = 'Info', /** * Type for error messages */ Error = 'Error', /** * Type for warning messages */ Warning = 'Warning', /** * Type for detailed messages * i.e.: During a compilation process, inform the status of each file and it's result. */ Log = 'Log', } export default class Utils { /** * Subscrição para evento de seleção de servidor/ambiente. */ static get onDidSelectedServer(): vscode.Event<ServerItem> { return Utils._onDidSelectedServer.event; } /** * Subscrição para evento de chave de compilação. */ static get onDidSelectedKey(): vscode.Event<CompileKey> { return Utils._onDidSelectedKey.event; } /** * Subscrição para evento de token de RPO. */ static get onDidRpoTokenSelected(): vscode.Event<void> { return Utils._onDidRpoTokenSelected.event; } /** * Emite a notificação de seleção de servidor/ambiente */ private static _onDidSelectedServer = new vscode.EventEmitter<ServerItem>(); /** * Emite a notificação de seleção de chave de compilação */ private static _onDidSelectedKey = new vscode.EventEmitter<CompileKey>(); /** * Emite a notificação de token de RPO */ private static _onDidRpoTokenSelected = new vscode.EventEmitter<void>(); /** * Gera um id de servidor */ public static generateRandomID() { return ( Math.random().toString(36).substring(2, 15) + Date.now().toString(36) + Math.random().toString(36).substring(2, 15) ); } /** * Troca o local da salva de servers.json */ static toggleWorkspaceServerConfig() { const config = vscode.workspace.getConfiguration('totvsLanguageServer'); config.update('workspaceServerConfig', !this.isWorkspaceServerConfig()); } /** * Pegar o arquivo servers.json da .vscode (workspace)? */ static isWorkspaceServerConfig(): boolean { let config = vscode.workspace.getConfiguration('totvsLanguageServer'); return config.get('workspaceServerConfig'); } /** * Retorna o path completo do servers.json */ static getServerConfigFile() { return path.join(this.getServerConfigPath(), 'servers.json'); } /** * Retorna o path de onde deve ficar o servers.json */ static getServerConfigPath() { return this.isWorkspaceServerConfig() ? this.getVSCodePath() : path.join(homedir, '/.totvsls'); } /** * Retorna o path completo do launch.json */ static getLaunchConfigFile() { return path.join(this.getVSCodePath(), 'launch.json'); } /** * Retorna o path da pasta .vscode dentro do workspace */ static getVSCodePath() { let rootPath: string = vscode.workspace.rootPath || process.cwd(); return path.join(rootPath, '.vscode'); } /** * Retorna todo o conteudo do servers.json */ static getServersConfig() { let config: any = {}; let serversJson = Utils.getServerConfigFile(); if (!fs.existsSync(serversJson)) { Utils.initializeServerConfigFile(serversJson); } let json = fs.readFileSync(serversJson).toString(); if (json) { try { config = JSON.parse(stripJsonComments(json)); } catch (e) { config = sampleServer(); } } //garante a existencia da sessão if (!config.savedTokens) { config.savedTokens = []; } //compatibilização com arquivos gravados com versão da extensão //anterior a 26/06/20 if ( config.hasOwnProperty('lastConnectedServer') && typeof config.lastConnectedServer !== 'string' ) { if (config.lastConnectedServer.hasOwnProperty('id')) { config.lastConnectedServer = config.lastConnectedServer.id; } } return config; } /** * Retorna todo o conteudo do launch.json */ static getLaunchConfig() { let config: any; let exist = fs.existsSync(Utils.getLaunchConfigFile()); if (exist) { let json = fs.readFileSync(Utils.getLaunchConfigFile()).toString(); if (json) { try { config = JSON.parse(stripJsonComments(json)); } catch (e) { console.error(e); throw e; //return {}; } } } return config; } static saveLaunchConfig(config: JSON) { let fs = require('fs'); fs.writeFileSync( Utils.getLaunchConfigFile(), JSON.stringify(config, null, '\t'), (err) => { if (err) { console.error(err); } } ); } static updateSavedToken(id: string, environment: string, token: string) { const servers = Utils.getServersConfig(); const data = { id: id, environment: environment }; servers.savedTokens[id + ':' + environment] = data; // persistir a configuracao Utils.persistServersInfo(servers); } static getSavedTokens(id: string, environment: string): undefined | string { const servers = Utils.getServersConfig(); let token = undefined; if (servers.savedTokens) { token = servers.savedTokens .filter((element) => { return element[0] === id + ':' + environment; }) .map((element) => { return element[1]['token']; }); if (token) { token = token[0]; } } return token; } /** * Salva o servidor logado por ultimo. * @param id Id do servidor logado * @param token Token que o LS gerou em cima das informacoes de login * @param name Nome do servidor logado * @param environment Ambiente utilizado no login */ static saveSelectServer( id: string, token: string, name: string, environment: string, username: string ) { const servers = Utils.getServersConfig(); servers.configurations.forEach((element) => { if (element.id === id) { if (element.environments === undefined) { element.environments = [environment]; } else if (element.environments.indexOf(environment) === -1) { element.environments.push(environment); } element.username = username; element.environment = environment; element.token = token; servers.connectedServer = element; servers.lastConnectedServer = element.id; } }); Utils.persistServersInfo(servers); Utils._onDidSelectedServer.fire(servers.connectedServer); } /** * Salva o servidor logado por ultimo. * @param id Id do servidor logado * @param token Token que o LS gerou em cima das informacoes de login * @param environment Ambiente utilizado no login */ static saveConnectionToken(id: string, token: string, environment: string) { const servers = Utils.getServersConfig(); if (!servers.savedTokens) { let emptySavedTokens: Array<[string, object]> = []; servers.savedTokens = emptySavedTokens; } else { let found: boolean = false; let key = id + ':' + environment; if (servers.savedTokens) { servers.savedTokens.forEach((element) => { if (element[0] === key) { found = true; // update token element[1] = { id: id, token: token }; } }); } if (!found) { servers.savedTokens.push([key, { id: id, token: token }]); } else { servers.savedTokens[key] = { id: id, token: token }; } Utils.persistServersInfo(servers); } } /** * Remove o token salvo do servidor/environment. * @param id Id do servidor logado * @param environment Ambiente utilizado no login */ static removeSavedConnectionToken(id: string, environment: string) { const servers = Utils.getServersConfig(); if (servers.savedTokens) { let key = id + ':' + environment; servers.savedTokens.forEach((element) => { if (element[0] === key) { const index = servers.savedTokens.indexOf(element, 0); servers.savedTokens.splice(index, 1); Utils.persistServersInfo(servers); return; } }); } } /** * Deleta o servidor logado por ultimo do servers.json */ static deleteSelectServer() { const servers = Utils.getServersConfig(); if (servers.connectedServer.id) { let server = {}; servers.connectedServer = server; const configADVPL = vscode.workspace.getConfiguration( 'totvsLanguageServer' ); //transformar em configuracao de workspace let isReconnectLastServer = configADVPL.get('reconnectLastServer'); if (!isReconnectLastServer) { servers.lastConnectedServer = ''; } Utils.persistServersInfo(servers); } } static clearConnectedServerConfig() { const allConfigs = Utils.getServersConfig(); allConfigs.connectedServer = {}; allConfigs.lastConnectedServer = ''; Utils.persistServersInfo(allConfigs); Utils._onDidSelectedServer.fire(undefined); } /** * Deleta o servidor logado por ultimo do servers.json */ static deleteServer(id: string) { const confirmationMessage = 'Tem certeza que deseja excluir este servidor?'; const optionYes = 'Sim'; const optionNo = 'Não'; vscode.window .showWarningMessage(confirmationMessage, optionYes, optionNo) .then((clicked) => { if (clicked === optionYes) { const allConfigs = Utils.getServersConfig(); if (allConfigs.configurations) { const configs = allConfigs.configurations; configs.forEach((element) => { if (element.id === id) { const index = configs.indexOf(element, 0); configs.splice(index, 1); Utils.persistServersInfo(allConfigs); return; } }); } } }); } /** * Grava no arquivo servers.json uma nova configuracao de servers * @param JSONServerInfo */ static persistServersInfo(JSONServerInfo) { let fs = require('fs'); fs.writeFileSync( Utils.getServerConfigFile(), JSON.stringify(JSONServerInfo, null, '\t'), (err) => { if (err) { console.error(err); } } ); } /** * Grava no arquivo launch.json uma nova configuracao de launchs * @param JSONServerInfo */ static persistLaunchsInfo(JSONLaunchInfo) { let fs = require('fs'); fs.writeFileSync( Utils.getLaunchConfigFile(), JSON.stringify(JSONLaunchInfo, null, '\t'), (err) => { if (err) { console.error(err); } } ); } /** * Cria uma nova configuracao de servidor no servers.json */ static createNewServer( typeServer, serverName, port, address, buildVersion, secure, includes ): string | undefined { Utils.createServerConfig(); let serverConfig = Utils.getServersConfig(); if (!serverConfig || !serverConfig.configurations) { let serversJson = Utils.getServerConfigFile(); Utils.initializeServerConfigFile(serversJson); serverConfig = Utils.getServersConfig(); } if (serverConfig.configurations) { const servers = serverConfig.configurations; if ( servers.find((element) => { return element.name === serverName; }) ) { vscode.window.showErrorMessage( localize( 'tds.webview.serversView.serverNameDuplicated', 'Server name already exists' ) ); return undefined; } else { let validate_includes: string[] = []; includes.forEach((element) => { if (element !== undefined && element.length > 0) { validate_includes.push(element); } }); const serverId: string = Utils.generateRandomID(); servers.push({ id: serverId, type: typeServer, name: serverName, port: parseInt(port), address: address, buildVersion: buildVersion, secure: secure, includes: validate_includes, }); Utils.persistServersInfo(serverConfig); return serverId; } } return undefined; } /** * Recupera o ultimo servidor logado */ static getCurrentServer() { const servers = Utils.getServersConfig(); if (servers.connectedServer.id) { // busca sempre pelo ID pois pode ter ocorrido alguma alteração nas configurações do servidor conectado return Utils.getServerById(servers.connectedServer.id); } else { return ''; } } static getAuthorizationToken(server: ServerItem): string { let authorizationToken: string = ''; let isSafeRPOServer: boolean = Utils.isSafeRPO(server); const permissionsInfos: IRpoToken | CompileKey = isSafeRPOServer ? Utils.getRpoTokenInfos() : Utils.getPermissionsInfos(); if (permissionsInfos) { if (isSafeRPOServer) { authorizationToken = (<IRpoToken>permissionsInfos).token; } else { authorizationToken = (<CompileKey>permissionsInfos).authorizationToken; } } return authorizationToken; } static getRpoTokenInfos(): IRpoToken { const servers = Utils.getServersConfig(); return servers ? servers.rpoToken : undefined; } static saveRpoTokenInfos(infos: IRpoToken) { const config = Utils.getServersConfig(); config.rpoToken = infos; Utils.persistServersInfo(config); //Utils._onDidSelectedKey.fire(infos); } static getPermissionsInfos(): CompileKey { const servers = Utils.getServersConfig(); return servers ? servers.permissions : undefined; } static savePermissionsInfos(infos: CompileKey) { const config = Utils.getServersConfig(); config.permissions = infos; Utils.persistServersInfo(config); Utils._onDidSelectedKey.fire(infos); } static deletePermissionsInfos() { const config = Utils.getServersConfig(); config.permissions = undefined; Utils.persistServersInfo(config); Utils._onDidSelectedKey.fire(undefined); } static removeExpiredAuthorization() { vscode.window.showWarningMessage( localize( 'tds.webview.utils.removeExpiredAuthorization', 'Expired authorization token deleted' ) ); Utils.deletePermissionsInfos(); // remove expired authorization key } /** * Recupera a lista de includes do arquivod servers.json */ static getIncludes( absolutePath: boolean = false, server: any = undefined ): Array<string> { let includes: Array<string>; // se houver includes de servidor utiliza, caso contrario utiliza o global if (server && server.includes && server.includes.length > 0) { includes = server.includes as Array<string>; } else { const servers = Utils.getServersConfig(); includes = servers.includes as Array<string>; } if (includes.length > 0) { if (absolutePath) { // resolve caminhos relativos ao workspace let ws: string = ''; if (vscode.window.activeTextEditor) { const workspaceFolder: vscode.WorkspaceFolder = vscode.workspace.getWorkspaceFolder( vscode.window.activeTextEditor.document.uri ); if (workspaceFolder) { ws = workspaceFolder.uri.fsPath; } } includes.forEach((value, index, elements) => { if (value.startsWith('.')) { value = path.resolve(ws, value); } else { value = path.resolve(value.replace('${workspaceFolder}', ws)); } elements[index] = value; }); // filtra diretorios invalidos e nao encontrados includes = includes.filter(function (value) { try { const fi: fs.Stats = fs.lstatSync(value); if (!fi.isDirectory()) { const msg: string = localize( 'tds.webview.utils.reviewList', 'Review the folder list in order to search for settings (.ch). Not recognized as folder: {0}', value ); vscode.window.showWarningMessage(msg); return false; } } catch (error) { const msg: string = localize( 'tds.webview.utils.reviewList2', 'Review the folder list in order to search for settings (.ch). Invalid folder: {0}', value ); vscode.window.showWarningMessage(msg); return false; } return true; }); } } else { vscode.window.showWarningMessage( localize( 'tds.webview.utils.listFolders', 'List of folders to search for definitions not configured.' ) ); } return includes; } /** * Cria o arquivo servers.json caso ele nao exista. */ static createServerConfig() { if (!fs.existsSync(Utils.getServerConfigPath())) { fs.mkdirSync(Utils.getServerConfigPath()); } let serversJson = Utils.getServerConfigFile(); if (!fs.existsSync(serversJson)) { Utils.initializeServerConfigFile(serversJson); } } static initializeServerConfigFile(serversJson) { try { fs.writeFileSync(serversJson, JSON.stringify(sampleServer(), null, '\t')); } catch (err) { console.error(err); } } /** * Cria o arquivo launch.json caso ele nao exista. */ static createLaunchConfig() { let launchConfig = undefined; try { launchConfig = Utils.getLaunchConfig(); if (!launchConfig) { let fs = require('fs'); let ext = vscode.extensions.getExtension('TOTVS.tds-vscode'); if (ext) { let sampleLaunch = { version: '0.2.0', configurations: [], }; let pkg = ext.packageJSON; let contributes = pkg['contributes']; let debug = (contributes['debuggers'] as any[]).filter( (element: any) => { return element.type === 'totvs_language_debug'; } ); if (debug.length === 1) { let initCfg = (debug[0]['initialConfigurations'] as any[]).filter( (element: any) => { return element.request === 'launch'; } ); if (initCfg.length === 1) { sampleLaunch = { version: '0.2.0', configurations: [initCfg[0] as never], }; } } if (!fs.existsSync(Utils.getVSCodePath())) { fs.mkdirSync(Utils.getVSCodePath()); } let launchJson = Utils.getLaunchConfigFile(); fs.writeFileSync( launchJson, JSON.stringify(sampleLaunch, null, '\t'), (err) => { if (err) { console.error(err); } } ); } } } catch (e) { Utils.logInvalidLaunchJsonFile(e); } } // Duplicado: Usar o getServerById // /** // *Recupera um servidor pelo ID informado. // * @param ID ID do servidor que sera selecionado. // */ // static getServerForID(ID: string) { // let server; // const allConfigs = Utils.getServersConfig(); // if (allConfigs.configurations) { // const configs = allConfigs.configurations; // configs.forEach((element) => { // if (element.id === ID) { // server = element; // if (server.environments === undefined) { // server.environments = []; // } // } // }); // } // return server; // } /** *Recupera um servidor pelo id informado. * @param id id do servidor alvo. * @param serversConfig opcional, se omitido utiliza o padrao */ static getServerById( id: string, serversConfig: any = Utils.getServersConfig() ) { let server; if (serversConfig.configurations) { const configs = serversConfig.configurations; configs.forEach((element) => { if (element.id === id) { server = element; if (server.environments === undefined) { server.environments = []; } } }); } return server; } /** *Recupera um servidor pelo nome informado. * @param name nome do servidor alvo. */ static getServerForNameWithConfig(name: string, serversConfig: any) { let server; if (serversConfig.configurations) { const configs = serversConfig.configurations; configs.forEach((element) => { if (element.name === name) { server = element; if (server.environments === undefined) { server.environments = []; } } }); } return server; } static addCssToHtml(htmlFilePath: vscode.Uri, cssFilePath: vscode.Uri) { const htmlContent = fs.readFileSync( htmlFilePath.with({ scheme: 'vscode-resource' }).fsPath ); const cssContent = fs.readFileSync( cssFilePath.with({ scheme: 'vscode-resource' }).fsPath ); const $ = cheerio.load(htmlContent.toString()); let style = $('style').html(); if (style === undefined || style === null || style === '') { $('html').append('<style>' + cssContent + '</style>'); } else { $('style').append(cssContent.toString()); } return $.html(); } /** *Salva uma nova configuracao de include. */ static saveIncludePath(includePath) { const servers = Utils.getServersConfig(); servers.includes = includePath; Utils.persistServersInfo(servers); let includes = ''; includePath.forEach((includeItem) => { includes += includeItem + ';'; }); changeSettings({ changeSettingInfo: { scope: 'advpls', key: 'includes', value: includes }, }); } /** *Atualiza no server.json a build de um servidor * @param id ID do server que sera atualizado * @param buildVersion Nova build do servidor */ static updateBuildVersion(id: string, buildVersion: string, secure: boolean) { let result = false; if (!id || !buildVersion) { return result; } const serverConfig = Utils.getServersConfig(); serverConfig.configurations.forEach((element) => { if (element.id === id) { element.buildVersion = buildVersion; element.secure = secure; Utils.persistServersInfo(serverConfig); result = true; } }); return result; } /** *Atualiza no server.json o nome de um servidor * @param id ID do server que sera atualizado * @param newName Novo nome do servidor */ static updateServerName(id: string, newName: string) { let result = false; if (!id || !newName) { return result; } const serverConfig = Utils.getServersConfig(); serverConfig.configurations.forEach((element) => { if (element.id === id) { element.name = newName; Utils.persistServersInfo(serverConfig); result = true; } }); return result; } static updatePatchGenerateDir(id: string, patchGenerateDir: string) { let result = false; if ( !id || id.length == 0 || !patchGenerateDir || patchGenerateDir.length == 0 ) { return result; } const serverConfig = Utils.getServersConfig(); serverConfig.configurations.forEach((element) => { if (element.id === id) { element.patchGenerateDir = patchGenerateDir; Utils.persistServersInfo(serverConfig); result = true; } }); return result; } static readCompileKeyFile(path): Authorization { if (fs.existsSync(path)) { const parseIni = ini.parse(fs.readFileSync(path, 'utf-8').toLowerCase()); // XXX toLowerCase?? return parseIni.authorization; } return undefined; } /** * Logs the informed messaged in the console and/or shows a dialog * Please note that the dialog opening respects the dialog settings defined by the user in editor.show.notification * @param message - The message to be shown * @param messageType - The message type * @param showDialog - If it must show a dialog. */ static logMessage( message: string, messageType: MESSAGETYPE, showDialog: boolean ) { let config = vscode.workspace.getConfiguration('totvsLanguageServer'); let notificationLevel = config.get('editor.show.notification'); switch (messageType) { case MESSAGETYPE.Error: languageClient !== undefined ? languageClient.error(message) : console.log(message); if (showDialog && notificationLevel !== 'none') { vscode.window.showErrorMessage(message); } break; case MESSAGETYPE.Info: languageClient !== undefined ? languageClient.info(message) : console.log(message); if ( (showDialog && notificationLevel === 'all') || notificationLevel === 'errors warnings and infos' ) { vscode.window.showInformationMessage(message); } break; case MESSAGETYPE.Warning: languageClient !== undefined ? languageClient.warn(message) : console.log(message); if ( showDialog && (notificationLevel === 'all' || notificationLevel === 'errors warnings and infos' || notificationLevel === 'errors and warnings') ) { vscode.window.showWarningMessage(message); } break; case MESSAGETYPE.Log: let time = Utils.timeAsHHMMSS(new Date()); languageClient !== undefined ? languageClient.outputChannel.appendLine( '[Log + ' + time + '] ' + message ) : console.log(message); if (showDialog && notificationLevel === 'all') { vscode.window.showInformationMessage(message); } break; } } static logInvalidLaunchJsonFile(e) { Utils.logMessage( `Ocorreu um problema ao ler o arquivo launch.json (O arquivo ainda pode estar funcional, porém verifique-o para evitar comportamentos indesejados): ${e}`, MESSAGETYPE.Warning, true ); } static timeAsHHMMSS(date): string { return ( Utils.leftpad(date.getHours(), 2) + ':' + Utils.leftpad(date.getMinutes(), 2) + ':' + Utils.leftpad(date.getSeconds(), 2) ); } static leftpad(val, resultLength = 2, leftpadChar = '0'): string { return (String(leftpadChar).repeat(resultLength) + String(val)).slice( String(val).length ); } static getAllFilesRecursive(folders: Array<string>): string[] { const files: string[] = []; folders.forEach((folder) => { if (fs.lstatSync(folder).isDirectory()) { fs.readdirSync(folder).forEach((file) => { if (!Utils.ignoreResource(file)) { const fn = path.join(folder, file); const ss = fs.statSync(fn); if (ss.isDirectory()) { files.push(...Utils.getAllFilesRecursive([fn])); } else { files.push(fn); } } else { vscode.window.showWarningMessage( "File/folder '" + file + "' was ignored." ); } }); } else { files.push(folder); } }); return files; } static ignoreResource(fileName: string): boolean { return processIgnoreList(ignoreListExpressions, path.basename(fileName)); } static checkDir(selectedDir: string): string { if (fs.existsSync(selectedDir)) { if (!fs.lstatSync(selectedDir).isDirectory()) { selectedDir = path.dirname(selectedDir); } if (fs.lstatSync(selectedDir).isDirectory()) { return selectedDir; } } vscode.window.showErrorMessage( selectedDir + ' does not exist or it is not a directory.' ); return ''; } static deepCopy(obj: any): any { let copy: any; // Handle the 3 simple types, and null or undefined if (null === obj || 'object' !== typeof obj) { return obj; } // Handle Date if (obj instanceof Date) { copy = new Date(); copy.setTime(obj.getTime()); return copy; } // Handle Array if (obj instanceof Array) { copy = []; for (let i = 0, len = obj.length; i < len; i++) { copy[i] = Utils.deepCopy(obj[i]); } return copy; } // Handle Object if (obj instanceof Object) { copy = {}; for (let attr in obj) { if (obj.hasOwnProperty(attr)) { copy[attr] = Utils.deepCopy(obj[attr]); } } return copy; } throw new Error("Unable to copy obj! Its type isn't supported."); } //TODO: melhorar lendo de "package.json" // retorna null ao ler configuração advpl/4gl // let config: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration('languages'); // const advpl = config.get("advpl")["extensions"]; // const logix = config.get("4gl")["extensions"]; private static advpl: string[] = [ '.ch', '.prw', '.prg', '.prx', '.ppx', '.ppp', '.tlpp', '.aph', '.ahu', '.apl', '.apw', ]; private static logix: string[] = ['.4gl', '.per']; static isAdvPlSource(fileName: string): boolean { const ext = path.extname(fileName); return this.advpl.indexOf(ext.toLocaleLowerCase()) > -1; } static is4glSource(fileName: string): boolean { const ext = path.extname(fileName); return this.logix.indexOf(ext.toLocaleLowerCase()) > -1; } static isResource(fileName: string): boolean { return !this.isAdvPlSource(fileName) && !this.is4glSource(fileName); } /** * Deleta o servidor logado por ultimo do servers.json */ static deleteEnvironmentServer(envinronment: EnvSection) { const allConfigs = Utils.getServersConfig(); if (allConfigs.configurations) { const configs = allConfigs.configurations; const id = envinronment.serverItemParent.id; configs.forEach((element) => { if (element.id === id) { const index = element.environments.indexOf(envinronment.label, 0); if (index > -1) { element.environments.splice(index, 1); Utils.persistServersInfo(allConfigs); } return; } }); } } static isSafeRPO(server: ServerItem): boolean { if (server && server.buildVersion) { return server.buildVersion.localeCompare('7.00.191205P') > 0; } return false; } } function sampleServer(): any { return { version: '0.2.1', includes: [''], permissions: { authorizationtoken: '', }, connectedServer: {}, configurations: [], savedTokens: [], lastConnectedServer: '', }; } export function groupBy<T, K>(list: T[], getKey: (item: T) => K) { const map = new Map<K, T[]>(); list.forEach((item) => { const key = getKey(item); const collection = map.get(key); if (!collection) { map.set(key, [item]); } else { collection.push(item); } }); return Array.from(map.values()); } //TODO: pegar a lista de arquivos a ignorar da configuração const ignoreListExpressions: Array<RegExp> = []; ignoreListExpressions.push(/(.*)?(\.vscode)$/gi); //.vscode //ignoreListExpressions.push(/(\.)$/ig); // sem extensão (não é possivel determinar se é fonte ou recurso) ignoreListExpressions.push(/(.+)(\.erx_)$/gi); // arquivos de definição e trabalho ignoreListExpressions.push(/(.+)(\.ppx_)$/gi); // arquivos de definição e trabalho ignoreListExpressions.push(/(.+)(\.err)$/gi); // arquivos de definição e trabalho //lista de arquivos/pastas normalmente ignorados ignoreListExpressions.push(/(.*)?(#.*#)$/gi); ignoreListExpressions.push(/(.*)?(\.#*)$/gi); ignoreListExpressions.push(/(.*)?(%.*%)$/gi); ignoreListExpressions.push(/(.*)?(\._.*)$/gi); ignoreListExpressions.push(/(.*)?(CVS)$/gi); ignoreListExpressions.push(/(.*)?.*(CVS)$/gi); ignoreListExpressions.push(/(.*)?(\.cvsignore)$/gi); ignoreListExpressions.push(/(.*)?(SCCS)$/gi); ignoreListExpressions.push(/(.*)?.*\/SCCS\/.*$/gi); ignoreListExpressions.push(/(.*)?(vssver\.scc)$/gi); ignoreListExpressions.push(/(.*)?(\.svn)$/gi); ignoreListExpressions.push(/(.*)?(\.DS_Store)$/gi); ignoreListExpressions.push(/(.*)?(\.git)$/gi); ignoreListExpressions.push(/(.*)?(\.gitattributes)$/gi); ignoreListExpressions.push(/(.*)?(\.gitignore)$/gi); ignoreListExpressions.push(/(.*)?(\.gitmodules)$/gi); ignoreListExpressions.push(/(.*)?(\.hg)$/gi); ignoreListExpressions.push(/(.*)?(\.hgignore)$/gi); ignoreListExpressions.push(/(.*)?(\.hgsub)$/gi); ignoreListExpressions.push(/(.*)?(\.hgsubstate)$/gi); ignoreListExpressions.push(/(.*)?(\.hgtags)$/gi); ignoreListExpressions.push(/(.*)?(\.bzr)$/gi); ignoreListExpressions.push(/(.*)?(\.bzrignore)$/gi); function processIgnoreList( ignoreList: Array<RegExp>, testName: string ): boolean { let result: boolean = false; for (let index = 0; index < ignoreList.length; index++) { const regexp = ignoreList[index]; if (regexp.test(testName)) { result = true; break; } } return result; }
the_stack
import { Client, MessageEmbed } from "discord.js"; import { FetchHelper } from "./fetchHelper"; import { INodeInfo } from "./models/api/chrysalis/INodeInfo"; import { IStatsGetResponse } from "./models/api/stats/IStatsGetResponse"; import { ICMCQuotesLatestResponse } from "./models/ICMCQuotesLatestResponse"; import { ICoinGeckoPriceResponse } from "./models/ICoinGeckoPriceResponse"; import { IConfiguration } from "./models/IConfiguration"; import { INetworksResponse } from "./models/INetworksResponse"; const COIN_GECKO_URL = "https://api.coingecko.com/api/v3/"; const CMC_URL = "https://pro-api.coinmarketcap.com/v1/"; const CHRYSALIS_STATUS = "https://chrysalis.iota.org/api/tokens"; const MS_60_MINUTES = 60 * 60 * 1000; const MS_30_SECONDS = 30 * 1000; const MARKET_TRIGGER = "!m"; const CHRYSALIS_TRIGGER = "!c-status"; export class App { private readonly _config: IConfiguration; private _botClient: Client; private _explorerNetworks: INetworksResponse | undefined; private _timeLastNetworks: number; private _coinMarketCapCurrencies: string[]; private _lastCoinMarketCapCurrencies: number; private _coinGeckoCurrencies: string[]; private _lastCoinGeckoCurrencies: number; private readonly _lastReactions: { [id: string]: number }; private _lastUsdTime: number; private _lastUsdPrice: number; private _lastChrysalisStats: { day: string; migrationAddresses: string; lockedTokens: string; migratedTokens: string; lastUpdated: string; }[]; /** * Create a new instance of App. * @param config The configuration. */ constructor(config: IConfiguration) { this._config = config; this._timeLastNetworks = 0; this._lastCoinMarketCapCurrencies = 0; this._coinMarketCapCurrencies = []; this._lastCoinGeckoCurrencies = 0; this._coinGeckoCurrencies = []; this._lastReactions = {}; this._lastChrysalisStats = []; this._lastUsdPrice = 0; this._lastUsdTime = 0; } /** * Format the value to number of significant digits. * @param fiat The value to format. * @param numDigits The num of digits to include. * @param extendToFindMax The max number of digits. * @returns The formatted fiat. */ public formatFiat(fiat: number, numDigits: number, extendToFindMax: number): string { const regEx = new RegExp(`^-?\\d*\\.?0*\\d{0,${numDigits}}`); const found = regEx.exec(fiat.toFixed(extendToFindMax)); return found ? found[0] : fiat.toFixed(3); } /** * Start the bot. */ public async start(): Promise<void> { await this.stop(); this._botClient = new Client(); this._botClient.on("ready", () => { console.log(`Logged in as ${this._botClient.user.tag}!`); }); this._botClient.on("message", async msg => { try { if (msg.content.startsWith("!")) { console.log("Bot Command", msg.content); const now = Date.now(); if (this._lastReactions[msg.content] && now - this._lastReactions[msg.content] < MS_30_SECONDS) { if (msg.content === CHRYSALIS_TRIGGER) { const embed = await this.handleChrysalisStats(); if (embed) { await msg.channel.send({ embed }); } } else { await msg.react("🐌"); } } else { let embed: MessageEmbed | undefined; if (msg.content === MARKET_TRIGGER || msg.content.startsWith(`${MARKET_TRIGGER}-`)) { embed = await this.handleMarket(msg.content); } else if (msg.content === CHRYSALIS_TRIGGER) { embed = await this.handleChrysalis(); } else { embed = await this.handleNetwork(msg.content); } if (embed) { this._lastReactions[msg.content] = now; await msg.channel.send({ embed }); } } } } catch (err) { console.error(err); } }); console.log("Bot Logging in..."); await this._botClient.login(this._config.discordToken); console.log("Bot Login Complete"); } /** * Stop the bot running. */ public async stop(): Promise<void> { try { if (this._botClient) { this._botClient.destroy(); this._botClient = undefined; } } catch (err) { console.error("Error Stopping bot", err); } } /** * Handle the network commands. * @param command The command to process. * @returns The message response. */ private async handleNetwork(command: string): Promise<MessageEmbed | undefined> { if (command.startsWith("!")) { const network = command.slice(1); const status = await this.fetchNetworkData(network); if (status) { let color = status.color; let healthReason; let health; if (status.health === 0) { color = "#ff6755"; health = "Bad"; healthReason = status.healthReason; } else if (status.health === 1) { color = "#ff8b5c"; health = "Degraded"; healthReason = status.healthReason; } const embed = new MessageEmbed() .setTitle(status.label) .setColor(color) .addField(status.protocol === "og" ? "TPS" : "MPS", status.itemsPerSecond.toString(), true) .addField(status.protocol === "og" ? "CTPS" : "CMPS", status.confirmedItemsPerSecond.toString(), true) .addField(status.protocol === "og" ? "Confirmation Rate" : "Referenced Rate", `${status.confirmationRate.toFixed(1)}%`, true) .addField( "Latest Milestone Index", status.latestMilestoneIndex ? status.latestMilestoneIndex.toString() : "Unknown"); if (health) { embed.addField("Health", health); } if (healthReason) { embed.addField("Reason", healthReason); } return embed; } } } /** * Fetch the status for a network. * @param network The network to process. * @returns The status for the network. */ private async fetchNetworkData(network: string): Promise<{ health?: number; healthReason?: string; itemsPerSecond?: number; confirmedItemsPerSecond?: number; confirmationRate?: number; latestMilestoneIndex?: number; label: string; protocol: string; color: string; } | undefined> { const now = Date.now(); // If we are using explorer for status endpoints, grab a cached list of the networks if (this._config.explorerEndpoint && (!this._explorerNetworks || now - this._timeLastNetworks > MS_60_MINUTES)) { this._explorerNetworks = await FetchHelper.json<unknown, INetworksResponse>( this._config.explorerEndpoint, "networks", "get"); this._timeLastNetworks = now; } if (this._explorerNetworks?.networks) { const foundNetwork = this._explorerNetworks?.networks.find( n => n.network === network && n.isEnabled && !n.isHidden); if (foundNetwork) { const res = await FetchHelper.json<unknown, IStatsGetResponse>( this._config.explorerEndpoint, `stats/${foundNetwork.network}`, "get"); return { ...res, label: foundNetwork.label, protocol: foundNetwork.protocolVersion, color: foundNetwork.primaryColor }; } } else if (this._config.chrysalisStatusEndpoints) { const statusEndpoint = this._config.chrysalisStatusEndpoints[network]; if (statusEndpoint) { const res = await FetchHelper.json<unknown, { data: INodeInfo }>( statusEndpoint.url, "api/v1/info", "get"); const timeSinceLastMsInMinutes = (Date.now() - (res.data.latestMilestoneTimestamp * 1000)) / 60000; let health = 0; let healthReason = "No milestone within 5 minutes"; if (timeSinceLastMsInMinutes < 2) { health = 2; healthReason = "OK"; } else if (timeSinceLastMsInMinutes < 5) { health = 1; healthReason = "No milestone within 2 minutes"; } return { health, healthReason, itemsPerSecond: res.data.messagesPerSecond, confirmedItemsPerSecond: res.data.referencedMessagesPerSecond, confirmationRate: res.data.referencedRate, latestMilestoneIndex: res.data.latestMilestoneIndex, label: statusEndpoint.label, protocol: "chrysalis", color: statusEndpoint.color }; } } } /** * Handle the market commands. * @param command The command to process. * @returns The message response. */ private async handleMarket(command: string): Promise<MessageEmbed | undefined> { const parts = command.split("-"); let convertCurrency = "usd"; if (parts.length === 2) { convertCurrency = parts[1].toLowerCase(); } const convertCurrencyUpper = convertCurrency.toUpperCase(); let embed = new MessageEmbed() .setTitle(`Market ${convertCurrencyUpper}`) .setColor("#0fc1b7"); let added = false; await this.updateCmcCurrencies(); if (this._coinMarketCapCurrencies.includes(convertCurrency)) { const cmcResponse = await this.updateCmcQuotes(convertCurrency); if (!cmcResponse.data?.["1720"]?.quote[convertCurrencyUpper]) { console.error("CMC Response", cmcResponse); } else { const price = cmcResponse.data["1720"]?.quote[convertCurrencyUpper].price; const change1 = cmcResponse.data["1720"]?.quote[convertCurrencyUpper].percent_change_1h; const change24 = cmcResponse.data["1720"]?.quote[convertCurrencyUpper].percent_change_24h; if (convertCurrencyUpper === "USD") { this._lastUsdPrice = price; } embed = embed.addField("CoinMarketCap", this.formatFiat(price, 3, 8), true) .addField("24H Change", `${change24 >= 0 ? "+" : ""}${change24.toFixed(2)}%`, true) .addField("1H Change", `${change1 >= 0 ? "+" : ""}${change1.toFixed(2)}%`, true); added = true; } } await this.updateCoinGeckoCurrencies(); if (this._coinGeckoCurrencies.includes(convertCurrency)) { const coinGeckoResponse = await FetchHelper.json<unknown, ICoinGeckoPriceResponse>( COIN_GECKO_URL, `simple/price?ids=iota&vs_currencies=${convertCurrency}&include_24hr_change=true&include_24hr_vol=true`, "get"); if (!coinGeckoResponse.iota || !coinGeckoResponse.iota[convertCurrency]) { console.error("Coin Gecko Response", coinGeckoResponse); } else { const price = coinGeckoResponse.iota[convertCurrency]; const change24 = coinGeckoResponse.iota[`${convertCurrency}_24h_change`]; const volume24 = coinGeckoResponse.iota[`${convertCurrency}_24h_vol`]; embed = embed .addField("CoinGecko", this.formatFiat(price, 3, 8), true) .addField("24H Change", `${change24 >= 0 ? "+" : ""}${change24.toFixed(2)}%`, true) .addField("24H Volume", `${volume24.toFixed(0).replace(/\B(?=(\d{3})+(?!\d))/g, ",")}`, true); added = true; } } if (!added) { return new MessageEmbed() .setTitle("Market Unknown") .setColor("#0fc1b7") .addField(":cry:", "I have no data for that currency"); } return embed; } /** * Update the CoinMarketCap data */ private async updateCmcCurrencies(): Promise<void> { const now = Date.now(); if (now - this._lastCoinMarketCapCurrencies > MS_60_MINUTES) { const response = await FetchHelper.json<unknown, { data?: { symbol: string }[] }>( CMC_URL, "cryptocurrency/map", "get", undefined, { "X-CMC_PRO_API_KEY": this._config.coinMarketCapKey } ); if (response?.data) { this._coinMarketCapCurrencies = response?.data.map(d => d.symbol.toLowerCase()); } const response2 = await FetchHelper.json<unknown, { data?: { symbol: string }[] }>( CMC_URL, "fiat/map", "get", undefined, { "X-CMC_PRO_API_KEY": this._config.coinMarketCapKey } ); if (response2?.data) { this._coinMarketCapCurrencies = this._coinMarketCapCurrencies.concat(response2?.data.map(d => d.symbol.toLowerCase())); } this._lastCoinMarketCapCurrencies = now; } } /** * Update the quote data for the currency. * @param currency The currency to retrieve. * @returns The quote data. */ private async updateCmcQuotes(currency: string): Promise<ICMCQuotesLatestResponse> { return FetchHelper.json<unknown, ICMCQuotesLatestResponse>( CMC_URL, `cryptocurrency/quotes/latest?id=1720&convert=${currency}`, "get", undefined, { "X-CMC_PRO_API_KEY": this._config.coinMarketCapKey }); } /** * Update the CoinGecko data. */ private async updateCoinGeckoCurrencies(): Promise<void> { const now = Date.now(); if (now - this._lastCoinGeckoCurrencies > MS_60_MINUTES) { const coinGeckoCurrenciesResponse = await FetchHelper.json<unknown, string[]>( COIN_GECKO_URL, "simple/supported_vs_currencies", "get"); this._coinGeckoCurrencies = coinGeckoCurrenciesResponse; this._lastCoinGeckoCurrencies = now; } } /** * Handle the market commands. * @returns The message response. */ private async handleChrysalis(): Promise<MessageEmbed | undefined> { const response = await FetchHelper.json<unknown, [{ day: string; migrationAddresses: string; lockedTokens: string; migratedTokens: string; lastUpdated: string; }]>( CHRYSALIS_STATUS, "", "get" ); if (Array.isArray(response)) { this._lastChrysalisStats = response.sort((a, b) => b.day.localeCompare(a.day)); return this.handleChrysalisStats(); } } /** * Handle the market commands. * @returns The message response. */ private async handleChrysalisStats(): Promise<MessageEmbed | undefined> { const embed = new MessageEmbed() .setTitle("Chrysalis Migration") .setColor("#0fc1b7"); const MAX_TOKENS = 2779530283000000; if (Array.isArray(this._lastChrysalisStats) && this._lastChrysalisStats.length > 0) { const totalMigrated = Number.parseInt(this._lastChrysalisStats[0].migratedTokens, 10); const totalAddresses = Number.parseInt(this._lastChrysalisStats[0].migrationAddresses, 10); embed.addField("Migrated Tokens", `${(totalMigrated / MAX_TOKENS * 100).toFixed(2)} %`); embed.addField("Amount Migrated Tokens", `${(totalMigrated / 1000000000000).toFixed(2)} Ti`); if (this._lastUsdPrice === 0 || Date.now() - this._lastUsdTime > MS_30_SECONDS) { const quotes = await this.updateCmcQuotes("usd"); this._lastUsdPrice = quotes.data["1720"]?.quote.USD.price; this._lastUsdTime = Date.now(); } if (this._lastUsdPrice !== 0) { // eslint-disable-next-line new-cap const cur = Intl.NumberFormat("en", { style: "currency", currency: "USD" }).format((totalMigrated / 1000000) * this._lastUsdPrice); embed.addField("Value Migrated", cur); } embed.addField("Addresses Migrated", totalAddresses.toString()); } return embed; } }
the_stack
import { Promises, Queue } from 'vs/base/common/async'; import { CancellationToken } from 'vs/base/common/cancellation'; import { IStringDictionary } from 'vs/base/common/collections'; import { toErrorMessage } from 'vs/base/common/errorMessage'; import { getErrorMessage } from 'vs/base/common/errors'; import { Disposable } from 'vs/base/common/lifecycle'; import { Schemas } from 'vs/base/common/network'; import * as path from 'vs/base/common/path'; import { isMacintosh, isWindows } from 'vs/base/common/platform'; import { joinPath } from 'vs/base/common/resources'; import * as semver from 'vs/base/common/semver/semver'; import { isBoolean, isUndefined } from 'vs/base/common/types'; import { URI } from 'vs/base/common/uri'; import { generateUuid } from 'vs/base/common/uuid'; import * as pfs from 'vs/base/node/pfs'; import { extract, ExtractError, IFile, zip } from 'vs/base/node/zip'; import * as nls from 'vs/nls'; import { IDownloadService } from 'vs/platform/download/common/download'; import { INativeEnvironmentService } from 'vs/platform/environment/common/environment'; import { AbstractExtensionManagementService, AbstractExtensionTask, IInstallExtensionTask, IUninstallExtensionTask, joinErrors, UninstallExtensionTaskOptions } from 'vs/platform/extensionManagement/common/abstractExtensionManagementService'; import { ExtensionManagementError, ExtensionManagementErrorCode, IExtensionGalleryService, IExtensionIdentifier, IExtensionManagementService, IGalleryExtension, IGalleryMetadata, ILocalExtension, InstallOperation, InstallOptions, InstallVSIXOptions, Metadata } from 'vs/platform/extensionManagement/common/extensionManagement'; import { areSameExtensions, computeTargetPlatform, ExtensionKey, getGalleryExtensionId, groupByExtension } from 'vs/platform/extensionManagement/common/extensionManagementUtil'; import { IExtensionsScannerService, IScannedExtension, ScanOptions } from 'vs/platform/extensionManagement/common/extensionsScannerService'; import { ExtensionsDownloader } from 'vs/platform/extensionManagement/node/extensionDownloader'; import { ExtensionsLifecycle } from 'vs/platform/extensionManagement/node/extensionLifecycle'; import { getManifest } from 'vs/platform/extensionManagement/node/extensionManagementUtil'; import { ExtensionsManifestCache } from 'vs/platform/extensionManagement/node/extensionsManifestCache'; import { ExtensionsWatcher } from 'vs/platform/extensionManagement/node/extensionsWatcher'; import { ExtensionType, IExtensionManifest, TargetPlatform } from 'vs/platform/extensions/common/extensions'; import { isEngineValid } from 'vs/platform/extensions/common/extensionValidator'; import { IFileService } from 'vs/platform/files/common/files'; import { IInstantiationService } from 'vs/platform/instantiation/common/instantiation'; import { ILogService } from 'vs/platform/log/common/log'; import { IProductService } from 'vs/platform/product/common/productService'; import { ITelemetryService } from 'vs/platform/telemetry/common/telemetry'; import { IUriIdentityService } from 'vs/platform/uriIdentity/common/uriIdentity'; interface InstallableExtension { zipPath: string; key: ExtensionKey; metadata?: Metadata; } export class ExtensionManagementService extends AbstractExtensionManagementService implements IExtensionManagementService { private readonly extensionsScanner: ExtensionsScanner; private readonly manifestCache: ExtensionsManifestCache; private readonly extensionsDownloader: ExtensionsDownloader; constructor( @IExtensionGalleryService galleryService: IExtensionGalleryService, @ITelemetryService telemetryService: ITelemetryService, @ILogService logService: ILogService, @INativeEnvironmentService private readonly environmentService: INativeEnvironmentService, @IDownloadService private downloadService: IDownloadService, @IInstantiationService instantiationService: IInstantiationService, @IFileService private readonly fileService: IFileService, @IProductService productService: IProductService, @IUriIdentityService uriIdentityService: IUriIdentityService ) { super(galleryService, telemetryService, logService, productService); const extensionLifecycle = this._register(instantiationService.createInstance(ExtensionsLifecycle)); this.extensionsScanner = this._register(instantiationService.createInstance(ExtensionsScanner, extension => extensionLifecycle.postUninstall(extension))); this.manifestCache = this._register(new ExtensionsManifestCache(environmentService, this)); this.extensionsDownloader = this._register(instantiationService.createInstance(ExtensionsDownloader)); const extensionsWatcher = this._register(new ExtensionsWatcher(this, fileService, environmentService, logService, uriIdentityService)); this._register(extensionsWatcher.onDidChangeExtensionsByAnotherSource(({ added, removed }) => { if (added.length) { this._onDidInstallExtensions.fire(added.map(local => ({ identifier: local.identifier, operation: InstallOperation.None, local }))); } removed.forEach(extension => this._onDidUninstallExtension.fire({ identifier: extension })); })); } private _targetPlatformPromise: Promise<TargetPlatform> | undefined; getTargetPlatform(): Promise<TargetPlatform> { if (!this._targetPlatformPromise) { this._targetPlatformPromise = computeTargetPlatform(this.fileService, this.logService); } return this._targetPlatformPromise; } async zip(extension: ILocalExtension): Promise<URI> { this.logService.trace('ExtensionManagementService#zip', extension.identifier.id); const files = await this.collectFiles(extension); const location = await zip(joinPath(this.environmentService.tmpDir, generateUuid()).fsPath, files); return URI.file(location); } async unzip(zipLocation: URI): Promise<IExtensionIdentifier> { this.logService.trace('ExtensionManagementService#unzip', zipLocation.toString()); const local = await this.install(zipLocation); return local.identifier; } async getManifest(vsix: URI): Promise<IExtensionManifest> { const downloadLocation = await this.downloadVsix(vsix); const zipPath = path.resolve(downloadLocation.fsPath); return getManifest(zipPath); } getInstalled(type: ExtensionType | null = null): Promise<ILocalExtension[]> { return this.extensionsScanner.scanExtensions(type); } async install(vsix: URI, options: InstallVSIXOptions = {}): Promise<ILocalExtension> { this.logService.trace('ExtensionManagementService#install', vsix.toString()); const downloadLocation = await this.downloadVsix(vsix); const manifest = await getManifest(path.resolve(downloadLocation.fsPath)); if (manifest.engines && manifest.engines.vscode && !isEngineValid(manifest.engines.vscode, this.productService.version, this.productService.date)) { throw new Error(nls.localize('incompatible', "Unable to install extension '{0}' as it is not compatible with VS Code '{1}'.", getGalleryExtensionId(manifest.publisher, manifest.name), this.productService.version)); } return this.installExtension(manifest, downloadLocation, options); } async updateMetadata(local: ILocalExtension, metadata: IGalleryMetadata): Promise<ILocalExtension> { this.logService.trace('ExtensionManagementService#updateMetadata', local.identifier.id); const localMetadata: Metadata = { ...metadata }; if (metadata.isPreReleaseVersion) { localMetadata.preRelease = true; } local = await this.extensionsScanner.updateMetadata(local, localMetadata); this.manifestCache.invalidate(); return local; } async updateExtensionScope(local: ILocalExtension, isMachineScoped: boolean): Promise<ILocalExtension> { this.logService.trace('ExtensionManagementService#updateExtensionScope', local.identifier.id); local = await this.extensionsScanner.updateMetadata(local, { isMachineScoped }); this.manifestCache.invalidate(); return local; } removeDeprecatedExtensions(): Promise<void> { return this.extensionsScanner.cleanUp(); } private async downloadVsix(vsix: URI): Promise<URI> { if (vsix.scheme === Schemas.file) { return vsix; } const downloadedLocation = joinPath(this.environmentService.tmpDir, generateUuid()); await this.downloadService.download(vsix, downloadedLocation); return downloadedLocation; } protected createInstallExtensionTask(manifest: IExtensionManifest, extension: URI | IGalleryExtension, options: InstallOptions & InstallVSIXOptions): IInstallExtensionTask { return URI.isUri(extension) ? new InstallVSIXTask(manifest, extension, options, this.galleryService, this.extensionsScanner, this.logService) : new InstallGalleryExtensionTask(extension, options, this.extensionsDownloader, this.extensionsScanner, this.logService); } protected createUninstallExtensionTask(extension: ILocalExtension, options: UninstallExtensionTaskOptions): IUninstallExtensionTask { return new UninstallExtensionTask(extension, options, this.extensionsScanner); } private async collectFiles(extension: ILocalExtension): Promise<IFile[]> { const collectFilesFromDirectory = async (dir: string): Promise<string[]> => { let entries = await pfs.Promises.readdir(dir); entries = entries.map(e => path.join(dir, e)); const stats = await Promise.all(entries.map(e => pfs.Promises.stat(e))); let promise: Promise<string[]> = Promise.resolve([]); stats.forEach((stat, index) => { const entry = entries[index]; if (stat.isFile()) { promise = promise.then(result => ([...result, entry])); } if (stat.isDirectory()) { promise = promise .then(result => collectFilesFromDirectory(entry) .then(files => ([...result, ...files]))); } }); return promise; }; const files = await collectFilesFromDirectory(extension.location.fsPath); return files.map(f => (<IFile>{ path: `extension/${path.relative(extension.location.fsPath, f)}`, localPath: f })); } } class ExtensionsScanner extends Disposable { private readonly uninstalledPath: string; private readonly uninstalledFileLimiter: Queue<any>; constructor( private readonly beforeRemovingExtension: (e: ILocalExtension) => Promise<void>, @IFileService private readonly fileService: IFileService, @IExtensionsScannerService private readonly extensionsScannerService: IExtensionsScannerService, @ILogService private readonly logService: ILogService, ) { super(); this.uninstalledPath = joinPath(this.extensionsScannerService.userExtensionsLocation, '.obsolete').fsPath; this.uninstalledFileLimiter = new Queue(); } async cleanUp(): Promise<void> { await this.removeUninstalledExtensions(); await this.removeOutdatedExtensions(); } async scanExtensions(type: ExtensionType | null): Promise<ILocalExtension[]> { const scannedOptions: ScanOptions = { includeInvalid: true }; let scannedExtensions: IScannedExtension[] = []; if (type === null || type === ExtensionType.System) { scannedExtensions.push(...await this.extensionsScannerService.scanAllExtensions(scannedOptions)); } else if (type === ExtensionType.User) { scannedExtensions.push(...await this.extensionsScannerService.scanUserExtensions(scannedOptions)); } scannedExtensions = type !== null ? scannedExtensions.filter(r => r.type === type) : scannedExtensions; return Promise.all(scannedExtensions.map(extension => this.toLocalExtension(extension))); } async scanUserExtensions(excludeOutdated: boolean): Promise<ILocalExtension[]> { const scannedExtensions = await this.extensionsScannerService.scanUserExtensions({ includeAllVersions: !excludeOutdated, includeInvalid: true }); return Promise.all(scannedExtensions.map(extension => this.toLocalExtension(extension))); } async extractUserExtension(extensionKey: ExtensionKey, zipPath: string, metadata: Metadata | undefined, token: CancellationToken): Promise<ILocalExtension> { const folderName = extensionKey.toString(); const tempPath = path.join(this.extensionsScannerService.userExtensionsLocation.fsPath, `.${generateUuid()}`); const extensionPath = path.join(this.extensionsScannerService.userExtensionsLocation.fsPath, folderName); try { await pfs.Promises.rm(extensionPath); } catch (error) { throw new ExtensionManagementError(nls.localize('errorDeleting', "Unable to delete the existing folder '{0}' while installing the extension '{1}'. Please delete the folder manually and try again", extensionPath, extensionKey.id), ExtensionManagementErrorCode.Delete); } await this.extractAtLocation(extensionKey, zipPath, tempPath, token); await this.extensionsScannerService.updateMetadata(URI.file(tempPath), { ...metadata, installedTimestamp: Date.now() }); try { await this.rename(extensionKey, tempPath, extensionPath, Date.now() + (2 * 60 * 1000) /* Retry for 2 minutes */); this.logService.info('Renamed to', extensionPath); } catch (error) { try { await pfs.Promises.rm(tempPath); } catch (e) { /* ignore */ } if (error.code === 'ENOTEMPTY') { this.logService.info(`Rename failed because extension was installed by another source. So ignoring renaming.`, extensionKey.id); } else { this.logService.info(`Rename failed because of ${getErrorMessage(error)}. Deleted from extracted location`, tempPath); throw error; } } return this.scanLocalExtension(URI.file(extensionPath), ExtensionType.User); } async updateMetadata(local: ILocalExtension, metadata: Partial<Metadata>): Promise<ILocalExtension> { await this.extensionsScannerService.updateMetadata(local.location, metadata); return this.scanLocalExtension(local.location, local.type); } getUninstalledExtensions(): Promise<IStringDictionary<boolean>> { return this.withUninstalledExtensions(); } async setUninstalled(...extensions: ILocalExtension[]): Promise<void> { const extensionKeys: ExtensionKey[] = extensions.map(e => ExtensionKey.create(e)); await this.withUninstalledExtensions(uninstalled => { extensionKeys.forEach(extensionKey => uninstalled[extensionKey.toString()] = true); }); } async setInstalled(extensionKey: ExtensionKey): Promise<ILocalExtension | null> { await this.withUninstalledExtensions(uninstalled => delete uninstalled[extensionKey.toString()]); const userExtensions = await this.scanUserExtensions(true); const localExtension = userExtensions.find(i => ExtensionKey.create(i).equals(extensionKey)) || null; if (!localExtension) { return null; } return this.updateMetadata(localExtension, { installedTimestamp: Date.now() }); } async removeExtension(extension: ILocalExtension | IScannedExtension, type: string): Promise<void> { this.logService.trace(`Deleting ${type} extension from disk`, extension.identifier.id, extension.location.fsPath); await pfs.Promises.rm(extension.location.fsPath); this.logService.info('Deleted from disk', extension.identifier.id, extension.location.fsPath); } async removeUninstalledExtension(extension: ILocalExtension | IScannedExtension): Promise<void> { await this.removeExtension(extension, 'uninstalled'); await this.withUninstalledExtensions(uninstalled => delete uninstalled[ExtensionKey.create(extension).toString()]); } private async withUninstalledExtensions(updateFn?: (uninstalled: IStringDictionary<boolean>) => void): Promise<IStringDictionary<boolean>> { return this.uninstalledFileLimiter.queue(async () => { let raw: string | undefined; try { raw = await pfs.Promises.readFile(this.uninstalledPath, 'utf8'); } catch (err) { if (err.code !== 'ENOENT') { throw err; } } let uninstalled = {}; if (raw) { try { uninstalled = JSON.parse(raw); } catch (e) { /* ignore */ } } if (updateFn) { updateFn(uninstalled); if (Object.keys(uninstalled).length) { await pfs.Promises.writeFile(this.uninstalledPath, JSON.stringify(uninstalled)); } else { await pfs.Promises.rm(this.uninstalledPath); } } return uninstalled; }); } private async extractAtLocation(identifier: IExtensionIdentifier, zipPath: string, location: string, token: CancellationToken): Promise<void> { this.logService.trace(`Started extracting the extension from ${zipPath} to ${location}`); // Clean the location try { await pfs.Promises.rm(location); } catch (e) { throw new ExtensionManagementError(this.joinErrors(e).message, ExtensionManagementErrorCode.Delete); } try { await extract(zipPath, location, { sourcePath: 'extension', overwrite: true }, token); this.logService.info(`Extracted extension to ${location}:`, identifier.id); } catch (e) { try { await pfs.Promises.rm(location); } catch (e) { /* Ignore */ } let errorCode = ExtensionManagementErrorCode.Extract; if (e instanceof ExtractError) { if (e.type === 'CorruptZip') { errorCode = ExtensionManagementErrorCode.CorruptZip; } else if (e.type === 'Incomplete') { errorCode = ExtensionManagementErrorCode.IncompleteZip; } } throw new ExtensionManagementError(e.message, errorCode); } } private async rename(identifier: IExtensionIdentifier, extractPath: string, renamePath: string, retryUntil: number): Promise<void> { try { await pfs.Promises.rename(extractPath, renamePath); } catch (error) { if (isWindows && error && error.code === 'EPERM' && Date.now() < retryUntil) { this.logService.info(`Failed renaming ${extractPath} to ${renamePath} with 'EPERM' error. Trying again...`, identifier.id); return this.rename(identifier, extractPath, renamePath, retryUntil); } throw new ExtensionManagementError(error.message || nls.localize('renameError', "Unknown error while renaming {0} to {1}", extractPath, renamePath), error.code || ExtensionManagementErrorCode.Rename); } } private async scanLocalExtension(location: URI, type: ExtensionType): Promise<ILocalExtension> { const scannedExtension = await this.extensionsScannerService.scanExistingExtension(location, type, { includeInvalid: true }); if (scannedExtension) { return this.toLocalExtension(scannedExtension); } throw new Error(nls.localize('cannot read', "Cannot read the extension from {0}", location.path)); } private async toLocalExtension(extension: IScannedExtension): Promise<ILocalExtension> { const stat = await this.fileService.resolve(extension.location); let readmeUrl: URI | undefined; let changelogUrl: URI | undefined; if (stat.children) { readmeUrl = stat.children.find(({ name }) => /^readme(\.txt|\.md|)$/i.test(name))?.resource; changelogUrl = stat.children.find(({ name }) => /^changelog(\.txt|\.md|)$/i.test(name))?.resource; } return { identifier: extension.identifier, type: extension.type, isBuiltin: extension.isBuiltin || !!extension.metadata?.isBuiltin, location: extension.location, manifest: extension.manifest, targetPlatform: extension.targetPlatform, validations: extension.validations, isValid: extension.isValid, readmeUrl, changelogUrl, publisherDisplayName: extension.metadata?.publisherDisplayName || null, publisherId: extension.metadata?.publisherId || null, isMachineScoped: !!extension.metadata?.isMachineScoped, isPreReleaseVersion: !!extension.metadata?.isPreReleaseVersion, preRelease: !!extension.metadata?.preRelease, installedTimestamp: extension.metadata?.installedTimestamp, updated: !!extension.metadata?.updated, }; } private async removeUninstalledExtensions(): Promise<void> { const uninstalled = await this.getUninstalledExtensions(); const extensions = await this.extensionsScannerService.scanUserExtensions({ includeAllVersions: true, includeUninstalled: true, includeInvalid: true }); // All user extensions const installed: Set<string> = new Set<string>(); for (const e of extensions) { if (!uninstalled[ExtensionKey.create(e).toString()]) { installed.add(e.identifier.id.toLowerCase()); } } const byExtension = groupByExtension(extensions, e => e.identifier); await Promises.settled(byExtension.map(async e => { const latest = e.sort((a, b) => semver.rcompare(a.manifest.version, b.manifest.version))[0]; if (!installed.has(latest.identifier.id.toLowerCase())) { await this.beforeRemovingExtension(await this.toLocalExtension(latest)); } })); const toRemove = extensions.filter(e => uninstalled[ExtensionKey.create(e).toString()]); await Promises.settled(toRemove.map(e => this.removeUninstalledExtension(e))); } private async removeOutdatedExtensions(): Promise<void> { const extensions = await this.extensionsScannerService.scanUserExtensions({ includeAllVersions: true, includeUninstalled: true, includeInvalid: true }); // All user extensions const toRemove: IScannedExtension[] = []; // Outdated extensions const targetPlatform = await this.extensionsScannerService.getTargetPlatform(); const byExtension = groupByExtension(extensions, e => e.identifier); toRemove.push(...byExtension.map(p => p.sort((a, b) => { const vcompare = semver.rcompare(a.manifest.version, b.manifest.version); if (vcompare !== 0) { return vcompare; } if (a.targetPlatform === targetPlatform) { return -1; } return 1; }).slice(1)).flat()); await Promises.settled(toRemove.map(extension => this.removeExtension(extension, 'outdated'))); } private joinErrors(errorOrErrors: (Error | string) | (Array<Error | string>)): Error { const errors = Array.isArray(errorOrErrors) ? errorOrErrors : [errorOrErrors]; if (errors.length === 1) { return errors[0] instanceof Error ? <Error>errors[0] : new Error(<string>errors[0]); } return errors.reduce<Error>((previousValue: Error, currentValue: Error | string) => { return new Error(`${previousValue.message}${previousValue.message ? ',' : ''}${currentValue instanceof Error ? currentValue.message : currentValue}`); }, new Error('')); } } abstract class AbstractInstallExtensionTask extends AbstractExtensionTask<ILocalExtension> implements IInstallExtensionTask { protected _operation = InstallOperation.Install; get operation() { return isUndefined(this.options.operation) ? this._operation : this.options.operation; } constructor( readonly identifier: IExtensionIdentifier, readonly source: URI | IGalleryExtension, protected readonly options: InstallOptions, protected readonly extensionsScanner: ExtensionsScanner, protected readonly logService: ILogService, ) { super(); } protected async installExtension(installableExtension: InstallableExtension, token: CancellationToken): Promise<ILocalExtension> { try { const local = await this.unsetUninstalledAndGetLocal(installableExtension.key); if (local) { return installableExtension.metadata ? this.extensionsScanner.updateMetadata(local, installableExtension.metadata) : local; } } catch (e) { if (isMacintosh) { throw new ExtensionManagementError(nls.localize('quitCode', "Unable to install the extension. Please Quit and Start VS Code before reinstalling."), ExtensionManagementErrorCode.Internal); } else { throw new ExtensionManagementError(nls.localize('exitCode', "Unable to install the extension. Please Exit and Start VS Code before reinstalling."), ExtensionManagementErrorCode.Internal); } } return this.extract(installableExtension, token); } protected async unsetUninstalledAndGetLocal(extensionKey: ExtensionKey): Promise<ILocalExtension | null> { const isUninstalled = await this.isUninstalled(extensionKey); if (!isUninstalled) { return null; } this.logService.trace('Removing the extension from uninstalled list:', extensionKey.id); // If the same version of extension is marked as uninstalled, remove it from there and return the local. const local = await this.extensionsScanner.setInstalled(extensionKey); this.logService.info('Removed the extension from uninstalled list:', extensionKey.id); return local; } private async isUninstalled(extensionId: ExtensionKey): Promise<boolean> { const uninstalled = await this.extensionsScanner.getUninstalledExtensions(); return !!uninstalled[extensionId.toString()]; } private async extract({ zipPath, key, metadata }: InstallableExtension, token: CancellationToken): Promise<ILocalExtension> { let local = await this.extensionsScanner.extractUserExtension(key, zipPath, metadata, token); this.logService.info('Extracting completed.', key.id); return local; } } class InstallGalleryExtensionTask extends AbstractInstallExtensionTask { constructor( private readonly gallery: IGalleryExtension, options: InstallOptions, private readonly extensionsDownloader: ExtensionsDownloader, extensionsScanner: ExtensionsScanner, logService: ILogService, ) { super(gallery.identifier, gallery, options, extensionsScanner, logService); } protected async doRun(token: CancellationToken): Promise<ILocalExtension> { const installed = await this.extensionsScanner.scanExtensions(null); const existingExtension = installed.find(i => areSameExtensions(i.identifier, this.gallery.identifier)); if (existingExtension) { this._operation = InstallOperation.Update; } const installableExtension = await this.downloadInstallableExtension(this.gallery, this._operation); installableExtension.metadata.isMachineScoped = this.options.isMachineScoped || existingExtension?.isMachineScoped; installableExtension.metadata.isBuiltin = this.options.isBuiltin || existingExtension?.isBuiltin; installableExtension.metadata.isSystem = existingExtension?.type === ExtensionType.System ? true : undefined; installableExtension.metadata.updated = !!existingExtension; installableExtension.metadata.isPreReleaseVersion = this.gallery.properties.isPreReleaseVersion; installableExtension.metadata.preRelease = this.gallery.properties.isPreReleaseVersion || (isBoolean(this.options.installPreReleaseVersion) ? this.options.installPreReleaseVersion /* Respect the passed flag */ : existingExtension?.preRelease /* Respect the existing pre-release flag if it was set */); try { const local = await this.installExtension(installableExtension, token); if (existingExtension && (existingExtension.targetPlatform !== local.targetPlatform || semver.neq(existingExtension.manifest.version, local.manifest.version))) { await this.extensionsScanner.setUninstalled(existingExtension); } return local; } catch (error) { await this.deleteDownloadedVSIX(installableExtension.zipPath); throw error; } } private async deleteDownloadedVSIX(vsix: string): Promise<void> { try { await this.extensionsDownloader.delete(URI.file(vsix)); } catch (error) { /* Ignore */ this.logService.warn('Error while deleting the downloaded vsix', vsix.toString(), getErrorMessage(error)); } } private async downloadInstallableExtension(extension: IGalleryExtension, operation: InstallOperation): Promise<Required<InstallableExtension>> { const metadata = <IGalleryMetadata>{ id: extension.identifier.uuid, publisherId: extension.publisherId, publisherDisplayName: extension.publisherDisplayName, targetPlatform: extension.properties.targetPlatform }; let zipPath: string | undefined; try { this.logService.trace('Started downloading extension:', extension.identifier.id); zipPath = (await this.extensionsDownloader.downloadExtension(extension, operation)).fsPath; this.logService.info('Downloaded extension:', extension.identifier.id, zipPath); } catch (error) { throw new ExtensionManagementError(joinErrors(error).message, ExtensionManagementErrorCode.Download); } try { await getManifest(zipPath); return (<Required<InstallableExtension>>{ zipPath, key: ExtensionKey.create(extension), metadata }); } catch (error) { await this.deleteDownloadedVSIX(zipPath); throw new ExtensionManagementError(joinErrors(error).message, ExtensionManagementErrorCode.Invalid); } } } class InstallVSIXTask extends AbstractInstallExtensionTask { constructor( private readonly manifest: IExtensionManifest, private readonly location: URI, options: InstallOptions, private readonly galleryService: IExtensionGalleryService, extensionsScanner: ExtensionsScanner, logService: ILogService ) { super({ id: getGalleryExtensionId(manifest.publisher, manifest.name) }, location, options, extensionsScanner, logService); } protected async doRun(token: CancellationToken): Promise<ILocalExtension> { const extensionKey = new ExtensionKey(this.identifier, this.manifest.version); const installedExtensions = await this.extensionsScanner.scanExtensions(ExtensionType.User); const existing = installedExtensions.find(i => areSameExtensions(this.identifier, i.identifier)); const metadata = await this.getMetadata(this.identifier.id, this.manifest.version, token); metadata.isMachineScoped = this.options.isMachineScoped || existing?.isMachineScoped; metadata.isBuiltin = this.options.isBuiltin || existing?.isBuiltin; if (existing) { this._operation = InstallOperation.Update; if (extensionKey.equals(new ExtensionKey(existing.identifier, existing.manifest.version))) { try { await this.extensionsScanner.removeExtension(existing, 'existing'); } catch (e) { throw new Error(nls.localize('restartCode', "Please restart VS Code before reinstalling {0}.", this.manifest.displayName || this.manifest.name)); } } else if (semver.gt(existing.manifest.version, this.manifest.version)) { await this.extensionsScanner.setUninstalled(existing); } } else { // Remove the extension with same version if it is already uninstalled. // Installing a VSIX extension shall replace the existing extension always. const existing = await this.unsetUninstalledAndGetLocal(extensionKey); if (existing) { try { await this.extensionsScanner.removeExtension(existing, 'existing'); } catch (e) { throw new Error(nls.localize('restartCode', "Please restart VS Code before reinstalling {0}.", this.manifest.displayName || this.manifest.name)); } } } return this.installExtension({ zipPath: path.resolve(this.location.fsPath), key: extensionKey, metadata }, token); } private async getMetadata(id: string, version: string, token: CancellationToken): Promise<Metadata> { try { let [galleryExtension] = await this.galleryService.getExtensions([{ id, version }], token); if (!galleryExtension) { [galleryExtension] = await this.galleryService.getExtensions([{ id }], token); } if (galleryExtension) { return { id: galleryExtension.identifier.uuid, publisherDisplayName: galleryExtension.publisherDisplayName, publisherId: galleryExtension.publisherId, isPreReleaseVersion: galleryExtension.properties.isPreReleaseVersion, preRelease: galleryExtension.properties.isPreReleaseVersion || this.options.installPreReleaseVersion }; } } catch (error) { /* Ignore Error */ } return {}; } } class UninstallExtensionTask extends AbstractExtensionTask<void> implements IUninstallExtensionTask { constructor( readonly extension: ILocalExtension, private readonly options: UninstallExtensionTaskOptions, private readonly extensionsScanner: ExtensionsScanner ) { super(); } protected async doRun(token: CancellationToken): Promise<void> { const toUninstall: ILocalExtension[] = []; const userExtensions = await this.extensionsScanner.scanUserExtensions(false); if (this.options.versionOnly) { const extensionKey = ExtensionKey.create(this.extension); toUninstall.push(...userExtensions.filter(u => extensionKey.equals(ExtensionKey.create(u)))); } else { toUninstall.push(...userExtensions.filter(u => areSameExtensions(u.identifier, this.extension.identifier))); } if (!toUninstall.length) { throw new Error(nls.localize('notInstalled', "Extension '{0}' is not installed.", this.extension.manifest.displayName || this.extension.manifest.name)); } await this.extensionsScanner.setUninstalled(...toUninstall); if (this.options.remove) { for (const extension of toUninstall) { try { if (!token.isCancellationRequested) { await this.extensionsScanner.removeUninstalledExtension(extension); } } catch (e) { throw new Error(nls.localize('removeError', "Error while removing the extension: {0}. Please Quit and Start VS Code before trying again.", toErrorMessage(e))); } } } } }
the_stack
import test from 'ava'; import { Nohm, nohm } from '../ts'; import * as args from './testArgs'; import { cleanUpPromise } from './helper'; import { exists, get, keys } from '../ts/typed-redis-helper'; const redis = args.redis; const Model = Nohm.model('UniqueTests', { properties: { name: { defaultValue: 'test', type: 'string', unique: true, validations: ['notEmpty'], }, visits: { index: true, type: 'integer', }, email: { defaultValue: 'email@email.de', type: 'string', unique: true, validations: ['email'], }, emailOptional: { defaultValue: '', type: 'string', unique: true, validations: [ { name: 'email', options: { optional: true, }, }, ], }, country: { index: true, defaultValue: 'Tibet', type: 'string', validations: ['notEmpty'], }, }, idGenerator: 'increment', }); const prefix = args.prefix + 'unique'; test.before(async () => { nohm.setPrefix(prefix); await args.setClient(nohm, redis); await cleanUpPromise(redis, prefix); }); test.afterEach(async () => { await cleanUpPromise(redis, prefix); }); test.serial('unique', async (t) => { const instance1 = new Model(); const instance2 = new Model(); instance1.property('name', 'duplicateTest'); instance1.property('email', 'duplicateTest@test.de'); instance2.property('name', 'duplicateTest'); instance2.property('email', 'dubplicateTest@test.de'); // intentional typo "dubplicate" await instance1.save(); const uniqueLock1 = await get( redis, `${prefix}:uniques:${instance1.modelName}:name:duplicatetest`, ); t.truthy(instance1.id, 'User id b0rked while checking uniques'); t.is(uniqueLock1, instance1.id, 'The unique key did not have the correct id'); const valid = await instance2.validate(); t.true( !valid, 'A unique property was not recognized as a duplicate in valid without setDirectly', ); try { await instance2.save(); t.true( false, 'Saving a model with an invalid non-unique property did not throw/reject.', ); } catch (err) { t.true( err instanceof nohm.ValidationError, 'A saved unique property was not recognized as a duplicate', ); t.deepEqual( err.errors.name, ['notUnique'], 'A saved unique property was not recognized as a duplicate', ); const doesExist = await exists( redis, `${prefix}:uniques:${instance1.modelName}:email:dubbplicatetest@test.de`, ); t.is( doesExist, 0, 'The tmp unique lock was not deleted for a failed save.', ); const uniqueLock2 = await get( redis, `${prefix}:uniques:${instance1.modelName}:name:duplicatetest`, ); t.is( uniqueLock2, instance1.id, 'The unique key did not have the correct id after trying to save another unique.', ); } }); test.serial('unique with lowerLowerCase', async (t) => { const instance1 = new Model(); const instance2 = new Model(); instance1.property('name', 'LowerCaseTest'); instance1.property('email', 'LowerCaseTest@test.de'); instance2.property('name', 'lowercasetest'); instance2.property('email', 'lowercasetest@test.de'); await instance1.save(); const uniqueLock = await get( redis, `${prefix}:uniques:${instance1.modelName}:name:${instance1 .property('name') .toLowerCase()}`, ); t.is(uniqueLock, instance1.id, 'The unique key did not have the correct id'); const valid = await instance2.validate(); t.true( !valid, 'A unique property was not recognized as a duplicate in valid without setDirectly.', ); try { await instance2.save(); t.fail( 'Saving a model with an invalid non-unique property did not throw/reject.', ); } catch (err) { t.true( err instanceof nohm.ValidationError, 'A saved unique property was not recognized as a duplicate', ); const value = await get( redis, `${prefix}:uniques:${instance1.modelName}:name:lowercasetest`, ); t.is( value, instance1.id, 'The unique key did not have the correct id after trying to save another unique.', ); } }); test.serial( 'deletes unique lock when a non-unique validation fails', async (t) => { const instance = new Model(); instance.property('name', 'uniqueDeleteTest'); instance.property('email', 'uniqueDeleteTest@test.de'); instance.property('country', ''); try { await instance.save(); t.fail('Saving the instance succeeded where it should have failed.'); } catch (err) { t.true( err instanceof nohm.ValidationError, 'There was an unexpected problem: ' + err, ); const value = await exists( redis, prefix + ':uniques:UserMockup:name:' + instance.property('name').toLowerCase(), ); t.is( value, 0, 'The unique was locked although there were errors in the non-unique checks.', ); } }, ); test.serial( 'validate on only one property checks unique properly', async (t) => { const instance1 = new Model(); instance1.property('name', 'duplicateTest'); instance1.property('email', 'duplicateTest@test.de'); await instance1.save(); const instance2 = new Model(); instance2.property('name', 'duplicateTest'); instance2.property('email', 'duplicateTest@test.de'); const valid = await instance2.validate('name'); t.is(valid, false, 'Checking the duplication status failed in valid().'); t.deepEqual( instance2.errors.email, [], 'Checking the duplication status of one property set the error for another one.', ); }, ); test.serial('uniqueDeletion', async (t) => { const instance = new Model(); instance.property({ name: 'duplicateDeletionTest', email: 'duplicateDeletionTest@test.de', country: '', }); try { await instance.save(); t.fail('Saving the instance succeeded where it should have failed.'); } catch (err) { const value = await exists( redis, `${prefix}:uniques:${instance.modelName}:name:duplicateDeletionTest`, ); t.is( value, 0, 'The tmp unique key was not deleted if a non-unique saving failure occurred.', ); } }); test.serial('uniques are case INsensitive', async (t) => { const instance1 = new Model(); const instance2 = new Model(); instance1.property({ name: 'uniqueCaseInSensitive', email: 'uniqueCaseInSensitive@test.de', }); instance2.property({ name: instance1.property('name').toLowerCase(), email: instance1.property('email').toLowerCase(), }); await instance1.save(); const valid = await instance2.validate(); t.true(!valid, 'A duplicate (different case) unique property was validated.'); t.deepEqual( instance2.errors.name, ['notUnique'], 'The error for name was not correct.', ); t.deepEqual( instance2.errors.email, ['notUnique'], 'The error for email was not correct.', ); }); test.serial('uniqueEmpty', async (t) => { const instance = new Model(); const doesExist = await exists( redis, prefix + ':uniques:UserMockup:emailOptional:', ); t.is(doesExist, 0, 'An empty unique was set before the test for it was run'); instance.property({ name: 'emailOptional', email: 'emailOptionalTest@test.de', emailOptional: '', }); await instance.save(); const uniqueEmailKeys = await keys( redis, prefix + ':uniques:UserMockup:emailOptional:', ); t.is(uniqueEmailKeys.length, 0, 'An empty unique was set'); }); test.serial('integer uniques', async (t) => { nohm.model('UniqueInteger', { properties: { unique: { type: 'integer', unique: true, }, }, }); const instance1 = await nohm.factory('UniqueInteger'); const instance2 = await nohm.factory('UniqueInteger'); instance1.property('unique', 123); instance2.property('unique', 123); await instance1.save(); t.deepEqual( instance1.allProperties(), { unique: 123, id: instance1.id, }, 'Properties not correct', ); try { await instance2.save(); } catch (err) { t.true( err instanceof nohm.ValidationError, 'Unique integer conflict did not result in error.', ); await instance1.remove(); await t.notThrowsAsync(async () => { await instance2.save(); }); } }); test.serial('uniqueDefaultOverwritten', async (t) => { const instance1 = new Model(); const instance2 = new Model(); await instance1.save(); try { await instance2.save(); t.fail('Saving succeeded where it should not have.'); } catch (err) { t.true( err instanceof nohm.ValidationError, 'Saving a default unique value did not return with the error "invalid"', ); t.deepEqual( instance2.errors.name, ['notUnique'], 'Saving a default unique value returned the wrong error: ' + instance2.errors.name, ); } }); test.serial('removing unique frees unique with uppercase values', async (t) => { const instance1 = new Model(); const instance2 = new Model(); const old = 'Removing Unique Property Frees The Value'; instance1.property('name', old); instance1.property('email', 'remove_frees@unique.de'); await instance1.save(); await instance1.remove(); instance2.property('name', old); await t.notThrowsAsync(async () => { return instance2.save(); }); }); test.serial( 'changing unique frees old unique with uppercase values', async (t) => { const obj = new Model(); const obj2 = new Model(); const obj3 = new Model(); const old = 'Changing Unique Property Frees The Value'; obj.property('name', old); obj.property('email', 'change_frees@unique.de'); await obj.save(); await obj2.load(obj.id); obj2.property( 'name', 'changing unique property frees the value to something else', ); await obj2.save(); await obj3.load(obj.id); obj2.property('name', old); try { obj2.save(); // test something, so we at least have the resemblance of normal testing here........ // the way it actually tests whether the uniques are freed is by not throwing errors during save t.is(obj2.id, obj3.id, 'Something went wrong'); } catch (err) { t.true( !err, 'Unexpected saving error. (May be because old uniques are not freed properly on change.', ); } }, );
the_stack
import { EventEmitter } from 'events' import { Connection, createConnection, DataAndMoneyStream } from 'ilp-protocol-stream' import IlpPluginBtp from 'ilp-plugin-btp' import { AdaptiveBandwidth, asyncUtils, getFarFutureExpiry, getSPSPResponse, PaymentDetails, SPSPError, SPSPResponse } from '@webmonetization/polyfill-utils' import { Container, inject, injectable } from 'inversify' import { BandwidthTiers } from '@coil/polyfill-utils' import { notNullOrUndef } from '../../util/nullables' import * as tokens from '../../types/tokens' import { BTP_ENDPOINT } from '../../webpackDefines' import { AnonymousTokens } from './AnonymousTokens' import { Logger, logger } from './utils' const { timeout } = asyncUtils const UPDATE_AMOUNT_TIMEOUT = 2000 let ATTEMPT = 0 // @sharafian explained to me that the extension popup shows source amounts, // while the web-monetization-scripts which use the monetizationprogress // event show received amounts. export interface StreamMoneyEvent { /** * Currently means packet number for a given StreamAttempt. * Could change. */ packetNumber: number // requestId requestId: string paymentPointer: string initiatingUrl: string msSinceLastPacket: number sentAmount: string // dest=received amount: string assetCode: string assetScale: number // source=source sourceAmount: string sourceAssetCode: string sourceAssetScale: number receipt?: string } type OnMoneyEvent = { sentAmount: string amount: number assetCode: string assetScale: number sourceAmount: string sourceAssetCode: string sourceAssetScale: number receipt?: string } @injectable() export class Stream extends EventEmitter { private readonly _requestId: string private readonly _spspUrl: string private readonly _paymentPointer: string private _authToken: string private readonly _server: string private readonly _tiers: BandwidthTiers private readonly _initiatingUrl: string private _lastDelivered: number private _lastOutgoingMs!: number private _packetNumber!: number private _active: boolean private _looping: boolean private _attempt: StreamAttempt | null private _coilDomain: string private _anonTokens: AnonymousTokens private _assetCode: string private _assetScale: number private _exchangeRate: number constructor( @logger('Stream') private readonly _debug: Logger, private container: Container, @inject(tokens.StreamDetails) { requestId, spspEndpoint, paymentPointer, token, initiatingUrl }: PaymentDetails & { token: string spspEndpoint: string initiatingUrl: string } ) { super() this._paymentPointer = paymentPointer this._requestId = requestId this._spspUrl = spspEndpoint this._authToken = token this._tiers = container.get(BandwidthTiers) this._coilDomain = container.get(tokens.CoilDomain) this._anonTokens = container.get(AnonymousTokens) this._assetCode = '' this._assetScale = 0 this._exchangeRate = 1 this._active = false this._looping = false this._attempt = null this._lastDelivered = 0 this._initiatingUrl = initiatingUrl const server = new URL(this._coilDomain) server.pathname = '/btp' this._server = server.href.replace(/^http/, 'btp+ws') if (BTP_ENDPOINT) { this._server = BTP_ENDPOINT } } async start() { if (this._active) return this._active = true // reset this upon every start *before* early exit while _looping this._packetNumber = 0 if (this._looping) return this._looping = true if (this._attempt) { void this._attempt.stop() this._attempt = null } // Hack for for issue #144 // Let pause() stream when tab is backgrounded have a chance to // to work to avoid wasted refreshBtpToken/SPSP queries await timeout(1) if (!this._active) { this._looping = false return } // reset our timer when we start streaming. const bandwidth = new AdaptiveBandwidth( this._initiatingUrl, this._tiers, this._debug ) while (this._active) { let btpToken: string | undefined let plugin, attempt try { btpToken = await this._anonTokens.getToken(this._authToken) plugin = await this._makePlugin(btpToken) const spspDetails = await this._getSPSPDetails() this.container .rebind(tokens.NoContextLoggerName) .toConstantValue(`StreamAttempt:${this._requestId}:${++ATTEMPT}`) attempt = this._attempt = new StreamAttempt({ bandwidth, onMoney: this.onMoney.bind(this), requestId: this._requestId, plugin, spspDetails, debug: this.container.get(tokens.Logger) }) if (this._active) { await attempt.start() await timeout(1000) } } catch (e) { const { ilpReject } = e if ( btpToken && ilpReject && ilpReject.message === 'exhausted capacity.' && ilpReject.data.equals(await sha256(Buffer.from(btpToken))) ) { this._debug('anonymous token exhausted; retrying, err=%s', e.message) this._anonTokens.removeToken(btpToken) continue } this._debug('error streaming. retry in 2s. err=', e.message, e.stack) if (this._active) await timeout(2000) } finally { if (attempt) bandwidth.addSentAmount(attempt.getTotalSent()) if (plugin) await plugin.disconnect() } } this._looping = false this._debug('aborted because stream is no longer active.') } async _makePlugin(btpToken: string) { // these are interspersed in order to not waste time if connection // is severed before full establishment if (!this._active) throw new Error('aborted monetization') const plugin = new IlpPluginBtp({ server: this._server, btpToken }) this._debug('connecting ilp plugin. server=', this._server) // createConnection(...) does this, so this is somewhat superfluous await plugin.connect() return plugin } async _getSPSPDetails(): Promise<SPSPResponse> { this._debug('fetching spsp details. url=', this._spspUrl) let details: SPSPResponse try { details = await getSPSPResponse(this._spspUrl, this._requestId) } catch (e) { if (e instanceof SPSPError) { const status = e.response?.status // Abort on Bad Request 4XX if (!status || (status >= 400 && status < 500)) { this.abort() } } throw e } if (!this._active) throw new Error('aborted monetization') return details } onMoney(data: OnMoneyEvent) { if (data.amount <= 0) return const now = Date.now() const msSinceLastPacket = now - this._lastOutgoingMs this._lastOutgoingMs = now const event: StreamMoneyEvent = Object.assign(data, { paymentPointer: this._paymentPointer, packetNumber: this._packetNumber++, requestId: this._requestId, initiatingUrl: this._initiatingUrl, msSinceLastPacket: msSinceLastPacket, amount: data.amount.toString(), receipt: data.receipt }) this._assetCode = data.assetCode this._assetScale = data.assetScale this._exchangeRate = (Number(data.amount) / Number(data.sourceAmount)) * (10 ** data.assetScale / 10 ** data.sourceAssetScale) this.emit('money', event) } async stop() { this._active = false if (this._attempt) { await this._attempt.stop() this._attempt = null } } async pause() { this.stop() } async resume() { this.start() } private async abort() { // Don't call this.stop() directly, let BackgroundScript orchestrate the // stop. this.emit('abort', this._requestId) } getPaymentPointer() { return this._paymentPointer } getAssetDetails() { return { assetCode: this._assetCode, assetScale: this._assetScale, exchangeRate: this._exchangeRate } } } interface StreamAttemptOptions { bandwidth: AdaptiveBandwidth onMoney: (event: OnMoneyEvent) => void requestId: string plugin: IlpPluginBtp spspDetails: SPSPResponse debug: Logger } class StreamAttempt { private readonly _onMoney: (event: OnMoneyEvent) => void private readonly _bandwidth: AdaptiveBandwidth // eslint-disable-next-line @typescript-eslint/no-explicit-any private readonly _debug: Logger private readonly _plugin: IlpPluginBtp private readonly _spspDetails: SPSPResponse private _ilpStream!: DataAndMoneyStream private _connection!: Connection private _active = true private _lastDelivered = 0 constructor(opts: StreamAttemptOptions) { this._onMoney = opts.onMoney this._bandwidth = opts.bandwidth this._plugin = opts.plugin this._spspDetails = opts.spspDetails this._debug = opts.debug } async start(): Promise<void> { if (!this._active) return const plugin = this._plugin this._debug('creating ilp/stream connection.') this._connection = await createConnection({ ...this._spspDetails, plugin, slippage: 1.0, exchangeRate: 1.0, maximumPacketAmount: '10000000', getExpiry: getFarFutureExpiry }) if (!this._active) return // send practically forever at allowed bandwidth this._debug('attempting to send on connection.') this._ilpStream = this._connection.createStream() // TODO: if we save the tier from earlier we don't need to do this async // TODO: does doing this async allow a race condition if we stop right away const initialSendAmount = await this._bandwidth.getStreamSendMax() this._ilpStream.setSendMax(initialSendAmount) return new Promise((resolve, reject) => { const onMoney = (sentAmount: string) => { // Wait until `setImmediate` so that `connection.totalDelivered` has been updated. const receipt = this._ilpStream.receipt ? this._ilpStream.receipt.toString('base64') : undefined setImmediate(this.onMoney.bind(this), sentAmount, receipt) } const onPluginDisconnect = async () => { this._debug('onPluginDisconnect()') cleanUp() this._debug( 'this._ilpStream.isOpen()', this._ilpStream.isOpen(), "this._connection['closed']", this._connection['closed'], 'this._plugin.isConnected()', this._plugin.isConnected() ) if (this._ilpStream.isOpen()) { this._ilpStream.destroy() } if (!this._connection['closed']) { this._debug('waiting connection destroy') await this._connection.destroy() this._debug('connection destroyed') } if (plugin.isConnected()) { this._debug('waiting plugin disconnect') await plugin.disconnect() this._debug('plugin disconnected') } // resolve instead of reject to avoid delay this._debug('resolving') resolve() } const onConnectionError = (err: Error) => { this._debug('onConnectionError(%s)', err) cleanUp() reject(err) } const onUpdateAmountTimeout = async () => { // we set this before the async operation to prevent any race // conditions on cleanup // eslint-disable-next-line @typescript-eslint/no-use-before-define updateAmountTimeout = setTimeout( onUpdateAmountTimeout, UPDATE_AMOUNT_TIMEOUT ) if (this._ilpStream.isOpen()) { const sendAmount = await this._bandwidth.getStreamSendMax() this._ilpStream.setSendMax(sendAmount) } } const cleanUp = () => { this._debug('cleanup()') this._ilpStream.removeListener('outgoing_money', onMoney) this._connection.removeListener('error', onConnectionError) plugin.removeListener('disconnect', onPluginDisconnect) // eslint-disable-next-line @typescript-eslint/no-use-before-define clearTimeout(updateAmountTimeout) } plugin.once('disconnect', onPluginDisconnect) this._ilpStream.on('outgoing_money', onMoney) this._connection.once('error', onConnectionError) let updateAmountTimeout = setTimeout( onUpdateAmountTimeout, UPDATE_AMOUNT_TIMEOUT ) }) } async stop(): Promise<void> { this._active = false if (!this._connection) return this._debug('initiating stream shutdown') if (this._ilpStream.isOpen()) { // Stop it sending any more than is already sent this._ilpStream.setSendMax(this._ilpStream.totalSent) } await this.waitHoldsUptoMs(2e3) await new Promise(resolve => { this._debug('severing ilp/stream connection.') this._ilpStream.once('close', resolve) this._ilpStream.destroy() }) this._debug( 'stream close event fired; plugin connected=', this._plugin.isConnected() ) await this._connection.end() this._debug('connection destroyed') // stream createConnection() automatically closes the plugin as of // time of writing: https://github.com/interledgerjs/ilp-protocol-stream/blob/9b49b1cad11d4b7a71fb31a8da61c729fbba7d9a/src/index.ts#L69-L71 if (this._plugin.isConnected()) { this._debug('disconnecting plugin') await this._plugin.disconnect() this._debug('plugin disconnected') } } getTotalSent(): string { return this._ilpStream ? this._ilpStream.totalSent : '0' } private onMoney(sentAmount: string, receipt?: string): void { const delivered = Number(this._connection.totalDelivered) const amount = delivered - this._lastDelivered this._debug('delivered', delivered, 'lastDelivered', this._lastDelivered) this._lastDelivered = delivered this._onMoney({ sentAmount, // dest=received amount, assetCode: notNullOrUndef(this._connection.destinationAssetCode), assetScale: notNullOrUndef(this._connection.destinationAssetScale), receipt, // source=source sourceAmount: sentAmount, sourceAssetCode: this._connection.sourceAssetCode, sourceAssetScale: this._connection.sourceAssetScale }) } private async waitHoldsUptoMs(totalMs: number): Promise<void> { while (totalMs > 0) { const holds = Object.keys(this._ilpStream['holds']).length this._debug({ holds: holds }) if (holds === 0) { break } else { await timeout(100) totalMs -= 100 } } } } async function sha256(preimage: Buffer): Promise<Buffer> { const digest = await crypto.subtle.digest({ name: 'SHA-256' }, preimage) return Buffer.from(digest) }
the_stack
"use strict"; import { assert } from "chai"; import { Strings } from "../../../src/helpers/strings"; import { TfvcError, TfvcErrorCodes } from "../../../src/tfvc/tfvcerror"; import { FindWorkspace } from "../../../src/tfvc/commands/findworkspace"; import { IExecutionResult, IWorkspace } from "../../../src/tfvc/interfaces"; describe("Tfvc-FindWorkspaceCommand", function() { beforeEach(function() { // }); it("should verify constructor", function() { const localPath: string = "/path/to/workspace"; new FindWorkspace(localPath); }); it("should verify constructor - undefined args", function() { assert.throws(() => new FindWorkspace(undefined), TfvcError, /Argument is required/); }); it("should verify GetOptions", function() { const localPath: string = "/path/to/workspace"; const cmd: FindWorkspace = new FindWorkspace(localPath); assert.deepEqual(cmd.GetOptions(), { cwd: "/path/to/workspace" }); }); it("should verify GetExeOptions", function() { const localPath: string = "/path/to/workspace"; const cmd: FindWorkspace = new FindWorkspace(localPath); assert.deepEqual(cmd.GetExeOptions(), { cwd: "/path/to/workspace" }); }); it("should verify arguments", function() { const localPath: string = "/path/to/workspace"; const cmd: FindWorkspace = new FindWorkspace(localPath); assert.equal(cmd.GetArguments().GetArgumentsForDisplay(), "workfold -noprompt ********"); }); it("should verify GetExeArguments", function() { const localPath: string = "/path/to/workspace"; const cmd: FindWorkspace = new FindWorkspace(localPath); assert.equal(cmd.GetExeArguments().GetArgumentsForDisplay(), "workfold -noprompt ********"); }); it("should verify working folder", function() { const localPath: string = "/path/to/workspace"; const cmd: FindWorkspace = new FindWorkspace(localPath); assert.equal(cmd.GetOptions().cwd, localPath); }); it("should verify EXE working folder", function() { const localPath: string = "/path/to/workspace"; const cmd: FindWorkspace = new FindWorkspace(localPath); assert.equal(cmd.GetExeOptions().cwd, localPath); }); it("should verify parse output - no output", async function() { const localPath: string = "/path/to/workspace"; const cmd: FindWorkspace = new FindWorkspace(localPath); const executionResult: IExecutionResult = { exitCode: 0, stdout: undefined, stderr: undefined }; const workspace: IWorkspace = await cmd.ParseOutput(executionResult); assert.equal(workspace, undefined); }); it("should verify parse output - no errors", async function() { const localPath: string = "/path/to/workspace"; const cmd: FindWorkspace = new FindWorkspace(localPath); const executionResult: IExecutionResult = { exitCode: 0, stdout: "=====================================================================================================================================================\n" + "Workspace: MyWorkspace\n" + "Collection: http://server:8080/tfs/\n" + "$/project1: /path", stderr: undefined }; const workspace: IWorkspace = await cmd.ParseOutput(executionResult); assert.equal(workspace.name, "MyWorkspace"); assert.equal(workspace.server, "http://server:8080/tfs/"); assert.equal(workspace.defaultTeamProject, "project1"); assert.equal(workspace.comment, undefined); assert.equal(workspace.computer, undefined); assert.equal(workspace.owner, undefined); assert.equal(workspace.mappings.length, 1); assert.isFalse(workspace.mappings[0].cloaked); assert.equal(workspace.mappings[0].localPath, `/path`); assert.equal(workspace.mappings[0].serverPath, `$/project1`); }); it("should verify parse output - no errors - cloaked folders - entire project cloaked", async function() { const localPath: string = "/path/to/workspace"; const cmd: FindWorkspace = new FindWorkspace(localPath); const executionResult: IExecutionResult = { exitCode: 0, stdout: "=====================================================================================================================================================\n" + "Workspace: MyWorkspace\n" + "Collection: http://server:8080/tfs/\n" + "$/project1: /path\n" + " (cloaked) $/project2\n" + "$/project3: /path3", stderr: undefined }; const workspace: IWorkspace = await cmd.ParseOutput(executionResult); assert.equal(workspace.name, "MyWorkspace"); assert.equal(workspace.server, "http://server:8080/tfs/"); assert.equal(workspace.defaultTeamProject, "project1"); assert.equal(workspace.comment, undefined); assert.equal(workspace.computer, undefined); assert.equal(workspace.owner, undefined); assert.equal(workspace.mappings.length, 3); assert.isTrue(workspace.mappings[1].cloaked); assert.isUndefined(workspace.mappings[1].localPath); assert.equal(workspace.mappings[1].serverPath, `$/project2`); }); it("should verify parse output - no errors - cloaked folders - middle project sub-folder cloaked", async function() { const localPath: string = "/path/to/workspace"; const cmd: FindWorkspace = new FindWorkspace(localPath); const executionResult: IExecutionResult = { exitCode: 0, stdout: "=====================================================================================================================================================\n" + "Workspace: MyWorkspace\n" + "Collection: http://server:8080/tfs/\n" + "$/project1: /path\n" + "$/project2: /path2\n" + " (cloaked) $/project2/main:\n" + "$/project3: /path3", stderr: undefined }; const workspace: IWorkspace = await cmd.ParseOutput(executionResult); assert.equal(workspace.name, "MyWorkspace"); assert.equal(workspace.server, "http://server:8080/tfs/"); assert.equal(workspace.defaultTeamProject, "project1"); assert.equal(workspace.comment, undefined); assert.equal(workspace.computer, undefined); assert.equal(workspace.owner, undefined); assert.equal(workspace.mappings.length, 4); assert.isTrue(workspace.mappings[2].cloaked); assert.isUndefined(workspace.mappings[2].localPath); assert.equal(workspace.mappings[2].serverPath, `$/project2/main`); }); it("should verify parse output - no errors - cloaked folders - last project sub-folder cloaked", async function() { const localPath: string = "/path/to/workspace"; const cmd: FindWorkspace = new FindWorkspace(localPath); const executionResult: IExecutionResult = { exitCode: 0, stdout: "=====================================================================================================================================================\n" + "Workspace: MyWorkspace\n" + "Collection: http://server:8080/tfs/\n" + "$/project1: /path\n" + "$/project2: /path2\n" + "$/project3: /path3\n" + "$/project4: /path4\n" + " (cloaked) $/project4/main:", stderr: undefined }; const workspace: IWorkspace = await cmd.ParseOutput(executionResult); assert.equal(workspace.name, "MyWorkspace"); assert.equal(workspace.server, "http://server:8080/tfs/"); assert.equal(workspace.defaultTeamProject, "project1"); assert.equal(workspace.comment, undefined); assert.equal(workspace.computer, undefined); assert.equal(workspace.owner, undefined); assert.equal(workspace.mappings.length, 5); assert.isTrue(workspace.mappings[4].cloaked); assert.isUndefined(workspace.mappings[4].localPath); assert.equal(workspace.mappings[4].serverPath, `$/project4/main`); }); it("should verify parse output - German - no 'workspace' and 'collection'", async function() { const localPath: string = "/path/to/workspace"; const cmd: FindWorkspace = new FindWorkspace(localPath); const executionResult: IExecutionResult = { exitCode: 0, stdout: "=====================================================================================================================================================\n" + "Arbeitsbereich: DESKTOP-KI56MCL (Jeff Young (TFS))\n" + "Sammlung : http://java-tfs2015:8081/tfs/defaultcollection\n" + "$/project1: /path", stderr: undefined }; try { await cmd.ParseOutput(executionResult); } catch (err) { assert.isTrue(err.message.startsWith(Strings.NotAnEnuTfCommandLine)); assert.equal(err.tfvcErrorCode, TfvcErrorCodes.NotAnEnuTfCommandLine); } }); it("should verify parse output - not a tf workspace", async function() { const localPath: string = "/path/to/workspace"; const cmd: FindWorkspace = new FindWorkspace(localPath); const executionResult: IExecutionResult = { exitCode: 0, stdout: undefined, stderr: "An argument error occurred: The workspace could not be determined from any argument paths or the current working directory." }; try { await cmd.ParseOutput(executionResult); } catch (err) { assert.isTrue(err.message.startsWith(Strings.NoWorkspaceMappings)); assert.equal(err.tfvcErrorCode, TfvcErrorCodes.NotATfvcRepository); } }); it("should verify parse output - no mappings error", async function() { const localPath: string = "/path/to/workspace"; const cmd: FindWorkspace = new FindWorkspace(localPath); const executionResult: IExecutionResult = { exitCode: 0, stdout: "=====================================================================================================================================================\n" + "Workspace: MyWorkspace\n" + "Collection: http://server:8080/tfs/\n", stderr: undefined }; try { await cmd.ParseOutput(executionResult); } catch (err) { assert.isTrue(err.message.startsWith(Strings.NoWorkspaceMappings)); assert.equal(err.tfvcErrorCode, TfvcErrorCodes.NotATfvcRepository); } }); it("should verify parse output - no errors - restrictWorkspace", async function() { const localPath: string = "/path2/to/workspace/project2"; const cmd: FindWorkspace = new FindWorkspace(localPath, true); const executionResult: IExecutionResult = { exitCode: 0, stdout: "=====================================================================================================================================================\n" + "Workspace: MyWorkspace\n" + "Collection: http://server:8080/tfs/\n" + "$/project1: /path\n" + "$/project2: /path2", stderr: undefined }; const workspace: IWorkspace = await cmd.ParseOutput(executionResult); assert.equal(workspace.name, "MyWorkspace"); assert.equal(workspace.server, "http://server:8080/tfs/"); //This test should find project2 as the team project since the localPath contains project2 and we have restrictWorkspace assert.equal(workspace.defaultTeamProject, "project2"); assert.equal(workspace.comment, undefined); assert.equal(workspace.computer, undefined); assert.equal(workspace.owner, undefined); assert.equal(workspace.mappings.length, 2); }); //The CLC will always return *all* server mappings in the workspace even if you pass a particular local folder //TF.exe will only return the server mappings in the workspace that apply to the particular local folder it("should verify parse output - no errors - restrictWorkspace - sub-folder", async function() { const localPath: string = "/path2/to/workspace/project2/sub-folder"; const cmd: FindWorkspace = new FindWorkspace(localPath, true); const executionResult: IExecutionResult = { exitCode: 0, stdout: "=====================================================================================================================================================\n" + "Workspace: MyWorkspace\n" + "Collection: http://server:8080/tfs/\n" + "$/project1: /path\n" + "$/project2: /path2", stderr: undefined }; const workspace: IWorkspace = await cmd.ParseOutput(executionResult); assert.equal(workspace.name, "MyWorkspace"); assert.equal(workspace.server, "http://server:8080/tfs/"); //This test should find project2 as the team project since the localPath contains project2 and we have restrictWorkspace assert.equal(workspace.defaultTeamProject, "project2"); assert.equal(workspace.comment, undefined); assert.equal(workspace.computer, undefined); assert.equal(workspace.owner, undefined); assert.equal(workspace.mappings.length, 2); }); it("should verify parse output - no errors - restrictWorkspace - sub-folder - Windows path", async function() { const localPath: string = "c:\\path2\\to\\workspace\\project2\\sub-folder\\"; const cmd: FindWorkspace = new FindWorkspace(localPath, true); const executionResult: IExecutionResult = { exitCode: 0, stdout: "=====================================================================================================================================================\n" + "Workspace: MyWorkspace\n" + "Collection: http://server:8080/tfs/\n" + "$/project1: c:\\path\n" + "$/project2: c:\\path2", stderr: undefined }; const workspace: IWorkspace = await cmd.ParseOutput(executionResult); assert.equal(workspace.name, "MyWorkspace"); assert.equal(workspace.server, "http://server:8080/tfs/"); //This test should find project2 as the team project since the localPath contains project2 and we have restrictWorkspace assert.equal(workspace.defaultTeamProject, "project2"); assert.equal(workspace.comment, undefined); assert.equal(workspace.computer, undefined); assert.equal(workspace.owner, undefined); assert.equal(workspace.mappings.length, 2); }); it("should verify parse output - no errors - encoded output", async function() { const localPath: string = "/path/to/workspace/project1"; const cmd: FindWorkspace = new FindWorkspace(localPath, true); const executionResult: IExecutionResult = { exitCode: 0, stdout: "=====================================================================================================================================================\n" + "Workspace: MyWorkspace\n" + "Collection: http://server:8080/tfs/spaces%20in%20the%20name/\n" + "$/project1: /path", stderr: undefined }; const workspace: IWorkspace = await cmd.ParseOutput(executionResult); assert.equal(workspace.name, "MyWorkspace"); assert.equal(workspace.server, "http://server:8080/tfs/spaces in the name/"); assert.equal(workspace.defaultTeamProject, "project1"); assert.equal(workspace.comment, undefined); assert.equal(workspace.computer, undefined); assert.equal(workspace.owner, undefined); assert.equal(workspace.mappings.length, 1); }); /*********************************************************************************************** * The methods below are duplicates of the parse output methods but call the parseExeOutput. ***********************************************************************************************/ it("should verify parse EXE output - no output", async function() { const localPath: string = "/path/to/workspace"; const cmd: FindWorkspace = new FindWorkspace(localPath); const executionResult: IExecutionResult = { exitCode: 0, stdout: undefined, stderr: undefined }; const workspace: IWorkspace = await cmd.ParseExeOutput(executionResult); assert.equal(workspace, undefined); }); it("should verify parse EXE output - no errors", async function() { const localPath: string = "/path/to/workspace"; const cmd: FindWorkspace = new FindWorkspace(localPath); const executionResult: IExecutionResult = { exitCode: 0, stdout: "=============================================================================\n" + "Workspace : MyWorkspace (Jason Prickett)\n" + "Collection: http://server:8080/tfs/\n" + " $/project1/subfolder: /path\n", stderr: undefined }; const workspace: IWorkspace = await cmd.ParseExeOutput(executionResult); assert.equal(workspace.name, "MyWorkspace"); assert.equal(workspace.server, "http://server:8080/tfs/"); assert.equal(workspace.defaultTeamProject, "project1"); assert.equal(workspace.comment, undefined); assert.equal(workspace.computer, undefined); assert.equal(workspace.owner, undefined); assert.equal(workspace.mappings.length, 1); }); it("should verify parse EXE output - no errors - cloaked folders - entire project cloaked", async function() { const localPath: string = "/path/to/workspace"; const cmd: FindWorkspace = new FindWorkspace(localPath); const executionResult: IExecutionResult = { exitCode: 0, stdout: "=====================================================================================================================================================\n" + "Workspace: MyWorkspace\n" + "Collection: http://server:8080/tfs/\n" + "$/project1: /path\n" + " (cloaked) $/project2\n" + "$/project3: /path3", stderr: undefined }; const workspace: IWorkspace = await cmd.ParseExeOutput(executionResult); assert.equal(workspace.name, "MyWorkspace"); assert.equal(workspace.server, "http://server:8080/tfs/"); assert.equal(workspace.defaultTeamProject, "project1"); assert.equal(workspace.comment, undefined); assert.equal(workspace.computer, undefined); assert.equal(workspace.owner, undefined); assert.equal(workspace.mappings.length, 3); assert.isTrue(workspace.mappings[1].cloaked); assert.isUndefined(workspace.mappings[1].localPath); assert.equal(workspace.mappings[1].serverPath, `$/project2`); }); it("should verify parse EXE output - no errors - cloaked folders - middle project sub-folder cloaked", async function() { const localPath: string = "/path/to/workspace"; const cmd: FindWorkspace = new FindWorkspace(localPath); const executionResult: IExecutionResult = { exitCode: 0, stdout: "=====================================================================================================================================================\n" + "Workspace: MyWorkspace\n" + "Collection: http://server:8080/tfs/\n" + "$/project1: /path\n" + "$/project2: /path2\n" + " (cloaked) $/project2/main:\n" + "$/project3: /path3", stderr: undefined }; const workspace: IWorkspace = await cmd.ParseExeOutput(executionResult); assert.equal(workspace.name, "MyWorkspace"); assert.equal(workspace.server, "http://server:8080/tfs/"); assert.equal(workspace.defaultTeamProject, "project1"); assert.equal(workspace.comment, undefined); assert.equal(workspace.computer, undefined); assert.equal(workspace.owner, undefined); assert.equal(workspace.mappings.length, 4); assert.isTrue(workspace.mappings[2].cloaked); assert.isUndefined(workspace.mappings[2].localPath); assert.equal(workspace.mappings[2].serverPath, `$/project2/main`); }); it("should verify parse EXE output - no errors - cloaked folders - last project sub-folder cloaked", async function() { const localPath: string = "/path/to/workspace"; const cmd: FindWorkspace = new FindWorkspace(localPath); const executionResult: IExecutionResult = { exitCode: 0, stdout: "=====================================================================================================================================================\n" + "Workspace: MyWorkspace\n" + "Collection: http://server:8080/tfs/\n" + "$/project1: /path\n" + "$/project2: /path2\n" + "$/project3: /path3\n" + "$/project4: /path4\n" + " (cloaked) $/project4/main:", stderr: undefined }; const workspace: IWorkspace = await cmd.ParseExeOutput(executionResult); assert.equal(workspace.name, "MyWorkspace"); assert.equal(workspace.server, "http://server:8080/tfs/"); assert.equal(workspace.defaultTeamProject, "project1"); assert.equal(workspace.comment, undefined); assert.equal(workspace.computer, undefined); assert.equal(workspace.owner, undefined); assert.equal(workspace.mappings.length, 5); assert.isTrue(workspace.mappings[4].cloaked); assert.isUndefined(workspace.mappings[4].localPath); assert.equal(workspace.mappings[4].serverPath, `$/project4/main`); }); it("should verify parse EXE output - German - no 'workspace' and 'collection'", async function() { const localPath: string = "/path/to/workspace"; const cmd: FindWorkspace = new FindWorkspace(localPath); const executionResult: IExecutionResult = { exitCode: 0, stdout: "=====================================================================================================================================================\n" + "Arbeitsbereich: DESKTOP-KI56MCL (Jeff Young (TFS))\n" + "Sammlung : http://java-tfs2015:8081/tfs/defaultcollection\n" + "$/project1: /path", stderr: undefined }; try { await cmd.ParseExeOutput(executionResult); } catch (err) { assert.isTrue(err.message.startsWith(Strings.NotAnEnuTfCommandLine)); assert.equal(err.tfvcErrorCode, TfvcErrorCodes.NotAnEnuTfCommandLine); } }); it("should verify parse EXE output - not a tf workspace", async function() { const localPath: string = "/path/to/workspace"; const cmd: FindWorkspace = new FindWorkspace(localPath); const executionResult: IExecutionResult = { exitCode: 0, stdout: undefined, stderr: "Unable to determine the source control server." }; try { await cmd.ParseExeOutput(executionResult); } catch (err) { assert.isTrue(err.message.startsWith(Strings.NoWorkspaceMappings)); assert.equal(err.tfvcErrorCode, TfvcErrorCodes.NotATfvcRepository); } }); it("should verify parse EXE output - no mappings error", async function() { const localPath: string = "/path/to/workspace"; const cmd: FindWorkspace = new FindWorkspace(localPath); const executionResult: IExecutionResult = { exitCode: 0, stdout: "=============================================================================\n" + "Workspace : MyWorkspace (Jason Prickett)\n" + "Collection: http://server:8080/tfs/\n", stderr: undefined }; try { await cmd.ParseExeOutput(executionResult); } catch (err) { assert.isTrue(err.message.startsWith(Strings.NoWorkspaceMappings)); assert.equal(err.tfvcErrorCode, TfvcErrorCodes.NotATfvcRepository); } }); it("should verify parse EXE output - no errors - restrictWorkspace", async function() { const localPath: string = "/path2/to/workspace/project2"; const cmd: FindWorkspace = new FindWorkspace(localPath, true); const executionResult: IExecutionResult = { exitCode: 0, stdout: "=====================================================================================================================================================\n" + "Workspace: MyWorkspace\n" + "Collection: http://server:8080/tfs/\n" + "$/project1: /path\n" + "$/project2: /path2", stderr: undefined }; const workspace: IWorkspace = await cmd.ParseExeOutput(executionResult); assert.equal(workspace.name, "MyWorkspace"); assert.equal(workspace.server, "http://server:8080/tfs/"); //This test should find project2 as the team project since the localPath contains project2 and we have restrictWorkspace assert.equal(workspace.defaultTeamProject, "project2"); assert.equal(workspace.comment, undefined); assert.equal(workspace.computer, undefined); assert.equal(workspace.owner, undefined); assert.equal(workspace.mappings.length, 2); }); it("should verify parse EXE output - no errors - restrictWorkspace - sub-folder", async function() { const localPath: string = "/path2/to/workspace/project2/sub-folder"; const cmd: FindWorkspace = new FindWorkspace(localPath, true); //TF.exe won't return "$/project1: /path1" if it's in the overall workspace (see the CLC test of the same scenario, above) const executionResult: IExecutionResult = { exitCode: 0, stdout: "=====================================================================================================================================================\n" + "Workspace: MyWorkspace\n" + "Collection: http://server:8080/tfs/\n" + "$/project2: /path2", stderr: undefined }; const workspace: IWorkspace = await cmd.ParseExeOutput(executionResult); assert.equal(workspace.name, "MyWorkspace"); assert.equal(workspace.server, "http://server:8080/tfs/"); //This test should find project2 as the team project since the localPath contains project2 and we have restrictWorkspace assert.equal(workspace.defaultTeamProject, "project2"); assert.equal(workspace.comment, undefined); assert.equal(workspace.computer, undefined); assert.equal(workspace.owner, undefined); assert.equal(workspace.mappings.length, 1); }); it("should verify parse EXE output - no errors - restrictWorkspace - sub-folder - Windows path", async function() { const localPath: string = "c:\\path2\\to\\workspace\\project2\\sub-folder\\"; const cmd: FindWorkspace = new FindWorkspace(localPath, true); //TF.exe won't return "$/project1: c:\\path1" if it's in the overall workspace (see the CLC test of the same scenario, earlier) const executionResult: IExecutionResult = { exitCode: 0, stdout: "=====================================================================================================================================================\n" + "Workspace: MyWorkspace\n" + "Collection: http://server:8080/tfs/\n" + "$/project2: c:\\path2", stderr: undefined }; const workspace: IWorkspace = await cmd.ParseExeOutput(executionResult); assert.equal(workspace.name, "MyWorkspace"); assert.equal(workspace.server, "http://server:8080/tfs/"); //This test should find project2 as the team project since the localPath contains project2 and we have restrictWorkspace assert.equal(workspace.defaultTeamProject, "project2"); assert.equal(workspace.comment, undefined); assert.equal(workspace.computer, undefined); assert.equal(workspace.owner, undefined); assert.equal(workspace.mappings.length, 1); }); it("should verify parse EXE output - no errors - encoded output", async function() { const localPath: string = "/path/to/workspace/project1"; const cmd: FindWorkspace = new FindWorkspace(localPath, true); const executionResult: IExecutionResult = { exitCode: 0, stdout: "=====================================================================================================================================================\n" + "Workspace: MyWorkspace\n" + "Collection: http://server:8080/tfs/spaces%20in%20the%20name/\n" + "$/project1: /path", stderr: undefined }; const workspace: IWorkspace = await cmd.ParseExeOutput(executionResult); assert.equal(workspace.name, "MyWorkspace"); assert.equal(workspace.server, "http://server:8080/tfs/spaces in the name/"); assert.equal(workspace.defaultTeamProject, "project1"); assert.equal(workspace.comment, undefined); assert.equal(workspace.computer, undefined); assert.equal(workspace.owner, undefined); assert.equal(workspace.mappings.length, 1); }); });
the_stack
import Game from '../Core/Game'; import Hilo3d from '../Core/Hilo3d'; import SceneActor, {isSceneActor} from '../Renderer/SceneActor'; import SceneComponent from '../Renderer/SceneComponent'; import SkeletalMeshActor from '../Renderer/SkeletalMeshActor'; import StaticMeshActor from '../Renderer/StaticMeshActor'; import OrthographicCameraActor from '../Camera/OrthographicCameraActor'; import PerspectiveCameraActor from '../Camera/PerspectiveCameraActor'; import AmbientLightActor from '../Light/AmbientLightActor'; import DirectionalLightActor from '../Light/DirectionalLightActor'; import PointLightActor from '../Light/PointLightActor'; import SpotLightActor from '../Light/SpotLightActor'; import SkeletalMeshComponent from '../Renderer/SkeletalMeshComponent'; import StaticMeshComponent from '../Renderer/StaticMeshComponent'; import OrthographicCameraComponent from '../Camera/OrthographicCameraComponent'; import PerspectiveCameraComponent from '../Camera/PerspectiveCameraComponent'; import AmbientLightComponent from '../Light/AmbientLightComponent'; import DirectionalLightComponent from '../Light/DirectionalLightComponent'; import PointLightComponent from '../Light/PointLightComponent'; import SpotLightComponent from '../Light/SpotLightComponent'; import {ESeinNodeType, INodeWithGlTFExtensions, ISeinNodeExtension, IGlTFModel} from '../types/Resource'; import AnimatorComponent from '../Animation/AnimatorComponent'; import World from '../Core/World'; import SArray from '../DataStructure/SArray'; import {MetaSClasses} from '../Core/MetaTypes'; import BSPMorphComponent from '../BSP/BSPMorphComponent'; import BSPMorphActor from '../BSP/BSPMorphActor'; import Debug from '../Debug'; import {FakeHiloSprite} from '../Resource/GlTFExtensions'; import SpriteActor from '../Renderer/SpriteActor'; import SpriteComponent from '../Renderer/SpriteComponent'; /* tslint:disable */ /** * @hidden */ function generateActorOrComponentFromNode( node: INodeWithGlTFExtensions, parentActor: SceneActor, parent: SceneComponent, isComponent: boolean, resource: IGlTFModel, world: World ): SceneActor { const child = node.children[0] as (Hilo3d.Node | Hilo3d.Mesh | Hilo3d.SkinedMesh | Hilo3d.OrthographicCamera | Hilo3d.PerspectiveCamera | Hilo3d.AmbientLight | Hilo3d.DirectionalLight | Hilo3d.PointLight | Hilo3d.SpotLight ); let result = null; let root = null; let Class; let initOptions: any = {__fromGlTF: true, matrix: node.matrix}; if (node.gltfExtensions.Sein_node && node.gltfExtensions.Sein_node.className) { const className = node.gltfExtensions.Sein_node.className; Class = MetaSClasses[className]; if (!Class) { Debug.warn(`No class named '${className}', no effect, you must use decorator 'SClass' to annotate your class before use it !`); } else { Object.assign(initOptions, node.gltfExtensions.Sein_node.initOptions || {}); } } if (!child) { if (isComponent) { root = result = parentActor.addComponent(node.name, Class || SceneComponent, initOptions, parent); } else { root = (result = world.addActor(node.name, Class || SceneActor, initOptions, parentActor, parent)).root; } } else if ((child as Hilo3d.SkinedMesh).isSkinedMesh) { let length = node.children.length; const meshes = []; for (let index = 0; index < length; index += 1) { const mesh = node.children[index] as Hilo3d.SkinedMesh; if (!(mesh as any).isSkinedMesh) { break; } meshes.push(mesh); (node as any).childrenOffset += 1; } length = meshes.length; const {geometry, material} = child as Hilo3d.SkinedMesh; Object.assign(initOptions, {__doNotUseMultiPrimitiveYourself: meshes, geometry, material}); if (isComponent) { root = result = parentActor.addComponent(node.name, Class || SkeletalMeshComponent, initOptions, parent); (parentActor as any).skeletalMeshComponents.push([root, meshes]); } else { root = (result = world.addActor(node.name, Class || SkeletalMeshActor, initOptions, parentActor, parent)).root; root.getOwner().skeletalMeshComponents = [[root, meshes]]; } } else if ((child as Hilo3d.Mesh).isMesh) { let length = node.children.length; const meshes = []; for (let index = 0; index < length; index += 1) { const mesh = node.children[index] as Hilo3d.Mesh; if (!(mesh as any).isMesh) { break; } meshes.push(mesh); (node as any).childrenOffset += 1; } length = meshes.length; const {geometry, material} = child as Hilo3d.Mesh; Object.assign(initOptions, {__doNotUseMultiPrimitiveYourself: meshes, geometry, material}); if ((geometry as Hilo3d.MorphGeometry).isMorphGeometry) { if (isComponent) { root = result = parentActor.addComponent(node.name, Class || BSPMorphComponent, initOptions, parent); } else { root = (result = world.addActor(node.name, Class || BSPMorphActor, initOptions, parentActor, parent)).root; } } else { if (isComponent) { root = result = parentActor.addComponent(node.name, Class || StaticMeshComponent, initOptions, parent); } else { root = (result = world.addActor(node.name, Class || StaticMeshActor, initOptions, parentActor, parent)).root; } } } else if ((child as FakeHiloSprite).isFakeHiloSprite) { const {width, height, isBillboard, frustumTest, atlas} = (child as FakeHiloSprite).sprite; const {material} = (child as FakeHiloSprite); const {frameName, index} = atlas; const atlasManager = resource['atlases'][index]; Object.assign(initOptions, {width, height, isBillboard, frustumTest, frameName, atlas: atlasManager, material, materialOptions: {alphaMode: 'BLEND'}}); if (isComponent) { root = result = parentActor.addComponent(node.name, Class || SpriteComponent, initOptions, parent); } else { root = (result = world.addActor(node.name, Class || SpriteActor, initOptions, parentActor, parent)).root; } (node as any).childrenOffset += 1; } else if ((child as Hilo3d.OrthographicCamera).isOrthographicCamera) { const {far, near, left, right, top, bottom, backgroundMat} = child as any; Object.assign(initOptions, {far, near, left, right, top, bottom, backgroundMat}); if (isComponent) { root = result = parentActor.addComponent(node.name, Class || OrthographicCameraComponent, initOptions, parent); } else { root = (result = world.addActor(node.name, Class || OrthographicCameraActor, initOptions, parentActor, parent)).root; } (node as any).childrenOffset += 1; } else if ((child as Hilo3d.PerspectiveCamera).isPerspectiveCamera) { const {far, near, fov, aspect, backgroundMat} = child as any; Object.assign(initOptions, {far, near, fov, aspect, backgroundMat}); if (isComponent) { root = result = parentActor.addComponent(node.name, Class || PerspectiveCameraComponent, initOptions, parent); } else { root = (result = world.addActor(node.name, Class || PerspectiveCameraActor, initOptions, parentActor, parent)).root; } (node as any).childrenOffset += 1; } else if ((child as Hilo3d.AmbientLight).isAmbientLight) { const {amount, color, shadow} = child as Hilo3d.AmbientLight; Object.assign(initOptions, {amount, color, shadow}); if (isComponent) { root = result = parentActor.addComponent(node.name, Class || AmbientLightComponent, initOptions, parent); } else { root = (result = world.addActor(node.name, Class || AmbientLightActor, initOptions, parentActor, parent)).root; } (node as any).childrenOffset += 1; } else if ((child as Hilo3d.DirectionalLight).isDirectionalLight) { const {amount, color, shadow, direction} = child as Hilo3d.DirectionalLight; Object.assign(initOptions, {amount, color, shadow, direction}); if (isComponent) { root = result = parentActor.addComponent(node.name, Class || DirectionalLightComponent, initOptions, parent); } else { root = (result = world.addActor(node.name, Class || DirectionalLightActor, initOptions, parentActor, parent)).root; } (node as any).childrenOffset += 1; } else if ((child as Hilo3d.PointLight).isPointLight) { const {amount, color, shadow, range, constantAttenuation, linearAttenuation, quadraticAttenuation} = child as Hilo3d.PointLight; Object.assign(initOptions, {amount, color, shadow, range, constantAttenuation, linearAttenuation, quadraticAttenuation}); if (isComponent) { root = result = parentActor.addComponent(node.name, Class || PointLightComponent, initOptions, parent); } else { root = (result = world.addActor(node.name, Class || PointLightActor, initOptions, parentActor, parent)).root; } (node as any).childrenOffset += 1; } else if ((child as Hilo3d.SpotLight).isSpotLight) { const {amount, color, shadow, range, constantAttenuation, linearAttenuation, quadraticAttenuation, cutoff, outerCutoff, direction} = child as Hilo3d.SpotLight; Object.assign(initOptions, {amount, color, shadow, range, constantAttenuation, linearAttenuation, quadraticAttenuation, cutoff, outerCutoff, direction}); if (isComponent) { root = result = parentActor.addComponent(node.name, Class || SpotLightComponent, initOptions, parent); } else { root = (result = world.addActor(node.name, Class || SpotLightActor, initOptions, parentActor, parent)).root; } (node as any).childrenOffset += 1; } else { if (isComponent) { root = result = parentActor.addComponent(node.name, Class || SceneComponent, initOptions, parent); } else { root = (result = world.addActor(node.name, Class || SceneActor, initOptions, parentActor, parent)).root; } } root.cloneFromHiloNode(node as Hilo3d.Node); root.needReleaseGlRes = false; const animationId = root.hiloNode.animationId; if (isComponent && resource.anim && resource.anim.validAnimationIds[animationId]) { (parentActor as any).animNameMap[animationId] = root.hiloNode; (parentActor as any).animCount += 1; } return result; } /** * @hidden */ function convert( game: Game, parent: SceneActor | SceneComponent, children: INodeWithGlTFExtensions[], actors: SArray<SceneActor>, resource: IGlTFModel, forceAsComponent: boolean = false, className: string = null ) { // if parent is null let isComponent: boolean = false; let parentNode: INodeWithGlTFExtensions = null; let parentSeinNode: ISeinNodeExtension = null; if (parent) { if (isSceneActor(parent)) { parentNode = parent.root.hiloNode as INodeWithGlTFExtensions; } else { parentNode = parent.hiloNode as INodeWithGlTFExtensions; // parent is component, child must be component isComponent = true; } } if (parentNode && parentNode.gltfExtensions && parentNode.gltfExtensions.Sein_node) { parentSeinNode = parentNode.gltfExtensions.Sein_node; } else { parentSeinNode = {}; } const length = children.length; for (let i = 0; i < length; i += 1) { const child = children[i]; child.gltfExtensions = child.gltfExtensions || {}; (child as any).childrenOffset = 0; let childSeinNode: ISeinNodeExtension; let skipThisNode: boolean = false; if (child.gltfExtensions.Sein_node) { childSeinNode = child.gltfExtensions.Sein_node; skipThisNode = childSeinNode.skipThisNode; } if (forceAsComponent || className) { childSeinNode = childSeinNode || { selfType: ESeinNodeType.Actor, childrenType: ESeinNodeType.Component }; } if (forceAsComponent) { childSeinNode.selfType = ESeinNodeType.Component; } if (className) { childSeinNode.className = className; } // parent is actor, childrenType is component and selfType of child is component if (childSeinNode && childSeinNode.selfType === ESeinNodeType.Actor) { isComponent = false; } else if ( !isComponent && parentSeinNode.childrenType === ESeinNodeType.Component && (!childSeinNode || childSeinNode.selfType !== ESeinNodeType.Actor) ) { isComponent = true; } else if (childSeinNode && childSeinNode.selfType === ESeinNodeType.Component) { isComponent = true; } let result = parent; if (!skipThisNode) { result = generateActorOrComponentFromNode( child, (parent && !isSceneActor(parent)) ? (parent as any).getOwner() : parent, (parent && isSceneActor(parent)) ? null : parent as SceneComponent, isComponent, resource, game.world ); if (isSceneActor(result)) { const actor = result; (actor as any).animNameMap = {}; (actor as any).animCount = 0; (actor as any).skeletalMeshComponents = (actor as any).skeletalMeshComponents || []; const animationId = actor.root.hiloNode.animationId; if (resource.anim && resource.anim.validAnimationIds[animationId]) { (actor as any).animNameMap[animationId] = actor.root.hiloNode; (actor as any).animCount += 1; } actors.add(actor); } Object.keys(child.gltfExtensions).forEach(name => { // 避免循环依赖,临时解决方案 const handler = (Hilo3d.GLTFParser as any).extensionHandlers[name]; if (handler && handler.instantiate) { handler.instantiate(result, child.gltfExtensions[name], game, child, resource); } }); } const offset = (child as any).childrenOffset || 0; // Leaf node if (!child.children || child.children.length === offset) { continue; } // const grandson = child.children[offset]; // if (child.children.length === offset + 1 && (!grandson.children || grandson.children.length === 0)) { // console.log(child, child.jointName); // continue; // } convert(game, result, child.children.slice(offset) as INodeWithGlTFExtensions[], actors, resource); } } /* tslint:enable */ /** * @hidden */ export default function addActorsFromGlTF( game: Game, entity: any, options?: any ): SArray<SceneActor> { const resource = entity.result; let node = resource.node as INodeWithGlTFExtensions; if (options && options.nodePath && options.nodePath.length !== 0) { node = resource.node.getChildByNamePath(options.nodePath) as INodeWithGlTFExtensions; if (!node) { throw new Error(`Resource "${entity.name}" in type "GlTF" dose not has node "${options.nodePath.toString()}" !`); } } let children: Hilo3d.Node[] = null; const actors = new SArray<SceneActor>(); if (node !== resource.node) { children = [node]; } else { children = node.children.slice() as Hilo3d.Node[]; const al = resource['ambientLight']; if (al && !(game.world as any).__gltfAmbientLightCreated) { const lNode = new Hilo3d.Node(); lNode.name = al.name; lNode.addChild(al); children.push(lNode); (game.world as any).__gltfAmbientLightCreated = true; } } if (options && options.name && children.length === 1) { const child = children[0]; child.name = options.name; } convert( game, options && (options.parentActor || options.parentComponent), children as INodeWithGlTFExtensions[], actors, resource, options && options.asComponent, options && (options.className || (options.Class && options.Class.CLASS_NAME.value)) ); actors.forEach(a => { const {animCount, animNameMap, skeletalMeshComponents} = a as any; let length = skeletalMeshComponents.length; for (let i = 0; i < length; i += 1 ) { const [component, meshes] = skeletalMeshComponents[i]; const len = meshes.length; for (let index = 0; index < len; index += 1) { component.cloneSkinningFromHilo(meshes[index], index); } } delete (a as any).animCount; delete (a as any).animNameMap; delete (a as any).skeletalMeshComponents; if (animCount > 0) { const hiloNode = a.root.hiloNode as INodeWithGlTFExtensions; hiloNode.anim = resource.anim.clone(null); (hiloNode as any).anim.nodeNameMap = animNameMap; if (hiloNode.gltfExtensions.Sein_animator) { const {modelAnimations, prefix, prefixes} = hiloNode.gltfExtensions.Sein_animator; length = modelAnimations.length; if (length !== 0) { const originClips = hiloNode.anim.clips; const clips = hiloNode.anim.clips = {}; for (let index = 0; index < length; index += 1) { const name = modelAnimations[index]; const finalPrefix = prefixes ? (prefixes[index] || prefix) : prefix; clips[name] = originClips[finalPrefix ? `${finalPrefix}@${name}` : name]; } } } a.addComponent('animator', AnimatorComponent); if (hiloNode.gltfExtensions.Sein_animator) { const {defaultAnimation} = hiloNode.gltfExtensions.Sein_animator; if (defaultAnimation) { a.animator.setDefault(defaultAnimation); } } } if (options.preRender) { a.preRender(); } a.instantiated(); }); return actors; }
the_stack
import { SqrlJs } from "../js/SqrlJs"; import { SqrlParseInfo, SqrlParserState, SlotFilter } from "./SqrlParserState"; import { processExprAst } from "../ast/AstExpr"; import { Expr, walkExpr, Slot } from "../expr/Expr"; import { Ast } from "../ast/Ast"; import { SqrlInputSlot } from "../slot/SqrlSlot"; import invariant from "../jslib/invariant"; import { isValidFeatureName } from "../feature/FeatureName"; import { compileParserStateAst } from "./SqrlCompile"; import { ExecutableSpec, RuleSpecMap, FeatureDocMap } from "../api/spec"; import { Context } from "../api/ctx"; import { buildSqrlError } from "../api/parse"; class ExprLoopError extends Error { constructor() { super("Encountered loop while generating expr output"); } } export class SqrlCompiledOutput extends SqrlParseInfo { readonly usedFiles: string[]; readonly ruleSpecs: RuleSpecMap; private slotExprMap: { [slotName: string]: Expr } = {}; private cost: { [name: string]: number } = {}; private recursiveCost: { [name: string]: number } = {}; /** * List of slots that are used in the calculation of the given slot */ private load: { [name: string]: Set<string> } = {}; constructor( parserState: SqrlParserState, public slotFilter: SlotFilter | null = null ) { super(parserState.slots, parserState.options); this.usedFiles = Array.from(parserState.usedFiles).sort(); this.ruleSpecs = parserState.getRuleSpecs(); } /** * Recurse through the given slot calculating cost and load data */ private recurseSlot(name: string) { // If we've got a cost make sure it's not `null` ("in calculation") if (this.cost.hasOwnProperty(name)) { invariant(this.cost[name] !== null, "Loop while calculating slotCost"); return; } else { this.cost[name] = null; } const expr = this.exprForSlot(name); const load: Set<string> = new Set(); let cost = 0; // Walk through the expr, keep track of everything we load and our own cost walkExpr(expr, (node) => { (node.load || []).forEach((slot) => { if (load.has(slot.name)) { return; } this.recurseSlot(slot.name); // We need to load the given slot, and all it's children load.add(slot.name); this.load[slot.name].forEach((slotName) => load.add(slotName)); }); if (node.type === "call") { cost += this.instance.getCost(node.func); } }); let recursiveCost = cost; load.forEach((name) => { recursiveCost += this.cost[name]; }); this.cost[name] = cost; this.recursiveCost[name] = recursiveCost; this.load[name] = load; } exprForSlot(slotName: string): Expr { if (this.slotExprMap.hasOwnProperty(slotName)) { if (this.slotExprMap[slotName] === null) { throw new ExprLoopError(); } return this.slotExprMap[slotName]; } const slot = this.slots[slotName]; if (slot instanceof SqrlInputSlot) { return { type: "input", }; } // Mark it as null before processing so that we can throw if we find ourselves in a loop this.slotExprMap[slotName] = null; const ast: Ast = slot.finalizedAst(); const expr = processExprAst(ast, this, this.instance); this.slotExprMap[slotName] = expr; return expr; } private _slotNames: string[]; private _usedSlotNames: (string | null)[]; private calculateSlotNames() { const used: Set<Slot> = new Set(); const current: Set<Slot> = new Set(); const throwLoopError = (slot: Slot, slotNames: string[]) => { // @TODO: This invariant protects us from allowing loops inside sqrl, // but it's implemented at too late a stage to provide nice error // messages. Ideally we'd have it higher up as well. slotNames = slotNames.filter(isValidFeatureName).sort(); let errorMessage: string; if (isValidFeatureName(slot.name)) { errorMessage = `Feature '${slot.name}' depends on itself`; slotNames = slotNames.filter((name) => name !== slot.name); if (slotNames.length) { errorMessage += ", see " + slotNames.join(", "); } } else { this.warn( {}, "Feature loop detected on non-feature slot:: %s", slot.name ); errorMessage = "Feature loop detected with features: " + slotNames.join(", "); } // @NOTE: You get much better error messages with this, but it's not user safe // const loops = this.printFeatureLoop(slot); // errorMessage += '\nDetected loops:\n ' + loops.join('\n '); throw buildSqrlError(slot.finalizedAst(), errorMessage); }; const recurseUsedSlot = (slot: Slot) => { if (used.has(slot)) { return; } else { if (current.has(slot)) { throwLoopError( slot, Array.from(current).map((slot) => slot.name) ); } } current.add(slot); let slotExpr: Expr; try { slotExpr = this.exprForSlot(slot.name); } catch (err) { if (err instanceof ExprLoopError) { const names = Object.keys(this.slotExprMap).filter((name) => { return this.slotExprMap[name] === null; }); throwLoopError(slot, names); } else { throw err; } } walkExpr(slotExpr, (expr) => { (expr.load || []).forEach((slot) => { if (!used.has(slot)) { recurseUsedSlot(slot); } }); }); current.delete(slot); used.add(slot); }; let slotNames: string[]; if (this.slotFilter) { Object.entries(this.slots).forEach(([name, slot]) => { if (this.slotFilter(name)) { recurseUsedSlot(slot); } }); slotNames = Object.keys(this.slots).filter((name) => { return used.has(this.slots[name]); }); } else { slotNames = Object.keys(this.slots); // This recurse is required for picking up cycles, might be able to remove one day Object.values(this.slots).forEach((slot) => recurseUsedSlot(slot)); } this._slotNames = slotNames; this._usedSlotNames = slotNames.map((name) => this.slots.hasOwnProperty(name) ? name : null ); } get slotNames(): string[] { if (!this._slotNames) { this.calculateSlotNames(); } return this._slotNames; } get usedSlotNames(): string[] { if (!this._slotNames) { this.calculateSlotNames(); } return this._usedSlotNames; } private _slotExprs: Expr[]; get slotExprs() { if (!this._slotExprs) { this._slotExprs = this.usedSlotNames.map((name, idx) => { if (!name) { return null; } this.slots[name].setIndex(idx); return this.exprForSlot(name); }); } return this._slotExprs; } private _recursed = false; private recurseAllSlots() { if (this._recursed) { return; } this.usedSlotNames.forEach((name) => { if (name) { this.recurseSlot(name); } }); this._recursed = true; } public get slotCosts(): number[] { this.recurseAllSlots(); return this.usedSlotNames.map((name) => name && this.cost[name]); } public get slotRecursiveCosts(): number[] { this.recurseAllSlots(); return this.usedSlotNames.map((name) => name && this.recursiveCost[name]); } public get slotLoad(): number[][] { return this.usedSlotNames.map((name) => { return Array.from(this.load[name]) .map((loadName) => { const index = this.usedSlotNames.indexOf(loadName); invariant(index >= 0, "Could not find slot index: " + loadName); return index; }) .sort(); }); } get usedFunctions(): string[] { const functions: Set<string> = new Set(); for (const expr of this.slotExprs) { walkExpr(expr, (node) => { if (node.type === "call") { functions.add(node.func); } }); } return Array.from(functions).sort(); } get featureDocs(): FeatureDocMap { this.recurseAllSlots(); const rv: FeatureDocMap = {}; this.foreachFeatureSlot((slot) => { rv[slot.name] = slot.buildDoc({ cost: this.cost[slot.name], recursiveCost: this.recursiveCost[slot.name], }); }); this.foreachRuleSlot((slot) => { rv[slot.name] = slot.buildDoc({ cost: this.cost[slot.name], recursiveCost: this.recursiveCost[slot.name], }); }); return rv; } get slotJs() { return this.slotExprs.map((fetchExpr, idx) => { invariant( fetchExpr, "Expected source for null fetchExpr:: %s", this.slotNames[idx] ); if (fetchExpr.type === "input") { return null; } return SqrlJs.generateExpr(this.instance, fetchExpr); }); } get executableSpec(): ExecutableSpec { return { slotNames: this.slotNames, slotCosts: this.slotCosts, slotRecursiveCosts: this.slotRecursiveCosts, rules: this.ruleSpecs, usedFiles: this.usedFiles, slotJs: this.slotJs, }; } getSlotIndex(slotName: string): number { const idx = this.slotNames.indexOf(slotName); invariant(idx >= 0, "Could not find slot: " + slotName); return idx; } /** * Fetch the cost for a single slot without recursing all the others */ getSlotCost( slotName: string ): { cost: number; recursiveCost: number; } { this.recurseSlot(slotName); return { cost: this.cost[slotName], recursiveCost: this.recursiveCost[slotName], }; } static async build( ctx: Context, parserState: SqrlParserState, options: { buildFeatures?: string[]; skipCostCalculations?: boolean; } = {} ): Promise<SqrlCompiledOutput> { compileParserStateAst(parserState); const ruleNames = []; let featureSet = null; if (options.buildFeatures) { // Make sure to include ruleNames as well to reduce confusion featureSet = new Set([...options.buildFeatures, ...ruleNames]); } let slotFilter: SlotFilter = null; if (featureSet) { slotFilter = (name) => featureSet.has(name); } return new SqrlCompiledOutput(parserState, slotFilter); } }
the_stack
import { Component, Vue, Watch } from 'vue-property-decorator'; import { TweenLite } from 'gsap'; import $ from 'jquery'; import _ from 'lodash'; import { checkEdgeConnectivity } from '@/store/dataflow'; import { CreateNodeData } from '@/store/dataflow/types'; import { DEFAULT_ANIMATION_DURATION_S, PORT_SIZE_PX, PORT_MARGIN_PX, ICONIZED_NODE_SIZE_PX } from '@/common/constants'; import { NodeSave } from './types'; import { Port, InputPort, OutputPort } from '@/components/port'; import ContextMenu from '@/components/context-menu/context-menu'; import Edge from '@/components/edge/edge'; import GlobalClick from '@/directives/global-click'; import NodeCover from './node-cover.vue'; import NodeLabel from './node-label.vue'; import ns from '@/store/namespaces'; import OptionPanel from '@/components/option-panel/option-panel'; import template from './node.html'; import { HistoryNodeEvent } from '@/store/history/types'; import * as history from './history'; import { vectorDistance } from '@/common/vector'; import BaseModal from '@/components/modals/base-modal/base-modal'; const GRID_SIZE = 10; // Parameters for computing the activeness of nodes. const FOCUS_ALPHA = 2; const FOCUS_BETA = 5; const FOCUS_GAMMA = 500; const MINIMUM_ACTIVENESS = .1; @Component({ components: { NodeLabel, NodeCover, ContextMenu, OptionPanel, Port, BaseModal, }, directives: { GlobalClick, }, template, }) export default class Node extends Vue { public id!: string; public layer = 0; // whether the node is focused and its option panel is shown public isActive = false; // whether the node is among the current selection, which may contain multiple nodes public isSelected = false; // whether the propagation should start from this node public isPropagationSource = false; // For most nodes, the output is connected with its input. // The only exception is a data reservoir, of which the output only flashes connecting its input on user release. // A data reservoir does not introduce backward cycle. public isInputOutputDisconnected = false; // Beta feature allows data mutation. public isDataMutated = false; public get isVisible(): boolean { return !this.isSystemInVisMode || this.isInVisMode; } public get nodeType(): string { return this.NODE_TYPE; } @ns.dataflow.Mutation('portUpdated') protected portUpdated!: (port: Port) => void; protected NODE_TYPE = 'node'; protected DEFAULT_WIDTH = 50; protected DEFAULT_HEIGHT = 50; protected MIN_WIDTH = 30; protected MIN_HEIGHT = 30; protected RESIZABLE = false; protected ENLARGEABLE = false; // if the node can be enlarged to fullscreen modal protected REVERSE_INPUT_OUTPUT_PORTS = false; // if the input is on the right and the output is on the left protected HAS_SETTINGS = false; // has advanced settings configured by a modal protected label = ''; // background color of the content div protected backgroundColor = 'white'; // boundary color of the node, used to show data mutation boundaries protected boundaryColor = 'none'; // ports: input/output port id's must be unique protected inputPorts: InputPort[] = []; protected outputPorts: OutputPort[] = []; // Maps port id to port. protected inputPortMap: { [id: string]: InputPort } = {}; protected outputPortMap: { [id: string]: OutputPort } = {}; // Layout related properties. // Changing width and height will resize the node. protected width = 0; // initialized in created() protected height = 0; // initialized in created() protected dataflowX = 0; // CSS "left" in the dataflow, when not iconized protected dataflowY = 0; // CSS "top" in the dataflow, when not iconized protected dataflowWidth = 0; // width when not iconized protected dataflowHeight = 0; // height when not iconized // Changing x and y will change the position of the node. protected x = 0; // CSS "left" of top-left corner protected y = 0; // CSS "top" of top-left corner protected isIconized = false; protected isInVisMode = false; protected isLabelVisible = false; protected isEnlarged = false; // These are the options passed to the node on node creation, and are only used once in created(). protected dataOnCreate: CreateNodeData = {}; protected isDragging = false; /** * The serialization chain is a list of functions to be called to generate the serialized NodeSave. * The functions are pushed to the list in the created() call of base node and inheritting node sequentially. * We utilize the Vue design that all created() of base and inheritting node classes are called. * * The deserialization chain is similar and assigns values in NodeSave to the deserialized node. * Each function in the chain is called sequentially after the NodeSave is written to the node. */ protected serializationChain: Array<() => {}> = []; protected deserializationChain: Array<(save: {}) => void> = []; /** * Stores named setters. * In deserialized undo/redo, a setter is retrieved by finding the function in this object. */ protected setters: { [name: string]: (value: any) => void } = {}; // tslint:disable-line no-any protected coverText: string = ''; // A list of classes to be added to the node container. Push to this list on inheritting node's created() call. protected containerClasses: string[] = ['node']; // Flag to indicate the node is in transition to its next position / size. When this is true, the node should avoid // costly operation such as re-rendering. protected isAnimating = false; @ns.interaction.Getter('isShiftPressed') protected isShiftPressed!: boolean; @ns.history.Mutation('commit') protected commitHistory!: (evt: HistoryNodeEvent) => void; // Measures how actively this node is used by the user. private activeness = 0; private isDragged = false; private isMousedowned = false; private visModeX = 0; private visModeY = 0; private visModeWidth = 0; private visModeHeight = 0; // Used to hide ports when visMode is exiting. private isExitingVisMode = false; // Whether the settings modal is visible. private isSettingsVisible = false; get numInputPorts(): number { return this.inputPorts.length; } get numOutputPorts(): number { return this.outputPorts.length; } get allPorts(): Port[] { return _.concat(this.inputPorts as Port[], this.outputPorts); } get getIconPath() { return this.getImgSrc(this.NODE_TYPE); } get isContentVisible(): boolean { return !this.coverText && !this.isAnimating && this.isExpanded; } get isIconVisible(): boolean { return !this.isExpanded && !this.isAnimating; } get isExpanded(): boolean { return this.isEnlarged || !this.isIconized || (this.isSystemInVisMode && this.isInVisMode); } get arePortsVisible(): boolean { return !this.isEnlarged && !this.isSystemInVisMode && !this.isExitingVisMode; } get displayX(): number { if (this.isSystemInVisMode) { return this.visModeX; } if (this.isIconized) { return this.dataflowX + this.dataflowWidth / 2 - ICONIZED_NODE_SIZE_PX / 2; } return this.dataflowX; } get displayY(): number { if (this.isSystemInVisMode) { return this.visModeY; } if (this.isIconized) { return this.dataflowY + this.dataflowHeight / 2 - ICONIZED_NODE_SIZE_PX / 2; } return this.dataflowY; } get displayWidth(): number { if (this.isSystemInVisMode) { return this.visModeWidth; } return this.isIconized ? ICONIZED_NODE_SIZE_PX : this.dataflowWidth; } get displayHeight(): number { if (this.isSystemInVisMode) { return this.visModeHeight; } return this.isIconized ? ICONIZED_NODE_SIZE_PX : this.dataflowHeight; } get displayCss(): { left: number, top: number, width: number, height: number} { return { left: this.displayX, top: this.displayY, width: this.displayWidth, height: this.displayHeight, }; } @ns.dataflow.Getter('topNodeLayer') private topNodeLayer!: number; @ns.dataflow.Getter('getImgSrc') private getImgSrc!: (type: string) => string; @ns.dataflow.Mutation('incrementNodeLayer') private incrementNodeLayer!: () => void; @ns.dataflow.Mutation('removeSelectedNodes') private removeSelectedNodes!: (node: Node) => void; @ns.interaction.State('isSystemInVisMode') private isSystemInVisMode!: boolean; @ns.interaction.State('lastMouseX') private lastMouseX!: number; @ns.interaction.State('lastMouseY') private lastMouseY!: number; @ns.interaction.Getter('numSelectedNodes') private numSelectedNodes!: number; @ns.interaction.Getter('selectedNodes') private selectedNodes!: Node[]; @ns.interaction.Mutation('reduceAllNodeActiveness') private reduceAllNodeActiveness!: (node: Node) => void; @ns.interaction.Mutation('dropPortOnNode') private dropPortOnNode!: (node: Node) => void; @ns.interaction.Mutation('dragNode') private dragNode!: (payload: { node: Node, dx: number, dy: number}) => void; @ns.interaction.Mutation('clickNode') private clickNode!: (node: Node) => void; @ns.interaction.Mutation('nodeDragStarted') private nodeDragStarted!: (node: Node) => void; @ns.interaction.Mutation('nodeDragEnded') private nodeDragEnded!: () => void; @ns.systemOptions.State('nodeLabelsVisible') private nodeLabelsVisible!: boolean; @ns.panels.Mutation('mountOptionPanel') private mountOptionPanel!: (panel: Vue) => void; @ns.flowsense.State('enabled') private isFlowsenseEnabled!: boolean; @ns.flowsense.Mutation('openInput') private openFlowsenseInput!: (noActivePosition?: boolean) => void; public undo(evt: HistoryNodeEvent) { this.undoBase(evt); } public redo(evt: HistoryNodeEvent) { this.redoBase(evt); } public setIconized(value: boolean) { this.isIconized = value; } public setInVisMode(value: boolean) { this.isInVisMode = value; } public setLabelVisible(value: boolean) { this.isLabelVisible = value; } public findConnectablePort(port: Port): Port | null { if (port.isInput) { for (const output of this.outputPorts) { const connectivity = checkEdgeConnectivity(output, port); if (connectivity.connectable) { return output; } } } else { for (const input of this.inputPorts) { const connectivity = checkEdgeConnectivity(port, input); if (connectivity.connectable) { return input; } } } return null; } /** Retrives the list of nodes that output to this node. */ public getInputNodes(): Node[] { const nodes: Set<Node> = new Set(); for (const port of this.inputPorts) { const inputs = port.getConnectedNodes(); for (const node of inputs) { nodes.add(node); } } return Array.from(nodes); } /** Retrieves the list of nodes that this node connects to via output ports. */ public getOutputNodes(): Node[] { const nodes: Set<Node> = new Set(); for (const port of this.outputPorts) { const outputs = port.getConnectedNodes(); for (const node of outputs) { nodes.add(node); } } return Array.from(nodes); } public getBoundingBox(): Box { const $node = $(this.$refs.node); const width = $node.width() as number; const height = $node.height() as number; return { x: this.x, y: this.y, width, height, }; } public getLabel(): string { return this.label; } public getCenter(): Point { return { x: this.x + this.width / 2, y: this.y + this.height / 2, }; } /** Makes the node activated. This is typically auto-triggered by mouse click on the node. */ public activate() { this.isActive = true; // Activating the node implies selecting it. // Must use $nextTick because $refs.optionPanel appears asynchronously after isActive becomes true. this.$nextTick(() => this.mountOptionPanel(this.$refs.optionPanel as Vue)); } /** Makes the node deactivated. This is typically auto-triggered by clicking outside the node. */ public deactivate() { this.isActive = false; } public select() { this.isSelected = true; this.incrementActiveness(); this.reduceAllNodeActiveness(this); } public deselect() { this.isSelected = false; } public getAllEdges(): Edge[] { let edges: Edge[] = []; for (const port of this.allPorts) { edges = edges.concat(port.getAllEdges()); } return edges; } public getOutputEdges(): Edge[] { let edges: Edge[] = []; for (const port of this.outputPorts) { edges = edges.concat(port.getAllEdges()); } return edges; } /** Moves the node to a given position. */ public moveTo(x: number, y: number) { this.x = x; this.y = y; } /** Moves the node to a given position with transition */ public moveToWithTransition(x: number, y: number, duration: number, onComplete?: () => void) { const $node = $(this.$refs.node); TweenLite.to(this.$refs.node, duration, { left: x, top: y, onUpdate: () => { const offset = $node.offset() as JQuery.Coordinates; this.x = offset.left; this.y = offset.top; this.updatePortCoordinates(); }, onComplete: () => { this.x = x; this.y = y; if (onComplete) { onComplete(); } }, }); } /** Moves the node by the given (dx, dy) from its current position. */ public moveBy(dx: number, dy: number) { this.x += dx; this.y += dy; } /** * Sets the size of the node. * Note that setView or setLocation is not provided, because a node's (x, y) location also depends on the global * translation. Use moveBy with relative movement instead. */ public setSize(width: number, height: number) { this.width = width; this.height = height; } /** * Starts a node update by first checking if the update is necessary. * An update is necessary when some input port has changed package and all connections are valid. */ public startUpdate() { if (this.isUpdateNecessary() && this.areConnectionsValid()) { console.log('startUpdate', this.label); this.update(); } } /** Clears the updated flags of all ports. */ public clearUpdatedPorts() { for (const port of this.inputPorts) { // Packages of input ports solely depend on its connected output ports. So there are no package update // flags to clear. port.clearConnectionUpdate(); } for (const port of this.outputPorts) { port.clearPackageUpdate(); port.clearConnectionUpdate(); } } public getInputPort(id: string): InputPort { const port = this.inputPorts.find(inputPort => inputPort.id === id); if (!port) { console.error(`port "${id}" is not an input port of node ${this.id} (${this.label})`); } return port as InputPort; } public getOutputPort(id: string): OutputPort { const port = this.outputPorts.find(outputPort => outputPort.id === id); if (!port) { console.error(`port "${id}" is not an output port of node ${this.id} (${this.label})`); } return port as OutputPort; } /** * Serializes the node into a NodeSave object. * serialize() shall not be overridden from its base class implementation. */ public serialize(): NodeSave { // Call each function in the serialization chain to store node attributes into the save object. return this.serializationChain.reduce((save, f) => { return _.extend(save, f()); }, {}) as NodeSave; } /** * Deserializes the node from a NodeSave object. * deserialize() shall not be overridden from its base class implementation. */ public deserialize(save: NodeSave) { // _.extend(this, save); this.deserializationChain.forEach(f => f(save)); } /** * Handles local keyboard combinations. */ public onKeys(keys: string): boolean { return this.onKeysNode(keys); } /** * Increases the activeness of the node. This is triggered by mouse click. */ public incrementActiveness() { this.activeness++; } /** * Decreases the activeness by half. */ public reduceActiveness() { this.activeness /= 2.0; if (this.activeness <= MINIMUM_ACTIVENESS) { this.activeness = 0; } } public getActiveness() { return this.activeness; } /** * Computes the focus score for this node. */ public focusScore(): number { const d = this.distanceToMouse() / FOCUS_GAMMA; // dFactor is the flipped & shifted sigmoid function // 1 - 1 / (1 + e^-(d/gamma - beta)) const dFactor = 1.0 - 1.0 / (1 + Math.exp(-(d - FOCUS_BETA))); return this.activeness + FOCUS_ALPHA * dFactor; } /** * Sets the boundary color of this node. * This is used to highlight data mutation boundaries. */ public setBoundaryColor(color: string) { this.boundaryColor = color; } /** * Updates all outputs based on the (possibly) new inputs. This is called by dataflow propagation. * Inheriting node types should implement this method to define how they output data. * * Each node type is responsible for setting the packages of output ports and notify the global store * to propagate the changes. * * @abstract */ protected update() { console.error(`update() is not implemented for node type "${this.NODE_TYPE}"`); } /** * Propagates the output. * * @abstract */ protected propagate() { console.error(`propagate() is not implemented for node type "${this.NODE_TYPE}"`); } /** * First updates and then propagates. */ protected updateAndPropagate() { this.update(); this.propagate(); } protected created() { this.label = this.label || this.id; this.createPorts(); this.createPortMap(); this.update(); // Update to show proper coverText even when there is no connection // Base serialization this.serializationChain.push((): NodeSave => ({ id: this.id, type: this.NODE_TYPE, layer: this.layer, label: this.label, isIconized: this.isIconized, isInVisMode: this.isInVisMode, isLabelVisible: this.isLabelVisible, dataflowX: this.dataflowX, dataflowY: this.dataflowY, dataflowWidth: this.dataflowWidth, dataflowHeight: this.dataflowHeight, visModeX: this.visModeX, visModeY: this.visModeY, visModeWidth: this.visModeWidth, visModeHeight: this.visModeHeight, })); } /** * Defines the input ports for the node. Inheriting nodes may override this method. */ protected createInputPorts() { this.inputPorts = []; } /** * Defines the output ports for the node. Inheriting nodes may override this method. */ protected createOutputPorts() { this.outputPorts = []; } /** * Displays the node in fullscreen. */ protected enlarge() {} /** * Responds to width/height changes. */ protected onResizeStart() {} protected onResize() {} protected onResizeStop() {} /** * Responds to node enlarge. */ protected onEnlarge() {} /** * Determintes whether the node should respond to dragging. * Override this method to disable dragging under some conditions, e.g. when visualization selection is prioritized. */ protected isDraggable(evt: Event, ui: JQueryUI.DraggableEventUIParams) { return true; } protected enableDraggable() { $(this.$refs.node).draggable('enable'); } protected disableDraggable() { $(this.$refs.node).draggable('disable'); } protected enableResizable() { if (this.RESIZABLE) { $(this.$refs.node).resizable('enable'); } } protected disableResizable() { if (this.RESIZABLE) { $(this.$refs.node).resizable('disable'); } } /** Checks if there is an input port that has updated package. */ protected isUpdateNecessary(): boolean { for (const port of this.inputPorts) { if (port.isPackageUpdated() || port.isConnectionUpdated()) { return true; } } return false; } protected areConnectionsValid(): boolean { for (const port of this.inputPorts) { if (!port.checkValidConnections()) { return false; } } return true; } /** * Default click behavior is for node selection and activation when the node is NOT dragged. * If shift is held, a click toggles node selection. * Otherwise the click selects the node excusively (deselecting all other nodes) and shows its option panel by * activating it. */ protected onClick(evt: MouseEvent) { if (!this.isDragged) { if (this.isShiftPressed) { // When shift is pressed, clicking a node toggles its selection. this.toggleSelected(); } else { this.clickNode(this); this.select(); this.activate(); } } // prevent the click to be released globally, which would cancel key presses evt.stopPropagation(); } /** * Provides base node level operation undo. */ protected undoBase(evt: HistoryNodeEvent) { history.undo(this.$store, evt); } /** * Provides base node level operation redo. */ protected redoBase(evt: HistoryNodeEvent) { history.redo(this.$store, evt); } /** * Responds to mounted life cycle. */ protected onMounted() {} /** * Base responds of keyboard that are shared by all node types. */ protected onKeysNode(keys: string): boolean { switch (keys) { case 'm': this.toggleIconized(); break; case 'v': this.toggleVisMode(); break; default: return false; } return true; } /** * Inheritting nodes fire this when they change their input/output ports. * So far only script editor is able to change the number of input output ports. */ protected onPortsChanged() { this.createPortMap(); this.$nextTick(() => { this.mountPorts(); this.updatePortCoordinates(); }); } /** * Fires when the settings modal opens. */ protected onOpenSettingsModal() {} /** * We make mounted() private so that inheriting class cannot add mounted behavior. * Though vue supports all mounted() to be called sequentially, any inheriting class should update their * type-specific data and properties in created() rather than mounted(). * ExtendedNode.created() is called before Node.mounted(), so that the updates can take effect * before we set up things here. */ private mounted() { this.initDragAndResize(); this.initDrop(); this.initPositionAndSize(); this.mountPorts(); this.initDeserializedProperties(); this.appear(); // animate node appearance } private createPorts() { this.createInputPorts(); this.createOutputPorts(); } /** Creates a mapping from port id to port component. */ private createPortMap() { this.inputPortMap = {}; this.inputPorts.forEach(port => { this.inputPortMap[port.id] = port; }); this.outputPortMap = {}; this.outputPorts.forEach(port => { this.outputPortMap[port.id] = port; }); } /** Update the ports' coordinates when the node moves. */ private updatePortCoordinates() { if (!this.arePortsVisible) { return; } // Port coordinates are Vue reactive and async. // We must update coordinates till Vue updates the ports. this.$nextTick(() => { for (const port of this.allPorts) { port.updateCoordinates(); } }); } private initDragAndResize() { const $node = $(this.$refs.node); let lastDragPosition: Point; let dragStartPosition: Point; let alreadySelected: boolean; $node.draggable({ grid: [GRID_SIZE, GRID_SIZE], start: (evt: Event, ui: JQueryUI.DraggableEventUIParams) => { if (!this.isDraggable(evt, ui)) { return false; } this.nodeDragStarted(this); this.isDragging = true; lastDragPosition = dragStartPosition = { x: ui.position.left, y: ui.position.top }; alreadySelected = this.isSelected; }, drag: (evt: Event, ui: JQueryUI.DraggableEventUIParams) => { const x = ui.position.left; const y = ui.position.top; if (x !== lastDragPosition.x || y !== lastDragPosition.y) { this.isDragged = true; if (!alreadySelected) { if (!this.isShiftPressed) { this.clickNode(this); } this.select(); } this.dragNode({ node: this, dx: x - lastDragPosition.x, dy: y - lastDragPosition.y, }); lastDragPosition = { x, y }; this.x = x; this.y = y; } }, stop: (evt: Event, ui: JQueryUI.DraggableEventUIParams) => { this.x = ui.position.left; this.y = ui.position.top; this.isDragged = false; this.isDragging = false; this.activate(); this.nodeDragEnded(); history.moveNode(this.$store, this, this.selectedNodes, { x: this.x, y: this.y }, dragStartPosition); }, }); if (this.RESIZABLE) { let resizeStartView: Box; $node.resizable({ handles: 'all', grid: GRID_SIZE, minWidth: this.MIN_WIDTH, minHeight: this.MIN_HEIGHT, start: () => { this.onResizeStart(); resizeStartView = { x: this.x, y: this.y, width: this.width, height: this.height, }; }, resize: (evt: Event, ui: JQueryUI.ResizableUIParams) => { this.x = ui.position.left; this.y = ui.position.top; this.width = ui.size.width; this.height = ui.size.height; }, stop: () => { this.onResizeStop(); const newView = { x: this.x, y: this.y, width: this.width, height: this.height, }; history.resizeNode(this.$store, this, newView, resizeStartView); }, }); } } private initDrop() { // Ports can be dropped on nodes to create an edge. $(this.$refs.background).droppable({ /** * General note on using jquery callback within vue components: * "this" of the callback function is the Vue component. * If we add console.log(this) in the callback function, it may print the Vue component. * However in chrome debugger console if we set a breakpoint and use the debugger console to print "this", * the DOM element may be incorrectly printed. */ drop: (evt: Event, ui: JQueryUI.DroppableEventUIParam) => { if (ui.draggable.hasClass('port')) { this.dropPortOnNode(this); } }, }); } private mountPorts() { const $node = $(this.$refs.node); for (const port of this.allPorts) { const container = $node.find(port.isInput ? '.input.port-group' : '.output.port-group') .find(`#port-container-${port.id}`); port.$mount(); container.append(port.$el); } } private initPositionAndSize() { const $node = $(this.$refs.node); $node.addClass(this.containerClasses); if (this.dataflowWidth === 0) { this.dataflowWidth = this.DEFAULT_WIDTH; this.dataflowHeight = this.DEFAULT_HEIGHT; } if (this.dataOnCreate.dataflowX !== undefined && this.dataOnCreate.dataflowY !== undefined) { this.dataflowX = this.dataOnCreate.dataflowX; this.dataflowY = this.dataOnCreate.dataflowY; } else if (this.dataOnCreate.dataflowCenterX !== undefined && this.dataOnCreate.dataflowCenterY !== undefined) { this.dataflowX = this.dataOnCreate.dataflowCenterX - this.dataflowWidth / 2; this.dataflowY = this.dataOnCreate.dataflowCenterY - this.dataflowHeight / 2; } // jQuery.draggable sets position to relative, we override here. $node.css({ position: 'absolute', }); this.updateDisplay(); } private initDeserializedProperties() { this.onIconizedChangeResizable(); // When the node is deserialized, layer is never changed and we trigger z-index setting manually. this.onLayerChange(); } private appear() { TweenLite.from(this.$refs.node, DEFAULT_ANIMATION_DURATION_S, { scale: 1.5, onComplete: () => { // When the node is deserialized, without this the port coordinates are never computed after scaling. this.updatePortCoordinates(); // When the node is deserialized, its label does not animate to the correct position before the node appears. if (this.isLabelVisible) { this.isLabelVisible = false; this.$nextTick(() => this.isLabelVisible = true); } this.onMounted(); }, }); } private contextMenuRemove() { // The user may right click on an unselected node. We consider it first clicked and to be exclusively selected. if (!this.isSelected) { this.select(); this.clickNode(this); } this.removeSelectedNodes(this); } private onMousedown(evt: MouseEvent) { this.isMousedowned = true; } private onMouseup(evt: MouseEvent) { if (!this.isMousedowned) { return; } this.isMousedowned = false; if (evt.which === 1) { // Only click with left mouse button this.onClick(evt); } } private toggleSelected() { if (this.isSelected) { this.deselect(); this.deactivate(); } else { this.select(); this.activate(); } } private globalClick(evt: MouseEvent) { if (!this.isActive) { return; } const element = evt.target as Element; if ( // If the click is on the node or its option panel, do nothing. this.$el.contains(element) || // If the click is on a modal, do nothing. $(element).parents('.modal-dialog').length || // If the click is on modal backdrop, do nothing. $(element).hasClass('modal-backdrop') || // If the click is in the history panel to undo/redo events, do nothing. // $('.history-panel')[0].contains(element) || // If the click is on the node's own option panel, do nothing. this.$refs.optionPanel && (this.$refs.optionPanel as Vue).$el.contains(evt.target as Element)) { return; } this.deactivate(); } private toggleIconized() { if (this.isSystemInVisMode) { return; // iconized cannot be toggled in visMode } this.isIconized = !this.isIconized; this.commitHistory(history.toggleIconizedEvent(this, this.isIconized)); } private toggleVisMode() { this.isInVisMode = !this.isInVisMode; this.commitHistory(history.toggleIconizedEvent(this, this.isInVisMode)); } private toggleLabelVisible() { this.isLabelVisible = !this.isLabelVisible; this.commitHistory(history.toggleLabelVisibleEvent(this, this.isLabelVisible)); } private onToggleIconized(value: boolean) { this.setIconized(value); this.commitHistory(history.toggleIconizedEvent(this, value)); } private onToggleInVisMode(value: boolean) { this.setInVisMode(value); this.commitHistory(history.toggleInVisModeEvent(this, value)); } private onToggleLabelVisible(value: boolean) { this.setLabelVisible(value); this.commitHistory(history.toggleLabelVisibleEvent(this, value)); } private onInputLabel(value: string) { this.label = value; } @Watch('isActive') private onActivatedChange(newValue: boolean) { if (newValue) { this.incrementNodeLayer(); this.layer = this.topNodeLayer; } } @Watch('layer') private onLayerChange() { $(this.$refs.node).css('z-index', this.layer); } private recordX() { if (this.isAnimating) { return; } if (this.isSystemInVisMode) { this.visModeX = this.x; return; } if (!this.isIconized) { this.dataflowX = this.x; } else { this.dataflowX = this.x + (ICONIZED_NODE_SIZE_PX - this.dataflowWidth) / 2; } } private recordY() { if (this.isAnimating) { return; } if (this.isSystemInVisMode) { this.visModeY = this.y; return; } if (!this.isIconized) { this.dataflowY = this.y; } else { this.dataflowY = this.y + (ICONIZED_NODE_SIZE_PX - this.dataflowHeight) / 2; } } private recordWidth() { if (this.isAnimating) { return; } if (!this.isIconized) { if (!this.isSystemInVisMode) { this.dataflowWidth = this.width; } else { this.visModeWidth = this.width; } } } private recordHeight() { if (this.isAnimating) { return; } if (!this.isIconized) { if (!this.isSystemInVisMode) { this.dataflowHeight = this.height; } else { this.visModeHeight = this.height; } } } // Watch layout parameter changes to re-position the node and its ports reactively. @Watch('x') private onXChange() { $(this.$refs.node).css('left', this.x); this.updatePortCoordinates(); this.recordX(); } @Watch('y') private onYChange() { $(this.$refs.node).css('top', this.y); this.updatePortCoordinates(); this.recordY(); } @Watch('width') private onWidthChange() { $(this.$refs.node).css('width', this.width); this.updatePortCoordinates(); this.onResize(); this.recordWidth(); } @Watch('height') private onHeightChange() { $(this.$refs.node).css('height', this.height); this.updatePortCoordinates(); this.onResize(); this.recordHeight(); } @Watch('isIconized') private onIconizedChange() { this.onIconizedChangeResizable(); if (this.isSystemInVisMode) { return; } const $node = $(this.$refs.node); this.isAnimating = true; TweenLite.to(this.$refs.node, DEFAULT_ANIMATION_DURATION_S, { ...this.displayCss, // allow Vue transition to complete, otherwise elements will scatter when fading out delay: DEFAULT_ANIMATION_DURATION_S, onUpdate: () => { this.width = $node.width() as number; this.height = $node.height() as number; const offset = $node.offset() as JQuery.Coordinates; this.x = offset.left; this.y = offset.top; this.updatePortCoordinates(); }, onComplete: () => { this.isAnimating = false; this.updatePortCoordinates(); this.onResize(); }, }); } private onIconizedChangeResizable() { if (this.isIconized) { this.disableResizable(); } else { this.enableResizable(); } } @Watch('isSystemInVisMode') private onSystemVisModeChange() { if (!this.isInVisMode) { return; } if (this.isSystemInVisMode && this.visModeWidth === 0) { // First time entering visMode. Initialize the size and location. this.visModeX = this.x; this.visModeY = this.y; this.visModeWidth = this.width; this.visModeHeight = this.height; } if (this.isIconized) { // Turn on animating flag to hide rendered node in transition (which looks awkward). this.isAnimating = true; } if (!this.isSystemInVisMode) { // If visMode is exiting, ports will not be shown (which otherwise would fly around). this.isExitingVisMode = true; } TweenLite.to(this.$refs.node, DEFAULT_ANIMATION_DURATION_S, { ...this.displayCss, onComplete: () => { this.isExitingVisMode = false; this.isAnimating = false; this.updateDisplay(); }, }); } /** Sets the locations of ports. */ private portStyles(port: Port, index: number, isInputPort: boolean): { left: string, top: string } { const length = isInputPort ? this.inputPorts.length : this.outputPorts.length; const totalHeight = length * PORT_SIZE_PX + (length - 1) * PORT_MARGIN_PX; return { left: (isInputPort !== this.REVERSE_INPUT_OUTPUT_PORTS ? -PORT_SIZE_PX : this.width) + 'px', top: (this.height / 2 - totalHeight / 2 + index * (PORT_SIZE_PX + PORT_MARGIN_PX)) + 'px', }; } private inputPortGroupClass(): string { return !this.REVERSE_INPUT_OUTPUT_PORTS ? 'left' : 'right'; } private outputPortGroupClass(): string { return this.REVERSE_INPUT_OUTPUT_PORTS ? 'left' : 'right'; } private updateDisplay() { this.x = this.displayX; this.y = this.displayY; this.width = this.displayWidth; this.height = this.displayHeight; } private openContextMenu(evt: MouseEvent) { (this.$refs.contextMenu as ContextMenu).open(evt); } private distanceToMouse(): number { return vectorDistance(this.getCenter(), [this.lastMouseX, this.lastMouseY]); } private getContentStyles() { return { background: this.backgroundColor, outline: this.boundaryColor ? `1.25px solid ${this.boundaryColor}` : '', boxShadow: this.boundaryColor ? `1.25px 1.25px 2.5px ${this.boundaryColor}` : '', }; } private openSettingsModal() { this.isSettingsVisible = true; this.onOpenSettingsModal(); } private closeSettingsModal() { this.isSettingsVisible = false; } }
the_stack
import * as _ from 'underscore'; import animations from './animations.js'; import * as coreState from './core_state.js'; import * as Deferred from './deferred'; import WindowGroups from './window_groups'; import WindowGroupTransactionTracker, { ITransaction } from './window_group_transaction_tracker'; import { toSafeInt } from '../common/safe_int'; import ofEvents from './of_events'; import route from '../common/route'; import { clipBounds, windowSetBoundsToVisible } from './utils'; import { BrowserWindow, GroupWindow } from '../shapes'; import { windowTransaction } from 'electron'; import {RectangleBase, Rectangle} from './rectangle'; // change types const POSITION = 0; const SIZE = 1; const POSITION_AND_SIZE = 2; const isWin32 = process.platform === 'win32'; const DisableWindowGroupTracking = 'disable-window-group-tracking'; // Added Runtime argument: --disable-group-window-tracking=resize,api // resize: core does not handle resize event for grouped windows // api: core does not handle bound-changed event for grouped windows if generated by OpenFin API calls // so with disable-group-window-tracking="resize,api", docking framework can customize resize behaviors // for grouped windows const shouldTrack = (action: string): boolean => { // track everything by default return !coreState.argo[DisableWindowGroupTracking] || !coreState.argo[DisableWindowGroupTracking].split(',').includes(action); }; const trackingResize = shouldTrack('resize'); const trackingAPI = shouldTrack('api'); interface DecoratedBounds extends RectangleBase { frame: boolean; windowState: WindowState; } interface BoundChanged { x: boolean; y: boolean; state: boolean; width: boolean; height: boolean; changed: boolean; } interface Delta { x: number; x2: number; y: number; y2: number; width: number; height: number; } enum WindowState { Normal = 'normal', Maximized = 'maximized', Minimized = 'minimized' } interface DeferedEvent { changeType: number; reason: string; name: string; uuid: string; type: string; deferred: boolean; top: number; left: number; height: number; width: number; } export default class BoundsChangedStateTracker { private _listeners: any; constructor(private uuid: string, private name: string, private browserWindow: BrowserWindow) { this._listeners = { 'begin-user-bounds-change': (): void => { this.setUserBoundsChangeActive(true); const cachedBounds = this.getCachedBounds(); const payload = { uuid, name, top: cachedBounds.y, left: cachedBounds.x }; ofEvents.emit(route.window('begin-user-bounds-changing', uuid, name), Object.assign(payload, cachedBounds)); }, 'end-user-bounds-change': (): void => { this.setUserBoundsChangeActive(false); const bounds = this.getCurrentBounds(); const payload = { uuid, name, top: bounds.y, left: bounds.x }; ofEvents.emit(route.window('end-user-bounds-changing', uuid, name), Object.assign(payload, bounds)); this.handleBoundsChange(false, true); }, 'bounds-changing': (event: any, bounds: Rectangle): void => { this.handleBoundsChange(true, false, bounds); }, 'bounds-changed': (): void => { const ofWindow = coreState.getWindowByUuidName(uuid, name); const groupUuid = ofWindow ? ofWindow.groupUuid : null; const dispatchedChange = this.handleBoundsChange(true); if (groupUuid && !coreState.argo['use-legacy-window-groups']) { return; } if (dispatchedChange) { if (groupUuid) { const groupLeader = WindowGroupTransactionTracker.getGroupLeader(groupUuid); if (groupLeader && groupLeader.type === 'api') { this.handleBoundsChange(false, true); } } else { if (!animations.getAnimationHandler().hasWindow(this.browserWindow.id) && !this.isUserBoundsChangeActive()) { this.handleBoundsChange(false, true); } } } }, 'synth-animate-end': (meta: any): void => { if (meta.bounds) { // COMMENT THIS OUT FOR TESTING FLICKERING this.handleBoundsChange(false, true); } }, 'visibility-changed': (event: any, isVisible: boolean): void => { if (!isVisible || this.browserWindow.isMinimized() || this.browserWindow.isMaximized()) { this._deferred = true; } else { this._deferred = false; this.dispatchDeferredEvents(); } }, 'minimize': (): void => { this._deferred = true; this.updateCachedBounds(this.getCurrentBounds()); }, 'maximize': (): void => { this._deferred = true; this.updateCachedBounds(this.getCurrentBounds()); }, 'restore': (): void => { this._deferred = false; windowSetBoundsToVisible(this.browserWindow); this.updateCachedBounds(this.getCurrentBounds()); this.dispatchDeferredEvents(); }, 'unmaximize': (): void => { this._deferred = false; this.updateCachedBounds(this.getCurrentBounds()); this.dispatchDeferredEvents(); }, 'deferred-set-bounds': (event: any, payload: any): void => { Deferred.handleMove(this.browserWindow.id, payload); } }; // Cache the current bounds on construction this.updateCachedBounds(this.getCurrentBounds()); // listen to relevant browser-window events this.hookListeners(); } // a flag that represents if any change in the size has happened // without relying on the checking of the previous bounds which // may or may not be reliable depending on the previous event ( // specifically bounds-changing) private sizeChanged = false; private positionChanged = false; private _cachedBounds: DecoratedBounds; private _userBoundsChangeActive = false; private _deferred = false; private _deferredEvents: DeferedEvent[] = []; private setUserBoundsChangeActive = (enabled: boolean): void => { this._userBoundsChangeActive = enabled; }; private isUserBoundsChangeActive = (): boolean => { return this._userBoundsChangeActive; }; private updateCachedBounds = (bounds: DecoratedBounds): void => { this._cachedBounds = bounds; }; public getCachedBounds = (): DecoratedBounds => { return this._cachedBounds; }; private getCurrentBounds = (): DecoratedBounds => { const bounds = this.browserWindow.getBounds(); let windowState = WindowState.Normal; if (this.browserWindow.isMaximized()) { windowState = WindowState.Maximized; } if (this.browserWindow.isMinimized()) { windowState = WindowState.Minimized; } const frame = this.browserWindow._options.frame; return { ...bounds, frame, windowState }; }; private compareBoundsResult = (boundsOne: DecoratedBounds, boundsTwo: DecoratedBounds): BoundChanged => { let xDiff = boundsOne.x !== boundsTwo.x; let yDiff = boundsOne.y !== boundsTwo.y; const widthDiff = boundsOne.width !== boundsTwo.width; const heightDiff = boundsOne.height !== boundsTwo.height; const stateDiff = boundsOne.windowState !== boundsTwo.windowState; const changed = xDiff || yDiff || widthDiff || heightDiff /* || stateDiff*/; // set the changed flag only if it has not been set this.sizeChanged = this.sizeChanged || (widthDiff || heightDiff); if (this.sizeChanged) { xDiff = xDiff && ((boundsOne.x - boundsTwo.x) !== (boundsTwo.width - boundsOne.width)); yDiff = yDiff && ((boundsOne.y - boundsTwo.y) !== (boundsTwo.height - boundsOne.height)); } this.positionChanged = this.positionChanged || (xDiff || yDiff); return { x: xDiff, y: yDiff, width: widthDiff, height: heightDiff, state: stateDiff, changed }; }; private getBoundsDelta = (current: RectangleBase, cached: RectangleBase): Delta => { return { x: current.x - cached.x, x2: (current.x + current.width) - (cached.x + cached.width), y: current.y - cached.y, y2: (current.y + current.height) - (cached.y + cached.height), width: current.width - cached.width, height: current.height - cached.height }; }; private boundsChangeReason = (name: string, groupUuid?: string): 'animation' | 'group-animation' | 'self' | 'group' => { if (groupUuid) { const groupLeader = WindowGroupTransactionTracker.getGroupLeader(groupUuid); if (groupLeader && groupLeader.uuid && groupLeader.name) { const ofWindow = coreState.getWindowByUuidName(groupLeader.uuid, groupLeader.name); if (ofWindow && animations.getAnimationHandler().hasWindow(ofWindow.browserWindow.id)) { return groupLeader.name === name ? 'animation' : 'group-animation'; } else { return groupLeader.name === name ? 'self' : 'group'; } } } return animations.getAnimationHandler().hasWindow(this.browserWindow.id) ? 'animation' : 'self'; }; private sharedBoundPixelDiff = 5; // TODO this needs to account for if the window boarder has been crossed over private sharedBound = (boundOne: number, boundTwo: number): boolean => { return Math.abs(boundOne - boundTwo) < this.sharedBoundPixelDiff; }; private handleGroupedResize = (windowToUpdate: GroupWindow, bounds: RectangleBase): RectangleBase => { if (!trackingResize) { return bounds; } const thisRect = Rectangle.CREATE_FROM_BOUNDS(bounds); const currentBounds = this.getCurrentBounds(); const cachedBounds = this.getCachedBounds(); const moved = thisRect.propagateMoveToThisRect(cachedBounds, currentBounds); return clipBounds(moved, windowToUpdate.browserWindow); }; private checkTrackingApi = (groupLeader: ITransaction): boolean => groupLeader.type === 'api' ? !!trackingAPI : true; //tslint:disable-next-line private handleBoundsChange = (isAdditionalChangeExpected: boolean, force = false, bounds: Rectangle = null): boolean => { let dispatchedChange = false; let currentBounds = this.getCurrentBounds(); if (bounds) { currentBounds = { x: bounds.x, y: bounds.y, width: bounds.width, height: bounds.height, frame: currentBounds.frame, windowState: currentBounds.windowState }; } const cachedBounds = this.getCachedBounds(); const boundsCompare = this.compareBoundsResult(currentBounds, cachedBounds); const stateMin = boundsCompare.state && currentBounds.windowState === 'minimized'; const eventType = isAdditionalChangeExpected ? 'bounds-changing' : 'bounds-changed'; const sizeChangedCriteria = [ boundsCompare.width, boundsCompare.height ]; const positionChangedCriteria = [ boundsCompare.x, boundsCompare.y ]; const isBoundsChanged = eventType === 'bounds-changed'; // if this is to be the "last" event in a transaction, be sure to // any diff in the size or position towards the change type if (isBoundsChanged) { sizeChangedCriteria.push(this.sizeChanged); positionChangedCriteria.push(this.positionChanged); } if (boundsCompare.changed && !stateMin || force) { // returns true if any of the criteria are true const sizeChange = _.some(sizeChangedCriteria, (criteria): boolean => { return criteria; }); const posChange = _.some(positionChangedCriteria, (criteria): boolean => { return criteria; }); //const posChange = boundsCompare.x || boundsCompare.y; //0 means a change in position. //1 means a change in size. //2 means a change in position and size. // Default to change in position when there is no change const changeType = (sizeChange ? (posChange ? POSITION_AND_SIZE : SIZE) : POSITION); const ofWindow = coreState.getWindowByUuidName(this.uuid, this.name); const groupUuid = ofWindow ? ofWindow.groupUuid : null; // determine what caused the bounds change const reason = this.boundsChangeReason(this.name, groupUuid); // handle window group movements if (groupUuid && coreState.argo['use-legacy-window-groups']) { let groupLeader = WindowGroupTransactionTracker.getGroupLeader(groupUuid); if (force) { if (groupLeader && groupLeader.name === this.name) { // no need to notify group members for api moves since every window // will already receive an end notification if (groupLeader.type !== 'api') { WindowGroupTransactionTracker.notifyEndTransaction(groupUuid); } WindowGroupTransactionTracker.clearGroup(groupUuid); } } else { if (!groupLeader || !groupLeader.name) { const type = this.isUserBoundsChangeActive() ? 'user' : animations.getAnimationHandler().hasWindow(this.browserWindow.id) ? 'animation' : 'api'; WindowGroupTransactionTracker.setGroupLeader(groupUuid, this.name, this.uuid, type); } } groupLeader = WindowGroupTransactionTracker.getGroupLeader(groupUuid); if (groupLeader && groupLeader.name === this.name && this.checkTrackingApi(groupLeader)) { const delta = this.getBoundsDelta(currentBounds, cachedBounds); let wt: windowTransaction.Transaction; // window-transaction const hwndToId: { [hwnd: number]: number } = {}; const { noZorder, noSize, noActivate } = windowTransaction.flag; let flags: number; if (changeType === SIZE) { // this may need to change to 1 or 2 if we fix functionality for changeType 2 flags = noZorder + noActivate; } else { flags = noZorder + noSize + noActivate; } const windowGroup = WindowGroups.getGroup(groupUuid); const winsToMove = []; const positions: Map<string, RectangleBase> = new Map(); const setPositions: Array<() => void> = []; for (let i = 0; i < windowGroup.length; i++) { if (windowGroup[i].name !== this.name) { winsToMove.push(windowGroup[i]); } positions.set(windowGroup[i].name, windowGroup[i].browserWindow.getBounds()); } for (let i = 0; i < winsToMove.length; i++) { const win = winsToMove[i]; win.browserWindow.bringToFront(); // maybe just do this once? const winBounds = positions.get(win.name); const bounds = (changeType === SIZE) // here bounds compare and delta are from the window that is resizing ? this.handleGroupedResize(win, winBounds) : winBounds; let { x, y } = bounds; const { width, height } = bounds; // If it is a change in position (working correctly) or a change in position and size (not yet implemented) if (changeType === POSITION || changeType === POSITION_AND_SIZE) { x = toSafeInt(x + delta.x, x); y = toSafeInt(y + delta.y, y); } if (isWin32) { const hwnd = parseInt(win.browserWindow.nativeId, 16); if (!wt) { wt = new windowTransaction.Transaction(0); wt.on('deferred-set-window-pos', (event, payload: any): void => { payload.forEach((winPos: any): void => { const bwId = hwndToId[parseInt(winPos.hwnd)]; Deferred.handleMove(bwId, winPos); }); }); } hwndToId[hwnd] = win.browserWindow.id; if (win.browserWindow.isMaximized()) { win.browserWindow.unmaximize(); } /* Leave this in here (commented out) for now. The idea is to only actually move the windows after all window positions are known in order to detect if any min/max restriction has been violated. The reason it is not included here is that it changes the .deferred and .reason values on the event payloads in a way that breaks tests, though it may be the desired behavior. This will be revisited as we evaluate making the entire transaction happen deferred window bounds. setPositions.push(() => { const myBounds = positions.get(win.name); const { x, y, width, height } = myBounds; const [w, h] = [width, height]; wt.setWindowPos(hwnd, { x, y, w, h, flags }); }); */ const [w, h] = [width, height]; wt.setWindowPos(hwnd, { x, y, w, h, flags }); } else { if (win.browserWindow.isFullScreen()) { win.browserWindow.setFullScreen(false); } else if (win.browserWindow.isMaximized()) { win.browserWindow.unmaximize(); } else { positions.set(win.name, { x, y, width, height }); // see note above about deferred moves // setPositions.push(() => { // win.browserWindow.setBounds(positions.get(win.name)); // }); win.browserWindow.setBounds(positions.get(win.name)); } } } // see note above about deferred moves // setPositions.forEach(boundsSet => boundsSet()); if (wt) { wt.commit(); } } } const payload = { changeType, reason, name: this.name, uuid: this.uuid, type: eventType, deferred: this._deferred, top: currentBounds.y, left: currentBounds.x, height: currentBounds.height, width: currentBounds.width }; if (this._deferred) { this._deferredEvents.push(payload); } else { this.browserWindow.emit('synth-bounds-change', payload); } dispatchedChange = true; } this.updateCachedBounds(currentBounds); // this represents the changed event, reset the overall changed flag if (!isAdditionalChangeExpected) { this.sizeChanged = false; this.positionChanged = false; } return dispatchedChange; }; private collapseEventReasonTypes = (eventsList: DeferedEvent[]): DeferedEvent[] => { const eventGroups: DeferedEvent[][] = []; eventsList.forEach((event, index): void => { if (index === 0 || event.reason !== eventsList[index - 1].reason) { const list = []; list.push(event); eventGroups.push(list); } else { _.last(eventGroups).push(event); } }); return eventGroups.map((group): DeferedEvent => { let sizeChange = false; let posChange = false; group.forEach((event): void => { if (event.changeType === POSITION) { posChange = true; } else if (event.changeType === SIZE) { sizeChange = true; } else { sizeChange = true; posChange = true; } }); const lastEvent = _.last(group); lastEvent.changeType = (sizeChange ? (posChange ? POSITION_AND_SIZE : SIZE) : POSITION); return lastEvent; }); }; private dispatchDeferredEvents = (): void => { const boundsChangedEvents = this._deferredEvents.filter((event): boolean => { return event.type === 'bounds-changed'; }); const reasonGroupedEvents = this.collapseEventReasonTypes(boundsChangedEvents); reasonGroupedEvents.forEach((event): void => { event.type = 'bounds-changing'; this.browserWindow.emit('synth-bounds-change', event); event.type = 'bounds-changed'; this.browserWindow.emit('synth-bounds-change', event); }); this._deferredEvents.length = 0; }; private endWindowGroupTransactionListener = (groupUuid: string): void => { const ofWindow = coreState.getWindowByUuidName(this.uuid, this.name); const _groupUuid = ofWindow ? ofWindow.groupUuid : null; if (_groupUuid === groupUuid) { const groupLeader = WindowGroupTransactionTracker.getGroupLeader(groupUuid); if (groupLeader && groupLeader.name !== this.name) { this.handleBoundsChange(false, true); } } }; private updateEvents = (register: boolean): void => { const listenerFn = register ? 'on' : 'removeListener'; Object.keys(this._listeners).forEach((key): void => { this.browserWindow[listenerFn](key, this._listeners[key]); }); WindowGroupTransactionTracker[listenerFn]('end-window-group-transaction', this.endWindowGroupTransactionListener); }; private hookListeners = (): void => { this.updateEvents(true); }; private unHookListeners = (): void => { this.updateEvents(false); }; // Remove all event listeners this instance subscribed on public teardown = (): void => { this.unHookListeners(); }; }
the_stack
import { GraphQLBoolean, GraphQLFieldConfig, GraphQLFieldConfigArgumentMap, GraphQLFieldConfigMap, GraphQLFieldResolver, GraphQLFloat, GraphQLInputObjectType, GraphQLInputType, GraphQLInt, GraphQLList, GraphQLNonNull, GraphQLObjectType, GraphQLOutputType, GraphQLScalarType, GraphQLSchema, GraphQLString, GraphQLTypeResolver, isObjectType } from "graphql"; import { tuple } from "@adpt/utils"; import GraphQLJSON from "graphql-type-json"; import * as ld from "lodash"; import * as util from "util"; import { isRef, Swagger2, Swagger2Operation, Swagger2Parameter, Swagger2Ref, Swagger2Schema } from "../../src/swagger2gql/swagger_types"; import { TypeResolver } from "../../src/swagger2gql/type_resolver"; interface LTypeResolver { input: TypeResolver<GraphQLInputType>; output: TypeResolver<GraphQLOutputType>; param: TypeResolver<Swagger2Parameter>; } function isComplexType(schema: Swagger2Schema): boolean { return schema.type === "object" || schema.type === "array"; } interface Fields<T> { [name: string]: { description?: string; type: T; }; } function buildFieldsFromSchema( baseName: string, schema: Swagger2Schema, tyResolver: LTypeResolver, inputType: true): (() => Fields<GraphQLInputType>) | GraphQLInputType; function buildFieldsFromSchema( baseName: string, schema: Swagger2Schema, tyResolver: LTypeResolver, inputType: false): (() => Fields<GraphQLOutputType>) | GraphQLOutputType; function buildFieldsFromSchema( baseName: string, schema: Swagger2Schema, tyResolver: LTypeResolver, inputType: boolean): (() => Fields<GraphQLInputType | GraphQLOutputType>) | GraphQLInputType | GraphQLOutputType; function buildFieldsFromSchema( baseName: string, schema: Swagger2Schema, tyResolver: LTypeResolver, inputType: boolean): (() => Fields<GraphQLInputType | GraphQLOutputType>) | GraphQLInputType | GraphQLOutputType { const properties = schema.properties; //FIXME(manishv) add a unit test for these two cases below, do not rely on k8s tests if (properties === undefined) return GraphQLJSON; if (Object.keys(properties).length === 0) return GraphQLJSON; return () => { const ret: Fields<GraphQLInputType | GraphQLOutputType> = {}; const required = schema.required ? schema.required : []; for (const propName in properties) { if (propName.startsWith("x-")) continue; // Do not try to process custom extensions if (!Object.hasOwnProperty.call(properties, propName)) continue; const prop = properties[propName]; const nonNull = required.find((val) => val === propName) !== undefined; const baseType = getOrBuildType(baseName + "_" + propName, prop, tyResolver, inputType); const type = nonNull ? new GraphQLNonNull(baseType) : baseType; ret[makeGQLFieldName(propName)] = { description: schema.description, type }; } if (Object.keys(ret).length === 0) { throw new Error("Internal Error: no fields, how'd we get here??"); } return ret; }; } function makeGQLTypeName(swaggerName: string) { //FIXME(manishv) make robust removing all legal swagger characters that are illegal in graphql let gqlName = swaggerName.replace("#/definitions/", ""); gqlName = gqlName.replace(/[\/\.-]/g, "_"); return gqlName; } function makeGQLFieldName(swaggerName: string) { //FIXME(manishv) make robust removing all legal swagger characters that are illegal in graphql const gqlName = swaggerName.replace(/\$/, "dollar_"); return gqlName; } function jsonSchema2GraphQLType( name: string, schema: Swagger2Schema, tyResolver: LTypeResolver, inputType: true): GraphQLInputType; function jsonSchema2GraphQLType( name: string, schema: Swagger2Schema, tyResolver: LTypeResolver, inputType: false): GraphQLOutputType; function jsonSchema2GraphQLType( name: string, schema: Swagger2Schema, tyResolver: LTypeResolver, inputType: boolean): GraphQLInputType | GraphQLOutputType; function jsonSchema2GraphQLType( name: string, schema: Swagger2Schema, tyResolverIn: LTypeResolver, inputType: boolean): GraphQLInputType | GraphQLOutputType { const tyResolver = inputType ? tyResolverIn.input : tyResolverIn.output; if (schema.type === "array") { const items = schema.items; if (!items) throw new Error(`Saw array schema with no items: ${util.inspect(schema)}`); const itemsName = `${name}_items`; if (isRef(items) || !isComplexType(items)) { return new GraphQLList(getOrBuildType(itemsName, items, tyResolverIn, inputType)); } return new GraphQLList(jsonSchema2GraphQLType(itemsName, items, tyResolverIn, inputType)); } const primitive = isPrimitive(schema.type) ? tyResolver.getType(schema.type) : undefined; if (primitive) return primitive; const gqlName = makeGQLTypeName(name) + (inputType ? "_input" : "_output"); const consArgs = { name: gqlName, description: schema.description, }; if (inputType) { const fields = buildFieldsFromSchema(name, schema, tyResolverIn, true); if (!ld.isFunction(fields)) return fields; return new GraphQLInputObjectType({ ...consArgs, fields }); } else { //FIXME(manishv) attach resolvers somewhere const fields = buildFieldsFromSchema(name, schema, tyResolverIn, false); if (!ld.isFunction(fields)) return fields; return new GraphQLObjectType({ ...consArgs, fields }); } } function getDef(schema: Swagger2, tyName: string) { if (!tyName.startsWith("#/definitions/")) return; const defs = schema.definitions; if (!defs) return; const baseTyName = tyName.replace("#/definitions/", ""); return defs[baseTyName]; } function resolveParam(schema: Swagger2, tyName: string) { const params = schema.parameters; if (!params || !tyName.startsWith("#/parameters/")) { throw new Error(`Unable to look up parameter name ${tyName}`); } const baseTyName = tyName.replace("#/parameters/", ""); const param = params[baseTyName]; if (!param) throw new Error(`Parameter name ${tyName} not found`); return param; } function resolveType( swagger: Swagger2, tyName: string, tyResolver: LTypeResolver, input: true): GraphQLInputType; function resolveType( swagger: Swagger2, tyName: string, tyResolver: LTypeResolver, input: false): GraphQLOutputType; function resolveType( swagger: Swagger2, tyName: string, tyResolver: LTypeResolver, input: boolean): GraphQLInputType | GraphQLOutputType; function resolveType(swagger: Swagger2, tyName: string, tyResolver: LTypeResolver, input: boolean) { const schema = getDef(swagger, tyName); if (schema === undefined) throw new Error(`Unable to find type '${tyName}'`); return jsonSchema2GraphQLType(tyName, schema, tyResolver, input); } const primitiveTypes = { integer: GraphQLInt, number: GraphQLFloat, string: GraphQLString, boolean: GraphQLBoolean, _Empty: { input: GraphQLJSON, output: GraphQLJSON } }; function isPrimitive(tyName: string) { return Object.hasOwnProperty.call(primitiveTypes, tyName); } function populateBasicSwaggerTypes(tyResolver: LTypeResolver) { for (const nameI in primitiveTypes) { if (!Object.hasOwnProperty.call(primitiveTypes, nameI)) continue; const name = nameI as keyof (typeof primitiveTypes); const typ = primitiveTypes[name]; const inTyp = "input" in typ ? typ.input : typ; const outTyp = "output" in typ ? typ.output : typ; tyResolver.input.addType(name, inTyp); tyResolver.output.addType(name, outTyp); } } function getOrBuildType( typeName: string, refOrSchema: Swagger2Ref | Swagger2Schema, tyResolver: LTypeResolver, input: true): GraphQLInputType; function getOrBuildType( typeName: string, refOrSchema: Swagger2Ref | Swagger2Schema, tyResolver: LTypeResolver, input: false): GraphQLOutputType; function getOrBuildType( typeName: string, refOrSchema: Swagger2Ref | Swagger2Schema, tyResolver: LTypeResolver, input: boolean): GraphQLInputType | GraphQLOutputType; function getOrBuildType( typeName: string, refOrSchema: Swagger2Ref | Swagger2Schema, tyResolver: LTypeResolver, input: boolean) { const name = isRef(refOrSchema) ? refOrSchema.$ref : typeName; try { const type = input ? tyResolver.input.getType(name) : tyResolver.output.getType(name); if (type) return type; } catch (err) { if (!ld.isError(err) || !err.message.startsWith("Unable to find type")) { throw err; } } if (isRef(refOrSchema)) throw new Error(`Unable to find ref type ${name}`); return jsonSchema2GraphQLType(typeName, refOrSchema, tyResolver, input); } function getParameterInfo( operationId: string, param: Swagger2Parameter, tyResolver: LTypeResolver) { let type: GraphQLInputType; if (param.in === "body") { return { type: getOrBuildType(`${operationId}_body`, param.schema, tyResolver, true), required: param.required ? param.required : false, }; } if (param.type === "array") { const items = param.items; if (!items) throw new Error(`Saw array param with no items: ${util.inspect(param)}`); type = new GraphQLList(getOrBuildType(`${operationId}_${param.name}`, items, tyResolver, true)); } else { type = tyResolver.input.getType(param.type); } return { type, required: param.required ? param.required : false, default: param.default }; } function buildArgsForOperation( operationId: string | undefined, parameters: (Swagger2Parameter | Swagger2Ref)[], tyResolver: LTypeResolver): GraphQLFieldConfigArgumentMap | undefined { if (parameters.length === 0) return; if (operationId == null) throw new Error(`operationId is null`); const ret: GraphQLFieldConfigArgumentMap = {}; for (let param of parameters) { if (isRef(param)) { param = tyResolver.param.getType(param.$ref); } const info = getParameterInfo(operationId, param, tyResolver); const defaultValue = param.in === "body" ? undefined : param.default; ret[makeGQLTypeName(param.name)] = { type: (info.required ? new GraphQLNonNull(info.type) : info.type), defaultValue }; } return ret; } function responseTypeForOperation( op: Swagger2Operation, tyResolver: LTypeResolver): GraphQLOutputType { const okResponse = op.responses["200"]; //FIXME(manishv) deal with other non-error responses here if (okResponse === undefined) return tyResolver.output.getType("_Empty"); const schema = okResponse.schema; if (schema === undefined) return GraphQLJSON; return getOrBuildType(op.operationId + "_Response", schema, tyResolver, false); } function buildQueryField( op: Swagger2Operation, itemParams: (Swagger2Parameter | Swagger2Ref)[] | undefined, tyResolver: LTypeResolver): GraphQLFieldConfig<unknown, unknown> { const iparams = itemParams ? itemParams : []; const oparams = op.parameters ? op.parameters : []; return { type: responseTypeForOperation(op, tyResolver), args: buildArgsForOperation(op.operationId, [...iparams, ...oparams], tyResolver) }; } const supportedOps = tuple("get", "post"); function buildQueryFields( swagger: Swagger2, tyResolver: LTypeResolver): GraphQLFieldConfigMap<unknown, unknown> { const ret: GraphQLFieldConfigMap<unknown, unknown> = {}; for (const swagPath in swagger.paths) { if (!Object.hasOwnProperty.call(swagger.paths, swagPath)) continue; const pathItem = swagger.paths[swagPath]; for (const opType of supportedOps) { const op = pathItem[opType]; if (op === undefined) continue; if (op.operationId === undefined) continue; //FIXME(manishv) should we compute a name here? ret[makeGQLFieldName(op.operationId)] = buildQueryField(op, pathItem.parameters, tyResolver); } } return ret; } function buildQueryObject(swagger: Swagger2): GraphQLObjectType { const tyResolver: LTypeResolver = { input: new TypeResolver<GraphQLInputType>((n) => resolveType(swagger, n, tyResolver, true)), output: new TypeResolver<GraphQLOutputType>((n) => resolveType(swagger, n, tyResolver, false)), param: new TypeResolver<Swagger2Parameter>((n) => resolveParam(swagger, n)), }; populateBasicSwaggerTypes(tyResolver); const fields = buildQueryFields(swagger, tyResolver); return new GraphQLObjectType({ name: "Query", fields }); } export interface UnknownArgs { [name: string]: unknown; } type GQLFieldResolver<ObjectT = unknown, Context = unknown, Args = UnknownArgs> = GraphQLFieldResolver<ObjectT, Context, Args>; type GQLTypeResolver<ObjectT = unknown, Context = unknown> = GraphQLTypeResolver<ObjectT, Context>; type FieldResolverFactory<ObjectT = unknown, Context = unknown, Args = UnknownArgs> = (ty: GraphQLObjectType, field: string, isQueryType: boolean) => GQLFieldResolver<ObjectT, Context, Args> | undefined; type TypeResolverFactory = (ty: GraphQLScalarType, field: undefined, isQueryType: boolean) => GQLTypeResolver | undefined; export interface ResolverFactory<ObjectT = unknown, Context = unknown, Args = UnknownArgs> { fieldResolvers?: FieldResolverFactory<ObjectT, Context, Args>; typeResolvers?: TypeResolverFactory; } function addResolversToFields<ObjectT = unknown, Context = unknown, Args = UnknownArgs>( seen: Set<GraphQLObjectType>, obj: GraphQLObjectType, getResolver: ResolverFactory<ObjectT, Context, Args>, isQuery: boolean = false): void { if (seen.has(obj)) return; seen.add(obj); const fields = obj.getFields(); for (const fieldName in fields) { if (!Object.hasOwnProperty.call(fields, fieldName)) continue; const field = fields[fieldName]; const fieldResolvers = getResolver.fieldResolvers; const resolver = fieldResolvers ? fieldResolvers(obj, fieldName, isQuery) : undefined; field.resolve = resolver; const fieldType = field.type; if (isObjectType(fieldType)) { addResolversToFields(seen, fieldType, getResolver, false); } //FIXME(manishv) How to deal with custom scalar types? } } function addResolversToSchema<ObjectT = unknown, Context = unknown, Args = UnknownArgs>( schema: GraphQLSchema, getResolver: ResolverFactory<ObjectT, Context, Args>): void { const queryType = schema.getQueryType(); if (!queryType) return; addResolversToFields(new Set<GraphQLObjectType>(), queryType, getResolver, true); return; } export function buildGraphQLSchema<ObjectT = unknown, Context = unknown, Args = UnknownArgs>( swagger: Swagger2, getResolver?: ResolverFactory<ObjectT, Context, Args>): GraphQLSchema { const qobj = buildQueryObject(swagger); const schema = new GraphQLSchema({ query: qobj }); if (getResolver) addResolversToSchema(schema, getResolver); return schema; }
the_stack
import express from 'express'; import * as fs from 'fs'; import { Server } from 'http'; import * as path from 'path'; import requests from 'supertest'; import { UIServer } from '../app'; import { loadConfigs } from '../configs'; import { TEST_ONLY as K8S_TEST_EXPORT } from '../k8s-helper'; import { buildQuery, commonSetup, mkTempDir } from './test-helper'; beforeEach(() => { jest.spyOn(global.console, 'info').mockImplementation(); jest.spyOn(global.console, 'log').mockImplementation(); jest.spyOn(global.console, 'debug').mockImplementation(); }); describe('/apps/tensorboard', () => { let app: UIServer; afterEach(() => { if (app) { app.close(); } }); const tagName = '1.0.0'; const commitHash = 'abcdefg'; const { argv } = commonSetup({ tagName, commitHash }); const POD_TEMPLATE_SPEC = { spec: { containers: [ { volumeMounts: [ { name: 'tensorboard', mountPath: '/logs', }, { name: 'data', subPath: 'tensorboard', mountPath: '/data', }, ], }, ], volumes: [ { name: 'tensorboard', persistentVolumeClaim: { claimName: 'logs', }, }, { name: 'data', persistentVolumeClaim: { claimName: 'data', }, }, ], }, }; let k8sGetCustomObjectSpy: jest.SpyInstance; let k8sDeleteCustomObjectSpy: jest.SpyInstance; let k8sCreateCustomObjectSpy: jest.SpyInstance; let kfpApiServer: Server; function newGetTensorboardResponse({ name = 'viewer-example', logDir = 'log-dir-example', tensorflowImage = 'tensorflow:2.0.0', type = 'tensorboard', }: { name?: string; logDir?: string; tensorflowImage?: string; type?: string; } = {}) { return { response: undefined as any, // unused body: { metadata: { name, }, spec: { tensorboardSpec: { logDir, tensorflowImage }, type, }, }, }; } beforeEach(() => { k8sGetCustomObjectSpy = jest.spyOn( K8S_TEST_EXPORT.k8sV1CustomObjectClient, 'getNamespacedCustomObject', ); k8sDeleteCustomObjectSpy = jest.spyOn( K8S_TEST_EXPORT.k8sV1CustomObjectClient, 'deleteNamespacedCustomObject', ); k8sCreateCustomObjectSpy = jest.spyOn( K8S_TEST_EXPORT.k8sV1CustomObjectClient, 'createNamespacedCustomObject', ); }); afterEach(() => { if (kfpApiServer) { kfpApiServer.close(); } }); describe('get', () => { it('requires logdir for get tensorboard', done => { app = new UIServer(loadConfigs(argv, {})); requests(app.start()) .get('/apps/tensorboard') .expect(400, 'logdir argument is required', done); }); it('requires namespace for get tensorboard', done => { app = new UIServer(loadConfigs(argv, {})); requests(app.start()) .get('/apps/tensorboard?logdir=some-log-dir') .expect(400, 'namespace argument is required', done); }); it('does not crash with a weird query', done => { app = new UIServer(loadConfigs(argv, {})); k8sGetCustomObjectSpy.mockImplementation(() => Promise.resolve(newGetTensorboardResponse())); // The special case is that, decodeURIComponent('%2') throws an // exception, so this can verify handler doesn't do extra // decodeURIComponent on queries. const weirdLogDir = encodeURIComponent('%2'); requests(app.start()) .get(`/apps/tensorboard?logdir=${weirdLogDir}&namespace=test-ns`) .expect(200, done); }); function setupMockKfpApiService({ port = 3001 }: { port?: number } = {}) { const receivedHeaders: any[] = []; kfpApiServer = express() .get('/apis/v1beta1/auth', (req, res) => { receivedHeaders.push(req.headers); res.status(200).send('{}'); // Authorized }) .listen(port); return { receivedHeaders, host: 'localhost', port }; } it('authorizes user requests from KFP auth api', done => { const { receivedHeaders, host, port } = setupMockKfpApiService(); app = new UIServer( loadConfigs(argv, { ENABLE_AUTHZ: 'true', ML_PIPELINE_SERVICE_PORT: `${port}`, ML_PIPELINE_SERVICE_HOST: host, }), ); k8sGetCustomObjectSpy.mockImplementation(() => Promise.resolve(newGetTensorboardResponse())); requests(app.start()) .get(`/apps/tensorboard?logdir=some-log-dir&namespace=test-ns`) .set('x-goog-authenticated-user-email', 'accounts.google.com:user@google.com') .expect(200, err => { expect(receivedHeaders).toHaveLength(1); expect(receivedHeaders[0]).toMatchInlineSnapshot(` Object { "accept": "*/*", "accept-encoding": "gzip,deflate", "connection": "close", "host": "localhost:3001", "user-agent": "node-fetch/1.0 (+https://github.com/bitinn/node-fetch)", "x-goog-authenticated-user-email": "accounts.google.com:user@google.com", } `); done(err); }); }); it('uses configured KUBEFLOW_USERID_HEADER for user identity', done => { const { receivedHeaders, host, port } = setupMockKfpApiService(); app = new UIServer( loadConfigs(argv, { ENABLE_AUTHZ: 'true', KUBEFLOW_USERID_HEADER: 'x-kubeflow-userid', ML_PIPELINE_SERVICE_PORT: `${port}`, ML_PIPELINE_SERVICE_HOST: host, }), ); k8sGetCustomObjectSpy.mockImplementation(() => Promise.resolve(newGetTensorboardResponse())); requests(app.start()) .get(`/apps/tensorboard?logdir=some-log-dir&namespace=test-ns`) .set('x-kubeflow-userid', 'user@kubeflow.org') .expect(200, err => { expect(receivedHeaders).toHaveLength(1); expect(receivedHeaders[0]).toHaveProperty('x-kubeflow-userid', 'user@kubeflow.org'); done(err); }); }); it('rejects user requests when KFP auth api rejected', done => { const errorSpy = jest.spyOn(console, 'error'); errorSpy.mockImplementation(); const apiServerPort = 3001; kfpApiServer = express() .get('/apis/v1beta1/auth', (_, res) => { res.status(400).send( JSON.stringify({ error: 'User xxx is not unauthorized to list viewers', details: ['unauthorized', 'callstack'], }), ); }) .listen(apiServerPort); app = new UIServer( loadConfigs(argv, { ENABLE_AUTHZ: 'true', ML_PIPELINE_SERVICE_PORT: `${apiServerPort}`, ML_PIPELINE_SERVICE_HOST: 'localhost', }), ); k8sGetCustomObjectSpy.mockImplementation(() => Promise.resolve(newGetTensorboardResponse())); requests(app.start()) .get(`/apps/tensorboard?logdir=some-log-dir&namespace=test-ns`) .expect( 401, 'User is not authorized to GET VIEWERS in namespace test-ns: User xxx is not unauthorized to list viewers', err => { expect(errorSpy).toHaveBeenCalledTimes(1); expect( errorSpy, ).toHaveBeenCalledWith( 'User is not authorized to GET VIEWERS in namespace test-ns: User xxx is not unauthorized to list viewers', ['unauthorized', 'callstack'], ); done(err); }, ); }); it('gets tensorboard url, version and image', done => { app = new UIServer(loadConfigs(argv, {})); k8sGetCustomObjectSpy.mockImplementation(() => Promise.resolve( newGetTensorboardResponse({ name: 'viewer-abcdefg', logDir: 'log-dir-1', tensorflowImage: 'tensorflow:2.0.0', }), ), ); requests(app.start()) .get(`/apps/tensorboard?logdir=${encodeURIComponent('log-dir-1')}&namespace=test-ns`) .expect( 200, JSON.stringify({ podAddress: 'http://viewer-abcdefg-service.test-ns.svc.cluster.local:80/tensorboard/viewer-abcdefg/', tfVersion: '2.0.0', image: 'tensorflow:2.0.0', }), err => { expect(k8sGetCustomObjectSpy.mock.calls[0]).toMatchInlineSnapshot(` Array [ "kubeflow.org", "v1beta1", "test-ns", "viewers", "viewer-5e1404e679e27b0f0b8ecee8fe515830eaa736c5", ] `); done(err); }, ); }); }); describe('post (create)', () => { it('requires logdir', done => { app = new UIServer(loadConfigs(argv, {})); requests(app.start()) .post('/apps/tensorboard') .expect(400, 'logdir argument is required', done); }); it('requires namespace', done => { app = new UIServer(loadConfigs(argv, {})); requests(app.start()) .post('/apps/tensorboard?logdir=some-log-dir') .expect(400, 'namespace argument is required', done); }); it('requires tfversion or image', done => { app = new UIServer(loadConfigs(argv, {})); requests(app.start()) .post('/apps/tensorboard?logdir=some-log-dir&namespace=test-ns') .expect(400, 'missing required argument: tfversion (tensorflow version) or image', done); }); it('creates tensorboard viewer custom object and waits for it', done => { let getRequestCount = 0; k8sGetCustomObjectSpy.mockImplementation(() => { ++getRequestCount; switch (getRequestCount) { case 1: return Promise.reject('Not found'); case 2: return Promise.resolve( newGetTensorboardResponse({ name: 'viewer-abcdefg', logDir: 'log-dir-1', tensorflowImage: 'tensorflow:2.0.0', }), ); default: throw new Error('only expected to be called twice in this test'); } }); k8sCreateCustomObjectSpy.mockImplementation(() => Promise.resolve()); app = new UIServer(loadConfigs(argv, {})); requests(app.start()) .post( `/apps/tensorboard?logdir=${encodeURIComponent( 'log-dir-1', )}&namespace=test-ns&tfversion=2.0.0`, ) .expect( 200, 'http://viewer-abcdefg-service.test-ns.svc.cluster.local:80/tensorboard/viewer-abcdefg/', err => { expect(k8sGetCustomObjectSpy.mock.calls[0]).toMatchInlineSnapshot(` Array [ "kubeflow.org", "v1beta1", "test-ns", "viewers", "viewer-5e1404e679e27b0f0b8ecee8fe515830eaa736c5", ] `); expect(k8sCreateCustomObjectSpy.mock.calls[0]).toMatchInlineSnapshot(` Array [ "kubeflow.org", "v1beta1", "test-ns", "viewers", Object { "apiVersion": "kubeflow.org/v1beta1", "kind": "Viewer", "metadata": Object { "name": "viewer-5e1404e679e27b0f0b8ecee8fe515830eaa736c5", "namespace": "test-ns", }, "spec": Object { "podTemplateSpec": Object { "spec": Object { "containers": Array [ Object {}, ], }, }, "tensorboardSpec": Object { "logDir": "log-dir-1", "tensorflowImage": "tensorflow/tensorflow:2.0.0", }, "type": "tensorboard", }, }, ] `); expect(k8sGetCustomObjectSpy.mock.calls[1]).toMatchInlineSnapshot(` Array [ "kubeflow.org", "v1beta1", "test-ns", "viewers", "viewer-5e1404e679e27b0f0b8ecee8fe515830eaa736c5", ] `); done(err); }, ); }); it('creates tensorboard viewer with specified image', done => { let getRequestCount = 0; const image = 'gcr.io/deeplearning-platform-release/tf2-cpu.2-4'; k8sGetCustomObjectSpy.mockImplementation(() => { ++getRequestCount; switch (getRequestCount) { case 1: return Promise.reject('Not found'); case 2: return Promise.resolve( newGetTensorboardResponse({ tensorflowImage: image, }), ); default: throw new Error('only expected to be called twice in this test'); } }); k8sCreateCustomObjectSpy.mockImplementation(() => Promise.resolve()); app = new UIServer(loadConfigs(argv, {})); requests(app.start()) .post( `/apps/tensorboard${buildQuery({ logdir: 'log-dir-1', namespace: 'test-ns', image })}`, ) .expect(200, err => { expect( k8sCreateCustomObjectSpy.mock.calls[0][4].spec.tensorboardSpec.tensorflowImage, ).toEqual(image); done(err); }); }); it('creates tensorboard viewer with exist volume', done => { let getRequestCount = 0; k8sGetCustomObjectSpy.mockImplementation(() => { ++getRequestCount; switch (getRequestCount) { case 1: return Promise.reject('Not found'); case 2: return Promise.resolve( newGetTensorboardResponse({ name: 'viewer-abcdefg', logDir: 'Series1:/logs/log-dir-1,Series2:/logs/log-dir-2', tensorflowImage: 'tensorflow:2.0.0', }), ); default: throw new Error('only expected to be called twice in this test'); } }); k8sCreateCustomObjectSpy.mockImplementation(() => Promise.resolve()); const tempPath = path.join(mkTempDir(), 'config.json'); fs.writeFileSync(tempPath, JSON.stringify(POD_TEMPLATE_SPEC)); app = new UIServer( loadConfigs(argv, { VIEWER_TENSORBOARD_POD_TEMPLATE_SPEC_PATH: tempPath }), ); requests(app.start()) .post( `/apps/tensorboard?logdir=${encodeURIComponent( 'Series1:volume://tensorboard/log-dir-1,Series2:volume://tensorboard/log-dir-2', )}&namespace=test-ns&tfversion=2.0.0`, ) .expect( 200, 'http://viewer-abcdefg-service.test-ns.svc.cluster.local:80/tensorboard/viewer-abcdefg/', err => { expect(k8sGetCustomObjectSpy.mock.calls[0]).toMatchInlineSnapshot(` Array [ "kubeflow.org", "v1beta1", "test-ns", "viewers", "viewer-a800f945f0934d978f9cce9959b82ff44dac8493", ] `); expect(k8sCreateCustomObjectSpy.mock.calls[0]).toMatchInlineSnapshot(` Array [ "kubeflow.org", "v1beta1", "test-ns", "viewers", Object { "apiVersion": "kubeflow.org/v1beta1", "kind": "Viewer", "metadata": Object { "name": "viewer-a800f945f0934d978f9cce9959b82ff44dac8493", "namespace": "test-ns", }, "spec": Object { "podTemplateSpec": Object { "spec": Object { "containers": Array [ Object { "volumeMounts": Array [ Object { "mountPath": "/logs", "name": "tensorboard", }, Object { "mountPath": "/data", "name": "data", "subPath": "tensorboard", }, ], }, ], "volumes": Array [ Object { "name": "tensorboard", "persistentVolumeClaim": Object { "claimName": "logs", }, }, Object { "name": "data", "persistentVolumeClaim": Object { "claimName": "data", }, }, ], }, }, "tensorboardSpec": Object { "logDir": "Series1:/logs/log-dir-1,Series2:/logs/log-dir-2", "tensorflowImage": "tensorflow/tensorflow:2.0.0", }, "type": "tensorboard", }, }, ] `); expect(k8sGetCustomObjectSpy.mock.calls[1]).toMatchInlineSnapshot(` Array [ "kubeflow.org", "v1beta1", "test-ns", "viewers", "viewer-a800f945f0934d978f9cce9959b82ff44dac8493", ] `); done(err); }, ); }); it('creates tensorboard viewer with exist subPath volume', done => { let getRequestCount = 0; k8sGetCustomObjectSpy.mockImplementation(() => { ++getRequestCount; switch (getRequestCount) { case 1: return Promise.reject('Not found'); case 2: return Promise.resolve( newGetTensorboardResponse({ name: 'viewer-abcdefg', logDir: 'Series1:/data/log-dir-1,Series2:/data/log-dir-2', tensorflowImage: 'tensorflow:2.0.0', }), ); default: throw new Error('only expected to be called twice in this test'); } }); k8sCreateCustomObjectSpy.mockImplementation(() => Promise.resolve()); const tempPath = path.join(mkTempDir(), 'config.json'); fs.writeFileSync(tempPath, JSON.stringify(POD_TEMPLATE_SPEC)); app = new UIServer( loadConfigs(argv, { VIEWER_TENSORBOARD_POD_TEMPLATE_SPEC_PATH: tempPath }), ); requests(app.start()) .post( `/apps/tensorboard?logdir=${encodeURIComponent( 'Series1:volume://data/tensorboard/log-dir-1,Series2:volume://data/tensorboard/log-dir-2', )}&namespace=test-ns&tfversion=2.0.0`, ) .expect( 200, 'http://viewer-abcdefg-service.test-ns.svc.cluster.local:80/tensorboard/viewer-abcdefg/', err => { expect(k8sGetCustomObjectSpy.mock.calls[0]).toMatchInlineSnapshot(` Array [ "kubeflow.org", "v1beta1", "test-ns", "viewers", "viewer-82d7d06a6ecb1e4dcba66d06b884d6445a88e4ca", ] `); expect(k8sCreateCustomObjectSpy.mock.calls[0]).toMatchInlineSnapshot(` Array [ "kubeflow.org", "v1beta1", "test-ns", "viewers", Object { "apiVersion": "kubeflow.org/v1beta1", "kind": "Viewer", "metadata": Object { "name": "viewer-82d7d06a6ecb1e4dcba66d06b884d6445a88e4ca", "namespace": "test-ns", }, "spec": Object { "podTemplateSpec": Object { "spec": Object { "containers": Array [ Object { "volumeMounts": Array [ Object { "mountPath": "/logs", "name": "tensorboard", }, Object { "mountPath": "/data", "name": "data", "subPath": "tensorboard", }, ], }, ], "volumes": Array [ Object { "name": "tensorboard", "persistentVolumeClaim": Object { "claimName": "logs", }, }, Object { "name": "data", "persistentVolumeClaim": Object { "claimName": "data", }, }, ], }, }, "tensorboardSpec": Object { "logDir": "Series1:/data/log-dir-1,Series2:/data/log-dir-2", "tensorflowImage": "tensorflow/tensorflow:2.0.0", }, "type": "tensorboard", }, }, ] `); expect(k8sGetCustomObjectSpy.mock.calls[1]).toMatchInlineSnapshot(` Array [ "kubeflow.org", "v1beta1", "test-ns", "viewers", "viewer-82d7d06a6ecb1e4dcba66d06b884d6445a88e4ca", ] `); done(err); }, ); }); it('creates tensorboard viewer with not exist volume and return error', done => { const errorSpy = jest.spyOn(console, 'error'); errorSpy.mockImplementation(); k8sGetCustomObjectSpy.mockImplementation(() => { return Promise.reject('Not found'); }); const tempPath = path.join(mkTempDir(), 'config.json'); fs.writeFileSync(tempPath, JSON.stringify(POD_TEMPLATE_SPEC)); app = new UIServer( loadConfigs(argv, { VIEWER_TENSORBOARD_POD_TEMPLATE_SPEC_PATH: tempPath }), ); requests(app.start()) .post( `/apps/tensorboard?logdir=${encodeURIComponent( 'volume://notexistvolume/logs/log-dir-1', )}&namespace=test-ns&tfversion=2.0.0`, ) .expect( 500, `Failed to start Tensorboard app: Cannot find file "volume://notexistvolume/logs/log-dir-1" in pod "unknown": volume "notexistvolume" not configured`, err => { expect(errorSpy).toHaveBeenCalledTimes(1); done(err); }, ); }); it('creates tensorboard viewer with not exist subPath volume mount and return error', done => { const errorSpy = jest.spyOn(console, 'error'); errorSpy.mockImplementation(); k8sGetCustomObjectSpy.mockImplementation(() => { return Promise.reject('Not found'); }); const tempPath = path.join(mkTempDir(), 'config.json'); fs.writeFileSync(tempPath, JSON.stringify(POD_TEMPLATE_SPEC)); app = new UIServer( loadConfigs(argv, { VIEWER_TENSORBOARD_POD_TEMPLATE_SPEC_PATH: tempPath }), ); requests(app.start()) .post( `/apps/tensorboard?logdir=${encodeURIComponent( 'volume://data/notexit/mountnotexist/log-dir-1', )}&namespace=test-ns&tfversion=2.0.0`, ) .expect( 500, `Failed to start Tensorboard app: Cannot find file "volume://data/notexit/mountnotexist/log-dir-1" in pod "unknown": volume "data" not mounted or volume "data" with subPath (which is prefix of notexit/mountnotexist/log-dir-1) not mounted`, err => { expect(errorSpy).toHaveBeenCalledTimes(1); done(err); }, ); }); it('returns error when there is an existing tensorboard with different version', done => { const errorSpy = jest.spyOn(console, 'error'); errorSpy.mockImplementation(); k8sGetCustomObjectSpy.mockImplementation(() => Promise.resolve( newGetTensorboardResponse({ name: 'viewer-abcdefg', logDir: 'log-dir-1', tensorflowImage: 'tensorflow:2.1.0', }), ), ); k8sCreateCustomObjectSpy.mockImplementation(() => Promise.resolve()); app = new UIServer(loadConfigs(argv, {})); requests(app.start()) .post( `/apps/tensorboard?logdir=${encodeURIComponent( 'log-dir-1', )}&namespace=test-ns&tfversion=2.0.0`, ) .expect( 500, `Failed to start Tensorboard app: There's already an existing tensorboard instance with a different version 2.1.0`, err => { expect(errorSpy).toHaveBeenCalledTimes(1); done(err); }, ); }); it('returns existing pod address if there is an existing tensorboard with the same version', done => { k8sGetCustomObjectSpy.mockImplementation(() => Promise.resolve( newGetTensorboardResponse({ name: 'viewer-abcdefg', logDir: 'log-dir-1', tensorflowImage: 'tensorflow:2.0.0', }), ), ); k8sCreateCustomObjectSpy.mockImplementation(() => Promise.resolve()); app = new UIServer(loadConfigs(argv, {})); requests(app.start()) .post( `/apps/tensorboard?logdir=${encodeURIComponent( 'log-dir-1', )}&namespace=test-ns&tfversion=2.0.0`, ) .expect( 200, 'http://viewer-abcdefg-service.test-ns.svc.cluster.local:80/tensorboard/viewer-abcdefg/', done, ); }); }); describe('delete', () => { it('requires logdir', done => { app = new UIServer(loadConfigs(argv, {})); requests(app.start()) .delete('/apps/tensorboard') .expect(400, 'logdir argument is required', done); }); it('requires namespace', done => { app = new UIServer(loadConfigs(argv, {})); requests(app.start()) .delete('/apps/tensorboard?logdir=some-log-dir') .expect(400, 'namespace argument is required', done); }); it('deletes tensorboard viewer custom object', done => { k8sGetCustomObjectSpy.mockImplementation(() => Promise.resolve( newGetTensorboardResponse({ name: 'viewer-abcdefg', logDir: 'log-dir-1', tensorflowImage: 'tensorflow:2.0.0', }), ), ); k8sDeleteCustomObjectSpy.mockImplementation(() => Promise.resolve()); app = new UIServer(loadConfigs(argv, {})); requests(app.start()) .delete(`/apps/tensorboard?logdir=${encodeURIComponent('log-dir-1')}&namespace=test-ns`) .expect(200, 'Tensorboard deleted.', err => { expect(k8sDeleteCustomObjectSpy.mock.calls[0]).toMatchInlineSnapshot(` Array [ "kubeflow.org", "v1beta1", "test-ns", "viewers", "viewer-5e1404e679e27b0f0b8ecee8fe515830eaa736c5", V1DeleteOptions {}, ] `); done(err); }); }); }); });
the_stack
import {app, net} from 'electron'; // Electron app import {stat, mkdir, createWriteStream, readFile as fsReadFile} from 'fs'; import {join, parse} from 'path'; import {parse as parseUrl} from 'url'; import {createHash} from 'crypto'; import * as log from './log'; import { isFileUrl, isHttpUrl, uriToPath, isBase64 } from '../common/main'; import { addPendingAuthRequests, createAuthUI } from './authentication_delegate'; import { AuthCallback, Identity } from '../shapes'; import { getSession } from './core_state'; const path = require('path'); let appQuiting: boolean = false; const expectedStatusCode = /^[23]/; // 2xx & 3xx status codes are okay const fetchMap: Map<string, Promise<any>> = new Map(); const authMap: Map<string, Function> = new Map(); // auth UUID => auth callback app.on('quit', () => { appQuiting = true; }); export const grantAccess = (() => { let queue = Promise.resolve(); return async <T extends (...args: any[]) => any>(cb: T, ...args: Parameters<T>): Promise<ReturnType<T>> => { const prev = queue; queue = prev.then(() => cb(...args)).catch(() => cb(...args)); return <Promise<ReturnType<T>>>queue; }; })(); /** * Downloads a file if it doesn't exist in cache yet. */ export async function cachedFetch(identity: Identity, url: string, callback: (error: null|Error, path?: string) => any): Promise<any> { if (typeof url !== 'string') { callback(new Error(`Bad file url: '${url}'`)); return; } if (appQuiting) { callback(new Error('Runtime is exiting')); return; } if (!isHttpUrl(url)) { if (isFileUrl(url)) { callback(null, uriToPath(url)); } else if ( isBase64(url)) { callback(null, url); } else { // this is C:\whatever\ stat(url, (err: null|Error) => { if (err) { app.vlog(1, `cachedFetch invalid file url ${url}`); callback(new Error(`Invalid file url: '${url}'`)); } else { callback(null, url); } }); } return; } const { uuid } = identity; const appCacheDir = getAppCacheDir(uuid); const filePath = getFilePath(appCacheDir, url); let err: Error; app.vlog(1, `cachedFetch ${url} ${filePath}`); if (fetchMap.has(filePath)) { fetchMap.get(filePath).then(() => callback(null, filePath)).catch(callback); } else { const p = grantAccess(() => new Promise( async (resolve, reject) => { try { await prepDownloadLocation(appCacheDir); await download(identity, url, filePath, appCacheDir); callback(null, filePath); resolve(filePath); } catch (e) { err = e; app.vlog(1, `cachedFetch uuid ${uuid} url ${url} file ${filePath} err ${e.message}`); callback(err, filePath); reject(err); } finally { fetchMap.delete(filePath); } })); fetchMap.set(filePath, p); } } function pathExists (location: string): Promise<boolean> { return new Promise((resolve, reject) => { stat(location, (err: null | Error) => { if (err) { resolve(false); } else { resolve(true); } }); }); } function makeDirectory(location: string) { return new Promise((resolve, reject) => { mkdir(location, (err: null | Error) => { if (err) { app.vlog(1, `cachedFetch makeDirectory error, check EEXIST ${err.message}`); // EEXIST not an error pathExists(location).then(value => value ? resolve() : reject(err)) .catch(() => { app.vlog(1, `cachedFetch makeDirectory error ${err.message}`); reject(err); }); } else { resolve(); } }); }); } async function prepDownloadLocation(appCacheDir: string) { const appCacheDirExists = await pathExists(appCacheDir); if (appCacheDirExists) { return; } const rootCachePath = getRootCachePath(); const cacheRootPathExists = await pathExists(rootCachePath); if (!cacheRootPathExists) { await makeDirectory(rootCachePath); } const cacheAppPathExists = await pathExists(appCacheDir); if (!cacheAppPathExists) { await makeDirectory(appCacheDir); } return; } function getRootCachePath () { const p: any = process; if (p.buildFlags.enableChromium) { return join(app.getPath('userData') , 'Default', 'Cache'); } else { return join(app.getPath('userData') , 'Cache'); } } /** * Generates a folder name for the app to store the file in. */ function getAppCacheDir(appUuid: string): string { const appUuidHash = generateHash(appUuid); const rootCachePath = getRootCachePath(); return join(rootCachePath, appUuidHash); } /** * Generates file name and returns a full path. */ function getFilePath(appCacheDir: string, fileUrl: string): string { const fileUrlHash = generateHash(fileUrl); const fileUrlPathname = parseUrl(fileUrl).pathname; const fileExt = parse(fileUrlPathname).ext; const filename = fileUrlHash + fileExt; // <HASH>.<EXT> return join(appCacheDir, filename); // path/to/<HASH>.<EXT> } /** * Generates SHA-256 hash */ function generateHash(str: string): string { const hash = createHash('sha256'); hash.update(str); return hash.digest('hex'); } function authRequest(url: string, authInfo: any, authCallback: AuthCallback): void { const uuid: string = app.generateGUID(); const identity = { name: uuid, uuid: uuid, resourceFetch: true // not tied to a window }; log.writeToLog(1, `fetchURL login event ${url} uuid ${uuid} ${JSON.stringify(authInfo)}`, true); authMap.set(uuid, authCallback); addPendingAuthRequests(identity, authInfo, authCallback); createAuthUI(identity); } /** * Downloads the file from given url using Resource Fetcher and saves it into specified path */ async function download(identity: Identity, url: string, saveToPath: string, appCacheDir: string): Promise<any> { return new Promise(async (resolve, reject) => { const session = getSession(identity); const request = net.request(url); const binaryWriteStream = createWriteStream(saveToPath, { encoding: 'binary' }); request.once('response', (response: any) => { const { statusCode } = response; app.vlog(1, `cachedFetch download status ${saveToPath} ${statusCode} `); response.setEncoding('binary'); response.on('data', (chunk: any) => { binaryWriteStream.write(chunk, 'binary'); }); response.once('error', (err: Error) => { reject(err); }); response.on('end', () => { binaryWriteStream.once('close', () => { resolve(); }); binaryWriteStream.once('error', (err: Error) => { reject(err); }); binaryWriteStream.end(); if (!expectedStatusCode.test(statusCode)) { const error = new Error(`Failed to download resource. Status code: ${statusCode}`); reject(error); } }); }); request.on('login', (authInfo: any, callback: AuthCallback) => { authRequest(saveToPath, authInfo, callback); }); request.once('error', (err: Error) => { reject(err); }); if (session) { session.cookies.get({}).then((cookies: any) => { const cookiesNameValue = cookies.map((e: any) => `${e.name}=${e.value}`); request.setHeader('cookie', cookiesNameValue); // TODO: Somehow compiler uses Promise defnition that does not have finally. request.end(); }).catch((error: any) => { log.writeToLog(1, 'Error getting session cookies for identity ' + `${identity.uuid}-${identity.name} while trying to fetch a ` + `resource from URL ${url}. Will attempt to fetch the resource ` + `without cookies. Error received: ${error}`, true); // TODO: Somehow compiler uses Promise defnition that does not have finally. request.end(); }); // .finally(() => { request.end(); }); } else { request.end(); } }); } export function fetchURL(url: string, done: (resp: any) => void, onError: (err: Error) => void ): void { log.writeToLog(1, `fetchURL ${url}`, true); const request = net.request(url); request.once('response', (response: any) => { let data = ''; const { statusCode } = response; log.writeToLog(1, `fetchURL statusCode: ${statusCode} for ${url}`, true); if (!expectedStatusCode.test(statusCode)) { const error = new Error(`Failed to download resource. Status code: ${statusCode}`); onError(error); } response.setEncoding('utf8'); response.once('error', (err: Error) => { onError(err); }); response.on('data', (chunk: string) => { data = data.concat(chunk); }); response.on('end', () => { log.writeToLog(1, `Contents from ${url}`, true); log.writeToLog(1, data, true); try { const obj = JSON.parse(data); done(obj); } catch (e) { onError(new Error(`Error parsing JSON from ${url}`)); } }); }); request.on('login', (authInfo: any, callback: AuthCallback) => { authRequest(url, authInfo, callback); }); request.once('error', (err: Error) => { onError(err); }); request.end(); } /** * Fetches a file to disk and then reads it */ export function fetchReadFile(url: string, isJSON: boolean): Promise<string|object> { return new Promise((resolve, reject) => { if (isHttpUrl(url)) { fetchURL(url, resolve, reject); } else if (isFileUrl(url)) { const pathToFile = uriToPath(url); readFile(pathToFile, isJSON) .then(resolve) .catch(reject); } else { stat(url, (err: null|Error) => { if (err) { reject(new Error(`URL protocol is not supported in ${url}`)); } else { readFile(url, isJSON) .then(resolve) .catch(reject); } }); } }); } /** * Reads a file from disk */ export function readFile(pathToFile: string, isJSON: boolean): Promise<string|object> { return new Promise((resolve, reject) => { log.writeToLog(1, `Requested contents from ${pathToFile}`, true); const normalizedPath = path.resolve(pathToFile); log.writeToLog(1, `Normalized path as ${normalizedPath}`, true); fsReadFile(normalizedPath, 'utf-8', (error, data) => { if (error) { reject(error); } else { log.writeToLog(1, `Contents from ${normalizedPath}`, true); log.writeToLog(1, data, true); isJSON ? resolve(JSON.parse(data)) : resolve(data); } }); }); } export function authenticateFetch(uuid: string, username: string, password: string): void { if (authMap.has(uuid)) { log.writeToLog(1, `Auth resource fetch uuid ${uuid} ${username}`, true); authMap.get(uuid).call(null, username, password); authMap.delete(uuid); } else { log.writeToLog(1, `Missing resource auth uuid ${uuid}`, true); } }
the_stack
import { Properties } from '@posthog/plugin-scaffold' import { DateTime } from 'luxon' import { Group, Hub, Person, Team } from '../../../src/types' import { DB } from '../../../src/utils/db/db' import { createHub } from '../../../src/utils/db/hub' import { UUIDT } from '../../../src/utils/utils' import { updatePersonProperties as originalUpdatePersonProperties, upsertGroup, } from '../../../src/worker/ingestion/properties-updater' import { createPromise } from '../../helpers/promises' import { getFirstTeam, resetTestDatabase } from '../../helpers/sql' jest.mock('../../../src/utils/status') let hub: Hub let closeServer: () => Promise<void> let db: DB let team: Team let person: Person const uuid = new UUIDT().toString() const distinctId = 'distinct_id_update_person_properties' const FUTURE_TIMESTAMP = DateTime.fromISO('2050-10-14T11:42:06.502Z') const MIDDLE_TIMESTAMP = DateTime.fromISO('2021-10-14T11:42:06.502Z') const PAST_TIMESTAMP = DateTime.fromISO('2000-10-14T11:42:06.502Z') beforeEach(async () => { ;[hub, closeServer] = await createHub() await resetTestDatabase() db = hub.db team = await getFirstTeam(hub) person = await db.createPerson(PAST_TIMESTAMP, {}, {}, team.id, null, false, uuid, [distinctId]) }) afterEach(async () => { await closeServer() }) describe('updatePersonProperties()', () => { // How we expect this query to behave: // | value exists | method | previous method | previous TS is ___ call TS | write/override // 1 | no | N/A | N/A | N/A | yes // 2 | yes | set | set | before | yes // 3 | yes | set_once | set | before | no // 4 | yes | set | set_once | before | yes // 5 | yes | set_once | set_once | before | no // 6 | yes | set | set | equal | no // 7 | yes | set_once | set | equal | no // 8 | yes | set | set_once | equal | yes // 9 | yes | set_once | set_once | equal | no // 10 | yes | set | set | after | no // 11 | yes | set_once | set | after | no // 12 | yes | set | set_once | after | yes // 13 | yes | set_once | set_once | after | yes // util to get the new props after an update async function updatePersonProperties( properties: Properties, propertiesOnce: Properties, timestamp: DateTime ): Promise<Person['properties'] | undefined> { await originalUpdatePersonProperties(db, team.id, distinctId, properties, propertiesOnce, timestamp) return (await fetchPersonByPersonId(team.id, person.id)).properties } async function fetchPersonByPersonId(teamId: number, personId: number): Promise<Person> { const selectResult = await db.postgresQuery( `SELECT * FROM posthog_person WHERE team_id = $1 AND id = $2`, [teamId, personId], 'fetchPersonByPersonId' ) return selectResult.rows[0] } it('handles empty properties', async () => { const props = await updatePersonProperties({}, {}, PAST_TIMESTAMP) expect(props).toEqual({}) }) it('handles non-existent single property', async () => { const props = await updatePersonProperties({ a: 'a' }, {}, PAST_TIMESTAMP) expect(props).toEqual({ a: 'a' }) }) it('handles non-existent property', async () => { const props = await updatePersonProperties({ a: 'a' }, { b: 'b' }, PAST_TIMESTAMP) expect(props).toEqual({ a: 'a', b: 'b' }) }) it('handles set and set once same key', async () => { const props = await updatePersonProperties({ a: 'a set' }, { a: 'a set_once' }, PAST_TIMESTAMP) expect(props).toEqual({ a: 'a set' }) }) it('handles prop with newer timestamp - rows [2-5]', async () => { // setup initially lower case letters let props = await updatePersonProperties({ r2: 'a', r3: 'b' }, { r4: 'c', r5: 'd' }, PAST_TIMESTAMP) expect(props).toEqual({ r2: 'a', r3: 'b', r4: 'c', r5: 'd' }) // update to upper case letters props = await updatePersonProperties({ r2: 'A', r4: 'C' }, { r3: 'B', r5: 'D' }, FUTURE_TIMESTAMP) expect(props).toEqual({ r2: 'A', r3: 'b', r4: 'C', r5: 'd' }) }) it('handles prop with equal timestamp - rows [6-9] ', async () => { // setup initially lower case letters let props = await updatePersonProperties({ r6: 'a', r7: 'b' }, { r8: 'c', r9: 'd' }, PAST_TIMESTAMP) expect(props).toEqual({ r6: 'a', r7: 'b', r8: 'c', r9: 'd' }) // update to upper case letters props = await updatePersonProperties({ r6: 'A', r8: 'C' }, { r7: 'B', r9: 'D' }, PAST_TIMESTAMP) expect(props).toEqual({ r6: 'a', r7: 'b', r8: 'C', r9: 'd' }) }) it('handles prop with older timestamp - rows [10-13] ', async () => { // setup initially lower case letters let props = await updatePersonProperties({ r10: 'a', r11: 'b' }, { r12: 'c', r13: 'd' }, FUTURE_TIMESTAMP) expect(props).toEqual({ r10: 'a', r11: 'b', r12: 'c', r13: 'd' }) // update to upper case letters props = await updatePersonProperties({ r10: 'A', r12: 'C' }, { r11: 'B', r13: 'D' }, PAST_TIMESTAMP) expect(props).toEqual({ r10: 'a', r11: 'b', r12: 'C', r13: 'D' }) }) it('updates timestamps when newer timestamp equal values for set op', async () => { // set initial properties let props = await updatePersonProperties({ a: 'a' }, { b: 'b' }, PAST_TIMESTAMP) expect(props).toEqual({ a: 'a', b: 'b' }) // no-value change with future timestamp props = await updatePersonProperties({ a: 'a' }, { b: 'b' }, FUTURE_TIMESTAMP) expect(props).toEqual({ a: 'a', b: 'b' }) // value change with middle timestamp is ignored props = await updatePersonProperties({ a: 'aaaa' }, { b: 'bbbb' }, MIDDLE_TIMESTAMP) expect(props).toEqual({ a: 'a', b: 'b' }) }) it('updates timestamps when newer timestamp equal values for set_once', async () => { // set initial properties let props = await updatePersonProperties({ a: 'a' }, { b: 'b' }, FUTURE_TIMESTAMP) expect(props).toEqual({ a: 'a', b: 'b' }) // no-value change with past timestamp props = await updatePersonProperties({ a: 'a' }, { b: 'b' }, PAST_TIMESTAMP) expect(props).toEqual({ a: 'a', b: 'b' }) // value change with middle timestamp is ignored props = await updatePersonProperties({ a: 'aaaa' }, { b: 'bbbb' }, MIDDLE_TIMESTAMP) expect(props).toEqual({ a: 'a', b: 'b' }) }) // TODO test that we can't change the person in the middle of the update }) describe('upsertGroup()', () => { async function upsert(properties: Properties, timestamp: DateTime) { await upsertGroup(hub.db, team.id, 0, 'group_key', properties, timestamp) } async function fetchGroup(): Promise<Group> { return (await hub.db.fetchGroup(team.id, 0, 'group_key'))! } it('creates a row if one does not yet exist with empty properties', async () => { await upsert({}, PAST_TIMESTAMP) const group = await fetchGroup() expect(group.version).toEqual(1) expect(group.group_properties).toEqual({}) expect(group.properties_last_operation).toEqual({}) expect(group.properties_last_updated_at).toEqual({}) }) it('handles initial properties', async () => { await upsert({ foo: 'bar' }, PAST_TIMESTAMP) const group = await fetchGroup() expect(group.version).toEqual(1) expect(group.group_properties).toEqual({ foo: 'bar' }) expect(group.properties_last_operation).toEqual({ foo: 'set' }) expect(group.properties_last_updated_at).toEqual({ foo: PAST_TIMESTAMP.toISO() }) }) it('handles updating properties as new ones come in', async () => { await upsert({ foo: 'bar', a: 1 }, PAST_TIMESTAMP) await upsert({ foo: 'zeta', b: 2 }, FUTURE_TIMESTAMP) const group = await fetchGroup() expect(group.version).toEqual(2) expect(group.group_properties).toEqual({ foo: 'zeta', a: 1, b: 2 }) expect(group.properties_last_operation).toEqual({ foo: 'set', a: 'set', b: 'set' }) expect(group.properties_last_updated_at).toEqual({ foo: FUTURE_TIMESTAMP.toISO(), a: PAST_TIMESTAMP.toISO(), b: FUTURE_TIMESTAMP.toISO(), }) }) it('handles updating when processing old events', async () => { await upsert({ foo: 'bar', a: 1 }, FUTURE_TIMESTAMP) await upsert({ foo: 'zeta', b: 2 }, PAST_TIMESTAMP) const group = await fetchGroup() expect(group.version).toEqual(2) expect(group.group_properties).toEqual({ foo: 'bar', a: 1, b: 2 }) expect(group.properties_last_operation).toEqual({ foo: 'set', a: 'set', b: 'set' }) expect(group.properties_last_updated_at).toEqual({ foo: FUTURE_TIMESTAMP.toISO(), a: FUTURE_TIMESTAMP.toISO(), b: PAST_TIMESTAMP.toISO(), }) }) it('updates timestamp even if properties do not change', async () => { await upsert({ foo: 'bar' }, PAST_TIMESTAMP) await upsert({ foo: 'bar' }, FUTURE_TIMESTAMP) const group = await fetchGroup() expect(group.version).toEqual(2) expect(group.group_properties).toEqual({ foo: 'bar' }) expect(group.properties_last_operation).toEqual({ foo: 'set' }) expect(group.properties_last_updated_at).toEqual({ foo: FUTURE_TIMESTAMP.toISO() }) }) it('does nothing if handling equal timestamps', async () => { await upsert({ foo: '1' }, PAST_TIMESTAMP) await upsert({ foo: '2' }, PAST_TIMESTAMP) const group = await fetchGroup() expect(group.version).toEqual(1) expect(group.group_properties).toEqual({ foo: '1' }) expect(group.properties_last_operation).toEqual({ foo: 'set' }) expect(group.properties_last_updated_at).toEqual({ foo: PAST_TIMESTAMP.toISO() }) }) it('does nothing if nothing gets updated due to timestamps', async () => { await upsert({ foo: 'new' }, FUTURE_TIMESTAMP) await upsert({ foo: 'old' }, PAST_TIMESTAMP) const group = await fetchGroup() expect(group.version).toEqual(1) expect(group.group_properties).toEqual({ foo: 'new' }) expect(group.properties_last_operation).toEqual({ foo: 'set' }) expect(group.properties_last_updated_at).toEqual({ foo: FUTURE_TIMESTAMP.toISO() }) }) it('handles race conditions as inserts happen in parallel', async () => { // :TRICKY: This test is closely coupled with the method under test and we // control the timing of functions called precisely to emulate a race condition const firstFetchIsDonePromise = createPromise() const firstInsertShouldStartPromise = createPromise() jest.spyOn(db, 'insertGroup').mockImplementationOnce(async (...args) => { firstFetchIsDonePromise.resolve() await firstInsertShouldStartPromise.promise return await db.insertGroup(...args) }) // First, we start first update, and wait until first fetch is done (and returns that group does not exist) const firstUpsertPromise = upsert({ a: 1, b: 2 }, PAST_TIMESTAMP) await firstFetchIsDonePromise.promise // Second, we do a another (complete) upsert in-between which creates a row in groups table await upsert({ a: 3 }, FUTURE_TIMESTAMP) // Third, we continue with the original upsert, and wait for the end firstInsertShouldStartPromise.resolve() await firstUpsertPromise // Verify the results const group = await fetchGroup() expect(group.version).toEqual(2) expect(group.group_properties).toEqual({ a: 3, b: 2 }) expect(group.properties_last_operation).toEqual({ a: 'set', b: 'set' }) expect(group.properties_last_updated_at).toEqual({ a: FUTURE_TIMESTAMP.toISO(), b: PAST_TIMESTAMP.toISO() }) }) })
the_stack
import { camelCase } from "lodash-es"; import { i18n } from "@/i18n"; /** * 通用属性 */ export interface CommonProperty { id: string; nopercent?: boolean; dmg?: boolean; noplus?: boolean; negative?: boolean; format?: (v: number) => string; } /** Property Calculate System @summary OPERATORS: base: the base prop value 任意属性的基础值 abs-inc: increase by percent before all 按比例增加 绝对 abs-more: scale by percent before all 按比例缩放 绝对 abs-extra: increase by number before all 可被影响的绝对数值 inc: increase by percent 按比例增加 相对 more: scale by percent 按比例缩放 相对 extra: increase by number after all 不可被影响的绝对数值 * damage inc reducer (毒化者机制) Final Calculate Formula: (base * (1 + abs-inc1 + abs-inc2) * (1 + abs-more1) * (1 + abs-more2) + abs-extra) * (1 + inc1 + inc2) * (1 + more1) * (1 + more2) + extra @example base=30% crit chance abs-inc=90% True Steel abs-extra=30% Arcane Avenger more=165%*2=330% Blood Rush RESULT = (30% * (1 + 90%) + 30%) * (1 + 330%) = 374.1% base=300 Blast layer: Weapon Damage abs-more=-100% Weapon Damage abs-extra=700 Heat layer: Element Damage abs-inc=90% Hellfire RESULT = (300 * (1 - 100%) + 700) * (1 + 90%) = 1330 Heat * ! System Layers * Weapon Damage 武器伤害 基本输入 "基伤" * Element Damage 元素伤害 基本输入 "元素" * Crit Damage 暴击伤害 关联性引用 "暴击" * Enemy Damage 派系伤害 关联性引用 "歧视" * Status Damage 触发伤害 关联性引用 "触发" * Final Damage 总伤害 结算 "总伤" * ? prefix * i abs-extra (percent) * e abs-extra * m more * b extra * ! innate 固有 - 以下属性天生具有不同的等级 * P (穿透) - abs-extra * N (连击) - abs-extra */ export const CommonPropertyDataBase: { [key: string]: CommonProperty } = [ // abs-inc 绝对增加 { id: "0", dmg: true }, // 暴击率 Critical Chance { id: "1", dmg: true }, // 暴击伤害 Critical Damage { id: "2" }, // 触发率 { id: "3" }, // 触发时间 { id: "4", dmg: true }, // 火伤 Heat { id: "5", dmg: true }, // 冰伤 Cold { id: "6", dmg: true }, // 毒伤 Toxin { id: "7", dmg: true }, // 电伤 Electricity { id: "8", dmg: true }, // 冲击 Impact { id: "9", dmg: true }, // 穿刺 Puncture { id: "A", dmg: true }, // 切割 Slash { id: "G", dmg: true }, // G系伤害 Damage to Grineer { id: "I", dmg: true }, // I系伤害 Damage to Infested { id: "C", dmg: true }, // C系伤害 Damage to Corpus { id: "D", dmg: true }, // 伤害 Damage { id: "S", dmg: true }, // 多重 Multishot { id: "R", dmg: true }, // 射速 Fire Rate { id: "L", dmg: true }, // 弹匣 Magazine Capacity { id: "F", dmg: true }, // 装填 { id: "M" }, // 弹药 Ammo Maximum { id: "P", nopercent: true }, // 穿透 // abs-extra 绝对数值增加 { id: "H" }, // 变焦 { id: "V" }, // 弹道 Projectile Flight Speed { id: "Z" }, // 后坐 { id: "K", dmg: true }, // 近战伤害 { id: "T", nopercent: true }, // 范围 Range { id: "J", dmg: true }, // 攻速 Attack Speed { id: "B", nopercent: true }, // 初始连击 Initial Combo { id: "U" }, // 连击效率 Combo Efficiency { id: "O" }, // 连击获取 Combo Count Chance { id: "Q" }, // 连击获取 Combo Count Chance { id: "N", nopercent: true }, // 连击持续时间 Combo Duration // abs-extra 绝对数值增加 { id: "E", dmg: true }, // 滑暴 Critical Hit Chance for Slide Attack { id: "X" }, // 处决 Finisher Damage // convert 伤害转换 { id: "p4", dmg: true }, // 物理转火伤 Physical to Heat { id: "p5", dmg: true }, // 物理转冰伤 Physical to Cold { id: "p6", dmg: true }, // 物理转毒伤 Physical to Toxin { id: "p7", dmg: true }, // 物理转电伤 Physical to Electricity // init more 赤毒武器加成 { id: "b4", dmg: true }, // Initial Heat 初始火伤 { id: "b5", dmg: true }, // Initial Cold 初始冰伤 { id: "b6", dmg: true }, // Initial Toxin 初始毒伤 { id: "b7", dmg: true }, // Initial Electricity 初始电伤 { id: "b8", dmg: true }, // Initial Impact 初始冲击 { id: "b9", dmg: true }, // Initial Puncture 初始穿刺 { id: "bA", dmg: true }, // Initial Slash 初始切割 { id: "bM", dmg: true }, // Initial Magnetic 初始磁力 { id: "bR", dmg: true }, // Initial Radiation 初始辐射 // 战甲 { id: "h" }, // Health { id: "s" }, // Shield { id: "a" }, // Amror { id: "e" }, // Energy { id: "f" }, // Sprint { id: "r" }, // ShieldRecharge { id: "t" }, // AbilityStrength S=>t { id: "u" }, // AbilityDuration D=>u { id: "x" }, // AbilityEfficiency E=>x { id: "g" }, // AbilityRange R=>g { id: "c" }, // CastSpeed { id: "k" }, // KnockdownResistance { id: "y" }, // KnockdownRecovery h=>y { id: "l" }, // Slide { id: "i" }, // Friction F=>i { id: "v" }, // ParkourVelocity { id: "z" }, // QuickThinking { id: "rg" }, // Rage A=>rg { id: "hc", nopercent: true }, // HealthConversion { id: "ec" }, // EnergyConversion { id: "tr" }, // TauResist { id: "as" }, // AuraStrength { id: "ae" }, // AuraEffectiveness { id: "at" }, // AimGlideWallLatchTime { id: "er", nopercent: true }, // EnemyRadar { id: "lr", nopercent: true }, // LootRadar { id: "ea", nopercent: true }, // extra armor { id: "fsr" }, // fully shield recovery { id: "psr" }, // persecond shield recovery { id: "phr" }, // persecond health recovery { id: "ivb" }, // invisible { id: "ivc" }, // invulnerable { id: "ehb" }, // extra health orb { id: "eeb" }, // extra energy orb { id: "rgd" }, // range knockdown { id: "tt" }, // team AbilityStrength { id: "ab" }, // Resistance to that Damage Type for 10s. Stacks up to 90%. { id: "cc" }, // Counter Chance { id: "ddb" }, // Damage during Bleedout { id: "pr" }, // Toxin Resistance { id: "rr" }, // Radiation Resistance { id: "drk" }, // Damage Resistance on Knockdown { id: "cr" }, // Cold Resistance { id: "fr" }, // Heat Resistance { id: "ir" }, // Electricity Resistance { id: "ll" }, // chance to unlock locked lockers { id: "br" }, // Bleedout Reduction { id: "apc" }, // Parry Angle { id: "sr" }, // Faster Stagger Recovery { id: "fl" }, // Flight Speed (Archwing) { id: "es" }, // Energy Rate (Aura) { id: "ap" }, // Ammo Pickup (Aura) { id: "ev" }, // Evasion { id: "eq" }, // Convert Health/Energy Ball { id: "m" }, // Movement Speed when Aiming { id: "wc" }, // Shield Resistance to Ice Levels { id: "adr" }, // Reduces damage by |val|% when Airborne. { id: "her" }, // EnergyOnHeadshotRifle { id: "ens" }, // Enemy Shield { id: "ena" }, // Enemy Amror { id: "ref" }, // % Damage taken is reflected when Blocking attacks while Channeling. { id: "hps", nopercent: true }, // 每秒生命回复 Heal Rate/s { id: "eac" }, // % Hit Chance { id: "esp" }, // % Speed { id: "ovs", dmg: true }, // % Overall Strength { id: "ovr", dmg: true }, // % Overall Range { id: "res", dmg: true }, // Damage Resistance // 集团 { id: "vp", nopercent: true }, // 'Purity' { id: "vt", nopercent: true }, // 'Truth' { id: "ve", nopercent: true }, // 'Entropy' { id: "vs", nopercent: true }, // 'Sequence' { id: "vj", nopercent: true }, // 'Justice' { id: "vb", nopercent: true }, // 'Blight' // ======================== // Special 特殊 // inc { id: "rN" }, // 相对连击时间 // abs-extra 绝对加法 { id: "erd", dmg: true }, // 辐射伤害 { id: "ecd", dmg: true }, // 腐蚀伤害 { id: "eed", dmg: true }, // 电击伤害 { id: "efd", dmg: true }, // 火焰伤害 { id: "etd", dmg: true }, // 毒素伤害 { id: "eid", dmg: true }, // Initial damage 初始伤害 { id: "e4", dmg: true, nopercent: true }, // Initial Heat 初始火伤 { id: "e5", dmg: true, nopercent: true }, // Initial Cold 初始冰伤 { id: "e6", dmg: true, nopercent: true }, // Initial Toxin 初始毒伤 { id: "e7", dmg: true, nopercent: true }, // Initial Electricity 初始电伤 { id: "e8", dmg: true, nopercent: true }, // Initial Impact 初始冲击 { id: "e9", dmg: true, nopercent: true }, // Initial Puncture 初始穿刺 { id: "eA", dmg: true, nopercent: true }, // Initial Slash 初始切割 { id: "eh", dmg: true, nopercent: true }, // extra health 生命点数 // extra { id: "bL", dmg: true, nopercent: true }, // 基础弹匣 Magazine Capacity // abs-extra (percent) 绝对加法 (百分比) { id: "i0", dmg: true }, // 暴击率 Critical Chance { id: "i1", dmg: true }, // 暴击伤害 Critical Damage { id: "i2" }, // 触发率 { id: "i3" }, // 触发时间 { id: "iG", dmg: true }, // G系伤害 Damage to Grineer { id: "iI", dmg: true }, // I系伤害 Damage to Infested { id: "iC", dmg: true }, // C系伤害 Damage to Corpus { id: "iD", dmg: true, nopercent: true }, // 伤害 Damage { id: "iS", dmg: true, nopercent: true }, // 多重 Multishot { id: "iR", dmg: true }, // 射速 Fire Rate { id: "iF", dmg: true }, // 装填 { id: "iM" }, // 弹药 Ammo Maximum { id: "iP" }, // 穿透 { id: "iH" }, // 变焦 { id: "iV" }, // 弹道 Projectile Flight Speed { id: "iZ" }, // 后坐 { id: "iK", dmg: true }, // 近战伤害 { id: "iJ", dmg: true }, // 攻速 Attack Speed { id: "iE", dmg: true }, // 滑暴 Critical Hit Chance for Slide Attack { id: "iX" }, // 处决 Finisher Damage // rel-inc extend 扩展相对增加 { id: "e0", dmg: true }, // 总暴击率 { id: "e1", dmg: true }, // 总暴击伤害 { id: "e2" }, // 总触发率 { id: "e3" }, // 总触发时间 { id: "hd", dmg: true }, // 重击伤害 { id: "wu" }, // 重击速度 { id: "ccb" }, // 格挡获取连击数 { id: "aed", dmg: true }, // 全派系伤害 { id: "od", dmg: true }, // O系伤害 { id: "fsb", dmg: true }, // 首发伤害 Damage on first shot in Magazine { id: "da", dmg: true }, // 正中红心 Dead Aim { id: "oad", dmg: true }, // 最终伤害 { id: "ds", dmg: true }, // 偷袭伤害 { id: "sd", dmg: true }, // 触发伤害 { id: "smd", dmg: true }, // 对Sentient伤害 Damage to Sentients { id: "dmg", dmg: true }, // 伤害 { id: "cwh", dmg: true }, // 爆头暴击率 { id: "rse", dmg: true, nopercent: true }, // Weapon Range for 4s on Status Effect { id: "lsb", dmg: true }, // Bonus Damage on final shot. Requires Magazine 6 or higher. 末发伤害 { id: "edm", dmg: true }, // Extra Damage against a Marked Enemy 对标记敌人增伤 { id: "bsk", dmg: true }, // 最终攻速 Attack Speed (Max: 75%) for 4s on Critical Hit { id: "ce", dmg: true }, // 暴击强化 { id: "ac", dmg: true, noplus: true }, // 暴击造成切割触发 chance to apply <DT_SLASH> on Critical { id: "bldr", dmg: true }, // 连击暴击率 Critical Chance stacks with Combo Multiplier { id: "fca" }, // Faster Charge Attack { id: "esc", dmg: true, nopercent: true }, // extra status count { id: "ess", dmg: true }, // extra slash state { id: "hm", dmg: true }, // 爆头倍率 to Headshot Multiplier { id: "range", nopercent: true }, // 射程 { id: "red", dmg: true }, // 连击额外伤害 Final Damage stacks with Combo Multiplier // ======================== // Other 其他 { id: "acc" }, // 精准 { id: "stick" }, // 壁面附着 { id: "aimm" }, // 瞄准移速 { id: "ckm" }, // 移动速度 { id: "kb", nopercent: true, noplus: true }, // 死亡爆炸 { id: "kbr", noplus: true }, // 死亡爆炸 (percent) { id: "brad" }, // 爆炸半径 Blast Radius { id: "hr" }, // 拔枪速度 Holster Speed { id: "am" }, // 弹药转换 { id: "lal" }, // 自动装填 { id: "spr" }, // 扩散 Spread { id: "slc" }, // 消音 Reduces the chance an enemy will hear gunfire by { id: "bnc", nopercent: true }, // 反弹 Bounce { id: "exp", dmg: true }, // 爆炸 Chance to Explode (Use with Caution) { id: "ls" }, // 生命窃取 Life Steal { id: "sccm" }, // 连击触发几率 Status Chance per Combo Multiplier { id: "ccws" }, // 切割增加连击数 chance to increase Melee Combo Counter when <DT_SLASH>Slash Status deals damage. { id: "co", dmg: true }, // 异常状态增加伤害 Melee Damage per Status Type affecting the target. { id: "ga", dmg: true }, // 异常状态增加总伤害 Final Damage per Status Type affecting the target. { id: "gdr", nopercent: true }, // 嘲讽 { id: "hlr", nopercent: true, noplus: true }, // 治愈 { id: "exd", nopercent: true }, // 额外伤害 { id: "amr" }, // +护甲 { id: "msd" }, // 近战震波伤害 { id: "fs" }, // 飞行速度 (战刃) { id: "ld", nopercent: true }, // Extra Damage on Melee Attacks, or Lethal Damage on Finishers. { id: "ar", nopercent: true }, // + Range (nopercent) { id: "cd", dmg: true }, // Critical Chance and Damage when Aiming { id: "ca" }, // 蓄力速度 Charge Rate { id: "ck" }, // Chance to Resist Staggers/Knockdowns when Aiming { id: "sds" }, // Status Duration on Self { id: "but" }, // Shots now bounce up to 1x and travel 5% further. { id: "el" }, // Grenades tether up to 2 enemies from 4m away. { id: "sb" }, // Self-damage { id: "si", nopercent: true }, // Impact damage reduces enemy armor by 1. { id: "rc" }, // Fire/Charge Rate { id: "scan" }, // Fatal strikes against an enemy also perform a Codex Scan { id: "apd" }, // first Pellet Damage additionally { id: "ccl", noplus: true }, // crit chance lock { id: "erc" }, // energy recovery { id: "rvs" }, // Revive Speed { id: "dgs" }, // Dodge Speed { id: "hl" }, // Health Link { id: "sl" }, // Shield Link { id: "al" }, // Amror Link { id: "bl" }, // Bleedout Link { id: "vl" }, // Lifesteal Link { id: "cl" }, // Critical Chance Link { id: "rl" }, // Companion Lifesteal-Link { id: "pl" }, // Status-Link { id: "gd", noplus: true }, // Guardian { id: "rh", noplus: true }, // Medi-Ray { id: "cs", noplus: true, nopercent: true }, // Sanctuary { id: "ws" }, // Warframe Shield { id: "wr" }, // Warframe ShieldRecharge { id: "ava" }, // Warframe Jump Height { id: "reg", noplus: true, format: v => Math.max(1, Math.round(v)) }, // Warframe Jump Height { id: "rmh", noplus: true }, // Regen { id: "chf", noplus: true }, // Regen { id: "rd", noplus: true }, // Reflects +1000% Damage // no parameter 无参数 { id: "sp" }, // 魔改 // ======================== // Amp damage convert { id: "vte", dmg: true }, // to Electricity { id: "vtv", dmg: true }, // to Viral { id: "vtp", dmg: true }, // to Puncture { id: "vth", dmg: true }, // to Heat ].reduce((a, b) => ((a[b.id] = b), a), {}); const HeadTags = { "+": "prop.fullName.teamPlus", "-": "prop.fullName.companionPlus", }; /** * 带值通用属性 */ export class ValuedProperty { static parse([vn, vv]: [string, number]): ValuedProperty { const pn = HeadTags[vn[0]] ? vn.substr(1) : vn; let prop = CommonPropertyDataBase[pn]; if (prop) { return new ValuedProperty(prop, vv, HeadTags[vn[0]]); } return { id: vn, displayValue: String(vv), get fullString() { let rn = pn; if (vn.endsWith(" Augment")) { const skillName = "skill." + camelCase(vn.substr(0, vn.length - 8)); return i18n.t("prop.fullName.augment", [i18n.te(skillName) ? i18n.t(skillName) : vn.substr(0, vn.length - 8)]); } const ikey = `prop.fullName.${camelCase(pn)}`; if (i18n.te(ikey)) rn = i18n.t(ikey, [vv]); if (vn.startsWith("+")) rn = i18n.t("prop.fullName.teamPlus", [rn]); if (vn.startsWith("-")) rn = i18n.t("prop.fullName.companionPlus", [rn]); return rn; }, get shortString() { if (vn.endsWith(" Augment")) { const skillName = "skill." + camelCase(vn.substr(0, vn.length - 8)); return i18n.t("prop.fullName.augment", [i18n.te(skillName) ? i18n.t(skillName) : vn.substr(0, vn.length - 8)]); } const ikey = `prop.shortName.${camelCase(vn)}`; if (i18n.te(ikey)) return i18n.t(ikey, [vv]); return vn; }, value: vv, prop: { id: vn }, }; } /** 属性原型 */ prop: CommonProperty; /** 属性值 */ value: number; plus?: string; constructor(prop: CommonProperty, value: number, plus?: string) { this.prop = prop; this.value = value; this.plus = plus; } /** * 属性值显示 */ get displayValue() { if (this.prop.format) return this.prop.format(this.value); let dv = this.prop.nopercent ? this.value.toString() : +this.value.toFixed(1) + "%"; if (!this.prop.noplus && dv[0] != "-") return "+" + dv; return dv; } get id() { return this.prop.id; } /** * 完整属性显示 */ get fullString() { let rn = (i18n.te("prop.fullName." + this.prop.id) && i18n.t("prop.fullName." + this.prop.id, [this.displayValue])) || this.prop.id; if (this.plus) rn = i18n.t(this.plus, [rn]); return rn; } /** * 属性简称 */ get shortString() { return (i18n.te("prop.shortName." + this.prop.id) && i18n.t("prop.shortName." + this.prop.id)) || this.prop.id; } }
the_stack
import * as React from 'react' import {WebOfTrustVerificationType} from '../../constants/types/more' import * as Constants from '../../constants/profile' import * as UsersConstants from '../../constants/users' import * as Kb from '../../common-adapters' import * as Styles from '../../styles' import * as Container from '../../util/container' import * as RouteTreeGen from '../../actions/route-tree-gen' import * as Tracker2Types from '../../constants/types/tracker2' import {SiteIcon} from '../../profile/generic/shared' import * as ProfileGen from '../../actions/profile-gen' import * as UsersGen from '../../actions/users-gen' import * as Tracker2Constants from '../../constants/tracker2' import * as RPCTypes from '../../constants/types/rpc-gen' import sortBy from 'lodash/sortBy' // Keep in sync with server limits: https://github.com/keybase/proofs/blob/master/src/wot.iced const statementLimit = 700 const otherLimit = 90 export type Question1Props = { error?: string initialVerificationType: WebOfTrustVerificationType onSubmit: (_: Question1Answer) => void proofs: Array<Proof> voucheeUsername: string } export type Question1Answer = { otherText: string proofs: Array<RPCTypes.WotProof> verificationType: WebOfTrustVerificationType } type ReviewAction = 'accept' | 'propose' | 'reject' export type ReviewProps = { disabled?: boolean // disable all buttons error?: string firstDraft: boolean onAccept?: () => void onProposeEdits?: () => void onReject?: () => void otherText: string proofs?: Array<ProofLite> statement: string verificationType: WebOfTrustVerificationType voucheeUsername: string voucherUsername: string waiting?: ReviewAction } export type Question2Props = { error?: string onBack: () => void onSubmit: ({statement: string}) => void voucheeUsername: string waiting?: boolean } type WotModalProps = { children: React.ReactNode error?: string onBack?: () => void onSubmit: () => void scrollViewRef?: React.Ref<Kb.ScrollView> submitDisabled?: boolean submitLabel: string submitWaiting?: boolean } export type Proof = ProofLite & { wotProof: RPCTypes.WotProof } type ProofLite = { type: string value: string siteIcon?: Tracker2Types.SiteIconSet | null siteIconDarkmode?: Tracker2Types.SiteIconSet | null } type Checkboxed = { checked: boolean onCheck: (_: boolean) => void } export const Question1Wrapper = ( props: Container.RouteProps<{ username: string guiID: string }> ) => { const voucheeUsername = Container.getRouteProps(props, 'username', '') const guiID = Container.getRouteProps(props, 'guiID', '') const nav = Container.useSafeNavigation() const dispatch = Container.useDispatch() let error = Container.useSelector(state => state.profile.wotAuthorError) if (!error && !voucheeUsername) { error = 'Routing missing username.' } const {username: trackerUsername, assertions} = Container.useSelector(state => Tracker2Constants.getDetails(state, voucheeUsername) ) let proofs: Proof[] = [] if (trackerUsername === voucheeUsername) { if (assertions) { // Pull proofs from the profile the user was just looking at. // Only take passing proofs that have a `wotProof` field filled by the service. proofs = sortBy( Array.from(assertions, ([_, assertion]) => assertion), x => x.priority ).reduce<Array<Proof>>((acc, x) => { if (x.wotProof && x.state === 'valid') { acc.push({...x, wotProof: x.wotProof}) } return acc }, []) } } else { error = `Proofs not loaded: ${trackerUsername} != ${voucheeUsername}` } const onSubmit = (answer: Question1Answer) => { dispatch( nav.safeNavigateAppendPayload({ path: [ { props: {guiID, question1Answer: answer, username: voucheeUsername}, selected: 'profileWotAuthorQ2', }, ], }) ) } return ( <Question1 error={error} initialVerificationType={'in_person'} onSubmit={onSubmit} proofs={proofs} voucheeUsername={voucheeUsername} /> ) } export const Question2Wrapper = ( props: Container.RouteProps<{ username: string guiID: string question1Answer: Question1Answer }> ) => { const voucheeUsername = Container.getRouteProps(props, 'username', '') const guiID = Container.getRouteProps(props, 'guiID', '') const question1Answer = Container.getRoutePropsOr(props, 'question1Answer', 'error') const nav = Container.useSafeNavigation() const dispatch = Container.useDispatch() let error = Container.useSelector(state => state.profile.wotAuthorError) if (!error && !voucheeUsername) { error = 'Routing missing username.' } if (!error && question1Answer === 'error') { error = 'Routing missing q1 answer.' } const waiting = Container.useAnyWaiting(Constants.wotAuthorWaitingKey) const onSubmit = ({statement}: {statement: string}) => { if (question1Answer === 'error') { return } const {otherText, proofs, verificationType} = question1Answer dispatch( ProfileGen.createWotVouch({ guiID, otherText, proofs, statement, username: voucheeUsername, verificationType, }) ) } const onBack = () => { dispatch(ProfileGen.createWotVouchSetError({error: ''})) dispatch(nav.safeNavigateUpPayload()) } return ( <Question2 error={error} onBack={onBack} onSubmit={onSubmit} voucheeUsername={voucheeUsername} waiting={waiting} /> ) } export const ReviewWrapper = ( props: Container.RouteProps<{ sigID: string // sigID of the vouch. }> ) => { const sigID = Container.getRouteProps(props, 'sigID', '') const dispatch = Container.useDispatch() const voucheeUsername = Container.useSelector(state => state.config.username) const details = Container.useSelector(state => Tracker2Constants.getDetails(state, voucheeUsername)) const wotEntry = details.webOfTrustEntries?.find(entry => entry.proofID === sigID) const error = Container.useSelector(state => state.profile.wotAuthorError) const [lastAction, setLastAction] = React.useState<ReviewAction | undefined>(undefined) const isWaiting = Container.useAnyWaiting(UsersConstants.wotReactWaitingKey) let waiting = isWaiting ? lastAction : undefined let fatalError = '' if (!sigID) { fatalError = 'Routing missing ID.' } if (!wotEntry) { fatalError = 'Statement not found.' } if (fatalError || !wotEntry) { return ( <Review disabled={true} error={fatalError} firstDraft={false} otherText="" statement="" verificationType="in_person" voucheeUsername={voucheeUsername} voucherUsername="_" /> ) } const onReact = (accept: boolean) => () => { setLastAction(accept ? 'accept' : 'reject') // TODO PICNIC-1150 pin reactions to the sigID dispatch( UsersGen.createWotReact({ fromModal: true, reaction: accept ? RPCTypes.WotReactionType.accept : RPCTypes.WotReactionType.reject, sigID, voucher: wotEntry.attestingUser, }) ) } const onProposeEdits = () => { // TODO PICNIC-1145 hook this up setLastAction('propose') dispatch(ProfileGen.createWotVouchSetError({error: 'proposing edits not implemented'})) } return ( <Review error={error} firstDraft={true} // TODO PICNIC-1171 plug this bit in onAccept={onReact(true)} onProposeEdits={onProposeEdits} onReject={onReact(false)} otherText={wotEntry.otherText ?? ''} proofs={wotEntry.proofs || []} statement={wotEntry.attestation} verificationType={wotEntry.verificationType} voucheeUsername={voucheeUsername} voucherUsername={wotEntry.attestingUser} waiting={waiting} /> ) } export const Question1 = (props: Question1Props) => { const scrollViewRef = React.useRef<Kb.ScrollView>(null) const [selectedVerificationType, _setVerificationType] = React.useState<WebOfTrustVerificationType>( props.initialVerificationType ) const [otherText, setOtherText] = React.useState('') const [proofs, clearCheckboxes] = useCheckboxesState(props.proofs, () => _setVerificationType('proofs')) const setVerificationType = newVerificationType => { if (newVerificationType === selectedVerificationType) { return } if (newVerificationType !== 'proofs') { clearCheckboxes() } if (newVerificationType === 'other' && scrollViewRef.current) { const hackDelay = 50 // With no delay scrolling undershoots. Perhaps the bottom component doesn't exist yet. setTimeout(() => scrollViewRef.current?.scrollToEnd({animated: true}), hackDelay) } _setVerificationType(newVerificationType) } const submitDisabled = (selectedVerificationType === 'other' && otherText === '') || (selectedVerificationType === 'proofs' && !proofs.some(x => x.checked)) const onSubmit = () => { props.onSubmit({ otherText: selectedVerificationType === 'other' ? otherText : '', proofs: proofs.filter(({checked}) => checked).map(proof => proof.wotProof), verificationType: selectedVerificationType, }) } return ( <WotModal error={props.error} onSubmit={onSubmit} scrollViewRef={scrollViewRef} submitDisabled={submitDisabled} submitLabel="Continue" > <Kb.Box2 direction="horizontal" alignSelf="stretch" alignItems="center" style={Styles.collapseStyles([styles.sidePadding, styles.id])} > <Kb.Avatar username={props.voucheeUsername} size={48} /> <Kb.Text type="BodySemibold" style={styles.idInner}> How do you know{' '} <Kb.ConnectedUsernames usernames={props.voucheeUsername} type="BodyBold" inline={true} colorFollowing={true} colorBroken={true} />{' '} is the person you think they are? </Kb.Text> </Kb.Box2> {Constants.choosableWotVerificationTypes .filter(loopVerificationType => loopVerificationType !== 'proofs' || proofs.length) .map(loopVerificationType => ( <VerificationChoice key={loopVerificationType} voucheeUsername={props.voucheeUsername} verificationType={loopVerificationType} selected={selectedVerificationType === loopVerificationType} onSelect={() => setVerificationType(loopVerificationType)} > {/* For 'proofs': Show a row for each proof */} {loopVerificationType === 'proofs' && proofList(selectedVerificationType === 'proofs', proofs)} {/* For 'other': Show an input area when active */} {loopVerificationType === 'other' && selectedVerificationType === loopVerificationType && ( <OtherInput otherText={otherText} setOtherText={setOtherText} /> )} </VerificationChoice> ))} </WotModal> ) } export const Question2 = (props: Question2Props) => { const [statement, setStatement] = React.useState('') const submitDisabled = statement === '' const onSubmit = () => props.onSubmit({statement}) return ( <WotModal error={props.error} onBack={props.onBack} onSubmit={onSubmit} submitDisabled={submitDisabled} submitWaiting={props.waiting} submitLabel="Submit" > <Kb.Box2 direction="vertical" alignSelf="stretch" alignItems="stretch" style={Styles.collapseStyles([styles.sidePadding, styles.outside])} > <Kb.Box2 direction="horizontal" alignItems="center" style={styles.outsideBox}> <Kb.Avatar username={props.voucheeUsername} size={48} /> <Kb.Text type="BodySemibold" style={styles.idInner}> How do you know{' '} <Kb.ConnectedUsernames usernames={props.voucheeUsername} type="BodyBold" inline={true} colorFollowing={true} colorBroken={true} />{' '} outside of Keybase? </Kb.Text> </Kb.Box2> <Kb.LabeledInput placeholder="Your claim" hoverPlaceholder={'Write how you met them and what experiences you shared with them.'} multiline={true} rowsMin={9} autoFocus={!Styles.isMobile} maxLength={statementLimit} value={statement} onChangeText={setStatement} /> <Kb.Text type="BodySmall" style={styles.approveNote}> {props.voucheeUsername} will be able to approve or suggest edits to what you’ve written. </Kb.Text> </Kb.Box2> </WotModal> ) } export const Review = (props: ReviewProps) => { const dispatch = Container.useDispatch() const [checkedVerificationType, setCheckedVerificationType] = React.useState(false) const [checkedStatement, setCheckedStatement] = React.useState(false) const canAccept = checkedVerificationType && checkedStatement const onClose = () => { dispatch(ProfileGen.createWotVouchSetError({error: ''})) dispatch(RouteTreeGen.createClearModals()) } const buttonState = (button: ReviewAction) => { // When waiting, spinner the relevant button and disable the others. if (props.waiting === button) { return {waiting: true} } else if (props.waiting || props.disabled) { return {disabled: true} } if (button === 'accept' && !canAccept) { return {disabled: true} } return {} } return ( <Kb.Modal onClose={onClose} header={{ leftButton: Styles.isMobile && ( <Kb.Text onClick={onClose} type="BodyPrimaryLink"> Cancel </Kb.Text> ), title: 'Review claim', }} mode="DefaultFullHeight" banners={[ !!props.error && ( <Kb.Banner key="error" color="red"> <Kb.BannerParagraph bannerColor="red" content={props.error} /> </Kb.Banner> ), ]} footer={{ content: ( <Kb.ButtonBar align="center" direction="column" fullWidth={true} style={styles.buttonBar}> <Kb.Button mode="Secondary" type="Default" fullWidth={true} label={`No, propose ${props.firstDraft ? '' : 'more '}edits`} onClick={props.onProposeEdits} {...buttonState('propose')} /> <Kb.Button mode="Secondary" type="Danger" fullWidth={true} label="No, reject" onClick={props.onReject} {...buttonState('reject')} /> </Kb.ButtonBar> ), style: {paddingBottom: Styles.globalMargins.xtiny, paddingTop: Styles.globalMargins.xxtiny}, }} > <Kb.Box2 direction="vertical" alignSelf="stretch" alignItems="stretch" style={Styles.collapseStyles([styles.sidePadding, styles.outside])} > <Kb.Box2 direction="horizontal" alignItems="center" alignSelf="stretch" style={styles.outsideBox}> {props.firstDraft ? ( <Kb.Text type="BodyBig" style={styles.reviewInstruction}> Review what{' '} <Kb.ConnectedUsernames usernames={props.voucherUsername} type="BodyBig" inline={true} colorFollowing={true} colorBroken={true} />{' '} wrote about you: </Kb.Text> ) : ( <Kb.Text type="BodyBig" style={styles.reviewInstruction}> Review{' '} <Kb.ConnectedUsernames usernames={props.voucherUsername} type="BodyBig" inline={true} colorFollowing={true} colorBroken={true} /> 's edits: </Kb.Text> )} </Kb.Box2> <Kb.Box2 direction="horizontal" alignSelf="stretch" alignItems="center"> <Kb.Box2 key="colorbar" direction="vertical" alignSelf="stretch" style={{ backgroundColor: verificationTypeColors[props.verificationType] ?? Styles.globalColors.white, flexShrink: 0, marginRight: Styles.globalMargins.small, width: 4, }} /> <Kb.Box2 direction="vertical" alignSelf="stretch" style={Styles.globalStyles.flexOne}> <Kb.Box2 direction="horizontal" alignSelf="stretch" alignItems="center"> <Kb.Text type="Body" style={Styles.globalStyles.flexOne}> {props.verificationType === 'other' ? props.otherText : verificationTypeText(props.verificationType, props.voucheeUsername)} </Kb.Text> </Kb.Box2> {props.verificationType === 'proofs' && props.proofs && props.proofs.map(proof => ( <Kb.Box2 key={`${proof.type}:${proof.value}`} direction="horizontal" alignSelf="stretch" alignItems="center" > <ProofSingle {...proof} /> </Kb.Box2> ))} </Kb.Box2> </Kb.Box2> <Kb.Checkbox checked={checkedVerificationType} onCheck={setCheckedVerificationType} style={styles.reviewCheckbox} label="This is true" /> <Kb.Box2 direction="horizontal" alignSelf="stretch" alignItems="center"> <Kb.Box2 key="colorbar" direction="vertical" alignSelf="stretch" style={styles.reviewColorbar} /> <Kb.Box2 direction="vertical" alignSelf="stretch" style={Styles.globalStyles.flexOne}> <Kb.Box2 direction="horizontal" alignSelf="stretch" alignItems="center"> <Kb.Text type="Body" style={Styles.globalStyles.flexOne}> {props.statement} </Kb.Text> </Kb.Box2> </Kb.Box2> </Kb.Box2> <Kb.Checkbox checked={checkedStatement} onCheck={setCheckedStatement} label="This is entirely true" style={styles.reviewCheckbox} /> </Kb.Box2> <Kb.Box2 direction="horizontal" alignSelf="stretch" alignItems="center" style={Styles.collapseStyles([ styles.sidePadding, {marginTop: 'auto', paddingBottom: Styles.globalMargins.tiny}, ])} > <Kb.Button label="Accept" mode="Primary" type="Success" fullWidth={true} onClick={props.onAccept} {...buttonState('accept')} /> </Kb.Box2> </Kb.Modal> ) } const WotModal = (props: WotModalProps) => { const dispatch = Container.useDispatch() const onClose = () => { dispatch(ProfileGen.createWotVouchSetError({error: ''})) dispatch(RouteTreeGen.createClearModals()) } return ( <Kb.Modal onClose={onClose} scrollViewRef={props.scrollViewRef} header={{ leftButton: props.onBack ? ( <Kb.Text onClick={props.onBack} type="BodyPrimaryLink"> Back </Kb.Text> ) : Styles.isMobile ? ( <Kb.Text onClick={onClose} type="BodyPrimaryLink"> Cancel </Kb.Text> ) : ( undefined ), title: 'Web of Trust', }} mode="DefaultFullHeight" banners={[ !!props.error && ( <Kb.Banner key="error" color="red"> <Kb.BannerParagraph bannerColor="red" content={props.error} /> </Kb.Banner> ), ]} footer={{ content: ( <Kb.ButtonBar align="center" direction="row" fullWidth={true} style={styles.buttonBar}> <Kb.Button fullWidth={true} label={props.submitLabel} onClick={props.onSubmit} disabled={props.submitDisabled} waiting={props.submitWaiting} /> </Kb.ButtonBar> ), }} > <Kb.Box2 direction="vertical" alignSelf="stretch" alignItems="center" style={styles.topIconContainer}> <Kb.Icon type="icon-illustration-wot-460-96" /> </Kb.Box2> {props.children} </Kb.Modal> ) } /* eslint-disable sort-keys */ const verificationTypeColors = { in_person: Styles.globalColors.greenDark, video: '#56fff5', audio: Styles.globalColors.blueLight, proofs: Styles.globalColors.blueLight, other_chat: Styles.globalColors.yellow, familiar: Styles.globalColors.yellow, other: Styles.globalColors.yellowDark, } /* eslint-enable sort-keys */ const verificationTypeText = ( verificationType: WebOfTrustVerificationType, voucheeUsername: string ): React.ReactNode => { switch (verificationType) { case 'in_person': return ( <> {voucheeUsername} told me their username <Kb.Text type="BodyBold">in person</Kb.Text> </> ) case 'video': return `${voucheeUsername} told me their username over video` case 'audio': return `${voucheeUsername} told me their username over audio` case 'proofs': return `I know one of ${voucheeUsername}'s proofs` case 'other_chat': return `${voucheeUsername} texted me their username` case 'familiar': return 'We are longtime Keybase friends' case 'other': return 'Other' default: return `Unknown verification type: ${verificationType}` } } const VerificationChoice = (props: { children?: React.ReactNode voucheeUsername: string verificationType: WebOfTrustVerificationType selected: boolean onSelect: () => void }) => { const text = verificationTypeText(props.verificationType, props.voucheeUsername) const color = verificationTypeColors[props.verificationType] ?? Styles.globalColors.white return ( <Kb.Box2 direction="horizontal" alignSelf="stretch" alignItems="center"> <Kb.Box2 key="colorbar" direction="vertical" alignSelf="stretch" style={{backgroundColor: color, flexShrink: 0, width: 6}} /> <Kb.Box2 direction="vertical" alignSelf="stretch" style={Styles.globalStyles.flexOne}> <Kb.Box2 direction="horizontal" alignSelf="stretch" alignItems="center"> <Kb.RadioButton label={ <Kb.Text type="Body" style={Styles.globalStyles.flexOne}> {text} </Kb.Text> } selected={props.selected} onSelect={props.onSelect} style={styles.choiceRadio} /> </Kb.Box2> {props.children} </Kb.Box2> </Kb.Box2> ) } const proofList = (selected: boolean, proofs: Array<Proof & Checkboxed>) => proofs.map(proof => ( <Kb.Box2 key={`${proof.type}:${proof.value}`} direction="horizontal" alignSelf="stretch" alignItems="center" style={styles.insetContainer} > <Kb.Checkbox checked={proof.checked && selected} onCheck={proof.onCheck} labelComponent={<ProofSingle {...proof} />} /> </Kb.Box2> )) const ProofSingle = (props: ProofLite) => { let siteIcon: React.ReactNode = null const iconSet = Styles.isDarkMode() ? props.siteIconDarkmode : props.siteIcon if (iconSet) { siteIcon = <SiteIcon full={false} set={iconSet} /> } return ( <Kb.Box2 direction="horizontal" alignItems="center" style={styles.proofSingle}> {siteIcon} <Kb.Text type="Body" style={styles.proofSingleValue} lineClamp={1}> {props.value} </Kb.Text> <Kb.Text type="Body">@{props.type}</Kb.Text> </Kb.Box2> ) } const OtherInput = (props: {otherText: string; setOtherText: (_: string) => void}) => ( <Kb.Box2 direction="vertical" alignSelf="stretch" alignItems="flex-start" style={Styles.collapseStyles([styles.insetContainer, styles.otherInputContainer])} > <Kb.LabeledInput placeholder={'Specify (required)'} value={props.otherText} onChangeText={props.setOtherText} maxLength={otherLimit} /> </Kb.Box2> ) // Store checkedness for a list of checkboxes. function useCheckboxesState<T>(items: Array<T>, onCheck: () => void): [Array<T & Checkboxed>, () => void] { const [stateStored, setState] = React.useState<Array<boolean>>(items.map(() => false)) const state = items.length === stateStored.length ? stateStored : items.map(() => false) const clear = () => setState(items.map(() => false)) return [ items.map((item, i) => ({ ...item, checked: state[i], onCheck: checked => { setState(state.map((wasChecked, j) => (i === j ? checked : wasChecked))) onCheck() }, })), clear, ] } const styles = Styles.styleSheetCreate( () => ({ approveNote: {paddingTop: Styles.globalMargins.tiny}, buttonBar: {minHeight: undefined}, choiceRadio: { flex: 1, paddingBottom: Styles.globalMargins.tiny, paddingLeft: Styles.globalMargins.small, paddingTop: Styles.globalMargins.tiny, }, id: {paddingBottom: Styles.globalMargins.tiny, paddingTop: Styles.globalMargins.tiny}, idInner: { flex: 1, paddingLeft: Styles.globalMargins.tiny, }, insetContainer: Styles.platformStyles({ common: {marginLeft: 38, marginRight: Styles.globalMargins.small}, isMobile: {marginLeft: 46}, }), otherInputContainer: {paddingBottom: Styles.globalMargins.tiny}, outside: {paddingTop: Styles.globalMargins.tiny}, outsideBox: {paddingBottom: Styles.globalMargins.small}, proofSingle: { flexShrink: 1, marginBottom: 2, marginLeft: 3, marginTop: 0, }, proofSingleValue: {flexShrink: 1, marginLeft: 8}, reviewCheckbox: {paddingBottom: Styles.globalMargins.small, paddingTop: Styles.globalMargins.small}, reviewColorbar: { backgroundColor: Styles.globalColors.blueLight, flexShrink: 0, marginRight: Styles.globalMargins.small, width: 4, }, reviewInstruction: { flex: 1, paddingTop: Styles.globalMargins.tiny, }, sidePadding: {paddingLeft: Styles.globalMargins.small, paddingRight: Styles.globalMargins.small}, topIconContainer: {backgroundColor: Styles.globalColors.green, overflow: 'hidden'}, } as const) )
the_stack
import * as jschardet from "jschardet"; import * as iconv from "iconv-lite"; import * as path from "path"; import * as fs from "fs"; import { ProgressFunc } from "../../common/Reader"; import { File } from "../../common/File"; import { Logger } from "../../common/Logger"; import { Readable, Transform } from "stream"; import { convertAttrToStatMode } from "../FileReader"; const log = Logger("Archive"); export abstract class ArchiveCommon { protected originalFile: File = null; protected supportType: string = null; public setFile( file: File ): boolean { if ( !file ) { return false; } this.originalFile = file; this.supportType = this.isSupportType( file ); return !!this.supportType; } public getSupportType(): string { return this.supportType; } protected abstract isSupportType( file: File ): string; public abstract getArchivedFiles(progress?: ProgressFunc): Promise<File[]>; public abstract uncompress( extractDir: File, files?: File[], progress?: ProgressFunc ): Promise<void>; public compress( sourceFile: File[], baseDir: File, targetDirOrNewFile: File, progress?: ProgressFunc ): Promise<void> { // eslint-disable-next-line no-async-promise-executor return new Promise( async (resolve, reject) => { let tmpWriteFileName = null; if ( targetDirOrNewFile.fstype === "file" ) { tmpWriteFileName = targetDirOrNewFile.fullname; } else if ( this.originalFile ) { tmpWriteFileName = this.originalFile.fullname + ".bak"; } if ( !this.originalFile ) { this.supportType = this.isSupportType( targetDirOrNewFile ); } const writeNewTarStream = fs.createWriteStream( tmpWriteFileName ); try { await this.commonCompress( writeNewTarStream, async (pack) => { if ( targetDirOrNewFile.fstype === "archive" ) { await this.originalPacking(pack, null, progress); } for ( const item of sourceFile ) { let stream = null; if ( !item.dir && !item.link ) { stream = fs.createReadStream(item.fullname); } const targetDir = targetDirOrNewFile.fstype === "archive" ? targetDirOrNewFile.fullname : ""; const fileHeader = this.convertFileToHeader(item, baseDir, targetDir); await this.packEntry(item, fileHeader, stream, pack); } }); if ( this.originalFile ) { fs.unlinkSync( this.originalFile.fullname ); fs.renameSync( tmpWriteFileName, this.originalFile.fullname ); } resolve(); } catch( err ) { if ( fs.existsSync(tmpWriteFileName) ) { fs.unlinkSync( tmpWriteFileName ); } reject( err ); } }); } public rename( source: File, rename: string, progress?: ProgressFunc ): Promise<void> { rename = path.posix.normalize(rename); const filterEntryFunc = (tarFileInfo: File, header): boolean => { if ( !source.dir && source.fullname === tarFileInfo.fullname ) { header.name = rename.replace( /^\//, "" ); } else if ( source.dir && tarFileInfo.fullname.indexOf(source.fullname) > -1 ) { header.name = tarFileInfo.fullname.replace( source.fullname, rename + path.posix.sep).replace( /^\//, "" ); } return true; }; // eslint-disable-next-line no-async-promise-executor return new Promise( async (resolve, reject) => { const tmpWriteFileName = this.originalFile.fullname + ".bak"; const writeNewTarStream = fs.createWriteStream( tmpWriteFileName ); try { await this.commonCompress( writeNewTarStream, async (pack) => { await this.originalPacking( pack, filterEntryFunc, progress ); }); fs.unlinkSync( this.originalFile.fullname ); fs.renameSync( tmpWriteFileName, this.originalFile.fullname ); resolve(); } catch( err ) { if ( fs.existsSync(tmpWriteFileName) ) { fs.unlinkSync( tmpWriteFileName ); } reject( err ); } }); } public remove( sourceFile: File[], progress?: ProgressFunc ): Promise<void> { const filterEntryFunc = (tarFileInfo: File, _header): boolean => { if ( sourceFile.find( item => item.fullname == tarFileInfo.fullname ) ) { return false; } return true; }; // eslint-disable-next-line no-async-promise-executor return new Promise( async (resolve, reject) => { const tmpWriteFileName = this.originalFile.fullname + ".bak"; const writeNewTarStream = fs.createWriteStream( tmpWriteFileName ); try { await this.commonCompress( writeNewTarStream, async (pack) => { await this.originalPacking( pack, filterEntryFunc, progress ); }); fs.unlinkSync( this.originalFile.fullname ); fs.renameSync( tmpWriteFileName, this.originalFile.fullname ); resolve(); } catch( err ) { if ( fs.existsSync(tmpWriteFileName) ) { fs.unlinkSync( tmpWriteFileName ); } reject( err ); } }); } protected abstract commonCompress( writeTarStream: fs.WriteStream, packFunc: (pack) => Promise<void>, progress?: ProgressFunc ): Promise<void>; protected abstract originalPacking( pack, filterEntryFunc: (packFileInfo: File, header) => boolean, progress?: ProgressFunc ): Promise<void>; protected abstract packEntry(file: File, header, stream: Readable, pack, reportProgress?: Transform): Promise<void>; protected abstract convertFileToHeader(file: File, srcBaseDir: File, targetDir: string): any; protected subDirectoryCheck(files: File[]): File[] { const dirFilter = files.filter( item => item.dir ); const addFiles: File[] = []; files.forEach( item => { if ( item.fullname !== path.posix.sep && item.dirname !== path.posix.sep && addFiles.findIndex( (addItem) => addItem.fullname === item.dirname + "/" ) === -1 ) { if ( dirFilter.findIndex( (dirItem) => dirItem.fullname === item.dirname + path.posix.sep ) === -1 ) { const file = item.clone(); file.fullname = item.dirname + path.posix.sep; file.name = path.basename(item.dirname); file.orgname = file.fullname.replace(/^\//, ""); file.attr = "drwxr-xr-x"; file.size = 0; file.dir = true; addFiles.push( file ); } } }); return files.concat( addFiles ); } protected fileStreamWrite(extractDir: File, filesBaseDir: string, file: File, readStream: Readable, reportProgress: Transform, next: (status: string, err?: any) => void) { try { let filename = extractDir.fullname + ((filesBaseDir && filesBaseDir !== "/") ? file.fullname.substr(filesBaseDir.length) : file.fullname); filename = path.normalize( filename ); const dirname = path.dirname(filename); const mode = convertAttrToStatMode(file); // console.log( filename, dirname ); if ( !fs.existsSync( dirname ) ) { fs.mkdirSync( dirname, { recursive: true }); } if ( fs.existsSync( filename ) ) { next( "error", "file exist: " + filename ); return; } if ( file.link ) { fs.unlinkSync( filename ); fs.symlinkSync( filename, file.link.name, file.dir ? "dir" : "file" ); fs.utimesSync(filename, file.atime || new Date(), file.mtime || new Date()); readStream && readStream.resume(); next("link"); } else if ( file.dir && !file.link ) { fs.mkdirSync( filename, { recursive: true, mode }); try { fs.chownSync( filename, file.uid, file.gid ); } catch( e ) { console.error( e.message ); } fs.utimesSync(filename, file.atime || new Date(), file.mtime || new Date()); readStream && readStream.resume(); next("directory"); } else if ( readStream ) { const writeStream = fs.createWriteStream(filename, { mode }); const rejectFunc = (err) => { readStream.destroy(); writeStream.end(() => { try { fs.unlinkSync( filename ); // eslint-disable-next-line no-empty } catch( e ) {} }); log.debug( "Uncompress error - " + err ); next("error", err); }; readStream.on("error", rejectFunc); writeStream.on("error", rejectFunc); writeStream.on("finish", () => { try { fs.chownSync( filename, file.uid, file.gid ); } catch( e ) { log.error( e.message ); } fs.utimesSync(filename, file.atime || new Date(), file.mtime || new Date()); next("finish"); }); if ( reportProgress ) { readStream.pipe(reportProgress).pipe(writeStream); } else { readStream.pipe(writeStream); } } } catch( e ) { log.error( "%s", e.stack ); next("error", e); } } protected decodeString(buffer) { let result = null; try { result = jschardet.detect( buffer ); } catch ( e ) { log.error( e ); } let data = null; if ( result && result.encoding && [ "utf8", "ascii" ].indexOf(result.encoding) === -1 ) { if ( (global as any)?.LOCALE?.indexOf("ko-KR") > -1 ) { if ( result.confidence < 0.7 || result.encoding === "windows-1252") { result.encoding = "EUC-KR"; } } data = iconv.decode(buffer, result.encoding); } else { data = buffer.toString("utf8"); } //log.info( "decode file: %s %s", result, data ); return data; } }
the_stack
import Patch from "../../patchwork/core/Patch"; import IPoint from "../data/interface/IPoint"; import EventDispatcher from "../../patchwork/core/EventDispatcher"; import ConnectionsSelectionGrid from "./ConnectionsSelectionGrid"; import Connection from "../../patchwork/core/Connection"; import ConnectionsCanvasEvent from "../event/ConnectionsCanvasEvent"; declare var $:any; class ConnectionsCanvas extends EventDispatcher { public drawDebugSelectionGrid = false; // draws the connection selection grid public viewOffset:IPoint; public connectionSelectionGrid:ConnectionsSelectionGrid; public connectionMouseOverIndex:number = -1; public $canvas:any; public $container:any; public canvas:HTMLCanvasElement; public context:CanvasRenderingContext2D; public connectionCreationData:any; public width:number; public height:number; constructor(viewOffset:IPoint) { super(); this.viewOffset = viewOffset; this.connectionSelectionGrid = new ConnectionsSelectionGrid(10, this.drawDebugSelectionGrid); // set canvas references this.$canvas = $('.draw-area canvas'); this.canvas = this.$canvas[0]; // canvas container (to scale the canvas to) this.$container = $('.draw-area'); // get the context this.context = this.canvas.getContext('2d'); // data for creationg a connection this.connectionCreationData = null; this.setSize(); this.clear(); // resize on browser resize $(window).resize(function(){ this.setSize(); //this.draw(); TODO fix this stuff with having to give a patch }.bind(this)); this.$canvas.on('mousemove', function(event) { // get the index of the connection under the mouse var connectionMouseOverIndex = this.connectionSelectionGrid.getConnectionIndexAt(event.clientX, event.clientY); // redraw if value differs from currently set value if(this.connectionMouseOverIndex !== connectionMouseOverIndex) { this.connectionMouseOverIndex = connectionMouseOverIndex; //this.draw(); } }.bind(this)); this.$canvas.on('click', function(event) { if(this.connectionMouseOverIndex >= 0) this.dispatchEvent(ConnectionsCanvasEvent.CONNECTION_CLICKED, {connectionIndex: this.connectionMouseOverIndex}); }.bind(this)); } public setSize():void { this.width = this.$container.outerWidth(); this.height = this.$container.outerHeight(); this.$canvas.attr({width: this.width, height: this.height}); // create new grid this.connectionSelectionGrid.create(this.width, this.height); } public clear():void { this.context.clearRect(0, 0, this.canvas.width, this.canvas.height); this.connectionSelectionGrid.create(this.canvas.width, this.canvas.height); //var margin = 10; //this.context.fillStyle = "rgba(0,0,0,0.3)"; //this.context.fillRect(margin, margin, this.canvas.width - 2 * margin, this.canvas.height - 2 * margin); } public draw(patch:Patch):void { if(!patch) return; this.clear(); // make a list of x,y points var lineObjects = []; // add all start/end points of all connections var connections = patch.connections; // todo skip creation of connections var for(var i = 0; i < connections.length; i++) { lineObjects = lineObjects.concat(this.createLineSegments(connections[i], i)); } // then draw all lines for(var i = 0; i < lineObjects.length; i++) this.drawLine(lineObjects[i]); if(this.drawDebugSelectionGrid) { this.context.strokeStyle = "rgba(255,255,255,0.5)"; var gridSize = this.connectionSelectionGrid.gridSize; var linesX = Math.floor(this.width / gridSize); for(var i = 0; i < linesX; i++) { this.context.beginPath(); this.context.moveTo(i * gridSize, 0); this.context.lineTo(i * gridSize, this.height); this.context.stroke(); } var linesY = Math.floor(this.height / gridSize); for(var i = 0; i < linesX; i++) { this.context.beginPath(); this.context.moveTo(0, i * gridSize); this.context.lineTo(this.width, i * gridSize); this.context.stroke(); } for(var i = 0; i < this.connectionSelectionGrid.locations.length; i++) { this.context.fillStyle = "rgba(0,0,0,1)"; var x = 1 + this.connectionSelectionGrid.locations[i].x * gridSize; var y = 1 + this.connectionSelectionGrid.locations[i].y * gridSize; this.context.fillRect(x, y, gridSize - 2, gridSize - 2); } } } public createLineSegments(connection:Connection, index:number):Array<any> { var segments = []; var $output = this.findTransputByModuleIdAndIndex(connection.sourceModule.id, connection.sourceOutputIndex, 'output'); var $input = this.findTransputByModuleIdAndIndex(connection.destinationModule.id, connection.destinationInputIndex, 'input'); var transputOutDistanceGrowth = 5; var transputOutDistance = 8 + connection.sourceOutputIndex * transputOutDistanceGrowth; var transputInDistance = 14 + connection.destinationInputIndex * transputOutDistanceGrowth; if($output[0] && $input[0]) { var outputOffset = $output.offset(); var inputOffset = $input.offset(); var startX = outputOffset.left + $output.outerWidth(); var startY = outputOffset.top + 0.5 * $output.outerHeight(); var endX = inputOffset.left; var endY = inputOffset.top + 0.5 * $input.outerHeight(); // decide where the end is with regard to the start var positionMode; if(endX - transputInDistance > startX + transputOutDistance) { // end to the right positionMode = 'right' } else { // end to the left positionMode = 'left'; } // first go a little right, out of the output segments.push({ fromX: startX, fromY: startY, toX: startX + transputOutDistance, toY: startY, connectionIndex: index }); switch(positionMode) { case 'right': { // end is to the right, most simple case. just move to the correct y first, and then go to end segments.push({ fromX: startX + transputOutDistance, fromY: startY, toX: startX + transputOutDistance, toY: endY, connectionIndex: index }); segments.push({ fromX: startX + transputOutDistance, fromY: endY, toX: endX - transputInDistance, toY: endY, connectionIndex: index }); break; } case 'left': { // end is to the left, for now jsut go down halfway, then fully to the left, then final half down segments.push({ fromX: startX + transputOutDistance, fromY: startY, toX: startX + transputOutDistance, toY: startY + 0.5 * (endY - startY), connectionIndex: index }); segments.push({ fromX: startX + transputOutDistance, fromY: startY + 0.5 * (endY - startY), toX: endX - transputInDistance, toY: startY + 0.5 * (endY - startY), connectionIndex: index }); segments.push({ fromX: endX - transputInDistance, fromY: startY + 0.5 * (endY - startY), toX: endX - transputInDistance, toY: endY, connectionIndex: index }); break; } default: { // unhandled cases. just draw a straight line segments.push({ fromX: startX + transputOutDistance, fromY: startY, toX: endX - transputInDistance, toY: endY, connectionIndex: index }); } } // final part that goes into the input segments.push({ fromX: endX - transputInDistance, fromY: endY, toX: endX, toY: endY, connectionIndex: index, end: true }); } else { console.log('No output or input found!') } return segments; } public drawWithCreation(patch:Patch, mouseX:number, mouseY:number):void { // first do a normal draw this.draw(patch); // then add the mouse-line. connectionsdata is set before the mouse move listener is added if(this.connectionCreationData) { var lineObject = {connectionIndex: -1, toX: -1, toY: -1, fromX: -1, fromY: -1}; // todo lineObject.toX = mouseX; lineObject.toY = mouseY; if(this.connectionCreationData.source) { // drawing from an output var $transputElement = this.findTransputByModuleIdAndIndex(this.connectionCreationData.source.moduleId, this.connectionCreationData.source.transputIndex, 'output'); } else { // drawing from an input var $transputElement = this.findTransputByModuleIdAndIndex(this.connectionCreationData.destination.moduleId, this.connectionCreationData.destination.transputIndex, 'input'); } var transputElementOffset = $transputElement.offset(); lineObject.fromX = transputElementOffset.left + 0.5 * $transputElement.outerWidth(); lineObject.fromY = transputElementOffset.top + 0.5 * $transputElement.outerHeight(); this.drawLine(lineObject); } } public drawLine(lineObject:any):void { //this.context.strokeStyle = (this.connectionMouseOverIndex !== -1 && this.connectionMouseOverIndex === lineObject.connectionIndex) ? 'red' : 'black'; this.context.strokeStyle = "#999"; this.context.lineWidth = 2; // convert so we have sharp lines // lineObject.fromX = this.convertToCanvasSafeNumber(lineObject.fromX); // lineObject.fromY = this.convertToCanvasSafeNumber(lineObject.fromY); // lineObject.toX = this.convertToCanvasSafeNumber(lineObject.toX); // lineObject.toY = this.convertToCanvasSafeNumber(lineObject.toY); this.context.beginPath(); this.context.moveTo(lineObject.fromX, lineObject.fromY); this.context.lineTo(lineObject.toX, lineObject.toY); this.context.stroke(); if(lineObject.end === true) { // draw arrow var arrowWidth = 12; var arrowLength = 10; var arrowBack = 2; this.context.fillStyle = '#999'; this.context.beginPath(); this.context.moveTo(lineObject.toX, lineObject.toY); this.context.lineTo(lineObject.toX - arrowLength, lineObject.toY - 0.5 * arrowWidth); this.context.lineTo(lineObject.toX - arrowLength + arrowBack, lineObject.toY); this.context.lineTo(lineObject.toX - arrowLength, lineObject.toY + 0.5 * arrowWidth); this.context.lineTo(lineObject.toX, lineObject.toY); this.context.fill(); } // give same coordinates to grid this.connectionSelectionGrid.drawLine(lineObject.connectionIndex, lineObject.fromX, lineObject.fromY, lineObject.toX, lineObject.toY); } public convertToCanvasSafeNumberfunction(value:number):number { return Math.round(value) + 0.5; } public findTransputByModuleIdAndIndex(moduleId, index, type):any { var typeClass = type === 'input' ? 'input' : 'output'; var selector = 'div[data-id="' + moduleId +'"].module .' + typeClass + '[data-index="' + index + '"]'; return $(selector); } } export default ConnectionsCanvas;
the_stack
import { ArgumentOutOfRangeException } from "../Exceptions/ArgumentException"; import { ArrayHelper, StringHelper, TypeSystem } from "../ExtensionMethods"; import { EwsLogging } from "../Core/EwsLogging"; import { EwsServiceJsonReader } from "../Core/EwsServiceJsonReader"; import { EwsServiceXmlWriter } from "../Core/EwsServiceXmlWriter"; import { ExchangeService } from "../Core/ExchangeService"; import { ICustomUpdateSerializer } from "../Interfaces/ICustomXmlUpdateSerializer"; import { IEnumerable } from "../Interfaces/IEnumerable"; import { PropertyDefinition } from "../PropertyDefinitions/PropertyDefinition"; import { ServiceLocalException } from '../Exceptions/ServiceLocalException'; import { ServiceObject } from "../Core/ServiceObjects/ServiceObject"; import { Strings } from "../Strings"; import { XmlNamespace } from "../Enumerations/XmlNamespace"; import { ComplexProperty } from "./ComplexProperty"; /** * Represents a collection of properties that can be sent to and retrieved from EWS. * * @type <TComplexProperty> ComplexProperty type. */ export abstract class ComplexPropertyCollection<TComplexProperty extends ComplexProperty> extends ComplexProperty implements IEnumerable<TComplexProperty>, ICustomUpdateSerializer { ___typeGenerics: string[] = ["ComplexProperty"]; private items: TComplexProperty[] = []; private addedItems: TComplexProperty[] = []; private modifiedItems: TComplexProperty[] = []; private removedItems: TComplexProperty[] = []; /** * @internal Gets the items. (workaround for GetEnumerator) * * @return The items. */ get Items(): TComplexProperty[] { return this.items; } /** * @internal Gets the added items. * * @return The added items. */ get AddedItems(): TComplexProperty[] { return this.addedItems; } /** * @internal Gets the modified items. * * @return The modified items */ get ModifiedItems(): TComplexProperty[] { return this.modifiedItems; } /** * @internal Gets the removed items. * * @return The removed items. */ get RemovedItems(): TComplexProperty[] { return this.removedItems; } /** * Gets the total number of properties in the collection. */ get Count(): number { return this.items.length; } /** * Gets the property at the specified index. * * @param {number} index The zero-based index of the property to get. * @return {TComplexProperty} The property at the specified index. */ _getItem(index: number): TComplexProperty { if (index < 0 || index >= this.Count) { throw new ArgumentOutOfRangeException("index", Strings.IndexIsOutOfRange); } return this.items[index]; } /** * @internal Initializes a new instance of the **ComplexPropertyCollection** class. * */ constructor() { super(); } /** * @internal Clears the change log. */ ClearChangeLog(): void { this.removedItems.splice(0); this.addedItems.splice(0); this.modifiedItems.splice(0); } /** * Determines whether a specific property is in the collection. * * @param {TComplexProperty} complexProperty The property to locate in the collection. * @return {boolean} True if the property was found in the collection, false otherwise. */ Contains(complexProperty: TComplexProperty): boolean { return this.items.indexOf(complexProperty) >= 0; } /** * @internal Creates the complex property. * * @param {string} xmlElementName Name of the XML element. * @return {TComplexProperty} Complex property instance. */ abstract CreateComplexProperty(xmlElementName: string): TComplexProperty; /** * @internal Creates the default complex property. * * @return {TComplexProperty} Complex property instance. */ abstract CreateDefaultComplexProperty(): TComplexProperty; /** * @internal Loads from XMLJsObject collection to create a new collection item. * * @interface IJsonCollectionDeserializer * * @param {any} jsObjectCollection The json collection. * @param {ExchangeService} service The service. */ CreateFromXmlJsObjectCollection(jsObjectCollection: any, service: ExchangeService): void { let collection: TComplexProperty[] = jsObjectCollection; if (!ArrayHelper.isArray(collection)) { collection = []; let collectionElement = this.GetCollectionItemXmlElementName(null); let typeName = TypeSystem.GetJsObjectTypeName(jsObjectCollection) if (collectionElement === null || (typeName && collectionElement === typeName)) { collection = [jsObjectCollection]; } else { for (let key in jsObjectCollection) { if (key.indexOf("__") === 0) //skip xmljsobject conversion entries like __type and __prefix continue; let collectionObj: TComplexProperty[] = jsObjectCollection[key]; if (!ArrayHelper.isArray(collectionObj)) { collectionObj = EwsServiceJsonReader.ReadAsArray(jsObjectCollection, key); } ArrayHelper.AddRange(collection, collectionObj); } } } for (let jsonObject of collection) { let jsonProperty = jsonObject; if (jsonProperty != null) { let complexProperty: TComplexProperty = null; // If type property is present, use it. Otherwise create default property instance. // Note: polymorphic collections (such as Attachments) need a type property so // the CreateDefaultComplexProperty call will fail. if (TypeSystem.GetJsObjectTypeName(jsonProperty)) { complexProperty = this.CreateComplexProperty(TypeSystem.GetJsObjectTypeName(jsonProperty)); } else { complexProperty = this.CreateDefaultComplexProperty(); } if (complexProperty != null) { complexProperty.LoadFromXmlJsObject(jsonProperty, service); this.InternalAdd(complexProperty, true); } } } } /** * @internal Gets the name of the collection item XML element. * * @param {TComplexProperty} complexProperty The complex property. * @return {string} XML element name. */ abstract GetCollectionItemXmlElementName(complexProperty: TComplexProperty): string; /** * Returns an enumerator that iterates through the collection. this case this.items */ GetEnumerator(): TComplexProperty[] { return this.items; } /** * Searches for a specific property and return its zero-based index within the collection. * * @param {TComplexProperty} complexProperty The property to locate in the collection. * @return {number} The zero-based index of the property within the collection. */ IndexOf(complexProperty: TComplexProperty): number { return this.items.indexOf(complexProperty); } /** * @internal Add complex property. * * @param {TComplexProperty} complexProperty The complex property. */ InternalAdd(complexProperty: TComplexProperty): void; /** * @private Add complex property. * * @param {TComplexProperty} complexProperty The complex property. * @param {boolean} loading If true, collection is being loaded. */ InternalAdd(complexProperty: TComplexProperty, loading: boolean): void; InternalAdd(complexProperty: TComplexProperty, loading: boolean = false): void { EwsLogging.Assert( complexProperty != null, "ComplexPropertyCollection.InternalAdd", "complexProperty is null"); if (this.items.indexOf(complexProperty) < 0) { this.items.push(complexProperty); if (!loading) { ArrayHelper.RemoveEntry(this.removedItems, complexProperty);// this.removedItems.Remove(complexProperty); this.addedItems.push(complexProperty); } complexProperty.OnChange.push(this.ItemChanged.bind(this)); this.Changed(); } } /** * @internal Clear collection. */ InternalClear(): void { while (this.Count > 0) { this.InternalRemoveAt(0); } } /** * @internal Remove specified complex property. * * @param {TComplexProperty} complexProperty The complex property. * @return {boolean} True if the complex property was successfully removed from the collection, false otherwise. */ InternalRemove(complexProperty: TComplexProperty): boolean { EwsLogging.Assert( complexProperty != null, "ComplexPropertyCollection.InternalRemove", "complexProperty is null"); if (ArrayHelper.RemoveEntry(this.items, complexProperty)) { // this.items.Remove(complexProperty)) ArrayHelper.RemoveEntry(complexProperty.OnChange, this.ItemChanged);// complexProperty.OnChange -= this.ItemChanged; if (this.addedItems.indexOf(complexProperty) < 0) { this.removedItems.push(complexProperty); } else { ArrayHelper.RemoveEntry(this.addedItems, complexProperty);// this.addedItems.Remove(complexProperty); } ArrayHelper.RemoveEntry(this.modifiedItems, complexProperty);// this.modifiedItems.Remove(complexProperty); this.Changed(); return true; } else { return false; } } /** * @internal Remote entry at index. * * @param {number} index The index. */ InternalRemoveAt(index: number): void { EwsLogging.Assert( index >= 0 && index < this.Count, "ComplexPropertyCollection.InternalRemoveAt", "index is out of range."); this.InternalRemove(this.items[index]); } /** * @internal Item changed. * * @param {ComplexProperty} complexProperty The complex property. */ ItemChanged(complexProperty: ComplexProperty): void { //TComplexProperty property = complexProperty as TComplexProperty; let property = complexProperty; // EwsLogging.Assert( // property != null, // "ComplexPropertyCollection.ItemChanged", // StringHelper.Format("ComplexPropertyCollection.ItemChanged: the type of the complexProperty argument ({0}) is not supported.", complexProperty.___typeName)); if (this.addedItems.indexOf(<TComplexProperty>property) < 0) { if (this.modifiedItems.indexOf(<TComplexProperty>property) < 0) { this.modifiedItems.push(<TComplexProperty>property); this.Changed(); } } } /** * @internal Loads service object from XML. * * @param {any} jsObject Json Object converted from XML. * @param {ExchangeService} service The service. */ LoadFromXmlJsObject(jsObject: any, service: ExchangeService): void { EwsLogging.Assert(false, "ComplexPropertyCollection.LoadFromXmlJsObject", "LoadFromXmlJsObject was called, should not be calling. Fix it to direct to Create or Update call instad.") this.CreateFromXmlJsObjectCollection(jsObject, service); } /** * @internal Removes from change log. * * @param {TComplexProperty} complexProperty The complex property. */ RemoveFromChangeLog(complexProperty: TComplexProperty): void { ArrayHelper.RemoveEntry(this.removedItems, complexProperty); //this.removedItems.Remove(complexProperty); ArrayHelper.RemoveEntry(this.modifiedItems, complexProperty); //this.modifiedItems.Remove(complexProperty); ArrayHelper.RemoveEntry(this.addedItems, complexProperty); //this.addedItems.Remove(complexProperty); } /** * @internal Determine whether we should write collection to XML or not. * * @return {boolean} True if collection contains at least one element. */ ShouldWriteToRequest(): boolean { // Only write collection if it has at least one element. return this.Count > 0; } /** * @internal Loads from XMLJsObject collection to update collection Items. * * @interface IJsonCollectionDeserializer * * @param {any} jsObjectCollection The XMLJsObject collection. * @param {ExchangeService} service The service. */ UpdateFromXmlJsObjectCollection(jsObjectCollection: any, service: ExchangeService): void { let collection: TComplexProperty[] = jsObjectCollection; if (!ArrayHelper.isArray(collection)) { collection = []; let collectionElement = this.GetCollectionItemXmlElementName(null); let typeName = TypeSystem.GetJsObjectTypeName(jsObjectCollection) if (collectionElement === null || (typeName && collectionElement === typeName)) { collection = [jsObjectCollection]; } else { for (let key in jsObjectCollection) { if (key.indexOf("__") === 0) //skip xmljsobject conversion entries like __type and __prefix continue; let collectionObj: TComplexProperty[] = jsObjectCollection[key]; if (!ArrayHelper.isArray(collectionObj)) { collectionObj = EwsServiceJsonReader.ReadAsArray(jsObjectCollection, key); } ArrayHelper.AddRange(collection, collectionObj); } } } if (this.Count != collection.length) { throw new ServiceLocalException(Strings.PropertyCollectionSizeMismatch); } let index: number = 0; for (let jsonObject of collection) { let jsonProperty = jsonObject; if (jsonProperty != null) { let expectedComplexProperty: TComplexProperty = null; if (TypeSystem.GetJsObjectTypeName(jsonProperty)) { expectedComplexProperty = this.CreateComplexProperty(TypeSystem.GetJsObjectTypeName(jsonProperty)); } else { expectedComplexProperty = this.CreateDefaultComplexProperty(); } let actualComplexProperty: TComplexProperty = this._getItem(index++); if (expectedComplexProperty == null || !(actualComplexProperty instanceof expectedComplexProperty.constructor)) { throw new ServiceLocalException(Strings.PropertyTypeIncompatibleWhenUpdatingCollection); } actualComplexProperty.LoadFromXmlJsObject(jsonProperty, service); } else { throw new ServiceLocalException(); } } } /** * @internal Writes elements to XML. * * @param {EwsServiceXmlWriter} writer The writer. */ WriteElementsToXml(writer: EwsServiceXmlWriter): void { for (let complexProperty of this.items) { complexProperty.WriteToXml(writer, this.GetCollectionItemXmlElementName(complexProperty)); } } /** * @internal Writes to XML. * * @param {EwsServiceXmlWriter} writer The writer. * @param {XmlNamespace} xmlNamespace The XML namespace. * @param {string} xmlElementName Name of the XML element. */ WriteToXml(writer: EwsServiceXmlWriter, xmlElementName: string, xmlNamespace: XmlNamespace = XmlNamespace.Types): void { if (this.ShouldWriteToRequest()) { super.WriteToXml( writer, xmlElementName, xmlNamespace); } } /** * @internal Writes the update to XML. * ICustomUpdateSerializer.WriteSetUpdateToXml * * @param {EwsServiceXmlWriter} writer The writer. * @param {ServiceObject} ewsObject The ews object. * @param {PropertyDefinition} propertyDefinition Property definition. * @return {boolean} True if property generated serialization. */ WriteSetUpdateToXml( writer: EwsServiceXmlWriter, ewsObject: ServiceObject, propertyDefinition: PropertyDefinition): boolean { // If the collection is empty, delete the property. if (this.Count == 0) { writer.WriteStartElement(XmlNamespace.Types, ewsObject.GetDeleteFieldXmlElementName()); propertyDefinition.WriteToXml(writer); writer.WriteEndElement(); return true; } // Otherwise, use the default XML serializer. else { return false; } } /** * @internal Writes the deletion update to XML. * ICustomUpdateSerializer.WriteDeleteUpdateToXml * * @param {EwsServiceXmlWriter} writer The writer. * @param {ServiceObject} ewsObject The ews object. * @return {boolean} True if property generated serialization. */ WriteDeleteUpdateToXml(writer: EwsServiceXmlWriter, ewsObject: ServiceObject): boolean { // Use the default XML serializer. return false; } }
the_stack
import * as xml2js from 'xml2js'; import { AbstractTest, StaticTestEventBase, AbstractTestEvent, SharedWithTest } from '../AbstractTest'; import { inspect } from 'util'; import { TestEventBuilder } from '../TestEventBuilder'; import * as pathlib from 'path'; import { Version } from '../Util'; import { Suite } from '../Suite'; import { AbstractRunnable } from '../AbstractRunnable'; interface XmlObject { [prop: string]: any; //eslint-disable-line } export class Catch2Section { public constructor(name: string, file: string | undefined, line: number) { this.name = name; this.filename = file ? pathlib.normalize(file) : undefined; this.line = line; } public readonly name: string; public readonly filename: string | undefined; public readonly line: number; public readonly children: Catch2Section[] = []; public failed = false; public get escapedName(): string { // some debug adapter on ubuntu starts debug session in shell, // this prevents the SECTION("`pwd`") to be executed return this.name.replace(/`/g, '\\`'); } } const EscapeCharParserFix = new Version(2, 11, 4); export class Catch2Test extends AbstractTest { public constructor( shared: SharedWithTest, runnable: AbstractRunnable, parent: Suite, frameworkVersion: Version | undefined, testNameAsId: string, tags: string[], file: string | undefined, line: number | undefined, description: string | undefined, ) { const badChars = [ // this 3 relates some catch2 bug '[', '\\', ',', // this two has some on windows '±', '§', ]; const forceIgnoreEvent: StaticTestEventBase | undefined = frameworkVersion && frameworkVersion.smaller(EscapeCharParserFix) && badChars.some(b => testNameAsId.indexOf(b) != -1) ? ({ state: 'errored', message: [ '⚡️ This extension is unable to run this test.', '', `Current Catch2 framework version ${frameworkVersion} has a bug (https://github.com/catchorg/Catch2/issues/1905).`, `Update your framework to at least ${EscapeCharParserFix}.`, 'Avoid test names with the following characters: ' + badChars.map(b => `'${b}'`).join(', ') + '.', ].join('\n'), description: '⚡️ Run me for details ⚡️', decorations: [ { line: line, message: 'Invalid character in test name. Check the output.', }, ], } as StaticTestEventBase) : undefined; super( shared, runnable, parent, testNameAsId, testNameAsId, file, line, Catch2Test._isSkipped(tags, testNameAsId), forceIgnoreEvent, tags, description, undefined, undefined, ); } private static _isSkipped(tags: string[], testNameAsId: string): boolean { return tags.some((v: string) => v.startsWith('.') || v == 'hide' || v == '!hide') || testNameAsId.startsWith('./'); } public update( tags: string[], file: string | undefined, line: number | undefined, description: string | undefined, ): boolean { return this._updateBase( this._label, file, line, Catch2Test._isSkipped(tags, this.testNameAsId), tags, description, undefined, undefined, undefined, ); } public compare(testNameAsId: string): boolean { // Catch2: xml output trimmes the name of the test return this.testNameAsId.trim() === testNameAsId.trim(); } private _sections: undefined | Catch2Section[]; public get sections(): undefined | Catch2Section[] { return this._sections; } public getEscapedTestName(): string { /* ',' and '[' has special meaning */ return this.testNameAsId.replace('\\', '\\\\').replace(/,/g, '\\,').replace(/\[/g, '\\['); } public parseAndProcessTestCase( testRunId: string, output: string, rngSeed: number | undefined, timeout: number | null, stderr: string | undefined, ): AbstractTestEvent { if (timeout !== null) { const ev = this.getTimeoutEvent(testRunId, timeout); this.lastRunEvent = ev; return ev; } let res: XmlObject = {}; new xml2js.Parser({ explicitArray: true }).parseString(output, (err: Error, result: XmlObject) => { if (err) { throw Error(inspect(err)); } else { res = result; } }); const testEventBuilder = new TestEventBuilder(this, testRunId); if (rngSeed) testEventBuilder.appendMessage(`🔀 Randomness seeded to: ${rngSeed.toString()}`, 0); this._processXmlTagTestCaseInner(res.TestCase, testEventBuilder); if (stderr) { testEventBuilder.appendMessage('stderr arrived during running this test', null); testEventBuilder.appendMessage('⬇ std::cerr:', null); testEventBuilder.appendMessage(stderr, 1); testEventBuilder.appendMessage('⬆ std::cerr', null); } const testEvent = testEventBuilder.build(); return testEvent; } private _processXmlTagTestCaseInner(testCase: XmlObject, testEventBuilder: TestEventBuilder): void { if (testCase.OverallResult[0].$.hasOwnProperty('durationInSeconds')) testEventBuilder.setDurationMilisec(Number(testCase.OverallResult[0].$.durationInSeconds) * 1000); if (testCase._) { testEventBuilder.appendMessage('⬇ std::cout:', 1); testEventBuilder.appendMessage(testCase._.trim(), 2); testEventBuilder.appendMessage('⬆ std::cout', 1); } const main: Catch2Section = new Catch2Section(testCase.$.name, testCase.$.filename, testCase.$.line); this._processTags(testCase, main, [], testEventBuilder); this._processXmlTagSections(testCase, main, [], testEventBuilder, main); this._sections = main.children; if (testCase.OverallResult[0].StdOut) { testEventBuilder.appendMessage('⬇ std::cout:', 1); for (let i = 0; i < testCase.OverallResult[0].StdOut.length; i++) testEventBuilder.appendMessage(testCase.OverallResult[0].StdOut[i].trim(), 2); testEventBuilder.appendMessage('⬆ std::cout', 1); } if (testCase.OverallResult[0].StdErr) { testEventBuilder.appendMessage('⬇ std::cerr:', 1); for (let i = 0; i < testCase.OverallResult[0].StdErr.length; i++) testEventBuilder.appendMessage(testCase.OverallResult[0].StdErr[i].trim(), 2); testEventBuilder.appendMessage('⬆ std::cerr', 1); } if (testCase.OverallResult[0].$.success === 'true') { testEventBuilder.passed(); } else { testEventBuilder.failed(); } if (this._sections.length) { let failedBranch = 0; let succBranch = 0; const traverse = (section: Catch2Section): void => { if (section.children.length === 0) { section.failed ? ++failedBranch : ++succBranch; } else { for (let i = 0; i < section.children.length; ++i) { traverse(section.children[i]); } } }; this._sections.forEach(section => traverse(section)); const branchMsg = (failedBranch ? '✘' + failedBranch + '|' : '') + '✔︎' + succBranch; testEventBuilder.appendDescription(`ᛦ${branchMsg}ᛦ`); testEventBuilder.appendTooltip(`ᛦ ${branchMsg} branches`); } } private static readonly _expectedPropertyNames = new Set([ '_', '$', 'Section', 'Info', 'Warning', 'Failure', 'Expression', 'Exception', 'OverallResult', 'OverallResults', 'FatalErrorCondition', 'BenchmarkResults', ]); private _processTags( xml: XmlObject, main: Catch2Section, stack: Catch2Section[], testEventBuilder: TestEventBuilder, ): void { { Object.getOwnPropertyNames(xml).forEach(n => { if (!Catch2Test._expectedPropertyNames.has(n)) { this._shared.log.error('unexpected Catch2 tag: ' + n); testEventBuilder.appendMessage('unexpected Catch2 tag:' + n, 0); testEventBuilder.errored(); } }); } if (xml._) { testEventBuilder.appendMessage('⬇ std::cout:', 1); testEventBuilder.appendMessage(xml._.trim(), 2); testEventBuilder.appendMessage('⬆ std::cout', 1); } if (xml.Info) { for (let i = 0; i < xml.Info.length; i++) { try { const piece = xml.Info[i]; const location = piece.$ && piece.$.filename && piece.$.line ? ` (at ${piece.$.filename}:${piece.$.line})` : ''; testEventBuilder.appendMessage(`⬇ Info:${location}`, 1); testEventBuilder.appendMessage(piece, 2); testEventBuilder.appendMessage('⬆ Info', 1); } catch (e) { this._shared.log.exceptionS(e); testEventBuilder.appendMessage('Error during processing output', 2); } } } if (xml.Warning) { for (let i = 0; i < xml.Warning.length; i++) { try { const piece = xml.Warning[i]; const location = piece.$ && piece.$.filename && piece.$.line ? ` (at ${piece.$.filename}:${piece.$.line})` : ''; testEventBuilder.appendMessage(`⬇ Warning${location}:`, 1); testEventBuilder.appendMessageWithDecorator(piece.$.filename, Number(piece.$.line) - 1, piece, 2); testEventBuilder.appendMessage('⬆ Warning', 1); } catch (e) { this._shared.log.exceptionS(e); testEventBuilder.appendMessage('Error during processing output', 2); } } } if (xml.Failure) { for (let i = 0; i < xml.Failure.length; i++) { try { const piece = xml.Failure[i]; const location = piece.$ && piece.$.filename && piece.$.line ? ` (at ${piece.$.filename}:${piece.$.line})` : ''; testEventBuilder.appendMessage(`⬇ Failure${location}:`, 1); if (typeof piece._ !== 'string') this._shared.log.warn('No _ under failure', piece); const msg = typeof piece._ === 'string' ? piece._.trim() : piece.toString(); testEventBuilder.appendMessageWithDecorator(piece.$.filename, Number(piece.$.line) - 1, msg, 2); testEventBuilder.appendMessage('⬆ Failure', 1); } catch (e) { this._shared.log.exceptionS(e); testEventBuilder.appendMessage('Error during processing output', 2); } } } try { if (xml.BenchmarkResults) { for (let i = 0; i < xml.BenchmarkResults.length; i++) { this._processBenchmark(xml.BenchmarkResults[i], stack, testEventBuilder); } } } catch (e) { this._shared.log.exceptionS(e); } if (xml.Expression) { for (let i = 0; i < xml.Expression.length; ++i) { try { const expr = xml.Expression[i]; const file = expr.$.filename; const line = Number(expr.$.line); const message = '❕Original: ' + expr.Original.map((x: string) => x.trim()).join('; ') + '\n' + '❗️Expanded: ' + expr.Expanded.map((x: string) => x.trim()).join('; '); testEventBuilder.appendMessage(`Expression failed (at ${file}:${line}):`, 1); testEventBuilder.appendMessage(message, 2); testEventBuilder.appendDecorator( file, line - 1, expr.Expanded.map((x: string) => x.trim()).join(' | '), message, ); } catch (e) { this._shared.log.exceptionS(e); } } } for (let i = 0; xml.Exception && i < xml.Exception.length; ++i) { try { const piece = xml.Exception[i]; if (typeof piece._ !== 'string') this._shared.log.warn('No _ under exception', piece); const msg = typeof piece._ === 'string' ? piece._.trim() : piece.toString(); testEventBuilder.appendMessage(`${msg} (at ${piece.$.filename}:${piece.$.line})`, 1); testEventBuilder.appendDecorator(piece.$.filename, Number(piece.$.line) - 1, `Exception was thrown: ${msg}`); } catch (e) { this._shared.log.exceptionS(e); } } if (xml.FatalErrorCondition) { for (let i = 0; i < xml.FatalErrorCondition.length; ++i) { try { const piece = xml.FatalErrorCondition[i]; const location = piece.$.filename && piece.$.line ? ` (at ${piece.$.filename}:${piece.$.line})` : ''; testEventBuilder.appendMessage(`⬇ FatalErrorCondition${location}:`, 1); testEventBuilder.appendMessage(piece._, 2); testEventBuilder.appendDecorator(piece.$.filename, Number(piece.$.line) - 1, piece._); testEventBuilder.appendMessage('⬆ FatalErrorCondition', 1); } catch (error) { this._shared.log.exceptionS(error); testEventBuilder.appendMessage('Unknown fatal error: ' + inspect(error), 1); } } } } private _processXmlTagSections( xml: XmlObject, main: Catch2Section, stack: Catch2Section[], testEventBuilder: TestEventBuilder, parentSection: Catch2Section, ): void { for (let j = 0; xml.Section && j < xml.Section.length; ++j) { const section = xml.Section[j]; try { const currSection = ((): Catch2Section => { const found = parentSection.children.find( v => v.name === section.$.name && v.filename === section.$.filename && v.line === section.$.line, ); if (found) return found; const currSection = new Catch2Section(section.$.name, section.$.filename, section.$.line); parentSection.children.push(currSection); return currSection; })(); const isLeaf = section.Section === undefined || section.Section.length === 0; if ( isLeaf && section.OverallResults && section.OverallResults.length > 0 && section.OverallResults[0].$.failures !== '0' ) { currSection.failed = true; } const msg = `⮑ ${isLeaf ? (currSection.failed ? '❌' : '✅') : ''}"${currSection.name}"`; testEventBuilder.appendMessage(msg, stack.length, 3); const currStack = stack.concat(currSection); this._processTags(section, main, currStack, testEventBuilder); this._processXmlTagSections(section, main, currStack, testEventBuilder, currSection); } catch (error) { testEventBuilder.appendMessage('Fatal error processing section', 0); this._shared.log.exceptionS(error); } } } private _processBenchmark(benchmark: XmlObject, stack: Catch2Section[], testEventBuilder: TestEventBuilder): void { const currSection = new Catch2Section(benchmark.$.name, undefined, 0); const msg = `⮑ benchmark of "${currSection.name}"`; testEventBuilder.appendMessage(msg, stack.length, 3); for (let j = 0; benchmark.mean && j < benchmark.mean.length; ++j) { const mean = benchmark.mean[j].$; const params = Object.keys(mean) .filter(n => n !== 'value') .map(key => `${key}: ${mean[key]} ns`) .join(', '); testEventBuilder.appendMessage(`Mean: ${mean.value} ns (${params})`, 2); } for (let j = 0; benchmark.standardDeviation && j < benchmark.standardDeviation.length; ++j) { const standardDeviation = benchmark.standardDeviation[j].$; const params = Object.keys(standardDeviation) .filter(n => n !== 'value') .map(key => `${key}: ${standardDeviation[key]} ns`) .join(', '); testEventBuilder.appendMessage(`Standard Deviation: ${standardDeviation.value} ns (${params})`, 2); } for (let j = 0; benchmark.outliers && j < benchmark.outliers.length; ++j) { const outliers = benchmark.outliers[j].$; const params = Object.keys(outliers) .map(key => `${key}: ${outliers[key]} ns`) .join(', '); testEventBuilder.appendMessage(`Outliers: ${params}`, 2); } testEventBuilder.appendMessage( 'Parameters: ' + Object.keys(benchmark.$) .filter(n => n !== 'name') .map(key => `${key}: ${benchmark.$[key]}`) .join(', '), 2, ); } }
the_stack
import { expect } from "chai"; import { Id64String } from "@itwin/core-bentley"; import { SpatialClassifier, SpatialClassifierFlags, SpatialClassifierInsideDisplay, SpatialClassifierOutsideDisplay, SpatialClassifierProps, SpatialClassifiers, SpatialClassifiersContainer, } from "../SpatialClassification"; describe("SpatialClassifierFlags", () => { it("normalizes display mode", () => { const tests: Array<[number, number | undefined, number | undefined]> = [ [SpatialClassifierInsideDisplay.Off, undefined, undefined], [SpatialClassifierInsideDisplay.On, undefined, undefined], [SpatialClassifierInsideDisplay.Dimmed, undefined, undefined], [SpatialClassifierInsideDisplay.Hilite, undefined, SpatialClassifierOutsideDisplay.Dimmed], [SpatialClassifierInsideDisplay.ElementColor, undefined, SpatialClassifierOutsideDisplay.Dimmed], [-1, SpatialClassifierInsideDisplay.ElementColor, SpatialClassifierOutsideDisplay.Dimmed], [5, SpatialClassifierInsideDisplay.ElementColor, SpatialClassifierOutsideDisplay.Dimmed], ]; for (const test of tests) { const flags = SpatialClassifierFlags.fromJSON({ inside: test[0], outside: test[0] }); expect(flags.inside).to.equal(test[1] ?? test[0]); expect(flags.outside).to.equal(test[2] ?? test[0]); } }); }); describe("SpatialClassifiers", () => { function makeClassifier(modelId: Id64String, name: string, flags = new SpatialClassifierFlags(), expand = 0) { return new SpatialClassifier(modelId, name, flags, expand); } function makeClassifierProps(classifier: SpatialClassifier, isActive?: boolean) { const props = classifier.toJSON(); if (undefined !== isActive) props.isActive = isActive; return props; } function expectJson(actual: SpatialClassifierProps[] | undefined, expected: SpatialClassifierProps[] | undefined) { expect(actual).to.deep.equal(expected); } it("populates from JSON", () => { const json: SpatialClassifiersContainer = {}; let set = new SpatialClassifiers({}); expect(set.size).to.equal(0); expect(json.classifiers).to.be.undefined; const c1 = makeClassifier("0x1c", "c1"); const c2 = makeClassifier("0x2c", "c2", undefined, 12); set = new SpatialClassifiers({ classifiers: [c1.toJSON(), c2.toJSON()] }); expect(set.size).to.equal(2); expect(set.active).to.be.undefined; expect(set.has(c1)).to.be.true; expect(set.has(c2)).to.be.true; }); it("uses first active classifier", () => { const json: SpatialClassifiersContainer = { classifiers: [ makeClassifierProps(makeClassifier("0x1c", "c1"), false), makeClassifierProps(makeClassifier("0x2c", "c2"), true), makeClassifierProps(makeClassifier("0x3c", "c3"), true), makeClassifierProps(makeClassifier("0x4c", "c4"), false), ], }; const set = new SpatialClassifiers(json); const active = set.active!; expect(active).not.to.be.undefined; expect(active.modelId).to.equal("0x2c"); for (const props of json.classifiers!) expect(props.isActive).to.equal(props.modelId === "0x2c"); }); it("sets active classifier", () => { const classifiers = [ makeClassifier("0x1", "1"), makeClassifier("0x2", "2"), makeClassifier("0x3", "3"), ]; const json = { classifiers: classifiers.map((x) => x.toJSON()) }; const set = new SpatialClassifiers(json); expect(set.size).to.equal(3); expect(set.active).to.be.undefined; for (const classifier of set) { expect(set.setActive(classifier)).to.equal(classifier); expect(set.active).to.equal(classifier); for (const props of json.classifiers) expect(props.isActive).to.equal(props.name === classifier.name); expect(set.setActive(undefined)).to.be.undefined; expect(set.active).to.be.undefined; for (const props of json.classifiers) expect(props.isActive).to.be.false; } for (const classifier of classifiers) { expect(set.setActive(classifier)).not.to.equal(classifier); expect(set.active).not.to.equal(classifier); expect(set.active).to.equal(set.findEquivalent(classifier)); } const prevActive = set.active; expect(prevActive).not.to.be.undefined; expect(set.setActive(makeClassifier("0x4", "4"))).to.equal(prevActive); expect(set.active).to.equal(prevActive); expect(set.setActive(undefined)).to.be.undefined; expect(set.active).to.be.undefined; expect(set.setActive(makeClassifier("0x5", "5"))).to.be.undefined; expect(set.active).to.be.undefined; }); it("adds classifiers", () => { const json = { classifiers: [makeClassifier("0x1", "1").toJSON()] }; const set = new SpatialClassifiers(json); expect(set.size).to.equal(1); const c2 = makeClassifier("0x2", "2"); expect(set.add(c2)).to.equal(c2); expect(set.size).to.equal(2); expect(set.has(c2)).to.be.true; const c1 = makeClassifier("0x1", "1"); expect(set.add(c1)).not.to.equal(c1); expect(set.size).to.equal(2); expect(set.add(c1)).to.equal(set.findEquivalent(c1)); expect(set.has(c1)).to.be.true; const c = makeClassifier("0x1", "1", undefined, 12); expect(set.add(c)).to.equal(c); expect(set.size).to.equal(3); expect(set.has(c)).to.be.true; expectJson(json.classifiers, [ makeClassifier("0x1", "1").toJSON(), makeClassifier("0x2", "2").toJSON(), makeClassifier("0x1", "1", undefined, 12).toJSON(), ]); }); it("deletes classifiers", () => { const json = { classifiers: [makeClassifier("0x1", "1").toJSON(), makeClassifier("0x2", "2").toJSON(), makeClassifier("0x3", "3").toJSON()] }; const set = new SpatialClassifiers(json); expect(set.size).to.equal(3); const c2 = set.findEquivalent(makeClassifier("0x2", "2"))!; expect(c2).not.to.be.undefined; expect(set.delete(c2)).to.equal(c2); expect(set.size).to.equal(2); expect(set.delete(c2)).to.be.undefined; expect(set.size).to.equal(2); expectJson(json.classifiers, [makeClassifier("0x1", "1").toJSON(), makeClassifier("0x3", "3").toJSON()]); const c1 = makeClassifier("0x1", "1"); const c1FromSet = set.findEquivalent(c1)!; expect(c1FromSet).not.to.be.undefined; expect(c1FromSet).not.to.equal(c1); expect(set.delete(c1)).to.equal(c1FromSet); expect(set.size).to.equal(1); expectJson(json.classifiers, [makeClassifier("0x3", "3").toJSON()]); for (const c of set) expect(set.delete(c)).to.equal(c); expect(set.size).to.equal(0); expectJson(json.classifiers, undefined); expect(set.add(makeClassifier("0x1", "1"))).not.to.be.undefined; expect(set.size).to.equal(1); expectJson(json.classifiers, [makeClassifier("0x1", "1").toJSON()]); expect(set.delete(makeClassifier("0x4", "4"))).to.be.undefined; expect(set.size).to.equal(1); }); it("resets active classifier if deleted", () => { const set = new SpatialClassifiers({ classifiers: [ makeClassifier("0x1", "1").toJSON(), makeClassifierProps(makeClassifier("0x2", "2"), true), makeClassifier("0x3", "3").toJSON(), ], }); expect(set.active!.name).to.equal("2"); set.delete(set.active!); expect(set.active).to.be.undefined; expect(set.setActive(makeClassifier("0x3", "3"))).not.to.be.undefined; expect(set.active).not.to.be.undefined; set.delete(makeClassifier("0x1", "1")); expect(set.active).not.to.be.undefined; expect(set.active!.name).to.equal("3"); set.delete(makeClassifier("0x3", "3")); expect(set.active).to.be.undefined; expect(set.size).to.equal(0); }); it("clears classifiers", () => { const json = { classifiers: [makeClassifier("0x1", "1").toJSON(), makeClassifier("0x2", "2").toJSON()] }; const set = new SpatialClassifiers(json); expect(set.size).to.equal(2); set.clear(); expect(set.size).to.equal(0); expectJson(json.classifiers, undefined); }); it("resets active classifier when cleared", () => { const set = new SpatialClassifiers({ classifiers: [ makeClassifierProps(makeClassifier("0x1", "1"), true), makeClassifier("0x2", "2").toJSON(), ], }); expect(set.active).not.to.be.undefined; set.clear(); expect(set.active).to.be.undefined; }); it("replaces classifiers", () => { const json = { classifiers: [makeClassifier("0x1", "1").toJSON(), makeClassifier("0x2", "2").toJSON(), makeClassifierProps(makeClassifier("0x3", "3"), true)] }; const set = new SpatialClassifiers(json); const c2 = set.findEquivalent(makeClassifier("0x2", "2"))!; expect(c2.flags.inside).to.equal(SpatialClassifierInsideDisplay.ElementColor); expect(c2.flags.outside).to.equal(SpatialClassifierOutsideDisplay.Dimmed); expect(c2.expand).to.equal(0); const c2New = c2.clone({ flags: c2.flags.clone({ inside: SpatialClassifierInsideDisplay.Hilite }).toJSON(), expand: 12 }); expect(set.replace(c2, c2New)).to.be.true; expect(c2New.equals(c2)).to.be.false; expect(c2New.flags.inside).to.equal(SpatialClassifierInsideDisplay.Hilite); expect(c2New.flags.outside).to.equal(SpatialClassifierOutsideDisplay.Dimmed); expect(c2New.expand).to.equal(12); expect(set.size).to.equal(3); expect(set.has(c2New)).to.be.true; expect(set.has(c2)).to.be.false; const c1 = makeClassifier("0x1", "1"); const c1New = c1.clone({ name: "1new" }); expect(set.replace(c1, c1New)).to.be.true; expect(set.has(c1New)).to.be.true; expect(set.has(c1)).to.be.false; expect(c1New.name).to.equal("1new"); expect(set.active).not.to.be.undefined; expect(set.active!.name).to.equal("3"); const c3New = makeClassifier("0x3", "3new"); expect(set.replace(makeClassifier("0x3", "3"), c3New)).to.be.true; expect(set.active).to.equal(c3New); expect(set.active!.name).to.equal("3new"); expectJson(json.classifiers, [c1New.toJSON(), c2New.toJSON(), makeClassifierProps(c3New, true)]); expect(set.replace(makeClassifier("0x4", "4"), makeClassifier("0x4", "4new"))).to.be.false; set.clear(); expect(set.replace(c3New, makeClassifier("0x3", "3newer"))).to.be.false; }); });
the_stack
import { Auto, IPlugin, execPromise, validatePluginConfiguration, ILogger, getPrNumberFromEnv, DEFAULT_PRERELEASE_BRANCHES, getCurrentBranch, determineNextVersion, } from "@auto-it/core"; import { inc, ReleaseType } from "semver"; import * as t from "io-ts"; import { getPodspecContents, writePodspecContents } from "./utilities"; const logPrefix = "[Cocoapods-Plugin]"; /** Regex used to pull the version line from the spec */ const versionRegex = /\.version\s*=\s*['|"](?<version>\d+\.\d+\.\d+.*?)['|"]/; /** Regex used to pull the source dictionary from the spec */ const sourceLineRegex = /\.source.*(?<source>\{\s*:\s*git.*\})/; /** * Wrapper to add logPrefix to messages * * @param msg - The message to add a prefix to * @returns Log message with prefix prepended */ const logMessage = (msg: string): string => `${logPrefix} ${msg}`; const required = t.interface({ /** Relative path to podspec file */ podspecPath: t.union([t.string, t.array(t.string)]), }); const optional = t.partial({ /** The Cocoapods repo to publish to */ specsRepo: t.string, /** Any additional command line flags to pass to `pod repo push` */ flags: t.array(t.string), /** The command to use for `pod` if it needs to be separate like `bundle exec pod` */ podCommand: t.string, }); const pluginOptions = t.intersection([required, optional]); export type ICocoapodsPluginOptions = t.TypeOf<typeof pluginOptions>; /** * Returns the regex'd version of the podspec file * * @param podspecPath - The relative path to the podspec file * @returns The regular expression array for use in replacing file contents */ export function getParsedPodspecContents( podspecPath: string ): RegExpExecArray | null { const podspecContents = getPodspecContents(podspecPath); return versionRegex.exec(podspecContents); } /** * Retrieves the version currently in the podspec file * * @param podspecPath - The relative path to the podspec file */ export function getVersion(podspecPath: string): string { const podspecContents = getParsedPodspecContents(podspecPath); if (podspecContents?.groups?.version) { return podspecContents.groups.version; } throw new Error(`Version could not be found in podspec: ${podspecPath}`); } /** * Retrieves the source dictionary currently in the podspec file * * @param podspecPath - The relative path to the podspec file */ export function getSourceInfo(podspecPath: string): string { const podspecContents = sourceLineRegex.exec(getPodspecContents(podspecPath)); if (podspecContents?.groups?.source) { return podspecContents.groups.source; } throw new Error(`Source could not be found in podspec: ${podspecPath}`); } /** * Updates the version in the podspec to the supplied version * * @param podspecPath - The relative path to the podspec file * @param version - The version to update the podspec to */ export function updatePodspecVersion(podspecPath: string, version: string) { const previousVersion = getVersion(podspecPath); const parsedContents = getParsedPodspecContents(podspecPath); const podspecContents = getPodspecContents(podspecPath); try { if (parsedContents?.[0]) { const newVersionString = parsedContents[0].replace( previousVersion, version ); const newPodspec = podspecContents.replace( versionRegex, newVersionString ); writePodspecContents(podspecPath, newPodspec); } } catch (error) { throw new Error(`Error updating version in podspec: ${podspecPath}`); } } /** * Updates the source location to point to the current commit for the given remote * * @param podspecPath - The relative path to the podspec file * @param remote - The git remote that is being used */ export async function updateSourceLocation( podspecPath: string, remote: string ) { const podspecContents = getPodspecContents(podspecPath); const source = getSourceInfo(podspecPath); try { const revision = await execPromise("git", ["rev-parse", "HEAD"]); const newPodspec = podspecContents.replace( source, `{ :git => '${remote}', :commit => '${revision}' }` ); writePodspecContents(podspecPath, newPodspec); } catch (error) { throw new Error( `Error updating source location in podspec: ${podspecPath}` ); } } /** Use auto to version your cocoapod */ export default class CocoapodsPlugin implements IPlugin { /** The name of the plugin */ name = "cocoapods"; /** The auto logger */ logger?: ILogger; /** The options of the plugin */ readonly options: ICocoapodsPluginOptions; /** * */ private get paths() { if (typeof this.options.podspecPath === "string") { return [this.options.podspecPath]; } return this.options.podspecPath; } /** Initialize the plugin with it's options */ constructor(options: ICocoapodsPluginOptions) { this.options = options; } /** Tap into auto plugin points. */ apply(auto: Auto) { this.logger = auto.logger; const isQuiet = auto.logger.logLevel === "quiet"; const isVerbose = auto.logger.logLevel === "verbose" || auto.logger.logLevel === "veryVerbose"; const podLogLevel = isQuiet ? ["--silent"] : isVerbose ? ["--verbose"] : []; auto.hooks.validateConfig.tapPromise(this.name, async (name, options) => { if (name === this.name || name === `@auto-it/${this.name}`) { return validatePluginConfiguration(this.name, pluginOptions, options); } }); auto.hooks.modifyConfig.tap(this.name, (config) => ({ ...config, noVersionPrefix: true, })); auto.hooks.getPreviousVersion.tapPromise(this.name, async () => { // Due to CocoaPods being git backed, all the versions will be the same // so there are no git tag collisions return auto.prefixRelease(getVersion(this.paths[0])); }); auto.hooks.version.tapPromise( this.name, async ({ bump, dryRun, quiet }) => { const previousVersion = getVersion(this.paths[0]); const releaseVersion = inc(previousVersion, bump as ReleaseType); if (dryRun && releaseVersion) { if (quiet) { console.log(releaseVersion); } else { auto.logger.log.info(`Would have published: ${releaseVersion}`); } return; } if (!releaseVersion) { throw new Error( `Could not increment previous version: ${previousVersion}` ); } this.paths.forEach((path) => { updatePodspecVersion(path, releaseVersion); }); await execPromise("git", [ "commit", "-am", `"update version: ${releaseVersion} [skip ci]"`, "--no-verify", ]); await execPromise("git", [ "tag", `${releaseVersion}`, "-m", `"Update version to ${releaseVersion}"`, ]); } ); auto.hooks.canary.tapPromise( this.name, async ({ bump, canaryIdentifier, dryRun, quiet }) => { if (!auto.git) { return; } const pr = getPrNumberFromEnv(); if (!pr) { this.logger?.log.info( logMessage( `No PR number found, using ${auto.remote} as the remote for canary. Commit must be pushed for this to work.` ) ); } const remoteRepo = pr ? (await auto.git.getPullRequest(pr)).data.head.repo?.clone_url || auto.remote : auto.remote; const lastRelease = await auto.git.getLatestRelease(); const current = await auto.getCurrentVersion(lastRelease); const nextVersion = inc(current, bump as ReleaseType); const canaryVersion = `${nextVersion}-${canaryIdentifier}`; if (dryRun) { if (quiet) { console.log(canaryVersion); } else { auto.logger.log.info(`Would have published: ${canaryVersion}`); } return; } await this.paths.reduce( (promise, path) => promise.then(async () => { await updateSourceLocation(path, remoteRepo); updatePodspecVersion(path, canaryVersion); }), Promise.resolve() ); // Publish the canary podspec, committing it isn't needed for specs push await this.publishPodSpec(podLogLevel); // Reset changes to podspec file since it doesn't need to be committed await this.paths.reduce( (promise, path) => promise.then(async () => { await execPromise("git", ["checkout", path]); }), Promise.resolve() ); return canaryVersion; } ); auto.hooks.next.tapPromise( this.name, async (preReleaseVersions, { bump, dryRun }) => { if (!auto.git) { return preReleaseVersions; } const prereleaseBranches = auto.config?.prereleaseBranches ?? DEFAULT_PRERELEASE_BRANCHES; const branch = getCurrentBranch() || ""; const prereleaseBranch = prereleaseBranches.includes(branch) ? branch : prereleaseBranches[0]; const lastRelease = await auto.git.getLatestRelease(); const current = (await auto.git.getLastTagNotInBaseBranch(prereleaseBranch)) || (await auto.getCurrentVersion(lastRelease)); const prerelease = determineNextVersion( lastRelease, current, bump, prereleaseBranch ); preReleaseVersions.push(prerelease); if (dryRun) { return preReleaseVersions; } await execPromise("git", [ "tag", prerelease, "-m", `"Tag pre-release: ${prerelease}"`, ]); await execPromise("git", ["push", auto.remote, branch, "--tags"]); this.paths.forEach((path) => updatePodspecVersion(path, prerelease)); // Publish the next podspec, committing it isn't needed for specs push await this.publishPodSpec(podLogLevel); // Reset changes to podspec file since it doesn't need to be committed await Promise.all( this.paths.map((path) => execPromise("git", ["checkout", path])) ); return preReleaseVersions; } ); auto.hooks.beforeShipIt.tapPromise(this.name, async ({ dryRun }) => { if (dryRun) { auto.logger.log.info(logMessage('dryRun - running "pod lib lint"')); const [pod, ...commands] = this.options.podCommand?.split(" ") || [ "pod", ]; await this.paths.reduce( (promise, path) => promise.then(() => execPromise(pod, [ ...commands, "lib", "lint", ...(this.options.flags || []), path, ]) ), Promise.resolve("") ); } }); auto.hooks.publish.tapPromise(this.name, async () => { await execPromise("git", [ "push", "--follow-tags", "--set-upstream", auto.remote, auto.baseBranch, ]); await this.publishPodSpec(podLogLevel); }); } /** * */ async publishPodSpec(podLogLevel: string[]) { const [pod, ...commands] = this.options.podCommand?.split(" ") || ["pod"]; if (!this.options.specsRepo) { this.logger?.log.info(logMessage(`Pushing to Cocoapods trunk`)); await this.paths.reduce( (promise, path) => promise.then(() => execPromise(pod, [ ...commands, "trunk", "push", ...(this.options.flags || []), path, ...podLogLevel, ]) ), Promise.resolve("") ); return; } try { const existingRepos = await execPromise(pod, [ ...commands, "repo", "list", ]); if (existingRepos.indexOf("autoPublishRepo") !== -1) { this.logger?.log.info("Removing existing autoPublishRepo"); await execPromise(pod, [ ...commands, "repo", "remove", "autoPublishRepo", ...podLogLevel, ]); } } catch (error) { this.logger?.log.warn( `Error Checking for existing Specs repositories: ${error}` ); } try { await execPromise(pod, [ ...commands, "repo", "add", "autoPublishRepo", this.options.specsRepo, ...podLogLevel, ]); this.logger?.log.info( logMessage(`Pushing to specs repo: ${this.options.specsRepo}`) ); await this.paths.reduce( (promise, path) => promise.then(() => execPromise(pod, [ ...commands, "repo", "push", ...(this.options.flags || []), "autoPublishRepo", path, ...podLogLevel, ]) ), Promise.resolve("") ); } catch (error) { this.logger?.log.error( logMessage( `Error pushing to specs repo: ${this.options.specsRepo}. Error: ${error}` ) ); process.exit(1); } finally { await execPromise(pod, [ ...commands, "repo", "remove", "autoPublishRepo", ...podLogLevel, ]); } } }
the_stack
import * as vscode from 'vscode'; import * as assert from 'assert'; import { promises as fs } from 'fs'; import * as path from 'path'; import * as os from 'os'; import 'mocha'; const testFolder = fs.mkdtemp(path.join(os.tmpdir(), 'conf-editing-')); suite('Completions in settings.json', () => { const testFile = 'settings.json'; test('window.title', async () => { { // inserting after text const content = [ '{', ' "window.title": "custom|"', '}', ].join('\n'); const resultText = [ '{', ' "window.title": "custom${activeEditorShort}"', '}', ].join('\n'); const expected = { label: '${activeEditorShort}', resultText }; await testCompletion(testFile, 'jsonc', content, expected); } { // inserting before a variable const content = [ '{', ' "window.title": "|${activeEditorShort}"', '}', ].join('\n'); const resultText = [ '{', ' "window.title": "${folderPath}${activeEditorShort}"', '}', ].join('\n'); const expected = { label: '${folderPath}', resultText }; await testCompletion(testFile, 'jsonc', content, expected); } { // inserting after a variable const content = [ '{', ' "window.title": "${activeEditorShort}|"', '}', ].join('\n'); const resultText = [ '{', ' "window.title": "${activeEditorShort}${folderPath}"', '}', ].join('\n'); const expected = { label: '${folderPath}', resultText }; await testCompletion(testFile, 'jsonc', content, expected); } { // replacing an variable const content = [ '{', ' "window.title": "${a|ctiveEditorShort}"', '}', ].join('\n'); const resultText = [ '{', ' "window.title": "${activeEditorMedium}"', '}', ].join('\n'); const expected = { label: '${activeEditorMedium}', resultText }; await testCompletion(testFile, 'jsonc', content, expected); } { // inserting a literal const content = [ '{', ' "window.title": |', '}', ].join('\n'); const resultText = [ '{', ' "window.title": "${activeEditorMedium}"', '}', ].join('\n'); const expected = { label: '"${activeEditorMedium}"', resultText }; await testCompletion(testFile, 'jsonc', content, expected); } { // no proposals after literal const content = [ '{', ' "window.title": "${activeEditorShort}" |', '}', ].join('\n'); const expected = { label: '${activeEditorMedium}', notAvailable: true }; await testCompletion(testFile, 'jsonc', content, expected); } }); test('files.associations', async () => { { const content = [ '{', ' "files.associations": {', ' |', ' }', '}', ].join('\n'); const resultText = [ '{', ' "files.associations": {', ' "*.${1:extension}": "${2:language}"', ' }', '}', ].join('\n'); const expected = { label: 'Files with Extension', resultText }; await testCompletion(testFile, 'jsonc', content, expected); } { const content = [ '{', ' "files.associations": {', ' |', ' }', '}', ].join('\n'); const resultText = [ '{', ' "files.associations": {', ' "/${1:path to file}/*.${2:extension}": "${3:language}"', ' }', '}', ].join('\n'); const expected = { label: 'Files with Path', resultText }; await testCompletion(testFile, 'jsonc', content, expected); } { const content = [ '{', ' "files.associations": {', ' "*.extension": "|bat"', ' }', '}', ].join('\n'); const resultText = [ '{', ' "files.associations": {', ' "*.extension": "json"', ' }', '}', ].join('\n'); const expected = { label: '"json"', resultText }; await testCompletion(testFile, 'jsonc', content, expected); } { const content = [ '{', ' "files.associations": {', ' "*.extension": "bat"|', ' }', '}', ].join('\n'); const resultText = [ '{', ' "files.associations": {', ' "*.extension": "json"', ' }', '}', ].join('\n'); const expected = { label: '"json"', resultText }; await testCompletion(testFile, 'jsonc', content, expected); } { const content = [ '{', ' "files.associations": {', ' "*.extension": "bat" |', ' }', '}', ].join('\n'); const expected = { label: '"json"', notAvailable: true }; await testCompletion(testFile, 'jsonc', content, expected); } }); test('files.exclude', async () => { { const content = [ '{', ' "files.exclude": {', ' |', ' }', '}', ].join('\n'); const resultText = [ '{', ' "files.exclude": {', ' "**/*.${1:extension}": true', ' }', '}', ].join('\n'); const expected = { label: 'Files by Extension', resultText }; await testCompletion(testFile, 'jsonc', content, expected); } { const content = [ '{', ' "files.exclude": {', ' "**/*.extension": |true', ' }', '}', ].join('\n'); const resultText = [ '{', ' "files.exclude": {', ' "**/*.extension": { "when": "$(basename).${1:extension}" }', ' }', '}', ].join('\n'); const expected = { label: 'Files with Siblings by Name', resultText }; await testCompletion(testFile, 'jsonc', content, expected); } }); test('files.defaultLanguage', async () => { { const content = [ '{', ' "files.defaultLanguage": "json|"', '}', ].join('\n'); const resultText = [ '{', ' "files.defaultLanguage": "jsonc"', '}', ].join('\n'); const expected = { label: '"jsonc"', resultText }; await testCompletion(testFile, 'jsonc', content, expected); } { const content = [ '{', ' "files.defaultLanguage": |', '}', ].join('\n'); const resultText = [ '{', ' "files.defaultLanguage": "jsonc"', '}', ].join('\n'); const expected = { label: '"jsonc"', resultText }; await testCompletion(testFile, 'jsonc', content, expected); } }); test('remote.extensionKind', async () => { { const content = [ '{', '\t"remote.extensionKind": {', '\t\t|', '\t}', '}', ].join('\n'); const expected = { label: 'vscode.npm' }; await testCompletion(testFile, 'jsonc', content, expected); } }); test('remote.portsAttributes', async () => { { const content = [ '{', ' "remote.portsAttributes": {', ' |', ' }', '}', ].join('\n'); const expected = { label: '"3000"' }; await testCompletion(testFile, 'jsonc', content, expected); } }); }); suite('Completions in extensions.json', () => { const testFile = 'extensions.json'; test('change recommendation', async () => { { const content = [ '{', ' "recommendations": [', ' "|a.b"', ' ]', '}', ].join('\n'); const resultText = [ '{', ' "recommendations": [', ' "ms-vscode.js-debug"', ' ]', '}', ].join('\n'); const expected = { label: 'ms-vscode.js-debug', resultText }; await testCompletion(testFile, 'jsonc', content, expected); } }); test('add recommendation', async () => { { const content = [ '{', ' "recommendations": [', ' |', ' ]', '}', ].join('\n'); const resultText = [ '{', ' "recommendations": [', ' "ms-vscode.js-debug"', ' ]', '}', ].join('\n'); const expected = { label: 'ms-vscode.js-debug', resultText }; await testCompletion(testFile, 'jsonc', content, expected); } }); }); suite('Completions in launch.json', () => { const testFile = 'launch.json'; test('variable completions', async () => { { const content = [ '{', ' "version": "0.2.0",', ' "configurations": [', ' {', ' "name": "Run Extension",', ' "type": "extensionHost",', ' "preLaunchTask": "${|defaultBuildTask}"', ' }', ' ]', '}', ].join('\n'); const resultText = [ '{', ' "version": "0.2.0",', ' "configurations": [', ' {', ' "name": "Run Extension",', ' "type": "extensionHost",', ' "preLaunchTask": "${cwd}"', ' }', ' ]', '}', ].join('\n'); const expected = { label: '${cwd}', resultText }; await testCompletion(testFile, 'jsonc', content, expected); } { const content = [ '{', ' "version": "0.2.0",', ' "configurations": [', ' {', ' "name": "Run Extension",', ' "type": "extensionHost",', ' "preLaunchTask": "|${defaultBuildTask}"', ' }', ' ]', '}', ].join('\n'); const resultText = [ '{', ' "version": "0.2.0",', ' "configurations": [', ' {', ' "name": "Run Extension",', ' "type": "extensionHost",', ' "preLaunchTask": "${cwd}${defaultBuildTask}"', ' }', ' ]', '}', ].join('\n'); const expected = { label: '${cwd}', resultText }; await testCompletion(testFile, 'jsonc', content, expected); } }); }); suite('Completions in tasks.json', () => { const testFile = 'tasks.json'; test('variable completions', async () => { { const content = [ '{', ' "version": "0.2.0",', ' "tasks": [', ' {', ' "type": "shell",', ' "command": "${|defaultBuildTask}"', ' }', ' ]', '}', ].join('\n'); const resultText = [ '{', ' "version": "0.2.0",', ' "tasks": [', ' {', ' "type": "shell",', ' "command": "${cwd}"', ' }', ' ]', '}', ].join('\n'); const expected = { label: '${cwd}', resultText }; await testCompletion(testFile, 'jsonc', content, expected); } { const content = [ '{', ' "version": "0.2.0",', ' "tasks": [', ' {', ' "type": "shell",', ' "command": "${defaultBuildTask}|"', ' }', ' ]', '}', ].join('\n'); const resultText = [ '{', ' "version": "0.2.0",', ' "tasks": [', ' {', ' "type": "shell",', ' "command": "${defaultBuildTask}${cwd}"', ' }', ' ]', '}', ].join('\n'); const expected = { label: '${cwd}', resultText }; await testCompletion(testFile, 'jsonc', content, expected); } }); }); suite('Completions in keybindings.json', () => { const testFile = 'keybindings.json'; test('context key insertion', async () => { { const content = [ '[', ' {', ' "key": "ctrl+k ctrl+,",', ' "command": "editor.jumpToNextFold",', ' "when": "|"', ' }', ']', ].join('\n'); const resultText = [ '[', ' {', ' "key": "ctrl+k ctrl+,",', ' "command": "editor.jumpToNextFold",', ' "when": "resourcePath"', ' }', ']', ].join('\n'); const expected = { label: 'resourcePath', resultText }; await testCompletion(testFile, 'jsonc', content, expected); } }); test('context key replace', async () => { { const content = [ '[', ' {', ' "key": "ctrl+k ctrl+,",', ' "command": "editor.jumpToNextFold",', ' "when": "resou|rcePath"', ' }', ']', ].join('\n'); const resultText = [ '[', ' {', ' "key": "ctrl+k ctrl+,",', ' "command": "editor.jumpToNextFold",', ' "when": "resource"', ' }', ']', ].join('\n'); const expected = { label: 'resource', resultText }; await testCompletion(testFile, 'jsonc', content, expected); } }); }); interface ItemDescription { label: string; resultText?: string; notAvailable?: boolean; } async function testCompletion(testFileName: string, languageId: string, content: string, expected: ItemDescription) { const offset = content.indexOf('|'); content = content.substring(0, offset) + content.substring(offset + 1); const docUri = vscode.Uri.file(path.join(await testFolder, testFileName)); await fs.writeFile(docUri.fsPath, content); const editor = await setTestContent(docUri, languageId, content); const position = editor.document.positionAt(offset); // Executing the command `vscode.executeCompletionItemProvider` to simulate triggering completion const actualCompletions = (await vscode.commands.executeCommand('vscode.executeCompletionItemProvider', docUri, position)) as vscode.CompletionList; const matches = actualCompletions.items.filter(completion => { return completion.label === expected.label; }); if (expected.notAvailable) { assert.strictEqual(matches.length, 0, `${expected.label} should not existing is results`); } else { assert.strictEqual(matches.length, 1, `${expected.label} should only existing once: Actual: ${actualCompletions.items.map(c => c.label).join(', ')}`); if (expected.resultText) { const match = matches[0]; if (match.range && match.insertText) { const range = match.range instanceof vscode.Range ? match.range : match.range.replacing; const text = typeof match.insertText === 'string' ? match.insertText : match.insertText.value; await editor.edit(eb => eb.replace(range, text)); assert.strictEqual(editor.document.getText(), expected.resultText); } else { assert.fail(`Range or insertText missing`); } } } } async function setTestContent(docUri: vscode.Uri, languageId: string, content: string): Promise<vscode.TextEditor> { const ext = vscode.extensions.getExtension('vscode.configuration-editing')!; await ext.activate(); const doc = await vscode.workspace.openTextDocument(docUri); await vscode.languages.setTextDocumentLanguage(doc, languageId); const editor = await vscode.window.showTextDocument(doc); const fullRange = new vscode.Range(new vscode.Position(0, 0), doc.positionAt(doc.getText().length)); await editor.edit(eb => eb.replace(fullRange, content)); return editor; }
the_stack
import { ScrollViewItem } from "./scrollviewitem"; import { TimerMgr } from "../timer/timer_mgr"; import { gen_handler } from "../util"; import { LayoutUtil } from "./layout_utils"; import { Action1 } from "../../const"; export class ScrollView extends cc.EventTarget { protected scrollview:cc.ScrollView; protected mask:cc.Mask; protected content:cc.Node; protected item_templates:Map<string, cc.Node>; protected item_classes:Map<string, new() => ScrollViewItem>; protected item_pools:Map<string, ScrollViewItem[]>; protected dir:number; protected width:number; protected height:number; protected original_width:number; protected original_height:number; protected gap_x:number; protected gap_y:number; protected padding_left:number; protected padding_right:number; protected padding_top:number; protected padding_bottom:number; protected item_anchorX:number; protected item_anchorY:number; protected cb_host:any; protected scroll_to_end_cb:Action1; protected auto_scrolling:boolean; protected packItems:PackItem[]; protected start_index:number; protected stop_index:number; private _selected_index:number = -1; private content_width:number; private content_height:number; private min_item_width:number; private min_item_height:number; private max_item_width:number; private max_item_height:number; private renderDirty:boolean; private timer:number; constructor(params:ScrollViewParams) { super(); this.scrollview = params.scrollview; this.mask = params.mask; this.content = params.content; this.item_pools = new Map(); this.item_templates = new Map(); this.item_classes = new Map(); params.item_templates.forEach(tpl => { tpl.node.active = false; this.item_templates.set(tpl.key, tpl.node); this.item_classes.set(tpl.key, tpl.item_class); }); this.dir = params.direction || ScrollDirection.Vertical; this.width = params.width || this.scrollview.node.width; this.height = params.height || this.scrollview.node.height; this.gap_x = params.gap_x || 0; this.gap_y = params.gap_y || 0; this.padding_left = params.padding_left || 0; this.padding_right = params.padding_right || 0; this.padding_top = params.padding_top || 0; this.padding_bottom = params.padding_bottom || 0; this.item_anchorX = params.item_anchorX != null ? params.item_anchorX : 0; this.item_anchorY = params.item_anchorY != null ? params.item_anchorY : 1; this.cb_host = params.cb_host; this.scroll_to_end_cb = params.scroll_to_end_cb; this.auto_scrolling = params.auto_scrolling || false; this.min_item_width = Infinity; this.min_item_height = Infinity; this.max_item_width = 0; this.max_item_height = 0; if(this.dir == ScrollDirection.Vertical) { this.set_content_size(this.width, 0); } else { this.set_content_size(0, this.height); } this.original_width = this.width; this.original_height = this.height; this.mask.node.setContentSize(this.width, this.height); this.scrollview.node.setContentSize(this.width, this.height); this.scrollview.vertical = this.dir == ScrollDirection.Vertical; this.scrollview.horizontal = this.dir == ScrollDirection.Horizontal; this.scrollview.inertia = true; this.scrollview.node.on("scrolling", this.on_scrolling, this); this.scrollview.node.on("scroll-to-bottom", this.on_scroll_to_end, this); this.scrollview.node.on("scroll-to-right", this.on_scroll_to_end, this); this.scrollview.node.on(cc.Node.EventType.TOUCH_START, this.on_scroll_touch_start, this); this.scrollview.node.on(cc.Node.EventType.TOUCH_END, this.on_scroll_touch_end, this); this.scrollview.node.on(cc.Node.EventType.TOUCH_CANCEL, this.on_scroll_touch_cancel, this); this.timer = TimerMgr.getInst().add_updater(gen_handler(this.onUpdate, this), "scrollView render timer"); // cc.log("constructor", this.mask.width, this.mask.height, this.scrollview.node.width, this.scrollview.node.height, this.content.width, this.content.height); } protected _touchBeganPosition:cc.Vec2; protected _touchEndPosition:cc.Vec2; private on_scroll_touch_start(event:cc.Event.EventTouch) { this._touchBeganPosition = event.touch.getLocation(); } private on_scroll_touch_cancel(event:cc.Event.EventTouch) { this._touchEndPosition = event.touch.getLocation(); this.handle_release_logic(); } private on_scroll_touch_end(event:cc.Event.EventTouch) { this._touchEndPosition = event.touch.getLocation(); this.handle_release_logic(); } protected handle_release_logic() { const touchPos = this._touchEndPosition; const moveOffset = this._touchBeganPosition.sub(this._touchEndPosition); const dragDirection = this.get_drag_direction(moveOffset); if(dragDirection != 0) { return; } if(!this.packItems || !this.packItems.length) { return; } //无滑动的情况下点击 const touchPosInContent = this.content.convertToNodeSpaceAR(touchPos); for(let i = this.start_index; i <= this.stop_index; i++) { const packItem = this.packItems[i]; if(packItem && packItem.item && packItem.item.node.getBoundingBox().contains(touchPosInContent)) { packItem.item.onTouchEnd(packItem.key, packItem.data, packItem.item.node.convertToNodeSpaceAR(touchPos), i); break; } } } protected get_drag_direction(moveOffset:cc.Vec2) { if (this.dir === ScrollDirection.Horizontal) { if (Math.abs(moveOffset.x) < 3) { return 0; } return (moveOffset.x > 0 ? 1 : -1); } else if (this.dir === ScrollDirection.Vertical) { // 由于滚动 Y 轴的原点在在右上角所以应该是小于 0 if (Math.abs(moveOffset.y) < 3) { return 0; } return (moveOffset.y < 0 ? 1 : -1); } } private on_scroll_to_end() { if(this.scroll_to_end_cb) { this.scroll_to_end_cb.call(this.cb_host); } } private last_content_pos:number; protected on_scrolling() { let pos:number; let threshold:number; if(this.dir == ScrollDirection.Vertical) { pos = this.content.y; threshold = this.min_item_height; } else { pos = this.content.x; threshold = this.min_item_width; } if(this.last_content_pos != null && Math.abs(pos - this.last_content_pos) < threshold) { return; } this.last_content_pos = pos; this.render(); } protected render() { if(!this.packItems || !this.packItems.length) { return; } if(this.dir == ScrollDirection.Vertical) { let posy = this.content.y; // cc.log("onscrolling, content posy=", posy); if(posy < 0) { posy = 0; } if(posy > this.content_height - this.height) { posy = this.content_height - this.height; } let viewport_start = -posy; let viewport_stop = viewport_start - this.height; // while(this.packItems[start].y - this.packItems[start].height > viewport_start) // { // start++; // } // while(this.packItems[stop].y < viewport_stop) // { // stop--; // } let start = this.indexFromOffset(viewport_start); let stop = this.indexFromOffset(viewport_stop); //expand viewport for better experience start = Math.max(start - 1, 0); stop = Math.min(this.packItems.length - 1, stop + 1); if(start != this.start_index) { this.start_index = start; this.renderDirty = true; } if(stop != this.stop_index) { this.stop_index = stop; this.renderDirty = true; } } else { let posx = this.content.x; // cc.log("onscrolling, content posx=", posx); if(posx > 0) { posx = 0; } if(posx < this.width - this.content_width) { posx = this.width - this.content_width; } let viewport_start = -posx; let viewport_stop = viewport_start + this.width; // while(this.packItems[start].x + this.packItems[start].width < viewport_start) // { // start++; // } // while(this.packItems[stop].x > viewport_stop) // { // stop--; // } let start = this.indexFromOffset(viewport_start); let stop = this.indexFromOffset(viewport_stop); //expand viewport for better experience start = Math.max(start - 1, 0); stop = Math.min(this.packItems.length - 1, stop + 1); if(start != this.start_index) { this.start_index = start; this.renderDirty = true; } if(stop != this.stop_index) { this.stop_index = stop; this.renderDirty = true; } } } onUpdate() { if(this.renderDirty && cc.isValid(this.scrollview.node)) { cc.log("scrollView, render_from:", this.start_index, this.stop_index); this.render_items(); this.renderDirty = false; } } private indexFromOffset(offset:number) { let low = 0; let high = 0; let max_idx = 0; high = max_idx = this.packItems.length - 1; if(this.dir == ScrollDirection.Vertical) { while(high >= low) { const index = low + Math.floor((high - low) / 2); const itemStart = this.packItems[index].y; const itemStop = index < max_idx ? this.packItems[index + 1].y : -this.content_height; if(offset <= itemStart && offset >= itemStop) { return index; } else if(offset > itemStart) { high = index - 1; } else { low = index + 1; } } } else { while(high >= low) { const index = low + Math.floor((high - low) / 2); const itemStart = this.packItems[index].x; const itemStop = index < max_idx ? this.packItems[index + 1].x : this.content_width; if(offset >= itemStart && offset <= itemStop) { return index; } else if(offset > itemStart) { low = index + 1; } else { high = index - 1; } } } return -1; } select_data(data) { const idx = this.packItems.findIndex(item => item.data == data); if(idx != -1) { this.select_item(idx); } } select_item(index:number) { if(index == this._selected_index) { return; } if(this._selected_index != -1) { this.inner_select_item(this._selected_index, false); } this._selected_index = index; this.inner_select_item(index, true); } private inner_select_item(index:number, is_select:boolean) { let packItem:PackItem = this.packItems[index]; if(!packItem) { cc.warn("inner_select_item index is out of range{", 0, this.packItems.length - 1, "}", index); return; } packItem.is_select = is_select; if(packItem.item) { packItem.item.onSetSelect(packItem.key, is_select, index); if(is_select) { packItem.item.onSelected(packItem.key, packItem.data, index); } } } private spawn_item(key:string, is_measure = false):ScrollViewItem { const pools = this.item_pools.get(key); let item:ScrollViewItem; if(pools && pools.length > 0) { item = pools.pop(); } else { item = cc.instantiate(this.item_templates.get(key)).addComponent(this.item_classes.get(key)) as ScrollViewItem; item.node.active = true; //仅仅改变父节点锚点,子元素位置不会随之变化 // item.node.setAnchorPoint(this.item_anchorX, this.item_anchorY); LayoutUtil.set_pivot_smart(item.node, this.item_anchorX, this.item_anchorY); item.onInit(key); // cc.log("spawn_item, key=", key); } if(!is_measure) { item.node.parent = this.content; } return item; } private recycle_item(packItem:PackItem, is_measure = false) { const item = packItem.item; if(item && cc.isValid(item.node)) { let pools = this.item_pools.get(packItem.key); if(!pools) { pools = []; this.item_pools.set(packItem.key, pools); } pools.push(item); item.onRecycle(packItem.key, packItem.data, is_measure); item.node.removeFromParent(); packItem.item = null; } } private clear_items() { if(this.packItems) { this.packItems.forEach(packItem => { this.recycle_item(packItem); }); } } private render_items() { let packItem:PackItem; for(let i = 0; i < this.start_index; i++) { packItem = this.packItems[i]; if(packItem.item) { // cc.log("recycle_item", i); this.recycle_item(packItem); } } for(let i = this.packItems.length - 1; i > this.stop_index; i--) { packItem = this.packItems[i]; if(packItem.item) { // cc.log("recycle_item", i); this.recycle_item(packItem); } } for(let i = this.start_index; i <= this.stop_index; i++) { packItem = this.packItems[i]; if(!packItem.item) { // cc.log("render_item", i); packItem.item = this.spawn_item(packItem.key); packItem.item.onSetData(packItem.key, packItem.data, i, false); packItem.item.onSetSelect(packItem.key, packItem.is_select, i); if(packItem.is_select) { packItem.item.onSelected(packItem.key, packItem.data, i); } } // packItem.item.node.setPosition(packItem.x, packItem.y); packItem.item.setLeftTop(packItem.x, packItem.y); } } private pack_item(index:number, data:ScrollItemData):PackItem { const item = this.spawn_item(data.key, true); const [width, height]:[number, number] = item.onSetData(data.key, data.data, index, true); const packItem:PackItem = {x:0, y:0, width, height, item, key:data.key, data:data.data, is_select:false}; this.recycle_item(packItem, true); if(width < this.min_item_width) { this.min_item_width = width; } else if(width > this.max_item_width) { this.max_item_width = width; } if(height < this.min_item_height) { this.min_item_height = height; } else if(height > this.max_item_height) { this.max_item_height = height; } return packItem; } protected layout_items(start:number) { // cc.log("layout_items, start=", start); if(this.packItems.length <= 0) { return; } let start_pos = this.dir == ScrollDirection.Vertical ? -this.padding_top : this.padding_left; if(start > 0) { const prev_packItem = this.packItems[start - 1]; if(this.dir == ScrollDirection.Vertical) { start_pos = prev_packItem.y - prev_packItem.height - this.gap_y; } else { start_pos = prev_packItem.x + prev_packItem.width + this.gap_x; } } for(let index = start, stop = this.packItems.length; index < stop; index++) { const packItem = this.packItems[index]; if(this.dir == ScrollDirection.Vertical) { packItem.x = this.padding_left; packItem.y = start_pos; start_pos -= packItem.height + this.gap_y; } else { packItem.x = start_pos; packItem.y = -this.padding_top; start_pos += packItem.width + this.gap_x; } } } private adjust_content() { if(this.packItems.length <= 0) { this.set_content_size(0, 0); return; } const last_packItem = this.packItems[this.packItems.length - 1]; if(this.dir == ScrollDirection.Vertical) { //content_width可能比width大,导致水平方向上有部分内容被裁剪 const width = Math.max(this.width, this.padding_left + this.max_item_width + this.padding_right); const height = Math.max(this.height, last_packItem.height - last_packItem.y + this.padding_bottom); this.set_content_size(width, height); } else { const width = Math.max(this.width, last_packItem.x + last_packItem.width + this.padding_right); //content_height可能比height大,导致垂直方向上有部分内容被裁剪 const height = Math.max(this.height, this.padding_top + this.max_item_height + this.padding_bottom); this.set_content_size(width, height); } } private set_content_size(width:number, height:number) { if(this.content_width != width) { this.content_width = width; this.content.width = width; } if(this.content_height != height) { this.content_height = height; this.content.height = height; } // cc.log("ScrollView, set_content_size", width, height, this.content.width, this.content.height); } set_viewport(width?:number, height?:number) { if(width == null) { width = this.width; } else if(width > this.content_width) { width = this.content_width; } if(height == null) { height = this.height; } else if(height > this.content_height) { height = this.content_height; } //设置遮罩区域尺寸 this.width = width; this.height = height; this.mask.node.setContentSize(width, height); this.scrollview.node.setContentSize(width, height); this.render(); } renderAll(value:boolean) { let width:number; let height:number; if(value) { width = this.content_width; height = this.content_height; } else { width = this.original_width; height = this.original_height; } this.set_viewport(width, height); } set_data(datas:ScrollItemData[]) { if(this.packItems) { this.clear_items(); this.packItems.length = 0; } else { this.packItems = []; } datas.forEach((data, index) => { let packItem = this.pack_item(index, data); this.packItems.push(packItem); }); this.layout_items(0); this.adjust_content(); this.start_index = -1; this.stop_index = -1; if(this.dir == ScrollDirection.Vertical) { this.content.y = 0; } else { this.content.x = 0; } if(this.packItems.length > 0) { this.render(); } } insert_data(index:number, ...datas:ScrollItemData[]) { if(datas.length == 0 ) { cc.log("nothing to insert"); return; } if(!this.packItems) { this.packItems = []; } if(index < 0 || index > this.packItems.length) { cc.warn("insert_data, invalid index", index); return; } let is_append = index == this.packItems.length; let packItems:PackItem[] = []; datas.forEach((data, index) => { let packItem = this.pack_item(index, data); packItems.push(packItem); }); this.packItems.splice(index, 0, ...packItems); this.layout_items(index); this.adjust_content(); this.start_index = -1; this.stop_index = -1; if(this.auto_scrolling && is_append) { this.scroll_to_end(); } this.render(); } remove_data(index:number, count:number = 1) { if(!this.packItems) { cc.log("call set_data before call this method"); return; } if(index < 0 || index >= this.packItems.length) { cc.warn("remove_data, invalid index", index); return; } if(count < 1) { cc.log("nothing to remove"); return; } let old_length = this.packItems.length; let del_items = this.packItems.splice(index, count); //回收node del_items.forEach(packItem => { this.recycle_item(packItem); }); //重新排序index后面的 if(index + count < old_length) { this.layout_items(index); } this.adjust_content(); if(this.packItems.length > 0) { this.start_index = -1; this.stop_index = -1; this.render(); } } append_data(...datas:ScrollItemData[]) { if(!this.packItems) { this.packItems = []; } this.insert_data(this.packItems.length, ...datas); } scroll_to_end() { if(this.dir == ScrollDirection.Vertical) { this.scrollview.scrollToBottom(); } else { this.scrollview.scrollToRight(); } } scroll_to(index:number, time:number = 0) { if(!this.packItems) { return; } const packItem = this.packItems[index]; if(!packItem) { cc.log("scroll_to, index out of range"); return; } if(this.dir = ScrollDirection.Vertical) { const min_y = this.height - this.content_height; if(min_y >= 0) { cc.log("no need to scroll"); return; } let y = packItem.y; if(y < min_y) { y = min_y; cc.log("content reach bottom"); } const x = this.content.x; if(time == 0) { this.scrollview.setContentPosition(cc.v2(x, -y)); } else { this.scrollview.scrollToOffset(cc.v2(x, -y), time); } this.render(); } else { const max_x = this.content_width - this.width; if(max_x <= 0) { cc.log("no need to scroll"); return; } let x = packItem.x; if(x > max_x) { x = max_x; cc.log("content reach right"); } const y = this.content.y; if(time == 0) { this.scrollview.setContentPosition(cc.v2(-x, y)); } else { this.scrollview.scrollToOffset(cc.v2(-x, y), time); } this.render(); } } get_scroll_offset() { const offset = this.scrollview.getScrollOffset(); if(this.dir == ScrollDirection.Vertical) { return offset.y; } else { return offset.x; } } scroll_to_offset(value:number, time = 0) { if(this.dir == ScrollDirection.Vertical) { const x = this.content.x; if(time == 0) { this.scrollview.setContentPosition(cc.v2(x, value)); } else { this.scrollview.scrollToOffset(cc.v2(x, value), time); } this.render(); } else { const y = this.content.y; if(time == 0) { this.scrollview.setContentPosition(cc.v2(value, y)); } else { this.scrollview.scrollToOffset(cc.v2(value, y), time); } this.render(); } } refresh_item(index:number, data:ScrollItemData) { const packItem = this.get_pack_item(index); if(!packItem) { return; } const oldData = packItem; packItem.key = data.key; packItem.data = data.data; if(packItem.item) { packItem.item.onRecycle(oldData.key, oldData.data, false); packItem.item.onSetData(packItem.key, packItem.data, index, false); } } reload_item(index:number) { const packItem = this.get_pack_item(index); if(packItem && packItem.item) { packItem.item.onRecycle(packItem.key, packItem.data, false); packItem.item.onSetData(packItem.key, packItem.data, index, false); } } private get_pack_item(index:number) { if(!this.packItems) { cc.log("call set_data before call this method"); return null; } if(index < 0 || index >= this.packItems.length) { cc.warn("get_pack_item, invalid index", index); return null; } return this.packItems[index]; } get_item(index:number) { const packItem = this.get_pack_item(index); return packItem ? packItem.item : null; } get_data(index:number) { const packItem = this.get_pack_item(index); return packItem ? packItem.data : null; } find_item(predicate:(key:string, data:any) => boolean) { if(!this.packItems || !this.packItems.length) { cc.log("call set_data before call this method"); return null; } for(let i = this.start_index; i <= this.stop_index; i++) { const packItem = this.packItems[i]; if(predicate(packItem.key, packItem.data)) { return packItem.item; } } return null; } find_index(predicate:(key:string, data:any) => boolean) { if(!this.packItems || !this.packItems.length) { cc.log("call set_data before call this method"); return -1; } return this.packItems.findIndex(packItem => { return predicate(packItem.key, packItem.data); }); } get renderedItems() { const items:ScrollViewItem[] = []; for(let i = this.start_index; i <= this.stop_index; i++) { const packItem = this.packItems[i]; if(packItem && packItem.item) { items.push(packItem.item); } } return items; } get length() { if(!this.packItems) { cc.log("call set_data before call this method"); return 0; } return this.packItems.length; } destroy() { this.clear_items(); this.item_pools.forEach((pools, key) => { pools.forEach(item => { item.onUnInit(key); item.node.destroy(); }); }); this.item_templates = null; this.item_classes = null; this.item_pools = null; this.packItems = null; if(this.timer) { TimerMgr.getInst().remove(this.timer); this.timer = null; } this.renderDirty = null; if(cc.isValid(this.scrollview.node)) { this.scrollview.node.off("scrolling", this.on_scrolling, this); this.scrollview.node.off("scroll-to-bottom", this.on_scroll_to_end, this); this.scrollview.node.off("scroll-to-right", this.on_scroll_to_end, this); this.scrollview.node.off(cc.Node.EventType.TOUCH_START, this.on_scroll_touch_start, this); this.scrollview.node.off(cc.Node.EventType.TOUCH_END, this.on_scroll_touch_end, this); this.scrollview.node.off(cc.Node.EventType.TOUCH_CANCEL, this.on_scroll_touch_cancel, this); } } get selected_index():number { return this._selected_index; } get selected_data():any { let packItem:PackItem = this.packItems[this._selected_index]; if(packItem) { return packItem.data; } return null; } set scrollable(value:boolean) { if(this.dir == ScrollDirection.Vertical) { this.scrollview.vertical = value; } else { this.scrollview.horizontal = value; } } } export type ScrollItemTemplate = { key:string; node:cc.Node; item_class:new() => ScrollViewItem; //item对应的类型 } export type ScrollItemData = { key:string; data:any; } export enum ScrollDirection { Vertical = 1, Horizontal = 2, } export type ScrollViewParams = { scrollview:cc.ScrollView; mask:cc.Mask; content:cc.Node; item_templates:ScrollItemTemplate[]; direction?:ScrollDirection; width?:number; height?:number; gap_x?:number; gap_y?:number; padding_left?:number; padding_right?:number; padding_top?:number; padding_bottom?:number; item_anchorX?:number; item_anchorY?:number; cb_host?:any; //回调函数host scroll_to_end_cb?:Action1; //滚动到尽头的回调 auto_scrolling?:boolean; //append时自动滚动到尽头 } type PackItem = { x:number; y:number; width:number; height:number; key:string; data:any; is_select:boolean; item:ScrollViewItem; }
the_stack
import * as PIXI from 'pixi.js'; import { Engine, Composite, World, Constraint, Body, Bodies, Vector, Grid } from 'matter-js'; import { IBallRouter } from './router'; import { Board } from './board'; import { Renderer } from 'renderer'; import { Part } from 'parts/part'; import { Ball } from 'parts/ball'; import { Colors, Alphas } from 'ui/config'; import { Gearbit, GearBase } from 'parts/gearbit'; import { PartBody, PartBodyFactory } from 'parts/partbody'; import { SPACING } from './constants'; import { Animator } from 'ui/animator'; import { PartType } from 'parts/factory'; export type PartBallContact = { ballPartBody: PartBody, tangent: Vector }; export type ContactMap = Map<PartBody,Set<PartBallContact>>; export class PhysicalBallRouter implements IBallRouter { constructor(public readonly board:Board) { this.engine = Engine.create(); this.balls = this.board.balls; // make walls to catch stray balls this._createWalls(); // capture initial board state this.beforeUpdate(); } public readonly engine:Engine; public balls:Set<Ball>; public onBoardSizeChanged():void { // update the walls around the board this._updateWalls(); // re-render the wireframe this.renderWireframe(); // capture changes to board state this.beforeUpdate(); } public partBodyFactory:PartBodyFactory = new PartBodyFactory(); // UPDATING ***************************************************************** public update(speed:number, correction:number):void { if (! (speed > 0)) return; let iterations:number = speed * 2; if (iterations < 1) { this.engine.timing.timeScale = speed; iterations = 1; } else this.engine.timing.timeScale = 1; for (let i:number = 0; i < iterations; i++) { this.beforeUpdate(); Engine.update(this.engine); this.afterUpdate(); GearBase.update(); } } public beforeUpdate():void { const partsChanged:boolean = this.addNeighborParts(this._boardChangeCounter !== this.board.changeCounter); this._boardChangeCounter = this.board.changeCounter; for (const partBody of this._parts.values()) { partBody.updateBodyFromPart(); } // if parts have been added or removed, update the broadphase grid if ((partsChanged) && (this.engine.broadphase)) { Grid.update(this.engine.broadphase, Composite.allBodies(this.engine.world), this.engine, true); } } private _boardChangeCounter:number = -1; public afterUpdate():void { // determine the set of balls touching each part const contacts:ContactMap = this._mapContacts(); const nearby = this._mapNearby(); // apply physics corrections for (const partBody of this._parts.values()) { partBody.cheat(contacts.get(partBody), nearby.get(partBody)); } // transfer part positions for (const [ part, partBody ] of this._parts.entries()) { partBody.updatePartFromBody(); if (part.bodyCanMove) { this.board.layoutPart(part, part.column, part.row); } } // combine the velocities of connected gear trains this.connectGears(contacts); // re-render the wireframe if there is one this.renderWireframe(); // re-render the whole display if we're managing parts if (this._parts.size > 0) Renderer.needsUpdate(); } // average the angular velocities of all simulated gears with ball contacts, // and transfer it to all simulated gears that are connected protected connectGears(contacts:ContactMap):void { const activeTrains:Set<Set<GearBase>> = new Set(); for (const part of this._parts.keys()) { if (part instanceof GearBase) activeTrains.add(part.connected); } for (const train of activeTrains) { let av:number = 0; let contactCount:number = 0; for (const gear of train) { // select gears which are simulated and have balls in contact const partBody = this._parts.get(gear); if ((partBody) && (partBody.body) && (contacts.has(partBody))) { av += partBody.body.angularVelocity; contactCount++; } } // transfer the average angular velocity to all connected gears if (contactCount > 0) { av /= contactCount; for (const gear of train) { const partBody = this._parts.get(gear); if ((partBody) && (partBody.body)) { Body.setAngularVelocity(partBody.body, av); } } } } } protected _mapContacts():ContactMap { const contacts:ContactMap = new Map(); for (const pair of this.engine.pairs.collisionActive) { const partA = this._findPartBody(pair.bodyA); if (! partA) continue; const partB = this._findPartBody(pair.bodyB); if (! partB) continue; if ((partA.type == PartType.BALL) && (partB.type != PartType.BALL)) { if (! contacts.has(partB)) contacts.set(partB, new Set()); contacts.get(partB).add({ ballPartBody: partA, tangent: pair.collision.tangent }); } else if ((partB.type == PartType.BALL) && (partA.type != PartType.BALL)) { if (! contacts.has(partA)) contacts.set(partA, new Set()); contacts.get(partA).add({ ballPartBody: partB, tangent: pair.collision.tangent }); } } return(contacts); } protected _findPartBody(body:Body):PartBody { if (this._bodies.has(body)) return(this._bodies.get(body)); if ((body.parent) && (body.parent !== body)) { return(this._findPartBody(body.parent)); } return(null); } // map parts to the balls in their grid square protected _mapNearby():Map<PartBody,Set<PartBody>> { const map:Map<PartBody,Set<PartBody>> = new Map; for (const ball of this.balls) { const ballPartBody = this._parts.get(ball); if (! ballPartBody) continue; const part = this.board.getPart( Math.round(ball.column), Math.round(ball.row)); const partBody = this._parts.get(part); if (! partBody) continue; if (! map.has(partBody)) map.set(partBody, new Set()); map.get(partBody).add(ballPartBody); } return(map); } // STATE MANAGEMENT ********************************************************* private _createWalls():void { const options = { isStatic: true }; this._top = Bodies.rectangle(0, 0, this._wallWidth, this._wallThickness, options); this._bottom = Bodies.rectangle(0, 0, this._wallWidth, this._wallThickness, options); this._left = Bodies.rectangle(0, 0, this._wallThickness, this._wallHeight, options); this._right = Bodies.rectangle(0, 0, this._wallThickness, this._wallHeight, options); World.add(this.engine.world, [ this._top, this._right, this._bottom, this._left ]); } private _wallWidth:number = 16; private _wallHeight:number = 16; private _wallThickness:number = 16; private _updateWalls():void { const w:number = ((this.board.columnCount + 3) * SPACING); const h:number = ((this.board.rowCount + 5) * SPACING); const hw:number = (w - this._wallThickness) / 2; const hh:number = (h + this._wallThickness) / 2; const cx:number = ((this.board.columnCount - 1) / 2) * SPACING; const cy:number = ((this.board.rowCount - 1) / 2) * SPACING; Body.setPosition(this._top, { x: cx, y: cy - hh }); Body.setPosition(this._bottom, { x: cx, y: cy + hh }); Body.setPosition(this._left, { x: cx - hw, y: cy }); Body.setPosition(this._right, { x: cx + hw, y: cy }); const sx = w / this._wallWidth; const sy = h / this._wallHeight; if (sx != 1.0) { Body.scale(this._top, sx, 1.0); Body.scale(this._bottom, sx, 1.0); } if (sy != 1.0) { Body.scale(this._left, 1.0, sy); Body.scale(this._right, 1.0, sy); } this._wallWidth = w; this._wallHeight = h; } private _top:Body; private _right:Body; private _bottom:Body; private _left:Body; // update the working set of parts to include those that are near balls, // and return whether parts have been added or removed protected addNeighborParts(force:boolean = false):boolean { // track parts to add and remove const addParts:Set<Part> = new Set(); const removeParts:Set<Part> = new Set(this._parts.keys()); // update for all balls on the board for (const ball of this.balls) { // get the ball's current location const column = Math.round(ball.column); const row = Math.round(ball.row); // remove balls that drop off the board if (Math.round(row) > this.board.rowCount) { this.board.removeBall(ball); continue; } // don't update for balls in the same locality (unless forced to) if ((! force) && (this._ballNeighbors.has(ball)) && (ball.lastColumn === column) && ((ball.lastRow === row) || (ball.lastRow === row + 1))) { removeParts.delete(ball); for (const part of this._ballNeighbors.get(ball)) { removeParts.delete(part); } continue; } // add the ball itself addParts.add(ball); removeParts.delete(ball); // reset the list of neighbors if (! this._ballNeighbors.has(ball)) { this._ballNeighbors.set(ball, new Set()); } const neighbors = this._ballNeighbors.get(ball); neighbors.clear(); // update the neighborhood of parts around the ball for (let c:number = -1; c <= 1; c++) { for (let r:number = -1; r <= 1; r++) { const part = this.board.getPart(column + c, row + r); if (! part) continue; addParts.add(part); removeParts.delete(part); neighbors.add(part); } } // store the last place we updated the ball ball.lastColumn = column; ball.lastRow = row; } // add new parts and remove old ones for (const part of addParts) this.addPart(part); for (const part of removeParts) this.removePart(part); return((addParts.size > 0) || (removeParts.size > 0)); } private _ballNeighbors:Map<Ball,Set<Part>> = new Map(); protected addPart(part:Part):void { if (this._parts.has(part)) return; // make it idempotent const partBody = this.partBodyFactory.make(part); this._parts.set(part, partBody); partBody.updateBodyFromPart(); partBody.addToWorld(this.engine.world); if (partBody.body) this._bodies.set(partBody.body, partBody); } protected removePart(part:Part):void { if (! this._parts.has(part)) return; // make it idempotent const partBody = this._parts.get(part); partBody.removeFromWorld(this.engine.world); this._bodies.delete(partBody.body); this.partBodyFactory.release(partBody); this._parts.delete(part); this._restoreRestingRotation(part); } private _parts:Map<Part,PartBody> = new Map(); private _bodies:Map<Body,PartBody> = new Map(); // restore the rotation of the part if it has one protected _restoreRestingRotation(part:Part):void { if (part.rotation === part.restingRotation) return; // ensure we don't "restore" a gear that's still connected // to a chain that's being simulated if ((part instanceof Gearbit) && (part.connected)) { for (const gear of part.connected) { if ((gear instanceof Gearbit) && (this._parts.has(gear))) return; } } if (this.board.speed > 0) { Animator.current.animate(part, 'rotation', part.rotation, part.restingRotation, 0.1 / this.board.speed); } } // WIREFRAME PREVIEW ******************************************************** public get showWireframe():boolean { return(this._wireframe ? true : false); } public set showWireframe(v:boolean) { if ((v) && (! this._wireframe)) { this._wireframe = new PIXI.Sprite(); this._wireframeGraphics = new PIXI.Graphics(); this._wireframe.addChild(this._wireframeGraphics); this.board._layers.addChild(this._wireframe); this.onBoardSizeChanged(); this.renderWireframe(); } else if ((! v) && (this._wireframe)) { this.board._layers.removeChild(this._wireframe); this._wireframe = null; this._wireframeGraphics = null; Renderer.needsUpdate(); } } private _wireframe:PIXI.Sprite; private _wireframeGraphics:PIXI.Graphics; public renderWireframe():void { if (! this._wireframe) return; // setup const g = this._wireframeGraphics; g.clear(); const scale = this.board.spacing / SPACING; // draw all constraints var constraints = (Composite.allConstraints(this.engine.world) as any) as Constraint[]; for (const constraint of constraints) { this._drawConstraint(g, constraint, scale); } // draw all bodies var bodies = Composite.allBodies(this.engine.world); for (const body of bodies) { this._drawBody(g, body, scale); } Renderer.needsUpdate(); } protected _drawBody(g:PIXI.Graphics, body:Body, scale:number):void { if (body.parts.length > 1) { // if the body has more than one part, the first is the convex hull, which // we draw in a different color to distinguish it this._drawVertices(g, body.vertices, Colors.WIREFRAME_HULL, scale); for (let i:number = 1; i < body.parts.length; i++) { this._drawBody(g, body.parts[i], scale); } } // otherwise this is a terminal part else { this._drawVertices(g, body.vertices, Colors.WIREFRAME, scale); } } protected _drawVertices(g:PIXI.Graphics, vertices:Vector[], color:number, scale:number):void { g.lineStyle(1, color); g.beginFill(color, Alphas.WIREFRAME); // draw the vertices of the body let first:boolean = true; for (const vertex of vertices) { if (first) { g.moveTo(vertex.x * scale, vertex.y * scale); first = false; } else { g.lineTo(vertex.x * scale, vertex.y * scale); } } g.closePath(); g.endFill(); } protected _drawConstraint(g:PIXI.Graphics, c:Constraint, scale:number) { if ((! c.pointA) || (! c.pointB)) return; g.lineStyle(2, Colors.WIREFRAME_CONSTRAINT, 0.5); if (c.bodyA) { g.moveTo((c.bodyA.position.x + c.pointA.x) * scale, (c.bodyA.position.y + c.pointA.y) * scale); } else { g.moveTo(c.pointA.x * scale, c.pointA.y * scale); } if (c.bodyB) { g.lineTo((c.bodyB.position.x + c.pointB.x) * scale, (c.bodyB.position.y + c.pointB.y) * scale); } else { g.lineTo(c.pointB.x * scale, c.pointB.y * scale); } } }
the_stack
import { ModelingType } from '../modeling-type-provider.service'; import { jsonModelType } from './json.model.type'; /* cspell: disable */ export const stringModelType: ModelingType = { id: 'string', properties: jsonModelType.properties, methods: [[ { type: 'string', signature: 'charAt', documentation: 'Returns the char value at the specified index.', parameters: [ { label: 'index', documentation: 'integer' } ] }, { type: 'integer', signature: 'codePointAt', documentation: 'Returns the character (Unicode code point) at the specified index.', parameters: [ { label: 'index', documentation: 'integer' } ] }, { type: 'integer', signature: 'codePointBefore', documentation: 'Returns the character (Unicode code point) before the specified index.' }, { type: 'integer', signature: 'codePointCount', documentation: 'Returns the number of Unicode code points in the specified text range of this String.', parameters: [ { label: 'beginIndex', documentation: 'integer' }, { label: 'endIndex', documentation: 'integer' } ] }, { type: 'integer', signature: 'compareTo', documentation: 'Compares two strings lexicographically.', parameters: [ { label: 'anotherString', documentation: 'string' } ] }, { type: 'integer', signature: 'compareToIgnoreCase', documentation: 'Compares two strings lexicographically, ignoring case differences.', parameters: [ { label: 'str', documentation: 'string' } ] }, { type: 'string', signature: 'concat', documentation: 'Concatenates the specified string to the end of this string.', parameters: [ { label: 'str', documentation: 'string' } ] }, { type: 'boolean', signature: 'contains', documentation: 'Returns true if and only if this string contains the specified sequence of char values.', parameters: [ { label: 's', documentation: 'string' } ] }, { type: 'boolean', signature: 'contentEquals', documentation: 'Compares this string to the specified CharSequence.', parameters: [ { label: 's', documentation: 'string' } ] }, { type: 'boolean', signature: 'endsWith', documentation: 'Tests if this string ends with the specified suffix.', parameters: [ { label: 'suffix', documentation: 'string' } ] }, { type: 'boolean', signature: 'equalsIgnoreCase', documentation: 'Compares this String to another String, ignoring case considerations.', parameters: [ { label: 'anotherString', documentation: 'string' } ] }, { type: 'array', signature: 'getBytes', documentation: 'Encodes this String into a sequence of bytes using the platform\'s default charset, storing the result into a new byte array.' }, { type: 'array', signature: 'getBytes', documentation: 'Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array.', parameters: [ { label: 'charsetName', documentation: 'string' } ] }, { type: 'null', signature: 'getChars', documentation: 'Copies characters from this string into the destination character array.', parameters: [ { label: 'srcBegin', documentation: 'integer' }, { label: 'srcEnd', documentation: 'integer' }, { label: 'dst', documentation: 'string' }, { label: 'dstBegin', documentation: 'integer' } ] }, { type: 'integer', signature: 'hashCode', documentation: 'Returns a hash code for this string.' }, { type: 'integer', signature: 'indexOf', documentation: 'Returns the index within this string of the first occurrence of the specified character.', parameters: [ { label: 'ch', documentation: 'integer' } ] }, { type: 'integer', signature: 'indexOf', documentation: 'Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index.', parameters: [ { label: 'ch', documentation: 'integer' }, { label: 'fromIndex', documentation: 'integer' } ] }, { type: 'integer', signature: 'indexOf', documentation: 'Returns the index within this string of the first occurrence of the specified substring.', parameters: [ { label: 'str', documentation: 'string' } ] }, { type: 'integer', signature: 'indexOf', documentation: 'Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.', parameters: [ { label: 'str', documentation: 'string' }, { label: 'fromIndex', documentation: 'integer' } ] }, { type: 'string', signature: 'intern', documentation: 'Returns a canonical representation for the string object.' }, { type: 'boolean', signature: 'isBlank', documentation: 'Returns true if the string is empty or contains only white space codepoints, otherwise false.' }, { type: 'boolean', signature: 'isEmpty', documentation: 'Returns true if, and only if, length() is 0.' }, { type: 'integer', signature: 'lastIndexOf', documentation: 'Returns the index within this string of the last occurrence of the specified character.', parameters: [ { label: 'ch', documentation: 'integer' } ] }, { type: 'integer', signature: 'lastIndexOf', documentation: 'Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.', parameters: [ { label: 'ch', documentation: 'integer' }, { label: 'fromIndex', documentation: 'integer' } ] }, { type: 'integer', signature: 'lastIndexOf', documentation: 'Returns the index within this string of the last occurrence of the specified substring.', parameters: [ { label: 'str', documentation: 'string' } ] }, { type: 'integer', signature: 'lastIndexOf', documentation: 'Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.', parameters: [ { label: 'str', documentation: 'string' }, { label: 'fromIndex', documentation: 'integer' } ] }, { type: 'integer', signature: 'length', documentation: 'Returns the length of this string.' }, { type: 'boolean', signature: 'matches', documentation: 'Tells whether or not this string matches the given regular expression.', parameters: [ { label: 'regex', documentation: 'string' } ] }, { type: 'integer', signature: 'offsetByCodePoints', documentation: 'Returns the index within this String that is offset from the given index by codePointOffset code points.', parameters: [ { label: 'index', documentation: 'integer' }, { label: 'codePointOffset', documentation: 'integer' } ] }, { type: 'boolean', signature: 'regionMatches', documentation: 'Tests if two string regions are equal.', parameters: [ { label: 'ignoreCase', documentation: 'boolean' }, { label: 'toffset', documentation: 'integer' }, { label: 'other', documentation: 'string' }, { label: 'ooffset', documentation: 'integer' }, { label: 'len', documentation: 'integer' } ] }, { type: 'boolean', signature: 'regionMatches', documentation: 'Tests if two string regions are equal.', parameters: [ { label: 'toffset', documentation: 'integer' }, { label: 'other', documentation: 'string' }, { label: 'ooffset', documentation: 'integer' }, { label: 'len', documentation: 'integer' } ] }, { type: 'string', signature: 'repeat', documentation: 'Returns a string whose value is the concatenation of this string repeated count times.', parameters: [ { label: 'count', documentation: 'integer' } ] }, { type: 'string', signature: 'replace', documentation: 'Returns a string resulting from replacing all occurrences of oldChar in this string with newChar.', parameters: [ { label: 'oldChar', documentation: 'string' }, { label: 'newChar', documentation: 'string' } ] }, { type: 'string', signature: 'replaceAll', documentation: 'Replaces each substring of this string that matches the given regular expression with the given replacement.', parameters: [ { label: 'regex', documentation: 'string' }, { label: 'replacement', documentation: 'string' } ] }, { type: 'string', signature: 'replaceFirst', documentation: 'Replaces the first substring of this string that matches the given regular expression with the given replacement.', parameters: [ { label: 'regex', documentation: 'string' }, { label: 'replacement', documentation: 'string' } ] }, { type: 'string-array', signature: 'split', documentation: 'Splits this string around matches of the given regular expression.', parameters: [ { label: 'regex', documentation: 'string' } ] }, { type: 'string-array', signature: 'split', documentation: 'Splits this string around matches of the given regular expression.', parameters: [ { label: 'regex', documentation: 'string' }, { label: 'limit', documentation: 'integer' } ] }, { type: 'boolean', signature: 'startsWith', documentation: 'Tests if this string starts with the specified prefix.', parameters: [ { label: 'prefix', documentation: 'string' } ] }, { type: 'boolean', signature: 'startsWith', documentation: 'Tests if the substring of this string beginning at the specified index starts with the specified prefix.', parameters: [ { label: 'prefix', documentation: 'string' }, { label: 'offset', documentation: 'integer' } ] }, { type: 'string', signature: 'strip', documentation: 'Returns a string whose value is this string, with all leading and trailing white space removed.' }, { type: 'string', signature: 'stripLeading', documentation: 'Returns a string whose value is this string, with all leading white space removed.' }, { type: 'string', signature: 'stripTrailing', documentation: 'Returns a string whose value is this string, with all trailing white space removed.' }, { type: 'string', signature: 'substring', documentation: 'Returns a string that is a substring of this string.', parameters: [ { label: 'beginIndex', documentation: 'integer' } ] }, { type: 'string', signature: 'substring', documentation: 'Returns a string that is a substring of this string.', parameters: [ { label: 'beginIndex', documentation: 'integer' }, { label: 'endIndex', documentation: 'integer' } ] }, { type: 'array', signature: 'toCharArray', documentation: 'Converts this string to a new character array.' }, { type: 'string', signature: 'toLowerCase', documentation: 'Converts all of the characters in this String to lower case using the rules of the default locale.' }, { type: 'string', signature: 'toUpperCase', documentation: 'Converts all of the characters in this String to upper case using the rules of the default locale.' }, { type: 'string', signature: 'trim', documentation: 'Returns a string whose value is this string, with all leading and trailing space removed, where space is defined as any character whose codepoint is less than or equal to \'U+ 0020\' (the space character).' } ], jsonModelType.methods].flat() };
the_stack