regexp.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import type {CodeKeywordDefinition, KeywordCxt, JSONSchemaType, Name} from "ajv"
  2. import {_} from "ajv/dist/compile/codegen"
  3. import {usePattern} from "./_util"
  4. interface RegexpSchema {
  5. pattern: string
  6. flags?: string
  7. }
  8. const regexpMetaSchema: JSONSchemaType<RegexpSchema> = {
  9. type: "object",
  10. properties: {
  11. pattern: {type: "string"},
  12. flags: {type: "string", nullable: true},
  13. },
  14. required: ["pattern"],
  15. additionalProperties: false,
  16. }
  17. const metaRegexp = /^\/(.*)\/([gimuy]*)$/
  18. export default function getDef(): CodeKeywordDefinition {
  19. return {
  20. keyword: "regexp",
  21. type: "string",
  22. schemaType: ["string", "object"],
  23. code(cxt: KeywordCxt) {
  24. const {data, schema} = cxt
  25. const regx = getRegExp(schema)
  26. cxt.pass(_`${regx}.test(${data})`)
  27. function getRegExp(sch: string | RegexpSchema): Name {
  28. if (typeof sch == "object") return usePattern(cxt, sch.pattern, sch.flags)
  29. const rx = metaRegexp.exec(sch)
  30. if (rx) return usePattern(cxt, rx[1], rx[2])
  31. throw new Error("cannot parse string into RegExp")
  32. }
  33. },
  34. metaSchema: {
  35. anyOf: [{type: "string"}, regexpMetaSchema],
  36. },
  37. }
  38. }
  39. module.exports = getDef