id
int64
0
3.78k
code
stringlengths
13
37.9k
declarations
stringlengths
16
64.6k
2,600
function parsePropertyValue(cxt: ParseCxt, key: Name, schema: SchemaObject): void { parseCode({...cxt, schema, data: _`${cxt.data}[${key}]`}) }
interface SchemaObject extends _SchemaObject { id?: string $id?: string $schema?: string $async?: false [x: string]: any // TODO }
2,601
function parseType(cxt: ParseCxt): void { const {gen, schema, data, self} = cxt switch (schema.type) { case "boolean": parseBoolean(cxt) break case "string": parseString(cxt) break case "timestamp": { parseString(cxt) const vts = useFunc(gen, validTimestamp) const {allowDate, parseDate} = self.opts const notValid = allowDate ? _`!${vts}(${data}, true)` : _`!${vts}(${data})` const fail: Code = parseDate ? or(notValid, _`(${data} = new Date(${data}), false)`, _`isNaN(${data}.valueOf())`) : notValid gen.if(fail, () => parsingError(cxt, str`invalid timestamp`)) break } case "float32": case "float64": parseNumber(cxt) break default: { const t = schema.type as IntType if (!self.opts.int32range && (t === "int32" || t === "uint32")) { parseNumber(cxt, 16) // 2 ** 53 - max safe integer if (t === "uint32") { gen.if(_`${data} < 0`, () => parsingError(cxt, str`integer out of range`)) } } else { const [min, max, maxDigits] = intRange[t] parseNumber(cxt, maxDigits) gen.if(_`${data} < ${min} || ${data} > ${max}`, () => parsingError(cxt, str`integer out of range`) ) } } } }
interface ParseCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code parseName: Name char: Name }
2,602
function parseString(cxt: ParseCxt): void { parseToken(cxt, '"') parseWith(cxt, parseJsonString) }
interface ParseCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code parseName: Name char: Name }
2,603
function parseEnum(cxt: ParseCxt): void { const {gen, data, schema} = cxt const enumSch = schema.enum parseToken(cxt, '"') // TODO loopEnum gen.if(false) for (const value of enumSch) { const valueStr = JSON.stringify(value).slice(1) // remove starting quote gen.elseIf(_`${jsonSlice(valueStr.length)} === ${valueStr}`) gen.assign(data, str`${value}`) gen.add(N.jsonPos, valueStr.length) } gen.else() jsonSyntaxError(cxt) gen.endIf() }
interface ParseCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code parseName: Name char: Name }
2,604
function parseNumber(cxt: ParseCxt, maxDigits?: number): void { const {gen} = cxt skipWhitespace(cxt) gen.if( _`"-0123456789".indexOf(${jsonSlice(1)}) < 0`, () => jsonSyntaxError(cxt), () => parseWith(cxt, parseJsonNumber, maxDigits) ) }
interface ParseCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code parseName: Name char: Name }
2,605
function parseRef(cxt: ParseCxt): void { const {gen, self, definitions, schema, schemaEnv} = cxt const {ref} = schema const refSchema = definitions[ref] if (!refSchema) throw new MissingRefError(self.opts.uriResolver, "", ref, `No definition ${ref}`) if (!hasRef(refSchema)) return parseCode({...cxt, schema: refSchema}) const {root} = schemaEnv const sch = compileParser.call(self, new SchemaEnv({schema: refSchema, root}), definitions) partialParse(cxt, getParser(gen, sch), true) }
interface ParseCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code parseName: Name char: Name }
2,606
function getParser(gen: CodeGen, sch: SchemaEnv): Code { return sch.parse ? gen.scopeValue("parse", {ref: sch.parse}) : _`${gen.scopeValue("wrapper", {ref: sch})}.parse` }
class SchemaEnv implements SchemaEnvArgs { readonly schema: AnySchema readonly schemaId?: "$id" | "id" readonly root: SchemaEnv baseId: string // TODO possibly, it should be readonly schemaPath?: string localRefs?: LocalRefs readonly meta?: boolean readonly $async?: boolean // true if the current schema is asynchronous. readonly refs: SchemaRefs = {} readonly dynamicAnchors: {[Ref in string]?: true} = {} validate?: AnyValidateFunction validateName?: ValueScopeName serialize?: (data: unknown) => string serializeName?: ValueScopeName parse?: (data: string) => unknown parseName?: ValueScopeName constructor(env: SchemaEnvArgs) { let schema: AnySchemaObject | undefined if (typeof env.schema == "object") schema = env.schema this.schema = env.schema this.schemaId = env.schemaId this.root = env.root || this this.baseId = env.baseId ?? normalizeId(schema?.[env.schemaId || "$id"]) this.schemaPath = env.schemaPath this.localRefs = env.localRefs this.meta = env.meta this.$async = schema?.$async this.refs = {} } }
2,607
function getParser(gen: CodeGen, sch: SchemaEnv): Code { return sch.parse ? gen.scopeValue("parse", {ref: sch.parse}) : _`${gen.scopeValue("wrapper", {ref: sch})}.parse` }
class CodeGen { readonly _scope: Scope readonly _extScope: ValueScope readonly _values: ScopeValueSets = {} private readonly _nodes: ParentNode[] private readonly _blockStarts: number[] = [] private readonly _constants: Constants = {} private readonly opts: CGOptions constructor(extScope: ValueScope, opts: CodeGenOptions = {}) { this.opts = {...opts, _n: opts.lines ? "\n" : ""} this._extScope = extScope this._scope = new Scope({parent: extScope}) this._nodes = [new Root()] } toString(): string { return this._root.render(this.opts) } // returns unique name in the internal scope name(prefix: string): Name { return this._scope.name(prefix) } // reserves unique name in the external scope scopeName(prefix: string): ValueScopeName { return this._extScope.name(prefix) } // reserves unique name in the external scope and assigns value to it scopeValue(prefixOrName: ValueScopeName | string, value: NameValue): Name { const name = this._extScope.value(prefixOrName, value) const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set()) vs.add(name) return name } getScopeValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined { return this._extScope.getValue(prefix, keyOrRef) } // return code that assigns values in the external scope to the names that are used internally // (same names that were returned by gen.scopeName or gen.scopeValue) scopeRefs(scopeName: Name): Code { return this._extScope.scopeRefs(scopeName, this._values) } scopeCode(): Code { return this._extScope.scopeCode(this._values) } private _def( varKind: Name, nameOrPrefix: Name | string, rhs?: SafeExpr, constant?: boolean ): Name { const name = this._scope.toName(nameOrPrefix) if (rhs !== undefined && constant) this._constants[name.str] = rhs this._leafNode(new Def(varKind, name, rhs)) return name } // `const` declaration (`var` in es5 mode) const(nameOrPrefix: Name | string, rhs: SafeExpr, _constant?: boolean): Name { return this._def(varKinds.const, nameOrPrefix, rhs, _constant) } // `let` declaration with optional assignment (`var` in es5 mode) let(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name { return this._def(varKinds.let, nameOrPrefix, rhs, _constant) } // `var` declaration with optional assignment var(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name { return this._def(varKinds.var, nameOrPrefix, rhs, _constant) } // assignment code assign(lhs: Code, rhs: SafeExpr, sideEffects?: boolean): CodeGen { return this._leafNode(new Assign(lhs, rhs, sideEffects)) } // `+=` code add(lhs: Code, rhs: SafeExpr): CodeGen { return this._leafNode(new AssignOp(lhs, operators.ADD, rhs)) } // appends passed SafeExpr to code or executes Block code(c: Block | SafeExpr): CodeGen { if (typeof c == "function") c() else if (c !== nil) this._leafNode(new AnyCode(c)) return this } // returns code for object literal for the passed argument list of key-value pairs object(...keyValues: [Name | string, SafeExpr | string][]): _Code { const code: CodeItem[] = ["{"] for (const [key, value] of keyValues) { if (code.length > 1) code.push(",") code.push(key) if (key !== value || this.opts.es5) { code.push(":") addCodeArg(code, value) } } code.push("}") return new _Code(code) } // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed) if(condition: Code | boolean, thenBody?: Block, elseBody?: Block): CodeGen { this._blockNode(new If(condition)) if (thenBody && elseBody) { this.code(thenBody).else().code(elseBody).endIf() } else if (thenBody) { this.code(thenBody).endIf() } else if (elseBody) { throw new Error('CodeGen: "else" body without "then" body') } return this } // `else if` clause - invalid without `if` or after `else` clauses elseIf(condition: Code | boolean): CodeGen { return this._elseNode(new If(condition)) } // `else` clause - only valid after `if` or `else if` clauses else(): CodeGen { return this._elseNode(new Else()) } // end `if` statement (needed if gen.if was used only with condition) endIf(): CodeGen { return this._endBlockNode(If, Else) } private _for(node: For, forBody?: Block): CodeGen { this._blockNode(node) if (forBody) this.code(forBody).endFor() return this } // a generic `for` clause (or statement if `forBody` is passed) for(iteration: Code, forBody?: Block): CodeGen { return this._for(new ForLoop(iteration), forBody) } // `for` statement for a range of values forRange( nameOrPrefix: Name | string, from: SafeExpr, to: SafeExpr, forBody: (index: Name) => void, varKind: Code = this.opts.es5 ? varKinds.var : varKinds.let ): CodeGen { const name = this._scope.toName(nameOrPrefix) return this._for(new ForRange(varKind, name, from, to), () => forBody(name)) } // `for-of` statement (in es5 mode replace with a normal for loop) forOf( nameOrPrefix: Name | string, iterable: Code, forBody: (item: Name) => void, varKind: Code = varKinds.const ): CodeGen { const name = this._scope.toName(nameOrPrefix) if (this.opts.es5) { const arr = iterable instanceof Name ? iterable : this.var("_arr", iterable) return this.forRange("_i", 0, _`${arr}.length`, (i) => { this.var(name, _`${arr}[${i}]`) forBody(name) }) } return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)) } // `for-in` statement. // With option `ownProperties` replaced with a `for-of` loop for object keys forIn( nameOrPrefix: Name | string, obj: Code, forBody: (item: Name) => void, varKind: Code = this.opts.es5 ? varKinds.var : varKinds.const ): CodeGen { if (this.opts.ownProperties) { return this.forOf(nameOrPrefix, _`Object.keys(${obj})`, forBody) } const name = this._scope.toName(nameOrPrefix) return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)) } // end `for` loop endFor(): CodeGen { return this._endBlockNode(For) } // `label` statement label(label: Name): CodeGen { return this._leafNode(new Label(label)) } // `break` statement break(label?: Code): CodeGen { return this._leafNode(new Break(label)) } // `return` statement return(value: Block | SafeExpr): CodeGen { const node = new Return() this._blockNode(node) this.code(value) if (node.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node') return this._endBlockNode(Return) } // `try` statement try(tryBody: Block, catchCode?: (e: Name) => void, finallyCode?: Block): CodeGen { if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"') const node = new Try() this._blockNode(node) this.code(tryBody) if (catchCode) { const error = this.name("e") this._currNode = node.catch = new Catch(error) catchCode(error) } if (finallyCode) { this._currNode = node.finally = new Finally() this.code(finallyCode) } return this._endBlockNode(Catch, Finally) } // `throw` statement throw(error: Code): CodeGen { return this._leafNode(new Throw(error)) } // start self-balancing block block(body?: Block, nodeCount?: number): CodeGen { this._blockStarts.push(this._nodes.length) if (body) this.code(body).endBlock(nodeCount) return this } // end the current self-balancing block endBlock(nodeCount?: number): CodeGen { const len = this._blockStarts.pop() if (len === undefined) throw new Error("CodeGen: not in self-balancing block") const toClose = this._nodes.length - len if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) { throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`) } this._nodes.length = len return this } // `function` heading (or definition if funcBody is passed) func(name: Name, args: Code = nil, async?: boolean, funcBody?: Block): CodeGen { this._blockNode(new Func(name, args, async)) if (funcBody) this.code(funcBody).endFunc() return this } // end function definition endFunc(): CodeGen { return this._endBlockNode(Func) } optimize(n = 1): void { while (n-- > 0) { this._root.optimizeNodes() this._root.optimizeNames(this._root.names, this._constants) } } private _leafNode(node: LeafNode): CodeGen { this._currNode.nodes.push(node) return this } private _blockNode(node: StartBlockNode): void { this._currNode.nodes.push(node) this._nodes.push(node) } private _endBlockNode(N1: EndBlockNodeType, N2?: EndBlockNodeType): CodeGen { const n = this._currNode if (n instanceof N1 || (N2 && n instanceof N2)) { this._nodes.pop() return this } throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`) } private _elseNode(node: If | Else): CodeGen { const n = this._currNode if (!(n instanceof If)) { throw new Error('CodeGen: "else" without "if"') } this._currNode = n.else = node return this } private get _root(): Root { return this._nodes[0] as Root } private get _currNode(): ParentNode { const ns = this._nodes return ns[ns.length - 1] } private set _currNode(node: ParentNode) { const ns = this._nodes ns[ns.length - 1] = node } // get nodeCount(): number { // return this._root.count // } }
2,608
function parseEmpty(cxt: ParseCxt): void { parseWith(cxt, parseJson) }
interface ParseCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code parseName: Name char: Name }
2,609
function parseWith(cxt: ParseCxt, parseFunc: {code: string}, args?: SafeExpr): void { partialParse(cxt, useFunc(cxt.gen, parseFunc), args) }
type SafeExpr = Code | number | boolean | null
2,610
function parseWith(cxt: ParseCxt, parseFunc: {code: string}, args?: SafeExpr): void { partialParse(cxt, useFunc(cxt.gen, parseFunc), args) }
type SafeExpr = Code | number | boolean | null
2,611
function parseWith(cxt: ParseCxt, parseFunc: {code: string}, args?: SafeExpr): void { partialParse(cxt, useFunc(cxt.gen, parseFunc), args) }
interface ParseCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code parseName: Name char: Name }
2,612
function partialParse(cxt: ParseCxt, parseFunc: Name, args?: SafeExpr): void { const {gen, data} = cxt gen.assign(data, _`${parseFunc}(${N.json}, ${N.jsonPos}${args ? _`, ${args}` : nil})`) gen.assign(N.jsonPos, _`${parseFunc}.position`) gen.if(_`${data} === undefined`, () => parsingError(cxt, _`${parseFunc}.message`)) }
type SafeExpr = Code | number | boolean | null
2,613
function partialParse(cxt: ParseCxt, parseFunc: Name, args?: SafeExpr): void { const {gen, data} = cxt gen.assign(data, _`${parseFunc}(${N.json}, ${N.jsonPos}${args ? _`, ${args}` : nil})`) gen.assign(N.jsonPos, _`${parseFunc}.position`) gen.if(_`${data} === undefined`, () => parsingError(cxt, _`${parseFunc}.message`)) }
type SafeExpr = Code | number | boolean | null
2,614
function partialParse(cxt: ParseCxt, parseFunc: Name, args?: SafeExpr): void { const {gen, data} = cxt gen.assign(data, _`${parseFunc}(${N.json}, ${N.jsonPos}${args ? _`, ${args}` : nil})`) gen.assign(N.jsonPos, _`${parseFunc}.position`) gen.if(_`${data} === undefined`, () => parsingError(cxt, _`${parseFunc}.message`)) }
interface ParseCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code parseName: Name char: Name }
2,615
function partialParse(cxt: ParseCxt, parseFunc: Name, args?: SafeExpr): void { const {gen, data} = cxt gen.assign(data, _`${parseFunc}(${N.json}, ${N.jsonPos}${args ? _`, ${args}` : nil})`) gen.assign(N.jsonPos, _`${parseFunc}.position`) gen.if(_`${data} === undefined`, () => parsingError(cxt, _`${parseFunc}.message`)) }
class Name extends _CodeOrName { readonly str: string constructor(s: string) { super() if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier") this.str = s } toString(): string { return this.str } emptyStr(): boolean { return false } get names(): UsedNames { return {[this.str]: 1} } }
2,616
function parseToken(cxt: ParseCxt, tok: string): void { tryParseToken(cxt, tok, jsonSyntaxError) }
interface ParseCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code parseName: Name char: Name }
2,617
function tryParseToken(cxt: ParseCxt, tok: string, fail: GenParse, success?: GenParse): void { const {gen} = cxt const n = tok.length skipWhitespace(cxt) gen.if( _`${jsonSlice(n)} === ${tok}`, () => { gen.add(N.jsonPos, n) success?.(cxt) }, () => fail(cxt) ) }
interface ParseCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code parseName: Name char: Name }
2,618
function tryParseToken(cxt: ParseCxt, tok: string, fail: GenParse, success?: GenParse): void { const {gen} = cxt const n = tok.length skipWhitespace(cxt) gen.if( _`${jsonSlice(n)} === ${tok}`, () => { gen.add(N.jsonPos, n) success?.(cxt) }, () => fail(cxt) ) }
type GenParse = (cxt: ParseCxt) => void
2,619
function skipWhitespace({gen, char: c}: ParseCxt): void { gen.code( _`while((${c}=${N.json}[${N.jsonPos}],${c}===" "||${c}==="\\n"||${c}==="\\r"||${c}==="\\t"))${N.jsonPos}++;` ) }
interface ParseCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code parseName: Name char: Name }
2,620
function jsonSyntaxError(cxt: ParseCxt): void { parsingError(cxt, _`"unexpected token " + ${N.json}[${N.jsonPos}]`) }
interface ParseCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code parseName: Name char: Name }
2,621
function parsingError({gen, parseName}: ParseCxt, msg: Code): void { gen.assign(_`${parseName}.message`, msg) gen.assign(_`${parseName}.position`, N.jsonPos) gen.return(undef) }
interface ParseCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code parseName: Name char: Name }
2,622
function parsingError({gen, parseName}: ParseCxt, msg: Code): void { gen.assign(_`${parseName}.message`, msg) gen.assign(_`${parseName}.position`, N.jsonPos) gen.return(undef) }
type Code = _Code | Name
2,623
(cxt: SerializeCxt) => void
interface SerializeCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code }
2,624
function compileSerializer( this: Ajv, sch: SchemaEnv, definitions: SchemaObjectMap ): SchemaEnv { const _sch = getCompilingSchema.call(this, sch) if (_sch) return _sch const {es5, lines} = this.opts.code const {ownProperties} = this.opts const gen = new CodeGen(this.scope, {es5, lines, ownProperties}) const serializeName = gen.scopeName("serialize") const cxt: SerializeCxt = { self: this, gen, schema: sch.schema as SchemaObject, schemaEnv: sch, definitions, data: N.data, } let sourceCode: string | undefined try { this._compilations.add(sch) sch.serializeName = serializeName gen.func(serializeName, N.data, false, () => { gen.let(N.json, str``) serializeCode(cxt) gen.return(N.json) }) gen.optimize(this.opts.code.optimize) const serializeFuncCode = gen.toString() sourceCode = `${gen.scopeRefs(N.scope)}return ${serializeFuncCode}` const makeSerialize = new Function(`${N.scope}`, sourceCode) const serialize: (data: unknown) => string = makeSerialize(this.scope.get()) this.scope.value(serializeName, {ref: serialize}) sch.serialize = serialize } catch (e) { if (sourceCode) this.logger.error("Error compiling serializer, function code:", sourceCode) delete sch.serialize delete sch.serializeName throw e } finally { this._compilations.delete(sch) } return sch }
class SchemaEnv implements SchemaEnvArgs { readonly schema: AnySchema readonly schemaId?: "$id" | "id" readonly root: SchemaEnv baseId: string // TODO possibly, it should be readonly schemaPath?: string localRefs?: LocalRefs readonly meta?: boolean readonly $async?: boolean // true if the current schema is asynchronous. readonly refs: SchemaRefs = {} readonly dynamicAnchors: {[Ref in string]?: true} = {} validate?: AnyValidateFunction validateName?: ValueScopeName serialize?: (data: unknown) => string serializeName?: ValueScopeName parse?: (data: string) => unknown parseName?: ValueScopeName constructor(env: SchemaEnvArgs) { let schema: AnySchemaObject | undefined if (typeof env.schema == "object") schema = env.schema this.schema = env.schema this.schemaId = env.schemaId this.root = env.root || this this.baseId = env.baseId ?? normalizeId(schema?.[env.schemaId || "$id"]) this.schemaPath = env.schemaPath this.localRefs = env.localRefs this.meta = env.meta this.$async = schema?.$async this.refs = {} } }
2,625
function compileSerializer( this: Ajv, sch: SchemaEnv, definitions: SchemaObjectMap ): SchemaEnv { const _sch = getCompilingSchema.call(this, sch) if (_sch) return _sch const {es5, lines} = this.opts.code const {ownProperties} = this.opts const gen = new CodeGen(this.scope, {es5, lines, ownProperties}) const serializeName = gen.scopeName("serialize") const cxt: SerializeCxt = { self: this, gen, schema: sch.schema as SchemaObject, schemaEnv: sch, definitions, data: N.data, } let sourceCode: string | undefined try { this._compilations.add(sch) sch.serializeName = serializeName gen.func(serializeName, N.data, false, () => { gen.let(N.json, str``) serializeCode(cxt) gen.return(N.json) }) gen.optimize(this.opts.code.optimize) const serializeFuncCode = gen.toString() sourceCode = `${gen.scopeRefs(N.scope)}return ${serializeFuncCode}` const makeSerialize = new Function(`${N.scope}`, sourceCode) const serialize: (data: unknown) => string = makeSerialize(this.scope.get()) this.scope.value(serializeName, {ref: serialize}) sch.serialize = serialize } catch (e) { if (sourceCode) this.logger.error("Error compiling serializer, function code:", sourceCode) delete sch.serialize delete sch.serializeName throw e } finally { this._compilations.delete(sch) } return sch }
class Ajv { opts: InstanceOptions errors?: ErrorObject[] | null // errors from the last validation logger: Logger // shared external scope values for compiled functions readonly scope: ValueScope readonly schemas: {[Key in string]?: SchemaEnv} = {} readonly refs: {[Ref in string]?: SchemaEnv | string} = {} readonly formats: {[Name in string]?: AddedFormat} = {} readonly RULES: ValidationRules readonly _compilations: Set<SchemaEnv> = new Set() private readonly _loading: {[Ref in string]?: Promise<AnySchemaObject>} = {} private readonly _cache: Map<AnySchema, SchemaEnv> = new Map() private readonly _metaOpts: InstanceOptions static ValidationError = ValidationError static MissingRefError = MissingRefError constructor(opts: Options = {}) { opts = this.opts = {...opts, ...requiredOptions(opts)} const {es5, lines} = this.opts.code this.scope = new ValueScope({scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines}) this.logger = getLogger(opts.logger) const formatOpt = opts.validateFormats opts.validateFormats = false this.RULES = getRules() checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED") checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn") this._metaOpts = getMetaSchemaOptions.call(this) if (opts.formats) addInitialFormats.call(this) this._addVocabularies() this._addDefaultMetaSchema() if (opts.keywords) addInitialKeywords.call(this, opts.keywords) if (typeof opts.meta == "object") this.addMetaSchema(opts.meta) addInitialSchemas.call(this) opts.validateFormats = formatOpt } _addVocabularies(): void { this.addKeyword("$async") } _addDefaultMetaSchema(): void { const {$data, meta, schemaId} = this.opts let _dataRefSchema: SchemaObject = $dataRefSchema if (schemaId === "id") { _dataRefSchema = {...$dataRefSchema} _dataRefSchema.id = _dataRefSchema.$id delete _dataRefSchema.$id } if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false) } defaultMeta(): string | AnySchemaObject | undefined { const {meta, schemaId} = this.opts return (this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : undefined) } // Validate data using schema // AnySchema will be compiled and cached using schema itself as a key for Map validate(schema: Schema | string, data: unknown): boolean validate(schemaKeyRef: AnySchema | string, data: unknown): boolean | Promise<unknown> validate<T>(schema: Schema | JSONSchemaType<T> | string, data: unknown): data is T // Separated for type inference to work // eslint-disable-next-line @typescript-eslint/unified-signatures validate<T>(schema: JTDSchemaType<T>, data: unknown): data is T // This overload is only intended for typescript inference, the first // argument prevents manual type annotation from matching this overload validate<N extends never, T extends SomeJTDSchemaType>( schema: T, data: unknown ): data is JTDDataType<T> validate<T>(schema: AsyncSchema, data: unknown | T): Promise<T> validate<T>(schemaKeyRef: AnySchema | string, data: unknown): data is T | Promise<T> validate<T>( schemaKeyRef: AnySchema | string, // key, ref or schema object data: unknown | T // to be validated ): boolean | Promise<T> { let v: AnyValidateFunction | undefined if (typeof schemaKeyRef == "string") { v = this.getSchema<T>(schemaKeyRef) if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`) } else { v = this.compile<T>(schemaKeyRef) } const valid = v(data) if (!("$async" in v)) this.errors = v.errors return valid } // Create validation function for passed schema // _meta: true if schema is a meta-schema. Used internally to compile meta schemas of user-defined keywords. compile<T = unknown>(schema: Schema | JSONSchemaType<T>, _meta?: boolean): ValidateFunction<T> // Separated for type inference to work // eslint-disable-next-line @typescript-eslint/unified-signatures compile<T = unknown>(schema: JTDSchemaType<T>, _meta?: boolean): ValidateFunction<T> // This overload is only intended for typescript inference, the first // argument prevents manual type annotation from matching this overload compile<N extends never, T extends SomeJTDSchemaType>( schema: T, _meta?: boolean ): ValidateFunction<JTDDataType<T>> compile<T = unknown>(schema: AsyncSchema, _meta?: boolean): AsyncValidateFunction<T> compile<T = unknown>(schema: AnySchema, _meta?: boolean): AnyValidateFunction<T> compile<T = unknown>(schema: AnySchema, _meta?: boolean): AnyValidateFunction<T> { const sch = this._addSchema(schema, _meta) return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction<T> } // Creates validating function for passed schema with asynchronous loading of missing schemas. // `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema. // TODO allow passing schema URI // meta - optional true to compile meta-schema compileAsync<T = unknown>( schema: SchemaObject | JSONSchemaType<T>, _meta?: boolean ): Promise<ValidateFunction<T>> // Separated for type inference to work // eslint-disable-next-line @typescript-eslint/unified-signatures compileAsync<T = unknown>(schema: JTDSchemaType<T>, _meta?: boolean): Promise<ValidateFunction<T>> compileAsync<T = unknown>(schema: AsyncSchema, meta?: boolean): Promise<AsyncValidateFunction<T>> // eslint-disable-next-line @typescript-eslint/unified-signatures compileAsync<T = unknown>( schema: AnySchemaObject, meta?: boolean ): Promise<AnyValidateFunction<T>> compileAsync<T = unknown>( schema: AnySchemaObject, meta?: boolean ): Promise<AnyValidateFunction<T>> { if (typeof this.opts.loadSchema != "function") { throw new Error("options.loadSchema should be a function") } const {loadSchema} = this.opts return runCompileAsync.call(this, schema, meta) async function runCompileAsync( this: Ajv, _schema: AnySchemaObject, _meta?: boolean ): Promise<AnyValidateFunction> { await loadMetaSchema.call(this, _schema.$schema) const sch = this._addSchema(_schema, _meta) return sch.validate || _compileAsync.call(this, sch) } async function loadMetaSchema(this: Ajv, $ref?: string): Promise<void> { if ($ref && !this.getSchema($ref)) { await runCompileAsync.call(this, {$ref}, true) } } async function _compileAsync(this: Ajv, sch: SchemaEnv): Promise<AnyValidateFunction> { try { return this._compileSchemaEnv(sch) } catch (e) { if (!(e instanceof MissingRefError)) throw e checkLoaded.call(this, e) await loadMissingSchema.call(this, e.missingSchema) return _compileAsync.call(this, sch) } } function checkLoaded(this: Ajv, {missingSchema: ref, missingRef}: MissingRefError): void { if (this.refs[ref]) { throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`) } } async function loadMissingSchema(this: Ajv, ref: string): Promise<void> { const _schema = await _loadSchema.call(this, ref) if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema) if (!this.refs[ref]) this.addSchema(_schema, ref, meta) } async function _loadSchema(this: Ajv, ref: string): Promise<AnySchemaObject> { const p = this._loading[ref] if (p) return p try { return await (this._loading[ref] = loadSchema(ref)) } finally { delete this._loading[ref] } } } // Adds schema to the instance addSchema( schema: AnySchema | AnySchema[], // If array is passed, `key` will be ignored key?: string, // Optional schema key. Can be passed to `validate` method instead of schema object or id/ref. One schema per instance can have empty `id` and `key`. _meta?: boolean, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead. _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead. ): Ajv { if (Array.isArray(schema)) { for (const sch of schema) this.addSchema(sch, undefined, _meta, _validateSchema) return this } let id: string | undefined if (typeof schema === "object") { const {schemaId} = this.opts id = schema[schemaId] if (id !== undefined && typeof id != "string") { throw new Error(`schema ${schemaId} must be string`) } } key = normalizeId(key || id) this._checkUnique(key) this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true) return this } // Add schema that will be used to validate other schemas // options in META_IGNORE_OPTIONS are alway set to false addMetaSchema( schema: AnySchemaObject, key?: string, // schema key _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema ): Ajv { this.addSchema(schema, key, true, _validateSchema) return this } // Validate schema against its meta-schema validateSchema(schema: AnySchema, throwOrLogError?: boolean): boolean | Promise<unknown> { if (typeof schema == "boolean") return true let $schema: string | AnySchemaObject | undefined $schema = schema.$schema if ($schema !== undefined && typeof $schema != "string") { throw new Error("$schema must be a string") } $schema = $schema || this.opts.defaultMeta || this.defaultMeta() if (!$schema) { this.logger.warn("meta-schema not available") this.errors = null return true } const valid = this.validate($schema, schema) if (!valid && throwOrLogError) { const message = "schema is invalid: " + this.errorsText() if (this.opts.validateSchema === "log") this.logger.error(message) else throw new Error(message) } return valid } // Get compiled schema by `key` or `ref`. // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id) getSchema<T = unknown>(keyRef: string): AnyValidateFunction<T> | undefined { let sch while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch if (sch === undefined) { const {schemaId} = this.opts const root = new SchemaEnv({schema: {}, schemaId}) sch = resolveSchema.call(this, root, keyRef) if (!sch) return this.refs[keyRef] = sch } return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction<T> | undefined } // Remove cached schema(s). // If no parameter is passed all schemas but meta-schemas are removed. // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed. // Even if schema is referenced by other schemas it still can be removed as other schemas have local references. removeSchema(schemaKeyRef?: AnySchema | string | RegExp): Ajv { if (schemaKeyRef instanceof RegExp) { this._removeAllSchemas(this.schemas, schemaKeyRef) this._removeAllSchemas(this.refs, schemaKeyRef) return this } switch (typeof schemaKeyRef) { case "undefined": this._removeAllSchemas(this.schemas) this._removeAllSchemas(this.refs) this._cache.clear() return this case "string": { const sch = getSchEnv.call(this, schemaKeyRef) if (typeof sch == "object") this._cache.delete(sch.schema) delete this.schemas[schemaKeyRef] delete this.refs[schemaKeyRef] return this } case "object": { const cacheKey = schemaKeyRef this._cache.delete(cacheKey) let id = schemaKeyRef[this.opts.schemaId] if (id) { id = normalizeId(id) delete this.schemas[id] delete this.refs[id] } return this } default: throw new Error("ajv.removeSchema: invalid parameter") } } // add "vocabulary" - a collection of keywords addVocabulary(definitions: Vocabulary): Ajv { for (const def of definitions) this.addKeyword(def) return this } addKeyword( kwdOrDef: string | KeywordDefinition, def?: KeywordDefinition // deprecated ): Ajv { let keyword: string | string[] if (typeof kwdOrDef == "string") { keyword = kwdOrDef if (typeof def == "object") { this.logger.warn("these parameters are deprecated, see docs for addKeyword") def.keyword = keyword } } else if (typeof kwdOrDef == "object" && def === undefined) { def = kwdOrDef keyword = def.keyword if (Array.isArray(keyword) && !keyword.length) { throw new Error("addKeywords: keyword must be string or non-empty array") } } else { throw new Error("invalid addKeywords parameters") } checkKeyword.call(this, keyword, def) if (!def) { eachItem(keyword, (kwd) => addRule.call(this, kwd)) return this } keywordMetaschema.call(this, def) const definition: AddedKeywordDefinition = { ...def, type: getJSONTypes(def.type), schemaType: getJSONTypes(def.schemaType), } eachItem( keyword, definition.type.length === 0 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)) ) return this } getKeyword(keyword: string): AddedKeywordDefinition | boolean { const rule = this.RULES.all[keyword] return typeof rule == "object" ? rule.definition : !!rule } // Remove keyword removeKeyword(keyword: string): Ajv { // TODO return type should be Ajv const {RULES} = this delete RULES.keywords[keyword] delete RULES.all[keyword] for (const group of RULES.rules) { const i = group.rules.findIndex((rule) => rule.keyword === keyword) if (i >= 0) group.rules.splice(i, 1) } return this } // Add format addFormat(name: string, format: Format): Ajv { if (typeof format == "string") format = new RegExp(format) this.formats[name] = format return this } errorsText( errors: ErrorObject[] | null | undefined = this.errors, // optional array of validation errors {separator = ", ", dataVar = "data"}: ErrorsTextOptions = {} // optional options with properties `separator` and `dataVar` ): string { if (!errors || errors.length === 0) return "No errors" return errors .map((e) => `${dataVar}${e.instancePath} ${e.message}`) .reduce((text, msg) => text + separator + msg) } $dataMetaSchema(metaSchema: AnySchemaObject, keywordsJsonPointers: string[]): AnySchemaObject { const rules = this.RULES.all metaSchema = JSON.parse(JSON.stringify(metaSchema)) for (const jsonPointer of keywordsJsonPointers) { const segments = jsonPointer.split("/").slice(1) // first segment is an empty string let keywords = metaSchema for (const seg of segments) keywords = keywords[seg] as AnySchemaObject for (const key in rules) { const rule = rules[key] if (typeof rule != "object") continue const {$data} = rule.definition const schema = keywords[key] as AnySchemaObject | undefined if ($data && schema) keywords[key] = schemaOrData(schema) } } return metaSchema } private _removeAllSchemas(schemas: {[Ref in string]?: SchemaEnv | string}, regex?: RegExp): void { for (const keyRef in schemas) { const sch = schemas[keyRef] if (!regex || regex.test(keyRef)) { if (typeof sch == "string") { delete schemas[keyRef] } else if (sch && !sch.meta) { this._cache.delete(sch.schema) delete schemas[keyRef] } } } } _addSchema( schema: AnySchema, meta?: boolean, baseId?: string, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema ): SchemaEnv { let id: string | undefined const {schemaId} = this.opts if (typeof schema == "object") { id = schema[schemaId] } else { if (this.opts.jtd) throw new Error("schema must be object") else if (typeof schema != "boolean") throw new Error("schema must be object or boolean") } let sch = this._cache.get(schema) if (sch !== undefined) return sch baseId = normalizeId(id || baseId) const localRefs = getSchemaRefs.call(this, schema, baseId) sch = new SchemaEnv({schema, schemaId, meta, baseId, localRefs}) this._cache.set(sch.schema, sch) if (addSchema && !baseId.startsWith("#")) { // TODO atm it is allowed to overwrite schemas without id (instead of not adding them) if (baseId) this._checkUnique(baseId) this.refs[baseId] = sch } if (validateSchema) this.validateSchema(schema, true) return sch } private _checkUnique(id: string): void { if (this.schemas[id] || this.refs[id]) { throw new Error(`schema with key or id "${id}" already exists`) } } private _compileSchemaEnv(sch: SchemaEnv): AnyValidateFunction { if (sch.meta) this._compileMetaSchema(sch) else compileSchema.call(this, sch) /* istanbul ignore if */ if (!sch.validate) throw new Error("ajv implementation error") return sch.validate } private _compileMetaSchema(sch: SchemaEnv): void { const currentOpts = this.opts this.opts = this._metaOpts try { compileSchema.call(this, sch) } finally { this.opts = currentOpts } } }
2,626
function compileSerializer( this: Ajv, sch: SchemaEnv, definitions: SchemaObjectMap ): SchemaEnv { const _sch = getCompilingSchema.call(this, sch) if (_sch) return _sch const {es5, lines} = this.opts.code const {ownProperties} = this.opts const gen = new CodeGen(this.scope, {es5, lines, ownProperties}) const serializeName = gen.scopeName("serialize") const cxt: SerializeCxt = { self: this, gen, schema: sch.schema as SchemaObject, schemaEnv: sch, definitions, data: N.data, } let sourceCode: string | undefined try { this._compilations.add(sch) sch.serializeName = serializeName gen.func(serializeName, N.data, false, () => { gen.let(N.json, str``) serializeCode(cxt) gen.return(N.json) }) gen.optimize(this.opts.code.optimize) const serializeFuncCode = gen.toString() sourceCode = `${gen.scopeRefs(N.scope)}return ${serializeFuncCode}` const makeSerialize = new Function(`${N.scope}`, sourceCode) const serialize: (data: unknown) => string = makeSerialize(this.scope.get()) this.scope.value(serializeName, {ref: serialize}) sch.serialize = serialize } catch (e) { if (sourceCode) this.logger.error("Error compiling serializer, function code:", sourceCode) delete sch.serialize delete sch.serializeName throw e } finally { this._compilations.delete(sch) } return sch }
class Ajv extends AjvCore { constructor(opts: JTDOptions = {}) { super({ ...opts, jtd: true, }) } _addVocabularies(): void { super._addVocabularies() this.addVocabulary(jtdVocabulary) } _addDefaultMetaSchema(): void { super._addDefaultMetaSchema() if (!this.opts.meta) return this.addMetaSchema(jtdMetaSchema, META_SCHEMA_ID, false) } defaultMeta(): string | AnySchemaObject | undefined { return (this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined)) } compileSerializer<T = unknown>(schema: SchemaObject): (data: T) => string // Separated for type inference to work // eslint-disable-next-line @typescript-eslint/unified-signatures compileSerializer<T = unknown>(schema: JTDSchemaType<T>): (data: T) => string compileSerializer<T = unknown>(schema: SchemaObject): (data: T) => string { const sch = this._addSchema(schema) return sch.serialize || this._compileSerializer(sch) } compileParser<T = unknown>(schema: SchemaObject): JTDParser<T> // Separated for type inference to work // eslint-disable-next-line @typescript-eslint/unified-signatures compileParser<T = unknown>(schema: JTDSchemaType<T>): JTDParser<T> compileParser<T = unknown>(schema: SchemaObject): JTDParser<T> { const sch = this._addSchema(schema) return (sch.parse || this._compileParser(sch)) as JTDParser<T> } private _compileSerializer<T>(sch: SchemaEnv): (data: T) => string { compileSerializer.call(this, sch, (sch.schema as AnySchemaObject).definitions || {}) /* istanbul ignore if */ if (!sch.serialize) throw new Error("ajv implementation error") return sch.serialize } private _compileParser(sch: SchemaEnv): JTDParser { compileParser.call(this, sch, (sch.schema as AnySchemaObject).definitions || {}) /* istanbul ignore if */ if (!sch.parse) throw new Error("ajv implementation error") return sch.parse } }
2,627
function compileSerializer( this: Ajv, sch: SchemaEnv, definitions: SchemaObjectMap ): SchemaEnv { const _sch = getCompilingSchema.call(this, sch) if (_sch) return _sch const {es5, lines} = this.opts.code const {ownProperties} = this.opts const gen = new CodeGen(this.scope, {es5, lines, ownProperties}) const serializeName = gen.scopeName("serialize") const cxt: SerializeCxt = { self: this, gen, schema: sch.schema as SchemaObject, schemaEnv: sch, definitions, data: N.data, } let sourceCode: string | undefined try { this._compilations.add(sch) sch.serializeName = serializeName gen.func(serializeName, N.data, false, () => { gen.let(N.json, str``) serializeCode(cxt) gen.return(N.json) }) gen.optimize(this.opts.code.optimize) const serializeFuncCode = gen.toString() sourceCode = `${gen.scopeRefs(N.scope)}return ${serializeFuncCode}` const makeSerialize = new Function(`${N.scope}`, sourceCode) const serialize: (data: unknown) => string = makeSerialize(this.scope.get()) this.scope.value(serializeName, {ref: serialize}) sch.serialize = serialize } catch (e) { if (sourceCode) this.logger.error("Error compiling serializer, function code:", sourceCode) delete sch.serialize delete sch.serializeName throw e } finally { this._compilations.delete(sch) } return sch }
class Ajv extends AjvCore { _addVocabularies(): void { super._addVocabularies() draft7Vocabularies.forEach((v) => this.addVocabulary(v)) if (this.opts.discriminator) this.addKeyword(discriminator) } _addDefaultMetaSchema(): void { super._addDefaultMetaSchema() if (!this.opts.meta) return const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema this.addMetaSchema(metaSchema, META_SCHEMA_ID, false) this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID } defaultMeta(): string | AnySchemaObject | undefined { return (this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : undefined)) } }
2,628
function compileSerializer( this: Ajv, sch: SchemaEnv, definitions: SchemaObjectMap ): SchemaEnv { const _sch = getCompilingSchema.call(this, sch) if (_sch) return _sch const {es5, lines} = this.opts.code const {ownProperties} = this.opts const gen = new CodeGen(this.scope, {es5, lines, ownProperties}) const serializeName = gen.scopeName("serialize") const cxt: SerializeCxt = { self: this, gen, schema: sch.schema as SchemaObject, schemaEnv: sch, definitions, data: N.data, } let sourceCode: string | undefined try { this._compilations.add(sch) sch.serializeName = serializeName gen.func(serializeName, N.data, false, () => { gen.let(N.json, str``) serializeCode(cxt) gen.return(N.json) }) gen.optimize(this.opts.code.optimize) const serializeFuncCode = gen.toString() sourceCode = `${gen.scopeRefs(N.scope)}return ${serializeFuncCode}` const makeSerialize = new Function(`${N.scope}`, sourceCode) const serialize: (data: unknown) => string = makeSerialize(this.scope.get()) this.scope.value(serializeName, {ref: serialize}) sch.serialize = serialize } catch (e) { if (sourceCode) this.logger.error("Error compiling serializer, function code:", sourceCode) delete sch.serialize delete sch.serializeName throw e } finally { this._compilations.delete(sch) } return sch }
type SchemaObjectMap = {[Ref in string]?: SchemaObject}
2,629
function serializeCode(cxt: SerializeCxt): void { let form: JTDForm | undefined for (const key of jtdForms) { if (key in cxt.schema) { form = key break } } serializeNullable(cxt, form ? genSerialize[form] : serializeEmpty) }
interface SerializeCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code }
2,630
function serializeNullable(cxt: SerializeCxt, serializeForm: (_cxt: SerializeCxt) => void): void { const {gen, schema, data} = cxt if (!schema.nullable) return serializeForm(cxt) gen.if( _`${data} === undefined || ${data} === null`, () => gen.add(N.json, _`"null"`), () => serializeForm(cxt) ) }
interface SerializeCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code }
2,631
(_cxt: SerializeCxt) => void
interface SerializeCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code }
2,632
function serializeElements(cxt: SerializeCxt): void { const {gen, schema, data} = cxt gen.add(N.json, str`[`) const first = gen.let("first", true) gen.forOf("el", data, (el) => { addComma(cxt, first) serializeCode({...cxt, schema: schema.elements, data: el}) }) gen.add(N.json, str`]`) }
interface SerializeCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code }
2,633
function serializeValues(cxt: SerializeCxt): void { const {gen, schema, data} = cxt gen.add(N.json, str`{`) const first = gen.let("first", true) gen.forIn("key", data, (key) => serializeKeyValue(cxt, key, schema.values, first)) gen.add(N.json, str`}`) }
interface SerializeCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code }
2,634
function serializeKeyValue(cxt: SerializeCxt, key: Name, schema: SchemaObject, first?: Name): void { const {gen, data} = cxt addComma(cxt, first) serializeString({...cxt, data: key}) gen.add(N.json, str`:`) const value = gen.const("value", _`${data}${getProperty(key)}`) serializeCode({...cxt, schema, data: value}) }
interface SerializeCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code }
2,635
function serializeKeyValue(cxt: SerializeCxt, key: Name, schema: SchemaObject, first?: Name): void { const {gen, data} = cxt addComma(cxt, first) serializeString({...cxt, data: key}) gen.add(N.json, str`:`) const value = gen.const("value", _`${data}${getProperty(key)}`) serializeCode({...cxt, schema, data: value}) }
class Name extends _CodeOrName { readonly str: string constructor(s: string) { super() if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier") this.str = s } toString(): string { return this.str } emptyStr(): boolean { return false } get names(): UsedNames { return {[this.str]: 1} } }
2,636
function serializeKeyValue(cxt: SerializeCxt, key: Name, schema: SchemaObject, first?: Name): void { const {gen, data} = cxt addComma(cxt, first) serializeString({...cxt, data: key}) gen.add(N.json, str`:`) const value = gen.const("value", _`${data}${getProperty(key)}`) serializeCode({...cxt, schema, data: value}) }
interface SchemaObject extends _SchemaObject { id?: string $id?: string $schema?: string $async?: false [x: string]: any // TODO }
2,637
function serializeDiscriminator(cxt: SerializeCxt): void { const {gen, schema, data} = cxt const {discriminator} = schema gen.add(N.json, str`{${JSON.stringify(discriminator)}:`) const tag = gen.const("tag", _`${data}${getProperty(discriminator)}`) serializeString({...cxt, data: tag}) gen.if(false) for (const tagValue in schema.mapping) { gen.elseIf(_`${tag} === ${tagValue}`) const sch = schema.mapping[tagValue] serializeSchemaProperties({...cxt, schema: sch}, discriminator) } gen.endIf() gen.add(N.json, str`}`) }
interface SerializeCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code }
2,638
function serializeProperties(cxt: SerializeCxt): void { const {gen} = cxt gen.add(N.json, str`{`) serializeSchemaProperties(cxt) gen.add(N.json, str`}`) }
interface SerializeCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code }
2,639
function serializeSchemaProperties(cxt: SerializeCxt, discriminator?: string): void { const {gen, schema, data} = cxt const {properties, optionalProperties} = schema const props = keys(properties) const optProps = keys(optionalProperties) const allProps = allProperties(props.concat(optProps)) let first = !discriminator let firstProp: Name | undefined for (const key of props) { if (first) first = false else gen.add(N.json, str`,`) serializeProperty(key, properties[key], keyValue(key)) } if (first) firstProp = gen.let("first", true) for (const key of optProps) { const value = keyValue(key) gen.if(and(_`${value} !== undefined`, isOwnProperty(gen, data, key)), () => { addComma(cxt, firstProp) serializeProperty(key, optionalProperties[key], value) }) } if (schema.additionalProperties) { gen.forIn("key", data, (key) => gen.if(isAdditional(key, allProps), () => serializeKeyValue(cxt, key, {}, firstProp)) ) } function keys(ps?: SchemaObjectMap): string[] { return ps ? Object.keys(ps) : [] } function allProperties(ps: string[]): string[] { if (discriminator) ps.push(discriminator) if (new Set(ps).size !== ps.length) { throw new Error("JTD: properties/optionalProperties/disciminator overlap") } return ps } function keyValue(key: string): Name { return gen.const("value", _`${data}${getProperty(key)}`) } function serializeProperty(key: string, propSchema: SchemaObject, value: Name): void { gen.add(N.json, str`${JSON.stringify(key)}:`) serializeCode({...cxt, schema: propSchema, data: value}) } function isAdditional(key: Name, ps: string[]): Code | true { return ps.length ? and(...ps.map((p) => _`${key} !== ${p}`)) : true } }
interface SerializeCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code }
2,640
function keys(ps?: SchemaObjectMap): string[] { return ps ? Object.keys(ps) : [] }
type SchemaObjectMap = {[Ref in string]?: SchemaObject}
2,641
function isAdditional(key: Name, ps: string[]): Code | true { return ps.length ? and(...ps.map((p) => _`${key} !== ${p}`)) : true }
class Name extends _CodeOrName { readonly str: string constructor(s: string) { super() if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier") this.str = s } toString(): string { return this.str } emptyStr(): boolean { return false } get names(): UsedNames { return {[this.str]: 1} } }
2,642
function serializeType(cxt: SerializeCxt): void { const {gen, schema, data} = cxt switch (schema.type) { case "boolean": gen.add(N.json, _`${data} ? "true" : "false"`) break case "string": serializeString(cxt) break case "timestamp": gen.if( _`${data} instanceof Date`, () => gen.add(N.json, _`'"' + ${data}.toISOString() + '"'`), () => serializeString(cxt) ) break default: serializeNumber(cxt) } }
interface SerializeCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code }
2,643
function serializeString({gen, data}: SerializeCxt): void { gen.add(N.json, _`${useFunc(gen, quote)}(${data})`) }
interface SerializeCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code }
2,644
function serializeNumber({gen, data}: SerializeCxt): void { gen.add(N.json, _`"" + ${data}`) }
interface SerializeCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code }
2,645
function serializeRef(cxt: SerializeCxt): void { const {gen, self, data, definitions, schema, schemaEnv} = cxt const {ref} = schema const refSchema = definitions[ref] if (!refSchema) throw new MissingRefError(self.opts.uriResolver, "", ref, `No definition ${ref}`) if (!hasRef(refSchema)) return serializeCode({...cxt, schema: refSchema}) const {root} = schemaEnv const sch = compileSerializer.call(self, new SchemaEnv({schema: refSchema, root}), definitions) gen.add(N.json, _`${getSerialize(gen, sch)}(${data})`) }
interface SerializeCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code }
2,646
function getSerialize(gen: CodeGen, sch: SchemaEnv): Code { return sch.serialize ? gen.scopeValue("serialize", {ref: sch.serialize}) : _`${gen.scopeValue("wrapper", {ref: sch})}.serialize` }
class SchemaEnv implements SchemaEnvArgs { readonly schema: AnySchema readonly schemaId?: "$id" | "id" readonly root: SchemaEnv baseId: string // TODO possibly, it should be readonly schemaPath?: string localRefs?: LocalRefs readonly meta?: boolean readonly $async?: boolean // true if the current schema is asynchronous. readonly refs: SchemaRefs = {} readonly dynamicAnchors: {[Ref in string]?: true} = {} validate?: AnyValidateFunction validateName?: ValueScopeName serialize?: (data: unknown) => string serializeName?: ValueScopeName parse?: (data: string) => unknown parseName?: ValueScopeName constructor(env: SchemaEnvArgs) { let schema: AnySchemaObject | undefined if (typeof env.schema == "object") schema = env.schema this.schema = env.schema this.schemaId = env.schemaId this.root = env.root || this this.baseId = env.baseId ?? normalizeId(schema?.[env.schemaId || "$id"]) this.schemaPath = env.schemaPath this.localRefs = env.localRefs this.meta = env.meta this.$async = schema?.$async this.refs = {} } }
2,647
function getSerialize(gen: CodeGen, sch: SchemaEnv): Code { return sch.serialize ? gen.scopeValue("serialize", {ref: sch.serialize}) : _`${gen.scopeValue("wrapper", {ref: sch})}.serialize` }
class CodeGen { readonly _scope: Scope readonly _extScope: ValueScope readonly _values: ScopeValueSets = {} private readonly _nodes: ParentNode[] private readonly _blockStarts: number[] = [] private readonly _constants: Constants = {} private readonly opts: CGOptions constructor(extScope: ValueScope, opts: CodeGenOptions = {}) { this.opts = {...opts, _n: opts.lines ? "\n" : ""} this._extScope = extScope this._scope = new Scope({parent: extScope}) this._nodes = [new Root()] } toString(): string { return this._root.render(this.opts) } // returns unique name in the internal scope name(prefix: string): Name { return this._scope.name(prefix) } // reserves unique name in the external scope scopeName(prefix: string): ValueScopeName { return this._extScope.name(prefix) } // reserves unique name in the external scope and assigns value to it scopeValue(prefixOrName: ValueScopeName | string, value: NameValue): Name { const name = this._extScope.value(prefixOrName, value) const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set()) vs.add(name) return name } getScopeValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined { return this._extScope.getValue(prefix, keyOrRef) } // return code that assigns values in the external scope to the names that are used internally // (same names that were returned by gen.scopeName or gen.scopeValue) scopeRefs(scopeName: Name): Code { return this._extScope.scopeRefs(scopeName, this._values) } scopeCode(): Code { return this._extScope.scopeCode(this._values) } private _def( varKind: Name, nameOrPrefix: Name | string, rhs?: SafeExpr, constant?: boolean ): Name { const name = this._scope.toName(nameOrPrefix) if (rhs !== undefined && constant) this._constants[name.str] = rhs this._leafNode(new Def(varKind, name, rhs)) return name } // `const` declaration (`var` in es5 mode) const(nameOrPrefix: Name | string, rhs: SafeExpr, _constant?: boolean): Name { return this._def(varKinds.const, nameOrPrefix, rhs, _constant) } // `let` declaration with optional assignment (`var` in es5 mode) let(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name { return this._def(varKinds.let, nameOrPrefix, rhs, _constant) } // `var` declaration with optional assignment var(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name { return this._def(varKinds.var, nameOrPrefix, rhs, _constant) } // assignment code assign(lhs: Code, rhs: SafeExpr, sideEffects?: boolean): CodeGen { return this._leafNode(new Assign(lhs, rhs, sideEffects)) } // `+=` code add(lhs: Code, rhs: SafeExpr): CodeGen { return this._leafNode(new AssignOp(lhs, operators.ADD, rhs)) } // appends passed SafeExpr to code or executes Block code(c: Block | SafeExpr): CodeGen { if (typeof c == "function") c() else if (c !== nil) this._leafNode(new AnyCode(c)) return this } // returns code for object literal for the passed argument list of key-value pairs object(...keyValues: [Name | string, SafeExpr | string][]): _Code { const code: CodeItem[] = ["{"] for (const [key, value] of keyValues) { if (code.length > 1) code.push(",") code.push(key) if (key !== value || this.opts.es5) { code.push(":") addCodeArg(code, value) } } code.push("}") return new _Code(code) } // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed) if(condition: Code | boolean, thenBody?: Block, elseBody?: Block): CodeGen { this._blockNode(new If(condition)) if (thenBody && elseBody) { this.code(thenBody).else().code(elseBody).endIf() } else if (thenBody) { this.code(thenBody).endIf() } else if (elseBody) { throw new Error('CodeGen: "else" body without "then" body') } return this } // `else if` clause - invalid without `if` or after `else` clauses elseIf(condition: Code | boolean): CodeGen { return this._elseNode(new If(condition)) } // `else` clause - only valid after `if` or `else if` clauses else(): CodeGen { return this._elseNode(new Else()) } // end `if` statement (needed if gen.if was used only with condition) endIf(): CodeGen { return this._endBlockNode(If, Else) } private _for(node: For, forBody?: Block): CodeGen { this._blockNode(node) if (forBody) this.code(forBody).endFor() return this } // a generic `for` clause (or statement if `forBody` is passed) for(iteration: Code, forBody?: Block): CodeGen { return this._for(new ForLoop(iteration), forBody) } // `for` statement for a range of values forRange( nameOrPrefix: Name | string, from: SafeExpr, to: SafeExpr, forBody: (index: Name) => void, varKind: Code = this.opts.es5 ? varKinds.var : varKinds.let ): CodeGen { const name = this._scope.toName(nameOrPrefix) return this._for(new ForRange(varKind, name, from, to), () => forBody(name)) } // `for-of` statement (in es5 mode replace with a normal for loop) forOf( nameOrPrefix: Name | string, iterable: Code, forBody: (item: Name) => void, varKind: Code = varKinds.const ): CodeGen { const name = this._scope.toName(nameOrPrefix) if (this.opts.es5) { const arr = iterable instanceof Name ? iterable : this.var("_arr", iterable) return this.forRange("_i", 0, _`${arr}.length`, (i) => { this.var(name, _`${arr}[${i}]`) forBody(name) }) } return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name)) } // `for-in` statement. // With option `ownProperties` replaced with a `for-of` loop for object keys forIn( nameOrPrefix: Name | string, obj: Code, forBody: (item: Name) => void, varKind: Code = this.opts.es5 ? varKinds.var : varKinds.const ): CodeGen { if (this.opts.ownProperties) { return this.forOf(nameOrPrefix, _`Object.keys(${obj})`, forBody) } const name = this._scope.toName(nameOrPrefix) return this._for(new ForIter("in", varKind, name, obj), () => forBody(name)) } // end `for` loop endFor(): CodeGen { return this._endBlockNode(For) } // `label` statement label(label: Name): CodeGen { return this._leafNode(new Label(label)) } // `break` statement break(label?: Code): CodeGen { return this._leafNode(new Break(label)) } // `return` statement return(value: Block | SafeExpr): CodeGen { const node = new Return() this._blockNode(node) this.code(value) if (node.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node') return this._endBlockNode(Return) } // `try` statement try(tryBody: Block, catchCode?: (e: Name) => void, finallyCode?: Block): CodeGen { if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"') const node = new Try() this._blockNode(node) this.code(tryBody) if (catchCode) { const error = this.name("e") this._currNode = node.catch = new Catch(error) catchCode(error) } if (finallyCode) { this._currNode = node.finally = new Finally() this.code(finallyCode) } return this._endBlockNode(Catch, Finally) } // `throw` statement throw(error: Code): CodeGen { return this._leafNode(new Throw(error)) } // start self-balancing block block(body?: Block, nodeCount?: number): CodeGen { this._blockStarts.push(this._nodes.length) if (body) this.code(body).endBlock(nodeCount) return this } // end the current self-balancing block endBlock(nodeCount?: number): CodeGen { const len = this._blockStarts.pop() if (len === undefined) throw new Error("CodeGen: not in self-balancing block") const toClose = this._nodes.length - len if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) { throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`) } this._nodes.length = len return this } // `function` heading (or definition if funcBody is passed) func(name: Name, args: Code = nil, async?: boolean, funcBody?: Block): CodeGen { this._blockNode(new Func(name, args, async)) if (funcBody) this.code(funcBody).endFunc() return this } // end function definition endFunc(): CodeGen { return this._endBlockNode(Func) } optimize(n = 1): void { while (n-- > 0) { this._root.optimizeNodes() this._root.optimizeNames(this._root.names, this._constants) } } private _leafNode(node: LeafNode): CodeGen { this._currNode.nodes.push(node) return this } private _blockNode(node: StartBlockNode): void { this._currNode.nodes.push(node) this._nodes.push(node) } private _endBlockNode(N1: EndBlockNodeType, N2?: EndBlockNodeType): CodeGen { const n = this._currNode if (n instanceof N1 || (N2 && n instanceof N2)) { this._nodes.pop() return this } throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`) } private _elseNode(node: If | Else): CodeGen { const n = this._currNode if (!(n instanceof If)) { throw new Error('CodeGen: "else" without "if"') } this._currNode = n.else = node return this } private get _root(): Root { return this._nodes[0] as Root } private get _currNode(): ParentNode { const ns = this._nodes return ns[ns.length - 1] } private set _currNode(node: ParentNode) { const ns = this._nodes ns[ns.length - 1] = node } // get nodeCount(): number { // return this._root.count // } }
2,648
function serializeEmpty({gen, data}: SerializeCxt): void { gen.add(N.json, _`JSON.stringify(${data})`) }
interface SerializeCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code }
2,649
function addComma({gen}: SerializeCxt, first?: Name): void { if (first) { gen.if( first, () => gen.assign(first, false), () => gen.add(N.json, str`,`) ) } else { gen.add(N.json, str`,`) } }
interface SerializeCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code }
2,650
function addComma({gen}: SerializeCxt, first?: Name): void { if (first) { gen.if( first, () => gen.assign(first, false), () => gen.add(N.json, str`,`) ) } else { gen.add(N.json, str`,`) } }
class Name extends _CodeOrName { readonly str: string constructor(s: string) { super() if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier") this.str = s } toString(): string { return this.str } emptyStr(): boolean { return false } get names(): UsedNames { return {[this.str]: 1} } }
2,651
(names: UsedNames, c) => { if (c instanceof Name) names[c.str] = (names[c.str] || 0) + 1 return names }
type UsedNames = Record<string, number | undefined>
2,652
function mergeExprItems(a: CodeItem, b: CodeItem): CodeItem | undefined { if (b === '""') return a if (a === '""') return b if (typeof a == "string") { if (b instanceof Name || a[a.length - 1] !== '"') return if (typeof b != "string") return `${a.slice(0, -1)}${b}"` if (b[0] === '"') return a.slice(0, -1) + b.slice(1) return } if (typeof b == "string" && b[0] === '"' && !(a instanceof Name)) return `"${a}${b.slice(1)}` return }
type CodeItem = Name | string | number | boolean | null
2,653
function strConcat(c1: Code, c2: Code): Code { return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}` }
type Code = _Code | Name
2,654
optimizeNames(_names: UsedNames, _constants: Constants): this | undefined { return this }
type Constants = Record<string, SafeExpr | undefined>
2,655
optimizeNames(_names: UsedNames, _constants: Constants): this | undefined { return this }
type UsedNames = Record<string, number | undefined>
2,656
constructor(private readonly varKind: Name, private readonly name: Name, private rhs?: SafeExpr) { super() }
type SafeExpr = Code | number | boolean | null
2,657
constructor(private readonly varKind: Name, private readonly name: Name, private rhs?: SafeExpr) { super() }
type SafeExpr = Code | number | boolean | null
2,658
constructor(private readonly varKind: Name, private readonly name: Name, private rhs?: SafeExpr) { super() }
class Name extends _CodeOrName { readonly str: string constructor(s: string) { super() if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier") this.str = s } toString(): string { return this.str } emptyStr(): boolean { return false } get names(): UsedNames { return {[this.str]: 1} } }
2,659
render({es5, _n}: CGOptions): string { const varKind = es5 ? varKinds.var : this.varKind const rhs = this.rhs === undefined ? "" : ` = ${this.rhs}` return `${varKind} ${this.name}${rhs};` + _n }
interface CGOptions extends CodeGenOptions { _n: "\n" | "" }
2,660
optimizeNames(names: UsedNames, constants: Constants): this | undefined { if (!names[this.name.str]) return if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants) return this }
type Constants = Record<string, SafeExpr | undefined>
2,661
optimizeNames(names: UsedNames, constants: Constants): this | undefined { if (!names[this.name.str]) return if (this.rhs) this.rhs = optimizeExpr(this.rhs, names, constants) return this }
type UsedNames = Record<string, number | undefined>
2,662
constructor(readonly lhs: Code, public rhs: SafeExpr, private readonly sideEffects?: boolean) { super() }
type SafeExpr = Code | number | boolean | null
2,663
constructor(readonly lhs: Code, public rhs: SafeExpr, private readonly sideEffects?: boolean) { super() }
type SafeExpr = Code | number | boolean | null
2,664
constructor(readonly lhs: Code, public rhs: SafeExpr, private readonly sideEffects?: boolean) { super() }
type Code = _Code | Name
2,665
render({_n}: CGOptions): string { return `${this.lhs} = ${this.rhs};` + _n }
interface CGOptions extends CodeGenOptions { _n: "\n" | "" }
2,666
optimizeNames(names: UsedNames, constants: Constants): this | undefined { if (this.lhs instanceof Name && !names[this.lhs.str] && !this.sideEffects) return this.rhs = optimizeExpr(this.rhs, names, constants) return this }
type Constants = Record<string, SafeExpr | undefined>
2,667
optimizeNames(names: UsedNames, constants: Constants): this | undefined { if (this.lhs instanceof Name && !names[this.lhs.str] && !this.sideEffects) return this.rhs = optimizeExpr(this.rhs, names, constants) return this }
type UsedNames = Record<string, number | undefined>
2,668
constructor(lhs: Code, private readonly op: Code, rhs: SafeExpr, sideEffects?: boolean) { super(lhs, rhs, sideEffects) }
type SafeExpr = Code | number | boolean | null
2,669
constructor(lhs: Code, private readonly op: Code, rhs: SafeExpr, sideEffects?: boolean) { super(lhs, rhs, sideEffects) }
type SafeExpr = Code | number | boolean | null
2,670
constructor(lhs: Code, private readonly op: Code, rhs: SafeExpr, sideEffects?: boolean) { super(lhs, rhs, sideEffects) }
type Code = _Code | Name
2,671
render({_n}: CGOptions): string { return `${this.lhs} ${this.op}= ${this.rhs};` + _n }
interface CGOptions extends CodeGenOptions { _n: "\n" | "" }
2,672
constructor(readonly label: Name) { super() }
class Name extends _CodeOrName { readonly str: string constructor(s: string) { super() if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier") this.str = s } toString(): string { return this.str } emptyStr(): boolean { return false } get names(): UsedNames { return {[this.str]: 1} } }
2,673
render({_n}: CGOptions): string { return `${this.label}:` + _n }
interface CGOptions extends CodeGenOptions { _n: "\n" | "" }
2,674
constructor(readonly label?: Code) { super() }
type Code = _Code | Name
2,675
render({_n}: CGOptions): string { const label = this.label ? ` ${this.label}` : "" return `break${label};` + _n }
interface CGOptions extends CodeGenOptions { _n: "\n" | "" }
2,676
constructor(readonly error: Code) { super() }
type Code = _Code | Name
2,677
render({_n}: CGOptions): string { return `throw ${this.error};` + _n }
interface CGOptions extends CodeGenOptions { _n: "\n" | "" }
2,678
constructor(private code: SafeExpr) { super() }
type SafeExpr = Code | number | boolean | null
2,679
constructor(private code: SafeExpr) { super() }
type SafeExpr = Code | number | boolean | null
2,680
render({_n}: CGOptions): string { return `${this.code};` + _n }
interface CGOptions extends CodeGenOptions { _n: "\n" | "" }
2,681
optimizeNames(names: UsedNames, constants: Constants): this { this.code = optimizeExpr(this.code, names, constants) return this }
type Constants = Record<string, SafeExpr | undefined>
2,682
optimizeNames(names: UsedNames, constants: Constants): this { this.code = optimizeExpr(this.code, names, constants) return this }
type UsedNames = Record<string, number | undefined>
2,683
render(opts: CGOptions): string { return this.nodes.reduce((code, n) => code + n.render(opts), "") }
interface CGOptions extends CodeGenOptions { _n: "\n" | "" }
2,684
optimizeNames(names: UsedNames, constants: Constants): this | undefined { const {nodes} = this let i = nodes.length while (i--) { // iterating backwards improves 1-pass optimization const n = nodes[i] if (n.optimizeNames(names, constants)) continue subtractNames(names, n.names) nodes.splice(i, 1) } return nodes.length > 0 ? this : undefined }
type Constants = Record<string, SafeExpr | undefined>
2,685
optimizeNames(names: UsedNames, constants: Constants): this | undefined { const {nodes} = this let i = nodes.length while (i--) { // iterating backwards improves 1-pass optimization const n = nodes[i] if (n.optimizeNames(names, constants)) continue subtractNames(names, n.names) nodes.splice(i, 1) } return nodes.length > 0 ? this : undefined }
type UsedNames = Record<string, number | undefined>
2,686
(names: UsedNames, n) => addNames(names, n.names)
type UsedNames = Record<string, number | undefined>
2,687
render(opts: CGOptions): string { return "{" + opts._n + super.render(opts) + "}" + opts._n }
interface CGOptions extends CodeGenOptions { _n: "\n" | "" }
2,688
render(opts: CGOptions): string { let code = `if(${this.condition})` + super.render(opts) if (this.else) code += "else " + this.else.render(opts) return code }
interface CGOptions extends CodeGenOptions { _n: "\n" | "" }
2,689
optimizeNames(names: UsedNames, constants: Constants): this | undefined { this.else = this.else?.optimizeNames(names, constants) if (!(super.optimizeNames(names, constants) || this.else)) return this.condition = optimizeExpr(this.condition, names, constants) return this }
type Constants = Record<string, SafeExpr | undefined>
2,690
optimizeNames(names: UsedNames, constants: Constants): this | undefined { this.else = this.else?.optimizeNames(names, constants) if (!(super.optimizeNames(names, constants) || this.else)) return this.condition = optimizeExpr(this.condition, names, constants) return this }
type UsedNames = Record<string, number | undefined>
2,691
constructor(private iteration: Code) { super() }
type Code = _Code | Name
2,692
render(opts: CGOptions): string { return `for(${this.iteration})` + super.render(opts) }
interface CGOptions extends CodeGenOptions { _n: "\n" | "" }
2,693
optimizeNames(names: UsedNames, constants: Constants): this | undefined { if (!super.optimizeNames(names, constants)) return this.iteration = optimizeExpr(this.iteration, names, constants) return this }
type Constants = Record<string, SafeExpr | undefined>
2,694
optimizeNames(names: UsedNames, constants: Constants): this | undefined { if (!super.optimizeNames(names, constants)) return this.iteration = optimizeExpr(this.iteration, names, constants) return this }
type UsedNames = Record<string, number | undefined>
2,695
constructor( private readonly varKind: Name, private readonly name: Name, private readonly from: SafeExpr, private readonly to: SafeExpr ) { super() }
type SafeExpr = Code | number | boolean | null
2,696
constructor( private readonly varKind: Name, private readonly name: Name, private readonly from: SafeExpr, private readonly to: SafeExpr ) { super() }
type SafeExpr = Code | number | boolean | null
2,697
constructor( private readonly varKind: Name, private readonly name: Name, private readonly from: SafeExpr, private readonly to: SafeExpr ) { super() }
class Name extends _CodeOrName { readonly str: string constructor(s: string) { super() if (!IDENTIFIER.test(s)) throw new Error("CodeGen: name must be a valid identifier") this.str = s } toString(): string { return this.str } emptyStr(): boolean { return false } get names(): UsedNames { return {[this.str]: 1} } }
2,698
render(opts: CGOptions): string { const varKind = opts.es5 ? varKinds.var : this.varKind const {name, from, to} = this return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts) }
interface CGOptions extends CodeGenOptions { _n: "\n" | "" }
2,699
render(opts: CGOptions): string { return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts) }
interface CGOptions extends CodeGenOptions { _n: "\n" | "" }