context.ts 8.9 KB

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