index.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. import type {
  2. AnySchema,
  3. AnySchemaObject,
  4. AnyValidateFunction,
  5. AsyncValidateFunction,
  6. EvaluatedProperties,
  7. EvaluatedItems,
  8. } from "../types"
  9. import type Ajv from "../core"
  10. import type {InstanceOptions} from "../core"
  11. import {CodeGen, _, nil, stringify, Name, Code, ValueScopeName} from "./codegen"
  12. import {ValidationError} from "./error_classes"
  13. import N from "./names"
  14. import {LocalRefs, getFullPath, _getFullPath, inlineRef, normalizeId, resolveUrl} from "./resolve"
  15. import {schemaHasRulesButRef, unescapeFragment} from "./util"
  16. import {validateFunctionCode} from "./validate"
  17. import * as URI from "uri-js"
  18. import {JSONType} from "./rules"
  19. export type SchemaRefs = {
  20. [Ref in string]?: SchemaEnv | AnySchema
  21. }
  22. export interface SchemaCxt {
  23. readonly gen: CodeGen
  24. readonly allErrors?: boolean // validation mode - whether to collect all errors or break on error
  25. readonly data: Name // Name with reference to the current part of data instance
  26. readonly parentData: Name // should be used in keywords modifying data
  27. readonly parentDataProperty: Code | number // should be used in keywords modifying data
  28. readonly dataNames: Name[]
  29. readonly dataPathArr: (Code | number)[]
  30. readonly dataLevel: number // the level of the currently validated data,
  31. // it can be used to access both the property names and the data on all levels from the top.
  32. dataTypes: JSONType[] // data types applied to the current part of data instance
  33. definedProperties: Set<string> // set of properties to keep track of for required checks
  34. readonly topSchemaRef: Code
  35. readonly validateName: Name
  36. evaluated?: Name
  37. readonly ValidationError?: Name
  38. readonly schema: AnySchema // current schema object - equal to parentSchema passed via KeywordCxt
  39. readonly schemaEnv: SchemaEnv
  40. readonly rootId: string
  41. baseId: string // the current schema base URI that should be used as the base for resolving URIs in references (\$ref)
  42. readonly schemaPath: Code // the run-time expression that evaluates to the property name of the current schema
  43. readonly errSchemaPath: string // this is actual string, should not be changed to Code
  44. readonly errorPath: Code
  45. readonly propertyName?: Name
  46. readonly compositeRule?: boolean // true indicates that the current schema is inside the compound keyword,
  47. // where failing some rule doesn't mean validation failure (`anyOf`, `oneOf`, `not`, `if`).
  48. // This flag is used to determine whether you can return validation result immediately after any error in case the option `allErrors` is not `true.
  49. // You only need to use it if you have many steps in your keywords and potentially can define multiple errors.
  50. props?: EvaluatedProperties | Name // properties evaluated by this schema - used by parent schema or assigned to validation function
  51. items?: EvaluatedItems | Name // last item evaluated by this schema - used by parent schema or assigned to validation function
  52. jtdDiscriminator?: string
  53. jtdMetadata?: boolean
  54. readonly createErrors?: boolean
  55. readonly opts: InstanceOptions // Ajv instance option.
  56. readonly self: Ajv // current Ajv instance
  57. }
  58. export interface SchemaObjCxt extends SchemaCxt {
  59. readonly schema: AnySchemaObject
  60. }
  61. interface SchemaEnvArgs {
  62. readonly schema: AnySchema
  63. readonly root?: SchemaEnv
  64. readonly baseId?: string
  65. readonly localRefs?: LocalRefs
  66. readonly meta?: boolean
  67. }
  68. export class SchemaEnv implements SchemaEnvArgs {
  69. readonly schema: AnySchema
  70. readonly root: SchemaEnv
  71. baseId: string // TODO possibly, it should be readonly
  72. localRefs?: LocalRefs
  73. readonly meta?: boolean
  74. readonly $async?: boolean // true if the current schema is asynchronous.
  75. readonly refs: SchemaRefs = {}
  76. readonly dynamicAnchors: {[Ref in string]?: true} = {}
  77. validate?: AnyValidateFunction
  78. validateName?: ValueScopeName
  79. serialize?: (data: unknown) => string
  80. serializeName?: ValueScopeName
  81. parse?: (data: string) => unknown
  82. parseName?: ValueScopeName
  83. constructor(env: SchemaEnvArgs) {
  84. let schema: AnySchemaObject | undefined
  85. if (typeof env.schema == "object") schema = env.schema
  86. this.schema = env.schema
  87. this.root = env.root || this
  88. this.baseId = env.baseId ?? normalizeId(schema?.$id)
  89. this.localRefs = env.localRefs
  90. this.meta = env.meta
  91. this.$async = schema?.$async
  92. this.refs = {}
  93. }
  94. }
  95. // let codeSize = 0
  96. // let nodeCount = 0
  97. // Compiles schema in SchemaEnv
  98. export function compileSchema(this: Ajv, sch: SchemaEnv): SchemaEnv {
  99. // TODO refactor - remove compilations
  100. const _sch = getCompilingSchema.call(this, sch)
  101. if (_sch) return _sch
  102. const rootId = getFullPath(sch.root.baseId) // TODO if getFullPath removed 1 tests fails
  103. const {es5, lines} = this.opts.code
  104. const {ownProperties} = this.opts
  105. const gen = new CodeGen(this.scope, {es5, lines, ownProperties})
  106. let _ValidationError
  107. if (sch.$async) {
  108. _ValidationError = gen.scopeValue("Error", {
  109. ref: ValidationError,
  110. code: _`require("ajv/dist/compile/error_classes").ValidationError`,
  111. })
  112. }
  113. const validateName = gen.scopeName("validate")
  114. sch.validateName = validateName
  115. const schemaCxt: SchemaCxt = {
  116. gen,
  117. allErrors: this.opts.allErrors,
  118. data: N.data,
  119. parentData: N.parentData,
  120. parentDataProperty: N.parentDataProperty,
  121. dataNames: [N.data],
  122. dataPathArr: [nil], // TODO can its length be used as dataLevel if nil is removed?
  123. dataLevel: 0,
  124. dataTypes: [],
  125. definedProperties: new Set<string>(),
  126. topSchemaRef: gen.scopeValue(
  127. "schema",
  128. this.opts.code.source === true
  129. ? {ref: sch.schema, code: stringify(sch.schema)}
  130. : {ref: sch.schema}
  131. ),
  132. validateName,
  133. ValidationError: _ValidationError,
  134. schema: sch.schema,
  135. schemaEnv: sch,
  136. rootId,
  137. baseId: sch.baseId || rootId,
  138. schemaPath: nil,
  139. errSchemaPath: this.opts.jtd ? "" : "#",
  140. errorPath: _`""`,
  141. opts: this.opts,
  142. self: this,
  143. }
  144. let sourceCode: string | undefined
  145. try {
  146. this._compilations.add(sch)
  147. validateFunctionCode(schemaCxt)
  148. gen.optimize(this.opts.code.optimize)
  149. // gen.optimize(1)
  150. const validateCode = gen.toString()
  151. sourceCode = `${gen.scopeRefs(N.scope)}return ${validateCode}`
  152. // console.log((codeSize += sourceCode.length), (nodeCount += gen.nodeCount))
  153. if (this.opts.code.process) sourceCode = this.opts.code.process(sourceCode, sch)
  154. // console.log("\n\n\n *** \n", sourceCode)
  155. const makeValidate = new Function(`${N.self}`, `${N.scope}`, sourceCode)
  156. const validate: AnyValidateFunction = makeValidate(this, this.scope.get())
  157. this.scope.value(validateName, {ref: validate})
  158. validate.errors = null
  159. validate.schema = sch.schema
  160. validate.schemaEnv = sch
  161. if (sch.$async) (validate as AsyncValidateFunction).$async = true
  162. if (this.opts.code.source === true) {
  163. validate.source = {validateName, validateCode, scopeValues: gen._values}
  164. }
  165. if (this.opts.unevaluated) {
  166. const {props, items} = schemaCxt
  167. validate.evaluated = {
  168. props: props instanceof Name ? undefined : props,
  169. items: items instanceof Name ? undefined : items,
  170. dynamicProps: props instanceof Name,
  171. dynamicItems: items instanceof Name,
  172. }
  173. if (validate.source) validate.source.evaluated = stringify(validate.evaluated)
  174. }
  175. sch.validate = validate
  176. return sch
  177. } catch (e) {
  178. delete sch.validate
  179. delete sch.validateName
  180. if (sourceCode) this.logger.error("Error compiling schema, function code:", sourceCode)
  181. // console.log("\n\n\n *** \n", sourceCode, this.opts)
  182. throw e
  183. } finally {
  184. this._compilations.delete(sch)
  185. }
  186. }
  187. export function resolveRef(
  188. this: Ajv,
  189. root: SchemaEnv,
  190. baseId: string,
  191. ref: string
  192. ): AnySchema | SchemaEnv | undefined {
  193. ref = resolveUrl(baseId, ref)
  194. const schOrFunc = root.refs[ref]
  195. if (schOrFunc) return schOrFunc
  196. let _sch = resolve.call(this, root, ref)
  197. if (_sch === undefined) {
  198. const schema = root.localRefs?.[ref] // TODO maybe localRefs should hold SchemaEnv
  199. if (schema) _sch = new SchemaEnv({schema, root, baseId})
  200. }
  201. if (_sch === undefined) return
  202. return (root.refs[ref] = inlineOrCompile.call(this, _sch))
  203. }
  204. function inlineOrCompile(this: Ajv, sch: SchemaEnv): AnySchema | SchemaEnv {
  205. if (inlineRef(sch.schema, this.opts.inlineRefs)) return sch.schema
  206. return sch.validate ? sch : compileSchema.call(this, sch)
  207. }
  208. // Index of schema compilation in the currently compiled list
  209. export function getCompilingSchema(this: Ajv, schEnv: SchemaEnv): SchemaEnv | void {
  210. for (const sch of this._compilations) {
  211. if (sameSchemaEnv(sch, schEnv)) return sch
  212. }
  213. }
  214. function sameSchemaEnv(s1: SchemaEnv, s2: SchemaEnv): boolean {
  215. return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId
  216. }
  217. // resolve and compile the references ($ref)
  218. // TODO returns AnySchemaObject (if the schema can be inlined) or validation function
  219. function resolve(
  220. this: Ajv,
  221. root: SchemaEnv, // information about the root schema for the current schema
  222. ref: string // reference to resolve
  223. ): SchemaEnv | undefined {
  224. let sch
  225. while (typeof (sch = this.refs[ref]) == "string") ref = sch
  226. return sch || this.schemas[ref] || resolveSchema.call(this, root, ref)
  227. }
  228. // Resolve schema, its root and baseId
  229. export function resolveSchema(
  230. this: Ajv,
  231. root: SchemaEnv, // root object with properties schema, refs TODO below SchemaEnv is assigned to it
  232. ref: string // reference to resolve
  233. ): SchemaEnv | undefined {
  234. const p = URI.parse(ref)
  235. const refPath = _getFullPath(p)
  236. let baseId = getFullPath(root.baseId)
  237. // TODO `Object.keys(root.schema).length > 0` should not be needed - but removing breaks 2 tests
  238. if (Object.keys(root.schema).length > 0 && refPath === baseId) {
  239. return getJsonPointer.call(this, p, root)
  240. }
  241. const id = normalizeId(refPath)
  242. const schOrRef = this.refs[id] || this.schemas[id]
  243. if (typeof schOrRef == "string") {
  244. const sch = resolveSchema.call(this, root, schOrRef)
  245. if (typeof sch?.schema !== "object") return
  246. return getJsonPointer.call(this, p, sch)
  247. }
  248. if (typeof schOrRef?.schema !== "object") return
  249. if (!schOrRef.validate) compileSchema.call(this, schOrRef)
  250. if (id === normalizeId(ref)) {
  251. const {schema} = schOrRef
  252. if (schema.$id) baseId = resolveUrl(baseId, schema.$id)
  253. return new SchemaEnv({schema, root, baseId})
  254. }
  255. return getJsonPointer.call(this, p, schOrRef)
  256. }
  257. const PREVENT_SCOPE_CHANGE = new Set([
  258. "properties",
  259. "patternProperties",
  260. "enum",
  261. "dependencies",
  262. "definitions",
  263. ])
  264. function getJsonPointer(
  265. this: Ajv,
  266. parsedRef: URI.URIComponents,
  267. {baseId, schema, root}: SchemaEnv
  268. ): SchemaEnv | undefined {
  269. if (parsedRef.fragment?.[0] !== "/") return
  270. for (const part of parsedRef.fragment.slice(1).split("/")) {
  271. if (typeof schema == "boolean") return
  272. schema = schema[unescapeFragment(part)]
  273. if (schema === undefined) return
  274. // TODO PREVENT_SCOPE_CHANGE could be defined in keyword def?
  275. if (!PREVENT_SCOPE_CHANGE.has(part) && typeof schema == "object" && schema.$id) {
  276. baseId = resolveUrl(baseId, schema.$id)
  277. }
  278. }
  279. let env: SchemaEnv | undefined
  280. if (typeof schema != "boolean" && schema.$ref && !schemaHasRulesButRef(schema, this.RULES)) {
  281. const $ref = resolveUrl(baseId, schema.$ref)
  282. env = resolveSchema.call(this, root, $ref)
  283. }
  284. // even though resolution failed we need to return SchemaEnv to throw exception
  285. // so that compileAsync loads missing schema.
  286. env = env || new SchemaEnv({schema, root, baseId})
  287. if (env.schema !== env.root.schema) return env
  288. return undefined
  289. }