text
stringlengths
2.5k
6.39M
kind
stringclasses
3 values
import {IOas20NodeVisitor} from "../visitors/visitor.iface"; import {Oas20Document} from "../models/2.0/document.model"; import {Oas20Info} from "../models/2.0/info.model"; import {Oas20Contact} from "../models/2.0/contact.model"; import {Oas20License} from "../models/2.0/license.model"; import {Oas20Paths} from "../models/2.0/paths.model"; import {Oas20PathItem} from "../models/2.0/path-item.model"; import {Oas20Operation} from "../models/2.0/operation.model"; import {Oas20Parameter, Oas20ParameterBase, Oas20ParameterDefinition} from "../models/2.0/parameter.model"; import {Oas20ExternalDocumentation} from "../models/2.0/external-documentation.model"; import {Oas20SecurityRequirement} from "../models/2.0/security-requirement.model"; import {Oas20Responses} from "../models/2.0/responses.model"; import {Oas20Response, Oas20ResponseBase, Oas20ResponseDefinition} from "../models/2.0/response.model"; import { Oas20AdditionalPropertiesSchema, Oas20AllOfSchema, Oas20ItemsSchema, Oas20PropertySchema, Oas20Schema, Oas20SchemaDefinition } from "../models/2.0/schema.model"; import {Oas20Headers} from "../models/2.0/headers.model"; import {Oas20Header} from "../models/2.0/header.model"; import {Oas20Example} from "../models/2.0/example.model"; import {Oas20Items} from "../models/2.0/items.model"; import {Oas20Tag} from "../models/2.0/tag.model"; import {Oas20SecurityDefinitions} from "../models/2.0/security-definitions.model"; import {Oas20SecurityScheme} from "../models/2.0/security-scheme.model"; import {Oas20Scopes} from "../models/2.0/scopes.model"; import {Oas20XML} from "../models/2.0/xml.model"; import {Oas20Definitions} from "../models/2.0/definitions.model"; import {Oas20ParametersDefinitions} from "../models/2.0/parameters-definitions.model"; import {Oas20ResponsesDefinitions} from "../models/2.0/responses-definitions.model"; import {OasExtension} from "../models/extension.model"; import {OasNode, OasValidationProblem} from "../models/node.model"; import {Oas30Document} from "../models/3.0/document.model"; import {OasLibraryUtils} from "../library.utils"; import {Oas30Contact} from "../models/3.0/contact.model"; import {OasNodePath} from "../models/node-path"; import {Oas30License} from "../models/3.0/license.model"; import {Oas30Info} from "../models/3.0/info.model"; import {OasExtensibleNode} from "../models/enode.model"; import {Oas30Paths} from "../models/3.0/paths.model"; import {Oas30PathItem} from "../models/3.0/path-item.model"; import {Oas30Operation} from "../models/3.0/operation.model"; import {IOasParameterParent} from "../models/common/parameter.model"; import {Oas30Parameter, Oas30ParameterDefinition} from "../models/3.0/parameter.model"; import { Oas30AdditionalPropertiesSchema, Oas30AllOfSchema, Oas30ItemsSchema, Oas30PropertySchema, Oas30Schema, Oas30SchemaDefinition } from "../models/3.0/schema.model"; import {Oas30Components} from "../models/3.0/components.model"; import {Oas30ExternalDocumentation} from "../models/3.0/external-documentation.model"; import {Oas30SecurityRequirement} from "../models/3.0/security-requirement.model"; import {Oas30Responses} from "../models/3.0/responses.model"; import {Oas30Response, Oas30ResponseBase, Oas30ResponseDefinition} from "../models/3.0/response.model"; import {Oas30Header} from "../models/3.0/header.model"; import {Oas30Tag} from "../models/3.0/tag.model"; import {Oas30SecurityScheme} from "../models/3.0/security-scheme.model"; import {Oas30XML} from "../models/3.0/xml.model"; import {OasTraverserDirection, OasVisitorUtil} from "../visitors/visitor.utils"; import {Oas20NodeVisitorAdapter} from "../visitors/visitor.base"; import {Oas30MediaType} from "../models/3.0/media-type.model"; import {Oas30RequestBody, Oas30RequestBodyDefinition} from "../models/3.0/request-body.model"; import {Oas30Server} from "../models/3.0/server.model"; import {Oas30ServerVariable} from "../models/3.0/server-variable.model"; import {ReferenceUtil} from "../util"; /** * A visitor used to transform an OpenAPI 2.0 document into an OpenAPI 3.0.x document. */ export class Oas20to30TransformationVisitor implements IOas20NodeVisitor { private doc30: Oas30Document; private _library: OasLibraryUtils = new OasLibraryUtils(); private _nodeMap: any = {}; private _postProcessResponses: Oas30ResponseBase[] = []; private _postProcessingComplete: boolean = false; public getResult(): Oas30Document { if (!this._postProcessingComplete) { this.postProcess(); } return this.doc30; } public visitDocument(node: Oas20Document): void { this.doc30 = this._library.createDocument("3.0.2") as Oas30Document; if (node.host) { let basePath: string = node.basePath; if (!basePath) { basePath = ""; } let schemes: string[] = node.schemes; if (!schemes || schemes.length === 0) { schemes = [ "http" ]; } let server30: Oas30Server = this.doc30.createServer(); this.doc30.servers = [ server30 ]; if (schemes.length === 1) { server30.url = `${ schemes[0] }://${ node.host }${ basePath }`; } else { server30.url = `{scheme}://${ node.host }${ basePath }`; let var30: Oas30ServerVariable = server30.createServerVariable("scheme"); server30.addServerVariable("scheme", var30); var30.default = schemes[0]; var30.enum = schemes.slice(0); var30.description = "The supported protocol schemes."; } } this.mapNode(node, this.doc30); } public visitInfo(node: Oas20Info): void { this.doc30.info = this.doc30.createInfo(); this.doc30.info.title = node.title; this.doc30.info.description = node.description; this.doc30.info.termsOfService = node.termsOfService; this.doc30.info.version = node.version; this.mapNode(node, this.doc30.info); } public visitContact(node: Oas20Contact): void { let info30: Oas30Info = this.lookup(node.parent()) as Oas30Info; let contact30: Oas30Contact = info30.createContact(); info30.contact = contact30; contact30.name = node.name; contact30.url = node.url; contact30.email = node.email; this.mapNode(node, contact30); } public visitLicense(node: Oas20License): void { let info30: Oas30Info = this.lookup(node.parent()) as Oas30Info; let license30: Oas30License = info30.createLicense(); info30.license = license30; license30.name = node.name; license30.url = node.url; this.mapNode(node, license30); } public visitPaths(node: Oas20Paths): void { this.doc30.paths = this.doc30.createPaths(); this.mapNode(node, this.doc30.paths); } public visitPathItem(node: Oas20PathItem): void { let paths30: Oas30Paths = this.lookup(node.parent()) as Oas30Paths; let pathItem30: Oas30PathItem = paths30.createPathItem(node.path()); paths30.addPathItem(node.path(), pathItem30); pathItem30.$ref = this.updateRef(node.$ref); this.mapNode(node, pathItem30); } public visitOperation(node: Oas20Operation): void { let pathItem30: Oas30PathItem = this.lookup(node.parent()) as Oas30PathItem; let operation30: Oas30Operation = pathItem30.createOperation(node.method()); pathItem30[node.method()] = operation30; operation30.tags = node.tags; operation30.summary = node.summary; operation30.description = node.description; operation30.operationId = node.operationId; operation30.deprecated = node.deprecated; if (node.schemes && node.schemes.length > 0 && this.doc30.servers && this.doc30.servers.length > 0) { let server30: Oas30Server = operation30.createServer(); operation30.servers = [ server30 ]; server30.url = this.doc30.servers[0].url; if (node.schemes.length === 1) { server30.url = server30.url.replace("{scheme}", node.schemes[0]); server30.removeServerVariable("scheme"); } else { server30.url = "{scheme}" + server30.url.substring(server30.url.indexOf("://")); let var30: Oas30ServerVariable = server30.createServerVariable("scheme"); server30.addServerVariable("scheme", var30); var30.description = "The supported protocol schemes."; var30.default = node.schemes[0]; var30.enum = node.schemes.slice(0); } } // Note: consumes/produces will be handled elsewhere (when Request Body and Response models are created) this.mapNode(node, operation30); } public visitParameter(node: Oas20Parameter): void { if (node.in === "body") { let operation30: Oas30Operation = this.lookup(this.findParentOperation(node)) as Oas30Operation; if (operation30) { let body30: Oas30RequestBody = operation30.createRequestBody(); operation30.requestBody = body30; body30.description = node.description; body30.required = node.required; if (node.schema) { let consumes: string[] = this.findConsumes(node); let schema: Oas20Schema = node.schema as Oas20Schema; consumes.forEach( ct => { let mediaType30: Oas30MediaType = body30.createMediaType(ct); body30.addMediaType(ct, mediaType30); let schema30: Oas30Schema = mediaType30.createSchema(); mediaType30.schema = this.toSchema(schema, schema30, true); this.mapNode(schema, schema30); }); } } } else if (node.in === "formData") { let operation30: Oas30Operation = this.lookup(this.findParentOperation(node)) as Oas30Operation; if (operation30) { let consumes: string[] = this.findConsumes(node); if (!this.hasFormDataMimeType(consumes)) { consumes = ["application/x-www-form-urlencoded"]; } consumes.forEach(ct => { if (this.isFormDataMimeType(ct)) { let body30: Oas30RequestBody = operation30.requestBody; if (!body30) { body30 = operation30.createRequestBody(); operation30.requestBody = body30; body30.required = true; } let mediaType30: Oas30MediaType = body30.getMediaType(ct); if (!mediaType30) { mediaType30 = body30.createMediaType(ct); body30.addMediaType(ct, mediaType30); } let schema30: Oas30Schema = mediaType30.schema; if (!schema30) { schema30 = mediaType30.createSchema(); mediaType30.schema = schema30; schema30.type = "object"; } let property30: Oas30PropertySchema = schema30.createPropertySchema(node.name); schema30.addProperty(node.name, property30); property30.description = node.description; this.toSchema(node, property30, false); this.mapNode(node, schema30); } }); } } else { if (this.isRef(node)) { let paramDef: Oas20ParameterDefinition = ReferenceUtil.resolveRef(node.$ref, node) as Oas20ParameterDefinition; // Handle the case where there is a parameter $ref to a "body" param. All body params become // Request Bodies. So a reference to a "body" param should become a reference to a request body. if (paramDef && paramDef.in === "body") { let parent30: Oas30Operation = this.lookup(this.findParentOperation(node)) as Oas30Operation; if (parent30) { let body30: Oas30RequestBody = parent30.createRequestBody(); parent30.requestBody = body30; body30.$ref = "#/components/requestBodies/" + paramDef.parameterName(); this.mapNode(node, body30); return; } } // Handle the case where the parameter is a $ref to a formData param. In this case we want to // treat the param as though it is inlined (which will result in a requestBody model). if (paramDef && paramDef.in === "formData") { // Inline the parameter definition and then re-visit it. this._library.readNode(this._library.writeNode(paramDef), node); node.$ref = null; this.visitParameter(node); return; } } // Now we have normal handling of a parameter, examples include path params, query params, header params, etc. let parent30: IOasParameterParent = this.lookup(node.parent()) as any; let param30: Oas30Parameter = parent30.createParameter() as Oas30Parameter; parent30.addParameter(param30); this.transformParam(node, param30); this.mapNode(node, param30); } } private transformParam(node: Oas20ParameterBase, param30: Oas30Parameter): Oas30Parameter { param30.$ref = this.updateRef(node["$ref"]); if (param30.$ref) { return param30; } param30.name = node.name; param30.in = node.in; param30.description = node.description; param30.required = node.required; param30.allowEmptyValue = node.allowEmptyValue; param30.schema = this.toSchema(node, param30.createSchema(), false); this.collectionFormatToStyleAndExplode(node, param30); return param30; } public visitParameterDefinition(node: Oas20ParameterDefinition): void { if (node.in === "body") { let parent30: Oas30Components = this.getOrCreateComponents(); let bodyDef30: Oas30RequestBodyDefinition = parent30.createRequestBodyDefinition(node.parameterName()); parent30.addRequestBodyDefinition(node.parameterName(), bodyDef30); bodyDef30.description = node.description; bodyDef30.required = node.required; if (node.schema) { let consumes: string[] = this.findConsumes(node); let schema: Oas20Schema = node.schema as Oas20Schema; consumes.forEach( ct => { let mediaType30: Oas30MediaType = bodyDef30.createMediaType(ct); bodyDef30.addMediaType(ct, mediaType30); let schema30: Oas30Schema = mediaType30.createSchema(); mediaType30.schema = this.toSchema(schema, schema30, true); this.mapNode(schema, schema30); }); } } else if (node.in === "formData") { // Exclude any re-usable formData parameters - they are currently being inlined elsewhere. I'm not sure // what we would do with them anyway. } else { let components30: Oas30Components = this.getOrCreateComponents(); let paramDef30: Oas30ParameterDefinition = components30.createParameterDefinition(node.parameterName()); components30.addParameterDefinition(node.parameterName(), paramDef30); this.transformParam(node, paramDef30); this.mapNode(node, paramDef30); } } public visitExternalDocumentation(node: Oas20ExternalDocumentation): void { let parent30: Oas30Document | Oas30Operation = this.lookup(node.parent()) as any; let externalDocs30: Oas30ExternalDocumentation = parent30.createExternalDocumentation(); parent30.externalDocs = externalDocs30; externalDocs30.description = node.description; externalDocs30.url = node.url; this.mapNode(node, externalDocs30); } public visitSecurityRequirement(node: Oas20SecurityRequirement): void { let parent30: Oas30Document | Oas30Operation = this.lookup(node.parent()) as any; let securityRequirement30: Oas30SecurityRequirement = parent30.createSecurityRequirement(); if (!parent30.security) { parent30.security = []; } parent30.security.push(securityRequirement30); node.securityRequirementNames().forEach( name => { securityRequirement30.addSecurityRequirementItem(name, node.scopes(name)); }); this.mapNode(node, securityRequirement30); } public visitResponses(node: Oas20Responses): void { let parent30: Oas30Operation = this.lookup(node.parent()) as Oas30Operation; let responses30: Oas30Responses = parent30.createResponses(); parent30.responses = responses30; this.mapNode(node, responses30); } public visitResponse(node: Oas20Response): void { let parent30: Oas30Responses = this.lookup(node.parent()) as Oas30Responses; let response30: Oas30Response = parent30.createResponse(node.statusCode()); parent30.addResponse(node.statusCode(), response30); response30.$ref = this.updateRef(node.$ref); this.transformResponse(node, response30); this.mapNode(node, response30); } public visitResponseDefinition(node: Oas20ResponseDefinition): void { let parent30: Oas30Components = this.getOrCreateComponents(); let responseDef30: Oas30ResponseDefinition = parent30.createResponseDefinition(node.name()); parent30.addResponseDefinition(node.name(), responseDef30); this.transformResponse(node, responseDef30); this.mapNode(node, responseDef30); } private transformResponse(node: Oas20ResponseBase, response30: Oas30ResponseBase): void { response30.description = node.description; if (node.schema) { let produces: string[] = this.findProduces(node); let schema: Oas20Schema = node.schema; produces.forEach( ct => { let mediaType30: Oas30MediaType = response30.createMediaType(ct); response30.addMediaType(ct, mediaType30); let schema30: Oas30Schema = mediaType30.createSchema(); mediaType30.schema = this.toSchema(schema, schema30, true); if (node.examples) { let ctexample: any = node.examples.example(ct); if (ctexample) { mediaType30.example = ctexample; } } this.mapNode(schema, schema30); }); // TODO update: mark the Response as needing Content post-processing if (produces.length > 1) { this._postProcessResponses.push(response30); } } } public visitSchema(node: Oas20Schema): void { // In 2.0, Schemas can only be located on responses and parameters. In both cases, we // handle processing and indexing the schema in their respective visit methods - so we // can skip doing that here. } public visitHeaders(node: Oas20Headers): void { let parent30: Oas30ResponseBase = this.lookup(node.parent()) as Oas30ResponseBase; // No processing to do here, because 3.0 doesn't have a "headers" node. So instead // we'll map the headers node to the 3.0 response node, because that will be the // effective parent for any 3.0 Header nodes. this.mapNode(node, parent30); } public visitHeader(node: Oas20Header): void { let parent30: Oas30ResponseBase = this.lookup(node.parent()) as Oas30ResponseBase; let header30: Oas30Header = parent30.createHeader(node.headerName()); parent30.addHeader(node.headerName(), header30); header30.description = node.description; header30.schema = this.toSchema(node, header30.createSchema(), false); this.mapNode(node, header30); } public visitExample(node: Oas20Example): void { // Examples are processed as part of "transformResponse" } public visitItems(node: Oas20Items): void { let parent30: Oas30Schema = this.findItemsParent(node); let items30: Oas30ItemsSchema = parent30.createItemsSchema(); parent30.items = items30; this.toSchema(node, items30, false); this.mapNode(node, items30); } public visitTag(node: Oas20Tag): void { let parent30: Oas30Document = this.doc30; if (!parent30.tags) { parent30.tags = []; } let tag30: Oas30Tag = parent30.createTag(); tag30.name = node.name; tag30.description = node.description; parent30.tags.push(tag30); this.mapNode(node, tag30); } public visitSecurityDefinitions(node: Oas20SecurityDefinitions): void { // OpenAPI has no "Security Definitions" wrapper entity. } public visitSecurityScheme(node: Oas20SecurityScheme): void { let parent30: Oas30Components = this.getOrCreateComponents(); let scheme30: Oas30SecurityScheme = parent30.createSecurityScheme(node.schemeName()); parent30.addSecurityScheme(node.schemeName(), scheme30); scheme30.type = node.type; scheme30.description = node.description; scheme30.name = node.name; scheme30.in = node.in; if (node.type === "oauth2") { if (node.flow === "implicit") { scheme30.flows = scheme30.createOAuthFlows(); scheme30.flows.implicit = scheme30.flows.createImplicitOAuthFlow(); scheme30.flows.implicit.authorizationUrl = node.authorizationUrl; if (node.scopes) { node.scopes.scopes().forEach( scopeName => { scheme30.flows.implicit.addScope(scopeName, node.scopes.getScopeDescription(scopeName)); }) } } if (node.flow === "accessCode") { scheme30.flows = scheme30.createOAuthFlows(); scheme30.flows.authorizationCode = scheme30.flows.createAuthorizationCodeOAuthFlow(); scheme30.flows.authorizationCode.authorizationUrl = node.authorizationUrl; scheme30.flows.authorizationCode.tokenUrl = node.tokenUrl; if (node.scopes) { node.scopes.scopes().forEach( scopeName => { scheme30.flows.authorizationCode.addScope(scopeName, node.scopes.getScopeDescription(scopeName)); }) } } if (node.flow === "password") { scheme30.flows = scheme30.createOAuthFlows(); scheme30.flows.password = scheme30.flows.createPasswordOAuthFlow(); scheme30.flows.password.tokenUrl = node.tokenUrl; if (node.scopes) { node.scopes.scopes().forEach( scopeName => { scheme30.flows.password.addScope(scopeName, node.scopes.getScopeDescription(scopeName)); }) } } if (node.flow === "application") { scheme30.flows = scheme30.createOAuthFlows(); scheme30.flows.clientCredentials = scheme30.flows.createClientCredentialsOAuthFlow(); scheme30.flows.clientCredentials.tokenUrl = node.tokenUrl; if (node.scopes) { node.scopes.scopes().forEach( scopeName => { scheme30.flows.clientCredentials.addScope(scopeName, node.scopes.getScopeDescription(scopeName)); }) } } } this.mapNode(node, scheme30); } public visitScopes(node: Oas20Scopes): void { // Note: scopes are handled during the processing of the security scheme. See `visitSecurityScheme` for details. } public visitXML(node: Oas20XML): void { let parent30: Oas30Schema = this.lookup(node.parent()) as Oas30Schema; let xml30: Oas30XML = parent30.createXML(); parent30.xml = xml30; xml30.name = node.name; xml30.namespace = node.namespace; xml30.prefix = node.prefix; xml30.attribute = node.attribute; xml30.wrapped = node.wrapped; this.mapNode(node, xml30); } public visitSchemaDefinition(node: Oas20SchemaDefinition): void { let parent30: Oas30Components = this.getOrCreateComponents(); let schemaDef30: Oas30SchemaDefinition = parent30.createSchemaDefinition(node.definitionName()); parent30.addSchemaDefinition(node.definitionName(), schemaDef30); this.toSchema(node, schemaDef30, true); this.mapNode(node, schemaDef30); } public visitPropertySchema(node: Oas20PropertySchema): void { let parent30: Oas30Schema = this.lookup(node.parent()) as Oas30Schema; let property30: Oas30PropertySchema = parent30.createPropertySchema(node.propertyName()); parent30.addProperty(node.propertyName(), property30); this.toSchema(node, property30, true); this.mapNode(node, property30); } public visitAdditionalPropertiesSchema(node: Oas20AdditionalPropertiesSchema): void { let parent30: Oas30Schema = this.lookup(node.parent()) as Oas30Schema; let additionalProps30: Oas30AdditionalPropertiesSchema = parent30.createAdditionalPropertiesSchema(); parent30.additionalProperties = additionalProps30; this.toSchema(node, additionalProps30, true); this.mapNode(node, additionalProps30); } public visitAllOfSchema(node: Oas20AllOfSchema): void { let parent30: Oas30Schema = this.lookup(node.parent()) as Oas30Schema; let allOf30: Oas30AllOfSchema = parent30.createAllOfSchema(); if (!parent30.allOf) { parent30.allOf = []; } parent30.allOf.push(allOf30); this.toSchema(node, allOf30, true); this.mapNode(node, allOf30); } public visitItemsSchema(node: Oas20ItemsSchema): void { let parent30: Oas30Schema = this.lookup(node.parent()) as Oas30Schema; let items30: Oas30ItemsSchema = parent30.createItemsSchema(); if (parent30.items && typeof parent30.items === "object") { parent30.items = [ parent30.items as Oas30Schema ]; parent30.items.push(items30); } else { parent30.items = items30; } this.toSchema(node, items30, true); this.mapNode(node, items30); } public visitDefinitions(node: Oas20Definitions): void { // Note: there is no "definitions" entity in 3.0, so nothing to do here. } public visitParametersDefinitions(node: Oas20ParametersDefinitions): void { // Note: there is no "parameters definitions" entity in 3.0, so nothing to do here. } public visitResponsesDefinitions(node: Oas20ResponsesDefinitions): void { // Note: there is no "responses definitions" entity in 3.0, so nothing to do here. } public visitExtension(node: OasExtension): void { let parent30: OasExtensibleNode = this.lookup(node.parent()) as OasExtensibleNode; parent30.addExtension(node.name, node.value); } public visitValidationProblem(node: OasValidationProblem): void { // Note: nothing to do for a validation problem } private mapNode(from: OasNode, to: OasNode): void { let nodePath: OasNodePath = this._library.createNodePath(from); let mapIndex: string = nodePath.toString(); this._nodeMap[mapIndex] = to; } private lookup(node: OasNode): OasNode { let nodePath: OasNodePath = this._library.createNodePath(node); let mapIndex: string = nodePath.toString(); return this._nodeMap[mapIndex] as OasNode; } private getOrCreateComponents(): Oas30Components { if (!this.doc30.components) { this.doc30.components = this.doc30.createComponents(); } return this.doc30.components; } private toSchema(from: Oas20ParameterBase | Oas20Header | Oas20Items | Oas20Schema | Oas20SchemaDefinition, schema30: Oas30Schema, isSchema: boolean): Oas30Schema { schema30.type = from.type; schema30.format = from.format; if (from.type === "file") { schema30.type = "string"; schema30.format = "binary"; } if (from.items && !Array.isArray(from.items)) { // This is done so that we can lookup the appropriate parent for an "Items" object later // on in the visit. This is a special case because we're introducing a new Oas30Schema // entity in between e.g. a Response and the ItemsSchema - whereas in 2.0 the ItemsSchema // is a direct child of Response and Parameter. So when visiting a Items, we cannot lookup // the new 3.0 Schema using the Items' parent (because the parent maps to something else - // the grandparent, in fact). THIS IS ONLY A PROBLEM FOR "ITEMS" ON PARAM AND RESPONSE. (from.items as OasNode).n_attribute("_transformation_items-parent", schema30); } else if (from.items && Array.isArray(from.items)) { // TODO handle the case where "items" is an array of items!! } // Note: Not sure what to do with the "collectionFormat" of a schema. Dropping it for now. //schema30.collectionFormat = from.collectionFormat; schema30.default = from.default; schema30.maximum = from.maximum; schema30.exclusiveMaximum = from.exclusiveMaximum; schema30.minimum = from.minimum; schema30.exclusiveMinimum = from.exclusiveMinimum; schema30.maxLength = from.maxLength; schema30.minLength = from.minLength; schema30.pattern = from.pattern; schema30.maxItems = from.maxItems; schema30.minItems = from.minItems; schema30.uniqueItems = from.uniqueItems; schema30.enum = from.enum; schema30.multipleOf = from.multipleOf; if (isSchema) { let schema20: Oas20Schema = from as Oas20Schema; schema30.$ref = this.updateRef(schema20.$ref); if (typeof schema20.additionalProperties === "boolean") { schema30.additionalProperties = schema20.additionalProperties as boolean; } schema30.readOnly = schema20.readOnly; schema30.example = schema20.example; schema30.title = schema20.title; schema30.description = schema20.description; schema30.maxProperties = schema20.maxProperties; schema30.minProperties = schema20.minProperties; schema30.required = schema20.required; if (schema20.discriminator) { schema30.discriminator = schema30.createDiscriminator(); schema30.discriminator.propertyName = schema20.discriminator; } } return schema30; } private findItemsParent(node: Oas20Items): Oas30Schema { let itemsParent: Oas30Schema = node.n_attribute("_transformation_items-parent"); if (!itemsParent) { itemsParent = this.lookup(node.parent()) as Oas30Schema; } return itemsParent; } private findParentOperation(node: Oas20Parameter): Oas20Operation { let visitor: ParentOperationFinderVisitor = new ParentOperationFinderVisitor(); OasVisitorUtil.visitTree(node, visitor, OasTraverserDirection.up); return visitor.operation; } private findProduces(node: OasNode): string[] { let visitor: ProducesFinderVisitor = new ProducesFinderVisitor(); OasVisitorUtil.visitTree(node, visitor, OasTraverserDirection.up); return visitor.produces; } private findConsumes(node: OasNode): string[] { let visitor: ConsumesFinderVisitor = new ConsumesFinderVisitor(); OasVisitorUtil.visitTree(node, visitor, OasTraverserDirection.up); return visitor.consumes; } private collectionFormatToStyleAndExplode(node: Oas20ParameterBase, param30: Oas30Parameter): void { if (node.type === "array" && node.collectionFormat === "multi" && (node.in === "query" || node.in === "cookie")) { param30.style = "form"; param30.explode = true; return; } if (node.type === "array" && node.collectionFormat === "csv" && (node.in === "query" || node.in === "cookie")) { param30.style = "form"; param30.explode = false; return; } if (node.type === "array" && node.collectionFormat === "csv" && (node.in === "path" || node.in === "header")) { param30.style = "simple"; return; } if (node.type === "array" && node.collectionFormat === "ssv" && node.in === "query") { param30.style = "spaceDelimited"; return; } if (node.type === "array" && node.collectionFormat === "pipes" && node.in === "query") { param30.style = "pipeDelimited"; return; } } private isFormDataMimeType(mimetype: string): boolean { return mimetype && (mimetype === "multipart/form-data" || mimetype === "application/x-www-form-urlencoded"); } private hasFormDataMimeType(mimetypes: string[]): boolean { if (mimetypes) { for (let mt of mimetypes) { if (this.isFormDataMimeType(mt)) { return true; } } } return false; } private isRef(node: Oas20Schema | Oas20Response | Oas20Parameter): boolean { return node.$ref && node.$ref.length > 0; } private updateRef($ref: string): string { if (!$ref || $ref.length === 0) { return $ref; } let split: string[] = $ref.split("/"); if (split[0] === "#") { if (split[1] === "definitions") { split.splice(1, 1, "components", "schemas"); } else if (split[1] === "parameters") { split.splice(1, 1, "components", "parameters"); } else if (split[1] === "responses") { split.splice(1, 1, "components", "responses"); } } return split.join("/"); } /** * Called when visiting is complete. Any additional processing of the result can * be done here. */ private postProcess(): void { // Post process all of the responses that require it. Responses may require post-processing // when a response has multiple @Produces content types, which results in multiple MimeType // entities in the 3.0 Response 'content'. When this happens, only one of the mime types // will contain the visited (and thus transformed) data model. So we must post-process them // to "clone" that info to the other mime types. Otherwise we'll have a full mime type // definition for only ONE of the mime types, and partial definitions for the rest. this._postProcessResponses.forEach( response => { // First, figure out which of the media types is the largest (has the most content) let largest: number = 0; let srcMt: Oas30MediaType = null; response.getMediaTypes().forEach( mt => { let size: number = JSON.stringify(this._library.writeNode(mt.schema)).length; if (size > largest) { largest = size; srcMt = mt; } }); // Now clone the contents of the largest media type into all the others. response.getMediaTypes().forEach( mt => { if (srcMt !== mt) { console.info("Cloning Media Type " + srcMt.name() + " into " + mt.name()); let src: any = this._library.writeNode(srcMt.schema); this._library.readNode(src, mt.schema); } }); }); } } export class ProducesFinderVisitor extends Oas20NodeVisitorAdapter { public produces: string[] = [ "*/*" ]; public visitDocument(node: Oas20Document) { if (node.produces && node.produces.length > 0) { this.produces = node.produces; } } public visitOperation(node: Oas20Operation): void { if (node.produces && node.produces.length > 0) { this.produces = node.produces; } } } export class ConsumesFinderVisitor extends Oas20NodeVisitorAdapter { public consumes: string[] = [ "*/*" ]; public visitDocument(node: Oas20Document) { if (node.consumes && node.consumes.length > 0) { this.consumes = node.consumes; } } public visitOperation(node: Oas20Operation): void { if (node.consumes && node.consumes.length > 0) { this.consumes = node.consumes; } } } export class ParentOperationFinderVisitor extends Oas20NodeVisitorAdapter { public operation: Oas20Operation = null; public visitOperation(node: Oas20Operation): void { this.operation = node; } }
the_stack
import * as assert from 'assert' import * as fs from 'fs-extra' import * as os from 'os' import * as path from 'path' import * as vscode from 'vscode' import { generateJavaLambdaHandler, getLambdaHandlerComponents, isValidClassSymbol, isValidLambdaHandler, JavaLambdaHandlerComponents, } from '../../../shared/codelens/javaCodeLensProvider' import { makeTemporaryToolkitFolder } from '../../../shared/filesystemUtilities' import * as SampleJavaSamProgram from './sampleJavaSamProgram' const fakeRange = new vscode.Range(0, 0, 0, 0) describe('javaCodeLensProvider', () => { describe('getLambdaHandlerComponents', () => { let tempFolder: string beforeEach(async () => { // Make a temp folder for all these tests tempFolder = await makeTemporaryToolkitFolder() }) afterEach(async () => { await fs.remove(tempFolder) }) it('Detects a public function symbol', async function () { const programFile = path.join(tempFolder, 'App.java') await fs.writeFile(programFile, SampleJavaSamProgram.getFunctionText()) const textDoc = await vscode.workspace.openTextDocument(programFile) const documentSymbols = SampleJavaSamProgram.getDocumentSymbols() const componentsArray = getLambdaHandlerComponents(textDoc, documentSymbols) assert.ok(componentsArray) assert.strictEqual(componentsArray.length, 1, 'Expected only one set of Lambda Handler components') const components = componentsArray[0] assert.strictEqual(components.package, 'helloworld', 'Unexpected Lambda Handler Package') assert.strictEqual(components.class, 'App', 'Unexpected Lambda Handler Class') assert.strictEqual(components.method, 'handleRequest', 'Unexpected Lambda Handler Function') }) }) describe('isValidClassSymbol', () => { const sampleClassSymbol: vscode.DocumentSymbol = new vscode.DocumentSymbol( 'HelloWorld.Function', '', vscode.SymbolKind.Class, fakeRange, fakeRange ) it('returns true for a public class', async function () { const doc = { getText: (range?: vscode.Range): string => { return 'public class Function {}' }, } assert.strictEqual(isValidClassSymbol(doc, sampleClassSymbol), true, 'Expected symbol to be a public class') }) it('returns false when symbol is not of type Class', async function () { const symbol = new vscode.DocumentSymbol( sampleClassSymbol.name, sampleClassSymbol.detail, vscode.SymbolKind.Method, sampleClassSymbol.range, sampleClassSymbol.selectionRange ) const doc = { getText: (range?: vscode.Range): string => { return 'public method Function {}' }, } assert.strictEqual(isValidClassSymbol(doc, symbol), false, 'Expected symbol not to be a public class') }) it('returns false when class is not public', async function () { const doc = { getText: (range?: vscode.Range): string => 'private class Function {}', } assert.strictEqual( isValidClassSymbol(doc, sampleClassSymbol), false, 'Expected symbol not to be a public class' ) }) it('returns false when class is abstract', async function () { const doc = { getText: (range?: vscode.Range): string => 'public abstract class Function {}', } assert.strictEqual( isValidClassSymbol(doc, sampleClassSymbol), false, 'Expected symbol not to be a public class' ) }) }) describe('isValidMethodSignature/isValidLambdaHandler', () => { const validPublicMethodTests = [ { scenario: 'signature all on one line', functionHandlerParams: { name: 'FunctionHandler', args: [ { name: 'param1', type: 'String' }, { name: 'ctx', type: 'Context' }, ], }, functionSignatureParams: { access: 'public' }, }, { scenario: 'signature across many lines', functionHandlerParams: { name: 'FunctionHandler', args: [ { name: 'param1', type: 'String' }, { name: 'ctx', type: 'Context' }, ], beforeArg: true, }, functionSignatureParams: { access: 'public', beforeFunctionName: true, afterSignature: true }, }, { scenario: 'method name on another line', functionHandlerParams: { name: 'FunctionHandler', args: [ { name: 'param1', type: 'String' }, { name: 'ctx', type: 'Context' }, ], beforeArg: true, }, functionSignatureParams: { access: 'public', beforeFunctionName: true }, }, { scenario: 'args on many lines', functionHandlerParams: { name: 'FunctionHandler', args: [ { name: 'param1', type: 'String' }, { name: 'ctx', type: 'Context' }, ], beforeArg: true, }, functionSignatureParams: { access: 'public' }, }, { scenario: 'first arg is generic', functionHandlerParams: { name: 'FunctionHandler', args: [ { name: 'param1', type: 'Foo<Asdf, Jkl>' }, { name: 'ctx', type: 'Context' }, ], beforeArg: true, }, functionSignatureParams: { access: 'public' }, }, { scenario: 'only one arg is present', functionHandlerParams: { name: 'FunctionHandler', args: [{ name: 'param1', type: 'String' }], beforeArg: true, }, functionSignatureParams: { access: 'public' }, }, { scenario: 'an input and output stream are present with no context', functionHandlerParams: { name: 'FunctionHandler', args: [ { name: 'param1', type: 'InputStream' }, { name: 'param2', type: 'OutputStream' }, ], beforeArg: true, }, functionSignatureParams: { access: 'public' }, }, { scenario: 'three params are present', functionHandlerParams: { name: 'FunctionHandler', args: [ { name: 'param1', type: 'InputStream' }, { name: 'param2', type: 'OutputStream' }, { name: 'ctx', type: 'Context' }, ], beforeArg: true, }, functionSignatureParams: { access: 'public' }, }, ] validPublicMethodTests.forEach(test => { const sampleMethodSymbol: vscode.DocumentSymbol = new vscode.DocumentSymbol( 'FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context)', '', vscode.SymbolKind.Method, fakeRange, fakeRange ) it(`returns true for a public method symbol when ${test.scenario}`, async function () { const doc = { getText: (range?: vscode.Range): string => generateFunctionDeclaration( generateFunctionSignature( generateFunctionHandler( test.functionHandlerParams.name, test.functionHandlerParams.args, test.functionHandlerParams.beforeArg ), test.functionSignatureParams ) ), } const isValid = isValidLambdaHandler(doc, sampleMethodSymbol) assert.strictEqual(isValid, true, 'Expected symbol to be a valid method') }) }) it('returns false for a symbol that is not a method', async function () { const symbol = new vscode.DocumentSymbol( 'FunctionHandler(APIGatewayProxyRequest apigProxyEvent, ILambdaContext context)', '', vscode.SymbolKind.Class, fakeRange, fakeRange ) const doc = { getText: (range?: vscode.Range): string => { throw new Error('getText is unused') }, } const isValid = isValidLambdaHandler(doc, symbol) assert.strictEqual(isValid, false, 'Expected symbol not to be a public method') }) it('returns false when the method is not public', async function () { const handler = generateFunctionHandler('FunctionHandler', [ { name: 'param1', type: 'String' }, { name: 'ctx', type: 'Context' }, ]) const symbol = new vscode.DocumentSymbol(handler, '', vscode.SymbolKind.Method, fakeRange, fakeRange) const doc = { getText: (range?: vscode.Range): string => generateFunctionDeclaration(generateFunctionSignature(handler, { access: 'private' })), } const isValid = isValidLambdaHandler(doc, symbol) assert.strictEqual(isValid, false, 'Expected symbol not to be a public method') }) it('returns false when a private method name contains the word public in it', async function () { const symbol = new vscode.DocumentSymbol( 'notpublicmethod', '', vscode.SymbolKind.Method, fakeRange, fakeRange ) const doc = { getText: (range?: vscode.Range): string => generateFunctionDeclaration( generateFunctionSignature( generateFunctionHandler('FunctionHandler', [ { name: 'param1', type: 'String' }, { name: 'ctx', type: 'Context' }, ]), { access: 'private' } ) ), } const isValid = isValidLambdaHandler(doc, symbol) assert.strictEqual(isValid, false, 'Expected symbol not to be a public method') }) it('returns false when the second parameter is not a Context AND the params are not input and output streams', async function () { failedHandlerRunner( generateFunctionHandler('FunctionHandler', [ { name: 'param1', type: 'String' }, { name: 'ctx', type: 'int' }, ]) ) }) it('returns false when one param is a stream and the other is not', async function () { const testHandlers = [ generateFunctionHandler('FunctionHandler', [ { name: 'param1', type: 'int' }, { name: 'param2', type: 'OutputStream' }, ]), generateFunctionHandler('FunctionHandler', [ { name: 'param1', type: 'InputStream' }, { name: 'param2', type: 'int' }, ]), ] for (const test of testHandlers) { failedHandlerRunner(test) } }) it('returns false when any combination of three parameters is not two streams and a context', async function () { const testHandlers = [ generateFunctionHandler('FunctionHandler', [ { name: 'param1', type: 'InputStream' }, { name: 'param2', type: 'OutputStream' }, { name: 'ctx', type: 'int' }, ]), generateFunctionHandler('FunctionHandler', [ { name: 'param1', type: 'int' }, { name: 'param2', type: 'OutputStream' }, { name: 'ctx', type: 'Context' }, ]), generateFunctionHandler('FunctionHandler', [ { name: 'param1', type: 'InputStream' }, { name: 'param2', type: 'int' }, { name: 'ctx', type: 'Context' }, ]), ] for (const test of testHandlers) { failedHandlerRunner(test) } }) it('returns false with more than three parameters', async function () { failedHandlerRunner( generateFunctionHandler('FunctionHandler', [ { name: 'param1', type: 'InputStream' }, { name: 'param2', type: 'OutputStream' }, { name: 'ctx', type: 'Context' }, { name: 'silly', type: 'Whatever' }, ]) ) }) it('returns false with zero parameters', async function () { failedHandlerRunner(generateFunctionHandler('FunctionHandler', [])) }) }) describe('generateJavaLambdaHandler', () => { it('produces a handler name', async function () { const components: JavaLambdaHandlerComponents = { package: 'package', class: 'myClass', method: 'foo', handlerRange: undefined!, } const handlerName = generateJavaLambdaHandler(components) assert.strictEqual(handlerName, 'package.myClass::foo', 'Handler name mismatch') }) }) function failedHandlerRunner(handler: string) { const symbol: vscode.DocumentSymbol = new vscode.DocumentSymbol( handler, '', vscode.SymbolKind.Method, fakeRange, fakeRange ) const doc = { getText: (range?: vscode.Range): string => generateFunctionDeclaration(generateFunctionSignature(handler, { access: 'public' })), } const isValid = isValidLambdaHandler(doc, symbol) assert.strictEqual(isValid, false) } function generateFunctionDeclaration(functionSignature: string): string { return `${functionSignature} { Map<String, String> headers = new HashMap<>(); headers.put("Content-Type", "application/json"); headers.put("X-Custom-Header", "application/json"); APIGatewayProxyResponseEvent response = new APIGatewayProxyResponseEvent() .withHeaders(headers); try { final String pageContents = this.getPageContents("https://checkip.amazonaws.com"); String output = String.format("{ \"message\": \"hello world\", \"location\": \"%s\" }", pageContents); return response .withStatusCode(200) .withBody(output); } catch (IOException e) { return response .withBody("{}") .withStatusCode(500); } } ` } /** * Simulates the Function signature portion of the contents of a TextDocument that corresponds * to a Method Symbol's range. Used with generateFunctionDeclaration. */ function generateFunctionSignature( functionHandler: string, params: { access: string beforeFunctionName?: boolean afterSignature?: boolean } ): string { const beforeFunctionText = params.beforeFunctionName ? os.EOL : '' const afterSignatureText = params.afterSignature ? os.EOL : '' return `${params.access} APIGatewayProxyResponseEvent ${beforeFunctionText}${functionHandler}${afterSignatureText}` } function generateFunctionHandler( functionName: string, params: { type: string name: string }[], beforeArgument: boolean = false ): string { const beforeArgumentText = beforeArgument ? os.EOL : '' const paramsString = params.map(curr => `${beforeArgumentText}${curr.type} ${curr.name}`).join(', ') return `${functionName}(${paramsString})` } })
the_stack
import * as PropTypes from 'prop-types'; import * as React from 'react'; import * as ReactDOM from 'react-dom'; import GestureViewCommon, { GestureStatePoint, GestureStatePointVelocity, GestureType, TouchEventBasic, TouchListBasic } from '../common/GestureView'; import { Types } from '../common/Interfaces'; import AccessibilityUtil from './AccessibilityUtil'; import { clone } from './utils/lodashMini'; import MouseResponder, { MouseResponderSubscription } from './utils/MouseResponder'; import Styles from './Styles'; // Cast to any to allow merging of web and RX styles const _styles = { defaultView: { position: 'relative', display: 'flex', flexDirection: 'column', flexGrow: 0, flexShrink: 0, overflow: 'hidden', alignItems: 'stretch', justifyContent: 'center', } as any, }; // Unique to web const _preferredPanRatio = 3; export interface GestureViewContext { isInRxMainView?: boolean; } let _idCounter = 1; interface Point2D { x: number; y: number; } export abstract class GestureView extends GestureViewCommon { private _id = _idCounter++; private _isMounted = false; private _container: HTMLElement | null | undefined; private _initialTouch: Point2D | undefined; private _ongoingGesture: GestureStatePointVelocity | undefined; private _responder: MouseResponderSubscription | undefined; private _pendingMouseGestureType = GestureType.None; private _gestureTypeLocked = false; static contextTypes: React.ValidationMap<any> = { isInRxMainView: PropTypes.bool, }; // Get preferred pan ratio for platform. protected _getPreferredPanRatio(): number { return _preferredPanRatio; } // Returns the timestamp for the touch event in milliseconds. protected _getEventTimestamp(e: Types.TouchEvent | Types.MouseEvent): number { return e.timeStamp; } componentDidMount() { this._isMounted = true; } componentWillUnmount() { super.componentWillUnmount(); this._isMounted = false; } render() { const ariaRole = AccessibilityUtil.accessibilityTraitToString(this.props.accessibilityTraits); const isAriaHidden = AccessibilityUtil.isHidden(this.props.importantForAccessibility); return ( <div style={ this._getStyles() } tabIndex={ this.props.tabIndex } ref={ this._setContainerRef } onMouseDown={ this._onMouseDown } onClick={ this._onClick } onWheel={ this._onWheel } onTouchStart={ this._onTouchStart } onTouchMove={ this._onTouchMove } onTouchEnd={ this._onTouchEnd } onFocus={ this.props.onFocus } onBlur={ this.props.onBlur } onKeyPress={ this.props.onKeyPress } role={ ariaRole } aria-label={ this.props.accessibilityLabel } aria-hidden={ isAriaHidden } onDoubleClick={ this.props.onDoubleClick ? this._sendDoubleClickEvent : undefined } onContextMenu={ this.props.onContextMenu ? this._sendContextMenuEvent : undefined } data-test-id={ this.props.testId } > { this.props.children } </div> ); } blur() { const el = this._getContainer(); if (el) { el.blur(); } } focus() { const el = this._getContainer(); if (el) { el.focus(); } } protected _getContainer(): HTMLElement | null { if (!this._isMounted) { return null; } try { return ReactDOM.findDOMNode(this) as HTMLElement | null; } catch { // Handle exception due to potential unmount race condition. return null; } } private _createMouseResponder(container: HTMLElement) { this._disposeMouseResponder(); this._responder = MouseResponder.create({ id: this._id, target: container, disableWhenModal: !!this.context.isInRxMainView, shouldBecomeFirstResponder: (event: MouseEvent) => { if (!this.props.onPan && !this.props.onPanHorizontal && !this.props.onPanVertical) { return false; } const boundingRect = this._getGestureViewClientRect(); if (!boundingRect) { return false; } const { top, left, bottom, right } = boundingRect; const { clientX, clientY } = event; if (clientX >= left && clientX <= right && clientY >= top && clientY <= bottom) { return true; } return false; }, onMove: (event: MouseEvent, gestureState: Types.PanGestureState) => { this._pendingMouseGestureType = this._detectGestureType(gestureState); if (this._pendingMouseGestureType !== GestureType.None) { this._cancelLongPressTimer(); } this._sendMousePanEvent(gestureState); }, onTerminate: (event: MouseEvent, gestureState: Types.PanGestureState) => { this._cancelLongPressTimer(); this._pendingMouseGestureType = this._detectGestureType(gestureState); this._sendMousePanEvent(gestureState); this._pendingMouseGestureType = GestureType.None; this._gestureTypeLocked = false; }, }); } private _disposeMouseResponder() { if (this._responder) { this._responder.dispose(); delete this._responder; } } private _setContainerRef = (container: HTMLElement | null) => { // safe since div refs resolve into HTMLElement and not react element. this._container = container; if (container) { this._createMouseResponder(container); } else { this._disposeMouseResponder(); } }; private _getStyles(): any { const combinedStyles = Styles.combine([_styles.defaultView, this.props.style]); let cursorName: string | undefined; switch (this.props.mouseOverCursor) { case Types.GestureMouseCursor.Grab: cursorName = 'grab'; break; case Types.GestureMouseCursor.Move: cursorName = 'move'; break; case Types.GestureMouseCursor.Pointer: cursorName = 'pointer'; break; case Types.GestureMouseCursor.NSResize: cursorName = 'ns-resize'; break; case Types.GestureMouseCursor.EWResize: cursorName = 'ew-resize'; break; case Types.GestureMouseCursor.NESWResize: cursorName = 'nesw-resize'; break; case Types.GestureMouseCursor.NWSEResize: cursorName = 'nwse-resize'; break; case Types.GestureMouseCursor.NotAllowed: cursorName = 'not-allowed'; break; case Types.GestureMouseCursor.ZoomIn: cursorName = 'zoom-in'; break; case Types.GestureMouseCursor.ZoomOut: cursorName = 'zoom-out'; break; } if (cursorName) { combinedStyles.cursor = cursorName; } return combinedStyles; } private _onMouseDown = (e: React.MouseEvent<any>) => { if (this.props.onPan || this.props.onPanHorizontal || this.props.onPanVertical) { // Disable mousedown default action that initiates a drag/drop operation and breaks panning with a not-allowed cursor. // https://w3c.github.io/uievents/#mousedown e.preventDefault(); } if (this.props.onLongPress) { const gsState = this._mouseEventToTapGestureState(e); this._startLongPressTimer(gsState, true); } }; private _onClick = (e: React.MouseEvent<any>) => { this._cancelLongPressTimer(); const gsState = this._mouseEventToTapGestureState(e); if (!this.props.onDoubleTap) { // If there is no double-tap handler, we can invoke the tap handler immediately. this._sendTapEvent(gsState); } else if (this._isDoubleTap(gsState)) { // This is a double-tap, so swallow the previous single tap. this._cancelDoubleTapTimer(); this._sendDoubleTapEvent(gsState); } else { // This wasn't a double-tap. Report any previous single tap and start the double-tap // timer so we can determine whether the current tap is a single or double. this._reportDelayedTap(); this._startDoubleTapTimer(gsState); } }; private _sendDoubleClickEvent = (e: React.MouseEvent<any>) => { if (this.props.onDoubleClick) { e.preventDefault(); e.stopPropagation(); const tapEvent = this._mouseEventToTapGestureState(e); this.props.onDoubleClick(tapEvent); } }; private _sendContextMenuEvent = (e: React.MouseEvent<any>) => { if (this.props.onContextMenu) { e.preventDefault(); e.stopPropagation(); const tapEvent = this._mouseEventToTapGestureState(e); this.props.onContextMenu(tapEvent); } }; // The RN and React touch event types are basically identical except that React uses "clientX/Y" // and RN uses "locationX/Y", so we need to map one to the other. Unfortunately, due to inertia, // web loses. So, we need these 3 ugly functions... private static _reactTouchEventToBasic(e: React.TouchEvent<any>): TouchEventBasic { const ne = clone(e) as any as TouchEventBasic; ne.changedTouches = this._mapReactTouchListToBasic(e.changedTouches); ne.targetTouches = this._mapReactTouchListToBasic(e.targetTouches); ne.touches = this._mapReactTouchListToBasic(e.touches); const ft = ne.touches[0]; if (ft) { // RN also apparently shims the first touch's location info onto the root touch event ne.pageX = ft.pageX; ne.pageY = ft.pageY; ne.locationX = ft.locationX; ne.locationY = ft.locationY; } return ne; } private static _mapReactTouchListToBasic(l: React.TouchList): TouchListBasic { const nl: Types.Touch[] = new Array(l.length); for (let i = 0; i < l.length; i++) { nl[i] = this._mapReactTouchToRx(l[i]); } return nl; } private static _mapReactTouchToRx(l: React.Touch): Types.Touch { return { identifier: l.identifier, locationX: l.clientX, locationY: l.clientY, screenX: l.screenX, screenY: l.screenY, clientX: l.clientX, clientY: l.clientY, pageX: l.pageX, pageY: l.pageY, }; } private _onTouchStart = (e: React.TouchEvent<any>) => { if (!this._initialTouch) { const ft = e.touches[0]; this._initialTouch = { x: ft.clientX, y: ft.clientY }; this._ongoingGesture = { dx: 0, dy: 0, vx: 0, vy: 0 }; this._onTouchSeriesStart(GestureView._reactTouchEventToBasic(e)); } }; private _onTouchMove = (e: React.TouchEvent<any>) => { if (!this._initialTouch || !this._ongoingGesture) { return; } const ft = e.touches[0]; this._ongoingGesture = { dx: ft.clientX - this._initialTouch.x, dy: ft.clientY - this._initialTouch.y, // TODO: calculate velocity? vx: 0, vy: 0, }; this._onTouchChange(GestureView._reactTouchEventToBasic(e), this._ongoingGesture); }; private _onTouchEnd = (e: React.TouchEvent<any>) => { if (!this._initialTouch || !this._ongoingGesture) { return; } if (e.touches.length === 0) { this._onTouchSeriesFinished(GestureView._reactTouchEventToBasic(e), this._ongoingGesture); this._initialTouch = undefined; this._ongoingGesture = undefined; } }; private _detectGestureType = (gestureState: Types.PanGestureState) => { // we need to lock gesture type until it's completed if (this._gestureTypeLocked) { return this._pendingMouseGestureType; } this._gestureTypeLocked = true; const gsBasic: GestureStatePoint = { dx: gestureState.clientX - gestureState.initialClientX, dy: gestureState.clientY - gestureState.initialClientY, }; if (this._shouldRespondToPan(gsBasic)) { return GestureType.Pan; } else if (this._shouldRespondToPanVertical(gsBasic)) { return GestureType.PanVertical; } else if (this._shouldRespondToPanHorizontal(gsBasic)) { return GestureType.PanHorizontal; } this._gestureTypeLocked = false; return GestureType.None; }; private _onWheel = (e: React.WheelEvent<any>) => { if (this.props.onScrollWheel) { const clientRect = this._getGestureViewClientRect(); if (clientRect) { const scrollWheelEvent: Types.ScrollWheelGestureState = { clientX: e.clientX - clientRect.left, clientY: e.clientY - clientRect.top, pageX: e.pageX, pageY: e.pageY, scrollAmount: e.deltaY, timeStamp: e.timeStamp, isTouch: false, }; this.props.onScrollWheel(scrollWheelEvent); } } }; private _sendMousePanEvent = (gestureState: Types.PanGestureState) => { switch (this._pendingMouseGestureType) { case GestureType.Pan: if (this.props.onPan) { this.props.onPan(gestureState); } break; case GestureType.PanVertical: if (this.props.onPanVertical) { this.props.onPanVertical(gestureState); } break; case GestureType.PanHorizontal: if (this.props.onPanHorizontal) { this.props.onPanHorizontal(gestureState); } break; default: // do nothing; } // we need to clean taps in case there was a pan event in the meantime if (this._pendingMouseGestureType !== GestureType.None) { this._clearLastTap(); this._cancelDoubleTapTimer(); this._skipNextTap(); } }; protected _getClientXYOffset(): { x: number; y: number } { const rect = this._getGestureViewClientRect(); return rect ? { x: rect.left, y: rect.top } : { x: 0, y: 0 }; } private _getGestureViewClientRect() { return this._container ? this._container.getBoundingClientRect() : null; } } export default GestureView;
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { PollerLike, PollOperationState } from "@azure/core-lro"; import { AppServiceEnvironmentResource, AppServiceEnvironmentsListOptionalParams, AppServiceEnvironmentsListByResourceGroupOptionalParams, StampCapacity, AppServiceEnvironmentsListCapacitiesOptionalParams, Site, VirtualNetworkProfile, AppServiceEnvironmentsChangeVnetOptionalParams, InboundEnvironmentEndpoint, AppServiceEnvironmentsGetInboundNetworkDependenciesEndpointsOptionalParams, WorkerPoolResource, AppServiceEnvironmentsListMultiRolePoolsOptionalParams, ResourceMetricDefinition, AppServiceEnvironmentsListMultiRolePoolInstanceMetricDefinitionsOptionalParams, AppServiceEnvironmentsListMultiRoleMetricDefinitionsOptionalParams, SkuInfo, AppServiceEnvironmentsListMultiRolePoolSkusOptionalParams, Usage, AppServiceEnvironmentsListMultiRoleUsagesOptionalParams, OutboundEnvironmentEndpoint, AppServiceEnvironmentsGetOutboundNetworkDependenciesEndpointsOptionalParams, AppServiceEnvironmentsResumeOptionalParams, AppServicePlan, AppServiceEnvironmentsListAppServicePlansOptionalParams, AppServiceEnvironmentsListWebAppsOptionalParams, AppServiceEnvironmentsSuspendOptionalParams, CsmUsageQuota, AppServiceEnvironmentsListUsagesOptionalParams, AppServiceEnvironmentsListWorkerPoolsOptionalParams, AppServiceEnvironmentsListWorkerPoolInstanceMetricDefinitionsOptionalParams, AppServiceEnvironmentsListWebWorkerMetricDefinitionsOptionalParams, AppServiceEnvironmentsListWorkerPoolSkusOptionalParams, AppServiceEnvironmentsListWebWorkerUsagesOptionalParams, AppServiceEnvironmentsGetOptionalParams, AppServiceEnvironmentsGetResponse, AppServiceEnvironmentsCreateOrUpdateOptionalParams, AppServiceEnvironmentsCreateOrUpdateResponse, AppServiceEnvironmentsDeleteOptionalParams, AppServiceEnvironmentPatchResource, AppServiceEnvironmentsUpdateOptionalParams, AppServiceEnvironmentsUpdateResponse, AppServiceEnvironmentsGetVipInfoOptionalParams, AppServiceEnvironmentsGetVipInfoResponse, AppServiceEnvironmentsListDiagnosticsOptionalParams, AppServiceEnvironmentsListDiagnosticsResponse, AppServiceEnvironmentsGetDiagnosticsItemOptionalParams, AppServiceEnvironmentsGetDiagnosticsItemResponse, AppServiceEnvironmentsGetMultiRolePoolOptionalParams, AppServiceEnvironmentsGetMultiRolePoolResponse, AppServiceEnvironmentsCreateOrUpdateMultiRolePoolOptionalParams, AppServiceEnvironmentsCreateOrUpdateMultiRolePoolResponse, AppServiceEnvironmentsUpdateMultiRolePoolOptionalParams, AppServiceEnvironmentsUpdateMultiRolePoolResponse, AppServiceEnvironmentsListOperationsOptionalParams, AppServiceEnvironmentsListOperationsResponse, AppServiceEnvironmentsRebootOptionalParams, AppServiceEnvironmentsGetWorkerPoolOptionalParams, AppServiceEnvironmentsGetWorkerPoolResponse, AppServiceEnvironmentsCreateOrUpdateWorkerPoolOptionalParams, AppServiceEnvironmentsCreateOrUpdateWorkerPoolResponse, AppServiceEnvironmentsUpdateWorkerPoolOptionalParams, AppServiceEnvironmentsUpdateWorkerPoolResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Interface representing a AppServiceEnvironments. */ export interface AppServiceEnvironments { /** * Description for Get all App Service Environments for a subscription. * @param options The options parameters. */ list( options?: AppServiceEnvironmentsListOptionalParams ): PagedAsyncIterableIterator<AppServiceEnvironmentResource>; /** * Description for Get all App Service Environments in a resource group. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param options The options parameters. */ listByResourceGroup( resourceGroupName: string, options?: AppServiceEnvironmentsListByResourceGroupOptionalParams ): PagedAsyncIterableIterator<AppServiceEnvironmentResource>; /** * Description for Get the used, available, and total worker capacity an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ listCapacities( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListCapacitiesOptionalParams ): PagedAsyncIterableIterator<StampCapacity>; /** * Description for Move an App Service Environment to a different VNET. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param vnetInfo Details for the new virtual network. * @param options The options parameters. */ beginListChangeVnetAndWait( resourceGroupName: string, name: string, vnetInfo: VirtualNetworkProfile, options?: AppServiceEnvironmentsChangeVnetOptionalParams ): PagedAsyncIterableIterator<Site>; /** * Description for Get the network endpoints of all inbound dependencies of an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ listInboundNetworkDependenciesEndpoints( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsGetInboundNetworkDependenciesEndpointsOptionalParams ): PagedAsyncIterableIterator<InboundEnvironmentEndpoint>; /** * Description for Get all multi-role pools. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ listMultiRolePools( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListMultiRolePoolsOptionalParams ): PagedAsyncIterableIterator<WorkerPoolResource>; /** * Description for Get metric definitions for a specific instance of a multi-role pool of an App * Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param instance Name of the instance in the multi-role pool. * @param options The options parameters. */ listMultiRolePoolInstanceMetricDefinitions( resourceGroupName: string, name: string, instance: string, options?: AppServiceEnvironmentsListMultiRolePoolInstanceMetricDefinitionsOptionalParams ): PagedAsyncIterableIterator<ResourceMetricDefinition>; /** * Description for Get metric definitions for a multi-role pool of an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ listMultiRoleMetricDefinitions( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListMultiRoleMetricDefinitionsOptionalParams ): PagedAsyncIterableIterator<ResourceMetricDefinition>; /** * Description for Get available SKUs for scaling a multi-role pool. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ listMultiRolePoolSkus( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListMultiRolePoolSkusOptionalParams ): PagedAsyncIterableIterator<SkuInfo>; /** * Description for Get usage metrics for a multi-role pool of an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ listMultiRoleUsages( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListMultiRoleUsagesOptionalParams ): PagedAsyncIterableIterator<Usage>; /** * Description for Get the network endpoints of all outbound dependencies of an App Service * Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ listOutboundNetworkDependenciesEndpoints( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsGetOutboundNetworkDependenciesEndpointsOptionalParams ): PagedAsyncIterableIterator<OutboundEnvironmentEndpoint>; /** * Description for Resume an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ beginListResumeAndWait( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsResumeOptionalParams ): PagedAsyncIterableIterator<Site>; /** * Description for Get all App Service plans in an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ listAppServicePlans( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListAppServicePlansOptionalParams ): PagedAsyncIterableIterator<AppServicePlan>; /** * Description for Get all apps in an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ listWebApps( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListWebAppsOptionalParams ): PagedAsyncIterableIterator<Site>; /** * Description for Suspend an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ beginListSuspendAndWait( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsSuspendOptionalParams ): PagedAsyncIterableIterator<Site>; /** * Description for Get global usage metrics of an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ listUsages( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListUsagesOptionalParams ): PagedAsyncIterableIterator<CsmUsageQuota>; /** * Description for Get all worker pools of an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ listWorkerPools( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListWorkerPoolsOptionalParams ): PagedAsyncIterableIterator<WorkerPoolResource>; /** * Description for Get metric definitions for a specific instance of a worker pool of an App Service * Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param workerPoolName Name of the worker pool. * @param instance Name of the instance in the worker pool. * @param options The options parameters. */ listWorkerPoolInstanceMetricDefinitions( resourceGroupName: string, name: string, workerPoolName: string, instance: string, options?: AppServiceEnvironmentsListWorkerPoolInstanceMetricDefinitionsOptionalParams ): PagedAsyncIterableIterator<ResourceMetricDefinition>; /** * Description for Get metric definitions for a worker pool of an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param workerPoolName Name of the worker pool. * @param options The options parameters. */ listWebWorkerMetricDefinitions( resourceGroupName: string, name: string, workerPoolName: string, options?: AppServiceEnvironmentsListWebWorkerMetricDefinitionsOptionalParams ): PagedAsyncIterableIterator<ResourceMetricDefinition>; /** * Description for Get available SKUs for scaling a worker pool. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param workerPoolName Name of the worker pool. * @param options The options parameters. */ listWorkerPoolSkus( resourceGroupName: string, name: string, workerPoolName: string, options?: AppServiceEnvironmentsListWorkerPoolSkusOptionalParams ): PagedAsyncIterableIterator<SkuInfo>; /** * Description for Get usage metrics for a worker pool of an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param workerPoolName Name of the worker pool. * @param options The options parameters. */ listWebWorkerUsages( resourceGroupName: string, name: string, workerPoolName: string, options?: AppServiceEnvironmentsListWebWorkerUsagesOptionalParams ): PagedAsyncIterableIterator<Usage>; /** * Description for Get the properties of an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ get( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsGetOptionalParams ): Promise<AppServiceEnvironmentsGetResponse>; /** * Description for Create or update an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param hostingEnvironmentEnvelope Configuration details of the App Service Environment. * @param options The options parameters. */ beginCreateOrUpdate( resourceGroupName: string, name: string, hostingEnvironmentEnvelope: AppServiceEnvironmentResource, options?: AppServiceEnvironmentsCreateOrUpdateOptionalParams ): Promise< PollerLike< PollOperationState<AppServiceEnvironmentsCreateOrUpdateResponse>, AppServiceEnvironmentsCreateOrUpdateResponse > >; /** * Description for Create or update an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param hostingEnvironmentEnvelope Configuration details of the App Service Environment. * @param options The options parameters. */ beginCreateOrUpdateAndWait( resourceGroupName: string, name: string, hostingEnvironmentEnvelope: AppServiceEnvironmentResource, options?: AppServiceEnvironmentsCreateOrUpdateOptionalParams ): Promise<AppServiceEnvironmentsCreateOrUpdateResponse>; /** * Description for Delete an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ beginDelete( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsDeleteOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>>; /** * Description for Delete an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ beginDeleteAndWait( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsDeleteOptionalParams ): Promise<void>; /** * Description for Create or update an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param hostingEnvironmentEnvelope Configuration details of the App Service Environment. * @param options The options parameters. */ update( resourceGroupName: string, name: string, hostingEnvironmentEnvelope: AppServiceEnvironmentPatchResource, options?: AppServiceEnvironmentsUpdateOptionalParams ): Promise<AppServiceEnvironmentsUpdateResponse>; /** * Description for Get IP addresses assigned to an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ getVipInfo( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsGetVipInfoOptionalParams ): Promise<AppServiceEnvironmentsGetVipInfoResponse>; /** * Description for Get diagnostic information for an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ listDiagnostics( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListDiagnosticsOptionalParams ): Promise<AppServiceEnvironmentsListDiagnosticsResponse>; /** * Description for Get a diagnostics item for an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param diagnosticsName Name of the diagnostics item. * @param options The options parameters. */ getDiagnosticsItem( resourceGroupName: string, name: string, diagnosticsName: string, options?: AppServiceEnvironmentsGetDiagnosticsItemOptionalParams ): Promise<AppServiceEnvironmentsGetDiagnosticsItemResponse>; /** * Description for Get properties of a multi-role pool. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ getMultiRolePool( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsGetMultiRolePoolOptionalParams ): Promise<AppServiceEnvironmentsGetMultiRolePoolResponse>; /** * Description for Create or update a multi-role pool. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param multiRolePoolEnvelope Properties of the multi-role pool. * @param options The options parameters. */ beginCreateOrUpdateMultiRolePool( resourceGroupName: string, name: string, multiRolePoolEnvelope: WorkerPoolResource, options?: AppServiceEnvironmentsCreateOrUpdateMultiRolePoolOptionalParams ): Promise< PollerLike< PollOperationState< AppServiceEnvironmentsCreateOrUpdateMultiRolePoolResponse >, AppServiceEnvironmentsCreateOrUpdateMultiRolePoolResponse > >; /** * Description for Create or update a multi-role pool. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param multiRolePoolEnvelope Properties of the multi-role pool. * @param options The options parameters. */ beginCreateOrUpdateMultiRolePoolAndWait( resourceGroupName: string, name: string, multiRolePoolEnvelope: WorkerPoolResource, options?: AppServiceEnvironmentsCreateOrUpdateMultiRolePoolOptionalParams ): Promise<AppServiceEnvironmentsCreateOrUpdateMultiRolePoolResponse>; /** * Description for Create or update a multi-role pool. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param multiRolePoolEnvelope Properties of the multi-role pool. * @param options The options parameters. */ updateMultiRolePool( resourceGroupName: string, name: string, multiRolePoolEnvelope: WorkerPoolResource, options?: AppServiceEnvironmentsUpdateMultiRolePoolOptionalParams ): Promise<AppServiceEnvironmentsUpdateMultiRolePoolResponse>; /** * Description for List all currently running operations on the App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ listOperations( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsListOperationsOptionalParams ): Promise<AppServiceEnvironmentsListOperationsResponse>; /** * Description for Reboot all machines in an App Service Environment. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param options The options parameters. */ reboot( resourceGroupName: string, name: string, options?: AppServiceEnvironmentsRebootOptionalParams ): Promise<void>; /** * Description for Get properties of a worker pool. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param workerPoolName Name of the worker pool. * @param options The options parameters. */ getWorkerPool( resourceGroupName: string, name: string, workerPoolName: string, options?: AppServiceEnvironmentsGetWorkerPoolOptionalParams ): Promise<AppServiceEnvironmentsGetWorkerPoolResponse>; /** * Description for Create or update a worker pool. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param workerPoolName Name of the worker pool. * @param workerPoolEnvelope Properties of the worker pool. * @param options The options parameters. */ beginCreateOrUpdateWorkerPool( resourceGroupName: string, name: string, workerPoolName: string, workerPoolEnvelope: WorkerPoolResource, options?: AppServiceEnvironmentsCreateOrUpdateWorkerPoolOptionalParams ): Promise< PollerLike< PollOperationState< AppServiceEnvironmentsCreateOrUpdateWorkerPoolResponse >, AppServiceEnvironmentsCreateOrUpdateWorkerPoolResponse > >; /** * Description for Create or update a worker pool. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param workerPoolName Name of the worker pool. * @param workerPoolEnvelope Properties of the worker pool. * @param options The options parameters. */ beginCreateOrUpdateWorkerPoolAndWait( resourceGroupName: string, name: string, workerPoolName: string, workerPoolEnvelope: WorkerPoolResource, options?: AppServiceEnvironmentsCreateOrUpdateWorkerPoolOptionalParams ): Promise<AppServiceEnvironmentsCreateOrUpdateWorkerPoolResponse>; /** * Description for Create or update a worker pool. * @param resourceGroupName Name of the resource group to which the resource belongs. * @param name Name of the App Service Environment. * @param workerPoolName Name of the worker pool. * @param workerPoolEnvelope Properties of the worker pool. * @param options The options parameters. */ updateWorkerPool( resourceGroupName: string, name: string, workerPoolName: string, workerPoolEnvelope: WorkerPoolResource, options?: AppServiceEnvironmentsUpdateWorkerPoolOptionalParams ): Promise<AppServiceEnvironmentsUpdateWorkerPoolResponse>; }
the_stack
import type {LoaderWithParser, LoaderOptions} from '@loaders.gl/loader-utils'; import type {Batch} from '@loaders.gl/schema'; type Schema = any; import { AsyncQueue, TableBatchBuilder, convertToArrayRow, convertToObjectRow } from '@loaders.gl/schema'; import Papa from './libs/papaparse'; import AsyncIteratorStreamer from './lib/async-iterator-streamer'; // __VERSION__ is injected by babel-plugin-version-inline // @ts-ignore TS2304: Cannot find name '__VERSION__'. const VERSION = typeof __VERSION__ !== 'undefined' ? __VERSION__ : 'latest'; export type CSVLoaderOptions = LoaderOptions & { csv?: { // loaders.gl options shape?: 'array-row-table' | 'object-row-table' | 'columnar-table'; /** optimizes memory usage but increases parsing time. */ optimizeMemoryUsage?: boolean; columnPrefix?: string; header?: 'auto'; // CSV options (papaparse) // delimiter: auto // newline: auto quoteChar?: string; escapeChar?: string; // Convert numbers and boolean values in rows from strings dynamicTyping?: boolean; comments?: boolean; skipEmptyLines?: boolean | 'greedy'; // transform: null? delimitersToGuess?: string[]; // fastMode: auto }; }; const DEFAULT_CSV_LOADER_OPTIONS = { csv: { shape: 'object-row-table', optimizeMemoryUsage: false, // CSV options header: 'auto', columnPrefix: 'column', // delimiter: auto // newline: auto quoteChar: '"', escapeChar: '"', dynamicTyping: true, comments: false, skipEmptyLines: true, // transform: null? delimitersToGuess: [',', '\t', '|', ';'] // fastMode: auto } }; export const CSVLoader = { id: 'csv', module: 'csv', name: 'CSV', version: VERSION, extensions: ['csv', 'tsv', 'dsv'], mimeTypes: ['text/csv', 'text/tab-separated-values', 'text/dsv'], category: 'table', parse: async (arrayBuffer: ArrayBuffer, options?: CSVLoaderOptions) => parseCSV(new TextDecoder().decode(arrayBuffer), options), parseText: (text: string, options?: CSVLoaderOptions) => parseCSV(text, options), parseInBatches: parseCSVInBatches, // @ts-ignore // testText: null, options: DEFAULT_CSV_LOADER_OPTIONS as CSVLoaderOptions }; async function parseCSV(csvText: string, options?: CSVLoaderOptions) { // Apps can call the parse method directly, we so apply default options here const csvOptions = {...DEFAULT_CSV_LOADER_OPTIONS.csv, ...options?.csv}; const firstRow = readFirstRow(csvText); const header: boolean = csvOptions.header === 'auto' ? isHeaderRow(firstRow) : Boolean(csvOptions.header); const parseWithHeader = header; const papaparseConfig = { // dynamicTyping: true, ...csvOptions, header: parseWithHeader, download: false, // We handle loading, no need for papaparse to do it for us transformHeader: parseWithHeader ? duplicateColumnTransformer() : undefined, error: (e) => { throw new Error(e); } }; const result = Papa.parse(csvText, papaparseConfig); let {data: rows} = result; const headerRow = result.meta.fields || generateHeader(csvOptions.columnPrefix, firstRow.length); switch (csvOptions.shape) { case 'object-row-table': rows = rows.map((row) => (Array.isArray(row) ? convertToObjectRow(row, headerRow) : row)); break; case 'array-row-table': rows = rows.map((row) => (Array.isArray(row) ? row : convertToArrayRow(row, headerRow))); break; default: } /* if (!header && shape === 'object-row-table') { // If the dataset has no header, transform the array result into an object shape with an // autogenerated header return result.data.map((row) => row.reduce((acc, value, i) => { acc[headerRow[i]] = value; return acc; }, {}) ); } */ return rows; } // TODO - support batch size 0 = no batching/single batch? function parseCSVInBatches( asyncIterator: AsyncIterable<ArrayBuffer> | Iterable<ArrayBuffer>, options?: CSVLoaderOptions ): AsyncIterable<Batch> { // Papaparse does not support standard batch size handling // TODO - investigate papaparse chunks mode options = {...options}; if (options.batchSize === 'auto') { options.batchSize = 4000; } // Apps can call the parse method directly, we so apply default options here const csvOptions = {...DEFAULT_CSV_LOADER_OPTIONS.csv, ...options?.csv}; const asyncQueue = new AsyncQueue<Batch>(); let isFirstRow: boolean = true; let headerRow: string[] | null = null; let tableBatchBuilder: TableBatchBuilder | null = null; let schema: Schema | null = null; const config = { // dynamicTyping: true, // Convert numbers and boolean values in rows from strings, ...csvOptions, header: false, // Unfortunately, header detection is not automatic and does not infer shapes download: false, // We handle loading, no need for papaparse to do it for us // chunkSize is set to 5MB explicitly (same as Papaparse default) due to a bug where the // streaming parser gets stuck if skipEmptyLines and a step callback are both supplied. // See https://github.com/mholt/PapaParse/issues/465 chunkSize: 1024 * 1024 * 5, // skipEmptyLines is set to a boolean value if supplied. Greedy is set to true // skipEmptyLines is handled manually given two bugs where the streaming parser gets stuck if // both of the skipEmptyLines and step callback options are provided: // - true doesn't work unless chunkSize is set: https://github.com/mholt/PapaParse/issues/465 // - greedy doesn't work: https://github.com/mholt/PapaParse/issues/825 skipEmptyLines: false, // step is called on every row // eslint-disable-next-line complexity step(results) { let row = results.data; if (csvOptions.skipEmptyLines) { // Manually reject lines that are empty const collapsedRow = row.flat().join('').trim(); if (collapsedRow === '') { return; } } const bytesUsed = results.meta.cursor; // Check if we need to save a header row if (isFirstRow && !headerRow) { // Auto detects or can be forced with csvOptions.header const header = csvOptions.header === 'auto' ? isHeaderRow(row) : Boolean(csvOptions.header); if (header) { headerRow = row.map(duplicateColumnTransformer()); return; } } // If first data row, we can deduce the schema if (isFirstRow) { isFirstRow = false; if (!headerRow) { headerRow = generateHeader(csvOptions.columnPrefix, row.length); } schema = deduceSchema(row, headerRow); } if (csvOptions.optimizeMemoryUsage) { // A workaround to allocate new strings and don't retain pointers to original strings. // https://bugs.chromium.org/p/v8/issues/detail?id=2869 row = JSON.parse(JSON.stringify(row)); } // Add the row tableBatchBuilder = tableBatchBuilder || new TableBatchBuilder(schema, { // @ts-expect-error shape: csvOptions.shape || 'array-row-table', ...options }); try { tableBatchBuilder.addRow(row); // If a batch has been completed, emit it const batch = tableBatchBuilder && tableBatchBuilder.getFullBatch({bytesUsed}); if (batch) { asyncQueue.enqueue(batch); } } catch (error) { asyncQueue.enqueue(error as Error); } }, // complete is called when all rows have been read complete(results) { try { const bytesUsed = results.meta.cursor; // Ensure any final (partial) batch gets emitted const batch = tableBatchBuilder && tableBatchBuilder.getFinalBatch({bytesUsed}); if (batch) { asyncQueue.enqueue(batch); } } catch (error) { asyncQueue.enqueue(error as Error); } asyncQueue.close(); } }; Papa.parse(asyncIterator, config, AsyncIteratorStreamer); // TODO - Does it matter if we return asyncIterable or asyncIterator // return asyncQueue[Symbol.asyncIterator](); return asyncQueue; } /** * Checks if a certain row is a header row * @param row the row to check * @returns true if the row looks like a header */ function isHeaderRow(row: string[]): boolean { return row && row.every((value) => typeof value === 'string'); } /** * Reads, parses, and returns the first row of a CSV text * @param csvText the csv text to parse * @returns the first row */ function readFirstRow(csvText: string): any[] { const result = Papa.parse(csvText, { download: false, dynamicTyping: true, preview: 1 }); return result.data[0]; } /** * Creates a transformer that renames duplicate columns. This is needed as Papaparse doesn't handle * duplicate header columns and would use the latest occurrence by default. * See the header option in https://www.papaparse.com/docs#config * @returns a transform function that returns sanitized names for duplicate fields */ function duplicateColumnTransformer() { const observedColumns = new Set(); return (col) => { let colName = col; let counter = 1; while (observedColumns.has(colName)) { colName = `${col}.${counter}`; counter++; } observedColumns.add(colName); return colName; }; } /** * Generates the header of a CSV given a prefix and a column count * @param columnPrefix the columnPrefix to use * @param count the count of column names to generate * @returns an array of column names */ function generateHeader(columnPrefix: string, count: number = 0): string[] { const headers: string[] = []; for (let i = 0; i < count; i++) { headers.push(`${columnPrefix}${i + 1}`); } return headers; } function deduceSchema(row, headerRow) { const schema = headerRow ? {} : []; for (let i = 0; i < row.length; i++) { const columnName = (headerRow && headerRow[i]) || i; const value = row[i]; switch (typeof value) { case 'number': case 'boolean': // TODO - booleans could be handled differently... schema[columnName] = {name: String(columnName), index: i, type: Float32Array}; break; case 'string': default: schema[columnName] = {name: String(columnName), index: i, type: Array}; // We currently only handle numeric rows // TODO we could offer a function to map strings to numbers? } } return schema; } export const _typecheckCSVLoader: LoaderWithParser = CSVLoader;
the_stack
import { Component, ComponentFactory, ComponentFactoryResolver, ComponentRef, Inject, Injector, Input, OnDestroy, OnInit, ReflectiveInjector, ViewChild, ViewContainerRef, } from '@angular/core'; import { ActiveUIView, filter, inArray, isFunction, NATIVE_INJECTOR_TOKEN, Param, parse, PathNode, ResolveContext, StateDeclaration, trace, Transition, TransitionHookFn, UIRouter, unnestR, ViewConfig, ViewContext, } from '@uirouter/core'; import { Ng2ViewConfig } from '../statebuilders/views'; import { MergeInjector } from '../mergeInjector'; /** @hidden */ let id = 0; /** @internal These are provide()d as the string UIView.PARENT_INJECT */ export interface ParentUIViewInject { context: ViewContext; fqn: string; } /** @internal */ interface InputMapping { token: string; prop: string; } /** * Given a component class, gets the inputs of styles: * * - @Input('foo') _foo * - `inputs: ['foo']` * * @internal */ const ng2ComponentInputs = (factory: ComponentFactory<any>): InputMapping[] => { return factory.inputs.map((input) => ({ prop: input.propName, token: input.templateName })); }; /** * A UI-Router viewport directive, which is filled in by a view (component) on a state. * * ### Selector * * A `ui-view` directive can be created as an element: `<ui-view></ui-view>` or as an attribute: `<div ui-view></div>`. * * ### Purpose * * This directive is used in a Component template (or as the root component) to create a viewport. The viewport * is filled in by a view (as defined by a [[Ng2ViewDeclaration]] inside a [[Ng2StateDeclaration]]) when the view's * state has been activated. * * #### Example: * ```js * // This app has two states, 'foo' and 'bar' * stateRegistry.register({ name: 'foo', url: '/foo', component: FooComponent }); * stateRegistry.register({ name: 'bar', url: '/bar', component: BarComponent }); * ``` * ```html * <!-- This ui-view will be filled in by the foo state's component or * the bar state's component when the foo or bar state is activated --> * <ui-view></ui-view> * ``` * * ### Named ui-views * * A `ui-view` may optionally be given a name via the attribute value: `<div ui-view='header'></div>`. *Note: * an unnamed `ui-view` is internally named `$default`*. When a `ui-view` has a name, it will be filled in * by a matching named view. * * #### Example: * ```js * stateRegistry.register({ * name: 'foo', * url: '/foo', * views: { header: HeaderComponent, $default: FooComponent }); * ``` * ```html * <!-- When 'foo' state is active, filled by HeaderComponent --> * <div ui-view="header"></div> * * <!-- When 'foo' state is active, filled by FooComponent --> * <ui-view></ui-view> * ``` */ @Component({ selector: 'ui-view, [ui-view]', exportAs: 'uiView', template: ` <ng-template #componentTarget></ng-template> <ng-content *ngIf="!_componentRef"></ng-content> `, }) export class UIView implements OnInit, OnDestroy { static PARENT_INJECT = 'UIView.PARENT_INJECT'; @ViewChild('componentTarget', { read: ViewContainerRef, static: true }) _componentTarget: ViewContainerRef; @Input('name') name: string; @Input('ui-view') set _name(val: string) { this.name = val; } /** The reference to the component currently inside the viewport */ _componentRef: ComponentRef<any>; /** Deregisters the ui-view from the view service */ private _deregisterUIView: Function; /** Deregisters the master uiCanExit transition hook */ private _deregisterUiCanExitHook: Function; /** Deregisters the master uiOnParamsChanged transition hook */ private _deregisterUiOnParamsChangedHook: Function; /** Data about the this UIView */ private _uiViewData: ActiveUIView = <any>{}; private _parent: ParentUIViewInject; constructor( public router: UIRouter, @Inject(UIView.PARENT_INJECT) parent, public viewContainerRef: ViewContainerRef ) { this._parent = parent; } /** * @returns the UI-Router `state` that is filling this uiView, or `undefined`. */ public get state(): StateDeclaration { return parse('_uiViewData.config.viewDecl.$context.self')(this); } ngOnInit() { const router = this.router; const parentFqn = this._parent.fqn; const name = this.name || '$default'; this._uiViewData = { $type: 'ng2', id: id++, name: name, fqn: parentFqn ? parentFqn + '.' + name : name, creationContext: this._parent.context, configUpdated: this._viewConfigUpdated.bind(this), config: undefined, }; this._deregisterUiCanExitHook = router.transitionService.onBefore({}, (trans) => { return this._invokeUiCanExitHook(trans); }); this._deregisterUiOnParamsChangedHook = router.transitionService.onSuccess({}, (trans) => this._invokeUiOnParamsChangedHook(trans) ); this._deregisterUIView = router.viewService.registerUIView(this._uiViewData); } /** * For each transition, checks the component loaded in the ui-view for: * * - has a uiCanExit() component hook * - is being exited * * If both are true, adds the uiCanExit component function as a hook to that singular Transition. */ private _invokeUiCanExitHook(trans: Transition) { const instance = this._componentRef && this._componentRef.instance; const uiCanExitFn: TransitionHookFn = instance && instance.uiCanExit; if (isFunction(uiCanExitFn)) { const state: StateDeclaration = this.state; if (trans.exiting().indexOf(state) !== -1) { trans.onStart({}, function () { return uiCanExitFn.call(instance, trans); }); } } } /** * For each transition, checks if any param values changed and notify component */ private _invokeUiOnParamsChangedHook($transition$: Transition) { const instance = this._componentRef && this._componentRef.instance; const uiOnParamsChanged: TransitionHookFn = instance && instance.uiOnParamsChanged; if (isFunction(uiOnParamsChanged)) { const viewState: StateDeclaration = this.state; const resolveContext: ResolveContext = new ResolveContext(this._uiViewData.config.path); const viewCreationTrans = resolveContext.getResolvable('$transition$').data; // Exit early if the $transition$ is the same as the view was created within. // Exit early if the $transition$ will exit the state the view is for. if ($transition$ === viewCreationTrans || $transition$.exiting().indexOf(viewState as StateDeclaration) !== -1) return; const toParams: { [paramName: string]: any } = $transition$.params('to'); const fromParams: { [paramName: string]: any } = $transition$.params('from'); const getNodeSchema = (node: PathNode) => node.paramSchema; const toSchema: Param[] = $transition$.treeChanges('to').map(getNodeSchema).reduce(unnestR, []); const fromSchema: Param[] = $transition$.treeChanges('from').map(getNodeSchema).reduce(unnestR, []); // Find the to params that have different values than the from params const changedToParams = toSchema.filter((param: Param) => { const idx = fromSchema.indexOf(param); return idx === -1 || !fromSchema[idx].type.equals(toParams[param.id], fromParams[param.id]); }); // Only trigger callback if a to param has changed or is new if (changedToParams.length) { const changedKeys: string[] = changedToParams.map((x) => x.id); // Filter the params to only changed/new to params. `$transition$.params()` may be used to get all params. const newValues = filter(toParams, (val, key) => changedKeys.indexOf(key) !== -1); instance.uiOnParamsChanged(newValues, $transition$); } } } private _disposeLast() { if (this._componentRef) this._componentRef.destroy(); this._componentRef = null; } ngOnDestroy() { if (this._deregisterUIView) this._deregisterUIView(); if (this._deregisterUiCanExitHook) this._deregisterUiCanExitHook(); if (this._deregisterUiOnParamsChangedHook) this._deregisterUiOnParamsChangedHook(); this._deregisterUIView = this._deregisterUiCanExitHook = this._deregisterUiOnParamsChangedHook = null; this._disposeLast(); } /** * The view service is informing us of an updated ViewConfig * (usually because a transition activated some state and its views) */ _viewConfigUpdated(config: ViewConfig) { // The config may be undefined if there is nothing currently targeting this UIView. // Dispose the current component, if there is one if (!config) return this._disposeLast(); // Only care about Ng2 configs if (!(config instanceof Ng2ViewConfig)) return; // The "new" viewconfig is already applied, so exit early if (this._uiViewData.config === config) return; // This is a new ViewConfig. Dispose the previous component this._disposeLast(); trace.traceUIViewConfigUpdated(this._uiViewData, config && config.viewDecl.$context); this._applyUpdatedConfig(config); // Initiate change detection for the newly created component this._componentRef.changeDetectorRef.markForCheck(); } private _applyUpdatedConfig(config: Ng2ViewConfig) { this._uiViewData.config = config; // Create the Injector for the routed component const context = new ResolveContext(config.path); const componentInjector = this._getComponentInjector(context); // Get the component class from the view declaration. TODO: allow promises? const componentClass = config.viewDecl.component; // Create the component const compFactoryResolver = componentInjector.get(ComponentFactoryResolver); const compFactory = compFactoryResolver.resolveComponentFactory(componentClass); this._componentRef = this._componentTarget.createComponent(compFactory, undefined, componentInjector); // Wire resolves to @Input()s this._applyInputBindings(compFactory, this._componentRef.instance, context, componentClass); } /** * Creates a new Injector for a routed component. * * Adds resolve values to the Injector * Adds providers from the NgModule for the state * Adds providers from the parent Component in the component tree * Adds a PARENT_INJECT view context object * * @returns an Injector */ private _getComponentInjector(context: ResolveContext): Injector { // Map resolves to "useValue: providers" const resolvables = context .getTokens() .map((token) => context.getResolvable(token)) .filter((r) => r.resolved); const newProviders = resolvables.map((r) => ({ provide: r.token, useValue: context.injector().get(r.token) })); const parentInject = { context: this._uiViewData.config.viewDecl.$context, fqn: this._uiViewData.fqn }; newProviders.push({ provide: UIView.PARENT_INJECT, useValue: parentInject }); const parentComponentInjector = this.viewContainerRef.injector; const moduleInjector = context.getResolvable(NATIVE_INJECTOR_TOKEN).data; const mergedParentInjector = new MergeInjector(moduleInjector, parentComponentInjector); return ReflectiveInjector.resolveAndCreate(newProviders, mergedParentInjector); } /** * Supplies component inputs with resolve data * * Finds component inputs which match resolves (by name) and sets the input value * to the resolve data. */ private _applyInputBindings(factory: ComponentFactory<any>, component: any, context: ResolveContext, componentClass) { const bindings = this._uiViewData.config.viewDecl['bindings'] || {}; const explicitBoundProps = Object.keys(bindings); // Returns the actual component property for a renamed an input renamed using `@Input('foo') _foo`. // return the `_foo` property const renamedInputProp = (prop: string) => { const input = factory.inputs.find((i) => i.templateName === prop); return (input && input.propName) || prop; }; // Supply resolve data to component as specified in the state's `bindings: {}` const explicitInputTuples = explicitBoundProps.reduce( (acc, key) => acc.concat([{ prop: renamedInputProp(key), token: bindings[key] }]), [] ); // Supply resolve data to matching @Input('prop') or inputs: ['prop'] const implicitInputTuples = ng2ComponentInputs(factory).filter((tuple) => !inArray(explicitBoundProps, tuple.prop)); const addResolvable = (tuple: InputMapping) => ({ prop: tuple.prop, resolvable: context.getResolvable(tuple.token), }); const injector = context.injector(); explicitInputTuples .concat(implicitInputTuples) .map(addResolvable) .filter((tuple) => tuple.resolvable && tuple.resolvable.resolved) .forEach((tuple) => { component[tuple.prop] = injector.get(tuple.resolvable.token); }); } }
the_stack
import { AggregateFieldSubAggregateType, ChartDataSectionFieldActionType, ChartDataSectionType, ChartDataViewFieldCategory, DataViewFieldType, } from 'app/constants'; import useFieldActionModal from 'app/hooks/useFieldActionModal'; import ChartAggregationContext from 'app/pages/ChartWorkbenchPage/contexts/ChartAggregationContext'; import ChartDatasetContext from 'app/pages/ChartWorkbenchPage/contexts/ChartDatasetContext'; import VizDataViewContext from 'app/pages/ChartWorkbenchPage/contexts/ChartDataViewContext'; import ChartDrillContext from 'app/pages/ChartWorkbenchPage/contexts/ChartDrillContext'; import { ChartDataSectionField } from 'app/types/ChartConfig'; import { ChartDataConfigSectionProps } from 'app/types/ChartDataConfigSection'; import { getColumnRenderName } from 'app/utils/chartHelper'; import { reachLowerBoundCount } from 'app/utils/internalChartHelper'; import { updateBy, updateByKey } from 'app/utils/mutation'; import { CHART_DRAG_ELEMENT_TYPE } from 'globalConstants'; import { rgba } from 'polished'; import { FC, memo, useContext, useEffect, useState } from 'react'; import { DropTargetMonitor, useDrop } from 'react-dnd'; import styled from 'styled-components/macro'; import { BORDER_RADIUS, FONT_SIZE_SUBTITLE, LINE_HEIGHT_HEADING, SPACE, SPACE_MD, SPACE_SM, SPACE_XS, } from 'styles/StyleConstants'; import { ValueOf } from 'types'; import { uuidv4 } from 'utils/utils'; import ChartDraggableElement from './ChartDraggableElement'; import ChartDraggableElementField from './ChartDraggableElementField'; import ChartDraggableElementHierarchy from './ChartDraggableElementHierarchy'; import { updateDataConfigByField } from './utils'; type DragItem = { index?: number; }; export const ChartDraggableTargetContainer: FC<ChartDataConfigSectionProps> = memo(function ChartDraggableTargetContainer({ ancestors, modalSize, config, translate: t = (...args) => args?.[0], onConfigChanged, }) { const { dataset } = useContext(ChartDatasetContext); const { drillOption } = useContext(ChartDrillContext); const { dataView, availableSourceFunctions } = useContext(VizDataViewContext); const [currentConfig, setCurrentConfig] = useState(config); const [showModal, contextHolder] = useFieldActionModal({ i18nPrefix: 'viz.palette.data.enum.actionType', }); const { aggregation } = useContext(ChartAggregationContext); useEffect(() => { setCurrentConfig(config); }, [config]); const [{ isOver, canDrop }, drop] = useDrop( () => ({ accept: [ CHART_DRAG_ELEMENT_TYPE.DATASET_COLUMN, CHART_DRAG_ELEMENT_TYPE.DATASET_COLUMN_GROUP, CHART_DRAG_ELEMENT_TYPE.DATA_CONFIG_COLUMN, ], drop(item: ChartDataSectionField & DragItem, monitor) { let items = Array.isArray(item) ? item : [item]; let needDelete = true; if ( monitor.getItemType() === CHART_DRAG_ELEMENT_TYPE.DATASET_COLUMN ) { const currentColumns: ChartDataSectionField[] = ( currentConfig.rows || [] ).concat( items.map(val => { let config: ChartDataSectionField = { uid: uuidv4(), ...val, aggregate: getDefaultAggregate(val), }; if ( val.category === ChartDataViewFieldCategory.DateLevelComputedField ) { config.colName = `${val.colName}(${t(val.expression)})`; config.expression = `${val.expression}(${val.colName})`; config.field = val.colName; } return config; }), ); updateCurrentConfigColumns(currentConfig, currentColumns, true); } else if ( monitor.getItemType() === CHART_DRAG_ELEMENT_TYPE.DATASET_COLUMN_GROUP ) { const hierarchyChildFields = items?.[0]?.children || []; const currentColumns: ChartDataSectionField[] = ( currentConfig.rows || [] ).concat( hierarchyChildFields.map(val => ({ uid: uuidv4(), ...val, aggregate: getDefaultAggregate(val), })), ); updateCurrentConfigColumns(currentConfig, currentColumns, true); } else if ( monitor.getItemType() === CHART_DRAG_ELEMENT_TYPE.DATA_CONFIG_COLUMN ) { const originItemIndex = (currentConfig.rows || []).findIndex( r => r.uid === item.uid, ); if (originItemIndex > -1) { const needRefreshData = currentConfig?.type === ChartDataSectionType.GROUP; needDelete = false; const currentColumns = updateBy( currentConfig?.rows || [], draft => { draft.splice(originItemIndex, 1); item.aggregate = getDefaultAggregate(item); return draft.splice(item?.index!, 0, item); }, ); updateCurrentConfigColumns( currentConfig, currentColumns, needRefreshData, ); } else { const currentColumns = updateBy( currentConfig?.rows || [], draft => { item.aggregate = getDefaultAggregate(item); return draft.splice(item?.index!, 0, item); }, ); updateCurrentConfigColumns(currentConfig, currentColumns); } } return { delete: needDelete }; }, canDrop: (item: ChartDataSectionField, monitor) => { let items = Array.isArray(item) ? item : [item]; if ( [CHART_DRAG_ELEMENT_TYPE.DATASET_COLUMN_GROUP].includes( monitor.getItemType() as any, ) && ![ ChartDataSectionType.GROUP, ChartDataSectionType.COLOR, ChartDataSectionType.MIXED, ].includes(currentConfig.type as ChartDataSectionType) ) { return false; } if ( typeof currentConfig.actions === 'object' && !items.every(val => val.type in (currentConfig.actions || {})) ) { //zh: 判断现在拖动的数据项是否可以拖动到当前容器中 en: Determine whether the currently dragged data item can be dragged into the current container return false; } // if ( // typeof currentConfig.actions === 'object' && // !(item.type in currentConfig.actions) // ) { // return false; // } if (currentConfig.allowSameField) { return true; } if ( monitor.getItemType() === CHART_DRAG_ELEMENT_TYPE.DATA_CONFIG_COLUMN ) { return true; } if ( items[0].category === ChartDataViewFieldCategory.DateLevelComputedField ) { const colNames = currentConfig.rows?.map(col => col.colName); return colNames ? colNames.every(v => !v?.includes(items[0].colName)) : true; } const exists = currentConfig.rows?.map(col => col.colName); return items.every(i => !exists?.includes(i.colName)); }, collect: (monitor: DropTargetMonitor) => ({ isOver: monitor.isOver(), canDrop: monitor.canDrop(), }), }), [onConfigChanged, currentConfig, dataView, dataset], ); const updateCurrentConfigColumns = ( currentConfig, newColumns, refreshDataset = false, ) => { const newCurrentConfig = updateByKey(currentConfig, 'rows', newColumns); setCurrentConfig(newCurrentConfig); onConfigChanged?.(ancestors, newCurrentConfig, refreshDataset); }; const getDefaultAggregate = (item: ChartDataSectionField) => { if ( currentConfig?.type === ChartDataSectionType.AGGREGATE || currentConfig?.type === ChartDataSectionType.SIZE || currentConfig?.type === ChartDataSectionType.INFO || currentConfig?.type === ChartDataSectionType.MIXED ) { if ( currentConfig.disableAggregate || item.category === ChartDataViewFieldCategory.AggregateComputedField ) { return; } if (item.aggregate) { return item.aggregate; } let aggType: string = ''; if (currentConfig?.actions instanceof Array) { currentConfig?.actions?.find( type => type === ChartDataSectionFieldActionType.Aggregate || type === ChartDataSectionFieldActionType.AggregateLimit, ); } else if (currentConfig?.actions instanceof Object) { aggType = currentConfig?.actions?.[item?.type]?.find( type => type === ChartDataSectionFieldActionType.Aggregate || type === ChartDataSectionFieldActionType.AggregateLimit, ); } if (aggType) { return AggregateFieldSubAggregateType?.[aggType]?.[0]; } } }; const onDraggableItemMove = (dragIndex: number, hoverIndex: number) => { const draggedItem = currentConfig.rows?.[dragIndex]; if (draggedItem) { const newCurrentConfig = updateBy(currentConfig, draft => { const columns = draft.rows || []; columns.splice(dragIndex, 1); columns.splice(hoverIndex, 0, draggedItem); }); setCurrentConfig(newCurrentConfig); } else { // const placeholder = { // uid: CHARTCONFIG_FIELD_PLACEHOLDER_UID, // colName: 'Placeholder', // category: 'field', // type: 'STRING', // } as any; // const newCurrentConfig = updateBy(currentConfig, draft => { // const columns = draft.rows || []; // if (dragIndex) { // columns.splice(dragIndex, 1); // } // columns.splice(hoverIndex, 0, placeholder); // }); // setCurrentConfig(newCurrentConfig); } }; const handleOnDeleteItem = config => () => { if (config.uid) { let newCurrentConfig = updateBy(currentConfig, draft => { draft.rows = draft.rows?.filter(c => c.uid !== config.uid); if ( config.category === ChartDataViewFieldCategory.DateLevelComputedField ) { draft.replacedColName = config.colName; } }); setCurrentConfig(newCurrentConfig); onConfigChanged?.(ancestors, newCurrentConfig, true); } }; const renderDropItems = () => { if ( !currentConfig.rows || !currentConfig?.rows?.filter(Boolean)?.length ) { const fieldCount = reachLowerBoundCount(currentConfig?.limit, 0); if (fieldCount > 0) { return ( <DropPlaceholder> {t('dropCount', undefined, { count: fieldCount })} </DropPlaceholder> ); } return <DropPlaceholder>{t('drop')}</DropPlaceholder>; } return currentConfig.rows?.map((columnConfig, index) => { return ( <ChartDraggableElement key={columnConfig.uid} id={columnConfig.uid} index={index} config={columnConfig} content={() => { const contentProps = { modalSize: modalSize, config: currentConfig, columnConfig: columnConfig, ancestors: ancestors, aggregation: aggregation, availableSourceFunctions, onConfigChanged: onConfigChanged, handleOpenActionModal: handleOpenActionModal, }; return columnConfig.category === ChartDataViewFieldCategory.Hierarchy ? ( <ChartDraggableElementHierarchy {...contentProps} /> ) : ( <ChartDraggableElementField {...contentProps} /> ); }} moveCard={onDraggableItemMove} onDelete={handleOnDeleteItem(columnConfig)} ></ChartDraggableElement> ); }); }; const renderDrillFilters = () => { if (currentConfig?.type !== ChartDataSectionType.FILTER) { return; } return getDillConditions()?.map(drill => { const field = drill.field; return ( <StyledDillFilter type={field.type}> {getColumnRenderName(field)} </StyledDillFilter> ); }); }; const getDillConditions = () => { return drillOption ?.getAllDrillDownFields() ?.filter(drill => Boolean(drill?.condition)); }; const handleFieldConfigChanged = ( columnUid: string, fieldConfig: ChartDataSectionField, needRefresh?: boolean, ) => { if (!fieldConfig) { return; } const newConfig = updateDataConfigByField( columnUid, currentConfig, fieldConfig, ); onConfigChanged?.(ancestors, newConfig, needRefresh); }; const handleOpenActionModal = (uid: string) => (actionType: ValueOf<typeof ChartDataSectionFieldActionType>) => { (showModal as Function)( uid, actionType, currentConfig, handleFieldConfigChanged, dataset, dataView, modalSize, aggregation, ); }; return ( <StyledContainer ref={drop} isOver={isOver} canDrop={canDrop}> {renderDropItems()} {renderDrillFilters()} {contextHolder} </StyledContainer> ); }); export default ChartDraggableTargetContainer; const StyledContainer = styled.div<{ isOver: boolean; canDrop: boolean; }>` padding: ${SPACE_SM}; color: ${p => p.theme.textColorLight}; text-align: center; background-color: ${props => props.canDrop ? rgba(props.theme.success, 0.25) : props.isOver ? rgba(props.theme.error, 0.25) : props.theme.emphasisBackground}; border-radius: ${BORDER_RADIUS}; .draggable-element:last-child { margin-bottom: 0; } `; const StyledDillFilter = styled.div<{ type: DataViewFieldType; }>` padding: ${SPACE_XS} ${SPACE_MD}; margin-bottom: ${SPACE}; font-size: ${FONT_SIZE_SUBTITLE}; color: ${p => p.theme.componentBackground}; cursor: move; background: ${p => p.type === DataViewFieldType.NUMERIC ? p.theme.success : p.theme.info}; border-radius: ${BORDER_RADIUS}; `; const DropPlaceholder = styled.p` line-height: ${LINE_HEIGHT_HEADING}; `;
the_stack
import { $BATCH, ACCEPT, APPLICATION_HTTP, APPLICATION_JSON, BATCH_PREFIX, BINARY, BOUNDARY_PREFIX_SUFFIX, CHANGESET_PREFIX, CONTENT_ID, CONTENT_TRANSFER_ENCODING, CONTENT_TYPE, HTTP11, MULTIPART_MIXED, MULTIPART_MIXED_BOUNDARY, NEWLINE, NEWLINE_REGEXP, ODATA_VERSION, VERSION_4_0, XSSI_PREFIX, } from '../../constants'; import { HttpErrorResponse, HttpHeaders, HttpResponse, } from '@angular/common/http'; import { Observable, Subject } from 'rxjs'; import { Http } from '../../utils/http'; import { ODataApi } from '../../api'; import { ODataOptions } from './options'; import { ODataPathSegments } from '../path-segments'; import { ODataRequest } from '../request'; import { ODataResource } from '../resource'; import { ODataResponse } from '../responses'; import { PathSegmentNames } from '../../types'; import { Strings } from '../../utils/strings'; export class ODataBatchRequest<T> extends Subject<ODataResponse<T>> { constructor(public request: ODataRequest<any>) { super(); } toString() { //TODO: Relative or Absolute url ? let res = [ `${this.request.method} ${this.request.pathWithParams} ${HTTP11}`, ]; if ( this.request.method === 'POST' || this.request.method === 'PATCH' || this.request.method === 'PUT' ) { res.push(`${CONTENT_TYPE}: ${APPLICATION_JSON}`); } if (this.request.headers instanceof HttpHeaders) { let headers = this.request.headers; res = [ ...res, ...headers .keys() .map((key) => `${key}: ${(headers.getAll(key) || []).join(',')}`), ]; } return res.join(NEWLINE); } onLoad(content: string[], status: { code: number; message: string }) { let headers: HttpHeaders = new HttpHeaders(); var index = 1; for (; index < content.length; index++) { const batchBodyLine: string = content[index]; if (batchBodyLine === '') { break; } const batchBodyLineParts: string[] = batchBodyLine.split(': '); headers = headers.append( batchBodyLineParts[0].trim(), batchBodyLineParts[1].trim() ); } let body: string | { error: any; text: string } = ''; for (; index < content.length; index++) { body += content[index]; } if (status.code === 0) { status.code = !!body ? 200 : 0; } let ok = status.code >= 200 && status.code < 300; if (this.request.responseType === 'json' && typeof body === 'string') { const originalBody = body; body = body.replace(XSSI_PREFIX, ''); try { body = body !== '' ? JSON.parse(body) : null; } catch (error) { body = originalBody; if (ok) { ok = false; body = { error, text: body }; } } } if (ok) { let res = new HttpResponse<any>({ body, headers, status: status.code, statusText: status.message, url: this.request.urlWithParams, }); this.next(ODataResponse.fromHttpResponse(this.request, res)); this.complete(); } else { // An unsuccessful request is delivered on the error channel. this.error( new HttpErrorResponse({ // The error in this case is the response body (error from the server). error: body, headers, status: status.code, statusText: status.message, url: this.request.urlWithParams, }) ); } } onError(content: string[], status: { code: number; text: string }) { const res = new HttpErrorResponse({ error: content.join(NEWLINE), status: status.code || 0, statusText: status.text || 'Unknown Error', url: this.request.urlWithParams || undefined, }); this.error(res); } } /** * OData Batch Resource * https://www.odata.org/getting-started/advanced-tutorial/#batch */ export class ODataBatchResource extends ODataResource<any> { // VARIABLES private _requests: ODataBatchRequest<any>[] = []; requests() { return this._requests.map((r) => r.request); } clone() { return new ODataBatchResource(this.api, this.cloneSegments()); } schema() { return undefined; } //#region Factory static factory(api: ODataApi) { let segments = new ODataPathSegments(); segments.add(PathSegmentNames.batch, $BATCH); return new ODataBatchResource(api, segments); } //#endregion /** * Execute the batch request * @param ctx The context for the request * @param options The options of the batch request * @returns The result of execute the context */ exec<R>( ctx: (batch: this) => Observable<R>, options?: ODataOptions ): Observable<R> { // Store original requester const current = this.api.request; // Switch to the batch requester this.api.request = (req: ODataRequest<any>): Observable<any> => { if (req.api !== this.api) throw new Error('Batch Request are for the same api.'); if (req.observe === 'events') throw new Error("Batch Request does not allows observe == 'events'."); this._requests.push(new ODataBatchRequest<any>(req)); return this._requests[this._requests.length - 1]; }; // Execute the context const obs$ = ctx(this); // Restore original requester this.api.request = current; if (this._requests.length >= 0) { const bound = Strings.uniqueId(BATCH_PREFIX); const requests = this._requests; const headers = Http.mergeHttpHeaders( (options && options.headers) || {}, { [ODATA_VERSION]: VERSION_4_0, [CONTENT_TYPE]: MULTIPART_MIXED_BOUNDARY + bound, [ACCEPT]: MULTIPART_MIXED, } ); const request = new ODataRequest({ method: 'POST', body: ODataBatchResource.buildBody(bound, requests), api: this.api, resource: this, observe: 'response', responseType: 'text', headers: headers, params: options ? options.params : undefined, withCredentials: options ? options.withCredentials : undefined, }); this.api.request(request).subscribe((response) => { ODataBatchResource.handleResponse(requests, response); }); } return obs$; } body() { return ODataBatchResource.buildBody( Strings.uniqueId(BATCH_PREFIX), this._requests ); } static buildBody( batchBoundary: string, requests: ODataBatchRequest<any>[] ): string { let res = []; let changesetBoundary: string | null = null; let changesetId = 1; for (const batch of requests) { // if method is GET and there is a changeset boundary open then close it if (batch.request.method === 'GET' && changesetBoundary !== null) { res.push( `${BOUNDARY_PREFIX_SUFFIX}${changesetBoundary}${BOUNDARY_PREFIX_SUFFIX}` ); changesetBoundary = null; } // if there is no changeset boundary open then open a batch boundary if (changesetBoundary === null) { res.push(`${BOUNDARY_PREFIX_SUFFIX}${batchBoundary}`); } // if method is not GET and there is no changeset boundary open then open a changeset boundary if (batch.request.method !== 'GET') { if (changesetBoundary === null) { changesetBoundary = Strings.uniqueId(CHANGESET_PREFIX); res.push( `${CONTENT_TYPE}: ${MULTIPART_MIXED_BOUNDARY}${changesetBoundary}` ); res.push(NEWLINE); } res.push(`${BOUNDARY_PREFIX_SUFFIX}${changesetBoundary}`); } res.push(`${CONTENT_TYPE}: ${APPLICATION_HTTP}`); res.push(`${CONTENT_TRANSFER_ENCODING}: ${BINARY}`); if (batch.request.method !== 'GET') { res.push(`${CONTENT_ID}: ${changesetId++}`); } res.push(NEWLINE); res.push(`${batch}`); if (batch.request.method === 'GET' || batch.request.method === 'DELETE') { res.push(NEWLINE); } else { res.push(`${NEWLINE}${JSON.stringify(batch.request.body)}`); } } if (res.length) { if (changesetBoundary !== null) { res.push( `${BOUNDARY_PREFIX_SUFFIX}${changesetBoundary}${BOUNDARY_PREFIX_SUFFIX}` ); changesetBoundary = null; } res.push( `${BOUNDARY_PREFIX_SUFFIX}${batchBoundary}${BOUNDARY_PREFIX_SUFFIX}` ); } return res.join(NEWLINE); } static handleResponse( requests: ODataBatchRequest<any>[], response: ODataResponse<any> ) { let chunks: string[][] = []; const contentType: string = response.headers.get(CONTENT_TYPE) || ''; const batchBoundary: string = Http.boundaryDelimiter(contentType); const endLine: string = Http.boundaryEnd(batchBoundary); const lines: string[] = response.body.split(NEWLINE_REGEXP); let changesetResponses: string[][] | null = null; let contentId: number | null = null; let changesetBoundary: string | null = null; let changesetEndLine: string | null = null; let startIndex: number | null = null; for (let index = 0; index < lines.length; index++) { const line = lines[index]; if (line.startsWith(CONTENT_TYPE)) { const contentTypeValue: string = Http.headerValue(line); if (contentTypeValue === MULTIPART_MIXED) { changesetResponses = []; contentId = null; changesetBoundary = Http.boundaryDelimiter(line); changesetEndLine = Http.boundaryEnd(changesetBoundary); startIndex = null; } continue; } else if (changesetResponses !== null && line.startsWith(CONTENT_ID)) { contentId = Number(Http.headerValue(line)); } else if (line.startsWith(HTTP11)) { startIndex = index; } else if ( line === batchBoundary || line === changesetBoundary || line === endLine || line === changesetEndLine ) { if (!startIndex) { continue; } const chunk = lines.slice(startIndex, index); if (changesetResponses !== null && contentId !== null) { changesetResponses[contentId] = chunk; } else { chunks.push(chunk); } if (line === batchBoundary || line === changesetBoundary) { startIndex = index + 1; } else if (line === endLine || line === changesetEndLine) { if (changesetResponses !== null) { for (const response of changesetResponses) { if (response) { chunks.push(response); } } } changesetResponses = null; changesetBoundary = null; changesetEndLine = null; startIndex = null; } } } chunks.forEach((chunk, index) => { const req = requests[index]; const { status, code, message } = Http.parseResponseStatus(chunk[0]); req.onLoad(chunk.slice(1), { code, message }); }); } }
the_stack
* @module Tree */ import { Observable } from "rxjs/internal/Observable"; import { concat } from "rxjs/internal/observable/concat"; import { defer } from "rxjs/internal/observable/defer"; import { EMPTY } from "rxjs/internal/observable/empty"; import { from } from "rxjs/internal/observable/from"; import { merge } from "rxjs/internal/observable/merge"; import { of } from "rxjs/internal/observable/of"; import { concatAll } from "rxjs/internal/operators/concatAll"; import { concatMap } from "rxjs/internal/operators/concatMap"; import { distinctUntilChanged } from "rxjs/internal/operators/distinctUntilChanged"; import { finalize } from "rxjs/internal/operators/finalize"; import { map } from "rxjs/internal/operators/map"; import { mergeAll } from "rxjs/internal/operators/mergeAll"; import { publishReplay } from "rxjs/internal/operators/publishReplay"; import { refCount } from "rxjs/internal/operators/refCount"; import { subscribeOn } from "rxjs/internal/operators/subscribeOn"; import { toArray } from "rxjs/internal/operators/toArray"; import { asapScheduler } from "rxjs/internal/scheduler/asap"; import { CheckBoxState } from "@itwin/core-react"; import { SelectionMode } from "../../common/selection/SelectionModes"; import { TreeNodeItem } from "../TreeDataProvider"; import { IndividualSelection, isRangeSelection, RangeSelection, TreeSelectionManager } from "./internal/TreeSelectionManager"; import { TreeActions } from "./TreeActions"; import { TreeEvents } from "./TreeEvents"; import { isTreeModelNode, TreeModelNode, TreeModelNodePlaceholder, VisibleTreeNodes } from "./TreeModel"; import { ITreeNodeLoader } from "./TreeNodeLoader"; /** * Default event dispatcher that emits tree events according performed actions. * It converts low level tree events into TreeEvents. * @internal */ export class TreeEventDispatcher implements TreeActions { private _treeEvents: TreeEvents; private _nodeLoader: ITreeNodeLoader; private _getVisibleNodes: (() => VisibleTreeNodes) | undefined; private _selectionManager: TreeSelectionManager; private _activeSelections = new Set<Observable<{ selectedNodeItems: TreeNodeItem[], deselectedNodeItems?: TreeNodeItem[] }>>(); constructor( treeEvents: TreeEvents, nodeLoader: ITreeNodeLoader, selectionMode: SelectionMode, getVisibleNodes?: () => VisibleTreeNodes, ) { this._treeEvents = treeEvents; this._nodeLoader = nodeLoader; this._getVisibleNodes = getVisibleNodes; this._selectionManager = new TreeSelectionManager(selectionMode, this._getVisibleNodes); this._selectionManager.onDragSelection.addListener(({ selectionChanges }) => { const modifications = from(selectionChanges) .pipe( map(({ selectedNodes, deselectedNodes }) => from(this.collectSelectionChanges(selectedNodes, [])) .pipe( concatMap(({ selectedNodeItems }) => from(selectedNodeItems)), toArray(), map((collectedIds) => ({ selectedNodeItems: collectedIds, deselectedNodeItems: this.collectNodeItems(deselectedNodes) })), ), ), concatAll(), publishReplay(), refCount(), ); /* istanbul ignore else */ if (this._treeEvents.onSelectionModified !== undefined) this._treeEvents.onSelectionModified({ modifications }); }); this._selectionManager.onSelectionChanged.addListener(({ selectedNodes, deselectedNodes }) => { const modifications = merge( defer(() => { this._activeSelections.add(modifications); return EMPTY; }), this.collectSelectionChanges(selectedNodes, deselectedNodes), ) .pipe( finalize(() => { this._activeSelections.delete(modifications); }), publishReplay(), refCount(), ); /* istanbul ignore else */ if (this._treeEvents.onSelectionModified !== undefined) this._treeEvents.onSelectionModified({ modifications }); }); this._selectionManager.onSelectionReplaced.addListener(({ selectedNodeIds }) => { const replacements = merge( defer(() => { this._activeSelections.add(replacements); return EMPTY; }), this.collectSelectionChanges(selectedNodeIds, []), ) .pipe( finalize(() => { this._activeSelections.delete(replacements); }), publishReplay(), refCount(), ); /* istanbul ignore else */ if (this._treeEvents.onSelectionReplaced !== undefined) this._treeEvents.onSelectionReplaced({ replacements }); }); } public setVisibleNodes(visibleNodes: () => VisibleTreeNodes) { this._getVisibleNodes = visibleNodes; this._selectionManager.setVisibleNodes(visibleNodes); } public onNodeCheckboxClicked(nodeId: string, newState: CheckBoxState) { if (this._getVisibleNodes === undefined) return; const visibleNodes = this._getVisibleNodes(); const clickedNode = visibleNodes.getModel().getNode(nodeId); if (clickedNode === undefined) return; const immediateStateChanges = [{ nodeItem: clickedNode.item, newState }]; if (clickedNode.isSelected) { for (const node of visibleNodes) { if (isTreeModelNode(node) && node.id !== clickedNode.id && node.isSelected && node.checkbox.state !== newState) { immediateStateChanges.push({ nodeItem: node.item, newState }); } } } const stateChanges = concat( of(immediateStateChanges), from(this._activeSelections) .pipe( mergeAll(), map(({ selectedNodeItems }) => selectedNodeItems.map((item) => ({ nodeItem: item, newState }))), ), ) .pipe( publishReplay(), refCount(), ); /* istanbul ignore else */ if (this._treeEvents.onCheckboxStateChanged !== undefined) this._treeEvents.onCheckboxStateChanged({ stateChanges }); } public onNodeExpanded(nodeId: string) { /* istanbul ignore else */ if (this._treeEvents.onNodeExpanded !== undefined) this._treeEvents.onNodeExpanded({ nodeId }); } public onNodeCollapsed(nodeId: string) { /* istanbul ignore else */ if (this._treeEvents.onNodeCollapsed !== undefined) this._treeEvents.onNodeCollapsed({ nodeId }); } public onNodeClicked(nodeId: string, event: React.MouseEvent<Element, MouseEvent>) { const node = this._getVisibleNodes ? this._getVisibleNodes().getModel().getNode(nodeId) : undefined; const isNodeSelected = node ? node.isSelected : false; this._selectionManager.onNodeClicked(nodeId, event); // if clicked node was already selected fire delayed click event if (isNodeSelected && this._treeEvents.onDelayedNodeClick !== undefined) { this._treeEvents.onDelayedNodeClick({ nodeId }); } } public onNodeMouseDown(nodeId: string) { this._selectionManager.onNodeMouseDown(nodeId); } public onNodeMouseMove(nodeId: string) { this._selectionManager.onNodeMouseMove(nodeId); } public onNodeEditorActivated(nodeId: string) { const node = this._getVisibleNodes ? this._getVisibleNodes().getModel().getNode(nodeId) : /* istanbul ignore next */ undefined; const isNodeSelected = node ? node.isSelected : false; // if node was already selected, fire onNodeEditorActivated event if (isNodeSelected && this._treeEvents.onNodeEditorActivated !== undefined) { this._treeEvents.onNodeEditorActivated({ nodeId }); } } public onTreeKeyDown(event: React.KeyboardEvent): void { this._selectionManager.onTreeKeyDown(event, this); } public onTreeKeyUp(event: React.KeyboardEvent): void { this._selectionManager.onTreeKeyUp(event, this); } private collectSelectionChanges( selection: IndividualSelection | RangeSelection, deselection: IndividualSelection, ): Observable<{ selectedNodeItems: TreeNodeItem[], deselectedNodeItems: TreeNodeItem[] }> { const deselectedItems = this.collectNodeItems(deselection); if (isRangeSelection(selection)) { let firstEmission = true; return this.collectNodesBetween(selection.from, selection.to) .pipe( map((selectedNodeItems) => { if (firstEmission) { firstEmission = false; return { selectedNodeItems, deselectedNodeItems: deselectedItems }; } return { selectedNodeItems, deselectedNodeItems: [] }; }), ); } const selectedItems = this.collectNodeItems(selection); return of({ selectedNodeItems: selectedItems, deselectedNodeItems: deselectedItems }); } private collectNodesBetween(nodeId1: string, nodeId2: string): Observable<TreeNodeItem[]> { const [readyNodes, nodesToLoad] = TreeEventDispatcher.groupNodesByLoadingState( this.iterateNodesBetween(nodeId1, nodeId2), ); const loadedSelectedNodes = from( nodesToLoad.map((node) => { const parentNode = node.parentId ? this._getVisibleNodes!().getModel().getNode(node.parentId) : this._getVisibleNodes!().getModel().getRootNode(); return parentNode ? this._nodeLoader.loadNode(parentNode, node.childIndex) : /* istanbul ignore next */ EMPTY; }), ) .pipe( // We have requested multiple nodes that may belong to the same page. // When the page loads we only want to process the loaded nodes once. // Making assumption that loaded nodes from the same page will be emitted without interruptions. // Maybe we could simplify this to `this._nodeLoader.loadNodes(nodesToLoad)`? mergeAll(), distinctUntilChanged(), map((loadResult) => loadResult.loadedNodes), ); return concat(of(readyNodes), loadedSelectedNodes) .pipe( // Give enough time for multiple subscribers to subscribe before any emissions begin subscribeOn(asapScheduler), ); } private *iterateNodesBetween( nodeId1: string, nodeId2: string, ): Iterable<TreeModelNode | TreeModelNodePlaceholder> { let firstNodeFound = false; if (this._getVisibleNodes === undefined) { return; } for (const node of this._getVisibleNodes()) { if (firstNodeFound) { yield node; } if (isTreeModelNode(node)) { if (nodeId1 === nodeId2 && node.id === nodeId1) { yield node; return; } if (node.id === nodeId1 || node.id === nodeId2) { if (firstNodeFound) { return; } firstNodeFound = true; yield node; } } } } private collectNodeItems(nodeIds: string[]): TreeNodeItem[] { const items: TreeNodeItem[] = []; if (this._getVisibleNodes === undefined) return items; for (const nodeId of nodeIds) { const node = this._getVisibleNodes().getModel().getNode(nodeId); // istanbul ignore else if (node !== undefined) items.push(node.item); } return items; } private static groupNodesByLoadingState( nodes: Iterable<TreeModelNode | TreeModelNodePlaceholder>, ): [TreeNodeItem[], TreeModelNodePlaceholder[]] { const loadedNodeItems: TreeNodeItem[] = []; const nodesToLoad: TreeModelNodePlaceholder[] = []; for (const node of nodes) { if (isTreeModelNode(node)) { loadedNodeItems.push(node.item); } else { nodesToLoad.push(node); } } return [loadedNodeItems, nodesToLoad]; } }
the_stack
import * as _ from 'lodash'; import {checkThat, isSimpleAllocation} from '../utils'; import {BN} from '../bignumber'; import {calculateChannelId, hashState, signState} from '../state-utils'; import {Address, SignatureEntry, SignedState, State, Uint256} from '../types'; import {BaseObjective, BaseObjectiveEvent} from './objective'; // TODO: This ought to be configurable export const MAX_WAITING_TIME = 5_000; export type OpenChannelEvent = BaseObjectiveEvent & ( | {type: 'Crank'} // Allows you to crank it every now and then to see if it's timed out. | {type: 'StatesReceived'; states: SignedState[]} | {type: 'FundingUpdated'; amount: Uint256; finalized: boolean} | {type: 'DepositSubmitted'; tx: string; attempt: number; submittedAt: number} | {type: 'Approval'} ); export type SignedStateHash = {hash: string; signatures: SignatureEntry[]}; export enum WaitingFor { approval = 'DirectFunder.approval', theirPreFundSetup = 'DirectFunder.theirPreFundSetup', safeToDeposit = 'DirectFunder.safeToDeposit', channelFunded = 'DirectFunder.channelFunded', theirPostFundState = 'DirectFunder.theirPostFundSetup' } const enum Steps { preFundSetup = 'preFundSetup', postFundSetup = 'postFundSetup' } export type OpenChannelObjective = BaseObjective & { status: WaitingFor | 'success' | 'error'; approved: boolean; channelId: string; openingState: State; myIndex: number; preFundSetup: SignedStateHash; // TODO: (ChainService) The asset class is _ignored_ here. funding: {amount: Uint256; finalized: boolean}; fundingRequest: {tx: string; attempts: number; submittedAt: number} | undefined; postFundSetup: SignedStateHash; }; export function initialize( openingState: State | SignedState, myIndex: number, approved = false ): OpenChannelObjective { if (openingState.turnNum !== 0) { throw new Error(`Unexpected state due to turnNum ${openingState.turnNum}`); } const allowedIndices = _.range(0, openingState.participants.length); if (!allowedIndices.includes(myIndex)) { throw new Error(`Unexpected index due to index ${myIndex}`); } // HACK (Implicitly) check that the outcome is as expected utils.fundingMilestone(openingState, openingState.participants[myIndex].destination); const signatures = 'signatures' in openingState ? mergeSignatures([], openingState.signatures) : []; return { type: 'OpenChannel', approved, channelId: calculateChannelId(openingState), myIndex, openingState: _.omit(openingState, 'signatures'), status: approved ? WaitingFor.theirPreFundSetup : WaitingFor.approval, preFundSetup: {hash: hashState(setupState(openingState, Steps.preFundSetup)), signatures}, funding: {amount: BN.from(0), finalized: true}, fundingRequest: undefined, postFundSetup: {hash: hashState(setupState(openingState, Steps.postFundSetup)), signatures: []} }; } export type Action = | {type: 'sendStates'; states: SignedState[]} // TODO: (ChainService) We will need to include more data once this gets hooked up to a chain service | {type: 'deposit'; amount: Uint256} | {type: 'handleError'; error: Error}; export type OpenChannelResult = { objective: OpenChannelObjective; actions: Action[]; }; /** * * @param objective: A rich OpenChannelObjective data structure storing relevant data to the objective * @param event an OpenChannelEvent that can trigger a state transition + actions * @param myPrivateKey * @returns OpenChannelResult, a data structure containing * - the current state of the objective * - actionst to be triggered by an imperative shell * * This is a state machine implementation of a protocol for opening a directly funded channel. * It operates on a "rich" OpenChannelObjective state, which stores: * 1. the channel's initial state * 2. the hash of the expected preFS and its hash * 3. the on-chain funding of the channel * 4. funding requests * 5. the hash of the expected preFS and its hash * * The machine receives either messages or chain events. * It _whitelists_ states, rejecting any state other than the expected state. * * A wallet implementation can then use the result with this sequence of asynchronous operations * 1. record the new objective state as well as the resulting actions * 2. trigger the resulting actions asynchronously * 3. mark the actions as being successful * * If the wallet crashes after 1 & before 3, the wallet can decide to re-trigger * the actions on a case-by-case basis, based on whether the action is safe to * re-trigger. * * ## ASSUMPTIONS ## * - the opening state has a SimpleAllocation outcome * - the outcome has exactly one destination per participant */ export function openChannelCranker( currentObjectiveState: OpenChannelObjective, event: OpenChannelEvent, myPrivateKey: string ): OpenChannelResult { const objective = _.cloneDeep(currentObjectiveState); const actions: Action[] = []; const {participants} = objective.openingState; const me = participants[objective.myIndex]; // First, process the event switch (event.type) { case 'Crank': break; case 'Approval': objective.approved = true; break; case 'DepositSubmitted': objective.fundingRequest = { tx: event.tx, submittedAt: event.submittedAt, attempts: event.attempt }; break; case 'FundingUpdated': objective.funding.amount = event.amount; objective.funding.finalized = event.finalized; break; case 'StatesReceived': { const {states: signedStates} = event; // TODO: Assume there's only one signed state if (signedStates && signedStates[0]) { const signedState = signedStates[0]; const hash = hashState(signedState); const {signatures} = signedState; for (const signature of signatures) { if (!participants.find(p => p.signingAddress === signature.signer)) { objective.status = 'error'; const error = new DirectFunderError({ message: 'NonParticipantSignature', signature }); actions.push({type: 'handleError', error}); return {objective, actions}; } } if (hash === objective.preFundSetup.hash) { objective.preFundSetup.signatures = mergeSignatures( objective.preFundSetup.signatures, signatures ); } else if (hash === objective.postFundSetup.hash) { objective.postFundSetup.signatures = mergeSignatures( objective.postFundSetup.signatures, signatures ); } else { objective.status = 'error'; const error = new DirectFunderError({ message: 'ReceivedUnexpectedState', received: hash, expected: [objective.preFundSetup.hash, objective.postFundSetup.hash] }); actions.push({type: 'handleError', error}); return {objective, actions}; } } break; } default: return handleUnexpectedEvent(event, objective); } // Then, transition & collect actions: if (!objective.approved) { objective.status = WaitingFor.approval; return {objective, actions}; } if (!signedbyMe(objective, Steps.preFundSetup, me.signingAddress)) { signStateAction(Steps.preFundSetup, myPrivateKey, objective, actions); } if (!completed(objective, Steps.preFundSetup)) { objective.status = WaitingFor.theirPreFundSetup; return {objective, actions}; } // Mostly copied from server-wallet/src/protocols/direct-funder const {funding} = objective; const {targetBefore, targetAfter, targetTotal} = utils.fundingMilestone( objective.openingState, me.destination ); // if we're fully funded, we're done if (BN.gte(funding.amount, targetTotal) && funding.finalized) { // This is the only path where the channel is directly funded, // so we move onto postFS // The rest of the paths should **return**. } // if it isn't my turn yet, take no action else if (BN.lt(funding.amount, targetBefore)) { objective.status = WaitingFor.safeToDeposit; return {objective, actions}; } // if my deposit is already on chain, take no action else if (BN.gte(funding.amount, targetAfter)) { objective.status = WaitingFor.channelFunded; return {objective, actions}; } // if there's an outstanding chain request, take no action // TODO: (ChainService) This assumes that each participant deposits exactly once per channel else if (objective.fundingRequest) { if (event.now && event.now >= objective.fundingRequest.submittedAt + MAX_WAITING_TIME) { objective.status = 'error'; const error = new DirectFunderError({ message: 'TimedOutWhileFunding', now: event.now, submittedAt: objective.fundingRequest.submittedAt }); actions.push({type: 'handleError', error}); return {objective, actions}; } else { objective.status = WaitingFor.channelFunded; return {objective, actions}; } } else { // otherwise, deposit const amount = BN.sub(targetAfter, funding.amount); // previous checks imply this is >0 actions.push({type: 'deposit', amount}); objective.status = WaitingFor.channelFunded; return {objective, actions}; } // Now that the channel is funded, it's safe to sign the postFS if (!signedbyMe(objective, Steps.postFundSetup, me.signingAddress)) { signStateAction(Steps.postFundSetup, myPrivateKey, objective, actions); } if (!completed(objective, Steps.postFundSetup)) { objective.status = WaitingFor.theirPostFundState; return {objective, actions}; } else { objective.status = 'success'; return {objective, actions}; } } function signedbyMe(objective: OpenChannelObjective, step: Steps, me: Address): boolean { return objective[step].signatures.map(e => e.signer).includes(me); } function completed(objective: OpenChannelObjective, step: Steps): boolean { const {openingState: firstState} = objective; return objective[step].signatures.length === firstState.participants.length; } function setupState(openingState: State, step: Steps): State { const turnNum = step === Steps.preFundSetup ? 0 : 2 * openingState.participants.length - 1; return {...openingState, turnNum}; } function signStateAction( step: Steps, myPrivateKey: string, objective: OpenChannelObjective, actions: Action[] ): Action[] { const {openingState, myIndex} = objective; const me = openingState.participants[myIndex]; const state = setupState(openingState, step); const signature = signState(state, myPrivateKey); const entry = {signature, signer: me.signingAddress}; objective[step].signatures = mergeSignatures(objective[step].signatures, [entry]); const signedState = {...state, signatures: [entry]}; const existingAction = actions.find(a => a.type === 'sendStates'); if (existingAction) { (existingAction as any).states.push(signedState); } else { actions.push({type: 'sendStates', states: [{...state, signatures: [entry]}]}); } return actions; } function mergeSignatures(left: SignatureEntry[], right: SignatureEntry[]): SignatureEntry[] { // TODO: Perhaps this should place signatures according to the participant's index? const unsorted = _.uniqBy(_.concat(left, right), entry => entry.signer); return _.sortBy(unsorted, entry => entry.signer); } type FundingMilestone = { targetBefore: Uint256; targetAfter: Uint256; targetTotal: Uint256; }; export const utils = { fundingMilestone(state: State, destination: string): FundingMilestone { const {allocationItems} = checkThat(state.outcome, isSimpleAllocation); const myAllocationItem = _.find(allocationItems, ai => ai.destination === destination); if (!myAllocationItem) { // throw new ChannelError(ChannelError.reasons.destinationNotInAllocations, { // destination: this.participants[this.myIndex].destination // }); throw new Error('unexpected outcome'); } const allocationsBefore = _.takeWhile(allocationItems, a => a.destination !== destination); const targetBefore = allocationsBefore.map(a => a.amount).reduce(BN.add, BN.from(0)); const targetAfter = BN.add(targetBefore, myAllocationItem.amount); const targetTotal = allocationItems.map(a => a.amount).reduce(BN.add, BN.from(0)); return {targetBefore, targetAfter, targetTotal}; } }; export type ErrorModes = | {message: 'NonParticipantSignature'; signature: SignatureEntry} | {message: 'ReceivedUnexpectedState'; received: string; expected: [string, string]} | {message: 'TimedOutWhileFunding'; now: number; submittedAt: number} | {message: 'UnexpectedEvent'; event: any}; class DirectFunderError extends Error { constructor(public data: ErrorModes) { super(data.message); } } /** * In principle, one can send any event to the cranker. * We handle this by moving to an error state with an "UnexpectedEvent" error, * to avoid throwing a generic error. * * By extracting this in a function where event has type `never`, this forces the * developer to handle all _known_ event types before returning the output of * handleUnexpectedEvent * * @param event unsafe event sent to the cranker * @param objective current objective state * @returns objective moved to error state * */ function handleUnexpectedEvent(event: never, objective: OpenChannelObjective): OpenChannelResult { const error = new DirectFunderError({event, message: 'UnexpectedEvent'}); objective.status = 'error'; return {objective, actions: [{type: 'handleError', error}]}; }
the_stack
import type { VirtualHost as _envoy_config_route_v3_VirtualHost, VirtualHost__Output as _envoy_config_route_v3_VirtualHost__Output } from '../../../../envoy/config/route/v3/VirtualHost'; import type { HeaderValueOption as _envoy_config_core_v3_HeaderValueOption, HeaderValueOption__Output as _envoy_config_core_v3_HeaderValueOption__Output } from '../../../../envoy/config/core/v3/HeaderValueOption'; import type { BoolValue as _google_protobuf_BoolValue, BoolValue__Output as _google_protobuf_BoolValue__Output } from '../../../../google/protobuf/BoolValue'; import type { Vhds as _envoy_config_route_v3_Vhds, Vhds__Output as _envoy_config_route_v3_Vhds__Output } from '../../../../envoy/config/route/v3/Vhds'; import type { UInt32Value as _google_protobuf_UInt32Value, UInt32Value__Output as _google_protobuf_UInt32Value__Output } from '../../../../google/protobuf/UInt32Value'; /** * [#next-free-field: 12] */ export interface RouteConfiguration { /** * The name of the route configuration. For example, it might match * :ref:`route_config_name * <envoy_api_field_extensions.filters.network.http_connection_manager.v3.Rds.route_config_name>` in * :ref:`envoy_api_msg_extensions.filters.network.http_connection_manager.v3.Rds`. */ 'name'?: (string); /** * An array of virtual hosts that make up the route table. */ 'virtual_hosts'?: (_envoy_config_route_v3_VirtualHost)[]; /** * Optionally specifies a list of HTTP headers that the connection manager * will consider to be internal only. If they are found on external requests they will be cleaned * prior to filter invocation. See :ref:`config_http_conn_man_headers_x-envoy-internal` for more * information. */ 'internal_only_headers'?: (string)[]; /** * Specifies a list of HTTP headers that should be added to each response that * the connection manager encodes. Headers specified at this level are applied * after headers from any enclosed :ref:`envoy_api_msg_config.route.v3.VirtualHost` or * :ref:`envoy_api_msg_config.route.v3.RouteAction`. For more information, including details on * header value syntax, see the documentation on :ref:`custom request headers * <config_http_conn_man_headers_custom_request_headers>`. */ 'response_headers_to_add'?: (_envoy_config_core_v3_HeaderValueOption)[]; /** * Specifies a list of HTTP headers that should be removed from each response * that the connection manager encodes. */ 'response_headers_to_remove'?: (string)[]; /** * Specifies a list of HTTP headers that should be added to each request * routed by the HTTP connection manager. Headers specified at this level are * applied after headers from any enclosed :ref:`envoy_api_msg_config.route.v3.VirtualHost` or * :ref:`envoy_api_msg_config.route.v3.RouteAction`. For more information, including details on * header value syntax, see the documentation on :ref:`custom request headers * <config_http_conn_man_headers_custom_request_headers>`. */ 'request_headers_to_add'?: (_envoy_config_core_v3_HeaderValueOption)[]; /** * An optional boolean that specifies whether the clusters that the route * table refers to will be validated by the cluster manager. If set to true * and a route refers to a non-existent cluster, the route table will not * load. If set to false and a route refers to a non-existent cluster, the * route table will load and the router filter will return a 404 if the route * is selected at runtime. This setting defaults to true if the route table * is statically defined via the :ref:`route_config * <envoy_api_field_extensions.filters.network.http_connection_manager.v3.HttpConnectionManager.route_config>` * option. This setting default to false if the route table is loaded dynamically via the * :ref:`rds * <envoy_api_field_extensions.filters.network.http_connection_manager.v3.HttpConnectionManager.rds>` * option. Users may wish to override the default behavior in certain cases (for example when * using CDS with a static route table). */ 'validate_clusters'?: (_google_protobuf_BoolValue | null); /** * Specifies a list of HTTP headers that should be removed from each request * routed by the HTTP connection manager. */ 'request_headers_to_remove'?: (string)[]; /** * An array of virtual hosts will be dynamically loaded via the VHDS API. * Both *virtual_hosts* and *vhds* fields will be used when present. *virtual_hosts* can be used * for a base routing table or for infrequently changing virtual hosts. *vhds* is used for * on-demand discovery of virtual hosts. The contents of these two fields will be merged to * generate a routing table for a given RouteConfiguration, with *vhds* derived configuration * taking precedence. */ 'vhds'?: (_envoy_config_route_v3_Vhds | null); /** * By default, headers that should be added/removed are evaluated from most to least specific: * * * route level * * virtual host level * * connection manager level * * To allow setting overrides at the route or virtual host level, this order can be reversed * by setting this option to true. Defaults to false. * * [#next-major-version: In the v3 API, this will default to true.] */ 'most_specific_header_mutations_wins'?: (boolean); /** * The maximum bytes of the response :ref:`direct response body * <envoy_api_field_config.route.v3.DirectResponseAction.body>` size. If not specified the default * is 4096. * * .. warning:: * * Envoy currently holds the content of :ref:`direct response body * <envoy_api_field_config.route.v3.DirectResponseAction.body>` in memory. Be careful setting * this to be larger than the default 4KB, since the allocated memory for direct response body * is not subject to data plane buffering controls. */ 'max_direct_response_body_size_bytes'?: (_google_protobuf_UInt32Value | null); } /** * [#next-free-field: 12] */ export interface RouteConfiguration__Output { /** * The name of the route configuration. For example, it might match * :ref:`route_config_name * <envoy_api_field_extensions.filters.network.http_connection_manager.v3.Rds.route_config_name>` in * :ref:`envoy_api_msg_extensions.filters.network.http_connection_manager.v3.Rds`. */ 'name': (string); /** * An array of virtual hosts that make up the route table. */ 'virtual_hosts': (_envoy_config_route_v3_VirtualHost__Output)[]; /** * Optionally specifies a list of HTTP headers that the connection manager * will consider to be internal only. If they are found on external requests they will be cleaned * prior to filter invocation. See :ref:`config_http_conn_man_headers_x-envoy-internal` for more * information. */ 'internal_only_headers': (string)[]; /** * Specifies a list of HTTP headers that should be added to each response that * the connection manager encodes. Headers specified at this level are applied * after headers from any enclosed :ref:`envoy_api_msg_config.route.v3.VirtualHost` or * :ref:`envoy_api_msg_config.route.v3.RouteAction`. For more information, including details on * header value syntax, see the documentation on :ref:`custom request headers * <config_http_conn_man_headers_custom_request_headers>`. */ 'response_headers_to_add': (_envoy_config_core_v3_HeaderValueOption__Output)[]; /** * Specifies a list of HTTP headers that should be removed from each response * that the connection manager encodes. */ 'response_headers_to_remove': (string)[]; /** * Specifies a list of HTTP headers that should be added to each request * routed by the HTTP connection manager. Headers specified at this level are * applied after headers from any enclosed :ref:`envoy_api_msg_config.route.v3.VirtualHost` or * :ref:`envoy_api_msg_config.route.v3.RouteAction`. For more information, including details on * header value syntax, see the documentation on :ref:`custom request headers * <config_http_conn_man_headers_custom_request_headers>`. */ 'request_headers_to_add': (_envoy_config_core_v3_HeaderValueOption__Output)[]; /** * An optional boolean that specifies whether the clusters that the route * table refers to will be validated by the cluster manager. If set to true * and a route refers to a non-existent cluster, the route table will not * load. If set to false and a route refers to a non-existent cluster, the * route table will load and the router filter will return a 404 if the route * is selected at runtime. This setting defaults to true if the route table * is statically defined via the :ref:`route_config * <envoy_api_field_extensions.filters.network.http_connection_manager.v3.HttpConnectionManager.route_config>` * option. This setting default to false if the route table is loaded dynamically via the * :ref:`rds * <envoy_api_field_extensions.filters.network.http_connection_manager.v3.HttpConnectionManager.rds>` * option. Users may wish to override the default behavior in certain cases (for example when * using CDS with a static route table). */ 'validate_clusters': (_google_protobuf_BoolValue__Output | null); /** * Specifies a list of HTTP headers that should be removed from each request * routed by the HTTP connection manager. */ 'request_headers_to_remove': (string)[]; /** * An array of virtual hosts will be dynamically loaded via the VHDS API. * Both *virtual_hosts* and *vhds* fields will be used when present. *virtual_hosts* can be used * for a base routing table or for infrequently changing virtual hosts. *vhds* is used for * on-demand discovery of virtual hosts. The contents of these two fields will be merged to * generate a routing table for a given RouteConfiguration, with *vhds* derived configuration * taking precedence. */ 'vhds': (_envoy_config_route_v3_Vhds__Output | null); /** * By default, headers that should be added/removed are evaluated from most to least specific: * * * route level * * virtual host level * * connection manager level * * To allow setting overrides at the route or virtual host level, this order can be reversed * by setting this option to true. Defaults to false. * * [#next-major-version: In the v3 API, this will default to true.] */ 'most_specific_header_mutations_wins': (boolean); /** * The maximum bytes of the response :ref:`direct response body * <envoy_api_field_config.route.v3.DirectResponseAction.body>` size. If not specified the default * is 4096. * * .. warning:: * * Envoy currently holds the content of :ref:`direct response body * <envoy_api_field_config.route.v3.DirectResponseAction.body>` in memory. Be careful setting * this to be larger than the default 4KB, since the allocated memory for direct response body * is not subject to data plane buffering controls. */ 'max_direct_response_body_size_bytes': (_google_protobuf_UInt32Value__Output | null); }
the_stack
* Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ import { AbstractClient } from "../../../common/abstract_client" import { ClientConfig } from "../../../common/interface" import { CreateVocabLibResponse, FaceIdentifyStatistic, DetailInfo, SubmitImageTaskPlusRequest, FacePoseResult, DeleteVocabLibRequest, DescribeAITaskResultRequest, ActionDurationStatistic, CreatePersonRequest, LightStatistic, DescribePersonsRequest, SubmitOneByOneClassTaskRequest, CreateVocabResponse, SubmitConversationTaskResponse, DescribeVocabLibRequest, ActionType, DescribePersonsResponse, HLFunction, CreateFaceRequest, DescribeImageTaskStatisticRequest, SubmitCheckAttendanceTaskPlusResponse, SubmitImageTaskRequest, WordTimePair, ModifyLibraryRequest, FaceInfo, LightDistributionStatistic, DeleteLibraryResponse, SubmitFullBodyClassTaskRequest, LightResult, DescribeAttendanceResultRequest, SubmitOpenClassTaskResponse, WholeTextItem, SubmitCheckAttendanceTaskPlusRequest, DescribeConversationTaskResponse, CreatePersonResponse, DescribeImageTaskRequest, HighlightsInfomation, TimeType, SubmitTraditionalClassTaskRequest, DeleteFaceResponse, SubmitDoubleVideoHighlightsRequest, ExpressRatioStatistic, TransmitAudioStreamResponse, DeletePersonRequest, DescribeLibrariesResponse, DeleteFaceRequest, DeleteLibraryRequest, DescribePersonResponse, StandardImageResult, DescribeVocabLibResponse, AttendanceInfo, SubmitCheckAttendanceTaskResponse, DeleteVocabResponse, CheckFacePhotoRequest, TeacherOutScreenResult, Word, DeleteVocabRequest, ActionInfo, FaceExpressionResult, StatInfo, ActionCountStatistic, GestureResult, CreateFaceResponse, BodyMovementResult, DescribeAITaskResultResponse, DescribeAudioTaskResponse, ActionDurationRatioStatistic, DescribePersonRequest, StandardVideoResult, ModifyLibraryResponse, TimeInfoResult, SubmitPartialBodyClassTaskResponse, ASRStat, TextItem, CancelTaskRequest, AllMuteSlice, DoubleVideoFunction, SubmitPartialBodyClassTaskRequest, DescribeHighlightResultResponse, SubmitOneByOneClassTaskResponse, LightStandard, SubmitHighlightsRequest, ModifyPersonResponse, PersonInfo, Face, Person, LightLevelRatioStatistic, DescribeVocabResponse, DescribeImageTaskStatisticResponse, SubmitCheckAttendanceTaskRequest, CancelTaskResponse, StudentBodyMovementResult, AbsenceInfo, ImageTaskFunction, FrameInfo, Library, SubmitConversationTaskRequest, SubmitHighlightsResponse, DeletePersonResponse, ImageTaskStatistic, SuspectedInfo, CheckFacePhotoResponse, ActionStatistic, DescribeHighlightResultRequest, DescribeVocabRequest, DeleteVocabLibResponse, ImageTaskResult, SubmitImageTaskPlusResponse, VocabStatInfomation, SubmitDoubleVideoHighlightsResponse, Function, DescribeAudioTaskRequest, DescribeAttendanceResultResponse, FaceExpressStatistic, AIAssistantRequest, DescribeLibrariesRequest, SubmitFullBodyClassTaskResponse, ModifyPersonRequest, DescribeImageTaskResponse, StandardAudioResult, HandTrackingResult, SubmitOpenClassTaskRequest, SubmitAudioTaskRequest, CreateVocabRequest, TransmitAudioStreamRequest, FaceAttrResult, SubmitTraditionalClassTaskResponse, AIAssistantResponse, SubmitImageTaskResponse, CreateVocabLibRequest, CreateLibraryResponse, FaceIdentifyResult, SubmitAudioTaskResponse, MuteSlice, DescribeConversationTaskRequest, VocabDetailInfomation, CreateLibraryRequest, FaceInfoResult, FaceDetectStatistic, } from "./tci_models" /** * tci client * @class */ export class Client extends AbstractClient { constructor(clientConfig: ClientConfig) { super("tci.tencentcloudapi.com", "2019-03-18", clientConfig) } /** * **提交线下小班(无课桌)课任务** 线下小班课是指有学生无课桌的课堂,满座15人以下,全局画面且背景不动,能清晰看到。 **提供的功能接口有:**学生人脸识别、学生表情识别、学生肢体动作识别。 可分析的指标维度包括:身份识别、正脸、侧脸、抬头、低头、高兴、中性、高兴、中性、惊讶、厌恶、恐惧、愤怒、蔑视、悲伤、站立、举手、坐着等。 **对场景的要求为:**真实常规教室,满座15人以下,全局画面且背景不动;人脸上下角度在20度以内,左右角度在15度以内,歪头角度在15度以内;光照均匀,无遮挡,人脸清晰可见;像素最好在 100X100 像素以上但是图像整体质量不能超过1080p。 **结果查询方式:**图像任务直接返回结果,点播及直播任务通过DescribeAITaskResult查询结果。 */ async SubmitOpenClassTask( req: SubmitOpenClassTaskRequest, cb?: (error: string, rep: SubmitOpenClassTaskResponse) => void ): Promise<SubmitOpenClassTaskResponse> { return this.request("SubmitOpenClassTask", req, cb) } /** * 支持多路视频流,提交高级人员考勤任务 */ async SubmitCheckAttendanceTaskPlus( req: SubmitCheckAttendanceTaskPlusRequest, cb?: (error: string, rep: SubmitCheckAttendanceTaskPlusResponse) => void ): Promise<SubmitCheckAttendanceTaskPlusResponse> { return this.request("SubmitCheckAttendanceTaskPlus", req, cb) } /** * 创建人员库 */ async CreateLibrary( req: CreateLibraryRequest, cb?: (error: string, rep: CreateLibraryResponse) => void ): Promise<CreateLibraryResponse> { return this.request("CreateLibrary", req, cb) } /** * 音频任务提交接口 */ async SubmitAudioTask( req: SubmitAudioTaskRequest, cb?: (error: string, rep: SubmitAudioTaskResponse) => void ): Promise<SubmitAudioTaskResponse> { return this.request("SubmitAudioTask", req, cb) } /** * 创建人脸 */ async CreateFace( req: CreateFaceRequest, cb?: (error: string, rep: CreateFaceResponse) => void ): Promise<CreateFaceResponse> { return this.request("CreateFace", req, cb) } /** * 修改人员信息 */ async ModifyPerson( req: ModifyPersonRequest, cb?: (error: string, rep: ModifyPersonResponse) => void ): Promise<ModifyPersonResponse> { return this.request("ModifyPerson", req, cb) } /** * 获取图像任务统计信息 */ async DescribeImageTaskStatistic( req: DescribeImageTaskStatisticRequest, cb?: (error: string, rep: DescribeImageTaskStatisticResponse) => void ): Promise<DescribeImageTaskStatisticResponse> { return this.request("DescribeImageTaskStatistic", req, cb) } /** * 提供 AI 助教基础版本功能接口 */ async AIAssistant( req: AIAssistantRequest, cb?: (error: string, rep: AIAssistantResponse) => void ): Promise<AIAssistantResponse> { return this.request("AIAssistant", req, cb) } /** * 修改人员库信息 */ async ModifyLibrary( req: ModifyLibraryRequest, cb?: (error: string, rep: ModifyLibraryResponse) => void ): Promise<ModifyLibraryResponse> { return this.request("ModifyLibrary", req, cb) } /** * 发起双路视频生成精彩集锦接口。该接口可以通过客户传入的学生音视频及老师视频两路Url,自动生成一堂课程的精彩集锦。需要通过DescribeHighlightResult 接口获取生成结果。 */ async SubmitDoubleVideoHighlights( req: SubmitDoubleVideoHighlightsRequest, cb?: (error: string, rep: SubmitDoubleVideoHighlightsResponse) => void ): Promise<SubmitDoubleVideoHighlightsResponse> { return this.request("SubmitDoubleVideoHighlights", req, cb) } /** * 拉取人员列表 */ async DescribePersons( req: DescribePersonsRequest, cb?: (error: string, rep: DescribePersonsResponse) => void ): Promise<DescribePersonsResponse> { return this.request("DescribePersons", req, cb) } /** * 对话任务分析接口 */ async SubmitConversationTask( req: SubmitConversationTaskRequest, cb?: (error: string, rep: SubmitConversationTaskResponse) => void ): Promise<SubmitConversationTaskResponse> { return this.request("SubmitConversationTask", req, cb) } /** * 视频精彩集锦结果查询接口,异步查询客户提交的请求的结果。 */ async DescribeHighlightResult( req: DescribeHighlightResultRequest, cb?: (error: string, rep: DescribeHighlightResultResponse) => void ): Promise<DescribeHighlightResultResponse> { return this.request("DescribeHighlightResult", req, cb) } /** * **提交线下传统面授大班课(含课桌)任务。** 传统教室课堂是指有学生课堂有课桌的课堂,满座20-50人,全局画面且背景不动。 **提供的功能接口有:**学生人脸识别、学生表情识别、学生肢体动作识别。可分析的指标维度包括:学生身份识别、正脸、侧脸、抬头、低头、高兴、中性、高兴、中性、惊讶、厌恶、恐惧、愤怒、蔑视、悲伤、举手、站立、坐着、趴桌子、玩手机等 **对场景的要求为:**传统的学生上课教室,满座20-50人,全局画面且背景不动;人脸上下角度在20度以内,左右角度在15度以内,歪头角度在15度以内;光照均匀,无遮挡,人脸清晰可见;像素最好在 100X100 像素以上,但是图像整体质量不能超过1080p。 **结果查询方式:**图像任务直接返回结果,点播及直播任务通过DescribeAITaskResult查询结果。 */ async SubmitTraditionalClassTask( req: SubmitTraditionalClassTaskRequest, cb?: (error: string, rep: SubmitTraditionalClassTaskResponse) => void ): Promise<SubmitTraditionalClassTaskResponse> { return this.request("SubmitTraditionalClassTask", req, cb) } /** * 获取标准化接口任务结果 */ async DescribeAITaskResult( req: DescribeAITaskResultRequest, cb?: (error: string, rep: DescribeAITaskResultResponse) => void ): Promise<DescribeAITaskResultResponse> { return this.request("DescribeAITaskResult", req, cb) } /** * 删除人员 */ async DeletePerson( req: DeletePersonRequest, cb?: (error: string, rep: DeletePersonResponse) => void ): Promise<DeletePersonResponse> { return this.request("DeletePerson", req, cb) } /** * 获取人员库列表 */ async DescribeLibraries( req?: DescribeLibrariesRequest, cb?: (error: string, rep: DescribeLibrariesResponse) => void ): Promise<DescribeLibrariesResponse> { return this.request("DescribeLibraries", req, cb) } /** * 用于取消已经提交的任务,目前只支持图像任务。 */ async CancelTask( req: CancelTaskRequest, cb?: (error: string, rep: CancelTaskResponse) => void ): Promise<CancelTaskResponse> { return this.request("CancelTask", req, cb) } /** * 发起视频生成精彩集锦接口。该接口可以通过客户传入的课程音频数据及相关策略(如微笑抽取,专注抽取等),自动生成一堂课程的精彩集锦。需要通过QueryHighlightResult接口获取生成结果。 */ async SubmitHighlights( req: SubmitHighlightsRequest, cb?: (error: string, rep: SubmitHighlightsResponse) => void ): Promise<SubmitHighlightsResponse> { return this.request("SubmitHighlights", req, cb) } /** * 查询词汇库 */ async DescribeVocabLib( req?: DescribeVocabLibRequest, cb?: (error: string, rep: DescribeVocabLibResponse) => void ): Promise<DescribeVocabLibResponse> { return this.request("DescribeVocabLib", req, cb) } /** * 创建词汇 */ async CreateVocab( req: CreateVocabRequest, cb?: (error: string, rep: CreateVocabResponse) => void ): Promise<CreateVocabResponse> { return this.request("CreateVocab", req, cb) } /** * **提交在线1对1课堂任务** 对于在线1对1课堂,老师通过视频向学生授课,并且学生人数为1人。通过上传学生端的图像信息,可以获取学生的听课情况分析。 具体指一路全局画面且背景不动,有1位学生的头像或上半身的画面,要求画面稳定清晰。 **提供的功能接口有:**学生人脸识别、学生表情识别、语音识别。可分析的指标维度包括:学生身份识别、正脸、侧脸、抬头、低头、人脸坐标、人脸尺寸、高兴、中性、高兴、中性、惊讶、厌恶、恐惧、愤怒、蔑视、悲伤、语音转文字、发音时长、非发音时长、音量、语速等。 **对场景的要求为:**真实常规1v1授课场景,学生2人以下,全局画面且背景不动;人脸上下角度在20度以内,左右角度在15度以内,歪头角度在15度以内;光照均匀,无遮挡,人脸清晰可见;像素最好在 100X100 像素以上,但是图像整体质量不能超过1080p。 **结果查询方式:**图像任务直接返回结果,点播及直播任务通过DescribeAITaskResult查询结果。 */ async SubmitOneByOneClassTask( req: SubmitOneByOneClassTaskRequest, cb?: (error: string, rep: SubmitOneByOneClassTaskResponse) => void ): Promise<SubmitOneByOneClassTaskResponse> { return this.request("SubmitOneByOneClassTask", req, cb) } /** * **在线小班课任务**:此场景是在线授课场景,老师一般为坐着授课,摄像头可以拍摄到老师的头部及上半身。拍摄视频为一路全局画面,且背景不动,要求画面稳定清晰。通过此接口可分析老师授课的行为及语音,以支持AI评教。 **提供的功能接口有:**老师人脸识别、老师表情识别、老师手势识别、光线识别、语音识别。 可分析的指标维度包括:身份识别、正脸、侧脸、人脸坐标、人脸尺寸、高兴、中性、高兴、中性、惊讶、厌恶、恐惧、愤怒、蔑视、悲伤、点赞手势、听你说手势、听我说手势、拿教具行为、语音转文字、发音时长、非发音时长、音量、语速、指定关键词的使用等 **对场景的要求为:**在线常规授课场景,全局画面且背景不动;人脸上下角度在20度以内,左右角度在15度以内,歪头角度在15度以内;光照均匀,无遮挡,人脸清晰可见;像素最好在 100X100 像素以上,但是图像整体质量不能超过1080p。 **结果查询方式:**图像任务直接返回结果,点播及直播任务通过DescribeAITaskResult查询结果。 */ async SubmitPartialBodyClassTask( req: SubmitPartialBodyClassTaskRequest, cb?: (error: string, rep: SubmitPartialBodyClassTaskResponse) => void ): Promise<SubmitPartialBodyClassTaskResponse> { return this.request("SubmitPartialBodyClassTask", req, cb) } /** * 提交人员考勤任务,支持包括点播和直播资源;支持通过DescribeAttendanceResult查询结果,也支持通过NoticeUrl设置考勤回调结果,回调结果结构如下: ##### 回调事件结构 | 参数名称 | 类型 | 描述 | | ---- | --- | ------ | | jobid | Integer | 任务ID | | person_info | array of PersonInfo | 识别到的人员列表 | #####子结构PersonInfo | 参数名称 | 类型 | 描述 | | ---- | --- | ------ | | traceid | String | 可用于区分同一路视频流下的不同陌生人 | | personid | String | 识别到的人员ID,如果是陌生人则返回空串 | | libid | String | 识别到的人员所在的库ID,如果是陌生人则返回空串 | | timestamp | uint64 | 识别到人脸的绝对时间戳,单位ms | | image_url | string | 识别到人脸的事件抓图的下载地址,不长期保存,需要请及时下载 | */ async SubmitCheckAttendanceTask( req: SubmitCheckAttendanceTaskRequest, cb?: (error: string, rep: SubmitCheckAttendanceTaskResponse) => void ): Promise<SubmitCheckAttendanceTaskResponse> { return this.request("SubmitCheckAttendanceTask", req, cb) } /** * 创建人员 */ async CreatePerson( req: CreatePersonRequest, cb?: (error: string, rep: CreatePersonResponse) => void ): Promise<CreatePersonResponse> { return this.request("CreatePerson", req, cb) } /** * 音频对话任务评估任务信息查询接口,异步查询客户提交的请求的结果。 */ async DescribeConversationTask( req: DescribeConversationTaskRequest, cb?: (error: string, rep: DescribeConversationTaskResponse) => void ): Promise<DescribeConversationTaskResponse> { return this.request("DescribeConversationTask", req, cb) } /** * 删除人员库 */ async DeleteLibrary( req: DeleteLibraryRequest, cb?: (error: string, rep: DeleteLibraryResponse) => void ): Promise<DeleteLibraryResponse> { return this.request("DeleteLibrary", req, cb) } /** * 拉取任务详情 */ async DescribeImageTask( req: DescribeImageTaskRequest, cb?: (error: string, rep: DescribeImageTaskResponse) => void ): Promise<DescribeImageTaskResponse> { return this.request("DescribeImageTask", req, cb) } /** * 提交图像分析任务 */ async SubmitImageTask( req: SubmitImageTaskRequest, cb?: (error: string, rep: SubmitImageTaskResponse) => void ): Promise<SubmitImageTaskResponse> { return this.request("SubmitImageTask", req, cb) } /** * 人脸考勤查询结果 */ async DescribeAttendanceResult( req: DescribeAttendanceResultRequest, cb?: (error: string, rep: DescribeAttendanceResultResponse) => void ): Promise<DescribeAttendanceResultResponse> { return this.request("DescribeAttendanceResult", req, cb) } /** * 高级图像分析任务,开放了图像任务里的所有开关,可以根据场景深度定制图像分析任务。支持的图像类别有,图片链接、图片二进制数据、点播链接和直播链接。 */ async SubmitImageTaskPlus( req: SubmitImageTaskPlusRequest, cb?: (error: string, rep: SubmitImageTaskPlusResponse) => void ): Promise<SubmitImageTaskPlusResponse> { return this.request("SubmitImageTaskPlus", req, cb) } /** * 建立词汇库 */ async CreateVocabLib( req: CreateVocabLibRequest, cb?: (error: string, rep: CreateVocabLibResponse) => void ): Promise<CreateVocabLibResponse> { return this.request("CreateVocabLib", req, cb) } /** * 删除词汇 */ async DeleteVocab( req: DeleteVocabRequest, cb?: (error: string, rep: DeleteVocabResponse) => void ): Promise<DeleteVocabResponse> { return this.request("DeleteVocab", req, cb) } /** * **传统课堂授课任务**:在此场景中,老师为站立授课,有白板或投影供老师展示课程内容,摄像头可以拍摄到老师的半身或者全身。拍摄视频为一路全局画面,且背景不动,要求画面稳定清晰。通过此接口可分析老师授课的行为及语音,以支持AI评教。 **提供的功能接口有:**老师人脸识别、老师表情识别、老师肢体动作识别、语音识别。 可分析的指标维度包括:身份识别、正脸、侧脸、人脸坐标、人脸尺寸、高兴、中性、高兴、中性、惊讶、厌恶、恐惧、愤怒、蔑视、悲伤、正面讲解、写板书、指黑板、语音转文字、发音时长、非发音时长、音量、语速、指定关键词的使用等 **对场景的要求为:**真实场景老师1人出现在画面中,全局画面且背景不动;人脸上下角度在20度以内,左右角度在15度以内,歪头角度在15度以内;光照均匀,无遮挡,人脸清晰可见;像素最好在 100X100 像素以上,但是图像整体质量不能超过1080p。 **结果查询方式:**图像任务直接返回结果,点播及直播任务通过DescribeAITaskResult查询结果。 */ async SubmitFullBodyClassTask( req: SubmitFullBodyClassTaskRequest, cb?: (error: string, rep: SubmitFullBodyClassTaskResponse) => void ): Promise<SubmitFullBodyClassTaskResponse> { return this.request("SubmitFullBodyClassTask", req, cb) } /** * 检查人脸图片是否合法 */ async CheckFacePhoto( req: CheckFacePhotoRequest, cb?: (error: string, rep: CheckFacePhotoResponse) => void ): Promise<CheckFacePhotoResponse> { return this.request("CheckFacePhoto", req, cb) } /** * 查询词汇 */ async DescribeVocab( req: DescribeVocabRequest, cb?: (error: string, rep: DescribeVocabResponse) => void ): Promise<DescribeVocabResponse> { return this.request("DescribeVocab", req, cb) } /** * 删除词汇库 */ async DeleteVocabLib( req: DeleteVocabLibRequest, cb?: (error: string, rep: DeleteVocabLibResponse) => void ): Promise<DeleteVocabLibResponse> { return this.request("DeleteVocabLib", req, cb) } /** * 获取人员详情 */ async DescribePerson( req: DescribePersonRequest, cb?: (error: string, rep: DescribePersonResponse) => void ): Promise<DescribePersonResponse> { return this.request("DescribePerson", req, cb) } /** * 删除人脸 */ async DeleteFace( req: DeleteFaceRequest, cb?: (error: string, rep: DeleteFaceResponse) => void ): Promise<DeleteFaceResponse> { return this.request("DeleteFace", req, cb) } /** * 音频评估任务信息查询接口,异步查询客户提交的请求的结果。 */ async DescribeAudioTask( req: DescribeAudioTaskRequest, cb?: (error: string, rep: DescribeAudioTaskResponse) => void ): Promise<DescribeAudioTaskResponse> { return this.request("DescribeAudioTask", req, cb) } /** * 分析音频信息 */ async TransmitAudioStream( req: TransmitAudioStreamRequest, cb?: (error: string, rep: TransmitAudioStreamResponse) => void ): Promise<TransmitAudioStreamResponse> { return this.request("TransmitAudioStream", req, cb) } }
the_stack
import React, { useState, useEffect, useCallback } from 'react'; import { useHistory } from 'react-router-dom'; import { Stack, TextField, Text, PrimaryButton, DefaultButton, IconButton, Pivot, PivotItem, ComboBox, ChoiceGroup, Label, IComboBoxOption } from '@fluentui/react'; import { OrganizationDefinition, DeploymentScopeDefinition, ProjectTemplateDefinition } from 'teamcloud' import { AzureRegions, Tags } from '../model'; import { CalloutLabel, ContentContainer, ContentHeader, ContentProgress, DeploymentScopeForm, ProjectTemplateForm } from '../components'; import { useCreateOrg, useAzureSubscriptions } from '../hooks'; export const NewOrgView: React.FC = () => { const history = useHistory(); const { data: subscriptions } = useAzureSubscriptions(); const createOrg = useCreateOrg(); // Basic Settings const [orgName, setOrgName] = useState<string>(); const [orgSubscription, setOrgSubscription] = useState<string>(); const [orgSubscriptionOptions, setOrgSubscriptionOptions] = useState<IComboBoxOption[]>(); const [orgRegion, setOrgRegion] = useState<string>(); const [webPortalEnabled, setWebPortalEnabled] = useState(true); const [scope, setScope] = useState<DeploymentScopeDefinition>(); const [template, setTemplate] = useState<ProjectTemplateDefinition>(); const [tags, setTags] = useState<Tags>(); // Misc. const [pivotKey, setPivotKey] = useState<string>('Basic Settings'); const [formEnabled, setFormEnabled] = useState<boolean>(true); const [percentComplete, setPercentComplete] = useState<number>(); const pivotKeys = ['Basic Settings', 'Configuration', 'Deployment Scope', 'Project Template', 'Tags', 'Review + create']; const _orgComplete = () => orgName && orgSubscription && orgRegion; const _scopeComplete = () => scope?.displayName && scope?.type && scope?.inputData; const _templateComplete = () => template?.displayName && template.repository.url; useEffect(() => { const newTags: Tags = {} newTags[''] = '' setTags(newTags) }, []); useEffect(() => { if (subscriptions && orgSubscriptionOptions === undefined) { // console.log('+ setOrgSubscriptionOptions') setOrgSubscriptionOptions(subscriptions?.map(s => ({ key: s.subscriptionId, text: s.displayName }))); } }, [subscriptions, orgSubscriptionOptions]); useEffect(() => { if (orgSubscriptionOptions && orgSubscriptionOptions.length === 1 && orgSubscription === undefined) { // console.log('+ setOrgSubscription') setOrgSubscription(orgSubscriptionOptions[0].key as string); } }, [orgSubscription, orgSubscriptionOptions]); const _submitForm = async () => { if (_orgComplete()) { setFormEnabled(false); setPercentComplete(undefined); const orgDef = { displayName: orgName, subscriptionId: orgSubscription, location: orgRegion } as OrganizationDefinition; const def = { orgDef: orgDef, scopeDef: scope && _scopeComplete() ? scope : undefined, templateDef: template && _templateComplete() ? template : undefined } await createOrg(def); } }; const _resetAndCloseForm = async () => { setFormEnabled(false); }; const _onTagKeyChange = (key: string, value: string, newKey?: string) => { const newTags: Tags = {} for (const k in tags) newTags[(k === key) ? newKey ?? '' : k] = value if (!newTags['']) newTags[''] = '' setTags(newTags) }; const _onTagValueChange = (key: string, newValue?: string) => { const newTags: Tags = {} for (const k in tags) newTags[k] = (k === key) ? newValue ?? '' : tags[k] setTags(newTags) }; const _getTagsTextFields = () => { let tagStack = []; if (tags) { let counter = 0 for (const key in tags) { tagStack.push( <Stack key={counter} horizontal tokens={{ childrenGap: '8px' }}> <TextField disabled={!formEnabled} description='Name' value={key} onChange={(_ev, val) => _onTagKeyChange(key, tags[key], val)} /> <TextField disabled={!formEnabled} description='Value' value={tags[key]} onChange={(_ev, val) => _onTagValueChange(key, val)} /> </Stack>) counter++ } } return (<Stack.Item>{tagStack}</Stack.Item>) }; const _onReview = (): boolean => pivotKeys.indexOf(pivotKey) === pivotKeys.length - 1; const _getPrimaryButtonText = (): string => { const currentIndex = pivotKeys.indexOf(pivotKey); return currentIndex === pivotKeys.length - 1 ? 'Create organization' : `Next: ${pivotKeys[currentIndex + 1]}`; }; const onScopeChange = useCallback((scope?: DeploymentScopeDefinition) => { // console.log(`+ onScopeChange: ${scope}`) setScope(scope); }, []); const onTemplateChange = useCallback((template?: ProjectTemplateDefinition) => { // console.log(`+ onTemplateChange: ${template}`) setTemplate(template); }, []); return ( <Stack styles={{ root: { height: '100%' } }}> <ContentProgress percentComplete={percentComplete} progressHidden={formEnabled} /> <ContentHeader title='New Organization' coin={false} wide> <IconButton iconProps={{ iconName: 'ChromeClose' }} onClick={() => history.push('/')} /> </ContentHeader> <ContentContainer wide full> <Pivot selectedKey={pivotKey} onLinkClick={(i, ev) => setPivotKey(i?.props.itemKey ?? 'Basic Settings')} styles={{ root: { height: '100%' } }}> <PivotItem headerText='Basic Settings' itemKey='Basic Settings'> <Stack tokens={{ childrenGap: '20px' }} styles={{ root: { padding: '24px 8px' } }}> <Stack.Item> <TextField required label='Name' description='Organization display name' disabled={!formEnabled} value={orgName} onChange={(_ev, val) => setOrgName(val)} /> </Stack.Item> <Stack.Item> <ComboBox required label='Subscription' disabled={!formEnabled} selectedKey={orgSubscription} options={orgSubscriptionOptions ?? []} onChange={(_ev, val) => setOrgSubscription(val ? val.key as string : undefined)} /> </Stack.Item> <Stack.Item> <ComboBox required label='Location' disabled={!formEnabled} allowFreeform autoComplete={'on'} selectedKey={orgRegion} options={AzureRegions.map(r => ({ key: r, text: r }))} onChange={(_ev, val) => setOrgRegion(val?.text ?? undefined)} /> </Stack.Item> </Stack> </PivotItem> <PivotItem headerText='Configuration' itemKey='Configuration'> <Stack tokens={{ childrenGap: '20px' }} styles={{ root: { padding: '24px 8px' } }}> <Stack.Item> <ChoiceGroup required label='Web portal' disabled={!formEnabled} selectedKey={webPortalEnabled ? 'enabled' : 'disabled'} onChange={(ev, opt) => setWebPortalEnabled(opt?.key === 'enabled' ?? false)} options={[{ key: 'enabled', text: 'Enabled' }, { key: 'disabled', text: 'Disabled' }]} /> </Stack.Item> </Stack> </PivotItem> <PivotItem headerText='Deployment Scope' itemKey='Deployment Scope'> <DeploymentScopeForm embedded onScopeChange={onScopeChange} /> </PivotItem> <PivotItem headerText='Project Template' itemKey='Project Template'> <ProjectTemplateForm embedded onTemplateChange={onTemplateChange} /> </PivotItem> <PivotItem headerText='Tags' itemKey='Tags'> <Stack tokens={{ childrenGap: '20px' }} styles={{ root: { padding: '24px 8px' } }}> <Stack.Item> <Label disabled={!formEnabled}>Tags</Label> {_getTagsTextFields()} </Stack.Item> </Stack> </PivotItem> <PivotItem headerText='Review + create' itemKey='Review + create'> <Stack tokens={{ childrenGap: '40px' }} styles={{ root: { padding: '24px 8px' } }}> <Stack.Item> <NewOrgReviewSection title='Basic Settings' details={[ { label: 'Name', value: orgName, required: true }, { label: 'Subscription', value: orgSubscription, required: true }, { label: 'Location', value: orgRegion, required: true } ]} /> </Stack.Item> <Stack.Item> <NewOrgReviewSection title='Configuration' details={[ { label: 'Web Portal', value: webPortalEnabled ? 'Enabled' : 'Disabled', required: true } ]} /> </Stack.Item> <Stack.Item> <NewOrgReviewSection title='Deployment Scope' details={[ { label: 'Name', value: scope?.displayName ?? '', required: true }, { label: 'Type', value: scope?.type ?? '', required: true }, { label: 'Data', value: scope?.inputData ?? '', required: true } ]} /> </Stack.Item> <Stack.Item> <NewOrgReviewSection title='Project Template' details={[ { label: 'Name', value: template?.displayName, required: true }, { label: 'Url', value: template?.repository.url, required: true }, { label: 'Version', value: template?.repository.version ?? undefined }, { label: 'Token', value: template?.repository.token ?? undefined } ]} /> </Stack.Item> </Stack> </PivotItem> </Pivot> </ContentContainer> <Stack.Item styles={{ root: { padding: '24px 52px' } }}> <PrimaryButton text={_getPrimaryButtonText()} disabled={!formEnabled || (_onReview() && !_orgComplete())} onClick={() => _onReview() ? _submitForm() : setPivotKey(pivotKeys[pivotKeys.indexOf(pivotKey) + 1])} styles={{ root: { marginRight: 8 } }} /> <DefaultButton text='Cancel' disabled={!formEnabled} onClick={() => _resetAndCloseForm()} /> </Stack.Item> </Stack> ); } export interface INewOrgReviewSection { title: string; details: { label: string, value?: string, required?: boolean }[] } export const NewOrgReviewSection: React.FC<INewOrgReviewSection> = (props) => { const _getDetailStacks = () => props.details.map(d => ( <Stack horizontal verticalAlign='baseline' key={`${props.title}${d.label}`} tokens={{ childrenGap: 10 }}> <Label required={d.required}>{d.label}:</Label> <Text>{d.value}</Text> </Stack> )); return ( <Stack> <CalloutLabel title={props.title} /> {_getDetailStacks()} </Stack> ); }
the_stack
import fs from "fs/promises"; import path from "path"; import { TransformStream } from "stream/web"; import { setImmediate, setTimeout } from "timers/promises"; import { useTmp } from "@miniflare/shared-test"; import { Watcher } from "@miniflare/watcher"; import anyTest, { ExecutionContext, Macro } from "ava"; // Only run watcher tests on macOS. The Watcher does work on Linux and Windows, // the tests are just very flaky. // TODO: make watcher tests more reliable :D const test = process.platform === "darwin" ? anyTest.serial : anyTest.skip; interface WatcherEvents { count: number; next: () => Promise<string>; } function useWatcher( t: ExecutionContext, forceRecursive?: boolean ): [watcher: Watcher, events: WatcherEvents] { const { readable, writable } = new TransformStream<string, string>(); const reader = readable.getReader(); const writer = writable.getWriter(); const events: WatcherEvents = { count: 0, next: async () => (await reader.read()).value ?? "", }; const watcher = new Watcher( (path) => { events.count++; void writer.write(path); }, { pollInterval: 50, createPollInterval: 50, forceRecursive } ); t.teardown(() => watcher.dispose()); return [watcher, events]; } test("PathWatcher: startCreatedWatcher: watches for file to be created", async (t) => { const tmp = await useTmp(t); const testPath = path.join(tmp, "test.txt"); const [watcher, events] = useWatcher(t); watcher.watch(testPath); await setImmediate(); await fs.writeFile(testPath, "test"); t.is(await events.next(), testPath); t.is(events.count, 1); }); test("PathWatcher: startCreatedWatcher: watches for directory to be created", async (t) => { const tmp = await useTmp(t); const testPath = path.join(tmp, "test"); const [watcher, events] = useWatcher(t); watcher.watch(testPath); await setImmediate(); await fs.mkdir(testPath); t.is(await events.next(), testPath); t.is(events.count, 1); }); test("PathWatcher: startPollingWatcher: watches single files", async (t) => { const tmp = await useTmp(t); const testPath = path.join(tmp, "test.txt"); await fs.writeFile(testPath, "test"); const [watcher, events] = useWatcher(t); watcher.watch(testPath); await setImmediate(); await fs.writeFile(testPath, "test2"); t.is(await events.next(), testPath); t.is(events.count, 1); }); test("PathWatcher: startPollingWatcher: watches for file to be created again if deleted", async (t) => { const tmp = await useTmp(t); const testPath = path.join(tmp, "test.txt"); await fs.writeFile(testPath, "test"); const [watcher, events] = useWatcher(t); watcher.watch(testPath); await setImmediate(); await fs.rm(testPath); t.is(await events.next(), testPath); t.is(events.count, 1); await fs.writeFile(testPath, "test"); t.is(await events.next(), testPath); t.is(events.count, 2); }); test("PathWatcher: startPollingWatcher: handles file being replaced by rename", async (t) => { const tmp = await useTmp(t); const testPath = path.join(tmp, "test.txt"); const testTmpPath = testPath + "~"; await fs.writeFile(testPath, "0"); const [watcher, events] = useWatcher(t); watcher.watch(testPath); await setImmediate(); await fs.writeFile(testTmpPath, "1"); await setTimeout(100); t.is(events.count, 0); await fs.rename(testTmpPath, testPath); t.is(await events.next(), testPath); t.is(events.count, 1); await fs.writeFile(testTmpPath, "2"); await setTimeout(100); t.is(events.count, 1); await fs.rename(testTmpPath, testPath); t.is(await events.next(), testPath); t.is(events.count, 2); }); const recursiveTitle = (title: string) => (providedTitle?: string, force?: boolean) => `PathWatcher: start${force ? "" : "Platform"}RecursiveWatcher: ${title}`; const recursiveRootMacro: Macro<[force?: boolean]> = async (t, force) => { const tmp = await useTmp(t); const [watcher, events] = useWatcher(t, force); watcher.watch(tmp); await fs.writeFile(path.join(tmp, "test.txt"), "value"); t.is(await events.next(), tmp); await fs.mkdir(path.join(tmp, "test")); t.is(await events.next(), tmp); }; recursiveRootMacro.title = recursiveTitle("watches files in root directory"); test(recursiveRootMacro); test(recursiveRootMacro, true); const recursiveNestedMacro: Macro<[force?: boolean]> = async (t, force) => { const tmp = await useTmp(t); const nestedDir = path.join(tmp, "nested"); await fs.mkdir(nestedDir); const [watcher, events] = useWatcher(t, force); watcher.watch(tmp); await fs.writeFile(path.join(nestedDir, "test.txt"), "value"); t.is(await events.next(), tmp); await fs.mkdir(path.join(nestedDir, "test")); t.is(await events.next(), tmp); }; recursiveNestedMacro.title = recursiveTitle( "watches files in nested directory" ); test(recursiveNestedMacro); test(recursiveNestedMacro, true); const recursiveNewMacro: Macro<[force?: boolean]> = async (t, force) => { const tmp = await useTmp(t); const nestedDir = path.join(tmp, "nested"); const [watcher, events] = useWatcher(t, force); watcher.watch(tmp); await setImmediate(); await fs.mkdir(nestedDir); await fs.writeFile(path.join(nestedDir, "test.txt"), "value"); t.is(await events.next(), tmp); await fs.mkdir(path.join(nestedDir, "test")); t.is(await events.next(), tmp); }; recursiveNewMacro.title = recursiveTitle( "watches files in newly created directory" ); test(recursiveNewMacro); test(recursiveNewMacro, true); const recursiveNewNestedMacro: Macro<[force?: boolean]> = async (t, force) => { const tmp = await useTmp(t); const tmp1 = path.join(tmp, "1"); const tmp2 = path.join(tmp, "2"); const tmp2Dir = path.join(tmp2, "dir"); const tmp2Nested = path.join(tmp2Dir, "nested"); const tmp2NestedFile = path.join(tmp2Nested, "test.txt"); await fs.mkdir(tmp1); await fs.mkdir(tmp2Nested, { recursive: true }); await fs.writeFile(tmp2NestedFile, "1"); const [watcher, events] = useWatcher(t, force); watcher.watch(tmp1); await setImmediate(); // Move tmp2 to inside tmp1 const newTmp2 = path.join(tmp1, "tmp2"); await fs.rename(tmp2, newTmp2); t.is(await events.next(), tmp1); await setTimeout(100); t.is(events.count, 1); // Update tmp2NestedFile in tmp1 await fs.writeFile(path.join(newTmp2, "dir", "nested", "test.txt"), "2"); t.is(await events.next(), tmp1); t.is(events.count, 2); // Create new file in dir await fs.writeFile(path.join(newTmp2, "dir", "new1.txt"), "1"); t.is(await events.next(), tmp1); t.is(events.count, 3); // Create new file in nested dir await fs.writeFile(path.join(newTmp2, "dir", "nested", "new2.txt"), "2"); t.is(await events.next(), tmp1); t.is(events.count, 4); }; recursiveNewNestedMacro.title = recursiveTitle( "watches files in newly created nested directories" ); test(recursiveNewNestedMacro); test(recursiveNewNestedMacro, true); const recursiveNestedDeleteMacro: Macro<[force?: boolean]> = async ( t, force ) => { const tmp = await useTmp(t); const nestedDir = path.join(tmp, "nested"); const nestedTestPath = path.join(nestedDir, "test.txt"); await fs.mkdir(nestedDir); const [watcher, events] = useWatcher(t, force); watcher.watch(tmp); await setImmediate(); // Delete nested directory await fs.rmdir(nestedDir); t.is(await events.next(), tmp); await setTimeout(100); t.is(events.count, 1); // Recreate directory await fs.mkdir(nestedDir); t.is(await events.next(), tmp); t.is(events.count, 2); // Create file in directory await fs.writeFile(nestedTestPath, "2"); t.is(await events.next(), tmp); t.is(events.count, 3); }; recursiveNestedDeleteMacro.title = recursiveTitle( "handles nested directory being deleted and recreated again" ); test(recursiveNestedDeleteMacro); test(recursiveNestedDeleteMacro, true); const recursiveRootDeleteMacro: Macro<[force?: boolean]> = async (t, force) => { const tmp = await useTmp(t); const root = path.join(tmp, "root"); const newRoot = path.join(tmp, "root2"); const newRootDir = path.join(newRoot, "dir"); const newRootDirNested = path.join(newRootDir, "nested"); const newRootDirNestedFile = path.join(newRootDirNested, "test.txt"); await fs.mkdir(root); await fs.mkdir(newRootDirNested, { recursive: true }); await fs.writeFile(newRootDirNestedFile, "1"); const [watcher, events] = useWatcher(t, force); watcher.watch(root); await setImmediate(); // Delete root directory and move new root in it's place await fs.rmdir(root); t.is(await events.next(), root); await setTimeout(100); t.is(events.count, 1); await fs.rename(newRoot, root); t.is(await events.next(), root); t.is(events.count, 2); // Update file in newly copied root await fs.writeFile(path.join(root, "dir", "nested", "test.txt"), "2"); t.is(await events.next(), root); t.is(events.count, 3); }; recursiveRootDeleteMacro.title = recursiveTitle( "handles root directory being deleted and recreated again" ); test(recursiveRootDeleteMacro); test(recursiveRootDeleteMacro, true); const recursiveRootReplaceFileMacro: Macro<[force?: boolean]> = async ( t, force ) => { const tmp = await useTmp(t); const root = path.join(tmp, "root"); await fs.mkdir(root); const [watcher, events] = useWatcher(t, force); watcher.watch(root); await setImmediate(); // Delete root directory and replace with file await fs.rmdir(root); t.is(await events.next(), root); await setTimeout(100); t.is(events.count, 1); await fs.writeFile(root, "1"); t.is(await events.next(), root); t.is(events.count, 2); await fs.writeFile(root, "2"); t.is(await events.next(), root); t.is(events.count, 3); }; recursiveRootReplaceFileMacro.title = recursiveTitle( "handles root directory being deleted and replaced with file of same name" ); test(recursiveRootReplaceFileMacro); test(recursiveRootReplaceFileMacro, true); test("PathWatcher: dispose: cleans up polling watchers", async (t) => { const tmp = await useTmp(t); const testPath = path.join(tmp, "test.txt"); await fs.writeFile(testPath, "1"); const [watcher, events] = useWatcher(t); watcher.watch(testPath); watcher.dispose(); await fs.writeFile(testPath, "1"); await setTimeout(100); t.is(events.count, 0); }); test("PathWatcher: dispose: cleans up platform recursive watchers", async (t) => { const tmp = await useTmp(t); const testPath = path.join(tmp, "test.txt"); await fs.writeFile(testPath, "1"); const [watcher, events] = useWatcher(t); watcher.watch(tmp); watcher.dispose(); await fs.writeFile(testPath, "1"); await setTimeout(100); t.is(events.count, 0); }); test("PathWatcher: dispose: cleans up recursive watchers", async (t) => { const tmp = await useTmp(t); const testPath = path.join(tmp, "test.txt"); await fs.writeFile(testPath, "1"); const [watcher, events] = useWatcher(t, true); watcher.watch(tmp); watcher.dispose(); await fs.writeFile(testPath, "1"); await setTimeout(100); t.is(events.count, 0); }); test("Watcher: watches and un-watches files", async (t) => { const tmp = await useTmp(t); const test1Path = path.join(tmp, "test1.txt"); const test2Path = path.join(tmp, "test2.txt"); await fs.writeFile(test1Path, "test1 value1"); await fs.writeFile(test2Path, "test2 value1"); const [watcher, events] = useWatcher(t); watcher.watch([test1Path, test2Path]); // Check event emitted on change await fs.writeFile(test2Path, "test2 value2"); t.is(await events.next(), test2Path); // Unwatch file and check no longer watcher watcher.unwatch(test2Path); await fs.writeFile(test2Path, "test2 value2"); await setTimeout(100); await fs.writeFile(test1Path, "test1 value2"); t.is(await events.next(), test1Path); }); test("Watcher: watches files once", async (t) => { const tmp = await useTmp(t); const testPath = path.join(tmp, "test.txt"); await fs.writeFile(testPath, "value1"); const [watcher, events] = useWatcher(t); watcher.watch([testPath, testPath]); watcher.watch(testPath); await fs.writeFile(testPath, "value2"); t.is(await events.next(), testPath); await setTimeout(100); t.is(events.count, 1); }); test("Watcher: dispose: cleans up watchers", async (t) => { const tmp = await useTmp(t); const test1Path = path.join(tmp, "test1.txt"); const test2Path = path.join(tmp, "test2.txt"); await fs.writeFile(test1Path, "test1 value1"); await fs.writeFile(test2Path, "test2 value1"); const [watcher, events] = useWatcher(t); watcher.watch([test1Path, test2Path]); watcher.dispose(); await fs.writeFile(test1Path, "test1 value2"); await fs.writeFile(test2Path, "test2 value2"); await setTimeout(100); t.is(events.count, 0); });
the_stack
import { Component, ComponentType, MouseEvent, ReactNode } from 'react' import PropTypes from 'prop-types' import cx from 'clsx' import CellValue from './components/CellValue' import ErrorBoundary from './components/ErrorBoundary' import Paginator from './components/Paginator' import Table from './components/Table' import Toggles, { TogglesSelectAllProps, togglesSelectAllPropTypes, } from './components/Toggles' import withPagination, { WrappedComponentProps, } from './components/helpers/with-pagination' import * as utils from './helpers/functions' import * as constants from './helpers/constants' import './css/basic.css' interface SmartDataTableProps { className: string data: string | utils.UnknownObject[] dataKey: string dataKeyResolver: utils.KeyResolverFN dataRequestOptions: RequestInit dataSampling: number dynamic: boolean emptyTable: ReactNode filterValue: string headers: utils.Headers hideUnordered: boolean loader: ReactNode name: string onRowClick: utils.RowClickFN orderedHeaders: string[] paginator: ComponentType<WrappedComponentProps> parseBool: boolean | utils.ParseBool parseImg: boolean | utils.ParseImg perPage: number sortable: boolean withFooter: boolean withHeader: boolean withLinks: boolean withToggles: boolean | { selectAll?: TogglesSelectAllProps } } interface SmartDataTableState { activePage: number asyncData: utils.UnknownObject[] colProperties: utils.Headers columns: utils.Column[] isLoading: boolean prevFilterValue: string sorting: utils.Sorting } class SmartDataTable extends Component< SmartDataTableProps, SmartDataTableState > { static propTypes static defaultProps constructor(props: SmartDataTableProps) { super(props) const { headers: colProperties = {} } = props this.state = { activePage: 1, asyncData: [], colProperties, columns: [], isLoading: false, prevFilterValue: '', sorting: { key: '', dir: '', }, } } static getDerivedStateFromProps( props: SmartDataTableProps, state: SmartDataTableState, ): SmartDataTableState | null { const { filterValue } = props const { prevFilterValue } = state if (filterValue !== prevFilterValue) { return { ...state, activePage: 1, prevFilterValue: filterValue, } } return null } componentDidMount(): void { void this.fetchData() } componentDidUpdate(prevProps: SmartDataTableProps): void { const { data } = this.props const { data: prevData } = prevProps if ( utils.isString(data) && (typeof data !== typeof prevData || data !== prevData) ) { void this.fetchData() } } handleRowClick = ( event: MouseEvent<HTMLElement>, rowData: utils.UnknownObject, rowIndex: number, tableData: utils.UnknownObject[], ): void => { const { onRowClick } = this.props if (onRowClick) { onRowClick(event, { rowData, rowIndex, tableData }) } } handleColumnToggle = (key: string): void => { const { colProperties } = this.state const newColProperties = { ...colProperties } if (!newColProperties[key]) { newColProperties[key] = { ...constants.defaultHeader, key, } } newColProperties[key].invisible = !newColProperties[key].invisible this.setState({ colProperties: newColProperties }) } handleColumnToggleAll = (columns: utils.Column[]) => (isChecked: boolean): void => { const { colProperties } = this.state const newColProperties = { ...colProperties } for (const { key } of columns) { if (!newColProperties[key]) { newColProperties[key] = { ...constants.defaultHeader, key, } } newColProperties[key].invisible = isChecked } this.setState({ colProperties: newColProperties }) } handleOnPageChange = ( event: MouseEvent<HTMLElement>, { activePage }: { activePage: number }, ): void => { this.setState({ activePage }) } handleSortChange(column: utils.Column): void { const { sorting } = this.state const { key } = column let dir = '' if (key !== sorting.key) { sorting.dir = '' } if (sorting.dir) { if (sorting.dir === constants.ORDER_ASC) { dir = constants.ORDER_DESC } else { dir = '' } } else { dir = constants.ORDER_ASC } this.setState({ sorting: { key, dir, }, }) } getColumns(force = false): utils.Column[] { const { asyncData, columns } = this.state const { data: propsData, dataSampling, headers, hideUnordered, orderedHeaders, } = this.props if (!force && !utils.isEmpty(columns)) { return columns } let data = propsData as utils.UnknownObject[] if (utils.isString(data)) { data = asyncData } return utils.parseDataForColumns( data, headers, orderedHeaders, hideUnordered, dataSampling, ) } getRows(): utils.UnknownObject[] { const { asyncData, colProperties, sorting } = this.state const { data: propsData, filterValue } = this.props let data = propsData as utils.UnknownObject[] if (utils.isString(data)) { data = asyncData } return utils.sortData( filterValue, colProperties, sorting, utils.parseDataForRows(data), ) } async fetchData(): Promise<void> { const { data, dataKey, dataKeyResolver, dataRequestOptions: options, } = this.props if (utils.isString(data)) { this.setState({ isLoading: true }) try { const asyncData = await utils.fetchData(data, { dataKey, dataKeyResolver, options, }) this.setState({ asyncData, isLoading: false, columns: this.getColumns(true), }) } catch (err) { this.setState({ isLoading: false, }) throw new Error(String(err)) } } } renderSorting(column: utils.Column): ReactNode { const { sorting: { key, dir }, } = this.state let sortingIcon = 'rsdt-sortable-icon' if (key === column.key) { if (dir) { if (dir === constants.ORDER_ASC) { sortingIcon = 'rsdt-sortable-asc' } else { sortingIcon = 'rsdt-sortable-desc' } } } return ( <i className={cx('rsdt', sortingIcon)} onClick={() => this.handleSortChange(column)} onKeyDown={() => this.handleSortChange(column)} role="button" tabIndex={0} aria-label="sorting column" /> ) } renderHeader(columns: utils.Column[]): ReactNode { const { colProperties } = this.state const { sortable } = this.props const headers = columns.map((column) => { const thisColProps = colProperties[column.key] const showCol = !thisColProps || !thisColProps.invisible if (showCol) { return ( <Table.HeaderCell key={column.key}> <span>{column.text}</span> <span className="rsdt rsdt-sortable"> {sortable && column.sortable ? this.renderSorting(column) : null} </span> </Table.HeaderCell> ) } return null }) return <Table.Row>{headers}</Table.Row> } renderRow( columns: utils.Column[], row: utils.UnknownObject, i: number, ): ReactNode { const { colProperties } = this.state const { withLinks, filterValue, parseBool, parseImg } = this.props return columns.map((column, j) => { const thisColProps = { ...colProperties[column.key] } const showCol = !thisColProps.invisible const transformFn = thisColProps.transform if (showCol) { return ( // eslint-disable-next-line react/no-array-index-key <Table.Cell key={`row-${i}-column-${j}`}> {utils.isFunction(transformFn) ? ( transformFn(row[column.key], i, row) ) : ( <ErrorBoundary> <CellValue withLinks={withLinks} filterValue={filterValue} parseBool={parseBool} parseImg={parseImg} filterable={thisColProps.filterable} isImg={thisColProps.isImg} > {row[column.key]} </CellValue> </ErrorBoundary> )} </Table.Cell> ) } return null }) } renderBody(columns: utils.Column[], rows: utils.UnknownObject[]): ReactNode { const { perPage } = this.props const { activePage } = this.state const visibleRows = utils.sliceRowsPerPage(rows, activePage, perPage) const tableRows = visibleRows.map((row, idx) => ( <Table.Row // eslint-disable-next-line react/no-array-index-key key={`row-${idx}`} onClick={(event: MouseEvent<HTMLElement>) => this.handleRowClick(event, row, idx, rows) } > {this.renderRow(columns, row, idx)} </Table.Row> )) return <Table.Body>{tableRows}</Table.Body> } renderToggles(columns: utils.Column[]): ReactNode { const { colProperties } = this.state const { withToggles } = this.props const togglesProps = typeof withToggles === 'object' ? withToggles : {} if (withToggles) { return ( <ErrorBoundary> <Toggles columns={columns} colProperties={colProperties} handleColumnToggle={this.handleColumnToggle} handleColumnToggleAll={this.handleColumnToggleAll(columns)} selectAll={togglesProps?.selectAll} /> </ErrorBoundary> ) } return null } renderPagination(rows: utils.UnknownObject[]): ReactNode { const { perPage, paginator: PaginatorComponent } = this.props const { activePage } = this.state const Paginate = withPagination(PaginatorComponent) if (perPage && perPage > 0) { return ( <ErrorBoundary> <Paginate rows={rows} perPage={perPage} activePage={activePage} onPageChange={this.handleOnPageChange} /> </ErrorBoundary> ) } return null } render(): ReactNode { const { className, dynamic, emptyTable, loader, name, withFooter, withHeader, } = this.props const { isLoading } = this.state const columns = this.getColumns(dynamic) const rows = this.getRows() if (isLoading) { return loader } if (utils.isEmpty(rows)) { return emptyTable } return ( <section className="rsdt rsdt-container"> {this.renderToggles(columns)} <Table data-table-name={name} className={className}> {withHeader && ( <Table.Header>{this.renderHeader(columns)}</Table.Header> )} {this.renderBody(columns, rows)} {withFooter && ( <Table.Footer>{this.renderHeader(columns)}</Table.Footer> )} </Table> {this.renderPagination(rows)} </section> ) } } // Defines the type of data expected in each passed prop SmartDataTable.propTypes = { className: PropTypes.string, data: PropTypes.oneOfType([PropTypes.string, PropTypes.array]).isRequired, dataKey: PropTypes.string, dataKeyResolver: PropTypes.func, dataRequestOptions: PropTypes.objectOf(PropTypes.any), dataSampling: PropTypes.number, dynamic: PropTypes.bool, emptyTable: PropTypes.node, filterValue: PropTypes.string, headers: PropTypes.shape({ key: PropTypes.string, text: PropTypes.string, invisible: PropTypes.bool, sortable: PropTypes.bool, filterable: PropTypes.bool, isImg: PropTypes.oneOf([ PropTypes.bool, PropTypes.shape({ style: PropTypes.objectOf(PropTypes.any), className: PropTypes.string, }), ]), transform: PropTypes.func, }), hideUnordered: PropTypes.bool, loader: PropTypes.node, name: PropTypes.string, onRowClick: PropTypes.func, orderedHeaders: PropTypes.arrayOf(PropTypes.string), paginator: PropTypes.elementType, parseBool: PropTypes.oneOfType([PropTypes.bool, PropTypes.object]), parseImg: PropTypes.oneOfType([PropTypes.bool, PropTypes.object]), perPage: PropTypes.number, sortable: PropTypes.bool, withFooter: PropTypes.bool, withHeader: PropTypes.bool, withLinks: PropTypes.bool, withToggles: PropTypes.oneOfType([ PropTypes.bool, PropTypes.shape({ selectAll: togglesSelectAllPropTypes, }), ]), } // Defines the default values for not passing a certain prop SmartDataTable.defaultProps = { className: '', dataKey: constants.DEFAULT_DATA_KEY, dataKeyResolver: null, dataRequestOptions: {}, dataSampling: 0, dynamic: false, emptyTable: null, filterValue: '', headers: {}, hideUnordered: false, loader: null, name: 'reactsmartdatatable', onRowClick: () => null, orderedHeaders: [], paginator: Paginator, parseBool: false, parseImg: false, perPage: 0, sortable: false, withFooter: false, withHeader: true, withLinks: false, withToggles: false, } export default SmartDataTable
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { MaintenanceConfigurations } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { ContainerServiceClient } from "../containerServiceClient"; import { MaintenanceConfiguration, MaintenanceConfigurationsListByManagedClusterNextOptionalParams, MaintenanceConfigurationsListByManagedClusterOptionalParams, MaintenanceConfigurationsListByManagedClusterResponse, MaintenanceConfigurationsGetOptionalParams, MaintenanceConfigurationsGetResponse, MaintenanceConfigurationsCreateOrUpdateOptionalParams, MaintenanceConfigurationsCreateOrUpdateResponse, MaintenanceConfigurationsDeleteOptionalParams, MaintenanceConfigurationsListByManagedClusterNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing MaintenanceConfigurations operations. */ export class MaintenanceConfigurationsImpl implements MaintenanceConfigurations { private readonly client: ContainerServiceClient; /** * Initialize a new instance of the class MaintenanceConfigurations class. * @param client Reference to the service client */ constructor(client: ContainerServiceClient) { this.client = client; } /** * Gets a list of maintenance configurations in the specified managed cluster. * @param resourceGroupName The name of the resource group. * @param resourceName The name of the managed cluster resource. * @param options The options parameters. */ public listByManagedCluster( resourceGroupName: string, resourceName: string, options?: MaintenanceConfigurationsListByManagedClusterOptionalParams ): PagedAsyncIterableIterator<MaintenanceConfiguration> { const iter = this.listByManagedClusterPagingAll( resourceGroupName, resourceName, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listByManagedClusterPagingPage( resourceGroupName, resourceName, options ); } }; } private async *listByManagedClusterPagingPage( resourceGroupName: string, resourceName: string, options?: MaintenanceConfigurationsListByManagedClusterOptionalParams ): AsyncIterableIterator<MaintenanceConfiguration[]> { let result = await this._listByManagedCluster( resourceGroupName, resourceName, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listByManagedClusterNext( resourceGroupName, resourceName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listByManagedClusterPagingAll( resourceGroupName: string, resourceName: string, options?: MaintenanceConfigurationsListByManagedClusterOptionalParams ): AsyncIterableIterator<MaintenanceConfiguration> { for await (const page of this.listByManagedClusterPagingPage( resourceGroupName, resourceName, options )) { yield* page; } } /** * Gets a list of maintenance configurations in the specified managed cluster. * @param resourceGroupName The name of the resource group. * @param resourceName The name of the managed cluster resource. * @param options The options parameters. */ private _listByManagedCluster( resourceGroupName: string, resourceName: string, options?: MaintenanceConfigurationsListByManagedClusterOptionalParams ): Promise<MaintenanceConfigurationsListByManagedClusterResponse> { return this.client.sendOperationRequest( { resourceGroupName, resourceName, options }, listByManagedClusterOperationSpec ); } /** * Gets the specified maintenance configuration of a managed cluster. * @param resourceGroupName The name of the resource group. * @param resourceName The name of the managed cluster resource. * @param configName The name of the maintenance configuration. * @param options The options parameters. */ get( resourceGroupName: string, resourceName: string, configName: string, options?: MaintenanceConfigurationsGetOptionalParams ): Promise<MaintenanceConfigurationsGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, resourceName, configName, options }, getOperationSpec ); } /** * Creates or updates a maintenance configuration in the specified managed cluster. * @param resourceGroupName The name of the resource group. * @param resourceName The name of the managed cluster resource. * @param configName The name of the maintenance configuration. * @param parameters The maintenance configuration to create or update. * @param options The options parameters. */ createOrUpdate( resourceGroupName: string, resourceName: string, configName: string, parameters: MaintenanceConfiguration, options?: MaintenanceConfigurationsCreateOrUpdateOptionalParams ): Promise<MaintenanceConfigurationsCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, resourceName, configName, parameters, options }, createOrUpdateOperationSpec ); } /** * Deletes a maintenance configuration. * @param resourceGroupName The name of the resource group. * @param resourceName The name of the managed cluster resource. * @param configName The name of the maintenance configuration. * @param options The options parameters. */ delete( resourceGroupName: string, resourceName: string, configName: string, options?: MaintenanceConfigurationsDeleteOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, resourceName, configName, options }, deleteOperationSpec ); } /** * ListByManagedClusterNext * @param resourceGroupName The name of the resource group. * @param resourceName The name of the managed cluster resource. * @param nextLink The nextLink from the previous successful call to the ListByManagedCluster method. * @param options The options parameters. */ private _listByManagedClusterNext( resourceGroupName: string, resourceName: string, nextLink: string, options?: MaintenanceConfigurationsListByManagedClusterNextOptionalParams ): Promise<MaintenanceConfigurationsListByManagedClusterNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, resourceName, nextLink, options }, listByManagedClusterNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const listByManagedClusterOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/managedClusters/{resourceName}/maintenanceConfigurations", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.MaintenanceConfigurationListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.resourceName ], headerParameters: [Parameters.accept], serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/managedClusters/{resourceName}/maintenanceConfigurations/{configName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.MaintenanceConfiguration }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.resourceName, Parameters.configName ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/managedClusters/{resourceName}/maintenanceConfigurations/{configName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.MaintenanceConfiguration }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.parameters4, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.resourceName, Parameters.configName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.ContainerService/managedClusters/{resourceName}/maintenanceConfigurations/{configName}", httpMethod: "DELETE", responses: { 200: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.resourceName, Parameters.configName ], headerParameters: [Parameters.accept], serializer }; const listByManagedClusterNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.MaintenanceConfigurationListResult }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.resourceName, Parameters.nextLink ], headerParameters: [Parameters.accept], serializer };
the_stack
import './i18n'; import React from 'react'; import { debounce, isEqual, omit } from 'lodash'; import ReactDOM from 'react-dom'; import { Async as _Async, AsyncProps, FieldFeedback, FieldFeedbacks, FormWithConstraints } from 'react-form-with-constraints'; import { DisplayFields } from 'react-form-with-constraints-tools'; import { Trans, WithTranslation, withTranslation } from 'react-i18next'; import { Gender } from './Gender'; import { Loader } from './Loader'; import './index.html'; import './style.css'; function wait(ms: number) { return new Promise<void>(resolve => setTimeout(resolve, ms)); } async function checkUsernameAvailability(value: string) { console.log('checkUsernameAvailability'); await wait(1000); return !['john', 'paul', 'george', 'ringo'].includes(value.toLowerCase()); } // Async with a default React component for pending state function Async<T>({ promise, then, catch: _catch }: AsyncProps<T>) { return <_Async promise={promise} pending={<Loader />} then={then} catch={_catch} />; } const VALIDATE_DEBOUNCE_WAIT = 1000; interface Props extends WithTranslation {} interface State { language: string; firstName: string; lastName: string; username: string; email: string; gender?: Gender; age: string; phone: string; favoriteColor?: string; isEmployed?: boolean; notes: string; hasWebsite?: boolean; website: string; password: string; passwordConfirm: string; signUpButtonDisabled: boolean; resetButtonDisabled: boolean; } class SignUp extends React.Component<Props, State> { form: FormWithConstraints | null = null; passwordInput: HTMLInputElement | null = null; state: State = this.getInitialState(); private getInitialState() { return { // en-US => en, fr-FR => fr // eslint-disable-next-line react/destructuring-assignment language: this.props.i18n.language.slice(0, 2), firstName: '', lastName: '', username: '', email: '', gender: undefined, age: '', phone: '', favoriteColor: undefined, isEmployed: undefined, notes: '', hasWebsite: undefined, website: '', password: '', passwordConfirm: '', signUpButtonDisabled: false, resetButtonDisabled: true }; } // eslint-disable-next-line react/sort-comp handleChange = async ( { target }: React.ChangeEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>, _debounce = true ) => { await this._handleChange(target, _debounce, true); }; _handleChange = async ( target: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement, _debounce: boolean, forceValidateFields: boolean ) => { const value = target.type === 'checkbox' ? (target as HTMLInputElement).checked : target.value; // FIXME [Computed property key names should not be widened](https://github.com/Microsoft/TypeScript/issues/13948) // @ts-ignore this.setState({ [target.name as keyof State]: value }); await this.validateFields(target, _debounce, forceValidateFields); }; handleBlur = async ({ target }: React.FocusEvent<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement>) => { await this._handleChange(target, false, false); }; handleLanguageChange = ({ target }: React.ChangeEvent<HTMLSelectElement>) => { // eslint-disable-next-line react/destructuring-assignment this.props.i18n.changeLanguage(target.value); // FIXME [Computed property key names should not be widened](https://github.com/Microsoft/TypeScript/issues/13948) // @ts-ignore this.setState({ [target.name as keyof State]: target.value }); }; private shouldDisableResetButton(state: State) { const omitList = ['signUpButtonDisabled', 'resetButtonDisabled']; return ( isEqual(omit(this.getInitialState(), omitList), omit(state, omitList)) && !this.form!.hasFeedbacks() ); } async validateFieldsWithoutDebounce( target: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement, forceValidateFields: boolean ) { await (forceValidateFields ? this.form!.validateFields(target) : this.form!.validateFieldsWithoutFeedback(target)); this.setState(prevState => ({ signUpButtonDisabled: !this.form!.isValid(), resetButtonDisabled: this.shouldDisableResetButton(prevState) })); } validateFieldsWithDebounce = debounce(this.validateFieldsWithoutDebounce, VALIDATE_DEBOUNCE_WAIT); previousValidateFields: string | undefined; async validateFields( target: HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement, _debounce: boolean, forceValidateFields: boolean ) { // Flush the previous debounce if input is not the same otherwise validateFields(input2) will overwrite validateFields(input1) // if the user changes input2 before validateFields(input1) is called if (this.previousValidateFields !== target.name) { this.validateFieldsWithDebounce.flush(); } this.previousValidateFields = target.name; if (forceValidateFields) this.form!.resetFields(target); await (_debounce ? this.validateFieldsWithDebounce(target, forceValidateFields) : this.validateFieldsWithoutDebounce(target, forceValidateFields)); } handleHasWebsiteChange = (e: React.ChangeEvent<HTMLInputElement>) => { const hasWebsite = e.target.checked; if (!hasWebsite) { // Reset this.state.website if it was previously filled this.setState({ website: '' }); } this.handleChange(e); }; handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => { e.preventDefault(); await this.form!.validateForm(); const formIsValid = this.form!.isValid(); this.setState(prevState => ({ signUpButtonDisabled: !formIsValid, resetButtonDisabled: this.shouldDisableResetButton(prevState) })); if (formIsValid) { alert(`Valid form\n\nthis.state =\n${JSON.stringify(this.state, null, 2)}`); } }; handleReset = () => { this.setState(this.getInitialState()); this.form!.resetFields(); this.setState({ resetButtonDisabled: true }); }; render() { const { t } = this.props; const { language, firstName, lastName, username, email, gender, age, phone, favoriteColor, isEmployed, notes, hasWebsite, website, password, passwordConfirm, signUpButtonDisabled, resetButtonDisabled } = this.state; const Color = { Red: t('Red'), Orange: t('Orange'), Yellow: t('Yellow'), Green: t('Green'), Blue: t('Blue'), Indigo: t('Indigo'), Violet: t('Violet') }; const colorKeys = Object.keys(Color) as (keyof typeof Color)[]; return ( <> <label> {t('Language:')}{' '} <select name="language" value={language} onChange={this.handleLanguageChange}> <option value="en">{t('English')}</option> <option value="fr">{t('French')}</option> </select> </label> <br /> <br /> <Trans>Note: each field is debounced with a 1s delay</Trans> <br /> <br /> <FormWithConstraints ref={formWithConstraints => (this.form = formWithConstraints)} onSubmit={this.handleSubmit} noValidate > <div> <label htmlFor="first-name">{t('First Name')}</label> <input name="firstName" id="first-name" value={firstName} onChange={this.handleChange} onBlur={this.handleBlur} required minLength={3} /> <FieldFeedbacks for="firstName"> <FieldFeedback when="tooShort">{t('Too short')}</FieldFeedback> <FieldFeedback when="*" /> <FieldFeedback when="valid">{t('Looks good!')}</FieldFeedback> </FieldFeedbacks> </div> <div> <label htmlFor="last-name">{t('Last Name')}</label> <input name="lastName" id="last-name" value={lastName} onChange={this.handleChange} onBlur={this.handleBlur} required minLength={3} /> <FieldFeedbacks for="lastName"> <FieldFeedback when="tooShort">{t('Too short')}</FieldFeedback> <FieldFeedback when="*" /> <FieldFeedback when="valid">{t('Looks good!')}</FieldFeedback> </FieldFeedbacks> </div> <div> <label htmlFor="username"> <Trans> Username <small>(already taken: john, paul, george, ringo)</small> </Trans> </label> <input name="username" id="username" value={username} onChange={this.handleChange} onBlur={this.handleBlur} required minLength={3} /> <FieldFeedbacks for="username"> <FieldFeedback when="tooShort">{t('Too short')}</FieldFeedback> <FieldFeedback when="*" /> <Async promise={checkUsernameAvailability} then={available => available ? ( <FieldFeedback key="1" info style={{ color: 'green' }}> {t('Username available')} </FieldFeedback> ) : ( <FieldFeedback key="2"> {t('Username already taken, choose another')} </FieldFeedback> ) } /> <FieldFeedback when="valid">{t('Looks good!')}</FieldFeedback> </FieldFeedbacks> </div> <div> <label htmlFor="email">{t('Email')}</label> <input type="email" name="email" id="email" value={email} onChange={this.handleChange} onBlur={this.handleBlur} required minLength={5} /> <FieldFeedbacks for="email"> <FieldFeedback when="tooShort">{t('Too short')}</FieldFeedback> <FieldFeedback when="*" /> <FieldFeedback when="valid">{t('Looks good!')}</FieldFeedback> </FieldFeedbacks> </div> <div> <label>{t('Gender')}</label> <label> <input type="radio" name="gender" value={Gender.Male} checked={gender === Gender.Male} onChange={this.handleChange} onBlur={this.handleBlur} required /> {t('Male')} </label> <label> <input type="radio" name="gender" value={Gender.Female} checked={gender === Gender.Female} onChange={this.handleChange} onBlur={this.handleBlur} /> {t('Female')} </label> <FieldFeedbacks for="gender"> <FieldFeedback when="*" /> </FieldFeedbacks> </div> <div> <label htmlFor="age">{t('Age')}</label> <input type="number" name="age" id="age" value={age} onChange={this.handleChange} onBlur={this.handleBlur} required /> <FieldFeedbacks for="age"> <FieldFeedback when="*" /> <FieldFeedback when={value => Number(value) < 18}> {t('Sorry, you must be at least 18 years old')} </FieldFeedback> <FieldFeedback when={value => Number(value) < 19} warning> {t('Hmm, you seem a bit young...')} </FieldFeedback> <FieldFeedback when="valid">{t('Looks good!')}</FieldFeedback> </FieldFeedbacks> </div> <div> <label htmlFor="phone">{t('Phone number')}</label> <input type="tel" name="phone" id="phone" value={phone} onChange={this.handleChange} onBlur={this.handleBlur} required /> <FieldFeedbacks for="phone"> <FieldFeedback when="*" /> <FieldFeedback when={value => !/^\d{10}$/.test(value)}> {t('Invalid phone number, must be 10 digits')} </FieldFeedback> <FieldFeedback when="valid">{t('Looks good!')}</FieldFeedback> </FieldFeedbacks> </div> <div> <label> {t('Favorite Color')} <br /> {/* https://github.com/facebook/react/issues/4085#issuecomment-262990423 */} <select name="favoriteColor" value={favoriteColor || ''} onChange={this.handleChange} onBlur={this.handleBlur} required > <option value="" disabled> {t('Select a color...')} </option> {colorKeys.map(colorKey => ( <option value={colorKey} key={colorKey}> {Color[colorKey]} </option> ))} </select> </label> <FieldFeedbacks for="favoriteColor"> <FieldFeedback when="*" /> <FieldFeedback when="valid">{t('Looks good!')}</FieldFeedback> </FieldFeedbacks> </div> {favoriteColor && ( <div style={{ height: 80, width: 200, backgroundColor: favoriteColor }} /> )} <div> <label> <input type="checkbox" name="isEmployed" checked={isEmployed || false} onChange={this.handleChange} onBlur={this.handleBlur} /> {t('Employed')} </label> </div> <div> <label htmlFor="notes">{t('Notes')}</label> <textarea name="notes" id="notes" value={notes} onChange={this.handleChange} onBlur={this.handleBlur} /> </div> <div> <label> <input type="checkbox" name="hasWebsite" checked={hasWebsite || false} onChange={this.handleHasWebsiteChange} onBlur={this.handleBlur} /> {t('Do you have a website?')} </label> </div> {hasWebsite && ( <div> <label htmlFor="website">{t('Website')}</label> <input type="url" name="website" id="website" value={website} onChange={this.handleChange} onBlur={this.handleBlur} required minLength={3} /> <FieldFeedbacks for="website"> <FieldFeedback when="*" /> <FieldFeedback when="valid">{t('Looks good!')}</FieldFeedback> </FieldFeedbacks> </div> )} <div> <label htmlFor="password">{t('Password')}</label> <input type="password" name="password" id="password" ref={passwordInput => (this.passwordInput = passwordInput)} value={password} onChange={this.handleChange} onBlur={this.handleBlur} required pattern=".{5,}" /> <FieldFeedbacks for="password"> <FieldFeedback when="valueMissing" /> <FieldFeedback when="patternMismatch"> {t('Should be at least 5 characters long')} </FieldFeedback> <FieldFeedback when={value => !/\d/.test(value)} warning> {t('Should contain numbers')} </FieldFeedback> <FieldFeedback when={value => !/[a-z]/.test(value)} warning> {t('Should contain small letters')} </FieldFeedback> <FieldFeedback when={value => !/[A-Z]/.test(value)} warning> {t('Should contain capital letters')} </FieldFeedback> <FieldFeedback when={value => !/\W/.test(value)} warning> {t('Should contain special characters')} </FieldFeedback> <FieldFeedback when="valid">{t('Looks good!')}</FieldFeedback> </FieldFeedbacks> </div> <div> <label htmlFor="password-confirm">{t('Confirm Password')}</label> <input type="password" name="passwordConfirm" id="password-confirm" value={passwordConfirm} onChange={this.handleChange} onBlur={this.handleBlur} /> <FieldFeedbacks for="passwordConfirm"> <FieldFeedback when={value => value !== this.passwordInput!.value}> {t('Not the same password')} </FieldFeedback> </FieldFeedbacks> </div> <button type="submit" disabled={signUpButtonDisabled}> {t('Sign Up')} </button> <button type="button" onClick={this.handleReset} disabled={resetButtonDisabled}> {t('Reset')} </button> <div> <pre>this.state = {JSON.stringify(this.state, null, 2)}</pre> </div> <pre> <small> Fields = <DisplayFields /> </small> </pre> </FormWithConstraints> </> ); } } const SignUpTranslated = withTranslation()(SignUp); ReactDOM.render(<SignUpTranslated />, document.getElementById('app'));
the_stack
import { vec3 } from 'gl-matrix'; import Scene from '../../scene'; import Shader from '../../gl/shader'; import ClientBuffer from '../../gl/clientbuffer'; import Texture from '../../texture'; import ParticleEmitter2Object from './particleemitter2object'; import RibbonEmitterObject from './ribbonemitterobject'; import EventObjectEmitterObject from './eventobjectemitterobject'; import MdxModelInstance from './modelinstance'; import ParticleEmitter2 from './particleemitter2'; import RibbonEmitter from './ribbonemitter'; import EventObjectSplEmitter from './eventobjectsplemitter'; import EventObjectUbrEmitter from './eventobjectubremitter'; import Particle2 from './particle2'; import Ribbon from './ribbon'; import EventObjectSplUbr from './eventobjectsplubr'; import MdxTexture from './texture'; import { HeadOrTail } from '../../../parsers/mdlx/particleemitter2'; import { MdxHandlerObject } from './handler'; const locationHeap = vec3.create(); const startHeap = vec3.create(); const endHeap = vec3.create(); // The total storage that emitted objects can use. // This is enough to support all of the MDX geometry emitters. // The memory layout is the same as this C struct: // // struct { // float p0[3] // float p1[3] // float p2[3] // float p3[3] // float health // byte color[4] // byte tail // byte leftRightTop[3] // } // export const BYTES_PER_OBJECT = 60; export const FLOATS_PER_OBJECT = BYTES_PER_OBJECT >> 2; // Offsets into the emitted object structure. export const BYTE_OFFSET_P0 = 0; export const BYTE_OFFSET_P1 = 12; export const BYTE_OFFSET_P2 = 24; export const BYTE_OFFSET_P3 = 36; export const BYTE_OFFSET_HEALTH = 48; export const BYTE_OFFSET_COLOR = 52; export const BYTE_OFFSET_TAIL = 56; export const BYTE_OFFSET_LEFT_RIGHT_TOP = 57; // Offset aliases. export const FLOAT_OFFSET_P0 = BYTE_OFFSET_P0 >> 2; export const FLOAT_OFFSET_P1 = BYTE_OFFSET_P1 >> 2; export const FLOAT_OFFSET_P2 = BYTE_OFFSET_P2 >> 2; export const FLOAT_OFFSET_P3 = BYTE_OFFSET_P3 >> 2; export const FLOAT_OFFSET_HEALTH = BYTE_OFFSET_HEALTH >> 2; export const BYTE_OFFSET_TEAM_COLOR = BYTE_OFFSET_LEFT_RIGHT_TOP; // Emitter types export const EMITTER_PARTICLE2 = 0; export const EMITTER_RIBBON = 1; export const EMITTER_SPLAT = 2; export const EMITTER_UBERSPLAT = 3; // Offsets for overriding emitter textures using setResource(). export const EMITTER_PARTICLE2_TEXTURE_OFFSET = 1000; export const EMITTER_EVENT_TEXTURE_OFFSET = 10000; // The game scales the emission rate of particle emitters depending on the particles setting. // High seems to double the emission. export const SETTING_PARTICLES_HIGH = 2; export type GeometryEmitter = ParticleEmitter2 | RibbonEmitter | EventObjectSplEmitter | EventObjectUbrEmitter; export type GeometryEmitterObject = ParticleEmitter2Object | RibbonEmitterObject | EventObjectEmitterObject; function bindParticleEmitter2Buffer(emitter: ParticleEmitter2, buffer: ClientBuffer): void { const instance = <MdxModelInstance>emitter.instance; const objects = <Particle2[]>emitter.objects; const byteView = <Uint8Array>buffer.byteView; const floatView = <Float32Array>buffer.floatView; const emitterObject = <ParticleEmitter2Object>emitter.emitterObject; const modelSpace = emitterObject.modelSpace; const tailLength = emitterObject.tailLength; const node = emitter.node; const teamColor = instance.teamColor; let offset = 0; for (const object of objects) { const byteOffset = offset * BYTES_PER_OBJECT; const floatOffset = offset * FLOATS_PER_OBJECT; const p0Offset = floatOffset + FLOAT_OFFSET_P0; let location = object.location; const scale = object.scale; const tail = object.tail; if (tail === HeadOrTail.Head) { // If this is a model space emitter, the location is in local space, so convert it to world space. if (modelSpace) { location = vec3.transformMat4(locationHeap, location, node.worldMatrix); } floatView[p0Offset + 0] = location[0]; floatView[p0Offset + 1] = location[1]; floatView[p0Offset + 2] = location[2]; // Used to rotate XY particles to face their velocity on the XY plane. floatView[p0Offset + 3] = object.facing; } else { const velocity = object.velocity; let start = startHeap; let end = location; start[0] = end[0] - tailLength * velocity[0]; start[1] = end[1] - tailLength * velocity[1]; start[2] = end[2] - tailLength * velocity[2]; // If this is a model space emitter, the start and end are in local space, so convert them to world space. if (modelSpace) { start = vec3.transformMat4(start, start, node.worldMatrix); end = vec3.transformMat4(endHeap, end, node.worldMatrix); } floatView[p0Offset + 0] = start[0]; floatView[p0Offset + 1] = start[1]; floatView[p0Offset + 2] = start[2]; floatView[p0Offset + 3] = end[0]; floatView[p0Offset + 4] = end[1]; floatView[p0Offset + 5] = end[2]; } floatView[p0Offset + 6] = scale[0]; floatView[p0Offset + 7] = scale[0]; floatView[p0Offset + 8] = scale[0]; floatView[floatOffset + FLOAT_OFFSET_HEALTH] = object.health; byteView[byteOffset + BYTE_OFFSET_TAIL] = tail; byteView[byteOffset + BYTE_OFFSET_TEAM_COLOR] = teamColor; offset += 1; } } function bindParticleEmitter2Shader(emitter: ParticleEmitter2, shader: Shader): void { const instance = <MdxModelInstance>emitter.instance; const textureOverrides = instance.textureOverrides; const scene = <Scene>instance.scene; const camera = scene.camera; const emitterObject = <ParticleEmitter2Object>emitter.emitterObject; const model = emitterObject.model; const viewer = model.viewer; const gl = viewer.gl; const mdxCache = <MdxHandlerObject>viewer.sharedCache.get('mdx'); const uniforms = shader.uniforms; const colors = emitterObject.colors; const intervals = emitterObject.intervals; const replaceable = emitterObject.replaceableId; let vectors; let mdxTexture = <MdxTexture>emitterObject.internalTexture; gl.blendFunc(emitterObject.blendSrc, emitterObject.blendDst); gl.uniform1f(uniforms['u_filterMode'], emitterObject.filterMode); // Determine where this texture is coming from. // This is to get the texture wrap modes. // The texture is either a replaceable in which case it's stored internally, a team color in which case it's stored in the handler, or a reference to one of the model textures. if (emitterObject.internalTexture) { mdxTexture = emitterObject.internalTexture; } else if (replaceable === 1) { mdxTexture = mdxCache.teamColors[instance.teamColor]; } else if (replaceable === 2) { mdxTexture = mdxCache.teamGlows[instance.teamColor]; } else { mdxTexture = model.textures[emitterObject.textureId]; } // Now get the actual texture itself. // First check if there is an override for this particle emitter. let texture: Texture | null | undefined = textureOverrides.get(EMITTER_PARTICLE2_TEXTURE_OFFSET + emitterObject.index); if (!texture) { // Next check if there is an override for model textures if this is one. if (replaceable === 0) { texture = textureOverrides.get(emitterObject.textureId); } // If there is still no override, get it from the existing texture object. if (!texture) { texture = mdxTexture.texture; } } viewer.webgl.bindTextureAndWrap(texture, 0, mdxTexture.wrapS, mdxTexture.wrapT); // Choose between a default rectangle or a billboarded one if (emitterObject.xYQuad) { vectors = camera.vectors; } else { vectors = camera.billboardedVectors; } gl.uniform1f(uniforms['u_lifeSpan'], emitterObject.lifeSpan); gl.uniform1f(uniforms['u_timeMiddle'], emitterObject.timeMiddle); gl.uniform1f(uniforms['u_columns'], emitterObject.columns); gl.uniform1f(uniforms['u_rows'], emitterObject.rows); gl.uniform1f(uniforms['u_teamColored'], emitterObject.teamColored); gl.uniform3fv(uniforms['u_intervals[0]'], intervals[0]); gl.uniform3fv(uniforms['u_intervals[1]'], intervals[1]); gl.uniform3fv(uniforms['u_intervals[2]'], intervals[2]); gl.uniform3fv(uniforms['u_intervals[3]'], intervals[3]); gl.uniform4fv(uniforms['u_colors[0]'], colors[0]); gl.uniform4fv(uniforms['u_colors[1]'], colors[1]); gl.uniform4fv(uniforms['u_colors[2]'], colors[2]); gl.uniform3fv(uniforms['u_scaling'], emitterObject.scaling); if (emitterObject.head) { gl.uniform3fv(uniforms['u_vertices[0]'], vectors[0]); gl.uniform3fv(uniforms['u_vertices[1]'], vectors[1]); gl.uniform3fv(uniforms['u_vertices[2]'], vectors[2]); gl.uniform3fv(uniforms['u_vertices[3]'], vectors[3]); } if (emitterObject.tail) { gl.uniform3fv(uniforms['u_cameraZ'], camera.directionZ); } } function bindRibbonEmitterBuffer(emitter: RibbonEmitter, buffer: ClientBuffer): void { let object = <Ribbon>emitter.first; const byteView = <Uint8Array>buffer.byteView; const floatView = <Float32Array>buffer.floatView; const emitterObject = <RibbonEmitterObject>emitter.emitterObject; const columns = emitterObject.columns; const alive = emitter.alive; const chainLengthFactor = 1 / (alive - 1); let offset = 0; while (object.next) { const next = object.next.vertices; const byteOffset = offset * BYTES_PER_OBJECT; const floatOffset = offset * FLOATS_PER_OBJECT; const p0Offset = floatOffset + FLOAT_OFFSET_P0; const colorOffset = byteOffset + BYTE_OFFSET_COLOR; const leftRightTopOffset = byteOffset + BYTE_OFFSET_LEFT_RIGHT_TOP; const left = ((object.slot % columns) + (1 - (offset * chainLengthFactor) - chainLengthFactor)) / columns; const top = object.slot / columns; const right = left + chainLengthFactor; const vertices = object.vertices; const color = object.color; floatView[p0Offset + 0] = vertices[0]; floatView[p0Offset + 1] = vertices[1]; floatView[p0Offset + 2] = vertices[2]; floatView[p0Offset + 3] = vertices[3]; floatView[p0Offset + 4] = vertices[4]; floatView[p0Offset + 5] = vertices[5]; floatView[p0Offset + 6] = next[3]; floatView[p0Offset + 7] = next[4]; floatView[p0Offset + 8] = next[5]; floatView[p0Offset + 9] = next[0]; floatView[p0Offset + 10] = next[1]; floatView[p0Offset + 11] = next[2]; byteView[colorOffset + 0] = color[0]; byteView[colorOffset + 1] = color[1]; byteView[colorOffset + 2] = color[2]; byteView[colorOffset + 3] = color[3]; byteView[leftRightTopOffset + 0] = left * 255; byteView[leftRightTopOffset + 1] = right * 255; byteView[leftRightTopOffset + 2] = top * 255; object = object.next; offset += 1; } } function bindRibbonEmitterShader(emitter: RibbonEmitter, shader: Shader): void { const textureOverrides = emitter.instance.textureOverrides; const emitterObject = <RibbonEmitterObject>emitter.emitterObject; const layer = emitterObject.layer; const model = emitterObject.model; const gl = model.viewer.gl; const uniforms = shader.uniforms; const texture = model.textures[layer.textureId]; const actualTexture = textureOverrides.get(layer.textureId) || texture.texture; layer.bind(shader); gl.uniform1f(uniforms['u_filterMode'], layer.filterMode); model.viewer.webgl.bindTextureAndWrap(actualTexture, 0, texture.wrapS, texture.wrapT); gl.uniform1f(uniforms['u_columns'], emitterObject.columns); gl.uniform1f(uniforms['u_rows'], emitterObject.rows); } function bindEventObjectEmitterBuffer(emitter: EventObjectSplEmitter | EventObjectUbrEmitter, buffer: ClientBuffer): void { const objects = <EventObjectSplUbr[]>emitter.objects; const floatView = <Float32Array>buffer.floatView; let offset = 0; for (const object of objects) { const floatOffset = offset * FLOATS_PER_OBJECT; const p0Offset = floatOffset + FLOAT_OFFSET_P0; const vertices = object.vertices; floatView[p0Offset + 0] = vertices[0]; floatView[p0Offset + 1] = vertices[1]; floatView[p0Offset + 2] = vertices[2]; floatView[p0Offset + 3] = vertices[3]; floatView[p0Offset + 4] = vertices[4]; floatView[p0Offset + 5] = vertices[5]; floatView[p0Offset + 6] = vertices[6]; floatView[p0Offset + 7] = vertices[7]; floatView[p0Offset + 8] = vertices[8]; floatView[p0Offset + 9] = vertices[9]; floatView[p0Offset + 10] = vertices[10]; floatView[p0Offset + 11] = vertices[11]; floatView[floatOffset + FLOAT_OFFSET_HEALTH] = object.health; offset += 1; } } function bindEventObjectSplEmitterShader(emitter: EventObjectSplEmitter, shader: Shader): void { const textureOverrides = emitter.instance.textureOverrides; const emitterObject = <EventObjectEmitterObject>emitter.emitterObject; const intervalTimes = emitterObject.intervalTimes; const intervals = emitterObject.intervals; const colors = emitterObject.colors; const model = emitterObject.model; const gl = model.viewer.gl; const uniforms = shader.uniforms; const texture = <MdxTexture>emitterObject.internalTexture; const actualTexture = textureOverrides.get(EMITTER_EVENT_TEXTURE_OFFSET + emitterObject.index) || texture.texture; gl.blendFunc(emitterObject.blendSrc, emitterObject.blendDst); model.viewer.webgl.bindTextureAndWrap(actualTexture, 0, texture.wrapS, texture.wrapT); gl.uniform1f(uniforms['u_lifeSpan'], emitterObject.lifeSpan); gl.uniform1f(uniforms['u_columns'], emitterObject.columns); gl.uniform1f(uniforms['u_rows'], emitterObject.rows); // 3 because the uniform is shared with UBR, which has 3 values. gl.uniform3f(uniforms['u_intervalTimes'], intervalTimes[0], intervalTimes[1], 0); gl.uniform3fv(uniforms['u_intervals[0]'], intervals[0]); gl.uniform3fv(uniforms['u_intervals[1]'], intervals[1]); gl.uniform4fv(uniforms['u_colors[0]'], colors[0]); gl.uniform4fv(uniforms['u_colors[1]'], colors[1]); gl.uniform4fv(uniforms['u_colors[2]'], colors[2]); } function bindEventObjectUbrEmitterShader(emitter: EventObjectUbrEmitter, shader: Shader): void { const textureOverrides = emitter.instance.textureOverrides; const emitterObject = <EventObjectEmitterObject>emitter.emitterObject; const intervalTimes = emitterObject.intervalTimes; const colors = emitterObject.colors; const model = emitterObject.model; const viewer = model.viewer; const gl = viewer.gl; const uniforms = shader.uniforms; const texture = <MdxTexture>emitterObject.internalTexture; const actualTexture = textureOverrides.get(EMITTER_EVENT_TEXTURE_OFFSET + emitterObject.index) || texture.texture; gl.blendFunc(emitterObject.blendSrc, emitterObject.blendDst); model.viewer.webgl.bindTextureAndWrap(actualTexture, 0, texture.wrapS, texture.wrapT); gl.uniform1f(uniforms['u_lifeSpan'], emitterObject.lifeSpan); gl.uniform1f(uniforms['u_columns'], emitterObject.columns); gl.uniform1f(uniforms['u_rows'], emitterObject.rows); gl.uniform3fv(uniforms['u_intervalTimes'], intervalTimes); gl.uniform4fv(uniforms['u_colors[0]'], colors[0]); gl.uniform4fv(uniforms['u_colors[1]'], colors[1]); gl.uniform4fv(uniforms['u_colors[2]'], colors[2]); } export function renderEmitter(emitter: GeometryEmitter, shader: Shader): void { let alive = emitter.alive; const emitterObject = <GeometryEmitterObject>emitter.emitterObject; const emitterType = emitterObject.geometryEmitterType; if (emitterType === EMITTER_RIBBON) { alive -= 1; } if (alive > 0) { const viewer = emitter.instance.model.viewer; const buffer = viewer.buffer; const gl = viewer.gl; const instancedArrays = <ANGLE_instanced_arrays>viewer.webgl.extensions['ANGLE_instanced_arrays']; const size = alive * BYTES_PER_OBJECT; const attribs = shader.attribs; buffer.reserve(size); if (emitterType === EMITTER_PARTICLE2) { bindParticleEmitter2Buffer(<ParticleEmitter2>emitter, buffer); bindParticleEmitter2Shader(<ParticleEmitter2>emitter, shader); } else if (emitterType === EMITTER_RIBBON) { bindRibbonEmitterBuffer(<RibbonEmitter>emitter, buffer); bindRibbonEmitterShader(<RibbonEmitter>emitter, shader); } else if (emitterType === EMITTER_SPLAT) { bindEventObjectEmitterBuffer(<EventObjectSplEmitter>emitter, buffer); bindEventObjectSplEmitterShader(<EventObjectSplEmitter>emitter, shader); } else { bindEventObjectEmitterBuffer(<EventObjectUbrEmitter>emitter, buffer); bindEventObjectUbrEmitterShader(<EventObjectUbrEmitter>emitter, shader); } buffer.bindAndUpdate(size); gl.uniform1i(shader.uniforms['u_emitter'], emitterType); gl.vertexAttribPointer(attribs['a_p0'], 3, gl.FLOAT, false, BYTES_PER_OBJECT, BYTE_OFFSET_P0); gl.vertexAttribPointer(attribs['a_p1'], 3, gl.FLOAT, false, BYTES_PER_OBJECT, BYTE_OFFSET_P1); gl.vertexAttribPointer(attribs['a_p2'], 3, gl.FLOAT, false, BYTES_PER_OBJECT, BYTE_OFFSET_P2); gl.vertexAttribPointer(attribs['a_p3'], 3, gl.FLOAT, false, BYTES_PER_OBJECT, BYTE_OFFSET_P3); gl.vertexAttribPointer(attribs['a_health'], 1, gl.FLOAT, false, BYTES_PER_OBJECT, BYTE_OFFSET_HEALTH); gl.vertexAttribPointer(attribs['a_color'], 4, gl.UNSIGNED_BYTE, true, BYTES_PER_OBJECT, BYTE_OFFSET_COLOR); gl.vertexAttribPointer(attribs['a_tail'], 1, gl.UNSIGNED_BYTE, false, BYTES_PER_OBJECT, BYTE_OFFSET_TAIL); gl.vertexAttribPointer(attribs['a_leftRightTop'], 3, gl.UNSIGNED_BYTE, false, BYTES_PER_OBJECT, BYTE_OFFSET_LEFT_RIGHT_TOP); instancedArrays.drawArraysInstancedANGLE(gl.TRIANGLES, 0, 6, alive); } }
the_stack
import { EventData, Observable } from "data/observable"; import { KeyedTemplate, Length, View } from "ui/core/view"; import * as utils from "utils/utils"; import { GridViewBase, itemTemplatesProperty, orientationProperty, paddingBottomProperty, paddingLeftProperty, paddingRightProperty, paddingTopProperty, } from "./grid-view-common"; import { GridItemEventData, Orientation, ScrollEventData } from "."; export * from "./grid-view-common"; export class GridView extends GridViewBase { private _layout: UICollectionViewFlowLayout; private _dataSource: GridViewDataSource; private _delegate: UICollectionViewDelegateImpl; private _preparingCell: boolean = false; private _map: Map<GridViewCell, View>; constructor() { super(); this._map = new Map<GridViewCell, View>(); } public createNativeView() { this._layout = UICollectionViewFlowLayout.alloc().init(); this._layout.minimumLineSpacing = 0; this._layout.minimumInteritemSpacing = 0; return UICollectionView.alloc().initWithFrameCollectionViewLayout(CGRectMake(0, 0, 0, 0), this._layout); } public initNativeView() { super.initNativeView(); const nativeView: UICollectionView = this.nativeViewProtected; nativeView.backgroundColor = utils.ios.getter(UIColor, UIColor.clearColor); nativeView.registerClassForCellWithReuseIdentifier(GridViewCell.class(), this._defaultTemplate.key); nativeView.autoresizesSubviews = false; nativeView.autoresizingMask = UIViewAutoresizing.None; this._dataSource = GridViewDataSource.initWithOwner(new WeakRef(this)); nativeView.dataSource = this._dataSource; this._delegate = UICollectionViewDelegateImpl.initWithOwner(new WeakRef(this)); this._setNativeClipToBounds(); // These are needed in cases where the native view is inited after the property has been set // For example happens with Angular usage. this._updateColWidthProperty(); this._updateRowHeightProperty(); } public disposeNativeView() { this._layout = null; this._delegate = null; this._dataSource = null; super.disposeNativeView(); } public onLoaded() { super.onLoaded(); this.ios.delegate = this._delegate; } public onUnloaded() { this.ios.delegate = null; super.onUnloaded(); } get ios(): UICollectionView { return this.nativeViewProtected; } get _childrenCount(): number { return this._map.size; } get horizontalOffset(): number { return this.nativeViewProtected.contentOffset.x; } get verticalOffset(): number { return this.nativeViewProtected.contentOffset.y; } public [paddingTopProperty.getDefault](): number { return this._layout.sectionInset.top; } public [paddingTopProperty.setNative](value: Length) { this._setPadding({ top: utils.layout.toDeviceIndependentPixels(this.effectivePaddingTop) }); } public [paddingRightProperty.getDefault](): number { return this._layout.sectionInset.right; } public [paddingRightProperty.setNative](value: Length) { this._setPadding({ right: utils.layout.toDeviceIndependentPixels(this.effectivePaddingRight) }); } public [paddingBottomProperty.getDefault](): number { return this._layout.sectionInset.bottom; } public [paddingBottomProperty.setNative](value: Length) { this._setPadding({ bottom: utils.layout.toDeviceIndependentPixels(this.effectivePaddingBottom) }); } public [paddingLeftProperty.getDefault](): number { return this._layout.sectionInset.left; } public [paddingLeftProperty.setNative](value: Length) { this._setPadding({ left: utils.layout.toDeviceIndependentPixels(this.effectivePaddingLeft) }); } public [orientationProperty.getDefault](): Orientation { if (this._layout.scrollDirection === UICollectionViewScrollDirection.Horizontal) { return "horizontal"; } return "vertical"; } public [orientationProperty.setNative](value: Orientation) { if (value === "horizontal") { this._layout.scrollDirection = UICollectionViewScrollDirection.Horizontal; } else { this._layout.scrollDirection = UICollectionViewScrollDirection.Vertical; } } public [itemTemplatesProperty.getDefault](): KeyedTemplate[] { return null; } public [itemTemplatesProperty.setNative](value: KeyedTemplate[]) { this._itemTemplatesInternal = new Array<KeyedTemplate>(this._defaultTemplate); if (value) { for (const template of value) { this.ios.registerClassForCellWithReuseIdentifier(GridViewCell.class(), template.key); } this._itemTemplatesInternal = this._itemTemplatesInternal.concat(value); } this.refresh(); } public eachChildView(callback: (child: View) => boolean): void { this._map.forEach((view, key) => { callback(view); }); } public onLayout(left: number, top: number, right: number, bottom: number) { super.onLayout(left, top, right, bottom); const layout = this.ios.collectionViewLayout as UICollectionViewFlowLayout; layout.itemSize = CGSizeMake(utils.layout.toDeviceIndependentPixels(this._effectiveColWidth), utils.layout.toDeviceIndependentPixels(this._effectiveRowHeight)); this._map.forEach((childView, listViewCell) => { childView.iosOverflowSafeAreaEnabled = false; View.layoutChild(this, childView, 0, 0, this._effectiveColWidth, this._effectiveRowHeight); }); } public refresh() { // clear bindingContext when it is not observable because otherwise bindings to items won't reevaluate this.eachChildView((view) => { if (!(view.bindingContext instanceof Observable)) { view.bindingContext = null; } return true; }); if (this.isLoaded) { this.ios.reloadData(); this.requestLayout(); } } public scrollToIndex(index: number, animated: boolean = true) { this.ios.scrollToItemAtIndexPathAtScrollPositionAnimated( NSIndexPath.indexPathForItemInSection(index, 0), this.orientation === "vertical" ? UICollectionViewScrollPosition.Top : UICollectionViewScrollPosition.Left, animated, ); } public requestLayout(): void { // When preparing cell don't call super - no need to invalidate our measure when cell desiredSize is changed. if (!this._preparingCell) { super.requestLayout(); } } public measure(widthMeasureSpec: number, heightMeasureSpec: number): void { const changed = (this as any)._setCurrentMeasureSpecs(widthMeasureSpec, heightMeasureSpec); super.measure(widthMeasureSpec, heightMeasureSpec); if (changed) { this.ios.reloadData(); } } public onMeasure(widthMeasureSpec: number, heightMeasureSpec: number): void { super.onMeasure(widthMeasureSpec, heightMeasureSpec); this._map.forEach((childView: any, gridViewCell) => { View.measureChild(this, childView, childView._currentWidthMeasureSpec, childView._currentHeightMeasureSpec); }); } public _setNativeClipToBounds() { this.ios.clipsToBounds = true; } public _removeContainer(cell: GridViewCell): void { const view = cell.view; view.parent._removeView(view); this._map.delete(cell); } public _prepareCell(cell: GridViewCell, indexPath: NSIndexPath) { try { this._preparingCell = true; let view = cell.view; if (!view) { view = this._getItemTemplate(indexPath.row).createView(); } const args: GridItemEventData = { eventName: GridViewBase.itemLoadingEvent, object: this, index: indexPath.row, view, ios: cell, android: undefined, }; this.notify(args); // Get the view as some listener to the itemLoading event could have changed it // For example the angular component does this when it is a single template. view = args.view; // If cell is reused it have old content - remove it first. if (!cell.view) { cell.owner = new WeakRef(view); } else if (cell.view !== view) { this._removeContainer(cell); (cell.view.nativeView as UIView).removeFromSuperview(); cell.owner = new WeakRef(view); } this._prepareItem(view, indexPath.row); this._map.set(cell, view); if (view && !view.parent) { this._addView(view); cell.contentView.addSubview(view.ios); } this._layoutCell(view, indexPath); } finally { this._preparingCell = false; } } private _layoutCell(cellView: View, index: NSIndexPath) { if (cellView) { const widthMeasureSpec = utils.layout.makeMeasureSpec(this._effectiveColWidth, utils.layout.EXACTLY); const heightMeasureSpec = utils.layout.makeMeasureSpec(this._effectiveRowHeight, utils.layout.EXACTLY); View.measureChild(this, cellView, widthMeasureSpec, heightMeasureSpec); } } private _setPadding(newPadding: { top?: number, right?: number, bottom?: number, left?: number }) { const padding = { top: this._layout.sectionInset.top, right: this._layout.sectionInset.right, bottom: this._layout.sectionInset.bottom, left: this._layout.sectionInset.left }; // tslint:disable-next-line:prefer-object-spread const newValue = Object.assign(padding, newPadding); this._layout.sectionInset = UIEdgeInsetsFromString(`{${newValue.top},${newValue.left},${newValue.bottom},${newValue.right}}`); } } class GridViewCell extends UICollectionViewCell { public static new(): GridViewCell { return super.new() as GridViewCell; } public static class(): any { return GridViewCell; } public owner: WeakRef<View>; get view(): View { return this.owner ? this.owner.get() : null; } public willMoveToSuperview(newSuperview: UIView): void { const parent = (this.view ? this.view.parent : null) as GridView; // When inside GidView and there is no newSuperview this cell is // removed from native visual tree so we remove it from our tree too. if (parent && !newSuperview) { parent._removeContainer(this); } } } @ObjCClass(UICollectionViewDataSource) class GridViewDataSource extends NSObject implements UICollectionViewDataSource { public static initWithOwner(owner: WeakRef<GridView>): GridViewDataSource { const dataSource = GridViewDataSource.new() as GridViewDataSource; dataSource._owner = owner; return dataSource; } private _owner: WeakRef<GridView>; public numberOfSectionsInCollectionView(collectionView: UICollectionView) { return 1; } public collectionViewNumberOfItemsInSection(collectionView: UICollectionView, section: number) { const owner = this._owner.get(); return owner.items ? owner.items.length : 0; } public collectionViewCellForItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath): UICollectionViewCell { const owner = this._owner.get(); const template = owner._getItemTemplate(indexPath.row); const cell: any = collectionView.dequeueReusableCellWithReuseIdentifierForIndexPath(template.key, indexPath) || GridViewCell.new(); owner._prepareCell(cell, indexPath); const cellView: View = cell.view; if (cellView && (cellView as any).isLayoutRequired) { cellView.iosOverflowSafeAreaEnabled = false; View.layoutChild(owner, cellView, 0, 0, owner._effectiveColWidth, owner._effectiveRowHeight); } return cell; } } @ObjCClass(UICollectionViewDelegate, UICollectionViewDelegateFlowLayout) class UICollectionViewDelegateImpl extends NSObject implements UICollectionViewDelegate, UICollectionViewDelegateFlowLayout { public static initWithOwner(owner: WeakRef<GridView>): UICollectionViewDelegateImpl { const delegate = UICollectionViewDelegateImpl.new() as UICollectionViewDelegateImpl; delegate._owner = owner; return delegate; } private _owner: WeakRef<GridView>; public collectionViewWillDisplayCellForItemAtIndexPath(collectionView: UICollectionView, cell: UICollectionViewCell, indexPath: NSIndexPath) { const owner = this._owner.get(); if (indexPath.row === owner.items.length - 1) { owner.notify<EventData>({ eventName: GridViewBase.loadMoreItemsEvent, object: owner }); } if (cell.preservesSuperviewLayoutMargins) { cell.preservesSuperviewLayoutMargins = false; } if (cell.layoutMargins) { cell.layoutMargins = UIEdgeInsetsZero; } } public collectionViewDidSelectItemAtIndexPath(collectionView: UICollectionView, indexPath: NSIndexPath) { const cell = collectionView.cellForItemAtIndexPath(indexPath); const owner = this._owner.get(); owner.notify<GridItemEventData>({ eventName: GridViewBase.itemTapEvent, object: owner, index: indexPath.row, view: (cell as GridViewCell).view, ios: cell, android: undefined, }); cell.highlighted = false; return indexPath; } public scrollViewDidScroll(collectionView: UICollectionView) { const owner = this._owner.get(); owner.notify<ScrollEventData>({ object: owner, eventName: GridViewBase.scrollEvent, scrollX: owner.horizontalOffset, scrollY: owner.verticalOffset }); } }
the_stack
import { P2PCommunicationClient } from './transports/clients/P2PCommunicationClient' import { AppMetadata } from './types/beacon/AppMetadata' import { PermissionRequest } from './types/beacon/messages/PermissionRequest' import { Network } from './types/beacon/Network' import { BeaconBaseMessage } from './types/beacon/BeaconBaseMessage' import { BeaconMessageType } from './types/beacon/BeaconMessageType' import { PermissionScope } from './types/beacon/PermissionScope' import { PermissionResponse } from './types/beacon/messages/PermissionResponse' import { OperationRequest } from './types/beacon/messages/OperationRequest' import { OperationResponse } from './types/beacon/messages/OperationResponse' import { SignPayloadRequest } from './types/beacon/messages/SignPayloadRequest' import { SignPayloadResponse } from './types/beacon/messages/SignPayloadResponse' import { BroadcastRequest } from './types/beacon/messages/BroadcastRequest' import { BroadcastResponse } from './types/beacon/messages/BroadcastResponse' import { NetworkType } from './types/beacon/NetworkType' import { TezosBaseOperation } from './types/tezos/TezosBaseOperation' import { TezosOperationType } from './types/tezos/OperationTypes' import { TezosActivateAccountOperation } from './types/tezos/operations/ActivateAccount' import { TezosBallotOperation } from './types/tezos/operations/Ballot' import { TezosDelegationOperation } from './types/tezos/operations/Delegation' import { TezosDoubleBakingEvidenceOperation } from './types/tezos/operations/DoubleBakingEvidence' import { TezosBlockHeader } from './types/tezos/TezosBlockHeader' import { TezosDoubleEndorsementEvidenceOperation } from './types/tezos/operations/DoubleEndorsementEvidence' import { TezosEndorsementOperation } from './types/tezos/operations/Endorsement' import { TezosOriginationOperation } from './types/tezos/operations/Origination' import { TezosProposalOperation } from './types/tezos/operations/Proposal' import { TezosRevealOperation } from './types/tezos/operations/Reveal' import { TezosSeedNonceRevelationOperation } from './types/tezos/operations/SeedNonceRevelation' import { TezosTransactionOperation } from './types/tezos/operations/Transaction' import { MichelsonPrimitives } from './types/tezos/MichelsonPrimitives' import { TezosTransactionParameters } from './types/tezos/TezosTransactionParameters' import { Origin } from './types/Origin' import { AccountInfo, AccountIdentifier } from './types/AccountInfo' import { EncryptedExtensionMessage, ExtensionMessage } from './types/ExtensionMessage' import { ExtensionMessageTarget } from './types/ExtensionMessageTarget' import { TezosOperation } from './types/tezos/TezosOperation' import { Client } from './clients/client/Client' import { WalletClient } from './clients/wallet-client/WalletClient' import { DAppClient } from './clients/dapp-client/DAppClient' import { BeaconError } from './errors/BeaconError' import { BeaconErrorType } from './types/BeaconErrorType' import { BroadcastBeaconError } from './errors/BroadcastBeaconError' import { NetworkNotSupportedBeaconError } from './errors/NetworkNotSupportedBeaconError' import { NoAddressBeaconError } from './errors/NoAddressBeaconError' import { NoPrivateKeyBeaconError } from './errors/NoPrivateKeyBeaconError' import { NotGrantedBeaconError } from './errors/NotGrantedBeaconError' import { ParametersInvalidBeaconError } from './errors/ParametersInvalidBeaconError' import { TooManyOperationsBeaconError } from './errors/TooManyOperationsBeaconError' import { TransactionInvalidBeaconError } from './errors/TransactionInvalidBeaconError' import { UnknownBeaconError } from './errors/UnknownBeaconError' import { ErrorResponse } from './types/beacon/messages/ErrorResponse' import { TransportStatus } from './types/transport/TransportStatus' import { TransportType } from './types/transport/TransportType' import { PostMessageTransport } from './transports/PostMessageTransport' import { Transport } from './transports/Transport' import { P2PTransport } from './transports/P2PTransport' import { Storage } from './storage/Storage' import { StorageKey } from './types/storage/StorageKey' import { StorageKeyReturnDefaults } from './types/storage/StorageKeyReturnDefaults' import { StorageKeyReturnType } from './types/storage/StorageKeyReturnType' import { ExtendedP2PPairingRequest, P2PPairingRequest } from './types/P2PPairingRequest' import { ChromeStorage } from './storage/ChromeStorage' import { LocalStorage } from './storage/LocalStorage' import { getStorage } from './storage/getStorage' import { BeaconMessage } from './types/beacon/BeaconMessage' import { Serializer } from './Serializer' import { RequestPermissionInput } from './types/RequestPermissionInput' import { RequestSignPayloadInput } from './types/RequestSignPayloadInput' // import { RequestEncryptPayloadInput } from './types/RequestEncryptPayloadInput' import { RequestOperationInput } from './types/RequestOperationInput' import { RequestBroadcastInput } from './types/RequestBroadcastInput' import { PermissionResponseInput, SignPayloadResponseInput, // EncryptPayloadResponseInput, OperationResponseInput, BroadcastResponseInput, BeaconResponseInputMessage, AcknowledgeResponseInput, ErrorResponseInput } from './types/beacon/messages/BeaconResponseInputMessage' import { PermissionResponseOutput, SignPayloadResponseOutput, // EncryptPayloadResponseOutput, OperationResponseOutput, BroadcastResponseOutput, BeaconResponseOutputMessage } from './types/beacon/messages/BeaconResponseOutputMessage' import { PermissionRequestInput, SignPayloadRequestInput, // EncryptPayloadRequestInput, OperationRequestInput, BroadcastRequestInput, BeaconRequestInputMessage } from './types/beacon/messages/BeaconRequestInputMessage' import { PermissionRequestOutput, SignPayloadRequestOutput, // EncryptPayloadRequestOutput, OperationRequestOutput, BroadcastRequestOutput, BeaconRequestOutputMessage } from './types/beacon/messages/BeaconRequestOutputMessage' import { ClientOptions } from './clients/client/ClientOptions' import { DAppClientOptions } from './clients/dapp-client/DAppClientOptions' import { WalletClientOptions } from './clients/wallet-client/WalletClientOptions' import { PermissionInfo } from './types/PermissionInfo' import { SDK_VERSION, BEACON_VERSION } from './constants' import { AccountManager } from './managers/AccountManager' import { AppMetadataManager } from './managers/AppMetadataManager' import { PermissionManager } from './managers/PermissionManager' import { BeaconEvent, BeaconEventHandler, defaultEventCallbacks } from './events' import { getAddressFromPublicKey } from './utils/crypto' import { BeaconClient } from './clients/beacon-client/BeaconClient' import { BeaconClientOptions } from './clients/beacon-client/BeaconClientOptions' import { getAccountIdentifier } from './utils/get-account-identifier' import { ConnectionContext } from './types/ConnectionContext' import { Threshold } from './types/beacon/Threshold' import { PartialTezosTransactionOperation, PartialTezosOperation, PartialTezosDelegationOperation, PartialTezosOriginationOperation, PartialTezosRevealOperation } from './types/tezos/PartialTezosOperation' import { AbortedBeaconError } from './errors/AbortedBeaconError' import { ExtendedPeerInfo, PeerInfo } from './types/PeerInfo' import { availableTransports } from './utils/available-transports' import { AcknowledgeResponse } from './types/beacon/messages/AcknowledgeResponse' import { DisconnectMessage } from './types/beacon/messages/DisconnectMessage' import { DappP2PTransport } from './transports/DappP2PTransport' import { DappPostMessageTransport } from './transports/DappPostMessageTransport' import { WalletP2PTransport } from './transports/WalletP2PTransport' import { WalletPostMessageTransport } from './transports/WalletPostMessageTransport' import { getSenderId } from './utils/get-sender-id' import { SigningType } from './types/beacon/SigningType' import { ExtendedP2PPairingResponse } from './types/P2PPairingResponse' import { ExtendedPostMessagePairingRequest, PostMessagePairingRequest } from './types/PostMessagePairingRequest' import { ExtendedPostMessagePairingResponse } from './types/PostMessagePairingResponse' import { PeerManager } from './managers/PeerManager' import { MessageBasedClient } from './transports/clients/MessageBasedClient' import { BeaconRequestMessage } from './types/beacon/BeaconRequestMessage' import { BeaconResponseMessage } from './types/beacon/BeaconResponseMessage' import { Pairing } from './ui/alert/Pairing' import { BlockExplorer } from './utils/block-explorer' import { TezblockBlockExplorer } from './utils/tezblock-blockexplorer' import { setDebugEnabled, getDebugEnabled } from './debug' import { ColorMode } from './types/ColorMode' // import { EncryptPayloadRequest } from './types/beacon/messages/EncryptPayloadRequest' // import { EncryptPayloadResponse } from './types/beacon/messages/EncryptPayloadResponse' // import { EncryptionTypeNotSupportedBeaconError } from './errors/EncryptionTypeNotSupportedBeaconError' import { SignatureTypeNotSupportedBeaconError } from './errors/SignatureTypeNotSupportedBeaconError' // import { EncryptionType } from './types/EncryptionType' // import { EncryptionOperation } from './types/EncryptionOperation' // Tezos export { TezosBaseOperation, TezosOperationType, TezosBlockHeader, MichelsonPrimitives, TezosTransactionParameters, TezosOperation } // Tezos Operations export { TezosActivateAccountOperation, TezosBallotOperation, TezosDelegationOperation, TezosDoubleBakingEvidenceOperation, TezosDoubleEndorsementEvidenceOperation, TezosEndorsementOperation, TezosOriginationOperation, TezosProposalOperation, TezosRevealOperation, TezosSeedNonceRevelationOperation, TezosTransactionOperation, PartialTezosOperation, PartialTezosTransactionOperation, PartialTezosDelegationOperation, PartialTezosOriginationOperation, PartialTezosRevealOperation } // Clients export { BeaconClient, BeaconClientOptions, Client, ClientOptions, DAppClient, DAppClientOptions, WalletClient, WalletClientOptions, P2PCommunicationClient } // Beacon export { AccountIdentifier, AppMetadata, Network, NetworkType, BeaconMessage, PermissionRequest, PermissionResponse, OperationRequest, OperationResponse, SignPayloadRequest, // EncryptPayloadRequest, SignPayloadResponse, // EncryptPayloadResponse, BroadcastRequest, BroadcastResponse, AcknowledgeResponse, DisconnectMessage, BeaconBaseMessage, BeaconMessageType, PermissionScope, Origin, AccountInfo, Threshold, SigningType, // EncryptionType, // EncryptionOperation, ExtensionMessageTarget, ExtensionMessage, EncryptedExtensionMessage, RequestPermissionInput, RequestSignPayloadInput, // RequestEncryptPayloadInput, RequestOperationInput, RequestBroadcastInput, PermissionInfo } export { PermissionResponseInput, SignPayloadResponseInput, // EncryptPayloadResponseInput, OperationResponseInput, BroadcastResponseInput, AcknowledgeResponseInput, ErrorResponseInput, PermissionResponseOutput, SignPayloadResponseOutput, // EncryptPayloadResponseOutput, OperationResponseOutput, BroadcastResponseOutput, PermissionRequestInput, SignPayloadRequestInput, // EncryptPayloadRequestInput, OperationRequestInput, BroadcastRequestInput, PermissionRequestOutput, SignPayloadRequestOutput, // EncryptPayloadRequestOutput, OperationRequestOutput, BroadcastRequestOutput, BeaconRequestInputMessage, BeaconRequestOutputMessage, BeaconResponseInputMessage, BeaconResponseOutputMessage, BeaconRequestMessage, BeaconResponseMessage } // Errors export { BeaconError, BeaconErrorType, ErrorResponse, AbortedBeaconError, BroadcastBeaconError, NetworkNotSupportedBeaconError, NoAddressBeaconError, NoPrivateKeyBeaconError, NotGrantedBeaconError, ParametersInvalidBeaconError, TooManyOperationsBeaconError, TransactionInvalidBeaconError, SignatureTypeNotSupportedBeaconError, // EncryptionTypeNotSupportedBeaconError, UnknownBeaconError } // Transport export { TransportStatus, TransportType, Transport, PostMessageTransport, P2PTransport, WalletP2PTransport, WalletPostMessageTransport, DappP2PTransport, DappPostMessageTransport, MessageBasedClient, Pairing } // Events export { BeaconEvent, BeaconEventHandler, defaultEventCallbacks } // Storage export { Storage, StorageKey, StorageKeyReturnDefaults, StorageKeyReturnType, ChromeStorage, LocalStorage, getStorage } // Managers export { PeerManager, AccountManager, AppMetadataManager, PermissionManager } // Constants export { SDK_VERSION, BEACON_VERSION } // Utils export { getSenderId, getAccountIdentifier, getAddressFromPublicKey } // Pairing export { PeerInfo, ExtendedPeerInfo, PostMessagePairingRequest, ExtendedPostMessagePairingRequest, ExtendedPostMessagePairingResponse, P2PPairingRequest, ExtendedP2PPairingRequest, ExtendedP2PPairingResponse } // BlockExplorer export { BlockExplorer, TezblockBlockExplorer } // Others export { ConnectionContext, Serializer, availableTransports, ColorMode } // Debug export { setDebugEnabled, getDebugEnabled }
the_stack
import * as R from 'ramda' import * as React from 'react' import * as redux from 'react-redux' import { Link } from 'react-router-dom' import { createStructuredSelector } from 'reselect' import * as M from '@material-ui/core' import Logo from 'components/Logo' import * as style from 'constants/style' import * as URLS from 'constants/urls' import * as authSelectors from 'containers/Auth/selectors' import * as BucketConfig from 'utils/BucketConfig' import * as CatalogSettings from 'utils/CatalogSettings' import * as Config from 'utils/Config' import HashLink from 'utils/HashLink' import * as NamedRoutes from 'utils/NamedRoutes' import { useRoute } from 'utils/router' import bg from './bg.png' import Controls from './Controls' const useLogoLinkStyles = M.makeStyles((t) => ({ root: { margin: t.spacing(2), }, })) function LogoLink() { const classes = useLogoLinkStyles() const cfg = Config.useConfig() const { urls } = NamedRoutes.use() return ( <Link className={classes.root} to={urls.home()}> <Logo responsive forcedShort={cfg.mode === 'OPEN' || cfg.mode === 'PRODUCT'} /> </Link> ) } const useItemStyles = M.makeStyles({ root: { display: 'inline-flex', maxWidth: '400px', overflow: 'hidden', textOverflow: 'ellipsis', }, }) // type ItemProps = (LinkProps | { href: string }) & M.MenuItemProps interface ItemProps extends M.MenuItemProps { to?: string href?: string } // FIXME: doesn't compile with Ref<unknown> // const Item = React.forwardRef((props: ItemProps, ref: React.Ref<unknown>) => ( const Item = React.forwardRef( ({ children, ...props }: ItemProps, ref: React.Ref<any>) => { const classes = useItemStyles() return ( <M.MenuItem // @ts-expect-error // eslint-disable-next-line no-nested-ternary component={props.to ? Link : props.href ? 'a' : undefined} ref={ref} {...props} > <span className={classes.root}>{children}</span> </M.MenuItem> ) }, ) const selectUser = createStructuredSelector({ name: authSelectors.username, isAdmin: authSelectors.isAdmin, }) const userDisplay = (user: $TSFixMe) => ( <> {user.isAdmin && ( <> <M.Icon fontSize="small">security</M.Icon> &nbsp; </> )} {user.name} </> ) function UserDropdown() { const cfg = Config.useConfig() const user = redux.useSelector(selectUser) const { urls, paths } = NamedRoutes.use() const isProfile = !!useRoute(paths.profile, { exact: true }).match const isAdmin = !!useRoute(paths.admin).match const [anchor, setAnchor] = React.useState(null) const open = React.useCallback( (evt) => { setAnchor(evt.target) }, [setAnchor], ) const close = React.useCallback(() => { setAnchor(null) }, [setAnchor]) return ( <> <M.Button variant="text" color="inherit" onClick={open}> {userDisplay(user)} <M.Icon>expand_more</M.Icon> </M.Button> <M.MuiThemeProvider theme={style.appTheme}> <M.Menu anchorEl={anchor} open={!!anchor} onClose={close}> {user.isAdmin && ( <Item to={urls.admin()} onClick={close} selected={isAdmin} divider> <M.Icon fontSize="small">security</M.Icon>&nbsp;Admin settings </Item> )} {cfg.mode === 'OPEN' && ( <Item to={urls.profile()} onClick={close} selected={isProfile}> Profile </Item> )} <Item to={urls.signOut()} onClick={close}> Sign Out </Item> </M.Menu> </M.MuiThemeProvider> </> ) } function useHam() { const [anchor, setAnchor] = React.useState(null) const open = React.useCallback( (evt) => { setAnchor(evt.target) }, [setAnchor], ) const close = React.useCallback(() => { setAnchor(null) }, [setAnchor]) const render = (children: React.ReactNode) => ( <> <M.IconButton onClick={open} aria-label="Menu" edge="end"> <M.Icon>menu</M.Icon> </M.IconButton> <M.MuiThemeProvider theme={style.appTheme}> <M.Menu anchorEl={anchor} open={!!anchor} onClose={close} MenuListProps={ { component: 'nav', style: { minWidth: 120 }, } as M.MenuListProps } > {children} </M.Menu> </M.MuiThemeProvider> </> ) return { open, close, render } } interface AuthHamburgerProps { authenticated: boolean waiting: boolean error: boolean } function AuthHamburger({ authenticated, waiting, error }: AuthHamburgerProps) { const cfg = Config.useConfig() const user = redux.useSelector(selectUser) const { urls, paths } = NamedRoutes.use() const isProfile = !!useRoute(paths.profile, { exact: true }).match const isAdmin = !!useRoute(paths.admin).match const ham = useHam() const links = useLinks() return ham.render([ ...// eslint-disable-next-line no-nested-ternary (authenticated ? [ <M.MenuItem key="user" component="div"> {userDisplay(user)} </M.MenuItem>, user.isAdmin && ( <Item key="admin" to={urls.admin()} onClick={ham.close} selected={isAdmin}> <M.Box component="span" pr={2} /> <M.Icon fontSize="small">security</M.Icon> &nbsp;Admin settings </Item> ), cfg.mode === 'OPEN' && ( <Item key="profile" to={urls.profile()} onClick={ham.close} selected={isProfile} > <M.Box component="span" pr={2} /> Profile </Item> ), <Item key="signout" to={urls.signOut()} onClick={ham.close}> <M.Box component="span" pr={2} /> Sign Out </Item>, ] : waiting ? [ <Item onClick={ham.close} key="progress"> <M.CircularProgress /> </Item>, ] : [ <Item to={urls.signIn()} onClick={ham.close} key="sign-in"> {error && ( <> <M.Icon>error_outline</M.Icon>{' '} </> )} Sign In </Item>, ]), <M.Divider key="divider" />, ...links.map(({ label, ...rest }) => ( <Item key={`${label}:${rest.to || rest.href}`} {...rest} onClick={ham.close}> {label} </Item> )), ]) } function LinksHamburger() { const ham = useHam() return ham.render( useLinks().map(({ label, ...rest }) => ( <Item key={`${label}:${rest.to || rest.href}`} {...rest} onClick={ham.close}> {label} </Item> )), ) } const useSignInStyles = M.makeStyles((t) => ({ icon: { marginRight: t.spacing(1), }, })) interface AuthError { message: string } interface SignInProps { error?: AuthError waiting: boolean } function SignIn({ error, waiting }: SignInProps) { const classes = useSignInStyles() const { urls } = NamedRoutes.use() if (waiting) { return <M.CircularProgress color="inherit" /> } return ( <> {error && ( <M.Icon title={`${error.message}\n${JSON.stringify(error)}`} className={classes.icon} > error_outline </M.Icon> )} <M.Button component={Link} to={urls.signIn()} variant="contained" color="primary"> Sign In </M.Button> </> ) } const AppBar = M.styled(M.AppBar)(({ theme: t }) => ({ background: `left / 64px url(${bg})`, zIndex: t.zIndex.appBar + 1, })) interface ContainerProps { children?: React.ReactNode } export function Container({ children }: ContainerProps) { const trigger = M.useScrollTrigger() return ( <M.MuiThemeProvider theme={style.navTheme}> <M.Box> <M.Toolbar /> <M.Slide appear={false} direction="down" in={!trigger}> <AppBar> <M.Toolbar disableGutters> <M.Container maxWidth="lg" style={{ display: 'flex', alignItems: 'center' }} > <LogoLink /> {children} </M.Container> </M.Toolbar> </AppBar> </M.Slide> </M.Box> </M.MuiThemeProvider> ) } interface NavLinkOwnProps { to?: string path?: string } type NavLinkProps = NavLinkOwnProps & M.BoxProps const NavLink = React.forwardRef((props: NavLinkProps, ref: React.Ref<unknown>) => { const isActive = !!useRoute(props.path, { exact: true }).match return ( <M.Box component={props.to ? HashLink : 'a'} mr={2} color={isActive ? 'text.disabled' : 'text.secondary'} fontSize="body2.fontSize" maxWidth={64} whiteSpace="nowrap" overflow="hidden" textOverflow="ellipsis" title={ typeof props.children === 'string' && props.children.length > 10 ? props.children : undefined } {...props} ref={ref} /> ) }) interface LinkDescriptor { label: string to?: string href?: string } function useLinks(): LinkDescriptor[] { const { paths, urls } = NamedRoutes.use() const cfg = Config.useConfig() const settings = CatalogSettings.use() return [ process.env.NODE_ENV === 'development' && { to: urls.example(), label: 'Example', }, settings?.customNavLink && { href: settings.customNavLink.url, label: settings.customNavLink.label, }, cfg.mode !== 'MARKETING' && { to: urls.uriResolver(), label: 'URI', path: paths.uriResolver, }, { href: URLS.docs, label: 'Docs' }, cfg.mode === 'MARKETING' && { to: `${urls.home()}#pricing`, label: 'Pricing' }, (cfg.mode === 'MARKETING' || cfg.mode === 'OPEN') && { href: URLS.jobs, label: 'Jobs', }, { href: URLS.blog, label: 'Blog' }, cfg.mode === 'MARKETING' && { to: urls.about(), label: 'About' }, ].filter(Boolean) as LinkDescriptor[] } const selector = createStructuredSelector( R.pick(['error', 'waiting', 'authenticated'], authSelectors), ) export function NavBar() { const cfg = Config.use() const bucket = BucketConfig.useCurrentBucket() const { paths } = NamedRoutes.use() const isSignIn = !!useRoute(paths.signIn, { exact: true }).match const { error, waiting, authenticated } = redux.useSelector(selector) const t = M.useTheme() const useHamburger = M.useMediaQuery(t.breakpoints.down('sm')) const links = useLinks() return ( <Container> {cfg.disableNavigator || (cfg.alwaysRequiresAuth && isSignIn) ? ( <M.Box flexGrow={1} /> ) : ( <Controls {...{ bucket, disableSearch: cfg.mode === 'LOCAL' }} /> )} {!useHamburger && ( <M.Box component="nav" display="flex" alignItems="center" ml={3}> {links.map(({ label, ...rest }) => ( <NavLink key={`${label}:${rest.to || rest.href}`} {...rest}> {label} </NavLink> ))} </M.Box> )} {!cfg.disableNavigator && cfg.mode !== 'LOCAL' && !useHamburger && (authenticated ? ( <UserDropdown /> ) : ( !isSignIn && <SignIn error={error} waiting={waiting} /> ))} {useHamburger && (cfg.disableNavigator || cfg.mode === 'LOCAL' ? ( <LinksHamburger /> ) : ( <AuthHamburger {...{ authenticated, error, waiting }} /> ))} </Container> ) } export default NavBar
the_stack
import { DI, IContainer, inject, InterfaceSymbol, Registration, singleton } from '@aurelia/kernel'; import { assert, createSpy, ISpy } from '@aurelia/testing'; describe('DI.singleton', function () { describe('registerInRequester', function () { class Foo { } const fooSelfRegister = DI.singleton(Foo, { scoped: true }); it('root', function () { const root = DI.createContainer(); const foo1 = root.get(fooSelfRegister); const foo2 = root.get(fooSelfRegister); assert.strictEqual(foo1, foo2); }); it('children', function () { const root = DI.createContainer(); const child1 = root.createChild(); const child2 = root.createChild(); const foo1 = child1.get(fooSelfRegister); const foo2 = child2.get(fooSelfRegister); assert.notStrictEqual(foo1, foo2); }); }); }); describe('DI.getDependencies', function () { it('string param', function () { @singleton class Foo { public constructor(public readonly test: string) {} } const actual = DI.getDependencies(Foo); assert.deepStrictEqual(actual, [String]); }); it('class param', function () { class Bar {} @singleton class Foo { public constructor(public readonly test: Bar) {} } const actual = DI.getDependencies(Foo); assert.deepStrictEqual(actual, [Bar]); }); }); describe('DI.createInterface() -> container.get()', function () { let container: IContainer; interface ITransient {} class Transient implements ITransient {} let ITransient: InterfaceSymbol<ITransient>; interface ISingleton {} class Singleton implements ISingleton {} let ISingleton: InterfaceSymbol<ISingleton>; interface IInstance {} class Instance implements IInstance {} let IInstance: InterfaceSymbol<IInstance>; let instance: Instance; interface ICallback {} class Callback implements ICallback {} let ICallback: InterfaceSymbol<ICallback>; interface ICachedCallback {} class CachedCallback implements ICachedCallback {} let ICachedCallback: InterfaceSymbol<ICachedCallback>; const cachedCallback = 'cachedCallBack'; let callbackCount = 0; function callbackToCache() { ++callbackCount; return new CachedCallback(); } let callback: ISpy<() => ICallback>; let get: ISpy<IContainer['get']>; // eslint-disable-next-line mocha/no-hooks beforeEach(function () { callbackCount = 0; container = DI.createContainer(); ITransient = DI.createInterface<ITransient>('ITransient', x => x.transient(Transient)); ISingleton = DI.createInterface<ISingleton>('ISingleton', x => x.singleton(Singleton)); instance = new Instance(); IInstance = DI.createInterface<IInstance>('IInstance', x => x.instance(instance)); callback = createSpy(() => new Callback()); ICallback = DI.createInterface<ICallback>('ICallback', x => x.callback(callback)); ICachedCallback = DI.createInterface<ICachedCallback>('ICachedCallback', x => x.cachedCallback(callbackToCache)); get = createSpy(container, 'get', true); }); // eslint-disable-next-line mocha/no-hooks afterEach(function () { get.restore(); }); describe('leaf', function () { it(`transient registration returns a new instance each time`, function () { const actual1 = container.get(ITransient); assert.instanceOf(actual1, Transient, `actual1`); const actual2 = container.get(ITransient); assert.instanceOf(actual2, Transient, `actual2`); assert.notStrictEqual(actual1, actual2, `actual1`); assert.deepStrictEqual( get.calls, [ [ITransient], [ITransient], ], `get.calls`, ); }); it(`singleton registration returns the same instance each time`, function () { const actual1 = container.get(ISingleton); assert.instanceOf(actual1, Singleton, `actual1`); const actual2 = container.get(ISingleton); assert.instanceOf(actual2, Singleton, `actual2`); assert.strictEqual(actual1, actual2, `actual1`); assert.deepStrictEqual( get.calls, [ [ISingleton], [ISingleton], ], `get.calls`, ); }); it(`instance registration returns the same instance each time`, function () { const actual1 = container.get(IInstance); assert.instanceOf(actual1, Instance, `actual1`); const actual2 = container.get(IInstance); assert.instanceOf(actual2, Instance, `actual2`); assert.strictEqual(actual1, instance, `actual1`); assert.strictEqual(actual2, instance, `actual2`); assert.deepStrictEqual( get.calls, [ [IInstance], [IInstance], ], `get.calls`, ); }); it(`callback registration is invoked each time`, function () { const actual1 = container.get(ICallback); assert.instanceOf(actual1, Callback, `actual1`); const actual2 = container.get(ICallback); assert.instanceOf(actual2, Callback, `actual2`); assert.notStrictEqual(actual1, actual2, `actual1`); assert.deepStrictEqual( callback.calls, [ [container, container, container.getResolver(ICallback)], [container, container, container.getResolver(ICallback)], ], `callback.calls`, ); assert.deepStrictEqual( get.calls, [ [ICallback], [ICallback], ], `get.calls`, ); }); it(`cachedCallback registration is invoked once`, function () { container.register(Registration.cachedCallback(cachedCallback, callbackToCache)); const child = container.createChild(); child.register(Registration.cachedCallback(cachedCallback, callbackToCache)); const actual1 = container.get(cachedCallback); const actual2 = container.get(cachedCallback); assert.strictEqual(callbackCount, 1, `only called once`); assert.strictEqual(actual2, actual1, `getting from the same container`); const actual3 = child.get(cachedCallback); assert.notStrictEqual(actual3, actual1, `get from child that has new resolver`); }); it(`cacheCallback multiple root containers`, function () { const container0 = DI.createContainer(); const container1 = DI.createContainer(); container0.register(Registration.cachedCallback(cachedCallback, callbackToCache)); container1.register(Registration.cachedCallback(cachedCallback, callbackToCache)); const actual11 = container0.get(cachedCallback); const actual12 = container0.get(cachedCallback); assert.strictEqual(callbackCount, 1, 'one callback'); assert.strictEqual(actual11, actual12); const actual21 = container1.get(cachedCallback); const actual22 = container1.get(cachedCallback); assert.strictEqual(callbackCount, 2); assert.strictEqual(actual21, actual22); }); it(`cacheCallback different containers should not create the same singleton GH #1064`, function () { const reg = Registration.cachedCallback(cachedCallback, callbackToCache); const container0 = DI.createContainer(); const container1 = DI.createContainer(); container0.register(reg); container1.register(reg); const actual11 = container0.get(cachedCallback); const actual12 = container0.get(cachedCallback); assert.strictEqual(actual11, actual12, "11 equals 12"); assert.strictEqual(callbackCount, 1, "callback count 1"); const actual21 = container1.get(cachedCallback); const actual22 = container1.get(cachedCallback); assert.strictEqual(actual21, actual22, "21 equals 22"); assert.strictEqual(callbackCount, 2, "callback count 2"); assert.notStrictEqual(actual11, actual21, "11 does not equal 21"); }); it(`cachedCallback registration on interface is invoked once`, function () { const actual1 = container.get(ICachedCallback); const actual2 = container.get(ICachedCallback); assert.strictEqual(callbackCount, 1, `only called once`); assert.strictEqual(actual2, actual1, `getting from the same container`); }); it(`cacheCallback interface multiple root containers`, function () { const container0 = DI.createContainer(); const container1 = DI.createContainer(); const actual11 = container0.get(ICachedCallback); const actual12 = container0.get(ICachedCallback); assert.strictEqual(callbackCount, 1); assert.strictEqual(actual11, actual12); const actual21 = container1.get(ICachedCallback); const actual22 = container1.get(ICachedCallback); assert.strictEqual(callbackCount, 2); assert.strictEqual(actual21, actual22); }); it(`InterfaceSymbol alias to transient registration returns a new instance each time`, function () { interface IAlias {} const IAlias = DI.createInterface<IAlias>('IAlias', x => x.aliasTo(ITransient)); const actual1 = container.get(IAlias); assert.instanceOf(actual1, Transient, `actual1`); const actual2 = container.get(IAlias); assert.instanceOf(actual2, Transient, `actual2`); assert.notStrictEqual(actual1, actual2, `actual1`); assert.deepStrictEqual( get.calls, [ [IAlias], [ITransient], [IAlias], [ITransient], ], `get.calls`, ); }); it(`InterfaceSymbol alias to singleton registration returns the same instance each time`, function () { interface IAlias {} const IAlias = DI.createInterface<IAlias>('IAlias', x => x.aliasTo(ISingleton)); const actual1 = container.get(IAlias); assert.instanceOf(actual1, Singleton, `actual1`); const actual2 = container.get(IAlias); assert.instanceOf(actual2, Singleton, `actual2`); assert.strictEqual(actual1, actual2, `actual1`); assert.deepStrictEqual( get.calls, [ [IAlias], [ISingleton], [IAlias], [ISingleton], ], `get.calls`, ); }); it(`InterfaceSymbol alias to instance registration returns the same instance each time`, function () { interface IAlias {} const IAlias = DI.createInterface<IAlias>('IAlias', x => x.aliasTo(IInstance)); const actual1 = container.get(IAlias); assert.instanceOf(actual1, Instance, `actual1`); const actual2 = container.get(IAlias); assert.instanceOf(actual2, Instance, `actual2`); assert.strictEqual(actual1, instance, `actual1`); assert.strictEqual(actual2, instance, `actual2`); assert.deepStrictEqual( get.calls, [ [IAlias], [IInstance], [IAlias], [IInstance], ], `get.calls`, ); }); // TODO: make test work it(`InterfaceSymbol alias to callback registration is invoked each time`, function () { interface IAlias {} const IAlias = DI.createInterface<IAlias>('IAlias', x => x.aliasTo(ICallback)); const actual1 = container.get(IAlias); assert.instanceOf(actual1, Callback, `actual1`); const actual2 = container.get(IAlias); assert.instanceOf(actual2, Callback, `actual2`); assert.notStrictEqual(actual1, actual2, `actual1`); assert.deepStrictEqual( callback.calls, [ [container, container, container.getResolver(ICallback)], [container, container, container.getResolver(ICallback)], ], `callback.calls`, ); assert.deepStrictEqual( get.calls, [ [IAlias], [ICallback], [IAlias], [ICallback], ], `get.calls`, ); }); it(`string alias to transient registration returns a new instance each time`, function () { container.register(Registration.aliasTo(ITransient, 'alias')); const actual1 = container.get('alias'); assert.instanceOf(actual1, Transient, `actual1`); const actual2 = container.get('alias'); assert.instanceOf(actual2, Transient, `actual2`); assert.notStrictEqual(actual1, actual2, `actual1`); assert.deepStrictEqual( get.calls, [ ['alias'], [ITransient], ['alias'], [ITransient], ], `get.calls`, ); }); it(`string alias to singleton registration returns the same instance each time`, function () { container.register(Registration.aliasTo(ISingleton, 'alias')); const actual1 = container.get('alias'); assert.instanceOf(actual1, Singleton, `actual1`); const actual2 = container.get('alias'); assert.instanceOf(actual2, Singleton, `actual2`); assert.strictEqual(actual1, actual2, `actual1`); assert.deepStrictEqual( get.calls, [ ['alias'], [ISingleton], ['alias'], [ISingleton], ], `get.calls`, ); }); it(`string alias to instance registration returns the same instance each time`, function () { container.register(Registration.aliasTo(IInstance, 'alias')); const actual1 = container.get('alias'); assert.instanceOf(actual1, Instance, `actual1`); const actual2 = container.get('alias'); assert.instanceOf(actual2, Instance, `actual2`); assert.strictEqual(actual1, instance, `actual1`); assert.strictEqual(actual2, instance, `actual2`); assert.deepStrictEqual( get.calls, [ ['alias'], [IInstance], ['alias'], [IInstance], ], `get.calls`, ); }); it(`string alias to callback registration is invoked each time`, function () { container.register(Registration.aliasTo(ICallback, 'alias')); const actual1 = container.get('alias'); assert.instanceOf(actual1, Callback, `actual1`); const actual2 = container.get('alias'); assert.instanceOf(actual2, Callback, `actual2`); assert.notStrictEqual(actual1, actual2, `actual1`); assert.deepStrictEqual( callback.calls, [ [container, container, container.getResolver(ICallback)], [container, container, container.getResolver(ICallback)], ], `callback.calls`, ); assert.deepStrictEqual( get.calls, [ ['alias'], [ICallback], ['alias'], [ICallback], ], `get.calls`, ); }); }); // describe('parent without inject decorator', function () { // function decorator(): ClassDecorator { return (target: any) => target; } // interface IParent { dep: any; } // let IParent: InterfaceSymbol<IParent>; // function register(cls: any) { // IParent = DI.createInterface<IParent>('IParent', x => x.transient(cls)); // } // it(`transient child registration throws`, function () { // @decorator() // class Parent implements IParent { constructor(public dep: ITransient) {} } // register(Parent); // assert.throws(() => container.get(IParent), /5/, `() => container.get(IParent)`); // }); // it(`singleton child registration throws`, function () { // @decorator() // class Parent implements IParent { constructor(public dep: ISingleton) {} } // register(Parent); // assert.throws(() => container.get(IParent), /5/, `() => container.get(IParent)`); // }); // it(`instance child registration throws`, function () { // @decorator() // class Parent implements IParent { constructor(public dep: IInstance) {} } // register(Parent); // assert.throws(() => container.get(IParent), /5/, `() => container.get(IParent)`); // }); // it(`callback child registration throws`, function () { // @decorator() // class Parent implements IParent { constructor(public dep: ICallback) {} } // register(Parent); // assert.throws(() => container.get(IParent), /5/, `() => container.get(IParent)`); // }); // }); describe('transient parent', function () { interface ITransientParent { dep: any } let ITransientParent: InterfaceSymbol<ITransientParent>; function register(cls: any) { ITransientParent = DI.createInterface<ITransientParent>('ITransientParent', x => x.transient(cls)); } it(`transient child registration returns a new instance each time`, function () { @inject(ITransient) class TransientParent implements ITransientParent { public constructor(public dep: ITransient) {} } register(TransientParent); const actual1 = container.get(ITransientParent); assert.instanceOf(actual1, TransientParent, `actual1`); assert.instanceOf(actual1.dep, Transient, `actual1.dep`); const actual2 = container.get(ITransientParent); assert.instanceOf(actual2, TransientParent, `actual2`); assert.instanceOf(actual2.dep, Transient, `actual2.dep`); assert.notStrictEqual(actual1, actual2, `actual1`); assert.notStrictEqual(actual1.dep, actual2.dep, `actual1.dep`); assert.deepStrictEqual( get.calls, [ [ITransientParent], [ITransient], [ITransientParent], [ITransient], ], `get.calls`, ); }); it(`singleton child registration returns the same instance each time`, function () { @inject(ISingleton) class TransientParent implements ITransientParent { public constructor(public dep: ISingleton) {} } register(TransientParent); const actual1 = container.get(ITransientParent); assert.instanceOf(actual1, TransientParent, `actual1`); assert.instanceOf(actual1.dep, Singleton, `actual1.dep`); const actual2 = container.get(ITransientParent); assert.instanceOf(actual2, TransientParent, `actual2`); assert.instanceOf(actual2.dep, Singleton, `actual2.dep`); assert.notStrictEqual(actual1, actual2, `actual1`); assert.strictEqual(actual1.dep, actual2.dep, `actual1.dep`); assert.deepStrictEqual( get.calls, [ [ITransientParent], [ISingleton], [ITransientParent], [ISingleton], ], `get.calls`, ); }); it(`instance child registration returns the same instance each time`, function () { @inject(IInstance) class TransientParent implements ITransientParent { public constructor(public dep: IInstance) {} } register(TransientParent); const actual1 = container.get(ITransientParent); assert.instanceOf(actual1, TransientParent, `actual1`); assert.instanceOf(actual1.dep, Instance, `actual1.dep`); const actual2 = container.get(ITransientParent); assert.instanceOf(actual2, TransientParent, `actual2`); assert.instanceOf(actual2.dep, Instance, `actual2.dep`); assert.notStrictEqual(actual1, actual2, `actual1`); assert.strictEqual(actual1.dep, actual2.dep, `actual1.dep`); assert.deepStrictEqual( get.calls, [ [ITransientParent], [IInstance], [ITransientParent], [IInstance], ], `get.calls`, ); }); it(`callback child registration is invoked each time`, function () { @inject(ICallback) class TransientParent implements ITransientParent { public constructor(public dep: ICallback) {} } register(TransientParent); const actual1 = container.get(ITransientParent); assert.instanceOf(actual1, TransientParent, `actual1`); assert.instanceOf(actual1.dep, Callback, `actual1.dep`); const actual2 = container.get(ITransientParent); assert.instanceOf(actual2, TransientParent, `actual2`); assert.instanceOf(actual2.dep, Callback, `actual2.dep`); assert.notStrictEqual(actual1, actual2, `actual1`); assert.notStrictEqual(actual1.dep, actual2.dep, `actual1.dep`); assert.deepStrictEqual( callback.calls, [ [container, container, container.getResolver(ICallback)], [container, container, container.getResolver(ICallback)], ], `callback.calls`, ); assert.deepStrictEqual( get.calls, [ [ITransientParent], [ICallback], [ITransientParent], [ICallback], ], `get.calls`, ); }); }); describe('singleton parent', function () { interface ISingletonParent { dep: any } let ISingletonParent: InterfaceSymbol<ISingletonParent>; function register(cls: any) { ISingletonParent = DI.createInterface<ISingletonParent>('ISingletonParent', x => x.singleton(cls)); } it(`transient child registration is reused by the singleton parent`, function () { @inject(ITransient) class SingletonParent implements ISingletonParent { public constructor(public dep: ITransient) {} } register(SingletonParent); const actual1 = container.get(ISingletonParent); assert.instanceOf(actual1, SingletonParent, `actual1`); assert.instanceOf(actual1.dep, Transient, `actual1.dep`); const actual2 = container.get(ISingletonParent); assert.instanceOf(actual2, SingletonParent, `actual2`); assert.instanceOf(actual2.dep, Transient, `actual2.dep`); assert.strictEqual(actual1, actual2, `actual1`); assert.strictEqual(actual1.dep, actual2.dep, `actual1.dep`); assert.deepStrictEqual( get.calls, [ [ISingletonParent], [ITransient], [ISingletonParent], ], `get.calls`, ); }); it(`singleton registration is reused by the singleton parent`, function () { @inject(ISingleton) class SingletonParent implements ISingletonParent { public constructor(public dep: ISingleton) {} } register(SingletonParent); const actual1 = container.get(ISingletonParent); assert.instanceOf(actual1, SingletonParent, `actual1`); assert.instanceOf(actual1.dep, Singleton, `actual1.dep`); const actual2 = container.get(ISingletonParent); assert.instanceOf(actual2, SingletonParent, `actual2`); assert.instanceOf(actual2.dep, Singleton, `actual2.dep`); assert.strictEqual(actual1, actual2, `actual1`); assert.strictEqual(actual1.dep, actual2.dep, `actual1.dep`); assert.deepStrictEqual( get.calls, [ [ISingletonParent], [ISingleton], [ISingletonParent], ], `get.calls`, ); }); it(`instance registration is reused by the singleton parent`, function () { @inject(IInstance) class SingletonParent implements ISingletonParent { public constructor(public dep: IInstance) {} } register(SingletonParent); const actual1 = container.get(ISingletonParent); assert.instanceOf(actual1, SingletonParent, `actual1`); assert.instanceOf(actual1.dep, Instance, `actual1.dep`); const actual2 = container.get(ISingletonParent); assert.instanceOf(actual2, SingletonParent, `actual2`); assert.instanceOf(actual2.dep, Instance, `actual2.dep`); assert.strictEqual(actual1, actual2, `actual1`); assert.strictEqual(actual1.dep, actual2.dep, `actual1.dep`); assert.deepStrictEqual( get.calls, [ [ISingletonParent], [IInstance], [ISingletonParent], ], `get.calls`, ); }); it(`callback registration is reused by the singleton parent`, function () { @inject(ICallback) class SingletonParent implements ISingletonParent { public constructor(public dep: ICallback) {} } register(SingletonParent); const actual1 = container.get(ISingletonParent); assert.instanceOf(actual1, SingletonParent, `actual1`); assert.instanceOf(actual1.dep, Callback, `actual1.dep`); const actual2 = container.get(ISingletonParent); assert.instanceOf(actual2, SingletonParent, `actual2`); assert.instanceOf(actual2.dep, Callback, `actual2.dep`); assert.strictEqual(actual1, actual2, `actual1`); assert.strictEqual(actual1.dep, actual2.dep, `actual1.dep`); assert.deepStrictEqual( callback.calls, [ [container, container, container.getResolver(ICallback)], ], `callback.calls`, ); assert.deepStrictEqual( get.calls, [ [ISingletonParent], [ICallback], [ISingletonParent], ], `get.calls`, ); }); }); describe('instance parent', function () { interface IInstanceParent { dep: any } let IInstanceParent: InterfaceSymbol<IInstanceParent>; let instanceParent: IInstanceParent; function register(cls: any) { instanceParent = container.get(cls); get.reset(); IInstanceParent = DI.createInterface<IInstanceParent>('IInstanceParent', x => x.instance(instanceParent)); } it(`transient registration is reused by the instance parent`, function () { @inject(ITransient) class InstanceParent implements IInstanceParent { public constructor(public dep: ITransient) {} } register(InstanceParent); const actual1 = container.get(IInstanceParent); assert.instanceOf(actual1, InstanceParent, `actual1`); assert.instanceOf(actual1.dep, Transient, `actual1.dep`); const actual2 = container.get(IInstanceParent); assert.instanceOf(actual2, InstanceParent, `actual2`); assert.instanceOf(actual2.dep, Transient, `actual2.dep`); assert.strictEqual(actual1, actual2, `actual1`); assert.strictEqual(actual1.dep, actual2.dep, `actual1.dep`); assert.deepStrictEqual( get.calls, [ [IInstanceParent], [IInstanceParent], ], `get.calls`, ); }); it(`singleton registration is reused by the instance parent`, function () { @inject(ISingleton) class InstanceParent implements IInstanceParent { public constructor(public dep: ISingleton) {} } register(InstanceParent); const actual1 = container.get(IInstanceParent); assert.instanceOf(actual1, InstanceParent, `actual1`); assert.instanceOf(actual1.dep, Singleton, `actual1.dep`); const actual2 = container.get(IInstanceParent); assert.instanceOf(actual2, InstanceParent, `actual2`); assert.instanceOf(actual2.dep, Singleton, `actual2.dep`); assert.strictEqual(actual1, actual2, `actual1`); assert.strictEqual(actual1.dep, actual2.dep, `actual1.dep`); assert.deepStrictEqual( get.calls, [ [IInstanceParent], [IInstanceParent], ], `get.calls`, ); }); it(`instance registration is reused by the instance parent`, function () { @inject(IInstance) class InstanceParent implements IInstanceParent { public constructor(public dep: IInstance) {} } register(InstanceParent); const actual1 = container.get(IInstanceParent); assert.instanceOf(actual1, InstanceParent, `actual1`); assert.instanceOf(actual1.dep, Instance, `actual1.dep`); const actual2 = container.get(IInstanceParent); assert.instanceOf(actual2, InstanceParent, `actual2`); assert.instanceOf(actual2.dep, Instance, `actual2.dep`); assert.strictEqual(actual1, actual2, `actual1`); assert.strictEqual(actual1.dep, actual2.dep, `actual1.dep`); assert.deepStrictEqual( get.calls, [ [IInstanceParent], [IInstanceParent], ], `get.calls`, ); }); it(`callback registration is reused by the instance parent`, function () { @inject(ICallback) class InstanceParent implements IInstanceParent { public constructor(public dep: ICallback) {} } register(InstanceParent); const actual1 = container.get(IInstanceParent); assert.instanceOf(actual1, InstanceParent, `actual1`); assert.instanceOf(actual1.dep, Callback, `actual1.dep`); const actual2 = container.get(IInstanceParent); assert.instanceOf(actual2, InstanceParent, `actual2`); assert.instanceOf(actual2.dep, Callback, `actual2.dep`); assert.strictEqual(actual1, actual2, `actual1`); assert.strictEqual(actual1.dep, actual2.dep, `actual1.dep`); assert.deepStrictEqual( callback.calls, [ [container, container, container.getResolver(ICallback)], ], `callback.calls`, ); assert.deepStrictEqual( get.calls, [ [IInstanceParent], [IInstanceParent], ], `get.calls`, ); }); }); }); describe('defer registration', function () { class FakeCSSService { public constructor(public data: any) {} } class FakeCSSHandler { public register(container: IContainer, data) { container.register( Registration.instance( FakeCSSService, new FakeCSSService(data) ) ); } } it(`enables the handler class to provide registrations for data`, function () { const container = DI.createContainer(); const data = {}; container.register( Registration.singleton('.css', FakeCSSHandler) ); container.register( Registration.defer('.css', data) ); const service = container.get(FakeCSSService); assert.strictEqual(service.data, data); }); it(`passes the params to the container's register method if no handler is found`, function () { const container = DI.createContainer(); const data = { wasCalled: false, register() { this.wasCalled = true; } }; container.register( Registration.defer('.css', data) ); assert.strictEqual(data.wasCalled, true); }); [ { name: 'string', value: 'some string value' }, { name: 'boolean', value: true }, { name: 'number', value: 42 } ].forEach(x => { it(`does not pass ${x.name} params to the container's register when no handler is found`, function () { const container = DI.createContainer(); container.register( Registration.defer('.css', x.value) ); }); }); // TODO: fix test setup for emitDecoratorMetadata // it('can inject dependencies based on TS metadata', function () { // const deco: ClassDecorator = function (target) { return target; }; // class Foo {} // @deco // class Bar { // public constructor( // public readonly foo: Foo // ) {} // } // const bar = DI.createContainer().get(Bar); // assert.instanceOf(bar.foo, Foo); // }); });
the_stack
import { PagedAsyncIterableIterator } from "@azure/core-paging"; import { IntegrationRuntimes } from "../operationsInterfaces"; import * as coreClient from "@azure/core-client"; import * as Mappers from "../models/mappers"; import * as Parameters from "../models/parameters"; import { DataFactoryClient } from "../dataFactoryClient"; import { PollerLike, PollOperationState, LroEngine } from "@azure/core-lro"; import { LroImpl } from "../lroImpl"; import { IntegrationRuntimeResource, IntegrationRuntimesListByFactoryNextOptionalParams, IntegrationRuntimesListByFactoryOptionalParams, IntegrationRuntimesListByFactoryResponse, IntegrationRuntimesCreateOrUpdateOptionalParams, IntegrationRuntimesCreateOrUpdateResponse, IntegrationRuntimesGetOptionalParams, IntegrationRuntimesGetResponse, UpdateIntegrationRuntimeRequest, IntegrationRuntimesUpdateOptionalParams, IntegrationRuntimesUpdateResponse, IntegrationRuntimesDeleteOptionalParams, IntegrationRuntimesGetStatusOptionalParams, IntegrationRuntimesGetStatusResponse, IntegrationRuntimesListOutboundNetworkDependenciesEndpointsOptionalParams, IntegrationRuntimesListOutboundNetworkDependenciesEndpointsResponse, IntegrationRuntimesGetConnectionInfoOptionalParams, IntegrationRuntimesGetConnectionInfoResponse, IntegrationRuntimeRegenerateKeyParameters, IntegrationRuntimesRegenerateAuthKeyOptionalParams, IntegrationRuntimesRegenerateAuthKeyResponse, IntegrationRuntimesListAuthKeysOptionalParams, IntegrationRuntimesListAuthKeysResponse, IntegrationRuntimesStartOptionalParams, IntegrationRuntimesStartResponse, IntegrationRuntimesStopOptionalParams, IntegrationRuntimesSyncCredentialsOptionalParams, IntegrationRuntimesGetMonitoringDataOptionalParams, IntegrationRuntimesGetMonitoringDataResponse, IntegrationRuntimesUpgradeOptionalParams, LinkedIntegrationRuntimeRequest, IntegrationRuntimesRemoveLinksOptionalParams, CreateLinkedIntegrationRuntimeRequest, IntegrationRuntimesCreateLinkedIntegrationRuntimeOptionalParams, IntegrationRuntimesCreateLinkedIntegrationRuntimeResponse, IntegrationRuntimesListByFactoryNextResponse } from "../models"; /// <reference lib="esnext.asynciterable" /> /** Class containing IntegrationRuntimes operations. */ export class IntegrationRuntimesImpl implements IntegrationRuntimes { private readonly client: DataFactoryClient; /** * Initialize a new instance of the class IntegrationRuntimes class. * @param client Reference to the service client */ constructor(client: DataFactoryClient) { this.client = client; } /** * Lists integration runtimes. * @param resourceGroupName The resource group name. * @param factoryName The factory name. * @param options The options parameters. */ public listByFactory( resourceGroupName: string, factoryName: string, options?: IntegrationRuntimesListByFactoryOptionalParams ): PagedAsyncIterableIterator<IntegrationRuntimeResource> { const iter = this.listByFactoryPagingAll( resourceGroupName, factoryName, options ); return { next() { return iter.next(); }, [Symbol.asyncIterator]() { return this; }, byPage: () => { return this.listByFactoryPagingPage( resourceGroupName, factoryName, options ); } }; } private async *listByFactoryPagingPage( resourceGroupName: string, factoryName: string, options?: IntegrationRuntimesListByFactoryOptionalParams ): AsyncIterableIterator<IntegrationRuntimeResource[]> { let result = await this._listByFactory( resourceGroupName, factoryName, options ); yield result.value || []; let continuationToken = result.nextLink; while (continuationToken) { result = await this._listByFactoryNext( resourceGroupName, factoryName, continuationToken, options ); continuationToken = result.nextLink; yield result.value || []; } } private async *listByFactoryPagingAll( resourceGroupName: string, factoryName: string, options?: IntegrationRuntimesListByFactoryOptionalParams ): AsyncIterableIterator<IntegrationRuntimeResource> { for await (const page of this.listByFactoryPagingPage( resourceGroupName, factoryName, options )) { yield* page; } } /** * Lists integration runtimes. * @param resourceGroupName The resource group name. * @param factoryName The factory name. * @param options The options parameters. */ private _listByFactory( resourceGroupName: string, factoryName: string, options?: IntegrationRuntimesListByFactoryOptionalParams ): Promise<IntegrationRuntimesListByFactoryResponse> { return this.client.sendOperationRequest( { resourceGroupName, factoryName, options }, listByFactoryOperationSpec ); } /** * Creates or updates an integration runtime. * @param resourceGroupName The resource group name. * @param factoryName The factory name. * @param integrationRuntimeName The integration runtime name. * @param integrationRuntime Integration runtime resource definition. * @param options The options parameters. */ createOrUpdate( resourceGroupName: string, factoryName: string, integrationRuntimeName: string, integrationRuntime: IntegrationRuntimeResource, options?: IntegrationRuntimesCreateOrUpdateOptionalParams ): Promise<IntegrationRuntimesCreateOrUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, factoryName, integrationRuntimeName, integrationRuntime, options }, createOrUpdateOperationSpec ); } /** * Gets an integration runtime. * @param resourceGroupName The resource group name. * @param factoryName The factory name. * @param integrationRuntimeName The integration runtime name. * @param options The options parameters. */ get( resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: IntegrationRuntimesGetOptionalParams ): Promise<IntegrationRuntimesGetResponse> { return this.client.sendOperationRequest( { resourceGroupName, factoryName, integrationRuntimeName, options }, getOperationSpec ); } /** * Updates an integration runtime. * @param resourceGroupName The resource group name. * @param factoryName The factory name. * @param integrationRuntimeName The integration runtime name. * @param updateIntegrationRuntimeRequest The parameters for updating an integration runtime. * @param options The options parameters. */ update( resourceGroupName: string, factoryName: string, integrationRuntimeName: string, updateIntegrationRuntimeRequest: UpdateIntegrationRuntimeRequest, options?: IntegrationRuntimesUpdateOptionalParams ): Promise<IntegrationRuntimesUpdateResponse> { return this.client.sendOperationRequest( { resourceGroupName, factoryName, integrationRuntimeName, updateIntegrationRuntimeRequest, options }, updateOperationSpec ); } /** * Deletes an integration runtime. * @param resourceGroupName The resource group name. * @param factoryName The factory name. * @param integrationRuntimeName The integration runtime name. * @param options The options parameters. */ delete( resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: IntegrationRuntimesDeleteOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, factoryName, integrationRuntimeName, options }, deleteOperationSpec ); } /** * Gets detailed status information for an integration runtime. * @param resourceGroupName The resource group name. * @param factoryName The factory name. * @param integrationRuntimeName The integration runtime name. * @param options The options parameters. */ getStatus( resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: IntegrationRuntimesGetStatusOptionalParams ): Promise<IntegrationRuntimesGetStatusResponse> { return this.client.sendOperationRequest( { resourceGroupName, factoryName, integrationRuntimeName, options }, getStatusOperationSpec ); } /** * Gets the list of outbound network dependencies for a given Azure-SSIS integration runtime. * @param resourceGroupName The resource group name. * @param factoryName The factory name. * @param integrationRuntimeName The integration runtime name. * @param options The options parameters. */ listOutboundNetworkDependenciesEndpoints( resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: IntegrationRuntimesListOutboundNetworkDependenciesEndpointsOptionalParams ): Promise< IntegrationRuntimesListOutboundNetworkDependenciesEndpointsResponse > { return this.client.sendOperationRequest( { resourceGroupName, factoryName, integrationRuntimeName, options }, listOutboundNetworkDependenciesEndpointsOperationSpec ); } /** * Gets the on-premises integration runtime connection information for encrypting the on-premises data * source credentials. * @param resourceGroupName The resource group name. * @param factoryName The factory name. * @param integrationRuntimeName The integration runtime name. * @param options The options parameters. */ getConnectionInfo( resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: IntegrationRuntimesGetConnectionInfoOptionalParams ): Promise<IntegrationRuntimesGetConnectionInfoResponse> { return this.client.sendOperationRequest( { resourceGroupName, factoryName, integrationRuntimeName, options }, getConnectionInfoOperationSpec ); } /** * Regenerates the authentication key for an integration runtime. * @param resourceGroupName The resource group name. * @param factoryName The factory name. * @param integrationRuntimeName The integration runtime name. * @param regenerateKeyParameters The parameters for regenerating integration runtime authentication * key. * @param options The options parameters. */ regenerateAuthKey( resourceGroupName: string, factoryName: string, integrationRuntimeName: string, regenerateKeyParameters: IntegrationRuntimeRegenerateKeyParameters, options?: IntegrationRuntimesRegenerateAuthKeyOptionalParams ): Promise<IntegrationRuntimesRegenerateAuthKeyResponse> { return this.client.sendOperationRequest( { resourceGroupName, factoryName, integrationRuntimeName, regenerateKeyParameters, options }, regenerateAuthKeyOperationSpec ); } /** * Retrieves the authentication keys for an integration runtime. * @param resourceGroupName The resource group name. * @param factoryName The factory name. * @param integrationRuntimeName The integration runtime name. * @param options The options parameters. */ listAuthKeys( resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: IntegrationRuntimesListAuthKeysOptionalParams ): Promise<IntegrationRuntimesListAuthKeysResponse> { return this.client.sendOperationRequest( { resourceGroupName, factoryName, integrationRuntimeName, options }, listAuthKeysOperationSpec ); } /** * Starts a ManagedReserved type integration runtime. * @param resourceGroupName The resource group name. * @param factoryName The factory name. * @param integrationRuntimeName The integration runtime name. * @param options The options parameters. */ async beginStart( resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: IntegrationRuntimesStartOptionalParams ): Promise< PollerLike< PollOperationState<IntegrationRuntimesStartResponse>, IntegrationRuntimesStartResponse > > { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<IntegrationRuntimesStartResponse> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, factoryName, integrationRuntimeName, options }, startOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Starts a ManagedReserved type integration runtime. * @param resourceGroupName The resource group name. * @param factoryName The factory name. * @param integrationRuntimeName The integration runtime name. * @param options The options parameters. */ async beginStartAndWait( resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: IntegrationRuntimesStartOptionalParams ): Promise<IntegrationRuntimesStartResponse> { const poller = await this.beginStart( resourceGroupName, factoryName, integrationRuntimeName, options ); return poller.pollUntilDone(); } /** * Stops a ManagedReserved type integration runtime. * @param resourceGroupName The resource group name. * @param factoryName The factory name. * @param integrationRuntimeName The integration runtime name. * @param options The options parameters. */ async beginStop( resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: IntegrationRuntimesStopOptionalParams ): Promise<PollerLike<PollOperationState<void>, void>> { const directSendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ): Promise<void> => { return this.client.sendOperationRequest(args, spec); }; const sendOperation = async ( args: coreClient.OperationArguments, spec: coreClient.OperationSpec ) => { let currentRawResponse: | coreClient.FullOperationResponse | undefined = undefined; const providedCallback = args.options?.onResponse; const callback: coreClient.RawResponseCallback = ( rawResponse: coreClient.FullOperationResponse, flatResponse: unknown ) => { currentRawResponse = rawResponse; providedCallback?.(rawResponse, flatResponse); }; const updatedArgs = { ...args, options: { ...args.options, onResponse: callback } }; const flatResponse = await directSendOperation(updatedArgs, spec); return { flatResponse, rawResponse: { statusCode: currentRawResponse!.status, body: currentRawResponse!.parsedBody, headers: currentRawResponse!.headers.toJSON() } }; }; const lro = new LroImpl( sendOperation, { resourceGroupName, factoryName, integrationRuntimeName, options }, stopOperationSpec ); return new LroEngine(lro, { resumeFrom: options?.resumeFrom, intervalInMs: options?.updateIntervalInMs }); } /** * Stops a ManagedReserved type integration runtime. * @param resourceGroupName The resource group name. * @param factoryName The factory name. * @param integrationRuntimeName The integration runtime name. * @param options The options parameters. */ async beginStopAndWait( resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: IntegrationRuntimesStopOptionalParams ): Promise<void> { const poller = await this.beginStop( resourceGroupName, factoryName, integrationRuntimeName, options ); return poller.pollUntilDone(); } /** * Force the integration runtime to synchronize credentials across integration runtime nodes, and this * will override the credentials across all worker nodes with those available on the dispatcher node. * If you already have the latest credential backup file, you should manually import it (preferred) on * any self-hosted integration runtime node than using this API directly. * @param resourceGroupName The resource group name. * @param factoryName The factory name. * @param integrationRuntimeName The integration runtime name. * @param options The options parameters. */ syncCredentials( resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: IntegrationRuntimesSyncCredentialsOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, factoryName, integrationRuntimeName, options }, syncCredentialsOperationSpec ); } /** * Get the integration runtime monitoring data, which includes the monitor data for all the nodes under * this integration runtime. * @param resourceGroupName The resource group name. * @param factoryName The factory name. * @param integrationRuntimeName The integration runtime name. * @param options The options parameters. */ getMonitoringData( resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: IntegrationRuntimesGetMonitoringDataOptionalParams ): Promise<IntegrationRuntimesGetMonitoringDataResponse> { return this.client.sendOperationRequest( { resourceGroupName, factoryName, integrationRuntimeName, options }, getMonitoringDataOperationSpec ); } /** * Upgrade self-hosted integration runtime to latest version if availability. * @param resourceGroupName The resource group name. * @param factoryName The factory name. * @param integrationRuntimeName The integration runtime name. * @param options The options parameters. */ upgrade( resourceGroupName: string, factoryName: string, integrationRuntimeName: string, options?: IntegrationRuntimesUpgradeOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, factoryName, integrationRuntimeName, options }, upgradeOperationSpec ); } /** * Remove all linked integration runtimes under specific data factory in a self-hosted integration * runtime. * @param resourceGroupName The resource group name. * @param factoryName The factory name. * @param integrationRuntimeName The integration runtime name. * @param linkedIntegrationRuntimeRequest The data factory name for the linked integration runtime. * @param options The options parameters. */ removeLinks( resourceGroupName: string, factoryName: string, integrationRuntimeName: string, linkedIntegrationRuntimeRequest: LinkedIntegrationRuntimeRequest, options?: IntegrationRuntimesRemoveLinksOptionalParams ): Promise<void> { return this.client.sendOperationRequest( { resourceGroupName, factoryName, integrationRuntimeName, linkedIntegrationRuntimeRequest, options }, removeLinksOperationSpec ); } /** * Create a linked integration runtime entry in a shared integration runtime. * @param resourceGroupName The resource group name. * @param factoryName The factory name. * @param integrationRuntimeName The integration runtime name. * @param createLinkedIntegrationRuntimeRequest The linked integration runtime properties. * @param options The options parameters. */ createLinkedIntegrationRuntime( resourceGroupName: string, factoryName: string, integrationRuntimeName: string, createLinkedIntegrationRuntimeRequest: CreateLinkedIntegrationRuntimeRequest, options?: IntegrationRuntimesCreateLinkedIntegrationRuntimeOptionalParams ): Promise<IntegrationRuntimesCreateLinkedIntegrationRuntimeResponse> { return this.client.sendOperationRequest( { resourceGroupName, factoryName, integrationRuntimeName, createLinkedIntegrationRuntimeRequest, options }, createLinkedIntegrationRuntimeOperationSpec ); } /** * ListByFactoryNext * @param resourceGroupName The resource group name. * @param factoryName The factory name. * @param nextLink The nextLink from the previous successful call to the ListByFactory method. * @param options The options parameters. */ private _listByFactoryNext( resourceGroupName: string, factoryName: string, nextLink: string, options?: IntegrationRuntimesListByFactoryNextOptionalParams ): Promise<IntegrationRuntimesListByFactoryNextResponse> { return this.client.sendOperationRequest( { resourceGroupName, factoryName, nextLink, options }, listByFactoryNextOperationSpec ); } } // Operation Specifications const serializer = coreClient.createSerializer(Mappers, /* isXml */ false); const listByFactoryOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/integrationRuntimes", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.IntegrationRuntimeListResponse }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.factoryName ], headerParameters: [Parameters.accept], serializer }; const createOrUpdateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/integrationRuntimes/{integrationRuntimeName}", httpMethod: "PUT", responses: { 200: { bodyMapper: Mappers.IntegrationRuntimeResource }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.integrationRuntime, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.factoryName, Parameters.integrationRuntimeName ], headerParameters: [ Parameters.accept, Parameters.contentType, Parameters.ifMatch ], mediaType: "json", serializer }; const getOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/integrationRuntimes/{integrationRuntimeName}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.IntegrationRuntimeResource }, 304: {}, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.factoryName, Parameters.integrationRuntimeName ], headerParameters: [Parameters.accept, Parameters.ifNoneMatch], serializer }; const updateOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/integrationRuntimes/{integrationRuntimeName}", httpMethod: "PATCH", responses: { 200: { bodyMapper: Mappers.IntegrationRuntimeResource }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.updateIntegrationRuntimeRequest, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.factoryName, Parameters.integrationRuntimeName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const deleteOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/integrationRuntimes/{integrationRuntimeName}", httpMethod: "DELETE", responses: { 200: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.factoryName, Parameters.integrationRuntimeName ], headerParameters: [Parameters.accept], serializer }; const getStatusOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/integrationRuntimes/{integrationRuntimeName}/getStatus", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.IntegrationRuntimeStatusResponse }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.factoryName, Parameters.integrationRuntimeName ], headerParameters: [Parameters.accept], serializer }; const listOutboundNetworkDependenciesEndpointsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/integrationRuntimes/{integrationRuntimeName}/outboundNetworkDependenciesEndpoints", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.IntegrationRuntimeOutboundNetworkDependenciesEndpointsResponse }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.factoryName, Parameters.integrationRuntimeName ], headerParameters: [Parameters.accept], serializer }; const getConnectionInfoOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/integrationRuntimes/{integrationRuntimeName}/getConnectionInfo", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.IntegrationRuntimeConnectionInfo }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.factoryName, Parameters.integrationRuntimeName ], headerParameters: [Parameters.accept], serializer }; const regenerateAuthKeyOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/integrationRuntimes/{integrationRuntimeName}/regenerateAuthKey", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.IntegrationRuntimeAuthKeys }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.regenerateKeyParameters, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.factoryName, Parameters.integrationRuntimeName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listAuthKeysOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/integrationRuntimes/{integrationRuntimeName}/listAuthKeys", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.IntegrationRuntimeAuthKeys }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.factoryName, Parameters.integrationRuntimeName ], headerParameters: [Parameters.accept], serializer }; const startOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/integrationRuntimes/{integrationRuntimeName}/start", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.IntegrationRuntimeStatusResponse }, 201: { bodyMapper: Mappers.IntegrationRuntimeStatusResponse }, 202: { bodyMapper: Mappers.IntegrationRuntimeStatusResponse }, 204: { bodyMapper: Mappers.IntegrationRuntimeStatusResponse }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.factoryName, Parameters.integrationRuntimeName ], headerParameters: [Parameters.accept], serializer }; const stopOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/integrationRuntimes/{integrationRuntimeName}/stop", httpMethod: "POST", responses: { 200: {}, 201: {}, 202: {}, 204: {}, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.factoryName, Parameters.integrationRuntimeName ], headerParameters: [Parameters.accept], serializer }; const syncCredentialsOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/integrationRuntimes/{integrationRuntimeName}/syncCredentials", httpMethod: "POST", responses: { 200: {}, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.factoryName, Parameters.integrationRuntimeName ], headerParameters: [Parameters.accept], serializer }; const getMonitoringDataOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/integrationRuntimes/{integrationRuntimeName}/monitoringData", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.IntegrationRuntimeMonitoringData }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.factoryName, Parameters.integrationRuntimeName ], headerParameters: [Parameters.accept], serializer }; const upgradeOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/integrationRuntimes/{integrationRuntimeName}/upgrade", httpMethod: "POST", responses: { 200: {}, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.factoryName, Parameters.integrationRuntimeName ], headerParameters: [Parameters.accept], serializer }; const removeLinksOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/integrationRuntimes/{integrationRuntimeName}/removeLinks", httpMethod: "POST", responses: { 200: {}, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.linkedIntegrationRuntimeRequest, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.factoryName, Parameters.integrationRuntimeName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const createLinkedIntegrationRuntimeOperationSpec: coreClient.OperationSpec = { path: "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataFactory/factories/{factoryName}/integrationRuntimes/{integrationRuntimeName}/linkedIntegrationRuntime", httpMethod: "POST", responses: { 200: { bodyMapper: Mappers.IntegrationRuntimeStatusResponse }, default: { bodyMapper: Mappers.CloudError } }, requestBody: Parameters.createLinkedIntegrationRuntimeRequest, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.factoryName, Parameters.integrationRuntimeName ], headerParameters: [Parameters.accept, Parameters.contentType], mediaType: "json", serializer }; const listByFactoryNextOperationSpec: coreClient.OperationSpec = { path: "{nextLink}", httpMethod: "GET", responses: { 200: { bodyMapper: Mappers.IntegrationRuntimeListResponse }, default: { bodyMapper: Mappers.CloudError } }, queryParameters: [Parameters.apiVersion], urlParameters: [ Parameters.$host, Parameters.nextLink, Parameters.subscriptionId, Parameters.resourceGroupName, Parameters.factoryName ], headerParameters: [Parameters.accept], serializer };
the_stack
import {TestOptions, Test, Spec, Report} from "@swim/unit"; import {Attr, Slot, Value, Record, Data, Text, Num, Bool} from "@swim/structure"; import {ReconExam} from "../ReconExam"; export class ReconParserSpec extends Spec { override createExam(report: Report, name: string, options: TestOptions): ReconExam { return new ReconExam(report, this, name, options); } @Test parseEmptyInput(exam: ReconExam): void { exam.parses("", Value.absent()); } @Test parseComments(exam: ReconExam): void { exam.parses("#", Value.absent()); exam.parses("#comment", Value.absent()); exam.parses("#\n", Value.absent()); exam.parses("#comment\n", Value.absent()); } @Test parseEmptyRecords(exam: ReconExam): void { exam.parses("{}", Record.empty()); } @Test parseNonEmptyRecords(exam: ReconExam): void { exam.parses("{1,2,\"3\",true}", Record.of(1, 2, "3", true)); exam.parses("1,2,\"3\",true", Record.of(1, 2, "3", true)); } @Test parseNestedRecords(exam: ReconExam): void { exam.parses("{{1,2},{3,4}}", Record.of(Record.of(1, 2), Record.of(3, 4))); exam.parses("{1,2},{3,4}", Record.of(Record.of(1, 2), Record.of(3, 4))); } @Test parseRecordsWithComments(exam: ReconExam): void { exam.parses("{#comment\n}", Record.empty()); exam.parses("{#comment\n#comment\n}", Record.empty()); } @Test parseEmptyData(exam: ReconExam): void { exam.parses("%", Data.empty()); } @Test parseNonEmptyData(exam: ReconExam): void { exam.parses("%AAAA", Data.fromBase64("AAAA")); exam.parses("%AAA=", Data.fromBase64("AAA=")); exam.parses("%AA==", Data.fromBase64("AA==")); exam.parses("%ABCDabcd12/+", Data.fromBase64("ABCDabcd12/+")); } @Test parseEmptyMarkup(exam: ReconExam): void { exam.parses("[]", Record.empty()); } @Test parseEmptyStrings(exam: ReconExam): void { exam.parses("\"\"", Text.empty()); exam.parses("''", Text.empty()); } @Test parseNonEmptyStrings(exam: ReconExam): void { exam.parses("\"test\"", Text.from("test")); exam.parses("'test'", Text.from("test")); } @Test parseStringsWithEscapes(exam: ReconExam): void { exam.parses("\"\\\"\\\\\\/\\@\\{\\}\\[\\]\\b\\f\\n\\r\\t\"", Text.from("\"\\/@{}[]\b\f\n\r\t")); exam.parses("'\\'\\\\\\/\\@\\{\\}\\[\\]\\b\\f\\n\\r\\t'", Text.from("'\\/@{}[]\b\f\n\r\t")); } @Test parseEmptyRawStrings(exam: ReconExam): void { exam.parses("``", Text.empty()); exam.parses(" `` ", Text.empty()); exam.parses("``````", Text.empty()); exam.parses(" `````` ", Text.empty()); } @Test parseNonEmptyRawStrings(exam: ReconExam): void { exam.parses("`test`", Text.from("test")); exam.parses("```test```", Text.from("test")); } @Test parseRawStringsWithBackticks(exam: ReconExam): void { exam.parses("``` ` ```", Text.from(" ` ")); exam.parses("``` `` ```", Text.from(" `` ")); exam.parses("``` \\` ```", Text.from(" ` ")); exam.parses("``` \\`\\` ```", Text.from(" `` ")); exam.parses("``` \\`\\`\\` ```", Text.from(" ``` ")); } @Test parseRawStringsWithBackslashes(exam: ReconExam): void { exam.parses("``` \\ ```", Text.from(" \\ ")); exam.parses("``` \\\\` ```", Text.from(" \\` ")); } @Test parseIdentifiers(exam: ReconExam): void { exam.parses("test", Text.from("test")); } @Test parseUnicodeIdentifiers(exam: ReconExam): void { exam.parses("À", Text.from("À")); // U+C0 exam.parses("Ö", Text.from("Ö")); // U+D6 exam.parses("Ø", Text.from("Ø")); // U+D8 exam.parses("ö", Text.from("ö")); // U+F6 exam.parses("ø", Text.from("ø")); // U+F8 exam.parses("˿", Text.from("˿")); // U+2FF exam.parses("Ͱ", Text.from("Ͱ")); // U+370 exam.parses("ͽ", Text.from("ͽ")); // U+37D exam.parses("Ϳ", Text.from("Ϳ")); // U+37F exam.parses("῿", Text.from("῿")); // U+1FFF exam.parses("⁰", Text.from("⁰")); // U+2070 exam.parses("↏", Text.from("↏")); // U+218F exam.parses("Ⰰ", Text.from("Ⰰ")); // U+2C00 exam.parses("⿯", Text.from("⿯")); // U+2FEF exam.parses("、", Text.from("、")); // U+3001 exam.parses("퟿", Text.from("퟿")); // U+D7FF exam.parses("豈", Text.from("豈")); // U+F900 exam.parses("﷏", Text.from("﷏")); // U+FDCF exam.parses("ﷰ", Text.from("ﷰ")); // U+FDF0 //exam.parses("𐀀", Text.from("𐀀")); // U+10000 //exam.parses("󯿿", Text.from("󯿿")); // U+EFFFF exam.parses("_À", Text.from("_À")); // U+C0 exam.parses("_Ö", Text.from("_Ö")); // U+D6 exam.parses("_Ø", Text.from("_Ø")); // U+D8 exam.parses("_ö", Text.from("_ö")); // U+F6 exam.parses("_ø", Text.from("_ø")); // U+F8 exam.parses("_˿", Text.from("_˿")); // U+2FF exam.parses("_Ͱ", Text.from("_Ͱ")); // U+370 exam.parses("_ͽ", Text.from("_ͽ")); // U+37D exam.parses("_Ϳ", Text.from("_Ϳ")); // U+37F exam.parses("_῿", Text.from("_῿")); // U+1FFF exam.parses("_⁰", Text.from("_⁰")); // U+2070 exam.parses("_↏", Text.from("_↏")); // U+218F exam.parses("_Ⰰ", Text.from("_Ⰰ")); // U+2C00 exam.parses("_⿯", Text.from("_⿯")); // U+2FEF exam.parses("_、", Text.from("_、")); // U+3001 exam.parses("_퟿", Text.from("_퟿")); // U+D7FF exam.parses("_豈", Text.from("_豈")); // U+F900 exam.parses("_﷏", Text.from("_﷏")); // U+FDCF exam.parses("_ﷰ", Text.from("_ﷰ")); // U+FDF0 //exam.parses("_𐀀", Text.from("_𐀀")); // U+10000 //exam.parses("_󯿿", Text.from("_󯿿")); // U+EFFFF } @Test parsePositiveIntegers(exam: ReconExam): void { exam.parses("0", Num.from(0)); exam.parses("1", Num.from(1)); exam.parses("5", Num.from(5)); exam.parses("10", Num.from(10)); exam.parses("11", Num.from(11)); exam.parses("15", Num.from(15)); exam.parses("2147483647", Num.from(2147483647)); exam.parses("9007199254740992", Num.from(9007199254740992)); } @Test parseNegativeIntegers(exam: ReconExam): void { exam.parses("-0", Num.from(-0)); exam.parses("-1", Num.from(-1)); exam.parses("-5", Num.from(-5)); exam.parses("-10", Num.from(-10)); exam.parses("-11", Num.from(-11)); exam.parses("-15", Num.from(-15)); exam.parses("-2147483648", Num.from(-2147483648)); exam.parses("-9007199254740991", Num.from(-9007199254740991)); } @Test parsePositiveDecimals(exam: ReconExam): void { exam.parses("0.0", Num.from(0.0)); exam.parses("0.5", Num.from(0.5)); exam.parses("1.0", Num.from(1.0)); exam.parses("1.5", Num.from(1.5)); exam.parses("1.05", Num.from(1.05)); exam.parses("10.0", Num.from(10.0)); exam.parses("10.5", Num.from(10.5)); } @Test parseNegativeDecimals(exam: ReconExam): void { exam.parses("-0.0", Num.from(-0.0)); exam.parses("-0.5", Num.from(-0.5)); exam.parses("-1.0", Num.from(-1.0)); exam.parses("-1.5", Num.from(-1.5)); exam.parses("-1.05", Num.from(-1.05)); exam.parses("-10.0", Num.from(-10.0)); exam.parses("-10.5", Num.from(-10.5)); } @Test parsePositiveDecimalsWithExponents(exam: ReconExam): void { exam.parses("4e0", Num.from(4e0)); exam.parses("4E0", Num.from(4E0)); exam.parses("4e1", Num.from(4e1)); exam.parses("4E1", Num.from(4E1)); exam.parses("4e2", Num.from(4e2)); exam.parses("4E2", Num.from(4E2)); exam.parses("4e+0", Num.from(4e+0)); exam.parses("4E+0", Num.from(4E+0)); exam.parses("4e-0", Num.from(4e-0)); exam.parses("4E-0", Num.from(4E-0)); exam.parses("4e+1", Num.from(4e+1)); exam.parses("4E+1", Num.from(4E+1)); exam.parses("4e-1", Num.from(4e-1)); exam.parses("4E-1", Num.from(4E-1)); exam.parses("4e+2", Num.from(4e+2)); exam.parses("4E+2", Num.from(4E+2)); exam.parses("4e-2", Num.from(4e-2)); exam.parses("4E-2", Num.from(4E-2)); exam.parses("4.0e2", Num.from(4.0e2)); exam.parses("4.0E2", Num.from(4.0E2)); exam.parses("4.0e+2", Num.from(4.0e+2)); exam.parses("4.0E+2", Num.from(4.0E+2)); exam.parses("4.0e-2", Num.from(4.0e-2)); exam.parses("4.0E-2", Num.from(4.0E-2)); exam.parses("1.17549435e-38", Num.from(1.17549435e-38)); // Float.MIN_VALUE exam.parses("3.4028235e38", Num.from(3.4028235e38)); // Float.MAX_VALUE exam.parses("1.17549435e-38", Num.from(1.17549435e-38)); // Float.MIN_NORMAL exam.parses("4.9e-324", Num.from(4.9e-324)); // Double.MIN_VALUE exam.parses("1.7976931348623157e308", Num.from(1.7976931348623157e308)); // Double.MAX_VALUE exam.parses("2.2250738585072014e-308", Num.from(2.2250738585072014e-308)); // Double.MIN_NORMAL } @Test parseNegativeDecimalsWithExponents(exam: ReconExam): void { exam.parses("-4e0", Num.from(-4e0)); exam.parses("-4E0", Num.from(-4E0)); exam.parses("-4e1", Num.from(-4e1)); exam.parses("-4E1", Num.from(-4E1)); exam.parses("-4e2", Num.from(-4e2)); exam.parses("-4E2", Num.from(-4E2)); exam.parses("-4e+0", Num.from(-4e+0)); exam.parses("-4E+0", Num.from(-4E+0)); exam.parses("-4e-0", Num.from(-4e-0)); exam.parses("-4E-0", Num.from(-4E-0)); exam.parses("-4e+1", Num.from(-4e+1)); exam.parses("-4E+1", Num.from(-4E+1)); exam.parses("-4e-1", Num.from(-4e-1)); exam.parses("-4E-1", Num.from(-4E-1)); exam.parses("-4e+2", Num.from(-4e+2)); exam.parses("-4E+2", Num.from(-4E+2)); exam.parses("-4e-2", Num.from(-4e-2)); exam.parses("-4E-2", Num.from(-4E-2)); exam.parses("-4.0e2", Num.from(-4.0e2)); exam.parses("-4.0E2", Num.from(-4.0E2)); exam.parses("-4.0e+2", Num.from(-4.0e+2)); exam.parses("-4.0E+2", Num.from(-4.0E+2)); exam.parses("-4.0e-2", Num.from(-4.0e-2)); exam.parses("-4.0E-2", Num.from(-4.0E-2)); exam.parses("-4.0e02", Num.from(-4.0e2)); exam.parses("-4.0E02", Num.from(-4.0E2)); exam.parses("-4.0e+02", Num.from(-4.0e+2)); exam.parses("-4.0E+02", Num.from(-4.0E+2)); exam.parses("-4.0e-02", Num.from(-4.0e-2)); exam.parses("-4.0E-02", Num.from(-4.0E-2)); } @Test parseUint32s(exam: ReconExam): void { exam.parses("0x0", Num.uint32(0x0)); exam.parses("0x00000001", Num.uint32(0x00000001)); exam.parses("0x00000010", Num.uint32(0x00000010)); exam.parses("0x00000100", Num.uint32(0x00000100)); exam.parses("0x00001000", Num.uint32(0x00001000)); exam.parses("0x00010000", Num.uint32(0x00010000)); exam.parses("0x00100000", Num.uint32(0x00100000)); exam.parses("0x01000000", Num.uint32(0x01000000)); exam.parses("0x10000000", Num.uint32(0x10000000)); exam.parses("0xFFFFFFFF", Num.uint32(0xFFFFFFFF)); exam.parses("0xFEDCBA98", Num.uint32(0xFEDCBA98)); exam.parses("0x01234567", Num.uint32(0x01234567)); } @Test parseBooleans(exam: ReconExam): void { exam.parses("true", Bool.from(true)); exam.parses("false", Bool.from(false)); } @Test parseSingleValuesWithTrailingCommas(exam: ReconExam): void { exam.parses("1,", Num.from(1)); } @Test parseSingleValuesWithTrailingSemicolons(exam: ReconExam): void { exam.parses("1;", Num.from(1)); } @Test parseMultipleCommaSeparatedItems(exam: ReconExam): void { exam.parses(" 1, 2,3 ,4 ", Record.of(1, 2, 3, 4)); exam.parses("{1, 2,3 ,4 }", Record.of(1, 2, 3, 4)); } @Test parseMultipleSemicolonSeparatedItems(exam: ReconExam): void { exam.parses(" 1; 2;3 ;4 ", Record.of(1, 2, 3, 4)); exam.parses("{1; 2;3 ;4 }", Record.of(1, 2, 3, 4)); } @Test parseMultipleItemsWithTrailingCommas(exam: ReconExam): void { exam.parses(" 1, 2,3 ,4, ", Record.of(1, 2, 3, 4)); exam.parses("{1, 2,3 ,4, }", Record.of(1, 2, 3, 4)); } @Test parseMultipleItemsWithTrailingSemicolons(exam: ReconExam): void { exam.parses(" 1, 2,3 ,4; ", Record.of(1, 2, 3, 4)); exam.parses("{1, 2,3 ,4; }", Record.of(1, 2, 3, 4)); } @Test parseMultipleNewlineSeparatedItems(exam: ReconExam): void { exam.parses(" 1\n 2\n3 \n4 ", Record.of(1, 2, 3, 4)); exam.parses("{1\n 2\n3 \n4 }", Record.of(1, 2, 3, 4)); } @Test parseMultipleItemsWithMixedSeparators(exam: ReconExam): void { exam.parses(" 1, 2\n3 \n4; 5 ", Record.of(1, 2, 3, 4, 5)); exam.parses("{1, 2\n3 \n4; 5 }", Record.of(1, 2, 3, 4, 5)); } @Test parseMultipleCommaNewlineSeparatedItems(exam: ReconExam): void { exam.parses(" \n 1,\n 2,\n3 \n ", Record.of(1, 2, 3)); exam.parses("{\n 1,\n 2,\n3 \n}", Record.of(1, 2, 3)); } @Test parseMultipleSemicolonNewlineSeparatedItems(exam: ReconExam): void { exam.parses(" \n 1;\n 2;\n3 \n ", Record.of(1, 2, 3)); exam.parses("{\n 1;\n 2;\n3 \n}", Record.of(1, 2, 3)); } @Test parseHeterogeneousTopLevelItemsAsRecord(exam: ReconExam): void { exam.parses(" extant:\n record: {}\n markup: []\n \"\"\n %AA==\n integer: 0\n decimal: 0.0\n true\n false\n", Record.of(Slot.of("extant"), Slot.of("record", Record.empty()), Slot.of("markup", Record.empty()), "", Data.fromBase64("AA=="), Slot.of("integer", 0), Slot.of("decimal", 0.0), true, false)); } @Test parseHeterogeneousItemsInRecord(exam: ReconExam): void { exam.parses("{\n extant:\n record: {}\n markup: []\n \"\"\n %AA==\n integer: 0\n decimal: 0.0\n true\n false\n}", Record.of(Slot.of("extant"), Slot.of("record", Record.empty()), Slot.of("markup", Record.empty()), "", Data.fromBase64("AA=="), Slot.of("integer", 0), Slot.of("decimal", 0.0), true, false)); } @Test parseLeadingComments(exam: ReconExam): void { exam.parses("#comment\ntest", Text.from("test")); } @Test parseLeadingCommentsInBlocks(exam: ReconExam): void { exam.parses("#comment\n1\n#comment\n2", Record.of(1, 2)); } @Test parseLeadingCommentsInRecords(exam: ReconExam): void { exam.parses("{#comment\n1\n#comment\n2}", Record.of(1, 2)); } @Test parseTrailingComments(exam: ReconExam): void { exam.parses("test#comment", Text.from("test")); } @Test parseTrailingCommentsInBlocks(exam: ReconExam): void { exam.parses("1#comment\n2#comment", Record.of(1, 2)); } @Test parseTrailingCommentsInRecords(exam: ReconExam): void { exam.parses("{1#comment\n2#comment\n}", Record.of(1, 2)); } @Test parseSingleExtantAttributesWithNoParameters(exam: ReconExam): void { exam.parses("@test", Record.of(Attr.of("test"))); } @Test parseSingleExtantAttributesWithEmptyParameters(exam: ReconExam): void { exam.parses("@test()", Record.of(Attr.of("test"))); } @Test parseQuotedAttributeNames(exam: ReconExam): void { exam.parses("@\"test\"", Record.of(Attr.of("test"))); exam.parses("@\"test\"()", Record.of(Attr.of("test"))); exam.parses("@\"@at\"", Record.of(Attr.of("@at"))); exam.parses("@\"@at\"()", Record.of(Attr.of("@at"))); } @Test parseSingleExtantAttributesWithSingleParameters(exam: ReconExam): void { exam.parses("@hello()", Record.of(Attr.of("hello"))); exam.parses("@hello([world])", Record.of(Attr.of("hello", Record.of("world")))); exam.parses("@hello(\"world\")", Record.of(Attr.of("hello", "world"))); exam.parses("@hello(42)", Record.of(Attr.of("hello", 42))); } @Test parseSingleExtantAttributesWithMultipleParameters(exam: ReconExam): void { exam.parses("@hello(\"world\", %AA==, 42, true)", Record.of(Attr.of("hello", Record.of("world", Data.fromBase64("AA=="), 42, true)))); exam.parses("@hello(\"world\"; %AA==; 42; true)", Record.of(Attr.of("hello", Record.of("world", Data.fromBase64("AA=="), 42, true)))); exam.parses("@hello(\"world\"\n%AA==\n42\ntrue)", Record.of(Attr.of("hello", Record.of("world", Data.fromBase64("AA=="), 42, true)))); } @Test parseSingleExtantAttributesWithNamedParameters(exam: ReconExam): void { exam.parses("@hello(name: \"world\")", Record.of(Attr.of("hello", Record.of(Slot.of("name", "world"))))); exam.parses("@hello(name: \"world\", data: %AA==, number: 42, false)", Record.of(Attr.of("hello", Record.of(Slot.of("name", "world"), Slot.of("data", Data.fromBase64("AA==")), Slot.of("number", 42), false)))); } @Test parseMultipleExtantAttributesWithNoParameters(exam: ReconExam): void { exam.parses("@a@b", Record.of(Attr.of("a"), Attr.of("b"))); exam.parses("@a @b", Record.of(Attr.of("a"), Attr.of("b"))); } @Test parseMultipleExtantAttributesWithEmptyParameters(exam: ReconExam): void { exam.parses("@a()@b()", Record.of(Attr.of("a"), Attr.of("b"))); exam.parses("@a() @b()", Record.of(Attr.of("a"), Attr.of("b"))); } @Test parseMultipleExtantAttributesWithSingleParameters(exam: ReconExam): void { exam.parses("@a({})@b([])", Record.of(Attr.of("a", Record.empty()), Attr.of("b", Record.empty()))); exam.parses("@a(\"test\") @b(42)", Record.of(Attr.of("a", "test"), Attr.of("b", 42))); exam.parses("@a(true) @b(false)", Record.of(Attr.of("a", Bool.from(true)), Attr.of("b", Bool.from(false)))); } @Test parseMultipleExtantAttributesWithComplexParameters(exam: ReconExam): void { exam.parses("@hello(\"world\", 42) @test(name: \"parse\", pending: false)", Record.of(Attr.of("hello", Record.of("world", 42)), Attr.of("test", Record.of(Slot.of("name", "parse"), Slot.of("pending", Bool.from(false)))))); } @Test parsePrefixAttributedEmptyRecords(exam: ReconExam): void { exam.parses("@hello {}", Record.of(Attr.of("hello"))); exam.parses("@hello() {}", Record.of(Attr.of("hello"))); exam.parses("@hello(\"world\") {}", Record.of(Attr.of("hello", "world"))); exam.parses("@hello(name: \"world\") {}", Record.of(Attr.of("hello", Record.of(Slot.of("name", "world"))))); } @Test parsePrefixAttributedNonEmptyRecords(exam: ReconExam): void { exam.parses("@hello { {}, [] }", Record.of(Attr.of("hello"), Record.empty(), Record.empty())); exam.parses("@hello() { \"world\", 42 }", Record.of(Attr.of("hello"), "world", 42)); exam.parses("@hello(\"world\") { number: 42, true }", Record.of(Attr.of("hello", "world"), Slot.of("number", 42), true)); exam.parses("@hello(name: \"world\") { {1,2} }", Record.of(Attr.of("hello", Record.of(Slot.of("name", "world"))), Record.of(1, 2))); } @Test parsePrefixAttributedEmptyMarkup(exam: ReconExam): void { exam.parses("@hello []", Record.of(Attr.of("hello"))); exam.parses("@hello() []", Record.of(Attr.of("hello"))); exam.parses("@hello(\"world\") []", Record.of(Attr.of("hello", "world"))); exam.parses("@hello(name: \"world\") []", Record.of(Attr.of("hello", Record.of(Slot.of("name", "world"))))); } @Test parsePrefixAttributedNonEmptyMarkup(exam: ReconExam): void { exam.parses("@hello [test]", Record.of(Attr.of("hello"), "test")); exam.parses("@hello() [test]", Record.of(Attr.of("hello"), "test")); exam.parses("@hello(\"world\") [test]", Record.of(Attr.of("hello", "world"), "test")); exam.parses("@hello(name: \"world\") [test]", Record.of(Attr.of("hello", Record.of(Slot.of("name", "world"))), "test")); } @Test parsePrefixAttributedEmptyStrings(exam: ReconExam): void { exam.parses("@hello \"\"", Record.of(Attr.of("hello"), "")); exam.parses("@hello() \"\"", Record.of(Attr.of("hello"), "")); exam.parses("@hello(\"world\") \"\"", Record.of(Attr.of("hello", "world"), "")); exam.parses("@hello(name: \"world\") \"\"", Record.of(Attr.of("hello", Record.of(Slot.of("name", "world"))), "")); exam.parses("@hello ''", Record.of(Attr.of("hello"), "")); exam.parses("@hello() ''", Record.of(Attr.of("hello"), "")); exam.parses("@hello('world') ''", Record.of(Attr.of("hello", "world"), "")); exam.parses("@hello(name: 'world') ''", Record.of(Attr.of("hello", Record.of(Slot.of("name", "world"))), "")); } @Test parsePrefixAttributedNonEmptyStrings(exam: ReconExam): void { exam.parses("@hello \"test\"", Record.of(Attr.of("hello"), "test")); exam.parses("@hello() \"test\"", Record.of(Attr.of("hello"), "test")); exam.parses("@hello(\"world\") \"test\"", Record.of(Attr.of("hello", "world"), "test")); exam.parses("@hello(name: \"world\") \"test\"", Record.of(Attr.of("hello", Record.of(Slot.of("name", "world"))), "test")); exam.parses("@hello 'test'", Record.of(Attr.of("hello"), "test")); exam.parses("@hello() 'test'", Record.of(Attr.of("hello"), "test")); exam.parses("@hello('world') 'test'", Record.of(Attr.of("hello", "world"), "test")); exam.parses("@hello(name: 'world') 'test'", Record.of(Attr.of("hello", Record.of(Slot.of("name", "world"))), "test")); } @Test parsePrefixAttributedEmptyData(exam: ReconExam): void { exam.parses("@hello %", Record.of(Attr.of("hello"), Data.empty())); exam.parses("@hello() %", Record.of(Attr.of("hello"), Data.empty())); exam.parses("@hello(\"world\") %", Record.of(Attr.of("hello", "world"), Data.empty())); exam.parses("@hello(name: \"world\") %", Record.of(Attr.of("hello", Record.of(Slot.of("name", "world"))), Data.empty())); } @Test parsePrefixAttributedNonEmptyData(exam: ReconExam): void { exam.parses("@hello %AA==", Record.of(Attr.of("hello"), Data.fromBase64("AA=="))); exam.parses("@hello() %AAA=", Record.of(Attr.of("hello"), Data.fromBase64("AAA="))); exam.parses("@hello(\"world\") %AAAA", Record.of(Attr.of("hello", "world"), Data.fromBase64("AAAA"))); exam.parses("@hello(name: \"world\") %ABCDabcd12+/", Record.of(Attr.of("hello", Record.of(Slot.of("name", "world"))), Data.fromBase64("ABCDabcd12+/"))); } @Test parsePrefixAttributedNumbers(exam: ReconExam): void { exam.parses("@hello 42", Record.of(Attr.of("hello"), 42)); exam.parses("@hello() -42", Record.of(Attr.of("hello"), -42)); exam.parses("@hello(\"world\") 42.0", Record.of(Attr.of("hello", "world"), 42.0)); exam.parses("@hello(name: \"world\") -42.0", Record.of(Attr.of("hello", Record.of(Slot.of("name", "world"))), -42.0)); } @Test parsePrefixAttributedBooleans(exam: ReconExam): void { exam.parses("@hello true", Record.of(Attr.of("hello"), true)); exam.parses("@hello() false", Record.of(Attr.of("hello"), false)); exam.parses("@hello(\"world\") true", Record.of(Attr.of("hello", "world"), true)); exam.parses("@hello(name: \"world\") false", Record.of(Attr.of("hello", Record.of(Slot.of("name", "world"))), false)); } @Test parsePostfixAttributedEmptyRecords(exam: ReconExam): void { exam.parses("{} @signed", Record.of(Attr.of("signed"))); exam.parses("{} @signed()", Record.of(Attr.of("signed"))); exam.parses("{} @signed(\"me\")", Record.of(Attr.of("signed", "me"))); exam.parses("{} @signed(by: \"me\")", Record.of(Attr.of("signed", Record.of(Slot.of("by", "me"))))); } @Test parsePostfixAttributedNonEmptyRecords(exam: ReconExam): void { exam.parses("{ {}, [] } @signed", Record.of(Record.empty(), Record.empty(), Attr.of("signed"))); exam.parses("{ \"world\", 42 } @signed()", Record.of("world", 42, Attr.of("signed"))); exam.parses("{ number: 42, true } @signed(\"me\")", Record.of(Slot.of("number", 42), true, Attr.of("signed", "me"))); exam.parses("{ {1,2} } @signed(by: \"me\")", Record.of(Record.of(1, 2), Attr.of("signed", Record.of(Slot.of("by", "me"))))); } @Test parsePostfixAttributedEmptyMarkup(exam: ReconExam): void { exam.parses("[] @signed", Record.of(Attr.of("signed"))); exam.parses("[] @signed()", Record.of(Attr.of("signed"))); exam.parses("[] @signed(\"me\")", Record.of(Attr.of("signed", "me"))); exam.parses("[] @signed(by: \"me\")", Record.of(Attr.of("signed", Record.of(Slot.of("by", "me"))))); } @Test parsePostfixAttributedNonEmptyMarkup(exam: ReconExam): void { exam.parses("[test] @signed", Record.of("test", Attr.of("signed"))); exam.parses("[test] @signed()", Record.of("test", Attr.of("signed"))); exam.parses("[test] @signed(\"me\")", Record.of("test", Attr.of("signed", "me"))); exam.parses("[test] @signed(by: \"me\")", Record.of("test", Attr.of("signed", Record.of(Slot.of("by", "me"))))); } @Test parsePostfixAttributedEmptyStrings(exam: ReconExam): void { exam.parses("\"\" @signed", Record.of("", Attr.of("signed"))); exam.parses("\"\" @signed()", Record.of("", Attr.of("signed"))); exam.parses("\"\" @signed(\"me\")", Record.of("", Attr.of("signed", "me"))); exam.parses("\"\" @signed(by: \"me\")", Record.of("", Attr.of("signed", Record.of(Slot.of("by", "me"))))); exam.parses("'' @signed", Record.of("", Attr.of("signed"))); exam.parses("'' @signed()", Record.of("", Attr.of("signed"))); exam.parses("'' @signed('me')", Record.of("", Attr.of("signed", "me"))); exam.parses("'' @signed(by: 'me')", Record.of("", Attr.of("signed", Record.of(Slot.of("by", "me"))))); } @Test parsePostfixAttributedNonEmptyStrings(exam: ReconExam): void { exam.parses("\"test\" @signed", Record.of("test", Attr.of("signed"))); exam.parses("\"test\" @signed()", Record.of("test", Attr.of("signed"))); exam.parses("\"test\" @signed(\"me\")", Record.of("test", Attr.of("signed", "me"))); exam.parses("\"test\" @signed(by: \"me\")", Record.of("test", Attr.of("signed", Record.of(Slot.of("by", "me"))))); exam.parses("'test' @signed", Record.of("test", Attr.of("signed"))); exam.parses("'test' @signed()", Record.of("test", Attr.of("signed"))); exam.parses("'test' @signed('me')", Record.of("test", Attr.of("signed", "me"))); exam.parses("'test' @signed(by: 'me')", Record.of("test", Attr.of("signed", Record.of(Slot.of("by", "me"))))); } @Test parsePostfixAttributedEmptyData(exam: ReconExam): void { exam.parses("% @signed", Record.of(Data.empty(), Attr.of("signed"))); exam.parses("% @signed()", Record.of(Data.empty(), Attr.of("signed"))); exam.parses("% @signed(\"me\")", Record.of(Data.empty(), Attr.of("signed", "me"))); exam.parses("% @signed(by: \"me\")", Record.of(Data.empty(), Attr.of("signed", Record.of(Slot.of("by", "me"))))); } @Test parsePostfixAttributedNonEmptyData(exam: ReconExam): void { exam.parses("%AA== @signed", Record.of(Data.fromBase64("AA=="), Attr.of("signed"))); exam.parses("%AAA= @signed()", Record.of(Data.fromBase64("AAA="), Attr.of("signed"))); exam.parses("%AAAA @signed(\"me\")", Record.of(Data.fromBase64("AAAA"), Attr.of("signed", "me"))); exam.parses("%ABCDabcd12+/ @signed(by: \"me\")", Record.of(Data.fromBase64("ABCDabcd12+/"), Attr.of("signed", Record.of(Slot.of("by", "me"))))); } @Test parsePostfixAttributeNumbers(exam: ReconExam): void { exam.parses("42 @signed", Record.of(42, Attr.of("signed"))); exam.parses("-42 @signed()", Record.of(-42, Attr.of("signed"))); exam.parses("42.0 @signed(\"me\")", Record.of(42.0, Attr.of("signed", "me"))); exam.parses("-42.0 @signed(by: \"me\")", Record.of(-42.0, Attr.of("signed", Record.of(Slot.of("by", "me"))))); } @Test parsePostfixAttributeBooleans(exam: ReconExam): void { exam.parses("true @signed", Record.of(true, Attr.of("signed"))); exam.parses("false @signed()", Record.of(false, Attr.of("signed"))); exam.parses("true @signed(\"me\")", Record.of(true, Attr.of("signed", "me"))); exam.parses("false @signed(by: \"me\")", Record.of(false, Attr.of("signed", Record.of(Slot.of("by", "me"))))); } @Test parseInfixAttributedEmptyRecords(exam: ReconExam): void { exam.parses("{}@hello{}", Record.of(Attr.of("hello"))); exam.parses("{}@hello(){}", Record.of(Attr.of("hello"))); exam.parses("{}@hello(\"world\"){}", Record.of(Attr.of("hello", "world"))); exam.parses("{}@hello(name: \"world\"){}", Record.of(Attr.of("hello", Record.of(Slot.of("name", "world"))))); } @Test parseInfixAttributedNonEmptyRecords(exam: ReconExam): void { exam.parses("{{}}@hello{[]}", Record.of(Record.empty(), Attr.of("hello"), Record.empty())); exam.parses("{42}@hello(){\"world\"}", Record.of(42, Attr.of("hello"), "world")); exam.parses("{number: 42}@hello(\"world\"){true}", Record.of(Slot.of("number", 42), Attr.of("hello", "world"), true)); exam.parses("{{1,2}}@hello(name: \"world\"){{3,4}}", Record.of(Record.of(1, 2), Attr.of("hello", Record.of(Slot.of("name", "world"))), Record.of(3, 4))); } @Test parseInfixAttributedEmptyMarkup(exam: ReconExam): void { exam.parses("[]@hello[]", Record.of(Attr.of("hello"))); exam.parses("[]@hello()[]", Record.of(Attr.of("hello"))); exam.parses("[]@hello(\"world\")[]", Record.of(Attr.of("hello", "world"))); exam.parses("[]@hello(name: \"world\")[]", Record.of(Attr.of("hello", Record.of(Slot.of("name", "world"))))); } @Test parseInfixAttributedNonEmptyMarkup(exam: ReconExam): void { exam.parses("[a]@hello[test]", Record.of("a", Attr.of("hello"), "test")); exam.parses("[a]@hello()[test]", Record.of("a", Attr.of("hello"), "test")); exam.parses("[a]@hello(\"world\")[test]", Record.of("a", Attr.of("hello", "world"), "test")); exam.parses("[a]@hello(name: \"world\")[test]", Record.of("a", Attr.of("hello", Record.of(Slot.of("name", "world"))), "test")); } @Test parseInfixAttributedEmptyStrings(exam: ReconExam): void { exam.parses("\"\"@hello\"\"", Record.of("", Attr.of("hello"), "")); exam.parses("\"\"@hello()\"\"", Record.of("", Attr.of("hello"), "")); exam.parses("\"\"@hello(\"world\")\"\"", Record.of("", Attr.of("hello", "world"), "")); exam.parses("\"\"@hello(name: \"world\")\"\"", Record.of("", Attr.of("hello", Record.of(Slot.of("name", "world"))), "")); exam.parses("''@hello''", Record.of("", Attr.of("hello"), "")); exam.parses("''@hello()''", Record.of("", Attr.of("hello"), "")); exam.parses("''@hello('world')''", Record.of("", Attr.of("hello", "world"), "")); exam.parses("''@hello(name: 'world')''", Record.of("", Attr.of("hello", Record.of(Slot.of("name", "world"))), "")); } @Test parseInfixAttributedNonEmptyStrings(exam: ReconExam): void { exam.parses("\"a\"@hello\"test\"", Record.of("a", Attr.of("hello"), "test")); exam.parses("\"a\"@hello()\"test\"", Record.of("a", Attr.of("hello"), "test")); exam.parses("\"a\"@hello(\"world\")\"test\"", Record.of("a", Attr.of("hello", "world"), "test")); exam.parses("\"a\"@hello(name: \"world\")\"test\"", Record.of("a", Attr.of("hello", Record.of(Slot.of("name", "world"))), "test")); exam.parses("'a'@hello'test'", Record.of("a", Attr.of("hello"), "test")); exam.parses("'a'@hello()'test'", Record.of("a", Attr.of("hello"), "test")); exam.parses("'a'@hello('world')'test'", Record.of("a", Attr.of("hello", "world"), "test")); exam.parses("'a'@hello(name: 'world')'test'", Record.of("a", Attr.of("hello", Record.of(Slot.of("name", "world"))), "test")); } @Test parseInfixAttributedEmptyData(exam: ReconExam): void { exam.parses("%@hello%", Record.of(Data.empty(), Attr.of("hello"), Data.empty())); exam.parses("%@hello()%", Record.of(Data.empty(), Attr.of("hello"), Data.empty())); exam.parses("%@hello(\"world\")%", Record.of(Data.empty(), Attr.of("hello", "world"), Data.empty())); exam.parses("%@hello(name: \"world\")%", Record.of(Data.empty(), Attr.of("hello", Record.of(Slot.of("name", "world"))), Data.empty())); } @Test parseInfixAttributedNonEmptyData(exam: ReconExam): void { exam.parses("%AA==@hello%BB==", Record.of(Data.fromBase64("AA=="), Attr.of("hello"), Data.fromBase64("BB=="))); exam.parses("%AAA=@hello()%BBB=", Record.of(Data.fromBase64("AAA="), Attr.of("hello"), Data.fromBase64("BBB="))); exam.parses("%AAAA@hello(\"world\")%BBBB", Record.of(Data.fromBase64("AAAA"), Attr.of("hello", "world"), Data.fromBase64("BBBB"))); exam.parses("%ABCDabcd12+/@hello(name: \"world\")%/+21dcbaDCBA", Record.of(Data.fromBase64("ABCDabcd12+/"), Attr.of("hello", Record.of(Slot.of("name", "world"))), Data.fromBase64("/+21dcbaDCBA"))); } @Test parseInfixAttributedNumbers(exam: ReconExam): void { exam.parses("2@hello 42", Record.of(2, Attr.of("hello"), 42)); exam.parses("-2@hello()-42", Record.of(-2, Attr.of("hello"), -42)); exam.parses("2.0@hello(\"world\")42.0", Record.of(2.0, Attr.of("hello", "world"), 42.0)); exam.parses("-2.0@hello(name: \"world\")-42.0", Record.of(-2.0, Attr.of("hello", Record.of(Slot.of("name", "world"))), -42.0)); } @Test parseInfixAttributedBooleans(exam: ReconExam): void { exam.parses("true@hello true", Record.of(true, Attr.of("hello"), true)); exam.parses("false@hello()false", Record.of(false, Attr.of("hello"), false)); exam.parses("true@hello(\"world\")true", Record.of(true, Attr.of("hello", "world"), true)); exam.parses("false@hello(name: \"world\")false", Record.of(false, Attr.of("hello", Record.of(Slot.of("name", "world"))), false)); } @Test parseNonEmptyMarkup(exam: ReconExam): void { exam.parses("[test]", Record.of("test")); } @Test parseMarkupWithEmbeddedMarkup(exam: ReconExam): void { exam.parses("[Hello, [good] world!]", Record.of("Hello, ", "good", " world!")); } @Test parseMarkupWithEscapes(exam: ReconExam): void { exam.parses("[\\\"\\$\\'\\\\\\/\\@\\{\\}\\[\\]\\b\\f\\n\\r\\t]", Record.of("\"$'\\/@{}[]\b\f\n\r\t")); } @Test parseMarkupWithEmbeddedStructure(exam: ReconExam): void { exam.parses("[Hello{}world]", Record.of("Hello", "world")); exam.parses("[A: {\"answer\"}.]", Record.of("A: ", "answer", ".")); exam.parses("[A: {%AA==}.]", Record.of("A: ", Data.fromBase64("AA=="), ".")); exam.parses("[A: {42}.]", Record.of("A: ", 42, ".")); exam.parses("[A: {true}.]", Record.of("A: ", true, ".")); exam.parses("[A: {false}.]", Record.of("A: ", false, ".")); exam.parses("[A: {answer:0.0}.]", Record.of("A: ", Slot.of("answer", 0.0), ".")); } @Test parseMarkupWithEmbeddedSingleExtantAttributes(exam: ReconExam): void { exam.parses("[A: @answer.]", Record.of("A: ", Record.of(Attr.of("answer")), ".")); exam.parses("[A: @answer().]", Record.of("A: ", Record.of(Attr.of("answer")), ".")); exam.parses("[A: @answer(\"secret\").]", Record.of("A: ", Record.of(Attr.of("answer", "secret")), ".")); exam.parses("[A: @answer(number: 42, true).]", Record.of("A: ", Record.of(Attr.of("answer", Record.of(Slot.of("number", 42), true))), ".")); } @Test parseMarkupWithEmbeddedSequentialExtantAttributes(exam: ReconExam): void { exam.parses("[A: @good @answer.]", Record.of("A: ", Record.of(Attr.of("good")), " ", Record.of(Attr.of("answer")), ".")); exam.parses("[A: @good@answer.]", Record.of("A: ", Record.of(Attr.of("good")), Record.of(Attr.of("answer")), ".")); exam.parses("[A: @good() @answer().]", Record.of("A: ", Record.of(Attr.of("good")), " ", Record.of(Attr.of("answer")), ".")); exam.parses("[A: @good()@answer().]", Record.of("A: ", Record.of(Attr.of("good")), Record.of(Attr.of("answer")), ".")); } @Test parseMarkupWithEmbeddedAttributedMarkup(exam: ReconExam): void { exam.parses("[Hello, @em[world]!]", Record.of("Hello, ", Record.of(Attr.of("em"), "world"), "!")); exam.parses("[Hello, @em()[world]!]", Record.of("Hello, ", Record.of(Attr.of("em"), "world"), "!")); exam.parses("[Hello, @em(\"italic\")[world]!]", Record.of("Hello, ", Record.of(Attr.of("em", "italic"), "world"), "!")); exam.parses("[Hello, @em(class:\"subject\",style:\"italic\")[world]!]", Record.of("Hello, ", Record.of(Attr.of("em", Record.of(Slot.of("class", "subject"), Slot.of("style", "italic"))), "world"), "!")); } @Test parseMarkupWithEmbeddedAttributedValues(exam: ReconExam): void { exam.parses("[A: @answer{42}.]", Record.of("A: ", Record.of(Attr.of("answer"), 42), ".")); exam.parses("[A: @answer(){42}.]", Record.of("A: ", Record.of(Attr.of("answer"), 42), ".")); exam.parses("[A: @answer(\"secret\"){42}.]", Record.of("A: ", Record.of(Attr.of("answer", "secret"), 42), ".")); exam.parses("[A: @answer(number: 42, secret){true}.]", Record.of("A: ", Record.of(Attr.of("answer", Record.of(Slot.of("number", 42), "secret")), true), ".")); } @Test parseUnclosedEmptyRecordFails(exam: ReconExam): void { exam.parseFails("{"); exam.parseFails("{#comment"); } @Test parseUnclosedNonEmptyRecordFails(exam: ReconExam): void { exam.parseFails("{1"); exam.parseFails("{1 "); exam.parseFails("{1,"); exam.parseFails("{1#comment"); } @Test parseUnclosedEmptyMarkupFails(exam: ReconExam): void { exam.parseFails("["); } @Test parseUnclosedNonEmptyMarkupFails(exam: ReconExam): void { exam.parseFails("[test"); exam.parseFails("[test{}"); } @Test parseUnclosedEmptyStringFails(exam: ReconExam): void { exam.parseFails("\""); exam.parseFails("'"); } @Test parseUnclosedNonEmptyStringFails(exam: ReconExam): void { exam.parseFails("\"test"); exam.parseFails("\"test\\"); exam.parseFails("'test"); exam.parseFails("'test\\"); } @Test parseNakedNegativeFails(exam: ReconExam): void { exam.parseFails("-"); } @Test parseTrailingDecimalFails(exam: ReconExam): void { exam.parseFails("1."); } @Test parseTrailingExponentFails(exam: ReconExam): void { exam.parseFails("1e"); exam.parseFails("1E"); exam.parseFails("1.e"); exam.parseFails("1.E"); exam.parseFails("1.0e"); exam.parseFails("1.0E"); exam.parseFails("1.0e+"); exam.parseFails("1.0E+"); exam.parseFails("1.0e-"); exam.parseFails("1.0E-"); } @Test parseUnpaddedDataFails(exam: ReconExam): void { exam.parseFails("%AAA"); exam.parseFails("%AA"); exam.parseFails("%A"); } @Test parseMalformedDataFails(exam: ReconExam): void { exam.parseFails("%AA=A"); } @Test parseKeylessAttrFails(exam: ReconExam): void { exam.parseFails("@"); exam.parseFails("@()"); } @Test parseKeylessSlotFails(exam: ReconExam): void { exam.parseFails(":"); exam.parseFails(":test"); } @Test parseTrailingValuesFails(exam: ReconExam): void { exam.parseFails("{}{}"); exam.parseFails("1 2"); } }
the_stack
import * as fs from "fs"; import * as path from "path"; import { is } from "@atjson/document"; import { VerticalAdjust } from "../src/annotations"; import { GDocsPasteBuffer } from "../src/gdocs-parser"; import GDocsSource from "../src/index"; describe("@atjson/source-gdocs-paste", () => { describe("relatively complex document", () => { let pasteBuffer: GDocsPasteBuffer; beforeAll(() => { // https://docs.google.com/document/d/18pp4dAGx5II596HHGOLUXXcc6VKLAVRBUMLm9Ge8eOE/edit?usp=sharing let fixturePath = path.join(__dirname, "fixtures", "complex.json"); pasteBuffer = JSON.parse(fs.readFileSync(fixturePath).toString()); }); it("has some json", () => { expect(pasteBuffer).toHaveProperty("resolved"); }); it("does not throw an error when instantiating with GDocsSource", () => { expect(GDocsSource.fromRaw(pasteBuffer)).toBeDefined(); }); it("correctly sets the content", () => { let gdocs = GDocsSource.fromRaw(pasteBuffer); expect(gdocs.content.length).toEqual(438); expect(gdocs.content).toMatchSnapshot(); }); it("extracts bold", () => { let gdocs = GDocsSource.fromRaw(pasteBuffer); let annotations = gdocs.where((a) => a.type === "ts_bd"); expect(annotations.length).toEqual(2); let [a0, a1] = annotations; expect(gdocs.content.substring(a0.start, a0.end)).toEqual("simple te"); expect(gdocs.content.substring(a1.start, a1.end)).toEqual("re is so"); }); it("extracts italic", () => { let gdocs = GDocsSource.fromRaw(pasteBuffer); let annotations = gdocs.where((a) => a.type === "ts_it"); expect(annotations.length).toEqual(2); let [a0, a1] = [...annotations]; expect(gdocs.content.substring(a0.start, a0.end)).toEqual("simple "); expect(gdocs.content.substring(a1.start, a1.end)).toEqual("some "); }); it("extracts headings", () => { let gdocs = GDocsSource.fromRaw(pasteBuffer); let annotations = gdocs.where((a) => a.type === "ps_hd").sort(); expect(annotations.length).toEqual(4); let [a0, a1, a2, a3] = [...annotations]; expect(gdocs.content.substring(a0.start, a0.end)).toEqual("Heading 1"); expect(a0.attributes.level).toEqual(1); expect(gdocs.content.substring(a1.start, a1.end)).toEqual("Heading 2"); expect(a1.attributes.level).toEqual(2); expect(gdocs.content.substring(a2.start, a2.end)).toEqual("Title"); expect(a2.attributes.level).toEqual(100); expect(gdocs.content.substring(a3.start, a3.end)).toEqual("Subtitle"); expect(a3.attributes.level).toEqual(101); }); describe("lists", () => { it("extracts lists", () => { let gdocs = GDocsSource.fromRaw(pasteBuffer); let annotations = gdocs.where((a) => a.type === "list"); expect(annotations.length).toEqual(2); let [a0] = [...annotations]; expect(gdocs.content.substring(a0.start, a0.end)).toEqual( "Here’s a numbered list\nAnd another item" ); expect(a0.attributes.ls_id).toEqual("kix.trdi2u6o1bvt"); }); it("extracts list items", () => { let gdocs = GDocsSource.fromRaw(pasteBuffer); let annotations = gdocs.where((a) => a.type === "list_item"); expect(annotations.length).toEqual(4); let [a0, a1] = [...annotations]; expect(gdocs.content.substring(a0.start, a0.end)).toEqual( "Here’s a numbered list" ); expect(a0.attributes.ls_id).toEqual("kix.trdi2u6o1bvt"); expect(a0.attributes.ls_nest).toEqual(0); expect(gdocs.content.substring(a1.start, a1.end)).toEqual( "And another item" ); expect(a1.attributes.ls_id).toEqual("kix.trdi2u6o1bvt"); expect(a1.attributes.ls_nest).toEqual(0); }); }); it("extracts links", () => { let gdocs = GDocsSource.fromRaw(pasteBuffer); let annotations = gdocs.where((a) => a.type === "lnks_link"); expect(annotations.length).toEqual(1); let [link] = [...annotations]; expect(gdocs.content.substring(link.start, link.end)).toEqual(" is "); expect(link.attributes.ulnk_url).toEqual("https://www.google.com/"); expect(link.attributes.lnk_type).toEqual(0); }); }); describe("a grab-bag of Google Docs features", () => { let gdocsBuffer: any; beforeAll(() => { // https://docs.google.com/document/d/18pp4dAGx5II596HHGOLUXXcc6VKLAVRBUMLm9Ge8eOE/edit?usp=sharing let fixturePath = path.join( __dirname, "fixtures", "formats-and-tabs.json" ); gdocsBuffer = JSON.parse(fs.readFileSync(fixturePath).toString()); }); it("has some json", () => { expect(gdocsBuffer).toHaveProperty("resolved"); }); it("does not throw an error when instantiating with GDocsSource", () => { expect(GDocsSource.fromRaw(gdocsBuffer)).toBeDefined(); }); it("correctly sets the content", () => { let gdocs = GDocsSource.fromRaw(gdocsBuffer); expect(gdocs.content.length).toEqual(219); expect(gdocs.content).toMatchSnapshot(); }); it("extracts bold", () => { let gdocs = GDocsSource.fromRaw(gdocsBuffer); let annotations = gdocs.where((a) => a.type === "ts_bd"); expect(annotations.length).toEqual(1); let [bold] = annotations; expect(gdocs.content.substring(bold.start, bold.end)).toEqual("bold"); }); it("extracts italic", () => { let gdocs = GDocsSource.fromRaw(gdocsBuffer); let annotations = gdocs.where((a) => a.type === "ts_it"); expect(annotations.length).toEqual(1); let [italic] = annotations; expect(gdocs.content.substring(italic.start, italic.end)).toEqual( "italic" ); }); it("extracts underline", () => { let gdocs = GDocsSource.fromRaw(gdocsBuffer); let annotations = gdocs.where((a) => a.type === "ts_un"); expect(annotations.length).toEqual(1); let [underline] = annotations; expect(gdocs.content.substring(underline.start, underline.end)).toEqual( "underlined" ); }); it("extracts horizontal rules", () => { let gdocs = GDocsSource.fromRaw(gdocsBuffer); let annotations = gdocs.where((a) => a.type === "horizontal_rule"); expect(annotations.length).toEqual(1); let [hr] = annotations; expect(gdocs.content.substring(hr.start, hr.end)).toEqual("-"); }); it("extracts strikethrough", () => { let gdocs = GDocsSource.fromRaw(gdocsBuffer); let annotations = gdocs.where((a) => a.type === "ts_st"); expect(annotations.length).toEqual(1); let [strikethrough] = annotations; expect( gdocs.content.substring(strikethrough.start, strikethrough.end) ).toEqual("strikethrough"); }); it("extracts vertical adjust", () => { let gdocs = GDocsSource.fromRaw(gdocsBuffer); let annotations = gdocs.where((a) => is(a, VerticalAdjust)); expect(annotations.length).toEqual(2); let [superscript] = annotations.where( (annotation) => annotation.attributes.va === "sup" ); let [subscript] = annotations.where( (annotation) => annotation.attributes.va === "sub" ); expect( gdocs.content.substring(superscript.start, superscript.end) ).toEqual("TM"); expect(gdocs.content.substring(subscript.start, subscript.end)).toEqual( "2" ); }); }); describe("list styles", () => { let gdocsBuffer: any; beforeAll(() => { let fixturePath = path.join(__dirname, "fixtures", "list-styles.json"); gdocsBuffer = JSON.parse(fs.readFileSync(fixturePath).toString()); }); it("creates the right number of list annotations", () => { let gdocs = GDocsSource.fromRaw(gdocsBuffer); let lists = gdocs.where((a) => a.type === "list"); expect(lists.length).toEqual(2); }); it("captures list-specific attributes", () => { let gdocs = GDocsSource.fromRaw(gdocsBuffer); let lists = gdocs.where((a) => a.type === "list"); let expectedShape = expect.objectContaining({ ls_b_gs: expect.anything(), ls_b_gt: expect.anything(), ls_b_a: expect.anything(), }); for (let list of lists) { expect(list.attributes).toEqual(expectedShape); } }); it("distinguishes numbered from bulleted lists", () => { let gdocs = GDocsSource.fromRaw(gdocsBuffer); let lists = gdocs.annotations .filter((a) => a.type === "list") .filter((a) => a.attributes.ls_b_gt === 9); expect(lists.length).toEqual(1); }); }); describe("partial link pastes", () => { let gdocsBuffer: any; beforeAll(() => { let fixturePath = path.join(__dirname, "fixtures", "partial.json"); gdocsBuffer = JSON.parse(fs.readFileSync(fixturePath).toString()); }); it("creates the right number of link annotations", () => { let gdocs = GDocsSource.fromRaw(gdocsBuffer); let links = gdocs.annotations.filter((a) => a.type === "lnks_link"); expect(links.length).toEqual(1); }); }); describe("partial list pastes", () => { let pasteBuffer: any; beforeAll(() => { // https://docs.google.com/document/d/1PKNoasDTf0Pj71vJs4MAi9zOrWDA3TDSNj0RFXWoCp4/edit let fixturePath = path.join( __dirname, "fixtures", "list-styles-partial.json" ); pasteBuffer = JSON.parse(fs.readFileSync(fixturePath).toString()); }); it("creates the right number of list and list-item annotations", () => { let gdocs = GDocsSource.fromRaw(pasteBuffer); let listAndItems = gdocs .where((a) => a.type === "list") .as("list") .join( gdocs.where((a) => a.type === "list_item").as("listItems"), (l, r) => l.start <= r.start && l.end >= r.end ); expect(listAndItems.toJSON()).toMatchObject([ { list: { start: 0, end: 22, type: "-gdocs-list" }, listItems: [ { start: 0, end: 8, type: "-gdocs-list_item" }, { start: 9, end: 22, type: "-gdocs-list_item" }, ], }, { list: { start: 41, end: 68, type: "-gdocs-list" }, listItems: [ { start: 41, end: 54, type: "-gdocs-list_item" }, { start: 55, end: 68, type: "-gdocs-list_item" }, ], }, { list: { start: 89, end: 102, type: "-gdocs-list" }, listItems: [{ start: 89, end: 102, type: "-gdocs-list_item" }], }, ]); }); }); });
the_stack
import * as angular from 'angular'; import { ICompileService, IRootScopeService } from 'angular'; import { extend } from '@uirouter/core'; declare let inject, jasmine; const module = angular.mock.module; function animateFlush($animate) { if ($animate && $animate.flush) { $animate.flush(); // 1.4 } else if ($animate && $animate.triggerCallbacks) { $animate.triggerCallbacks(); // 1.2-1.3 } } describe('uiView', function () { 'use strict'; let $stateProvider, scope, $compile, elem, log; beforeEach(function () { const depends = ['ui.router']; log = ''; try { angular.module('ngAnimate'); depends.push('ngAnimate', 'ngAnimateMock'); } catch (e) { angular.module('mock.animate', []).value('$animate', null); module('mock.animate'); } angular.module('ui.router.test', depends); module('ui.router.test'); }); beforeEach( module(function ($provide) { $provide.decorator('$uiViewScroll', function () { return jasmine.createSpy('$uiViewScroll'); }); }) ); const aState = { template: 'aState template', }, bState = { template: 'bState template', }, cState = { views: { cview: { template: 'cState cview template', }, }, }, dState = { views: { dview1: { template: 'dState dview1 template', }, dview2: { template: 'dState dview2 template', }, }, }, eState = { template: '<div ui-view="eview" class="eview"></div>', }, fState = { views: { eview: { template: 'fState eview template', }, }, }, gState = { template: '<div ui-view="inner"><span>{{content}}</span></div>', }, hState = { views: { inner: { template: 'hState inner template', }, }, }, iState = { template: '<div ui-view>' + '<ul><li ng-repeat="item in items">{{item}}</li></ul>' + '</div>', }, jState = { template: 'jState', }, kState = { controller: function () { this.someProperty = 'value'; }, template: '{{vm.someProperty}}', controllerAs: 'vm', }, lState = { views: { view1: { template: 'view1', }, view2: { template: 'view2', }, view3: { template: 'view3', }, }, }, mState = { template: 'mState', controller: function ($scope, $element) { $scope.elementId = $element.attr('id'); }, }, nState = { template: 'nState', controller: function ($scope, $element) { const data = $element.data('$uiViewAnim'); $scope.$on('$destroy', function () { log += 'destroy;'; }); data.$animEnter.then(function () { log += 'animEnter;'; }); data.$animLeave.then(function () { log += 'animLeave;'; }); }, }; beforeEach( module(function (_$stateProvider_) { $stateProvider = _$stateProvider_; $stateProvider .state('a', aState) .state('b', bState) .state('c', cState) .state('d', dState) .state('e', eState) .state('e.f', fState) .state('g', gState) .state('g.h', hState) .state('i', iState) .state('j', jState) .state('k', kState) .state('l', lState) .state('m', mState) .state('n', nState); }) ); beforeEach(inject(function ($rootScope, _$compile_) { scope = $rootScope.$new(); $compile = _$compile_; elem = angular.element('<div>'); })); describe('linking ui-directive', function () { it('anonymous ui-view should be replaced with the template of the current $state', inject(function ($state, $q) { elem.append($compile('<div><ui-view></ui-view></div>')(scope)); expect(elem.find('ui-view').text()).toBe(''); $state.transitionTo(aState); $q.flush(); expect(elem.find('ui-view').text()).toBe(aState.template); })); it('named ui-view should be replaced with the template of the current $state', inject(function ($state, $q) { elem.append($compile('<div><ui-view name="cview"></ui-view></div>')(scope)); $state.transitionTo(cState); $q.flush(); expect(elem.find('ui-view').text()).toBe(cState.views.cview.template); })); it('ui-view should be updated after transition to another state', inject(function ($state, $q) { elem.append($compile('<div><ui-view></ui-view></div>')(scope)); expect(elem.find('ui-view').text()).toBe(''); $state.transitionTo(aState); $q.flush(); expect(elem.find('ui-view').text()).toBe(aState.template); $state.transitionTo(bState); $q.flush(); expect(elem.find('ui-view').text()).toBe(bState.template); })); it('should handle NOT nested ui-views', inject(function ($state, $q) { elem.append( $compile( '<div><ui-view name="dview1" class="dview1"></ui-view><ui-view name="dview2" class="dview2"></ui-view></div>' )(scope) ); expect(elem.find('ui-view').eq(0).text()).toBe(''); expect(elem.find('ui-view').eq(1).text()).toBe(''); $state.transitionTo(dState); $q.flush(); expect(elem.find('ui-view').eq(0).text()).toBe(dState.views.dview1.template); expect(elem.find('ui-view').eq(1).text()).toBe(dState.views.dview2.template); })); it('should handle nested ui-views (testing two levels deep)', inject(function ($state, $q) { $compile(elem.append('<div><ui-view></ui-view></div>'))(scope); expect(elem.find('ui-view').text()).toBe(''); $state.transitionTo(fState); $q.flush(); expect(elem.find('ui-view').text()).toBe(fState.views.eview.template); })); }); describe('handling initial view', function () { it('initial view should be compiled if the view is empty', inject(function ($state, $q) { const content = 'inner content'; scope.content = content; elem.append($compile('<div><ui-view></ui-view></div>')(scope)); $state.transitionTo(gState); $q.flush(); expect(elem.find('ui-view').text()).toBe(content); })); it('initial view should be put back after removal of the view', inject(function ($state, $q) { const content = 'inner content'; scope.content = content; elem.append($compile('<div><ui-view></ui-view></div>')(scope)); $state.go(hState); $q.flush(); expect(elem.find('ui-view').text()).toBe(hState.views.inner.template); // going to the parent state which makes the inner view empty $state.go(gState); $q.flush(); expect(elem.find('ui-view').text()).toBe(content); })); // related to issue #435 it('initial view should be transcluded once to prevent breaking other directives', inject(function ($state, $q) { scope.items = ['I', 'am', 'a', 'list', 'of', 'items']; elem.append($compile('<div><ui-view></ui-view></div>')(scope)); // transition to state that has an initial view $state.transitionTo(iState); $q.flush(); // verify if ng-repeat has been compiled expect(elem.find('li').length).toBe(scope.items.length); // transition to another state that replace the initial content $state.transitionTo(jState); $q.flush(); expect(elem.find('ui-view').text()).toBe(jState.template); // transition back to the state with empty subview and the initial view $state.transitionTo(iState); $q.flush(); // verify if the initial view is correct expect(elem.find('li').length).toBe(scope.items.length); // change scope properties scope.$apply(function () { scope.items.push('.', 'Working?'); }); // verify if the initial view has been updated expect(elem.find('li').length).toBe(scope.items.length); })); }); describe('autoscroll attribute', function () { it('should NOT autoscroll when unspecified', inject(function ($state, $q, $uiViewScroll, $animate) { elem.append($compile('<div><ui-view></ui-view></div>')(scope)); $state.transitionTo(aState); $q.flush(); animateFlush($animate); expect($uiViewScroll).not.toHaveBeenCalled(); })); it('should autoscroll when expression is missing', inject(function ($state, $q, $uiViewScroll, $animate) { elem.append($compile('<div><ui-view autoscroll></ui-view></div>')(scope)); $state.transitionTo(aState); $q.flush(); animateFlush($animate); expect($uiViewScroll).toHaveBeenCalledWith(elem.find('ui-view')); })); it('should autoscroll based on expression', inject(function ($state, $q, $uiViewScroll, $animate) { scope.doScroll = false; elem.append($compile('<div><ui-view autoscroll="doScroll"></ui-view></div>')(scope)); $state.transitionTo(aState); $q.flush(); animateFlush($animate); expect($uiViewScroll).not.toHaveBeenCalled(); scope.doScroll = true; $state.transitionTo(bState); $q.flush(); animateFlush($animate); let target, index = -1, uiViews = elem.find('ui-view'); while (index++ < uiViews.length) { const uiView = angular.element(uiViews[index]); if (uiView.text() === bState.template) target = uiView; } expect($uiViewScroll).toHaveBeenCalledWith(target); })); }); it('should instantiate a controller with controllerAs', inject(function ($state, $q) { elem.append($compile('<div><ui-view></ui-view></div>')(scope)); $state.transitionTo(kState); $q.flush(); expect(elem.text()).toBe('value'); })); it('should instantiate a controller with both $scope and $element injections', inject(function ($state, $q) { elem.append($compile('<div><ui-view id="mState">{{elementId}}</ui-view></div>')(scope)); $state.transitionTo(mState); $q.flush(); expect(elem.text()).toBe('mState'); })); describe('(resolved data)', function () { let _scope; function controller($scope) { _scope = $scope; } const _state = { name: 'resolve', resolve: { user: function ($timeout) { return $timeout(function () { return 'joeschmoe'; }, 100); }, }, }; it('should provide the resolved data on the $scope', inject(function ($state, $q, $timeout) { const state = angular.extend({}, _state, { template: '{{$resolve.user}}', controller: controller }); $stateProvider.state(state); elem.append($compile('<div><ui-view></ui-view></div>')(scope)); $state.transitionTo('resolve'); $q.flush(); $timeout.flush(); expect(elem.text()).toBe('joeschmoe'); expect(_scope.$resolve).toBeDefined(); expect(_scope.$resolve.user).toBe('joeschmoe'); })); // Test for #2626 it('should provide the resolved data on the $scope even if there is no controller', inject(function ( $state, $q, $timeout ) { const state = angular.extend({}, _state, { template: '{{$resolve.user}}' }); $stateProvider.state(state); elem.append($compile('<div><ui-view></ui-view></div>')(scope)); expect(elem.text()).toBe(''); $state.transitionTo('resolve'); $q.flush(); $timeout.flush(); expect(elem.text()).toBe('joeschmoe'); })); it('should put the resolved data on the resolveAs variable', inject(function ($state, $q, $timeout) { const state = angular.extend({}, _state, { template: '{{$$$resolve.user}}', resolveAs: '$$$resolve', controller: controller, }); $stateProvider.state(state); elem.append($compile('<div><ui-view></ui-view></div>')(scope)); $state.transitionTo('resolve'); $q.flush(); $timeout.flush(); expect(elem.text()).toBe('joeschmoe'); expect(_scope.$$$resolve).toBeDefined(); expect(_scope.$$$resolve.user).toBe('joeschmoe'); })); it('should put the resolved data on the controllerAs', inject(function ($state, $q, $timeout) { const state = angular.extend({}, _state, { template: '{{$ctrl.$resolve.user}}', controllerAs: '$ctrl', controller: controller, }); $stateProvider.state(state); elem.append($compile('<div><ui-view></ui-view></div>')(scope)); $state.transitionTo('resolve'); $q.flush(); $timeout.flush(); expect(elem.text()).toBe('joeschmoe'); expect(_scope.$resolve).toBeDefined(); expect(_scope.$ctrl).toBeDefined(); expect(_scope.$ctrl.$resolve).toBeDefined(); expect(_scope.$ctrl.$resolve.user).toBe('joeschmoe'); })); it('should not allow both view-level resolveAs and state-level resolveAs on the same state', inject(function ( $state, $q, $timeout ) { const views = { $default: { controller: controller, template: '{{$$$resolve.user}}', resolveAs: '$$$resolve', }, }; const state = angular.extend({}, _state, { resolveAs: 'foo', views: views }); expect(() => $stateProvider.state(state)).toThrowError(/resolveAs/); })); }); it('should call the existing $onInit after instantiating a controller', inject(function ($state, $q) { const $onInit = jasmine.createSpy(); $stateProvider.state('onInit', { controller: function () { this.$onInit = $onInit; }, template: 'hi', controllerAs: 'vm', }); elem.append($compile('<div><ui-view></ui-view></div>')(scope)); $state.transitionTo('onInit'); $q.flush(); expect($onInit).toHaveBeenCalled(); })); it('should default the template to a <ui-view>', inject(function ($state, $q) { $stateProvider.state('abstract', { abstract: true }); $stateProvider.state('abstract.foo', { template: 'hello' }); elem.append($compile('<div><ui-view></ui-view></div>')(scope)); $state.transitionTo('abstract.foo'); $q.flush(); expect(elem.text()).toBe('hello'); })); describe('play nicely with other directives', function () { // related to issue #857 it('should work with ngIf', inject(function ($state, $q, $compile) { // ngIf does not exist in 1.0.8 if (angular.version.full === '1.0.8') return; scope.someBoolean = false; elem.append($compile('<div ng-if="someBoolean"><ui-view></ui-view></div>')(scope)); $state.transitionTo(aState); $q.flush(); // Verify there is no ui-view in the DOM expect(elem.find('ui-view').length).toBe(0); // Turn on the div that holds the ui-view scope.someBoolean = true; scope.$digest(); // Verify that the ui-view is there and it has the correct content expect(elem.find('ui-view').text()).toBe(aState.template); // Turn off the ui-view scope.someBoolean = false; scope.$digest(); // Verify there is no ui-view in the DOM expect(elem.find('ui-view').length).toBe(0); // Turn on the div that holds the ui-view once again scope.someBoolean = true; scope.$digest(); // Verify that the ui-view is there and it has the correct content expect(elem.find('ui-view').text()).toBe(aState.template); })); it('should work with ngClass', inject(function ($state, $q, $compile) { const classes = (elem) => Array.prototype.slice.call(elem[0].classList); scope.showClass = false; elem.append($compile('<div><ui-view ng-class="{\'someClass\': showClass}"></ui-view></div>')(scope)); expect(classes(elem.find('ui-view'))).not.toContain('someClass'); scope.showClass = true; scope.$digest(); expect(classes(elem.find('ui-view'))).toContain('someClass'); scope.showClass = false; scope.$digest(); expect(classes(elem.find('ui-view'))).not.toContain('someClass'); })); describe('working with ngRepeat', function () { // ngRepeat does not work properly with uiView in 1.0.8 & 1.1.5 if (['1.0.8', '1.1.5'].indexOf(angular.version.full) !== -1) return; it('should have correct number of uiViews', inject(function ($state, $q, $compile) { elem.append($compile('<div><ui-view ng-repeat="view in views" name="{{view}}"></ui-view></div>')(scope)); // Should be no ui-views in DOM expect(elem.find('ui-view').length).toBe(0); // Lets add 3 scope.views = ['view1', 'view2', 'view3']; scope.$digest(); // Should be 3 ui-views in the DOM expect(elem.find('ui-view').length).toBe(scope.views.length); // Lets add one more - yay two-way binding scope.views.push('view4'); scope.$digest(); // Should have 4 ui-views expect(elem.find('ui-view').length).toBe(scope.views.length); // Lets remove 2 ui-views from the DOM scope.views.pop(); scope.views.pop(); scope.$digest(); // Should have 2 ui-views expect(elem.find('ui-view').length).toBe(scope.views.length); })); it('should populate each view with content', inject(function ($state, $q, $compile) { elem.append( $compile('<div><ui-view ng-repeat="view in views" name="{{view}}">defaultcontent</ui-view></div>')(scope) ); $state.transitionTo(lState); $q.flush(); expect(elem.find('ui-view').length).toBe(0); scope.views = ['view1', 'view2']; scope.$digest(); let uiViews = elem.find('ui-view'); expect(uiViews.eq(0).text()).toBe(lState.views.view1.template); expect(uiViews.eq(1).text()).toBe(lState.views.view2.template); expect(uiViews.eq(2).length).toBe(0); scope.views.push('view3'); scope.$digest(); uiViews = elem.find('ui-view'); expect(uiViews.eq(0).text()).toBe(lState.views.view1.template); expect(uiViews.eq(1).text()).toBe(lState.views.view2.template); expect(uiViews.eq(2).text()).toBe(lState.views.view3.template); })); it('should interpolate ui-view names', inject(function ($state, $q, $compile) { elem.append( $compile('<div ng-repeat="view in views">' + '<ui-view name="view{{$index + 1}}">hallo</ui-view>' + '</div>')( scope ) ); $state.transitionTo(lState); $q.flush(); expect(elem.find('ui-view').length).toBe(0); scope.views = ['view1', 'view2']; scope.$digest(); let uiViews = elem.find('ui-view'); expect(uiViews.eq(0).text()).toBe(lState.views.view1.template); expect(uiViews.eq(1).text()).toBe(lState.views.view2.template); expect(uiViews.eq(2).length).toBe(0); scope.views.push('view3'); scope.$digest(); uiViews = elem.find('ui-view'); expect(uiViews.eq(0).text()).toBe(lState.views.view1.template); expect(uiViews.eq(1).text()).toBe(lState.views.view2.template); expect(uiViews.eq(2).text()).toBe(lState.views.view3.template); })); }); }); describe('AngularJS Animations', function () { it('should do transition animations', inject(function ($state, $q, $compile, $animate) { let content = 'Initial Content', animation; elem.append($compile('<div><ui-view>' + content + '</ui-view></div>')(scope)); // Enter Animation animation = $animate.queue.shift(); expect(animation.event).toBe('enter'); expect(animation.element.text() + '-1').toBe(content + '-1'); $state.transitionTo(aState); $q.flush(); // Enter Animation animation = $animate.queue.shift(); expect(animation.event).toBe('enter'); expect(animation.element.text() + '-2').toBe(aState.template + '-2'); // Leave Animation animation = $animate.queue.shift(); expect(animation.event).toBe('leave'); expect(animation.element.text() + '-3').toBe(content + '-3'); $state.transitionTo(bState); $q.flush(); // Enter Animation animation = $animate.queue.shift(); expect(animation.event).toBe('enter'); expect(animation.element.text() + '-4').toBe(bState.template + '-4'); // Leave Animation animation = $animate.queue.shift(); expect(animation.event).toBe('leave'); expect(animation.element.text() + '-5').toBe(aState.template + '-5'); // No more animations expect($animate.queue.length).toBe(0); })); it('should do ngClass animations', inject(function ($state, $q, $compile, $animate) { scope.classOn = false; let content = 'Initial Content', className = 'yay', animation; elem.append( $compile('<div><ui-view ng-class="{\'' + className + '\': classOn}">' + content + '</ui-view></div>')(scope) ); // Don't care about enter class $animate.queue.shift(); scope.classOn = true; scope.$digest(); animation = $animate.queue.shift(); expect(animation.event).toBe('addClass'); expect(animation.element.text()).toBe(content); scope.classOn = false; scope.$digest(); animation = $animate.queue.shift(); expect(animation.event).toBe('removeClass'); expect(animation.element.text()).toBe(content); // No more animations expect($animate.queue.length).toBe(0); })); it('should do ngIf animations', inject(function ($state, $q, $compile, $animate) { scope.shouldShow = false; let content = 'Initial Content', animation; elem.append($compile('<div><ui-view ng-if="shouldShow">' + content + '</ui-view></div>')(scope)); // No animations yet expect($animate.queue.length).toBe(0); scope.shouldShow = true; scope.$digest(); // $ViewDirective enter animation - Basically it's just the <!-- uiView --> comment animation = $animate.queue.shift(); expect(animation.event).toBe('enter'); expect(animation.element.text()).toBe(''); // $ViewDirectiveFill enter animation - The second uiView directive that files in the content animation = $animate.queue.shift(); expect(animation.event).toBe('enter'); expect(animation.element.text()).toBe(content); scope.shouldShow = false; scope.$digest(); // uiView leave animation animation = $animate.queue.shift(); expect(animation.event).toBe('leave'); expect(animation.element.text()).toBe(content); // No more animations expect($animate.queue.length).toBe(0); })); it('should expose animation promises to controllers', inject(function ( $state, $q, $compile, $animate, $transitions ) { $transitions.onStart({}, function ($transition$) { log += 'start:' + $transition$.to().name + ';'; }); $transitions.onFinish({}, function ($transition$) { log += 'finish:' + $transition$.to().name + ';'; }); $transitions.onSuccess({}, function ($transition$) { log += 'success:' + $transition$.to().name + ';'; }); const content = 'Initial Content'; elem.append($compile('<div><ui-view>' + content + '</ui-view></div>')(scope)); $state.transitionTo('n'); $q.flush(); expect($state.current.name).toBe('n'); expect(log).toBe('start:n;finish:n;success:n;'); animateFlush($animate); $q.flush(); expect(log).toBe('start:n;finish:n;success:n;animEnter;'); $state.transitionTo('a'); $q.flush(); expect($state.current.name).toBe('a'); expect(log).toBe('start:n;finish:n;success:n;animEnter;start:a;finish:a;destroy;success:a;'); animateFlush($animate); $q.flush(); expect(log).toBe('start:n;finish:n;success:n;animEnter;start:a;finish:a;destroy;success:a;animLeave;'); })); }); }); describe('UiView', function () { beforeEach(module('ui.router')); beforeEach( module(function ($stateProvider) { $stateProvider .state('main', { abstract: true, views: { main: {} } }) .state('main.home', { views: { content: { template: 'HOME' } } }) .state('test', { views: { nest: { template: 'TEST' } } }); }) ); it("shouldn't puke on weird nested view setups", inject(function ($compile, $rootScope, $q, $state) { $compile('<div ui-view="main"><div ui-view="content"></div></div>')($rootScope); $state.go('main.home'); $q.flush(); expect($state.current.name).toBe('main.home'); })); // Test for https://github.com/angular-ui/ui-router/issues/3355 it("should target weird nested view setups using the view's simple name", inject(function ( $compile, $rootScope, $q, $state ) { const tpl = ` <div> <div ui-view="main"> MAIN-DEFAULT- <div ui-view="content"> <div ui-view="nest"></div> </div> </div> </div> `; const el = $compile(tpl)($rootScope); $state.go('test'); $q.flush(); expect($state.current.name).toBe('test'); expect(el.text().replace(/\s*/g, '')).toBe('MAIN-DEFAULT-TEST'); })); }); describe('uiView transclusion', function () { let scope, $compile, elem; beforeEach(function () { const app = angular.module('foo', []); app.directive('scopeObserver', function () { return { restrict: 'E', link: function (scope) { scope.$emit('directiveCreated'); scope.$on('$destroy', function () { scope.$emit('directiveDestroyed'); }); }, }; }); }); beforeEach(module('ui.router', 'foo')); beforeEach( module(function ($stateProvider) { $stateProvider .state('a', { template: '<ui-view><scope-observer></scope-observer></ui-view>' }) .state('a.b', { template: 'anything' }); }) ); beforeEach(inject(function ($rootScope, _$compile_) { scope = $rootScope.$new(); $compile = _$compile_; elem = angular.element('<div>'); })); it('should not link the initial view and leave its scope undestroyed when a subview is activated', inject(function ( $state, $q ) { let aliveCount = 0; scope.$on('directiveCreated', function () { aliveCount++; }); scope.$on('directiveDestroyed', function () { aliveCount--; }); elem.append($compile('<div><ui-view></ui-view></div>')(scope)); $state.transitionTo('a.b'); $q.flush(); expect(aliveCount).toBe(0); })); }); describe('uiView controllers or onEnter handlers', function () { let el, template, scope, document, count; beforeEach(module('ui.router')); beforeEach( module(function ($stateProvider) { count = 0; $stateProvider .state('aside', { url: '/aside', template: '<div class="aside"></div>' }) .state('A', { url: '/A', template: '<div class="A" ui-view="fwd"></div>' }) .state('A.fwd', { url: '/fwd', views: { fwd: { template: '<div class="fwd" ui-view>', controller: function ($state) { if (count++ < 20 && $state.current.name == 'A.fwd') $state.go('.nest'); }, }, }, }) .state('A.fwd.nest', { url: '/nest', template: '<div class="nest"></div>' }); }) ); beforeEach(inject(function ($document) { document = $document[0]; })); it('should not go into an infinite loop when controller uses $state.go', inject(function ( $rootScope, $q, $compile, $state ) { el = angular.element('<div><ui-view></ui-view></div>'); template = $compile(el)($rootScope); $rootScope.$digest(); $state.transitionTo('aside'); $q.flush(); expect(template[0].querySelector('.aside')).toBeDefined(); expect(template[0].querySelector('.fwd')).toBeNull(); $state.transitionTo('A'); $q.flush(); expect(template[0].querySelector('.A')).not.toBeNull(); expect(template[0].querySelector('.fwd')).toBeNull(); $state.transitionTo('A.fwd'); $q.flush(); expect(template[0].querySelector('.A')).not.toBeNull(); expect(template[0].querySelector('.fwd')).not.toBeNull(); expect(template[0].querySelector('.nest')).not.toBeNull(); expect(count).toBe(1); })); }); describe('angular 1.5+ style .component()', function () { let el, app, scope, log, svcs, $stateProvider; beforeEach(function () { app = angular.module('foo', []); // ng 1.2 directive (manually bindToController) app.directive('ng12Directive', function () { return { restrict: 'E', scope: { data: '=' }, templateUrl: '/comp_tpl.html', controller: function ($scope) { this.data = $scope.data; }, controllerAs: '$ctrl', }; }); // ng 1.3-1.4 directive with bindToController app.directive('ng13Directive', function () { return { scope: { data: '=' }, templateUrl: '/comp_tpl.html', controller: function () { this.$onInit = function () { log += 'onInit;'; }; }, bindToController: true, controllerAs: '$ctrl', }; }); app.directive('ng12DynamicDirective', function () { return { restrict: 'E', template: 'dynamic directive', }; }); // ng 1.5+ component if (angular.version.minor >= 5) { app.component('ngComponent', { bindings: { data: '<', data2: '<' }, templateUrl: '/comp_tpl.html', controller: function () { this.$onInit = function () { log += 'onInit;'; }; }, }); app.component('header', { bindings: { status: '<' }, template: '#{{ $ctrl.status }}#', }); app.component('bindingTypes', { bindings: { oneway: '<oneway', twoway: '=', attribute: '@attr' }, template: '-{{ $ctrl.oneway }},{{ $ctrl.twoway }},{{ $ctrl.attribute }}-', }); app.component('optionalBindingTypes', { bindings: { oneway: '<?oneway', twoway: '=?', attribute: '@?attr' }, template: '-{{ $ctrl.oneway }},{{ $ctrl.twoway }},{{ $ctrl.attribute }}-', }); app.component('eventComponent', { bindings: { evt: '&' }, template: 'eventCmp', }); app.component('mydataComponent', { bindings: { dataUser: '<' }, template: '-{{ $ctrl.dataUser }}-', }); app.component('dataComponent', { template: 'DataComponent', }); app.component('parentCallbackComponent', { controller: function ($rootScope) { this.handleEvent = function (foo, bar) { $rootScope.log.push(foo); $rootScope.log.push(bar); }; }, template: ` <h1>parentCmp</h1> <ui-view on-event="$ctrl.handleEvent(foo, bar)"></ui-view> `, }); app.component('childEventComponent', { bindings: { onEvent: '&' }, template: ` <h1>childCmp</h1> <button id="eventbtn" ng-click="$ctrl.onEvent({ foo: 123, bar: 456 })">Button</button> `, }); app.component('dynamicComponent', { template: 'dynamicComponent {{ $ctrl.param }}', controller: function () { this.uiOnParamsChanged = function (params) { this.param = params.param; }; }, }); } }); beforeEach(module('ui.router', 'foo')); beforeEach( module(function (_$stateProvider_) { $stateProvider = _$stateProvider_; }) ); beforeEach(inject(function ($rootScope, _$httpBackend_, _$compile_, _$state_, _$q_) { svcs = { $httpBackend: _$httpBackend_, $compile: _$compile_, $state: _$state_, $q: _$q_ }; scope = $rootScope.$new(); log = ''; el = angular.element('<div><ui-view></ui-view></div>'); svcs.$compile(el)(scope); })); describe('routing using component templates', function () { beforeEach(function () { $stateProvider.state('cmp_tpl', { url: '/cmp_tpl', templateUrl: '/state_tpl.html', controller: function () {}, resolve: { data: function () { return 'DATA!'; }, }, }); }); it('should work with directives which themselves have templateUrls', function () { const $state = svcs.$state, $httpBackend = svcs.$httpBackend, $q = svcs.$q; $httpBackend.expectGET('/state_tpl.html').respond('x<ng12-directive data="$resolve.data"></ng12-directive>x'); $httpBackend.expectGET('/comp_tpl.html').respond('-{{ $ctrl.data }}-'); $state.transitionTo('cmp_tpl'); $q.flush(); // Template has not yet been fetched let directiveEl = el[0].querySelector('div ui-view ng12-directive'); expect(directiveEl).toBeNull(); expect($state.current.name).toBe(''); // Fetch templates $httpBackend.flush(); directiveEl = el[0].querySelector('div ui-view ng12-directive'); expect(directiveEl).toBeDefined(); expect($state.current.name).toBe('cmp_tpl'); expect(angular.element(directiveEl).data('$ng12DirectiveController')).toBeDefined(); expect(el.text()).toBe('x-DATA!-x'); }); if (angular.version.minor >= 3) { it('should work with ng 1.3+ bindToController directives', function () { const $state = svcs.$state, $httpBackend = svcs.$httpBackend, $q = svcs.$q; $httpBackend.expectGET('/state_tpl.html').respond('x<ng13-directive data="$resolve.data"></ng13-directive>x'); $httpBackend.expectGET('/comp_tpl.html').respond('-{{ $ctrl.data }}-'); $state.transitionTo('cmp_tpl'); $q.flush(); $httpBackend.flush(); const directiveEl = el[0].querySelector('div ui-view ng13-directive'); expect(directiveEl).toBeDefined(); expect($state.current.name).toBe('cmp_tpl'); expect(angular.element(directiveEl).data('$ng13DirectiveController')).toBeDefined(); expect(el.text()).toBe('x-DATA!-x'); }); } if (angular.version.minor >= 5) { it('should work with ng 1.5+ .component()s', function () { const $state = svcs.$state, $httpBackend = svcs.$httpBackend, $q = svcs.$q; $httpBackend.expectGET('/state_tpl.html').respond('x<ng-component data="$resolve.data"></ng-component>x'); $httpBackend.expectGET('/comp_tpl.html').respond('-{{ $ctrl.data }}-'); $state.transitionTo('cmp_tpl'); $q.flush(); $httpBackend.flush(); const directiveEl = el[0].querySelector('div ui-view ng-component'); expect(directiveEl).toBeDefined(); expect($state.current.name).toBe('cmp_tpl'); expect(angular.element(directiveEl).data('$ngComponentController')).toBeDefined(); expect(el.text()).toBe('x-DATA!-x'); }); } }); describe('+ component: declaration', function () { it('should disallow controller/template configuration', function () { const stateDef = { url: '/route2cmp', component: 'ng12Directive', resolve: { data: function () { return 'DATA!'; }, }, }; expect(function () { $stateProvider.state('route2cmp', extend({ template: 'fail' }, stateDef)); }).toThrow(); expect(function () { $stateProvider.state('route2cmp', extend({ templateUrl: 'fail.html' }, stateDef)); }).toThrow(); expect(function () { $stateProvider.state('route2cmp', extend({ templateProvider: function () {} }, stateDef)); }).toThrow(); expect(function () { $stateProvider.state('route2cmp', extend({ controllerAs: 'fail' }, stateDef)); }).toThrow(); expect(function () { $stateProvider.state('route2cmp', extend({ controller: 'FailCtrl' }, stateDef)); }).toThrow(); expect(function () { $stateProvider.state('route2cmp', extend({ controllerProvider: function () {} }, stateDef)); }).toThrow(); expect(function () { $stateProvider.state('route2cmp', stateDef); }).not.toThrow(); }); it('should work with angular 1.2+ directives', function () { $stateProvider.state('route2cmp', { url: '/route2cmp', component: 'ng12Directive', resolve: { data: function () { return 'DATA!'; }, }, }); const $state = svcs.$state, $httpBackend = svcs.$httpBackend, $q = svcs.$q; $httpBackend.expectGET('/comp_tpl.html').respond('-{{ $ctrl.data }}-'); $state.transitionTo('route2cmp'); $q.flush(); $httpBackend.flush(); const directiveEl = el[0].querySelector('div ui-view ng12-directive'); expect(directiveEl).toBeDefined(); expect($state.current.name).toBe('route2cmp'); expect(el.text()).toBe('-DATA!-'); }); if (angular.version.minor >= 3) { it('should work with angular 1.3+ bindToComponent directives', function () { $stateProvider.state('route2cmp', { url: '/route2cmp', component: 'ng13Directive', resolve: { data: function () { return 'DATA!'; }, }, }); const $state = svcs.$state, $httpBackend = svcs.$httpBackend, $q = svcs.$q; $httpBackend.expectGET('/comp_tpl.html').respond('-{{ $ctrl.data }}-'); $state.transitionTo('route2cmp'); $q.flush(); $httpBackend.flush(); const directiveEl = el[0].querySelector('div ui-view ng13-directive'); expect(directiveEl).toBeDefined(); expect($state.current.name).toBe('route2cmp'); expect(el.text()).toBe('-DATA!-'); }); it('should call $onInit() once', function () { $stateProvider.state('route2cmp', { url: '/route2cmp', component: 'ng13Directive', resolve: { data: function () { return 'DATA!'; }, }, }); const $state = svcs.$state, $httpBackend = svcs.$httpBackend, $q = svcs.$q; $httpBackend.expectGET('/comp_tpl.html').respond('-{{ $ctrl.data }}-'); $state.transitionTo('route2cmp'); $q.flush(); $httpBackend.flush(); expect(log).toBe('onInit;'); }); } if (angular.version.minor >= 5) { it('should work with angular 1.5+ .component()s', function () { $stateProvider.state('route2cmp', { url: '/route2cmp', component: 'ngComponent', resolve: { data: function () { return 'DATA!'; }, }, }); const $state = svcs.$state, $httpBackend = svcs.$httpBackend, $q = svcs.$q; $httpBackend.expectGET('/comp_tpl.html').respond('-{{ $ctrl.data }}-'); $state.transitionTo('route2cmp'); $q.flush(); $httpBackend.flush(); const directiveEl = el[0].querySelector('div ui-view ng-component'); expect(directiveEl).toBeDefined(); expect($state.current.name).toBe('route2cmp'); expect(el.text()).toBe('-DATA!-'); }); it('should only call $onInit() once', function () { $stateProvider.state('route2cmp', { component: 'ngComponent', resolve: { data: function () { return 'DATA!'; }, }, }); const $state = svcs.$state, $httpBackend = svcs.$httpBackend, $q = svcs.$q; $httpBackend.expectGET('/comp_tpl.html').respond('-{{ $ctrl.data }}-'); $state.transitionTo('route2cmp'); $q.flush(); $httpBackend.flush(); expect(log).toBe('onInit;'); }); it('should only call $onInit() once with componentProvider', function () { $stateProvider.state('route2cmp', { componentProvider: () => 'ngComponent', resolve: { data: function () { return 'DATA!'; }, }, }); const $state = svcs.$state, $httpBackend = svcs.$httpBackend, $q = svcs.$q; $httpBackend.expectGET('/comp_tpl.html').respond('-{{ $ctrl.data }}-'); $state.transitionTo('route2cmp'); $q.flush(); $httpBackend.flush(); expect(log).toBe('onInit;'); }); it('should supply resolve data to "<", "=", "@" bindings', function () { $stateProvider.state('bindingtypes', { component: 'bindingTypes', resolve: { oneway: function () { return 'ONEWAY'; }, twoway: function () { return 'TWOWAY'; }, attribute: function () { return 'ATTRIBUTE'; }, }, bindings: { attr: 'attribute' }, }); const $state = svcs.$state, $httpBackend = svcs.$httpBackend, $q = svcs.$q; $state.transitionTo('bindingtypes'); $q.flush(); expect(el.text()).toBe('-ONEWAY,TWOWAY,ATTRIBUTE-'); }); it('should supply resolve data to optional "<?", "=?", "@?" bindings', function () { $stateProvider.state('optionalbindingtypes', { component: 'optionalBindingTypes', resolve: { oneway: function () { return 'ONEWAY'; }, twoway: function () { return 'TWOWAY'; }, attribute: function () { return 'ATTRIBUTE'; }, }, bindings: { attr: 'attribute' }, }); const $state = svcs.$state, $httpBackend = svcs.$httpBackend, $q = svcs.$q; $state.transitionTo('optionalbindingtypes'); $q.flush(); expect(el.text()).toBe('-ONEWAY,TWOWAY,ATTRIBUTE-'); }); // Test for #3099 it('should not throw when routing to a component with output "&" binding', function () { $stateProvider.state('nothrow', { component: 'eventComponent', }); const $state = svcs.$state, $q = svcs.$q; $state.transitionTo('nothrow'); $q.flush(); expect(el.text()).toBe('eventCmp'); }); // Test for #3276 it('should route to a component that is prefixed with "data"', function () { $stateProvider.state('data', { component: 'dataComponent', }); const $state = svcs.$state, $q = svcs.$q; $state.transitionTo('data'); $q.flush(); expect(el.text()).toBe('DataComponent'); }); // Test for #3276 it('should bind a resolve that is prefixed with "data"', function () { $stateProvider.state('data', { component: 'mydataComponent', resolve: { dataUser: () => 'user' }, }); const $state = svcs.$state, $q = svcs.$q; $state.transitionTo('data'); $q.flush(); expect(el.text()).toBe('-user-'); }); // Test for #3239 it('should pass any bindings (wired from a parent component template via the ui-view) through to the child', inject(function ( $rootScope ) { const $state = svcs.$state, $q = svcs.$q; $stateProvider.state('parent', { template: '<ui-view oneway="data1w" twoway="data2w" attr="attrval"></ui-view>', controller: function ($scope) { $scope.data1w = '1w'; $scope.data2w = '2w'; }, }); $stateProvider.state('parent.child', { component: 'bindingTypes', }); $state.transitionTo('parent.child'); $q.flush(); expect(el.text()).toEqual('-1w,2w,attrval-'); })); // Test for #3239 it('should prefer ui-view bindings over resolve data', inject(function ($rootScope) { const $state = svcs.$state, $q = svcs.$q; $stateProvider.state('parent', { template: '<ui-view oneway="data1w" twoway="data2w" attr="attrval"></ui-view>', resolve: { oneway: () => 'asfasfd', twoway: () => 'asfasfd', attr: () => 'asfasfd', }, controller: function ($scope) { $scope.data1w = '1w'; $scope.data2w = '2w'; }, }); $stateProvider.state('parent.child', { component: 'bindingTypes', }); $state.transitionTo('parent.child'); $q.flush(); expect(el.text()).toEqual('-1w,2w,attrval-'); })); // Test for #3239 it('should prefer ui-view bindings over resolve data unless a bindings exists', inject(function ($rootScope) { const $state = svcs.$state, $q = svcs.$q; $stateProvider.state('parent', { template: '<ui-view oneway="data1w" twoway="data2w" attr="attrval"></ui-view>', resolve: { oneway: () => 'asfasfd', twoway: () => 'asfasfd', attr: () => 'asfasfd', }, controller: function ($scope) { $scope.data1w = '1w'; $scope.data2w = '2w'; }, }); $stateProvider.state('parent.child', { component: 'bindingTypes', bindings: { oneway: 'oneway' }, }); $state.transitionTo('parent.child'); $q.flush(); expect(el.text()).toEqual('-asfasfd,2w,attrval-'); })); // Test for #3239 it('should pass & bindings (wired from a parent component via the ui-view) through to the child', inject(function ( $rootScope ) { const $state = svcs.$state, $q = svcs.$q; $rootScope.log = []; $stateProvider.state('parent', { component: 'parentCallbackComponent', }); $stateProvider.state('parent.child', { component: 'childEventComponent', }); $state.transitionTo('parent.child'); $q.flush(); expect($rootScope.log).toEqual([]); expect( el .text() .split(/\s+/) .filter((x) => x) ).toEqual(['parentCmp', 'childCmp', 'Button']); // - Click button // - ng-click handler calls $ctrl.onEvent({ foo: 123, bar: 456 }) // - on-event is bound to $ctrl.handleEvent(foo, bar) on parentCallbackComponent // - handleEvent pushes param values to the log el.find('button')[0].click(); expect($rootScope.log).toEqual([123, 456]); })); // Test for #3111 it('should bind & bindings to a resolve that returns a function', inject(function ($rootScope) { const $state = svcs.$state, $q = svcs.$q, log = []; $stateProvider.state('resolve', { component: 'childEventComponent', resolve: { onEvent: () => (foo, bar) => { log.push(foo); log.push(bar); }, }, }); $state.transitionTo('resolve'); $q.flush(); expect(log).toEqual([]); el.find('button')[0].click(); expect(log).toEqual([123, 456]); })); // Test for #3111 it('should bind & bindings to a resolve that returns an array-style function', inject(function ($rootScope) { const $state = svcs.$state, $q = svcs.$q, log = []; $stateProvider.state('resolve', { component: 'childEventComponent', resolve: { onEvent: () => [ 'foo', 'bar', (foo, bar) => { log.push(foo); log.push(bar); }, ], }, }); $state.transitionTo('resolve'); $q.flush(); expect(log).toEqual([]); el.find('button')[0].click(); expect(log).toEqual([123, 456]); })); } }); if (angular.version.minor >= 5) { describe('+ named views with component: declaration', function () { let stateDef; beforeEach(function () { stateDef = { url: '/route2cmp', views: { header: { component: 'header' }, content: { component: 'ngComponent' }, }, resolve: { status: function () { return 'awesome'; }, data: function () { return 'DATA!'; }, }, }; el = angular.element('<div><div ui-view="header"></div><div ui-view="content"</div>'); svcs.$compile(el)(scope); }); it('should disallow controller/template configuration in the view', function () { expect(function () { $stateProvider.state('route2cmp', stateDef); }).not.toThrow(); expect(function () { const state = extend({}, stateDef); state.views.header.template = 'fails'; $stateProvider.state('route2cmp', state); }).toThrow(); }); it('should render components as views', function () { $stateProvider.state('route2cmp', stateDef); const $state = svcs.$state, $httpBackend = svcs.$httpBackend, $q = svcs.$q; $httpBackend.expectGET('/comp_tpl.html').respond('-{{ $ctrl.data }}-'); $state.transitionTo('route2cmp'); $q.flush(); $httpBackend.flush(); const header = el[0].querySelector('[ui-view=header]'); const content = el[0].querySelector('[ui-view=content]'); expect(header.textContent).toBe('#awesome#'); expect(content.textContent).toBe('-DATA!-'); }); it('should allow a component view declaration to use a string as a shorthand', function () { stateDef = { url: '/route2cmp', views: { header: 'header', content: 'ngComponent' }, resolve: { status: function () { return 'awesome'; }, data: function () { return 'DATA!'; }, }, }; $stateProvider.state('route2cmp', stateDef); const $state = svcs.$state, $httpBackend = svcs.$httpBackend, $q = svcs.$q; $httpBackend.expectGET('/comp_tpl.html').respond('-{{ $ctrl.data }}-'); $state.transitionTo('route2cmp'); $q.flush(); $httpBackend.flush(); const header = el[0].querySelector('[ui-view=header]'); const content = el[0].querySelector('[ui-view=content]'); expect(header.textContent).toBe('#awesome#'); expect(content.textContent).toBe('-DATA!-'); }); // Test for https://github.com/angular-ui/ui-router/issues/3353 it('should allow different states to reuse view declaration', function () { const views = { header: { component: 'header' }, content: { component: 'ngComponent' }, }; const stateDef1 = { name: 'def1', url: '/def1', views: views }; const stateDef2 = { name: 'def2', url: '/def2', views: views }; $stateProvider.state(stateDef1); $stateProvider.state(stateDef2); }); }); } describe('+ bindings: declaration', function () { it('should provide the named component binding with data from the named resolve', function () { $stateProvider.state('route2cmp', { url: '/route2cmp', component: 'ng12Directive', bindings: { data: 'foo' }, resolve: { foo: function () { return 'DATA!'; }, }, }); const $state = svcs.$state, $httpBackend = svcs.$httpBackend, $q = svcs.$q; $httpBackend.expectGET('/comp_tpl.html').respond('-{{ $ctrl.data }}-'); $state.transitionTo('route2cmp'); $q.flush(); $httpBackend.flush(); const directiveEl = el[0].querySelector('div ui-view ng12-directive'); expect(directiveEl).toBeDefined(); expect($state.current.name).toBe('route2cmp'); expect(el.text()).toBe('-DATA!-'); }); if (angular.version.minor >= 5) { it('should provide default bindings for any component bindings omitted in the state.bindings map', function () { $stateProvider.state('route2cmp', { url: '/route2cmp', component: 'ngComponent', bindings: { data: 'foo' }, resolve: { foo: function () { return 'DATA!'; }, data2: function () { return 'DATA2!'; }, }, }); const $state = svcs.$state, $httpBackend = svcs.$httpBackend, $q = svcs.$q; $httpBackend.expectGET('/comp_tpl.html').respond('-{{ $ctrl.data }}.{{ $ctrl.data2 }}-'); $state.transitionTo('route2cmp'); $q.flush(); $httpBackend.flush(); const directiveEl = el[0].querySelector('div ui-view ng-component'); expect(directiveEl).toBeDefined(); expect($state.current.name).toBe('route2cmp'); expect(el.text()).toBe('-DATA!.DATA2!-'); }); } }); describe('componentProvider', function () { it('should work with angular 1.2+ directives', function () { $stateProvider.state('ng12-dynamic-directive', { url: '/ng12dynamicDirective/:type', componentProvider: [ '$stateParams', function ($stateParams) { return $stateParams.type; }, ], }); const $state = svcs.$state, $q = svcs.$q; $state.transitionTo('ng12-dynamic-directive', { type: 'ng12DynamicDirective' }); $q.flush(); const directiveEl = el[0].querySelector('div ui-view ng12-dynamic-directive'); expect(directiveEl).toBeDefined(); expect($state.current.name).toBe('ng12-dynamic-directive'); expect(el.text()).toBe('dynamic directive'); }); if (angular.version.minor >= 5) { it('should load correct component when using componentProvider', function () { $stateProvider.state('dynamicComponent', { url: '/dynamicComponent/:type', componentProvider: [ '$stateParams', function ($stateParams) { return $stateParams.type; }, ], }); const $state = svcs.$state, $httpBackend = svcs.$httpBackend, $q = svcs.$q; $state.transitionTo('dynamicComponent', { type: 'dynamicComponent' }); $q.flush(); const directiveEl = el[0].querySelector('div ui-view dynamic-component'); expect(directiveEl).toBeDefined(); expect($state.current.name).toBe('dynamicComponent'); expect(el.text().trim()).toBe('dynamicComponent'); }); } }); if (angular.version.minor >= 5) { describe('uiOnParamsChanged()', () => { let param; beforeEach(inject(($rootScope: IRootScopeService, $compile: ICompileService) => { param = null; $stateProvider.state('dynamic', { url: '/dynamic/:param', component: 'dynamicComponent', params: { param: { dynamic: true } }, }); $stateProvider.state('dynamic2', { url: '/dynamic2/:param', componentProvider: () => 'dynamicComponent', params: { param: { dynamic: true } }, }); })); it('should not be called on the initial transition', () => { const $state = svcs.$state, $q = svcs.$q; $state.go('dynamic', { param: 'abc' }); $q.flush(); expect(el.text().trim()).toBe('dynamicComponent'); }); it('should be called when dynamic parameters change', () => { const $state = svcs.$state, $q = svcs.$q; $state.go('dynamic', { param: 'abc' }); $q.flush(); $state.go('dynamic', { param: 'def' }); $q.flush(); expect(el.text().trim()).toBe('dynamicComponent def'); }); it('should work with componentProvider', () => { const $state = svcs.$state, $q = svcs.$q; $state.go('dynamic2', { param: 'abc' }); $q.flush(); $state.go('dynamic2', { param: 'def' }); $q.flush(); expect(el.text().trim()).toBe('dynamicComponent def'); }); }); } });
the_stack
Papa Parse v5.0.0-beta.0 https://github.com/mholt/PapaParse License: MIT */ // FORK SUMMARY: // - Adopt ES6 exports // - Implement new AsyncIteratorStreamer // - Remove non Async Iterator streamers (can all be handled by new streamer) // - Remove unused Worker support (loaders.gl worker system used instead) // - Remove unused jQuery plugin support /* eslint-disable */ const BYTE_ORDER_MARK = '\ufeff'; const Papa = { parse: CsvToJson, unparse: JsonToCsv, RECORD_SEP: String.fromCharCode(30), UNIT_SEP: String.fromCharCode(31), BYTE_ORDER_MARK, BAD_DELIMITERS: ['\r', '\n', '"', BYTE_ORDER_MARK], WORKERS_SUPPORTED: false, // !IS_WORKER && !!globalThis.Worker NODE_STREAM_INPUT: 1, // Configurable chunk sizes for local and remote files, respectively LocalChunkSize: 1024 * 1024 * 10, // 10 M, RemoteChunkSize: 1024 * 1024 * 5, // 5 M, DefaultDelimiter: ',', // Used if not specified and detection fail, // Exposed for testing and development only Parser: Parser, ParserHandle: ParserHandle, // BEGIN FORK ChunkStreamer: ChunkStreamer, StringStreamer: StringStreamer }; export default Papa; /* Papa.NetworkStreamer = NetworkStreamer; Papa.FileStreamer = FileStreamer; Papa.ReadableStreamStreamer = ReadableStreamStreamer; if (typeof PAPA_BROWSER_CONTEXT === 'undefined') { Papa.DuplexStreamStreamer = DuplexStreamStreamer; } */ // END FORK // BEGIN FORK // Adds an argument to papa.parse // function CsvToJson(_input, _config) function CsvToJson( _input, _config, UserDefinedStreamer? // BEGIN FORK ) { _config = _config || {}; var dynamicTyping = _config.dynamicTyping || false; if (isFunction(dynamicTyping)) { _config.dynamicTypingFunction = dynamicTyping; // Will be filled on first row call dynamicTyping = {}; } _config.dynamicTyping = dynamicTyping; _config.transform = isFunction(_config.transform) ? _config.transform : false; if (_config.worker && Papa.WORKERS_SUPPORTED) { var w = newWorker(); w.userStep = _config.step; w.userChunk = _config.chunk; w.userComplete = _config.complete; w.userError = _config.error; _config.step = isFunction(_config.step); _config.chunk = isFunction(_config.chunk); _config.complete = isFunction(_config.complete); _config.error = isFunction(_config.error); delete _config.worker; // prevent infinite loop w.postMessage({ input: _input, config: _config, workerId: w.id }); return; } var streamer = null; /* if (_input === Papa.NODE_STREAM_INPUT && typeof PAPA_BROWSER_CONTEXT === 'undefined') { // create a node Duplex stream for use // with .pipe streamer = new DuplexStreamStreamer(_config); return streamer.getStream(); } else */ if (typeof _input === 'string') { // if (_config.download) streamer = new NetworkStreamer(_config); // else streamer = new StringStreamer(_config); } /* else if (_input.readable === true && isFunction(_input.read) && isFunction(_input.on)) { streamer = new ReadableStreamStreamer(_config); } else if ((globalThis.File && _input instanceof File) || _input instanceof Object) // ...Safari. (see issue #106) streamer = new FileStreamer(_config); */ // BEGIN FORK if (!streamer) { streamer = new UserDefinedStreamer(_config); } // END FORK return streamer.stream(_input); } function JsonToCsv(_input, _config) { // Default configuration /** whether to surround every datum with quotes */ var _quotes = false; /** whether to write headers */ var _writeHeader = true; /** delimiting character(s) */ var _delimiter = ','; /** newline character(s) */ var _newline = '\r\n'; /** quote character */ var _quoteChar = '"'; /** escaped quote character, either "" or <config.escapeChar>" */ var _escapedQuote = _quoteChar + _quoteChar; /** whether to skip empty lines */ var _skipEmptyLines = false; /** the columns (keys) we expect when we unparse objects */ var _columns = null; unpackConfig(); var quoteCharRegex = new RegExp(escapeRegExp(_quoteChar), 'g'); if (typeof _input === 'string') _input = JSON.parse(_input); if (Array.isArray(_input)) { if (!_input.length || Array.isArray(_input[0])) return serialize(null, _input, _skipEmptyLines); else if (typeof _input[0] === 'object') return serialize(_columns || objectKeys(_input[0]), _input, _skipEmptyLines); } else if (typeof _input === 'object') { if (typeof _input.data === 'string') _input.data = JSON.parse(_input.data); if (Array.isArray(_input.data)) { if (!_input.fields) _input.fields = _input.meta && _input.meta.fields; if (!_input.fields) _input.fields = Array.isArray(_input.data[0]) ? _input.fields : objectKeys(_input.data[0]); if (!Array.isArray(_input.data[0]) && typeof _input.data[0] !== 'object') _input.data = [_input.data]; // handles input like [1,2,3] or ['asdf'] } return serialize(_input.fields || [], _input.data || [], _skipEmptyLines); } // Default (any valid paths should return before this) throw new Error('Unable to serialize unrecognized input'); function unpackConfig() { if (typeof _config !== 'object') return; if ( typeof _config.delimiter === 'string' && !Papa.BAD_DELIMITERS.filter(function (value) { return _config.delimiter.indexOf(value) !== -1; }).length ) { _delimiter = _config.delimiter; } if (typeof _config.quotes === 'boolean' || Array.isArray(_config.quotes)) _quotes = _config.quotes; if (typeof _config.skipEmptyLines === 'boolean' || typeof _config.skipEmptyLines === 'string') _skipEmptyLines = _config.skipEmptyLines; if (typeof _config.newline === 'string') _newline = _config.newline; if (typeof _config.quoteChar === 'string') _quoteChar = _config.quoteChar; if (typeof _config.header === 'boolean') _writeHeader = _config.header; if (Array.isArray(_config.columns)) { if (_config.columns.length === 0) throw new Error('Option columns is empty'); _columns = _config.columns; } if (_config.escapeChar !== undefined) { _escapedQuote = _config.escapeChar + _quoteChar; } } /** Turns an object's keys into an array */ function objectKeys(obj) { if (typeof obj !== 'object') return []; var keys = []; for (var key in obj) keys.push(key); return keys; } /** The double for loop that iterates the data and writes out a CSV string including header row */ function serialize(fields, data, skipEmptyLines) { var csv = ''; if (typeof fields === 'string') fields = JSON.parse(fields); if (typeof data === 'string') data = JSON.parse(data); var hasHeader = Array.isArray(fields) && fields.length > 0; var dataKeyedByField = !Array.isArray(data[0]); // If there a header row, write it first if (hasHeader && _writeHeader) { for (var i = 0; i < fields.length; i++) { if (i > 0) csv += _delimiter; csv += safe(fields[i], i); } if (data.length > 0) csv += _newline; } // Then write out the data for (var row = 0; row < data.length; row++) { var maxCol = hasHeader ? fields.length : data[row].length; var emptyLine = false; var nullLine = hasHeader ? Object.keys(data[row]).length === 0 : data[row].length === 0; if (skipEmptyLines && !hasHeader) { emptyLine = skipEmptyLines === 'greedy' ? data[row].join('').trim() === '' : data[row].length === 1 && data[row][0].length === 0; } if (skipEmptyLines === 'greedy' && hasHeader) { var line = []; for (var c = 0; c < maxCol; c++) { var cx = dataKeyedByField ? fields[c] : c; line.push(data[row][cx]); } emptyLine = line.join('').trim() === ''; } if (!emptyLine) { for (var col = 0; col < maxCol; col++) { if (col > 0 && !nullLine) csv += _delimiter; var colIdx = hasHeader && dataKeyedByField ? fields[col] : col; csv += safe(data[row][colIdx], col); } if (row < data.length - 1 && (!skipEmptyLines || (maxCol > 0 && !nullLine))) { csv += _newline; } } } return csv; } /** Encloses a value around quotes if needed (makes a value safe for CSV insertion) */ function safe(str, col) { if (typeof str === 'undefined' || str === null) return ''; if (str.constructor === Date) return JSON.stringify(str).slice(1, 25); str = str.toString().replace(quoteCharRegex, _escapedQuote); var needsQuotes = (typeof _quotes === 'boolean' && _quotes) || (Array.isArray(_quotes) && _quotes[col]) || hasAny(str, Papa.BAD_DELIMITERS) || str.indexOf(_delimiter) > -1 || str.charAt(0) === ' ' || str.charAt(str.length - 1) === ' '; return needsQuotes ? _quoteChar + str + _quoteChar : str; } function hasAny(str, substrings) { for (var i = 0; i < substrings.length; i++) if (str.indexOf(substrings[i]) > -1) return true; return false; } } /** ChunkStreamer is the base prototype for various streamer implementations. */ function ChunkStreamer(config) { this._handle = null; this._finished = false; this._completed = false; this._input = null; this._baseIndex = 0; this._partialLine = ''; this._rowCount = 0; this._start = 0; this._nextChunk = null; this.isFirstChunk = true; this._completeResults = { data: [], errors: [], meta: {} }; replaceConfig.call(this, config); this.parseChunk = function (chunk, isFakeChunk) { // First chunk pre-processing if (this.isFirstChunk && isFunction(this._config.beforeFirstChunk)) { var modifiedChunk = this._config.beforeFirstChunk(chunk); if (modifiedChunk !== undefined) chunk = modifiedChunk; } this.isFirstChunk = false; // Rejoin the line we likely just split in two by chunking the file var aggregate = this._partialLine + chunk; this._partialLine = ''; var results = this._handle.parse(aggregate, this._baseIndex, !this._finished); if (this._handle.paused() || this._handle.aborted()) return; var lastIndex = results.meta.cursor; if (!this._finished) { this._partialLine = aggregate.substring(lastIndex - this._baseIndex); this._baseIndex = lastIndex; } if (results && results.data) this._rowCount += results.data.length; var finishedIncludingPreview = this._finished || (this._config.preview && this._rowCount >= this._config.preview); if (isFunction(this._config.chunk) && !isFakeChunk) { this._config.chunk(results, this._handle); if (this._handle.paused() || this._handle.aborted()) return; results = undefined; this._completeResults = undefined; } if (!this._config.step && !this._config.chunk) { this._completeResults.data = this._completeResults.data.concat(results.data); this._completeResults.errors = this._completeResults.errors.concat(results.errors); this._completeResults.meta = results.meta; } if ( !this._completed && finishedIncludingPreview && isFunction(this._config.complete) && (!results || !results.meta.aborted) ) { this._config.complete(this._completeResults, this._input); this._completed = true; } if (!finishedIncludingPreview && (!results || !results.meta.paused)) this._nextChunk(); return results; }; this._sendError = function (error) { if (isFunction(this._config.error)) this._config.error(error); }; function replaceConfig(config) { // Deep-copy the config so we can edit it var configCopy = copy(config); configCopy.chunkSize = parseInt(configCopy.chunkSize); // parseInt VERY important so we don't concatenate strings! if (!config.step && !config.chunk) configCopy.chunkSize = null; // disable Range header if not streaming; bad values break IIS - see issue #196 this._handle = new ParserHandle(configCopy); this._handle.streamer = this; this._config = configCopy; // persist the copy to the caller } } function StringStreamer(config) { config = config || {}; ChunkStreamer.call(this, config); var remaining; this.stream = function (s) { remaining = s; return this._nextChunk(); }; this._nextChunk = function () { if (this._finished) return; var size = this._config.chunkSize; var chunk = size ? remaining.substr(0, size) : remaining; remaining = size ? remaining.substr(size) : ''; this._finished = !remaining; return this.parseChunk(chunk); }; } StringStreamer.prototype = Object.create(StringStreamer.prototype); StringStreamer.prototype.constructor = StringStreamer; // Use one ParserHandle per entire CSV file or string function ParserHandle(_config) { // One goal is to minimize the use of regular expressions... var FLOAT = /^\s*-?(\d*\.?\d+|\d+\.?\d*)(e[-+]?\d+)?\s*$/i; var ISO_DATE = /(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d\.\d+([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))|(\d{4}-[01]\d-[0-3]\dT[0-2]\d:[0-5]\d([+-][0-2]\d:[0-5]\d|Z))/; var self = this; var _stepCounter = 0; // Number of times step was called (number of rows parsed) var _rowCounter = 0; // Number of rows that have been parsed so far var _input; // The input being parsed var _parser; // The core parser being used var _paused = false; // Whether we are paused or not var _aborted = false; // Whether the parser has aborted or not var _delimiterError; // Temporary state between delimiter detection and processing results var _fields = []; // Fields are from the header row of the input, if there is one var _results = { // The last results returned from the parser data: [], errors: [], meta: {} }; if (isFunction(_config.step)) { var userStep = _config.step; _config.step = function (results) { _results = results; if (needsHeaderRow()) processResults(); // only call user's step function after header row else { processResults(); // It's possbile that this line was empty and there's no row here after all if (!_results.data || _results.data.length === 0) return; _stepCounter += results.data.length; if (_config.preview && _stepCounter > _config.preview) _parser.abort(); else userStep(_results, self); } }; } /** * Parses input. Most users won't need, and shouldn't mess with, the baseIndex * and ignoreLastRow parameters. They are used by streamers (wrapper functions) * when an input comes in multiple chunks, like from a file. */ this.parse = function (input, baseIndex, ignoreLastRow) { var quoteChar = _config.quoteChar || '"'; if (!_config.newline) _config.newline = guessLineEndings(input, quoteChar); _delimiterError = false; if (!_config.delimiter) { var delimGuess = guessDelimiter( input, _config.newline, _config.skipEmptyLines, _config.comments, _config.delimitersToGuess ); if (delimGuess.successful) _config.delimiter = delimGuess.bestDelimiter; else { _delimiterError = true; // add error after parsing (otherwise it would be overwritten) _config.delimiter = Papa.DefaultDelimiter; } _results.meta.delimiter = _config.delimiter; } else if (isFunction(_config.delimiter)) { _config.delimiter = _config.delimiter(input); _results.meta.delimiter = _config.delimiter; } var parserConfig = copy(_config); if (_config.preview && _config.header) parserConfig.preview++; // to compensate for header row _input = input; _parser = new Parser(parserConfig); _results = _parser.parse(_input, baseIndex, ignoreLastRow); processResults(); return _paused ? {meta: {paused: true}} : _results || {meta: {paused: false}}; }; this.paused = function () { return _paused; }; this.pause = function () { _paused = true; _parser.abort(); _input = _input.substr(_parser.getCharIndex()); }; this.resume = function () { _paused = false; self.streamer.parseChunk(_input, true); }; this.aborted = function () { return _aborted; }; this.abort = function () { _aborted = true; _parser.abort(); _results.meta.aborted = true; if (isFunction(_config.complete)) _config.complete(_results); _input = ''; }; function testEmptyLine(s) { return _config.skipEmptyLines === 'greedy' ? s.join('').trim() === '' : s.length === 1 && s[0].length === 0; } function processResults() { if (_results && _delimiterError) { addError( 'Delimiter', 'UndetectableDelimiter', "Unable to auto-detect delimiting character; defaulted to '" + Papa.DefaultDelimiter + "'" ); _delimiterError = false; } if (_config.skipEmptyLines) { for (var i = 0; i < _results.data.length; i++) if (testEmptyLine(_results.data[i])) _results.data.splice(i--, 1); } if (needsHeaderRow()) fillHeaderFields(); return applyHeaderAndDynamicTypingAndTransformation(); } function needsHeaderRow() { return _config.header && _fields.length === 0; } function fillHeaderFields() { if (!_results) return; function addHeder(header) { if (isFunction(_config.transformHeader)) header = _config.transformHeader(header); _fields.push(header); } if (Array.isArray(_results.data[0])) { for (var i = 0; needsHeaderRow() && i < _results.data.length; i++) _results.data[i].forEach(addHeder); _results.data.splice(0, 1); } // if _results.data[0] is not an array, we are in a step where _results.data is the row. else _results.data.forEach(addHeder); } function shouldApplyDynamicTyping(field) { // Cache function values to avoid calling it for each row if (_config.dynamicTypingFunction && _config.dynamicTyping[field] === undefined) { _config.dynamicTyping[field] = _config.dynamicTypingFunction(field); } return (_config.dynamicTyping[field] || _config.dynamicTyping) === true; } function parseDynamic(field, value) { if (shouldApplyDynamicTyping(field)) { if (value === 'true' || value === 'TRUE') return true; else if (value === 'false' || value === 'FALSE') return false; else if (FLOAT.test(value)) return parseFloat(value); else if (ISO_DATE.test(value)) return new Date(value); else return value === '' ? null : value; } return value; } function applyHeaderAndDynamicTypingAndTransformation() { if ( !_results || !_results.data || (!_config.header && !_config.dynamicTyping && !_config.transform) ) return _results; function processRow(rowSource, i) { var row = _config.header ? {} : []; var j; for (j = 0; j < rowSource.length; j++) { var field = j; var value = rowSource[j]; if (_config.header) field = j >= _fields.length ? '__parsed_extra' : _fields[j]; if (_config.transform) value = _config.transform(value, field); value = parseDynamic(field, value); if (field === '__parsed_extra') { row[field] = row[field] || []; row[field].push(value); } else row[field] = value; } if (_config.header) { if (j > _fields.length) addError( 'FieldMismatch', 'TooManyFields', 'Too many fields: expected ' + _fields.length + ' fields but parsed ' + j, _rowCounter + i ); else if (j < _fields.length) addError( 'FieldMismatch', 'TooFewFields', 'Too few fields: expected ' + _fields.length + ' fields but parsed ' + j, _rowCounter + i ); } return row; } var incrementBy = 1; if (!_results.data[0] || Array.isArray(_results.data[0])) { _results.data = _results.data.map(processRow); incrementBy = _results.data.length; } else _results.data = processRow(_results.data, 0); if (_config.header && _results.meta) _results.meta.fields = _fields; _rowCounter += incrementBy; return _results; } function guessDelimiter(input, newline, skipEmptyLines, comments, delimitersToGuess) { var bestDelim, bestDelta, fieldCountPrevRow; delimitersToGuess = delimitersToGuess || [',', '\t', '|', ';', Papa.RECORD_SEP, Papa.UNIT_SEP]; for (var i = 0; i < delimitersToGuess.length; i++) { var delim = delimitersToGuess[i]; var delta = 0, avgFieldCount = 0, emptyLinesCount = 0; fieldCountPrevRow = undefined; var preview = new Parser({ comments: comments, delimiter: delim, newline: newline, preview: 10 }).parse(input); for (var j = 0; j < preview.data.length; j++) { if (skipEmptyLines && testEmptyLine(preview.data[j])) { emptyLinesCount++; continue; } var fieldCount = preview.data[j].length; avgFieldCount += fieldCount; if (typeof fieldCountPrevRow === 'undefined') { fieldCountPrevRow = 0; continue; } else if (fieldCount > 1) { delta += Math.abs(fieldCount - fieldCountPrevRow); fieldCountPrevRow = fieldCount; } } if (preview.data.length > 0) avgFieldCount /= preview.data.length - emptyLinesCount; if ((typeof bestDelta === 'undefined' || delta > bestDelta) && avgFieldCount > 1.99) { bestDelta = delta; bestDelim = delim; } } _config.delimiter = bestDelim; return { successful: !!bestDelim, bestDelimiter: bestDelim }; } function guessLineEndings(input, quoteChar) { input = input.substr(0, 1024 * 1024); // max length 1 MB // Replace all the text inside quotes var re = new RegExp(escapeRegExp(quoteChar) + '([^]*?)' + escapeRegExp(quoteChar), 'gm'); input = input.replace(re, ''); var r = input.split('\r'); var n = input.split('\n'); var nAppearsFirst = n.length > 1 && n[0].length < r[0].length; if (r.length === 1 || nAppearsFirst) return '\n'; var numWithN = 0; for (var i = 0; i < r.length; i++) { if (r[i][0] === '\n') numWithN++; } return numWithN >= r.length / 2 ? '\r\n' : '\r'; } function addError(type, code, msg, row) { _results.errors.push({ type: type, code: code, message: msg, row: row }); } } /** https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions */ function escapeRegExp(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string } /** The core parser implements speedy and correct CSV parsing */ function Parser(config) { // Unpack the config object config = config || {}; var delim = config.delimiter; var newline = config.newline; var comments = config.comments; var step = config.step; var preview = config.preview; var fastMode = config.fastMode; var quoteChar; /** Allows for no quoteChar by setting quoteChar to undefined in config */ if (config.quoteChar === undefined) { quoteChar = '"'; } else { quoteChar = config.quoteChar; } var escapeChar = quoteChar; if (config.escapeChar !== undefined) { escapeChar = config.escapeChar; } // Delimiter must be valid if (typeof delim !== 'string' || Papa.BAD_DELIMITERS.indexOf(delim) > -1) delim = ','; // Comment character must be valid if (comments === delim) throw new Error('Comment character same as delimiter'); else if (comments === true) comments = '#'; else if (typeof comments !== 'string' || Papa.BAD_DELIMITERS.indexOf(comments) > -1) comments = false; // Newline must be valid: \r, \n, or \r\n if (newline !== '\n' && newline !== '\r' && newline !== '\r\n') newline = '\n'; // We're gonna need these at the Parser scope var cursor = 0; var aborted = false; this.parse = function (input, baseIndex, ignoreLastRow) { // For some reason, in Chrome, this speeds things up (!?) if (typeof input !== 'string') throw new Error('Input must be a string'); // We don't need to compute some of these every time parse() is called, // but having them in a more local scope seems to perform better var inputLen = input.length, delimLen = delim.length, newlineLen = newline.length, commentsLen = comments.length; var stepIsFunction = isFunction(step); // Establish starting state cursor = 0; var data = [], errors = [], row = [], lastCursor = 0; if (!input) return returnable(); if (fastMode || (fastMode !== false && input.indexOf(quoteChar) === -1)) { var rows = input.split(newline); for (var i = 0; i < rows.length; i++) { row = rows[i]; cursor += row.length; if (i !== rows.length - 1) cursor += newline.length; else if (ignoreLastRow) return returnable(); if (comments && row.substr(0, commentsLen) === comments) continue; if (stepIsFunction) { data = []; pushRow(row.split(delim)); doStep(); if (aborted) return returnable(); } else pushRow(row.split(delim)); if (preview && i >= preview) { data = data.slice(0, preview); return returnable(true); } } return returnable(); } var nextDelim = input.indexOf(delim, cursor); var nextNewline = input.indexOf(newline, cursor); var quoteCharRegex = new RegExp(escapeRegExp(escapeChar) + escapeRegExp(quoteChar), 'g'); var quoteSearch; // Parser loop for (;;) { // Field has opening quote if (input[cursor] === quoteChar) { // Start our search for the closing quote where the cursor is quoteSearch = cursor; // Skip the opening quote cursor++; for (;;) { // Find closing quote quoteSearch = input.indexOf(quoteChar, quoteSearch + 1); //No other quotes are found - no other delimiters if (quoteSearch === -1) { if (!ignoreLastRow) { // No closing quote... what a pity errors.push({ type: 'Quotes', code: 'MissingQuotes', message: 'Quoted field unterminated', row: data.length, // row has yet to be inserted index: cursor }); } return finish(); } // Closing quote at EOF if (quoteSearch === inputLen - 1) { var value = input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar); return finish(value); } // If this quote is escaped, it's part of the data; skip it // If the quote character is the escape character, then check if the next character is the escape character if (quoteChar === escapeChar && input[quoteSearch + 1] === escapeChar) { quoteSearch++; continue; } // If the quote character is not the escape character, then check if the previous character was the escape character if ( quoteChar !== escapeChar && quoteSearch !== 0 && input[quoteSearch - 1] === escapeChar ) { continue; } // Check up to nextDelim or nextNewline, whichever is closest var checkUpTo = nextNewline === -1 ? nextDelim : Math.min(nextDelim, nextNewline); var spacesBetweenQuoteAndDelimiter = extraSpaces(checkUpTo); // Closing quote followed by delimiter or 'unnecessary spaces + delimiter' if (input[quoteSearch + 1 + spacesBetweenQuoteAndDelimiter] === delim) { row.push(input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar)); cursor = quoteSearch + 1 + spacesBetweenQuoteAndDelimiter + delimLen; nextDelim = input.indexOf(delim, cursor); nextNewline = input.indexOf(newline, cursor); if (stepIsFunction) { doStep(); if (aborted) return returnable(); } if (preview && data.length >= preview) return returnable(true); break; } var spacesBetweenQuoteAndNewLine = extraSpaces(nextNewline); // Closing quote followed by newline or 'unnecessary spaces + newLine' if ( input.substr(quoteSearch + 1 + spacesBetweenQuoteAndNewLine, newlineLen) === newline ) { row.push(input.substring(cursor, quoteSearch).replace(quoteCharRegex, quoteChar)); saveRow(quoteSearch + 1 + spacesBetweenQuoteAndNewLine + newlineLen); nextDelim = input.indexOf(delim, cursor); // because we may have skipped the nextDelim in the quoted field if (stepIsFunction) { doStep(); if (aborted) return returnable(); } if (preview && data.length >= preview) return returnable(true); break; } // Checks for valid closing quotes are complete (escaped quotes or quote followed by EOF/delimiter/newline) -- assume these quotes are part of an invalid text string errors.push({ type: 'Quotes', code: 'InvalidQuotes', message: 'Trailing quote on quoted field is malformed', row: data.length, // row has yet to be inserted index: cursor }); quoteSearch++; continue; } if (stepIsFunction) { doStep(); if (aborted) return returnable(); } if (preview && data.length >= preview) return returnable(true); continue; } // Comment found at start of new line if (comments && row.length === 0 && input.substr(cursor, commentsLen) === comments) { if (nextNewline === -1) // Comment ends at EOF return returnable(); cursor = nextNewline + newlineLen; nextNewline = input.indexOf(newline, cursor); nextDelim = input.indexOf(delim, cursor); continue; } // Next delimiter comes before next newline, so we've reached end of field if (nextDelim !== -1 && (nextDelim < nextNewline || nextNewline === -1)) { row.push(input.substring(cursor, nextDelim)); cursor = nextDelim + delimLen; nextDelim = input.indexOf(delim, cursor); continue; } // End of row if (nextNewline !== -1) { row.push(input.substring(cursor, nextNewline)); saveRow(nextNewline + newlineLen); if (stepIsFunction) { doStep(); if (aborted) return returnable(); } if (preview && data.length >= preview) return returnable(true); continue; } break; } return finish(); function pushRow(row) { data.push(row); lastCursor = cursor; } /** * checks if there are extra spaces after closing quote and given index without any text * if Yes, returns the number of spaces */ function extraSpaces(index) { var spaceLength = 0; if (index !== -1) { var textBetweenClosingQuoteAndIndex = input.substring(quoteSearch + 1, index); if (textBetweenClosingQuoteAndIndex && textBetweenClosingQuoteAndIndex.trim() === '') { spaceLength = textBetweenClosingQuoteAndIndex.length; } } return spaceLength; } /** * Appends the remaining input from cursor to the end into * row, saves the row, calls step, and returns the results. */ function finish(value) { if (ignoreLastRow) return returnable(); if (typeof value === 'undefined') value = input.substr(cursor); row.push(value); cursor = inputLen; // important in case parsing is paused pushRow(row); if (stepIsFunction) doStep(); return returnable(); } /** * Appends the current row to the results. It sets the cursor * to newCursor and finds the nextNewline. The caller should * take care to execute user's step function and check for * preview and end parsing if necessary. */ function saveRow(newCursor) { cursor = newCursor; pushRow(row); row = []; nextNewline = input.indexOf(newline, cursor); } /** Returns an object with the results, errors, and meta. */ function returnable(stopped, step) { var isStep = step || false; return { data: isStep ? data[0] : data, errors: errors, meta: { delimiter: delim, linebreak: newline, aborted: aborted, truncated: !!stopped, cursor: lastCursor + (baseIndex || 0) } }; } /** Executes the user's step function and resets data & errors. */ function doStep() { step(returnable(undefined, true)); data = []; errors = []; } }; /** Sets the abort flag */ this.abort = function () { aborted = true; }; /** Gets the cursor position */ this.getCharIndex = function () { return cursor; }; } function notImplemented() { throw new Error('Not implemented.'); } /** Makes a deep copy of an array or object (mostly) */ function copy(obj) { if (typeof obj !== 'object' || obj === null) return obj; var cpy = Array.isArray(obj) ? [] : {}; for (var key in obj) cpy[key] = copy(obj[key]); return cpy; } function isFunction(func) { return typeof func === 'function'; }
the_stack
import {Component, ElementRef, Input, Output, EventEmitter, OnInit, OnDestroy, Inject, ViewEncapsulation} from '@angular/core'; import { Subject, fromEvent } from 'rxjs'; import { debounceTime } from 'rxjs/operators'; import { dia } from 'jointjs'; import { Flo } from '../shared/flo-common'; import '../shared/shapes'; import { Shapes, Constants } from '../shared/shapes'; import { DOCUMENT } from '@angular/common' import * as _$ from 'jquery'; import {Logger} from '../shared/logger'; const joint: any = Flo.joint; const $: any = _$; const DEBOUNCE_TIME = 300; @Component({ selector: 'flo-palette', templateUrl: './palette.component.html', styleUrls: ['./palette.component.scss'], encapsulation: ViewEncapsulation.None }) export class Palette implements OnInit, OnDestroy { private _metamodelListener: Flo.MetamodelListener = { metadataError: (data) => {}, metadataAboutToChange: () => {}, metadataChanged: () => { if (this.initialized && this.metamodel) { this.metamodel.load().then(metamodel => this.buildPalette(metamodel)); } } }; /** * The names of any groups in the palette that have been deliberately closed (the arrow clicked on) */ private closedGroups: Set<string>; /** * Model of the clicked element */ private clickedElement: dia.Cell | undefined; private viewBeingDragged: dia.CellView | undefined; private initialized = false; private _paletteSize: number; private _filterText = ''; private paletteGraph: dia.Graph; private palette: dia.Paper; private floaterpaper: dia.Paper; private filterTextModel = new Subject<string>(); private noMacthesFoundNode: dia.Cell; @Input() metamodel: Flo.Metamodel; @Input() renderer: Flo.Renderer; @Input() paletteEntryPadding: dia.Size = {width: 12, height: 12}; @Input() searchFilterPlaceHolder = 'Search...'; @Output() onPaletteEntryDrop = new EventEmitter<Flo.DnDEvent>(); @Output() paletteReady = new EventEmitter<boolean>(); @Output() paletteFocus = new EventEmitter<void>(); private mouseMoveHanlder = (e: any) => this.handleDrag(e); private mouseUpHanlder = (e: any) => this.handleMouseUp(e); @Input() set paletteSize(size: number) { Logger.debug('Palette Size: ' + size); if (this._paletteSize !== size) { this._paletteSize = size; if (this.palette) { this.layout(); } } } constructor(private element: ElementRef, @Inject(DOCUMENT) private document: any) { this.paletteGraph = new joint.dia.Graph(); this.paletteGraph.set('type', Constants.PALETTE_CONTEXT); this._filterText = ''; this.closedGroups = new Set<string>(); } onFocus(): void { this.paletteFocus.emit(); } ngOnInit() { let element = $('#palette-paper', this.element.nativeElement); // Create the paper for the palette using the specified element view this.palette = new joint.dia.Paper({ el: element, gridSize: 1, model: this.paletteGraph, height: $(this.element.nativeElement.parentNode).height(), width: $(this.element.nativeElement.parentNode).width(), elementView: this.getPaletteView(this.renderer && this.renderer.getNodeView ? this.renderer.getNodeView() : joint.dia.ElementView), interactive: false }); this.palette.on('cell:pointerup', (cellview: dia.CellView, evt: any) => { if (this.viewBeingDragged) { this.trigger({ type: Flo.DnDEventType.DROP, view: this.viewBeingDragged, event: evt }); this.viewBeingDragged = undefined; } this.clickedElement = undefined; $('#palette-floater').remove(); if (this.floaterpaper) { this.floaterpaper.remove(); } }); // Toggle the header open/closed on a click this.palette.on('cell:pointerclick', (cellview: dia.CellView, event: any) => { // TODO [design][palette] should the user need to click on the arrow rather than anywhere on the header? // Click position within the element would be: evt.offsetX, evt.offsetY const cell: dia.Cell = cellview.model; if (cell.attributes.header) { // Toggle the header open/closed // if (cell.get('isOpen')) { // this.rotateClosed(cell); // } else { // this.rotateOpen(cell); // } } // TODO [palette] ensure other mouse handling events do nothing for headers // TODO [palette] move 'metadata' field to the right place (not inside attrs I think) }); $(this.document).on('mouseup', this.mouseUpHanlder); if (this.metamodel) { this.metamodel.load().then(data => { this.buildPalette(data); // Add listener to metamodel if (this.metamodel && this.metamodel.subscribe) { this.metamodel.subscribe(this._metamodelListener); } // Add debounced listener to filter text changes this.filterTextModel .pipe(debounceTime(DEBOUNCE_TIME)) .subscribe((value) => this.layout()); this.initialized = true; }); } else { Logger.error('No Metamodel service specified for palette!'); } this._paletteSize = this._paletteSize || $(this.element.nativeElement.parentNode).width(); } ngOnDestroy() { if (this.metamodel && this.metamodel.unsubscribe) { this.metamodel.unsubscribe(this._metamodelListener); } $(this.document).off('mouseup', this.mouseUpHanlder); this.palette.remove(); } private createPaletteGroup(title: string, isOpen: boolean): dia.Element { const paletteRenderer: Flo.PaletteRenderer = this.renderer && this.renderer.getPaletteRenderer ? this.renderer.getPaletteRenderer() : { createGroupHeader: (titleStr: string, isOpenParam: boolean) => { const header = new joint.shapes.flo.PaletteGroupHeader({attrs: {text: {text: titleStr}}}); if (!isOpenParam) { header.attr({'path': {'transform': 'rotate(-90,15,13)'}}); } return header; }, onClose: (groupView: dia.CellView) => this.rotateClosed(groupView.model), onOpen: (groupView: dia.CellView) => this.rotateOpen(groupView.model) }; let newGroupHeader = paletteRenderer.createGroupHeader(title, isOpen); if (!isOpen) { newGroupHeader.set('isOpen', false); } newGroupHeader.set('header', title); this.paletteGraph.addCell(newGroupHeader); const view = this.palette.findViewByModel(newGroupHeader); view.on('cell:pointerclick', () => { if (newGroupHeader.get('isOpen')) { if (typeof paletteRenderer.onClose === 'function') { paletteRenderer.onClose(view).then(() => { newGroupHeader.set('isOpen', false); this.closedGroups.add(newGroupHeader.get('header')); this.layout(); }); } else { newGroupHeader.set('isOpen', false); this.closedGroups.add(newGroupHeader.get('header')); this.layout(); } } else { if (typeof paletteRenderer.onOpen === 'function') { paletteRenderer.onOpen(view).then(() => { newGroupHeader.set('isOpen', true); this.closedGroups.delete(newGroupHeader.get('header')); this.layout(); }); } else { newGroupHeader.set('isOpen', true); this.closedGroups.delete(newGroupHeader.get('header')); this.layout(); } } }); return newGroupHeader; } private createPaletteEntry(title: string, metadata: Flo.ElementMetadata) { return Shapes.Factory.createNode({ renderer: this.renderer, paper: this.palette, metadata: metadata }); } private buildPalette(metamodel: Map<string, Map<string, Flo.ElementMetadata>>) { let startTime: number = new Date().getTime(); this.paletteReady.emit(false); this.paletteGraph.clear(); let groupAdded: Set<string> = new Set<string>(); let parentWidth: number = this._paletteSize - Flo.SCROLLBAR_WIDTH; Logger.debug(`Parent Width: ${parentWidth}`); // The field closedGroups tells us which should not be shown // Work out the list of active groups/nodes based on the filter text this.metamodel.groups().forEach(group => { if (metamodel && metamodel.has(group)) { Array.from(metamodel.get(group)!.keys()).sort().forEach(name => { let node = metamodel.get(group)!.get(name); if (node) { if (!groupAdded.has(group)) { this.createPaletteGroup(group, !this.closedGroups.has(group)); groupAdded.add(group); } if (!(node.metadata && node.metadata.noPaletteEntry)) { this.createPaletteEntry(name, node); } } }); } }); this.noMacthesFoundNode = new joint.shapes.flo.NoMatchesFound(); this.palette.model.addCell(this.noMacthesFoundNode); this.layout(); this.paletteReady.emit(true); Logger.debug('buildPalette took ' + (new Date().getTime() - startTime) + 'ms'); } private layout() { let startTime: number = new Date().getTime(); let filterText = this.filterText; if (filterText) { filterText = filterText.toLowerCase(); } let paletteNodes: Array<dia.Cell> = []; let parentWidth: number = this._paletteSize - Flo.SCROLLBAR_WIDTH; Logger.debug(`Parent Width: ${parentWidth}`); const presentGroups = new Set<string>(); this.palette.model.getCells().forEach((cell: dia.Cell) => { const metadata: Flo.ElementMetadata = cell.get('metadata'); if (cell.get('header')) { paletteNodes.push(cell); } else if (metadata && metadata.group && metadata.name && (!filterText || metadata.group.toLocaleLowerCase().indexOf(filterText) >= 0 || metadata.name.toLocaleLowerCase().indexOf(filterText) >= 0) ) { if (!this.closedGroups.has(metadata.group)) { cell.attr('./display', 'block'); cell.removeAttr('./display'); paletteNodes.push(cell); } else { cell.attr('./display', 'none'); } presentGroups.add(metadata.group); } else { if (cell === this.noMacthesFoundNode) { } else { cell.attr('./display', 'none'); } } }); // Clean group headers const filteredGroupHeaders: dia.Cell[] = []; paletteNodes.forEach(cell => { if (cell.get('header')) { if (presentGroups.has(cell.get('header'))) { cell.attr('./display', 'block'); cell.removeAttr('./display'); filteredGroupHeaders.push(cell); } else { cell.attr('./display', 'none'); } } else { filteredGroupHeaders.push(cell); } }); paletteNodes = filteredGroupHeaders; // Check if last group is empty const previous = paletteNodes.length > 0 ? paletteNodes[paletteNodes.length - 1] : undefined; // If previous is a paletter header node as well then the previous header had no nodes under it and we can hide it and remove from paletteNodes aeeay if (previous && previous.get('header') && !this.closedGroups.has(previous.get('header'))) { paletteNodes.pop().attr('./display', 'none'); } let cellWidth = 0, cellHeight = 0; // Determine the size of the palette entry cell (width and height) paletteNodes.forEach(pnode => { if (pnode.get('metadata')?.name) { const elementSize = this.palette.findViewByModel(pnode).getBBox(); let dimension: dia.Size = { width: elementSize.width, height: elementSize.height }; if (cellWidth < dimension.width) { cellWidth = dimension.width; } if (cellHeight < dimension.height) { cellHeight = dimension.height; } } }); // Adjust the palette entry cell size with paddings. cellWidth += 2 * this.paletteEntryPadding.width; cellHeight += 2 * this.paletteEntryPadding.height; // Align palette entries row to be at the center let startX: number = parentWidth >= cellWidth ? (parentWidth - Math.floor(parentWidth / cellWidth) * cellWidth) / 2 : 0; let xpos = startX; let ypos = 0; let prevNode: dia.Cell; // Layout palette entry nodes paletteNodes.forEach(pnode => { const elementSize = this.palette.findViewByModel(pnode).getBBox(); let dimension: dia.Size = { width: elementSize.width, height: elementSize.height }; if (pnode.get('header')) { //attributes.attrs.header) { // Palette entry header xpos = startX; if (ypos) { ypos += this.paletteEntryPadding.height; } pnode.set('size', {width: parentWidth, height: pnode.get('size').height || 30}); pnode.set('position', {x: 0, y: ypos}); ypos += dimension.height + this.paletteEntryPadding.height; } else { // Palette entry element if (xpos + cellWidth > parentWidth) { // Not enough real estate to place entry in a row - reset x position and leave the y pos which is next line xpos = startX; pnode.set('position', { x: xpos + (cellWidth - dimension.width) / 2, y: ypos + (cellHeight - dimension.height) / 2}); } else { // Enough real estate to place entry in a row - adjust y position if (prevNode && prevNode.get('metadata')?.name) { ypos -= cellHeight; } pnode.set('position', { x: xpos + (cellWidth - dimension.width) / 2, y: ypos + (cellHeight - dimension.height) / 2}); } // increment x position and y position (can be reorganized) xpos += cellWidth; ypos += cellHeight; } prevNode = pnode; }); this.noMacthesFoundNode.set('size', {width: parentWidth, height: this.noMacthesFoundNode.get('size').height || 30}); this.noMacthesFoundNode.set('position', {x: 0, y: 0}); if (paletteNodes.length === 0 && filterText) { // There is a filter present but everything is filtered out // Show no matches found node this.noMacthesFoundNode.attr('./display', 'block'); this.noMacthesFoundNode.removeAttr('./display'); ypos = this.noMacthesFoundNode.get('size').height; } else { // Hide no matches node in all other cases this.noMacthesFoundNode.attr('./display', 'none'); } this.palette.setDimensions(parentWidth, ypos); Logger.debug('buildPalette layout ' + (new Date().getTime() - startTime) + 'ms'); } set filterText(text: string) { if (this._filterText !== text) { this._filterText = text; this.filterTextModel.next(text); } } get filterText(): string { return this._filterText; } private getPaletteView(view: any): dia.Element { let self: Palette = this; return view.extend({ pointerdown: function(/*evt, x, y*/) { // Remove the tooltip // $('.node-tooltip').remove(); // TODO move metadata to the right place (not inside attrs I think) self.clickedElement = this.model; if (self.clickedElement && self.clickedElement.get('metadata')) { $(self.document).on('mousemove', self.mouseMoveHanlder); } }, pointermove: function(/*evt, x, y*/) { // Nothing to prevent move within the palette canvas }, // events: { // // Tooltips on the palette elements // 'mouseenter': function(evt) { // // // Ignore 'mouseenter' if any other buttons are pressed // if (evt.buttons) { // return; // } // // var model = this.model; // var metadata = model.get('metadata'); // if (!metadata) { // return; // } // // this.showTooltip(evt.pageX, evt.pageY); // }, // // TODO bug here - if the call to get the info takes a while, the tooltip may appear after the pointer has left the cell // 'mouseleave': function(/*evt, x,y*/) { // this.hideTooltip(); // }, // 'mousemove': function(evt) { // this.moveTooltip(evt.pageX, evt.pageY); // } // }, // showTooltip: function(x, y) { // var model = this.model; // var metadata = model.get('metadata'); // // TODO refactor to use tooltip module // var nodeTooltip = document.createElement('div'); // $(nodeTooltip).addClass('node-tooltip'); // $(nodeTooltip).appendTo($('body')).fadeIn('fast'); // var nodeDescription = document.createElement('div'); // $(nodeTooltip).addClass('tooltip-description'); // $(nodeTooltip).append(nodeDescription); // // metadata.get('description').then(function(description) { // $(nodeDescription).text(description ? description: model.attr('metadata/name')); // }, function() { // $(nodeDescription).text(model.attr('metadata/name')); // }); // // if (!metadata.metadata || !metadata.metadata['hide-tooltip-options']) { // metadata.get('properties').then(function(metaProps) { // if (metaProps) { // Object.keys(metaProps).sort().forEach(function(propertyName) { // var optionRow = document.createElement('div'); // var optionName = document.createElement('span'); // var optionDescription = document.createElement('span'); // $(optionName).addClass('node-tooltip-option-name'); // $(optionDescription).addClass('node-tooltip-option-description'); // $(optionName).text(metaProps[propertyName].name); // $(optionDescription).text(metaProps[propertyName].description); // $(optionRow).append(optionName); // $(optionRow).append(optionDescription); // $(nodeTooltip).append(optionRow); // }); // } // }, function(error) { // if (error) { // $log.error(error); // } // }); // } // // var mousex = x + 10; // var mousey = y + 10; // $('.node-tooltip').css({ top: mousey, left: mousex }); // }, // // hideTooltip: function() { // $('.node-tooltip').remove(); // }, // // moveTooltip: function(x, y) { // var mousex = x + 10; // Get X coordinates // var mousey = y + 10; // Get Y coordinates // $('.node-tooltip').css({ top: mousey, left: mousex }); // } }); } private handleMouseUp(event: any) { $(this.document).off('mousemove', this.mouseMoveHanlder); } private trigger(event: Flo.DnDEvent) { this.onPaletteEntryDrop.emit(event); } private handleDrag(event: any) { // TODO offsetX/Y not on firefox // Logger.debug("tracking move: x="+event.pageX+",y="+event.pageY); // Logger.debug('Element = ' + (this.clickedElement ? this.clickedElement.attr('metadata/name'): 'null')); if (this.clickedElement && this.clickedElement.get('metadata')) { if (!this.viewBeingDragged) { let dataOfClickedElement: Flo.ElementMetadata = this.clickedElement.get('metadata'); // custom div if not already built. $('<div>', { id: 'palette-floater' }).appendTo($('body')); let floatergraph: dia.Graph = new joint.dia.Graph(); floatergraph.set('type', Constants.FEEDBACK_CONTEXT); const parent = $('#palette-floater'); this.floaterpaper = new joint.dia.Paper({ el: $('#palette-floater'), elementView: this.renderer && this.renderer.getNodeView ? this.renderer.getNodeView() : joint.dia.ElementView, gridSize: 10, model: floatergraph, height: parent.height(), width: parent.width(), validateMagnet: () => false, validateConnection: () => false }); // TODO float thing needs to be bigger otherwise icon label is missing // Initiative drag and drop - create draggable element let floaternode: dia.Element = Shapes.Factory.createNode({ 'renderer': this.renderer, 'paper': this.floaterpaper, 'graph': floatergraph, 'metadata': dataOfClickedElement }); // Only node view expected this.viewBeingDragged = this.floaterpaper.findViewByModel(floaternode); const resizeObserver = new ResizeObserver(() => { if (this.viewBeingDragged) { const box: dia.BBox = (<dia.ElementView>this.viewBeingDragged).getBBox(); const size: dia.Size = (<dia.ElementView>this.viewBeingDragged).model.size(); // Account for ports. Especially on the left side. Box includes ports, size does not parent.css('width', box.width + box.width - size.width); parent.css('height', box.height + box.height - size.height); floaternode.position(box.width - size.width, box.height - size.height); } }); resizeObserver.observe(this.viewBeingDragged.el); let box: dia.BBox = (<dia.ElementView>this.viewBeingDragged).getBBox(); let size: dia.Size = floaternode.size(); // Account for node real size including ports parent.css('width', box.width + box.width - size.width); parent.css('height', box.height + box.height - size.height); floaternode.position(box.width - size.width, box.height - size.height); parent.offset({left: event.pageX + 5, top: event.pageY + 5}); } else { $('#palette-floater').offset({left: event.pageX + 5, top: event.pageY + 5}); this.trigger({ type: Flo.DnDEventType.DRAG, view: this.viewBeingDragged, event: event }); } } } /* * Modify the rotation of the arrow in the header from horizontal(closed) to vertical(open) */ private rotateOpen(element: dia.Cell): Promise<void> { return new Promise(resolve => { setTimeout(() => this.doRotateOpen(element, 90).then(() => { resolve(); })); }); } private doRotateOpen(element: dia.Cell, angle: number): Promise<void> { return new Promise(resolve => { angle -= 10; element.attr({'path': {'transform': 'rotate(-' + angle + ',15,13)'}}); if (angle <= 0) { resolve(); } else { setTimeout(() => this.doRotateOpen(element, angle).then(() => resolve()), 10); } }); } private doRotateClose(element: dia.Cell, angle: number): Promise<void> { return new Promise(resolve => { angle += 10; element.attr({'path': {'transform': 'rotate(-' + angle + ',15,13)'}}); if (angle >= 90) { resolve(); } else { setTimeout(() => this.doRotateClose(element, angle).then(() => resolve()), 10); } }); } // TODO better name for this function as this does the animation *and* updates the palette /* * Modify the rotation of the arrow in the header from vertical(open) to horizontal(closed) */ private rotateClosed(element: dia.Cell): Promise<void> { return new Promise(resolve => { setTimeout(() => { this.doRotateClose(element, 0).then(() => { resolve(); }); }); }); } }
the_stack
import { detect } from "detect-browser"; import { AuthEvent, AuthEventKind, AuthInfo, CoreStitchAuth, CoreStitchUser, DeviceFields, StitchAppClientInfo, StitchAuthResponseCredential, StitchClientError, StitchClientErrorCode, StitchCredential, StitchRequestClient, StitchUserFactory, Storage } from "mongodb-stitch-core-sdk"; import version from "../../internal/common/Version"; import AuthProviderClientFactory from "../providers/internal/AuthProviderClientFactory"; import NamedAuthProviderClientFactory from "../providers/internal/NamedAuthProviderClientFactory"; import StitchRedirectCredential from "../providers/StitchRedirectCredential"; import StitchAuth from "../StitchAuth"; import StitchAuthListener from "../StitchAuthListener"; import StitchUser from "../StitchUser"; import RedirectFragmentFields from "./RedirectFragmentFields"; import RedirectKeys from "./RedirectKeys"; import StitchBrowserAppAuthRoutes from "./StitchBrowserAppAuthRoutes"; import StitchRedirectError from "./StitchRedirectError"; import StitchUserFactoryImpl from "./StitchUserFactoryImpl"; const alphaNumericCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; /** * Partial JSDOM window.location containing only the * properties and method we need */ interface PartialLocation { hash: string; protocol: string; host: string; pathname: string; replace(url: string); } /** * Partial JSDOM window.history containing only the method * we need */ interface PartialHistory { replaceState(data: any, title?: string, url?: string | null); } /** * Partial JSDOM window interface to contract the functionality * of the window for StitchAuthImpl */ interface PartialWindow { location: PartialLocation; history: PartialHistory; } /** @hidden */ export default class StitchAuthImpl extends CoreStitchAuth<StitchUser> implements StitchAuth { public static injectedFetch?: any; private readonly listeners: Set<StitchAuthListener> = new Set(); private readonly synchronousListeners: Set<StitchAuthListener> = new Set(); /** * Construct a new StitchAuth implementation * * @param requestClient StitchRequestClient that does request * @param browserAuthRoutes pathnames to call for browser routes * @param authStorage internal storage * @param appInfo info about the current stitch app * @param jsdomWindow window interface to interact with JSDOM window */ public constructor( requestClient: StitchRequestClient, private readonly browserAuthRoutes: StitchBrowserAppAuthRoutes, private readonly authStorage: Storage, private readonly appInfo: StitchAppClientInfo, private readonly jsdomWindow: PartialWindow = window ) { super(requestClient, browserAuthRoutes, authStorage); } protected get userFactory(): StitchUserFactory<StitchUser> { return new StitchUserFactoryImpl(this); } public getProviderClient<ClientT>( factory: | AuthProviderClientFactory<ClientT> | NamedAuthProviderClientFactory<ClientT>, providerName?: string ): ClientT { if (isAuthProviderClientFactory(factory)) { return factory.getClient(this, this.requestClient, this.authRoutes); } else { return factory.getNamedClient( providerName!, this.requestClient, this.authRoutes ); } } public loginWithCredential( credential: StitchCredential ): Promise<StitchUser> { return super.loginWithCredentialInternal(credential); } public loginWithRedirect(credential: StitchRedirectCredential): void { const { redirectUrl, state } = this.prepareRedirect(credential); this.requestClient.getBaseURL().then(baseUrl => { this.jsdomWindow.location.replace(baseUrl + this.browserAuthRoutes.getAuthProviderRedirectRoute( credential, redirectUrl, state, this.deviceInfo ) ) }); } public linkWithRedirectInternal( user: StitchUser, credential: StitchRedirectCredential ): Promise<void> { if (this.user !== undefined && user.id !== this.user.id) { return Promise.reject( new StitchClientError(StitchClientErrorCode.UserNoLongerValid) ); } const { redirectUrl, state } = this.prepareRedirect(credential); return this.requestClient.getBaseURL().then(baseUrl => { const link = baseUrl + this.browserAuthRoutes.getAuthProviderLinkRedirectRoute( credential, redirectUrl, state, this.deviceInfo ); return (StitchAuthImpl.injectedFetch ? StitchAuthImpl.injectedFetch! : fetch)( new Request(link, { credentials: "include", headers: { Authorization: "Bearer " + this.authInfo.accessToken }, mode: 'cors' }) ) }).then(response => { this.jsdomWindow.location.replace( response.headers.get("X-Stitch-Location")! ); }); } public hasRedirectResult(): boolean { let isValid = false; try { isValid = this.parseRedirect().isValid; return isValid; } catch (_) { return false; } finally { if (!isValid) { this.cleanupRedirect(); } } } public handleRedirectResult(): Promise<StitchUser> { try { const providerName = this.authStorage.get(RedirectKeys.ProviderName); const providerType = this.authStorage.get(RedirectKeys.ProviderType); const redirectFragment = this.parseRedirect(); return this.loginWithCredentialInternal( new StitchAuthResponseCredential( this.processRedirectResult(redirectFragment), providerType, providerName, redirectFragment.asLink ) ).then(user => user); } catch (err) { return Promise.reject(err); } } public linkWithCredential( user: CoreStitchUser, credential: StitchCredential ): Promise<StitchUser> { return super.linkUserWithCredentialInternal(user, credential); } public logout(): Promise<void> { // Guard against users accidentally thinking this is logoutUserWithId if (arguments.length > 0) { return Promise.reject( new StitchClientError(StitchClientErrorCode.UnexpectedArguments) ); } return super.logoutInternal(); } public logoutUserWithId(userId: string): Promise<void> { return super.logoutUserWithIdInternal(userId); } public removeUser(): Promise<void> { // Guard against users accidentally thinking this is removeUserWithId if (arguments.length > 0) { return Promise.reject( new StitchClientError(StitchClientErrorCode.UnexpectedArguments) ); } return super.removeUserInternal(); } public removeUserWithId(userId: string): Promise<void> { return super.removeUserWithIdInternal(userId); } protected get deviceInfo() { const info = {}; if (this.hasDeviceId) { info[DeviceFields.DEVICE_ID] = this.deviceId; } if (this.appInfo.localAppName !== undefined) { info[DeviceFields.APP_ID] = this.appInfo.localAppName; } if (this.appInfo.localAppVersion !== undefined) { info[DeviceFields.APP_VERSION] = this.appInfo.localAppVersion; } const browser = detect(); if (browser) { info[DeviceFields.PLATFORM] = browser.name; info[DeviceFields.PLATFORM_VERSION] = browser.version; } else { info[DeviceFields.PLATFORM] = "web"; info[DeviceFields.PLATFORM_VERSION] = "0.0.0"; } info[DeviceFields.SDK_VERSION] = version; return info; } public addAuthListener(listener: StitchAuthListener) { this.listeners.add(listener); // Trigger the ListenerRegistered event in case some event happens and // This caller would miss out on this event other wise. // Dispatch a legacy deprecated auth event this.onAuthEvent(listener); // Dispatch a new style auth event this.dispatchAuthEvent({ kind: AuthEventKind.ListenerRegistered, }); } public addSynchronousAuthListener(listener: StitchAuthListener) { this.listeners.add(listener); // Trigger the ListenerRegistered event in case some event happens and // This caller would miss out on this event other wise. // Dispatch a legacy deprecated auth event this.onAuthEvent(listener); // Dispatch a new style auth event this.dispatchAuthEvent({ kind: AuthEventKind.ListenerRegistered, }); } public removeAuthListener(listener: StitchAuthListener) { this.listeners.delete(listener); } /** * Dispatch method for the deprecated auth listener method onAuthEvent. */ public onAuthEvent(listener?: StitchAuthListener) { if (listener) { const _ = new Promise(resolve => { if (listener.onAuthEvent) { listener.onAuthEvent(this); } resolve(undefined); }); } else { this.listeners.forEach(one => { this.onAuthEvent(one); }); } } /** * Dispatch method for the new auth listener methods. * @param event the discriminated union representing the auth event */ public dispatchAuthEvent(event: AuthEvent<StitchUser>) { switch(event.kind) { case AuthEventKind.ActiveUserChanged: this.dispatchBlockToListeners((listener: StitchAuthListener) => { if (listener.onActiveUserChanged) { listener.onActiveUserChanged( this, event.currentActiveUser, event.previousActiveUser ); } }); break; case AuthEventKind.ListenerRegistered: this.dispatchBlockToListeners((listener: StitchAuthListener) => { if (listener.onListenerRegistered) { listener.onListenerRegistered(this); } }); break; case AuthEventKind.UserAdded: this.dispatchBlockToListeners((listener: StitchAuthListener) => { if (listener.onUserAdded) { listener.onUserAdded(this, event.addedUser); } }); break; case AuthEventKind.UserLinked: this.dispatchBlockToListeners((listener: StitchAuthListener) => { if (listener.onUserLinked) { listener.onUserLinked(this, event.linkedUser); } }) break; case AuthEventKind.UserLoggedIn: this.dispatchBlockToListeners((listener: StitchAuthListener) => { if (listener.onUserLoggedIn) { listener.onUserLoggedIn( this, event.loggedInUser ); } }); break; case AuthEventKind.UserLoggedOut: this.dispatchBlockToListeners((listener: StitchAuthListener) => { if (listener.onUserLoggedOut) { listener.onUserLoggedOut( this, event.loggedOutUser ); } }); break; case AuthEventKind.UserRemoved: this.dispatchBlockToListeners((listener: StitchAuthListener) => { if (listener.onUserRemoved) { listener.onUserRemoved(this, event.removedUser); } }); break; default: /* Compiler trick to force this switch to be exhaustive. if the above * switch statement doesn't check all AuthEventKinds, event will not * be of type never */ return this.assertNever(event); } } public refreshCustomData(): Promise<void> { return this.refreshAccessToken(); } /** * Utility function used to force the compiler to enforce an exhaustive * switch statment in dispatchAuthEvent at compile-time. * @see https://www.typescriptlang.org/docs/handbook/advanced-types.html */ private assertNever(x: never): never { throw new Error("unexpected object: " + x); } /** * Dispatches the provided block to all auth listeners, including the * synchronous and asynchronous ones. * @param block The block to dispatch to listeners. */ private dispatchBlockToListeners(block: (StitchAuthListener) => void) { // Dispatch to all synchronous listeners this.synchronousListeners.forEach(block); // Dispatch to all asynchronous listeners this.listeners.forEach(listener => { const _ = new Promise(resolve => { block(listener); resolve(undefined); }) }); } private cleanupRedirect() { // This should probably be undefined, but null works just fine and we dont want to test // all browsers which may behave differently. Furthermore, the documentation on replaceState() // uses null. /* tslint:disable:no-null-keyword */ this.jsdomWindow.history.replaceState(null, "", this.pageRootUrl()); /* tslint:enable:no-null-keyword */ this.authStorage.remove(RedirectKeys.State); this.authStorage.remove(RedirectKeys.ProviderName); this.authStorage.remove(RedirectKeys.ProviderType); } private parseRedirect(): ParsedRedirectFragment | never { if (typeof this.jsdomWindow === "undefined") { // This means we're running in some environment other // Than a browser - so handling a redirect makes no sense here. throw new StitchRedirectError("running in a non-browser environment"); } if (!this.jsdomWindow.location || !this.jsdomWindow.location.hash) { throw new StitchRedirectError("window location hash was undefined"); } const ourState = this.authStorage.get(RedirectKeys.State); const redirectFragment = this.jsdomWindow.location.hash.substring(1); return parseRedirectFragment( redirectFragment, ourState, this.appInfo.clientAppId ); } private processRedirectResult(redirectFragment: ParsedRedirectFragment): AuthInfo | never { try { if (!redirectFragment.isValid) { throw new StitchRedirectError(`invalid redirect result`); } if (redirectFragment.lastError) { // Remove the fragment from the window history and reject throw new StitchRedirectError( `error handling redirect: ${redirectFragment.lastError}` ); } if (!redirectFragment.authInfo) { throw new StitchRedirectError( "no user auth value was found: it could not be decoded from fragment" ); } } catch (err) { throw err; } finally { this.cleanupRedirect(); } return redirectFragment.authInfo; } private prepareRedirect( credential: StitchRedirectCredential ): { redirectUrl: string; state: string } { this.authStorage.set(RedirectKeys.ProviderName, credential.providerName); this.authStorage.set(RedirectKeys.ProviderType, credential.providerType); let redirectUrl = credential.redirectUrl; if (redirectUrl === undefined) { redirectUrl = this.pageRootUrl(); } const state = generateState(); this.authStorage.set(RedirectKeys.State, state); return { redirectUrl, state }; } private pageRootUrl(): string { return [ this.jsdomWindow.location.protocol, "//", this.jsdomWindow.location.host, this.jsdomWindow.location.pathname ].join(""); } } function generateState(): string { let state = ""; for (let i = 0; i < 64; ++i) { state += alphaNumericCharacters.charAt( Math.floor(Math.random() * alphaNumericCharacters.length) ); } return state; } function unmarshallUserAuth(data): AuthInfo { const parts = data.split("$"); if (parts.length !== 4) { throw new StitchRedirectError( "invalid user auth data provided while " + "marshalling user authentication data: " + data ); } const [accessToken, refreshToken, userId, deviceId] = parts; return new AuthInfo(userId, deviceId, accessToken, refreshToken); } class ParsedRedirectFragment { public stateValid = false; public authInfo?: AuthInfo; public lastError?: string; public clientAppIdValid = false; public asLink = false; get isValid(): boolean { return this.stateValid && this.clientAppIdValid; } } function parseRedirectFragment( fragment, ourState, ourClientAppId ): ParsedRedirectFragment { /* * After being redirected from oauth, the URL will look like: * https://todo.examples.stitch.mongodb.com/#_stitch_state=...&_stitch_ua=... * This function parses out stitch-specific tokens from the fragment and * builds an object describing the result. */ const vars = fragment.split("&"); const result: ParsedRedirectFragment = new ParsedRedirectFragment(); vars.forEach(kvp => { const pairParts = kvp.split("="); const pairKey = decodeURIComponent(pairParts[0]); switch (pairKey) { case RedirectFragmentFields.StitchError: result.lastError = decodeURIComponent(pairParts[1]); break; case RedirectFragmentFields.UserAuth: try { result.authInfo = unmarshallUserAuth( decodeURIComponent(pairParts[1]) ); } catch (e) { result.lastError = e; } break; case RedirectFragmentFields.StitchLink: if (pairParts[1] === "ok") { result.asLink = true; } break; case RedirectFragmentFields.State: const theirState = decodeURIComponent(pairParts[1]); if (ourState === theirState) { result.stateValid = true; } break; case RedirectFragmentFields.ClientAppId: const clientAppId = decodeURIComponent(pairParts[1]); if (ourClientAppId === clientAppId) { result.clientAppIdValid = true; } break; default: break; } }); return result; } function isAuthProviderClientFactory<ClientT>( factory: | AuthProviderClientFactory<ClientT> | NamedAuthProviderClientFactory<ClientT> ): factory is AuthProviderClientFactory<ClientT> { return ( (factory as AuthProviderClientFactory<ClientT>).getClient !== undefined ); }
the_stack
import * as fs from 'fs'; import * as path from 'path'; import { W3 } from './W3'; // tslint:disable:max-line-length export module soltsice { export interface SoltsiceOptions { paths: string[]; cleanArtifacts: boolean; skipPattern: string; } // tslint:disable-next-line:typedef function parseArgs( args: SoltsiceOptions ): { source: string; destination: string; W3importPath: string; cleanArtifacts: boolean; skipPattern: string } { if (args.paths.length < 1 || args.paths.length > 3) { throw new Error('Wrong number of args'); } if (args.cleanArtifacts) { throw new Error('Cleaning artifacts is not supported yet'); } if (args.skipPattern) { throw new Error('Skip pattern is not supported yet'); } var options = { source: args.paths[0], destination: args.paths.length > 1 ? args.paths[1] : args.paths[0], W3importPath: args.paths.length > 2 ? args.paths[2] : 'soltsice', cleanArtifacts: args.cleanArtifacts, skipPattern: args.skipPattern }; console.log('Soltsice optoins: ', options); return options; } // tslint:disable-next-line:typedef export function generateTypes(args: SoltsiceOptions) { let options = parseArgs(args); let endOfLine = require('os').EOL; let destination = options.destination; if (!fs.existsSync(destination)) { fs.mkdirSync(destination); } let files = getSourceFiles(options.source); // console.log('FILES', files); let paths = getSourcePaths(options.source, files); // console.log('PATHS', paths); let targets = getDestinationPaths(options.destination, files); // console.log('TARGETS', targets); paths.forEach((file, idx) => { var ts = processFile(files[idx], file, targets[idx], options.W3importPath); console.log('Writing to ', targets[idx]); fs.writeFileSync(targets[idx], ts); }); // create index file let exports = files.map(f => `export * from './${f.replace('.json', '')}';`).join(endOfLine); fs.writeFileSync(path.join(destination, 'index.ts'), exports); } function getSourceFiles(src: string): string[] { let filesArr: string[] = fs.readdirSync(src).filter(f => f.endsWith('.json')); return filesArr; } function getSourcePaths(src: string, files: string[]): string[] { let filesArr = files.map(f => path.resolve(path.join(src, f))); // __dirname, filesArr.forEach(file => { // console.log(file); }); return filesArr; } function getDestinationPaths(destination: string, files: string[]): string[] { let filesArr = files .map(f => path.resolve(path.join(destination, f))) // __dirname, .map(f => f.replace('.json', '.ts')); return filesArr; } function abiTypeToTypeName(abiType?: string, isReturnType?: boolean) { let outputType: string[]; let arrayPosition = -1; if (!abiType) { outputType = ['void']; } else { arrayPosition = abiType.indexOf('['); if (arrayPosition >= 0) { abiType = abiType.substring(0, arrayPosition); } if (abiType.startsWith('uint') || abiType.startsWith('int')) { outputType = isReturnType ? ['BigNumber'] : ['BigNumber', 'number']; } else if (abiType.startsWith('bytes')) { outputType = ['string']; } else { // export type ABIDataTypes = 'uint256' | 'boolean' | 'string' | 'bytes' | string; // TODO complete list switch (abiType) { case 'bool': outputType = ['boolean']; break; case 'string': case 'address': outputType = ['string']; break; default: console.warn('Not implemented ABI type, using `any` instead: ', abiType); outputType = ['any']; } } } if (arrayPosition >= 0) { outputType = outputType.map(x => x + '[]'); } return outputType.join(' | '); } function processCtor(abi: W3.ABIDefinition): { typesNames: string; names: string } { let inputs = abi.inputs; let inputsString: string; let inputsNamesString: string; if (inputs && inputs.length > 0) { inputsString = inputs.map(i => i.name + ': ' + abiTypeToTypeName(i.type)).join(', '); inputsNamesString = inputs.map(i => 'ctorParams!.' + i.name).join(', '); } else { inputsString = ''; inputsNamesString = ''; } return { typesNames: inputsString, names: inputsNamesString }; } function processInputs(abi: W3.ABIDefinition): { typesNames: string; names: string } { let inputs = abi.inputs; let inputsString: string; let inputsNamesString: string; if (inputs && inputs.length > 0) { inputs = inputs.map((i, idx) => (i.name === '' ? Object.assign(i, { name: '_' + idx }) : i)); inputsString = inputs.map(i => i.name + ': ' + abiTypeToTypeName(i.type)).join(', '); // comma for tx params inputsNamesString = inputs.map(i => i.name).join(', '); } else { inputsString = ''; inputsNamesString = ''; } return { typesNames: inputsString, names: inputsNamesString }; } function processAbi(abi: W3.ABIDefinition): string { let name = abi.name; let isConstant = abi.constant; let inputs = processInputs(abi); let inputsString = inputs.typesNames; let inputsNamesString = inputs.names; let outputs = abi.outputs; let outputType: string; if (outputs && outputs.length > 1) { console.warn('Multiple output ABI not implemented, using `any` type for: ', abi); outputType = 'any'; } else { outputType = abiTypeToTypeName(outputs && outputs.length > 0 ? outputs[0].type : undefined, true); } let methodsBody: string = isConstant ? ` // tslint:disable-next-line:max-line-length // tslint:disable-next-line:variable-name public ${name}(${inputsString === '' ? '' : inputsString + ','} txParams?: W3.TX.TxParams): Promise<${outputType}> { return new Promise((resolve, reject) => { this._instance.${name} .call(${inputsNamesString === '' ? '' : inputsNamesString + ','} txParams || this._sendParams) .then((res: any) => resolve(res)) .catch((err: any) => reject(err)); }); } ` : ` // tslint:disable-next-line:member-ordering public ${name} = Object.assign( // tslint:disable-next-line:max-line-length // tslint:disable-next-line:variable-name (${ inputsString === '' ? '' : inputsString + ',' } txParams?: W3.TX.TxParams, privateKey?: string): Promise<W3.TX.TransactionResult> => { if (!privateKey) { return new Promise((resolve, reject) => { this._instance.${name}(${ inputsNamesString === '' ? '' : inputsNamesString + ',' } txParams || this._sendParams) .then((res: any) => resolve(res)) .catch((err: any) => reject(err)); }); } else { // tslint:disable-next-line:max-line-length return this.w3.sendSignedTransaction(this.address, privateKey, this._instance.${name}.request(${inputsNamesString}).params[0].data, txParams || this._sendParams, undefined) .then(txHash => { return this.waitTransactionReceipt(txHash); }); } }, { // tslint:disable-next-line:max-line-length // tslint:disable-next-line:variable-name sendTransaction: Object.assign((${ inputsString === '' ? '' : inputsString + ',' } txParams?: W3.TX.TxParams): Promise<string> => { return new Promise((resolve, reject) => { this._instance.${name}.sendTransaction(${ inputsNamesString === '' ? '' : inputsNamesString + ',' } txParams || this._sendParams) .then((res: any) => resolve(res)) .catch((err: any) => reject(err)); }); }, { // tslint:disable-next-line:max-line-length // tslint:disable-next-line:variable-name sendSigned: (${ inputsString === '' ? '' : inputsString + ',' } privateKey: string, txParams?: W3.TX.TxParams, nonce?: number): Promise<string> => { // tslint:disable-next-line:max-line-length return this.w3.sendSignedTransaction(this.address, privateKey, this._instance.${name}.request(${inputsNamesString}).params[0].data, txParams || this._sendParams, nonce); } } ) }, { // tslint:disable-next-line:max-line-length // tslint:disable-next-line:variable-name data: (${inputsString}): Promise<string> => { return new Promise((resolve, reject) => { resolve(this._instance.${name}.request(${inputsNamesString}).params[0].data); }); } }, { // tslint:disable-next-line:max-line-length // tslint:disable-next-line:variable-name estimateGas: (${inputsString}): Promise<number> => { return new Promise((resolve, reject) => { this._instance.${name}.estimateGas(${inputsNamesString}).then((g: any) => resolve(g)).catch((err: any) => reject(err)); }); } }); `; return methodsBody; } function processFile(fileName: string, filePath: string, targetPath: string, W3ImportPath: string): string { console.log('Processing ', filePath); let contract = JSON.parse(fs.readFileSync(filePath, { encoding: 'utf8' })); let importPath = W3ImportPath; let artifactRelPath = path.relative(path.dirname(targetPath), filePath).replace(/\\/g, '/'); // path.resolve(filePath).replace(/\\/g, '/'); // console.log('REL PATH ', artifactRelPath); let contractName: string = contract.contract_name || contract.contractName; if (!contractName) { throw new Error('Cannot find contract name in the artifact'); } let abis = contract.abi as W3.ABIDefinition[]; // When a contract is created, its constructor (a function declared with the constructor keyword) // is executed once. A constructor is optional. Only one constructor is allowed, and this means // overloading is not supported. let ctor = abis.filter(a => a.type === 'constructor'); let ctorParams = ctor.length === 1 ? processCtor(ctor[0]) : { typesNames: '', names: '' }; let names = abis.map(x => x.name); let methodsBody = abis .filter((value, index, self) => { // filter duplicate names and keep only the first one // order of filters matters because we use names arrays built from abis before the next 'function' filter return names.indexOf(value.name) === index; }) .filter(a => a.type === 'function') .map(processAbi) .join(''); let bnImport = ``; if (ctorParams.typesNames.indexOf('BigNumber') >= 0 || methodsBody.indexOf('BigNumber') >= 0) { bnImport = ` import { BigNumber } from 'bignumber.js';`; } // TODO let template: string = `${bnImport} import { W3, SoltsiceContract } from '${importPath}'; /** * ${contractName} API */ export class ${contractName} extends SoltsiceContract { public static get artifacts() { return require('${artifactRelPath}'); } public static get bytecodeHash() { // we need this before ctor, but artifacts are static and we cannot pass it to the base class, so need to generate let artifacts = ${contractName}.artifacts; if (!artifacts || !artifacts.bytecode) { return undefined; } let hash = W3.sha3(JSON.stringify(artifacts.bytecode)); return hash; } // tslint:disable-next-line:max-line-length public static async new(deploymentParams: W3.TX.TxParams, ctorParams?: {${ ctorParams.typesNames }}, w3?: W3, link?: SoltsiceContract[], privateKey?: string): Promise<${contractName}> { w3 = w3 || W3.default; if (!privateKey) { let contract = new ${contractName}(deploymentParams, ctorParams, w3, link); await contract._instancePromise; return contract; } else { let data = ${contractName}.newData(ctorParams, w3); let txHash = await w3.sendSignedTransaction(W3.zeroAddress, privateKey, data, deploymentParams); let txReceipt = await w3.waitTransactionReceipt(txHash); let rawAddress = txReceipt.contractAddress!; let contract = await ${contractName}.at(rawAddress, w3); return contract; } } public static async at(address: string | object, w3?: W3): Promise<${contractName}> { let contract = new ${contractName}(address, undefined, w3, undefined); await contract._instancePromise; return contract; } public static async deployed(w3?: W3): Promise<${contractName}> { let contract = new ${contractName}('', undefined, w3, undefined); await contract._instancePromise; return contract; } // tslint:disable-next-line:max-line-length public static newData(ctorParams?: {${ctorParams.typesNames}}, w3?: W3): string { // tslint:disable-next-line:max-line-length let data = SoltsiceContract.newDataImpl(w3, ${contractName}.artifacts, ctorParams ? [${ctorParams.names}] : []); return data; } protected constructor( deploymentParams: string | W3.TX.TxParams | object, ctorParams?: {${ctorParams.typesNames}}, w3?: W3, link?: SoltsiceContract[] ) { // tslint:disable-next-line:max-line-length super( w3, ${contractName}.artifacts, ctorParams ? [${ctorParams.names}] : [], deploymentParams, link ); } /* Contract methods */ ${methodsBody} } `; return template; } /** Create or get local key file and return private key and address. This is a blocking sync function for file read/write, therefore should be used during initial startup. */ export function getLocalPrivateKeyAndAddress(filepath: string, password: string): W3.Account { let address: string = ''; let privateKey: string = ''; let publicKey: string = ''; let keythereum = W3.getKeythereum(); let createNew = (): void => { let dk = keythereum.create(); privateKey = W3.EthUtils.bufferToHex(dk.privateKey); publicKey = W3.EthUtils.bufferToHex(W3.EthUtils.privateToPublic(dk.privateKey)); let addrBuffer = W3.EthUtils.privateToAddress(dk.privateKey); address = W3.EthUtils.bufferToHex(addrBuffer); let keyObject = keythereum.dump(password, dk.privateKey, dk.salt, dk.iv); fs.writeFileSync(filepath, JSON.stringify(keyObject), { encoding: 'ascii' }); }; if (fs.existsSync(filepath)) { let keyObject = JSON.parse(fs.readFileSync(filepath, { encoding: 'ascii' }).trim()); address = keyObject.address; let privateBuffer = keythereum.recover(password, keyObject); privateKey = W3.EthUtils.bufferToHex(privateBuffer); publicKey = W3.EthUtils.bufferToHex(W3.EthUtils.privateToPublic(privateBuffer)); } else { createNew(); } if (privateKey && !privateKey.startsWith('0x')) { privateKey = '0x' + privateKey; } if (publicKey && !publicKey.startsWith('0x')) { publicKey = '0x' + publicKey; } if (address && !address.startsWith('0x')) { address = '0x' + address; } return { privateKey, publicKey, address }; } }
the_stack
import { NS_FILE_ROOT_METADATA } from "@core/constant/ns.constant"; import { PLUGIN_SDK_EK_BATCH_META_UPDATE, PLUGIN_SDK_EK_DRAG_AND_DROPPED, PLUGIN_SDK_NS_UI_API, PLUGIN_SDK_EK_UI_RESIZE, PLUGIN_SDK_EK_UI_SHOW, PLUGIN_SDK_EK_UI_HIDE, PLUGIN_SDK_EK_UI_CLOSE, PLUGIN_SDK_EK_REQUEST_FETCH_NODE_MAIN_COMPONENT_META, PLUGIN_SDK_EK_REQUEST_FETCH_NODE_META, PLUGIN_SDK_EK_REQUEST_FETCH_ROOT_META, PLUGIN_SDK_EK_SIMPLE_NOTIFY, __PLUGIN_SDK_NAMESPACE_BASE_TOKEN, PLUGIN_SDK_NS_APP_REQUEST_CUSTOM_ALL, PLUGIN_SDK_NS_DRAG_AND_DROP, PLUGIN_SDK_NS_META_API, PLUGIN_SDK_NS_NOTIFY_API, PLUGIN_SDK_NS_REMOTE_API, PLUGIN_SDK_NS_RESPONSE_ALL, PLUGIN_SDK_NS_STORAGE, PLUGIN_SDK_NS_FOCUS_API, PUGIN_SDK_EK_REQUEST_UPDATE_MAIN_COMPONENT_META, PUGIN_SDK_EK_REQUEST_UPDATE_NODE_META, TransportPluginEvent, DragAndDropHandlerCallback, DragAndDropOnCanvasRequest, BatchMetaFetchRequest, BatchMetaUpdateRequest, NodeMetaFetchRequest, NodeMetaUpdateRequest, NotifyRequest, FocusRequest, PLUGIN_SDK_EK_SIMPLE_FOCUS, PLUGIN_SDK_NS_BROWSER_API, PLUGIN_SDK_EK_BROWSER_OPEN_URI, PLUGIN_SDK_EK_REQUEST_EXPORT_AS_IMAGE, PLUGIN_SDK_NS_EXPORT_AS_IMAGE, ImageExportResponse, _ImageExportOption_to_FigmaCompat, ImageExportRequest, PLUGIN_SDK_EK_REQUEST_GET_NODE_BY_ID, PLUGIN_SDK_NS_GET_NODE, TargetPlatform, target_platform, MetaRequest, makeExportSetting, UIControlRequest, } from "@plugin-sdk/core"; import { WebStorage, FigmaStorage, IStorage, LayerMetadataStorage, } from "./storage"; // TODO - make it universal import { Figma, figma } from "@design-sdk/figma"; import type { SceneNode } from "@design-sdk/figma"; import { StorageGetItemResponse, StorageRequest, } from "../plugin-sdk-core/interfaces/storage"; interface HanderProps<T = any> { id: string; key: string; data: T; } figma?.on("selectionchange", () => { PluginSdkService.onSelectionChange(); }); export class PluginSdkService { private static _appRequestHandlers: Map<string, (data) => void> = new Map(); // Todo - rename as invokeOnSelectionChange for no confusion static onSelectionChange() { const selection = figma.currentPage.selection; if (selection.length == 0) { // sync({ // namespace: PLUGIN_SDK_NS_SYNC, // key: // }); // deselect } else if (selection.length == 1) { // select single // sync(); } else if (selection.length >= 2) { // selections // sync(); } } private static dragAndDropHandlers = new Map< string, DragAndDropHandlerCallback >(); static registerDragAndDropHandler( key: string, handler: DragAndDropHandlerCallback ) { this.dragAndDropHandlers.set(key, handler); } static handleDragAndDropEvent(key: string, data: any, position: { x; y }) { if (!PluginSdkService.dragAndDropHandlers.has(key)) { throw `no handler found for event ${key} on drag and drop handler`; } PluginSdkService.dragAndDropHandlers.get(key)(data, position); } static handle(event: TransportPluginEvent): boolean { // logging // console.info( // `start handling event from PluginSdkServer with event - `, // event // ); // validate the givven event if (!event.namespace) { return; } if (event.namespace == "__INTERNAL__") { // console.log( // 'handling internal ivent with event ns - "__INTERNAL__"', // event // ); return handleInternalEvent(event); } if (!event.namespace.includes(__PLUGIN_SDK_NAMESPACE_BASE_TOKEN)) { console.warn( `the event is passed to PluginSdkServer, but the namespace or structure does not meet the standard interface. the givven event was - `, event ); return false; } const handerProps: HanderProps = { id: event.id, key: event.key, data: event.data, }; // meta if (event.namespace == PLUGIN_SDK_NS_META_API) { handleMetaEvent(handerProps); return true; } // image export else if (event.namespace == PLUGIN_SDK_NS_EXPORT_AS_IMAGE) { handleExportEvent(handerProps); } // get node else if (event.namespace == PLUGIN_SDK_NS_GET_NODE) { handleGetNodeEvent(handerProps); } // storage else if (event.namespace == PLUGIN_SDK_NS_STORAGE) { handleStorageEvent(handerProps); return true; } // browser api else if (event.namespace == PLUGIN_SDK_NS_BROWSER_API) { handleBrowserApiEvent(event); return true; } // // remote api call else if (event.namespace == PLUGIN_SDK_NS_REMOTE_API) { handleRemoteApiEvent(handerProps); return true; } // notify else if (event.namespace == PLUGIN_SDK_NS_NOTIFY_API) { handleNotify(handerProps); return true; } // ui api else if (event.namespace == PLUGIN_SDK_NS_UI_API) { handleUiApiEvent(event); return true; } // focus to target layer else if (event.namespace == PLUGIN_SDK_NS_FOCUS_API) { handleFocus(handerProps); return true; } // drag & drop else if (event.namespace == PLUGIN_SDK_NS_DRAG_AND_DROP) { if (PLUGIN_SDK_EK_DRAG_AND_DROPPED) { handleDragDropped(handerProps); } } else if (event.namespace == PLUGIN_SDK_NS_APP_REQUEST_CUSTOM_ALL) { this.invokeAppRequestHandler(event.key, event.data); } return true; } ////#region custom app request handling /** * this is a callback register method for code side thread. * when custom event or request raised from app side (via PluginSdk). * this listens to that event and transports to callback so custom handler can be registered easily. * this shall be called once on warmup, do not use this on runtime via logic gate since it has no unregister method. (intended this way) * @param key - a event key (namespace is not required) * @param callback */ static onAppReqquest<T>(key: string, callback: (data: T) => void) { console.log(`registering custom app event handler for key: ${key}.`); this._appRequestHandlers.set(key, callback); } private static invokeAppRequestHandler(key: string, data: any) { const handler = this._appRequestHandlers.get(key); if (handler) { handler(data); } else { console.warn( `custom app request with key ${key} was raised, but no handler was found. please add handler for ${key} with "PluginSdkService.onAppReqquest(${key}, callback)" or remove unused event` ); } } ////#endregion custom app request handling } function handleInternalEvent(event: HanderProps) { if (event.key == "sync-target-platform") { return response(event.id, __syncTargetPlatformForCodeThread(event.data)); } return response(event.id, true); } function handleMetaEvent(props: HanderProps<MetaRequest>) { if ( props.key == PLUGIN_SDK_EK_BATCH_META_UPDATE || props.key == PLUGIN_SDK_EK_REQUEST_FETCH_ROOT_META || props.key == PLUGIN_SDK_EK_REQUEST_FETCH_NODE_META || props.key == PUGIN_SDK_EK_REQUEST_UPDATE_NODE_META ) { const d = props.data; switch (d.type) { case "batch-meta-update-request": { new LayerMetadataStorage(figma.root.id, NS_FILE_ROOT_METADATA).setItem( d.key, d.value ); figma.notify("metadata updated", { timeout: 1 }); return response(props.id, true); } case "batch-meta-fetch-request": { const fetched = new LayerMetadataStorage( figma.root.id, NS_FILE_ROOT_METADATA ).getItem(d.key); return response(props.id, fetched); } case "node-meta-fetch-request": { if (!d.id) { throw `node id is required in order to perform meta fetch`; } const fetched = new LayerMetadataStorage( figma.root.id, d.namespace ).getItem(d.key); return response(props.id, fetched); } case "node-meta-update-request": { new LayerMetadataStorage(figma.root.id, d.namespace).setItem( d.key, d.value ); return response(props.id, true); } } } // if (props.key == PLUGIN_SDK_EK_REQUEST_FETCH_NODE_MAIN_COMPONENT_META) { // const request: NodeMetaFetchRequest = props.data; // let targetNode: Figma.SceneNode = getMaincomponentLike(request.id); // const data = targetNode.getSharedPluginData(request.namespace, request.key); // const normData = decode(data); // return response(props.id, normData); // } else if (props.key == PUGIN_SDK_EK_REQUEST_UPDATE_MAIN_COMPONENT_META) { // const request: NodeMetaUpdateRequest = props.data; // let targetNode: Figma.SceneNode = getMaincomponentLike(request?.id); // targetNode.setSharedPluginData( // request.namespace, // request.key, // encode(request.value) // ); // return response(props.id, true); // // // } } function handleRemoteApiEvent(props: HanderProps) { throw "not implemented"; } function handleNotify(props: HanderProps<NotifyRequest>) { if (props.key == PLUGIN_SDK_EK_SIMPLE_NOTIFY) { switch (target_platform.get()) { case TargetPlatform.webdev: { alert(props.data.message); } case TargetPlatform.figma: { figma?.notify(props.data.message, { timeout: props.data.duration ?? 1, }); } } } response(props.id, true); } function handleUiApiEvent(props: HanderProps<UIControlRequest>) { switch (target_platform.get()) { case TargetPlatform.webdev: { break; // not handled } case TargetPlatform.figma: { switch (props.data.type) { case PLUGIN_SDK_EK_UI_CLOSE: { figma?.ui.close(); break; } case PLUGIN_SDK_EK_UI_SHOW: { figma?.ui.show(); break; } case PLUGIN_SDK_EK_UI_HIDE: { figma?.ui.hide(); break; } case PLUGIN_SDK_EK_UI_RESIZE: { figma?.ui.resize(props.data.size.width, props.data.size.height); break; } } } } response(props.id, true); } function handleGetNodeEvent(props: HanderProps<{ id: string }>) { if (props.key == PLUGIN_SDK_EK_REQUEST_GET_NODE_BY_ID) { switch (target_platform.get()) { case TargetPlatform.webdev: { } case TargetPlatform.figma: { const node = figma?.getNodeById(props.data.id) as SceneNode; response(props.id, { id: node?.id, name: node?.name, x: node?.x, y: node?.y, width: node?.width, height: node?.height, ...node, }); } } } } function handleFocus(props: HanderProps<FocusRequest>) { if (props.key == PLUGIN_SDK_EK_SIMPLE_FOCUS) { switch (target_platform.get()) { case TargetPlatform.webdev: { // none console.log("mock focus event from webdev", props); } case TargetPlatform.figma: { const target = figma.getNodeById(props.data.target) as SceneNode; //@ts-ignore TODO: remove ts-ignore figma.currentPage.selection = [target]; // TODO: add zoom usage //@ts-ignore figma.viewport.scrollAndZoomIntoView([target]); } } } } async function handleExportEvent(event: HanderProps<ImageExportRequest>) { if (event.key === PLUGIN_SDK_EK_REQUEST_EXPORT_AS_IMAGE) { switch (target_platform.get()) { case TargetPlatform.webdev: { console.log( "webdev cannot perform image export request. ignoring this." ); return undefined; } case TargetPlatform.figma: { const r = await (figma.getNodeById( event.data.id ) as SceneNode).exportAsync({ ...makeExportSetting(event.data.opt), }); return response<ImageExportResponse>(event.id, { id: event.data.id, data: r, opt: event.data.opt, }); } } } } async function handleStorageEvent(props: HanderProps<StorageRequest>) { const _get_dedicated_storage = (): IStorage => { switch (target_platform.get()) { case TargetPlatform.webdev: { return new WebStorage(); } case TargetPlatform.figma: { return new FigmaStorage(); } } }; const _storage = _get_dedicated_storage(); switch (props.data.type) { case "get-item": const d = await _storage.getItem(props.data.key); response<StorageGetItemResponse>(props.id, { value: d }); break; case "set-item": await _storage.setItem(props.data.key, props.data.value); response(props.id, true); // setting data to storage does not require response data payload (using `true`.). break; } } async function handleBrowserApiEvent(props: TransportPluginEvent) { if (props.key == PLUGIN_SDK_EK_BROWSER_OPEN_URI) { requestToHost(props); } } function handleDragDropped(props: HanderProps<DragAndDropOnCanvasRequest>) { console.log("handling drop event", props.data); const { dropPosition, windowSize, offset, itemSize, eventKey, customData, } = props.data; // Getting the position and size of the visible area of the canvas. const bounds = figma.viewport.bounds; // Getting the zoom level const zoom = figma.viewport.zoom; // There are two states of the Figma interface: With or without the UI (toolbar + left and right panes) // The calculations would be slightly different, depending on whether the UI is shown. // So to determine if the UI is shown, we'll be comparing the bounds to the window's width. // Math.round is used here because sometimes bounds.width * zoom may return a floating point number very close but not exactly the window width. // This also applies when chrome developer tool is open on thr right side (not floating). currently, we cannot handle this issue. (PLEASE NOTE THAT YOU'LL NEED TO USE FLOATING DEVELOPER TOOLS WHEN DEVELOPING DnD!) const hasUI = Math.round(bounds.width * zoom) !== windowSize.width; // Since the left pane is resizable, we need to get its width by subtracting the right pane and the canvas width from the window width. const leftPaneWidth = windowSize.width - bounds.width * zoom - 240; // Getting the position of the cursor relative to the top-left corner of the canvas. const xFromCanvas = hasUI ? dropPosition.clientX - leftPaneWidth : dropPosition.clientX; const yFromCanvas = hasUI ? dropPosition.clientY - 40 : dropPosition.clientY; // The canvas position of the drop point can be calculated using the following: const x = bounds.x + xFromCanvas / zoom - offset.x; const y = bounds.y + yFromCanvas / zoom - offset.y; PluginSdkService.handleDragAndDropEvent(eventKey, customData, { x: x, y: y }); } /// /// -------------------------- footer response section ---------------------------- /// function response<T = any>( requestId: string, data: T, error: Error | undefined = undefined ): boolean { if (process.env.NODE_ENV == "development" && process.env.VERBOSE) { console.info( `${target_platform.get()}>> responding to request ${requestId} with data ${JSON.stringify( data )} and ${error ? "" + error : "no error"}` ); } const msg = <TransportPluginEvent>{ id: requestId, namespace: PLUGIN_SDK_NS_RESPONSE_ALL, type: "response", error: error, data: data, }; switch (target_platform.get()) { case TargetPlatform.webdev: { window.postMessage({ pluginMessage: msg }, undefined); break; } case TargetPlatform.figma: { figma.ui.postMessage(msg); break; } } return true; } /** this is used to proxy a request from inner iframe to host iframe. */ function requestToHost(req) { console.log("requesting host to handle requests from hosted app.", req); switch (target_platform.get()) { case TargetPlatform.webdev: { window.postMessage( { pluginMessage: { __proxy_request_from_hosted_plugin: true, ...req } }, undefined ); break; } case TargetPlatform.figma: { figma.ui.postMessage({ __proxy_request_from_hosted_plugin: true, ...req, }); break; } } } export function __syncTargetPlatformForCodeThread( platform: TargetPlatform ): boolean { // console.info(`thread#code: syncing target platform to ${platform}`); target_platform.set(platform); return true; } /** * this is for syncing data with PluginApp's general data such as currently selected node. * @param withEvent */ function sync(withEvent: TransportPluginEvent) {}
the_stack
import { useRecords } from "beneath-react"; import _ from "lodash"; import { Button, Chip, Grid, makeStyles, Theme, Tooltip, Typography } from "@material-ui/core"; import ArrowDownwardIcon from "@material-ui/icons/ArrowDownward"; import FiberManualRecordIcon from "@material-ui/icons/FiberManualRecord"; import { ToggleButton, ToggleButtonGroup } from "@material-ui/lab"; import { useRouter } from "next/router"; import React, { FC, useEffect, useState } from "react"; import { useToken } from "../../hooks/useToken"; import RecordsView from "./RecordsView"; import { Schema } from "./schema"; import WriteTable from "./WriteTable"; import FilterForm from "./FilterForm"; import { NakedLink } from "components/Link"; import VSpace from "components/VSpace"; import clsx from "clsx"; import { TableInstance } from "components/table/types"; import ContentContainer, { CallToAction } from "components/ContentContainer"; import { TableInstanceByOrganizationProjectTableAndVersion_tableInstanceByOrganizationProjectTableAndVersion_table } from "apollo/types/TableInstanceByOrganizationProjectTableAndVersion"; import { makeTableAs, makeTableHref } from "./urls"; interface DataTabProps { table: TableInstanceByOrganizationProjectTableAndVersion_tableInstanceByOrganizationProjectTableAndVersion_table; instance: TableInstance | null; } const useStyles = makeStyles((theme: Theme) => ({ topRowHeight: { height: "28px", padding: "0 9px", }, toggleButton: { width: "100px", }, toggleButtonLabel: { display: "block", width: "100%", }, liveIcon: { color: theme.palette.success.light, }, pausedIcon: { color: theme.palette.grey[500], }, infoCaption: { color: theme.palette.text.disabled, }, errorCaption: { color: theme.palette.error.main, }, safariButtonFix: { whiteSpace: "nowrap", }, })); const DataTab: FC<DataTabProps> = ({ table, instance }) => { if (!instance) { const cta: CallToAction = { message: `Please select a table version`, }; return ( <> <ContentContainer callToAction={cta} /> </> ); } const NO_FILTER = {}; // determine if table may have more data incoming const finalized = !!instance.madeFinalOn; // state const [logPeek, setLogPeek] = useState(finalized ? false : true); const [subscribeToggle, setSubscribeToggle] = React.useState(true); // updated by the LIVE/PAUSED toggle (used in call to useRecords) // optimization: initializing a schema is expensive, so we keep it as state and reload it if table changes const [schema, setSchema] = useState(() => new Schema(table.avroSchema, table.tableIndexes)); useEffect(() => { setSchema(new Schema(table.avroSchema, table.tableIndexes)); }, [table.tableID]); const router = useRouter(); const [filter, setFilter] = useState<any>(() => { // checks to see if a filter was provided in the URL if (typeof router.query.filter !== "string") return NO_FILTER; // attempts to parse JSON let filter: any; try { filter = JSON.parse(router.query.filter); } catch { return NO_FILTER; } // checks that the filter's keys are in the table's index const keys = Object.keys(filter); const index = schema.columns.filter((col) => col.isKey); for (const key of keys) { const col = index.find((col) => col.name === key); if (typeof col === "undefined") return NO_FILTER; } // if query submitted in form {"key": "value"}, convert it to form {"key": {"_eq": "value"}} for (const key of keys) { const val = filter[key]; if (typeof val !== "object") { filter[key] = { _eq: val }; } } return filter; }); const [queryType, setQueryType] = useState<"log" | "index">(finalized || !_.isEmpty(filter) ? "index" : "log"); // get records const token = useToken(); const { records, error, loading, fetchMore, fetchMoreChanges, subscription, truncation } = useRecords({ secret: token || undefined, table: { instanceID: instance?.tableInstanceID, }, query: queryType === "index" ? { type: "index", filter: _.isEmpty(filter) ? undefined : JSON.stringify(filter) } : { type: "log", peek: logPeek }, pageSize: 25, subscribe: isSubscribed(finalized, subscribeToggle) ? { pageSize: 100, pollFrequencyMs: 250, } : false, renderFrequencyMs: 250, maxRecords: 1000, flashDurationMs: 2000, }); const classes = useStyles(); // set filter in URL useEffect(() => { let href = makeTableHref(table, instance); let as = makeTableAs(table, instance); if (queryType === "index") { const filterJSON = JSON.stringify(filter); const noFilterJSON = JSON.stringify(NO_FILTER); href = href + (filterJSON !== noFilterJSON ? `&filter=${encodeURIComponent(filterJSON)}` : ""); as = as + (filterJSON !== noFilterJSON ? `?filter=${encodeURIComponent(filterJSON)}` : ""); } router.replace(href, as); }, [JSON.stringify(filter), queryType]); // CTAs let containerCta: CallToAction | undefined; if (!fetchMore && fetchMoreChanges) { containerCta = { buttons: [{ label: "Fetch more changes", onClick: () => fetchMoreChanges() }], }; } let recordsCta: CallToAction | undefined; if (!loading && _.isEmpty(filter) && records.length === 0) { recordsCta = { message: `There's no data in this table instance`, }; if (table.project.permissions.create && !table.meta) { recordsCta.buttons = [ { label: "Go to API docs", href: makeTableHref(table, instance, "api"), as: makeTableAs(table, instance, "api"), }, ]; } } if (!loading && queryType === "index" && !_.isEmpty(filter) && records.length === 0) { recordsCta = { message: `Found no rows that match the filter`, }; } // NOTES let note: string | undefined; if (truncation.end) { note = "We removed some records from the bottom to fit new records in the table"; } // Messages at the top of the records view use this component const Message: FC<{ children: string; error?: boolean }> = ({ error, children }) => ( <Typography className={error ? classes.errorCaption : classes.infoCaption} variant="body2" align="center"> {children} </Typography> ); return ( <> <ContentContainer callToAction={containerCta}> {/* top-row buttons */} <Grid container spacing={1} alignItems="center"> <Grid item> <ToggleButtonGroup exclusive size="small" value={queryType} onChange={(_, value: "log" | "index" | null) => { if (value !== null) setQueryType(value); }} > <ToggleButton value="log" className={clsx(classes.topRowHeight, classes.toggleButton)}> <Tooltip title="Sort the table by the time of each write"> <span className={classes.toggleButtonLabel}>Log</span> </Tooltip> </ToggleButton> <ToggleButton value="index" className={clsx(classes.topRowHeight, classes.toggleButton)}> <Tooltip title="Query the table by the key fields"> <span className={classes.toggleButtonLabel}>Index</span> </Tooltip> </ToggleButton> </ToggleButtonGroup> </Grid> <Grid item> {isSubscribed(finalized, subscribeToggle) && ( <Chip label="Live" variant="outlined" size="small" clickable onClick={() => setSubscribeToggle(false)} icon={<FiberManualRecordIcon className={classes.liveIcon} />} className={classes.topRowHeight} /> )} {!isSubscribed(finalized, subscribeToggle) && ( <Chip label="Paused" variant="outlined" size="small" clickable={isSubscribeable(finalized) ? true : false} onClick={() => { if (isSubscribeable(finalized)) { setSubscribeToggle(true); } return; }} icon={<FiberManualRecordIcon className={classes.pausedIcon} />} className={classes.topRowHeight} /> )} </Grid> {queryType === "log" && ( <Grid item> {logPeek && ( <Button variant="outlined" onClick={() => setLogPeek(!logPeek)} size="small" startIcon={<ArrowDownwardIcon />} className={classes.topRowHeight} > Newest to oldest </Button> )} {!logPeek && ( <Button variant="outlined" onClick={() => setLogPeek(!logPeek)} size="small" startIcon={<ArrowDownwardIcon />} className={classes.topRowHeight} > Oldest to newest </Button> )} </Grid> )} {queryType === "index" && ( <FilterForm filter={filter} index={schema.columns.filter((col) => col.isKey)} onChange={(filter: any) => setFilter({ ...filter })} /> )} <Grid item xs> <Grid container spacing={1} justify="flex-end" wrap="nowrap"> {table.project.permissions.create && table.allowManualWrites && !table.meta && ( <Grid item> <WriteTable table={table} instanceID={instance.tableInstanceID} buttonClassName={clsx(classes.topRowHeight, classes.safariButtonFix)} /> </Grid> )} <Grid item> <Button variant="outlined" component={NakedLink} href={`/-/sql?table=${table.project.organization.name}/${table.project.name}/${table.name}`} as={`/-/sql`} size="small" classes={{ root: clsx(classes.topRowHeight, classes.safariButtonFix) }} disabled={!table.useWarehouse} > Query with SQL </Button> </Grid> </Grid> </Grid> </Grid> {/* records view */} <VSpace units={3} /> {truncation.start && <Message>You loaded so many more rows that we had to remove some from the top</Message>} {subscription.error && <Message error={true}>{subscription.error.message}</Message>} <RecordsView paper schema={schema} records={records} fetchMore={fetchMore} showTimestamps={queryType === "log"} callToAction={recordsCta} error={error?.message} note={note} loading={loading} /> </ContentContainer> </> ); }; export default DataTab; const isSubscribeable = (finalized: boolean) => { if (typeof window === "undefined" || finalized) { return false; } else { return true; } }; const isSubscribed = (finalized: boolean, subscribeToggle: boolean) => { return isSubscribeable(finalized) ? subscribeToggle : false; };
the_stack
import { $BuiltinFunction, $Function, $OrdinaryCreateFromConstructor, } from '../types/function.js'; import { Realm, ExecutionContext, } from '../realm.js'; import { $AnyNonEmpty, CompletionType, $AnyNonEmptyNonError, } from '../types/_shared.js'; import { $TypeError, } from '../types/error.js'; import { $Undefined, } from '../types/undefined.js'; import { $FunctionPrototype, } from './function.js'; import { $Object, } from '../types/object.js'; import { $ObjectPrototype, } from './object.js'; import { $PropertyDescriptor, } from '../types/property-descriptor.js'; import { $DefinePropertyOrThrow, } from '../operations.js'; import { $String, } from '../types/string.js'; import { $List } from '../types/list.js'; // http://www.ecma-international.org/ecma-262/#sec-error-constructor export class $ErrorConstructor extends $BuiltinFunction<'%Error%'> { public get $prototype(): $ErrorPrototype { return this.getProperty(this.realm['[[Intrinsics]]'].$prototype)['[[Value]]'] as $ErrorPrototype; } public set $prototype(value: $ErrorPrototype) { this.setDataProperty(this.realm['[[Intrinsics]]'].$prototype, value, false, false, false); } public constructor( realm: Realm, functionPrototype: $FunctionPrototype, ) { super(realm, '%Error%', functionPrototype); } // http://www.ecma-international.org/ecma-262/#sec-error-message // 19.5.1.1 Error ( message ) public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, [message]: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // 1. If NewTarget is undefined, let newTarget be the active function object, else let newTarget be NewTarget. const newTarget = NewTarget.isUndefined ? ctx.Function : NewTarget; // 2. Let O be ? OrdinaryCreateFromConstructor(newTarget, "%ErrorPrototype%", « [[ErrorData]] »). const O = $OrdinaryCreateFromConstructor(ctx, newTarget as $Function, '%ErrorPrototype%', { '[[ErrorData]]': void 0 }); if (O.isAbrupt) { return O; } // 3. If message is not undefined, then if (message !== void 0) { // 3. a. Let msg be ? ToString(message). const msg = message.ToString(ctx); if (msg.isAbrupt) { return msg; } // 3. b. Let msgDesc be the PropertyDescriptor { [[Value]]: msg, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }. const msgDesc = new $PropertyDescriptor( realm, intrinsics.message, { '[[Value]]': msg, '[[Writable]]': intrinsics.true, '[[Enumerable]]': intrinsics.false, '[[Configurable]]': intrinsics.true, }, ); // 3. c. Perform ! DefinePropertyOrThrow(O, "message", msgDesc). $DefinePropertyOrThrow(ctx, O, intrinsics.message, msgDesc); } // 4. Return O. return O; } } // http://www.ecma-international.org/ecma-262/#sec-properties-of-the-error-prototype-object export class $ErrorPrototype extends $Object<'%ErrorPrototype%'> { public get $constructor(): $ErrorConstructor { return this.getProperty(this.realm['[[Intrinsics]]'].$constructor)['[[Value]]'] as $ErrorConstructor; } public set $constructor(value: $ErrorConstructor) { this.setDataProperty(this.realm['[[Intrinsics]]'].$constructor, value); } public get message(): $String { return this.getProperty(this.realm['[[Intrinsics]]'].message)['[[Value]]'] as $String; } public set message(value: $String) { this.setDataProperty(this.realm['[[Intrinsics]]'].message, value); } public get $name(): $String { return this.getProperty(this.realm['[[Intrinsics]]'].$name)['[[Value]]'] as $String; } public set $name(value: $String) { this.setDataProperty(this.realm['[[Intrinsics]]'].$name, value); } public get $toString(): $ErrorPrototype_toString { return this.getProperty(this.realm['[[Intrinsics]]'].$name)['[[Value]]'] as $ErrorPrototype_toString; } public set $toString(value: $ErrorPrototype_toString) { this.setDataProperty(this.realm['[[Intrinsics]]'].$name, value); } public constructor( realm: Realm, objectPrototype: $ObjectPrototype, ) { const intrinsics = realm['[[Intrinsics]]']; super(realm, '%ErrorPrototype%', objectPrototype, CompletionType.normal, intrinsics.empty); } } // http://www.ecma-international.org/ecma-262/#sec-error.prototype.tostring export class $ErrorPrototype_toString extends $BuiltinFunction<'Error.prototype.toString'> { public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, argumentsList: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // 1. Let O be the this value. const O = thisArgument; // 2. If Type(O) is not Object, throw a TypeError exception. if (!O.isObject) { return new $TypeError(realm, `Error.prototype.toString called on ${O}, but expected an object`); } // 3. Let name be ? Get(O, "name"). let name = O['[[Get]]'](ctx, intrinsics.$name, O); if (name.isAbrupt) { return name; } // 4. If name is undefined, set name to "Error"; otherwise set name to ? ToString(name). if (name.isUndefined) { name = new $String(realm, 'Error'); } else { name = name.ToString(ctx); if (name.isAbrupt) { return name; } } // 5. Let msg be ? Get(O, "message"). let msg = O['[[Get]]'](ctx, intrinsics.message, O); if (msg.isAbrupt) { return msg; } // 6. If msg is undefined, set msg to the empty String; otherwise set msg to ? ToString(msg). if (msg.isUndefined) { msg = new $String(realm, ''); } else { msg = msg.ToString(ctx); if (msg.isAbrupt) { return msg; } } // 7. If name is the empty String, return msg. if (name['[[Value]]'] === '') { return msg; } // 8. If msg is the empty String, return name. if (msg['[[Value]]'] === '') { return name; } // 9. Return the string-concatenation of name, the code unit 0x003A (COLON), the code unit 0x0020 (SPACE), and msg. return new $String(realm, `${name['[[Value]]']}: ${msg['[[Value]]']}`); } } // http://www.ecma-international.org/ecma-262/#sec-nativeerror-constructors export class $EvalErrorConstructor extends $BuiltinFunction<'%EvalError%'> { public get $prototype(): $EvalErrorPrototype { return this.getProperty(this.realm['[[Intrinsics]]'].$prototype)['[[Value]]'] as $EvalErrorPrototype; } public set $prototype(value: $EvalErrorPrototype) { this.setDataProperty(this.realm['[[Intrinsics]]'].$prototype, value, false, false, false); } public constructor( realm: Realm, errorConstructor: $ErrorConstructor, ) { super(realm, '%EvalError%', errorConstructor); } // http://www.ecma-international.org/ecma-262/#sec-nativeerror // 19.5.6.1.1 NativeError ( message ) public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, [message]: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // 1. If NewTarget is undefined, let newTarget be the active function object, else let newTarget be NewTarget. const newTarget = NewTarget.isUndefined ? ctx.Function : NewTarget; // 2. Let O be ? OrdinaryCreateFromConstructor(newTarget, "%EvalErrorPrototype%", « [[ErrorData]] »). const O = $OrdinaryCreateFromConstructor(ctx, newTarget as $Function, '%EvalErrorPrototype%', { '[[ErrorData]]': void 0 }); if (O.isAbrupt) { return O; } // 3. If message is not undefined, then if (message !== void 0) { // 3. a. Let msg be ? ToString(message). const msg = message.ToString(ctx); if (msg.isAbrupt) { return msg; } // 3. b. Let msgDesc be the PropertyDescriptor { [[Value]]: msg, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }. const msgDesc = new $PropertyDescriptor( realm, intrinsics.message, { '[[Value]]': msg, '[[Writable]]': intrinsics.true, '[[Enumerable]]': intrinsics.false, '[[Configurable]]': intrinsics.true, }, ); // 3. c. Perform ! DefinePropertyOrThrow(O, "message", msgDesc). $DefinePropertyOrThrow(ctx, O, intrinsics.message, msgDesc); } // 4. Return O. return O; } } // http://www.ecma-international.org/ecma-262/#sec-properties-of-the-nativeerror-prototype-objects export class $EvalErrorPrototype extends $Object<'%EvalErrorPrototype%'> { public get $constructor(): $EvalErrorConstructor { return this.getProperty(this.realm['[[Intrinsics]]'].$constructor)['[[Value]]'] as $EvalErrorConstructor; } public set $constructor(value: $EvalErrorConstructor) { this.setDataProperty(this.realm['[[Intrinsics]]'].$constructor, value); } public get message(): $String { return this.getProperty(this.realm['[[Intrinsics]]'].message)['[[Value]]'] as $String; } public set message(value: $String) { this.setDataProperty(this.realm['[[Intrinsics]]'].message, value); } public get $name(): $String { return this.getProperty(this.realm['[[Intrinsics]]'].$name)['[[Value]]'] as $String; } public set $name(value: $String) { this.setDataProperty(this.realm['[[Intrinsics]]'].$name, value); } public constructor( realm: Realm, errorPrototype: $ErrorPrototype, ) { const intrinsics = realm['[[Intrinsics]]']; super(realm, '%EvalErrorPrototype%', errorPrototype, CompletionType.normal, intrinsics.empty); } } // http://www.ecma-international.org/ecma-262/#sec-nativeerror-constructors export class $RangeErrorConstructor extends $BuiltinFunction<'%RangeError%'> { public get $prototype(): $RangeErrorPrototype { return this.getProperty(this.realm['[[Intrinsics]]'].$prototype)['[[Value]]'] as $RangeErrorPrototype; } public set $prototype(value: $RangeErrorPrototype) { this.setDataProperty(this.realm['[[Intrinsics]]'].$prototype, value, false, false, false); } public constructor( realm: Realm, errorConstructor: $ErrorConstructor, ) { super(realm, '%RangeError%', errorConstructor); } // http://www.ecma-international.org/ecma-262/#sec-nativeerror // 19.5.6.1.1 NativeError ( message ) public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, [message]: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // 1. If NewTarget is undefined, let newTarget be the active function object, else let newTarget be NewTarget. const newTarget = NewTarget.isUndefined ? ctx.Function : NewTarget; // 2. Let O be ? OrdinaryCreateFromConstructor(newTarget, "%RangeErrorPrototype%", « [[ErrorData]] »). const O = $OrdinaryCreateFromConstructor(ctx, newTarget as $Function, '%RangeErrorPrototype%', { '[[ErrorData]]': void 0 }); if (O.isAbrupt) { return O; } // 3. If message is not undefined, then if (message !== void 0) { // 3. a. Let msg be ? ToString(message). const msg = message.ToString(ctx); if (msg.isAbrupt) { return msg; } // 3. b. Let msgDesc be the PropertyDescriptor { [[Value]]: msg, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }. const msgDesc = new $PropertyDescriptor( realm, intrinsics.message, { '[[Value]]': msg, '[[Writable]]': intrinsics.true, '[[Enumerable]]': intrinsics.false, '[[Configurable]]': intrinsics.true, }, ); // 3. c. Perform ! DefinePropertyOrThrow(O, "message", msgDesc). $DefinePropertyOrThrow(ctx, O, intrinsics.message, msgDesc); } // 4. Return O. return O; } } // http://www.ecma-international.org/ecma-262/#sec-properties-of-the-nativeerror-prototype-objects export class $RangeErrorPrototype extends $Object<'%RangeErrorPrototype%'> { public get $constructor(): $RangeErrorConstructor { return this.getProperty(this.realm['[[Intrinsics]]'].$constructor)['[[Value]]'] as $RangeErrorConstructor; } public set $constructor(value: $RangeErrorConstructor) { this.setDataProperty(this.realm['[[Intrinsics]]'].$constructor, value); } public get message(): $String { return this.getProperty(this.realm['[[Intrinsics]]'].message)['[[Value]]'] as $String; } public set message(value: $String) { this.setDataProperty(this.realm['[[Intrinsics]]'].message, value); } public get $name(): $String { return this.getProperty(this.realm['[[Intrinsics]]'].$name)['[[Value]]'] as $String; } public set $name(value: $String) { this.setDataProperty(this.realm['[[Intrinsics]]'].$name, value); } public constructor( realm: Realm, errorPrototype: $ErrorPrototype, ) { const intrinsics = realm['[[Intrinsics]]']; super(realm, '%RangeErrorPrototype%', errorPrototype, CompletionType.normal, intrinsics.empty); } } // http://www.ecma-international.org/ecma-262/#sec-nativeerror-constructors export class $ReferenceErrorConstructor extends $BuiltinFunction<'%ReferenceError%'> { public get $prototype(): $ReferenceErrorPrototype { return this.getProperty(this.realm['[[Intrinsics]]'].$prototype)['[[Value]]'] as $ReferenceErrorPrototype; } public set $prototype(value: $ReferenceErrorPrototype) { this.setDataProperty(this.realm['[[Intrinsics]]'].$prototype, value, false, false, false); } public constructor( realm: Realm, errorConstructor: $ErrorConstructor, ) { super(realm, '%ReferenceError%', errorConstructor); } // http://www.ecma-international.org/ecma-262/#sec-nativeerror // 19.5.6.1.1 NativeError ( message ) public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, [message]: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // 1. If NewTarget is undefined, let newTarget be the active function object, else let newTarget be NewTarget. const newTarget = NewTarget.isUndefined ? ctx.Function : NewTarget; // 2. Let O be ? OrdinaryCreateFromConstructor(newTarget, "%ReferenceErrorPrototype%", « [[ErrorData]] »). const O = $OrdinaryCreateFromConstructor(ctx, newTarget as $Function, '%ReferenceErrorPrototype%', { '[[ErrorData]]': void 0 }); if (O.isAbrupt) { return O; } // 3. If message is not undefined, then if (message !== void 0) { // 3. a. Let msg be ? ToString(message). const msg = message.ToString(ctx); if (msg.isAbrupt) { return msg; } // 3. b. Let msgDesc be the PropertyDescriptor { [[Value]]: msg, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }. const msgDesc = new $PropertyDescriptor( realm, intrinsics.message, { '[[Value]]': msg, '[[Writable]]': intrinsics.true, '[[Enumerable]]': intrinsics.false, '[[Configurable]]': intrinsics.true, }, ); // 3. c. Perform ! DefinePropertyOrThrow(O, "message", msgDesc). $DefinePropertyOrThrow(ctx, O, intrinsics.message, msgDesc); } // 4. Return O. return O; } } // http://www.ecma-international.org/ecma-262/#sec-properties-of-the-nativeerror-prototype-objects export class $ReferenceErrorPrototype extends $Object<'%ReferenceErrorPrototype%'> { public get $constructor(): $ReferenceErrorConstructor { return this.getProperty(this.realm['[[Intrinsics]]'].$constructor)['[[Value]]'] as $ReferenceErrorConstructor; } public set $constructor(value: $ReferenceErrorConstructor) { this.setDataProperty(this.realm['[[Intrinsics]]'].$constructor, value); } public get message(): $String { return this.getProperty(this.realm['[[Intrinsics]]'].message)['[[Value]]'] as $String; } public set message(value: $String) { this.setDataProperty(this.realm['[[Intrinsics]]'].message, value); } public get $name(): $String { return this.getProperty(this.realm['[[Intrinsics]]'].$name)['[[Value]]'] as $String; } public set $name(value: $String) { this.setDataProperty(this.realm['[[Intrinsics]]'].$name, value); } public constructor( realm: Realm, errorPrototype: $ErrorPrototype, ) { const intrinsics = realm['[[Intrinsics]]']; super(realm, '%ReferenceErrorPrototype%', errorPrototype, CompletionType.normal, intrinsics.empty); } } // http://www.ecma-international.org/ecma-262/#sec-nativeerror-constructors export class $SyntaxErrorConstructor extends $BuiltinFunction<'%SyntaxError%'> { public get $prototype(): $SyntaxErrorPrototype { return this.getProperty(this.realm['[[Intrinsics]]'].$prototype)['[[Value]]'] as $SyntaxErrorPrototype; } public set $prototype(value: $SyntaxErrorPrototype) { this.setDataProperty(this.realm['[[Intrinsics]]'].$prototype, value, false, false, false); } public constructor( realm: Realm, errorConstructor: $ErrorConstructor, ) { super(realm, '%SyntaxError%', errorConstructor); } // http://www.ecma-international.org/ecma-262/#sec-nativeerror // 19.5.6.1.1 NativeError ( message ) public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, [message]: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // 1. If NewTarget is undefined, let newTarget be the active function object, else let newTarget be NewTarget. const newTarget = NewTarget.isUndefined ? ctx.Function : NewTarget; // 2. Let O be ? OrdinaryCreateFromConstructor(newTarget, "%SyntaxErrorPrototype%", « [[ErrorData]] »). const O = $OrdinaryCreateFromConstructor(ctx, newTarget as $Function, '%SyntaxErrorPrototype%', { '[[ErrorData]]': void 0 }); if (O.isAbrupt) { return O; } // 3. If message is not undefined, then if (message !== void 0) { // 3. a. Let msg be ? ToString(message). const msg = message.ToString(ctx); if (msg.isAbrupt) { return msg; } // 3. b. Let msgDesc be the PropertyDescriptor { [[Value]]: msg, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }. const msgDesc = new $PropertyDescriptor( realm, intrinsics.message, { '[[Value]]': msg, '[[Writable]]': intrinsics.true, '[[Enumerable]]': intrinsics.false, '[[Configurable]]': intrinsics.true, }, ); // 3. c. Perform ! DefinePropertyOrThrow(O, "message", msgDesc). $DefinePropertyOrThrow(ctx, O, intrinsics.message, msgDesc); } // 4. Return O. return O; } } // http://www.ecma-international.org/ecma-262/#sec-properties-of-the-nativeerror-prototype-objects export class $SyntaxErrorPrototype extends $Object<'%SyntaxErrorPrototype%'> { public get $constructor(): $SyntaxErrorConstructor { return this.getProperty(this.realm['[[Intrinsics]]'].$constructor)['[[Value]]'] as $SyntaxErrorConstructor; } public set $constructor(value: $SyntaxErrorConstructor) { this.setDataProperty(this.realm['[[Intrinsics]]'].$constructor, value); } public get message(): $String { return this.getProperty(this.realm['[[Intrinsics]]'].message)['[[Value]]'] as $String; } public set message(value: $String) { this.setDataProperty(this.realm['[[Intrinsics]]'].message, value); } public get $name(): $String { return this.getProperty(this.realm['[[Intrinsics]]'].$name)['[[Value]]'] as $String; } public set $name(value: $String) { this.setDataProperty(this.realm['[[Intrinsics]]'].$name, value); } public constructor( realm: Realm, errorPrototype: $ErrorPrototype, ) { const intrinsics = realm['[[Intrinsics]]']; super(realm, '%SyntaxErrorPrototype%', errorPrototype, CompletionType.normal, intrinsics.empty); } } // http://www.ecma-international.org/ecma-262/#sec-nativeerror-constructors export class $TypeErrorConstructor extends $BuiltinFunction<'%TypeError%'> { public get $prototype(): $TypeErrorPrototype { return this.getProperty(this.realm['[[Intrinsics]]'].$prototype)['[[Value]]'] as $TypeErrorPrototype; } public set $prototype(value: $TypeErrorPrototype) { this.setDataProperty(this.realm['[[Intrinsics]]'].$prototype, value, false, false, false); } public constructor( realm: Realm, errorConstructor: $ErrorConstructor, ) { super(realm, '%TypeError%', errorConstructor); } // http://www.ecma-international.org/ecma-262/#sec-nativeerror // 19.5.6.1.1 NativeError ( message ) public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, [message]: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // 1. If NewTarget is undefined, let newTarget be the active function object, else let newTarget be NewTarget. const newTarget = NewTarget.isUndefined ? ctx.Function : NewTarget; // 2. Let O be ? OrdinaryCreateFromConstructor(newTarget, "%TypeErrorPrototype%", « [[ErrorData]] »). const O = $OrdinaryCreateFromConstructor(ctx, newTarget as $Function, '%TypeErrorPrototype%', { '[[ErrorData]]': void 0 }); if (O.isAbrupt) { return O; } // 3. If message is not undefined, then if (message !== void 0) { // 3. a. Let msg be ? ToString(message). const msg = message.ToString(ctx); if (msg.isAbrupt) { return msg; } // 3. b. Let msgDesc be the PropertyDescriptor { [[Value]]: msg, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }. const msgDesc = new $PropertyDescriptor( realm, intrinsics.message, { '[[Value]]': msg, '[[Writable]]': intrinsics.true, '[[Enumerable]]': intrinsics.false, '[[Configurable]]': intrinsics.true, }, ); // 3. c. Perform ! DefinePropertyOrThrow(O, "message", msgDesc). $DefinePropertyOrThrow(ctx, O, intrinsics.message, msgDesc); } // 4. Return O. return O; } } // http://www.ecma-international.org/ecma-262/#sec-properties-of-the-nativeerror-prototype-objects export class $TypeErrorPrototype extends $Object<'%TypeErrorPrototype%'> { public get $constructor(): $TypeErrorConstructor { return this.getProperty(this.realm['[[Intrinsics]]'].$constructor)['[[Value]]'] as $TypeErrorConstructor; } public set $constructor(value: $TypeErrorConstructor) { this.setDataProperty(this.realm['[[Intrinsics]]'].$constructor, value); } public get message(): $String { return this.getProperty(this.realm['[[Intrinsics]]'].message)['[[Value]]'] as $String; } public set message(value: $String) { this.setDataProperty(this.realm['[[Intrinsics]]'].message, value); } public get $name(): $String { return this.getProperty(this.realm['[[Intrinsics]]'].$name)['[[Value]]'] as $String; } public set $name(value: $String) { this.setDataProperty(this.realm['[[Intrinsics]]'].$name, value); } public constructor( realm: Realm, errorPrototype: $ErrorPrototype, ) { const intrinsics = realm['[[Intrinsics]]']; super(realm, '%TypeErrorPrototype%', errorPrototype, CompletionType.normal, intrinsics.empty); } } // http://www.ecma-international.org/ecma-262/#sec-nativeerror-constructors export class $URIErrorConstructor extends $BuiltinFunction<'%URIError%'> { public get $prototype(): $URIErrorPrototype { return this.getProperty(this.realm['[[Intrinsics]]'].$prototype)['[[Value]]'] as $URIErrorPrototype; } public set $prototype(value: $URIErrorPrototype) { this.setDataProperty(this.realm['[[Intrinsics]]'].$prototype, value, false, false, false); } public constructor( realm: Realm, errorConstructor: $ErrorConstructor, ) { super(realm, '%URIError%', errorConstructor); } // http://www.ecma-international.org/ecma-262/#sec-nativeerror // 19.5.6.1.1 NativeError ( message ) public performSteps( ctx: ExecutionContext, thisArgument: $AnyNonEmptyNonError, [message]: $List<$AnyNonEmpty>, NewTarget: $Function | $Undefined, ): $AnyNonEmpty { const realm = ctx.Realm; const intrinsics = realm['[[Intrinsics]]']; // 1. If NewTarget is undefined, let newTarget be the active function object, else let newTarget be NewTarget. const newTarget = NewTarget.isUndefined ? ctx.Function : NewTarget; // 2. Let O be ? OrdinaryCreateFromConstructor(newTarget, "%URIErrorPrototype%", « [[ErrorData]] »). const O = $OrdinaryCreateFromConstructor(ctx, newTarget as $Function, '%URIErrorPrototype%', { '[[ErrorData]]': void 0 }); if (O.isAbrupt) { return O; } // 3. If message is not undefined, then if (message !== void 0) { // 3. a. Let msg be ? ToString(message). const msg = message.ToString(ctx); if (msg.isAbrupt) { return msg; } // 3. b. Let msgDesc be the PropertyDescriptor { [[Value]]: msg, [[Writable]]: true, [[Enumerable]]: false, [[Configurable]]: true }. const msgDesc = new $PropertyDescriptor( realm, intrinsics.message, { '[[Value]]': msg, '[[Writable]]': intrinsics.true, '[[Enumerable]]': intrinsics.false, '[[Configurable]]': intrinsics.true, }, ); // 3. c. Perform ! DefinePropertyOrThrow(O, "message", msgDesc). $DefinePropertyOrThrow(ctx, O, intrinsics.message, msgDesc); } // 4. Return O. return O; } } // http://www.ecma-international.org/ecma-262/#sec-properties-of-the-nativeerror-prototype-objects export class $URIErrorPrototype extends $Object<'%URIErrorPrototype%'> { public get $constructor(): $URIErrorConstructor { return this.getProperty(this.realm['[[Intrinsics]]'].$constructor)['[[Value]]'] as $URIErrorConstructor; } public set $constructor(value: $URIErrorConstructor) { this.setDataProperty(this.realm['[[Intrinsics]]'].$constructor, value); } public get message(): $String { return this.getProperty(this.realm['[[Intrinsics]]'].message)['[[Value]]'] as $String; } public set message(value: $String) { this.setDataProperty(this.realm['[[Intrinsics]]'].message, value); } public get $name(): $String { return this.getProperty(this.realm['[[Intrinsics]]'].$name)['[[Value]]'] as $String; } public set $name(value: $String) { this.setDataProperty(this.realm['[[Intrinsics]]'].$name, value); } public constructor( realm: Realm, errorPrototype: $ErrorPrototype, ) { const intrinsics = realm['[[Intrinsics]]']; super(realm, '%URIErrorPrototype%', errorPrototype, CompletionType.normal, intrinsics.empty); } }
the_stack
| Copyright (c) 2014-2017, PhosphorJS Contributors | | Distributed under the terms of the BSD 3-Clause License. | | The full license is in the file LICENSE, distributed with this software. |----------------------------------------------------------------------------*/ import { IIterable, IIterator, each } from '@lumino/algorithm'; import { IDisposable } from '@lumino/disposable'; import { ElementExt } from '@lumino/domutils'; import { Message, MessageLoop } from '@lumino/messaging'; import { AttachedProperty } from '@lumino/properties'; import { Signal } from '@lumino/signaling'; import { Widget } from './widget'; /** * An abstract base class for creating lumino layouts. * * #### Notes * A layout is used to add widgets to a parent and to arrange those * widgets within the parent's DOM node. * * This class implements the base functionality which is required of * nearly all layouts. It must be subclassed in order to be useful. * * Notably, this class does not define a uniform interface for adding * widgets to the layout. A subclass should define that API in a way * which is meaningful for its intended use. */ export abstract class Layout implements IIterable<Widget>, IDisposable { /** * Construct a new layout. * * @param options - The options for initializing the layout. */ constructor(options: Layout.IOptions = {}) { this._fitPolicy = options.fitPolicy || 'set-min-size'; } /** * Dispose of the resources held by the layout. * * #### Notes * This should be reimplemented to clear and dispose of the widgets. * * All reimplementations should call the superclass method. * * This method is called automatically when the parent is disposed. */ dispose(): void { this._parent = null; this._disposed = true; Signal.clearData(this); AttachedProperty.clearData(this); } /** * Test whether the layout is disposed. */ get isDisposed(): boolean { return this._disposed; } /** * Get the parent widget of the layout. */ get parent(): Widget | null { return this._parent; } /** * Set the parent widget of the layout. * * #### Notes * This is set automatically when installing the layout on the parent * widget. The parent widget should not be set directly by user code. */ set parent(value: Widget | null) { if (this._parent === value) { return; } if (this._parent) { throw new Error('Cannot change parent widget.'); } if (value!.layout !== this) { throw new Error('Invalid parent widget.'); } this._parent = value; this.init(); } /** * Get the fit policy for the layout. * * #### Notes * The fit policy controls the computed size constraints which are * applied to the parent widget by the layout. * * Some layout implementations may ignore the fit policy. */ get fitPolicy(): Layout.FitPolicy { return this._fitPolicy; } /** * Set the fit policy for the layout. * * #### Notes * The fit policy controls the computed size constraints which are * applied to the parent widget by the layout. * * Some layout implementations may ignore the fit policy. * * Changing the fit policy will clear the current size constraint * for the parent widget and then re-fit the parent. */ set fitPolicy(value: Layout.FitPolicy) { // Bail if the policy does not change if (this._fitPolicy === value) { return; } // Update the internal policy. this._fitPolicy = value; // Clear the size constraints and schedule a fit of the parent. if (this._parent) { let style = this._parent.node.style; style.minWidth = ''; style.minHeight = ''; style.maxWidth = ''; style.maxHeight = ''; this._parent.fit(); } } /** * Create an iterator over the widgets in the layout. * * @returns A new iterator over the widgets in the layout. * * #### Notes * This abstract method must be implemented by a subclass. */ abstract iter(): IIterator<Widget>; /** * Remove a widget from the layout. * * @param widget - The widget to remove from the layout. * * #### Notes * A widget is automatically removed from the layout when its `parent` * is set to `null`. This method should only be invoked directly when * removing a widget from a layout which has yet to be installed on a * parent widget. * * This method should *not* modify the widget's `parent`. */ abstract removeWidget(widget: Widget): void; /** * Process a message sent to the parent widget. * * @param msg - The message sent to the parent widget. * * #### Notes * This method is called by the parent widget to process a message. * * Subclasses may reimplement this method as needed. */ processParentMessage(msg: Message): void { switch (msg.type) { case 'resize': this.onResize(msg as Widget.ResizeMessage); break; case 'update-request': this.onUpdateRequest(msg); break; case 'fit-request': this.onFitRequest(msg); break; case 'before-show': this.onBeforeShow(msg); break; case 'after-show': this.onAfterShow(msg); break; case 'before-hide': this.onBeforeHide(msg); break; case 'after-hide': this.onAfterHide(msg); break; case 'before-attach': this.onBeforeAttach(msg); break; case 'after-attach': this.onAfterAttach(msg); break; case 'before-detach': this.onBeforeDetach(msg); break; case 'after-detach': this.onAfterDetach(msg); break; case 'child-removed': this.onChildRemoved(msg as Widget.ChildMessage); break; case 'child-shown': this.onChildShown(msg as Widget.ChildMessage); break; case 'child-hidden': this.onChildHidden(msg as Widget.ChildMessage); break; } } /** * Perform layout initialization which requires the parent widget. * * #### Notes * This method is invoked immediately after the layout is installed * on the parent widget. * * The default implementation reparents all of the widgets to the * layout parent widget. * * Subclasses should reimplement this method and attach the child * widget nodes to the parent widget's node. */ protected init(): void { each(this, widget => { widget.parent = this.parent; }); } /** * A message handler invoked on a `'resize'` message. * * #### Notes * The layout should ensure that its widgets are resized according * to the specified layout space, and that they are sent a `'resize'` * message if appropriate. * * The default implementation of this method sends an `UnknownSize` * resize message to all widgets. * * This may be reimplemented by subclasses as needed. */ protected onResize(msg: Widget.ResizeMessage): void { each(this, widget => { MessageLoop.sendMessage(widget, Widget.ResizeMessage.UnknownSize); }); } /** * A message handler invoked on an `'update-request'` message. * * #### Notes * The layout should ensure that its widgets are resized according * to the available layout space, and that they are sent a `'resize'` * message if appropriate. * * The default implementation of this method sends an `UnknownSize` * resize message to all widgets. * * This may be reimplemented by subclasses as needed. */ protected onUpdateRequest(msg: Message): void { each(this, widget => { MessageLoop.sendMessage(widget, Widget.ResizeMessage.UnknownSize); }); } /** * A message handler invoked on a `'before-attach'` message. * * #### Notes * The default implementation of this method forwards the message * to all widgets. It assumes all widget nodes are attached to the * parent widget node. * * This may be reimplemented by subclasses as needed. */ protected onBeforeAttach(msg: Message): void { each(this, widget => { MessageLoop.sendMessage(widget, msg); }); } /** * A message handler invoked on an `'after-attach'` message. * * #### Notes * The default implementation of this method forwards the message * to all widgets. It assumes all widget nodes are attached to the * parent widget node. * * This may be reimplemented by subclasses as needed. */ protected onAfterAttach(msg: Message): void { each(this, widget => { MessageLoop.sendMessage(widget, msg); }); } /** * A message handler invoked on a `'before-detach'` message. * * #### Notes * The default implementation of this method forwards the message * to all widgets. It assumes all widget nodes are attached to the * parent widget node. * * This may be reimplemented by subclasses as needed. */ protected onBeforeDetach(msg: Message): void { each(this, widget => { MessageLoop.sendMessage(widget, msg); }); } /** * A message handler invoked on an `'after-detach'` message. * * #### Notes * The default implementation of this method forwards the message * to all widgets. It assumes all widget nodes are attached to the * parent widget node. * * This may be reimplemented by subclasses as needed. */ protected onAfterDetach(msg: Message): void { each(this, widget => { MessageLoop.sendMessage(widget, msg); }); } /** * A message handler invoked on a `'before-show'` message. * * #### Notes * The default implementation of this method forwards the message to * all non-hidden widgets. It assumes all widget nodes are attached * to the parent widget node. * * This may be reimplemented by subclasses as needed. */ protected onBeforeShow(msg: Message): void { each(this, widget => { if (!widget.isHidden) { MessageLoop.sendMessage(widget, msg); } }); } /** * A message handler invoked on an `'after-show'` message. * * #### Notes * The default implementation of this method forwards the message to * all non-hidden widgets. It assumes all widget nodes are attached * to the parent widget node. * * This may be reimplemented by subclasses as needed. */ protected onAfterShow(msg: Message): void { each(this, widget => { if (!widget.isHidden) { MessageLoop.sendMessage(widget, msg); } }); } /** * A message handler invoked on a `'before-hide'` message. * * #### Notes * The default implementation of this method forwards the message to * all non-hidden widgets. It assumes all widget nodes are attached * to the parent widget node. * * This may be reimplemented by subclasses as needed. */ protected onBeforeHide(msg: Message): void { each(this, widget => { if (!widget.isHidden) { MessageLoop.sendMessage(widget, msg); } }); } /** * A message handler invoked on an `'after-hide'` message. * * #### Notes * The default implementation of this method forwards the message to * all non-hidden widgets. It assumes all widget nodes are attached * to the parent widget node. * * This may be reimplemented by subclasses as needed. */ protected onAfterHide(msg: Message): void { each(this, widget => { if (!widget.isHidden) { MessageLoop.sendMessage(widget, msg); } }); } /** * A message handler invoked on a `'child-removed'` message. * * #### Notes * This will remove the child widget from the layout. * * Subclasses should **not** typically reimplement this method. */ protected onChildRemoved(msg: Widget.ChildMessage): void { this.removeWidget(msg.child); } /** * A message handler invoked on a `'fit-request'` message. * * #### Notes * The default implementation of this handler is a no-op. */ protected onFitRequest(msg: Message): void { } /** * A message handler invoked on a `'child-shown'` message. * * #### Notes * The default implementation of this handler is a no-op. */ protected onChildShown(msg: Widget.ChildMessage): void { } /** * A message handler invoked on a `'child-hidden'` message. * * #### Notes * The default implementation of this handler is a no-op. */ protected onChildHidden(msg: Widget.ChildMessage): void { } private _disposed = false; private _fitPolicy: Layout.FitPolicy; private _parent: Widget | null = null; } /** * The namespace for the `Layout` class statics. */ export namespace Layout { /** * A type alias for the layout fit policy. * * #### Notes * The fit policy controls the computed size constraints which are * applied to the parent widget by the layout. * * Some layout implementations may ignore the fit policy. */ export type FitPolicy = ( /** * No size constraint will be applied to the parent widget. */ 'set-no-constraint' | /** * The computed min size will be applied to the parent widget. */ 'set-min-size' ); /** * An options object for initializing a layout. */ export interface IOptions { /** * The fit policy for the layout. * * The default is `'set-min-size'`. */ fitPolicy?: FitPolicy; } /** * A type alias for the horizontal alignment of a widget. */ export type HorizontalAlignment = 'left' | 'center' | 'right'; /** * A type alias for the vertical alignment of a widget. */ export type VerticalAlignment = 'top' | 'center' | 'bottom'; /** * Get the horizontal alignment for a widget. * * @param widget - The widget of interest. * * @returns The horizontal alignment for the widget. * * #### Notes * If the layout width allocated to a widget is larger than its max * width, the horizontal alignment controls how the widget is placed * within the extra horizontal space. * * If the allocated width is less than the widget's max width, the * horizontal alignment has no effect. * * Some layout implementations may ignore horizontal alignment. */ export function getHorizontalAlignment(widget: Widget): HorizontalAlignment { return Private.horizontalAlignmentProperty.get(widget); } /** * Set the horizontal alignment for a widget. * * @param widget - The widget of interest. * * @param value - The value for the horizontal alignment. * * #### Notes * If the layout width allocated to a widget is larger than its max * width, the horizontal alignment controls how the widget is placed * within the extra horizontal space. * * If the allocated width is less than the widget's max width, the * horizontal alignment has no effect. * * Some layout implementations may ignore horizontal alignment. * * Changing the horizontal alignment will post an `update-request` * message to widget's parent, provided the parent has a layout * installed. */ export function setHorizontalAlignment(widget: Widget, value: HorizontalAlignment): void { Private.horizontalAlignmentProperty.set(widget, value); } /** * Get the vertical alignment for a widget. * * @param widget - The widget of interest. * * @returns The vertical alignment for the widget. * * #### Notes * If the layout height allocated to a widget is larger than its max * height, the vertical alignment controls how the widget is placed * within the extra vertical space. * * If the allocated height is less than the widget's max height, the * vertical alignment has no effect. * * Some layout implementations may ignore vertical alignment. */ export function getVerticalAlignment(widget: Widget): VerticalAlignment { return Private.verticalAlignmentProperty.get(widget); } /** * Set the vertical alignment for a widget. * * @param widget - The widget of interest. * * @param value - The value for the vertical alignment. * * #### Notes * If the layout height allocated to a widget is larger than its max * height, the vertical alignment controls how the widget is placed * within the extra vertical space. * * If the allocated height is less than the widget's max height, the * vertical alignment has no effect. * * Some layout implementations may ignore vertical alignment. * * Changing the horizontal alignment will post an `update-request` * message to widget's parent, provided the parent has a layout * installed. */ export function setVerticalAlignment(widget: Widget, value: VerticalAlignment): void { Private.verticalAlignmentProperty.set(widget, value); } } /** * An object which assists in the absolute layout of widgets. * * #### Notes * This class is useful when implementing a layout which arranges its * widgets using absolute positioning. * * This class is used by nearly all of the built-in lumino layouts. */ export class LayoutItem implements IDisposable { /** * Construct a new layout item. * * @param widget - The widget to be managed by the item. * * #### Notes * The widget will be set to absolute positioning. */ constructor(widget: Widget) { this.widget = widget; this.widget.node.style.position = 'absolute'; } /** * Dispose of the the layout item. * * #### Notes * This will reset the positioning of the widget. */ dispose(): void { // Do nothing if the item is already disposed. if (this._disposed) { return; } // Mark the item as disposed. this._disposed = true; // Reset the widget style. let style = this.widget.node.style; style.position = ''; style.top = ''; style.left = ''; style.width = ''; style.height = ''; } /** * The widget managed by the layout item. */ readonly widget: Widget; /** * The computed minimum width of the widget. * * #### Notes * This value can be updated by calling the `fit` method. */ get minWidth(): number { return this._minWidth; } /** * The computed minimum height of the widget. * * #### Notes * This value can be updated by calling the `fit` method. */ get minHeight(): number { return this._minHeight; } /** * The computed maximum width of the widget. * * #### Notes * This value can be updated by calling the `fit` method. */ get maxWidth(): number { return this._maxWidth; } /** * The computed maximum height of the widget. * * #### Notes * This value can be updated by calling the `fit` method. */ get maxHeight(): number { return this._maxHeight; } /** * Whether the layout item is disposed. */ get isDisposed(): boolean { return this._disposed; } /** * Whether the managed widget is hidden. */ get isHidden(): boolean { return this.widget.isHidden; } /** * Whether the managed widget is visible. */ get isVisible(): boolean { return this.widget.isVisible; } /** * Whether the managed widget is attached. */ get isAttached(): boolean { return this.widget.isAttached; } /** * Update the computed size limits of the managed widget. */ fit(): void { let limits = ElementExt.sizeLimits(this.widget.node); this._minWidth = limits.minWidth; this._minHeight = limits.minHeight; this._maxWidth = limits.maxWidth; this._maxHeight = limits.maxHeight; } /** * Update the position and size of the managed widget. * * @param left - The left edge position of the layout box. * * @param top - The top edge position of the layout box. * * @param width - The width of the layout box. * * @param height - The height of the layout box. */ update(left: number, top: number, width: number, height: number): void { // Clamp the size to the computed size limits. let clampW = Math.max(this._minWidth, Math.min(width, this._maxWidth)); let clampH = Math.max(this._minHeight, Math.min(height, this._maxHeight)); // Adjust the left edge for the horizontal alignment, if needed. if (clampW < width) { switch (Layout.getHorizontalAlignment(this.widget)) { case 'left': break; case 'center': left += (width - clampW) / 2; break; case 'right': left += width - clampW; break; default: throw 'unreachable'; } } // Adjust the top edge for the vertical alignment, if needed. if (clampH < height) { switch (Layout.getVerticalAlignment(this.widget)) { case 'top': break; case 'center': top += (height - clampH) / 2; break; case 'bottom': top += height - clampH; break; default: throw 'unreachable'; } } // Set up the resize variables. let resized = false; let style = this.widget.node.style; // Update the top edge of the widget if needed. if (this._top !== top) { this._top = top; style.top = `${top}px`; } // Update the left edge of the widget if needed. if (this._left !== left) { this._left = left; style.left = `${left}px`; } // Update the width of the widget if needed. if (this._width !== clampW) { resized = true; this._width = clampW; style.width = `${clampW}px`; } // Update the height of the widget if needed. if (this._height !== clampH) { resized = true; this._height = clampH; style.height = `${clampH}px`; } // Send a resize message to the widget if needed. if (resized) { let msg = new Widget.ResizeMessage(clampW, clampH); MessageLoop.sendMessage(this.widget, msg); } } private _top = NaN; private _left = NaN; private _width = NaN; private _height = NaN; private _minWidth = 0; private _minHeight = 0; private _maxWidth = Infinity; private _maxHeight = Infinity; private _disposed = false; } /** * The namespace for the module implementation details. */ namespace Private { /** * The attached property for a widget horizontal alignment. */ export const horizontalAlignmentProperty = new AttachedProperty<Widget, Layout.HorizontalAlignment>({ name: 'horizontalAlignment', create: () => 'center', changed: onAlignmentChanged }); /** * The attached property for a widget vertical alignment. */ export const verticalAlignmentProperty = new AttachedProperty<Widget, Layout.VerticalAlignment>({ name: 'verticalAlignment', create: () => 'top', changed: onAlignmentChanged }); /** * The change handler for the attached alignment properties. */ function onAlignmentChanged(child: Widget): void { if (child.parent && child.parent.layout) { child.parent.update(); } } }
the_stack
import * as http from "http"; import * as os from "os"; import * as path from "path"; import { resolve as pathResolve } from "path"; import { ParsedUrlQuery } from "querystring"; import * as url from "url"; import * as util from "util"; import * as _ from "lodash"; import * as models from "../models"; import { requestResponseDefinition } from "../models/requestResponse"; import { LowerHttpMethods, SwaggerSpec } from "../swagger/swaggerTypes"; import { SchemaValidateFunction, SchemaValidateIssue, SchemaValidator, } from "../swaggerValidator/schemaValidator"; import * as C from "../util/constants"; import { log } from "../util/logging"; import * as utils from "../util/utils"; import { RuntimeException } from "../util/validationError"; import { inversifyGetContainer, inversifyGetInstance, TYPES } from "../inversifyUtils"; import { setDefaultOpts } from "../swagger/loader"; import { apiValidationErrors, ApiValidationErrorCode } from "../util/errorDefinitions"; import { LiveValidatorLoader, LiveValidatorLoaderOption } from "./liveValidatorLoader"; import { getProviderFromPathTemplate, OperationSearcher } from "./operationSearcher"; import { LiveRequest, LiveResponse, OperationContext, validateSwaggerLiveRequest, validateSwaggerLiveResponse, ValidationRequest, } from "./operationValidator"; const glob = require("glob"); export interface LiveValidatorOptions extends LiveValidatorLoaderOption { swaggerPaths: string[]; git: { shouldClone: boolean; url?: string; branch?: string; }; useRelativeSourceLocationUrl?: boolean; directory: string; swaggerPathsPattern: string[]; excludedSwaggerPathsPattern: string[]; isPathCaseSensitive: boolean; loadValidatorInBackground: boolean; loadValidatorInInitialize: boolean; } export interface RequestResponsePair { readonly liveRequest: LiveRequest; readonly liveResponse: LiveResponse; } export interface LiveValidationResult { readonly isSuccessful?: boolean; readonly operationInfo: OperationContext; readonly errors: LiveValidationIssue[]; readonly runtimeException?: RuntimeException; } export interface RequestResponseLiveValidationResult { readonly requestValidationResult: LiveValidationResult; readonly responseValidationResult: LiveValidationResult; readonly runtimeException?: RuntimeException; } export type LiveValidationIssue = { code: ApiValidationErrorCode; pathsInPayload: string[]; documentationUrl?: string; } & Omit<SchemaValidateIssue, "code">; /** * Additional data to log. */ interface Meta { [key: string]: any; } /** * Options for a validation operation. * If `includeErrors` is missing or empty, all error codes will be included. */ export interface ValidateOptions { readonly includeErrors?: ApiValidationErrorCode[]; readonly includeOperationMatch?: boolean; } export enum LiveValidatorLoggingLevels { error = "error", warn = "warn", info = "info", verbose = "verbose", debug = "debug", silly = "silly", } export enum LiveValidatorLoggingTypes { trace = "trace", perfTrace = "perfTrace", error = "error", incomingRequest = "incomingRequest", } /** * @class * Live Validator for Azure swagger APIs. */ export class LiveValidator { public options: LiveValidatorOptions; public operationSearcher: OperationSearcher; private logFunction?: (message: string, level: string, meta?: Meta) => void; private loader?: LiveValidatorLoader; private loadInBackgroundComplete: boolean = false; private validateRequestResponsePair?: SchemaValidateFunction; /** * Constructs LiveValidator based on provided options. * * @param {object} ops The configuration options. * @param {callback function} logCallback The callback logger. * * @returns CacheBuilder Returns the configured CacheBuilder object. */ public constructor( options?: Partial<LiveValidatorOptions>, logCallback?: (message: string, level: string, meta?: Meta) => void ) { const ops: Partial<LiveValidatorOptions> = options || {}; this.logFunction = logCallback; setDefaultOpts(ops, { swaggerPaths: [], excludedSwaggerPathsPattern: C.DefaultConfig.ExcludedSwaggerPathsPattern, directory: path.resolve(os.homedir(), "repo"), isPathCaseSensitive: false, loadValidatorInBackground: true, loadValidatorInInitialize: false, isArmCall: false, }); if (!ops.git) { ops.git = { url: "https://github.com/Azure/azure-rest-api-specs.git", shouldClone: false, }; } if (!ops.git.url) { ops.git.url = "https://github.com/Azure/azure-rest-api-specs.git"; } if (!ops.git.shouldClone) { ops.git.shouldClone = false; } this.options = ops as LiveValidatorOptions; this.logging(`Creating livevalidator with options:${JSON.stringify(this.options)}`); this.operationSearcher = new OperationSearcher(this.logging); } /** * Initializes the Live Validator. */ public async initialize(): Promise<void> { const startTime = Date.now(); // Clone github repository if required if (this.options.git.shouldClone && this.options.git.url) { const cloneStartTime = Date.now(); utils.gitClone(this.options.directory, this.options.git.url, this.options.git.branch); this.logging( `Clone spec repository ${this.options.git.url}, branch:${this.options.git.branch} in livevalidator.initialize` ); this.logging( `Clone spec repository ${this.options.git.url}, branch:${this.options.git.branch}`, LiveValidatorLoggingLevels.info, LiveValidatorLoggingTypes.perfTrace, "Oav.liveValidator.initialize.gitclone", Date.now() - cloneStartTime ); } // Construct array of swagger paths to be used for building a cache this.logging("Get swagger path."); const swaggerPaths = await this.getSwaggerPaths(); const container = inversifyGetContainer(); this.loader = inversifyGetInstance(LiveValidatorLoader, { container, fileRoot: this.options.directory, ...this.options, loadSuppression: this.options.loadSuppression ?? Object.keys(apiValidationErrors), }); this.loader.logging = this.logging; // re-set the transform context after set the logging function this.loader.setTransformContext(); const schemaValidator = container.get(TYPES.schemaValidator) as SchemaValidator; this.validateRequestResponsePair = await schemaValidator.compileAsync( requestResponseDefinition ); const allSpecs: SwaggerSpec[] = []; while (swaggerPaths.length > 0) { const swaggerPath = swaggerPaths.shift()!; const spec = await this.getSwaggerInitializer(this.loader!, swaggerPath); if (spec !== undefined) { allSpecs.push(spec); } } this.logging("Apply global transforms for all specs"); try { this.loader.transformLoadedSpecs(); } catch (e) { const errMsg = `Failed to transform loaded specs, detail error message:${e?.message}.ErrorStack:${e?.stack}`; this.logging( errMsg, LiveValidatorLoggingLevels.error, LiveValidatorLoggingTypes.error, "Oav.liveValidator.initialize.transformLoadedSpecs" ); throw new Error(errMsg); } if (this.options.loadValidatorInInitialize) { while (allSpecs.length > 0) { try { const spec = allSpecs.shift()!; const loadStart = Date.now(); this.logging( `Start building validator for ${spec._filePath}`, LiveValidatorLoggingLevels.debug, LiveValidatorLoggingTypes.trace, "Oav.liveValidator.loader.buildAjvValidator" ); await this.loader.buildAjvValidator(spec); const durationInMs = Date.now() - loadStart; this.logging( `Complete building validator for ${spec._filePath} with DurationInMs:${durationInMs}`, LiveValidatorLoggingLevels.debug, LiveValidatorLoggingTypes.trace, "Oav.liveValidator.loader.buildAjvValidator" ); this.logging( `Complete building validator for ${spec._filePath} in initialization time`, LiveValidatorLoggingLevels.info, LiveValidatorLoggingTypes.perfTrace, "Oav.liveValidator.initialize.loader.buildAjvValidator", durationInMs ); } catch (e) { this.logging( `ErrorMessage:${e?.message}.ErrorStack:${e?.stack}`, LiveValidatorLoggingLevels.error, LiveValidatorLoggingTypes.error, "Oav.liveValidator.initialize.loadValidatorInInitialize" ); } } this.loader = undefined; } this.logging("Cache initialization complete."); const elapsedTime = Date.now() - startTime; this.logging( `Cache complete initialization with DurationInMs:${elapsedTime}`, LiveValidatorLoggingLevels.info, LiveValidatorLoggingTypes.trace, "Oav.liveValidator.initialize" ); this.logging( `Cache complete initialization`, LiveValidatorLoggingLevels.info, LiveValidatorLoggingTypes.perfTrace, "Oav.liveValidator.initialize", elapsedTime ); if (this.options.loadValidatorInBackground) { // eslint-disable-next-line @typescript-eslint/no-floating-promises this.loadAllSpecValidatorInBackground(allSpecs); } } public isLoadInBackgroundCompleted() { return this.loadInBackgroundComplete; } private async loadAllSpecValidatorInBackground(allSpecs: SwaggerSpec[]) { const backgroundStartTime = Date.now(); utils.shuffleArray(allSpecs); while (allSpecs.length > 0) { try { const spec = allSpecs.shift()!; const startTime = Date.now(); this.logging( `Start building validator for ${spec._filePath} in background`, LiveValidatorLoggingLevels.debug, LiveValidatorLoggingTypes.trace, "Oav.liveValidator.loadAllSpecValidatorInBackground" ); await this.loader!.buildAjvValidator(spec, { inBackground: true }); const elapsedTime = Date.now() - startTime; this.logging( `Complete building validator for ${spec._filePath} in background with DurationInMs:${elapsedTime}.`, LiveValidatorLoggingLevels.debug, LiveValidatorLoggingTypes.trace, "Oav.liveValidator.loadAllSpecValidatorInBackground" ); this.logging( `Complete building for ${spec._filePath} in background`, LiveValidatorLoggingLevels.info, LiveValidatorLoggingTypes.perfTrace, "Oav.liveValidator.loadAllSpecValidatorInBackground-1", elapsedTime ); } catch (e) { this.logging( `ErrorMessage:${e?.message}.ErrorStack:${e?.stack}`, LiveValidatorLoggingLevels.error, LiveValidatorLoggingTypes.error, "Oav.liveValidator.loadAllSpecValidatorInBackground" ); } } this.loader = undefined; this.loadInBackgroundComplete = true; const elapsedTimeForBuild = Date.now() - backgroundStartTime; this.logging( `Build validator for all specs finished in background with DurationInMs:${elapsedTimeForBuild}.`, LiveValidatorLoggingLevels.info, LiveValidatorLoggingTypes.trace, "Oav.liveValidator.loadAllSpecValidatorInBackground" ); this.logging( `Build validator for all specs finished in background`, LiveValidatorLoggingLevels.info, LiveValidatorLoggingTypes.perfTrace, "Oav.liveValidator.loadAllSpecValidatorInBackground", elapsedTimeForBuild ); } /** * Validates live request. */ public async validateLiveRequest( liveRequest: LiveRequest, options: ValidateOptions = {}, operationInfo?: OperationContext ): Promise<LiveValidationResult> { const startTime = Date.now(); const correlationId = liveRequest.headers?.["x-ms-correlation-request-id"] || ""; const { info, error } = this.getOperationInfo(liveRequest, correlationId, operationInfo); if (error !== undefined) { this.logging( `ErrorMessage:${error.message}.ErrorStack:${error.stack}`, LiveValidatorLoggingLevels.error, LiveValidatorLoggingTypes.error, "Oav.liveValidator.validateLiveRequest", undefined, info.validationRequest ); return { isSuccessful: undefined, errors: [], runtimeException: error, operationInfo: info, }; } if (!liveRequest.query) { liveRequest.query = url.parse(liveRequest.url, true).query; } let errors: LiveValidationIssue[] = []; let runtimeException; try { errors = await validateSwaggerLiveRequest( liveRequest, info, this.loader, options.includeErrors, this.logging ); } catch (reqValidationError) { const msg = `An error occurred while validating the live request for operation ` + `"${info.operationId}". The error is:\n ` + `${util.inspect(reqValidationError, { depth: null })}`; runtimeException = { code: C.ErrorCodes.RequestValidationError.name, message: msg }; this.logging( msg, LiveValidatorLoggingLevels.error, LiveValidatorLoggingTypes.error, "Oav.liveValidator.validateLiveRequest", undefined, info.validationRequest ); } const elapsedTime = Date.now() - startTime; this.logging( `Complete request validation`, LiveValidatorLoggingLevels.info, LiveValidatorLoggingTypes.perfTrace, "Oav.liveValidator.validateLiveRequest", elapsedTime, info.validationRequest ); if (!options.includeOperationMatch) { delete info.operationMatch; delete info.validationRequest; } return { isSuccessful: runtimeException ? undefined : errors.length === 0, operationInfo: info, errors, runtimeException, }; } /** * Validates live response. */ public async validateLiveResponse( liveResponse: LiveResponse, specOperation: { url: string; method: string }, options: ValidateOptions = {}, operationInfo?: OperationContext ): Promise<LiveValidationResult> { const startTime = Date.now(); const correlationId = liveResponse.headers?.["x-ms-correlation-request-id"] || ""; const { info, error } = this.getOperationInfo(specOperation, correlationId, operationInfo); if (error !== undefined) { this.logging( `ErrorMessage:${error.message}.ErrorStack:${error.stack}`, LiveValidatorLoggingLevels.error, LiveValidatorLoggingTypes.error, "Oav.liveValidator.validateLiveResponse", undefined, info.validationRequest ); return { isSuccessful: undefined, errors: [], runtimeException: error, operationInfo: { apiVersion: C.unknownApiVersion, operationId: C.unknownOperationId }, }; } let errors: LiveValidationIssue[] = []; let runtimeException; this.transformResponseStatusCode(liveResponse); try { errors = await validateSwaggerLiveResponse( liveResponse, info, this.loader, options.includeErrors, this.options.isArmCall, this.logging ); } catch (resValidationError) { const msg = `An error occurred while validating the live response for operation ` + `"${info.operationId}". The error is:\n ` + `${util.inspect(resValidationError, { depth: null })}`; runtimeException = { code: C.ErrorCodes.RequestValidationError.name, message: msg }; this.logging( msg, LiveValidatorLoggingLevels.error, LiveValidatorLoggingTypes.error, "Oav.liveValidator.validateLiveResponse", undefined, info.validationRequest ); } const elapsedTime = Date.now() - startTime; this.logging( `Complete response validation`, LiveValidatorLoggingLevels.info, LiveValidatorLoggingTypes.perfTrace, "Oav.liveValidator.validateLiveResponse", elapsedTime, info.validationRequest ); if (!options.includeOperationMatch) { delete info.operationMatch; delete info.validationRequest; } return { isSuccessful: runtimeException ? undefined : errors.length === 0, operationInfo: info, errors, runtimeException, }; } /** * Validates live request and response. */ public async validateLiveRequestResponse( requestResponseObj: RequestResponsePair, options?: ValidateOptions ): Promise<RequestResponseLiveValidationResult> { const validationResult = { requestValidationResult: { errors: [], operationInfo: { apiVersion: C.unknownApiVersion, operationId: C.unknownOperationId }, }, responseValidationResult: { errors: [], operationInfo: { apiVersion: C.unknownApiVersion, operationId: C.unknownOperationId }, }, }; if (!requestResponseObj) { const message = 'requestResponseObj cannot be null or undefined and must be of type "object".'; return { ...validationResult, runtimeException: { code: C.ErrorCodes.IncorrectInput.name, message, }, }; } const errors = this.validateRequestResponsePair!({}, requestResponseObj); if (errors.length > 0) { const error = errors[0]; const message = `Found errors "${error.message}" in the provided input in path ${error.jsonPathsInPayload[0]}:\n` + `${util.inspect(requestResponseObj, { depth: null })}.`; return { ...validationResult, runtimeException: { code: C.ErrorCodes.IncorrectInput.name, message, }, }; } const request = requestResponseObj.liveRequest; const response = requestResponseObj.liveResponse; this.transformResponseStatusCode(response); const requestValidationResult = await this.validateLiveRequest(request, { ...options, includeOperationMatch: true, }); const info = requestValidationResult.operationInfo; const responseValidationResult = requestValidationResult.isSuccessful === undefined && requestValidationResult.runtimeException === undefined ? requestValidationResult : await this.validateLiveResponse( response, request, { ...options, includeOperationMatch: false, }, info ); delete info.validationRequest; delete info.operationMatch; return { requestValidationResult, responseValidationResult, }; } private transformResponseStatusCode(liveResponse: LiveResponse) { // If status code is passed as a status code string (e.g. "OK") transform it to the status code // number (e.g. '200'). if ( !http.STATUS_CODES[liveResponse.statusCode] && utils.statusCodeStringToStatusCode[liveResponse.statusCode.toLowerCase()] ) { liveResponse.statusCode = utils.statusCodeStringToStatusCode[liveResponse.statusCode.toLowerCase()]; } } private getOperationInfo( request: { url: string; method: string }, correlationId: string, operationInfo?: OperationContext ): { info: OperationContext; error?: any; } { const info = operationInfo ?? { apiVersion: C.unknownApiVersion, operationId: C.unknownOperationId, }; try { if (info.validationRequest === undefined) { info.validationRequest = this.parseValidationRequest( request.url, request.method, correlationId ); } if (info.operationMatch === undefined) { const result = this.operationSearcher.search(info.validationRequest); info.apiVersion = result.apiVersion; info.operationMatch = result.operationMatch; } info.operationId = info.operationMatch.operation.operationId!; return { info }; } catch (error) { return { info, error }; } } public parseValidationRequest( requestUrl: string, requestMethod: string | undefined | null, correlationId: string ): ValidationRequest { return parseValidationRequest(requestUrl, requestMethod, correlationId); } private async getMatchedPaths(jsonsPattern: string | string[]): Promise<string[]> { const startTime = Date.now(); let matchedPaths: string[] = []; if (typeof jsonsPattern === "string") { matchedPaths = glob.sync(jsonsPattern, { ignore: this.options.excludedSwaggerPathsPattern, nodir: true, }); } else { for (const pattern of jsonsPattern) { const res: string[] = glob.sync(pattern, { ignore: this.options.excludedSwaggerPathsPattern, nodir: true, }); matchedPaths = matchedPaths.concat(res); } } this.logging( `Using swaggers found from directory: "${ this.options.directory }" and pattern: "${jsonsPattern.toString()}". Total paths count: ${matchedPaths.length}`, LiveValidatorLoggingLevels.info ); this.logging( `Using swaggers found from directory: "${ this.options.directory }" and pattern: "${jsonsPattern.toString()}". Total paths count: ${matchedPaths.length}`, LiveValidatorLoggingLevels.info, LiveValidatorLoggingTypes.perfTrace, "Oav.livevalidator.getMatchedPaths", Date.now() - startTime ); return matchedPaths; } private async getSwaggerPaths(): Promise<string[]> { if (this.options.swaggerPaths.length !== 0) { this.logging( `Using user provided swagger paths by options.swaggerPaths. Total paths count: ${this.options.swaggerPaths.length}` ); return this.options.swaggerPaths; } else { const allJsonsPattern = path.join(this.options.directory, "/specification/**/*.json"); const swaggerPathPatterns: string[] = []; if ( this.options.swaggerPathsPattern === undefined || this.options.swaggerPathsPattern.length === 0 ) { return this.getMatchedPaths(allJsonsPattern); } else { this.options.swaggerPathsPattern.map((item) => { swaggerPathPatterns.push(path.join(this.options.directory, item)); }); return this.getMatchedPaths(swaggerPathPatterns); } } } private async getSwaggerInitializer( loader: LiveValidatorLoader, swaggerPath: string ): Promise<SwaggerSpec | undefined> { const startTime = Date.now(); this.logging(`Building cache from:${swaggerPath}`, LiveValidatorLoggingLevels.debug); try { const spec = await loader.load(pathResolve(swaggerPath)); const elapsedTimeLoadSpec = Date.now() - startTime; this.logging( `Load spec ${swaggerPath}`, LiveValidatorLoggingLevels.info, LiveValidatorLoggingTypes.perfTrace, "Oav.liveValidator.getSwaggerInitializer.loader.load", elapsedTimeLoadSpec ); const startTimeAddSpecToCache = Date.now(); this.operationSearcher.addSpecToCache(spec); this.logging( `Add spec to cache ${swaggerPath}`, LiveValidatorLoggingLevels.info, LiveValidatorLoggingTypes.perfTrace, "Oav.liveValidator.getSwaggerInitializer.operationSearcher.addSpecToCache", Date.now() - startTimeAddSpecToCache ); const elapsedTime = Date.now() - startTime; this.logging( `Complete loading with DurationInMs:${elapsedTime}`, LiveValidatorLoggingLevels.debug, LiveValidatorLoggingTypes.trace, "Oav.liveValidator.getSwaggerInitializer" ); return spec; } catch (err) { this.logging( `Unable to initialize "${swaggerPath}" file from SpecValidator. We are ` + `ignoring this swagger file and continuing to build cache for other valid specs. ErrorMessage: ${err?.message};ErrorStack: ${err?.stack}`, LiveValidatorLoggingLevels.warn, LiveValidatorLoggingTypes.error ); return undefined; } } private logging = ( message: string, level?: LiveValidatorLoggingLevels, loggingType?: LiveValidatorLoggingTypes, operationName?: string, durationInMilliseconds?: number, validationRequest?: ValidationRequest ) => { level = level || LiveValidatorLoggingLevels.info; loggingType = loggingType || LiveValidatorLoggingTypes.trace; operationName = operationName || ""; durationInMilliseconds = durationInMilliseconds || 0; if (this.logFunction !== undefined) { if (validationRequest !== undefined && validationRequest !== null) { this.logFunction(message, level, { CorrelationId: validationRequest.correlationId, ProviderNamespace: validationRequest.providerNamespace, ResourceType: validationRequest.resourceType, ApiVersion: validationRequest.apiVersion, OperationName: operationName, LoggingType: loggingType, DurationInMilliseconds: durationInMilliseconds, }); } else { this.logFunction(message, level, { OperationName: operationName, LoggingType: loggingType, DurationInMilliseconds: durationInMilliseconds, }); } } else { log.log(level, message); } }; } /** * OAV expects the url that is sent to match exactly with the swagger path. For this we need to keep only the part after * where the swagger path starts. Currently those are '/subscriptions' and '/providers'. */ export function formatUrlToExpectedFormat(requestUrl: string): string { return requestUrl.substring(requestUrl.search("/?(subscriptions|providers)/i")); } /** * Parse the validation request information. * * @param requestUrl The url of service api call. * * @param requestMethod The http verb for the method to be used for lookup. * * @param correlationId The id to correlate the api calls. * * @returns parsed ValidationRequest info. */ export const parseValidationRequest = ( requestUrl: string, requestMethod: string | undefined | null, correlationId: string ): ValidationRequest => { if ( requestUrl === undefined || requestUrl === null || typeof requestUrl.valueOf() !== "string" || !requestUrl.trim().length ) { const msg = "An error occurred while trying to parse validation payload." + 'requestUrl is a required parameter of type "string" and it cannot be an empty string.'; const e = new models.LiveValidationError(C.ErrorCodes.PotentialOperationSearchError.name, msg); throw e; } if ( requestMethod === undefined || requestMethod === null || typeof requestMethod.valueOf() !== "string" || !requestMethod.trim().length ) { const msg = "An error occurred while trying to parse validation payload." + 'requestMethod is a required parameter of type "string" and it cannot be an empty string.'; const e = new models.LiveValidationError(C.ErrorCodes.PotentialOperationSearchError.name, msg); throw e; } let queryStr; let apiVersion = ""; let resourceType = ""; let providerNamespace = ""; const parsedUrl = url.parse(requestUrl, true); const pathStr = parsedUrl.pathname || ""; if (pathStr !== "") { // Lower all the keys and values of query parameters before searching for `api-version` const queryObject = _.transform( parsedUrl.query, (obj: ParsedUrlQuery, value, key) => (obj[key.toLowerCase()] = _.isString(value) ? value.toLowerCase() : value) ); apiVersion = (queryObject["api-version"] || C.unknownApiVersion) as string; providerNamespace = getProviderFromPathTemplate(pathStr) || C.unknownResourceProvider; resourceType = utils.getResourceType(pathStr, providerNamespace); // Provider would be provider found from the path or Microsoft.Unknown providerNamespace = providerNamespace || C.unknownResourceProvider; if (providerNamespace === C.unknownResourceProvider) { apiVersion = C.unknownApiVersion; } providerNamespace = providerNamespace.toLowerCase(); apiVersion = apiVersion.toLowerCase(); queryStr = queryObject; requestMethod = requestMethod.toLowerCase(); } return { providerNamespace, resourceType, apiVersion, requestMethod: requestMethod as LowerHttpMethods, host: parsedUrl.host!, pathStr, query: queryStr, correlationId, requestUrl, }; };
the_stack
import { createContext, useCallback, useContext, useEffect, useState, } from 'react'; import { ViewOptions } from 'components'; import { useEventListener, useMKEventListener, useWindowContext } from 'hooks'; import * as ConversionUtils from 'utils/conversion'; import { IpodEvent } from 'utils/events'; import { useMusicKit, useSettings, useSpotifySDK, VOLUME_KEY } from '../'; const defaultPlatbackInfoState = { isPlaying: false, isPaused: false, isLoading: false, currentTime: 0, timeRemaining: 0, percent: 0, duration: 0, }; interface AudioPlayerState { playbackInfo: typeof defaultPlatbackInfoState; nowPlayingItem?: IpodApi.MediaItem; volume: number; play: (queueOptions: IpodApi.QueueOptions) => Promise<void>; pause: () => Promise<void>; seekToTime: (time: number) => void; setVolume: (volume: number) => void; updateNowPlayingItem: () => void; updatePlaybackInfo: () => void; } export const AudioPlayerContext = createContext<AudioPlayerState>({} as any); type AudioPlayerHook = AudioPlayerState; export const useAudioPlayer = (): AudioPlayerHook => { const state = useContext(AudioPlayerContext); return { ...state, }; }; interface Props { children: React.ReactNode; } export const AudioPlayerProvider = ({ children }: Props) => { const { windowStack } = useWindowContext(); const { service, isSpotifyAuthorized, isAppleAuthorized } = useSettings(); const { spotifyPlayer, accessToken, deviceId } = useSpotifySDK(); const { music } = useMusicKit(); const [volume, setVolume] = useState(0.5); const [nowPlayingItem, setNowPlayingItem] = useState<IpodApi.MediaItem>(); const [playbackInfo, setPlaybackInfo] = useState(defaultPlatbackInfoState); const playAppleMusic = useCallback( async (queueOptions: IpodApi.QueueOptions) => { if (!isAppleAuthorized) { throw new Error('Unable to play: Not authorized'); } /** * MusicKit JS V3 doesn't seem to support passing in a single playlist id to the queue. * A workaround is to just grab the song ids instead. * */ const playlistSongs = queueOptions.playlist?.songs?.map(({ id }) => id); /** * MusicKit JS V3 expects only a single media type with no empty keys. * We're filtering out any keys that are undefined. * * @example { album: 'a.12345', startPosition: 0 } */ const queue = Object.fromEntries( Object.entries({ album: queueOptions.album?.id, songs: playlistSongs ?? queueOptions.songs?.map((song) => song.url), song: queueOptions.song?.id, startPosition: queueOptions.startPosition, }).filter(([_, value]) => value !== undefined) ); await music.setQueue({ ...queue }); await music.play(); }, [isAppleAuthorized, music] ); const playSpotify = useCallback( async (queueOptions: IpodApi.QueueOptions) => { if (!isSpotifyAuthorized) { throw new Error('Unable to play: Not authorized'); } // Spotify only accepts a list of song URIs, so we'll look through each media type provided for songs. const uris = [ ...(queueOptions.album?.songs?.map((song) => song.url) ?? []), ...(queueOptions.playlist?.songs?.map((song) => song.url) ?? []), ...(queueOptions.songs?.map((song) => song.url) ?? []), queueOptions.song?.url, ].filter((item) => !!item); setPlaybackInfo((prevState) => ({ ...prevState, isLoading: true, })); await fetch( `https://api.spotify.com/v1/me/player/play?device_id=${deviceId}`, { method: 'PUT', body: JSON.stringify({ uris, offset: { position: queueOptions.startPosition }, }), headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${accessToken}`, }, } ); setPlaybackInfo((prevState) => ({ ...prevState, isLoading: false, })); }, [accessToken, deviceId, isSpotifyAuthorized] ); const play = useCallback( async (queueOptions: IpodApi.QueueOptions) => { switch (service) { case 'apple': return playAppleMusic(queueOptions); case 'spotify': return playSpotify(queueOptions); default: throw new Error('Unable to play: service not specified'); } }, [playAppleMusic, playSpotify, service] ); const pause = useCallback(async () => { switch (service) { case 'apple': return spotifyPlayer.pause(); case 'spotify': return music.pause(); default: throw new Error('Unable to play: service not specified'); } }, [music, service, spotifyPlayer]); const togglePlayPause = useCallback(async () => { const activeWindow = windowStack[windowStack.length - 1]; // Don't toggle play/pause when using the on-screen keyboard. if (!nowPlayingItem || activeWindow.id === ViewOptions.keyboard.id) { return; } switch (service) { case 'apple': // TODO: Update types for MusicKit V3 if ((music as any).isPlaying) { music.pause(); // TODO: Update types for MusicKit V3 } else if (!(music as any).isPlaying) { music.play(); } break; case 'spotify': spotifyPlayer.togglePlay(); break; default: throw new Error('Unable to play: service not specified'); } }, [music, nowPlayingItem, service, spotifyPlayer, windowStack]); const skipNext = useCallback(async () => { if (!nowPlayingItem) { return; } setPlaybackInfo((prevState) => ({ ...prevState, isLoading: true, })); switch (service) { case 'apple': // TODO: Update types for MusicKit V3 if ((music as any).nowPlayingItem) { await music.skipToNextItem(); } break; case 'spotify': await spotifyPlayer.nextTrack(); break; default: throw new Error('Unable to play: service not specified'); } setPlaybackInfo((prevState) => ({ ...prevState, isLoading: false, })); }, [music, nowPlayingItem, service, spotifyPlayer]); const skipPrevious = useCallback(async () => { if (!nowPlayingItem) { return; } setPlaybackInfo((prevState) => ({ ...prevState, isLoading: true, })); switch (service) { case 'apple': // TODO: Update types for MusicKit V3 if ((music as any).nowPlayingItem) { await music.skipToPreviousItem(); } break; case 'spotify': await spotifyPlayer.previousTrack(); break; default: throw new Error('Unable to play: service not specified'); } setPlaybackInfo((prevState) => ({ ...prevState, isLoading: false, })); }, [music, nowPlayingItem, service, spotifyPlayer]); const updateNowPlayingItem = useCallback(async () => { let mediaItem: IpodApi.MediaItem | undefined; // TODO: Update types for MusicKit V3 if (service === 'apple' && (music as any).nowPlayingItem) { // TODO: Update types for MusicKit V3 mediaItem = ConversionUtils.convertAppleMediaItem( (music as any).nowPlayingItem ); } else if (service === 'spotify') { const state = await spotifyPlayer.getCurrentState(); if (state) { mediaItem = ConversionUtils.convertSpotifyMediaItem(state); } } setNowPlayingItem(mediaItem); }, [music, service, spotifyPlayer]); const handleApplePlaybackStateChange = useCallback( ({ state }: { state: MusicKit.PlaybackStates }) => { let isLoading = false; let isPlaying = false; let isPaused = false; switch (state) { case MusicKit.PlaybackStates.playing: isPlaying = true; break; case MusicKit.PlaybackStates.paused: isPaused = true; break; case MusicKit.PlaybackStates.loading: case MusicKit.PlaybackStates.waiting: case MusicKit.PlaybackStates.stalled: isLoading = true; break; } setPlaybackInfo((prevState) => ({ ...prevState, isPlaying, isPaused, isLoading, })); updateNowPlayingItem(); }, [updateNowPlayingItem] ); const handleSpotifyPlaybackStateChange = useCallback( (state?: Spotify.PlaybackState) => { if (!state) { return; } if (state.disallows.resuming) { setPlaybackInfo((prevState) => ({ ...prevState, isPlaying: true, isPaused: false, isLoading: false, })); } else if (state.paused) { setPlaybackInfo((prevState) => ({ ...prevState, isPlaying: false, isPaused: true, isLoading: false, })); } updateNowPlayingItem(); }, [updateNowPlayingItem] ); const updatePlaybackInfo = useCallback(async () => { if (service === 'apple') { setPlaybackInfo((prevState) => ({ ...prevState, // TODO: Update types for MusicKit V3 currentTime: (music as any).currentPlaybackTime, timeRemaining: (music as any).currentPlaybackTimeRemaining, percent: (music as any).currentPlaybackProgress * 100, duration: (music as any).currentPlaybackDuration, })); } else if (service === 'spotify') { const { position, duration } = (await spotifyPlayer.getCurrentState()) ?? {}; const currentTime = (position ?? 0) / 1000; const maxTime = (duration ?? 0) / 1000; const timeRemaining = maxTime - currentTime; const percent = Math.round((currentTime / maxTime) * 100); setPlaybackInfo((prevState) => ({ ...prevState, currentTime, timeRemaining, percent, duration: maxTime, })); } }, [music, service, spotifyPlayer]); const seekToTime = useCallback( async (time: number) => { if (service === 'apple') { // TODO: Update types for MusicKit V3 await (music as any).player.seekToTime(time); } else if (service === 'spotify') { // Seek to time (in ms) await spotifyPlayer.seek(time * 1000); } updatePlaybackInfo(); }, [music, service, spotifyPlayer, updatePlaybackInfo] ); const handleChangeVolume = useCallback( (newVolume: number) => { if (isSpotifyAuthorized) { spotifyPlayer.setVolume(newVolume); } if (isAppleAuthorized) { // TODO: Update types for MusicKit V3 (music as any).volume = newVolume; } localStorage.setItem(VOLUME_KEY, `${newVolume}`); setVolume(newVolume); }, [isAppleAuthorized, isSpotifyAuthorized, music, spotifyPlayer] ); useEventListener<IpodEvent>('playpauseclick', () => { togglePlayPause(); }); useEventListener<IpodEvent>('forwardclick', () => { skipNext(); }); useEventListener<IpodEvent>('backwardclick', () => { skipPrevious(); }); // Apple playback event listeners useMKEventListener('playbackStateDidChange', handleApplePlaybackStateChange); useMKEventListener('queuePositionDidChange', updateNowPlayingItem); useEffect(() => { if (isSpotifyAuthorized) { spotifyPlayer.addListener( 'player_state_changed', handleSpotifyPlaybackStateChange ); const savedVolume = parseFloat(localStorage.getItem(VOLUME_KEY) ?? '0.5'); handleChangeVolume(savedVolume); return () => spotifyPlayer.removeListener( 'player_state_changed', handleSpotifyPlaybackStateChange ); } }, [ handleChangeVolume, handleSpotifyPlaybackStateChange, isSpotifyAuthorized, spotifyPlayer, ]); useEffect(() => { if (isAppleAuthorized) { const savedVolume = parseFloat(localStorage.getItem(VOLUME_KEY) ?? '0.5'); handleChangeVolume(savedVolume); } }, [handleChangeVolume, isAppleAuthorized]); return ( <AudioPlayerContext.Provider value={{ playbackInfo, nowPlayingItem, volume, play, pause, seekToTime, setVolume: handleChangeVolume, updateNowPlayingItem, updatePlaybackInfo, }} > {children} </AudioPlayerContext.Provider> ); }; export default useAudioPlayer;
the_stack
import { configureTestSuite } from '../../test-utils/configure-suite'; import { TestBed, tick, fakeAsync, ComponentFixture } from '@angular/core/testing'; import { By } from '@angular/platform-browser'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { IgxHierarchicalGridModule } from './public_api'; import { IgxHierarchicalGridComponent } from './hierarchical-grid.component'; import { wait, UIInteractions } from '../../test-utils/ui-interactions.spec'; import { SortingDirection } from '../../data-operations/sorting-expression.interface'; import { DefaultSortingStrategy } from '../../data-operations/sorting-strategy'; import { IgxColumnMovingDragDirective } from '../moving/moving.drag.directive'; import { IgxHierarchicalRowComponent } from './hierarchical-row.component'; import { IgxChildGridRowComponent } from './child-grid-row.component'; import { IgxStringFilteringOperand } from '../../data-operations/filtering-condition'; import { take } from 'rxjs/operators'; import { IgxIconModule } from '../../icon/public_api'; import { IgxHierarchicalGridTestBaseComponent, IgxHierarchicalGridTestCustomToolbarComponent, IgxHierarchicalGridWithTransactionProviderComponent } from '../../test-utils/hierarchical-grid-components.spec'; import { GridFunctions, GridSelectionFunctions } from '../../test-utils/grid-functions.spec'; import { HierarchicalGridFunctions } from '../../test-utils/hierarchical-grid-functions.spec'; import { GridSelectionMode, ColumnPinningPosition, RowPinningPosition } from '../common/enums'; import { IgxPaginatorComponent } from '../../paginator/paginator.component'; import { SampleTestData } from '../../test-utils/sample-test-data.spec'; describe('IgxHierarchicalGrid Integration #hGrid', () => { let fixture: ComponentFixture<IgxHierarchicalGridTestBaseComponent>; let hierarchicalGrid: IgxHierarchicalGridComponent; const DEBOUNCE_TIME = 30; const FILTERING_ROW_CLASS = 'igx-grid-filtering-row'; const FILTERING_CELL_CLASS = 'igx-grid-filtering-cell'; configureTestSuite((() => { TestBed.configureTestingModule({ declarations: [ IgxHierarchicalGridTestBaseComponent, IgxHierarchicalGridTestCustomToolbarComponent, IgxHierarchicalGridWithTransactionProviderComponent ], imports: [ NoopAnimationsModule, IgxHierarchicalGridModule, IgxIconModule] }); })); beforeEach(fakeAsync(() => { fixture = TestBed.createComponent(IgxHierarchicalGridTestBaseComponent); tick(); fixture.detectChanges(); hierarchicalGrid = fixture.componentInstance.hgrid; })); describe('MCH', () => { it('should allow declaring column groups.', fakeAsync(() => { const expectedColumnGroups = 1; const expectedLevel = 1; expect(hierarchicalGrid.columnList.filter(col => col.columnGroup).length).toEqual(expectedColumnGroups); expect(hierarchicalGrid.getColumnByName('ProductName').level).toEqual(expectedLevel); expect(GridFunctions.getColumnHeaders(fixture).length).toEqual(3); const firstRow = hierarchicalGrid.dataRowList.first; // the first row's cell should contain an expand indicator expect(HierarchicalGridFunctions.hasExpander(firstRow)).toBeTruthy(); hierarchicalGrid.expandRow(firstRow.rowID); tick(DEBOUNCE_TIME); fixture.detectChanges(); const childGrid = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; expect(childGrid.columnList.filter(col => col.columnGroup).length).toEqual(expectedColumnGroups); expect(childGrid.getColumnByName('ProductName').level).toEqual(expectedLevel); expect(GridFunctions.getColumnHeaders(fixture).length).toEqual(6); })); it('should apply height correctly with and without filtering', fakeAsync(() => { let filteringCells = fixture.debugElement.queryAll(By.css(FILTERING_CELL_CLASS)); expect(hierarchicalGrid.nativeElement.offsetHeight).toBe(600); hierarchicalGrid.height = '800px'; tick(); fixture.detectChanges(); expect(hierarchicalGrid.nativeElement.offsetHeight).toBe(800); expect(filteringCells.length).toBe(3); hierarchicalGrid.allowFiltering = false; fixture.detectChanges(); expect(hierarchicalGrid.nativeElement.offsetHeight).toBe(800); filteringCells = fixture.debugElement.queryAll(By.css(FILTERING_CELL_CLASS)); expect(filteringCells.length).toBe(0); })); }); describe('Selection', () => { it('should allow only one cell to be selected in the whole hierarchical grid.', (async () => { let firstRow = hierarchicalGrid.dataRowList.first as IgxHierarchicalRowComponent; hierarchicalGrid.expandRow(firstRow.rowID); expect(firstRow.expanded).toBeTruthy(); let fCell = firstRow.cells.toArray()[0]; // select parent cell GridFunctions.focusCell(fixture, fCell); await wait(100); fixture.detectChanges(); expect(fCell.selected).toBeTruthy(); const childGrid = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; const fChildCell = childGrid.dataRowList.first.cells.first; // select child cell GridFunctions.focusCell(fixture, fChildCell); await wait(100); fixture.detectChanges(); expect(fChildCell.selected).toBeTruthy(); expect(fCell.selected).toBeFalsy(); // select parent cell firstRow = hierarchicalGrid.dataRowList.toArray()[0] as IgxHierarchicalRowComponent; fCell = firstRow.cells.toArray()[0]; GridFunctions.focusCell(fixture, fCell); await wait(100); fixture.detectChanges(); expect(fChildCell.selected).toBeFalsy(); expect(fCell.selected).toBeTruthy(); })); }); describe('Updating', () => { it(`should have separate instances of updating service for parent and children and the same for children of the same island`, fakeAsync(() => { const firstLayoutInstances: IgxHierarchicalGridComponent[] = []; hierarchicalGrid.childLayoutList.first.gridCreated.pipe(take(2)).subscribe((args) => { firstLayoutInstances.push(args.grid); }); const dataRows = hierarchicalGrid.dataRowList.toArray(); // expand 1st row hierarchicalGrid.expandRow(dataRows[0].rowID); tick(DEBOUNCE_TIME); fixture.detectChanges(); // expand 2nd row hierarchicalGrid.expandRow(dataRows[1].rowID); tick(DEBOUNCE_TIME); fixture.detectChanges(); // test instances expect(firstLayoutInstances.length).toEqual(2); expect(hierarchicalGrid.transactions).not.toBe(firstLayoutInstances[0].transactions); expect(firstLayoutInstances[0].transactions).not.toBe(firstLayoutInstances[1].transactions); })); it('should contain all transactions for a row island', fakeAsync(() => { const firstLayoutInstances: IgxHierarchicalGridComponent[] = []; hierarchicalGrid.childLayoutList.first.gridCreated.pipe(take(2)).subscribe((args) => { firstLayoutInstances.push(args.grid); }); hierarchicalGrid.batchEditing = true; tick(); fixture.detectChanges(); const dataRows = hierarchicalGrid.dataRowList.toArray(); // expand 1st row hierarchicalGrid.expandRow(dataRows[0].rowID); tick(); fixture.detectChanges(); // expand 2nd row hierarchicalGrid.expandRow(dataRows[1].rowID); tick(); fixture.detectChanges(); firstLayoutInstances[0].updateRow({ ProductName: 'Changed' }, '00'); firstLayoutInstances[1].updateRow({ ProductName: 'Changed' }, '10'); expect(hierarchicalGrid.transactions.getTransactionLog().length).toEqual(0); expect(firstLayoutInstances[0].transactions.getTransactionLog().length).toEqual(1); expect(fixture.componentInstance.rowIsland.transactions.getTransactionLog().length).toEqual(0); })); it('should remove expand indicator for uncommitted added rows', fakeAsync(() => { hierarchicalGrid.batchEditing = true; fixture.detectChanges(); hierarchicalGrid.data = hierarchicalGrid.data.slice(0, 3); fixture.detectChanges(); hierarchicalGrid.addRow({ ID: -1, ProductName: 'Name1' }); fixture.detectChanges(); const rows = HierarchicalGridFunctions.getHierarchicalRows(fixture); const lastRow = rows[rows.length - 1]; expect(lastRow.query(By.css('igx-icon')).nativeElement).toHaveClass('igx-icon--inactive'); hierarchicalGrid.transactions.commit(hierarchicalGrid.data); fixture.detectChanges(); expect(lastRow.query(By.css('igx-icon')).nativeElement).not.toHaveClass('igx-icon--inactive'); })); it('should now allow expanding uncommitted added rows', fakeAsync(() => { /* using the API here assumes keyboard interactions to expand/collapse would also be blocked */ hierarchicalGrid.batchEditing = true; fixture.detectChanges(); hierarchicalGrid.data = hierarchicalGrid.data.slice(0, 3); fixture.detectChanges(); hierarchicalGrid.addRow({ ID: -1, ProductName: 'Name1' }); fixture.detectChanges(); const dataRows = hierarchicalGrid.dataRowList; hierarchicalGrid.expandRow(dataRows.last.rowID); let childRows = fixture.debugElement.queryAll(By.directive(IgxChildGridRowComponent)); expect(childRows.length).toEqual(0); hierarchicalGrid.transactions.commit(hierarchicalGrid.data); fixture.detectChanges(); hierarchicalGrid.expandRow(dataRows.last.rowID); tick(DEBOUNCE_TIME); fixture.detectChanges(); childRows = fixture.debugElement.queryAll(By.directive(IgxChildGridRowComponent)); expect(childRows.length).toEqual(1); })); it('should revert changes when transactions are cleared for child grids', fakeAsync(() => { hierarchicalGrid.batchEditing = true; fixture.detectChanges(); let childGrid; hierarchicalGrid.childLayoutList.first.gridCreated.pipe(take(1)).subscribe((args) => { childGrid = args.grid; }); // expand first row hierarchicalGrid.expandRow(hierarchicalGrid.dataRowList.first.rowID); childGrid.updateRow({ ProductName: 'Changed' }, '00'); fixture.detectChanges(); expect(childGrid.gridAPI.get_cell_by_index(0, 'ProductName').nativeElement.innerText).toEqual('Changed'); childGrid.transactions.clear(); fixture.detectChanges(); expect(childGrid.gridAPI.get_cell_by_index(0, 'ProductName').nativeElement.innerText).toEqual('Product: A0'); })); it('should return correctly the rowData', () => { hierarchicalGrid.primaryKey = 'ID'; fixture.detectChanges(); const rowData = hierarchicalGrid.getRowByKey('2').data; expect(hierarchicalGrid.getRowData('2')).toEqual(rowData); hierarchicalGrid.sort({ fieldName: 'ChildLevels', dir: SortingDirection.Desc, ignoreCase: true }); fixture.detectChanges(); expect(hierarchicalGrid.getRowData('2')).toEqual(rowData); expect(hierarchicalGrid.getRowData('101')).toEqual({}); hierarchicalGrid.filter('ID', '1', IgxStringFilteringOperand.instance().condition('startsWith')); fixture.detectChanges(); expect(hierarchicalGrid.getRowData('2')).toEqual(rowData); expect(hierarchicalGrid.getRowData('101')).toEqual({}); }); it('should respect transaction service that is provided in the providers array', fakeAsync(() => { fixture = TestBed.createComponent(IgxHierarchicalGridWithTransactionProviderComponent); tick(); fixture.detectChanges(); hierarchicalGrid = fixture.componentInstance.hgrid; expect(hierarchicalGrid.transactions.enabled).toBeTruthy(); expect(hierarchicalGrid.batchEditing).toBeFalsy(); let childGrid: IgxHierarchicalGridComponent; hierarchicalGrid.childLayoutList.first.gridCreated.pipe(take(1)).subscribe((args) => { childGrid = args.grid; }); // expand first row hierarchicalGrid.expandRow(hierarchicalGrid.dataRowList.first.rowID); expect(childGrid).toBeDefined(); expect(childGrid.transactions.enabled).toBeTruthy(); childGrid.updateRow({ ProductName: 'Changed' }, '00'); expect(childGrid.transactions.getAggregatedChanges(false).length).toBe(1); })); }); describe('Sorting', () => { it('should display correct child data for expanded row after sorting.', fakeAsync(() => { /* this test doesn't need scrolling as it only cares about the child grid getting assigned to the correct parent */ hierarchicalGrid.data = hierarchicalGrid.data.slice(0, 3); fixture.detectChanges(); // expand first row hierarchicalGrid.expandRow(hierarchicalGrid.dataRowList.first.rowID); hierarchicalGrid.sort({ fieldName: 'ID', dir: SortingDirection.Desc, ignoreCase: false, strategy: DefaultSortingStrategy.instance() }); fixture.detectChanges(); const childGrid = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; const firstChildCell = childGrid.dataRowList.first.cells.first; expect(hierarchicalGrid.hgridAPI.get_row_by_index(3) instanceof IgxChildGridRowComponent).toBeTruthy(); expect(childGrid.data).toBe(fixture.componentInstance.data[0]['childData']); expect(firstChildCell.value).toBe('00'); })); it('should allow sorting via headers in child grids', fakeAsync(() => { // expand first row hierarchicalGrid.expandRow(hierarchicalGrid.dataRowList.first.rowID); // enable sorting const childGrid = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; childGrid.columnList.first.sortable = true; fixture.detectChanges(); const childHeader = GridFunctions.getColumnHeader('ID', fixture, childGrid); GridFunctions.clickHeaderSortIcon(childHeader); fixture.detectChanges(); GridFunctions.clickHeaderSortIcon(childHeader); fixture.detectChanges(); expect(childGrid.dataRowList.first.cells.first.value).toBe('09'); const icon = GridFunctions.getHeaderSortIcon(childHeader); expect(icon).not.toBeNull(); expect(icon.nativeElement.textContent.toLowerCase().trim()).toBe('arrow_downward'); })); }); describe('Filtering', () => { it('should enable filter-row for root and child grids', fakeAsync(() => { let filteringCells = fixture.debugElement.queryAll(By.css(FILTERING_CELL_CLASS)); expect(filteringCells.length).toEqual(3); GridFunctions.clickFilterCellChipUI(fixture, 'ID'); expect(document.querySelectorAll(FILTERING_ROW_CLASS).length).toEqual(1); // expand first row hierarchicalGrid.expandRow(hierarchicalGrid.dataRowList.first.rowID); filteringCells = fixture.debugElement.queryAll(By.css(FILTERING_CELL_CLASS)); expect(filteringCells.length).toEqual(6); GridFunctions.clickFilterCellChipUI(fixture, 'ProductName', hierarchicalGrid.hgridAPI.getChildGrids(false)[0]); expect(document.querySelectorAll(FILTERING_ROW_CLASS).length).toEqual(2); })); it('should not lose child grid states after filtering in parent grid.', fakeAsync(() => { // expand first row hierarchicalGrid.expandRow(hierarchicalGrid.dataRowList.first.rowID); tick(DEBOUNCE_TIME); fixture.detectChanges(); let childGrid = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; let firstChildCell = childGrid.dataRowList.first.cells.first; UIInteractions.simulateClickAndSelectEvent(firstChildCell); tick(DEBOUNCE_TIME); fixture.detectChanges(); expect(firstChildCell.selected).toBe(true); // apply some filter hierarchicalGrid.filter('ID', '0', IgxStringFilteringOperand.instance().condition('contains'), true); expect(hierarchicalGrid.getRowByIndex(0).expanded).toBe(true); expect(hierarchicalGrid.hgridAPI.get_row_by_index(1) instanceof IgxChildGridRowComponent).toBeTruthy(); childGrid = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; firstChildCell = childGrid.dataRowList.first.cells.first; expect(firstChildCell.selected).toBe(true); })); it('should show empty filter message when there are no records matching the filter', fakeAsync(() => { fixture.componentInstance.data = []; fixture.detectChanges(); const gridBody = fixture.debugElement.query(By.css('.igx-grid__tbody-content')); expect(gridBody.nativeElement.innerText).toMatch(hierarchicalGrid.emptyGridMessage); fixture.componentInstance.data = SampleTestData.generateHGridData(40, 3); fixture.detectChanges(); hierarchicalGrid.filter('ID', '123450', IgxStringFilteringOperand.instance().condition('contains'), true); fixture.detectChanges(); expect(gridBody.nativeElement.innerText).toMatch(hierarchicalGrid.emptyFilteredGridMessage); })); it('should apply classes to the header when filter row is visible', fakeAsync(() => { hierarchicalGrid.rowSelection = GridSelectionMode.multiple; fixture.detectChanges(); const headerExpander: HTMLElement = HierarchicalGridFunctions.getExpander(fixture); const headerCheckbox: HTMLElement = GridSelectionFunctions.getRowCheckboxDiv(fixture.nativeElement); expect(HierarchicalGridFunctions.isExpander(headerExpander, '--push')).toBeFalsy(); expect(GridSelectionFunctions.isCheckbox(headerCheckbox, '--push')).toBeFalsy(); // open filter row GridFunctions.clickFilterCellChipUI(fixture, 'ID'); expect(HierarchicalGridFunctions.isExpander(headerExpander, '--push')).toBeTruthy(); expect(GridSelectionFunctions.isCheckbox(headerCheckbox, '--push')).toBeTruthy(); })); }); describe('Summaries', () => { const SUMMARIES_MARGIN_CLASS = '.igx-grid__summaries-patch'; it('should allow defining summaries for child grid and child should be sized correctly.', fakeAsync(() => { // expand first row hierarchicalGrid.expandRow(hierarchicalGrid.dataRowList.first.rowID); // summaries seem to require this additional change detection call with Ivy disabled to display for the child grid fixture.detectChanges(); const childGrid = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; const expander = childGrid.dataRowList.first.expander; // Expect expansion cell to be rendered and sized the same as the expansion cell inside the grid const summaryRow = childGrid.summariesRowList.first.nativeElement; const summaryRowIndentation = summaryRow.querySelector(SUMMARIES_MARGIN_CLASS); expect(summaryRow.children.length).toEqual(2); expect(summaryRowIndentation.offsetWidth).toEqual(expander.nativeElement.offsetWidth); const gridHeight = childGrid.nativeElement.offsetHeight; const childElements: HTMLElement[] = Array.from(childGrid.nativeElement.children); const elementsHeight = childElements.map(elem => elem.offsetHeight).reduce((total, height) => total + height, 0); // Expect the combined height of all elements (header, body, footer etc) to equal the calculated height of the grid. expect(elementsHeight).toEqual(gridHeight); // expand first row of child childGrid.expandRow(childGrid.dataRowList.first.rowID); const grandChild = childGrid.hgridAPI.getChildGrids(false)[0]; const grandChildSummaryRow = grandChild.summariesRowList.first.nativeElement; const childSummaryRowIndentation = grandChildSummaryRow.querySelector(SUMMARIES_MARGIN_CLASS); expect(grandChildSummaryRow.children.length).toEqual(1); expect(childSummaryRowIndentation).toBeNull(); })); it('should size summaries with row selectors for parent and child grids correctly.', fakeAsync(() => { hierarchicalGrid.rowSelection = GridSelectionMode.multiple; fixture.detectChanges(); // expand first row hierarchicalGrid.expandRow(hierarchicalGrid.dataRowList.first.rowID); // summaries seem to require this additional change detection call with Ivy disabled to display for the child grid fixture.detectChanges(); const rootExpander = (hierarchicalGrid.dataRowList.first as IgxHierarchicalRowComponent).expander; const rootCheckbox = hierarchicalGrid.headerSelectorContainer; const rootSummaryRow = hierarchicalGrid.summariesRowList.first.nativeElement; const rootSummaryIndentation = rootSummaryRow.querySelector(SUMMARIES_MARGIN_CLASS); expect(rootSummaryRow.children.length).toEqual(2); expect(rootSummaryIndentation.offsetWidth) .toEqual(rootExpander.nativeElement.offsetWidth + rootCheckbox.nativeElement.offsetWidth); const childGrid = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; const expander = childGrid.dataRowList.first.expander; // Expect expansion cell to be rendered and sized the same as the expansion cell inside the grid const summaryRow = childGrid.summariesRowList.first.nativeElement; const childSummaryIndentation = summaryRow.querySelector(SUMMARIES_MARGIN_CLASS); expect(summaryRow.children.length).toEqual(2); expect(childSummaryIndentation.offsetWidth).toEqual(expander.nativeElement.offsetWidth); })); it('should render summaries for column inside a column group.', fakeAsync(() => { fixture.componentInstance.rowIsland.childColumns.first.hasSummary = false; fixture.componentInstance.rowIsland.childColumns.last.hasSummary = true; fixture.detectChanges(); // expand first row hierarchicalGrid.expandRow(hierarchicalGrid.dataRowList.first.rowID); // summaries seem to require this additional change detection call with Ivy disabled to display for the child grid fixture.detectChanges(); const childGrid = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; const summaryRow = childGrid.summariesRowList.first; expect(summaryRow.nativeElement.children.length).toEqual(2); expect(summaryRow.summaryCells.length).toEqual(3); })); }); describe('Paging', () => { it('should work on data records only when paging is enabled and should not be affected by child grid rows.', fakeAsync(() => { fixture.componentInstance.paging = true; fixture.detectChanges(); hierarchicalGrid.notifyChanges(); fixture.detectChanges(); expect(hierarchicalGrid.dataView.length).toEqual(15); const dataRows = hierarchicalGrid.dataRowList.toArray(); // expand 1st row hierarchicalGrid.expandRow(dataRows[0].rowID); tick(DEBOUNCE_TIME); fixture.detectChanges(); expect(hierarchicalGrid.dataView.length).toEqual(16); // expand 2nd row hierarchicalGrid.expandRow(dataRows[1].rowID); tick(DEBOUNCE_TIME); fixture.detectChanges(); expect(hierarchicalGrid.dataView.length).toEqual(17); expect(hierarchicalGrid.dataView.pop().ID).toEqual('14'); })); it('should preserve expansion states after changing pages.', fakeAsync(() => { fixture.componentInstance.paging = true; fixture.detectChanges(); let dataRows = hierarchicalGrid.dataRowList.toArray() as IgxHierarchicalRowComponent[]; // expand 1st row hierarchicalGrid.expandRow(dataRows[0].rowID); // expand 2nd row hierarchicalGrid.expandRow(dataRows[1].rowID); expect(dataRows[0].expanded).toBeTruthy(); expect(dataRows[1].expanded).toBeTruthy(); expect(hierarchicalGrid.dataView.length).toEqual(17); let childGrids = hierarchicalGrid.hgridAPI.getChildGrids(false); expect(childGrids.length).toEqual(2); expect(childGrids[0].dataRowList.first.cells.first.value).toEqual('00'); // Go to next page GridFunctions.navigateToNextPage(hierarchicalGrid.nativeElement); fixture.detectChanges(); dataRows = hierarchicalGrid.dataRowList.toArray() as IgxHierarchicalRowComponent[]; expect(dataRows[0].cells.first.value).toEqual('15'); expect(dataRows[0].expanded).toBeFalsy(); expect(dataRows[1].expanded).toBeFalsy(); expect(hierarchicalGrid.dataView.length).toEqual(15); childGrids = hierarchicalGrid.hgridAPI.getChildGrids(false); // Return to previous page GridFunctions.navigateToPrevPage(hierarchicalGrid.nativeElement); fixture.detectChanges(); dataRows = hierarchicalGrid.dataRowList.toArray() as IgxHierarchicalRowComponent[]; expect(dataRows[0].cells.first.value).toEqual('0'); expect(dataRows[0].expanded).toBeTruthy(); expect(dataRows[1].expanded).toBeTruthy(); expect(hierarchicalGrid.dataView.length).toEqual(17); childGrids = hierarchicalGrid.hgridAPI.getChildGrids(false); expect(childGrids[0].dataRowList.first.cells.first.value).toEqual('00'); })); it('should allow scrolling to the last row after page size has been changed and rows are expanded.', fakeAsync(() => { /* it's better to avoid scrolling and only check for scrollbar availability */ /* scrollbar doesn't update its visibility in fakeAsync tests */ fixture.componentInstance.paging = true; fixture.detectChanges(); hierarchicalGrid.perPage = 20; hierarchicalGrid.height = '800px'; fixture.componentInstance.rowIsland.height = '200px'; tick(); fixture.detectChanges(); expect(hierarchicalGrid.hasVerticalScroll()).toBeTruthy(); hierarchicalGrid.perPage = 5; tick(DEBOUNCE_TIME); fixture.detectChanges(); expect(hierarchicalGrid.hasVerticalScroll()).toBeFalsy(); const dataRows = hierarchicalGrid.dataRowList.toArray() as IgxHierarchicalRowComponent[]; // expand 1st row hierarchicalGrid.expandRow(dataRows[0].rowID); tick(DEBOUNCE_TIME); fixture.detectChanges(); expect(hierarchicalGrid.hasVerticalScroll()).toBeFalsy(); expect(hierarchicalGrid.hgridAPI.get_row_by_index(1) instanceof IgxChildGridRowComponent).toBeTruthy(); // expand 3rd row hierarchicalGrid.expandRow(dataRows[3].rowID); tick(DEBOUNCE_TIME); fixture.detectChanges(); expect(hierarchicalGrid.hgridAPI.get_row_by_index(4) instanceof IgxChildGridRowComponent).toBeTruthy(); })); it('should correctly hide/show vertical scrollbar after page is changed.', (async () => { /* scrollbar doesn't update its visibility in fakeAsync tests */ fixture.componentInstance.paging = true; fixture.detectChanges(); hierarchicalGrid.perPage = 5; fixture.detectChanges(); expect(hierarchicalGrid.hasVerticalScroll()).toBeFalsy(); // expand 1st row hierarchicalGrid.expandRow(hierarchicalGrid.dataRowList.first.rowID); await wait(DEBOUNCE_TIME); expect(hierarchicalGrid.hasVerticalScroll()).toBeTruthy(); // change page hierarchicalGrid.page = 1; fixture.detectChanges(); await wait(DEBOUNCE_TIME); expect(hierarchicalGrid.hasVerticalScroll()).toBeFalsy(); // change page hierarchicalGrid.page = 0; fixture.detectChanges(); await wait(DEBOUNCE_TIME); expect(hierarchicalGrid.hasVerticalScroll()).toBeTruthy(); })); }); describe('Hiding', () => { it('should leave no feature UI elements when all columns are hidden', fakeAsync(() => { fixture.componentInstance.paging = true; fixture.detectChanges(); hierarchicalGrid.rowSelection = GridSelectionMode.multiple; hierarchicalGrid.rowDraggable = true; tick(DEBOUNCE_TIME); fixture.detectChanges(); let headers = GridFunctions.getColumnHeaders(fixture); let gridRows = HierarchicalGridFunctions.getHierarchicalRows(fixture); let paging = GridFunctions.getGridPaginator(fixture); let rowSelectors = GridSelectionFunctions.getCheckboxes(fixture); let dragIndicators = GridFunctions.getDragIndicators(fixture); let expander = HierarchicalGridFunctions.getExpander(fixture, '[hidden]'); expect(headers.length).toBeGreaterThan(0); expect(gridRows.length).toBeGreaterThan(0); expect(paging).not.toBeNull(); expect(rowSelectors.length).toBeGreaterThan(0); expect(dragIndicators.length).toBeGreaterThan(0); // this check executes correctly on Ivy only // expect(Object.keys(expanders[0].attributes)).not.toContain('hidden'); expect(expander).toBeNull(); expect(hierarchicalGrid.hasVerticalScroll()).toBeTruthy(); hierarchicalGrid.columnList.forEach((col) => col.hidden = true); tick(DEBOUNCE_TIME); fixture.detectChanges(); headers = GridFunctions.getColumnHeaders(fixture); gridRows = HierarchicalGridFunctions.getHierarchicalRows(fixture); paging = GridFunctions.getGridPaginator(fixture); rowSelectors = GridSelectionFunctions.getCheckboxes(fixture); dragIndicators = GridFunctions.getDragIndicators(fixture); expander = HierarchicalGridFunctions.getExpander(fixture, '[hidden]'); expect(headers.length).toBe(0); expect(gridRows.length).toBe(0); expect(paging).toBeNull(); expect(rowSelectors.length).toBe(0); expect(dragIndicators.length).toBe(0); // this check executes correctly on Ivy only // expect(Object.keys(expanders[0].attributes)).toContain('hidden'); expect(expander).not.toBeNull(); expect(hierarchicalGrid.hasVerticalScroll()).toBeFalsy(); })); }); describe('Toolbar', () => { it('should be displayed correctly for child layout and hiding should apply to the correct child.', fakeAsync(() => { pending('Change test for new scrollbar structure'); hierarchicalGrid.expandRow(hierarchicalGrid.dataRowList.first.rowID); tick(); fixture.detectChanges(); const childGrid = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; const toolbar = childGrid.nativeElement.querySelector('igx-grid-toolbar'); const hidingUI = toolbar.querySelector('igx-grid-toolbar-hiding'); // Check if visible columns and headers are rendered correctly expect(childGrid.visibleColumns.length).toEqual(4); // Check if hiding button & dropdown are init expect(toolbar).toBeDefined(); expect(hidingUI).toBeDefined(); hidingUI.click(); tick(); fixture.detectChanges(); // // Check if the child grid columns are the one used by the hiding UI // childGrid.visibleColumns.forEach((column, index) => expect(toolbar.columnHidingUI.columns[index]).toEqual(column)); // // Instead of clicking we can just toggle the checkbox // toolbar.columnHidingUI.columnItems.toArray()[2].toggle(); // fixture.detectChanges(); // And it should hide the column of the child grid // expect(childGrid.visibleColumns.length).toEqual(3); })); it('should be displayed correctly for child layout and pinning should apply to the correct child.', fakeAsync(() => { pending('Change test for new scrollbar structure'); hierarchicalGrid.expandRow(hierarchicalGrid.dataRowList.first.rowID); const childGrid = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; const toolbar = childGrid.nativeElement.querySelector('igx-grid-toolbar'); // Check if visible columns and headers are rendered correctly expect(childGrid.visibleColumns.length).toEqual(4); // Check if pinning button & dropdown are init expect(toolbar).toBeDefined(); expect(toolbar.querySelector('igx-grid-toolbar-pinning')).toBeDefined(); // Check if the child grid columns are the one used by the pinning UI childGrid.visibleColumns.forEach((column, index) => expect(toolbar.columnPinningUI.columns[index]).toEqual(column)); // Instead of clicking we can just toggle the checkbox toolbar.columnPinningUI.columnItems.toArray()[1].toggle(); fixture.detectChanges(); // Check pinned state expect(childGrid.getColumnByName('ChildLevels').pinned).toBeTruthy(); expect(childGrid.getColumnByName('ProductName').pinned).toBeTruthy(); expect(childGrid.getColumnByName('ID').pinned).toBeFalsy(); })); it('should read from custom templates per level', fakeAsync(() => { pending('Change test for new scrollbar structure'); fixture = TestBed.createComponent(IgxHierarchicalGridTestCustomToolbarComponent); tick(); fixture.detectChanges(); hierarchicalGrid = fixture.componentInstance.hgrid; hierarchicalGrid.expandRow(hierarchicalGrid.dataRowList.first.rowID); tick(DEBOUNCE_TIME); fixture.detectChanges(); const toolbars = fixture.debugElement.queryAll(By.css('igx-grid-toolbar')); expect(toolbars.length).toEqual(3); expect(toolbars[0].query(By.css('button')).nativeElement.innerText.trim()).toEqual('Parent Button'); expect(toolbars[1].query(By.css('button')).nativeElement.innerText.trim()).toEqual('Child 1 Button'); expect(toolbars[2].query(By.css('button')).nativeElement.innerText.trim()).toEqual('Child 2 Button'); })); it('should have same width as the grid whole width', fakeAsync(() => { fixture = TestBed.createComponent(IgxHierarchicalGridTestCustomToolbarComponent); tick(); fixture.detectChanges(); hierarchicalGrid = fixture.componentInstance.hgrid; const toolbar = fixture.debugElement.query(By.css('igx-grid-toolbar')); expect(toolbar.nativeElement.offsetWidth).toEqual(hierarchicalGrid.nativeElement.offsetWidth); })); }); describe('Moving', () => { // TODO: Revise this test! That DOM digging is sloppy xit('should not be possible to drag move a column from another grid.', (async () => { hierarchicalGrid.expandRow(hierarchicalGrid.dataRowList.first.rowID); const childGrids = fixture.debugElement.queryAll(By.css('igx-child-grid-row')); const childHeader = childGrids[0].queryAll(By.css('igx-grid-header'))[0].nativeElement; const mainHeaders = hierarchicalGrid.nativeElement .querySelectorAll('igx-grid-header[ng-reflect-grid-i-d="' + hierarchicalGrid.id + '"]'); const childHeaderX = childHeader.getBoundingClientRect().x + childHeader.getBoundingClientRect().width / 2; const childHeaderY = childHeader.getBoundingClientRect().y + childHeader.getBoundingClientRect().height / 2; const mainHeaderX = mainHeaders[0].getBoundingClientRect().x + mainHeaders[0].getBoundingClientRect().width / 2; const mainHeaderY = mainHeaders[0].getBoundingClientRect().y + mainHeaders[0].getBoundingClientRect().height / 2; UIInteractions.simulatePointerEvent('pointerdown', childHeader, childHeaderX, childHeaderY); await wait(); fixture.detectChanges(); UIInteractions.simulatePointerEvent('pointermove', childHeader, childHeaderX, childHeaderY - 10); await wait(100); fixture.detectChanges(); UIInteractions.simulatePointerEvent('pointermove', childHeader, mainHeaderX + 50, mainHeaderY); await wait(100); fixture.detectChanges(); // The moving indicator shouldn't show that a column can be moved. const childGroupHeader = childGrids[0].query(By.css('igx-grid-header')).injector.get(IgxColumnMovingDragDirective); const dragElem = childGroupHeader.ghostElement; const dragIcon = dragElem.querySelector('i'); expect(dragElem).toBeDefined(); expect(dragIcon.innerText.trim()).toEqual('block'); UIInteractions.simulatePointerEvent('pointerup', childHeader, mainHeaderX + 50, mainHeaderY); await wait(); fixture.detectChanges(); expect(hierarchicalGrid.columnList.length).toEqual(4); // expect(mainHeaders.length).toEqual(3); // expect(mainHeaders[0].children[0].innerText.trim()).toEqual('ID'); // expect(mainHeaders[1].children[0].innerText.trim()).toEqual('ChildLevels'); // expect(mainHeaders[2].children[0].innerText.trim()).toEqual('ProductName'); })); }); describe('Pinning', () => { it('should be possible by templating the header and getting column reference for child grid', fakeAsync(() => { hierarchicalGrid.expandRow(hierarchicalGrid.dataRowList.first.rowID); const childGrid = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; let childHeader = GridFunctions.getColumnHeaders(fixture)[3]; const firstHeaderIcon = childHeader.query(By.css('.igx-icon')); expect(GridFunctions.isHeaderPinned(childHeader.parent)).toBeFalsy(); expect(childGrid.columnList.first.pinned).toBeFalsy(); expect(firstHeaderIcon).toBeDefined(); UIInteractions.simulateClickAndSelectEvent(firstHeaderIcon); fixture.detectChanges(); tick(); childHeader = GridFunctions.getColumnHeaders(fixture)[3]; expect(childGrid.columnList.first.pinned).toBeTruthy(); expect(GridFunctions.isHeaderPinned(childHeader.parent)).toBeTruthy(); })); it('should be applied correctly for child grid with multi-column header.', fakeAsync(() => { fixture.componentInstance.rowIsland.columnList.find(x => x.header === 'Information').pinned = true; tick(DEBOUNCE_TIME); fixture.detectChanges(); hierarchicalGrid.expandRow(hierarchicalGrid.dataRowList.first.rowID); tick(DEBOUNCE_TIME); fixture.detectChanges(); const childGrid = hierarchicalGrid.hgridAPI.getChildGrids(false)[0]; // check unpinned/pinned columns expect(childGrid.pinnedColumns.length).toBe(3); expect(childGrid.unpinnedColumns.length).toBe(1); // check cells expect(childGrid.gridAPI.get_row_by_index(0).cells.length).toBe(3); let cell = childGrid.gridAPI.get_cell_by_index(0, 'ChildLevels'); expect(cell.visibleColumnIndex).toEqual(0); expect(GridFunctions.isCellPinned(cell)).toBeTruthy(); cell = childGrid.gridAPI.get_cell_by_index(0, 'ProductName'); expect(cell.visibleColumnIndex).toEqual(1); expect(GridFunctions.isCellPinned(cell)).toBeTruthy(); cell = childGrid.gridAPI.get_cell_by_index(0, 'ID'); expect(cell.visibleColumnIndex).toEqual(2); expect(GridFunctions.isCellPinned(cell)).toBeFalsy(); })); it('should be applied correctly even on the right side', fakeAsync(() => { hierarchicalGrid = fixture.componentInstance.hgrid; hierarchicalGrid.columnList.find(x => x.field === 'ID').pinned = true; hierarchicalGrid.pinning.columns = 1; hierarchicalGrid.cdr.detectChanges(); tick(); fixture.detectChanges(); const rightMostGridPart = hierarchicalGrid.nativeElement.getBoundingClientRect().right; const leftMostGridPart = hierarchicalGrid.nativeElement.getBoundingClientRect().left; const leftMostRightPinnedCellsPart = hierarchicalGrid.gridAPI.get_cell_by_index(0, 'ID') .nativeElement.getBoundingClientRect().left; const pinnedCellWidth = hierarchicalGrid.getCellByColumn(0, 'ID').width; // Expects that right pinning has been in action expect(leftMostGridPart).not.toEqual(leftMostRightPinnedCellsPart); // Expects that pinned column is in the visible grid's area expect(leftMostRightPinnedCellsPart).toBeLessThan(rightMostGridPart); // Expects that the whole pinned column is visible expect(leftMostRightPinnedCellsPart + Number.parseInt(pinnedCellWidth, 10)).toBeLessThan(rightMostGridPart); })); }); describe('Row Pinning', () => { const FIXED_ROW_CONTAINER = '.igx-grid__tr--pinned'; const FIXED_ROW_CONTAINER_TOP = 'igx-grid__tr--pinned-top'; const FIXED_ROW_CONTAINER_BOTTOM = 'igx-grid__tr--pinned-bottom'; beforeEach(() => { hierarchicalGrid.width = '800px'; hierarchicalGrid.height = '500px'; fixture.detectChanges(); }); it('should pin rows to top ', (() => { hierarchicalGrid.pinRow('0'); expect(hierarchicalGrid.pinnedRows.length).toBe(1); hierarchicalGrid.unpinRow('0'); expect(hierarchicalGrid.pinnedRows.length).toBe(0); hierarchicalGrid.pinRow('0'); expect(hierarchicalGrid.pinnedRows.length).toBe(1); let pinRowContainer = fixture.debugElement.queryAll(By.css(FIXED_ROW_CONTAINER)); expect(pinRowContainer.length).toBe(1); expect(pinRowContainer[0].nativeElement.classList.contains(FIXED_ROW_CONTAINER_TOP)).toBeTruthy(); expect(pinRowContainer[0].nativeElement.classList.contains(FIXED_ROW_CONTAINER_BOTTOM)).toBeFalsy(); expect(pinRowContainer[0].children[0].context.rowID).toBe('0'); expect(hierarchicalGrid.getRowByIndex(1).key).toBe('0'); expect(hierarchicalGrid.getRowByIndex(2).key).toBe('1'); expect(hierarchicalGrid.getRowByIndex(3).key).toBe('2'); hierarchicalGrid.pinRow('2'); pinRowContainer = fixture.debugElement.queryAll(By.css(FIXED_ROW_CONTAINER)); expect(pinRowContainer[0].children.length).toBe(2); expect(pinRowContainer[0].children[0].context.rowID).toBe('0'); expect(pinRowContainer[0].children[1].context.rowID).toBe('2'); expect(hierarchicalGrid.getRowByIndex(2).key).toBe('0'); expect(hierarchicalGrid.getRowByIndex(3).key).toBe('1'); expect(hierarchicalGrid.getRowByIndex(4).key).toBe('2'); fixture.detectChanges(); expect(hierarchicalGrid.pinnedRowHeight).toBe(2 * hierarchicalGrid.renderedRowHeight + 2); const expectedHeight = parseInt(hierarchicalGrid.height, 10) - hierarchicalGrid.pinnedRowHeight - 18 - hierarchicalGrid.theadRow.nativeElement.offsetHeight; expect(hierarchicalGrid.calcHeight - expectedHeight).toBeLessThanOrEqual(1); })); it('should pin rows to bottom', (() => { fixture.componentInstance.pinningConfig = { columns: ColumnPinningPosition.Start, rows: RowPinningPosition.Bottom }; fixture.detectChanges(); // Pin 2nd row hierarchicalGrid.pinRow('1'); fixture.detectChanges(); expect(hierarchicalGrid.pinnedRows.length).toBe(1); let pinRowContainer = fixture.debugElement.queryAll(By.css(FIXED_ROW_CONTAINER)); expect(pinRowContainer.length).toBe(1); expect(pinRowContainer[0].nativeElement.classList.contains(FIXED_ROW_CONTAINER_TOP)).toBeFalsy(); expect(pinRowContainer[0].nativeElement.classList.contains(FIXED_ROW_CONTAINER_BOTTOM)).toBeTruthy(); expect(pinRowContainer[0].children.length).toBe(1); expect(pinRowContainer[0].children[0].context.rowID).toBe('1'); expect(pinRowContainer[0].children[0].context.index).toBe(fixture.componentInstance.data.length); expect(pinRowContainer[0].children[0].nativeElement) .toBe(hierarchicalGrid.gridAPI.get_row_by_index(fixture.componentInstance.data.length).nativeElement); expect(hierarchicalGrid.getRowByIndex(0).key).toBe('0'); expect(hierarchicalGrid.getRowByIndex(1).key).toBe('1'); expect(hierarchicalGrid.getRowByIndex(2).key).toBe('2'); // Pin 1st row hierarchicalGrid.pinRow('0'); fixture.detectChanges(); pinRowContainer = fixture.debugElement.queryAll(By.css(FIXED_ROW_CONTAINER)); expect(pinRowContainer[0].children.length).toBe(2); expect(pinRowContainer[0].children[0].context.rowID).toBe('1'); expect(pinRowContainer[0].children[1].context.rowID).toBe('0'); expect(hierarchicalGrid.getRowByIndex(0).key).toBe('0'); expect(hierarchicalGrid.getRowByIndex(1).key).toBe('1'); expect(hierarchicalGrid.getRowByIndex(2).key).toBe('2'); fixture.detectChanges(); // Check last pinned is fully in view const last = pinRowContainer[0].children[1].context.nativeElement; expect(last.getBoundingClientRect().bottom - hierarchicalGrid.tbody.nativeElement.getBoundingClientRect().bottom).toBe(0); // 2 records pinned + 2px border expect(hierarchicalGrid.pinnedRowHeight).toBe(2 * hierarchicalGrid.renderedRowHeight + 2); const expectedHeight = parseInt(hierarchicalGrid.height, 10) - hierarchicalGrid.pinnedRowHeight - 18 - hierarchicalGrid.theadRow.nativeElement.offsetHeight; expect(hierarchicalGrid.calcHeight - expectedHeight).toBeLessThanOrEqual(1); })); it('should search in both pinned and unpinned rows.', () => { let findCount = hierarchicalGrid.findNext('Product: A0'); fixture.detectChanges(); let spans = fixture.debugElement.queryAll(By.css('.igx-highlight')); expect(spans.length).toBe(1); expect(findCount).toEqual(1); // Pin 1st row hierarchicalGrid.pinRow('0'); fixture.detectChanges(); expect(hierarchicalGrid.pinnedRows.find(r => r.rowID === '0')).toBeDefined(); findCount = hierarchicalGrid.findNext('Product: A0'); fixture.detectChanges(); spans = fixture.debugElement.queryAll(By.css('.igx-highlight')); expect(spans.length).toBe(2); expect(findCount).toEqual(2); }); it('should apply filtering to both pinned and unpinned rows.', () => { hierarchicalGrid.pinRow('1'); fixture.detectChanges(); hierarchicalGrid.pinRow('5'); fixture.detectChanges(); let pinRowContainer = fixture.debugElement.queryAll(By.css(FIXED_ROW_CONTAINER)); expect(pinRowContainer[0].children.length).toBe(2); expect(pinRowContainer[0].children[0].context.rowID).toBe('1'); expect(pinRowContainer[0].children[1].context.rowID).toBe('5'); hierarchicalGrid.filter('ID', '5', IgxStringFilteringOperand.instance().condition('contains'), false); fixture.detectChanges(); const allRows = HierarchicalGridFunctions.getHierarchicalRows(fixture); pinRowContainer = fixture.debugElement.queryAll(By.css(FIXED_ROW_CONTAINER)); expect(pinRowContainer[0].children.length).toBe(1); expect(pinRowContainer[0].children[0].context.rowID).toBe('5'); expect(allRows[1].componentInstance.rowID).toEqual('5'); }); it('should render paging with correct data and rows be correctly paged.', () => { hierarchicalGrid.height = '700px'; fixture.detectChanges(); fixture.componentInstance.paging = true; fixture.detectChanges(); hierarchicalGrid.perPage = 5; fixture.detectChanges(); let rows = HierarchicalGridFunctions.getHierarchicalRows(fixture); const paginator = fixture.debugElement.query(By.directive(IgxPaginatorComponent)); expect(rows.length).toEqual(5); expect(paginator.componentInstance.perPage).toEqual(5); expect(paginator.componentInstance.totalPages).toEqual(8); hierarchicalGrid.pinRow('1'); fixture.detectChanges(); rows = HierarchicalGridFunctions.getHierarchicalRows(fixture); expect(rows.length).toEqual(6); expect(paginator.componentInstance.perPage).toEqual(5); expect(paginator.componentInstance.totalPages).toEqual(8); hierarchicalGrid.pinRow('3'); fixture.detectChanges(); rows = HierarchicalGridFunctions.getHierarchicalRows(fixture); expect(rows.length).toEqual(7); expect(paginator.componentInstance.perPage).toEqual(5); expect(paginator.componentInstance.totalPages).toEqual(8); }); it('should apply sorting to both pinned and unpinned rows.', () => { hierarchicalGrid.pinRow('1'); hierarchicalGrid.pinRow('3'); fixture.detectChanges(); expect(hierarchicalGrid.getRowByIndex(0).key).toBe('1'); expect(hierarchicalGrid.getRowByIndex(1).key).toBe('3'); hierarchicalGrid.sort({ fieldName: 'ID', dir: SortingDirection.Desc, ignoreCase: false }); fixture.detectChanges(); // check pinned rows data is sorted expect(hierarchicalGrid.getRowByIndex(0).key).toBe('3'); expect(hierarchicalGrid.getRowByIndex(1).key).toBe('1'); // check unpinned rows data is sorted // Expect 9 since it is a string. expect(hierarchicalGrid.getRowByIndex(2).key).toBe('9'); }); it('should return pinned rows as well on multiple cell selection in both pinned and unpinned areas', async () => { hierarchicalGrid.pinRow('1'); fixture.detectChanges(); let range = { rowStart: 0, rowEnd: 2, columnStart: 'ID', columnEnd: 'ChildLevels' }; hierarchicalGrid.selectRange(range); fixture.detectChanges(); let selectedData = hierarchicalGrid.getSelectedData(); expect(selectedData).toEqual([{ID: '1', ChildLevels: 3}, {ID: '0', ChildLevels: 3}, {ID: '1', ChildLevels: 3}]); fixture.componentInstance.pinningConfig = { columns: ColumnPinningPosition.Start, rows: RowPinningPosition.Bottom }; fixture.detectChanges(); hierarchicalGrid.verticalScrollContainer.getScroll().scrollTop = 5000; await wait(); range = { rowStart: 38, rowEnd: 40, columnStart: 'ID', columnEnd: 'ChildLevels' }; hierarchicalGrid.clearCellSelection(); hierarchicalGrid.selectRange(range); fixture.detectChanges(); selectedData = hierarchicalGrid.getSelectedData(); expect(selectedData).toEqual([{ID: '38', ChildLevels: 3}, {ID: '39', ChildLevels: 3}, {ID: '1', ChildLevels: 3}]); }); it('should return correct filterData collection after filtering.', () => { hierarchicalGrid.pinRow('1'); hierarchicalGrid.pinRow('11'); fixture.detectChanges(); hierarchicalGrid.filter('ID', '1', IgxStringFilteringOperand.instance().condition('contains'), false); fixture.detectChanges(); let gridFilterData = hierarchicalGrid.filteredData; expect(gridFilterData.length).toBe(15); expect(gridFilterData[0].ID).toBe('1'); expect(gridFilterData[1].ID).toBe('11'); expect(gridFilterData[2].ID).toBe('1'); fixture.componentInstance.pinningConfig = { columns: ColumnPinningPosition.Start, rows: RowPinningPosition.Bottom }; fixture.detectChanges(); gridFilterData = hierarchicalGrid.filteredData; expect(gridFilterData.length).toBe(15); expect(gridFilterData[0].ID).toBe('1'); expect(gridFilterData[1].ID).toBe('11'); expect(gridFilterData[2].ID).toBe('1'); }); it('should correctly apply paging state for grid and paginator when there are pinned rows.', fakeAsync(() => { fixture.componentInstance.paging = true; fixture.detectChanges(); hierarchicalGrid.perPage = 5; hierarchicalGrid.height = '700px'; fixture.detectChanges(); const paginator = fixture.debugElement.query(By.directive(IgxPaginatorComponent)).componentInstance; // pin the first row hierarchicalGrid.getRowByIndex(0).pin(); expect(hierarchicalGrid.rowList.length).toEqual(6); expect(hierarchicalGrid.perPage).toEqual(5); expect(paginator.perPage).toEqual(5); expect(paginator.totalRecords).toEqual(40); expect(paginator.totalPages).toEqual(8); // pin the second row hierarchicalGrid.getRowByIndex(2).pin(); expect(hierarchicalGrid.rowList.length).toEqual(7); expect(hierarchicalGrid.perPage).toEqual(5); expect(paginator.perPage).toEqual(5); expect(paginator.totalRecords).toEqual(40); expect(paginator.totalPages).toEqual(8); // expand the first row hierarchicalGrid.expandRow(hierarchicalGrid.dataRowList.first.rowID); fixture.detectChanges(); tick(50); fixture.detectChanges(); expect(hierarchicalGrid.rowList.length).toEqual(8); expect(hierarchicalGrid.perPage).toEqual(5); expect(paginator.perPage).toEqual(5); expect(paginator.totalRecords).toEqual(40); expect(paginator.totalPages).toEqual(8); expect(hierarchicalGrid.rowList.toArray()[1] instanceof IgxChildGridRowComponent).toBeFalsy(); expect(hierarchicalGrid.rowList.toArray()[3] instanceof IgxChildGridRowComponent).toBeTruthy(); })); it('should have the correct records shown for pages with pinned rows', () => { fixture.componentInstance.paging = true; fixture.detectChanges(); hierarchicalGrid.perPage = 6; hierarchicalGrid.height = '700px'; fixture.detectChanges(); hierarchicalGrid.getRowByIndex(0).pin(); let rows = hierarchicalGrid.rowList.toArray(); [0, 0, 1, 2, 3, 4, 5].forEach((x, index) => expect(parseInt(rows[index].cells.first.value, 10)).toEqual(x)); hierarchicalGrid.paginate(6); fixture.detectChanges(); rows = hierarchicalGrid.rowList.toArray(); [0, 36, 37, 38, 39].forEach((x, index) => expect(parseInt(rows[index].cells.first.value, 10)).toEqual(x)); }); }); });
the_stack
import { Support } from './support'; import { Device } from './device'; import { Events } from './events'; import { PaneSettings, PaneBreaks, ZStackSettings } from './models'; import { Settings } from './settings'; import { Breakpoints } from './breakpoints'; export type CupertinoSettings = Partial<PaneSettings>; export class CupertinoPane { public disableDragEvents: boolean = false; public screen_height: number; public screenHeightOffset: number; public preventDismissEvent: boolean = false; public preventedDismiss: boolean = false; public rendered: boolean = false; public wrapperEl: HTMLDivElement; public paneEl: HTMLDivElement; public overflowEl: HTMLElement; public el: HTMLElement; public contentEl: HTMLElement; public parentEl: HTMLElement; public backdropEl: HTMLDivElement; private draggableEl: HTMLDivElement; private moveEl: HTMLDivElement; private destroyButtonEl: HTMLDivElement; private followerEl: HTMLElement; private settings: CupertinoSettings = (new Settings()).instance; private device: Device = new Device(); private events: Events; private breakpoints: Breakpoints; private zStackDefaults: ZStackSettings = { pushElements: null, minPushHeight: null, cardYOffset: 0, cardZScale: 0.93, cardContrast: 0.85, stackZAngle: 160, }; constructor(private selector: (string | HTMLElement), conf: CupertinoSettings = {}) { // Element or selector if (selector instanceof HTMLElement) { this.selector = selector; } else { this.selector = <HTMLElement>document.querySelector(selector); } // Unable attach selector or DOM element if (!this.selector) { console.warn('Cupertino Pane: wrong selector or DOM element specified', this.selector); return; } // Pane class created if (this.isPanePresented()) { console.error('Cupertino Pane: specified selector or DOM element already in use', this.selector); return; } this.el = this.selector; this.el.style.display = 'none'; this.settings = {...this.settings, ...conf}; if (this.settings.parentElement) { this.settings.parentElement = <HTMLElement>document.querySelector( this.settings.parentElement ); } else { this.settings.parentElement = this.el.parentElement; } this.breakpoints = new Breakpoints(this, this.settings); this.events = new Events(this, this.settings, this.device, this.breakpoints); } private drawBaseElements() { // Parent this.parentEl = this.settings.parentElement; // Wrapper this.wrapperEl = document.createElement('div'); this.wrapperEl.classList.add('cupertino-pane-wrapper'); if (this.settings.inverse) { this.wrapperEl.classList.add('inverse'); } if (this.settings.cssClass) { this.wrapperEl.className += ` ${this.settings.cssClass}`; }; let internalStyles: string = ''; internalStyles += ` .cupertino-pane-wrapper { display: none; position: absolute; top: 0; left: 0; } `; // Panel (appying transform ASAP, avoid timeouts for animate:true) this.paneEl = document.createElement('div'); this.paneEl.style.transform = `translateY(${this.screenHeightOffset}px) translateZ(0px)`; this.paneEl.classList.add('pane'); internalStyles += ` .cupertino-pane-wrapper .pane { position: fixed; z-index: 11; width: 100%; max-width: 500px; left: 0px; right: 0px; margin-left: auto; margin-right: auto; background: var(--cupertino-pane-background, #ffffff); color: var(--cupertino-pane-color, #333333); box-shadow: var(--cupertino-pane-shadow, 0 4px 16px rgba(0,0,0,.12)); will-change: transform; padding-top: 15px; border-radius: var(--cupertino-pane-border-radius, 20px) var(--cupertino-pane-border-radius, 20px) 0 0; } .cupertino-pane-wrapper.inverse .pane { padding-bottom: 15px; border-radius: 0 0 20px 20px; border-radius: 0 0 var(--cupertino-pane-border-radius, 20px) var(--cupertino-pane-border-radius, 20px); } `; // Draggable this.draggableEl = document.createElement('div'); this.draggableEl.classList.add('draggable'); if (this.settings.draggableOver) { this.draggableEl.classList.add('over'); } internalStyles += ` .cupertino-pane-wrapper .draggable { padding: 5px; position: absolute; left: 0; right: 0; margin-left: auto; margin-right: auto; height: 30px; z-index: 12; top: 0; bottom: initial; } .cupertino-pane-wrapper .draggable.over { top: -30px; padding: 15px; } .cupertino-pane-wrapper.inverse .draggable { bottom: 0; top: initial; } .cupertino-pane-wrapper.inverse .draggable.over { bottom: -30px; top: initial; } `; // Move this.moveEl = document.createElement('div'); this.moveEl.classList.add('move'); internalStyles += ` .cupertino-pane-wrapper .move { margin: 0 auto; height: 5px; background: var(--cupertino-pane-move-background, #c0c0c0); width: 36px; border-radius: 4px; } .cupertino-pane-wrapper .draggable.over .move { width: 70px; background: var(--cupertino-pane-move-background, rgba(225, 225, 225, 0.6)); ${Support.backdropFilter ? ` backdrop-filter: saturate(180%) blur(20px); -webkit-backdrop-filter: saturate(180%) blur(20px); ` : ``} } .cupertino-pane-wrapper.inverse .move { margin-top: 15px; } .cupertino-pane-wrapper.inverse .draggable.over .move { margin-top: -5px; } `; // Destroy button this.destroyButtonEl = document.createElement('div'); this.destroyButtonEl.classList.add('destroy-button'); internalStyles += ` .cupertino-pane-wrapper .destroy-button { width: 26px; height: 26px; position: absolute; background: var(--cupertino-pane-destroy-button-background, #ebebeb); fill: var(--cupertino-pane-icon-close-color, #7a7a7e); right: 20px; z-index: 14; border-radius: 100%; top: 16px; } `; // Content user element this.contentEl = this.el; this.contentEl.style.transition = `opacity ${this.settings.animationDuration}ms ${this.settings.animationType} 0s`; this.contentEl.style.overflowX = 'hidden'; // Backdrop internalStyles += ` .cupertino-pane-wrapper .backdrop { overflow: hidden; position: fixed; width: 100%; bottom: 0; right: 0; left: 0; top: 0; display: none; z-index: 10; } `; // Inject internal CSS this.addStyle(internalStyles); // inject DOM this.parentEl.appendChild(this.wrapperEl); this.wrapperEl.appendChild(this.paneEl); this.paneEl.appendChild(this.contentEl); if (this.settings.showDraggable) { this.paneEl.appendChild(this.draggableEl); this.draggableEl.appendChild(this.moveEl); } } async present(conf: {animate: boolean} = {animate: false}): Promise<CupertinoPane> { if (!this.el) return; // Pane already exist and was rendered if (this.isPanePresented() && this.rendered) { this.moveToBreak(this.settings.initialBreak); return; } // Pane already exist but not rendered in this class if (this.isPanePresented() && !this.rendered) { console.warn('Cupertino Pane: specified selector or DOM element already in use', this.selector); return; } // Emit event this.settings.onWillPresent(); this.updateScreenHeights(); this.drawBaseElements(); await this.setBreakpoints(); // Necessary Inlines with breakpoints this.paneEl.style.height = `${this.getPaneHeight()}px`; if (this.settings.inverse) { this.paneEl.style.top = `-${this.breakpoints.bottomer - this.settings.bottomOffset}px`; } // Show elements this.wrapperEl.style.display = 'block'; this.contentEl.style.display = 'block'; this.wrapperEl.classList.add('rendered'); this.rendered = true; if (this.settings.followerElement) { if (!<HTMLElement>document.querySelector(this.settings.followerElement)) { console.warn('Cupertino Pane: wrong follower element selector specified', this.settings.followerElement); return; } this.followerEl = <HTMLElement>document.querySelector( this.settings.followerElement ); this.followerEl.style.willChange = 'transform, border-radius'; this.followerEl.style.transform = `translateY(0px) translateZ(0px)`; this.followerEl.style.transition = `all ${this.settings.animationDuration}ms ${this.getTimingFunction(this.settings.breaks[this.currentBreak()]?.bounce)} 0s`; } // Assign multiplicators for push elements if (this.settings.zStack) { this.setZstackConfig(this.settings.zStack); this.setPushMultiplicators(); } if ((this.settings.buttonClose && this.settings.buttonDestroy) && !this.settings.inverse) { this.paneEl.appendChild(this.destroyButtonEl); this.destroyButtonEl.addEventListener('click', (t) => this.destroy({animate:true, destroyButton: true})); this.destroyButtonEl.innerHTML = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"> <path d="M278.6 256l68.2-68.2c6.2-6.2 6.2-16.4 0-22.6-6.2-6.2-16.4-6.2-22.6 0L256 233.4l-68.2-68.2c-6.2-6.2-16.4-6.2-22.6 0-3.1 3.1-4.7 7.2-4.7 11.3 0 4.1 1.6 8.2 4.7 11.3l68.2 68.2-68.2 68.2c-3.1 3.1-4.7 7.2-4.7 11.3 0 4.1 1.6 8.2 4.7 11.3 6.2 6.2 16.4 6.2 22.6 0l68.2-68.2 68.2 68.2c6.2 6.2 16.4 6.2 22.6 0 6.2-6.2 6.2-16.4 0-22.6L278.6 256z"/> </svg>`; } if (this.settings.bottomClose) { this.settings.breaks.bottom.enabled = true; } if (this.settings.freeMode) { this.settings.lowerThanBottom = false; } if (this.settings.backdrop) { this.renderBackdrop(); } this.checkOpacityAttr(this.breakpoints.currentBreakpoint); /****** Fix android issues *******/ if (this.device.android) { // Body patch prevent android pull-to-refresh document.body.style['overscrollBehaviorY'] = 'none'; } /****** Attach Events *******/ this.events.attachAllEvents(); /****** Animation & Transition ******/ if (conf.animate) { await this.doTransition({type: 'present', translateY: this.breakpoints.breaks[this.settings.initialBreak]}); } else { // No initial transitions this.breakpoints.prevBreakpoint = this.settings.initialBreak; this.paneEl.style.transform = `translateY(${this.breakpoints.breaks[this.settings.initialBreak]}px) translateZ(0px)`; if (this.settings.backdrop) { this.backdropEl.style.display = `block`; } if (this.settings.zStack) { this.settings.zStack.pushElements.forEach(item => this.pushTransition( document.querySelector(item), this.breakpoints.breaks[this.settings.initialBreak], 'unset' ) ); } // Emit event this.settings.onDidPresent(); } // Some timeout to get offsetTop await new Promise((resolve) => setTimeout(() => resolve(true), 150)); this.scrollElementInit(); this.checkOverflowAttr(this.breakpoints.currentBreakpoint); return this; } public getPaneHeight(): number { if (!this.settings.inverse) { return this.screen_height - this.breakpoints.topper - this.settings.bottomOffset; } return this.breakpoints.bottomer - this.settings.bottomOffset; } public updateScreenHeights():void { if (this.settings.inverse) { this.screen_height = window.innerHeight; this.screenHeightOffset = 0; } else { this.screen_height = window.innerHeight; this.screenHeightOffset = window.innerHeight; } } public scrollElementInit() { let attrElements = this.el.querySelectorAll('[overflow-y]'); if (!attrElements.length || attrElements.length > 1) { this.overflowEl = this.contentEl; } else { this.overflowEl = <HTMLElement>attrElements[0]; this.overflowEl.style.overflowX = 'hidden'; } if (this.settings.topperOverflow) { if (this.settings.upperThanTop) { console.warn('Cupertino Pane: "upperThanTop" allowed for disabled "topperOverflow"'); } this.setOverflowHeight(); } } public setOverflowHeight(offset = 0) { if (!this.settings.inverse) { this.overflowEl.style.height = `${this.getPaneHeight() - this.settings.topperOverflowOffset - this.overflowEl.offsetTop - offset}px`; } else { this.overflowEl.style.height = `${this.getPaneHeight() - 30 - this.settings.topperOverflowOffset - this.overflowEl.offsetTop}px`; } } public checkOpacityAttr(val) { let attrElements = this.el.querySelectorAll('[hide-on-bottom]'); if (!attrElements.length) return; if (this.settings.inverse) return; attrElements.forEach((item) => { (<HTMLElement>item).style.transition = `opacity ${this.settings.animationDuration}ms ${this.settings.animationType} 0s`; (<HTMLElement>item).style.opacity = (val >= this.breakpoints.breaks['bottom']) ? '0' : '1'; }); } public checkOverflowAttr(val) { if (!this.settings.topperOverflow || !this.overflowEl) { return; } if (!this.settings.inverse) { this.overflowEl.style.overflowY = (val <= this.breakpoints.topper) ? 'auto' : 'hidden'; } else { this.overflowEl.style.overflowY = (val >= this.breakpoints.bottomer) ? 'auto' : 'hidden'; } } public isPanePresented():boolean { // Check through all presented panes let wrappers = Array.from(document.querySelectorAll(`.cupertino-pane-wrapper.rendered`)); if (!wrappers.length) return false; return wrappers.find((item) => item.contains(<HTMLElement>this.selector)) ? true: false; } public swipeNextPoint = (diff, maxDiff, closest) => { let brs = {}; let settingsBreaks = {}; if (this.settings.inverse) { brs['top'] = this.breakpoints.breaks['bottom']; brs['middle'] = this.breakpoints.breaks['middle']; brs['bottom'] = this.breakpoints.breaks['top']; settingsBreaks['top'] = {...this.settings.breaks['bottom']}; settingsBreaks['middle'] = {...this.settings.breaks['middle']}; settingsBreaks['bottom'] = {...this.settings.breaks['top']}; } else { brs = {...this.breakpoints.breaks} settingsBreaks = {...this.settings.breaks}; } if (this.breakpoints.currentBreakpoint === brs['top']) { if (diff > maxDiff) { if (settingsBreaks['middle'].enabled) { return brs['middle']; } if (settingsBreaks['bottom'].enabled) { if (brs['middle'] < closest) { return closest; } return brs['bottom']; } } return brs['top']; } if (this.breakpoints.currentBreakpoint === brs['middle']) { if (diff < -maxDiff) { if (settingsBreaks['top'].enabled) { return brs['top']; } } if (diff > maxDiff) { if (settingsBreaks['bottom'].enabled) { return brs['bottom']; } } return brs['middle']; } if (this.breakpoints.currentBreakpoint === brs['bottom']) { if (diff < -maxDiff) { if (settingsBreaks['middle'].enabled) { if (brs['middle'] > closest) { return closest; } return brs['middle']; } if (settingsBreaks['top'].enabled) { return brs['top']; } } return brs['bottom']; } return closest; } /** * Private Utils methods */ private getTimingFunction(bounce) { return bounce ? 'cubic-bezier(0.175, 0.885, 0.370, 1.120)' : this.settings.animationType; } private isBackdropPresented() { return document.querySelector(`.cupertino-pane-wrapper .backdrop`) ? true : false; } private renderBackdrop() { this.backdropEl = document.createElement('div'); this.backdropEl.classList.add('backdrop'); this.backdropEl.style.transition = `all ${this.settings.animationDuration}ms ${this.settings.animationType} 0s`; this.backdropEl.style.backgroundColor = `rgba(0,0,0, ${this.settings.backdropOpacity})`; this.wrapperEl.appendChild(this.backdropEl); this.backdropEl.addEventListener('click', (t) => this.settings.onBackdropTap()); } /** * Utility function to add minified internal CSS to head. * @param {string} styleString */ private addStyle(styleString): void { if (document.querySelector('#cupertino-panes-internal')) return; const style = document.createElement('style'); style.id = 'cupertino-panes-internal'; styleString = styleString.replace(/\s\s+/g, ' '); style.textContent = styleString; document.head.prepend(style); }; // Z-Stack: Pushed elements multiplicators private setPushMultiplicators(): void { this.settings.zStack.pushElements.forEach((item) => { let pushElement: HTMLElement = document.querySelector(item); let multiplicator = this.getPushMulitplicator(pushElement); multiplicator = multiplicator ? multiplicator + 1 : 1; pushElement.style.setProperty('--push-multiplicator', `${multiplicator}`); }); } private clearPushMultiplicators(): void { for (let i = 0; i < this.settings.zStack.pushElements.length; i++) { let pushElement: HTMLElement = document.querySelector( this.settings.zStack.pushElements[i] ); let multiplicator = this.getPushMulitplicator(pushElement); multiplicator -= 1; if (multiplicator) { pushElement.style.setProperty('--push-multiplicator', `${multiplicator}`); } else { pushElement.style.removeProperty('--push-multiplicator'); } } } private getPushMulitplicator(el: HTMLElement): number { let multiplicator: (string | number) = el.style.getPropertyValue('--push-multiplicator'); return parseInt(multiplicator); } public setZstackConfig(zStack: ZStackSettings): void { this.settings.zStack = zStack ? {...this.zStackDefaults, ...zStack} : null;; } /** * Backdrop */ public backdrop(conf = { show: true }) { if (!this.isPanePresented()) { console.warn(`Cupertino Pane: Present pane before call backdrop()`); return null; } if (!this.isBackdropPresented()) { this.renderBackdrop(); // Reset events to attach backdrop stop propagation this.events.resetEvents(); } const transitionEnd = () => { this.backdropEl.style.transition = `initial`; this.backdropEl.style.display = `none`; this.backdropEl.removeEventListener('transitionend', transitionEnd); } this.backdropEl.style.transition = `all ${this.settings.animationDuration}ms ${this.settings.animationType} 0s`; this.backdropEl.style.backgroundColor = 'rgba(0,0,0,.0)'; if (!conf.show) { // Destroy if (this.backdropEl.style.display === 'none') return; this.backdropEl.addEventListener('transitionend', transitionEnd); } else { // Present this.backdropEl.style.display = 'block'; setTimeout(() => { this.backdropEl.style.backgroundColor = `rgba(0,0,0, ${this.settings.backdropOpacity})`; }, 50); } } // TODO: static method public getPanelTransformY():number { const translateYRegex = /\.*translateY\((.*)px\)/i; return parseFloat(translateYRegex.exec(this.paneEl.style.transform)[1]); } /************************************ * Public user methods */ /** * Prevent dismiss event */ public preventDismiss(val: boolean = false): void { this.preventDismissEvent = val; } /** * Disable pane drag events */ public disableDrag(): void { this.disableDragEvents = true; } /** * Enable pane drag events */ public enableDrag(): void { this.disableDragEvents = false; } /** * Public user method to reset breakpoints * @param conf */ public async setBreakpoints(conf?: PaneBreaks, bottomOffset?: number) { if (this.isPanePresented() && !conf) { console.warn(`Cupertino Pane: Provide any breaks configuration`); return; } await this.breakpoints.buildBreakpoints(conf, bottomOffset); } public async calcFitHeight() { // Allow user to call method asap, dont check with this.isPanePresented() if (!this.wrapperEl || !this.el) { return null; } if (this.breakpoints.calcHeightInProcess) { console.warn(`Cupertino Pane: calcFitHeight() already in process`); return null; } await this.breakpoints.buildBreakpoints(this.breakpoints.lockedBreakpoints); } public moveToBreak(val: string) { if (!this.isPanePresented()) { console.warn(`Cupertino Pane: Present pane before call moveToBreak()`); return null; } if (!this.settings.breaks[val].enabled) { console.warn('Cupertino Pane: %s breakpoint disabled', val); return; } this.checkOpacityAttr(this.breakpoints.breaks[val]); this.checkOverflowAttr(this.breakpoints.breaks[val]); this.doTransition({type: 'breakpoint', translateY: this.breakpoints.breaks[val]}); this.breakpoints.currentBreakpoint = this.breakpoints.breaks[val]; } public moveToHeight(val: number) { if (!this.isPanePresented()) { console.warn(`Cupertino Pane: Present pane before call moveToHeight()`); return null; } let translateY = this.screenHeightOffset ? this.screen_height - val : val; this.checkOpacityAttr(translateY); this.doTransition({type: 'breakpoint', translateY }); } public hide() { if (!this.isPanePresented()) { console.warn(`Cupertino Pane: Present pane before call hide()`); return null; } if (this.isHidden()) { console.warn(`Cupertino Pane: Pane already hidden`); return null; } this.doTransition({type: 'hide', translateY: this.screenHeightOffset}); } public isHidden(): (boolean|null) { if (!this.isPanePresented()) { console.warn(`Cupertino Pane: Present pane before call isHidden()`); return null; } return this.paneEl.style.transform === `translateY(${this.screenHeightOffset}px) translateZ(0px)`; } public currentBreak(): (string|null) { if (!this.isPanePresented()) { console.warn(`Cupertino Pane: Present pane before call currentBreak()`); return null; } return this.breakpoints.getCurrentBreakName(); }; private destroyResets(): void { this.parentEl.appendChild(this.contentEl); this.wrapperEl.remove(); /****** Detach Events *******/ this.events.detachAllEvents(); // Clear pushed elements if (this.settings.zStack) { // this.clearPushMultiplicators(); } // Reset vars delete this.rendered; delete this.breakpoints.prevBreakpoint; // Reset styles this.contentEl.style.display = 'none'; } public async destroy(conf: { animate: boolean, destroyButton?: boolean } = { animate: false, destroyButton: false }): Promise<true> { if (!this.isPanePresented()) { console.warn(`Cupertino Pane: Present pane before call destroy()`); return null; } // Prevent dismiss if (this.preventDismissEvent) { // Emit event with prevent dismiss if not already sent from drag event if (!this.preventedDismiss) { this.settings.onWillDismiss({prevented: true} as any); this.moveToBreak(this.breakpoints.prevBreakpoint); } return; } // Emit event this.settings.onWillDismiss(); /****** Animation & Transition ******/ if (conf.animate) { await this.doTransition({type: 'destroy', translateY: this.screenHeightOffset, destroyButton: conf.destroyButton}); } else { this.destroyResets(); // Emit event this.settings.onDidDismiss({destroyButton: conf.destroyButton} as any); } } private pushTransition(pushElement: HTMLElement, newPaneY: number, transition: string) { let zStack = this.settings.zStack.pushElements; pushElement.style.transition = transition; newPaneY = this.screenHeightOffset - newPaneY; const topHeight = this.settings.zStack.minPushHeight ? this.settings.zStack.minPushHeight : this.screenHeightOffset - this.breakpoints.bottomer; const minHeight = this.screenHeightOffset - this.breakpoints.topper; // Math calculations let multiplicator = this.getPushMulitplicator(pushElement); let scaleNew = Math.pow(this.settings.zStack.cardZScale, multiplicator); let scaleNormal = Math.pow(this.settings.zStack.cardZScale, multiplicator - 1); let pushY = 6 + this.settings.zStack.cardYOffset; // 6 is iOS style offset for z-stacks let yNew = -1 * (pushY * multiplicator); let yNormal = (yNew + pushY); let contrastNew = Math.pow(this.settings.zStack.cardContrast, multiplicator); let contrastNormal = Math.pow(this.settings.zStack.cardContrast, multiplicator - 1); // Accumulated styles from each pusher to pushed const setStyles = (scale, y, contrast, border) => { let exponentAngle = Math.pow(scale, this.settings.zStack.stackZAngle / 100); pushElement.style.transform = `translateY(${y * (exponentAngle/scale)}px) scale(${scale})`; pushElement.style.borderRadius = `${border}px`; pushElement.style.filter = `contrast(${contrast})`; // When destroy transition and last item moved we reduce multiplicators let lastPushed = document.querySelector(zStack[zStack.length - 1]); if (!newPaneY && pushElement.className === lastPushed.className) { this.clearPushMultiplicators(); } }; // Pusher cleared or pane destroyed if (newPaneY <= topHeight) { // defaults setStyles( scaleNormal, // scale yNormal, // transformY contrastNormal, // contrast 0 // border ); return; } // Pusher drag/move const getXbyY = (min, max) => { let val = (minHeight * max - topHeight * min) * -1; val -= (min - max) * newPaneY; val /= (topHeight - minHeight); if (val > max) val = max; if (val < min) val = min; return val; }; setStyles( getXbyY(scaleNew, scaleNormal), getXbyY(yNew, yNormal), getXbyY(contrastNew, contrastNormal), getXbyY(-10, 0) * -1, ); } /*********************************** * Transitions handler */ public doTransition(params:any = {}): Promise<true> { return new Promise((resolve) => { // touchmove simple event if (params.type === 'move') { this.paneEl.style.transition = 'all 0ms linear 0ms'; this.paneEl.style.transform = `translateY(${params.translateY}px) translateZ(0px)`; // Bind for follower same transitions if (this.followerEl) { this.followerEl.style.transition = 'all 0ms linear 0ms'; this.followerEl.style.transform = `translateY(${params.translateY - this.breakpoints.breaks[this.settings.initialBreak]}px) translateZ(0px)`; } // Push transition for each element if (this.settings.zStack) { this.settings.zStack.pushElements.forEach(item => this.pushTransition( document.querySelector(item), this.getPanelTransformY(), 'all 0ms linear 0ms' ) ); } return resolve(true); } // Transition end const transitionEnd = () => { if (params.type === 'destroy') { this.destroyResets(); } this.paneEl.style.transition = `initial`; // Bind for follower same transitions if (this.followerEl) { this.followerEl.style.transition = `initial`; } // Backdrop if (this.settings.backdrop) { if (params.type === 'destroy' || params.type === 'hide') { this.backdropEl.style.transition = `initial`; this.backdropEl.style.display = `none`; } } // Emit event if (params.type === 'present') { this.settings.onDidPresent(); } if (params.type === 'destroy') { this.settings.onDidDismiss({destroyButton: params.destroyButton} as any); } this.settings.onTransitionEnd({target: document.body.contains(this.paneEl) ? this.paneEl : null}); // Remove listener this.paneEl.removeEventListener('transitionend', transitionEnd); return resolve(true); }; // MoveToBreak, Touchend, Present, Hide, Destroy events if (params.type === 'breakpoint' || params.type === 'end' || params.type === 'present' || params.type === 'hide' || params.type === 'destroy') { // backdrop if (this.settings.backdrop) { if (this.isHidden() || params.type === 'hide' || params.type === 'destroy' || params.type === 'present') { this.backdropEl.style.backgroundColor = 'rgba(0,0,0,.0)'; this.backdropEl.style.transition = `all ${this.settings.animationDuration}ms ${this.settings.animationType} 0s`; if (params.type !== 'hide' && params.type !== 'destroy') { this.backdropEl.style.display = 'block'; setTimeout(() => { this.backdropEl.style.backgroundColor = `rgba(0,0,0, ${this.settings.backdropOpacity})`; }, 50); } } } // freemode if (params.type === 'end' && this.settings.freeMode) return resolve(true); // Get timing function && push for next const nextBreak = Object.entries(this.breakpoints.breaks).find( val => val[1] === params.translateY ); let bounce = nextBreak && this.settings.breaks[nextBreak[0]]?.bounce; const timingForNext = this.getTimingFunction(bounce); // style this.paneEl.style.transition = `transform ${this.settings.animationDuration}ms ${timingForNext} 0s`; // Bind for follower same transitions if (this.followerEl) { this.followerEl.style.transition = `transform ${this.settings.animationDuration}ms ${timingForNext} 0s`; } // Push transition if (this.settings.zStack) { // Reason of timeout is to hide empty space when present pane and push element // we should start push after pushMinHeight but for present // transition we can't calculate where pane Y is. setTimeout(() => { this.settings.zStack.pushElements.forEach(item => this.pushTransition( document.querySelector(item), params.translateY, `all ${this.settings.animationDuration}ms ${this.settings.animationType} 0s` ) ); }, (this.settings.zStack.cardYOffset && params.type === 'present') ? 50 : 0); } // Main transitions setTimeout(() => { // Emit event this.settings.onTransitionStart({translateY: {new: params.translateY}}); this.paneEl.style.transform = `translateY(${params.translateY}px) translateZ(0px)`; // Bind for follower same transitions if (this.followerEl) { this.followerEl.style.transform = `translateY(${params.translateY - this.breakpoints.breaks[this.settings.initialBreak]}px) translateZ(0px)`; } }, params.type === 'present' ? 50 : 0); let getNextBreakpoint = Object.entries(this.breakpoints.breaks).find(val => val[1] === params.translateY); if (getNextBreakpoint) { this.breakpoints.prevBreakpoint = getNextBreakpoint[0]; } this.paneEl.addEventListener('transitionend', transitionEnd); } }); } }
the_stack
import { ParsedPlaylist } from './src/typings.d'; import { app, BrowserWindow, ipcMain, session } from 'electron'; import { parse } from 'iptv-playlist-parser'; import axios from 'axios'; import { guid } from '@datorama/akita'; import { Playlist, PlaylistUpdateState } from './shared/playlist.interface'; import Nedb, { Cursor } from 'nedb-promises-ts'; import { CHANNEL_SET_USER_AGENT, EPG_ERROR, EPG_FETCH, EPG_FETCH_DONE, EPG_GET_PROGRAM, EPG_GET_PROGRAM_DONE, ERROR, PLAYLIST_SAVE_DETAILS, PLAYLIST_PARSE, PLAYLIST_PARSE_RESPONSE, PLAYLIST_UPDATE, PLAYLIST_UPDATE_RESPONSE, PLAYLIST_UPDATE_POSITIONS, } from './shared/ipc-commands'; const fs = require('fs'); const userData = app.getPath('userData'); const db = new Nedb<Playlist>({ filename: `${userData}/db/data.db`, autoload: true, }); export class Api { /** Instance of the main application window */ mainWindow: BrowserWindow; /** Default user agent stored as a fallback value */ defaultUserAgent: string; /** Default referer url value */ defaultReferer: string; /** Instance of the epg browser window */ workerWindow: BrowserWindow; constructor() { ipcMain.on('parse-playlist-by-url', (event, args) => { try { axios.get(args.url).then((result) => { const parsedPlaylist = this.convertFileStringToPlaylist( result.data ); const playlistObject = this.createPlaylistObject( args.title, parsedPlaylist, args.url, 'URL' ); this.insertToDb(playlistObject); event.sender.send(PLAYLIST_PARSE_RESPONSE, { payload: playlistObject, }); }); } catch (err) { event.sender.send(ERROR, { message: err.response.statusText, status: err.response.status, }); } }); ipcMain.on(PLAYLIST_PARSE, (event, args) => { const parsedPlaylist = this.parsePlaylist(args.playlist); const playlistObject = this.createPlaylistObject( args.title, parsedPlaylist, args.path, 'FILE' ); this.insertToDb(playlistObject); event.sender.send(PLAYLIST_PARSE_RESPONSE, { payload: playlistObject, }); }); ipcMain.on('playlists-all', (event) => this.sendAllPlaylists(event)); ipcMain.on('playlist-by-id', (event, args) => { db.findOne({ _id: args.id }).then((playlist) => { this.setUserAgent(playlist.userAgent); event.sender.send(PLAYLIST_PARSE_RESPONSE, { payload: playlist, }); }); }); ipcMain.on('playlist-remove-by-id', (event, args) => { db.remove({ _id: args.id }).then((removed) => { if (removed) { event.sender.send('playlist-remove-by-id-result', { message: 'playlist was removed', }); } }); }); // open playlist from file system ipcMain.on('open-file', (event, args) => { fs.readFile( args.filePath, 'utf-8', (err: NodeJS.ErrnoException, data: string) => { if (err) { console.log( 'An error ocurred reading the file :' + err.message ); return; } const parsedPlaylist = this.convertFileStringToPlaylist(data); const playlistObject = this.createPlaylistObject( args.fileName, parsedPlaylist, args.filePath, 'FILE' ); this.insertToDb(playlistObject); event.sender.send(PLAYLIST_PARSE_RESPONSE, { payload: playlistObject, }); } ); }); ipcMain.on('update-favorites', (event, args) => { db.update( { id: args.id }, { $set: { favorites: args.favorites } } ).then((updated) => { if (!updated.numAffected || updated.numAffected === 0) { console.error('Error: Favorites were not updated'); } }); }); // listeners for EPG events ipcMain .on(EPG_GET_PROGRAM, (event, arg) => this.workerWindow.webContents.send(EPG_GET_PROGRAM, arg) ) .on(EPG_GET_PROGRAM_DONE, (event, arg) => { this.mainWindow.webContents.send(EPG_GET_PROGRAM_DONE, arg); }) .on(EPG_FETCH, (event, arg) => this.workerWindow.webContents.send(EPG_FETCH, arg?.url) ) .on(EPG_FETCH_DONE, (event, arg) => this.mainWindow.webContents.send(EPG_FETCH_DONE, arg) ) .on(EPG_ERROR, (event, arg) => this.mainWindow.webContents.send(EPG_ERROR, arg) ); ipcMain.on( PLAYLIST_SAVE_DETAILS, ( event, args: Pick< Playlist, '_id' | 'title' | 'userAgent' | 'autoRefresh' > ) => { this.updatePlaylistById(args._id, { title: args.title, userAgent: args.userAgent, autoRefresh: args.autoRefresh, }).then((updated) => { if (!updated.numAffected || updated.numAffected === 0) { console.error( 'Error: Playlist details were not updated' ); } this.sendAllPlaylists(event); }); } ); ipcMain.on( PLAYLIST_UPDATE, (event, args: { id: string; filePath?: string; url?: string }) => { if (args.filePath && args.id) { this.fetchPlaylistByFilePath(args.id, args.filePath, event); } else if (args.url && args.id) { this.fetchPlaylistByUrl(args.id, args.url, event); } } ); ipcMain.on( CHANNEL_SET_USER_AGENT, (event, args: { userAgent: string; referer?: string }) => { if (args.userAgent && args.referer) { this.setUserAgent(args.userAgent, args.referer); } else { this.setUserAgent(this.defaultUserAgent, 'localhost'); } } ); ipcMain.on( PLAYLIST_UPDATE_POSITIONS, (event, playlists: Partial<Playlist[]>) => playlists.forEach((list, index) => { this.updatePlaylistById(list._id, { ...list, position: index, }); }) ); this.refreshPlaylists(); } /** * Starts the update process for all the playlists with the enabled auto-refresh flag */ refreshPlaylists(): void { this.getAllPlaylistsMeta().then((playlists) => { playlists.forEach((playlist) => { if (playlist.autoRefresh && playlist.autoRefresh === true) { if (playlist.url) { this.fetchPlaylistByUrl(playlist._id, playlist.url); } else if (playlist.filePath) { this.fetchPlaylistByFilePath( playlist._id, playlist.filePath ); } else { console.log('skip...'); } } }); }); } /** * Sends list with all playlists which are stored in the database * @param event main event */ sendAllPlaylists(event: Electron.IpcMainEvent): void { this.getAllPlaylistsMeta().then((playlists) => { event.sender.send('playlist-all-result', { payload: playlists, }); }); } /** * Returns all existing playlists with meta information from the database * @returns */ getAllPlaylistsMeta(): Cursor<Playlist> { return db .find({ type: { $exists: false } }) .projection({ count: 1, title: 1, _id: 1, url: 1, importDate: 1, userAgent: 1, filename: 1, filePath: 1, autoRefresh: 1, updateDate: 1, updateState: 1, position: 1, }) .sort({ position: 1, importDate: -1 }); } /** * Sets the user agent header for all http requests * @param userAgent user agent to use * @param referer referer to use */ setUserAgent(userAgent: string, referer?: string): void { if (userAgent === undefined || userAgent === null || userAgent === '') { userAgent = this.defaultUserAgent; } session.defaultSession.webRequest.onBeforeSendHeaders( (details, callback) => { details.requestHeaders['User-Agent'] = userAgent; details.requestHeaders['Referer'] = referer; callback({ requestHeaders: details.requestHeaders }); } ); console.log(`Success: Set "${userAgent}" as user agent header`); } /** * Sets epg browser window * @param workerWindow */ setEpgWorkerWindow(workerWindow: BrowserWindow): void { this.workerWindow = workerWindow; // store default user agent as fallback this.defaultUserAgent = this.workerWindow.webContents.getUserAgent(); } /** * Sets browser window of the main app window * @param mainWindow */ setMainWindow(mainWindow: BrowserWindow): void { this.mainWindow = mainWindow; } /** * Saves playlist to the localStorage * @param name name of the playlist * @param playlist playlist to save * @param urlOrPath absolute fs path or url of the playlist * @param uploadType upload type - by file or via an url */ createPlaylistObject( name: string, playlist: ParsedPlaylist, urlOrPath?: string, uploadType?: 'URL' | 'FILE' ): Playlist { return { id: guid(), _id: guid(), filename: name, title: name, count: playlist.items.length, playlist: { ...playlist, items: playlist.items.map((item) => ({ id: guid(), ...item, })), }, importDate: new Date().toISOString(), lastUsage: new Date().toISOString(), favorites: [], autoRefresh: false, ...(uploadType === 'URL' ? { url: urlOrPath } : {}), ...(uploadType === 'FILE' ? { filePath: urlOrPath } : {}), }; } /** * Updates the provided playlist in the database * @param id id of the playlist * @param data playlist data to update * @returns */ updatePlaylistById( id: string, data: Partial<Playlist> ): Promise<{ numAffected: number; upsert: boolean; }> { return db.update( { _id: id }, { $set: data, } ); } /** * Converts the fetched playlist string to the playlist object, updates it in the database and sends the updated playlists array back to the renderer * @param id id of the playlist to update * @param playlistString updated playlist as string * @param event ipc event to send the response back to the renderer */ async handlePlaylistRefresh( id: string, playlistString: string, event?: Electron.IpcMainEvent ): Promise<void> { const playlist: ParsedPlaylist = this.convertFileStringToPlaylist(playlistString); const updated = await this.updatePlaylistById(id, { playlist, count: playlist.items.length, updateDate: Date.now(), updateState: PlaylistUpdateState.UPDATED, }); if (!updated.numAffected || updated.numAffected === 0) { console.error('Error: Playlist details were not updated'); } if (event) { event.sender.send(PLAYLIST_UPDATE_RESPONSE, { message: `Success! The playlist was successfully updated (${playlist.items.length} channels)`, }); // send all playlists back to the renderer process this.sendAllPlaylists(event); } } /** * Fetches the playlist from the given url and triggers the update operation * @param id id of the playlist to update * @param playlistString updated playlist as string * @param event ipc event to send the response back to the renderer */ async fetchPlaylistByUrl( id: string, url: string, event?: Electron.IpcMainEvent ): Promise<void> { try { await axios .get(url) .then((result) => this.handlePlaylistRefresh(id, result.data, event) ); } catch (err) { this.updatePlaylistById(id, { updateState: PlaylistUpdateState.NOT_UPDATED, }); event.sender.send(ERROR, { message: `File not found. Please check the entered playlist URL again.`, status: err.response.status, }); } } /** * Fetches the playlist from the given path from the file system and triggers the update operation * @param id id of the playlist to update * @param playlistString updated playlist as string * @param event ipc event to send the response back to the renderer */ fetchPlaylistByFilePath( id: string, path: string, event?: Electron.IpcMainEvent ): void { try { fs.readFile(path, 'utf-8', (err, data) => { if (err) { this.handleFileNotFoundError(err, id, event); return; } this.handlePlaylistRefresh(id, data, event); }); } catch (err) { this.handleFileNotFoundError(err, id, event); } } /** * Sends an error message to the renderer process * @param error * @param id * @param event */ handleFileNotFoundError( error: { errno: string; code: string; syscall: string; path: string; }, id: string, event?: Electron.IpcMainEvent ): void { console.error(error); this.updatePlaylistById(id, { updateState: PlaylistUpdateState.NOT_UPDATED, }); if (event) { // send all playlists back to the renderer process this.sendAllPlaylists(event); event.sender.send(ERROR, { message: `Sorry, playlist was not found (${error.path})`, status: 'ENOENT', }); } } convertFileStringToPlaylist(m3uString: string): ParsedPlaylist { return this.parsePlaylist(m3uString.split('\n')); } /** * Parses string based array to playlist object * @param m3uArray m3u playlist as array with strings */ parsePlaylist(m3uArray: string[]): ParsedPlaylist { const playlistAsString = m3uArray.join('\n'); return parse(playlistAsString); } /** * Inserts new playlist to the database * @param playlist playlist to add */ insertToDb(playlist: Playlist): void { db.insert(playlist).then((response) => { console.log('playlist was saved...', response._id); }); } }
the_stack
import { bson } from '@mongosh/service-provider-core'; import chai, { expect } from 'chai'; import { Duplex, PassThrough } from 'stream'; import Nanobus from 'nanobus'; import path from 'path'; import { promises as fs } from 'fs'; import { promisify } from 'util'; import rimraf from 'rimraf'; import sinon from 'ts-sinon'; import sinonChai from 'sinon-chai'; import { Editor, EditorOptions } from './editor'; chai.use(sinonChai); interface FakeEditor { fakeLoadExternalCodeResult?: any; cmd?: string, contextObject?: any } function useTmpdir(): { readonly path: string } { let tmpdir: string; beforeEach(async() => { tmpdir = path.resolve(__dirname, '..', '..', '..', 'tmp', 'test', `editor-${Date.now()}-${new bson.ObjectId()}`); await fs.mkdir(tmpdir, { recursive: true }); }); afterEach(async() => { try { await promisify(rimraf)(tmpdir); } catch (err) { // On Windows in CI, this can fail with EPERM for some reason. // If it does, just log the error instead of failing all tests. console.error('Could not remove fake home directory:', err); } }); return { get path(): string { return tmpdir; } }; } const fakeExternalEditor = async( { base, name, flags = '', output }: { base: string, name: string, flags?: string, output?: string } ): Promise<string> => { const tmpDoc = path.join(base, name); let script: string; if (typeof output === 'string') { script = `(async () => { const tmpDoc = process.argv[process.argv.length - 1]; const { promises: { writeFile } } = require('fs'); await writeFile(tmpDoc, ${JSON.stringify(output)}, { mode: 0o600 }); })()`; } else { script = 'process.exit(1);'; } await fs.mkdir(path.dirname(tmpDoc), { recursive: true, mode: 0o700 }); await fs.writeFile(tmpDoc, script, { mode: 0o600 }); return `node "${tmpDoc}" ${flags}`; }; describe('Editor', () => { const base = useTmpdir(); let input: Duplex; let vscodeDir: string; let tmpDir: string; let busMessages: ({ ev: any, data?: any })[]; let makeEditor: (data?: FakeEditor) => Editor; let makeEditorOptions: (data?: FakeEditor) => EditorOptions; let makeContextObject: (cmd?: string | null) => any; beforeEach(async() => { input = new PassThrough(); vscodeDir = path.join(base.path, '.vscode'); tmpDir = path.join(base.path, 'editor'); const messageBus = new Nanobus('mongosh-editor-test'); busMessages = []; messageBus.on('*', (ev: any, data: any) => { if (typeof data === 'number') { busMessages.push({ ev }); } else { busMessages.push({ ev, data }); } }); makeContextObject = (cmd: string | null = null) => ({ config: { get(key: string): any { switch (key) { case 'editor': return cmd; default: throw new Error(`Don’t know what to do with config key ${key}`); } } }, print: sinon.stub() }); makeEditorOptions = (data: FakeEditor = {}): EditorOptions => { const { fakeLoadExternalCodeResult, cmd, contextObject = makeContextObject(cmd) } = data; return { input, vscodeDir, tmpDir, instanceState: { context: contextObject, shellApi: contextObject, registerPlugin: sinon.stub(), messageBus } as any, loadExternalCode: (): Promise<any> => Promise.resolve(fakeLoadExternalCodeResult) }; }; makeEditor = (data: FakeEditor = {}) => new Editor(makeEditorOptions(data)); // make nyc happy when we spawn npm below await fs.mkdir(path.resolve(base.path, '.mongodb', '.nyc_output', 'processinfo'), { recursive: true }); await fs.mkdir(path.resolve(base.path, 'mongodb', '.nyc_output', 'processinfo'), { recursive: true }); }); describe('create', () => { it('returns an editor instance', () => { const editor = Editor.create(makeEditorOptions()); expect(typeof editor).to.be.equal('object'); expect(editor instanceof Editor).to.be.equal(true); }); }); describe('wrapper fn', () => { it('returns a "synthetic" promise', async() => { const cmd = await fakeExternalEditor({ base: base.path, name: 'editor-script.js', output: '' }); const contextObject = makeContextObject(cmd); Editor.create(makeEditorOptions({ contextObject })); const result = contextObject.edit(); expect(result[Symbol.for('@@mongosh.syntheticPromise')]).to.equal(true); expect(await result).to.not.exist; }); }); describe('_getExtension', () => { let editor: Editor; beforeEach(() => { delete process.env.EDITOR; editor = makeEditor(); }); context('when editor is node command', () => { it('returns js', async() => { const cmd = 'node editor-script.js'; const extension = await editor._getExtension(cmd); expect(extension).to.be.equal('js'); }); }); context('when editor is executable file', () => { context('not vscode', () => { it('returns js', async() => { const cmd = '/path/to/some/executable'; const extension = await editor._getExtension(cmd); expect(extension).to.be.equal('js'); }); }); context('vscode', () => { context('when mongodb extension is not installed', () => { it('returns js', async() => { const cmd = 'code'; const extension = await editor._getExtension(cmd); expect(extension).to.be.equal('js'); }); }); context('when mongodb extension is installed', () => { beforeEach(async() => { // make a fake dir for vscode mongodb extension await fs.mkdir( path.join(vscodeDir, 'extensions', 'mongodb.mongodb-vscode-0.0.0'), { recursive: true } ); }); it('returns mongodb for code command', async() => { const cmd = 'code'; const extension = await editor._getExtension(cmd); expect(extension).to.be.equal('mongodb'); }); it('returns mongodb for code path', async() => { const cmd = '/usr/local/bin/code'; const extension = await editor._getExtension(cmd); expect(extension).to.be.equal('mongodb'); }); it('returns mongodb for code.exe', async() => { const cmd = '/usr/local/bin/code.exe'; const extension = await editor._getExtension(cmd); expect(extension).to.be.equal('mongodb'); }); it('returns mongodb for code path with flag', async() => { const cmd = '/usr/local/bin/code --wait'; const extension = await editor._getExtension(cmd); expect(extension).to.be.equal('mongodb'); }); }); }); }); }); describe('_getEditor', () => { let editor: Editor; beforeEach(() => { delete process.env.EDITOR; }); it('returns an editor value from process.env.EDITOR', async() => { process.env.EDITOR = 'neweprocessditor'; editor = makeEditor(); const editorName = await editor._getEditor(); expect(editorName).to.be.equal(process.env.EDITOR); }); it('returns an editor value from the mongosh config', async() => { process.env.EDITOR = 'neweprocessditor'; editor = makeEditor({ cmd: 'newcmdeditor' }); const editorName = await editor._getEditor(); expect(editorName).to.be.equal('newcmdeditor'); }); }); describe('_isVscodeApp', () => { let editor: Editor; beforeEach(() => { editor = makeEditor(); }); it('returns true if command is code', () => { const isVscodeApp = editor._isVscodeApp('code'); expect(isVscodeApp).to.be.equal(true); }); it('returns true if command is path to code', () => { const isVscodeApp = editor._isVscodeApp('/usr/local/bin/code'); expect(isVscodeApp).to.be.equal(true); }); it('returns true if command is path to code on windows', () => { const isVscodeApp = editor._isVscodeApp('C:\\Program Files\\Microsoft VS Code\\Code.exe'); expect(isVscodeApp).to.be.equal(true); }); it('returns false if command is nano', () => { const isVscodeApp = editor._isVscodeApp('nano'); expect(isVscodeApp).to.be.equal(false); }); }); describe('_isIdentifier', () => { let editor: Editor; beforeEach(() => { editor = makeEditor(); }); it('returns false if a command is an empty find statement', () => { const isIdentifier = editor._isIdentifier('db.test.find()'); expect(isIdentifier).to.be.equal(false); }); it('returns false if a command is a find statement with a query', () => { const isIdentifier = editor._isIdentifier("db.test.find({ name: 'lena' })"); expect(isIdentifier).to.be.equal(false); }); it('returns true if a command is an identifier written with dots', () => { const isIdentifier = editor._isIdentifier('db.test.find'); expect(isIdentifier).to.be.equal(true); }); it('returns false if a command is an identifier written as an array and double quotes', () => { const isIdentifier = editor._isIdentifier('db["test"]find'); expect(isIdentifier).to.be.equal(false); }); it('returns false if a command is an identifier written as an array and single quotes', () => { const isIdentifier = editor._isIdentifier("db['test']find"); expect(isIdentifier).to.be.equal(false); }); it('returns true if it contains $', () => { const isIdentifier = editor._isIdentifier('$something'); expect(isIdentifier).to.be.equal(true); }); it('returns false for sum of numbers', () => { const isIdentifier = editor._isIdentifier('1 + 2'); expect(isIdentifier).to.be.equal(false); }); it('returns false for a class', () => { const isIdentifier = editor._isIdentifier('class A {}'); expect(isIdentifier).to.be.equal(false); }); it('returns false for a string', () => { const isIdentifier = editor._isIdentifier('"some string"'); expect(isIdentifier).to.be.equal(false); }); it('returns false for a number', () => { const isIdentifier = editor._isIdentifier('111'); expect(isIdentifier).to.be.equal(false); }); }); describe('_getEditorContent', () => { let editor: Editor; it('returns a function implementation', async() => { const fakeLoadExternalCodeResult = function wrapper(...args: any[]) { return { args, done: true }; }; editor = makeEditor({ fakeLoadExternalCodeResult }); const code = 'db.test.find'; const content = (await editor._getEditorContent(code)).replace(/\r\n/g, '\n'); expect(content).to.be.equal('function wrapper(...args) {\n return { args, done: true };\n }'); }); it('returns var', async() => { editor = makeEditor({ fakeLoadExternalCodeResult: 111 }); const code = 'myVar'; const content = (await editor._getEditorContent(code)); expect(content).to.be.equal('111'); }); it('returns a.b.c', async() => { editor = makeEditor({ fakeLoadExternalCodeResult: { field: { child: 'string value' } } }); const code = 'myObj'; const content = (await editor._getEditorContent(code)); expect(content).to.be.equal('{"field":{"child":"string value"}}'); }); it('returns function', async() => { editor = makeEditor(); const code = "function foo() { return 'a b'; }"; const content = await editor._getEditorContent(code); expect(content).to.be.equal(code); }); it('returns an unmodified statment', async() => { editor = makeEditor(); const code = 'db.coll.find()'; const content = await editor._getEditorContent(code); expect(content).to.be.equal(code); }); it('returns a string', async() => { editor = makeEditor({ fakeLoadExternalCodeResult: 111 }); const code = '"111"'; const content = await editor._getEditorContent(code); expect(content).to.be.equal(code); }); it('returns the last opened content for the empty edit command', async() => { editor = makeEditor(); editor._lastContent = 'db.test.find()'; const content = await editor._getEditorContent(''); expect(content).to.be.equal('db.test.find()'); }); it('returns a new content for not empty edit command', async() => { editor = makeEditor(); editor._lastContent = 'db.coll.find()'; const content = await editor._getEditorContent('1 + 1'); expect(content).to.be.equal('1 + 1'); }); }); describe('_prepareResult', () => { let editor: Editor; beforeEach(() => { editor = makeEditor(); }); it('returns an assignment statement for an identifier', () => { const result = editor._prepareResult({ originalCode: 'fn', modifiedCode: 'function() { console.log(222); };' }); expect(result).to.be.equal('fn = function() { console.log(222); };'); }); it('returns an assignment statement for an identifier', () => { const result = editor._prepareResult({ originalCode: '111', modifiedCode: '222' }); expect(result).to.be.equal('222'); }); }); describe('runEditCommand', () => { let editor: Editor; beforeEach(() => { delete process.env.EDITOR; }); context('when editor is not defined', () => { it('returns please define an external editor error', async() => { editor = makeEditor(); try { await editor.runEditCommand(''); } catch (error) { expect(error.message).to.include('Command failed with an error: please define an external editor'); } }); }); context('when editor is defined', () => { it('returns an error when editor exits with exitCode 1', async() => { const cmd = await fakeExternalEditor({ base: base.path, name: 'editor-script.js' }); editor = makeEditor({ cmd }); try { await editor.runEditCommand('function() {}'); } catch (error) { expect(error.message).to.include('failed with an exit code 1'); } }); it('returns a modified find statement to the mongosh input', async() => { const shellOriginalInput = 'db.test.find()'; const editorOutput = `db.test.find({ field: 'new value' })`; const shellModifiedInput = "db.test.find({ field: 'new value' })"; const cmd = await fakeExternalEditor({ base: base.path, name: 'editor-script.js', output: editorOutput }); editor = makeEditor({ cmd }); await editor.runEditCommand(shellOriginalInput); const shellResult = editor._input.read().toString(); expect(shellResult).to.be.equal(shellModifiedInput); }); it('writes a modified function statement to the mongosh input', async() => { const shellOriginalInput = 'function () {}'; const editorOutput = `function () { console.log(111); }`; const shellModifiedInput = 'function () { console.log(111); }'; const cmd = await fakeExternalEditor({ base: base.path, name: 'editor-script.js', output: editorOutput }); editor = makeEditor({ cmd }); await editor.runEditCommand(shellOriginalInput); const shellResult = editor._input.read().toString(); expect(shellResult).to.be.equal(shellModifiedInput); }); it('allows spaces in the editor name', async() => { const shellOriginalInput = '"some string"'; const editorOutput = '"some modified string"'; const shellModifiedInput = '"some modified string"'; const cmd = await fakeExternalEditor({ base: base.path, name: 'editor script.js', output: editorOutput }); editor = makeEditor({ cmd }); await editor.runEditCommand(shellOriginalInput); const shellResult = editor._input.read().toString(); expect(shellResult).to.be.equal(shellModifiedInput); }); it('allows flags in the editor', async() => { const shellOriginalInput = '"some string"'; const editorOutput = '"some modified string"'; const shellModifiedInput = '"some modified string"'; const cmd = await fakeExternalEditor({ base: base.path, name: 'editor-script.js', flags: '--trace-warnings', output: editorOutput }); editor = makeEditor({ cmd }); await editor.runEditCommand(shellOriginalInput); const shellResult = editor._input.read().toString(); expect(shellResult).to.be.equal(shellModifiedInput); }); it('returns a proper statement when editing previous code - input is not a statement', async() => { const shellOriginalInput = 'foo'; const editorOutput = '20'; const shellModifiedInput = 'foo = 20'; const cmd = await fakeExternalEditor({ base: base.path, name: 'editor-script.js', output: editorOutput }); editor = makeEditor({ cmd }); await editor.runEditCommand(shellOriginalInput); let shellResult = editor._input.read().toString(); expect(shellResult).to.be.equal(shellModifiedInput); await editor.runEditCommand(''); shellResult = editor._input.read().toString(); expect(shellResult).to.be.equal(shellModifiedInput); }); it('returns a proper statement when editing previous code - input is a statement', async() => { const shellOriginalInput = 'function () {}'; const editorOutput = `function () { console.log(111); }`; const shellModifiedInput = 'function () { console.log(111); }'; const cmd = await fakeExternalEditor({ base: base.path, name: 'editor-script.js', output: editorOutput }); editor = makeEditor({ cmd }); await editor.runEditCommand(shellOriginalInput); let shellResult = editor._input.read().toString(); expect(shellResult).to.be.equal(shellModifiedInput); await editor.runEditCommand(''); shellResult = editor._input.read().toString(); expect(shellResult).to.be.equal(shellModifiedInput); }); }); }); });
the_stack
//@ts-check ///<reference path="devkit.d.ts" /> declare namespace DevKit { namespace FormProductPriceLevel_Information { interface tab_general_Sections { price_list_item_information: DevKit.Controls.Section; pricing: DevKit.Controls.Section; rounding: DevKit.Controls.Section; } interface tab_general extends DevKit.Controls.ITab { Section: tab_general_Sections; } interface Tabs { general: tab_general; } interface Body { Tab: Tabs; /** Monetary amount for the price list. */ Amount: DevKit.Controls.Money; /** Unique identifier of the discount list associated with the price list. */ DiscountTypeId: DevKit.Controls.Lookup; /** Percentage for the price list. */ Percentage: DevKit.Controls.Decimal; /** Unique identifier of the price level associated with this price list. */ PriceLevelId: DevKit.Controls.Lookup; /** Pricing method applied to the price list. */ PricingMethodCode: DevKit.Controls.OptionSet; /** Product associated with the price list. */ ProductId: DevKit.Controls.Lookup; /** Quantity of the product that must be sold for a given price level. */ QuantitySellingCode: DevKit.Controls.OptionSet; /** Rounding option amount for the price list. */ RoundingOptionAmount: DevKit.Controls.Money; /** Option for rounding the price list. */ RoundingOptionCode: DevKit.Controls.OptionSet; /** Policy for rounding the price list. */ RoundingPolicyCode: DevKit.Controls.OptionSet; /** Choose the local currency for the record to make sure budgets are reported in the correct currency. */ TransactionCurrencyId: DevKit.Controls.Lookup; /** Unique identifier of the unit for the price list. */ UoMId: DevKit.Controls.Lookup; } } class FormProductPriceLevel_Information extends DevKit.IForm { /** * DynamicsCrm.DevKit form ProductPriceLevel_Information * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form ProductPriceLevel_Information */ Body: DevKit.FormProductPriceLevel_Information.Body; } namespace FormProduct_Price_List { interface tab_general_Sections { Currency: DevKit.Controls.Section; price_list_item_information: DevKit.Controls.Section; } interface tab_Pricing_information_Sections { pricing: DevKit.Controls.Section; rounding: DevKit.Controls.Section; } interface tab_general extends DevKit.Controls.ITab { Section: tab_general_Sections; } interface tab_Pricing_information extends DevKit.Controls.ITab { Section: tab_Pricing_information_Sections; } interface Tabs { general: tab_general; Pricing_information: tab_Pricing_information; } interface Body { Tab: Tabs; /** Monetary amount for the price list. */ Amount: DevKit.Controls.Money; /** Unique identifier of the discount list associated with the price list. */ DiscountTypeId: DevKit.Controls.Lookup; /** Percentage for the price list. */ Percentage: DevKit.Controls.Decimal; /** Unique identifier of the price level associated with this price list. */ PriceLevelId: DevKit.Controls.Lookup; /** Pricing method applied to the price list. */ PricingMethodCode: DevKit.Controls.OptionSet; /** Product associated with the price list. */ ProductId: DevKit.Controls.Lookup; /** Quantity of the product that must be sold for a given price level. */ QuantitySellingCode: DevKit.Controls.OptionSet; /** Rounding option amount for the price list. */ RoundingOptionAmount: DevKit.Controls.Money; /** Option for rounding the price list. */ RoundingOptionCode: DevKit.Controls.OptionSet; /** Policy for rounding the price list. */ RoundingPolicyCode: DevKit.Controls.OptionSet; /** Choose the local currency for the record to make sure budgets are reported in the correct currency. */ TransactionCurrencyId: DevKit.Controls.Lookup; /** Unique identifier of the unit for the price list. */ UoMId: DevKit.Controls.Lookup; } } class FormProduct_Price_List extends DevKit.IForm { /** * DynamicsCrm.DevKit form Product_Price_List * @param executionContext the execution context * @param defaultWebResourceName default resource name. E.g.: "devkit_/resources/Resource" */ constructor(executionContext: any, defaultWebResourceName?: string); /** Utility functions/methods/objects for Dynamics 365 form */ Utility: DevKit.Utility; /** The Body section of form Product_Price_List */ Body: DevKit.FormProduct_Price_List.Body; } class ProductPriceLevelApi { /** * DynamicsCrm.DevKit ProductPriceLevelApi * @param entity The entity object */ constructor(entity?: any); /** * Get the value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedValue(alias: string, isMultiOptionSet?: boolean): any; /** * Get the formatted value of alias * @param alias the alias value * @param isMultiOptionSet true if the alias is multi OptionSet */ getAliasedFormattedValue(alias: string, isMultiOptionSet?: boolean): string; /** The entity object */ Entity: any; /** The entity name */ EntityName: string; /** The entity collection name */ EntityCollectionName: string; /** The @odata.etag is then used to build a cache of the response that is dependant on the fields that are retrieved */ "@odata.etag": string; /** Monetary amount for the price list. */ Amount: DevKit.WebApi.MoneyValue; /** Value of the Amount in base currency. */ Amount_Base: DevKit.WebApi.MoneyValueReadonly; /** Unique identifier of the user who created the price list. */ CreatedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the price list was created. */ CreatedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who created the record on behalf of another user. */ CreatedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the discount list associated with the price list. */ DiscountTypeId: DevKit.WebApi.LookupValue; /** Shows the conversion rate of the record's currency. The exchange rate is used to convert all money fields in the record from the local currency to the system's default currency. */ ExchangeRate: DevKit.WebApi.DecimalValueReadonly; /** Sequence number of the import that created this record. */ ImportSequenceNumber: DevKit.WebApi.IntegerValue; /** Unique identifier of the user who last modified the price list. */ ModifiedBy: DevKit.WebApi.LookupValueReadonly; /** Date and time when the price list was last modified. */ ModifiedOn_UtcDateAndTime: DevKit.WebApi.UtcDateAndTimeValueReadonly; /** Shows who last updated the record on behalf of another user. */ ModifiedOnBehalfBy: DevKit.WebApi.LookupValueReadonly; /** Unique identifier of the organization associated with the price list. */ OrganizationId: DevKit.WebApi.GuidValueReadonly; /** Date and time that the record was migrated. */ OverriddenCreatedOn_UtcDateOnly: DevKit.WebApi.UtcDateOnlyValue; /** Percentage for the price list. */ Percentage: DevKit.WebApi.DecimalValue; /** Unique identifier of the price level associated with this price list. */ PriceLevelId: DevKit.WebApi.LookupValue; /** Pricing method applied to the price list. */ PricingMethodCode: DevKit.WebApi.OptionSetValue; /** Contains the id of the process associated with the entity. */ ProcessId: DevKit.WebApi.GuidValue; /** Product associated with the price list. */ ProductId: DevKit.WebApi.LookupValue; /** User-defined product number. */ ProductNumber: DevKit.WebApi.StringValueReadonly; /** Unique identifier of the price list. */ ProductPriceLevelId: DevKit.WebApi.GuidValue; /** Quantity of the product that must be sold for a given price level. */ QuantitySellingCode: DevKit.WebApi.OptionSetValue; /** Rounding option amount for the price list. */ RoundingOptionAmount: DevKit.WebApi.MoneyValue; /** Value of the Rounding Amount in base currency. */ RoundingOptionAmount_Base: DevKit.WebApi.MoneyValueReadonly; /** Option for rounding the price list. */ RoundingOptionCode: DevKit.WebApi.OptionSetValue; /** Policy for rounding the price list. */ RoundingPolicyCode: DevKit.WebApi.OptionSetValue; /** Contains the id of the stage where the entity is located. */ StageId: DevKit.WebApi.GuidValue; /** For internal use only. */ TimeZoneRuleVersionNumber: DevKit.WebApi.IntegerValue; /** Choose the local currency for the record to make sure budgets are reported in the correct currency. */ TransactionCurrencyId: DevKit.WebApi.LookupValue; /** A comma separated list of string values representing the unique identifiers of stages in a Business Process Flow Instance in the order that they occur. */ TraversedPath: DevKit.WebApi.StringValue; /** Unique identifier of the unit for the price list. */ UoMId: DevKit.WebApi.LookupValue; /** Unique identifier of the unit schedule for the price list. */ UoMScheduleId: DevKit.WebApi.LookupValue; /** Time zone code that was in use when the record was created. */ UTCConversionTimeZoneCode: DevKit.WebApi.IntegerValue; /** Version Number */ VersionNumber: DevKit.WebApi.BigIntValueReadonly; } } declare namespace OptionSet { namespace ProductPriceLevel { enum PricingMethodCode { /** 1 */ Currency_Amount, /** 4 */ Percent_Margin_Current_Cost, /** 6 */ Percent_Margin_Standard_Cost, /** 3 */ Percent_Markup_Current_Cost, /** 5 */ Percent_Markup_Standard_Cost, /** 2 */ Percent_of_List } enum QuantitySellingCode { /** 1 */ No_Control, /** 2 */ Whole, /** 3 */ Whole_and_Fractional } enum RoundingOptionCode { /** 1 */ Ends_in, /** 2 */ Multiple_of } enum RoundingPolicyCode { /** 3 */ Down, /** 1 */ None, /** 4 */ To_Nearest, /** 2 */ Up } enum RollupState { /** 0 - Attribute value is yet to be calculated */ NotCalculated, /** 1 - Attribute value has been calculated per the last update time in <AttributeSchemaName>_Date attribute */ Calculated, /** 2 - Attribute value calculation lead to overflow error */ OverflowError, /** 3 - Attribute value calculation failed due to an internal error, next run of calculation job will likely fix it */ OtherError, /** 4 - Attribute value calculation failed because the maximum number of retry attempts to calculate the value were exceeded likely due to high number of concurrency and locking conflicts */ RetryLimitExceeded, /** 5 - Attribute value calculation failed because maximum hierarchy depth limit for calculation was reached */ HierarchicalRecursionLimitReached, /** 6 - Attribute value calculation failed because a recursive loop was detected in the hierarchy of the record */ LoopDetected } } } //{'JsForm':['Information','Product Price List'],'JsWebApi':true,'IsDebugForm':true,'IsDebugWebApi':true,'Version':'2.12.31','JsFormVersion':'v2'}
the_stack
import assert from "assert"; import { deserialize, serialize } from "v8"; import { OutputGate, Storage, StoredValue, addAll, runWithInputGateClosed, viewToArray, waitUntilOnOutputGate, } from "@miniflare/shared"; import { DurableObjectError } from "./error"; import { ReadWriteMutex } from "./rwmutex"; import { ShadowStorage } from "./shadow"; const MAX_KEYS = 128; const MAX_KEY_SIZE = 2048; /* 2KiB */ const MAX_VALUE_SIZE = 128 * 1024; /* 128KiB */ // As V8 serialisation adds some tagging information, Workers actually allows // values to be 32 bytes greater than the advertised limit. This allows 128KiB // byte arrays to be stored for example. const ENFORCED_MAX_VALUE_SIZE = MAX_VALUE_SIZE + 32; const undefinedKeyError = ": parameter 1 is not of type 'variant'. (key is undefined)"; function intersects<T>(a: Set<T>, b: Set<T>): boolean { for (const value of a) if (b.has(value)) return true; return false; } export interface DurableObjectGetOptions { allowConcurrency?: boolean; noCache?: boolean; // Currently ignored } export interface DurableObjectPutOptions extends DurableObjectGetOptions { allowUnconfirmed?: boolean; } export interface DurableObjectListOptions extends DurableObjectGetOptions { start?: string; end?: string; prefix?: string; reverse?: boolean; limit?: number; } export interface DurableObjectOperator { get<Value = unknown>( key: string, options?: DurableObjectGetOptions ): Promise<Value | undefined>; get<Value = unknown>( keys: string[], options?: DurableObjectGetOptions ): Promise<Map<string, Value>>; put<Value = unknown>( key: string, value: Value, options?: DurableObjectPutOptions ): Promise<void>; put<Value = unknown>( entries: Record<string, Value>, options?: DurableObjectPutOptions ): Promise<void>; delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; list<Value = unknown>( options?: DurableObjectListOptions ): Promise<Map<string, Value>>; } function assertKeySize(key: string, many = false) { if (Buffer.byteLength(key) <= MAX_KEY_SIZE) return; if (many) { throw new RangeError( `Key "${key}" is larger than the limit of ${MAX_KEY_SIZE} bytes.` ); } throw new RangeError(`Keys cannot be larger than ${MAX_KEY_SIZE} bytes.`); } function assertValueSize(value: Buffer, key?: string) { if (value.byteLength <= ENFORCED_MAX_VALUE_SIZE) return; if (key !== undefined) { throw new RangeError( `Value for key "${key}" is above the limit of ${MAX_VALUE_SIZE} bytes.` ); } throw new RangeError(`Values cannot be larger than ${MAX_VALUE_SIZE} bytes.`); } function helpfulDeserialize(buffer: NodeJS.TypedArray): any { try { return deserialize(buffer); } catch (e: any) { throw new DurableObjectError( "ERR_DESERIALIZATION", "Unable to deserialize stored Durable Object data due to an " + "invalid or unsupported version.\nThe Durable Object data storage " + "format changed in Miniflare 2. You cannot load Durable Object data " + "created with Miniflare 1 and must delete it.", e ); } } async function get<Value = unknown>( storage: Storage, key: string, checkMaxKeys?: boolean ): Promise<Value | undefined>; // noinspection JSUnusedLocalSymbols async function get<Value = unknown>( storage: Storage, keys: string[], checkMaxKeys?: boolean ): Promise<Map<string, Value>>; async function get<Value = unknown>( storage: Storage, keys: string | string[], checkMaxKeys = true ): Promise<Value | undefined | Map<string, Value>> { if (Array.isArray(keys)) { if (checkMaxKeys && keys.length > MAX_KEYS) { throw new RangeError(`Maximum number of keys is ${MAX_KEYS}.`); } // Filter out undefined keys const defined: string[] = []; for (const key of keys) { if (key === undefined) continue; defined.push(key); assertKeySize(key, true); } // If array of keys passed, build map of results const res = new Map<string, Value>(); const values = await storage.getMany(defined); assert.strictEqual(defined.length, values.length); for (let i = 0; i < defined.length; i++) { const value = values[i]; if (value !== undefined) { res.set(defined[i], helpfulDeserialize(value.value)); } } return res; } // Otherwise, return a single result assertKeySize(keys); const value = await storage.get(keys); return value && helpfulDeserialize(value.value); } async function list<Value = unknown>( storage: Storage, options: DurableObjectListOptions = {} ): Promise<Map<string, Value>> { if (options.limit !== undefined && options.limit <= 0) { throw new TypeError("List limit must be positive."); } const { keys } = await storage.list(options); return get( storage, keys.map(({ name }) => name), // Allow listing more than MAX_KEYS keys false /* checkMaxKeys */ ); } function normalisePutEntries<Value = unknown>( keyEntries: string | Record<string, Value>, valueOptions?: Value ): [key: string, value: StoredValue][] { if (typeof keyEntries === "string") { assertKeySize(keyEntries); if (valueOptions === undefined) { throw new TypeError("put() called with undefined value."); } const serialized = serialize(valueOptions); assertValueSize(serialized); return [[keyEntries, { value: viewToArray(serialized) }]]; } const entries = Object.entries(keyEntries); if (entries.length > MAX_KEYS) { throw new RangeError(`Maximum number of pairs is ${MAX_KEYS}.`); } const result: [key: string, value: StoredValue][] = []; for (const [key, rawValue] of entries) { assertKeySize(key, true); if (rawValue === undefined) continue; const serialized = serialize(rawValue); assertValueSize(serialized, key); result.push([key, { value: viewToArray(serialized) }]); } return result; } function normaliseDeleteKeys(keys: string | string[]): string[] { if (Array.isArray(keys)) { if (keys.length > MAX_KEYS) { throw new RangeError(`Maximum number of keys is ${MAX_KEYS}.`); } const defined: string[] = []; for (const key of keys) { if (key === undefined) continue; assertKeySize(key, true); defined.push(key); } return defined; } else { assertKeySize(keys); return [keys]; } } const kInner = Symbol("kInner"); const kStartTxnCount = Symbol("kStartTxnCount"); const kRolledback = Symbol("kRolledback"); const kCommitted = Symbol("kCommitted"); const kWriteSet = Symbol("kWriteSet"); export class DurableObjectTransaction implements DurableObjectOperator { readonly [kInner]: ShadowStorage; readonly [kStartTxnCount]: number; [kRolledback] = false; [kCommitted] = false; readonly [kWriteSet] = new Set<string>(); constructor(inner: Storage, startTxnCount: number) { this[kInner] = new ShadowStorage(inner); this[kStartTxnCount] = startTxnCount; } #check(op: string): void { if (this[kRolledback]) { throw new Error(`Cannot ${op}() on rolled back transaction`); } if (this[kCommitted]) { throw new Error( `Cannot call ${op}() on transaction that has already committed: did you move \`txn\` outside of the closure?` ); } } #markWritten(...keys: string[]): void { addAll(this[kWriteSet], keys); if (this[kWriteSet].size > MAX_KEYS) { throw new Error( `Maximum number of keys modified in a transaction is ${MAX_KEYS}.` ); } } get<Value = unknown>( key: string, options?: DurableObjectGetOptions ): Promise<Value | undefined>; get<Value = unknown>( keys: string[], options?: DurableObjectGetOptions ): Promise<Map<string, Value>>; get<Value = unknown>( keys: string | string[], options?: DurableObjectGetOptions ): Promise<Value | undefined | Map<string, Value>> { if (keys === undefined) { throw new TypeError( "Failed to execute 'get' on 'DurableObjectTransaction'" + undefinedKeyError ); } this.#check("get"); return runWithInputGateClosed( () => get(this[kInner], keys as any), options?.allowConcurrency ); } #put<Value = unknown>( keyEntries: string | Record<string, Value>, valueOptions?: Value ): Promise<void> { const entries = normalisePutEntries(keyEntries, valueOptions); this.#markWritten(...entries.map(([key]) => key)); return this[kInner].putMany(entries); } put<Value = unknown>( key: string, value: Value, options?: DurableObjectPutOptions ): Promise<void>; put<Value = unknown>( entries: Record<string, Value>, options?: DurableObjectPutOptions ): Promise<void>; put<Value = unknown>( keyEntries: string | Record<string, Value>, valueOptions?: Value | DurableObjectPutOptions, options?: DurableObjectPutOptions ): Promise<void> { if (keyEntries === undefined) { throw new TypeError( "Failed to execute 'put' on 'DurableObjectTransaction'" + undefinedKeyError ); } this.#check("put"); if (!options && typeof keyEntries !== "string") options = valueOptions; return waitUntilOnOutputGate( runWithInputGateClosed( () => this.#put(keyEntries, valueOptions), options?.allowConcurrency ), options?.allowUnconfirmed ); } #delete(keys: string | string[]): Promise<boolean | number> { const keysIsArray = Array.isArray(keys); keys = normaliseDeleteKeys(keys); this.#markWritten(...keys); return keysIsArray ? this[kInner].deleteMany(keys) : Promise.resolve(this[kInner].delete(keys[0])); } delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; delete( keys: string | string[], options?: DurableObjectPutOptions ): Promise<boolean | number> { if (keys === undefined) { throw new TypeError( "Failed to execute 'delete' on 'DurableObjectTransaction'" + undefinedKeyError ); } this.#check("delete"); return waitUntilOnOutputGate( runWithInputGateClosed( () => this.#delete(keys), options?.allowConcurrency ), options?.allowUnconfirmed ); } deleteAll(): never { throw new Error("Cannot call deleteAll() within a transaction"); } list<Value = unknown>( options: DurableObjectListOptions = {} ): Promise<Map<string, Value>> { this.#check("list"); return runWithInputGateClosed( () => list(this[kInner], options), options.allowConcurrency ); } rollback(): void { if (this[kRolledback]) return; // Allow multiple rollback() calls this.#check("rollback"); this[kRolledback] = true; } } // Maximum size of txnWriteSets map for validation, this is basically the // maximum number of concurrent transactions we expect to be running on a single // storage instance const txnWriteSetsMaxSize = 16; function runWithGatesClosed<T>( closure: () => Promise<T>, options?: DurableObjectPutOptions ): Promise<T> { return waitUntilOnOutputGate( runWithInputGateClosed(closure, options?.allowConcurrency), options?.allowUnconfirmed ); } export class DurableObjectStorage implements DurableObjectOperator { readonly #mutex = new ReadWriteMutex(); #txnCount = 0; readonly #txnWriteSets = new Map<number, Set<string>>(); // Ordered array of keys deleted in delete calls #deletedKeySets: string[][] = []; // Map array reference to number of keys deleted from that array readonly #deletedKeyResults = new Map<string[], number>(); readonly #inner: Storage; // Shadow copies only used for write coalescing, not caching. Caching might // be added in the future, but it seemed redundant since most users will be // using in-memory storage anyways, and the file system isn't *too* slow. readonly #shadow: ShadowStorage; constructor(inner: Storage) { this.#inner = inner; // false disables recording readSet, only needed for transactions this.#shadow = new ShadowStorage(inner, false); } async #txnRead<T>( closure: (txn: DurableObjectTransaction) => Promise<T> ): Promise<{ txn: DurableObjectTransaction; result: T }> { // 1. Read Phase const startTxnCount = this.#txnCount; // Note txn uses #shadow as its inner storage, so in-progress non-durable // puts/deletes are visible const txn = new DurableObjectTransaction(this.#shadow, startTxnCount); const result = await closure(txn); // Might not actually commit, this is just for #check() txn[kCommitted] = true; return { txn, result }; } async #txnValidateWrite(txn: DurableObjectTransaction): Promise<boolean> { // This function returns false iff the transaction should be retried // Don't commit if rolledback if (txn[kRolledback]) return true; // Mutex needed as these phases need to be performed as a critical section return this.#mutex.runWithWrite(async () => { // 2. Validate Phase const finishTxnCount = this.#txnCount; const readSet = txn[kInner].readSet!; for (let t = txn[kStartTxnCount] + 1; t <= finishTxnCount; t++) { const otherWriteSet = await this.#txnWriteSets.get(t); if (!otherWriteSet || intersects(otherWriteSet, readSet)) { return false; } } // 3. Write Phase this.#txnRecordWriteSet(txn[kWriteSet]); for (const [key, value] of txn[kInner].copies.entries()) { this.#shadow.copies.set(key, value); } await this.#flush(); return true; }); } #txnRecordWriteSet(writeSet: Set<string>): void { this.#txnCount++; this.#txnWriteSets.set(this.#txnCount, writeSet); // Keep txnWriteSets.size <= txnMapSize: deleted ID may be negative // (i.e. transaction never existed), but delete on non-existent key is noop this.#txnWriteSets.delete(this.#txnCount - txnWriteSetsMaxSize); } transaction<T>( closure: (txn: DurableObjectTransaction) => Promise<T> ): Promise<T> { // Close input and output gate, we don't know what this transaction will do return runWithGatesClosed(async () => { // TODO (someday): maybe throw exception after n retries? while (true) { const outputGate = new OutputGate(); const { txn, result } = await outputGate.runWith(() => this.#txnRead(closure) ); if (await this.#txnValidateWrite(txn)) return result; } }); } get<Value = unknown>( key: string, options?: DurableObjectGetOptions ): Promise<Value | undefined>; get<Value = unknown>( keys: string[], options?: DurableObjectGetOptions ): Promise<Map<string, Value>>; async get<Value = unknown>( keys: string | string[], options?: DurableObjectGetOptions ): Promise<Value | undefined | Map<string, Value>> { if (keys === undefined) { throw new TypeError( "Failed to execute 'get' on 'DurableObjectStorage'" + undefinedKeyError ); } return runWithInputGateClosed( () => this.#mutex.runWithRead(() => get(this.#shadow, keys as any)), options?.allowConcurrency ); } #flush = async (): Promise<void> => { // Must be called with #mutex's write lock held // If already flushed everything, don't flush again if (this.#shadow.copies.size === 0) { assert.strictEqual(this.#deletedKeySets.length, 0); return; } // Copy deletedKeySets and entries at the start of the flush, as more values // may be added mid-way through. These will be handled on the next flush. const deletedKeySets = this.#deletedKeySets; this.#deletedKeySets = []; const entries = [...this.#shadow.copies.entries()]; // Keep non-durable data in shadow copies whilst writing, in case it's read // Try to delete everything before putting, so we don't delete data put // after call to delete. We still need to check with the database to see // if the keys were deleted, as the user might await the promise afterwards: // // ```js // // storage includes "key" // const promise = storage.delete("key"); // storage.put("key", "value"); // await promise; // should be true // ``` // // ```js // // storage doesn't include "key" // const promise = storage.delete("key"); // storage.put("key", "value"); // await promise; // should be false // ``` // // Record allDeletedKeys so we can record keys that aren't in deletedKeySets // (because they existed as shadow copies before hand so we know they would // be deleted), but still need to be deleted anyways. const allDeletedKeys = new Set<string>(); for (const deleteKeySet of deletedKeySets) { const result = await this.#inner.deleteMany(deleteKeySet); this.#deletedKeyResults.set(deleteKeySet, result); addAll(allDeletedKeys, deleteKeySet); } const putEntries: [key: string, value: StoredValue][] = []; const deleteKeys: string[] = []; for (const [key, value] of entries) { if (value) putEntries.push([key, value]); else if (!allDeletedKeys.has(key)) deleteKeys.push(key); } if (putEntries.length > 0) await this.#inner.putMany(putEntries); if (deleteKeys.length > 0) await this.#inner.deleteMany(deleteKeys); // TODO: can probably just clear the map here: as flush must be run with // the write mutex held and shadow copies are only mutated with that held, // we know the map won't be mutated during the flush // (check this is the only case copies #shadow.copies mutated) for (const [key, value] of entries) { // If shadow copy unchanged during flush, delete it as it's now durable, // otherwise, there must've been another call to put/delete which // will flush again with the now changed value. if (this.#shadow.copies.get(key) === value) { this.#shadow.copies.delete(key); } } }; put<Value = unknown>( key: string, value: Value, options?: DurableObjectPutOptions ): Promise<void>; put<Value = unknown>( entries: Record<string, Value>, options?: DurableObjectPutOptions ): Promise<void>; put<Value = unknown>( keyEntries: string | Record<string, Value>, valueOptions?: Value | DurableObjectPutOptions, options?: DurableObjectPutOptions ): Promise<void> { if (keyEntries === undefined) { throw new TypeError( "Failed to execute 'put' on 'DurableObjectStorage'" + undefinedKeyError ); } const entries = normalisePutEntries(keyEntries, valueOptions); if (!options && typeof keyEntries !== "string") options = valueOptions; return runWithGatesClosed(async () => { await this.#mutex.runWithWrite(() => { for (const [key, value] of entries) this.#shadow.put(key, value); // "Commit" write this.#txnRecordWriteSet(new Set(entries.map(([key]) => key))); }); // Promise.resolve() allows other puts/deletes (coalescing) before flush await Promise.resolve(); return this.#mutex.runWithWrite(this.#flush); }, options); } delete(key: string, options?: DurableObjectPutOptions): Promise<boolean>; delete(keys: string[], options?: DurableObjectPutOptions): Promise<number>; delete( keys: string | string[], options?: DurableObjectPutOptions ): Promise<boolean | number> { if (keys === undefined) { throw new TypeError( "Failed to execute 'delete' on 'DurableObjectStorage'" + undefinedKeyError ); } // Record this so we know whether to return a boolean or number at the end const keysIsArray = Array.isArray(keys); keys = normaliseDeleteKeys(keys); let deleted = 0; const deletedKeySet: string[] = []; return runWithGatesClosed(async () => { await this.#mutex.runWithWrite(() => { for (const key of keys) { // Filter out undefined keys if (key === undefined) continue; if (this.#shadow.copies.has(key)) { if (this.#shadow.copies.get(key) !== undefined) { // Previously called put with this key, no need to check if it got // deleted, we know it will deleted++; } // ...else, previously called delete with this key, no need to check if // it got deleted, we know it already has } else { // If we haven't done anything with this key yet, we need to check with // the database whether it's deleted deletedKeySet.push(key); } // Not using this.#shadow.delete as we need this to be synchronous this.#shadow.copies.set(key, undefined); } // If there are keys we need to check if deleted, record them, we'll do this // when we flush if (deletedKeySet.length) this.#deletedKeySets.push(deletedKeySet); // "Commit" delete this.#txnRecordWriteSet(new Set(keys)); }); // Promise.resolve() allows other puts/deletes (coalescing) before flush await Promise.resolve(); return this.#mutex.runWithWrite(async () => { await this.#flush(); if (deletedKeySet.length) { assert(!this.#deletedKeySets.includes(deletedKeySet)); const result = this.#deletedKeyResults.get(deletedKeySet); this.#deletedKeyResults.delete(deletedKeySet); assert(result !== undefined); deleted += result; } return keysIsArray ? deleted : deleted > 0; }); }, options); } async deleteAll(options?: DurableObjectPutOptions): Promise<void> { return runWithGatesClosed( () => this.#mutex.runWithWrite(async () => { const { keys } = await this.#shadow.list(); const names = keys.map(({ name }) => name); for (const key of names) this.#shadow.copies.set(key, undefined); this.#txnRecordWriteSet(new Set(names)); await this.#flush(); }), options ); } async list<Value = unknown>( options?: DurableObjectListOptions ): Promise<Map<string, Value>> { return runWithInputGateClosed( () => this.#mutex.runWithRead(() => list(this.#shadow, options)), options?.allowConcurrency ); } }
the_stack
namespace eui.sys { let SOLUTION_TOLERANCE = 0.1; let MIN_MAX_TOLERANCE = 0.1; /** * @private */ export class MatrixUtil { /** * @private */ public static fitBounds(width:number, height:number, matrix:egret.Matrix, explicitWidth:number, explicitHeight:number, preferredWidth:number, preferredHeight:number, minWidth:number, minHeight:number, maxWidth:number, maxHeight:number):egret.Point { if (isNaN(width) && isNaN(height)) return egret.Point.create(preferredWidth, preferredHeight); let newMinWidth = (minWidth < MIN_MAX_TOLERANCE) ? 0 : minWidth - MIN_MAX_TOLERANCE; let newMinHeight = (minHeight < MIN_MAX_TOLERANCE) ? 0 : minHeight - MIN_MAX_TOLERANCE; let newMaxWidth = maxWidth + MIN_MAX_TOLERANCE; let newMaxHeight = maxHeight + MIN_MAX_TOLERANCE; let actualSize:egret.Point; if (!isNaN(width) && !isNaN(height)) { actualSize = calcUBoundsToFitTBounds(width, height, matrix, newMinWidth, newMinHeight, newMaxWidth, newMaxHeight); if (!actualSize) { let actualSize1:egret.Point; actualSize1 = fitTBoundsWidth(width, matrix, explicitWidth, explicitHeight, preferredWidth, preferredHeight, newMinWidth, newMinHeight, newMaxWidth, newMaxHeight); if (actualSize1) { let fitHeight = transformSize(actualSize1.x, actualSize1.y, matrix).height; if (fitHeight - SOLUTION_TOLERANCE > height) { egret.Point.release(actualSize1); actualSize1 = null; } } let actualSize2:egret.Point actualSize2 = fitTBoundsHeight(height, matrix, explicitWidth, explicitHeight, preferredWidth, preferredHeight, newMinWidth, newMinHeight, newMaxWidth, newMaxHeight); if (actualSize2) { let fitWidth = transformSize(actualSize2.x, actualSize2.y, matrix).width; if (fitWidth - SOLUTION_TOLERANCE > width) { egret.Point.release(actualSize2); actualSize2 = null; } } if (actualSize1 && actualSize2) { actualSize = ((actualSize1.x * actualSize1.y) > (actualSize2.x * actualSize2.y)) ? actualSize1 : actualSize2; } else if (actualSize1) { actualSize = actualSize1; } else { actualSize = actualSize2; } egret.Point.release(actualSize1); egret.Point.release(actualSize2); } return actualSize; } else if (!isNaN(width)) { return fitTBoundsWidth(width, matrix, explicitWidth, explicitHeight, preferredWidth, preferredHeight, newMinWidth, newMinHeight, newMaxWidth, newMaxHeight); } else { return fitTBoundsHeight(height, matrix, explicitWidth, explicitHeight, preferredWidth, preferredHeight, newMinWidth, newMinHeight, newMaxWidth, newMaxHeight); } } } /** * @private */ function fitTBoundsWidth(width:number, matrix:egret.Matrix, explicitWidth:number, explicitHeight:number, preferredWidth:number, preferredHeight:number, minWidth:number, minHeight:number, maxWidth:number, maxHeight:number):egret.Point { let actualSize:egret.Point; if (!isNaN(explicitWidth) && isNaN(explicitHeight)) { actualSize = calcUBoundsToFitTBoundsWidth(width, matrix, explicitWidth, preferredHeight, explicitWidth, minHeight, explicitWidth, maxHeight); if (actualSize) return actualSize; } else if (isNaN(explicitWidth) && !isNaN(explicitHeight)) { actualSize = calcUBoundsToFitTBoundsWidth(width, matrix, preferredWidth, explicitHeight, minWidth, explicitHeight, maxWidth, explicitHeight); if (actualSize) return actualSize; } actualSize = calcUBoundsToFitTBoundsWidth(width, matrix, preferredWidth, preferredHeight, minWidth, minHeight, maxWidth, maxHeight); return actualSize; } /** * @private */ function fitTBoundsHeight(height:number, matrix:egret.Matrix, explicitWidth:number, explicitHeight:number, preferredWidth:number, preferredHeight:number, minWidth:number, minHeight:number, maxWidth:number, maxHeight:number):egret.Point { let actualSize:egret.Point; if (!isNaN(explicitWidth) && isNaN(explicitHeight)) { actualSize = calcUBoundsToFitTBoundsHeight(height, matrix, explicitWidth, preferredHeight, explicitWidth, minHeight, explicitWidth, maxHeight); if (actualSize) return actualSize; } else if (isNaN(explicitWidth) && !isNaN(explicitHeight)) { actualSize = calcUBoundsToFitTBoundsHeight(height, matrix, preferredWidth, explicitHeight, minWidth, explicitHeight, maxWidth, explicitHeight); if (actualSize) return actualSize; } actualSize = calcUBoundsToFitTBoundsHeight(height, matrix, preferredWidth, preferredHeight, minWidth, minHeight, maxWidth, maxHeight); return actualSize; } /** * @private */ function calcUBoundsToFitTBoundsHeight(h:number, matrix:egret.Matrix, preferredX:number, preferredY:number, minX:number, minY:number, maxX:number, maxY:number):egret.Point { let b = matrix.b; let d = matrix.d; if (-1.0e-9 < b && b < +1.0e-9) b = 0; if (-1.0e-9 < d && d < +1.0e-9) d = 0; if (b == 0 && d == 0) return null; if (b == 0 && d == 0) return null; if (b == 0) return egret.Point.create(preferredX, h / Math.abs(d)); else if (d == 0) return egret.Point.create(h / Math.abs(b), preferredY); let d1 = (b * d >= 0) ? d : -d; let s:egret.Point; let x:number; let y:number; if (d1 != 0 && preferredX > 0) { let invD1 = 1 / d1; preferredX = Math.max(minX, Math.min(maxX, preferredX)); x = preferredX; y = (h - b * x) * invD1; if (minY <= y && y <= maxY && b * x + d1 * y >= 0) { s = egret.Point.create(x, y); } y = (-h - b * x) * invD1; if (minY <= y && y <= maxY && b * x + d1 * y < 0) { if (!s || transformSize(s.x, s.y, matrix).width > transformSize(x, y, matrix).width) { egret.Point.release(s); s = egret.Point.create(x, y); } } } if (b != 0 && preferredY > 0) { let invB = 1 / b; preferredY = Math.max(minY, Math.min(maxY, preferredY)); y = preferredY; x = ( h - d1 * y ) * invB; if (minX <= x && x <= maxX && b * x + d1 * y >= 0) { if (!s || transformSize(s.x, s.y, matrix).width > transformSize(x, y, matrix).width) s = egret.Point.create(x, y); } x = ( -h - d1 * y ) * invB; if (minX <= x && x <= maxX && b * x + d1 * y < 0) { if (!s || transformSize(s.x, s.y, matrix).width > transformSize(x, y, matrix).width) { egret.Point.release(s); s = egret.Point.create(x, y); } } } if (s) return s; let a = matrix.a; let c = matrix.c; let c1 = ( a * c >= 0 ) ? c : -c; return solveEquation(b, d1, h, minX, minY, maxX, maxY, a, c1); } /** * @private */ function calcUBoundsToFitTBoundsWidth(w:number, matrix:egret.Matrix, preferredX:number, preferredY:number, minX:number, minY:number, maxX:number, maxY:number):egret.Point { let a = matrix.a; let c = matrix.c; if (-1.0e-9 < a && a < +1.0e-9) a = 0; if (-1.0e-9 < c && c < +1.0e-9) c = 0; if (a == 0 && c == 0) return null; if (a == 0) return egret.Point.create(preferredX, w / Math.abs(c)); else if (c == 0) return egret.Point.create(w / Math.abs(a), preferredY); let c1 = ( a * c >= 0 ) ? c : -c; let s:egret.Point; let x:number; let y:number; if (c1 != 0 && preferredX > 0) { let invC1 = 1 / c1; preferredX = Math.max(minX, Math.min(maxX, preferredX)); x = preferredX; y = (w - a * x) * invC1; if (minY <= y && y <= maxY && a * x + c1 * y >= 0) { s = egret.Point.create(x, y); } y = (-w - a * x) * invC1; if (minY <= y && y <= maxY && a * x + c1 * y < 0) { if (!s || transformSize(s.x, s.y, matrix).height > transformSize(x, y, matrix).height) { egret.Point.release(s); s = egret.Point.create(x, y); } } } if (a != 0 && preferredY > 0) { let invA = 1 / a; preferredY = Math.max(minY, Math.min(maxY, preferredY)); y = preferredY; x = (w - c1 * y ) * invA; if (minX <= x && x <= maxX && a * x + c1 * y >= 0) { if (!s || transformSize(s.x, s.y, matrix).height > transformSize(x, y, matrix).height) { egret.Point.release(s); s = egret.Point.create(x, y); } } x = (-w - c1 * y ) * invA; if (minX <= x && x <= maxX && a * x + c1 * y < 0) { if (!s || transformSize(s.x, s.y, matrix).height > transformSize(x, y, matrix).height) { egret.Point.release(s); s = egret.Point.create(x, y); } } } if (s) return s; let b = matrix.b; let d = matrix.d; let d1 = (b * d >= 0) ? d : -d; return solveEquation(a, c1, w, minX, minY, maxX, maxY, b, d1); } /** * @private */ function solveEquation(a:number, c:number, w:number, minX:number, minY:number, maxX:number, maxY:number, b:number, d:number):egret.Point { if (a == 0 || c == 0) return null; let x:number; let y:number; let A = (w - minX * a) / c; let B = (w - maxX * a) / c; let rangeMinY = Math.max(minY, Math.min(A, B)); let rangeMaxY = Math.min(maxY, Math.max(A, B)); let det = (b * c - a * d); if (rangeMinY <= rangeMaxY) { if (Math.abs(det) < 1.0e-9) { y = w / ( a + c ); } else { y = b * w / det; } y = Math.max(rangeMinY, Math.min(y, rangeMaxY)); x = (w - c * y) / a; return egret.Point.create(x, y); } A = -(minX * a + w) / c; B = -(maxX * a + w) / c; rangeMinY = Math.max(minY, Math.min(A, B)); rangeMaxY = Math.min(maxY, Math.max(A, B)); if (rangeMinY <= rangeMaxY) { if (Math.abs(det) < 1.0e-9) { y = -w / ( a + c ); } else { y = -b * w / det; } y = Math.max(rangeMinY, Math.min(y, rangeMaxY)); x = (-w - c * y) / a; return egret.Point.create(x, y); } return null; } /** * @private */ function calcUBoundsToFitTBounds(w:number, h:number, matrix:egret.Matrix, minX:number, minY:number, maxX:number, maxY:number):egret.Point { let a = matrix.a; let b = matrix.b; let c = matrix.c; let d = matrix.d; if (-1.0e-9 < a && a < +1.0e-9) a = 0; if (-1.0e-9 < b && b < +1.0e-9) b = 0; if (-1.0e-9 < c && c < +1.0e-9) c = 0; if (-1.0e-9 < d && d < +1.0e-9) d = 0; if (b == 0 && c == 0) { if (a == 0 || d == 0) return null; return egret.Point.create(w / Math.abs(a), h / Math.abs(d)); } if (a == 0 && d == 0) { if (b == 0 || c == 0) return null; return egret.Point.create(h / Math.abs(b), w / Math.abs(c)); } let c1 = ( a * c >= 0 ) ? c : -c; let d1 = ( b * d >= 0 ) ? d : -d; let det = a * d1 - b * c1; if (Math.abs(det) < 1.0e-9) { if (c1 == 0 || a == 0 || a == -c1) return null; if (Math.abs(a * h - b * w) > 1.0e-9) return null; return solveEquation(a, c1, w, minX, minX, maxX, maxY, b, d1); } let invDet = 1 / det; w *= invDet; h *= invDet; let s:egret.Point; s = solveSystem(a, c1, b, d1, w, h); if (s && minX <= s.x && s.x <= maxX && minY <= s.y && s.y <= maxY && a * s.x + c1 * s.x >= 0 && b * s.x + d1 * s.y >= 0) return s; s = solveSystem(a, c1, b, d1, w, -h); if (s && minX <= s.x && s.x <= maxX && minY <= s.y && s.y <= maxY && a * s.x + c1 * s.x >= 0 && b * s.x + d1 * s.y < 0) return s; s = solveSystem(a, c1, b, d1, -w, h); if (s && minX <= s.x && s.x <= maxX && minY <= s.y && s.y <= maxY && a * s.x + c1 * s.x < 0 && b * s.x + d1 * s.y >= 0) return s; s = solveSystem(a, c1, b, d1, -w, -h); if (s && minX <= s.x && s.x <= maxX && minY <= s.y && s.y <= maxY && a * s.x + c1 * s.x < 0 && b * s.x + d1 * s.y < 0) return s; egret.Point.release(s); return null; } /** * @private */ function transformSize(width:number, height:number, matrix:egret.Matrix):egret.Rectangle { let bounds = egret.$TempRectangle.setTo(0, 0, width, height); matrix.$transformBounds(bounds); return bounds; } /** * @private */ function solveSystem(a:number, c:number, b:number, d:number, mOverDet:number, nOverDet:number):egret.Point { return egret.Point.create(d * mOverDet - c * nOverDet, a * nOverDet - b * mOverDet); } }
the_stack
import React from 'react'; import cx from 'classnames'; import '@itwin/itwinui-css/css/table.css'; import SvgChevronLeft from '@itwin/itwinui-icons-react/cjs/icons/ChevronLeft'; import SvgChevronRight from '@itwin/itwinui-icons-react/cjs/icons/ChevronRight'; import { IconButton, Button, DropdownButton } from '../Buttons'; import { ProgressRadial } from '../ProgressIndicators'; import { MenuItem } from '../Menu'; import { CommonProps, getBoundedValue, useTheme, useOverflow, useContainerWidth, } from '../utils'; import { TablePaginatorRendererProps } from './Table'; const defaultLocalization = { pageSizeLabel: (size: number) => `${size} per page`, rangeLabel: ( startIndex: number, endIndex: number, totalRows: number, isLoading: boolean, ) => isLoading ? `${startIndex}-${endIndex}…` : `${startIndex}-${endIndex} of ${totalRows}`, previousPage: 'Previous page', nextPage: 'Next page', goToPageLabel: (page: number) => `Go to page ${page}`, rowsPerPageLabel: 'Rows per page', } as const; export type TablePaginatorProps = { /** * Control whether focusing tabs (using arrow keys) should automatically select them. * Use 'manual' if tab panel content is not preloaded. * @default 'manual' */ focusActivationMode?: 'auto' | 'manual'; /** * Array of possible page size options. When provided then shows the range of rows within the current page and page size selection. * @example * <TablePaginator * // ... * pageSizeList={[10, 25, 50]} * /> */ pageSizeList?: number[]; /** * Object of labels and functions used for pagination localization. */ localization?: { /** * Function that returns a label for the page size selector. * @default (size: number) => `${size} per page` */ pageSizeLabel?: (size: number) => string; /** * Function that returns a label for the range of rows within the current page and the length of the whole data. * @default * (startIndex, endIndex, totalRows, isLoading) => * isLoading * ? `${startIndex}-${endIndex}…` * : `${startIndex}-${endIndex} of ${totalRows}`; */ rangeLabel?: ( startIndex: number, endIndex: number, totalRows: number, isLoading: boolean, ) => string; /** * A label for previous page button. Used for accessibility attribute. * @default 'Previous page' */ previousPage?: string; /** * A label for next page button. Used for accessibility attribute. * @default 'Next page' */ nextPage?: string; /** * Function that returns a label for page selector buttons. Used for accessibility attribute. * @default (page: number) => `Go to page ${page}` */ goToPageLabel?: (page: number) => string; /** * A label shown next to the page size selector. Use `null` to hide. * @default 'Rows per page' */ rowsPerPageLabel?: string | null; }; } & TablePaginatorRendererProps & Omit<CommonProps, 'title'>; /** * Table paginator component. Recommended to pass to the `Table` as `paginatorRenderer` prop. * Passing `props` from `paginatorRenderer` handles all state management and is enough for basic use-cases. * @example * <Table * // ... * paginatorRenderer={(props) => <TablePaginator {...props} />} * /> */ export const TablePaginator = (props: TablePaginatorProps) => { const { currentPage, totalRowsCount, pageSize, onPageChange, focusActivationMode = 'manual', isLoading = false, size = 'default', pageSizeList, onPageSizeChange, localization: userLocalization, className, ...rest } = props; useTheme(); const localization = React.useMemo( () => ({ ...defaultLocalization, ...userLocalization }), [userLocalization], ); const pageListRef = React.useRef<HTMLDivElement | null>(null); const [focusedIndex, setFocusedIndex] = React.useState<number>(currentPage); React.useEffect(() => { setFocusedIndex(currentPage); }, [currentPage]); const needFocus = React.useRef(false); const isMounted = React.useRef(false); React.useEffect(() => { // Checking `isMounted.current` prevents from focusing on initial load. // Checking `needFocus.current` prevents from focusing page when clicked on previous/next page. if (isMounted.current && needFocus.current) { const buttonToFocus = Array.from( pageListRef.current?.querySelectorAll('.iui-paginator-page-button') ?? [], ).find((el) => el.textContent?.trim() === (focusedIndex + 1).toString()); (buttonToFocus as HTMLButtonElement | undefined)?.focus(); needFocus.current = false; } isMounted.current = true; }, [focusedIndex]); const buttonSize = size != 'default' ? 'small' : undefined; const pageButton = React.useCallback( (index: number, tabIndex = index === focusedIndex ? 0 : -1) => ( <div key={index}> <button className={cx('iui-paginator-page-button', { 'iui-active': index === currentPage, 'iui-paginator-page-button-small': buttonSize === 'small', })} onClick={() => onPageChange(index)} aria-current={index === currentPage} aria-label={localization.goToPageLabel(index + 1)} tabIndex={tabIndex} > {index + 1} </button> </div> ), [focusedIndex, currentPage, localization, buttonSize, onPageChange], ); const totalPagesCount = Math.ceil(totalRowsCount / pageSize); const pageList = React.useMemo( () => new Array(totalPagesCount) .fill(null) .map((_, index) => pageButton(index)), [pageButton, totalPagesCount], ); const [overflowRef, visibleCount] = useOverflow(pageList); const [paginatorResizeRef, paginatorWidth] = useContainerWidth(); const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => { // alt + arrow keys are used by browser/assistive technologies if (event.altKey) { return; } const focusPage = (delta: number) => { const newFocusedIndex = getBoundedValue( focusedIndex + delta, 0, totalPagesCount - 1, ); needFocus.current = true; if (focusActivationMode === 'auto') { onPageChange(newFocusedIndex); } else { setFocusedIndex(newFocusedIndex); } }; switch (event.key) { case 'ArrowRight': { focusPage(+1); event.preventDefault(); break; } case 'ArrowLeft': { focusPage(-1); event.preventDefault(); break; } case 'Enter': case ' ': case 'Spacebar': { if (focusActivationMode === 'manual') { onPageChange(focusedIndex); } break; } default: break; } }; const halfVisibleCount = Math.floor(visibleCount / 2); let startPage = focusedIndex - halfVisibleCount; let endPage = focusedIndex + halfVisibleCount + 1; if (startPage < 0) { endPage = Math.min(totalPagesCount, endPage + Math.abs(startPage)); // If no room at the beginning, show extra pages at the end startPage = 0; } if (endPage > totalPagesCount) { startPage = Math.max(0, startPage - (endPage - totalPagesCount)); // If no room at the end, show extra pages at the beginning endPage = totalPagesCount; } const hasNoRows = totalPagesCount === 0; const showPagesList = totalPagesCount > 1 || isLoading; const showPageSizeList = pageSizeList && onPageSizeChange && !!totalRowsCount; const ellipsis = ( <div> <span className={cx('iui-paginator-ellipsis', { 'iui-paginator-ellipsis-small': size === 'small', })} > … </span> </div> ); const noRowsContent = ( <> {isLoading ? ( <ProgressRadial indeterminate size='small' /> ) : ( <Button styleType='borderless' disabled size={buttonSize}> 1 </Button> )} </> ); if (!showPagesList && !showPageSizeList) { return null; } return ( <div className={cx('iui-paginator', className)} ref={paginatorResizeRef} {...rest} > <div className='iui-left' /> {showPagesList && ( <div className='iui-center' ref={overflowRef}> <IconButton styleType='borderless' disabled={currentPage === 0} onClick={() => onPageChange(currentPage - 1)} size={buttonSize} aria-label={localization.previousPage} > <SvgChevronLeft /> </IconButton> <span className='iui-paginator-pages-group' onKeyDown={onKeyDown} ref={pageListRef} > {(() => { if (hasNoRows) { return noRowsContent; } if (visibleCount === 1) { return pageButton(focusedIndex); } return ( <> {startPage !== 0 && ( <> {pageButton(0, 0)} {ellipsis} </> )} {pageList.slice(startPage, endPage)} {endPage !== totalPagesCount && !isLoading && ( <> {ellipsis} {pageButton(totalPagesCount - 1, 0)} </> )} {isLoading && ( <> {ellipsis} <ProgressRadial indeterminate size='small' /> </> )} </> ); })()} </span> <IconButton styleType='borderless' disabled={currentPage === totalPagesCount - 1 || hasNoRows} onClick={() => onPageChange(currentPage + 1)} size={buttonSize} aria-label={localization.nextPage} > <SvgChevronRight /> </IconButton> </div> )} <div className='iui-right'> {showPageSizeList && ( <> {localization.rowsPerPageLabel !== null && paginatorWidth >= 1024 && ( <span className='iui-paginator-page-size-label'> {localization.rowsPerPageLabel} </span> )} <DropdownButton styleType='borderless' size={buttonSize} menuItems={(close) => pageSizeList.map((size) => ( <MenuItem key={size} isSelected={size === pageSize} onClick={() => { close(); onPageSizeChange(size); }} > {localization.pageSizeLabel(size)} </MenuItem> )) } > {localization.rangeLabel( currentPage * pageSize + 1, Math.min(totalRowsCount, (currentPage + 1) * pageSize), totalRowsCount, isLoading, )} </DropdownButton> </> )} </div> </div> ); }; export default TablePaginator;
the_stack
import { ComponentFixture, TestBed } from '@angular/core/testing'; import { NoopAnimationsModule } from '@angular/platform-browser/animations'; import { InteractivityChecker } from '@angular/cdk/a11y'; import { TestbedHarnessEnvironment } from '@angular/cdk/testing/testbed'; import { HttpTestingController } from '@angular/common/http/testing'; import { HarnessLoader } from '@angular/cdk/testing'; import { MatFormFieldHarness } from '@angular/material/form-field/testing'; import { MatInputHarness } from '@angular/material/input/testing'; import { MatSelectHarness } from '@angular/material/select/testing'; import { GioSaveBarHarness } from '@gravitee/ui-particles-angular'; import { Validators } from '@angular/forms'; import { OrgSettingsNewUserComponent, UserType } from './org-settings-new-user.component'; import { CONSTANTS_TESTING, GioHttpTestingModule } from '../../../../shared/testing'; import { OrganizationSettingsModule } from '../../organization-settings.module'; import { UIRouterState } from '../../../../ajs-upgraded-providers'; import { fakeIdentityProviderListItem } from '../../../../entities/identity-provider'; import { fakeUser } from '../../../../entities/user/user.fixture'; import { GioFormCardGroupHarness } from '../../../../shared/components/gio-form-card-group/gio-form-card-group.harness'; describe('OrgSettingsNewUserComponent', () => { let fixture: ComponentFixture<OrgSettingsNewUserComponent>; let loader: HarnessLoader; let httpTestingController: HttpTestingController; let component: OrgSettingsNewUserComponent; beforeEach(async () => { await TestBed.configureTestingModule({ imports: [NoopAnimationsModule, GioHttpTestingModule, OrganizationSettingsModule], providers: [{ provide: UIRouterState, useValue: { go: jest.fn() } }], }) .overrideProvider(InteractivityChecker, { useValue: { isFocusable: () => true, // This checks focus trap, set it to true to avoid the warning }, }) .compileComponents(); }); beforeEach(() => { fixture = TestBed.createComponent(OrgSettingsNewUserComponent); loader = TestbedHarnessEnvironment.loader(fixture); component = fixture.componentInstance; httpTestingController = TestBed.inject(HttpTestingController); fixture.detectChanges(); }); it('should create a user when no identity provider is configured', async () => { httpTestingController.expectOne(`${CONSTANTS_TESTING.org.baseURL}/configuration/identities`).flush([]); fixture.detectChanges(); const formCardGroup = await loader.getHarness(GioFormCardGroupHarness.with({ selector: '[formControlName=type]' })); expect(await formCardGroup.getSelectedValue()).toEqual(UserType.EXTERNAL_USER); expect(component.userForm.get('firstName').hasValidator(Validators.required)).toBeTruthy(); expect(component.userForm.get('email').hasValidator(Validators.required)).toBeTruthy(); expect(component.userForm.get('email').hasValidator(Validators.email)).toBeTruthy(); const firstNameFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: /First Name/ })); const firstNameInput = await firstNameFormField.getControl(MatInputHarness); await firstNameInput?.setValue('Bruce'); const lastNameFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: /Last Name/ })); const lastNameInput = await lastNameFormField.getControl(MatInputHarness); await lastNameInput?.setValue('Wayne'); const saveBar = await loader.getHarness(GioSaveBarHarness); expect(await saveBar.isSubmitButtonInvalid()).toBeTruthy(); const emailFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: /Email/ })); const emailInput = await emailFormField.getControl(MatInputHarness); await emailInput?.setValue('contact@batman.com'); expect(await saveBar.isSubmitButtonInvalid()).toBeFalsy(); await saveBar.clickSubmit(); const req = httpTestingController.expectOne(`${CONSTANTS_TESTING.org.baseURL}/users`); expect(req.request.method).toEqual('POST'); expect(req.request.body).toEqual({ firstname: 'Bruce', lastname: 'Wayne', email: 'contact@batman.com', service: false, }); req.flush(fakeUser()); }); it('should create a user when multiple identity providers are configured', async () => { httpTestingController.expectOne(`${CONSTANTS_TESTING.org.baseURL}/configuration/identities`).flush([ fakeIdentityProviderListItem({ id: 'google', type: 'GOOGLE', name: 'Google', }), fakeIdentityProviderListItem({ id: 'github', type: 'GITHUB', name: 'GitHub', }), ]); fixture.detectChanges(); const formCardGroup = await loader.getHarness(GioFormCardGroupHarness.with({ selector: '[formControlName=type]' })); expect(await formCardGroup.getSelectedValue()).toEqual(UserType.EXTERNAL_USER); expect(component.userForm.get('firstName').hasValidator(Validators.required)).toBeTruthy(); expect(component.userForm.get('email').hasValidator(Validators.required)).toBeTruthy(); expect(component.userForm.get('email').hasValidator(Validators.email)).toBeTruthy(); const firstNameFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: /^First Name/ })); const firstNameInput = await firstNameFormField.getControl(MatInputHarness); await firstNameInput?.setValue('Bruce'); const lastNameFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: /^Last Name/ })); const lastNameInput = await lastNameFormField.getControl(MatInputHarness); await lastNameInput?.setValue('Wayne'); const emailFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: /^Email/ })); const emailInput = await emailFormField.getControl(MatInputHarness); await emailInput?.setValue('contact@batman.com'); const idpFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: /^Name/ })); const idpSelect = await idpFormField.getControl(MatSelectHarness); await idpSelect.clickOptions({ text: 'GitHub' }); const idpIdFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: /^Identifier/ })); const idpIdInput = await idpIdFormField.getControl(MatInputHarness); await idpIdInput?.setValue('idp-id'); const gioSaveBar = await loader.getHarness(GioSaveBarHarness); expect(await gioSaveBar.isSubmitButtonInvalid()).toBeFalsy(); await gioSaveBar.clickSubmit(); const req = httpTestingController.expectOne(`${CONSTANTS_TESTING.org.baseURL}/users`); expect(req.request.method).toEqual('POST'); expect(req.request.body).toEqual({ firstname: 'Bruce', lastname: 'Wayne', email: 'contact@batman.com', service: false, source: 'github', sourceId: 'idp-id', }); req.flush(fakeUser()); }); it('should create a service account with email', async () => { httpTestingController.expectOne(`${CONSTANTS_TESTING.org.baseURL}/configuration/identities`).flush([]); fixture.detectChanges(); const formCardGroup = await loader.getHarness(GioFormCardGroupHarness.with({ selector: '[formControlName=type]' })); expect(await formCardGroup.getSelectedValue()).toEqual(UserType.EXTERNAL_USER); await formCardGroup.select(UserType.SERVICE_ACCOUNT); expect(component.userForm.get('firstName')).toBeNull(); expect(component.userForm.get('email').hasValidator(Validators.required)).toBeFalsy(); const lastNameFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: /Service Name/ })); const lastNameInput = await lastNameFormField.getControl(MatInputHarness); await lastNameInput?.setValue('Bat-AI'); const saveBar = await loader.getHarness(GioSaveBarHarness); expect(await saveBar.isSubmitButtonInvalid()).toBeFalsy(); const emailFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: /Email/ })); const emailInput = await emailFormField.getControl(MatInputHarness); await emailInput?.setValue('bat-ai-service@batman.com'); expect(await saveBar.isSubmitButtonInvalid()).toBeFalsy(); await saveBar.clickSubmit(); const req = httpTestingController.expectOne(`${CONSTANTS_TESTING.org.baseURL}/users`); expect(req.request.method).toEqual('POST'); expect(req.request.body).toEqual({ lastname: 'Bat-AI', email: 'bat-ai-service@batman.com', service: true, }); req.flush(fakeUser()); }); it('should create a service account without email', async () => { httpTestingController.expectOne(`${CONSTANTS_TESTING.org.baseURL}/configuration/identities`).flush([]); fixture.detectChanges(); const formCardGroup = await loader.getHarness(GioFormCardGroupHarness.with({ selector: '[formControlName=type]' })); expect(await formCardGroup.getSelectedValue()).toEqual(UserType.EXTERNAL_USER); await formCardGroup.select(UserType.SERVICE_ACCOUNT); expect(component.userForm.get('firstName')).toBeNull(); expect(component.userForm.get('email').hasValidator(Validators.required)).toBeFalsy(); const lastNameFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: /Service Name/ })); const lastNameInput = await lastNameFormField.getControl(MatInputHarness); await lastNameInput?.setValue('Bat-AI'); const saveBar = await loader.getHarness(GioSaveBarHarness); expect(await saveBar.isSubmitButtonInvalid()).toBeFalsy(); await saveBar.clickSubmit(); const req = httpTestingController.expectOne(`${CONSTANTS_TESTING.org.baseURL}/users`); expect(req.request.method).toEqual('POST'); expect(req.request.body).toEqual({ lastname: 'Bat-AI', email: '', service: true, }); req.flush(fakeUser()); }); it('should reset form when changing user type', async () => { httpTestingController.expectOne(`${CONSTANTS_TESTING.org.baseURL}/configuration/identities`).flush([]); fixture.detectChanges(); const formCardGroup = await loader.getHarness(GioFormCardGroupHarness.with({ selector: '[formControlName=type]' })); expect(await formCardGroup.getSelectedValue()).toEqual(UserType.EXTERNAL_USER); // Fill form for External User const firstNameFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: /^First Name/ })); const firstNameInput = await firstNameFormField.getControl(MatInputHarness); await firstNameInput?.setValue('Bruce'); const lastNameFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: /^Last Name/ })); const lastNameInput = await lastNameFormField.getControl(MatInputHarness); await lastNameInput?.setValue('Wayne'); const emailFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: /^Email/ })); const emailInput = await emailFormField.getControl(MatInputHarness); await emailInput?.setValue('contact@batman.com'); // Switch to Service account form and fill it await formCardGroup.select(UserType.SERVICE_ACCOUNT); expect(component.userForm.get('firstName')).toBeNull(); expect(component.userForm.get('email').hasValidator(Validators.required)).toBeFalsy(); const serviceNameFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: /Service Name/ })); const serviceNameInput = await serviceNameFormField.getControl(MatInputHarness); expect(await serviceNameInput.getValue()).toEqual(''); await serviceNameInput?.setValue('Bat-AI'); const serviceEmailFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: /^Email/ })); const serviceEmailInput = await serviceEmailFormField.getControl(MatInputHarness); expect(await serviceEmailInput.getValue()).toEqual(''); await serviceEmailInput?.setValue('contact-service@batman.com'); // Switch back to user form await formCardGroup.select(UserType.EXTERNAL_USER); expect(component.userForm.get('firstName')).not.toBeNull(); expect(component.userForm.get('email').hasValidator(Validators.required)).toBeTruthy(); const firstNameAfterTypeChangeFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: /^First Name/ })); const firstNameAfterTypeChangeInput = await firstNameAfterTypeChangeFormField.getControl(MatInputHarness); const lastNameAfterTypeChangeFormField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: /^Last Name/ })); const lastNameAfterTypeChangeInput = await lastNameAfterTypeChangeFormField.getControl(MatInputHarness); const emailFormAfterTypeChangeField = await loader.getHarness(MatFormFieldHarness.with({ floatingLabelText: /^Email/ })); const emailInputAfterTypeChange = await emailFormAfterTypeChangeField.getControl(MatInputHarness); expect(await firstNameAfterTypeChangeInput.getValue()).toEqual(''); expect(await lastNameAfterTypeChangeInput.getValue()).toEqual(''); expect(await emailInputAfterTypeChange.getValue()).toEqual(''); }); afterEach(() => { httpTestingController.verify(); }); });
the_stack
import GL from '@luma.gl/constants'; import {RenderLoop, AnimationProps, Model, CubeGeometry} from '@luma.gl/engine'; import { Framebuffer, clear, Program, VertexArray, UniformBufferLayout, Buffer, } from '@luma.gl/gltools'; import {Matrix4, radians} from '@math.gl/core'; const INFO_HTML = ` <p> <b>Depth of Field</b>. <p> Several instanced luma.gl <code>Cubes</code> rendered with a Depth of Field post-processing effect. <div> <label>Focal Length</label><input type="range" id="focal-length" min="0.1" max="10.0" step="0.1"> </div> <div> <label>Focus Distance</label><input type="range" id="focus-distance" min="0.1" max="10.0" step="0.1"> </div> <div> <label>F-Stop</label><input type="range" id="f-stop" min="0.1" max="10.0" step="0.1"> </div> `; const ALT_TEXT = "THIS DEMO REQUIRES WEBGL 2, BUT YOUR BROWSER DOESN'T SUPPORT IT"; const QUAD_VERTS = [1, 1, 0, -1, 1, 0, 1, -1, 0, -1, -1, 0]; // eslint-disable-line const NUM_ROWS = 5; const CUBES_PER_ROW = 20; const NUM_CUBES = CUBES_PER_ROW * NUM_ROWS; const NEAR = 0.1; const FAR = 30.0; const vs = `\ #version 300 es #define SHADER_NAME scene.vs in vec3 positions; in vec3 normals; in vec2 texCoords; in vec4 modelMatCol1; in vec4 modelMatCol2; in vec4 modelMatCol3; in vec4 modelMatCol4; uniform mat4 uView; uniform mat4 uProjection; out vec3 vNormal; out vec2 vUV; void main(void) { mat4 modelMat = mat4( modelMatCol1, modelMatCol2, modelMatCol3, modelMatCol4 ); gl_Position = uProjection * uView * modelMat * vec4(positions, 1.0); vNormal = vec3(modelMat * vec4(normals, 0.0)); vUV = texCoords; } `; const fs = `\ #version 300 es precision highp float; #define SHADER_NAME scene.fs in vec3 vNormal; in vec2 vUV; uniform sampler2D uTexture; out vec4 fragColor; void main(void) { float d = clamp(dot(normalize(vNormal), normalize(vec3(1.0, 1.0, 0.2))), 0.0, 1.0); fragColor.rgb = texture(uTexture, vec2(vUV.x, 1.0 - vUV.y)).rgb * (d + 0.1); fragColor.a = 1.0; } `; class InstancedCube extends Model { count: number; xforms: any[]; matrices: Float32Array; matrixBuffer: Buffer; constructor(gl, props) { const count = props.count; const xforms = new Array(count); const matrices = new Float32Array(count * 16); const matrixBuffer = new Buffer(gl, matrices.byteLength); super( gl, Object.assign({geometry: new CubeGeometry()}, props, { vs, fs, isInstanced: 1, instanceCount: count, uniforms: { uTexture: props.uniforms.uTexture }, attributes: { // Attributes are limited to 4 components, // So we have to split the matrices across // 4 attributes. They're reconstructed in // the vertex shader. modelMatCol1: { buffer: matrixBuffer, size: 4, stride: 64, offset: 0, divisor: 1 }, modelMatCol2: { buffer: matrixBuffer, size: 4, stride: 64, offset: 16, divisor: 1 }, modelMatCol3: { buffer: matrixBuffer, size: 4, stride: 64, offset: 32, divisor: 1 }, modelMatCol4: { buffer: matrixBuffer, size: 4, stride: 64, offset: 48, divisor: 1 } } }) ); this.count = count; this.xforms = xforms; this.matrices = matrices; this.matrixBuffer = matrixBuffer; } updateMatrixBuffer() { this.matrixBuffer.setData(this.matrices); } } const DOF_VERTEX = `\ #version 300 es #define SHADER_NAME quad.vs layout(location=0) in vec3 aPosition; void main() { gl_Position = vec4(aPosition, 1.0); } `; const DOF_FRAGMENT = `\ #version 300 es precision highp float; #define SHADER_NAME dof.fs #define MAX_BLUR 20.0 uniform DOFUniforms { vec2 uDepthRange; float uFocusDistance; float uBlurCoefficient; float uPPM; }; uniform vec2 uTexelOffset; uniform sampler2D uColor; uniform sampler2D uDepth; out vec4 fragColor; void main() { ivec2 fragCoord = ivec2(gl_FragCoord.xy); ivec2 resolution = textureSize(uColor, 0) - 1; // Convert to linear depth float ndc = 2.0 * texelFetch(uDepth, fragCoord, 0).r - 1.0; float depth = -(2.0 * uDepthRange.y * uDepthRange.x) / (ndc * (uDepthRange.y - uDepthRange.x) - uDepthRange.y - uDepthRange.x); float deltaDepth = abs(uFocusDistance - depth); // Blur more quickly in the foreground. float xdd = depth < uFocusDistance ? abs(uFocusDistance - deltaDepth) : abs(uFocusDistance + deltaDepth); float blurRadius = min(floor(uBlurCoefficient * (deltaDepth / xdd) * uPPM), MAX_BLUR); vec4 color = vec4(0.0); if (blurRadius > 1.0) { float halfBlur = blurRadius * 0.5; float count = 0.0; for (float i = 0.0; i <= MAX_BLUR; ++i) { if (i > blurRadius) { break; } // texelFetch outside texture gives vec4(0.0) (undefined in ES 3) ivec2 sampleCoord = clamp(fragCoord + ivec2(((i - halfBlur) * uTexelOffset)), ivec2(0), resolution); color += texelFetch(uColor, sampleCoord, 0); ++count; } color /= count; } else { color = texelFetch(uColor, fragCoord, 0); } fragColor = color; } `; let focalLength = 2.0; let focusDistance = 3.0; let fStop = 2.8; const texelOffset = new Float32Array(2); export default class AppRenderLoop extends RenderLoop { static info = INFO_HTML; projMat = new Matrix4(); viewMat = new Matrix4().lookAt({eye: [0, 0, 8]}); instancedCubeTransforms = []; instancedCubes: InstancedCube; sceneFramebuffer: Framebuffer; dofFramebuffer: Framebuffer; quadVertexArray: VertexArray; dofProgram: Program; dofUniforms: Buffer; dofUniformsLayout: UniformBufferLayout; constructor({device}: AnimationProps) { super(); if (!device.features.has('webgl2')) { throw new Error(ALT_TEXT); } // Create postprocessing pass program. this.dofUniformsLayout = new UniformBufferLayout({ uDepthRange: GL.FLOAT_VEC2, uFocusDistance: GL.FLOAT, uBlurCoefficient: GL.FLOAT, uPPM: GL.FLOAT }).setUniforms({ uDepthRange: [NEAR, FAR] }); this.dofUniforms = device.createBuffer({ target: GL.UNIFORM_BUFFER, data: this.dofUniformsLayout.getData(), accessor: { index: 0 } }); this.dofProgram = new Program(device, { id: 'DOF_PROGRAM', vs: DOF_VERTEX, fs: DOF_FRAGMENT, parameters: { depthWriteEnabled: true, depthCompare: 'less-equal' } }); this.dofProgram.uniformBlockBinding(this.dofProgram.getUniformBlockIndex('DOFUniforms'), 0); // Set up frambuffers. // Need to ensure both color and depth targets can be sampled. this.sceneFramebuffer = new Framebuffer(device, { width: gl.drawingBufferWidth, height: gl.drawingBufferHeight, attachments: { [GL.COLOR_ATTACHMENT0]: device.createTexture({ format: GL.RGBA, type: GL.UNSIGNED_BYTE, width: gl.drawingBufferWidth, height: gl.drawingBufferHeight, mipmaps: false, parameters: { [GL.TEXTURE_MIN_FILTER]: GL.LINEAR, [GL.TEXTURE_MAG_FILTER]: GL.LINEAR, [GL.TEXTURE_WRAP_S]: GL.CLAMP_TO_EDGE, [GL.TEXTURE_WRAP_T]: GL.CLAMP_TO_EDGE } }), [GL.DEPTH_ATTACHMENT]: device.createTexture({ format: GL.DEPTH_COMPONENT16, type: GL.UNSIGNED_SHORT, dataFormat: GL.DEPTH_COMPONENT, width: gl.drawingBufferWidth, height: gl.drawingBufferHeight, mipmaps: false, parameters: { [GL.TEXTURE_MIN_FILTER]: GL.NEAREST, [GL.TEXTURE_MAG_FILTER]: GL.NEAREST, [GL.TEXTURE_WRAP_S]: GL.CLAMP_TO_EDGE, [GL.TEXTURE_WRAP_T]: GL.CLAMP_TO_EDGE } }) } }); // Postprocessing FBO doesn't need a depth attachment. this.dofFramebuffer = new Framebuffer(device, { width: gl.drawingBufferWidth, height: gl.drawingBufferHeight, depth: false }); // Input handlers. const focalLengthInput = document.getElementById('focal-length'); const focusDistanceInput = document.getElementById('focus-distance'); const fStopInput = document.getElementById('f-stop'); if (focalLengthInput) { // @ts-ignore focalLengthInput.value = focalLength; focalLengthInput.addEventListener('input', () => { // @ts-ignore focalLength = parseFloat(focalLengthInput.value); }); // @ts-ignore focusDistanceInput.value = focusDistance; focusDistanceInput.addEventListener('input', () => { // @ts-ignore focusDistance = parseFloat(focusDistanceInput.value); }); // @ts-ignore fStopInput.value = fStop; fStopInput.addEventListener('input', () => { // @ts-ignore fStop = parseFloat(fStopInput.value); }); } const texture = device.createTexture({ data: 'vis-logo.png', mipmaps: true, parameters: { [GL.TEXTURE_MAG_FILTER]: GL.LINEAR, [GL.TEXTURE_MIN_FILTER]: GL.LINEAR_MIPMAP_NEAREST } }); // Create instanced model and initialize transform matrices. this.instancedCubes = new InstancedCube(device, { count: NUM_CUBES, uniforms: { uTexture: texture } }); let cubeI = 0; for (let j = 0; j < NUM_ROWS; ++j) { const rowOffset = j - Math.floor(NUM_ROWS / 2); for (let i = 0; i < CUBES_PER_ROW; ++i) { const scale = [0.4, 0.4, 0.4]; const rotate = [-Math.sin(i * 18.23) * Math.PI, 0, Math.cos(i * 11.27) * Math.PI]; const translate = [-i + 2 - rowOffset, 0, -i + 2 + rowOffset]; this.instancedCubeTransforms[cubeI] = { scale, translate, rotate, matrix: new Matrix4().translate(translate).rotateXYZ(rotate).scale(scale) }; this.instancedCubes.matrices.set(this.instancedCubeTransforms[cubeI].matrix, cubeI * 16); ++cubeI; } } this.instancedCubes.updateMatrixBuffer(); // Full-screen quad VAO for postprocessing // passes. this.quadVertexArray = new VertexArray(device, { program: this.dofProgram, attributes: { aPosition: device.createBuffer(new Float32Array(QUAD_VERTS)) } }); } onRender({ device, tick, width, height, aspect, }: AnimationProps) { const {gl} = device; // TODO this.sceneFramebuffer.resize(gl.drawingBufferWidth, gl.drawingBufferHeight); this.dofFramebuffer.resize(gl.drawingBufferWidth, gl.drawingBufferHeight); const magnification = focalLength / Math.max(0.1, Math.abs(focusDistance - focalLength)); const blurCoefficient = (focalLength * magnification) / fStop; const ppm = Math.sqrt( gl.drawingBufferWidth * gl.drawingBufferWidth + gl.drawingBufferHeight * gl.drawingBufferHeight ) / 35; clear(gl, {color: [0, 0, 0, 1], depth: true, framebuffer: this.sceneFramebuffer}); this.projMat.perspective({fov: radians(75), aspect, near: NEAR, far: FAR}); this.viewMat.lookAt({eye: [3, 1.5, 3], center: [0, 0, 0], up: [0, 1, 0]}); // Update model matrix data and then // update the attribute buffer./ for (let i = 0; i < NUM_CUBES; ++i) { const box = this.instancedCubeTransforms[i]; box.rotate[0] += 0.01; box.rotate[1] += 0.02; box.matrix.identity().translate(box.translate).rotateXYZ(box.rotate).scale(box.scale); this.instancedCubes.matrices.set(box.matrix, i * 16); } this.instancedCubes.updateMatrixBuffer(); // Draw cubes to scene framebuffer. this.instancedCubes.draw({ uniforms: { uProjection: this.projMat, uView: this.viewMat }, framebuffer: this.sceneFramebuffer }); // Apply DOF // Horizontal DOF blur clear(device, {color: [0, 0, 0, 1], framebuffer: this.dofFramebuffer}); // texelOffset determines the direction of the blur texelOffset[0] = 1; texelOffset[1] = 0; this.dofUniformsLayout.setUniforms({ uFocusDistance: focusDistance, uBlurCoefficient: blurCoefficient, uPPM: ppm }); this.dofUniforms.setData(this.dofUniformsLayout.getData()); this.dofUniforms.bind(); this.dofProgram.setUniforms({ uTexelOffset: texelOffset, uColor: this.sceneFramebuffer.color, uDepth: this.sceneFramebuffer.depth }); this.dofProgram.draw({ vertexArray: this.quadVertexArray, drawMode: gl.TRIANGLE_STRIP, vertexCount: 4, framebuffer: this.dofFramebuffer }); // Vertical DOF blur clear(device, {color: [0, 0, 0, 1]}); texelOffset[0] = 0; texelOffset[1] = 1; this.dofProgram.setUniforms({ uTexelOffset: texelOffset, uColor: this.sceneFramebuffer.color, uDepth: this.sceneFramebuffer.depth }); this.dofProgram.draw({ vertexArray: this.quadVertexArray, drawMode: GL.TRIANGLE_STRIP, vertexCount: 4 }); this.dofUniforms.unbind(); } } // @ts-ignore if (typeof window !== 'undefined' && !window.website) { RenderLoop.run(AppRenderLoop).start(); }
the_stack
import CLASS from './class' import { isValue, isFunction, isString, isEmpty, getBBox } from './util' import { AxisInternal } from './axis-internal' export default class AxisClass { owner: any d3: any internal: typeof AxisInternal constructor(owner) { this.owner = owner this.d3 = owner.d3 this.internal = AxisInternal } } const Axis = AxisClass as any Axis.prototype.init = function init() { var $$ = this.owner, config = $$.config, main = $$.main $$.axes.x = main .append('g') .attr('class', CLASS.axis + ' ' + CLASS.axisX) .attr('clip-path', config.axis_x_inner ? '' : $$.clipPathForXAxis) .attr('transform', $$.getTranslate('x')) .style('visibility', config.axis_x_show ? 'visible' : 'hidden') $$.axes.x .append('text') .attr('class', CLASS.axisXLabel) .attr('transform', config.axis_rotated ? 'rotate(-90)' : '') .style('text-anchor', this.textAnchorForXAxisLabel.bind(this)) $$.axes.y = main .append('g') .attr('class', CLASS.axis + ' ' + CLASS.axisY) .attr('clip-path', config.axis_y_inner ? '' : $$.clipPathForYAxis) .attr('transform', $$.getTranslate('y')) .style('visibility', config.axis_y_show ? 'visible' : 'hidden') $$.axes.y .append('text') .attr('class', CLASS.axisYLabel) .attr('transform', config.axis_rotated ? '' : 'rotate(-90)') .style('text-anchor', this.textAnchorForYAxisLabel.bind(this)) $$.axes.y2 = main .append('g') .attr('class', CLASS.axis + ' ' + CLASS.axisY2) // clip-path? .attr('transform', $$.getTranslate('y2')) .style('visibility', config.axis_y2_show ? 'visible' : 'hidden') $$.axes.y2 .append('text') .attr('class', CLASS.axisY2Label) .attr('transform', config.axis_rotated ? '' : 'rotate(-90)') .style('text-anchor', this.textAnchorForY2AxisLabel.bind(this)) } Axis.prototype.getXAxis = function getXAxis( scale, orient, tickFormat, tickValues, withOuterTick, withoutTransition, withoutRotateTickText ) { var $$ = this.owner, config = $$.config, axisParams = { isCategory: $$.isCategorized(), withOuterTick: withOuterTick, tickMultiline: config.axis_x_tick_multiline, tickMultilineMax: config.axis_x_tick_multiline ? Number(config.axis_x_tick_multilineMax) : 0, tickWidth: config.axis_x_tick_width, tickTextRotate: withoutRotateTickText ? 0 : config.axis_x_tick_rotate, withoutTransition: withoutTransition }, axis = new this.internal(this, axisParams).axis.scale(scale).orient(orient) if ($$.isTimeSeries() && tickValues && typeof tickValues !== 'function') { tickValues = tickValues.map(function(v) { return $$.parseDate(v) }) } // Set tick axis.tickFormat(tickFormat).tickValues(tickValues) if ($$.isCategorized()) { axis.tickCentered(config.axis_x_tick_centered) if (isEmpty(config.axis_x_tick_culling)) { config.axis_x_tick_culling = false } } return axis } Axis.prototype.updateXAxisTickValues = function updateXAxisTickValues( targets, axis ) { var $$ = this.owner, config = $$.config, tickValues if (config.axis_x_tick_fit || config.axis_x_tick_count) { tickValues = this.generateTickValues( $$.mapTargetsToUniqueXs(targets), config.axis_x_tick_count, $$.isTimeSeries() ) } if (axis) { axis.tickValues(tickValues) } else { $$.xAxis.tickValues(tickValues) $$.subXAxis.tickValues(tickValues) } return tickValues } Axis.prototype.getYAxis = function getYAxis( axisId, scale, orient, tickValues, withOuterTick, withoutTransition, withoutRotateTickText ) { const $$ = this.owner const config = $$.config let tickFormat = config[`axis_${axisId}_tick_format`] if (!tickFormat && $$.isAxisNormalized(axisId)) { tickFormat = x => `${x}%` } const axis = new this.internal(this, { withOuterTick: withOuterTick, withoutTransition: withoutTransition, tickTextRotate: withoutRotateTickText ? 0 : config.axis_y_tick_rotate }).axis .scale(scale) .orient(orient) if (tickFormat) { axis.tickFormat(tickFormat) } if ($$.isTimeSeriesY()) { axis.ticks(config.axis_y_tick_time_type, config.axis_y_tick_time_interval) } else { axis.tickValues(tickValues) } return axis } Axis.prototype.getId = function getId(id) { var config = this.owner.config return id in config.data_axes ? config.data_axes[id] : 'y' } Axis.prototype.getXAxisTickFormat = function getXAxisTickFormat() { // #2251 previously set any negative values to a whole number, // however both should be truncated according to the users format specification var $$ = this.owner, config = $$.config let format = $$.isTimeSeries() ? $$.defaultAxisTimeFormat : $$.isCategorized() ? $$.categoryName : function(v) { return v } if (config.axis_x_tick_format) { if (isFunction(config.axis_x_tick_format)) { format = config.axis_x_tick_format } else if ($$.isTimeSeries()) { format = function(date) { return date ? $$.axisTimeFormat(config.axis_x_tick_format)(date) : '' } } } return isFunction(format) ? function(v) { return format.call($$, v) } : format } Axis.prototype.getTickValues = function getTickValues(tickValues, axis) { return tickValues ? tickValues : axis ? axis.tickValues() : undefined } Axis.prototype.getXAxisTickValues = function getXAxisTickValues() { return this.getTickValues( this.owner.config.axis_x_tick_values, this.owner.xAxis ) } Axis.prototype.getYAxisTickValues = function getYAxisTickValues() { return this.getTickValues( this.owner.config.axis_y_tick_values, this.owner.yAxis ) } Axis.prototype.getY2AxisTickValues = function getY2AxisTickValues() { return this.getTickValues( this.owner.config.axis_y2_tick_values, this.owner.y2Axis ) } Axis.prototype.getLabelOptionByAxisId = function getLabelOptionByAxisId( axisId ) { var $$ = this.owner, config = $$.config, option if (axisId === 'y') { option = config.axis_y_label } else if (axisId === 'y2') { option = config.axis_y2_label } else if (axisId === 'x') { option = config.axis_x_label } return option } Axis.prototype.getLabelText = function getLabelText(axisId) { var option = this.getLabelOptionByAxisId(axisId) return isString(option) ? option : option ? option.text : null } Axis.prototype.setLabelText = function setLabelText(axisId, text) { var $$ = this.owner, config = $$.config, option = this.getLabelOptionByAxisId(axisId) if (isString(option)) { if (axisId === 'y') { config.axis_y_label = text } else if (axisId === 'y2') { config.axis_y2_label = text } else if (axisId === 'x') { config.axis_x_label = text } } else if (option) { option.text = text } } Axis.prototype.getLabelPosition = function getLabelPosition( axisId, defaultPosition ) { var option = this.getLabelOptionByAxisId(axisId), position = option && typeof option === 'object' && option.position ? option.position : defaultPosition return { isInner: position.indexOf('inner') >= 0, isOuter: position.indexOf('outer') >= 0, isLeft: position.indexOf('left') >= 0, isCenter: position.indexOf('center') >= 0, isRight: position.indexOf('right') >= 0, isTop: position.indexOf('top') >= 0, isMiddle: position.indexOf('middle') >= 0, isBottom: position.indexOf('bottom') >= 0 } } Axis.prototype.getXAxisLabelPosition = function getXAxisLabelPosition() { return this.getLabelPosition( 'x', this.owner.config.axis_rotated ? 'inner-top' : 'inner-right' ) } Axis.prototype.getYAxisLabelPosition = function getYAxisLabelPosition() { return this.getLabelPosition( 'y', this.owner.config.axis_rotated ? 'inner-right' : 'inner-top' ) } Axis.prototype.getY2AxisLabelPosition = function getY2AxisLabelPosition() { return this.getLabelPosition( 'y2', this.owner.config.axis_rotated ? 'inner-right' : 'inner-top' ) } Axis.prototype.getLabelPositionById = function getLabelPositionById(id) { return id === 'y2' ? this.getY2AxisLabelPosition() : id === 'y' ? this.getYAxisLabelPosition() : this.getXAxisLabelPosition() } Axis.prototype.textForXAxisLabel = function textForXAxisLabel() { return this.getLabelText('x') } Axis.prototype.textForYAxisLabel = function textForYAxisLabel() { return this.getLabelText('y') } Axis.prototype.textForY2AxisLabel = function textForY2AxisLabel() { return this.getLabelText('y2') } Axis.prototype.xForAxisLabel = function xForAxisLabel(forHorizontal, position) { var $$ = this.owner if (forHorizontal) { return position.isLeft ? 0 : position.isCenter ? $$.width / 2 : $$.width } else { return position.isBottom ? -$$.height : position.isMiddle ? -$$.height / 2 : 0 } } Axis.prototype.dxForAxisLabel = function dxForAxisLabel( forHorizontal, position ) { if (forHorizontal) { return position.isLeft ? '0.5em' : position.isRight ? '-0.5em' : '0' } else { return position.isTop ? '-0.5em' : position.isBottom ? '0.5em' : '0' } } Axis.prototype.textAnchorForAxisLabel = function textAnchorForAxisLabel( forHorizontal, position ) { if (forHorizontal) { return position.isLeft ? 'start' : position.isCenter ? 'middle' : 'end' } else { return position.isBottom ? 'start' : position.isMiddle ? 'middle' : 'end' } } Axis.prototype.xForXAxisLabel = function xForXAxisLabel() { return this.xForAxisLabel( !this.owner.config.axis_rotated, this.getXAxisLabelPosition() ) } Axis.prototype.xForYAxisLabel = function xForYAxisLabel() { return this.xForAxisLabel( this.owner.config.axis_rotated, this.getYAxisLabelPosition() ) } Axis.prototype.xForY2AxisLabel = function xForY2AxisLabel() { return this.xForAxisLabel( this.owner.config.axis_rotated, this.getY2AxisLabelPosition() ) } Axis.prototype.dxForXAxisLabel = function dxForXAxisLabel() { return this.dxForAxisLabel( !this.owner.config.axis_rotated, this.getXAxisLabelPosition() ) } Axis.prototype.dxForYAxisLabel = function dxForYAxisLabel() { return this.dxForAxisLabel( this.owner.config.axis_rotated, this.getYAxisLabelPosition() ) } Axis.prototype.dxForY2AxisLabel = function dxForY2AxisLabel() { return this.dxForAxisLabel( this.owner.config.axis_rotated, this.getY2AxisLabelPosition() ) } Axis.prototype.dyForXAxisLabel = function dyForXAxisLabel() { var $$ = this.owner, config = $$.config, position = this.getXAxisLabelPosition() if (config.axis_rotated) { return position.isInner ? '1.2em' : -25 - ($$.config.axis_x_inner ? 0 : this.getMaxTickWidth('x')) } else { return position.isInner ? '-0.5em' : $$.getHorizontalAxisHeight('x') - 10 } } Axis.prototype.dyForYAxisLabel = function dyForYAxisLabel() { var $$ = this.owner, position = this.getYAxisLabelPosition() if ($$.config.axis_rotated) { return position.isInner ? '-0.5em' : '3em' } else { return position.isInner ? '1.2em' : -10 - ($$.config.axis_y_inner ? 0 : this.getMaxTickWidth('y') + 10) } } Axis.prototype.dyForY2AxisLabel = function dyForY2AxisLabel() { var $$ = this.owner, position = this.getY2AxisLabelPosition() if ($$.config.axis_rotated) { return position.isInner ? '1.2em' : '-2.2em' } else { return position.isInner ? '-0.5em' : 15 + ($$.config.axis_y2_inner ? 0 : this.getMaxTickWidth('y2') + 15) } } Axis.prototype.textAnchorForXAxisLabel = function textAnchorForXAxisLabel() { var $$ = this.owner return this.textAnchorForAxisLabel( !$$.config.axis_rotated, this.getXAxisLabelPosition() ) } Axis.prototype.textAnchorForYAxisLabel = function textAnchorForYAxisLabel() { var $$ = this.owner return this.textAnchorForAxisLabel( $$.config.axis_rotated, this.getYAxisLabelPosition() ) } Axis.prototype.textAnchorForY2AxisLabel = function textAnchorForY2AxisLabel() { var $$ = this.owner return this.textAnchorForAxisLabel( $$.config.axis_rotated, this.getY2AxisLabelPosition() ) } Axis.prototype.getMaxTickWidth = function getMaxTickWidth( id, withoutRecompute ) { var $$ = this.owner, maxWidth = 0, targetsToShow, scale, axis, dummy, svg if (withoutRecompute && $$.currentMaxTickWidths[id]) { return $$.currentMaxTickWidths[id] } if ($$.svg) { targetsToShow = $$.filterTargetsToShow($$.data.targets) if (id === 'y') { scale = $$.y.copy().domain($$.getYDomain(targetsToShow, 'y')) axis = this.getYAxis( id, scale, $$.yOrient, $$.yAxisTickValues, false, true, true ) } else if (id === 'y2') { scale = $$.y2.copy().domain($$.getYDomain(targetsToShow, 'y2')) axis = this.getYAxis( id, scale, $$.y2Orient, $$.y2AxisTickValues, false, true, true ) } else { scale = $$.x.copy().domain($$.getXDomain(targetsToShow)) axis = this.getXAxis( scale, $$.xOrient, $$.xAxisTickFormat, $$.xAxisTickValues, false, true, true ) this.updateXAxisTickValues(targetsToShow, axis) } dummy = $$.d3 .select('body') .append('div') .classed('c3', true) ;(svg = dummy .append('svg') .style('visibility', 'hidden') .style('position', 'fixed') .style('top', 0) .style('left', 0)), svg .append('g') .call(axis) .each(function() { $$.d3 .select(this) .selectAll('text') .each(function() { var box = getBBox(this) if (maxWidth < box.width) { maxWidth = box.width } }) dummy.remove() }) } $$.currentMaxTickWidths[id] = maxWidth <= 0 ? $$.currentMaxTickWidths[id] : maxWidth return $$.currentMaxTickWidths[id] } Axis.prototype.updateLabels = function updateLabels(withTransition) { var $$ = this.owner var axisXLabel = $$.main.select('.' + CLASS.axisX + ' .' + CLASS.axisXLabel), axisYLabel = $$.main.select('.' + CLASS.axisY + ' .' + CLASS.axisYLabel), axisY2Label = $$.main.select('.' + CLASS.axisY2 + ' .' + CLASS.axisY2Label) ;(withTransition ? axisXLabel.transition() : axisXLabel) .attr('x', this.xForXAxisLabel.bind(this)) .attr('dx', this.dxForXAxisLabel.bind(this)) .attr('dy', this.dyForXAxisLabel.bind(this)) .text(this.textForXAxisLabel.bind(this)) ;(withTransition ? axisYLabel.transition() : axisYLabel) .attr('x', this.xForYAxisLabel.bind(this)) .attr('dx', this.dxForYAxisLabel.bind(this)) .attr('dy', this.dyForYAxisLabel.bind(this)) .text(this.textForYAxisLabel.bind(this)) ;(withTransition ? axisY2Label.transition() : axisY2Label) .attr('x', this.xForY2AxisLabel.bind(this)) .attr('dx', this.dxForY2AxisLabel.bind(this)) .attr('dy', this.dyForY2AxisLabel.bind(this)) .text(this.textForY2AxisLabel.bind(this)) } Axis.prototype.getPadding = function getPadding( padding, key, defaultValue, domainLength ) { var p = typeof padding === 'number' ? padding : padding[key] if (!isValue(p)) { return defaultValue } if (padding.unit === 'ratio') { return padding[key] * domainLength } // assume padding is pixels if unit is not specified return this.convertPixelsToAxisPadding(p, domainLength) } Axis.prototype.convertPixelsToAxisPadding = function convertPixelsToAxisPadding( pixels, domainLength ) { var $$ = this.owner, length = $$.config.axis_rotated ? $$.width : $$.height return domainLength * (pixels / length) } Axis.prototype.generateTickValues = function generateTickValues( values, tickCount, forTimeSeries ) { var tickValues = values, targetCount, start, end, count, interval, i, tickValue if (tickCount) { targetCount = isFunction(tickCount) ? tickCount() : tickCount // compute ticks according to tickCount if (targetCount === 1) { tickValues = [values[0]] } else if (targetCount === 2) { tickValues = [values[0], values[values.length - 1]] } else if (targetCount > 2) { count = targetCount - 2 start = values[0] end = values[values.length - 1] interval = (end - start) / (count + 1) // re-construct unique values tickValues = [start] for (i = 0; i < count; i++) { tickValue = +start + interval * (i + 1) tickValues.push(forTimeSeries ? new Date(tickValue) : tickValue) } tickValues.push(end) } } if (!forTimeSeries) { tickValues = tickValues.sort(function(a, b) { return a - b }) } return tickValues } Axis.prototype.generateTransitions = function generateTransitions(duration) { var $$ = this.owner, axes = $$.axes return { axisX: duration ? axes.x.transition().duration(duration) : axes.x, axisY: duration ? axes.y.transition().duration(duration) : axes.y, axisY2: duration ? axes.y2.transition().duration(duration) : axes.y2, axisSubX: duration ? axes.subx.transition().duration(duration) : axes.subx } } Axis.prototype.redraw = function redraw(duration, isHidden) { var $$ = this.owner, transition = duration ? $$.d3.transition().duration(duration) : null $$.axes.x.style('opacity', isHidden ? 0 : 1).call($$.xAxis, transition) $$.axes.y.style('opacity', isHidden ? 0 : 1).call($$.yAxis, transition) $$.axes.y2.style('opacity', isHidden ? 0 : 1).call($$.y2Axis, transition) $$.axes.subx.style('opacity', isHidden ? 0 : 1).call($$.subXAxis, transition) }
the_stack
import fs from 'fs'; import path from 'path'; import R from 'ramda'; import { partition, set } from 'lodash'; import generateTree, { processPath } from './generate-tree-madge'; import { DEFAULT_BINDINGS_PREFIX } from '../../../../constants'; import { getPathMapWithLinkFilesData, convertPathMapToRelativePaths } from './path-map'; import { PathMapItem } from './path-map'; import { Tree, FileObject, ImportSpecifier, DependencyTreeParams, ResolveModulesConfig, ResolvedNodePackage } from './types/dependency-tree-type'; import PackageJson from '../../package-json'; import { PathOsBased, PathLinuxAbsolute } from '../../../../utils/path'; import { BitId } from '../../../../bit-id'; export type LinkFile = { file: string; importSpecifiers: ImportSpecifier[]; }; interface SimpleGroupedDependencies { bits: string[]; packages: string[]; files: string[]; } /** * Group dependencies by types (files, bits, packages) * @param {any} dependencies list of dependencies paths to group * @returns {Function} function which group the dependencies */ const byType = (list, bindingPrefix): SimpleGroupedDependencies => { const grouped = R.groupBy(item => { if (item.includes(`node_modules/${bindingPrefix}`) || item.includes(`node_modules/${DEFAULT_BINDINGS_PREFIX}`)) { return 'bits'; } return item.includes('node_modules') ? 'packages' : 'files'; }); return grouped(list); }; /** * Get a path to node package and return the name and version * * @param {any} packageFullPath full path to the package * @returns {Object} name and version of the package */ export function resolveNodePackage(cwd: string, packageFullPath: PathLinuxAbsolute): ResolvedNodePackage | undefined { const NODE_MODULES = 'node_modules'; const result: ResolvedNodePackage = { fullPath: packageFullPath, name: '', componentId: undefined }; // Start by searching in the component dir and up from there // If not found search in package dir itself. // We are doing this, because the package.json inside the package dir contain exact version // And the component/consumer package.json might contain semver like ^ or ~ // We want to have this semver as dependency and not the exact version, otherwise it will be considered as modified all the time // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! const packageJsonInfo = PackageJson.findPackage(cwd); if (packageJsonInfo) { // The +1 is for the / after the node_modules, we didn't enter it into the NODE_MODULES const because it makes problems on windows const packageRelativePath = packageFullPath.substring( packageFullPath.lastIndexOf(NODE_MODULES) + NODE_MODULES.length + 1, packageFullPath.length ); const packageName = resolvePackageNameByPath(packageRelativePath); const packageNameNormalized = packageName.replace('\\', '/'); const packageVersion = R.path(['dependencies', packageNameNormalized], packageJsonInfo) || R.path(['devDependencies', packageNameNormalized], packageJsonInfo) || R.path(['peerDependencies', packageNameNormalized], packageJsonInfo); if (packageVersion) { result.name = packageNameNormalized; result.versionUsedByDependent = packageVersion; } } // Get the package relative path to the node_modules dir const packageDir = resolvePackageDirFromFilePath(packageFullPath); // don't propagate here since loading a package.json of another folder and taking the version from it will result wrong version // This for example happen in the following case: // if you have 2 authored component which one dependent on the other // we will look for the package.json on the dependency but won't find it // if we propagate we will take the version from the root's package json which has nothing with the component version // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! const packageInfo = PackageJson.loadSync(packageDir); // when running 'bitjs get-dependencies' command, packageInfo is sometimes empty // or when using custom-module-resolution it may be empty or the name/version are empty if (!packageInfo || !packageInfo.name || !packageInfo.version) { if (!result.name) { return undefined; } return result; } result.name = packageInfo.name; result.concreteVersion = packageInfo.version; if (packageInfo.componentId) { result.componentId = new BitId(packageInfo.componentId); } return result; } /** * given the full path of a package file, returns the root dir of the package, so then we could * find the package.json in that directory. * * example of a normal package: * absolutePackageFilePath: /user/workspace/node_modules/lodash.isboolean/index.js * returns: /user/workspace/node_modules/lodash.isboolean * * example of a scoped package: * absolutePackageFilePath: /user/workspace/node_modules/@babel/core/lib/index.js * returns: /user/workspace/node_modules/@babel/core */ function resolvePackageDirFromFilePath(absolutePackageFilePath: string): string { const NODE_MODULES = 'node_modules'; const indexOfLastNodeModules = absolutePackageFilePath.lastIndexOf(NODE_MODULES) + NODE_MODULES.length + 1; const pathInsideNodeModules = absolutePackageFilePath.substring(indexOfLastNodeModules); const packageName = resolvePackageNameByPath(pathInsideNodeModules); const pathUntilNodeModules = absolutePackageFilePath.substring(0, indexOfLastNodeModules); return pathUntilNodeModules + packageName; } interface GroupedDependenciesResolved { bits: Array<ResolvedNodePackage>; packages: PackageDependency; files: string[]; unidentifiedPackages: PathOsBased[]; } /** * Gets a list of dependencies and group them by types (files, bits, packages) * It's also transform the node package dependencies from array of paths to object in this format: * {dependencyName: version} (like in package.json) * * @param {any} list of dependencies paths * @param {any} cwd root of working directory (used for node packages version calculation) * @returns {Object} object with the dependencies groups */ function groupDependencyList(list, cwd, bindingPrefix): GroupedDependenciesResolved { const groups = byType(list, bindingPrefix); const resultGroups: GroupedDependenciesResolved = { bits: [], packages: {}, files: groups.files, unidentifiedPackages: [] }; const unidentifiedPackages: string[] = []; if (groups.packages) { const packages = {}; groups.packages.forEach(packagePath => { const resolvedPackage = resolveNodePackage(cwd, path.join(cwd, packagePath)); // If the package is actually a component add it to the components (bits) list if (resolvedPackage) { if (resolvedPackage.componentId) { resultGroups.bits.push(resolvedPackage); } else { const version = resolvedPackage.versionUsedByDependent || resolvedPackage.concreteVersion; if (version) { const packageWithVersion = { [resolvedPackage.name]: version }; Object.assign(packages, packageWithVersion); } } } else unidentifiedPackages.push(packagePath); }); resultGroups.packages = packages; } if (groups.bits) { groups.bits.forEach(packagePath => { const resolvedPackage = resolveNodePackage(cwd, path.join(cwd, packagePath)); // If the package is actually a component add it to the components (bits) list if (resolvedPackage) { resultGroups.bits.push(resolvedPackage); } else { unidentifiedPackages.push(packagePath); } }); } if (!R.isEmpty(unidentifiedPackages)) { resultGroups.unidentifiedPackages = unidentifiedPackages; } return resultGroups; } interface GroupedDependenciesTree { [filePath: string]: GroupedDependenciesResolved; } /** * Run over each entry in the tree and transform the dependencies from list of paths * to object with dependencies types * * @param {any} tree * @param {any} cwd the working directory path * @returns new tree with grouped dependencies */ function groupDependencyTree(tree, cwd, bindingPrefix): GroupedDependenciesTree { const result = {}; Object.keys(tree).forEach(key => { if (tree[key] && !R.isEmpty(tree[key])) { result[key] = groupDependencyList(tree[key], cwd, bindingPrefix); } else { result[key] = {}; } }); return result; } /** * return the package name by the import statement path to node package * * @param {string} packagePath import statement path * @returns {string} name of the package */ function resolvePackageNameByPath(packagePath): string { const packagePathArr = packagePath.split(path.sep); // TODO: make sure this is working on windows // Regular package without path. example - import _ from 'lodash' if (packagePathArr.length === 1) return packagePath; // Scoped package. example - import getSymbolIterator from '@angular/core/src/util.d.ts'; if (packagePathArr[0].startsWith('@')) return path.join(packagePathArr[0], packagePathArr[1]); // Regular package with internal path. example import something from 'mypackage/src/util/isString' return packagePathArr[0]; } /** * Recursively search for node module inside node_modules dir * This function propagate up until it gets to the root provided then stops * * @param {string} nmPath - package name * @param {string} workingDir - dir to start searching of * @param {string} root - path to dir to stop the search * @returns The resolved path for the package directory */ export function resolveModulePath(nmPath: string, workingDir: string, root: string): PathOsBased | undefined { const pathToCheck = path.resolve(workingDir, 'node_modules', nmPath); if (fs.existsSync(pathToCheck)) { return pathToCheck; } if (workingDir === root) { return undefined; } const parentWorkingDir = path.dirname(workingDir); if (parentWorkingDir === workingDir) return undefined; return resolveModulePath(nmPath, parentWorkingDir, root); } interface PackageDependency { [dependencyId: string]: string; } interface PackageDependenciesTypes { dependencies?: PackageDependency; devDependencies?: PackageDependency; peerDependencies?: PackageDependency; } interface FindPackagesResult { foundPackages: { [packageName: string]: PackageDependenciesTypes; }; missingPackages: string[]; } /** * Resolve package dependencies from package.json according to package names * * @param {Object} packageJson * @param {string []} packagesNames * @returns new object with found and missing */ function findPackagesInPackageJson(packageJson: Record<string, any>, packagesNames: string[]): FindPackagesResult { const { dependencies, devDependencies, peerDependencies } = packageJson; const foundPackages = {}; const mergedDependencies = Object.assign({}, dependencies, devDependencies, peerDependencies); if (packagesNames && packagesNames.length && !R.isNil(mergedDependencies)) { const [foundPackagesPartition, missingPackages] = partition(packagesNames, item => item in mergedDependencies); foundPackagesPartition.forEach(pack => (foundPackages[pack] = mergedDependencies[pack])); return { foundPackages, missingPackages }; } return { foundPackages: {}, missingPackages: packagesNames }; } type Missing = { [absolutePath: string]: string[] }; // e.g. { '/tmp/workspace': ['lodash', 'ramda'] }; type MissingGroupItem = { originFile: string; packages?: string[]; bits?: string[]; files?: string[] }; type FoundPackages = { packages: { [packageName: string]: string }; bits: Array<ResolvedNodePackage> }; /** * Run over each entry in the missing array and transform the missing from list of paths * to object with missing types * * @param {Array} missing * @param {string} cwd * @param {string} workspacePath * @param {string} bindingPrefix * @returns new object with grouped missing */ function groupMissing( missing: Missing, cwd, workspacePath, bindingPrefix ): { missingGroups: MissingGroupItem[]; foundPackages: FoundPackages } { // temporarily disable this functionality since it cause few bugs: explanation below (on using the packageJson) // const packageJson = PackageJson.findPackage(cwd); /** * Group missing dependencies by types (files, bits, packages) * @param {Array} missing list of missing paths to group * @returns {Function} function which group the dependencies */ const byPathType = R.groupBy(item => { if (item.startsWith(`${bindingPrefix}/`) || item.startsWith(`${DEFAULT_BINDINGS_PREFIX}/`)) return 'bits'; return item.startsWith('.') ? 'files' : 'packages'; }); const groups: MissingGroupItem[] = Object.keys(missing).map(key => Object.assign({ originFile: processPath(key, {}, cwd) }, byPathType(missing[key], bindingPrefix)) ); groups.forEach((group: MissingGroupItem) => { if (group.packages) group.packages = group.packages.map(resolvePackageNameByPath); if (group.bits) group.bits = group.bits.map(resolvePackageNameByPath); }); // This is a hack to solve problems that madge has with packages for type script files // It see them as missing even if they are exists const foundPackages: FoundPackages = { packages: {}, bits: [] }; const packageJson = PackageJson.findPackage(cwd); groups.forEach((group: MissingGroupItem) => { const missingPackages: string[] = []; if (group.packages) { group.packages.forEach(packageName => { // Don't try to resolve the same package twice if (R.contains(packageName, missingPackages)) return; const resolvedPath = resolveModulePath(packageName, cwd, workspacePath); if (!resolvedPath) { missingPackages.push(packageName); return; } const resolvedPackage = resolveNodePackage(cwd, resolvedPath); // If the package is actually a component add it to the components (bits) list if (resolvedPackage) { if (resolvedPackage.componentId) { foundPackages.bits.push(resolvedPackage); } else { const version = resolvedPackage.versionUsedByDependent || resolvedPackage.concreteVersion; if (version) { const packageWithVersion = { [resolvedPackage.name]: version }; Object.assign(foundPackages.packages, packageWithVersion); } } } else { missingPackages.push(packageName); } }); } // this was disabled since it cause these bugs: // (as part of 9ddeb61aa29c170cd58df0c2cc1cc30db1ebded8 of bit-javascript) // https://github.com/teambit/bit/issues/635 // https://github.com/teambit/bit/issues/690 // later it re-enabled by this commit (d192a295632255dba9f0d62232fb237feeb8f33a of bit-javascript) // we should think if we really want it if (packageJson) { const result = findPackagesInPackageJson(packageJson, missingPackages); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! groups.packages = result.missingPackages; Object.assign(foundPackages.packages, result.foundPackages); if (group.bits) { const foundBits = findPackagesInPackageJson(packageJson, group.bits); R.forEachObjIndexed((version, name) => { const resolvedFoundBit: ResolvedNodePackage = { name, versionUsedByDependent: version }; foundPackages.bits.push(resolvedFoundBit); }, foundBits.foundPackages); } } }); return { missingGroups: groups, foundPackages }; } /** * add extra data such as custom-resolve and link-files from pathMap */ function updateTreeWithPathMap(tree: Tree, pathMapAbsolute: PathMapItem[], baseDir: string): void { if (!pathMapAbsolute.length) return; const pathMapRelative = convertPathMapToRelativePaths(pathMapAbsolute, baseDir); const pathMap = getPathMapWithLinkFilesData(pathMapRelative); Object.keys(tree).forEach((filePath: string) => { const treeFiles = tree[filePath].files; if (!treeFiles || !treeFiles.length) return; // file has no dependency const mainFilePathMap = pathMap.find(file => file.file === filePath); if (!mainFilePathMap) throw new Error(`updateTreeWithPathMap: PathMap is missing for ${filePath}`); // a file might have a cycle dependency with itself, remove it from the dependencies. const files: FileObject[] = treeFiles // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! .filter(dependency => dependency !== filePath) // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! .map((dependency: string) => { const dependencyPathMap = mainFilePathMap.dependencies.find(file => file.resolvedDep === dependency); if (!dependencyPathMap) throw new Error(`updateTreeWithPathMap: dependencyPathMap is missing for ${dependency}`); const fileObject: FileObject = { file: dependency, importSource: dependencyPathMap.importSource, isCustomResolveUsed: dependencyPathMap.isCustomResolveUsed }; if (dependencyPathMap.linkFile) { fileObject.isLink = true; fileObject.linkDependencies = dependencyPathMap.realDependencies; return fileObject; } if (dependencyPathMap.importSpecifiers && dependencyPathMap.importSpecifiers.length) { const depImportSpecifiers = dependencyPathMap.importSpecifiers.map(importSpecifier => { return { mainFile: importSpecifier }; }); fileObject.importSpecifiers = depImportSpecifiers; } return fileObject; }); tree[filePath].files = files; // eslint-disable-line no-param-reassign }); } /** * config aliases are passed later on to webpack-enhancer and it expects them to have the full path */ function getResolveConfigAbsolute( workspacePath: string, resolveConfig: ResolveModulesConfig | null | undefined ): ResolveModulesConfig | null | undefined { if (!resolveConfig) return resolveConfig; const resolveConfigAbsolute = R.clone(resolveConfig); if (resolveConfig.modulesDirectories) { resolveConfigAbsolute.modulesDirectories = resolveConfig.modulesDirectories.map(moduleDirectory => { return path.isAbsolute(moduleDirectory) ? moduleDirectory : path.join(workspacePath, moduleDirectory); }); } if (resolveConfigAbsolute.aliases) { Object.keys(resolveConfigAbsolute.aliases).forEach(alias => { if (!path.isAbsolute(resolveConfigAbsolute.aliases[alias])) { resolveConfigAbsolute.aliases[alias] = path.join(workspacePath, resolveConfigAbsolute.aliases[alias]); } }); } return resolveConfigAbsolute; } function mergeManuallyFoundPackagesToTree(foundPackages: FoundPackages, missingGroups: MissingGroupItem[], tree: Tree) { if (R.isEmpty(foundPackages.bits) && R.isEmpty(foundPackages.packages)) return; // Merge manually found packages (by groupMissing()) with the packages found by Madge (generate-tree-madge) Object.keys(foundPackages.packages).forEach(pkg => { // locate package in groups(contains missing) missingGroups.forEach((fileDep: MissingGroupItem) => { if (fileDep.packages && fileDep.packages.includes(pkg)) { fileDep.packages = fileDep.packages.filter(packageName => packageName !== pkg); set(tree[fileDep.originFile], ['packages', pkg], foundPackages.packages[pkg]); } if (fileDep.bits && fileDep.bits.includes(pkg)) { fileDep.bits = fileDep.bits.filter(packageName => packageName !== pkg); if (!tree[fileDep.originFile]) tree[fileDep.originFile] = {}; if (!tree[fileDep.originFile].bits) tree[fileDep.originFile].bits = []; // @ts-ignore tree[fileDep.originFile].bits.push(pkg); } }); }); foundPackages.bits.forEach(component => { missingGroups.forEach((fileDep: MissingGroupItem) => { if ( fileDep.bits && ((component.fullPath && fileDep.bits.includes(component.fullPath)) || fileDep.bits.includes(component.name)) ) { fileDep.bits = fileDep.bits.filter(existComponent => { return existComponent !== component.fullPath && existComponent !== component.name; }); if (!tree[fileDep.originFile]) tree[fileDep.originFile] = {}; if (!tree[fileDep.originFile].bits) tree[fileDep.originFile].bits = []; // @ts-ignore tree[fileDep.originFile].bits.push(component); } }); }); } function mergeMissingToTree(missingGroups, tree: Tree) { if (R.isEmpty(missingGroups)) return; missingGroups.forEach(missing => { const missingCloned = R.clone(missing); delete missingCloned.originFile; if (tree[missing.originFile]) tree[missing.originFile].missing = missingCloned; else tree[missing.originFile] = { missing: missingCloned }; }); } function mergeErrorsToTree(baseDir, errors, tree: Tree) { if (R.isEmpty(errors)) return; Object.keys(errors).forEach(file => { if (tree[file]) tree[file].error = errors[file]; else tree[file] = { error: errors[file] }; }); } /** * Function for fetching dependency tree of file or dir * @param baseDir working directory * @param workspacePath * @param filePaths path of the file to calculate the dependencies * @param bindingPrefix * @return {Promise<{missing, tree}>} */ export async function getDependencyTree({ baseDir, workspacePath, filePaths, bindingPrefix, resolveModulesConfig, visited = {}, cacheProjectAst }: DependencyTreeParams): Promise<{ tree: Tree }> { const resolveConfigAbsolute = getResolveConfigAbsolute(workspacePath, resolveModulesConfig); const config = { baseDir, includeNpm: true, requireConfig: null, webpackConfig: null, visited, nonExistent: [], resolveConfig: resolveConfigAbsolute, cacheProjectAst }; // This is important because without this, madge won't know to resolve files if we run the // CMD not from the root dir const fullPaths = filePaths.map(filePath => { if (filePath.startsWith(baseDir)) { return filePath; } return path.resolve(baseDir, filePath); }); // @ts-ignore AUTO-ADDED-AFTER-MIGRATION-PLEASE-FIX! const { madgeTree, skipped, pathMap, errors } = generateTree(fullPaths, config); // @ts-ignore const tree: Tree = groupDependencyTree(madgeTree, baseDir, bindingPrefix); const { missingGroups, foundPackages } = groupMissing(skipped, baseDir, workspacePath, bindingPrefix); if (foundPackages) mergeManuallyFoundPackagesToTree(foundPackages, missingGroups, tree); if (errors) mergeErrorsToTree(baseDir, errors, tree); if (missingGroups) mergeMissingToTree(missingGroups, tree); if (pathMap) updateTreeWithPathMap(tree, pathMap, baseDir); return { tree }; }
the_stack
import { MCanvas, MImage } from '../src/index' import ear from './images/ear.png' import watermark from './images/watermark.jpg' import imgTest from './images/1.jpg' import './main.scss' // (async () => { // const mc = new MImage('http://mtapplet.meitudata.com/596c72073971d86b5128.jpg') // const b64 = await mc.crop({ // width: 300, // height: 300, // x: 0, // y: 0, // }).filter('blur').compress({ // width: 100, // height: 100, // }).draw() // $('.js-result').attr('src', b64) // })() let $sure = $('.js-sure') let $params = $('.js-params') let $dialog = $('.js-dialog') let $result = $('.js-result') let $cancel = $('.js-cancel') let $clear = $('.js-clear') let data = { addImageOps : { image: ear, options: { width: 482, // crop: { // x: 192, // y: 84, // width: 365, // height: 365, // radius: '50%', // }, pos: { x: 150, y: 50, scale: 1, rotate: 0, }, }, }, addWmOps : { image: watermark, options: { width: '40%', pos: 'rightBottom', }, }, addRectOps: { x: 0, y: 'bottom:0', width: '100%', height: 300, radius: 30, strokeWidth : 5, strokeColor: '#996699', fillColor: 'rgba(0,0,0,.5)', }, addCircleOps: { x: 'center', y: 'center', r: 100, strokeWidth : 5, strokeColor: '#996699', fillColor: 'rgba(0,0,0,.5)', }, addTextOps : { // text:'<b>A</b>BBBBB<s>MCanvas.js</s>', text: '<b>Large/Stroke</b><br>Normal/Gradient<br><s>Small/Shadow</s>', options: { width: '600', align: 'center', largeStyle: { color: 'red', font: '90px Microsoft YaHei,sans-serif', type: 'stroke', lineWidth: 2, lineHeight : 90, }, normalStyle: { color: 'blue', font: '70px Microsoft YaHei,sans-serif', lineHeight : 70, // shadow:{ // color: 'red', // blur: 4, // offsetX: 2, // offsetY: 2, // }, gradient: { type: 2, // 1: 横向渐变; 2: 纵向渐变; colorStop: ['red', 'blue'], }, }, smallStyle: { color: 'yellow', font: '50px Microsoft YaHei,sans-serif', lineHeight : 50, shadow: { color: 'red', blur: 10, offsetX: 5, offsetY: 5, }, }, pos: { x: 'center', y: 'bottom', rotate: 0, }, }, }, crop: { x: 'center', y: 'center', width: 300, height: 300, radius: 150, } } let mc = new MCanvas({ width: 1000, height: 1500, // backgroundColor: 'black', }) mc.background('http://mtapplet.meitudata.com/596c72073971d86b5128.jpg', { // mc.background('http://mtapplet.meitudata.com/59e8765b6492c541.jpg',{ type: 'origin', left: '50%', top: '50%', }) const mi = new MImage('http://mtapplet.meitudata.com/596c72073971d86b5128.jpg') let timer $('.Button').on('touchstart', function(this: any) { $(this).addClass('taped') timer = setTimeout(() => { $(this).removeClass('taped') }, 2000) }) $('.Button').on('touchend', function(this: any) { $(this).removeClass('taped') clearTimeout(timer) }) $cancel.on('click', () => { $dialog.hide() }) $clear.on('click', () => { // mc.clear(); mc.background().clear().draw(b64 => { $result.attr('src', b64) }) }) $('.js-addImage').on('click', () => { showDialog(`image`, data.addImageOps) }) $('.js-addWm').on('click', () => { showDialog(`watermark`, data.addWmOps) }) $('.js-addText').on('click', () => { showDialog(`text`, data.addTextOps) }) $('.js-addRect').on('click', () => { mcDraw(data.addRectOps, 'rect') }) $('.js-addCircle').on('click', () => { mcDraw(data.addCircleOps, 'circle') }) $sure.on('click', function(this: any) { let ops = $(this).data('ops') let type = $(this).data('type') mcDraw(ops, type) }) function mcDraw(ops, type) { let img switch (type) { case `image`: img = new Image() img.crossOrigin = '*' img.onload = async () => { const b64 = await mc.add(img, ops.options).draw({ type: 'jpg', quality: .9, }) $result.attr('src', b64) $dialog.hide() } img.src = ops.image break case `watermark`: mc.watermark(ops.image, ops.options).draw(b64 => { $result.attr('src', b64) $dialog.hide() }) break case `text`: mc.text(ops.text, ops.options).draw(b64 => { $result.attr('src', b64) $dialog.hide() }) break case `rect`: mc.rect(ops).draw(b64 => { $result.attr('src', b64) $dialog.hide() }) break case `circle`: mc.circle(ops).draw(b64 => { $result.attr('src', b64) $dialog.hide() }) break case `crop`: mi.crop(ops).draw({ type: 'png', success(b64) { $('.js-cropResult').css('background-image', `url(${b64})`) $dialog.hide() } }) break default: } } function showDialog(type, ops) { let tab = `&nbsp;&nbsp;&nbsp;&nbsp;` let html switch (type) { case 'image': html = `<li>options: {</li> <li>${tab + tab}width:<input data-type='width' class='js-input input' type='text' value='${ops.options.width}'></li> <li>${tab + tab}pos: {</li> <li>${tab + tab + tab + tab}x:<input data-type='x' class='js-input input' type='text' value='${ops.options.pos.x}'></li> <li>${tab + tab + tab + tab}y:<input data-type='y' class='js-input input' type='text' value='${ops.options.pos.y}'></li> <li>${tab + tab + tab + tab}scale:<input data-type='scale' class='js-input input' type='text' value='${ops.options.pos.scale}'></li> <li>${tab + tab + tab + tab}rotate:<input data-type='rotate' class='js-input input' type='text' value='${ops.options.pos.rotate}'></li> <li>${tab + tab}}</li> <li>}</li>` break case 'watermark': html = `<li>options: {</li> <li>${tab + tab}width:<input data-type='width' class='js-input input' type='text' value='${ops.options.width}'></li> <li>${tab + tab}pos: <select data-type='pos' class='js-select select'> <option>rightBottom</option> <option>rightTop</option> <option>leftBottom</option> <option>leftTop</option> </select> <li>}</li>` break case 'text': html = `<li>text: <span style="font-size:12px;">''&lt;b&gt;Large/Stroke&lt;/b&gt;Normal/Gradient&lt;s&gt;Small/Shadow&lt;/s&gt;''</span></li> <li>options:{</li> <li>${tab + tab}width:<input data-type='width' class='js-input input' type='text' value='${ops.options.width}'></li> <li>${tab + tab}align: <select data-type='align' class='js-select select'> <option>left</option> <option>center</option> <option>right</option> </select> </li> <li>${tab + tab}pos:{ <li>${tab + tab + tab + tab}x:<input data-type='x' class='js-input input' type='text' value='${ops.options.pos.x}'></li> <li>${tab + tab + tab + tab}y:<input data-type='y' class='js-input input' type='text' value='${ops.options.pos.y}'></li> <li>${tab + tab}}</li> <li>}</li>` break case 'crop': html = `<li>options: {</li> <li>${tab + tab}width: <input data-class="crop" data-type='width' class='js-input input' type='text' value='${ops.width}'></li> <li>${tab + tab}height: <input data-class="crop" data-type='height' class='js-input input' type='text' value='${ops.height}'></li> <li>${tab + tab}x:<input data-class="crop" data-type='x' class='js-input input' type='text' value='${ops.x}'></li> <li>${tab + tab}y:<input data-class="crop" data-type='y' class='js-input input' type='text' value='${ops.y}'></li> <li>${tab + tab}radius:<input data-class="crop" data-type='radius' class='js-input input' type='text' value='${ops.radius}'></li> <li>}</li>` break default: } $params.html(html) $sure.data('ops', JSON.stringify(ops)).data('type', type) $dialog.show() } $(window).on('input', '.js-input', function(this: any) { let $this = $(this) let v = $this.val() let type = $this.data('type') let ops = $sure.data('ops') const cls = $this.data('class') if (cls === 'crop') { switch (type) { case 'width': ops.width = v break case 'height': ops.height = v break case 'x': ops.x = v break case 'y': ops.y = v break case 'radius': ops.radius = v break default: break } } else { switch (type) { case 'width': ops.options.width = v break case 'x': ops.options.pos.x = v break case 'y': ops.options.pos.y = v break case 'scale': ops.options.pos.scale = v break case 'rotate': ops.options.pos.rotate = v break case 'align': ops.options.align = v break default: } } $sure.data('ops', JSON.stringify(ops)) }) $(window).on('focus', '.js-input', function(this: any) { $(this).addClass('focus') }) $(window).on('blur', '.js-input', function(this: any) { $(this).removeClass('focus') }) $(window).on('change', '.js-select', function(this: any) { let ops = $sure.data('ops') let type = $(this).data('type') ops.options[type] = $(this).val() $sure.data('ops', JSON.stringify(ops)) }) $('.js-cropImage').on('click', () => { showDialog(`crop`, data.crop) }) $('.js-filter').on('click', function(this: any) { const $btn = $(this) const $par = $btn.parent() const type = $btn.data('type') mi.filter(type).draw(b64 => { $par.css('background-image', `url(${b64})`) }) })
the_stack
import { Injector } from '@opensumi/di'; import { RPCProtocol, ProxyIdentifier } from '@opensumi/ide-connection'; import { Emitter, Deferred, IExtensionProps, Uri, IReporterService, ReporterService, REPORT_HOST, IReporter, REPORT_NAME, } from '@opensumi/ide-core-common'; import { IExtensionWorkerHost, EXTENSION_EXTEND_SERVICE_PREFIX } from '../common'; import { ActivatedExtension, ActivatedExtensionJSON } from '../common/activator'; import { MainThreadAPIIdentifier, ExtHostAPIIdentifier, ExtensionIdentifier, SumiWorkerExtensionService, } from '../common/vscode'; import { ExtensionContext } from './api/vscode/ext.host.extensions'; import { ExtHostSecret } from './api/vscode/ext.host.secrets'; import { ExtHostStorage } from './api/vscode/ext.host.storage'; import { createAPIFactory } from './api/worker/worker.host.api.impl'; import { ExtensionLogger } from './extension-log'; import { KTWorkerExtension } from './vscode.extension'; export function initRPCProtocol() { const onMessageEmitter = new Emitter<string>(); const channel = new MessageChannel(); self.postMessage(channel.port2, [channel.port2]); channel.port1.onmessage = (e) => { onMessageEmitter.fire(e.data); }; const onMessage = onMessageEmitter.event; const extProtocol = new RPCProtocol({ onMessage, send: (data) => { channel.port1.postMessage(data); }, }); return extProtocol; } export class ExtensionWorkerHost implements IExtensionWorkerHost { private extensions: IExtensionProps[]; private sumiAPIFactory: any; private sumiExtAPIImpl: Map<string, any> = new Map(); public logger: ExtensionLogger; private initDeferred = new Deferred(); private activatedExtensions: Map<string, ActivatedExtension> = new Map<string, ActivatedExtension>(); private mainThreadExtensionService: SumiWorkerExtensionService; readonly extensionsChangeEmitter: Emitter<void> = new Emitter<void>(); public staticServicePath: string; public storage: ExtHostStorage; public secret: ExtHostSecret; private reporterService: IReporterService; constructor(private rpcProtocol: RPCProtocol, private injector: Injector) { const reporter = this.injector.get(IReporter); this.sumiAPIFactory = createAPIFactory(this.rpcProtocol, this, 'worker'); this.mainThreadExtensionService = this.rpcProtocol.getProxy<SumiWorkerExtensionService>( MainThreadAPIIdentifier.MainThreadExtensionService, ); this.logger = new ExtensionLogger(rpcProtocol); this.storage = new ExtHostStorage(rpcProtocol); this.secret = new ExtHostSecret(rpcProtocol); rpcProtocol.set(ExtHostAPIIdentifier.ExtHostStorage, this.storage); this.reporterService = new ReporterService(reporter, { host: REPORT_HOST.EXTENSION, }); } async $getActivatedExtensions(): Promise<ActivatedExtensionJSON[]> { return Array.from(this.activatedExtensions.values()).map((e) => e.toJSON()); } private async init() { this.staticServicePath = await this.mainThreadExtensionService.$getStaticServicePath(); } getExtensionExports(id: string) { return this.activatedExtensions.get(id)?.exports; } getExtensions(): KTWorkerExtension[] { return this.extensions.map( (ext) => new KTWorkerExtension(ext, this, this.mainThreadExtensionService, this.getExtensionExports(ext.id)), ); } createExtension(extensionDescription: IExtensionProps) { const activated = this.activatedExtensions.get(extensionDescription.id); return new KTWorkerExtension(extensionDescription, this, this.mainThreadExtensionService, activated?.exports); } getExtension(extensionId: string) { const extension = this.extensions.find((e) => e.id === extensionId); if (extension) { return this.createExtension(extension); } } isActivated(id: string): boolean { return this.activatedExtensions.has(id); } static workerApiNamespace: string[] = [ 'sumi', 'sumi-browser', // @deprecated 'kaitian', // @deprecated 'kaitian-worker', 'vscode', ]; public async $updateExtHostData() { await this.init(); const extensions = await this.mainThreadExtensionService.$getExtensions(); this.extensions = extensions.map((ext) => ({ ...ext, identifier: new ExtensionIdentifier(ext.id), extensionLocation: Uri.from(ext.extensionLocation), })); this.logger.verbose( 'worker $handleExtHostCreated', this.extensions.map((extension) => extension.packageJSON.name), ); this.extendExtHostErrorStackTrace(); this.initDeferred.resolve(undefined); } private _extHostErrorStackTraceExtended = false; private extendExtHostErrorStackTrace() { if (this._extHostErrorStackTraceExtended) { return; } this._extHostErrorStackTraceExtended = true; Error.stackTraceLimit = 100; Error.prepareStackTrace = (error: Error, stackTrace: any[]) => { let extension: IExtensionProps | undefined; let stackTraceMessage = ''; for (const call of stackTrace) { stackTraceMessage += `\n\tat ${call.toString()}`; if (call.isEval() && !extension) { const scriptPath = call.getEvalOrigin(); const maybeExtension = this.findExtensionFormScriptPath(scriptPath); if (maybeExtension) { extension = maybeExtension; const columnNumber = call.getColumnNumber(); const lineNumber = call.getLineNumber(); stackTraceMessage = `\n\tat ${extension.name} (${extension.workerScriptPath}:${lineNumber}:${columnNumber})` + stackTraceMessage; } } } if (extension) { const traceMessage = `${extension && extension.name} - ${error.name || 'Error'}: ${ error.message || '' }${stackTraceMessage}`; this.reportRuntimeError(error, extension, traceMessage); return traceMessage; } return error.stack; }; } private reportRuntimeError(err: Error, extension: IExtensionProps, stackTraceMessage: string): void { if (err && err.message) { this.reporterService.point(REPORT_NAME.RUNTIME_ERROR_EXTENSION, extension.id, { stackTraceMessage, error: err.message, version: extension.packageJSON?.version, }); } } private findExtensionFormScriptPath(scriptPath: string) { return this.extensions.find((extension) => extension.workerScriptPath === scriptPath); } private getExtendModuleProxy(extension: IExtensionProps) { /** * @example * "kaitianContributes": { * "viewsProxies": ["ViewComponentID"], * } */ if (extension.packageJSON.kaitianContributes && extension.packageJSON.kaitianContributes.viewsProxies) { return this.getExtensionViewModuleProxy(extension, extension.packageJSON.kaitianContributes.viewsProxies); } else if (extension.extendConfig && extension.extendConfig.browser && extension.extendConfig.browser.componentId) { return this.getExtensionViewModuleProxy(extension, extension.extendConfig.browser.componentId); } else { return {}; } } private getExtensionViewModuleProxy(extension: IExtensionProps, viewsProxies: string[]) { return viewsProxies.reduce((proxies, viewId) => { proxies[viewId] = this.rpcProtocol.getProxy({ serviceId: `${EXTENSION_EXTEND_SERVICE_PREFIX}:${extension.id}:${viewId}`, } as ProxyIdentifier<any>); proxies[viewId] = new Proxy(proxies[viewId], { get: (obj, prop) => { if (typeof prop === 'symbol') { return obj[prop]; } return obj[`$${prop}`]; }, }); return proxies; }, {}); } private registerExtendModuleService(exportsData, extension: IExtensionProps) { const service = {}; for (const key in exportsData) { if (exportsData.hasOwnProperty(key)) { if (typeof exportsData[key] === 'function') { service[`$${key}`] = exportsData[key]; } } } this.rpcProtocol.set( { serviceId: `${EXTENSION_EXTEND_SERVICE_PREFIX}:${extension.id}` } as ProxyIdentifier<any>, service, ); } private async loadContext(extensionDescription: IExtensionProps) { const componentProxy = this.getExtendModuleProxy(extensionDescription); const registerExtendFn = (exportsData) => this.registerExtendModuleService(exportsData, extensionDescription); const context = new ExtensionContext({ extensionDescription, createExtension: this.createExtension.bind(this), extensionId: extensionDescription.id, extendProxy: componentProxy, registerExtendModuleService: registerExtendFn, extensionPath: extensionDescription.realPath, storageProxy: this.storage, secretProxy: this.secret, extensionLocation: extensionDescription.extensionLocation, }); return Promise.all([context.globalState.whenReady, context.workspaceState.whenReady]).then(() => Object.freeze(context), ); } public async $activateExtension(id: string) { await this.initDeferred.promise; return this.activateExtension(id); } public async activateExtension(id: string) { const extension = this.extensions.find((extension) => extension.id === id); if (!extension) { this.logger.error(`[Worker-Host] extension worker not found ${id} `); return; } this.logger.verbose(`[Worker-Host] extension worker start activate ${id} ${extension.workerScriptPath}`); if (extension.workerScriptPath) { const response = await fetch(decodeURIComponent(extension.workerScriptPath)); if (response.status !== 200) { this.logger.error(response.statusText); return; } // https://developer.mozilla.org/en-US/docs/Tools/Debugger/How_to/Debug_eval_sources const initFn = new Function( 'module', 'exports', 'require', 'window', (await response.text()) + `\n//# sourceURL=${extension.workerScriptPath}`, ); const _exports = {}; const _module = { exports: _exports }; const _require = (request: string) => { if (ExtensionWorkerHost.workerApiNamespace.includes(request)) { let sumiAPIImpl = this.sumiExtAPIImpl.get(id); if (!sumiAPIImpl) { try { sumiAPIImpl = this.sumiAPIFactory(extension); this.sumiExtAPIImpl.set(id, sumiAPIImpl); } catch (e) { this.logger.error('[Worker-Host] worker error'); this.logger.error(e); } } return sumiAPIImpl; } }; try { initFn(_module, _exports, _require, self); } catch (err) { this.logger.error(`[Worker-Host] failed to initialize extension ${extension.id} \n`, err); } let extensionActivateFailed; let moduleExports; if (_module.exports && (_module.exports as any).activate) { const workerExtContext = await this.loadContext(extension); try { moduleExports = await (_module.exports as any).activate(Object.freeze(workerExtContext)); } catch (err) { extensionActivateFailed = err; this.logger.error(`[Worker-Host] failed to activate extension ${extension.id} \n\n ${err.message}`); } const activatedExtension = new ActivatedExtension( id, extension.packageJSON.displayName || extension.name, extension.packageJSON.description || '', 'worker', !!extensionActivateFailed, extensionActivateFailed, _module.exports, moduleExports, workerExtContext.subscriptions, undefined, undefined, undefined, ); this.activatedExtensions.set(id, activatedExtension); } } else { this.logger.error('[Worker-Host] extension worker activate error', extension); } } }
the_stack
import {Mutable, Class, AnyTiming, Timing} from "@swim/util"; import {Affinity, FastenerOwner, Property} from "@swim/component"; import {AnyLength, Length} from "@swim/math"; import type {Color} from "@swim/style"; import {Look, Mood, MoodVector, ThemeMatrix, ThemeAnimator} from "@swim/theme"; import {ViewContextType, ViewContext, View, ViewRefFactory, ViewRef} from "@swim/view"; import {HtmlView} from "@swim/dom"; import {SvgIconView} from "@swim/graphics"; import {DeckSlot} from "./DeckSlot"; import type {DeckButtonObserver} from "./DeckButtonObserver"; /** @public */ export class DeckButton extends DeckSlot { constructor(node: HTMLElement) { super(node); this.labelCount = 0; this.label = null; this.initButton(); } protected initButton(): void { this.addClass("deck-button"); this.position.setState("relative", Affinity.Intrinsic); this.userSelect.setState("none", Affinity.Intrinsic); this.cursor.setState("pointer", Affinity.Intrinsic); } override readonly observerType?: Class<DeckButtonObserver>; @Property({type: Length, value: Length.px(12)}) readonly iconPadding!: Property<this, Length, AnyLength>; @ThemeAnimator({type: Number, inherits: true, updateFlags: View.NeedsLayout}) readonly deckPhase!: ThemeAnimator<this, number | undefined>; @ThemeAnimator({type: Number, value: 0}) readonly slotAlign!: ThemeAnimator<this, number>; override get colorLook(): Look<Color> { return Look.accentColor; } /** @internal */ readonly closeIcon!: DeckButtonCloseIcon<this, SvgIconView>; // defined by DeckButtonCloseIcon /** @internal */ readonly backIcon!: DeckButtonBackIcon<this, SvgIconView>; // defined by DeckButtonBackIcon /** @internal */ labelCount: number; /** @internal */ label: DeckButtonLabel<this, HtmlView> | null; protected createLabel(value: string): HtmlView { const labelView = HtmlView.fromTag("span"); labelView.display.setState("flex", Affinity.Intrinsic); labelView.alignItems.setState("center", Affinity.Intrinsic); labelView.whiteSpace.setState("nowrap", Affinity.Intrinsic); labelView.text(value); return labelView; } pushLabel(newLabelView: HtmlView | string, timing?: AnyTiming | boolean): void { if (typeof newLabelView === "string") { newLabelView = this.createLabel(newLabelView); } const oldLabelCount = this.labelCount; const newLabelCount = oldLabelCount + 1; this.labelCount = newLabelCount; const oldLabelKey = "label" + oldLabelCount; const oldLabelRef = this.getFastener(oldLabelKey, ViewRef) as DeckButtonLabel<this, HtmlView> | null; const oldLabelView = oldLabelRef !== null ? oldLabelRef.view : null; const newLabelKey = "label" + newLabelCount; const newLabelRef = DeckButtonLabelRef.create(this) as DeckButtonLabel<this, HtmlView>; Object.defineProperty(newLabelRef, "name", { value: newLabelKey, configurable: true, }) newLabelRef.labelIndex = newLabelCount; this.willPushLabel(newLabelView, oldLabelView); this.label = newLabelRef; this.setFastener(newLabelKey, newLabelRef); newLabelRef.setView(newLabelView); newLabelRef.insertView(); if (timing === void 0 && oldLabelCount === 0) { timing = false; } else if (timing === void 0 || timing === true) { timing = this.getLookOr(Look.timing, Mood.navigating, false); } else { timing = Timing.fromAny(timing); } //if (this.deckPhase.superFastener === null) { // this.deckPhase.setState(newLabelCount, timing); //} if (timing === false) { this.didPushLabel(newLabelView, oldLabelView); } } protected willPushLabel(newLabelView: HtmlView, oldLabelView: HtmlView | null): void { this.forEachObserver(function (observer: DeckButtonObserver): void { if (observer.deckButtonWillPushLabel !== void 0) { observer.deckButtonWillPushLabel(newLabelView, oldLabelView, this); } }); } protected didPushLabel(newLabelView: HtmlView, oldLabelView: HtmlView | null): void { if (oldLabelView !== null && oldLabelView.parent === this) { oldLabelView.remove(); } this.forEachObserver(function (observer: DeckButtonObserver): void { if (observer.deckButtonDidPushLabel !== void 0) { observer.deckButtonDidPushLabel(newLabelView, oldLabelView, this); } }); } popLabel(timing?: AnyTiming | boolean): HtmlView | null { const oldLabelCount = this.labelCount; const newLabelCount = oldLabelCount - 1; this.labelCount = newLabelCount; const oldLabelKey = "label" + oldLabelCount; const oldLabelRef = this.getFastener(oldLabelKey, ViewRef) as DeckButtonLabel<this, HtmlView> | null; const oldLabelView = oldLabelRef !== null ? oldLabelRef.view : null; if (oldLabelView !== null) { const newLabelKey = "label" + newLabelCount; const newLabelRef = this.getFastener(newLabelKey, ViewRef) as DeckButtonLabel<this, HtmlView> | null; const newLabelView = newLabelRef !== null ? newLabelRef.view : null; this.willPopLabel(newLabelView, oldLabelView); this.label = newLabelRef; if (newLabelRef !== null) { newLabelRef.insertView(); } if (timing === void 0 || timing === true) { timing = this.getLookOr(Look.timing, Mood.navigating, false); } else { timing = Timing.fromAny(timing); } //if (this.deckPhase.superFastener === null) { // this.deckPhase.setState(newLabelCount, timing); //} if (timing === false) { this.didPopLabel(newLabelView, oldLabelView); } } return oldLabelView; } protected willPopLabel(newLabelView: HtmlView | null, oldLabelView: HtmlView): void { this.forEachObserver(function (observer: DeckButtonObserver): void { if (observer.deckButtonWillPopLabel !== void 0) { observer.deckButtonWillPopLabel(newLabelView, oldLabelView, this); } }); } protected didPopLabel(newLabelView: HtmlView | null, oldLabelView: HtmlView): void { const oldLabelKey = oldLabelView.key; oldLabelView.remove(); if (oldLabelKey !== void 0) { const oldLabelRef = this.getFastener(oldLabelKey, ViewRef) as DeckButtonLabel<this, HtmlView> | null; if (oldLabelRef !== null && oldLabelRef.labelIndex > this.labelCount) { this.setFastener(oldLabelKey, null); } } this.forEachObserver(function (observer: DeckButtonObserver): void { if (observer.deckButtonDidPopLabel !== void 0) { observer.deckButtonDidPopLabel(newLabelView, oldLabelView, this); } }); } protected override didLayout(viewContext: ViewContextType<this>): void { if (!this.deckPhase.tweening) { const deckPhase = this.deckPhase.value; if (deckPhase !== void 0) { const nextLabelIndex = Math.round(deckPhase + 1); const nextLabelKey = "label" + nextLabelIndex; const nextLabelRef = this.getFastener(nextLabelKey, ViewRef) as DeckButtonLabel<this, HtmlView> | null; const nextLabelView = nextLabelRef !== null ? nextLabelRef.view : null; if (nextLabelView !== null) { this.didPopLabel(this.label !== null ? this.label.view : null, nextLabelView); } else if (this.label !== null && this.label.view !== null && Math.round(deckPhase) > 0) { const prevLabelIndex = Math.round(deckPhase - 1); const prevLabelKey = "label" + prevLabelIndex; const prevLabelRef = this.getFastener(prevLabelKey, ViewRef) as DeckButtonLabel<this, HtmlView> | null; const prevLabelView = prevLabelRef !== null ? prevLabelRef.view : null; this.didPushLabel(this.label.view, prevLabelView); } } } super.didLayout(viewContext); } } /** @internal */ export interface DeckButtonCloseIcon<O extends DeckButton = DeckButton, V extends SvgIconView = SvgIconView> extends ViewRef<O, V> { /** @override */ didAttachView(iconView: V): void; /** @override */ insertChild(parent: View, child: V, target: View | number | null, key: string | undefined): void; viewDidLayout(viewContext: ViewContext, iconView: V): void; /** @protected */ initIcon(iconView: V): void; /** @protected */ layoutIcon(iconView: V): void; } /** @internal */ export const DeckButtonCloseIcon = (function (_super: typeof ViewRef) { const DeckButtonCloseIcon = _super.extend("DeckButtonCloseIcon") as ViewRefFactory<DeckButtonCloseIcon<any, any>>; DeckButtonCloseIcon.prototype.didAttachView = function (this: DeckButtonCloseIcon, iconView: SvgIconView): void { this.initIcon(iconView); }; DeckButtonCloseIcon.prototype.insertChild = function (this: DeckButtonCloseIcon, parent: View, child: SvgIconView, target: View | number | null, key: string | undefined): void { parent.prependChild(child, key); }; DeckButtonCloseIcon.prototype.viewDidLayout = function (this: DeckButtonCloseIcon, viewContext: ViewContext, iconView: SvgIconView): void { this.layoutIcon(iconView); }; DeckButtonCloseIcon.prototype.initIcon = function (this: DeckButtonCloseIcon, iconView: SvgIconView): void { iconView.addClass("close-icon"); iconView.setStyle("position", "absolute"); iconView.pointerEvents.setState("none", Affinity.Intrinsic); }; DeckButtonCloseIcon.prototype.layoutIcon = function (this: DeckButtonCloseIcon, iconView: SvgIconView): void { const slotAlign = this.owner.slotAlign.getValue(); let slotWidth: Length | number | null = this.owner.width.state; slotWidth = slotWidth instanceof Length ? slotWidth.pxValue() : this.owner.node.offsetWidth; let slotHeight: Length | number | null = this.owner.height.state; slotHeight = slotHeight instanceof Length ? slotHeight.pxValue() : this.owner.node.offsetHeight; const iconPadding = this.owner.iconPadding.getValue().pxValue(slotWidth); let iconWidth: Length | number | null = iconView.width.state; iconWidth = iconWidth instanceof Length ? iconWidth.pxValue() : 0; let iconHeight: Length | number | null = iconView.height.state; iconHeight = iconHeight instanceof Length ? iconHeight.pxValue() : 0; const deckPhase = this.owner.deckPhase.getValueOr(0); const iconPhase = Math.min(Math.max(0, deckPhase - 1), 1); const slotSpace = slotWidth - iconWidth - iconPadding; const iconLeft = iconPadding + slotSpace * slotAlign; const iconTop = (slotHeight - iconHeight) / 2; iconView.setStyle("left", iconLeft + "px"); iconView.setStyle("top", iconTop + "px"); iconView.viewBox.setState("0 0 " + iconWidth + " " + iconHeight, Affinity.Intrinsic); iconView.opacity.setState(1 - iconPhase, Affinity.Intrinsic); }; return DeckButtonCloseIcon; })(ViewRef); ViewRef({ extends: DeckButtonCloseIcon, key: true, type: SvgIconView, observes: true, })(DeckButton.prototype, "closeIcon"); /** @internal */ export interface DeckButtonBackIcon<O extends DeckButton = DeckButton, V extends SvgIconView = SvgIconView> extends ViewRef<O, V> { /** @override */ didAttachView(iconView: V): void; /** @override */ insertChild(parent: View, child: V, target: View | number | null, key: string | undefined): void; viewDidLayout(viewContext: ViewContext, iconView: V): void; /** @protected */ initIcon(iconView: V): void; /** @protected */ layoutIcon(iconView: V): void; } /** @internal */ export const DeckButtonBackIcon = (function (_super: typeof ViewRef) { const DeckButtonBackIcon = _super.extend("DeckButtonBackIcon") as ViewRefFactory<DeckButtonBackIcon<any, any>>; DeckButtonBackIcon.prototype.didAttachView = function (this: DeckButtonBackIcon, iconView: SvgIconView): void { this.initIcon(iconView); }; DeckButtonBackIcon.prototype.insertChild = function (this: DeckButtonBackIcon, parent: View, child: SvgIconView, target: View | number | null, key: string | undefined): void { parent.prependChild(child, key); }; DeckButtonBackIcon.prototype.viewDidLayout = function (this: DeckButtonBackIcon, viewContext: ViewContext, iconView: SvgIconView): void { this.layoutIcon(iconView); }; DeckButtonBackIcon.prototype.initIcon = function (this: DeckButtonBackIcon, iconView: SvgIconView): void { iconView.addClass("back-icon"); iconView.setStyle("position", "absolute"); iconView.pointerEvents.setState("none", Affinity.Intrinsic); }; DeckButtonBackIcon.prototype.layoutIcon = function (this: DeckButtonBackIcon, iconView: SvgIconView): void { const slotAlign = this.owner.slotAlign.getValue(); let slotWidth: Length | number | null = this.owner.width.state; slotWidth = slotWidth instanceof Length ? slotWidth.pxValue() : this.owner.node.offsetWidth; let slotHeight: Length | number | null = this.owner.height.state; slotHeight = slotHeight instanceof Length ? slotHeight.pxValue() : this.owner.node.offsetHeight; const iconPadding = this.owner.iconPadding.getValue().pxValue(slotWidth); let iconWidth: Length | number | null = iconView.width.state; iconWidth = iconWidth instanceof Length ? iconWidth.pxValue() : 0; let iconHeight: Length | number | null = iconView.height.state; iconHeight = iconHeight instanceof Length ? iconHeight.pxValue() : 0; const deckPhase = this.owner.deckPhase.getValueOr(0); const nextIndex = Math.max(this.owner.labelCount, Math.ceil(deckPhase)); const labelKey = "label" + nextIndex; const labelView = this.owner.getChild(labelKey) as HtmlView | null; const slotSpace = slotWidth - iconWidth - iconPadding; let iconLeft = iconPadding + slotSpace * slotAlign; const iconTop = (slotHeight - iconHeight) / 2; let iconOpacity: number | undefined; if (deckPhase <= 1) { iconOpacity = 0; iconView.iconColor.setState(null, Affinity.Intrinsic); } else if (labelView !== null && deckPhase < 2) { const parent = this.owner.parent; const nextPost = this.owner.nextPost.value; const nextSlot = parent !== null && nextPost !== null ? parent.getChild(nextPost.key) : null; let nextSlotAlign: number; let nextSlotWidth: Length | number | null; if (nextSlot instanceof DeckSlot) { nextSlotAlign = nextSlot.slotAlign.value; nextSlotWidth = nextSlot.width.state; nextSlotWidth = nextSlotWidth instanceof Length ? nextSlotWidth.pxValue() : nextSlot.node.offsetWidth; let nextSlotLeft: Length | number | null = nextSlot.left.state; nextSlotLeft = nextSlotLeft instanceof Length ? nextSlotLeft.pxValue() : nextSlot.node.offsetLeft; let slotLeft: Length | number | null = this.owner.left.state; slotLeft = slotLeft instanceof Length ? slotLeft.pxValue() : this.owner.node.offsetLeft; const slotGap = nextSlotLeft - (slotLeft + slotWidth); nextSlotWidth += slotGap; } else { nextSlotAlign = 0; nextSlotWidth = 0; } const prevIndex = nextIndex - 1; const labelPhase = deckPhase - prevIndex; let labelWidth: Length | number | null = labelView.width.state; if (labelWidth instanceof Length) { labelWidth = labelWidth.pxValue(slotWidth); } else { labelWidth = labelView.node.offsetWidth; } const labelSlotSpace = slotWidth - iconLeft - iconWidth + (nextSlotWidth - labelWidth) * nextSlotAlign; iconLeft += (labelSlotSpace * (1 - labelPhase) + labelSlotSpace * slotAlign * labelPhase); iconOpacity = labelPhase; const nextColor = nextSlot instanceof DeckSlot ? nextSlot.getLookOr(nextSlot.colorLook, null) : null; const thisColor = this.owner.getLookOr(this.owner.colorLook, null); if (nextColor !== null && thisColor !== null) { iconView.iconColor.setState(nextColor.interpolateTo(thisColor)(labelPhase), Affinity.Intrinsic); } else { iconView.iconColor.setState(thisColor, Affinity.Intrinsic); } } iconView.setStyle("left", iconLeft + "px"); iconView.setStyle("top", iconTop + "px"); iconView.viewBox.setState("0 0 " + iconWidth + " " + iconHeight, Affinity.Intrinsic); iconView.opacity.setState(iconOpacity, Affinity.Intrinsic); }; return DeckButtonBackIcon; })(ViewRef); ViewRef({ extends: DeckButtonBackIcon, key: true, type: SvgIconView, observes: true, })(DeckButton.prototype, "backIcon"); /** @internal */ export interface DeckButtonLabel<O extends DeckButton = DeckButton, V extends HtmlView = HtmlView> extends ViewRef<O, V> { labelIndex: number; /** @internal */ labelWidth: Length | string | null; /** @internal */ layoutWidth: number; /** @override */ didAttachView(labelView: V): void; /** @override */ insertChild(parent: View, child: V, target: View | number | null, key: string | undefined): void; /** @protected */ viewDidApplyTheme(theme: ThemeMatrix, mood: MoodVector, timing: Timing | boolean, labelView: V): void; viewDidLayout(viewContext: ViewContext, labelView: V): void; /** @protected */ initLabel(labelView: V): void; /** @protected */ layoutLabel(labelView: V): void; } /** @internal */ export const DeckButtonLabel = (function (_super: typeof ViewRef) { const DeckButtonLabel = _super.extend("DeckButtonLabel") as ViewRefFactory<DeckButtonLabel<any, any>>; DeckButtonLabel.prototype.didAttachView = function (this: DeckButtonLabel, labelView: HtmlView): void { this.initLabel(labelView); }; DeckButtonLabel.prototype.insertChild = function (this: DeckButtonLabel, parent: View, child: HtmlView, target: View | number | null, key: string | undefined): void { const targetKey = "label" + (this.labelIndex + 1); target = parent.getChild(targetKey); parent.insertChild(child, target, key); }; DeckButtonLabel.prototype.viewDidApplyTheme = function (this: DeckButtonLabel, theme: ThemeMatrix, mood: MoodVector, timing: Timing | boolean, labelView: HtmlView): void { if (labelView.color.hasAffinity(Affinity.Intrinsic)) { labelView.color.setState(theme.getOr(this.owner.colorLook, mood, null), timing, Affinity.Intrinsic); } }; DeckButtonLabel.prototype.viewDidLayout = function (this: DeckButtonLabel, viewContext: ViewContext, labelView: HtmlView): void { this.layoutLabel(labelView); }; DeckButtonLabel.prototype.initLabel = function (this: DeckButtonLabel, labelView: HtmlView): void { labelView.position.setState("absolute", Affinity.Intrinsic); labelView.pointerEvents.setState("none", Affinity.Intrinsic); }; DeckButtonLabel.prototype.layoutLabel = function (this: DeckButtonLabel, labelView: HtmlView): void { const labelIndex = this.labelIndex; const slotAlign = this.owner.slotAlign.getValue(); let slotWidth: Length | number | null = this.owner.width.state; slotWidth = slotWidth instanceof Length ? slotWidth.pxValue() : this.owner.node.offsetWidth; let slotHeight: Length | number | null = this.owner.height.state; slotHeight = slotHeight instanceof Length ? slotHeight.pxValue() : this.owner.node.offsetHeight; const parent = this.owner.parent; const nextPost = this.owner.nextPost.value; const nextSlot = parent !== null && nextPost !== null ? parent.getChild(nextPost.key) : null; let nextSlotAlign: number; let nextSlotWidth: Length | number | null; if (nextSlot instanceof DeckSlot) { nextSlotAlign = nextSlot.slotAlign.value; nextSlotWidth = nextSlot.width.state; nextSlotWidth = nextSlotWidth instanceof Length ? nextSlotWidth.pxValue() : nextSlot.node.offsetWidth; let nextSlotLeft: Length | number | null = nextSlot.left.state; nextSlotLeft = nextSlotLeft instanceof Length ? nextSlotLeft.pxValue() : nextSlot.node.offsetLeft; let slotLeft: Length | number | null = this.owner.left.state; slotLeft = slotLeft instanceof Length ? slotLeft.pxValue() : this.owner.node.offsetLeft; const slotGap = nextSlotLeft - (slotLeft + slotWidth); nextSlotWidth += slotGap; } else { nextSlotAlign = 0; nextSlotWidth = 0; } const iconPadding = this.owner.iconPadding.getValue().pxValue(slotWidth); let iconWidth: Length | number | null; let iconHeight: Length | number | null; const iconView = this.owner.backIcon.view; if (iconView !== null) { iconWidth = iconView.width.state; iconWidth = iconWidth instanceof Length ? iconWidth.pxValue() : 0; iconHeight = iconView.height.state; iconHeight = iconHeight instanceof Length ? iconHeight.pxValue() : 0; } else { iconWidth = 0; iconHeight = 0; } const deckPhase = this.owner.deckPhase.getValueOr(0); const nextIndex = Math.max(this.owner.labelCount, Math.ceil(deckPhase)); const prevIndex = nextIndex - 1; const labelPhase = deckPhase - prevIndex; let labelWidth: Length | number | null = labelView.width.state; this.labelWidth = labelWidth; if (labelWidth instanceof Length) { labelWidth = labelWidth.pxValue(slotWidth); } else { labelWidth = labelView.node.offsetWidth; // Memoize computed label width while animating // to avoid style recalculation in animation frames. if (this.owner.deckPhase.tweening) { labelView.width.setState(labelWidth, Affinity.Intrinsic); } else { labelView.width.setState(this.labelWidth, Affinity.Intrinsic); } } const slotSpace = slotWidth - iconWidth - iconPadding; const iconLeft = iconPadding + slotSpace * slotAlign; const iconTop = (slotHeight - iconHeight) / 2; const labelSlotSpace = slotWidth - iconLeft - iconWidth + (nextSlotWidth - labelWidth) * nextSlotAlign; if (labelIndex < prevIndex || labelIndex === prevIndex && labelPhase === 1) { // under labelView.left.setState(iconLeft + iconWidth, Affinity.Intrinsic); labelView.top.setState(iconTop, Affinity.Intrinsic); labelView.height.setState(iconHeight, Affinity.Intrinsic); labelView.opacity.setState(0, Affinity.Intrinsic); labelView.setCulled(true); } else if (labelIndex === prevIndex) { // out labelView.left.setState(iconLeft + iconWidth + (labelSlotSpace * slotAlign * (1 - labelPhase)), Affinity.Intrinsic); labelView.top.setState(iconTop, Affinity.Intrinsic); labelView.height.setState(iconHeight, Affinity.Intrinsic); labelView.opacity.setState(1 - labelPhase, Affinity.Intrinsic); labelView.setCulled(false); } else if (labelIndex === nextIndex) { // in labelView.left.setState(iconLeft + iconWidth + (labelSlotSpace * (1 - labelPhase) + labelSlotSpace * slotAlign * labelPhase), Affinity.Intrinsic); labelView.top.setState(iconTop, Affinity.Intrinsic); labelView.height.setState(iconHeight, Affinity.Intrinsic); const nextColor = nextSlot instanceof DeckSlot ? nextSlot.getLookOr(nextSlot.colorLook, null) : null; const thisColor = this.owner.getLookOr(this.owner.colorLook, null); if (nextColor !== null && thisColor !== null) { labelView.color.setState(nextColor.interpolateTo(thisColor)(labelPhase), Affinity.Intrinsic); } else { labelView.color.setState(thisColor, Affinity.Intrinsic); } labelView.opacity.setState(1, Affinity.Intrinsic); labelView.setCulled(false); } else { // over labelView.left.setState(iconLeft + iconWidth + labelSlotSpace, Affinity.Intrinsic); labelView.top.setState(iconTop, Affinity.Intrinsic); labelView.height.setState(iconHeight, Affinity.Intrinsic); labelView.opacity.setState(0, Affinity.Intrinsic); labelView.setCulled(true); } this.layoutWidth = iconLeft + iconWidth + labelWidth + iconPadding; }; DeckButtonLabel.construct = function <F extends DeckButtonLabel<any, any>>(fastenerClass: {prototype: F}, fastener: F | null, owner: FastenerOwner<F>): F { fastener = _super.construct(fastenerClass, fastener, owner) as F; (fastener as Mutable<typeof fastener>).labelIndex = 0; (fastener as Mutable<typeof fastener>).labelWidth = null; (fastener as Mutable<typeof fastener>).layoutWidth = 0; return fastener; }; return DeckButtonLabel; })(ViewRef); /** @internal */ export const DeckButtonLabelRef = ViewRef.define<DeckButton, HtmlView>("DeckButtonLabelRef", { extends: DeckButtonLabel, key: true, type: HtmlView, observes: true, });
the_stack
import AWS = require('aws-sdk'); import { TypeShape, Value } from '@punchcard/shape'; import { Compact } from 'typelevel-ts'; import { DSL } from './dsl'; import { Condition } from './filter'; import { Mapper } from './mapper'; import { Update } from './update'; import { Writer } from './writer'; export interface BaseClientProps<T extends TypeShape, K extends DDB.KeyOf<T>> { /** * Record typr of the table's properties. */ data: T; /** * Key of the Table. */ key: K; /** * DynamoDB Table Name. */ tableName: string; /** * Name of the DynamoDB Index. * * @default - no index */ indexName?: string; /** * Configured AWS DynamoDB Client. * * @default - one using the default environment configuration is created for you. */ client?: AWS.DynamoDB; } export class BaseClient<T extends TypeShape<any>, K extends DDB.KeyOf<T>> { public readonly client: AWS.DynamoDB; public readonly mapper: Mapper<T>; public readonly tableName: string; public readonly indexName?: string; public readonly hashKeyMapper: Mapper<DDB.HashKeyShape<T, K>>; public readonly sortKeyMapper: Mapper<DDB.SortKeyShape<T, K>>; public readonly readKey: (key: AWS.DynamoDB.Key) => DDB.KeyValue<T, K>; public readonly writeKey: (key: DDB.KeyValue<T, K>) => any; protected readonly dsl: DSL.Root<T>; public readonly type: T; public readonly key: K; constructor(config: BaseClientProps<T, K>) { this.type = config.data; this.key = config.key; this.dsl = DSL.of(this.type); this.client = config.client || new AWS.DynamoDB(); this.tableName = config.tableName; this.indexName = config.indexName; this.mapper = Mapper.of(this.type); if (typeof this.key.sort === 'undefined') { const hashKeyMapper = Mapper.of(this.type.Members[this.key.partition]); this.writeKey = (k: any) => ({ [this.key.partition]: hashKeyMapper.write(k[this.key.partition]) }); this.readKey = (k: any) => ({ [this.key.partition]: hashKeyMapper.read(k[this.key.partition]) }) as any; } else { const hk = this.key.partition; const sk = this.key.sort; const hashKeyMapper = Mapper.of(this.type.Members[hk]); const sortKeyMapper = Mapper.of(this.type.Members[sk]); this.writeKey = (k: any) => ({ [hk]: hashKeyMapper.write(k[hk]), [sk]: sortKeyMapper.write(k[sk]) }); this.readKey = (k: any) => ({ [hk]: hashKeyMapper.read(k[hk]), [sk]: sortKeyMapper.read(k[sk]) }) as any; } } // TODO: Support paging, etc. public async scan(): Promise<Value.Of<T>[]> { const request: AWS.DynamoDB.ScanInput = { TableName: this.tableName, }; if (this.indexName) { request.IndexName = this.indexName; } const result = await this.client.scan(request).promise(); if (result.Items) { return result.Items.map(item => this.mapper.read({ M: item } as any)); } else { return []; } } public async query(condition: DDB.QueryCondition<T, K>, props: DDB.QueryProps<T, K> = {}): Promise<DDB.QueryOutput<T, K>> { const namespace = new Writer.Namespace(); const queryWriter = new Writer(namespace); let filterExpr; if (props.filter) { const filterWriter = new Writer(namespace); props.filter(this.dsl)[DSL.Synthesize](filterWriter); filterExpr = filterWriter.toExpression(); } let queryCondition = (this.dsl as any)[this.key.partition].equals(condition[this.key.partition]); if ((condition as any)[this.key.sort] !== undefined) { queryCondition = queryCondition.and((condition as any)[this.key.sort]((this.dsl as any)[this.key.sort])); } queryCondition[DSL.Synthesize](queryWriter); const queryExpr = queryWriter.toExpression(); const req: AWS.DynamoDB.QueryInput = { TableName: this.tableName, KeyConditionExpression: queryExpr.Expression, FilterExpression: filterExpr?.Expression, ExpressionAttributeNames: queryExpr?.ExpressionAttributeNames, ExpressionAttributeValues: queryExpr?.ExpressionAttributeValues, ExclusiveStartKey: props.ExclusiveStartKey === undefined ? undefined : this.writeKey(props.ExclusiveStartKey), ScanIndexForward: props.ScanIndexForward }; if (req.ScanIndexForward === undefined) { delete req.ScanIndexForward; } if (req.FilterExpression === undefined) { delete req.FilterExpression; } if (req.ExclusiveStartKey === undefined) { delete req.ExclusiveStartKey; } if (this.indexName) { req.IndexName = this.indexName; } if (!req.ExpressionAttributeNames) { delete req.ExpressionAttributeNames; } if (!req.ExpressionAttributeValues) { delete req.ExpressionAttributeValues; } const result = await this.client.query(req).promise(); return { ...result, Items: result.Items?.map(v => this.mapper.read({M : v} as any)), LastEvaluatedKey: result.LastEvaluatedKey === undefined ? undefined : this.readKey(result.LastEvaluatedKey) as any }; } } export interface TableClientProps<T extends TypeShape, K extends DDB.KeyOf<T>> extends Omit<BaseClientProps<T, K>, 'indexName'> {} export class TableClient<T extends TypeShape, K extends DDB.KeyOf<T>> extends BaseClient<T, K> { constructor(config: TableClientProps<T, K>) { super(config); } public async get(key: DDB.KeyValue<T, K>): Promise<Value.Of<T> | undefined> { const req: AWS.DynamoDB.GetItemInput = { TableName: this.tableName, Key: this.writeKey(key) }; const result = await this.client.getItem(req).promise(); if (result.Item !== undefined) { return this.mapper.read({M: result.Item} as any); } else { return undefined; } } // TODO: retry behavior/more options/etc. public async batchGet(keys: DDB.KeyValue<T, K>[]): Promise<Value.Of<T>[]> { const result = await this.client.batchGetItem({ RequestItems: { [this.tableName]: { Keys: keys.map(key => this.writeKey(key)), } } }).promise(); if (result.Responses) { const items = result.Responses[this.tableName]; if (items) { return items.map(item => this.mapper.read({ M: item.Item } as any)); } } throw new Error('TODO'); } public async put(item: Value.Of<T>, props: { if?: DDB.Condition<T>; } = {}) { if (props.if) { const expr = Condition.compile(props.if(this.dsl)); return await this.client.putItem({ TableName: this.tableName, Item: (this.mapper.write(item) as any).M, ConditionExpression: expr.Expression, ExpressionAttributeNames: expr.ExpressionAttributeNames, ExpressionAttributeValues: expr.ExpressionAttributeValues }).promise(); } else { return await this.client.putItem({ TableName: this.tableName, Item: (this.mapper.write(item) as any).M, }).promise(); } } /** * Put a batch of records * * @param batch * @returns failed PutRequests */ public async batchPut(batch: Value.Of<T>[]): Promise<AWS.DynamoDB.WriteRequest[]> { try { const result = await this.client.batchWriteItem({ RequestItems: { [this.tableName]: batch.map(record => { return { PutRequest: { Item: (this.mapper.write(record) as any).M } }; }) } }).promise(); if (!result.UnprocessedItems) { return []; } else { return result.UnprocessedItems[this.tableName]; } } catch (error) { console.error('putBatch error', error); throw error; } } public async update(key: DDB.KeyValue<T, K>, props: DDB.Update<T>) { const writer = new Writer(); const req: AWS.DynamoDB.UpdateItemInput = { TableName: this.tableName, Key: this.writeKey(key), ...(Update.compile(props.actions(this.dsl), writer)), }; if (props.if) { const expr = Condition.compile(props.if(this.dsl), new Writer(writer.namespace)); req.ConditionExpression = expr.Expression; req.ExpressionAttributeNames = expr.ExpressionAttributeNames; req.ExpressionAttributeValues = expr.ExpressionAttributeValues; if (!req.ExpressionAttributeNames) { delete req.ExpressionAttributeNames; } if (!req.ExpressionAttributeValues) { delete req.ExpressionAttributeValues; } } const response = await this.client.updateItem(req).promise(); return response; } } export interface IndexClientProps<T extends TypeShape<any>, K extends DDB.KeyOf<T>> extends TableClientProps<T, K> { /** * Name of the DynamoDB Index. * Required for the IndexClient. */ indexName: string; } /** * Client to Query and Scan a DynamoDB Index. */ export class IndexClient<T extends TypeShape, K extends DDB.KeyOf<T>> extends BaseClient<T, K> { constructor(config: IndexClientProps<T, K>) { super(config); } } export namespace DDB { type _QueryOutput<T extends TypeShape<any>, K extends KeyOf<T>> = Compact< Omit<AWS.DynamoDB.QueryOutput, 'Items' | 'LastEvaulatedKey'> & { Items?: Value.Of<T>[]; LastEvaluatedKey?: KeyValue<T, K> }>; export interface QueryOutput<T extends TypeShape<any>, K extends KeyOf<T>> extends _QueryOutput<T, K> {} export type HashKey<T> = keyof T; export type SortKey<T> = [keyof T, keyof T]; export interface KeyOf<T extends TypeShape> { partition: keyof T['Members']; sort?: keyof T['Members'] | undefined; } export type KeyNames<T extends TypeShape<any>, K extends KeyOf<T>> = K extends { partition: infer PK, sort?: undefined } ? PK : K extends { partition: infer PK, sort: infer SK } ? PK | SK : never; export type KeyValue<T extends TypeShape<any>, K extends KeyOf<T>> = { [k in KeyNames<T, K>]: Value.Of<T['Members'][k]>; }; export type HashKeyName<K> = K extends { partition: infer H; } ? H : never; export type HashKeyValue<T extends TypeShape<any>, K extends KeyOf<T>> = Value.Of<HashKeyShape<T, K>>; export type HashKeyShape<T extends TypeShape<any>, K extends KeyOf<T>> = T['Members'][HashKeyName<K>]; export type SortKeyName<K> = K extends { sort?: infer S; } ? S : undefined; export type SortKeyValue<T extends TypeShape<any>, K extends KeyOf<T>> = Value.Of<SortKeyShape<T, K>>; export type SortKeyShape<T extends TypeShape<any>, K extends KeyOf<T>> = T['Members'][SortKeyName<K>]; export type QueryCondition<T extends TypeShape<any>, K extends KeyOf<T>> = SortKeyName<K> extends undefined ? { [k in HashKeyName<K>]: HashKeyValue<T, K>; } : { [k in HashKeyName<K>]: HashKeyValue<T, K>; } & { [k in SortKeyName<K>]?: (i: DSL.Of<SortKeyShape<T, K>>) => DSL.Bool } ; export interface QueryProps<T extends TypeShape<any>, K extends KeyOf<T>> { filter?: DDB.Condition<T>; Limit?: number; ExclusiveStartKey?: DDB.KeyValue<T, K>; ContinuationToken?: string; ScanIndexForward?: boolean; } export type Condition<T extends TypeShape<any>> = (item: DSL.Root<T>) => DSL.Bool; export interface Update<T extends TypeShape<any>> { actions: (item: DSL.Root<T>) => DSL.Action[]; if?: DDB.Condition<T>; } }
the_stack
import * as React from 'react'; import * as strings from 'ControlStrings'; import styles from './RichTextPropertyPane.module.scss'; import RteColorPicker from './RteColorPicker'; import { IRichTextPropertyPaneProps, IRichTextPropertyPaneState } from './RichTextPropertyPane.types'; import { IconButton } from 'office-ui-fabric-react/lib/Button'; import { Panel, PanelType } from 'office-ui-fabric-react/lib/Panel'; import { TooltipHost } from 'office-ui-fabric-react/lib/Tooltip'; import { Dropdown, IDropdownOption } from 'office-ui-fabric-react/lib/Dropdown'; import { ThemeColorHelper } from '../../common/utilities/ThemeColorHelper'; export default class RichTextPropertyPane extends React.Component<IRichTextPropertyPaneProps, IRichTextPropertyPaneState> { constructor(props: IRichTextPropertyPaneProps) { super(props); this.state = { formats: {} }; } /** * componentDidUpdate lifecycle hook * * @param prevProps * @param prevState */ public componentDidUpdate(prevProps: IRichTextPropertyPaneProps, prevState: IRichTextPropertyPaneState): void { // if we're just opening, sync the format choices with the current selection if (!prevProps.isOpen && this.props.isOpen) { const quill = this.props.editor; if (quill === undefined) { return; } const range = quill.getSelection(); this.onChangeSelection(range, undefined, undefined); } } /** * Default React render method */ public render(): React.ReactElement<IRichTextPropertyPaneProps> { return ( <Panel className={styles.richTextPropertyPane} isBlocking={false} isOpen={this.props.isOpen} type={PanelType.smallFixedFar} onDismiss={this.props.onClose} closeButtonAriaLabel={strings.CloseButton} onRenderNavigation={this.handleRenderNavigation} focusTrapZoneProps={{ forceFocusInsideTrap: false, isClickableOutsideFocusTrap: true }}> <div> <div> <div> <div className={styles.propertyPaneGroupContent}> {this.renderActionsGroup()} {this.renderFontStylesGroup()} {this.renderFontSizesGroup()} {this.renderInlineStylesGroup()} {this.renderColorStylesGroup()} </div> </div> <div className={styles.propertyPaneGroupContent}> <div className={styles.propertyPaneGroupHeaderNoAccordion}>{strings.ParagraphSectionTitle}</div> {this.renderAlignmentStylesGroup()} {this.renderListStylesGroup()} </div> <div className={styles.propertyPaneGroupContent}> <div className={styles.propertyPaneGroupHeaderNoAccordion}>{strings.HyperlinkSectionTitle}</div> {this.renderHyperlinkStylesGroup()} </div> </div> </div> </Panel> ); } /** * On selection changed event handler */ public onChangeSelection = (range, oldRange?, source?) => { const quill = this.props.editor; if (quill === undefined || range === undefined) { return; } if (range) { const formats = quill.getFormat(range); this.setState({ formats }); } } /** * Render the actions group */ private renderActionsGroup = (): JSX.Element => { return ( <div className={styles.propertyPaneGroupField}> <div className="ms-CustomFieldHost"> <div className={styles.controlsInOneRow}> <TooltipHost content={strings.UndoTitle} id="undo-propertyPaneButton" calloutProps={{ gapSpace: 0 }}> <IconButton onClick={this.handleUndo} className={styles.propertyPaneButton} aria-describedby="undo-propertyPaneButton" iconProps={{ iconName: 'Undo', style: { fontSize: '20px' } }} /> </TooltipHost> <TooltipHost content={strings.RedoTitle} id="redo-propertyPaneButton" calloutProps={{ gapSpace: 0 }}> <IconButton onClick={this.handleRedo} className={styles.propertyPaneButton} aria-describedby="redo-propertyPaneButton" iconProps={{ iconName: 'Redo', style: { fontSize: '20px' } }} /> </TooltipHost> <TooltipHost content={strings.ClearFormattingTitle} id="clearFormatting-button-propertyPaneButton" calloutProps={{ gapSpace: 0 }}> <IconButton onClick={this.handleClearFormatting} className={styles.propertyPaneButton} aria-describedby="clearFormatting-button-propertyPaneButton" iconProps={{ iconName: 'ClearFormatting', style: { fontSize: '20px' } }} /> </TooltipHost> </div> </div> </div> ); } /** * Render font styles group */ private renderFontStylesGroup = (): JSX.Element => { const selectedHeader = this.state.formats!.header ? this.state.formats!.header : 0; return ( <div className={styles.propertyPaneGroupField}> <Dropdown label={strings.FontStyleTitle} ariaLabel={strings.FontStyleTitle} selectedKey={selectedHeader} options={[ { key: 0, text: strings.HeaderNormalText }, { key: 2, text: strings.HeaderH2 }, { key: 3, text: strings.HeaderH3 }, { key: 4, text: strings.HeaderH4 }, { key: 7, text: strings.HeaderBlockQuote } ]} onChanged={this.onChangeHeading} /> </div> ); } /** * Render font size group */ private renderFontSizesGroup = (): JSX.Element => { // get the selected header const selectedSize = this.state.formats!.size ? this.state.formats!.size : 'large'; return ( <div className={styles.propertyPaneGroupField}> <Dropdown label={strings.FontSizeTitle} ariaLabel={strings.FontSizeTitle} selectedKey={selectedSize} options={[ { key: 'small', text: '12' }, { key: 'medium', text: '14' }, { key: 'mediumplus', text: '15' }, { key: 'large', text: '17' }, { key: 'xlarge', text: '21' }, { key: 'xlargeplus', text: '24' }, { key: 'xxlarge', text: '28' }, { key: 'xxxlarge', text: '32' }, { key: 'xxlargeplus', text: '36' }, { key: 'super', text: '42' }, ]} onChanged={this.onChangeSize} /> </div> ); } /** * Render inline styles group */ private renderInlineStylesGroup = (): JSX.Element => { return ( <div className={styles.propertyPaneGroupField}> <div className="ms-CustomFieldHost"> <div className={styles.controlsInOneRow}> <TooltipHost content={strings.BoldTitle} id="bold-propertyPaneButton" calloutProps={{ gapSpace: 0 }}> <IconButton checked={this.state.formats!.bold} onClick={() => this.applyFormat('bold', !this.state.formats!.bold)} className={styles.propertyPaneButton} aria-describedby="bold-propertyPaneButton" iconProps={{ iconName: 'Bold', style: { fontSize: '20px' } }} /> </TooltipHost> <TooltipHost content={strings.ItalicTitle} id="italic-propertyPaneButton" calloutProps={{ gapSpace: 0 }}> <IconButton checked={this.state.formats!.italic} onClick={() => this.applyFormat('italic', !this.state.formats!.italic)} className={styles.propertyPaneButton} aria-describedby="italic-propertyPaneButton" iconProps={{ iconName: 'Italic', style: { fontSize: '20px' } }} /> </TooltipHost> <TooltipHost content={strings.UnderlineTitle} id="underline-propertyPaneButton" calloutProps={{ gapSpace: 0 }}> <IconButton checked={this.state.formats!.underline} onClick={() => this.applyFormat('underline', !this.state.formats!.underline)} className={styles.propertyPaneButton} aria-describedby="underline-propertyPaneButton" iconProps={{ iconName: 'Underline', style: { fontSize: '20px' } }} /> </TooltipHost> <TooltipHost content={strings.StrikethroughTitle} id="strikethrough-propertyPaneButton" calloutProps={{ gapSpace: 0 }}> <IconButton checked={this.state.formats!.strike} onClick={() => this.applyFormat('strike', !this.state.formats!.strike)} className={styles.propertyPaneButton} aria-describedby="strikethrough-propertyPaneButton" iconProps={{ iconName: 'Strikethrough', style: { fontSize: '20px' } }} /> </TooltipHost> <TooltipHost content={strings.SuperscriptTitle} id="superscript-propertyPaneButton" calloutProps={{ gapSpace: 0 }}> <IconButton checked={this.state.formats!.script === 'super'} onClick={() => this.applyFormat('script', this.state.formats!.script === 'super' ? '' : 'super')} className={styles.propertyPaneButton} aria-describedby="superscript-propertyPaneButton" iconProps={{ iconName: 'Superscript', style: { fontSize: '20px' } }} /> </TooltipHost> <TooltipHost content={strings.SubscriptTitle} id="subscript-propertyPaneButton" calloutProps={{ gapSpace: 0 }}> <IconButton checked={this.state.formats!.script === 'sub'} onClick={() => this.applyFormat('script', this.state.formats!.script === 'sub' ? '' : 'sub')} className={styles.propertyPaneButton} aria-describedby="subscript-propertyPaneButton" iconProps={{ iconName: 'Subscript', style: { fontSize: '20px' } }} /> </TooltipHost> </div> </div> </div> ); } /** * Render color styles group */ private renderColorStylesGroup = (): JSX.Element => { const color: string = this.state.formats.color || ThemeColorHelper.GetThemeColor(styles.NeutralPrimary); const backgroundColor: string = this.state.formats.background || "rgba(0, 0, 0, 0)"; /** * Add custom colors if passed as a property */ let fontColorGroups = ["themeColors","standardColors"]; if(this.props.customColors) fontColorGroups.push('customColors'); return ( <div className={styles.propertyPaneGroupField}> <div className="ms-CustomFieldHost"> <div className={styles.controlsInOneRow}> <RteColorPicker colorPickerGroups={fontColorGroups} // changed to variable customColors={this.props.customColors} buttonLabel={strings.FontColorLabel} id="fontColor-propertyPaneButton" defaultButtonLabel={strings.AutomaticFontColor} fillThemeColor={true} previewColor={color} selectedColor={color} onColorChanged={this.handleFillColorChanged} switchToDefaultColor={() => this.handleFillColorChanged(undefined)} /> <RteColorPicker buttonLabel={strings.HighlightColorLabel} colorPickerGroups={[ "highlightColors" ]} fillThemeColor={false} onColorChanged={this.handleHighlightColorChanged} switchToDefaultColor={() => this.handleHighlightColorChanged(undefined)} previewColor={backgroundColor} defaultButtonLabel={strings.NoColorHighlightColor} selectedColor={backgroundColor} id="highlightColor-propertyPaneButton" /> </div> </div> </div> ); } /** * Render alignment style groups */ private renderAlignmentStylesGroup = (): JSX.Element => { return ( <div className={styles.propertyPaneGroupField}> <div className="ms-CustomFieldHost"> <div className={styles.controlsInOneRow}> <TooltipHost content={strings.AlignLeft} id="left-propertyPaneButton" calloutProps={{ gapSpace: 0 }}> <IconButton checked={this.state.formats!.align === undefined} onClick={() => this.applyFormat('align', undefined)} className={styles.propertyPaneButton} aria-describedby="left-propertyPaneButton" iconProps={{ iconName: 'AlignLeft', style: { fontSize: '20px' } }} /> </TooltipHost> <TooltipHost content={strings.AlignCenter} id="center-propertyPaneButton" calloutProps={{ gapSpace: 0 }}> <IconButton checked={this.state.formats!.align === 'center'} onClick={() => this.applyFormat('align', 'center')} className={styles.propertyPaneButton} aria-describedby="center-propertyPaneButton" iconProps={{ iconName: 'AlignCenter', style: { fontSize: '20px' } }} /> </TooltipHost> <TooltipHost content={strings.AlignRight} id="right-propertyPaneButton" calloutProps={{ gapSpace: 0 }}> <IconButton checked={this.state.formats!.align === 'right'} onClick={() => this.applyFormat('align', 'right')} className={styles.propertyPaneButton} aria-describedby="right-propertyPaneButton" iconProps={{ iconName: 'AlignRight', style: { fontSize: '20px' } }} /> </TooltipHost> <TooltipHost content={strings.AlignJustify} id="justify-propertyPaneButton" calloutProps={{ gapSpace: 0 }}> <IconButton checked={this.state.formats!.align === 'justify'} onClick={() => this.applyFormat('align', 'justify')} className={styles.propertyPaneButton} aria-describedby="justify-propertyPaneButton" iconProps={{ iconName: 'AlignJustify', style: { fontSize: '20px' } }} /> </TooltipHost> <TooltipHost content={strings.IncreaseIndentTitle} id="increaseindent-propertyPaneButton" calloutProps={{ gapSpace: 0 }}> <IconButton onClick={() => this.onChangeIndent(1)} className={styles.propertyPaneButton} aria-describedby="increaseindent-propertyPaneButton" iconProps={{ iconName: 'IncreaseIndentLegacy', style: { fontSize: '20px' } }} /> </TooltipHost> <TooltipHost content={strings.DecreaseIndentTitle} id="decreaseindent-propertyPaneButton" calloutProps={{ gapSpace: 0 }}> <IconButton onClick={() => this.onChangeIndent(-1)} className={styles.propertyPaneButton} aria-describedby="decreaseindent-propertyPaneButton" iconProps={{ iconName: 'DecreaseIndentLegacy', style: { fontSize: '20px' } }} /> </TooltipHost> </div> </div> </div> ); } /** * Render list styles group */ private renderListStylesGroup = (): JSX.Element => { return <div className={styles.propertyPaneGroupField}> <div className="ms-CustomFieldHost"> <div className={styles.controlsInOneRow}> <TooltipHost content={strings.ListBullet} id="bullet-propertyPaneButton" calloutProps={{ gapSpace: 0 }}> <IconButton checked={this.state.formats!.list === 'bullet'} onClick={() => this.applyFormat('list', 'bullet')} className={styles.propertyPaneButton} aria-describedby="bullet-propertyPaneButton" iconProps={{ iconName: 'BulletedList', style: { fontSize: '20px' } }} /> </TooltipHost> <TooltipHost content={strings.ListNumbered} id="ordered-propertyPaneButton" calloutProps={{ gapSpace: 0 }}> <IconButton checked={this.state.formats!.list === 'ordered'} onClick={() => this.applyFormat('list', 'ordered')} className={styles.propertyPaneButton} aria-describedby="ordered-propertyPaneButton" iconProps={{ iconName: 'NumberedList', style: { fontSize: '20px' } }} /> </TooltipHost> </div> </div> </div>; } /** * Render hyperlink styles group */ private renderHyperlinkStylesGroup = (): JSX.Element => { return ( <div className={styles.propertyPaneGroupField}> <div className="ms-CustomFieldHost"> <div className={styles.controlsInOneRow}> <TooltipHost content={strings.LinkTitle} id="link-propertyPaneButton" calloutProps={{ gapSpace: 0 }}> <IconButton checked={this.state.formats!.link !== undefined} onClick={() => this.props.onLink()} className={styles.propertyPaneButton} aria-describedby="link-propertyPaneButton" iconProps={{ iconName: 'Link', style: { fontSize: '20px' } }} /> </TooltipHost> <TooltipHost content={strings.RemoveLinkLabel} id="unlink-propertyPaneButton" calloutProps={{ gapSpace: 0 }}> <IconButton disabled={this.state.formats!.link === undefined} onClick={() => this.applyFormat('link', false)} className={styles.propertyPaneButton} aria-describedby="unlink-propertyPaneButton" iconProps={{ iconName: 'RemoveLink', style: { fontSize: '20px' } }} /> </TooltipHost> </div> </div> </div> ); } /** * Handle fill color change */ private handleFillColorChanged = (color: string) => { this.applyFormat('color', color); } /** * Handle the hightlight color change */ private handleHighlightColorChanged = (color: string) => { this.applyFormat('background', color); } /** * On heading change */ private onChangeHeading = (item: IDropdownOption): void => { const newHeadingValue = item.key === 0 ? '' : item.key.toString(); this.applyFormat("header", newHeadingValue); } /** * On indentation change. */ private onChangeIndent = (direction: 1 | -1) => { const quill = this.props.editor; const current = +(quill.getFormat(quill.getSelection()).indent || 0); this.applyFormat("indent", current + direction); } /** * On size change */ private onChangeSize = (item: IDropdownOption): void => { const newSizeValue = item.key === 0 ? '' : item.key.toString(); this.applyFormat("size", newSizeValue); } /** * Apply the new format * * @param name * @param value */ private applyFormat(name: string, value: any) { const quill = this.props.editor; quill.format(name, value); setTimeout(() => { this.onChangeSelection(quill.getSelection()); }, 100); } /** * Handle the undo action */ private handleUndo = (): void => { const quill = this.props.editor; quill!.getModule("history")!.undo(); setTimeout(() => { this.onChangeSelection(quill.getSelection()); }, 100); } /** * Handle the clear formatting action */ private handleClearFormatting = (): void => { const quill = this.props.editor; var range = quill.getSelection(); if (range) { if (range.length > 0) { quill.removeFormat(range.index, range.length); setTimeout(() => { this.onChangeSelection(quill.getSelection()); }, 100); } } } /** * Handle the redo action */ private handleRedo = (): void => { const quill = this.props.editor; quill!.getModule("history")!.redo(); setTimeout(() => { this.onChangeSelection(quill.getSelection()); }, 100); } /** * Navigation render */ private handleRenderNavigation = (): JSX.Element => { return ( <div className={styles.formattingPaneTitle} aria-hidden="true">{strings.FormattingPaneTitle} <IconButton onClick={() => this.props.onClose()} className={styles.propertyPaneClose} iconProps={{ iconName: 'Cancel' }} title={strings.CloseButton} ariaLabel={strings.CloseButton} /> </div> ); } }
the_stack
import _ from 'lodash'; import { DbDiffOptions, generateTablePairingId } from './diffTools'; import { AlterProcessor, ColumnInfo, ConstraintInfo, DatabaseInfo, SqlObjectInfo, SqlDialect, TableInfo, NamedObjectInfo, } from '../../types'; import { DatabaseInfoAlterProcessor } from './database-info-alter-processor'; import { DatabaseAnalyser } from './DatabaseAnalyser'; interface AlterOperation_CreateTable { operationType: 'createTable'; newObject: TableInfo; } interface AlterOperation_DropTable { operationType: 'dropTable'; oldObject: TableInfo; } interface AlterOperation_CreateSqlObject { operationType: 'createSqlObject'; newObject: SqlObjectInfo; } interface AlterOperation_DropSqlObject { operationType: 'dropSqlObject'; oldObject: SqlObjectInfo; } interface AlterOperation_RenameTable { operationType: 'renameTable'; object: TableInfo; newName: string; } interface AlterOperation_CreateColumn { operationType: 'createColumn'; newObject: ColumnInfo; } interface AlterOperation_ChangeColumn { operationType: 'changeColumn'; oldObject: ColumnInfo; newObject: ColumnInfo; } interface AlterOperation_RenameColumn { operationType: 'renameColumn'; object: ColumnInfo; newName: string; } interface AlterOperation_DropColumn { operationType: 'dropColumn'; oldObject: ColumnInfo; } interface AlterOperation_CreateConstraint { operationType: 'createConstraint'; newObject: ConstraintInfo; } interface AlterOperation_ChangeConstraint { operationType: 'changeConstraint'; oldObject: ConstraintInfo; newObject: ConstraintInfo; } interface AlterOperation_DropConstraint { operationType: 'dropConstraint'; oldObject: ConstraintInfo; } interface AlterOperation_RenameConstraint { operationType: 'renameConstraint'; object: ConstraintInfo; newName: string; } interface AlterOperation_RecreateTable { operationType: 'recreateTable'; table: TableInfo; operations: AlterOperation[]; } interface AlterOperation_FillPreloadedRows { operationType: 'fillPreloadedRows'; table: NamedObjectInfo; oldRows: any[]; newRows: any[]; key: string[]; insertOnly: string[]; } type AlterOperation = | AlterOperation_CreateColumn | AlterOperation_ChangeColumn | AlterOperation_DropColumn | AlterOperation_CreateConstraint | AlterOperation_ChangeConstraint | AlterOperation_DropConstraint | AlterOperation_CreateTable | AlterOperation_DropTable | AlterOperation_RenameTable | AlterOperation_RenameColumn | AlterOperation_RenameConstraint | AlterOperation_CreateSqlObject | AlterOperation_DropSqlObject | AlterOperation_RecreateTable | AlterOperation_FillPreloadedRows; export class AlterPlan { recreates = { tables: 0, constraints: 0, sqlObjects: 0, }; public operations: AlterOperation[] = []; constructor( public wholeOldDb: DatabaseInfo, public wholeNewDb: DatabaseInfo, public dialect: SqlDialect, public opts: DbDiffOptions ) {} createTable(table: TableInfo) { this.operations.push({ operationType: 'createTable', newObject: table, }); } dropTable(table: TableInfo) { this.operations.push({ operationType: 'dropTable', oldObject: table, }); } createSqlObject(obj: SqlObjectInfo) { this.operations.push({ operationType: 'createSqlObject', newObject: obj, }); } dropSqlObject(obj: SqlObjectInfo) { this.operations.push({ operationType: 'dropSqlObject', oldObject: obj, }); } createColumn(column: ColumnInfo) { this.operations.push({ operationType: 'createColumn', newObject: column, }); } changeColumn(oldColumn: ColumnInfo, newColumn: ColumnInfo) { this.operations.push({ operationType: 'changeColumn', oldObject: oldColumn, newObject: newColumn, }); } dropColumn(column: ColumnInfo) { this.operations.push({ operationType: 'dropColumn', oldObject: column, }); } createConstraint(constraint: ConstraintInfo) { this.operations.push({ operationType: 'createConstraint', newObject: constraint, }); } changeConstraint(oldConstraint: ConstraintInfo, newConstraint: ConstraintInfo) { this.operations.push({ operationType: 'changeConstraint', oldObject: oldConstraint, newObject: newConstraint, }); } dropConstraint(constraint: ConstraintInfo) { this.operations.push({ operationType: 'dropConstraint', oldObject: constraint, }); } renameTable(table: TableInfo, newName: string) { this.operations.push({ operationType: 'renameTable', object: table, newName, }); } renameColumn(column: ColumnInfo, newName: string) { this.operations.push({ operationType: 'renameColumn', object: column, newName, }); } renameConstraint(constraint: ConstraintInfo, newName: string) { this.operations.push({ operationType: 'renameConstraint', object: constraint, newName, }); } recreateTable(table: TableInfo, operations: AlterOperation[]) { this.operations.push({ operationType: 'recreateTable', table, operations, }); this.recreates.tables += 1; } fillPreloadedRows(table: NamedObjectInfo, oldRows: any[], newRows: any[], key: string[], insertOnly: string[]) { this.operations.push({ operationType: 'fillPreloadedRows', table, oldRows, newRows, key, insertOnly, }); } run(processor: AlterProcessor) { for (const op of this.operations) { runAlterOperation(op, processor); } } _getDependendColumnConstraints(column: ColumnInfo, dependencyDefinition) { const table = this.wholeOldDb.tables.find(x => x.pureName == column.pureName && x.schemaName == column.schemaName); if (!table) return []; const fks = dependencyDefinition?.includes('dependencies') ? table.dependencies.filter(fk => fk.columns.find(col => col.refColumnName == column.columnName)) : []; const constraints = _.compact([ dependencyDefinition?.includes('primaryKey') ? table.primaryKey : null, ...(dependencyDefinition?.includes('foreignKeys') ? table.foreignKeys : []), ...(dependencyDefinition?.includes('indexes') ? table.indexes : []), ...(dependencyDefinition?.includes('uniques') ? table.uniques : []), ]).filter(cnt => cnt.columns.find(col => col.columnName == column.columnName)); return [...fks, ...constraints]; } _addLogicalDependencies(): AlterOperation[] { const lists = this.operations.map(op => { if (op.operationType == 'dropColumn') { const constraints = this._getDependendColumnConstraints(op.oldObject, this.dialect.dropColumnDependencies); if (constraints.length > 0 && this.opts.noDropConstraint) { return []; } const res: AlterOperation[] = [ ...constraints.map(oldObject => { const opRes: AlterOperation = { operationType: 'dropConstraint', oldObject, }; return opRes; }), op, ]; return res; } if (op.operationType == 'changeColumn') { const constraints = this._getDependendColumnConstraints(op.oldObject, this.dialect.changeColumnDependencies); if (constraints.length > 0 && this.opts.noDropConstraint) { return []; } const res: AlterOperation[] = [ ...constraints.map(oldObject => { const opRes: AlterOperation = { operationType: 'dropConstraint', oldObject, }; return opRes; }), op, ..._.reverse([...constraints]).map(newObject => { const opRes: AlterOperation = { operationType: 'createConstraint', newObject, }; return opRes; }), ]; if (constraints.length > 0) { this.recreates.constraints += 1; } return res; } if (op.operationType == 'dropTable') { return [ ...(this.dialect.dropReferencesWhenDropTable ? (op.oldObject.dependencies || []).map(oldObject => { const opRes: AlterOperation = { operationType: 'dropConstraint', oldObject, }; return opRes; }) : []), op, ]; } if (op.operationType == 'changeConstraint') { if (this.opts.noDropConstraint) { // skip constraint recreate return []; } this.recreates.constraints += 1; const opDrop: AlterOperation = { operationType: 'dropConstraint', oldObject: op.oldObject, }; const opCreate: AlterOperation = { operationType: 'createConstraint', newObject: op.newObject, }; return [opDrop, opCreate]; } return [op]; }); return _.flatten(lists); } _transformToImplementedOps(): AlterOperation[] { const lists = this.operations.map(op => { return ( this._testTableRecreate(op, 'createColumn', this.dialect.createColumn, 'newObject') || this._testTableRecreate(op, 'dropColumn', this.dialect.dropColumn, 'oldObject') || this._testTableRecreate(op, 'createConstraint', obj => this._canCreateConstraint(obj), 'newObject') || this._testTableRecreate(op, 'dropConstraint', obj => this._canDropConstraint(obj), 'oldObject') || this._testTableRecreate(op, 'changeColumn', this.dialect.changeColumn, 'newObject') || [op] ); }); return _.flatten(lists); } _canCreateConstraint(cnt: ConstraintInfo) { if (cnt.constraintType == 'primaryKey') return this.dialect.createPrimaryKey; if (cnt.constraintType == 'foreignKey') return this.dialect.createForeignKey; if (cnt.constraintType == 'index') return this.dialect.createIndex; if (cnt.constraintType == 'unique') return this.dialect.createUnique; if (cnt.constraintType == 'check') return this.dialect.createCheck; return null; } _canDropConstraint(cnt: ConstraintInfo) { if (cnt.constraintType == 'primaryKey') return this.dialect.dropPrimaryKey; if (cnt.constraintType == 'foreignKey') return this.dialect.dropForeignKey; if (cnt.constraintType == 'index') return this.dialect.dropIndex; if (cnt.constraintType == 'unique') return this.dialect.dropUnique; if (cnt.constraintType == 'check') return this.dialect.dropCheck; return null; } _testTableRecreate( op: AlterOperation, operationType: string, isAllowed: boolean | Function, objectField: string ): AlterOperation[] | null { if (op.operationType == operationType) { if (_.isFunction(isAllowed)) { if (isAllowed(op[objectField])) return null; } else { if (isAllowed) return null; } // console.log('*****************RECREATED NEEDED', op, operationType, isAllowed); // console.log(this.dialect); if (this.opts.noDropTable) { // skip this operation, as it cannot be achieved return []; } const table = this.wholeNewDb.tables.find( x => x.pureName == op[objectField].pureName && x.schemaName == op[objectField].schemaName ); this.recreates.tables += 1; return [ { operationType: 'recreateTable', table, operations: [op], }, ]; } return null; } _groupTableRecreations(): AlterOperation[] { const res = []; const recreates = {}; for (const op of this.operations) { if (op.operationType == 'recreateTable' && op.table) { const existingRecreate = recreates[`${op.table.schemaName}||${op.table.pureName}`]; if (existingRecreate) { existingRecreate.operations.push(...op.operations); } else { const recreate = { ...op, operations: [...op.operations], }; res.push(recreate); recreates[`${op.table.schemaName}||${op.table.pureName}`] = recreate; } } else { // @ts-ignore const oldObject: TableInfo = op.oldObject; if (oldObject) { const recreated = recreates[`${oldObject.schemaName}||${oldObject.pureName}`]; if (recreated) { recreated.operations.push(op); continue; } } res.push(op); } } return res; } _moveForeignKeysToLast(): AlterOperation[] { if (!this.dialect.createForeignKey) { return this.operations; } const fks = []; const res = this.operations.map(op => { if (op.operationType == 'createTable') { fks.push(...(op.newObject.foreignKeys || [])); return { ...op, newObject: { ...op.newObject, foreignKeys: [], }, }; } return op; }); return [ ...res, ...fks.map( fk => ({ operationType: 'createConstraint', newObject: fk, } as AlterOperation_CreateConstraint) ), ]; } _filterAllowedOperations(): AlterOperation[] { return this.operations.filter(op => { if (this.opts.noDropColumn && op.operationType == 'dropColumn') return false; if (this.opts.noDropTable && op.operationType == 'dropTable') return false; if (this.opts.noDropTable && op.operationType == 'recreateTable') return false; if (this.opts.noDropConstraint && op.operationType == 'dropConstraint') return false; if (this.opts.noDropSqlObject && op.operationType == 'dropSqlObject') return false; return true; }); } transformPlan() { // console.log('*****************OPERATIONS0', this.operations); this.operations = this._addLogicalDependencies(); // console.log('*****************OPERATIONS1', this.operations); this.operations = this._transformToImplementedOps(); // console.log('*****************OPERATIONS2', this.operations); this.operations = this._groupTableRecreations(); // console.log('*****************OPERATIONS3', this.operations); this.operations = this._moveForeignKeysToLast(); // console.log('*****************OPERATIONS4', this.operations); this.operations = this._filterAllowedOperations(); // console.log('*****************OPERATIONS5', this.operations); } } export function runAlterOperation(op: AlterOperation, processor: AlterProcessor) { switch (op.operationType) { case 'createTable': processor.createTable(op.newObject); break; case 'changeColumn': processor.changeColumn(op.oldObject, op.newObject); break; case 'createColumn': processor.createColumn(op.newObject, []); break; case 'dropColumn': processor.dropColumn(op.oldObject); break; case 'dropTable': processor.dropTable(op.oldObject); break; case 'changeConstraint': processor.changeConstraint(op.oldObject, op.newObject); break; case 'createConstraint': processor.createConstraint(op.newObject); break; case 'dropConstraint': processor.dropConstraint(op.oldObject); break; case 'renameColumn': processor.renameColumn(op.object, op.newName); break; case 'renameTable': processor.renameTable(op.object, op.newName); break; case 'renameConstraint': processor.renameConstraint(op.object, op.newName); break; case 'createSqlObject': processor.createSqlObject(op.newObject); break; case 'dropSqlObject': processor.dropSqlObject(op.oldObject); break; case 'fillPreloadedRows': processor.fillPreloadedRows(op.table, op.oldRows, op.newRows, op.key, op.insertOnly); break; case 'recreateTable': { const oldTable = generateTablePairingId(op.table); const newTable = _.cloneDeep(oldTable); const newDb = DatabaseAnalyser.createEmptyStructure(); newDb.tables.push(newTable); // console.log('////////////////////////////newTable1', newTable); op.operations.forEach(child => runAlterOperation(child, new DatabaseInfoAlterProcessor(newDb))); // console.log('////////////////////////////op.operations', op.operations); // console.log('////////////////////////////op.table', op.table); // console.log('////////////////////////////newTable2', newTable); processor.recreateTable(oldTable, newTable); } break; } }
the_stack
import React, { FC, ReactNode, createContext, useContext, useEffect, useReducer, Reducer, useMemo } from 'react'; import AsyncStorage from '@react-native-community/async-storage'; import i18n, {TFunction} from 'i18next'; import {useTranslation, UseTranslationResponse} from 'react-i18next'; import {TraceConfiguration} from 'react-native-exposure-notification-service'; import * as SecureStore from 'expo-secure-store'; import {Duration} from 'date-fns'; import * as api from '../services/api'; import {requestWithCache} from '../services/api/utils'; import {fallback} from '../services/i18n/common'; import {Platform} from 'react-native'; export interface BasicItem { label: string; value: any; } export const reminderKeys = [ 'exposureReminder', 'caseReminder', 'restrictionEnd' // "restricted movement" after exposure ("isolation" is after diagnosis) ] as const; export type ReminderKey = typeof reminderKeys[number]; type ReminderConfig = Record<ReminderKey, ReminderOption>; export interface AppConfig { checkInMaxAge: number; riskGroupMinAge: number; hsePhoneNumber: string; latestVersion: string | null; dateFormat: string; durations: ReminderConfig; codeLength: number; deepLinkLength: number; } interface AgeOption extends BasicItem { riskGroup?: boolean; } export interface ReminderOption extends Duration { earliest?: string; // 24hr time like '08:00' latest?: string; // 24hr time like '21:00' at?: string; // 24hr time like '12:00'; overrides earliest and latest } // Don't turn these keys into numbers when parsing API settings: const reminderOptionStringKeys = ['earliest', 'latest', 'at']; interface CheckerThankYouText { noSymptomsWell: string; noSymptomsNotWell: string; riskGroup: string; recovered: string; virusIsolation: string; } interface DbTextContextValue { sexOptions: BasicItem[]; ageRangeOptions: AgeOption[]; closeContactInfo: string; closeContactAlert: string; closeContactCallBack: string; closeContactCallbackQueued: string; dpinText: string; tandcText: string; checkerThankYouText: CheckerThankYouText; tutorialVideoID: string | null; } type GetTranslatedTextFn = ( t: TFunction, i18nCurrent: UseTranslationResponse['i18n'] ) => DbTextContextValue; interface SettingsContextValue { loaded: boolean; loadedTime: Date | null; reload: () => void; appConfig: AppConfig; traceConfiguration: TraceConfiguration; user: string | null; consent: string | null; completedExposureOnboarding: string | null; analyticsConsent: string | null; dpinDate: string | null; tandcDate: string | null; getTranslatedDbText: GetTranslatedTextFn; } interface SettingsProviderProps { children: ReactNode; } type ApiSettings = Record<string, any>; type DeepSettings = { [key: string]: string | DeepSettings; }; const defaultDbText: DbTextContextValue = { sexOptions: [], ageRangeOptions: [], closeContactInfo: '', closeContactAlert: '', closeContactCallBack: '', closeContactCallbackQueued: '', dpinText: '', tandcText: '', checkerThankYouText: {} as DbTextContextValue['checkerThankYouText'], tutorialVideoID: null }; const daytime = {earliest: '08:00', latest: '21:00'}; const defaultSettings: SettingsContextValue = { loaded: false, loadedTime: null, reload: () => {}, user: null, consent: null, analyticsConsent: null, completedExposureOnboarding: null, appConfig: { checkInMaxAge: 28, riskGroupMinAge: 60, hsePhoneNumber: 'XXXX-XXXXXX', latestVersion: null, dateFormat: 'do LLL yyyy', durations: { restrictionEnd: {days: 14, at: '18:00'}, exposureReminder: {days: 2, ...daytime}, caseReminder: {days: 2, ...daytime} }, codeLength: 6, // digits, deepLinkLength: 16 }, traceConfiguration: { exposureCheckInterval: 180, storeExposuresFor: 14 }, dpinDate: null, tandcDate: null, getTranslatedDbText: () => defaultDbText }; const parseReminderOption = (obj: Record<keyof ReminderOption, string>) => Object.entries(obj).reduce( (items, [key, value]) => ({ ...items, [key]: reminderOptionStringKeys.includes(key) ? value : Number(value) }), {} as ReminderOption ); const getDbText = ( apiSettings: ApiSettings, key: string, acceptFallbackLanguage = false ): string | DeepSettings => { const data = (apiSettings[key] && (apiSettings[key]![i18n.language] || (acceptFallbackLanguage && apiSettings[key][fallback]))) || ''; return getCleanedText(data); }; const getCleanedText = (data: string | DeepSettings): string | DeepSettings => { if (typeof data === 'string') { return data.replace(/\\n/g, '\n').replace(/(^|[^\n])\n(?!\n)/g, '$1\n\n'); } else { return Object.entries(data).reduce( (textObj, [key, value]) => ({ ...textObj, [key]: getCleanedText(value) }), {} as DeepSettings ); } }; export const SettingsContext = createContext<SettingsContextValue>( defaultSettings ); export const DbTextContext = createContext<DbTextContextValue>(defaultDbText); interface SettingsReducerAction { type: 'set' | 'loaded' | 'reload'; state?: SettingsContextValue; loaded?: boolean; } const settingsReducer: Reducer<SettingsContextValue, SettingsReducerAction> = ( oldState, {type, state, loaded} ) => { switch (type) { case 'set': return state || ({} as SettingsContextValue); case 'loaded': return {...oldState, loaded} as SettingsContextValue; case 'reload': // Quietly reload settings from API in the background return {...oldState, loadedTime: null} as SettingsContextValue; } }; export const SettingsProvider: FC<SettingsProviderProps> = ({children}) => { const {t, i18n: i18nCurrent} = useTranslation(); const [state, dispatchState] = useReducer(settingsReducer, defaultSettings); useEffect(() => { const loadSettingsAsync = async () => { const [ user, consent, completedExposureOnboarding, analyticsConsent ] = await AsyncStorage.multiGet([ 'cti.user', 'cti.checkInConsent', 'cti.completedExposureOnboarding', 'analyticsConsent' ]); const analyticsConsentSecure = await SecureStore.getItemAsync( 'analyticsConsent' ); const {data} = await requestWithCache('cti.settings', api.loadSettings); const apiSettings: ApiSettings = data ?? {}; const appConfig: AppConfig = {...defaultSettings.appConfig}; if (apiSettings.checkInMaxAge) { appConfig.checkInMaxAge = Number(apiSettings.checkInMaxAge); } if (apiSettings.riskGroupMinAge) { appConfig.riskGroupMinAge = Number(apiSettings.riskGroupMinAge); } if (apiSettings.hsePhoneNumber) { appConfig.hsePhoneNumber = apiSettings.hsePhoneNumber; } if (apiSettings.latestAppVersion) { appConfig.latestVersion = apiSettings.latestAppVersion; } if (apiSettings.latestVersion) { appConfig.latestVersion = apiSettings.latestVersion[Platform.OS]; } if (apiSettings.dateFormat) { appConfig.dateFormat = apiSettings.dateFormat; } if (apiSettings.durations?.restrictionEnd) { appConfig.durations.restrictionEnd = parseReminderOption( apiSettings.durations.restrictionEnd ); } if (apiSettings.durations?.exposureReminder) { appConfig.durations.exposureReminder = parseReminderOption( apiSettings.durations.exposureReminder ); } if (apiSettings.durations?.caseReminder) { appConfig.durations.caseReminder = parseReminderOption( apiSettings.durations.caseReminder ); } if (apiSettings.codeLength) { appConfig.codeLength = Number(apiSettings.codeLength); } if (apiSettings.deepLinkLength) { appConfig.deepLinkLength = Number(apiSettings.deepLinkLength); } const tc: TraceConfiguration = { ...defaultSettings.traceConfiguration }; if (apiSettings.exposureCheckInterval) { tc.exposureCheckInterval = Number(apiSettings.exposureCheckInterval); } if (apiSettings.storeExposuresFor) { tc.storeExposuresFor = Number(apiSettings.storeExposuresFor); } const dpinDate = apiSettings.dpinDate || null; const tandcDate = apiSettings.tandcDate || null; const getTranslatedDbText = makeGetTranslatedDbText(apiSettings); dispatchState({ type: 'set', state: { loaded: true, loadedTime: new Date(), reload: () => dispatchState({type: 'reload'}), user: user[1], consent: consent[1], analyticsConsent: analyticsConsent[1] === 'true' || analyticsConsentSecure === 'true' ? 'true' : 'false', completedExposureOnboarding: completedExposureOnboarding[1], appConfig, traceConfiguration: tc, dpinDate, tandcDate, getTranslatedDbText } }); }; try { if (!state.loadedTime) { loadSettingsAsync(); } } catch (err) { console.log(err, 'Error loading settings'); dispatchState({type: 'loaded', loaded: true}); } }, [state.loadedTime]); // Runs only on first mount or on `reload()` const translatedDbText = useMemo( () => state.getTranslatedDbText(t, i18nCurrent), // Re-apply saved db text on language change. Since getTranslatedDbText modifies i18n object contents, // to ensure future updates can't cause an infinite loop, exclude useTranslation returns from deps array. /* eslint-disable-next-line react-hooks/exhaustive-deps */ [state, i18nCurrent.language] ); return ( <SettingsContext.Provider value={state}> <DbTextContext.Provider value={translatedDbText}> {children} </DbTextContext.Provider> </SettingsContext.Provider> ); }; export const useSettings = () => useContext(SettingsContext); export const useDbText = () => useContext(DbTextContext); function getSexOptions(t: TFunction) { return [ {label: t('sex:female'), value: 'f'}, {label: t('sex:male'), value: 'm'}, {label: t('common:preferNotToSay'), value: 'u'} ]; } function getAgeRangeOptions(t: TFunction) { return [ {label: t('common:preferNotToSay'), value: 'u'}, {label: '16-39', value: '16-39'}, {label: '40-59', value: '40-59'}, {label: '60+', value: '60+', riskGroup: true} ]; } function addI18nBundle( bundle: any, namespace: string, i18nCurrent: UseTranslationResponse['i18n'] ) { if (bundle) { i18nCurrent.addResourceBundle( i18nCurrent.language, namespace, bundle, true, true ); } } function makeGetTranslatedDbText(apiSettings: ApiSettings) { const getTranslatedText: GetTranslatedTextFn = (t, i18nCurrent) => { // Allow any app text to be overridden from the API const textOverrides = apiSettings.textOverrides && apiSettings.textOverrides[i18nCurrent.language]; if (textOverrides) { Object.entries(textOverrides).forEach(([namespace, bundle]) => { addI18nBundle(bundle, namespace, i18nCurrent); }); } const closeContactInfo = getDbText(apiSettings, 'closeContactInfo3') || t('closeContactInfo:content'); const closeContactAlert = getDbText(apiSettings, 'closeContactAlert3') || t('closeContactAlert:content'); const closeContactCallBack = getDbText(apiSettings, 'closeContactCallBack3') || t('closeContactAlert:call-back'); const closeContactCallbackQueued = getDbText(apiSettings, 'closeContactCallBackQueued') || t('closeContactAlert:callback-queued'); const dpinText = getDbText(apiSettings, 'dpinText', true) || t('dataProtectionPolicy:text'); const tandcText = getDbText(apiSettings, 'tandcText', true) || t('tandcPolicy:text'); const checkerThankYouText: CheckerThankYouText = Object.assign( { noSymptomsWell: t('checker:noSymptomsWell:message'), noSymptomsNotWell: t('checker:noSymptomsNotWell:message'), riskGroup: t('checker:riskGroup:warning'), recovered: t('checker:recovered'), virusIsolation: t('checker:virusIsolation') }, getDbText(apiSettings, 'checkerThankYouText') ); const tutorialVideoID = getDbText(apiSettings, 'tutorialVideoID') || null; // Add reminder db text as i18n resources to preserve placeholder subsitution const reminderDbText = apiSettings.reminderText && apiSettings.reminderText[i18nCurrent.language]; if (reminderDbText) { reminderKeys.forEach((namespace) => { const bundle = reminderDbText[namespace]; addI18nBundle(bundle, namespace, i18nCurrent); }); } return { sexOptions: getSexOptions(t), ageRangeOptions: getAgeRangeOptions(t), closeContactInfo, closeContactAlert, closeContactCallBack, closeContactCallbackQueued, dpinText, tandcText, checkerThankYouText, tutorialVideoID } as DbTextContextValue; }; return getTranslatedText; }
the_stack
import { Grid } from '../../../src/grid/base/grid'; import { Sort } from '../../../src/grid/actions/sort'; import { Filter } from '../../../src/grid/actions/filter'; import { Page } from '../../../src/grid/actions/page'; import { Print } from '../../../src/grid/actions/print'; import { Group } from '../../../src/grid/actions/group'; import { Toolbar } from '../../../src/grid/actions/toolbar'; import { DetailRow } from '../../../src/grid/actions/detail-row'; import { data, employeeData, fCustomerData } from '../base/datasource.spec'; import { createGrid, destroy } from '../base/specutil.spec'; import '../../../node_modules/es6-promise/dist/es6-promise'; import { IGrid } from '../../../src/grid/base/interface'; import {profile , inMB, getMemoryProfile} from '../base/common.spec'; Grid.Inject(Sort, Page, Filter, Print, Group, Toolbar, DetailRow); describe('Print module', () => { describe('Print without paging', () => { let gridObj: Grid; let actionComplete: Function; // (<any>window).open = () => { // return { // document: { write: () => { }, close: () => { } }, // close: () => { }, print: () => { }, focus: () => { }, moveTo: () => { }, resizeTo: () => { } // }; // }; beforeAll((done: Function) => { const isDef = (o: any) => o !== undefined && o !== null; if (!isDef(window.performance)) { console.log("Unsupported environment, window.performance.memory is unavailable"); this.skip(); //Skips test (in Chai) } gridObj = createGrid({ dataSource: data.slice(0, 15), columns: [{ field: 'OrderID' }, { field: 'CustomerID' }, { field: 'EmployeeID' }, { field: 'Freight' }, { field: 'ShipCity' }], allowSelection: false, allowFiltering: true, allowGrouping: true, allowPaging: true }, done); }); it('basic feature testing', (done: Function) => { let printComplete = (args?: { element: Element }): void => { expect(args.element.querySelectorAll('.e-gridpager').length).toBe(0); expect(args.element.querySelectorAll('.e-filterbar').length).toBe(1); expect(args.element.classList.contains('e-print-grid-layout')).toBeTruthy(); expect(args.element.querySelectorAll('.e-row').length).toBe(15); let contentDiv: HTMLElement = (args.element.querySelector('.e-content') as HTMLElement); expect(contentDiv.style.height).toBe('auto'); expect(contentDiv.style.overflowY).toBe('auto'); expect(contentDiv.style.overflowX).toBe('hidden'); expect((args.element.querySelector('.e-groupdroparea') as HTMLElement).style.display).toBe('none'); expect(args.element.querySelectorAll('.e-spin-show').length).toBe(0); expect(args.element.classList.contains('e-print-grid')).toBe(false); done(); }; window.print = () => { }; (<any>Window).print = () => { }; gridObj.printComplete = printComplete; gridObj.dataBind(); gridObj.print(); }); afterAll(() => { destroy(gridObj); gridObj = null; actionComplete = null; }); }); describe('Print with paging', () => { let gridObj: Grid; let actionComplete: Function; // (<any>window).open = () => { // return { // document: { write: () => { }, close: () => { } }, // close: () => { }, print: () => { }, focus: () => { }, moveTo: () => { }, resizeTo: () => { } // }; // }; beforeAll((done: Function) => { gridObj = createGrid({ dataSource: data, columns: [{ field: 'OrderID' }, { field: 'CustomerID' }, { field: 'EmployeeID' }, { field: 'Freight' }, { field: 'ShipCity' }], allowSelection: false, allowFiltering: true, allowGrouping: true, allowPaging: true, groupSettings: { columns: ['OrderID'] }, toolbar: ['Add'], height: 200, printMode: 'CurrentPage' }, done); }); it('current page testing and group column', (done: Function) => { let printComplete = (args?: { element: Element }): void => { expect(args.element.querySelectorAll('.e-gridpager').length).toBe(1); expect(args.element.querySelector('.e-gridpager').clientWidth).toBe(0); expect(args.element.querySelector('.e-grouptopleftcell').clientWidth).toBe(0); expect(args.element.querySelector('.e-indentcell').clientWidth).toBe(0); expect(args.element.querySelector('.e-recordplusexpand').clientWidth).toBe(0); expect(args.element.querySelectorAll('.e-toolbar').length).toBe(0); done(); }; window.print = () => { }; (<any>Window).print = () => { }; gridObj.printComplete = printComplete; gridObj.print(); }); afterAll(() => { destroy(gridObj); gridObj = null; actionComplete = null; }); }); describe('Print empty grid', () => { let gridObj: Grid; let actionComplete: Function; // (<any>window).open = () => { // return { // document: { write: () => { }, close: () => { } }, // close: () => { }, print: () => { }, focus: () => { }, moveTo: () => { }, resizeTo: () => { } // }; // }; beforeAll((done: Function) => { gridObj = createGrid({ dataSource: [], columns: [{ field: 'OrderID' }, { field: 'CustomerID' }, { field: 'EmployeeID' }, { field: 'Freight' }, { field: 'ShipCity' }], allowSelection: false, allowFiltering: true, allowGrouping: true, allowPaging: true }, done); }); it('cancel print', (done: Function) => { let beforePrint = (args?: { element: Element, cancel?: boolean }): void => { args.cancel = true; expect(args.element.classList.contains('e-print-grid')).toBe(true); done(); }; window.print = () => { }; (<any>Window).print = () => { }; gridObj.beforePrint = beforePrint; gridObj.print(); }); it('check cancel print grid element has removed', () => { let id = gridObj.element.id + '_print'; expect(document.getElementById(id)).toBe(null); }); it('empty page testing', (done: Function) => { let printComp = (args?: { element: Element }): void => { done(); }; window.print = () => { }; (<any>Window).print = () => { }; gridObj.beforePrint = printComp; gridObj.print(); }); afterAll(() => { destroy(gridObj); gridObj = null; actionComplete = null; }); }); describe('Print with custom action', () => { let gridObj: Grid; let actionComplete: Function; // (<any>window).open = () => { // return { // document: { write: () => { }, close: () => { } }, // close: () => { }, print: () => { }, focus: () => { }, moveTo: () => { }, resizeTo: () => { } // }; // }; beforeAll((done: Function) => { gridObj = createGrid({ dataSource: data, columns: [{ field: 'OrderID' }, { field: 'CustomerID' }, { field: 'EmployeeID' }, { field: 'Freight' }, { field: 'ShipCity' }], allowSelection: false, allowFiltering: true, allowGrouping: true, allowPaging: true }, done); }); it('group in before print', (done: Function) => { let beforePrint = (args?: { element: Element, cancel?: boolean }): void => { (args.element as any).ej2_instances[0].groupColumn('OrderID'); }; window.print = () => { }; (<any>Window).print = () => { }; gridObj.beforePrint = beforePrint; gridObj.printComplete = function (args) { done(); } gridObj.print(); }); afterAll(() => { gridObj.printModule.destroy(); destroy(gridObj); gridObj = null; actionComplete = null; }); }); describe('Print with hierarchy grid All mode=>', () => { let gridObj: Grid; let printGrid: Grid; let c: number = 0; beforeAll((done: Function) => { gridObj = createGrid({ dataSource: employeeData.slice(0, 4), allowSorting: true, allowFiltering: true, allowGrouping: true, hierarchyPrintMode: 'All', columns: [ { field: 'EmployeeID', headerText: 'Employee ID', textAlign: 'Right', width: 125 }, { field: 'FirstName', headerText: 'Name', width: 125 }, { field: 'Title', headerText: 'Title', width: 180 }, { field: 'City', headerText: 'City', width: 110 }, { field: 'Country', headerText: 'Country', width: 110 } ], childGrid: { created: () => ++c, dataSource: data.slice(0, 20), queryString: 'EmployeeID', hierarchyPrintMode: 'All', columns: [ { field: 'OrderID', headerText: 'Order ID', textAlign: 'Right', width: 120 }, { field: 'ShipCity', headerText: 'Ship City', width: 120 }, { field: 'Freight', headerText: 'Freight', width: 120 }, { field: 'ShipName', headerText: 'Ship Name', width: 150 } ], childGrid: { dataSource: fCustomerData, queryString: 'CustomerID', columns: [ { field: 'CustomerID', headerText: 'Customer ID', textAlign: 'Right', width: 75 }, { field: 'Phone', headerText: 'Phone', width: 100 }, { field: 'Address', headerText: 'Address', width: 120 }, { field: 'Country', headerText: 'Country', width: 100 } ], created: () => ++c }, } }, done); }); it('Check hierarchy in before print', (done: Function) => { let trigger: number = 0; expect(gridObj.hierarchyPrintMode).toBe('All'); gridObj.beforePrint = (args) => { expect(args.element.classList.contains('e-print-grid')).toBeTruthy(); expect(args.element.querySelectorAll('[aria-busy=true]').length).toBe(0); expect((args.element as any).ej2_instances[0]['isPrinting']).toBeTruthy(); expect(args.element.querySelectorAll('.e-grid').length).toBe(c); expect(trigger).toBe(0); expect((<{printGridObj?: IGrid}>window).printGridObj.expandedRows).not.toBeUndefined(); printGrid = (<{printGridObj?: IGrid}>window).printGridObj as Grid; }; gridObj.printComplete = (args) => { expect((args.element as any).ej2_instances[0]['isPrinting']).toBeFalsy(); expect((<{printGridObj?: IGrid}>window).printGridObj).toBeUndefined(); expect(args.element.classList.contains('e-print-grid-layout')).toBeTruthy(); done(); } (<any>gridObj.printModule).printGridElement = () => true; (<any>gridObj.printModule).renderPrintGrid(); (<Grid>(<{printGridObj?: IGrid}>window).printGridObj).actionFailure = () => trigger++; }); afterAll(() => { gridObj.printModule.destroy(); destroy(gridObj); destroy(printGrid); printGrid = null; gridObj = null; c = null; }); }); describe('Print with hierarchy grid expanded mode =>', () => { let gridObj: Grid; let childGrid: Grid; let printGrid: Grid; beforeAll((done: Function) => { gridObj = createGrid({ dataSource: employeeData.slice(0, 4), allowSorting: true, allowFiltering: true, allowGrouping: true, hierarchyPrintMode: 'Expanded', columns: [ { field: 'EmployeeID', headerText: 'Employee ID', textAlign: 'Right', width: 125 }, { field: 'FirstName', headerText: 'Name', width: 125 }, { field: 'Title', headerText: 'Title', width: 180 }, { field: 'City', headerText: 'City', width: 110 }, { field: 'Country', headerText: 'Country', width: 110 } ], childGrid: { dataSource: data.slice(0, 20), queryString: 'EmployeeID', columns: [ { field: 'OrderID', headerText: 'Order ID', textAlign: 'Right', width: 120 }, { field: 'ShipCity', headerText: 'Ship City', width: 120 }, { field: 'Freight', headerText: 'Freight', width: 120 }, { field: 'ShipName', headerText: 'Ship Name', width: 150 } ], childGrid: { dataSource: fCustomerData, queryString: 'CustomerID', columns: [ { field: 'CustomerID', headerText: 'Customer ID', textAlign: 'Right', width: 75 }, { field: 'Phone', headerText: 'Phone', width: 100 }, { field: 'Address', headerText: 'Address', width: 120 }, { field: 'Country', headerText: 'Country', width: 100 } ] }, } }, done); }); it('expand the child grid', (done: Function) => { gridObj.detailDataBound = (args: any) => { childGrid = args.childGrid; childGrid.dataBound = () => {done()}; expect(gridObj.element.querySelectorAll('.e-grid').length).toBe(1); }; gridObj.detailRowModule.expand(2); }); it('expand inner childGrid', (done: Function) => { childGrid.detailDataBound = (args) => { expect(gridObj.element.querySelectorAll('.e-grid').length).toBe(2); done(); }; childGrid.detailRowModule.expand(1); }); it('Check hierarchy in before expanded print', (done: Function) => { let trigger: number = 0; expect(gridObj.hierarchyPrintMode).toBe('Expanded'); gridObj.beforePrint = (args) => { expect(args.element.classList.contains('e-print-grid')).toBeTruthy(); expect(args.element.querySelectorAll('[aria-busy=true]').length).toBe(0); expect((args.element as any).ej2_instances[0]['isPrinting']).toBeTruthy(); expect(args.element.querySelectorAll('.e-grid').length).toBe(2); expect(trigger).toBe(0); expect((<{printGridObj?: IGrid}>window).printGridObj.expandedRows).not.toBeUndefined(); printGrid = (<{printGridObj?: IGrid}>window).printGridObj as Grid; }; gridObj.printComplete = (args) => { expect((args.element as any).ej2_instances[0]['isPrinting']).toBeFalsy(); expect((<{printGridObj?: IGrid}>window).printGridObj).toBeUndefined(); expect(args.element.classList.contains('e-print-grid-layout')).toBeTruthy(); done(); } (<any>gridObj.printModule).printGridElement = () => true; (<any>gridObj.printModule).renderPrintGrid(); (<Grid>(<{printGridObj?: IGrid}>window).printGridObj).actionFailure = () => trigger++; }); afterAll(() => { gridObj.printModule.destroy(); destroy(gridObj); destroy(printGrid); gridObj = null; childGrid = null; printGrid = null; }); }); describe('Print with hierarchy grid None mode =>', () => { let gridObj: Grid; let printGrid: Grid; beforeAll((done: Function) => { gridObj = createGrid({ dataSource: employeeData.slice(0, 4), allowSorting: true, allowFiltering: true, allowGrouping: true, hierarchyPrintMode: 'None', columns: [ { field: 'EmployeeID', headerText: 'Employee ID', textAlign: 'Right', width: 125 }, { field: 'FirstName', headerText: 'Name', width: 125 }, { field: 'Title', headerText: 'Title', width: 180 }, { field: 'City', headerText: 'City', width: 110 }, { field: 'Country', headerText: 'Country', width: 110 } ], childGrid: { dataSource: data.slice(0, 20), queryString: 'EmployeeID', columns: [ { field: 'OrderID', headerText: 'Order ID', textAlign: 'Right', width: 120 }, { field: 'ShipCity', headerText: 'Ship City', width: 120 }, { field: 'Freight', headerText: 'Freight', width: 120 }, { field: 'ShipName', headerText: 'Ship Name', width: 150 } ], childGrid: { dataSource: fCustomerData, queryString: 'CustomerID', columns: [ { field: 'CustomerID', headerText: 'Customer ID', textAlign: 'Right', width: 75 }, { field: 'Phone', headerText: 'Phone', width: 100 }, { field: 'Address', headerText: 'Address', width: 120 }, { field: 'Country', headerText: 'Country', width: 100 } ] }, } }, done); }); it('expand the child grid', (done: Function) => { gridObj.detailDataBound = (args: any) => { expect(gridObj.element.querySelectorAll('.e-grid').length).toBe(1); done(); }; gridObj.detailRowModule.expand(2); }); it('Check hierarchy in before None print', (done: Function) => { let trigger: number = 0; expect(gridObj.hierarchyPrintMode).toBe('None'); gridObj.beforePrint = (args) => { expect(args.element.classList.contains('e-print-grid')).toBeTruthy(); expect(args.element.querySelectorAll('[aria-busy=true]').length).toBe(0); expect((args.element as any).ej2_instances[0]['isPrinting']).toBeTruthy(); expect(args.element.querySelectorAll('.e-grid').length).toBe(0); expect((<{printGridObj?: IGrid}>window).printGridObj.expandedRows).toBeUndefined(); printGrid = (<{printGridObj?: IGrid}>window).printGridObj as Grid; }; gridObj.printComplete = (args) => { expect((args.element as any).ej2_instances[0]['isPrinting']).toBeFalsy(); expect((<{printGridObj?: IGrid}>window).printGridObj).toBeUndefined(); expect(args.element.classList.contains('e-print-grid-layout')).toBeTruthy(); done(); } (<any>gridObj.printModule).printGridElement = () => true; (<any>gridObj.printModule).renderPrintGrid(); (<Grid>(<{printGridObj?: IGrid}>window).printGridObj).actionFailure = () => trigger++; }); it('memory leak', () => { profile.sample(); let average: any = inMB(profile.averageChange) //Check average change in memory samples to not be over 10MB expect(average).toBeLessThan(10); let memory: any = inMB(getMemoryProfile()) //Check the final memory usage against the first usage, there should be little change if everything was properly deallocated expect(memory).toBeLessThan(profile.samples[0] + 0.25); }); afterAll(() => { gridObj.printModule.destroy(); destroy(gridObj); destroy(printGrid); gridObj = null; printGrid = null; }); }); describe('EJ2 - 57790 - Print not working when sortComparer property set to a column =>', () => { let gridObj: Grid; let printGrid: Grid; // (<any>window).open = () => { // return { // document: { write: () => { }, close: () => { } }, // close: () => { }, print: () => { }, focus: () => { }, moveTo: () => { }, resizeTo: () => { } // }; // }; beforeAll((done: Function) => { gridObj = createGrid({ dataSource: employeeData.slice(0, 4), allowSorting: true, sortSettings: { columns: [ { field: 'FirstName', direction: 'Ascending' } ], }, columns: [ { field: 'EmployeeID', headerText: 'Employee ID', textAlign: 'Right', width: 125 }, { field: 'FirstName', headerText: 'Name', width: 125, sortComparer: (reference: string, comparer: string) => { if (reference < comparer) return -1; else if (reference > comparer) return 1; return 0; }, }, { field: 'Title', headerText: 'Title', width: 180 }, { field: 'City', headerText: 'City', width: 110 }, { field: 'Country', headerText: 'Country', width: 110 } ], }, done); }); it('sorting after print', (done: Function) => { window.print = () => { }; (<any>Window).print = () => { }; gridObj.printComplete = function (args) { done(); } gridObj.print(); }); afterAll(() => { gridObj.printModule.destroy(); destroy(gridObj); gridObj = null; }); }); });
the_stack
import { constants, providers, EventFilter } from 'ethers'; import { Result } from 'ethers/lib/utils'; import { IColonyEvents, IColonyEventsFactory, IColonyNetwork, IColonyNetworkFactory, } from '@colony/colony-js/extras'; import type { BlockTag, Filter } from '@ethersproject/abstract-provider'; import { addressesAreEqual, getLogs, nonNullable } from './utils'; /** Valid sources for Colony emitted events. Used to map the parsed event data */ export interface EventSources { Colony: IColonyEvents; ColonyNetwork: IColonyNetwork; } /** An EventSource is essentially an _ethers_ contract, that we can keep track of */ export type EventSource = EventSources[keyof EventSources]; /** A Colony extended ethers Filter to keep track of where events are coming from */ export interface ColonyFilter extends Filter { eventSource: keyof EventSources; eventName: string; } // TODO: consider allowing an address array /** ColonyFilter with support for multi-events * For the multi-event compatible filters the following assumptions prevail: * - `address` is a mandatory field * - it can only take a single `topic` * - `fromBlock` and `toBlock` are not available */ export interface ColonyMultiFilter extends Omit<ColonyFilter, 'address' | 'topics' | 'fromBlock' | 'toBlock'> { address: string; topic: string; } /** An Event that came from a contract within the Colony Network */ export interface ColonyEvent extends ColonyFilter { data: Result; } /** * The ColonyEvents class is a wrapper around _ethers_'s event implementations to make it easier to track and fetch Colony related events. * It works by creating specific filters that can keep track of event sources and map filters to their respective events. This allows for * easy parsing of event data, without necessarily knowing the contract that emitted it. * * @remarks * The API is subject to change as we find more applications for this */ export class ColonyEvents { eventSources: EventSources; provider: providers.JsonRpcProvider; /** * Create a new ColonyEvents instance * * @remarks * As opposed to the [[ColonyNetwork.ColonyNetwork]] class, this constructor _needs_ an _ethers_ JsonRpcProvider (or a subclass of it) as it's * the only provider that supports topic filtering by multiple addresses * * @param provider An _ethers_ `JsonRpcProvider` * @returns A ColonyEvents instance */ constructor(provider: providers.JsonRpcProvider) { this.provider = provider; this.eventSources = { Colony: IColonyEventsFactory.connect(constants.AddressZero, provider), ColonyNetwork: IColonyNetworkFactory.connect( constants.AddressZero, provider, ), }; } private static extractSingleTopic(filter?: Filter) { if (!filter || !filter.topics) return null; const topic = filter.topics; if (typeof topic[0] == 'string') return topic[0]; if (Array.isArray(topic[0]) && typeof topic[0][0] == 'string') { return topic[0][0]; } return null; } private getEventSourceName(contract: EventSource) { // Find contract for filter in eventSources to store the name alongside it const eventSource = Object.entries(this.eventSources).find( ([, c]) => c === contract, ); return eventSource && (eventSource[0] as keyof EventSources); } /** * Get events for multiple filters across multiple addresses at once * * All the filters are connected by a logical OR, i.e. it will find ALL given events for ALL the given contract addresses * This is handy when you want to listen to a fixed set of events for a lot of different contracts * * @remarks * `fromBlock` and `toBlock` properties of the indivdual filters will be ignored * * @example * ```typescript * Retrieve and parse all `DomainAdded` events for a specific [[ColonyNetwork.Colony]] contract * const domainAdded = colonyEvents.createFilter( * colonyEvents.eventSources.Colony, * 'DomainAdded(address,uint256)', * colonyAddress, * ); * // Immediately executing async function * (async function() { * const events = await colonyEvents.getMultiEvents([domainAdded]); * })(); * ``` * * @param filters An array of [[ColonyMultiFilter]]s. Normal [[ColonyFilters]] will not work * @param options You can define `fromBlock` and `toBlock` only once for all the filters given * @returns An array of [[ColonyEvent]]s */ async getMultiEvents( filters: ColonyMultiFilter[], options: { fromBlock?: BlockTag; toBlock?: BlockTag } = {}, ): Promise<ColonyEvent[]> { // Unique list of addresses const addresses = Array.from( new Set(filters.map(({ address }) => address)), ); // Unique list of topics const topics = Array.from(new Set(filters.map(({ topic }) => topic))); const logs = await getLogs( { address: addresses, fromBlock: options.fromBlock, toBlock: options.toBlock, topics: [topics], }, this.provider, ); return logs .map((log) => { const filter = filters.find( ({ topic, address }) => log.topics.includes(topic) && addressesAreEqual(address, log.address), ); if (!filter) return null; const { eventSource, topic, eventName, address } = filter; const data = this.eventSources[eventSource].interface.decodeEventLog( eventName, log.data, log.topics, ); return { address, eventSource, topic, eventName, data, }; }) .filter(nonNullable); } /** * Create a [[ColonyFilter]] that keeps track of its event source * * To create a [[ColonyFilter]], we need to not only give it the topics and addresses as required by _ethers_ * [`Filter`s](https://docs.ethers.io/v5/api/providers/types/#providers-Filter), but also the actual source contract of that Filter. * Like this we can keep track of the source contract interface to parse the event data when it's emitted * * @remarks * We can do that as we do not have ambiguous events across our contracts, so we will always be able to find the right contract to parse the event data later on * * @example * Filter for all `DomainAdded` events between block 21830000 and 21840000 (across all deployed [[ColonyNetwork.Colony]] contracts) * ```typescript * const domainAdded = colonyEvents.createFilter( * colonyEvents.eventSources.Colony, * 'DomainAdded(address,uint256)', * null, * { fromBlock: 21830000 , toBlock: 21840000 }, * ); * ``` * * @typeParam T Needs to be a valid [[EventSource]] (i.e. from `colonyEvents.eventSources`) * @typeParam N An event signature as defined in the _ethers_ contract's [`filters`](https://docs.ethers.io/v5/api/contract/contract/#Contract--filters) object. * See the [ColonyJS documentation](https://colony.gitbook.io/colony/colonyjs) for a list of all available contracts and events * * @param contract A valid [[EventSource]] * @param eventName A valid event signature from the contract's `filters` object * @param address Address of the contract that can emit this event * @param params Parameters to filter by for the event. Has to be indexed in the contract (see _ethers_ [Event Filters](https://docs.ethers.io/v5/api/contract/contract/#Contract--filters)) * @param options You can define `fromBlock` and `toBlock` only once for all the filters given * @returns A [[ColonyFilter]] */ createFilter< T extends EventSource & { filters: { [P in N]: (...args: never) => EventFilter }; }, N extends keyof T['filters'], >( contract: T, eventName: N, address?: string, params?: Parameters<T['filters'][N]>, options: { fromBlock?: BlockTag; toBlock?: BlockTag } = {}, ): ColonyFilter { // Create standard filter const filter = contract.filters[eventName].apply(params); const eventSource = this.getEventSourceName(contract); if (!eventSource) { throw new Error(`Could not find event contract for filter`); } return { eventSource, eventName: eventName as string, topics: filter.topics, address, fromBlock: options.fromBlock, toBlock: options.toBlock, }; } /** * Create a [[ColonyMultiFilter]] that keeps track of its event source and can work alongside other filters in [[getMultiEvents]] * * The [[ColonyMultiFilter]] works much like the [[ColonyFilter]], just that we _have_ to specify an address of the contract which emits this event. * Furthermore, no `fromBlock` or `toBlock` requirements can be given (that is done on a global level in [[getMultiEvents]]) * * @remarks * We can do that as we do not have ambiguous events across our contracts, so we will always be able to find the right contract to parse the event data later on * * @example * ```typescript * Filter for all `DomainAdded` events for a specific [[ColonyNetwork.Colony]] contract * const domainAdded = colonyEvents.createFilter( * colonyEvents.eventSources.Colony, * 'DomainAdded(address,uint256)', * colonyAddress, * ); * ``` * * @typeParam T Needs to be a valid [[EventSource]] (i.e. from `colonyEvents.eventSources`) * @typeParam N An event signature as defined in the _ethers_ contract's [`filters`](https://docs.ethers.io/v5/api/contract/contract/#Contract--filters) object. * See the [ColonyJS documentation](https://colony.gitbook.io/colony/colonyjs) for a list of all available contracts and events * * @param contract A valid [[EventSource]] * @param eventName A valid event signature from the contract's `filters` object * @param address Address of the contract that can emit this event * @param params Parameters to filter by for the event. Has to be indexed in the contract (see _ethers_ [Event Filters](https://docs.ethers.io/v5/api/contract/contract/#Contract--filters)) * @returns A [[ColonyMultiFilter]] */ createMultiFilter< T extends EventSource & { filters: { [P in N]: (...args: never) => EventFilter }; }, N extends keyof T['filters'], >( contract: T, eventName: N, address: string, params?: Parameters<T['filters'][N]>, ): ColonyMultiFilter { const filter = this.createFilter(contract, eventName, address, params); // Just use the first topic for now. Let's see how far we get with this. They will be connected with ORs const topic = ColonyEvents.extractSingleTopic(filter); if (!topic) { throw new Error(`Filter does not have any topics: ${eventName}`); } delete filter.topics; const colonyFilter = filter as ColonyMultiFilter; colonyFilter.topic = topic; return colonyFilter; } }
the_stack
import { API, CameraRecordingConfiguration, CameraRecordingDelegate, HAP, HDSProtocolSpecificErrorReason, Logging, PlatformAccessory, RecordingPacket } from "homebridge"; import { ProtectCamera, RtspEntry } from "./protect-camera"; import { FfmpegRecordingProcess } from "./protect-ffmpeg-record"; import { ProtectCameraConfig } from "unifi-protect"; import { ProtectNvr } from "./protect-nvr"; import { ProtectTimeshiftBuffer } from "./protect-timeshift"; // Camera recording delegate implementation for Protect. export class ProtectRecordingDelegate implements CameraRecordingDelegate { private _isRecording: boolean; private readonly accessory: PlatformAccessory; private readonly api: API; private readonly hap: HAP; private debug: (message: string, ...parameters: unknown[]) => void; private ffmpegStream: FfmpegRecordingProcess | null; private isInitialized: boolean; private isTransmitting: boolean; private readonly log: Logging; private readonly maxRecordingDuration: number; private readonly name: () => string; private nvr: ProtectNvr; private readonly protectCamera: ProtectCamera; private recordingConfig: CameraRecordingConfiguration | undefined; private rtspEntry: RtspEntry | null; private transmittedSegments: number; private readonly timeshift: ProtectTimeshiftBuffer; private timeshiftedSegments: number; private transmitListener: ((segment: Buffer) => void) | null; // Create an instance of the HKSV recording delegate. constructor(protectCamera: ProtectCamera) { this._isRecording = false; this.accessory = protectCamera.accessory; this.api = protectCamera.api; this.hap = protectCamera.api.hap; this.debug = protectCamera.platform.debug.bind(protectCamera.platform); this.ffmpegStream = null; this.isInitialized = false; this.isTransmitting = false; this.log = protectCamera.platform.log; this.name = protectCamera.name.bind(protectCamera); this.nvr = protectCamera.nvr; this.protectCamera = protectCamera; this.maxRecordingDuration = parseInt(this.nvr.optionGet(this.accessory.context.device as ProtectCameraConfig, "Video.HKSV.Recording.MaxDuration") ?? "0"); this.timeshiftedSegments = 0; this.transmittedSegments = 0; this.rtspEntry = null; this.timeshift = new ProtectTimeshiftBuffer(protectCamera); this.transmitListener = null; } // Process HomeKit requests to activate or deactivate HKSV recording capabilities for a camera. public async updateRecordingActive(active: boolean): Promise<void> { // If we are no longer recording, stop the livestream. if(!active) { this.timeshift.stop(); // Inform the user of the state change, if needed. if(this.isRecording !== active) { this.log.info("%s: Disabling HomeKit Secure Video event recording.", this.name()); } // Disable recording. this._isRecording = active; // Turn off any potential inflight motion detection. Strictly speaking, this shouldn't be needed since any inflight // motion sensor events will clear themselves. That said, we play it safe just the same. this.accessory.getService(this.hap.Service.MotionSensor)?.updateCharacteristic(this.hap.Characteristic.MotionDetected, false); // We're done. return; } // We have no recording configuration available yet. Set our desired state and we're done. // Once we have a recording configuration, we'll get called again and be able to begin timeshifting. if(!this.recordingConfig) { this._isRecording = active; return; } // Figure out which camera channel we should use for the livestream based on the requested resolution. this.rtspEntry = this.protectCamera.findRecordingRtsp(this.recordingConfig.videoCodec.resolution[0], this.recordingConfig.videoCodec.resolution[1], this.accessory.context.device as ProtectCameraConfig); if(!this.rtspEntry) { this._isRecording = false; this.log.error("%s: Unable to start the HomeKit Secure Video timeshift buffer: no valid RTSP stream profile was found.", this.name()); return; } // If the user has disabled timeshifting, don't start the timeshift buffer. if(this.nvr.optionEnabled(this.accessory.context.device as ProtectCameraConfig, "Video.HKSV.TimeshiftBuffer")) { if(!this.recordingConfig || !this.rtspEntry) { return; } // Set the bitrate to what HomeKit is looking for. This is particularly useful when we occasionally have // to livestream to a user, where bitrates can be different and even get reconfigured in realtime. By // contrast, HomeKit Secure Video has a consistent bitrate it accepts, and we want to try to match it as // closely as posible. if(!(await this.protectCamera.setBitrate(this.rtspEntry.channel.id, this.recordingConfig.videoCodec.parameters.bitRate * 1000))) { this.log.error("%s: Unable to set the bitrate to %skbps for HomeKit Secure Video event recording.", this.name(), this.recordingConfig.videoCodec.parameters.bitRate); return; } // Fire up the timeshift buffer. if(!(await this.timeshift.start(this.rtspEntry.channel.id))) { this.log.error("%s: Unable to start the timeshift buffer for HomeKit Secure Video.", this.name()); return; } } // Inform the user of the state change, if needed. if((this._isRecording !== active) || !this.isInitialized) { this.isInitialized = true; this.log.info("%s: HomeKit Secure Video event recording enabled: %s, %s kbps with %s", this.name(), this.rtspEntry?.name, this.recordingConfig?.videoCodec.parameters.bitRate, this.nvr.optionEnabled(this.accessory.context.device as ProtectCameraConfig, "Video.HKSV.TimeshiftBuffer") ? "a " + (this.timeshift.length / 1000).toString() + " second timeshift buffer." : "no timeshift buffer. Warning: this may provide a suboptimal HKSV experience." ); // Inform the user if there's a maximum event recording duration set. if(this.maxRecordingDuration) { this.log.info("%s: HomeKit Secure Video recordings will be no longer than ~%s seconds.", this.name(), this.maxRecordingDuration); } } // Update our recording state internally. this._isRecording = active; } // Process updated recording configuration settings from HomeKit Secure Video. public updateRecordingConfiguration(configuration: CameraRecordingConfiguration | undefined): void { // If we're set to an undefined state, it's because HomeKit can't figure out a valid configuration to use. // This is typically due to a factory reset of the camera or a similar edge case. We choose to handle it // by stopping our timeshift buffer. if(!configuration) { this.recordingConfig = configuration; this.timeshift.stop(); return; } // Save the new recording configuration. this.recordingConfig = configuration; // Tell our timeshift buffer how many seconds HomeKit has requested we prebuffer. this.timeshift.length = this.recordingConfig.prebufferLength; // Start or restart our timeshift buffer based on our updated configuration. void this.updateRecordingActive(this.isRecording); } // Handle the actual recording stream request. // eslint-disable-next-line @typescript-eslint/no-unused-vars public async *handleRecordingStreamRequest(streamId: number): AsyncGenerator<RecordingPacket> { let isLastSegment = false; this.transmittedSegments = 0; // If we've explicitly disabled HKSV recording, we're done right now. Otherwise, start transmitting our timeshift // buffer and process it through FFmpeg. if(!this.accessory.context.hksvRecording || !(await this.startTransmitting()) || !this.ffmpegStream) { // Stop transmitting, if needed. If HKSV recording has been disabled explicitly, it should never start in the first place. this.stopTransmitting(); // Something's gone wrong, or we've disabled HKSV recording. In either event, we send an fMP4 stream header // back to HKSV and exit as cleanly as we can. If we can't get the stream header, we still send an empty segment // to HKSV - this will still generate a warning in Homebridge that can be ignored. const streamHeader = (await this.timeshift.getInitSegment()) ?? Buffer.alloc(0); yield { data: streamHeader, isLast: true }; return; } // Process our FFmpeg-generated segments and send them back to HKSV. for await (const segment of this.ffmpegStream.segmentGenerator()) { // If we've not transmitting, we're done. if(!this.isTransmitting) { return; } // No segment doesn't mean we're done necessarily, but it does mean we need to wait for FFmpeg to catch up. if(!segment) { continue; } // If we've exceeded a user-configured maximum recording duration, let HomeKit know we're stopping. We imperfectly calculate // our recording duration by using the fact that each transmitted segment will contain a single I-frame. The method is imperfect because // partial segments happen, as well as other edge cases, but it's more than good enough for our purposes. if(this.maxRecordingDuration && this.rtspEntry && ((this.transmittedSegments * this.rtspEntry.channel.idrInterval) > this.maxRecordingDuration)) { isLastSegment = true; } // Send HKSV the segment. yield { data: segment, isLast: isLastSegment }; // Keep track of how many segments we've sent to HKSV. this.transmittedSegments++; // If we've sent the last segment, we're done. if(isLastSegment) { return; } } // If we're done transmitting, we're done here. if(!this.isTransmitting) { return; } // Something's gone wrong and we've sent HKSV no segments. Let's send an fMP4 stream header back to HKSV and exit // as cleanly as we can. If we can't get the stream header, we send an empty segment to HKSV - this will still // generate a warning in HAP-NodeJS that can be ignored. if(!this.transmittedSegments) { this.debug("%s: HKSV event recording ending without sending any segments. Transmitting a final packet to ensure we end properly.", this.name()); yield { data: (await this.timeshift.getInitSegment()) ?? Buffer.alloc(0), isLast: true }; return; } // Something likely happened to FFmpeg and we didn't send out a final segment. Tell HKSV we're really done. if(!isLastSegment) { this.log.error("%s: HKSV event recording ending abruptly, likely due to an FFmpeg failure. " + "Transmitting a final packet to ensure we end properly. " + "Note: Homebridge / HAP-NodeJS may generate an HDS error as a result. This can be safely ignored.", this.name()); yield { data: Buffer.alloc(0), isLast: true }; return; } } // Receive an acknowledgement from HomeKit that it's seen an end-of-stream packet from us. // eslint-disable-next-line @typescript-eslint/no-unused-vars public acknowledgeStream(streamId: number): void { // Since HomeKit knows our transmission is ending, it's safe to do so now. this.stopTransmitting(); } // Process HomeKit requests to end the transmission of the recording stream. public closeRecordingStream(streamId: number, reason: HDSProtocolSpecificErrorReason | undefined): void { this.stopTransmitting(reason); } // Start transmitting to the HomeKit hub our timeshifted fMP4 stream. private async startTransmitting(): Promise<boolean> { // If there's a prior instance of FFmpeg, clean up after ourselves. if(this.ffmpegStream) { this.ffmpegStream.stop(); this.ffmpegStream = null; } // If there's a prior instance of our transmit handler, clean it up. if(this.transmitListener) { this.timeshift.removeListener("segment", this.transmitListener); this.transmitListener = null; } // If we don't have a recording configuration from HomeKit or an RTSP profile, we can't continue. if(!this.recordingConfig || !this.rtspEntry) { return false; } // We want to keep feeding HomeKit until it tells us it's finished, or we decide we don't want to send anymore // fMP4 packets. We treat this the same was a DVR works where you can pause live television, but it continues to // buffer what's being broadcast until you're ready to watch it. This is the same idea. // Keep track of how many fMP4 segments we are feeding FFmpeg. this.transmittedSegments = 0; // Check to see if the user has audio enabled or disabled for recordings. const isAudioActive = this.protectCamera.stream.controller.recordingManagement?.recordingManagementService .getCharacteristic(this.api.hap.Characteristic.RecordingAudioActive).value === 1 ? true : false; // Start a new FFmpeg instance to transcode using HomeKit's requirements. this.ffmpegStream = new FfmpegRecordingProcess(this.protectCamera, this.recordingConfig, this.rtspEntry, isAudioActive); this.isTransmitting = true; // Let the timeshift buffer know it's time to transmit and continue timeshifting. if(this.nvr.optionEnabled(this.accessory.context.device as ProtectCameraConfig, "Video.HKSV.TimeshiftBuffer")) { this.timeshiftedSegments = 0; await this.timeshift.transmitStream(true); let seenInitSegment = false; // Listen in for events from the timeshift buffer and feed FFmpeg. This looks simple, conceptually, // but there's a lot going on here. this.transmitListener = (segment: Buffer): void => { if(!seenInitSegment && this.timeshift.isInitSegment(segment)) { seenInitSegment = true; this.ffmpegStream?.stdin?.write(segment); return; } // We don't want to send the initialization segment more than once - FFmpeg will get confused if you do, plus // it's wrong and you should only send the fMP4 stream header information once. if(this.timeshift.isInitSegment(segment)) { return; } // Send the segment to FFmpeg for processing. this.ffmpegStream?.stdin?.write(segment); this.timeshiftedSegments++; }; this.timeshift.on("segment", this.transmitListener); } // Inform the user. this.log.debug("%s: Beginning a HomeKit Secure Video recording event.", this.name()); return true; } // Stop transmitting the HomeKit hub our timeshifted fMP4 stream. private stopTransmitting(reason?: HDSProtocolSpecificErrorReason): void { const device = this.accessory.context.device as ProtectCameraConfig; // We're done transmitting, so we can go back to maintaining our timeshift buffer for HomeKit. if(this.nvr.optionEnabled(device, "Video.HKSV.TimeshiftBuffer")) { void this.timeshift.transmitStream(false); } // Kill any FFmpeg sessions. if(this.ffmpegStream) { this.ffmpegStream.stop(); this.ffmpegStream = null; } this.isTransmitting = false; if(this.transmitListener) { this.timeshift.removeListener("segment", this.transmitListener); this.transmitListener = null; } // We actually have one less segment than we think we do since we counted the fMP4 stream header as well, which // shouldn't count toward our total of transmitted video segments. if(this.transmittedSegments) { this.transmittedSegments--; } // Inform the user if we've recorded something. if(this.accessory.context.hksvRecording && this.transmittedSegments && this.rtspEntry) { // Calculate approximately how many seconds we've recorded. We have more accuracy in timeshifted segments, so we'll use the more // accurate statistics when we can. Otherwise, we use the number of segments transmitted to HomeKit as a close proxy. const recordedSeconds = this.timeshiftedSegments ? ((this.timeshiftedSegments * this.timeshift.segmentLength) / 1000) : (this.transmittedSegments * this.rtspEntry?.channel.idrInterval); let recordedTime = ""; // Create a nicely formatted string for end users. Yes, the author recognizes this isn't // essential, but it does bring a smile to their face. if(recordedSeconds < 1) { recordedTime = recordedSeconds.toString(); } else if(recordedSeconds < 60) { recordedTime = Math.round(recordedSeconds).toString(); } else { // Calculate the time elements. const hours = Math.floor(recordedSeconds / 3600); const minutes = Math.floor((recordedSeconds % 3600)/ 60); const seconds = Math.floor((recordedSeconds % 3600) % 60); // Build the string. if(hours > 10) { recordedTime = hours.toString() + ":"; } else if(hours > 0) { recordedTime = "0" + hours.toString() + ":"; } if(minutes > 10) { recordedTime += minutes.toString() + ":"; } else if(minutes > 0) { recordedTime += (hours > 0) ? "0" : "" + minutes.toString() + ":"; } if(recordedTime.length && (seconds < 10)) { recordedTime += "0" + seconds.toString(); } else { recordedTime += seconds ? seconds.toString() : recordedSeconds.toString(); } } let timeUnit; switch(recordedTime.split(":").length - 1) { case 1: timeUnit = "minute"; break; case 2: timeUnit = "hour"; break; default: timeUnit = "second"; break; } // Inform the user if they've enabled logging. We log HKSV events by default, for now. if(this.nvr.optionEnabled(device, "Log.HKSV") || this.nvr.optionEnabled(device, "Log.Motion", false)) { this.log.info("%s: HomeKit Secure Video has recorded %s %s %s motion event.", this.name(), this.timeshiftedSegments ? "a" : "an approximately", recordedTime, timeUnit); } } // If we have a reason for stopping defined, and it's noteworthy, inform the user. let reasonDescription; switch(reason) { case HDSProtocolSpecificErrorReason.CANCELLED: reasonDescription = "HomeKit canceled the request."; break; case HDSProtocolSpecificErrorReason.UNEXPECTED_FAILURE: reasonDescription = "An unexpected protocol failure has occured."; break; case HDSProtocolSpecificErrorReason.TIMEOUT: reasonDescription = "The request timed out."; break; default: break; } if((reason !== undefined) && (reason !== HDSProtocolSpecificErrorReason.NORMAL)) { this.log.error("%s: HomeKit Secure Video event recording ended abnormally: %s", this.name(), reasonDescription); } } // Return our HomeKit Secure Video recording state. This effectively tells us if HKSV has been configured and is on. public get isRecording(): boolean { return this._isRecording; } // Return our current HomeKit Secure Video recording configuration. public get recordingConfiguration(): CameraRecordingConfiguration | null { return this.recordingConfig ?? null; } }
the_stack
import { addListeners } from '../../../../../client/addListener' import { ANIMATION_T_MS } from '../../../../../client/animation/animation' import applyStyle, { mergeStyle } from '../../../../../client/applyStyle' import classnames from '../../../../../client/classnames' import debounce from '../../../../../client/debounce' import { Element } from '../../../../../client/element' import { IOPointerEvent } from '../../../../../client/event/pointer' import { makeClickListener } from '../../../../../client/event/pointer/click' import { makePointerCancelListener } from '../../../../../client/event/pointer/pointercancel' import { makePointerDownListener } from '../../../../../client/event/pointer/pointerdown' import { makePointerEnterListener } from '../../../../../client/event/pointer/pointerenter' import { makePointerLeaveListener } from '../../../../../client/event/pointer/pointerleave' import { makePointerMoveListener } from '../../../../../client/event/pointer/pointermove' import { makePointerUpListener } from '../../../../../client/event/pointer/pointerup' import { makeResizeListener } from '../../../../../client/event/resize' import parentElement from '../../../../../client/platform/web/parentElement' import { COLOR_NONE } from '../../../../../client/theme' import { Pod } from '../../../../../pod' import { System } from '../../../../../system' import { Dict } from '../../../../../types/Dict' import { IHTMLDivElement } from '../../../../../types/global/dom' import { Unlisten } from '../../../../../types/Unlisten' import Div from '../../Div/Component' import Frame from '../../Frame/Component' import Icon from '../../Icon/Component' export interface Props { className?: string style?: Dict<string> title?: string height?: number width?: number component?: Element icon?: string active?: boolean hidden?: boolean y?: number } export const KNOB_HEIGHT = 35 const DEFAULT_STYLE = { position: 'absolute', width: 'fit-content', height: 'fit-content', touchAction: 'none', } export default class Drawer extends Element<IHTMLDivElement, Props> { public drawer: Div public content: Div public frame: Frame private _knob: Icon private _column: Div private _active: boolean = false private _hidden: boolean = false private _hover: boolean = false private _y: number = 0 constructor($props: Props, $system: System, $pod: Pod) { super($props, $system, $pod) const { className, style = {}, icon, title, component, active = false, hidden = false, y = 0, width = 0, height = KNOB_HEIGHT, } = this.$props this._active = active this._hidden = hidden this._y = 0 const { backgroundColor = 'inherit' } = style const knob = new Icon( { className: 'drawer-knob', icon, active, style: { position: 'absolute', top: '0', padding: '6px', transform: 'translateX(-100%)', height: `${KNOB_HEIGHT - 12 - 2}px`, width: `${KNOB_HEIGHT - 12 - 2}px`, touchAction: 'none', boxShadow: 'inset 1px 0 0 0 currentColor, inset -1px 0 0 0 #00000000, inset 0 1px 0 0 currentColor, inset 0 -1px 0 0 currentColor', backgroundColor, cursor: 'pointer', }, title, }, this.$system, this.$pod ) knob.addEventListener( makeClickListener({ onClick: this._on_knob_click, }) ) knob.addEventListener(makePointerEnterListener(this._on_knob_pointer_enter)) knob.addEventListener(makePointerLeaveListener(this._on_knob_pointer_leave)) knob.addEventListener(makePointerDownListener(this._on_knob_pointer_down)) knob.preventDefault('mousedown') knob.preventDefault('touchdown') this._knob = knob const frame = new Frame( { className: 'drawer-frame', style: { position: 'absolute', width: `${width + 2}px`, height: `${height + 2}px`, borderWidth: '1px', borderStyle: 'solid', borderColor: COLOR_NONE, borderRadius: '1px', boxSizing: 'border-box', overflow: 'hidden', }, }, this.$system, this.$pod ) this.frame = frame const content = new Div( { className: 'drawer-content', style: { display: 'flex', width: component ? `${width + 2 + 6}px` : '0', height: `${height + 2 + 6}px`, // borderWidth: component ? '1px' : '0', // borderStyle: 'solid', // borderColor: 'currentColor', boxShadow: 'inset 1px 0 0 0 #00000000, inset -1px 0 0 0 currentColor, inset 0 1px 0 0 currentColor, inset 0 -1px 0 0 currentColor', // borderLeftColor: NONE, boxSizing: 'border-box', borderRadius: '0px', borderBottomLeftRadius: '1px', minHeight: '35px', padding: component ? '3px' : '0', // padding: '3px', }, }, this.$system, this.$pod ) content.registerParentRoot(frame) this.content = content const column = new Div( { className: 'drawer-column', style: { position: 'absolute', bottom: '0px', left: '0px', width: '0px', height: 'calc(100% - 32px)', backgroundColor: 'none', borderWidth: '0px 1px 0px 0px', borderStyle: 'solid', borderColor: 'currentColor', }, }, this.$system, this.$pod ) this._column = column const drawer = new Div( { className: classnames('drawer', className), style: { ...DEFAULT_STYLE, ...style, }, }, this.$system, this.$pod ) this.drawer = drawer drawer.registerParentRoot(knob) drawer.registerParentRoot(content) drawer.registerParentRoot(column) const $element = parentElement($system) this.$subComponent = { drawer, knob, content, column, } this.$element = $element this.$slot = drawer.$slot this.$unbundled = false this.registerRoot(drawer) } private _drawer_style = (): Dict<string> => { const { style = {} } = this.$props return { ...DEFAULT_STYLE, top: `${this._y}px`, transform: this._transform(), ...style, } } onPropChanged(prop: string, current: any): void { // console.log('Drawer', 'onPropChanged', prop, current) if (prop === 'className') { this.drawer.setProp('className', current) } else if (prop === 'style') { const style = this._drawer_style() applyStyle(this.drawer.$element, style) const { backgroundColor = COLOR_NONE } = style // @ts-ignore this._knob.$slot['default'].$element.style.backgroundColor = backgroundColor } else if (prop === 'active') { // this._setActive(current) this.setActive(current) } else if (prop === 'y') { this._y = current this.drawer.$element.style.top = `${this._y}px` } else if (prop === 'width') { this._resize() } else if (prop === 'height') { this._resize() } else if (prop === 'hidden') { // this._resize() this._translate() } } private setActive = (active: boolean): void => { if (active) { if (this._active) { return } this._setActive(true) this.dispatchEvent('active', {}) } else { if (!this._active) { return } this._setActive(false) this.dispatchEvent('inactive', {}) } } private _transform = (): string => { const translateX = this._get_translate_x() return `translateX(${translateX}px)` } private _get_translate_x = (): number => { const { $width } = this.$context const { width = 0, component } = this.$props let translateX: number = 0 if (this._active) { translateX = -Math.min( component ? width + 2 + 6 - 1 : 0, $width - KNOB_HEIGHT ) } if (this._hidden) { translateX = -translateX + 34 } return translateX } private _setActive = (active: boolean) => { this._active = active this._knob.setProp('active', active) this._animate_transform(true) } private _translate = (): void => { const transform = this._transform() this.drawer.$element.style.transform = transform } private _resize = (): void => { console.log('Drawer', '_resize') const { $width } = this.$context const { width = 0, height = KNOB_HEIGHT, component } = this.$props this._translate() if (width > $width - KNOB_HEIGHT) { this.frame.$element.style.width = `${$width - KNOB_HEIGHT - 8}px` this.frame.$element.style.height = `${height + 2}px` this.content.$element.style.width = component ? `${$width - KNOB_HEIGHT}px` : '0' this.content.$element.style.height = `${height + 6}px` } else { this.frame.$element.style.width = `${width + 2}px` this.frame.$element.style.height = `${height + 2}px` this.content.$element.style.width = component ? `${width + 2 + 6}px` : '0' this.content.$element.style.height = `${height + 2 + 6}px` } } private _on_knob_click = (event: IOPointerEvent) => { this.setActive(!this._active) } private _on_knob_pointer_enter = (event: IOPointerEvent) => { this._hover = true } private _on_knob_pointer_leave = (event: IOPointerEvent) => { this._hover = false } private _drag: boolean = false private _drag_dy: number = 0 private _drag_pointer_id: number private _clamp_top = (top: number): number => { const { $height } = this.$context return Math.max(Math.min(top, $height - KNOB_HEIGHT), 0) } private _on_knob_pointer_down = (event: IOPointerEvent) => { // log('Drawer', '_on_knob_pointer_down') const { clientY, pointerId } = event this._knob.setPointerCapture(pointerId) this._drag_dy = this._y - clientY this._drag = true this._drag_pointer_id = pointerId const unlisten_knob = this._knob.addEventListeners([ makePointerMoveListener((event: IOPointerEvent) => { if (this._drag) { const { pointerId } = event if (this._drag_pointer_id === pointerId) { // console.log('Drawer', '_on_knob_pointer_move') const { clientY } = event this._y = this._clamp_top(clientY + this._drag_dy) this.drawer.$element.style.top = `${this._y}px` this.dispatchEvent('dragged', { y: this._y }) } } }), makePointerUpListener((event: IOPointerEvent) => { // log('Drawer', '_on_knob_pointer_up') const { pointerId } = event if (this._drag_pointer_id === pointerId) { this._drag = false this._knob.releasePointerCapture(pointerId) unlisten_knob() this.dispatchEvent('dragend', {}) } }), makePointerCancelListener(() => { // log('Drawer', '_on_knob_pointer_cancel') }), ]) this.dispatchEvent('dragstart', { y: this._y }) } private _on_container_resize = debounce(() => { if (this._active) { this._resize() } }, 300) private _frame_listener: Unlisten onMount() { // console.log('Drawer', 'onMount') this._frame_listener = addListeners(this.$context, [ makeResizeListener(this._on_container_resize), ]) } onUnmount() { this._frame_listener() } private _animate = (style: Dict<string>, animate: boolean): void => { const duration = animate ? ANIMATION_T_MS : 0 const fill = 'forwards' this.drawer.$element.animate([style], { duration, fill, }).onfinish = () => { mergeStyle(this.drawer.$element, style) } } private _animate_transform = (animate: boolean): void => { const transform = this._transform() this._animate( { transform, }, animate ) } public show(animate: boolean): void { this._hidden = false this._animate_transform(animate) } public hide(animate: boolean): void { this._hidden = true this._animate_transform(animate) } }
the_stack
import { RepeatType } from "@protobuf-ts/runtime"; import { ScalarType } from "@protobuf-ts/runtime"; import { MessageType } from "@protobuf-ts/runtime"; import { FileDescriptorProto } from "../descriptor"; /** * The version number of protocol compiler. * * @generated from protobuf message google.protobuf.compiler.Version */ export interface Version { /** * @generated from protobuf field: optional int32 major = 1; */ major?: number; /** * @generated from protobuf field: optional int32 minor = 2; */ minor?: number; /** * @generated from protobuf field: optional int32 patch = 3; */ patch?: number; /** * A suffix for alpha, beta or rc release, e.g., "alpha-1", "rc2". It should * be empty for mainline stable releases. * * @generated from protobuf field: optional string suffix = 4; */ suffix?: string; } /** * An encoded CodeGeneratorRequest is written to the plugin's stdin. * * @generated from protobuf message google.protobuf.compiler.CodeGeneratorRequest */ export interface CodeGeneratorRequest { /** * The .proto files that were explicitly listed on the command-line. The * code generator should generate code only for these files. Each file's * descriptor will be included in proto_file, below. * * @generated from protobuf field: repeated string file_to_generate = 1; */ fileToGenerate: string[]; /** * The generator parameter passed on the command-line. * * @generated from protobuf field: optional string parameter = 2; */ parameter?: string; /** * FileDescriptorProtos for all files in files_to_generate and everything * they import. The files will appear in topological order, so each file * appears before any file that imports it. * * protoc guarantees that all proto_files will be written after * the fields above, even though this is not technically guaranteed by the * protobuf wire format. This theoretically could allow a plugin to stream * in the FileDescriptorProtos and handle them one by one rather than read * the entire set into memory at once. However, as of this writing, this * is not similarly optimized on protoc's end -- it will store all fields in * memory at once before sending them to the plugin. * * Type names of fields and extensions in the FileDescriptorProto are always * fully qualified. * * @generated from protobuf field: repeated google.protobuf.FileDescriptorProto proto_file = 15; */ protoFile: FileDescriptorProto[]; /** * The version number of protocol compiler. * * @generated from protobuf field: optional google.protobuf.compiler.Version compiler_version = 3; */ compilerVersion?: Version; } /** * The plugin writes an encoded CodeGeneratorResponse to stdout. * * @generated from protobuf message google.protobuf.compiler.CodeGeneratorResponse */ export interface CodeGeneratorResponse { /** * Error message. If non-empty, code generation failed. The plugin process * should exit with status code zero even if it reports an error in this way. * * This should be used to indicate errors in .proto files which prevent the * code generator from generating correct code. Errors which indicate a * problem in protoc itself -- such as the input CodeGeneratorRequest being * unparseable -- should be reported by writing a message to stderr and * exiting with a non-zero status code. * * @generated from protobuf field: optional string error = 1; */ error?: string; /** * A bitmask of supported features that the code generator supports. * This is a bitwise "or" of values from the Feature enum. * * @generated from protobuf field: optional uint64 supported_features = 2; */ supportedFeatures?: string; /** * @generated from protobuf field: repeated google.protobuf.compiler.CodeGeneratorResponse.File file = 15; */ file: CodeGeneratorResponse_File[]; } /** * Represents a single generated file. * * @generated from protobuf message google.protobuf.compiler.CodeGeneratorResponse.File */ export interface CodeGeneratorResponse_File { /** * The file name, relative to the output directory. The name must not * contain "." or ".." components and must be relative, not be absolute (so, * the file cannot lie outside the output directory). "/" must be used as * the path separator, not "\". * * If the name is omitted, the content will be appended to the previous * file. This allows the generator to break large files into small chunks, * and allows the generated text to be streamed back to protoc so that large * files need not reside completely in memory at one time. Note that as of * this writing protoc does not optimize for this -- it will read the entire * CodeGeneratorResponse before writing files to disk. * * @generated from protobuf field: optional string name = 1; */ name?: string; /** * If non-empty, indicates that the named file should already exist, and the * content here is to be inserted into that file at a defined insertion * point. This feature allows a code generator to extend the output * produced by another code generator. The original generator may provide * insertion points by placing special annotations in the file that look * like: * @@protoc_insertion_point(NAME) * The annotation can have arbitrary text before and after it on the line, * which allows it to be placed in a comment. NAME should be replaced with * an identifier naming the point -- this is what other generators will use * as the insertion_point. Code inserted at this point will be placed * immediately above the line containing the insertion point (thus multiple * insertions to the same point will come out in the order they were added). * The double-@ is intended to make it unlikely that the generated code * could contain things that look like insertion points by accident. * * For example, the C++ code generator places the following line in the * .pb.h files that it generates: * // @@protoc_insertion_point(namespace_scope) * This line appears within the scope of the file's package namespace, but * outside of any particular class. Another plugin can then specify the * insertion_point "namespace_scope" to generate additional classes or * other declarations that should be placed in this scope. * * Note that if the line containing the insertion point begins with * whitespace, the same whitespace will be added to every line of the * inserted text. This is useful for languages like Python, where * indentation matters. In these languages, the insertion point comment * should be indented the same amount as any inserted code will need to be * in order to work correctly in that context. * * The code generator that generates the initial file and the one which * inserts into it must both run as part of a single invocation of protoc. * Code generators are executed in the order in which they appear on the * command line. * * If |insertion_point| is present, |name| must also be present. * * @generated from protobuf field: optional string insertion_point = 2; */ insertionPoint?: string; /** * The file contents. * * @generated from protobuf field: optional string content = 15; */ content?: string; } /** * Sync with code_generator.h. * * @generated from protobuf enum google.protobuf.compiler.CodeGeneratorResponse.Feature */ export enum CodeGeneratorResponse_Feature { /** * @generated from protobuf enum value: FEATURE_NONE = 0; */ NONE = 0, /** * @generated from protobuf enum value: FEATURE_PROTO3_OPTIONAL = 1; */ PROTO3_OPTIONAL = 1 } /** * Type for protobuf message google.protobuf.compiler.Version */ class Version$Type extends MessageType<Version> { constructor() { super("google.protobuf.compiler.Version", [ { no: 1, name: "major", kind: "scalar", opt: true, T: ScalarType.INT32 }, { no: 2, name: "minor", kind: "scalar", opt: true, T: ScalarType.INT32 }, { no: 3, name: "patch", kind: "scalar", opt: true, T: ScalarType.INT32 }, { no: 4, name: "suffix", kind: "scalar", opt: true, T: ScalarType.STRING } ]); } } export const Version = new Version$Type(); /** * Type for protobuf message google.protobuf.compiler.CodeGeneratorRequest */ class CodeGeneratorRequest$Type extends MessageType<CodeGeneratorRequest> { constructor() { super("google.protobuf.compiler.CodeGeneratorRequest", [ { no: 1, name: "file_to_generate", kind: "scalar", repeat: RepeatType.UNPACKED, T: ScalarType.STRING }, { no: 2, name: "parameter", kind: "scalar", opt: true, T: ScalarType.STRING }, { no: 15, name: "proto_file", kind: "message", repeat: RepeatType.UNPACKED, T: () => FileDescriptorProto }, { no: 3, name: "compiler_version", kind: "message", T: () => Version } ]); } } export const CodeGeneratorRequest = new CodeGeneratorRequest$Type(); /** * Type for protobuf message google.protobuf.compiler.CodeGeneratorResponse */ class CodeGeneratorResponse$Type extends MessageType<CodeGeneratorResponse> { constructor() { super("google.protobuf.compiler.CodeGeneratorResponse", [ { no: 1, name: "error", kind: "scalar", opt: true, T: ScalarType.STRING }, { no: 2, name: "supported_features", kind: "scalar", opt: true, T: ScalarType.UINT64 }, { no: 15, name: "file", kind: "message", repeat: RepeatType.UNPACKED, T: () => CodeGeneratorResponse_File } ]); } } export const CodeGeneratorResponse = new CodeGeneratorResponse$Type(); /** * Type for protobuf message google.protobuf.compiler.CodeGeneratorResponse.File */ class CodeGeneratorResponse_File$Type extends MessageType<CodeGeneratorResponse_File> { constructor() { super("google.protobuf.compiler.CodeGeneratorResponse.File", [ { no: 1, name: "name", kind: "scalar", opt: true, T: ScalarType.STRING }, { no: 2, name: "insertion_point", kind: "scalar", opt: true, T: ScalarType.STRING }, { no: 15, name: "content", kind: "scalar", opt: true, T: ScalarType.STRING } ]); } } export const CodeGeneratorResponse_File = new CodeGeneratorResponse_File$Type();
the_stack
import { AccessLevelList } from "../shared/access-level"; import { PolicyStatement } from "../shared"; /** * Statement provider for service [route53](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonroute53.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ export class Route53 extends PolicyStatement { public servicePrefix = 'route53'; /** * Statement provider for service [route53](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonroute53.html). * * @param sid [SID](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_sid.html) of the statement */ constructor (sid?: string) { super(sid); } /** * Grants permission to activate a key-signing key so that it can be used for signing by DNSSEC * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_ActivateKeySigningKey.html */ public toActivateKeySigningKey() { return this.to('ActivateKeySigningKey'); } /** * Grants permission to associate an additional Amazon VPC with a private hosted zone * * Access Level: Write * * Dependent actions: * - ec2:DescribeVpcs * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_AssociateVPCWithHostedZone.html */ public toAssociateVPCWithHostedZone() { return this.to('AssociateVPCWithHostedZone'); } /** * Grants permission to create, update, or delete a record, which contains authoritative DNS information for a specified domain or subdomain name * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_ChangeResourceRecordSets.html */ public toChangeResourceRecordSets() { return this.to('ChangeResourceRecordSets'); } /** * Grants permission to add, edit, or delete tags for a health check or a hosted zone * * Access Level: Tagging * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_ChangeTagsForResource.html */ public toChangeTagsForResource() { return this.to('ChangeTagsForResource'); } /** * Grants permission to create a new health check, which monitors the health and performance of your web applications, web servers, and other resources * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_CreateHealthCheck.html */ public toCreateHealthCheck() { return this.to('CreateHealthCheck'); } /** * Grants permission to create a public hosted zone, which you use to specify how the Domain Name System (DNS) routes traffic on the Internet for a domain, such as example.com, and its subdomains * * Access Level: Write * * Dependent actions: * - ec2:DescribeVpcs * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_CreateHostedZone.html */ public toCreateHostedZone() { return this.to('CreateHostedZone'); } /** * Grants permission to create a new key-signing key associated with a hosted zone * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_CreateKeySigningKey.html */ public toCreateKeySigningKey() { return this.to('CreateKeySigningKey'); } /** * Grants permission to create a configuration for DNS query logging * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_CreateQueryLoggingConfig.html */ public toCreateQueryLoggingConfig() { return this.to('CreateQueryLoggingConfig'); } /** * Grants permission to create a delegation set (a group of four name servers) that can be reused by multiple hosted zones * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_CreateReusableDelegationSet.html */ public toCreateReusableDelegationSet() { return this.to('CreateReusableDelegationSet'); } /** * Grants permission to create a traffic policy, which you use to create multiple DNS records for one domain name (such as example.com) or one subdomain name (such as www.example.com) * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_CreateTrafficPolicy.html */ public toCreateTrafficPolicy() { return this.to('CreateTrafficPolicy'); } /** * Grants permission to create records in a specified hosted zone based on the settings in a specified traffic policy version * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_CreateTrafficPolicyInstance.html */ public toCreateTrafficPolicyInstance() { return this.to('CreateTrafficPolicyInstance'); } /** * Grants permission to create a new version of an existing traffic policy * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_CreateTrafficPolicyVersion.html */ public toCreateTrafficPolicyVersion() { return this.to('CreateTrafficPolicyVersion'); } /** * Grants permission to authorize the AWS account that created a specified VPC to submit an AssociateVPCWithHostedZone request, which associates the VPC with a specified hosted zone that was created by a different account * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_CreateVPCAssociationAuthorization.html */ public toCreateVPCAssociationAuthorization() { return this.to('CreateVPCAssociationAuthorization'); } /** * Grants permission to deactivate a key-signing key so that it will not be used for signing by DNSSEC * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_DeactivateKeySigningKey.html */ public toDeactivateKeySigningKey() { return this.to('DeactivateKeySigningKey'); } /** * Grants permission to delete a health check * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_DeleteHealthCheck.html */ public toDeleteHealthCheck() { return this.to('DeleteHealthCheck'); } /** * Grants permission to delete a hosted zone * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_DeleteHostedZone.html */ public toDeleteHostedZone() { return this.to('DeleteHostedZone'); } /** * Grants permission to delete a key-signing key * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_DeleteKeySigningKey.html */ public toDeleteKeySigningKey() { return this.to('DeleteKeySigningKey'); } /** * Grants permission to delete a configuration for DNS query logging * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_DeleteQueryLoggingConfig.html */ public toDeleteQueryLoggingConfig() { return this.to('DeleteQueryLoggingConfig'); } /** * Grants permission to delete a reusable delegation set * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_DeleteReusableDelegationSet.html */ public toDeleteReusableDelegationSet() { return this.to('DeleteReusableDelegationSet'); } /** * Grants permission to delete a traffic policy * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_DeleteTrafficPolicy.html */ public toDeleteTrafficPolicy() { return this.to('DeleteTrafficPolicy'); } /** * Grants permission to delete a traffic policy instance and all the records that Route 53 created when you created the instance * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_DeleteTrafficPolicyInstance.html */ public toDeleteTrafficPolicyInstance() { return this.to('DeleteTrafficPolicyInstance'); } /** * Grants permission to remove authorization for associating an Amazon Virtual Private Cloud with a Route 53 private hosted zone * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_DeleteVPCAssociationAuthorization.html */ public toDeleteVPCAssociationAuthorization() { return this.to('DeleteVPCAssociationAuthorization'); } /** * Grants permission to disable DNSSEC signing in a specific hosted zone * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_DisableHostedZoneDNSSEC.html */ public toDisableHostedZoneDNSSEC() { return this.to('DisableHostedZoneDNSSEC'); } /** * Grants permission to disassociate an Amazon Virtual Private Cloud from a Route 53 private hosted zone * * Access Level: Write * * Dependent actions: * - ec2:DescribeVpcs * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_DisassociateVPCFromHostedZone.html */ public toDisassociateVPCFromHostedZone() { return this.to('DisassociateVPCFromHostedZone'); } /** * Grants permission to enable DNSSEC signing in a specific hosted zone * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_EnableHostedZoneDNSSEC.html */ public toEnableHostedZoneDNSSEC() { return this.to('EnableHostedZoneDNSSEC'); } /** * Grants permission to get the specified limit for the current account, for example, the maximum number of health checks that you can create using the account * * Access Level: Read * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_GetAccountLimit.html */ public toGetAccountLimit() { return this.to('GetAccountLimit'); } /** * Grants permission to get the current status of a request to create, update, or delete one or more records * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_GetChange.html */ public toGetChange() { return this.to('GetChange'); } /** * Grants permission to get a list of the IP ranges that are used by Route 53 health checkers to check the health of your resources * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_GetCheckerIpRanges.html */ public toGetCheckerIpRanges() { return this.to('GetCheckerIpRanges'); } /** * Grants permission to get information about DNSSEC for a specific hosted zone, including the key-signing keys in the hosted zone * * Access Level: Read * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_GetDNSSEC.html */ public toGetDNSSEC() { return this.to('GetDNSSEC'); } /** * Grants permission to get information about whether a specified geographic location is supported for Route 53 geolocation records * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_GetGeoLocation.html */ public toGetGeoLocation() { return this.to('GetGeoLocation'); } /** * Grants permission to get information about a specified health check * * Access Level: Read * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_GetHealthCheck.html */ public toGetHealthCheck() { return this.to('GetHealthCheck'); } /** * Grants permission to get the number of health checks that are associated with the current AWS account * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_GetHealthCheckCount.html */ public toGetHealthCheckCount() { return this.to('GetHealthCheckCount'); } /** * Grants permission to get the reason that a specified health check failed most recently * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_GetHealthCheckLastFailureReason.html */ public toGetHealthCheckLastFailureReason() { return this.to('GetHealthCheckLastFailureReason'); } /** * Grants permission to get the status of a specified health check * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_GetHealthCheckStatus.html */ public toGetHealthCheckStatus() { return this.to('GetHealthCheckStatus'); } /** * Grants permission to get information about a specified hosted zone including the four name servers that Route 53 assigned to the hosted zone * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_GetHostedZone.html */ public toGetHostedZone() { return this.to('GetHostedZone'); } /** * Grants permission to get the number of hosted zones that are associated with the current AWS account * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_GetHostedZoneCount.html */ public toGetHostedZoneCount() { return this.to('GetHostedZoneCount'); } /** * Grants permission to get the specified limit for a specified hosted zone * * Access Level: Read * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_GetHostedZoneLimit.html */ public toGetHostedZoneLimit() { return this.to('GetHostedZoneLimit'); } /** * Grants permission to get information about a specified configuration for DNS query logging * * Access Level: Read * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_GetQueryLoggingConfig.html */ public toGetQueryLoggingConfig() { return this.to('GetQueryLoggingConfig'); } /** * Grants permission to get information about a specified reusable delegation set, including the four name servers that are assigned to the delegation set * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_GetReusableDelegationSet.html */ public toGetReusableDelegationSet() { return this.to('GetReusableDelegationSet'); } /** * Grants permission to get the maximum number of hosted zones that you can associate with the specified reusable delegation set * * Access Level: Read * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_GetReusableDelegationSetLimit.html */ public toGetReusableDelegationSetLimit() { return this.to('GetReusableDelegationSetLimit'); } /** * Grants permission to get information about a specified traffic policy version * * Access Level: Read * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_GetTrafficPolicy.html */ public toGetTrafficPolicy() { return this.to('GetTrafficPolicy'); } /** * Grants permission to get information about a specified traffic policy instance * * Access Level: Read * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_GetTrafficPolicyInstance.html */ public toGetTrafficPolicyInstance() { return this.to('GetTrafficPolicyInstance'); } /** * Grants permission to get the number of traffic policy instances that are associated with the current AWS account * * Access Level: Read * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_GetTrafficPolicyInstanceCount.html */ public toGetTrafficPolicyInstanceCount() { return this.to('GetTrafficPolicyInstanceCount'); } /** * Grants permission to get a list of geographic locations that Route 53 supports for geolocation * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_ListGeoLocations.html */ public toListGeoLocations() { return this.to('ListGeoLocations'); } /** * Grants permission to get a list of the health checks that are associated with the current AWS account * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_ListHealthChecks.html */ public toListHealthChecks() { return this.to('ListHealthChecks'); } /** * Grants permission to get a list of the public and private hosted zones that are associated with the current AWS account * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_ListHostedZones.html */ public toListHostedZones() { return this.to('ListHostedZones'); } /** * Grants permission to get a list of your hosted zones in lexicographic order. Hosted zones are sorted by name with the labels reversed, for example, com.example.www. * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_ListHostedZonesByName.html */ public toListHostedZonesByName() { return this.to('ListHostedZonesByName'); } /** * Grants permission to get a list of all the private hosted zones that a specified VPC is associated with * * Access Level: List * * Dependent actions: * - ec2:DescribeVpcs * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_ListHostedZonesByVPC.html */ public toListHostedZonesByVPC() { return this.to('ListHostedZonesByVPC'); } /** * Grants permission to list the configurations for DNS query logging that are associated with the current AWS account or the configuration that is associated with a specified hosted zone. * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_ListQueryLoggingConfigs.html */ public toListQueryLoggingConfigs() { return this.to('ListQueryLoggingConfigs'); } /** * Grants permission to list the records in a specified hosted zone * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_ListResourceRecordSets.html */ public toListResourceRecordSets() { return this.to('ListResourceRecordSets'); } /** * Grants permission to list the reusable delegation sets that are associated with the current AWS account. * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_ListReusableDelegationSets.html */ public toListReusableDelegationSets() { return this.to('ListReusableDelegationSets'); } /** * Grants permission to list tags for one health check or hosted zone * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_ListTagsForResource.html */ public toListTagsForResource() { return this.to('ListTagsForResource'); } /** * Grants permission to list tags for up to 10 health checks or hosted zones * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_ListTagsForResources.html */ public toListTagsForResources() { return this.to('ListTagsForResources'); } /** * Grants permission to get information about the latest version for every traffic policy that is associated with the current AWS account. Policies are listed in the order in which they were created. * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_ListTrafficPolicies.html */ public toListTrafficPolicies() { return this.to('ListTrafficPolicies'); } /** * Grants permission to get information about the traffic policy instances that you created by using the current AWS account * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_ListTrafficPolicyInstances.html */ public toListTrafficPolicyInstances() { return this.to('ListTrafficPolicyInstances'); } /** * Grants permission to get information about the traffic policy instances that you created in a specified hosted zone * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_ListTrafficPolicyInstancesByHostedZone.html */ public toListTrafficPolicyInstancesByHostedZone() { return this.to('ListTrafficPolicyInstancesByHostedZone'); } /** * Grants permission to get information about the traffic policy instances that you created using a specified traffic policy version * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_ListTrafficPolicyInstancesByPolicy.html */ public toListTrafficPolicyInstancesByPolicy() { return this.to('ListTrafficPolicyInstancesByPolicy'); } /** * Grants permission to get information about all the versions for a specified traffic policy * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_ListTrafficPolicyVersions.html */ public toListTrafficPolicyVersions() { return this.to('ListTrafficPolicyVersions'); } /** * Grants permission to get a list of the VPCs that were created by other accounts and that can be associated with a specified hosted zone * * Access Level: List * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_ListVPCAssociationAuthorizations.html */ public toListVPCAssociationAuthorizations() { return this.to('ListVPCAssociationAuthorizations'); } /** * Grants permission to get the value that Route 53 returns in response to a DNS query for a specified record name and type * * Access Level: Read * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_TestDNSAnswer.html */ public toTestDNSAnswer() { return this.to('TestDNSAnswer'); } /** * Grants permission to update an existing health check * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_UpdateHealthCheck.html */ public toUpdateHealthCheck() { return this.to('UpdateHealthCheck'); } /** * Grants permission to update the comment for a specified hosted zone * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_UpdateHostedZoneComment.html */ public toUpdateHostedZoneComment() { return this.to('UpdateHostedZoneComment'); } /** * Grants permission to update the comment for a specified traffic policy version * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_UpdateTrafficPolicyComment.html */ public toUpdateTrafficPolicyComment() { return this.to('UpdateTrafficPolicyComment'); } /** * Grants permission to update the records in a specified hosted zone that were created based on the settings in a specified traffic policy version * * Access Level: Write * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_UpdateTrafficPolicyInstance.html */ public toUpdateTrafficPolicyInstance() { return this.to('UpdateTrafficPolicyInstance'); } protected accessLevelList: AccessLevelList = { "Write": [ "ActivateKeySigningKey", "AssociateVPCWithHostedZone", "ChangeResourceRecordSets", "CreateHealthCheck", "CreateHostedZone", "CreateKeySigningKey", "CreateQueryLoggingConfig", "CreateReusableDelegationSet", "CreateTrafficPolicy", "CreateTrafficPolicyInstance", "CreateTrafficPolicyVersion", "CreateVPCAssociationAuthorization", "DeactivateKeySigningKey", "DeleteHealthCheck", "DeleteHostedZone", "DeleteKeySigningKey", "DeleteQueryLoggingConfig", "DeleteReusableDelegationSet", "DeleteTrafficPolicy", "DeleteTrafficPolicyInstance", "DeleteVPCAssociationAuthorization", "DisableHostedZoneDNSSEC", "DisassociateVPCFromHostedZone", "EnableHostedZoneDNSSEC", "UpdateHealthCheck", "UpdateHostedZoneComment", "UpdateTrafficPolicyComment", "UpdateTrafficPolicyInstance" ], "Tagging": [ "ChangeTagsForResource" ], "Read": [ "GetAccountLimit", "GetDNSSEC", "GetHealthCheck", "GetHostedZoneLimit", "GetQueryLoggingConfig", "GetReusableDelegationSetLimit", "GetTrafficPolicy", "GetTrafficPolicyInstance", "GetTrafficPolicyInstanceCount", "TestDNSAnswer" ], "List": [ "GetChange", "GetCheckerIpRanges", "GetGeoLocation", "GetHealthCheckCount", "GetHealthCheckLastFailureReason", "GetHealthCheckStatus", "GetHostedZone", "GetHostedZoneCount", "GetReusableDelegationSet", "ListGeoLocations", "ListHealthChecks", "ListHostedZones", "ListHostedZonesByName", "ListHostedZonesByVPC", "ListQueryLoggingConfigs", "ListResourceRecordSets", "ListReusableDelegationSets", "ListTagsForResource", "ListTagsForResources", "ListTrafficPolicies", "ListTrafficPolicyInstances", "ListTrafficPolicyInstancesByHostedZone", "ListTrafficPolicyInstancesByPolicy", "ListTrafficPolicyVersions", "ListVPCAssociationAuthorizations" ] }; /** * Adds a resource of type change to the statement * * https://docs.aws.amazon.com/Route53/latest/APIReference/API_Change.html * * @param id - Identifier for the id. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onChange(id: string, partition?: string) { var arn = 'arn:${Partition}:route53:::change/${Id}'; arn = arn.replace('${Id}', id); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type delegationset to the statement * * https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/route-53-concepts.html#route-53-concepts-reusable-delegation-set * * @param id - Identifier for the id. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onDelegationset(id: string, partition?: string) { var arn = 'arn:${Partition}:route53:::delegationset/${Id}'; arn = arn.replace('${Id}', id); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type healthcheck to the statement * * https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/route-53-concepts.html#route-53-concepts-health-check * * @param id - Identifier for the id. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onHealthcheck(id: string, partition?: string) { var arn = 'arn:${Partition}:route53:::healthcheck/${Id}'; arn = arn.replace('${Id}', id); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type hostedzone to the statement * * https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/route-53-concepts.html#route-53-concepts-hosted-zone * * @param id - Identifier for the id. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onHostedzone(id: string, partition?: string) { var arn = 'arn:${Partition}:route53:::hostedzone/${Id}'; arn = arn.replace('${Id}', id); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type trafficpolicy to the statement * * https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/traffic-policies.html * * @param id - Identifier for the id. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onTrafficpolicy(id: string, partition?: string) { var arn = 'arn:${Partition}:route53:::trafficpolicy/${Id}'; arn = arn.replace('${Id}', id); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type trafficpolicyinstance to the statement * * https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/traffic-policy-records.html * * @param id - Identifier for the id. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onTrafficpolicyinstance(id: string, partition?: string) { var arn = 'arn:${Partition}:route53:::trafficpolicyinstance/${Id}'; arn = arn.replace('${Id}', id); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type queryloggingconfig to the statement * * https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/query-logs.html * * @param id - Identifier for the id. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onQueryloggingconfig(id: string, partition?: string) { var arn = 'arn:${Partition}:route53:::queryloggingconfig/${Id}'; arn = arn.replace('${Id}', id); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } /** * Adds a resource of type vpc to the statement * * https://docs.aws.amazon.com/vpc/latest/userguide/VPC_Subnets.html * * @param vpcId - Identifier for the vpcId. * @param account - Account of the resource; defaults to empty string: all accounts. * @param region - Region of the resource; defaults to empty string: all regions. * @param partition - Partition of the AWS account [aws, aws-cn, aws-us-gov]; defaults to `aws`. */ public onVpc(vpcId: string, account?: string, region?: string, partition?: string) { var arn = 'arn:${Partition}:ec2:${Region}:${Account}:vpc/${VpcId}'; arn = arn.replace('${VpcId}', vpcId); arn = arn.replace('${Account}', account || '*'); arn = arn.replace('${Region}', region || '*'); arn = arn.replace('${Partition}', partition || 'aws'); return this.on(arn); } }
the_stack
'use strict'; import {createTrieFromBase64} from './Trie'; import {base64} from './linebreak-trie'; import {fromCodePoint, toCodePoints} from './Util'; export const LETTER_NUMBER_MODIFIER = 50; // Non-tailorable Line Breaking Classes const BK = 1; // Cause a line break (after) const CR = 2; // Cause a line break (after), except between CR and LF const LF = 3; // Cause a line break (after) const CM = 4; // Prohibit a line break between the character and the preceding character const NL = 5; // Cause a line break (after) const SG = 6; // Do not occur in well-formed text const WJ = 7; // Prohibit line breaks before and after const ZW = 8; // Provide a break opportunity const GL = 9; // Prohibit line breaks before and after const SP = 10; // Enable indirect line breaks const ZWJ = 11; // Prohibit line breaks within joiner sequences // Break Opportunities const B2 = 12; // Provide a line break opportunity before and after the character const BA = 13; // Generally provide a line break opportunity after the character const BB = 14; // Generally provide a line break opportunity before the character const HY = 15; // Provide a line break opportunity after the character, except in numeric context const CB = 16; // Provide a line break opportunity contingent on additional information // Characters Prohibiting Certain Breaks const CL = 17; // Prohibit line breaks before const CP = 18; // Prohibit line breaks before const EX = 19; // Prohibit line breaks before const IN = 20; // Allow only indirect line breaks between pairs const NS = 21; // Allow only indirect line breaks before const OP = 22; // Prohibit line breaks after const QU = 23; // Act like they are both opening and closing // Numeric Context const IS = 24; // Prevent breaks after any and before numeric const NU = 25; // Form numeric expressions for line breaking purposes const PO = 26; // Do not break following a numeric expression const PR = 27; // Do not break in front of a numeric expression const SY = 28; // Prevent a break before; and allow a break after // Other Characters const AI = 29; // Act like AL when the resolvedEAW is N; otherwise; act as ID const AL = 30; // Are alphabetic characters or symbols that are used with alphabetic characters const CJ = 31; // Treat as NS or ID for strict or normal breaking. const EB = 32; // Do not break from following Emoji Modifier const EM = 33; // Do not break from preceding Emoji Base const H2 = 34; // Form Korean syllable blocks const H3 = 35; // Form Korean syllable blocks const HL = 36; // Do not break around a following hyphen; otherwise act as Alphabetic const ID = 37; // Break before or after; except in some numeric context const JL = 38; // Form Korean syllable blocks const JV = 39; // Form Korean syllable blocks const JT = 40; // Form Korean syllable blocks const RI = 41; // Keep pairs together. For pairs; break before and after other classes const SA = 42; // Provide a line break opportunity contingent on additional, language-specific context analysis const XX = 43; // Have as yet unknown line breaking behavior or unassigned code positions const ea_OP = [0x2329, 0xff08]; export const classes: {[key: string]: number} = { BK, CR, LF, CM, NL, SG, WJ, ZW, GL, SP, ZWJ, B2, BA, BB, HY, CB, CL, CP, EX, IN, NS, OP, QU, IS, NU, PO, PR, SY, AI, AL, CJ, EB, EM, H2, H3, HL, ID, JL, JV, JT, RI, SA, XX, }; export const BREAK_MANDATORY = '!'; export const BREAK_NOT_ALLOWED = '×'; export const BREAK_ALLOWED = '÷'; export const UnicodeTrie = createTrieFromBase64(base64); const ALPHABETICS = [AL, HL]; const HARD_LINE_BREAKS = [BK, CR, LF, NL]; const SPACE = [SP, ZW]; const PREFIX_POSTFIX = [PR, PO]; const LINE_BREAKS = HARD_LINE_BREAKS.concat(SPACE); const KOREAN_SYLLABLE_BLOCK = [JL, JV, JT, H2, H3]; const HYPHEN = [HY, BA]; export const codePointsToCharacterClasses = ( codePoints: number[], lineBreak: string = 'strict' ): [number[], number[], boolean[]] => { const types: number[] = []; const indices: number[] = []; const categories: boolean[] = []; codePoints.forEach((codePoint, index) => { let classType = UnicodeTrie.get(codePoint); if (classType > LETTER_NUMBER_MODIFIER) { categories.push(true); classType -= LETTER_NUMBER_MODIFIER; } else { categories.push(false); } if (['normal', 'auto', 'loose'].indexOf(lineBreak) !== -1) { // U+2010, – U+2013, 〜 U+301C, ゠ U+30A0 if ([0x2010, 0x2013, 0x301c, 0x30a0].indexOf(codePoint) !== -1) { indices.push(index); return types.push(CB); } } if (classType === CM || classType === ZWJ) { // LB10 Treat any remaining combining mark or ZWJ as AL. if (index === 0) { indices.push(index); return types.push(AL); } // LB9 Do not break a combining character sequence; treat it as if it has the line breaking class of // the base character in all of the following rules. Treat ZWJ as if it were CM. const prev = types[index - 1]; if (LINE_BREAKS.indexOf(prev) === -1) { indices.push(indices[index - 1]); return types.push(prev); } indices.push(index); return types.push(AL); } indices.push(index); if (classType === CJ) { return types.push(lineBreak === 'strict' ? NS : ID); } if (classType === SA) { return types.push(AL); } if (classType === AI) { return types.push(AL); } // For supplementary characters, a useful default is to treat characters in the range 10000..1FFFD as AL // and characters in the ranges 20000..2FFFD and 30000..3FFFD as ID, until the implementation can be revised // to take into account the actual line breaking properties for these characters. if (classType === XX) { if ((codePoint >= 0x20000 && codePoint <= 0x2fffd) || (codePoint >= 0x30000 && codePoint <= 0x3fffd)) { return types.push(ID); } else { return types.push(AL); } } types.push(classType); }); return [indices, types, categories]; }; const isAdjacentWithSpaceIgnored = ( a: number[] | number, b: number, currentIndex: number, classTypes: number[] ): boolean => { const current = classTypes[currentIndex]; if (Array.isArray(a) ? a.indexOf(current) !== -1 : a === current) { let i = currentIndex; while (i <= classTypes.length) { i++; let next = classTypes[i]; if (next === b) { return true; } if (next !== SP) { break; } } } if (current === SP) { let i = currentIndex; while (i > 0) { i--; const prev = classTypes[i]; if (Array.isArray(a) ? a.indexOf(prev) !== -1 : a === prev) { let n = currentIndex; while (n <= classTypes.length) { n++; let next = classTypes[n]; if (next === b) { return true; } if (next !== SP) { break; } } } if (prev !== SP) { break; } } } return false; }; const previousNonSpaceClassType = (currentIndex: number, classTypes: number[]): number => { let i = currentIndex; while (i >= 0) { let type = classTypes[i]; if (type === SP) { i--; } else { return type; } } return 0; }; export type BREAK_OPPORTUNITIES = typeof BREAK_NOT_ALLOWED | typeof BREAK_ALLOWED | typeof BREAK_MANDATORY; const _lineBreakAtIndex = ( codePoints: number[], classTypes: number[], indicies: number[], index: number, forbiddenBreaks?: boolean[] ): BREAK_OPPORTUNITIES => { if (indicies[index] === 0) { return BREAK_NOT_ALLOWED; } let currentIndex = index - 1; if (Array.isArray(forbiddenBreaks) && forbiddenBreaks[currentIndex] === true) { return BREAK_NOT_ALLOWED; } let beforeIndex = currentIndex - 1; let afterIndex = currentIndex + 1; let current = classTypes[currentIndex]; // LB4 Always break after hard line breaks. // LB5 Treat CR followed by LF, as well as CR, LF, and NL as hard line breaks. let before = beforeIndex >= 0 ? classTypes[beforeIndex] : 0; let next = classTypes[afterIndex]; if (current === CR && next === LF) { return BREAK_NOT_ALLOWED; } if (HARD_LINE_BREAKS.indexOf(current) !== -1) { return BREAK_MANDATORY; } // LB6 Do not break before hard line breaks. if (HARD_LINE_BREAKS.indexOf(next) !== -1) { return BREAK_NOT_ALLOWED; } // LB7 Do not break before spaces or zero width space. if (SPACE.indexOf(next) !== -1) { return BREAK_NOT_ALLOWED; } // LB8 Break before any character following a zero-width space, even if one or more spaces intervene. if (previousNonSpaceClassType(currentIndex, classTypes) === ZW) { return BREAK_ALLOWED; } // LB8a Do not break after a zero width joiner. if (UnicodeTrie.get(codePoints[currentIndex]) === ZWJ) { return BREAK_NOT_ALLOWED; } // zwj emojis if ((current === EB || current === EM) && UnicodeTrie.get(codePoints[afterIndex]) === ZWJ) { return BREAK_NOT_ALLOWED; } // LB11 Do not break before or after Word joiner and related characters. if (current === WJ || next === WJ) { return BREAK_NOT_ALLOWED; } // LB12 Do not break after NBSP and related characters. if (current === GL) { return BREAK_NOT_ALLOWED; } // LB12a Do not break before NBSP and related characters, except after spaces and hyphens. if ([SP, BA, HY].indexOf(current) === -1 && next === GL) { return BREAK_NOT_ALLOWED; } // LB13 Do not break before ‘]’ or ‘!’ or ‘;’ or ‘/’, even after spaces. if ([CL, CP, EX, IS, SY].indexOf(next) !== -1) { return BREAK_NOT_ALLOWED; } // LB14 Do not break after ‘[’, even after spaces. if (previousNonSpaceClassType(currentIndex, classTypes) === OP) { return BREAK_NOT_ALLOWED; } // LB15 Do not break within ‘”[’, even with intervening spaces. if (isAdjacentWithSpaceIgnored(QU, OP, currentIndex, classTypes)) { return BREAK_NOT_ALLOWED; } // LB16 Do not break between closing punctuation and a nonstarter (lb=NS), even with intervening spaces. if (isAdjacentWithSpaceIgnored([CL, CP], NS, currentIndex, classTypes)) { return BREAK_NOT_ALLOWED; } // LB17 Do not break within ‘——’, even with intervening spaces. if (isAdjacentWithSpaceIgnored(B2, B2, currentIndex, classTypes)) { return BREAK_NOT_ALLOWED; } // LB18 Break after spaces. if (current === SP) { return BREAK_ALLOWED; } // LB19 Do not break before or after quotation marks, such as ‘ ” ’. if (current === QU || next === QU) { return BREAK_NOT_ALLOWED; } // LB20 Break before and after unresolved CB. if (next === CB || current === CB) { return BREAK_ALLOWED; } // LB21 Do not break before hyphen-minus, other hyphens, fixed-width spaces, small kana, and other non-starters, or after acute accents. if ([BA, HY, NS].indexOf(next) !== -1 || current === BB) { return BREAK_NOT_ALLOWED; } // LB21a Don't break after Hebrew + Hyphen. if (before === HL && HYPHEN.indexOf(current) !== -1) { return BREAK_NOT_ALLOWED; } // LB21b Don’t break between Solidus and Hebrew letters. if (current === SY && next === HL) { return BREAK_NOT_ALLOWED; } // LB22 Do not break before ellipsis. if (next === IN) { return BREAK_NOT_ALLOWED; } // LB23 Do not break between digits and letters. if ((ALPHABETICS.indexOf(next) !== -1 && current === NU) || (ALPHABETICS.indexOf(current) !== -1 && next === NU)) { return BREAK_NOT_ALLOWED; } // LB23a Do not break between numeric prefixes and ideographs, or between ideographs and numeric postfixes. if ( (current === PR && [ID, EB, EM].indexOf(next) !== -1) || ([ID, EB, EM].indexOf(current) !== -1 && next === PO) ) { return BREAK_NOT_ALLOWED; } // LB24 Do not break between numeric prefix/postfix and letters, or between letters and prefix/postfix. if ( (ALPHABETICS.indexOf(current) !== -1 && PREFIX_POSTFIX.indexOf(next) !== -1) || (PREFIX_POSTFIX.indexOf(current) !== -1 && ALPHABETICS.indexOf(next) !== -1) ) { return BREAK_NOT_ALLOWED; } // LB25 Do not break between the following pairs of classes relevant to numbers: if ( // (PR | PO) × ( OP | HY )? NU ([PR, PO].indexOf(current) !== -1 && (next === NU || ([OP, HY].indexOf(next) !== -1 && classTypes[afterIndex + 1] === NU))) || // ( OP | HY ) × NU ([OP, HY].indexOf(current) !== -1 && next === NU) || // NU × (NU | SY | IS) (current === NU && [NU, SY, IS].indexOf(next) !== -1) ) { return BREAK_NOT_ALLOWED; } // NU (NU | SY | IS)* × (NU | SY | IS | CL | CP) if ([NU, SY, IS, CL, CP].indexOf(next) !== -1) { let prevIndex = currentIndex; while (prevIndex >= 0) { let type = classTypes[prevIndex]; if (type === NU) { return BREAK_NOT_ALLOWED; } else if ([SY, IS].indexOf(type) !== -1) { prevIndex--; } else { break; } } } // NU (NU | SY | IS)* (CL | CP)? × (PO | PR)) if ([PR, PO].indexOf(next) !== -1) { let prevIndex = [CL, CP].indexOf(current) !== -1 ? beforeIndex : currentIndex; while (prevIndex >= 0) { let type = classTypes[prevIndex]; if (type === NU) { return BREAK_NOT_ALLOWED; } else if ([SY, IS].indexOf(type) !== -1) { prevIndex--; } else { break; } } } // LB26 Do not break a Korean syllable. if ( (JL === current && [JL, JV, H2, H3].indexOf(next) !== -1) || ([JV, H2].indexOf(current) !== -1 && [JV, JT].indexOf(next) !== -1) || ([JT, H3].indexOf(current) !== -1 && next === JT) ) { return BREAK_NOT_ALLOWED; } // LB27 Treat a Korean Syllable Block the same as ID. if ( (KOREAN_SYLLABLE_BLOCK.indexOf(current) !== -1 && [IN, PO].indexOf(next) !== -1) || (KOREAN_SYLLABLE_BLOCK.indexOf(next) !== -1 && current === PR) ) { return BREAK_NOT_ALLOWED; } // LB28 Do not break between alphabetics (“at”). if (ALPHABETICS.indexOf(current) !== -1 && ALPHABETICS.indexOf(next) !== -1) { return BREAK_NOT_ALLOWED; } // LB29 Do not break between numeric punctuation and alphabetics (“e.g.”). if (current === IS && ALPHABETICS.indexOf(next) !== -1) { return BREAK_NOT_ALLOWED; } // LB30 Do not break between letters, numbers, or ordinary symbols and opening or closing parentheses. if ( (ALPHABETICS.concat(NU).indexOf(current) !== -1 && next === OP && ea_OP.indexOf(codePoints[afterIndex]) === -1) || (ALPHABETICS.concat(NU).indexOf(next) !== -1 && current === CP) ) { return BREAK_NOT_ALLOWED; } // LB30a Break between two regional indicator symbols if and only if there are an even number of regional // indicators preceding the position of the break. if (current === RI && next === RI) { let i = indicies[currentIndex]; let count = 1; while (i > 0) { i--; if (classTypes[i] === RI) { count++; } else { break; } } if (count % 2 !== 0) { return BREAK_NOT_ALLOWED; } } // LB30b Do not break between an emoji base and an emoji modifier. if (current === EB && next === EM) { return BREAK_NOT_ALLOWED; } return BREAK_ALLOWED; }; export const lineBreakAtIndex = (codePoints: number[], index: number): BREAK_OPPORTUNITIES => { // LB2 Never break at the start of text. if (index === 0) { return BREAK_NOT_ALLOWED; } // LB3 Always break at the end of text. if (index >= codePoints.length) { return BREAK_MANDATORY; } const [indices, classTypes] = codePointsToCharacterClasses(codePoints); return _lineBreakAtIndex(codePoints, classTypes, indices, index); }; export type LINE_BREAK = 'auto' | 'normal' | 'strict'; export type WORD_BREAK = 'normal' | 'break-all' | 'break-word' | 'keep-all'; interface IOptions { lineBreak?: LINE_BREAK; wordBreak?: WORD_BREAK; } const cssFormattedClasses = (codePoints: number[], options?: IOptions): [number[], number[], boolean[] | undefined] => { if (!options) { options = {lineBreak: 'normal', wordBreak: 'normal'}; } let [indicies, classTypes, isLetterNumber] = codePointsToCharacterClasses(codePoints, options.lineBreak); if (options.wordBreak === 'break-all' || options.wordBreak === 'break-word') { classTypes = classTypes.map((type) => ([NU, AL, SA].indexOf(type) !== -1 ? ID : type)); } const forbiddenBreakpoints = options.wordBreak === 'keep-all' ? isLetterNumber.map((letterNumber, i) => { return letterNumber && codePoints[i] >= 0x4e00 && codePoints[i] <= 0x9fff; }) : undefined; return [indicies, classTypes, forbiddenBreakpoints]; }; export const inlineBreakOpportunities = (str: string, options?: IOptions): string => { const codePoints = toCodePoints(str); let output = BREAK_NOT_ALLOWED; const [indicies, classTypes, forbiddenBreakpoints] = cssFormattedClasses(codePoints, options); codePoints.forEach((codePoint, i) => { output += fromCodePoint(codePoint) + (i >= codePoints.length - 1 ? BREAK_MANDATORY : _lineBreakAtIndex(codePoints, classTypes, indicies, i + 1, forbiddenBreakpoints)); }); return output; }; class Break { private readonly codePoints: number[]; readonly required: boolean; readonly start: number; readonly end: number; constructor(codePoints: number[], lineBreak: string, start: number, end: number) { this.codePoints = codePoints; this.required = lineBreak === BREAK_MANDATORY; this.start = start; this.end = end; } slice(): string { return fromCodePoint(...this.codePoints.slice(this.start, this.end)); } } export type LineBreak = | { done: true; value: null; } | { done: false; value: Break; }; interface ILineBreakIterator { next: () => LineBreak; } export const LineBreaker = (str: string, options?: IOptions): ILineBreakIterator => { const codePoints = toCodePoints(str); const [indicies, classTypes, forbiddenBreakpoints] = cssFormattedClasses(codePoints, options); const length = codePoints.length; let lastEnd = 0; let nextIndex = 0; return { next: () => { if (nextIndex >= length) { return {done: true, value: null}; } let lineBreak = BREAK_NOT_ALLOWED; while ( nextIndex < length && (lineBreak = _lineBreakAtIndex(codePoints, classTypes, indicies, ++nextIndex, forbiddenBreakpoints)) === BREAK_NOT_ALLOWED ) {} if (lineBreak !== BREAK_NOT_ALLOWED || nextIndex === length) { const value = new Break(codePoints, lineBreak, lastEnd, nextIndex); lastEnd = nextIndex; return {value, done: false}; } return {done: true, value: null}; }, }; };
the_stack
import { h, Fragment } from 'https://unpkg.com/preact@10.5.12?module'; import { useState, useEffect } from 'https://unpkg.com/preact@10.5.12/hooks/dist/hooks.module.js?module'; // import type definitions import { FieldViewProps } from './interface.ts'; /******************************************************************************************* */ /** * @description renders the view for individual fields * switches between a new entry view - for creating new entries * into the selected collection, and a edit entry view - for * editing the currently selected entry * * @param activeEntry - an object holding keys for each field name, and value of * an array containing 3 elements - [value (string), data type (string), error message (string)] * * @param activeItem - the currently selected collection (string) * * @param newEntry - a boolean representing if this is an entry being added (true) or an entry * being edited (false) * * @param collectionEntries - an array containing all active entries in the selected collection * * @param handleResultsView - a function which sets the resultsView variable (boolean) determining * if the view should be displaying all collection entries or an individual entry */ const FieldView = ({ activeEntry, activeItem, newEntry, collectionEntries, handleResultsView }: FieldViewProps) => { // holds state of api request for updating or adding new entry const [saveFail, setSaveFail] = useState(false); // holds state of api request for updating or adding new entry const [saveSuccess, setSaveSuccess] = useState(false); // holds state of api request for updating or adding new entry const [loading, setLoading] = useState(false); // holds object of each entry. Each key is the field name, each value is // an array containing the value of the input box, the data type, // and the error message (or empty string if no error) const [activeEntryValues, setActiveEntryValues] = useState(activeEntry); // holds the value of the id on newly created entries const [newId, setNewId] = useState(1); // used to force rerender on update of error message in activeEntryValues object const [changed, setChanged] = useState(0); // holds boolean representing state of Confirm Delete popup - open or closed const [deletePopup, setDeletePopup] = useState(false); /******************************************************************************************* */ // set activeEntryValues to passed down activeEntry prop on mount // if this is a new entry being created, set id to the id which the entry will be created with in the db useEffect(() => { // @ts-ignore if (newEntry && Number(collectionEntries[collectionEntries.length - 1].id) + 1 !== 0) { // @ts-ignore setNewId(Number(collectionEntries[collectionEntries.length - 1].id) + 1); } }, []); // declare variable to hold let entryDataArr; // on update of changed - the state variable updated in handleChange and used to force rerender // - rebuild entryDataArr to display error message or remove error message for invalid input values useEffect(() => { entryDataArr = Object.entries(activeEntry).map(([field, value], index) => { if (index === 0) return ( <div className='fieldViewSect' key={`${field}-${index}`} > <label className='fieldViewLabel' htmlFor={field} > {field} </label> <input className='fieldViewInput' style={{ color: 'black' }} type='text' id={field} name={field} value={newEntry ? newId : activeEntryValues[field][0]} onChange={(e: any) => handleChange(e)} disabled /> </div> ); return ( <div className='fieldViewSect' key={`${field}-${index}`} > <label className='fieldViewLabel' htmlFor={field}>{field} </label> <input className='fieldViewInput' type='text' id={field} name={field} value={activeEntryValues[field][0]} onChange={(e: any) => handleChange(e)} /> {activeEntryValues[field][2].length > 0 && <p className='fieldViewErrorMsg'> {activeEntryValues[field][2]} </p> } </div> ); }); }, [changed]); // handle clicks of add entry or save edited entry button const handleSave = (event: any) => { event.preventDefault(); // reset any past failed or successful requests & set loading to true setSaveFail(false); setSaveSuccess(false); setLoading(true); // handle invalid inputs // if any inputs are invalid, set failed request state & return const valueKeys = Object.keys(activeEntryValues); let sendRequest = true; valueKeys.forEach(value => { if (activeEntryValues[value][2].length > 0) { sendRequest = false; setLoading(false); setSaveFail(true); } }); if (!sendRequest) return; // holds current count of fields for selected entry const inputCount = event.target.form.childElementCount; const data: any = {}; let count = 2; // iterate through each field and create as property on object // with key of field name & value of the field value while (count <= inputCount) { const inputName = event.target.form[count].labels[0].innerText; let value = event.target.form[count].value; // @ts-ignore // value === 'false' ? value = false : value === 'true' ? value = true : ''; data[inputName] = value; count += 1; }; // test if this a new entry being created or an active entry being edited // if new entry send request to create the new entry and handle loading state based on response if (newEntry) { fetch(`/api/tables/${activeItem}`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(res => res.json()) .then(res => { if (res.success) { setLoading(false); setSaveSuccess(true); setTimeout(() => handleResultsView(true), 1000); } else { setLoading(false); setSaveFail(true); } }) .catch(error => console.log(error)) // if saving an edited entry, send put request with updated information // and handle loadng state based on response } else { const value = activeEntryValues[Object.keys(activeEntryValues)[0]][0]; fetch(`/api/tables/update/${activeItem}/${value}`, { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(data) }) .then(res => res.json()) .then(res => { if (res.success) { setLoading(false); setSaveSuccess(true); setTimeout(() => handleResultsView(true), 1000); } else { setLoading(false); setSaveFail(true); } }) .catch(error => console.log(error)) } }; // Renders the popup box which confirms that the user would // intends to delete the selected entry const ConfirmDelete = () => { return ( <div className='confirmDeletePopup'> <p className='confirmDeleteText'> Are you sure you want to delete <br></br> <span className='confirmDeleteHighlight'>{activeEntryValues[Object.keys(activeEntryValues)[0]][0]} </span> from <span className='confirmDeleteHighlight'> {activeItem} </span> ? </p> <div className='confirmDeleteBtnContainer'> <p className='confirmDeleteCancel' onClick={() => setDeletePopup(false)} > cancel </p> <button className='confirmDeleteBtn' onClick={(e: any) => handleDelete(e)} > Delete Entry </button> </div> </div> ); }; // handles deletion of selected entry const handleDelete = (event: any) => { // sets confirm delete popup to true (open), if its currently false (closed) if (!deletePopup) setDeletePopup(true); // if the clicked buttons className is equal to 'confirmDeleteBtn', // delete selected entry & reset view back to all of the collections entries if (event.target.className === 'confirmDeleteBtn') { const value = activeEntryValues.id[0]; fetch(`/api/tables/row/${activeItem}/${value}`, { method: 'DELETE' }) .then(res => res.json()) .then(res => { handleResultsView(true); setDeletePopup(false); }) .catch(error => console.log(error)); } }; // handles changes on each individual input field const handleChange = (event: any) => { const field = event.target.name; const value = event.target.value; const dataType = activeEntryValues[field][1] const copy = activeEntryValues; copy[field] = [value, copy[field][1], '']; // handle adding error message to fields where input should be // of type integer, but user is inputing value that is not an integer // or of type boolean, but user is inputing value that is not a boolean if ((dataType === 'integer' && isNaN(Number(value))) || (dataType === 'boolean' && (value !== 'false' && value !== 'true')) ) { const dup = Object.assign(activeEntryValues); dup[field][0] = value; dup[field][2] = `Value should be of type ${dataType}`; setActiveEntryValues(dup); // if no errors with input value, set activeEntryValues to // current activeEntryValues with updated value for selected input } else { copy[field] = [value, copy[field][1], '']; setActiveEntryValues(copy); } // update changed state to force rerender const newCount = changed + 1; setChanged(newCount); } // declare variable which will hold the correct loading svg to render based on loading state let loader; // if loading is true set loader to loading spinner if (loading) { loader = <div className='saveFieldBtnLoader'></div>; // if saveFail is true, set loader to failed svg x } else if (saveFail) { loader = ( <div> <svg className='saveFieldFailSVG' xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" > <path d="M24 20.188l-8.315-8.209 8.2-8.282-3.697-3.697-8.212 8.318-8.31-8.203-3.666 3.666 8.321 8.24-8.206 8.313 3.666 3.666 8.237-8.318 8.285 8.203z"/> </svg> </div> ); // if saveSuccess is true, set loader to success svg checkmark } else if (saveSuccess) { loader = ( <div className={newEntry ? 'loader' : ''}> <svg className={`saveFieldSuccessSVG ${newEntry ? 'entryFieldSuccessSVG' : ''}`} xmlns="http://www.w3.org/2000/svg" width="15" height="15" viewBox="0 0 24 24" > <path d="M0 11c2.761.575 6.312 1.688 9 3.438 3.157-4.23 8.828-8.187 15-11.438-5.861 5.775-10.711 12.328-14 18.917-2.651-3.766-5.547-7.271-10-10.917z"/> </svg> </div> ); } // map through activeEntry entries and render labels & input fields for each entry // set the id field as disabled because it cannot be edited - id field should always be at index 0 entryDataArr = Object.entries(activeEntry).map(([field, value], index) => { if (index === 0) return ( <div className='fieldViewSect' key={`${field}-${index}`} > <label className='fieldViewLabel' htmlFor={field} > {field} </label> <input className='fieldViewInput' style={{ color: 'black' }} type='text' id={field} name={field} value={newEntry ? newId : activeEntryValues[field][0]} onChange={handleChange} disabled /> </div> ); return ( <div className='fieldViewSect' key={`${field}-${index}`} > <label className='fieldViewLabel' htmlFor={field} > {field} </label> <input className='fieldViewInput' type='text' id={field} name={field} value={activeEntryValues[field][0]} onChange={handleChange} /> {activeEntryValues[field][2].length > 0 && <p className='fieldViewErrorMsg'>{activeEntryValues[field][2]}</p> } </div> ); }); return ( <div className='fieldViewContainer'> <div className='fieldViewHeader'> <div className='deleteContainer'> <div className='fieldViewDetails'> {/* if this is a new entry being added, display the newId * if this is an entry being edited, display the selected entry's id */} <p className='fieldViewName'>{newEntry ? newId : activeEntryValues[Object.keys(activeEntryValues)[0]][0]}</p> <p className='fieldViewCollection'>{activeItem}</p> </div> {/* if this is a new entry being added, render the delete button */} {!newEntry && (<div className='deleteEntrySVG' onClick={handleDelete} > <svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill='#bd5555' > <path d="M3 6v18h18v-18h-18zm5 14c0 .552-.448 1-1 1s-1-.448-1-1v-10c0-.552.448-1 1-1s1 .448 1 1v10zm5 0c0 .552-.448 1-1 1s-1-.448-1-1v-10c0-.552.448-1 1-1s1 .448 1 1v10zm5 0c0 .552-.448 1-1 1s-1-.448-1-1v-10c0-.552.448-1 1-1s1 .448 1 1v10zm4-18v2h-20v-2h5.711c.9 0 1.631-1.099 1.631-2h5.315c0 .901.73 2 1.631 2h5.712z"/> </svg> </div>) } </div> <div className='saveFieldBtnContainer'> {loader} {/* if saveSuccess is false and this is a new entry being added or this is an active entry being edited, render the button to add or save entry */} {((!saveSuccess && newEntry) || (!newEntry)) && (<button onClick={handleSave} type='submit' form='fieldViewForm' className='saveFieldBtn' > {newEntry ? 'Add Entry' : 'Save'} </button>) } </div> </div> {deletePopup && <ConfirmDelete /> } <form id='fieldViewForm' className='fieldViewForm' > {entryDataArr} </form> </div> ); }; export default FieldView;
the_stack
import warning from 'tiny-warning'; import { ErrorConstant } from '@remirror/core-constants'; import { invariant, isEmptyArray, sort } from '@remirror/core-helpers'; import type { Dispose, EditorView } from '@remirror/core-types'; import { AnyExtension, AnyExtensionConstructor, GetExtensions, isExtension, isMarkExtension, isNodeExtension, isPlainExtension, } from '../extension'; import type { GetConstructor, StateUpdateLifecycleProps } from '../types'; /** * Transforms the unsorted array of presets and extension into presets and * sorted extensions. Handles uniqueness of extensions and automatically throws * an error when required extensions are missing. * * @internalremarks Currently matching by constructor - what if different * versions exist in the same app * * @param initialExtensions - the extensions to be transformed. This includes * the extension that are parents to other extensions. * * @returns the list of extension instances sorted by priority */ export function transformExtensions<RawExtensions extends AnyExtension>( initialExtensions: readonly RawExtensions[], settings: Remirror.ManagerSettings, ): ExtensionTransformation<RawExtensions> { type Extension = GetExtensions<RawExtensions>; type ExtensionConstructor = GetConstructor<Extension>; // This is the holder for the sorted and cleaned extensions returned by this // function. const extensions: Extension[] = []; const extensionMap = new WeakMap<ExtensionConstructor, Extension>(); // All the extensions which provide child extensions. const parentExtensions: Extension[] = []; // Used to track duplicates and the extension holders they were added by. const duplicateMap = new WeakMap<AnyExtensionConstructor, Extension[]>(); // The unsorted, de-duped, unrefined extensions. let gatheredExtensions: Extension[] = []; // The mutable objects and the manager settings which are used to gather all // the deeply nested extensions. const gatherRawExtensionConfig = { duplicateMap, parentExtensions, gatheredExtensions, settings }; for (const extension of initialExtensions) { gatherRawExtensions(gatherRawExtensionConfig, { extension: extension as Extension }); } // Sort the extensions. gatheredExtensions = sort(gatheredExtensions, (a, z) => z.priority - a.priority); // Keep track of added constructors for uniqueness. const found = new WeakSet<AnyExtensionConstructor>(); const names = new Set<string>(); // Remove extension duplicates and update the parent extension with the // highest priority identical extension. for (const extension of gatheredExtensions) { const key = extension.constructor; const name = extension.name; const duplicates = duplicateMap.get(key); invariant(duplicates, { message: `No entries were found for the ExtensionConstructor ${extension.name}`, code: ErrorConstant.INTERNAL, }); if (found.has(key) || names.has(name)) { continue; } found.add(key); names.add(name); extensions.push(extension); extensionMap.set(key, extension); // Replace the extensions for all presets that referenced this constructor. duplicates.forEach((parent) => parent?.replaceChildExtension(key, extension)); } const missing: Array<MissingConstructor<Extension>> = []; // Throw if any required extensions are missing. for (const extension of extensions) { findMissingExtensions({ extension, found, missing }); } invariant(isEmptyArray(missing), { code: ErrorConstant.MISSING_REQUIRED_EXTENSION, message: missing .map( ({ Constructor, extension }) => `The extension '${extension.name}' requires '${Constructor.name} in order to run correctly.`, ) .join('\n'), }); return { extensions, extensionMap }; } interface GatherAllExtensionsConfig<Extension extends AnyExtension> { /** The list of gathered raw extensions, updated by mutation. */ gatheredExtensions: Extension[]; /** The duplicate map which is updated by mutation. */ duplicateMap: WeakMap<AnyExtensionConstructor, Extension[]>; /** The parent extensions which are updated by mutation */ parentExtensions: Extension[]; /** The settings passed into the manager. */ settings: Remirror.ManagerSettings; } interface GatherAllExtensionsProps<Extension extends AnyExtension> { /** The extension to check and gather children from. */ extension: Extension; /** Used to check if there there is a circular dependency encountered. */ names?: string[]; /** The parent of this extension. */ parentExtension?: Extension; } /** * Dive into the current extension and gather all child extensions including * those which are deeply nested. * * It also automatically handles circular dependencies. And logs a warning when * one is encountered. * * @param config - the configuration and mutable objects which are updated by * this function. * @param props - the extension, gathered names and parent extension. */ function gatherRawExtensions<Extension extends AnyExtension>( config: GatherAllExtensionsConfig<Extension>, props: GatherAllExtensionsProps<Extension>, ) { const { gatheredExtensions, duplicateMap, parentExtensions, settings } = config; const { extension, parentExtension } = props; // Get the list of parent names of the current extension. This is used to // track circular dependencies. let { names = [] } = props; invariant(isExtension(extension), { code: ErrorConstant.INVALID_MANAGER_EXTENSION, message: `An invalid extension: ${extension} was provided to the [[\`RemirrorManager\`]].`, }); // The children provided by this extension. const childExtensions = extension.extensions; // Override the priority if the user has done so in the settings passed to the // [[`RemirrorManager`]]. extension.setPriority(settings.priority?.[extension.name]); // Update the gathered extension list in this block gatheredExtensions.push(extension); // Keep track of the extensions which have been added multiple times by // separate extension parents. Later on, the highest priority extension will // be added to each parent instead of the one that they may have been // configured with. updateExtensionDuplicates({ duplicateMap, extension, parentExtension }); // Check if there are any children extensions to be added an if not move onto // the next provided extension. if (childExtensions.length === 0) { return; } if (names.includes(extension.name)) { warning( false, `Circular dependency encountered when loading extensions: ${names.join(' > ')} > ${ extension.name }`, ); return; } names = [...names, extension.name]; parentExtensions.push(extension); for (const child of childExtensions) { // Recursively gather all the children extension from the current extension // level. gatherRawExtensions(config, { names, extension: child, parentExtension: extension }); } } interface FindMissingProps<Extension extends AnyExtension> { extension: Extension; found: WeakSet<AnyExtensionConstructor>; missing: Array<MissingConstructor<Extension>>; } /** * Populate missing Constructors. * * If any missing extensions are identified then it is the responsibility of the * calling method to deal with the error. Currently the action is to `throw` an * error. */ function findMissingExtensions<Extension extends AnyExtension>(props: FindMissingProps<Extension>) { const { extension, found, missing } = props; if (!extension.requiredExtensions) { return; } for (const Constructor of extension.requiredExtensions ?? []) { if (found.has(Constructor)) { continue; } missing.push({ Constructor: Constructor, extension }); } } interface UpdateExtensionDuplicatesProps<Extension extends AnyExtension> { /** * The map of all duplicates. */ duplicateMap: WeakMap<AnyExtensionConstructor, Extension[]>; /** * The extension to associate to the multiple presets that have added it.. */ extension: Extension; /** * The preset which was responsible for adding the extension (if it exists). */ parentExtension?: Extension; } /** * Adds the values to the duplicate map which identifies each unique extension * in the manager and tracks the presets responsible for adding them. This is * used to make sure that only one instance of each extension is shared amongst * the presets which require it. * * At the moment, the highest priority extension is the one that is to all * presets which require it. This is done by checking the `duplicateMap` for * each extension, and replacing the instance of the required extension within * the preset with the highest priority instance. */ function updateExtensionDuplicates<Extension extends AnyExtension>( props: UpdateExtensionDuplicatesProps<Extension>, ) { const { duplicateMap, extension, parentExtension } = props; // The extension constructor is used as the identifier for lookups. const key = extension.constructor; const duplicate = duplicateMap.get(key); const parentToAdd: Extension[] = parentExtension ? [parentExtension] : []; duplicateMap.set(key, duplicate ? [...duplicate, ...parentToAdd] : parentToAdd); } /** * This is the object shape that is returned from the combined transformation. */ export interface ExtensionTransformation< Extension extends AnyExtension, Expanded extends AnyExtension = GetExtensions<Extension>, > { /** * The list of extensions sorted by priority and original extension. Every * extension passed in and those contained by presets are placed here. */ extensions: Expanded[]; /** * A map where the key is the [[`ExtensionConstructor`]] and the value is the * [[`Extension`]] instance. This is used to lookup extensions contained * within a manager. It is a weak map so that values can be garbage collected * when references to the constructor are lost. */ extensionMap: WeakMap<GetConstructor<Expanded>, Expanded>; } interface MissingConstructor<Extension extends AnyExtension> { Constructor: AnyExtensionConstructor; extension: Extension; } export interface ManagerLifecycleHandlers { /** * Contains the methods run when the manager is first created. */ create: Array<() => Dispose | void>; /** * Holds the methods to run once the Editor has received the view from the * attached. */ view: Array<(view: EditorView) => Dispose | void>; /** * The update method is called every time the state updates. This allows * extensions to listen to updates. */ update: Array<(props: StateUpdateLifecycleProps) => void>; /** * Called when the manager is being destroyed. */ destroy: Array<() => void>; } interface SetupExtensionProps { extension: AnyExtension; nodeNames: string[]; markNames: string[]; plainNames: string[]; store: Remirror.ExtensionStore; handlers: ManagerLifecycleHandlers; } /** * This helper function extracts all the lifecycle methods from the provided * extension and adds them to the provided `handler` container. */ export function extractLifecycleMethods(props: SetupExtensionProps): void { const { extension, nodeNames, markNames, plainNames, store, handlers } = props; // Add the store to the extension. The store is used by extensions to access // all the data included in `Remirror.ExtensionStore`. I decided on this // pattern because passing around parameters into each call method was // tedious. Why not just access `this.store` within your extension to get // whatever you need? Also using the store allows developers to extend the // behaviour of their editor by adding different behaviour to the global // namespace [[`Remirror.ExtensionStore`]]. extension.setStore(store); // Gather all the handlers and add them where they exist. const createHandler = extension.onCreate?.bind(extension); const viewHandler = extension.onView?.bind(extension); const stateUpdateHandler = extension.onStateUpdate?.bind(extension); const destroyHandler = extension.onDestroy?.bind(extension); if (createHandler) { handlers.create.push(createHandler); } if (viewHandler) { handlers.view.push(viewHandler); } if (stateUpdateHandler) { handlers.update.push(stateUpdateHandler); } if (destroyHandler) { handlers.destroy.push(destroyHandler); } // Keep track of the names of the different types of extension held by this // manager. This is already in use by the [[`TagsExtension`]]. if (isMarkExtension(extension)) { markNames.push(extension.name); } // Don't include the `doc` as a node since it is a requirement for all editors // and doesn't behave in the same way as other nodes. if (isNodeExtension(extension) && extension.name !== 'doc') { nodeNames.push(extension.name); } if (isPlainExtension(extension)) { plainNames.push(extension.name); } }
the_stack
import React, {Component} from 'react' import {Form, Input, Modal, Select, Row, Col, InputNumber, Radio} from 'antd' import {Task} from "../model/TaskModel"; import {FormComponentProps} from "antd/lib/form/Form"; import CommonUtils from "../../../common/utils/CommonUtils"; import {DynamicFormUtils} from "../../../common/utils/DynamicFormUtils"; import {DomUtils} from "../../../common/utils/DomUtils"; import EnumUtils from "../../../common/utils/EnumUtils"; import {kernel} from "../../../common/utils/IOC" import {PluginModel} from "../../plugin/model/PluginModel"; const formItemLayout = { labelCol: { span: 6 }, wrapperCol: { span: 14 } }; export interface ModalProps extends FormComponentProps { task: Task; onOk: any; onCancel: any; } const modalWidth = 1000; class TaskModal extends Component<ModalProps, { retry, concurrency, pluginId, pluginMap }> { constructor(props) { super(props); } componentWillMount() { const that = this; const taskObj = this.getTaskObj(); this.setState({ retry: CommonUtils.getValueFromModel("isRetry", taskObj, 0), concurrency: CommonUtils.getValueFromModel("isConcurrency", taskObj, 0), pluginId: CommonUtils.getValueFromModel("pluginId", taskObj, 1), pluginMap: {} }); /** * 获取插件 * @type {any} */ const pluginModel = kernel.get(PluginModel); pluginModel.listAllValid().then(data => { if(data && data.length > 0){ let pluginMap = {}; for(let plugin of data){ pluginMap[plugin.id] = plugin; } that.setState({ pluginMap: pluginMap }); console.log("pluginMap=" + JSON.stringify(pluginMap)); } }); } getTaskObj() { let taskObj = this.props.task ? this.props.task : new Task; return taskObj; } /** * 获取周期 * @returns {any[]} */ getPeriodOptions() { const periods = EnumUtils.getPeriodOptionArray(); let options = DomUtils.getSelectOptionsWithoutAll(periods); return options; } /** * 重试 */ onRetryChange(object) { this.setState({ retry: object.target.value }); } /** * 获取重试配置 * @param retryValue * @returns {any} */ getRetryDoms(retryValue) { let doms = []; if (retryValue != 1) { return null; } const taskObj = this.getTaskObj(); doms.push(<Form.Item label='重试次数' hasFeedback {...formItemLayout} help={"失败后重试次数"}> {this.props.form.getFieldDecorator('retryConf.retryNum', { initialValue: CommonUtils.getValueFromModel("retryConf.retryNum", taskObj, 1), rules: [ { required: true, message: '不能为空' } ] })(<InputNumber min={1} max={5}/>)} </Form.Item>) doms.push(<Form.Item label='重试周期' hasFeedback {...formItemLayout} help={"失败后,下一次重试与当前时间的间隔"}> {this.props.form.getFieldDecorator('retryConf.retryPeriod', { initialValue: CommonUtils.getValueFromModel("retryConf.retryPeriod", taskObj, 1), rules: [ { required: true, message: '不能为空' } ] })(<InputNumber min={1}/>)} </Form.Item>) return doms; } /** * 并发 * @param object */ onConcurrencyChange(object) { this.setState({ concurrency: object.target.value }); } getConcurrencyDoms(concurrency, isDomDisable) { if (concurrency != 0) { return []; } const taskObj = this.getTaskObj(); let doms = []; const concurrencyArray = EnumUtils.getConcurrencyOptionArray(); let options = DomUtils.getSelectOptionsWithoutAll(concurrencyArray); doms.push(<Form.Item label={"运行策略"} hasFeedback {...formItemLayout}> {this.props.form.getFieldDecorator("concurrentStrategy", { initialValue: CommonUtils.getStringValueFromModel("concurrentStrategy", taskObj, "1"), rules: [ { required: true, message: '不能为空' } ] })(<Select disabled={isDomDisable}> {options} </Select>)} </Form.Item>); return doms; } /** * 插件 * @returns {any} */ onPluginChange(value){ this.setState({ pluginId: value }); } getPluginDoms(pluginId, isEdit, model){ const { pluginMap } = this.state; const pluginInfo = pluginMap[pluginId]; if(!pluginInfo){ return null; } const formFields = pluginInfo["fieldConfig"]; let doms = []; const isDomEdit = isEdit && model["status"] == EnumUtils.statusOnline; if(formFields && formFields.length > 0){ for(let formField of formFields){ let dom = DynamicFormUtils.getComponent({ property: formField, model: model, isEdit: isDomEdit, formParent: this }); if(dom){ doms.push(dom); } } } return doms; } render() { let isUpdate = false; if (this.props.task && this.props.task.id) { isUpdate = true; } let taskObj = this.getTaskObj(); let handleOk = (e) => { e.preventDefault(); this.props.form.validateFields((errors) => { if (errors) { return } const data = { ...this.props.form.getFieldsValue(), id: taskObj.id ? taskObj.id : '' }; let pluginConf = data["pluginConf"]; if(pluginConf){ data["pluginConf"] = JSON.stringify(pluginConf); }else{ data["pluginConf"] = ""; } let retryConf = data["retryConf"]; if(retryConf){ data["retryConf"] = JSON.stringify(retryConf); }else{ data["retryConf"] = ""; } this.props.onOk(data) }) }; const taskModalOpts = { title: isUpdate ? '编辑任务' : '添加任务', visible: true, maskClosable: false, width: modalWidth, style: {top: 10}, onOk: handleOk, onCancel: this.props.onCancel }; const {retry, concurrency, pluginId} = this.state; /** * 是否可以编辑 * @type {boolean} */ let isEditable = true; if(isUpdate && taskObj){ const status = taskObj["status"]; if(status == EnumUtils.statusOnline){ isEditable = false; } } const isDomDisable = !isEditable; /** * 周期 */ let periodOptions = this.getPeriodOptions(); /** * 重试 * @type {any[]} */ let retryDoms = this.getRetryDoms(retry); /** * 并发 * @type {any[]} */ let concurrentDoms = this.getConcurrencyDoms(concurrency, isDomDisable); /** * 插件 * @type {any[]} */ const {pluginMap} = this.state; let plugins = []; if(pluginMap){ for(let pluginId in pluginMap){ plugins.push(pluginMap[pluginId]); } } let pluginOptions = DomUtils.getSelectOptionsWithoutAll(plugins); let pluginDoms = this.getPluginDoms(pluginId, isUpdate, taskObj); return (<Modal {...taskModalOpts}> <Form layout={'horizontal'}> <Row> <Col span={12}> <Form.Item label='名称' hasFeedback {...formItemLayout}> {this.props.form.getFieldDecorator('name', { initialValue: CommonUtils.getStringValueFromModel("name", taskObj, ""), rules: [ { required: true, message: '不能为空' } ] })(<Input disabled={isUpdate}/>)} </Form.Item> <Form.Item label="周期" hasFeedback {...formItemLayout}> {this.props.form.getFieldDecorator("period", { initialValue: CommonUtils.getStringValueFromModel("period", taskObj, "4"), rules: [ { required: true, message: '不能为空' } ] })(<Select disabled={isDomDisable}> {periodOptions} </Select>)} </Form.Item> <Form.Item label='cron表达式' hasFeedback {...formItemLayout} help={'cron表达式,例如"0 1 * * ?",每天1点'}> {this.props.form.getFieldDecorator('cronExpression', { initialValue: CommonUtils.getStringValueFromModel("cronExpression", taskObj, "0 1 * * ?"), rules: [ { required: false, message: '不能为空' } ] })(<Input disabled={isDomDisable}/> )} </Form.Item> <Form.Item label='是否并发' hasFeedback {...formItemLayout} help={"任务是否可以并行运行"}> {this.props.form.getFieldDecorator('concurrency', { initialValue: CommonUtils.getValueFromModel("concurrency", taskObj, 0), rules: [ { required: true, message: '不能为空' } ] })(<Radio.Group onChange={this.onConcurrencyChange.bind(this)} disabled={isDomDisable}> <Radio value={0}>否</Radio> <Radio value={1}>是</Radio> </Radio.Group>)} </Form.Item> {concurrentDoms} <Form.Item label='失败重试' hasFeedback {...formItemLayout} help={"任务失败后是否重试"}> {this.props.form.getFieldDecorator('isRetry', { initialValue: CommonUtils.getValueFromModel("isRetry", taskObj, 0), rules: [ { required: true, message: '不能为空' } ] })(<Radio.Group onChange={this.onRetryChange.bind(this)}> <Radio value={0}>否</Radio> <Radio value={1}>是</Radio> </Radio.Group>)} </Form.Item> {retryDoms} <Form.Item label='最长运行时间' hasFeedback {...formItemLayout} help={"单位:分,-1代表没有限制"}> {this.props.form.getFieldDecorator('maxRunTime', { initialValue: CommonUtils.getStringValueFromModel("maxRunTime", taskObj, -1), rules: [ { required: false } ] })(<InputNumber min={-1}/>)} </Form.Item> <Form.Item label='报警邮箱' hasFeedback {...formItemLayout}> {this.props.form.getFieldDecorator('alarmEmail', { initialValue: CommonUtils.getStringValueFromModel("alarmEmail", taskObj, ""), rules: [ { required: false, message: '不能为空' } ] })(<Input/>)} </Form.Item> <Form.Item label='报警电话' hasFeedback {...formItemLayout}> {this.props.form.getFieldDecorator('alarmPhone', { initialValue: CommonUtils.getStringValueFromModel("alarmPhone", taskObj, ""), rules: [ { required: false, message: '不能为空' } ] })(<Input/>)} </Form.Item> <Form.Item label='描述' hasFeedback {...formItemLayout}> {this.props.form.getFieldDecorator('description', { initialValue: CommonUtils.getStringValueFromModel("description", taskObj, ""), rules: [ { required: false, message: '不能为空' } ] })(<Input.TextArea/>)} </Form.Item> </Col> <Col span={12}> <Form.Item label={"插件"} hasFeedback {...formItemLayout}> {this.props.form.getFieldDecorator("pluginId", { initialValue: CommonUtils.getStringValueFromModel("pluginId", taskObj, 1), rules: [ { required: true, message: '不能为空' } ] })(<Select onChange={this.onPluginChange.bind(this)} disabled={isDomDisable}> {pluginOptions} </Select>)} </Form.Item> {pluginDoms} </Col> </Row> </Form> </Modal>); } } export default Form.create()(TaskModal);
the_stack
import { BackgroundpageWindow, GreaseMonkeyData, EncodedContextData, MatchPattern, ToExecuteNode, ContextMenuCreateProperties, ContextMenuOverrides, UserAddedContextMenu, ContextMenuItemTreeItem } from './sharedTypes'; import { EncodedString } from '../../elements/elements'; import { I18NKeys } from "../../_locales/i18n-keys"; import { ModuleData } from "./moduleTypes"; declare const browserAPI: browserAPI; declare const BrowserAPI: BrowserAPI; declare const window: BackgroundpageWindow; export namespace CRMNodes.Script.Handler { async function genCodeOnPage({ tab, key, info, node, script, tabIndex, safeNode, indentUnit, contextData, greaseMonkeyData }: { tab: _browser.tabs.Tab; key: number[]; info: _browser.contextMenus.OnClickData; node: CRM.ScriptNode; safeNode: CRM.SafeNode; greaseMonkeyData: GreaseMonkeyData; script: string; indentUnit: string; tabIndex: number; contextData: EncodedContextData; }): Promise<string> { const enableBackwardsCompatibility = (await modules.Util.getScriptNodeScript(node)).indexOf('/*execute locally*/') > -1 && node.isLocal; const catchErrs = modules.storages.storageLocal.catchErrors; const supportedBrowserAPIs = []; if (BrowserAPI.isBrowserAPISupported('chrome')) { supportedBrowserAPIs.push('chrome'); } if (BrowserAPI.isBrowserAPISupported('browser')) { supportedBrowserAPIs.push('browser'); } const doDebug = modules.globalObject.globals.eventListeners.scriptDebugListeners.indexOf(node.id) > -1; if (doDebug) { modules.globalObject.globals.eventListeners.scriptDebugListeners .splice(modules.globalObject.globals.eventListeners.scriptDebugListeners.indexOf(node.id), 1); } modules.Util.setMapDefault(modules.storages.nodeStorage, node.id, {}); modules.Util.setMapDefault(modules.storages.nodeStorageSync, node.id, {}); return [ [ `var crmAPI = new (window._crmAPIRegistry.pop())(${[ safeNode, node.id, tab, info, key, modules.storages.nodeStorage.get(node.id), contextData, greaseMonkeyData, false, (node.value && node.value.options) || {}, enableBackwardsCompatibility, tabIndex, browserAPI.runtime.id, supportedBrowserAPIs.join(','), modules.storages.nodeStorageSync.get(node.id) ].map((param) => { if (param === void 0) { return JSON.stringify(null); } return JSON.stringify(param); }).join(', ')});` ].join(', '), modules.constants.templates.globalObjectWrapperCode('window', 'windowWrapper', node.isLocal && BrowserAPI.isBrowserAPISupported('chrome') ? 'chrome' : 'void 0', node.isLocal && BrowserAPI.isBrowserAPISupported('browser') ? 'browser' : 'void 0'), `${catchErrs ? 'try {' : ''}`, 'function main(crmAPI, window, chrome, browser, menuitemid, parentmenuitemid, mediatype,' + 'linkurl, srcurl, pageurl, frameurl, frameid,' + 'selectiontext, editable, waschecked, checked) {', doDebug ? 'debugger;' : '', script, '}', `crmAPI.onReady(function() {main.apply(this, [crmAPI, windowWrapper, ${node.isLocal && BrowserAPI.isBrowserAPISupported('chrome') ? 'chrome' : 'void 0'}, ${node.isLocal && BrowserAPI.isBrowserAPISupported('browser') ? 'browser' : 'void 0'}].concat(${ JSON.stringify([ info.menuItemId, info.parentMenuItemId, info.mediaType, info.linkUrl, info.srcUrl, info.pageUrl, info.frameUrl, (info as any).frameId, info.selectionText, info.editable, info.wasChecked, info.checked ]) }))})`, `${catchErrs ? [ `} catch (error) {`, `${indentUnit}if (crmAPI.debugOnError) {`, `${indentUnit}${indentUnit}debugger;`, `${indentUnit}}`, `${indentUnit}throw error;`, `}` ].join('\n') : ''}` ].join('\n'); } async function getScriptsToRun(code: string, runAt: _browser.extensionTypes.RunAt, node: CRM.ScriptNode, usesUnsafeWindow: boolean): Promise<{ code?: string; file?: string; runAt: _browser.extensionTypes.RunAt; }[]> { const scripts = []; const globalLibraries = modules.storages.storageLocal.libraries; const urlDataPairs = modules.storages.urlDataPairs; for (let i = 0; i < node.value.libraries.length; i++) { let lib: { name: string; url?: string; code?: string; } | { code: string; }; if (globalLibraries) { for (let j = 0; j < globalLibraries.length; j++) { if (globalLibraries[j].name === node.value.libraries[i].name) { const currentLib = globalLibraries[j]; if (currentLib.ts && currentLib.ts.enabled) { lib = { code: await modules.Util.getLibraryCode(currentLib) } } else { lib = currentLib; } break; } } } if (!lib) { //Resource hasn't been registered with its name, try if it's an anonymous one if (!node.value.libraries[i].name) { //Check if the value has been registered as a resource if (urlDataPairs.get(node.value.libraries[i].url as any)) { lib = { code: urlDataPairs.get(node.value.libraries[i].url as any).dataString }; } } } if (lib) { scripts.push({ code: lib.code, runAt: runAt }); } } if (!usesUnsafeWindow) { //Let the content script determine whether to run this scripts.push({ file: '/js/crmapi.js', runAt: runAt }); } scripts.push({ code: code, runAt: runAt }); return scripts; } function generateMetaAccessFunction(metaData: { [key: string]: any; }): (key: string) => any { return (key: string) => { if (metaData[key]) { return metaData[key][0]; } return undefined; }; } function getResourcesArrayForScript(scriptId: CRM.NodeId<CRM.ScriptNode>): { name: string; sourceUrl: string; matchesHashes: boolean; dataURI: string; dataString: string; crmUrl: string; hashes: { algorithm: string; hash: string; }[]; }[] { const resourcesArray = []; const scriptResources = modules.storages.resources.get(scriptId); if (!scriptResources) { return []; } for (let resourceName in scriptResources) { if (scriptResources.hasOwnProperty(resourceName)) { resourcesArray.push(scriptResources[resourceName]); } } return resourcesArray; } function ensureRunAt(id: CRM.GenericNodeId, script: { code?: string; file?: string; runAt: string; }): { code?: string; file?: string; runAt: 'document_start'|'document_end'|'document_idle'; } { const newScript: { code?: string; file?: string; runAt: 'document_start'|'document_end'|'document_idle'; } = { code: script.code, file: script.file, runAt: 'document_idle' }; const runAt = script.runAt; if (runAt === 'document_start' || runAt === 'document_end' || runAt === 'document_idle') { newScript.runAt = runAt; } else { window.logAsync( window.__(I18NKeys.background.crm.invalidRunat, id + '', runAt)); } return newScript; } function executeScripts(nodeId: CRM.NodeId<CRM.ScriptNode>, tabId: TabId, scripts: { code?: string; file?: string; runAt: _browser.extensionTypes.RunAt; }[], usesUnsafeWindow: boolean) { if (usesUnsafeWindow) { //Send it to the content script and run it there browserAPI.tabs.sendMessage(tabId, { type: 'runScript', data: { scripts: scripts } }); } else { modules.Util.promiseChain(scripts.map((script) => { return async () => { try { await browserAPI.tabs.executeScript(tabId, ensureRunAt(nodeId, script)).catch((err) => { if (err.message.indexOf('Could not establish connection') === -1 && err.message.indexOf('closed') === -1) { window.logAsync(window.__(I18NKeys.background.crm.executionFailed, tabId, nodeId), err); } }); } catch(e) { //The tab was closed during execution } } })); } } export async function generateGreaseMonkeyData(metaData: { [key: string]: any; }, node: CRM.ScriptNode, includes: string[], excludes: string[], tab: { incognito: boolean }): Promise<GreaseMonkeyData> { const metaString = (MetaTags.getMetaLines(node.value .script) || []).join('\n'); const metaVal = generateMetaAccessFunction(metaData); return { info: { script: { author: metaVal('author') || '', copyright: metaVal('copyright'), description: metaVal('description'), excludes: metaData['excludes'], homepage: metaVal('homepage'), icon: metaVal('icon'), icon64: metaVal('icon64'), includes: (metaData['includes'] || []).concat(metaData['include']), lastUpdated: 0, //Never updated matches: metaData['matches'], isIncognito: tab.incognito, downloadMode: 'browser', name: node.name, namespace: metaVal('namespace'), options: { awareOfChrome: true, compat_arrayleft: false, compat_foreach: false, compat_forvarin: false, compat_metadata: false, compat_prototypes: false, compat_uW_gmonkey: false, noframes: metaVal('noframes'), override: { excludes: true, includes: true, orig_excludes: metaData['excludes'], orig_includes: (metaData['includes'] || []).concat(metaData['include']), use_excludes: excludes, use_includes: includes } }, position: 1, // what does this mean? resources: getResourcesArrayForScript(node.id), "run-at": metaData['run-at'] || metaData['run_at'] || 'document_end', system: false, unwrap: true, version: metaVal('version') }, scriptMetaStr: metaString, scriptSource: await modules.Util.getScriptNodeScript(node), scriptUpdateURL: metaVal('updateURL'), scriptWillUpdate: true, scriptHandler: 'Custom Right-Click Menu', version: (await browserAPI.runtime.getManifest()).version }, resources: modules.storages.resources.get(node.id) || {} }; } export function getInExcludes(node: CRM.ScriptNode): { excludes: string[], includes: string[] } { const excludes: string[] = []; const includes: string[] = []; if (node.triggers) { for (let i = 0; i < node.triggers.length; i++) { if (node.triggers[i].not) { excludes.push(node.triggers[i].url); } else { includes.push(node.triggers[i].url); } } } return { excludes, includes } } export function genTabData(tabId: TabId, key: number[], nodeId: CRM.NodeId<CRM.ScriptNode>, script: string) { modules.Util.setMapDefault(modules.crmValues.tabData, tabId, { libraries: new window.Map(), nodes: new window.Map() }); modules.Util.setMapDefault(modules.crmValues.tabData.get(tabId).nodes, nodeId, []); modules.crmValues.tabData.get(tabId).nodes.get(nodeId).push({ secretKey: key, usesLocalStorage: script.indexOf('localStorageProxy') > -1 }); } export function createHandler(node: CRM.ScriptNode): ClickHandler { return async (info: _browser.contextMenus.OnClickData, tab: _browser.tabs.Tab, isAutoActivate: boolean = false) => { let key: number[] = []; let err = false; try { key = modules.Util.createSecretKey(); } catch (e) { //There somehow was a stack overflow err = e; } if (err) { browserAPI.tabs.executeScript(tab.id, { code: 'alert("Something went wrong very badly, please go to your Custom Right-Click Menu' + ' options page and remove any sketchy scripts.")' }).then(() => { browserAPI.runtime.reload(); }); } else { const indentUnit = ' '; const [ contextData, { greaseMonkeyData, runAt }, script, tabIndex ] = await window.Promise.all<any>([ modules.Util.iipe<EncodedContextData>(async () => { //If it was triggered by clicking, ask contentscript about some data if (isAutoActivate) { return null; } else { const response = await browserAPI.tabs.sendMessage(tab.id, { type: 'getLastClickInfo' }) as EncodedContextData; return response; } }), modules.Util.iipe<{ greaseMonkeyData: GreaseMonkeyData, runAt: _browser.extensionTypes.RunAt }>(async () => { const metaData: { [key: string]: any; } = MetaTags.getMetaTags(await modules.Util.getScriptNodeScript(node)); let runAt: _browser.extensionTypes.RunAt = metaData['run-at'] || metaData['run_at'] || 'document_end'; if (runAt && Array.isArray(runAt)) { runAt = runAt[0]; } const { excludes, includes } = getInExcludes(node) return { greaseMonkeyData: await generateGreaseMonkeyData(metaData, node, includes, excludes, tab), runAt } }), modules.Util.iipe<string>(async () => { return (await modules.Util.getScriptNodeScript(node)).split('\n').map((line) => { return indentUnit + line; }).join('\n'); }), modules.Util.iipe<number>(async () => { genTabData(tab.id, key, node.id, await modules.Util.getScriptNodeScript(node)) const tabIndex = modules.crmValues.tabData .get(tab.id).nodes .get(node.id).length - 1; modules.Logging.Listeners.updateTabAndIdLists(); return tabIndex; }) ]) as [EncodedContextData, { greaseMonkeyData: GreaseMonkeyData; runAt: _browser.extensionTypes.RunAt }, string, number]; const safeNode = makeSafe(node); (safeNode as any).permissions = node.permissions; const code = await genCodeOnPage({ node, safeNode, tab, info, key, contextData, greaseMonkeyData, indentUnit, script, tabIndex }); const usesUnsafeWindow = (await modules.Util.getScriptNodeScript(node)).indexOf('unsafeWindow') > -1; const scripts = await getScriptsToRun(code, runAt, node, usesUnsafeWindow); executeScripts(node.id, tab.id, scripts, usesUnsafeWindow); } }; } } export namespace CRMNodes.Script.Background { async function loadBackgroundPageLibs(node: CRM.ScriptNode): Promise<{ libraries: string[]; code: string[]; }> { const libraries = []; const code = []; const globalLibraries = modules.storages.storageLocal.libraries; const urlDataPairs = modules.storages.urlDataPairs; for (let i = 0; i < node.value.libraries.length; i++) { let lib: { name: string; url?: string; code?: string; location?: string; } | { code: string; location?: string; }; if (globalLibraries) { for (let j = 0; j < globalLibraries.length; j++) { if (globalLibraries[j].name === node.value.libraries[i].name) { const currentLib = globalLibraries[j]; if (currentLib.ts && currentLib.ts.enabled) { lib = { code: await modules.Util.getLibraryCode(currentLib) } } else { lib = currentLib; } break; } else { //Resource hasn't been registered with its name, try if it's an anonymous one if (node.value.libraries[i].name === null) { //Check if the value has been registered as a resource if (urlDataPairs.get(node.value.libraries[i].url as any)) { lib = { code: urlDataPairs.get(node.value.libraries[i].url as any).dataString }; } } } } } if (lib) { if (lib.location) { libraries.push(`/js/defaultLibraries/${lib.location}`); } else { code.push(lib.code); } } } return { libraries: libraries, code: code }; } async function genCodeBackground(code: string[], { key, node, script, safeNode, indentUnit, greaseMonkeyData }: { key: number[]; node: CRM.ScriptNode; script: string; safeNode: CRM.SafeNode; indentUnit: string; greaseMonkeyData: GreaseMonkeyData; }, doDebug: boolean): Promise<string> { const enableBackwardsCompatibility = (await modules.Util.getScriptNodeScript(node)).indexOf('/*execute locally*/') > -1 && node.isLocal; const catchErrs = modules.storages.storageLocal.catchErrors; const supportedBrowserAPIs = []; if (BrowserAPI.isBrowserAPISupported('chrome')) { supportedBrowserAPIs.push('chrome'); } if (BrowserAPI.isBrowserAPISupported('browser')) { supportedBrowserAPIs.push('browser'); } modules.Util.setMapDefault(modules.storages.nodeStorage, node.id, {}); modules.Util.setMapDefault(modules.storages.nodeStorageSync, node.id, {}); return [ code.join('\n'), [ `var crmAPI = new (window._crmAPIRegistry.pop())(${[ safeNode, node.id, { id: 0 }, {}, key, modules.storages.nodeStorage.get(node.id), null, greaseMonkeyData, true, fixOptionsErrors((node.value && node.value.options) || {}), enableBackwardsCompatibility, 0, browserAPI.runtime.id, supportedBrowserAPIs.join(','), modules.storages.nodeStorageSync.get(node.id) ] .map((param) => { if (param === void 0) { return JSON.stringify(null); } return JSON.stringify(param); }).join(', ')});` ].join(', '), modules.constants.templates.globalObjectWrapperCode('self', 'selfWrapper', void 0, void 0), `${catchErrs ? 'try {' : ''}`, 'function main(crmAPI, self, menuitemid, parentmenuitemid, mediatype,' + `${indentUnit}linkurl, srcurl, pageurl, frameurl, frameid,` + `${indentUnit}selectiontext, editable, waschecked, checked) {`, doDebug ? 'debugger;' : '', script, '}', `window.crmAPI = self.crmAPI = crmAPI`, `crmAPI.onReady(function() {main(crmAPI, selfWrapper)});`, `${catchErrs ? [ `} catch (error) {`, `${indentUnit}if (crmAPI.debugOnError) {`, `${indentUnit}${indentUnit}debugger;`, `${indentUnit}}`, `${indentUnit}throw error;`, `}` ].join('\n') : ''}` ].join('\n') } async function isValidBackgroundPage(node: CRM.ScriptNode) { if (!node || node.type !== 'script' || !await modules.Util.getScriptNodeScript(node, 'background') || await modules.Util.getScriptNodeScript(node, 'background') === '') { return false; } return true; } export async function createBackgroundPage(node: CRM.ScriptNode, doDebug: boolean = false) { if (!await isValidBackgroundPage(node)) { return; } let isRestart = false; if (modules.background.byId.has(node.id)) { isRestart = true; await modules.Logging.backgroundPageLog(node.id, null, await window.__(I18NKeys.background.crm.restartingBackgroundPage)); modules.background.byId.get(node.id).terminate(); modules.Logging.backgroundPageLog(node.id, null, await window.__(I18NKeys.background.crm.terminatedBackgroundPage)); } if (modules.background.byId.has(node.id)) { modules.background.byId.get(node.id).terminate(); } //There can only be one backgroundscript if (modules.crmValues.tabData.has(0) && modules.crmValues.tabData.get(0).nodes.has(node.id)) { modules.crmValues.tabData.get(0).nodes.delete(node.id); } let key: number[] = []; let err = false; try { key = modules.Util.createSecretKey(); } catch (e) { //There somehow was a stack overflow err = e; } if (err) { window.logAsync(window.__(I18NKeys.background.crm.setupError, node.id), err); throw err; } const indentUnit = ' '; const [{ code: backgroundPageCode, libraries }, script, greaseMonkeyData ] = await window.Promise.all<any>([ modules.Util.iipe<{ code: string[]; libraries: string[] }>(async () => { return await loadBackgroundPageLibs(node); }), modules.Util.iipe<string>(async () => { return (await modules.Util.getScriptNodeScript(node, 'background')).split('\n').map((line) => { return indentUnit + line; }).join('\n'); }), modules.Util.iipe<any>(async () => { const metaData = MetaTags.getMetaTags(await modules.Util.getScriptNodeScript(node)); const { excludes, includes } = Handler.getInExcludes(node); return await Handler.generateGreaseMonkeyData(metaData, node, includes, excludes, { incognito: false }); }), modules.Util.iipe<void>(async () => { Handler.genTabData(0, key, node.id, await modules.Util.getScriptNodeScript(node, 'background')); modules.Logging.Listeners.updateTabAndIdLists(); }) ]) as [{ code: string[]; libraries: string[] }, string, GreaseMonkeyData]; const safeNode = makeSafe(node) as any; safeNode.permissions = node.permissions; const code = await genCodeBackground(backgroundPageCode, { key, node, script, safeNode, indentUnit, greaseMonkeyData }, doDebug); modules.Sandbox.sandbox(node.id, code, libraries, key, () => { const instancesArr: { id: TabId|string; tabIndex: TabIndex; }[] = []; const allInstances = modules.crmValues.nodeInstances; modules.Util.setMapDefault(allInstances, node.id, new window.Map()); const nodeInstances = allInstances.get(node.id); modules.Util.iterateMap(nodeInstances, (tabId) => { try { modules.crmValues.tabData.get(tabId).nodes.get(node.id) .forEach((tabIndexInstance, index) => { modules.Util.postMessage(tabIndexInstance.port, { messageType: 'dummy' }); instancesArr.push({ id: tabId, tabIndex: index }); }); } catch (e) { nodeInstances.delete(tabId); } }); return instancesArr; }, (worker) => { modules.background.byId.set(node.id, worker); if (isRestart) { modules.Logging.log(node.id, '*', `Background page [${node.id}]: `, 'Restarted background page...'); } }); } export async function createBackgroundPages() { //Iterate through every node modules.Util.asyncIterateMap(modules.crm.crmById, async (_nodeId, node) => { if (node.type === 'script' && node.value.backgroundScript.length > 0) { if (isValidBackgroundPage(node)) { window.info(await window.__(I18NKeys.background.crm.createdBackgroundPage, node.id)); } await createBackgroundPage(node); } }); } } export namespace CRMNodes.MetaTags { export function getMetaIndexes(code: string): { start: number; end: number; }[] { const indexes: { start: number; end: number; }[] = []; let metaStart = -1; let metaEnd = -1; const lines = code.split('\n'); for (let i = 0; i < lines.length; i++) { if (metaStart !== -1) { if (lines[i].indexOf('==/UserScript==') > -1 || lines[i].indexOf('==/UserStyle==') > -1) { metaEnd = i; indexes.push({ start: metaStart, end: metaEnd }); metaStart = -1; metaEnd = -1; } } else if (lines[i].indexOf('==UserScript==') > -1 || lines[i].indexOf('==UserStyle==') > -1) { metaStart = i; } } return indexes; } export function getMetaLines(code: string, fromCache: any = true): string[] { if (fromCache) { return modules.Caches.cacheCall(getMetaLines, arguments, true); } const metaIndexes = getMetaIndexes(code); const metaLines: string[] = []; const lines = code.split('\n'); for (const { start, end } of metaIndexes) { for (let i = start + 1; i < end; i++) { metaLines.push(lines[i]); } } return metaLines; } const cachedData: Map<string, { [key: string]: any; }> = new window.Map<string, { [key: string]: any; }>(); export function getMetaTags(code: string): { [key: string]: string[]; } { const hash = window.md5(code); if (cachedData.has(hash)) { return cachedData.get(hash); } const metaLines = getMetaLines(code); const metaTags: { [key: string]: any; } = {}; let currentMatch: { key: string; value: string; } = null; const regex = /@(\w+)(\s+)(.+)/; for (let i = 0; i < metaLines.length; i++) { const regexMatches = metaLines[i].match(regex); if (regexMatches) { if (currentMatch) { //Write previous match to object const { key, value } = currentMatch; metaTags[key] = metaTags[key] || []; metaTags[key].push(value); } currentMatch = { key: regexMatches[1], value: regexMatches[3] } } else { //No match, that means the last metatag is //still continuing, add to that currentMatch.value += ('\n' + metaLines[i]); } } if (currentMatch) { //Write previous match to object const { key, value } = currentMatch; metaTags[key] = metaTags[key] || []; metaTags[key].push(value); } cachedData.set(hash, metaTags); return metaTags; } export function getMetaTag(metaTags: { [key: string]: any; }, tag: string): any { if (tag in metaTags) { if (Array.isArray(metaTags[tag])) { return metaTags[tag][0]; } return metaTags[tag]; } return undefined; } export function getlastMetaTagValue(metaTags: { [key: string]: any; }, key: string) { return metaTags[key] && metaTags[key][metaTags[key].length - 1]; } } export namespace CRMNodes.Script.Updating { export async function removeOldNode(id: CRM.GenericNodeId) { const { children } = modules.crm.crmById.get(id); if (children) { for (let i = 0; i < children.length; i++) { await removeOldNode(children[i].id); } } if (modules.background.byId.has(id)) { modules.background.byId.get(id).terminate(); modules.background.byId.delete(id) } modules.crm.crmById.delete(id); modules.crm.crmByIdSafe.delete(id); const contextMenuId = modules.crmValues.contextMenuIds.get(id); if (contextMenuId !== undefined && contextMenuId !== null) { await browserAPI.contextMenus.remove(contextMenuId).catch(() => {}); } } export function registerNode(node: CRM.Node, oldPath?: number[]) { //Update it in CRM tree if (oldPath !== undefined && oldPath !== null) { let currentTree = modules.storages.settingsStorage.crm; for (const index of oldPath.slice(0, -1)) { const { children } = currentTree[index]; if (!children) { return; } currentTree = children; } currentTree[modules.Util.getLastItem(oldPath)] = node; } else { modules.storages.settingsStorage.crm.push(node); } } function deduceLaunchmode(metaTags: { [key: string]: any; }, triggers: CRM.Triggers): CRMLaunchModes { //if it's explicitly set in a metatag, use that value if (MetaTags.getlastMetaTagValue(metaTags, 'CRM_LaunchMode')) { return MetaTags.getlastMetaTagValue(metaTags, 'CRM_LaunchMode'); } if (triggers.length === 0) { //No triggers, probably only run on clicking return CRMLaunchModes.RUN_ON_CLICKING; } return CRMLaunchModes.RUN_ON_SPECIFIED; } function createUserscriptTriggers(metaTags: { [key: string]: any; }): { triggers: CRM.Triggers, launchMode: CRMLaunchModes } { let triggers: CRM.Triggers = []; const includes: string[] = (metaTags['includes'] || []).concat(metaTags['include']); if (includes) { triggers = triggers.concat(includes.map(include => ({ url: include, not: false })).filter(include => (!!include.url))); } const matches: string[] = metaTags['match']; if (matches) { triggers = triggers.concat(matches.map(match => ({ url: match, not: false })).filter(match => (!!match.url))); } const excludes: string[] = metaTags['exclude']; if (excludes) { triggers = triggers.concat(excludes.map(exclude => ({ url: exclude, not: false })).filter(exclude => (!!exclude.url))); } //Filter out duplicates triggers = triggers.filter((trigger, index) => (triggers.indexOf(trigger) === index)); return { triggers, launchMode: deduceLaunchmode(metaTags, triggers) } } async function createUserscriptScriptData(metaTags: { [key: string]: any; }, code: string, node: Partial<CRM.Node>) { node.type = 'script'; const scriptNode = node as CRM.ScriptNode; //Libraries let libs: { url: string; name: string; }[] = []; if (metaTags['CRM_libraries']) { (metaTags['CRM_libraries'] as EncodedString<{ url: string; name: string; }>[]).forEach(item => { try { libs.push(JSON.parse(item)); } catch (e) { } }); } const requires: string[] = metaTags['require'] || []; const anonymousLibs: CRM.Library[] = []; for (let i = 0; i < requires.length; i++) { let skip = false; for (let j = 0; j < libs.length; j++) { if (libs[j].url === requires[i]) { skip = true; break; } } if (skip) { continue; } anonymousLibs.push({ url: requires[i], name: null }); } // (anonymousLibs as { // url: string; // name: null; // }[]).forEach(anonymousLib => { // modules.Resources.Anonymous.handle({ // type: 'register', // name: anonymousLib.url, // url: anonymousLib.url, // scriptId: scriptNode.id // }); // }); const { libraries } = await browserAPI.storage.local.get('libraries'); //Install all libraries const newLibs: CRM.InstalledLibrary[] = [ ...libraries, ...(await Promise.all(libs.map(({ name, url }) => { return new Promise<CRM.InstalledLibrary>(async (resolve) => { const code = await modules.Util.xhr(url).catch(() => { resolve(null); }); if (!code) { resolve(null); } resolve({ name, code, url, ts: { enabled: false, code: {} } }); }); }))).filter(val => !!val)]; await browserAPI.storage.local.set({ libraries: newLibs }); await modules.Storages.applyChanges({ type: 'libraries', libraries: newLibs }); libs = libs.concat(anonymousLibs as any); scriptNode.value = modules.constants.templates.getDefaultScriptValue({ script: code, libraries: libs }); } function createUserscriptStylesheetData(metaTags: { [key: string]: any; }, code: string, node: Partial<CRM.Node>) { node = node as CRM.StylesheetNode; node.type = 'stylesheet'; node.value = { stylesheet: code, defaultOn: (metaTags['CRM_defaultOn'] = MetaTags.getlastMetaTagValue(metaTags, 'CRM_defaultOn') || false), toggle: (metaTags['CRM_toggle'] = MetaTags .getlastMetaTagValue(metaTags, 'CRM_toggle') || false), launchMode: CRMLaunchModes.ALWAYS_RUN, options: {}, convertedStylesheet: null }; } async function createUserscriptTypeData(metaTags: { [key: string]: any; }, code: string, node: Partial<CRM.Node>) { if (MetaTags.getlastMetaTagValue(metaTags, 'CRM_stylesheet')) { createUserscriptStylesheetData(metaTags, code, node); } else { await createUserscriptScriptData(metaTags, code, node); } } export async function install(message: { script: string; downloadURL: string; allowedPermissions: CRM.Permission[]; metaTags: { [key: string]: any; }; }) { const oldTree = JSON.parse(JSON.stringify( modules.storages.settingsStorage.crm)); const { path, oldNodeId, node } = await Updating.installUserscript(message.metaTags, message.script, message.downloadURL, message.allowedPermissions); if (path) { //Has old node const nodePath = path as number[]; await removeOldNode(oldNodeId); registerNode(node, nodePath); } else { registerNode(node); } await modules.Storages.uploadChanges('settings', [{ key: 'crm', oldValue: oldTree, newValue: modules.storages.settingsStorage.crm }]); } export async function installUserscript(metaTags: { [key: string]: any; }, code: string, downloadURL: string, allowedPermissions: CRM.Permission[], oldNodeId?: CRM.NodeId<CRM.ScriptNode>): Promise<{ node: CRM.ScriptNode | CRM.StylesheetNode, path?: number[], oldNodeId?: CRM.NodeId<CRM.ScriptNode>, }> { let node: Partial<CRM.ScriptNode | CRM.StylesheetNode> = {}; let hasOldNode = false; if (oldNodeId !== undefined && oldNodeId !== null) { hasOldNode = true; node.id = oldNodeId; } else { node.id = await modules.Util.generateItemId() as CRM.NodeId<CRM.ScriptNode>| CRM.NodeId<CRM.StylesheetNode> } //If userscripts is empty something might have gone wrong, try to re-parse it if (Object.getOwnPropertyNames(metaTags).length === 0) { metaTags = MetaTags.getMetaTags(code); } node.name = MetaTags.getlastMetaTagValue(metaTags, 'name') || 'name'; await createUserscriptTypeData(metaTags, code, node); const { launchMode, triggers } = createUserscriptTriggers(metaTags); node.triggers = triggers; node.value.launchMode = launchMode; const updateUrl = MetaTags.getlastMetaTagValue(metaTags, 'updateURL') || MetaTags.getlastMetaTagValue(metaTags, 'downloadURL') || downloadURL; //Requested permissions let permissions = []; if (metaTags['grant']) { permissions = metaTags['grant']; permissions = permissions.splice(permissions.indexOf('none'), 1); } //NodeInfo node.nodeInfo = { version: MetaTags.getlastMetaTagValue(metaTags, 'version') || null, source: { updateURL: updateUrl || downloadURL, url: updateUrl || MetaTags.getlastMetaTagValue(metaTags, 'namespace') || downloadURL, author: MetaTags.getlastMetaTagValue(metaTags, 'author') || 'Anonymous', autoUpdate: true }, isRoot: true, permissions: permissions, lastUpdatedAt: Date.now(), installDate: new Date().toLocaleDateString() }; if (hasOldNode) { node.nodeInfo.installDate = modules.Util.accessPath( modules.crm.crmById.get(oldNodeId), 'nodeInfo', 'installDate') || node.nodeInfo.installDate; } //Content types if (MetaTags.getlastMetaTagValue(metaTags,'CRM_contentTypes')) { try { node.onContentTypes = JSON.parse(MetaTags.getlastMetaTagValue(metaTags, 'CRM_contentTypes')); } catch (e) { } } if (!node.onContentTypes) { node.onContentTypes = [true, true, true, true, true, true]; } //Allowed permissions node.permissions = allowedPermissions || []; // //Resources // if (metaTags['resource']) { // //Register resources // const resources: string[] = metaTags['resource']; // resources.forEach(resource => { // const resourceSplit = resource.split(/(\s*)/); // const [resourceName, resourceUrl] = resourceSplit; // modules.Resources.Resource.handle({ // type: 'register', // name: resourceName, // url: resourceUrl, // scriptId: node.id as CRM.NodeId<CRM.ScriptNode> // }); // }); // } const { requestPermissions = [] } = await browserAPI.storage.local.get<CRM.StorageLocal>(); const allPermissions = browserAPI.permissions ? await browserAPI.permissions.getAll() : { permissions: [] }; const allowed = allPermissions.permissions || []; const joinedPermissions = [...requestPermissions, ...node.permissions].filter((permission: _browser.permissions.Permission) => { return allowed.indexOf(permission) === -1; }).filter((permission, index, self) => { return self.indexOf(permission) === index; }); browserAPI.storage.local.set({ requestPermissions: joinedPermissions }); if (node.type === 'script') { node = modules.constants.templates.getDefaultScriptNode(node); } else { node = modules.constants.templates.getDefaultStylesheetNode(node); } if (hasOldNode) { const { path } = modules.crm.crmById.get(oldNodeId); return { node: node as CRM.ScriptNode | CRM.StylesheetNode, path: path, oldNodeId: oldNodeId }; } else { return { node: node as CRM.ScriptNode | CRM.StylesheetNode, path: null, oldNodeId: null }; } } function getDownloadURL({ nodeInfo }: CRM.Node) { return nodeInfo && nodeInfo.source && typeof nodeInfo.source !== 'string' && (nodeInfo.source.downloadURL || nodeInfo.source.updateURL || nodeInfo.source.url); } export async function updateScripts() { const updated: { node: CRM.ScriptNode; }[] = []; const oldTree = JSON.parse(JSON.stringify( modules.storages.settingsStorage.crm)); await Promise.all(modules.Util.mapToArr(modules.crm.crmById).map(async ([_id, node]) => { if (node.type !== 'script') { return; } const isRoot = node.nodeInfo && node.nodeInfo.isRoot; const downloadURL = getDownloadURL(node); if (downloadURL && isRoot && node.nodeInfo.source !== 'local' && node.nodeInfo.source.autoUpdate) { await checkNodeForUpdate(node, downloadURL, updated); } })); await onNodeUpdateDone(updated, oldTree) } async function onNodeUpdateDone(updated: { node: CRM.ScriptNode; }[], oldTree: CRM.Tree) { const updatedData = updated.map(({ node: { id, name, nodeInfo }}) => { const oldNode = modules.Storages.findNodeWithId(oldTree, id); return { name: name, id: id, oldVersion: (oldNode && oldNode.nodeInfo && oldNode.nodeInfo.version) || '', newVersion: nodeInfo.version || '' }; }); await modules.Storages.uploadChanges('settings', [{ key: 'crm', oldValue: oldTree, newValue: modules.storages.settingsStorage.crm }]); const { updatedNodes = [] } = await browserAPI.storage.local.get<CRM.StorageLocal>(); const joinedData = [...updatedNodes, ...updatedData]; browserAPI.storage.local.set({ updatedScripts: joinedData }); return joinedData; } function checkNodeForUpdate(node: CRM.ScriptNode, downloadURL: string, updatedScripts: { node: CRM.Node; path?: number[]; oldNodeId?: CRM.NodeId<CRM.ScriptNode>; }[]) { return new Promise<void>((resolve) => { //Do a request to get that script from its download URL if (downloadURL && modules.Util.endsWith(downloadURL, '.user.js')) { try { modules.Util.convertFileToDataURI(downloadURL, async (_dataURI, dataString) => { //Get the meta tags try { const metaTags = MetaTags.getMetaTags(dataString); if (modules.Util.isNewer(metaTags['version'][0], node.nodeInfo.version)) { if (!modules.Util.compareArray(node.nodeInfo.permissions, metaTags['grant']) && !(metaTags['grant'].length === 1 && metaTags['grant'][0] === 'none')) { //New permissions were added, notify user const { addedPermissions = [] } = await browserAPI.storage.local.get<CRM.StorageLocal>(); addedPermissions.push({ node: node.id, permissions: metaTags['grant'].filter((newPermission: CRM.Permission) => { return node.nodeInfo.permissions.indexOf(newPermission) === -1; }) }); await browserAPI.storage.local.set({ addedPermissions: addedPermissions }); } updatedScripts.push(await installUserscript(metaTags, dataString, downloadURL, node.permissions, node.id)); } } catch (err) { window.logAsync(window.__(I18NKeys.background.crm.updateDownload404, 'script', node.id, node.name)); } resolve(null); }, () => { window.logAsync(window.__(I18NKeys.background.crm.updateDownload404, 'script', node.id, node.name)); resolve(null); }); } catch (e) { window.logAsync(window.__(I18NKeys.background.crm.updateDownload404, 'script', node.id, node.name)); resolve(null); } } }); } } export namespace CRMNodes.Running { export function urlIsGlobalExcluded(url: string): boolean { if (modules.storages.globalExcludes.indexOf('<all_urls>') >-1) { return true; } for (let i = 0; i < modules.storages.globalExcludes.length;i++) { const pattern = modules.storages.globalExcludes[i] as MatchPattern; if (pattern && modules.URLParsing.urlMatchesPattern(pattern, url)) { return true; } } return false; } export function executeNode(node: CRM.Node, tab: _browser.tabs.Tab) { if (node.type === 'script') { Script.Handler.createHandler(node as CRM.ScriptNode)({ pageUrl: tab.url, menuItemId: 0, editable: false, modifiers: [] }, tab, true); } else if (node.type === 'stylesheet') { Stylesheet.createClickHandler(node)({ pageUrl: tab.url, menuItemId: 0, editable: false, modifiers: [] }, tab); } else if (node.type === 'link') { Link.createHandler(node)({ pageUrl: tab.url, menuItemId: 0, editable: false, modifiers: [] }, tab); } } export async function executeScriptsForTab(tabId: TabId, isReload: boolean) { try { const tab = await browserAPI.tabs.get(tabId); if (tab.url && modules.Util.canRunOnUrl(tab.url)) { modules.crmValues.tabData.set(tab.id, { libraries: new window.Map(), nodes: new window.Map() }); modules.Logging.Listeners.updateTabAndIdLists(); if (isReload) { modules.GlobalDeclarations.runAlwaysRunNodes(tab); } if (!urlIsGlobalExcluded(tab.url)) { const { toExecuteNodes } = modules; const toExecute = toExecuteNodes.onUrl.documentEnd.filter(({ triggers }) => { return modules.URLParsing.matchesUrlSchemes(triggers, tab.url); }); for (const { id } of toExecuteNodes.always.documentEnd.concat(toExecute)) { executeNode(modules.crm.crmById.get(id), tab); } return { matched: toExecute.length > 0 }; } } } catch(e) { console.log('Error while executing scripts for tab', e); } return { matched: false }; } }; export namespace CRMNodes.Script { } export namespace CRMNodes.Link { function sanitizeUrl(url: string): string { if (url.indexOf('://') === -1) { url = `http://${url}`; } return url; } function substituteSearch(url: string, clickData: _browser.contextMenus.OnClickData) { return url.replace(/%s/g, clickData.selectionText || ''); } export function createHandler(node: CRM.LinkNode): ClickHandler { return (clickData: _browser.contextMenus.OnClickData, tabInfo: _browser.tabs.Tab) => { let finalUrl: string; for (let i = 0; i < node.value.length; i++) { if (node.value[i].newTab) { browserAPI.tabs.create({ windowId: tabInfo.windowId, url: substituteSearch( sanitizeUrl(node.value[i].url), clickData), openerTabId: tabInfo.id }); } else { finalUrl = node.value[i].url; } } if (finalUrl) { browserAPI.tabs.update(tabInfo.id, { url: substituteSearch( sanitizeUrl(finalUrl), clickData) }); } }; } } export namespace CRMNodes.Stylesheet.Updating { export function getDownloadURL({ nodeInfo }: CRM.Node) { return nodeInfo && nodeInfo.source && typeof nodeInfo.source !== 'string' && (nodeInfo.source.downloadURL || nodeInfo.source.updateURL || nodeInfo.source.url); } export async function updateStylesheet(nodeId: CRM.NodeId<CRM.StylesheetNode>) { const node = modules.crm.crmById.get(nodeId) as CRM.StylesheetNode; const url = getDownloadURL(node); const updateData = (await CRMNodes.Stylesheet.Installing.getUserstyleMeta(url)) .sections[node.nodeInfo.source !== 'local' && node.nodeInfo.source.sectionIndex]; const launchData = CRMNodes.Stylesheet.Installing.extractStylesheetData( updateData); const oldTree = JSON.parse(JSON.stringify( modules.storages.settingsStorage.crm)); node.value.launchMode = launchData.launchMode; node.triggers = JSON.parse(JSON.stringify(launchData.triggers)); node.value.stylesheet = launchData.code; await modules.Storages.uploadChanges('settings', [{ key: 'crm', oldValue: oldTree, newValue: modules.storages.settingsStorage.crm }]); } export async function updateStylesheets() { const updated: { node: CRM.StylesheetNode; }[] = []; const oldTree = JSON.parse(JSON.stringify( modules.storages.settingsStorage.crm)); await Promise.all(modules.Util.mapToArr(modules.crm.crmById).map(async ([_id, node]) => { if (node.type !== 'stylesheet') { return; } const isRoot = node.nodeInfo && node.nodeInfo.isRoot; const downloadURL = getDownloadURL(node); if (downloadURL && isRoot && node.nodeInfo.source !== 'local' && node.nodeInfo.source.autoUpdate) { await checkNodeForUpdate(node, downloadURL, updated); } })); await onNodeUpdateDone(updated, oldTree) } function checkNodeForUpdate(node: CRM.StylesheetNode, downloadURL: string, updatedScripts: { node: CRM.Node; }[]) { return new Promise<void>((resolve) => { modules.Util.convertFileToDataURI(downloadURL, async (_, dataString) => { try { const parsed = Installing.getUserstyleMeta(dataString); //Just check whether everything matches for (let i = 0; i < parsed.sections.length; i++) { const section = parsed.sections[i]; const launchData = CRMNodes.Stylesheet.Installing.extractStylesheetData( section); let wasUpdated = false; //Make sure the section index is correct if (node.nodeInfo.source !== 'local' && node.nodeInfo.source.sectionIndex !== i) { continue; } if (node.value.launchMode !== launchData.launchMode) { node.value.launchMode = launchData.launchMode; wasUpdated = true; } if (!modules.Util.compareArray(node.triggers, launchData.triggers)) { node.triggers = JSON.parse(JSON.stringify(launchData.triggers)); wasUpdated = true; } if (node.value.stylesheet !== launchData.code) { node.value.stylesheet = launchData.code; wasUpdated = true; } if (wasUpdated) { updatedScripts.push({ node }); } } resolve(null); } catch(e) { //Malformed data string or wrong URL resolve(null); } }, () => { window.logAsync(window.__(I18NKeys.background.crm.updateDownload404, 'stylesheet', node.id, node.name)); resolve(null); }); }); } async function onNodeUpdateDone(updated: { node: CRM.StylesheetNode; }[], oldTree: CRM.Tree) { const updatedData = updated.map(({ node: { id, name, nodeInfo } }) => { const oldNode = modules.Storages.findNodeWithId(oldTree, id); return { name: name, id: id, oldVersion: modules.Util.accessPath(oldNode, 'nodeInfo', 'version') || undefined, newVersion: nodeInfo.version }; }); await modules.Storages.uploadChanges('settings', [{ key: 'crm', oldValue: oldTree, newValue: modules.storages.settingsStorage.crm }]); const { updatedNodes = [] } = await browserAPI.storage.local.get<CRM.StorageLocal>(); const joinedData = [...updatedNodes, ...updatedData]; browserAPI.storage.local.set({ updatedScripts: joinedData }); return joinedData; } } export namespace CRMNodes.Stylesheet.Options { function getOptionValue(option: CRM.OptionsValue): any { switch (option.type) { case 'array': return option.items; case 'boolean': case 'number': case 'string': case 'color': return option.value; case 'choice': return option.values[option.selected]; } } const _variableRegex = /\/\*\[\[((.)+)\]\]\*\//; function preprocessUSO(id: number, stylesheet: string, options: CRM.Options): string { let match: any; while ((match = _variableRegex.exec(stylesheet))) { const name = match[1]; if (!(name in options)) { window.logAsync(window.__(I18NKeys.background.crm.optionNotFound, name, id)); //Prevent it from matching again stylesheet = stylesheet.replace(_variableRegex, `/*[${name}]*/`); } else { const value = getOptionValue(options[name]); stylesheet = stylesheet.replace(_variableRegex, value); } } return stylesheet; } type Preprocessor = 'less'|'stylus'|'default'|'uso'; function parseVar(value: string) { const [type, name, ...rest] = value.replace(/\n/g, '').split(' '); const joined = rest.join(' ').trim(); let label: string; let lastLabelChar: number; if (joined.indexOf('"') === 0 || joined.indexOf("'") === 0) { const strChar = joined[0]; //Find end of string label = joined.slice(1, 1 + joined.slice(1).indexOf(strChar)); } else { label = rest[0]; } lastLabelChar = type.length + 1 + name.length + 1 + label.length + 2; const defaultValue = value.replace(/\n/g, '').slice(lastLabelChar).trim(); return { type, name, label, defaultValue } } function metaTagVarTypeToCodeOptionType(type: string) { switch (type) { case 'text': return 'string'; case 'color': return 'color'; case 'checkbox': return 'boolean'; case 'select': return 'choice'; } return '?'; } function metaTagVarsToCodeOptions(stylesheet: string, options: CRM.Options|string) { const metaTags = MetaTags.getMetaTags(stylesheet); const vars = [...(metaTags['var'] || []), ...(metaTags['advanced'] || [])]; if (vars.length === 0) { return null; } else { const obj: CRM.Options = {}; let option; vars.forEach((value: string) => { const { type, name, label, defaultValue } = parseVar(value); const descriptor = {...(typeof options !== 'string' && options[name] || {}), ...{ type: metaTagVarTypeToCodeOptionType(type), descr: label } as Partial<CRM.OptionsValue>}; switch (type) { case 'text': case 'color': case 'checkbox': option = typeof options !== 'string' && options[name] as CRM.OptionString|CRM.OptionColorPicker| CRM.OptionCheckbox; if (option && option.value === null) { (descriptor as CRM.OptionString|CRM.OptionColorPicker|CRM.OptionCheckbox) .value =defaultValue; } break; case 'select': try { const parsed = JSON.parse(defaultValue); if (Array.isArray(defaultValue)) { obj[name] = {...descriptor, ...{ values: defaultValue.map((value) => { if (value.indexOf(':') > -1) { return value.split(':')[0]; } else { return value; } }), selected: 0 }} as CRM.OptionChoice; } else { obj[name] = {...descriptor, ...{ values: Object.getOwnPropertyNames(parsed).map((name) => { return parsed[name]; }), selected: 0 }} as CRM.OptionChoice; } } catch(e) { obj[name] = {...descriptor, ...{ values: [], selected: 0 }} as CRM.OptionChoice; break; } } obj[name] = descriptor as CRM.OptionsValue; }); return obj; } } function getPreprocessorFormat(preprocessor: Preprocessor|string, options: CRM.Options): { key: string; value: string; }[] { if (preprocessor === 'less' || preprocessor === 'stylus') { return modules.Util.toArray<CRM.OptionsValue>(options || {}).map(([key, value]) => { switch (value.type) { case 'string': case 'color': case 'number': return { key, value: (value.value === null ? value.defaultValue : value.value) + '' } case 'boolean': return { key, value: value.value ? 'true' : 'false' } case 'array': return { key, value: (value.value === null ? value.defaultValue : value.value).join(' ') }; case 'choice': return { key, value: value.values[value.selected || 0] + '' } } }); } else if (preprocessor === 'default') { modules.Util.toArray<CRM.OptionsValue>(options || {}).map(([key, value]) => { switch (value.type) { case 'string': case 'color': case 'number': case 'boolean': return { key, value: (value.value === null ? value.defaultValue : value.value) + '' } case 'array': return { key, value: (value.value === null ? value.defaultValue : value.value).join(' ') } case 'choice': return { key, value: (value.values[value.selected || 0]) + '' } } }); } else if (preprocessor === 'uso') { return []; } return []; } function compileVars(stylesheet: string, options: CRM.Options, preprocessor: Preprocessor|string) { const codeOptions = metaTagVarsToCodeOptions(stylesheet, options); const format = getPreprocessorFormat(preprocessor, codeOptions); if (preprocessor === 'less') { return `${format.map(({key, value}) => { return `@${key}:\t${value}`; }).join('\n')}\n${stylesheet}`; } else if (preprocessor === 'stylus') { return `${format.map(({key, value}) => { return `${key} = ${value};`; }).join('\n')}\n${stylesheet}`; } else if (preprocessor === 'default') { return `:root {\n${format.map(({key, value}) => { return `\t--${key}: ${value}`; }).join('\n')}\n}\n${stylesheet}`; } else { return stylesheet; } } function compileLess(stylesheet: string, id: CRM.NodeId<CRM.StylesheetNode>): Promise<string> { return new Promise<string>((resolve) => { window.less.Parser().parse(stylesheet, (err, result) => { if (!err) { resolve(result.toCSS()); } else { window.logAsync(`${window.__(I18NKeys.background.crm.cssCompileError, 'less', id)}:`, err.name, err.message); resolve(stylesheet);; } }); }); } function compileStylus(stylesheet: string, id: CRM.NodeId<CRM.StylesheetNode>): Promise<string> { return new Promise<string>((resolve) => { window.stylus(stylesheet).render((err, result) => { if (!err) { resolve(result.trim()); } else { window.logAsync(`${window.__(I18NKeys.background.crm.cssCompileError, 'stylus', id)}:`, err.name, err.message); resolve(stylesheet);; } }); }); } async function applyPreprocessor(stylesheet: string, id: CRM.NodeId<CRM.StylesheetNode>, preprocessor: Preprocessor|string, options: CRM.Options) { if (preprocessor === 'less') { await modules.Util.execFile('js/libraries/less.js', 'less'); return await compileLess(stylesheet, id); } else if (preprocessor === 'stylus') { await modules.Util.execFile('js/libraries/stylus.js', 'stylus'); return await compileStylus(stylesheet, id); } else if (preprocessor === 'uso') { return preprocessUSO(id, stylesheet, options); } else { return stylesheet; } } async function convertStylesheet(id: CRM.NodeId<CRM.StylesheetNode>, stylesheet: string, options: CRM.Options): Promise<string> { const meta = MetaTags.getMetaTags(stylesheet); const vars = [...(meta['var'] || []), ...(meta['advanced'] || [])]; const preprocessor = (meta['preprocessor'] && meta['preprocessor'][0]) || (vars.length ? 'uso' : 'default') return await applyPreprocessor(compileVars(stylesheet, options, preprocessor), id, preprocessor, options) } export async function getConvertedStylesheet(node: CRM.StylesheetNode): Promise<string> { if (node.value.convertedStylesheet && node.value.convertedStylesheet.options === JSON.stringify(node.value.options)) { return node.value.convertedStylesheet.stylesheet; } node.value.convertedStylesheet = { options: JSON.stringify(node.value.options), stylesheet: await convertStylesheet(node.id, node.value.stylesheet, typeof node.value.options === 'string' ? {} : node.value.options) }; return node.value.convertedStylesheet.stylesheet; } } export namespace CRMNodes.Stylesheet.Installing { function triggerify(url: string): string { const match = /((http|https|file|ftp):\/\/)?(www\.)?((\w+)\.)*((\w+)?|(\w+)?(\/(.*)))?/g .exec(url); return [ match[2] || '*', '://', (match[4] && match[6]) ? match[4] + match[6] : '*', match[7] || '/' ].join(''); } export function extractStylesheetData(data: { domains: string[]; regexps: string[]; urlPrefixes: string[]; urls: string[]; code: string; }) { //Get the @document declaration if (data.domains.length === 0 && data.regexps.length === 0 && data.urlPrefixes.length && data.urls.length === 0) { return { launchMode: 1, triggers: [], code: data.code }; } const triggers: string[] = []; data.domains.forEach((domainRule) => { triggers.push(`*://${domainRule}/*`); }); data.regexps.forEach((regexpRule) => { const match = /((http|https|file|ftp):\/\/)?(www\.)?((\w+)\.)*((\w+)?|(\w+)?(\/(.*)))?/g .exec(regexpRule); triggers.push([ (match[2] ? (match[2].indexOf('*') > -1 ? '*' : match[2]) : '*'), '://', ((match[4] && match[6]) ? ((match[4].indexOf('*') > -1 || match[6].indexOf('*') > -1) ? '*' : match[4] + match[6]) : '*'), (match[7] ? (match[7].indexOf('*') > -1 ? '*' : match[7]) : '*') ].join('')); }); data.urlPrefixes.forEach((urlPrefixRule) => { if (modules.URLParsing.triggerMatchesScheme(urlPrefixRule)) { triggers.push(urlPrefixRule + '*'); } else { triggers.push(triggerify(urlPrefixRule + '*')); } }); data.urls.forEach((urlRule) => { if (modules.URLParsing.triggerMatchesScheme(urlRule)) { triggers.push(urlRule); } else { triggers.push(triggerify(urlRule)); } }); return { launchMode: 2, triggers: triggers.map((trigger) => { return { url: trigger, not: false }; }), code: data.code }; } function canBeUpdated(node: CRM.StylesheetNode, data: { md5Url :string; name: string; originalMd5: string; updateUrl: string; url: string; sections: { domains: string[]; regexps: string[]; urlPrefixes: string[]; urls: string[]; code: string; }[]; version?: string; }) { if (data.version && node.nodeInfo.version) { return modules.Storages.getVersionDiff(node.nodeInfo.version, data.version) === 1; } //Just check whether everything matches for (let i = 0; i < data.sections.length; i++) { const section = data.sections[i]; const launchData = CRMNodes.Stylesheet.Installing.extractStylesheetData( section); //Make sure the section index is correct if (node.nodeInfo.source !== 'local' && node.nodeInfo.source.sectionIndex !== i) { continue; } if (node.value.launchMode !== launchData.launchMode || !modules.Util.compareArray(node.triggers, launchData.triggers) || node.value.stylesheet !== launchData.code) { return true; } } return false; } export async function getInstalledStatus(url: string) { const results: { node: CRM.StylesheetNode; state: 'installed'|'updatable' }[] = []; let code: string; try { code = await modules.Util.xhr(url); } catch(e) { return []; } const data = await getUserstyleMeta(code); await modules.Util.crmForEachAsync(modules.crm.crmTree, async (node) => { if (node.type !== 'stylesheet') { return; } if (node.nodeInfo && node.nodeInfo.source && node.nodeInfo.source !== 'local' && (node.nodeInfo.source.updateURL === url || node.nodeInfo.source.downloadURL === url)) { if (canBeUpdated(node, data)) { results.push({ node, state: 'updatable', }); } else { results.push({ node, state: 'installed' }); } } }); return results; } function stringStartsFromHere(haystack: string, index: number, needle: string) { for (let i = 0; i < needle.length; i++) { if (haystack[index + i] !== needle[i]) { return false; } } return true; } function findDocDeclarations(code: string): { start: number; firstBracket: number; end: number; }[] { const declarations: { start: number; firstBracket: number; end: number; }[] = []; let end = -1; let start = -1; let firstBracket = -1; let openBrackets = 0; let waitingForOpenBracket: boolean = true; for (let i = 0; i < code.length; i++) { const char = code[i]; if (stringStartsFromHere(code, i, '@-moz-document') || stringStartsFromHere(code, i, '@document')) { if (start !== -1) { end = i - 1; declarations.push({ start, end, firstBracket }); start = end = firstBracket = -1; } openBrackets = 0; waitingForOpenBracket = true; if (code[i + 1] === '-') { i += '@-moz-document'.length; } else { i += '@document'.length; } start = i; } if (openBrackets === 0 && waitingForOpenBracket === false) { end = i; waitingForOpenBracket = true; declarations.push({ start, end, firstBracket }); start = end = firstBracket = -1; } if (char === '{') { waitingForOpenBracket = false; if (firstBracket === -1) { firstBracket = i; } openBrackets += 1; } else if (char === '}') { openBrackets -= 1; } } return declarations; } function getMetaFunction(str: string) { const exec = /(.*)\(['"](.*)['"]\)/.exec(str); if (!exec) { return { fn: null, url: null } } return { fn: exec[1], url: exec[2] } } function getUrls(code: string) { const metaLines = MetaTags.getMetaLines(code); return findDocDeclarations(code).map(({ start, end, firstBracket }) => { const meta = code.slice(start, firstBracket); const metaPrefix = metaLines.length > 0 ? `/* ==UserStyle==\n${metaLines.map((line) => { return `${line}`; }).join('\n')}\n==/UserStyle==*/` : ''; const metaData: { domains: string[]; regexps: string[]; urlPrefixes: string[]; urls: string[]; code: string; } = { code: `${metaPrefix}\n${code.slice(firstBracket + 1, end - 1)}`, domains: [], regexps: [], urlPrefixes: [], urls: [] }; const metaDeclarations = meta.split(',').map(str => str.trim()).map((str) => { return getMetaFunction(str); }); for (const { fn, url } of metaDeclarations) { switch (fn) { case 'url': metaData.urls.push(url); break; case 'url-prefix': metaData.urlPrefixes.push(url); break; case 'domain': metaData.domains.push(url); break; case 'regexp': metaData.regexps.push(url); break; } } return metaData; }); } export function getUserstyleMeta(code: EncodedString<{ sections: { domains: string[]; regexps: string[]; urlPrefixes: string[]; urls: string[]; code: string; }[]; md5Url :string; name: string; originalMd5: string; updateUrl: string; url: string; }>|string): { sections: { domains: string[]; regexps: string[]; urlPrefixes: string[]; urls: string[]; code: string; }[]; md5Url :string; name: string; originalMd5: string; updateUrl: string; url: string; version?: string; author?: string; } { let parsable: boolean = false; try { JSON.parse(code); parsable = true; } catch(e) { } if (parsable) { return JSON.parse(code); } else { const metaTags = MetaTags.getMetaTags(code); return { sections: getUrls(code), md5Url: window.md5(code), name: MetaTags.getMetaTag(metaTags, 'name') || 'Userstyle', originalMd5: window.md5(code), updateUrl: MetaTags.getMetaTag(metaTags, 'updateURL') || MetaTags.getMetaTag(metaTags, 'homepageURL') || undefined, url: MetaTags.getMetaTag(metaTags, 'homepageURL'), version: MetaTags.getMetaTag(metaTags, 'version'), author: MetaTags.getMetaTag(metaTags, 'author') } } } export async function installStylesheet(data: { downloadURL: string; code: string|EncodedString<{ sections: { domains: string[]; regexps: string[]; urlPrefixes: string[]; urls: string[]; code: string; }[]; md5Url :string; name: string; originalMd5: string; updateUrl: string; url: string; }>; author: string name?: string; }) { const stylesheetData = getUserstyleMeta(data.code); if ((await getInstalledStatus(data.downloadURL)).length > 0) { //Already installed, quit return; } const ids = await modules.Util.getMultipleItemIds(stylesheetData.sections.length); await modules.Util.promiseChain(stylesheetData.sections.map((section, index) => { return async () => { const sectionData = extractStylesheetData(section); const node = modules.constants.templates .getDefaultStylesheetNode({ isLocal: false, name: data.name || stylesheetData.name, nodeInfo: { version: '1.0.0', source: { updateURL: stylesheetData.updateUrl, url: stylesheetData.url, author: stylesheetData.author || data.author, sectionIndex: index, downloadURL: data.downloadURL, autoUpdate: true }, permissions: [], installDate: new Date().toLocaleDateString() }, triggers: sectionData.triggers, value: { launchMode: sectionData.launchMode, stylesheet: sectionData.code }, id: ids[index] }); const crmFn = new modules.CRMAPICall.Instance(null, null); await crmFn.moveNode(node, {}); } })); } }; export namespace CRMNodes.Stylesheet { export function createToggleHandler(node: CRM.StylesheetNode): ClickHandler { return async (info: _browser.contextMenus.OnClickData, tab: _browser.tabs.Tab) => { let code: string; const className = node.id + '' + tab.id; if (info.wasChecked) { code = [ `var nodes = Array.prototype.slice.apply(document.querySelectorAll(".styleNodes${className}")).forEach(function(node){`, 'node.remove();', '});' ].join(''); } else { const css = (await Options.getConvertedStylesheet(node)).replace(/[ |\n]/g, ''); code = [ 'var CRMSSInsert=document.createElement("style");', `CRMSSInsert.className="styleNodes${className}";`, 'CRMSSInsert.type="text/css";', `CRMSSInsert.appendChild(document.createTextNode(${JSON .stringify(css)}));`, 'document.head.appendChild(CRMSSInsert);' ].join(''); } if (!modules.crmValues.nodeTabStatuses.get(node.id).tabs.has(tab.id)) { modules.crmValues.nodeTabStatuses.get(node.id).tabs.set(tab.id, {}); } modules.crmValues.nodeTabStatuses.get(node.id).tabs.get(tab.id).checked = info.checked; browserAPI.tabs.executeScript(tab.id, { code: code, allFrames: true }); }; } export function createClickHandler(node: CRM.StylesheetNode): ClickHandler { return async (_info: _browser.contextMenus.OnClickData, tab: _browser.tabs.Tab) => { const className = node.id + '' + tab.id; const css = (await Options.getConvertedStylesheet(node)).replace(/[ |\n]/g, ''); const code = [ '(function() {', `if (document.querySelector(".styleNodes${className}")) {`, 'return false;', '}', 'var CRMSSInsert=document.createElement("style");', `CRMSSInsert.classList.add("styleNodes${className}");`, 'CRMSSInsert.type="text/css";', `CRMSSInsert.appendChild(document.createTextNode(${JSON.stringify(css)}));`, 'document.head.appendChild(CRMSSInsert);', '}());' ].join(''); browserAPI.tabs.executeScript(tab.id, { code: code, allFrames: true }); return node.value.stylesheet; }; } } export namespace CRMNodes.NodeCreation { function getStylesheetReplacementTabs(node: CRM.Node): { id: TabId; }[] { const replaceOnTabs: { id: TabId; }[] = []; const crmNode: CRM.Node = modules.crm.crmById.get(node.id as CRM.GenericNodeId); if (modules.crmValues.contextMenuIds.get(node.id) && //Node already exists crmNode.type === 'stylesheet' && node.type === 'stylesheet' && //Node type stayed stylesheet crmNode.value.stylesheet !== node.value.stylesheet) { //Value changed //Update after creating a new node const statusses = modules.crmValues.nodeTabStatuses; modules.Util.iterateMap(statusses.get(node.id).tabs, (tabId) => { replaceOnTabs.push({ id: tabId }); }); } return replaceOnTabs; } function extractToExecuteNode(node: CRM.Node): ToExecuteNode { const { triggers, id } = node; return { triggers, id } } function pushToGlobalToExecute(node: CRM.Node, launchMode: CRMLaunchModes) { //On by default if (node.type === 'stylesheet' && node.value.toggle && node.value.defaultOn) { if (launchMode === CRMLaunchModes.ALWAYS_RUN || launchMode === CRMLaunchModes.RUN_ON_CLICKING) { modules.toExecuteNodes.always.documentEnd.push(extractToExecuteNode(node)); } else if (launchMode === CRMLaunchModes.RUN_ON_SPECIFIED || launchMode === CRMLaunchModes.SHOW_ON_SPECIFIED) { modules.toExecuteNodes.onUrl.documentEnd.push(extractToExecuteNode(node)); } } } function handleHideOnPages(node: CRM.Node, launchMode: CRMLaunchModes, rightClickItemOptions: ContextMenuCreateProperties) { if ((node['showOnSpecified'] && (node.type === 'link' || node.type === 'divider' || node.type === 'menu')) || launchMode === CRMLaunchModes.SHOW_ON_SPECIFIED) { rightClickItemOptions.documentUrlPatterns = []; modules.crmValues.hideNodesOnPagesData.set(node.id, []); for (let i = 0; i < node.triggers.length; i++) { const prepared = modules.URLParsing.prepareTrigger(node.triggers[i].url); if (prepared) { if (node.triggers[i].not) { modules.crmValues.hideNodesOnPagesData.get(node.id) .push({ not: false, url: prepared }); } else { rightClickItemOptions.documentUrlPatterns.push(prepared); } } } } } function generateClickHandler(node: CRM.Node, rightClickItemOptions: ContextMenuCreateProperties) { //It requires a click handler switch (node.type) { case 'divider': rightClickItemOptions.type = 'separator'; break; case 'link': rightClickItemOptions.onclick = Link.createHandler(node); break; case 'script': rightClickItemOptions.onclick = Script.Handler.createHandler(node); break; case 'stylesheet': if (node.value.toggle) { rightClickItemOptions.type = 'checkbox'; rightClickItemOptions.onclick = Stylesheet.createToggleHandler(node); rightClickItemOptions.checked = node.value.defaultOn; } else { rightClickItemOptions.onclick = Stylesheet.createClickHandler(node); } modules.crmValues.nodeTabStatuses.set(node.id, { defaultCheckedValue: node.value.defaultOn, tabs: new window.Map() }); break; } } async function handleContextMenuError(options: ContextMenuCreateProperties, e: _chrome.runtime.LastError|string, idHolder: { id: number|string; }) { if (options.documentUrlPatterns) { window.logAsync(window.__(I18NKeys.background.crm.contextmenuErrorRetry), e); delete options.documentUrlPatterns; idHolder.id = await browserAPI.contextMenus.create(options, async () => { idHolder.id = await browserAPI.contextMenus.create({ title: 'ERROR', onclick: createOptionsPageHandler() }); window.logAsync(window.__(I18NKeys.background.crm.contextmenuError), e); }); } else { window.logAsync(window.__(I18NKeys.background.crm.contextmenuError), e); } } async function generateContextMenuItem(rightClickItemOptions: ContextMenuCreateProperties, idHolder: { id: number|string; }) { try { idHolder.id = await browserAPI.contextMenus.create(rightClickItemOptions, async () => { if ((window as any).chrome && (window as any).chrome.runtime) { const __chrome: typeof _chrome = (window as any).chrome; if (__chrome && __chrome.runtime && __chrome.runtime.lastError) { await handleContextMenuError(rightClickItemOptions, __chrome.runtime.lastError, idHolder); } } else { if (browserAPI.runtime.lastError) { await handleContextMenuError(rightClickItemOptions, browserAPI.runtime.lastError, idHolder); } } }); } catch(e) { await handleContextMenuError(rightClickItemOptions, e, idHolder); } } function getContextmenuGlobalOverrides(node: CRM.Node): ContextMenuOverrides { return modules.crmValues.contextMenuGlobalOverrides.get(node.id); } async function addRightClickItemClick(node: CRM.Node, launchMode: CRMLaunchModes, rightClickItemOptions: ContextMenuCreateProperties, idHolder: { id: number|string; }) { //On by default pushToGlobalToExecute(node, launchMode) handleHideOnPages(node, launchMode, rightClickItemOptions); generateClickHandler(node, rightClickItemOptions); modules.Util.applyContextmenuOverride( rightClickItemOptions, getContextmenuGlobalOverrides(node)); await generateContextMenuItem(rightClickItemOptions, idHolder); modules.crmValues.contextMenuInfoById.set(idHolder.id, { settings: rightClickItemOptions, path: node.path, enabled: false }); } function pushToToExecute(node: CRM.Node, always: boolean, onDocumentStart: boolean) { const toExecute = extractToExecuteNode(node); if (always) { if (onDocumentStart) { modules.toExecuteNodes.always.documentStart.push(toExecute); } else { modules.toExecuteNodes.always.documentEnd.push(toExecute); } } else { if (onDocumentStart) { modules.toExecuteNodes.onUrl.documentStart.push(toExecute); } else { modules.toExecuteNodes.onUrl.documentEnd.push(toExecute); } } } async function hasDocumentStartMetaTag(node: CRM.Node) { if (node.type === 'script') { const meta = MetaTags.getMetaTags(await modules.Util.getScriptNodeScript(node)); let runAtTag = meta['run-at'] || meta['run_at']; if (!Array.isArray(runAtTag)) { runAtTag = [runAtTag]; } return runAtTag[0] === 'document_start'; } return false; } async function setupUserInteraction(node: CRM.Node, rightClickItemOptions: ContextMenuCreateProperties, idHolder: { id: number|string; }) { const launchMode = ((node.type === 'script' || node.type === 'stylesheet') && node.value.launchMode) || CRMLaunchModes.RUN_ON_CLICKING; if (launchMode === CRMLaunchModes.ALWAYS_RUN || launchMode === CRMLaunchModes.RUN_ON_SPECIFIED) { //If always run, place in .always instead of .onUrl //If it's a styesheet or has the run_at=document_start tag, run early pushToToExecute(node, launchMode === CRMLaunchModes.ALWAYS_RUN, node.type === 'stylesheet' || await hasDocumentStartMetaTag(node)); } else if (launchMode !== CRMLaunchModes.DISABLED) { await addRightClickItemClick(node, launchMode, rightClickItemOptions, idHolder); } } export async function createNode(node: CRM.Node, parentId: string|number) { const replaceStylesheetTabs = getStylesheetReplacementTabs(node); const rightClickItemOptions = { title: node.name, contexts: getContexts(node.onContentTypes), parentId: parentId }; const idHolder: { id: number|string; } = { id: null }; await setupUserInteraction(node, rightClickItemOptions, idHolder); const id = idHolder.id; if (replaceStylesheetTabs.length !== 0) { node = node as CRM.StylesheetNode; for (let i = 0; i < replaceStylesheetTabs.length; i++) { const className = node.id + '' + replaceStylesheetTabs[i].id; let code = `var nodes = document.querySelectorAll(".styleNodes${ className }");var i;for (i = 0; i < nodes.length; i++) {nodes[i].remove();}`; const css = node.value.stylesheet.replace(/[ |\n]/g, ''); code += `var CRMSSInsert=document.createElement("style");CRMSSInsert.className="styleNodes${className}";CRMSSInsert.type="text/css";CRMSSInsert.appendChild(document.createTextNode(${JSON.stringify(css)}));document.head.appendChild(CRMSSInsert);`; browserAPI.tabs.executeScript(replaceStylesheetTabs[i].id, { code: code, allFrames: true }); const statusses = modules.crmValues.nodeTabStatuses; statusses.get(node.id).tabs.get(replaceStylesheetTabs[i].id).checked = true; } } return id; } } export namespace CRMNodes.TS { export async function compileAllInTree() { await compileTree(modules.crm.crmTree); } export async function compileNode(node: CRM.ScriptNode|CRM.SafeScriptNode) { if (node.value.ts && node.value.ts.enabled) { node.value.ts.script = await compileChangedScript(node.value.script, node.value.ts.script); node.value.ts.backgroundScript = await compileChangedScript(modules.Util.getScriptNodeJS(node, 'background'), node.value.ts.backgroundScript); } } export async function compileLibrary(library: CRM.InstalledLibrary): Promise<CRM.InstalledLibrary> { if (library.ts && library.ts.enabled) { library.ts.code = await compileChangedScript(library.code, library.ts.code); } return library; } export async function compileAllLibraries(libraries: CRM.InstalledLibrary[]): Promise<CRM.InstalledLibrary[]> { for (const library of libraries) { await compileLibrary(library); } return libraries; } async function compileTree(tree: CRM.Tree) { const length = tree.length; for (let i = 0; i < length; i++) { const node = tree[i]; if (!node) { continue; } if (node.type === 'script') { await compileNode(node); } else if (node.type === 'menu') { await compileTree(node.children); } } } async function compileChangedScript(script: string, compilationData: CRM.TypescriptCompilationData): Promise<CRM.TypescriptCompilationData> { const { sourceHash } = compilationData; const scriptHash = window.md5(script); if (scriptHash !== sourceHash) { return { compiled: await compileScript(script), sourceHash: scriptHash } } return compilationData; } function captureTSDef() { window.module = { exports: {} }; return Promise.resolve(() => { const ts = window.module && window.module.exports; window.ts = window.ts || ts; window.module = undefined; }); } async function compileScript(script: string): Promise<string> { return new window.Promise<string>(async (resolve) => { await window.withAsync(captureTSDef, async () => { await modules.Util.execFile('js/libraries/typescript.js', 'ts'); }); resolve(window.ts.transpile(script, { module: window.ts.ModuleKind.None, target: window.ts.ScriptTarget.ES3, noLib: true, noResolve: true, suppressOutputPathCheck: true })); }); } } export namespace CRMNodes { export let modules: ModuleData; export function initModule(_modules: ModuleData) { modules = _modules; } export type ClickHandler = (clickData: _browser.contextMenus.OnClickData, tabInfo: _browser.tabs.Tab, isAutoActivate?: boolean) => void; export async function updateCrm(toUpdate?: CRM.GenericNodeId[]) { await modules.Storages.uploadChanges('settings', [{ key: 'crm', newValue: JSON.parse(JSON.stringify(modules.crm.crmTree)), oldValue: {} as any }]); TS.compileAllInTree(); await updateCRMValues(); await buildPageCRM(); await modules.MessageHandling.signalNewCRM(); toUpdate && await modules.Storages.checkBackgroundPagesForChange({ toUpdate }); } async function _assertItemIds() { const crmBefore = JSON.stringify(modules.storages.settingsStorage.crm); await modules.Util.crmForEachAsync(modules.storages.settingsStorage.crm, async (node) => { if (!node.id && node.id !== 0) { node.id = await modules.Util.generateItemId(); } }); return crmBefore !== JSON.stringify(modules.storages.settingsStorage.crm); } function _assertCRMNodeShape(node: CRM.Node): boolean { let changed = false; if (node.type !== 'menu') { return false; } if (!node.children) { node.children = []; changed = true; } for (let i = node.children.length - 1; i >= 0; i--) { if (!node.children[i]) { // Remove dead children node.children.splice(i, 1); changed = true; } } for (const child of node.children) { // Put the function first to make sure it's executed // even when changed is true changed = _assertCRMNodeShape(child) || changed; } return changed; } function _assertCRMShape(crm: CRM.Tree) { let changed = false; for (let i = 0; i < crm.length; i++) { // Put the function first to make sure it's executed // even when changed is true changed = _assertCRMNodeShape(crm[i]) || changed; } return changed; } export async function updateCRMValues() { let changed = await _assertItemIds(); changed = _assertCRMShape(modules.storages.settingsStorage.crm) || changed; modules.crm.crmTree = modules.storages.settingsStorage.crm; modules.crm.safeTree = buildSafeTree(modules.storages.settingsStorage.crm); buildNodePaths(modules.crm.crmTree); buildByIdObjects(); if (changed) { await modules.Storages.uploadChanges('settings', [{ key: 'crm', newValue: JSON.parse(JSON.stringify(modules.crm.crmTree)), oldValue: {} as any }]); } } export function makeSafe(node: CRM.Node): CRM.SafeNode { let newNode: CRM.SafeNode = {} as any; if (node.children) { const menuNode = newNode as CRM.SafeMenuNode; menuNode.children = []; for (let i = 0; i < node.children.length; i++) { menuNode.children[i] = makeSafe(node.children[i]); } newNode = menuNode; } const copy = createCopyFunction(node, newNode); copy([ 'id', 'path', 'type', 'name', 'value', 'linkVal', 'menuVal', 'scriptVal', 'stylesheetVal', 'nodeInfo', 'triggers', 'onContentTypes', 'showOnSpecified' ]); return newNode as CRM.SafeNode; } export function handleUserAddedContextMenuErrors() { const __window = window as any; if (__window.chrome && __window.chrome.runtime) { const __chrome: typeof _chrome = __window.chrome; if (__chrome && __chrome.runtime && __chrome.runtime.lastError) { window.logAsync(window.__(I18NKeys.background.crm.userContextmenuError), __chrome.runtime.lastError) } } else { if (browserAPI.runtime.lastError) { window.logAsync(window.__(I18NKeys.background.crm.userContextmenuError), browserAPI.runtime.lastError) } } } async function createUserContextMenuTree(tree: UserAddedContextMenu[]) { const byId = modules.crmValues.userAddedContextMenusById; for (const menu of tree) { const { children, createProperties } = menu; const { parentId } = createProperties; if (parentId && byId.get(parentId)) { //Map mapped value to actual value createProperties.parentId = byId.get(parentId).actualId; } const actualId = await browserAPI.contextMenus.create(createProperties, handleUserAddedContextMenuErrors); menu.actualId = actualId; createUserContextMenuTree(children); } } export async function addUserAddedContextMenuItems() { createUserContextMenuTree(modules.crmValues.userAddedContextMenus); } export function buildPageCRM() { return new Promise<void>((resolve) => { modules.crmValues.nodeTabStatuses = new window.Map(); browserAPI.contextMenus.removeAll().then(async () => { const contexts: CRM.ContentTypes[] = []; modules.Util.crmForEach(modules.crm.crmTree, (node) => { contexts.push(node.onContentTypes || [false, false, false, false, false, false]); }); const done = await modules.Util.lock(modules.Util.LOCK.ROOT_CONTEXTMENU_NODE); modules.crmValues.rootId = await browserAPI.contextMenus.create({ title: modules.storages.settingsStorage.rootName || 'Custom Menu', contexts: CRMNodes.getJoinedContexts(contexts) }); done(); modules.toExecuteNodes = { onUrl: { documentStart: [], documentEnd: [] }, always: { documentStart: [], documentEnd: [] } }; modules.Util.promiseChain(modules.crm.crmTree.map((node, index) => { return () => { return new Promise<void>((resolveInner) => { buildPageCRMTree(node, modules.crmValues.rootId, [index], modules.crmValues.contextMenuItemTree).then((result) => { if (result) { modules.crmValues.contextMenuItemTree[index] = { index, node, id: result.id, enabled: true, parentId: modules.crmValues.rootId, children: result.children, parentTree: modules.crmValues.contextMenuItemTree }; } resolveInner(null); }); }); } })).then(() => { addUserAddedContextMenuItems().then(async () => { if (modules.storages.storageLocal.showOptions) { const tree = modules.crmValues.contextMenuItemTree; const index = tree.length; tree[index] = { index, id: await browserAPI.contextMenus.create({ type: 'separator', parentId: modules.crmValues.rootId }), enabled: true, node: null, parentId: modules.crmValues.rootId, children: [], parentTree: tree }; tree[index + 1] = { index: index + 1, id: await browserAPI.contextMenus.create({ title: 'Options', onclick: createOptionsPageHandler(), parentId: modules.crmValues.rootId }), enabled: true, node: null, parentId: modules.crmValues.rootId, children: [], parentTree: tree }; } resolve(null); }); }); }); }); } export function getContexts(contexts: CRM.ContentTypes): _browser.contextMenus.ContextType[] { const newContexts: _browser.contextMenus.ContextType[] = ['browser_action']; const textContexts = modules.constants.contexts; for (let i = 0; i < 6; i++) { if (contexts[i]) { newContexts.push(textContexts[i]); } } if (contexts[0]) { newContexts.push('editable'); } return newContexts; } export function getJoinedContexts(contexts: CRM.ContentTypes[]): _browser.contextMenus.ContextType[] { const newContexts: { [key: string]: boolean; } = {}; newContexts['browser_action'] = true; const textContexts = modules.constants.contexts; for (const context of contexts) { for (let i = 0; i < 6; i++) { if (context[i]) { newContexts[textContexts[i]] = true; } } if (context[0]) { newContexts['editable'] = true; } } return Object.getOwnPropertyNames(newContexts) as _browser.contextMenus.ContextType[]; } export async function converToLegacy(): Promise<{ [key: number]: string; [key: string]: string; }> { const { arr } = walkCRM(modules.crm.crmTree, { arr: [] }); const res: { [key: number]: string; [key: string]: string; } = {}; for (let i = 0; i < arr.length; i++) { res[i] = await convertNodeToLegacy(arr[i]); } res.customcolors = '0'; res.firsttime = 'no'; res.noBeatAnnouncement = 'true'; res.numberofrows = arr.length + ''; res.optionson = modules.storages.storageLocal.showOptions.toString(); res.scriptoptions = '0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0'; res.waitforsearch = 'false'; res.whatpage = 'false'; res.indexIds = JSON.stringify(arr.map((node) => { return node.id; })); return res; } export function fixOptionsErrors(options: string): string; export function fixOptionsErrors(options: CRM.Options): CRM.Options; export function fixOptionsErrors(options: CRM.Options|string): CRM.Options|string; export function fixOptionsErrors(options: CRM.Options|string): CRM.Options|string { if (typeof options === 'string') { return options; } for (const key in options) { const value = options[key]; if (value.type === 'choice') { //If nothing is selected, select the first item const choice = value as CRM.OptionChoice; if (typeof choice.selected !== 'number' || choice.selected > choice.values.length || choice.selected < 0) { choice.selected = 0; } } options[key] = value; } return options; } async function convertNodeToLegacy(node: CRM.Node): Promise<string> { switch (node.type) { case 'divider': return [node.name, 'Divider', ''].join('%123'); case 'link': return [node.name, 'Link', node.value.map((val) => { return val.url; }).join(',')].join('%123'); case 'menu': return [node.name, 'Menu', node.children.length].join('%123'); case 'script': return [ node.name, 'Script', [ node.value.launchMode, await modules.Util.getScriptNodeScript(node) ].join('%124') ].join('%123'); case 'stylesheet': return [ node.name, 'Script', [ node.value.launchMode, node.value.stylesheet ].join('%124') ].join('%123'); } } function walkCRM(crm: CRM.Tree, state: { arr: CRM.Node[]; }) { for (let i = 0; i < crm.length; i++) { const node = crm[i]; state.arr.push(node); if (node.type === 'menu' && node.children) { walkCRM(node.children, state); } } return state; } function createCopyFunction(obj: CRM.Node, target: CRM.SafeNode): (props: string[]) => void { return (props: string[]) => { props.forEach((prop) => { if (prop in obj) { if (typeof obj[prop as keyof CRM.Node] === 'object') { (target as any)[prop as keyof CRM.SafeNode] = JSON.parse(JSON.stringify(obj[prop as keyof CRM.Node])); } else { (target as any)[prop] = obj[prop as keyof CRM.Node]; } } }); }; } export function buildNodePaths(tree: CRM.Node[], currentPath: number[] = []) { for (let i = 0; i < tree.length; i++) { const childPath = currentPath.concat([i]); const child = tree[i]; child.path = childPath; if (child.children) { buildNodePaths(child.children, childPath); } } } export function createOptionsPageHandler(): () => void { return () => { browserAPI.runtime.openOptionsPage(); }; } async function buildPageCRMTree(node: CRM.Node, parentId: string|number, path: number[], parentTree: ContextMenuItemTreeItem[]): Promise<{ id: string|number; path: number[]; enabled: boolean; children: ContextMenuItemTreeItem[]; index?: number; parentId?: string|number; node?: CRM.Node; parentTree?: ContextMenuItemTreeItem[]; }> { const id = await NodeCreation.createNode(node, parentId); modules.crmValues.contextMenuIds.set(node.id, id); if (id !== null) { const children = []; if (node.children) { let visibleIndex = 0; for (let i = 0; i < node.children.length; i++) { const newPath = JSON.parse(JSON.stringify(path)); newPath.push(visibleIndex); const result: any = await buildPageCRMTree(node.children[i], id, newPath, children); if (result) { visibleIndex++; result.index = i; result.parentId = id; result.node = node.children[i]; result.parentTree = parentTree; children.push(result); } } } modules.crmValues.contextMenuInfoById.get(id).path = path; return { id: id, path: path, enabled: true, children: children }; } return null; } function parseNode(node: CRM.Node, isSafe: boolean = false) { if (isSafe) { modules.crm.crmByIdSafe.set(node.id, makeSafe(node)); } else { modules.crm.crmById.set(node.id, node); } if (node.children && node.children.length > 0) { for (let i = 0; i < node.children.length; i++) { parseNode(node.children[i], isSafe); } } } function buildByIdObjects() { modules.crm.crmById = new window.Map(); modules.crm.crmByIdSafe = new window.Map(); for (let i = 0; i < modules.crm.crmTree.length; i++) { parseNode(modules.crm.crmTree[i]); parseNode(modules.crm.safeTree[i] as any, true); } } function safeTreeParse(node: CRM.Node): CRM.SafeNode { if (node.children) { const children = []; for (let i = 0; i < node.children.length; i++) { children.push(safeTreeParse(node.children[i])); } node.children = children as any; } return makeSafe(node); } function buildSafeTree(crm: CRM.Node[]): CRM.SafeNode[] { const treeCopy = JSON.parse(JSON.stringify(crm)); const safeBranch = []; for (let i = 0; i < treeCopy.length; i++) { safeBranch.push(safeTreeParse(treeCopy[i])); } return safeBranch; } }
the_stack
import { Vector3 } from 'three'; import { TOM_HEADER_NUM_BYTES, TOM_DIMENSIONS_START_POSITION, TOM_DIMENSIONS_NUM_BYTES, TOM_DATA_TYPE_START_POSITION, TOM_DATA_TYPE_NUM_BYTES, TOM_NUM_ELEMENTS_MARKER, TOM_NUM_ELEMENTS_START_POSITION, TOM_NUM_ELEMENTS_NUM_BYTES, TOM_USE_NULL_MARKER, TOM_USE_NULL_START_POSITION, TOM_USE_NULL_NUM_BYTES, BIN_HEADER_NUM_BYTES, BIN_DIMENSIONS_START_POSITION, BIN_DIMENSIONS_NUM_BYTES, BIN_DATA_TYPE_START_POSITION, BIN_DATA_TYPE_NUM_BYTES, BIN_NUM_ELEMENTS_START_POSITION, BIN_NUM_ELEMENTS_NUM_BYTES, BIN_USE_NULL_START_POSITION, BIN_USE_NULL_NUM_BYTES, MAX_NUM_ELEMENTS, } from './Defaults'; import { TomTypedArray, TomType, TypedArray, Type } from './types'; import { stringifyVector3, isPositiveInteger, isNonNegativeInteger, dataSizeForType, typeOfTypedArray } from './utils'; import { openSync, statSync, readSync, closeSync, writeSync, readFileSync } from 'fs'; import GPUHelper from './GPUHelper'; // Tom header // [22*2 = 44 bytes] uint16_t xsize,ysize,zsize,lmarg,rmarg,tmarg,bmarg,tzmarg,bzmarg,num_samples,num_proj,num_blocks,num_slices,bin,gain,speed,pepper,issue,num_frames,spare_int[13]__attribute__((packed)); // [13*4 = 52 bytes] float32 scale,offset,voltage,current,thickness,pixel_size,distance,exposure,mag_factor,filterb,correction_factor,spare_float[2]__attribute__((packed)); // [8*4 = 32 bytes] uint32_t z_shift,z,theta,spare_uint32[5]__attribute__((packed)); // [384*1 = 384 bytes] char time[26],duration[12],owner[21],user[5],specimen[32],scan[32],comment[64],spare_char[192]; // Init some arrays and buffers to use for moving data in and out of files. const tomHeaderBuffer = Buffer.alloc(TOM_HEADER_NUM_BYTES); const binHeaderBuffer = Buffer.alloc(BIN_HEADER_NUM_BYTES); const stringBuffer = Buffer.alloc(100); // Be careful when using this function, it inits a lot of memory, use BufferedTomR instead. export function readTom(path: string, filename: string) { const fullPath = `${path}${filename}.tom`; // Read data. const type = getTomDataType(path, filename); const typedArray = readDataAsType(fullPath, type, TOM_HEADER_NUM_BYTES); // Check that data is correct size. const numElements = getTomNumElements(path, filename); const dimensions = getTomDimensions(path, filename); if (typedArray.length !== dimensions.x * dimensions.y * dimensions.z * numElements) { throw new Error(`Error reading ${fullPath}. Expected tom dimensions ${stringifyVector3(dimensions)}, num elements ${numElements}, not compatible with data of length ${typedArray.length}.`); } return typedArray; }; export function getTomDimensions(path: string, filename: string, file?: number) { const fullPath = `${path}${filename}.tom`; // Read data. const buffer = readDataToBuffer(fullPath, tomHeaderBuffer, TOM_DIMENSIONS_START_POSITION, TOM_DIMENSIONS_NUM_BYTES, file); // Create Vector3 from dimensions. const dim = new Vector3(buffer.readUInt16LE(0), buffer.readUInt16LE(2), buffer.readUInt16LE(4)); if (!isPositiveInteger(dim.x) || !isPositiveInteger(dim.y) || !isPositiveInteger(dim.z)) { throw new Error(`Error reading ${fullPath}. Tom dimensions must be positive integers: ${stringifyVector3(dim)}`); } return dim; }; export function getTomNumElements(path: string, filename: string, file?: number) { const fullPath = `${path}${filename}.tom`; // Read marker from header, should read 'NumEl'. const marker = readString(fullPath, TOM_NUM_ELEMENTS_START_POSITION, TOM_NUM_ELEMENTS_MARKER.length, file); if (marker != TOM_NUM_ELEMENTS_MARKER) { // This is a tom file not generated by us, assume 1 element per voxel. return 1; } // Read next byte to get num elements. const buffer = readDataToBuffer(fullPath, tomHeaderBuffer, TOM_NUM_ELEMENTS_START_POSITION + TOM_NUM_ELEMENTS_MARKER.length, TOM_NUM_ELEMENTS_NUM_BYTES, file); // Parse as Uint8. const numElements = buffer[0]; if (!isPositiveInteger(numElements)) { throw new Error(`Error reading ${fullPath}. Invalid num elements: ${numElements}.`); } return numElements; }; export function getTomUseNull(path: string, filename: string, file?: number) { const fullPath = `${path}${filename}.tom`; // Read marker from header, should read 'Null'. const marker = readString(fullPath, TOM_USE_NULL_START_POSITION, TOM_USE_NULL_MARKER.length, file); if (marker != TOM_USE_NULL_MARKER) { // This is a tom file not generated by us, assume null is not encoded. return false; } // Read next byte to get use null bit. const buffer = readDataToBuffer(fullPath, tomHeaderBuffer, TOM_USE_NULL_START_POSITION + TOM_USE_NULL_MARKER.length, TOM_USE_NULL_NUM_BYTES, file); // Parse as bool. const useNull = buffer[0]; if (!isNonNegativeInteger(useNull) || useNull > 1) { throw new Error(`Error reading ${fullPath}. Invalid use null flag: ${useNull}.`); } return useNull > 0; }; export function getTomDataType(path: string, filename: string, file?: number): TomType { // Read string from file. const type = readString(`${path}${filename}.tom`, TOM_DATA_TYPE_START_POSITION, TOM_DATA_TYPE_NUM_BYTES, file).replace(/\0/g, ''); // Parse data type. switch(type) { case 'float32': return 'float32'; case 'uint32': return 'uint32'; case 'int32': return 'int32'; case 'uint8': default: // Orig tom data from ct scans do not have datatype info in them. // We assume these are uint8. return 'uint8'; } } export function readBin(path: string, filename: string, file?: number) { const fullPath = `${path}${filename}.bin`; let _file = file; // Open file if needed. if (_file === undefined) { _file = openSync(fullPath, 'r'); } // Read data. const type = getBinDataType(path, filename, file); const length = getBinLength(path, filename,file); const numElements = getBinNumElements(path, filename, file); const typedArray = readDataAsType(fullPath, type, BIN_HEADER_NUM_BYTES, length*numElements*dataSizeForType(type), file); // Close file if needed. if (file === undefined) { closeSync(_file); } return typedArray; }; export function getBinLength(path: string, filename: string, file?: number) { const fullPath = `${path}${filename}.bin`; // Read data. const buffer = readDataToBuffer(fullPath, binHeaderBuffer, BIN_DIMENSIONS_START_POSITION, BIN_DIMENSIONS_NUM_BYTES, file); // Create uint32 from dimensions. const length = buffer.readUInt32LE(0); if (!isPositiveInteger(length)) { throw new Error(`Error reading ${fullPath}. Invalid .bin length: ${length}.`); } return length; }; export function getBinNumElements(path: string, filename: string, file?: number) { const fullPath = `${path}${filename}.bin`; // Get data. const buffer = readDataToBuffer(fullPath, binHeaderBuffer, BIN_NUM_ELEMENTS_START_POSITION, BIN_NUM_ELEMENTS_NUM_BYTES, file); // Parse as Uint8. const numElements = buffer[0] if (!isPositiveInteger(numElements)) { throw new Error(`Error reading ${fullPath}. Invalid num elements: ${numElements}.`); } return numElements; }; export function getBinUseNull(path: string, filename: string, file?: number) { const fullPath = `${path}${filename}.bin`; // Get data. const buffer = readDataToBuffer(fullPath, binHeaderBuffer, BIN_USE_NULL_START_POSITION, BIN_USE_NULL_NUM_BYTES, file); // Parse as bool. const useNull = buffer[0]; if (!isNonNegativeInteger(useNull) || useNull > 1) { throw new Error(`Error reading ${fullPath}. Invalid use null flag: ${useNull}.`); } return useNull > 0; }; export function getBinDataType(path: string, filename: string, file?: number) { const fullPath = `${path}${filename}.bin`; // Read string from file. const type = readString(fullPath, BIN_DATA_TYPE_START_POSITION, BIN_DATA_TYPE_NUM_BYTES, file).replace(/\0/g, ''); // Parse data type. switch(type) { case 'float32': return 'float32'; case 'uint8': return 'uint8'; case 'uint32': return 'uint32'; case 'int32': return 'int32'; default: throw new Error(`Error reading ${fullPath}. Unknown data type: ${type}`); } } export function readDataAsType(fullPath: string, type: TomType, start: number, length?: number, file?: number): TomTypedArray; export function readDataAsType(fullPath: string, type: Type, start: number, length?: number, file?: number): TypedArray; export function readDataAsType(fullPath: string, type: TomType | Type, start: number, length?: number, file?: number) { // If no length passed, assume read to end of file. if (length === undefined) length = statSync(fullPath).size - start; // Allocate buffer. const buffer = Buffer.alloc(length); // Allocate TypedArray. const dataSize = dataSizeForType(type); const typedArrayLength = buffer.length / dataSize; let typedArray; switch (type) { case 'uint8': typedArray = new Uint8Array(typedArrayLength); break; case 'uint16': typedArray = new Uint16Array(typedArrayLength); break; case 'int16': typedArray = new Int16Array(typedArrayLength); break; case 'uint32': typedArray = new Uint32Array(typedArrayLength); break; case 'int32': typedArray = new Int32Array(typedArrayLength); break; case 'float32': typedArray = new Float32Array(typedArrayLength); break; default: throw new Error(`Error reading ${fullPath}. Unsupported type: ${type}.`); } return readDataToArray(fullPath, start, typedArray, buffer, file); } function parseBufferToTypedArray(buffer: Buffer, typedArray: TypedArray): TypedArray; function parseBufferToTypedArray(buffer: Buffer, typedArray: TomTypedArray): TomTypedArray; function parseBufferToTypedArray(buffer: Buffer, typedArray: TypedArray | TomTypedArray) { const type = typeOfTypedArray(typedArray); const dataSize = dataSizeForType(type); if (buffer.length !== typedArray.length * dataSize) { throw new Error(`Incompatible buffer lengths for reading tom: ${buffer.length}, ${typedArray.length * dataSize}`) } const length = typedArray.length; switch (type) { case 'uint8': // Buffer is same as Uint8Array, but we must explicitly cast it as a UInt8Array // so that the constructor checks work. for (let i = 0; i < length; i++) { typedArray[i] = buffer[i]; } break; case 'uint16': for (let i = 0; i < length; i++) { typedArray[i] = buffer.readUInt16LE(dataSize * i); } break; case 'int16': for (let i = 0; i < length; i++) { typedArray[i] = buffer.readInt16LE(dataSize * i); } break; case 'uint32': for (let i = 0; i < length; i++) { typedArray[i] = buffer.readUInt32LE(dataSize * i); } break; case 'int32': for (let i = 0; i < length; i++) { typedArray[i] = buffer.readInt32LE(dataSize * i); } break; case 'float32': for (let i = 0; i < length; i++) { typedArray[i] = buffer.readFloatLE(dataSize * i); } break; default: throw new Error(`Unsupported type: ${type}.`); } return typedArray; } export function readDataToArray(fullPath: string, start: number, typedArray: TomTypedArray, buffer: Buffer, file?: number): TomTypedArray; export function readDataToArray(fullPath: string, start: number, typedArray: TypedArray, buffer: Buffer, file?: number): TypedArray export function readDataToArray(fullPath: string, start: number, typedArray: TomTypedArray | TypedArray, buffer: Buffer, file?: number) { return parseBufferToTypedArray(readDataToBuffer(fullPath, buffer, start, buffer.length, file), typedArray); } function readDataToBuffer(fullPath: string, buffer: Buffer, start: number, length = buffer.length, file?: number) { let _file = file; // Optionally open file. if (_file === undefined) { _file = openSync(fullPath, 'r') } // Load up buffer. readSync(_file, buffer, 0, length, start); // Optionally close file. if (file === undefined) { closeSync(_file); } return buffer; } function readString(fullPath: string, startPosition: number, length: number, file?: number) { let _file = file; // Optionally open file. if (_file === undefined) { _file = openSync(fullPath, 'r') } // Load up buffer with full size of file (minus header). readSync(_file, stringBuffer, 0, length, startPosition); // Optionally close file. if (file === undefined) { closeSync(_file); } // Parse as utf-8. return stringBuffer.toString('utf-8', 0, length); } // Be careful when using this function, it inits a lot of memory, use BufferedTomW instead. export function writeTom(path: string, filename: string, typedArray: TomTypedArray, dimensions: Vector3, numElements = 1, useNull = false) { const fullPath = `${path}${filename}.tom`; // Check typedArray. const { length } = typedArray; if (length === 0) { throw new Error(`Error saving ${fullPath}. Attempting to save array of length 0.`); } if (length !== dimensions.x * dimensions.y * dimensions.z * numElements) { throw new Error(`Error saving ${fullPath}. Dimensions ${stringifyVector3(dimensions)}, num elements per voxel: ${numElements} not compatible with data of length ${length}.`); } // Get data type from TypedArray. const type = typeOfTypedArray(typedArray); // Get data type length. const dataLength = dataSizeForType(type); // Open file. let fd = openSync(fullPath, 'w'); // Write header. writeTomHeaderToBuffer(fullPath, tomHeaderBuffer, type, dimensions, numElements, useNull); writeSync(fd, tomHeaderBuffer); // Fill buffer with data. const buffer = Buffer.alloc(typedArray.length * dataLength); writeDataToBuffer(typedArray, buffer, fullPath); writeSync(fd, buffer); // Close file. closeSync(fd); } export function copyTom(inputPath: string, inputFilename: string, outputPath: string, outputFilename: string) { // Get metadata. const type = getTomDataType(inputPath, inputFilename); const numElements = getTomNumElements(inputPath, inputFilename); const useNull = getTomUseNull(inputPath, inputFilename); const dimensions = getTomDimensions(inputPath, inputFilename); const fullPath = `${outputPath}${outputFilename}.tom`; // Open files. let inputFile = openSync(`${inputPath}${inputFilename}.tom`, 'r'); let outputFile = openSync(fullPath, 'w'); // Write header. writeTomHeaderToBuffer(fullPath, tomHeaderBuffer, type, dimensions, numElements, useNull); writeSync(outputFile, tomHeaderBuffer); // Init a buffer to hold a single layer of data. const layerBuffer = Buffer.alloc(dataSizeForType(type) * numElements * dimensions.x * dimensions.y); // Loop through z layers and write each layer. for (let z = 0; z < dimensions.z; z++) { readSync(inputFile, layerBuffer, 0, layerBuffer.length, TOM_HEADER_NUM_BYTES + z * layerBuffer.length); writeSync(outputFile, layerBuffer, 0, layerBuffer.length, TOM_HEADER_NUM_BYTES + z * layerBuffer.length); } // Close file. closeSync(inputFile); closeSync(outputFile); } export function writeTomHeaderToBuffer(fullPath: string, buffer: Buffer, type: TomType, dimensions: Vector3, numElements = 1, useNull = false) { // Check that numElements is a valid number. if (numElements > MAX_NUM_ELEMENTS) { throw new Error(`Error saving ${fullPath}. Invalid num elements: ${numElements}.`); } // Clear buffer. buffer.fill(0); // Write dimensions of tom data to header. writeNumberToBuffer(fullPath, dimensions.x, 'uint16', buffer, TOM_DIMENSIONS_START_POSITION); writeNumberToBuffer(fullPath, dimensions.y, 'uint16', buffer, TOM_DIMENSIONS_START_POSITION + 2); writeNumberToBuffer(fullPath, dimensions.z, 'uint16', buffer, TOM_DIMENSIONS_START_POSITION + 4); // Write data type to header. writeStringToBuffer(fullPath, type, buffer, TOM_DATA_TYPE_START_POSITION, TOM_DATA_TYPE_NUM_BYTES); // Write num elements to header. writeStringToBuffer(fullPath, TOM_NUM_ELEMENTS_MARKER, buffer, TOM_NUM_ELEMENTS_START_POSITION, TOM_NUM_ELEMENTS_MARKER.length); writeNumberToBuffer(fullPath, numElements, 'uint8', buffer, TOM_NUM_ELEMENTS_START_POSITION + TOM_NUM_ELEMENTS_MARKER.length); // Write useNull to header. writeStringToBuffer(fullPath, TOM_USE_NULL_MARKER, buffer, TOM_USE_NULL_START_POSITION, TOM_USE_NULL_MARKER.length); writeNumberToBuffer(fullPath, useNull ? 1 : 0, 'uint8', buffer, TOM_USE_NULL_START_POSITION + TOM_USE_NULL_MARKER.length); } export function writeBin(path: string, filename: string, typedArray: TypedArray, numElements = 1, useNull = false, length = typedArray.length) { const fullPath = `${path}${filename}.bin`; // Open file and write header. let fd = writeBinHeader(path, filename, typedArray, numElements, useNull, length); // Get data type from TypedArray. const type = typeOfTypedArray(typedArray); const dataLength = dataSizeForType(type); // Fill remainder of buffer with data. const buffer = Buffer.alloc(length * dataLength); writeDataToBuffer(typedArray, buffer, fullPath, 0, length); writeSync(fd, buffer); // Close file. closeSync(fd); } export function writeBinHeader(path: string, filename: string, typedArray: TypedArray, numElements = 1, useNull = false, length = typedArray.length) { const fullPath = `${path}${filename}.bin`; // Check typedArray. if (length === 0) { throw new Error(`Error saving ${fullPath}. Attempting to save array of length 0.`); } if (length % numElements !== 0) { throw new Error(`Error saving ${fullPath}. Num elements per entry: ${numElements} not compatible with data of length ${length}.`); } if (numElements > MAX_NUM_ELEMENTS) { throw new Error(`Error saving ${fullPath}. Invalid num elements: ${numElements}.`); } // Get data type from TypedArray. const type = typeOfTypedArray(typedArray); // Open file. let fd = openSync(fullPath, 'w'); // Write header. writeBinHeaderToBuffer(fullPath, binHeaderBuffer, type, length, numElements, useNull); writeSync(fd, binHeaderBuffer); return fd; } export function writeBinHeaderToBuffer(fullPath: string, buffer: Buffer, type: Type, length: number, numElements = 1, useNull = false) { // Check that numElements is a valid number. if (numElements > MAX_NUM_ELEMENTS) { throw new Error(`Error saving ${fullPath}. Invalid num elements: ${numElements}.`); } // Clear buffer. buffer.fill(0); // Write length to header. writeNumberToBuffer(fullPath, length / numElements, 'uint32', buffer, BIN_DIMENSIONS_START_POSITION); // Write data type to header. writeStringToBuffer(fullPath, type, buffer, BIN_DATA_TYPE_START_POSITION, BIN_DATA_TYPE_NUM_BYTES); // Write num elements to header. writeNumberToBuffer(fullPath, numElements, 'uint8', buffer, BIN_NUM_ELEMENTS_START_POSITION); // Write useNull to header. writeNumberToBuffer(fullPath, useNull ? 1 : 0, 'uint8', buffer, BIN_USE_NULL_START_POSITION); } function writeStringToBuffer(fullPath: string, type: Type | typeof TOM_NUM_ELEMENTS_MARKER | typeof TOM_USE_NULL_MARKER, buffer: Buffer, startPosition: number, numBytes: number) { const _buffer = Buffer.from(type, 'utf-8'); if (_buffer.length > numBytes) { throw new Error(`Error saving ${fullPath}. Not enough bytes (${numBytes}) to store string ${type}`); } for (let i = 0; i < _buffer.length; i++) { buffer[startPosition + i] = _buffer[i]; } } function writeNumberToBuffer(fullPath: string, number: number, type: Type, buffer: Buffer, position = 0) { // Write data to buffer. switch (type) { case 'uint8': buffer[position] = number; break; case 'uint32': buffer.writeUInt32LE(number, position); break; case 'int32': buffer.writeInt32LE(number, position); break; case 'float32': buffer.writeFloatLE(number, position); break; case 'uint16': buffer.writeUInt16LE(number, position); break; case 'int16': buffer.writeInt16LE(number, position); break; default: throw new Error(`Error saving ${fullPath}. Unknown type ${type}.`); } } export function writeDataToBuffer(typedArray: TypedArray, buffer: Buffer, fullPath?: string, startPosition = 0, length = typedArray.length) { // Write data to buffer. const type = typeOfTypedArray(typedArray); switch (type) { case 'uint8': for (let i = 0; i < length; i++) { buffer[i + startPosition] = typedArray[i]; } break; case 'uint32': for (let i = 0; i < length; i++) { buffer.writeUInt32LE(typedArray[i], 4 * i + startPosition); } break; case 'int32': for (let i = 0; i < length; i++) { buffer.writeInt32LE(typedArray[i], 4 * i + startPosition); } break; case 'float32': for (let i = 0; i < length; i++) { buffer.writeFloatLE(typedArray[i], 4 * i + startPosition); } break; case 'uint16': for (let i = 0; i < length; i++) { buffer.writeUInt16LE(typedArray[i], 2 * i + startPosition); } break; case 'int16': for (let i = 0; i < length; i++) { buffer.writeInt16LE(typedArray[i], 2 * i + startPosition); } break; default: throw new Error(`Error saving ${fullPath}. Unknown typed array constructor ${typedArray.constructor}.`); } } // // TODO: delete these eventually. // export function convertVolToBin(path: string, filename: string, numElements: number, useNull: boolean, type: Type) { // const fullPath = `${path}${filename}.vol`; // const data = readDataAsType(fullPath, type, 0); // writeBin(path, filename, data, numElements, useNull); // } // export function readVol(path: string, filename: string, type: Type) { // const fullPath = `${path}${filename}.vol`; // return readDataAsType(fullPath, type, 0); // }
the_stack
import { Resolvers, VoteResults } from './types'; import { FilterQuery } from 'mongoose'; import diffHistory from 'mongoose-diff-history/diffHistory'; import { PROCEDURE as PROCEDURE_DEFINITIONS } from '@democracy-deutschland/bundestag.io-definitions'; import { xml2js } from 'xml-js'; import axios from 'axios'; import PROCEDURE_STATES from '../../config/procedureStates'; import { IProcedure } from '@democracy-deutschland/bundestagio-common/dist/models/Procedure/schema'; import { ConferenceWeekDetailModel } from '@democracy-deutschland/bundestagio-common'; const deputiesNumber = { 19: { Linke: 69, SPD: 153, Grüne: 67, 'B90/Grüne': 67, CDU: 246, Union: 246, 'CDU/CSU': 246, FDP: 80, AFD: 92, AfD: 92, Andere: 2, Fraktionslos: 2, }, 20: { Linke: 39, SPD: 206, Grüne: 118, 'B90/Grüne': 118, CDU: 197, Union: 197, 'CDU/CSU': 197, FDP: 92, AFD: 82, AfD: 82, Andere: 2, Fraktionslos: 2, }, }; const ProcedureResolvers: Resolvers = { Query: { procedures: async ( parent, { IDs, period = [19], type = [PROCEDURE_DEFINITIONS.TYPE.GESETZGEBUNG, PROCEDURE_DEFINITIONS.TYPE.ANTRAG], status, voteDate, manageVoteDate = false, limit = 99999, offset = 0, }, { ProcedureModel }, ) => { let match: FilterQuery<IProcedure> = { period: { $in: period }, type: { $in: type } }; if (voteDate) { match = { ...match, history: { $elemMatch: { decision: { $elemMatch: { tenor: { $in: [ PROCEDURE_DEFINITIONS.HISTORY.DECISION.TENOR.VORLAGE_ABLEHNUNG, PROCEDURE_DEFINITIONS.HISTORY.DECISION.TENOR.VORLAGE_ANNAHME, ], }, }, }, }, }, }; return ProcedureModel.find({ ...match }) .sort({ createdAt: 1 }) .skip(offset) .limit(limit); } if (manageVoteDate) { match = { ...match, 'customData.voteResults.yes': { $not: { $gte: 1 } }, $or: [ { history: { $elemMatch: { decision: { $elemMatch: { tenor: { $in: [ PROCEDURE_DEFINITIONS.HISTORY.DECISION.TENOR.VORLAGE_ABLEHNUNG, PROCEDURE_DEFINITIONS.HISTORY.DECISION.TENOR.VORLAGE_ANNAHME, PROCEDURE_DEFINITIONS.HISTORY.DECISION.TENOR.VORLAGE_ERLEDIGT, ], }, }, }, }, }, }, { currentStatus: { $in: PROCEDURE_STATES.COMPLETED }, }, { voteDate: { $lte: new Date() }, }, ], currentStatus: { $nin: [ PROCEDURE_DEFINITIONS.STATUS.ZURUECKGEZOGEN, PROCEDURE_DEFINITIONS.STATUS.ERLEDIGT, ], }, }; return ProcedureModel.find({ ...match }).sort({ updatedAt: 1 }); } if (status) { match = { ...match, currentStatus: { $in: status } }; } if (IDs) { match = { ...match, procedureId: { $in: IDs } }; } return ProcedureModel.find(match).skip(offset).limit(limit); }, proceduresData: async ( parent, { IDs, period, type = [PROCEDURE_DEFINITIONS.TYPE.GESETZGEBUNG, PROCEDURE_DEFINITIONS.TYPE.ANTRAG], status, voteDate, manageVoteDate = false, limit = 99999, offset = 0, }, { ProcedureModel }, ) => { let match: FilterQuery<IProcedure> = { period: { $in: period }, type: { $in: type } }; if (voteDate) { match = { ...match, history: { $elemMatch: { decision: { $elemMatch: { tenor: { $in: [ PROCEDURE_DEFINITIONS.HISTORY.DECISION.TENOR.VORLAGE_ABLEHNUNG, PROCEDURE_DEFINITIONS.HISTORY.DECISION.TENOR.VORLAGE_ANNAHME, ], }, }, }, }, }, }; return { nodes: await ProcedureModel.find({ ...match }) .sort({ createdAt: 1 }) .skip(offset) .limit(limit), totalCount: await ProcedureModel.count({ ...match }), }; } if (manageVoteDate) { match = { ...match, 'customData.voteResults.yes': { $not: { $gte: 1 } }, $or: [ { history: { $elemMatch: { decision: { $elemMatch: { tenor: { $in: [ PROCEDURE_DEFINITIONS.HISTORY.DECISION.TENOR.VORLAGE_ABLEHNUNG, PROCEDURE_DEFINITIONS.HISTORY.DECISION.TENOR.VORLAGE_ANNAHME, PROCEDURE_DEFINITIONS.HISTORY.DECISION.TENOR.VORLAGE_ERLEDIGT, ], }, }, }, }, }, }, { currentStatus: { $in: PROCEDURE_STATES.COMPLETED }, }, { voteDate: { $lte: new Date() }, }, ], currentStatus: { $nin: [ PROCEDURE_DEFINITIONS.STATUS.ZURUECKGEZOGEN, PROCEDURE_DEFINITIONS.STATUS.ERLEDIGT, ], }, }; return { nodes: await ProcedureModel.find({ ...match }) .sort({ updatedAt: 1 }) .skip(offset) .limit(limit), totalCount: await ProcedureModel.count({ ...match }), }; } if (status) { match = { ...match, currentStatus: { $in: status } }; } if (IDs) { match = { ...match, procedureId: { $in: IDs } }; } return { nodes: await ProcedureModel.find(match).skip(offset).limit(limit), totalCount: await ProcedureModel.count(match), }; }, allProcedures: async ( parent, { period = [19], type = [PROCEDURE_DEFINITIONS.TYPE.GESETZGEBUNG, PROCEDURE_DEFINITIONS.TYPE.ANTRAG], }, { ProcedureModel }, ) => ProcedureModel.find({ period: { $in: period }, type: { $in: type }, }), procedureUpdates: async ( parent, { since, limit = 99, offset = 0, periods, types }, { ProcedureModel }, ) => { const periodMatch = periods ? { period: { $in: periods } } : {}; const typesMatch = types ? { type: { $in: types } } : {}; const beforeCount = await ProcedureModel.count({ // createdAt: { $lte: since }, ...periodMatch, ...typesMatch, }); const afterCount = await ProcedureModel.count({ ...periodMatch, ...typesMatch, }); const proceduresFindQuery = { // updatedAt: { $gt: since }, ...periodMatch, ...typesMatch, }; const changed = await ProcedureModel.count(proceduresFindQuery); const procedures = await ProcedureModel.find( proceduresFindQuery, {}, // Even tho the index for createdAt is set - the memory limit is reached - therefore no sort { /* sort: { createdAt: 1 }, */ skip: offset, limit }, ); return { beforeCount, afterCount, newCount: afterCount - beforeCount, changedCount: changed, procedures, }; }, procedure: async (parent, { procedureId }, { ProcedureModel }) => ProcedureModel.findOne({ procedureId }), voteResultTextHelper: async ( parent, { procedureId }, { PlenaryMinuteModel, ProcedureModel }, ) => { const procedure = await ProcedureModel.findOne({ procedureId }); const docNumbers = procedure.importantDocuments.map(({ number }) => number); const flattenElements = (elements) => { return elements.reduce((prev, el) => { if (Array.isArray(el.elements)) { return [...prev, ...flattenElements(el.elements)]; } else if (el.type === 'text') { return [...prev, el.text]; } return prev; }, []); }; console.log('procedure', procedure); if (procedure) { const axiosInstance = axios.create(); const date = procedure.voteDate; const conferenceWeekDetail = await ConferenceWeekDetailModel.findOne({ 'sessions.date': { $gte: new Date(date.getFullYear(), date.getMonth(), date.getDate()), $lte: new Date(date.getFullYear(), date.getMonth(), date.getDate() + 1), }, }); const session = conferenceWeekDetail.sessions.find((s) => { if (s.date.getDate() === date.getDate()) { return true; } return false; }); if (!session) { return null; } const plenaryMinute = await PlenaryMinuteModel.findOne({ meeting: parseInt(session.session), }); console.log('plenaryMinute', plenaryMinute); if (plenaryMinute) { const { data } = await axiosInstance.get(plenaryMinute.xml); const json = await xml2js(data, { compact: false, }); const protocol = json.elements.find(({ name }) => name === 'dbtplenarprotokoll'); const sessionHistory = protocol.elements.find(({ name }) => name === 'sitzungsverlauf'); const output = flattenElements(sessionHistory.elements); const resultIndexes = output.reduce((prev, text, index) => { const matches = docNumbers.filter((number) => text.indexOf(number) !== -1); if (matches.length > 0) { return [...prev, index]; } return prev; }, []); const outputLines = resultIndexes.reduce((prev, line) => { return [ ...prev, { results: [ output[line - 1], output[line], output[line + 1] || '', output[line + 2] || '', output[line + 3] || '', output[line + 4] || '', output[line + 5] || '', ], }, ]; }, []); return outputLines; } return null; } }, }, Mutation: { saveProcedureCustomData: async ( parent, { procedureId, partyVotes, decisionText, votingDocument, toggleDecision }, { ProcedureModel }, ) => { const procedure = await ProcedureModel.findOne({ procedureId }); let voteResults: VoteResults = { partyVotes, decisionText: decisionText.trim(), votingDocument, }; if (deputiesNumber[procedure.period]) { const sumResults = { yes: 0, abstination: 0, no: 0, }; const partyResults = partyVotes.map(({ party, main, deviants: partyDeviants }) => { const deviants = { ...partyDeviants }; switch (main) { case 'YES': deviants.yes = deputiesNumber[procedure.period][party] - deviants.abstination - deviants.no; break; case 'ABSTINATION': deviants.abstination = deputiesNumber[procedure.period][party] - deviants.yes - deviants.no; break; case 'NO': deviants.no = deputiesNumber[procedure.period][party] - deviants.yes - deviants.abstination; break; default: break; } sumResults.yes += deviants.yes; sumResults.abstination += deviants.abstination; sumResults.no += deviants.no; return { party, main, deviants }; }); voteResults = { ...voteResults, partyVotes: partyResults, ...sumResults, }; voteResults.votingRecommendation = toggleDecision; } await ProcedureModel.update( { procedureId }, { $set: { 'customData.voteResults': { ...voteResults }, }, }, ); return ProcedureModel.findOne({ procedureId }); }, saveProcedurenamedPollCustomData: async ( parent, { procedureId, toggleDecision }, { ProcedureModel }, ) => { const procedure = await ProcedureModel.findOne({ procedureId }); const { voteResults } = procedure.customData; voteResults.votingRecommendation = toggleDecision; await ProcedureModel.update( { procedureId }, { $set: { 'customData.voteResults': { ...voteResults }, }, }, ); return ProcedureModel.findOne({ procedureId }); }, }, Procedure: { currentStatusHistory: async (procedure) => { const { _id } = procedure; const history = await diffHistory.getDiffs('Procedure', _id).then((histories) => histories.reduce((prev, version) => { const cur = prev; if (version.diff.currentStatus) { if (cur.length === 0) { cur.push(version.diff.currentStatus[0]); } cur.push(version.diff.currentStatus[1]); } return cur; }, []), ); return history; }, namedVote: (procedure) => { const namedVote = procedure.history.some((h) => { if (h.decision) { return h.decision.some((decision) => { if ( decision.type === PROCEDURE_DEFINITIONS.HISTORY.DECISION.TYPE.NAMENTLICHE_ABSTIMMUNG && decision.tenor.search( PROCEDURE_DEFINITIONS.HISTORY.DECISION.TENOR.FIND_AENDERUNGSANTRAG, ) === -1 ) { return true; } return false; }); } return false; }); return namedVote; }, sessions: async (procedure, _, { ConferenceWeekDetailModel }) => ConferenceWeekDetailModel.aggregate([ { $match: { 'sessions.tops.topic.procedureIds': procedure.procedureId, }, }, { $unwind: '$sessions' }, { $addFields: { session: '$sessions' } }, { $project: { sessions: 0 } }, { $unwind: '$session.tops' }, { $addFields: { 'session.top': '$session.tops' } }, { $project: { 'session.tops': 0 } }, { $unwind: '$session.top.topic' }, { $unwind: '$session.top.topic.procedureIds' }, { $addFields: { 'session.top.topic.procedureId': '$session.top.topic.procedureIds' } }, { $project: { 'session.top.topic.procedureIds': 0 } }, { $match: { 'session.top.topic.procedureId': procedure.procedureId } }, ]), }, }; export default ProcedureResolvers;
the_stack
import { ServiceClientOptions, RequestOptions, ServiceCallback, HttpOperationResponse } from 'ms-rest'; import * as models from '../models'; /** * @class * Operations * __NOTE__: An instance of this class is automatically created for an * instance of the AzureStackManagementClient. */ export interface Operations { /** * Returns the list of supported REST operations. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<OperationList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationList>>; /** * Returns the list of supported REST operations. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {OperationList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {OperationList} [result] - The deserialized result object if an error did not occur. * See {@link OperationList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationList>; list(callback: ServiceCallback<models.OperationList>): void; list(options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationList>): void; /** * Returns the list of supported REST operations. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<OperationList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.OperationList>>; /** * Returns the list of supported REST operations. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {OperationList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {OperationList} [result] - The deserialized result object if an error did not occur. * See {@link OperationList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.OperationList>; listNext(nextPageLink: string, callback: ServiceCallback<models.OperationList>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.OperationList>): void; } /** * @class * Products * __NOTE__: An instance of this class is automatically created for an * instance of the AzureStackManagementClient. */ export interface Products { /** * Returns a list of products. * * @param {string} resourceGroup Name of the resource group. * * @param {string} registrationName Name of the Azure Stack registration. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ProductList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(resourceGroup: string, registrationName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProductList>>; /** * Returns a list of products. * * @param {string} resourceGroup Name of the resource group. * * @param {string} registrationName Name of the Azure Stack registration. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ProductList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ProductList} [result] - The deserialized result object if an error did not occur. * See {@link ProductList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(resourceGroup: string, registrationName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProductList>; list(resourceGroup: string, registrationName: string, callback: ServiceCallback<models.ProductList>): void; list(resourceGroup: string, registrationName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProductList>): void; /** * Returns the specified product. * * @param {string} resourceGroup Name of the resource group. * * @param {string} registrationName Name of the Azure Stack registration. * * @param {string} productName Name of the product. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Product>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroup: string, registrationName: string, productName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Product>>; /** * Returns the specified product. * * @param {string} resourceGroup Name of the resource group. * * @param {string} registrationName Name of the Azure Stack registration. * * @param {string} productName Name of the product. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Product} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Product} [result] - The deserialized result object if an error did not occur. * See {@link Product} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroup: string, registrationName: string, productName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Product>; get(resourceGroup: string, registrationName: string, productName: string, callback: ServiceCallback<models.Product>): void; get(resourceGroup: string, registrationName: string, productName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Product>): void; /** * Returns the extended properties of a product. * * @param {string} resourceGroup Name of the resource group. * * @param {string} registrationName Name of the Azure Stack registration. * * @param {string} productName Name of the product. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ExtendedProduct>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listDetailsWithHttpOperationResponse(resourceGroup: string, registrationName: string, productName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ExtendedProduct>>; /** * Returns the extended properties of a product. * * @param {string} resourceGroup Name of the resource group. * * @param {string} registrationName Name of the Azure Stack registration. * * @param {string} productName Name of the product. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ExtendedProduct} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ExtendedProduct} [result] - The deserialized result object if an error did not occur. * See {@link ExtendedProduct} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listDetails(resourceGroup: string, registrationName: string, productName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ExtendedProduct>; listDetails(resourceGroup: string, registrationName: string, productName: string, callback: ServiceCallback<models.ExtendedProduct>): void; listDetails(resourceGroup: string, registrationName: string, productName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ExtendedProduct>): void; /** * Returns a list of products. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ProductList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ProductList>>; /** * Returns a list of products. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ProductList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ProductList} [result] - The deserialized result object if an error did not occur. * See {@link ProductList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ProductList>; listNext(nextPageLink: string, callback: ServiceCallback<models.ProductList>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ProductList>): void; } /** * @class * Registrations * __NOTE__: An instance of this class is automatically created for an * instance of the AzureStackManagementClient. */ export interface Registrations { /** * Returns a list of all registrations. * * @param {string} resourceGroup Name of the resource group. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RegistrationList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(resourceGroup: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RegistrationList>>; /** * Returns a list of all registrations. * * @param {string} resourceGroup Name of the resource group. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RegistrationList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RegistrationList} [result] - The deserialized result object if an error did not occur. * See {@link RegistrationList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(resourceGroup: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RegistrationList>; list(resourceGroup: string, callback: ServiceCallback<models.RegistrationList>): void; list(resourceGroup: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RegistrationList>): void; /** * Returns the properties of an Azure Stack registration. * * @param {string} resourceGroup Name of the resource group. * * @param {string} registrationName Name of the Azure Stack registration. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Registration>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroup: string, registrationName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Registration>>; /** * Returns the properties of an Azure Stack registration. * * @param {string} resourceGroup Name of the resource group. * * @param {string} registrationName Name of the Azure Stack registration. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Registration} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Registration} [result] - The deserialized result object if an error did not occur. * See {@link Registration} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroup: string, registrationName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Registration>; get(resourceGroup: string, registrationName: string, callback: ServiceCallback<models.Registration>): void; get(resourceGroup: string, registrationName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Registration>): void; /** * Delete the requested Azure Stack registration. * * @param {string} resourceGroup Name of the resource group. * * @param {string} registrationName Name of the Azure Stack registration. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroup: string, registrationName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Delete the requested Azure Stack registration. * * @param {string} resourceGroup Name of the resource group. * * @param {string} registrationName Name of the Azure Stack registration. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroup: string, registrationName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroup: string, registrationName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroup: string, registrationName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Create or update an Azure Stack registration. * * @param {string} resourceGroup Name of the resource group. * * @param {string} registrationName Name of the Azure Stack registration. * * @param {object} token Registration token * * @param {string} token.registrationToken The token identifying registered * Azure Stack * * @param {object} [token.tags] Custom tags for the resource. * * @param {string} [token.etag] The entity tag used for optimistic concurency * when modifying the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<Registration>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createOrUpdateWithHttpOperationResponse(resourceGroup: string, registrationName: string, token: models.RegistrationParameter, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.Registration>>; /** * Create or update an Azure Stack registration. * * @param {string} resourceGroup Name of the resource group. * * @param {string} registrationName Name of the Azure Stack registration. * * @param {object} token Registration token * * @param {string} token.registrationToken The token identifying registered * Azure Stack * * @param {object} [token.tags] Custom tags for the resource. * * @param {string} [token.etag] The entity tag used for optimistic concurency * when modifying the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {Registration} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {Registration} [result] - The deserialized result object if an error did not occur. * See {@link Registration} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ createOrUpdate(resourceGroup: string, registrationName: string, token: models.RegistrationParameter, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.Registration>; createOrUpdate(resourceGroup: string, registrationName: string, token: models.RegistrationParameter, callback: ServiceCallback<models.Registration>): void; createOrUpdate(resourceGroup: string, registrationName: string, token: models.RegistrationParameter, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.Registration>): void; /** * Returns Azure Stack Activation Key. * * @param {string} resourceGroup Name of the resource group. * * @param {string} registrationName Name of the Azure Stack registration. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<ActivationKeyResult>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getActivationKeyWithHttpOperationResponse(resourceGroup: string, registrationName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.ActivationKeyResult>>; /** * Returns Azure Stack Activation Key. * * @param {string} resourceGroup Name of the resource group. * * @param {string} registrationName Name of the Azure Stack registration. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {ActivationKeyResult} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {ActivationKeyResult} [result] - The deserialized result object if an error did not occur. * See {@link ActivationKeyResult} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ getActivationKey(resourceGroup: string, registrationName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.ActivationKeyResult>; getActivationKey(resourceGroup: string, registrationName: string, callback: ServiceCallback<models.ActivationKeyResult>): void; getActivationKey(resourceGroup: string, registrationName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.ActivationKeyResult>): void; /** * Returns a list of all registrations. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<RegistrationList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.RegistrationList>>; /** * Returns a list of all registrations. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {RegistrationList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {RegistrationList} [result] - The deserialized result object if an error did not occur. * See {@link RegistrationList} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.RegistrationList>; listNext(nextPageLink: string, callback: ServiceCallback<models.RegistrationList>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.RegistrationList>): void; } /** * @class * CustomerSubscriptions * __NOTE__: An instance of this class is automatically created for an * instance of the AzureStackManagementClient. */ export interface CustomerSubscriptions { /** * Returns a list of products. * * @param {string} resourceGroup Name of the resource group. * * @param {string} registrationName Name of the Azure Stack registration. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<CustomerSubscriptionList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listWithHttpOperationResponse(resourceGroup: string, registrationName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.CustomerSubscriptionList>>; /** * Returns a list of products. * * @param {string} resourceGroup Name of the resource group. * * @param {string} registrationName Name of the Azure Stack registration. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {CustomerSubscriptionList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {CustomerSubscriptionList} [result] - The deserialized result object if an error did not occur. * See {@link CustomerSubscriptionList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ list(resourceGroup: string, registrationName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.CustomerSubscriptionList>; list(resourceGroup: string, registrationName: string, callback: ServiceCallback<models.CustomerSubscriptionList>): void; list(resourceGroup: string, registrationName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.CustomerSubscriptionList>): void; /** * Returns the specified product. * * @param {string} resourceGroup Name of the resource group. * * @param {string} registrationName Name of the Azure Stack registration. * * @param {string} customerSubscriptionName Name of the product. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<CustomerSubscription>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ getWithHttpOperationResponse(resourceGroup: string, registrationName: string, customerSubscriptionName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.CustomerSubscription>>; /** * Returns the specified product. * * @param {string} resourceGroup Name of the resource group. * * @param {string} registrationName Name of the Azure Stack registration. * * @param {string} customerSubscriptionName Name of the product. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {CustomerSubscription} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {CustomerSubscription} [result] - The deserialized result object if an error did not occur. * See {@link CustomerSubscription} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ get(resourceGroup: string, registrationName: string, customerSubscriptionName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.CustomerSubscription>; get(resourceGroup: string, registrationName: string, customerSubscriptionName: string, callback: ServiceCallback<models.CustomerSubscription>): void; get(resourceGroup: string, registrationName: string, customerSubscriptionName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.CustomerSubscription>): void; /** * Deletes a customer subscription under a registration. * * @param {string} resourceGroup Name of the resource group. * * @param {string} registrationName Name of the Azure Stack registration. * * @param {string} customerSubscriptionName Name of the product. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<null>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ deleteMethodWithHttpOperationResponse(resourceGroup: string, registrationName: string, customerSubscriptionName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<void>>; /** * Deletes a customer subscription under a registration. * * @param {string} resourceGroup Name of the resource group. * * @param {string} registrationName Name of the Azure Stack registration. * * @param {string} customerSubscriptionName Name of the product. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {null} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {null} [result] - The deserialized result object if an error did not occur. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ deleteMethod(resourceGroup: string, registrationName: string, customerSubscriptionName: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<void>; deleteMethod(resourceGroup: string, registrationName: string, customerSubscriptionName: string, callback: ServiceCallback<void>): void; deleteMethod(resourceGroup: string, registrationName: string, customerSubscriptionName: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<void>): void; /** * Creates a new customer subscription under a registration. * * @param {string} resourceGroup Name of the resource group. * * @param {string} registrationName Name of the Azure Stack registration. * * @param {string} customerSubscriptionName Name of the product. * * @param {object} customerCreationParameters Parameters use to create a * customer subscription. * * @param {string} [customerCreationParameters.tenantId] Tenant Id. * * @param {object} [customerCreationParameters.tags] Custom tags for the * resource. * * @param {string} [customerCreationParameters.etag] The entity tag used for * optimistic concurency when modifying the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<CustomerSubscription>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ createWithHttpOperationResponse(resourceGroup: string, registrationName: string, customerSubscriptionName: string, customerCreationParameters: models.CustomerSubscription, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.CustomerSubscription>>; /** * Creates a new customer subscription under a registration. * * @param {string} resourceGroup Name of the resource group. * * @param {string} registrationName Name of the Azure Stack registration. * * @param {string} customerSubscriptionName Name of the product. * * @param {object} customerCreationParameters Parameters use to create a * customer subscription. * * @param {string} [customerCreationParameters.tenantId] Tenant Id. * * @param {object} [customerCreationParameters.tags] Custom tags for the * resource. * * @param {string} [customerCreationParameters.etag] The entity tag used for * optimistic concurency when modifying the resource. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {CustomerSubscription} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {CustomerSubscription} [result] - The deserialized result object if an error did not occur. * See {@link CustomerSubscription} for more information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ create(resourceGroup: string, registrationName: string, customerSubscriptionName: string, customerCreationParameters: models.CustomerSubscription, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.CustomerSubscription>; create(resourceGroup: string, registrationName: string, customerSubscriptionName: string, customerCreationParameters: models.CustomerSubscription, callback: ServiceCallback<models.CustomerSubscription>): void; create(resourceGroup: string, registrationName: string, customerSubscriptionName: string, customerCreationParameters: models.CustomerSubscription, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.CustomerSubscription>): void; /** * Returns a list of products. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @returns {Promise} A promise is returned * * @resolve {HttpOperationResponse<CustomerSubscriptionList>} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. */ listNextWithHttpOperationResponse(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<HttpOperationResponse<models.CustomerSubscriptionList>>; /** * Returns a list of products. * * @param {string} nextPageLink The NextLink from the previous successful call * to List operation. * * @param {object} [options] Optional Parameters. * * @param {object} [options.customHeaders] Headers that will be added to the * request * * @param {ServiceCallback} [optionalCallback] - The optional callback. * * @returns {ServiceCallback|Promise} If a callback was passed as the last * parameter then it returns the callback else returns a Promise. * * {Promise} A promise is returned. * * @resolve {CustomerSubscriptionList} - The deserialized result object. * * @reject {Error|ServiceError} - The error object. * * {ServiceCallback} optionalCallback(err, result, request, response) * * {Error|ServiceError} err - The Error object if an error occurred, null otherwise. * * {CustomerSubscriptionList} [result] - The deserialized result object if an error did not occur. * See {@link CustomerSubscriptionList} for more * information. * * {WebResource} [request] - The HTTP Request object if an error did not occur. * * {http.IncomingMessage} [response] - The HTTP Response stream if an error did not occur. */ listNext(nextPageLink: string, options?: { customHeaders? : { [headerName: string]: string; } }): Promise<models.CustomerSubscriptionList>; listNext(nextPageLink: string, callback: ServiceCallback<models.CustomerSubscriptionList>): void; listNext(nextPageLink: string, options: { customHeaders? : { [headerName: string]: string; } }, callback: ServiceCallback<models.CustomerSubscriptionList>): void; }
the_stack
import { getElementByIdOrThrow, State } from './utils'; // see vis.js documentation at // https://visjs.github.io/vis-network/docs/network/ // https://visjs.github.io/vis-data/data/dataset.html // https://visjs.github.io/vis-network/examples/ // eslint-disable-next-line @typescript-eslint/no-empty-interface interface Node { readonly id: number; readonly label: string; readonly title: string; group?: string; shape?: string; } interface ActionEdge { readonly id?: number; // required by the DataSet class, but not used readonly from: number; readonly to: number; readonly label: string; readonly title: string; readonly actionName: string; // this is a custom extension to the vis.js network Edge } // eslint-disable-next-line @typescript-eslint/no-namespace declare namespace vis { type IdType = number | string; class DataSet<T> { constructor(content: T[]); length: number; add(node: T): void; get(id: number): T; get(filter: { filter: (edge: ActionEdge) => boolean }): T[]; clear(): void; update(nodes: Node[]): void; update(node: Node): void; } export class Network { // eslint-disable-next-line @typescript-eslint/no-explicit-any constructor(container: HTMLElement, treeData: { nodes: DataSet<Node>; edges: DataSet<ActionEdge> }, options: any); fit(): void; getSelectedNodes(): number[]; releaseNode(): void; focus(nodeId: number, arg1: { animation: boolean; locked: boolean }): void; selectNodes(arg0: number[]): void; on(arg0: string, event: (nodeEvent: { nodes: number[] }) => void): void; } } export class SearchTree { readonly network: vis.Network; autoFitEnabled = true; // create an array with nodes readonly nodes: vis.DataSet<Node> = new vis.DataSet([]); // create an array with edges readonly edges: vis.DataSet<ActionEdge> = new vis.DataSet([]); readonly treeData = { nodes: this.nodes, edges: this.edges }; /** * Creates tree */ constructor() { // create the network const container = getElementByIdOrThrow('network'); const options = { autoResize: true, height: '100%', width: '100%', layout: { hierarchical: { direction: "UD", sortMethod: "directed", blockShifting: true, edgeMinimization: true, parentCentralization: true, levelSeparation: 180, shakeTowards: "roots" // vs. "leaves" } }, interaction: { dragNodes: false }, physics: { enabled: false }, configure: { enabled: false }, nodes: { color: { highlight: { background: 'red', border: 'red' } } }, edges: { font: { align: 'top' }, arrows: { to: { enabled: true, scaleFactor: 0.5 } } }, groups: { plan: { color: { background: 'lightgreen' }, borderWidth: 0 }, deadEnd: { color: { background: 'brown' }, borderWidth: 0 }, visitedOrWorse: { color: { background: 'black' }, font: { color: 'white' }, borderWidth: 0 }, goal: { color: { background: 'green' }, borderWidth: 0 } } }; this.network = new vis.Network(container, this.treeData, options); } toggleAutoFit(): void { this.autoFitEnabled = !this.autoFitEnabled; } /** * Adds state to tree * @param newState new state * @param batch batch mode */ addStateToTree(newState: State, batch: boolean): void { this.nodes.add(toNode(newState)); if (newState.parentId !== null && newState.actionName) { this.addStateEdge(newState); } if (!batch && this.nodes.length < 100 && this.autoFitEnabled) { this.network.fit(); } } /** * Add edge towards the newState * @param newState new child state */ addStateEdge(newState: State): void { if (!newState.actionName || newState.parentId === undefined) { throw new Error(`Cannot progress _to_ the initial state.`); } const undecoratedActionName = newState.actionName.replace(/[├┤]$/, "").replace(/\[\d+\]/, "").trim(); const actionLabel = createActionLabel(newState.actionName!); const actionTitle = createActionTooltip(newState.actionName!); const edge: ActionEdge = { from: newState.parentId!, to: newState.id, actionName: undecoratedActionName, label: actionLabel, title: actionTitle }; this.edges.add(edge); } /** * Ends tree batch update. */ endTreeBatch(): void { this.network.fit(); } updateStateOnTree(state: State): void { this.nodes.update([toNode(state)]); } /** * Re-paints all states on the plan branch * @param planStates intermediate states in the plan and the goal state */ showPlanOnTree(planStates: State[]): void { planStates.forEach(state => this.updateStateOnTree(state)); // assuming state IDs grow monotonically const lastStateId = Math.max(...planStates.map(state => state.id as number)); const lastState = planStates.find(state => state.id === lastStateId); if (lastState) { lastState.isGoal = true; this.updateStateOnTree(lastState); } } /** * Visually select tree node * @param id state id */ selectTreeNode(id: number | null): void { if (id !== null) { this.network.selectNodes([id]); this.network.focus(id, { animation: true, locked: false }); } else { this.network.selectNodes([]); this.network.releaseNode(); } } clearTree(): void { this.nodes.clear(); this.edges.clear(); } fitTree(): void { this.network.fit(); } /** * @returns parent ID, selected ID (if root), or null if there is no selected node */ navigateTreeUp(): number | null { const selectedNodes = this.network.getSelectedNodes(); if (selectedNodes.length === 0) { return null; } const selectedNode = toIntNodeId(selectedNodes[0]); const parent = this.getParent(selectedNode); if (parent !== null) { return parent; } // in all other cases, the selection did not change return selectedNode; } /** * @returns parent ID, selected ID (if leaf), or null if there is no selected node */ navigateTreeDown(): number | null { const selectedNodes = this.network.getSelectedNodes(); if (selectedNodes.length === 0) { return null; } const selectedNode = toIntNodeId(selectedNodes[0]); const children = this.getChildren(selectedNode); if (children.length > 0) { return children[0]; } // in all other cases, the selection did not change return selectedNode; } /** * Navigating to +1 moves to the next sibling to the right. * Offset -2 navigates two sibling states to the left. * @param {int} offset direction and distance of navigation * @returns sibling ID, selected node ID (if most left/right sibling), or null if there is no selected node */ navigateTreeSiblings(offset: number): number | null { const selectedNodes = this.network.getSelectedNodes(); if (selectedNodes.length === 0) { return null; } const selectedNode = toIntNodeId(selectedNodes[0]); const siblings = this.getSiblingsIncludingSelf(selectedNode); const indexOfThisNodeAmongSiblings = siblings.indexOf(selectedNode); const newSelectedNodeIndex = indexOfThisNodeAmongSiblings + offset; if (newSelectedNodeIndex > -1 && newSelectedNodeIndex < siblings.length) { return siblings[newSelectedNodeIndex]; } // in all other cases, the selection did not change return selectedNode; } /** * Finds node's parent * @param childId child node ID */ getParent(childId: number): number | null { const parents = this.edges.get({ filter: function (edge: ActionEdge) { return edge.to === childId; } }); if (parents.length > 0) { return parents[0].from; } else { return null; } } /** * @param parentId parent ID * @returns sibling IDs */ getChildren(parentId: number): number[] { const edgesFromParent = this.edges.get({ filter: function (edge: ActionEdge) { return edge.from === parentId; } }); const children = edgesFromParent.map((e: ActionEdge) => e.to).filter(e => !!e).map(e => toIntNodeId(e!)); return children; } /** * Gets all siblings including this node. * @param nodeId node ID * @returns sibling IDs */ getSiblingsIncludingSelf(nodeId: number): number[] { const parent = this.getParent(nodeId); if (parent === null) { return []; } const siblings = this.getChildren(parent); return siblings; } /** * Navigates the tree to the child (if the action was exanded) * @param parentStateId parent state ID * @param actionName action name that expands the parent state * @returns child ID, or null, if the action was not expanded */ navigateToChildState(parentStateId: number, actionName: string): number | null { const edgesFromParent = this.edges.get({ filter: function (edge: ActionEdge) { return edge.from === parentStateId && edge.actionName === actionName; } }); if (edgesFromParent.length > 0) { return edgesFromParent[0].to; } else { return null; } } /** * Changes selected node shape * @param shape shape name; supported are: diamond, dot, star, triangle, triangleDown, hexagon, square and icon */ changeSelectedNodeShape(shape: string): void { const selectedNodes = this.network.getSelectedNodes(); if (selectedNodes.length === 0) { return; } const selectedNodeId = selectedNodes[0]; const selectedNode = this.nodes.get(selectedNodeId); if (selectedNode) { (selectedNode as Node).shape = shape; this.nodes.update(selectedNode); } } } const snapActionLegend = new Map<string, string>(); snapActionLegend.set('├', "Action start"); snapActionLegend.set('┤', "Action end"); /** * Constructs edge tooltip * @param fullActionName full action name * @returns action edge tooltip */ function createActionTooltip(fullActionName: string): string { let counter = 0; const counterMatch = fullActionName.match(/\[(\d+)\]/); if (counterMatch) { counter = parseInt(counterMatch[1]); } let tooltip = fullActionName.replace(/\[\d+\]/, "").replace(/[├┤]$/, " $&").split(' ') .filter(fragment => fragment !== ' ') .map(fragment => fragment in snapActionLegend ? snapActionLegend.get(fragment) : fragment) .join('\n'); if (counter > 0) { tooltip += '\nShot counter: ' + counter; } return tooltip; } /** * Constructs edge label * @param fullActionName full action name * @returns action label */ function createActionLabel(fullActionName: string): string { const fragments = fullActionName.replace(/\[\d+\]/, "").split(' '); const maxLineLength = 19; const label = fragments.reduce((prevValue, currentValue) => { const separator = prevValue.length + currentValue.length > maxLineLength ? '\n' : ' '; return prevValue + separator + currentValue; }); return label; } /** * Converts state to network node object * @param newState state */ function toNode(newState: State): Node { const label = toNodeLabel(newState); const title = toNodeTitle(newState); const node: Node = { id: newState.id, label: label, title: title }; if (newState.wasVisitedOrIsWorse) { node.group = 'visitedOrWorse'; } if (newState.isPlan) { // this flag is set in the extension for all states on the plan node.group = 'plan'; } if (newState.h !== undefined) { if (newState.isDeadEnd) { node.group = 'deadEnd'; } } if (newState.isGoal) { node.group = 'goal'; // todo: this is a wrong assumption that it is also a plan } return node; } /** * Creates label for the state visual node * @param newState state */ function toNodeLabel(newState: State): string { let label = 'O: ' + newState.id; if (newState.h !== undefined) { label += '\nH: ' + (newState.isDeadEnd ? 'Infinite' : newState.h); } return label; } /** * Creates tooltip for the state visual node * @param newState state */ function toNodeTitle(newState: State): string { let title = 'Order: ' + newState.id; if (newState.id.toString() !== newState.origId) { title += ' (' + newState.origId + ')'; } title += '\nGeneration: ' + newState.g + '\nEarliest time: ' + newState.earliestTime; if (newState.landmarks !== undefined) { title += '\nLandmarks: ' + newState.landmarks; } if (newState.wasVisitedOrIsWorse) { title += '\nState was visited or is worse than a previously visited state'; } if (newState.h !== undefined) { title += '\nHeuristic value: ' + (newState.isDeadEnd ? 'Infinite' : newState.h); } if (newState.totalMakespan) { title += '\nTotal makespan: ' + newState.totalMakespan; } if (newState.helpfulActions) { title += '\nHelpful actions: ' + newState.helpfulActions.length; } return title; } function toIntNodeId(nodeId: vis.IdType): number { return nodeId as number; } // todo: support for context menu: http://jsbin.com/qeyumiwepo/5/edit?html,output // todo: nodes.shape: diamond, dot, star, triangle, triangleDown, hexagon, square and icon // https://visjs.github.io/vis-network/examples/network/nodeStyles/icons.html
the_stack
import m from "mithril"; import Stream from "mithril/stream"; import {PipelineGroup} from "models/admin_pipelines/admin_pipelines"; import {Authorization, AuthorizedUsersAndRoles} from "models/authorization/authorization"; import {PipelineConfigTestData} from "models/pipeline_configs/spec/test_data"; import {Stage} from "models/pipeline_configs/stage"; import { PermissionsWidget, RolesSuggestionProvider } from "views/pages/clicky_pipeline_config/tabs/stage/permissions_tab_content"; import {TestHelper} from "views/pages/spec/test_helper"; describe("Permissions Tab Content", () => { const helper = new TestHelper(); afterEach(helper.unmount.bind(helper)); it("should render permissions info message", () => { const stage = Stage.fromJSON(PipelineConfigTestData.stage("Test")); mount(stage); expect(helper.byTestId("flash-message-info")) .toContainText( "All system administrators and pipeline group administrators can operate on this stage (this cannot be overridden)."); }); it("should render switch for inherit or specify locally", () => { const stage = Stage.fromJSON(PipelineConfigTestData.stage("Test")); mount(stage); expect(helper.byTestId("permissions-heading")).toContainText("Permissions for this stage:"); expect(helper.byTestId("input-field-for-inherit")).toBeInDOM(); expect(helper.allByTestId("form-field-label")[0]).toContainText("Inherit from the Pipeline Group"); expect(helper.q("span", helper.byTestId("input-field-for-inherit"))) .toContainText("Inherit authorization from the pipeline group."); expect(helper.byTestId("input-field-for-local")).toBeInDOM(); expect(helper.allByTestId("form-field-label")[1]).toContainText("Specify locally"); expect(helper.q("span", helper.byTestId("input-field-for-local"))) .toContainText("Define specific permissions locally. This will override pipeline group authorization."); }); it("should select inherit when no permissions are specified", () => { const stage = Stage.fromJSON(PipelineConfigTestData.stage("Test")); mount(stage); expect(stage.approval().authorization().isInherited()).toBeTrue(); expect(helper.byTestId("radio-inherit")).toBeChecked(); expect(helper.byTestId("radio-local")).not.toBeChecked(); }); it("should select local when permissions are overridden locally", () => { const stage = Stage.fromJSON(PipelineConfigTestData.stage("Test")); stage.approval().authorization().isInherited(false); stage.approval().authorization()._users.push(Stream("user1")); mount(stage); expect(stage.approval().authorization().isInherited()).toBeFalse(); expect(helper.byTestId("radio-inherit")).not.toBeChecked(); expect(helper.byTestId("radio-local")).toBeChecked(); }); it("should toggle isInherited state when permissions are toggled", () => { const stage = Stage.fromJSON(PipelineConfigTestData.stage("Test")); mount(stage); expect(stage.approval().authorization().isInherited()).toBeTrue(); expect(helper.byTestId("radio-inherit")).toBeChecked(); expect(helper.byTestId("radio-local")).not.toBeChecked(); helper.click(helper.byTestId("radio-local")); expect(stage.approval().authorization().isInherited()).toBeFalse(); expect(helper.byTestId("radio-inherit")).not.toBeChecked(); expect(helper.byTestId("radio-local")).toBeChecked(); }); it("should not render users and roles section when permissions are inherited", () => { const stage = Stage.fromJSON(PipelineConfigTestData.stage("Test")); mount(stage); expect(stage.approval().authorization().isInherited()).toBeTrue(); expect(helper.byTestId("radio-inherit")).toBeChecked(); expect(helper.byTestId("radio-local")).not.toBeChecked(); expect(helper.byTestId("users-and-roles")).not.toBeInDOM(); }); it("should render users and roles section when permissions are defined locally", () => { const stage = Stage.fromJSON(PipelineConfigTestData.stage("Test")); stage.approval().authorization().isInherited(false); stage.approval().authorization()._users.push(Stream("user1")); mount(stage); expect(stage.approval().authorization().isInherited()).toBeFalse(); expect(helper.byTestId("radio-inherit")).not.toBeChecked(); expect(helper.byTestId("radio-local")).toBeChecked(); expect(helper.byTestId("users-and-roles")).toBeInDOM(); }); it("should show no group permissions configured message no pipeline group permissions are defined", () => { const stage = Stage.fromJSON(PipelineConfigTestData.stage("Test")); stage.approval().authorization().isInherited(true); mount(stage); expect(stage.approval().authorization().isInherited()).toBeTrue(); expect(helper.byTestId("radio-inherit")).toBeChecked(); expect(helper.byTestId("radio-local")).not.toBeChecked(); const msg = "There is no authorization configured for this stage nor its pipeline group. Only GoCD administrators can operate this stage."; expect(helper.qa(`[data-test-id="flash-message-info"]`)).toContainText(msg); }); it("should render inherited group permissions", () => { const stage = Stage.fromJSON(PipelineConfigTestData.stage("Test")); stage.approval().authorization().isInherited(true); const admin = new AuthorizedUsersAndRoles([Stream("admin")], [Stream("admin-role")]); const operate = new AuthorizedUsersAndRoles([Stream("operate")], [Stream("operate-role")]); const pipelineGroup = new PipelineGroup("group1", new Authorization(undefined, admin, operate)); mount(stage, false, pipelineGroup); expect(helper.q("input", helper.byTestId("input-field-for-admin"))).toHaveValue("admin"); expect(helper.q("input", helper.byTestId("input-field-for-operate"))).toHaveValue("operate"); expect(helper.q("input", helper.byTestId("input-field-for-admin-role"))).toHaveValue("admin-role"); expect(helper.q("input", helper.byTestId("input-field-for-operate-role"))).toHaveValue("operate-role"); }); it("should copy over inherited permissions when toggled to specify locally", () => { const stage = Stage.fromJSON(PipelineConfigTestData.stage("Test")); stage.approval().authorization().isInherited(true); const admin = new AuthorizedUsersAndRoles([Stream("admin")], [Stream("admin-role")]); const operate = new AuthorizedUsersAndRoles([Stream("operate")], [Stream("operate-role")]); const pipelineGroup = new PipelineGroup("group1", new Authorization(undefined, admin, operate)); mount(stage, false, pipelineGroup); expect(helper.byTestId("radio-inherit")).toBeChecked(); expect(helper.byTestId("radio-local")).not.toBeChecked(); expect(helper.q("input", helper.byTestId("input-field-for-admin"))).toHaveValue("admin"); expect(helper.q("input", helper.byTestId("input-field-for-operate"))).toHaveValue("operate"); expect(helper.q("input", helper.byTestId("input-field-for-admin-role"))).toHaveValue("admin-role"); expect(helper.q("input", helper.byTestId("input-field-for-operate-role"))).toHaveValue("operate-role"); //toggle to specify locally helper.click(helper.byTestId("radio-local")); expect(helper.byTestId("radio-inherit")).not.toBeChecked(); expect(helper.byTestId("radio-local")).toBeChecked(); expect(helper.q("input", helper.byTestId("input-field-for-admin"))).toHaveValue("admin"); expect(helper.q("input", helper.byTestId("input-field-for-operate"))).toHaveValue("operate"); expect(helper.q("input", helper.byTestId("input-field-for-admin-role"))).toHaveValue("admin-role"); expect(helper.q("input", helper.byTestId("input-field-for-operate-role"))).toHaveValue("operate-role"); }); it("should not copy over inherited permissions when toggled to specify locally and locally permissions exists", () => { const stage = Stage.fromJSON(PipelineConfigTestData.stage("Test")); stage.approval().authorization().isInherited(false); stage.approval().authorization()._users.push(Stream("user1")); const admin = new AuthorizedUsersAndRoles([Stream("admin")], [Stream("admin-role")]); const operate = new AuthorizedUsersAndRoles([Stream("operate")], [Stream("operate-role")]); const pipelineGroup = new PipelineGroup("group1", new Authorization(undefined, admin, operate)); mount(stage, false, pipelineGroup); //initially permissions are defined locally expect(helper.byTestId("radio-inherit")).not.toBeChecked(); expect(helper.byTestId("radio-local")).toBeChecked(); expect(helper.q("input", helper.byTestId("input-field-for-user1"))).toHaveValue("user1"); //toggle to inherit helper.click(helper.byTestId("radio-inherit")); expect(helper.byTestId("radio-inherit")).toBeChecked(); expect(helper.byTestId("radio-local")).not.toBeChecked(); expect(helper.q("input", helper.byTestId("input-field-for-admin"))).toHaveValue("admin"); expect(helper.q("input", helper.byTestId("input-field-for-operate"))).toHaveValue("operate"); expect(helper.q("input", helper.byTestId("input-field-for-admin-role"))).toHaveValue("admin-role"); expect(helper.q("input", helper.byTestId("input-field-for-operate-role"))).toHaveValue("operate-role"); //again toggle back to specify locally helper.click(helper.byTestId("radio-local")); expect(helper.byTestId("radio-inherit")).not.toBeChecked(); expect(helper.byTestId("radio-local")).toBeChecked(); expect(helper.q("input", helper.byTestId("input-field-for-user1"))).toHaveValue("user1"); }); it("should not allow users to modify inherited group permissions", () => { const stage = Stage.fromJSON(PipelineConfigTestData.stage("Test")); stage.approval().authorization().isInherited(true); const admin = new AuthorizedUsersAndRoles([Stream("admin")], [Stream("admin-role")]); const operate = new AuthorizedUsersAndRoles([Stream("operate")], [Stream("operate-role")]); const pipelineGroup = new PipelineGroup("group1", new Authorization(undefined, admin, operate)); mount(stage, false, pipelineGroup); expect(helper.q("input", helper.byTestId("input-field-for-admin"))).toBeDisabled(); expect(helper.q("input", helper.byTestId("input-field-for-operate"))).toBeDisabled(); expect(helper.q("input", helper.byTestId("input-field-for-admin-role"))).toBeDisabled(); expect(helper.q("input", helper.byTestId("input-field-for-operate-role"))).toBeDisabled(); expect(helper.q("i", helper.byTestId("input-field-for-admin"))).not.toBeInDOM(); expect(helper.q("i", helper.byTestId("input-field-for-operate"))).not.toBeInDOM(); expect(helper.q("i", helper.byTestId("input-field-for-admin-role"))).not.toBeInDOM(); expect(helper.q("i", helper.byTestId("input-field-for-operate-role"))).not.toBeInDOM(); }); it("should render users in an input field", () => { const stage = Stage.fromJSON(PipelineConfigTestData.stage("Test")); stage.approval().authorization().isInherited(false); stage.approval().authorization()._users.push(Stream("user1"), Stream("user2")); mount(stage); expect(helper.byTestId("input-field-for-user1")).toBeInDOM(); expect(helper.q("input", helper.byTestId("input-field-for-user1"))).toHaveValue("user1"); expect(helper.byTestId("input-field-for-user2")).toBeInDOM(); expect(helper.q("input", helper.byTestId("input-field-for-user2"))).toHaveValue("user2"); }); it("should render users in an input field", () => { const stage = Stage.fromJSON(PipelineConfigTestData.stage("Test")); stage.approval().authorization().isInherited(false); stage.approval().authorization()._users.push(Stream("user1"), Stream("user2")); mount(stage); expect(helper.qa("input", helper.byTestId("users"))).toHaveLength(2); expect(helper.byTestId("input-field-for-user1")).toBeInDOM(); expect(helper.q("input", helper.byTestId("input-field-for-user1"))).toHaveValue("user1"); expect(helper.byTestId("input-field-for-user2")).toBeInDOM(); expect(helper.q("input", helper.byTestId("input-field-for-user2"))).toHaveValue("user2"); }); it("should render roles in an input field", () => { const stage = Stage.fromJSON(PipelineConfigTestData.stage("Test")); stage.approval().authorization().isInherited(false); stage.approval().authorization()._roles.push(Stream("role1"), Stream("role2")); mount(stage); expect(helper.qa("input", helper.byTestId("roles"))).toHaveLength(2); expect(helper.byTestId("input-field-for-role1")).toBeInDOM(); expect(helper.q("input", helper.byTestId("input-field-for-role1"))).toHaveValue("role1"); expect(helper.byTestId("input-field-for-role2")).toBeInDOM(); expect(helper.q("input", helper.byTestId("input-field-for-role2"))).toHaveValue("role2"); }); it("should bind user input to model", () => { const stage = Stage.fromJSON(PipelineConfigTestData.stage("Test")); stage.approval().authorization().isInherited(false); stage.approval().authorization()._users.push(Stream("user1")); mount(stage); expect(stage.approval().authorization()._users[0]()).toEqual("user1"); expect(helper.q("input", helper.byTestId("input-field-for-user1"))).toHaveValue("user1"); helper.oninput("input", "bob", helper.byTestId("input-field-for-user1")); expect(stage.approval().authorization()._users[0]()).toEqual("bob"); expect(helper.q("input", helper.byTestId("input-field-for-bob"))).toHaveValue("bob"); }); it("should bind role input to model", () => { const stage = Stage.fromJSON(PipelineConfigTestData.stage("Test")); stage.approval().authorization().isInherited(false); stage.approval().authorization()._roles.push(Stream("role1")); mount(stage); expect(stage.approval().authorization()._roles[0]()).toEqual("role1"); expect(helper.q("input", helper.byTestId("input-field-for-role1"))).toHaveValue("role1"); helper.oninput("input", "developers", helper.byTestId("input-field-for-role1")); expect(stage.approval().authorization()._roles[0]()).toEqual("developers"); expect(helper.q("input", helper.byTestId("input-field-for-developers"))).toHaveValue("developers"); }); it("should remove user on click of remove icon", () => { const stage = Stage.fromJSON(PipelineConfigTestData.stage("Test")); stage.approval().authorization().isInherited(false); stage.approval().authorization()._users.push(Stream("user1"), Stream("user2")); mount(stage); expect(stage.approval().authorization()._users).toHaveLength(2); expect(helper.q("input", helper.byTestId("input-field-for-user1"))).toHaveValue("user1"); expect(helper.q("input", helper.byTestId("input-field-for-user2"))).toHaveValue("user2"); helper.click("i", helper.byTestId("input-field-for-user1")); expect(stage.approval().authorization()._users).toHaveLength(1); expect(helper.byTestId("input-field-for-user1")).not.toBeInDOM(); expect(helper.q("input", helper.byTestId("input-field-for-user2"))).toHaveValue("user2"); }); it("should remove role on click of remove icon", () => { const stage = Stage.fromJSON(PipelineConfigTestData.stage("Test")); stage.approval().authorization().isInherited(false); stage.approval().authorization()._roles.push(Stream("role1"), Stream("role2")); mount(stage); expect(stage.approval().authorization()._roles).toHaveLength(2); expect(helper.q("input", helper.byTestId("input-field-for-role1"))).toHaveValue("role1"); expect(helper.q("input", helper.byTestId("input-field-for-role2"))).toHaveValue("role2"); helper.click("i", helper.byTestId("input-field-for-role1")); expect(stage.approval().authorization()._roles).toHaveLength(1); expect(helper.byTestId("input-field-for-role1")).not.toBeInDOM(); expect(helper.q("input", helper.byTestId("input-field-for-role2"))).toHaveValue("role2"); }); it("should add an empty user input on click of add", () => { const stage = Stage.fromJSON(PipelineConfigTestData.stage("Test")); stage.approval().authorization().isInherited(false); mount(stage); expect(helper.qa("input", helper.byTestId("users"))).toHaveLength(0); helper.click("button", helper.byTestId("users")); expect(helper.qa("input", helper.byTestId("users"))).toHaveLength(1); }); it("should add an empty role input on click of add", () => { const stage = Stage.fromJSON(PipelineConfigTestData.stage("Test")); stage.approval().authorization().isInherited(false); mount(stage); expect(helper.qa("input", helper.byTestId("roles"))).toHaveLength(0); helper.click("button", helper.byTestId("roles")); expect(helper.qa("input", helper.byTestId("roles"))).toHaveLength(1); }); describe("Role Autocompletion", () => { beforeEach(() => { const stage = Stage.fromJSON(PipelineConfigTestData.stage("Test")); stage.approval().authorization().isInherited(false); mount(stage); }); it("should provide all roles", (done) => { const allRoles = Stream(["admin", "operators", "viewers"] as string[]); const configuredRoles = [] as string[]; const provider = new RolesSuggestionProvider(allRoles, configuredRoles); provider.getData().then((suggestions) => { expect(suggestions).toEqual(allRoles()); done(); }); }); it("should provide no roles suggestions when all roles are configured", (done) => { const allRoles = Stream(["admin", "operators", "viewers"] as string[]); const configuredRoles = ["admin", "operators", "viewers"] as string[]; const provider = new RolesSuggestionProvider(allRoles, configuredRoles); provider.getData().then((suggestions) => { expect(suggestions).toEqual([]); done(); }); }); it("should provide roles suggestions which are not configured", (done) => { const allRoles = Stream(["admin", "operators", "viewers"] as string[]); const configuredRoles = ["admin"] as string[]; const provider = new RolesSuggestionProvider(allRoles, configuredRoles); provider.getData().then((suggestions) => { expect(suggestions).toEqual(["operators", "viewers"]); done(); }); }); }); it("should render errors related to users", () => { const stage = Stage.fromJSON(PipelineConfigTestData.stage("Test")); stage.approval().authorization().isInherited(false); stage.approval().authorization()._users.push(Stream("user1")); stage.approval().authorization().errors().add("users", "user 'user1' does not exists"); mount(stage); expect(helper.byTestId("users-errors")).toContainText("user 'user1' does not exists"); }); it("should render errors related to roles", () => { const stage = Stage.fromJSON(PipelineConfigTestData.stage("Test")); stage.approval().authorization().isInherited(false); stage.approval().authorization()._roles.push(Stream("role1")); stage.approval().authorization().errors().add("roles", "role 'role1' does not exists"); mount(stage); expect(helper.byTestId("roles-errors")).toContainText("role 'role1' does not exists"); }); it("should not render local permission definition message when permissions are inherited", () => { const stage = Stage.fromJSON(PipelineConfigTestData.stage("Test")); stage.approval().authorization().isInherited(true); mount(stage); expect(helper.byTestId("local-permission-msg")).not.toBeInDOM(); }); it("should render local permission definition message", () => { const msg = "The pipeline group that this pipeline belongs to has permissions configured. You can add only those users and roles that have permissions to operate on this pipeline group."; const stage = Stage.fromJSON(PipelineConfigTestData.stage("Test")); stage.approval().authorization().isInherited(false); stage.approval().authorization()._roles.push(Stream("role1")); mount(stage); expect(helper.byTestId("local-permission-msg")).toContainText(msg); }); describe("Read Only", () => { beforeEach(() => { const stage = Stage.fromJSON(PipelineConfigTestData.stage("Test", "Job1")); stage.approval().authorization().isInherited(false); stage.approval().authorization()._users.push(Stream("user1")); stage.approval().authorization()._roles.push(Stream("role1")); mount(stage, true); }); it("should render disabled switch for inherit or specify locally", () => { expect(helper.byTestId("radio-inherit")).toBeDisabled(); expect(helper.byTestId("radio-local")).toBeDisabled(); }); it("should render disabled input for user", () => { expect(helper.q("input", helper.byTestId("users"))).toBeDisabled(); }); it("should render disabled input for role", () => { expect(helper.q("input", helper.byTestId("roles"))).toBeDisabled(); }); it("should not render remove user", () => { expect(helper.q("i", helper.byTestId("input-field-for-user1"))).not.toBeInDOM(); }); it("should not render remove role", () => { expect(helper.q("i", helper.byTestId("input-field-for-role1"))).not.toBeInDOM(); }); it("should not render add user button", () => { expect(helper.q("button", helper.byTestId("users"))).not.toBeInDOM(); }); it("should not render add role button", () => { expect(helper.q("button", helper.byTestId("roles"))).not.toBeInDOM(); }); }); function mount(stage: Stage, isEntityDefinedInConfigRepository: boolean = false, pipelineGroup: PipelineGroup = new PipelineGroup("", new Authorization())) { const isInherited = stage.approval().authorization().isInherited(); const selectedPermission = Stream(isInherited ? "inherit" : "local"); helper.mount(() => <PermissionsWidget entity={stage} groupPermissions={Stream(pipelineGroup)} isEntityDefinedInConfigRepository={isEntityDefinedInConfigRepository} selectedPermission={selectedPermission} allRoles={Stream<string[]>([])}/>); } });
the_stack
import type { Tanker, b64string } from '@tanker/core'; import { errors, statuses } from '@tanker/core'; import { createIdentity } from '@tanker/identity'; import { expect, silencer } from '@tanker/test-utils'; import { zeroDelayGenerator } from '@tanker/http-utils'; import { random, utils } from '@tanker/crypto'; import type { TestArgs } from './helpers'; const { STOPPED, READY, IDENTITY_REGISTRATION_NEEDED, IDENTITY_VERIFICATION_NEEDED } = statuses; export const generateSessionTests = (args: TestArgs) => { describe('start', () => { let bobIdentity: b64string; let bobLaptop: Tanker; beforeEach(async () => { bobIdentity = await args.appHelper.generateIdentity(); bobLaptop = args.makeTanker(); }); afterEach(async () => { await bobLaptop.stop(); }); it('has STOPPED status before start', async () => { expect(bobLaptop.status).to.equal(STOPPED); }); it('throws when having configured a non existing app', silencer.wrapper('error', /trustchain_not_found/)(async () => { const nonExistentB64AppSecret = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=='; const publicKey = 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA='; const publicKeyBytes = utils.fromBase64(publicKey); const nonExistentB64AppId = utils.toBase64(utils.generateAppID(publicKeyBytes)); const userId = 'bob'; bobIdentity = await createIdentity(nonExistentB64AppId, nonExistentB64AppSecret, userId); const bobMobile = args.makeTanker(nonExistentB64AppId); await expect(bobMobile.start(bobIdentity)).to.be.rejectedWith(errors.PreconditionFailed, 'app_not_found'); await bobMobile.stop(); })); it('throws when giving an invalid identity', async () => { await expect(bobLaptop.start('secret')).to.be.rejectedWith(errors.InvalidArgument); }); it('returns IDENTITY_REGISTRATION_NEEDED status if new identity provided', async () => { await bobLaptop.start(bobIdentity); await expect(bobLaptop.status).to.equal(IDENTITY_REGISTRATION_NEEDED); }); it('returns IDENTITY_VERIFICATION_NEEDED status if identity of existing user provided on new device', async () => { await bobLaptop.start(bobIdentity); await bobLaptop.registerIdentity({ passphrase: 'passphrase' }); const bobPhone = args.makeTanker(); await bobPhone.start(bobIdentity); await expect(bobPhone.status).to.equal(IDENTITY_VERIFICATION_NEEDED); await bobPhone.stop(); }); it('returns READY status if identity of existing user provided on existing device', async () => { await bobLaptop.start(bobIdentity); await bobLaptop.registerIdentity({ passphrase: 'passphrase' }); await bobLaptop.stop(); await bobLaptop.start(bobIdentity); await expect(bobLaptop.status).to.equal(READY); }); }); describe('stop', () => { let bobIdentity: b64string; let bobLaptop: Tanker; beforeEach(async () => { bobIdentity = await args.appHelper.generateIdentity(); bobLaptop = args.makeTanker(); await bobLaptop.start(bobIdentity); }); it('stops a session with identity registration needed status', async () => { await bobLaptop.stop(); await expect(bobLaptop.status).to.equal(STOPPED); }); it('stops a session with ready or identity verification needed status', async () => { await bobLaptop.registerIdentity({ passphrase: 'passphrase' }); await expect(bobLaptop.status).to.equal(READY); await bobLaptop.stop(); await expect(bobLaptop.status).to.equal(STOPPED); const bobPhone = args.makeTanker(); await bobPhone.start(bobIdentity); await expect(bobPhone.status).to.equal(IDENTITY_VERIFICATION_NEEDED); await bobPhone.stop(); await expect(bobPhone.status).to.equal(STOPPED); }); it('stops a session and rejects in-progress operations with OperationCanceled error', async () => { const registrationPromise = bobLaptop.registerIdentity({ passphrase: 'passphrase' }); await bobLaptop.stop(); await expect(bobLaptop.status).to.equal(STOPPED); await expect(registrationPromise).to.be.rejectedWith(errors.OperationCanceled); }); }); describe('registerIdentity', () => { let bobIdentity: b64string; let bobLaptop: Tanker; beforeEach(async () => { bobIdentity = await args.appHelper.generateIdentity(); bobLaptop = args.makeTanker(); }); afterEach(async () => { await bobLaptop.stop(); }); it('throws when registering before having started a session', async () => { await expect(bobLaptop.registerIdentity({ passphrase: 'passphrase' })).to.be.rejectedWith(errors.PreconditionFailed); }); it('creates the first device with the passphrase method', async () => { await bobLaptop.start(bobIdentity); await bobLaptop.registerIdentity({ passphrase: 'passphrase' }); await expect(bobLaptop.status).to.equal(READY); }); it('re-start the first device created with the passphrase method', async () => { await bobLaptop.start(bobIdentity); await bobLaptop.registerIdentity({ passphrase: 'passphrase' }); await expect(bobLaptop.status).to.equal(READY); await bobLaptop.stop(); await expect(bobLaptop.status).to.equal(STOPPED); await bobLaptop.start(bobIdentity); await expect(bobLaptop.status).to.equal(READY); }); }); describe('recovery after interrupted session opening', () => { let bobIdentity: b64string; let bobLaptop: Tanker; beforeEach(async () => { bobIdentity = await args.appHelper.generateIdentity(); bobLaptop = args.makeTanker(); }); afterEach(async () => { await bobLaptop.stop(); }); const interruptMessage = 'Browser crashed!'; /* eslint-disable no-param-reassign, no-shadow */ const interruptBefore = (object: any, method: string) => { const originalMethod = object[method]; object[method] = () => { object[method] = originalMethod; throw new Error(interruptMessage); }; }; /* eslint-enable no-param-reassign, no-shadow */ describe('during registration', () => { it('can start and create a new device if interrupted just after sending user creation blocks', async () => { await bobLaptop.start(bobIdentity); // Force an exception to occur between block sending and receival during registration interruptBefore(bobLaptop.session._localUserManager, 'updateDeviceInfo'); // eslint-disable-line no-underscore-dangle // Will create the user on the trustchain but fail to go further... the first device is lost await expect(bobLaptop.registerIdentity({ passphrase: 'passphrase' })).to.be.rejectedWith(interruptMessage); await bobLaptop.stop(); // Will detect user exists on the trustchain, and ask for a new identity verification to create a new device await bobLaptop.start(bobIdentity); await expect(bobLaptop.status).to.equal(IDENTITY_VERIFICATION_NEEDED); await bobLaptop.verifyIdentity({ passphrase: 'passphrase' }); // Check two devices have been created const devices = await bobLaptop.getDeviceList(); expect(devices).to.have.lengthOf(2); expect(devices).to.deep.include.members([{ id: bobLaptop.deviceId, isRevoked: false }]); }); }); describe('during verification', () => { let bobDesktop: Tanker; beforeEach(async () => { bobDesktop = args.makeTanker(); await bobDesktop.start(bobIdentity); await bobDesktop.registerIdentity({ passphrase: 'passphrase' }); }); afterEach(async () => { await bobDesktop.stop(); }); it('can start and create a new device if interrupted just after sending device creation block', async () => { await bobLaptop.start(bobIdentity); // Force an exception to occur between block sending and receival during verification interruptBefore(bobLaptop.session._localUserManager, 'updateDeviceInfo'); // eslint-disable-line no-underscore-dangle // Will create the device on the trustchain but fail to go further... await expect(bobLaptop.verifyIdentity({ passphrase: 'passphrase' })).to.be.rejectedWith(interruptMessage); await bobLaptop.stop(); // Will detect user exists on the trustchain, and ask for a new identity verification to create a new device await bobLaptop.start(bobIdentity); await expect(bobLaptop.status).to.equal(IDENTITY_VERIFICATION_NEEDED); await bobLaptop.verifyIdentity({ passphrase: 'passphrase' }); // Check two devices have been created const devices = await bobLaptop.getDeviceList(); expect(devices).to.have.lengthOf(3); expect(devices).to.deep.include.members([{ id: bobLaptop.deviceId, isRevoked: false }]); }); }); }); describe('session expiration', () => { let bobIdentity: b64string; let bobLaptop: Tanker; /* eslint-disable no-param-reassign, no-underscore-dangle */ const mockExpireAccessToken = (tanker: Tanker) => { tanker._session!._client._accessToken = utils.toSafeBase64(random(32)); tanker._session!._client._retryDelayGenerator = zeroDelayGenerator; }; /* eslint-enable no-param-reassign, no-underscore-dangle */ beforeEach(async () => { bobIdentity = await args.appHelper.generateIdentity(); bobLaptop = args.makeTanker(); await bobLaptop.start(bobIdentity); await bobLaptop.registerIdentity({ passphrase: 'passphrase' }); }); afterEach(async () => { await bobLaptop.stop(); }); it('can re-authenticate a new user after session token expiration and retry the failed operation', async () => { mockExpireAccessToken(bobLaptop); await expect(bobLaptop.encrypt('some secret')).to.be.fulfilled; }); it('can re-authenticate a new device after session token expiration and retry the failed operation', async () => { const bobDesktop = args.makeTanker(); await bobDesktop.start(bobIdentity); await bobDesktop.verifyIdentity({ passphrase: 'passphrase' }); mockExpireAccessToken(bobDesktop); await expect(bobDesktop.encrypt('some secret')).to.be.fulfilled; await bobDesktop.stop(); }); it('can re-authenticate an existing device after session token expiration and retry the failed operation', async () => { // Reopen existing device await bobLaptop.stop(); await bobLaptop.start(bobIdentity); mockExpireAccessToken(bobLaptop); await expect(bobLaptop.encrypt('some secret')).to.be.fulfilled; }); }); };
the_stack
import Debug from 'debug'; import { isI18nData, RootSchema, NodeSchema, isJSExpression, JSSlot } from '@alilc/lowcode-types'; // moment对象配置 import _moment from 'moment'; import 'moment/locale/zh-cn'; import pkg from '../../package.json'; import { isEmpty } from 'lodash'; import _serialize from 'serialize-javascript'; import * as _jsonuri from 'jsonuri'; import IntlMessageFormat from 'intl-messageformat'; export const moment = _moment; moment.locale('zh-cn'); (window as any).sdkVersion = pkg.version; export { pick, isEqualWith as deepEqual, cloneDeep as clone, isEmpty, throttle, debounce } from 'lodash'; export const jsonuri = _jsonuri; export const serialize = _serialize; const ReactIs = require('react-is'); const ReactPropTypesSecret = require('prop-types/lib/ReactPropTypesSecret'); const factoryWithTypeCheckers = require('prop-types/factoryWithTypeCheckers'); const PropTypes2 = factoryWithTypeCheckers(ReactIs.isElement, true); const EXPRESSION_TYPE = { JSEXPRESSION: 'JSExpression', JSFUNCTION: 'JSFunction', JSSLOT: 'JSSlot', JSBLOCK: 'JSBlock', I18N: 'i18n', }; const debug = Debug('utils:index'); /** * check if schema passed in is a valid schema * @name isSchema * @returns boolean */ export function isSchema(schema: any): schema is NodeSchema { if (isEmpty(schema)) { return false; } // Leaf and Slot should be valid if (schema.componentName === 'Leaf' || schema.componentName === 'Slot') { return true; } if (Array.isArray(schema)) { return schema.every((item) => isSchema(item)); } // check if props is valid const isValidProps = (props: any) => { if (!props) { return false; } if (isJSExpression(props)) { return true; } return (typeof schema.props === 'object' && !Array.isArray(props)); }; return !!(schema.componentName && isValidProps(schema.props)); } /** * check if schema passed in is a container type, including : Component Block Page * @param schema * @returns boolean */ export function isFileSchema(schema: NodeSchema): schema is RootSchema { if (!isSchema(schema)) { return false; } return ['Page', 'Block', 'Component'].includes(schema.componentName); } /** * check if current page is nested within another page with same host * @returns boolean */ export function inSameDomain() { try { return window.parent !== window && window.parent.location.host === window.location.host; } catch (e) { return false; } } /** * get css styled name from schema`s fileName * FileName -> lce-file-name * @returns string */ export function getFileCssName(fileName: string) { if (!fileName) { return; } const name = fileName.replace(/([A-Z])/g, '-$1').toLowerCase(); return (`lce-${name}`) .split('-') .filter((p) => !!p) .join('-'); } /** * check if a object is type of JSSlot * @returns string */ export function isJSSlot(obj: any): obj is JSSlot { if (!obj) { return false; } if (typeof obj !== 'object' || Array.isArray(obj)) { return false; } // Compatible with the old protocol JSBlock return ([EXPRESSION_TYPE.JSSLOT, EXPRESSION_TYPE.JSBLOCK].includes(obj.type)); } /** * get value from an object * @returns string */ export function getValue(obj: any, path: string, defaultValue = {}) { // array is not valid type, return default value if (Array.isArray(obj)) { return defaultValue; } if (isEmpty(obj) || typeof obj !== 'object') { return defaultValue; } const res = path.split('.').reduce((pre, cur) => { return pre && pre[cur]; }, obj); if (res === undefined) { return defaultValue; } return res; } /** * 用于处理国际化字符串 * @param {*} key 语料标识 * @param {*} values 字符串模版变量 * @param {*} locale 国际化标识,例如 zh-CN、en-US * @param {*} messages 国际化语言包 */ export function getI18n(key: string, values = {}, locale = 'zh-CN', messages: Record<string, any> = {}) { if (!messages || !messages[locale] || !messages[locale][key]) { return ''; } const formater = new IntlMessageFormat(messages[locale][key], locale); return formater.format(values); } /** * 判断当前组件是否能够设置ref * @param {*} Comp 需要判断的组件 */ export function canAcceptsRef(Comp: any) { const hasSymbol = typeof Symbol === 'function' && Symbol.for; const REACT_FORWARD_REF_TYPE = hasSymbol ? Symbol.for('react.forward_ref') : 0xead0; // eslint-disable-next-line max-len return Comp?.$$typeof === REACT_FORWARD_REF_TYPE || Comp?.prototype?.isReactComponent || Comp?.prototype?.setState || Comp._forwardRef; } /** * transform array to a object * @param arr array to be transformed * @param key key of array item, which`s value will be used as key in result map * @param overwrite overwrite existing item in result or not * @returns object result map */ export function transformArrayToMap(arr: any[], key: string, overwrite = true) { if (isEmpty(arr) || !Array.isArray(arr)) { return {}; } const res: any = {}; arr.forEach((item) => { const curKey = item[key]; if (item[key] === undefined) { return; } if (res[curKey] && !overwrite) { return; } res[curKey] = item; }); return res; } export function checkPropTypes(value: any, name: string, rule: any, componentName: string) { let ruleFunction = rule; if (typeof rule === 'string') { ruleFunction = new Function(`"use strict"; const PropTypes = arguments[0]; return ${rule}`)(PropTypes2); } if (!ruleFunction || typeof ruleFunction !== 'function') { console.warn('checkPropTypes should have a function type rule argument'); return true; } const err = ruleFunction( { [name]: value, }, name, componentName, 'prop', null, ReactPropTypesSecret, ); if (err) { console.warn(err); } return !err; } /** * transform string to a function * @param str function in string form * @returns funtion */ export function transformStringToFunction(str: string) { if (typeof str !== 'string') { return str; } if (inSameDomain() && (window.parent as any).__newFunc) { return (window.parent as any).__newFunc(`"use strict"; return ${str}`)(); } else { return new Function(`"use strict"; return ${str}`)(); } } /** * 对象类型JSExpression,支持省略this * @param str expression in string form * @param self scope object * @returns funtion */ export function parseExpression(str: any, self: any) { try { const contextArr = ['"use strict";', 'var __self = arguments[0];']; contextArr.push('return '); let tarStr: string; tarStr = (str.value || '').trim(); // NOTE: use __self replace 'this' in the original function str // may be wrong in extreme case which contains '__self' already tarStr = tarStr.replace(/this(\W|$)/g, (_a: any, b: any) => `__self${b}`); tarStr = contextArr.join('\n') + tarStr; // 默认调用顶层窗口的parseObj, 保障new Function的window对象是顶层的window对象 if (inSameDomain() && (window.parent as any).__newFunc) { return (window.parent as any).__newFunc(tarStr)(self); } const code = `with($scope || {}) { ${tarStr} }`; return new Function('$scope', code)(self); } catch (err) { debug('parseExpression.error', err, str, self); return undefined; } } /** * capitalize first letter * @param word string to be proccessed * @returns string capitalized string */ export function capitalizeFirstLetter(word: string) { if (!word || !isString(word) || word.length === 0) { return word; } return word[0].toUpperCase() + word.slice(1); } /** * check str passed in is a string type of not * @param str obj to be checked * @returns boolean */ export function isString(str: any): boolean { return {}.toString.call(str) === '[object String]'; } /** * check if obj is type of variable structure * @param obj object to be checked * @returns boolean */ export function isVariable(obj: any) { if (!obj || Array.isArray(obj)) { return false; } return typeof obj === 'object' && obj?.type === 'variable'; } /** * 将 i18n 结构,降级解释为对 i18n 接口的调用 * @param i18nInfo object * @param self context */ export function parseI18n(i18nInfo: any, self: any) { return parseExpression({ type: EXPRESSION_TYPE.JSEXPRESSION, value: `this.i18n('${i18nInfo.key}')`, }, self); } /** * for each key in targetObj, run fn with the value of the value, and the context paased in. * @param targetObj object that keys will be for each * @param fn function that process each item * @param context */ export function forEach(targetObj: any, fn: any, context?: any) { if (!targetObj || Array.isArray(targetObj) || isString(targetObj) || typeof targetObj !== 'object') { return; } Object.keys(targetObj).forEach((key) => fn.call(context, targetObj[key], key)); } export function parseData(schema: unknown, self: any): any { if (isJSExpression(schema)) { return parseExpression(schema, self); } else if (isI18nData(schema)) { return parseI18n(schema, self); } else if (typeof schema === 'string') { return schema.trim(); } else if (Array.isArray(schema)) { return schema.map((item) => parseData(item, self)); } else if (typeof schema === 'function') { return schema.bind(self); } else if (typeof schema === 'object') { // 对于undefined及null直接返回 if (!schema) { return schema; } const res: any = {}; forEach(schema, (val: any, key: string) => { if (key.startsWith('__')) { return; } res[key] = parseData(val, self); }); return res; } return schema; } /** * process params for using in a url query * @param obj params to be processed * @returns string */ export function serializeParams(obj: any) { let result: any = []; forEach(obj, (val: any, key: any) => { if (val === null || val === undefined || val === '') { return; } if (typeof val === 'object') { result.push(`${key}=${encodeURIComponent(JSON.stringify(val))}`); } else { result.push(`${key}=${encodeURIComponent(val)}`); } }); return result.join('&'); }
the_stack
import { Base } from "../class/Base.js" import { CalculationContext, CalculationGen, CalculationSync, Context, ContextGen, Contexts, ContextSync } from "../primitives/Calculation.js" import { prototypeValue } from "../util/Helpers.js" import { ProposedOrPrevious } from "./Effect.js" import { ChronoGraph } from "./Graph.js" import { Quark, QuarkConstructor } from "./Quark.js" import { Revision } from "./Revision.js" import { Transaction, YieldableValue } from "./Transaction.js" //--------------------------------------------------------------------------------------------------------------------- /** Levels of the [[Identifier|identifiers]] as simple integers. Defines the order of calculation, enforced by the following rule - all lower level identifiers should be already calculated before the calculation of the identifier with the higher level starts. Because of this, the lower level identifiers can not depend on higher level identifiers. This rule means that effects from all identifiers of the lower levels will be already processed, when calculating an identifier of the higher level. Normally you don't need to specify a level for your identifiers. */ export enum Levels { // must be sync UserInput = 0, DependsOnlyOnUserInput = 1, DependsOnlyOnDependsOnlyOnUserInput = 2, // asynchronicity starts from here DependsOnSelfKind = 3 } //--------------------------------------------------------------------------------------------------------------------- /** * The base class for [[Identifier|identifiers]]. It contains only "meta" properties that describes "abstract" identifier. * The [[Field]] class inherit from this class. * * To understand the difference between the "abstract" identifier and the "specific" identifier, * imagine a set of instances of the same entity class. Lets say that class has a field "name". * All of those instances each will have different "specific" identifiers for the field "name". * * In the same time, some properties are common for all "specific" identifiers, like [[Meta.equality|equality]], [[Meta.lazy|lazy]] etc. * Such properties, that does not change between every "specific" identifier we will call "meta" properties. * * This class has 2 generic arguments - `ValueT` and `ContextT`. The 1st one defines the type of the identifier's value. * The 2nd - the identifier's computation context (synchronous of generator). */ export class Meta<ValueT = any, ContextT extends Context = Context> extends Base { /** * The name of the identifiers. Not an id, does not imply uniqueness. */ name : any = undefined ArgsT : any[] /** * The type of the effects that can be "yielded" from the calculation function */ YieldT : YieldableValue ValueT : ValueT /** * [[Levels|Level]] of the identifier. This attribute is supposed to be defined on the prototype level only. */ @prototypeValue(Levels.DependsOnSelfKind) level : Levels /** * Whether this identifier is lazy (`true`) or strict (`false`). * * Lazy identifiers are calculated on-demand (when read from graph or used by another identifiers). * * Strict identifiers will be calculated on read or during the [[ChronoGraph.commit|commit]] call. */ lazy : boolean = false /** * Whether this identifier is sync (`true`) or generator-based (`false`). Default value is `true`. * This attribute is supposed to be defined on the prototype level only. */ @prototypeValue(true) sync : boolean // no cancels total : boolean = true // no "nested" writes pure : boolean = true quarkClass : QuarkConstructor proposedValueIsBuilt : boolean = false // no init value - only a type CalcContextT : any /** * The calculation function of the identifier. Its returning value has a generic type, that is converted to a specific type, * based on the generic attribute `ContextT`. * * This function will receive a single argument - current calculation context (effects handler). * * When using generators, there's no need to use this handler - one can "yield" the value directly, using the `yield` construct. * * Compare: * * class Author extends Entity.mix(Base) { * @field() * firstName : string * @field() * lastName : string * @field() * fullName : string * * @calculate('fullName') * * calculateFullName () : ChronoIterator<string> { * return (yield this.$.firstName) + ' ' + (yield this.$.lastName) * } * * @calculate('fullName') * calculateFullName (Y) : string { * return Y(this.$.firstName) + ' ' + Y(this.$.lastName) * } * } * * @param Y */ calculation (this : this[ 'CalcContextT' ], Y : CalculationContext<this[ 'YieldT' ]>) : Contexts<ValueT, this[ 'YieldT' ]>[ ContextT ] { throw new Error("Abstract method `calculation` called") } /** * The equality check of the identifier. By default is performed with `===`. * * @param v1 First value * @param v2 Second value */ equality (v1 : ValueT, v2 : ValueT) : boolean { return v1 === v2 } } //--------------------------------------------------------------------------------------------------------------------- /** * The generic "specific" identifier class (see [[Meta]] for "abstract" properties). This class is generic in the sense that it does not * specify the type of the calculation function - it can be either synchronous or generator-based. * * It is also low-level and generally not supposed to be used directly in the application. Instead, one should * declare identifiers as fields (decorated class properties) in the [[Replica|replica]]. */ export class Identifier<ValueT = any, ContextT extends Context = Context> extends Meta<ValueT, ContextT> { /** * The scope (`this` value) for the calculation function. */ context : this[ 'CalcContextT' ] = undefined newQuark (createdAt : Revision) : InstanceType<this[ 'quarkClass' ]> { // micro-optimization - we don't pass a config object to the `new` constructor // but instead assign directly to instance const newQuark = this.quarkClass.new() as InstanceType<this[ 'quarkClass' ]> newQuark.createdAt = createdAt newQuark.identifier = this newQuark.needToBuildProposedValue = this.proposedValueIsBuilt return newQuark } write (me : this, transaction : Transaction, quark : InstanceType<this[ 'quarkClass' ]>, proposedValue : ValueT, ...args : this[ 'ArgsT' ]) { quark = quark || transaction.getWriteTarget(me) quark.proposedValue = proposedValue quark.proposedArguments = args.length > 0 ? args : undefined } writeToTransaction (transaction : Transaction, proposedValue : ValueT, ...args : this[ 'ArgsT' ]) { transaction.write(this, proposedValue, ...args) } /** * Write a value to this identifier, in the context of `graph`. * * @param graph * @param proposedValue * @param args */ writeToGraph (graph : ChronoGraph, proposedValue : ValueT, ...args : this[ 'ArgsT' ]) { graph.write(this, proposedValue, ...args) } /** * Read the value of this identifier, in the context of `graph`, asynchronously * @param graph */ readFromGraphAsync (graph : ChronoGraph) : Promise<ValueT> { return graph.readAsync(this) } /** * Read the value of this identifier, in the context of `graph`, synchronously * @param graph */ readFromGraph (graph : ChronoGraph) : ValueT { return graph.read(this) } readFromTransaction (transaction : Transaction) : ValueT { return transaction.read(this) } readFromTransactionAsync (transaction : Transaction) : Promise<ValueT> { return transaction.readAsync(this) } // readFromGraphDirtySync (graph : CheckoutI) : ValueT { // return graph.readDirty(this) // } buildProposedValue (me : this, quark : InstanceType<this[ 'quarkClass' ]>, transaction : Transaction) : ValueT { return undefined } /** * Template method, which is called, when this identifier "enters" the graph. * * @param graph */ enterGraph (graph : ChronoGraph) { } /** * Template method, which is called, when this identifier "leaves" the graph. * * @param graph */ leaveGraph (graph : ChronoGraph) { } } /** * Constructor for the [[Identifier]] class. Used only for typization purposes, to be able to specify the generics arguments. */ export const IdentifierC = <ValueT, ContextT extends Context>(config : Partial<Identifier>) : Identifier<ValueT, ContextT> => Identifier.new(config) as Identifier<ValueT, ContextT> //@ts-ignore export const QuarkSync = Quark.mix(CalculationSync.mix(Map)) //@ts-ignore export const QuarkGen = Quark.mix(CalculationGen.mix(Map)) //--------------------------------------------------------------------------------------------------------------------- /** * Variable is a subclass of [[Identifier]], that does not perform any calculation and instead is always equal to a user-provided value. * It is a bit more light-weight */ export class Variable<ValueT = any> extends Identifier<ValueT, typeof ContextSync> { YieldT : never @prototypeValue(Levels.UserInput) level : Levels @prototypeValue(QuarkSync) quarkClass : QuarkConstructor calculation (this : this[ 'CalcContextT' ], YIELD : CalculationContext<this[ 'YieldT' ]>) : Contexts<ValueT, this[ 'YieldT' ]>[ typeof ContextSync ] { throw new Error("The 'calculation' method of the variables will never be called. Instead the value will be set directly to quark") } write (me : this, transaction : Transaction, quark : Quark, proposedValue : ValueT, ...args : this[ 'ArgsT' ]) { quark = quark || transaction.getWriteTarget(me) quark.value = proposedValue quark.proposedArguments = args.length > 0 ? args : undefined } } /** * Constructor for the [[Variable]] class. Used only for typization purposes. */ export function VariableC<ValueT> (...args) : Variable<ValueT> { return Variable.new(...args) as Variable<ValueT> } //--------------------------------------------------------------------------------------------------------------------- /** * Subclass of the [[Identifier]], representing synchronous computation. */ export class CalculatedValueSync<ValueT = any> extends Identifier<ValueT, typeof ContextSync> { @prototypeValue(QuarkSync) quarkClass : QuarkConstructor calculation (this : this[ 'CalcContextT' ], YIELD : CalculationContext<this[ 'YieldT' ]>) : Contexts<ValueT, this[ 'YieldT' ]>[ typeof ContextSync ] { return YIELD(ProposedOrPrevious) } } /** * Constructor for the [[CalculatedValueSync]] class. Used only for typization purposes. */ export function CalculatedValueSyncC<ValueT> (...args) : CalculatedValueSync<ValueT> { return CalculatedValueSync.new(...args) as CalculatedValueSync<ValueT> } //--------------------------------------------------------------------------------------------------------------------- /** * Subclass of the [[Identifier]], representing generator-based computation. */ export class CalculatedValueGen<ValueT = any> extends Identifier<ValueT, typeof ContextGen> { @prototypeValue(QuarkGen) quarkClass : QuarkConstructor * calculation (this : this[ 'CalcContextT' ], YIELD : CalculationContext<this[ 'YieldT' ]>) : Contexts<ValueT, this[ 'YieldT' ]>[ typeof ContextGen ] { return yield ProposedOrPrevious } } /** * Constructor for the [[CalculatedValueGen]] class. Used only for typization purposes. */ export function CalculatedValueGenC<ValueT> (...args) : CalculatedValueGen<ValueT> { return CalculatedValueGen.new(...args) as CalculatedValueGen<ValueT> } //--------------------------------------------------------------------------------------------------------------------- export const throwUnknownIdentifier = (identifier : Identifier) => { throw new Error(`Unknown identifier ${identifier}`) }
the_stack
export interface AccountAccountCounters { /** * New app requests number */ app_requests: number, /** * New events number */ events: number, /** * New faves number */ faves: number, /** * New friends requests number */ friends: number, /** * New friends suggestions number */ friends_suggestions: number, /** * New friends recommendations number */ friends_recommendations: number, /** * New gifts number */ gifts: number, /** * New groups number */ groups: number, /** * */ menu_discover_badge: number, /** * */ menu_clips_badge: number, /** * New messages number */ messages: number, /** * New memories number */ memories: number, /** * New notes number */ notes: number, /** * New notifications number */ notifications: number, /** * New photo tags number */ photos: number, /** * New sdk number */ sdk: number } export interface AccountInfo { /** * */ wishlists_ae_promo_banner_show: BaseBoolInt, /** * Two factor authentication is enabled */ twoFaRequired: BaseBoolInt, /** * Country code */ country: string, /** * Information whether HTTPS-only is enabled */ https_required: BaseBoolInt, /** * Information whether user has been processed intro */ intro: BaseBoolInt, /** * */ show_vk_apps_intro: boolean, /** * Ads slot id for MyTarget */ mini_apps_ads_slot_id: number, /** * */ qr_promotion: number, /** * */ link_redirects: any, /** * Language ID */ lang: number, /** * Information whether wall comments should be hidden */ no_wall_replies: BaseBoolInt, /** * Information whether only owners posts should be shown */ own_posts_default: BaseBoolInt, /** * */ subscriptions: number[] } export interface AccountNameRequest { /** * First name in request */ first_name: string, /** * Request ID needed to cancel the request */ id: number, /** * Last name in request */ last_name: string, /** * */ status: AccountNameRequestStatus, /** * Text to display to user */ lang: string, /** * href for link in lang field */ link_href: string, /** * label to display for link in lang field */ link_label: string } export type AccountNameRequestStatus = string export interface AccountOffer { /** * Offer description */ description: string, /** * Offer ID */ id: number, /** * URL of the preview image */ img: string, /** * Instruction how to process the offer */ instruction: string, /** * Instruction how to process the offer (HTML format) */ instruction_html: string, /** * Offer price */ price: number, /** * Offer short description */ short_description: string, /** * Offer tag */ tag: string, /** * Offer title */ title: string, /** * Currency amount */ currency_amount: number, /** * Link id */ link_id: number, /** * Link type */ link_type: string } export interface AccountPushConversations { /** * Items count */ count: number, /** * */ items: AccountPushConversationsItem[] } export interface AccountPushConversationsItem { /** * Time until that notifications are disabled in seconds */ disabled_until: number, /** * Peer ID */ peer_id: number, /** * Information whether the sound are enabled */ sound: BaseBoolInt } export interface AccountPushParams { /** * */ msg: AccountPushParamsMode[], /** * */ chat: AccountPushParamsMode[], /** * */ like: AccountPushParamsSettings[], /** * */ repost: AccountPushParamsSettings[], /** * */ comment: AccountPushParamsSettings[], /** * */ mention: AccountPushParamsSettings[], /** * */ reply: AccountPushParamsOnoff[], /** * */ new_post: AccountPushParamsOnoff[], /** * */ wall_post: AccountPushParamsOnoff[], /** * */ wall_publish: AccountPushParamsOnoff[], /** * */ friend: AccountPushParamsOnoff[], /** * */ friend_found: AccountPushParamsOnoff[], /** * */ friend_accepted: AccountPushParamsOnoff[], /** * */ group_invite: AccountPushParamsOnoff[], /** * */ group_accepted: AccountPushParamsOnoff[], /** * */ birthday: AccountPushParamsOnoff[], /** * */ event_soon: AccountPushParamsOnoff[], /** * */ app_request: AccountPushParamsOnoff[], /** * */ sdk_open: AccountPushParamsOnoff[] } export type AccountPushParamsMode = string export type AccountPushParamsOnoff = string export type AccountPushParamsSettings = string export interface AccountPushSettings { /** * Information whether notifications are disabled */ disabled: BaseBoolInt, /** * Time until that notifications are disabled in Unixtime */ disabled_until: number, /** * */ settings: AccountPushParams, /** * */ conversations: AccountPushConversations } export interface AccountUserSettings { /** * Returns if a profile is deleted or blocked */ deactivated: string, /** * User first name */ first_name: string, /** * Returns if a profile is hidden. */ hidden: number, /** * User ID */ id: number, /** * User last name */ last_name: string, /** * */ can_access_closed: boolean, /** * */ is_closed: boolean, /** * */ connections: UsersUserConnections, /** * User's date of birth */ bdate: string, /** * Information whether user's birthdate are hidden */ bdate_visibility: number, /** * */ city: BaseCity, /** * */ country: BaseCountry, /** * User's hometown */ home_town: string, /** * User maiden name */ maiden_name: string, /** * */ name_request: AccountNameRequest, /** * */ personal: UsersPersonal, /** * User phone number with some hidden digits */ phone: string, /** * User relationship status */ relation: UsersUserRelation, /** * */ relation_partner: UsersUserMin, /** * Information whether relation status is pending */ relation_pending: BaseBoolInt, /** * */ relation_requests: UsersUserMin[], /** * Domain name of the user's page */ screen_name: string, /** * User sex */ sex: BaseSex, /** * User status */ status: string, /** * */ status_audio: AudioAudio, /** * */ interests: AccountUserSettingsInterests, /** * */ languages: string[], /** * URL of square photo of the user with 200 pixels in width */ photo_200: string, /** * flag about service account */ is_service_account: boolean } export interface AccountUserSettingsInterest { /** * */ title: string, /** * */ value: string } export interface AccountUserSettingsInterests { /** * */ activities: AccountUserSettingsInterest, /** * */ interests: AccountUserSettingsInterest, /** * */ music: AccountUserSettingsInterest, /** * */ tv: AccountUserSettingsInterest, /** * */ movies: AccountUserSettingsInterest, /** * */ books: AccountUserSettingsInterest, /** * */ games: AccountUserSettingsInterest, /** * */ quotes: AccountUserSettingsInterest, /** * */ about: AccountUserSettingsInterest } export type AddressesFields = string export type AdsAccessRole = string export type AdsAccessRolePublic = string export interface AdsAccesses { /** * Client ID */ client_id: string, /** * */ role: AdsAccessRole } export interface AdsAccount { /** * */ access_role: AdsAccessRole, /** * Account ID */ account_id: number, /** * Information whether account is active */ account_status: BaseBoolInt, /** * */ account_type: AdsAccountType, /** * Account name */ account_name: string, /** * Can user view account budget */ can_view_budget: boolean } export type AdsAccountType = string export interface AdsAd { /** * Ad format */ ad_format: number, /** * Ad platform */ ad_platform: any, /** * Total limit */ all_limit: number, /** * */ approved: AdsAdApproved, /** * Campaign ID */ campaign_id: number, /** * Category ID */ category1_id: number, /** * Additional category ID */ category2_id: number, /** * */ cost_type: AdsAdCostType, /** * Cost of a click, kopecks */ cpc: number, /** * Cost of 1000 impressions, kopecks */ cpm: number, /** * Cost of an action, kopecks */ cpa: number, /** * Cost of 1000 impressions optimized, kopecks */ ocpm: number, /** * Max cost of target actions for autobidding, kopecks */ autobidding_max_cost: number, /** * Information whether disclaimer is enabled */ disclaimer_medical: BaseBoolInt, /** * Information whether disclaimer is enabled */ disclaimer_specialist: BaseBoolInt, /** * Information whether disclaimer is enabled */ disclaimer_supplements: BaseBoolInt, /** * Ad ID */ id: number, /** * Impressions limit */ impressions_limit: number, /** * Information whether impressions are limited */ impressions_limited: BaseBoolInt, /** * Ad title */ name: string, /** * */ status: AdsAdStatus, /** * Information whether the ad is a video */ video: BaseBoolInt } export type AdsAdApproved = number export type AdsAdCostType = number export interface AdsAdLayout { /** * Ad format */ ad_format: number, /** * Campaign ID */ campaign_id: number, /** * */ cost_type: AdsAdCostType, /** * Ad description */ description: string, /** * Ad ID */ id: number, /** * Image URL */ image_src: string, /** * URL of the preview image in double size */ image_src_2x: string, /** * Domain of advertised object */ link_domain: string, /** * URL of advertised object */ link_url: string, /** * link to preview an ad as it is shown on the website */ preview_link: any, /** * Ad title */ title: string, /** * Information whether the ad is a video */ video: BaseBoolInt } export type AdsAdStatus = number export interface AdsCampaign { /** * Campaign's total limit, rubles */ all_limit: string, /** * Campaign's day limit, rubles */ day_limit: string, /** * Campaign ID */ id: number, /** * Campaign title */ name: string, /** * Campaign start time, as Unixtime */ start_time: number, /** * */ status: AdsCampaignStatus, /** * Campaign stop time, as Unixtime */ stop_time: number, /** * */ type: AdsCampaignType } export type AdsCampaignStatus = number export type AdsCampaignType = string export interface AdsCategory { /** * Category ID */ id: number, /** * Category name */ name: string, /** * */ subcategories: BaseObjectWithName[] } export interface AdsClient { /** * Client's total limit, rubles */ all_limit: string, /** * Client's day limit, rubles */ day_limit: string, /** * Client ID */ id: number, /** * Client name */ name: string } export interface AdsCriteria { /** * Age from */ age_from: number, /** * Age to */ age_to: number, /** * Apps IDs */ apps: string, /** * Apps IDs to except */ apps_not: string, /** * Days to birthday */ birthday: number, /** * Cities IDs */ cities: string, /** * Cities IDs to except */ cities_not: string, /** * Country ID */ country: number, /** * Districts IDs */ districts: string, /** * Communities IDs */ groups: string, /** * Interests categories IDs */ interest_categories: string, /** * Interests */ interests: string, /** * Information whether the user has proceeded VK payments before */ paying: BaseBoolInt, /** * Positions IDs */ positions: string, /** * Religions IDs */ religions: string, /** * Retargeting groups IDs */ retargeting_groups: string, /** * Retargeting groups IDs to except */ retargeting_groups_not: string, /** * School graduation year from */ school_from: number, /** * School graduation year to */ school_to: number, /** * Schools IDs */ schools: string, /** * */ sex: AdsCriteriaSex, /** * Stations IDs */ stations: string, /** * Relationship statuses */ statuses: string, /** * Streets IDs */ streets: string, /** * Travellers only */ travellers: BasePropertyExists, /** * University graduation year from */ uni_from: number, /** * University graduation year to */ uni_to: number, /** * Browsers */ user_browsers: string, /** * Devices */ user_devices: string, /** * Operating systems */ user_os: string } export type AdsCriteriaSex = number export interface AdsDemoStats { /** * Object ID */ id: number, /** * */ stats: AdsDemostatsFormat, /** * */ type: AdsObjectType } export interface AdsDemostatsFormat { /** * */ age: AdsStatsAge[], /** * */ cities: AdsStatsCities[], /** * Day as YYYY-MM-DD */ day: string, /** * Month as YYYY-MM */ month: string, /** * 1 if period=overall */ overall: number, /** * */ sex: AdsStatsSex[], /** * */ sex_age: AdsStatsSexAge[] } export interface AdsFloodStats { /** * Requests left */ left: number, /** * Time to refresh in seconds */ refresh: number } export interface AdsLinkStatus { /** * Reject reason */ description: string, /** * URL */ redirect_url: string, /** * Link status */ status: string } export interface AdsLookalikeRequest { /** * Lookalike request ID */ id: number, /** * Lookalike request create time, as Unixtime */ create_time: number, /** * Lookalike request update time, as Unixtime */ update_time: number, /** * Time by which lookalike request would be deleted, as Unixtime */ scheduled_delete_time: number, /** * Lookalike request status */ status: string, /** * Lookalike request source type */ source_type: string, /** * Retargeting group id, which was used as lookalike seed */ source_retargeting_group_id: number, /** * Lookalike request seed name (retargeting group name) */ source_name: string, /** * Lookalike request seed audience size */ audience_count: number, /** * */ save_audience_levels: AdsLookalikeRequestSaveAudienceLevel[] } export interface AdsLookalikeRequestSaveAudienceLevel { /** * Save audience level id, which is used in save audience queries */ level: number, /** * Saved audience audience size for according level */ audience_count: number } export interface AdsMusician { /** * Targeting music artist ID */ id: number, /** * Music artist name */ name: string } export type AdsObjectType = string export interface AdsParagraphs { /** * Rules paragraph */ paragraph: string } export interface AdsPromotedPostReach { /** * Hides amount */ hide: number, /** * Object ID from 'ids' parameter */ id: number, /** * Community joins */ join_group: number, /** * Link clicks */ links: number, /** * Subscribers reach */ reach_subscribers: number, /** * Total reach */ reach_total: number, /** * Reports amount */ report: number, /** * Community clicks */ to_group: number, /** * 'Unsubscribe' events amount */ unsubscribe: number, /** * Video views for 100 percent */ video_views_100p: number, /** * Video views for 25 percent */ video_views_25p: number, /** * Video views for 3 seconds */ video_views_3s: number, /** * Video views for 50 percent */ video_views_50p: number, /** * Video views for 75 percent */ video_views_75p: number, /** * Video starts */ video_views_start: number } export interface AdsRejectReason { /** * Comment text */ comment: string, /** * */ rules: AdsRules[] } export interface AdsRules { /** * */ paragraphs: AdsParagraphs[], /** * Comment */ title: string } export interface AdsStats { /** * Object ID */ id: number, /** * */ stats: AdsStatsFormat, /** * */ type: AdsObjectType, /** * */ views_times: AdsStatsViewsTimes } export interface AdsStatsAge { /** * Clicks rate */ clicks_rate: number, /** * Impressions rate */ impressions_rate: number, /** * Age interval */ value: string } export interface AdsStatsCities { /** * Clicks rate */ clicks_rate: number, /** * Impressions rate */ impressions_rate: number, /** * City name */ name: string, /** * City ID */ value: number } export interface AdsStatsFormat { /** * Clicks number */ clicks: number, /** * Day as YYYY-MM-DD */ day: string, /** * Impressions number */ impressions: number, /** * Events number */ join_rate: number, /** * Month as YYYY-MM */ month: string, /** * 1 if period=overall */ overall: number, /** * Reach */ reach: number, /** * Spent funds */ spent: number, /** * Clickthoughs to the advertised site */ video_clicks_site: number, /** * Video views number */ video_views: number, /** * Video views (full video) */ video_views_full: number, /** * Video views (half of video) */ video_views_half: number } export interface AdsStatsSex { /** * Clicks rate */ clicks_rate: number, /** * Impressions rate */ impressions_rate: number, /** * */ value: AdsStatsSexValue } export interface AdsStatsSexAge { /** * Clicks rate */ clicks_rate: number, /** * Impressions rate */ impressions_rate: number, /** * Sex and age interval */ value: string } export type AdsStatsSexValue = string export interface AdsStatsViewsTimes { /** * */ views_ads_times_1: number, /** * */ views_ads_times_2: number, /** * */ views_ads_times_3: number, /** * */ views_ads_times_4: number, /** * */ views_ads_times_5: string, /** * */ views_ads_times_6: number, /** * */ views_ads_times_7: number, /** * */ views_ads_times_8: number, /** * */ views_ads_times_9: number, /** * */ views_ads_times_10: number, /** * */ views_ads_times_11_plus: number } export interface AdsTargSettings { /** * Ad ID */ id: number, /** * Campaign ID */ campaign_id: number, /** * Age from */ age_from: number, /** * Age to */ age_to: number, /** * Apps IDs */ apps: string, /** * Apps IDs to except */ apps_not: string, /** * Days to birthday */ birthday: number, /** * Cities IDs */ cities: string, /** * Cities IDs to except */ cities_not: string, /** * Country ID */ country: number, /** * Districts IDs */ districts: string, /** * Communities IDs */ groups: string, /** * Interests categories IDs */ interest_categories: string, /** * Interests */ interests: string, /** * Information whether the user has proceeded VK payments before */ paying: BaseBoolInt, /** * Positions IDs */ positions: string, /** * Religions IDs */ religions: string, /** * Retargeting groups IDs */ retargeting_groups: string, /** * Retargeting groups IDs to except */ retargeting_groups_not: string, /** * School graduation year from */ school_from: number, /** * School graduation year to */ school_to: number, /** * Schools IDs */ schools: string, /** * */ sex: AdsCriteriaSex, /** * Stations IDs */ stations: string, /** * Relationship statuses */ statuses: string, /** * Streets IDs */ streets: string, /** * Travellers only */ travellers: BasePropertyExists, /** * University graduation year from */ uni_from: number, /** * University graduation year to */ uni_to: number, /** * Browsers */ user_browsers: string, /** * Devices */ user_devices: string, /** * Operating systems */ user_os: string } export interface AdsTargStats { /** * Audience */ audience_count: number, /** * Recommended CPC value for 50% reach (old format) */ recommended_cpc: number, /** * Recommended CPM value for 50% reach (old format) */ recommended_cpm: number, /** * Recommended CPC value for 50% reach */ recommended_cpc_50: number, /** * Recommended CPM value for 50% reach */ recommended_cpm_50: number, /** * Recommended CPC value for 70% reach */ recommended_cpc_70: number, /** * Recommended CPM value for 70% reach */ recommended_cpm_70: number, /** * Recommended CPC value for 90% reach */ recommended_cpc_90: number, /** * Recommended CPM value for 90% reach */ recommended_cpm_90: number } export interface AdsTargSuggestions { /** * Object ID */ id: number, /** * Object name */ name: string } export interface AdsTargSuggestionsCities { /** * Object ID */ id: number, /** * Object name */ name: string, /** * Parent object */ parent: string } export interface AdsTargSuggestionsRegions { /** * Object ID */ id: number, /** * Object name */ name: string, /** * Object type */ type: string } export interface AdsTargSuggestionsSchools { /** * Full school title */ desc: string, /** * School ID */ id: number, /** * School title */ name: string, /** * City name */ parent: string, /** * */ type: AdsTargSuggestionsSchoolsType } export type AdsTargSuggestionsSchoolsType = string export interface AdsTargetGroup { /** * Audience */ audience_count: number, /** * Site domain */ domain: string, /** * Group ID */ id: number, /** * Number of days for user to be in group */ lifetime: number, /** * Group name */ name: string, /** * Pixel code */ pixel: string } export interface AdsUpdateOfficeUsersResult { /** * */ user_id: number, /** * */ is_success: boolean, /** * */ error: BaseError } export interface AdsUserSpecification { /** * */ user_id: number, /** * */ role: AdsAccessRolePublic, /** * */ grant_access_to_all_clients: boolean, /** * */ client_ids: number[], /** * */ view_budget: boolean } export interface AdsUserSpecificationCutted { /** * */ user_id: number, /** * */ role: AdsAccessRolePublic, /** * */ client_id: number, /** * */ view_budget: boolean } export interface AdsUsers { /** * */ accesses: AdsAccesses[], /** * User ID */ user_id: number } export interface AdswebGetAdCategoriesResponseCategoriesCategory { /** * */ id: number, /** * */ name: string } export interface AdswebGetAdUnitsResponseAdUnitsAdUnit { /** * */ id: number, /** * */ site_id: number, /** * */ name: string } export interface AdswebGetFraudHistoryResponseEntriesEntry { /** * */ site_id: number, /** * */ day: string } export interface AdswebGetSitesResponseSitesSite { /** * */ id: number, /** * */ status_user: string, /** * */ status_moder: string, /** * */ domains: string } export interface AdswebGetStatisticsResponseItemsItem { /** * */ site_id: number, /** * */ ad_unit_id: number, /** * */ overall_count: number, /** * */ months_count: number, /** * */ month_min: string, /** * */ month_max: string, /** * */ days_count: number, /** * */ day_min: string, /** * */ day_max: string, /** * */ hours_count: number, /** * */ hour_min: string, /** * */ hour_max: string } export interface AppWidgetsPhoto { /** * Image ID */ id: string, /** * */ images: BaseImage[] } export interface AppWidgetsPhotos { /** * */ count: number, /** * */ items: AppWidgetsPhoto[] } export interface AppsApp { /** * */ type: AppsAppType, /** * Application ID */ id: number, /** * Application title */ title: string, /** * Application author's ID */ author_owner_id: number, /** * Is application installed */ is_installed: boolean, /** * URL of the app icon with 139 px in width */ icon_139: string, /** * URL of the app icon with 150 px in width */ icon_150: string, /** * URL of the app icon with 278 px in width */ icon_278: string, /** * URL of the app icon with 576 px in width */ icon_576: string, /** * Hex color code without hash sign */ background_loader_color: string, /** * SVG data */ loader_icon: string, /** * URL of the app icon with 75 px in width */ icon_75: string, /** * Application author's URL */ author_url: string, /** * URL of the app banner with 1120 px in width */ banner_1120: string, /** * URL of the app banner with 560 px in width */ banner_560: string, /** * URL of the app icon with 16 px in width */ icon_16: string, /** * Is new flag */ is_new: BaseBoolInt, /** * Is push enabled */ push_enabled: BaseBoolInt, /** * Screen orientation */ screen_orientation: number, /** * */ friends: number[], /** * Catalog position */ catalog_position: number, /** * Application description */ description: string, /** * Genre name */ genre: string, /** * Genre ID */ genre_id: number, /** * Information whether the application is multilanguage */ international: boolean, /** * Information whether application is in mobile catalog */ is_in_catalog: number, /** * */ leaderboard_type: AppsAppLeaderboardType, /** * Members number */ members_count: number, /** * Application ID in store */ platform_id: string, /** * Date when the application has been published in Unixtime */ published_date: number, /** * Screen name */ screen_name: string, /** * Application section name */ section: string } export type AppsAppLeaderboardType = number export interface AppsAppMin { /** * */ type: AppsAppType, /** * Application ID */ id: number, /** * Application title */ title: string, /** * Application author's ID */ author_owner_id: number, /** * Is application installed */ is_installed: boolean, /** * URL of the app icon with 139 px in width */ icon_139: string, /** * URL of the app icon with 150 px in width */ icon_150: string, /** * URL of the app icon with 278 px in width */ icon_278: string, /** * URL of the app icon with 576 px in width */ icon_576: string, /** * Hex color code without hash sign */ background_loader_color: string, /** * SVG data */ loader_icon: string, /** * URL of the app icon with 75 px in width */ icon_75: string } export type AppsAppType = string export interface AppsLeaderboard { /** * Level */ level: number, /** * Points number */ points: number, /** * Score number */ score: number, /** * User ID */ user_id: number } export interface AppsScope { /** * Scope name */ name: string, /** * Scope title */ title: string } export interface AudioAudio { /** * Artist name */ artist: string, /** * Audio ID */ id: number, /** * Title */ title: string, /** * URL of mp3 file */ url: string, /** * Duration in seconds */ duration: number, /** * Date when uploaded */ date: number, /** * Album ID */ album_id: number, /** * Genre ID */ genre_id: number, /** * Performer name */ performer: string } export type BaseBoolInt = number export interface BaseCity { /** * City ID */ id: number, /** * City title */ title: string } export interface BaseCommentsInfo { /** * Information whether current user can comment the post */ can_post: BaseBoolInt, /** * Comments number */ count: number, /** * Information whether groups can comment the post */ groups_can_post: boolean, /** * */ donut: WallWallpostCommentsDonut } export interface BaseCountry { /** * Country ID */ id: number, /** * Country title */ title: string } export interface BaseCropPhoto { /** * */ photo: PhotosPhoto, /** * */ crop: BaseCropPhotoCrop, /** * */ rect: BaseCropPhotoRect } export interface BaseCropPhotoCrop { /** * Coordinate X of the left upper corner */ x: number, /** * Coordinate Y of the left upper corner */ y: number, /** * Coordinate X of the right lower corner */ x2: number, /** * Coordinate Y of the right lower corner */ y2: number } export interface BaseCropPhotoRect { /** * Coordinate X of the left upper corner */ x: number, /** * Coordinate Y of the left upper corner */ y: number, /** * Coordinate X of the right lower corner */ x2: number, /** * Coordinate Y of the right lower corner */ y2: number } export interface BaseError { /** * Error code */ error_code: number, /** * Error subcode */ error_subcode: number, /** * Error message */ error_msg: string, /** * Localized error message */ error_text: string, /** * */ request_params: BaseRequestParam[] } export interface BaseGeo { /** * */ coordinates: BaseGeoCoordinates, /** * */ place: BasePlace, /** * Information whether a map is showed */ showmap: number, /** * Place type */ type: string } export interface BaseGeoCoordinates { /** * */ latitude: number, /** * */ longitude: number } export interface BaseGradientPoint { /** * Hex color code without # */ color: string, /** * Point position */ position: number } export interface BaseImage { /** * */ id: string, /** * Image height */ height: number, /** * Image url */ url: string, /** * Image width */ width: number } export interface BaseLikes { /** * Likes number */ count: number, /** * Information whether current user likes the photo */ user_likes: BaseBoolInt } export interface BaseLikesInfo { /** * Information whether current user can like the post */ can_like: BaseBoolInt, /** * Information whether current user can repost */ can_publish: BaseBoolInt, /** * Likes number */ count: number, /** * Information whether current uer has liked the post */ user_likes: number } export interface BaseLink { /** * */ application: BaseLinkApplication, /** * */ button: BaseLinkButton, /** * Link caption */ caption: string, /** * Link description */ description: string, /** * Link ID */ id: string, /** * */ is_favorite: boolean, /** * */ photo: PhotosPhoto, /** * String ID of the page with article preview */ preview_page: string, /** * URL of the page with article preview */ preview_url: string, /** * */ product: BaseLinkProduct, /** * */ rating: BaseLinkRating, /** * Link title */ title: string, /** * Link URL */ url: string, /** * */ target_object: LinkTargetObject, /** * Information whether the current link is external */ is_external: boolean, /** * Video from link */ video: VideoVideo } export interface BaseLinkApplication { /** * Application Id */ app_id: number, /** * */ store: BaseLinkApplicationStore } export interface BaseLinkApplicationStore { /** * Store Id */ id: number, /** * Store name */ name: string } export interface BaseLinkButton { /** * Button action */ action: BaseLinkButtonAction, /** * Button title */ title: string, /** * Target block id */ block_id: string, /** * Target section id */ section_id: string, /** * curator id */ curator_id: number, /** * Owner id */ owner_id: number, /** * Button icon name, e.g. 'phone' or 'gift' */ icon: string, /** * */ style: BaseLinkButtonStyle } export interface BaseLinkButtonAction { /** * */ type: BaseLinkButtonActionType, /** * Action URL */ url: string, /** * */ consume_reason: string } export type BaseLinkButtonActionType = string export type BaseLinkButtonStyle = string export interface BaseLinkProduct { /** * */ price: MarketPrice, /** * */ merchant: string, /** * */ orders_count: number } export type BaseLinkProductStatus = string export interface BaseLinkRating { /** * Count of reviews */ reviews_count: number, /** * Count of stars */ stars: number } export interface BaseMessageError { /** * Error code */ code: number, /** * Error message */ description: string } export interface BaseObject { /** * Object ID */ id: number, /** * Object title */ title: string } export interface BaseObjectCount { /** * Items count */ count: number } export interface BaseObjectWithName { /** * Object ID */ id: number, /** * Object name */ name: string } export interface BasePlace { /** * Place address */ address: string, /** * Checkins number */ checkins: number, /** * City name */ city: string, /** * Country name */ country: string, /** * Date of the place creation in Unixtime */ created: number, /** * URL of the place's icon */ icon: string, /** * Place ID */ id: number, /** * Place latitude */ latitude: number, /** * Place longitude */ longitude: number, /** * Place title */ title: string, /** * Place type */ type: string } export type BasePropertyExists = number export interface BaseRepostsInfo { /** * Total reposts counter. Sum of wall and mail reposts counters */ count: number, /** * Wall reposts counter */ wall_count: number, /** * Mail reposts counter */ mail_count: number, /** * Information whether current user has reposted the post */ user_reposted: number } export interface BaseRequestParam { /** * Parameter name */ key: string, /** * Parameter value */ value: string } export type BaseSex = number export interface BaseSticker { /** * Sticker ID */ sticker_id: number, /** * Pack ID */ product_id: number, /** * */ images: BaseImage[], /** * */ images_with_background: BaseImage[], /** * URL of sticker animation script */ animation_url: string, /** * Array of sticker animation script objects */ animations: BaseStickerAnimation[], /** * Information whether the sticker is allowed */ is_allowed: boolean } export interface BaseStickerAnimation { /** * Type of animation script */ type: string, /** * URL of animation script */ url: string } export interface BaseUploadServer { /** * Upload URL */ upload_url: string } export type BaseUserGroupFields = string export interface BaseUserId { /** * User ID */ user_id: number } export type BoardDefaultOrder = number export interface BoardTopic { /** * Comments number */ comments: number, /** * Date when the topic has been created in Unixtime */ created: number, /** * Creator ID */ created_by: number, /** * Topic ID */ id: number, /** * Information whether the topic is closed */ is_closed: BaseBoolInt, /** * Information whether the topic is fixed */ is_fixed: BaseBoolInt, /** * Topic title */ title: string, /** * Date when the topic has been updated in Unixtime */ updated: number, /** * ID of user who updated the topic */ updated_by: number } export interface BoardTopicComment { /** * */ attachments: WallCommentAttachment[], /** * Date when the comment has been added in Unixtime */ date: number, /** * Author ID */ from_id: number, /** * Comment ID */ id: number, /** * Real position of the comment */ real_offset: number, /** * Comment text */ text: string, /** * Information whether current user can edit the comment */ can_edit: BaseBoolInt, /** * */ likes: BaseLikesInfo } export interface BoardTopicPoll { /** * Poll owner's ID */ owner_id: number, /** * Poll ID */ poll_id: number, /** * Date when poll has been created in Unixtime */ created: number, /** * Information whether the poll is closed */ is_closed: BaseBoolInt, /** * Poll question */ question: string, /** * Votes number */ votes: number, /** * Current user's answer ID */ answer_id: number, /** * */ answers: PollsAnswer[] } export interface CallbackBoardPostDelete { /** * */ topic_owner_id: number, /** * */ topic_id: number, /** * */ id: number } export interface CallbackConfirmationMessage { /** * */ type: CallbackMessageType, /** * */ group_id: number, /** * */ secret: string } export interface CallbackDonutMoneyWithdraw { /** * */ amount: number, /** * */ amount_without_fee: number } export interface CallbackDonutMoneyWithdrawError { /** * */ reason: string } export interface CallbackDonutSubscriptionCancelled { /** * */ user_id: number } export interface CallbackDonutSubscriptionCreate { /** * */ user_id: number, /** * */ amount: number, /** * */ amount_without_fee: number } export interface CallbackDonutSubscriptionExpired { /** * */ user_id: number } export interface CallbackDonutSubscriptionPriceChanged { /** * */ user_id: number, /** * */ amount_old: number, /** * */ amount_new: number, /** * */ amount_diff: number, /** * */ amount_diff_without_fee: number } export interface CallbackDonutSubscriptionProlonged { /** * */ user_id: number, /** * */ amount: number, /** * */ amount_without_fee: number } export interface CallbackGroupChangePhoto { /** * */ user_id: number, /** * */ photo: PhotosPhoto } export interface CallbackGroupChangeSettings { /** * */ user_id: number, /** * */ self: BaseBoolInt } export interface CallbackGroupJoin { /** * */ user_id: number, /** * */ join_type: CallbackGroupJoinType } export type CallbackGroupJoinType = string export interface CallbackGroupLeave { /** * */ user_id: number, /** * */ self: BaseBoolInt } export type CallbackGroupMarket = number export type CallbackGroupOfficerRole = number export interface CallbackGroupOfficersEdit { /** * */ admin_id: number, /** * */ user_id: number, /** * */ level_old: CallbackGroupOfficerRole, /** * */ level_new: CallbackGroupOfficerRole } export interface CallbackGroupSettingsChanges { /** * */ title: string, /** * */ description: string, /** * */ access: GroupsGroupIsClosed, /** * */ screen_name: string, /** * */ public_category: number, /** * */ public_subcategory: number, /** * */ age_limits: GroupsGroupFullAgeLimits, /** * */ website: string, /** * */ enable_status_default: GroupsGroupWall, /** * */ enable_audio: GroupsGroupAudio, /** * */ enable_video: GroupsGroupVideo, /** * */ enable_photo: GroupsGroupPhotos, /** * */ enable_market: CallbackGroupMarket } export interface CallbackLikeAddRemove { /** * */ liker_id: number, /** * */ object_type: string, /** * */ object_owner_id: number, /** * */ object_id: number, /** * */ post_id: number, /** * */ thread_reply_id: number } export interface CallbackMarketComment { /** * */ id: number, /** * */ from_id: number, /** * */ date: number, /** * */ text: string, /** * */ market_owner_od: number, /** * */ photo_id: number } export interface CallbackMarketCommentDelete { /** * */ owner_id: number, /** * */ id: number, /** * */ user_id: number, /** * */ item_id: number } export interface CallbackMessageAllow { /** * */ user_id: number, /** * */ key: string } export type CallbackMessageBase = any export interface CallbackMessageDeny { /** * */ user_id: number } export type CallbackMessageType = string export interface CallbackPhotoComment { /** * */ id: number, /** * */ from_id: number, /** * */ date: number, /** * */ text: string, /** * */ photo_owner_od: number } export interface CallbackPhotoCommentDelete { /** * */ id: number, /** * */ owner_id: number, /** * */ user_id: number, /** * */ photo_id: number } export interface CallbackPollVoteNew { /** * */ owner_id: number, /** * */ poll_id: number, /** * */ option_id: number, /** * */ user_id: number } export interface CallbackQrScan { /** * */ user_id: number, /** * */ data: string, /** * */ type: string, /** * */ subtype: string, /** * */ reread: boolean } export interface CallbackUserBlock { /** * */ admin_id: number, /** * */ user_id: number, /** * */ unblock_date: number, /** * */ reason: number, /** * */ comment: string } export interface CallbackUserUnblock { /** * */ admin_id: number, /** * */ user_id: number, /** * */ by_end_date: number } export interface CallbackVideoComment { /** * */ id: number, /** * */ from_id: number, /** * */ date: number, /** * */ text: string, /** * */ video_owner_od: number } export interface CallbackVideoCommentDelete { /** * */ id: number, /** * */ owner_id: number, /** * */ user_id: number, /** * */ video_id: number } export interface CallbackWallCommentDelete { /** * */ owner_id: number, /** * */ id: number, /** * */ user_id: number, /** * */ post_id: number } export interface CallsCall { /** * Call duration */ duration: number, /** * Caller initiator */ initiator_id: number, /** * Caller receiver */ receiver_id: number, /** * */ state: CallsEndState, /** * Timestamp for call */ time: number, /** * Was this call initiated as video call */ video: boolean } export type CallsEndState = string export interface CallsParticipants { /** * */ list: number[], /** * Participants count */ count: number } export interface CommentThread { /** * Information whether current user can comment the post */ can_post: boolean, /** * Comments number */ count: number, /** * Information whether groups can comment the post */ groups_can_post: boolean, /** * */ items: WallWallComment[], /** * Information whether recommended to display reply button */ show_reply_button: boolean } export interface DatabaseCity { /** * Object ID */ id: number, /** * Object title */ title: string, /** * Area title */ area: string, /** * Region title */ region: string, /** * Information whether the city is included in important cities list */ important: BaseBoolInt } export interface DatabaseFaculty { /** * Faculty ID */ id: number, /** * Faculty title */ title: string } export interface DatabaseRegion { /** * Region ID */ id: number, /** * Region title */ title: string } export interface DatabaseSchool { /** * School ID */ id: number, /** * School title */ title: string } export interface DatabaseStation { /** * City ID */ city_id: number, /** * Hex color code without # */ color: string, /** * Station ID */ id: number, /** * Station name */ name: string } export interface DatabaseUniversity { /** * University ID */ id: number, /** * University title */ title: string } export interface DocsDoc { /** * Document ID */ id: number, /** * Document owner ID */ owner_id: number, /** * Document title */ title: string, /** * File size in bites */ size: number, /** * File extension */ ext: string, /** * File URL */ url: string, /** * Date when file has been uploaded in Unixtime */ date: number, /** * Document type */ type: number, /** * */ preview: DocsDocPreview, /** * */ is_licensed: BaseBoolInt, /** * Access key for the document */ access_key: string, /** * Document tags */ tags: string[] } export type DocsDocAttachmentType = string export interface DocsDocPreview { /** * */ audio_msg: DocsDocPreviewAudioMsg, /** * */ graffiti: DocsDocPreviewGraffiti, /** * */ photo: DocsDocPreviewPhoto, /** * */ video: DocsDocPreviewVideo } export interface DocsDocPreviewAudioMsg { /** * Audio message duration in seconds */ duration: number, /** * MP3 file URL */ link_mp3: string, /** * OGG file URL */ link_ogg: string, /** * */ waveform: number[] } export interface DocsDocPreviewGraffiti { /** * Graffiti file URL */ src: string, /** * Graffiti width */ width: number, /** * Graffiti height */ height: number } export interface DocsDocPreviewPhoto { /** * */ sizes: DocsDocPreviewPhotoSizes[] } export interface DocsDocPreviewPhotoSizes { /** * URL of the image */ src: string, /** * Width in px */ width: number, /** * Height in px */ height: number, /** * */ type: PhotosPhotoSizesType } export interface DocsDocPreviewVideo { /** * Video URL */ src: string, /** * Video's width in pixels */ width: number, /** * Video's height in pixels */ height: number, /** * Video file size in bites */ file_size: number } export interface DocsDocTypes { /** * Doc type ID */ id: number, /** * Doc type title */ name: string, /** * Number of docs */ count: number } export interface DocsDocUploadResponse { /** * Uploaded file data */ file: string } export interface DonutDonatorSubscriptionInfo { /** * */ owner_id: number, /** * */ next_payment_date: number, /** * */ amount: number, /** * */ status: string } export interface EventsEventAttach { /** * address of event */ address: string, /** * text of attach */ button_text: string, /** * array of friends ids */ friends: number[], /** * event ID */ id: number, /** * is favorite */ is_favorite: boolean, /** * Current user's member status */ member_status: GroupsGroupFullMemberStatus, /** * text of attach */ text: string, /** * event start time */ time: number } export interface FaveBookmark { /** * Timestamp, when this item was bookmarked */ added_date: number, /** * */ link: BaseLink, /** * */ post: WallWallpostFull, /** * */ product: MarketMarketItem, /** * Has user seen this item */ seen: boolean, /** * */ tags: FaveTag[], /** * Item type */ type: FaveBookmarkType, /** * */ video: VideoVideo } export type FaveBookmarkType = string export interface FavePage { /** * Some info about user or group */ description: string, /** * */ group: GroupsGroupFull, /** * */ tags: FaveTag[], /** * Item type */ type: FavePageType, /** * Timestamp, when this page was bookmarked */ updated_date: number, /** * */ user: UsersUserFull } export type FavePageType = string export interface FaveTag { /** * Tag id */ id: number, /** * Tag name */ name: string } export interface FriendsFriendExtendedStatus { /** * */ friend_status: FriendsFriendStatusStatus, /** * MD5 hash for the result validation */ sign: string, /** * User ID */ user_id: number, /** * Is friend request from other user unread */ is_request_unread: boolean } export interface FriendsFriendStatus { /** * */ friend_status: FriendsFriendStatusStatus, /** * MD5 hash for the result validation */ sign: string, /** * User ID */ user_id: number } export type FriendsFriendStatusStatus = number export interface FriendsFriendsList { /** * List ID */ id: number, /** * List title */ name: string } export interface FriendsMutualFriend { /** * Total mutual friends number */ common_count: number, /** * */ common_friends: number[], /** * User ID */ id: number } export interface FriendsRequests { /** * ID of the user by whom friend has been suggested */ from: string, /** * */ mutual: FriendsRequestsMutual, /** * User ID */ user_id: number } export interface FriendsRequestsMutual { /** * Total mutual friends number */ count: number, /** * */ users: number[] } export interface FriendsRequestsXtrMessage { /** * ID of the user by whom friend has been suggested */ from: string, /** * Message sent with a request */ message: string, /** * */ mutual: FriendsRequestsMutual, /** * User ID */ user_id: number } export interface FriendsUserXtrLists { /** * Returns if a profile is deleted or blocked */ deactivated: string, /** * User first name */ first_name: string, /** * Returns if a profile is hidden. */ hidden: number, /** * User ID */ id: number, /** * User last name */ last_name: string, /** * */ can_access_closed: boolean, /** * */ is_closed: boolean, /** * User sex */ sex: BaseSex, /** * Domain name of the user's page */ screen_name: string, /** * URL of square photo of the user with 50 pixels in width */ photo_50: string, /** * URL of square photo of the user with 100 pixels in width */ photo_100: string, /** * */ online_info: UsersOnlineInfo, /** * Information whether the user is online */ online: BaseBoolInt, /** * Information whether the user is online in mobile site or application */ online_mobile: BaseBoolInt, /** * Application ID */ online_app: number, /** * Information whether the user is verified */ verified: BaseBoolInt, /** * Information whether the user has a "fire" pictogram. */ trending: BaseBoolInt, /** * */ friend_status: FriendsFriendStatusStatus, /** * */ mutual: FriendsRequestsMutual, /** * User's first name in nominative case */ first_name_nom: string, /** * User's first name in genitive case */ first_name_gen: string, /** * User's first name in dative case */ first_name_dat: string, /** * User's first name in accusative case */ first_name_acc: string, /** * User's first name in instrumental case */ first_name_ins: string, /** * User's first name in prepositional case */ first_name_abl: string, /** * User's last name in nominative case */ last_name_nom: string, /** * User's last name in genitive case */ last_name_gen: string, /** * User's last name in dative case */ last_name_dat: string, /** * User's last name in accusative case */ last_name_acc: string, /** * User's last name in instrumental case */ last_name_ins: string, /** * User's last name in prepositional case */ last_name_abl: string, /** * User nickname */ nickname: string, /** * User maiden name */ maiden_name: string, /** * User contact name */ contact_name: string, /** * Domain name of the user's page */ domain: string, /** * User's date of birth */ bdate: string, /** * */ city: BaseCity, /** * */ country: BaseCountry, /** * User's timezone */ timezone: number, /** * */ owner_state: OwnerState, /** * URL of square photo of the user with 200 pixels in width */ photo_200: string, /** * URL of square photo of the user with maximum width */ photo_max: string, /** * URL of user's photo with 200 pixels in width */ photo_200_orig: string, /** * URL of user's photo with 400 pixels in width */ photo_400_orig: string, /** * URL of user's photo of maximum size */ photo_max_orig: string, /** * ID of the user's main photo */ photo_id: string, /** * Information whether the user has main photo */ has_photo: BaseBoolInt, /** * Information whether the user specified his phone number */ has_mobile: BaseBoolInt, /** * Information whether the user is a friend of current user */ is_friend: BaseBoolInt, /** * Information whether current user can comment wall posts */ wall_comments: BaseBoolInt, /** * Information whether current user can post on the user's wall */ can_post: BaseBoolInt, /** * Information whether current user can see other users' audio on the wall */ can_see_all_posts: BaseBoolInt, /** * Information whether current user can see the user's audio */ can_see_audio: BaseBoolInt, /** * */ type: UsersUserType, /** * */ email: string, /** * */ skype: string, /** * */ facebook: string, /** * */ facebook_name: string, /** * */ twitter: string, /** * */ livejournal: string, /** * */ instagram: string, /** * */ test: BaseBoolInt, /** * */ video_live: VideoLiveInfo, /** * */ is_video_live_notifications_blocked: BaseBoolInt, /** * */ is_service: boolean, /** * */ service_description: string, /** * */ photo_rec: PhotosPhotoFalseable, /** * */ photo_medium: PhotosPhotoFalseable, /** * */ photo_medium_rec: PhotosPhotoFalseable, /** * */ photo: string, /** * */ photo_big: string, /** * */ photo_400: string, /** * */ photo_max_size: PhotosPhoto, /** * */ language: string, /** * */ stories_archive_count: number, /** * */ wall_default: string, /** * Information whether current user can call */ can_call: boolean, /** * Information whether current user can see the user's wishes */ can_see_wishes: boolean, /** * Information whether current user can see the user's gifts */ can_see_gifts: BaseBoolInt, /** * */ interests: string, /** * */ books: string, /** * */ tv: string, /** * */ quotes: string, /** * */ about: string, /** * */ games: string, /** * */ movies: string, /** * */ activities: string, /** * */ music: string, /** * Information whether current user can write private message */ can_write_private_message: BaseBoolInt, /** * Information whether current user can send a friend request */ can_send_friend_request: BaseBoolInt, /** * Information whether current user can be invited to the community */ can_be_invited_group: boolean, /** * User's mobile phone number */ mobile_phone: string, /** * User's additional phone number */ home_phone: string, /** * User's website */ site: string, /** * */ status_audio: AudioAudio, /** * User's status */ status: string, /** * User's status */ activity: string, /** * */ last_seen: UsersLastSeen, /** * */ exports: UsersExports, /** * */ crop_photo: BaseCropPhoto, /** * Number of user's followers */ followers_count: number, /** * User level in live streams achievements */ video_live_level: number, /** * Number of user's live streams */ video_live_count: number, /** * Number of user's clips */ clips_count: number, /** * Information whether current user is in the requested user's blacklist. */ blacklisted: BaseBoolInt, /** * Information whether the requested user is in current user's blacklist */ blacklisted_by_me: BaseBoolInt, /** * Information whether the requested user is in faves of current user */ is_favorite: BaseBoolInt, /** * Information whether the requested user is hidden from current user's newsfeed */ is_hidden_from_feed: BaseBoolInt, /** * Number of common friends with current user */ common_count: number, /** * */ occupation: UsersOccupation, /** * */ career: UsersCareer[], /** * */ military: UsersMilitary[], /** * University ID */ university: number, /** * University name */ university_name: string, /** * */ university_group_id: number, /** * Faculty ID */ faculty: number, /** * Faculty name */ faculty_name: string, /** * Graduation year */ graduation: number, /** * Education form */ education_form: string, /** * User's education status */ education_status: string, /** * User hometown */ home_town: string, /** * User relationship status */ relation: UsersUserRelation, /** * */ relation_partner: UsersUserMin, /** * */ personal: UsersPersonal, /** * */ universities: UsersUniversity[], /** * */ schools: UsersSchool[], /** * */ relatives: UsersRelative[], /** * Information whether current user is subscribed to podcasts */ is_subscribed_podcasts: boolean, /** * Owner in whitelist or not */ can_subscribe_podcasts: boolean, /** * Can subscribe to wall */ can_subscribe_posts: boolean, /** * */ counters: UsersUserCounters, /** * */ access_key: string, /** * */ can_upload_doc: BaseBoolInt, /** * */ hash: string, /** * */ has_email: boolean, /** * */ lists: number[] } export interface FriendsUserXtrPhone { /** * Returns if a profile is deleted or blocked */ deactivated: string, /** * User first name */ first_name: string, /** * Returns if a profile is hidden. */ hidden: number, /** * User ID */ id: number, /** * User last name */ last_name: string, /** * */ can_access_closed: boolean, /** * */ is_closed: boolean, /** * User sex */ sex: BaseSex, /** * Domain name of the user's page */ screen_name: string, /** * URL of square photo of the user with 50 pixels in width */ photo_50: string, /** * URL of square photo of the user with 100 pixels in width */ photo_100: string, /** * */ online_info: UsersOnlineInfo, /** * Information whether the user is online */ online: BaseBoolInt, /** * Information whether the user is online in mobile site or application */ online_mobile: BaseBoolInt, /** * Application ID */ online_app: number, /** * Information whether the user is verified */ verified: BaseBoolInt, /** * Information whether the user has a "fire" pictogram. */ trending: BaseBoolInt, /** * */ friend_status: FriendsFriendStatusStatus, /** * */ mutual: FriendsRequestsMutual, /** * User's first name in nominative case */ first_name_nom: string, /** * User's first name in genitive case */ first_name_gen: string, /** * User's first name in dative case */ first_name_dat: string, /** * User's first name in accusative case */ first_name_acc: string, /** * User's first name in instrumental case */ first_name_ins: string, /** * User's first name in prepositional case */ first_name_abl: string, /** * User's last name in nominative case */ last_name_nom: string, /** * User's last name in genitive case */ last_name_gen: string, /** * User's last name in dative case */ last_name_dat: string, /** * User's last name in accusative case */ last_name_acc: string, /** * User's last name in instrumental case */ last_name_ins: string, /** * User's last name in prepositional case */ last_name_abl: string, /** * User nickname */ nickname: string, /** * User maiden name */ maiden_name: string, /** * User contact name */ contact_name: string, /** * Domain name of the user's page */ domain: string, /** * User's date of birth */ bdate: string, /** * */ city: BaseCity, /** * */ country: BaseCountry, /** * User's timezone */ timezone: number, /** * */ owner_state: OwnerState, /** * URL of square photo of the user with 200 pixels in width */ photo_200: string, /** * URL of square photo of the user with maximum width */ photo_max: string, /** * URL of user's photo with 200 pixels in width */ photo_200_orig: string, /** * URL of user's photo with 400 pixels in width */ photo_400_orig: string, /** * URL of user's photo of maximum size */ photo_max_orig: string, /** * ID of the user's main photo */ photo_id: string, /** * Information whether the user has main photo */ has_photo: BaseBoolInt, /** * Information whether the user specified his phone number */ has_mobile: BaseBoolInt, /** * Information whether the user is a friend of current user */ is_friend: BaseBoolInt, /** * Information whether current user can comment wall posts */ wall_comments: BaseBoolInt, /** * Information whether current user can post on the user's wall */ can_post: BaseBoolInt, /** * Information whether current user can see other users' audio on the wall */ can_see_all_posts: BaseBoolInt, /** * Information whether current user can see the user's audio */ can_see_audio: BaseBoolInt, /** * */ type: UsersUserType, /** * */ email: string, /** * */ skype: string, /** * */ facebook: string, /** * */ facebook_name: string, /** * */ twitter: string, /** * */ livejournal: string, /** * */ instagram: string, /** * */ test: BaseBoolInt, /** * */ video_live: VideoLiveInfo, /** * */ is_video_live_notifications_blocked: BaseBoolInt, /** * */ is_service: boolean, /** * */ service_description: string, /** * */ photo_rec: PhotosPhotoFalseable, /** * */ photo_medium: PhotosPhotoFalseable, /** * */ photo_medium_rec: PhotosPhotoFalseable, /** * */ photo: string, /** * */ photo_big: string, /** * */ photo_400: string, /** * */ photo_max_size: PhotosPhoto, /** * */ language: string, /** * */ stories_archive_count: number, /** * */ wall_default: string, /** * Information whether current user can call */ can_call: boolean, /** * Information whether current user can see the user's wishes */ can_see_wishes: boolean, /** * Information whether current user can see the user's gifts */ can_see_gifts: BaseBoolInt, /** * */ interests: string, /** * */ books: string, /** * */ tv: string, /** * */ quotes: string, /** * */ about: string, /** * */ games: string, /** * */ movies: string, /** * */ activities: string, /** * */ music: string, /** * Information whether current user can write private message */ can_write_private_message: BaseBoolInt, /** * Information whether current user can send a friend request */ can_send_friend_request: BaseBoolInt, /** * Information whether current user can be invited to the community */ can_be_invited_group: boolean, /** * User's mobile phone number */ mobile_phone: string, /** * User's additional phone number */ home_phone: string, /** * User's website */ site: string, /** * */ status_audio: AudioAudio, /** * User's status */ status: string, /** * User's status */ activity: string, /** * */ last_seen: UsersLastSeen, /** * */ exports: UsersExports, /** * */ crop_photo: BaseCropPhoto, /** * Number of user's followers */ followers_count: number, /** * User level in live streams achievements */ video_live_level: number, /** * Number of user's live streams */ video_live_count: number, /** * Number of user's clips */ clips_count: number, /** * Information whether current user is in the requested user's blacklist. */ blacklisted: BaseBoolInt, /** * Information whether the requested user is in current user's blacklist */ blacklisted_by_me: BaseBoolInt, /** * Information whether the requested user is in faves of current user */ is_favorite: BaseBoolInt, /** * Information whether the requested user is hidden from current user's newsfeed */ is_hidden_from_feed: BaseBoolInt, /** * Number of common friends with current user */ common_count: number, /** * */ occupation: UsersOccupation, /** * */ career: UsersCareer[], /** * */ military: UsersMilitary[], /** * University ID */ university: number, /** * University name */ university_name: string, /** * */ university_group_id: number, /** * Faculty ID */ faculty: number, /** * Faculty name */ faculty_name: string, /** * Graduation year */ graduation: number, /** * Education form */ education_form: string, /** * User's education status */ education_status: string, /** * User hometown */ home_town: string, /** * User relationship status */ relation: UsersUserRelation, /** * */ relation_partner: UsersUserMin, /** * */ personal: UsersPersonal, /** * */ universities: UsersUniversity[], /** * */ schools: UsersSchool[], /** * */ relatives: UsersRelative[], /** * Information whether current user is subscribed to podcasts */ is_subscribed_podcasts: boolean, /** * Owner in whitelist or not */ can_subscribe_podcasts: boolean, /** * Can subscribe to wall */ can_subscribe_posts: boolean, /** * */ counters: UsersUserCounters, /** * */ access_key: string, /** * */ can_upload_doc: BaseBoolInt, /** * */ hash: string, /** * */ has_email: boolean, /** * User phone */ phone: string } export interface GiftsGift { /** * Date when gist has been sent in Unixtime */ date: number, /** * Gift sender ID */ from_id: number, /** * */ gift: GiftsLayout, /** * Hash */ gift_hash: string, /** * Gift ID */ id: number, /** * Comment text */ message: string, /** * */ privacy: GiftsGiftPrivacy } export type GiftsGiftPrivacy = number export interface GiftsLayout { /** * Gift ID */ id: number, /** * URL of the preview image with 512 px in width */ thumb_512: string, /** * URL of the preview image with 256 px in width */ thumb_256: string, /** * URL of the preview image with 48 px in width */ thumb_48: string, /** * URL of the preview image with 96 px in width */ thumb_96: string, /** * ID of the sticker pack, if the gift is representing one */ stickers_product_id: number, /** * Information whether gift represents a stickers style */ is_stickers_style: boolean, /** * ID of the build of constructor gift */ build_id: string, /** * Keywords used for search */ keywords: string } export interface GroupsAddress { /** * Additional address to the place (6 floor, left door) */ additional_address: string, /** * String address to the place (Nevsky, 28) */ address: string, /** * City id of address */ city_id: number, /** * Country id of address */ country_id: number, /** * Distance from the point */ distance: number, /** * Address id */ id: number, /** * Address latitude */ latitude: number, /** * Address longitude */ longitude: number, /** * Metro id of address */ metro_station_id: number, /** * Address phone */ phone: string, /** * Time offset int minutes from utc time */ time_offset: number, /** * Week timetable for the address */ timetable: GroupsAddressTimetable, /** * Title of the place (Zinger, etc) */ title: string, /** * Status of information about timetable */ work_info_status: GroupsAddressWorkInfoStatus } export interface GroupsAddressTimetable { /** * Timetable for friday */ fri: GroupsAddressTimetableDay, /** * Timetable for monday */ mon: GroupsAddressTimetableDay, /** * Timetable for saturday */ sat: GroupsAddressTimetableDay, /** * Timetable for sunday */ sun: GroupsAddressTimetableDay, /** * Timetable for thursday */ thu: GroupsAddressTimetableDay, /** * Timetable for tuesday */ tue: GroupsAddressTimetableDay, /** * Timetable for wednesday */ wed: GroupsAddressTimetableDay } export interface GroupsAddressTimetableDay { /** * Close time of the break in minutes */ break_close_time: number, /** * Start time of the break in minutes */ break_open_time: number, /** * Close time in minutes */ close_time: number, /** * Open time in minutes */ open_time: number } export type GroupsAddressWorkInfoStatus = string export interface GroupsAddressesInfo { /** * Information whether addresses is enabled */ is_enabled: boolean, /** * Main address id for group */ main_address_id: number } export interface GroupsBanInfo { /** * Administrator ID */ admin_id: number, /** * Comment for a ban */ comment: string, /** * Show comment for user */ comment_visible: boolean, /** * */ is_closed: boolean, /** * Date when user has been added to blacklist in Unixtime */ date: number, /** * Date when user will be removed from blacklist in Unixtime */ end_date: number, /** * */ reason: GroupsBanInfoReason } export type GroupsBanInfoReason = number export type GroupsBannedItem = GroupsOwnerXtrBanInfo export interface GroupsCallbackServer { /** * */ id: number, /** * */ title: string, /** * */ creator_id: number, /** * */ url: string, /** * */ secret_key: string, /** * */ status: string } export interface GroupsCallbackSettings { /** * API version used for the events */ api_version: string, /** * */ events: GroupsLongPollEvents } export interface GroupsContactsItem { /** * User ID */ user_id: number, /** * Contact description */ desc: string, /** * Contact phone */ phone: string, /** * Contact email */ email: string } export interface GroupsCountersGroup { /** * Addresses number */ addresses: number, /** * Photo albums number */ albums: number, /** * Audios number */ audios: number, /** * Audio playlists number */ audio_playlists: number, /** * Docs number */ docs: number, /** * Market items number */ market: number, /** * Photos number */ photos: number, /** * Topics number */ topics: number, /** * Videos number */ videos: number } export interface GroupsCover { /** * Information whether cover is enabled */ enabled: BaseBoolInt, /** * */ images: BaseImage[] } export type GroupsFields = string export type GroupsFilter = string export interface GroupsGroup { /** * Community ID */ id: number, /** * Community name */ name: string, /** * Domain of the community page */ screen_name: string, /** * */ is_closed: GroupsGroupIsClosed, /** * */ type: GroupsGroupType, /** * Information whether current user is administrator */ is_admin: BaseBoolInt, /** * */ admin_level: GroupsGroupAdminLevel, /** * Information whether current user is member */ is_member: BaseBoolInt, /** * Information whether current user is advertiser */ is_advertiser: BaseBoolInt, /** * Start date in Unixtime format */ start_date: number, /** * Finish date in Unixtime format */ finish_date: number, /** * Information whether community is banned */ deactivated: string, /** * URL of square photo of the community with 50 pixels in width */ photo_50: string, /** * URL of square photo of the community with 100 pixels in width */ photo_100: string, /** * URL of square photo of the community with 200 pixels in width */ photo_200: string } export type GroupsGroupAccess = number export type GroupsGroupAdminLevel = number export type GroupsGroupAgeLimits = number export interface GroupsGroupAttach { /** * group ID */ id: number, /** * text of attach */ text: string, /** * activity or category of group */ status: string, /** * size of group */ size: number, /** * is favorite */ is_favorite: boolean } export type GroupsGroupAudio = number export interface GroupsGroupBanInfo { /** * Ban comment */ comment: string, /** * End date of ban in Unixtime */ end_date: number, /** * */ reason: GroupsBanInfoReason } export interface GroupsGroupCategory { /** * Category ID */ id: number, /** * Category name */ name: string, /** * */ subcategories: BaseObjectWithName[] } export interface GroupsGroupCategoryFull { /** * Category ID */ id: number, /** * Category name */ name: string, /** * Pages number */ page_count: number, /** * */ page_previews: GroupsGroup[], /** * */ subcategories: GroupsGroupCategory[] } export interface GroupsGroupCategoryType { /** * */ id: number, /** * */ name: string } export type GroupsGroupDocs = number export interface GroupsGroupFull { /** * Community ID */ id: number, /** * Community name */ name: string, /** * Domain of the community page */ screen_name: string, /** * */ is_closed: GroupsGroupIsClosed, /** * */ type: GroupsGroupType, /** * Information whether current user is administrator */ is_admin: BaseBoolInt, /** * */ admin_level: GroupsGroupAdminLevel, /** * Information whether current user is member */ is_member: BaseBoolInt, /** * Information whether current user is advertiser */ is_advertiser: BaseBoolInt, /** * Start date in Unixtime format */ start_date: number, /** * Finish date in Unixtime format */ finish_date: number, /** * Information whether community is banned */ deactivated: string, /** * URL of square photo of the community with 50 pixels in width */ photo_50: string, /** * URL of square photo of the community with 100 pixels in width */ photo_100: string, /** * URL of square photo of the community with 200 pixels in width */ photo_200: string, /** * */ market: GroupsMarketInfo, /** * Current user's member status */ member_status: GroupsGroupFullMemberStatus, /** * Information whether community is adult */ is_adult: BaseBoolInt, /** * Information whether community is hidden from current user's newsfeed */ is_hidden_from_feed: BaseBoolInt, /** * Information whether community is in faves */ is_favorite: BaseBoolInt, /** * Information whether current user is subscribed */ is_subscribed: BaseBoolInt, /** * */ city: BaseObject, /** * */ country: BaseCountry, /** * Information whether community is verified */ verified: BaseBoolInt, /** * Community description */ description: string, /** * Community's main wiki page title */ wiki_page: string, /** * Community members number */ members_count: number, /** * The number of incoming requests to the community */ requests_count: number, /** * Community level live streams achievements */ video_live_level: number, /** * Number of community's live streams */ video_live_count: number, /** * Number of community's clips */ clips_count: number, /** * */ counters: GroupsCountersGroup, /** * */ cover: GroupsCover, /** * Information whether current user can post on community's wall */ can_post: BaseBoolInt, /** * */ can_suggest: BaseBoolInt, /** * Information whether current user can upload story */ can_upload_story: BaseBoolInt, /** * Information whether current user can upload doc */ can_upload_doc: BaseBoolInt, /** * Information whether current user can upload video */ can_upload_video: BaseBoolInt, /** * Information whether current user can see all posts on community's wall */ can_see_all_posts: BaseBoolInt, /** * Information whether current user can create topic */ can_create_topic: BaseBoolInt, /** * Type of group, start date of event or category of public page */ activity: string, /** * Fixed post ID */ fixed_post: number, /** * Information whether community has photo */ has_photo: BaseBoolInt, /** * Данные о точках, по которым вырезаны профильная и миниатюрная фотографии сообщества */ crop_photo: BaseCropPhoto, /** * Community status */ status: string, /** * */ status_audio: AudioAudio, /** * Community's main photo album ID */ main_album_id: number, /** * */ links: GroupsLinksItem[], /** * */ contacts: GroupsContactsItem[], /** * Information about wall status in community */ wall: number, /** * Community's website */ site: string, /** * */ main_section: GroupsGroupFullMainSection, /** * */ secondary_section: number, /** * Information whether the community has a "fire" pictogram. */ trending: BaseBoolInt, /** * Information whether current user can send a message to community */ can_message: BaseBoolInt, /** * Information whether community can send a message to current user */ is_messages_blocked: BaseBoolInt, /** * Information whether community can send notifications by phone number to current user */ can_send_notify: BaseBoolInt, /** * Status of replies in community messages */ online_status: GroupsOnlineStatus, /** * Inviter ID */ invited_by: number, /** * Information whether age limit */ age_limits: GroupsGroupFullAgeLimits, /** * User ban info */ ban_info: GroupsGroupBanInfo, /** * Information whether community has installed market app */ has_market_app: boolean, /** * */ using_vkpay_market_app: boolean, /** * */ has_group_channel: boolean, /** * Info about addresses in groups */ addresses: GroupsAddressesInfo, /** * Information whether current user is subscribed to podcasts */ is_subscribed_podcasts: boolean, /** * Owner in whitelist or not */ can_subscribe_podcasts: boolean, /** * Can subscribe to wall */ can_subscribe_posts: boolean, /** * Live covers state */ live_covers: GroupsLiveCovers, /** * */ stories_archive_count: number } export type GroupsGroupFullAgeLimits = number export type GroupsGroupFullMainSection = number export type GroupsGroupFullMemberStatus = number export type GroupsGroupIsClosed = number export interface GroupsGroupLink { /** * Link label */ name: string, /** * Link description */ desc: string, /** * Information whether the title can be edited */ edit_title: BaseBoolInt, /** * Link ID */ id: number, /** * Information whether the image on processing */ image_processing: BaseBoolInt, /** * Link URL */ url: string } export type GroupsGroupMarketCurrency = number export type GroupsGroupPhotos = number export interface GroupsGroupPublicCategoryList { /** * */ id: number, /** * */ name: string, /** * */ subcategories: GroupsGroupCategoryType[] } export type GroupsGroupRole = string export type GroupsGroupSubject = string export type GroupsGroupSuggestedPrivacy = number export interface GroupsGroupTag { /** * */ id: number, /** * */ name: string, /** * */ color: string, /** * */ uses: number } export type GroupsGroupTopics = number export type GroupsGroupType = string export type GroupsGroupVideo = number export type GroupsGroupWall = number export type GroupsGroupWiki = number export interface GroupsGroupsArray { /** * Communities number */ count: number, /** * */ items: number[] } export interface GroupsLinksItem { /** * Link description */ desc: string, /** * Information whether the link title can be edited */ edit_title: BaseBoolInt, /** * Link ID */ id: number, /** * Link title */ name: string, /** * URL of square image of the link with 100 pixels in width */ photo_100: string, /** * URL of square image of the link with 50 pixels in width */ photo_50: string, /** * Link URL */ url: string } export interface GroupsLiveCovers { /** * Information whether live covers is enabled */ is_enabled: boolean, /** * Information whether live covers photo scaling is enabled */ is_scalable: boolean, /** * */ story_ids: string[] } export interface GroupsLongPollEvents { /** * */ audio_new: BaseBoolInt, /** * */ board_post_delete: BaseBoolInt, /** * */ board_post_edit: BaseBoolInt, /** * */ board_post_new: BaseBoolInt, /** * */ board_post_restore: BaseBoolInt, /** * */ group_change_photo: BaseBoolInt, /** * */ group_change_settings: BaseBoolInt, /** * */ group_join: BaseBoolInt, /** * */ group_leave: BaseBoolInt, /** * */ group_officers_edit: BaseBoolInt, /** * */ lead_forms_new: BaseBoolInt, /** * */ market_comment_delete: BaseBoolInt, /** * */ market_comment_edit: BaseBoolInt, /** * */ market_comment_new: BaseBoolInt, /** * */ market_comment_restore: BaseBoolInt, /** * */ market_order_new: BaseBoolInt, /** * */ market_order_edit: BaseBoolInt, /** * */ message_allow: BaseBoolInt, /** * */ message_deny: BaseBoolInt, /** * */ message_new: BaseBoolInt, /** * */ message_read: BaseBoolInt, /** * */ message_reply: BaseBoolInt, /** * */ message_typing_state: BaseBoolInt, /** * */ message_edit: BaseBoolInt, /** * */ photo_comment_delete: BaseBoolInt, /** * */ photo_comment_edit: BaseBoolInt, /** * */ photo_comment_new: BaseBoolInt, /** * */ photo_comment_restore: BaseBoolInt, /** * */ photo_new: BaseBoolInt, /** * */ poll_vote_new: BaseBoolInt, /** * */ user_block: BaseBoolInt, /** * */ user_unblock: BaseBoolInt, /** * */ video_comment_delete: BaseBoolInt, /** * */ video_comment_edit: BaseBoolInt, /** * */ video_comment_new: BaseBoolInt, /** * */ video_comment_restore: BaseBoolInt, /** * */ video_new: BaseBoolInt, /** * */ wall_post_new: BaseBoolInt, /** * */ wall_reply_delete: BaseBoolInt, /** * */ wall_reply_edit: BaseBoolInt, /** * */ wall_reply_new: BaseBoolInt, /** * */ wall_reply_restore: BaseBoolInt, /** * */ wall_repost: BaseBoolInt, /** * */ donut_subscription_create: BaseBoolInt, /** * */ donut_subscription_prolonged: BaseBoolInt, /** * */ donut_subscription_cancelled: BaseBoolInt, /** * */ donut_subscription_expired: BaseBoolInt, /** * */ donut_subscription_price_changed: BaseBoolInt, /** * */ donut_money_withdraw: BaseBoolInt, /** * */ donut_money_withdraw_error: BaseBoolInt } export interface GroupsLongPollServer { /** * Long Poll key */ key: string, /** * Long Poll server address */ server: string, /** * Number of the last event */ ts: string } export interface GroupsLongPollSettings { /** * API version used for the events */ api_version: string, /** * */ events: GroupsLongPollEvents, /** * Shows whether Long Poll is enabled */ is_enabled: boolean } export interface GroupsMarketInfo { /** * Contact person ID */ contact_id: number, /** * */ currency: MarketCurrency, /** * Currency name */ currency_text: string, /** * Information whether the market is enabled */ enabled: BaseBoolInt, /** * Main market album ID */ main_album_id: number, /** * Maximum price */ price_max: string, /** * Minimum price */ price_min: string } export type GroupsMarketState = string export interface GroupsMemberRole { /** * User ID */ id: number, /** * */ permissions: GroupsMemberRolePermission[], /** * */ role: GroupsMemberRoleStatus } export type GroupsMemberRolePermission = string export type GroupsMemberRoleStatus = string export interface GroupsMemberStatus { /** * Information whether user is a member of the group */ member: BaseBoolInt, /** * User ID */ user_id: number } export interface GroupsMemberStatusFull { /** * Information whether user can be invited */ can_invite: BaseBoolInt, /** * Information whether user's invite to the group can be recalled */ can_recall: BaseBoolInt, /** * Information whether user has been invited to the group */ invitation: BaseBoolInt, /** * Information whether user is a member of the group */ member: BaseBoolInt, /** * Information whether user has send request to the group */ request: BaseBoolInt, /** * User ID */ user_id: number } export interface GroupsOnlineStatus { /** * Estimated time of answer (for status = answer_mark) */ minutes: number, /** * */ status: GroupsOnlineStatusType } export type GroupsOnlineStatusType = string export interface GroupsOwnerXtrBanInfo { /** * */ ban_info: GroupsBanInfo, /** * Information about group if type = group */ group: GroupsGroup, /** * Information about group if type = profile */ profile: UsersUser, /** * */ type: GroupsOwnerXtrBanInfoType } export type GroupsOwnerXtrBanInfoType = string export interface GroupsProfileItem { /** * User id */ id: number, /** * Url for user photo */ photo_50: string, /** * Url for user photo */ photo_100: string } export type GroupsRoleOptions = string export interface GroupsSettingsTwitter { /** * */ status: string, /** * */ name: string } export interface GroupsSubjectItem { /** * Subject ID */ id: number, /** * Subject title */ name: string } export interface GroupsTokenPermissionSetting { /** * */ name: string, /** * */ setting: number } export interface GroupsUserXtrRole { /** * Returns if a profile is deleted or blocked */ deactivated: string, /** * User first name */ first_name: string, /** * Returns if a profile is hidden. */ hidden: number, /** * User ID */ id: number, /** * User last name */ last_name: string, /** * */ can_access_closed: boolean, /** * */ is_closed: boolean, /** * User sex */ sex: BaseSex, /** * Domain name of the user's page */ screen_name: string, /** * URL of square photo of the user with 50 pixels in width */ photo_50: string, /** * URL of square photo of the user with 100 pixels in width */ photo_100: string, /** * */ online_info: UsersOnlineInfo, /** * Information whether the user is online */ online: BaseBoolInt, /** * Information whether the user is online in mobile site or application */ online_mobile: BaseBoolInt, /** * Application ID */ online_app: number, /** * Information whether the user is verified */ verified: BaseBoolInt, /** * Information whether the user has a "fire" pictogram. */ trending: BaseBoolInt, /** * */ friend_status: FriendsFriendStatusStatus, /** * */ mutual: FriendsRequestsMutual, /** * User's first name in nominative case */ first_name_nom: string, /** * User's first name in genitive case */ first_name_gen: string, /** * User's first name in dative case */ first_name_dat: string, /** * User's first name in accusative case */ first_name_acc: string, /** * User's first name in instrumental case */ first_name_ins: string, /** * User's first name in prepositional case */ first_name_abl: string, /** * User's last name in nominative case */ last_name_nom: string, /** * User's last name in genitive case */ last_name_gen: string, /** * User's last name in dative case */ last_name_dat: string, /** * User's last name in accusative case */ last_name_acc: string, /** * User's last name in instrumental case */ last_name_ins: string, /** * User's last name in prepositional case */ last_name_abl: string, /** * User nickname */ nickname: string, /** * User maiden name */ maiden_name: string, /** * User contact name */ contact_name: string, /** * Domain name of the user's page */ domain: string, /** * User's date of birth */ bdate: string, /** * */ city: BaseCity, /** * */ country: BaseCountry, /** * User's timezone */ timezone: number, /** * */ owner_state: OwnerState, /** * URL of square photo of the user with 200 pixels in width */ photo_200: string, /** * URL of square photo of the user with maximum width */ photo_max: string, /** * URL of user's photo with 200 pixels in width */ photo_200_orig: string, /** * URL of user's photo with 400 pixels in width */ photo_400_orig: string, /** * URL of user's photo of maximum size */ photo_max_orig: string, /** * ID of the user's main photo */ photo_id: string, /** * Information whether the user has main photo */ has_photo: BaseBoolInt, /** * Information whether the user specified his phone number */ has_mobile: BaseBoolInt, /** * Information whether the user is a friend of current user */ is_friend: BaseBoolInt, /** * Information whether current user can comment wall posts */ wall_comments: BaseBoolInt, /** * Information whether current user can post on the user's wall */ can_post: BaseBoolInt, /** * Information whether current user can see other users' audio on the wall */ can_see_all_posts: BaseBoolInt, /** * Information whether current user can see the user's audio */ can_see_audio: BaseBoolInt, /** * */ type: UsersUserType, /** * */ email: string, /** * */ skype: string, /** * */ facebook: string, /** * */ facebook_name: string, /** * */ twitter: string, /** * */ livejournal: string, /** * */ instagram: string, /** * */ test: BaseBoolInt, /** * */ video_live: VideoLiveInfo, /** * */ is_video_live_notifications_blocked: BaseBoolInt, /** * */ is_service: boolean, /** * */ service_description: string, /** * */ photo_rec: PhotosPhotoFalseable, /** * */ photo_medium: PhotosPhotoFalseable, /** * */ photo_medium_rec: PhotosPhotoFalseable, /** * */ photo: string, /** * */ photo_big: string, /** * */ photo_400: string, /** * */ photo_max_size: PhotosPhoto, /** * */ language: string, /** * */ stories_archive_count: number, /** * */ wall_default: string, /** * Information whether current user can call */ can_call: boolean, /** * Information whether current user can see the user's wishes */ can_see_wishes: boolean, /** * Information whether current user can see the user's gifts */ can_see_gifts: BaseBoolInt, /** * */ interests: string, /** * */ books: string, /** * */ tv: string, /** * */ quotes: string, /** * */ about: string, /** * */ games: string, /** * */ movies: string, /** * */ activities: string, /** * */ music: string, /** * Information whether current user can write private message */ can_write_private_message: BaseBoolInt, /** * Information whether current user can send a friend request */ can_send_friend_request: BaseBoolInt, /** * Information whether current user can be invited to the community */ can_be_invited_group: boolean, /** * User's mobile phone number */ mobile_phone: string, /** * User's additional phone number */ home_phone: string, /** * User's website */ site: string, /** * */ status_audio: AudioAudio, /** * User's status */ status: string, /** * User's status */ activity: string, /** * */ last_seen: UsersLastSeen, /** * */ exports: UsersExports, /** * */ crop_photo: BaseCropPhoto, /** * Number of user's followers */ followers_count: number, /** * User level in live streams achievements */ video_live_level: number, /** * Number of user's live streams */ video_live_count: number, /** * Number of user's clips */ clips_count: number, /** * Information whether current user is in the requested user's blacklist. */ blacklisted: BaseBoolInt, /** * Information whether the requested user is in current user's blacklist */ blacklisted_by_me: BaseBoolInt, /** * Information whether the requested user is in faves of current user */ is_favorite: BaseBoolInt, /** * Information whether the requested user is hidden from current user's newsfeed */ is_hidden_from_feed: BaseBoolInt, /** * Number of common friends with current user */ common_count: number, /** * */ occupation: UsersOccupation, /** * */ career: UsersCareer[], /** * */ military: UsersMilitary[], /** * University ID */ university: number, /** * University name */ university_name: string, /** * */ university_group_id: number, /** * Faculty ID */ faculty: number, /** * Faculty name */ faculty_name: string, /** * Graduation year */ graduation: number, /** * Education form */ education_form: string, /** * User's education status */ education_status: string, /** * User hometown */ home_town: string, /** * User relationship status */ relation: UsersUserRelation, /** * */ relation_partner: UsersUserMin, /** * */ personal: UsersPersonal, /** * */ universities: UsersUniversity[], /** * */ schools: UsersSchool[], /** * */ relatives: UsersRelative[], /** * Information whether current user is subscribed to podcasts */ is_subscribed_podcasts: boolean, /** * Owner in whitelist or not */ can_subscribe_podcasts: boolean, /** * Can subscribe to wall */ can_subscribe_posts: boolean, /** * */ counters: UsersUserCounters, /** * */ access_key: string, /** * */ can_upload_doc: BaseBoolInt, /** * */ hash: string, /** * */ has_email: boolean, /** * */ role: GroupsRoleOptions } export type LikesType = string export interface LinkTargetObject { /** * Object type */ type: string, /** * Owner ID */ owner_id: number, /** * Item ID */ item_id: number } export interface MarketCurrency { /** * Currency ID */ id: number, /** * Currency sign */ name: string } export interface MarketMarketAlbum { /** * Items number */ count: number, /** * Market album ID */ id: number, /** * Market album owner's ID */ owner_id: number, /** * */ photo: PhotosPhoto, /** * Market album title */ title: string, /** * Date when album has been updated last time in Unixtime */ updated_time: number } export type MarketMarketCategory = MarketMarketCategoryOld export interface MarketMarketCategoryNested { /** * Category ID */ id: number, /** * Category name */ name: string, /** * */ parent: MarketMarketCategoryNested } export interface MarketMarketCategoryOld { /** * Category ID */ id: number, /** * Category name */ name: string, /** * */ section: MarketSection } export interface MarketMarketCategoryTree { /** * Category ID */ id: number, /** * Category name */ name: string, /** * */ children: MarketMarketCategoryTree[] } export interface MarketMarketItem { /** * Access key for the market item */ access_key: string, /** * */ availability: MarketMarketItemAvailability, /** * Title for button for url */ button_title: string, /** * */ category: MarketMarketCategory, /** * Date when the item has been created in Unixtime */ date: number, /** * Item description */ description: string, /** * */ external_id: string, /** * Item ID */ id: number, /** * */ is_favorite: boolean, /** * Item owner's ID */ owner_id: number, /** * */ price: MarketPrice, /** * URL of the preview image */ thumb_photo: string, /** * Item title */ title: string, /** * URL to item */ url: string, /** * */ variants_grouping_id: number, /** * */ is_main_variant: boolean } export type MarketMarketItemAvailability = number export interface MarketMarketItemFull { /** * Access key for the market item */ access_key: string, /** * */ availability: MarketMarketItemAvailability, /** * Title for button for url */ button_title: string, /** * */ category: MarketMarketCategory, /** * Date when the item has been created in Unixtime */ date: number, /** * Item description */ description: string, /** * */ external_id: string, /** * Item ID */ id: number, /** * */ is_favorite: boolean, /** * Item owner's ID */ owner_id: number, /** * */ price: MarketPrice, /** * URL of the preview image */ thumb_photo: string, /** * Item title */ title: string, /** * URL to item */ url: string, /** * */ variants_grouping_id: number, /** * */ is_main_variant: boolean, /** * */ albums_ids: number[], /** * */ photos: PhotosPhoto[], /** * Information whether current use can comment the item */ can_comment: BaseBoolInt, /** * Information whether current use can repost the item */ can_repost: BaseBoolInt, /** * */ likes: BaseLikes, /** * */ reposts: BaseRepostsInfo, /** * Views number */ views_count: number, /** * Object identifier in wishlist of viewer */ wishlist_item_id: number, /** * Information for cancel and revert order */ cancel_info: BaseLink, /** * User agreement info */ user_agreement_info: string } export interface MarketOrder { /** * */ id: number, /** * */ group_id: number, /** * */ user_id: number, /** * */ display_order_id: string, /** * */ date: number, /** * */ status: number, /** * */ items_count: number, /** * */ track_number: string, /** * */ track_link: string, /** * */ comment: string, /** * */ address: string, /** * */ merchant_comment: string, /** * */ weight: number, /** * */ total_price: MarketPrice, /** * Several order items for preview */ preview_order_items: MarketOrderItem[], /** * Information for cancel and revert order */ cancel_info: BaseLink } export interface MarketOrderItem { /** * */ owner_id: number, /** * */ item_id: number, /** * */ price: MarketPrice, /** * */ quantity: number, /** * */ item: MarketMarketItem, /** * */ title: string, /** * */ photo: PhotosPhoto, /** * */ variants: string[] } export interface MarketPrice { /** * Amount */ amount: string, /** * */ currency: MarketCurrency, /** * */ discount_rate: number, /** * */ old_amount: string, /** * Text */ text: string, /** * Textual representation of old price */ old_amount_text: string } export interface MarketSection { /** * Section ID */ id: number, /** * Section name */ name: string } export interface MediaRestriction { /** * */ text: string, /** * */ title: string, /** * */ button: VideoRestrictionButton, /** * Need show restriction always or not */ always_shown: BaseBoolInt, /** * Need blur current video or not */ blur: BaseBoolInt, /** * Can play video or not */ can_play: BaseBoolInt, /** * Can preview video or not */ can_preview: BaseBoolInt, /** * */ card_icon: BaseImage[], /** * */ list_icon: BaseImage[] } export interface MessagesAudioMessage { /** * Access key for audio message */ access_key: string, /** * */ transcript_error: number, /** * Audio message duration in seconds */ duration: number, /** * Audio message ID */ id: number, /** * MP3 file URL */ link_mp3: string, /** * OGG file URL */ link_ogg: string, /** * Audio message owner ID */ owner_id: number, /** * */ waveform: number[] } export interface MessagesChat { /** * Chat creator ID */ admin_id: number, /** * Chat ID */ id: number, /** * Shows that user has been kicked from the chat */ kicked: BaseBoolInt, /** * Shows that user has been left the chat */ left: BaseBoolInt, /** * URL of the preview image with 100 px in width */ photo_100: string, /** * URL of the preview image with 200 px in width */ photo_200: string, /** * URL of the preview image with 50 px in width */ photo_50: string, /** * */ push_settings: MessagesChatPushSettings, /** * Chat title */ title: string, /** * Chat type */ type: string, /** * */ users: number[], /** * If provided photo is default */ is_default_photo: boolean } export interface MessagesChatFull { /** * Chat creator ID */ admin_id: number, /** * Chat ID */ id: number, /** * Shows that user has been kicked from the chat */ kicked: BaseBoolInt, /** * Shows that user has been left the chat */ left: BaseBoolInt, /** * URL of the preview image with 100 px in width */ photo_100: string, /** * URL of the preview image with 200 px in width */ photo_200: string, /** * URL of the preview image with 50 px in width */ photo_50: string, /** * */ push_settings: MessagesChatPushSettings, /** * Chat title */ title: string, /** * Chat type */ type: string, /** * */ users: MessagesUserXtrInvitedBy[] } export interface MessagesChatPreview { /** * */ admin_id: number, /** * */ joined: boolean, /** * */ local_id: number, /** * */ members: number[], /** * */ members_count: number, /** * */ title: string } export interface MessagesChatPushSettings { /** * Time until that notifications are disabled */ disabled_until: number, /** * Information whether the sound is on */ sound: BaseBoolInt } export interface MessagesChatRestrictions { /** * Only admins can promote users to admins */ admins_promote_users: boolean, /** * Only admins can change chat info */ only_admins_edit_info: boolean, /** * Only admins can edit pinned message */ only_admins_edit_pin: boolean, /** * Only admins can invite users to this chat */ only_admins_invite: boolean, /** * Only admins can kick users from this chat */ only_admins_kick: boolean } export interface MessagesChatSettings { /** * */ members_count: number, /** * */ owner_id: number, /** * Chat title */ title: string, /** * */ pinned_message: MessagesPinnedMessage, /** * */ state: MessagesChatSettingsState, /** * */ photo: MessagesChatSettingsPhoto, /** * Ids of chat admins */ admin_ids: number[], /** * */ active_ids: number[], /** * */ is_group_channel: boolean, /** * */ acl: MessagesChatSettingsAcl, /** * */ permissions: MessagesChatSettingsPermissions, /** * */ is_disappearing: boolean, /** * */ theme: string, /** * */ disappearing_chat_link: string, /** * */ is_service: boolean } export interface MessagesChatSettingsAcl { /** * Can you change photo, description and name */ can_change_info: boolean, /** * Can you change invite link for this chat */ can_change_invite_link: boolean, /** * Can you pin/unpin message for this chat */ can_change_pin: boolean, /** * Can you invite other peers in chat */ can_invite: boolean, /** * Can you promote simple users to chat admins */ can_promote_users: boolean, /** * Can you see invite link for this chat */ can_see_invite_link: boolean, /** * Can you moderate (delete) other users' messages */ can_moderate: boolean, /** * Can you copy chat */ can_copy_chat: boolean, /** * Can you init group call in the chat */ can_call: boolean, /** * Can you use mass mentions */ can_use_mass_mentions: boolean, /** * Can you change chat service type */ can_change_service_type: boolean } export interface MessagesChatSettingsPermissions { /** * Who can invite users to chat */ invite: string, /** * Who can change chat info */ change_info: string, /** * Who can change pinned message */ change_pin: string, /** * Who can use mass mentions */ use_mass_mentions: string, /** * Who can see invite link */ see_invite_link: string, /** * Who can make calls */ call: string, /** * Who can change admins */ change_admins: string } export interface MessagesChatSettingsPhoto { /** * URL of the preview image with 50px in width */ photo_50: string, /** * URL of the preview image with 100px in width */ photo_100: string, /** * URL of the preview image with 200px in width */ photo_200: string, /** * If provided photo is default */ is_default_photo: boolean } export type MessagesChatSettingsState = string export interface MessagesConversation { /** * */ peer: MessagesConversationPeer, /** * */ sort_id: MessagesConversationSortId, /** * ID of the last message in conversation */ last_message_id: number, /** * Last message user have read */ in_read: number, /** * Last outcoming message have been read by the opponent */ out_read: number, /** * Unread messages number */ unread_count: number, /** * Is this conversation uread */ is_marked_unread: boolean, /** * */ out_read_by: MessagesOutReadBy, /** * */ important: boolean, /** * */ unanswered: boolean, /** * */ special_service_type: string, /** * */ message_request_data: MessagesMessageRequestData, /** * Ids of messages with mentions */ mentions: number[], /** * */ current_keyboard: MessagesKeyboard, /** * */ push_settings: MessagesPushSettings, /** * */ can_write: MessagesConversationCanWrite, /** * */ chat_settings: MessagesChatSettings } export interface MessagesConversationCanWrite { /** * */ allowed: boolean, /** * */ reason: number } export interface MessagesConversationMember { /** * Is it possible for user to kick this member */ can_kick: boolean, /** * */ invited_by: number, /** * */ is_admin: boolean, /** * */ is_owner: boolean, /** * */ is_message_request: boolean, /** * */ join_date: number, /** * Message request date */ request_date: number, /** * */ member_id: number } export interface MessagesConversationPeer { /** * */ id: number, /** * */ local_id: number, /** * */ type: MessagesConversationPeerType } export type MessagesConversationPeerType = string export interface MessagesConversationSortId { /** * Major id for sorting conversations */ major_id: number, /** * Minor id for sorting conversations */ minor_id: number } export interface MessagesConversationWithMessage { /** * */ conversation: MessagesConversation, /** * */ last_message: MessagesMessage } export interface MessagesForeignMessage { /** * */ attachments: MessagesMessageAttachment[], /** * Conversation message ID */ conversation_message_id: number, /** * Date when the message was created */ date: number, /** * Message author's ID */ from_id: number, /** * */ fwd_messages: MessagesForeignMessage[], /** * */ geo: BaseGeo, /** * Message ID */ id: number, /** * Peer ID */ peer_id: number, /** * */ reply_message: MessagesForeignMessage, /** * Message text */ text: string, /** * Date when the message has been updated in Unixtime */ update_time: number, /** * Was the audio message inside already listened by you */ was_listened: boolean, /** * Additional data sent along with message for developer convenience */ payload: string } export interface MessagesForward { /** * Messages owner_id */ owner_id: number, /** * Messages peer_id */ peer_id: number, /** * */ conversation_message_ids: number[], /** * */ message_ids: number[], /** * If you need to reply to a message */ is_reply: boolean } export interface MessagesGraffiti { /** * Access key for graffiti */ access_key: string, /** * Graffiti height */ height: number, /** * Graffiti ID */ id: number, /** * Graffiti owner ID */ owner_id: number, /** * Graffiti URL */ url: string, /** * Graffiti width */ width: number } export interface MessagesHistoryAttachment { /** * */ attachment: MessagesHistoryMessageAttachment, /** * Message ID */ message_id: number, /** * Message author's ID */ from_id: number, /** * Forward level (optional) */ forward_level: number } export interface MessagesHistoryMessageAttachment { /** * */ audio: AudioAudio, /** * */ audio_message: MessagesAudioMessage, /** * */ doc: DocsDoc, /** * */ graffiti: MessagesGraffiti, /** * */ link: BaseLink, /** * */ market: BaseLink, /** * */ photo: PhotosPhoto, /** * */ share: BaseLink, /** * */ type: MessagesHistoryMessageAttachmentType, /** * */ video: VideoVideo, /** * */ wall: BaseLink } export type MessagesHistoryMessageAttachmentType = string export interface MessagesKeyboard { /** * Community or bot, which set this keyboard */ author_id: number, /** * */ buttons: MessagesKeyboardButton[][], /** * Should this keyboard disappear on first use */ one_time: boolean, /** * */ inline: boolean } export interface MessagesKeyboardButton { /** * */ action: MessagesKeyboardButtonAction, /** * Button color */ color: string } export interface MessagesKeyboardButtonAction { /** * Fragment value in app link like vk.com/app{app_id}_-654321#hash */ app_id: number, /** * Fragment value in app link like vk.com/app123456_-654321#{hash} */ hash: string, /** * Label for button */ label: string, /** * link for button */ link: string, /** * Fragment value in app link like vk.com/app123456_{owner_id}#hash */ owner_id: number, /** * Additional data sent along with message for developer convenience */ payload: string, /** * Button type */ type: MessagesTemplateActionTypeNames } export interface MessagesLastActivity { /** * Information whether user is online */ online: BaseBoolInt, /** * Time when user was online in Unixtime */ time: number } export interface MessagesLongpollMessages { /** * Total number */ count: number, /** * */ items: MessagesMessage[] } export interface MessagesLongpollParams { /** * Server URL */ server: string, /** * Key */ key: string, /** * Timestamp */ ts: number, /** * Persistent timestamp */ pts: number } export interface MessagesMessage { /** * */ action: MessagesMessageAction, /** * Only for messages from community. Contains user ID of community admin, who sent this message. */ admin_author_id: number, /** * */ attachments: MessagesMessageAttachment[], /** * Unique auto-incremented number for all messages with this peer */ conversation_message_id: number, /** * Date when the message has been sent in Unixtime */ date: number, /** * Is it an deleted message */ deleted: BaseBoolInt, /** * Message author's ID */ from_id: number, /** * Forwarded messages */ fwd_messages: MessagesForeignMessage[], /** * */ geo: BaseGeo, /** * Message ID */ id: number, /** * Is it an important message */ important: boolean, /** * */ is_hidden: boolean, /** * this message is cropped for bot */ is_cropped: boolean, /** * */ keyboard: MessagesKeyboard, /** * Members number */ members_count: number, /** * Information whether the message is outcoming */ out: BaseBoolInt, /** * */ payload: string, /** * Peer ID */ peer_id: number, /** * ID used for sending messages. It returned only for outgoing messages */ random_id: number, /** * */ ref: string, /** * */ ref_source: string, /** * */ reply_message: MessagesForeignMessage, /** * Message text */ text: string, /** * Date when the message has been updated in Unixtime */ update_time: number, /** * Was the audio message inside already listened by you */ was_listened: boolean, /** * Date when the message has been pinned in Unixtime */ pinned_at: number } export interface MessagesMessageAction { /** * Message ID */ conversation_message_id: number, /** * Email address for chat_invite_user or chat_kick_user actions */ email: string, /** * User or email peer ID */ member_id: number, /** * Message body of related message */ message: string, /** * */ photo: MessagesMessageActionPhoto, /** * New chat title for chat_create and chat_title_update actions */ text: string, /** * */ type: MessagesMessageActionStatus } export interface MessagesMessageActionPhoto { /** * URL of the preview image with 100px in width */ photo_100: string, /** * URL of the preview image with 200px in width */ photo_200: string, /** * URL of the preview image with 50px in width */ photo_50: string } export type MessagesMessageActionStatus = string export interface MessagesMessageAttachment { /** * */ audio: AudioAudio, /** * */ audio_message: MessagesAudioMessage, /** * */ call: CallsCall, /** * */ doc: DocsDoc, /** * */ gift: GiftsLayout, /** * */ graffiti: MessagesGraffiti, /** * */ link: BaseLink, /** * */ market: MarketMarketItem, /** * */ market_market_album: MarketMarketAlbum, /** * */ photo: PhotosPhoto, /** * */ sticker: BaseSticker, /** * */ story: StoriesStory, /** * */ type: MessagesMessageAttachmentType, /** * */ video: VideoVideo, /** * */ wall: WallWallpostFull, /** * */ wall_reply: WallWallComment, /** * */ poll: PollsPoll } export type MessagesMessageAttachmentType = string export interface MessagesMessageRequestData { /** * Status of message request */ status: string, /** * Message request sender id */ inviter_id: number, /** * Message request date */ request_date: number } export interface MessagesMessagesArray { /** * */ count: number, /** * */ items: MessagesMessage[] } export interface MessagesOutReadBy { /** * */ count: number, /** * */ member_ids: number[] } export interface MessagesPinnedMessage { /** * */ attachments: MessagesMessageAttachment[], /** * Unique auto-incremented number for all messages with this peer */ conversation_message_id: number, /** * Date when the message has been sent in Unixtime */ date: number, /** * Message author's ID */ from_id: number, /** * Forwarded messages */ fwd_messages: MessagesForeignMessage[], /** * */ geo: BaseGeo, /** * Message ID */ id: number, /** * Peer ID */ peer_id: number, /** * */ reply_message: MessagesForeignMessage, /** * Message text */ text: string, /** * */ keyboard: MessagesKeyboard } export interface MessagesPushSettings { /** * Information whether push notifications are disabled forever */ disabled_forever: boolean, /** * Time until what notifications are disabled */ disabled_until: number, /** * Information whether the sound is on */ no_sound: boolean } export type MessagesTemplateActionTypeNames = string export interface MessagesUserXtrInvitedBy { /** * Returns if a profile is deleted or blocked */ deactivated: string, /** * User first name */ first_name: string, /** * Returns if a profile is hidden. */ hidden: number, /** * User ID */ id: number, /** * User last name */ last_name: string, /** * */ can_access_closed: boolean, /** * */ is_closed: boolean, /** * User sex */ sex: BaseSex, /** * Domain name of the user's page */ screen_name: string, /** * URL of square photo of the user with 50 pixels in width */ photo_50: string, /** * URL of square photo of the user with 100 pixels in width */ photo_100: string, /** * */ online_info: UsersOnlineInfo, /** * Information whether the user is online */ online: BaseBoolInt, /** * Information whether the user is online in mobile site or application */ online_mobile: BaseBoolInt, /** * Application ID */ online_app: number, /** * Information whether the user is verified */ verified: BaseBoolInt, /** * Information whether the user has a "fire" pictogram. */ trending: BaseBoolInt, /** * */ friend_status: FriendsFriendStatusStatus, /** * */ mutual: FriendsRequestsMutual, /** * */ type: UsersUserType, /** * ID of the inviter */ invited_by: number } export type NewsfeedCommentsFilters = string export interface NewsfeedEventActivity { /** * address of event */ address: string, /** * text of attach */ button_text: string, /** * array of friends ids */ friends: number[], /** * Current user's member status */ member_status: GroupsGroupFullMemberStatus, /** * text of attach */ text: string, /** * event start time */ time: number } export type NewsfeedFilters = string export type NewsfeedIgnoreItemType = string export interface NewsfeedItemAudio { /** * */ type: NewsfeedNewsfeedItemType, /** * Item source ID */ source_id: number, /** * Date when item has been added in Unixtime */ date: number, /** * */ audio: NewsfeedItemAudioAudio, /** * Post ID */ post_id: number } export interface NewsfeedItemAudioAudio { /** * Audios number */ count: number, /** * */ items: AudioAudio[] } export interface NewsfeedItemBase { /** * */ type: NewsfeedNewsfeedItemType, /** * Item source ID */ source_id: number, /** * Date when item has been added in Unixtime */ date: number } export interface NewsfeedItemDigest { /** * */ type: NewsfeedNewsfeedItemType, /** * Item source ID */ source_id: number, /** * Date when item has been added in Unixtime */ date: number, /** * id of feed in digest */ feed_id: string, /** * */ items: NewsfeedItemDigestItem[], /** * */ main_post_ids: string[], /** * type of digest */ template: string, /** * */ header: NewsfeedItemDigestHeader, /** * */ footer: NewsfeedItemDigestFooter, /** * */ track_code: string } export interface NewsfeedItemDigestButton { /** * */ title: string, /** * */ style: string } export interface NewsfeedItemDigestFooter { /** * */ style: string, /** * text for invite to enable smart feed */ text: string, /** * */ button: NewsfeedItemDigestButton } export interface NewsfeedItemDigestFullItem { /** * */ text: string, /** * */ source_name: string, /** * */ attachment_index: number, /** * */ attachment: WallWallpostAttachment, /** * */ style: string, /** * */ post: WallWallpost } export interface NewsfeedItemDigestHeader { /** * Title of the header */ title: string, /** * Subtitle of the header, when title have two strings */ subtitle: string, /** * */ style: string, /** * */ button: NewsfeedItemDigestButton } export type NewsfeedItemDigestItem = WallWallpost export interface NewsfeedItemFriend { /** * */ type: NewsfeedNewsfeedItemType, /** * Item source ID */ source_id: number, /** * Date when item has been added in Unixtime */ date: number, /** * */ friends: NewsfeedItemFriendFriends } export interface NewsfeedItemFriendFriends { /** * Number of friends has been added */ count: number, /** * */ items: BaseUserId[] } export interface NewsfeedItemHolidayRecommendationsBlockHeader { /** * Title of the header */ title: string, /** * Subtitle of the header */ subtitle: string, /** * */ image: BaseImage[], /** * */ action: BaseLinkButtonAction } export interface NewsfeedItemPhoto { /** * Index of current carousel element */ carousel_offset: number, /** * */ type: NewsfeedNewsfeedItemType, /** * Item source ID */ source_id: number, /** * Date when item has been added in Unixtime */ date: number, /** * */ photos: NewsfeedItemPhotoPhotos, /** * Post ID */ post_id: number } export interface NewsfeedItemPhotoPhotos { /** * Photos number */ count: number, /** * */ items: NewsfeedNewsfeedPhoto[] } export interface NewsfeedItemPhotoTag { /** * Index of current carousel element */ carousel_offset: number, /** * */ type: NewsfeedNewsfeedItemType, /** * Item source ID */ source_id: number, /** * Date when item has been added in Unixtime */ date: number, /** * */ photo_tags: NewsfeedItemPhotoTagPhotoTags, /** * Post ID */ post_id: number } export interface NewsfeedItemPhotoTagPhotoTags { /** * Tags number */ count: number, /** * */ items: NewsfeedNewsfeedPhoto[] } export interface NewsfeedItemPromoButton { /** * */ type: NewsfeedNewsfeedItemType, /** * Item source ID */ source_id: number, /** * Date when item has been added in Unixtime */ date: number, /** * */ text: string, /** * */ title: string, /** * */ action: NewsfeedItemPromoButtonAction, /** * */ images: NewsfeedItemPromoButtonImage[], /** * */ track_code: string } export interface NewsfeedItemPromoButtonAction { /** * */ url: string, /** * */ type: string, /** * */ target: string } export interface NewsfeedItemPromoButtonImage { /** * */ width: number, /** * */ height: number, /** * */ url: string } export interface NewsfeedItemTopic { /** * */ type: NewsfeedNewsfeedItemType, /** * Item source ID */ source_id: number, /** * Date when item has been added in Unixtime */ date: number, /** * */ comments: BaseCommentsInfo, /** * */ likes: BaseLikesInfo, /** * Topic post ID */ post_id: number, /** * Post text */ text: string } export interface NewsfeedItemVideo { /** * Index of current carousel element */ carousel_offset: number, /** * */ type: NewsfeedNewsfeedItemType, /** * Item source ID */ source_id: number, /** * Date when item has been added in Unixtime */ date: number, /** * */ video: NewsfeedItemVideoVideo } export interface NewsfeedItemVideoVideo { /** * Tags number */ count: number, /** * */ items: VideoVideo[] } export interface NewsfeedItemWallpost { /** * Index of current carousel element */ carousel_offset: number, /** * */ type: NewsfeedNewsfeedItemType, /** * Item source ID */ source_id: number, /** * Date when item has been added in Unixtime */ date: number, /** * */ activity: NewsfeedEventActivity, /** * */ attachments: WallWallpostAttachment[], /** * */ comments: BaseCommentsInfo, /** * */ copy_history: WallWallpost[], /** * */ feedback: NewsfeedItemWallpostFeedback, /** * */ geo: BaseGeo, /** * Information whether the post in favorites list */ is_favorite: boolean, /** * */ likes: BaseLikesInfo, /** * Information whether the post is marked as ads */ marked_as_ads: BaseBoolInt, /** * Post ID */ post_id: number, /** * */ post_source: WallPostSource, /** * */ post_type: NewsfeedItemWallpostType, /** * */ reposts: BaseRepostsInfo, /** * Post signer ID */ signer_id: number, /** * Post text */ text: string, /** * Count of views */ views: WallViews, /** * Preview length control parameter */ short_text_rate: number } export interface NewsfeedItemWallpostFeedback { /** * */ type: NewsfeedItemWallpostFeedbackType, /** * */ question: string, /** * */ answers: NewsfeedItemWallpostFeedbackAnswer[], /** * */ stars_count: number, /** * */ gratitude: string } export interface NewsfeedItemWallpostFeedbackAnswer { /** * */ title: string, /** * */ id: string } export type NewsfeedItemWallpostFeedbackType = string export type NewsfeedItemWallpostType = string export interface NewsfeedList { /** * List ID */ id: number, /** * List title */ title: string } export interface NewsfeedListFull { /** * List ID */ id: number, /** * List title */ title: string, /** * Information whether reposts hiding is enabled */ no_reposts: BaseBoolInt, /** * */ source_ids: number[] } export interface NewsfeedNewsfeedItem { } export type NewsfeedNewsfeedItemType = string export interface NewsfeedNewsfeedPhoto { /** * Access key for the photo */ access_key: string, /** * Album ID */ album_id: number, /** * Date when uploaded */ date: number, /** * Original photo height */ height: number, /** * Photo ID */ id: number, /** * */ images: PhotosImage[], /** * Latitude */ lat: number, /** * Longitude */ long: number, /** * Photo owner's ID */ owner_id: number, /** * URL of image with 2560 px width */ photo_256: string, /** * Information whether current user can comment the photo */ can_comment: BaseBoolInt, /** * */ place: string, /** * Post ID */ post_id: number, /** * */ sizes: PhotosPhotoSizes[], /** * Photo caption */ text: string, /** * ID of the user who have uploaded the photo */ user_id: number, /** * Original photo width */ width: number, /** * Whether photo has attached tag links */ has_tags: boolean, /** * */ restrictions: MediaRestriction, /** * */ likes: BaseLikes, /** * */ comments: BaseObjectCount, /** * Information whether current user can repost the photo */ can_repost: BaseBoolInt } export interface NotesNote { /** * */ read_comments: number, /** * Information whether current user can comment the note */ can_comment: BaseBoolInt, /** * Comments number */ comments: number, /** * Date when the note has been created in Unixtime */ date: number, /** * Note ID */ id: number, /** * Note owner's ID */ owner_id: number, /** * Note text */ text: string, /** * Note text in wiki format */ text_wiki: string, /** * Note title */ title: string, /** * URL of the page with note preview */ view_url: string } export interface NotesNoteComment { /** * Date when the comment has beed added in Unixtime */ date: number, /** * Comment ID */ id: number, /** * Comment text */ message: string, /** * Note ID */ nid: number, /** * Note ID */ oid: number, /** * ID of replied comment */ reply_to: number, /** * Comment author's ID */ uid: number } export interface NotificationsFeedback { /** * */ attachments: WallWallpostAttachment[], /** * Reply author's ID */ from_id: number, /** * */ geo: BaseGeo, /** * Item ID */ id: number, /** * */ likes: BaseLikesInfo, /** * Reply text */ text: string, /** * Wall owner's ID */ to_id: number } export interface NotificationsNotification { /** * Date when the event has been occurred */ date: number, /** * */ feedback: NotificationsFeedback, /** * */ parent: NotificationsNotificationParent, /** * */ reply: NotificationsReply, /** * Notification type */ type: string } export type NotificationsNotificationItem = any export interface NotificationsNotificationParent { /** * */ attachments: WallWallpostAttachment[], /** * Number of comments */ comments: number, /** * ID of the source post owner */ copy_owner_id: number, /** * ID of the source post */ copy_post_id: number, /** * Date when the comment has been added in Unixtime */ date: number, /** * Post author ID */ from_id: number, /** * */ geo: WallGeo, /** * Comment ID */ id: number, /** * Whether video is added to bookmarks */ is_favorite: boolean, /** * */ likes: BaseLikes, /** * Post ID */ post_id: number, /** * */ post_source: WallPostSource, /** * */ post_type: WallPostType, /** * */ reposts: BaseRepostsInfo, /** * Post signer ID */ signer_id: number, /** * Comment text */ text: string, /** * Wall owner's ID */ to_id: number, /** * Video access key */ access_key: string, /** * Album ID */ album_id: number, /** * Video height */ height: number, /** * */ images: PhotosImage[], /** * Latitude */ lat: number, /** * Longitude */ long: number, /** * Author ID */ owner_id: number, /** * URL of image with 2560 px width */ photo_256: string, /** * Information whether current user can comment the video */ can_comment: BaseBoolInt, /** * */ place: string, /** * */ sizes: PhotosPhotoSizes[], /** * Id of the user who uploaded the video if it was uploaded to a group by member */ user_id: number, /** * Video width */ width: number, /** * Whether photo has attached tag links */ has_tags: boolean, /** * */ restrictions: MediaRestriction, /** * Date when the topic has been created in Unixtime */ created: number, /** * Creator ID */ created_by: number, /** * Information whether the topic is closed */ is_closed: BaseBoolInt, /** * Information whether the topic is fixed */ is_fixed: BaseBoolInt, /** * Video title */ title: string, /** * Date when the topic has been updated in Unixtime */ updated: number, /** * ID of user who updated the topic */ updated_by: number, /** * Date when the video has been added in Unixtime */ adding_date: number, /** * Information whether current user can edit the video */ can_edit: BaseBoolInt, /** * Information whether current user can like the video */ can_like: BaseBoolInt, /** * Information whether current user can repost the video */ can_repost: BaseBoolInt, /** * Information whether current user can subscribe to author of the video */ can_subscribe: BaseBoolInt, /** * Information whether current user can add the video to favourites */ can_add_to_faves: BaseBoolInt, /** * Information whether current user can add the video */ can_add: BaseBoolInt, /** * Information whether current user can attach action button to the video */ can_attach_link: BaseBoolInt, /** * 1 if video is private */ is_private: BaseBoolInt, /** * Video description */ description: string, /** * Video duration in seconds */ duration: number, /** * */ image: VideoVideoImage[], /** * */ first_frame: VideoVideoImage[], /** * Video embed URL */ player: string, /** * Returns if the video is processing */ processing: BasePropertyExists, /** * 1 if video is being converted */ converting: BaseBoolInt, /** * */ restriction: MediaRestriction, /** * 1 if video is added to user's albums */ added: BaseBoolInt, /** * 1 if user is subscribed to author of the video */ is_subscribed: BaseBoolInt, /** * */ track_code: string, /** * Information whether the video is repeated */ repeat: BasePropertyExists, /** * */ type: string, /** * Number of views */ views: number, /** * If video is external, number of views on vk */ local_views: number, /** * Restriction code */ content_restricted: number, /** * Restriction text */ content_restricted_message: string, /** * Live donations balance */ balance: number, /** * Live stream status */ live_status: string, /** * 1 if the video is a live stream */ live: BasePropertyExists, /** * 1 if the video is an upcoming stream */ upcoming: BasePropertyExists, /** * Date in Unixtime when the live stream is scheduled to start by the author */ live_start_time: number, /** * Whether current user is subscribed to the upcoming live stream notification (if not subscribed to the author) */ live_notify: BaseBoolInt, /** * Number of spectators of the stream */ spectators: number, /** * External platform */ platform: string, /** * */ photo: PhotosPhoto, /** * */ post: WallWallpost, /** * */ topic: BoardTopic, /** * */ video: VideoVideo } export interface NotificationsNotificationsComment { /** * Date when the comment has been added in Unixtime */ date: number, /** * Comment ID */ id: number, /** * Author ID */ owner_id: number, /** * */ photo: PhotosPhoto, /** * */ post: WallWallpost, /** * Comment text */ text: string, /** * */ topic: BoardTopic, /** * */ video: VideoVideo } export interface NotificationsReply { /** * Date when the reply has been created in Unixtime */ date: number, /** * Reply ID */ id: number, /** * Reply text */ text: number } export interface NotificationsSendMessageError { /** * Error code */ code: number, /** * Error description */ description: string } export interface NotificationsSendMessageItem { /** * User ID */ user_id: number, /** * Notification status */ status: boolean, /** * */ error: NotificationsSendMessageError } export interface OauthError { /** * Error type */ error: string, /** * Error description */ error_description: string, /** * URI for validation */ redirect_uri: string } export interface OrdersAmount { /** * */ amounts: OrdersAmountItem[], /** * Currency name */ currency: string } export interface OrdersAmountItem { /** * Votes amount in user's currency */ amount: number, /** * Amount description */ description: string, /** * Votes number */ votes: string } export interface OrdersOrder { /** * Amount */ amount: number, /** * App order ID */ app_order_id: number, /** * Cancel transaction ID */ cancel_transaction_id: number, /** * Date of creation in Unixtime */ date: number, /** * Order ID */ id: number, /** * Order item */ item: string, /** * Receiver ID */ receiver_id: number, /** * Order status */ status: string, /** * Transaction ID */ transaction_id: number, /** * User ID */ user_id: number } export interface OrdersSubscription { /** * Cancel reason */ cancel_reason: string, /** * Date of creation in Unixtime */ create_time: number, /** * Subscription ID */ id: number, /** * Subscription order item */ item_id: string, /** * Date of next bill in Unixtime */ next_bill_time: number, /** * Pending cancel state */ pending_cancel: boolean, /** * Subscription period */ period: number, /** * Date of last period start in Unixtime */ period_start_time: number, /** * Subscription price */ price: number, /** * Subscription status */ status: string, /** * Is test subscription */ test_mode: boolean, /** * Date of trial expire in Unixtime */ trial_expire_time: number, /** * Date of last change in Unixtime */ update_time: number } export interface OwnerState { /** * */ state: number, /** * wiki text to describe user state */ description: string } export type PagesPrivacySettings = number export interface PagesWikipage { /** * Page creator ID */ creator_id: number, /** * Page creator name */ creator_name: number, /** * Last editor ID */ editor_id: number, /** * Last editor name */ editor_name: string, /** * Community ID */ group_id: number, /** * Page ID */ id: number, /** * Page title */ title: string, /** * Views number */ views: number, /** * Edit settings of the page */ who_can_edit: PagesPrivacySettings, /** * View settings of the page */ who_can_view: PagesPrivacySettings } export interface PagesWikipageFull { /** * Date when the page has been created in Unixtime */ created: number, /** * Page creator ID */ creator_id: number, /** * Information whether current user can edit the page */ current_user_can_edit: BaseBoolInt, /** * Information whether current user can edit the page access settings */ current_user_can_edit_access: BaseBoolInt, /** * Date when the page has been edited in Unixtime */ edited: number, /** * Last editor ID */ editor_id: number, /** * Community ID */ group_id: number, /** * Page content, HTML */ html: string, /** * Page ID */ id: number, /** * Page content, wiki */ source: string, /** * Page title */ title: string, /** * URL of the page preview */ view_url: string, /** * Views number */ views: number, /** * Edit settings of the page */ who_can_edit: PagesPrivacySettings, /** * View settings of the page */ who_can_view: PagesPrivacySettings } export interface PagesWikipageHistory { /** * Version ID */ id: number, /** * Page size in bytes */ length: number, /** * Date when the page has been edited in Unixtime */ date: number, /** * Last editor ID */ editor_id: number, /** * Last editor name */ editor_name: string } export interface PhotosCommentXtrPid { /** * */ attachments: WallCommentAttachment[], /** * Date when the comment has been added in Unixtime */ date: number, /** * Author ID */ from_id: number, /** * Comment ID */ id: number, /** * */ likes: BaseLikesInfo, /** * Photo ID */ pid: number, /** * Replied comment ID */ reply_to_comment: number, /** * Replied user ID */ reply_to_user: number, /** * Comment text */ text: string, /** * */ parents_stack: number[], /** * */ thread: CommentThread } export interface PhotosImage { /** * Height of the photo in px. */ height: number, /** * */ type: PhotosImageType, /** * Photo URL. */ url: string, /** * Width of the photo in px. */ width: number } export type PhotosImageType = string export interface PhotosMarketAlbumUploadResponse { /** * Community ID */ gid: number, /** * Uploading hash */ hash: string, /** * Uploaded photo data */ photo: string, /** * Upload server number */ server: number } export interface PhotosMarketUploadResponse { /** * Crop data */ crop_data: string, /** * Crop hash */ crop_hash: string, /** * Community ID */ group_id: number, /** * Uploading hash */ hash: string, /** * Uploaded photo data */ photo: string, /** * Upload server number */ server: number } export interface PhotosMessageUploadResponse { /** * Uploading hash */ hash: string, /** * Uploaded photo data */ photo: string, /** * Upload server number */ server: number } export interface PhotosOwnerUploadResponse { /** * Uploading hash */ hash: string, /** * Uploaded photo data */ photo: string, /** * Upload server number */ server: number } export interface PhotosPhoto { /** * Access key for the photo */ access_key: string, /** * Album ID */ album_id: number, /** * Date when uploaded */ date: number, /** * Original photo height */ height: number, /** * Photo ID */ id: number, /** * */ images: PhotosImage[], /** * Latitude */ lat: number, /** * Longitude */ long: number, /** * Photo owner's ID */ owner_id: number, /** * URL of image with 2560 px width */ photo_256: string, /** * Information whether current user can comment the photo */ can_comment: BaseBoolInt, /** * */ place: string, /** * Post ID */ post_id: number, /** * */ sizes: PhotosPhotoSizes[], /** * Photo caption */ text: string, /** * ID of the user who have uploaded the photo */ user_id: number, /** * Original photo width */ width: number, /** * Whether photo has attached tag links */ has_tags: boolean, /** * */ restrictions: MediaRestriction } export interface PhotosPhotoAlbum { /** * Date when the album has been created in Unixtime */ created: number, /** * Photo album description */ description: string, /** * Photo album ID */ id: number, /** * Album owner's ID */ owner_id: number, /** * Photos number */ size: number, /** * */ thumb: PhotosPhoto, /** * Photo album title */ title: string, /** * Date when the album has been updated last time in Unixtime */ updated: number } export interface PhotosPhotoAlbumFull { /** * Information whether current user can upload photo to the album */ can_upload: BaseBoolInt, /** * Information whether album comments are disabled */ comments_disabled: BaseBoolInt, /** * Date when the album has been created in Unixtime */ created: number, /** * Photo album description */ description: string, /** * Photo album ID */ id: number, /** * Album owner's ID */ owner_id: number, /** * Photos number */ size: number, /** * */ sizes: PhotosPhotoSizes[], /** * Thumb photo ID */ thumb_id: number, /** * Information whether the album thumb is last photo */ thumb_is_last: BaseBoolInt, /** * URL of the thumb image */ thumb_src: string, /** * Photo album title */ title: string, /** * Date when the album has been updated last time in Unixtime */ updated: number, /** * Information whether only community administrators can upload photos */ upload_by_admins_only: BaseBoolInt } export type PhotosPhotoFalseable = any export interface PhotosPhotoFull { /** * Access key for the photo */ access_key: string, /** * Album ID */ album_id: number, /** * Information whether current user can comment the photo */ can_comment: BaseBoolInt, /** * Date when uploaded */ date: number, /** * Original photo height */ height: number, /** * Photo ID */ id: number, /** * */ images: PhotosImage[], /** * Latitude */ lat: number, /** * */ likes: BaseLikes, /** * */ reposts: BaseRepostsInfo, /** * */ comments: BaseObjectCount, /** * Longitude */ long: number, /** * Photo owner's ID */ owner_id: number, /** * Post ID */ post_id: number, /** * */ tags: BaseObjectCount, /** * Photo caption */ text: string, /** * ID of the user who have uploaded the photo */ user_id: number, /** * Original photo width */ width: number } export interface PhotosPhotoFullXtrRealOffset { /** * Access key for the photo */ access_key: string, /** * Album ID */ album_id: number, /** * */ can_comment: BaseBoolInt, /** * */ comments: BaseObjectCount, /** * Date when uploaded */ date: number, /** * Original photo height */ height: number, /** * Returns if the photo is hidden above the wall */ hidden: BasePropertyExists, /** * Photo ID */ id: number, /** * Latitude */ lat: number, /** * */ likes: BaseLikes, /** * Longitude */ long: number, /** * Photo owner's ID */ owner_id: number, /** * URL of image with 1280 px width */ photo_1280: string, /** * URL of image with 130 px width */ photo_130: string, /** * URL of image with 2560 px width */ photo_2560: string, /** * URL of image with 604 px width */ photo_604: string, /** * URL of image with 75 px width */ photo_75: string, /** * URL of image with 807 px width */ photo_807: string, /** * Post ID */ post_id: number, /** * Real position of the photo */ real_offset: number, /** * */ reposts: BaseObjectCount, /** * */ sizes: PhotosPhotoSizes[], /** * */ tags: BaseObjectCount, /** * Photo caption */ text: string, /** * ID of the user who have uploaded the photo */ user_id: number, /** * Original photo width */ width: number } export interface PhotosPhotoSizes { /** * Height in px */ height: number, /** * URL of the image */ url: string, /** * URL of the image */ src: string, /** * */ type: PhotosPhotoSizesType, /** * Width in px */ width: number } export type PhotosPhotoSizesType = string export interface PhotosPhotoTag { /** * Date when tag has been added in Unixtime */ date: number, /** * Tag ID */ id: number, /** * ID of the tag creator */ placer_id: number, /** * Tag description */ tagged_name: string, /** * Tagged description. */ description: string, /** * Tagged user ID */ user_id: number, /** * Information whether the tag is reviewed */ viewed: BaseBoolInt, /** * Coordinate X of the left upper corner */ x: number, /** * Coordinate X of the right lower corner */ x2: number, /** * Coordinate Y of the left upper corner */ y: number, /** * Coordinate Y of the right lower corner */ y2: number } export interface PhotosPhotoUpload { /** * Album ID */ album_id: number, /** * URL to upload photo */ upload_url: string, /** * Fallback URL if upload_url returned error */ fallback_upload_url: string, /** * User ID */ user_id: number, /** * Group ID */ group_id: number } export interface PhotosPhotoUploadResponse { /** * Album ID */ aid: number, /** * Uploading hash */ hash: string, /** * Uploaded photo data */ photo: string, /** * Uploaded photos data */ photos_list: string, /** * Upload server number */ server: number } export interface PhotosPhotoXtrRealOffset { /** * Access key for the photo */ access_key: string, /** * Album ID */ album_id: number, /** * Date when uploaded */ date: number, /** * Original photo height */ height: number, /** * Returns if the photo is hidden above the wall */ hidden: BasePropertyExists, /** * Photo ID */ id: number, /** * Latitude */ lat: number, /** * Longitude */ long: number, /** * Photo owner's ID */ owner_id: number, /** * URL of image with 1280 px width */ photo_1280: string, /** * URL of image with 130 px width */ photo_130: string, /** * URL of image with 2560 px width */ photo_2560: string, /** * URL of image with 604 px width */ photo_604: string, /** * URL of image with 75 px width */ photo_75: string, /** * URL of image with 807 px width */ photo_807: string, /** * Post ID */ post_id: number, /** * Real position of the photo */ real_offset: number, /** * */ sizes: PhotosPhotoSizes[], /** * Photo caption */ text: string, /** * ID of the user who have uploaded the photo */ user_id: number, /** * Original photo width */ width: number } export interface PhotosPhotoXtrTagInfo { /** * Access key for the photo */ access_key: string, /** * Album ID */ album_id: number, /** * Date when uploaded */ date: number, /** * Original photo height */ height: number, /** * Photo ID */ id: number, /** * Latitude */ lat: number, /** * Longitude */ long: number, /** * Photo owner's ID */ owner_id: number, /** * URL of image with 1280 px width */ photo_1280: string, /** * URL of image with 130 px width */ photo_130: string, /** * URL of image with 2560 px width */ photo_2560: string, /** * URL of image with 604 px width */ photo_604: string, /** * URL of image with 75 px width */ photo_75: string, /** * URL of image with 807 px width */ photo_807: string, /** * ID of the tag creator */ placer_id: number, /** * Post ID */ post_id: number, /** * */ sizes: PhotosPhotoSizes[], /** * Date when tag has been added in Unixtime */ tag_created: number, /** * Tag ID */ tag_id: number, /** * Photo caption */ text: string, /** * ID of the user who have uploaded the photo */ user_id: number, /** * Original photo width */ width: number } export interface PhotosTagsSuggestionItem { /** * */ title: string, /** * */ caption: string, /** * */ type: string, /** * */ buttons: PhotosTagsSuggestionItemButton[], /** * */ photo: PhotosPhoto, /** * */ tags: PhotosPhotoTag[], /** * */ track_code: string } export interface PhotosTagsSuggestionItemButton { /** * */ title: string, /** * */ action: string, /** * */ style: string } export interface PhotosWallUploadResponse { /** * Uploading hash */ hash: string, /** * Uploaded photo data */ photo: string, /** * Upload server number */ server: number } export interface PollsAnswer { /** * Answer ID */ id: number, /** * Answer rate in percents */ rate: number, /** * Answer text */ text: string, /** * Votes number */ votes: number } export interface PollsBackground { /** * Gradient angle with 0 on positive X axis */ angle: number, /** * Hex color code without # */ color: string, /** * Original height of pattern tile */ height: number, /** * */ id: number, /** * */ name: string, /** * Pattern tiles */ images: BaseImage[], /** * Gradient points */ points: BaseGradientPoint[], /** * */ type: string, /** * Original with of pattern tile */ width: number } export interface PollsFriend { /** * */ id: number } export interface PollsPoll { /** * */ anonymous: PollsPollAnonymous, /** * */ friends: PollsFriend[], /** * Information whether the poll with multiple choices */ multiple: boolean, /** * Current user's answer ID */ answer_id: number, /** * */ end_date: number, /** * Current user's answer IDs */ answer_ids: number[], /** * */ closed: boolean, /** * */ is_board: boolean, /** * */ can_edit: boolean, /** * */ can_vote: boolean, /** * */ can_report: boolean, /** * */ can_share: boolean, /** * */ photo: PollsBackground, /** * */ answers: PollsAnswer[], /** * Date when poll has been created in Unixtime */ created: number, /** * Poll ID */ id: number, /** * Poll owner's ID */ owner_id: number, /** * Poll author's ID */ author_id: number, /** * Poll question */ question: string, /** * */ background: PollsBackground, /** * Votes number */ votes: number, /** * */ disable_unvote: boolean } export type PollsPollAnonymous = boolean export interface PollsVoters { /** * Answer ID */ answer_id: number, /** * */ users: PollsVotersUsers } export interface PollsVotersUsers { /** * Votes number */ count: number, /** * */ items: number[] } export interface PrettyCardsPrettyCard { /** * Button key */ button: string, /** * Button text in current language */ button_text: string, /** * Card ID (long int returned as string) */ card_id: string, /** * */ images: BaseImage[], /** * Link URL */ link_url: string, /** * Photo ID (format "<owner_id>_<media_id>") */ photo: string, /** * Price if set (decimal number returned as string) */ price: string, /** * Old price if set (decimal number returned as string) */ price_old: string, /** * Title */ title: string } export interface SearchHint { /** * */ app: AppsApp, /** * Object description */ description: string, /** * Information whether the object has been found globally */ global: BaseBoolInt, /** * */ group: GroupsGroup, /** * */ profile: UsersUserMin, /** * */ section: SearchHintSection, /** * */ type: SearchHintType } export type SearchHintSection = string export type SearchHintType = string export interface SecureLevel { /** * Level */ level: number, /** * User ID */ uid: number } export interface SecureSmsNotification { /** * Application ID */ app_id: string, /** * Date when message has been sent in Unixtime */ date: string, /** * Notification ID */ id: string, /** * Messsage text */ message: string, /** * User ID */ user_id: string } export interface SecureTokenChecked { /** * Date when access_token has been generated in Unixtime */ date: number, /** * Date when access_token will expire in Unixtime */ expire: number, /** * Returns if successfully processed */ success: number, /** * User ID */ user_id: number } export interface SecureTransaction { /** * Transaction date in Unixtime */ date: number, /** * Transaction ID */ id: number, /** * From ID */ uid_from: number, /** * To ID */ uid_to: number, /** * Votes number */ votes: number } export interface StatsActivity { /** * Comments number */ comments: number, /** * Reposts number */ copies: number, /** * Hidden from news count */ hidden: number, /** * Likes number */ likes: number, /** * New subscribers count */ subscribed: number, /** * Unsubscribed count */ unsubscribed: number } export interface StatsCity { /** * Visitors number */ count: number, /** * City name */ name: string, /** * City ID */ value: number } export interface StatsCountry { /** * Country code */ code: string, /** * Visitors number */ count: number, /** * Country name */ name: string, /** * Country ID */ value: number } export interface StatsPeriod { /** * */ activity: StatsActivity, /** * Unix timestamp */ period_from: number, /** * Unix timestamp */ period_to: number, /** * */ reach: StatsReach, /** * */ visitors: StatsViews } export interface StatsReach { /** * */ age: StatsSexAge[], /** * */ cities: StatsCity[], /** * */ countries: StatsCountry[], /** * Reach count from mobile devices */ mobile_reach: number, /** * Reach count */ reach: number, /** * Subscribers reach count */ reach_subscribers: number, /** * */ sex: StatsSexAge[], /** * */ sex_age: StatsSexAge[] } export interface StatsSexAge { /** * Visitors number */ count: number, /** * Sex/age value */ value: string, /** * */ reach: number, /** * */ reach_subscribers: number, /** * */ count_subscribers: number } export interface StatsViews { /** * */ age: StatsSexAge[], /** * */ cities: StatsCity[], /** * */ countries: StatsCountry[], /** * Number of views from mobile devices */ mobile_views: number, /** * */ sex: StatsSexAge[], /** * */ sex_age: StatsSexAge[], /** * Views number */ views: number, /** * Visitors number */ visitors: number } export interface StatsWallpostStat { /** * */ post_id: number, /** * Hidings number */ hide: number, /** * People have joined the group */ join_group: number, /** * Link clickthrough */ links: number, /** * Subscribers reach */ reach_subscribers: number, /** * */ reach_subscribers_count: number, /** * Total reach */ reach_total: number, /** * */ reach_total_count: number, /** * */ reach_viral: number, /** * */ reach_ads: number, /** * Reports number */ report: number, /** * Clickthrough to community */ to_group: number, /** * Unsubscribed members */ unsubscribe: number, /** * */ sex_age: StatsSexAge[] } export interface StatusStatus { /** * Status text */ text: string, /** * */ audio: AudioAudio } export interface StorageValue { /** * */ key: string, /** * */ value: string } export interface StoriesClickableArea { /** * */ x: number, /** * */ y: number } export interface StoriesClickableSticker { /** * */ clickable_area: StoriesClickableArea[], /** * Clickable sticker ID */ id: number, /** * */ hashtag: string, /** * */ link_object: BaseLink, /** * */ mention: string, /** * */ tooltip_text: string, /** * */ owner_id: number, /** * */ story_id: number, /** * */ question: string, /** * */ question_button: string, /** * */ place_id: number, /** * */ market_item: MarketMarketItem, /** * */ audio: AudioAudio, /** * */ audio_start_time: number, /** * */ style: string, /** * */ type: string, /** * */ subtype: string, /** * */ post_owner_id: number, /** * */ post_id: number, /** * */ poll: PollsPoll, /** * Color, hex format */ color: string, /** * Sticker ID */ sticker_id: number, /** * Sticker pack ID */ sticker_pack_id: number, /** * */ app: AppsAppMin, /** * Additional context for app sticker */ app_context: string, /** * Whether current user has unread interaction with this app */ has_new_interactions: boolean, /** * Whether current user allowed broadcast notify from this app */ is_broadcast_notify_allowed: boolean, /** * */ situational_theme_id: number, /** * */ situational_app_url: string } export interface StoriesClickableStickers { /** * */ clickable_stickers: StoriesClickableSticker[], /** * */ original_height: number, /** * */ original_width: number } export interface StoriesFeedItem { /** * Type of Feed Item */ type: string, /** * */ id: string, /** * Author stories */ stories: StoriesStory[], /** * Grouped stories of various authors (for types community_grouped_stories/app_grouped_stories type) */ grouped: StoriesFeedItem[], /** * App, which stories has been grouped (for type app_grouped_stories) */ app: AppsAppMin, /** * Additional data for promo stories (for type promo_stories) */ promo_data: StoriesPromoBlock, /** * */ birthday_user_id: number } export interface StoriesPromoBlock { /** * Promo story title */ name: string, /** * RL of square photo of the story with 50 pixels in width */ photo_50: string, /** * RL of square photo of the story with 100 pixels in width */ photo_100: string, /** * Hide animation for promo story */ not_animated: boolean } export interface StoriesReplies { /** * Replies number. */ count: number, /** * New replies number. */ new: number } export interface StoriesStatLine { /** * */ name: string, /** * */ counter: number, /** * */ is_unavailable: boolean } export interface StoriesStory { /** * Access key for private object. */ access_key: string, /** * Information whether current user can comment the story (0 - no, 1 - yes). */ can_comment: BaseBoolInt, /** * Information whether current user can reply to the story (0 - no, 1 - yes). */ can_reply: BaseBoolInt, /** * Information whether current user can see the story (0 - no, 1 - yes). */ can_see: BaseBoolInt, /** * Information whether current user can like the story. */ can_like: boolean, /** * Information whether current user can share the story (0 - no, 1 - yes). */ can_share: BaseBoolInt, /** * Information whether current user can hide the story (0 - no, 1 - yes). */ can_hide: BaseBoolInt, /** * Date when story has been added in Unixtime. */ date: number, /** * Story expiration time. Unixtime. */ expires_at: number, /** * Story ID. */ id: number, /** * Information whether the story is deleted (false - no, true - yes). */ is_deleted: boolean, /** * Information whether the story is expired (false - no, true - yes). */ is_expired: boolean, /** * */ link: StoriesStoryLink, /** * Story owner's ID. */ owner_id: number, /** * */ parent_story: StoriesStory, /** * Access key for private object. */ parent_story_access_key: string, /** * Parent story ID. */ parent_story_id: number, /** * Parent story owner's ID. */ parent_story_owner_id: number, /** * */ photo: PhotosPhoto, /** * Replies counters to current story. */ replies: StoriesReplies, /** * Information whether current user has seen the story or not (0 - no, 1 - yes). */ seen: BaseBoolInt, /** * */ type: StoriesStoryType, /** * */ clickable_stickers: StoriesClickableStickers, /** * */ video: VideoVideo, /** * Views number. */ views: number, /** * Information whether story has question sticker and current user can send question to the author */ can_ask: BaseBoolInt, /** * Information whether story has question sticker and current user can send anonymous question to the author */ can_ask_anonymous: BaseBoolInt, /** * */ narratives_count: number, /** * */ first_narrative_title: string, /** * */ birthday_wish_user_id: number, /** * */ can_use_in_narrative: boolean } export interface StoriesStoryLink { /** * Link text */ text: string, /** * Link URL */ url: string } export interface StoriesStoryStats { /** * */ answer: StoriesStoryStatsStat, /** * */ bans: StoriesStoryStatsStat, /** * */ open_link: StoriesStoryStatsStat, /** * */ replies: StoriesStoryStatsStat, /** * */ shares: StoriesStoryStatsStat, /** * */ subscribers: StoriesStoryStatsStat, /** * */ views: StoriesStoryStatsStat, /** * */ likes: StoriesStoryStatsStat } export interface StoriesStoryStatsStat { /** * Stat value */ count: number, /** * */ state: StoriesStoryStatsState } export type StoriesStoryStatsState = string export type StoriesStoryType = string export type StoriesUploadLinkText = string export interface StoriesViewersItem { /** * user has like for this object */ is_liked: boolean, /** * user id */ user_id: number, /** * */ user: UsersUserFull } export interface UsersCareer { /** * City ID */ city_id: number, /** * City name */ city_name: string, /** * Company name */ company: string, /** * Country ID */ country_id: number, /** * From year */ from: number, /** * Community ID */ group_id: number, /** * Career ID */ id: number, /** * Position */ position: string, /** * Till year */ until: number } export interface UsersExports { /** * */ facebook: number, /** * */ livejournal: number, /** * */ twitter: number } export type UsersFields = string export interface UsersLastSeen { /** * Type of the platform that used for the last authorization */ platform: number, /** * Last visit date (in Unix time) */ time: number } export interface UsersMilitary { /** * Country ID */ country_id: number, /** * From year */ from: number, /** * Military ID */ id: number, /** * Unit name */ unit: string, /** * Unit ID */ unit_id: number, /** * Till year */ until: number } export interface UsersOccupation { /** * ID of school, university, company group */ id: number, /** * Name of occupation */ name: string, /** * Type of occupation */ type: string } export interface UsersOnlineInfo { /** * Whether you can see real online status of user or not */ visible: boolean, /** * Last time we saw user being active */ last_seen: number, /** * Whether user is currently online or not */ is_online: boolean, /** * Application id from which user is currently online or was last seen online */ app_id: number, /** * Is user online from desktop app or mobile app */ is_mobile: boolean, /** * In case user online is not visible, it indicates approximate timeframe of user online */ status: string } export interface UsersPersonal { /** * User's views on alcohol */ alcohol: number, /** * User's inspired by */ inspired_by: string, /** * */ langs: string[], /** * User's personal priority in life */ life_main: number, /** * User's personal priority in people */ people_main: number, /** * User's political views */ political: number, /** * User's religion */ religion: string, /** * User's religion id */ religion_id: number, /** * User's views on smoking */ smoking: number } export interface UsersRelative { /** * Date of child birthday (format dd.mm.yyyy) */ birth_date: string, /** * Relative ID */ id: number, /** * Name of relative */ name: string, /** * Relative type */ type: string } export interface UsersSchool { /** * City ID */ city: number, /** * School class letter */ schoolClass: string, /** * Country ID */ country: number, /** * School ID */ id: string, /** * School name */ name: string, /** * School type ID */ type: number, /** * School type name */ type_str: string, /** * Year the user started to study */ year_from: number, /** * Graduation year */ year_graduated: number, /** * Year the user finished to study */ year_to: number, /** * */ speciality: string } export interface UsersSubscriptionsItem { } export interface UsersUniversity { /** * Chair ID */ chair: number, /** * Chair name */ chair_name: string, /** * City ID */ city: number, /** * Country ID */ country: number, /** * Education form */ education_form: string, /** * Education status */ education_status: string, /** * Faculty ID */ faculty: number, /** * Faculty name */ faculty_name: string, /** * Graduation year */ graduation: number, /** * University ID */ id: number, /** * University name */ name: string, /** * */ university_group_id: number } export interface UsersUser { /** * Returns if a profile is deleted or blocked */ deactivated: string, /** * User first name */ first_name: string, /** * Returns if a profile is hidden. */ hidden: number, /** * User ID */ id: number, /** * User last name */ last_name: string, /** * */ can_access_closed: boolean, /** * */ is_closed: boolean, /** * User sex */ sex: BaseSex, /** * Domain name of the user's page */ screen_name: string, /** * URL of square photo of the user with 50 pixels in width */ photo_50: string, /** * URL of square photo of the user with 100 pixels in width */ photo_100: string, /** * */ online_info: UsersOnlineInfo, /** * Information whether the user is online */ online: BaseBoolInt, /** * Information whether the user is online in mobile site or application */ online_mobile: BaseBoolInt, /** * Application ID */ online_app: number, /** * Information whether the user is verified */ verified: BaseBoolInt, /** * Information whether the user has a "fire" pictogram. */ trending: BaseBoolInt, /** * */ friend_status: FriendsFriendStatusStatus, /** * */ mutual: FriendsRequestsMutual } export interface UsersUserConnections { /** * User's Skype nickname */ skype: string, /** * User's Facebook account */ facebook: string, /** * User's Facebook name */ facebook_name: string, /** * User's Twitter account */ twitter: string, /** * User's Livejournal account */ livejournal: string, /** * User's Instagram account */ instagram: string } export interface UsersUserCounters { /** * Albums number */ albums: number, /** * Audios number */ audios: number, /** * Followers number */ followers: number, /** * Friends number */ friends: number, /** * Gifts number */ gifts: number, /** * Communities number */ groups: number, /** * Notes number */ notes: number, /** * Online friends number */ online_friends: number, /** * Public pages number */ pages: number, /** * Photos number */ photos: number, /** * Subscriptions number */ subscriptions: number, /** * Number of photos with user */ user_photos: number, /** * Number of videos with user */ user_videos: number, /** * Videos number */ videos: number, /** * */ new_photo_tags: number, /** * */ new_recognition_tags: number, /** * */ mutual_friends: number, /** * */ posts: number, /** * */ articles: number, /** * */ wishes: number, /** * */ podcasts: number, /** * */ clips: number, /** * */ clips_followers: number } export interface UsersUserFull { /** * Returns if a profile is deleted or blocked */ deactivated: string, /** * User first name */ first_name: string, /** * Returns if a profile is hidden. */ hidden: number, /** * User ID */ id: number, /** * User last name */ last_name: string, /** * */ can_access_closed: boolean, /** * */ is_closed: boolean, /** * User sex */ sex: BaseSex, /** * Domain name of the user's page */ screen_name: string, /** * URL of square photo of the user with 50 pixels in width */ photo_50: string, /** * URL of square photo of the user with 100 pixels in width */ photo_100: string, /** * */ online_info: UsersOnlineInfo, /** * Information whether the user is online */ online: BaseBoolInt, /** * Information whether the user is online in mobile site or application */ online_mobile: BaseBoolInt, /** * Application ID */ online_app: number, /** * Information whether the user is verified */ verified: BaseBoolInt, /** * Information whether the user has a "fire" pictogram. */ trending: BaseBoolInt, /** * */ friend_status: FriendsFriendStatusStatus, /** * */ mutual: FriendsRequestsMutual, /** * User's first name in nominative case */ first_name_nom: string, /** * User's first name in genitive case */ first_name_gen: string, /** * User's first name in dative case */ first_name_dat: string, /** * User's first name in accusative case */ first_name_acc: string, /** * User's first name in instrumental case */ first_name_ins: string, /** * User's first name in prepositional case */ first_name_abl: string, /** * User's last name in nominative case */ last_name_nom: string, /** * User's last name in genitive case */ last_name_gen: string, /** * User's last name in dative case */ last_name_dat: string, /** * User's last name in accusative case */ last_name_acc: string, /** * User's last name in instrumental case */ last_name_ins: string, /** * User's last name in prepositional case */ last_name_abl: string, /** * User nickname */ nickname: string, /** * User maiden name */ maiden_name: string, /** * User contact name */ contact_name: string, /** * Domain name of the user's page */ domain: string, /** * User's date of birth */ bdate: string, /** * */ city: BaseCity, /** * */ country: BaseCountry, /** * User's timezone */ timezone: number, /** * */ owner_state: OwnerState, /** * URL of square photo of the user with 200 pixels in width */ photo_200: string, /** * URL of square photo of the user with maximum width */ photo_max: string, /** * URL of user's photo with 200 pixels in width */ photo_200_orig: string, /** * URL of user's photo with 400 pixels in width */ photo_400_orig: string, /** * URL of user's photo of maximum size */ photo_max_orig: string, /** * ID of the user's main photo */ photo_id: string, /** * Information whether the user has main photo */ has_photo: BaseBoolInt, /** * Information whether the user specified his phone number */ has_mobile: BaseBoolInt, /** * Information whether the user is a friend of current user */ is_friend: BaseBoolInt, /** * Information whether current user can comment wall posts */ wall_comments: BaseBoolInt, /** * Information whether current user can post on the user's wall */ can_post: BaseBoolInt, /** * Information whether current user can see other users' audio on the wall */ can_see_all_posts: BaseBoolInt, /** * Information whether current user can see the user's audio */ can_see_audio: BaseBoolInt, /** * */ type: UsersUserType, /** * */ email: string, /** * */ skype: string, /** * */ facebook: string, /** * */ facebook_name: string, /** * */ twitter: string, /** * */ livejournal: string, /** * */ instagram: string, /** * */ test: BaseBoolInt, /** * */ video_live: VideoLiveInfo, /** * */ is_video_live_notifications_blocked: BaseBoolInt, /** * */ is_service: boolean, /** * */ service_description: string, /** * */ photo_rec: PhotosPhotoFalseable, /** * */ photo_medium: PhotosPhotoFalseable, /** * */ photo_medium_rec: PhotosPhotoFalseable, /** * */ photo: string, /** * */ photo_big: string, /** * */ photo_400: string, /** * */ photo_max_size: PhotosPhoto, /** * */ language: string, /** * */ stories_archive_count: number, /** * */ wall_default: string, /** * Information whether current user can call */ can_call: boolean, /** * Information whether current user can see the user's wishes */ can_see_wishes: boolean, /** * Information whether current user can see the user's gifts */ can_see_gifts: BaseBoolInt, /** * */ interests: string, /** * */ books: string, /** * */ tv: string, /** * */ quotes: string, /** * */ about: string, /** * */ games: string, /** * */ movies: string, /** * */ activities: string, /** * */ music: string, /** * Information whether current user can write private message */ can_write_private_message: BaseBoolInt, /** * Information whether current user can send a friend request */ can_send_friend_request: BaseBoolInt, /** * Information whether current user can be invited to the community */ can_be_invited_group: boolean, /** * User's mobile phone number */ mobile_phone: string, /** * User's additional phone number */ home_phone: string, /** * User's website */ site: string, /** * */ status_audio: AudioAudio, /** * User's status */ status: string, /** * User's status */ activity: string, /** * */ last_seen: UsersLastSeen, /** * */ exports: UsersExports, /** * */ crop_photo: BaseCropPhoto, /** * Number of user's followers */ followers_count: number, /** * User level in live streams achievements */ video_live_level: number, /** * Number of user's live streams */ video_live_count: number, /** * Number of user's clips */ clips_count: number, /** * Information whether current user is in the requested user's blacklist. */ blacklisted: BaseBoolInt, /** * Information whether the requested user is in current user's blacklist */ blacklisted_by_me: BaseBoolInt, /** * Information whether the requested user is in faves of current user */ is_favorite: BaseBoolInt, /** * Information whether the requested user is hidden from current user's newsfeed */ is_hidden_from_feed: BaseBoolInt, /** * Number of common friends with current user */ common_count: number, /** * */ occupation: UsersOccupation, /** * */ career: UsersCareer[], /** * */ military: UsersMilitary[], /** * University ID */ university: number, /** * University name */ university_name: string, /** * */ university_group_id: number, /** * Faculty ID */ faculty: number, /** * Faculty name */ faculty_name: string, /** * Graduation year */ graduation: number, /** * Education form */ education_form: string, /** * User's education status */ education_status: string, /** * User hometown */ home_town: string, /** * User relationship status */ relation: UsersUserRelation, /** * */ relation_partner: UsersUserMin, /** * */ personal: UsersPersonal, /** * */ universities: UsersUniversity[], /** * */ schools: UsersSchool[], /** * */ relatives: UsersRelative[], /** * Information whether current user is subscribed to podcasts */ is_subscribed_podcasts: boolean, /** * Owner in whitelist or not */ can_subscribe_podcasts: boolean, /** * Can subscribe to wall */ can_subscribe_posts: boolean, /** * */ counters: UsersUserCounters, /** * */ access_key: string, /** * */ can_upload_doc: BaseBoolInt, /** * */ hash: string, /** * */ has_email: boolean } export interface UsersUserMin { /** * Returns if a profile is deleted or blocked */ deactivated: string, /** * User first name */ first_name: string, /** * Returns if a profile is hidden. */ hidden: number, /** * User ID */ id: number, /** * User last name */ last_name: string, /** * */ can_access_closed: boolean, /** * */ is_closed: boolean } export type UsersUserRelation = number export interface UsersUserSettingsXtr { /** * */ connections: UsersUserConnections, /** * User's date of birth */ bdate: string, /** * Information whether user's birthdate are hidden */ bdate_visibility: number, /** * */ city: BaseCity, /** * */ country: BaseCountry, /** * User first name */ first_name: string, /** * User's hometown */ home_town: string, /** * User last name */ last_name: string, /** * User maiden name */ maiden_name: string, /** * */ name_request: AccountNameRequest, /** * */ personal: UsersPersonal, /** * User phone number with some hidden digits */ phone: string, /** * User relationship status */ relation: UsersUserRelation, /** * */ relation_partner: UsersUserMin, /** * Information whether relation status is pending */ relation_pending: BaseBoolInt, /** * */ relation_requests: UsersUserMin[], /** * Domain name of the user's page */ screen_name: string, /** * User sex */ sex: BaseSex, /** * User status */ status: string, /** * */ status_audio: AudioAudio, /** * */ interests: AccountUserSettingsInterests, /** * */ languages: string[] } export type UsersUserType = string export interface UsersUserXtrCounters { /** * Returns if a profile is deleted or blocked */ deactivated: string, /** * User first name */ first_name: string, /** * Returns if a profile is hidden. */ hidden: number, /** * User ID */ id: number, /** * User last name */ last_name: string, /** * */ can_access_closed: boolean, /** * */ is_closed: boolean, /** * User sex */ sex: BaseSex, /** * Domain name of the user's page */ screen_name: string, /** * URL of square photo of the user with 50 pixels in width */ photo_50: string, /** * URL of square photo of the user with 100 pixels in width */ photo_100: string, /** * */ online_info: UsersOnlineInfo, /** * Information whether the user is online */ online: BaseBoolInt, /** * Information whether the user is online in mobile site or application */ online_mobile: BaseBoolInt, /** * Application ID */ online_app: number, /** * Information whether the user is verified */ verified: BaseBoolInt, /** * Information whether the user has a "fire" pictogram. */ trending: BaseBoolInt, /** * */ friend_status: FriendsFriendStatusStatus, /** * */ mutual: FriendsRequestsMutual, /** * User's first name in nominative case */ first_name_nom: string, /** * User's first name in genitive case */ first_name_gen: string, /** * User's first name in dative case */ first_name_dat: string, /** * User's first name in accusative case */ first_name_acc: string, /** * User's first name in instrumental case */ first_name_ins: string, /** * User's first name in prepositional case */ first_name_abl: string, /** * User's last name in nominative case */ last_name_nom: string, /** * User's last name in genitive case */ last_name_gen: string, /** * User's last name in dative case */ last_name_dat: string, /** * User's last name in accusative case */ last_name_acc: string, /** * User's last name in instrumental case */ last_name_ins: string, /** * User's last name in prepositional case */ last_name_abl: string, /** * User nickname */ nickname: string, /** * User maiden name */ maiden_name: string, /** * User contact name */ contact_name: string, /** * Domain name of the user's page */ domain: string, /** * User's date of birth */ bdate: string, /** * */ city: BaseCity, /** * */ country: BaseCountry, /** * User's timezone */ timezone: number, /** * */ owner_state: OwnerState, /** * URL of square photo of the user with 200 pixels in width */ photo_200: string, /** * URL of square photo of the user with maximum width */ photo_max: string, /** * URL of user's photo with 200 pixels in width */ photo_200_orig: string, /** * URL of user's photo with 400 pixels in width */ photo_400_orig: string, /** * URL of user's photo of maximum size */ photo_max_orig: string, /** * ID of the user's main photo */ photo_id: string, /** * Information whether the user has main photo */ has_photo: BaseBoolInt, /** * Information whether the user specified his phone number */ has_mobile: BaseBoolInt, /** * Information whether the user is a friend of current user */ is_friend: BaseBoolInt, /** * Information whether current user can comment wall posts */ wall_comments: BaseBoolInt, /** * Information whether current user can post on the user's wall */ can_post: BaseBoolInt, /** * Information whether current user can see other users' audio on the wall */ can_see_all_posts: BaseBoolInt, /** * Information whether current user can see the user's audio */ can_see_audio: BaseBoolInt, /** * */ type: UsersUserType, /** * */ email: string, /** * */ skype: string, /** * */ facebook: string, /** * */ facebook_name: string, /** * */ twitter: string, /** * */ livejournal: string, /** * */ instagram: string, /** * */ test: BaseBoolInt, /** * */ video_live: VideoLiveInfo, /** * */ is_video_live_notifications_blocked: BaseBoolInt, /** * */ is_service: boolean, /** * */ service_description: string, /** * */ photo_rec: PhotosPhotoFalseable, /** * */ photo_medium: PhotosPhotoFalseable, /** * */ photo_medium_rec: PhotosPhotoFalseable, /** * */ photo: string, /** * */ photo_big: string, /** * */ photo_400: string, /** * */ photo_max_size: PhotosPhoto, /** * */ language: string, /** * */ stories_archive_count: number, /** * */ wall_default: string, /** * Information whether current user can call */ can_call: boolean, /** * Information whether current user can see the user's wishes */ can_see_wishes: boolean, /** * Information whether current user can see the user's gifts */ can_see_gifts: BaseBoolInt, /** * */ interests: string, /** * */ books: string, /** * */ tv: string, /** * */ quotes: string, /** * */ about: string, /** * */ games: string, /** * */ movies: string, /** * */ activities: string, /** * */ music: string, /** * Information whether current user can write private message */ can_write_private_message: BaseBoolInt, /** * Information whether current user can send a friend request */ can_send_friend_request: BaseBoolInt, /** * Information whether current user can be invited to the community */ can_be_invited_group: boolean, /** * User's mobile phone number */ mobile_phone: string, /** * User's additional phone number */ home_phone: string, /** * User's website */ site: string, /** * */ status_audio: AudioAudio, /** * User's status */ status: string, /** * User's status */ activity: string, /** * */ last_seen: UsersLastSeen, /** * */ exports: UsersExports, /** * */ crop_photo: BaseCropPhoto, /** * Number of user's followers */ followers_count: number, /** * User level in live streams achievements */ video_live_level: number, /** * Number of user's live streams */ video_live_count: number, /** * Number of user's clips */ clips_count: number, /** * Information whether current user is in the requested user's blacklist. */ blacklisted: BaseBoolInt, /** * Information whether the requested user is in current user's blacklist */ blacklisted_by_me: BaseBoolInt, /** * Information whether the requested user is in faves of current user */ is_favorite: BaseBoolInt, /** * Information whether the requested user is hidden from current user's newsfeed */ is_hidden_from_feed: BaseBoolInt, /** * Number of common friends with current user */ common_count: number, /** * */ occupation: UsersOccupation, /** * */ career: UsersCareer[], /** * */ military: UsersMilitary[], /** * University ID */ university: number, /** * University name */ university_name: string, /** * */ university_group_id: number, /** * Faculty ID */ faculty: number, /** * Faculty name */ faculty_name: string, /** * Graduation year */ graduation: number, /** * Education form */ education_form: string, /** * User's education status */ education_status: string, /** * User hometown */ home_town: string, /** * User relationship status */ relation: UsersUserRelation, /** * */ relation_partner: UsersUserMin, /** * */ personal: UsersPersonal, /** * */ universities: UsersUniversity[], /** * */ schools: UsersSchool[], /** * */ relatives: UsersRelative[], /** * Information whether current user is subscribed to podcasts */ is_subscribed_podcasts: boolean, /** * Owner in whitelist or not */ can_subscribe_podcasts: boolean, /** * Can subscribe to wall */ can_subscribe_posts: boolean, /** * */ counters: UsersUserCounters, /** * */ access_key: string, /** * */ can_upload_doc: BaseBoolInt, /** * */ hash: string, /** * */ has_email: boolean } export interface UsersUserXtrType { /** * Returns if a profile is deleted or blocked */ deactivated: string, /** * User first name */ first_name: string, /** * Returns if a profile is hidden. */ hidden: number, /** * User ID */ id: number, /** * User last name */ last_name: string, /** * */ can_access_closed: boolean, /** * */ is_closed: boolean, /** * User sex */ sex: BaseSex, /** * Domain name of the user's page */ screen_name: string, /** * URL of square photo of the user with 50 pixels in width */ photo_50: string, /** * URL of square photo of the user with 100 pixels in width */ photo_100: string, /** * */ online_info: UsersOnlineInfo, /** * Information whether the user is online */ online: BaseBoolInt, /** * Information whether the user is online in mobile site or application */ online_mobile: BaseBoolInt, /** * Application ID */ online_app: number, /** * Information whether the user is verified */ verified: BaseBoolInt, /** * Information whether the user has a "fire" pictogram. */ trending: BaseBoolInt, /** * */ friend_status: FriendsFriendStatusStatus, /** * */ mutual: FriendsRequestsMutual, /** * */ type: UsersUserType } export interface UsersUsersArray { /** * Users number */ count: number, /** * */ items: number[] } export interface UtilsDomainResolved { /** * Object ID */ object_id: number, /** * Group ID */ group_id: number, /** * */ type: UtilsDomainResolvedType } export type UtilsDomainResolvedType = string export interface UtilsLastShortenedLink { /** * Access key for private stats */ access_key: string, /** * Link key (characters after vk.cc/) */ key: string, /** * Short link URL */ short_url: string, /** * Creation time in Unixtime */ timestamp: number, /** * Full URL */ url: string, /** * Total views number */ views: number } export interface UtilsLinkChecked { /** * Link URL */ link: string, /** * */ status: UtilsLinkCheckedStatus } export type UtilsLinkCheckedStatus = string export interface UtilsLinkStats { /** * Link key (characters after vk.cc/) */ key: string, /** * */ stats: UtilsStats[] } export interface UtilsLinkStatsExtended { /** * Link key (characters after vk.cc/) */ key: string, /** * */ stats: UtilsStatsExtended[] } export interface UtilsShortLink { /** * Access key for private stats */ access_key: string, /** * Link key (characters after vk.cc/) */ key: string, /** * Short link URL */ short_url: string, /** * Full URL */ url: string } export interface UtilsStats { /** * Start time */ timestamp: number, /** * Total views number */ views: number } export interface UtilsStatsCity { /** * City ID */ city_id: number, /** * Views number */ views: number } export interface UtilsStatsCountry { /** * Country ID */ country_id: number, /** * Views number */ views: number } export interface UtilsStatsExtended { /** * */ cities: UtilsStatsCity[], /** * */ countries: UtilsStatsCountry[], /** * */ sex_age: UtilsStatsSexAge[], /** * Start time */ timestamp: number, /** * Total views number */ views: number } export interface UtilsStatsSexAge { /** * Age denotation */ age_range: string, /** * Views by female users */ female: number, /** * Views by male users */ male: number } export interface VideoLiveInfo { /** * */ enabled: BaseBoolInt, /** * */ is_notifications_blocked: BaseBoolInt } export interface VideoLiveSettings { /** * If user car rewind live or not */ can_rewind: BaseBoolInt, /** * If live is endless or not */ is_endless: BaseBoolInt, /** * Max possible time for rewind */ max_duration: number } export interface VideoRestrictionButton { /** * */ action: string, /** * */ title: string } export interface VideoSaveResult { /** * Video access key */ access_key: string, /** * Video description */ description: string, /** * Video owner ID */ owner_id: number, /** * Video title */ title: string, /** * URL for the video uploading */ upload_url: string, /** * Video ID */ video_id: number } export interface VideoVideo { /** * Video access key */ access_key: string, /** * Date when the video has been added in Unixtime */ adding_date: number, /** * Information whether current user can comment the video */ can_comment: BaseBoolInt, /** * Information whether current user can edit the video */ can_edit: BaseBoolInt, /** * Information whether current user can like the video */ can_like: BaseBoolInt, /** * Information whether current user can repost the video */ can_repost: BaseBoolInt, /** * Information whether current user can subscribe to author of the video */ can_subscribe: BaseBoolInt, /** * Information whether current user can add the video to favourites */ can_add_to_faves: BaseBoolInt, /** * Information whether current user can add the video */ can_add: BaseBoolInt, /** * Information whether current user can attach action button to the video */ can_attach_link: BaseBoolInt, /** * 1 if video is private */ is_private: BaseBoolInt, /** * Number of comments */ comments: number, /** * Date when video has been uploaded in Unixtime */ date: number, /** * Video description */ description: string, /** * Video duration in seconds */ duration: number, /** * */ image: VideoVideoImage[], /** * */ first_frame: VideoVideoImage[], /** * Video width */ width: number, /** * Video height */ height: number, /** * Video ID */ id: number, /** * Video owner ID */ owner_id: number, /** * Id of the user who uploaded the video if it was uploaded to a group by member */ user_id: number, /** * Video title */ title: string, /** * Whether video is added to bookmarks */ is_favorite: boolean, /** * Video embed URL */ player: string, /** * Returns if the video is processing */ processing: BasePropertyExists, /** * 1 if video is being converted */ converting: BaseBoolInt, /** * */ restriction: MediaRestriction, /** * 1 if video is added to user's albums */ added: BaseBoolInt, /** * 1 if user is subscribed to author of the video */ is_subscribed: BaseBoolInt, /** * */ track_code: string, /** * Information whether the video is repeated */ repeat: BasePropertyExists, /** * */ type: string, /** * Number of views */ views: number, /** * If video is external, number of views on vk */ local_views: number, /** * Restriction code */ content_restricted: number, /** * Restriction text */ content_restricted_message: string, /** * Live donations balance */ balance: number, /** * Live stream status */ live_status: string, /** * 1 if the video is a live stream */ live: BasePropertyExists, /** * 1 if the video is an upcoming stream */ upcoming: BasePropertyExists, /** * Date in Unixtime when the live stream is scheduled to start by the author */ live_start_time: number, /** * Whether current user is subscribed to the upcoming live stream notification (if not subscribed to the author) */ live_notify: BaseBoolInt, /** * Number of spectators of the stream */ spectators: number, /** * External platform */ platform: string, /** * */ likes: BaseLikes, /** * */ reposts: BaseRepostsInfo } export interface VideoVideoAlbumFull { /** * Total number of videos in album */ count: number, /** * Album ID */ id: number, /** * Album cover image in different sizes */ image: VideoVideoImage[], /** * Need blur album thumb or not */ image_blur: BasePropertyExists, /** * Information whether album is system */ is_system: BasePropertyExists, /** * Album owner's ID */ owner_id: number, /** * Album title */ title: string, /** * Date when the album has been updated last time in Unixtime */ updated_time: number } export interface VideoVideoFiles { /** * URL of the external player */ external: string, /** * URL of the mpeg4 file with 240p quality */ mp4_240: string, /** * URL of the mpeg4 file with 360p quality */ mp4_360: string, /** * URL of the mpeg4 file with 480p quality */ mp4_480: string, /** * URL of the mpeg4 file with 720p quality */ mp4_720: string, /** * URL of the mpeg4 file with 1080p quality */ mp4_1080: string, /** * URL of the flv file with 320p quality */ flv_320: string } export interface VideoVideoFull { /** * Video access key */ access_key: string, /** * Date when the video has been added in Unixtime */ adding_date: number, /** * Information whether current user can comment the video */ can_comment: BaseBoolInt, /** * Information whether current user can edit the video */ can_edit: BaseBoolInt, /** * Information whether current user can like the video */ can_like: BaseBoolInt, /** * Information whether current user can repost the video */ can_repost: BaseBoolInt, /** * Information whether current user can subscribe to author of the video */ can_subscribe: BaseBoolInt, /** * Information whether current user can add the video to favourites */ can_add_to_faves: BaseBoolInt, /** * Information whether current user can add the video */ can_add: BaseBoolInt, /** * Information whether current user can attach action button to the video */ can_attach_link: BaseBoolInt, /** * 1 if video is private */ is_private: BaseBoolInt, /** * Number of comments */ comments: number, /** * Date when video has been uploaded in Unixtime */ date: number, /** * Video description */ description: string, /** * Video duration in seconds */ duration: number, /** * */ image: VideoVideoImage[], /** * */ first_frame: VideoVideoImage[], /** * Video width */ width: number, /** * Video height */ height: number, /** * Video ID */ id: number, /** * Video owner ID */ owner_id: number, /** * Id of the user who uploaded the video if it was uploaded to a group by member */ user_id: number, /** * Video title */ title: string, /** * Whether video is added to bookmarks */ is_favorite: boolean, /** * Video embed URL */ player: string, /** * Returns if the video is processing */ processing: BasePropertyExists, /** * 1 if video is being converted */ converting: BaseBoolInt, /** * */ restriction: MediaRestriction, /** * 1 if video is added to user's albums */ added: BaseBoolInt, /** * 1 if user is subscribed to author of the video */ is_subscribed: BaseBoolInt, /** * */ track_code: string, /** * Information whether the video is repeated */ repeat: BasePropertyExists, /** * */ type: string, /** * Number of views */ views: number, /** * If video is external, number of views on vk */ local_views: number, /** * Restriction code */ content_restricted: number, /** * Restriction text */ content_restricted_message: string, /** * Live donations balance */ balance: number, /** * Live stream status */ live_status: string, /** * 1 if the video is a live stream */ live: BasePropertyExists, /** * 1 if the video is an upcoming stream */ upcoming: BasePropertyExists, /** * Date in Unixtime when the live stream is scheduled to start by the author */ live_start_time: number, /** * Whether current user is subscribed to the upcoming live stream notification (if not subscribed to the author) */ live_notify: BaseBoolInt, /** * Number of spectators of the stream */ spectators: number, /** * External platform */ platform: string, /** * */ likes: BaseLikes, /** * */ reposts: BaseRepostsInfo, /** * */ files: VideoVideoFiles, /** * Settings for live stream */ live_settings: VideoLiveSettings } export interface VideoVideoImage { /** * */ id: string, /** * Image height */ height: number, /** * Image url */ url: string, /** * Image width */ width: number, /** * */ with_padding: BasePropertyExists } export interface WallAppPost { /** * Application ID */ id: number, /** * Application name */ name: string, /** * URL of the preview image with 130 px in width */ photo_130: string, /** * URL of the preview image with 604 px in width */ photo_604: string } export interface WallAttachedNote { /** * Comments number */ comments: number, /** * Date when the note has been created in Unixtime */ date: number, /** * Note ID */ id: number, /** * Note owner's ID */ owner_id: number, /** * Read comments number */ read_comments: number, /** * Note title */ title: string, /** * URL of the page with note preview */ view_url: string } export interface WallCarouselBase { /** * Index of current carousel element */ carousel_offset: number } export interface WallCommentAttachment { /** * */ audio: AudioAudio, /** * */ doc: DocsDoc, /** * */ link: BaseLink, /** * */ market: MarketMarketItem, /** * */ market_market_album: MarketMarketAlbum, /** * */ note: WallAttachedNote, /** * */ page: PagesWikipageFull, /** * */ photo: PhotosPhoto, /** * */ sticker: BaseSticker, /** * */ type: WallCommentAttachmentType, /** * */ video: VideoVideo } export type WallCommentAttachmentType = string export interface WallGeo { /** * Coordinates as string. <latitude> <longtitude> */ coordinates: string, /** * */ place: BasePlace, /** * Information whether a map is showed */ showmap: number, /** * Place type */ type: string } export interface WallGraffiti { /** * Graffiti ID */ id: number, /** * Graffiti owner's ID */ owner_id: number, /** * URL of the preview image with 200 px in width */ photo_200: string, /** * URL of the preview image with 586 px in width */ photo_586: string } export interface WallPostCopyright { /** * */ id: number, /** * */ link: string, /** * */ name: string, /** * */ type: string } export interface WallPostSource { /** * Additional data */ data: string, /** * Platform name */ platform: string, /** * */ type: WallPostSourceType, /** * URL to an external site used to publish the post */ url: string } export type WallPostSourceType = string export type WallPostType = string export interface WallPostedPhoto { /** * Photo ID */ id: number, /** * Photo owner's ID */ owner_id: number, /** * URL of the preview image with 130 px in width */ photo_130: string, /** * URL of the preview image with 604 px in width */ photo_604: string } export interface WallViews { /** * Count */ count: number } export interface WallWallComment { /** * */ attachments: WallCommentAttachment[], /** * Date when the comment has been added in Unixtime */ date: number, /** * */ donut: WallWallCommentDonut, /** * Author ID */ from_id: number, /** * Comment ID */ id: number, /** * */ likes: BaseLikesInfo, /** * Real position of the comment */ real_offset: number, /** * Replied comment ID */ reply_to_comment: number, /** * Replied user ID */ reply_to_user: number, /** * Comment text */ text: string, /** * */ thread: CommentThread, /** * */ post_id: number, /** * */ owner_id: number, /** * */ parents_stack: number[], /** * */ deleted: boolean } export interface WallWallCommentDonut { /** * Means commentator is donator */ is_don: boolean, /** * */ placeholder: WallWallCommentDonutPlaceholder } export interface WallWallCommentDonutPlaceholder { /** * */ text: string } export interface WallWallpost { /** * Access key to private object */ access_key: string, /** * */ attachments: WallWallpostAttachment[], /** * Information about the source of the post */ copyright: WallPostCopyright, /** * Date of publishing in Unixtime */ date: number, /** * Date of editing in Unixtime */ edited: number, /** * Post author ID */ from_id: number, /** * */ geo: WallGeo, /** * Post ID */ id: number, /** * Is post archived, only for post owners */ is_archived: boolean, /** * Information whether the post in favorites list */ is_favorite: boolean, /** * Count of likes */ likes: BaseLikesInfo, /** * Wall owner's ID */ owner_id: number, /** * */ poster: any, /** * If post type 'reply', contains original post ID */ post_id: number, /** * If post type 'reply', contains original parent IDs stack */ parents_stack: number[], /** * */ post_source: WallPostSource, /** * */ post_type: WallPostType, /** * */ reposts: BaseRepostsInfo, /** * Post signer ID */ signer_id: number, /** * Post text */ text: string, /** * Count of views */ views: WallViews } export interface WallWallpostAttachment { /** * Access key for the audio */ access_key: string, /** * */ album: PhotosPhotoAlbum, /** * */ app: WallAppPost, /** * */ audio: AudioAudio, /** * */ doc: DocsDoc, /** * */ event: EventsEventAttach, /** * */ group: GroupsGroupAttach, /** * */ graffiti: WallGraffiti, /** * */ link: BaseLink, /** * */ market: MarketMarketItem, /** * */ market_album: MarketMarketAlbum, /** * */ note: WallAttachedNote, /** * */ page: PagesWikipageFull, /** * */ photo: PhotosPhoto, /** * */ photos_list: string[], /** * */ poll: PollsPoll, /** * */ posted_photo: WallPostedPhoto, /** * */ type: WallWallpostAttachmentType, /** * */ video: VideoVideo } export type WallWallpostAttachmentType = string export interface WallWallpostCommentsDonut { /** * */ placeholder: WallWallpostCommentsDonutPlaceholder } export interface WallWallpostCommentsDonutPlaceholder { /** * */ text: string } export interface WallWallpostDonut { /** * Post only for dons */ is_donut: boolean, /** * Value of this field need to pass in wall.post/edit in donut_paid_duration */ paid_duration: number, /** * If placeholder was respond, text and all attachments will be hidden */ placeholder: WallWallpostDonutPlaceholder, /** * Says whether group admin can post free copy of this donut post */ can_publish_free_copy: boolean, /** * Says what user can edit in post about donut properties */ edit_mode: string } export interface WallWallpostDonutPlaceholder { /** * */ text: string } export interface WallWallpostFull { /** * Index of current carousel element */ carousel_offset: number, /** * Access key to private object */ access_key: string, /** * */ attachments: WallWallpostAttachment[], /** * Information about the source of the post */ copyright: WallPostCopyright, /** * Date of publishing in Unixtime */ date: number, /** * Date of editing in Unixtime */ edited: number, /** * Post author ID */ from_id: number, /** * */ geo: WallGeo, /** * Post ID */ id: number, /** * Is post archived, only for post owners */ is_archived: boolean, /** * Information whether the post in favorites list */ is_favorite: boolean, /** * Count of likes */ likes: BaseLikesInfo, /** * Wall owner's ID */ owner_id: number, /** * */ poster: any, /** * If post type 'reply', contains original post ID */ post_id: number, /** * If post type 'reply', contains original parent IDs stack */ parents_stack: number[], /** * */ post_source: WallPostSource, /** * */ post_type: WallPostType, /** * */ reposts: BaseRepostsInfo, /** * Post signer ID */ signer_id: number, /** * Post text */ text: string, /** * Count of views */ views: WallViews, /** * */ copy_history: WallWallpost[], /** * Information whether current user can edit the post */ can_edit: BaseBoolInt, /** * Post creator ID (if post still can be edited) */ created_by: number, /** * Information whether current user can delete the post */ can_delete: BaseBoolInt, /** * Information whether current user can pin the post */ can_pin: BaseBoolInt, /** * */ donut: WallWallpostDonut, /** * Information whether the post is pinned */ is_pinned: number, /** * */ comments: BaseCommentsInfo, /** * Information whether the post is marked as ads */ marked_as_ads: BaseBoolInt, /** * Preview length control parameter */ short_text_rate: number } export interface WallWallpostToId { /** * */ attachments: WallWallpostAttachment[], /** * */ comments: BaseCommentsInfo, /** * ID of the source post owner */ copy_owner_id: number, /** * ID of the source post */ copy_post_id: number, /** * Date of publishing in Unixtime */ date: number, /** * Post author ID */ from_id: number, /** * */ geo: WallGeo, /** * Post ID */ id: number, /** * Information whether the post in favorites list */ is_favorite: boolean, /** * */ likes: BaseLikesInfo, /** * wall post ID (if comment) */ post_id: number, /** * */ post_source: WallPostSource, /** * */ post_type: WallPostType, /** * */ reposts: BaseRepostsInfo, /** * Post signer ID */ signer_id: number, /** * Post text */ text: string, /** * Wall owner's ID */ to_id: number } export interface WidgetsCommentMedia { /** * Media item ID */ item_id: number, /** * Media owner's ID */ owner_id: number, /** * URL of the preview image (type=photo only) */ thumb_src: string, /** * */ type: WidgetsCommentMediaType } export type WidgetsCommentMediaType = string export interface WidgetsCommentReplies { /** * Information whether current user can comment the post */ can_post: BaseBoolInt, /** * Comments number */ count: number, /** * */ replies: WidgetsCommentRepliesItem[] } export interface WidgetsCommentRepliesItem { /** * Comment ID */ cid: number, /** * Date when the comment has been added in Unixtime */ date: number, /** * */ likes: WidgetsWidgetLikes, /** * Comment text */ text: string, /** * User ID */ uid: number, /** * */ user: UsersUserFull } export interface WidgetsWidgetComment { /** * */ attachments: WallCommentAttachment[], /** * Information whether current user can delete the comment */ can_delete: BaseBoolInt, /** * */ comments: WidgetsCommentReplies, /** * Date when the comment has been added in Unixtime */ date: number, /** * Comment author ID */ from_id: number, /** * Comment ID */ id: number, /** * */ likes: BaseLikesInfo, /** * */ media: WidgetsCommentMedia, /** * */ post_source: WallPostSource, /** * Post type */ post_type: number, /** * */ reposts: BaseRepostsInfo, /** * Comment text */ text: string, /** * Wall owner */ to_id: number, /** * */ user: UsersUserFull } export interface WidgetsWidgetLikes { /** * Likes number */ count: number } export interface WidgetsWidgetPage { /** * */ comments: BaseObjectCount, /** * Date when widgets on the page has been initialized firstly in Unixtime */ date: number, /** * Page description */ description: string, /** * Page ID */ id: number, /** * */ likes: BaseObjectCount, /** * page_id parameter value */ page_id: string, /** * URL of the preview image */ photo: string, /** * Page title */ title: string, /** * Page absolute URL */ url: string } export type Poster = any
the_stack
import { AccessorInterface, ReadResult, UpdateResult, AddResult, RemoveResult, CountResult } from "./accessor" import { Params, ActionType, Order, Direction } from '../types' import { MongoClient, ObjectId, MongoClientOptions, Db, UpdateOptions, Filter } from 'mongodb' import * as mongodb from 'mongodb' import { DefaultLogger, LoggerInterface } from "../logger" import { EventEmitter } from "events" import { EJSON } from "bson" import { AggregateStage } from "database-ql/dist/commonjs/interface" /** * Mongodb Accessor 负责执行 mongodb 数据操作 * * 连接参数同 mongodb nodejs driver,参考以下链接: * @see https://docs.mongodb.com/manual/reference/connection-string/ * * 实例化本对象后,须调用 `init()` 待数据库连接成功,方可执行数据操作。 * ```js * const accessor = new MongoAccessor('dbname', 'mongodb://localhost:27017', { directConnection: true }) * * accessor.init() * ``` * * 可通过 `ready` 属性等待数据库连接就绪,该属性为 `Promise` 对象: * ```js * accessor.ready.then(() => { * // 连接就绪,可进行数据操作 * }) * ``` */ export class MongoAccessor implements AccessorInterface { readonly type: string = 'mongo' /** * 数据库名 */ readonly db_name: string readonly conn: MongoClient protected _event = new EventEmitter() /** * `ready` 属性可用于等待数据库连接就绪,该属性为 `Promise` 对象: * ```js * accessor.ready.then(() => { * // 连接就绪,可进行数据操作 * }) * ``` */ ready: Promise<MongoClient> db: Db private _logger: LoggerInterface get logger() { if (!this._logger) { this._logger = new DefaultLogger() } return this._logger } setLogger(logger: LoggerInterface) { this._logger = logger } /** * Mongodb Accessor 负责执行 mongodb 数据操作 * * 连接参数同 mongodb nodejs driver,参考以下链接: * @see https://docs.mongodb.com/manual/reference/connection-string/ * * 实例化本对象后,须调用 `init()` 待数据库连接成功,方可执行数据操作。 * ```js * const accessor = new MongoAccessor('dbname', 'mongodb://localhost:27017', { directConnection: true }) * * accessor.init() * ``` * * 可通过 `ready` 属性等待数据库连接就绪,该属性为 `Promise` 对象: * ```js * accessor.ready.then(() => { * // 连接就绪,可进行数据操作 * }) * ``` */ constructor(db: string, url: string, options?: MongoClientOptions) { this.db_name = db this.conn = new MongoClient(url, options || {}) this.db = null // 初始化为空 Promise,永远不被 resolved this.ready = new Promise(() => { /* nop */ }) } emit(event: string | symbol, ...args: any[]): boolean { return this._event.emit(event, ...args) } once(event: string | symbol, listener: (...args: any[]) => void): void { this.once(event, listener) } removeAllListeners(event?: string | symbol): void { this._event.removeAllListeners(event) } on(event: string | symbol, listener: (...args: any[]) => void): void { this._event.on(event, listener) } off(event: string | symbol, listener: (...args: any[]) => void): void { this._event.off(event, listener) } /** * 初始化实例: 执行数据库连接 * @returns Promise<MongoClient> */ async init() { this.logger.info(`mongo accessor connecting...`) this.ready = this.conn .connect() .then(ret => { this.logger.info(`mongo accessor connected, db: ` + this.db_name) this.db = this.conn.db(this.db_name) return ret }) return await this.ready } /** * 关闭连接 */ async close() { await this.conn.close() this.logger.info('mongo connection closed') } /** * 执行数据请求 * @param params 数据请求参数 * @returns */ async execute(params: Params): Promise<ReadResult | UpdateResult | AddResult | RemoveResult | CountResult | never> { const { collection, action } = params this.logger.info(`mongo start executing {${collection}}: ` + JSON.stringify(params)) if (action === ActionType.READ) { return await this.read(collection, params) } if (action === ActionType.AGGREGATE) { return await this.aggregate(collection, params) } if (action === ActionType.UPDATE) { return await this.update(collection, params) } if (action === ActionType.ADD) { return await this.add(collection, params) } if (action === ActionType.REMOVE) { return await this.remove(collection, params) } if (action === ActionType.COUNT) { return await this.count(collection, params) } const error = new Error(`invalid 'action': ${action}`) this.logger.error(`mongo end of executing occurred error: `, error) throw error } /** * 查询单个文档,主要用于 `访问规则` 中的数据查询 */ async get(collection: string, query: Filter<any>): Promise<any> { const coll = this.db.collection(collection) return await coll.findOne(query) } /** * 触发查询结果事件 * @param params * @param data */ protected emitResult(params: Params, result: any) { this.emit('result', { params, result }) } /** * 执行查询文档操作 * @param collection 集合名 * @param params 请求参数 * @returns 查询结果 */ protected async read(collection: string, params: Params): Promise<ReadResult> { const coll = this.db.collection(collection) const { order, offset, limit, projection, count } = params const query: any = this.deserializedEjson(params.query || {}) const options: any = { limit: 100, skip: 0 } if (order) options.sort = this.processOrder(order) if (offset) options.skip = offset if (projection) options.projection = projection if (limit) { options.limit = limit } this.logger.debug(`mongo before read {${collection}}: `, { query, options }) const data = await coll.find(query, options).toArray() this.logger.debug(`mongo end of read {${collection}}: `, { query, options, dataLength: data.length }) let total: number if (count) { total = await coll.countDocuments(query as Filter<any>) } this.emitResult(params, { data }) const serialized = data.map(doc => this.serializeBson(doc)) return { list: serialized, limit: options.limit, offset: options.skip, total } } /** * Execute aggregate query * @param collection * @param params * @returns */ protected async aggregate(collection: string, params: Params): Promise<ReadResult> { const coll = this.db.collection(collection) const stages = this.processAggregateStages(params.stages) this.logger.debug(`mongo before aggregate {${collection}}: `, stages) const data = await coll.aggregate(stages).toArray() this.logger.debug(`mongo after aggregate {${collection}}: `, stages, { dataLength: data.length }) this.emitResult(params, { data }) const serialized = data.map(doc => this.serializeBson(doc)) return { list: serialized } } /** * Execute update query * @param collection Collection name * @param params * @returns */ protected async update(collection: string, params: Params): Promise<UpdateResult> { const coll = this.db.collection(collection) let { query, data, multi, upsert, merge } = params query = this.deserializedEjson(query || {}) data = this.deserializedEjson(data || {}) let options: UpdateOptions = {} if (upsert) options.upsert = upsert // merge 不为 true 代表替换操作,暂只允许单条替换 if (!merge) { this.logger.debug(`mongo before update (replaceOne) {${collection}}: `, { query, data, options, merge, multi }) const result: any = await coll.replaceOne(query, data, options) const _data = { upsert_id: result.upsertedId, updated: result.modifiedCount, matched: result.matchedCount } this.emitResult(params, _data) return _data } let result: mongodb.UpdateResult // multi 表示更新一条或多条 if (!multi) { this.logger.debug(`mongo before update (updateOne) {${collection}}: `, { query, data, options, merge, multi }) result = await coll.updateOne(query, data, options) } else { options.upsert = false this.logger.debug(`mongo before update (updateMany) {${collection}}: `, { query, data, options, merge, multi }) result = await coll.updateMany(query, data, options) as mongodb.UpdateResult } const ret: UpdateResult = { upsert_id: this.serializeBson(result.upsertedId) as any, updated: result.modifiedCount, matched: result.matchedCount } this.emitResult(params, ret) this.logger.debug(`mongo end of update {${collection}}: `, { query, data, options, merge, multi, result: ret }) return ret } /** * Execute insert query * @param collection Collection name * @param params * @returns */ protected async add(collection: string, params: Params): Promise<AddResult> { const coll = this.db.collection(collection) let { data, multi } = params data = this.deserializedEjson(data || {}) let result: mongodb.InsertOneResult | mongodb.InsertManyResult this.logger.debug(`mongo before add {${collection}}: `, { data, multi }) // multi 表示单条或多条添加 if (!multi) { data._id = this.generateDocId() result = await coll.insertOne(data) } else { data = data instanceof Array ? data : [data] data.forEach((ele: any) => ele._id = this.generateDocId()) result = await coll.insertMany(data) } const ret: AddResult = { _id: this.serializeBson((result as mongodb.InsertManyResult).insertedIds || (result as mongodb.InsertOneResult).insertedId) as any, insertedCount: (result as mongodb.InsertManyResult).insertedCount } this.emitResult(params, ret) this.logger.debug(`mongo end of add {${collection}}: `, { data, multi, result: ret }) return ret } /** * 执行删除文档操作 * @param collection 集合名 * @param params 请求参数 * @returns 执行结果 */ protected async remove(collection: string, params: Params): Promise<RemoveResult> { const coll = this.db.collection(collection) let { query, multi } = params query = this.deserializedEjson(query || {}) let result: any this.logger.debug(`mongo before remove {${collection}}: `, { query, multi }) // multi 表示单条或多条删除 if (!multi) { result = await coll.deleteOne(query) } else { result = await coll.deleteMany(query) } const ret = { deleted: result.deletedCount } this.emitResult(params, ret) this.logger.debug(`mongo end of remove {${collection}}: `, ret) return ret } /** * 执行文档计数操作 * @param collection 集合名 * @param params 请求参数 * @returns 执行结果 */ protected async count(collection: string, params: Params): Promise<CountResult> { const coll = this.db.collection(collection) const query = this.deserializedEjson(params.query || {}) as any const options = {} this.logger.debug(`mongo before count {${collection}}: `, { query }) const result = await coll.countDocuments(query, options) this.logger.debug(`mongo end of count {${collection}}: `, { query, result }) this.emitResult(params, result) return { total: result } } /** * Convert order params to Mongodb's order format * @param order * @returns */ protected processOrder(order: Order[]) { if (!(order instanceof Array)) return undefined return order.map(o => { const dir = o.direction === Direction.DESC ? -1 : 1 return [o.field, dir] }) } /** * Generate a hex string document id * @returns */ protected generateDocId(): string { const id = new ObjectId() return id.toHexString() } /** * Serialize Bson to Extended JSON * @see https://docs.mongodb.com/manual/reference/mongodb-extended-json/ * @param bsonDoc * @returns */ protected serializeBson(bsonDoc: any) { return EJSON.serialize(bsonDoc, { relaxed: true }) } /** * Deserialize Extended JSOn to Bson * @see https://docs.mongodb.com/manual/reference/mongodb-extended-json/ * @param ejsonDoc * @returns */ protected deserializedEjson(ejsonDoc: any) { return EJSON.deserialize(ejsonDoc, { relaxed: true }) } /** * Convert aggregate stages params to Mongodb aggregate pipelines * @param stages * @returns */ protected processAggregateStages(stages: AggregateStage[]) { const _stages = stages.map(item => { const key = item.stageKey const value = EJSON.parse(item.stageValue, { relaxed: true }) return { [key]: value } }) return _stages } }
the_stack
import createAnimation from './animation'; import PhotoRoot from './PhotoRoot'; import PhotoMain from './PhotoMain'; import $tool from './tool'; import { Square, Rect, Point, PhotoBasic, TouchePoint, AnimationInterface, ClipResult, RectFull } from './interface'; export interface Draw{ (maskRect: Rect, touchePosition: boolean, mask: PhotoMask): void; } const cursorConfig = new Map([ ['Top Left', 'nw-resize'], ['Top Right', 'ne-resize'], ['Bottom Left', 'sw-resize'], ['Bottom Right', 'se-resize'], ['Top', 'n-resize'], ['Left', 'w-resize'], ['Right', 'e-resize'], ['Bottom', 's-resize'] ]); /** * 遮罩 */ export default class PhotoMask implements PhotoBasic { className = 'PhotoMask'; readonly root: PhotoRoot; // 裁剪框宽高比例 width!: number; height!: number; // 是否圆形裁剪 private _isRound = false; // 是否可以调整比例 private resize: boolean; // 触点容错:5个像素 private readonly faultTolerant: number; private maskRect: Rect; private _maskRect?: Rect; // 当前触点 private touche: TouchePoint | null = null; private touchePosition: string | undefined = undefined; private animation: AnimationInterface | undefined = undefined; private readonly _draw: Draw; /** * 构造函数 * @param root PhotoRoot引用 * @param width 裁剪框宽 * @param height 裁剪框高 * @param resize 是否可以调整比例 * @param draw */ constructor(root: PhotoRoot, width: number, height: number, resize: boolean, draw: Draw) { root.addEventList(this); this.root = root; this.width = width || 1; this.height = height || 1; this.resize = resize; this.faultTolerant = 8 * root.magnification; const mr = this.maskRect = this._getMaskRect(); this._draw = draw; draw(this.maskRect, false, this); const photoMain = this.root.getEventList<PhotoMain>('PhotoMain'); if (photoMain) { photoMain.loadImgEd.set( this.className, (newObj = {}, animation: boolean) => this._reset(photoMain, newObj, animation) ); photoMain.setMoveRange(mr.x, mr.y, mr.x + mr.w, mr.y + mr.h); } } getMaskRect(): Rect { return this.maskRect; } /** * 重新设置裁剪框宽高比例 * @param photoMain // 原PhotoMain对象 * @param newObj // 该json会与photoMain合并 * @param animation // 改变图片的矩形是否经过动画 * @private */ private _reset(photoMain: PhotoMain, newObj = {}, animation = false) { const newPhotoMain = Object.assign({}, photoMain, newObj) as PhotoMain; const r = this._getMaskRect(); const showRect = newPhotoMain.showRect; const newRect = this._isRound ? $tool.getEllipseRectByRect(r.w, r.h, showRect.r) : $tool.getRectByRect(r.w, r.h, showRect.r); const [offX, offY, offW, offH] = photoMain.setMoveRange( newRect.x, newRect.y, newRect.x + newRect.w, newRect.y + newRect.h ); if (animation) { photoMain.doAnimation(offX, offY, offW, offH, showRect.r - photoMain.showRect.r); } else { photoMain.setShowRect({ x: showRect.x + offX, y: showRect.y + offY, w: showRect.w + offW, h: showRect.h + offH, r: showRect.r, sV: showRect.sV, sH: showRect.sH }); } } /** * 重新设置裁剪框宽高比例 * @param width * @param height */ reset(width: number, height: number): void { this.width = width || 1; this.height = height || 1; const r = this._getMaskRect(); const offX = r.x - this.maskRect.x; const offY = r.y - this.maskRect.y; const offW = r.w - this.maskRect.w; const offH = r.h - this.maskRect.h; const photoMain = this.root.getEventList<PhotoMain>('PhotoMain'); if (photoMain) { const showRect = photoMain.showRect; const zoom: number = r.w / this.maskRect.w; const rotatePoint: Point = $tool.rotatePoint( this.maskRect.x + this.maskRect.w / 2, this.maskRect.y + this.maskRect.h / 2, -showRect.r ); const offPoint: Point = { x: (showRect.x - rotatePoint.x) * zoom, y: (showRect.y - rotatePoint.y) * zoom, }; const newRect = this._isRound ? $tool.getEllipseRectByRect(r.w, r.h, showRect.r) : $tool.getRectByRect(r.w, r.h, showRect.r); const [offX, offY, offW, offH] = photoMain.setMoveRange(newRect.x, newRect.y, newRect.x + newRect.w, newRect.y + newRect.h, offPoint, zoom); photoMain.doAnimation(offX, offY, offW, offH, 0); } this._animation(offX, offY, offW, offH); this.root.onPhotoChange && this.root.onPhotoChange({ target: this, type: 'maskReset' }); } get isRound(): boolean { return this._isRound; } set isRound(value: boolean) { this._isRound = value; this._draw(this.maskRect, false, this); this.reset(this.maskRect.w, this.maskRect.h); } /** * 设置是否可拖动改变裁剪框比例 * @param value */ setResize(value: boolean): void { if (!value) { this.touchEnd(); } this.resize = value; this._draw(this.maskRect, false, this); this.root.onPhotoChange && this.root.onPhotoChange({ target: this, type: 'maskResize' }); } getResize(): boolean { return this.resize; } /** * 获取裁剪信息 * @param maxPixel 裁剪长边像素 */ getCutInfo(maxPixel?: number): {cutSize: Square; showInfo: RectFull } | null { const photoMain = this.root.getEventList<PhotoMain>('PhotoMain'); if (!photoMain || !photoMain.originalImg || !photoMain.img) { return null; } const originalImg = photoMain.originalImg; const showRect = photoMain.showRect; const maskRect = this.maskRect; let r; // 缩放比例 if (maxPixel) { const k = maskRect.w / maskRect.h; if (k < 1) { r = maxPixel * k / maskRect.w; } else { r = maxPixel / maskRect.w; } } else { r = originalImg.width / showRect.w; } const cutSize = { w: Math.round(maskRect.w * r), h: Math.round(maskRect.h * r) }; const showInfo: RectFull = { x: (showRect.x - showRect.w / 2) * r, y: (showRect.y - showRect.h / 2) * r, w: showRect.w * r, h: showRect.h * r, r: showRect.r, sV: showRect.sV, sH: showRect.sH } return {cutSize, showInfo }; } /** * 裁剪 * @maxPixel 裁剪长边像素 * @encoderOptions 裁剪压缩率(仅jpg) * @format 裁剪格式 */ clip(maxPixel?: number, encoderOptions?: number, format?: string): ClipResult | null { const photoMain = this.root.getEventList<PhotoMain>('PhotoMain'); if (!photoMain || !photoMain.originalImg || !photoMain.img) { return null; } const originalImg = photoMain.originalImg; const { cutSize, showInfo } = this.getCutInfo(maxPixel) as {cutSize: Square; showInfo: RectFull }; const base64 = this._isRound ? $tool.clipByRound(originalImg, cutSize.w, cutSize.h, showInfo, encoderOptions, format) : $tool.clipBy(originalImg, cutSize.w, cutSize.h, showInfo, encoderOptions, format); return { src: base64, file: $tool.base64ToBlob(base64) } } /** * 计算裁剪框矩形 */ private _getMaskRect(): Rect { const k1 = this.width / this.height; const k2 = this.root.drawWidth / this.root.drawHeight; let w, h; if (k1 < k2) { h = this.root.drawHeight * 0.75; w = k1 * h; } else { w= this.root.drawWidth * 0.75; h = w / k1; } return { x: -w / 2, y: -h / 2, w, h } } /** * 动画 * @private */ _animation(offX: number, offY: number, offW: number, offH: number): void { if (!offX && !offY && !offW && !offH) { return; } const {x, y, w, h} = this.maskRect; this._maskRect = this.maskRect; this.maskRect = { x: x + offX, y: y + offY, w: w + offW, h: h + offH }; this.animation = createAnimation({ duration: 300, timing: 'ease-in-out', change: (i, j) => { this._maskRect = { x: x + j * offX, y: y + j * offY, w: w + j * offW, h: h + j * offH } this._draw(this._maskRect, false, this); }, end: () => { if (this._maskRect) { this.maskRect = this._maskRect; this._maskRect = undefined; } } }).start(); } /** * 指定坐标与裁剪框边框的碰撞检测 * @param x * @param y * @private * @return 返回碰撞位置 */ _isHover (x: number, y: number): string | undefined { const ft = this.faultTolerant; const lw = 2; const {x: mx, y: my, w: mw, h: mh} = this.maskRect; if (x >= mx - ft - lw && x <= mx + ft && y >= my - ft - lw && y <= my + ft) { return 'Top Left'; } else if (x >= mx + mw - ft - lw && x <= mx + mw + ft && y >= my - ft - lw && y <= my + ft) { return 'Top Right'; } else if (x >= mx - ft - lw && x <= mx + ft && y >= my + mh - ft - lw && y <= my + mh + ft) { return 'Bottom Left'; } else if (x >= mx + mw - ft - lw && x <= mx + mw + ft && y >= my + mh - ft - lw && y <= my + mh + ft) { return 'Bottom Right'; } else if (x >= mx && x <= mx + mw && y >= my - ft - lw && y <= my + ft) { return 'Top'; } else if (x >= mx - ft - lw && x <= mx + ft && y >= my && y <= my + mh) { return 'Left'; } else if (x >= mx + mw - ft - lw && x <= mx + mw + ft && y >= my && y <= my + mh) { return 'Right'; } else if (x >= mx && x <= mx + mw && y >= my + mh - ft - lw && y <= my + mh + ft) { return 'Bottom'; } } touchStart(tps: TouchePoint[]): void { if (this.resize && this.touche === null) { const tp = tps[0]; this.touchePosition = this._isHover(tp.x, tp.y); if (this.touchePosition) { this.root.setPriority(this); this.touche = tp; this._draw(this.maskRect, true, this); } } } touchEnd(): void { if (this.touche !== null && this.touchePosition) { this.touche = null; if (this.maskRect.w < 0) { this.maskRect.x += this.maskRect.w; this.maskRect.w *= -1; } if (this.maskRect.h < 0) { this.maskRect.y += this.maskRect.h; this.maskRect.h *= -1; } this.reset(this.maskRect.w, this.maskRect.h); this.root.deletePriority(this.className); this.touchePosition = undefined; this._draw(this._maskRect ||this.maskRect, false, this); this.root.cursor = 'default'; } } touchMove(tps: TouchePoint[]): void { if (this.resize && this.touche !== null && this.touchePosition) { const toucheId = this.touche.id; const tp = tps.find(t => t.id === toucheId); if (tp) { this.touchePosition.split(' ').forEach(str => { switch (str) { case 'Top': this._moveTop(tp); break; case 'Bottom': this._moveBottom(tp); break; case 'Left': this._moveLeft(tp); break; case 'Right': this._moveRight(tp); break; } }); this.touche = tp; this._draw(this.maskRect, true, this); this.root.onPhotoChange && this.root.onPhotoChange({ target: this, type: 'maskMove' }); } } else if (this.resize) { const touchePosition = this._isHover(tps[0].x, tps[0].y); this.root.cursor = touchePosition && cursorConfig.get(touchePosition) || 'move'; } } wheelStart(): void { return; } wheelEnd(): void { return; } wheelChange(): void { return; } private _moveTop (tp: TouchePoint) { const _y = tp.y - (this.touche as TouchePoint).y; this.maskRect.y += _y; this.maskRect.h -= _y; } private _moveBottom (tp: TouchePoint) { const _y = tp.y - (this.touche as TouchePoint).y; this.maskRect.h += _y; } private _moveLeft (tp: TouchePoint) { const _x = tp.x - (this.touche as TouchePoint).x; this.maskRect.x += _x; this.maskRect.w -= _x; } private _moveRight (tp: TouchePoint) { const _x = tp.x - (this.touche as TouchePoint).x; this.maskRect.w += _x; } }
the_stack
import path = require('path'); import { ForceIgnore } from '@salesforce/source-deploy-retrieve/lib/src/metadata-registry/forceIgnore'; import { ConfigFile, ConfigContents, Logger, fs as fscore, SfdxProject } from '@salesforce/core'; import { isEmpty } from '@salesforce/kit'; import { Dictionary, Nullable } from '@salesforce/ts-types'; import Org = require('../core/scratchOrgApi'); import Messages = require('../messages'); import { SourcePathInfo, SourcePathStatusManager } from './sourcePathStatusManager'; const messages = Messages(); const Package2ConfigFileNames = ['package2-descriptor.json', 'package2-manifest.json']; type WorkspacePath = string; type PathInfos = Map<WorkspacePath, SourcePathInfo>; /** * The Workspace class is responsible for traversing the project directory * and creating SourcePathInfos for each source path and directory. */ export namespace Workspace { export interface Options extends ConfigFile.Options { org: any; forceIgnore: ForceIgnore; isStateless: boolean; } } // eslint-disable-next-line no-redeclare export class Workspace extends ConfigFile<Workspace.Options> { private org: Org; private forceIgnore: ForceIgnore; private isStateless: boolean; private backupPath: string; private logger!: Logger; public pathInfos: PathInfos = new Map(); public workspacePath: string; public trackedPackages: string[] = []; constructor(options: Workspace.Options) { super(options); this.org = options.org; this.forceIgnore = options.forceIgnore; this.isStateless = options.isStateless; this.workspacePath = options.org.config.getProjectPath(); } protected async init(): Promise<void> { this.logger = await Logger.child(this.constructor.name); this.options.filePath = path.join('orgs', this.org.name); this.options.filename = Workspace.getFileName(); await super.init(); this.backupPath = `${this.getPath()}.bak`; if (!this.isStateless) { await this.initializeCached(); const pathInfos = this.getContents(); if (isEmpty(pathInfos)) { await this.initializeStateFull(); } } else { this.initializeStateless(); } } private async initializeCached() { this.logger.debug('Reading workspace from cache'); let workspacePathChanged: boolean; const trackedPackages = []; try { const oldSourcePathInfos = [...this.values()]; let oldWorkspacePath: string; for (const sourcePathInfoObj of oldSourcePathInfos) { if (!sourcePathInfoObj.package) { const packagePath = SfdxProject.getInstance().getPackageNameFromPath(sourcePathInfoObj.sourcePath); if (packagePath) { sourcePathInfoObj.package = packagePath; } } if (sourcePathInfoObj.isWorkspace) { oldWorkspacePath = sourcePathInfoObj.sourcePath; } if (sourcePathInfoObj.isArtifactRoot) { trackedPackages.push(sourcePathInfoObj.sourcePath); } } this.trackedPackages = trackedPackages; workspacePathChanged = !!oldWorkspacePath && this.workspacePath !== oldWorkspacePath; for (const sourcePathInfoObj of oldSourcePathInfos) { const sourcePathInfo = await SourcePathInfo.create(sourcePathInfoObj); if (workspacePathChanged) { const oldPath = sourcePathInfo.sourcePath; sourcePathInfo.sourcePath = path.join( this.workspacePath, path.relative(oldWorkspacePath, sourcePathInfo.sourcePath) ); this.unset(oldPath); } this.set(sourcePathInfo.sourcePath, sourcePathInfo); } } catch (e) { // Do nothing if the file can't be read, which will cause the workspace to be initialized } if (workspacePathChanged) { await this.write(); } } private async initializeStateFull() { this.logger.debug('Initializing statefull workspace'); const packages = SfdxProject.getInstance() .getUniquePackageDirectories() .map((p) => stripTrailingSlash(p.fullPath)); this.trackedPackages = packages; await this.walkDirectories(packages); await this.write(); } private initializeStateless() { this.logger.debug('Initializing stateless workspace'); this.trackedPackages = SfdxProject.getInstance() .getUniquePackageDirectories() .map((p) => stripTrailingSlash(p.fullPath)); this.setContents({}); } public getContents(): Dictionary<SourcePathInfo.Json> { return this['contents'] as Dictionary<SourcePathInfo.Json>; } public entries(): Array<[string, SourcePathInfo.Json]> { // override entries and cast here to avoid casting every entries() call return super.entries() as Array<[string, SourcePathInfo.Json]>; } public static getFileName(): string { return 'sourcePathInfos.json'; } public async rewriteInfos() { await this.initializeStateFull(); } public async walkDirectories(directories: string[]) { for (const directory of directories) { const exists = await fscore.fileExists(directory); if (!exists) { const error = new Error(messages.getMessage('InvalidPackageDirectory', directory)); error['name'] = 'InvalidProjectWorkspace'; throw error; } await this.walk(directory); } } /** * Walks the directory using native fs.readdir */ public async walk(directory: string, recur?: boolean): Promise<void> { if (!recur) { await this.handleArtifact(directory, directory); } const files = await fscore.readdir(directory); for (const filename of files) { const sourcePath = path.join(directory, filename); const sourcePathInfo = await this.handleArtifact(sourcePath, directory); if (sourcePathInfo.isDirectory) { await this.walk(sourcePath, true); } } } public async handleArtifact(sourcePath: string, parentDirectory?: string): Promise<SourcePathInfo> { const isWorkspace = false; const isArtifactRoot = parentDirectory ? sourcePath === parentDirectory : false; const sourcePathInfo = await SourcePathInfo.create({ sourcePath, deferContentHash: false, isWorkspace, isArtifactRoot, }); if (this.isValidSourcePath(sourcePathInfo)) { this.set(sourcePath, sourcePathInfo); } return sourcePathInfo; } /** * Check if the given sourcePath should be ignored */ public isValidSourcePath(sourcePathInfo: SourcePathInfo): boolean { const sourcePath = sourcePathInfo.sourcePath; let isValid = this.forceIgnore.accepts(sourcePath); const basename = path.basename(sourcePath); const isPackage2ConfigFile = Package2ConfigFileNames.includes(basename); isValid = !basename.startsWith('.') && !basename.endsWith('.dup') && isValid && !isPackage2ConfigFile; if (isValid && !!SourcePathStatusManager.metadataRegistry) { if (!sourcePathInfo.isDirectory) { if (!SourcePathStatusManager.metadataRegistry.isValidSourceFilePath(sourcePath)) { const error = new Error(`Unexpected file found in package directory: ${sourcePath}`); error['name'] = 'UnexpectedFileFound'; throw error; } } } // Skip directories/files beginning with '.', end with .dup, and that should be ignored return isValid; } public async write() { if (!this.has(this.workspacePath)) { const workspaceSourcePathInfo = await SourcePathInfo.create({ sourcePath: this.workspacePath, deferContentHash: false, isWorkspace: true, isArtifactRoot: false, }); this.set(this.workspacePath, workspaceSourcePathInfo); } return super.write(); } public get(key: string): Nullable<SourcePathInfo.Json> { return this.getContents()[key]; } public async getInitializedValue(key: string): Promise<SourcePathInfo> { const value = this.get(key); return SourcePathInfo.create(value); } public has(key: string): boolean { return !!this.get(key); } public values(): SourcePathInfo.Json[] { return super.values() as SourcePathInfo.Json[]; } public async getInitializedValues(): Promise<SourcePathInfo[]> { const values = this.values(); const initialized: SourcePathInfo[] = []; for (const value of values) { initialized.push(await SourcePathInfo.create(value)); } return initialized; } // @ts-ignore because typescript expects value to be a SourcePathInfo.Json but we want to do the // conversion from a SourcePathInfo instance to SourcePathInfo.Json here instead of relying on whoever // calls this method to do it first. public set(key: string, value: SourcePathInfo) { return super.set(key, value.toJson()); } protected setMethod(contents: Dictionary<SourcePathInfo.Json>, key: string, value: SourcePathInfo.Json) { contents[key] = value; } public async revert() { if (await fscore.fileExists(this.backupPath)) { const backedupContents = await fscore.readFile(this.backupPath, 'UTF-8'); this.setContentsFromObject(JSON.parse(backedupContents)); await this.write(); await fscore.unlink(this.backupPath); } } public async backup() { // eslint-disable-next-line @typescript-eslint/no-misused-promises if (this.exists()) { await fscore.writeFile(this.backupPath, JSON.stringify(this.getContents())); } } public async read() { try { return await super.read(); } catch (err) { if (err.name === 'JsonDataFormatError') { // This error means that the old sourcePathInfos format is still // in use and so we need to convert it to the new format. const contents = await fscore.readFile(this.getPath(), 'utf-8'); const map = new Map(JSON.parse(contents)); const obj: ConfigContents = {}; map.forEach((value: SourcePathInfo.Json, key: string) => (obj[key] = value)); this.setContentsFromObject(obj); await this.write(); return this.getContents(); } } } } function stripTrailingSlash(str: string): string { return str.endsWith(path.sep) ? str.slice(0, -1) : str; }
the_stack
import { BulkFileHandle, SessionConfiguration, CreateSessionOptions } from "@extraterm/extraterm-extension-api"; import { html, render } from "extraterm-lit-html"; import { CustomElement, Attribute, Observe } from "extraterm-web-component-decorators"; import { Logger, getLogger } from "extraterm-logging"; import { log } from "extraterm-logging"; import { BulkFileBroker } from "./bulk_file_handling/BulkFileBroker"; import * as config from "../Config"; import * as DisposableUtils from "../utils/DisposableUtils"; import * as DomUtils from "./DomUtils"; import { EmbeddedViewer } from "./viewers/EmbeddedViewer"; import { EmptyPaneMenu } from "./command/EmptyPaneMenu"; import { EVENT_DRAG_STARTED, EVENT_DRAG_ENDED } from "./GeneralEvents"; import { ElementMimeType, FrameMimeType } from "./InternalMimeTypes"; import { KeybindingsManager } from "./keybindings/KeyBindingsManager"; import { SettingsTab } from "./settings/SettingsTab"; import { DroppedEventDetail as SnapDroppedEventDetail, DropLocation } from "./gui/SnapDropContainer"; import { SplitLayout } from "./SplitLayout"; import { SplitOrientation } from "./gui/Splitter"; import * as SupportsClipboardPaste from "./SupportsClipboardPaste"; import { Tab } from "./gui/Tab"; import { TabWidget, DroppedEventDetail } from "./gui/TabWidget"; import { EtTerminal, EXTRATERM_COOKIE_ENV } from "./Terminal"; import * as ThemeTypes from "../theme/Theme"; import { ThemeableElementBase } from "./ThemeableElementBase"; import { ViewerElement } from "./viewers/ViewerElement"; import * as ViewerElementTypes from "./viewers/ViewerElementTypes"; import { EtViewerTab } from "./ViewerTab"; import { PtyIpcBridge } from "./PtyIpcBridge"; import { ExtensionManager, ViewerTabDisplay } from "./extension/InternalTypes"; import { trimBetweenTags } from "extraterm-trim-between-tags"; import { NewTerminalContextArea } from "./NewTerminalContextArea"; import { CommandAndShortcut } from "./command/CommandPalette"; import { dispatchContextMenuRequest, ContextMenuType, ExtensionContextOverride } from "./command/CommandUtils"; import { TerminalVisualConfig, injectTerminalVisualConfig } from "./TerminalVisualConfig"; import { doLater } from "extraterm-later"; import { focusElement } from "./DomUtils"; import { ConfigDatabase } from "../ConfigDatabase"; const VisualState = ViewerElementTypes.VisualState; const ID_TOP_LAYOUT = "ID_TOP_LAYOUT"; const ID_MAIN_CONTENTS = "ID_MAIN_CONTENTS"; const ID_TITLE_BAR = "ID_TITLE_BAR"; const ID_TITLE_BAR_SPACE = "ID_TITLE_BAR_SPACE"; const ID_DRAG_BAR = "ID_DRAG_BAR"; const ID_TOP_RESIZE_BAR = "ID_TOP_RESIZE_BAR"; const ID_MINIMIZE_BUTTON = "ID_MINIMIZE_BUTTON"; const ID_MAXIMIZE_BUTTON = "ID_MAXIMIZE_BUTTON"; const ID_CLOSE_BUTTON = "ID_CLOSE_BUTTON"; const ID_NEW_TERMINAL_CONTEXT_AREA = "ID_NEW_TERMINAL_CONTEXT_AREA"; const ID_REST_SLOT = "ID_REST_SLOT"; const ID_REST_DIV_LEFT = "ID_REST_DIV_LEFT"; const CLASS_TAB_HEADER_CONTAINER = "tab_header_container"; const CLASS_TAB_HEADER_ICON = "tab_header_icon"; const CLASS_TAB_HEADER_MIDDLE = "tab_header_middle"; const CLASS_TAB_HEADER_TAG = "tab_header_tag"; const CLASS_TAB_HEADER_CLOSE = "tab_header_close"; const CLASS_TAB_CONTENT = "tab_content"; const CLASS_NEW_BUTTON_CONTAINER = "CLASS_NEW_BUTTON_CONTAINER"; const CLASS_NEW_TAB_BUTTON = "CLASS_NEW_TAB_BUTTON"; const CLASS_SPACE = "CLASS_SPACE"; const CLASS_MAIN_DRAGGING = "CLASS_MAIN_DRAGGING"; const CLASS_MAIN_NOT_DRAGGING = "CLASS_MAIN_NOT_DRAGGING"; /** * Top level UI component for a normal terminal window */ @CustomElement("extraterm-mainwebui") export class MainWebUi extends ThemeableElementBase implements ViewerTabDisplay { static TAG_NAME = "EXTRATERM-MAINWEBUI"; static EVENT_TAB_OPENED = "mainwebui-tab-opened"; static EVENT_TAB_CLOSED = "mainwebui-tab-closed"; static EVENT_TITLE = "mainwebui-title"; static EVENT_MINIMIZE_WINDOW_REQUEST = "mainwebui-minimize-window-request"; static EVENT_MAXIMIZE_WINDOW_REQUEST = "mainwebui-maximize-window-request"; static EVENT_CLOSE_WINDOW_REQUEST = "mainwebui-close-window-request"; static EVENT_QUIT_APPLICATION_REQUEST = "mainwebui-quit-application-request"; private _log: Logger; #ptyIpcBridge: PtyIpcBridge = null; #configDatabase: ConfigDatabase = null; #keybindingsManager: KeybindingsManager = null; #extensionManager: ExtensionManager = null; #themes: ThemeTypes.ThemeInfo[] = []; #terminalVisualConfig: TerminalVisualConfig = null; #lastFocus: Element = null; #splitLayout: SplitLayout = null; #fileBroker = new BulkFileBroker(); constructor() { super(); this.#splitLayout = new SplitLayout(); this._log = getLogger("ExtratermMainWebUI", this); this._handleViewerElementFocus = this._handleViewerElementFocus.bind(this); } setDependencies(configDatabase: ConfigDatabase, keyBindingManager: KeybindingsManager, extensionManager: ExtensionManager): void { this.#configDatabase = configDatabase; this.#keybindingsManager = keyBindingManager; this.#extensionManager = extensionManager; this._registerCommands(extensionManager); } connectedCallback(): void { super.connectedCallback(); this._setUpShadowDom(); this._setUpSplitLayout(); this._setupPtyIpc(); } @Attribute windowId = ""; @Observe("windowId") private _observeWindowId(target: string): void { this.#splitLayout.setWindowId(this.windowId); } focus(): void { if (this.#lastFocus != null) { this._focusTabContent(this.#lastFocus); } else { const allContentElements = this.#splitLayout.getAllTabContents(); if (allContentElements.length !== 0) { this._focusTabContent(allContentElements[0]); } } } render(): void { this.#splitLayout.update(); } setTerminalVisualConfig(terminalVisualConfig: TerminalVisualConfig): void { this.#terminalVisualConfig = terminalVisualConfig; const settingsTab = this._getSettingsTab(); if (settingsTab != null) { settingsTab.setTerminalVisualConfig(terminalVisualConfig); } for (const el of this.#splitLayout.getAllTabContents()) { injectTerminalVisualConfig(el, terminalVisualConfig); } } setThemes(themes: ThemeTypes.ThemeInfo[]): void { this.#themes = themes; const settingsTab = this._getSettingsTab(); if (settingsTab != null) { settingsTab.setThemes(this.#themes); } } getTabCount(): number { return this.#splitLayout.getAllTabContents().filter( (el) => !(el instanceof EmptyPaneMenu)).length; } getSplitLayout(): SplitLayout { return this.#splitLayout; } closeAllTabs(): void { const elements = this.#splitLayout.getAllTabContents().filter( (el) => !(el instanceof EmptyPaneMenu)); for (const element of elements) { this._disposeTab(element); } } private _setUpShadowDom(): void { this.attachShadow({ mode: "open", delegatesFocus: false }); const handleMainContainerFocus = { handleEvent: this._handleMainContainerFocusCapture.bind(this), capture: true }; render(html`${this._styleTag()} <div id=${ID_TOP_LAYOUT}> <div id=${ID_TITLE_BAR}> <div id=${ID_TITLE_BAR_SPACE}> <div id=${ID_TOP_RESIZE_BAR}></div> <div id=${ID_DRAG_BAR}></div> </div> ${this._showWindowControls() ? html` <button id=${ID_MINIMIZE_BUTTON} tabindex="-1" @click=${this._handleMinimizeClick.bind(this)}></button> <button id=${ID_MAXIMIZE_BUTTON} tabindex="-1" @click=${this._handleMaximizeClick.bind(this)}></button> <button id=${ID_CLOSE_BUTTON} tabindex="-1" @click=${this._handleCloseWindowClick.bind(this)}></button>` : null} </div> <div id=${ID_MAIN_CONTENTS} class=${CLASS_MAIN_NOT_DRAGGING} @focus=${handleMainContainerFocus} @click=${this._handleMainContainerClickEvent.bind(this)} @et-viewer-element_metadata-change=${this._handleViewerMetadataChanged.bind(this)}} @et-tab-widget_switch=${this._handleTabSwitchEvent.bind(this)} @et-tab-widget_dropped=${this._handleTabWidgetDroppedEvent.bind(this)} @et-snap-drop-container_dropped=${this._handleTabWidgetSnapDroppedEvent.bind(this)} @extraterm_drag-started=${this._handleDragStartedEvent.bind(this)} @extraterm_drag-ended=${this._handleDragEndedEvent.bind(this)}> </div> </div>`, this.shadowRoot); this.updateThemeCss(); const mainContainer = DomUtils.getShadowId(this, ID_MAIN_CONTENTS); DomUtils.addCustomEventResender(mainContainer, EVENT_DRAG_STARTED, this); DomUtils.addCustomEventResender(mainContainer, EVENT_DRAG_ENDED, this); } private _handleMainContainerFocusCapture(ev: FocusEvent): void { this.#extensionManager.updateExtensionWindowStateFromEvent(ev); } private _handleMinimizeClick(): void { focusElement(this, this._log); this._sendWindowRequestEvent(MainWebUi.EVENT_MINIMIZE_WINDOW_REQUEST); }; private _handleMaximizeClick(): void { focusElement(this, this._log); this._sendWindowRequestEvent(MainWebUi.EVENT_MAXIMIZE_WINDOW_REQUEST); }; private _handleCloseWindowClick(): void { focusElement(this, this._log); this._commandCloseWindow(); }; private _handleViewerMetadataChanged(ev: CustomEvent): void { const target = ev.target; if (target instanceof ViewerElement) { this._updateTabTitle(target); } } private _handleTabWidgetDroppedEvent(ev: CustomEvent): void { const detail = <DroppedEventDetail> ev.detail; if (ElementMimeType.equals(detail.mimeType, this.windowId)) { this._handleElementDroppedEvent(detail.targetTabWidget, detail.tabIndex, detail.dropData); } else if (FrameMimeType.equals(detail.mimeType, this.windowId)) { this._handleFrameDroppedEvent(detail.targetTabWidget, detail.tabIndex, detail.dropData); } } private _handleElementDroppedEvent(targetTabWidget: TabWidget, tabIndex: number, dropData: string): void { if (ElementMimeType.tagNameFromData(dropData) === Tab.TAG_NAME) { const tabElement = <Tab> DomUtils.getShadowId(this, ElementMimeType.elementIdFromData(dropData)); this.#splitLayout.moveTabToTabWidget(tabElement, targetTabWidget, tabIndex); this.#splitLayout.update(); const tabContent = this.#splitLayout.getTabContentByTab(tabElement); targetTabWidget.selectedIndex = tabIndex; this._focusTabContent(tabContent); } } private _handleFrameDroppedEvent(targetTabWidget: TabWidget, tabIndex: number, dropData: string): void { for (const el of this.#splitLayout.getAllTabContents()) { if (el instanceof EtTerminal) { const embeddedViewer = el.getEmbeddedViewerByFrameId(dropData); if (embeddedViewer != null) { const viewerTab = this._popOutEmbeddedViewer(embeddedViewer, el); const tab = this.#splitLayout.getTabByTabContent(viewerTab); this.#splitLayout.moveTabToTabWidget(tab, targetTabWidget, tabIndex); this.#splitLayout.update(); this.focusTab(viewerTab); return; } } } } private _handleTabWidgetSnapDroppedEvent(ev: CustomEvent): void { const detail = <SnapDroppedEventDetail> ev.detail; const target = ev.target; if (target instanceof TabWidget) { switch (detail.dropLocation) { case DropLocation.MIDDLE: this._handleTabWidgetSnapDroppedMiddleEvent(ev); break; case DropLocation.NORTH: this._handleTabWidgetSnapDroppedDirectionEvent(ev, SplitOrientation.HORIZONTAL, true); break; case DropLocation.SOUTH: this._handleTabWidgetSnapDroppedDirectionEvent(ev, SplitOrientation.HORIZONTAL, false); break; case DropLocation.WEST: this._handleTabWidgetSnapDroppedDirectionEvent(ev, SplitOrientation.VERTICAL, true); break; case DropLocation.EAST: this._handleTabWidgetSnapDroppedDirectionEvent(ev, SplitOrientation.VERTICAL, false); break; } } } private _handleTabWidgetSnapDroppedMiddleEvent(ev: CustomEvent): void { const detail = <SnapDroppedEventDetail> ev.detail; const target = ev.target; if (target instanceof TabWidget) { if (ElementMimeType.equals(detail.mimeType, this.windowId)) { this._handleElementDroppedEvent(target, target.selectedIndex + 1, detail.dropData); } else if (FrameMimeType.equals(detail.mimeType, this.windowId)) { this._handleFrameDroppedEvent(target, target.selectedIndex + 1, detail.dropData); } } } private _handleTabWidgetSnapDroppedDirectionEvent(ev: CustomEvent, orientation: SplitOrientation, splitBefore: boolean): void { const detail = <SnapDroppedEventDetail> ev.detail; const target = ev.target; if (target instanceof TabWidget) { const newTabWidget = splitBefore ? this.#splitLayout.splitBeforeTabWidget(target, orientation) : this.#splitLayout.splitAfterTabWidget(target, orientation); this.#splitLayout.update(); if (ElementMimeType.equals(detail.mimeType, this.windowId)) { this._handleElementDroppedEvent(newTabWidget, 0, detail.dropData); } else if (FrameMimeType.equals(detail.mimeType, this.windowId)) { this._handleFrameDroppedEvent(newTabWidget, 0, detail.dropData); } } } private _handleDragStartedEvent(ev: CustomEvent): void { const mainContainer = DomUtils.getShadowId(this, ID_MAIN_CONTENTS); mainContainer.classList.add(CLASS_MAIN_DRAGGING); mainContainer.classList.remove(CLASS_MAIN_NOT_DRAGGING); } private _handleDragEndedEvent(ev: CustomEvent): void { const mainContainer = DomUtils.getShadowId(this, ID_MAIN_CONTENTS); mainContainer.classList.remove(CLASS_MAIN_DRAGGING); mainContainer.classList.add(CLASS_MAIN_NOT_DRAGGING); } private _handleMainContainerClickEvent(ev): void { // This handler is intended to be triggered by the plus (new tab) button in the tab bar. for (const part of ev.path) { if (part instanceof HTMLButtonElement && part.classList.contains(CLASS_NEW_TAB_BUTTON)) { let el: HTMLElement = part; while (el != null && ! (el instanceof TabWidget)) { el = el.parentElement; } if (this.#configDatabase.getSessionConfig().length !== 0) { const sessionUuid = this.#configDatabase.getSessionConfig()[0].uuid; this.commandNewTerminal({sessionUuid}); } } } } private _setUpSplitLayout(): void { this.#splitLayout.setRootContainer(DomUtils.getShadowId(this, ID_MAIN_CONTENTS)); this.#splitLayout.setTabContainerFactory( (tabWidget: TabWidget, tab: Tab, tabContent: Element): Element => { const divContainer = document.createElement("DIV"); divContainer.classList.add(CLASS_TAB_CONTENT); return divContainer; }); this.#splitLayout.setRightSpaceDefaultElementFactory( (): Element => { const tempDiv = document.createElement("DIV"); tempDiv.innerHTML = this._newTabRestAreaHtml(); return tempDiv.children.item(0); }); this.#splitLayout.setTopLeftElement(this._leftControls()); this.#splitLayout.setTopRightElement(this._menuControls()); this.#splitLayout.setEmptySplitElementFactory( (previousElement: Element): Element => { let emptyPaneMenu: EmptyPaneMenu = <EmptyPaneMenu> previousElement; if (emptyPaneMenu == null) { emptyPaneMenu = <EmptyPaneMenu> document.createElement(EmptyPaneMenu.TAG_NAME); emptyPaneMenu.addEventListener("selected", (ev: CustomEvent): void => { const windowState = this.#extensionManager.getExtensionWindowStateFromEvent(ev); emptyPaneMenu.setFilter(""); for (const entry of entriesAndShortcuts) { if (entry.id === ev.detail.selected) { this.#extensionManager.executeCommandWithExtensionWindowState(windowState, entry.command); } } }); } const entries = this.#extensionManager.queryCommands({ emptyPaneMenu: true, categories: ["application", "window", "textEditing", "terminal", "terminalCursorMode", "viewer"], when: true }); const termKeybindingsMapping = this.#keybindingsManager.getKeybindingsMapping(); const entriesAndShortcuts = entries.map((entry): CommandAndShortcut => { const shortcuts = termKeybindingsMapping.getKeyStrokesForCommand(entry.command); const shortcut = shortcuts.length !== 0 ? shortcuts[0].formatHumanReadable() : ""; return { id: entry.command + "_" + entry.category, shortcut, markedupLabel: entry.title, score: 0, ...entry }; }); emptyPaneMenu.setEntries(entriesAndShortcuts); return emptyPaneMenu; }); } private _menuControls(): Element { const tempDiv = document.createElement("DIV"); tempDiv.innerHTML = this._newTabRestAreaHtml(`<slot id="${ID_REST_SLOT}"></slot>`); return tempDiv.children.item(0); } private _leftControls(): Element { const tempDiv = document.createElement("DIV"); tempDiv.innerHTML = `<div id="${ID_REST_DIV_LEFT}"></div>`; return tempDiv.children.item(0); } private _showWindowControls(): boolean { const systemConfig = this.#configDatabase.getSystemConfig(); return systemConfig.titleBarStyle === "theme" && process.platform !== "darwin"; } private _newTabRestAreaHtml(extraContents = ""): string { return trimBetweenTags(` <div class="${CLASS_NEW_BUTTON_CONTAINER}"> <${NewTerminalContextArea.TAG_NAME} id="${ID_NEW_TERMINAL_CONTEXT_AREA}"> <button class="microtool primary ${CLASS_NEW_TAB_BUTTON}"><i class="fa fa-plus"></i></button> </${NewTerminalContextArea.TAG_NAME}> <div class="${CLASS_SPACE}"></div> ${extraContents} </div> `); } protected _themeCssFiles(): ThemeTypes.CssFile[] { return [ThemeTypes.CssFile.GENERAL_GUI, ThemeTypes.CssFile.FONT_AWESOME, ThemeTypes.CssFile.EXTRAICONS, ThemeTypes.CssFile.MAIN_UI]; } private _addTab(tabContentElement: HTMLElement, tabWidget: TabWidget=null): Tab { const isTerminal = tabContentElement instanceof EtTerminal; if (tabWidget == null) { tabWidget = this.#splitLayout.firstTabWidget(); } const newTab = <Tab> document.createElement(Tab.TAG_NAME); newTab.tabIndex = -1; newTab.addEventListener("contextmenu", this._handleTabHeaderContextMenu.bind(this, tabContentElement), true); this._renderTabHtml(newTab, tabContentElement); this.#splitLayout.appendTab(tabWidget, newTab, tabContentElement); this.#splitLayout.update(); if (isTerminal) { const extensionsDiv = <HTMLDivElement> newTab.querySelector(".tab_title_extensions"); this._addTabTitleWidgets(extensionsDiv, <EtTerminal> tabContentElement); } return newTab; } private _renderTabHtml(tab: Tab, tabContentElement: Element): void { const isTerminal = tabContentElement instanceof EtTerminal; let title = ""; let icon = null; let tag: string = null; if (tabContentElement instanceof EtViewerTab) { title = tabContentElement.getMetadata().title; icon = tabContentElement.getMetadata().icon; if (tabContentElement.getTag() !== null) { tag = tabContentElement.getTag(); } } else if (tabContentElement instanceof ViewerElement) { title = tabContentElement.getMetadata().title; icon = tabContentElement.getMetadata().icon; } else if ( ! isTerminal) { this._log.warn(`Unrecognized element type in _updateTabTitle(). ${tabContentElement}`); } const template = html` <div class=${CLASS_TAB_HEADER_CONTAINER}> ${isTerminal ? html`<div class="tab_title_extensions"></div>` : html` <div class=${CLASS_TAB_HEADER_ICON}>${icon != null ? html`<i class=${icon}></i>` : null}</div> <div class=${CLASS_TAB_HEADER_MIDDLE} title=${title}>${title}</div> <div class=${CLASS_TAB_HEADER_TAG}>${tag != null ? html`<i class="fa fa-tag"></i> ${tag}` : null}</div>`} <div class=${CLASS_TAB_HEADER_CLOSE}> <button @click=${this._disposeTab.bind(this, tabContentElement)} class="microtool danger"> <i class="fa fa-times"></i> </button> </div> </div>`; render(template, tab); } private _handleTabHeaderContextMenu(tabContentElement: Element, ev: MouseEvent): void { ev.stopImmediatePropagation(); ev.preventDefault(); const override: ExtensionContextOverride = {}; if (tabContentElement instanceof EtTerminal) { override.activeTerminal = tabContentElement; } dispatchContextMenuRequest(this, ev.clientX, ev.clientY, ContextMenuType.TERMINAL_TAB, override); } private _addTabTitleWidgets(extensionsDiv: HTMLDivElement, terminal: EtTerminal): void { const widgets = this.#extensionManager.createNewTerminalTabTitleWidgets(terminal); for (const widget of widgets) { extensionsDiv.appendChild(widget); } } private _tabWidgetFromElement(el: Element): TabWidget { return this.#splitLayout.getTabWidgetByTabContent(el); } private _handleTabSwitchEvent(ev: CustomEvent): void { if (ev.target instanceof TabWidget) { const el = this.#splitLayout.getTabContentByTab(ev.target.getSelectedTab()); let title = ""; if (el instanceof EtTerminal) { title = el.getTerminalTitle(); } else if (el instanceof EtViewerTab || el instanceof ViewerElement) { title = el.getMetadata().title; } this._sendTitleEvent(title); this._focusTabContent(el); } } private newTerminalTab(sessionConfiguration: SessionConfiguration, workingDirectory: string, tabWidget: TabWidget=null): EtTerminal { const newTerminal = <EtTerminal> document.createElement(EtTerminal.TAG_NAME); newTerminal.setDependencies(this.#configDatabase, this.#keybindingsManager, this.#extensionManager, this.#fileBroker); newTerminal.setWindowId(this.windowId); newTerminal.setFrameFinder(this._frameFinder.bind(this)); newTerminal.setTerminalVisualConfig(this.#terminalVisualConfig); newTerminal.setSessionConfiguration(sessionConfiguration); // Set the default name of the terminal tab to the session name. newTerminal.setTerminalTitle(sessionConfiguration.name); this._addTab(newTerminal, tabWidget); this._setUpNewTerminalEventHandlers(newTerminal); this._createPtyForTerminal(newTerminal, sessionConfiguration.uuid, workingDirectory); this._sendTabOpenedEvent(); return newTerminal; } private _getSessionByUuid(sessionUuid: string): SessionConfiguration { const sessions = this.#configDatabase.getSessionConfigCopy(); for (const session of sessions) { if (session.uuid === sessionUuid) { return session; } } return null; } private _getSessionByName(sessionName: string): SessionConfiguration { const sessions = this.#configDatabase.getSessionConfigCopy(); for (const session of sessions) { if (session.name === sessionName) { return session; } } return null; } private _createPtyForTerminal(newTerminal: EtTerminal, sessionUuid: string, workingDirectory: string): void { const extraEnv = { [EXTRATERM_COOKIE_ENV]: newTerminal.getExtratermCookieValue(), "COLORTERM": "truecolor", // Advertise that we support 24bit color }; const sessionOptions: CreateSessionOptions = { extraEnv, cols: newTerminal.getColumns(), rows: newTerminal.getRows() }; if (workingDirectory != null) { sessionOptions.workingDirectory = workingDirectory; } const pty = this.#ptyIpcBridge.createPtyForTerminal(sessionUuid, sessionOptions); pty.onExit(() => { this._disposeTab(newTerminal); }); newTerminal.setPty(pty); } private _setUpNewTerminalEventHandlers(newTerminal: EtTerminal): void { newTerminal.addEventListener("focus", (ev: FocusEvent) => { this.#lastFocus = newTerminal; }); newTerminal.addEventListener(EtTerminal.EVENT_TITLE, (ev: CustomEvent): void => { this._updateTabTitle(newTerminal); this._sendTitleEvent(ev.detail.title); }); newTerminal.addEventListener(EtTerminal.EVENT_EMBEDDED_VIEWER_POP_OUT, this._handleEmbeddedViewerPopOutEvent.bind(this)); } private _handleEmbeddedViewerPopOutEvent(ev: CustomEvent): void { this._popOutEmbeddedViewer(ev.detail.embeddedViewer, ev.detail.terminal); } private _popOutEmbeddedViewer(embeddedViewer: EmbeddedViewer, terminal: EtTerminal): EtViewerTab { const viewerTab = this._openEmbeddedViewerInTab(embeddedViewer, terminal.getFontAdjust()); this.focusTab(viewerTab); terminal.deleteEmbeddedViewer(embeddedViewer); return viewerTab; } private _openEmbeddedViewerInTab(embeddedViewer: EmbeddedViewer, fontAdjust: number): EtViewerTab { const viewerElement = embeddedViewer.getViewerElement(); const viewerTab = <EtViewerTab> document.createElement(EtViewerTab.TAG_NAME); viewerTab.setDependencies(this.#configDatabase, this.#keybindingsManager, this.#extensionManager); viewerTab.setFontAdjust(fontAdjust); viewerTab.setTitle(embeddedViewer.getMetadata().title); viewerTab.setTag(embeddedViewer.getTag()); viewerElement.setMode(ViewerElementTypes.Mode.CURSOR); viewerElement.setVisualState(VisualState.AUTO); this.openViewerTab(viewerTab); viewerTab.setViewerElement(viewerElement); return viewerTab; } openViewerTab(viewerElement: ViewerElement, tabWidget: TabWidget=null): void { viewerElement.setFocusable(true); this._addTab(viewerElement, tabWidget); viewerElement.addEventListener("focus", this._handleViewerElementFocus); this._sendTabOpenedEvent(); } private _handleViewerElementFocus(ev: FocusEvent): void { this.#lastFocus = <Element> ev.target; } closeViewerTab(viewerElement: ViewerElement): void { this.closeTab(viewerElement); } switchToTab(viewerElement: ViewerElement): void { this.focusTab(viewerElement); } private _updateTabTitle(el: HTMLElement): void { if (el instanceof EtTerminal) { return; } const tab = this.#splitLayout.getTabByTabContent(el); this._renderTabHtml(tab, el); } private _getSettingsTab(): SettingsTab { const settingsTabs = this.#splitLayout.getAllTabContents().filter(el => el instanceof SettingsTab); if (settingsTabs.length !== 0) { return <SettingsTab> settingsTabs[0]; } else { return null; } } commandOpenSettingsTab(tabName: string=null): void { const settingsTab = this._getSettingsTab(); if (settingsTab != null) { this.focusTab(settingsTab); } else { const settingsTabElement = <SettingsTab> document.createElement(SettingsTab.TAG_NAME); settingsTabElement.setDependencies(this.#configDatabase, this.#keybindingsManager, this.#extensionManager); settingsTabElement.setTerminalVisualConfig(this.#terminalVisualConfig); settingsTabElement.setThemes(this.#themes); if (tabName != null) { settingsTabElement.setSelectedTab(tabName); } this.openViewerTab(settingsTabElement); this.focusTab(settingsTabElement); } } private _commandApplicationQuit(): void { this._sendWindowRequestEvent(MainWebUi.EVENT_QUIT_APPLICATION_REQUEST); } closeTab(tabContentElement: Element): void { const tabWidget = this.#splitLayout.getTabWidgetByTabContent(tabContentElement); const tabWidgetContents = this.#splitLayout.getTabContentsByTabWidget(tabWidget); this.#splitLayout.removeTabContent(tabContentElement); this.#splitLayout.update(); const oldIndex = tabWidgetContents.indexOf(tabContentElement); if (tabWidgetContents.length >= 2) { this.focusTab(tabWidgetContents[oldIndex === 0 ? 1 : oldIndex-1]); } else { const tabContents = this.#splitLayout.getTabContentsByTabWidget(tabWidget); if (tabContents.length !== 0) { this.focusTab(tabContents[0]); } } if (tabContentElement instanceof ViewerElement) { tabContentElement.didClose(); } this._sendTabClosedEvent(tabContentElement); } private _disposeTab(tabContentElement: Element): void { this.closeTab(tabContentElement); if (tabContentElement instanceof EtTerminal) { const pty = tabContentElement.getPty(); if (pty !== null) { pty.destroy(); } const allTerminals = this._getAllTerminals().filter(t => t !== tabContentElement); this.#extensionManager.terminalDestroyed(tabContentElement, allTerminals); } if (DisposableUtils.isDisposable(tabContentElement)) { tabContentElement.dispose(); } } focusTab(tabContentElement: Element): void { this.#splitLayout.showTabByTabContent(tabContentElement); this._focusTabContent(tabContentElement); // FIXME This is a work-around for the problem where new tabs can't get the focus immediately. if ( ! DomUtils.activeNestedElements().includes(tabContentElement)) { doLater(() => { this.#splitLayout.showTabByTabContent(tabContentElement); this._focusTabContent(tabContentElement); }); } } private _selectAdjacentTab(tabWidget: TabWidget, direction: number): void { const contents = this.#splitLayout.getTabContentsByTabWidget(tabWidget); const len = contents.length; if (len === 0) { return; } let i = tabWidget.selectedIndex; i = i + direction; if (i < 0) { i = len - 1; } else if (i >= len) { i = 0; } tabWidget.selectedIndex = i; this._focusTabContent(contents[i]); } private _focusPaneLeft(tabElement: Element): { tabWidget: TabWidget, tabContent: Element} { return this._focusPaneInDirection(tabElement, this.#splitLayout.getTabWidgetToLeft); } private _focusPaneRight(tabElement: Element): { tabWidget: TabWidget, tabContent: Element} { return this._focusPaneInDirection(tabElement, this.#splitLayout.getTabWidgetToRight); } private _focusPaneAbove(tabElement: Element): { tabWidget: TabWidget, tabContent: Element} { return this._focusPaneInDirection(tabElement, this.#splitLayout.getTabWidgetAbove); } private _focusPaneBelow(tabElement: Element): { tabWidget: TabWidget, tabContent: Element} { return this._focusPaneInDirection(tabElement, this.#splitLayout.getTabWidgetBelow); } private _focusPaneInDirection(tabElement: Element, directionFunc: (tabWidget: TabWidget) => TabWidget): { tabWidget: TabWidget, tabContent: Element} { const currentTabWidget = this.#splitLayout.getTabWidgetByTabContent(tabElement); const targetTabWidget = directionFunc.call(this.#splitLayout, currentTabWidget); if (targetTabWidget != null) { focusElement(targetTabWidget, this._log); const content = this.#splitLayout.getTabContentByTab(targetTabWidget.getSelectedTab()); if (elementSupportsFocus(content)) { focusElement(content, this._log); return { tabWidget: targetTabWidget, tabContent: content }; } return { tabWidget: targetTabWidget, tabContent: null }; } return { tabWidget: null, tabContent: null }; } private _moveTabElementToPaneLeft(tabElement: Element): void { this._moveTabElementToPaneInDirection(tabElement, this.#splitLayout.getTabWidgetToLeft); } private _moveTabElementToPaneRight(tabElement: Element): void { this._moveTabElementToPaneInDirection(tabElement, this.#splitLayout.getTabWidgetToRight); } private _moveTabElementToPaneUp(tabElement: Element): void { this._moveTabElementToPaneInDirection(tabElement, this.#splitLayout.getTabWidgetAbove); } private _moveTabElementToPaneDown(tabElement: Element): void { this._moveTabElementToPaneInDirection(tabElement, this.#splitLayout.getTabWidgetBelow); } private _moveTabElementToPaneInDirection(tabElement: Element, directionFunc: (tabWidget: TabWidget) => TabWidget): void { const currentTabWidget = this.#splitLayout.getTabWidgetByTabContent(tabElement); const targetTabWidget = directionFunc.call(this.#splitLayout, currentTabWidget); if (targetTabWidget != null) { this.#splitLayout.moveTabToTabWidget(this.#splitLayout.getTabByTabContent(tabElement), targetTabWidget, 0); this.#splitLayout.update(); focusElement(targetTabWidget, this._log); if (elementSupportsFocus(tabElement)) { focusElement(tabElement, this._log); } } } private _getTabElementWithFocus(): Element { for (const el of this.#splitLayout.getAllTabContents()) { if (elementSupportsFocus(el)) { if (el.hasFocus()) { return el; } } } return null; } private _focusTabContent(el: Element): void { if (el instanceof EtTerminal) { el.resizeToContainer(); focusElement(el, this._log); } else if (elementSupportsFocus(el)) { focusElement(el, this._log); } } private _horizontalSplit(tabContentElement: Element): void { this._split(tabContentElement, SplitOrientation.HORIZONTAL); } private _verticalSplit(tabContentElement: Element): void { this._split(tabContentElement, SplitOrientation.VERTICAL); } private _split(tabContentElement: Element, orientation: SplitOrientation): void { const newTabWidget = this.#splitLayout.splitAfterTabContent(tabContentElement, orientation); this.#splitLayout.update(); if (newTabWidget != null) { const element = this.#splitLayout.getEmptyContentByTabWidget(newTabWidget); if (element != null) { if (element instanceof EmptyPaneMenu) { // I can't figure out why a focusElement() doesn't work immediately. // It does work later though. doLater(() => { focusElement(element, this._log); }); } } else { const tabWidget = this.#splitLayout.getTabWidgetByTabContent(tabContentElement); focusElement(tabWidget, this._log); if (elementSupportsFocus(tabContentElement)) { focusElement(tabContentElement, this._log); } } } } private _closeSplit(tabContentElement: Element): void { let focusInfo: {tabWidget: TabWidget, tabContent: Element} = null; if (tabContentElement instanceof EmptyPaneMenu) { focusInfo = this._focusPaneLeft(tabContentElement); if (focusInfo.tabWidget == null) { focusInfo = this._focusPaneRight(tabContentElement); if (focusInfo.tabWidget == null) { focusInfo = this._focusPaneAbove(tabContentElement); if (focusInfo.tabWidget == null) { focusInfo = this._focusPaneBelow(tabContentElement); } } } } this.#splitLayout.closeSplitAtTabContent(tabContentElement); this.#splitLayout.update(); if (focusInfo == null) { const tabWidget = this.#splitLayout.getTabWidgetByTabContent(tabContentElement); focusInfo = {tabWidget, tabContent: tabContentElement}; } if (focusInfo.tabWidget != null) { focusElement(focusInfo.tabWidget, this._log); if (focusInfo.tabContent != null) { if (elementSupportsFocus(focusInfo.tabContent)) { focusElement(focusInfo.tabContent, this._log); } } } } /** * Copys the selection in the focussed terminal to the clipboard. */ copyToClipboard(): void { const elWithFocus = this._getTabElementWithFocus(); if (elWithFocus != null) { if (elWithFocus instanceof EtTerminal || elWithFocus instanceof EtViewerTab) { elWithFocus.copyToClipboard(); } } } /** * Pastes text into the terminal which has the input focus. * * @param text the text to paste. */ pasteText(text: string): void { const elWithFocus = this._getTabElementWithFocus(); if (elWithFocus != null && SupportsClipboardPaste.isSupportsClipboardPaste(elWithFocus)) { elWithFocus.pasteText(text); } } private _sendTabOpenedEvent(): void { const event = new CustomEvent(MainWebUi.EVENT_TAB_OPENED, { detail: null }); this.dispatchEvent(event); } private _sendTabClosedEvent(tabContentElement: Element): void { const event = new CustomEvent(MainWebUi.EVENT_TAB_CLOSED, { detail: { tabContentElement } }); this.dispatchEvent(event); } private _sendTitleEvent(title: string): void { const event = new CustomEvent(MainWebUi.EVENT_TITLE, { detail: {title: title} }); this.dispatchEvent(event); } private _sendWindowRequestEvent(eventName: string): void { const event = new CustomEvent(eventName, { }); this.dispatchEvent(event); } private _frameFinder(frameId: string): BulkFileHandle { for (const el of this.#splitLayout.getAllTabContents()) { let bulkFileHandle: BulkFileHandle = null; if (el instanceof EtViewerTab && el.getTag() === frameId) { bulkFileHandle = el.getFrameContents(frameId); } else if (el instanceof EtTerminal) { bulkFileHandle = el.getFrameContents(frameId); } if (bulkFileHandle != null) { return bulkFileHandle; } } return null; } private _registerCommands(extensionManager: ExtensionManager): void { const commands = extensionManager.getExtensionContextByName("internal-commands").commands; commands.registerCommand("extraterm:application.quit", (args: any) => this._commandApplicationQuit()); commands.registerCommand("extraterm:window.closePane", (args: any) => this._commandClosePane()); commands.registerCommand("extraterm:window.closeTab", (args: any) => this._commandCloseTab()); commands.registerCommand("extraterm:window.closeWindow", (args: any) => this._commandCloseWindow()); commands.registerCommand("extraterm:window.focusPaneAbove", (args: any) => this._commandFocusPaneAbove()); commands.registerCommand("extraterm:window.focusPaneBelow", (args: any) => this._commandFocusPaneBelow()); commands.registerCommand("extraterm:window.focusPaneLeft", (args: any) => this._commandFocusPaneLeft()); commands.registerCommand("extraterm:window.focusPaneRight", (args: any) => this._commandFocusPaneRight()); commands.registerCommand("extraterm:window.focusTabLeft", (args: any) => this._commandFocusTabLeft()); commands.registerCommand("extraterm:window.focusTabRight", (args: any) => this._commandFocusTabRight()); commands.registerCommand("extraterm:window.horizontalSplit", (args: any) => this._commandHorizontalSplit()); commands.registerCommand("extraterm:window.moveTabToPaneDown", (args: any) => this._commandMoveTabToPaneDown()); commands.registerCommand("extraterm:window.moveTabToPaneLeft", (args: any) => this._commandMoveTabToPaneLeft()); commands.registerCommand("extraterm:window.moveTabToPaneRight", (args: any) => this._commandMoveTabToPaneRight()); commands.registerCommand("extraterm:window.moveTabToPaneUp", (args: any) => this._commandMoveTabToPaneUp()); commands.registerCommand("extraterm:window.newTerminal", (args: any) => this.commandNewTerminal(args)); commands.registerCommand("extraterm:window.openSettings", (args: any) => this.commandOpenSettingsTab()); commands.registerCommand("extraterm:window.verticalSplit", (args: any) => this._commandVerticalSplit()); } private _getActiveTabElement(): HTMLElement { return this.#extensionManager.getActiveTab(); } private _getActiveTabWidget(): TabWidget { return this.#extensionManager.getActiveTabWidget(); } async commandNewTerminal(args: {sessionUuid?: string, sessionName?: string, workingDirectory?: string}): Promise<void> { let sessionConfiguration: SessionConfiguration = this.#configDatabase.getSessionConfig()[0]; if (args.sessionUuid != null) { sessionConfiguration = this._getSessionByUuid(args.sessionUuid); if (sessionConfiguration == null) { throw new Error(`Unable to find session with UUID ${args.sessionUuid}`); } } else if (args.sessionName != null) { sessionConfiguration = this._getSessionByName(args.sessionName); if (sessionConfiguration == null) { throw new Error(`Unable to find session with name ${args.sessionName}`); } } let workingDirectory: string = null; if (args.workingDirectory != null) { workingDirectory = args.workingDirectory; } else { const activeTerminal = this.#extensionManager.getActiveTerminal(); if (activeTerminal != null && activeTerminal.getSessionConfiguration().type === sessionConfiguration.type) { workingDirectory = await activeTerminal.getPty().getWorkingDirectory(); } } const newTerminal = this.newTerminalTab(sessionConfiguration, workingDirectory, this._getActiveTabWidget()); this.focusTab(newTerminal); this.#extensionManager.newTerminalCreated(newTerminal, this._getAllTerminals()); } private _getAllTerminals(): EtTerminal[] { return <EtTerminal[]> this.#splitLayout.getAllTabContents().filter(el => el instanceof EtTerminal); } private _commandFocusTabLeft(): void { this._selectAdjacentTab(this._tabWidgetFromElement(this._getActiveTabElement()), -1); } private _commandFocusTabRight(): void { this._selectAdjacentTab(this._tabWidgetFromElement(this._getActiveTabElement()), 1); } private _commandFocusPaneLeft(): void { this._focusPaneLeft(this._getActiveTabElement()); } private _commandFocusPaneRight(): void { this._focusPaneRight(this._getActiveTabElement()); } private _commandFocusPaneAbove(): void { this._focusPaneAbove(this._getActiveTabElement()); } private _commandFocusPaneBelow(): void { this._focusPaneBelow(this._getActiveTabElement()); } private _commandCloseTab(): void { this._disposeTab(this._getActiveTabElement()); } private _commandHorizontalSplit(): void { this._horizontalSplit(this._getActiveTabElement()); } private _commandVerticalSplit(): void { this._verticalSplit(this._getActiveTabElement()); } private _commandClosePane(): void { this._closeSplit(this._getActiveTabElement()); } private _commandMoveTabToPaneLeft(): void { this._moveTabElementToPaneLeft(this._getActiveTabElement()); } private _commandMoveTabToPaneRight(): void { this._moveTabElementToPaneRight(this._getActiveTabElement()); } private _commandMoveTabToPaneUp(): void { this._moveTabElementToPaneUp(this._getActiveTabElement()); } private _commandMoveTabToPaneDown(): void { this._moveTabElementToPaneDown(this._getActiveTabElement()); } private _commandCloseWindow(): void { this._sendWindowRequestEvent(MainWebUi.EVENT_CLOSE_WINDOW_REQUEST); } private _setupPtyIpc(): void { this.#ptyIpcBridge = new PtyIpcBridge(); } } interface Focusable { focus(options?: { preventScroll: boolean }): void; hasFocus(): boolean; } function elementSupportsFocus(content: Element | Focusable): content is Focusable & HTMLElement { return content instanceof EtTerminal || content instanceof EmptyPaneMenu || content instanceof EtViewerTab || content instanceof SettingsTab; }
the_stack
import { aws_stepfunctions, Stack } from "aws-cdk-lib"; import { Pass } from "aws-cdk-lib/aws-stepfunctions"; import "jest"; import { $AWS, $SFN, EventBus, Event, ExpressStepFunction, StepFunction, SyncExecutionResult, ErrorCodes, SynthError, } from "../src"; import { StateMachine, States, Task } from "../src/asl"; import { Function } from "../src/function"; import { initStepFunctionApp, normalizeCDKJson, Person } from "./util"; /** * Removes randomized values (CDK token strings) form the definitions. */ const normalizeDefinition = (definition: StateMachine<States>): any => { return normalizeCDKJson(definition); }; /** * Expect a task to match the given contents. Use Jest's `toMatchObject`. * Selects the task to check using the first key in states or by finding the key using the taskNameMatcher. */ const expectTaskToMatch = ( definition: StateMachine<States>, partialTask: Partial<Task>, taskNameMatcher?: string | RegExp ): any => { const [key] = !taskNameMatcher ? Object.keys(definition.States) : Object.keys(definition.States).filter((k) => typeof taskNameMatcher === "string" ? k.includes(taskNameMatcher) : taskNameMatcher.test(k) ); expect(key).toBeDefined(); const task = <Task>definition.States[key]; expect(task).toMatchObject(partialTask); }; test("empty function", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", () => {}).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("return identifier", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ id: string }, string>( stack, "fn", (input) => { return input.id; } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("return PropAccessExpr", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction( stack, "fn", (input: { input: { id: string } }) => { return input.input.id; } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("return optional PropAccessExpr", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction< { input: { id?: string } }, string | undefined >(stack, "fn", (input) => { return input.input?.id; }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("return items.slice(1)", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ items: string[] }, string[]>( stack, "fn", (input) => { return input.items.slice(1); } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("return items.slice(1, undefined)", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ items: string[] }, string[]>( stack, "fn", (input) => { return input.items.slice(1, undefined); } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("return items.slice(-1)", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ items: string[] }, string[]>( stack, "fn", (input) => { return input.items.slice(-1); } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("return items.slice(0, -1)", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ items: string[] }, string[]>( stack, "fn", (input) => { return input.items.slice(0, -1); } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("return items.slice(1, 3)", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ items: string[] }, string[]>( stack, "fn", (input) => { return input.items.slice(1, 3); } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("return task({key: items.slice(1, 3)})", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction< { items: string[] }, number | null >(stack, "fn", (input) => { return task({ key: input.items.slice(1, 3) }); }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("let and set", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", () => { let a; a = null; a = true; a = false; a = 0; a = -1; a = -100; a = 1 + 2; a = "hello"; a = "hello" + " world"; a = "hello" + 1; a = 1 + "hello"; a = "hello" + true; a = false + "hello"; a = null + "hello"; a = "hello" + null; a = [null]; a = [1]; a = [-1]; a = [true]; a = [ { key: "value", }, ]; a = { key: "value", }; a = a; a = "hello" + { place: "world" }; a = "hello" + ["world"]; return a; }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("task(any)", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", () => { task(null); task(true); task(false); task(0); task(-1); task(-100); task(1 + 2); task("hello"); task("hello" + " world"); task("hello" + 1); task(1 + "hello"); task("hello" + true); task(false + "hello"); task(null + "hello"); task("hello" + null); task([null]); task([1]); task([-1]); task([true]); task([ { key: "value", }, ]); task({ key: "value", }); task("hello" + { place: "world" }); task("hello" + ["world"]); }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("spread constant array and object", () => { const array = [1, 2]; const object = { hello: "world" }; const definition = new StepFunction(stack, "fn", () => { return { array: [0, ...array, 3], object: { key: "value", ...object, }, }; }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("return void", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", () => { return; }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("conditionally return void", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ id: string }, void>( stack, "fn", (input) => { if (input.id === "hello") { return; } } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("if-else", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ id: string }, string>( stack, "fn", (input) => { if (input.id === "hello") { return "hello"; } else { return "world"; } } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("if (typeof x === ??)", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ id: string }, string | null>( stack, "fn", (input) => { if (input.id === undefined) { return "null"; } else if (typeof input.id === "undefined") { return "undefined"; } else if (typeof input.id === "string") { return "string"; } else if (typeof input.id === "boolean") { return "boolean"; } else if (typeof input.id === "number") { return "number"; } else if (typeof input.id === "bigint") { return "bigint"; } return null; } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); let stack: Stack; beforeEach(() => { stack = new Stack(); }); test("put an event bus event", () => { interface BusDetails { value: string; } interface BusEvent extends Event<BusDetails> {} const bus = new EventBus<BusEvent>(stack, "testBus2"); const definition = new ExpressStepFunction<{ id: string }, void>( stack, "fn", (input) => { bus.putEvents({ "detail-type": "someEvent", source: "sfnTest", detail: { value: input.id, }, }); } ).definition; expectTaskToMatch( definition, { Parameters: { Entries: [{ EventBusName: bus.eventBusArn }] }, }, "bus.putEvents" ); expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("put multiple event bus events", () => { interface BusDetails { value: string; constant?: string; } interface BusEvent extends Event<BusDetails> {} const bus = new EventBus<BusEvent>(stack, "testBus"); const definition = new ExpressStepFunction<{ id: string }, void>( stack, "fn", (input) => { bus.putEvents( { "detail-type": "someEvent", source: "sfnTest", detail: { value: input.id, }, }, { "detail-type": "someOtherEvent", source: "sfnTest", detail: { constant: "hi", value: input.id, }, } ); } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("if (typeof x !== ??)", () => { const definition = new ExpressStepFunction<{ id: any }, string | null>( stack, "fn", (input) => { if (input.id !== undefined) { return "null"; } else if ("undefined" !== typeof input.id) { return "undefined"; } else if (typeof input.id !== "string") { return "string"; } else if (typeof input.id !== "boolean") { return "boolean"; } else if (typeof input.id !== "number") { return "number"; } else if (typeof input.id !== "bigint") { return "bigint"; } return null; } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("if-else-if", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ id: string }, string | void>( stack, "fn", (input) => { if (input.id === "hello") { return "hello"; } else if (input.id === "world") { return "world"; } return; } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("for-loop and do nothing", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ items: string[] }, void>( stack, "fn", (input) => { for (const item of input.items) { // @ts-ignore const a = item; } } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("for i in items, items[i]", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ items: string[] }, void>( stack, "fn", (input) => { for (const i in input.items) { // @ts-ignore const a = items[i]; } } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("return a single Lambda Function call", () => { const { stack, getPerson } = initStepFunctionApp(); const definition = new ExpressStepFunction< { id: string }, Person | undefined >(stack, "fn", (input) => { return getPerson({ id: input.id }); }).definition; expectTaskToMatch(definition, { Parameters: { FunctionName: getPerson.resource.functionName, }, }); expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("task(-1)", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ id: string }, any>( stack, "fn", () => { return task(-1); } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("task(input.list[-1])", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction( stack, "fn", (input: { list: { [-1]: string } }) => { return task(input.list[-1]); } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("call Lambda Function, store as variable, return variable", () => { const { stack, getPerson } = initStepFunctionApp(); const definition = new ExpressStepFunction< { id: string }, Person | undefined >(stack, "fn", (input) => { const person = getPerson({ id: input.id }); return person; }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("return AWS.DynamoDB.GetItem", () => { const { stack, personTable } = initStepFunctionApp(); const definition = new ExpressStepFunction< { id: string }, Person | undefined >(stack, "fn", (input) => { const person = $AWS.DynamoDB.GetItem({ TableName: personTable, Key: { id: { S: input.id, }, }, }); if (person.Item === undefined) { return undefined; } return { id: person.Item.id.S, name: person.Item.name.S, }; }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("call AWS.DynamoDB.GetItem, then Lambda and return LiteralExpr", () => { const { stack, personTable, computeScore } = initStepFunctionApp(); const definition = new ExpressStepFunction< { id: string }, (Person & { score: number }) | undefined >(stack, "fn", (input) => { const person = $AWS.DynamoDB.GetItem({ TableName: personTable, Key: { id: { S: input.id, }, }, }); if (person.Item === undefined) { return undefined; } const score = computeScore({ id: person.Item.id.S, name: person.Item.name.S, }); return { id: person.Item.id.S, name: person.Item.name.S, score, }; }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("for-loop over a list literal", () => { const { stack, computeScore } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ id: string }, void>( stack, "fn", (input) => { const people = ["sam", "brendan"]; for (const name of people) { computeScore({ id: input.id, name, }); } } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("conditionally call DynamoDB and then void", () => { const { stack, personTable } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ id: string }, void>( stack, "fn", (input): void => { if (input.id === "hello") { $AWS.DynamoDB.GetItem({ TableName: personTable, Key: { id: { S: input.id, }, }, }); } } ).definition; expectTaskToMatch( definition, { Parameters: { TableName: personTable.resource.tableName, }, }, "$AWS.DynamoDB.GetItem" ); expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("waitFor literal number of seconds", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", (): string | void => { $SFN.waitFor(1); }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("waitFor reference number of seconds", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction< { seconds: number }, string | void >(stack, "fn", (input) => { $SFN.waitFor(input.seconds); }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("waitFor literal timestamp", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", (): string | void => { $SFN.waitUntil("2022-08-01T00:00:00Z"); }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("waitUntil reference timestamp", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ until: string }, string | void>( stack, "fn", (input) => { $SFN.waitUntil(input.until); } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("throw new Error", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", () => { throw new Error("cause"); }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("throw Error", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", () => { throw Error("cause"); }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); class CustomError { constructor(readonly property: string) {} } test("throw new CustomError", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", () => { throw new CustomError("cause"); }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("try, throw Error('error'), empty catch", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", () => { try { throw Error("cause"); } catch {} }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("try, throw, empty catch", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", () => { try { throw new CustomError("cause"); } catch {} }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("try, task, empty catch", () => { const { stack, computeScore } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", () => { try { computeScore({ id: "id", name: "name", }); } catch {} }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("catch and throw new Error", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", () => { try { throw new Error("cause"); } catch (err: any) { throw new CustomError("custom cause"); } }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("catch and throw Error", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", () => { try { throw Error("cause"); } catch (err: any) { throw new CustomError("custom cause"); } }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("try-catch with inner return and no catch variable", () => { const { stack, computeScore } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", () => { try { computeScore({ id: "id", name: "name", }); return "hello"; } catch { return "world"; } }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("try-catch with inner return and a catch variable", () => { const { stack, computeScore } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", () => { try { computeScore({ id: "id", name: "name", }); return "hello"; } catch (err: any) { return err.message; } }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("try-catch with guaranteed throw new Error", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", () => { try { throw new Error("cause"); } catch (err: any) { if (err.message === "cause") { return "hello"; } else { return "world"; } } }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("try-catch with optional throw of an Error", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ id: string }, void>( stack, "fn", (input) => { try { if (input.id === "hello") { throw new Error("cause"); } return "hello world"; } catch (err: any) { if (err.message === "cause") { return "hello"; } else { return "world"; } } } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("try-catch with optional task", () => { const { stack, computeScore } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ id: string }, string>( stack, "fn", (input) => { try { if (input.id === "hello") { computeScore({ id: input.id, name: "sam", }); } return "hello world"; } catch (err: any) { if (err.message === "cause") { return "hello"; } else { return "world"; } } } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("try-catch with optional return of task", () => { const { stack, computeScore } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ id: string }, string | number>( stack, "fn", (input) => { try { if (input.id === "hello") { return computeScore({ id: input.id, name: "sam", }); } return "hello world"; } catch (err: any) { if (err.message === "cause") { return "hello"; } else { return "world"; } } } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("nested try-catch", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", () => { try { try { throw new Error("error1"); } catch { throw new Error("error2"); } } catch { throw new Error("error3"); } }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("throw in for-of", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ items: string[] }, void>( stack, "fn", (input) => { // @ts-ignore for (const item of input.items) { throw new Error("err"); } } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("try-catch, no variable, contains for-of, throw", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction< { items: string[] }, string | void >(stack, "fn", (input): string | void => { try { // @ts-ignore for (const item of input.items) { throw new Error("err"); } } catch { return "hello"; } }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("try-catch, err variable, contains for-of, throw new Error", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction< { items: string[] }, string | void >(stack, "fn", (input): string | void => { try { // @ts-ignore for (const item of input.items) { throw new Error("err"); } } catch (err: any) { return err.message; } }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("try-catch, err variable, contains for-of, throw Error", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction< { items: string[] }, string | void >(stack, "fn", (input): string | void => { try { // @ts-ignore for (const item of input.items) { throw Error("err"); } } catch (err: any) { return err.message; } }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("try-catch-finally", () => { const { stack, computeScore } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", (): string | void => { try { computeScore({ id: "id", name: "name", }); } catch { } finally { return "hello"; } }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("try { task } catch { throw } finally { task() }", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", (): string | void => { try { task(); } catch { throw new Error("cause"); } finally { task("recover"); } }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("try { task() } catch { task() } finally { task() }", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", (): void => { try { task("1"); } catch { task("2"); } finally { task("3"); } }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("try, throw, finally", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", (): string | void => { try { throw new Error("cause"); } catch { } finally { return "hello"; } }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("try, throw, catch, throw, finally, return", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", (): string | void => { try { throw new Error("go"); } catch { throw new Error("little"); } finally { return "rock-star"; } }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("try { throw } catch { (maybe) throw } finally { task }", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ id: string }, string | void>( stack, "fn", (input) => { try { throw new Error("go"); } catch { if (input.id === "sam") { throw new Error("little"); } } finally { // task should run after both throws // for second throw, an error should be re-thrown task(); } } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("try { task() } catch { (maybe) throw } finally { task }", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ id: string }, string | void>( stack, "fn", (input) => { try { task("1"); } catch { if (input.id === "sam") { throw new Error("little"); } } finally { // task should run after both throws // for second throw, an error should be re-thrown task("2"); } } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("try { task() } catch(err) { (maybe) throw } finally { task }", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", (): string | void => { try { task("1"); } catch (err: any) { if (err.message === "sam") { throw new Error("little"); } } finally { // task should run after both throws // for second throw, an error should be re-thrown task("2"); } }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("try { for-of } catch { (maybe) throw } finally { task }", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction< { items: string[] }, string | void >(stack, "fn", (input): string | void => { try { for (const item of input.items) { task(item); } } catch (err: any) { if (err.message === "you dun' goofed") { throw new Error("little"); } } finally { // task should run after both throws // for second throw, an error should be re-thrown task("2"); } }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("for-of { try { task() } catch (err) { if(err) throw } finally { task() } }", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction< { items: string[] }, string | void >(stack, "fn", (input): string | void => { for (const item of input.items) { try { task(item); } catch (err: any) { if (err.message === "you dun' goofed") { throw new Error("little"); } } finally { // task should run after both throws // for second throw, an error should be re-thrown task("2"); } } }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("while (cond) { cond = task() }", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", () => { let cond; while (cond === undefined) { cond = task(); } }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("while (cond); cond = task()", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", () => { let cond; while (cond === undefined) cond = task(); }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("let cond; do { cond = task() } while (cond)", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", () => { let cond; do { cond = task(); } while (cond === undefined); }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("list.map(item => task(item))", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction< { list: string[] }, (number | null)[] >(stack, "fn", (input) => { return input.list.map((item) => task(item)); }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("list.map((item, i) => if (i == 0) task(item))", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction< { list: string[] }, (number | null)[] >(stack, "fn", (input) => { return input.list.map((item, i) => { if (i === 0) { return task(item); } else { return null; } }); }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("list.map((item, i, list) => if (i == 0) task(item) else task(list[0]))", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction< { list: string[] }, (number | null)[] >(stack, "fn", (input) => { return input.list.map((item, i) => { if (i === 0) { return task(item); } else { return task(input.list[0]); } }); }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("try { list.map(item => task(item)) }", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction< { list: string[] }, (null | number)[] | null >(stack, "fn", (input) => { try { return input.list.map((item) => task(item)); } catch { return null; } }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("try { list.map(item => task(item)) }", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction< { list: string[] }, (number | null)[] >(stack, "fn", (input) => { return input.list.map((item) => { try { return task(item); } catch { return null; } }); }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("try { list.map(item => throw) }", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction< { list: string[] }, null | string[] >(stack, "fn", (input) => { try { return input.list.map(() => { throw new Error("cause"); }); } catch { return null; } }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("try { list.map(item => throw) } catch (err)", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction< { list: string[] }, string[] | number >(stack, "fn", (input) => { try { return input.list.map(() => { throw new Error("cause"); }); } catch (err: any) { if (err.message === "cause") { return 0; } else { return 1; } } }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("list.forEach(item => task(item))", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ list: string[] }, void>( stack, "fn", (input) => { return input.list.forEach((item) => task(item)); } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("list.forEach((item, i) => if (i == 0) task(item))", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ list: string[] }, void>( stack, "fn", (input) => { return input.list.forEach((item, i) => { if (i === 0) { return task(item); } else { return null; } }); } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("list.forEach((item, i, list) => if (i == 0) task(item) else task(list[0]))", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ list: string[] }, void>( stack, "fn", (input) => { return input.list.forEach((item, i) => { if (i === 0) { return task(item); } else { return task(input.list[0]); } }); } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("try { list.forEach(item => task(item)) }", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ list: string[] }, void | null>( stack, "fn", (input) => { try { return input.list.forEach((item) => task(item)); } catch { return null; } } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("try { list.forEach(item => task(item)) }", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ list: string[] }, void>( stack, "fn", (input) => { return input.list.forEach((item) => { try { return task(item); } catch { return null; } }); } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("try { list.forEach(item => throw) }", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ list: string[] }, void | null>( stack, "fn", (input) => { try { return input.list.forEach(() => { throw new Error("cause"); }); } catch { return null; } } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("try { list.forEach(item => throw) } catch (err)", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ list: string[] }, void | number>( stack, "fn", (input) => { try { return input.list.forEach(() => { throw new Error("cause"); }); } catch (err: any) { if (err.message === "cause") { return 0; } else { return 1; } } } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("return $SFN.map(list, (item) => task(item))", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction< { list: string[] }, (number | null)[] >(stack, "fn", (input) => { return $SFN.map(input.list, (item) => task(item)); }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("return $SFN.map(list, {maxConcurrency: 2} (item) => task(item))", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction< { list: string[] }, (number | null)[] >(stack, "fn", (input) => { return $SFN.map(input.list, { maxConcurrency: 2 }, (item) => task(item)); }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("$SFN.map(list, (item) => task(item))", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ list: string[] }, void>( stack, "fn", (input) => { $SFN.map(input.list, (item) => task(item)); } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("result = $SFN.map(list, (item) => task(item))", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction< { list: string[] }, (number | null)[] >(stack, "fn", (input) => { const result = $SFN.map(input.list, (item) => task(item)); return result; }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("return $SFN.map(list, (item) => try { task(item)) } catch { return null }", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction< { list: string[] }, (number | null)[] >(stack, "fn", (input) => { return $SFN.map(input.list, (item) => { try { return task(item); } catch { return null; } }); }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("try { $SFN.map(list, (item) => task(item)) } catch { return null }", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction< { list: string[] }, (number | null)[] | null >(stack, "fn", (input) => { try { return $SFN.map(input.list, (item) => task(item)); } catch { return null; } }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("return $SFN.forEach(list, (item) => task(item))", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ list: string[] }, void>( stack, "fn", (input) => { return $SFN.forEach(input.list, (item) => task(item)); } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("return $SFN.forEach(list, {maxConcurrency: 2} (item) => task(item))", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ list: string[] }, void>( stack, "fn", (input) => { return $SFN.forEach(input.list, { maxConcurrency: 2 }, (item) => task(item) ); } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("$SFN.forEach(list, (item) => task(item))", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ list: string[] }, void>( stack, "fn", (input) => { $SFN.forEach(input.list, (item) => task(item)); } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("result = $SFN.forEach(list, (item) => task(item))", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ list: string[] }, void>( stack, "fn", (input) => { const result = $SFN.forEach(input.list, (item) => task(item)); return result; } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("return $SFN.forEach(list, (item) => try { task(item)) } catch { return null }", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ list: string[] }, void>( stack, "fn", (input) => { return $SFN.forEach(input.list, (item) => { try { return task(item); } catch { return null; } }); } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("try { $SFN.forEach(list, (item) => task(item)) } catch { return null }", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ list: string[] }, void | null>( stack, "fn", (input) => { try { return $SFN.forEach(input.list, (item) => task(item)); } catch { return null; } } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test('return $SFN.parallel(() => "hello", () => "world"))', () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", () => { return $SFN.parallel( () => "hello", () => "world" ); }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test('try { return $SFN.parallel(() => "hello", () => "world")) } catch { return null }', () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", () => { try { return $SFN.parallel( () => "hello", () => "world" ); } catch { return null; } }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("return $SFN.parallel(() => try { task() } catch { return null })) }", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", () => { try { return $SFN.parallel(() => { try { return task(); } catch { return null; } }); } catch { return null; } }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("return task({ key: items.filter(*) })", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction< { items: { str: string; items: string[] }[] }, number | null >(stack, "fn", (input) => { return task({ equals: input.items.filter((item) => item.str === "hello"), and: input.items.filter( (item) => item.str === "hello" && item.items[0] === "hello" ), or: input.items.filter( (item) => item.str === "hello" || item.items[0] === "hello" ), }); }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("single quotes in StringLiteralExpr should be escaped in a JSON Path filter expression", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction< { items: { str: string; items: string[] }[] }, number | null >(stack, "fn", (input) => { return task({ escape: input.items.filter((item) => item.str === "hello'world"), }); }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("template literal strings", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction< { obj: { str: string; items: string } }, number | null >(stack, "fn", (input) => { return task({ key: `${input.obj.str} ${"hello"} ${input.obj.items[0]}`, }); }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("break from for-loop", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ items: string[] }, void>( stack, "fn", (input) => { for (const item of input.items) { if (item === "hello") { break; } } } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("break from while-loop", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", () => { while (true) { break; } }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("break from do-while-loop", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", () => { do { break; } while (true); }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("continue in for loop", () => { const { stack } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ items: string[] }, void>( stack, "fn", (input) => { for (const item of input.items) { if (item === "hello") { continue; } } } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("continue in while loop", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ key: string }, void>( stack, "fn", (input) => { while (true) { if (input.key === "sam") { continue; } task(input.key); } } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("continue in do..while loop", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction<{ key: string }, void>( stack, "fn", (input) => { do { if (input.key === "sam") { continue; } task(input.key); } while (true); } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("return task(task())", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", () => { return task(task()); }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); // test("return cond ? task(1) : task(2))", () => { // const { stack, task } = initStepFunctionApp(); // const definition = new ExpressStepFunction(stack, "fn", (cond: boolean) => { // return cond ? task(1) : task(2); // }).definition; // expect(definition).toMatchSnapshot() // }); // test("return task(1) ?? task(2))", () => { // const { stack, task } = initStepFunctionApp(); // const definition = new ExpressStepFunction(stack, "fn", () => { // return task(1) ?? task(2); // }).definition; // expect(definition).toMatchSnapshot() // }); test("while(true) { try { } catch { wait }", () => { const { stack, task } = initStepFunctionApp(); const definition = new ExpressStepFunction(stack, "fn", () => { while (true) { try { task(); } catch { $SFN.waitFor(1); } } }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("call Step Function from another Step Function", () => { const { stack } = initStepFunctionApp(); const machine1 = new ExpressStepFunction(stack, "machine1", () => { return "hello"; }); const definition = new ExpressStepFunction(stack, "machine2", () => { const result = machine1({}); return result; }).definition; expectTaskToMatch(definition, { Parameters: { StateMachineArn: machine1.resource.stateMachineArn }, }); expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("call Step Function from another Step Function with name and trace", () => { const { stack } = initStepFunctionApp(); const machine1 = new ExpressStepFunction(stack, "machine1", () => { return "hello"; }); const definition = new ExpressStepFunction(stack, "machine2", () => { const result = machine1({ name: "exec1", traceHeader: "1", }); return result; }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("call Step Function from another Step Function with name and trace from variables", () => { const { stack } = initStepFunctionApp(); const machine1 = new ExpressStepFunction(stack, "machine1", () => { return "hello"; }); const definition = new ExpressStepFunction( stack, "machine2", (input: { name: string; header: string }) => { const result = machine1({ name: input.name, traceHeader: input.header, }); return result; } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("call Step Function from another Step Function with input", () => { const { stack } = initStepFunctionApp(); const machine1 = new ExpressStepFunction<{ value: string }, string>( stack, "machine1", () => { return "hello"; } ); const definition = new ExpressStepFunction(stack, "machine2", () => { const result = machine1({ input: { value: "hello", }, }); return result; }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("call Step Function from another Step Function with dynamic input", () => { const { stack } = initStepFunctionApp(); const machine1 = new ExpressStepFunction<{ value: string }, string>( stack, "machine1", () => { return "hello"; } ); const definition = new ExpressStepFunction< { value1: string }, SyncExecutionResult<string> >(stack, "machine2", (input) => { const result = machine1({ input: { value: input.value1, }, }); return result; }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("call Step Function from another Step Function with dynamic input field input", () => { const { stack } = initStepFunctionApp(); const machine1 = new ExpressStepFunction<{ value: string }, string>( stack, "machine1", () => { return "hello"; } ); const definition = new ExpressStepFunction< { value: string }, SyncExecutionResult<string> >(stack, "machine2", (input) => { const result = machine1({ input: input, }); return result; }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("call Step Function from another Step Function not supported with reference argument", () => { const { stack } = initStepFunctionApp(); const machine1 = new ExpressStepFunction<{ value: string }, string>( stack, "machine1", () => { return "hello"; } ); expect( () => new ExpressStepFunction<{ value1: string }, SyncExecutionResult<string>>( stack, "machine2", (input) => { const _input = { input: { value: input.value1, }, }; const result = machine1(_input); return result; } ) ).toThrow( "Step function invocation must use a single, inline object parameter. Variable references are not supported currently." ); }); test("call Step Function from another Step Function not supported with computed keys", () => { const { stack } = initStepFunctionApp(); const machine1 = new ExpressStepFunction<{ value: string }, string>( stack, "machine1", () => { return "hello"; } ); expect( () => new ExpressStepFunction<{ value1: string }, SyncExecutionResult<string>>( stack, "machine2", (input) => { const _inputStr = "input"; const result = machine1({ [_inputStr]: { value: input.value1, }, }); return result; } ) ).toThrow( "Step function invocation must use a single, inline object instantiated without computed or spread keys." ); }); test("call Step Function from another Step Function not supported with spread assignment", () => { const { stack } = initStepFunctionApp(); const machine1 = new ExpressStepFunction<{ value: string }, string>( stack, "machine1", () => { return "hello"; } ); expect( () => new ExpressStepFunction<{ value1: string }, SyncExecutionResult<string>>( stack, "machine2", (input) => { const _input = { input: { value: input.value1, }, }; const result = machine1({ ..._input }); return result; } ) ).toThrow( "Step function invocation must use a single, inline object instantiated without computed or spread keys." ); }); test("call Step Function describe from another Step Function", () => { const { stack } = initStepFunctionApp(); const machine1 = new StepFunction<{ value: string }, string>( stack, "machine1", () => { return "hello"; } ); const definition = new ExpressStepFunction(stack, "machine2", () => { const result = machine1.describeExecution("hello"); return result; }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("call Step Function describe from another Step Function from context", () => { const { stack } = initStepFunctionApp(); const machine1 = new StepFunction<{ value: string }, string>( stack, "machine1", () => { return "hello"; } ); const definition = new ExpressStepFunction( stack, "machine2", (input: { id: string }) => { const result = machine1.describeExecution(input.id); return result; } ).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); }); test("on success event", () => { const machine = new StepFunction(stack, "machine", () => {}); const success = machine.onSucceeded(stack, "onSuccess"); expect(success.resource._renderEventPattern()).toEqual({ source: ["aws.states"], "detail-type": ["Step Functions Execution Status Change"], detail: { status: ["SUCCEEDED"], stateMachineArn: [machine.resource.stateMachineArn], }, }); }); test("on status change event", () => { const machine = new StepFunction(stack, "machine", () => {}); const statusChange = machine.onStatusChanged(stack, "onSuccess"); expect(statusChange.resource._renderEventPattern()).toEqual({ source: ["aws.states"], "detail-type": ["Step Functions Execution Status Change"], detail: { stateMachineArn: [machine.resource.stateMachineArn], }, }); }); test("on status change event refine", () => { const machine = new StepFunction(stack, "machine", () => {}); const success = machine .onStatusChanged(stack, "onStatus") .when(stack, "onRunning", (event) => event.detail.status === "RUNNING"); expect(success.resource._renderEventPattern()).toEqual({ source: ["aws.states"], "detail-type": ["Step Functions Execution Status Change"], detail: { status: ["RUNNING"], stateMachineArn: [machine.resource.stateMachineArn], }, }); }); test("import from state machine", () => { const awsMachine = new aws_stepfunctions.StateMachine(stack, "m", { definition: new Pass(stack, "p"), }); const machine = StepFunction.fromStateMachine<{ id: string }, string>( awsMachine ); new Function(stack, "func", async () => { machine({ input: { id: "hi", }, }); }); }); test("import from state machine into state machine", () => { const awsMachine = new aws_stepfunctions.StateMachine(stack, "m", { definition: new Pass(stack, "p"), }); const machine = StepFunction.fromStateMachine<{ id: string }, string>( awsMachine ); const definition = new StepFunction(stack, "func", () => { machine({ input: { id: "hi", }, }); }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); expectTaskToMatch( definition, { Parameters: { StateMachineArn: awsMachine.stateMachineArn, }, }, "machine" ); }); test("import express from standard should fail", () => { const awsMachine = new aws_stepfunctions.StateMachine(stack, "m", { definition: new Pass(stack, "p"), stateMachineType: aws_stepfunctions.StateMachineType.EXPRESS, }); expect(() => StepFunction.fromStateMachine<{ id: string }, string>(awsMachine) ).toThrow(new SynthError(ErrorCodes.Incorrect_StateMachine_Import_Type)); }); test("import from express state machine", () => { const awsMachine = new aws_stepfunctions.StateMachine(stack, "m", { definition: new Pass(stack, "p"), stateMachineType: aws_stepfunctions.StateMachineType.EXPRESS, }); const machine = ExpressStepFunction.fromStateMachine<{ id: string }, string>( awsMachine ); new Function(stack, "func", async () => { machine({ input: { id: "hi", }, }); }); }); test("import from express state machine into machine", () => { const awsMachine = new aws_stepfunctions.StateMachine(stack, "m", { definition: new Pass(stack, "p"), stateMachineType: aws_stepfunctions.StateMachineType.EXPRESS, }); const machine = ExpressStepFunction.fromStateMachine<{ id: string }, string>( awsMachine ); const definition = new StepFunction(stack, "func", () => { machine({ input: { id: "hi", }, }); }).definition; expect(normalizeDefinition(definition)).toMatchSnapshot(); expectTaskToMatch( definition, { Parameters: { StateMachineArn: awsMachine.stateMachineArn, }, }, "machine" ); }); test("import standard from express should fail", () => { const awsMachine = new aws_stepfunctions.StateMachine(stack, "m", { definition: new Pass(stack, "p"), stateMachineType: aws_stepfunctions.StateMachineType.STANDARD, }); expect(() => ExpressStepFunction.fromStateMachine<{ id: string }, string>(awsMachine) ).toThrow(new SynthError(ErrorCodes.Incorrect_StateMachine_Import_Type)); });
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 ChimeSDKIdentity extends Service { /** * Constructs a service object. This object has one method for each API operation. */ constructor(options?: ChimeSDKIdentity.Types.ClientConfiguration) config: Config & ChimeSDKIdentity.Types.ClientConfiguration; /** * Creates an Amazon Chime SDK messaging AppInstance under an AWS account. Only SDK messaging customers use this API. CreateAppInstance supports idempotency behavior as described in the AWS API Standard. identity */ createAppInstance(params: ChimeSDKIdentity.Types.CreateAppInstanceRequest, callback?: (err: AWSError, data: ChimeSDKIdentity.Types.CreateAppInstanceResponse) => void): Request<ChimeSDKIdentity.Types.CreateAppInstanceResponse, AWSError>; /** * Creates an Amazon Chime SDK messaging AppInstance under an AWS account. Only SDK messaging customers use this API. CreateAppInstance supports idempotency behavior as described in the AWS API Standard. identity */ createAppInstance(callback?: (err: AWSError, data: ChimeSDKIdentity.Types.CreateAppInstanceResponse) => void): Request<ChimeSDKIdentity.Types.CreateAppInstanceResponse, AWSError>; /** * Promotes an AppInstanceUser to an AppInstanceAdmin. The promoted user can perform the following actions. ChannelModerator actions across all channels in the AppInstance. DeleteChannelMessage actions. Only an AppInstanceUser can be promoted to an AppInstanceAdmin role. */ createAppInstanceAdmin(params: ChimeSDKIdentity.Types.CreateAppInstanceAdminRequest, callback?: (err: AWSError, data: ChimeSDKIdentity.Types.CreateAppInstanceAdminResponse) => void): Request<ChimeSDKIdentity.Types.CreateAppInstanceAdminResponse, AWSError>; /** * Promotes an AppInstanceUser to an AppInstanceAdmin. The promoted user can perform the following actions. ChannelModerator actions across all channels in the AppInstance. DeleteChannelMessage actions. Only an AppInstanceUser can be promoted to an AppInstanceAdmin role. */ createAppInstanceAdmin(callback?: (err: AWSError, data: ChimeSDKIdentity.Types.CreateAppInstanceAdminResponse) => void): Request<ChimeSDKIdentity.Types.CreateAppInstanceAdminResponse, AWSError>; /** * Creates a user under an Amazon Chime AppInstance. The request consists of a unique appInstanceUserId and Name for that user. */ createAppInstanceUser(params: ChimeSDKIdentity.Types.CreateAppInstanceUserRequest, callback?: (err: AWSError, data: ChimeSDKIdentity.Types.CreateAppInstanceUserResponse) => void): Request<ChimeSDKIdentity.Types.CreateAppInstanceUserResponse, AWSError>; /** * Creates a user under an Amazon Chime AppInstance. The request consists of a unique appInstanceUserId and Name for that user. */ createAppInstanceUser(callback?: (err: AWSError, data: ChimeSDKIdentity.Types.CreateAppInstanceUserResponse) => void): Request<ChimeSDKIdentity.Types.CreateAppInstanceUserResponse, AWSError>; /** * Deletes an AppInstance and all associated data asynchronously. */ deleteAppInstance(params: ChimeSDKIdentity.Types.DeleteAppInstanceRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes an AppInstance and all associated data asynchronously. */ deleteAppInstance(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Demotes an AppInstanceAdmin to an AppInstanceUser. This action does not delete the user. */ deleteAppInstanceAdmin(params: ChimeSDKIdentity.Types.DeleteAppInstanceAdminRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Demotes an AppInstanceAdmin to an AppInstanceUser. This action does not delete the user. */ deleteAppInstanceAdmin(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes an AppInstanceUser. */ deleteAppInstanceUser(params: ChimeSDKIdentity.Types.DeleteAppInstanceUserRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deletes an AppInstanceUser. */ deleteAppInstanceUser(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deregisters an AppInstanceUserEndpoint. */ deregisterAppInstanceUserEndpoint(params: ChimeSDKIdentity.Types.DeregisterAppInstanceUserEndpointRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Deregisters an AppInstanceUserEndpoint. */ deregisterAppInstanceUserEndpoint(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Returns the full details of an AppInstance. */ describeAppInstance(params: ChimeSDKIdentity.Types.DescribeAppInstanceRequest, callback?: (err: AWSError, data: ChimeSDKIdentity.Types.DescribeAppInstanceResponse) => void): Request<ChimeSDKIdentity.Types.DescribeAppInstanceResponse, AWSError>; /** * Returns the full details of an AppInstance. */ describeAppInstance(callback?: (err: AWSError, data: ChimeSDKIdentity.Types.DescribeAppInstanceResponse) => void): Request<ChimeSDKIdentity.Types.DescribeAppInstanceResponse, AWSError>; /** * Returns the full details of an AppInstanceAdmin. */ describeAppInstanceAdmin(params: ChimeSDKIdentity.Types.DescribeAppInstanceAdminRequest, callback?: (err: AWSError, data: ChimeSDKIdentity.Types.DescribeAppInstanceAdminResponse) => void): Request<ChimeSDKIdentity.Types.DescribeAppInstanceAdminResponse, AWSError>; /** * Returns the full details of an AppInstanceAdmin. */ describeAppInstanceAdmin(callback?: (err: AWSError, data: ChimeSDKIdentity.Types.DescribeAppInstanceAdminResponse) => void): Request<ChimeSDKIdentity.Types.DescribeAppInstanceAdminResponse, AWSError>; /** * Returns the full details of an AppInstanceUser. */ describeAppInstanceUser(params: ChimeSDKIdentity.Types.DescribeAppInstanceUserRequest, callback?: (err: AWSError, data: ChimeSDKIdentity.Types.DescribeAppInstanceUserResponse) => void): Request<ChimeSDKIdentity.Types.DescribeAppInstanceUserResponse, AWSError>; /** * Returns the full details of an AppInstanceUser. */ describeAppInstanceUser(callback?: (err: AWSError, data: ChimeSDKIdentity.Types.DescribeAppInstanceUserResponse) => void): Request<ChimeSDKIdentity.Types.DescribeAppInstanceUserResponse, AWSError>; /** * Returns the full details of an AppInstanceUserEndpoint. */ describeAppInstanceUserEndpoint(params: ChimeSDKIdentity.Types.DescribeAppInstanceUserEndpointRequest, callback?: (err: AWSError, data: ChimeSDKIdentity.Types.DescribeAppInstanceUserEndpointResponse) => void): Request<ChimeSDKIdentity.Types.DescribeAppInstanceUserEndpointResponse, AWSError>; /** * Returns the full details of an AppInstanceUserEndpoint. */ describeAppInstanceUserEndpoint(callback?: (err: AWSError, data: ChimeSDKIdentity.Types.DescribeAppInstanceUserEndpointResponse) => void): Request<ChimeSDKIdentity.Types.DescribeAppInstanceUserEndpointResponse, AWSError>; /** * Gets the retention settings for an AppInstance. */ getAppInstanceRetentionSettings(params: ChimeSDKIdentity.Types.GetAppInstanceRetentionSettingsRequest, callback?: (err: AWSError, data: ChimeSDKIdentity.Types.GetAppInstanceRetentionSettingsResponse) => void): Request<ChimeSDKIdentity.Types.GetAppInstanceRetentionSettingsResponse, AWSError>; /** * Gets the retention settings for an AppInstance. */ getAppInstanceRetentionSettings(callback?: (err: AWSError, data: ChimeSDKIdentity.Types.GetAppInstanceRetentionSettingsResponse) => void): Request<ChimeSDKIdentity.Types.GetAppInstanceRetentionSettingsResponse, AWSError>; /** * Returns a list of the administrators in the AppInstance. */ listAppInstanceAdmins(params: ChimeSDKIdentity.Types.ListAppInstanceAdminsRequest, callback?: (err: AWSError, data: ChimeSDKIdentity.Types.ListAppInstanceAdminsResponse) => void): Request<ChimeSDKIdentity.Types.ListAppInstanceAdminsResponse, AWSError>; /** * Returns a list of the administrators in the AppInstance. */ listAppInstanceAdmins(callback?: (err: AWSError, data: ChimeSDKIdentity.Types.ListAppInstanceAdminsResponse) => void): Request<ChimeSDKIdentity.Types.ListAppInstanceAdminsResponse, AWSError>; /** * Lists all the AppInstanceUserEndpoints created under a single AppInstanceUser. */ listAppInstanceUserEndpoints(params: ChimeSDKIdentity.Types.ListAppInstanceUserEndpointsRequest, callback?: (err: AWSError, data: ChimeSDKIdentity.Types.ListAppInstanceUserEndpointsResponse) => void): Request<ChimeSDKIdentity.Types.ListAppInstanceUserEndpointsResponse, AWSError>; /** * Lists all the AppInstanceUserEndpoints created under a single AppInstanceUser. */ listAppInstanceUserEndpoints(callback?: (err: AWSError, data: ChimeSDKIdentity.Types.ListAppInstanceUserEndpointsResponse) => void): Request<ChimeSDKIdentity.Types.ListAppInstanceUserEndpointsResponse, AWSError>; /** * List all AppInstanceUsers created under a single AppInstance. */ listAppInstanceUsers(params: ChimeSDKIdentity.Types.ListAppInstanceUsersRequest, callback?: (err: AWSError, data: ChimeSDKIdentity.Types.ListAppInstanceUsersResponse) => void): Request<ChimeSDKIdentity.Types.ListAppInstanceUsersResponse, AWSError>; /** * List all AppInstanceUsers created under a single AppInstance. */ listAppInstanceUsers(callback?: (err: AWSError, data: ChimeSDKIdentity.Types.ListAppInstanceUsersResponse) => void): Request<ChimeSDKIdentity.Types.ListAppInstanceUsersResponse, AWSError>; /** * Lists all Amazon Chime AppInstances created under a single AWS account. */ listAppInstances(params: ChimeSDKIdentity.Types.ListAppInstancesRequest, callback?: (err: AWSError, data: ChimeSDKIdentity.Types.ListAppInstancesResponse) => void): Request<ChimeSDKIdentity.Types.ListAppInstancesResponse, AWSError>; /** * Lists all Amazon Chime AppInstances created under a single AWS account. */ listAppInstances(callback?: (err: AWSError, data: ChimeSDKIdentity.Types.ListAppInstancesResponse) => void): Request<ChimeSDKIdentity.Types.ListAppInstancesResponse, AWSError>; /** * Lists the tags applied to an Amazon Chime SDK identity resource. */ listTagsForResource(params: ChimeSDKIdentity.Types.ListTagsForResourceRequest, callback?: (err: AWSError, data: ChimeSDKIdentity.Types.ListTagsForResourceResponse) => void): Request<ChimeSDKIdentity.Types.ListTagsForResourceResponse, AWSError>; /** * Lists the tags applied to an Amazon Chime SDK identity resource. */ listTagsForResource(callback?: (err: AWSError, data: ChimeSDKIdentity.Types.ListTagsForResourceResponse) => void): Request<ChimeSDKIdentity.Types.ListTagsForResourceResponse, AWSError>; /** * Sets the amount of time in days that a given AppInstance retains data. */ putAppInstanceRetentionSettings(params: ChimeSDKIdentity.Types.PutAppInstanceRetentionSettingsRequest, callback?: (err: AWSError, data: ChimeSDKIdentity.Types.PutAppInstanceRetentionSettingsResponse) => void): Request<ChimeSDKIdentity.Types.PutAppInstanceRetentionSettingsResponse, AWSError>; /** * Sets the amount of time in days that a given AppInstance retains data. */ putAppInstanceRetentionSettings(callback?: (err: AWSError, data: ChimeSDKIdentity.Types.PutAppInstanceRetentionSettingsResponse) => void): Request<ChimeSDKIdentity.Types.PutAppInstanceRetentionSettingsResponse, AWSError>; /** * Registers an endpoint under an Amazon Chime AppInstanceUser. The endpoint receives messages for a user. For push notifications, the endpoint is a mobile device used to receive mobile push notifications for a user. */ registerAppInstanceUserEndpoint(params: ChimeSDKIdentity.Types.RegisterAppInstanceUserEndpointRequest, callback?: (err: AWSError, data: ChimeSDKIdentity.Types.RegisterAppInstanceUserEndpointResponse) => void): Request<ChimeSDKIdentity.Types.RegisterAppInstanceUserEndpointResponse, AWSError>; /** * Registers an endpoint under an Amazon Chime AppInstanceUser. The endpoint receives messages for a user. For push notifications, the endpoint is a mobile device used to receive mobile push notifications for a user. */ registerAppInstanceUserEndpoint(callback?: (err: AWSError, data: ChimeSDKIdentity.Types.RegisterAppInstanceUserEndpointResponse) => void): Request<ChimeSDKIdentity.Types.RegisterAppInstanceUserEndpointResponse, AWSError>; /** * Applies the specified tags to the specified Amazon Chime SDK identity resource. */ tagResource(params: ChimeSDKIdentity.Types.TagResourceRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Applies the specified tags to the specified Amazon Chime SDK identity resource. */ tagResource(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Removes the specified tags from the specified Amazon Chime SDK identity resource. */ untagResource(params: ChimeSDKIdentity.Types.UntagResourceRequest, callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Removes the specified tags from the specified Amazon Chime SDK identity resource. */ untagResource(callback?: (err: AWSError, data: {}) => void): Request<{}, AWSError>; /** * Updates AppInstance metadata. */ updateAppInstance(params: ChimeSDKIdentity.Types.UpdateAppInstanceRequest, callback?: (err: AWSError, data: ChimeSDKIdentity.Types.UpdateAppInstanceResponse) => void): Request<ChimeSDKIdentity.Types.UpdateAppInstanceResponse, AWSError>; /** * Updates AppInstance metadata. */ updateAppInstance(callback?: (err: AWSError, data: ChimeSDKIdentity.Types.UpdateAppInstanceResponse) => void): Request<ChimeSDKIdentity.Types.UpdateAppInstanceResponse, AWSError>; /** * Updates the details of an AppInstanceUser. You can update names and metadata. */ updateAppInstanceUser(params: ChimeSDKIdentity.Types.UpdateAppInstanceUserRequest, callback?: (err: AWSError, data: ChimeSDKIdentity.Types.UpdateAppInstanceUserResponse) => void): Request<ChimeSDKIdentity.Types.UpdateAppInstanceUserResponse, AWSError>; /** * Updates the details of an AppInstanceUser. You can update names and metadata. */ updateAppInstanceUser(callback?: (err: AWSError, data: ChimeSDKIdentity.Types.UpdateAppInstanceUserResponse) => void): Request<ChimeSDKIdentity.Types.UpdateAppInstanceUserResponse, AWSError>; /** * Updates the details of an AppInstanceUserEndpoint. You can update the name and AllowMessage values. */ updateAppInstanceUserEndpoint(params: ChimeSDKIdentity.Types.UpdateAppInstanceUserEndpointRequest, callback?: (err: AWSError, data: ChimeSDKIdentity.Types.UpdateAppInstanceUserEndpointResponse) => void): Request<ChimeSDKIdentity.Types.UpdateAppInstanceUserEndpointResponse, AWSError>; /** * Updates the details of an AppInstanceUserEndpoint. You can update the name and AllowMessage values. */ updateAppInstanceUserEndpoint(callback?: (err: AWSError, data: ChimeSDKIdentity.Types.UpdateAppInstanceUserEndpointResponse) => void): Request<ChimeSDKIdentity.Types.UpdateAppInstanceUserEndpointResponse, AWSError>; } declare namespace ChimeSDKIdentity { export type AllowMessages = "ALL"|"NONE"|string; export interface AppInstance { /** * The ARN of the messaging instance. */ AppInstanceArn?: ChimeArn; /** * The name of an AppInstance. */ Name?: NonEmptyResourceName; /** * The time at which an AppInstance was created. In epoch milliseconds. */ CreatedTimestamp?: Timestamp; /** * The time an AppInstance was last updated. In epoch milliseconds. */ LastUpdatedTimestamp?: Timestamp; /** * The metadata of an AppInstance. */ Metadata?: Metadata; } export interface AppInstanceAdmin { /** * The AppInstanceAdmin data. */ Admin?: Identity; /** * The ARN of the AppInstance for which the user is an administrator. */ AppInstanceArn?: ChimeArn; /** * The time at which an administrator was created. */ CreatedTimestamp?: Timestamp; } export type AppInstanceAdminList = AppInstanceAdminSummary[]; export interface AppInstanceAdminSummary { /** * The details of the AppInstanceAdmin. */ Admin?: Identity; } export type AppInstanceList = AppInstanceSummary[]; export interface AppInstanceRetentionSettings { /** * The length of time in days to retain the messages in a channel. */ ChannelRetentionSettings?: ChannelRetentionSettings; } export interface AppInstanceSummary { /** * The AppInstance ARN. */ AppInstanceArn?: ChimeArn; /** * The name of the AppInstance. */ Name?: NonEmptyResourceName; /** * The metadata of the AppInstance. */ Metadata?: Metadata; } export interface AppInstanceUser { /** * The ARN of the AppInstanceUser. */ AppInstanceUserArn?: ChimeArn; /** * The name of the AppInstanceUser. */ Name?: UserName; /** * The metadata of the AppInstanceUser. */ Metadata?: Metadata; /** * The time at which the AppInstanceUser was created. */ CreatedTimestamp?: Timestamp; /** * The time at which the AppInstanceUser was last updated. */ LastUpdatedTimestamp?: Timestamp; } export interface AppInstanceUserEndpoint { /** * The ARN of the AppInstanceUser. */ AppInstanceUserArn?: SensitiveChimeArn; /** * The unique identifier of the AppInstanceUserEndpoint. */ EndpointId?: SensitiveString64; /** * The name of the AppInstanceUserEndpoint. */ Name?: SensitiveString1600; /** * The type of the AppInstanceUserEndpoint. */ Type?: AppInstanceUserEndpointType; /** * The ARN of the resource to which the endpoint belongs. */ ResourceArn?: SensitiveChimeArn; /** * The attributes of an Endpoint. */ EndpointAttributes?: EndpointAttributes; /** * The time at which an AppInstanceUserEndpoint was created. */ CreatedTimestamp?: Timestamp; /** * The time at which an AppInstanceUserEndpoint was last updated. */ LastUpdatedTimestamp?: Timestamp; /** * Boolean that controls whether the AppInstanceUserEndpoint is opted in to receive messages. ALL indicates the endpoint will receive all messages. NONE indicates the endpoint will receive no messages. */ AllowMessages?: AllowMessages; /** * A read-only field that represents the state of an AppInstanceUserEndpoint. Supported values: ACTIVE: The AppInstanceUserEndpoint is active and able to receive messages. When ACTIVE, the EndpointStatusReason remains empty. INACTIVE: The AppInstanceUserEndpoint is inactive and can't receive message. When INACTIVE, the corresponding reason will be conveyed through EndpointStatusReason. INVALID_DEVICE_TOKEN indicates that an AppInstanceUserEndpoint is INACTIVE due to invalid device token INVALID_PINPOINT_ARN indicates that an AppInstanceUserEndpoint is INACTIVE due to an invalid pinpoint ARN that was input through the ResourceArn field. */ EndpointState?: EndpointState; } export interface AppInstanceUserEndpointSummary { /** * The ARN of the AppInstanceUser. */ AppInstanceUserArn?: SensitiveChimeArn; /** * The unique identifier of the AppInstanceUserEndpoint. */ EndpointId?: SensitiveString64; /** * The name of the AppInstanceUserEndpoint. */ Name?: SensitiveString1600; /** * The type of the AppInstanceUserEndpoint. */ Type?: AppInstanceUserEndpointType; /** * BBoolean that controls whether the AppInstanceUserEndpoint is opted in to receive messages. ALL indicates the endpoint will receive all messages. NONE indicates the endpoint will receive no messages. */ AllowMessages?: AllowMessages; /** * A read-only field that represent the state of an AppInstanceUserEndpoint. */ EndpointState?: EndpointState; } export type AppInstanceUserEndpointSummaryList = AppInstanceUserEndpointSummary[]; export type AppInstanceUserEndpointType = "APNS"|"APNS_SANDBOX"|"GCM"|string; export type AppInstanceUserList = AppInstanceUserSummary[]; export interface AppInstanceUserSummary { /** * The ARN of the AppInstanceUser. */ AppInstanceUserArn?: ChimeArn; /** * The name of an AppInstanceUser. */ Name?: UserName; /** * The metadata of the AppInstanceUser. */ Metadata?: Metadata; } export interface ChannelRetentionSettings { /** * The time in days to retain the messages in a channel. */ RetentionDays?: RetentionDays; } export type ChimeArn = string; export type ClientRequestToken = string; export interface CreateAppInstanceAdminRequest { /** * The ARN of the administrator of the current AppInstance. */ AppInstanceAdminArn: ChimeArn; /** * The ARN of the AppInstance. */ AppInstanceArn: ChimeArn; } export interface CreateAppInstanceAdminResponse { /** * The name and ARN of the admin for the AppInstance. */ AppInstanceAdmin?: Identity; /** * The ARN of the of the admin for the AppInstance. */ AppInstanceArn?: ChimeArn; } export interface CreateAppInstanceRequest { /** * The name of the AppInstance. */ Name: NonEmptyResourceName; /** * The metadata of the AppInstance. Limited to a 1KB string in UTF-8. */ Metadata?: Metadata; /** * The ClientRequestToken of the AppInstance. */ ClientRequestToken: ClientRequestToken; /** * Tags assigned to the AppInstanceUser. */ Tags?: TagList; } export interface CreateAppInstanceResponse { /** * The Amazon Resource Number (ARN) of the AppInstance. */ AppInstanceArn?: ChimeArn; } export interface CreateAppInstanceUserRequest { /** * The ARN of the AppInstance request. */ AppInstanceArn: ChimeArn; /** * The user ID of the AppInstance. */ AppInstanceUserId: UserId; /** * The user's name. */ Name: UserName; /** * The request's metadata. Limited to a 1KB string in UTF-8. */ Metadata?: Metadata; /** * The token assigned to the user requesting an AppInstance. */ ClientRequestToken: ClientRequestToken; /** * Tags assigned to the AppInstanceUser. */ Tags?: TagList; } export interface CreateAppInstanceUserResponse { /** * The user's ARN. */ AppInstanceUserArn?: ChimeArn; } export interface DeleteAppInstanceAdminRequest { /** * The ARN of the AppInstance's administrator. */ AppInstanceAdminArn: ChimeArn; /** * The ARN of the AppInstance. */ AppInstanceArn: ChimeArn; } export interface DeleteAppInstanceRequest { /** * The ARN of the AppInstance. */ AppInstanceArn: ChimeArn; } export interface DeleteAppInstanceUserRequest { /** * The ARN of the user request being deleted. */ AppInstanceUserArn: ChimeArn; } export interface DeregisterAppInstanceUserEndpointRequest { /** * The ARN of the AppInstanceUser. */ AppInstanceUserArn: SensitiveChimeArn; /** * The unique identifier of the AppInstanceUserEndpoint. */ EndpointId: SensitiveString64; } export interface DescribeAppInstanceAdminRequest { /** * The ARN of the AppInstanceAdmin. */ AppInstanceAdminArn: ChimeArn; /** * The ARN of the AppInstance. */ AppInstanceArn: ChimeArn; } export interface DescribeAppInstanceAdminResponse { /** * The ARN and name of the AppInstanceUser, the ARN of the AppInstance, and the created and last-updated timestamps. All timestamps use epoch milliseconds. */ AppInstanceAdmin?: AppInstanceAdmin; } export interface DescribeAppInstanceRequest { /** * The ARN of the AppInstance. */ AppInstanceArn: ChimeArn; } export interface DescribeAppInstanceResponse { /** * The ARN, metadata, created and last-updated timestamps, and the name of the AppInstance. All timestamps use epoch milliseconds. */ AppInstance?: AppInstance; } export interface DescribeAppInstanceUserEndpointRequest { /** * The ARN of the AppInstanceUser. */ AppInstanceUserArn: SensitiveString1600; /** * The unique identifier of the AppInstanceUserEndpoint. */ EndpointId: SensitiveString64; } export interface DescribeAppInstanceUserEndpointResponse { /** * The full details of an AppInstanceUserEndpoint: the AppInstanceUserArn, ID, name, type, resource ARN, attributes, allow messages, state, and created and last updated timestamps. All timestamps use epoch milliseconds. */ AppInstanceUserEndpoint?: AppInstanceUserEndpoint; } export interface DescribeAppInstanceUserRequest { /** * The ARN of the AppInstanceUser. */ AppInstanceUserArn: ChimeArn; } export interface DescribeAppInstanceUserResponse { /** * The name of the AppInstanceUser. */ AppInstanceUser?: AppInstanceUser; } export interface EndpointAttributes { /** * The device token for the GCM, APNS, and APNS_SANDBOX endpoint types. */ DeviceToken: NonEmptySensitiveString1600; /** * The VOIP device token for the APNS and APNS_SANDBOX endpoint types. */ VoipDeviceToken?: NonEmptySensitiveString1600; } export interface EndpointState { /** * Enum that indicates the Status of an AppInstanceUserEndpoint. */ Status: EndpointStatus; /** * The reason for the EndpointStatus. */ StatusReason?: EndpointStatusReason; } export type EndpointStatus = "ACTIVE"|"INACTIVE"|string; export type EndpointStatusReason = "INVALID_DEVICE_TOKEN"|"INVALID_PINPOINT_ARN"|string; export interface GetAppInstanceRetentionSettingsRequest { /** * The ARN of the AppInstance. */ AppInstanceArn: ChimeArn; } export interface GetAppInstanceRetentionSettingsResponse { /** * The retention settings for the AppInstance. */ AppInstanceRetentionSettings?: AppInstanceRetentionSettings; /** * The timestamp representing the time at which the specified items are retained, in Epoch Seconds. */ InitiateDeletionTimestamp?: Timestamp; } export interface Identity { /** * The ARN in an Identity. */ Arn?: ChimeArn; /** * The name in an Identity. */ Name?: ResourceName; } export interface ListAppInstanceAdminsRequest { /** * The ARN of the AppInstance. */ AppInstanceArn: ChimeArn; /** * The maximum number of administrators that you want to return. */ MaxResults?: MaxResults; /** * The token returned from previous API requests until the number of administrators is reached. */ NextToken?: NextToken; } export interface ListAppInstanceAdminsResponse { /** * The ARN of the AppInstance. */ AppInstanceArn?: ChimeArn; /** * The information for each administrator. */ AppInstanceAdmins?: AppInstanceAdminList; /** * The token returned from previous API requests until the number of administrators is reached. */ NextToken?: NextToken; } export interface ListAppInstanceUserEndpointsRequest { /** * The ARN of the AppInstanceUser. */ AppInstanceUserArn: SensitiveChimeArn; /** * The maximum number of endpoints that you want to return. */ MaxResults?: MaxResults; /** * The token passed by previous API calls until all requested endpoints are returned. */ NextToken?: NextToken; } export interface ListAppInstanceUserEndpointsResponse { /** * The information for each requested AppInstanceUserEndpoint. */ AppInstanceUserEndpoints?: AppInstanceUserEndpointSummaryList; /** * The token passed by previous API calls until all requested endpoints are returned. */ NextToken?: NextToken; } export interface ListAppInstanceUsersRequest { /** * The ARN of the AppInstance. */ AppInstanceArn: ChimeArn; /** * The maximum number of requests that you want returned. */ MaxResults?: MaxResults; /** * The token passed by previous API calls until all requested users are returned. */ NextToken?: NextToken; } export interface ListAppInstanceUsersResponse { /** * The ARN of the AppInstance. */ AppInstanceArn?: ChimeArn; /** * The information for each requested AppInstanceUser. */ AppInstanceUsers?: AppInstanceUserList; /** * The token passed by previous API calls until all requested users are returned. */ NextToken?: NextToken; } export interface ListAppInstancesRequest { /** * The maximum number of AppInstances that you want to return. */ MaxResults?: MaxResults; /** * The token passed by previous API requests until you reach the maximum number of AppInstances. */ NextToken?: NextToken; } export interface ListAppInstancesResponse { /** * The information for each AppInstance. */ AppInstances?: AppInstanceList; /** * The token passed by previous API requests until the maximum number of AppInstances is reached. */ NextToken?: NextToken; } export interface ListTagsForResourceRequest { /** * The ARN of the resource. */ ResourceARN: ChimeArn; } export interface ListTagsForResourceResponse { /** * The tag key-value pairs. */ Tags?: TagList; } export type MaxResults = number; export type Metadata = string; export type NextToken = string; export type NonEmptyResourceName = string; export type NonEmptySensitiveString1600 = string; export interface PutAppInstanceRetentionSettingsRequest { /** * The ARN of the AppInstance. */ AppInstanceArn: ChimeArn; /** * The time in days to retain data. Data type: number. */ AppInstanceRetentionSettings: AppInstanceRetentionSettings; } export interface PutAppInstanceRetentionSettingsResponse { /** * The time in days to retain data. Data type: number. */ AppInstanceRetentionSettings?: AppInstanceRetentionSettings; /** * The time at which the API deletes data. */ InitiateDeletionTimestamp?: Timestamp; } export interface RegisterAppInstanceUserEndpointRequest { /** * The ARN of the AppInstanceUser. */ AppInstanceUserArn: SensitiveChimeArn; /** * The name of the AppInstanceUserEndpoint. */ Name?: SensitiveString1600; /** * The type of the AppInstanceUserEndpoint. Supported types: APNS: The mobile notification service for an Apple device. APNS_SANDBOX: The sandbox environment of the mobile notification service for an Apple device. GCM: The mobile notification service for an Android device. Populate the ResourceArn value of each type as PinpointAppArn. */ Type: AppInstanceUserEndpointType; /** * The ARN of the resource to which the endpoint belongs. */ ResourceArn: SensitiveChimeArn; /** * The attributes of an Endpoint. */ EndpointAttributes: EndpointAttributes; /** * The idempotency token for each client request. */ ClientRequestToken: ClientRequestToken; /** * Boolean that controls whether the AppInstanceUserEndpoint is opted in to receive messages. ALL indicates the endpoint receives all messages. NONE indicates the endpoint receives no messages. */ AllowMessages?: AllowMessages; } export interface RegisterAppInstanceUserEndpointResponse { /** * The ARN of the AppInstanceUser. */ AppInstanceUserArn?: SensitiveChimeArn; /** * The unique identifier of the AppInstanceUserEndpoint. */ EndpointId?: SensitiveString64; } export type ResourceName = string; export type RetentionDays = number; export type SensitiveChimeArn = string; export type SensitiveString1600 = string; export type SensitiveString64 = string; export interface Tag { /** * The key in a tag. */ Key: TagKey; /** * The value in a tag. */ Value: TagValue; } export type TagKey = string; export type TagKeyList = TagKey[]; export type TagList = Tag[]; export interface TagResourceRequest { /** * The resource ARN. */ ResourceARN: ChimeArn; /** * The tag key-value pairs. */ Tags: TagList; } export type TagValue = string; export type Timestamp = Date; export interface UntagResourceRequest { /** * The resource ARN. */ ResourceARN: ChimeArn; /** * The tag keys. */ TagKeys: TagKeyList; } export interface UpdateAppInstanceRequest { /** * The ARN of the AppInstance. */ AppInstanceArn: ChimeArn; /** * The name that you want to change. */ Name: NonEmptyResourceName; /** * The metadata that you want to change. */ Metadata: Metadata; } export interface UpdateAppInstanceResponse { /** * The ARN of the AppInstance. */ AppInstanceArn?: ChimeArn; } export interface UpdateAppInstanceUserEndpointRequest { /** * The ARN of the AppInstanceUser. */ AppInstanceUserArn: SensitiveChimeArn; /** * The unique identifier of the AppInstanceUserEndpoint. */ EndpointId: SensitiveString64; /** * The name of the AppInstanceUserEndpoint. */ Name?: SensitiveString1600; /** * Boolean that controls whether the AppInstanceUserEndpoint is opted in to receive messages. ALL indicates the endpoint will receive all messages. NONE indicates the endpoint will receive no messages. */ AllowMessages?: AllowMessages; } export interface UpdateAppInstanceUserEndpointResponse { /** * The ARN of the AppInstanceUser. */ AppInstanceUserArn?: SensitiveChimeArn; /** * The unique identifier of the AppInstanceUserEndpoint. */ EndpointId?: SensitiveString64; } export interface UpdateAppInstanceUserRequest { /** * The ARN of the AppInstanceUser. */ AppInstanceUserArn: ChimeArn; /** * The name of the AppInstanceUser. */ Name: UserName; /** * The metadata of the AppInstanceUser. */ Metadata: Metadata; } export interface UpdateAppInstanceUserResponse { /** * The ARN of the AppInstanceUser. */ AppInstanceUserArn?: ChimeArn; } export type UserId = string; export type UserName = string; /** * 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 = "2021-04-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 ChimeSDKIdentity client. */ export import Types = ChimeSDKIdentity; } export = ChimeSDKIdentity;
the_stack
import TestCase from '../testcase'; let swapDownKey = 'ctrl+j'; // let swapUpKey = 'ctrl+k'; describe('cloning', function() { it('works in basic case', async function() { let t = new TestCase([ { text: 'one', children: [ 'uno', ] }, { text: 'two', children: [ 'dos', ] }, { text: 'tacos', children: [ 'tacos', ] }, ]); t.sendKeys('yc'); t.sendKeys('jjj'); t.sendKeys('p'); t.expect([ { text: 'one', id: 1, children: [ 'uno', ] }, { text: 'two', children: [ 'dos', { clone: 1 }, ] }, { text: 'tacos', children: [ 'tacos', ] }, ]); await t.done(); }); it('works editing both clone and original; works with basic movement', async function() { let t = new TestCase([ { text: 'one', children: [ 'uno', ] }, { text: 'two', children: [ 'dos', ] }, { text: 'tacos', children: [ 'tacos', ] }, ]); t.sendKeys('yc'); t.sendKeys('jjj'); t.sendKeys('p'); t.sendKeys('gg'); t.sendKeys('x'); t.sendKeys('jjjj'); t.sendKeys('x'); t.expect([ { text: 'e', id: 1, children: [ 'uno', ] }, { text: 'two', children: [ 'dos', { clone: 1 }, ] }, { text: 'tacos', children: [ 'tacos', ] }, ]); // test movement from the clone t.sendKeys('jj'); t.sendKeys('x'); t.expect([ { text: 'e', id: 1, children: [ 'uno', ] }, { text: 'two', children: [ 'dos', { clone: 1 }, ] }, { text: 'acos', children: [ 'tacos', ] }, ]); await t.done(); }); it('works with movement in complex case', async function() { let t = new TestCase([ { text: 'Clone', children: [ 'Clone child', ] }, { text: 'Not a clone', children: [ 'Also not a clone and going to be deleted', ] }, ]); t.sendKeys('yc'); t.sendKeys('jjjj'); t.sendKeys('p'); t.expect([ { text: 'Clone', id: 1, children: [ 'Clone child', ] }, { text: 'Not a clone', children: [ 'Also not a clone and going to be deleted', { clone: 1 }, ] }, ]); t.sendKeys('kddk'); t.expect([ { text: 'Clone', id: 1, children: [ 'Clone child', ] }, { text: 'Not a clone', children: [ { clone: 1 }, ] }, ]); t.expectCursor(3, 0); // test movement t.sendKeys('k'); t.expectCursor(2, 0); t.sendKeys('k'); t.expectCursor(1, 0); t.sendKeys('k'); t.expectCursor(1, 0); await t.done(); }); it('prevents cloning to a sibling', async function() { let t = new TestCase([ 'one', 'two', 'three', ]); t.sendKeys('yc'); t.sendKeys('j'); t.sendKeys('p'); t.expect([ 'one', 'two', 'three', ]); await t.done(); }); it('prevents cycles', async function() { let t = new TestCase([ { text: 'one', children: [ 'uno', ] }, ]); t.sendKeys('yc'); t.sendKeys('j'); t.sendKeys('p'); t.expect([ { text: 'one', children: [ 'uno', ] }, ]); await t.done(); }); it('prevents cycles part 2', async function() { let t = new TestCase([ { text: 'blah', children: [ 'blah', ] }, { text: 'eventually cloned', children: [ { text: 'Will be cloned', children: [ 'Will be cloned', ] }, ] }, ]); t.sendKeys('jdd'); t.expect([ 'blah', { text: 'eventually cloned', children: [ { text: 'Will be cloned', children: [ 'Will be cloned', ] }, ] }, ]); t.sendKeys('jjyckP'); t.expect([ 'blah', { text: 'Will be cloned', id: 4, children: [ 'Will be cloned', ] }, { text: 'eventually cloned', children: [ { clone: 4 }, ] }, ]); t.sendKeys('jjyckp'); t.expect([ 'blah', { text: 'Will be cloned', id: 4, children: [ 'Will be cloned', ] }, { text: 'eventually cloned', children: [ { clone: 4 }, ] }, ]); t.sendKeys('kp'); t.expect([ 'blah', { text: 'Will be cloned', id: 4, children: [ 'Will be cloned', ] }, { text: 'eventually cloned', children: [ { clone: 4 }, ] }, ]); t.sendKeys('u'); t.expect([ 'blah', { text: 'eventually cloned', children: [ { text: 'Will be cloned', children: [ 'Will be cloned', ] }, ] }, ]); t.sendKeys('u'); t.expect([ { text: 'blah', children: [ 'blah', ] }, { text: 'eventually cloned', children: [ { text: 'Will be cloned', children: [ 'Will be cloned', ] }, ] }, ]); t.sendKeys('p'); t.expect([ { text: 'blah', children: [ 'blah', { text: 'eventually cloned', id: 3, children: [ { text: 'Will be cloned', children: [ 'Will be cloned', ] }, ] }, ] }, { clone: 3 }, ]); await t.done(); }); it('works with repeat', async function() { let t = new TestCase([ 'one', 'two', { text: 'three', children: [ 'child', ] }, ]); t.sendKeys('2yc'); t.sendKeys('p'); t.expect([ 'one', 'two', { text: 'three', children: [ 'child', ] }, ]); t.sendKeys('jjp'); t.expect([ { text: 'one', id: 1 }, { text: 'two', id: 2 }, { text: 'three', children: [ { clone: 1 }, { clone: 2 }, 'child', ] }, ]); await t.done(); }); it('does not add to history when constraints are violated', async function() { let t = new TestCase([ 'blah', { text: 'Will be cloned', children: [ 'not a clone', ] }, ]); t.sendKeys('x'); t.expect([ 'lah', { text: 'Will be cloned', children: [ 'not a clone', ] }, ]); t.sendKeys('jycp'); t.expect([ 'lah', { text: 'Will be cloned', children: [ 'not a clone', ] }, ]); t.sendKeys('u'); t.expect([ 'blah', { text: 'Will be cloned', children: [ 'not a clone', ] }, ]); await t.done(); }); it('enforces constraints upon movement', async function() { let t = new TestCase([ { text: 'Clone', children: [ 'Clone child', ] }, { text: 'Not a clone', children: [ 'Not a clone', ] }, ]); t.sendKeys('ycjjp'); t.expect([ { text: 'Clone', id: 1, children: [ 'Clone child', ] }, { text: 'Not a clone', children: [ { clone: 1 }, 'Not a clone', ] }, ]); t.sendKeys('gg'); t.sendKey(swapDownKey); t.expect([ { text: 'Clone', id: 1, children: [ 'Clone child', ] }, { text: 'Not a clone', children: [ { clone: 1 }, 'Not a clone', ] }, ]); t.sendKeys('u'); t.expect([ { text: 'Clone', children: [ 'Clone child', ] }, { text: 'Not a clone', children: [ 'Not a clone', ] }, ]); t.sendKeys('gg'); t.sendKey(swapDownKey); t.expect([ { text: 'Not a clone', children: [ { text: 'Clone', children: [ 'Clone child', ] }, 'Not a clone', ] }, ]); await t.done(); }); it('creates clone on regular paste', async function() { let t = new TestCase([ 'Will be cloned via delete', { text: 'parent', children: [ 'hm...', ] }, ]); t.sendKeys('x'); t.expect([ 'ill be cloned via delete', { text: 'parent', children: [ 'hm...', ] }, ]); t.sendKeys('dd'); t.expect([ { text: 'parent', children: [ 'hm...', ] }, ]); t.sendKeys('uu'); t.expect([ 'Will be cloned via delete', { text: 'parent', children: [ 'hm...', ] }, ]); t.sendKeys('jp'); // pastes with the W even though it was deleted while cloned t.expect([ { text: 'Will be cloned via delete', id: 1 }, { text: 'parent', children: [ { clone: 1 }, 'hm...', ] }, ]); await t.done(); }); it('prevents constraint violation on regular paste', async function() { let t = new TestCase([ 'Will be deleted', 'hm...', ]); t.sendKeys('dd'); t.sendKeys('u'); t.expect([ 'Will be deleted', 'hm...', ]); t.sendKeys('p'); t.expect([ 'Will be deleted', 'hm...', ]); await t.done(); }); it('prevents constraint violation on paste', async function() { let t = new TestCase([ 'Will be cloned', { text: 'parent', children: [ { text: 'blah', children: [ 'blah', ] }, ] }, ]); t.sendKeys('ycjp'); t.expect([ { text: 'Will be cloned', id: 1 }, { text: 'parent', children: [ { clone: 1 }, { text: 'blah', children: [ 'blah', ] }, ] }, ]); t.sendKeys('ddkkp'); t.expect([ 'Will be cloned', { text: 'parent', children: [ { text: 'blah', children: [ 'blah', ] }, ] }, ]); await t.done(); }); it('prevents constraint violation on indent', async function() { let t = new TestCase([ { text: 'parent', children: [ 'blah', ] }, 'Will be cloned', ]); t.sendKeys('Gyckp'); t.expect([ { text: 'parent', children: [ 'blah', { text: 'Will be cloned', id: 3 }, ] }, { clone: 3 }, ]); t.sendKeys('G'); t.sendKeys('>'); t.expect([ { text: 'parent', children: [ 'blah', { text: 'Will be cloned', id: 3 }, ] }, { clone: 3 }, ]); await t.done(); }); it('can paste clones of removed items', async function() { let t = new TestCase([ 'test', 'hi', ]); t.sendKeys('jddu'); t.sendKeys('yc'); t.sendKey('ctrl+r'); t.expect([ 'test', ]); t.sendKeys('p'); t.expect([ 'test', 'hi', ]); await t.done(); }); it('can paste clones of removed items, part 2', async function() { let t = new TestCase([ 'test', ]); t.sendKeys('ohi'); t.sendKey('esc'); t.expect([ 'test', 'hi', ]); t.sendKeys('ycu'); t.expect([ 'test', ]); t.sendKeys('p'); // the pasted row is empty, since the typing got undone! t.expect([ 'test', '', ]); await t.done(); }); it('works nested, basic test', async function() { let t = new TestCase([ { text: 'jango', children: [ { text: 'clone', id: 2, children: [ { text: 'subclone', id: 3 }, { text: 'fett', children: [ { clone: 3 }, ] }, ] }, ] }, { clone: 2 }, ]); t.sendKeys('Gdd'); t.expect([ { text: 'jango', children: [ { text: 'clone', id: 2, children: [ 'subclone', 'fett', ] }, ] }, { clone: 2 }, ]); t.sendKeys('ggjdd'); t.expect([ 'jango', { text: 'clone', children: [ 'subclone', 'fett', ] }, ]); t.sendKeys('u'); t.expect([ { text: 'jango', children: [ { text: 'clone', id: 2, children: [ 'subclone', 'fett', ] }, ] }, { clone: 2 }, ]); t.sendKeys('u'); t.expect([ { text: 'jango', children: [ { text: 'clone', id: 2, children: [ { text: 'subclone', id: 3 }, { text: 'fett', children: [ { clone: 3 }, ] }, ] }, ] }, { clone: 2 }, ]); await t.done(); }); it('works nested, second basic test', async function() { let t = new TestCase([ { text: 'jango', children: [ { text: 'clone', id: 2, children: [ { text: 'subclone', id: 3 }, { text: 'fett', children: [ { clone: 3 }, ] }, ] }, ] }, { clone: 2 }, ]); t.sendKeys('jdd'); t.expect([ 'jango', { text: 'clone', children: [ { text: 'subclone', id: 3 }, { text: 'fett', children: [ { clone: 3 }, ] }, ] }, ]); t.sendKeys('jjdd'); t.expect([ 'jango', { text: 'clone', children: [ { text: 'fett', children: [ 'subclone', ] }, ] }, ]); t.sendKeys('u'); t.expect([ 'jango', { text: 'clone', children: [ { text: 'subclone', id: 3 }, { text: 'fett', children: [ { clone: 3 }, ] }, ] }, ]); t.sendKeys('u'); t.expect([ { text: 'jango', children: [ { text: 'clone', id: 2, children: [ { text: 'subclone', id: 3 }, { text: 'fett', children: [ { clone: 3 }, ] }, ] }, ] }, { clone: 2 }, ]); await t.done(); }); it('can cycle between clones', async function() { let t = new TestCase([ { text: 'blah', children: [ { text: 'clone', id: 2, children: [ 'child', 'child', ] }, ] }, 'sibling', { clone: 2 }, 'sibling', ]); t.sendKeys('jx'); t.expect([ { text: 'blah', children: [ { text: 'lone', id: 2, children: [ 'child', 'child', ] }, ] }, 'sibling', { clone: 2 }, 'sibling', ]); t.sendKeys('gckx'); t.expect([ { text: 'blah', children: [ { text: 'lone', id: 2, children: [ 'child', 'child', ] }, ] }, 'ibling', { clone: 2 }, 'sibling', ]); t.sendKeys('jgckx'); t.expect([ { text: 'lah', children: [ { text: 'lone', id: 2, children: [ 'child', 'child', ] }, ] }, 'ibling', { clone: 2 }, 'sibling', ]); t.sendKeys('jddjjx'); t.expect([ 'lah', 'ibling', { text: 'one', children: [ 'child', 'child', ] }, 'sibling', ]); t.sendKeys('gcx'); t.expect([ 'lah', 'ibling', { text: 'ne', children: [ 'child', 'child', ] }, 'sibling', ]); await t.done(); }); it('can cycle between clones with stranded parents', async function() { let t = new TestCase([ { text: 'blah', children: [ { text: 'clone', id: 2 }, ] }, { text: 'blah2', children: [ { clone: 2 }, ] }, 'sibling', { clone: 2 }, 'sibling', ]); t.sendKeys('dd'); t.expect([ { text: 'blah2', children: [ { text: 'clone', id: 2 }, ] }, 'sibling', { clone: 2 }, 'sibling', ]); t.sendKeys('jgckx'); t.expect([ { text: 'blah2', children: [ { text: 'clone', id: 2 }, ] }, 'ibling', { clone: 2 }, 'sibling', ]); t.sendKeys('jgcjx'); t.expect([ { text: 'blah2', children: [ { text: 'clone', id: 2 }, ] }, 'bling', { clone: 2 }, 'sibling', ]); t.sendKeys('kgckx'); t.expect([ { text: 'blah2', children: [ { text: 'clone', id: 2 }, ] }, 'ling', { clone: 2 }, 'sibling', ]); await t.done(); }); });
the_stack
import { Command } from "commander"; import { loadCookies, getRequester, saveCookies, getRequesterCdn } from "./common"; import { CrDl, Episode } from "../api/CrDl"; import { UserInputError, RuntimeError } from "../Errors"; import { languages, Language } from "../types/language"; import { makeid, pad, toFilename, formatScene, deleteFolderRecursive } from "../Utils"; import * as util from "util"; import * as fs from "fs"; import * as path from "path"; import { SubtitleInfo, StreamInfo } from "../interfaces/video"; import { downloadFontsFromSubtitles } from "../downloader/FontDownloader"; import { Requester, RequesterCdn } from "../types/Requester"; import * as format_ from "string-format"; import { M3uDownloader } from "../downloader/M3uDownloader"; import { ListDownloader, DownloadUpdateOptions } from "../downloader/ListDownloader"; import { VideoMuxer } from "../downloader/VideoMuxer"; import * as cliProgress from "cli-progress"; import prettyBytes from "pretty-bytes"; import { spawn } from "child_process"; const format = format_.create({ scene: formatScene }); export const download = new Command(); interface Options { proxy?: string; proxyCdn?: string; format: string; connections: number; listSubs: boolean; defaultSub?: Language | "none"; subLang?: (Language | "none")[]; hardsub: boolean; attachFonts: boolean; subsOnly: boolean; output?: string; progressBar: boolean; retry: number; season?: string[]; episode?: string[]; cookies: string; } let requester: Requester; let requesterCdn: RequesterCdn; download .name("download").alias("dl") .description("Download video or series from URL") .arguments("<URL>") .option("-f, --format <resolution>", "Video resolution", "1080p") .option("--season <LIST>", "A season number or a comma-separated list (without spaces) of season numbers to download. A ```-``` (minus) can be used to specify a range (e.g. ```1,3-5```). Works only for series-links. Note: Season 1 is the bottom-most season on the website.") .option("--episode <LIST>", "A comma-separated list of episode numbers to download. A ```-``` (minus) can be used to specify a range (e.g. ```01,03-05,SP2```). If a given episode number exists in multiple seasons, you must specify one with --season.") .option("-c, --connections <connections>", "Number of simultaneous connections", "5") .option("--sub-lang <LANGS>", "Specify subtitle languages as a comma separated list to include in video. (e.g. deDE,enUS). Set to ```none``` to embed no subtitles. Use --list-subs for available languages. (Default: All available)") .option("--default-sub <LANG>", "Specify subtitle language to be set as default. (e.g. enUS). (Default: if --sub-lang defined: first entry, otherwise: crunchyroll default)") .option("--attach-fonts", "Automatically download and attach all fonts that are used in subtitles.") .option("--list-subs", "Don't download. List all available subtitles for the video.") .option("--subs-only", "Download only subtitles. No Video.") .option("--hardsub", "Download hardsubbed video stream. Only one subtitle language specified by --default-sub will be included.") .option("--retry <N>", "Max number of download attempts before aborting.", "5") .option("--cookies <FILE>", "File to read cookies from and dump cookie jar in", "cookies.txt") .option("--no-progress-bar", "Hide progress bar.") .option("--proxy <url>", "HTTP(s) proxy to access Crunchyroll. This is enough to bypass geo-blocking.") .option("--proxy-cdn <url>", "HTTP proxy used to download video files. Not required for bypassing geo-blocking.") .option("-o, --output <template>", "Output filename template, see the \"OUTPUT TEMPLATE\" in README for all the info.") .action(async function (url: string, cmdObj) { const options: Options = { proxy: cmdObj.proxy, proxyCdn: cmdObj.proxyCdn, format: cmdObj.format, connections: parseInt(cmdObj.connections), listSubs: !!cmdObj.listSubs, defaultSub: cmdObj.defaultSub, subLang: cmdObj.subLang ? cmdObj.subLang.split(/[, ]/) : undefined, hardsub: !!cmdObj.hardsub, attachFonts: !!cmdObj.attachFonts, subsOnly: !!cmdObj.subsOnly, output: cmdObj.output, progressBar: !!cmdObj.progressBar, retry: parseInt(cmdObj.retry), season: cmdObj.season?.split(/[, ]/), episode: cmdObj.episode?.split(/[, ]/), cookies: cmdObj.cookies, }; if (isNaN(options.connections)) { console.log("--connections must be a number"); return; } if (isNaN(options.retry)) { console.log("--retry must be a number"); return; } if (options.defaultSub && options.defaultSub !== "none" && !languages.includes(options.defaultSub)) { console.log("--default-sub: Unknown language. Must be one of: none, " + languages.join(", ")); return; } if (options.subLang) { for (const lang of options.subLang) { if (lang !== "none" && !languages.includes(lang)) { console.log("--sub-lang: Unknown language " + util.inspect(lang) + ". Must be one of: none, " + languages.join(", ")); return; } } } if (!options.subsOnly && !options.listSubs) { // ffmpeg is required try { await verifyFfmpeg(); } catch (e) { console.error("Error: ffmpeg needs to be installed"); return; } } loadCookies(options); requester = getRequester(options); requesterCdn = getRequesterCdn(options); const crDl = new CrDl({ requester: requester, requesterCdn: requesterCdn }); try { if (/www\.crunchyroll\.com\/([a-z-]{1,5}\/)?[^/]+\/[^/]+-[0-9]+(:?\?.*)?$/.exec(url)) { await downloadVideo(url, crDl, options); } else if (/www\.crunchyroll\.com\/([a-z-]{1,5}\/)?[^/]+\/?$/.exec(url)) { await downloadSeries(url, crDl, options); } else { console.log("Error: Unsupported URL"); } } catch (error) { if (error instanceof UserInputError) { console.log(error.message); // Dont print stacktrace } else { console.log(error); } } saveCookies(options); }); async function downloadVideo(url: string, crDl: CrDl, options: Options): Promise<void> { options = Object.assign({}, options); const tmpDir = "tmp_" + makeid(6) + "/"; try { const media = await crDl.loadEpisode(url); if (await media.isPremiumBlocked()) { throw new UserInputError("Error: Episode requires a premium account."); } if (await media.isRegionBlocked()) { throw new UserInputError("Error: Episode seems to be blocked in your region. In some cases it's still watchable with a premium account."); } const subtitles = await media.getSubtitles(); if (options.listSubs) { // List subs. Do not download. const subsTable: { title: string; langCode: string; isDefault: boolean }[] = []; for (const sub of subtitles) { subsTable.push({ title: await sub.getTitle(), langCode: await sub.getLanguage(), isDefault: await sub.isDefault() }); } console.table(subsTable); return; } // Ensure options if (!options.defaultSub) { if (options.subLang && options.subLang.length > 0) { options.defaultSub = options.subLang[0]; } else if (subtitles.length == 0) { options.defaultSub = "none"; } else { options.defaultSub = await media.getDefaultLanguage(); } } if (!options.subLang) { if (options.hardsub) { options.subLang = [options.defaultSub]; } else { options.subLang = []; for (const sub of subtitles) { options.subLang.push(await sub.getLanguage()); } } } // select and download Subs let hardsubLang: Language | null = null; let subsToInclude: SubToInclude[]; if (options.hardsub && options.defaultSub !== "none") { if (options.subLang.length > 1) throw new UserInputError("Cannot embed multiple subtitles with --hardsub"); hardsubLang = options.defaultSub; subsToInclude = []; console.log(`Selected "${hardsubLang}" as hardsub language.`); } else { hardsubLang = null; subsToInclude = await downloadSubs(subtitles, path.join(tmpDir, "SubData"), options.subLang, options.defaultSub); } if (subsToInclude.length > 0) { console.log("Following subtitles will be included: "); console.table(subsToInclude, ["title", "langCode", "default"]); } else { console.log("No subtitles will be included."); } // download fonts let fontsToInclude: string[] = []; if (options.attachFonts) { fontsToInclude = await downloadFontsFromSubtitles(requesterCdn, options.retry, subsToInclude, path.join(tmpDir, "Fonts")); } //console.log(fontsToInclude); let selectedStream: StreamInfo | undefined = undefined; if (!options.subsOnly) { const resolution = getMaxWantedResolution(await media.getAvailableResolutions(hardsubLang), options.format); // We may get multiple streams on different servers. Just take first. selectedStream = (await media.getStreams(resolution, hardsubLang))[0]; } const metadata: Record<string, string> = { episodeTitle: await media.getEpisodeTitle(), seriesTitle: await media.getSeriesTitle(), episodeNumber: await media.getEpisodeNumber(), seasonTitle: await media.getSeasonTitle(), resolution: options.subsOnly ? "subtitles" : selectedStream?.getHeight() + "p", }; if (!isNaN(parseInt(metadata.episodeNumber))) { metadata.episodeNumber = pad(metadata.episodeNumber, 2); } const formatData: Record<string, string> = {}; for (const prop in metadata) { formatData[prop] = toFilename(metadata[prop]); } if (!options.output) { if (options.subsOnly) { options.output = "{seasonTitle} [subtitles]/{seasonTitle} - {episodeNumber} - {episodeTitle}.ass"; } else { options.output = "{seasonTitle} [{resolution}]/{seasonTitle} - {episodeNumber} - {episodeTitle} [{resolution}].mkv"; } } let outputPath = format(options.output, formatData); const fullPath = path.join(process.cwd(), outputPath); if (fullPath.length > 255) { // windows doesnt support paths longer than 259(-4 for .tmp extension) characters console.log(); console.log(`Warning: The path is too long (${fullPath.length} characters but only 255 are allowed) and can cause issues. Please use --output <template> to select a shorter path: ${util.inspect(fullPath)}`); console.log(); if (process.platform == "win32") { outputPath = "\\\\?\\" + fullPath; // Windows unicode extended-length path } } console.log(`Downloading to "${outputPath}"...`); try { await fs.promises.access(outputPath, fs.constants.F_OK); console.log("File already exists. Skipping..."); return; } catch (e) { // empty } const outputDirectory = path.dirname(outputPath); if (outputDirectory.length > 0) { await fs.promises.mkdir(outputDirectory, { recursive: true }); } if (options.subsOnly) { await downloadSubsOnly(subsToInclude, outputPath); } else { //const m3u8File = await downloadVideoFromM3U(selectedStream.getUrl(), "VodVid", options) if (!selectedStream) throw new RuntimeError("No stream selcted. Should never happen."); await fs.promises.mkdir(path.join(tmpDir, "VodVid"), { recursive: true }); // === M3u8 File === const m3u8File = new M3uDownloader(); const m3u8FilePath = path.join(tmpDir, "VodVid.m3u8"); await m3u8File.load(selectedStream.getUrl(), tmpDir, "VodVid", requesterCdn); await fs.promises.writeFile(m3u8FilePath, m3u8File.getModifiedM3u()); // === Key File === const keyFile = m3u8File.getKeyFile(); if (keyFile) { await ListDownloader.safeDownload(keyFile.url, keyFile.destination, 5, requesterCdn); } // === Video Files Download === const listDownloader = new ListDownloader(m3u8File.getVideoFiles(), options.retry, options.connections, requesterCdn); if (options.progressBar) { const bar1 = new cliProgress.Bar({ format: "downloading [{bar}] {percentage}% | {downSize}/{estSize} | Speed: {speed}/s | ETA: {myEta}s" }, cliProgress.Presets.shades_classic); bar1.start(1, 0); listDownloader.on("update", (data: DownloadUpdateOptions) => { bar1.setTotal(data.estimatedSize); bar1.update(data.downloadedSize, { downSize: prettyBytes(data.downloadedSize), estSize: prettyBytes(data.estimatedSize), speed: prettyBytes(data.speed), myEta: Math.floor((data.estimatedSize - data.downloadedSize) / data.speed) }); }); await listDownloader.startDownload(); bar1.stop(); } else { let lastPrint = Date.now(); listDownloader.on("update", (data: DownloadUpdateOptions) => { const now = Date.now(); if (now < lastPrint + 1000) return; // Once per second lastPrint += 1000; const s = { percentage: Math.floor(data.downloadedSize / data.estimatedSize * 100), downSize: prettyBytes(data.downloadedSize), estSize: prettyBytes(data.estimatedSize), speed: prettyBytes(data.speed), myEta: Math.floor((data.estimatedSize - data.downloadedSize) / data.speed) }; process.stdout.write(`\rdownloading ${s.percentage}% | ${s.downSize}/${s.estSize} | Speed: ${s.speed}/s | ETA: ${s.myEta}s `); }); await listDownloader.startDownload(); console.log(); // new line } // === Video Muxing === const tmpPath = outputPath.substring(0, outputPath.lastIndexOf(".")) + ".tmp" + outputPath.substring(outputPath.lastIndexOf(".")); const videoMuxer = new VideoMuxer({ input: m3u8FilePath, subtitles: subsToInclude, fonts: fontsToInclude, output: tmpPath }); let totalDuration = ""; if (options.progressBar) { const bar2 = new cliProgress.Bar({ format: "muxing [{bar}] {percentage}% | {curDuration}/{totalDuration} | Speed: {fps} fps" }, cliProgress.Presets.shades_classic); bar2.start(1, 0); videoMuxer.on("total", (totalMilliseconds: number, totalString: string) => { bar2.setTotal(totalMilliseconds); totalDuration = totalString; }); videoMuxer.on("progress", (progressMilliseconds: number, progressString: string, fps: number) => { bar2.update(progressMilliseconds, { curDuration: progressString, totalDuration: totalDuration, fps }); }); const output: string[] = []; videoMuxer.on("info", (data: string) => { if (data.match(/Opening .* for reading/)) return; //Spam else if (data.startsWith("frame=")) return; //status else output.push(data); // Remember in case of error }); try { await videoMuxer.run(); bar2.stop(); } catch (e) { // Error: print ffmpeg output bar2.stop(); console.log("ffmpeg output: " + output.join("\r\n")); throw e; } } else { videoMuxer.on("info", (data: string) => { if (data.match(/Opening .* for reading/)) return; //Spam else if (data.startsWith("frame=")) process.stdout.write("\r" + data); //replace line else console.log(data); }); await videoMuxer.run(); } await fs.promises.rename(tmpPath, outputPath); } } finally { try { deleteFolderRecursive(tmpDir); } catch (e) { // empty } } } async function downloadSubsOnly(subtitlesToInclude: SubToInclude[], outputPath: string): Promise<void> { if (outputPath.lastIndexOf("/") < outputPath.lastIndexOf(".")) { outputPath = outputPath.substr(0, outputPath.lastIndexOf(".")); } for (const sub of subtitlesToInclude) { await fs.promises.rename(sub.path, `${outputPath}.${sub.langCode}.ass`); } } async function downloadSeries(url: string, crDl: CrDl, options: Options): Promise<void> { const list = await crDl.getEpisodesFormUrl(url); let seasonsToDownload = list; // select season(s) if (options.season) { const wantedSeasons: number[] = options.season.flatMap<number, string>((currentValue: string) => { const bounds = currentValue.split("-"); if (bounds.length == 1) { if (isNaN(parseInt(bounds[0]))) throw new UserInputError(`Season number "${bounds[0]}" invalid.`); return parseInt(bounds[0]) - 1; } else if (bounds.length == 2) { if (isNaN(parseInt(bounds[0]))) throw new UserInputError(`Season number "${bounds[0]}" invalid.`); if (isNaN(parseInt(bounds[1]))) throw new UserInputError(`Season number "${bounds[1]}" invalid.`); const r: number[] = []; for (let i = parseInt(bounds[0]); i <= parseInt(bounds[1]); i++) { r.push(i - 1); } return r; } else { throw new UserInputError(`Season number "${currentValue}" invalid.`); } }); seasonsToDownload = []; for (const s of wantedSeasons) { if (!list[s]) throw new UserInputError(`Season ${s + 1} not available.`); seasonsToDownload.push(list[s]); } } // notify of restricted seasons for (const s of seasonsToDownload) { if (s.isRegionBlocked) { console.log(`Notice: Season "${s.name}" is not available in your region and will be skipped.`); } else if (s.isLanguageUnavailable) { console.log(`Notice: Season "${s.name}" is not available in selected language and will be skipped.`); } else if (s.episodes.length === 0) { console.log(`Notice: Season "${s.name}" has no episodes and will be skipped.`); } } // Remove empty seasons seasonsToDownload = seasonsToDownload.filter(s => s.episodes.length > 0); if (seasonsToDownload.length == 0) throw new UserInputError("No Episodes found."); // select episode(s) if (options.episode) { // if episode number numeric, convert string to number and back to string to normalize representation (e.g. leading zeros) seasonsToDownload.forEach(s => s.episodes.forEach(e => { if (!isNaN(Number(e.number))) e.number = Number(e.number).toString(); })); type episodePosition = { seasonIndex: number; episodeIndex: number }; const getEpisodeFromNumber = (number: string): episodePosition => { if (!isNaN(Number(number))) number = Number(number).toString(); const results: episodePosition[] = []; for (let seasonIndex = 0; seasonIndex < seasonsToDownload.length; seasonIndex++) { const season = seasonsToDownload[seasonIndex].episodes; for (let episodeIndex = 0; episodeIndex < season.length; episodeIndex++) { const episode = season[episodeIndex]; if (episode.number == number) { results.push({ seasonIndex, episodeIndex }); } } } if (results.length == 0) { throw new UserInputError(`Episode "${number}" not found.`); } else if (results.length == 1) { return results[0]; } else { let areAllMatchesInSameSeason = true; for (let index = 0; index < results.length - 1; index++) { if (results[index].seasonIndex != results[index + 1].seasonIndex) areAllMatchesInSameSeason = false; } if (areAllMatchesInSameSeason) { // allow multiple matches within a season otherwise we wouldn't be able to specify an episode console.log(`Warning: Multiple episodes found matching "${number}". Selecting first.`); return results[0]; } else { throw new UserInputError(`Collision between seasons for episode "${number}". Please specify one season with --season to use --episode.`); } } }; const addEpisodesInRange = (start: episodePosition, end: episodePosition): Episode[] => { let curSeason = start.seasonIndex; let curEpisode = start.episodeIndex; const result: Episode[] = []; while (curSeason < end.seasonIndex || (curSeason == end.seasonIndex && curEpisode <= end.episodeIndex)) { result.push(seasonsToDownload[curSeason].episodes[curEpisode]); if (curEpisode < seasonsToDownload[curSeason].episodes.length - 1) { curEpisode++; } else { // Range between seasons curSeason++; curEpisode = 0; } } return result; }; const episodesToDownload = options.episode.flatMap(n => { const bounds = n.split("-"); if (bounds.length == 1) { const ep = getEpisodeFromNumber(n); return seasonsToDownload[ep.seasonIndex].episodes[ep.episodeIndex]; } else if (bounds.length == 2) { const min = getEpisodeFromNumber(bounds[0]); const max = getEpisodeFromNumber(bounds[1]); return addEpisodesInRange(min, max); } else { throw new UserInputError("Invalid episode number: " + n); } }); seasonsToDownload.forEach(value => { value.episodes = value.episodes.filter(ep => episodesToDownload.includes(ep)); }); } // Remove empty seasons (again) seasonsToDownload = seasonsToDownload.filter(s => s.episodes.length > 0); if (seasonsToDownload.length == 0) throw new UserInputError("No Episodes selected."); //console.log(require('util').inspect(seasonsToDownload, false, null, true /* enable colors */)) console.log("Following episodes will be dowloaded:"); for (const s of seasonsToDownload) { if (s.name !== "") console.log(`Season "${s.name}":`); console.log(s.episodes.map(e => e.number).join(", ")); console.log(); } for (const season of seasonsToDownload) { for (const episode of season.episodes) { console.log(); console.log(`Downloading S(${pad(seasonsToDownload.indexOf(season) + 1, 2)}/${pad(seasonsToDownload.length, 2)})E(${pad(season.episodes.indexOf(episode) + 1, 2)}/${pad(season.episodes.length, 2)}) - ${episode.name}`); await downloadVideo("http://www.crunchyroll.com" + episode.url, crDl, options); } } } async function getSubtitleByLanguage(subtitles: SubtitleInfo[], language: Language): Promise<SubtitleInfo | undefined> { let sub: SubtitleInfo | undefined = undefined; for (const subt of subtitles) { if (await subt.getLanguage() == language) { sub = subt; break; } } return sub; } interface SubToInclude { title: string; path: string; language: string; langCode: Language; default: boolean; } async function downloadSubs(subtitles: SubtitleInfo[], destination: string, langs: (Language | "none")[], defaultSub: Language | "none"): Promise<SubToInclude[]> { const subsToInclude: SubToInclude[] = []; await fs.promises.mkdir(destination, { recursive: true }); for (const lang of langs) { if (lang == "none") continue; const sub = await getSubtitleByLanguage(subtitles, lang); if (!sub) { console.error("Subtitles for " + lang + " not available. Skipping..."); } else { const filePath = path.join(destination, await sub.getLanguage() + ".ass"); fs.promises.writeFile(filePath, await sub.getData()); subsToInclude.push({ title: await sub.getTitle(), path: filePath, language: await sub.getLanguageISO6392T(), langCode: await sub.getLanguage(), default: false }); } } if (defaultSub != "none") { let defaultSet = false; for (const sub of subsToInclude) { if (sub.langCode == defaultSub) { sub.default = true; defaultSet = true; } else { sub.default = false; } } if (!defaultSet) { throw new UserInputError("Couldn't set " + defaultSub + " as default subtitle: subtitle not available."); } } return subsToInclude; } function getMaxWantedResolution(availableResolutions: number[], res: number | string): number { if (typeof res == "string" && res.endsWith("p")) { res = res.substr(0, res.length - 1); } res = parseInt(res as string); if (isNaN(res)) throw new UserInputError("Invalid resolution."); if (availableResolutions.indexOf(res) > -1) { return res; } availableResolutions = availableResolutions.sort((a, b) => a - b); console.log(availableResolutions); for (let i = availableResolutions.length - 1; i >= 0; i--) { if (availableResolutions[i] <= res) { console.log(`Resolution ${res}p not available. Using ${availableResolutions[i]}p instead.`); return availableResolutions[i]; } } throw new RuntimeError("No resolutions found."); } function verifyFfmpeg(): Promise<void> { return new Promise((resolve, reject) => { const proc = spawn("ffmpeg"); proc.on("error", (err) => { reject(err); }); proc.on("close", () => { resolve(); }); }); }
the_stack
import { EventEmitter } from "events"; /** * A selection is basically an array of ranges. Every range represents a real * selection or a cursor in the document (when the start position equals the * end position of the range). The array must not be empty. */ export class Selection { ranges: Selection.Range[]; position: number; selectionEnd?: any; equals(other: Selection): boolean; somethingSelected(): boolean; /** * Return the more current selection information. * @param operation The op */ compose(operation: TextOperation): Selection; /** * Update the selection with respect to an operation. * @param operation The op */ transform(operation: TextOperation): Selection; /** * Convenience method for creating selections only containing a single cursor * and no real selection range. * @param position The pos */ static createCursor(position: number): Selection; static fromJSON(obj: string): Selection; } export namespace Selection { /* * Range has `anchor` and `head` properties, which are zero-based indices into * the document. The `anchor` is the side of the selection that stays fixed, * `head` is the side of the selection where the cursor is. When both are * equal, the range represents a cursor. */ class Range { anchor: number; head: number; constructor(anchor: number, head: number); equals(other: Range): boolean; isEmpty(): boolean; transform(operation: TextOperation): Range; static fromJSON(object: { anchor: number; head: number; }): Range; } } export type SerializedTextOperation = Array<string | number>; /** * Operation are essentially lists of ops. There are three types of ops: * * * Retain ops: Advance the cursor position by a given number of characters. * Represented by positive ints. * * Insert ops: Insert a given string at the current cursor position. * Represented by strings. * * Delete ops: Delete the next n characters. Represented by negative ints. * * After an operation is constructed, the user of the library can specify the * actions of an operation (skip/insert/delete) with the three builder * methods. They all return the operation for convenient chaining. */ export class TextOperation { /** * An operation's baseLength is the length of every string the operation * can be applied to. */ baseLength: number; /** * When an operation is applied to an input string, you can think of this as * if an imaginary cursor runs over the entire string and skips over some * parts, deletes some parts and inserts characters at some positions. These * actions (skip/delete/insert) are stored as an array in the "ops" property. */ ops: SerializedTextOperation; /** * The targetLength is the length of every string that results from applying * the operation on a valid input string. */ targetLength: number; equals(other: TextOperation): boolean; /** * Apply an operation to a string, returning a new string. Throws an error if * there's a mismatch between the input string and the operation. * @param doc The doc */ apply(doc: string): string; /** * Computes the inverse of an operation. The inverse of an operation is the * operation that reverts the effects of the operation, e.g. when you have an * operation 'insert("hello "); skip(6);' then the inverse is 'delete("hello "); * skip(6);'. The inverse should be used for implementing undo. * @param doc The doc */ invert(doc: string): TextOperation; /** * Compose merges two consecutive operations into one operation, that * preserves the changes of both. Or, in other words, for each input string S * and a pair of consecutive operations A and B, * apply(apply(S, A), B) = apply(S, compose(A, B)) must hold. * @param operation The op */ compose(operation: TextOperation): TextOperation; /** * When you use ctrl-z to undo your latest changes, you expect the program not * to undo every single keystroke but to undo your last sentence you wrote at * a stretch or the deletion you did by holding the backspace key down. This * This can be implemented by composing operations on the undo stack. This * method can help decide whether two operations should be composed. It * returns true if the operations are consecutive insert operations or both * operations delete text at the same position. You may want to include other * factors like the time since the last change in your decision. * @param operation The op */ shouldBeComposedWith(operation: TextOperation): boolean; /** * Decides whether two operations should be composed with each other * if they were inverted, that is * `shouldBeComposedWith(a, b) = shouldBeComposedWithInverted(b^{-1}, a^{-1})`. * @param operation The op */ shouldBeComposedWithInverted(operation: TextOperation): boolean; /** * Delete a string at the current position. * @param str The string or its length */ delete(str: number | string): TextOperation; /** * Insert a string at the current position. * @param str The string */ insert(str: string): TextOperation; /** * Skip over a given number of characters. * @param length The length */ retain(length: number): TextOperation; /** * Tests whether this operation has no effect. */ isNoop(): boolean; /** * Pretty printing. */ toString(): string; /** * Converts operation into a JSON value. */ toJSON(): SerializedTextOperation; /** * Converts a plain JS object into an operation and validates it. * @param operation The op */ static fromJSON(operation: SerializedTextOperation): TextOperation; /** * Delete ops: Delete the next n characters. Represented by negative ints. * @param operation The op */ static isDelete(operation: string | number): boolean; /** * Insert ops: Insert a given string at the current cursor position. * Represented by strings. * @param operation The op */ static isInsert(operation: string | number): boolean; /** * Retain ops: Advance the cursor position by a given number of characters. * Represented by positive ints. * @param operation The op */ static isRetain(operation: string | number): boolean; /** * Transform takes two operations A and B that happened concurrently and * produces two operations A' and B' (in an array) such that * `apply(apply(S, A), B') = apply(apply(S, B), A')`. This function is the * heart of OT. * @param left The left op * @param right The right op */ static transform(left: TextOperation, right: TextOperation): TextOperation; } export class Client { revision: number; state: Client.Synchronized; constructor(revision: number); setState(state: Client.Synchronized): void; /** * Call this method when the user changes the document. * @param operation The op */ applyClient(operation: TextOperation): void; /** * Call this method with a new operation from the server * @param operation The op */ applyServer(operation: TextOperation): void; serverAck(): void; serverReconnect(): void; /** * Transforms a selection from the latest known server state to the current * client state. For example, if we get from the server the information that * another user's cursor is at position 3, but the server hasn't yet received * our newest operation, an insertion of 5 characters at the beginning of the * document, the correct position of the other user's cursor in our current * document is 8. * @param selection The selection */ transformSelection(selection: Selection): Selection; /** * Override this method. * @param revision The revision * @param operation The op */ sendOperation(revision: number, operation: TextOperation): void; /** * Override this method. * @param operation The op */ applyOperation(operation: TextOperation): void; } export namespace Client { interface Sync<C, S, A> { applyClient(client: Client, operation: TextOperation): C; applyServer(client: Client, operation: TextOperation): S; serverAck(): A; transformSelection(selection: Selection): Selection; } /** * In the 'Synchronized' state, there is no pending operation that the client * has sent to the server. */ interface Synchronized extends Sync<AwaitingConfirm, Synchronized, never> {} function Synchronized(): Synchronized; /** * In the 'AwaitingConfirm' state, there's one operation the client has sent * to the server and is still waiting for an acknowledgement. */ interface AwaitingConfirm extends Sync<AwaitingWithBuffer, AwaitingConfirm, Synchronized> { outstanding: TextOperation; resend(client: Client): void; } function AwaitingConfirm(outstanding: TextOperation): AwaitingConfirm; /** * In the 'AwaitingWithBuffer' state, the client is waiting for an operation * to be acknowledged by the server while buffering the edits the user makes */ interface AwaitingWithBuffer extends Sync<AwaitingWithBuffer, AwaitingWithBuffer, AwaitingConfirm> { outstanding: TextOperation; buffer: TextOperation; resend(client: Client): void; } function AwaitingWithBuffer(outstanding: TextOperation, buffer: TextOperation): AwaitingWithBuffer; } export class Server { document: string; operations?: TextOperation[] | undefined; /** * Constructor. Takes the current document as a string and optionally the array * of all operations. * @param document The doc * @param operations The ops */ constructor(document: string, operations?: TextOperation[]) /** * Call this method whenever you receive an operation from a client. * @param revision The revision * @param operation The op */ receiveOperation(revision: number, operation: TextOperation): TextOperation; } export class SimpleTextOperation { apply(doc: string): string; toString(): string; equals(other: SimpleTextOperation): boolean; static transform(a: SimpleTextOperation, b: SimpleTextOperation): [SimpleTextOperation, SimpleTextOperation]; /** * Convert a normal, composable `TextOperation` into an array of * `SimpleTextOperation`s. * @param operation The op */ static fromTextOperation(operation: TextOperation): SimpleTextOperation[]; } export namespace SimpleTextOperation { /** * Insert the string `str` at the zero-based `position` in the document. */ class Insert extends SimpleTextOperation { constructor(str: string, position: number); } /** * Delete `count` many characters at the zero-based `position` in the document. */ class Delete extends SimpleTextOperation { constructor(count: number, position: number); } /** * An operation that does nothing. This is needed for the result of the * transformation of two deletions of the same character. */ class Noop extends SimpleTextOperation {} } export interface EditorSocketIOServer<S extends { id: string } = any, C = any> extends EventEmitter, Server { // new(document: string, operations: TextOperation[], docId: string, mayWrite?: (_: any, cb: (b: boolean) => void) => void): EditorSocketIOServer; addClient(socket: S): void; onOperation(socket: S, revision: number, operation: string, selection: string): void; updateSelection(socket: S, selection: string): void; setName(socket: S, name: string): void; getClient(clientId: string): C; onDisconnect(socket: S): void; } export {}; type UndoState = 'normal' | 'undoing' | 'redoing'; export class UndoManager { /** * Create a new UndoManager with an optional maximum history size. * @param maxItems The max history size */ constructor(maxItems?: number); state: UndoState; dontCompose: boolean; undoStack: WrappedOperation[]; redoStack: WrappedOperation[]; /** * Add an operation to the undo or redo stack, depending on the current state * of the UndoManager. * @param operation The operation added must be the inverse of the last * edit. * @param compose When `true`, compose the operation with the last operation * unless the last operation was alread pushed on the redo stack or was hidden * by a newer operation on the undo stack */ add(operation: TextOperation | WrappedOperation, compose?: boolean): void; /** * Transform the undo and redo stacks against a operation by another client. * @param operation The op */ transform(operation: TextOperation | WrappedOperation): void; /** * Perform an undo by calling a function with the latest operation on the undo * stack. * @param fun The function is expected to call the `add` method with the inverse * of the operation, which pushes the inverse on the redo stack. */ performUndo(fun: (op: WrappedOperation) => void): void; /** * The inverse of `performUndo`. * @param fun The function */ performRedo(fun: (op: WrappedOperation) => void): void; /** * Is the undo stack not empty? */ canUndo(): boolean; /** * Is the redo stack not empty? */ canRedo(): boolean; /** * Whether the UndoManager is currently performing an undo. */ isUndoing(): boolean; /** * Whether the UndoManager is currently performing a redo. */ isRedoing(): boolean; } /** * A WrappedOperation contains an operation and corresponing metadata. */ export class WrappedOperation<T = any> { wrapped: TextOperation; meta: T; constructor(operation: TextOperation, meta?: T); apply(doc: string): string; invert(doc: string): WrappedOperation<T>; compose(operation: WrappedOperation<T>): WrappedOperation<T>; static transform<T>(left: WrappedOperation<T>, right: WrappedOperation<T>): WrappedOperation<T>; } export interface ClientAdapter { registerUndo(fun: () => void): void; registerRedo(fun: () => void): void; getValue(): string; applyOperation(operation: TextOperation): void; setSelection(selection?: Selection): void; getSelection(): Selection; registerCallbacks(callbacks: ClientAdapterCallbacks): void; setOtherSelection(selection: Selection, color: string, otherClientId: string): Mark; } export interface ClientAdapterCallbacks { change(operation: TextOperation, inverse: TextOperation): void; selectionChange(): void; blur(): void; } export interface ServerAdapter { sendSelection(selection?: Selection): void; sendOperation(revision: number, operation: SerializedTextOperation, selection?: Selection): void; registerCallbacks(callbacks: ServerAdapterCallbacks): void; } export interface ServerAdapterCallbacks { client_left(clientId: string): void; set_name(clientId: string, name: string): void; ack(): void; operation(operation: SerializedTextOperation): void; selection(clientId: string, selection: string): void; clients(clients: any): void; reconnect(): void; } export interface ClientObj { clientId: string; name?: string | undefined; selection: string; } export interface Clients<T = any> { [clientId: string]: T; } export interface Mark { clear(): void; } export class EditorClient extends Client { revision: number; clients: { [key: string]: EditorClient.OtherClient }; serverAdapter: any; editorAdapter: any; constructor(revision: number, clients: ClientObj[], serverAdapter: ServerAdapter, editorAdapter: ClientAdapter); // not sure about all those signatures addClient(clientId: string, clientObj: ClientObj): void; initializeClients(clients: Clients): void; getClientObject(clientId: string): ClientObj; onClientLeft(clientId: string): void; initializeClientList(): void; applyUnredo(operation: TextOperation): void; undo(): void; redo(): void; onChange(textOperation: TextOperation, inverse: TextOperation): void; updateSelection(): void; onSelectionChange(): void; onBlur(): void; sendSelection(selection: Selection): void; sendOperation(revision: number, operation: TextOperation): void; applyOperation(operation: TextOperation): void; } // TODO export namespace EditorClient { class SelfMeta {} class OtherClient {} } export const version: string;
the_stack
'use strict'; import * as assert from 'assert'; import Ajv = require('ajv'); const schema = require('../assets/nlu.schema.json'); import log from "./logging"; import {EVCb, NluConf, NluMap, NluMapItem, PkgJSON} from "./index"; import chalk from 'chalk'; import * as fs from 'fs'; import * as path from 'path'; import async = require('async'); import {NLURunOpts} from "./commands/run/cmd-line-opts"; import * as util from "util"; import semver = require('semver'); import * as residence from 'residence'; //////////////////////////////////////////////////////////////////// export const globalConfigFilePath = path.resolve(process.env.HOME + '/.nlu/global/settings.json'); export const getPath = (map: NluMap, dep: NluMapItem, opts: any) => { const isAccessible = (p: string) => { const matched = dep.searchRoots.some(r => p.startsWith(r)); if(!matched){ log.error('The following dep', p, 'is not accessible for project at path:', dep.path) } return matched; }; return (packageName: string) => { let path = null; for(let [key,val] of Object.entries(map)){ if(val.name === packageName){ if(val.path !== key){ throw new Error('Key of map should be the name as the path in value object => ' + util.inspect(val)); } if(!isAccessible(val.path)){ continue; } if(path){ throw new Error('Path should only be defined once.'); } path = val.path; } } if(!path && !opts.allow_missing){ log.error(`No package could be located on disk for package name: '${chalk.bold(packageName)}'.`); log.error(`To overcome this problem, either use the ${chalk.bold('--allow-missing')} flag, ` + 'or include the desired package in your searchRoots in .nlu.json.'); process.exit(1); } return path; } }; export const handleConfigCLIOpt = (cwd: string, opts: any) => { const configOpt = String(opts.config || ''); let isFile = null, nluConfigRoot = '', nluFilePath = String(opts.config || ''); if (configOpt) { if(!path.isAbsolute(opts.config)){ nluFilePath = path.resolve(cwd + '/' + String(configOpt || '')); } try { assert(fs.statSync(opts.config).isFile(), 'config path is not a file.'); isFile = true; } catch (err) { isFile = false; nluFilePath = path.resolve(cwd + '/' + String(configOpt || '') + '/.nlu.json'); try{ assert(fs.statSync(opts.config).isFile(), 'config path is not a file.'); } catch(err){ log.error( 'You declared a config path using the -c option, but the following path is not a file:', chalk.bold(opts.config) ); throw chalk.magenta(err.message); } } } if (nluFilePath) { nluConfigRoot = path.resolve(nluFilePath); if(isFile){ nluConfigRoot = path.dirname(nluConfigRoot); } } else { nluConfigRoot = residence.findRootDir(cwd, '.nlu.json'); } if (!nluConfigRoot) { nluConfigRoot = cwd; } if (!nluFilePath) { nluFilePath = path.resolve(nluConfigRoot + '/.nlu.json'); } return {nluFilePath, nluConfigRoot}; }; export const validateConfigFile = (data: NluConf) => { try { const ajv = new Ajv({allErrors: false}); // options can be passed, e.g. {allErrors: true} const validate = ajv.compile(schema); return true; // schema is broken for the moment const valid = validate(data); if (!valid) console.error(validate.errors); return valid; } catch (err) { log.error(err.message); return false; } }; export const getUniqueList = (a: Array<any>): Array<any> => { return Array.from(new Set(a)); }; export const getDepsListFromNluJSON = (nluJSON: NluConf): Array<string> => { let list, deps, packages; try { if ('list' in nluJSON) { assert(Array.isArray(nluJSON.list), `"list" property is not an array => '${util.inspect(nluJSON)}'`); list = nluJSON.list; } if ('deps' in nluJSON) { assert(Array.isArray(nluJSON.deps), `"deps" property is not an array => '${util.inspect(nluJSON)}'`); deps = nluJSON.deps; } if ('packages' in nluJSON) { packages = Object.keys(nluJSON.packages).filter(v => nluJSON.packages[v]); } } catch (err) { log.error('config file was malformed:', nluJSON); throw chalk.magenta(err.message); } return getUniqueList(flattenDeep([list, packages, deps]).filter(Boolean)); }; export const getSearchRootsFromNluConf = (nluJSON: NluConf): Array<string> => { let searchRoots: Array<string | Array<string>> = [nluJSON.searchRoots, nluJSON.searchRoot]; const searchRootsReduced: Array<string> = []; getUniqueList(flattenDeep(searchRoots)) .map(d => String(d || '').trim()) .filter(Boolean) .sort((a, b) => (a.length - b.length)) .filter((v, i, a) => { const s = !a.some(p => { return p.startsWith(v + '/'); }); if (s) { searchRootsReduced.push(v); } }); return searchRootsReduced; }; export const flattenDeep = function (a: Array<any>): Array<any> { return a.reduce((acc, val) => Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []); }; export const getProdKeys = (pkg: PkgJSON) => { return Object.keys(pkg.dependencies || {}); }; export const getDevKeys = (pkg: PkgJSON) => { return Object.keys(pkg.dependencies || {}) .concat(Object.keys(pkg.devDependencies || {})) .concat(Object.keys(pkg.optionalDependencies || {})); }; export const validateOptions = (opts: any) => { try { assert(opts.verbosity >= 1, chalk.magenta('Verbosity must be an integer between 1 and 4, inclusive')); assert(opts.verbosity <= 4, chalk.magenta('Verbosity must be an integer between 1 and 4, inclusive')); } catch (err) { log.error(err.message); return false; } return true; }; export const mapConfigObject = (obj: any) => { return Object.keys(obj).reduce((a, b) => { const key = String(b).replace(/[^a-zA-z]+/g, '_').toLowerCase(); return (a[key] = obj[b], a); }, {} as any); }; const checkPackages = (dep: NluMapItem, m: Map<string, string>, sym: Set<string>): boolean => { const d = dep.package.dependencies || {}; return Object.keys(d).some(v => { const desiredVersion = d[v]; if (sym.has(v)) { // this dep with name v is symlinked return false; } const installedVersion = m.get(v); try { // if(!semver.valid(desiredVersion)){ // log.warn(`The following semver version for package ${v} was not valid:`, desiredVersion); // return false; // } // // if(!semver.valid(installedVersion)){ // log.warn(`The following semver version for package ${v} was not valid:`, installedVersion); // return false; // } if (!/.*[0-9]{1,6}\.[0-9]{1,6}\.[0-9]{1,6}/.test(desiredVersion)) { log.warn('The following package version did not match a semverish regex:', desiredVersion, 'for package:', v); return false; } } catch (err) { log.warn(err.message); return false; } try { // if the installed version does not satisfy the requirement, then we reinstall const satisfies = semver.satisfies(installedVersion, desiredVersion); if (!satisfies) { log.warn('package with name', v, 'is not satisfied. Installed version:', installedVersion, 'desired version:', desiredVersion); } return !satisfies; } catch (err) { log.warn(err.message); return false; } }); }; export const determineIfReinstallIsNeeded = (nodeModulesPath: string, dep: NluMapItem, depsKeys: Array<string>, opts: NLURunOpts, cb: EVCb<boolean>) => { const map = new Map<string, string>(); const sym = new Set<string>(); const result = { install: false }; if (opts.no_install) { return process.nextTick(cb); } fs.readdir(nodeModulesPath, (err, originalItemsInNodeModules) => { if (err || !Array.isArray(originalItemsInNodeModules)) { // if there is an error, node_modules probably does not exist opts.verbosity > 1 && log.warn('Reinstalling because node_modules dir does not seem to exist in dir: ', nodeModulesPath); return cb(null, true); } const orgItems = originalItemsInNodeModules.filter(v => { return String(v).startsWith('@'); }); const topLevel = originalItemsInNodeModules.filter(v => { return !String(v).startsWith('@') && String(v) !== '.bin'; }); const totalValid = new Set(topLevel.slice(0)); const processFolder = (name: string, folder: string, cb: EVCb<null>) => { totalValid.add(name); async.autoInject({ stat(cb: EVCb<null>) { fs.lstat(folder, (err, stats) => { if (err) { result.install = true; return cb(err); } if (stats.isSymbolicLink()) { sym.add(name); } cb(null); }); }, package(cb: EVCb<null>) { const packageJSON = path.resolve(folder + '/package.json'); fs.readFile(packageJSON, (err, data) => { if (err) { result.install = true; return cb(err); } try { const version = JSON.parse(String(data)).version; assert(version && typeof version === 'string', 'version is not defined, or not a string.'); map.set(name, version); } catch (err) { result.install = true; return cb(err); } cb(null); }); } }, cb); }; async.autoInject({ topLevel(cb: EVCb<null>) { async.eachLimit(topLevel, 3, (item, cb) => { const folder = path.resolve(nodeModulesPath + '/' + item); processFolder(item, folder, cb); }, cb); }, orgLevel(cb: EVCb<null>) { async.eachLimit(orgItems, 3, (item, cb) => { const p = path.resolve(nodeModulesPath + '/' + item); fs.readdir(p, (err, orgtems) => { if (err) { result.install = true; return cb(err); } if (orgtems.length < 1) { return process.nextTick(cb); } async.eachLimit(orgtems, 5, (v, cb) => { const name = item + '/' + v; const folder = path.resolve(p + '/' + v); processFolder(name, folder, cb); }, cb); }); }, cb); } }, (err) => { if (err && result.install === true) { return cb(null, true); } if (err) { return cb(err, false); } // // * this method was not accurate in determining whether a reinstall was needed, so it's commented out * // // if (originalItemsInNodeModules.length <= depsKeys.length) { // // if there number of folders in node_modules is less than deps count, we def need to reinstall // opts.verbosity > 1 && log.warn('Reinstalling because node_modules dir does not have enough folders: ', nodeModulesPath); // opts.verbosity > 1 && log.warn(); // return cb(null, true); // } const allThere = depsKeys.every(d => { if (!totalValid.has(d)) { opts.verbosity > 1 && log.info('The following dep in package.json', d, 'did not appear to be in node_modules located here:', nodeModulesPath); return false } return true; }); if (!allThere) { // if not all deps in package.json are folders in node_modules, we need to reinstall opts.verbosity > 1 && log.warn('Reinstalling because not all package.json dependencies exist in node_modules:', nodeModulesPath); return cb(null, true); } if (checkPackages(dep, map, sym)) { return cb(null, true); } cb(null, false); }); }); };
the_stack
import { Block, BlockCompiler, BlockDefinitionCompiler, BlockFactorySync, Configuration, INLINE_DEFINITION_FILE, resolveConfiguration } from "@css-blocks/core"; import { BroccoliTreeImporter, CSSBlocksEmberOptions, EmberAnalysis, identToPath, isBroccoliTreeIdentifier } from "@css-blocks/ember-utils"; import type { ASTPluginEnvironment } from "@glimmer/syntax"; import { MultiMap } from "@opticss/util"; import type { InputNode } from "broccoli-node-api"; import outputWrapper = require("broccoli-output-wrapper"); import md5Sum = require("broccoli-persistent-filter/lib/md5-hex"); import persistentStrategy = require("broccoli-persistent-filter/lib/strategies/persistent"); import debugGenerator from "debug"; import TemplateCompilerPlugin = require("ember-cli-htmlbars/lib/template-compiler-plugin"); import FSMerger = require("fs-merger"); import type { FS as MergedFileSystem } from "fs-merger"; import * as FSTree from "fs-tree-diff"; import { postcss } from "opticss"; import * as path from "path"; import { AnalyzingRewriteManager } from "./AnalyzingRewriteManager"; import { BroccoliFileLocator } from "./BroccoliFileLocator"; import { ASTPluginWithDeps } from "./TemplateAnalyzingRewriter"; type PersistentStrategy = typeof persistentStrategy; interface AdditionalFile { outputPath: string; contents: string; } export const BLOCK_GLOB = "**/*.block.{css,scss,sass,less,styl}"; export const COMPILED_BLOCK_GLOB = "**/*.compiledblock.css"; const debug = debugGenerator("css-blocks:ember"); export interface EmberASTPluginEnvironment extends ASTPluginEnvironment { meta?: { moduleName?: string; }; } /** * This class extends ember-cli-htmlbars's template compiler (which is built on * top of broccoli-persistent-filter). In the ember-cli addon for this package * we monkey patch ember-cli-htmlbars' ember-cli addon to return an instance of * this class instead. * * The reason we must extend the template compiler is so that we can write * and manage the cache for the additional output files that are associated with * each template. We produce compiled css-blocks files for the parent as well * as template analysis metadata for each template. * * For each template that uses CSS Blocks we create a cache entry that contains * the cache keys for each additional file that is output with the template. * the cached data for each additional file includes the output path as well as * the contents for that file. * * Note: It is possible for several templates to depend on the same CSS Block * file and so their caches will point to the same additional file cache * entries. This produces a little extra work when the cache is warm but * ensures consistency if one of the templates is removed. * * In the case where just one of the templates is invalidated, the css block file * will get recompiled after it is retrieved from cache, but this is ok because * the output from css-blocks will be identical. */ export class CSSBlocksTemplateCompilerPlugin extends TemplateCompilerPlugin { previousSourceTree: FSTree; cssBlocksOptions: CSSBlocksEmberOptions; parserOpts: Readonly<Configuration>; rewriteManager: AnalyzingRewriteManager | undefined; input!: FSMerger.FS; output!: outputWrapper.FSOutput; persist: boolean; treeName: string; debug: debugGenerator.Debugger; isCssBlocksTemplateCompiler: true; constructor(inputTree: InputNode, treeName: string, htmlbarsOptions: TemplateCompilerPlugin.HtmlBarsOptions, cssBlocksOptions: CSSBlocksEmberOptions) { super(inputTree, htmlbarsOptions); this.isCssBlocksTemplateCompiler = true; this.cssBlocksOptions = cssBlocksOptions; this.parserOpts = resolveConfiguration(cssBlocksOptions.parserOpts); this.previousSourceTree = new FSTree(); this.treeName = treeName; let persist = htmlbarsOptions.persist; if (persist === undefined) persist = true; this.persist = TemplateCompilerPlugin.shouldPersist(process.env, persist); this.debug = debug.extend(treeName); } astPluginBuilder(env: EmberASTPluginEnvironment): ASTPluginWithDeps { let moduleName = env.meta?.["moduleName"]; if (!moduleName) { this.debug("No module name. Returning noop ast plugin"); return { name: "css-blocks-noop", visitor: {}, }; } this.debug(`Returning template analyzer and rewriter for ${moduleName}`); if (!this.rewriteManager) { throw new Error("[internal error] analyzing rewriter expected."); } // The analyzing rewriter gets swapped out at the beginning of build() with // a new instance. that instance tracks all the analyses that are produced // for each ast plugin that is created for each template once super.build() // is done, the analyses for all of the templates is complete and we can // write additional output files to the output tree. return this.rewriteManager.templateAnalyzerAndRewriter(moduleName, env.syntax); } async build() { let cssBlockEntries = this.input.entries(".", {globs: [BLOCK_GLOB]}); let currentFSTree = FSTree.fromEntries(cssBlockEntries); let patch = this.previousSourceTree.calculatePatch(currentFSTree); let removedFiles = patch.filter((change) => change[0] === "unlink"); this.previousSourceTree = currentFSTree; if (removedFiles.length > 0) { console.warn(`[WARN] ${removedFiles[0][1]} was just removed and the output directory was not cleaned up.`); } let namespace = md5Sum(this.treeName).slice(0, 3); let importer = new BroccoliTreeImporter(this.input, namespace, this.parserOpts.importer); let config = resolveConfiguration({importer}, this.parserOpts); let factory = new BlockFactorySync(config, postcss); let fileLocator = new BroccoliFileLocator(this.input); this.rewriteManager = new AnalyzingRewriteManager(factory, fileLocator, this.cssBlocksOptions.analysisOpts || {}, config); // Compiles the handlebars files, runs our plugin for each file // we have to wrap this RSVP Promise that's returned in a native promise or // else await won't work. await nativePromise(() => super.build()); this.debug(`Template rewriting complete.`); let blocks = new Set<Block>(); // these blocks must be compiled let blockOutputPaths = new Map<Block, string>(); // this mapping is needed by the template analysis serializer. let analyses = new Array<EmberAnalysis>(); // Analyses to serialize. let templateBlocks = new MultiMap<EmberAnalysis, Block>(); // Tracks the blocks associated with each template (there's a 1-1 relationship beteen analyses and templates). let additionalFileCacheKeys = new MultiMap<EmberAnalysis, string>(); // tracks the cache keys we create for each additional output file. // first pass discovers the set of all blocks & associate them to their corresponding analyses. for (let analyzedTemplate of this.rewriteManager.analyzedTemplates()) { let { analysis } = analyzedTemplate; analyses.push(analysis); for (let block of analysis.transitiveBlockDependencies()) { blocks.add(block); templateBlocks.set(analysis, block); } } this.debug(`Analyzed ${analyses.length} templates.`); this.debug(`Discovered ${blocks.size} blocks in use.`); // we have to pre-compute the paths of all the local blocks so that we can // rewrite the path in the compiled output of the definition file. for (let block of blocks) { let outputPath = getOutputPath(this.input, block); if (outputPath) blockOutputPaths.set(block, outputPath); } await this.buildCompiledBlocks(blocks, config, blockOutputPaths, additionalFileCacheKeys, templateBlocks); await this.buildSerializedAnalyses(analyses, blockOutputPaths, additionalFileCacheKeys); if (this.persist) { for (let analysis of additionalFileCacheKeys.keys()) { let cacheKey = this.additionalFilesCacheKey(this.inputFileCacheKey(analysis.template.relativePath)); let additionalCacheKeys = additionalFileCacheKeys.get(analysis); await (<PersistentStrategy>this.processor.processor)._cache?.set(cacheKey, JSON.stringify(additionalCacheKeys)); this.debug(`Stored ${additionalCacheKeys.length} additional output files for ${analysis.template.relativePath} to cache.`); this.debug(`Cache keys are: ${additionalCacheKeys.join(", ")}`); } } } async buildCompiledBlocks( blocks: Set<Block>, config: Readonly<Configuration>, blockOutputPaths: Map<Block, string>, additionalFileCacheKeys: MultiMap<EmberAnalysis, string>, templateBlocks: MultiMap<EmberAnalysis, Block>, ): Promise<void> { let compiler = new BlockCompiler(postcss, this.parserOpts); compiler.setDefinitionCompiler(new BlockDefinitionCompiler( postcss, (b, p) => { let basePath = blockOutputPaths.get(b)!; let referencedBlock: Block = b.blockReferencePaths.get(p)!; let toPath = blockOutputPaths.get(referencedBlock); if (!toPath) return p; // block is not part of this tree, keep the import as-is. let relativePath = path.relative(path.dirname(basePath), toPath); if (!relativePath.startsWith(".")) { relativePath = `./${relativePath}`; } debug("Constructing block import. %s => %s becomes %s", basePath, toPath, relativePath); return relativePath; }, this.parserOpts)); for (let block of blocks) { this.debug(`compiling: ${config.importer.debugIdentifier(block.identifier, config)}`); let outputPath = blockOutputPaths.get(block); // Skip processing if we don't get an output path. This happens for files that // get referenced in @block from node_modules. if (!outputPath) { continue; } if (!block.stylesheet) { throw new Error("[internal error] block stylesheet expected."); } // TODO - allow for inline definitions or files, by user option let { css: compiledAST } = compiler.compileWithDefinition(block, block.stylesheet, this.rewriteManager!.reservedClassNames(), INLINE_DEFINITION_FILE); // TODO disable source maps in production? let result = compiledAST.toResult({ to: outputPath, map: { inline: true } }); let contents = result.css; if (this.persist) { // We only compile and output each block once, but a block might be consumed // by several of the templates that we have processed. So we have to figure out // which template(s) depend on the block we're writing. for (let {analysis} of this.rewriteManager!.analyzedTemplates()) { if (templateBlocks.hasValue(analysis, block)) { await this.cacheAdditionalFile(additionalFileCacheKeys, analysis, {outputPath, contents}); } } } this.output.writeFileSync(outputPath, contents, "utf8"); this.debug(`compiled: ${outputPath}`); } } async buildSerializedAnalyses( analyses: Array<EmberAnalysis>, blockOutputPaths: Map<Block, string>, additionalFileCacheKeys: MultiMap<EmberAnalysis, string>, ): Promise<void> { for (let analysis of analyses) { let outputPath = analysisPath(analysis.template.relativePath); let contents = JSON.stringify(analysis.serializeSource(blockOutputPaths)); await this.cacheAdditionalFile(additionalFileCacheKeys, analysis, {outputPath, contents}); this.output.mkdirSync(path.dirname(outputPath), { recursive: true }); this.output.writeFileSync( outputPath, contents, "utf8", ); this.debug(`Analyzed ${analysis.template.relativePath} => ${outputPath}`); } } inputFileCacheKey(relativePath): string { // it would be nice if we could avoid this double read. let contents = this.input.readFileSync(relativePath, this.inputEncoding || "utf8"); return this.cacheKeyProcessString(contents, relativePath); } additionalFilesCacheKey(mainFileCacheKey: string): string { return `${mainFileCacheKey}-additional-files`; } async cacheAdditionalFile(additionalFileCacheKeys: MultiMap<EmberAnalysis, string>, analysis: EmberAnalysis, additionalFile: AdditionalFile) { if (this.persist) { let cacheKey = md5Sum([additionalFile.outputPath, additionalFile.contents]); additionalFileCacheKeys.set(analysis, cacheKey); await (<PersistentStrategy>this.processor.processor)._cache!.set(cacheKey, JSON.stringify(additionalFile)); this.debug(`Wrote cache key ${cacheKey} for ${additionalFile.outputPath}`); } } // We override broccoli-persistent-filter's _handleFile implementation // in order to extract the additional output files from cache when the file is cached. // ideally this would be a capability provided by broccoli-persistent-filter, because // in those cases, it would be able to recover from a missing cache entry correctly. async _handleFile(relativePath: string, srcDir: string, destDir: string, entry: Parameters<TemplateCompilerPlugin["_handleFile"]>[3], outputPath: string, forceInvalidation: boolean, isChange: boolean, stats: Parameters<TemplateCompilerPlugin["_handleFile"]>[7]) { let cached = false; let mainFileCacheKey: string | undefined; if (this.persist) { // check if the persistent cache is warm for the main file being handled. mainFileCacheKey = this.inputFileCacheKey(relativePath); let result = await (<PersistentStrategy>this.processor.processor)._cache!.get(mainFileCacheKey); cached = result.isCached; } let additionalFiles = new Array<AdditionalFile>(); let consistentCache = true; if (cached && !forceInvalidation) { // first we read the list of additional cache keys for other output files. let additionalFilesCacheKey = this.additionalFilesCacheKey(mainFileCacheKey!); let cacheKeysCacheResult = await (<PersistentStrategy>this.processor.processor)._cache!.get<string>(additionalFilesCacheKey); if (cacheKeysCacheResult.isCached) { let additionalCacheKeys: Array<string> = JSON.parse(cacheKeysCacheResult.value); // for each cache key we read out the additional file metadata that is cached and write the additional files to the output tree. for (let cacheKey of additionalCacheKeys) { let additionalFileCacheResult = await (<PersistentStrategy>this.processor.processor)._cache!.get<string>(cacheKey); if (!additionalFileCacheResult.isCached) { this.debug(`The cache is inconsistent (missing: ${cacheKey}). Force invalidating the template.`); forceInvalidation = true; consistentCache = false; } additionalFiles.push(JSON.parse(additionalFileCacheResult.value)); } this.debug(`Wrote ${additionalCacheKeys.length} additional cached files for ${relativePath}`); } else { // this happens when the file isn't a css-blocks based template. this.debug(`No additional cached files for ${relativePath}`); } } let result = await super._handleFile(relativePath, srcDir, destDir, entry, outputPath, forceInvalidation, isChange, stats); if (cached && consistentCache) { for (let additionalFile of additionalFiles) { this.output.mkdirSync(path.dirname(additionalFile.outputPath), { recursive: true }); this.output.writeFileSync(additionalFile.outputPath, additionalFile.contents, this.outputEncoding || "utf8"); } } return result; } } function analysisPath(templatePath: string): string { let analysisPath = path.parse(templatePath); delete analysisPath.base; analysisPath.ext = ".block-analysis.json"; return path.format(analysisPath); } function getOutputPath(input: MergedFileSystem, block: Block): string | null { if (isBroccoliTreeIdentifier(block.identifier)) { let blockPath = identToPath(input, block.identifier); let parsed = path.parse(blockPath); delete parsed.base; parsed.ext = ".css"; parsed.name = parsed.name.replace(".block", ".compiledblock"); return path.format(parsed); } else { return null; } } function nativePromise(work: () => void | PromiseLike<void>): Promise<void> { return new Promise((resolve, reject) => { try { let buildResult = work() || Promise.resolve(); buildResult.then(resolve, reject); } catch (e) { reject(e); } }); }
the_stack
import {VideoJsPlayerOptions} from "video.js"; import {Configuration, Transformation, Cloudinary} from "cloudinary-core" declare module 'cloudinary-core' { interface Cloudinary { /** * * @param elem * The video element for the player * @param options * Video player options * @param ready * Is the player ready to play */ videoPlayer(elem: string, options?: Options, ready?: boolean): VideoPlayer; /** * create video players from a css class class selector * @param {string} selector * Class name * @param ...args * arguments to pass to the video player constructor * @return {Array.VideoPlayer} * An array of video player objects */ videoPlayers(selector: string, ...args: any): VideoPlayer[]; } } export interface PosterOptions { /** * @param The public id of the poster */ publicId: string, /** * @param Cloudinary transformations to apply to the poster */ transformation: Transformation[] } /** @typedef {Object} json * @property {Object} ads * Enables serving ads in your video player based on leading video ad standards such as VAST, VPAID, and VMAP, including Google DoubleClick or AdSense. * @property {Boolean} allowUsageReport * Cloudinary can optionally collect aggregated statistics about how the video player is being used. * The collected data is used in aggregate form to help us improve future versions of the video player and cannot be used to identify individual video viewers. * When true (default), Cloudinary collects data on events performed by the video player * @property {Boolean} analytics * Whether to activate analytics for video player events. Default: false * @property {Boolean} autoplay * Whether to apply standard HTML5 autoplay. Default: false. * @property {String|Boolean} bigPlayButton * Whether to show a larger play button. * Possible values: * true: Always show big play button. * false: Never show big play button. * init: Show big play button on initial load only. * Default: false * @property {Object} colors * The colors to use for the player UI. The values must be supplied as hex color codes. You can set: * base: The base color for the player's controls and information bars as well as the base color of the central play button. * accent: The color for the progress bar and volume level. * text: The color for all text and icons. * @property {Boolean} controls * Whether to display the video player controls * @property {Object} floatingWhenNotVisible * Whether to display a floating player in the corner of the screen when a video is playing and less than half the player is visible. * Possible values: * right: Shows floating player in the bottom right of the screen * left: Shows floating player in the bottom left of the screen * @property {Boolean} fluid * Whether to activate fluid layout mode, which dynamically adjusts the player size to fit its container or window. * @property {String} fontFace * The font to use for text elements in the video player. If not specified, the player loads with the default player font-family: Fira Sans. * @property {Boolean} hideContextMenu * Whether to hide the context menu that appears when right-clicking on the player. Default: false * @property {String} logoImageUrl * The URL for the logo image to display in the player's control bar. Relevant only when showLogo is true. Default: Cloudinary logo. * @property {String} logoOnclickUrl * The URL where the viewer will be sent when clicking the logo in the player control bar. Relevant only when showLogo is true. Default: https://cloudinary.com * @property {Array} playbackRates * An array of playback rates to display in the control bar. Allows the user to change the speed that the video plays at. * @property {Object} playlistWidget * Adds a playlist widget to the video player. * @property {String} poster * The publicId from the poster image * @property {Object} posterOptions * A default poster that is shown every time a new video loads. It can include transformation settings * @property {Boolean} showLogo * Whether to show a clickable logo within the player. You can customize the logo image (logoImageUrl) and logo url (logoOnclickUrl) for your own requirements. Default: true * @property {String} transformation * Default transformation to apply on every source video that plays in the player * @property {Object} videoJS * Access all underlying capabilities of the VideoJS API */ export interface Options { bigPlayButton?: boolean | string, colors?: { base: string, accent: string, text: string }, controls?: boolean, floatingWhenNotVisible?: string, fluid?: boolean, autoplay?: boolean, fontFace?: string | boolean, hideContextMenu?: boolean, playbackRates?: string[], playlistWidget?: { direction?: string, total?: number, }, poster?: string, posterOptions?: PosterOptions, showLogo?: boolean, logoImageUrl?: string, logoOnclickUrl?: string, transformation?: Transformation[], ads?: AdsOptions, analytics?: boolean, allowUsageReport?: boolean, videojs?: VideoJsPlayerOptions; } /** * Video Source options * @param preload [options.preload] * The type of standard HTML5 video preloading to use. Relevant only when autoplay is false or autoplayMode is never. * Possible values: * auto: Default. Begin loading the video immediately. * metadata: Only load the video metadata. * none: Don't load any video data. * @param publicId [options.publicId] * The Cloudinary Public ID of the video source to use when the player loads. * @param sourceTransformation [options.sourceTransformation] * Default transformations to apply to a specific source type. * @param sourceTypes [options.sourceTypes] * The video source types (and optionally the corresponding codecs) that will be available for the player to request (as appropriate for the current browser). If a source type can't be played in the requesting browser, the next source in the array will be tried. Add the codec after the source type and separate with a '/', for example: mp4/h265. * For HLS and MPEG-DASH, use the values hls and dash respectively and optionally specify a codec as described above. * For audio only, use audio. * If you also define a codec as part of a transformation, this will override the source type. * Default: ['webm/vp9','mp4/h265','mp4']. * The default is configured to be the most optimal combination of source types for modern browsers. */ export interface SourceOptions { preload?: string, publicId?: string, sourceTransformation?: Transformation[], sourceTypes?: string[], } /** @typedef {Object} json * @property {String} adLabel * Optional. Alternative or translated text for the 'Advertisement' countdown label. Relevant only when showCountdown is true. * @property {String} adTagUrl * The full URL of the adTag to run * @property {String} adsInPlaylist * string value setting when to call the adTag * first-video: Calls the adTag on the first video in the playlist only. * every-video: Calls the adTag on every video in the playlist. * default first-video * @property {String} locale * Optional. Locale for ad localization. Can be any ISO 639-1 (two-letter) or ISO 639-2,(three-letter) locale code. * This setting affects the language of relevant elements within the adTag, such as the Skip option. Default: en. * @property {Number} postrollTimeout * Optional. Maximum time (in milliseconds) to wait for a postroll ad to start. * If the ad does not start an adtimeout event is triggered. * @property {Number} prerollTimeout * Optional. Maximum time (in milliseconds) to wait for a preroll ad to start. * If the ad does not start an adtimeout event is triggered. * @property {Boolean} showCountdown * Optional. When true, the 'Advertisement' countdown label is displayed in small text in the bottom center of the video player * along with a counter showing the time (in seconds) until the end of the video. Default: true. */ export interface AdsOptions { adTagUrl: string, adsInPlaylist?: string, showCountdown?: boolean, adLabel?: string locale?: string, prerollTimeout?: number postrollTimeout?: number } export class BaseSource { constructor(publicId: any, options?: {}); publicId: (publicId: string) => BaseSource; cloudinaryConfig: (config: {}) => BaseSource; resourceConfig: (config: any) => BaseSource; transformation: (trans: any) => BaseSource; queryParams: (params: any) => BaseSource; getType: () => string; config(): any; url({transformation}?: { transformation: any; }): string; } export interface imaAdPlayer { playAd: (adTad: string) => void; } export class VideoSource { constructor(publicId: any, options?: {}); _type: string; poster: (publicId: string, options?: {}) => VideoSource; sourceTypes: (types: Array<string>) => VideoSource; sourceTransformation: (trans: any) => VideoSource; info: (info: {}) => VideoSource; recommendations: (recommends: any) => VideoSource; objectId: number; } export class ImageSource { constructor(publicId: string, options?: {}); _type: string; } export class Playlist { constructor(context: CloudinaryContext, sources?: VideoSource|string[], { repeat, autoAdvance, presentUpcoming }?: { repeat?: boolean; autoAdvance?: boolean; presentUpcoming?: boolean; }); enqueue: (source: VideoSource|string, options?: {}) => VideoSource; currentIndex: (index: number) => number; presentUpcoming: (delay: number) => number; autoAdvance: (delay: number) => number; list: () => VideoSource[]; player: () => VideoPlayer; dispose: () => void; resetState: () => void; playItem(item: VideoSource): VideoSource; playAtIndex(index: number): VideoSource; currentSource(): VideoSource; removeAt(index: number): Playlist; repeat(repeat: any): boolean; first(): VideoSource; last(): VideoSource; next(): VideoSource; nextIndex(index: VideoSource): number; previousIndex(): number; playFirst(): VideoSource; playLast(): VideoSource; isLast(): boolean; isFirst(): boolean; length(): number; playNext(): VideoSource; playPrevious(): VideoSource; } export class CloudinaryContext { constructor(player: VideoPlayer, options?: Options); player: VideoPlayer; source: (source: VideoSource, options?: SourceOptions) => VideoPlayer; buildSource: (publicId: string|SourceOptions, options?: SourceOptions) => VideoPlayer; posterOptions: (options: PosterOptions) => VideoPlayer; cloudinaryConfig: (config: Configuration) => VideoPlayer; transformation: (trans: Transformation[]) => VideoPlayer; sourceTypes: (types: string[],) => VideoPlayer; getCurrentSources: () => VideoSource[]; sourceTransformation: (trans: Transformation[]) => VideoPlayer; on: (...args: any[]) => any; one: (...args: any[]) => any; off: (...args: any[]) => any; autoShowRecommendations: (autoShow: any) => boolean; dispose: () => void; currentSourceType(): string; currentPublicId(): string; currentPoster(): ImageSource; } export default class VideoPlayer { /** * * @param elem * The video element for the player * @param options * Video player options * @param ready * Is the player ready to play */ constructor(elem: string, options: Options, ready: boolean) /** * * @param config * The cloudinary core configurations * @return {Object} VideoPlayer class */ cloudinaryConfig(config: Configuration.Options): VideoPlayer; /** * @return {String} The current video publicId * */ currentPublicId(): string; /** * @return {String} The current video url */ currentSourceUrl(): string; /** * @return {Object} An ImageSource object of the video poster */ currentPoster(): ImageSource; /** * * @param {String} publicId * The publicId from the video source * @param {Object} options * The source configuration * @return {Object} A video source object */ source(publicId: string, options: SourceOptions): VideoSource; /** * * @param {Object} options * The Configuration for the poster * @return {Object} The VideoPlayer object */ posterOptions(options: PosterOptions): VideoPlayer; /** * * @param {String} name * The name of the skin to apply to the video player * @return {string} * the class prefix of the skin */ skin(name: string): string; /** * Create a playlist * @param {Array.<Object>} sources * A list of sources for the playlist * * @param {Object} options * Options from the playlist sources the options would be added to each source * @return {Object} The video player */ playlist(sources: SourceOptions[], options: SourceOptions): VideoPlayer; /** * Create a playlist from a cloudinary tag * @param {String} tag * The tag name to build the playlist from * @param {Object} options * Options from the playlist sources the options would be added to each source * @return {Object} The video player */ playlistByTag(tag: string, options: SourceOptions): VideoPlayer; /** * Get an Array ot sources from a cloudinary tag * @param {String} tag * The tag name to get the sources by * @param {Object} options * Options to apply to all sources * @return An array of sources */ sourcesByTag(tag: string, options: {}): VideoSource[]; /** * Should the player be responsive * @param {boolean} bool * @return */ fluid(bool: boolean): boolean | undefined | VideoPlayer; /** * Play the video * @return {Object} the video player */ play(): VideoPlayer; /** * Stop the video * @return {Object} the video player */ stop(): VideoPlayer; /** * In a playlist play the previous video * @return {Object} the video player */ playPrevious(): VideoPlayer; /** * * In a playlist play the next video * @return {Object} the video player */ playNext(): VideoPlayer; /** * Apply transformations to the video * @param {Array.Transformation} trans * An array of transformations to apply * @return {Object} the video player */ transformation(trans: Transformation[]): VideoPlayer; /** * Set the source types for the video * @param {array} types * The array of types * @return {Object} the video player */ sourceTypes(types: string[]): VideoPlayer; /** * * Apply transformations to this source * @param {Array.Transformation} trans * An array of transformations to apply * @return {Object} the video player */ sourceTransformation(trans: Transformation[]): VideoPlayer; /** * get or set would auto recommendation be shown * * @param {boolean} autoShow * @return {Object} the video player */ autoShowRecommendations(autoShow?: boolean): VideoPlayer; /** * Get the video duration * @return {number} the video duration */ duration(): number; /** * Set the player height * @param {number} dimension * The height in pixels * @return {Object} the video player */ height(dimension: number): VideoPlayer; /** * Set the width of the player * @param {number} dimension * The width in pixels * @return {Object} the video player */ width(dimension: number): VideoPlayer; /** * Set the player volume * @param {number} volume * Volume to apply * @return {Object} the video player */ volume(volume: number): VideoPlayer; /** * Mute the video * @return {Object} the video player */ mute(): VideoPlayer; /** * Unmute the player * @return {Object} the video player */ unmute(): VideoPlayer; /** * Is the player muted * @return {boolean} * true if the player is muted */ isMuted(): boolean; /** * Pause the video * @return {Object} the video player */ pause(): VideoPlayer; /** * Set or get the current video time * @param {number} offsetSeconds * optional if given the video would seek to that time * if non is given would return the current video time * @return {object} the video player */ currentTime(offsetSeconds?: number): VideoPlayer|number; /** * Enter fullscreen mode * @return {object} The video player */ maximize(): VideoPlayer; /** * Exit full screen mode * @return {object} The video player */ exitMaximize(): VideoPlayer; /** * Is the video player is in fullscreen mode * @return {boolean} */ isMaximized(): boolean; /** * Delete the current video player */ dispose(): void; /** * Get or set would the controls be shown * @param {boolean} bool * if given true to show the controls false to hide * if non is given returns the current control status * @return {object|Boolean} * if the an options is given would return the video player * if not the boolean with the current state */ controls(bool?: boolean): VideoPlayer; /** * Get the interface to play ads * @return {object} interface to play ads */ ima(): imaAdPlayer; /** * get or set if the video should automatically restart * @param {boolean} bool * true to auto restart false not to * @return {object|Boolean} * if the an options is given would return the video player * if not the boolean with the current state */ loop(bool?: boolean): VideoPlayer|boolean; /** * Proxy method for videojs el */ el(): Element; /** * create video players from a css class class selector * @param {string} selector * Class name * @param ...args * arguments to pass to the video player constructor * @return {Array.VideoPlayer} * An array of video player objects */ static all(selector: string, ...args: any): VideoPlayer[]; }
the_stack
import type { UnmatchedResult } from '..'; import type { Expect, Result, List } from '../types'; import { matched, unmatched } from '../match-result'; import { Token } from './token'; type TokenCollectionOptions = Partial< Omit<List, 'token'> & { speificSeparator: string | string[]; } >; export type TokenEachCheck = (head: Token | null, tail: TokenCollection) => Result | void; export class TokenCollection extends Array<Token> { private static _new(tokens: Token[], old?: TokenCollection) { const newCollection = new TokenCollection('', old); newCollection.push(...tokens); return newCollection; } static fromPatterns( value: Token | string, patterns: RegExp[], typeOptions?: Omit<TokenCollectionOptions, 'speificSeparator'> & { repeat?: boolean }, ) { const origin = typeof value === 'string' ? value : value.origin; let strings = typeof value === 'string' ? value : value.value; let cumulativeOffset = typeof value === 'string' ? 0 : value.offset; const tokens: Token[] = []; function addToken(tokenValue: string) { const token = new Token(tokenValue, cumulativeOffset, origin); tokens.push(token); strings = strings.slice(tokenValue.length); cumulativeOffset += tokenValue.length; return token; } let isBreaked = false; do { isBreaked = false; for (const pattern of patterns) { const res = pattern.exec(strings); let value: string; if (!res) { isBreaked = true; value = ''; } else { if (res.index !== 0) { value = strings.slice(res.index + res[0].length); } else { value = res[0] || ''; } } const token = addToken(value); // @ts-ignore token._ = pattern; } if (isBreaked) { addToken(strings); } } while (typeOptions?.repeat && strings); if (strings) { addToken(strings); } return TokenCollection._new(tokens, new TokenCollection('', typeOptions)); } static get [Symbol.species]() { return Array; } readonly disallowToSurroundBySpaces: NonNullable<List['disallowToSurroundBySpaces']>; readonly allowEmpty: NonNullable<List['allowEmpty']>; readonly ordered: NonNullable<List['ordered']>; readonly unique: NonNullable<List['unique']>; readonly caseInsensitive: NonNullable<List['caseInsensitive']>; readonly number: List['number']; readonly separator: NonNullable<List['separator']>; constructor(value?: string, typeOptions?: TokenCollectionOptions); constructor(value?: number); // for map method etc. constructor(value?: string | number, typeOptions?: TokenCollectionOptions) { super(); this.disallowToSurroundBySpaces = typeOptions?.disallowToSurroundBySpaces || false; this.allowEmpty = typeOptions?.allowEmpty || true; this.ordered = typeOptions?.ordered || false; this.unique = typeOptions?.unique || false; this.caseInsensitive = typeOptions?.caseInsensitive || true; this.number = typeOptions?.number; this.separator = typeOptions?.separator || 'space'; if (typeof value === 'number') { this.length = value; return; } if (!value) { return; } const separators: string[] = []; if (this.separator === 'comma') { separators.push(','); } if (typeOptions?.speificSeparator) { if (Array.isArray(typeOptions.speificSeparator)) { separators.push(...typeOptions.speificSeparator); } else { separators.push(typeOptions.speificSeparator); } } const chars = value.split(''); const values: string[] = []; let char: string | undefined; while ((char = chars.shift())) { const last = values.pop(); if (!last) { values.push(char); continue; } const lastChar = last[0]; if ( !separators.includes(char) && !separators.includes(last[0]) && ((Token.whitespace.includes(lastChar) && Token.whitespace.includes(char)) || (!Token.whitespace.includes(lastChar) && !Token.whitespace.includes(char))) ) { values.push(last + char); } else { values.push(last); values.push(char); } } let offset = 0; values.forEach(v => { const token = new Token(v, offset, value, separators); this.push(token); offset += v.length; }); } get value() { const value = this.map(t => t.value).join(''); return value; } filter(callback: (value: Token, index: number, array: Token[]) => boolean) { return TokenCollection._new(super.filter(callback), this); } headAndTail(): { head: Token | null; tail: TokenCollection } { const copy = this.slice(); const head = copy.shift(); if (!head) { return { head: head || null, tail: TokenCollection._new([], this) }; } const tail = TokenCollection._new(copy, this); return { head, tail }; } getIdentTokens() { return this.filter(token => token.type === Token.Ident); } compareTokens(callback: (prev: Token, current: Token) => Token | null | void) { const _tokens = this.slice(); let prev = _tokens.shift(); while (prev) { const current = _tokens.shift(); if (!current) { return; } const result = callback(prev, current); if (result) { return result; } prev = current; } return null; } /** * * @param value The token value or the token type or its list */ has(value: string | RegExp | number | (string | RegExp | number)[]) { return this.some(t => t.match(value)); } /** * * @param value The token value or the token type or its list */ search(value: string | RegExp | number | (string | RegExp | number)[]) { for (const token of this) { if (token.includes(value)) { return token; } } return null; } check(options: { expects?: Expect[]; ref?: string; cache?: boolean } = {}) { const { expects, ref } = options; if (this.disallowToSurroundBySpaces) { for (const token of this) { if (token.type === 13) { return token.unmatched({ reason: 'unexpected-space', ref, expects, }); } } } if (this.separator === 'comma') { const tokensWithoutWP = this.filter(token => token.type !== Token.WhiteSpace); const consecutiveComma = tokensWithoutWP.getConsecutiveToken(Token.Comma); if (consecutiveComma) { return consecutiveComma.unmatched({ reason: 'unexpected-comma', ref, expects, }); } if (tokensWithoutWP[0] && tokensWithoutWP[0].type === Token.Comma) { return tokensWithoutWP[0].unmatched({ reason: 'unexpected-comma', ref, expects, }); } const takeTurnsError = tokensWithoutWP.takeTurns([Token.Ident, Token.Comma], Token.Ident); if (takeTurnsError) { if (takeTurnsError.unexpectedLastToken) { return takeTurnsError.token.unmatched({ reason: 'extra-token', ref, expects, }); } else if (takeTurnsError.token.type === takeTurnsError.expectedTokenNumber) { // Consecutive cammas return takeTurnsError.token.unmatched({ reason: 'unexpected-comma', ref, expects, }); } return takeTurnsError.token.unmatched({ reason: 'missing-comma', ref, expects, candicate: `,${takeTurnsError.token.value}`, }); } } const identTokens = this.getIdentTokens(); const allowEmpty = this.allowEmpty ?? true; if (!allowEmpty && identTokens.length === 0) { return unmatched(this.value, 'empty-token', { ref, expects, }); } if (this.unique) { const duplicated = identTokens.getDuplicated(); if (duplicated) { return duplicated.unmatched({ partName: 'the content of the list', reason: 'duplicated', ref, expects, }); } } return matched(); } getConsecutiveToken(tokenType: number) { const resultToken = this.compareTokens((prev, current) => { if (prev.type === tokenType && current.type === tokenType) { return current; } }); return resultToken || null; } takeTurns(tokenNumbers: ReadonlyArray<number>, lastTokenNumber?: number) { const tokens = this.slice(); for (let i = 0; i < tokens.length; i++) { const token = tokens[i]; const expectedTokenNumber = tokenNumbers[i % tokenNumbers.length]; if (token.type !== expectedTokenNumber) { return { unexpectedLastToken: false, expectedTokenNumber, token, }; } if (lastTokenNumber != null && i === tokens.length - 1 && token.type !== lastTokenNumber) { return { unexpectedLastToken: true, expectedTokenNumber, token, }; } } return null; } eachCheck(...callbacks: TokenEachCheck[]): Result { let headAndTail = this.headAndTail(); let head = headAndTail.head; let tail = headAndTail.tail; let prev: Token | null = null; let cumulativeOffset = 0; let passCount = 0; let firstUnmatched: UnmatchedResult | null = null; let wait = 20; for (const callback of callbacks) { wait--; const result = callback.call(this, head, tail); if (result && !result.matched) { passCount += result.passCount || 0; if (prev && result.offset === 0 && result.length === 0) { const { offset, line, column } = Token.shiftLocation(prev, cumulativeOffset); firstUnmatched = firstUnmatched || { ...result, offset, line, column, }; } if (!prev && this.value.length === 0) { firstUnmatched = firstUnmatched || { ...result, reason: 'empty-token', expects: undefined, }; } switch (result.reason) { case 'extra-token': { passCount += 1; break; } default: { if (typeof result.reason !== 'string') { passCount += 2 * wait; } } } firstUnmatched = firstUnmatched || result; } else if (result && !firstUnmatched && result.matched) { return result; } else { if (head?.value && !head.match(/^\s*$/)) { passCount += 4 * wait; } } cumulativeOffset = head?.length || 0; headAndTail = tail.headAndTail(); prev = head; head = headAndTail.head; tail = headAndTail.tail; } if (firstUnmatched) { const res = { ...firstUnmatched, passCount, }; return res; } return matched(); } getDuplicated() { const aList = this.slice(); const bList = this.slice(); for (const aToken of aList) { for (const bToken of bList) { if (aToken.offset === bToken.offset) { continue; } let a = aToken.value; let b = bToken.value; if (this.caseInsensitive) { a = a.toLowerCase(); b = b.toLowerCase(); } if (a === b) { return bToken; } } } return null; } divide(position: number) { const _a = this.slice(0, position); const _b = this.slice(position); const a = TokenCollection._new(_a, this); const b = TokenCollection._new(_b, this); return [a, b] as const; } chunk(split: number) { const chunks: TokenCollection[] = []; const tokens = this.slice(); while (tokens.length) { const chunkTokens = tokens.splice(0, split); const chunk = TokenCollection._new(chunkTokens, this); chunks.push(chunk); } return chunks; } toJSON() { return this.map(t => t.toJSON()); } }
the_stack
import React, { ChangeEvent, useEffect } from 'react' import { OutlinedInput, InputLabel, InputAdornment, FormControl, Paper, Container, Grid, Select, Link, IconButton, makeStyles, } from '@material-ui/core' import clsx from 'clsx' import AttachMoneyIcon from '@material-ui/icons/AttachMoney' import AccessTimeIcon from '@material-ui/icons/AccessTime' import EmojiPeopleIcon from '@material-ui/icons/EmojiPeople' import GitHubIcon from '@material-ui/icons/GitHub' import Typography from '@material-ui/core/Typography' import { Breakdown } from './Breakdown' import { periodToYear, unitToYear } from './calcs' import AboutDialog from './About' const useStyles = makeStyles(theme => ({ root: { padding: '2em 3em', marginTop: theme.spacing(2), }, margin: { margin: theme.spacing(0.5), }, withoutLabel: { marginTop: theme.spacing(3), }, textField: { maxWidth: 150, }, heading: {}, panel: {}, topControls: { float: 'right', display: 'inline-flex', }, })) function TopControls() { const classes = useStyles() return ( <div className={classes.topControls}> <AboutDialog /> <IconButton href="https://github.com/oselz/isitworththecost"> <GitHubIcon fontSize="large" /> </IconButton> </div> ) } function App() { const classes = useStyles() const [values, setValues] = React.useState({ timeCost: { value: 25, unit: 'dollars', period: 'hour' }, serviceCost: { value: 125, unit: 'dollars', period: 'month' }, trainingTime: { value: 2, unit: 'hour', period: null }, timeSavings: { value: 60, unit: 'min', period: 'day' }, peopleCount: { value: 1, unit: null, period: null }, savingPeriodCost: 'year', savingPeriodPeople: 'day', paybackPeriod: 'day', }) const [costs, setCosts] = React.useState({ employeePerYear: 0, servicePerYear: 0, trainingPerYear: 0, savingsPerYear: 0, freeTimePerYear: 0, paybackTimePerYear: 0, }) const handleChange = (prop: string, key: string | null = null) => ( event: ChangeEvent<HTMLInputElement | { value: unknown }>, ): void => { let val: any = event.target.value if (key === null) { setValues({ ...values, [prop]: val, }) } else { if (key === 'value' && (val < 0 || isNaN(val))) { val = 0 } setValues({ ...values, [prop]: { //@ts-ignore value: values[prop].value, //@ts-ignore unit: values[prop].unit, //@ts-ignore period: values[prop].period, //@ts-ignore [key]: val, }, }) } } useEffect(() => { // save this to state for now for ease of visibility const employeePerYear = values.timeCost.value * periodToYear(values.timeCost.period, 1) const servicePerYear = values.serviceCost.value * periodToYear(values.serviceCost.period, 1) // assumes amortisation period of 1 year const trainingPerYear = unitToYear(values.trainingTime.unit, values.trainingTime.value) * employeePerYear * values.peopleCount.value const freeTimePerYear = periodToYear( values.timeSavings.period, unitToYear(values.timeSavings.unit, values.timeSavings.value), ) * values.peopleCount.value const savingsPerYear = employeePerYear * freeTimePerYear - servicePerYear - trainingPerYear const paybackTimePerYear = (trainingPerYear + servicePerYear) / employeePerYear setCosts({ employeePerYear, servicePerYear, trainingPerYear, savingsPerYear, freeTimePerYear, paybackTimePerYear, }) }, [values]) return ( <Container maxWidth={'md'}> <Paper className={classes.root} variant={'outlined'}> <div className={classes.heading}> <TopControls /> <Typography variant="h2" component="h1"> Is it worth the cost? </Typography> <Typography variant="h5" component="p" gutterBottom> A simple check on whether purchasing a service is worth the cost. </Typography> </div> <Grid container> <Grid item xs={12} md={6}> <h2>Basics</h2> <p>1. Cost of your time or an employees time.</p> <FormControl className={clsx(classes.margin, classes.textField)} variant="outlined" > <InputLabel htmlFor="time-cost"> Time Cost </InputLabel> <OutlinedInput id="time-cost" value={values.timeCost.value} type="number" onChange={handleChange('timeCost', 'value')} startAdornment={ <InputAdornment position="start"> <AttachMoneyIcon /> </InputAdornment> } labelWidth={80} /> </FormControl> <FormControl variant="outlined" className={classes.margin} > <InputLabel htmlFor="time-cost-unit"> per </InputLabel> <Select native value={values.timeCost.period} onChange={handleChange('timeCost', 'period')} labelWidth={40} inputProps={{ name: 'per', id: 'time-cost-unit', }} > <option value={'hour'}>hour</option> <option value={'day'}>day</option> <option value={'week'}>week</option> <option value={'month'}>month</option> <option value={'year'}>year</option> </Select> </FormControl> <p>2. Cost of the service under consideration.</p> <FormControl className={clsx(classes.margin, classes.textField)} variant="outlined" > <InputLabel htmlFor="service-cost"> Service Cost </InputLabel> <OutlinedInput id="service-cost" value={values.serviceCost.value} type="number" onChange={handleChange('serviceCost', 'value')} startAdornment={ <InputAdornment position="start"> <AttachMoneyIcon /> </InputAdornment> } labelWidth={95} /> </FormControl> <FormControl variant="outlined" className={classes.margin} > <InputLabel htmlFor="service-cost-period"> per </InputLabel> <Select native value={values.serviceCost.period} onChange={handleChange('serviceCost', 'period')} labelWidth={40} inputProps={{ name: 'per', id: 'service-cost-period', }} > {/*<option value={'hour'}>hour</option>*/} <option value={'day'}>day</option> <option value={'week'}>week</option> <option value={'month'}>month</option> <option value={'year'}>year</option> </Select> </FormControl> <p> 3. Estimate the training time required (one person). </p> <FormControl fullWidth className={clsx(classes.margin, classes.textField)} variant="outlined" > <InputLabel htmlFor="training-time"> Training Time </InputLabel> <OutlinedInput id="training-time" value={values.trainingTime.value} type="number" onChange={handleChange('trainingTime', 'value')} startAdornment={ <InputAdornment position="start"> <AccessTimeIcon /> </InputAdornment> } labelWidth={105} /> </FormControl> <FormControl variant="outlined" className={classes.margin} > <Select native value={values.trainingTime.unit} onChange={handleChange('trainingTime', 'unit')} inputProps={{ name: 'per', id: 'training-time-unit', }} > <option value={'hour'}>hours</option> <option value={'day'}>days</option> <option value={'week'}>weeks</option> <option value={'month'}>months</option> {/*<option value={'year'}>years</option>*/} </Select> </FormControl> <p> 4. Estimate the time this service will save (one person). </p> <FormControl className={clsx(classes.margin, classes.textField)} variant="outlined" > <InputLabel htmlFor="time-savings"> Time Saved </InputLabel> <OutlinedInput id="time-savings" type="number" value={values.timeSavings.value} onChange={handleChange('timeSavings', 'value')} startAdornment={ <InputAdornment position="start"> <AccessTimeIcon /> </InputAdornment> } labelWidth={80} /> </FormControl> <FormControl variant="outlined" className={classes.margin} > <Select native value={values.timeSavings.unit} onChange={handleChange('timeSavings', 'unit')} > <option value={'minute'}>minutes</option> <option value={'hour'}>hours</option> <option value={'day'}>days</option> <option value={'week'}>weeks</option> <option value={'month'}>months</option> </Select> </FormControl> <FormControl variant="outlined" className={classes.margin} > <InputLabel htmlFor="time-savings-period"> per </InputLabel> <Select id={'time-savings-period'} native value={values.timeSavings.period} onChange={handleChange('timeSavings', 'period')} labelWidth={40} > <option value={'hour'}>hour</option> <option value={'day'}>day</option> <option value={'week'}>week</option> <option value={'month'}>month</option> <option value={'year'}>year</option> </Select> </FormControl> <p>5. Number of people using the service.</p> <FormControl className={clsx(classes.margin, classes.textField)} variant="outlined" > <InputLabel htmlFor="people-count"> People </InputLabel> <OutlinedInput id="people-count" type="number" value={values.peopleCount.value} onChange={handleChange('peopleCount', 'value')} startAdornment={ <InputAdornment position="start"> <EmojiPeopleIcon /> </InputAdornment> } labelWidth={50} /> </FormControl> </Grid> <Grid item xs={12} md={6}> <Breakdown values={values} costs={costs} handleChange={handleChange} /> </Grid> </Grid> </Paper> </Container> ) } export default App
the_stack
import * as Icons from "phosphor-react"; import { IconEntry, IconCategory } from "."; export const icons: ReadonlyArray<IconEntry> = [ { name: "activity", categories: [IconCategory.HEALTH], tags: [ "heartbeat", "medical", "ecg", "ekg", "vitals", "monitor", "medicine", ], Icon: Icons.Activity, }, { name: "address-book", categories: [IconCategory.COMMUNICATION], tags: ["contacts", "roledex"], Icon: Icons.AddressBook, }, { name: "airplane", categories: [IconCategory.MAP, IconCategory.OBJECTS], tags: [ "vehicles", "airports", "flights", "flying", "planes", "transit", "transportation", "traveling", ], Icon: Icons.Airplane, }, { name: "airplane-in-flight", categories: [IconCategory.MAP, IconCategory.OBJECTS], tags: [ "vehicles", "airports", "flights", "flying", "planes", "transit", "transportation", "traveling", "arrival", ], Icon: Icons.AirplaneInFlight, }, { name: "airplane-landing", categories: [IconCategory.MAP, IconCategory.OBJECTS], tags: [ "vehicles", "airports", "flights", "flying", "planes", "transit", "transportation", "traveling", "arrival", ], Icon: Icons.AirplaneLanding, }, { name: "airplane-takeoff", categories: [IconCategory.MAP, IconCategory.OBJECTS], tags: [ "vehicles", "airports", "flights", "flying", "planes", "transit", "transportation", "traveling", "departure", ], Icon: Icons.AirplaneTakeoff, }, { name: "airplane-tilt", categories: [IconCategory.MAP, IconCategory.OBJECTS], tags: [ "vehicles", "airports", "flights", "flying", "planes", "transit", "transportation", "traveling", "departure", ], Icon: Icons.AirplaneTilt, }, { name: "airplay", categories: [IconCategory.MEDIA, IconCategory.SYSTEM], tags: ["*updated*", "apple", "screencasting", "television", "tv"], Icon: Icons.Airplay, }, { name: "alarm", categories: [IconCategory.SYSTEM], tags: ["times", "timer", "clock", "schedule", "events", "watch"], Icon: Icons.Alarm, }, { name: "alien", categories: [IconCategory.GAMES], tags: [ "*new*", "ufo", "space", "flying saucer", "extra terrestrial", "sci-fi", ], Icon: Icons.Alien, }, { name: "align-top", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["alignment", "arrangement", "layout", "flush top"], Icon: Icons.AlignTop, }, { name: "align-bottom", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["alignment", "arrangement", "layout", "flush bottom"], Icon: Icons.AlignBottom, }, { name: "align-left", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["alignment", "arrangement", "layout", "flush left"], Icon: Icons.AlignLeft, }, { name: "align-right", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["alignment", "arrangement", "layout", "flush right"], Icon: Icons.AlignRight, }, { name: "align-center-horizontal", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["alignment", "arrangement", "layout", "centered", "middle"], Icon: Icons.AlignCenterHorizontal, }, { name: "align-center-vertical", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["alignment", "arrangement", "layout", "centered", "middle"], Icon: Icons.AlignCenterVertical, }, { name: "align-bottom-simple", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["*new*", "alignment", "arrangement", "layout", "flush bottom"], Icon: Icons.AlignBottomSimple, }, { name: "align-center-horizontal-simple", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["*new*", "alignment", "arrangement", "layout", "centered", "middle"], Icon: Icons.AlignCenterHorizontalSimple, }, { name: "align-center-vertical-simple", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["*new*", "alignment", "arrangement", "layout", "centered", "middle"], Icon: Icons.AlignCenterVerticalSimple, }, { name: "align-left-simple", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["*new*", "alignment", "arrangement", "layout", "flush left"], Icon: Icons.AlignLeftSimple, }, { name: "align-right-simple", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["*new*", "alignment", "arrangement", "layout", "flush right"], Icon: Icons.AlignRightSimple, }, { name: "align-top-simple", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["*new*", "alignment", "arrangement", "layout", "flush top"], Icon: Icons.AlignTopSimple, }, { name: "anchor", categories: [ IconCategory.COMMUNICATION, IconCategory.MAP, IconCategory.OBJECTS, ], tags: ["nautical", "boats", "ships", "hope", "safety", "insurance"], Icon: Icons.Anchor, }, { name: "anchor-simple", categories: [ IconCategory.COMMUNICATION, IconCategory.MAP, IconCategory.OBJECTS, ], tags: ["nautical", "boats", "ships", "hope", "safety", "insurance"], Icon: Icons.AnchorSimple, }, { name: "android-logo", categories: [ IconCategory.BRAND, IconCategory.DEVELOPMENT, IconCategory.SYSTEM, ], tags: ["logos", "google", "mobile", "phone", "cellular", "cellphone"], Icon: Icons.AndroidLogo, }, { name: "angular-logo", categories: [IconCategory.BRAND, IconCategory.DEVELOPMENT], tags: ["*new*", "framework", "javascript", "google", "web"], Icon: Icons.AngularLogo, }, { name: "aperture", categories: [IconCategory.DESIGN, IconCategory.MEDIA], tags: ["photography", "cameras", "pictures", "lens"], Icon: Icons.Aperture, }, { name: "app-window", categories: [IconCategory.COMMUNICATION, IconCategory.SYSTEM], tags: ["windows", "software", "programs", "applications"], Icon: Icons.AppWindow, }, { name: "apple-logo", categories: [IconCategory.BRAND], tags: ["macintosh", "imac", "iphone", "ipad", "macos", "ios"], Icon: Icons.AppleLogo, }, { name: "app-store-logo", categories: [IconCategory.BRAND], tags: ["*new*", "macintosh", "imac", "iphone", "ipad", "macos", "ios"], Icon: Icons.AppStoreLogo, }, { name: "apple-podcasts-logo", categories: [IconCategory.BRAND, IconCategory.MEDIA], tags: ["*new*", "macintosh", "imac", "iphone", "ipad", "macos", "ios"], Icon: Icons.ApplePodcastsLogo, }, { name: "archive", categories: [IconCategory.OFFICE, IconCategory.SYSTEM], tags: [ "saved", "saving", "archived", "archiving", "archival", "downloaded", "downloading", ], Icon: Icons.Archive, }, { name: "archive-box", categories: [IconCategory.OFFICE, IconCategory.SYSTEM], tags: [ "saved", "saving", "archived", "archiving", "archival", "downloaded", "downloading", ], Icon: Icons.ArchiveBox, }, { name: "archive-tray", categories: [IconCategory.OFFICE, IconCategory.SYSTEM], tags: [ "saved", "saving", "archived", "archiving", "archival", "downloaded", "downloading", ], Icon: Icons.ArchiveTray, }, { name: "armchair", categories: [IconCategory.OBJECTS], tags: ["*updated*", "seat", "furniture"], Icon: Icons.Armchair, }, { name: "arrow-up", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowUp, }, { name: "arrow-down", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowDown, }, { name: "arrow-left", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowLeft, }, { name: "arrow-right", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowRight, }, { name: "arrow-up-left", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowUpLeft, }, { name: "arrow-up-right", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowUpRight, }, { name: "arrow-down-left", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowDownLeft, }, { name: "arrow-down-right", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowDownRight, }, { name: "arrow-circle-up", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowCircleUp, }, { name: "arrow-circle-down", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowCircleDown, }, { name: "arrow-circle-left", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowCircleLeft, }, { name: "arrow-circle-right", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowCircleRight, }, { name: "arrow-circle-up-left", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowCircleUpLeft, }, { name: "arrow-circle-up-right", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowCircleUpRight, }, { name: "arrow-circle-down-left", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowCircleDownLeft, }, { name: "arrow-circle-down-right", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowCircleDownRight, }, { name: "arrow-square-up", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowSquareUp, }, { name: "arrow-square-down", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowSquareDown, }, { name: "arrow-square-left", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowSquareLeft, }, { name: "arrow-square-right", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowSquareRight, }, { name: "arrow-square-up-left", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowSquareUpLeft, }, { name: "arrow-square-up-right", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowSquareUpRight, }, { name: "arrow-square-down-left", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowSquareDownLeft, }, { name: "arrow-square-down-right", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowSquareDownRight, }, { name: "arrow-square-in", categories: [IconCategory.ARROWS], tags: ["import", "directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowSquareIn, }, { name: "arrow-square-out", categories: [IconCategory.ARROWS], tags: [ "export", "external", "directional", "pointer", "pointing", "arrowhead", ], Icon: Icons.ArrowSquareOut, }, { name: "arrow-arc-left", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowArcLeft, }, { name: "arrow-arc-right", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowArcRight, }, { name: "arrow-bend-left-up", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowBendLeftUp, }, { name: "arrow-bend-right-up", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowBendRightUp, }, { name: "arrow-bend-left-down", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowBendLeftDown, }, { name: "arrow-bend-right-down", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowBendRightDown, }, { name: "arrow-bend-up-left", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowBendUpLeft, }, { name: "arrow-bend-down-left", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowBendDownLeft, }, { name: "arrow-bend-up-right", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowBendUpRight, }, { name: "arrow-bend-down-right", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowBendDownRight, }, { name: "arrow-bend-double-left", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowBendDoubleUpLeft, }, { name: "arrow-bend-double-right", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowBendDoubleUpRight, }, { name: "arrow-clockwise", categories: [IconCategory.ARROWS], tags: [ "directional", "pointer", "pointing", "arrowhead", "redo", "refreshing", "rotate", "spin", ], Icon: Icons.ArrowClockwise, }, { name: "arrow-counter-clockwise", categories: [IconCategory.ARROWS], tags: [ "directional", "pointer", "pointing", "arrowhead", "undo", "refreshing", "rotate", "spin", ], Icon: Icons.ArrowCounterClockwise, }, { name: "arrow-elbow-left", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowElbowLeft, }, { name: "arrow-elbow-right", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowElbowRight, }, { name: "arrow-elbow-left-up", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowElbowLeftUp, }, { name: "arrow-elbow-right-up", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowElbowRightUp, }, { name: "arrow-elbow-left-down", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowElbowLeftDown, }, { name: "arrow-elbow-right-down", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowElbowRightDown, }, { name: "arrow-elbow-up-left", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowElbowUpLeft, }, { name: "arrow-elbow-down-left", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowElbowDownLeft, }, { name: "arrow-elbow-up-right", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowElbowUpRight, }, { name: "arrow-elbow-down-right", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowElbowDownRight, }, { name: "arrow-fat-up", categories: [IconCategory.ARROWS], tags: [ "directional", "pointer", "pointing", "arrowhead", "shift", "outlined", ], Icon: Icons.ArrowFatUp, }, { name: "arrow-fat-down", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead", "outlined"], Icon: Icons.ArrowFatDown, }, { name: "arrow-fat-left", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead", "outlined"], Icon: Icons.ArrowFatLeft, }, { name: "arrow-fat-right", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead", "outlined"], Icon: Icons.ArrowFatRight, }, { name: "arrow-fat-line-up", categories: [IconCategory.ARROWS], tags: [ "directional", "pointer", "pointing", "arrowhead", "caps lock", "outlined", ], Icon: Icons.ArrowFatLineUp, }, { name: "arrow-fat-line-down", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead", "outlined"], Icon: Icons.ArrowFatLineDown, }, { name: "arrow-fat-line-left", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead", "outlined"], Icon: Icons.ArrowFatLineLeft, }, { name: "arrow-fat-line-right", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead", "outlined"], Icon: Icons.ArrowFatLineRight, }, { name: "arrow-fat-lines-up", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead", "outlined"], Icon: Icons.ArrowFatLinesUp, }, { name: "arrow-fat-lines-down", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead", "outlined"], Icon: Icons.ArrowFatLinesDown, }, { name: "arrow-fat-lines-left", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead", "outlined"], Icon: Icons.ArrowFatLinesLeft, }, { name: "arrow-fat-lines-right", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead", "outlined"], Icon: Icons.ArrowFatLinesRight, }, { name: "arrow-line-up", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead", "top"], Icon: Icons.ArrowLineUp, }, { name: "arrow-line-down", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead", "bottom"], Icon: Icons.ArrowLineDown, }, { name: "arrow-line-left", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowLineLeft, }, { name: "arrow-line-right", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowLineRight, }, { name: "arrow-line-up-left", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowLineUpLeft, }, { name: "arrow-line-up-right", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowLineUpRight, }, { name: "arrow-line-down-left", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowLineDownLeft, }, { name: "arrow-line-down-right", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowLineDownRight, }, { name: "arrow-u-left-up", categories: [IconCategory.ARROWS], tags: [ "directional", "pointer", "pointing", "arrowhead", "redo", "u-turns", ], Icon: Icons.ArrowULeftUp, }, { name: "arrow-u-right-up", categories: [IconCategory.ARROWS], tags: [ "directional", "pointer", "pointing", "arrowhead", "redo", "u-turns", ], Icon: Icons.ArrowURightUp, }, { name: "arrow-u-left-down", categories: [IconCategory.ARROWS], tags: [ "directional", "pointer", "pointing", "arrowhead", "undo", "return", "u-turns", ], Icon: Icons.ArrowULeftDown, }, { name: "arrow-u-right-down", categories: [IconCategory.ARROWS], tags: [ "directional", "pointer", "pointing", "arrowhead", "undo", "return", "u-turns", ], Icon: Icons.ArrowURightDown, }, { name: "arrow-u-up-left", categories: [IconCategory.ARROWS], tags: [ "directional", "pointer", "pointing", "arrowhead", "undo", "return", "u-turns", ], Icon: Icons.ArrowUUpLeft, }, { name: "arrow-u-down-left", categories: [IconCategory.ARROWS], tags: [ "directional", "pointer", "pointing", "arrowhead", "undo", "return", "u-turns", ], Icon: Icons.ArrowUDownLeft, }, { name: "arrow-u-up-right", categories: [IconCategory.ARROWS], tags: [ "directional", "pointer", "pointing", "arrowhead", "redo", "u-turns", ], Icon: Icons.ArrowUUpRight, }, { name: "arrow-u-down-right", categories: [IconCategory.ARROWS], tags: [ "directional", "pointer", "pointing", "arrowhead", "redo", "u-turns", ], Icon: Icons.ArrowUDownRight, }, { name: "arrows-clockwise", categories: [IconCategory.ARROWS], tags: [ "directional", "pointer", "pointing", "arrowhead", "redo", "refreshing", "sync", "synchronize", "rotate", "spin", ], Icon: Icons.ArrowsClockwise, }, { name: "arrows-counter-clockwise", categories: [IconCategory.ARROWS], tags: [ "directional", "pointer", "pointing", "arrowhead", "undo", "refreshing", "rotate", "spin", ], Icon: Icons.ArrowsCounterClockwise, }, { name: "arrows-down-up", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowsDownUp, }, { name: "arrows-left-right", categories: [IconCategory.ARROWS], tags: ["directional", "pointer", "pointing", "arrowhead"], Icon: Icons.ArrowsLeftRight, }, { name: "arrows-horizontal", categories: [IconCategory.ARROWS], tags: [ "*new*", "directional", "pointer", "cursor", "resize", "expand", "left", "right", ], Icon: Icons.ArrowsHorizontal, }, { name: "arrows-vertical", categories: [IconCategory.ARROWS], tags: [ "*new*", "directional", "pointer", "cursor", "resize", "expand", "up", "down", ], Icon: Icons.ArrowsVertical, }, { name: "arrows-in", categories: [IconCategory.ARROWS], tags: [ "directional", "pointer", "pointing", "arrowhead", "collapse", "minimize", "resize", "shrink", ], Icon: Icons.ArrowsIn, }, { name: "arrows-in-cardinal", categories: [IconCategory.ARROWS], tags: [ "directional", "pointer", "pointing", "arrowhead", "collapse", "minimize", "resize", "shrink", ], Icon: Icons.ArrowsInCardinal, }, { name: "arrows-in-simple", categories: [IconCategory.ARROWS], tags: [ "directional", "pointer", "pointing", "arrowhead", "collapse", "minimize", "resize", ], Icon: Icons.ArrowsInSimple, }, { name: "arrows-in-line-horizontal", categories: [IconCategory.ARROWS, IconCategory.DESIGN, IconCategory.EDITOR], tags: [ "directional", "pointer", "pointing", "arrowhead", "close", "center", "align", ], Icon: Icons.ArrowsInLineHorizontal, }, { name: "arrows-in-line-vertical", categories: [IconCategory.ARROWS, IconCategory.DESIGN, IconCategory.EDITOR], tags: [ "directional", "pointer", "pointing", "arrowhead", "close", "center", "align", ], Icon: Icons.ArrowsInLineVertical, }, { name: "arrows-out", categories: [IconCategory.ARROWS], tags: [ "directional", "pointer", "pointing", "arrowhead", "expand", "fullscreen", "resize", "grow", ], Icon: Icons.ArrowsOut, }, { name: "arrows-out-cardinal", categories: [IconCategory.ARROWS], tags: [ "directional", "pointer", "pointing", "arrowhead", "expand", "fullscreen", "resize", "pan", "move", "grow", ], Icon: Icons.ArrowsOutCardinal, }, { name: "arrows-out-simple", categories: [IconCategory.ARROWS], tags: [ "directional", "pointer", "pointing", "arrowhead", "expand", "fullscreen", "resize", ], Icon: Icons.ArrowsOutSimple, }, { name: "arrows-out-line-horizontal", categories: [IconCategory.ARROWS, IconCategory.DESIGN, IconCategory.EDITOR], tags: ["directional", "pointer", "pointing", "arrowhead", "open"], Icon: Icons.ArrowsOutLineHorizontal, }, { name: "arrows-out-line-vertical", categories: [IconCategory.ARROWS, IconCategory.DESIGN, IconCategory.EDITOR], tags: ["directional", "pointer", "pointing", "arrowhead", "open"], Icon: Icons.ArrowsOutLineVertical, }, { name: "article", categories: [IconCategory.MEDIA, IconCategory.OBJECTS], tags: [ "reading", "writing", "journals", "periodicals", "text", "newspaper", ], Icon: Icons.Article, }, { name: "article-medium", categories: [IconCategory.MEDIA, IconCategory.OBJECTS], tags: [ "reading", "writing", "journals", "periodicals", "text", "newspaper", ], Icon: Icons.ArticleMedium, }, { name: "article-ny-times", categories: [IconCategory.MEDIA, IconCategory.OBJECTS], tags: [ "reading", "writing", "journals", "periodicals", "text", "news", "newspaper", "nyt", "new york times", ], Icon: Icons.ArticleNyTimes, }, // { // name: "artificial-intelligence", // categories: [IconCategory.DEVELOPMENT], // tags: ["ai", "machine learning", "computer", "robot"], // Icon: Icons.ArtificialIntelligence, // }, { name: "asterisk", categories: [IconCategory.COMMUNICATION], tags: ["star", "wildcard", "bullet point", "6", "emergency"], Icon: Icons.Asterisk, }, { name: "asterisk-simple", categories: [IconCategory.COMMUNICATION], tags: ["*new*", "star", "wildcard", "bullet point", "5", "emergency"], Icon: Icons.AsteriskSimple, }, { name: "at", categories: [IconCategory.COMMUNICATION], tags: [ "*updated*", "@", "address", "email", "at symbol", "commercial at", "arobase", ], Icon: Icons.At, }, { name: "atom", categories: [IconCategory.DEVELOPMENT, IconCategory.NATURE], tags: [ "atomic", "nucleus", "nuclear", "reactor", "science", "physics", "electron", "automation", ], Icon: Icons.Atom, }, { name: "baby", categories: [IconCategory.PEOPLE, IconCategory.HEALTH], tags: ["*updated*", "infant", "child", "children", "toddler"], Icon: Icons.Baby, }, { name: "backpack", categories: [IconCategory.COMMERCE, IconCategory.OBJECTS], tags: ["*new*", "knapsack", "camping", "school", "bag"], Icon: Icons.Backpack, }, { name: "backspace", categories: [IconCategory.SYSTEM], tags: ["keyboard", "remove", "delete"], Icon: Icons.Backspace, }, { name: "bag", categories: [IconCategory.COMMERCE, IconCategory.OBJECTS], tags: ["suitcase", "valise", "baggage", "folders", "portfolio"], Icon: Icons.Bag, }, { name: "bag-simple", categories: [IconCategory.COMMERCE, IconCategory.OBJECTS], tags: ["suitcase", "valise", "baggage", "folders", "portfolio"], Icon: Icons.BagSimple, }, { name: "balloon", categories: [IconCategory.COMMERCE, IconCategory.OBJECTS], tags: ["*new*", "helium", "birthday", "party"], Icon: Icons.Balloon, }, { name: "bandaids", categories: [IconCategory.HEALTH], tags: ["bandages", "medical", "medicine", "first aid", "injury"], Icon: Icons.Bandaids, }, { name: "bank", categories: [IconCategory.FINANCE], tags: [ "banking", "checking", "money", "savings", "deposit", "withdraw", "places", "locations", ], Icon: Icons.Bank, }, { name: "barbell", categories: [IconCategory.HEALTH], tags: [ "gym", "weights", "dumbbells", "strength training", "workout", "exercises", "fitness", ], Icon: Icons.Barbell, }, { name: "barcode", categories: [IconCategory.COMMERCE, IconCategory.SYSTEM], tags: ["upc", "qr", "products", "shopping", "scanner"], Icon: Icons.Barcode, }, { name: "barricade", categories: [IconCategory.MAP, IconCategory.OBJECTS], tags: ["*new*", "construction", "safety", "gate"], Icon: Icons.Barricade, }, { name: "baseball", categories: [IconCategory.GAMES, IconCategory.HEALTH], tags: ["*updated*", "sports", "mlb"], Icon: Icons.Baseball, }, { name: "basketball", categories: [IconCategory.GAMES, IconCategory.HEALTH], tags: ["*updated*", "sports", "nba"], Icon: Icons.Basketball, }, { name: "bathtub", categories: [IconCategory.OBJECTS], tags: ["*new*", "bath", "shower", "bathroom", "faucet"], Icon: Icons.Bathtub, }, { name: "battery-charging", categories: [IconCategory.SYSTEM], tags: ["charged", "charger", "charging", "power"], Icon: Icons.BatteryCharging, }, { name: "battery-charging-vertical", categories: [IconCategory.SYSTEM], tags: ["charged", "charger", "charging", "power"], Icon: Icons.BatteryChargingVertical, }, { name: "battery-full", categories: [IconCategory.SYSTEM], tags: ["charged", "charger", "charging", "power", "filled"], Icon: Icons.BatteryFull, }, { name: "battery-high", categories: [IconCategory.SYSTEM], tags: ["charged", "charger", "charging", "power"], Icon: Icons.BatteryHigh, }, { name: "battery-medium", categories: [IconCategory.SYSTEM], tags: ["charged", "charger", "charging", "power"], Icon: Icons.BatteryMedium, }, { name: "battery-low", categories: [IconCategory.SYSTEM], tags: ["charged", "charger", "charging", "power"], Icon: Icons.BatteryLow, }, { name: "battery-empty", categories: [IconCategory.SYSTEM], tags: ["charged", "charger", "charging", "power", "dead"], Icon: Icons.BatteryEmpty, }, { name: "battery-plus", categories: [IconCategory.SYSTEM], tags: ["*new*", "charged", "charger", "charging", "power"], Icon: Icons.BatteryPlus, }, { name: "battery-warning", categories: [IconCategory.SYSTEM], tags: ["charged", "charger", "charging", "power", "empty", "critical"], Icon: Icons.BatteryWarning, }, { name: "battery-warning-vertical", categories: [IconCategory.SYSTEM], tags: ["charged", "charger", "charging", "power", "empty", "critical"], Icon: Icons.BatteryWarningVertical, }, { name: "bed", categories: [IconCategory.HEALTH, IconCategory.MAP, IconCategory.OBJECTS], tags: [ "hotels", "accommodations", "sleeping", "places", "locations", "medical", "hospital", ], Icon: Icons.Bed, }, { name: "beer-bottle", categories: [IconCategory.COMMERCE, IconCategory.MAP, IconCategory.OBJECTS], tags: [ "*new*", "drinks", "beverages", "places", "locations", "bars", "restaurants", "food", "dining", ], Icon: Icons.BeerBottle, }, { name: "behance-logo", categories: [IconCategory.BRAND, IconCategory.DESIGN], tags: ["*new*", "logos", "illustration", "ui", "interface"], Icon: Icons.BehanceLogo, }, { name: "bell", categories: [IconCategory.SYSTEM], tags: [ "alarm", "notifications", "times", "timer", "clock", "schedule", "events", "ringer", "calls", ], Icon: Icons.Bell, }, { name: "bell-ringing", categories: [IconCategory.SYSTEM], tags: [ "alarm", "notifications", "times", "timer", "clock", "schedule", "events", "ringer", "calls", ], Icon: Icons.BellRinging, }, { name: "bell-slash", categories: [IconCategory.SYSTEM], tags: [ "alarm", "notifications", "times", "timer", "clock", "schedule", "events", "silent", "silenced", "ringer", "calls", "disabled", ], Icon: Icons.BellSlash, }, { name: "bell-z", categories: [IconCategory.SYSTEM], tags: [ "alarm", "notifications", "times", "timer", "clock", "schedule", "events", "ringer", "snooze", ], Icon: Icons.BellZ, }, { name: "bell-simple", categories: [IconCategory.SYSTEM], tags: [ "alarm", "notifications", "times", "timer", "clock", "schedule", "events", "ringer", "calls", ], Icon: Icons.BellSimple, }, { name: "bell-simple-ringing", categories: [IconCategory.SYSTEM], tags: [ "alarm", "notifications", "times", "timer", "clock", "schedule", "events", "ringer", "calls", ], Icon: Icons.BellSimpleRinging, }, { name: "bell-simple-slash", categories: [IconCategory.SYSTEM], tags: [ "alarm", "notifications", "times", "timer", "clock", "schedule", "events", "ringer", "silent", "silenced", "disabled", ], Icon: Icons.BellSimpleSlash, }, { name: "bell-simple-z", categories: [IconCategory.SYSTEM], tags: [ "alarm", "notifications", "times", "timer", "clock", "schedule", "events", "ringer", "snooze", ], Icon: Icons.BellSimpleZ, }, { name: "bezier-curve", categories: [IconCategory.DESIGN], tags: ["*new*", "shapes", "drawing", "path", "pen"], Icon: Icons.BezierCurve, }, { name: "bicycle", categories: [IconCategory.HEALTH, IconCategory.MAP, IconCategory.OBJECTS], tags: [ "bikers", "bicycling", "cyclists", "transit", "transportation", "commuter", "exercises", "fitness", ], Icon: Icons.Bicycle, }, { name: "binoculars", categories: [IconCategory.NATURE, IconCategory.OBJECTS, IconCategory.MAP], tags: ["*new*", "telescope", "glasses", "search", "find", "explore"], Icon: Icons.Binoculars, }, { name: "bird", categories: [IconCategory.NATURE], tags: ["animals", "pets"], Icon: Icons.Bird, }, { name: "bluetooth", categories: [IconCategory.SYSTEM], tags: ["wireless", "connection", "connected", "connectivity"], Icon: Icons.Bluetooth, }, { name: "bluetooth-connected", categories: [IconCategory.SYSTEM], tags: ["wireless", "connection", "connected", "connectivity"], Icon: Icons.BluetoothConnected, }, { name: "bluetooth-slash", categories: [IconCategory.SYSTEM], tags: [ "wireless", "connection", "connectivity", "disconnected", "disabled", ], Icon: Icons.BluetoothSlash, }, { name: "bluetooth-x", categories: [IconCategory.SYSTEM], tags: ["wireless", "connection", "connectivity", "disconnected", "errors"], Icon: Icons.BluetoothX, }, { name: "boat", categories: [IconCategory.MAP, IconCategory.OBJECTS], tags: [ "ferry", "ship", "cruise", "vehicles", "public transit", "transportation", "commuter", "traveling", "sailing", "places", "locations", ], Icon: Icons.Boat, }, { name: "book", categories: [IconCategory.OFFICE, IconCategory.MEDIA, IconCategory.OBJECTS], tags: ["reading", "reader", "novel", "story", "library"], Icon: Icons.Book, }, { name: "book-bookmark", categories: [IconCategory.OFFICE, IconCategory.MEDIA, IconCategory.OBJECTS], tags: [ "reading", "reader", "novel", "story", "library", "favorites", "favorited", ], Icon: Icons.BookBookmark, }, { name: "book-open", categories: [IconCategory.OFFICE, IconCategory.MEDIA, IconCategory.OBJECTS], tags: ["reading", "reader", "novel", "story", "library"], Icon: Icons.BookOpen, }, { name: "books", categories: [ IconCategory.OFFICE, IconCategory.MAP, IconCategory.MEDIA, IconCategory.OBJECTS, ], tags: ["reading", "reader", "bookshelf", "library", "places", "locations"], Icon: Icons.Books, }, { name: "bookmark", categories: [IconCategory.OFFICE, IconCategory.MEDIA, IconCategory.OBJECTS], tags: [ "reading", "reader", "novel", "story", "placeholder", "favorites", "favorited", "library", ], Icon: Icons.Bookmark, }, { name: "bookmark-simple", categories: [IconCategory.OFFICE, IconCategory.MEDIA, IconCategory.OBJECTS], tags: [ "reading", "reader", "novel", "story", "placeholder", "favorites", "favorited", "library", ], Icon: Icons.BookmarkSimple, }, { name: "bookmarks", categories: [IconCategory.OFFICE, IconCategory.OBJECTS], tags: [ "reading", "reader", "novel", "story", "placeholder", "favorites", "favorited", "library", ], Icon: Icons.Bookmarks, }, { name: "bookmarks-simple", categories: [IconCategory.OFFICE, IconCategory.OBJECTS], tags: [ "reading", "reader", "novel", "story", "placeholder", "favorites", "favorited", "library", ], Icon: Icons.BookmarksSimple, }, { name: "bounding-box", categories: [IconCategory.DESIGN], tags: ["polygon", "shapes", "outline", "corners", "rectangle"], Icon: Icons.BoundingBox, }, { name: "brackets-angle", categories: [IconCategory.DEVELOPMENT, IconCategory.EDITOR], tags: ["code", "angle brackets", "angle braces"], Icon: Icons.BracketsAngle, }, { name: "brackets-curly", categories: [IconCategory.DEVELOPMENT, IconCategory.EDITOR], tags: ["code", "curly brackets", "curly braces"], Icon: Icons.BracketsCurly, }, { name: "brackets-round", categories: [IconCategory.DEVELOPMENT, IconCategory.EDITOR], tags: ["code", "parentheses", "round brackets", "round braces"], Icon: Icons.BracketsRound, }, { name: "brackets-square", categories: [IconCategory.DEVELOPMENT, IconCategory.EDITOR], tags: ["code", "square brackets", "square braces", "array"], Icon: Icons.BracketsSquare, }, { name: "brain", categories: [IconCategory.HEALTH, IconCategory.NATURE], tags: ["mind", "mental"], Icon: Icons.Brain, }, { name: "brandy", categories: [IconCategory.COMMERCE, IconCategory.MAP, IconCategory.OBJECTS], tags: [ "drinks", "beverages", "whiskey", "cocktail", "places", "locations", "bars", "restaurants", "food", "dining", ], Icon: Icons.Brandy, }, { name: "briefcase", categories: [IconCategory.OFFICE, IconCategory.OBJECTS], tags: ["suitcase", "valise", "baggage", "folders", "portfolio"], Icon: Icons.Briefcase, }, { name: "briefcase-metal", categories: [IconCategory.OFFICE, IconCategory.OBJECTS], tags: [ "*updated*", "suitcase", "valise", "baggage", "folders", "portfolio", ], Icon: Icons.BriefcaseMetal, }, { name: "broadcast", categories: [ IconCategory.COMMUNICATION, IconCategory.MEDIA, IconCategory.SYSTEM, ], tags: ["radio", "hotspot", "wifi", "emit"], Icon: Icons.Broadcast, }, { name: "browser", categories: [IconCategory.COMMUNICATION, IconCategory.SYSTEM], tags: [ "web browsers", "windows", "internet", "website", "webpage", "chrome", "edge", "firefox", ], Icon: Icons.Browser, }, { name: "browsers", categories: [IconCategory.COMMUNICATION, IconCategory.SYSTEM], tags: [ "web browsers", "windows", "internet", "website", "webpage", "chrome", "edge", "firefox", ], Icon: Icons.Browsers, }, { name: "buildings", categories: [IconCategory.COMMERCE, IconCategory.MAP], tags: ["places", "locations", "company", "business"], Icon: Icons.Buildings, }, { name: "bug", categories: [IconCategory.DEVELOPMENT, IconCategory.NATURE], tags: ["debug", "errors", "insect", "ladybug"], Icon: Icons.Bug, }, { name: "bug-beetle", categories: [IconCategory.DEVELOPMENT, IconCategory.NATURE], tags: ["debug", "errors", "insect", "ladybug"], Icon: Icons.BugBeetle, }, { name: "bug-droid", categories: [IconCategory.DEVELOPMENT, IconCategory.NATURE], tags: ["debug", "errors", "insect", "android", "google"], Icon: Icons.BugDroid, }, { name: "bus", categories: [IconCategory.MAP, IconCategory.OBJECTS], tags: [ "vehicles", "automobile", "public transit", "transportation", "commuter", "traveling", "places", "locations", ], Icon: Icons.Bus, }, { name: "butterfly", categories: [IconCategory.NATURE], tags: ["*new*", "animals", "insects", "moth"], Icon: Icons.Butterfly, }, { name: "cactus", categories: [IconCategory.NATURE], tags: ["*new*", "plants", "cacti", "desert", "western"], Icon: Icons.Cactus, }, { name: "cake", categories: [IconCategory.OBJECTS], tags: ["dessert", "birthday", "celebration", "event"], Icon: Icons.Cake, }, { name: "calculator", categories: [ IconCategory.DEVELOPMENT, IconCategory.FINANCE, IconCategory.OFFICE, IconCategory.OBJECTS, ], tags: [ "addition", "sum", "subtraction", "difference", "multiply", "multiplication", "product", "divide", "division", "divisor", "dividend", "quotient", "equals", "equality", "mathematics", "arithmetic", "+", "-", "±", "×", "÷", "=", ], Icon: Icons.Calculator, }, { name: "calendar", categories: [IconCategory.OFFICE, IconCategory.SYSTEM], tags: ["dates", "times", "events", "schedule", "31"], Icon: Icons.Calendar, }, { name: "calendar-blank", categories: [IconCategory.OFFICE, IconCategory.SYSTEM], tags: ["dates", "times", "events", "schedule", "none"], Icon: Icons.CalendarBlank, }, { name: "calendar-check", categories: [IconCategory.OFFICE, IconCategory.SYSTEM], tags: ["dates", "times", "events", "schedule", "todo", "checklist"], Icon: Icons.CalendarCheck, }, { name: "calendar-plus", categories: [IconCategory.OFFICE, IconCategory.SYSTEM], tags: ["dates", "times", "events", "schedule", "add"], Icon: Icons.CalendarPlus, }, { name: "calendar-x", categories: [IconCategory.OFFICE, IconCategory.SYSTEM], tags: ["dates", "times", "events", "schedule", "closed", "cancelled"], Icon: Icons.CalendarX, }, { name: "camera", categories: [IconCategory.MEDIA, IconCategory.SYSTEM], tags: ["photography", "pictures", "lens"], Icon: Icons.Camera, }, { name: "camera-rotate", categories: [IconCategory.MEDIA, IconCategory.SYSTEM], tags: [ "*new*", "photography", "pictures", "orientation", "portrait", "landscape", ], Icon: Icons.CameraRotate, }, { name: "camera-slash", categories: [IconCategory.MEDIA, IconCategory.SYSTEM], tags: ["photography", "pictures", "lens", "disabled"], Icon: Icons.CameraSlash, }, { name: "campfire", categories: [IconCategory.NATURE], tags: ["*new*", "camping", "flame", "bonfire", "outdoors"], Icon: Icons.Campfire, }, { name: "car", categories: [IconCategory.MAP, IconCategory.OBJECTS], tags: [ "cars", "vehicles", "automobile", "transit", "transportation", "traveling", ], Icon: Icons.Car, }, { name: "car-simple", categories: [IconCategory.MAP, IconCategory.OBJECTS], tags: [ "cars", "vehicles", "automobile", "transit", "transportation", "traveling", ], Icon: Icons.CarSimple, }, { name: "cards", categories: [IconCategory.DESIGN, IconCategory.SYSTEM], tags: [ "card", "slides", "slideshow", "windows", "website", "webpage", "layers", ], Icon: Icons.Cards, }, { name: "cardholder", categories: [ IconCategory.COMMERCE, IconCategory.FINANCE, IconCategory.OBJECTS, ], tags: ["wallet", "money", "payment", "paying", "purchase"], Icon: Icons.Cardholder, }, { name: "caret-up", categories: [IconCategory.ARROWS], tags: [ "chevron", "directional", "pointer", "pointing", "arrowhead", "triangle", ], Icon: Icons.CaretUp, }, { name: "caret-down", categories: [IconCategory.ARROWS], tags: [ "chevron", "directional", "pointer", "pointing", "arrowhead", "triangle", ], Icon: Icons.CaretDown, }, { name: "caret-left", categories: [IconCategory.ARROWS], tags: [ "chevron", "directional", "pointer", "pointing", "arrowhead", "triangle", ], Icon: Icons.CaretLeft, }, { name: "caret-right", categories: [IconCategory.ARROWS], tags: [ "chevron", "directional", "pointer", "pointing", "arrowhead", "triangle", ], Icon: Icons.CaretRight, }, { name: "caret-double-up", categories: [IconCategory.ARROWS], tags: [ "chevron", "directional", "pointer", "pointing", "arrowhead", "triangle", ], Icon: Icons.CaretDoubleUp, }, { name: "caret-double-down", categories: [IconCategory.ARROWS], tags: [ "chevron", "directional", "pointer", "pointing", "arrowhead", "triangle", ], Icon: Icons.CaretDoubleDown, }, { name: "caret-double-left", categories: [IconCategory.ARROWS], tags: [ "chevron", "directional", "pointer", "pointing", "arrowhead", "triangle", ], Icon: Icons.CaretDoubleLeft, }, { name: "caret-double-right", categories: [IconCategory.ARROWS], tags: [ "chevron", "directional", "pointer", "pointing", "arrowhead", "triangle", ], Icon: Icons.CaretDoubleRight, }, { name: "caret-circle-up", categories: [IconCategory.ARROWS], tags: [ "chevron", "directional", "pointer", "pointing", "arrowhead", "triangle", ], Icon: Icons.CaretCircleUp, }, { name: "caret-circle-down", categories: [IconCategory.ARROWS], tags: [ "chevron", "directional", "pointer", "pointing", "arrowhead", "triangle", ], Icon: Icons.CaretCircleDown, }, { name: "caret-circle-left", categories: [IconCategory.ARROWS], tags: [ "chevron", "directional", "pointer", "pointing", "arrowhead", "triangle", ], Icon: Icons.CaretCircleLeft, }, { name: "caret-circle-right", categories: [IconCategory.ARROWS], tags: [ "chevron", "directional", "pointer", "pointing", "arrowhead", "triangle", ], Icon: Icons.CaretCircleRight, }, { name: "caret-circle-double-up", categories: [IconCategory.ARROWS], tags: [ "chevron", "directional", "pointer", "pointing", "arrowhead", "triangle", ], Icon: Icons.CaretCircleDoubleUp, }, { name: "caret-circle-double-down", categories: [IconCategory.ARROWS], tags: [ "chevron", "directional", "pointer", "pointing", "arrowhead", "triangle", ], Icon: Icons.CaretCircleDoubleDown, }, { name: "caret-circle-double-left", categories: [IconCategory.ARROWS], tags: [ "chevron", "directional", "pointer", "pointing", "arrowhead", "triangle", ], Icon: Icons.CaretCircleDoubleLeft, }, { name: "caret-circle-double-right", categories: [IconCategory.ARROWS], tags: [ "chevron", "directional", "pointer", "pointing", "arrowhead", "triangle", ], Icon: Icons.CaretCircleDoubleRight, }, { name: "cat", categories: [IconCategory.NATURE], tags: ["*updated*", "pets", "animals", "kitty", "kitten"], Icon: Icons.Cat, }, { name: "cell-signal-full", categories: [IconCategory.SYSTEM], tags: [ "wireless", "cellular", "phone", "mobile", "network", "connection", "connectivity", "reception", "service", ], Icon: Icons.CellSignalFull, }, { name: "cell-signal-high", categories: [IconCategory.SYSTEM], tags: [ "wireless", "cellular", "phone", "mobile", "network", "connection", "connectivity", "reception", "service", ], Icon: Icons.CellSignalHigh, }, { name: "cell-signal-medium", categories: [IconCategory.SYSTEM], tags: [ "wireless", "cellular", "phone", "mobile", "network", "connection", "connectivity", "reception", "service", ], Icon: Icons.CellSignalMedium, }, { name: "cell-signal-low", categories: [IconCategory.SYSTEM], tags: [ "wireless", "cellular", "phone", "mobile", "network", "connection", "connectivity", "reception", "service", ], Icon: Icons.CellSignalLow, }, { name: "cell-signal-none", categories: [IconCategory.SYSTEM], tags: [ "wireless", "cellular", "phone", "mobile", "network", "connection", "connectivity", "reception", "service", ], Icon: Icons.CellSignalNone, }, { name: "cell-signal-slash", categories: [IconCategory.SYSTEM], tags: [ "wireless", "cellular", "phone", "mobile", "network", "connection", "connectivity", "disconnected", "disabled", "reception", "service", ], Icon: Icons.CellSignalSlash, }, { name: "cell-signal-x", categories: [IconCategory.SYSTEM], tags: [ "*updated*", "wireless", "cellular", "phone", "mobile", "network", "connection", "connectivity", "reception", "disconnected", "errors", "service", ], Icon: Icons.CellSignalX, }, // { // name: "certificate", // categories: [IconCategory.DEVELOPMENT, IconCategory.OFFICE], // tags: [ "diploma", "valid", "authentic"], // Icon: Icons.Certificate, // }, { name: "chalkboard", categories: [IconCategory.MAP, IconCategory.OBJECTS], tags: [ "blackboard", "whiteboard", "classroom", "teacher", "education", "school", "college", "university", ], Icon: Icons.Chalkboard, }, { name: "chalkboard-simple", categories: [IconCategory.MAP, IconCategory.OBJECTS], tags: [ "blackboard", "whiteboard", "classroom", "teacher", "education", "school", "college", "university", ], Icon: Icons.ChalkboardSimple, }, { name: "chalkboard-teacher", categories: [IconCategory.MAP, IconCategory.OBJECTS, IconCategory.PEOPLE], tags: [ "blackboard", "whiteboard", "classroom", "education", "school", "college", "university", ], Icon: Icons.ChalkboardTeacher, }, { name: "chart-bar", categories: [IconCategory.FINANCE], tags: [ "graphs", "graphing", "charts", "statistics", "histogram", "analyze", "analysis", ], Icon: Icons.ChartBar, }, { name: "chart-bar-horizontal", categories: [IconCategory.FINANCE], tags: [ "graphs", "graphing", "charts", "statistics", "histogram", "analyze", "analysis", ], Icon: Icons.ChartBarHorizontal, }, { name: "chart-line", categories: [IconCategory.FINANCE], tags: [ "graphs", "graphing", "charts", "statistics", "analyze", "analysis", "stocks", ], Icon: Icons.ChartLine, }, { name: "chart-line-up", categories: [IconCategory.FINANCE], tags: [ "graphs", "graphing", "charts", "statistics", "analyze", "analysis", "stocks", ], Icon: Icons.ChartLineUp, }, { name: "chart-pie", categories: [IconCategory.FINANCE], tags: [ "graphs", "graphing", "charts", "statistics", "circle", "analyze", "analysis", ], Icon: Icons.ChartPie, }, { name: "chart-pie-slice", categories: [IconCategory.FINANCE], tags: [ "graphs", "graphing", "charts", "statistics", "circle", "analyze", "analysis", ], Icon: Icons.ChartPieSlice, }, { name: "chat", categories: [IconCategory.COMMUNICATION], tags: [ "send", "sent", "messages", "messaging", "sms", "texting", "comment", "square", "bubble", ], Icon: Icons.Chat, }, { name: "chat-dots", categories: [IconCategory.COMMUNICATION], tags: [ "send", "sent", "messages", "messaging", "sms", "texting", "comment", "square", "bubble", ], Icon: Icons.ChatDots, }, { name: "chat-text", categories: [IconCategory.COMMUNICATION], tags: [ "send", "sent", "messages", "messaging", "sms", "texting", "comment", "square", "bubble", ], Icon: Icons.ChatText, }, { name: "chats", categories: [IconCategory.COMMUNICATION], tags: [ "send", "sent", "messages", "messaging", "sms", "texting", "comment", "square", "bubble", ], Icon: Icons.Chats, }, { name: "chat-centered", categories: [IconCategory.COMMUNICATION], tags: [ "send", "sent", "messages", "messaging", "sms", "texting", "comment", "square", "bubble", ], Icon: Icons.ChatCentered, }, { name: "chat-centered-dots", categories: [IconCategory.COMMUNICATION], tags: [ "send", "sent", "messages", "messaging", "sms", "texting", "comment", "square", "bubble", ], Icon: Icons.ChatCenteredDots, }, { name: "chat-centered-text", categories: [IconCategory.COMMUNICATION], tags: [ "send", "sent", "messages", "messaging", "sms", "texting", "comment", "square", "bubble", ], Icon: Icons.ChatCenteredText, }, { name: "chat-circle", categories: [IconCategory.COMMUNICATION], tags: [ "send", "sent", "messages", "messaging", "sms", "texting", "comment", "round", "bubble", ], Icon: Icons.ChatCircle, }, { name: "chat-circle-dots", categories: [IconCategory.COMMUNICATION], tags: [ "send", "sent", "messages", "messaging", "sms", "texting", "comment", "round", "bubble", ], Icon: Icons.ChatCircleDots, }, { name: "chat-circle-text", categories: [IconCategory.COMMUNICATION], tags: [ "send", "sent", "messages", "messaging", "sms", "texting", "comment", "round", "bubble", ], Icon: Icons.ChatCircleText, }, { name: "chats-circle", categories: [IconCategory.COMMUNICATION], tags: [ "send", "sent", "messages", "messaging", "sms", "texting", "comment", "round", "bubble", ], Icon: Icons.ChatsCircle, }, { name: "chat-teardrop", categories: [IconCategory.COMMUNICATION], tags: [ "send", "sent", "messages", "messaging", "sms", "texting", "comment", "bubble", ], Icon: Icons.ChatTeardrop, }, { name: "chat-teardrop-dots", categories: [IconCategory.COMMUNICATION], tags: [ "send", "sent", "messages", "messaging", "sms", "texting", "comment", "bubble", ], Icon: Icons.ChatTeardropDots, }, { name: "chat-teardrop-text", categories: [IconCategory.COMMUNICATION], tags: [ "send", "sent", "messages", "messaging", "sms", "texting", "comment", "bubble", ], Icon: Icons.ChatTeardropText, }, { name: "chats-teardrop", categories: [IconCategory.COMMUNICATION], tags: [ "send", "sent", "messages", "messaging", "sms", "texting", "comment", "bubble", ], Icon: Icons.ChatsTeardrop, }, { name: "check", categories: [IconCategory.SYSTEM], tags: ["todo", "to-do", "task", "list", "checkbox", "ok", "done"], Icon: Icons.Check, }, { name: "check-circle", categories: [IconCategory.SYSTEM], tags: ["todo", "to-do", "task", "list", "checkbox", "round", "ok", "done"], Icon: Icons.CheckCircle, }, { name: "check-square", categories: [IconCategory.SYSTEM], tags: [ "todo", "to-do", "task", "list", "checkbox", "rectangle", "ok", "done", ], Icon: Icons.CheckSquare, }, { name: "check-square-offset", categories: [IconCategory.SYSTEM], tags: [ "todo", "to-do", "task", "list", "checkbox", "rectangle", "ok", "done", ], Icon: Icons.CheckSquareOffset, }, { name: "checks", categories: [IconCategory.SYSTEM], tags: ["todo", "task", "to-do", "list", "checkbox", "ok", "done"], Icon: Icons.Checks, }, // { // name: "child", // categories: [IconCategory.PEOPLE], // tags: [ "kids", "children", "family"], // Icon: Icons.Child, // }, { name: "circle", categories: [IconCategory.DESIGN], tags: ["round", "shapes", "polygons"], Icon: Icons.Circle, }, { name: "circle-dashed", categories: [IconCategory.DESIGN], tags: ["missing", "round", "shapes", "polygons"], Icon: Icons.CircleDashed, }, { name: "circle-half", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["*updated*", "round", "shapes", "contrast", "brightness"], Icon: Icons.CircleHalf, }, { name: "circle-half-tilt", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["*updated*", "round", "shapes", "contrast", "brightness"], Icon: Icons.CircleHalfTilt, }, { name: "circle-notch", categories: [IconCategory.SYSTEM], tags: [ "*new*", "round", "shapes", "loading", "loader", "spinner", "waiting", "progress", ], Icon: Icons.CircleNotch, }, { name: "circle-wavy", categories: [IconCategory.DESIGN], tags: ["badge", "verified", "verification", "shapes", "polygons"], Icon: Icons.CircleWavy, }, { name: "circle-wavy-check", categories: [IconCategory.DESIGN], tags: ["badge", "verified", "verification", "shapes", "polygons"], Icon: Icons.CircleWavyCheck, }, { name: "circle-wavy-question", categories: [IconCategory.DESIGN], tags: ["badge", "unverified", "verification", "shapes", "polygons"], Icon: Icons.CircleWavyQuestion, }, { name: "circle-wavy-warning", categories: [IconCategory.DESIGN], tags: [ "badge", "unverified", "verification", "errors", "shapes", "polygons", ], Icon: Icons.CircleWavyWarning, }, { name: "circles-three", categories: [IconCategory.DESIGN], tags: ["round", "shapes", "polygons", "3", "asana"], Icon: Icons.CirclesThree, }, { name: "circles-three-plus", categories: [IconCategory.DESIGN], tags: ["round", "shapes", "polygons", "3", "+"], Icon: Icons.CirclesThreePlus, }, { name: "circles-four", categories: [IconCategory.DESIGN], tags: ["round", "shapes", "polygons", "4"], Icon: Icons.CirclesFour, }, { name: "clipboard", categories: [IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.SYSTEM], tags: ["copy", "copied", "checklist"], Icon: Icons.Clipboard, }, { name: "clipboard-text", categories: [IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.SYSTEM], tags: ["copy", "copied", "checklist"], Icon: Icons.ClipboardText, }, { name: "clock", categories: [IconCategory.SYSTEM], tags: ["times", "timer", "alarm", "schedule", "events", "watch"], Icon: Icons.Clock, }, { name: "clock-afternoon", categories: [IconCategory.SYSTEM], tags: ["times", "timer", "alarm", "schedule", "events", "watch"], Icon: Icons.ClockAfternoon, }, { name: "clock-clockwise", categories: [IconCategory.SYSTEM], tags: [ "times", "timer", "alarm", "schedule", "events", "restore", "fast forward", "update", ], Icon: Icons.ClockClockwise, }, { name: "clock-counter-clockwise", categories: [IconCategory.SYSTEM], tags: [ "times", "timer", "alarm", "schedule", "events", "backup", "rewind", "history", ], Icon: Icons.ClockCounterClockwise, }, { name: "closed-captioning", categories: [IconCategory.MEDIA], tags: [ "subtitles", "television", "tv", "transcribed", "transcription", "accessibility", "a11y", ], Icon: Icons.ClosedCaptioning, }, // { // name: "closed-captioning-slash", // categories: [IconCategory.MEDIA], // tags: [ // // "subtitles", // "television", // "tv", // "transcribed", // "transcription", // "accessibility", // "a11y", // "disabled", // ], // Icon: Icons.ClosedCaptioningSlash, // }, { name: "cloud", categories: [IconCategory.SYSTEM, IconCategory.WEATHER], tags: [ "*updated*", "serverless", "backup", "storage", "meteorology", "cloudy", "overcast", ], Icon: Icons.Cloud, }, { name: "cloud-arrow-down", categories: [IconCategory.SYSTEM], tags: ["*updated*", "serverless", "backup", "storage", "download"], Icon: Icons.CloudArrowDown, }, { name: "cloud-arrow-up", categories: [IconCategory.SYSTEM], tags: ["*updated*", "serverless", "backup", "storage", "upload"], Icon: Icons.CloudArrowUp, }, { name: "cloud-check", categories: [IconCategory.SYSTEM], tags: [ "*updated*", "serverless", "backup", "storage", "sync", "synchronized", ], Icon: Icons.CloudCheck, }, { name: "cloud-slash", categories: [IconCategory.SYSTEM], tags: ["serverless", "backup", "storage", "sync", "disabled"], Icon: Icons.CloudSlash, }, { name: "cloud-fog", categories: [IconCategory.WEATHER], tags: [ "*updated*", "meteorology", "cloudy", "overcast", "foggy", "misty", "haze", "hazy", ], Icon: Icons.CloudFog, }, { name: "cloud-lightning", categories: [IconCategory.WEATHER], tags: [ "*updated*", "meteorology", "cloudy", "overcast", "stormy", "thunderstorm", ], Icon: Icons.CloudLightning, }, { name: "cloud-moon", categories: [IconCategory.WEATHER], tags: ["meteorology", "cloudy", "partly cloudy", "night", "evening"], Icon: Icons.CloudMoon, }, { name: "cloud-rain", categories: [IconCategory.WEATHER], tags: [ "*updated*", "meteorology", "cloudy", "rainy", "raining", "stormy", "rainstorm", ], Icon: Icons.CloudRain, }, { name: "cloud-snow", categories: [IconCategory.WEATHER], tags: [ "*updated*", "meteorology", "cloudy", "snowy", "snowing", "stormy", "snowstorm", ], Icon: Icons.CloudSnow, }, { name: "cloud-sun", categories: [IconCategory.WEATHER], tags: ["meteorology", "cloudy", "partly cloudy", "partly sunny"], Icon: Icons.CloudSun, }, { name: "club", categories: [IconCategory.GAMES], tags: ["clubs", "suits", "cards", "gambling", "casino", "gaming"], Icon: Icons.Club, }, { name: "coat-hanger", categories: [IconCategory.COMMERCE], tags: ["*new*", "clothing", "clothes", "closet"], Icon: Icons.CoatHanger, }, { name: "code", categories: [IconCategory.DEVELOPMENT, IconCategory.EDITOR], tags: ["angle brackets", "angle braces", "snippets"], Icon: Icons.Code, }, { name: "code-simple", categories: [IconCategory.DEVELOPMENT, IconCategory.EDITOR], tags: ["angle brackets", "angle braces", "snippets"], Icon: Icons.CodeSimple, }, { name: "codepen-logo", categories: [IconCategory.BRAND, IconCategory.DEVELOPMENT], tags: ["*new*", "ide", "logos"], Icon: Icons.CodepenLogo, }, { name: "codesandbox-logo", categories: [IconCategory.BRAND, IconCategory.DEVELOPMENT], tags: ["*new*", "ide", "logos"], Icon: Icons.CodesandboxLogo, }, { name: "coffee", categories: [IconCategory.COMMERCE, IconCategory.OBJECTS], tags: [ "tea", "java", "beverages", "drinks", "cafe", "cup", "mug", "espresso", "cappuccino", "latte", "places", "locations", "bars", "restaurants", "food", "dining", ], Icon: Icons.Coffee, }, { name: "coin", categories: [IconCategory.COMMERCE, IconCategory.FINANCE], tags: [ "coins", "cents", "change", "money", "currency", "payment", "paying", "purchase", "price", "sell", ], Icon: Icons.Coin, }, { name: "coin-vertical", categories: [IconCategory.COMMERCE, IconCategory.FINANCE], tags: [ "*new*", "cents", "change", "money", "currency", "payment", "paying", "purchase", "price", "sell", ], Icon: Icons.CoinVertical, }, { name: "coins", categories: [IconCategory.COMMERCE, IconCategory.FINANCE], tags: [ "*new*", "cents", "change", "money", "currency", "payment", "paying", "purchase", "price", "sell", ], Icon: Icons.Coins, }, { name: "columns", categories: [IconCategory.DESIGN], tags: ["2", "shapes", "polygons", "box", "stack", "list", "table", "cards"], Icon: Icons.Columns, }, { name: "command", categories: [IconCategory.EDITOR, IconCategory.SYSTEM], tags: [ "apple", "keyboard", "shortcut", "modifier", "looped square", "Bowen knot", "Saint John's Arms", ], Icon: Icons.Command, }, { name: "compass", categories: [IconCategory.MAP, IconCategory.OBJECTS], tags: ["navigation", "directions", "maps", "safari", "apple"], Icon: Icons.Compass, }, { name: "computer-tower", categories: [IconCategory.DEVELOPMENT, IconCategory.OBJECTS], tags: ["desktop", "pc", "imac"], Icon: Icons.ComputerTower, }, { name: "confetti", categories: [IconCategory.COMMUNICATION], tags: ["*new*", "tada", "party", "emoji"], Icon: Icons.Confetti, }, { name: "cookie", categories: [ IconCategory.MAP, IconCategory.OBJECTS, IconCategory.DEVELOPMENT, ], tags: ["privacy", "dessert", "food", "dining"], Icon: Icons.Cookie, }, { name: "cooking-pot", categories: [IconCategory.MAP, IconCategory.OBJECTS], tags: ["stew", "kitchen", "steaming", "restaurants", "food", "dining"], Icon: Icons.CookingPot, }, { name: "copy", categories: [IconCategory.EDITOR, IconCategory.SYSTEM], tags: ["duplicated", "copied", "clipboard"], Icon: Icons.Copy, }, { name: "copy-simple", categories: [IconCategory.EDITOR, IconCategory.SYSTEM], tags: ["duplicated", "copied", "clipboard"], Icon: Icons.CopySimple, }, { name: "copyright", categories: [IconCategory.COMMERCE, IconCategory.MEDIA], tags: ["©", "intellectual property", "copr.", "symbol"], Icon: Icons.Copyright, }, { name: "copyleft", categories: [IconCategory.COMMERCE, IconCategory.MEDIA], tags: ["*new*", "🄯", "intellectual property", "copr.", "symbol"], Icon: Icons.Copyleft, }, { name: "corners-in", categories: [IconCategory.SYSTEM], tags: ["collapse", "windowed", "minimized"], Icon: Icons.CornersIn, }, { name: "corners-out", categories: [IconCategory.SYSTEM], tags: ["expand", "fullscreen", "maximized"], Icon: Icons.CornersOut, }, { name: "cpu", categories: [IconCategory.DEVELOPMENT], tags: ["processor", "microchip", "computer", "circuit"], Icon: Icons.Cpu, }, { name: "credit-card", categories: [IconCategory.COMMERCE, IconCategory.FINANCE], tags: [ "debit", "visa", "mastercard", "money", "payment", "paying", "purchase", "swipe", ], Icon: Icons.CreditCard, }, { name: "crop", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["photography", "clip", "screenshots"], Icon: Icons.Crop, }, { name: "crosshair", categories: [IconCategory.MAP, IconCategory.SYSTEM], tags: ["geolocation", "gps", "aiming", "targeting"], Icon: Icons.Crosshair, }, { name: "crosshair-simple", categories: [IconCategory.MAP, IconCategory.SYSTEM], tags: ["geolocation", "gps", "aiming", "targeting"], Icon: Icons.CrosshairSimple, }, { name: "crown", categories: [IconCategory.GAMES, IconCategory.OBJECTS], tags: ["king", "queen", "royalty", "monarch", "ruler", "leader"], Icon: Icons.Crown, }, { name: "crown-simple", categories: [IconCategory.GAMES, IconCategory.OBJECTS], tags: ["king", "queen", "royalty", "monarch", "ruler", "leader"], Icon: Icons.CrownSimple, }, { name: "cube", categories: [IconCategory.DESIGN, IconCategory.GAMES, IconCategory.OBJECTS], tags: ["square", "box", "3d", "volume", "blocks"], Icon: Icons.Cube, }, { name: "currency-dollar", categories: [IconCategory.COMMERCE, IconCategory.FINANCE], tags: ["money", "USD", "payment", "paying", "purchase"], Icon: Icons.CurrencyDollar, }, { name: "currency-dollar-simple", categories: [IconCategory.COMMERCE, IconCategory.FINANCE], tags: ["money", "USD", "payment", "paying", "purchase"], Icon: Icons.CurrencyDollarSimple, }, { name: "currency-btc", categories: [IconCategory.COMMERCE, IconCategory.FINANCE], tags: [ "money", "BTC", "bitcoin", "crypto", "cryptocurrency", "payment", "paying", "purchase", ], Icon: Icons.CurrencyBtc, }, { name: "currency-cny", categories: [IconCategory.COMMERCE, IconCategory.FINANCE], tags: ["money", "yuan", "payment", "paying", "purchase"], Icon: Icons.CurrencyCny, }, { name: "currency-eth", categories: [IconCategory.COMMERCE, IconCategory.FINANCE], tags: [ "*new*", "money", "ethereum", "crypto", "cryptocurrency", "payment", "paying", "purchase", ], Icon: Icons.CurrencyEth, }, { name: "currency-eur", categories: [IconCategory.COMMERCE, IconCategory.FINANCE], tags: ["money", "euros", "payment", "paying", "purchase"], Icon: Icons.CurrencyEur, }, { name: "currency-gbp", categories: [IconCategory.COMMERCE, IconCategory.FINANCE], tags: ["money", "pounds sterling", "payment", "paying", "purchase"], Icon: Icons.CurrencyGbp, }, { name: "currency-inr", categories: [IconCategory.COMMERCE, IconCategory.FINANCE], tags: ["money", "rupees", "payment", "paying", "purchase"], Icon: Icons.CurrencyInr, }, { name: "currency-jpy", categories: [IconCategory.COMMERCE, IconCategory.FINANCE], tags: ["money", "yen", "payment", "paying", "purchase"], Icon: Icons.CurrencyJpy, }, { name: "currency-krw", categories: [IconCategory.COMMERCE, IconCategory.FINANCE], tags: ["money", "won", "payment", "paying", "purchase"], Icon: Icons.CurrencyKrw, }, { name: "currency-kzt", categories: [IconCategory.COMMERCE, IconCategory.FINANCE], tags: [ "*new*", "money", "kazakhstan", "tenge", "payment", "paying", "purchase", ], Icon: Icons.CurrencyKzt, }, { name: "currency-ngn", categories: [IconCategory.COMMERCE, IconCategory.FINANCE], tags: [ "*new*", "money", "nigeria", "naira", "payment", "paying", "purchase", ], Icon: Icons.CurrencyNgn, }, { name: "currency-rub", categories: [IconCategory.COMMERCE, IconCategory.FINANCE], tags: ["money", "rubles", "payment", "paying", "purchase"], Icon: Icons.CurrencyRub, }, { name: "currency-circle-dollar", categories: [IconCategory.COMMERCE, IconCategory.FINANCE], tags: ["money", "USD", "payment", "paying", "purchase"], Icon: Icons.CurrencyCircleDollar, }, { name: "cursor", categories: [IconCategory.DESIGN, IconCategory.SYSTEM], tags: ["pointer", "arrowhead", "mouse", "click"], Icon: Icons.Cursor, }, // { // name: "cursor-click", // categories: [IconCategory.DESIGN, IconCategory.SYSTEM], // tags: ["pointer", "arrowhead", "mouse"], // Icon: Icons.CursorClick, // }, { name: "cursor-text", categories: [IconCategory.EDITOR, IconCategory.SYSTEM], tags: ["*new*", "i-beam", "input", "select"], Icon: Icons.CursorText, }, { name: "cylinder", categories: [IconCategory.DESIGN], tags: ["*new*", "shapes", "tube"], Icon: Icons.Cylinder, }, { name: "database", categories: [IconCategory.DEVELOPMENT, IconCategory.SYSTEM], tags: [ "saved", "saving", "archived", "archiving", "archival", "hard disk", "storage", "hdd", "servers", "databases", ], Icon: Icons.Database, }, { name: "desktop", categories: [IconCategory.DEVELOPMENT, IconCategory.OBJECTS], tags: ["computer", "pc", "imac", "tower"], Icon: Icons.Desktop, }, { name: "desktop-tower", categories: [IconCategory.DEVELOPMENT, IconCategory.OBJECTS], tags: ["computer", "pc", "imac"], Icon: Icons.DesktopTower, }, { name: "detective", categories: [IconCategory.PEOPLE, IconCategory.SYSTEM], tags: ["*new*", "incognito", "police", "law enforcement", "spy", "secret"], Icon: Icons.Detective, }, { name: "device-mobile", categories: [IconCategory.OBJECTS], tags: ["cellphone", "cellular"], Icon: Icons.DeviceMobile, }, { name: "device-mobile-camera", categories: [IconCategory.OBJECTS], tags: ["cellphone", "cellular"], Icon: Icons.DeviceMobileCamera, }, { name: "device-mobile-speaker", categories: [IconCategory.OBJECTS], tags: ["cellphone", "cellular"], Icon: Icons.DeviceMobileSpeaker, }, { name: "device-tablet", categories: [IconCategory.OBJECTS], tags: ["cellphone", "cellular", "ipad", "phablet"], Icon: Icons.DeviceTablet, }, { name: "device-tablet-camera", categories: [IconCategory.OBJECTS], tags: ["cellphone", "cellular", "ipad", "phablet"], Icon: Icons.DeviceTabletCamera, }, { name: "device-tablet-speaker", categories: [IconCategory.OBJECTS], tags: ["cellphone", "cellular", "ipad", "phablet"], Icon: Icons.DeviceTabletSpeaker, }, { name: "diamond", categories: [IconCategory.DESIGN, IconCategory.GAMES], tags: [ "rectangle", "shapes", "polygons", "diamonds", "suits", "cards", "gambling", "casino", "gaming", ], Icon: Icons.Diamond, }, { name: "diamonds-four", categories: [IconCategory.DESIGN], tags: ["*new*", "shapes", "grid"], Icon: Icons.DiamondsFour, }, // { // name: "dice", // categories: [IconCategory.OTHER], // tags: [ "die", "rolling", "gamble", "gambling", "casino", "gaming"], // Icon: Icons.Dice, // }, { name: "dice-one", categories: [IconCategory.GAMES, IconCategory.OBJECTS], tags: ["die", "rolling", "gamble", "gambling", "casino", "gaming", "1"], Icon: Icons.DiceOne, }, { name: "dice-two", categories: [IconCategory.GAMES, IconCategory.OBJECTS], tags: ["die", "rolling", "gamble", "gambling", "casino", "gaming", "2"], Icon: Icons.DiceTwo, }, { name: "dice-three", categories: [IconCategory.GAMES, IconCategory.OBJECTS], tags: ["die", "rolling", "gamble", "gambling", "casino", "gaming", "3"], Icon: Icons.DiceThree, }, { name: "dice-four", categories: [IconCategory.GAMES, IconCategory.OBJECTS], tags: ["die", "rolling", "gamble", "gambling", "casino", "gaming", "4"], Icon: Icons.DiceFour, }, { name: "dice-five", categories: [IconCategory.GAMES, IconCategory.OBJECTS], tags: ["die", "rolling", "gamble", "gambling", "casino", "gaming", "5"], Icon: Icons.DiceFive, }, { name: "dice-six", categories: [IconCategory.GAMES, IconCategory.OBJECTS], tags: ["die", "rolling", "gamble", "gambling", "casino", "gaming", "6"], Icon: Icons.DiceSix, }, { name: "disc", categories: [ IconCategory.DEVELOPMENT, IconCategory.MEDIA, IconCategory.OBJECTS, ], tags: ["cd-rom", "compact disk", "album", "record"], Icon: Icons.Disc, }, { name: "discord-logo", categories: [IconCategory.BRAND, IconCategory.COMMUNICATION], tags: ["logos", "messages", "messaging", "chat"], Icon: Icons.DiscordLogo, }, { name: "divide", categories: [IconCategory.DEVELOPMENT, IconCategory.FINANCE], tags: [ "division", "divisor", "dividend", "quotient", "mathematics", "arithmetic", "calculator", ], Icon: Icons.Divide, }, { name: "dog", categories: [IconCategory.NATURE], tags: ["pets", "animals", "puppy"], Icon: Icons.Dog, }, { name: "door", categories: [IconCategory.OBJECTS], tags: ["entrance", "exit"], Icon: Icons.Door, }, { name: "dots-nine", categories: [IconCategory.DESIGN], tags: ["grid", "circles", "shapes", "polygons", "9"], Icon: Icons.DotsNine, }, { name: "dots-six", categories: [IconCategory.SYSTEM], tags: ["drag handle", "knurling", "circles", "shapes", "polygons", "6"], Icon: Icons.DotsSix, }, { name: "dots-six-vertical", categories: [IconCategory.SYSTEM], tags: ["drag handle", "knurling", "circles", "shapes", "polygons", "6"], Icon: Icons.DotsSixVertical, }, { name: "dots-three", categories: [IconCategory.SYSTEM], tags: [ "menu", "overflow", "circles", "shapes", "polygons", "3", "ellipsis", "ellipses", "more", ], Icon: Icons.DotsThree, }, { name: "dots-three-vertical", categories: [IconCategory.SYSTEM], tags: [ "menu", "overflow", "circles", "shapes", "polygons", "3", "ellipsis", "ellipses", "more", ], Icon: Icons.DotsThreeVertical, }, { name: "dots-three-outline", categories: [IconCategory.SYSTEM], tags: [ "menu", "overflow", "circles", "shapes", "polygons", "3", "ellipsis", "ellipses", "more", ], Icon: Icons.DotsThreeOutline, }, { name: "dots-three-outline-vertical", categories: [IconCategory.SYSTEM], tags: [ "menu", "overflow", "circles", "shapes", "polygons", "3", "ellipsis", "ellipses", "more", ], Icon: Icons.DotsThreeOutlineVertical, }, { name: "dots-three-circle", categories: [IconCategory.SYSTEM], tags: [ "menu", "overflow", "circles", "shapes", "polygons", "3", "ellipsis", "ellipses", "more", ], Icon: Icons.DotsThreeCircle, }, { name: "dots-three-circle-vertical", categories: [IconCategory.SYSTEM], tags: [ "menu", "overflow", "circles", "shapes", "polygons", "3", "ellipsis", "ellipses", "more", ], Icon: Icons.DotsThreeCircleVertical, }, { name: "download", categories: [IconCategory.SYSTEM], tags: [ "*updated*", "saved", "saving", "archived", "archiving", "archival", "downloaded", "downloading", "hard drive", "disk", ], Icon: Icons.Download, }, { name: "download-simple", categories: [IconCategory.SYSTEM], tags: [ "saved", "saving", "archived", "archiving", "archival", "downloaded", "downloading", "hard drive", "disk", ], Icon: Icons.DownloadSimple, }, { name: "dribbble-logo", categories: [IconCategory.BRAND, IconCategory.DESIGN], tags: ["*updated*", "logos", "round", "basketball", "sports", "design"], Icon: Icons.DribbbleLogo, }, { name: "drop", categories: [IconCategory.NATURE, IconCategory.WEATHER], tags: [ "droplet", "teardrop", "raindrop", "raining", "meteorology", "water", ], Icon: Icons.Drop, }, { name: "drop-half", categories: [ IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.NATURE, IconCategory.WEATHER, ], tags: [ "*updated*", "droplet", "teardrop", "raindrop", "humidity", "water", "contrast", "brightness", ], Icon: Icons.DropHalf, }, { name: "drop-half-bottom", categories: [ IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.NATURE, IconCategory.WEATHER, ], tags: [ "*new*", "droplet", "teardrop", "raindrop", "humidity", "water", "contrast", "brightness", ], Icon: Icons.DropHalfBottom, }, // { // name: "dropbox-logo", // categories: [IconCategory.BRAND], // tags: [ "cloud", "backup"], // Icon: Icons.DropboxLogo, // }, { name: "ear", categories: [IconCategory.MEDIA, IconCategory.SYSTEM], tags: ["hearing", "audio", "sound"], Icon: Icons.Ear, }, { name: "ear-slash", categories: [IconCategory.MEDIA, IconCategory.SYSTEM], tags: ["hearing", "audio", "sound", "mute", "accessible"], Icon: Icons.EarSlash, }, { name: "egg", categories: [IconCategory.COMMERCE, IconCategory.NATURE], tags: ["*new*", "chicken", "food", "meal", "baby", "hatch"], Icon: Icons.Egg, }, { name: "egg-crack", categories: [IconCategory.COMMERCE, IconCategory.NATURE], tags: ["*new*", "chicken", "food", "meal", "baby", "hatch", "break"], Icon: Icons.EggCrack, }, { name: "eject", categories: [IconCategory.MEDIA], tags: ["disconnect"], Icon: Icons.Eject, }, { name: "eject-simple", categories: [IconCategory.MEDIA], tags: ["disconnect"], Icon: Icons.EjectSimple, }, { name: "equalizer", categories: [IconCategory.MEDIA, IconCategory.SYSTEM], tags: ["*new*", "music", "audio", "meter", "volume", "spectrum", "eq"], Icon: Icons.Equalizer, }, { name: "eraser", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["write", "writing", "editing", "undo", "deleted"], Icon: Icons.Eraser, }, { name: "envelope", categories: [IconCategory.COMMUNICATION], tags: ["mail", "email", "send", "sent", "message", "post", "letter"], Icon: Icons.Envelope, }, { name: "envelope-open", categories: [IconCategory.COMMUNICATION], tags: [ "mail", "email", "send", "sent", "message", "read", "post", "letter", ], Icon: Icons.EnvelopeOpen, }, { name: "envelope-simple", categories: [IconCategory.COMMUNICATION], tags: ["mail", "email", "send", "sent", "message", "post", "letter"], Icon: Icons.EnvelopeSimple, }, { name: "envelope-simple-open", categories: [IconCategory.COMMUNICATION], tags: [ "mail", "email", "send", "sent", "message", "read", "post", "letter", ], Icon: Icons.EnvelopeSimpleOpen, }, { name: "equals", categories: [IconCategory.DEVELOPMENT, IconCategory.FINANCE], tags: [ "=", "equality", "equivalent", "equivalence", "mathematics", "arithmetic", "calculator", ], Icon: Icons.Equals, }, { name: "exam", categories: [IconCategory.OBJECTS], tags: ["*new*", "text", "examination", "paper", "school", "grade"], Icon: Icons.Exam, }, { name: "export", categories: [IconCategory.COMMUNICATION, IconCategory.SYSTEM], tags: ["share", "send to", "arrows"], Icon: Icons.Export, }, { name: "eye", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["visible", "hidden", "show", "hide", "visibility", "view"], Icon: Icons.Eye, }, { name: "eye-slash", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: [ "visible", "hidden", "show", "hide", "visibility", "view", "invisible", "eyelashes", "disabled", "private", ], Icon: Icons.EyeSlash, }, { name: "eye-closed", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: [ "visible", "hidden", "show", "hide", "visibility", "view", "invisible", "private", ], Icon: Icons.EyeClosed, }, { name: "eyedropper", categories: [ IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.OBJECTS, ], tags: ["colors", "color picker", "sample", "arts"], Icon: Icons.Eyedropper, }, { name: "eyedropper-sample", categories: [ IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.OBJECTS, ], tags: ["*new*", "colors", "color picker", "arts"], Icon: Icons.EyedropperSample, }, { name: "eyeglasses", categories: [IconCategory.HEALTH, IconCategory.OBJECTS], tags: ["*new*", "vision", "spectacles"], Icon: Icons.Eyeglasses, }, { name: "face-mask", categories: [IconCategory.HEALTH], tags: ["ppe", "facemask", "covid-19", "coronavirus", "flu", "cold"], Icon: Icons.FaceMask, }, { name: "facebook-logo", categories: [IconCategory.BRAND, IconCategory.COMMUNICATION], tags: ["*updated*", "logos", "social media"], Icon: Icons.FacebookLogo, }, { name: "factory", categories: [IconCategory.COMMERCE, IconCategory.MAP], tags: ["industry", "manufacture", "buildings", "places", "locations"], Icon: Icons.Factory, }, { name: "faders", categories: [IconCategory.MEDIA, IconCategory.SYSTEM], tags: [ "music", "audio", "sliders", "filters", "equalizer", "volume", "settings", "preferences", ], Icon: Icons.Faders, }, { name: "faders-horizontal", categories: [IconCategory.MEDIA, IconCategory.SYSTEM], tags: [ "music", "audio", "sliders", "filters", "equalizer", "volume", "settings", "preferences", ], Icon: Icons.FadersHorizontal, }, // { // name: "family", // categories: [IconCategory.PEOPLE], // tags: [ "group", "community", "society", "parents", "children"], // Icon: Icons.Family, // }, { name: "fast-forward", categories: [IconCategory.MEDIA], tags: ["audio", "music", "seek", "scrub", "scan", "ahead", "skip"], Icon: Icons.FastForward, }, { name: "fast-forward-circle", categories: [IconCategory.MEDIA], tags: ["audio", "music", "seek", "scrub", "scan", "ahead", "skip"], Icon: Icons.FastForwardCircle, }, { name: "figma-logo", categories: [IconCategory.BRAND, IconCategory.DESIGN], tags: [ "logos", "drawing", "art", "illustration", "ui", "interface", "prototype", "prototyping", ], Icon: Icons.FigmaLogo, }, { name: "file", categories: [IconCategory.OFFICE, IconCategory.EDITOR], tags: ["documents", "files", "save", "write", "page"], Icon: Icons.File, }, { name: "file-arrow-up", categories: [IconCategory.OFFICE, IconCategory.EDITOR], tags: [ "documents", "files", "save", "write", "upload", "directional", "pointer", "pointing", "arrowhead", ], Icon: Icons.FileArrowUp, }, { name: "file-arrow-down", categories: [IconCategory.OFFICE, IconCategory.EDITOR], tags: [ "documents", "files", "save", "write", "download", "directional", "pointer", "pointing", "arrowhead", ], Icon: Icons.FileArrowDown, }, { name: "file-audio", categories: [IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.MEDIA], tags: ["*new*", "documents", "music", "sound"], Icon: Icons.FileAudio, }, { name: "file-plus", categories: [IconCategory.OFFICE, IconCategory.EDITOR], tags: ["documents", "files", "save", "write", "add", "new", "create", "+"], Icon: Icons.FilePlus, }, { name: "file-minus", categories: [IconCategory.OFFICE, IconCategory.EDITOR], tags: ["documents", "files", "delete", "write", "remove", "-"], Icon: Icons.FileMinus, }, { name: "file-cloud", categories: [IconCategory.OFFICE, IconCategory.EDITOR], tags: ["*new*", "documents", "sync"], Icon: Icons.FileCloud, }, { name: "file-code", categories: [ IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.DEVELOPMENT, ], tags: ["*new*", "documents"], Icon: Icons.FileCode, }, { name: "file-css", categories: [ IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.DEVELOPMENT, ], tags: ["*new*", "documents", "code"], Icon: Icons.FileCss, }, { name: "file-csv", categories: [IconCategory.OFFICE, IconCategory.EDITOR], tags: ["*new*", "documents", "data"], Icon: Icons.FileCsv, }, { name: "file-doc", categories: [IconCategory.OFFICE, IconCategory.EDITOR], tags: ["*new*", "documents", "word", "microsoft"], Icon: Icons.FileDoc, }, { name: "file-dotted", categories: [IconCategory.OFFICE, IconCategory.EDITOR], tags: ["documents", "files", "browse", "draft", "open"], Icon: Icons.FileDotted, }, { name: "file-html", categories: [ IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.DEVELOPMENT, ], tags: ["*new*", "documents", "code"], Icon: Icons.FileHtml, }, { name: "file-image", categories: [IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.MEDIA], tags: ["*new*", "documents", "pictures", "photograph"], Icon: Icons.FileImage, }, { name: "file-jpg", categories: [IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.MEDIA], tags: ["*new*", "documents", "pictures", "photograph", "jpeg"], Icon: Icons.FileJpg, }, { name: "file-js", categories: [ IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.DEVELOPMENT, ], tags: ["*new*", "documents", "code", "javascript"], Icon: Icons.FileJs, }, { name: "file-jsx", categories: [ IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.DEVELOPMENT, ], tags: ["*new*", "documents", "code", "javascript"], Icon: Icons.FileJsx, }, { name: "file-lock", categories: [IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.SYSTEM], tags: ["*new*", "documents", "secure", "locked", "private"], Icon: Icons.FileLock, }, { name: "file-pdf", categories: [IconCategory.OFFICE, IconCategory.EDITOR], tags: ["*updated*", "documents", "files", "acrobat"], Icon: Icons.FilePdf, }, { name: "file-png", categories: [IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.MEDIA], tags: ["*new*", "documents", "pictures", "photograph"], Icon: Icons.FilePng, }, { name: "file-ppt", categories: [IconCategory.OFFICE, IconCategory.EDITOR], tags: ["*new*", "documents", "powerpoint", "microsoft"], Icon: Icons.FilePpt, }, { name: "file-rs", categories: [ IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.DEVELOPMENT, ], tags: ["*new*", "documents", "code", "rust"], Icon: Icons.FileRs, }, { name: "file-search", categories: [IconCategory.OFFICE, IconCategory.EDITOR], tags: ["documents", "files", "find", "locate", "browse", "missing"], Icon: Icons.FileSearch, }, { name: "file-text", categories: [IconCategory.OFFICE, IconCategory.EDITOR], tags: ["documents", "files", "save", "write"], Icon: Icons.FileText, }, { name: "file-ts", categories: [ IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.DEVELOPMENT, ], tags: ["*new*", "documents", "code", "typescript"], Icon: Icons.FileTs, }, { name: "file-tsx", categories: [ IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.DEVELOPMENT, ], tags: ["*new*", "documents", "code", "typescript"], Icon: Icons.FileTsx, }, { name: "file-video", categories: [IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.MEDIA], tags: ["*new*", "documents", "movie"], Icon: Icons.FileVideo, }, { name: "file-vue", categories: [ IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.DEVELOPMENT, ], tags: ["*new*", "documents", "code"], Icon: Icons.FileVue, }, { name: "file-x", categories: [IconCategory.OFFICE, IconCategory.EDITOR], tags: ["documents", "files", "cancelled", "deleted", "removed", "errors"], Icon: Icons.FileX, }, { name: "file-xls", categories: [IconCategory.OFFICE, IconCategory.EDITOR], tags: ["*new*", "documents", "excel", "microsoft"], Icon: Icons.FileXls, }, { name: "file-zip", categories: [IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.SYSTEM], tags: ["*new*", "documents", "archive", "compression"], Icon: Icons.FileZip, }, { name: "files", categories: [IconCategory.OFFICE, IconCategory.EDITOR], tags: ["documents", "open", "library"], Icon: Icons.Files, }, { name: "film-script", categories: [IconCategory.OFFICE, IconCategory.MEDIA], tags: ["*new*", "screenplay", "movie"], Icon: Icons.FilmScript, }, { name: "film-slate", categories: [IconCategory.MEDIA], tags: ["*new*", "clapper", "movie"], Icon: Icons.FilmSlate, }, { name: "film-strip", categories: [IconCategory.MEDIA], tags: ["*updated*", "camera", "photography", "darkroom", "movie", "analog"], Icon: Icons.FilmStrip, }, { name: "fingerprint", categories: [IconCategory.SYSTEM], tags: [ "security", "secured", "authentication", "authenticated", "login", "locked", "biometrics", "encrypted", "encryption", ], Icon: Icons.Fingerprint, }, { name: "fingerprint-simple", categories: [IconCategory.SYSTEM], tags: [ "security", "secured", "authentication", "authenticated", "login", "locked", "biometrics", "encrypted", "encryption", ], Icon: Icons.FingerprintSimple, }, { name: "finn-the-human", categories: [IconCategory.GAMES], tags: ["adventure time", "cartoons", "television", "tv", "character"], Icon: Icons.FinnTheHuman, }, { name: "fire", categories: [IconCategory.NATURE, IconCategory.WEATHER], tags: ["flame", "burning", "match", "lighter"], Icon: Icons.Fire, }, { name: "fire-simple", categories: [IconCategory.NATURE, IconCategory.WEATHER], tags: ["flame", "burning", "match", "lighter"], Icon: Icons.FireSimple, }, { name: "first-aid", categories: [IconCategory.HEALTH], tags: [ "hospital", "cross", "medical", "medicine", "injury", "safety", "emergency", "doctor", ], Icon: Icons.FirstAid, }, { name: "first-aid-kit", categories: [IconCategory.HEALTH], tags: [ "bandages", "medical", "medicine", "injury", "safety", "emergency", "doctor", ], Icon: Icons.FirstAidKit, }, { name: "fish", categories: [IconCategory.NATURE, IconCategory.COMMERCE], tags: ["animals", "pets", "food", "seafood", "restaurants", "dining"], Icon: Icons.Fish, }, { name: "fish-simple", categories: [IconCategory.NATURE, IconCategory.COMMERCE], tags: ["animals", "pets", "food", "seafood", "restaurants", "dining"], Icon: Icons.FishSimple, }, { name: "flag", categories: [IconCategory.OBJECTS, IconCategory.MAP, IconCategory.SYSTEM], tags: ["country", "countries", "finished", "completed", "flags"], Icon: Icons.Flag, }, { name: "flag-banner", categories: [IconCategory.OBJECTS, IconCategory.MAP], tags: ["ribbon", "country", "countries", "finished", "completed", "flags"], Icon: Icons.FlagBanner, }, { name: "flag-checkered", categories: [IconCategory.MAP, IconCategory.OBJECTS, IconCategory.GAMES], tags: ["*new*", "flags", "race", "racing", "finish line"], Icon: Icons.FlagCheckered, }, { name: "flame", categories: [IconCategory.NATURE, IconCategory.WEATHER], tags: ["fire", "burning", "match", "lighter"], Icon: Icons.Flame, }, { name: "flashlight", categories: [IconCategory.SYSTEM, IconCategory.OBJECTS], tags: ["torch", "find", "search", "locate"], Icon: Icons.Flashlight, }, { name: "flask", categories: [IconCategory.DEVELOPMENT, IconCategory.NATURE], tags: ["beaker", "science", "chemistry", "experiment", "erlenmeyer"], Icon: Icons.Flask, }, { name: "floppy-disk", categories: [IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.SYSTEM], tags: [ "diskette", "directory", "directories", "folders", "documents", "files", "save", "write", ], Icon: Icons.FloppyDisk, }, { name: "floppy-disk-back", categories: [IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.SYSTEM], tags: [ "*updated*", "diskette", "directory", "directories", "folders", "documents", "files", "save", "write", ], Icon: Icons.FloppyDiskBack, }, { name: "flow-arrow", categories: [IconCategory.ARROWS, IconCategory.DESIGN, IconCategory.OFFICE], tags: ["flowchart", "arrowhead"], Icon: Icons.FlowArrow, }, { name: "flower", categories: [IconCategory.NATURE], tags: ["plants", "green", "environmental"], Icon: Icons.Flower, }, { name: "flower-lotus", categories: [IconCategory.NATURE], tags: ["plants", "green", "environmental", "spirituality"], Icon: Icons.FlowerLotus, }, { name: "flying-saucer", categories: [IconCategory.GAMES, IconCategory.OBJECTS], tags: ["*new*", "ufo", "space", "aliens", "extra terrestrial", "sci-fi"], Icon: Icons.FlyingSaucer, }, { name: "folder", categories: [IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.SYSTEM], tags: ["directory", "directories", "files", "folders"], Icon: Icons.Folder, }, { name: "folder-plus", categories: [IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.SYSTEM], tags: [ "directory", "directories", "files", "save", "write", "add", "new", "create", "+", ], Icon: Icons.FolderPlus, }, { name: "folder-minus", categories: [IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.SYSTEM], tags: [ "directory", "directories", "files", "delete", "write", "remove", "-", ], Icon: Icons.FolderMinus, }, { name: "folder-open", categories: [IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.SYSTEM], tags: ["directory", "directories", "files", "folders", "load"], Icon: Icons.FolderOpen, }, { name: "folder-dotted", categories: [IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.SYSTEM], tags: [ "*new*", "directory", "directories", "files", "folders", "missing", "temporary", ], Icon: Icons.FolderDotted, }, { name: "folder-lock", categories: [IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.SYSTEM], tags: [ "*new*", "directory", "directories", "files", "folders", "private", "secure", ], Icon: Icons.FolderLock, }, { name: "folder-star", categories: [IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.SYSTEM], tags: [ "*new*", "directory", "directories", "files", "folders", "favorite", "starred", ], Icon: Icons.FolderStar, }, { name: "folder-user", categories: [IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.SYSTEM], tags: ["*new*", "directory", "directories", "files", "folders", "personal"], Icon: Icons.FolderUser, }, { name: "folder-notch", categories: [IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.SYSTEM], tags: ["directory", "directories", "files", "folders"], Icon: Icons.FolderNotch, }, { name: "folder-notch-plus", categories: [IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.SYSTEM], tags: [ "directory", "directories", "files", "save", "write", "add", "new", "create", "+", ], Icon: Icons.FolderNotchPlus, }, { name: "folder-notch-minus", categories: [IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.SYSTEM], tags: [ "directory", "directories", "files", "delete", "write", "remove", "-", ], Icon: Icons.FolderNotchMinus, }, { name: "folder-notch-open", categories: [IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.SYSTEM], tags: ["directory", "directories", "files", "folders", "load"], Icon: Icons.FolderNotchOpen, }, { name: "folder-simple", categories: [IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.SYSTEM], tags: ["directory", "directories", "files", "folders"], Icon: Icons.FolderSimple, }, { name: "folder-simple-plus", categories: [IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.SYSTEM], tags: [ "directory", "directories", "files", "save", "write", "add", "new", "create", "+", ], Icon: Icons.FolderSimplePlus, }, { name: "folder-simple-minus", categories: [IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.SYSTEM], tags: [ "directory", "directories", "files", "delete", "write", "remove", "-", ], Icon: Icons.FolderSimpleMinus, }, { name: "folder-simple-dotted", categories: [IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.SYSTEM], tags: [ "*new*", "directory", "directories", "files", "folders", "missing", "temporary", ], Icon: Icons.FolderSimpleDotted, }, { name: "folder-simple-lock", categories: [IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.SYSTEM], tags: [ "*new*", "directory", "directories", "files", "folders", "private", "secure", ], Icon: Icons.FolderSimpleLock, }, { name: "folder-simple-star", categories: [IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.SYSTEM], tags: [ "*new*", "directory", "directories", "files", "folders", "favorite", "starred", ], Icon: Icons.FolderSimpleStar, }, { name: "folder-simple-user", categories: [IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.SYSTEM], tags: ["*new*", "directory", "directories", "files", "folders", "personal"], Icon: Icons.FolderSimpleUser, }, { name: "folders", categories: [IconCategory.OFFICE, IconCategory.EDITOR, IconCategory.SYSTEM], tags: [ "directory", "directories", "files", "folders", "copy", "copied", "duplicated", ], Icon: Icons.Folders, }, { name: "football", categories: [IconCategory.GAMES, IconCategory.HEALTH], tags: ["sports", "american football", "nfl"], Icon: Icons.Football, }, { name: "fork-knife", categories: [IconCategory.COMMERCE, IconCategory.MAP, IconCategory.OBJECTS], tags: ["food", "meal", "eating", "restaurants", "dining", "utensils"], Icon: Icons.ForkKnife, }, { name: "frame-corners", categories: [IconCategory.SYSTEM], tags: [ "expand", "fullscreen", "maximized", "resize", "windowed", "capture", ], Icon: Icons.FrameCorners, }, { name: "framer-logo", categories: [IconCategory.BRAND, IconCategory.DESIGN], tags: ["logos", "interface", "ui", "motion", "prototype", "prototyping"], Icon: Icons.FramerLogo, }, { name: "function", categories: [IconCategory.DEVELOPMENT], tags: ["*new*", "mathematics", "arithmetic"], Icon: Icons.Function, }, { name: "funnel", categories: [IconCategory.EDITOR, IconCategory.OBJECTS], tags: ["filters", "refine", "sorting"], Icon: Icons.Funnel, }, { name: "funnel-simple", categories: [IconCategory.EDITOR, IconCategory.OBJECTS], tags: ["filters", "refine", "sorting"], Icon: Icons.FunnelSimple, }, { name: "game-controller", categories: [IconCategory.GAMES, IconCategory.MEDIA, IconCategory.OBJECTS], tags: [ "gaming", "video games", "nintendo switch", "sony playstation", "microsoft xbox", ], Icon: Icons.GameController, }, { name: "gas-pump", categories: [IconCategory.MAP, IconCategory.OBJECTS], tags: ["gas station", "petrol", "fuel", "gasoline"], Icon: Icons.GasPump, }, { name: "gauge", categories: [ IconCategory.DEVELOPMENT, IconCategory.OBJECTS, IconCategory.SYSTEM, ], tags: [ "*updated*", "dashboard", "meter", "speed", "speedometer", "odometer", "performance", ], Icon: Icons.Gauge, }, { name: "gear", categories: [IconCategory.SYSTEM], tags: [ "8", "settings", "setup", "preferences", "cogs", "gears", "machinery", "mechanical", ], Icon: Icons.Gear, }, { name: "gear-six", categories: [IconCategory.SYSTEM], tags: [ "6", "settings", "setup", "preferences", "cogs", "gears", "machinery", "mechanical", ], Icon: Icons.GearSix, }, { name: "gender-female", categories: [IconCategory.PEOPLE], tags: ["woman", "feminine", "venus"], Icon: Icons.GenderFemale, }, { name: "gender-male", categories: [IconCategory.PEOPLE], tags: ["man", "masculine", "mars"], Icon: Icons.GenderMale, }, { name: "gender-intersex", categories: [IconCategory.PEOPLE], tags: ["transgender", "non-binary"], Icon: Icons.GenderIntersex, }, { name: "gender-transgender", categories: [IconCategory.PEOPLE], tags: ["intersex", "non-binary"], Icon: Icons.GenderTransgender, }, { name: "gender-nonbinary", categories: [IconCategory.PEOPLE], tags: ["intersex", "non-binary"], Icon: Icons.GenderNonbinary, }, { name: "gender-neuter", categories: [IconCategory.PEOPLE], tags: ["agender", "non-binary", "asexual"], Icon: Icons.GenderNeuter, }, { name: "ghost", categories: [IconCategory.GAMES, IconCategory.OBJECTS], tags: ["pac-man", "spirit", "scary", "halloween"], Icon: Icons.Ghost, }, { name: "gif", categories: [IconCategory.MEDIA], tags: ["gifs", ".gif", "giphy"], Icon: Icons.Gif, }, { name: "gift", categories: [IconCategory.COMMERCE, IconCategory.OBJECTS], tags: ["presents", "holiday", "birthday"], Icon: Icons.Gift, }, { name: "git-branch", categories: [IconCategory.DEVELOPMENT], tags: [ "github", "vcs", "source control", "version control", "versioning", "branches", ], Icon: Icons.GitBranch, }, { name: "git-commit", categories: [IconCategory.DEVELOPMENT], tags: [ "github", "vcs", "source control", "version control", "versioning", "commits", ], Icon: Icons.GitCommit, }, { name: "git-diff", categories: [IconCategory.DEVELOPMENT], tags: [ "github", "vcs", "source control", "version control", "versioning", "difference", "compare", ], Icon: Icons.GitDiff, }, { name: "git-fork", categories: [IconCategory.DEVELOPMENT], tags: [ "github", "vcs", "source control", "version control", "versioning", "split", ], Icon: Icons.GitFork, }, { name: "git-merge", categories: [IconCategory.DEVELOPMENT], tags: [ "github", "vcs", "source control", "version control", "versioning", "split", ], Icon: Icons.GitMerge, }, { name: "git-pull-request", categories: [IconCategory.DEVELOPMENT], tags: [ "github", "vcs", "source control", "version control", "versioning", "merge request", ], Icon: Icons.GitPullRequest, }, { name: "github-logo", categories: [IconCategory.DEVELOPMENT, IconCategory.BRAND], tags: [ "octocat", "vcs", "source control", "version control", "versioning", "branches", ], Icon: Icons.GithubLogo, }, { name: "gitlab-logo", categories: [IconCategory.BRAND, IconCategory.DEVELOPMENT], tags: [ "vcs", "source control", "version control", "versioning", "branches", ], Icon: Icons.GitlabLogo, }, { name: "gitlab-logo-simple", categories: [IconCategory.BRAND, IconCategory.DEVELOPMENT], tags: [ "vcs", "source control", "version control", "versioning", "branches", ], Icon: Icons.GitlabLogoSimple, }, { name: "globe", categories: [IconCategory.MAP], tags: [ "world", "earth", "global", "planet", "circle", "round", "internationalization", "i18n", "languages", "country", "countries", "geography", ], Icon: Icons.Globe, }, { name: "globe-simple", categories: [IconCategory.MAP], tags: [ "world", "earth", "global", "planet", "circle", "round", "internationalization", "i18n", "languages", "country", "countries", "geography", ], Icon: Icons.GlobeSimple, }, { name: "globe-hemisphere-east", categories: [IconCategory.MAP], tags: [ "world", "earth", "global", "planet", "circle", "round", "internationalization", "i18n", "languages", "country", "countries", "geography", "europe", "africa", "asia", "australia", ], Icon: Icons.GlobeHemisphereEast, }, { name: "globe-hemisphere-west", categories: [IconCategory.MAP], tags: [ "world", "earth", "global", "planet", "circle", "round", "internationalization", "i18n", "languages", "country", "countries", "geography", "north america", "south america", ], Icon: Icons.GlobeHemisphereWest, }, { name: "globe-stand", categories: [IconCategory.MAP], tags: [ "world", "global", "planet", "circle", "round", "internationalization", "i18n", "languages", "country", "countries", "geography", ], Icon: Icons.GlobeStand, }, { name: "google-logo", categories: [IconCategory.BRAND], tags: ["logos", "search engine", "phone", "mobile", "android"], Icon: Icons.GoogleLogo, }, { name: "google-chrome-logo", categories: [IconCategory.BRAND], tags: ["*new*", "web browsers", "internet"], Icon: Icons.GoogleChromeLogo, }, { name: "google-photos-logo", categories: [IconCategory.BRAND, IconCategory.MEDIA], tags: ["*new*", "album", "pictures", "photography"], Icon: Icons.GooglePhotosLogo, }, { name: "google-play-logo", categories: [IconCategory.BRAND, IconCategory.SYSTEM, IconCategory.MEDIA], tags: [ "logos", "games", "apps", "applications", "play store", "app store", "phone", "mobile", "android", ], Icon: Icons.GooglePlayLogo, }, { name: "google-podcasts-logo", categories: [IconCategory.BRAND, IconCategory.MEDIA], tags: ["*new*", "audio"], Icon: Icons.GooglePodcastsLogo, }, { name: "gradient", categories: [IconCategory.DESIGN], tags: ["*new*", "fade", "ombre", "opacity"], Icon: Icons.Gradient, }, { name: "graduation-cap", categories: [IconCategory.MAP, IconCategory.OBJECTS], tags: [ "classroom", "teacher", "education", "school", "college", "university", "degree", "graduate", ], Icon: Icons.GraduationCap, }, { name: "graph", categories: [IconCategory.OFFICE, IconCategory.DEVELOPMENT], tags: ["*new*", "nodes", "tree"], Icon: Icons.Graph, }, { name: "grid-four", categories: [IconCategory.DESIGN, IconCategory.SYSTEM], tags: [ "4", "apps", "applications", "squares", "tiles", "cells", "tables", "tabular", "spreadsheets", "excel", ], Icon: Icons.GridFour, }, { name: "hamburger", categories: [IconCategory.COMMERCE, IconCategory.MAP], tags: [ "*new*", "fast food", "party", "places", "locations", "restaurants", "food", "dining", ], Icon: Icons.Hamburger, }, { name: "hand", categories: [IconCategory.SYSTEM, IconCategory.PEOPLE], tags: ["pointers", "cursors", "emoji", "backhand"], Icon: Icons.Hand, }, { name: "hand-eye", categories: [IconCategory.PEOPLE], tags: ["*new*", "pointers", "cursors", "emoji", "hamsa", "evil eye"], Icon: Icons.HandEye, }, { name: "hand-fist", categories: [IconCategory.PEOPLE], tags: ["pointers", "cursors", "emoji", "power", "protest", "blm"], Icon: Icons.HandFist, }, { name: "hand-grabbing", categories: [IconCategory.SYSTEM, IconCategory.PEOPLE], tags: ["pointers", "cursors", "emoji", "drag", "hold"], Icon: Icons.HandGrabbing, }, // { // name: "hand-ok", // categories: [IconCategory.PEOPLE], // tags: [ "pointers", "emoji", "good", "nice"], // Icon: Icons.HandOk, // }, { name: "hand-palm", categories: [IconCategory.SYSTEM, IconCategory.PEOPLE], tags: [ "pointers", "cursors", "emoji", "palm", "stop", "wait", "hamsa", "5", ], Icon: Icons.HandPalm, }, // { // name: "hand-peace", // categories: [IconCategory.PEOPLE], // tags: [ // // "pointers", // "cursors", // "emoji", // "love", // "hippies", // "peace sign" // ], // Icon: Icons.HandPeace, // }, { name: "hand-pointing", categories: [IconCategory.SYSTEM, IconCategory.PEOPLE], tags: ["pointers", "cursors", "emoji", "fingers", "clicks", "mouse"], Icon: Icons.HandPointing, }, { name: "hand-waving", categories: [IconCategory.SYSTEM, IconCategory.PEOPLE], tags: ["pointers", "cursors", "emoji", "palm", "wave", "hello", "goodbye"], Icon: Icons.HandWaving, }, { name: "hands-clapping", categories: [IconCategory.SYSTEM, IconCategory.PEOPLE], tags: ["*updated*", "emoji", "clap", "applause"], Icon: Icons.HandsClapping, }, { name: "handshake", categories: [IconCategory.PEOPLE, IconCategory.COMMERCE], tags: ["pointers", "cursors", "emoji", "deal", "agreement"], Icon: Icons.Handshake, }, { name: "hand-soap", categories: [IconCategory.HEALTH], tags: ["dispenser", "pump", "sanitizer", "disinfectant"], Icon: Icons.HandSoap, }, { name: "handbag", categories: [IconCategory.COMMERCE, IconCategory.OBJECTS], tags: ["suitcases", "valises", "baggage", "purses"], Icon: Icons.Handbag, }, { name: "handbag-simple", categories: [IconCategory.COMMERCE, IconCategory.OBJECTS], tags: ["suitcases", "valises", "baggage", "purses"], Icon: Icons.HandbagSimple, }, { name: "hard-drive", categories: [IconCategory.SYSTEM], tags: [ "saved", "saving", "archived", "archiving", "archival", "hard disk", "storage", "hdd", "servers", "databases", ], Icon: Icons.HardDrive, }, { name: "hard-drives", categories: [IconCategory.SYSTEM], tags: [ "saved", "saving", "archived", "archiving", "archival", "hard disk", "storage", "hdd", "servers", "databases", ], Icon: Icons.HardDrives, }, { name: "hash", categories: [IconCategory.COMMUNICATION], tags: [ "hashtag", "octothorpe", "pound sign", "number sign", "tic-tac-toe", "symbol", ], Icon: Icons.Hash, }, { name: "hash-straight", categories: [IconCategory.COMMUNICATION], tags: [ "hashtag", "octothorpe", "pound sign", "number sign", "tic-tac-toe", "symbol", ], Icon: Icons.HashStraight, }, { name: "headlights", categories: [IconCategory.MAP, IconCategory.OBJECTS], tags: ["brights", "high beams"], Icon: Icons.Headlights, }, { name: "headphones", categories: [IconCategory.MEDIA, IconCategory.OBJECTS], tags: ["music", "audio", "listening"], Icon: Icons.Headphones, }, { name: "headset", categories: [IconCategory.MEDIA, IconCategory.GAMES, IconCategory.OBJECTS], tags: ["music", "audio", "listening", "gaming", "voice chat", "microphone"], Icon: Icons.Headset, }, { name: "heart", categories: [ IconCategory.COMMUNICATION, IconCategory.GAMES, IconCategory.HEALTH, ], tags: [ "wellness", "love", "healthy", "like", "favorites", "favorited", "suits", "cards", "gambling", "casino", "gaming", ], Icon: Icons.Heart, }, { name: "heart-break", categories: [IconCategory.COMMUNICATION], tags: ["*new*", "love", "hate", "crack", "split", "divorce", "emoji"], Icon: Icons.HeartBreak, }, { name: "heart-straight", categories: [ IconCategory.COMMUNICATION, IconCategory.GAMES, IconCategory.HEALTH, ], tags: [ "wellness", "love", "healthy", "like", "favorites", "favorited", "suits", "cards", "gambling", "casino", "gaming", ], Icon: Icons.HeartStraight, }, { name: "heart-straight-break", categories: [IconCategory.COMMUNICATION], tags: ["*new*", "love", "hate", "crack", "split", "divorce", "emoji"], Icon: Icons.HeartStraightBreak, }, { name: "heartbeat", categories: [IconCategory.HEALTH, IconCategory.SYSTEM], tags: [ "*updated*", "wellness", "healthy", "ecg", "ekg", "vitals", "monitor", ], Icon: Icons.Heartbeat, }, { name: "hexagon", categories: [IconCategory.DESIGN], tags: ["6", "shapes", "polygons"], Icon: Icons.Hexagon, }, { name: "highlighter-circle", categories: [IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.OFFICE], tags: ["write", "writing", "editing", "drawing"], Icon: Icons.HighlighterCircle, }, { name: "horse", categories: [IconCategory.GAMES, IconCategory.HEALTH, IconCategory.NATURE], tags: ["animals", "equestrian", "chess", "knight", "sports"], Icon: Icons.Horse, }, // { // name: "hospital", // categories: [IconCategory.HEALTH, IconCategory.MAP], // tags: [ "medical", "medicine", "injury", "safety", "emergency"], // Icon: Icons.Hospital, // }, { name: "hourglass", categories: [IconCategory.SYSTEM, IconCategory.OBJECTS], tags: [ "times", "timer", "alarms", "clock", "schedule", "events", "waiting", "progress", ], Icon: Icons.Hourglass, }, { name: "hourglass-high", categories: [IconCategory.SYSTEM, IconCategory.OBJECTS], tags: [ "times", "timer", "alarms", "clock", "schedule", "events", "waiting", "progress", ], Icon: Icons.HourglassHigh, }, { name: "hourglass-medium", categories: [IconCategory.SYSTEM, IconCategory.OBJECTS], tags: [ "times", "timer", "alarms", "clock", "schedule", "events", "waiting", "progress", ], Icon: Icons.HourglassMedium, }, { name: "hourglass-low", categories: [IconCategory.SYSTEM, IconCategory.OBJECTS], tags: [ "times", "timer", "alarms", "clock", "schedule", "events", "waiting", "progress", ], Icon: Icons.HourglassLow, }, { name: "hourglass-simple", categories: [IconCategory.SYSTEM, IconCategory.OBJECTS], tags: [ "times", "timer", "alarms", "clock", "schedule", "events", "waiting", "progress", ], Icon: Icons.HourglassSimple, }, { name: "hourglass-simple-high", categories: [IconCategory.SYSTEM, IconCategory.OBJECTS], tags: [ "times", "timer", "alarms", "clock", "schedule", "events", "waiting", "progress", ], Icon: Icons.HourglassSimpleHigh, }, { name: "hourglass-simple-medium", categories: [IconCategory.SYSTEM, IconCategory.OBJECTS], tags: [ "times", "timer", "alarms", "clock", "schedule", "events", "waiting", "progress", ], Icon: Icons.HourglassSimpleMedium, }, { name: "hourglass-simple-low", categories: [IconCategory.SYSTEM, IconCategory.OBJECTS], tags: [ "times", "timer", "alarms", "clock", "schedule", "events", "waiting", "progress", ], Icon: Icons.HourglassSimpleLow, }, { name: "house", categories: [IconCategory.MAP, IconCategory.SYSTEM], tags: ["homes", "buildings", "places", "locations"], Icon: Icons.House, }, { name: "house-line", categories: [IconCategory.MAP, IconCategory.SYSTEM], tags: ["homes", "buildings", "places", "locations"], Icon: Icons.HouseLine, }, { name: "house-simple", categories: [IconCategory.MAP, IconCategory.SYSTEM], tags: ["homes", "buildings", "places", "locations"], Icon: Icons.HouseSimple, }, // { // name: "ice-cubes", // categories: [IconCategory.COMMERCE, IconCategory.OBJECTS], // tags: [ // // "drinks", // "beverages", // "locations", // "bars", // "restaurants", // "food", // "dining", // ], // Icon: Icons.IceCubes, // }, { name: "identification-badge", categories: [IconCategory.PEOPLE], tags: ["license", "credentials", "nametag", "user", "verification"], Icon: Icons.IdentificationBadge, }, { name: "identification-card", categories: [IconCategory.PEOPLE], tags: [ "license", "badge", "credentials", "nametag", "user", "verification", ], Icon: Icons.IdentificationCard, }, { name: "image", categories: [IconCategory.MEDIA], tags: [ "pictures", "photographs", "photography", "wallpapers", "gallery", "landscape", ], Icon: Icons.Image, }, { name: "image-square", categories: [IconCategory.MEDIA], tags: [ "pictures", "photographs", "photography", "wallpapers", "gallery", "landscape", ], Icon: Icons.ImageSquare, }, { name: "infinity", categories: [IconCategory.DEVELOPMENT, IconCategory.FINANCE], tags: [ "infinite", "figure-eight", "mathematics", "arithmetic", "calculator", "∞", ], Icon: Icons.Infinity, }, { name: "info", categories: [IconCategory.SYSTEM], tags: ["information", "help", "support"], Icon: Icons.Info, }, { name: "instagram-logo", categories: [IconCategory.BRAND, IconCategory.COMMUNICATION], tags: ["logos", "social media", "photography", "camera"], Icon: Icons.InstagramLogo, }, { name: "intersect", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: [ "round", "joining", "union", "merged", "merging", "intersecting", "intersection", ], Icon: Icons.Intersect, }, { name: "jeep", categories: [IconCategory.MAP, IconCategory.OBJECTS], tags: [ "*updated*", "vehicles", "automobile", "suv", "cars", "trucks", "wrangler", "off-road", "transit", "transportation", "traveling", ], Icon: Icons.Jeep, }, { name: "kanban", categories: [IconCategory.OFFICE], tags: [ "*new*", "scheduling", "tasks", "project management", "process", "lean", "agile", ], Icon: Icons.Kanban, }, { name: "key", categories: [IconCategory.OBJECTS, IconCategory.SYSTEM], tags: [ "padlock", "security", "secured", "authentication", "authenticated", "login", "locked", "encrypted", "encryption", ], Icon: Icons.Key, }, // { // name: "key-escape", // categories: [IconCategory.SYSTEM], // tags: [ "keyboard", "exit", "back"], // Icon: Icons.KeyEscape, // }, { name: "key-return", categories: [IconCategory.SYSTEM], tags: ["keyboard", "enter"], Icon: Icons.KeyReturn, }, { name: "keyboard", categories: [IconCategory.SYSTEM], tags: ["typing", "type", "keys", "input"], Icon: Icons.Keyboard, }, { name: "keyhole", categories: [IconCategory.OBJECTS, IconCategory.SYSTEM], tags: [ "*new*", "lock", "security", "secured", "authentication", "authenticated", "login", "locked", "encrypted", "encryption", "privacy", "private", ], Icon: Icons.Keyhole, }, { name: "knife", categories: [IconCategory.COMMERCE, IconCategory.OBJECTS], tags: [ "tools", "food", "meal", "eating", "restaurants", "dining", "utensils", ], Icon: Icons.Knife, }, { name: "ladder", categories: [IconCategory.OBJECTS], tags: ["*new*", "stairs", "steps", "climbing"], Icon: Icons.Ladder, }, { name: "ladder-simple", categories: [IconCategory.OBJECTS], tags: ["*new*", "stairs", "steps", "climbing"], Icon: Icons.LadderSimple, }, { name: "lamp", categories: [IconCategory.OBJECTS], tags: ["light", "furniture", "appliances"], Icon: Icons.Lamp, }, { name: "laptop", categories: [IconCategory.DEVELOPMENT, IconCategory.OBJECTS], tags: ["computer", "notebook", "pc", "macbook"], Icon: Icons.Laptop, }, { name: "layout", categories: [IconCategory.DESIGN], tags: ["wireframe", "sidebar", "ui", "interface"], Icon: Icons.Layout, }, { name: "leaf", categories: [IconCategory.NATURE], tags: [ "plants", "trees", "branches", "leaves", "nodes", "green", "environmental", ], Icon: Icons.Leaf, }, { name: "lifebuoy", categories: [ IconCategory.HEALTH, IconCategory.OBJECTS, IconCategory.SYSTEM, ], tags: [ "lifebelt", "lifesaver", "safety", "help", "support", "nautical", "boats", "ships", ], Icon: Icons.Lifebuoy, }, { name: "lightbulb", categories: [IconCategory.SYSTEM, IconCategory.OBJECTS], tags: ["flashlight", "bulbs", "lighting", "led", "energy", "idea"], Icon: Icons.Lightbulb, }, { name: "lightbulb-filament", categories: [IconCategory.SYSTEM, IconCategory.OBJECTS], tags: ["flashlight", "bulbs", "lighting", "led", "energy", "idea"], Icon: Icons.LightbulbFilament, }, { name: "lightning", categories: [IconCategory.WEATHER, IconCategory.SYSTEM], tags: [ "meteorology", "stormy", "thunderstorm", "thunderbolt", "charged", "charger", "charging", "power", "electricity", ], Icon: Icons.Lightning, }, { name: "lightning-slash", categories: [IconCategory.SYSTEM], tags: [ "thunderbolt", "charged", "charger", "charging", "power", "electricity", "disabled", ], Icon: Icons.LightningSlash, }, { name: "line-segment", categories: [IconCategory.DESIGN], tags: ["shapes", "drawing", "path", "pen"], Icon: Icons.LineSegment, }, { name: "line-segments", categories: [IconCategory.DESIGN], tags: ["shapes", "drawing", "path", "pen"], Icon: Icons.LineSegments, }, { name: "link", categories: [IconCategory.COMMUNICATION, IconCategory.OBJECTS], tags: ["anchor", "hyperlink", "hypertext", "chains", "chained"], Icon: Icons.Link, }, { name: "link-break", categories: [IconCategory.COMMUNICATION, IconCategory.OBJECTS], tags: [ "anchor", "hyperlink", "hypertext", "chains", "chained", "errors", "broken", ], Icon: Icons.LinkBreak, }, { name: "link-simple", categories: [IconCategory.COMMUNICATION, IconCategory.OBJECTS], tags: ["anchor", "hyperlink", "hypertext", "chains", "chained"], Icon: Icons.LinkSimple, }, { name: "link-simple-break", categories: [IconCategory.COMMUNICATION, IconCategory.OBJECTS], tags: [ "anchor", "hyperlink", "hypertext", "chains", "chained", "errors", "broken", ], Icon: Icons.LinkSimpleBreak, }, { name: "link-simple-horizontal", categories: [IconCategory.COMMUNICATION, IconCategory.OBJECTS], tags: ["anchor", "hyperlink", "hypertext", "chains", "chained"], Icon: Icons.LinkSimpleHorizontal, }, { name: "link-simple-horizontal-break", categories: [IconCategory.COMMUNICATION, IconCategory.OBJECTS], tags: [ "anchor", "hyperlink", "hypertext", "chains", "chained", "errors", "broken", ], Icon: Icons.LinkSimpleHorizontalBreak, }, { name: "linkedin-logo", categories: [IconCategory.BRAND, IconCategory.COMMUNICATION], tags: ["logos", "jobs", "employment", "social media"], Icon: Icons.LinkedinLogo, }, { name: "linux-logo", categories: [IconCategory.BRAND, IconCategory.DEVELOPMENT], tags: ["*new*", "penguin", "computer", "animals"], Icon: Icons.LinuxLogo, }, { name: "list", categories: [IconCategory.SYSTEM, IconCategory.EDITOR], tags: [ "hamburger menu", "overflow menu", "sidebar", "3", "ul", "ol", "unordered list", "ordered list", "checklist", ], Icon: Icons.List, }, { name: "list-bullets", categories: [IconCategory.EDITOR], tags: ["ul", "unordered list", "bulleted list", "checklist"], Icon: Icons.ListBullets, }, { name: "list-checks", categories: [IconCategory.OFFICE, IconCategory.EDITOR], tags: ["*new*", "checklist", "todo"], Icon: Icons.ListChecks, }, { name: "list-dashes", categories: [IconCategory.EDITOR], tags: ["ul", "unordered list", "dashed list", "checklist"], Icon: Icons.ListDashes, }, { name: "list-numbers", categories: [IconCategory.EDITOR], tags: ["ol", "ordered list", "numbered list", "checklist"], Icon: Icons.ListNumbers, }, { name: "list-plus", categories: [IconCategory.EDITOR], tags: [ "ul", "ol", "unordered list", "ordered list", "checklist", "add", "+", ], Icon: Icons.ListPlus, }, { name: "lock", categories: [IconCategory.OBJECTS, IconCategory.SYSTEM], tags: [ "padlock", "security", "secured", "authentication", "authenticated", "login", "locked", "encrypted", "encryption", "privacy", "private", ], Icon: Icons.Lock, }, { name: "lock-open", categories: [IconCategory.OBJECTS, IconCategory.SYSTEM], tags: [ "padlock", "security", "unsecured", "authentication", "unauthenticated", "login", "unlocked", "unencrypted", "encryption", "privacy", ], Icon: Icons.LockOpen, }, { name: "lock-key", categories: [IconCategory.OBJECTS, IconCategory.SYSTEM], tags: [ "padlock", "security", "secured", "authentication", "authenticated", "login", "locked", "encrypted", "encryption", "privacy", "private", ], Icon: Icons.LockKey, }, { name: "lock-key-open", categories: [IconCategory.OBJECTS, IconCategory.SYSTEM], tags: [ "padlock", "security", "unsecured", "authentication", "unauthenticated", "login", "unlocked", "unencrypted", "encryption", "privacy", ], Icon: Icons.LockKeyOpen, }, { name: "lock-laminated", categories: [IconCategory.OBJECTS, IconCategory.SYSTEM], tags: [ "padlock", "security", "secured", "authentication", "authenticated", "login", "locked", "encrypted", "encryption", "privacy", "private", ], Icon: Icons.LockLaminated, }, { name: "lock-laminated-open", categories: [IconCategory.OBJECTS, IconCategory.SYSTEM], tags: [ "padlock", "security", "unsecured", "authentication", "unauthenticated", "login", "unlocked", "unencrypted", "encryption", "privacy", "private", ], Icon: Icons.LockLaminatedOpen, }, { name: "lock-simple", categories: [IconCategory.OBJECTS, IconCategory.SYSTEM], tags: [ "padlock", "security", "secured", "authentication", "authenticated", "login", "locked", "encrypted", "encryption", "privacy", "private", ], Icon: Icons.LockSimple, }, { name: "lock-simple-open", categories: [IconCategory.OBJECTS, IconCategory.SYSTEM], tags: [ "padlock", "security", "unsecured", "authentication", "unauthenticated", "login", "unlocked", "unencrypted", "encryption", "privacy", "private", ], Icon: Icons.LockSimpleOpen, }, { name: "magic-wand", categories: [IconCategory.DESIGN, IconCategory.GAMES, IconCategory.OBJECTS], tags: ["selection", "wizard", "games"], Icon: Icons.MagicWand, }, { name: "magnet", categories: [IconCategory.DEVELOPMENT, IconCategory.OBJECTS], tags: ["magnetism", "science", "physics"], Icon: Icons.Magnet, }, { name: "magnet-straight", categories: [IconCategory.DEVELOPMENT, IconCategory.OBJECTS], tags: ["magnetism", "science", "physics"], Icon: Icons.MagnetStraight, }, { name: "magnifying-glass", categories: [IconCategory.EDITOR, IconCategory.SYSTEM], tags: ["search", "find", "locate", "query", "inspect"], Icon: Icons.MagnifyingGlass, }, { name: "magnifying-glass-plus", categories: [IconCategory.EDITOR, IconCategory.SYSTEM], tags: ["search", "find", "locate", "query", "inspect", "zoom in", "+"], Icon: Icons.MagnifyingGlassPlus, }, { name: "magnifying-glass-minus", categories: [IconCategory.EDITOR, IconCategory.SYSTEM], tags: ["search", "find", "locate", "query", "inspect", "zoom out", "-"], Icon: Icons.MagnifyingGlassMinus, }, { name: "map-pin", categories: [IconCategory.MAP], tags: ["maps", "places", "markers", "pins", "locations"], Icon: Icons.MapPin, }, { name: "map-pin-line", categories: [IconCategory.MAP], tags: ["maps", "places", "markers", "pins", "locations"], Icon: Icons.MapPinLine, }, { name: "map-trifold", categories: [IconCategory.MAP], tags: ["maps", "places", "locations", "cartography", "geography"], Icon: Icons.MapTrifold, }, { name: "marker-circle", categories: [IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.OFFICE], tags: ["write", "writing", "editing", "drawing"], Icon: Icons.MarkerCircle, }, { name: "martini", categories: [IconCategory.COMMERCE, IconCategory.MAP, IconCategory.OBJECTS], tags: [ "glass", "drinks", "beverages", "cocktails", "places", "locations", "bars", "restaurants", "food", "dining", ], Icon: Icons.Martini, }, { name: "mask-happy", categories: [IconCategory.COMMUNICATION, IconCategory.GAMES], tags: ["*new*", "theater", "costume", "smile", "smiling", "thalia"], Icon: Icons.MaskHappy, }, { name: "mask-sad", categories: [IconCategory.COMMUNICATION, IconCategory.GAMES], tags: ["*new*", "theater", "costume", "cry", "crying", "melpomene"], Icon: Icons.MaskSad, }, { name: "math-operations", categories: [IconCategory.DEVELOPMENT, IconCategory.FINANCE], tags: [ "addition", "sum", "subtraction", "difference", "multiply", "multiplication", "product", "divide", "division", "divisor", "dividend", "quotient", "equals", "equality", "mathematics", "arithmetic", "calculator", "+", "-", "±", "×", "÷", "=", ], Icon: Icons.MathOperations, }, { name: "medal", categories: [IconCategory.OBJECTS], tags: ["ribbons", "winning", "victory", "awards"], Icon: Icons.Medal, }, { name: "medium-logo", categories: [IconCategory.BRAND], tags: ["logos", "reading", "writing", "news", "social media"], Icon: Icons.MediumLogo, }, { name: "megaphone", categories: [IconCategory.COMMUNICATION, IconCategory.OBJECTS], tags: ["bullhorn", "announcements", "loudspeaker", "broadcast"], Icon: Icons.Megaphone, }, { name: "megaphone-simple", categories: [IconCategory.COMMUNICATION, IconCategory.OBJECTS], tags: ["bullhorn", "announcements", "loudspeaker", "broadcast"], Icon: Icons.MegaphoneSimple, }, { name: "messenger-logo", categories: [IconCategory.BRAND, IconCategory.COMMUNICATION], tags: ["logos", "facebook", "social media"], Icon: Icons.MessengerLogo, }, { name: "microphone", categories: [ IconCategory.COMMUNICATION, IconCategory.MEDIA, IconCategory.SYSTEM, ], tags: ["audio", "recording", "music", "sound", "podcast", "studio"], Icon: Icons.Microphone, }, { name: "microphone-slash", categories: [ IconCategory.COMMUNICATION, IconCategory.MEDIA, IconCategory.SYSTEM, ], tags: [ "audio", "recording", "music", "sound", "podcast", "studio", "muted", "disabled", ], Icon: Icons.MicrophoneSlash, }, { name: "microphone-stage", categories: [ IconCategory.COMMUNICATION, IconCategory.MEDIA, IconCategory.SYSTEM, ], tags: [ "*new*", "audio", "recording", "music", "sound", "performance", "concert", ], Icon: Icons.MicrophoneStage, }, { name: "microsoft-excel-logo", categories: [IconCategory.BRAND, IconCategory.OFFICE], tags: ["*new*", "tables", "spreadsheets", "tabular"], Icon: Icons.MicrosoftExcelLogo, }, { name: "microsoft-powerpoint-logo", categories: [IconCategory.BRAND, IconCategory.OFFICE], tags: ["*new*", "slides", "slideshow", "presentation"], Icon: Icons.MicrosoftPowerpointLogo, }, { name: "microsoft-teams-logo", categories: [IconCategory.BRAND, IconCategory.COMMUNICATION], tags: ["*new*", "chat", "video conference"], Icon: Icons.MicrosoftTeamsLogo, }, { name: "microsoft-word-logo", categories: [IconCategory.BRAND, IconCategory.EDITOR, IconCategory.OFFICE], tags: ["*new*", "documents", "word processor", "doc", "docx"], Icon: Icons.MicrosoftWordLogo, }, { name: "minus", categories: [ IconCategory.DEVELOPMENT, IconCategory.FINANCE, IconCategory.SYSTEM, ], tags: [ "-", "subtraction", "difference", "mathematics", "arithmetic", "calculator", ], Icon: Icons.Minus, }, { name: "minus-circle", categories: [ IconCategory.DEVELOPMENT, IconCategory.FINANCE, IconCategory.SYSTEM, ], tags: [ "-", "subtraction", "difference", "mathematics", "arithmetic", "calculator", "round", ], Icon: Icons.MinusCircle, }, { name: "money", categories: [IconCategory.COMMERCE, IconCategory.FINANCE], tags: ["cash", "dollars", "paper bills", "payment", "paying", "purchase"], Icon: Icons.Money, }, { name: "monitor", categories: [IconCategory.SYSTEM], tags: ["screen", "television", "tv", "displays"], Icon: Icons.Monitor, }, { name: "monitor-play", categories: [IconCategory.SYSTEM, IconCategory.MEDIA], tags: [ "screen", "television", "tv", "displays", "screencast", "video", "movie", ], Icon: Icons.MonitorPlay, }, { name: "moon", categories: [ IconCategory.NATURE, IconCategory.SYSTEM, IconCategory.WEATHER, ], tags: [ "night", "evening", "clear", "sleep", "snooze", "night mode", "dark mode", "astronomy", "stargazing", ], Icon: Icons.Moon, }, { name: "moon-stars", categories: [IconCategory.NATURE, IconCategory.WEATHER], tags: [ "night", "evening", "clear", "sleep", "snooze", "night mode", "dark mode", "astronomy", "stargazing", "constellation", ], Icon: Icons.MoonStars, }, { name: "mountains", categories: [IconCategory.NATURE], tags: ["*new*", "hills", "outdoors", "terrain", "geology", "adventure"], Icon: Icons.Mountains, }, { name: "mouse", categories: [IconCategory.SYSTEM], tags: ["clicks", "input"], Icon: Icons.Mouse, }, { name: "mouse-simple", categories: [IconCategory.SYSTEM], tags: ["clicks", "input"], Icon: Icons.MouseSimple, }, { name: "music-note", categories: [IconCategory.MEDIA], tags: ["songs", "audio", "playlist", "albums"], Icon: Icons.MusicNote, }, { name: "music-notes", categories: [IconCategory.MEDIA], tags: ["songs", "audio", "playlist", "albums"], Icon: Icons.MusicNotes, }, { name: "music-notes-plus", categories: [IconCategory.MEDIA], tags: ["*new*", "songs", "audio", "playlist", "albums", "add"], Icon: Icons.MusicNotesPlus, }, { name: "music-note-simple", categories: [IconCategory.MEDIA], tags: ["songs", "audio", "playlist", "albums"], Icon: Icons.MusicNoteSimple, }, { name: "music-notes-simple", categories: [IconCategory.MEDIA], tags: ["songs", "audio", "playlist", "albums"], Icon: Icons.MusicNotesSimple, }, { name: "navigation-arrow", categories: [IconCategory.MAP], tags: ["location", "directions", "compass", "gps"], Icon: Icons.NavigationArrow, }, { name: "needle", categories: [IconCategory.OBJECTS, IconCategory.COMMERCE], tags: ["*new*", "sewing", "thread", "awl", "tailor"], Icon: Icons.Needle, }, { name: "newspaper", categories: [IconCategory.MEDIA, IconCategory.OBJECTS], tags: ["reading", "writing", "journals", "periodicals"], Icon: Icons.Newspaper, }, { name: "newspaper-clipping", categories: [IconCategory.MEDIA, IconCategory.OBJECTS], tags: ["reading", "writing", "journals", "periodicals"], Icon: Icons.NewspaperClipping, }, { name: "note", categories: [IconCategory.OFFICE, IconCategory.EDITOR], tags: ["notes", "note-taking", "memorandum", "post-it", "reminders"], Icon: Icons.Note, }, { name: "note-blank", categories: [IconCategory.OFFICE, IconCategory.EDITOR], tags: ["notes", "note-taking", "memorandum", "post-it", "reminders"], Icon: Icons.NoteBlank, }, { name: "note-pencil", categories: [IconCategory.OFFICE, IconCategory.EDITOR], tags: ["notes", "note-taking", "memorandum", "post-it", "reminders"], Icon: Icons.NotePencil, }, { name: "notebook", categories: [IconCategory.OFFICE, IconCategory.EDITOR], tags: [ "notes", "note-taking", "memorandum", "journal", "diary", "logs", "logbook", ], Icon: Icons.Notebook, }, { name: "notepad", categories: [IconCategory.OFFICE, IconCategory.EDITOR], tags: [ "logs", "logbook", "notes", "note-taking", "memorandum", "journal", "diary", ], Icon: Icons.Notepad, }, { name: "notification", categories: [IconCategory.SYSTEM], tags: ["badge", "pip"], Icon: Icons.Notification, }, { name: "number-zero", categories: [IconCategory.FINANCE], tags: [ "0", "numbers", "numerals", "digits", "mathematics", "arithmetic", "calculator", ], Icon: Icons.NumberZero, }, { name: "number-one", categories: [IconCategory.FINANCE], tags: [ "1", "numbers", "numerals", "digits", "mathematics", "arithmetic", "calculator", ], Icon: Icons.NumberOne, }, { name: "number-two", categories: [IconCategory.FINANCE], tags: [ "2", "numbers", "numerals", "digits", "mathematics", "arithmetic", "calculator", ], Icon: Icons.NumberTwo, }, { name: "number-three", categories: [IconCategory.FINANCE], tags: [ "3", "numbers", "numerals", "digits", "mathematics", "arithmetic", "calculator", ], Icon: Icons.NumberThree, }, { name: "number-four", categories: [IconCategory.FINANCE], tags: [ "4", "numbers", "numerals", "digits", "mathematics", "arithmetic", "calculator", ], Icon: Icons.NumberFour, }, { name: "number-five", categories: [IconCategory.FINANCE], tags: [ "5", "numbers", "numerals", "digits", "mathematics", "arithmetic", "calculator", ], Icon: Icons.NumberFive, }, { name: "number-six", categories: [IconCategory.FINANCE], tags: [ "6", "numbers", "numerals", "digits", "mathematics", "arithmetic", "calculator", ], Icon: Icons.NumberSix, }, { name: "number-seven", categories: [IconCategory.FINANCE], tags: [ "7", "numbers", "numerals", "digits", "mathematics", "arithmetic", "calculator", ], Icon: Icons.NumberSeven, }, { name: "number-eight", categories: [IconCategory.FINANCE], tags: [ "8", "numbers", "numerals", "digits", "mathematics", "arithmetic", "calculator", ], Icon: Icons.NumberEight, }, { name: "number-nine", categories: [IconCategory.FINANCE], tags: [ "9", "numbers", "numerals", "digits", "mathematics", "arithmetic", "calculator", ], Icon: Icons.NumberNine, }, { name: "number-circle-zero", categories: [IconCategory.FINANCE], tags: [ "0", "round", "numbers", "numerals", "digits", "mathematics", "arithmetic", "calculator", ], Icon: Icons.NumberCircleZero, }, { name: "number-circle-one", categories: [IconCategory.FINANCE], tags: [ "1", "round", "numbers", "numerals", "digits", "mathematics", "arithmetic", "calculator", ], Icon: Icons.NumberCircleOne, }, { name: "number-circle-two", categories: [IconCategory.FINANCE], tags: [ "2", "round", "numbers", "numerals", "digits", "mathematics", "arithmetic", "calculator", ], Icon: Icons.NumberCircleTwo, }, { name: "number-circle-three", categories: [IconCategory.FINANCE], tags: [ "3", "round", "numbers", "numerals", "digits", "mathematics", "arithmetic", "calculator", ], Icon: Icons.NumberCircleThree, }, { name: "number-circle-four", categories: [IconCategory.FINANCE], tags: [ "4", "round", "numbers", "numerals", "digits", "mathematics", "arithmetic", "calculator", ], Icon: Icons.NumberCircleFour, }, { name: "number-circle-five", categories: [IconCategory.FINANCE], tags: [ "5", "round", "numbers", "numerals", "digits", "mathematics", "arithmetic", "calculator", ], Icon: Icons.NumberCircleFive, }, { name: "number-circle-six", categories: [IconCategory.FINANCE], tags: [ "6", "round", "numbers", "numerals", "digits", "mathematics", "arithmetic", "calculator", ], Icon: Icons.NumberCircleSix, }, { name: "number-circle-seven", categories: [IconCategory.FINANCE], tags: [ "7", "round", "numbers", "numerals", "digits", "mathematics", "arithmetic", "calculator", ], Icon: Icons.NumberCircleSeven, }, { name: "number-circle-eight", categories: [IconCategory.FINANCE], tags: [ "8", "round", "numbers", "numerals", "digits", "mathematics", "arithmetic", "calculator", ], Icon: Icons.NumberCircleEight, }, { name: "number-circle-nine", categories: [IconCategory.FINANCE], tags: [ "9", "round", "numbers", "numerals", "digits", "mathematics", "arithmetic", "calculator", ], Icon: Icons.NumberCircleNine, }, { name: "number-square-zero", categories: [IconCategory.FINANCE], tags: [ "0", "numbers", "numerals", "digits", "mathematics", "arithmetic", "calculator", ], Icon: Icons.NumberSquareZero, }, { name: "number-square-one", categories: [IconCategory.FINANCE], tags: [ "1", "numbers", "numerals", "digits", "mathematics", "arithmetic", "calculator", ], Icon: Icons.NumberSquareOne, }, { name: "number-square-two", categories: [IconCategory.FINANCE], tags: [ "2", "numbers", "numerals", "digits", "mathematics", "arithmetic", "calculator", ], Icon: Icons.NumberSquareTwo, }, { name: "number-square-three", categories: [IconCategory.FINANCE], tags: [ "3", "numbers", "numerals", "digits", "mathematics", "arithmetic", "calculator", ], Icon: Icons.NumberSquareThree, }, { name: "number-square-four", categories: [IconCategory.FINANCE], tags: [ "4", "numbers", "numerals", "digits", "mathematics", "arithmetic", "calculator", ], Icon: Icons.NumberSquareFour, }, { name: "number-square-five", categories: [IconCategory.FINANCE], tags: [ "5", "numbers", "numerals", "digits", "mathematics", "arithmetic", "calculator", ], Icon: Icons.NumberSquareFive, }, { name: "number-square-six", categories: [IconCategory.FINANCE], tags: [ "6", "numbers", "numerals", "digits", "mathematics", "arithmetic", "calculator", ], Icon: Icons.NumberSquareSix, }, { name: "number-square-seven", categories: [IconCategory.FINANCE], tags: [ "7", "numbers", "numerals", "digits", "mathematics", "arithmetic", "calculator", ], Icon: Icons.NumberSquareSeven, }, { name: "number-square-eight", categories: [IconCategory.FINANCE], tags: [ "8", "numbers", "numerals", "digits", "mathematics", "arithmetic", "calculator", ], Icon: Icons.NumberSquareEight, }, { name: "number-square-nine", categories: [IconCategory.FINANCE], tags: [ "9", "numbers", "numerals", "digits", "mathematics", "arithmetic", "calculator", ], Icon: Icons.NumberSquareNine, }, { name: "nut", categories: [IconCategory.OBJECTS, IconCategory.SYSTEM], tags: ["bolts", "screws", "machinery", "tools", "hexagon"], Icon: Icons.Nut, }, { name: "ny-times-logo", categories: [IconCategory.BRAND], tags: [ "nyt", "new york times", "logos", "reading", "writing", "news", "newspaper", ], Icon: Icons.NyTimesLogo, }, { name: "octagon", categories: [IconCategory.DESIGN], tags: ["8", "shapes", "polygons"], Icon: Icons.Octagon, }, { name: "option", categories: [IconCategory.SYSTEM, IconCategory.EDITOR], tags: ["*new*", "keyboard", "shortcut", "modifier"], Icon: Icons.Option, }, { name: "package", categories: [IconCategory.DEVELOPMENT, IconCategory.OBJECTS], tags: [ "packages", "boxes", "delivery", "mail", "postal service", "bundles", "library", "libraries", "shipping", ], Icon: Icons.Package, }, { name: "paint-brush", categories: [ IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.OBJECTS, ], tags: ["colors", "color picker", "arts"], Icon: Icons.PaintBrush, }, { name: "paint-brush-household", categories: [ IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.OBJECTS, ], tags: ["colors", "color picker", "arts"], Icon: Icons.PaintBrushHousehold, }, { name: "paint-brush-broad", categories: [ IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.OBJECTS, ], tags: ["fill", "colors", "color picker", "arts"], Icon: Icons.PaintBrushBroad, }, { name: "paint-bucket", categories: [ IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.OBJECTS, ], tags: ["paintbucket", "colors", "color picker", "fill", "arts"], Icon: Icons.PaintBucket, }, { name: "paint-roller", categories: [ IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.OBJECTS, ], tags: ["colors", "color picker", "fill", "arts", "theme"], Icon: Icons.PaintRoller, }, { name: "palette", categories: [ IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.OBJECTS, ], tags: ["paint", "colors", "color picker", "arts"], Icon: Icons.Palette, }, { name: "paper-plane", categories: [ IconCategory.COMMUNICATION, IconCategory.MAP, IconCategory.OBJECTS, ], tags: [ "*updated*", "mail", "email", "send", "sent", "messages", "messaging", "toys", "games", ], Icon: Icons.PaperPlane, }, { name: "paper-plane-right", categories: [ IconCategory.COMMUNICATION, IconCategory.MAP, IconCategory.OBJECTS, ], tags: [ "*updated*", "mail", "email", "send", "sent", "messages", "messaging", "toys", "games", ], Icon: Icons.PaperPlaneRight, }, { name: "paper-plane-tilt", categories: [ IconCategory.COMMUNICATION, IconCategory.MAP, IconCategory.OBJECTS, ], tags: [ "*updated*", "mail", "email", "send", "sent", "messages", "messaging", "toys", "games", ], Icon: Icons.PaperPlaneTilt, }, { name: "paperclip", categories: [ IconCategory.COMMUNICATION, IconCategory.EDITOR, IconCategory.OFFICE, IconCategory.OBJECTS, ], tags: ["attachments", "mail", "email", "office"], Icon: Icons.Paperclip, }, { name: "paperclip-horizontal", categories: [ IconCategory.COMMUNICATION, IconCategory.EDITOR, IconCategory.OFFICE, IconCategory.OBJECTS, ], tags: ["attachments", "mail", "email", "office"], Icon: Icons.PaperclipHorizontal, }, { name: "parachute", categories: [IconCategory.OBJECTS, IconCategory.DEVELOPMENT], tags: ["*new*", "skydiving", "safety"], Icon: Icons.Parachute, }, // { // name: "party-hat", // categories: [IconCategory.OBJECT], // tags: [ "birthday", "celebration", "event"], // Icon: Icons.PartyHat, // }, { name: "password", categories: [IconCategory.SYSTEM], tags: [ "*new*", "security", "secured", "authentication", "authenticated", "login", "locked", "encrypted", "encryption", ], Icon: Icons.Password, }, { name: "path", categories: [IconCategory.DESIGN, IconCategory.MAP], tags: [ "transit", "travel", "trail", "gps", "navigation", "route", "destination", ], Icon: Icons.Path, }, { name: "pause", categories: [IconCategory.MEDIA], tags: ["music", "audio", "resume", "start", "stop"], Icon: Icons.Pause, }, { name: "pause-circle", categories: [IconCategory.MEDIA], tags: ["music", "audio", "resume", "start", "stop", "round"], Icon: Icons.PauseCircle, }, { name: "paw-print", categories: [ IconCategory.NATURE, IconCategory.COMMERCE, IconCategory.HEALTH, ], tags: [ "pets", "pet store", "pet shop", "animals", "cat", "dog", "veterinarian", ], Icon: Icons.PawPrint, }, { name: "peace", categories: [IconCategory.COMMUNICATION], tags: ["love", "hippies", "peace sign", "symbols"], Icon: Icons.Peace, }, { name: "person", categories: [IconCategory.MAP, IconCategory.PEOPLE], tags: [ "walking", "human", "woman", "man", "body", "transit", "transportation", "travel", "commuter", "user", ], Icon: Icons.Person, }, { name: "person-simple", categories: [IconCategory.MAP, IconCategory.PEOPLE, IconCategory.HEALTH], tags: [ "pedestrian", "walking", "human", "woman", "man", "body", "transit", "transportation", "travel", "commuter", "user", "exercise", ], Icon: Icons.PersonSimple, }, { name: "person-simple-walk", categories: [IconCategory.MAP, IconCategory.PEOPLE, IconCategory.HEALTH], tags: [ "pedestrian", "walking", "human", "woman", "man", "body", "transit", "transportation", "travel", "commuter", "user", "exercise", ], Icon: Icons.PersonSimpleWalk, }, { name: "person-simple-run", categories: [IconCategory.MAP, IconCategory.PEOPLE, IconCategory.HEALTH], tags: [ "pedestrian", "running", "human", "woman", "man", "body", "transit", "transportation", "travel", "commuter", "user", "exercise", ], Icon: Icons.PersonSimpleRun, }, { name: "pen", categories: [IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.OFFICE], tags: ["ink", "write", "writing", "editing", "sign", "signature"], Icon: Icons.Pen, }, { name: "pen-nib", categories: [IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.OFFICE], tags: [ "ink", "write", "writing", "editing", "sign", "signature", "fountain pen", "illustrator", ], Icon: Icons.PenNib, }, { name: "pen-nib-straight", categories: [IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.OFFICE], tags: [ "ink", "write", "writing", "editing", "sign", "signature", "fountain pen", "illustrator", ], Icon: Icons.PenNibStraight, }, { name: "pencil", categories: [IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.OFFICE], tags: ["*updated*", "write", "writing", "editing", "sign", "signature"], Icon: Icons.Pencil, }, { name: "pencil-circle", categories: [IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.OFFICE], tags: ["write", "writing", "editing", "sign", "signature"], Icon: Icons.PencilCircle, }, { name: "pencil-line", categories: [IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.OFFICE], tags: ["*updated*", "write", "writing", "editing", "sign", "signature"], Icon: Icons.PencilLine, }, { name: "pencil-simple", categories: [IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.OFFICE], tags: ["*updated*", "write", "writing", "editing", "sign", "signature"], Icon: Icons.PencilSimple, }, { name: "pencil-simple-line", categories: [IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.OFFICE], tags: ["*new*", "write", "writing", "editing", "sign", "signature"], Icon: Icons.PencilSimpleLine, }, { name: "percent", categories: [IconCategory.DEVELOPMENT, IconCategory.FINANCE], tags: [ "%", "percentage", "percentile", "ratio", "delta", "mathematics", "arithmetic", "calculator", ], Icon: Icons.Percent, }, { name: "perspective", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["*new*", "3d", "skew", "warp", "trapezoid"], Icon: Icons.Perspective, }, { name: "phone", categories: [IconCategory.COMMUNICATION, IconCategory.SYSTEM], tags: ["calls", "telephone", "landline", "talk"], Icon: Icons.Phone, }, { name: "phone-call", categories: [IconCategory.COMMUNICATION, IconCategory.SYSTEM], tags: ["calls", "calling", "ringing", "telephone", "landline", "talk"], Icon: Icons.PhoneCall, }, { name: "phone-disconnect", categories: [IconCategory.COMMUNICATION, IconCategory.SYSTEM], tags: ["calls", "hang up", "disconnected", "telephone", "landline", "talk"], Icon: Icons.PhoneDisconnect, }, { name: "phone-incoming", categories: [IconCategory.COMMUNICATION, IconCategory.SYSTEM], tags: ["calls", "calling", "telephone", "landline", "talk"], Icon: Icons.PhoneIncoming, }, { name: "phone-outgoing", categories: [IconCategory.COMMUNICATION, IconCategory.SYSTEM], tags: ["calls", "calling", "telephone", "landline", "talk"], Icon: Icons.PhoneOutgoing, }, { name: "phone-slash", categories: [IconCategory.COMMUNICATION, IconCategory.SYSTEM], tags: [ "calls", "disabled", "disconnected", "telephone", "landline", "talk", ], Icon: Icons.PhoneSlash, }, { name: "phone-x", categories: [IconCategory.COMMUNICATION, IconCategory.SYSTEM], tags: ["calls", "missed", "errors", "telephone", "landline", "talk"], Icon: Icons.PhoneX, }, { name: "phosphor-logo", categories: [IconCategory.BRAND], tags: ["logos"], Icon: Icons.PhosphorLogo, }, { name: "piano-keys", categories: [IconCategory.MEDIA, IconCategory.OBJECTS], tags: ["*new*", "music", "instrument", "keyboard"], Icon: Icons.PianoKeys, }, { name: "picture-in-picture", categories: [IconCategory.MEDIA, IconCategory.SYSTEM], tags: ["pip", "pop-out", "minimize", "maximize"], Icon: Icons.PictureInPicture, }, { name: "pill", categories: [IconCategory.HEALTH], tags: [ "capsule", "medicine", "rx", "pharmacy", "pharmacist", "pharmaceuticals", "prescription", "drugs", ], Icon: Icons.Pill, }, { name: "pinterest-logo", categories: [IconCategory.BRAND, IconCategory.COMMUNICATION], tags: ["*updated*", "logos", "vision board", "mood board", "social media"], Icon: Icons.PinterestLogo, }, { name: "pinwheel", categories: [IconCategory.GAMES, IconCategory.OBJECTS], tags: ["*new*", "toys", "whirligig"], Icon: Icons.Pinwheel, }, { name: "pizza", categories: [IconCategory.COMMERCE, IconCategory.MAP], tags: [ "fast food", "party", "places", "locations", "restaurants", "food", "dining", ], Icon: Icons.Pizza, }, { name: "placeholder", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["empty", "notdef", "tofu", "rectangle slash", "missing"], Icon: Icons.Placeholder, }, { name: "planet", categories: [IconCategory.NATURE], tags: ["saturn", "world", "globe", "astronomy", "space"], Icon: Icons.Planet, }, { name: "play", categories: [IconCategory.MEDIA], tags: ["music", "audio", "resume", "start"], Icon: Icons.Play, }, { name: "play-circle", categories: [IconCategory.MEDIA], tags: ["music", "audio", "resume", "start", "round"], Icon: Icons.PlayCircle, }, { name: "playlist", categories: [IconCategory.MEDIA], tags: ["music", "audio", "queue"], Icon: Icons.Playlist, }, { name: "plug", categories: [IconCategory.SYSTEM, IconCategory.OBJECTS], tags: ["*new*", "outlet", "socket", "plugin", "integration"], Icon: Icons.Plug, }, { name: "plugs", categories: [IconCategory.SYSTEM, IconCategory.OBJECTS], tags: [ "*new*", "outlet", "socket", "plugin", "integration", "disconnected", ], Icon: Icons.Plugs, }, { name: "plugs-connected", categories: [IconCategory.SYSTEM, IconCategory.OBJECTS], tags: ["*new*", "outlet", "socket", "plugin", "integration"], Icon: Icons.PlugsConnected, }, { name: "plus", categories: [ IconCategory.DEVELOPMENT, IconCategory.FINANCE, IconCategory.SYSTEM, ], tags: ["addition", "sum", "mathematics", "arithmetic", "calculator", "+"], Icon: Icons.Plus, }, { name: "plus-circle", categories: [ IconCategory.DEVELOPMENT, IconCategory.FINANCE, IconCategory.SYSTEM, ], tags: [ "addition", "sum", "mathematics", "arithmetic", "calculator", "round", "+", ], Icon: Icons.PlusCircle, }, { name: "plus-minus", categories: [IconCategory.DEVELOPMENT, IconCategory.FINANCE], tags: [ "plus or minus", "plus/minus", "add/subtract", "addition", "sum", "subtraction", "difference", "mathematics", "arithmetic", "calculator", "+", "-", "±", ], Icon: Icons.PlusMinus, }, { name: "poker-chip", categories: [IconCategory.GAMES], tags: ["chips", "tokens", "cards", "gambling", "casino"], Icon: Icons.PokerChip, }, // { // name: "police", // categories: [IconCategory.MAP, IconCategory.PEOPLE], // tags: [ "law enforcement", "emergency", "safety", "security"], // Icon: Icons.Police, // }, { name: "police-car", categories: [IconCategory.MAP, IconCategory.OBJECTS], tags: ["*new*", "vehicles", "cars", "automobiles", "law enforcement"], Icon: Icons.PoliceCar, }, { name: "polygon", categories: [IconCategory.DESIGN], tags: ["shapes", "drawing"], Icon: Icons.Polygon, }, { name: "popcorn", categories: [IconCategory.MAP, IconCategory.COMMERCE], tags: ["*new*", "food", "movies", "theater"], Icon: Icons.Popcorn, }, { name: "power", categories: [IconCategory.SYSTEM], tags: [ "charged", "charger", "charging", "on", "off", "on/off", "switch", "power switch", ], Icon: Icons.Power, }, { name: "prescription", categories: [IconCategory.HEALTH], tags: [ "rx", "medicine", "drugs", "pharmacy", "pharmacist", "pharmaceuticals", "doctor", ], Icon: Icons.Prescription, }, { name: "presentation", categories: [IconCategory.FINANCE, IconCategory.OFFICE], tags: [ "whiteboard", "flipchart", "charts", "statistics", "analyze", "analysis", "meeting", ], Icon: Icons.Presentation, }, { name: "presentation-chart", categories: [IconCategory.FINANCE, IconCategory.OFFICE], tags: [ "whiteboard", "flipchart", "graphs", "graphing", "charts", "statistics", "analyze", "analysis", "meeting", ], Icon: Icons.PresentationChart, }, { name: "printer", categories: [IconCategory.EDITOR, IconCategory.OFFICE], tags: ["printing"], Icon: Icons.Printer, }, { name: "prohibit", categories: [IconCategory.MAP, IconCategory.SYSTEM], tags: [ "forbidden", "prohibited", "cancelled", "prevent", "stop", "do not enter", ], Icon: Icons.Prohibit, }, { name: "prohibit-inset", categories: [IconCategory.MAP, IconCategory.SYSTEM], tags: [ "forbidden", "prohibited", "cancelled", "prevent", "stop", "do not enter", ], Icon: Icons.ProhibitInset, }, { name: "projector-screen", categories: [IconCategory.FINANCE, IconCategory.MEDIA, IconCategory.OFFICE], tags: [ "projection", "presentation", "slideshow", "movies", "charts", "statistics", "analyze", "analysis", ], Icon: Icons.ProjectorScreen, }, { name: "projector-screen-chart", categories: [IconCategory.FINANCE, IconCategory.OFFICE], tags: [ "projection", "presentation", "slideshow", "graphs", "graphing", "charts", "statistics", "analyze", "analysis", ], Icon: Icons.ProjectorScreenChart, }, { name: "push-pin", categories: [IconCategory.OFFICE, IconCategory.MAP, IconCategory.OBJECTS], tags: ["favorites", "favorited", "pushpin"], Icon: Icons.PushPin, }, { name: "push-pin-slash", categories: [IconCategory.OFFICE, IconCategory.MAP, IconCategory.OBJECTS], tags: ["favorites", "favorited", "pushpin", "disabled"], Icon: Icons.PushPinSlash, }, { name: "push-pin-simple", categories: [IconCategory.OFFICE, IconCategory.MAP, IconCategory.OBJECTS], tags: ["favorites", "favorited", "pushpin"], Icon: Icons.PushPinSimple, }, { name: "push-pin-simple-slash", categories: [IconCategory.OFFICE, IconCategory.MAP, IconCategory.OBJECTS], tags: ["favorites", "favorited", "pushpin", "disabled"], Icon: Icons.PushPinSimpleSlash, }, { name: "puzzle-piece", categories: [IconCategory.GAMES, IconCategory.DEVELOPMENT], tags: ["board game", "element", "component", "extension", "plugin"], Icon: Icons.PuzzlePiece, }, { name: "qr-code", categories: [IconCategory.SYSTEM], tags: ["upc", "barcode", "products", "shopping", "scanner"], Icon: Icons.QrCode, }, { name: "question", categories: [IconCategory.SYSTEM], tags: ["information", "help", "support", "questions"], Icon: Icons.Question, }, { name: "queue", categories: [IconCategory.MEDIA], tags: ["music", "audio", "playlist"], Icon: Icons.Queue, }, { name: "quotes", categories: [ IconCategory.COMMUNICATION, IconCategory.EDITOR, IconCategory.MEDIA, ], tags: ["quoations", "quotation marks", "double-quotes", "writing", "books"], Icon: Icons.Quotes, }, { name: "radical", categories: [IconCategory.DEVELOPMENT, IconCategory.FINANCE], tags: [ "√", "radix", "radicand", "square root", "squareroot", "mathematics", "arithmetic", "calculator", ], Icon: Icons.Radical, }, { name: "radio", categories: [ IconCategory.COMMUNICATION, IconCategory.MEDIA, IconCategory.OBJECTS, ], tags: ["broadcast", "fm", "am", "xm", "transmitter", "receiver"], Icon: Icons.Radio, }, { name: "radio-button", categories: [IconCategory.SYSTEM], tags: ["*new*", "input", "checkbox", "checked"], Icon: Icons.RadioButton, }, { name: "rainbow", categories: [IconCategory.WEATHER], tags: ["meteorology", "rainstorm", "arc", "pride", "LGBTQ+", "leprechaun"], Icon: Icons.Rainbow, }, { name: "rainbow-cloud", categories: [IconCategory.WEATHER], tags: [ "meteorology", "rainstorm", "cloudy", "partly cloudy", "partly sunny", "pride", "LGBTQ+", "leprechaun", ], Icon: Icons.RainbowCloud, }, { name: "receipt", categories: [IconCategory.COMMERCE, IconCategory.FINANCE], tags: ["purchased", "money", "clipping", "expenses"], Icon: Icons.Receipt, }, { name: "record", categories: [IconCategory.MEDIA], tags: ["music", "audio", "recording", "recorder", "voice memo"], Icon: Icons.Record, }, { name: "rectangle", categories: [IconCategory.DESIGN], tags: ["4", "shapes", "polygons", "box"], Icon: Icons.Rectangle, }, { name: "recycle", categories: [IconCategory.ARROWS, IconCategory.NATURE], tags: ["recycling", "trash", "environmental", "green"], Icon: Icons.Recycle, }, { name: "reddit-logo", categories: [IconCategory.BRAND, IconCategory.COMMUNICATION], tags: ["logos", "subreddit", "snoo", "social media"], Icon: Icons.RedditLogo, }, { name: "repeat", categories: [IconCategory.MEDIA], tags: ["music", "audio", "recycle"], Icon: Icons.Repeat, }, { name: "repeat-once", categories: [IconCategory.MEDIA], tags: ["music", "audio", "recycle"], Icon: Icons.RepeatOnce, }, { name: "rewind", categories: [IconCategory.MEDIA], tags: [ "music", "audio", "seek", "scrub", "scan", "skip", "back", "backwards", "reverse", ], Icon: Icons.Rewind, }, { name: "rewind-circle", categories: [IconCategory.MEDIA], tags: [ "music", "audio", "seek", "scrub", "scan", "skip", "back", "backwards", "reverse", ], Icon: Icons.RewindCircle, }, { name: "robot", categories: [IconCategory.DEVELOPMENT, IconCategory.OBJECTS], tags: ["automaton", "artificial intelligence"], Icon: Icons.Robot, }, { name: "rocket", categories: [ IconCategory.DEVELOPMENT, IconCategory.MAP, IconCategory.OBJECTS, ], tags: ["spaceship", "launch", "deployment", "rocketship"], Icon: Icons.Rocket, }, { name: "rocket-launch", categories: [ IconCategory.DEVELOPMENT, IconCategory.MAP, IconCategory.OBJECTS, ], tags: ["spaceship", "flying", "blastoff", "deployment", "rocketship"], Icon: Icons.RocketLaunch, }, { name: "rows", categories: [IconCategory.DESIGN], tags: ["2", "shapes", "polygons", "box", "stack", "list", "table", "cards"], Icon: Icons.Rows, }, { name: "rss", categories: [IconCategory.COMMUNICATION], tags: ["radio", "broadcast", "web feed", "news", "aggregator"], Icon: Icons.Rss, }, { name: "rss-simple", categories: [IconCategory.COMMUNICATION], tags: ["radio", "broadcast", "web feed", "news", "aggregator"], Icon: Icons.RssSimple, }, { name: "rug", categories: [IconCategory.OBJECTS], tags: ["*new*", "tapestry", "carpet"], Icon: Icons.Rug, }, { name: "ruler", categories: [ IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.OBJECTS, ], tags: ["*updated*", "measure", "scale", "distance"], Icon: Icons.Ruler, }, { name: "scales", categories: [IconCategory.COMMERCE, IconCategory.MAP, IconCategory.OBJECTS], tags: ["measure", "balance", "law", "justice", "government"], Icon: Icons.Scales, }, // { // name: "scalpel", // categories: [IconCategory.DESIGN, IconCategory.HEALTH], // tags: [ "x-acto", "hobby knife", "craft knife", "razor", "slice"], // Icon: Icons.Scalpel, // }, { name: "scan", categories: [IconCategory.SYSTEM], tags: ["*new*", "upc", "barcode", "products", "shopping", "scanner"], Icon: Icons.Scan, }, { name: "scissors", categories: [ IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.OFFICE, IconCategory.SYSTEM, ], tags: ["cut", "snip", "clipboard"], Icon: Icons.Scissors, }, { name: "screencast", categories: [IconCategory.MEDIA, IconCategory.SYSTEM], tags: [ "apple", "airplay", "screencasting", "screen share", "television", "tv", ], Icon: Icons.Screencast, }, { name: "scribble-loop", categories: [IconCategory.DESIGN], tags: ["doodles", "drawing", "sign", "signature"], Icon: Icons.ScribbleLoop, }, { name: "scroll", categories: [IconCategory.GAMES, IconCategory.OBJECTS], tags: ["*new*", "parchment", "paper", "script", "spell", "fantasy"], Icon: Icons.Scroll, }, { name: "selection", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["marquis", "select"], Icon: Icons.Selection, }, { name: "selection-all", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["marquis", "select all"], Icon: Icons.SelectionAll, }, { name: "selection-inverse", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["marquis", "invert"], Icon: Icons.SelectionInverse, }, { name: "selection-plus", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["marquis", "add"], Icon: Icons.SelectionPlus, }, { name: "selection-slash", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["marquis", "unselect"], Icon: Icons.SelectionSlash, }, { name: "selection-foreground", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["marquis"], Icon: Icons.SelectionForeground, }, { name: "selection-background", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["marquis"], Icon: Icons.SelectionBackground, }, { name: "share", categories: [IconCategory.COMMUNICATION, IconCategory.SYSTEM], tags: ["send to", "export", "arrows"], Icon: Icons.Share, }, { name: "share-network", categories: [IconCategory.COMMUNICATION, IconCategory.SYSTEM], tags: ["send to", "export"], Icon: Icons.ShareNetwork, }, { name: "shield", categories: [IconCategory.SYSTEM, IconCategory.OBJECTS], tags: [ "security", "secured", "defense", "defended", "authentication", "authenticated", "guarded", "locked", "encrypted", "encryption", ], Icon: Icons.Shield, }, { name: "shield-check", categories: [IconCategory.SYSTEM, IconCategory.OBJECTS], tags: [ "security", "secured", "defense", "defended", "authentication", "authenticated", "guarded", "locked", "encrypted", "encryption", ], Icon: Icons.ShieldCheck, }, { name: "shield-checkered", categories: [IconCategory.SYSTEM, IconCategory.OBJECTS], tags: [ "security", "secured", "defense", "defended", "authentication", "authenticated", "guarded", "locked", "encrypted", "encryption", ], Icon: Icons.ShieldCheckered, }, { name: "shield-chevron", categories: [IconCategory.SYSTEM, IconCategory.OBJECTS], tags: [ "security", "secured", "defense", "defended", "authentication", "authenticated", "guarded", "locked", "encrypted", "encryption", ], Icon: Icons.ShieldChevron, }, { name: "shield-plus", categories: [IconCategory.SYSTEM, IconCategory.OBJECTS], tags: [ "security", "secured", "defense", "defended", "authentication", "authenticated", "guarded", "locked", "encrypted", "encryption", ], Icon: Icons.ShieldPlus, }, { name: "shield-slash", categories: [IconCategory.SYSTEM, IconCategory.OBJECTS], tags: [ "security", "unsecured", "defense", "undefended", "authentication", "unauthenticated", "unguarded", "unlocked", "unencrypted", "encryption", "disabled", ], Icon: Icons.ShieldSlash, }, { name: "shield-star", categories: [IconCategory.OBJECTS, IconCategory.SYSTEM], tags: [ "*new*", "badge", "security", "defense", "authentication", "authenticated", "guarded", "locked", "encrypted", "encryption", ], Icon: Icons.ShieldStar, }, { name: "shield-warning", categories: [IconCategory.SYSTEM, IconCategory.OBJECTS], tags: [ "security", "unsecured", "defense", "undefended", "authentication", "unauthenticated", "unguarded", "unlocked", "unencrypted", "encryption", "errors", ], Icon: Icons.ShieldWarning, }, { name: "shopping-bag", categories: [IconCategory.COMMERCE, IconCategory.MAP, IconCategory.OBJECTS], tags: [ "ecommerce", "market", "basket", "buying", "checkout", "places", "locations", ], Icon: Icons.ShoppingBag, }, { name: "shopping-bag-open", categories: [IconCategory.COMMERCE, IconCategory.MAP, IconCategory.OBJECTS], tags: [ "ecommerce", "market", "basket", "buying", "checkout", "places", "locations", ], Icon: Icons.ShoppingBagOpen, }, { name: "shopping-cart", categories: [IconCategory.COMMERCE, IconCategory.MAP, IconCategory.OBJECTS], tags: [ "ecommerce", "market", "basket", "buying", "groceries", "checkout", "places", "locations", ], Icon: Icons.ShoppingCart, }, { name: "shopping-cart-simple", categories: [IconCategory.COMMERCE, IconCategory.MAP, IconCategory.OBJECTS], tags: [ "ecommerce", "market", "basket", "buying", "groceries", "checkout", "places", "locations", ], Icon: Icons.ShoppingCartSimple, }, { name: "shower", categories: [IconCategory.OBJECTS], tags: ["bath", "bathtub", "bathroom", "faucet"], Icon: Icons.Shower, }, { name: "shuffle", categories: [IconCategory.MEDIA, IconCategory.ARROWS], tags: ["music", "audio", "randomize", "crossed"], Icon: Icons.Shuffle, }, { name: "shuffle-angular", categories: [IconCategory.MEDIA, IconCategory.ARROWS], tags: ["music", "audio", "randomize", "crossed"], Icon: Icons.ShuffleAngular, }, { name: "shuffle-simple", categories: [IconCategory.MEDIA, IconCategory.ARROWS], tags: ["music", "audio", "randomize", "crossed"], Icon: Icons.ShuffleSimple, }, { name: "sidebar", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["*new*", "left rail", "wireframe", "ui", "interface"], Icon: Icons.Sidebar, }, { name: "sidebar-simple", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["*new*", "left rail", "wireframe", "ui", "interface"], Icon: Icons.SidebarSimple, }, { name: "sign-in", categories: [IconCategory.SYSTEM], tags: ["signin", "login", "log in", "enter"], Icon: Icons.SignIn, }, { name: "sign-out", categories: [IconCategory.SYSTEM], tags: ["signout", "logout", "log out", "exit"], Icon: Icons.SignOut, }, { name: "signpost", categories: [IconCategory.MAP], tags: [ "*new*", "direction", "traffic", "road sign", "transit", "transportation", ], Icon: Icons.Signpost, }, { name: "sim-card", categories: [IconCategory.COMMUNICATION, IconCategory.SYSTEM], tags: ["cellular", "cellphone", "mobile"], Icon: Icons.SimCard, }, { name: "sketch-logo", categories: [IconCategory.DESIGN], tags: [ "drawing", "art", "illustration", "ui", "interface", "prototype", "prototyping", "gemstone", "diamond", ], Icon: Icons.SketchLogo, }, { name: "skip-back", categories: [IconCategory.MEDIA], tags: [ "music", "audio", "seek", "scrub", "scan", "back", "backwards", "reverse", "previous", ], Icon: Icons.SkipBack, }, { name: "skip-back-circle", categories: [IconCategory.MEDIA], tags: [ "music", "audio", "seek", "scrub", "scan", "back", "backwards", "reverse", "previous", ], Icon: Icons.SkipBackCircle, }, { name: "skip-forward", categories: [IconCategory.MEDIA], tags: ["music", "audio", "seek", "scrub", "scan", "ahead", "next"], Icon: Icons.SkipForward, }, { name: "skip-forward-circle", categories: [IconCategory.MEDIA], tags: ["music", "audio", "seek", "scrub", "scan", "ahead", "next"], Icon: Icons.SkipForwardCircle, }, { name: "skull", categories: [IconCategory.GAMES], tags: ["*new*", "death", "dead", "kill"], Icon: Icons.Skull, }, { name: "slack-logo", categories: [IconCategory.BRAND, IconCategory.COMMUNICATION], tags: ["logos", "messaging"], Icon: Icons.SlackLogo, }, { name: "sliders", categories: [IconCategory.MEDIA, IconCategory.SYSTEM], tags: [ "music", "audio", "faders", "filters", "equalizer", "volume", "settings", "preferences", ], Icon: Icons.Sliders, }, { name: "sliders-horizontal", categories: [IconCategory.MEDIA, IconCategory.SYSTEM], tags: [ "music", "audio", "faders", "filters", "equalizer", "volume", "settings", "preferences", ], Icon: Icons.SlidersHorizontal, }, { name: "smiley", categories: [IconCategory.COMMUNICATION, IconCategory.PEOPLE], tags: ["face", "emoji", "happy", "grinning", "smiling"], Icon: Icons.Smiley, }, { name: "smiley-blank", categories: [IconCategory.COMMUNICATION, IconCategory.PEOPLE], tags: ["face", "emoji", "unimpressed", "no face"], Icon: Icons.SmileyBlank, }, { name: "smiley-meh", categories: [IconCategory.COMMUNICATION, IconCategory.PEOPLE], tags: ["face", "emoji", "unimpressed", "neutral"], Icon: Icons.SmileyMeh, }, { name: "smiley-nervous", categories: [IconCategory.COMMUNICATION, IconCategory.PEOPLE], tags: [ "face", "smiley", "emoji", "anxious", "uncomfortable", "uneasy", "queasy", "sick", "ill", ], Icon: Icons.SmileyNervous, }, { name: "smiley-sad", categories: [IconCategory.COMMUNICATION, IconCategory.PEOPLE], tags: ["face", "emoji", "unhappy", "frowning"], Icon: Icons.SmileySad, }, { name: "smiley-sticker", categories: [IconCategory.COMMUNICATION, IconCategory.PEOPLE], tags: ["face", "emoji", "happy", "grinning", "smiling"], Icon: Icons.SmileySticker, }, { name: "smiley-wink", categories: [IconCategory.COMMUNICATION, IconCategory.PEOPLE], tags: ["face", "emoji", "winking", "flirting", "cute"], Icon: Icons.SmileyWink, }, { name: "smiley-x-eyes", categories: [IconCategory.COMMUNICATION, IconCategory.PEOPLE], tags: ["face", "emoji", "dead", "killed", "unconscious"], Icon: Icons.SmileyXEyes, }, { name: "snapchat-logo", categories: [IconCategory.BRAND, IconCategory.COMMUNICATION], tags: ["logos", "messaging", "social media"], Icon: Icons.SnapchatLogo, }, { name: "snowflake", categories: [IconCategory.WEATHER], tags: ["meteorology", "snowy", "snowing", "snowstorm"], Icon: Icons.Snowflake, }, { name: "soccer-ball", categories: [IconCategory.GAMES, IconCategory.HEALTH], tags: ["sports", "football", "mls"], Icon: Icons.SoccerBall, }, { name: "sort-ascending", categories: [IconCategory.EDITOR], tags: ["sorted", "sorting", "increasing", "a to z", "arrows"], Icon: Icons.SortAscending, }, { name: "sort-descending", categories: [IconCategory.EDITOR], tags: ["sorted", "sorting", "decreasing", "z to a", "arrows"], Icon: Icons.SortDescending, }, { name: "spade", categories: [IconCategory.GAMES], tags: ["spades", "suits", "cards", "gambling", "casino", "gaming"], Icon: Icons.Spade, }, { name: "sparkle", categories: [IconCategory.COMMUNICATION, IconCategory.NATURE], tags: ["star", "rate", "ratings", "favorites", "favorited"], Icon: Icons.Sparkle, }, { name: "speaker-high", categories: [IconCategory.MEDIA, IconCategory.SYSTEM], tags: ["music", "audio", "volume", "sound"], Icon: Icons.SpeakerHigh, }, { name: "speaker-low", categories: [IconCategory.MEDIA, IconCategory.SYSTEM], tags: ["music", "audio", "volume", "sound"], Icon: Icons.SpeakerLow, }, { name: "speaker-none", categories: [IconCategory.MEDIA, IconCategory.SYSTEM], tags: ["music", "audio", "muted", "volume", "sound"], Icon: Icons.SpeakerNone, }, { name: "speaker-slash", categories: [IconCategory.MEDIA, IconCategory.SYSTEM], tags: ["music", "audio", "muted", "volume", "sound", "disabled"], Icon: Icons.SpeakerSlash, }, { name: "speaker-x", categories: [IconCategory.MEDIA, IconCategory.SYSTEM], tags: ["music", "audio", "muted", "volume", "sound", "disabled", "errors"], Icon: Icons.SpeakerX, }, { name: "speaker-simple-high", categories: [IconCategory.MEDIA, IconCategory.SYSTEM], tags: ["music", "audio", "volume", "sound"], Icon: Icons.SpeakerSimpleHigh, }, { name: "speaker-simple-low", categories: [IconCategory.MEDIA, IconCategory.SYSTEM], tags: ["music", "audio", "volume", "sound"], Icon: Icons.SpeakerSimpleLow, }, { name: "speaker-simple-none", categories: [IconCategory.MEDIA, IconCategory.SYSTEM], tags: ["music", "audio", "muted", "volume", "sound"], Icon: Icons.SpeakerSimpleNone, }, { name: "speaker-simple-slash", categories: [IconCategory.MEDIA, IconCategory.SYSTEM], tags: ["music", "audio", "muted", "volume", "sound", "disabled"], Icon: Icons.SpeakerSimpleSlash, }, { name: "speaker-simple-x", categories: [IconCategory.MEDIA, IconCategory.SYSTEM], tags: ["music", "audio", "muted", "volume", "sound", "disabled", "errors"], Icon: Icons.SpeakerSimpleX, }, { name: "spinner", categories: [IconCategory.SYSTEM], tags: ["loading", "loader", "waiting", "progress"], Icon: Icons.Spinner, }, { name: "spinner-gap", categories: [IconCategory.SYSTEM], tags: ["loading", "loader", "waiting", "progress"], Icon: Icons.SpinnerGap, }, { name: "spiral", categories: [IconCategory.COMMUNICATION, IconCategory.DESIGN], tags: ["*new*", "spin", "rotate", "dizzy"], Icon: Icons.Spiral, }, { name: "spotify-logo", categories: [IconCategory.BRAND, IconCategory.MEDIA], tags: ["music", "player", "streaming"], Icon: Icons.SpotifyLogo, }, { name: "square", categories: [IconCategory.DESIGN], tags: ["4", "shapes", "polygons", "box"], Icon: Icons.Square, }, { name: "square-half", categories: [IconCategory.DESIGN], tags: [ "*updated*", "4", "shapes", "polygons", "box", "columns", "sidebar", "split vertical", ], Icon: Icons.SquareHalf, }, { name: "square-half-bottom", categories: [IconCategory.DESIGN], tags: [ "*new*", "4", "shapes", "polygons", "box", "columns", "sidebar", "split vertical", ], Icon: Icons.SquareHalfBottom, }, { name: "squares-four", categories: [IconCategory.DESIGN, IconCategory.SYSTEM], tags: [ "4", "shapes", "polygons", "apps", "applications", "grid", "table", "microsoft", "logos", ], Icon: Icons.SquaresFour, }, { name: "square-logo", categories: [IconCategory.BRAND, IconCategory.COMMERCE], tags: ["squareup", "payment"], Icon: Icons.SquareLogo, }, { name: "stack", categories: [IconCategory.DESIGN, IconCategory.OFFICE, IconCategory.EDITOR], tags: ["cards", "layers"], Icon: Icons.Stack, }, { name: "stack-simple", categories: [IconCategory.DESIGN, IconCategory.OFFICE, IconCategory.EDITOR], tags: ["cards", "layers"], Icon: Icons.StackSimple, }, { name: "stack-overflow-logo", categories: [IconCategory.BRAND, IconCategory.DEVELOPMENT], tags: ["*new*", "logos", "code"], Icon: Icons.StackOverflowLogo, }, { name: "stamp", categories: [IconCategory.DESIGN, IconCategory.OBJECTS], tags: ["*new*", "clone", "seal", "official"], Icon: Icons.Stamp, }, { name: "star", categories: [ IconCategory.COMMUNICATION, IconCategory.MAP, IconCategory.NATURE, ], tags: ["rate", "ratings", "favorites", "favorited"], Icon: Icons.Star, }, { name: "star-half", categories: [IconCategory.COMMUNICATION], tags: ["*updated*", "rate", "ratings"], Icon: Icons.StarHalf, }, { name: "star-four", categories: [IconCategory.COMMUNICATION, IconCategory.NATURE], tags: ["rate", "ratings", "favorites", "favorited"], Icon: Icons.StarFour, }, // { // name: "steam-logo", // categories: [IconCategory.BRAND, IconCategory.GAMES], // tags: [ "logos","gaming", "valve"], // Icon: Icons.SteamLogo, // }, { name: "sticker", categories: [IconCategory.COMMUNICATION], tags: ["stickers", "sticker pack", "labels"], Icon: Icons.Sticker, }, { name: "stop", categories: [IconCategory.MEDIA], tags: ["music", "audio"], Icon: Icons.Stop, }, { name: "stop-circle", categories: [IconCategory.MEDIA], tags: ["music", "audio", "round"], Icon: Icons.StopCircle, }, { name: "storefront", categories: [IconCategory.COMMERCE, IconCategory.MAP], tags: [ "shops", "shopping", "markets", "stores", "buildings", "places", "locations", ], Icon: Icons.Storefront, }, { name: "strategy", categories: [IconCategory.GAMES, IconCategory.FINANCE], tags: ["*new*", "sports", "strategem", "plan", "tic-tac-toe"], Icon: Icons.Strategy, }, { name: "stripe-logo", categories: [IconCategory.BRAND, IconCategory.COMMERCE], tags: ["payment"], Icon: Icons.StripeLogo, }, { name: "student", categories: [IconCategory.PEOPLE], tags: [ "pupil", "classroom", "teacher", "education", "school", "college", "university", ], Icon: Icons.Student, }, { name: "suitcase", categories: [IconCategory.OFFICE, IconCategory.OBJECTS], tags: ["briefcase", "valise", "baggage", "folders", "portfolio"], Icon: Icons.Suitcase, }, { name: "suitcase-simple", categories: [IconCategory.OFFICE, IconCategory.OBJECTS], tags: ["briefcase", "valise", "baggage", "folders", "portfolio"], Icon: Icons.SuitcaseSimple, }, { name: "sun", categories: [ IconCategory.NATURE, IconCategory.SYSTEM, IconCategory.WEATHER, ], tags: [ "day", "daytime", "daylight", "clear", "sunny", "sunshine", "light mode", "brightness", "lighten", "brighten", ], Icon: Icons.Sun, }, { name: "sun-dim", categories: [ IconCategory.NATURE, IconCategory.SYSTEM, IconCategory.WEATHER, ], tags: [ "day", "daytime", "daylight", "clear", "sunny", "sunshine", "light mode", "brightness", "darken", ], Icon: Icons.SunDim, }, { name: "sun-horizon", categories: [IconCategory.NATURE, IconCategory.WEATHER], tags: [ "day", "daytime", "daylight", "clear", "sunny", "sunshine", "sunrise", "sunset", ], Icon: Icons.SunHorizon, }, { name: "sunglasses", categories: [IconCategory.HEALTH, IconCategory.OBJECTS], tags: ["*new*", "vision", "sun", "spectacles"], Icon: Icons.Sunglasses, }, { name: "swap", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["layers", "replace", "exchange", "reverse"], Icon: Icons.Swap, }, { name: "swatches", categories: [ IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.OBJECTS, ], tags: ["colors", "color picker", "samples", "pantone"], Icon: Icons.Swatches, }, { name: "sword", categories: [IconCategory.GAMES, IconCategory.OBJECTS], tags: [ "weapon", "knife", "dagger", "gladius", "video games", "rpg", "gaming", ], Icon: Icons.Sword, }, { name: "syringe", categories: [IconCategory.HEALTH], tags: [ "*new*", "needle", "vaccine", "medicine", "doctor", "shot", "hospital", ], Icon: Icons.Syringe, }, { name: "t-shirt", categories: [IconCategory.OBJECTS], tags: ["clothes", "clothing"], Icon: Icons.TShirt, }, // { // name: "tab", // categories: [IconCategory.SYSTEM], // tags: [ "tabs", "browser", "internet", "interface"], // Icon: Icons.Tab, // }, { name: "tabs", categories: [IconCategory.SYSTEM], tags: ["*new*", "browser", "window", "folders", "files"], Icon: Icons.Tabs, }, { name: "table", categories: [ IconCategory.FINANCE, IconCategory.OFFICE, IconCategory.EDITOR, ], tags: ["tables", "tabular", "speadsheets", "excel", "grid", "form"], Icon: Icons.Table, }, { name: "tag", categories: [ IconCategory.COMMERCE, IconCategory.DEVELOPMENT, IconCategory.OBJECTS, ], tags: ["tags", "hashtag", "labels", "sale", "sell", "price", "discount"], Icon: Icons.Tag, }, { name: "tag-simple", categories: [ IconCategory.COMMERCE, IconCategory.DEVELOPMENT, IconCategory.OBJECTS, ], tags: ["tags", "hashtag", "labels", "sale", "sell", "price", "discount"], Icon: Icons.TagSimple, }, { name: "tag-chevron", categories: [ IconCategory.COMMERCE, IconCategory.DEVELOPMENT, IconCategory.OBJECTS, ], tags: ["tags", "hashtag", "labels", "sale"], Icon: Icons.TagChevron, }, { name: "taxi", categories: [IconCategory.MAP, IconCategory.OBJECTS], tags: [ "*new*", "vehicles", "cars", "automobiles", "livery", "limousine", "uber", ], Icon: Icons.Taxi, }, { name: "target", categories: [IconCategory.MAP, IconCategory.OBJECTS], tags: ["bullseye", "radar", "archery", "accuracy", "precision"], Icon: Icons.Target, }, { name: "telegram-logo", categories: [IconCategory.BRAND, IconCategory.COMMUNICATION], tags: ["logos", "messages", "messaging"], Icon: Icons.TelegramLogo, }, { name: "television", categories: [IconCategory.SYSTEM, IconCategory.OBJECTS], tags: ["screen", "tv", "displays"], Icon: Icons.Television, }, { name: "television-simple", categories: [IconCategory.SYSTEM, IconCategory.OBJECTS], tags: ["screen", "tv", "displays"], Icon: Icons.TelevisionSimple, }, { name: "tennis-ball", categories: [IconCategory.GAMES, IconCategory.HEALTH], tags: ["*updated*", "sports", "mlb"], Icon: Icons.TennisBall, }, { name: "terminal", categories: [IconCategory.DEVELOPMENT, IconCategory.SYSTEM], tags: ["command line", "cli", "bash", "shell", "caret"], Icon: Icons.Terminal, }, { name: "terminal-window", categories: [IconCategory.DEVELOPMENT, IconCategory.SYSTEM], tags: ["command line", "cli", "bash", "shell", "caret"], Icon: Icons.TerminalWindow, }, { name: "test-tube", categories: [ IconCategory.DEVELOPMENT, IconCategory.NATURE, IconCategory.HEALTH, ], tags: ["science", "chemistry", "experiment", "vial"], Icon: Icons.TestTube, }, { name: "text-align-center", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["typography", "print", "font", "alignment", "centered"], Icon: Icons.TextAlignCenter, }, { name: "text-align-justify", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["typography", "print", "font", "alignment", "justified"], Icon: Icons.TextAlignJustify, }, { name: "text-align-left", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["typography", "print", "font", "alignment", "flush left"], Icon: Icons.TextAlignLeft, }, { name: "text-align-right", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["typography", "print", "font", "alignment", "flush right"], Icon: Icons.TextAlignRight, }, { name: "text-aa", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["typography", "typeface", "print", "font"], Icon: Icons.TextAa, }, { name: "text-t", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["typography", "typeface", "print", "font"], Icon: Icons.TextT, }, { name: "text-bolder", categories: [IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.OFFICE], tags: ["typography", "typeface", "print", "font", "boldface", "emphasis"], Icon: Icons.TextBolder, }, { name: "text-h", categories: [IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.OFFICE], tags: ["heading", "typography", "print"], Icon: Icons.TextH, }, { name: "text-h-one", categories: [IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.OFFICE], tags: ["heading", "h1", "typography", "print"], Icon: Icons.TextHOne, }, { name: "text-h-two", categories: [IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.OFFICE], tags: ["heading", "h2", "typography", "print"], Icon: Icons.TextHTwo, }, { name: "text-h-three", categories: [IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.OFFICE], tags: ["heading", "h3", "typography", "print"], Icon: Icons.TextHThree, }, { name: "text-h-four", categories: [IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.OFFICE], tags: ["heading", "h4", "typography", "print"], Icon: Icons.TextHFour, }, { name: "text-h-five", categories: [IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.OFFICE], tags: ["heading", "h5", "typography", "print"], Icon: Icons.TextHFive, }, { name: "text-h-six", categories: [IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.OFFICE], tags: ["heading", "h6", "typography", "print"], Icon: Icons.TextHSix, }, { name: "text-indent", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["*new*", "alignment", "tab"], Icon: Icons.TextIndent, }, { name: "text-outdent", categories: [IconCategory.DESIGN, IconCategory.EDITOR], tags: ["*new*", "alignment", "tab", "unindent", "dedent"], Icon: Icons.TextOutdent, }, { name: "text-italic", categories: [IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.OFFICE], tags: [ "typography", "typeface", "print", "font", "slant", "oblique", "stress", "emphasis", "calligraphy", ], Icon: Icons.TextItalic, }, { name: "text-underline", categories: [IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.OFFICE], tags: ["typography", "typeface", "print", "font", "underscore", "emphasis"], Icon: Icons.TextUnderline, }, { name: "text-strikethrough", categories: [IconCategory.DESIGN, IconCategory.EDITOR, IconCategory.OFFICE], tags: [ "typography", "typeface", "print", "font", "struck", "remove", "delete", "change", ], Icon: Icons.TextStrikethrough, }, { name: "textbox", categories: [IconCategory.EDITOR, IconCategory.SYSTEM], tags: ["*new*", "input", "cursor", "field"], Icon: Icons.Textbox, }, { name: "thermometer", categories: [ IconCategory.WEATHER, IconCategory.HEALTH, IconCategory.OBJECTS, ], tags: [ "meteorology", "temperature", "degrees", "°", "celcius", "centigrade", "kelvin", "fahrenheit", "hot", "warm", "cold", ], Icon: Icons.Thermometer, }, { name: "thermometer-simple", categories: [ IconCategory.WEATHER, IconCategory.HEALTH, IconCategory.OBJECTS, ], tags: [ "meteorology", "temperature", "degrees", "°", "celcius", "centigrade", "kelvin", "fahrenheit", "hot", "warm", "cold", ], Icon: Icons.ThermometerSimple, }, { name: "thermometer-cold", categories: [ IconCategory.WEATHER, IconCategory.HEALTH, IconCategory.OBJECTS, ], tags: [ "meteorology", "temperature", "degrees", "°", "celcius", "centigrade", "kelvin", "fahrenheit", ], Icon: Icons.ThermometerCold, }, { name: "thermometer-hot", categories: [ IconCategory.WEATHER, IconCategory.HEALTH, IconCategory.OBJECTS, ], tags: [ "meteorology", "temperature", "degrees", "°", "celcius", "centigrade", "kelvin", "fahrenheit", "warm", ], Icon: Icons.ThermometerHot, }, { name: "thumbs-up", categories: [IconCategory.COMMUNICATION, IconCategory.PEOPLE], tags: ["like", "love", "favorited", "favorites", "emoji", "yes"], Icon: Icons.ThumbsUp, }, { name: "thumbs-down", categories: [IconCategory.COMMUNICATION, IconCategory.PEOPLE], tags: ["dislike", "hate", "emoji", "no"], Icon: Icons.ThumbsDown, }, { name: "ticket", categories: [IconCategory.COMMERCE, IconCategory.MAP, IconCategory.OBJECTS], tags: ["ticketstub", "movie ticket", "entry", "admissions", "events"], Icon: Icons.Ticket, }, { name: "tiktok-logo", categories: [IconCategory.BRAND, IconCategory.COMMUNICATION], tags: ["logos", "social media"], Icon: Icons.TiktokLogo, }, { name: "timer", categories: [IconCategory.SYSTEM], tags: ["clock", "alarm", "schedule", "events", "stopwatch", "sports"], Icon: Icons.Timer, }, { name: "toggle-left", categories: [IconCategory.SYSTEM], tags: ["switch", "controls", "settings", "preferences"], Icon: Icons.ToggleLeft, }, { name: "toggle-right", categories: [IconCategory.SYSTEM], tags: ["switch", "controls", "settings", "preferences"], Icon: Icons.ToggleRight, }, { name: "toilet", categories: [IconCategory.HEALTH, IconCategory.OBJECTS], tags: ["*new*", "bathroom", "restroom", "lavatory", "water closet"], Icon: Icons.Toilet, }, { name: "toilet-paper", categories: [IconCategory.HEALTH, IconCategory.OBJECTS], tags: ["bathroom", "restroom", "lavatory", "water closet"], Icon: Icons.ToiletPaper, }, { name: "tote", categories: [IconCategory.COMMERCE, IconCategory.OBJECTS], tags: ["suitcases", "valises", "baggage", "tote-bag", "portfolios"], Icon: Icons.Tote, }, { name: "tote-simple", categories: [IconCategory.COMMERCE, IconCategory.OBJECTS], tags: ["suitcases", "valises", "baggage", "tote-bag", "portfolios"], Icon: Icons.ToteSimple, }, { name: "trademark-registered", categories: [IconCategory.COMMERCE], tags: ["*new*", "™", "intellectual property", ""], Icon: Icons.TrademarkRegistered, }, { name: "traffic-cone", categories: [IconCategory.MAP], tags: ["*new*", "pylon", "safety", "transit", "transportation"], Icon: Icons.TrafficCone, }, { name: "traffic-sign", categories: [IconCategory.MAP], tags: ["road signs", "transit", "transportation"], Icon: Icons.TrafficSign, }, { name: "traffic-signal", categories: [IconCategory.MAP], tags: ["*new*", "stop light", "safety", "transit", "transportation"], Icon: Icons.TrafficSignal, }, { name: "train", categories: [IconCategory.MAP, IconCategory.OBJECTS], tags: [ "vehicles", "subway", "light rail", "public transit", "transportation", "commuter", "traveling", "places", "locations", ], Icon: Icons.Train, }, { name: "train-regional", categories: [IconCategory.MAP, IconCategory.OBJECTS], tags: [ "vehicles", "subway", "railroad", "public transit", "transportation", "commuter", "freight", "shipping", "traveling", "places", "locations", ], Icon: Icons.TrainRegional, }, { name: "train-simple", categories: [IconCategory.MAP, IconCategory.OBJECTS], tags: [ "vehicles", "subway", "light rail", "public transit", "transportation", "commuter", "traveling", "places", "locations", ], Icon: Icons.TrainSimple, }, { name: "translate", categories: [IconCategory.COMMUNICATION, IconCategory.SYSTEM], tags: [ "translation", "languages", "internationalization", "i18n", "speech", ], Icon: Icons.Translate, }, { name: "trash", categories: [IconCategory.OFFICE, IconCategory.SYSTEM], tags: ["garbage", "remove", "delete", "destroy", "recycle", "recycling"], Icon: Icons.Trash, }, { name: "trash-simple", categories: [IconCategory.OFFICE, IconCategory.SYSTEM], tags: ["garbage", "remove", "delete", "destroy", "recycle", "recycling"], Icon: Icons.TrashSimple, }, { name: "tray", categories: [ IconCategory.OFFICE, IconCategory.COMMUNICATION, IconCategory.SYSTEM, ], tags: ["inbox", "mailbox", "bin"], Icon: Icons.Tray, }, { name: "tree", categories: [IconCategory.NATURE], tags: ["plants", "branches", "leaves", "green", "environmental"], Icon: Icons.Tree, }, { name: "tree-evergreen", categories: [IconCategory.NATURE], tags: [ "plants", "branches", "leaves", "pine", "conifer", "green", "environmental", ], Icon: Icons.TreeEvergreen, }, { name: "tree-structure", categories: [IconCategory.DEVELOPMENT, IconCategory.OFFICE], tags: [ "data structures", "family tree", "genealogy", "hierarchy", "taxonomy", "charts", "flowchart", ], Icon: Icons.TreeStructure, }, { name: "trend-up", categories: [IconCategory.FINANCE], tags: [ "graphs", "graphing", "charts", "statistics", "analyze", "analysis", "increase", "arrows", ], Icon: Icons.TrendUp, }, { name: "trend-down", categories: [IconCategory.FINANCE], tags: [ "graphs", "graphing", "charts", "statistics", "analyze", "analysis", "decrease", "arrows", ], Icon: Icons.TrendDown, }, { name: "triangle", categories: [IconCategory.DESIGN], tags: ["3", "shapes", "polygons"], Icon: Icons.Triangle, }, { name: "trophy", categories: [IconCategory.GAMES, IconCategory.OBJECTS], tags: ["ribbons", "medals", "winning", "victory", "awards", "prize"], Icon: Icons.Trophy, }, { name: "truck", categories: [IconCategory.COMMERCE, IconCategory.MAP, IconCategory.OBJECTS], tags: ["trucks", "cars", "vehicles", "automobile", "shipping", "delivery"], Icon: Icons.Truck, }, { name: "twitch-logo", categories: [ IconCategory.BRAND, IconCategory.COMMUNICATION, IconCategory.GAMES, ], tags: [ "logos", "streaming", "livestream", "gaming", "video games", "social media", ], Icon: Icons.TwitchLogo, }, { name: "twitter-logo", categories: [IconCategory.BRAND, IconCategory.COMMUNICATION], tags: ["logos", "social media", "tweets", "birds"], Icon: Icons.TwitterLogo, }, { name: "umbrella", categories: [IconCategory.OBJECTS, IconCategory.WEATHER], tags: ["raining", "rainy", "insurance"], Icon: Icons.Umbrella, }, { name: "umbrella-simple", categories: [IconCategory.OBJECTS, IconCategory.WEATHER], tags: ["raining", "rainy", "insurance"], Icon: Icons.UmbrellaSimple, }, { name: "upload", categories: [IconCategory.SYSTEM], tags: [ "*updated*", "saved", "saving", "archived", "archiving", "archival", "uploaded", "uploading", "hard drive", "disk", ], Icon: Icons.Upload, }, { name: "upload-simple", categories: [IconCategory.SYSTEM], tags: [ "saved", "saving", "archived", "archiving", "archival", "uploaded", "uploading", "hard drive", "disk", ], Icon: Icons.UploadSimple, }, { name: "user", categories: [IconCategory.PEOPLE], tags: ["person", "users", "profile", "account", "contact", "login"], Icon: Icons.User, }, { name: "user-focus", categories: [IconCategory.PEOPLE], tags: [ "identification", "biometrics", "facial recognition", "profile", "person", "account", "autofocus", ], Icon: Icons.UserFocus, }, { name: "user-gear", categories: [IconCategory.PEOPLE], tags: [ "person", "users", "profile", "account", "contact", "settings", "preferences", ], Icon: Icons.UserGear, }, { name: "user-list", categories: [IconCategory.PEOPLE], tags: [ "person", "users", "profiles", "accounts", "members", "address book", ], Icon: Icons.UserList, }, { name: "user-plus", categories: [IconCategory.PEOPLE], tags: [ "person", "users", "profile", "account", "contact", "add", "create", "+", ], Icon: Icons.UserPlus, }, { name: "user-minus", categories: [IconCategory.PEOPLE], tags: [ "person", "users", "profile", "account", "contact", "delete", "remove", "-", ], Icon: Icons.UserMinus, }, { name: "user-switch", categories: [IconCategory.PEOPLE], tags: [ "*new*", "person", "users", "profile", "account", "login", "logout", "signin", "signout", "settings", "preferences", ], Icon: Icons.UserSwitch, }, { name: "user-circle", categories: [IconCategory.PEOPLE], tags: ["person", "users", "profile", "account", "contact", "login"], Icon: Icons.UserCircle, }, { name: "user-circle-gear", categories: [IconCategory.PEOPLE], tags: [ "person", "users", "profile", "account", "contact", "settings", "preferences", ], Icon: Icons.UserCircleGear, }, { name: "user-circle-plus", categories: [IconCategory.PEOPLE], tags: [ "person", "users", "profile", "account", "contact", "add", "create", "+", ], Icon: Icons.UserCirclePlus, }, { name: "user-circle-minus", categories: [IconCategory.PEOPLE], tags: [ "person", "users", "profile", "account", "contact", "delete", "remove", "-", ], Icon: Icons.UserCircleMinus, }, { name: "user-rectangle", categories: [IconCategory.PEOPLE], tags: ["person", "users", "profile", "account", "contact", "login"], Icon: Icons.UserRectangle, }, { name: "user-square", categories: [IconCategory.PEOPLE], tags: ["person", "users", "profile", "account", "contact", "login"], Icon: Icons.UserSquare, }, { name: "users", categories: [IconCategory.PEOPLE], tags: [ "user", "group", "team", "people", "profiles", "accounts", "contacts", ], Icon: Icons.Users, }, { name: "users-three", categories: [IconCategory.PEOPLE], tags: [ "user", "group", "team", "community", "people", "profiles", "accounts", "contacts", ], Icon: Icons.UsersThree, }, { name: "users-four", categories: [IconCategory.PEOPLE], tags: [ "user", "group", "team", "department", "community", "people", "profiles", "accounts", "contacts", ], Icon: Icons.UsersFour, }, { name: "vault", categories: [ IconCategory.FINANCE, IconCategory.SYSTEM, IconCategory.OBJECTS, ], tags: [ "*new*", "safe", "bank", "security", "secured", "authentication", "authenticated", "locked", "encrypted", "encryption", ], Icon: Icons.Vault, }, { name: "vibrate", categories: [IconCategory.SYSTEM], tags: [ "audio", "volume", "viration", "ringer", "calls", "silent", "silenced", ], Icon: Icons.Vibrate, }, { name: "video-camera", categories: [IconCategory.MEDIA, IconCategory.SYSTEM], tags: ["videography", "films", "movies", "recording"], Icon: Icons.VideoCamera, }, { name: "video-camera-slash", categories: [IconCategory.MEDIA, IconCategory.SYSTEM], tags: ["videography", "films", "movies", "recording", "disabled"], Icon: Icons.VideoCameraSlash, }, { name: "vignette", categories: [IconCategory.DESIGN], tags: ["*new*", "photography", "darkroom", "movie", "analog"], Icon: Icons.Vignette, }, // { // name: "virus", // categories: [IconCategory.HEALTH], // tags: [ "illness", "disease", "covid-19", "coronavirus", "flu", "cold"], // Icon: Icons.Virus, // }, { name: "voicemail", categories: [IconCategory.SYSTEM], tags: ["phonecalls", "missed", "recording", "telephone", "landline"], Icon: Icons.Voicemail, }, { name: "volleyball", categories: [IconCategory.GAMES, IconCategory.HEALTH], tags: ["sports"], Icon: Icons.Volleyball, }, { name: "wall", categories: [IconCategory.OBJECTS, IconCategory.SYSTEM], tags: ["*updated*", "firewall", "security", "secured", "blocks", "bricks"], Icon: Icons.Wall, }, { name: "wallet", categories: [ IconCategory.COMMERCE, IconCategory.FINANCE, IconCategory.OBJECTS, ], tags: ["money", "payment", "paying", "purchase"], Icon: Icons.Wallet, }, { name: "warning", categories: [IconCategory.SYSTEM], tags: ["alert", "danger", "dangerous", "caution", "errors"], Icon: Icons.Warning, }, { name: "warning-circle", categories: [IconCategory.SYSTEM], tags: ["alert", "danger", "dangerous", "caution", "errors", "round"], Icon: Icons.WarningCircle, }, { name: "warning-octagon", categories: [IconCategory.SYSTEM], tags: ["alert", "danger", "dangerous", "caution", "errors", "8", "eight"], Icon: Icons.WarningOctagon, }, { name: "watch", categories: [IconCategory.SYSTEM], tags: [ "times", "timer", "alarm", "schedule", "events", "clock", "wristwatch", "wearable", ], Icon: Icons.Watch, }, { name: "wave-sawtooth", categories: [IconCategory.MEDIA], tags: [ "*new*", "synth", "synthesizer", "sound", "audio", "music", "waveform", ], Icon: Icons.WaveSawtooth, }, { name: "wave-sine", categories: [IconCategory.MEDIA], tags: [ "*new*", "synth", "synthesizer", "sound", "audio", "music", "waveform", ], Icon: Icons.WaveSine, }, { name: "wave-square", categories: [IconCategory.MEDIA], tags: [ "*new*", "synth", "synthesizer", "sound", "audio", "music", "waveform", ], Icon: Icons.WaveSquare, }, { name: "wave-triangle", categories: [IconCategory.MEDIA], tags: [ "*new*", "synth", "synthesizer", "sound", "audio", "music", "waveform", ], Icon: Icons.WaveTriangle, }, { name: "waves", categories: [IconCategory.NATURE, IconCategory.WEATHER], tags: ["ocean", "tides", "surf"], Icon: Icons.Waves, }, { name: "webcam", categories: [ IconCategory.COMMERCE, IconCategory.OBJECTS, IconCategory.SYSTEM, ], tags: ["*new*", "camera", "video conference"], Icon: Icons.Webcam, }, { name: "whatsapp-logo", categories: [IconCategory.BRAND, IconCategory.COMMUNICATION], tags: ["logos", "messages", "messaging"], Icon: Icons.WhatsappLogo, }, { name: "wheelchair", categories: [IconCategory.HEALTH, IconCategory.MAP, IconCategory.PEOPLE], tags: [ "handicapped", "medical", "disabled", "differently abled", "accessible", "accessibility", "a11y", ], Icon: Icons.Wheelchair, }, // { // name: "wheelchair-motion", // categories: [IconCategory.HEALTH, IconCategory.MAP, IconCategory.PEOPLE], // tags: [ // // "handicapped", // "medical", // "disabled", // "differently abled", // "accessible", // "accessibility", // "a11y", // ], // Icon: Icons.WheelchairMotion, // }, { name: "wifi-high", categories: [IconCategory.SYSTEM], tags: ["wireless", "internet", "network", "connection", "connectivity"], Icon: Icons.WifiHigh, }, { name: "wifi-medium", categories: [IconCategory.SYSTEM], tags: ["wireless", "internet", "network", "connection", "connectivity"], Icon: Icons.WifiMedium, }, { name: "wifi-low", categories: [IconCategory.SYSTEM], tags: ["wireless", "internet", "network", "connection", "connectivity"], Icon: Icons.WifiLow, }, { name: "wifi-none", categories: [IconCategory.SYSTEM], tags: ["wireless", "internet", "network", "connection", "connectivity"], Icon: Icons.WifiNone, }, { name: "wifi-slash", categories: [IconCategory.SYSTEM], tags: [ "wireless", "internet", "network", "connection", "connectivity", "disabled", "disconnected", ], Icon: Icons.WifiSlash, }, { name: "wifi-x", categories: [IconCategory.SYSTEM], tags: [ "*updated*", "wireless", "internet", "network", "connection", "connectivity", "disconnected", "errors", ], Icon: Icons.WifiX, }, { name: "wind", categories: [IconCategory.WEATHER], tags: ["meteorology", "windy", "stormy", "blustery", "gusty", "air"], Icon: Icons.Wind, }, { name: "windows-logo", categories: [IconCategory.BRAND, IconCategory.DEVELOPMENT], tags: ["microsoft", "computers"], Icon: Icons.WindowsLogo, }, { name: "wine", categories: [IconCategory.COMMERCE, IconCategory.MAP, IconCategory.OBJECTS], tags: [ "drinks", "beverages", "vineyard", "places", "locations", "bars", "restaurants", "food", "dining", ], Icon: Icons.Wine, }, { name: "wrench", categories: [IconCategory.SYSTEM, IconCategory.OBJECTS], tags: [ "settings", "setup", "preferences", "tools", "machinery", "mechanical", "repairs", ], Icon: Icons.Wrench, }, { name: "x", categories: [ IconCategory.DEVELOPMENT, IconCategory.FINANCE, IconCategory.SYSTEM, ], tags: [ "×", "closed", "cancelled", "dismissed", "times", "multiply", "mulitplication", "product", "mathematics", "arithmetic", "calculator", ], Icon: Icons.X, }, { name: "x-circle", categories: [IconCategory.SYSTEM], tags: ["closed", "cancelled", "dismissed", "round"], Icon: Icons.XCircle, }, { name: "x-square", categories: [IconCategory.SYSTEM], tags: ["closed", "cancelled", "dismissed"], Icon: Icons.XSquare, }, { name: "yin-yang", categories: [IconCategory.COMMUNICATION], tags: ["*new*", "symbol", "good", "evil", "black", "white"], Icon: Icons.YinYang, }, { name: "youtube-logo", categories: [ IconCategory.BRAND, IconCategory.COMMUNICATION, IconCategory.MEDIA, ], tags: ["logos", "google", "videos", "movies", "social media"], Icon: Icons.YoutubeLogo, }, ]; if (process.env.NODE_ENV === "development") { console.log(`${icons.length} icons`); } export const iconCount = (icons.length * 6) .toString() .replace(/\B(?=(\d{3})+(?!\d))/g, ",");
the_stack
import debugModule from "debug"; const debug = debugModule("codec:abi-data:allocate"); export * as Utils from "./utils"; import type * as Abi from "@truffle/abi-utils"; import * as Import from "@truffle/codec/abi-data/import"; import * as AbiDataUtils from "@truffle/codec/abi-data/utils"; const Web3Utils = require("web3-utils"); //sorry for untyped import import * as Evm from "@truffle/codec/evm"; import * as Common from "@truffle/codec/common"; import type * as Compiler from "@truffle/codec/compiler"; import * as Conversion from "@truffle/codec/conversion"; import * as Ast from "@truffle/codec/ast"; import type * as Contexts from "@truffle/codec/contexts"; import { makeTypeId } from "@truffle/codec/contexts/import"; import type * as Pointer from "@truffle/codec/pointer"; import type { AbiAllocation, AbiAllocations, AbiMemberAllocation, AbiSizeInfo, CalldataAndReturndataAllocation, FunctionCalldataAndReturndataAllocation, ConstructorCalldataAndReturndataAllocation, CalldataAllocation, ReturndataAllocation, ReturnValueReturndataAllocation, RevertReturndataAllocation, ConstructorReturndataAllocation, MessageReturndataAllocation, BlankReturndataAllocation, ReturnImmutableAllocation, CalldataAllocations, CalldataAllocationTemporary, CalldataArgumentAllocation, ContractAllocationInfo, ContractAndContexts, EventAllocation, EventAllocations, EventAllocationTemporary, EventArgumentAllocation, ReturndataAllocations } from "./types"; import type { DecodingMode } from "@truffle/codec/types"; import * as Format from "@truffle/codec/format"; import partition from "lodash.partition"; export { AbiAllocations, AbiSizeInfo, CalldataAllocation, ReturndataAllocation, ReturnValueReturndataAllocation, RevertReturndataAllocation, ConstructorReturndataAllocation, MessageReturndataAllocation, BlankReturndataAllocation, CalldataAndReturndataAllocation, ContractAllocationInfo, ContractAndContexts, EventAllocation, ReturndataAllocations }; interface AbiAllocationInfo { size?: number; //left out for types that don't go in the abi dynamic?: boolean; //similarly allocations: AbiAllocations; } interface EventParameterInfo { type: Format.Types.Type; name: string; indexed: boolean; } export const FallbackOutputAllocation: MessageReturndataAllocation = { kind: "returnmessage", selector: new Uint8Array(), //empty allocationMode: "full" }; export function getAbiAllocations( userDefinedTypes: Format.Types.TypesById ): AbiAllocations { let allocations: AbiAllocations = {}; for (const dataType of Object.values(userDefinedTypes)) { if (dataType.typeClass === "struct") { try { allocations = allocateStruct(dataType, userDefinedTypes, allocations); } catch (_) { //if allocation fails... oh well, allocation fails, we do nothing and just move on :P //note: a better way of handling this would probably be to *mark* it //as failed rather than throwing an exception as that would lead to less //recomputation, but this is simpler and I don't think the recomputation //should really be a problem } } } return allocations; } function allocateStruct( dataType: Format.Types.StructType, userDefinedTypes: Format.Types.TypesById, existingAllocations: AbiAllocations ): AbiAllocations { //NOTE: dataType here should be a *stored* type! //it is up to the caller to take care of this return allocateMembers( dataType.id, dataType.memberTypes, userDefinedTypes, existingAllocations ); } //note: we will still allocate circular structs, even though they're not allowed in the abi, because it's //not worth the effort to detect them. However on mappings or internal functions, we'll vomit (allocate null) function allocateMembers( parentId: string, members: Format.Types.NameTypePair[], userDefinedTypes: Format.Types.TypesById, existingAllocations: AbiAllocations, start: number = 0 ): AbiAllocations { let dynamic: boolean = false; //note that we will mutate the start argument also! //don't allocate things that have already been allocated if (parentId in existingAllocations) { return existingAllocations; } let allocations = { ...existingAllocations }; //otherwise, we'll be adding to this, so we better clone let memberAllocations: AbiMemberAllocation[] = []; for (const member of members) { let length: number; let dynamicMember: boolean; ({ size: length, dynamic: dynamicMember, allocations } = abiSizeAndAllocate( member.type, userDefinedTypes, allocations )); //vomit on illegal types in calldata -- note the short-circuit! if (length === undefined) { allocations[parentId] = null; return allocations; } let pointer: Pointer.AbiPointer = { location: "abi", start, length }; memberAllocations.push({ name: member.name, type: member.type, pointer }); start += length; dynamic = dynamic || dynamicMember; } allocations[parentId] = { members: memberAllocations, length: dynamic ? Evm.Utils.WORD_SIZE : start, dynamic }; return allocations; } //first return value is the actual size. //second return value is whether the type is dynamic //both will be undefined if type is a mapping or internal function //third return value is resulting allocations, INCLUDING the ones passed in function abiSizeAndAllocate( dataType: Format.Types.Type, userDefinedTypes: Format.Types.TypesById, existingAllocations?: AbiAllocations ): AbiAllocationInfo { switch (dataType.typeClass) { case "bool": case "address": case "contract": case "int": case "uint": case "fixed": case "ufixed": case "enum": case "userDefinedValueType": return { size: Evm.Utils.WORD_SIZE, dynamic: false, allocations: existingAllocations }; case "string": return { size: Evm.Utils.WORD_SIZE, dynamic: true, allocations: existingAllocations }; case "bytes": return { size: Evm.Utils.WORD_SIZE, dynamic: dataType.kind === "dynamic", allocations: existingAllocations }; case "mapping": return { allocations: existingAllocations }; case "function": switch (dataType.visibility) { case "external": return { size: Evm.Utils.WORD_SIZE, dynamic: false, allocations: existingAllocations }; case "internal": return { allocations: existingAllocations }; } case "array": { switch (dataType.kind) { case "dynamic": return { size: Evm.Utils.WORD_SIZE, dynamic: true, allocations: existingAllocations }; case "static": if (dataType.length.isZero()) { //arrays of length 0 are static regardless of base type return { size: 0, dynamic: false, allocations: existingAllocations }; } const { size: baseSize, dynamic, allocations } = abiSizeAndAllocate( dataType.baseType, userDefinedTypes, existingAllocations ); return { //WARNING! The use of toNumber() here may throw an exception! //I'm judging this OK since if you have arrays that large we have bigger problems :P size: dataType.length.toNumber() * baseSize, dynamic, allocations }; } } case "struct": { let allocations: AbiAllocations = existingAllocations; let allocation: AbiAllocation | null | undefined = allocations[dataType.id]; if (allocation === undefined) { //if we don't find an allocation, we'll have to do the allocation ourselves const storedType = <Format.Types.StructType>( userDefinedTypes[dataType.id] ); if (!storedType) { throw new Common.UnknownUserDefinedTypeError( dataType.id, Format.Types.typeString(dataType) ); } allocations = allocateStruct( storedType, userDefinedTypes, existingAllocations ); allocation = allocations[storedType.id]; } //having found our allocation, if it's not null, we can just look up its size and dynamicity if (allocation !== null) { return { size: allocation.length, dynamic: allocation.dynamic, allocations }; } //if it is null, this type doesn't go in the abi else { return { allocations }; } } case "tuple": { //Warning! Yucky wasteful recomputation here! let size = 0; let dynamic = false; //note that we don't just invoke allocateStruct here! //why not? because it has no ID to store the result in! //and we can't use a fake like -1 because there might be a recursive call to it, //and then the results would overwrite each other //I mean, we could do some hashing thing or something, but I think it's easier to just //copy the logic in this one case (sorry) for (let member of dataType.memberTypes) { let { size: memberSize, dynamic: memberDynamic } = abiSizeAndAllocate( member.type, userDefinedTypes, existingAllocations ); size += memberSize; dynamic = dynamic || memberDynamic; } return { size, dynamic, allocations: existingAllocations }; } } } //assumes you've already done allocation! don't use if you haven't! /** * @protected */ export function abiSizeInfo( dataType: Format.Types.Type, allocations?: AbiAllocations ): AbiSizeInfo { let { size, dynamic } = abiSizeAndAllocate(dataType, null, allocations); //the above line should work fine... as long as allocation is already done! //the middle argument, userDefinedTypes, is only needed during allocation //again, this function is only for use if allocation is done, so it's safe to pass null here return { size, dynamic }; } //allocates an external call //NOTE: returns just a single allocation; assumes primary allocation is already complete! //NOTE: returns undefined if attempting to allocate a constructor but we don't have the //bytecode for the constructor function allocateCalldataAndReturndata( abiEntry: Abi.FunctionEntry | Abi.ConstructorEntry, contractNode: Ast.AstNode | undefined, referenceDeclarations: Ast.AstNodes, userDefinedTypes: Format.Types.TypesById, abiAllocations: AbiAllocations, compilationId: string, compiler: Compiler.CompilerVersion | undefined, constructorContext?: Contexts.Context, deployedContext?: Contexts.Context ): CalldataAndReturndataAllocation | undefined { //first: determine the corresponding function node //(simultaneously: determine the offset) let node: Ast.AstNode | undefined = undefined; let inputParametersFull: Ast.AstNode[]; let outputParametersFull: Ast.AstNode[]; let inputParametersAbi: Abi.Parameter[]; let outputParametersAbi: Abi.Parameter[]; let offset: number; //refers to INPUT offset; output offset is always 0 debug("allocating calldata and returndata"); switch (abiEntry.type) { case "constructor": if (!constructorContext) { return undefined; } let rawLength = constructorContext.binary.length; offset = (rawLength - 2) / 2; //number of bytes in 0x-prefixed bytestring //for a constructor, we only want to search the particular contract if (contractNode) { node = contractNode.nodes.find(functionNode => AbiDataUtils.definitionMatchesAbi( //note this needn't actually be a function node, but then it will //return false (well, unless it's a getter node!) abiEntry, functionNode, referenceDeclarations ) ); } //if we can't find it, we'll handle this below break; case "function": offset = Evm.Utils.SELECTOR_SIZE; //search through base contracts, from most derived (left) to most base (right) if (contractNode) { const linearizedBaseContracts = contractNode.linearizedBaseContracts; debug("linearized: %O", linearizedBaseContracts); node = findNodeAndContract( linearizedBaseContracts, referenceDeclarations, functionNode => AbiDataUtils.definitionMatchesAbi( abiEntry, functionNode, referenceDeclarations ), contractNode ).node; //may be undefined! that's OK! debug("found node: %o", Boolean(node)); } break; } //now: get the parameters (both full-mode & ABI) if (node) { switch (node.nodeType) { case "FunctionDefinition": //normal case inputParametersFull = node.parameters.parameters; outputParametersFull = node.returnParameters.parameters; //this exists even for constructors! break; case "VariableDeclaration": //getter case ({ inputs: inputParametersFull, outputs: outputParametersFull } = Ast.Utils.getterParameters(node, referenceDeclarations)); break; } } else { inputParametersFull = undefined; outputParametersFull = undefined; } inputParametersAbi = abiEntry.inputs; switch (abiEntry.type) { case "function": outputParametersAbi = abiEntry.outputs; break; case "constructor": //we just leave this empty for constructors outputParametersAbi = []; break; } //now: do the allocation! let { allocation: abiAllocationInput, mode: inputMode } = allocateDataArguments( inputParametersFull, inputParametersAbi, userDefinedTypes, abiAllocations, compilationId, compiler, offset ); let { allocation: abiAllocationOutput, mode: outputMode } = allocateDataArguments( outputParametersFull, outputParametersAbi, userDefinedTypes, abiAllocations, compilationId, compiler //note no offset ); debug("modes: %s in, %s out", inputMode, outputMode); //finally: transform the allocation appropriately let inputArgumentsAllocation = abiAllocationInput.members.map(member => ({ ...member, pointer: { location: "calldata" as const, start: member.pointer.start, length: member.pointer.length } })); let outputArgumentsAllocation = abiAllocationOutput.members.map(member => ({ ...member, pointer: { location: "returndata" as const, start: member.pointer.start, length: member.pointer.length } })); let inputsAllocation: CalldataAllocation = { abi: abiEntry, offset, arguments: inputArgumentsAllocation, allocationMode: inputMode }; let outputsAllocation: ReturndataAllocation; switch (abiEntry.type) { case "function": outputsAllocation = { selector: new Uint8Array(), //empty by default arguments: outputArgumentsAllocation, allocationMode: outputMode, kind: "return" as const }; break; case "constructor": outputsAllocation = constructorOutputAllocation( deployedContext, contractNode, referenceDeclarations, outputMode ); break; } return <CalldataAndReturndataAllocation>{ input: inputsAllocation, output: outputsAllocation }; //TS chokes on this for some reason } interface AbiAllocationAndMode { allocation: AbiAllocation; mode: DecodingMode; } //note: allocateEvent doesn't use this because it needs additional //handling for indexed parameters (maybe these can be unified in //the future though?) function allocateDataArguments( fullModeParameters: Ast.AstNode[] | undefined, abiParameters: Abi.Parameter[], userDefinedTypes: Format.Types.TypesById, abiAllocations: AbiAllocations, compilationId: string, compiler: Compiler.CompilerVersion | undefined, offset: number = 0 ): AbiAllocationAndMode { let allocationMode: DecodingMode = fullModeParameters ? "full" : "abi"; //can degrade let parameterTypes: Format.Types.NameTypePair[]; let abiAllocation: AbiAllocation; if (allocationMode === "full") { let id = "-1"; //fake ID that doesn't matter parameterTypes = fullModeParameters.map(parameter => ({ name: parameter.name, type: Ast.Import.definitionToType(parameter, compilationId, compiler) //if node is defined, compiler had also better be! })); debug("parameterTypes: %O", parameterTypes); //now: perform the allocation! try { abiAllocation = allocateMembers( id, parameterTypes, userDefinedTypes, abiAllocations, offset )[id]; } catch { //if something goes wrong, switch to ABI mdoe debug("falling back to ABI due to exception!"); allocationMode = "abi"; } } if (allocationMode === "abi") { //THIS IS DELIBERATELY NOT AN ELSE //this is the ABI case. we end up here EITHER //if node doesn't exist, OR if something went wrong //during allocation let id = "-1"; //fake irrelevant ID parameterTypes = abiParameters.map(parameter => ({ name: parameter.name, type: Import.abiParameterToType(parameter) })); abiAllocation = allocateMembers( id, parameterTypes, userDefinedTypes, abiAllocations, offset )[id]; } return { allocation: abiAllocation, mode: allocationMode }; } interface EventParameterInfo { name: string; type: Format.Types.Type; indexed: boolean; } //allocates an event //NOTE: returns just a single allocation; assumes primary allocation is already complete! function allocateEvent( abiEntry: Abi.EventEntry, contractNode: Ast.AstNode | undefined, referenceDeclarations: Ast.AstNodes, userDefinedTypes: Format.Types.TypesById, abiAllocations: AbiAllocations, compilationId: string, compiler: Compiler.CompilerVersion | undefined ): EventAllocation | undefined { let parameterTypes: EventParameterInfo[]; let nodeId: string; let id: string; //first: determine the corresponding event node //search through base contracts, from most derived (right) to most base (left) let node: Ast.AstNode | undefined = undefined; let definedIn: Format.Types.ContractType | undefined = undefined; let allocationMode: DecodingMode = "full"; //degrade to abi as needed debug("allocating ABI: %O", abiEntry); if (contractNode) { //first: check same contract for the event node = contractNode.nodes.find(eventNode => AbiDataUtils.definitionMatchesAbi( //note this needn't actually be an event node, but then it will //return false abiEntry, eventNode, referenceDeclarations ) ); //if we found the node, great! If not... if (!node) { debug("didn't find node in base contract..."); //let's search for the node among the base contracts. //but if we find it... //[note: the following code is overcomplicated; it was used //when we were trying to get the actual node, it's overcomplicated //now that we're just determining its presence. oh well] let linearizedBaseContractsMinusSelf = contractNode.linearizedBaseContracts.slice(); linearizedBaseContractsMinusSelf.shift(); //remove self debug("checking contracts: %o", linearizedBaseContractsMinusSelf); node = findNodeAndContract( linearizedBaseContractsMinusSelf, referenceDeclarations, eventNode => AbiDataUtils.definitionMatchesAbi( //note this needn't actually be a event node, but then it will return false abiEntry, eventNode, referenceDeclarations ) //don't pass deriveContractNode here, we're not checking the contract itself ).node; //may be undefined! that's OK! if (node) { //...if we find the node in an ancestor, we //deliberately *don't* allocate! instead such cases //will be handled during a later combination step debug("bailing out for later handling!"); debug("ABI: %O", abiEntry); return undefined; } } } //otherwise, leave node undefined if (node) { debug("found node"); //if we found the node, let's also turn it into a type definedIn = <Format.Types.ContractType>( Ast.Import.definitionToStoredType(contractNode, compilationId, compiler) ); //can skip reference declarations argument here //...and set the ID id = makeTypeId(node.id, compilationId); } else { //if no node, have to fall back into ABI mode debug("falling back to ABI because no node"); allocationMode = "abi"; } //now: construct the list of parameter types, attaching indexedness info //and overall position (for later reconstruction) let indexed: EventParameterInfo[]; let nonIndexed: EventParameterInfo[]; let abiAllocation: AbiAllocation; //the untransformed allocation for the non-indexed parameters if (allocationMode === "full") { nodeId = node.id.toString(); let parameters = node.parameters.parameters; parameterTypes = parameters.map(definition => ({ //note: if node is defined, compiler had better be defined, too! type: Ast.Import.definitionToType(definition, compilationId, compiler), name: definition.name, indexed: definition.indexed })); //now: split the list of parameters into indexed and non-indexed [indexed, nonIndexed] = partition( parameterTypes, (parameter: EventParameterInfo) => parameter.indexed ); try { //now: perform the allocation for the non-indexed parameters! abiAllocation = allocateMembers( nodeId, nonIndexed, userDefinedTypes, abiAllocations )[nodeId]; //note the implicit conversion from EventParameterInfo to NameTypePair } catch { allocationMode = "abi"; } } if (allocationMode === "abi") { //THIS IS DELIBERATELY NOT AN ELSE nodeId = "-1"; //fake irrelevant ID parameterTypes = abiEntry.inputs.map(abiParameter => ({ type: Import.abiParameterToType(abiParameter), name: abiParameter.name, indexed: abiParameter.indexed })); //now: split the list of parameters into indexed and non-indexed [indexed, nonIndexed] = partition( parameterTypes, (parameter: EventParameterInfo) => parameter.indexed ); //now: perform the allocation for the non-indexed parameters! abiAllocation = allocateMembers( nodeId, nonIndexed, userDefinedTypes, abiAllocations )[nodeId]; //note the implicit conversion from EventParameterInfo to NameTypePair } //now: transform the result appropriately const nonIndexedArgumentsAllocation = abiAllocation.members.map(member => ({ ...member, pointer: { location: "eventdata" as const, start: member.pointer.start, length: member.pointer.length } })); //now: allocate the indexed parameters const startingTopic = abiEntry.anonymous ? 0 : 1; //if not anonymous, selector takes up topic 0 const indexedArgumentsAllocation = indexed.map( ({ type, name }, position) => ({ type, name, pointer: { location: "eventtopic" as const, topic: startingTopic + position } }) ); //finally: weave these back together let argumentsAllocation: EventArgumentAllocation[] = []; for (let parameter of parameterTypes) { let arrayToGrabFrom = parameter.indexed ? indexedArgumentsAllocation : nonIndexedArgumentsAllocation; argumentsAllocation.push(arrayToGrabFrom.shift()); //note that push and shift both modify! } //...and return return { abi: abiEntry, contextHash: undefined, //leave this for later (HACK) definedIn, id, arguments: argumentsAllocation, allocationMode, anonymous: abiEntry.anonymous }; } function allocateError( abiEntry: Abi.ErrorEntry, errorNode: Ast.AstNode | undefined, referenceDeclarations: Ast.AstNodes, userDefinedTypes: Format.Types.TypesById, abiAllocations: AbiAllocations, compilationId: string, compiler: Compiler.CompilerVersion | undefined ): RevertReturndataAllocation { //first: if we got passed just a node & no abi entry, let id: string | undefined = undefined; let definedIn: Format.Types.ContractType | undefined | null = undefined; let parametersFull: Ast.AstNode[] | undefined = undefined; const parametersAbi: Abi.Parameter[] = abiEntry.inputs; if (errorNode) { //first, set parametersFull parametersFull = errorNode.parameters.parameters; //now, set id id = makeTypeId(errorNode.id, compilationId); //now, set definedIn let contractNode: Ast.AstNode | null = null; for (const node of Object.values(referenceDeclarations)) { if (node.nodeType === "ContractDefinition") { if (node.nodes.some((subNode: Ast.AstNode) => subNode.id === errorNode.id)) { contractNode = node; break; } } //if we didn't find it, then contractNode is null //(and thus so will be definedIn) } if (contractNode === null) { definedIn = null; } else { definedIn = <Format.Types.ContractType>( Ast.Import.definitionToStoredType(contractNode, compilationId, compiler) ); } } //otherwise, leave parametersFull, id, and definedIn undefined const { allocation: abiAllocation, mode: allocationMode } = allocateDataArguments( parametersFull, parametersAbi, userDefinedTypes, abiAllocations, compilationId, compiler, Evm.Utils.SELECTOR_SIZE //errors use a 4-byte selector ); //finally: transform the allocation appropriately const argumentsAllocation = abiAllocation.members.map(member => ({ ...member, pointer: { location: "returndata" as const, start: member.pointer.start, length: member.pointer.length } })); const selector = Conversion.toBytes(AbiDataUtils.abiSelector(abiEntry)); return { kind: "revert", selector, abi: abiEntry, id, definedIn, arguments: argumentsAllocation, allocationMode }; } function getCalldataAllocationsForContract( abi: Abi.Abi, contractNode: Ast.AstNode, constructorContext: Contexts.Context, deployedContext: Contexts.Context, referenceDeclarations: Ast.AstNodes, userDefinedTypes: Format.Types.TypesById, abiAllocations: AbiAllocations, compilationId: string, compiler: Compiler.CompilerVersion ): CalldataAllocationTemporary { let allocations: CalldataAllocationTemporary = { constructorAllocation: undefined, //(if it doesn't then it will remain as default) functionAllocations: {} }; if (!abi) { //if no ABI, can't do much! allocations.constructorAllocation = defaultConstructorAllocation( constructorContext, contractNode, referenceDeclarations, deployedContext ); return allocations; } for (let abiEntry of abi) { if ( AbiDataUtils.abiEntryIsObviouslyIllTyped(abiEntry) || AbiDataUtils.abiEntryHasStorageParameters(abiEntry) ) { //the first of these conditions is a hack workaround for a Solidity bug. //the second of these is because... seriously? we're not handling these //(at least not for now!) (these only exist prior to Solidity 0.5.6, //thankfully) continue; } switch (abiEntry.type) { case "constructor": allocations.constructorAllocation = <ConstructorCalldataAndReturndataAllocation>allocateCalldataAndReturndata( abiEntry, contractNode, referenceDeclarations, userDefinedTypes, abiAllocations, compilationId, compiler, constructorContext, deployedContext ); debug("constructor alloc: %O", allocations.constructorAllocation); break; case "function": allocations.functionAllocations[ AbiDataUtils.abiSelector(abiEntry) ] = <FunctionCalldataAndReturndataAllocation>allocateCalldataAndReturndata( abiEntry, contractNode, referenceDeclarations, userDefinedTypes, abiAllocations, compilationId, compiler, constructorContext, deployedContext ); break; default: //skip over fallback, error, and event break; } } if (!allocations.constructorAllocation) { //set a default constructor allocation if we haven't allocated one yet allocations.constructorAllocation = defaultConstructorAllocation( constructorContext, contractNode, referenceDeclarations, deployedContext ); debug("default constructor alloc: %O", allocations.constructorAllocation); } return allocations; } function defaultConstructorAllocation( constructorContext: Contexts.Context, contractNode: Ast.AstNode | undefined, referenceDeclarations: Ast.AstNodes, deployedContext?: Contexts.Context ): ConstructorCalldataAndReturndataAllocation | undefined { if (!constructorContext) { return undefined; } const rawLength = constructorContext.binary.length; const offset = (rawLength - 2) / 2; //number of bytes in 0x-prefixed bytestring const input = { offset, abi: AbiDataUtils.DEFAULT_CONSTRUCTOR_ABI, arguments: [] as CalldataArgumentAllocation[], allocationMode: "full" as const }; const output = constructorOutputAllocation( deployedContext, contractNode, referenceDeclarations, "full" ); //assume full, degrade as necessary return { input, output }; } //note: context should be deployed context! function constructorOutputAllocation( context: Contexts.Context | undefined, contractNode: Ast.AstNode | undefined, referenceDeclarations: Ast.AstNodes, allocationMode: DecodingMode ): ConstructorReturndataAllocation { if (!context) { //just return a default abi mode result return { selector: new Uint8Array(), //always empty for constructor output allocationMode: "abi", kind: "bytecode" as const, delegatecallGuard: false }; } const { immutableReferences, compilationId, compiler, contractKind, binary } = context; let immutables: ReturnImmutableAllocation[] | undefined; if (allocationMode === "full" && immutableReferences) { if (contractNode) { debug("allocating immutables"); immutables = []; for (const [id, references] of Object.entries(immutableReferences)) { if (references.length === 0) { continue; //don't allocate immutables that don't exist } const astId: number = parseInt(id); //get the corresponding variable node; potentially fail const { node: definition, contract: definedIn } = findNodeAndContract( contractNode.linearizedBaseContracts, referenceDeclarations, node => node.id === astId, contractNode ); if (!definition || definition.nodeType !== "VariableDeclaration") { debug("didn't find definition for %d!", astId); allocationMode = "abi"; immutables = undefined; break; } const definedInClass = <Format.Types.ContractType>( Ast.Import.definitionToStoredType(definedIn, compilationId, compiler) ); //can skip reference declarations argument here const dataType = Ast.Import.definitionToType( definition, compilationId, compiler ); immutables.push({ name: definition.name, definedIn: definedInClass, type: dataType, pointer: { location: "returndata" as const, start: references[0].start, length: references[0].length } }); } } else if (Object.entries(immutableReferences).length > 0) { //if there are immutables, but no contract mode, go to abi mode debug("immutables but no node!"); allocationMode = "abi"; } } else { debug("no immutables"); } //now, is there a delegatecall guard? let delegatecallGuard: boolean = false; if (contractKind === "library") { //note: I am relying on this being present! //(also this part is a bit HACKy) const pushAddressInstruction = (0x60 + Evm.Utils.ADDRESS_SIZE - 1).toString( 16 ); //"73" const delegateCallGuardString = "0x" + pushAddressInstruction + "..".repeat(Evm.Utils.ADDRESS_SIZE); if (binary.startsWith(delegateCallGuardString)) { delegatecallGuard = true; } } return { selector: new Uint8Array(), //always empty for constructor output allocationMode, kind: "bytecode" as const, immutables, delegatecallGuard }; } export function getCalldataAllocations( contracts: ContractAllocationInfo[], referenceDeclarations: { [compilationId: string]: Ast.AstNodes }, userDefinedTypes: Format.Types.TypesById, abiAllocations: AbiAllocations ): CalldataAllocations { let allocations: CalldataAllocations = { constructorAllocations: {}, functionAllocations: {} }; for (let contract of contracts) { const contractAllocations = getCalldataAllocationsForContract( contract.abi, contract.contractNode, contract.constructorContext, contract.deployedContext, referenceDeclarations[contract.compilationId], userDefinedTypes, abiAllocations, contract.compilationId, contract.compiler ); if (contract.constructorContext) { allocations.constructorAllocations[contract.constructorContext.context] = contractAllocations.constructorAllocation; } if (contract.deployedContext) { allocations.functionAllocations[contract.deployedContext.context] = contractAllocations.functionAllocations; //set this up under both constructor *and* deployed! this is to handle //constructor returndata decoding allocations.constructorAllocations[contract.deployedContext.context] = contractAllocations.constructorAllocation; } } return allocations; } function getReturndataAllocationsForContract( abi: Abi.Abi, contractNode: Ast.AstNode | undefined, referenceDeclarations: Ast.AstNodes, userDefinedTypes: Format.Types.TypesById, abiAllocations: AbiAllocations, compilationId: string, compiler: Compiler.CompilerVersion | undefined ): RevertReturndataAllocation[] { let useAst = Boolean(contractNode && contractNode.usedErrors); if (useAst) { const errorNodes = contractNode.usedErrors.map( errorNodeId => referenceDeclarations[errorNodeId] ); let abis: Abi.ErrorEntry[]; try { abis = errorNodes.map( errorNode => <Abi.ErrorEntry>Ast.Utils.definitionToAbi( errorNode, referenceDeclarations ) ); } catch { useAst = false; } if (useAst) { //i.e. if the above operation succeeded return contractNode.usedErrors.map( errorNodeId => referenceDeclarations[errorNodeId] ).map((errorNode, index) => allocateError( abis[index], errorNode, referenceDeclarations, userDefinedTypes, abiAllocations, compilationId, compiler )); } } if (!useAst && abi) { //deliberately *not* an else! return abi .filter((abiEntry: Abi.Entry) => abiEntry.type === "error") .filter( (abiEntry: Abi.ErrorEntry) => !AbiDataUtils.abiEntryIsObviouslyIllTyped(abiEntry) ) //hack workaround .map((abiEntry: Abi.ErrorEntry) => allocateError( abiEntry, undefined, referenceDeclarations, userDefinedTypes, abiAllocations, compilationId, compiler )); } //otherwise just return nothing return []; } export function getReturndataAllocations( contracts: ContractAllocationInfo[], referenceDeclarations: { [compilationId: string]: Ast.AstNodes }, userDefinedTypes: Format.Types.TypesById, abiAllocations: AbiAllocations ): ReturndataAllocations { let allContexts: string[] = [].concat( ...contracts.map(({ deployedContext, constructorContext }) => [deployedContext, constructorContext] )).filter(x => x) //filter out nonexistent contexts .map(context => context.context); allContexts.push(""); //HACK: add fictional empty-string context to represent no-context //holds allocations for a given context let selfAllocations: { [contextHash: string]: RevertReturndataAllocation[] } = {}; //holds allocations for *other* contexts let additionalAllocations: { [contextHash: string]: RevertReturndataAllocation[] } = {}; //now: process the allocations for each contract. we'll add each contract's //allocations to *its* entries in allocations, and to every *other* entry //in additionalAllocations. for (const contract of contracts) { const contractAllocations = getReturndataAllocationsForContract( contract.abi, contract.contractNode, referenceDeclarations[contract.compilationId], userDefinedTypes, abiAllocations, contract.compilationId, contract.compiler ); const contexts: string[] = [ //contexts for this contract contract.deployedContext, contract.constructorContext ].filter(x => x) //filter out nonexistent contexts .map(context => context.context); const otherContexts: string[] = allContexts.filter( //contexts for all other contracts contextHash => !contexts.includes(contextHash) ); //add them to selfAllocations for (const contextHash of contexts) { selfAllocations[contextHash] = contractAllocations; } //add them to additionalAllocations for (const contextHash of otherContexts) { if (additionalAllocations[contextHash] === undefined) { additionalAllocations[contextHash] = []; } additionalAllocations[contextHash] = additionalAllocations[contextHash].concat(contractAllocations); } } let allocations: ReturndataAllocations = Object.assign( {}, ...allContexts.map(contextHash => ({ [contextHash]: {} })) ); //now: perform coalescense! for (const contract of contracts) { //we're setting up contexts again, sorry >_> const contexts: string[] = [ //contexts for this contract contract.deployedContext, contract.constructorContext ].filter(x => x) //filter out nonexistent contexts .map(context => context.context); for (const contextHash of contexts) { allocations[contextHash] = coalesceReturndataAllocations( selfAllocations[contextHash] || [], additionalAllocations[contextHash] || [] ); debug("allocations: %O", allocations[contextHash]); } } //...also coalesce the fake "" context allocations[""] = coalesceReturndataAllocations( [], additionalAllocations[""] || [] ); /* for (const [contextHash, contextAllocations] of Object.entries(allAllocations)) { for (const [signature, signatureAllocations] of Object.entries(contextAllocations)) { const selector = Web3Utils.soliditySha3({ type: "string", value: signature }) .slice(0, 2 + 2 * Evm.Utils.SELECTOR_SIZE); //arithmetic to account for hex string if (!allocations[contextHash][selector]) { allocations[contextHash][selector] = []; } allocations[contextHash][selector] = allocations[contextHash][selector].concat(signatureAllocations); } } */ debug("error allocations: %O", allocations); return allocations; } function coalesceReturndataAllocations( selfAllocations: RevertReturndataAllocation[], additionalAllocations: RevertReturndataAllocation[] ): { [selector: string]: RevertReturndataAllocation[] } { let bySelector: { [selector: string]: RevertReturndataAllocation[] } = {}; //start with the additional allocations; we want to process //the self allocations last, due to special handling of no-ID allocations there for (const allocation of additionalAllocations) { const signature = AbiDataUtils.abiSignature(allocation.abi); const selector = Web3Utils.soliditySha3({ type: "string", value: signature }) .slice(0, 2 + 2 * Evm.Utils.SELECTOR_SIZE); //arithmetic to account for hex string if (bySelector[selector]) { //note: at this point, for any given signature, there should only be a //no-ID allocation for that signature if it's the only one if (allocation.id !== undefined) { //delete anything with that signature but w/o an ID, or with this same ID bySelector[selector] = bySelector[selector].filter( ({ abi, id }) => !(AbiDataUtils.abiSignature(abi) === signature && (id === undefined || id === allocation.id)) ); //add this allocation bySelector[selector].push(allocation); } else if ( !bySelector[selector].some( ({ abi }) => AbiDataUtils.abiSignature(abi) === signature ) ) { //only add ID-less ones if there isn't anything of that signature already bySelector[selector].push(allocation); } } else { //if there's nothing there thus far, add it bySelector[selector] = [allocation]; } } //store for later: # of allocs per selector const selectorCounts: { [selector: string]: number } = Object.assign({}, ...Object.entries(bySelector).map( ([selector, allocations]) => ({ [selector]: allocations.length }) ) ); //now we're going to perform a modified version of this procedure for the self allocations: //1. we're going to add to the front, not the back //2. we can add an ID-less one even if there are already ones with IDs there //(sorry for the copypaste) for (const allocation of selfAllocations) { const signature = AbiDataUtils.abiSignature(allocation.abi); const selector = Web3Utils.soliditySha3({ type: "string", value: signature }) .slice(0, 2 + 2 * Evm.Utils.SELECTOR_SIZE); //arithmetic to account for hex string if (bySelector[selector]) { //delete anything with that signature but w/o an ID, or with this same ID //(if this alloc has no ID, this will only delete ID-less ones :) ) bySelector[selector] = bySelector[selector].filter( ({ abi, id }) => !(AbiDataUtils.abiSignature(abi) === signature && (id === undefined || id === allocation.id)) ); //add this allocation to front, not back! bySelector[selector].unshift(allocation); } else { //if there's nothing there thus far, add it bySelector[selector] = [allocation]; } } return bySelector; } function getEventAllocationsForContract( abi: Abi.Abi, contractNode: Ast.AstNode | undefined, referenceDeclarations: Ast.AstNodes, userDefinedTypes: Format.Types.TypesById, abiAllocations: AbiAllocations, compilationId: string, compiler: Compiler.CompilerVersion | undefined ): EventAllocationTemporary[] { return abi .filter((abiEntry: Abi.Entry) => abiEntry.type === "event") .filter( (abiEntry: Abi.EventEntry) => !AbiDataUtils.abiEntryIsObviouslyIllTyped(abiEntry) ) //hack workaround .map((abiEntry: Abi.EventEntry) => ({ selector: AbiDataUtils.abiSelector(abiEntry), anonymous: abiEntry.anonymous, topics: AbiDataUtils.topicsCount(abiEntry), allocation: allocateEvent( abiEntry, contractNode, referenceDeclarations, userDefinedTypes, abiAllocations, compilationId, compiler ) })); //note we do *not* filter out undefined allocations; we need these as placeholders } //note: constructor context is ignored by this function; no need to pass it in //WARNING: this function is full of hacks... sorry export function getEventAllocations( contracts: ContractAllocationInfo[], referenceDeclarations: { [compilationId: string]: Ast.AstNodes }, userDefinedTypes: Format.Types.TypesById, abiAllocations: AbiAllocations ): EventAllocations { //first: do allocations for individual contracts let individualAllocations: { [contractKey: string]: { [selector: string]: { context: Contexts.Context; contractNode: Ast.AstNode; allocationTemporary: EventAllocationTemporary; compilationId: string; }; }; } = {}; let groupedAllocations: { [contractKey: string]: { [selector: string]: { context: Contexts.Context; contractNode: Ast.AstNode; allocationsTemporary: EventAllocationTemporary[]; }; }; } = {}; let allocations: EventAllocations = {}; for (let { abi, deployedContext, contractNode, compilationId, compiler } of contracts) { if (!deployedContext && !contractNode) { //we'll need *one* of these two at least continue; } let contractAllocations = getEventAllocationsForContract( abi, contractNode, referenceDeclarations[compilationId], userDefinedTypes, abiAllocations, compilationId, compiler ); let key = makeContractKey( deployedContext, contractNode ? contractNode.id : undefined, compilationId ); if (individualAllocations[key] === undefined) { individualAllocations[key] = {}; } for (let allocationTemporary of contractAllocations) { //we'll use selector *even for anonymous* here, because it's just //for determining what overrides what at this point individualAllocations[key][allocationTemporary.selector] = { context: deployedContext, contractNode, allocationTemporary, compilationId }; } } //now: put things together for inheritance //note how we always put things in order from most derived to most base for (let contextOrId in individualAllocations) { groupedAllocations[contextOrId] = {}; for (let selector in individualAllocations[contextOrId]) { let { context, contractNode, allocationTemporary, compilationId } = individualAllocations[contextOrId][selector]; debug("allocationTemporary: %O", allocationTemporary); let allocationsTemporary = allocationTemporary.allocation ? [allocationTemporary] : []; //filter out undefined allocations //first, copy from individual allocations groupedAllocations[contextOrId][selector] = { context, contractNode, allocationsTemporary }; //if no contract node, that's all. if there is... if (contractNode) { //...we have to do inheritance processing debug("contract Id: %d", contractNode.id); debug("base contracts: %o", contractNode.linearizedBaseContracts); let linearizedBaseContractsMinusSelf = contractNode.linearizedBaseContracts.slice(); linearizedBaseContractsMinusSelf.shift(); //remove contract itself; only want ancestors for (let baseId of linearizedBaseContractsMinusSelf) { debug("checking baseId: %d", baseId); let baseNode = referenceDeclarations[compilationId][baseId]; if (!baseNode || baseNode.nodeType !== "ContractDefinition") { debug("failed to find node for baseId: %d", baseId); break; //not a continue! //if we can't find the base node, it's better to stop the loop, //rather than continue to potentially erroneous things } //note: we're not actually going to *use* the baseNode here. //we're just checking for whether we can *find* it //why? because if we couldn't find it, that means that events defined in //base contracts *weren't* skipped earlier, and so we shouldn't now add them in let baseContractInfo = contracts.find( contractAllocationInfo => contractAllocationInfo.compilationId === compilationId && contractAllocationInfo.contractNode && contractAllocationInfo.contractNode.id === baseId ); if (!baseContractInfo) { //similar to above... this failure case can happen when there are //two contracts with the same name and you attempt to use the //artifacts; say you have contracts A, B, and B', where A inherits //from B, and B and B' have the same name, and B' is the one that //gets the artifact; B will end up in reference declarations and so //get found above, but it won't appear in contracts, causing the //problem here. Unfortunately I don't know any great way to handle this, //so, uh, we treat it as a failure same as above. debug("failed to find contract info for baseId: %d", baseId); break; } let baseContext = baseContractInfo.deployedContext; let baseKey = makeContractKey(baseContext, baseId, compilationId); if (individualAllocations[baseKey][selector] !== undefined) { let baseAllocation = individualAllocations[baseKey][selector].allocationTemporary; debug("(probably) pushing inherited alloc from baseId: %d", baseId); if (baseAllocation.allocation) { //don't push undefined! groupedAllocations[contextOrId][ selector ].allocationsTemporary.push(baseAllocation); } } } } } } //finally: transform into final form & return, //filtering out things w/o a context for (let contractKey in groupedAllocations) { if (!hasContext(contractKey)) { continue; //(this filters out ones that had no context and therefore were //given by ID; we needed these at the previous stage but from //here on they're irrelevant) } let contextHash = contextHashForKey(contractKey); for (let selector in groupedAllocations[contextHash]) { let { allocationsTemporary, context } = groupedAllocations[contextHash][ selector ]; for (let { anonymous, topics, allocation } of allocationsTemporary) { let contractKind = context.contractKind; //HACK: this is the wrong context, but libraries can't inherit, so it's OK if (contractKind !== "library") { contractKind = "contract"; //round off interfaces to being contracts for our purposes :P } allocation = { ...allocation, contextHash }; //the allocation's context hash at this point depends on where it was defined, but //that's not what we want going in the final allocation table! if (allocations[topics] === undefined) { allocations[topics] = { bySelector: {}, anonymous: { contract: {}, library: {} } }; } if (!anonymous) { if (allocations[topics].bySelector[selector] === undefined) { allocations[topics].bySelector[selector] = { contract: {}, library: {} }; } if ( allocations[topics].bySelector[selector][contractKind][ contextHash ] === undefined ) { allocations[topics].bySelector[selector][contractKind][ contextHash ] = []; } allocations[topics].bySelector[selector][contractKind][ contextHash ].push(allocation); } else { if ( allocations[topics].anonymous[contractKind][contextHash] === undefined ) { allocations[topics].anonymous[contractKind][contextHash] = []; } allocations[topics].anonymous[contractKind][contextHash].push( allocation ); } } } } return allocations; } interface NodeAndContract { node: Ast.AstNode | undefined; contract: Ast.AstNode | undefined; } //if derivedContractNode is passed, we check that before referenceDeclarations function findNodeAndContract( linearizedBaseContracts: number[], referenceDeclarations: Ast.AstNodes, condition: (node: Ast.AstNode) => boolean, derivedContractNode?: Ast.AstNode ): NodeAndContract { const searchResult: | NodeAndContract | null | undefined = linearizedBaseContracts.reduce( ( foundNodeAndContract: NodeAndContract | undefined | null, baseContractId: number ) => { if (foundNodeAndContract !== undefined) { return foundNodeAndContract; //once we've found something, we don't need to keep looking } debug("searching contract %d", baseContractId); let baseContractNode = derivedContractNode && baseContractId === derivedContractNode.id ? derivedContractNode //skip the lookup if we already have the right node! this is to reduce errors from collision : referenceDeclarations[baseContractId]; if ( baseContractNode === undefined || baseContractNode.nodeType !== "ContractDefinition" ) { debug("bad contract node!"); return null; //return null rather than undefined so that this will propagate through //(i.e. by returning null here we give up the search) //(we don't want to continue due to possibility of grabbing the wrong override) } const node = baseContractNode.nodes.find(condition); //may be undefined! that's OK! if (node) { debug("found node: %o", node); return { node, contract: baseContractNode }; } else { return undefined; } }, undefined //start with no node found ); return searchResult || { node: undefined, contract: undefined }; } function makeContractKey( context: Contexts.Context | undefined, id: number, compilationId: string ): string { return context ? context.context : id + ":" + compilationId; //HACK! } function hasContext(key: string): boolean { return key.startsWith("0x"); //HACK! } function contextHashForKey(key: string): string { return hasContext(key) ? key //HACK! : undefined; }
the_stack
import { destroy, detach, onSnapshot, onPatch, onAction, applyPatch, applyAction, applySnapshot, getSnapshot, unprotect, types, setLivelinessChecking, getParent, SnapshotOut, IJsonPatch, ISerializedActionCall, isAlive, cast, resolveIdentifier } from "../../src" import { autorun, reaction, observable, configure } from "mobx" const createTestFactories = () => { const Factory = types .model({ to: "world" }) .actions((self) => { function setTo(to: string) { self.to = to } return { setTo } }) const ComputedFactory = types .model({ width: 100, height: 200 }) .views((self) => ({ get area() { return self.width * self.height } })) const ComputedFactory2 = types .model({ props: types.map(types.number) }) .views((self) => ({ get area() { return self.props.get("width")! * self.props.get("height")! } })) .actions((self) => { function setWidth(value: number) { self.props.set("width", value) } function setHeight(value: number) { self.props.set("height", value) } return { setWidth, setHeight } }) const BoxFactory = types.model({ width: 0, height: 0 }) const ColorFactory = types.model({ color: "#FFFFFF" }) return { Factory, ComputedFactory, ComputedFactory2, BoxFactory, ColorFactory } } const createFactoryWithChildren = () => { const File = types .model("File", { name: types.string }) .actions((self) => ({ rename(value: string) { self.name = value } })) const Folder = types .model("Folder", { name: types.string, files: types.array(File) }) .actions((self) => ({ rename(value: string) { self.name = value } })) return Folder } // === FACTORY TESTS === test("it should create a factory", () => { const { Factory } = createTestFactories() const instance = Factory.create() const snapshot = getSnapshot(instance) expect(snapshot).toEqual({ to: "world" }) expect(getSnapshot(Factory.create())).toEqual({ to: "world" }) // toJSON is there as shortcut for getSnapshot(), primarily for debugging convenience expect(Factory.create().toString()).toEqual("AnonymousModel@<root>") }) test("it should restore the state from the snapshot", () => { const { Factory } = createTestFactories() expect(getSnapshot(Factory.create({ to: "universe" }))).toEqual({ to: "universe" }) }) // === SNAPSHOT TESTS === test("it should emit snapshots", () => { const { Factory } = createTestFactories() const doc = Factory.create() unprotect(doc) let snapshots: SnapshotOut<typeof doc>[] = [] onSnapshot(doc, (snapshot) => snapshots.push(snapshot)) doc.to = "universe" expect(snapshots).toEqual([{ to: "universe" }]) }) test("it should emit snapshots for children", () => { const Factory = createFactoryWithChildren() const folder = Factory.create({ name: "Photos to sort", files: [ { name: "Photo1" }, { name: "Photo2" } ] }) let snapshotsP: SnapshotOut<typeof folder>[] = [] let snapshotsC: SnapshotOut<typeof folder.files[0]>[] = [] onSnapshot(folder, (snapshot) => snapshotsP.push(snapshot)) folder.rename("Vacation photos") expect(snapshotsP[0]).toEqual({ name: "Vacation photos", files: [{ name: "Photo1" }, { name: "Photo2" }] }) onSnapshot(folder.files[0], (snapshot) => snapshotsC.push(snapshot)) folder.files[0].rename("01-arrival") expect(snapshotsP[1]).toEqual({ name: "Vacation photos", files: [{ name: "01-arrival" }, { name: "Photo2" }] }) expect(snapshotsC[0]).toEqual({ name: "01-arrival" }) folder.files[1].rename("02-hotel") expect(snapshotsP[2]).toEqual({ name: "Vacation photos", files: [{ name: "01-arrival" }, { name: "02-hotel" }] }) expect(snapshotsP.length).toBe(3) expect(snapshotsC.length).toBe(1) }) test("it should apply snapshots", () => { const { Factory } = createTestFactories() const doc = Factory.create() applySnapshot(doc, { to: "universe" }) expect(getSnapshot(doc)).toEqual({ to: "universe" }) }) test("it should apply and accept null value for types.maybe(complexType)", () => { const Item = types.model("Item", { value: types.string }) const Model = types.model("Model", { item: types.maybe(Item) }) const myModel = Model.create() applySnapshot(myModel, { item: { value: "something" } }) applySnapshot(myModel, { item: undefined }) expect(getSnapshot(myModel)).toEqual({ item: undefined }) }) test("it should apply and accept null value for types.maybeNull(complexType)", () => { const Item = types.model("Item", { value: types.string }) const Model = types.model("Model", { item: types.maybeNull(Item) }) const myModel = Model.create() applySnapshot(myModel, { item: { value: "something" } }) applySnapshot(myModel, { item: null }) expect(getSnapshot(myModel)).toEqual({ item: null }) }) test("it should return a snapshot", () => { const { Factory } = createTestFactories() const doc = Factory.create() expect(getSnapshot(doc)).toEqual({ to: "world" }) }) // === PATCHES TESTS === test("it should emit patches", () => { const { Factory } = createTestFactories() const doc = Factory.create() unprotect(doc) let patches: IJsonPatch[] = [] onPatch(doc, (patch) => patches.push(patch)) doc.to = "universe" expect(patches).toEqual([{ op: "replace", path: "/to", value: "universe" }]) }) test("it should apply a patch", () => { const { Factory } = createTestFactories() const doc = Factory.create() applyPatch(doc, { op: "replace", path: "/to", value: "universe" }) expect(getSnapshot(doc)).toEqual({ to: "universe" }) }) test("it should apply patches", () => { const { Factory } = createTestFactories() const doc = Factory.create() applyPatch(doc, [ { op: "replace", path: "/to", value: "mars" }, { op: "replace", path: "/to", value: "universe" } ]) expect(getSnapshot(doc)).toEqual({ to: "universe" }) }) test("it should stop listening to patches patches", () => { const { Factory } = createTestFactories() const doc = Factory.create() unprotect(doc) let patches: IJsonPatch[] = [] let disposer = onPatch(doc, (patch) => patches.push(patch)) doc.to = "universe" disposer() doc.to = "mweststrate" expect(patches).toEqual([{ op: "replace", path: "/to", value: "universe" }]) }) // === ACTIONS TESTS === test("it should call actions correctly", () => { const { Factory } = createTestFactories() const doc = Factory.create() doc.setTo("universe") expect(getSnapshot(doc)).toEqual({ to: "universe" }) }) test("it should emit action calls", () => { const { Factory } = createTestFactories() const doc = Factory.create() let actions: ISerializedActionCall[] = [] onAction(doc, (action) => actions.push(action)) doc.setTo("universe") expect(actions).toEqual([{ name: "setTo", path: "", args: ["universe"] }]) }) test("it should apply action call", () => { const { Factory } = createTestFactories() const doc = Factory.create() applyAction(doc, { name: "setTo", path: "", args: ["universe"] }) expect(getSnapshot(doc)).toEqual({ to: "universe" }) }) test("it should apply actions calls", () => { const { Factory } = createTestFactories() const doc = Factory.create() applyAction(doc, [ { name: "setTo", path: "", args: ["mars"] }, { name: "setTo", path: "", args: ["universe"] } ]) expect(getSnapshot(doc)).toEqual({ to: "universe" }) }) // === COMPUTED VALUES === test("it should have computed properties", () => { const { ComputedFactory } = createTestFactories() const doc = ComputedFactory.create() unprotect(doc) doc.width = 3 doc.height = 2 expect(doc.area).toEqual(6) }) test("it should throw if a replaced object is read or written to", () => { const Todo = types .model("Todo", { title: "test", arr: types.array(types.string), map: types.map(types.string), sub: types.optional( types .model("Sub", { title: "test2" }) .actions((self) => ({ fn2() {} })), {} ) }) .actions((self) => ({ fn() { self.sub.fn2() } })) const Store = types.model("Store", { todo: Todo }) const data = { title: "alive", arr: ["arr0"], map: { mapkey0: "mapval0" }, sub: { title: "title" } } const s = Store.create({ todo: { ...data, title: "dead" } }) unprotect(s) const deadArr = s.todo.arr s.todo.arr = cast(data.arr) const deadMap = s.todo.map s.todo.map = cast(data.map) const deadSub = s.todo.sub s.todo.sub = cast(data.sub) const deadTodo = s.todo s.todo = Todo.create(data) expect(s.todo.title).toBe("alive") setLivelinessChecking("error") function getError(objType: string, path: string, subpath: string, action: string) { return `You are trying to read or write to an object that is no longer part of a state tree. (Object type: '${objType}', Path upon death: '${path}', Subpath: '${subpath}', Action: '${action}'). Either detach nodes first, or don't use objects after removing / replacing them in the tree.` } // dead todo expect(() => { deadTodo.fn() }).toThrow(getError("Todo", "/todo", "", "/todo.fn()")) expect(() => { // tslint:disable-next-line:no-unused-expression deadTodo.title }).toThrow(getError("Todo", "/todo", "title", "")) expect(() => { deadTodo.title = "5" }).toThrow(getError("Todo", "/todo", "title", "")) expect(() => { // tslint:disable-next-line:no-unused-expression deadTodo.arr[0] }).toThrow(getError("Todo", "/todo", "arr", "")) expect(() => { deadTodo.arr.push("arr1") }).toThrow(getError("Todo", "/todo", "arr", "")) expect(() => { deadTodo.map.get("mapkey0") }).toThrow(getError("Todo", "/todo", "map", "")) expect(() => { deadTodo.map.set("mapkey1", "val") }).toThrow(getError("Todo", "/todo", "map", "")) expect(() => { deadTodo.sub.fn2() }).toThrow(getError("Todo", "/todo", "sub", "")) expect(() => { // tslint:disable-next-line:no-unused-expression deadTodo.sub.title }).toThrow(getError("Todo", "/todo", "sub", "")) expect(() => { deadTodo.sub.title = "hi" }).toThrow(getError("Todo", "/todo", "sub", "")) // dead array expect(() => { // tslint:disable-next-line:no-unused-expression deadArr[0] }).toThrow(getError("string[]", "/todo/arr", "0", "")) expect(() => { deadArr[0] = "hi" }).toThrow(getError("string[]", "/todo/arr", "0", "")) expect(() => { deadArr.push("hi") }).toThrow(getError("string[]", "/todo/arr", "1", "")) // dead map expect(() => { deadMap.get("mapkey0") }).toThrow(getError("map<string, string>", "/todo/map", "mapkey0", "")) expect(() => { deadMap.set("mapkey0", "val") }).toThrow(getError("map<string, string>", "/todo/map", "mapkey0", "")) // dead subobj expect(() => { deadSub.fn2() }).toThrow(getError("Sub", "/todo/sub", "", "/todo/sub.fn2()")) expect(() => { // tslint:disable-next-line:no-unused-expression deadSub.title }).toThrow(getError("Sub", "/todo/sub", "title", "")) expect(() => { deadSub.title = "ho" }).toThrow(getError("Sub", "/todo/sub", "title", "")) }) test("it should warn if a replaced object is read or written to", () => { const Todo = types .model("Todo", { title: "test" }) .actions((self) => { function fn() {} return { fn } }) const Store = types.model("Store", { todo: Todo }) const s = Store.create({ todo: { title: "3" } }) unprotect(s) const todo = s.todo s.todo = Todo.create({ title: "4" }) expect(s.todo.title).toBe("4") // try reading old todo setLivelinessChecking("error") const error = "You are trying to read or write to an object that is no longer part of a state tree" expect(() => todo.fn()).toThrow(error) expect(() => todo.title).toThrow(error) unprotect(todo) expect(() => { todo.title = "5" }).toThrow(error) }) // === COMPOSE FACTORY === test("it should compose factories", () => { const { BoxFactory, ColorFactory } = createTestFactories() const ComposedFactory = types.compose(BoxFactory, ColorFactory) expect(getSnapshot(ComposedFactory.create())).toEqual({ width: 0, height: 0, color: "#FFFFFF" }) }) test("it should compose factories with computed properties", () => { const { ComputedFactory2, ColorFactory } = createTestFactories() const ComposedFactory = types.compose(ColorFactory, ComputedFactory2) const store = ComposedFactory.create({ props: { width: 100, height: 200 } }) expect(getSnapshot(store)).toEqual({ props: { width: 100, height: 200 }, color: "#FFFFFF" }) expect(store.area).toBe(20000) expect(typeof store.setWidth).toBe("function") expect(typeof store.setHeight).toBe("function") }) test("it should compose multiple types with computed properties", () => { const { ComputedFactory2, ColorFactory } = createTestFactories() const ComposedFactory = types.compose(ColorFactory, ComputedFactory2) const store = ComposedFactory.create({ props: { width: 100, height: 200 } }) expect(getSnapshot(store)).toEqual({ props: { width: 100, height: 200 }, color: "#FFFFFF" }) expect(store.area).toBe(20000) expect(typeof store.setWidth).toBe("function") expect(typeof store.setHeight).toBe("function") }) test("methods get overridden by compose", () => { const A = types .model({ count: types.optional(types.number, 0) }) .actions((self) => { function increment() { self.count += 1 } return { increment } }) const B = A.actions((self) => ({ increment() { self.count += 10 } })) const store = B.create() expect(getSnapshot(store)).toEqual({ count: 0 }) expect(store.count).toBe(0) store.increment() expect(store.count).toBe(10) }) test("compose should add new props", () => { const A = types.model({ count: types.optional(types.number, 0) }) const B = A.props({ called: types.optional(types.number, 0) }) const store = B.create() expect(getSnapshot(store)).toEqual({ count: 0, called: 0 }) expect(store.count).toBe(0) }) test("models should expose their actions to be used in a composable way", () => { const A = types .model({ count: types.optional(types.number, 0) }) .actions((self) => { function increment() { self.count += 1 } return { increment } }) const B = A.props({ called: types.optional(types.number, 0) }).actions((self) => { const baseIncrement = self.increment return { increment() { baseIncrement() self.called += 1 } } }) const store = B.create() expect(getSnapshot(store)).toEqual({ count: 0, called: 0 }) expect(store.count).toBe(0) store.increment() expect(store.count).toBe(1) expect(store.called).toBe(1) }) test("compose should be overwrite", () => { const A = types .model({ name: "", alias: "" }) .views((self) => ({ get displayName() { return self.alias || self.name } })) const B = A.props({ type: "" }).views((self) => ({ get displayName() { return self.alias || self.name + self.type } })) const storeA = A.create({ name: "nameA", alias: "aliasA" }) const storeB = B.create({ name: "nameB", alias: "aliasB", type: "typeB" }) const storeC = B.create({ name: "nameC", type: "typeC" }) expect(storeA.displayName).toBe("aliasA") expect(storeB.displayName).toBe("aliasB") expect(storeC.displayName).toBe("nameCtypeC") }) // === TYPE CHECKS === test("it should check the type correctly", () => { const { Factory } = createTestFactories() const doc = Factory.create() expect(Factory.is(doc)).toEqual(true) expect(Factory.is([])).toEqual(false) expect(Factory.is({})).toEqual(true) expect(Factory.is({ to: "mars" })).toEqual(true) expect(Factory.is({ wrongKey: true })).toEqual(true) expect(Factory.is({ to: 3 })).toEqual(false) }) if (process.env.NODE_ENV !== "production") { test("complex map / array values are optional by default", () => { expect( types .model({ todo: types.model({}) }) .is({}) ).toBe(false) expect(() => types .model({ todo: types.model({}) }) .create({} as any) ).toThrow() expect( types .model({ todo: types.array(types.string) }) .is({}) ).toBe(true) // TBD: or true? expect( getSnapshot( types .model({ todo: types.array(types.string) }) .create({}) ) ).toEqual({ todo: [] }) expect( types .model({ todo: types.map(types.string) }) .is({}) ).toBe(true) expect( getSnapshot( types .model({ todo: types.map(types.string) }) .create({}) ) ).toEqual({ todo: {} }) }) } // === VIEW FUNCTIONS === test("view functions should be tracked", () => { const model = types .model({ x: 3 }) .views((self) => ({ doubler() { return self.x * 2 } })) .create() unprotect(model) const values: number[] = [] const d = autorun(() => { values.push(model.doubler()) }) model.x = 7 expect(values).toEqual([6, 14]) }) test("view functions should not be allowed to change state", () => { const model = types .model({ x: 3 }) .views((self) => ({ doubler() { self.x *= 2 } })) .actions((self) => { function anotherDoubler() { self.x *= 2 } return { anotherDoubler } }) .create() expect(() => model.doubler()).toThrow() model.anotherDoubler() expect(model.x).toBe(6) }) test("it should consider primitives as proposed defaults", () => { const now = new Date() const Todo = types.model({ id: 0, name: "Hello world", done: false, createdAt: now }) const doc = Todo.create() expect(getSnapshot(doc)).toEqual({ id: 0, name: "Hello world", done: false, createdAt: now.getTime() }) }) test("it should throw if a non-primitive value is provided and no default can be created", () => { expect(() => { types.model({ complex: { a: 1, b: 2 } as any }) }).toThrow() }) if (process.env.NODE_ENV !== "production") { test("it should not be possible to remove a node from a parent if it is required, see ", () => { const A = types.model("A", { x: 3 }) const B = types.model("B", { a: A }) const b = B.create({ a: { x: 7 } }) unprotect(b) expect(() => { detach(b.a) }).toThrowError(/Error while converting `undefined` to `A`/) expect(() => { destroy(b.a) }).toThrowError(/Error while converting `undefined` to `A`/) }) test("it should be possible to remove a node from a parent if it is defined as type maybe ", () => { const A = types.model("A", { x: 3 }) const B = types.model("B", { a: types.maybe(A) }) const b = B.create({ a: { x: 7 } }) unprotect(b) expect(() => { const a = b.a! detach(a) destroy(a) }).not.toThrow() expect(b.a).toBe(undefined) expect(getSnapshot(b).a).toBe(undefined) }) test("it should be possible to remove a node from a parent if it is defined as type maybeNull ", () => { const A = types.model("A", { x: 3 }) const B = types.model("B", { a: types.maybeNull(A) }) const b = B.create({ a: { x: 7 } }) unprotect(b) expect(() => { const a = b.a! detach(a) destroy(a) }).not.toThrow() expect(b.a).toBe(null) expect(getSnapshot(b).a).toBe(null) }) } test("it should be possible to share states between views and actions using enhance", () => { const A = types.model({}).extend((self) => { const localState = observable.box(3) return { views: { get x() { return localState.get() } }, actions: { setX(value: number) { localState.set(value) } } } }) let x = 0 let a = A.create() const d = reaction( () => a.x, (v) => { x = v } ) a.setX(7) expect(a.x).toBe(7) expect(x).toBe(7) d() }) test("It should throw if any other key is returned from extend", () => { const A = types.model({}).extend(() => ({ stuff() {} } as any)) expect(() => A.create()).toThrowError(/stuff/) }) test("782, TS + compose", () => { const User = types.model("User", { id: types.identifier, name: types.maybe(types.string), avatar: types.maybe(types.string) }) const user = User.create({ id: "someId" }) }) test("961 - model creating should not change snapshot", () => { const M = types.model({ foo: 1 }) const o = {} const m = M.create(o) expect(o).toEqual({}) expect(getSnapshot(m)).toEqual({ foo: 1 }) }) if (process.env.NODE_ENV === "development") test("beautiful errors", () => { expect(() => { types.model("User", { x: (types.identifier as any)() }) }).toThrow("types.identifier is not a function") expect(() => { types.model("User", { x: { bla: true } as any }) }).toThrow( "Invalid type definition for property 'x', it looks like you passed an object. Try passing another model type or a types.frozen" ) expect(() => { types.model("User", { x: function () {} as any }) }).toThrow( "Invalid type definition for property 'x', it looks like you passed a function. Did you forget to invoke it, or did you intend to declare a view / action?" ) }) test("#967 - changing values in afterCreate/afterAttach when node is instantiated from view", () => { const Answer = types .model("Answer", { title: types.string, selected: false }) .actions((self) => ({ toggle() { self.selected = !self.selected } })) const Question = types .model("Question", { title: types.string, answers: types.array(Answer) }) .views((self) => ({ get brokenView() { // this should not be allowed // MWE: disabled, MobX 6 no longer forbids this // expect(() => { // self.answers[0].toggle() // }).toThrow() return 0 } })) .actions((self) => ({ afterCreate() { // we should allow changes even when inside a computed property when done inside afterCreate/afterAttach self.answers[0].toggle() // but not further computed changes expect(self.brokenView).toBe(0) }, afterAttach() { // we should allow changes even when inside a computed property when done inside afterCreate/afterAttach self.answers[0].toggle() expect(self.brokenView).toBe(0) } })) const Product = types .model("Product", { questions: types.array(Question) }) .views((self) => ({ get selectedAnswers() { const result = [] for (const question of self.questions) { result.push(question.answers.find((a) => a.selected)) } return result } })) const product = Product.create({ questions: [ { title: "Q 0", answers: [{ title: "A 0.0" }, { title: "A 0.1" }] }, { title: "Q 1", answers: [{ title: "A 1.0" }, { title: "A 1.1" }] } ] }) // tslint:disable-next-line:no-unused-expression product.selectedAnswers }) test("#993-1 - after attach should have a parent when accesing a reference directly", () => { const L4 = types .model("Todo", { id: types.identifier, finished: false }) .actions((self) => ({ afterAttach() { expect(getParent(self)).toBeTruthy() } })) const L3 = types.model({ l4: L4 }).actions((self) => ({ afterAttach() { expect(getParent(self)).toBeTruthy() } })) const L2 = types .model({ l3: L3 }) .actions((self) => ({ afterAttach() { expect(getParent(self)).toBeTruthy() } })) const L1 = types .model({ l2: L2, selected: types.reference(L4) }) .actions((self) => ({ afterAttach() { throw fail("should never be called") } })) const createL1 = () => L1.create({ l2: { l3: { l4: { id: "11124091-11c1-4dda-b2ed-7dd6323491a5" } } }, selected: "11124091-11c1-4dda-b2ed-7dd6323491a5" }) // test 1, real child first { const l1 = createL1() const a = l1.l2.l3.l4 const b = l1.selected } // test 2, reference first { const l1 = createL1() const a = l1.selected const b = l1.l2.l3.l4 } }) test("#993-2 - references should have a parent event when the parent has not been accesed before", () => { const events: string[] = [] const L4 = types .model("Todo", { id: types.identifier, finished: false }) .actions((self) => ({ toggle() { self.finished = !self.finished }, afterCreate() { events.push("l4-ac") }, afterAttach() { events.push("l4-at") } })) const L3 = types.model({ l4: L4 }).actions((self) => ({ afterCreate() { events.push("l3-ac") }, afterAttach() { events.push("l3-at") } })) const L2 = types .model({ l3: L3 }) .actions((self) => ({ afterCreate() { events.push("l2-ac") }, afterAttach() { events.push("l2-at") } })) const L1 = types .model({ l2: L2, selected: types.reference(L4) }) .actions((self) => ({ afterCreate() { events.push("l1-ac") }, afterAttach() { events.push("l1-at") } })) const createL1 = () => L1.create({ l2: { l3: { l4: { id: "11124091-11c1-4dda-b2ed-7dd6323491a5" } } }, selected: "11124091-11c1-4dda-b2ed-7dd6323491a5" }) const expectedEvents = [ "l1-ac", "l2-ac", "l2-at", "l3-ac", "l3-at", "l4-ac", "l4-at", "onSnapshot", "onSnapshot" ] // test 1, real child first { const l1 = createL1() onSnapshot(l1, () => { events.push("onSnapshot") }) l1.l2.l3.l4.toggle() l1.selected.toggle() expect(events).toEqual(expectedEvents) } // test 2, reference first events.length = 0 { const l1 = createL1() onSnapshot(l1, () => { events.push("onSnapshot") }) l1.selected.toggle() l1.l2.l3.l4.toggle() expect(events).toEqual(expectedEvents) } // test 3, reference get parent should be available from the beginning and all the way to the root { const rootL1 = createL1() const l4 = rootL1.selected const l3 = getParent(l4) expect(l3).toBeTruthy() const l2 = getParent(l3) expect(l2).toBeTruthy() const l1 = getParent(l2) expect(l1).toBeTruthy() expect(l1).toBe(rootL1) expect(l2).toBe(rootL1.l2) expect(l3).toBe(rootL1.l2.l3) expect(l4).toBe(rootL1.l2.l3.l4) } }) test("it should emit patches when applySnapshot is used", () => { const { Factory } = createTestFactories() const doc = Factory.create() let patches: IJsonPatch[] = [] onPatch(doc, (patch) => patches.push(patch)) applySnapshot(doc, { ...getSnapshot(doc), to: "universe" }) expect(patches).toEqual([{ op: "replace", path: "/to", value: "universe" }]) }) test("isAlive must be reactive", () => { const Todo = types.model({ text: types.string }) const TodoStore = types.model({ todos: types.array(Todo), todo: types.maybe(Todo) }) const store = TodoStore.create({ todos: [{ text: "1" }, { text: "2" }], todo: { text: "3" } }) unprotect(store) const t1 = store.todos[0]! const t2 = store.todos[1]! const t3 = store.todo! let calls = 0 const r1 = reaction( () => isAlive(t1), (v) => { expect(v).toBe(false) calls++ } ) const r2 = reaction( () => isAlive(t2), (v) => { expect(v).toBe(false) calls++ } ) const r3 = reaction( () => isAlive(t3), (v) => { expect(v).toBe(false) calls++ } ) try { store.todos = cast([]) store.todo = undefined expect(calls).toBe(3) } finally { r1() r2() r3() } }) test("#1112 - identifier cache should be cleared for unaccessed wrapped objects", () => { const mock1 = [ { id: "1", name: "Kate" }, { id: "2", name: "John" } ] const mock2 = [ { id: "3", name: "Andrew" }, { id: "2", name: "John" } ] const mock1_2 = mock1.map((i, index) => ({ text: `Text${index}`, entity: i })) const mock2_2 = mock2.map((i, index) => ({ text: `Text${index}`, entity: i })) const Entity = types.model({ id: types.identifier, name: types.string }) const Wrapper = types.model({ text: types.string, entity: Entity }) const Store = types .model({ list: types.optional(types.array(Wrapper), []), selectedId: 2 }) .views((self) => ({ get selectedEntity() { return resolveIdentifier(Entity, self, self.selectedId) } })) const store = Store.create() unprotect(store) store.list.replace(mock1_2) store.list.replace(mock2_2) expect(store.selectedEntity!.id).toBe("2") }) test("#1173 - detaching a model should not screw it", () => { const AM = types.model({ x: 5 }) const Store = types.model({ item: types.maybe(AM) }) const s = Store.create({ item: { x: 6 } }) const n0 = s.item unprotect(s) const detachedItem = detach(s.item!) expect(s.item).not.toBe(detachedItem) expect(s.item).toBe(undefined) expect(detachedItem.x).toBe(6) expect(detachedItem).toBe(n0) }) test("#1702 - should not throw with useProxies: 'ifavailable'", () => { configure({ useProxies: "ifavailable" }) const M = types.model({ x: 5 }).views((self) => ({ get y() { return self.x } })) expect(() => { M.create({}) }).not.toThrow() })
the_stack
import * as ts from 'typescript'; import {isExpressionString, parseExpressionToken, TokenItem} from 'rcre-runtime'; import {templateParse} from './templateParse'; export * from './templateParse'; const TOKEN_PLACEHOLDER = '__TOKEN__ITEM__'; type BlackList = { [key: string]: boolean; }; /** * 生成节点的操作 递归 * @param node {ts.node} 当前节点 * @param blackList {BlackList} 属性黑名单 * @param isInBlackList {boolean} 表达式是否在属性黑名单中 * @param parentNode {ts.node} 节点的父节点 * @param isKey {boolean} 是否是key 用于判断是否需要添加runTime * @return node {ts.node} 处理后的节点 */ function generateNode(node: ts.Node, blackList: BlackList, isInBlackList: boolean, parentNode?: ts.Node, isKey?: boolean): any { isInBlackList = isInBlackList || blackList[node.getText()]; switch (node.kind) { case ts.SyntaxKind.PropertyAccessExpression: case ts.SyntaxKind.ElementAccessExpression: return createAccessExpression(node, blackList, isInBlackList); case ts.SyntaxKind.ParenthesizedExpression: // 括号 return ts.createParen( generateNode(node.getChildren()[1], blackList, isInBlackList) ); case ts.SyntaxKind.BinaryExpression: // && || 表达式 return ts.createBinary( generateNode(node.getChildren()[0], blackList, isInBlackList, node), generateNode(node.getChildren()[1], blackList, isInBlackList, node), generateNode(node.getChildren()[2], blackList, isInBlackList, node) ); case ts.SyntaxKind.ConditionalExpression: // ? 条件表达式 return ts.createConditional( generateNode(node.getChildren()[0], blackList, isInBlackList), generateNode(node.getChildren()[2], blackList, isInBlackList), generateNode(node.getChildren()[4], blackList, isInBlackList) ); case ts.SyntaxKind.PrefixUnaryExpression: // 前缀符号 return ts.createPrefix( node['operator'], generateNode(node.getChildren()[1], blackList, isInBlackList) ); case ts.SyntaxKind.CallExpression: // 函数 let funcArgs: any = []; node.getChildAt(2).getChildren().forEach((argument: ts.Node) => { if (argument.kind !== ts.SyntaxKind.CommaToken) { funcArgs.push(generateNode(argument, blackList, isInBlackList)); } }); return ts.createCall( generateNode(node.getChildren()[0], blackList, isInBlackList), undefined, funcArgs ); case ts.SyntaxKind.Identifier: // 变量 if (!isKey && !isInBlackList) { return ts.createIdentifier('runTime.' + node.getText()); } else { return ts.createIdentifier(node.getText()); } case ts.SyntaxKind.ObjectLiteralExpression: // {} 对象类型 let properties: any = []; node.getChildren()[1].getChildren().forEach((curNode: ts.Node) => { if (curNode.kind !== ts.SyntaxKind.CommaToken) { properties.push(generateNode(curNode, blackList, isInBlackList)); } }); return ts.createObjectLiteral( properties ); case ts.SyntaxKind.PropertyAssignment: // 对象的属性 return ts.createPropertyAssignment( generateNode(node.getChildren()[0], blackList, isInBlackList, node, true), generateNode(node.getChildren()[2], blackList, isInBlackList) ); case ts.SyntaxKind.NewExpression: // new let newArgs: any = []; node.getChildAt(3).getChildren().forEach((argument: ts.Node) => { if (argument.kind !== ts.SyntaxKind.CommaToken) { newArgs.push(generateNode(argument, blackList, isInBlackList)); } }); return ts.createNew( ts.createIdentifier('runTime.' + node.getChildren()[1].getText()), undefined, newArgs ); case ts.SyntaxKind.ArrayLiteralExpression: // [] 数组类型 let elements: any = []; node.getChildren()[1].getChildren().forEach((curNode: ts.Node) => { if (curNode.kind !== ts.SyntaxKind.CommaToken) { elements.push(generateNode(curNode, blackList, isInBlackList)); } }); return ts.createArrayLiteral( elements ); case ts.SyntaxKind.RegularExpressionLiteral: // 正则表达式 return ts.createRegularExpressionLiteral(node.getText()); case ts.SyntaxKind.AmpersandAmpersandToken: // 符号 return node.kind; case ts.SyntaxKind.NumericLiteral: // 数字 return ts.createNumericLiteral(node.getText()); case ts.SyntaxKind.SpreadElement: // ... return ts.createSpread( generateNode(node.getChildAt(1), blackList, isInBlackList) ); case ts.SyntaxKind.StringLiteral: // 字符串 return ts.createStringLiteral(node.getText().slice(1, node.getText().length - 1)); default: return node; } } /** * 根据传入的kind创建不同的表达式 * @param kind {number} * @return {Expression} */ function createAccessExpressionByKind(kind: number, keyExpression: ts.Expression, valueExpression: any) { if (kind === ts.SyntaxKind.PropertyAccessExpression) { return ts.createPropertyAccess( keyExpression, valueExpression ); } else { return ts.createElementAccess( keyExpression, valueExpression ); } } /** * a.b.c.d => runTime.a.b.c.d 类似的类型生成逻辑 * 左侧加runTime时 所有结合方式改变 树需要重新生成 * ((a.b).c).d => (((runTime.a).b).c).d * @param node {ts.Node} * @param blackList {BlackList} * @return {Expression} */ function createAccessExpression(node: ts.Node, blackList: BlackList, isInBlackList: boolean) { // 使用栈存储树结构 // stack存储节点 // accessStack存储链接节点的方式 let stack: any = []; let accessStack: any = []; let curNode = node; while (curNode.kind === ts.SyntaxKind.PropertyAccessExpression || curNode.kind === ts.SyntaxKind.ElementAccessExpression) { accessStack.push(curNode.kind); stack.push(curNode.getChildAt(2)); curNode = curNode.getChildAt(0); } let newAccessExpression = createAccessExpressionByKind( accessStack.pop(), generateNode(curNode, blackList, isInBlackList, undefined, blackList[node.getText()]), generateNode(stack.pop(), blackList, isInBlackList, undefined, true) ); while (stack.length > 0) { let cur = stack.pop(); newAccessExpression = createAccessExpressionByKind( accessStack.pop(), newAccessExpression, generateNode(cur, blackList, isInBlackList, undefined, true) ); } return newAccessExpression; } export function createNodeFromSource(sourceCode: string, blackList: BlackList) { let sourceFile: ts.SourceFile = ts.createSourceFile( 'test.ts', sourceCode, ts.ScriptTarget.ES2015, true, ts.ScriptKind.TS ); return generateNode(sourceFile.statements[0].getChildAt(0), blackList, false, undefined, undefined); } function createNodeFromExpressionString(esString: string, blackList: BlackList) { esString = esString.trim(); let tokens = parseExpressionToken(esString); let code: string = ''; let generatedCode; if (tokens.length === 1 && tokens[0].token) { code = tokens[0].token!; return createNodeFromSource(code, blackList); } else if (tokens.length > 1) { let strSplits: string[] = []; let index = 0; for (let i = 0; i < tokens.length; i ++) { if (tokens[i].token) { strSplits.push(esString.slice(index, tokens[i].start)); strSplits.push(TOKEN_PLACEHOLDER); index = tokens[i].end; } } if (index < esString.length) { strSplits.push(esString.slice(index, esString.length)); } generatedCode = createTemplateLiteral(strSplits, tokens.filter(token => !!token.token), blackList); } else { return null; } return generatedCode; } /** * 生成箭头函数 * @param node {ts.Node} 源文件 * @return {ArrowFunction} */ function makeArrowFunction(node: ts.Expression) { // 生成箭头函数参数 let parameters = [ ts.createParameter( undefined, undefined, undefined, 'runTime', undefined, ts.createTypeReferenceNode('any', []) ) ]; // 生成箭头函数body let body = ts.createBlock( [ts.createReturn(node)], true ); // 生成箭头函数语句 let arrowFunction = ts.createArrowFunction( undefined, undefined, parameters, undefined, undefined, body ); // 生成包裹as any的定义 return ts.createAsExpression( ts.createParen(arrowFunction), ts.createKeywordTypeNode(ts.SyntaxKind.AnyKeyword) ); } /** * 生成闭包包裹的箭头函数 * @param node {ts.Node} 源文件 * @return {ArrowFunction} */ function makeClosureArrowFunction(node: ts.Expression) { let arrowFunction = makeArrowFunction(node); // 生成闭包函数 let closureFunction = ts.createCall( ts.createParen(arrowFunction), undefined, [] ); // 生成[]包裹 return ts.createComputedPropertyName( closureFunction ); } /** * 创建模板字符串 * @param strSplits 模板片段 * @param tokens 代码片段 * @param blackList 黑名单变量 */ function createTemplateLiteral(strSplits: string[], tokens: TokenItem[], blackList: BlackList) { let headStr; if (strSplits[0] === TOKEN_PLACEHOLDER) { headStr = ''; } else { headStr = strSplits.shift() || ''; } let head = ts.createTemplateHead(headStr); let spans = []; for (let i = 0; i < tokens.length; i ++) { let code = tokens[i].token!; if (i < tokens.length - 1) { let node = createNodeFromSource(code, blackList); strSplits.shift(); let middleText = strSplits.shift() || ''; let middle = ts.createTemplateMiddle(middleText); let span = ts.createTemplateSpan(node, middle); spans.push(span); } else { let node = createNodeFromSource(code, blackList); strSplits.shift(); let tailText = strSplits.shift() || ''; let tail = ts.createTemplateTail(tailText); let span = ts.createTemplateSpan(node, tail); spans.push(span); } } return ts.createTemplateExpression(head, spans); } /** * 将ES表达式中的内容根据自定义函数进行转换 * @param esString {string} ES表达式中的内容 * @return {string} 表达式转换成箭头函数 */ export function transform(esString: string) { let sourceFile: ts.SourceFile = ts.createSourceFile( 'test.ts', esString, ts.ScriptTarget.ES2015, true, ts.ScriptKind.TS ); let expression = generateNode(sourceFile.statements[0].getChildAt(0), {}, false); let node = makeArrowFunction(expression); let printer: ts.Printer = ts.createPrinter(); let result = printer.printNode( ts.EmitHint.Unspecified, node, sourceFile ); return result; } const transformer = <T extends ts.Node>(context: ts.TransformationContext) => (rootNode: T) => { function visit(node: ts.Node): ts.Node { node = ts.visitEachChild(node, visit, context); switch (node.kind) { case ts.SyntaxKind.PropertyAssignment: { let assignment = node as ts.PropertyAssignment; let name = assignment.name; let initializer = assignment.initializer; if (name.kind === ts.SyntaxKind.StringLiteral) { let text = name.text.trim(); if (isExpressionString(text)) { let generateCode = createNodeFromExpressionString(text, {}); if (!generateCode) { return node; } let key = makeClosureArrowFunction(generateCode); return ts.createPropertyAssignment(key, initializer); } } else if (name.kind === ts.SyntaxKind.ComputedPropertyName) { if (name.expression.kind === ts.SyntaxKind.StringLiteral) { let text = name.expression['text']; if (isExpressionString(text)) { let generateCode = createNodeFromExpressionString(text, {}); if (!generateCode) { return node; } let key = makeClosureArrowFunction(generateCode); return ts.createPropertyAssignment(key, initializer); } } if (name.expression.kind === ts.SyntaxKind.NoSubstitutionTemplateLiteral || name.expression.kind === ts.SyntaxKind.TemplateExpression) { let text = name.expression.getText().trim(); let { code, blackList } = templateParse(text); code = code.slice(1, -1); if (isExpressionString(code)) { let generatedNode = createNodeFromExpressionString(code, blackList); if (!generatedNode) { return node; } let key = makeClosureArrowFunction(generatedNode); return ts.createPropertyAssignment(key, initializer); } } } break; } case ts.SyntaxKind.TemplateExpression: case ts.SyntaxKind.NoSubstitutionTemplateLiteral: { if (node.parent.kind === ts.SyntaxKind.ComputedPropertyName && (node.parent as ts.ComputedPropertyName).expression === node) { break; } let text = node.getText().trim(); let { code, blackList } = templateParse(text); code = code.slice(1, -1); if (isExpressionString(code)) { let generatedNode = createNodeFromExpressionString(code, blackList); if (!generatedNode) { return node; } return makeArrowFunction(generatedNode); } break; } case ts.SyntaxKind.StringLiteral: { if ((node.parent.kind === ts.SyntaxKind.PropertyAssignment && (node.parent as ts.PropertyAssignment).name === node) || (node.parent.kind === ts.SyntaxKind.ComputedPropertyName && (node.parent as ts.ComputedPropertyName).expression === node)) { break; } let text = node.getText().slice(1, -1).trim(); if (isExpressionString(text)) { let generatedNode = createNodeFromExpressionString(text, {}); if (!generatedNode) { return node; } return makeArrowFunction(generatedNode); } break; } default: } return node; } return ts.visitNode(rootNode, visit); }; const stringPreCompileTransFormer = <T extends ts.Node>(context: ts.TransformationContext) => (rootNode: T) => { function visit(node: ts.Node): ts.Node { node = ts.visitEachChild(node, visit, context); if (node.kind === ts.SyntaxKind.BinaryExpression) { let binary = node as ts.BinaryExpression; if (binary.operatorToken.kind !== ts.SyntaxKind.PlusToken) { return node; } let leftKind = binary.left.kind; let rightKind = binary.right.kind; let left: string = ''; let right: string = ''; // 两边都是直接拼接的字符串 if ( (leftKind === ts.SyntaxKind.StringLiteral || leftKind === ts.SyntaxKind.NoSubstitutionTemplateLiteral || leftKind === ts.SyntaxKind.TemplateExpression) && (rightKind === ts.SyntaxKind.StringLiteral || rightKind === ts.SyntaxKind.NoSubstitutionTemplateLiteral || rightKind === ts.SyntaxKind.TemplateExpression) ) { if (leftKind === ts.SyntaxKind.TemplateExpression) { let expression = binary.left as ts.TemplateExpression; let head = expression.head.text; let spans = expression.templateSpans.map((span: ts.TemplateSpan) => { let tail = span.literal.text; let body = span.expression.getText(); return '${' + body + '}' + tail; }); left = head + spans.join(''); } else if (binary.left.kind === ts.SyntaxKind.StringLiteral || binary.left.kind === ts.SyntaxKind.NoSubstitutionTemplateLiteral) { let leftNode = binary.left as ts.StringLiteralLike; left = leftNode.text; } if (rightKind === ts.SyntaxKind.TemplateExpression) { let expression = binary.right as ts.TemplateExpression; let head = expression.head.text; let spans = expression.templateSpans.map((span: ts.TemplateSpan) => { let tail = span.literal.text; let body = span.expression.getText(); return '${' + body + '}' + tail; }); right = head + spans.join(''); } else if (binary.right.kind === ts.SyntaxKind.StringLiteral || binary.right.kind === ts.SyntaxKind.NoSubstitutionTemplateLiteral) { let rightNode = binary.right as ts.StringLiteralLike; right = rightNode.text; } return ts.createNoSubstitutionTemplateLiteral(left + right); } } return node; } return ts.visitNode(rootNode, visit); }; function stringPreCompile(code: string, fileKind: string = 'ts') { let fileKindMap = { 'ts': ts.ScriptKind.TS, 'tsx': ts.ScriptKind.TSX }; const printer: ts.Printer = ts.createPrinter(); const sourceFile: ts.SourceFile = ts.createSourceFile( 'test.ts', code, ts.ScriptTarget.ES2015, true, fileKindMap[fileKind] ); const result: ts.TransformationResult<ts.SourceFile> = ts.transform<ts.SourceFile>( sourceFile, [stringPreCompileTransFormer] ); const transformedSourceFile: ts.SourceFile = result.transformed[0]; return printer.printFile(transformedSourceFile); } /** * 将整个文件内容进行转换 * @param file {string} 文件的内容 * @return {string} 转换后的文件内容 */ export function transformFile(file: string, fileKind: string = 'ts') { file = stringPreCompile(file, fileKind); const printer: ts.Printer = ts.createPrinter(); let fileKindMap = { 'ts': ts.ScriptKind.TS, 'tsx': ts.ScriptKind.TSX }; const sourceFile: ts.SourceFile = ts.createSourceFile( 'test.ts', file, ts.ScriptTarget.ES2015, true, fileKindMap[fileKind] ); const result: ts.TransformationResult<ts.SourceFile> = ts.transform<ts.SourceFile>( sourceFile, [transformer] ); const transformedSourceFile: ts.SourceFile = result.transformed[0]; return printer.printFile(transformedSourceFile); }
the_stack
import { PdfColor } from './pdf-color'; import { PdfSolidBrush } from './brushes/pdf-solid-brush'; import { PdfDashStyle, PdfLineCap, PdfLineJoin, PdfColorSpace } from './enum'; import { PdfBrush } from './brushes/pdf-brush'; import { GetResourceEventHandler } from './pdf-graphics'; import { PdfTransformationMatrix } from './pdf-transformation-matrix'; import { PdfStreamWriter } from './../input-output/pdf-stream-writer'; /** * `PdfPen` class defining settings for drawing operations, that determines the color, * width, and style of the drawing elements. * ```typescript * // create a new PDF document * let document : PdfDocument = new PdfDocument(); * // create a new page * let page1 : PdfPage = document.pages.add(); * // set pen * let pen : PdfPen = new PdfPen(new PdfColor(0, 0, 0)); * // draw rectangle * page1.graphics.drawRectangle(pen, new RectangleF({x : 0, y : 0}, {width : 100, height : 50})); * // save the document. * document.save('output.pdf'); * // destroy the document * document.destroy(); * ``` */ export class PdfPen { //Fields /** * Specifies the `color of the pen`. * @default new PdfColor() * @private */ private pdfColor : PdfColor = new PdfColor(0, 0, 0); /** * Specifies the `dash offset of the pen`. * @default 0 * @private */ private dashOffsetValue : number = 0; /** * Specifies the `dash pattern of the pen`. * @default [0] * @private */ private penDashPattern : number[] = [0]; /** * Specifies the `dash style of the pen`. * @default Solid * @private */ private pdfDashStyle : PdfDashStyle = PdfDashStyle.Solid; /** * Specifies the `line cap of the pen`. * @default 0 * @private */ private pdfLineCap : PdfLineCap = 0; /** * Specifies the `line join of the pen`. * @default 0 * @private */ private pdfLineJoin : PdfLineJoin = 0; /** * Specifies the `width of the pen`. * @default 1.0 * @private */ private penWidth : number = 1.0; /** * Specifies the `brush of the pen`. * @private */ private pdfBrush : PdfBrush; /** * Specifies the `mitter limit of the pen`. * @default 0.0 * @private */ private internalMiterLimit : number = 0.0; /** * Stores the `colorspace` value. * @default Rgb * @private */ private colorSpace : PdfColorSpace = PdfColorSpace.Rgb; /** * Initializes a new instance of the `PdfPen` class with color. * ```typescript * // create a new PDF document * let document : PdfDocument = new PdfDocument(); * // create a new page * let page1 : PdfPage = document.pages.add(); * // * // set pen * let pen : PdfPen = new PdfPen(new PdfColor(0, 0, 0)); * // * // draw rectangle * page1.graphics.drawRectangle(pen, new RectangleF({x : 0, y : 0}, {width : 100, height : 50})); * // save the document. * document.save('output.pdf'); * // destroy the document * document.destroy(); * ``` * @param color Color of the pen. */ public constructor(color : PdfColor) /** * Initializes a new instance of the `PdfPen` class with 'PdfBrush' class and width of the pen. * @private */ public constructor(brush : PdfBrush, width : number) /** * Initializes a new instance of the `PdfPen` class with color and width of the pen. * ```typescript * // create a new PDF document * let document : PdfDocument = new PdfDocument(); * // create a new page * let page1 : PdfPage = document.pages.add(); * // * // set pen * let pen : PdfPen = new PdfPen(new PdfColor(0, 0, 0), 2); * // * // draw rectangle * page1.graphics.drawRectangle(pen, new RectangleF({x : 0, y : 0}, {width : 100, height : 50})); * // save the document. * document.save('output.pdf'); * // destroy the document * document.destroy(); * ``` * @param color Color of the pen. * @param width Width of the pen's line. */ public constructor(color : PdfColor, width : number) public constructor(arg1 : PdfColor|PdfBrush, arg2? : number) { if ( arg1 instanceof PdfBrush) { this.setBrush(arg1 as PdfBrush); } else if ( arg1 instanceof PdfColor) { this.color = arg1; } if (typeof arg2 === 'number') { this.width = arg2; } } //Properties /** * Gets or sets the `color of the pen`. * @private */ public get color() : PdfColor { return this.pdfColor; } public set color(value : PdfColor) { this.pdfColor = value; } /** * Gets or sets the `dash offset of the pen`. * @private */ public get dashOffset() : number { if (typeof this.dashOffsetValue === 'undefined' || this.dashOffsetValue == null) { return 0; } else { return this.dashOffsetValue; } } public set dashOffset(value : number) { this.dashOffsetValue = value; } /** * Gets or sets the `dash pattern of the pen`. * @private */ public get dashPattern() : number[] { return this.penDashPattern; } public set dashPattern(value : number[]) { this.penDashPattern = value; } /** * Gets or sets the `dash style of the pen`. * ```typescript * // create a new PDF document * let document : PdfDocument = new PdfDocument(); * // create a new page * let page1 : PdfPage = document.pages.add(); * // set pen * let pen : PdfPen = new PdfPen(new PdfColor(0, 0, 0)); * // * // set pen style * pen.dashStyle = PdfDashStyle.DashDot; * // get pen style * let style : PdfDashStyle = pen.dashStyle; * // * // draw rectangle * page1.graphics.drawRectangle(pen, new RectangleF({x : 0, y : 0}, {width : 100, height : 50})); * // save the document. * document.save('output.pdf'); * // destroy the document * document.destroy(); * ``` */ public get dashStyle() : PdfDashStyle { return this.pdfDashStyle; } public set dashStyle(value : PdfDashStyle) { if (this.pdfDashStyle !== value) { this.pdfDashStyle = value; switch (this.pdfDashStyle) { case PdfDashStyle.Custom: break; case PdfDashStyle.Dash: this.penDashPattern = [3, 1]; break; case PdfDashStyle.Dot: this.penDashPattern = [1, 1]; break; case PdfDashStyle.DashDot: this.penDashPattern = [3, 1, 1, 1]; break; case PdfDashStyle.DashDotDot: this.penDashPattern = [3, 1, 1, 1, 1, 1]; break; case PdfDashStyle.Solid: break; default: this.pdfDashStyle = PdfDashStyle.Solid; this.penDashPattern = [0]; break; } } } /** * Gets or sets the `line cap of the pen`. * @private */ public get lineCap() : PdfLineCap { return this.pdfLineCap; } public set lineCap(value : PdfLineCap) { this.pdfLineCap = value; } /** * Gets or sets the `line join style of the pen`. * @private */ public get lineJoin() : PdfLineJoin { return this.pdfLineJoin; } public set lineJoin(value : PdfLineJoin) { this.pdfLineJoin = value; } /** * Gets or sets the `miter limit`. * @private */ public get miterLimit() : number { return this.internalMiterLimit; } public set miterLimit(value : number) { this.internalMiterLimit = value; } /** * Gets or sets the `width of the pen`. * ```typescript * // create a new PDF document * let document : PdfDocument = new PdfDocument(); * // create a new page * let page1 : PdfPage = document.pages.add(); * // set pen * let pen : PdfPen = new PdfPen(new PdfColor(0, 0, 0)); * // * // set pen width * pen.width = 2; * // * // draw rectangle * page1.graphics.drawRectangle(pen, new RectangleF({x : 0, y : 0}, {width : 100, height : 50})); * // save the document. * document.save('output.pdf'); * // destroy the document * document.destroy(); * ``` */ public get width() : number { return this.penWidth; } public set width(value : number) { this.penWidth = value; } //Helper /** * `Clones` this instance of PdfPen class. * @private */ public clone() : PdfPen { let pen : PdfPen = this; return pen; } /** * `Sets the brush`. * @private */ private setBrush(brush : PdfBrush) : void { let sBrush : PdfSolidBrush = brush as PdfSolidBrush; if ((sBrush != null && sBrush instanceof PdfSolidBrush)) { this.color = sBrush.color; this.pdfBrush = sBrush; } this.color = sBrush.color; this.pdfBrush = sBrush; } /** * `Monitors the changes`. * @private */ public monitorChanges(currentPen : PdfPen, streamWriter : PdfStreamWriter, getResources : GetResourceEventHandler, saveState : boolean, currentColorSpace : PdfColorSpace, matrix : PdfTransformationMatrix) : boolean { let diff : boolean = false; saveState = true; if (currentPen == null) { diff = true; } diff = this.dashControl(currentPen, saveState, streamWriter); streamWriter.setLineWidth(this.width); streamWriter.setLineJoin(this.lineJoin); streamWriter.setLineCap(this.lineCap); let miterLimit : number = this.miterLimit; if (miterLimit > 0) { streamWriter.setMiterLimit(miterLimit); diff = true; } let brush : PdfBrush = this.pdfBrush; streamWriter.setColorAndSpace(this.color, currentColorSpace, true); diff = true; return diff; } /** * `Controls the dash style` and behaviour of each line. * @private */ private dashControl(pen : PdfPen, saveState : boolean, streamWriter : PdfStreamWriter) : boolean { saveState = true; let lineWidth : number = this.width; let pattern : number[] = this.getPattern(); streamWriter.setLineDashPattern(pattern, this.dashOffset * lineWidth); return saveState; } /** * `Gets the pattern` of PdfPen. * @private */ public getPattern() : number[] { let pattern : number[] = this.dashPattern as number[]; for (let i : number = 0; i < pattern.length; ++i) { pattern[i] *= this.width; } return pattern; } }
the_stack
import { AST_NODE_TYPES, TSESTree, } from '@typescript-eslint/experimental-utils'; import * as util from '../util'; interface Failure { unify: Unify; only2: boolean; } type Unify = | { kind: 'single-parameter-difference'; p0: TSESTree.Parameter; p1: TSESTree.Parameter; } | { kind: 'extra-parameter'; extraParameter: TSESTree.Parameter; otherSignature: SignatureDefinition; }; /** * Returns true if typeName is the name of an *outer* type parameter. * In: `interface I<T> { m<U>(x: U): T }`, only `T` is an outer type parameter. */ type IsTypeParameter = (typeName: string) => boolean; type ScopeNode = | TSESTree.Program | TSESTree.TSModuleBlock | TSESTree.TSInterfaceBody | TSESTree.ClassBody | TSESTree.TSTypeLiteral; type OverloadNode = MethodDefinition | SignatureDefinition; type ContainingNode = | TSESTree.ExportNamedDeclaration | TSESTree.ExportDefaultDeclaration; type SignatureDefinition = | TSESTree.FunctionExpression | TSESTree.TSCallSignatureDeclaration | TSESTree.TSConstructSignatureDeclaration | TSESTree.TSDeclareFunction | TSESTree.TSEmptyBodyFunctionExpression | TSESTree.TSMethodSignature; type MethodDefinition = | TSESTree.MethodDefinition | TSESTree.TSAbstractMethodDefinition; export default util.createRule({ name: 'unified-signatures', meta: { docs: { description: 'Warns for any two overloads that could be unified into one by using a union or an optional/rest parameter', // too opinionated to be recommended recommended: false, }, type: 'suggestion', messages: { omittingRestParameter: '{{failureStringStart}} with a rest parameter.', omittingSingleParameter: '{{failureStringStart}} with an optional parameter.', singleParameterDifference: '{{failureStringStart}} taking `{{type1}} | {{type2}}`.', }, schema: [], }, defaultOptions: [], create(context) { const sourceCode = context.getSourceCode(); //---------------------------------------------------------------------- // Helpers //---------------------------------------------------------------------- function failureStringStart(otherLine?: number): string { // For only 2 overloads we don't need to specify which is the other one. const overloads = otherLine === undefined ? 'These overloads' : `This overload and the one on line ${otherLine}`; return `${overloads} can be combined into one signature`; } function addFailures(failures: Failure[]): void { for (const failure of failures) { const { unify, only2 } = failure; switch (unify.kind) { case 'single-parameter-difference': { const { p0, p1 } = unify; const lineOfOtherOverload = only2 ? undefined : p0.loc.start.line; const typeAnnotation0 = isTSParameterProperty(p0) ? p0.parameter.typeAnnotation : p0.typeAnnotation; const typeAnnotation1 = isTSParameterProperty(p1) ? p1.parameter.typeAnnotation : p1.typeAnnotation; context.report({ loc: p1.loc, messageId: 'singleParameterDifference', data: { failureStringStart: failureStringStart(lineOfOtherOverload), type1: sourceCode.getText(typeAnnotation0?.typeAnnotation), type2: sourceCode.getText(typeAnnotation1?.typeAnnotation), }, node: p1, }); break; } case 'extra-parameter': { const { extraParameter, otherSignature } = unify; const lineOfOtherOverload = only2 ? undefined : otherSignature.loc.start.line; context.report({ loc: extraParameter.loc, messageId: extraParameter.type === AST_NODE_TYPES.RestElement ? 'omittingRestParameter' : 'omittingSingleParameter', data: { failureStringStart: failureStringStart(lineOfOtherOverload), }, node: extraParameter, }); } } } } function checkOverloads( signatures: readonly OverloadNode[][], typeParameters?: TSESTree.TSTypeParameterDeclaration, ): Failure[] { const result: Failure[] = []; const isTypeParameter = getIsTypeParameter(typeParameters); for (const overloads of signatures) { if (overloads.length === 2) { const signature0 = (overloads[0] as MethodDefinition).value || overloads[0]; const signature1 = (overloads[1] as MethodDefinition).value || overloads[1]; const unify = compareSignatures( signature0, signature1, isTypeParameter, ); if (unify !== undefined) { result.push({ unify, only2: true }); } } else { forEachPair(overloads, (a, b) => { const signature0 = (a as MethodDefinition).value || a; const signature1 = (b as MethodDefinition).value || b; const unify = compareSignatures( signature0, signature1, isTypeParameter, ); if (unify !== undefined) { result.push({ unify, only2: false }); } }); } } return result; } function compareSignatures( a: SignatureDefinition, b: SignatureDefinition, isTypeParameter: IsTypeParameter, ): Unify | undefined { if (!signaturesCanBeUnified(a, b, isTypeParameter)) { return undefined; } return a.params.length === b.params.length ? signaturesDifferBySingleParameter(a.params, b.params) : signaturesDifferByOptionalOrRestParameter(a, b); } function signaturesCanBeUnified( a: SignatureDefinition, b: SignatureDefinition, isTypeParameter: IsTypeParameter, ): boolean { // Must return the same type. const aTypeParams = a.typeParameters !== undefined ? a.typeParameters.params : undefined; const bTypeParams = b.typeParameters !== undefined ? b.typeParameters.params : undefined; return ( typesAreEqual(a.returnType, b.returnType) && // Must take the same type parameters. // If one uses a type parameter (from outside) and the other doesn't, they shouldn't be joined. util.arraysAreEqual(aTypeParams, bTypeParams, typeParametersAreEqual) && signatureUsesTypeParameter(a, isTypeParameter) === signatureUsesTypeParameter(b, isTypeParameter) ); } /** Detect `a(x: number, y: number, z: number)` and `a(x: number, y: string, z: number)`. */ function signaturesDifferBySingleParameter( types1: readonly TSESTree.Parameter[], types2: readonly TSESTree.Parameter[], ): Unify | undefined { const index = getIndexOfFirstDifference( types1, types2, parametersAreEqual, ); if (index === undefined) { return undefined; } // If remaining arrays are equal, the signatures differ by just one parameter type if ( !util.arraysAreEqual( types1.slice(index + 1), types2.slice(index + 1), parametersAreEqual, ) ) { return undefined; } const a = types1[index]; const b = types2[index]; // Can unify `a?: string` and `b?: number`. Can't unify `...args: string[]` and `...args: number[]`. // See https://github.com/Microsoft/TypeScript/issues/5077 return parametersHaveEqualSigils(a, b) && a.type !== AST_NODE_TYPES.RestElement ? { kind: 'single-parameter-difference', p0: a, p1: b } : undefined; } /** * Detect `a(): void` and `a(x: number): void`. * Returns the parameter declaration (`x: number` in this example) that should be optional/rest, and overload it's a part of. */ function signaturesDifferByOptionalOrRestParameter( a: SignatureDefinition, b: SignatureDefinition, ): Unify | undefined { const sig1 = a.params; const sig2 = b.params; const minLength = Math.min(sig1.length, sig2.length); const longer = sig1.length < sig2.length ? sig2 : sig1; const shorter = sig1.length < sig2.length ? sig1 : sig2; const shorterSig = sig1.length < sig2.length ? a : b; // If one is has 2+ parameters more than the other, they must all be optional/rest. // Differ by optional parameters: f() and f(x), f() and f(x, ?y, ...z) // Not allowed: f() and f(x, y) for (let i = minLength + 1; i < longer.length; i++) { if (!parameterMayBeMissing(longer[i])) { return undefined; } } for (let i = 0; i < minLength; i++) { const sig1i = sig1[i]; const sig2i = sig2[i]; const typeAnnotation1 = isTSParameterProperty(sig1i) ? sig1i.parameter.typeAnnotation : sig1i.typeAnnotation; const typeAnnotation2 = isTSParameterProperty(sig2i) ? sig2i.parameter.typeAnnotation : sig2i.typeAnnotation; if (!typesAreEqual(typeAnnotation1, typeAnnotation2)) { return undefined; } } if ( minLength > 0 && shorter[minLength - 1].type === AST_NODE_TYPES.RestElement ) { return undefined; } return { extraParameter: longer[longer.length - 1], kind: 'extra-parameter', otherSignature: shorterSig, }; } /** Given type parameters, returns a function to test whether a type is one of those parameters. */ function getIsTypeParameter( typeParameters?: TSESTree.TSTypeParameterDeclaration, ): IsTypeParameter { if (typeParameters === undefined) { return (() => false) as IsTypeParameter; } const set = new Set<string>(); for (const t of typeParameters.params) { set.add(t.name.name); } return (typeName => set.has(typeName)) as IsTypeParameter; } /** True if any of the outer type parameters are used in a signature. */ function signatureUsesTypeParameter( sig: SignatureDefinition, isTypeParameter: IsTypeParameter, ): boolean { return sig.params.some((p: TSESTree.Parameter) => typeContainsTypeParameter( isTSParameterProperty(p) ? p.parameter.typeAnnotation : p.typeAnnotation, ), ); function typeContainsTypeParameter( type?: TSESTree.TSTypeAnnotation | TSESTree.TypeNode, ): boolean { if (!type) { return false; } if (type.type === AST_NODE_TYPES.TSTypeReference) { const typeName = type.typeName; if (isIdentifier(typeName) && isTypeParameter(typeName.name)) { return true; } } return typeContainsTypeParameter( (type as TSESTree.TSTypeAnnotation).typeAnnotation || (type as TSESTree.TSArrayType).elementType, ); } } function isTSParameterProperty( node: TSESTree.Node, ): node is TSESTree.TSParameterProperty { return ( (node as TSESTree.TSParameterProperty).type === AST_NODE_TYPES.TSParameterProperty ); } function parametersAreEqual( a: TSESTree.Parameter, b: TSESTree.Parameter, ): boolean { const typeAnnotationA = isTSParameterProperty(a) ? a.parameter.typeAnnotation : a.typeAnnotation; const typeAnnotationB = isTSParameterProperty(b) ? b.parameter.typeAnnotation : b.typeAnnotation; return ( parametersHaveEqualSigils(a, b) && typesAreEqual(typeAnnotationA, typeAnnotationB) ); } /** True for optional/rest parameters. */ function parameterMayBeMissing(p: TSESTree.Parameter): boolean | undefined { const optional = isTSParameterProperty(p) ? p.parameter.optional : p.optional; return p.type === AST_NODE_TYPES.RestElement || optional; } /** False if one is optional and the other isn't, or one is a rest parameter and the other isn't. */ function parametersHaveEqualSigils( a: TSESTree.Parameter, b: TSESTree.Parameter, ): boolean { const optionalA = isTSParameterProperty(a) ? a.parameter.optional : a.optional; const optionalB = isTSParameterProperty(b) ? b.parameter.optional : b.optional; return ( (a.type === AST_NODE_TYPES.RestElement) === (b.type === AST_NODE_TYPES.RestElement) && (optionalA !== undefined) === (optionalB !== undefined) ); } function typeParametersAreEqual( a: TSESTree.TSTypeParameter, b: TSESTree.TSTypeParameter, ): boolean { return ( a.name.name === b.name.name && constraintsAreEqual(a.constraint, b.constraint) ); } function typesAreEqual( a: TSESTree.TSTypeAnnotation | undefined, b: TSESTree.TSTypeAnnotation | undefined, ): boolean { return ( a === b || (a !== undefined && b !== undefined && sourceCode.getText(a.typeAnnotation) === sourceCode.getText(b.typeAnnotation)) ); } function constraintsAreEqual( a: TSESTree.TypeNode | undefined, b: TSESTree.TypeNode | undefined, ): boolean { return ( a === b || (a !== undefined && b !== undefined && a.type === b.type) ); } /* Returns the first index where `a` and `b` differ. */ function getIndexOfFirstDifference<T>( a: readonly T[], b: readonly T[], equal: util.Equal<T>, ): number | undefined { for (let i = 0; i < a.length && i < b.length; i++) { if (!equal(a[i], b[i])) { return i; } } return undefined; } /** Calls `action` for every pair of values in `values`. */ function forEachPair<T>( values: readonly T[], action: (a: T, b: T) => void, ): void { for (let i = 0; i < values.length; i++) { for (let j = i + 1; j < values.length; j++) { action(values[i], values[j]); } } } interface Scope { overloads: Map<string, OverloadNode[]>; parent?: ScopeNode; typeParameters?: TSESTree.TSTypeParameterDeclaration; } const scopes: Scope[] = []; let currentScope: Scope = { overloads: new Map<string, OverloadNode[]>(), }; function createScope( parent: ScopeNode, typeParameters?: TSESTree.TSTypeParameterDeclaration, ): void { currentScope && scopes.push(currentScope); currentScope = { overloads: new Map<string, OverloadNode[]>(), parent, typeParameters, }; } function checkScope(): void { const failures = checkOverloads( Array.from(currentScope.overloads.values()), currentScope.typeParameters, ); addFailures(failures); currentScope = scopes.pop()!; } function addOverload( signature: OverloadNode, key?: string, containingNode?: ContainingNode, ): void { key = key ?? getOverloadKey(signature); if ( currentScope && (containingNode || signature).parent === currentScope.parent ) { const overloads = currentScope.overloads.get(key); if (overloads !== undefined) { overloads.push(signature); } else { currentScope.overloads.set(key, [signature]); } } } //---------------------------------------------------------------------- // Public //---------------------------------------------------------------------- return { Program: createScope, TSModuleBlock: createScope, TSInterfaceDeclaration(node): void { createScope(node.body, node.typeParameters); }, ClassDeclaration(node): void { createScope(node.body, node.typeParameters); }, TSTypeLiteral: createScope, // collect overloads TSDeclareFunction(node): void { const exportingNode = getExportingNode(node); addOverload(node, node.id?.name ?? exportingNode?.type, exportingNode); }, TSCallSignatureDeclaration: addOverload, TSConstructSignatureDeclaration: addOverload, TSMethodSignature: addOverload, TSAbstractMethodDefinition(node): void { if (!node.value.body) { addOverload(node); } }, MethodDefinition(node): void { if (!node.value.body) { addOverload(node); } }, // validate scopes 'Program:exit': checkScope, 'TSModuleBlock:exit': checkScope, 'TSInterfaceDeclaration:exit': checkScope, 'ClassDeclaration:exit': checkScope, 'TSTypeLiteral:exit': checkScope, }; }, }); function getExportingNode( node: TSESTree.TSDeclareFunction, ): | TSESTree.ExportNamedDeclaration | TSESTree.ExportDefaultDeclaration | undefined { return node.parent && (node.parent.type === AST_NODE_TYPES.ExportNamedDeclaration || node.parent.type === AST_NODE_TYPES.ExportDefaultDeclaration) ? node.parent : undefined; } function getOverloadKey(node: OverloadNode): string { const info = getOverloadInfo(node); return ( ((node as MethodDefinition).computed ? '0' : '1') + ((node as MethodDefinition).static ? '0' : '1') + info ); } function getOverloadInfo(node: OverloadNode): string { switch (node.type) { case AST_NODE_TYPES.TSConstructSignatureDeclaration: return 'constructor'; case AST_NODE_TYPES.TSCallSignatureDeclaration: return '()'; default: { const { key } = node as MethodDefinition; return isIdentifier(key) ? key.name : (key as TSESTree.Literal).raw; } } } function isIdentifier(node: TSESTree.Node): node is TSESTree.Identifier { return node.type === AST_NODE_TYPES.Identifier; }
the_stack
import { Injectable } from '@angular/core'; import { CoreError } from '@classes/errors/error'; import { CoreCourseCommonModWSOptions } from '@features/course/services/course'; import { CoreSites } from '@services/sites'; import { CoreDomUtils } from '@services/utils/dom'; import { CoreUtils } from '@services/utils/utils'; import { makeSingleton, Translate } from '@singletons'; import { AddonModScorm, AddonModScormAttempt, AddonModScormAttemptCountResult, AddonModScormDataValue, AddonModScormGetScosWithDataOptions, AddonModScormProvider, AddonModScormScoIcon, AddonModScormScorm, AddonModScormScoWithData, AddonModScormTOCListSco, AddonModScormUserDataMap, } from './scorm'; import { AddonModScormOffline } from './scorm-offline'; // List of elements we want to ignore when copying attempts (they're calculated). const elementsToIgnore = [ 'status', 'score_raw', 'total_time', 'session_time', 'student_id', 'student_name', 'credit', 'mode', 'entry', ]; /** * Helper service that provides some features for SCORM. */ @Injectable({ providedIn: 'root' }) export class AddonModScormHelperProvider { /** * Show a confirm dialog if needed. If SCORM doesn't have size, try to calculate it. * * @param scorm SCORM to download. * @param isOutdated True if package outdated, false if not outdated, undefined to calculate it. * @return Promise resolved if the user confirms or no confirmation needed. */ async confirmDownload(scorm: AddonModScormScorm, isOutdated?: boolean): Promise<void> { // Check if file should be downloaded. const download = await AddonModScorm.shouldDownloadMainFile(scorm, isOutdated); if (!download) { // No need to download main file, no need to confirm. return; } let size = scorm.packagesize; if (!size) { // We don't have package size, try to calculate it. size = await AddonModScorm.calculateScormSize(scorm); // Store it so we don't have to calculate it again when using the same object. scorm.packagesize = size; } return CoreDomUtils.confirmDownloadSize({ size: size, total: true }); } /** * Creates a new offline attempt based on an existing online attempt. * * @param scorm SCORM. * @param attempt Number of the online attempt. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the attempt is created. */ async convertAttemptToOffline(scorm: AddonModScormScorm, attempt: number, siteId?: string): Promise<void> { siteId = siteId || CoreSites.getCurrentSiteId(); // Get data from the online attempt. const onlineData = await CoreUtils.ignoreErrors( AddonModScorm.getScormUserData(scorm.id, attempt, { cmId: scorm.coursemodule, siteId }), ); if (!onlineData) { // Shouldn't happen. throw new CoreError(Translate.instant('addon.mod_scorm.errorcreateofflineattempt')); } // The SCORM API might have written some data to the offline attempt already. // We don't want to override it with cached online data. const offlineData = await CoreUtils.ignoreErrors( AddonModScormOffline.getScormUserData(scorm.id, attempt, undefined, siteId), ); const dataToStore = CoreUtils.clone(onlineData); // Filter the data to copy. for (const scoId in dataToStore) { const sco = dataToStore[scoId]; // Delete calculated data. elementsToIgnore.forEach((el) => { delete sco.userdata[el]; }); // Don't override offline data. if (offlineData && offlineData[sco.scoid] && offlineData[sco.scoid].userdata) { const scoUserData: Record<string, AddonModScormDataValue> = {}; for (const element in sco.userdata) { if (!offlineData[sco.scoid].userdata[element]) { // This element is not stored in offline, we can save it. scoUserData[element] = sco.userdata[element]; } } sco.userdata = scoUserData; } } await AddonModScormOffline.createNewAttempt(scorm, attempt, dataToStore, onlineData, siteId); } /** * Creates a new offline attempt. * * @param scorm SCORM. * @param newAttempt Number of the new attempt. * @param lastOnline Number of the last online attempt. * @param siteId Site ID. If not defined, current site. * @return Promise resolved when the attempt is created. */ async createOfflineAttempt(scorm: AddonModScormScorm, newAttempt: number, lastOnline: number, siteId?: string): Promise<void> { siteId = siteId || CoreSites.getCurrentSiteId(); // Try to get data from online attempts. const userData = await CoreUtils.ignoreErrors( this.searchOnlineAttemptUserData(scorm.id, lastOnline, { cmId: scorm.coursemodule, siteId }), ); if (!userData) { throw new CoreError(Translate.instant('addon.mod_scorm.errorcreateofflineattempt')); } // We're creating a new attempt, remove all the user data that is not needed for a new attempt. for (const scoId in userData) { const sco = userData[scoId]; const filtered: Record<string, AddonModScormDataValue> = {}; for (const element in sco.userdata) { if (element.indexOf('.') == -1 && elementsToIgnore.indexOf(element) == -1) { // The element doesn't use a dot notation, probably SCO data. filtered[element] = sco.userdata[element]; } } sco.userdata = filtered; } return AddonModScormOffline.createNewAttempt(scorm, newAttempt, userData, undefined, siteId); } /** * Determines the attempt to continue/review. It will be: * - The last incomplete online attempt if it hasn't been continued in offline and all offline attempts are complete. * - The attempt with highest number without surpassing max attempts otherwise. * * @param scorm SCORM object. * @param attempts Attempts count. * @param siteId Site ID. If not defined, current site. * @return Promise resolved with the attempt data. */ async determineAttemptToContinue( scorm: AddonModScormScorm, attempts: AddonModScormAttemptCountResult, siteId?: string, ): Promise<AddonModScormAttempt> { let lastOnline: number | undefined; // Get last online attempt. if (attempts.online.length) { lastOnline = Math.max.apply(Math, attempts.online); } if (!lastOnline) { return this.getLastBeforeMax(scorm, attempts); } // Check if last online incomplete. const hasOffline = attempts.offline.indexOf(lastOnline) > -1; const incomplete = await AddonModScorm.isAttemptIncomplete(scorm.id, lastOnline, { offline: hasOffline, cmId: scorm.coursemodule, siteId, }); if (incomplete) { return { num: lastOnline, offline: hasOffline, }; } else { return this.getLastBeforeMax(scorm, attempts); } } /** * Get the first SCO to load in a SCORM: the first valid and incomplete SCO. * * @param scormId Scorm ID. * @param attempt Attempt number. * @param options Other options. * @return Promise resolved with the first SCO. */ async getFirstSco( scormId: number, attempt: number, options: AddonModScormGetFirstScoOptions = {}, ): Promise<AddonModScormScoWithData | undefined> { const mode = options.mode || AddonModScormProvider.MODENORMAL; const isNormalMode = mode === AddonModScormProvider.MODENORMAL; let scos = options.toc; if (!scos || !scos.length) { // SCORM doesn't have a TOC. Get all the scos. scos = await AddonModScorm.getScosWithData(scormId, attempt, options); } // Search the first valid SCO. // In browse/review mode return the first visible sco. In normal mode, first incomplete sco. const sco = scos.find(sco => sco.isvisible && sco.launch && sco.prereq && (!isNormalMode || AddonModScorm.isStatusIncomplete(sco.status))); // If no "valid" SCO, load the first one. In web it loads the first child because the toc contains the organization SCO. return sco || scos[0]; } /** * Get the last attempt (number and whether it's offline). * It'll be the highest number as long as it doesn't surpass the max number of attempts. * * @param scorm SCORM object. * @param attempts Attempts count. * @return Last attempt data. */ protected getLastBeforeMax( scorm: AddonModScormScorm, attempts: AddonModScormAttemptCountResult, ): AddonModScormAttempt { if (scorm.maxattempt && attempts.lastAttempt.num > scorm.maxattempt) { return { num: scorm.maxattempt, offline: attempts.offline.indexOf(scorm.maxattempt) > -1, }; } else { return { num: attempts.lastAttempt.num, offline: attempts.lastAttempt.offline, }; } } /** * Given a TOC in array format and a scoId, return the next available SCO. * * @param toc SCORM's TOC. * @param scoId SCO ID. * @return Next SCO. */ getNextScoFromToc(toc: AddonModScormScoWithData[], scoId: number): AddonModScormScoWithData | undefined { const currentTocIndex = toc.findIndex((item) => item.id == scoId); // We found the current SCO. Now search the next visible SCO with fulfilled prerequisites. for (let j = currentTocIndex + 1; j < toc.length; j++) { if (toc[j].isvisible && toc[j].prereq && toc[j].launch) { return toc[j]; } } } /** * Given a TOC in array format and a scoId, return the previous available SCO. * * @param toc SCORM's TOC. * @param scoId SCO ID. * @return Previous SCO. */ getPreviousScoFromToc(toc: AddonModScormScoWithData[], scoId: number): AddonModScormScoWithData | undefined { const currentTocIndex = toc.findIndex((item) => item.id == scoId); // We found the current SCO. Now let's search the previous visible SCO with fulfilled prerequisites. for (let j = currentTocIndex - 1; j >= 0; j--) { if (toc[j].isvisible && toc[j].prereq && toc[j].launch) { return toc[j]; } } } /** * Given a TOC in array format and a scoId, return the SCO. * * @param toc SCORM's TOC. * @param scoId SCO ID. * @return SCO. */ getScoFromToc(toc: AddonModScormScoWithData[], scoId: number): AddonModScormScoWithData | undefined { return toc.find(sco => sco.id == scoId); } /** * Get SCORM TOC, formatted. * * @param scormId Scorm ID. * @param lastAttempt Last attempt number. * @param incomplete Whether last attempt is incomplete. * @param options Options. * @return Promise resolved with the TOC. */ async getToc( scormId: number, lastAttempt: number, incomplete: boolean, options: AddonModScormGetScosWithDataOptions = {}, ): Promise<AddonModScormTOCScoWithIcon[]> { const toc = await AddonModScorm.getOrganizationToc(scormId, lastAttempt, options); const tocArray = <AddonModScormTOCScoWithIcon[]> AddonModScorm.formatTocToArray(toc); // Get images for each SCO. tocArray.forEach((sco) => { sco.icon = AddonModScorm.getScoStatusIcon(sco, incomplete); }); return tocArray; } /** * Searches user data for an online attempt. If the data can't be retrieved, re-try with the previous online attempt. * * @param scormId SCORM ID. * @param attempt Online attempt to get the data. * @param options Other options. * @return Promise resolved with user data. */ async searchOnlineAttemptUserData( scormId: number, attempt: number, options: CoreCourseCommonModWSOptions = {}, ): Promise<AddonModScormUserDataMap> { options.siteId = options.siteId || CoreSites.getCurrentSiteId(); try { return await AddonModScorm.getScormUserData(scormId, attempt, options); } catch (error) { if (attempt <= 0) { // No more attempts to try. throw error; } try { // We couldn't retrieve the data. Try again with the previous online attempt. return await this.searchOnlineAttemptUserData(scormId, attempt - 1, options); } catch { // Couldn't retrieve previous attempts data either. throw error; } } } } export const AddonModScormHelper = makeSingleton(AddonModScormHelperProvider); /** * Options to pass to getFirstSco. */ export type AddonModScormGetFirstScoOptions = CoreCourseCommonModWSOptions & { toc?: AddonModScormScoWithData[]; // SCORM's TOC. If not provided, it will be calculated. organization?: string; // Organization to use. mode?: string; // Mode. offline?: boolean; // Whether the attempt is offline. }; /** * TOC SCO with icon. */ export type AddonModScormTOCScoWithIcon = AddonModScormTOCListSco & { icon?: AddonModScormScoIcon; };
the_stack
* Unit tests for recurrent.ts. */ import * as tfc from '@tensorflow/tfjs-core'; import {randomNormal, Scalar, scalar, Tensor, tensor1d, tensor2d, tensor3d, tensor4d} from '@tensorflow/tfjs-core'; import * as K from '../backend/tfjs_backend'; import * as tfl from '../index'; import {ActivationIdentifier} from '../keras_format/activation_config'; import {ModelAndWeightsConfig, modelFromJSON} from '../models'; import {Kwargs} from '../types'; import {convertPythonicToTs, convertTsToPythonic} from '../utils/serialization_utils'; import {describeMathCPU, describeMathCPUAndGPU, describeMathGPU, expectTensorsClose} from '../utils/test_utils'; import {GRU, LSTM, rnn, RNN, RNNCell} from './recurrent'; /** * A simplistic RNN step function for testing. * This step function simply * - calculates a reduced mean over all input elements, for each sample. * - adds that mean to the state tensor(s), * - take the negative of the 1st current state tensor and use it as the * output. * @param inputs * @param states */ function rnnStepForTest(inputs: Tensor, states: Tensor[]): [Tensor, Tensor[]] { const mean = tfc.mean(inputs) as Scalar; const newStates = states.map(state => tfc.add(mean, state)); const output = tfc.neg(newStates[0]); return [output, newStates]; } describeMathCPUAndGPU('rnn', () => { it('Simple step function: 3D inputs, 1 state', () => { const inputs = tensor3d( [[[1, 2], [3, 4], [5, 6]], [[10, 20], [30, 40], [50, 60]]], [2, 3, 2]); const initialStates = [tfc.zeros([2, 4])]; const rnnOutputs = rnn( rnnStepForTest, inputs, initialStates, false /* goBackwards */, null /* mask */, null /* constants */, false /* unroll */, true /* needPerStepOutputs */); const lastOutput = rnnOutputs[0]; const outputs = rnnOutputs[1]; const newStates = rnnOutputs[2]; expectTensorsClose( lastOutput, tensor2d( [ [-57.75, -57.75, -57.75, -57.75], [-57.75, -57.75, -57.75, -57.75] ], [2, 4])); expectTensorsClose( outputs, tensor3d( [ [ [-8.25, -8.25, -8.25, -8.25], [-27.5, -27.5, -27.5, -27.5], [-57.75, -57.75, -57.75, -57.75] ], [ [-8.25, -8.25, -8.25, -8.25], [-27.5, -27.5, -27.5, -27.5], [-57.75, -57.75, -57.75, -57.75] ] ], [2, 3, 4])); expect(newStates.length).toEqual(1); expectTensorsClose( newStates[0], tensor2d( [[57.75, 57.75, 57.75, 57.75], [57.75, 57.75, 57.75, 57.75]], [2, 4])); }); it('Simple step function: 3D inputs, 2 states', () => { const inputs = tensor3d( [[[1, 2], [3, 4], [5, 6]], [[10, 20], [30, 40], [50, 60]]], [2, 3, 2]); // The two state tensors have different shapes. const initialStates = [tfc.zeros([2, 4]), tfc.ones([2, 3])]; const rnnOutputs = rnn( rnnStepForTest, inputs, initialStates, false /* goBackwards */, null /* mask */, null /* constants */, false /* unroll */, true /* needPerStepOutputs */); const lastOutput = rnnOutputs[0]; const outputs = rnnOutputs[1]; const newStates = rnnOutputs[2]; expectTensorsClose( lastOutput, tensor2d( [ [-57.75, -57.75, -57.75, -57.75], [-57.75, -57.75, -57.75, -57.75] ], [2, 4])); expectTensorsClose( outputs, tensor3d( [ [ [-8.25, -8.25, -8.25, -8.25], [-27.5, -27.5, -27.5, -27.5], [-57.75, -57.75, -57.75, -57.75] ], [ [-8.25, -8.25, -8.25, -8.25], [-27.5, -27.5, -27.5, -27.5], [-57.75, -57.75, -57.75, -57.75] ] ], [2, 3, 4])); expect(newStates.length).toEqual(2); expectTensorsClose( newStates[0], tensor2d( [[57.75, 57.75, 57.75, 57.75], [57.75, 57.75, 57.75, 57.75]], [2, 4])); expectTensorsClose( newStates[1], tensor2d([[58.75, 58.75, 58.75], [58.75, 58.75, 58.75]], [2, 3])); }); it('Simple step function: 4D inputs, 2 states', () => { const inputs = tensor4d( [ [[[1], [2]], [[3], [4]], [[5], [6]]], [[[10], [20]], [[30], [40]], [[50], [60]]] ], [2, 3, 2, 1]); // The two state tensors have different shapes. const initialStates = [tfc.zeros([2, 4]), tfc.ones([2, 3])]; const rnnOutputs = rnn( rnnStepForTest, inputs, initialStates, false /* goBackwards */, null /* mask */, null /* constants */, false /* unroll */, true /* needPerStepOutputs */); const lastOutput = rnnOutputs[0]; const outputs = rnnOutputs[1]; const newStates = rnnOutputs[2]; expectTensorsClose( lastOutput, tensor2d( [ [-57.75, -57.75, -57.75, -57.75], [-57.75, -57.75, -57.75, -57.75] ], [2, 4])); expectTensorsClose( outputs, tensor3d( [ [ [-8.25, -8.25, -8.25, -8.25], [-27.5, -27.5, -27.5, -27.5], [-57.75, -57.75, -57.75, -57.75] ], [ [-8.25, -8.25, -8.25, -8.25], [-27.5, -27.5, -27.5, -27.5], [-57.75, -57.75, -57.75, -57.75] ] ], [2, 3, 4])); expect(newStates.length).toEqual(2); expectTensorsClose( newStates[0], tensor2d( [[57.75, 57.75, 57.75, 57.75], [57.75, 57.75, 57.75, 57.75]], [2, 4])); expectTensorsClose( newStates[1], tensor2d([[58.75, 58.75, 58.75], [58.75, 58.75, 58.75]], [2, 3])); }); it('Using inputs <3D leads to ValueError', () => { const inputs = tensor2d([[1, 2], [3, 4]], [2, 2]); const initialStates = [tfc.zeros([4]), tfc.ones([3])]; expect(() => rnn(rnnStepForTest, inputs, initialStates)).toThrowError(); }); }); /** * A simplistic RNNCell for testing. * * This RNNCell performs the following with the inputs and states. * - calculates a reduced mean over all input elements, * - adds that mean to the state tensor(s), * - take the negative of the 1st current state tensor and use it as the * output. */ class RNNCellForTest extends RNNCell { /** @nocollapse */ static className = 'RNNCellForTest'; constructor(stateSizes: number|number[]) { super({}); this.stateSize = stateSizes; } call(inputs: Tensor|Tensor[], kwargs: Kwargs): Tensor|Tensor[] { inputs = inputs as Tensor[]; const dataInputs = inputs[0]; const states = inputs.slice(1); const mean = tfc.mean(dataInputs) as Scalar; const newStates = states.map(state => tfc.add(mean, state)); const output = tfc.neg(newStates[0]); return [output].concat(newStates); } } describeMathCPU('RNN-Layer', () => { // TODO(cais): Add tests for stacked RNN cell (i.e., multiple cells) once it // implemented. // TODO(cais): Add tests for masks once implemented. // TODO(cais): Add tests for constants once implemented. it('constructor: only cell', () => { const cell = new RNNCellForTest(5); const rnn = tfl.layers.rnn({cell}) as RNN; expect(rnn.returnSequences).toEqual(false); expect(rnn.returnState).toEqual(false); expect(rnn.goBackwards).toEqual(false); }); it('constructor: cell and custom options', () => { const cell = new RNNCellForTest(5); const rnn = tfl.layers.rnn({ cell, returnSequences: true, returnState: true, goBackwards: true }) as RNN; expect(rnn.returnSequences).toEqual(true); expect(rnn.returnState).toEqual(true); expect(rnn.goBackwards).toEqual(true); }); it('computeOutputShape: 1 state, returnSequences=false, returnState=false', () => { const cell = new RNNCellForTest(5); const rnn = tfl.layers.rnn({cell}); const inputShape = [4, 3, 2]; expect(rnn.computeOutputShape(inputShape)).toEqual([4, 5]); }); it('computeOutputShape: 1 state, returnSequences=true, returnState=false', () => { const cell = new RNNCellForTest([5, 6]); const rnn = tfl.layers.rnn({cell, returnSequences: true}); const inputShape = [4, 3, 2]; expect(rnn.computeOutputShape(inputShape)).toEqual([4, 3, 5]); }); it('computeOutputShape: 1 state, returnSequences=true, returnState=true', () => { const cell = new RNNCellForTest(6); const rnn = tfl.layers.rnn({cell, returnSequences: true, returnState: true}); const inputShape = [4, 3, 2]; expect(rnn.computeOutputShape(inputShape)).toEqual([[4, 3, 6], [4, 6]]); }); it('computeOutputShape: 2 states, returnSequences=true, returnState=true', () => { const cell = new RNNCellForTest([5, 6]); const rnn = tfl.layers.rnn({cell, returnSequences: true, returnState: true}); const inputShape = [4, 3, 2]; expect(rnn.computeOutputShape(inputShape)).toEqual([ [4, 3, 5], [4, 5], [4, 6] ]); }); it('apply: Symbolic: 1 state, returnSequences=false, returnState=false', () => { const cell = new RNNCellForTest(6); const rnn = tfl.layers.rnn({cell}); const input = new tfl.SymbolicTensor('float32', [16, 10, 8], null, [], null); const output = rnn.apply(input) as tfl.SymbolicTensor; expect(output.shape).toEqual([16, 6]); }); it('apply: Symbolic: 1 state, returnSequences=true, returnState=false', () => { const cell = new RNNCellForTest(6); const rnn = tfl.layers.rnn({cell, returnSequences: true}); const input = new tfl.SymbolicTensor('float32', [16, 10, 8], null, [], null); const output = rnn.apply(input) as tfl.SymbolicTensor; expect(output.shape).toEqual([16, 10, 6]); }); it('apply: Symbolic: 1 state, returnSequences=true, returnState=true', () => { const cell = new RNNCellForTest(6); const rnn = tfl.layers.rnn({cell, returnSequences: true, returnState: true}); const input = new tfl.SymbolicTensor('float32', [16, 10, 8], null, [], null); const output = rnn.apply(input) as tfl.SymbolicTensor[]; expect(output.length).toEqual(2); expect(output[0].shape).toEqual([16, 10, 6]); expect(output[1].shape).toEqual([16, 6]); }); it('apply: Symbolic: 1 state, returnSequences=false, returnState=true', () => { const cell = new RNNCellForTest(6); const rnn = tfl.layers.rnn({cell, returnSequences: false, returnState: true}); const input = new tfl.SymbolicTensor('float32', [16, 10, 8], null, [], null); const output = rnn.apply(input) as tfl.SymbolicTensor[]; expect(output.length).toEqual(2); expect(output[0].shape).toEqual([16, 6]); expect(output[1].shape).toEqual([16, 6]); }); it('apply: Symbolic: 2 states, returnSequences=true, returnState=true', () => { const cell = new RNNCellForTest([5, 6]); const rnn = tfl.layers.rnn({cell, returnSequences: true, returnState: true}); const input = new tfl.SymbolicTensor('float32', [16, 10, 8], null, [], null); const output = rnn.apply(input) as tfl.SymbolicTensor[]; expect(output.length).toEqual(3); expect(output[0].shape).toEqual([16, 10, 5]); expect(output[1].shape).toEqual([16, 5]); expect(output[2].shape).toEqual([16, 6]); }); }); describeMathCPUAndGPU('RNN-Layer-Math', () => { it('getInitialState: 1 state', () => { const cell = new RNNCellForTest(5); const inputs = tfc.zeros([4, 3, 2]); const rnn = tfl.layers.rnn({cell}) as RNN; const initialStates = rnn.getInitialState(inputs); expect(initialStates.length).toEqual(1); expectTensorsClose(initialStates[0], tfc.zeros([4, 5])); }); it('getInitialState: 2 states', () => { const cell = new RNNCellForTest([5, 6]); const inputs = tfc.zeros([4, 3, 2]); const rnn = tfl.layers.rnn({cell}) as RNN; const initialStates = rnn.getInitialState(inputs); expect(initialStates.length).toEqual(2); expectTensorsClose(initialStates[0], tfc.zeros([4, 5])); expectTensorsClose(initialStates[1], tfc.zeros([4, 6])); }); it('call: 1 state: returnSequences=false, returnState=false', () => { const cell = new RNNCellForTest(4); const rnn = tfl.layers.rnn({cell}); const inputs = tensor3d( [[[1, 2], [3, 4], [5, 6]], [[10, 20], [30, 40], [50, 60]]], [2, 3, 2]); const outputs = rnn.apply(inputs) as Tensor; expectTensorsClose( outputs, tfc.mul(scalar(-57.75), tfc.ones([2, 4]))); }); it('apply: 1 state: returnSequences=true, returnState=false', () => { const cell = new RNNCellForTest(3); const rnn = tfl.layers.rnn({cell, returnSequences: true}); const inputs = tensor3d( [[[1, 2], [3, 4], [5, 6]], [[10, 20], [30, 40], [50, 60]]], [2, 3, 2]); const outputs = rnn.apply(inputs) as Tensor; expectTensorsClose( outputs, tensor3d( [ [ [-8.25, -8.25, -8.25], [-27.5, -27.5, -27.5], [-57.75, -57.75, -57.75] ], [ [-8.25, -8.25, -8.25], [-27.5, -27.5, -27.5], [-57.75, -57.75, -57.75] ], ], [2, 3, 3])); }); it('apply: 1 state: returnSequences=true, returnState=true', () => { const cell = new RNNCellForTest(3); const rnn = tfl.layers.rnn({cell, returnSequences: true, returnState: true}); const inputs = tensor3d( [[[1, 2], [3, 4], [5, 6]], [[10, 20], [30, 40], [50, 60]]], [2, 3, 2]); const outputs = rnn.apply(inputs) as Tensor[]; expect(outputs.length).toEqual(2); expectTensorsClose( outputs[0], tensor3d( [ [ [-8.25, -8.25, -8.25], [-27.5, -27.5, -27.5], [-57.75, -57.75, -57.75] ], [ [-8.25, -8.25, -8.25], [-27.5, -27.5, -27.5], [-57.75, -57.75, -57.75] ], ], [2, 3, 3])); expectTensorsClose( outputs[1], tensor2d([[57.75, 57.75, 57.75], [57.75, 57.75, 57.75]], [2, 3])); }); it('apply: 2 states: returnSequences=true, returnState=true', () => { const cell = new RNNCellForTest([3, 4]); const rnn = tfl.layers.rnn({cell, returnSequences: true, returnState: true}); const inputs = tensor3d( [[[1, 2], [3, 4], [5, 6]], [[10, 20], [30, 40], [50, 60]]], [2, 3, 2]); const outputs = rnn.apply(inputs) as Tensor[]; expect(outputs.length).toEqual(3); expectTensorsClose( outputs[0], tensor3d( [ [ [-8.25, -8.25, -8.25], [-27.5, -27.5, -27.5], [-57.75, -57.75, -57.75] ], [ [-8.25, -8.25, -8.25], [-27.5, -27.5, -27.5], [-57.75, -57.75, -57.75] ], ], [2, 3, 3])); expectTensorsClose( outputs[1], tensor2d([[57.75, 57.75, 57.75], [57.75, 57.75, 57.75]], [2, 3])); expectTensorsClose( outputs[2], tensor2d( [[57.75, 57.75, 57.75, 57.75], [57.75, 57.75, 57.75, 57.75]], [2, 4])); }); it('call: with 1 initialState', () => { const cell = new RNNCellForTest(4); const rnn = tfl.layers.rnn({cell}); const inputs = tensor3d( [[[1, 2], [3, 4], [5, 6]], [[10, 20], [30, 40], [50, 60]]], [2, 3, 2]); const outputs = rnn.apply(inputs, {'initialState': [tfc.ones([2, 4])]}) as Tensor; expectTensorsClose( outputs, tfc.mul(scalar(-58.75), tfc.ones([2, 4]))); }); it('call: with 2 initialStates', () => { const cell = new RNNCellForTest([4, 5]); const rnn = tfl.layers.rnn({cell, returnState: true}); const inputs = tensor3d( [[[1, 2], [3, 4], [5, 6]], [[10, 20], [30, 40], [50, 60]]], [2, 3, 2]); const outputs = rnn.apply(inputs, { 'initialState': [ tfc.ones([2, 4]), tfc.mul(scalar(2), tfc.ones([2, 5])) ] }) as Tensor[]; expect(outputs.length).toEqual(3); expectTensorsClose( outputs[0], tfc.mul(scalar(-58.75), tfc.ones([2, 4]))); expectTensorsClose( outputs[1], tfc.mul(scalar(58.75), tfc.ones([2, 4]))); expectTensorsClose( outputs[2], tfc.mul(scalar(59.75), tfc.ones([2, 5]))); }); it('call with incorrect number of initialStates leads to ValueError', () => { const cell = new RNNCellForTest([4, 5]); const rnn = tfl.layers.rnn({cell, returnState: true}); const inputs = tensor3d( [[[1, 2], [3, 4], [5, 6]], [[10, 20], [30, 40], [50, 60]]], [2, 3, 2]); expect(() => rnn.apply(inputs, { 'initialState': [tfc.ones([2, 4])] })).toThrowError(/An initialState was passed that is not compatible with/); }); }); describeMathCPU('SimpleRNN Symbolic', () => { it('returnSequences=false, returnState=false', () => { const input = new tfl.SymbolicTensor('float32', [9, 10, 8], null, [], null); const simpleRNN = tfl.layers.simpleRNN({units: 5}); const output = simpleRNN.apply(input) as tfl.SymbolicTensor; expect(output.shape).toEqual([9, 5]); }); it('returnSequences=false, returnState=true', () => { const input = new tfl.SymbolicTensor('float32', [9, 10, 8], null, [], null); const simpleRNN = tfl.layers.simpleRNN({units: 5, returnState: true}); const output = simpleRNN.apply(input) as tfl.SymbolicTensor[]; expect(output.length).toEqual(2); expect(output[0].shape).toEqual([9, 5]); expect(output[1].shape).toEqual([9, 5]); }); it('returnSequences=true, returnState=false', () => { const input = new tfl.SymbolicTensor('float32', [9, 10, 8], null, [], null); const simpleRNN = tfl.layers.simpleRNN({units: 5, returnSequences: true}); const output = simpleRNN.apply(input) as tfl.SymbolicTensor; expect(output.shape).toEqual([9, 10, 5]); }); it('returnSequences=true, returnState=true', () => { const input = new tfl.SymbolicTensor('float32', [9, 10, 8], null, [], null); const simpleRNN = tfl.layers.simpleRNN({ units: 5, returnSequences: true, returnState: true, }); const output = simpleRNN.apply(input) as tfl.SymbolicTensor[]; expect(output.length).toEqual(2); expect(output[0].shape).toEqual([9, 10, 5]); expect(output[1].shape).toEqual([9, 5]); }); it('Serialization round trip', () => { const layer = tfl.layers.simpleRNN({units: 4}); const pythonicConfig = convertTsToPythonic(layer.getConfig()); // tslint:disable-next-line:no-any const tsConfig = convertPythonicToTs(pythonicConfig) as any; const layerPrime = tfl.layers.simpleRNN(tsConfig); expect(layerPrime.getConfig().units).toEqual(4); }); it('Invalid units leads to Error', () => { expect(() => tfl.layers.simpleRNN({units: 12.5})) .toThrowError(/units.*positive integer.*12\.5\.$/); expect(() => tfl.layers.simpleRNN({units: 0})) .toThrowError(/units.*positive integer.*0\.$/); expect(() => tfl.layers.simpleRNN({units: -25})) .toThrowError(/units.*positive integer.*-25\.$/); }); }); describeMathCPUAndGPU('SimpleRNN Tensor', () => { const units = 5; const batchSize = 4; const inputSize = 2; // TODO(cais): Add test for the default recurrent initializer ('Orthogonal') // when it becomes available. const dropouts = [0.0, 0.1]; const trainings = [true, false]; for (const training of trainings) { for (const dropout of dropouts) { const testTitle = `returnSequences=false, returnState=false, useBias=true,` + ` ${training}, dropout=${dropout}`; it(testTitle, () => { const timeSteps = 3; const simpleRNN = tfl.layers.simpleRNN({ units, kernelInitializer: 'ones', recurrentInitializer: 'ones', biasInitializer: 'ones', dropout, }); const kwargs:Kwargs = {}; if (training) { kwargs['training'] = true; } const input = tfc.ones([batchSize, timeSteps, inputSize]); spyOn(tfc, 'dropout').and.callThrough(); let numTensors = 0; for (let i = 0; i < 2; i++){ tfc.dispose(simpleRNN.apply(input, kwargs) as Tensor); if (dropout !== 0.0 && training) { expect(tfc.dropout).toHaveBeenCalledTimes(1 * (i + 1)); } else { expect(tfc.dropout).toHaveBeenCalledTimes(0); } if (i === 0) { numTensors = tfc.memory().numTensors; } else { expect(tfc.memory().numTensors).toEqual(numTensors); } } }); } } const recurrentDropouts = [0.0, 0.1]; for (const training of trainings) { for (const recurrentDropout of recurrentDropouts) { const testTitle = `returnSequences=false, returnState=false, useBias=true,` + ` ${training}, recurrentDropout=${recurrentDropout}`; it(testTitle, () => { const timeSteps = 3; const simpleRNN = tfl.layers.simpleRNN({ units, kernelInitializer: 'ones', recurrentInitializer: 'ones', biasInitializer: 'ones', recurrentDropout, }); const kwargs:Kwargs = {}; if (training) { kwargs['training'] = true; } const input = tfc.ones([batchSize, timeSteps, inputSize]); spyOn(tfc, 'dropout').and.callThrough(); let numTensors = 0; for (let i = 0; i < 2; i++){ tfc.dispose(simpleRNN.apply(input, kwargs) as Tensor); if (recurrentDropout !== 0.0 && training) { expect(tfc.dropout).toHaveBeenCalledTimes(1 * (i + 1)); } else { expect(tfc.dropout).toHaveBeenCalledTimes(0); } if (i === 0) { numTensors = tfc.memory().numTensors; } else { expect(tfc.memory().numTensors).toEqual(numTensors); } } }); } } const activations : ActivationIdentifier[] = ['linear', 'tanh']; for (const activation of activations) { const testTitle = `returnSequences=false, returnState=false, useBias=true, ${activation}`; it(testTitle, () => { const timeSteps = 1; const simpleRNN = tfl.layers.simpleRNN({ units, kernelInitializer: 'ones', recurrentInitializer: 'ones', biasInitializer: 'ones', activation }); const input = tfc.ones([batchSize, timeSteps, inputSize]); const output = simpleRNN.apply(input) as Tensor; let expectedElementValue = inputSize + 1; if (activation === 'tanh') { expectedElementValue = Math.tanh(expectedElementValue); } expectTensorsClose( output, tfc.mul( scalar(expectedElementValue), tfc.ones([batchSize, units]))); }); } const returnStateValues = [false, true]; for (const returnState of returnStateValues) { const testTitle = `returnSequences=true, ` + `returnState=${returnState}, useBias=true, linear`; it(testTitle, () => { const timeSteps = 2; const simpleRNN = tfl.layers.simpleRNN({ units, returnSequences: true, returnState, kernelInitializer: 'ones', recurrentInitializer: 'ones', biasInitializer: 'ones', activation: 'linear' }); const input = tfc.ones([batchSize, timeSteps, inputSize]); let output = simpleRNN.apply(input); let finalState: Tensor; if (returnState) { output = output as Tensor[]; expect(output.length).toEqual(2); finalState = output[1]; output = output[0]; } else { output = output as Tensor; } expect(output.shape).toEqual([batchSize, timeSteps, units]); const timeMajorOutput = tfc.transpose(output, [1, 0, 2]); const outputT0 = K.sliceAlongFirstAxis(timeMajorOutput, 0, 1); const outputT1 = K.sliceAlongFirstAxis(timeMajorOutput, 1, 1); expectTensorsClose( outputT0, tfc.mul( scalar(inputSize + 1), tfc.ones([1, batchSize, units]))); expectTensorsClose( outputT1, tfc.mul( scalar((inputSize + 1) * (units + 1)), tfc.ones([1, batchSize, units]))); if (returnState) { expectTensorsClose(finalState, outputT1.reshape([batchSize, units])); } }); it('stateful missing batchInputShape leads to error' , () => { const sequenceLength = 3; const simpleRNN = tfl.layers.simpleRNN({ units, kernelInitializer: 'ones', recurrentInitializer: 'ones', biasInitializer: 'zeros', activation: 'linear', stateful: true, inputShape: [sequenceLength, inputSize] }) as RNN; const model = tfl.sequential(); expect(() => model.add(simpleRNN)).toThrowError( /needs to know its batch size/); }); // The reference values below can be obtained with PyKeras code: // ```python // import keras // import numpy as np // // units = 5 // batch_size = 4 // input_size = 2 // sequence_length = 3 // // rnn = keras.layers.SimpleRNN(units, // kernel_initializer='ones', // recurrent_initializer='ones', // bias_initializer='zeros', // activation='linear', // stateful=True, // batch_input_shape=[batch_size, // sequence_length, // input_size]) // // x = np.ones([batch_size, sequence_length, input_size]) // // model = keras.Sequential() // model.add(rnn) // print(model.predict(x)) // print(model.predict(x)) // model.reset_states() // print(model.predict(x)) // print(model.predict(x)) // ``` it('stateful forward: only RNN layer', async () => { const sequenceLength = 3; const rnn = tfl.layers.simpleRNN({ units, kernelInitializer: 'ones', recurrentInitializer: 'ones', biasInitializer: 'zeros', activation: 'linear', stateful: true, batchInputShape: [batchSize, sequenceLength, inputSize] }); const model = tfl.sequential(); model.add(rnn); const x = tfc.ones([batchSize, sequenceLength, inputSize]); const scalar1 = tfc.scalar(62); const scalar2 = tfc.scalar(7812); let y1 = model.predict(x) as Tensor; expect(y1.kept).toBe(false); let y1Expected = tfc.tidy(() => tfc.ones([batchSize, units]).mul(scalar1)); expectTensorsClose(y1, y1Expected); let y2 = model.predict(x) as Tensor; expect(y2.kept).toBe(false); // Future predicts should not dispose previous outputs. expect(y1.isDisposed).toBe(false); let y2Expected = tfc.tidy(() => tfc.ones([batchSize, units]).mul(scalar2)); expectTensorsClose(y2, y2Expected); tfc.dispose([y1, y2, y1Expected, y2Expected]); model.resetStates(); const numTensors0 = tfc.memory().numTensors; y1 = model.predict(x) as Tensor; expect(y1.kept).toBe(false); y1Expected = tfc.tidy(() => tfc.ones([batchSize, units]).mul(scalar1)); expectTensorsClose(y1, y1Expected); y2 = model.predict(x) as Tensor; expect(y2.kept).toBe(false); // Future predicts should not dispose previous outputs. expect(y1.isDisposed).toBe(false); y2Expected = tfc.tidy(() => tfc.ones([batchSize, units]).mul(scalar2)); expectTensorsClose(y2, y2Expected); tfc.dispose([y1, y2, y1Expected, y2Expected]); // Assert no memory leak, even without resetStates() being called. expect(tfc.memory().numTensors).toEqual(numTensors0); }); } // Reference Python code: // ```py // import numpy as np // from tensorflow import keras // // model = keras.Sequential() // model.add(keras.layers.SimpleRNN( // units=5, // kernel_initializer='ones', // recurrent_initializer='ones', // bias_initializer='zeros', // activation='linear', // stateful=True, // batch_input_shape=[4, 3, 2])) // model.add(keras.layers.Dense(units=1, kernel_initializer='ones')) // model.compile(loss='mean_squared_error', optimizer='sgd') // model.summary() // // xs = np.ones([4, 3, 2]) // y1 = model.predict(xs) // print(y1) // y2 = model.predict(xs) // print(y2) // // history = model.fit(xs, ys, batch_size=4, epochs=3) // print(history.history) // ``` it('stateful forward: RNN and dense layers', async () => { const sequenceLength = 3; const model = tfl.sequential(); model.add(tfl.layers.simpleRNN({ units, kernelInitializer: 'ones', recurrentInitializer: 'ones', biasInitializer: 'zeros', activation: 'linear', stateful: true, batchInputShape: [batchSize, sequenceLength, inputSize] })); model.add(tfl.layers.dense({ units: 1, kernelInitializer: 'ones' })); model.compile({loss: 'meanSquaredError', optimizer: 'sgd'}); const xs = tfc.ones([batchSize, sequenceLength, inputSize]); const ys = tfc.ones([batchSize, 1]); let y1: Tensor; let y2: Tensor; tfc.tidy(() => { y1 = model.predict(xs) as Tensor; expectTensorsClose(y1, tfc.tensor2d([310, 310, 310, 310], [4, 1])); y2 = model.predict(xs) as Tensor; expectTensorsClose( y2, tfc.tensor2d([39060, 39060, 39060, 39060], [4, 1])); }); model.resetStates(); const numTensors0 = tfc.memory().numTensors; tfc.tidy(() => { y1 = model.predict(xs) as Tensor; expect(y1.shape).toEqual([batchSize, 1]); expectTensorsClose(y1, tfc.tensor2d([310, 310, 310, 310], [4, 1])); y2 = model.predict(xs) as Tensor; expectTensorsClose( y2, tfc.tensor2d([39060, 39060, 39060, 39060], [4, 1])); }); // Assert no memory leak, even without resetStates() being called. expect(tfc.memory().numTensors).toEqual(numTensors0); const history = await model.fit(xs, ys, {epochs: 1, batchSize: 4}); expect(history.history.loss[0]).toBeCloseTo(23841822736384); }); it('computeMask: returnSequence = false, returnState = false', () => { const sequenceLength = 3; const rnn = tfl.layers.simpleRNN({ units, returnSequences: false, returnState: false, batchInputShape: [batchSize, sequenceLength, inputSize] }); const x = tfc.ones([batchSize, sequenceLength, inputSize]); const m = tfc.ones([sequenceLength, 1]); const mask = rnn.computeMask(x, m); expect(mask).toBeNull(); }); it('computeMask: returnSequence = true, returnState = false', () => { const sequenceLength = 3; const rnn = tfl.layers.simpleRNN({ units, returnSequences: true, returnState: false, batchInputShape: [batchSize, sequenceLength, inputSize] }); const x = tfc.ones([batchSize, sequenceLength, inputSize]); const m = tfc.ones([sequenceLength, 1]); const mask = rnn.computeMask(x, m) as Tensor; expectTensorsClose(mask, m); }); it('computeMask: returnSequence = true, returnState = true', () => { const sequenceLength = 3; const rnn = tfl.layers.simpleRNN({ units, returnSequences: true, returnState: true, stateful: true, batchInputShape: [batchSize, sequenceLength, inputSize] }); const x = tfc.ones([batchSize, sequenceLength, inputSize]); rnn.apply(x); rnn.resetStates(); // Let the RNN layer object construct its state first. const m = tfc.ones([sequenceLength, 1]); const masks = rnn.computeMask(x, m) as Tensor[]; expect(masks.length).toEqual(2); expectTensorsClose(masks[0], m); expect(masks[1]).toBeNull(); }); // The reference values can be obtained with the following PyKeras code: // ```python // import keras // import numpy as np // // batch_size = 4 // sequence_length = 3 // input_size = 2 // // model = keras.Sequential() // model.add(keras.layers.SimpleRNN( // units=5, // batch_input_shape=[batch_size, sequence_length, input_size], // kernel_initializer='ones', // recurrent_initializer='ones', // bias_initializer='zeros', // stateful=True)) // model.add(keras.layers.Dense(1, // kernel_initializer='zeros', // use_bias=False)) // model.compile(loss='mean_squared_error', optimizer='sgd') // // xs_1 = np.ones([batch_size, sequence_length, input_size]) // xs_2 = np.zeros([batch_size, sequence_length, input_size]) // xs = np.concatenate([xs_1, xs_2], 0) // ys = np.array([[-1], [-2], [0], [1], [1], [2], [0], [-1]]) // // history = model.fit(xs, ys, batch_size=batch_size, shuffle=False) // print(history.history) // ``` it('stateful BPTT', async () => { const sequenceLength = 3; const model = tfl.sequential(); model.add(tfl.layers.simpleRNN({ units, kernelInitializer: 'ones', recurrentInitializer: 'ones', biasInitializer: 'zeros', stateful: true, batchInputShape: [batchSize, sequenceLength, inputSize] })); model.add(tfl.layers.dense({ units: 1, kernelInitializer: 'zeros', useBias: false })); model.compile({loss: 'meanSquaredError', optimizer: 'sgd'}); const xs1 = tfc.ones([batchSize, sequenceLength, inputSize]); const xs2 = tfc.ones([batchSize, sequenceLength, inputSize]); const xs = tfc.concat([xs1, xs2], 0); const ys = tfc.tensor2d([[-1], [-2], [0], [1], [1], [2], [0], [-1]]); const history = await model.fit(xs, ys, {batchSize, shuffle: false}); // See code snippet above for the code used to obtain this loss value. expect(history.history.loss[0]).toBeCloseTo(1.5262475); }); it('BPTT', async () => { // The following golden values for assertion can be obtained with the // following Python Keras code. // ```python // import keras // import numpy as np // // sequence_length = 3 // input_size = 4 // batch_size = 5 // // t_input = keras.Input([sequence_length, input_size]) // simple_rnn = keras.layers.SimpleRNN(1, // kernel_initializer='ones', // recurrent_initializer='ones', // use_bias=False) // dense = keras.layers.Dense(1, // kernel_initializer='ones', // use_bias=False) // output = dense(simple_rnn(t_input)) // model = keras.Model(t_input, output) // optimizer = keras.optimizers.SGD(5) // model.compile(optimizer=optimizer, loss='mean_squared_error') // // x = np.ones([batch_size, sequence_length, input_size]) // y = np.zeros([batch_size, 1]) // model.fit(x, y, batch_size=batch_size, epochs=2) // print(simple_rnn.get_weights()[0]) // print(simple_rnn.get_weights()[1]) // print(dense.get_weights()[0]) // ``` const sequenceLength = 3; const inputSize = 4; const batchSize = 5; const model = tfl.sequential(); model.add(tfl.layers.simpleRNN({ units: 1, kernelInitializer: 'ones', recurrentInitializer: 'ones', useBias: false, inputShape: [sequenceLength, inputSize], })); model.add(tfl.layers.dense({ units: 1, kernelInitializer: 'ones', useBias: false, })); const x = tfc.ones([batchSize, sequenceLength, inputSize]); const y = tfc.zeros([batchSize, 1]); const sgd = tfc.train.sgd(5); model.compile({loss: 'meanSquaredError', optimizer: sgd}); await model.fit(x, y, {epochs: 2}); expectTensorsClose( model.layers[0].getWeights()[0], tfc.mul(scalar(0.8484658), tfc.ones([4, 1]))); expectTensorsClose( model.layers[0].getWeights()[1], tfc.mul(scalar(0.8484799), tfc.ones([1, 1]))); expectTensorsClose( model.layers[1].getWeights()[0], tfc.mul(scalar(80.967026), tfc.ones([1, 1]))); }); }); describeMathCPU('GRU Symbolic', () => { it('returnSequences=false, returnState=false', () => { const input = new tfl.SymbolicTensor('float32', [9, 10, 8], null, [], null); const gru = tfl.layers.gru({units: 5}); const output = gru.apply(input) as tfl.SymbolicTensor; expect(output.shape).toEqual([9, 5]); }); it('returnSequences=false, returnState=true', () => { const input = new tfl.SymbolicTensor('float32', [9, 10, 8], null, [], null); const gru = tfl.layers.gru({units: 5, returnState: true}); const output = gru.apply(input) as tfl.SymbolicTensor[]; expect(output.length).toEqual(2); expect(output[0].shape).toEqual([9, 5]); expect(output[1].shape).toEqual([9, 5]); }); it('returnSequences=true, returnState=false', () => { const input = new tfl.SymbolicTensor('float32', [9, 10, 8], null, [], null); const gru = tfl.layers.gru({units: 5, returnSequences: true}); const output = gru.apply(input) as tfl.SymbolicTensor; expect(output.shape).toEqual([9, 10, 5]); }); it('returnSequences=true, returnState=true', () => { const input = new tfl.SymbolicTensor('float32', [9, 10, 8], null, [], null); const gru = tfl.layers.gru({ units: 5, returnSequences: true, returnState: true, }); const output = gru.apply(input) as tfl.SymbolicTensor[]; expect(output.length).toEqual(2); expect(output[0].shape).toEqual([9, 10, 5]); expect(output[1].shape).toEqual([9, 5]); }); it('trainableWeights, nonTrainableWeights and weights give correct outputs', () => { const input = new tfl.SymbolicTensor('float32', [2, 3, 4], null, [], null); const gru = tfl.layers.gru({units: 5, returnState: true}); gru.apply(input); expect(gru.trainable).toEqual(true); // Trainable weights: kernel, recurrent kernel and bias. expect(gru.trainableWeights.length).toEqual(3); expect(gru.nonTrainableWeights.length).toEqual(0); expect(gru.weights.length).toEqual(3); }); for (const implementation of [1, 2]) { it('Serialization round trip', () => { const layer = tfl.layers.gru({units: 4, implementation}); const pythonicConfig = convertTsToPythonic(layer.getConfig()); // tslint:disable-next-line:no-any const tsConfig = convertPythonicToTs(pythonicConfig) as any; const layerPrime = tfl.layers.gru(tsConfig); expect(layerPrime.getConfig().units).toEqual(4); expect(layerPrime.getConfig().implementation).toEqual(implementation); }); } it('Invalid units leads to Error', () => { expect(() => tfl.layers.gru({units: 12.5})) .toThrowError(/units.*positive integer.*12\.5\.$/); expect(() => tfl.layers.gru({units: 0})) .toThrowError(/units.*positive integer.*0\.$/); expect(() => tfl.layers.gru({units: -25})) .toThrowError(/units.*positive integer.*-25\.$/); }); }); describeMathCPUAndGPU('GRU Tensor', () => { // Note: // The golden expected values used for assertions in these unit tests can be // obtained through running the Python code similar to the following example. // TensorFlow 1.5 was used to obtain the values. // // ```python // import numpy as np // import tensorflow as tf // // units = 5 // batch_size = 4 // input_size = 2 // time_steps = 3 // // with tf.Session() as sess: // lstm = tf.keras.layers.GRU(units, // kernel_initializer="ones", // recurrent_initializer="ones", // bias_initializer="ones", // return_sequences=True, // return_state=True) // inputs = tf.placeholder(tf.float32, shape=[None, None, input_size]) // outputs = lstm(inputs) // // sess.run(tf.global_variables_initializer()) // feed_inputs = np.ones([batch_size, time_steps, input_size]) // print(sess.run(outputs, feed_dict={inputs: feed_inputs})) // ``` const units = 5; const batchSize = 4; const inputSize = 2; const timeSteps = 3; const goldenOutputElementValues = [0.22847827, 0.2813754, 0.29444352]; // TODO(cais): Add test for the default recurrent initializer ('Orthogonal') // when it becomes available. const dropouts = [0.0, 0.1]; const trainings = [true, false]; for (const training of trainings) { for (const dropout of dropouts) { const testTitle = `returnSequences=false, returnState=false, useBias=true,` + ` ${training}, dropout=${dropout}`; it(testTitle, () => { const gru = tfl.layers.gru({ units, kernelInitializer: 'ones', recurrentInitializer: 'ones', biasInitializer: 'ones', dropout, implementation: 1 }); const kwargs:Kwargs = {}; if (training) { kwargs['training'] = true; } const input = tfc.ones([batchSize, timeSteps, inputSize]); spyOn(tfc, 'dropout').and.callThrough(); let numTensors = 0; for (let i = 0; i < 2; i++){ tfc.dispose(gru.apply(input, kwargs) as Tensor); if (dropout !== 0.0 && training) { expect(tfc.dropout).toHaveBeenCalledTimes(3 * (i + 1)); } else { expect(tfc.dropout).toHaveBeenCalledTimes(0); } if (i === 0) { numTensors = tfc.memory().numTensors; } else { expect(tfc.memory().numTensors).toEqual(numTensors); } } }); } } const recurrentDropouts = [0.0, 0.1]; for (const training of trainings) { for (const recurrentDropout of recurrentDropouts) { const testTitle = `returnSequences=false, returnState=false, useBias=true,` + ` ${training}, recurrentDropout=${recurrentDropout}`; it(testTitle, () => { const gru = tfl.layers.gru({ units, kernelInitializer: 'ones', recurrentInitializer: 'ones', biasInitializer: 'ones', recurrentDropout, implementation: 1 }); const kwargs:Kwargs = {}; if (training) { kwargs['training'] = true; } const input = tfc.ones([batchSize, timeSteps, inputSize]); spyOn(tfc, 'dropout').and.callThrough(); let numTensors = 0; for (let i = 0; i < 2; i++){ tfc.dispose(gru.apply(input, kwargs) as Tensor); if (recurrentDropout !== 0.0 && training) { expect(tfc.dropout).toHaveBeenCalledTimes(3 * (i + 1)); } else { expect(tfc.dropout).toHaveBeenCalledTimes(0); } if (i === 0) { numTensors = tfc.memory().numTensors; } else { expect(tfc.memory().numTensors).toEqual(numTensors); } } }); } } const implementations = [1, 2]; const returnStateValues = [false, true]; const returnSequencesValues = [false, true]; for (const implementation of implementations) { for (const returnState of returnStateValues) { for (const returnSequences of returnSequencesValues) { const testTitle = `implementation=${implementation}, ` + `returnSequences=${returnSequences}, ` + `returnState=${returnState}`; it(testTitle, () => { const gru = tfl.layers.gru({ units, kernelInitializer: 'ones', recurrentInitializer: 'ones', biasInitializer: 'ones', returnState, returnSequences, implementation }); const input = tfc.zeros([batchSize, timeSteps, inputSize]); let output = gru.apply(input); const goldenOutputElementValueFinal = goldenOutputElementValues[goldenOutputElementValues.length - 1]; let expectedOutput: Tensor; if (returnSequences) { const outputs = goldenOutputElementValues.map( value => tfc.mul( scalar(value), tfc.ones([1, batchSize, units]))); expectedOutput = tfc.transpose( K.concatAlongFirstAxis( K.concatAlongFirstAxis(outputs[0], outputs[1]), outputs[2]), [1, 0, 2]); } else { expectedOutput = tfc.mul( scalar(goldenOutputElementValueFinal), tfc.ones([batchSize, units])); } if (returnState) { output = output as Tensor[]; expect(output.length).toEqual(2); expectTensorsClose(output[0], expectedOutput); expectTensorsClose( output[1], tfc.mul( scalar(goldenOutputElementValueFinal), tfc.ones([batchSize, units]))); } else { output = output as Tensor; expectTensorsClose(output, expectedOutput); } }); } } } // The reference values below can be obtained with PyKeras code: // ```python // import keras // import numpy as np // // units = 5 // batch_size = 4 // input_size = 2 // sequence_length = 3 // // rnn = keras.layers.GRU(units, // kernel_initializer='ones', // recurrent_initializer='zeros', // bias_initializer='zeros', // activation='linear', // stateful=True, // batch_input_shape=[batch_size, // sequence_length, // input_size]) // // x = np.ones([batch_size, sequence_length, input_size]) // // model = keras.Sequential() // model.add(rnn) // print(model.predict(x)) // print(model.predict(x)) // model.reset_states() // print(model.predict(x)) // print(model.predict(x)) // ``` it('stateful forward', async () => { const sequenceLength = 3; const rnn = tfl.layers.gru({ units, kernelInitializer: 'ones', recurrentInitializer: 'zeros', biasInitializer: 'zeros', activation: 'linear', stateful: true, batchInputShape: [batchSize, sequenceLength, inputSize] }); const model = tfl.sequential(); model.add(rnn); const x = tfc.ones([batchSize, sequenceLength, inputSize]); const y1 = model.predict(x) as Tensor; expect(y1.kept).toBe(false); const y1Expected = tfc.tidy(() => tfc.ones([batchSize, units]).mul(tfc.scalar(0.542))); expectTensorsClose(y1, y1Expected); const y2 = model.predict(x) as Tensor; expect(y2.kept).toBe(false); // Future predicts should not dispose previous outputs. expect(y1.isDisposed).toBe(false); const y2Expected = tfc.tidy(() => tfc.ones([batchSize, units]).mul(tfc.scalar(0.9371182))); expectTensorsClose(y2, y2Expected); tfc.dispose([y1, y2, y1Expected, y2Expected]); model.resetStates(); const numTensors0 = tfc.memory().numTensors; const y3 = model.predict(x) as Tensor; expect(y3.kept).toBe(false); const y3Expected = tfc.tidy(() => tfc.ones([batchSize, units]).mul(tfc.scalar(0.542))); expectTensorsClose(y3, y3Expected); const y4 = model.predict(x) as Tensor; expect(y4.kept).toBe(false); // Future predicts should not dispose previous outputs. expect(y3.isDisposed).toBe(false); const y4Expected = tfc.tidy(() => tfc.ones([batchSize, units]).mul(tfc.scalar(0.9371182))); expectTensorsClose(y4, y4Expected); tfc.dispose([y3, y3Expected, y4, y4Expected]); // Assert no memory leak, even without resetStates() being called. expect(tfc.memory().numTensors).toEqual(numTensors0); }); // The reference values can be obtained with the following PyKeras code: // ```python // import keras // import numpy as np // // batch_size = 4 // sequence_length = 3 // input_size = 2 // // model = keras.Sequential() // model.add(keras.layers.GRU( // units=5, // batch_input_shape=[batch_size, sequence_length, input_size], // kernel_initializer='ones', // recurrent_initializer='ones', // bias_initializer='zeros', // stateful=True)) // model.add(keras.layers.Dense(1, // kernel_initializer='zeros', // use_bias=False)) // model.compile(loss='mean_squared_error', optimizer='sgd') // // xs_1 = np.ones([batch_size, sequence_length, input_size]) // xs_2 = np.zeros([batch_size, sequence_length, input_size]) // xs = np.concatenate([xs_1, xs_2], 0) // ys = np.array([[-1], [-2], [0], [1], [1], [2], [0], [-1]]) // // history = model.fit(xs, ys, batch_size=batch_size, shuffle=False) // print(history.history) // ``` it('stateful BPTT', async () => { const sequenceLength = 3; const model = tfl.sequential(); model.add(tfl.layers.gru({ units, kernelInitializer: 'ones', recurrentInitializer: 'ones', biasInitializer: 'zeros', stateful: true, batchInputShape: [batchSize, sequenceLength, inputSize] })); model.add(tfl.layers.dense({ units: 1, kernelInitializer: 'zeros', useBias: false })); model.compile({loss: 'meanSquaredError', optimizer: 'sgd'}); const xs1 = tfc.ones([batchSize, sequenceLength, inputSize]); const xs2 = tfc.ones([batchSize, sequenceLength, inputSize]); const xs = tfc.concat([xs1, xs2], 0); const ys = tfc.tensor2d([[-1], [-2], [0], [1], [1], [2], [0], [-1]]); const history = await model.fit(xs, ys, {batchSize, shuffle: false}); // See code snippet above for the code used to obtain this loss value. expect(history.history.loss[0]).toBeCloseTo(1.501); }); it('BPTT', async () => { // The following golden values for assertion can be obtained with the // following Python Keras code. // ```python // import keras // import numpy as np // sequence_length = 3 // input_size = 4 // batch_size = 5 // t_input = keras.Input([sequence_length, input_size]) // gru = keras.layers.GRU(1, // kernel_initializer='zeros', // recurrent_initializer='zeros', // use_bias=False) // dense = keras.layers.Dense(1, // kernel_initializer='ones', // use_bias=False) // output = dense(gru(t_input)) // model = keras.Model(t_input, output) // optimizer = keras.optimizers.SGD(1) // model.compile(optimizer=optimizer, loss='mean_squared_error') // x = np.ones([batch_size, sequence_length, input_size]) // y = np.ones([batch_size, 1]) // model.fit(x, y, batch_size=batch_size, epochs=2) // print(gru.get_weights()[0]) // print(gru.get_weights()[1]) // print(dense.get_weights()[0]) // ``` const sequenceLength = 3; const inputSize = 4; const batchSize = 5; const model = tfl.sequential(); model.add(tfl.layers.gru({ units: 1, kernelInitializer: 'zeros', recurrentInitializer: 'zeros', useBias: false, inputShape: [sequenceLength, inputSize] })); model.add(tfl.layers.dense({ units: 1, kernelInitializer: 'ones', useBias: false })); const sgd = tfc.train.sgd(1); model.compile({loss: 'meanSquaredError', optimizer: sgd}); const x = tfc.ones([batchSize, sequenceLength, inputSize]); const y = tfc.ones([batchSize, 1]); await model.fit(x, y, {epochs: 2}); expectTensorsClose( model.layers[0].getWeights()[0], K.tile(tensor2d([[-0.03750037, 0, 1.7500007]], [1, 3]), [4, 1])); expectTensorsClose( model.layers[0].getWeights()[1], tensor2d([[-1.562513e-02, 0, 2.086183e-07]], [1, 3])); expectTensorsClose( model.layers[1].getWeights()[0], tensor2d([[1.2187521]], [1, 1])); }); // Reference Python code: // ```py // import keras // import numpy as np // // in1 = keras.Input(shape=[5]) // out1 = keras.layers.Dense(2, // kernel_initializer='ones', // bias_initializer='zeros')(in1) // in2 = keras.Input(shape=[3, 4]) // out2 = keras.layers.GRU(2, // recurrent_initializer='ones', // kernel_initializer='ones', // bias_initializer='zeros')(in2, initial_state=out1) // model = keras.Model(inputs=[in1, in2], outputs=[out1, out2]) // // xs1 = np.array([[0.1, 0.2, 0.3, 0.4, 0.5]]) // xs2 = np.array([[[0.1, 0.2, 0.3, 0.4], [-0.1, -0.2, -0.3, -0.4], // [0.3, 0.4, 0.5, 0.6]]]) // print(model.predict([xs1, xs2])) // ``` it('SymbolicTensor as initialState thru kwargs; Save & Load', async () => { const in1 = tfl.input({shape: [5]}); const out1 = tfl.layers.dense({ units: 2, kernelInitializer: 'ones', biasInitializer: 'zeros' }).apply(in1) as tfl.SymbolicTensor; const in2 = tfl.input({shape: [3, 4]}); const out2 = tfl.layers.gru({ units: 2, recurrentInitializer: 'ones', kernelInitializer: 'ones', biasInitializer: 'zeros' }).apply(in2, {initialState: out1}) as tfl.SymbolicTensor; const model = tfl.model({inputs: [in1 , in2], outputs: [out1, out2]}); const xs1 = tensor2d([[0.1, 0.2, 0.3, 0.4, 0.5]]); const xs2 = tensor3d( [[[0.1, 0.2, 0.3, 0.4], [-0.1, -0.2, -0.3, -0.4], [0.3, 0.4, 0.5, 0.6]]]); const ys = model.predict([xs1, xs2]) as Tensor[]; expect(ys.length).toEqual(2); expectTensorsClose(ys[0], tensor2d([[1.5, 1.5]])); expectTensorsClose(ys[1], tensor2d([[1.4435408, 1.4435408]])); // NOTE: Here on down, i.e., the part that tests serialization and // deserialization of the model, has no counterpart in the Python // code snippet above. const modelJSON = model.toJSON(null, false); const modelPrime = await tfl.models.modelFromJSON({modelTopology: modelJSON}); const ysPrime = modelPrime.predict([xs1, xs2]) as Tensor[]; expect(ysPrime.length).toEqual(2); expectTensorsClose(ysPrime[0], ys[0]); expectTensorsClose(ysPrime[1], ys[1]); }); }); describeMathCPU('GRU-deserialization', () => { it('Default recurrentActivation round trip', () => { const x = randomNormal([1, 2, 3]); const layer = tfl.layers.gru({units: 4}) as GRU; const y = layer.apply(x) as Tensor; const pythonicConfig = convertTsToPythonic(layer.getConfig()); // tslint:disable-next-line:no-any const tsConfig = convertPythonicToTs(pythonicConfig) as any; const layerPrime = tfl.layers.gru(tsConfig) as GRU; const yPrime = layer.apply(x) as Tensor; expectTensorsClose(yPrime, y); expect(layerPrime.recurrentActivation.getClassName()) .toEqual(layer.recurrentActivation.getClassName()); }); it('Non-default recurrentActivation round trip', () => { const x = randomNormal([1, 2, 3]); const layer = tfl.layers.gru({units: 4, recurrentActivation: 'tanh'}) as GRU; const y = layer.apply(x) as Tensor; const pythonicConfig = convertTsToPythonic(layer.getConfig()); // tslint:disable-next-line:no-any const tsConfig = convertPythonicToTs(pythonicConfig) as any; const layerPrime = tfl.layers.gru(tsConfig) as GRU; const yPrime = layer.apply(x) as Tensor; expectTensorsClose(yPrime, y); expect(layerPrime.recurrentActivation.getClassName()) .toEqual(layer.recurrentActivation.getClassName()); }); }); describeMathCPU('LSTM Symbolic', () => { it('returnSequences=false, returnState=false', () => { const input = new tfl.SymbolicTensor('float32', [9, 10, 8], null, [], null); const lstm = tfl.layers.lstm({units: 5}); const output = lstm.apply(input) as tfl.SymbolicTensor; expect(output.shape).toEqual([9, 5]); }); it('returnSequences=false, returnState=true', () => { const input = new tfl.SymbolicTensor('float32', [9, 10, 8], null, [], null); const lstm = tfl.layers.lstm({units: 5, returnState: true}); const output = lstm.apply(input) as tfl.SymbolicTensor[]; expect(output.length).toEqual(3); expect(output[0].shape).toEqual([9, 5]); expect(output[1].shape).toEqual([9, 5]); expect(output[2].shape).toEqual([9, 5]); }); it('returnSequences=true, returnState=false', () => { const input = new tfl.SymbolicTensor('float32', [9, 10, 8], null, [], null); const lstm = tfl.layers.lstm({units: 5, returnSequences: true}); const output = lstm.apply(input) as tfl.SymbolicTensor; expect(output.shape).toEqual([9, 10, 5]); }); it('returnSequences=true, returnState=true', () => { const input = new tfl.SymbolicTensor('float32', [9, 10, 8], null, [], null); const lstm = tfl.layers.lstm({ units: 5, returnSequences: true, returnState: true, }); const output = lstm.apply(input) as tfl.SymbolicTensor[]; expect(output.length).toEqual(3); expect(output[0].shape).toEqual([9, 10, 5]); expect(output[1].shape).toEqual([9, 5]); expect(output[2].shape).toEqual([9, 5]); }); it('trainableWeights, nonTrainableWeights and weights give correct outputs', () => { const input = new tfl.SymbolicTensor('float32', [2, 3, 4], null, [], null); const lstm = tfl.layers.lstm({units: 5, returnState: true}); lstm.apply(input); expect(lstm.trainable).toEqual(true); // Trainable weights: kernel, recurrent kernel and bias. expect(lstm.trainableWeights.length).toEqual(3); expect(lstm.nonTrainableWeights.length).toEqual(0); expect(lstm.weights.length).toEqual(3); }); for (const implementation of [1, 2]) { it('Serialization round trip', () => { const layer = tfl.layers.lstm({units: 4, implementation}); const pythonicConfig = convertTsToPythonic(layer.getConfig()); // tslint:disable-next-line:no-any const tsConfig = convertPythonicToTs(pythonicConfig) as any; const layerPrime = tfl.layers.lstm(tsConfig); expect(layerPrime.getConfig().units).toEqual(4); expect(layerPrime.getConfig().implementation).toEqual(implementation); }); } it('Invalid units leads to Error', () => { expect(() => tfl.layers.lstm({units: 12.5})) .toThrowError(/units.*positive integer.*12\.5\.$/); expect(() => tfl.layers.lstm({units: 0})) .toThrowError(/units.*positive integer.*0\.$/); expect(() => tfl.layers.lstm({units: -25})) .toThrowError(/units.*positive integer.*-25\.$/); }); }); describeMathCPUAndGPU('LSTM Tensor', () => { // Note: // The golden expected values used for assertions in these unit tests can be // obtained through running the Python code similar to the following // example. TensorFlow 1.5 was used to obtain the values. // // ```python // import numpy as np // import tensorflow as tf // // units = 5 // batch_size = 4 // input_size = 2 // time_steps = 2 // // with tf.Session() as sess: // lstm = tf.keras.layers.LSTM(units, // kernel_initializer="ones", // recurrent_initializer="ones", // bias_initializer="ones", // return_sequences=True, // return_state=True, // unit_forget_bias=True) // inputs = tf.placeholder(tf.float32, shape=[None, None, input_size]) // outputs = lstm(inputs) // // sess.run(tf.global_variables_initializer()) // feed_inputs = np.ones([batch_size, time_steps, input_size]) // print(sess.run(outputs, feed_dict={inputs: feed_inputs})) // ``` const units = 5; const batchSize = 4; const inputSize = 2; const timeSteps = 2; // TODO(cais): Add test for the default recurrent initializer ('Orthogonal') // when it becomes available. const dropouts = [0.0, 0.1]; const trainings = [true, false]; for (const training of trainings) { for (const dropout of dropouts) { const testTitle = `returnSequences=false, returnState=false, useBias=true,` + ` ${training}, dropout=${dropout}`; it(testTitle, () => { const lstm = tfl.layers.lstm({ units, kernelInitializer: 'ones', recurrentInitializer: 'ones', biasInitializer: 'ones', dropout, implementation: 1 }); const kwargs:Kwargs = {}; if (training) { kwargs['training'] = true; } const input = tfc.ones([batchSize, timeSteps, inputSize]); spyOn(tfc, 'dropout').and.callThrough(); let numTensors = 0; for (let i = 0; i < 2; i++){ tfc.dispose(lstm.apply(input, kwargs) as Tensor); if (dropout !== 0.0 && training) { expect(tfc.dropout).toHaveBeenCalledTimes(4 * (i + 1)); } else { expect(tfc.dropout).toHaveBeenCalledTimes(0); } if (i === 0) { numTensors = tfc.memory().numTensors; } else { expect(tfc.memory().numTensors).toEqual(numTensors); } } }); } } const recurrentDropouts = [0.0, 0.1]; for (const training of trainings) { for (const recurrentDropout of recurrentDropouts) { const testTitle = `returnSequences=false, returnState=false, useBias=true,` + ` ${training}, recurrentDropout=${recurrentDropout}`; it(testTitle, () => { const lstm = tfl.layers.lstm({ units, kernelInitializer: 'ones', recurrentInitializer: 'ones', biasInitializer: 'ones', recurrentDropout, implementation: 1 }); const kwargs:Kwargs = {}; if (training) { kwargs['training'] = true; } const input = tfc.ones([batchSize, timeSteps, inputSize]); spyOn(tfc, 'dropout').and.callThrough(); let numTensors = 0; for (let i = 0; i < 2; i++){ tfc.dispose(lstm.apply(input, kwargs) as Tensor); if (recurrentDropout !== 0.0 && training) { expect(tfc.dropout).toHaveBeenCalledTimes(4 * (i + 1)); } else { expect(tfc.dropout).toHaveBeenCalledTimes(0); } if (i === 0) { numTensors = tfc.memory().numTensors; } else { expect(tfc.memory().numTensors).toEqual(numTensors); } } }); } } const implementations: Array<(1 | 2)> = [1, 2]; const returnStateValues = [false, true]; const returnSequencesValues = [false, true]; for (const implementation of implementations) { for (const returnState of returnStateValues) { for (const returnSequences of returnSequencesValues) { const testTitle = `implementation=${implementation}, ` + `returnSequences=${returnSequences}, ` + `returnState=${returnState}`; it(testTitle, () => { const lstm = tfl.layers.lstm({ units, kernelInitializer: 'ones', recurrentInitializer: 'ones', biasInitializer: 'ones', returnState, returnSequences, implementation }); const input = tfc.ones([batchSize, timeSteps, inputSize]); let output = lstm.apply(input); // See comments at the beginning of this describe() block on how // these golden expected values can be obtained. const goldenOutputElementValueAtT0 = 0.7595095; const goldenOutputElementValueAtT1 = 0.96367633; const goldenHStateElementValue = goldenOutputElementValueAtT1; const goldenCStateElementValue = 1.99505234; let expectedOutput: Tensor; if (returnSequences) { const outputAtT0 = tfc.mul( scalar(goldenOutputElementValueAtT0), tfc.ones([1, batchSize, units])); const outputAtT1 = tfc.mul( scalar(goldenOutputElementValueAtT1), tfc.ones([1, batchSize, units])); expectedOutput = tfc.transpose( K.concatAlongFirstAxis(outputAtT0, outputAtT1), [1, 0, 2]); } else { expectedOutput = tfc.mul( scalar(goldenOutputElementValueAtT1), tfc.ones([batchSize, units])); } if (returnState) { output = output as Tensor[]; expect(output.length).toEqual(3); expectTensorsClose(output[0], expectedOutput); expectTensorsClose( output[1], tfc.mul( scalar(goldenHStateElementValue), tfc.ones([batchSize, units]))); expectTensorsClose( output[2], tfc.mul( scalar(goldenCStateElementValue), tfc.ones([batchSize, units]))); } else { output = output as Tensor; expectTensorsClose(output, expectedOutput); } }); } } // The reference values below can be obtained with PyKeras code: // ```python // import keras // import numpy as np // // units = 5 // batch_size = 4 // input_size = 2 // sequence_length = 3 // // rnn = keras.layers.LSTM(units, // kernel_initializer='ones', // recurrent_initializer='ones', // bias_initializer='ones', // stateful=True, // batch_input_shape=[batch_size, // sequence_length, // input_size]) // // x = np.ones([batch_size, sequence_length, input_size]) // // model = keras.Sequential() // model.add(rnn) // print(model.predict(x)) // print(model.predict(x)) // model.reset_states() // print(model.predict(x)) // print(model.predict(x)) // ``` it('stateful forward', async () => { const sequenceLength = 3; const rnn = tfl.layers.lstm({ units, kernelInitializer: 'ones', recurrentInitializer: 'ones', biasInitializer: 'ones', stateful: true, batchInputShape: [batchSize, sequenceLength, inputSize] }); const model = tfl.sequential(); model.add(rnn); const x = tfc.ones([batchSize, sequenceLength, inputSize]); let y1 = model.predict(x) as Tensor; expect(y1.kept).toBe(false); let y1Expected = tfc.tidy(() => tfc.ones([batchSize, units]).mul(tfc.scalar(0.995))); expectTensorsClose(y1, y1Expected); let y2 = model.predict(x) as Tensor; expect(y2.kept).toBe(false); // Future predicts should not dispose previous outputs. expect(y1.isDisposed).toBe(false); let y2Expected = tfc.tidy( () => tfc.ones([batchSize, units]).mul(tfc.scalar(0.99998766))); expectTensorsClose(y2, y2Expected); tfc.dispose([y1, y2, y1Expected, y2Expected]); model.resetStates(); const numTensors0 = tfc.memory().numTensors; y1 = model.predict(x) as Tensor; expect(y1.kept).toBe(false); y1Expected = tfc.tidy(() => tfc.ones([batchSize, units]).mul(tfc.scalar(0.995))); expectTensorsClose(y1, y1Expected); y2 = model.predict(x) as Tensor; expect(y2.kept).toBe(false); // Future predicts should not dispose previous outputs. expect(y1.isDisposed).toBe(false); y2Expected = tfc.tidy( () => tfc.ones([batchSize, units]).mul(tfc.scalar(0.99998766))); expectTensorsClose(y2, y2Expected); tfc.dispose([y1, y2, y1Expected, y2Expected]); // Assert no memory leak, even without resetStates() being called. expect(tfc.memory().numTensors).toEqual(numTensors0); }); // The reference values can be obtained with the following PyKeras code: // ```python // import keras // import numpy as np // // batch_size = 4 // sequence_length = 3 // input_size = 2 // // model = keras.Sequential() // model.add(keras.layers.LSTM( // 5, // batch_input_shape=[batch_size, sequence_length, input_size], // kernel_initializer='ones', // recurrent_initializer='ones', // bias_initializer='ones', // stateful=True)) // model.add(keras.layers.Dense(1, // kernel_initializer='ones', // use_bias=False)) // model.compile(loss='mean_squared_error', optimizer='sgd') // // xs_1 = np.ones([batch_size, sequence_length, input_size]) // xs_2 = np.ones([batch_size, sequence_length, input_size]) // xs = np.concatenate([xs_1, xs_2], 0) // ys = np.array([[1], [2], [3], [4], [5], [6], [7], [8]]) // // history = model.fit(xs, ys, batch_size=batch_size, shuffle=False) // print(history.history) // ``` it('stateful BPTT', async () => { const sequenceLength = 3; const model = tfl.sequential(); model.add(tfl.layers.lstm({ units, kernelInitializer: 'ones', recurrentInitializer: 'ones', biasInitializer: 'ones', stateful: true, batchInputShape: [batchSize, sequenceLength, inputSize] })); model.add(tfl.layers.dense({ units: 1, kernelInitializer: 'ones', useBias: false })); model.compile({loss: 'meanSquaredError', optimizer: 'sgd'}); const xs1 = tfc.ones([batchSize, sequenceLength, inputSize]); const xs2 = tfc.ones([batchSize, sequenceLength, inputSize]); const xs = tfc.concat([xs1, xs2], 0); const ys = tfc.tensor2d([[1], [2], [3], [4], [5], [6], [7], [8]]); const history = await model.fit(xs, ys, {batchSize, shuffle: false}); // See code snippet above for the code used to obtain this loss value. expect(history.history.loss[0]).toBeCloseTo(5.8377); }); it('BPTT', async () => { // The following golden values for assertion can be obtained with the // following Python Keras code. // ```python // import keras // import numpy as np // // sequence_length = 3 // input_size = 4 // batch_size = 5 // // t_input = keras.Input([sequence_length, input_size]) // lstm = keras.layers.LSTM(1, // kernel_initializer='zeros', // recurrent_initializer='zeros', // use_bias=False) // dense = keras.layers.Dense(1, // kernel_initializer='ones', // use_bias=False) // output = dense(lstm(t_input)) // model = keras.Model(t_input, output) // optimizer = keras.optimizers.SGD(1) // model.compile(optimizer=optimizer, loss='mean_squared_error') // // x = np.ones([batch_size, sequence_length, input_size]) // y = np.ones([batch_size, 1]) // model.fit(x, y, batch_size=batch_size, epochs=2) // print(lstm.get_weights()[0]) // print(lstm.get_weights()[1]) // print(dense.get_weights()[0]) // ``` const sequenceLength = 3; const inputSize = 4; const batchSize = 5; const model = tfl.sequential(); model.add(tfl.layers.lstm({ units: 1, kernelInitializer: 'zeros', recurrentInitializer: 'zeros', useBias: false, inputShape: [sequenceLength, inputSize] })); model.add(tfl.layers.dense({ units: 1, kernelInitializer: 'ones', useBias: false, })); const sgd = tfc.train.sgd(1); model.compile({loss: 'meanSquaredError', optimizer: sgd}); const x = tfc.ones([batchSize, sequenceLength, inputSize]); const y = tfc.ones([batchSize, 1]); await model.fit(x, y, {epochs: 2}); expectTensorsClose( model.layers[0].getWeights()[0], K.tile( tensor2d( [[0.11455188, 0.06545822, 0.8760446, 0.18237013]], [1, 4]), [4, 1])); expectTensorsClose( model.layers[0].getWeights()[1], tensor2d([[0.02831176, 0.01934617, 0.00025817, 0.05784169]], [1, 4])); expectTensorsClose( model.layers[1].getWeights()[0], tensor2d([[1.4559253]], [1, 1])); }); } // Reference Python code: // ```py // import keras // import numpy as np // // model = keras.Sequential() // model.add(keras.layers.Embedding(10, // 4, // input_length=6, // mask_zero=True, // embeddings_initializer='ones')) // model.add(keras.layers.LSTM(3, // recurrent_initializer='ones', // kernel_initializer='ones', // bias_initializer='zeros')) // model.add(keras.layers.Dense(1, // kernel_initializer='ones', // bias_initializer='zero')) // // xs = np.array([[0, 0, 0, 0, 0, 0], // [1, 0, 0, 0, 0, 0], // [1, 2, 0, 0, 0, 0], // [1, 2, 3, 0, 0, 0]]) // ys = model.predict(xs) // print(ys) // ``` it('With mask', () => { const model = tfl.sequential(); model.add(tfl.layers.embedding({ inputDim: 10, outputDim: 4, inputLength: 6, maskZero: true, embeddingsInitializer: 'ones' })); model.add(tfl.layers.lstm({ units: 3, recurrentInitializer: 'ones', kernelInitializer: 'ones', biasInitializer: 'zeros' })); model.add(tfl.layers.dense({ units: 1, kernelInitializer: 'ones', biasInitializer: 'zeros'})); const xs = tensor2d( [[0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0], [1, 2, 0, 0, 0, 0], [1, 2, 3, 0, 0, 0]]); const ys = model.predict(xs) as Tensor; expectTensorsClose( ys, tensor2d([[0], [2.283937], [2.891939], [2.9851441]])); }); // Reference Python code: // ```py // import keras // // model = keras.Sequential() // embedding_layer = keras.layers.Embedding(4, // 2, // input_length=3, // mask_zero=True) // model.add(embedding_layer) // lstm_layer = keras.layers.LSTM(2, go_backwards=True) // model.add(lstm_layer) // model.add(keras.layers.Dense(1, // kernel_initializer='ones', // bias_initializer='zero')) // // embedding_layer.set_weights([ // np.array([[0.1, 0.2], [0.3, 0.4], [-0.1, -0.2], [-0.3, -0.4]])]) // print(lstm_layer.get_weights()) // lstm_layer.set_weights([ // np.array([[1, 2, 3, 4, 5, 6, 7, 8], // [-1, -2, -3, -4, -5, -6, -7, -8]]), // np.array([[1, 2, 3, 4, 5, 6, 7, 8], // [-1, -2, -3, -4, -5, -6, -7, -8]]), // np.array([1, 2, 3, 4, 5, 6, 7, 8])]) // // xs = np.array([[0, 0, 0], // [1, 0, 0], // [1, 2, 0], // [1, 2, 3]]) // ys = model.predict(xs) // print(ys) // ``` it('With mask, goBackwards = true', () => { const model = tfl.sequential(); const embeddingLayer = tfl.layers.embedding({ inputDim: 4, outputDim: 2, inputLength: 3, maskZero: true }); model.add(embeddingLayer); const lstmLayer = tfl.layers.lstm({ units: 2, goBackwards: true }); model.add(lstmLayer); model.add(tfl.layers.dense({ units: 1, kernelInitializer: 'ones', biasInitializer: 'zeros'})); // Setting weights to asymmetric, so that the effect of goBackwards=true // can show. embeddingLayer.setWeights([ tensor2d([[0.1, 0.2], [0.3, 0.4], [-0.1, -0.2], [-0.3, -0.4]])]); lstmLayer.setWeights([ tensor2d([[1, 2, 3, 4, 5, 6, 7, 8], [-1, -2, -3, -4, -5, -6, -7, -8]]), tensor2d([[1, 2, 3, 4, 5, 6, 7, 8], [-1, -2, -3, -4, -5, -6, -7, -8]]), tensor1d([1, 2, 3, 4, 5, 6, 7, 8])]); const xs = tensor2d([[0, 0, 0], [1, 0, 0], [1, 2, 0], [1, 2, 3]]); const ys = model.predict(xs) as Tensor; expectTensorsClose( ys, tensor2d([[0], [1.2876499], [1.8165315], [1.9599037]])); }); // Reference Python code: // ```py // import keras // import numpy as np // // model = keras.Sequential() // model.add(keras.layers.Reshape(target_shape=[6], input_shape=[6])) // nested_model = keras.Sequential() // nested_model.add(keras.layers.Embedding(10, // 4, // input_length=6, // mask_zero=True, // embeddings_initializer='ones')) // nested_model.add(keras.layers.LSTM(3, // recurrent_initializer='ones', // kernel_initializer='ones', // bias_initializer='zeros')) // model.add(nested_model) // model.add(keras.layers.Dense(1, // kernel_initializer='ones', // bias_initializer='zero')) // model.compile(loss='mean_squared_error', optimizer='sgd') // // xs = np.array([[0, 0, 0, 0, 0, 0], // [1, 0, 0, 0, 0, 0], // [1, 2, 0, 0, 0, 0], // [1, 2, 3, 0, 0, 0]]) // ys = model.predict(xs) // print(ys) // ``` it('With mask and a nested model', () => { const model = tfl.sequential(); model.add(tfl.layers.reshape({ targetShape: [6], inputShape: [6] })); // A dummy input layer. const nestedModel = tfl.sequential(); nestedModel.add(tfl.layers.embedding({ inputDim: 10, outputDim: 4, inputLength: 6, maskZero: true, embeddingsInitializer: 'ones' })); nestedModel.add(tfl.layers.lstm({ units: 3, recurrentInitializer: 'ones', kernelInitializer: 'ones', biasInitializer: 'zeros' })); model.add(nestedModel); model.add(tfl.layers.dense({ units: 1, kernelInitializer: 'ones', biasInitializer: 'zeros'})); const xs = tensor2d( [[0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0], [1, 2, 0, 0, 0, 0], [1, 2, 3, 0, 0, 0]]); const ys = model.predict(xs) as Tensor; expectTensorsClose( ys, tensor2d([[0], [2.283937], [2.891939], [2.9851441]])); }); // Reference Python code: // ```py // import keras // import numpy as np // // model = keras.Sequential() // model.add(keras.layers.Embedding(10, // 4, // input_length=6, // mask_zero=True, // embeddings_initializer='ones')) // model.add(keras.layers.LSTM(3, // recurrent_initializer='ones', // kernel_initializer='ones', // bias_initializer='zeros')) // model.add(keras.layers.Dense(1, // kernel_initializer='ones', // bias_initializer='zero')) // model.compile(loss='mean_squared_error', optimizer='sgd') // // xs = np.array([[0, 0, 0, 0, 0, 0], // [1, 0, 0, 0, 0, 0], // [1, 2, 0, 0, 0, 0], // [1, 2, 3, 0, 0, 0]]) // ys = np.array([[1], [2], [3], [4]]) // // model.fit(xs, ys, epochs=2, batch_size=4) // history = model.fit(xs, ys, epochs=2, batch_size=4) // print(history.history) // ``` it('BPTT with mask: correctness and no leak', async () => { const model = tfl.sequential(); model.add(tfl.layers.embedding({ inputDim: 10, outputDim: 4, inputLength: 6, maskZero: true, embeddingsInitializer: 'ones' })); model.add(tfl.layers.lstm({ units: 3, recurrentInitializer: 'ones', kernelInitializer: 'ones', biasInitializer: 'zeros' })); model.add(tfl.layers.dense({ units: 1, kernelInitializer: 'ones', biasInitializer: 'zeros'})); model.compile({loss: 'meanSquaredError', optimizer: 'sgd'}); const xs = tensor2d( [[0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0], [1, 2, 0, 0, 0, 0], [1, 2, 3, 0, 0, 0]]); const ys = tensor2d([[1], [2], [3], [4]]); // Serves as burn-in call for subsequent tracking of memory leak. await model.fit(xs, ys, {epochs: 2, batchSize: 4}); const numTensors0 = tfc.memory().numTensors; const history = await model.fit(xs, ys, {epochs: 2, batchSize: 4}); const numTensors1 = tfc.memory().numTensors; // Assert no memory leak. expect(numTensors1).toEqual(numTensors0); expect(history.history.loss.length).toEqual(2); expect(history.history.loss[0]).toBeCloseTo(0.503677); expect(history.history.loss[1]).toBeCloseTo(0.492173); }); // Reference Python code: // ```py // import keras // import numpy as np // // inp = keras.Input(shape=[6]) // y = keras.layers.Embedding(10, // 4, // input_length=6, // mask_zero=True, // embeddings_initializer='ones')(inp) // y = keras.layers.LSTM(3, // return_state=True, // recurrent_initializer='ones', // kernel_initializer='ones', // bias_initializer='zeros')(y) // // model = keras.Model(inputs=inp, outputs=y) // // xs = np.array([[0, 0, 0, 0, 0, 0], // [1, 0, 0, 0, 0, 0], // [1, 2, 0, 0, 0, 0], // [1, 2, 3, 0, 0, 0]]) // ys = model.predict(xs) // print(ys) // ``` it('With mask, returnStates = true', () => { const inp = tfl.input({shape: [6]}); let y: tfl.SymbolicTensor|tfl.SymbolicTensor[] = tfl.layers.embedding({ inputDim: 10, outputDim: 4, inputLength: 6, maskZero: true, embeddingsInitializer: 'ones' }).apply(inp) as tfl.SymbolicTensor; y = tfl.layers.lstm({ units: 3, returnState: true, recurrentInitializer: 'ones', kernelInitializer: 'ones', biasInitializer: 'zeros' }).apply(y) as tfl.SymbolicTensor[]; const model = tfl.model({inputs: inp, outputs: y}); const xs = tensor2d( [[0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0], [1, 2, 0, 0, 0, 0], [1, 2, 3, 0, 0, 0]]); const ys = model.predict(xs) as Tensor[]; expect(ys.length).toEqual(3); expectTensorsClose(ys[0], tensor2d([ [0, 0, 0], [0.76131237, 0.76131237, 0.76131237], [0.9639796, 0.9639796, 0.9639796], [0.99504817, 0.99504817, 0.99504817]])); expectTensorsClose(ys[1], tensor2d([ [0, 0, 0], [0.76131237, 0.76131237, 0.76131237], [0.9639796, 0.9639796, 0.9639796], [0.99504817, 0.99504817, 0.99504817]])); expectTensorsClose(ys[2], tensor2d([ [0, 0, 0], [0.9993292, 0.9993292, 0.9993292], [1.9993222, 1.9993222, 1.9993222], [2.9993203,2.9993203, 2.9993203]])); }); // Referernce Python code: // ```py // import keras // import numpy as np // // model = keras.Sequential() // model.add(keras.layers.Embedding(10, // 4, // input_length=3, // mask_zero=True, // embeddings_initializer='ones')) // model.add(keras.layers.LSTM(3, // return_sequences=True, // recurrent_initializer='ones', // kernel_initializer='ones', // bias_initializer='zeros')) // model.add(keras.layers.Dense(1, // kernel_initializer='ones', // bias_initializer='zeros')) // // xs = np.array([[0, 0, 0], // [1, 0, 0], // [1, 2, 0], // [1, 2, 3]]) // ys = model.predict(xs) // print(ys) // ``` it('With mask, returnSequences = true', () => { const model = tfl.sequential(); model.add(tfl.layers.embedding({ inputDim: 10, outputDim: 4, inputLength: 3, maskZero: true, embeddingsInitializer: 'ones' })); model.add(tfl.layers.lstm({ units: 3, returnSequences: true, recurrentInitializer: 'ones', kernelInitializer: 'ones', biasInitializer: 'zeros' })); model.add(tfl.layers.dense({ units: 1, kernelInitializer: 'ones', biasInitializer: 'zeros'})); const xs = tensor2d( [[0, 0, 0], [1, 0, 0], [1, 2, 0], [1, 2, 3]]); const ys = model.predict(xs) as Tensor; expectTensorsClose(ys, tensor3d( [[[0], [0], [0]], [[2.283937], [2.283937], [2.283937]], [[2.283937], [2.8919387], [2.8919387]], [[2.283937], [2.8919387], [2.9851446]]])); }); // Reference Python code: // ```py // import keras // import numpy as np // // model = keras.Sequential() // model.add(keras.layers.Embedding(10, // 4, // input_length=3, // mask_zero=True, // embeddings_initializer='ones')) // model.add(keras.layers.SimpleRNN(3, // return_sequences=True, // recurrent_initializer='ones', // kernel_initializer='ones', // bias_initializer='zeros')) // model.add(keras.layers.LSTM(3, // recurrent_initializer='ones', // kernel_initializer='ones', // bias_initializer='zeros')) // // xs = np.array([[0, 0, 0], // [1, 0, 0], // [1, 2, 0], // [1, 2, 3]]) // ys = model.predict(xs) // print(ys) // ``` it('Stacked RNNs with masking: correctness and no leak', () => { const model = tfl.sequential(); model.add(tfl.layers.embedding({ inputDim: 10, outputDim: 4, inputLength: 3, maskZero: true, embeddingsInitializer: 'ones' })); model.add(tfl.layers.simpleRNN({ units: 3, returnSequences: true, recurrentInitializer: 'ones', kernelInitializer: 'ones', biasInitializer: 'zeros' })); model.add(tfl.layers.lstm({ units: 3, recurrentInitializer: 'ones', kernelInitializer: 'ones', biasInitializer: 'zeros' })); const xs = tensor2d( [[0, 0, 0], [1, 0, 0], [1, 2, 0], [1, 2, 3]]); // Burn-in call for subsequent memory leak check. model.predict(xs); const numTensors0 = tfc.memory().numTensors; const ys = model.predict(xs) as Tensor; const numTensors1 = tfc.memory().numTensors; expectTensorsClose(ys, tensor2d( [[0, 0, 0], [0.75950104, 0.75950104, 0.75950104], [0.96367145, 0.96367145, 0.96367145], [0.9950049, 0.9950049, 0.9950049]])); ys.dispose(); // Assert no memory leak. expect(numTensors1).toEqual(numTensors0 + 1); }); }); describeMathCPU('LSTM-deserialization', () => { it('modelFromConfig', async () => { const model = await modelFromJSON(fakeLSTMModel); const encoderInputs = tfc.zeros([1, 3, 71], 'float32'); const decoderInputs = tfc.zeros([1, 3, 94], 'float32'); const outputs = model.predict([encoderInputs, decoderInputs]) as Tensor; expect(outputs.shape).toEqual([1, 3, 94]); }); it('Default recurrentActivation round trip', () => { const x = randomNormal([1, 2, 3]); const layer = tfl.layers.lstm({units: 4}) as LSTM; const y = layer.apply(x) as Tensor; const pythonicConfig = convertTsToPythonic(layer.getConfig()); // tslint:disable-next-line:no-any const tsConfig = convertPythonicToTs(pythonicConfig) as any; const layerPrime = tfl.layers.lstm(tsConfig) as LSTM; const yPrime = layer.apply(x) as Tensor; expectTensorsClose(yPrime, y); expect(layerPrime.recurrentActivation.getClassName()) .toEqual(layer.recurrentActivation.getClassName()); }); it('Non-default recurrentActivation round trip', () => { const x = randomNormal([1, 2, 3]); const layer = tfl.layers.lstm({units: 4, recurrentActivation: 'tanh'}) as LSTM; const y = layer.apply(x) as Tensor; const pythonicConfig = convertTsToPythonic(layer.getConfig()); // tslint:disable-next-line:no-any const tsConfig = convertPythonicToTs(pythonicConfig) as any; const layerPrime = tfl.layers.lstm(tsConfig) as LSTM; const yPrime = layer.apply(x) as Tensor; expectTensorsClose(yPrime, y); expect(layerPrime.recurrentActivation.getClassName()) .toEqual(layer.recurrentActivation.getClassName()); }); }); const fakeLSTMModel: ModelAndWeightsConfig = { modelTopology: { 'class_name': 'Model', 'keras_version': '2.1.2', 'config': { 'layers': [ { 'class_name': 'InputLayer', 'config': { 'dtype': 'float32', 'batch_input_shape': [null, null, 71], 'name': 'input_1', 'sparse': false }, 'inbound_nodes': [], 'name': 'input_1' }, { 'class_name': 'InputLayer', 'config': { 'dtype': 'float32', 'batch_input_shape': [null, null, 94], 'name': 'input_2', 'sparse': false }, 'inbound_nodes': [], 'name': 'input_2' }, { 'class_name': 'LSTM', 'config': { 'recurrent_activation': 'hard_sigmoid', 'trainable': true, 'recurrent_initializer': { 'class_name': 'VarianceScaling', 'config': { 'distribution': 'uniform', 'scale': 1.0, 'seed': null, 'mode': 'fan_avg' } }, 'use_bias': true, 'bias_regularizer': null, 'return_state': true, 'unroll': false, 'activation': 'tanh', 'bias_initializer': {'class_name': 'Zeros', 'config': {}}, 'units': 256, 'unit_forget_bias': true, 'activity_regularizer': null, 'recurrent_dropout': 0.0, 'kernel_initializer': { 'class_name': 'VarianceScaling', 'config': { 'distribution': 'uniform', 'scale': 1.0, 'seed': null, 'mode': 'fan_avg' } }, 'kernel_constraint': null, 'dropout': 0.0, 'stateful': false, 'recurrent_regularizer': null, 'name': 'lstm_1', 'bias_constraint': null, 'go_backwards': false, 'implementation': 1, 'kernel_regularizer': null, 'return_sequences': false, 'recurrent_constraint': null }, 'inbound_nodes': [[['input_1', 0, 0, {}]]], 'name': 'lstm_1' }, { 'class_name': 'LSTM', 'config': { 'recurrent_activation': 'hard_sigmoid', 'trainable': true, 'recurrent_initializer': { 'class_name': 'VarianceScaling', 'config': { 'distribution': 'uniform', 'scale': 1.0, 'seed': null, 'mode': 'fan_avg' } }, 'use_bias': true, 'bias_regularizer': null, 'return_state': true, 'unroll': false, 'activation': 'tanh', 'bias_initializer': {'class_name': 'Zeros', 'config': {}}, 'units': 256, 'unit_forget_bias': true, 'activity_regularizer': null, 'recurrent_dropout': 0.0, 'kernel_initializer': { 'class_name': 'VarianceScaling', 'config': { 'distribution': 'uniform', 'scale': 1.0, 'seed': null, 'mode': 'fan_avg' } }, 'kernel_constraint': null, 'dropout': 0.0, 'stateful': false, 'recurrent_regularizer': null, 'name': 'lstm_2', 'bias_constraint': null, 'go_backwards': false, 'implementation': 1, 'kernel_regularizer': null, 'return_sequences': true, 'recurrent_constraint': null }, 'inbound_nodes': [[ ['input_2', 0, 0, {}], ['lstm_1', 0, 1, {}], ['lstm_1', 0, 2, {}] ]], 'name': 'lstm_2' }, { 'class_name': 'Dense', 'config': { 'kernel_initializer': { 'class_name': 'VarianceScaling', 'config': { 'distribution': 'uniform', 'scale': 1.0, 'seed': null, 'mode': 'fan_avg' } }, 'name': 'dense_1', 'kernel_constraint': null, 'bias_regularizer': null, 'bias_constraint': null, 'activation': 'softmax', 'trainable': true, 'kernel_regularizer': null, 'bias_initializer': {'class_name': 'Zeros', 'config': {}}, 'units': 94, 'use_bias': true, 'activity_regularizer': null }, 'inbound_nodes': [[['lstm_2', 0, 0, {}]]], 'name': 'dense_1' } ], 'input_layers': [['input_1', 0, 0], ['input_2', 0, 0]], 'output_layers': [['dense_1', 0, 0]], 'name': 'model_1' }, 'backend': 'tensorflow' } }; describeMathCPU('StackedRNNCells Symbolic', () => { it('With SimpleRNNCell', () => { const stackedRNN = tfl.layers.rnn({ cell: tfl.layers.stackedRNNCells({ cells: [ tfl.layers.simpleRNNCell( {units: 3, recurrentInitializer: 'glorotNormal'}), tfl.layers.simpleRNNCell( {units: 2, recurrentInitializer: 'glorotNormal'}) ], }) }); const input = new tfl.SymbolicTensor('float32', [16, 10, 7], null, [], null); const output = stackedRNN.apply(input) as tfl.SymbolicTensor; expect(output.shape).toEqual([16, 2]); // 3 trainable weights from each cell. expect(stackedRNN.trainableWeights.length).toEqual(6); expect(stackedRNN.nonTrainableWeights.length).toEqual(0); // Kernel, recurrent kernel and bias of 1st cell. expect(stackedRNN.getWeights()[0].shape).toEqual([7, 3]); expect(stackedRNN.getWeights()[1].shape).toEqual([3, 3]); expect(stackedRNN.getWeights()[2].shape).toEqual([3]); // Kernel, recurrent kernel and bias of 2nd cell. expect(stackedRNN.getWeights()[3].shape).toEqual([3, 2]); expect(stackedRNN.getWeights()[4].shape).toEqual([2, 2]); expect(stackedRNN.getWeights()[5].shape).toEqual([2]); }); it('With LSTMCell', () => { const stackedRNN = tfl.layers.rnn({ cell: tfl.layers.stackedRNNCells({ cells: [ tfl.layers.lstmCell({units: 3, recurrentInitializer: 'glorotNormal'}), tfl.layers.lstmCell( {units: 2, recurrentInitializer: 'glorotNormal'}) ], }) }); const input = new tfl.SymbolicTensor('float32', [16, 10, 7], null, [], null); const output = stackedRNN.apply(input) as tfl.SymbolicTensor; expect(output.shape).toEqual([16, 2]); // 3 trainable weights from each cell. expect(stackedRNN.trainableWeights.length).toEqual(6); expect(stackedRNN.nonTrainableWeights.length).toEqual(0); // Kernel, recurrent kernel and bias of 1st cell. expect(stackedRNN.getWeights()[0].shape).toEqual([7, 12]); expect(stackedRNN.getWeights()[1].shape).toEqual([3, 12]); expect(stackedRNN.getWeights()[2].shape).toEqual([12]); // expect(stackedRNN.getWeights()[2].shape).toEqual([3]); // Kernel, recurrent kernel and bias of 2nd cell. expect(stackedRNN.getWeights()[3].shape).toEqual([3, 8]); expect(stackedRNN.getWeights()[4].shape).toEqual([2, 8]); expect(stackedRNN.getWeights()[5].shape).toEqual([8]); }); it('RNN with cell array creates StackedRNNCell', () => { const stackedRNN = tfl.layers.rnn({ cell: [ tfl.layers.gruCell({units: 3, recurrentInitializer: 'glorotNormal'}), tfl.layers.gruCell({units: 2, recurrentInitializer: 'glorotNormal'}), ], }); const input = new tfl.SymbolicTensor('float32', [16, 10, 7], null, [], null); const output = stackedRNN.apply(input) as tfl.SymbolicTensor; expect(output.shape).toEqual([16, 2]); // 3 trainable weights from each cell. expect(stackedRNN.trainableWeights.length).toEqual(6); expect(stackedRNN.nonTrainableWeights.length).toEqual(0); // Kernel, recurrent kernel and bias of 1st cell. expect(stackedRNN.getWeights()[0].shape).toEqual([7, 9]); expect(stackedRNN.getWeights()[1].shape).toEqual([3, 9]); expect(stackedRNN.getWeights()[2].shape).toEqual([9]); // expect(stackedRNN.getWeights()[2].shape).toEqual([3]); // Kernel, recurrent kernel and bias of 2nd cell. expect(stackedRNN.getWeights()[3].shape).toEqual([3, 6]); expect(stackedRNN.getWeights()[4].shape).toEqual([2, 6]); expect(stackedRNN.getWeights()[5].shape).toEqual([6]); }); }); describeMathCPU('Stacked RNN serialization', () => { it('StackedRNNCells', async () => { const model = tfl.sequential(); model.add(tfl.layers.dense({ units: 1, inputShape: [3, 4], kernelInitializer: 'ones' })); const cells = [ tfl.layers.lstmCell({ units: 5, kernelInitializer: 'ones', recurrentInitializer: 'ones' }), tfl.layers.lstmCell({ units: 6, kernelInitializer: 'ones', recurrentInitializer: 'ones' }) ]; const rnn = tfl.layers.rnn({cell: cells, returnSequences: true}); model.add(rnn); const xs = tfc.ones([1, 3, 4]).mul(0.1); const ys = model.predict(xs) as Tensor; const modelJSON = model.toJSON(null, false); const modelPrime = await tfl.models.modelFromJSON({modelTopology: modelJSON}); const ysPrime = modelPrime.predict(xs) as Tensor; expectTensorsClose(ysPrime, ys); }); }); describeMathGPU('StackedRNNCells Tensor', () => { // The golden values for assertion below can be obtained with the following // Python Keras code: // // ```python // import keras // import numpy as np // // stacked_rnn = keras.layers.RNN( // [ // keras.layers.SimpleRNNCell( // 3, // kernel_initializer='ones', // recurrent_initializer='ones', // use_bias=False), // keras.layers.GRUCell( // 2, // kernel_initializer='ones', // recurrent_initializer='ones', // use_bias=False), // keras.layers.LSTMCell( // 1, // kernel_initializer='ones', // recurrent_initializer='ones', // use_bias=False), // ]) // // t_input = keras.layers.Input(batch_shape=(2, 3, 4)) // t_output = stacked_rnn(t_input) // print(t_input.shape) // print(t_output.shape) // // model = keras.Model(t_input, t_output) // // input_val = np.array([ // [ // [0.1, -0.1, 0.2, -0.2], [-0.1, 0.1, -0.2, 0.2], // [0.1, 0.1, -0.2, -0.2] // ], // [ // [0.05, -0.05, 0.1, -0.1], [-0.05, 0.05, -0.1, 0.1], // [0.05, 0.05, -0.1, -0.1] // ] // ]) // print(model.predict(input_val)) // ``` it('Forward pass', () => { const stackedRNN = tfl.layers.rnn({ cell: tfl.layers.stackedRNNCells({ cells: [ tfl.layers.simpleRNNCell({ units: 3, recurrentInitializer: 'ones', kernelInitializer: 'ones', useBias: false }), tfl.layers.gruCell({ units: 2, recurrentInitializer: 'ones', kernelInitializer: 'ones', useBias: false }), tfl.layers.lstmCell({ units: 1, recurrentInitializer: 'ones', kernelInitializer: 'ones', useBias: false }), ], }) }); const input = tensor3d( [ [ [0.1, -0.1, 0.2, -0.2], [-0.1, 0.1, -0.2, 0.2], [0.1, 0.1, -0.2, -0.2] ], [ [0.05, -0.05, 0.1, -0.1], [-0.05, 0.05, -0.1, 0.1], [0.05, 0.05, -0.1, -0.1] ] ], [2, 3, 4]); const output = stackedRNN.apply(input) as Tensor; expectTensorsClose( output, tensor2d([[-0.07715216], [-0.05906887]], [2, 1])); }); });
the_stack
import * as msRest from "@azure/ms-rest-js"; import * as Models from "../models"; import * as Mappers from "../models/fileMappers"; import * as Parameters from "../models/parameters"; import { BatchServiceClientContext } from "../batchServiceClientContext"; /** Class representing a File. */ export class File { private readonly client: BatchServiceClientContext; /** * Create a File. * @param {BatchServiceClientContext} client Reference to the service client. */ constructor(client: BatchServiceClientContext) { this.client = client; } /** * @summary Deletes the specified Task file from the Compute Node where the Task ran. * @param jobId The ID of the Job that contains the Task. * @param taskId The ID of the Task whose file you want to delete. * @param filePath The path to the Task file or directory that you want to delete. * @param [options] The optional parameters * @returns Promise<Models.FileDeleteFromTaskResponse> */ deleteFromTask( jobId: string, taskId: string, filePath: string, options?: Models.FileDeleteFromTaskOptionalParams ): Promise<Models.FileDeleteFromTaskResponse>; /** * @param jobId The ID of the Job that contains the Task. * @param taskId The ID of the Task whose file you want to delete. * @param filePath The path to the Task file or directory that you want to delete. * @param callback The callback */ deleteFromTask( jobId: string, taskId: string, filePath: string, callback: msRest.ServiceCallback<void> ): void; /** * @param jobId The ID of the Job that contains the Task. * @param taskId The ID of the Task whose file you want to delete. * @param filePath The path to the Task file or directory that you want to delete. * @param options The optional parameters * @param callback The callback */ deleteFromTask( jobId: string, taskId: string, filePath: string, options: Models.FileDeleteFromTaskOptionalParams, callback: msRest.ServiceCallback<void> ): void; deleteFromTask( jobId: string, taskId: string, filePath: string, options?: Models.FileDeleteFromTaskOptionalParams | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void> ): Promise<Models.FileDeleteFromTaskResponse> { return this.client.sendOperationRequest( { jobId, taskId, filePath, options }, deleteFromTaskOperationSpec, callback ) as Promise<Models.FileDeleteFromTaskResponse>; } /** * Returns the content of the specified Task file. * @param jobId The ID of the Job that contains the Task. * @param taskId The ID of the Task whose file you want to retrieve. * @param filePath The path to the Task file that you want to get the content of. * @param [options] The optional parameters * @returns Promise<Models.FileGetFromTaskResponse> */ getFromTask( jobId: string, taskId: string, filePath: string, options?: Models.FileGetFromTaskOptionalParams ): Promise<Models.FileGetFromTaskResponse>; /** * @param jobId The ID of the Job that contains the Task. * @param taskId The ID of the Task whose file you want to retrieve. * @param filePath The path to the Task file that you want to get the content of. * @param callback The callback */ getFromTask( jobId: string, taskId: string, filePath: string, callback: msRest.ServiceCallback<void> ): void; /** * @param jobId The ID of the Job that contains the Task. * @param taskId The ID of the Task whose file you want to retrieve. * @param filePath The path to the Task file that you want to get the content of. * @param options The optional parameters * @param callback The callback */ getFromTask( jobId: string, taskId: string, filePath: string, options: Models.FileGetFromTaskOptionalParams, callback: msRest.ServiceCallback<void> ): void; getFromTask( jobId: string, taskId: string, filePath: string, options?: Models.FileGetFromTaskOptionalParams | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void> ): Promise<Models.FileGetFromTaskResponse> { return this.client.sendOperationRequest( { jobId, taskId, filePath, options }, getFromTaskOperationSpec, callback ) as Promise<Models.FileGetFromTaskResponse>; } /** * Gets the properties of the specified Task file. * @param jobId The ID of the Job that contains the Task. * @param taskId The ID of the Task whose file you want to get the properties of. * @param filePath The path to the Task file that you want to get the properties of. * @param [options] The optional parameters * @returns Promise<Models.FileGetPropertiesFromTaskResponse> */ getPropertiesFromTask( jobId: string, taskId: string, filePath: string, options?: Models.FileGetPropertiesFromTaskOptionalParams ): Promise<Models.FileGetPropertiesFromTaskResponse>; /** * @param jobId The ID of the Job that contains the Task. * @param taskId The ID of the Task whose file you want to get the properties of. * @param filePath The path to the Task file that you want to get the properties of. * @param callback The callback */ getPropertiesFromTask( jobId: string, taskId: string, filePath: string, callback: msRest.ServiceCallback<void> ): void; /** * @param jobId The ID of the Job that contains the Task. * @param taskId The ID of the Task whose file you want to get the properties of. * @param filePath The path to the Task file that you want to get the properties of. * @param options The optional parameters * @param callback The callback */ getPropertiesFromTask( jobId: string, taskId: string, filePath: string, options: Models.FileGetPropertiesFromTaskOptionalParams, callback: msRest.ServiceCallback<void> ): void; getPropertiesFromTask( jobId: string, taskId: string, filePath: string, options?: Models.FileGetPropertiesFromTaskOptionalParams | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void> ): Promise<Models.FileGetPropertiesFromTaskResponse> { return this.client.sendOperationRequest( { jobId, taskId, filePath, options }, getPropertiesFromTaskOperationSpec, callback ) as Promise<Models.FileGetPropertiesFromTaskResponse>; } /** * @summary Deletes the specified file from the Compute Node. * @param poolId The ID of the Pool that contains the Compute Node. * @param nodeId The ID of the Compute Node from which you want to delete the file. * @param filePath The path to the file or directory that you want to delete. * @param [options] The optional parameters * @returns Promise<Models.FileDeleteFromComputeNodeResponse> */ deleteFromComputeNode( poolId: string, nodeId: string, filePath: string, options?: Models.FileDeleteFromComputeNodeOptionalParams ): Promise<Models.FileDeleteFromComputeNodeResponse>; /** * @param poolId The ID of the Pool that contains the Compute Node. * @param nodeId The ID of the Compute Node from which you want to delete the file. * @param filePath The path to the file or directory that you want to delete. * @param callback The callback */ deleteFromComputeNode( poolId: string, nodeId: string, filePath: string, callback: msRest.ServiceCallback<void> ): void; /** * @param poolId The ID of the Pool that contains the Compute Node. * @param nodeId The ID of the Compute Node from which you want to delete the file. * @param filePath The path to the file or directory that you want to delete. * @param options The optional parameters * @param callback The callback */ deleteFromComputeNode( poolId: string, nodeId: string, filePath: string, options: Models.FileDeleteFromComputeNodeOptionalParams, callback: msRest.ServiceCallback<void> ): void; deleteFromComputeNode( poolId: string, nodeId: string, filePath: string, options?: Models.FileDeleteFromComputeNodeOptionalParams | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void> ): Promise<Models.FileDeleteFromComputeNodeResponse> { return this.client.sendOperationRequest( { poolId, nodeId, filePath, options }, deleteFromComputeNodeOperationSpec, callback ) as Promise<Models.FileDeleteFromComputeNodeResponse>; } /** * Returns the content of the specified Compute Node file. * @param poolId The ID of the Pool that contains the Compute Node. * @param nodeId The ID of the Compute Node that contains the file. * @param filePath The path to the Compute Node file that you want to get the content of. * @param [options] The optional parameters * @returns Promise<Models.FileGetFromComputeNodeResponse> */ getFromComputeNode( poolId: string, nodeId: string, filePath: string, options?: Models.FileGetFromComputeNodeOptionalParams ): Promise<Models.FileGetFromComputeNodeResponse>; /** * @param poolId The ID of the Pool that contains the Compute Node. * @param nodeId The ID of the Compute Node that contains the file. * @param filePath The path to the Compute Node file that you want to get the content of. * @param callback The callback */ getFromComputeNode( poolId: string, nodeId: string, filePath: string, callback: msRest.ServiceCallback<void> ): void; /** * @param poolId The ID of the Pool that contains the Compute Node. * @param nodeId The ID of the Compute Node that contains the file. * @param filePath The path to the Compute Node file that you want to get the content of. * @param options The optional parameters * @param callback The callback */ getFromComputeNode( poolId: string, nodeId: string, filePath: string, options: Models.FileGetFromComputeNodeOptionalParams, callback: msRest.ServiceCallback<void> ): void; getFromComputeNode( poolId: string, nodeId: string, filePath: string, options?: Models.FileGetFromComputeNodeOptionalParams | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void> ): Promise<Models.FileGetFromComputeNodeResponse> { return this.client.sendOperationRequest( { poolId, nodeId, filePath, options }, getFromComputeNodeOperationSpec, callback ) as Promise<Models.FileGetFromComputeNodeResponse>; } /** * Gets the properties of the specified Compute Node file. * @param poolId The ID of the Pool that contains the Compute Node. * @param nodeId The ID of the Compute Node that contains the file. * @param filePath The path to the Compute Node file that you want to get the properties of. * @param [options] The optional parameters * @returns Promise<Models.FileGetPropertiesFromComputeNodeResponse> */ getPropertiesFromComputeNode( poolId: string, nodeId: string, filePath: string, options?: Models.FileGetPropertiesFromComputeNodeOptionalParams ): Promise<Models.FileGetPropertiesFromComputeNodeResponse>; /** * @param poolId The ID of the Pool that contains the Compute Node. * @param nodeId The ID of the Compute Node that contains the file. * @param filePath The path to the Compute Node file that you want to get the properties of. * @param callback The callback */ getPropertiesFromComputeNode( poolId: string, nodeId: string, filePath: string, callback: msRest.ServiceCallback<void> ): void; /** * @param poolId The ID of the Pool that contains the Compute Node. * @param nodeId The ID of the Compute Node that contains the file. * @param filePath The path to the Compute Node file that you want to get the properties of. * @param options The optional parameters * @param callback The callback */ getPropertiesFromComputeNode( poolId: string, nodeId: string, filePath: string, options: Models.FileGetPropertiesFromComputeNodeOptionalParams, callback: msRest.ServiceCallback<void> ): void; getPropertiesFromComputeNode( poolId: string, nodeId: string, filePath: string, options?: Models.FileGetPropertiesFromComputeNodeOptionalParams | msRest.ServiceCallback<void>, callback?: msRest.ServiceCallback<void> ): Promise<Models.FileGetPropertiesFromComputeNodeResponse> { return this.client.sendOperationRequest( { poolId, nodeId, filePath, options }, getPropertiesFromComputeNodeOperationSpec, callback ) as Promise<Models.FileGetPropertiesFromComputeNodeResponse>; } /** * @summary Lists the files in a Task's directory on its Compute Node. * @param jobId The ID of the Job that contains the Task. * @param taskId The ID of the Task whose files you want to list. * @param [options] The optional parameters * @returns Promise<Models.FileListFromTaskResponse> */ listFromTask( jobId: string, taskId: string, options?: Models.FileListFromTaskOptionalParams ): Promise<Models.FileListFromTaskResponse>; /** * @param jobId The ID of the Job that contains the Task. * @param taskId The ID of the Task whose files you want to list. * @param callback The callback */ listFromTask( jobId: string, taskId: string, callback: msRest.ServiceCallback<Models.NodeFileListResult> ): void; /** * @param jobId The ID of the Job that contains the Task. * @param taskId The ID of the Task whose files you want to list. * @param options The optional parameters * @param callback The callback */ listFromTask( jobId: string, taskId: string, options: Models.FileListFromTaskOptionalParams, callback: msRest.ServiceCallback<Models.NodeFileListResult> ): void; listFromTask( jobId: string, taskId: string, options?: | Models.FileListFromTaskOptionalParams | msRest.ServiceCallback<Models.NodeFileListResult>, callback?: msRest.ServiceCallback<Models.NodeFileListResult> ): Promise<Models.FileListFromTaskResponse> { return this.client.sendOperationRequest( { jobId, taskId, options }, listFromTaskOperationSpec, callback ) as Promise<Models.FileListFromTaskResponse>; } /** * @summary Lists all of the files in Task directories on the specified Compute Node. * @param poolId The ID of the Pool that contains the Compute Node. * @param nodeId The ID of the Compute Node whose files you want to list. * @param [options] The optional parameters * @returns Promise<Models.FileListFromComputeNodeResponse> */ listFromComputeNode( poolId: string, nodeId: string, options?: Models.FileListFromComputeNodeOptionalParams ): Promise<Models.FileListFromComputeNodeResponse>; /** * @param poolId The ID of the Pool that contains the Compute Node. * @param nodeId The ID of the Compute Node whose files you want to list. * @param callback The callback */ listFromComputeNode( poolId: string, nodeId: string, callback: msRest.ServiceCallback<Models.NodeFileListResult> ): void; /** * @param poolId The ID of the Pool that contains the Compute Node. * @param nodeId The ID of the Compute Node whose files you want to list. * @param options The optional parameters * @param callback The callback */ listFromComputeNode( poolId: string, nodeId: string, options: Models.FileListFromComputeNodeOptionalParams, callback: msRest.ServiceCallback<Models.NodeFileListResult> ): void; listFromComputeNode( poolId: string, nodeId: string, options?: | Models.FileListFromComputeNodeOptionalParams | msRest.ServiceCallback<Models.NodeFileListResult>, callback?: msRest.ServiceCallback<Models.NodeFileListResult> ): Promise<Models.FileListFromComputeNodeResponse> { return this.client.sendOperationRequest( { poolId, nodeId, options }, listFromComputeNodeOperationSpec, callback ) as Promise<Models.FileListFromComputeNodeResponse>; } /** * @summary Lists the files in a Task's directory on its Compute Node. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.FileListFromTaskResponse> */ listFromTaskNext( nextPageLink: string, options?: Models.FileListFromTaskNextOptionalParams ): Promise<Models.FileListFromTaskResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listFromTaskNext( nextPageLink: string, callback: msRest.ServiceCallback<Models.NodeFileListResult> ): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listFromTaskNext( nextPageLink: string, options: Models.FileListFromTaskNextOptionalParams, callback: msRest.ServiceCallback<Models.NodeFileListResult> ): void; listFromTaskNext( nextPageLink: string, options?: | Models.FileListFromTaskNextOptionalParams | msRest.ServiceCallback<Models.NodeFileListResult>, callback?: msRest.ServiceCallback<Models.NodeFileListResult> ): Promise<Models.FileListFromTaskResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listFromTaskNextOperationSpec, callback ) as Promise<Models.FileListFromTaskResponse>; } /** * @summary Lists all of the files in Task directories on the specified Compute Node. * @param nextPageLink The NextLink from the previous successful call to List operation. * @param [options] The optional parameters * @returns Promise<Models.FileListFromComputeNodeResponse> */ listFromComputeNodeNext( nextPageLink: string, options?: Models.FileListFromComputeNodeNextOptionalParams ): Promise<Models.FileListFromComputeNodeResponse>; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param callback The callback */ listFromComputeNodeNext( nextPageLink: string, callback: msRest.ServiceCallback<Models.NodeFileListResult> ): void; /** * @param nextPageLink The NextLink from the previous successful call to List operation. * @param options The optional parameters * @param callback The callback */ listFromComputeNodeNext( nextPageLink: string, options: Models.FileListFromComputeNodeNextOptionalParams, callback: msRest.ServiceCallback<Models.NodeFileListResult> ): void; listFromComputeNodeNext( nextPageLink: string, options?: | Models.FileListFromComputeNodeNextOptionalParams | msRest.ServiceCallback<Models.NodeFileListResult>, callback?: msRest.ServiceCallback<Models.NodeFileListResult> ): Promise<Models.FileListFromComputeNodeResponse> { return this.client.sendOperationRequest( { nextPageLink, options }, listFromComputeNodeNextOperationSpec, callback ) as Promise<Models.FileListFromComputeNodeResponse>; } } // Operation Specifications const serializer = new msRest.Serializer(Mappers); const deleteFromTaskOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "jobs/{jobId}/tasks/{taskId}/files/{filePath}", urlParameters: [Parameters.batchUrl, Parameters.jobId, Parameters.taskId, Parameters.filePath], queryParameters: [Parameters.recursive, Parameters.apiVersion, Parameters.timeout37], headerParameters: [ Parameters.acceptLanguage, Parameters.clientRequestId46, Parameters.returnClientRequestId46, Parameters.ocpDate46 ], responses: { 200: { headersMapper: Mappers.FileDeleteFromTaskHeaders }, default: { bodyMapper: Mappers.BatchError, headersMapper: Mappers.FileDeleteFromTaskHeaders } }, serializer }; const getFromTaskOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "jobs/{jobId}/tasks/{taskId}/files/{filePath}", urlParameters: [Parameters.batchUrl, Parameters.jobId, Parameters.taskId, Parameters.filePath], queryParameters: [Parameters.apiVersion, Parameters.timeout38], headerParameters: [ Parameters.acceptLanguage, Parameters.clientRequestId47, Parameters.returnClientRequestId47, Parameters.ocpDate47, Parameters.ocpRange0, Parameters.ifModifiedSince15, Parameters.ifUnmodifiedSince15 ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Stream" } }, headersMapper: Mappers.FileGetFromTaskHeaders }, default: { bodyMapper: Mappers.BatchError, headersMapper: Mappers.FileGetFromTaskHeaders } }, serializer }; const getPropertiesFromTaskOperationSpec: msRest.OperationSpec = { httpMethod: "HEAD", path: "jobs/{jobId}/tasks/{taskId}/files/{filePath}", urlParameters: [Parameters.batchUrl, Parameters.jobId, Parameters.taskId, Parameters.filePath], queryParameters: [Parameters.apiVersion, Parameters.timeout39], headerParameters: [ Parameters.acceptLanguage, Parameters.clientRequestId48, Parameters.returnClientRequestId48, Parameters.ocpDate48, Parameters.ifModifiedSince16, Parameters.ifUnmodifiedSince16 ], responses: { 200: { headersMapper: Mappers.FileGetPropertiesFromTaskHeaders }, default: { bodyMapper: Mappers.BatchError, headersMapper: Mappers.FileGetPropertiesFromTaskHeaders } }, serializer }; const deleteFromComputeNodeOperationSpec: msRest.OperationSpec = { httpMethod: "DELETE", path: "pools/{poolId}/nodes/{nodeId}/files/{filePath}", urlParameters: [Parameters.batchUrl, Parameters.poolId, Parameters.nodeId, Parameters.filePath], queryParameters: [Parameters.recursive, Parameters.apiVersion, Parameters.timeout40], headerParameters: [ Parameters.acceptLanguage, Parameters.clientRequestId49, Parameters.returnClientRequestId49, Parameters.ocpDate49 ], responses: { 200: { headersMapper: Mappers.FileDeleteFromComputeNodeHeaders }, default: { bodyMapper: Mappers.BatchError, headersMapper: Mappers.FileDeleteFromComputeNodeHeaders } }, serializer }; const getFromComputeNodeOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "pools/{poolId}/nodes/{nodeId}/files/{filePath}", urlParameters: [Parameters.batchUrl, Parameters.poolId, Parameters.nodeId, Parameters.filePath], queryParameters: [Parameters.apiVersion, Parameters.timeout41], headerParameters: [ Parameters.acceptLanguage, Parameters.clientRequestId50, Parameters.returnClientRequestId50, Parameters.ocpDate50, Parameters.ocpRange1, Parameters.ifModifiedSince17, Parameters.ifUnmodifiedSince17 ], responses: { 200: { bodyMapper: { serializedName: "parsedResponse", type: { name: "Stream" } }, headersMapper: Mappers.FileGetFromComputeNodeHeaders }, default: { bodyMapper: Mappers.BatchError, headersMapper: Mappers.FileGetFromComputeNodeHeaders } }, serializer }; const getPropertiesFromComputeNodeOperationSpec: msRest.OperationSpec = { httpMethod: "HEAD", path: "pools/{poolId}/nodes/{nodeId}/files/{filePath}", urlParameters: [Parameters.batchUrl, Parameters.poolId, Parameters.nodeId, Parameters.filePath], queryParameters: [Parameters.apiVersion, Parameters.timeout42], headerParameters: [ Parameters.acceptLanguage, Parameters.clientRequestId51, Parameters.returnClientRequestId51, Parameters.ocpDate51, Parameters.ifModifiedSince18, Parameters.ifUnmodifiedSince18 ], responses: { 200: { headersMapper: Mappers.FileGetPropertiesFromComputeNodeHeaders }, default: { bodyMapper: Mappers.BatchError, headersMapper: Mappers.FileGetPropertiesFromComputeNodeHeaders } }, serializer }; const listFromTaskOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "jobs/{jobId}/tasks/{taskId}/files", urlParameters: [Parameters.batchUrl, Parameters.jobId, Parameters.taskId], queryParameters: [ Parameters.recursive, Parameters.apiVersion, Parameters.filter8, Parameters.maxResults9, Parameters.timeout43 ], headerParameters: [ Parameters.acceptLanguage, Parameters.clientRequestId52, Parameters.returnClientRequestId52, Parameters.ocpDate52 ], responses: { 200: { bodyMapper: Mappers.NodeFileListResult, headersMapper: Mappers.FileListFromTaskHeaders }, default: { bodyMapper: Mappers.BatchError, headersMapper: Mappers.FileListFromTaskHeaders } }, serializer }; const listFromComputeNodeOperationSpec: msRest.OperationSpec = { httpMethod: "GET", path: "pools/{poolId}/nodes/{nodeId}/files", urlParameters: [Parameters.batchUrl, Parameters.poolId, Parameters.nodeId], queryParameters: [ Parameters.recursive, Parameters.apiVersion, Parameters.filter9, Parameters.maxResults10, Parameters.timeout44 ], headerParameters: [ Parameters.acceptLanguage, Parameters.clientRequestId53, Parameters.returnClientRequestId53, Parameters.ocpDate53 ], responses: { 200: { bodyMapper: Mappers.NodeFileListResult, headersMapper: Mappers.FileListFromComputeNodeHeaders }, default: { bodyMapper: Mappers.BatchError, headersMapper: Mappers.FileListFromComputeNodeHeaders } }, serializer }; const listFromTaskNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "{batchUrl}", path: "{nextLink}", urlParameters: [Parameters.nextPageLink], queryParameters: [Parameters.recursive, Parameters.apiVersion], headerParameters: [ Parameters.acceptLanguage, Parameters.clientRequestId54, Parameters.returnClientRequestId54, Parameters.ocpDate54 ], responses: { 200: { bodyMapper: Mappers.NodeFileListResult, headersMapper: Mappers.FileListFromTaskHeaders }, default: { bodyMapper: Mappers.BatchError, headersMapper: Mappers.FileListFromTaskHeaders } }, serializer }; const listFromComputeNodeNextOperationSpec: msRest.OperationSpec = { httpMethod: "GET", baseUrl: "{batchUrl}", path: "{nextLink}", urlParameters: [Parameters.nextPageLink], queryParameters: [Parameters.recursive, Parameters.apiVersion], headerParameters: [ Parameters.acceptLanguage, Parameters.clientRequestId55, Parameters.returnClientRequestId55, Parameters.ocpDate55 ], responses: { 200: { bodyMapper: Mappers.NodeFileListResult, headersMapper: Mappers.FileListFromComputeNodeHeaders }, default: { bodyMapper: Mappers.BatchError, headersMapper: Mappers.FileListFromComputeNodeHeaders } }, serializer };
the_stack
import { OperationParameter, OperationURLParameter, OperationQueryParameter } from "@azure/core-client"; import { SearchRequest as SearchRequestMapper, SuggestRequest as SuggestRequestMapper, IndexBatch as IndexBatchMapper, AutocompleteRequest as AutocompleteRequestMapper } from "../models/mappers"; export const accept: OperationParameter = { parameterPath: "accept", mapper: { defaultValue: "application/json", isConstant: true, serializedName: "Accept", type: { name: "String" } } }; export const endpoint: OperationURLParameter = { parameterPath: "endpoint", mapper: { serializedName: "endpoint", required: true, type: { name: "String" } }, skipEncoding: true }; export const indexName: OperationURLParameter = { parameterPath: "indexName", mapper: { serializedName: "indexName", required: true, type: { name: "String" } } }; export const xMsClientRequestId: OperationParameter = { parameterPath: ["options", "requestOptionsParam", "xMsClientRequestId"], mapper: { serializedName: "x-ms-client-request-id", type: { name: "Uuid" } } }; export const apiVersion: OperationQueryParameter = { parameterPath: "apiVersion", mapper: { serializedName: "api-version", required: true, type: { name: "String" } } }; export const searchText: OperationQueryParameter = { parameterPath: ["options", "searchText"], mapper: { serializedName: "search", type: { name: "String" } } }; export const includeTotalResultCount: OperationQueryParameter = { parameterPath: ["options", "searchOptions", "includeTotalResultCount"], mapper: { serializedName: "$count", type: { name: "Boolean" } } }; export const facets: OperationQueryParameter = { parameterPath: ["options", "searchOptions", "facets"], mapper: { serializedName: "facet", type: { name: "Sequence", element: { type: { name: "String" } } } }, collectionFormat: "Multi" }; export const filter: OperationQueryParameter = { parameterPath: ["options", "searchOptions", "filter"], mapper: { serializedName: "$filter", type: { name: "String" } } }; export const highlightFields: OperationQueryParameter = { parameterPath: ["options", "searchOptions", "highlightFields"], mapper: { serializedName: "highlight", type: { name: "Sequence", element: { type: { name: "String" } } } }, collectionFormat: "CSV" }; export const highlightPostTag: OperationQueryParameter = { parameterPath: ["options", "searchOptions", "highlightPostTag"], mapper: { serializedName: "highlightPostTag", type: { name: "String" } } }; export const highlightPreTag: OperationQueryParameter = { parameterPath: ["options", "searchOptions", "highlightPreTag"], mapper: { serializedName: "highlightPreTag", type: { name: "String" } } }; export const minimumCoverage: OperationQueryParameter = { parameterPath: ["options", "searchOptions", "minimumCoverage"], mapper: { serializedName: "minimumCoverage", type: { name: "Number" } } }; export const orderBy: OperationQueryParameter = { parameterPath: ["options", "searchOptions", "orderBy"], mapper: { serializedName: "$orderby", type: { name: "Sequence", element: { type: { name: "String" } } } }, collectionFormat: "CSV" }; export const queryType: OperationQueryParameter = { parameterPath: ["options", "searchOptions", "queryType"], mapper: { serializedName: "queryType", type: { name: "Enum", allowedValues: ["simple", "full", "semantic"] } } }; export const scoringParameters: OperationQueryParameter = { parameterPath: ["options", "searchOptions", "scoringParameters"], mapper: { serializedName: "scoringParameter", type: { name: "Sequence", element: { type: { name: "String" } } } }, collectionFormat: "Multi" }; export const scoringProfile: OperationQueryParameter = { parameterPath: ["options", "searchOptions", "scoringProfile"], mapper: { serializedName: "scoringProfile", type: { name: "String" } } }; export const semanticConfiguration: OperationQueryParameter = { parameterPath: ["options", "searchOptions", "semanticConfiguration"], mapper: { serializedName: "semanticConfiguration", type: { name: "String" } } }; export const searchFields: OperationQueryParameter = { parameterPath: ["options", "searchOptions", "searchFields"], mapper: { serializedName: "searchFields", type: { name: "Sequence", element: { type: { name: "String" } } } }, collectionFormat: "CSV" }; export const queryLanguage: OperationQueryParameter = { parameterPath: ["options", "searchOptions", "queryLanguage"], mapper: { serializedName: "queryLanguage", type: { name: "String" } } }; export const speller: OperationQueryParameter = { parameterPath: ["options", "searchOptions", "speller"], mapper: { serializedName: "speller", type: { name: "String" } } }; export const answers: OperationQueryParameter = { parameterPath: ["options", "searchOptions", "answers"], mapper: { serializedName: "answers", type: { name: "String" } } }; export const searchMode: OperationQueryParameter = { parameterPath: ["options", "searchOptions", "searchMode"], mapper: { serializedName: "searchMode", type: { name: "Enum", allowedValues: ["any", "all"] } } }; export const scoringStatistics: OperationQueryParameter = { parameterPath: ["options", "searchOptions", "scoringStatistics"], mapper: { serializedName: "scoringStatistics", type: { name: "Enum", allowedValues: ["local", "global"] } } }; export const sessionId: OperationQueryParameter = { parameterPath: ["options", "searchOptions", "sessionId"], mapper: { serializedName: "sessionId", type: { name: "String" } } }; export const select: OperationQueryParameter = { parameterPath: ["options", "searchOptions", "select"], mapper: { serializedName: "$select", type: { name: "Sequence", element: { type: { name: "String" } } } }, collectionFormat: "CSV" }; export const skip: OperationQueryParameter = { parameterPath: ["options", "searchOptions", "skip"], mapper: { serializedName: "$skip", type: { name: "Number" } } }; export const top: OperationQueryParameter = { parameterPath: ["options", "searchOptions", "top"], mapper: { serializedName: "$top", type: { name: "Number" } } }; export const captions: OperationQueryParameter = { parameterPath: ["options", "searchOptions", "captions"], mapper: { serializedName: "captions", type: { name: "String" } } }; export const semanticFields: OperationQueryParameter = { parameterPath: ["options", "searchOptions", "semanticFields"], mapper: { serializedName: "semanticFields", type: { name: "Sequence", element: { type: { name: "String" } } } }, collectionFormat: "CSV" }; export const contentType: OperationParameter = { parameterPath: ["options", "contentType"], mapper: { defaultValue: "application/json", isConstant: true, serializedName: "Content-Type", type: { name: "String" } } }; export const searchRequest: OperationParameter = { parameterPath: "searchRequest", mapper: SearchRequestMapper }; export const key: OperationURLParameter = { parameterPath: "key", mapper: { serializedName: "key", required: true, type: { name: "String" } } }; export const selectedFields: OperationQueryParameter = { parameterPath: ["options", "selectedFields"], mapper: { serializedName: "$select", type: { name: "Sequence", element: { type: { name: "String" } } } }, collectionFormat: "CSV" }; export const searchText1: OperationQueryParameter = { parameterPath: "searchText", mapper: { serializedName: "search", required: true, type: { name: "String" } } }; export const suggesterName: OperationQueryParameter = { parameterPath: "suggesterName", mapper: { serializedName: "suggesterName", required: true, type: { name: "String" } } }; export const filter1: OperationQueryParameter = { parameterPath: ["options", "suggestOptions", "filter"], mapper: { serializedName: "$filter", type: { name: "String" } } }; export const useFuzzyMatching: OperationQueryParameter = { parameterPath: ["options", "suggestOptions", "useFuzzyMatching"], mapper: { serializedName: "fuzzy", type: { name: "Boolean" } } }; export const highlightPostTag1: OperationQueryParameter = { parameterPath: ["options", "suggestOptions", "highlightPostTag"], mapper: { serializedName: "highlightPostTag", type: { name: "String" } } }; export const highlightPreTag1: OperationQueryParameter = { parameterPath: ["options", "suggestOptions", "highlightPreTag"], mapper: { serializedName: "highlightPreTag", type: { name: "String" } } }; export const minimumCoverage1: OperationQueryParameter = { parameterPath: ["options", "suggestOptions", "minimumCoverage"], mapper: { serializedName: "minimumCoverage", type: { name: "Number" } } }; export const orderBy1: OperationQueryParameter = { parameterPath: ["options", "suggestOptions", "orderBy"], mapper: { serializedName: "$orderby", type: { name: "Sequence", element: { type: { name: "String" } } } }, collectionFormat: "CSV" }; export const searchFields1: OperationQueryParameter = { parameterPath: ["options", "suggestOptions", "searchFields"], mapper: { serializedName: "searchFields", type: { name: "Sequence", element: { type: { name: "String" } } } }, collectionFormat: "CSV" }; export const select1: OperationQueryParameter = { parameterPath: ["options", "suggestOptions", "select"], mapper: { serializedName: "$select", type: { name: "Sequence", element: { type: { name: "String" } } } }, collectionFormat: "CSV" }; export const top1: OperationQueryParameter = { parameterPath: ["options", "suggestOptions", "top"], mapper: { serializedName: "$top", type: { name: "Number" } } }; export const suggestRequest: OperationParameter = { parameterPath: "suggestRequest", mapper: SuggestRequestMapper }; export const batch: OperationParameter = { parameterPath: "batch", mapper: IndexBatchMapper }; export const autocompleteMode: OperationQueryParameter = { parameterPath: ["options", "autocompleteOptions", "autocompleteMode"], mapper: { serializedName: "autocompleteMode", type: { name: "Enum", allowedValues: ["oneTerm", "twoTerms", "oneTermWithContext"] } } }; export const filter2: OperationQueryParameter = { parameterPath: ["options", "autocompleteOptions", "filter"], mapper: { serializedName: "$filter", type: { name: "String" } } }; export const useFuzzyMatching1: OperationQueryParameter = { parameterPath: ["options", "autocompleteOptions", "useFuzzyMatching"], mapper: { serializedName: "fuzzy", type: { name: "Boolean" } } }; export const highlightPostTag2: OperationQueryParameter = { parameterPath: ["options", "autocompleteOptions", "highlightPostTag"], mapper: { serializedName: "highlightPostTag", type: { name: "String" } } }; export const highlightPreTag2: OperationQueryParameter = { parameterPath: ["options", "autocompleteOptions", "highlightPreTag"], mapper: { serializedName: "highlightPreTag", type: { name: "String" } } }; export const minimumCoverage2: OperationQueryParameter = { parameterPath: ["options", "autocompleteOptions", "minimumCoverage"], mapper: { serializedName: "minimumCoverage", type: { name: "Number" } } }; export const searchFields2: OperationQueryParameter = { parameterPath: ["options", "autocompleteOptions", "searchFields"], mapper: { serializedName: "searchFields", type: { name: "Sequence", element: { type: { name: "String" } } } }, collectionFormat: "CSV" }; export const top2: OperationQueryParameter = { parameterPath: ["options", "autocompleteOptions", "top"], mapper: { serializedName: "$top", type: { name: "Number" } } }; export const autocompleteRequest: OperationParameter = { parameterPath: "autocompleteRequest", mapper: AutocompleteRequestMapper };
the_stack
import globalContextInfo from '../utils/global-context-info'; import { isNativeFunction } from '../utils/overriding'; const NATIVE_CODE_RE = /\[native code]/; class NativeMethods { isStoragePropsLocatedInProto: boolean; createDocumentFragment: Document['createDocumentFragment']; createElement: Document['createElement']; createElementNS: Document['createElementNS']; createTextNode: Document['createTextNode']; documentOpenPropOwnerName: string; documentClosePropOwnerName: string; documentWritePropOwnerName: string; documentWriteLnPropOwnerName: string; documentOpen: Document['open']; documentClose: Document['close']; documentWrite: Document['write']; documentWriteLn: Document['writeln']; elementFromPoint: Document['elementFromPoint']; caretRangeFromPoint: any; caretPositionFromPoint: any; getElementById: Document['getElementById']; getElementsByClassName: Document['getElementsByClassName']; getElementsByName: Document['getElementsByName']; getElementsByTagName: Document['getElementsByTagName']; querySelector: any; querySelectorAll: any; createHTMLDocument: any; registerElement: any; documentAddEventListener: any; documentRemoveEventListener: any; documentCreateEvent: any; documentCreateTouch: any; documentCreateTouchList: any; documentCookiePropOwnerName: string; documentReferrerGetter: any; documentStyleSheetsGetter: any; documentActiveElementGetter: any; documentCookieGetter: any; documentCookieSetter: any; documentDocumentURIGetter: any; documentTitleGetter: any; documentTitleSetter: any; appendChild: Node['appendChild']; attachShadow: Element['attachShadow']; append: Element['append']; prepend: Element['prepend']; after: Element['after']; insertAdjacentMethodsOwner: Element; insertAdjacentElement: Element['insertAdjacentElement']; insertAdjacentHTML: Element['insertAdjacentHTML']; insertAdjacentText: Element['insertAdjacentText']; replaceChild: any; cloneNode: any; elementGetElementsByClassName: any; elementGetElementsByTagName: Function; elementQuerySelector: any; elementQuerySelectorAll: any; getAttribute: any; getAttributeNS: any; insertBefore: Node['insertBefore']; insertCell: any; insertTableRow: any; insertTBodyRow: any; importScripts: (...urls: string[]) => void removeAttribute: any; removeAttributeNS: any; removeChild: Node['removeChild']; remove: Element['remove']; elementReplaceWith: Element['replaceWith']; setAttribute: any; setAttributeNS: any; hasAttribute: any; hasAttributeNS: any; hasAttributes: any; anchorToString: any; matches: any; closest: any; appendData: any; addEventListener: any; removeEventListener: any; blur: any; click: any; dispatchEvent: any; focus: any; select: any; setSelectionRange: any; textAreaSetSelectionRange: any; svgFocus: any; svgBlur: any; htmlElementStylePropOwnerName: string; htmlElementStyleGetter: any; htmlElementStyleSetter: any; styleCssTextGetter: any; styleCssTextSetter: any; eval: any; formSubmit: any; documentFragmentQuerySelector: any; documentFragmentQuerySelectorAll: any; preventDefault: any; historyPushState: any; historyReplaceState: any; windowDispatchEvent: any; postMessage: any; windowOpen: Window['open']; setTimeout: Window['setTimeout']; setInterval: Window['setInterval']; clearTimeout: Window['clearTimeout']; clearInterval: Window['clearInterval']; registerProtocolHandler: any; sendBeacon: any; xhrAbort: XMLHttpRequest['abort']; xhrOpen: XMLHttpRequest['open']; xhrSend: XMLHttpRequest['send']; xhrAddEventListener: any; xhrRemoveEventListener: any; xhrGetResponseHeader: XMLHttpRequest['getResponseHeader']; xhrGetAllResponseHeaders: XMLHttpRequest['getAllResponseHeaders']; xhrSetRequestHeader: XMLHttpRequest['setRequestHeader']; xhrOverrideMimeType: any; xhrDispatchEvent: any; registerServiceWorker: any; getRegistrationServiceWorker: any; createContextualFragment: any; performanceNow: any; fetch: Window['fetch']; Request: typeof Request; requestUrlGetter: (this: Request) => Request['url']; requestReferrerGetter: (this: Request) => Request['referrer']; Headers: typeof Headers; headersSet: Headers['set']; headersGet: Headers['get']; headersDelete: Headers['delete']; headersEntries: Headers['entries']; headersForEach: Headers['forEach']; headersValues: Headers['values']; windowAddEventListener: any; windowRemoveEventListener: any; WindowPointerEvent: any; WindowMSPointerEvent: any; WindowTouch: any; WindowTouchEvent: any; WindowKeyboardEvent: any; WindowFocusEvent: any; WindowTextEvent: any; WindowInputEvent: typeof InputEvent; WindowMouseEvent: any; windowOriginGetter: (this: Window) => string; windowOriginSetter: (this: Window, value: string) => void; canvasContextDrawImage: any; formDataAppend: FormData['append']; date: DateConstructor; dateNow: DateConstructor['now']; math: any; mathRandom: any; // eslint-disable-next-line @typescript-eslint/ban-types objectToString: Object['toString']; objectAssign: ObjectConstructor['assign']; objectKeys: ObjectConstructor['keys']; objectDefineProperty: ObjectConstructor['defineProperty']; objectDefineProperties: ObjectConstructor['defineProperties']; objectCreate: ObjectConstructor['create']; objectIsExtensible: ObjectConstructor['isExtensible']; objectIsFrozen: ObjectConstructor['isFrozen']; objectGetOwnPropertyDescriptor: ObjectConstructor['getOwnPropertyDescriptor']; objectHasOwnProperty: ObjectConstructor['hasOwnProperty']; objectGetOwnPropertyNames: ObjectConstructor['getOwnPropertyNames']; objectGetPrototypeOf: ObjectConstructor['getPrototypeOf']; objectSetPrototypeOf: ObjectConstructor['setPrototypeOf']; objectGetOwnPropertySymbols: ObjectConstructor['getOwnPropertySymbols']; arraySlice: any; arrayConcat: any; arrayFilter: any; arrayFind: any; arrayMap: any; arrayJoin: any; arraySplice: any; arrayUnshift: any; arrayForEach: any; arrayIndexOf: any; arraySome: any; arrayReverse: any; arrayReduce: any; arrayFrom: any; isArray: ArrayConstructor['isArray'] DOMParserParseFromString: any; arrayBufferIsView: any; elementHTMLPropOwnerName: string; objectDataSetter: any; inputTypeSetter: any; inputValueSetter: any; inputDisabledSetter: any; inputRequiredSetter: any; textAreaValueSetter: any; imageSrcSetter: any; scriptSrcSetter: any; embedSrcSetter: any; sourceSrcSetter: any; mediaSrcSetter: any; inputSrcSetter: any; frameSrcSetter: any; iframeSrcSetter: any; iframeSrcdocSetter: (this: HTMLIFrameElement, val: HTMLIFrameElement['srcdoc']) => void; anchorHrefSetter: any; linkHrefSetter: any; linkRelSetter: any; linkAsSetter: any; areaHrefSetter: any; baseHrefSetter: any; anchorHostSetter: any; anchorHostnameSetter: any; anchorPathnameSetter: any; anchorPortSetter: any; anchorProtocolSetter: any; anchorSearchSetter: any; anchorTargetSetter: any; formTargetSetter: any; areaTargetSetter: any; baseTargetSetter: any; inputFormTargetSetter: any; buttonFormTargetSetter: any; svgAnimStrBaseValSetter: any; inputAutocompleteSetter: any; formActionSetter: any; inputFormActionSetter: any; buttonFormActionSetter: any; iframeSandboxSetter: any; htmlElementOnloadSetter: any; nodeTextContentSetter: any; htmlElementInnerTextSetter: any; scriptTextSetter: any; anchorTextSetter: any; elementInnerHTMLSetter: any; elementOuterHTMLSetter: any; scriptIntegritySetter: any; linkIntegritySetter: any; isEventPropsLocatedInProto: boolean; winOnBeforeUnloadSetter: any; winOnUnloadSetter: any; winOnPageHideSetter: any; winOnMessageSetter: any; winOnErrorSetter: any; winOnUnhandledRejectionSetter: any; winOnHashChangeSetter: any; webSocketUrlGetter: any; elementClassListPropOwnerName: string; elementClassListGetter: any; messageEventOriginGetter: any; htmlCollectionLengthGetter: (this: HTMLCollection) => HTMLCollection['length']; nodeListLengthGetter: (this: NodeListOf<ChildNode>) => NodeListOf<ChildNode>['length']; nodeParentNodeGetter: (this: Node) => Node['parentNode']; nodeChildNodesGetter: (this: Node) => Node['childNodes']; elementChildrenGetter: (this: Element) => Element['children']; elementChildElementCountGetter: any; inputFilesGetter: any; styleSheetHrefGetter: any; objectDataGetter: any; inputTypeGetter: any; inputValueGetter: any; inputDisabledGetter: any; inputRequiredGetter: any; textAreaValueGetter: any; imageSrcGetter: any; scriptSrcGetter: any; embedSrcGetter: any; sourceSrcGetter: any; mediaSrcGetter: any; inputSrcGetter: any; frameSrcGetter: any; iframeSrcGetter: any; iframeSrcdocGetter: (this: HTMLIFrameElement) => HTMLIFrameElement['srcdoc']; anchorHrefGetter: any; linkHrefGetter: any; linkRelGetter: any; areaHrefGetter: any; baseHrefGetter: any; anchorHostGetter: any; anchorHostnameGetter: any; anchorPathnameGetter: any; anchorPortGetter: any; anchorProtocolGetter: any; anchorSearchGetter: any; anchorTargetGetter: any; formTargetGetter: any; areaTargetGetter: any; baseTargetGetter: any; inputFormTargetGetter: any; buttonFormTargetGetter: any; svgImageHrefGetter: any; svgAnimStrAnimValGetter: any; svgAnimStrBaseValGetter: any; inputAutocompleteGetter: any; formActionGetter: any; inputFormActionGetter: any; buttonFormActionGetter: any; iframeSandboxGetter: any; contentWindowGetter: any; contentDocumentGetter: any; frameContentWindowGetter: any; nodeTextContentGetter: any; htmlElementInnerTextGetter: any; scriptTextGetter: any; anchorTextGetter: any; elementInnerHTMLGetter: any; elementOuterHTMLGetter: any; nodeFirstChildGetter: any; nodeLastChildGetter: any; nodeNextSiblingGetter: any; nodePrevSiblingGetter: any; elementFirstElementChildGetter: any; elementLastElementChildGetter: any; elementNextElementSiblingGetter: any; elementPrevElementSiblingGetter: any; scriptIntegrityGetter: any; linkIntegrityGetter: any; anchorOriginGetter: any; cssStyleSheetHrefGetter: any; nodeBaseURIGetter: any; elementAttributesPropOwnerName: string; elementAttributesGetter: any; performanceEntryNameGetter: any; messageEventDataGetter: (this: MessageEvent) => MessageEvent['data']; htmlManifestGetter: any; htmlManifestSetter: any; titleElementTextGetter: Function; titleElementTextSetter: Function; responseStatusGetter: any; responseTypeGetter: any; responseUrlGetter: any; promiseThen: any; promiseReject: any; xhrResponseURLGetter: any; winLocalStorageGetter: (this: Window) => Storage; winSessionStorageGetter: (this: Window) => Storage; mutationRecordNextSiblingGetter: any; mutationRecordPrevSiblingGetter: any; styleGetPropertyValue: any; styleSetProperty: any; styleRemoveProperty: any; styleInsertRule: any; console: any; consoleMeths: any; tokenListAdd: any; tokenListRemove: any; tokenListReplace: any; tokenListSupports: any; tokenListToggle: any; tokenListContains: any; tokenListValueSetter: (value: string) => void; windowClass: any; documentClass: any; locationClass: any; elementClass: any; svgElementClass: any; Worker: typeof Worker; MessageChannel: typeof MessageChannel; Array: typeof Array; ArrayBuffer: any; Uint8Array: typeof Uint8Array; Uint16Array: typeof Uint16Array; Uint32Array: typeof Uint32Array; DataView: any; Blob: typeof Blob; File: any; XMLHttpRequest: typeof XMLHttpRequest; Image: any; Function: any; Error: any; functionToString: Function; FontFace: any; StorageEvent: typeof StorageEvent; MutationObserver: any; EventSource: any; Proxy: any; WebSocket: any; HTMLCollection: any; NodeList: any; Node: any; DataTransfer: any; DataTransferItemList: any; DataTransferItem: any; FileList: any; createScript: any; runInDebugContext: any; runInContext: any; runInNewContext: any; runInThisContext: any; scrollTo: any; crypto: Crypto; cryptoGetRandomValues: Function; URL: typeof URL; storageGetItem: Storage['getItem']; storageSetItem: Storage['setItem']; storageRemoveItem: Storage['removeItem']; storageClear: Storage['clear']; storageKey: Storage['key']; storageLengthGetter: (this: Storage) => Storage['length']; eventTargetGetter: (this: Event) => Event['target']; constructor (doc?: Document, win?: Window & typeof globalThis) { win = win || globalContextInfo.global; this.refreshWindowMeths(win, globalContextInfo.isInWorker); this.refreshWorkerMeths(win); if (globalContextInfo.isInWorker) return; this.refreshDocumentMeths(doc, win); this.refreshElementMeths(doc, win); } static _getDocumentPropOwnerName (docPrototype, propName: string) { return docPrototype.hasOwnProperty(propName) ? 'Document' : 'HTMLDocument'; } getStoragesPropsOwner (win: Window & typeof globalThis) { return this.isStoragePropsLocatedInProto ? win.Window.prototype : win; } refreshWorkerMeths (scope: any /* WorkerGlobalScope */) { this.importScripts = scope.importScripts; } refreshDocumentMeths (doc: Document, win: Window & typeof globalThis) { doc = doc || document; win = win || window as Window & typeof globalThis; const docPrototype = win.Document.prototype; // Dom this.createDocumentFragment = docPrototype.createDocumentFragment; this.createElement = docPrototype.createElement; this.createElementNS = docPrototype.createElementNS; this.createTextNode = docPrototype.createTextNode; this.documentOpenPropOwnerName = NativeMethods._getDocumentPropOwnerName(docPrototype, 'open'); this.documentClosePropOwnerName = NativeMethods._getDocumentPropOwnerName(docPrototype, 'close'); this.documentWritePropOwnerName = NativeMethods._getDocumentPropOwnerName(docPrototype, 'write'); this.documentWriteLnPropOwnerName = NativeMethods._getDocumentPropOwnerName(docPrototype, 'writeln'); this.documentOpen = win[this.documentOpenPropOwnerName].prototype.open; this.documentClose = win[this.documentClosePropOwnerName].prototype.close; this.documentWrite = win[this.documentWritePropOwnerName].prototype.write; this.documentWriteLn = win[this.documentWriteLnPropOwnerName].prototype.writeln; this.elementFromPoint = docPrototype.elementFromPoint; this.caretRangeFromPoint = docPrototype.caretRangeFromPoint; this.caretPositionFromPoint = docPrototype.caretPositionFromPoint; this.getElementById = docPrototype.getElementById; this.getElementsByClassName = docPrototype.getElementsByClassName; this.getElementsByName = docPrototype.getElementsByName; this.getElementsByTagName = docPrototype.getElementsByTagName; this.querySelector = docPrototype.querySelector; this.querySelectorAll = docPrototype.querySelectorAll; this.createHTMLDocument = win.DOMImplementation.prototype.createHTMLDocument; // @ts-ignore if (doc.registerElement) { // @ts-ignore this.registerElement = docPrototype.registerElement; } // Event // NOTE: IE11 has no EventTarget so we should save "Event" methods separately if (!win.EventTarget) { this.documentAddEventListener = docPrototype.addEventListener; this.documentRemoveEventListener = docPrototype.removeEventListener; } this.documentCreateEvent = docPrototype.createEvent; // @ts-ignore Deprecated this.documentCreateTouch = docPrototype.createTouch; // @ts-ignore Deprecated this.documentCreateTouchList = docPrototype.createTouchList; // getters/setters this.documentCookiePropOwnerName = NativeMethods._getDocumentPropOwnerName(docPrototype, 'cookie'); const documentCookieDescriptor = win.Object.getOwnPropertyDescriptor(win[this.documentCookiePropOwnerName].prototype, 'cookie'); // TODO: remove this condition after the GH-1649 fix if (!this.isNativeCode(documentCookieDescriptor.get) || !this.isNativeCode(documentCookieDescriptor.get.toString)) { try { const parentNativeMethods = win.parent['%hammerhead%'].nativeMethods; documentCookieDescriptor.get = parentNativeMethods.documentCookieGetter; documentCookieDescriptor.set = parentNativeMethods.documentCookieSetter; } catch {} // eslint-disable-line no-empty } this.documentReferrerGetter = win.Object.getOwnPropertyDescriptor(docPrototype, 'referrer').get; this.documentStyleSheetsGetter = win.Object.getOwnPropertyDescriptor(docPrototype, 'styleSheets').get; this.documentActiveElementGetter = win.Object.getOwnPropertyDescriptor(docPrototype, 'activeElement').get; this.documentCookieGetter = documentCookieDescriptor.get; this.documentCookieSetter = documentCookieDescriptor.set; const documentDocumentURIDescriptor = win.Object.getOwnPropertyDescriptor(docPrototype, 'documentURI'); if (documentDocumentURIDescriptor) this.documentDocumentURIGetter = documentDocumentURIDescriptor.get; const documentTitleDescriptor = win.Object.getOwnPropertyDescriptor(docPrototype, 'title'); this.documentTitleGetter = documentTitleDescriptor.get; this.documentTitleSetter = documentTitleDescriptor.set; } refreshElementMeths (doc, win: Window & typeof globalThis) { win = win || window as Window & typeof globalThis; const createElement = (tagName => this.createElement.call(doc || document, tagName)) as Document['createElement']; const nativeElement = createElement('div'); const createTextNode = data => this.createTextNode.call(doc || document, data); const textNode = createTextNode('text'); // Dom this.appendChild = win.Node.prototype.appendChild; this.append = win.Element.prototype.append; this.prepend = win.Element.prototype.prepend; this.after = win.Element.prototype.after; this.attachShadow = win.Element.prototype.attachShadow; this.replaceChild = nativeElement.replaceChild; this.cloneNode = nativeElement.cloneNode; this.elementGetElementsByClassName = nativeElement.getElementsByClassName; this.elementGetElementsByTagName = nativeElement.getElementsByTagName; this.elementQuerySelector = nativeElement.querySelector; this.elementQuerySelectorAll = nativeElement.querySelectorAll; this.getAttribute = nativeElement.getAttribute; this.getAttributeNS = nativeElement.getAttributeNS; this.insertBefore = nativeElement.insertBefore; this.insertCell = createElement('tr').insertCell; this.insertTableRow = createElement('table').insertRow; this.insertTBodyRow = createElement('tbody').insertRow; this.removeAttribute = nativeElement.removeAttribute; this.removeAttributeNS = nativeElement.removeAttributeNS; this.removeChild = win.Node.prototype.removeChild; this.remove = win.Element.prototype.remove; this.elementReplaceWith = win.Element.prototype.replaceWith; this.setAttribute = nativeElement.setAttribute; this.setAttributeNS = nativeElement.setAttributeNS; this.hasAttribute = nativeElement.hasAttribute; this.hasAttributeNS = nativeElement.hasAttributeNS; this.hasAttributes = nativeElement.hasAttributes; this.anchorToString = win.HTMLAnchorElement.prototype.toString; this.matches = nativeElement.matches || nativeElement.msMatchesSelector; this.closest = nativeElement.closest; // NOTE: The 'insertAdjacent...' methods is located in HTMLElement prototype in IE11 only this.insertAdjacentMethodsOwner = win.Element.prototype.hasOwnProperty('insertAdjacentElement') ? win.Element.prototype : win.HTMLElement.prototype; this.insertAdjacentElement = this.insertAdjacentMethodsOwner.insertAdjacentElement; this.insertAdjacentHTML = this.insertAdjacentMethodsOwner.insertAdjacentHTML; this.insertAdjacentText = this.insertAdjacentMethodsOwner.insertAdjacentText; // Text node this.appendData = textNode.appendData; // TODO: remove this condition after the GH-1649 fix if (!this.isNativeCode(this.elementGetElementsByTagName)) { try { const parentNativeMethods = win.parent['%hammerhead%'].nativeMethods; this.elementGetElementsByTagName = parentNativeMethods.elementGetElementsByTagName; } // eslint-disable-next-line no-empty catch (e) { } } // Event if (win.EventTarget) { this.addEventListener = win.EventTarget.prototype.addEventListener; this.removeEventListener = win.EventTarget.prototype.removeEventListener; this.dispatchEvent = win.EventTarget.prototype.dispatchEvent; } // NOTE: IE11 has no EventTarget else { this.addEventListener = nativeElement.addEventListener; this.removeEventListener = nativeElement.removeEventListener; this.dispatchEvent = nativeElement.dispatchEvent; } this.blur = nativeElement.blur; this.click = nativeElement.click; this.focus = nativeElement.focus; // @ts-ignore this.select = window.TextRange ? createElement('body').createTextRange().select : null; this.setSelectionRange = createElement('input').setSelectionRange; this.textAreaSetSelectionRange = createElement('textarea').setSelectionRange; this.svgFocus = win.SVGElement ? win.SVGElement.prototype.focus : this.focus; this.svgBlur = win.SVGElement ? win.SVGElement.prototype.blur : this.blur; // Style // NOTE: The 'style' descriptor is located in the Element.prototype in the Safari on IOS this.htmlElementStylePropOwnerName = win.Element.prototype.hasOwnProperty('style') ? 'Element' : 'HTMLElement'; const htmlElementStyleDescriptor = win.Object.getOwnPropertyDescriptor(win[this.htmlElementStylePropOwnerName].prototype, 'style'); this.htmlElementStyleGetter = htmlElementStyleDescriptor.get; // NOTE: IE does not allow to set a style property if (htmlElementStyleDescriptor.set) this.htmlElementStyleSetter = htmlElementStyleDescriptor.set; const styleCssTextDescriptor = win.Object.getOwnPropertyDescriptor(win.CSSStyleDeclaration.prototype, 'cssText'); this.styleCssTextGetter = styleCssTextDescriptor.get; this.styleCssTextSetter = styleCssTextDescriptor.set; } _refreshGettersAndSetters (win, isInWorker = false) { win = win || window; const winProto = win.constructor.prototype; // NOTE: Event properties is located in window prototype only in IE11 this.isEventPropsLocatedInProto = winProto.hasOwnProperty('onerror'); const eventPropsOwner = this.isEventPropsLocatedInProto ? winProto : win; const winOnBeforeUnloadDescriptor = win.Object.getOwnPropertyDescriptor(eventPropsOwner, 'onbeforeunload'); const winOnUnloadDescriptor = win.Object.getOwnPropertyDescriptor(eventPropsOwner, 'onunload'); const winOnPageHideDescriptor = win.Object.getOwnPropertyDescriptor(eventPropsOwner, 'onpagehide'); const winOnMessageDescriptor = win.Object.getOwnPropertyDescriptor(eventPropsOwner, 'onmessage'); const winOnErrorDescriptor = win.Object.getOwnPropertyDescriptor(eventPropsOwner, 'onerror'); const winOnHashChangeDescriptor = win.Object.getOwnPropertyDescriptor(eventPropsOwner, 'onhashchange'); this.winOnBeforeUnloadSetter = winOnBeforeUnloadDescriptor && winOnBeforeUnloadDescriptor.set; this.winOnUnloadSetter = winOnUnloadDescriptor && winOnUnloadDescriptor.set; this.winOnPageHideSetter = winOnPageHideDescriptor && winOnPageHideDescriptor.set; this.winOnMessageSetter = winOnMessageDescriptor && winOnMessageDescriptor.set; this.winOnErrorSetter = winOnErrorDescriptor && winOnErrorDescriptor.set; this.winOnHashChangeSetter = winOnHashChangeDescriptor && winOnHashChangeDescriptor.set; const winOnUnhandledRejectionDescriptor = win.Object.getOwnPropertyDescriptor(eventPropsOwner, 'onunhandledrejection'); if (winOnUnhandledRejectionDescriptor) this.winOnUnhandledRejectionSetter = winOnUnhandledRejectionDescriptor.set; // Getters if (win.WebSocket) { const urlPropDescriptor = win.Object.getOwnPropertyDescriptor(win.WebSocket.prototype, 'url'); if (urlPropDescriptor && urlPropDescriptor.get && urlPropDescriptor.configurable) this.webSocketUrlGetter = urlPropDescriptor.get; } this.messageEventOriginGetter = win.Object.getOwnPropertyDescriptor(win.MessageEvent.prototype, 'origin').get; // NOTE: At present we proxy only the PerformanceNavigationTiming. // Another types of the PerformanceEntry will be fixed later // https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEntry if (win.PerformanceNavigationTiming) this.performanceEntryNameGetter = win.Object.getOwnPropertyDescriptor(win.PerformanceEntry.prototype, 'name').get; const dataPropDescriptor = win.Object.getOwnPropertyDescriptor(win.MessageEvent.prototype, 'data'); // NOTE: This condition is used for the Android 6.0 browser if (dataPropDescriptor) this.messageEventDataGetter = dataPropDescriptor.get; if (win.fetch) { this.responseStatusGetter = win.Object.getOwnPropertyDescriptor(win.Response.prototype, 'status').get; this.responseTypeGetter = win.Object.getOwnPropertyDescriptor(win.Response.prototype, 'type').get; this.responseUrlGetter = win.Object.getOwnPropertyDescriptor(win.Response.prototype, 'url').get; this.requestUrlGetter = win.Object.getOwnPropertyDescriptor(win.Request.prototype, 'url').get; this.requestReferrerGetter = win.Object.getOwnPropertyDescriptor(win.Request.prototype, 'referrer').get; } if (win.XMLHttpRequest) { const xhrResponseURLDescriptor = win.Object.getOwnPropertyDescriptor(win.XMLHttpRequest.prototype, 'responseURL'); // NOTE: IE doesn't support the 'responseURL' property if (xhrResponseURLDescriptor) this.xhrResponseURLGetter = xhrResponseURLDescriptor.get; } // eslint-disable-next-line no-restricted-properties if (win.Window) { // NOTE: The 'localStorage' and 'sessionStorage' properties is located in window prototype only in IE11 this.isStoragePropsLocatedInProto = win.Window.prototype.hasOwnProperty('localStorage'); const storagesPropsOwner = this.getStoragesPropsOwner(win); this.winLocalStorageGetter = win.Object.getOwnPropertyDescriptor(storagesPropsOwner, 'localStorage').get; this.winSessionStorageGetter = win.Object.getOwnPropertyDescriptor(storagesPropsOwner, 'sessionStorage').get; } if (isInWorker) return; this.storageGetItem = win.Storage.prototype.getItem; this.storageSetItem = win.Storage.prototype.setItem; this.storageRemoveItem = win.Storage.prototype.removeItem; this.storageClear = win.Storage.prototype.clear; this.storageKey = win.Storage.prototype.key; this.storageLengthGetter = win.Object.getOwnPropertyDescriptor(win.Storage.prototype, 'length'); const objectDataDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLObjectElement.prototype, 'data'); const inputTypeDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLInputElement.prototype, 'type'); const inputValueDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLInputElement.prototype, 'value'); const inputDisabledDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLInputElement.prototype, 'disabled'); const inputRequiredDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLInputElement.prototype, 'required'); const textAreaValueDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLTextAreaElement.prototype, 'value'); const imageSrcDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLImageElement.prototype, 'src'); const scriptSrcDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLScriptElement.prototype, 'src'); const scriptIntegrityDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLScriptElement.prototype, 'integrity'); const embedSrcDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLEmbedElement.prototype, 'src'); const sourceSrcDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLSourceElement.prototype, 'src'); const mediaSrcDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLMediaElement.prototype, 'src'); const inputSrcDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLInputElement.prototype, 'src'); const frameSrcDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLFrameElement.prototype, 'src'); const iframeSrcDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLIFrameElement.prototype, 'src'); const anchorHrefDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLAnchorElement.prototype, 'href'); const linkHrefDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLLinkElement.prototype, 'href'); const linkIntegrityDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLLinkElement.prototype, 'integrity'); const linkRelDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLLinkElement.prototype, 'rel'); const linkAsDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLLinkElement.prototype, 'as'); const areaHrefDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLAreaElement.prototype, 'href'); const baseHrefDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLBaseElement.prototype, 'href'); const anchorHostDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLAnchorElement.prototype, 'host'); const anchorHostnameDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLAnchorElement.prototype, 'hostname'); const anchorPathnameDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLAnchorElement.prototype, 'pathname'); const anchorPortDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLAnchorElement.prototype, 'port'); const anchorProtocolDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLAnchorElement.prototype, 'protocol'); const anchorSearchDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLAnchorElement.prototype, 'search'); const anchorTargetDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLAnchorElement.prototype, 'target'); const formTargetDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLFormElement.prototype, 'target'); const areaTargetDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLAreaElement.prototype, 'target'); const baseTargetDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLBaseElement.prototype, 'target'); const inputFormTargetDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLInputElement.prototype, 'formTarget'); const buttonFormTargetDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLButtonElement.prototype, 'formTarget'); const svgImageHrefDescriptor = win.Object.getOwnPropertyDescriptor(win.SVGImageElement.prototype, 'href'); const svgAnimStrAnimValDescriptor = win.Object.getOwnPropertyDescriptor(win.SVGAnimatedString.prototype, 'animVal'); const svgAnimStrBaseValDescriptor = win.Object.getOwnPropertyDescriptor(win.SVGAnimatedString.prototype, 'baseVal'); const inputAutocompleteDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLInputElement.prototype, 'autocomplete'); const formActionDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLFormElement.prototype, 'action'); const inputFormActionDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLInputElement.prototype, 'formAction'); const buttonFormActionDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLButtonElement.prototype, 'formAction'); const nodeTextContentDescriptor = win.Object.getOwnPropertyDescriptor(win.Node.prototype, 'textContent'); const htmlElementInnerTextDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLElement.prototype, 'innerText'); const scriptTextDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLScriptElement.prototype, 'text'); const anchorTextDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLAnchorElement.prototype, 'text'); const titleElementTextDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLTitleElement.prototype, 'text'); const iframeSandboxDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLIFrameElement.prototype, 'sandbox'); const windowOriginDescriptor = win.Object.getOwnPropertyDescriptor(win, 'origin'); if (windowOriginDescriptor) { this.windowOriginGetter = windowOriginDescriptor.get; this.windowOriginSetter = windowOriginDescriptor.set; } // NOTE: We need 'disabled' property only for Chrome. // In Chrome it's located in HTMLInputElement.prototype // But in IE11 it's located in HTMLElement.prototype // So we need the null check if (inputDisabledDescriptor) { this.inputDisabledSetter = inputDisabledDescriptor.set; this.inputDisabledGetter = inputDisabledDescriptor.get; } // NOTE: Html properties is located in HTMLElement prototype in IE11 only this.elementHTMLPropOwnerName = win.Element.prototype.hasOwnProperty('innerHTML') ? 'Element' : 'HTMLElement'; const elementInnerHTMLDescriptor = win.Object.getOwnPropertyDescriptor(win[this.elementHTMLPropOwnerName].prototype, 'innerHTML'); const elementOuterHTMLDescriptor = win.Object.getOwnPropertyDescriptor(win[this.elementHTMLPropOwnerName].prototype, 'outerHTML'); // Setters this.objectDataSetter = objectDataDescriptor.set; this.inputTypeSetter = inputTypeDescriptor.set; this.inputValueSetter = inputValueDescriptor.set; this.inputRequiredSetter = inputRequiredDescriptor.set; this.textAreaValueSetter = textAreaValueDescriptor.set; this.imageSrcSetter = imageSrcDescriptor.set; this.scriptSrcSetter = scriptSrcDescriptor.set; this.embedSrcSetter = embedSrcDescriptor.set; this.sourceSrcSetter = sourceSrcDescriptor.set; this.mediaSrcSetter = mediaSrcDescriptor.set; this.inputSrcSetter = inputSrcDescriptor.set; this.frameSrcSetter = frameSrcDescriptor.set; this.iframeSrcSetter = iframeSrcDescriptor.set; this.anchorHrefSetter = anchorHrefDescriptor.set; this.linkHrefSetter = linkHrefDescriptor.set; this.linkRelSetter = linkRelDescriptor.set; this.linkAsSetter = linkAsDescriptor && linkAsDescriptor.set; this.areaHrefSetter = areaHrefDescriptor.set; this.baseHrefSetter = baseHrefDescriptor.set; this.anchorHostSetter = anchorHostDescriptor.set; this.anchorHostnameSetter = anchorHostnameDescriptor.set; this.anchorPathnameSetter = anchorPathnameDescriptor.set; this.anchorPortSetter = anchorPortDescriptor.set; this.anchorProtocolSetter = anchorProtocolDescriptor.set; this.anchorSearchSetter = anchorSearchDescriptor.set; this.anchorTargetSetter = anchorTargetDescriptor.set; this.formTargetSetter = formTargetDescriptor.set; this.areaTargetSetter = areaTargetDescriptor.set; this.baseTargetSetter = baseTargetDescriptor.set; this.inputFormTargetSetter = inputFormTargetDescriptor.set; this.buttonFormTargetSetter = buttonFormTargetDescriptor.set; this.svgAnimStrBaseValSetter = svgAnimStrBaseValDescriptor.set; this.inputAutocompleteSetter = inputAutocompleteDescriptor.set; this.formActionSetter = formActionDescriptor.set; this.inputFormActionSetter = inputFormActionDescriptor.set; this.buttonFormActionSetter = buttonFormActionDescriptor.set; this.iframeSandboxSetter = iframeSandboxDescriptor.set; this.htmlElementOnloadSetter = win.Object.getOwnPropertyDescriptor(win.HTMLElement.prototype, 'onload').set; this.nodeTextContentSetter = nodeTextContentDescriptor.set; this.htmlElementInnerTextSetter = htmlElementInnerTextDescriptor.set; this.scriptTextSetter = scriptTextDescriptor.set; this.anchorTextSetter = anchorTextDescriptor.set; this.elementInnerHTMLSetter = elementInnerHTMLDescriptor.set; this.elementOuterHTMLSetter = elementOuterHTMLDescriptor.set; // NOTE: Some browsers (for example, Edge, Internet Explorer 11, Safari) don't support the 'integrity' property. if (scriptIntegrityDescriptor && linkIntegrityDescriptor) { this.scriptIntegritySetter = scriptIntegrityDescriptor.set; this.linkIntegritySetter = linkIntegrityDescriptor.set; } this.titleElementTextSetter = titleElementTextDescriptor.set; // NOTE: the classList property is located in HTMLElement prototype in IE11 this.elementClassListPropOwnerName = win.Element.prototype.hasOwnProperty('classList') ? 'Element' : 'HTMLElement'; this.elementClassListGetter = win.Object.getOwnPropertyDescriptor(win[this.elementClassListPropOwnerName].prototype, 'classList').get; this.htmlCollectionLengthGetter = win.Object.getOwnPropertyDescriptor(win.HTMLCollection.prototype, 'length').get; this.nodeListLengthGetter = win.Object.getOwnPropertyDescriptor(win.NodeList.prototype, 'length').get; this.elementChildElementCountGetter = win.Object.getOwnPropertyDescriptor(win.Element.prototype, 'childElementCount').get; this.inputFilesGetter = win.Object.getOwnPropertyDescriptor(win.HTMLInputElement.prototype, 'files').get; this.styleSheetHrefGetter = win.Object.getOwnPropertyDescriptor(win.StyleSheet.prototype, 'href').get; this.objectDataGetter = objectDataDescriptor.get; this.inputTypeGetter = inputTypeDescriptor.get; this.inputValueGetter = inputValueDescriptor.get; this.inputRequiredGetter = inputRequiredDescriptor.get; this.textAreaValueGetter = textAreaValueDescriptor.get; this.imageSrcGetter = imageSrcDescriptor.get; this.scriptSrcGetter = scriptSrcDescriptor.get; this.embedSrcGetter = embedSrcDescriptor.get; this.sourceSrcGetter = sourceSrcDescriptor.get; this.mediaSrcGetter = mediaSrcDescriptor.get; this.inputSrcGetter = inputSrcDescriptor.get; this.frameSrcGetter = frameSrcDescriptor.get; this.iframeSrcGetter = iframeSrcDescriptor.get; this.anchorHrefGetter = anchorHrefDescriptor.get; this.linkHrefGetter = linkHrefDescriptor.get; this.linkRelGetter = linkRelDescriptor.get; this.areaHrefGetter = areaHrefDescriptor.get; this.baseHrefGetter = baseHrefDescriptor.get; this.anchorHostGetter = anchorHostDescriptor.get; this.anchorHostnameGetter = anchorHostnameDescriptor.get; this.anchorPathnameGetter = anchorPathnameDescriptor.get; this.anchorPortGetter = anchorPortDescriptor.get; this.anchorProtocolGetter = anchorProtocolDescriptor.get; this.anchorSearchGetter = anchorSearchDescriptor.get; this.anchorTargetGetter = anchorTargetDescriptor.get; this.formTargetGetter = formTargetDescriptor.get; this.areaTargetGetter = areaTargetDescriptor.get; this.baseTargetGetter = baseTargetDescriptor.get; this.inputFormTargetGetter = inputFormTargetDescriptor.get; this.buttonFormTargetGetter = buttonFormTargetDescriptor.get; this.svgImageHrefGetter = svgImageHrefDescriptor.get; this.svgAnimStrAnimValGetter = svgAnimStrAnimValDescriptor.get; this.svgAnimStrBaseValGetter = svgAnimStrBaseValDescriptor.get; this.inputAutocompleteGetter = inputAutocompleteDescriptor.get; this.formActionGetter = formActionDescriptor.get; this.inputFormActionGetter = inputFormActionDescriptor.get; this.buttonFormActionGetter = buttonFormActionDescriptor.get; this.iframeSandboxGetter = iframeSandboxDescriptor.get; this.contentWindowGetter = win.Object.getOwnPropertyDescriptor(win.HTMLIFrameElement.prototype, 'contentWindow').get; this.contentDocumentGetter = win.Object.getOwnPropertyDescriptor(win.HTMLIFrameElement.prototype, 'contentDocument').get; this.frameContentWindowGetter = win.Object.getOwnPropertyDescriptor(win.HTMLFrameElement.prototype, 'contentWindow').get; this.nodeTextContentGetter = nodeTextContentDescriptor.get; this.htmlElementInnerTextGetter = htmlElementInnerTextDescriptor.get; this.scriptTextGetter = scriptTextDescriptor.get; this.anchorTextGetter = anchorTextDescriptor.get; this.elementInnerHTMLGetter = elementInnerHTMLDescriptor.get; this.elementOuterHTMLGetter = elementOuterHTMLDescriptor.get; this.nodeFirstChildGetter = win.Object.getOwnPropertyDescriptor(win.Node.prototype, 'firstChild').get; this.nodeLastChildGetter = win.Object.getOwnPropertyDescriptor(win.Node.prototype, 'lastChild').get; this.nodeNextSiblingGetter = win.Object.getOwnPropertyDescriptor(win.Node.prototype, 'nextSibling').get; this.nodePrevSiblingGetter = win.Object.getOwnPropertyDescriptor(win.Node.prototype, 'previousSibling').get; this.nodeParentNodeGetter = win.Object.getOwnPropertyDescriptor(win.Node.prototype, 'parentNode').get; this.nodeChildNodesGetter = win.Object.getOwnPropertyDescriptor(win.Node.prototype, 'childNodes').get; this.elementFirstElementChildGetter = win.Object.getOwnPropertyDescriptor(win.Element.prototype, 'firstElementChild').get; this.elementLastElementChildGetter = win.Object.getOwnPropertyDescriptor(win.Element.prototype, 'lastElementChild').get; this.elementNextElementSiblingGetter = win.Object.getOwnPropertyDescriptor(win.Element.prototype, 'nextElementSibling').get; this.elementPrevElementSiblingGetter = win.Object.getOwnPropertyDescriptor(win.Element.prototype, 'previousElementSibling').get; // NOTE: Some browsers (for example, Edge, Internet Explorer 11, Safari) don't support the 'integrity' property. if (scriptIntegrityDescriptor && linkIntegrityDescriptor) { this.scriptIntegrityGetter = scriptIntegrityDescriptor.get; this.linkIntegrityGetter = linkIntegrityDescriptor.get; } // NOTE: In the Internet Explorer 11 the children property is located in HTMLElement. const childrenPropOwner = win.Element.prototype.hasOwnProperty('children') ? win.Element.prototype : win.HTMLElement.prototype; this.elementChildrenGetter = win.Object.getOwnPropertyDescriptor(childrenPropOwner, 'children').get; const anchorOriginDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLAnchorElement.prototype, 'origin'); // NOTE: IE and Edge don't support origin property if (anchorOriginDescriptor) this.anchorOriginGetter = anchorOriginDescriptor.get; const iframeSrcdocDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLIFrameElement.prototype, 'srcdoc'); // NOTE: IE11 doesn't support the 'srcdoc' property if (iframeSrcdocDescriptor) { this.iframeSrcdocGetter = iframeSrcdocDescriptor.get; this.iframeSrcdocSetter = iframeSrcdocDescriptor.set; } const cssStyleSheetHrefDescriptor = win.Object.getOwnPropertyDescriptor(win.CSSStyleSheet.prototype, 'href'); // NOTE: IE11 doesn't support the 'href' property if (cssStyleSheetHrefDescriptor) this.cssStyleSheetHrefGetter = cssStyleSheetHrefDescriptor.get; const nodeBaseURIDescriptor = win.Object.getOwnPropertyDescriptor(win.Node.prototype, 'baseURI'); // NOTE: IE11 doesn't support the 'baseURI' property if (nodeBaseURIDescriptor) this.nodeBaseURIGetter = nodeBaseURIDescriptor.get; // NOTE: The 'attributes' property is located in Node prototype in IE11 only this.elementAttributesPropOwnerName = win.Element.prototype.hasOwnProperty('attributes') ? 'Element' : 'Node'; this.elementAttributesGetter = win.Object.getOwnPropertyDescriptor(win[this.elementAttributesPropOwnerName].prototype, 'attributes').get; const htmlManifestDescriptor = win.Object.getOwnPropertyDescriptor(win.HTMLHtmlElement.prototype, 'manifest'); // NOTE: Only the Safari browser supports the 'manifest' property if (htmlManifestDescriptor) { this.htmlManifestGetter = htmlManifestDescriptor.get; this.htmlManifestSetter = htmlManifestDescriptor.set; } this.titleElementTextGetter = titleElementTextDescriptor.get; // MutationRecord this.mutationRecordNextSiblingGetter = win.Object.getOwnPropertyDescriptor(win.MutationRecord.prototype, 'nextSibling').get; this.mutationRecordPrevSiblingGetter = win.Object.getOwnPropertyDescriptor(win.MutationRecord.prototype, 'previousSibling').get; } refreshWindowMeths (win, isInWorker = false) { win = win || window; const winProto = win.constructor.prototype; // Dom this.eval = win.eval; this.formSubmit = win.HTMLFormElement && win.HTMLFormElement.prototype.submit; this.documentFragmentQuerySelector = win.DocumentFragment && win.DocumentFragment.prototype.querySelector; this.documentFragmentQuerySelectorAll = win.DocumentFragment && win.DocumentFragment.prototype.querySelectorAll; this.preventDefault = win.Event.prototype.preventDefault; this.historyPushState = win.history && win.history.pushState; this.historyReplaceState = win.history && win.history.replaceState; this.postMessage = win.postMessage || winProto.postMessage; this.windowOpen = win.open || winProto.open; this.setTimeout = win.setTimeout || winProto.setTimeout; this.setInterval = win.setInterval || winProto.setInterval; this.clearTimeout = win.clearTimeout || winProto.clearTimeout; this.clearInterval = win.clearInterval || winProto.clearInterval; this.registerProtocolHandler = win.navigator.registerProtocolHandler; this.sendBeacon = win.Navigator && win.Navigator.prototype.sendBeacon; if (win.XMLHttpRequest) { // NOTE: IE11 has no EventTarget so we should save "Event" methods separately const xhrEventProto = (win.EventTarget || win.XMLHttpRequest).prototype; this.xhrAbort = win.XMLHttpRequest.prototype.abort; this.xhrOpen = win.XMLHttpRequest.prototype.open; this.xhrSend = win.XMLHttpRequest.prototype.send; this.xhrAddEventListener = xhrEventProto.addEventListener; this.xhrRemoveEventListener = xhrEventProto.removeEventListener; this.xhrDispatchEvent = xhrEventProto.dispatchEvent; this.xhrGetResponseHeader = win.XMLHttpRequest.prototype.getResponseHeader; this.xhrGetAllResponseHeaders = win.XMLHttpRequest.prototype.getAllResponseHeaders; this.xhrSetRequestHeader = win.XMLHttpRequest.prototype.setRequestHeader; this.xhrOverrideMimeType = win.XMLHttpRequest.prototype.overrideMimeType; } try { this.registerServiceWorker = win.navigator.serviceWorker.register; this.getRegistrationServiceWorker = win.navigator.serviceWorker.getRegistration; } catch (e) { this.registerServiceWorker = null; this.getRegistrationServiceWorker = null; } this.createContextualFragment = win.Range && win.Range.prototype.createContextualFragment; const nativePerformance = win.performance; if (nativePerformance) { // eslint-disable-next-line no-restricted-properties const nativePerformanceNow = win.performance.now || win.Performance.prototype.now; this.performanceNow = (...args) => nativePerformanceNow.apply(nativePerformance, args); } // Fetch this.fetch = win.fetch; this.Request = win.Request; if (win.Headers) { this.Headers = win.Headers; this.headersSet = win.Headers.prototype.set; this.headersGet = win.Headers.prototype.get; this.headersDelete = win.Headers.prototype.delete; this.headersEntries = win.Headers.prototype.entries; this.headersForEach = win.Headers.prototype.forEach; this.headersValues = win.Headers.prototype.values; } // Event this.windowAddEventListener = win.addEventListener || winProto.addEventListener; this.windowRemoveEventListener = win.removeEventListener || winProto.removeEventListener; this.windowDispatchEvent = win.dispatchEvent; this.WindowPointerEvent = win.PointerEvent || winProto.PointerEvent; this.WindowMSPointerEvent = win.MSPointerEvent || winProto.MSPointerEvent; this.WindowTouch = win.Touch || winProto.Touch; this.WindowTouchEvent = win.TouchEvent || winProto.TouchEvent; this.WindowKeyboardEvent = win.KeyboardEvent || winProto.KeyboardEvent; this.WindowFocusEvent = win.FocusEvent || winProto.FocusEvent; this.WindowTextEvent = win.TextEvent || winProto.TextEvent; this.WindowInputEvent = win.InputEvent || winProto.InputEvent; this.WindowMouseEvent = win.MouseEvent || winProto.MouseEvent; this.eventTargetGetter = win.Object.getOwnPropertyDescriptor(win.Event.prototype, 'target').get; this.canvasContextDrawImage = win.CanvasRenderingContext2D && win.CanvasRenderingContext2D.prototype.drawImage; // FormData this.formDataAppend = win.FormData && win.FormData.prototype.append; // DateTime this.date = win.Date; this.dateNow = win.Date.now; // eslint-disable-line no-restricted-properties // Math this.math = win.Math; this.mathRandom = win.Math.random; // Object this.objectToString = win.Object.prototype.toString; this.objectAssign = win.Object.assign; this.objectKeys = win.Object.keys; this.objectDefineProperty = win.Object.defineProperty; this.objectDefineProperties = win.Object.defineProperties; this.objectCreate = win.Object.create; this.objectIsExtensible = win.Object.isExtensible; this.objectIsFrozen = win.Object.isFrozen; this.objectGetOwnPropertyDescriptor = win.Object.getOwnPropertyDescriptor; this.objectHasOwnProperty = win.Object.hasOwnProperty; this.objectGetOwnPropertyNames = win.Object.getOwnPropertyNames; this.objectGetPrototypeOf = win.Object.getPrototypeOf; this.objectSetPrototypeOf = win.Object.setPrototypeOf; this.objectGetOwnPropertySymbols = win.Object.getOwnPropertySymbols; // Array this.arraySlice = win.Array.prototype.slice; this.arrayConcat = win.Array.prototype.concat; this.arrayFilter = win.Array.prototype.filter; this.arrayFind = win.Array.prototype.find; this.arrayMap = win.Array.prototype.map; this.arrayJoin = win.Array.prototype.join; this.arraySplice = win.Array.prototype.splice; this.arrayUnshift = win.Array.prototype.unshift; this.arrayForEach = win.Array.prototype.forEach; this.arrayIndexOf = win.Array.prototype.indexOf; this.arraySome = win.Array.prototype.some; this.arrayReverse = win.Array.prototype.reverse; this.arrayReduce = win.Array.prototype.reduce; this.arrayFrom = win.Array.from; this.isArray = win.Array.isArray; this.DOMParserParseFromString = win.DOMParser && win.DOMParser.prototype.parseFromString; this.arrayBufferIsView = win.ArrayBuffer.prototype.constructor.isView; // NOTE: this section relates to getting properties from DOM classes if (!isInWorker) { // DOMTokenList this.tokenListAdd = win.DOMTokenList.prototype.add; this.tokenListRemove = win.DOMTokenList.prototype.remove; this.tokenListReplace = win.DOMTokenList.prototype.replace; this.tokenListSupports = win.DOMTokenList.prototype.supports; this.tokenListToggle = win.DOMTokenList.prototype.toggle; this.tokenListContains = win.DOMTokenList.prototype.contains; const tokenListValueDescriptor = win.Object.getOwnPropertyDescriptor(win.DOMTokenList.prototype, 'value'); // NOTE: IE11 doesn't support the 'value' property of the DOMTokenList interface if (tokenListValueDescriptor) this.tokenListValueSetter = tokenListValueDescriptor.set; // Stylesheets this.styleGetPropertyValue = win.CSSStyleDeclaration.prototype.getPropertyValue; this.styleSetProperty = win.CSSStyleDeclaration.prototype.setProperty; this.styleRemoveProperty = win.CSSStyleDeclaration.prototype.removeProperty; this.styleInsertRule = win.CSSStyleSheet.prototype.insertRule; this.scrollTo = win.scrollTo; } if (win.Promise) { this.promiseThen = win.Promise.prototype.then; this.promiseReject = win.Promise.reject; } // Console this.console = win.console; if (this.console) { this.consoleMeths = { log: win.console.log, warn: win.console.warn, error: win.console.error, info: win.console.info }; } this.crypto = win.crypto || win.msCrypto; this.cryptoGetRandomValues = this.crypto && this.crypto.getRandomValues; this.refreshClasses(win); this._refreshGettersAndSetters(win, isInWorker); } refreshClasses (win) { this.windowClass = win.Window; this.documentClass = win.Document; this.locationClass = win.Location; this.elementClass = win.Element; this.svgElementClass = win.SVGElement; this.Worker = win.Worker; this.MessageChannel = win.MessageChannel; this.Array = win.Array; this.ArrayBuffer = win.ArrayBuffer; this.Uint8Array = win.Uint8Array; this.Uint16Array = win.Uint16Array; this.Uint32Array = win.Uint32Array; this.DataView = win.DataView; this.Blob = win.Blob; this.XMLHttpRequest = win.XMLHttpRequest; this.Image = win.Image; this.Function = win.Function; this.functionToString = win.Function.prototype.toString; this.Error = win.Error; this.FontFace = win.FontFace; this.StorageEvent = win.StorageEvent; this.MutationObserver = win.MutationObserver; this.EventSource = win.EventSource; this.Proxy = win.Proxy; this.WebSocket = win.WebSocket; this.HTMLCollection = win.HTMLCollection; this.NodeList = win.NodeList; this.Node = win.Node; this.URL = win.URL; this.DataTransfer = win.DataTransfer; this.DataTransferItemList = win.DataTransferItemList; this.DataTransferItem = win.DataTransferItem; this.FileList = win.FileList; // NOTE: non-IE11 case. window.File in IE11 is not constructable. if (win.File && typeof win.File === 'function') this.File = win.File; } refreshElectronMeths (vmModule): boolean { if (this.createScript && isNativeFunction(vmModule.createScript)) return false; this.createScript = vmModule.createScript; this.runInDebugContext = vmModule.runInDebugContext; this.runInContext = vmModule.runInContext; this.runInNewContext = vmModule.runInNewContext; this.runInThisContext = vmModule.runInThisContext; return true; } static _ensureDocumentMethodRestore (document, prototype, methodName, savedNativeMethod) { prototype[methodName] = savedNativeMethod; if (document[methodName] !== prototype[methodName]) document[methodName] = savedNativeMethod; } restoreDocumentMeths (window, document) { const docPrototype = window.Document.prototype; NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'createDocumentFragment', this.createDocumentFragment); NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'createElement', this.createElement); NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'createElementNS', this.createElementNS); NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'elementFromPoint', this.elementFromPoint); NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'caretRangeFromPoint', this.caretRangeFromPoint); NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'caretPositionFromPoint', this.caretPositionFromPoint); NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'getElementById', this.getElementById); NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'getElementsByClassName', this.getElementsByClassName); NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'getElementsByName', this.getElementsByName); NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'getElementsByTagName', this.getElementsByTagName); NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'querySelector', this.querySelector); NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'querySelectorAll', this.querySelectorAll); // Event // NOTE: IE11 has no EventTarget if (!window.EventTarget) { NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'addEventListener', this.documentAddEventListener); NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'removeEventListener', this.documentRemoveEventListener); } NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'createEvent', this.documentCreateEvent); NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'createTouch', this.documentCreateTouch); NativeMethods._ensureDocumentMethodRestore(document, docPrototype, 'createTouchList', this.documentCreateTouchList); NativeMethods._ensureDocumentMethodRestore(document, window[this.documentOpenPropOwnerName].prototype, 'open', this.documentOpen); NativeMethods._ensureDocumentMethodRestore(document, window[this.documentClosePropOwnerName].prototype, 'close', this.documentClose); NativeMethods._ensureDocumentMethodRestore(document, window[this.documentWritePropOwnerName].prototype, 'write', this.documentWrite); NativeMethods._ensureDocumentMethodRestore(document, window[this.documentWriteLnPropOwnerName].prototype, 'writeln', this.documentWriteLn); } refreshIfNecessary (doc: Document, win: Window & typeof globalThis) { const tryToExecuteCode = (func: Function) => { try { return func(); } catch (e) { return true; } }; const needToRefreshDocumentMethods = tryToExecuteCode( () => !doc.createElement || isNativeFunction(document.createElement) ); const needToRefreshElementMethods = tryToExecuteCode(() => { const nativeElement = this.createElement.call(doc, 'div'); return isNativeFunction(nativeElement.getAttribute); }); const needToRefreshWindowMethods = tryToExecuteCode(() => { this.setTimeout.call(win, () => void 0, 0); return isNativeFunction(win.XMLHttpRequest.prototype.open); }); // NOTE: T173709 if (needToRefreshDocumentMethods) this.refreshDocumentMeths(doc, win); if (needToRefreshElementMethods) this.refreshElementMeths(doc, win); // NOTE: T239109 if (needToRefreshWindowMethods) this.refreshWindowMeths(win); } isNativeCode (fn: Function): boolean { return NATIVE_CODE_RE.test(fn.toString()); } } export default new NativeMethods();
the_stack