1 import type {CodeKeywordDefinition, AnySchemaObject} from "../../types"
2 import type {KeywordCxt} from "../../compile/validate"
3 import {compileSchema, SchemaEnv} from "../../compile"
4 import {_, not, nil, stringify} from "../../compile/codegen"
5 import MissingRefError from "../../compile/ref_error"
6 import N from "../../compile/names"
7 import {getValidate, callRef} from "../core/ref"
8 import {checkMetadata} from "./metadata"
10 const def: CodeKeywordDefinition = {
13 code(cxt: KeywordCxt) {
15 const {gen, data, schema: ref, parentSchema, it} = cxt
19 const valid = gen.name("valid")
20 if (parentSchema.nullable) {
21 gen.var(valid, _`${data} === null`)
22 gen.if(not(valid), validateJtdRef)
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)
36 function callValidate(schema: AnySchemaObject): void {
37 const sch = compileSchema.call(
39 new SchemaEnv({schema, root, schemaPath: `/definitions/${ref}`})
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}`)
47 function inlineRefSchema(schema: AnySchemaObject): void {
48 const schName = gen.scopeValue(
50 it.opts.code.source === true ? {ref: schema, code: stringify(schema)} : {ref: schema}
57 topSchemaRef: schName,
58 errSchemaPath: `/definitions/${ref}`,
66 export 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