pattern.ts 908 B

1234567891011121314151617181920212223242526
  1. import type {CodeKeywordDefinition, ErrorObject, KeywordErrorDefinition} from "../../types"
  2. import type KeywordCxt from "../../compile/context"
  3. import {usePattern} from "../code"
  4. import {_, str} from "../../compile/codegen"
  5. export type PatternError = ErrorObject<"pattern", {pattern: string}, string | {$data: string}>
  6. const error: KeywordErrorDefinition = {
  7. message: ({schemaCode}) => str`should match pattern "${schemaCode}"`,
  8. params: ({schemaCode}) => _`{pattern: ${schemaCode}}`,
  9. }
  10. const def: CodeKeywordDefinition = {
  11. keyword: "pattern",
  12. type: "string",
  13. schemaType: "string",
  14. $data: true,
  15. error,
  16. code(cxt: KeywordCxt) {
  17. const {gen, data, $data, schema, schemaCode} = cxt
  18. const regExp = $data ? _`(new RegExp(${schemaCode}, "u"))` : usePattern(gen, schema) // TODO regexp should be wrapped in try/catch
  19. cxt.fail$data(_`!${regExp}.test(${data})`)
  20. },
  21. }
  22. export default def