dynamicAnchor.ts 1.1 KB

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