core.ts 27 KB

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