dynamicAnchor.ts 1.1 KB

12345678910111213141516171819202122232425262728293031
  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. 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 {schemaId} = self.opts
  23. const sch = new SchemaEnv({schema, schemaId, root, baseId, localRefs, meta})
  24. compileSchema.call(self, sch)
  25. return getValidate(cxt, sch)
  26. }
  27. export default def