id
int64
0
3.78k
code
stringlengths
13
37.9k
declarations
stringlengths
16
64.6k
2,300
code(cxt: KeywordCxt) { const {gen, data, $data, schema, schemaCode, it} = cxt if (!$data && schema.length === 0) throw new Error("enum must have non-empty array") const useLoop = schema.length >= it.opts.loopEnum let eql: Name | undefined const getEql = (): Name => (eql ??= useFunc(gen, equal)) let valid: Code if (useLoop || $data) { valid = gen.let("valid") cxt.block$data(valid, loopEnum) } else { /* istanbul ignore if */ if (!Array.isArray(schema)) throw new Error("ajv implementation error") const vSchema = gen.const("vSchema", schemaCode) valid = or(...schema.map((_x: unknown, i: number) => equalCode(vSchema, i))) } cxt.pass(valid) function loopEnum(): void { gen.assign(valid, false) gen.forOf("v", schemaCode as Code, (v) => gen.if(_`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break()) ) } function equalCode(vSchema: Name, i: number): Code { const sch = schema[i] return typeof sch === "object" && sch !== null ? _`${getEql()}(${data}, ${vSchema}[${i}])` : _`${data} === ${sch}` } }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,301
function equalCode(vSchema: Name, i: number): Code { const sch = schema[i] return typeof sch === "object" && sch !== null ? _`${getEql()}(${data}, ${vSchema}[${i}])` : _`${data} === ${sch}` }
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,302
code(cxt: KeywordCxt) { const {keyword, data, schemaCode} = cxt const op = keyword === "maxItems" ? operators.GT : operators.LT cxt.fail$data(_`${data}.length ${op} ${schemaCode}`) }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,303
code(cxt: KeywordCxt) { const {gen, data, schemaCode, it} = cxt // const bdt = bad$DataType(schemaCode, <string>def.schemaType, $data) const prec = it.opts.multipleOfPrecision const res = gen.let("res") const invalid = prec ? _`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : _`${res} !== parseInt(${res})` cxt.fail$data(_`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`) }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,304
code(cxt: KeywordCxt) { const {keyword, data, schemaCode} = cxt const op = keyword === "maxProperties" ? operators.GT : operators.LT cxt.fail$data(_`Object.keys(${data}).length ${op} ${schemaCode}`) }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,305
code(cxt: KeywordCxt) { const {gen, schema, schemaCode, data, $data, it} = cxt const {opts} = it if (!$data && schema.length === 0) return const useLoop = schema.length >= opts.loopRequired if (it.allErrors) allErrorsMode() else exitOnErrorMode() if (opts.strictRequired) { const props = cxt.parentSchema.properties const {definedProperties} = cxt.it for (const requiredKey of schema) { if (props?.[requiredKey] === undefined && !definedProperties.has(requiredKey)) { const schemaPath = it.schemaEnv.baseId + it.errSchemaPath const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)` checkStrictMode(it, msg, it.opts.strictRequired) } } } function allErrorsMode(): void { if (useLoop || $data) { cxt.block$data(nil, loopAllRequired) } else { for (const prop of schema) { checkReportMissingProp(cxt, prop) } } } function exitOnErrorMode(): void { const missing = gen.let("missing") if (useLoop || $data) { const valid = gen.let("valid", true) cxt.block$data(valid, () => loopUntilMissing(missing, valid)) cxt.ok(valid) } else { gen.if(checkMissingProp(cxt, schema, missing)) reportMissingProp(cxt, missing) gen.else() } } function loopAllRequired(): void { gen.forOf("prop", schemaCode as Code, (prop) => { cxt.setParams({missingProperty: prop}) gen.if(noPropertyInData(gen, data, prop, opts.ownProperties), () => cxt.error()) }) } function loopUntilMissing(missing: Name, valid: Name): void { cxt.setParams({missingProperty: missing}) gen.forOf( missing, schemaCode as Code, () => { gen.assign(valid, propertyInData(gen, data, missing, opts.ownProperties)) gen.if(not(valid), () => { cxt.error() gen.break() }) }, nil ) } }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,306
function loopUntilMissing(missing: Name, valid: Name): void { cxt.setParams({missingProperty: missing}) gen.forOf( missing, schemaCode as Code, () => { gen.assign(valid, propertyInData(gen, data, missing, opts.ownProperties)) gen.if(not(valid), () => { cxt.error() gen.break() }) }, nil ) }
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,307
code(cxt: KeywordCxt) { const {gen, data, $data, schemaCode, schema} = cxt if ($data || (schema && typeof schema == "object")) { cxt.fail$data(_`!${useFunc(gen, equal)}(${data}, ${schemaCode})`) } else { cxt.fail(_`${schema} !== ${data}`) } }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,308
code(cxt: KeywordCxt) { const {keyword, data, schemaCode} = cxt cxt.fail$data(_`${data} ${KWDs[keyword as Kwd].fail} ${schemaCode} || isNaN(${data})`) }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,309
code({keyword, parentSchema, it}: KeywordCxt) { if (parentSchema.contains === undefined) { checkStrictMode(it, `"${keyword}" without "contains" is ignored`) } }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,310
code(cxt: KeywordCxt) { const {data, $data, schema, schemaCode, it} = cxt // TODO regexp should be wrapped in try/catchs const u = it.opts.unicodeRegExp ? "u" : "" const regExp = $data ? _`(new RegExp(${schemaCode}, ${u}))` : usePattern(cxt, schema) cxt.fail$data(_`!${regExp}.test(${data})`) }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,311
code(cxt: KeywordCxt) { const {gen, data, $data, schema, parentSchema, schemaCode, it} = cxt if (!$data && !schema) return const valid = gen.let("valid") const itemTypes = parentSchema.items ? getSchemaTypes(parentSchema.items) : [] cxt.block$data(valid, validateUniqueItems, _`${schemaCode} === false`) cxt.ok(valid) function validateUniqueItems(): void { const i = gen.let("i", _`${data}.length`) const j = gen.let("j") cxt.setParams({i, j}) gen.assign(valid, true) gen.if(_`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j)) } function canOptimize(): boolean { return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array") } function loopN(i: Name, j: Name): void { const item = gen.name("item") const wrongType = checkDataTypes(itemTypes, item, it.opts.strictNumbers, DataType.Wrong) const indices = gen.const("indices", _`{}`) gen.for(_`;${i}--;`, () => { gen.let(item, _`${data}[${i}]`) gen.if(wrongType, _`continue`) if (itemTypes.length > 1) gen.if(_`typeof ${item} == "string"`, _`${item} += "_"`) gen .if(_`typeof ${indices}[${item}] == "number"`, () => { gen.assign(j, _`${indices}[${item}]`) cxt.error() gen.assign(valid, false).break() }) .code(_`${indices}[${item}] = ${i}`) }) } function loopN2(i: Name, j: Name): void { const eql = useFunc(gen, equal) const outer = gen.name("outer") gen.label(outer).for(_`;${i}--;`, () => gen.for(_`${j} = ${i}; ${j}--;`, () => gen.if(_`${eql}(${data}[${i}], ${data}[${j}])`, () => { cxt.error() gen.assign(valid, false).break(outer) }) ) ) } }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,312
function loopN(i: Name, j: Name): void { const item = gen.name("item") const wrongType = checkDataTypes(itemTypes, item, it.opts.strictNumbers, DataType.Wrong) const indices = gen.const("indices", _`{}`) gen.for(_`;${i}--;`, () => { gen.let(item, _`${data}[${i}]`) gen.if(wrongType, _`continue`) if (itemTypes.length > 1) gen.if(_`typeof ${item} == "string"`, _`${item} += "_"`) gen .if(_`typeof ${indices}[${item}] == "number"`, () => { gen.assign(j, _`${indices}[${item}]`) cxt.error() gen.assign(valid, false).break() }) .code(_`${indices}[${item}] = ${i}`) }) }
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,313
function loopN2(i: Name, j: Name): void { const eql = useFunc(gen, equal) const outer = gen.name("outer") gen.label(outer).for(_`;${i}--;`, () => gen.for(_`${j} = ${i}; ${j}--;`, () => gen.if(_`${eql}(${data}[${i}], ${data}[${j}])`, () => { cxt.error() gen.assign(valid, false).break(outer) }) ) ) }
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,314
code(cxt: KeywordCxt) { const {keyword, data, schemaCode, it} = cxt const op = keyword === "maxLength" ? operators.GT : operators.LT const len = it.opts.unicode === false ? _`${data}.length` : _`${useFunc(cxt.gen, ucs2length)}(${data})` cxt.fail$data(_`${len} ${op} ${schemaCode}`) }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,315
code(cxt: KeywordCxt): void { const {gen, schema: $ref, it} = cxt const {baseId, schemaEnv: env, validateName, opts, self} = it const {root} = env if (($ref === "#" || $ref === "#/") && baseId === root.baseId) return callRootRef() const schOrEnv = resolveRef.call(self, root, baseId, $ref) if (schOrEnv === undefined) throw new MissingRefError(it.opts.uriResolver, baseId, $ref) if (schOrEnv instanceof SchemaEnv) return callValidate(schOrEnv) return inlineRefSchema(schOrEnv) function callRootRef(): void { if (env === root) return callRef(cxt, validateName, env, env.$async) const rootName = gen.scopeValue("root", {ref: root}) return callRef(cxt, _`${rootName}.validate`, root, root.$async) } function callValidate(sch: SchemaEnv): void { const v = getValidate(cxt, sch) callRef(cxt, v, sch, sch.$async) } function inlineRefSchema(sch: AnySchema): void { const schName = gen.scopeValue( "schema", opts.code.source === true ? {ref: sch, code: stringify(sch)} : {ref: sch} ) const valid = gen.name("valid") const schCxt = cxt.subschema( { schema: sch, dataTypes: [], schemaPath: nil, topSchemaRef: schName, errSchemaPath: $ref, }, valid ) cxt.mergeEvaluated(schCxt) cxt.ok(valid) } }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,316
function callValidate(sch: SchemaEnv): void { const v = getValidate(cxt, sch) callRef(cxt, v, sch, sch.$async) }
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,317
function inlineRefSchema(sch: AnySchema): void { const schName = gen.scopeValue( "schema", opts.code.source === true ? {ref: sch, code: stringify(sch)} : {ref: sch} ) const valid = gen.name("valid") const schCxt = cxt.subschema( { schema: sch, dataTypes: [], schemaPath: nil, topSchemaRef: schName, errSchemaPath: $ref, }, valid ) cxt.mergeEvaluated(schCxt) cxt.ok(valid) }
type AnySchema = Schema | AsyncSchema
2,318
function getValidate(cxt: KeywordCxt, sch: SchemaEnv): Code { const {gen} = cxt return sch.validate ? gen.scopeValue("validate", {ref: sch.validate}) : _`${gen.scopeValue("wrapper", {ref: sch})}.validate` }
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,319
function getValidate(cxt: KeywordCxt, sch: SchemaEnv): Code { const {gen} = cxt return sch.validate ? gen.scopeValue("validate", {ref: sch.validate}) : _`${gen.scopeValue("wrapper", {ref: sch})}.validate` }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,320
function callRef(cxt: KeywordCxt, v: Code, sch?: SchemaEnv, $async?: boolean): void { const {gen, it} = cxt const {allErrors, schemaEnv: env, opts} = it const passCxt = opts.passContext ? N.this : nil if ($async) callAsyncRef() else callSyncRef() function callAsyncRef(): void { if (!env.$async) throw new Error("async schema referenced by sync schema") const valid = gen.let("valid") gen.try( () => { gen.code(_`await ${callValidateCode(cxt, v, passCxt)}`) addEvaluatedFrom(v) // TODO will not work with async, it has to be returned with the result if (!allErrors) gen.assign(valid, true) }, (e) => { gen.if(_`!(${e} instanceof ${it.ValidationError as Name})`, () => gen.throw(e)) addErrorsFrom(e) if (!allErrors) gen.assign(valid, false) } ) cxt.ok(valid) } function callSyncRef(): void { cxt.result( callValidateCode(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v) ) } function addErrorsFrom(source: Code): void { const errs = _`${source}.errors` gen.assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`) // TODO tagged gen.assign(N.errors, _`${N.vErrors}.length`) } function addEvaluatedFrom(source: Code): void { if (!it.opts.unevaluated) return const schEvaluated = sch?.validate?.evaluated // TODO refactor if (it.props !== true) { if (schEvaluated && !schEvaluated.dynamicProps) { if (schEvaluated.props !== undefined) { it.props = mergeEvaluated.props(gen, schEvaluated.props, it.props) } } else { const props = gen.var("props", _`${source}.evaluated.props`) it.props = mergeEvaluated.props(gen, props, it.props, Name) } } if (it.items !== true) { if (schEvaluated && !schEvaluated.dynamicItems) { if (schEvaluated.items !== undefined) { it.items = mergeEvaluated.items(gen, schEvaluated.items, it.items) } } else { const items = gen.var("items", _`${source}.evaluated.items`) it.items = mergeEvaluated.items(gen, items, it.items, Name) } } } }
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,321
function callRef(cxt: KeywordCxt, v: Code, sch?: SchemaEnv, $async?: boolean): void { const {gen, it} = cxt const {allErrors, schemaEnv: env, opts} = it const passCxt = opts.passContext ? N.this : nil if ($async) callAsyncRef() else callSyncRef() function callAsyncRef(): void { if (!env.$async) throw new Error("async schema referenced by sync schema") const valid = gen.let("valid") gen.try( () => { gen.code(_`await ${callValidateCode(cxt, v, passCxt)}`) addEvaluatedFrom(v) // TODO will not work with async, it has to be returned with the result if (!allErrors) gen.assign(valid, true) }, (e) => { gen.if(_`!(${e} instanceof ${it.ValidationError as Name})`, () => gen.throw(e)) addErrorsFrom(e) if (!allErrors) gen.assign(valid, false) } ) cxt.ok(valid) } function callSyncRef(): void { cxt.result( callValidateCode(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v) ) } function addErrorsFrom(source: Code): void { const errs = _`${source}.errors` gen.assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`) // TODO tagged gen.assign(N.errors, _`${N.vErrors}.length`) } function addEvaluatedFrom(source: Code): void { if (!it.opts.unevaluated) return const schEvaluated = sch?.validate?.evaluated // TODO refactor if (it.props !== true) { if (schEvaluated && !schEvaluated.dynamicProps) { if (schEvaluated.props !== undefined) { it.props = mergeEvaluated.props(gen, schEvaluated.props, it.props) } } else { const props = gen.var("props", _`${source}.evaluated.props`) it.props = mergeEvaluated.props(gen, props, it.props, Name) } } if (it.items !== true) { if (schEvaluated && !schEvaluated.dynamicItems) { if (schEvaluated.items !== undefined) { it.items = mergeEvaluated.items(gen, schEvaluated.items, it.items) } } else { const items = gen.var("items", _`${source}.evaluated.items`) it.items = mergeEvaluated.items(gen, items, it.items, Name) } } } }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,322
function callRef(cxt: KeywordCxt, v: Code, sch?: SchemaEnv, $async?: boolean): void { const {gen, it} = cxt const {allErrors, schemaEnv: env, opts} = it const passCxt = opts.passContext ? N.this : nil if ($async) callAsyncRef() else callSyncRef() function callAsyncRef(): void { if (!env.$async) throw new Error("async schema referenced by sync schema") const valid = gen.let("valid") gen.try( () => { gen.code(_`await ${callValidateCode(cxt, v, passCxt)}`) addEvaluatedFrom(v) // TODO will not work with async, it has to be returned with the result if (!allErrors) gen.assign(valid, true) }, (e) => { gen.if(_`!(${e} instanceof ${it.ValidationError as Name})`, () => gen.throw(e)) addErrorsFrom(e) if (!allErrors) gen.assign(valid, false) } ) cxt.ok(valid) } function callSyncRef(): void { cxt.result( callValidateCode(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v) ) } function addErrorsFrom(source: Code): void { const errs = _`${source}.errors` gen.assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`) // TODO tagged gen.assign(N.errors, _`${N.vErrors}.length`) } function addEvaluatedFrom(source: Code): void { if (!it.opts.unevaluated) return const schEvaluated = sch?.validate?.evaluated // TODO refactor if (it.props !== true) { if (schEvaluated && !schEvaluated.dynamicProps) { if (schEvaluated.props !== undefined) { it.props = mergeEvaluated.props(gen, schEvaluated.props, it.props) } } else { const props = gen.var("props", _`${source}.evaluated.props`) it.props = mergeEvaluated.props(gen, props, it.props, Name) } } if (it.items !== true) { if (schEvaluated && !schEvaluated.dynamicItems) { if (schEvaluated.items !== undefined) { it.items = mergeEvaluated.items(gen, schEvaluated.items, it.items) } } else { const items = gen.var("items", _`${source}.evaluated.items`) it.items = mergeEvaluated.items(gen, items, it.items, Name) } } } }
type Code = _Code | Name
2,323
function addErrorsFrom(source: Code): void { const errs = _`${source}.errors` gen.assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`) // TODO tagged gen.assign(N.errors, _`${N.vErrors}.length`) }
type Code = _Code | Name
2,324
function addEvaluatedFrom(source: Code): void { if (!it.opts.unevaluated) return const schEvaluated = sch?.validate?.evaluated // TODO refactor if (it.props !== true) { if (schEvaluated && !schEvaluated.dynamicProps) { if (schEvaluated.props !== undefined) { it.props = mergeEvaluated.props(gen, schEvaluated.props, it.props) } } else { const props = gen.var("props", _`${source}.evaluated.props`) it.props = mergeEvaluated.props(gen, props, it.props, Name) } } if (it.items !== true) { if (schEvaluated && !schEvaluated.dynamicItems) { if (schEvaluated.items !== undefined) { it.items = mergeEvaluated.items(gen, schEvaluated.items, it.items) } } else { const items = gen.var("items", _`${source}.evaluated.items`) it.items = mergeEvaluated.items(gen, items, it.items, Name) } } }
type Code = _Code | Name
2,325
code(cxt: KeywordCxt) { const {gen, data, schema, parentSchema, it} = cxt const {oneOf} = parentSchema if (!it.opts.discriminator) { throw new Error("discriminator: requires discriminator option") } const tagName = schema.propertyName if (typeof tagName != "string") throw new Error("discriminator: requires propertyName") if (schema.mapping) throw new Error("discriminator: mapping is not supported") if (!oneOf) throw new Error("discriminator: requires oneOf keyword") const valid = gen.let("valid", false) const tag = gen.const("tag", _`${data}${getProperty(tagName)}`) gen.if( _`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, {discrError: DiscrError.Tag, tag, tagName}) ) cxt.ok(valid) function validateMapping(): void { const mapping = getMapping() gen.if(false) for (const tagValue in mapping) { gen.elseIf(_`${tag} === ${tagValue}`) gen.assign(valid, applyTagSchema(mapping[tagValue])) } gen.else() cxt.error(false, {discrError: DiscrError.Mapping, tag, tagName}) gen.endIf() } function applyTagSchema(schemaProp?: number): Name { const _valid = gen.name("valid") const schCxt = cxt.subschema({keyword: "oneOf", schemaProp}, _valid) cxt.mergeEvaluated(schCxt, Name) return _valid } function getMapping(): {[T in string]?: number} { const oneOfMapping: {[T in string]?: number} = {} const topRequired = hasRequired(parentSchema) let tagRequired = true for (let i = 0; i < oneOf.length; i++) { let sch = oneOf[i] if (sch?.$ref && !schemaHasRulesButRef(sch, it.self.RULES)) { sch = resolveRef.call(it.self, it.schemaEnv.root, it.baseId, sch?.$ref) if (sch instanceof SchemaEnv) sch = sch.schema } const propSch = sch?.properties?.[tagName] if (typeof propSch != "object") { throw new Error( `discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"` ) } tagRequired = tagRequired && (topRequired || hasRequired(sch)) addMappings(propSch, i) } if (!tagRequired) throw new Error(`discriminator: "${tagName}" must be required`) return oneOfMapping function hasRequired({required}: AnySchemaObject): boolean { return Array.isArray(required) && required.includes(tagName) } function addMappings(sch: AnySchemaObject, i: number): void { if (sch.const) { addMapping(sch.const, i) } else if (sch.enum) { for (const tagValue of sch.enum) { addMapping(tagValue, i) } } else { throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`) } } function addMapping(tagValue: unknown, i: number): void { if (typeof tagValue != "string" || tagValue in oneOfMapping) { throw new Error(`discriminator: "${tagName}" values must be unique strings`) } oneOfMapping[tagValue] = i } } }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,326
function hasRequired({required}: AnySchemaObject): boolean { return Array.isArray(required) && required.includes(tagName) }
type AnySchemaObject = SchemaObject | AsyncSchema
2,327
function addMappings(sch: AnySchemaObject, i: number): void { if (sch.const) { addMapping(sch.const, i) } else if (sch.enum) { for (const tagValue of sch.enum) { addMapping(tagValue, i) } } else { throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`) } }
type AnySchemaObject = SchemaObject | AsyncSchema
2,328
function dynamicRef(cxt: KeywordCxt, ref: string): void { const {gen, keyword, it} = cxt if (ref[0] !== "#") throw new Error(`"${keyword}" only supports hash fragment reference`) const anchor = ref.slice(1) if (it.allErrors) { _dynamicRef() } else { const valid = gen.let("valid", false) _dynamicRef(valid) cxt.ok(valid) } function _dynamicRef(valid?: Name): void { // TODO the assumption here is that `recursiveRef: #` always points to the root // of the schema object, which is not correct, because there may be $id that // makes # point to it, and the target schema may not contain dynamic/recursiveAnchor. // Because of that 2 tests in recursiveRef.json fail. // This is a similar problem to #815 (`$id` doesn't alter resolution scope for `{ "$ref": "#" }`). // (This problem is not tested in JSON-Schema-Test-Suite) if (it.schemaEnv.root.dynamicAnchors[anchor]) { const v = gen.let("_v", _`${N.dynamicAnchors}${getProperty(anchor)}`) gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid)) } else { _callRef(it.validateName, valid)() } } function _callRef(validate: Code, valid?: Name): () => void { return valid ? () => gen.block(() => { callRef(cxt, validate) gen.let(valid, true) }) : () => callRef(cxt, validate) } }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,329
function _dynamicRef(valid?: Name): void { // TODO the assumption here is that `recursiveRef: #` always points to the root // of the schema object, which is not correct, because there may be $id that // makes # point to it, and the target schema may not contain dynamic/recursiveAnchor. // Because of that 2 tests in recursiveRef.json fail. // This is a similar problem to #815 (`$id` doesn't alter resolution scope for `{ "$ref": "#" }`). // (This problem is not tested in JSON-Schema-Test-Suite) if (it.schemaEnv.root.dynamicAnchors[anchor]) { const v = gen.let("_v", _`${N.dynamicAnchors}${getProperty(anchor)}`) gen.if(v, _callRef(v, valid), _callRef(it.validateName, valid)) } else { _callRef(it.validateName, valid)() } }
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,330
function _callRef(validate: Code, valid?: Name): () => void { return valid ? () => gen.block(() => { callRef(cxt, validate) gen.let(valid, true) }) : () => callRef(cxt, validate) }
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,331
function _callRef(validate: Code, valid?: Name): () => void { return valid ? () => gen.block(() => { callRef(cxt, validate) gen.let(valid, true) }) : () => callRef(cxt, validate) }
type Code = _Code | Name
2,332
function dynamicAnchor(cxt: KeywordCxt, anchor: string): void { const {gen, it} = cxt it.schemaEnv.root.dynamicAnchors[anchor] = true const v = _`${N.dynamicAnchors}${getProperty(anchor)}` const validate = it.errSchemaPath === "#" ? it.validateName : _getValidate(cxt) gen.if(_`!${v}`, () => gen.assign(v, validate)) }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,333
function _getValidate(cxt: KeywordCxt): Code { const {schemaEnv, schema, self} = cxt.it const {root, baseId, localRefs, meta} = schemaEnv.root const {schemaId} = self.opts const sch = new SchemaEnv({schema, schemaId, root, baseId, localRefs, meta}) compileSchema.call(self, sch) return getValidate(cxt, sch) }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,334
code(cxt: KeywordCxt) { const {gen, schema, it} = cxt if (alwaysValidSchema(it, schema)) { cxt.fail() return } const valid = gen.name("valid") cxt.subschema( { keyword: "not", compositeRule: true, createErrors: false, allErrors: false, }, valid ) cxt.failResult( valid, () => cxt.reset(), () => cxt.error() ) }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,335
code(cxt: KeywordCxt) { const {schema, it} = cxt if (Array.isArray(schema)) return validateTuple(cxt, "additionalItems", schema) it.items = true if (alwaysValidSchema(it, schema)) return cxt.ok(validateArray(cxt)) }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,336
function validateTuple( cxt: KeywordCxt, extraItems: string, schArr: AnySchema[] = cxt.schema ): void { const {gen, parentSchema, data, keyword, it} = cxt checkStrictTuple(parentSchema) if (it.opts.unevaluated && schArr.length && it.items !== true) { it.items = mergeEvaluated.items(gen, schArr.length, it.items) } const valid = gen.name("valid") const len = gen.const("len", _`${data}.length`) schArr.forEach((sch: AnySchema, i: number) => { if (alwaysValidSchema(it, sch)) return gen.if(_`${len} > ${i}`, () => cxt.subschema( { keyword, schemaProp: i, dataProp: i, }, valid ) ) cxt.ok(valid) }) function checkStrictTuple(sch: AnySchemaObject): void { const {opts, errSchemaPath} = it const l = schArr.length const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false) if (opts.strictTuples && !fullTuple) { const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"` checkStrictMode(it, msg, opts.strictTuples) } } }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,337
(sch: AnySchema, i: number) => { if (alwaysValidSchema(it, sch)) return gen.if(_`${len} > ${i}`, () => cxt.subschema( { keyword, schemaProp: i, dataProp: i, }, valid ) ) cxt.ok(valid) }
type AnySchema = Schema | AsyncSchema
2,338
function checkStrictTuple(sch: AnySchemaObject): void { const {opts, errSchemaPath} = it const l = schArr.length const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false) if (opts.strictTuples && !fullTuple) { const msg = `"${keyword}" is ${l}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"` checkStrictMode(it, msg, opts.strictTuples) } }
type AnySchemaObject = SchemaObject | AsyncSchema
2,339
code(cxt: KeywordCxt) { const [propDeps, schDeps] = splitDependencies(cxt) validatePropertyDeps(cxt, propDeps) validateSchemaDeps(cxt, schDeps) }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,340
function splitDependencies({schema}: KeywordCxt): [PropertyDependencies, SchemaDependencies] { const propertyDeps: PropertyDependencies = {} const schemaDeps: SchemaDependencies = {} for (const key in schema) { if (key === "__proto__") continue const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps deps[key] = schema[key] } return [propertyDeps, schemaDeps] }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,341
function validatePropertyDeps( cxt: KeywordCxt, propertyDeps: {[K in string]?: string[]} = cxt.schema ): void { const {gen, data, it} = cxt if (Object.keys(propertyDeps).length === 0) return const missing = gen.let("missing") for (const prop in propertyDeps) { const deps = propertyDeps[prop] as string[] if (deps.length === 0) continue const hasProperty = propertyInData(gen, data, prop, it.opts.ownProperties) cxt.setParams({ property: prop, depsCount: deps.length, deps: deps.join(", "), }) if (it.allErrors) { gen.if(hasProperty, () => { for (const depProp of deps) { checkReportMissingProp(cxt, depProp) } }) } else { gen.if(_`${hasProperty} && (${checkMissingProp(cxt, deps, missing)})`) reportMissingProp(cxt, missing) gen.else() } } }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,342
function validateSchemaDeps(cxt: KeywordCxt, schemaDeps: SchemaMap = cxt.schema): void { const {gen, data, keyword, it} = cxt const valid = gen.name("valid") for (const prop in schemaDeps) { if (alwaysValidSchema(it, schemaDeps[prop] as AnySchema)) continue gen.if( propertyInData(gen, data, prop, it.opts.ownProperties), () => { const schCxt = cxt.subschema({keyword, schemaProp: prop}, valid) cxt.mergeValidEvaluated(schCxt, valid) }, () => gen.var(valid, true) // TODO var ) cxt.ok(valid) } }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,343
function validateSchemaDeps(cxt: KeywordCxt, schemaDeps: SchemaMap = cxt.schema): void { const {gen, data, keyword, it} = cxt const valid = gen.name("valid") for (const prop in schemaDeps) { if (alwaysValidSchema(it, schemaDeps[prop] as AnySchema)) continue gen.if( propertyInData(gen, data, prop, it.opts.ownProperties), () => { const schCxt = cxt.subschema({keyword, schemaProp: prop}, valid) cxt.mergeValidEvaluated(schCxt, valid) }, () => gen.var(valid, true) // TODO var ) cxt.ok(valid) } }
type SchemaMap = {[Key in string]?: AnySchema}
2,344
code(cxt: KeywordCxt) { const {gen, schema, data, parentSchema, it} = cxt const {opts} = it const patterns = allSchemaProperties(schema) const alwaysValidPatterns = patterns.filter((p) => alwaysValidSchema(it, schema[p] as AnySchema) ) if ( patterns.length === 0 || (alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) ) { return } const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties const valid = gen.name("valid") if (it.props !== true && !(it.props instanceof Name)) { it.props = evaluatedPropsToName(gen, it.props) } const {props} = it validatePatternProperties() function validatePatternProperties(): void { for (const pat of patterns) { if (checkProperties) checkMatchingProperties(pat) if (it.allErrors) { validateProperties(pat) } else { gen.var(valid, true) // TODO var validateProperties(pat) gen.if(valid) } } } function checkMatchingProperties(pat: string): void { for (const prop in checkProperties) { if (new RegExp(pat).test(prop)) { checkStrictMode( it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)` ) } } } function validateProperties(pat: string): void { gen.forIn("key", data, (key) => { gen.if(_`${usePattern(cxt, pat)}.test(${key})`, () => { const alwaysValid = alwaysValidPatterns.includes(pat) if (!alwaysValid) { cxt.subschema( { keyword: "patternProperties", schemaProp: pat, dataProp: key, dataPropType: Type.Str, }, valid ) } if (it.opts.unevaluated && props !== true) { gen.assign(_`${props}[${key}]`, true) } else if (!alwaysValid && !it.allErrors) { // can short-circuit if `unevaluatedProperties` is not supported (opts.next === false) // or if all properties were evaluated (props === true) gen.if(not(valid), () => gen.break()) } }) }) } }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,345
code(cxt: KeywordCxt) { const {parentSchema, it} = cxt const {items} = parentSchema if (!Array.isArray(items)) { checkStrictMode(it, '"additionalItems" is ignored when "items" is not an array of schemas') return } validateAdditionalItems(cxt, items) }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,346
function validateAdditionalItems(cxt: KeywordCxt, items: AnySchema[]): void { const {gen, schema, data, keyword, it} = cxt it.items = true const len = gen.const("len", _`${data}.length`) if (schema === false) { cxt.setParams({len: items.length}) cxt.pass(_`${len} <= ${items.length}`) } else if (typeof schema == "object" && !alwaysValidSchema(it, schema)) { const valid = gen.var("valid", _`${len} <= ${items.length}`) // TODO var gen.if(not(valid), () => validateItems(valid)) cxt.ok(valid) } function validateItems(valid: Name): void { gen.forRange("i", items.length, len, (i) => { cxt.subschema({keyword, dataProp: i, dataPropType: Type.Num}, valid) if (!it.allErrors) gen.if(not(valid), () => gen.break()) }) } }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,347
function validateItems(valid: Name): void { gen.forRange("i", items.length, len, (i) => { cxt.subschema({keyword, dataProp: i, dataPropType: Type.Num}, valid) if (!it.allErrors) gen.if(not(valid), () => gen.break()) }) }
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,348
code({keyword, parentSchema, it}: KeywordCxt) { if (parentSchema.if === undefined) checkStrictMode(it, `"${keyword}" without "if" is ignored`) }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,349
(key: Name) => { if (!props.length && !patProps.length) additionalPropertyCode(key) else gen.if(isAdditional(key), () => additionalPropertyCode(key)) }
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,350
function isAdditional(key: Name): Code { let definedProp: Code if (props.length > 8) { // TODO maybe an option instead of hard-coded 8? const propsSchema = schemaRefOrVal(it, parentSchema.properties, "properties") definedProp = isOwnProperty(gen, propsSchema as Code, key) } else if (props.length) { definedProp = or(...props.map((p) => _`${key} === ${p}`)) } else { definedProp = nil } if (patProps.length) { definedProp = or(definedProp, ...patProps.map((p) => _`${usePattern(cxt, p)}.test(${key})`)) } return not(definedProp) }
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,351
function deleteAdditional(key: Name): void { gen.code(_`delete ${data}[${key}]`) }
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,352
function additionalPropertyCode(key: Name): void { if (opts.removeAdditional === "all" || (opts.removeAdditional && schema === false)) { deleteAdditional(key) return } if (schema === false) { cxt.setParams({additionalProperty: key}) cxt.error() if (!allErrors) gen.break() return } if (typeof schema == "object" && !alwaysValidSchema(it, schema)) { const valid = gen.name("valid") if (opts.removeAdditional === "failing") { applyAdditionalSchema(key, valid, false) gen.if(not(valid), () => { cxt.reset() deleteAdditional(key) }) } else { applyAdditionalSchema(key, valid) if (!allErrors) gen.if(not(valid), () => gen.break()) } } }
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,353
function applyAdditionalSchema(key: Name, valid: Name, errors?: false): void { const subschema: SubschemaArgs = { keyword: "additionalProperties", dataProp: key, dataPropType: Type.Str, } if (errors === false) { Object.assign(subschema, { compositeRule: true, createErrors: false, allErrors: false, }) } cxt.subschema(subschema, valid) }
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,354
code(cxt: KeywordCxt) { const {gen, schema, data, it} = cxt if (alwaysValidSchema(it, schema)) return const valid = gen.name("valid") gen.forIn("key", data, (key) => { cxt.setParams({propertyName: key}) cxt.subschema( { keyword: "propertyNames", data: key, dataTypes: ["string"], propertyName: key, compositeRule: true, }, valid ) gen.if(not(valid), () => { cxt.error(true) if (!it.allErrors) gen.break() }) }) cxt.ok(valid) }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,355
code(cxt: KeywordCxt) { const {schema, parentSchema, it} = cxt const {prefixItems} = parentSchema it.items = true if (alwaysValidSchema(it, schema)) return if (prefixItems) validateAdditionalItems(cxt, prefixItems) else cxt.ok(validateArray(cxt)) }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,356
code(cxt: KeywordCxt) { const {gen, schema, parentSchema, it} = cxt /* istanbul ignore if */ if (!Array.isArray(schema)) throw new Error("ajv implementation error") if (it.opts.discriminator && parentSchema.discriminator) return const schArr: AnySchema[] = schema const valid = gen.let("valid", false) const passing = gen.let("passing", null) const schValid = gen.name("_valid") cxt.setParams({passing}) // TODO possibly fail straight away (with warning or exception) if there are two empty always valid schemas gen.block(validateOneOf) cxt.result( valid, () => cxt.reset(), () => cxt.error(true) ) function validateOneOf(): void { schArr.forEach((sch: AnySchema, i: number) => { let schCxt: SchemaCxt | undefined if (alwaysValidSchema(it, sch)) { gen.var(schValid, true) } else { schCxt = cxt.subschema( { keyword: "oneOf", schemaProp: i, compositeRule: true, }, schValid ) } if (i > 0) { gen .if(_`${schValid} && ${valid}`) .assign(valid, false) .assign(passing, _`[${passing}, ${i}]`) .else() } gen.if(schValid, () => { gen.assign(valid, true) gen.assign(passing, i) if (schCxt) cxt.mergeEvaluated(schCxt, Name) }) }) } }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,357
(sch: AnySchema, i: number) => { let schCxt: SchemaCxt | undefined if (alwaysValidSchema(it, sch)) { gen.var(schValid, true) } else { schCxt = cxt.subschema( { keyword: "oneOf", schemaProp: i, compositeRule: true, }, schValid ) } if (i > 0) { gen .if(_`${schValid} && ${valid}`) .assign(valid, false) .assign(passing, _`[${passing}, ${i}]`) .else() } gen.if(schValid, () => { gen.assign(valid, true) gen.assign(passing, i) if (schCxt) cxt.mergeEvaluated(schCxt, Name) }) }
type AnySchema = Schema | AsyncSchema
2,358
code(cxt: KeywordCxt) { const {gen, parentSchema, it} = cxt if (parentSchema.then === undefined && parentSchema.else === undefined) { checkStrictMode(it, '"if" without "then" and "else" is ignored') } const hasThen = hasSchema(it, "then") const hasElse = hasSchema(it, "else") if (!hasThen && !hasElse) return const valid = gen.let("valid", true) const schValid = gen.name("_valid") validateIf() cxt.reset() if (hasThen && hasElse) { const ifClause = gen.let("ifClause") cxt.setParams({ifClause}) gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause)) } else if (hasThen) { gen.if(schValid, validateClause("then")) } else { gen.if(not(schValid), validateClause("else")) } cxt.pass(valid, () => cxt.error(true)) function validateIf(): void { const schCxt = cxt.subschema( { keyword: "if", compositeRule: true, createErrors: false, allErrors: false, }, schValid ) cxt.mergeEvaluated(schCxt) } function validateClause(keyword: string, ifClause?: Name): () => void { return () => { const schCxt = cxt.subschema({keyword}, schValid) gen.assign(valid, schValid) cxt.mergeValidEvaluated(schCxt, valid) if (ifClause) gen.assign(ifClause, _`${keyword}`) else cxt.setParams({ifClause: keyword}) } } }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,359
function hasSchema(it: SchemaObjCxt, keyword: string): boolean { const schema = it.schema[keyword] return schema !== undefined && !alwaysValidSchema(it, schema) }
interface SchemaObjCxt extends SchemaCxt { readonly schema: AnySchemaObject }
2,360
code(cxt: KeywordCxt) { const {gen, schema, it} = cxt /* istanbul ignore if */ if (!Array.isArray(schema)) throw new Error("ajv implementation error") const valid = gen.name("valid") schema.forEach((sch: AnySchema, i: number) => { if (alwaysValidSchema(it, sch)) return const schCxt = cxt.subschema({keyword: "allOf", schemaProp: i}, valid) cxt.ok(valid) cxt.mergeEvaluated(schCxt) }) }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,361
(sch: AnySchema, i: number) => { if (alwaysValidSchema(it, sch)) return const schCxt = cxt.subschema({keyword: "allOf", schemaProp: i}, valid) cxt.ok(valid) cxt.mergeEvaluated(schCxt) }
type AnySchema = Schema | AsyncSchema
2,362
code(cxt: KeywordCxt) { const {gen, schema, parentSchema, data, it} = cxt if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === undefined) { apDef.code(new KeywordCxt(it, apDef, "additionalProperties")) } const allProps = allSchemaProperties(schema) for (const prop of allProps) { it.definedProperties.add(prop) } if (it.opts.unevaluated && allProps.length && it.props !== true) { it.props = mergeEvaluated.props(gen, toHash(allProps), it.props) } const properties = allProps.filter((p) => !alwaysValidSchema(it, schema[p])) if (properties.length === 0) return const valid = gen.name("valid") for (const prop of properties) { if (hasDefault(prop)) { applyPropertySchema(prop) } else { gen.if(propertyInData(gen, data, prop, it.opts.ownProperties)) applyPropertySchema(prop) if (!it.allErrors) gen.else().var(valid, true) gen.endIf() } cxt.it.definedProperties.add(prop) cxt.ok(valid) } function hasDefault(prop: string): boolean | undefined { return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== undefined } function applyPropertySchema(prop: string): void { cxt.subschema( { keyword: "properties", schemaProp: prop, dataProp: prop, }, valid ) } }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,363
code(cxt: KeywordCxt) { const {gen, schema, parentSchema, data, it} = cxt let min: number let max: number | undefined const {minContains, maxContains} = parentSchema if (it.opts.next) { min = minContains === undefined ? 1 : minContains max = maxContains } else { min = 1 } const len = gen.const("len", _`${data}.length`) cxt.setParams({min, max}) if (max === undefined && min === 0) { checkStrictMode(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`) return } if (max !== undefined && min > max) { checkStrictMode(it, `"minContains" > "maxContains" is always invalid`) cxt.fail() return } if (alwaysValidSchema(it, schema)) { let cond = _`${len} >= ${min}` if (max !== undefined) cond = _`${cond} && ${len} <= ${max}` cxt.pass(cond) return } it.items = true const valid = gen.name("valid") if (max === undefined && min === 1) { validateItems(valid, () => gen.if(valid, () => gen.break())) } else if (min === 0) { gen.let(valid, true) if (max !== undefined) gen.if(_`${data}.length > 0`, validateItemsWithCount) } else { gen.let(valid, false) validateItemsWithCount() } cxt.result(valid, () => cxt.reset()) function validateItemsWithCount(): void { const schValid = gen.name("_valid") const count = gen.let("count", 0) validateItems(schValid, () => gen.if(schValid, () => checkLimits(count))) } function validateItems(_valid: Name, block: () => void): void { gen.forRange("i", 0, len, (i) => { cxt.subschema( { keyword: "contains", dataProp: i, dataPropType: Type.Num, compositeRule: true, }, _valid ) block() }) } function checkLimits(count: Name): void { gen.code(_`${count}++`) if (max === undefined) { gen.if(_`${count} >= ${min}`, () => gen.assign(valid, true).break()) } else { gen.if(_`${count} > ${max}`, () => gen.assign(valid, false).break()) if (min === 1) gen.assign(valid, true) else gen.if(_`${count} >= ${min}`, () => gen.assign(valid, true)) } } }
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,364
function validateItems(_valid: Name, block: () => void): void { gen.forRange("i", 0, len, (i) => { cxt.subschema( { keyword: "contains", dataProp: i, dataPropType: Type.Num, compositeRule: true, }, _valid ) block() }) }
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,365
function checkLimits(count: Name): void { gen.code(_`${count}++`) if (max === undefined) { gen.if(_`${count} >= ${min}`, () => gen.assign(valid, true).break()) } else { gen.if(_`${count} > ${max}`, () => gen.assign(valid, false).break()) if (min === 1) gen.assign(valid, true) else gen.if(_`${count} >= ${min}`, () => gen.assign(valid, 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,366
function addMetaSchema2019(this: Ajv, $data?: boolean): Ajv { ;[ metaSchema, applicator, content, core, with$data(this, format), metadata, with$data(this, validation), ].forEach((sch) => this.addMetaSchema(sch, undefined, false)) return this function with$data(ajv: Ajv, sch: AnySchemaObject): AnySchemaObject { return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : 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,367
function addMetaSchema2019(this: Ajv, $data?: boolean): Ajv { ;[ metaSchema, applicator, content, core, with$data(this, format), metadata, with$data(this, validation), ].forEach((sch) => this.addMetaSchema(sch, undefined, false)) return this function with$data(ajv: Ajv, sch: AnySchemaObject): AnySchemaObject { return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : 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,368
function addMetaSchema2019(this: Ajv, $data?: boolean): Ajv { ;[ metaSchema, applicator, content, core, with$data(this, format), metadata, with$data(this, validation), ].forEach((sch) => this.addMetaSchema(sch, undefined, false)) return this function with$data(ajv: Ajv, sch: AnySchemaObject): AnySchemaObject { return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : 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,369
function with$data(ajv: Ajv, sch: AnySchemaObject): AnySchemaObject { return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : sch }
type AnySchemaObject = SchemaObject | AsyncSchema
2,370
function with$data(ajv: Ajv, sch: AnySchemaObject): AnySchemaObject { return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : 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,371
function with$data(ajv: Ajv, sch: AnySchemaObject): AnySchemaObject { return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : 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,372
function with$data(ajv: Ajv, sch: AnySchemaObject): AnySchemaObject { return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : 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,373
function addMetaSchema2020(this: Ajv, $data?: boolean): Ajv { ;[ metaSchema, applicator, unevaluated, content, core, with$data(this, format), metadata, with$data(this, validation), ].forEach((sch) => this.addMetaSchema(sch, undefined, false)) return this function with$data(ajv: Ajv, sch: AnySchemaObject): AnySchemaObject { return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : 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,374
function addMetaSchema2020(this: Ajv, $data?: boolean): Ajv { ;[ metaSchema, applicator, unevaluated, content, core, with$data(this, format), metadata, with$data(this, validation), ].forEach((sch) => this.addMetaSchema(sch, undefined, false)) return this function with$data(ajv: Ajv, sch: AnySchemaObject): AnySchemaObject { return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : 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,375
function addMetaSchema2020(this: Ajv, $data?: boolean): Ajv { ;[ metaSchema, applicator, unevaluated, content, core, with$data(this, format), metadata, with$data(this, validation), ].forEach((sch) => this.addMetaSchema(sch, undefined, false)) return this function with$data(ajv: Ajv, sch: AnySchemaObject): AnySchemaObject { return $data ? ajv.$dataMetaSchema(sch, META_SUPPORT_DATA) : 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,376
(cxt: KeywordCxt, ruleType?: string) => void
class KeywordCxt implements KeywordErrorCxt { readonly gen: CodeGen readonly allErrors?: boolean readonly keyword: string readonly data: Name // Name referencing the current level of the data instance readonly $data?: string | false schema: any // keyword value in the schema readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data) readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema readonly parentSchema: AnySchemaObject readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword, // requires option trackErrors in keyword definition params: KeywordCxtParams // object to pass parameters to error messages from keyword code readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean) readonly def: AddedKeywordDefinition constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) { validateKeywordUsage(it, def, keyword) this.gen = it.gen this.allErrors = it.allErrors this.keyword = keyword this.data = it.data this.schema = it.schema[keyword] this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data) this.schemaType = def.schemaType this.parentSchema = it.schema this.params = {} this.it = it this.def = def if (this.$data) { this.schemaCode = it.gen.const("vSchema", getData(this.$data, it)) } else { this.schemaCode = this.schemaValue if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) { throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`) } } if ("code" in def ? def.trackErrors : def.errors !== false) { this.errsCount = it.gen.const("_errs", N.errors) } } result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) } failResult(condition: Code, successAction?: () => void, failAction?: () => void): void { this.gen.if(condition) if (failAction) failAction() else this.error() if (successAction) { this.gen.else() successAction() if (this.allErrors) this.gen.endIf() } else { if (this.allErrors) this.gen.endIf() else this.gen.else() } } pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) } fail(condition?: Code): void { if (condition === undefined) { this.error() if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize return } this.gen.if(condition) this.error() if (this.allErrors) this.gen.endIf() else this.gen.else() } fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) } error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void { if (errorParams) { this.setParams(errorParams) this._error(append, errorPaths) this.setParams({}) return } this._error(append, errorPaths) } private _error(append?: boolean, errorPaths?: ErrorPaths): void { ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths) } $dataError(): void { reportError(this, this.def.$dataError || keyword$DataError) } reset(): void { if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition') resetErrorsCount(this.gen, this.errsCount) } ok(cond: Code | boolean): void { if (!this.allErrors) this.gen.if(cond) } setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj } block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) } check$data(valid: Name = nil, $dataValid: Code = nil): void { if (!this.$data) return const {gen, schemaCode, schemaType, def} = this gen.if(or(_`${schemaCode} === undefined`, $dataValid)) if (valid !== nil) gen.assign(valid, true) if (schemaType.length || def.validateSchema) { gen.elseIf(this.invalid$data()) this.$dataError() if (valid !== nil) gen.assign(valid, false) } gen.else() } invalid$data(): Code { const {gen, schemaCode, schemaType, def, it} = this return or(wrong$DataType(), invalid$DataSchema()) function wrong$DataType(): Code { if (schemaType.length) { /* istanbul ignore if */ if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error") const st = Array.isArray(schemaType) ? schemaType : [schemaType] return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}` } return nil } function invalid$DataSchema(): Code { if (def.validateSchema) { const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone return _`!${validateSchemaRef}(${schemaCode})` } return nil } } subschema(appl: SubschemaArgs, valid: Name): SchemaCxt { const subschema = getSubschema(this.it, appl) extendSubschemaData(subschema, this.it, appl) extendSubschemaMode(subschema, appl) const nextContext = {...this.it, ...subschema, items: undefined, props: undefined} subschemaCode(nextContext, valid) return nextContext } mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void { const {it, gen} = this if (!it.opts.unevaluated) return if (it.props !== true && schemaCxt.props !== undefined) { it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName) } if (it.items !== true && schemaCxt.items !== undefined) { it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName) } } mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void { const {it, gen} = this if (it.opts.unevaluated && (it.props !== true || it.items !== true)) { gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name)) return true } } }
2,377
(cxt: KeywordErrorCxt) => string | Code
interface KeywordErrorCxt { gen: CodeGen keyword: string data: Name $data?: string | false schema: any // TODO parentSchema?: AnySchemaObject schemaCode: Code | number | boolean schemaValue: Code | number | boolean schemaType?: JSONType[] errsCount?: Name params: KeywordCxtParams it: SchemaCxt }
2,378
(cxt: KeywordErrorCxt) => Code
interface KeywordErrorCxt { gen: CodeGen keyword: string data: Name $data?: string | false schema: any // TODO parentSchema?: AnySchemaObject schemaCode: Code | number | boolean schemaValue: Code | number | boolean schemaType?: JSONType[] errsCount?: Name params: KeywordCxtParams it: SchemaCxt }
2,379
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 = {} }
interface SchemaEnvArgs { readonly schema: AnySchema readonly schemaId?: "$id" | "id" readonly root?: SchemaEnv readonly baseId?: string readonly schemaPath?: string readonly localRefs?: LocalRefs readonly meta?: boolean }
2,380
function compileSchema(this: Ajv, sch: SchemaEnv): SchemaEnv { // TODO refactor - remove compilations const _sch = getCompilingSchema.call(this, sch) if (_sch) return _sch const rootId = getFullPath(this.opts.uriResolver, sch.root.baseId) // TODO if getFullPath removed 1 tests fails const {es5, lines} = this.opts.code const {ownProperties} = this.opts const gen = new CodeGen(this.scope, {es5, lines, ownProperties}) let _ValidationError if (sch.$async) { _ValidationError = gen.scopeValue("Error", { ref: ValidationError, code: _`require("ajv/dist/runtime/validation_error").default`, }) } const validateName = gen.scopeName("validate") sch.validateName = validateName const schemaCxt: SchemaCxt = { gen, allErrors: this.opts.allErrors, data: N.data, parentData: N.parentData, parentDataProperty: N.parentDataProperty, dataNames: [N.data], dataPathArr: [nil], // TODO can its length be used as dataLevel if nil is removed? dataLevel: 0, dataTypes: [], definedProperties: new Set<string>(), topSchemaRef: gen.scopeValue( "schema", this.opts.code.source === true ? {ref: sch.schema, code: stringify(sch.schema)} : {ref: sch.schema} ), validateName, ValidationError: _ValidationError, schema: sch.schema, schemaEnv: sch, rootId, baseId: sch.baseId || rootId, schemaPath: nil, errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), errorPath: _`""`, opts: this.opts, self: this, } let sourceCode: string | undefined try { this._compilations.add(sch) validateFunctionCode(schemaCxt) gen.optimize(this.opts.code.optimize) // gen.optimize(1) const validateCode = gen.toString() sourceCode = `${gen.scopeRefs(N.scope)}return ${validateCode}` // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount)) if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch) // console.log("\n\n\n *** \n", sourceCode) const makeValidate = new Function(`${N.self}`, `${N.scope}`, sourceCode) const validate: AnyValidateFunction = makeValidate(this, this.scope.get()) this.scope.value(validateName, {ref: validate}) validate.errors = null validate.schema = sch.schema validate.schemaEnv = sch if (sch.$async) (validate as AsyncValidateFunction).$async = true if (this.opts.code.source === true) { validate.source = {validateName, validateCode, scopeValues: gen._values} } if (this.opts.unevaluated) { const {props, items} = schemaCxt validate.evaluated = { props: props instanceof Name ? undefined : props, items: items instanceof Name ? undefined : items, dynamicProps: props instanceof Name, dynamicItems: items instanceof Name, } if (validate.source) validate.source.evaluated = stringify(validate.evaluated) } sch.validate = validate return sch } catch (e) { delete sch.validate delete sch.validateName if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode) // console.log("\n\n\n *** \n", sourceCode, this.opts) throw e } finally { this._compilations.delete(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,381
function compileSchema(this: Ajv, sch: SchemaEnv): SchemaEnv { // TODO refactor - remove compilations const _sch = getCompilingSchema.call(this, sch) if (_sch) return _sch const rootId = getFullPath(this.opts.uriResolver, sch.root.baseId) // TODO if getFullPath removed 1 tests fails const {es5, lines} = this.opts.code const {ownProperties} = this.opts const gen = new CodeGen(this.scope, {es5, lines, ownProperties}) let _ValidationError if (sch.$async) { _ValidationError = gen.scopeValue("Error", { ref: ValidationError, code: _`require("ajv/dist/runtime/validation_error").default`, }) } const validateName = gen.scopeName("validate") sch.validateName = validateName const schemaCxt: SchemaCxt = { gen, allErrors: this.opts.allErrors, data: N.data, parentData: N.parentData, parentDataProperty: N.parentDataProperty, dataNames: [N.data], dataPathArr: [nil], // TODO can its length be used as dataLevel if nil is removed? dataLevel: 0, dataTypes: [], definedProperties: new Set<string>(), topSchemaRef: gen.scopeValue( "schema", this.opts.code.source === true ? {ref: sch.schema, code: stringify(sch.schema)} : {ref: sch.schema} ), validateName, ValidationError: _ValidationError, schema: sch.schema, schemaEnv: sch, rootId, baseId: sch.baseId || rootId, schemaPath: nil, errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), errorPath: _`""`, opts: this.opts, self: this, } let sourceCode: string | undefined try { this._compilations.add(sch) validateFunctionCode(schemaCxt) gen.optimize(this.opts.code.optimize) // gen.optimize(1) const validateCode = gen.toString() sourceCode = `${gen.scopeRefs(N.scope)}return ${validateCode}` // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount)) if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch) // console.log("\n\n\n *** \n", sourceCode) const makeValidate = new Function(`${N.self}`, `${N.scope}`, sourceCode) const validate: AnyValidateFunction = makeValidate(this, this.scope.get()) this.scope.value(validateName, {ref: validate}) validate.errors = null validate.schema = sch.schema validate.schemaEnv = sch if (sch.$async) (validate as AsyncValidateFunction).$async = true if (this.opts.code.source === true) { validate.source = {validateName, validateCode, scopeValues: gen._values} } if (this.opts.unevaluated) { const {props, items} = schemaCxt validate.evaluated = { props: props instanceof Name ? undefined : props, items: items instanceof Name ? undefined : items, dynamicProps: props instanceof Name, dynamicItems: items instanceof Name, } if (validate.source) validate.source.evaluated = stringify(validate.evaluated) } sch.validate = validate return sch } catch (e) { delete sch.validate delete sch.validateName if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode) // console.log("\n\n\n *** \n", sourceCode, this.opts) throw e } finally { this._compilations.delete(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,382
function compileSchema(this: Ajv, sch: SchemaEnv): SchemaEnv { // TODO refactor - remove compilations const _sch = getCompilingSchema.call(this, sch) if (_sch) return _sch const rootId = getFullPath(this.opts.uriResolver, sch.root.baseId) // TODO if getFullPath removed 1 tests fails const {es5, lines} = this.opts.code const {ownProperties} = this.opts const gen = new CodeGen(this.scope, {es5, lines, ownProperties}) let _ValidationError if (sch.$async) { _ValidationError = gen.scopeValue("Error", { ref: ValidationError, code: _`require("ajv/dist/runtime/validation_error").default`, }) } const validateName = gen.scopeName("validate") sch.validateName = validateName const schemaCxt: SchemaCxt = { gen, allErrors: this.opts.allErrors, data: N.data, parentData: N.parentData, parentDataProperty: N.parentDataProperty, dataNames: [N.data], dataPathArr: [nil], // TODO can its length be used as dataLevel if nil is removed? dataLevel: 0, dataTypes: [], definedProperties: new Set<string>(), topSchemaRef: gen.scopeValue( "schema", this.opts.code.source === true ? {ref: sch.schema, code: stringify(sch.schema)} : {ref: sch.schema} ), validateName, ValidationError: _ValidationError, schema: sch.schema, schemaEnv: sch, rootId, baseId: sch.baseId || rootId, schemaPath: nil, errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), errorPath: _`""`, opts: this.opts, self: this, } let sourceCode: string | undefined try { this._compilations.add(sch) validateFunctionCode(schemaCxt) gen.optimize(this.opts.code.optimize) // gen.optimize(1) const validateCode = gen.toString() sourceCode = `${gen.scopeRefs(N.scope)}return ${validateCode}` // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount)) if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch) // console.log("\n\n\n *** \n", sourceCode) const makeValidate = new Function(`${N.self}`, `${N.scope}`, sourceCode) const validate: AnyValidateFunction = makeValidate(this, this.scope.get()) this.scope.value(validateName, {ref: validate}) validate.errors = null validate.schema = sch.schema validate.schemaEnv = sch if (sch.$async) (validate as AsyncValidateFunction).$async = true if (this.opts.code.source === true) { validate.source = {validateName, validateCode, scopeValues: gen._values} } if (this.opts.unevaluated) { const {props, items} = schemaCxt validate.evaluated = { props: props instanceof Name ? undefined : props, items: items instanceof Name ? undefined : items, dynamicProps: props instanceof Name, dynamicItems: items instanceof Name, } if (validate.source) validate.source.evaluated = stringify(validate.evaluated) } sch.validate = validate return sch } catch (e) { delete sch.validate delete sch.validateName if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode) // console.log("\n\n\n *** \n", sourceCode, this.opts) throw e } finally { this._compilations.delete(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,383
function compileSchema(this: Ajv, sch: SchemaEnv): SchemaEnv { // TODO refactor - remove compilations const _sch = getCompilingSchema.call(this, sch) if (_sch) return _sch const rootId = getFullPath(this.opts.uriResolver, sch.root.baseId) // TODO if getFullPath removed 1 tests fails const {es5, lines} = this.opts.code const {ownProperties} = this.opts const gen = new CodeGen(this.scope, {es5, lines, ownProperties}) let _ValidationError if (sch.$async) { _ValidationError = gen.scopeValue("Error", { ref: ValidationError, code: _`require("ajv/dist/runtime/validation_error").default`, }) } const validateName = gen.scopeName("validate") sch.validateName = validateName const schemaCxt: SchemaCxt = { gen, allErrors: this.opts.allErrors, data: N.data, parentData: N.parentData, parentDataProperty: N.parentDataProperty, dataNames: [N.data], dataPathArr: [nil], // TODO can its length be used as dataLevel if nil is removed? dataLevel: 0, dataTypes: [], definedProperties: new Set<string>(), topSchemaRef: gen.scopeValue( "schema", this.opts.code.source === true ? {ref: sch.schema, code: stringify(sch.schema)} : {ref: sch.schema} ), validateName, ValidationError: _ValidationError, schema: sch.schema, schemaEnv: sch, rootId, baseId: sch.baseId || rootId, schemaPath: nil, errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"), errorPath: _`""`, opts: this.opts, self: this, } let sourceCode: string | undefined try { this._compilations.add(sch) validateFunctionCode(schemaCxt) gen.optimize(this.opts.code.optimize) // gen.optimize(1) const validateCode = gen.toString() sourceCode = `${gen.scopeRefs(N.scope)}return ${validateCode}` // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount)) if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch) // console.log("\n\n\n *** \n", sourceCode) const makeValidate = new Function(`${N.self}`, `${N.scope}`, sourceCode) const validate: AnyValidateFunction = makeValidate(this, this.scope.get()) this.scope.value(validateName, {ref: validate}) validate.errors = null validate.schema = sch.schema validate.schemaEnv = sch if (sch.$async) (validate as AsyncValidateFunction).$async = true if (this.opts.code.source === true) { validate.source = {validateName, validateCode, scopeValues: gen._values} } if (this.opts.unevaluated) { const {props, items} = schemaCxt validate.evaluated = { props: props instanceof Name ? undefined : props, items: items instanceof Name ? undefined : items, dynamicProps: props instanceof Name, dynamicItems: items instanceof Name, } if (validate.source) validate.source.evaluated = stringify(validate.evaluated) } sch.validate = validate return sch } catch (e) { delete sch.validate delete sch.validateName if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode) // console.log("\n\n\n *** \n", sourceCode, this.opts) throw e } finally { this._compilations.delete(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,384
function resolveRef( this: Ajv, root: SchemaEnv, baseId: string, ref: string ): AnySchema | SchemaEnv | undefined { ref = resolveUrl(this.opts.uriResolver, baseId, ref) const schOrFunc = root.refs[ref] if (schOrFunc) return schOrFunc let _sch = resolve.call(this, root, ref) if (_sch === undefined) { const schema = root.localRefs?.[ref] // TODO maybe localRefs should hold SchemaEnv const {schemaId} = this.opts if (schema) _sch = new SchemaEnv({schema, schemaId, root, baseId}) } if (_sch === undefined) return return (root.refs[ref] = inlineOrCompile.call(this, _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,385
function resolveRef( this: Ajv, root: SchemaEnv, baseId: string, ref: string ): AnySchema | SchemaEnv | undefined { ref = resolveUrl(this.opts.uriResolver, baseId, ref) const schOrFunc = root.refs[ref] if (schOrFunc) return schOrFunc let _sch = resolve.call(this, root, ref) if (_sch === undefined) { const schema = root.localRefs?.[ref] // TODO maybe localRefs should hold SchemaEnv const {schemaId} = this.opts if (schema) _sch = new SchemaEnv({schema, schemaId, root, baseId}) } if (_sch === undefined) return return (root.refs[ref] = inlineOrCompile.call(this, _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,386
function resolveRef( this: Ajv, root: SchemaEnv, baseId: string, ref: string ): AnySchema | SchemaEnv | undefined { ref = resolveUrl(this.opts.uriResolver, baseId, ref) const schOrFunc = root.refs[ref] if (schOrFunc) return schOrFunc let _sch = resolve.call(this, root, ref) if (_sch === undefined) { const schema = root.localRefs?.[ref] // TODO maybe localRefs should hold SchemaEnv const {schemaId} = this.opts if (schema) _sch = new SchemaEnv({schema, schemaId, root, baseId}) } if (_sch === undefined) return return (root.refs[ref] = inlineOrCompile.call(this, _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,387
function resolveRef( this: Ajv, root: SchemaEnv, baseId: string, ref: string ): AnySchema | SchemaEnv | undefined { ref = resolveUrl(this.opts.uriResolver, baseId, ref) const schOrFunc = root.refs[ref] if (schOrFunc) return schOrFunc let _sch = resolve.call(this, root, ref) if (_sch === undefined) { const schema = root.localRefs?.[ref] // TODO maybe localRefs should hold SchemaEnv const {schemaId} = this.opts if (schema) _sch = new SchemaEnv({schema, schemaId, root, baseId}) } if (_sch === undefined) return return (root.refs[ref] = inlineOrCompile.call(this, _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,388
function inlineOrCompile(this: Ajv, sch: SchemaEnv): AnySchema | SchemaEnv { if (inlineRef(sch.schema, this.opts.inlineRefs)) return sch.schema return sch.validate ? sch : compileSchema.call(this, 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,389
function inlineOrCompile(this: Ajv, sch: SchemaEnv): AnySchema | SchemaEnv { if (inlineRef(sch.schema, this.opts.inlineRefs)) return sch.schema return sch.validate ? sch : compileSchema.call(this, 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,390
function inlineOrCompile(this: Ajv, sch: SchemaEnv): AnySchema | SchemaEnv { if (inlineRef(sch.schema, this.opts.inlineRefs)) return sch.schema return sch.validate ? sch : compileSchema.call(this, 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,391
function inlineOrCompile(this: Ajv, sch: SchemaEnv): AnySchema | SchemaEnv { if (inlineRef(sch.schema, this.opts.inlineRefs)) return sch.schema return sch.validate ? sch : compileSchema.call(this, 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,392
function getCompilingSchema(this: Ajv, schEnv: SchemaEnv): SchemaEnv | void { for (const sch of this._compilations) { if (sameSchemaEnv(sch, schEnv)) 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,393
function getCompilingSchema(this: Ajv, schEnv: SchemaEnv): SchemaEnv | void { for (const sch of this._compilations) { if (sameSchemaEnv(sch, schEnv)) 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,394
function getCompilingSchema(this: Ajv, schEnv: SchemaEnv): SchemaEnv | void { for (const sch of this._compilations) { if (sameSchemaEnv(sch, schEnv)) 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,395
function getCompilingSchema(this: Ajv, schEnv: SchemaEnv): SchemaEnv | void { for (const sch of this._compilations) { if (sameSchemaEnv(sch, schEnv)) 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,396
function sameSchemaEnv(s1: SchemaEnv, s2: SchemaEnv): boolean { return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId }
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,397
function resolve( this: Ajv, root: SchemaEnv, // information about the root schema for the current schema ref: string // reference to resolve ): SchemaEnv | undefined { let sch while (typeof (sch = this.refs[ref]) == "string") ref = sch return sch || this.schemas[ref] || resolveSchema.call(this, root, ref) }
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,398
function resolve( this: Ajv, root: SchemaEnv, // information about the root schema for the current schema ref: string // reference to resolve ): SchemaEnv | undefined { let sch while (typeof (sch = this.refs[ref]) == "string") ref = sch return sch || this.schemas[ref] || resolveSchema.call(this, root, ref) }
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,399
function resolve( this: Ajv, root: SchemaEnv, // information about the root schema for the current schema ref: string // reference to resolve ): SchemaEnv | undefined { let sch while (typeof (sch = this.refs[ref]) == "string") ref = sch return sch || this.schemas[ref] || resolveSchema.call(this, root, ref) }
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 } }