diff --git a/src/contracts/portablePattern.test.ts b/src/contracts/portablePattern.test.ts index 4908769248..6239ef57dd 100644 --- a/src/contracts/portablePattern.test.ts +++ b/src/contracts/portablePattern.test.ts @@ -206,6 +206,29 @@ const PRESENTERS = [ ] as const; describe("advertised pattern presentation", () => { + it.each(PRESENTERS)( + "omits overlapping widened alternatives from the %s schema", + (_kind, present) => { + for (const pattern of ["^(?:é|è)+$", "^(?:é|[èa])+$", "^(?:(?:é|è))+$"]) { + const canonical = new Ajv({ strict: false }).compile({ + type: "string", + pattern, + }); + const schema = present(property({ type: "string", pattern })); + expect( + (schema.properties as Record).name, + ).not.toHaveProperty("pattern"); + const validate = new Ajv({ strict: false }).compile(schema); + expect(validate({ name: "é".repeat(1000) + "A" })).toBe(true); + expect(canonical("éè"), pattern).toBe(true); + expect(canonical("éèA"), pattern).toBe(false); + } + expect(projectPortablePattern("^(?:a|b)+$").kind).toBe("exact"); + expect(projectPortablePattern("^[éè]+$").kind).toBe("wider"); + expect(projectPortablePattern("^é(?:a|b)+$").kind).toBe("wider"); + }, + ); + const lookAround = "^(?!con$)[a-z]+$"; const property = (schema: Record) => ({ type: "object", diff --git a/src/contracts/portablePattern.ts b/src/contracts/portablePattern.ts index 2ab43fc0df..6428ff5ab0 100644 --- a/src/contracts/portablePattern.ts +++ b/src/contracts/portablePattern.ts @@ -143,7 +143,7 @@ const SHORTHAND_NON_ASCII: Readonly> = { class Projector { #index = 0; - #wider = false; + #widenings = 0; constructor(private readonly source: string) {} @@ -165,7 +165,7 @@ class Projector { completed.length === 1 ? `^${completed[0]!}$` : `^(?:${completed.join("|")})$`; - return { kind: this.#wider ? "wider" : "exact", pattern }; + return { kind: this.#widenings > 0 ? "wider" : "exact", pattern }; } #peek(offset = 0): string { @@ -173,15 +173,21 @@ class Projector { } #widen = (): void => { - this.#wider = true; + this.#widenings++; }; #disjunction(): string[][] { + const wideningsBefore = this.#widenings; const alternatives = [this.#alternative()]; while (this.#peek() === "|") { this.#index++; alternatives.push(this.#alternative()); } + // Widening can make disjoint alternatives overlap. Repeating such a + // group, including through a parent group, can backtrack exponentially. + // Omit the advertisement rather than assume those branches stay disjoint. + if (alternatives.length > 1 && this.#widenings > wideningsBefore) + throw new Unexpressible(); return alternatives; }