UNPKG

19.2 kBPlain TextView Raw
1import type {
2 AddedKeywordDefinition,
3 AnySchema,
4 AnySchemaObject,
5 KeywordErrorCxt,
6 KeywordCxtParams,
7} from "../../types"
8import type {SchemaCxt, SchemaObjCxt} from ".."
9import type {InstanceOptions} from "../../core"
10import {boolOrEmptySchema, topBoolOrEmptySchema} from "./boolSchema"
11import {coerceAndCheckDataType, getSchemaTypes} from "./dataType"
12import {shouldUseGroup, shouldUseRule} from "./applicability"
13import {checkDataType, checkDataTypes, reportTypeError, DataType} from "./dataType"
14import {assignDefaults} from "./defaults"
15import {funcKeywordCode, macroKeywordCode, validateKeywordUsage, validSchemaType} from "./keyword"
16import {getSubschema, extendSubschemaData, SubschemaArgs, extendSubschemaMode} from "./subschema"
17import {_, nil, str, or, not, getProperty, Block, Code, Name, CodeGen} from "../codegen"
18import N from "../names"
19import {resolveUrl} from "../resolve"
20import {
21 schemaRefOrVal,
22 schemaHasRulesButRef,
23 checkUnknownRules,
24 checkStrictMode,
25 unescapeJsonPointer,
26 mergeEvaluated,
27} from "../util"
28import type {JSONType, Rule, RuleGroup} from "../rules"
29import {
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
38export 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
49function 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
66function 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
72function 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
92function 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
106function 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
114function funcSourceUrl(schema: AnySchema, opts: InstanceOptions): Code {
115 const schId = typeof schema == "object" && schema[opts.schemaId]
116 return schId && (opts.code.source || opts.code.process) ? _`/*# sourceURL=${schId} */` : nil
117}
118
119// schema compilation - this function is used recursively to generate code for sub-schemas
120function subschemaCode(it: SchemaCxt, valid: Name): void {
121 if (isSchemaObj(it)) {
122 checkKeywords(it)
123 if (schemaCxtHasRules(it)) {
124 subSchemaObjCode(it, valid)
125 return
126 }
127 }
128 boolOrEmptySchema(it, valid)
129}
130
131function schemaCxtHasRules({schema, self}: SchemaCxt): boolean {
132 if (typeof schema == "boolean") return !schema
133 for (const key in schema) if (self.RULES.all[key]) return true
134 return false
135}
136
137function isSchemaObj(it: SchemaCxt): it is SchemaObjCxt {
138 return typeof it.schema != "boolean"
139}
140
141function subSchemaObjCode(it: SchemaObjCxt, valid: Name): void {
142 const {schema, gen, opts} = it
143 if (opts.$comment && schema.$comment) commentKeyword(it)
144 updateContext(it)
145 checkAsyncSchema(it)
146 const errsCount = gen.const("_errs", N.errors)
147 typeAndKeywords(it, errsCount)
148 // TODO var
149 gen.var(valid, _`${errsCount} === ${N.errors}`)
150}
151
152function checkKeywords(it: SchemaObjCxt): void {
153 checkUnknownRules(it)
154 checkRefsAndKeywords(it)
155}
156
157function typeAndKeywords(it: SchemaObjCxt, errsCount?: Name): void {
158 if (it.opts.jtd) return schemaKeywords(it, [], false, errsCount)
159 const types = getSchemaTypes(it.schema)
160 const checkedTypes = coerceAndCheckDataType(it, types)
161 schemaKeywords(it, types, !checkedTypes, errsCount)
162}
163
164function checkRefsAndKeywords(it: SchemaObjCxt): void {
165 const {schema, errSchemaPath, opts, self} = it
166 if (schema.$ref && opts.ignoreKeywordsWithRef && schemaHasRulesButRef(schema, self.RULES)) {
167 self.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`)
168 }
169}
170
171function checkNoDefault(it: SchemaObjCxt): void {
172 const {schema, opts} = it
173 if (schema.default !== undefined && opts.useDefaults && opts.strictSchema) {
174 checkStrictMode(it, "default is ignored in the schema root")
175 }
176}
177
178function updateContext(it: SchemaObjCxt): void {
179 const schId = it.schema[it.opts.schemaId]
180 if (schId) it.baseId = resolveUrl(it.opts.uriResolver, it.baseId, schId)
181}
182
183function checkAsyncSchema(it: SchemaObjCxt): void {
184 if (it.schema.$async && !it.schemaEnv.$async) throw new Error("async schema in sync schema")
185}
186
187function 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
198function 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
214function 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
219function 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
255function 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
271function 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
278function 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
292function 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
298function 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
311function hasApplicableType(schTs: JSONType[], kwdT: JSONType): boolean {
312 return schTs.includes(kwdT) || (kwdT === "number" && schTs.includes("integer"))
313}
314
315function includesType(ts: JSONType[], t: JSONType): boolean {
316 return ts.includes(t) || (t === "integer" && ts.includes("number"))
317}
318
319function 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
325export 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.failResult(not(condition), successAction, failAction)
373 }
374
375 failResult(condition: Code, successAction?: () => void, failAction?: () => void): void {
376 this.gen.if(condition)
377 if (failAction) failAction()
378 else this.error()
379 if (successAction) {
380 this.gen.else()
381 successAction()
382 if (this.allErrors) this.gen.endIf()
383 } else {
384 if (this.allErrors) this.gen.endIf()
385 else this.gen.else()
386 }
387 }
388
389 pass(condition: Code, failAction?: () => void): void {
390 this.failResult(not(condition), undefined, failAction)
391 }
392
393 fail(condition?: Code): void {
394 if (condition === undefined) {
395 this.error()
396 if (!this.allErrors) this.gen.if(false) // this branch will be removed by gen.optimize
397 return
398 }
399 this.gen.if(condition)
400 this.error()
401 if (this.allErrors) this.gen.endIf()
402 else this.gen.else()
403 }
404
405 fail$data(condition: Code): void {
406 if (!this.$data) return this.fail(condition)
407 const {schemaCode} = this
408 this.fail(_`${schemaCode} !== undefined && (${or(this.invalid$data(), condition)})`)
409 }
410
411 error(append?: boolean, errorParams?: KeywordCxtParams, errorPaths?: ErrorPaths): void {
412 if (errorParams) {
413 this.setParams(errorParams)
414 this._error(append, errorPaths)
415 this.setParams({})
416 return
417 }
418 this._error(append, errorPaths)
419 }
420
421 private _error(append?: boolean, errorPaths?: ErrorPaths): void {
422 ;(append ? reportExtraError : reportError)(this, this.def.error, errorPaths)
423 }
424
425 $dataError(): void {
426 reportError(this, this.def.$dataError || keyword$DataError)
427 }
428
429 reset(): void {
430 if (this.errsCount === undefined) throw new Error('add "trackErrors" to keyword definition')
431 resetErrorsCount(this.gen, this.errsCount)
432 }
433
434 ok(cond: Code | boolean): void {
435 if (!this.allErrors) this.gen.if(cond)
436 }
437
438 setParams(obj: KeywordCxtParams, assign?: true): void {
439 if (assign) Object.assign(this.params, obj)
440 else this.params = obj
441 }
442
443 block$data(valid: Name, codeBlock: () => void, $dataValid: Code = nil): void {
444 this.gen.block(() => {
445 this.check$data(valid, $dataValid)
446 codeBlock()
447 })
448 }
449
450 check$data(valid: Name = nil, $dataValid: Code = nil): void {
451 if (!this.$data) return
452 const {gen, schemaCode, schemaType, def} = this
453 gen.if(or(_`${schemaCode} === undefined`, $dataValid))
454 if (valid !== nil) gen.assign(valid, true)
455 if (schemaType.length || def.validateSchema) {
456 gen.elseIf(this.invalid$data())
457 this.$dataError()
458 if (valid !== nil) gen.assign(valid, false)
459 }
460 gen.else()
461 }
462
463 invalid$data(): Code {
464 const {gen, schemaCode, schemaType, def, it} = this
465 return or(wrong$DataType(), invalid$DataSchema())
466
467 function wrong$DataType(): Code {
468 if (schemaType.length) {
469 /* istanbul ignore if */
470 if (!(schemaCode instanceof Name)) throw new Error("ajv implementation error")
471 const st = Array.isArray(schemaType) ? schemaType : [schemaType]
472 return _`${checkDataTypes(st, schemaCode, it.opts.strictNumbers, DataType.Wrong)}`
473 }
474 return nil
475 }
476
477 function invalid$DataSchema(): Code {
478 if (def.validateSchema) {
479 const validateSchemaRef = gen.scopeValue("validate$data", {ref: def.validateSchema}) // TODO value.code for standalone
480 return _`!${validateSchemaRef}(${schemaCode})`
481 }
482 return nil
483 }
484 }
485
486 subschema(appl: SubschemaArgs, valid: Name): SchemaCxt {
487 const subschema = getSubschema(this.it, appl)
488 extendSubschemaData(subschema, this.it, appl)
489 extendSubschemaMode(subschema, appl)
490 const nextContext = {...this.it, ...subschema, items: undefined, props: undefined}
491 subschemaCode(nextContext, valid)
492 return nextContext
493 }
494
495 mergeEvaluated(schemaCxt: SchemaCxt, toName?: typeof Name): void {
496 const {it, gen} = this
497 if (!it.opts.unevaluated) return
498 if (it.props !== true && schemaCxt.props !== undefined) {
499 it.props = mergeEvaluated.props(gen, schemaCxt.props, it.props, toName)
500 }
501 if (it.items !== true && schemaCxt.items !== undefined) {
502 it.items = mergeEvaluated.items(gen, schemaCxt.items, it.items, toName)
503 }
504 }
505
506 mergeValidEvaluated(schemaCxt: SchemaCxt, valid: Name): boolean | void {
507 const {it, gen} = this
508 if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
509 gen.if(valid, () => this.mergeEvaluated(schemaCxt, Name))
510 return true
511 }
512 }
513}
514
515function keywordCode(
516 it: SchemaObjCxt,
517 keyword: string,
518 def: AddedKeywordDefinition,
519 ruleType?: JSONType
520): void {
521 const cxt = new KeywordCxt(it, def, keyword)
522 if ("code" in def) {
523 def.code(cxt, ruleType)
524 } else if (cxt.$data && def.validate) {
525 funcKeywordCode(cxt, def)
526 } else if ("macro" in def) {
527 macroKeywordCode(cxt, def)
528 } else if (def.compile || def.validate) {
529 funcKeywordCode(cxt, def)
530 }
531}
532
533const JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/
534const RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/
535export function getData(
536 $data: string,
537 {dataLevel, dataNames, dataPathArr}: SchemaCxt
538): Code | number {
539 let jsonPointer
540 let data: Code
541 if ($data === "") return N.rootData
542 if ($data[0] === "/") {
543 if (!JSON_POINTER.test($data)) throw new Error(`Invalid JSON-pointer: ${$data}`)
544 jsonPointer = $data
545 data = N.rootData
546 } else {
547 const matches = RELATIVE_JSON_POINTER.exec($data)
548 if (!matches) throw new Error(`Invalid JSON-pointer: ${$data}`)
549 const up: number = +matches[1]
550 jsonPointer = matches[2]
551 if (jsonPointer === "#") {
552 if (up >= dataLevel) throw new Error(errorMsg("property/index", up))
553 return dataPathArr[dataLevel - up]
554 }
555 if (up > dataLevel) throw new Error(errorMsg("data", up))
556 data = dataNames[dataLevel - up]
557 if (!jsonPointer) return data
558 }
559
560 let expr = data
561 const segments = jsonPointer.split("/")
562 for (const segment of segments) {
563 if (segment) {
564 data = _`${data}${getProperty(unescapeJsonPointer(segment))}`
565 expr = _`${expr} && ${data}`
566 }
567 }
568 return expr
569
570 function errorMsg(pointerType: string, up: number): string {
571 return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`
572 }
573}
574
\No newline at end of file