core.ts 28 KB

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