pattern.ts 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types"
  2. import type {KeywordCxt} from "../../compile/validate"
  3. import {usePattern} from "../code"
  4. import {useFunc} from "../../compile/util"
  5. import {_, str} from "../../compile/codegen"
  6. export type PatternError = ErrorObject<"pattern", {pattern: string}, string | {$data: string}>
  7. const error: KeywordErrorDefinition = {
  8. message: ({schemaCode}) => str`must match pattern "${schemaCode}"`,
  9. params: ({schemaCode}) => _`{pattern: ${schemaCode}}`,
  10. }
  11. const def: CodeKeywordDefinition = {
  12. keyword: "pattern",
  13. type: "string",
  14. schemaType: "string",
  15. $data: true,
  16. error,
  17. code(cxt: KeywordCxt) {
  18. const {gen, data, $data, schema, schemaCode, it} = cxt
  19. const u = it.opts.unicodeRegExp ? "u" : ""
  20. if ($data) {
  21. const {regExp} = it.opts.code
  22. const regExpCode = regExp.code === "new RegExp" ? _`new RegExp` : useFunc(gen, regExp)
  23. const valid = gen.let("valid")
  24. gen.try(
  25. () => gen.assign(valid, _`${regExpCode}(${schemaCode}, ${u}).test(${data})`),
  26. () => gen.assign(valid, false)
  27. )
  28. cxt.fail$data(_`!${valid}`)
  29. } else {
  30. const regExp = usePattern(cxt, schema)
  31. cxt.fail$data(_`!${regExp}.test(${data})`)
  32. }
  33. },
  34. }
  35. export default def