core.ts 30 KB

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