1 | import type {CodeKeywordDefinition} from "../../types"
|
2 | import type {KeywordCxt} from "../../compile/validate"
|
3 | import {_, getProperty, Code} from "../../compile/codegen"
|
4 | import N from "../../compile/names"
|
5 | import {SchemaEnv, compileSchema} from "../../compile"
|
6 | import {getValidate} from "../core/ref"
|
7 |
|
8 | const def: CodeKeywordDefinition = {
|
9 | keyword: "$dynamicAnchor",
|
10 | schemaType: "string",
|
11 | code: (cxt) => dynamicAnchor(cxt, cxt.schema),
|
12 | }
|
13 |
|
14 | export function dynamicAnchor(cxt: KeywordCxt, anchor: string): void {
|
15 | const {gen, it} = cxt
|
16 | it.schemaEnv.root.dynamicAnchors[anchor] = true
|
17 | const v = _`${N.dynamicAnchors}${getProperty(anchor)}`
|
18 | const validate = it.errSchemaPath === "#" ? it.validateName : _getValidate(cxt)
|
19 | gen.if(_`!${v}`, () => gen.assign(v, validate))
|
20 | }
|
21 |
|
22 | function _getValidate(cxt: KeywordCxt): Code {
|
23 | const {schemaEnv, schema, self} = cxt.it
|
24 | const {root, baseId, localRefs, meta} = schemaEnv.root
|
25 | const {schemaId} = self.opts
|
26 | const sch = new SchemaEnv({schema, schemaId, root, baseId, localRefs, meta})
|
27 | compileSchema.call(self, sch)
|
28 | return getValidate(cxt, sch)
|
29 | }
|
30 |
|
31 | export default def
|