core.ts 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892
  1. export {
  2. Format,
  3. FormatDefinition,
  4. AsyncFormatDefinition,
  5. KeywordDefinition,
  6. KeywordErrorDefinition,
  7. CodeKeywordDefinition,
  8. MacroKeywordDefinition,
  9. FuncKeywordDefinition,
  10. Vocabulary,
  11. Schema,
  12. SchemaObject,
  13. AnySchemaObject,
  14. AsyncSchema,
  15. AnySchema,
  16. ValidateFunction,
  17. AsyncValidateFunction,
  18. AnyValidateFunction,
  19. ErrorObject,
  20. ErrorNoParams,
  21. } from "./types"
  22. export {SchemaCxt, SchemaObjCxt} from "./compile"
  23. export interface Plugin<Opts> {
  24. (ajv: Ajv, options?: Opts): Ajv
  25. [prop: string]: any
  26. }
  27. export {KeywordCxt} from "./compile/validate"
  28. export {DefinedError} from "./vocabularies/errors"
  29. export {JSONType} from "./compile/rules"
  30. export {JSONSchemaType} from "./types/json-schema"
  31. export {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from "./types/jtd-schema"
  32. export {_, str, stringify, nil, Name, Code, CodeGen, CodeGenOptions} from "./compile/codegen"
  33. import type {
  34. Schema,
  35. AnySchema,
  36. AnySchemaObject,
  37. SchemaObject,
  38. AsyncSchema,
  39. Vocabulary,
  40. KeywordDefinition,
  41. AddedKeywordDefinition,
  42. AnyValidateFunction,
  43. ValidateFunction,
  44. AsyncValidateFunction,
  45. ErrorObject,
  46. Format,
  47. AddedFormat,
  48. RegExpEngine,
  49. UriResolver,
  50. } from "./types"
  51. import type {JSONSchemaType} from "./types/json-schema"
  52. import type {JTDSchemaType, SomeJTDSchemaType, JTDDataType} from "./types/jtd-schema"
  53. import ValidationError from "./runtime/validation_error"
  54. import MissingRefError from "./compile/ref_error"
  55. import {getRules, ValidationRules, Rule, RuleGroup, JSONType} from "./compile/rules"
  56. import {SchemaEnv, compileSchema, resolveSchema} from "./compile"
  57. import {Code, ValueScope} from "./compile/codegen"
  58. import {normalizeId, getSchemaRefs} from "./compile/resolve"
  59. import {getJSONTypes} from "./compile/validate/dataType"
  60. import {eachItem} from "./compile/util"
  61. import * as $dataRefSchema from "./refs/data.json"
  62. import DefaultUriResolver from "./runtime/uri"
  63. const defaultRegExp: RegExpEngine = (str, flags) => new RegExp(str, flags)
  64. defaultRegExp.code = "new RegExp"
  65. const META_IGNORE_OPTIONS: (keyof Options)[] = ["removeAdditional", "useDefaults", "coerceTypes"]
  66. const EXT_SCOPE_NAMES = new Set([
  67. "validate",
  68. "serialize",
  69. "parse",
  70. "wrapper",
  71. "root",
  72. "schema",
  73. "keyword",
  74. "pattern",
  75. "formats",
  76. "validate$data",
  77. "func",
  78. "obj",
  79. "Error",
  80. ])
  81. export type Options = CurrentOptions & DeprecatedOptions
  82. export interface CurrentOptions {
  83. // strict mode options (NEW)
  84. strict?: boolean | "log"
  85. strictSchema?: boolean | "log"
  86. strictNumbers?: boolean | "log"
  87. strictTypes?: boolean | "log"
  88. strictTuples?: boolean | "log"
  89. strictRequired?: boolean | "log"
  90. allowMatchingProperties?: boolean // disables a strict mode restriction
  91. allowUnionTypes?: boolean
  92. validateFormats?: boolean
  93. // validation and reporting options:
  94. $data?: boolean
  95. allErrors?: boolean
  96. verbose?: boolean
  97. discriminator?: boolean
  98. unicodeRegExp?: boolean
  99. timestamp?: "string" | "date" // JTD only
  100. parseDate?: boolean // JTD only
  101. allowDate?: boolean // JTD only
  102. specialNumbers?: "fast" | "null" // JTD only
  103. $comment?:
  104. | true
  105. | ((comment: string, schemaPath?: string, rootSchema?: AnySchemaObject) => unknown)
  106. formats?: {[Name in string]?: Format}
  107. keywords?: Vocabulary
  108. schemas?: AnySchema[] | {[Key in string]?: AnySchema}
  109. logger?: Logger | false
  110. loadSchema?: (uri: string) => Promise<AnySchemaObject>
  111. // options to modify validated data:
  112. removeAdditional?: boolean | "all" | "failing"
  113. useDefaults?: boolean | "empty"
  114. coerceTypes?: boolean | "array"
  115. // advanced options:
  116. next?: boolean // NEW
  117. unevaluated?: boolean // NEW
  118. dynamicRef?: boolean // NEW
  119. schemaId?: "id" | "$id"
  120. jtd?: boolean // NEW
  121. meta?: SchemaObject | boolean
  122. defaultMeta?: string | AnySchemaObject
  123. validateSchema?: boolean | "log"
  124. addUsedSchema?: boolean
  125. inlineRefs?: boolean | number
  126. passContext?: boolean
  127. loopRequired?: number
  128. loopEnum?: number // NEW
  129. ownProperties?: boolean
  130. multipleOfPrecision?: number
  131. int32range?: boolean // JTD only
  132. messages?: boolean
  133. code?: CodeOptions // NEW
  134. uriResolver?: UriResolver
  135. }
  136. export interface CodeOptions {
  137. es5?: boolean
  138. esm?: boolean
  139. lines?: boolean
  140. optimize?: boolean | number
  141. formats?: Code // code to require (or construct) map of available formats - for standalone code
  142. source?: boolean
  143. process?: (code: string, schema?: SchemaEnv) => string
  144. regExp?: RegExpEngine
  145. }
  146. interface InstanceCodeOptions extends CodeOptions {
  147. regExp: RegExpEngine
  148. optimize: number
  149. }
  150. interface DeprecatedOptions {
  151. /** @deprecated */
  152. ignoreKeywordsWithRef?: boolean
  153. /** @deprecated */
  154. jsPropertySyntax?: boolean // added instead of jsonPointers
  155. /** @deprecated */
  156. unicode?: boolean
  157. }
  158. interface RemovedOptions {
  159. format?: boolean
  160. errorDataPath?: "object" | "property"
  161. nullable?: boolean // "nullable" keyword is supported by default
  162. jsonPointers?: boolean
  163. extendRefs?: true | "ignore" | "fail"
  164. missingRefs?: true | "ignore" | "fail"
  165. processCode?: (code: string, schema?: SchemaEnv) => string
  166. sourceCode?: boolean
  167. strictDefaults?: boolean
  168. strictKeywords?: boolean
  169. uniqueItems?: boolean
  170. unknownFormats?: true | string[] | "ignore"
  171. cache?: any
  172. serialize?: (schema: AnySchema) => unknown
  173. ajvErrors?: boolean
  174. }
  175. type OptionsInfo<T extends RemovedOptions | DeprecatedOptions> = {
  176. [K in keyof T]-?: string | undefined
  177. }
  178. const removedOptions: OptionsInfo<RemovedOptions> = {
  179. errorDataPath: "",
  180. format: "`validateFormats: false` can be used instead.",
  181. nullable: '"nullable" keyword is supported by default.',
  182. jsonPointers: "Deprecated jsPropertySyntax can be used instead.",
  183. extendRefs: "Deprecated ignoreKeywordsWithRef can be used instead.",
  184. missingRefs: "Pass empty schema with $id that should be ignored to ajv.addSchema.",
  185. processCode: "Use option `code: {process: (code, schemaEnv: object) => string}`",
  186. sourceCode: "Use option `code: {source: true}`",
  187. strictDefaults: "It is default now, see option `strict`.",
  188. strictKeywords: "It is default now, see option `strict`.",
  189. uniqueItems: '"uniqueItems" keyword is always validated.',
  190. unknownFormats: "Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",
  191. cache: "Map is used as cache, schema object as key.",
  192. serialize: "Map is used as cache, schema object as key.",
  193. ajvErrors: "It is default now.",
  194. }
  195. const deprecatedOptions: OptionsInfo<DeprecatedOptions> = {
  196. ignoreKeywordsWithRef: "",
  197. jsPropertySyntax: "",
  198. unicode: '"minLength"/"maxLength" account for unicode characters by default.',
  199. }
  200. type RequiredInstanceOptions = {
  201. [K in
  202. | "strictSchema"
  203. | "strictNumbers"
  204. | "strictTypes"
  205. | "strictTuples"
  206. | "strictRequired"
  207. | "inlineRefs"
  208. | "loopRequired"
  209. | "loopEnum"
  210. | "meta"
  211. | "messages"
  212. | "schemaId"
  213. | "addUsedSchema"
  214. | "validateSchema"
  215. | "validateFormats"
  216. | "int32range"
  217. | "unicodeRegExp"
  218. | "uriResolver"]: NonNullable<Options[K]>
  219. } & {code: InstanceCodeOptions}
  220. export type InstanceOptions = Options & RequiredInstanceOptions
  221. const MAX_EXPRESSION = 200
  222. // eslint-disable-next-line complexity
  223. function requiredOptions(o: Options): RequiredInstanceOptions {
  224. const s = o.strict
  225. const _optz = o.code?.optimize
  226. const optimize = _optz === true || _optz === undefined ? 1 : _optz || 0
  227. const regExp = o.code?.regExp ?? defaultRegExp
  228. const uriResolver = o.uriResolver ?? DefaultUriResolver
  229. return {
  230. strictSchema: o.strictSchema ?? s ?? true,
  231. strictNumbers: o.strictNumbers ?? s ?? true,
  232. strictTypes: o.strictTypes ?? s ?? "log",
  233. strictTuples: o.strictTuples ?? s ?? "log",
  234. strictRequired: o.strictRequired ?? s ?? false,
  235. code: o.code ? {...o.code, optimize, regExp} : {optimize, regExp},
  236. loopRequired: o.loopRequired ?? MAX_EXPRESSION,
  237. loopEnum: o.loopEnum ?? MAX_EXPRESSION,
  238. meta: o.meta ?? true,
  239. messages: o.messages ?? true,
  240. inlineRefs: o.inlineRefs ?? true,
  241. schemaId: o.schemaId ?? "$id",
  242. addUsedSchema: o.addUsedSchema ?? true,
  243. validateSchema: o.validateSchema ?? true,
  244. validateFormats: o.validateFormats ?? true,
  245. unicodeRegExp: o.unicodeRegExp ?? true,
  246. int32range: o.int32range ?? true,
  247. uriResolver: uriResolver,
  248. }
  249. }
  250. export interface Logger {
  251. log(...args: unknown[]): unknown
  252. warn(...args: unknown[]): unknown
  253. error(...args: unknown[]): unknown
  254. }
  255. export default class Ajv {
  256. opts: InstanceOptions
  257. errors?: ErrorObject[] | null // errors from the last validation
  258. logger: Logger
  259. // shared external scope values for compiled functions
  260. readonly scope: ValueScope
  261. readonly schemas: {[Key in string]?: SchemaEnv} = {}
  262. readonly refs: {[Ref in string]?: SchemaEnv | string} = {}
  263. readonly formats: {[Name in string]?: AddedFormat} = {}
  264. readonly RULES: ValidationRules
  265. readonly _compilations: Set<SchemaEnv> = new Set()
  266. private readonly _loading: {[Ref in string]?: Promise<AnySchemaObject>} = {}
  267. private readonly _cache: Map<AnySchema, SchemaEnv> = new Map()
  268. private readonly _metaOpts: InstanceOptions
  269. static ValidationError = ValidationError
  270. static MissingRefError = MissingRefError
  271. constructor(opts: Options = {}) {
  272. opts = this.opts = {...opts, ...requiredOptions(opts)}
  273. const {es5, lines} = this.opts.code
  274. this.scope = new ValueScope({scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines})
  275. this.logger = getLogger(opts.logger)
  276. const formatOpt = opts.validateFormats
  277. opts.validateFormats = false
  278. this.RULES = getRules()
  279. checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED")
  280. checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn")
  281. this._metaOpts = getMetaSchemaOptions.call(this)
  282. if (opts.formats) addInitialFormats.call(this)
  283. this._addVocabularies()
  284. this._addDefaultMetaSchema()
  285. if (opts.keywords) addInitialKeywords.call(this, opts.keywords)
  286. if (typeof opts.meta == "object") this.addMetaSchema(opts.meta)
  287. addInitialSchemas.call(this)
  288. opts.validateFormats = formatOpt
  289. }
  290. _addVocabularies(): void {
  291. this.addKeyword("$async")
  292. }
  293. _addDefaultMetaSchema(): void {
  294. const {$data, meta, schemaId} = this.opts
  295. let _dataRefSchema: SchemaObject = $dataRefSchema
  296. if (schemaId === "id") {
  297. _dataRefSchema = {...$dataRefSchema}
  298. _dataRefSchema.id = _dataRefSchema.$id
  299. delete _dataRefSchema.$id
  300. }
  301. if (meta && $data) this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false)
  302. }
  303. defaultMeta(): string | AnySchemaObject | undefined {
  304. const {meta, schemaId} = this.opts
  305. return (this.opts.defaultMeta = typeof meta == "object" ? meta[schemaId] || meta : undefined)
  306. }
  307. // Validate data using schema
  308. // AnySchema will be compiled and cached using schema itself as a key for Map
  309. validate(schema: Schema | string, data: unknown): boolean
  310. validate(schemaKeyRef: AnySchema | string, data: unknown): boolean | Promise<unknown>
  311. validate<T>(schema: Schema | JSONSchemaType<T> | string, data: unknown): data is T
  312. // Separated for type inference to work
  313. // eslint-disable-next-line @typescript-eslint/unified-signatures
  314. validate<T>(schema: JTDSchemaType<T>, data: unknown): data is T
  315. // This overload is only intended for typescript inference, the first
  316. // argument prevents manual type annotation from matching this overload
  317. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  318. validate<N extends never, T extends SomeJTDSchemaType>(
  319. schema: T,
  320. data: unknown
  321. ): data is JTDDataType<T>
  322. // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
  323. validate<T>(schema: AsyncSchema, data: unknown | T): Promise<T>
  324. validate<T>(schemaKeyRef: AnySchema | string, data: unknown): data is T | Promise<T>
  325. validate<T>(
  326. schemaKeyRef: AnySchema | string, // key, ref or schema object
  327. // eslint-disable-next-line @typescript-eslint/no-redundant-type-constituents
  328. data: unknown | T // to be validated
  329. ): boolean | Promise<T> {
  330. let v: AnyValidateFunction | undefined
  331. if (typeof schemaKeyRef == "string") {
  332. v = this.getSchema<T>(schemaKeyRef)
  333. if (!v) throw new Error(`no schema with key or ref "${schemaKeyRef}"`)
  334. } else {
  335. v = this.compile<T>(schemaKeyRef)
  336. }
  337. const valid = v(data)
  338. if (!("$async" in v)) this.errors = v.errors
  339. return valid
  340. }
  341. // Create validation function for passed schema
  342. // _meta: true if schema is a meta-schema. Used internally to compile meta schemas of user-defined keywords.
  343. compile<T = unknown>(schema: Schema | JSONSchemaType<T>, _meta?: boolean): ValidateFunction<T>
  344. // Separated for type inference to work
  345. // eslint-disable-next-line @typescript-eslint/unified-signatures
  346. compile<T = unknown>(schema: JTDSchemaType<T>, _meta?: boolean): ValidateFunction<T>
  347. // This overload is only intended for typescript inference, the first
  348. // argument prevents manual type annotation from matching this overload
  349. // eslint-disable-next-line @typescript-eslint/no-unused-vars
  350. compile<N extends never, T extends SomeJTDSchemaType>(
  351. schema: T,
  352. _meta?: boolean
  353. ): ValidateFunction<JTDDataType<T>>
  354. compile<T = unknown>(schema: AsyncSchema, _meta?: boolean): AsyncValidateFunction<T>
  355. compile<T = unknown>(schema: AnySchema, _meta?: boolean): AnyValidateFunction<T>
  356. compile<T = unknown>(schema: AnySchema, _meta?: boolean): AnyValidateFunction<T> {
  357. const sch = this._addSchema(schema, _meta)
  358. return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction<T>
  359. }
  360. // Creates validating function for passed schema with asynchronous loading of missing schemas.
  361. // `loadSchema` option should be a function that accepts schema uri and returns promise that resolves with the schema.
  362. // TODO allow passing schema URI
  363. // meta - optional true to compile meta-schema
  364. compileAsync<T = unknown>(
  365. schema: SchemaObject | JSONSchemaType<T>,
  366. _meta?: boolean
  367. ): Promise<ValidateFunction<T>>
  368. // Separated for type inference to work
  369. // eslint-disable-next-line @typescript-eslint/unified-signatures
  370. compileAsync<T = unknown>(schema: JTDSchemaType<T>, _meta?: boolean): Promise<ValidateFunction<T>>
  371. compileAsync<T = unknown>(schema: AsyncSchema, meta?: boolean): Promise<AsyncValidateFunction<T>>
  372. // eslint-disable-next-line @typescript-eslint/unified-signatures
  373. compileAsync<T = unknown>(
  374. schema: AnySchemaObject,
  375. meta?: boolean
  376. ): Promise<AnyValidateFunction<T>>
  377. compileAsync<T = unknown>(
  378. schema: AnySchemaObject,
  379. meta?: boolean
  380. ): Promise<AnyValidateFunction<T>> {
  381. if (typeof this.opts.loadSchema != "function") {
  382. throw new Error("options.loadSchema should be a function")
  383. }
  384. const {loadSchema} = this.opts
  385. return runCompileAsync.call(this, schema, meta)
  386. async function runCompileAsync(
  387. this: Ajv,
  388. _schema: AnySchemaObject,
  389. _meta?: boolean
  390. ): Promise<AnyValidateFunction> {
  391. await loadMetaSchema.call(this, _schema.$schema)
  392. const sch = this._addSchema(_schema, _meta)
  393. return sch.validate || _compileAsync.call(this, sch)
  394. }
  395. async function loadMetaSchema(this: Ajv, $ref?: string): Promise<void> {
  396. if ($ref && !this.getSchema($ref)) {
  397. await runCompileAsync.call(this, {$ref}, true)
  398. }
  399. }
  400. async function _compileAsync(this: Ajv, sch: SchemaEnv): Promise<AnyValidateFunction> {
  401. try {
  402. return this._compileSchemaEnv(sch)
  403. } catch (e) {
  404. if (!(e instanceof MissingRefError)) throw e
  405. checkLoaded.call(this, e)
  406. await loadMissingSchema.call(this, e.missingSchema)
  407. return _compileAsync.call(this, sch)
  408. }
  409. }
  410. function checkLoaded(this: Ajv, {missingSchema: ref, missingRef}: MissingRefError): void {
  411. if (this.refs[ref]) {
  412. throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`)
  413. }
  414. }
  415. async function loadMissingSchema(this: Ajv, ref: string): Promise<void> {
  416. const _schema = await _loadSchema.call(this, ref)
  417. if (!this.refs[ref]) await loadMetaSchema.call(this, _schema.$schema)
  418. if (!this.refs[ref]) this.addSchema(_schema, ref, meta)
  419. }
  420. async function _loadSchema(this: Ajv, ref: string): Promise<AnySchemaObject> {
  421. const p = this._loading[ref]
  422. if (p) return p
  423. try {
  424. return await (this._loading[ref] = loadSchema(ref))
  425. } finally {
  426. delete this._loading[ref]
  427. }
  428. }
  429. }
  430. // Adds schema to the instance
  431. addSchema(
  432. schema: AnySchema | AnySchema[], // If array is passed, `key` will be ignored
  433. 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`.
  434. _meta?: boolean, // true if schema is a meta-schema. Used internally, addMetaSchema should be used instead.
  435. _validateSchema = this.opts.validateSchema // false to skip schema validation. Used internally, option validateSchema should be used instead.
  436. ): Ajv {
  437. if (Array.isArray(schema)) {
  438. for (const sch of schema) this.addSchema(sch, undefined, _meta, _validateSchema)
  439. return this
  440. }
  441. let id: string | undefined
  442. if (typeof schema === "object") {
  443. const {schemaId} = this.opts
  444. id = schema[schemaId]
  445. if (id !== undefined && typeof id != "string") {
  446. throw new Error(`schema ${schemaId} must be string`)
  447. }
  448. }
  449. key = normalizeId(key || id)
  450. this._checkUnique(key)
  451. this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true)
  452. return this
  453. }
  454. // Add schema that will be used to validate other schemas
  455. // options in META_IGNORE_OPTIONS are alway set to false
  456. addMetaSchema(
  457. schema: AnySchemaObject,
  458. key?: string, // schema key
  459. _validateSchema = this.opts.validateSchema // false to skip schema validation, can be used to override validateSchema option for meta-schema
  460. ): Ajv {
  461. this.addSchema(schema, key, true, _validateSchema)
  462. return this
  463. }
  464. // Validate schema against its meta-schema
  465. validateSchema(schema: AnySchema, throwOrLogError?: boolean): boolean | Promise<unknown> {
  466. if (typeof schema == "boolean") return true
  467. let $schema: string | AnySchemaObject | undefined
  468. $schema = schema.$schema
  469. if ($schema !== undefined && typeof $schema != "string") {
  470. throw new Error("$schema must be a string")
  471. }
  472. $schema = $schema || this.opts.defaultMeta || this.defaultMeta()
  473. if (!$schema) {
  474. this.logger.warn("meta-schema not available")
  475. this.errors = null
  476. return true
  477. }
  478. const valid = this.validate($schema, schema)
  479. if (!valid && throwOrLogError) {
  480. const message = "schema is invalid: " + this.errorsText()
  481. if (this.opts.validateSchema === "log") this.logger.error(message)
  482. else throw new Error(message)
  483. }
  484. return valid
  485. }
  486. // Get compiled schema by `key` or `ref`.
  487. // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)
  488. getSchema<T = unknown>(keyRef: string): AnyValidateFunction<T> | undefined {
  489. let sch
  490. while (typeof (sch = getSchEnv.call(this, keyRef)) == "string") keyRef = sch
  491. if (sch === undefined) {
  492. const {schemaId} = this.opts
  493. const root = new SchemaEnv({schema: {}, schemaId})
  494. sch = resolveSchema.call(this, root, keyRef)
  495. if (!sch) return
  496. this.refs[keyRef] = sch
  497. }
  498. return (sch.validate || this._compileSchemaEnv(sch)) as AnyValidateFunction<T> | undefined
  499. }
  500. // Remove cached schema(s).
  501. // If no parameter is passed all schemas but meta-schemas are removed.
  502. // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
  503. // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
  504. removeSchema(schemaKeyRef?: AnySchema | string | RegExp): Ajv {
  505. if (schemaKeyRef instanceof RegExp) {
  506. this._removeAllSchemas(this.schemas, schemaKeyRef)
  507. this._removeAllSchemas(this.refs, schemaKeyRef)
  508. return this
  509. }
  510. switch (typeof schemaKeyRef) {
  511. case "undefined":
  512. this._removeAllSchemas(this.schemas)
  513. this._removeAllSchemas(this.refs)
  514. this._cache.clear()
  515. return this
  516. case "string": {
  517. const sch = getSchEnv.call(this, schemaKeyRef)
  518. if (typeof sch == "object") this._cache.delete(sch.schema)
  519. delete this.schemas[schemaKeyRef]
  520. delete this.refs[schemaKeyRef]
  521. return this
  522. }
  523. case "object": {
  524. const cacheKey = schemaKeyRef
  525. this._cache.delete(cacheKey)
  526. let id = schemaKeyRef[this.opts.schemaId]
  527. if (id) {
  528. id = normalizeId(id)
  529. delete this.schemas[id]
  530. delete this.refs[id]
  531. }
  532. return this
  533. }
  534. default:
  535. throw new Error("ajv.removeSchema: invalid parameter")
  536. }
  537. }
  538. // add "vocabulary" - a collection of keywords
  539. addVocabulary(definitions: Vocabulary): Ajv {
  540. for (const def of definitions) this.addKeyword(def)
  541. return this
  542. }
  543. addKeyword(
  544. kwdOrDef: string | KeywordDefinition,
  545. def?: KeywordDefinition // deprecated
  546. ): Ajv {
  547. let keyword: string | string[]
  548. if (typeof kwdOrDef == "string") {
  549. keyword = kwdOrDef
  550. if (typeof def == "object") {
  551. this.logger.warn("these parameters are deprecated, see docs for addKeyword")
  552. def.keyword = keyword
  553. }
  554. } else if (typeof kwdOrDef == "object" && def === undefined) {
  555. def = kwdOrDef
  556. keyword = def.keyword
  557. if (Array.isArray(keyword) && !keyword.length) {
  558. throw new Error("addKeywords: keyword must be string or non-empty array")
  559. }
  560. } else {
  561. throw new Error("invalid addKeywords parameters")
  562. }
  563. checkKeyword.call(this, keyword, def)
  564. if (!def) {
  565. eachItem(keyword, (kwd) => addRule.call(this, kwd))
  566. return this
  567. }
  568. keywordMetaschema.call(this, def)
  569. const definition: AddedKeywordDefinition = {
  570. ...def,
  571. type: getJSONTypes(def.type),
  572. schemaType: getJSONTypes(def.schemaType),
  573. }
  574. eachItem(
  575. keyword,
  576. definition.type.length === 0
  577. ? (k) => addRule.call(this, k, definition)
  578. : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t))
  579. )
  580. return this
  581. }
  582. getKeyword(keyword: string): AddedKeywordDefinition | boolean {
  583. const rule = this.RULES.all[keyword]
  584. return typeof rule == "object" ? rule.definition : !!rule
  585. }
  586. // Remove keyword
  587. removeKeyword(keyword: string): Ajv {
  588. // TODO return type should be Ajv
  589. const {RULES} = this
  590. delete RULES.keywords[keyword]
  591. delete RULES.all[keyword]
  592. for (const group of RULES.rules) {
  593. const i = group.rules.findIndex((rule) => rule.keyword === keyword)
  594. if (i >= 0) group.rules.splice(i, 1)
  595. }
  596. return this
  597. }
  598. // Add format
  599. addFormat(name: string, format: Format): Ajv {
  600. if (typeof format == "string") format = new RegExp(format)
  601. this.formats[name] = format
  602. return this
  603. }
  604. errorsText(
  605. errors: ErrorObject[] | null | undefined = this.errors, // optional array of validation errors
  606. {separator = ", ", dataVar = "data"}: ErrorsTextOptions = {} // optional options with properties `separator` and `dataVar`
  607. ): string {
  608. if (!errors || errors.length === 0) return "No errors"
  609. return errors
  610. .map((e) => `${dataVar}${e.instancePath} ${e.message}`)
  611. .reduce((text, msg) => text + separator + msg)
  612. }
  613. $dataMetaSchema(metaSchema: AnySchemaObject, keywordsJsonPointers: string[]): AnySchemaObject {
  614. const rules = this.RULES.all
  615. metaSchema = JSON.parse(JSON.stringify(metaSchema))
  616. for (const jsonPointer of keywordsJsonPointers) {
  617. const segments = jsonPointer.split("/").slice(1) // first segment is an empty string
  618. let keywords = metaSchema
  619. for (const seg of segments) keywords = keywords[seg] as AnySchemaObject
  620. for (const key in rules) {
  621. const rule = rules[key]
  622. if (typeof rule != "object") continue
  623. const {$data} = rule.definition
  624. const schema = keywords[key] as AnySchemaObject | undefined
  625. if ($data && schema) keywords[key] = schemaOrData(schema)
  626. }
  627. }
  628. return metaSchema
  629. }
  630. private _removeAllSchemas(schemas: {[Ref in string]?: SchemaEnv | string}, regex?: RegExp): void {
  631. for (const keyRef in schemas) {
  632. const sch = schemas[keyRef]
  633. if (!regex || regex.test(keyRef)) {
  634. if (typeof sch == "string") {
  635. delete schemas[keyRef]
  636. } else if (sch && !sch.meta) {
  637. this._cache.delete(sch.schema)
  638. delete schemas[keyRef]
  639. }
  640. }
  641. }
  642. }
  643. _addSchema(
  644. schema: AnySchema,
  645. meta?: boolean,
  646. baseId?: string,
  647. validateSchema = this.opts.validateSchema,
  648. addSchema = this.opts.addUsedSchema
  649. ): SchemaEnv {
  650. let id: string | undefined
  651. const {schemaId} = this.opts
  652. if (typeof schema == "object") {
  653. id = schema[schemaId]
  654. } else {
  655. if (this.opts.jtd) throw new Error("schema must be object")
  656. else if (typeof schema != "boolean") throw new Error("schema must be object or boolean")
  657. }
  658. let sch = this._cache.get(schema)
  659. if (sch !== undefined) return sch
  660. baseId = normalizeId(id || baseId)
  661. const localRefs = getSchemaRefs.call(this, schema, baseId)
  662. sch = new SchemaEnv({schema, schemaId, meta, baseId, localRefs})
  663. this._cache.set(sch.schema, sch)
  664. if (addSchema && !baseId.startsWith("#")) {
  665. // TODO atm it is allowed to overwrite schemas without id (instead of not adding them)
  666. if (baseId) this._checkUnique(baseId)
  667. this.refs[baseId] = sch
  668. }
  669. if (validateSchema) this.validateSchema(schema, true)
  670. return sch
  671. }
  672. private _checkUnique(id: string): void {
  673. if (this.schemas[id] || this.refs[id]) {
  674. throw new Error(`schema with key or id "${id}" already exists`)
  675. }
  676. }
  677. private _compileSchemaEnv(sch: SchemaEnv): AnyValidateFunction {
  678. if (sch.meta) this._compileMetaSchema(sch)
  679. else compileSchema.call(this, sch)
  680. /* istanbul ignore if */
  681. if (!sch.validate) throw new Error("ajv implementation error")
  682. return sch.validate
  683. }
  684. private _compileMetaSchema(sch: SchemaEnv): void {
  685. const currentOpts = this.opts
  686. this.opts = this._metaOpts
  687. try {
  688. compileSchema.call(this, sch)
  689. } finally {
  690. this.opts = currentOpts
  691. }
  692. }
  693. }
  694. export interface ErrorsTextOptions {
  695. separator?: string
  696. dataVar?: string
  697. }
  698. function checkOptions(
  699. this: Ajv,
  700. checkOpts: OptionsInfo<RemovedOptions | DeprecatedOptions>,
  701. options: Options & RemovedOptions,
  702. msg: string,
  703. log: "warn" | "error" = "error"
  704. ): void {
  705. for (const key in checkOpts) {
  706. const opt = key as keyof typeof checkOpts
  707. if (opt in options) this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`)
  708. }
  709. }
  710. function getSchEnv(this: Ajv, keyRef: string): SchemaEnv | string | undefined {
  711. keyRef = normalizeId(keyRef) // TODO tests fail without this line
  712. return this.schemas[keyRef] || this.refs[keyRef]
  713. }
  714. function addInitialSchemas(this: Ajv): void {
  715. const optsSchemas = this.opts.schemas
  716. if (!optsSchemas) return
  717. if (Array.isArray(optsSchemas)) this.addSchema(optsSchemas)
  718. else for (const key in optsSchemas) this.addSchema(optsSchemas[key] as AnySchema, key)
  719. }
  720. function addInitialFormats(this: Ajv): void {
  721. for (const name in this.opts.formats) {
  722. const format = this.opts.formats[name]
  723. if (format) this.addFormat(name, format)
  724. }
  725. }
  726. function addInitialKeywords(
  727. this: Ajv,
  728. defs: Vocabulary | {[K in string]?: KeywordDefinition}
  729. ): void {
  730. if (Array.isArray(defs)) {
  731. this.addVocabulary(defs)
  732. return
  733. }
  734. this.logger.warn("keywords option as map is deprecated, pass array")
  735. for (const keyword in defs) {
  736. const def = defs[keyword] as KeywordDefinition
  737. if (!def.keyword) def.keyword = keyword
  738. this.addKeyword(def)
  739. }
  740. }
  741. function getMetaSchemaOptions(this: Ajv): InstanceOptions {
  742. const metaOpts = {...this.opts}
  743. for (const opt of META_IGNORE_OPTIONS) delete metaOpts[opt]
  744. return metaOpts
  745. }
  746. const noLogs = {log() {}, warn() {}, error() {}}
  747. function getLogger(logger?: Partial<Logger> | false): Logger {
  748. if (logger === false) return noLogs
  749. if (logger === undefined) return console
  750. if (logger.log && logger.warn && logger.error) return logger as Logger
  751. throw new Error("logger must implement log, warn and error methods")
  752. }
  753. const KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i
  754. function checkKeyword(this: Ajv, keyword: string | string[], def?: KeywordDefinition): void {
  755. const {RULES} = this
  756. eachItem(keyword, (kwd) => {
  757. if (RULES.keywords[kwd]) throw new Error(`Keyword ${kwd} is already defined`)
  758. if (!KEYWORD_NAME.test(kwd)) throw new Error(`Keyword ${kwd} has invalid name`)
  759. })
  760. if (!def) return
  761. if (def.$data && !("code" in def || "validate" in def)) {
  762. throw new Error('$data keyword must have "code" or "validate" function')
  763. }
  764. }
  765. function addRule(
  766. this: Ajv,
  767. keyword: string,
  768. definition?: AddedKeywordDefinition,
  769. dataType?: JSONType
  770. ): void {
  771. const post = definition?.post
  772. if (dataType && post) throw new Error('keyword with "post" flag cannot have "type"')
  773. const {RULES} = this
  774. let ruleGroup = post ? RULES.post : RULES.rules.find(({type: t}) => t === dataType)
  775. if (!ruleGroup) {
  776. ruleGroup = {type: dataType, rules: []}
  777. RULES.rules.push(ruleGroup)
  778. }
  779. RULES.keywords[keyword] = true
  780. if (!definition) return
  781. const rule: Rule = {
  782. keyword,
  783. definition: {
  784. ...definition,
  785. type: getJSONTypes(definition.type),
  786. schemaType: getJSONTypes(definition.schemaType),
  787. },
  788. }
  789. if (definition.before) addBeforeRule.call(this, ruleGroup, rule, definition.before)
  790. else ruleGroup.rules.push(rule)
  791. RULES.all[keyword] = rule
  792. definition.implements?.forEach((kwd) => this.addKeyword(kwd))
  793. }
  794. function addBeforeRule(this: Ajv, ruleGroup: RuleGroup, rule: Rule, before: string): void {
  795. const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before)
  796. if (i >= 0) {
  797. ruleGroup.rules.splice(i, 0, rule)
  798. } else {
  799. ruleGroup.rules.push(rule)
  800. this.logger.warn(`rule ${before} is not defined`)
  801. }
  802. }
  803. function keywordMetaschema(this: Ajv, def: KeywordDefinition): void {
  804. let {metaSchema} = def
  805. if (metaSchema === undefined) return
  806. if (def.$data && this.opts.$data) metaSchema = schemaOrData(metaSchema)
  807. def.validateSchema = this.compile(metaSchema, true)
  808. }
  809. const $dataRef = {
  810. $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",
  811. }
  812. function schemaOrData(schema: AnySchema): AnySchemaObject {
  813. return {anyOf: [schema, $dataRef]}
  814. }