context.ts 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. import type {
  2. AddedKeywordDefinition,
  3. KeywordErrorCxt,
  4. KeywordCxtParams,
  5. AnySchemaObject,
  6. } from "../types"
  7. import {SchemaCxt, SchemaObjCxt} from "./index"
  8. import {JSONType} from "./rules"
  9. import {checkDataTypes, DataType} from "./validate/dataType"
  10. import {schemaRefOrVal, unescapeJsonPointer, mergeEvaluated} from "./util"
  11. import {
  12. reportError,
  13. reportExtraError,
  14. resetErrorsCount,
  15. keywordError,
  16. keyword$DataError,
  17. } from "./errors"
  18. import {CodeGen, _, nil, or, not, getProperty, Code, Name} from "./codegen"
  19. import N from "./names"
  20. import {applySubschema, SubschemaArgs} from "./subschema"
  21. export default class KeywordCxt implements KeywordErrorCxt {
  22. readonly gen: CodeGen
  23. readonly allErrors?: boolean
  24. readonly keyword: string
  25. readonly data: Name // Name referencing the current level of the data instance
  26. readonly $data?: string | false
  27. readonly schema: any // keyword value in the schema
  28. readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value
  29. readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data)
  30. readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema
  31. readonly parentSchema: AnySchemaObject
  32. readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword,
  33. // requires option trackErrors in keyword definition
  34. params: KeywordCxtParams // object to pass parameters to error messages from keyword code
  35. readonly it: SchemaObjCxt // schema compilation context (schema is guaranted to be an object, not boolean)
  36. readonly def: AddedKeywordDefinition
  37. constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) {
  38. validateKeywordUsage(it, def, keyword)
  39. this.gen = it.gen
  40. this.allErrors = it.allErrors
  41. this.keyword = keyword
  42. this.data = it.data
  43. this.schema = it.schema[keyword]
  44. this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data
  45. this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data)
  46. this.schemaType = def.schemaType
  47. this.parentSchema = it.schema
  48. this.params = {}
  49. this.it = it
  50. this.def = def
  51. if (this.$data) {
  52. this.schemaCode = it.gen.const("vSchema", getData(this.$data, it))
  53. } else {
  54. this.schemaCode = this.schemaValue
  55. if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) {
  56. throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`)
  57. }
  58. }
  59. if ("code" in def ? def.trackErrors : def.errors !== false) {
  60. this.errsCount = it.gen.const("_errs", N.errors)
  61. }
  62. }
  63. result(condition: Code, successAction?: () => void, failAction?: () => void): void {
  64. this.gen.if(not(condition))
  65. if (failAction) failAction()
  66. else this.error()
  67. if (successAction) {
  68. this.gen.else()
  69. successAction()
  70. if (this.allErrors) this.gen.endIf()
  71. } else {
  72. if (this.allErrors) this.gen.endIf()
  73. else this.gen.else()
  74. }
  75. }
  76. pass(condition: Code, failAction?: () => void): void {
  77. this.result(condition, undefined, failAction)
  78. }
  79. fail(condition?: Code): void {
  80. if (condition === undefined) {
  81. this.error()
  82. if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize
  83. return
  84. }
  85. this.gen.if(condition)
  86. this.error()
  87. if (this.allErrors) this.gen.endIf()
  88. else this.gen.else()
  89. }
  90. fail$data(condition: Code): void {
  91. if (!this.$data) return this.fail(condition)
  92. const {schemaCode} = this
  93. this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`)
  94. }
  95. error(append?: true): void {
  96. ;(append ? reportExtraError : reportError)(this, this.def.error || keywordError)
  97. }
  98. $dataError(): void {
  99. reportError(this, this.def.$dataError || keyword$DataError)
  100. }
  101. reset(): void {
  102. if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition')
  103. resetErrorsCount(this.gen, this.errsCount)
  104. }
  105. ok(cond: Code | boolean): void {
  106. if (!this.allErrors) this.gen.if(cond)
  107. }
  108. setParams(obj: KeywordCxtParams, assign?: true): void {
  109. if (assign) Object.assign(this.params, obj)
  110. else this.params = obj
  111. }
  112. block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void {
  113. this.gen.block(() => {
  114. this.check$data(valid, $dataValid)
  115. codeBlock()
  116. })
  117. }
  118. check$data(valid: Name = nil, $dataValid: Code = nil): void {
  119. if (!this.$data) return
  120. const {gen, schemaCode, schemaType, def} = this
  121. gen.if(or(_`${schemaCode} === undefined`, $dataValid))
  122. if (valid !== nil) gen.assign(valid, true)
  123. if (schemaType.length || def.validateSchema) {
  124. gen.elseIf(this.invalid$data())
  125. this.$dataError()
  126. if (valid !== nil) gen.assign(valid, false)
  127. }
  128. gen.else()
  129. }
  130. invalid$data(): Code {
  131. const {gen, schemaCode, schemaType, def, it} = this
  132. return or(wrong$DataType(), invalid$DataSchema())
  133. function wrong$DataType(): Code {
  134. if (schemaType.length) {
  135. /* istanbul ignore if */
  136. if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error")
  137. const st = Array.isArray(schemaType) ? schemaType : [schemaType]
  138. return _`${checkDataTypes(st, schemaCode, it.opts.strict, DataType.Wrong)}`
  139. }
  140. return nil
  141. }
  142. function invalid$DataSchema(): Code {
  143. if (def.validateSchema) {
  144. const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone
  145. return _`!${validateSchemaRef}(${schemaCode})`
  146. }
  147. return nil
  148. }
  149. }
  150. subschema(appl: SubschemaArgs, valid: Name): SchemaCxt {
  151. return applySubschema(this.it, appl, valid)
  152. }
  153. mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void {
  154. const {it, gen} = this
  155. if (!it.opts.unevaluated) return
  156. if (it.props !== true && schemaCxt.props !== undefined) {
  157. it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName)
  158. }
  159. if (it.items !== true && schemaCxt.items !== undefined) {
  160. it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName)
  161. }
  162. }
  163. mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void {
  164. const {it, gen} = this
  165. if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
  166. gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name))
  167. return true
  168. }
  169. }
  170. }
  171. function validSchemaType(schema: unknown, schemaType: JSONType[], allowUndefined = false): boolean {
  172. // TODO add tests
  173. return (
  174. !schemaType.length ||
  175. schemaType.some((st) =>
  176. st === "array"
  177. ? Array.isArray(schema)
  178. : st === "object"
  179. ? schema && typeof schema == "object" && !Array.isArray(schema)
  180. : typeof schema == st || (allowUndefined && typeof schema == "undefined")
  181. )
  182. )
  183. }
  184. function validateKeywordUsage(
  185. {schema, opts, self}: SchemaObjCxt,
  186. def: AddedKeywordDefinition,
  187. keyword: string
  188. ): void {
  189. /* istanbul ignore if */
  190. if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {
  191. throw new Error("ajv implementation error")
  192. }
  193. const deps = def.dependencies
  194. if (deps?.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {
  195. throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`)
  196. }
  197. if (def.validateSchema) {
  198. const valid = def.validateSchema(schema[keyword])
  199. if (!valid) {
  200. const msg = "keyword value is invalid: " + self.errorsText(def.validateSchema.errors)
  201. if (opts.validateSchema === "log") self.logger.error(msg)
  202. else throw new Error(msg)
  203. }
  204. }
  205. }
  206. const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/
  207. const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/
  208. export function getData(
  209. $data: string,
  210. {dataLevel, dataNames, dataPathArr}: SchemaCxt
  211. ): Code | number {
  212. let jsonPointer
  213. let data: Code
  214. if ($data === "") return N.rootData
  215. if ($data[0] === "/") {
  216. if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`)
  217. jsonPointer = $data
  218. data = N.rootData
  219. } else {
  220. const matches = RELATIVE_JSON_POINTER.exec($data)
  221. if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`)
  222. const up: number = +matches[1]
  223. jsonPointer = matches[2]
  224. if (jsonPointer === "#") {
  225. if (up >= dataLevel) throw new Error(errorMsg("property/index", up))
  226. return dataPathArr[dataLevel - up]
  227. }
  228. if (up > dataLevel) throw new Error(errorMsg("data", up))
  229. data = dataNames[dataLevel - up]
  230. if (!jsonPointer) return data
  231. }
  232. let expr = data
  233. const segments = jsonPointer.split("/")
  234. for (const segment of segments) {
  235. if (segment) {
  236. data = _`${data}${getProperty(unescapeJsonPointer(segment))}`
  237. expr = _`${expr} && ${data}`
  238. }
  239. }
  240. return expr
  241. function errorMsg(pointerType: string, up: number): string {
  242. return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`
  243. }
  244. }