id
int64
0
3.78k
code
stringlengths
13
37.9k
declarations
stringlengths
16
64.6k
2,500
function returnResults(it: SchemaCxt): void { const {gen, schemaEnv, validateName, ValidationError, opts} = it if (schemaEnv.$async) { // TODO assign unevaluated gen.if( _`${N.errors} === 0`, () => gen.return(N.data), () => gen.throw(_`new ${ValidationError as Name}(${N.vErrors})`) ) ...
interface SchemaCxt { readonly gen: CodeGen readonly allErrors?: boolean // validation mode - whether to collect all errors or break on error readonly data: Name // Name with reference to the current part of data instance readonly parentData: Name // should be used in keywords modifying data readonly parentDa...
2,501
function assignEvaluated({gen, evaluated, props, items}: SchemaCxt): void { if (props instanceof Name) gen.assign(_`${evaluated}.props`, props) if (items instanceof Name) gen.assign(_`${evaluated}.items`, items) }
interface SchemaCxt { readonly gen: CodeGen readonly allErrors?: boolean // validation mode - whether to collect all errors or break on error readonly data: Name // Name with reference to the current part of data instance readonly parentData: Name // should be used in keywords modifying data readonly parentDa...
2,502
function schemaKeywords( it: SchemaObjCxt, types: JSONType[], typeErrors: boolean, errsCount?: Name ): void { const {gen, schema, data, allErrors, opts, self} = it const {RULES} = self if (schema.$ref && (opts.ignoreKeywordsWithRef || !schemaHasRulesButRef(schema, RULES))) { gen.block(() => keywordCod...
interface SchemaObjCxt extends SchemaCxt { readonly schema: AnySchemaObject }
2,503
function schemaKeywords( it: SchemaObjCxt, types: JSONType[], typeErrors: boolean, errsCount?: Name ): void { const {gen, schema, data, allErrors, opts, self} = it const {RULES} = self if (schema.$ref && (opts.ignoreKeywordsWithRef || !schemaHasRulesButRef(schema, RULES))) { gen.block(() => keywordCod...
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(): UsedN...
2,504
function groupKeywords(group: RuleGroup): void { if (!shouldUseGroup(schema, group)) return if (group.type) { gen.if(checkDataType(group.type, data, opts.strictNumbers)) iterateKeywords(it, group) if (types.length === 1 && types[0] === group.type && typeErrors) { gen.else() rep...
interface RuleGroup { type?: JSONType rules: Rule[] }
2,505
function iterateKeywords(it: SchemaObjCxt, group: RuleGroup): void { const { gen, schema, opts: {useDefaults}, } = it if (useDefaults) assignDefaults(it, group.type) gen.block(() => { for (const rule of group.rules) { if (shouldUseRule(schema, rule)) { keywordCode(it, rule.keyword,...
interface RuleGroup { type?: JSONType rules: Rule[] }
2,506
function iterateKeywords(it: SchemaObjCxt, group: RuleGroup): void { const { gen, schema, opts: {useDefaults}, } = it if (useDefaults) assignDefaults(it, group.type) gen.block(() => { for (const rule of group.rules) { if (shouldUseRule(schema, rule)) { keywordCode(it, rule.keyword,...
interface SchemaObjCxt extends SchemaCxt { readonly schema: AnySchemaObject }
2,507
function checkStrictTypes(it: SchemaObjCxt, types: JSONType[]): void { if (it.schemaEnv.meta || !it.opts.strictTypes) return checkContextTypes(it, types) if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types) checkKeywordTypes(it, it.dataTypes) }
interface SchemaObjCxt extends SchemaCxt { readonly schema: AnySchemaObject }
2,508
function checkContextTypes(it: SchemaObjCxt, types: JSONType[]): void { if (!types.length) return if (!it.dataTypes.length) { it.dataTypes = types return } types.forEach((t) => { if (!includesType(it.dataTypes, t)) { strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join...
interface SchemaObjCxt extends SchemaCxt { readonly schema: AnySchemaObject }
2,509
function checkMultipleTypes(it: SchemaObjCxt, ts: JSONType[]): void { if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) { strictTypesError(it, "use allowUnionTypes to allow union type keyword") } }
interface SchemaObjCxt extends SchemaCxt { readonly schema: AnySchemaObject }
2,510
function checkKeywordTypes(it: SchemaObjCxt, ts: JSONType[]): void { const rules = it.self.RULES.all for (const keyword in rules) { const rule = rules[keyword] if (typeof rule == "object" && shouldUseRule(it.schema, rule)) { const {type} = rule.definition if (type.length && !type.some((t) => has...
interface SchemaObjCxt extends SchemaCxt { readonly schema: AnySchemaObject }
2,511
function narrowSchemaTypes(it: SchemaObjCxt, withTypes: JSONType[]): void { const ts: JSONType[] = [] for (const t of it.dataTypes) { if (includesType(withTypes, t)) ts.push(t) else if (withTypes.includes("integer") && t === "number") ts.push("integer") } it.dataTypes = ts }
interface SchemaObjCxt extends SchemaCxt { readonly schema: AnySchemaObject }
2,512
function strictTypesError(it: SchemaObjCxt, msg: string): void { const schemaPath = it.schemaEnv.baseId + it.errSchemaPath msg += ` at "${schemaPath}" (strictTypes)` checkStrictMode(it, msg, it.opts.strictTypes) }
interface SchemaObjCxt extends SchemaCxt { readonly schema: AnySchemaObject }
2,513
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.sch...
type AddedKeywordDefinition = KeywordDefinition & { type: JSONType[] schemaType: JSONType[] }
2,514
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.sch...
interface SchemaObjCxt extends SchemaCxt { readonly schema: AnySchemaObject }
2,515
result(condition: Code, successAction?: () => void, failAction?: () => void): void { this.failResult(not(condition), successAction, failAction) }
type Code = _Code | Name
2,516
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...
type Code = _Code | Name
2,517
pass(condition: Code, failAction?: () => void): void { this.failResult(not(condition), undefined, failAction) }
type Code = _Code | Name
2,518
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() }
type Code = _Code | Name
2,519
fail$data(condition: Code): void { if (!this.$data) return this.fail(condition) const {schemaCode} = this this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`) }
type Code = _Code | Name
2,520
setParams(obj: KeywordCxtParams, assign?: true): void { if (assign) Object.assign(this.params, obj) else this.params = obj }
type KeywordCxtParams = {[P in string]?: Code | string | number}
2,521
block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) }
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(): UsedN...
2,522
block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void { this.gen.block(() => { this.check$data(valid, $dataValid) codeBlock() }) }
type Code = _Code | Name
2,523
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...
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(): UsedN...
2,524
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...
type Code = _Code | Name
2,525
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, vali...
type SubschemaArgs = Partial<{ keyword: string schemaProp: string | number schema: AnySchema schemaPath: Code errSchemaPath: string topSchemaRef: Code data: Name | Code dataProp: Code | string | number dataTypes: JSONType[] definedProperties: Set<string> propertyName: Name dataPropType: Type j...
2,526
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, vali...
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(): UsedN...
2,527
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.item...
interface SchemaCxt { readonly gen: CodeGen readonly allErrors?: boolean // validation mode - whether to collect all errors or break on error readonly data: Name // Name with reference to the current part of data instance readonly parentData: Name // should be used in keywords modifying data readonly parentDa...
2,528
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 } }
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(): UsedN...
2,529
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 } }
interface SchemaCxt { readonly gen: CodeGen readonly allErrors?: boolean // validation mode - whether to collect all errors or break on error readonly data: Name // Name with reference to the current part of data instance readonly parentData: Name // should be used in keywords modifying data readonly parentDa...
2,530
function keywordCode( it: SchemaObjCxt, keyword: string, def: AddedKeywordDefinition, ruleType?: JSONType ): void { const cxt = new KeywordCxt(it, def, keyword) if ("code" in def) { def.code(cxt, ruleType) } else if (cxt.$data && def.validate) { funcKeywordCode(cxt, def) } else if ("macro" in de...
type AddedKeywordDefinition = KeywordDefinition & { type: JSONType[] schemaType: JSONType[] }
2,531
function keywordCode( it: SchemaObjCxt, keyword: string, def: AddedKeywordDefinition, ruleType?: JSONType ): void { const cxt = new KeywordCxt(it, def, keyword) if ("code" in def) { def.code(cxt, ruleType) } else if (cxt.$data && def.validate) { funcKeywordCode(cxt, def) } else if ("macro" in de...
interface SchemaObjCxt extends SchemaCxt { readonly schema: AnySchemaObject }
2,532
function keywordCode( it: SchemaObjCxt, keyword: string, def: AddedKeywordDefinition, ruleType?: JSONType ): void { const cxt = new KeywordCxt(it, def, keyword) if ("code" in def) { def.code(cxt, ruleType) } else if (cxt.$data && def.validate) { funcKeywordCode(cxt, def) } else if ("macro" in de...
type JSONType<T extends string, IsPartial extends boolean> = IsPartial extends true ? T | undefined : T
2,533
function keywordCode( it: SchemaObjCxt, keyword: string, def: AddedKeywordDefinition, ruleType?: JSONType ): void { const cxt = new KeywordCxt(it, def, keyword) if ("code" in def) { def.code(cxt, ruleType) } else if (cxt.$data && def.validate) { funcKeywordCode(cxt, def) } else if ("macro" in de...
type JSONType = (typeof _jsonTypes)[number]
2,534
function macroKeywordCode(cxt: KeywordCxt, def: MacroKeywordDefinition): void { const {gen, keyword, schema, parentSchema, it} = cxt const macroSchema = def.macro.call(it.self, schema, parentSchema, it) const schemaRef = useKeyword(gen, keyword, macroSchema) if (it.opts.validateSchema !== false) it.self.validat...
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 | n...
2,535
function macroKeywordCode(cxt: KeywordCxt, def: MacroKeywordDefinition): void { const {gen, keyword, schema, parentSchema, it} = cxt const macroSchema = def.macro.call(it.self, schema, parentSchema, it) const schemaRef = useKeyword(gen, keyword, macroSchema) if (it.opts.validateSchema !== false) it.self.validat...
interface MacroKeywordDefinition extends FuncKeywordDefinition { macro: MacroKeywordFunc }
2,536
function funcKeywordCode(cxt: KeywordCxt, def: FuncKeywordDefinition): void { const {gen, keyword, schema, parentSchema, $data, it} = cxt checkAsyncKeyword(it, def) const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate const validateRef = useKeyword(gen,...
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 | n...
2,537
function funcKeywordCode(cxt: KeywordCxt, def: FuncKeywordDefinition): void { const {gen, keyword, schema, parentSchema, $data, it} = cxt checkAsyncKeyword(it, def) const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate const validateRef = useKeyword(gen,...
interface FuncKeywordDefinition extends _KeywordDef { validate?: SchemaValidateFunction | DataValidateFunction compile?: CompileKeywordFunc // schema: false makes validate not to expect schema (DataValidateFunction) schema?: boolean // requires "validate" modifying?: boolean async?: boolean valid?: boolea...
2,538
function assignValid(_await: Code = def.async ? _`await ` : nil): void { const passCxt = it.opts.passContext ? N.this : N.self const passSchema = !(("compile" in def && !$data) || def.schema === false) gen.assign( valid, _`${_await}${callValidateCode(cxt, validateRef, passCxt, passSchema)}`, ...
type Code = _Code | Name
2,539
function modifyData(cxt: KeywordCxt): void { const {gen, data, it} = cxt gen.if(it.parentData, () => gen.assign(data, _`${it.parentData}[${it.parentDataProperty}]`)) }
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 | n...
2,540
function addErrs(cxt: KeywordCxt, errs: Code): void { const {gen} = cxt gen.if( _`Array.isArray(${errs})`, () => { gen .assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`) .assign(N.errors, _`${N.vErrors}.length`) extendErrors(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 | n...
2,541
function addErrs(cxt: KeywordCxt, errs: Code): void { const {gen} = cxt gen.if( _`Array.isArray(${errs})`, () => { gen .assign(N.vErrors, _`${N.vErrors} === null ? ${errs} : ${N.vErrors}.concat(${errs})`) .assign(N.errors, _`${N.vErrors}.length`) extendErrors(cxt) }, () =...
type Code = _Code | Name
2,542
function checkAsyncKeyword({schemaEnv}: SchemaObjCxt, def: FuncKeywordDefinition): void { if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema") }
interface SchemaObjCxt extends SchemaCxt { readonly schema: AnySchemaObject }
2,543
function checkAsyncKeyword({schemaEnv}: SchemaObjCxt, def: FuncKeywordDefinition): void { if (def.async && !schemaEnv.$async) throw new Error("async keyword in sync schema") }
interface FuncKeywordDefinition extends _KeywordDef { validate?: SchemaValidateFunction | DataValidateFunction compile?: CompileKeywordFunc // schema: false makes validate not to expect schema (DataValidateFunction) schema?: boolean // requires "validate" modifying?: boolean async?: boolean valid?: boolea...
2,544
function useKeyword(gen: CodeGen, keyword: string, result?: KeywordCompilationResult): Name { if (result === undefined) throw new Error(`keyword "${keyword}" failed to compile`) return gen.scopeValue( "keyword", typeof result == "function" ? {ref: result} : {ref: result, code: stringify(result)} ) }
type KeywordCompilationResult = AnySchema | SchemaValidateFunction | AnyValidateFunction
2,545
function useKeyword(gen: CodeGen, keyword: string, result?: KeywordCompilationResult): Name { if (result === undefined) throw new Error(`keyword "${keyword}" failed to compile`) return gen.scopeValue( "keyword", typeof result == "function" ? {ref: result} : {ref: result, code: stringify(result)} ) }
class CodeGen { readonly _scope: Scope readonly _extScope: ValueScope readonly _values: ScopeValueSets = {} private readonly _nodes: ParentNode[] private readonly _blockStarts: number[] = [] private readonly _constants: Constants = {} private readonly opts: CGOptions constructor(extScope: ValueScope, o...
2,546
function validateKeywordUsage( {schema, opts, self, errSchemaPath}: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string ): void { /* istanbul ignore if */ if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) { throw new Error("ajv implementation error") } ...
type AddedKeywordDefinition = KeywordDefinition & { type: JSONType[] schemaType: JSONType[] }
2,547
function validateKeywordUsage( {schema, opts, self, errSchemaPath}: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string ): void { /* istanbul ignore if */ if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) { throw new Error("ajv implementation error") } ...
interface SchemaObjCxt extends SchemaCxt { readonly schema: AnySchemaObject }
2,548
function getSchemaTypes(schema: AnySchemaObject): JSONType[] { const types = getJSONTypes(schema.type) const hasNull = types.includes("null") if (hasNull) { if (schema.nullable === false) throw new Error("type: null contradicts nullable: false") } else { if (!types.length && schema.nullable !== undefine...
type AnySchemaObject = SchemaObject | AsyncSchema
2,549
function coerceAndCheckDataType(it: SchemaObjCxt, types: JSONType[]): boolean { const {gen, data, opts} = it const coerceTo = coerceToTypes(types, opts.coerceTypes) const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && schemaHasRulesForType(it, types[0])) if (checkTypes...
interface SchemaObjCxt extends SchemaCxt { readonly schema: AnySchemaObject }
2,550
function coerceData(it: SchemaObjCxt, types: JSONType[], coerceTo: JSONType[]): void { const {gen, data, opts} = it const dataType = gen.let("dataType", _`typeof ${data}`) const coerced = gen.let("coerced", _`undefined`) if (opts.coerceTypes === "array") { gen.if(_`${dataType} == 'object' && Array.isArray($...
interface SchemaObjCxt extends SchemaCxt { readonly schema: AnySchemaObject }
2,551
function assignParentData({gen, parentData, parentDataProperty}: SchemaObjCxt, expr: Name): void { // TODO use gen.property gen.if(_`${parentData} !== undefined`, () => gen.assign(_`${parentData}[${parentDataProperty}]`, expr) ) }
interface SchemaObjCxt extends SchemaCxt { readonly schema: AnySchemaObject }
2,552
function assignParentData({gen, parentData, parentDataProperty}: SchemaObjCxt, expr: Name): void { // TODO use gen.property gen.if(_`${parentData} !== undefined`, () => gen.assign(_`${parentData}[${parentDataProperty}]`, expr) ) }
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(): UsedN...
2,553
function checkDataType( dataType: JSONType, data: Name, strictNums?: boolean | "log", correct = DataType.Correct ): Code { const EQ = correct === DataType.Correct ? operators.EQ : operators.NEQ let cond: Code switch (dataType) { case "null": return _`${data} ${EQ} null` case "array": c...
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(): UsedN...
2,554
function checkDataType( dataType: JSONType, data: Name, strictNums?: boolean | "log", correct = DataType.Correct ): Code { const EQ = correct === DataType.Correct ? operators.EQ : operators.NEQ let cond: Code switch (dataType) { case "null": return _`${data} ${EQ} null` case "array": c...
type JSONType<T extends string, IsPartial extends boolean> = IsPartial extends true ? T | undefined : T
2,555
function checkDataType( dataType: JSONType, data: Name, strictNums?: boolean | "log", correct = DataType.Correct ): Code { const EQ = correct === DataType.Correct ? operators.EQ : operators.NEQ let cond: Code switch (dataType) { case "null": return _`${data} ${EQ} null` case "array": c...
type JSONType = (typeof _jsonTypes)[number]
2,556
function numCond(_cond: Code = nil): Code { return and(_`typeof ${data} == "number"`, _cond, strictNums ? _`isFinite(${data})` : nil) }
type Code = _Code | Name
2,557
function reportTypeError(it: SchemaObjCxt): void { const cxt = getTypeErrorContext(it) reportError(cxt, typeError) }
interface SchemaObjCxt extends SchemaCxt { readonly schema: AnySchemaObject }
2,558
function getTypeErrorContext(it: SchemaObjCxt): KeywordErrorCxt { const {gen, data, schema} = it const schemaCode = schemaRefOrVal(it, schema, "type") return { gen, keyword: "type", data, schema: schema.type, schemaCode, schemaValue: schemaCode, parentSchema: schema, params: {}, ...
interface SchemaObjCxt extends SchemaCxt { readonly schema: AnySchemaObject }
2,559
function getSubschema( it: SchemaObjCxt, {keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef}: SubschemaArgs ): SubschemaContext { if (keyword !== undefined && schema !== undefined) { throw new Error('both "keyword" and "schema" passed, only one allowed') } if (keyword !== undefined) { ...
type SubschemaArgs = Partial<{ keyword: string schemaProp: string | number schema: AnySchema schemaPath: Code errSchemaPath: string topSchemaRef: Code data: Name | Code dataProp: Code | string | number dataTypes: JSONType[] definedProperties: Set<string> propertyName: Name dataPropType: Type j...
2,560
function getSubschema( it: SchemaObjCxt, {keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef}: SubschemaArgs ): SubschemaContext { if (keyword !== undefined && schema !== undefined) { throw new Error('both "keyword" and "schema" passed, only one allowed') } if (keyword !== undefined) { ...
interface SchemaObjCxt extends SchemaCxt { readonly schema: AnySchemaObject }
2,561
function extendSubschemaData( subschema: SubschemaContext, it: SchemaObjCxt, {dataProp, dataPropType: dpType, data, dataTypes, propertyName}: SubschemaArgs ): void { if (data !== undefined && dataProp !== undefined) { throw new Error('both "data" and "dataProp" passed, only one allowed') } const {gen} ...
type SubschemaArgs = Partial<{ keyword: string schemaProp: string | number schema: AnySchema schemaPath: Code errSchemaPath: string topSchemaRef: Code data: Name | Code dataProp: Code | string | number dataTypes: JSONType[] definedProperties: Set<string> propertyName: Name dataPropType: Type j...
2,562
function extendSubschemaData( subschema: SubschemaContext, it: SchemaObjCxt, {dataProp, dataPropType: dpType, data, dataTypes, propertyName}: SubschemaArgs ): void { if (data !== undefined && dataProp !== undefined) { throw new Error('both "data" and "dataProp" passed, only one allowed') } const {gen} ...
interface SubschemaContext { // TODO use Optional? align with SchemCxt property types schema: AnySchema schemaPath: Code errSchemaPath: string topSchemaRef?: Code errorPath?: Code dataLevel?: number dataTypes?: JSONType[] data?: Name parentData?: Name parentDataProperty?: Code | number dataNames...
2,563
function extendSubschemaData( subschema: SubschemaContext, it: SchemaObjCxt, {dataProp, dataPropType: dpType, data, dataTypes, propertyName}: SubschemaArgs ): void { if (data !== undefined && dataProp !== undefined) { throw new Error('both "data" and "dataProp" passed, only one allowed') } const {gen} ...
interface SchemaObjCxt extends SchemaCxt { readonly schema: AnySchemaObject }
2,564
function dataContextProps(_nextData: Name): void { subschema.data = _nextData subschema.dataLevel = it.dataLevel + 1 subschema.dataTypes = [] it.definedProperties = new Set<string>() subschema.parentData = it.data subschema.dataNames = [...it.dataNames, _nextData] }
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(): UsedN...
2,565
function extendSubschemaMode( subschema: SubschemaContext, {jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors}: SubschemaArgs ): void { if (compositeRule !== undefined) subschema.compositeRule = compositeRule if (createErrors !== undefined) subschema.createErrors = createErrors if (allErro...
type SubschemaArgs = Partial<{ keyword: string schemaProp: string | number schema: AnySchema schemaPath: Code errSchemaPath: string topSchemaRef: Code data: Name | Code dataProp: Code | string | number dataTypes: JSONType[] definedProperties: Set<string> propertyName: Name dataPropType: Type j...
2,566
function extendSubschemaMode( subschema: SubschemaContext, {jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors}: SubschemaArgs ): void { if (compositeRule !== undefined) subschema.compositeRule = compositeRule if (createErrors !== undefined) subschema.createErrors = createErrors if (allErro...
interface SubschemaContext { // TODO use Optional? align with SchemCxt property types schema: AnySchema schemaPath: Code errSchemaPath: string topSchemaRef?: Code errorPath?: Code dataLevel?: number dataTypes?: JSONType[] data?: Name parentData?: Name parentDataProperty?: Code | number dataNames...
2,567
function assignDefaults(it: SchemaObjCxt, ty?: string): void { const {properties, items} = it.schema if (ty === "object" && properties) { for (const key in properties) { assignDefault(it, key, properties[key].default) } } else if (ty === "array" && Array.isArray(items)) { items.forEach((sch, i: ...
interface SchemaObjCxt extends SchemaCxt { readonly schema: AnySchemaObject }
2,568
function assignDefault(it: SchemaObjCxt, prop: string | number, defaultValue: unknown): void { const {gen, compositeRule, data, opts} = it if (defaultValue === undefined) return const childData = _`${data}${getProperty(prop)}` if (compositeRule) { checkStrictMode(it, `default is ignored for: ${childData}`) ...
interface SchemaObjCxt extends SchemaCxt { readonly schema: AnySchemaObject }
2,569
function schemaHasRulesForType( {schema, self}: SchemaObjCxt, type: JSONType ): boolean | undefined { const group = self.RULES.types[type] return group && group !== true && shouldUseGroup(schema, group) }
interface SchemaObjCxt extends SchemaCxt { readonly schema: AnySchemaObject }
2,570
function schemaHasRulesForType( {schema, self}: SchemaObjCxt, type: JSONType ): boolean | undefined { const group = self.RULES.types[type] return group && group !== true && shouldUseGroup(schema, group) }
type JSONType<T extends string, IsPartial extends boolean> = IsPartial extends true ? T | undefined : T
2,571
function schemaHasRulesForType( {schema, self}: SchemaObjCxt, type: JSONType ): boolean | undefined { const group = self.RULES.types[type] return group && group !== true && shouldUseGroup(schema, group) }
type JSONType = (typeof _jsonTypes)[number]
2,572
function shouldUseGroup(schema: AnySchemaObject, group: RuleGroup): boolean { return group.rules.some((rule) => shouldUseRule(schema, rule)) }
type AnySchemaObject = SchemaObject | AsyncSchema
2,573
function shouldUseGroup(schema: AnySchemaObject, group: RuleGroup): boolean { return group.rules.some((rule) => shouldUseRule(schema, rule)) }
interface RuleGroup { type?: JSONType rules: Rule[] }
2,574
function shouldUseRule(schema: AnySchemaObject, rule: Rule): boolean | undefined { return ( schema[rule.keyword] !== undefined || rule.definition.implements?.some((kwd) => schema[kwd] !== undefined) ) }
type AnySchemaObject = SchemaObject | AsyncSchema
2,575
function shouldUseRule(schema: AnySchemaObject, rule: Rule): boolean | undefined { return ( schema[rule.keyword] !== undefined || rule.definition.implements?.some((kwd) => schema[kwd] !== undefined) ) }
interface Rule { keyword: string definition: AddedKeywordDefinition }
2,576
(cxt: ParseCxt) => void
interface ParseCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code parseName: Name char: Name }
2,577
function compileParser( this: Ajv, sch: SchemaEnv, definitions: SchemaObjectMap ): SchemaEnv { const _sch = getCompilingSchema.call(this, sch) if (_sch) return _sch const {es5, lines} = this.opts.code const {ownProperties} = this.opts const gen = new CodeGen(this.scope, {es5, lines, ownProperties}) co...
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...
2,578
function compileParser( this: Ajv, sch: SchemaEnv, definitions: SchemaObjectMap ): SchemaEnv { const _sch = getCompilingSchema.call(this, sch) if (_sch) return _sch const {es5, lines} = this.opts.code const {ownProperties} = this.opts const gen = new CodeGen(this.scope, {es5, lines, ownProperties}) co...
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} = {...
2,579
function compileParser( this: Ajv, sch: SchemaEnv, definitions: SchemaObjectMap ): SchemaEnv { const _sch = getCompilingSchema.call(this, sch) if (_sch) return _sch const {es5, lines} = this.opts.code const {ownProperties} = this.opts const gen = new CodeGen(this.scope, {es5, lines, ownProperties}) co...
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) ret...
2,580
function compileParser( this: Ajv, sch: SchemaEnv, definitions: SchemaObjectMap ): SchemaEnv { const _sch = getCompilingSchema.call(this, sch) if (_sch) return _sch const {es5, lines} = this.opts.code const {ownProperties} = this.opts const gen = new CodeGen(this.scope, {es5, lines, ownProperties}) co...
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 ...
2,581
function compileParser( this: Ajv, sch: SchemaEnv, definitions: SchemaObjectMap ): SchemaEnv { const _sch = getCompilingSchema.call(this, sch) if (_sch) return _sch const {es5, lines} = this.opts.code const {ownProperties} = this.opts const gen = new CodeGen(this.scope, {es5, lines, ownProperties}) co...
type SchemaObjectMap = {[Ref in string]?: SchemaObject}
2,582
function parserFunction(cxt: ParseCxt): void { const {gen, parseName, char} = cxt gen.func(parseName, _`${N.json}, ${N.jsonPos}, ${N.jsonPart}`, false, () => { gen.let(N.data) gen.let(char) gen.assign(_`${parseName}.message`, undef) gen.assign(_`${parseName}.position`, undef) gen.assign(N.jsonPo...
interface ParseCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code parseName: Name char: Name }
2,583
function parseCode(cxt: ParseCxt): void { let form: JTDForm | undefined for (const key of jtdForms) { if (key in cxt.schema) { form = key break } } if (form) parseNullable(cxt, genParse[form]) else parseEmpty(cxt) }
interface ParseCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code parseName: Name char: Name }
2,584
function parseNullable(cxt: ParseCxt, parseForm: GenParse): void { const {gen, schema, data} = cxt if (!schema.nullable) return parseForm(cxt) tryParseToken(cxt, "null", parseForm, () => gen.assign(data, null)) }
interface ParseCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code parseName: Name char: Name }
2,585
function parseNullable(cxt: ParseCxt, parseForm: GenParse): void { const {gen, schema, data} = cxt if (!schema.nullable) return parseForm(cxt) tryParseToken(cxt, "null", parseForm, () => gen.assign(data, null)) }
type GenParse = (cxt: ParseCxt) => void
2,586
function parseElements(cxt: ParseCxt): void { const {gen, schema, data} = cxt parseToken(cxt, "[") const ix = gen.let("i", 0) gen.assign(data, _`[]`) parseItems(cxt, "]", () => { const el = gen.let("el") parseCode({...cxt, schema: schema.elements, data: el}) gen.assign(_`${data}[${ix}++]`, el) }...
interface ParseCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code parseName: Name char: Name }
2,587
function parseValues(cxt: ParseCxt): void { const {gen, schema, data} = cxt parseToken(cxt, "{") gen.assign(data, _`{}`) parseItems(cxt, "}", () => parseKeyValue(cxt, schema.values)) }
interface ParseCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code parseName: Name char: Name }
2,588
function parseItems(cxt: ParseCxt, endToken: string, block: () => void): void { tryParseItems(cxt, endToken, block) parseToken(cxt, endToken) }
interface ParseCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code parseName: Name char: Name }
2,589
function tryParseItems(cxt: ParseCxt, endToken: string, block: () => void): void { const {gen} = cxt gen.for(_`;${N.jsonPos}<${N.jsonLen} && ${jsonSlice(1)}!==${endToken};`, () => { block() tryParseToken(cxt, ",", () => gen.break(), hasItem) }) function hasItem(): void { tryParseToken(cxt, endToken...
interface ParseCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code parseName: Name char: Name }
2,590
function parseKeyValue(cxt: ParseCxt, schema: SchemaObject): void { const {gen} = cxt const key = gen.let("key") parseString({...cxt, data: key}) parseToken(cxt, ":") parsePropertyValue(cxt, key, schema) }
interface ParseCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code parseName: Name char: Name }
2,591
function parseKeyValue(cxt: ParseCxt, schema: SchemaObject): void { const {gen} = cxt const key = gen.let("key") parseString({...cxt, data: key}) parseToken(cxt, ":") parsePropertyValue(cxt, key, schema) }
interface SchemaObject extends _SchemaObject { id?: string $id?: string $schema?: string $async?: false [x: string]: any // TODO }
2,592
function parseDiscriminator(cxt: ParseCxt): void { const {gen, data, schema} = cxt const {discriminator, mapping} = schema parseToken(cxt, "{") gen.assign(data, _`{}`) const startPos = gen.const("pos", N.jsonPos) const value = gen.let("value") const tag = gen.let("tag") tryParseItems(cxt, "}", () => { ...
interface ParseCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code parseName: Name char: Name }
2,593
function parseProperties(cxt: ParseCxt): void { const {gen, data} = cxt parseToken(cxt, "{") gen.assign(data, _`{}`) parseSchemaProperties(cxt) }
interface ParseCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code parseName: Name char: Name }
2,594
function parseSchemaProperties(cxt: ParseCxt, discriminator?: string): void { const {gen, schema, data} = cxt const {properties, optionalProperties, additionalProperties} = schema parseItems(cxt, "}", () => { const key = gen.let("key") parseString({...cxt, data: key}) parseToken(cxt, ":") gen.if(f...
interface ParseCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code parseName: Name char: Name }
2,595
function parseDefinedProperty(cxt: ParseCxt, key: Name, schemas: SchemaObjectMap = {}): void { const {gen} = cxt for (const prop in schemas) { gen.elseIf(_`${key} === ${prop}`) parsePropertyValue(cxt, key, schemas[prop] as SchemaObject) } }
interface ParseCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code parseName: Name char: Name }
2,596
function parseDefinedProperty(cxt: ParseCxt, key: Name, schemas: SchemaObjectMap = {}): void { const {gen} = cxt for (const prop in schemas) { gen.elseIf(_`${key} === ${prop}`) parsePropertyValue(cxt, key, schemas[prop] as SchemaObject) } }
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(): UsedN...
2,597
function parseDefinedProperty(cxt: ParseCxt, key: Name, schemas: SchemaObjectMap = {}): void { const {gen} = cxt for (const prop in schemas) { gen.elseIf(_`${key} === ${prop}`) parsePropertyValue(cxt, key, schemas[prop] as SchemaObject) } }
type SchemaObjectMap = {[Ref in string]?: SchemaObject}
2,598
function parsePropertyValue(cxt: ParseCxt, key: Name, schema: SchemaObject): void { parseCode({...cxt, schema, data: _`${cxt.data}[${key}]`}) }
interface ParseCxt { readonly gen: CodeGen readonly self: Ajv // current Ajv instance readonly schemaEnv: SchemaEnv readonly definitions: SchemaObjectMap schema: SchemaObject data: Code parseName: Name char: Name }
2,599
function parsePropertyValue(cxt: ParseCxt, key: Name, schema: SchemaObject): void { parseCode({...cxt, schema, data: _`${cxt.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(): UsedN...