.gitignore added
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-prettier / node_modules / table / node_modules / ajv / lib / compile / validate / index.ts
1 import type {
2   AddedKeywordDefinition,
3   AnySchema,
4   AnySchemaObject,
5   KeywordErrorCxt,
6   KeywordCxtParams,
7 } from "../../types"
8 import type {SchemaCxt, SchemaObjCxt} from ".."
9 import type {InstanceOptions} from "../../core"
10 import {boolOrEmptySchema, topBoolOrEmptySchema} from "./boolSchema"
11 import {coerceAndCheckDataType, getSchemaTypes} from "./dataType"
12 import {shouldUseGroup, shouldUseRule} from "./applicability"
13 import {checkDataType, checkDataTypes, reportTypeError, DataType} from "./dataType"
14 import {assignDefaults} from "./defaults"
15 import {funcKeywordCode, macroKeywordCode, validateKeywordUsage, validSchemaType} from "./keyword"
16 import {getSubschema, extendSubschemaData, SubschemaArgs, extendSubschemaMode} from "./subschema"
17 import {_, nil, str, or, not, getProperty, Block, Code, Name, CodeGen} from "../codegen"
18 import N from "../names"
19 import {resolveUrl} from "../resolve"
20 import {
21   schemaRefOrVal,
22   schemaHasRulesButRef,
23   checkUnknownRules,
24   checkStrictMode,
25   unescapeJsonPointer,
26   mergeEvaluated,
27 } from "../util"
28 import type {JSONType, Rule, RuleGroup} from "../rules"
29 import {
30   ErrorPaths,
31   reportError,
32   reportExtraError,
33   resetErrorsCount,
34   keyword$DataError,
35 } from "../errors"
36
37 // schema compilation - generates validation function, subschemaCode (below) is used for subschemas
38 export function validateFunctionCode(it: SchemaCxt): void {
39   if (isSchemaObj(it)) {
40     checkKeywords(it)
41     if (schemaCxtHasRules(it)) {
42       topSchemaObjCode(it)
43       return
44     }
45   }
46   validateFunction(it, () => topBoolOrEmptySchema(it))
47 }
48
49 function validateFunction(
50   {gen, validateName, schema, schemaEnv, opts}: SchemaCxt,
51   body: Block
52 ): void {
53   if (opts.code.es5) {
54     gen.func(validateName, _`${N.data}, ${N.valCxt}`, schemaEnv.$async, () => {
55       gen.code(_`"use strict"; ${funcSourceUrl(schema, opts)}`)
56       destructureValCxtES5(gen, opts)
57       gen.code(body)
58     })
59   } else {
60     gen.func(validateName, _`${N.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () =>
61       gen.code(funcSourceUrl(schema, opts)).code(body)
62     )
63   }
64 }
65
66 function destructureValCxt(opts: InstanceOptions): Code {
67   return _`{${N.instancePath}="", ${N.parentData}, ${N.parentDataProperty}, ${N.rootData}=${
68     N.data
69   }${opts.dynamicRef ? _`, ${N.dynamicAnchors}={}` : nil}}={}`
70 }
71
72 function destructureValCxtES5(gen: CodeGen, opts: InstanceOptions): void {
73   gen.if(
74     N.valCxt,
75     () => {
76       gen.var(N.instancePath, _`${N.valCxt}.${N.instancePath}`)
77       gen.var(N.parentData, _`${N.valCxt}.${N.parentData}`)
78       gen.var(N.parentDataProperty, _`${N.valCxt}.${N.parentDataProperty}`)
79       gen.var(N.rootData, _`${N.valCxt}.${N.rootData}`)
80       if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`${N.valCxt}.${N.dynamicAnchors}`)
81     },
82     () => {
83       gen.var(N.instancePath, _`""`)
84       gen.var(N.parentData, _`undefined`)
85       gen.var(N.parentDataProperty, _`undefined`)
86       gen.var(N.rootData, N.data)
87       if (opts.dynamicRef) gen.var(N.dynamicAnchors, _`{}`)
88     }
89   )
90 }
91
92 function topSchemaObjCode(it: SchemaObjCxt): void {
93   const {schema, opts, gen} = it
94   validateFunction(it, () => {
95     if (opts.$comment && schema.$comment) commentKeyword(it)
96     checkNoDefault(it)
97     gen.let(N.vErrors, null)
98     gen.let(N.errors, 0)
99     if (opts.unevaluated) resetEvaluated(it)
100     typeAndKeywords(it)
101     returnResults(it)
102   })
103   return
104 }
105
106 function resetEvaluated(it: SchemaObjCxt): void {
107   // TODO maybe some hook to execute it in the end to check whether props/items are Name, as in assignEvaluated
108   const {gen, validateName} = it
109   it.evaluated = gen.const("evaluated", _`${validateName}.evaluated`)
110   gen.if(_`${it.evaluated}.dynamicProps`, () => gen.assign(_`${it.evaluated}.props`, _`undefined`))
111   gen.if(_`${it.evaluated}.dynamicItems`, () => gen.assign(_`${it.evaluated}.items`, _`undefined`))
112 }
113
114 function funcSourceUrl(schema: AnySchema, opts: InstanceOptions): Code {
115   return typeof schema == "object" && schema.$id && (opts.code.source || opts.code.process)
116     ? _`/*# sourceURL=${schema.$id} */`
117     : nil
118 }
119
120 // schema compilation - this function is used recursively to generate code for sub-schemas
121 function subschemaCode(it: SchemaCxt, valid: Name): void {
122   if (isSchemaObj(it)) {
123     checkKeywords(it)
124     if (schemaCxtHasRules(it)) {
125       subSchemaObjCode(it, valid)
126       return
127     }
128   }
129   boolOrEmptySchema(it, valid)
130 }
131
132 function schemaCxtHasRules({schema, self}: SchemaCxt): boolean {
133   if (typeof schema == "boolean") return !schema
134   for (const key in schema) if (self.RULES.all[key]) return true
135   return false
136 }
137
138 function isSchemaObj(it: SchemaCxt): it is SchemaObjCxt {
139   return typeof it.schema != "boolean"
140 }
141
142 function subSchemaObjCode(it: SchemaObjCxt, valid: Name): void {
143   const {schema, gen, opts} = it
144   if (opts.$comment && schema.$comment) commentKeyword(it)
145   updateContext(it)
146   checkAsyncSchema(it)
147   const errsCount = gen.const("_errs", N.errors)
148   typeAndKeywords(it, errsCount)
149   // TODO var
150   gen.var(valid, _`${errsCount} === ${N.errors}`)
151 }
152
153 function checkKeywords(it: SchemaObjCxt): void {
154   checkUnknownRules(it)
155   checkRefsAndKeywords(it)
156 }
157
158 function typeAndKeywords(it: SchemaObjCxt, errsCount?: Name): void {
159   if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount)
160   const types = getSchemaTypes(it.schema)
161   const checkedTypes = coerceAndCheckDataType(it, types)
162   schemaKeywords(it, types, !checkedTypes, errsCount)
163 }
164
165 function checkRefsAndKeywords(it: SchemaObjCxt): void {
166   const {schema, errSchemaPath, opts, self} = it
167   if (schema.$ref && opts.ignoreKeywordsWithRef && schemaHasRulesButRef(schema, self.RULES)) {
168     self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`)
169   }
170 }
171
172 function checkNoDefault(it: SchemaObjCxt): void {
173   const {schema, opts} = it
174   if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) {
175     checkStrictMode(it, "default is ignored in the schema root")
176   }
177 }
178
179 function updateContext(it: SchemaObjCxt): void {
180   if (it.schema.$id) it.baseId = resolveUrl(it.baseId, it.schema.$id)
181 }
182
183 function checkAsyncSchema(it: SchemaObjCxt): void {
184   if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema")
185 }
186
187 function commentKeyword({gen, schemaEnv, schema, errSchemaPath, opts}: SchemaObjCxt): void {
188   const msg = schema.$comment
189   if (opts.$comment === true) {
190     gen.code(_`${N.self}.logger.log(${msg})`)
191   } else if (typeof opts.$comment == "function") {
192     const schemaPath = str`${errSchemaPath}/$comment`
193     const rootName = gen.scopeValue("root", {ref: schemaEnv.root})
194     gen.code(_`${N.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`)
195   }
196 }
197
198 function returnResults(it: SchemaCxt): void {
199   const {gen, schemaEnv, validateName, ValidationError, opts} = it
200   if (schemaEnv.$async) {
201     // TODO assign unevaluated
202     gen.if(
203       _`${N.errors} === 0`,
204       () => gen.return(N.data),
205       () => gen.throw(_`new ${ValidationError as Name}(${N.vErrors})`)
206     )
207   } else {
208     gen.assign(_`${validateName}.errors`, N.vErrors)
209     if (opts.unevaluated) assignEvaluated(it)
210     gen.return(_`${N.errors} === 0`)
211   }
212 }
213
214 function assignEvaluated({gen, evaluated, props, items}: SchemaCxt): void {
215   if (props instanceof Name) gen.assign(_`${evaluated}.props`, props)
216   if (items instanceof Name) gen.assign(_`${evaluated}.items`, items)
217 }
218
219 function schemaKeywords(
220   it: SchemaObjCxt,
221   types: JSONType[],
222   typeErrors: boolean,
223   errsCount?: Name
224 ): void {
225   const {gen, schema, data, allErrors, opts, self} = it
226   const {RULES} = self
227   if (schema.$ref && (opts.ignoreKeywordsWithRef || !schemaHasRulesButRef(schema, RULES))) {
228     gen.block(() => keywordCode(it, "$ref", (RULES.all.$ref as Rule).definition)) // TODO typecast
229     return
230   }
231   if (!opts.jtd) checkStrictTypes(it, types)
232   gen.block(() => {
233     for (const group of RULES.rules) groupKeywords(group)
234     groupKeywords(RULES.post)
235   })
236
237   function groupKeywords(group: RuleGroup): void {
238     if (!shouldUseGroup(schema, group)) return
239     if (group.type) {
240       gen.if(checkDataType(group.type, data, opts.strictNumbers))
241       iterateKeywords(it, group)
242       if (types.length === 1 && types[0] === group.type && typeErrors) {
243         gen.else()
244         reportTypeError(it)
245       }
246       gen.endIf()
247     } else {
248       iterateKeywords(it, group)
249     }
250     // TODO make it "ok" call?
251     if (!allErrors) gen.if(_`${N.errors} === ${errsCount || 0}`)
252   }
253 }
254
255 function iterateKeywords(it: SchemaObjCxt, group: RuleGroup): void {
256   const {
257     gen,
258     schema,
259     opts: {useDefaults},
260   } = it
261   if (useDefaults) assignDefaults(it, group.type)
262   gen.block(() => {
263     for (const rule of group.rules) {
264       if (shouldUseRule(schema, rule)) {
265         keywordCode(it, rule.keyword, rule.definition, group.type)
266       }
267     }
268   })
269 }
270
271 function checkStrictTypes(it: SchemaObjCxt, types: JSONType[]): void {
272   if (it.schemaEnv.meta || !it.opts.strictTypes) return
273   checkContextTypes(it, types)
274   if (!it.opts.allowUnionTypes) checkMultipleTypes(it, types)
275   checkKeywordTypes(it, it.dataTypes)
276 }
277
278 function checkContextTypes(it: SchemaObjCxt, types: JSONType[]): void {
279   if (!types.length) return
280   if (!it.dataTypes.length) {
281     it.dataTypes = types
282     return
283   }
284   types.forEach((t) => {
285     if (!includesType(it.dataTypes, t)) {
286       strictTypesError(it, `type "${t}" not allowed by context "${it.dataTypes.join(",")}"`)
287     }
288   })
289   it.dataTypes = it.dataTypes.filter((t) => includesType(types, t))
290 }
291
292 function checkMultipleTypes(it: SchemaObjCxt, ts: JSONType[]): void {
293   if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
294     strictTypesError(it, "use allowUnionTypes to allow union type keyword")
295   }
296 }
297
298 function checkKeywordTypes(it: SchemaObjCxt, ts: JSONType[]): void {
299   const rules = it.self.RULES.all
300   for (const keyword in rules) {
301     const rule = rules[keyword]
302     if (typeof rule == "object" && shouldUseRule(it.schema, rule)) {
303       const {type} = rule.definition
304       if (type.length && !type.some((t) => hasApplicableType(ts, t))) {
305         strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`)
306       }
307     }
308   }
309 }
310
311 function hasApplicableType(schTs: JSONType[], kwdT: JSONType): boolean {
312   return schTs.includes(kwdT) || (kwdT === "number" && schTs.includes("integer"))
313 }
314
315 function includesType(ts: JSONType[], t: JSONType): boolean {
316   return ts.includes(t) || (t === "integer" && ts.includes("number"))
317 }
318
319 function strictTypesError(it: SchemaObjCxt, msg: string): void {
320   const schemaPath = it.schemaEnv.baseId + it.errSchemaPath
321   msg += ` at "${schemaPath}" (strictTypes)`
322   checkStrictMode(it, msg, it.opts.strictTypes)
323 }
324
325 export class KeywordCxt implements KeywordErrorCxt {
326   readonly gen: CodeGen
327   readonly allErrors?: boolean
328   readonly keyword: string
329   readonly data: Name // Name referencing the current level of the data instance
330   readonly $data?: string | false
331   schema: any // keyword value in the schema
332   readonly schemaValue: Code | number | boolean // Code reference to keyword schema value or primitive value
333   readonly schemaCode: Code | number | boolean // Code reference to resolved schema value (different if schema is $data)
334   readonly schemaType: JSONType[] // allowed type(s) of keyword value in the schema
335   readonly parentSchema: AnySchemaObject
336   readonly errsCount?: Name // Name reference to the number of validation errors collected before this keyword,
337   // requires option trackErrors in keyword definition
338   params: KeywordCxtParams // object to pass parameters to error messages from keyword code
339   readonly it: SchemaObjCxt // schema compilation context (schema is guaranteed to be an object, not boolean)
340   readonly def: AddedKeywordDefinition
341
342   constructor(it: SchemaObjCxt, def: AddedKeywordDefinition, keyword: string) {
343     validateKeywordUsage(it, def, keyword)
344     this.gen = it.gen
345     this.allErrors = it.allErrors
346     this.keyword = keyword
347     this.data = it.data
348     this.schema = it.schema[keyword]
349     this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data
350     this.schemaValue = schemaRefOrVal(it, this.schema, keyword, this.$data)
351     this.schemaType = def.schemaType
352     this.parentSchema = it.schema
353     this.params = {}
354     this.it = it
355     this.def = def
356
357     if (this.$data) {
358       this.schemaCode = it.gen.const("vSchema", getData(this.$data, it))
359     } else {
360       this.schemaCode = this.schemaValue
361       if (!validSchemaType(this.schema, def.schemaType, def.allowUndefined)) {
362         throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`)
363       }
364     }
365
366     if ("code" in def ? def.trackErrors : def.errors !== false) {
367       this.errsCount = it.gen.const("_errs", N.errors)
368     }
369   }
370
371   result(condition: Code, successAction?: () => void, failAction?: () => void): void {
372     this.gen.if(not(condition))
373     if (failAction) failAction()
374     else this.error()
375     if (successAction) {
376       this.gen.else()
377       successAction()
378       if (this.allErrors) this.gen.endIf()
379     } else {
380       if (this.allErrors) this.gen.endIf()
381       else this.gen.else()
382     }
383   }
384
385   pass(condition: Code, failAction?: () => void): void {
386     this.result(condition, undefined, failAction)
387   }
388
389   fail(condition?: Code): void {
390     if (condition === undefined) {
391       this.error()
392       if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize
393       return
394     }
395     this.gen.if(condition)
396     this.error()
397     if (this.allErrors) this.gen.endIf()
398     else this.gen.else()
399   }
400
401   fail$data(condition: Code): void {
402     if (!this.$data) return this.fail(condition)
403     const {schemaCode} = this
404     this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`)
405   }
406
407   error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void {
408     if (errorParams) {
409       this.setParams(errorParams)
410       this._error(append, errorPaths)
411       this.setParams({})
412       return
413     }
414     this._error(append, errorPaths)
415   }
416
417   private _error(append?: boolean, errorPaths?: ErrorPaths): void {
418     ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths)
419   }
420
421   $dataError(): void {
422     reportError(this, this.def.$dataError || keyword$DataError)
423   }
424
425   reset(): void {
426     if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition')
427     resetErrorsCount(this.gen, this.errsCount)
428   }
429
430   ok(cond: Code | boolean): void {
431     if (!this.allErrors) this.gen.if(cond)
432   }
433
434   setParams(obj: KeywordCxtParams, assign?: true): void {
435     if (assign) Object.assign(this.params, obj)
436     else this.params = obj
437   }
438
439   block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void {
440     this.gen.block(() => {
441       this.check$data(valid, $dataValid)
442       codeBlock()
443     })
444   }
445
446   check$data(valid: Name = nil, $dataValid: Code = nil): void {
447     if (!this.$data) return
448     const {gen, schemaCode, schemaType, def} = this
449     gen.if(or(_`${schemaCode} === undefined`, $dataValid))
450     if (valid !== nil) gen.assign(valid, true)
451     if (schemaType.length || def.validateSchema) {
452       gen.elseIf(this.invalid$data())
453       this.$dataError()
454       if (valid !== nil) gen.assign(valid, false)
455     }
456     gen.else()
457   }
458
459   invalid$data(): Code {
460     const {gen, schemaCode, schemaType, def, it} = this
461     return or(wrong$DataType(), invalid$DataSchema())
462
463     function wrong$DataType(): Code {
464       if (schemaType.length) {
465         /* istanbul ignore if */
466         if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error")
467         const st = Array.isArray(schemaType) ? schemaType : [schemaType]
468         return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}`
469       }
470       return nil
471     }
472
473     function invalid$DataSchema(): Code {
474       if (def.validateSchema) {
475         const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone
476         return _`!${validateSchemaRef}(${schemaCode})`
477       }
478       return nil
479     }
480   }
481
482   subschema(appl: SubschemaArgs, valid: Name): SchemaCxt {
483     const subschema = getSubschema(this.it, appl)
484     extendSubschemaData(subschema, this.it, appl)
485     extendSubschemaMode(subschema, appl)
486     const nextContext = {...this.it, ...subschema, items: undefined, props: undefined}
487     subschemaCode(nextContext, valid)
488     return nextContext
489   }
490
491   mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void {
492     const {it, gen} = this
493     if (!it.opts.unevaluated) return
494     if (it.props !== true && schemaCxt.props !== undefined) {
495       it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName)
496     }
497     if (it.items !== true && schemaCxt.items !== undefined) {
498       it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName)
499     }
500   }
501
502   mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void {
503     const {it, gen} = this
504     if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
505       gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name))
506       return true
507     }
508   }
509 }
510
511 function keywordCode(
512   it: SchemaObjCxt,
513   keyword: string,
514   def: AddedKeywordDefinition,
515   ruleType?: JSONType
516 ): void {
517   const cxt = new KeywordCxt(it, def, keyword)
518   if ("code" in def) {
519     def.code(cxt, ruleType)
520   } else if (cxt.$data && def.validate) {
521     funcKeywordCode(cxt, def)
522   } else if ("macro" in def) {
523     macroKeywordCode(cxt, def)
524   } else if (def.compile || def.validate) {
525     funcKeywordCode(cxt, def)
526   }
527 }
528
529 const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/
530 const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/
531 export function getData(
532   $data: string,
533   {dataLevel, dataNames, dataPathArr}: SchemaCxt
534 ): Code | number {
535   let jsonPointer
536   let data: Code
537   if ($data === "") return N.rootData
538   if ($data[0] === "/") {
539     if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`)
540     jsonPointer = $data
541     data = N.rootData
542   } else {
543     const matches = RELATIVE_JSON_POINTER.exec($data)
544     if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`)
545     const up: number = +matches[1]
546     jsonPointer = matches[2]
547     if (jsonPointer === "#") {
548       if (up >= dataLevel) throw new Error(errorMsg("property/index", up))
549       return dataPathArr[dataLevel - up]
550     }
551     if (up > dataLevel) throw new Error(errorMsg("data", up))
552     data = dataNames[dataLevel - up]
553     if (!jsonPointer) return data
554   }
555
556   let expr = data
557   const segments = jsonPointer.split("/")
558   for (const segment of segments) {
559     if (segment) {
560       data = _`${data}${getProperty(unescapeJsonPointer(segment))}`
561       expr = _`${expr} && ${data}`
562     }
563   }
564   return expr
565
566   function errorMsg(pointerType: string, up: number): string {
567     return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`
568   }
569 }