Skip to content

Commit

Permalink
use unicodeRegExp ajv option, fix #220 (regexp flags ignored when reg…
Browse files Browse the repository at this point in the history
…exp is cached)
  • Loading branch information
epoberezkin committed Nov 21, 2021
1 parent b698f4b commit b8ec5ba
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 10 deletions.
4 changes: 2 additions & 2 deletions package.json
Expand Up @@ -38,7 +38,7 @@
"fast-deep-equal": "^3.1.3"
},
"peerDependencies": {
"ajv": "^8.0.0"
"ajv": "^8.8.2"
},
"devDependencies": {
"@ajv-validator/config": "^0.2.3",
Expand All @@ -48,7 +48,7 @@
"@types/uuid": "^8.3.0",
"@typescript-eslint/eslint-plugin": "^4.4.1",
"@typescript-eslint/parser": "^4.4.1",
"ajv": "^8.0.0",
"ajv": "^8.8.2",
"ajv-formats": "^2.0.0",
"chai": "^4.2.0",
"eslint": "^7.2.0",
Expand Down
13 changes: 9 additions & 4 deletions src/definitions/_util.ts
@@ -1,5 +1,5 @@
import type {DefinitionOptions} from "./_types"
import type {SchemaObject, CodeGen, Name} from "ajv"
import type {SchemaObject, KeywordCxt, Name} from "ajv"
import {_} from "ajv/dist/compile/codegen"

const META_SCHEMA_ID = "http://json-schema.org/schema"
Expand All @@ -8,10 +8,15 @@ export function metaSchemaRef({defaultMeta}: DefinitionOptions = {}): SchemaObje
return defaultMeta === false ? {} : {$ref: defaultMeta || META_SCHEMA_ID}
}

export function usePattern(gen: CodeGen, pattern: string, flags = "u"): Name {
export function usePattern(
{gen, it: {opts}}: KeywordCxt,
pattern: string,
flags = opts.unicodeRegExp ? "u" : ""
): Name {
const rx = new RegExp(pattern, flags)
return gen.scopeValue("pattern", {
key: pattern,
ref: new RegExp(pattern, flags),
key: rx.toString(),
ref: rx,
code: _`new RegExp(${pattern}, ${flags})`,
})
}
2 changes: 1 addition & 1 deletion src/definitions/patternRequired.ts
Expand Up @@ -26,7 +26,7 @@ export default function getDef(): CodeKeywordDefinition {
const matched = gen.let("matched", false)

gen.forIn("key", data, (key) => {
gen.assign(matched, _`${usePattern(gen, pattern)}.test(${key})`)
gen.assign(matched, _`${usePattern(cxt, pattern)}.test(${key})`)
gen.if(matched, () => gen.break())
})

Expand Down
6 changes: 3 additions & 3 deletions src/definitions/regexp.ts
Expand Up @@ -25,14 +25,14 @@ export default function getDef(): CodeKeywordDefinition {
type: "string",
schemaType: ["string", "object"],
code(cxt: KeywordCxt) {
const {gen, data, schema} = cxt
const {data, schema} = cxt
const regx = getRegExp(schema)
cxt.pass(_`${regx}.test(${data})`)

function getRegExp(sch: string | RegexpSchema): Name {
if (typeof sch == "object") return usePattern(gen, sch.pattern, sch.flags)
if (typeof sch == "object") return usePattern(cxt, sch.pattern, sch.flags)
const rx = metaRegexp.exec(sch)
if (rx) return usePattern(gen, rx[1], rx[2])
if (rx) return usePattern(cxt, rx[1], rx[2])
throw new Error("cannot parse string into RegExp")
}
},
Expand Down

0 comments on commit b8ec5ba

Please sign in to comment.