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