source: trip-planner-front/node_modules/ajv/lib/vocabularies/jtd/ref.ts

Last change on this file was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 2.3 KB
Line 
1import type {CodeKeywordDefinition, AnySchemaObject} from "../../types"
2import type {KeywordCxt} from "../../compile/validate"
3import {compileSchema, SchemaEnv} from "../../compile"
4import {_, not, nil, stringify} from "../../compile/codegen"
5import MissingRefError from "../../compile/ref_error"
6import N from "../../compile/names"
7import {getValidate, callRef} from "../core/ref"
8import {checkMetadata} from "./metadata"
9
10const def: CodeKeywordDefinition = {
11 keyword: "ref",
12 schemaType: "string",
13 code(cxt: KeywordCxt) {
14 checkMetadata(cxt)
15 const {gen, data, schema: ref, parentSchema, it} = cxt
16 const {
17 schemaEnv: {root},
18 } = it
19 const valid = gen.name("valid")
20 if (parentSchema.nullable) {
21 gen.var(valid, _`${data} === null`)
22 gen.if(not(valid), validateJtdRef)
23 } else {
24 gen.var(valid, false)
25 validateJtdRef()
26 }
27 cxt.ok(valid)
28
29 function validateJtdRef(): void {
30 const refSchema = (root.schema as AnySchemaObject).definitions?.[ref]
31 if (!refSchema) throw new MissingRefError("", ref, `No definition ${ref}`)
32 if (hasRef(refSchema) || !it.opts.inlineRefs) callValidate(refSchema)
33 else inlineRefSchema(refSchema)
34 }
35
36 function callValidate(schema: AnySchemaObject): void {
37 const sch = compileSchema.call(
38 it.self,
39 new SchemaEnv({schema, root, schemaPath: `/definitions/${ref}`})
40 )
41 const v = getValidate(cxt, sch)
42 const errsCount = gen.const("_errs", N.errors)
43 callRef(cxt, v, sch, sch.$async)
44 gen.assign(valid, _`${errsCount} === ${N.errors}`)
45 }
46
47 function inlineRefSchema(schema: AnySchemaObject): void {
48 const schName = gen.scopeValue(
49 "schema",
50 it.opts.code.source === true ? {ref: schema, code: stringify(schema)} : {ref: schema}
51 )
52 cxt.subschema(
53 {
54 schema,
55 dataTypes: [],
56 schemaPath: nil,
57 topSchemaRef: schName,
58 errSchemaPath: `/definitions/${ref}`,
59 },
60 valid
61 )
62 }
63 },
64}
65
66export function hasRef(schema: AnySchemaObject): boolean {
67 for (const key in schema) {
68 let sch: AnySchemaObject
69 if (key === "ref" || (typeof (sch = schema[key]) == "object" && hasRef(sch))) return true
70 }
71 return false
72}
73
74export default def
Note: See TracBrowser for help on using the repository browser.