id
int64 0
3.78k
| code
stringlengths 13
37.9k
| declarations
stringlengths 16
64.6k
|
---|---|---|
2,200 | function addInitialSchemas(this: Ajv): void {
const optsSchemas = this.opts.schemas
if (!optsSchemas) return
if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas)
else for (const key in optsSchemas) this.addSchema(optsSchemas[key] as AnySchema, key)
} | 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,201 | function addInitialFormats(this: Ajv): void {
for (const name in this.opts.formats) {
const format = this.opts.formats[name]
if (format) this.addFormat(name, format)
}
} | 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,202 | function addInitialFormats(this: Ajv): void {
for (const name in this.opts.formats) {
const format = this.opts.formats[name]
if (format) this.addFormat(name, format)
}
} | 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,203 | function addInitialFormats(this: Ajv): void {
for (const name in this.opts.formats) {
const format = this.opts.formats[name]
if (format) this.addFormat(name, format)
}
} | 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,204 | function addInitialKeywords(
this: Ajv,
defs: Vocabulary | {[K in string]?: KeywordDefinition}
): void {
if (Array.isArray(defs)) {
this.addVocabulary(defs)
return
}
this.logger.warn("keywords option as map is deprecated, pass array")
for (const keyword in defs) {
const def = defs[keyword] as KeywordDefinition
if (!def.keyword) def.keyword = keyword
this.addKeyword(def)
}
} | 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,205 | function addInitialKeywords(
this: Ajv,
defs: Vocabulary | {[K in string]?: KeywordDefinition}
): void {
if (Array.isArray(defs)) {
this.addVocabulary(defs)
return
}
this.logger.warn("keywords option as map is deprecated, pass array")
for (const keyword in defs) {
const def = defs[keyword] as KeywordDefinition
if (!def.keyword) def.keyword = keyword
this.addKeyword(def)
}
} | 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,206 | function addInitialKeywords(
this: Ajv,
defs: Vocabulary | {[K in string]?: KeywordDefinition}
): void {
if (Array.isArray(defs)) {
this.addVocabulary(defs)
return
}
this.logger.warn("keywords option as map is deprecated, pass array")
for (const keyword in defs) {
const def = defs[keyword] as KeywordDefinition
if (!def.keyword) def.keyword = keyword
this.addKeyword(def)
}
} | 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,207 | function getMetaSchemaOptions(this: Ajv): InstanceOptions {
const metaOpts = {...this.opts}
for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]
return metaOpts
} | 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,208 | function getMetaSchemaOptions(this: Ajv): InstanceOptions {
const metaOpts = {...this.opts}
for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]
return metaOpts
} | 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,209 | function getMetaSchemaOptions(this: Ajv): InstanceOptions {
const metaOpts = {...this.opts}
for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]
return metaOpts
} | 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,210 | function checkKeyword(this: Ajv, keyword: string | string[], def?: KeywordDefinition): void {
const {RULES} = this
eachItem(keyword, (kwd) => {
if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`)
if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`)
})
if (!def) return
if (def.$data && !("code" in def || "validate" in def)) {
throw new Error('$data keyword must have "code" or "validate" function')
}
} | 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,211 | function checkKeyword(this: Ajv, keyword: string | string[], def?: KeywordDefinition): void {
const {RULES} = this
eachItem(keyword, (kwd) => {
if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`)
if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`)
})
if (!def) return
if (def.$data && !("code" in def || "validate" in def)) {
throw new Error('$data keyword must have "code" or "validate" function')
}
} | 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,212 | function checkKeyword(this: Ajv, keyword: string | string[], def?: KeywordDefinition): void {
const {RULES} = this
eachItem(keyword, (kwd) => {
if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`)
if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`)
})
if (!def) return
if (def.$data && !("code" in def || "validate" in def)) {
throw new Error('$data keyword must have "code" or "validate" function')
}
} | 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,213 | function checkKeyword(this: Ajv, keyword: string | string[], def?: KeywordDefinition): void {
const {RULES} = this
eachItem(keyword, (kwd) => {
if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`)
if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`)
})
if (!def) return
if (def.$data && !("code" in def || "validate" in def)) {
throw new Error('$data keyword must have "code" or "validate" function')
}
} | type KeywordDefinition =
| CodeKeywordDefinition
| FuncKeywordDefinition
| MacroKeywordDefinition |
2,214 | function addRule(
this: Ajv,
keyword: string,
definition?: AddedKeywordDefinition,
dataType?: JSONType
): void {
const post = definition?.post
if (dataType && post) throw new Error('keyword with "post" flag cannot have "type"')
const {RULES} = this
let ruleGroup = post ? RULES.post : RULES.rules.find(({type: t}) => t === dataType)
if (!ruleGroup) {
ruleGroup = {type: dataType, rules: []}
RULES.rules.push(ruleGroup)
}
RULES.keywords[keyword] = true
if (!definition) return
const rule: Rule = {
keyword,
definition: {
...definition,
type: getJSONTypes(definition.type),
schemaType: getJSONTypes(definition.schemaType),
},
}
if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before)
else ruleGroup.rules.push(rule)
RULES.all[keyword] = rule
definition.implements?.forEach((kwd) => this.addKeyword(kwd))
} | type AddedKeywordDefinition = KeywordDefinition & {
type: JSONType[]
schemaType: JSONType[]
} |
2,215 | function addRule(
this: Ajv,
keyword: string,
definition?: AddedKeywordDefinition,
dataType?: JSONType
): void {
const post = definition?.post
if (dataType && post) throw new Error('keyword with "post" flag cannot have "type"')
const {RULES} = this
let ruleGroup = post ? RULES.post : RULES.rules.find(({type: t}) => t === dataType)
if (!ruleGroup) {
ruleGroup = {type: dataType, rules: []}
RULES.rules.push(ruleGroup)
}
RULES.keywords[keyword] = true
if (!definition) return
const rule: Rule = {
keyword,
definition: {
...definition,
type: getJSONTypes(definition.type),
schemaType: getJSONTypes(definition.schemaType),
},
}
if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before)
else ruleGroup.rules.push(rule)
RULES.all[keyword] = rule
definition.implements?.forEach((kwd) => this.addKeyword(kwd))
} | 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,216 | function addRule(
this: Ajv,
keyword: string,
definition?: AddedKeywordDefinition,
dataType?: JSONType
): void {
const post = definition?.post
if (dataType && post) throw new Error('keyword with "post" flag cannot have "type"')
const {RULES} = this
let ruleGroup = post ? RULES.post : RULES.rules.find(({type: t}) => t === dataType)
if (!ruleGroup) {
ruleGroup = {type: dataType, rules: []}
RULES.rules.push(ruleGroup)
}
RULES.keywords[keyword] = true
if (!definition) return
const rule: Rule = {
keyword,
definition: {
...definition,
type: getJSONTypes(definition.type),
schemaType: getJSONTypes(definition.schemaType),
},
}
if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before)
else ruleGroup.rules.push(rule)
RULES.all[keyword] = rule
definition.implements?.forEach((kwd) => this.addKeyword(kwd))
} | 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,217 | function addRule(
this: Ajv,
keyword: string,
definition?: AddedKeywordDefinition,
dataType?: JSONType
): void {
const post = definition?.post
if (dataType && post) throw new Error('keyword with "post" flag cannot have "type"')
const {RULES} = this
let ruleGroup = post ? RULES.post : RULES.rules.find(({type: t}) => t === dataType)
if (!ruleGroup) {
ruleGroup = {type: dataType, rules: []}
RULES.rules.push(ruleGroup)
}
RULES.keywords[keyword] = true
if (!definition) return
const rule: Rule = {
keyword,
definition: {
...definition,
type: getJSONTypes(definition.type),
schemaType: getJSONTypes(definition.schemaType),
},
}
if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before)
else ruleGroup.rules.push(rule)
RULES.all[keyword] = rule
definition.implements?.forEach((kwd) => this.addKeyword(kwd))
} | 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,218 | function addRule(
this: Ajv,
keyword: string,
definition?: AddedKeywordDefinition,
dataType?: JSONType
): void {
const post = definition?.post
if (dataType && post) throw new Error('keyword with "post" flag cannot have "type"')
const {RULES} = this
let ruleGroup = post ? RULES.post : RULES.rules.find(({type: t}) => t === dataType)
if (!ruleGroup) {
ruleGroup = {type: dataType, rules: []}
RULES.rules.push(ruleGroup)
}
RULES.keywords[keyword] = true
if (!definition) return
const rule: Rule = {
keyword,
definition: {
...definition,
type: getJSONTypes(definition.type),
schemaType: getJSONTypes(definition.schemaType),
},
}
if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before)
else ruleGroup.rules.push(rule)
RULES.all[keyword] = rule
definition.implements?.forEach((kwd) => this.addKeyword(kwd))
} | type JSONType<T extends string, IsPartial extends boolean> = IsPartial extends true
? T | undefined
: T |
2,219 | function addRule(
this: Ajv,
keyword: string,
definition?: AddedKeywordDefinition,
dataType?: JSONType
): void {
const post = definition?.post
if (dataType && post) throw new Error('keyword with "post" flag cannot have "type"')
const {RULES} = this
let ruleGroup = post ? RULES.post : RULES.rules.find(({type: t}) => t === dataType)
if (!ruleGroup) {
ruleGroup = {type: dataType, rules: []}
RULES.rules.push(ruleGroup)
}
RULES.keywords[keyword] = true
if (!definition) return
const rule: Rule = {
keyword,
definition: {
...definition,
type: getJSONTypes(definition.type),
schemaType: getJSONTypes(definition.schemaType),
},
}
if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before)
else ruleGroup.rules.push(rule)
RULES.all[keyword] = rule
definition.implements?.forEach((kwd) => this.addKeyword(kwd))
} | type JSONType = (typeof _jsonTypes)[number] |
2,220 | function addBeforeRule(this: Ajv, ruleGroup: RuleGroup, rule: Rule, before: string): void {
const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before)
if (i >= 0) {
ruleGroup.rules.splice(i, 0, rule)
} else {
ruleGroup.rules.push(rule)
this.logger.warn(`rule ${before} is not defined`)
}
} | interface RuleGroup {
type?: JSONType
rules: Rule[]
} |
2,221 | function addBeforeRule(this: Ajv, ruleGroup: RuleGroup, rule: Rule, before: string): void {
const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before)
if (i >= 0) {
ruleGroup.rules.splice(i, 0, rule)
} else {
ruleGroup.rules.push(rule)
this.logger.warn(`rule ${before} is not defined`)
}
} | 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,222 | function addBeforeRule(this: Ajv, ruleGroup: RuleGroup, rule: Rule, before: string): void {
const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before)
if (i >= 0) {
ruleGroup.rules.splice(i, 0, rule)
} else {
ruleGroup.rules.push(rule)
this.logger.warn(`rule ${before} is not defined`)
}
} | 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,223 | function addBeforeRule(this: Ajv, ruleGroup: RuleGroup, rule: Rule, before: string): void {
const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before)
if (i >= 0) {
ruleGroup.rules.splice(i, 0, rule)
} else {
ruleGroup.rules.push(rule)
this.logger.warn(`rule ${before} is not defined`)
}
} | 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,224 | function addBeforeRule(this: Ajv, ruleGroup: RuleGroup, rule: Rule, before: string): void {
const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before)
if (i >= 0) {
ruleGroup.rules.splice(i, 0, rule)
} else {
ruleGroup.rules.push(rule)
this.logger.warn(`rule ${before} is not defined`)
}
} | interface Rule {
keyword: string
definition: AddedKeywordDefinition
} |
2,225 | function keywordMetaschema(this: Ajv, def: KeywordDefinition): void {
let {metaSchema} = def
if (metaSchema === undefined) return
if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema)
def.validateSchema = this.compile(metaSchema, true)
} | 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,226 | function keywordMetaschema(this: Ajv, def: KeywordDefinition): void {
let {metaSchema} = def
if (metaSchema === undefined) return
if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema)
def.validateSchema = this.compile(metaSchema, true)
} | 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,227 | function keywordMetaschema(this: Ajv, def: KeywordDefinition): void {
let {metaSchema} = def
if (metaSchema === undefined) return
if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema)
def.validateSchema = this.compile(metaSchema, true)
} | 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,228 | function keywordMetaschema(this: Ajv, def: KeywordDefinition): void {
let {metaSchema} = def
if (metaSchema === undefined) return
if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema)
def.validateSchema = this.compile(metaSchema, true)
} | type KeywordDefinition =
| CodeKeywordDefinition
| FuncKeywordDefinition
| MacroKeywordDefinition |
2,229 | function schemaOrData(schema: AnySchema): AnySchemaObject {
return {anyOf: [schema, $dataRef]}
} | type AnySchema = Schema | AsyncSchema |
2,230 | constructor(opts: JTDOptions = {}) {
super({
...opts,
jtd: true,
})
} | type JTDOptions = CurrentOptions & {
// strict mode options not supported with JTD:
strict?: never
allowMatchingProperties?: never
allowUnionTypes?: never
validateFormats?: never
// validation and reporting options not supported with JTD:
$data?: never
verbose?: boolean
$comment?: never
formats?: never
loadSchema?: never
// options to modify validated data:
useDefaults?: never
coerceTypes?: never
// advanced options:
next?: never
unevaluated?: never
dynamicRef?: never
meta?: boolean
defaultMeta?: never
inlineRefs?: boolean
loopRequired?: never
multipleOfPrecision?: never
} |
2,231 | compileSerializer<T = unknown>(schema: SchemaObject): (data: T) => string | interface SchemaObject extends _SchemaObject {
id?: string
$id?: string
$schema?: string
$async?: false
[x: string]: any // TODO
} |
2,232 | compileSerializer<T = unknown>(schema: SchemaObject): (data: T) => string {
const sch = this._addSchema(schema)
return sch.serialize || this._compileSerializer(sch)
} | interface SchemaObject extends _SchemaObject {
id?: string
$id?: string
$schema?: string
$async?: false
[x: string]: any // TODO
} |
2,233 | compileParser<T = unknown>(schema: SchemaObject): JTDParser<T> | interface SchemaObject extends _SchemaObject {
id?: string
$id?: string
$schema?: string
$async?: false
[x: string]: any // TODO
} |
2,234 | compileParser<T = unknown>(schema: SchemaObject): JTDParser<T> {
const sch = this._addSchema(schema)
return (sch.parse || this._compileParser(sch)) as JTDParser<T>
} | interface SchemaObject extends _SchemaObject {
id?: string
$id?: string
$schema?: string
$async?: false
[x: string]: any // TODO
} |
2,235 | 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
} | 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,236 | 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
} | 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,237 | function funcExportCode(source?: SourceCode): string {
const usedValues: UsedScopeValues = {}
const n = source?.validateName
const vCode = validateCode(usedValues, source)
if (ajv.opts.code.esm) {
// Always do named export as `validate` rather than the variable `n` which is `validateXX` for known export value
return `"use strict";${_n}export const validate = ${n};${_n}export default ${n};${_n}${vCode}`
}
return `"use strict";${_n}module.exports = ${n};${_n}module.exports.default = ${n};${_n}${vCode}`
} | interface SourceCode {
validateName: ValueScopeName
validateCode: string
scopeValues: ScopeValueSets
evaluated?: Code
} |
2,238 | function validateCode(usedValues: UsedScopeValues, s?: SourceCode): Code {
if (!s) throw new Error('moduleCode: function does not have "source" property')
if (usedState(s.validateName) === UsedValueState.Completed) return nil
setUsedState(s.validateName, UsedValueState.Started)
const scopeCode = ajv.scope.scopeCode(s.scopeValues, usedValues, refValidateCode)
const code = new _Code(`${scopeCode}${_n}${s.validateCode}`)
return s.evaluated ? _`${code}${s.validateName}.evaluated = ${s.evaluated};${_n}` : code
function refValidateCode(n: ValueScopeName): Code | undefined {
const vRef = n.value?.ref
if (n.prefix === "validate" && typeof vRef == "function") {
const v = vRef as AnyValidateFunction
return validateCode(usedValues, v.source)
} else if ((n.prefix === "root" || n.prefix === "wrapper") && typeof vRef == "object") {
const {validate, validateName} = vRef as SchemaEnv
if (!validateName) throw new Error("ajv internal error")
const def = ajv.opts.code.es5 ? varKinds.var : varKinds.const
const wrapper = _`${def} ${n} = {validate: ${validateName}};`
if (usedState(validateName) === UsedValueState.Started) return wrapper
const vCode = validateCode(usedValues, validate?.source)
return _`${wrapper}${_n}${vCode}`
}
return undefined
}
function usedState(name: ValueScopeName): UsedValueState | undefined {
return usedValues[name.prefix]?.get(name)
}
function setUsedState(name: ValueScopeName, state: UsedValueState): void {
const {prefix} = name
const names = (usedValues[prefix] = usedValues[prefix] || new Map())
names.set(name, state)
}
} | type UsedScopeValues = {
[Prefix in string]?: Map<ValueScopeName, UsedValueState | undefined>
} |
2,239 | function validateCode(usedValues: UsedScopeValues, s?: SourceCode): Code {
if (!s) throw new Error('moduleCode: function does not have "source" property')
if (usedState(s.validateName) === UsedValueState.Completed) return nil
setUsedState(s.validateName, UsedValueState.Started)
const scopeCode = ajv.scope.scopeCode(s.scopeValues, usedValues, refValidateCode)
const code = new _Code(`${scopeCode}${_n}${s.validateCode}`)
return s.evaluated ? _`${code}${s.validateName}.evaluated = ${s.evaluated};${_n}` : code
function refValidateCode(n: ValueScopeName): Code | undefined {
const vRef = n.value?.ref
if (n.prefix === "validate" && typeof vRef == "function") {
const v = vRef as AnyValidateFunction
return validateCode(usedValues, v.source)
} else if ((n.prefix === "root" || n.prefix === "wrapper") && typeof vRef == "object") {
const {validate, validateName} = vRef as SchemaEnv
if (!validateName) throw new Error("ajv internal error")
const def = ajv.opts.code.es5 ? varKinds.var : varKinds.const
const wrapper = _`${def} ${n} = {validate: ${validateName}};`
if (usedState(validateName) === UsedValueState.Started) return wrapper
const vCode = validateCode(usedValues, validate?.source)
return _`${wrapper}${_n}${vCode}`
}
return undefined
}
function usedState(name: ValueScopeName): UsedValueState | undefined {
return usedValues[name.prefix]?.get(name)
}
function setUsedState(name: ValueScopeName, state: UsedValueState): void {
const {prefix} = name
const names = (usedValues[prefix] = usedValues[prefix] || new Map())
names.set(name, state)
}
} | interface SourceCode {
validateName: ValueScopeName
validateCode: string
scopeValues: ScopeValueSets
evaluated?: Code
} |
2,240 | function refValidateCode(n: ValueScopeName): Code | undefined {
const vRef = n.value?.ref
if (n.prefix === "validate" && typeof vRef == "function") {
const v = vRef as AnyValidateFunction
return validateCode(usedValues, v.source)
} else if ((n.prefix === "root" || n.prefix === "wrapper") && typeof vRef == "object") {
const {validate, validateName} = vRef as SchemaEnv
if (!validateName) throw new Error("ajv internal error")
const def = ajv.opts.code.es5 ? varKinds.var : varKinds.const
const wrapper = _`${def} ${n} = {validate: ${validateName}};`
if (usedState(validateName) === UsedValueState.Started) return wrapper
const vCode = validateCode(usedValues, validate?.source)
return _`${wrapper}${_n}${vCode}`
}
return undefined
} | class ValueScopeName extends Name {
readonly prefix: string
value?: NameValue
scopePath?: Code
constructor(prefix: string, nameStr: string) {
super(nameStr)
this.prefix = prefix
}
setValue(value: NameValue, {property, itemIndex}: ScopePath): void {
this.value = value
this.scopePath = _`.${new Name(property)}[${itemIndex}]`
}
} |
2,241 | function usedState(name: ValueScopeName): UsedValueState | undefined {
return usedValues[name.prefix]?.get(name)
} | class ValueScopeName extends Name {
readonly prefix: string
value?: NameValue
scopePath?: Code
constructor(prefix: string, nameStr: string) {
super(nameStr)
this.prefix = prefix
}
setValue(value: NameValue, {property, itemIndex}: ScopePath): void {
this.value = value
this.scopePath = _`.${new Name(property)}[${itemIndex}]`
}
} |
2,242 | function setUsedState(name: ValueScopeName, state: UsedValueState): void {
const {prefix} = name
const names = (usedValues[prefix] = usedValues[prefix] || new Map())
names.set(name, state)
} | class ValueScopeName extends Name {
readonly prefix: string
value?: NameValue
scopePath?: Code
constructor(prefix: string, nameStr: string) {
super(nameStr)
this.prefix = prefix
}
setValue(value: NameValue, {property, itemIndex}: ScopePath): void {
this.value = value
this.scopePath = _`.${new Name(property)}[${itemIndex}]`
}
} |
2,243 | constructor(readonly ajv: Ajv) {} | 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,244 | constructor(readonly ajv: Ajv) {} | 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,245 | constructor(readonly ajv: Ajv) {} | 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,246 | compile<T = unknown>(schema: AnySchema, meta?: boolean): AnyValidateFunction<T> {
return this.getStandalone(this.ajv.compile<T>(schema, meta))
} | type AnySchema = Schema | AsyncSchema |
2,247 | function checkReportMissingProp(cxt: KeywordCxt, prop: string): void {
const {gen, data, it} = cxt
gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {
cxt.setParams({missingProperty: _`${prop}`}, true)
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,248 | function checkMissingProp(
{gen, data, it: {opts}}: KeywordCxt,
properties: string[],
missing: Name
): Code {
return or(
...properties.map((prop) =>
and(noPropertyInData(gen, data, prop, opts.ownProperties), _`${missing} = ${prop}`)
)
)
} | 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,249 | function checkMissingProp(
{gen, data, it: {opts}}: KeywordCxt,
properties: string[],
missing: Name
): Code {
return or(
...properties.map((prop) =>
and(noPropertyInData(gen, data, prop, opts.ownProperties), _`${missing} = ${prop}`)
)
)
} | 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,250 | function reportMissingProp(cxt: KeywordCxt, missing: Name): void {
cxt.setParams({missingProperty: missing}, true)
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,251 | function reportMissingProp(cxt: KeywordCxt, missing: Name): void {
cxt.setParams({missingProperty: missing}, true)
cxt.error()
} | 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,252 | function hasPropFunc(gen: CodeGen): Name {
return gen.scopeValue("func", {
// eslint-disable-next-line @typescript-eslint/unbound-method
ref: Object.prototype.hasOwnProperty,
code: _`Object.prototype.hasOwnProperty`,
})
} | class CodeGen {
readonly _scope: Scope
readonly _extScope: ValueScope
readonly _values: ScopeValueSets = {}
private readonly _nodes: ParentNode[]
private readonly _blockStarts: number[] = []
private readonly _constants: Constants = {}
private readonly opts: CGOptions
constructor(extScope: ValueScope, opts: CodeGenOptions = {}) {
this.opts = {...opts, _n: opts.lines ? "\n" : ""}
this._extScope = extScope
this._scope = new Scope({parent: extScope})
this._nodes = [new Root()]
}
toString(): string {
return this._root.render(this.opts)
}
// returns unique name in the internal scope
name(prefix: string): Name {
return this._scope.name(prefix)
}
// reserves unique name in the external scope
scopeName(prefix: string): ValueScopeName {
return this._extScope.name(prefix)
}
// reserves unique name in the external scope and assigns value to it
scopeValue(prefixOrName: ValueScopeName | string, value: NameValue): Name {
const name = this._extScope.value(prefixOrName, value)
const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set())
vs.add(name)
return name
}
getScopeValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined {
return this._extScope.getValue(prefix, keyOrRef)
}
// return code that assigns values in the external scope to the names that are used internally
// (same names that were returned by gen.scopeName or gen.scopeValue)
scopeRefs(scopeName: Name): Code {
return this._extScope.scopeRefs(scopeName, this._values)
}
scopeCode(): Code {
return this._extScope.scopeCode(this._values)
}
private _def(
varKind: Name,
nameOrPrefix: Name | string,
rhs?: SafeExpr,
constant?: boolean
): Name {
const name = this._scope.toName(nameOrPrefix)
if (rhs !== undefined && constant) this._constants[name.str] = rhs
this._leafNode(new Def(varKind, name, rhs))
return name
}
// `const` declaration (`var` in es5 mode)
const(nameOrPrefix: Name | string, rhs: SafeExpr, _constant?: boolean): Name {
return this._def(varKinds.const, nameOrPrefix, rhs, _constant)
}
// `let` declaration with optional assignment (`var` in es5 mode)
let(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name {
return this._def(varKinds.let, nameOrPrefix, rhs, _constant)
}
// `var` declaration with optional assignment
var(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name {
return this._def(varKinds.var, nameOrPrefix, rhs, _constant)
}
// assignment code
assign(lhs: Code, rhs: SafeExpr, sideEffects?: boolean): CodeGen {
return this._leafNode(new Assign(lhs, rhs, sideEffects))
}
// `+=` code
add(lhs: Code, rhs: SafeExpr): CodeGen {
return this._leafNode(new AssignOp(lhs, operators.ADD, rhs))
}
// appends passed SafeExpr to code or executes Block
code(c: Block | SafeExpr): CodeGen {
if (typeof c == "function") c()
else if (c !== nil) this._leafNode(new AnyCode(c))
return this
}
// returns code for object literal for the passed argument list of key-value pairs
object(...keyValues: [Name | string, SafeExpr | string][]): _Code {
const code: CodeItem[] = ["{"]
for (const [key, value] of keyValues) {
if (code.length > 1) code.push(",")
code.push(key)
if (key !== value || this.opts.es5) {
code.push(":")
addCodeArg(code, value)
}
}
code.push("}")
return new _Code(code)
}
// `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)
if(condition: Code | boolean, thenBody?: Block, elseBody?: Block): CodeGen {
this._blockNode(new If(condition))
if (thenBody && elseBody) {
this.code(thenBody).else().code(elseBody).endIf()
} else if (thenBody) {
this.code(thenBody).endIf()
} else if (elseBody) {
throw new Error('CodeGen: "else" body without "then" body')
}
return this
}
// `else if` clause - invalid without `if` or after `else` clauses
elseIf(condition: Code | boolean): CodeGen {
return this._elseNode(new If(condition))
}
// `else` clause - only valid after `if` or `else if` clauses
else(): CodeGen {
return this._elseNode(new Else())
}
// end `if` statement (needed if gen.if was used only with condition)
endIf(): CodeGen {
return this._endBlockNode(If, Else)
}
private _for(node: For, forBody?: Block): CodeGen {
this._blockNode(node)
if (forBody) this.code(forBody).endFor()
return this
}
// a generic `for` clause (or statement if `forBody` is passed)
for(iteration: Code, forBody?: Block): CodeGen {
return this._for(new ForLoop(iteration), forBody)
}
// `for` statement for a range of values
forRange(
nameOrPrefix: Name | string,
from: SafeExpr,
to: SafeExpr,
forBody: (index: Name) => void,
varKind: Code = this.opts.es5 ? varKinds.var : varKinds.let
): CodeGen {
const name = this._scope.toName(nameOrPrefix)
return this._for(new ForRange(varKind, name, from, to), () => forBody(name))
}
// `for-of` statement (in es5 mode replace with a normal for loop)
forOf(
nameOrPrefix: Name | string,
iterable: Code,
forBody: (item: Name) => void,
varKind: Code = varKinds.const
): CodeGen {
const name = this._scope.toName(nameOrPrefix)
if (this.opts.es5) {
const arr = iterable instanceof Name ? iterable : this.var("_arr", iterable)
return this.forRange("_i", 0, _`${arr}.length`, (i) => {
this.var(name, _`${arr}[${i}]`)
forBody(name)
})
}
return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name))
}
// `for-in` statement.
// With option `ownProperties` replaced with a `for-of` loop for object keys
forIn(
nameOrPrefix: Name | string,
obj: Code,
forBody: (item: Name) => void,
varKind: Code = this.opts.es5 ? varKinds.var : varKinds.const
): CodeGen {
if (this.opts.ownProperties) {
return this.forOf(nameOrPrefix, _`Object.keys(${obj})`, forBody)
}
const name = this._scope.toName(nameOrPrefix)
return this._for(new ForIter("in", varKind, name, obj), () => forBody(name))
}
// end `for` loop
endFor(): CodeGen {
return this._endBlockNode(For)
}
// `label` statement
label(label: Name): CodeGen {
return this._leafNode(new Label(label))
}
// `break` statement
break(label?: Code): CodeGen {
return this._leafNode(new Break(label))
}
// `return` statement
return(value: Block | SafeExpr): CodeGen {
const node = new Return()
this._blockNode(node)
this.code(value)
if (node.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node')
return this._endBlockNode(Return)
}
// `try` statement
try(tryBody: Block, catchCode?: (e: Name) => void, finallyCode?: Block): CodeGen {
if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"')
const node = new Try()
this._blockNode(node)
this.code(tryBody)
if (catchCode) {
const error = this.name("e")
this._currNode = node.catch = new Catch(error)
catchCode(error)
}
if (finallyCode) {
this._currNode = node.finally = new Finally()
this.code(finallyCode)
}
return this._endBlockNode(Catch, Finally)
}
// `throw` statement
throw(error: Code): CodeGen {
return this._leafNode(new Throw(error))
}
// start self-balancing block
block(body?: Block, nodeCount?: number): CodeGen {
this._blockStarts.push(this._nodes.length)
if (body) this.code(body).endBlock(nodeCount)
return this
}
// end the current self-balancing block
endBlock(nodeCount?: number): CodeGen {
const len = this._blockStarts.pop()
if (len === undefined) throw new Error("CodeGen: not in self-balancing block")
const toClose = this._nodes.length - len
if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) {
throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`)
}
this._nodes.length = len
return this
}
// `function` heading (or definition if funcBody is passed)
func(name: Name, args: Code = nil, async?: boolean, funcBody?: Block): CodeGen {
this._blockNode(new Func(name, args, async))
if (funcBody) this.code(funcBody).endFunc()
return this
}
// end function definition
endFunc(): CodeGen {
return this._endBlockNode(Func)
}
optimize(n = 1): void {
while (n-- > 0) {
this._root.optimizeNodes()
this._root.optimizeNames(this._root.names, this._constants)
}
}
private _leafNode(node: LeafNode): CodeGen {
this._currNode.nodes.push(node)
return this
}
private _blockNode(node: StartBlockNode): void {
this._currNode.nodes.push(node)
this._nodes.push(node)
}
private _endBlockNode(N1: EndBlockNodeType, N2?: EndBlockNodeType): CodeGen {
const n = this._currNode
if (n instanceof N1 || (N2 && n instanceof N2)) {
this._nodes.pop()
return this
}
throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`)
}
private _elseNode(node: If | Else): CodeGen {
const n = this._currNode
if (!(n instanceof If)) {
throw new Error('CodeGen: "else" without "if"')
}
this._currNode = n.else = node
return this
}
private get _root(): Root {
return this._nodes[0] as Root
}
private get _currNode(): ParentNode {
const ns = this._nodes
return ns[ns.length - 1]
}
private set _currNode(node: ParentNode) {
const ns = this._nodes
ns[ns.length - 1] = node
}
// get nodeCount(): number {
// return this._root.count
// }
} |
2,253 | function isOwnProperty(gen: CodeGen, data: Name, property: Name | string): Code {
return _`${hasPropFunc(gen)}.call(${data}, ${property})`
} | 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,254 | function isOwnProperty(gen: CodeGen, data: Name, property: Name | string): Code {
return _`${hasPropFunc(gen)}.call(${data}, ${property})`
} | class CodeGen {
readonly _scope: Scope
readonly _extScope: ValueScope
readonly _values: ScopeValueSets = {}
private readonly _nodes: ParentNode[]
private readonly _blockStarts: number[] = []
private readonly _constants: Constants = {}
private readonly opts: CGOptions
constructor(extScope: ValueScope, opts: CodeGenOptions = {}) {
this.opts = {...opts, _n: opts.lines ? "\n" : ""}
this._extScope = extScope
this._scope = new Scope({parent: extScope})
this._nodes = [new Root()]
}
toString(): string {
return this._root.render(this.opts)
}
// returns unique name in the internal scope
name(prefix: string): Name {
return this._scope.name(prefix)
}
// reserves unique name in the external scope
scopeName(prefix: string): ValueScopeName {
return this._extScope.name(prefix)
}
// reserves unique name in the external scope and assigns value to it
scopeValue(prefixOrName: ValueScopeName | string, value: NameValue): Name {
const name = this._extScope.value(prefixOrName, value)
const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set())
vs.add(name)
return name
}
getScopeValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined {
return this._extScope.getValue(prefix, keyOrRef)
}
// return code that assigns values in the external scope to the names that are used internally
// (same names that were returned by gen.scopeName or gen.scopeValue)
scopeRefs(scopeName: Name): Code {
return this._extScope.scopeRefs(scopeName, this._values)
}
scopeCode(): Code {
return this._extScope.scopeCode(this._values)
}
private _def(
varKind: Name,
nameOrPrefix: Name | string,
rhs?: SafeExpr,
constant?: boolean
): Name {
const name = this._scope.toName(nameOrPrefix)
if (rhs !== undefined && constant) this._constants[name.str] = rhs
this._leafNode(new Def(varKind, name, rhs))
return name
}
// `const` declaration (`var` in es5 mode)
const(nameOrPrefix: Name | string, rhs: SafeExpr, _constant?: boolean): Name {
return this._def(varKinds.const, nameOrPrefix, rhs, _constant)
}
// `let` declaration with optional assignment (`var` in es5 mode)
let(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name {
return this._def(varKinds.let, nameOrPrefix, rhs, _constant)
}
// `var` declaration with optional assignment
var(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name {
return this._def(varKinds.var, nameOrPrefix, rhs, _constant)
}
// assignment code
assign(lhs: Code, rhs: SafeExpr, sideEffects?: boolean): CodeGen {
return this._leafNode(new Assign(lhs, rhs, sideEffects))
}
// `+=` code
add(lhs: Code, rhs: SafeExpr): CodeGen {
return this._leafNode(new AssignOp(lhs, operators.ADD, rhs))
}
// appends passed SafeExpr to code or executes Block
code(c: Block | SafeExpr): CodeGen {
if (typeof c == "function") c()
else if (c !== nil) this._leafNode(new AnyCode(c))
return this
}
// returns code for object literal for the passed argument list of key-value pairs
object(...keyValues: [Name | string, SafeExpr | string][]): _Code {
const code: CodeItem[] = ["{"]
for (const [key, value] of keyValues) {
if (code.length > 1) code.push(",")
code.push(key)
if (key !== value || this.opts.es5) {
code.push(":")
addCodeArg(code, value)
}
}
code.push("}")
return new _Code(code)
}
// `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)
if(condition: Code | boolean, thenBody?: Block, elseBody?: Block): CodeGen {
this._blockNode(new If(condition))
if (thenBody && elseBody) {
this.code(thenBody).else().code(elseBody).endIf()
} else if (thenBody) {
this.code(thenBody).endIf()
} else if (elseBody) {
throw new Error('CodeGen: "else" body without "then" body')
}
return this
}
// `else if` clause - invalid without `if` or after `else` clauses
elseIf(condition: Code | boolean): CodeGen {
return this._elseNode(new If(condition))
}
// `else` clause - only valid after `if` or `else if` clauses
else(): CodeGen {
return this._elseNode(new Else())
}
// end `if` statement (needed if gen.if was used only with condition)
endIf(): CodeGen {
return this._endBlockNode(If, Else)
}
private _for(node: For, forBody?: Block): CodeGen {
this._blockNode(node)
if (forBody) this.code(forBody).endFor()
return this
}
// a generic `for` clause (or statement if `forBody` is passed)
for(iteration: Code, forBody?: Block): CodeGen {
return this._for(new ForLoop(iteration), forBody)
}
// `for` statement for a range of values
forRange(
nameOrPrefix: Name | string,
from: SafeExpr,
to: SafeExpr,
forBody: (index: Name) => void,
varKind: Code = this.opts.es5 ? varKinds.var : varKinds.let
): CodeGen {
const name = this._scope.toName(nameOrPrefix)
return this._for(new ForRange(varKind, name, from, to), () => forBody(name))
}
// `for-of` statement (in es5 mode replace with a normal for loop)
forOf(
nameOrPrefix: Name | string,
iterable: Code,
forBody: (item: Name) => void,
varKind: Code = varKinds.const
): CodeGen {
const name = this._scope.toName(nameOrPrefix)
if (this.opts.es5) {
const arr = iterable instanceof Name ? iterable : this.var("_arr", iterable)
return this.forRange("_i", 0, _`${arr}.length`, (i) => {
this.var(name, _`${arr}[${i}]`)
forBody(name)
})
}
return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name))
}
// `for-in` statement.
// With option `ownProperties` replaced with a `for-of` loop for object keys
forIn(
nameOrPrefix: Name | string,
obj: Code,
forBody: (item: Name) => void,
varKind: Code = this.opts.es5 ? varKinds.var : varKinds.const
): CodeGen {
if (this.opts.ownProperties) {
return this.forOf(nameOrPrefix, _`Object.keys(${obj})`, forBody)
}
const name = this._scope.toName(nameOrPrefix)
return this._for(new ForIter("in", varKind, name, obj), () => forBody(name))
}
// end `for` loop
endFor(): CodeGen {
return this._endBlockNode(For)
}
// `label` statement
label(label: Name): CodeGen {
return this._leafNode(new Label(label))
}
// `break` statement
break(label?: Code): CodeGen {
return this._leafNode(new Break(label))
}
// `return` statement
return(value: Block | SafeExpr): CodeGen {
const node = new Return()
this._blockNode(node)
this.code(value)
if (node.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node')
return this._endBlockNode(Return)
}
// `try` statement
try(tryBody: Block, catchCode?: (e: Name) => void, finallyCode?: Block): CodeGen {
if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"')
const node = new Try()
this._blockNode(node)
this.code(tryBody)
if (catchCode) {
const error = this.name("e")
this._currNode = node.catch = new Catch(error)
catchCode(error)
}
if (finallyCode) {
this._currNode = node.finally = new Finally()
this.code(finallyCode)
}
return this._endBlockNode(Catch, Finally)
}
// `throw` statement
throw(error: Code): CodeGen {
return this._leafNode(new Throw(error))
}
// start self-balancing block
block(body?: Block, nodeCount?: number): CodeGen {
this._blockStarts.push(this._nodes.length)
if (body) this.code(body).endBlock(nodeCount)
return this
}
// end the current self-balancing block
endBlock(nodeCount?: number): CodeGen {
const len = this._blockStarts.pop()
if (len === undefined) throw new Error("CodeGen: not in self-balancing block")
const toClose = this._nodes.length - len
if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) {
throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`)
}
this._nodes.length = len
return this
}
// `function` heading (or definition if funcBody is passed)
func(name: Name, args: Code = nil, async?: boolean, funcBody?: Block): CodeGen {
this._blockNode(new Func(name, args, async))
if (funcBody) this.code(funcBody).endFunc()
return this
}
// end function definition
endFunc(): CodeGen {
return this._endBlockNode(Func)
}
optimize(n = 1): void {
while (n-- > 0) {
this._root.optimizeNodes()
this._root.optimizeNames(this._root.names, this._constants)
}
}
private _leafNode(node: LeafNode): CodeGen {
this._currNode.nodes.push(node)
return this
}
private _blockNode(node: StartBlockNode): void {
this._currNode.nodes.push(node)
this._nodes.push(node)
}
private _endBlockNode(N1: EndBlockNodeType, N2?: EndBlockNodeType): CodeGen {
const n = this._currNode
if (n instanceof N1 || (N2 && n instanceof N2)) {
this._nodes.pop()
return this
}
throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`)
}
private _elseNode(node: If | Else): CodeGen {
const n = this._currNode
if (!(n instanceof If)) {
throw new Error('CodeGen: "else" without "if"')
}
this._currNode = n.else = node
return this
}
private get _root(): Root {
return this._nodes[0] as Root
}
private get _currNode(): ParentNode {
const ns = this._nodes
return ns[ns.length - 1]
}
private set _currNode(node: ParentNode) {
const ns = this._nodes
ns[ns.length - 1] = node
}
// get nodeCount(): number {
// return this._root.count
// }
} |
2,255 | function propertyInData(
gen: CodeGen,
data: Name,
property: Name | string,
ownProperties?: boolean
): Code {
const cond = _`${data}${getProperty(property)} !== undefined`
return ownProperties ? _`${cond} && ${isOwnProperty(gen, data, property)}` : cond
} | 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,256 | function propertyInData(
gen: CodeGen,
data: Name,
property: Name | string,
ownProperties?: boolean
): Code {
const cond = _`${data}${getProperty(property)} !== undefined`
return ownProperties ? _`${cond} && ${isOwnProperty(gen, data, property)}` : cond
} | class CodeGen {
readonly _scope: Scope
readonly _extScope: ValueScope
readonly _values: ScopeValueSets = {}
private readonly _nodes: ParentNode[]
private readonly _blockStarts: number[] = []
private readonly _constants: Constants = {}
private readonly opts: CGOptions
constructor(extScope: ValueScope, opts: CodeGenOptions = {}) {
this.opts = {...opts, _n: opts.lines ? "\n" : ""}
this._extScope = extScope
this._scope = new Scope({parent: extScope})
this._nodes = [new Root()]
}
toString(): string {
return this._root.render(this.opts)
}
// returns unique name in the internal scope
name(prefix: string): Name {
return this._scope.name(prefix)
}
// reserves unique name in the external scope
scopeName(prefix: string): ValueScopeName {
return this._extScope.name(prefix)
}
// reserves unique name in the external scope and assigns value to it
scopeValue(prefixOrName: ValueScopeName | string, value: NameValue): Name {
const name = this._extScope.value(prefixOrName, value)
const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set())
vs.add(name)
return name
}
getScopeValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined {
return this._extScope.getValue(prefix, keyOrRef)
}
// return code that assigns values in the external scope to the names that are used internally
// (same names that were returned by gen.scopeName or gen.scopeValue)
scopeRefs(scopeName: Name): Code {
return this._extScope.scopeRefs(scopeName, this._values)
}
scopeCode(): Code {
return this._extScope.scopeCode(this._values)
}
private _def(
varKind: Name,
nameOrPrefix: Name | string,
rhs?: SafeExpr,
constant?: boolean
): Name {
const name = this._scope.toName(nameOrPrefix)
if (rhs !== undefined && constant) this._constants[name.str] = rhs
this._leafNode(new Def(varKind, name, rhs))
return name
}
// `const` declaration (`var` in es5 mode)
const(nameOrPrefix: Name | string, rhs: SafeExpr, _constant?: boolean): Name {
return this._def(varKinds.const, nameOrPrefix, rhs, _constant)
}
// `let` declaration with optional assignment (`var` in es5 mode)
let(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name {
return this._def(varKinds.let, nameOrPrefix, rhs, _constant)
}
// `var` declaration with optional assignment
var(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name {
return this._def(varKinds.var, nameOrPrefix, rhs, _constant)
}
// assignment code
assign(lhs: Code, rhs: SafeExpr, sideEffects?: boolean): CodeGen {
return this._leafNode(new Assign(lhs, rhs, sideEffects))
}
// `+=` code
add(lhs: Code, rhs: SafeExpr): CodeGen {
return this._leafNode(new AssignOp(lhs, operators.ADD, rhs))
}
// appends passed SafeExpr to code or executes Block
code(c: Block | SafeExpr): CodeGen {
if (typeof c == "function") c()
else if (c !== nil) this._leafNode(new AnyCode(c))
return this
}
// returns code for object literal for the passed argument list of key-value pairs
object(...keyValues: [Name | string, SafeExpr | string][]): _Code {
const code: CodeItem[] = ["{"]
for (const [key, value] of keyValues) {
if (code.length > 1) code.push(",")
code.push(key)
if (key !== value || this.opts.es5) {
code.push(":")
addCodeArg(code, value)
}
}
code.push("}")
return new _Code(code)
}
// `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)
if(condition: Code | boolean, thenBody?: Block, elseBody?: Block): CodeGen {
this._blockNode(new If(condition))
if (thenBody && elseBody) {
this.code(thenBody).else().code(elseBody).endIf()
} else if (thenBody) {
this.code(thenBody).endIf()
} else if (elseBody) {
throw new Error('CodeGen: "else" body without "then" body')
}
return this
}
// `else if` clause - invalid without `if` or after `else` clauses
elseIf(condition: Code | boolean): CodeGen {
return this._elseNode(new If(condition))
}
// `else` clause - only valid after `if` or `else if` clauses
else(): CodeGen {
return this._elseNode(new Else())
}
// end `if` statement (needed if gen.if was used only with condition)
endIf(): CodeGen {
return this._endBlockNode(If, Else)
}
private _for(node: For, forBody?: Block): CodeGen {
this._blockNode(node)
if (forBody) this.code(forBody).endFor()
return this
}
// a generic `for` clause (or statement if `forBody` is passed)
for(iteration: Code, forBody?: Block): CodeGen {
return this._for(new ForLoop(iteration), forBody)
}
// `for` statement for a range of values
forRange(
nameOrPrefix: Name | string,
from: SafeExpr,
to: SafeExpr,
forBody: (index: Name) => void,
varKind: Code = this.opts.es5 ? varKinds.var : varKinds.let
): CodeGen {
const name = this._scope.toName(nameOrPrefix)
return this._for(new ForRange(varKind, name, from, to), () => forBody(name))
}
// `for-of` statement (in es5 mode replace with a normal for loop)
forOf(
nameOrPrefix: Name | string,
iterable: Code,
forBody: (item: Name) => void,
varKind: Code = varKinds.const
): CodeGen {
const name = this._scope.toName(nameOrPrefix)
if (this.opts.es5) {
const arr = iterable instanceof Name ? iterable : this.var("_arr", iterable)
return this.forRange("_i", 0, _`${arr}.length`, (i) => {
this.var(name, _`${arr}[${i}]`)
forBody(name)
})
}
return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name))
}
// `for-in` statement.
// With option `ownProperties` replaced with a `for-of` loop for object keys
forIn(
nameOrPrefix: Name | string,
obj: Code,
forBody: (item: Name) => void,
varKind: Code = this.opts.es5 ? varKinds.var : varKinds.const
): CodeGen {
if (this.opts.ownProperties) {
return this.forOf(nameOrPrefix, _`Object.keys(${obj})`, forBody)
}
const name = this._scope.toName(nameOrPrefix)
return this._for(new ForIter("in", varKind, name, obj), () => forBody(name))
}
// end `for` loop
endFor(): CodeGen {
return this._endBlockNode(For)
}
// `label` statement
label(label: Name): CodeGen {
return this._leafNode(new Label(label))
}
// `break` statement
break(label?: Code): CodeGen {
return this._leafNode(new Break(label))
}
// `return` statement
return(value: Block | SafeExpr): CodeGen {
const node = new Return()
this._blockNode(node)
this.code(value)
if (node.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node')
return this._endBlockNode(Return)
}
// `try` statement
try(tryBody: Block, catchCode?: (e: Name) => void, finallyCode?: Block): CodeGen {
if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"')
const node = new Try()
this._blockNode(node)
this.code(tryBody)
if (catchCode) {
const error = this.name("e")
this._currNode = node.catch = new Catch(error)
catchCode(error)
}
if (finallyCode) {
this._currNode = node.finally = new Finally()
this.code(finallyCode)
}
return this._endBlockNode(Catch, Finally)
}
// `throw` statement
throw(error: Code): CodeGen {
return this._leafNode(new Throw(error))
}
// start self-balancing block
block(body?: Block, nodeCount?: number): CodeGen {
this._blockStarts.push(this._nodes.length)
if (body) this.code(body).endBlock(nodeCount)
return this
}
// end the current self-balancing block
endBlock(nodeCount?: number): CodeGen {
const len = this._blockStarts.pop()
if (len === undefined) throw new Error("CodeGen: not in self-balancing block")
const toClose = this._nodes.length - len
if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) {
throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`)
}
this._nodes.length = len
return this
}
// `function` heading (or definition if funcBody is passed)
func(name: Name, args: Code = nil, async?: boolean, funcBody?: Block): CodeGen {
this._blockNode(new Func(name, args, async))
if (funcBody) this.code(funcBody).endFunc()
return this
}
// end function definition
endFunc(): CodeGen {
return this._endBlockNode(Func)
}
optimize(n = 1): void {
while (n-- > 0) {
this._root.optimizeNodes()
this._root.optimizeNames(this._root.names, this._constants)
}
}
private _leafNode(node: LeafNode): CodeGen {
this._currNode.nodes.push(node)
return this
}
private _blockNode(node: StartBlockNode): void {
this._currNode.nodes.push(node)
this._nodes.push(node)
}
private _endBlockNode(N1: EndBlockNodeType, N2?: EndBlockNodeType): CodeGen {
const n = this._currNode
if (n instanceof N1 || (N2 && n instanceof N2)) {
this._nodes.pop()
return this
}
throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`)
}
private _elseNode(node: If | Else): CodeGen {
const n = this._currNode
if (!(n instanceof If)) {
throw new Error('CodeGen: "else" without "if"')
}
this._currNode = n.else = node
return this
}
private get _root(): Root {
return this._nodes[0] as Root
}
private get _currNode(): ParentNode {
const ns = this._nodes
return ns[ns.length - 1]
}
private set _currNode(node: ParentNode) {
const ns = this._nodes
ns[ns.length - 1] = node
}
// get nodeCount(): number {
// return this._root.count
// }
} |
2,257 | function noPropertyInData(
gen: CodeGen,
data: Name,
property: Name | string,
ownProperties?: boolean
): Code {
const cond = _`${data}${getProperty(property)} === undefined`
return ownProperties ? or(cond, not(isOwnProperty(gen, data, property))) : cond
} | 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,258 | function noPropertyInData(
gen: CodeGen,
data: Name,
property: Name | string,
ownProperties?: boolean
): Code {
const cond = _`${data}${getProperty(property)} === undefined`
return ownProperties ? or(cond, not(isOwnProperty(gen, data, property))) : cond
} | class CodeGen {
readonly _scope: Scope
readonly _extScope: ValueScope
readonly _values: ScopeValueSets = {}
private readonly _nodes: ParentNode[]
private readonly _blockStarts: number[] = []
private readonly _constants: Constants = {}
private readonly opts: CGOptions
constructor(extScope: ValueScope, opts: CodeGenOptions = {}) {
this.opts = {...opts, _n: opts.lines ? "\n" : ""}
this._extScope = extScope
this._scope = new Scope({parent: extScope})
this._nodes = [new Root()]
}
toString(): string {
return this._root.render(this.opts)
}
// returns unique name in the internal scope
name(prefix: string): Name {
return this._scope.name(prefix)
}
// reserves unique name in the external scope
scopeName(prefix: string): ValueScopeName {
return this._extScope.name(prefix)
}
// reserves unique name in the external scope and assigns value to it
scopeValue(prefixOrName: ValueScopeName | string, value: NameValue): Name {
const name = this._extScope.value(prefixOrName, value)
const vs = this._values[name.prefix] || (this._values[name.prefix] = new Set())
vs.add(name)
return name
}
getScopeValue(prefix: string, keyOrRef: unknown): ValueScopeName | undefined {
return this._extScope.getValue(prefix, keyOrRef)
}
// return code that assigns values in the external scope to the names that are used internally
// (same names that were returned by gen.scopeName or gen.scopeValue)
scopeRefs(scopeName: Name): Code {
return this._extScope.scopeRefs(scopeName, this._values)
}
scopeCode(): Code {
return this._extScope.scopeCode(this._values)
}
private _def(
varKind: Name,
nameOrPrefix: Name | string,
rhs?: SafeExpr,
constant?: boolean
): Name {
const name = this._scope.toName(nameOrPrefix)
if (rhs !== undefined && constant) this._constants[name.str] = rhs
this._leafNode(new Def(varKind, name, rhs))
return name
}
// `const` declaration (`var` in es5 mode)
const(nameOrPrefix: Name | string, rhs: SafeExpr, _constant?: boolean): Name {
return this._def(varKinds.const, nameOrPrefix, rhs, _constant)
}
// `let` declaration with optional assignment (`var` in es5 mode)
let(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name {
return this._def(varKinds.let, nameOrPrefix, rhs, _constant)
}
// `var` declaration with optional assignment
var(nameOrPrefix: Name | string, rhs?: SafeExpr, _constant?: boolean): Name {
return this._def(varKinds.var, nameOrPrefix, rhs, _constant)
}
// assignment code
assign(lhs: Code, rhs: SafeExpr, sideEffects?: boolean): CodeGen {
return this._leafNode(new Assign(lhs, rhs, sideEffects))
}
// `+=` code
add(lhs: Code, rhs: SafeExpr): CodeGen {
return this._leafNode(new AssignOp(lhs, operators.ADD, rhs))
}
// appends passed SafeExpr to code or executes Block
code(c: Block | SafeExpr): CodeGen {
if (typeof c == "function") c()
else if (c !== nil) this._leafNode(new AnyCode(c))
return this
}
// returns code for object literal for the passed argument list of key-value pairs
object(...keyValues: [Name | string, SafeExpr | string][]): _Code {
const code: CodeItem[] = ["{"]
for (const [key, value] of keyValues) {
if (code.length > 1) code.push(",")
code.push(key)
if (key !== value || this.opts.es5) {
code.push(":")
addCodeArg(code, value)
}
}
code.push("}")
return new _Code(code)
}
// `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)
if(condition: Code | boolean, thenBody?: Block, elseBody?: Block): CodeGen {
this._blockNode(new If(condition))
if (thenBody && elseBody) {
this.code(thenBody).else().code(elseBody).endIf()
} else if (thenBody) {
this.code(thenBody).endIf()
} else if (elseBody) {
throw new Error('CodeGen: "else" body without "then" body')
}
return this
}
// `else if` clause - invalid without `if` or after `else` clauses
elseIf(condition: Code | boolean): CodeGen {
return this._elseNode(new If(condition))
}
// `else` clause - only valid after `if` or `else if` clauses
else(): CodeGen {
return this._elseNode(new Else())
}
// end `if` statement (needed if gen.if was used only with condition)
endIf(): CodeGen {
return this._endBlockNode(If, Else)
}
private _for(node: For, forBody?: Block): CodeGen {
this._blockNode(node)
if (forBody) this.code(forBody).endFor()
return this
}
// a generic `for` clause (or statement if `forBody` is passed)
for(iteration: Code, forBody?: Block): CodeGen {
return this._for(new ForLoop(iteration), forBody)
}
// `for` statement for a range of values
forRange(
nameOrPrefix: Name | string,
from: SafeExpr,
to: SafeExpr,
forBody: (index: Name) => void,
varKind: Code = this.opts.es5 ? varKinds.var : varKinds.let
): CodeGen {
const name = this._scope.toName(nameOrPrefix)
return this._for(new ForRange(varKind, name, from, to), () => forBody(name))
}
// `for-of` statement (in es5 mode replace with a normal for loop)
forOf(
nameOrPrefix: Name | string,
iterable: Code,
forBody: (item: Name) => void,
varKind: Code = varKinds.const
): CodeGen {
const name = this._scope.toName(nameOrPrefix)
if (this.opts.es5) {
const arr = iterable instanceof Name ? iterable : this.var("_arr", iterable)
return this.forRange("_i", 0, _`${arr}.length`, (i) => {
this.var(name, _`${arr}[${i}]`)
forBody(name)
})
}
return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name))
}
// `for-in` statement.
// With option `ownProperties` replaced with a `for-of` loop for object keys
forIn(
nameOrPrefix: Name | string,
obj: Code,
forBody: (item: Name) => void,
varKind: Code = this.opts.es5 ? varKinds.var : varKinds.const
): CodeGen {
if (this.opts.ownProperties) {
return this.forOf(nameOrPrefix, _`Object.keys(${obj})`, forBody)
}
const name = this._scope.toName(nameOrPrefix)
return this._for(new ForIter("in", varKind, name, obj), () => forBody(name))
}
// end `for` loop
endFor(): CodeGen {
return this._endBlockNode(For)
}
// `label` statement
label(label: Name): CodeGen {
return this._leafNode(new Label(label))
}
// `break` statement
break(label?: Code): CodeGen {
return this._leafNode(new Break(label))
}
// `return` statement
return(value: Block | SafeExpr): CodeGen {
const node = new Return()
this._blockNode(node)
this.code(value)
if (node.nodes.length !== 1) throw new Error('CodeGen: "return" should have one node')
return this._endBlockNode(Return)
}
// `try` statement
try(tryBody: Block, catchCode?: (e: Name) => void, finallyCode?: Block): CodeGen {
if (!catchCode && !finallyCode) throw new Error('CodeGen: "try" without "catch" and "finally"')
const node = new Try()
this._blockNode(node)
this.code(tryBody)
if (catchCode) {
const error = this.name("e")
this._currNode = node.catch = new Catch(error)
catchCode(error)
}
if (finallyCode) {
this._currNode = node.finally = new Finally()
this.code(finallyCode)
}
return this._endBlockNode(Catch, Finally)
}
// `throw` statement
throw(error: Code): CodeGen {
return this._leafNode(new Throw(error))
}
// start self-balancing block
block(body?: Block, nodeCount?: number): CodeGen {
this._blockStarts.push(this._nodes.length)
if (body) this.code(body).endBlock(nodeCount)
return this
}
// end the current self-balancing block
endBlock(nodeCount?: number): CodeGen {
const len = this._blockStarts.pop()
if (len === undefined) throw new Error("CodeGen: not in self-balancing block")
const toClose = this._nodes.length - len
if (toClose < 0 || (nodeCount !== undefined && toClose !== nodeCount)) {
throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`)
}
this._nodes.length = len
return this
}
// `function` heading (or definition if funcBody is passed)
func(name: Name, args: Code = nil, async?: boolean, funcBody?: Block): CodeGen {
this._blockNode(new Func(name, args, async))
if (funcBody) this.code(funcBody).endFunc()
return this
}
// end function definition
endFunc(): CodeGen {
return this._endBlockNode(Func)
}
optimize(n = 1): void {
while (n-- > 0) {
this._root.optimizeNodes()
this._root.optimizeNames(this._root.names, this._constants)
}
}
private _leafNode(node: LeafNode): CodeGen {
this._currNode.nodes.push(node)
return this
}
private _blockNode(node: StartBlockNode): void {
this._currNode.nodes.push(node)
this._nodes.push(node)
}
private _endBlockNode(N1: EndBlockNodeType, N2?: EndBlockNodeType): CodeGen {
const n = this._currNode
if (n instanceof N1 || (N2 && n instanceof N2)) {
this._nodes.pop()
return this
}
throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.kind}"`)
}
private _elseNode(node: If | Else): CodeGen {
const n = this._currNode
if (!(n instanceof If)) {
throw new Error('CodeGen: "else" without "if"')
}
this._currNode = n.else = node
return this
}
private get _root(): Root {
return this._nodes[0] as Root
}
private get _currNode(): ParentNode {
const ns = this._nodes
return ns[ns.length - 1]
}
private set _currNode(node: ParentNode) {
const ns = this._nodes
ns[ns.length - 1] = node
}
// get nodeCount(): number {
// return this._root.count
// }
} |
2,259 | function allSchemaProperties(schemaMap?: SchemaMap): string[] {
return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : []
} | type SchemaMap = {[Key in string]?: AnySchema} |
2,260 | function schemaProperties(it: SchemaCxt, schemaMap: SchemaMap): string[] {
return allSchemaProperties(schemaMap).filter(
(p) => !alwaysValidSchema(it, schemaMap[p] as AnySchema)
)
} | 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 parentDataProperty: Code | number // should be used in keywords modifying data
readonly dataNames: Name[]
readonly dataPathArr: (Code | number)[]
readonly dataLevel: number // the level of the currently validated data,
// it can be used to access both the property names and the data on all levels from the top.
dataTypes: JSONType[] // data types applied to the current part of data instance
definedProperties: Set<string> // set of properties to keep track of for required checks
readonly topSchemaRef: Code
readonly validateName: Name
evaluated?: Name
readonly ValidationError?: Name
readonly schema: AnySchema // current schema object - equal to parentSchema passed via KeywordCxt
readonly schemaEnv: SchemaEnv
readonly rootId: string
baseId: string // the current schema base URI that should be used as the base for resolving URIs in references (\$ref)
readonly schemaPath: Code // the run-time expression that evaluates to the property name of the current schema
readonly errSchemaPath: string // this is actual string, should not be changed to Code
readonly errorPath: Code
readonly propertyName?: Name
readonly compositeRule?: boolean // true indicates that the current schema is inside the compound keyword,
// where failing some rule doesn't mean validation failure (`anyOf`, `oneOf`, `not`, `if`).
// This flag is used to determine whether you can return validation result immediately after any error in case the option `allErrors` is not `true.
// You only need to use it if you have many steps in your keywords and potentially can define multiple errors.
props?: EvaluatedProperties | Name // properties evaluated by this schema - used by parent schema or assigned to validation function
items?: EvaluatedItems | Name // last item evaluated by this schema - used by parent schema or assigned to validation function
jtdDiscriminator?: string
jtdMetadata?: boolean
readonly createErrors?: boolean
readonly opts: InstanceOptions // Ajv instance option.
readonly self: Ajv // current Ajv instance
} |
2,261 | function schemaProperties(it: SchemaCxt, schemaMap: SchemaMap): string[] {
return allSchemaProperties(schemaMap).filter(
(p) => !alwaysValidSchema(it, schemaMap[p] as AnySchema)
)
} | type SchemaMap = {[Key in string]?: AnySchema} |
2,262 | function callValidateCode(
{schemaCode, data, it: {gen, topSchemaRef, schemaPath, errorPath}, it}: KeywordCxt,
func: Code,
context: Code,
passSchema?: boolean
): Code {
const dataAndSchema = passSchema ? _`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data
const valCxt: [Name, Code | number][] = [
[N.instancePath, strConcat(N.instancePath, errorPath)],
[N.parentData, it.parentData],
[N.parentDataProperty, it.parentDataProperty],
[N.rootData, N.rootData],
]
if (it.opts.dynamicRef) valCxt.push([N.dynamicAnchors, N.dynamicAnchors])
const args = _`${dataAndSchema}, ${gen.object(...valCxt)}`
return context !== nil ? _`${func}.call(${context}, ${args})` : _`${func}(${args})`
} | 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,263 | function callValidateCode(
{schemaCode, data, it: {gen, topSchemaRef, schemaPath, errorPath}, it}: KeywordCxt,
func: Code,
context: Code,
passSchema?: boolean
): Code {
const dataAndSchema = passSchema ? _`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data
const valCxt: [Name, Code | number][] = [
[N.instancePath, strConcat(N.instancePath, errorPath)],
[N.parentData, it.parentData],
[N.parentDataProperty, it.parentDataProperty],
[N.rootData, N.rootData],
]
if (it.opts.dynamicRef) valCxt.push([N.dynamicAnchors, N.dynamicAnchors])
const args = _`${dataAndSchema}, ${gen.object(...valCxt)}`
return context !== nil ? _`${func}.call(${context}, ${args})` : _`${func}(${args})`
} | type Code = _Code | Name |
2,264 | function usePattern({gen, it: {opts}}: KeywordCxt, pattern: string): Name {
const u = opts.unicodeRegExp ? "u" : ""
const {regExp} = opts.code
const rx = regExp(pattern, u)
return gen.scopeValue("pattern", {
key: rx.toString(),
ref: rx,
code: _`${regExp.code === "new RegExp" ? newRegExp : useFunc(gen, regExp)}(${pattern}, ${u})`,
})
} | 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,265 | function validateArray(cxt: KeywordCxt): Name {
const {gen, data, keyword, it} = cxt
const valid = gen.name("valid")
if (it.allErrors) {
const validArr = gen.let("valid", true)
validateItems(() => gen.assign(validArr, false))
return validArr
}
gen.var(valid, true)
validateItems(() => gen.break())
return valid
function validateItems(notValid: () => void): void {
const len = gen.const("len", _`${data}.length`)
gen.forRange("i", 0, len, (i) => {
cxt.subschema(
{
keyword,
dataProp: i,
dataPropType: Type.Num,
},
valid
)
gen.if(not(valid), notValid)
})
}
} | 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,266 | function validateUnion(cxt: KeywordCxt): void {
const {gen, schema, keyword, it} = cxt
/* istanbul ignore if */
if (!Array.isArray(schema)) throw new Error("ajv implementation error")
const alwaysValid = schema.some((sch: AnySchema) => alwaysValidSchema(it, sch))
if (alwaysValid && !it.opts.unevaluated) return
const valid = gen.let("valid", false)
const schValid = gen.name("_valid")
gen.block(() =>
schema.forEach((_sch: AnySchema, i: number) => {
const schCxt = cxt.subschema(
{
keyword,
schemaProp: i,
compositeRule: true,
},
schValid
)
gen.assign(valid, _`${valid} || ${schValid}`)
const merged = cxt.mergeValidEvaluated(schCxt, schValid)
// can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true)
// or if all properties and items were evaluated (it.props === true && it.items === true)
if (!merged) gen.if(not(valid))
})
)
cxt.result(
valid,
() => cxt.reset(),
() => cxt.error(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,267 | (sch: AnySchema) => alwaysValidSchema(it, sch) | type AnySchema = Schema | AsyncSchema |
2,268 | (_sch: AnySchema, i: number) => {
const schCxt = cxt.subschema(
{
keyword,
schemaProp: i,
compositeRule: true,
},
schValid
)
gen.assign(valid, _`${valid} || ${schValid}`)
const merged = cxt.mergeValidEvaluated(schCxt, schValid)
// can short-circuit if `unevaluatedProperties/Items` not supported (opts.unevaluated !== true)
// or if all properties and items were evaluated (it.props === true && it.items === true)
if (!merged) gen.if(not(valid))
} | type AnySchema = Schema | AsyncSchema |
2,269 | code(cxt: KeywordCxt, ruleType?: string) {
const {gen, data, $data, schema, schemaCode, it} = cxt
const {opts, errSchemaPath, schemaEnv, self} = it
if (!opts.validateFormats) return
if ($data) validate$DataFormat()
else validateFormat()
function validate$DataFormat(): void {
const fmts = gen.scopeValue("formats", {
ref: self.formats,
code: opts.code.formats,
})
const fDef = gen.const("fDef", _`${fmts}[${schemaCode}]`)
const fType = gen.let("fType")
const format = gen.let("format")
// TODO simplify
gen.if(
_`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`,
() => gen.assign(fType, _`${fDef}.type || "string"`).assign(format, _`${fDef}.validate`),
() => gen.assign(fType, _`"string"`).assign(format, fDef)
)
cxt.fail$data(or(unknownFmt(), invalidFmt()))
function unknownFmt(): Code {
if (opts.strictSchema === false) return nil
return _`${schemaCode} && !${format}`
}
function invalidFmt(): Code {
const callFormat = schemaEnv.$async
? _`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))`
: _`${format}(${data})`
const validData = _`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`
return _`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`
}
}
function validateFormat(): void {
const formatDef: AddedFormat | undefined = self.formats[schema]
if (!formatDef) {
unknownFormat()
return
}
if (formatDef === true) return
const [fmtType, format, fmtRef] = getFormat(formatDef)
if (fmtType === ruleType) cxt.pass(validCondition())
function unknownFormat(): void {
if (opts.strictSchema === false) {
self.logger.warn(unknownMsg())
return
}
throw new Error(unknownMsg())
function unknownMsg(): string {
return `unknown format "${schema as string}" ignored in schema at path "${errSchemaPath}"`
}
}
function getFormat(fmtDef: AddedFormat): [string, FormatValidate, Code] {
const code =
fmtDef instanceof RegExp
? regexpCode(fmtDef)
: opts.code.formats
? _`${opts.code.formats}${getProperty(schema)}`
: undefined
const fmt = gen.scopeValue("formats", {key: schema, ref: fmtDef, code})
if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) {
return [fmtDef.type || "string", fmtDef.validate, _`${fmt}.validate`]
}
return ["string", fmtDef, fmt]
}
function validCondition(): Code {
if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) {
if (!schemaEnv.$async) throw new Error("async format in sync schema")
return _`await ${fmtRef}(${data})`
}
return typeof format == "function" ? _`${fmtRef}(${data})` : _`${fmtRef}.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,270 | function getFormat(fmtDef: AddedFormat): [string, FormatValidate, Code] {
const code =
fmtDef instanceof RegExp
? regexpCode(fmtDef)
: opts.code.formats
? _`${opts.code.formats}${getProperty(schema)}`
: undefined
const fmt = gen.scopeValue("formats", {key: schema, ref: fmtDef, code})
if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) {
return [fmtDef.type || "string", fmtDef.validate, _`${fmt}.validate`]
}
return ["string", fmtDef, fmt]
} | type AddedFormat =
| true
| RegExp
| FormatValidator<string>
| FormatDefinition<string>
| FormatDefinition<number>
| AsyncFormatDefinition<string>
| AsyncFormatDefinition<number> |
2,271 | code(cxt: KeywordCxt) {
const {gen, schema, data, it} = cxt
const items = it.items || 0
if (items === true) return
const len = gen.const("len", _`${data}.length`)
if (schema === false) {
cxt.setParams({len: items})
cxt.fail(_`${len} > ${items}`)
} else if (typeof schema == "object" && !alwaysValidSchema(it, schema)) {
const valid = gen.var("valid", _`${len} <= ${items}`)
gen.if(not(valid), () => validateItems(valid, items))
cxt.ok(valid)
}
it.items = true
function validateItems(valid: Name, from: Name | number): void {
gen.forRange("i", from, len, (i) => {
cxt.subschema({keyword: "unevaluatedItems", 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,272 | function validateItems(valid: Name, from: Name | number): void {
gen.forRange("i", from, len, (i) => {
cxt.subschema({keyword: "unevaluatedItems", 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,273 | (key: Name) =>
gen.if(unevaluatedDynamic(props, key), () => unevaluatedPropCode(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,274 | (key: Name) =>
props === undefined
? unevaluatedPropCode(key)
: gen.if(unevaluatedStatic(props, key), () => unevaluatedPropCode(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,275 | function unevaluatedPropCode(key: Name): void {
if (schema === false) {
cxt.setParams({unevaluatedProperty: key})
cxt.error()
if (!allErrors) gen.break()
return
}
if (!alwaysValidSchema(it, schema)) {
const valid = gen.name("valid")
cxt.subschema(
{
keyword: "unevaluatedProperties",
dataProp: key,
dataPropType: Type.Str,
},
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,276 | function unevaluatedDynamic(evaluatedProps: Name, key: Name): Code {
return _`!${evaluatedProps} || !${evaluatedProps}[${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,277 | code(cxt: KeywordCxt) {
checkMetadata(cxt)
const {gen, data, schema, schemaValue, parentSchema, it} = cxt
if (schema.length === 0) throw new Error("enum must have non-empty array")
if (schema.length !== new Set(schema).size) throw new Error("enum items must be unique")
let valid: Code
const isString = _`typeof ${data} == "string"`
if (schema.length >= it.opts.loopEnum) {
let cond: Code
;[valid, cond] = checkNullable(cxt, isString)
gen.if(cond, loopEnum)
} else {
/* istanbul ignore if */
if (!Array.isArray(schema)) throw new Error("ajv implementation error")
valid = and(isString, or(...schema.map((value: string) => _`${data} === ${value}`)))
if (parentSchema.nullable) valid = or(_`${data} === null`, valid)
}
cxt.pass(valid)
function loopEnum(): void {
gen.forOf("v", schemaValue as Code, (v) =>
gen.if(_`${valid} = ${data} === ${v}`, () => 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,278 | code(cxt: KeywordCxt) {
checkMetadata(cxt)
const {gen, data, schema: ref, parentSchema, it} = cxt
const {
schemaEnv: {root},
} = it
const valid = gen.name("valid")
if (parentSchema.nullable) {
gen.var(valid, _`${data} === null`)
gen.if(not(valid), validateJtdRef)
} else {
gen.var(valid, false)
validateJtdRef()
}
cxt.ok(valid)
function validateJtdRef(): void {
const refSchema = (root.schema as AnySchemaObject).definitions?.[ref]
if (!refSchema) {
throw new MissingRefError(it.opts.uriResolver, "", ref, `No definition ${ref}`)
}
if (hasRef(refSchema) || !it.opts.inlineRefs) callValidate(refSchema)
else inlineRefSchema(refSchema)
}
function callValidate(schema: AnySchemaObject): void {
const sch = compileSchema.call(
it.self,
new SchemaEnv({schema, root, schemaPath: `/definitions/${ref}`})
)
const v = getValidate(cxt, sch)
const errsCount = gen.const("_errs", N.errors)
callRef(cxt, v, sch, sch.$async)
gen.assign(valid, _`${errsCount} === ${N.errors}`)
}
function inlineRefSchema(schema: AnySchemaObject): void {
const schName = gen.scopeValue(
"schema",
it.opts.code.source === true ? {ref: schema, code: stringify(schema)} : {ref: schema}
)
cxt.subschema(
{
schema,
dataTypes: [],
schemaPath: nil,
topSchemaRef: schName,
errSchemaPath: `/definitions/${ref}`,
},
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,279 | function callValidate(schema: AnySchemaObject): void {
const sch = compileSchema.call(
it.self,
new SchemaEnv({schema, root, schemaPath: `/definitions/${ref}`})
)
const v = getValidate(cxt, sch)
const errsCount = gen.const("_errs", N.errors)
callRef(cxt, v, sch, sch.$async)
gen.assign(valid, _`${errsCount} === ${N.errors}`)
} | type AnySchemaObject = SchemaObject | AsyncSchema |
2,280 | function inlineRefSchema(schema: AnySchemaObject): void {
const schName = gen.scopeValue(
"schema",
it.opts.code.source === true ? {ref: schema, code: stringify(schema)} : {ref: schema}
)
cxt.subschema(
{
schema,
dataTypes: [],
schemaPath: nil,
topSchemaRef: schName,
errSchemaPath: `/definitions/${ref}`,
},
valid
)
} | type AnySchemaObject = SchemaObject | AsyncSchema |
2,281 | function hasRef(schema: AnySchemaObject): boolean {
for (const key in schema) {
let sch: AnySchemaObject
if (key === "ref" || (typeof (sch = schema[key]) == "object" && hasRef(sch))) return true
}
return false
} | type AnySchemaObject = SchemaObject | AsyncSchema |
2,282 | function checkNullable(
{gen, data, parentSchema}: KeywordCxt,
cond: Code = nil
): [Name, Code] {
const valid = gen.name("valid")
if (parentSchema.nullable) {
gen.let(valid, _`${data} === null`)
cond = not(valid)
} else {
gen.let(valid, false)
}
return [valid, cond]
} | 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,283 | function checkNullable(
{gen, data, parentSchema}: KeywordCxt,
cond: Code = nil
): [Name, Code] {
const valid = gen.name("valid")
if (parentSchema.nullable) {
gen.let(valid, _`${data} === null`)
cond = not(valid)
} else {
gen.let(valid, false)
}
return [valid, cond]
} | type Code = _Code | Name |
2,284 | function checkNullableObject(cxt: KeywordCxt, cond: Code): [Name, Code] {
const [valid, cond_] = checkNullable(cxt, cond)
return [valid, _`${cond_} && typeof ${cxt.data} == "object" && !Array.isArray(${cxt.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,285 | function checkNullableObject(cxt: KeywordCxt, cond: Code): [Name, Code] {
const [valid, cond_] = checkNullable(cxt, cond)
return [valid, _`${cond_} && typeof ${cxt.data} == "object" && !Array.isArray(${cxt.data})`]
} | type Code = _Code | Name |
2,286 | code(cxt: KeywordCxt) {
checkMetadata(cxt)
const {gen, data, schema, it} = cxt
if (alwaysValidSchema(it, schema)) return
const [valid] = checkNullable(cxt)
gen.if(not(valid), () =>
gen.if(
_`Array.isArray(${data})`,
() => gen.assign(valid, validateArray(cxt)),
() => cxt.error()
)
)
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,287 | code(cxt: KeywordCxt) {
checkMetadata(cxt)
const {gen, schema, it} = cxt
if (alwaysValidSchema(it, schema)) return
const valid = gen.name("valid")
cxt.subschema({keyword: "metadata", jtdMetadata: true}, valid)
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,288 | function checkMetadata({it, keyword}: KeywordCxt, metadata?: boolean): void {
if (it.jtdMetadata !== metadata) {
throw new Error(`JTD: "${keyword}" cannot be used in this schema location`)
}
} | 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,289 | code(cxt: KeywordCxt) {
checkMetadata(cxt)
const {gen, data, schema, parentSchema} = cxt
const [valid, cond] = checkNullableObject(cxt, data)
gen.if(cond)
validateDiscriminator()
gen.elseIf(not(valid))
cxt.error()
gen.endIf()
cxt.ok(valid)
function validateDiscriminator(): void {
const tag = gen.const("tag", _`${data}${getProperty(schema)}`)
gen.if(_`${tag} === undefined`)
cxt.error(false, {discrError: DiscrError.Tag, tag})
gen.elseIf(_`typeof ${tag} == "string"`)
validateMapping(tag)
gen.else()
cxt.error(false, {discrError: DiscrError.Tag, tag}, {instancePath: schema})
gen.endIf()
}
function validateMapping(tag: Name): void {
gen.if(false)
for (const tagValue in parentSchema.mapping) {
gen.elseIf(_`${tag} === ${tagValue}`)
gen.assign(valid, applyTagSchema(tagValue))
}
gen.else()
cxt.error(
false,
{discrError: DiscrError.Mapping, tag},
{instancePath: schema, schemaPath: "mapping", parentSchema: true}
)
gen.endIf()
}
function applyTagSchema(schemaProp: string): Name {
const _valid = gen.name("valid")
cxt.subschema(
{
keyword: "mapping",
schemaProp,
jtdDiscriminator: schema,
},
_valid
)
return _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,290 | function validateMapping(tag: Name): void {
gen.if(false)
for (const tagValue in parentSchema.mapping) {
gen.elseIf(_`${tag} === ${tagValue}`)
gen.assign(valid, applyTagSchema(tagValue))
}
gen.else()
cxt.error(
false,
{discrError: DiscrError.Mapping, tag},
{instancePath: schema, schemaPath: "mapping", parentSchema: true}
)
gen.endIf()
} | 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,291 | code(cxt: KeywordCxt) {
checkMetadata(cxt)
const {gen, data, schema, it} = cxt
const [valid, cond] = checkNullableObject(cxt, data)
if (alwaysValidSchema(it, schema)) {
gen.if(not(or(cond, valid)), () => cxt.error())
} else {
gen.if(cond)
gen.assign(valid, validateMap())
gen.elseIf(not(valid))
cxt.error()
gen.endIf()
}
cxt.ok(valid)
function validateMap(): Name | boolean {
const _valid = gen.name("valid")
if (it.allErrors) {
const validMap = gen.let("valid", true)
validateValues(() => gen.assign(validMap, false))
return validMap
}
gen.var(_valid, true)
validateValues(() => gen.break())
return _valid
function validateValues(notValid: () => void): void {
gen.forIn("key", data, (key) => {
cxt.subschema(
{
keyword: "values",
dataProp: key,
dataPropType: Type.Str,
},
_valid
)
gen.if(not(_valid), notValid)
})
}
}
} | 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,292 | function typeErrorMessage({parentSchema}: KeywordErrorCxt, t: string): string {
return parentSchema?.nullable ? `must be ${t} or null` : `must be ${t}`
} | 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,293 | function typeErrorParams({parentSchema}: KeywordErrorCxt, t: string): Code {
return _`{type: ${t}, nullable: ${!!parentSchema?.nullable}}`
} | 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,294 | code(cxt: KeywordCxt) {
if (cxt.parentSchema.properties) return
validateProperties(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,295 | function timestampCode(cxt: KeywordCxt): Code {
const {gen, data, it} = cxt
const {timestamp, allowDate} = it.opts
if (timestamp === "date") return _`${data} instanceof Date `
const vts = useFunc(gen, validTimestamp)
const allowDateArg = allowDate ? _`, true` : nil
const validString = _`typeof ${data} == "string" && ${vts}(${data}${allowDateArg})`
return timestamp === "string" ? validString : or(_`${data} instanceof Date`, validString)
} | 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,296 | code(cxt: KeywordCxt) {
checkMetadata(cxt)
const {data, schema, parentSchema, it} = cxt
let cond: Code
switch (schema) {
case "boolean":
case "string":
cond = _`typeof ${data} == ${schema}`
break
case "timestamp": {
cond = timestampCode(cxt)
break
}
case "float32":
case "float64":
cond = _`typeof ${data} == "number"`
break
default: {
const sch = schema as IntType
cond = _`typeof ${data} == "number" && isFinite(${data}) && !(${data} % 1)`
if (!it.opts.int32range && (sch === "int32" || sch === "uint32")) {
if (sch === "uint32") cond = _`${cond} && ${data} >= 0`
} else {
const [min, max] = intRange[sch]
cond = _`${cond} && ${data} >= ${min} && ${data} <= ${max}`
}
}
}
cxt.pass(parentSchema.nullable ? or(_`${data} === null`, cond) : cond)
} | 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,297 | function validateProperties(cxt: KeywordCxt): void {
checkMetadata(cxt)
const {gen, data, parentSchema, it} = cxt
const {additionalProperties, nullable} = parentSchema
if (it.jtdDiscriminator && nullable) throw new Error("JTD: nullable inside discriminator mapping")
if (commonProperties()) {
throw new Error("JTD: properties and optionalProperties have common members")
}
const [allProps, properties] = schemaProperties("properties")
const [allOptProps, optProperties] = schemaProperties("optionalProperties")
if (properties.length === 0 && optProperties.length === 0 && additionalProperties) {
return
}
const [valid, cond] =
it.jtdDiscriminator === undefined
? checkNullableObject(cxt, data)
: [gen.let("valid", false), true]
gen.if(cond, () =>
gen.assign(valid, true).block(() => {
validateProps(properties, "properties", true)
validateProps(optProperties, "optionalProperties")
if (!additionalProperties) validateAdditional()
})
)
cxt.pass(valid)
function commonProperties(): boolean {
const props = parentSchema.properties as Record<string, any> | undefined
const optProps = parentSchema.optionalProperties as Record<string, any> | undefined
if (!(props && optProps)) return false
for (const p in props) {
if (Object.prototype.hasOwnProperty.call(optProps, p)) return true
}
return false
}
function schemaProperties(keyword: string): [string[], string[]] {
const schema = parentSchema[keyword]
const allPs = schema ? allSchemaProperties(schema) : []
if (it.jtdDiscriminator && allPs.some((p) => p === it.jtdDiscriminator)) {
throw new Error(`JTD: discriminator tag used in ${keyword}`)
}
const ps = allPs.filter((p) => !alwaysValidSchema(it, schema[p]))
return [allPs, ps]
}
function validateProps(props: string[], keyword: string, required?: boolean): void {
const _valid = gen.var("valid")
for (const prop of props) {
gen.if(
propertyInData(gen, data, prop, it.opts.ownProperties),
() => applyPropertySchema(prop, keyword, _valid),
() => missingProperty(prop)
)
cxt.ok(_valid)
}
function missingProperty(prop: string): void {
if (required) {
gen.assign(_valid, false)
cxt.error(false, {propError: PropError.Missing, missingProperty: prop}, {schemaPath: prop})
} else {
gen.assign(_valid, true)
}
}
}
function applyPropertySchema(prop: string, keyword: string, _valid: Name): void {
cxt.subschema(
{
keyword,
schemaProp: prop,
dataProp: prop,
},
_valid
)
}
function validateAdditional(): void {
gen.forIn("key", data, (key: Name) => {
const addProp = isAdditional(key, allProps, "properties", it.jtdDiscriminator)
const addOptProp = isAdditional(key, allOptProps, "optionalProperties")
const extra =
addProp === true ? addOptProp : addOptProp === true ? addProp : and(addProp, addOptProp)
gen.if(extra, () => {
if (it.opts.removeAdditional) {
gen.code(_`delete ${data}[${key}]`)
} else {
cxt.error(
false,
{propError: PropError.Additional, additionalProperty: key},
{instancePath: key, parentSchema: true}
)
if (!it.opts.allErrors) gen.break()
}
})
})
}
function isAdditional(
key: Name,
props: string[],
keyword: string,
jtdDiscriminator?: string
): Code | true {
let additional: Code | boolean
if (props.length > 8) {
// TODO maybe an option instead of hard-coded 8?
const propsSchema = schemaRefOrVal(it, parentSchema[keyword], keyword)
additional = not(isOwnProperty(gen, propsSchema as Code, key))
if (jtdDiscriminator !== undefined) {
additional = and(additional, _`${key} !== ${jtdDiscriminator}`)
}
} else if (props.length || jtdDiscriminator !== undefined) {
const ps = jtdDiscriminator === undefined ? props : [jtdDiscriminator].concat(props)
additional = and(...ps.map((p) => _`${key} !== ${p}`))
} else {
additional = true
}
return additional
}
} | 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,298 | (key: Name) => {
const addProp = isAdditional(key, allProps, "properties", it.jtdDiscriminator)
const addOptProp = isAdditional(key, allOptProps, "optionalProperties")
const extra =
addProp === true ? addOptProp : addOptProp === true ? addProp : and(addProp, addOptProp)
gen.if(extra, () => {
if (it.opts.removeAdditional) {
gen.code(_`delete ${data}[${key}]`)
} else {
cxt.error(
false,
{propError: PropError.Additional, additionalProperty: key},
{instancePath: key, parentSchema: true}
)
if (!it.opts.allErrors) 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,299 | function isAdditional(
key: Name,
props: string[],
keyword: string,
jtdDiscriminator?: string
): Code | true {
let additional: Code | boolean
if (props.length > 8) {
// TODO maybe an option instead of hard-coded 8?
const propsSchema = schemaRefOrVal(it, parentSchema[keyword], keyword)
additional = not(isOwnProperty(gen, propsSchema as Code, key))
if (jtdDiscriminator !== undefined) {
additional = and(additional, _`${key} !== ${jtdDiscriminator}`)
}
} else if (props.length || jtdDiscriminator !== undefined) {
const ps = jtdDiscriminator === undefined ? props : [jtdDiscriminator].concat(props)
additional = and(...ps.map((p) => _`${key} !== ${p}`))
} else {
additional = true
}
return additional
} | 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}
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.