diff --git a/.agents/matching.md b/.agents/matching.md index 6042aa5..f5104ae 100644 --- a/.agents/matching.md +++ b/.agents/matching.md @@ -65,7 +65,7 @@ Segments after a `**` match from the **end** of the path; the `**` takes what is - Plain pattern: identity = the rewritten segment join (static keys via `segmentKey`, dynamic segments as written, suffix included), the same string `ctx.static` is keyed by. Spellings the tree can't distinguish remove each other (`/a/` ≡ `/a`, `\)` ≡ `)`, `/**.md` ≡ `/**/*.md`, `/café-:id` ≡ `/caf%C3%A9-:id`). - Identities are compared canonically (`routeId`: each segment through `dynamicKey`, which percent-encodes a dynamic segment's literal text like `getParamRegexp`, outside constraints, `?{}` kept as syntax, and is a no-op on a static key), in `removeRoute` and `findOverlappingRoutes`' dedupe, so both spellings alias; a constraint is regex and stays distinct (`:x(é)` vs `:x(%C3%A9)`). Escapes are not canonicalized (`/:x-a` vs `/:x-\a` stay distinct): a missed alias, never a wrong one. The canonical form is computed where identities are compared, not stamped by `addRoute`, so the core bundle (routers that never remove) doesn't carry it. -- Expanding pattern (groups, modifiers): every entry gets the pre-expansion text normalized by `expandedRouteId()` (static segments via `segmentKey`), so the `/admin` entry of `/admin/:page?` never collides with a separately registered `/admin`. A group that expands to a single route (`/a/*-{:x}?` is `/a/*-:x?`, `/a{b}` is `/ab`) is that route: it takes the rewritten route's identity (both `_add` and `_removeRoute` skip `expandedRouteId` there). `expandGroupDelimiters` returns that rewrite alone, also next to another group, so the next group is expanded from the rewritten text: its identity is `expandedRouteId` of `/*-:x?/b{.json}?` for `/*-{:x}?/b{.json}?` too, and `skipGroup` renumbers the right group (`/a/*{:x}?/b{/(\d+)}?/*` on `/a/q/b/z` is `{0:"q", 2:"z"}`, as in URLPattern). +- Expanding pattern (groups, modifiers): every entry gets the pre-expansion text normalized by `expandedRouteId()` (static segments via `segmentKey`), so the `/admin` entry of `/admin/:page?` never collides with a separately registered `/admin`. A group that expands to a single route (`/a/*-{:x}?` is `/a/*-:x?`, `/a{b}` is `/ab`) is that route: it takes the rewritten route's identity (both `_add` and `_removeRoute` skip `expandedRouteId` there). `expandGroupDelimiters` returns that rewrite alone, also next to another group, so the next group is expanded from the rewritten text: its identity is `expandedRouteId` of `/*-:x?/b{.json}?` for `/*-{:x}?/b{.json}?` too, and `skipGroup` renumbers the right group (`/a/*{:x}?/b{/(\d+)}?/*` on `/a/q/b/z` is `{0:"q", 2:"z"}`, as in URLPattern). A pattern starting with a group (no `/` in front, see [syntax.md](syntax.md#leading-)) is read after a `/` (the split drops a path's first piece) and marked with a leading `{`: read after a `/`, `{a}?/b` is the text of `/{a}?/b`, and both register `/a/b`. A malformed `{…` removes nothing. - All entries with that identity go (duplicates together). An emptied static node deletes its `ctx.static` key via the join accumulated during the walk (no value scan). - Removal is by registered pattern: `/x/*` does not remove `/x/:id`; `:id(\d+)` and `:x(\d+)` are distinct. - Suffix routes: `_removeSuffix` walks back from the last segment, prunes empty trie nodes, then `wildcard.suffix`, then the wildcard (`_isEmptyNode` counts `suffix`). diff --git a/.agents/regexp.md b/.agents/regexp.md index aeedbdf..de64579 100644 --- a/.agents/regexp.md +++ b/.agents/regexp.md @@ -33,7 +33,7 @@ A path matches iff the body matches it with one trailing `/` stripped. The gener ### Optional group inlining (`inlineOptionalGroup`) -The tree expands `{…}?` into two routes, but `routeToRegExp` inlines a single optional group as `(?:…)?` to avoid repeating named groups across alternation branches (PCRE2 and Node 22 reject duplicates). The group must end a segment (or start one, see below); both expansions (`routeToRegExpSegments`) must line up as shared head + one differing segment (or added whole segments) + shared tail; with a tail, the head must pass `isFixedSegment()`. When the base segment ends in its only capture, `mergeCapture()` makes it split like the router, whose extended route wins where it matches: a lazy `:name` is emitted as `(?[^/]+?)(?:rest)?` (shortest first with the group before without it finds the router's split, `archive.tar.gz` → `archive` + `tar.gz`). A greedy `*` or a constraint gets a look-ahead instead, unless a `\d`/`\w` run can't take the group's first char. Look-ahead forms are RE2-incompatible and not reversible (`LOOKAHEAD_ROUTES`). An appended part after other captures is inlined only where `appendsCleanly` holds: every capture before it is a lazy `:name` (`/f/:x.a{.a}?/m`), the segment and its extension can't end in the same char (`/*-x{.png}?`), or every capture before it can't match the literal char right after it (`/:id(\d+)-x{.png}?`, `/img/:w(\d+)x:h(\d+){.png}?`), so it splits one way. A group that starts its segment before more of it (`/{:x}?(\d+)`, `inSegment`) is inlined as `(?:X)?rest` where the full segment is `X` + the base one and `X` compiles alone (`isRegExpSource`), with a fixed head: `(?:X)?C` tries `XC`, then `C`, the router's order (with equal weights the route with the group, registered first, wins); `regExpToRoute` reads the rest of the segment after such a unit as part of a segment (`reverseSegment(…, part)`: a `(.+)` is no `:_0+`), and throws where another in-segment optional unit follows it (`/{:x}?(.+)-:y?`: a `{:y}?` would route otherwise than the in-place `-:y?`). Falls back to alternation for multi-group routes, non-aligning expansions (an in-segment group followed by optional segments, `/:x{.:e}?/:y?`), a mid-segment optional group after other captures otherwise (`/media/*{.webp}?`, `/*-x{-x}?`), and router-order expansion shapes. +The tree expands `{…}?` into two routes, but `routeToRegExp` inlines a single optional group as `(?:…)?` to avoid repeating named groups across alternation branches (PCRE2 and Node 22 reject duplicates). The group must end a segment (or start one, see below); a leading group's expansions get the `/` `expandGroupDelimiters` gives them (`{a}?/b` is `(?:\/a)?\/b`), and one with an empty base (`{/:a}?`) falls back; both expansions (`routeToRegExpSegments`) must line up as shared head + one differing segment (or added whole segments) + shared tail; with a tail, the head must pass `isFixedSegment()`. When the base segment ends in its only capture, `mergeCapture()` makes it split like the router, whose extended route wins where it matches: a lazy `:name` is emitted as `(?[^/]+?)(?:rest)?` (shortest first with the group before without it finds the router's split, `archive.tar.gz` → `archive` + `tar.gz`). A greedy `*` or a constraint gets a look-ahead instead, unless a `\d`/`\w` run can't take the group's first char. Look-ahead forms are RE2-incompatible and not reversible (`LOOKAHEAD_ROUTES`). An appended part after other captures is inlined only where `appendsCleanly` holds: every capture before it is a lazy `:name` (`/f/:x.a{.a}?/m`), the segment and its extension can't end in the same char (`/*-x{.png}?`), or every capture before it can't match the literal char right after it (`/:id(\d+)-x{.png}?`, `/img/:w(\d+)x:h(\d+){.png}?`), so it splits one way. A group that starts its segment before more of it (`/{:x}?(\d+)`, `inSegment`) is inlined as `(?:X)?rest` where the full segment is `X` + the base one and `X` compiles alone (`isRegExpSource`), with a fixed head: `(?:X)?C` tries `XC`, then `C`, the router's order (with equal weights the route with the group, registered first, wins); `regExpToRoute` reads the rest of the segment after such a unit as part of a segment (`reverseSegment(…, part)`: a `(.+)` is no `:_0+`), and throws where another in-segment optional unit follows it (`/{:x}?(.+)-:y?`: a `{:y}?` would route otherwise than the in-place `-:y?`). Falls back to alternation for multi-group routes, non-aligning expansions (an in-segment group followed by optional segments, `/:x{.:e}?/:y?`), a mid-segment optional group after other captures otherwise (`/media/*{.webp}?`, `/*-x{-x}?`), and router-order expansion shapes. ### Duplicate names @@ -57,7 +57,7 @@ Inverse of `routeToRegExp`: parses an anchored, PCRE-compatible regex (or source - **Endings** are normalized structurally, exact shapes only (`ROOT_REPEAT`, `plainBody()` for closed endings, `TRAILING_CATCH_ALL`, `TRAILING_DOT`), then the look-behind suffix, the legacy two-slash suffix or a plain `\/?` is stripped. No generic `.*?` rewrite, so lazy quantifiers inside user constraints survive. - **Body walk** recognizes `\/` separators, optional units `(?:…)?` / `(?:…)??`, nested optionals, catch-alls (an unnamed `(?<_N>[\s\S]*)` → `**`, greedy or lazy; for a group named `_`, how 0.11 and older emitted `**`: greedy `(?:\/(?<_>[\s\S]*))?` → `**`, a lazy group with a lazy body → `**`, with a greedy body → `{/**}?` (merged; `:_*` where no group can be)), `\/(?[\s\S]+)` → `:x+`, root forms, `NESTED_CATCH_ALL`: `:x*` then `*` (`[\s\S]+`; `[\s\S]*` in 0.11, and 0.10's `**` / `:x*` then `:y?`)). `.*` / `.+` read as catch-alls (legacy output), unless the regex has a lazy user-`.` ending. - **Segments:** `(?[^/]+)`, `[^/]+?` (in a mixed segment) / legacy `[^/]*` → `:x`; `\/(?[\s\S]+)` → `:x+` (legacy `[\s\S]*` too), in an optional unit `:x*` (same route as `{/:x+}?`; 0.11's empty-capable `[\s\S]*` one too, which now needs a value); the closed `**:x` ending `(?:\/\/|(?…)\/?)` → `(?[\s\S]+)` (`REQUIRED_VALUE`, the 0.10 `(?:\/|…)` one → `[\s\S]*`); an in-segment optional lone param comes back as `pre-:x?` (`mergeGroup`); unnamed `[^/]*` → `*`; `(pat)` → `(pat)`; `(?pat)` → `:x(pat)`; route-syntax literals re-escaped; a word char or non-ASCII char after a bare `:name` is escaped (`:x\abc`, `:x\é`; a `-` ends a name, so it stays bare); a group after a bare `:name` gives the name its body without a `/` (`(?[^/]+?)(?<_0>\d+)` → `:x([^\x2f]+?)(\d+)`, which `getParamRegexp` emits back as `[^/]+?`: the regex for `{:x}(\d+)`, see `joinGroup`); a constraint body holding a capturing group throws, and so does a `*` right after a `*` (would read as `**`): `addRoute` rejects both. Optional units classify by inner shape into `:x?` / `:x*` / `*` / merged `{…}?` groups. Equivalent outputs come back in one spelling (`/a{/:x+}?` → `/a/:x*`, `/a{/:x+}?/b` → `/a/:x*/b`, `/a{/**}?` → `/a/**`, and so does `/a{/([\s\S]*)}?`, an over-matching constraint with the same regex). -- **Unnamed captures** (`(?<_N>…)`) are told apart by the raw group name (`matchNamedGroup`'s `unnamed`, `UNNAMED`), never the decoded one: a param `:_0` is emitted escaped (`__rou3_esc___0`) and decodes to the same `_0`. An optional one stays unnamed: `(?:\/(?<_0>pat))?` → `{/(pat)}?` on the previous segment (`:_0(pat)?` would be a param keyed `_0`, not `0`; with no previous segment, inside a group (`{…}` can't nest), or a body with no constraint form like `[^/]+`, it throws). A `[^/]*` is a bare `*` only where that is optional (ending the route, or with the next optionals nested in its group), else `{/*}?` (`/a{/*}?/b`). +- **Unnamed captures** (`(?<_N>…)`) are told apart by the raw group name (`matchNamedGroup`'s `unnamed`, `UNNAMED`), never the decoded one: a param `:_0` is emitted escaped (`__rou3_esc___0`) and decodes to the same `_0`. An optional one stays unnamed: `(?:\/(?<_0>pat))?` → `{/(pat)}?` on the previous segment, or starting the route with none (`{/(pat)}?/b`, absolute, see [syntax.md](syntax.md#leading-)) (`:_0(pat)?` would be a param keyed `_0`, not `0`; inside a group (`{…}` can't nest), or a body with no constraint form like `[^/]+`, it throws). Other root optionals of whole segments with nothing to merge onto lead the route the same way (`^(?:\/a)?\/b` → `{/a}?/b`); a root in-segment one (`^(?:foo)?`), text after a leading group (`^(?:\/a)?(?:b)?\/c`) and a group in a group (`^(?:\/a(?:\/b)?)?\/c`, also after a segment) throw: `addRoute` rejects those routes. A `[^/]*` is a bare `*` only where that is optional (ending the route, or with the next optionals nested in its group), else `{/*}?` (`/a{/*}?/b`). - **Percent-encoding:** `%XX` comes back as written (`/caf%C3%A9`, never decoded: `%2F`, `%25` would change the route), and `reverseSegment`'s `literal` throws on a char (read by code point) `encodeLiteral` would change (`é`, space, `\{`, `\?`, `\^`) or a U+FFFD-U+FFFF placeholder, naming its encoded form: route text is encoded, so no route has it (see [syntax.md](syntax.md#percent-encoding)). - **Reject by default:** `reverseSegment()` is a whitelist; look-arounds and other `(?…)` constructs, backreferences / metaclass escapes outside a constraint, bare regex operators, constraint bodies with `/`, flags `i`/`m`/`s`/`u`/`v` (`g`/`y`/`d` ignored), unanchored input, and group names that decode to no valid param name all throw. Constraint bodies are opaque and kept verbatim. - **Legacy inputs** (older look-behind, pre-trailing-slash-change two-slash, 0.9.x `\/?` endings with `.*` / `.+` catch-alls, 0.10's closed endings for an empty-capable `:x` / `**:x`, 0.11's empty-capable `:x*` forms and `ROOT_REPEAT`) are accepted and read as the route they were emitted for, which may now match fewer paths; pinned in `regexp-to-route.test.ts`. diff --git a/.agents/syntax.md b/.agents/syntax.md index 82a9fae..70d3509 100644 --- a/.agents/syntax.md +++ b/.agents/syntax.md @@ -1,6 +1,18 @@ # Pattern syntax -`addRoute` pipeline: `checkConstraints` → `expandGroupDelimiters` → `encodeEscapes` / `splitRoute` → `expandModifiers` (`:x+` → `**:x`, `:x*` → `**:x` + the route without it, see [matching.md](matching.md#empty-segments-and-normalization); `pre-:x?` → `pre-:x` + `pre-`, but after a capture it stays for `getParamRegexp`, see [below](#params-sharing-a-segment)) → per segment `segmentKey` (static key) or `getParamRegexp` / `addName`, both percent-encoding literal text (`encodeLiteral`, see [below](#percent-encoding)). Each helper bails early when its trigger is absent (`\`, `�`, `{`, trailing `?`/`+`/`*`, `(`/`{`/`}`, an encode-set char), so plain routes skip the scanners. Keep those guards. +`addRoute` pipeline: `absolutePattern` (see [below](#leading-)) → `checkConstraints` → `expandGroupDelimiters` → `encodeEscapes` / `splitRoute` → `expandModifiers` (`:x+` → `**:x`, `:x*` → `**:x` + the route without it, see [matching.md](matching.md#empty-segments-and-normalization); `pre-:x?` → `pre-:x` + `pre-`, but after a capture it stays for `getParamRegexp`, see [below](#params-sharing-a-segment)) → per segment `segmentKey` (static key) or `getParamRegexp` / `addName`, both percent-encoding literal text (`encodeLiteral`, see [below](#percent-encoding)). Each helper bails early when its trigger is absent (`\`, `�`, `{`, trailing `?`/`+`/`*`, `(`/`{`/`}`, an encode-set char), so plain routes skip the scanners. Keep those guards. + +## Leading `/` + +A relative pattern gets a `/` (`foo/:id` is `/foo/:id`; URLPattern never matches one on an absolute path). `absolutePattern()` (`operations/_utils.ts`) is the one rule, used by `addRoute`, `removeRoute` and `routeToRegExp`: a pattern starting with `/` or `{` is left alone. A leading `{…}` group can't be prefixed as a whole: `{/:a}?/b` is absolute in URLPattern (WPT gives `{/:foo}bar` as the canonical form of `/:foo\bar`), and a `/` in front would add an empty first segment (`//b`). So `expandGroupDelimiters` applies `absolutePattern` to each expansion of a leading group (`pre === ""`): one starting with `/` is absolute (`/:a/b`), the empty one is the root (`{/:a}?` is `/:a` or `/`, like `/:a?`), any other is relative and gets a `/` (`{a}?/b` is `/a/b` or `/b`, `{a}?b` is `/ab` or `/b`; URLPattern matches only `/b` and nothing for the relative forms), and one starting with `{` is the next group's (`{/a}?{/:b}?/c`). Escaped braces (`\{/a\}`) are literals: relative. Insert-time only: lookup is untouched. + +- **Reserved:** text right after a leading `{/…}?` throws (`{/a}?b`, `{/:a}?.png`, `{/a}?{.json}?`, `{/a}?{b}?/c`): the pattern is absolute, but without the group the route would be relative, a form URLPattern gives no meaning (`{/a}?b` matches only `/ab` there; the same rule would have made it match `/b`, `{/:a}?.png` `/.png`, `{/a}?{.json}?` `/.json`). After it come `/`, another `{/…}` group, or nothing. `{/…}+` / `{/…}*` throw as anywhere. +- **Malformed `{…`** (no group to expand): `addRoute` rejects it in `checkConstraints`; `removeRoute` doesn't validate, so `_removeRoute` returns when an unexpanded path has no leading `/` (it would split into another route's segments: `{oops/users/:id` is `/users/:id`). It threads `input` like `_add`, so the reserved syntax its expansions check (`{…}+`, text after a leading `{/…}?`, a misplaced modifier) throws quoting the pattern as written, never an expansion. +- **Removal identity:** `expandedRouteId` reads a leading-group pattern after a `/` (the split drops a path's first piece) and marks it with a `{`, which no other identity starts with: read after a `/`, `{a}?/b` would be the text of `/{a}?/b`, and both register `/a/b`. The `/` alone keeps `{/:a}?/b` apart from a plain `/b`, `/{/:a}?/b` or `{x/:a}?/b`. +- **Unnamed captures:** `skipGroup` counts a relative leading group's captures after its `/` (`{(\d+)}?/*` on `/x` is `{ 1: "x" }`). +- `routeToRegExp`: `inlineOptionalGroup` builds the full expansion with the same `/` (`{a}?/b` is `(?:\/a)?\/b`); a leading group with nothing after it (`{/:a}?`) has an empty base and falls back to alternation. +- `regExpToRoute`: a root optional of whole segments with no segment to merge onto comes back as a leading group (`^(?:\/(?<_0>\d+))?\/b` → `{/(\d+)}?/b`; `mergeGroup`). Only at the top level and only when the body has no `\/` before it (`/{/a}?` is an empty first segment, then the group). The result's groups are expanded like `addRoute` does, so text after it throws (`^(?:\/a)?(?:b)?\/c`); a body holding a group throws in `mergeGroup` (`^(?:\/a(?:\/b)?)?\/c` would be `{/a{/b}?}?/c`, after a segment too). +- Types (`InferRouteParams`) need nothing: they read names, not segments. ## Escapes @@ -34,7 +46,7 @@ A `(` there would still read as the name's constraint, and a `?` / `+` / `*` as Syntax with no defined meaning throws `rou3: ()` (`invalidSyntax()`), so it can get a meaning later without a breaking change. Checks sit where the pipeline already looks: - `checkConstraints` (route level): a U+FFFD-U+FFFF char, the internal placeholders (`encodeEscapes`' `\uFFFD`, `getParamRegexp`'s `\uFFFE`; U+FFFF stays reserved for the next one, so it can take a meaning without a breaking change), which a route could otherwise write as syntax (`/a/\uFFFD0x` would read as an escaped `:`; checked in the same early bail); a `(` that does not close in its own segment, including a `/` inside a constraint (one message for both causes, bundle size); a `^` / `$` outside a class, a look-around or a numbered backreference (`\1`) in a constraint (the tree tests the segment alone, so they see its ends and count its groups; the inline regex sees the rest of the path and all its groups); a capturing group inside a constraint, unnamed or `(?…)` (`/:x((a))`, `/a/((b)c)`, `/:n/:x((?a))`: a stray param that could collide with a route param or unnamed key; groups are removed innermost-out and a capturing one leaves a `\0`, like a backreference, that its enclosing group trips on). Only `(?:…)` may sit inside a constraint. The compiler's `_normalizeGroups` fallback (a non-identifier group name) is unreachable through `addRoute` (every group name is an identifier) and kept as a defensive path, pinned in `compiler.test.ts` with a hand-patched entry. Escapes are replaced by `_` (a backreference by `\0`) first, so `\(?=` is no look-ahead; after dropping escapes and constraints, a `\` that escapes nothing (`\/`, a trailing `\`) and unbalanced or nested `{}`. A stray `)` is literal. -- `expandGroupDelimiters`: `{…}+`, `{…}*`; via `joinGroup`, a `?` / `+` / `*` that a group's `{` / `}` puts right after a `:name`, a group of its segment or a `*` (a stray `)` is a literal: `/a){*}` is valid; the group is read as `(` … a `)` with no `\` right before it, so `(a\\){?}` slips through to the modifier reading) (`/{:x}{*}`, `/{:x}?*`, `/:x{}?*`, `/{:x}{?}`, `/:x(\d+){?}`, `/*{*}`): it would be a modifier on the param or group (`/{:x}{*}` was `/:x*`, `/*{*}` a `**`), URLPattern reads `:x` then `*`, two `*`s, or rejects `{?}`. A modifier on the unnamed group after one throws in `expandModifiers` / `getParamRegexp` like any other (`/{:x}(y)?` was an optional `:x(y)`). +- `expandGroupDelimiters`: `{…}+`, `{…}*`; text right after a leading `{/…}?` (`{/a}?b`, see [above](#leading-)); via `joinGroup`, a `?` / `+` / `*` that a group's `{` / `}` puts right after a `:name`, a group of its segment or a `*` (a stray `)` is a literal: `/a){*}` is valid; the group is read as `(` … a `)` with no `\` right before it, so `(a\\){?}` slips through to the modifier reading) (`/{:x}{*}`, `/{:x}?*`, `/:x{}?*`, `/{:x}{?}`, `/:x(\d+){?}`, `/*{*}`): it would be a modifier on the param or group (`/{:x}{*}` was `/:x*`, `/*{*}` a `**`), URLPattern reads `:x` then `*`, two `*`s, or rejects `{?}`. A modifier on the unnamed group after one throws in `expandModifiers` / `getParamRegexp` like any other (`/{:x}(y)?` was an optional `:x(y)`). - `expandModifiers`: `+` / `*` on anything but a whole-segment `:name` (`:x(\d+)?` and `pre-:x?` are fine), and a `?` on a `**:name` (the `**` is no text before the param). - `getParamRegexp` (depth 0): an invalid name after `:` (it reads the `\w`, `$` and non-ASCII run, so `:`, `:0`, `:1st`, `:café` and `:id$` all throw `invalid param name` naming the run); a group that is empty or starts with `?`; a raw `?` / `+` quantifier (a `?` ending the segment right after a `:name` / `:name(…)`, `PARAM_MODIFIER`, is the in-place optional); a `*` right after a name, group or `*` (ambiguous with a modifier; `a**b`, `x**`: a mid-segment `**`, while a segment starting with `**` is split by `splitRoute`, `/**.md` = `/**\/*.md`). - `_add`, static segment: an unescaped `?` (`/foo?`, `/a/b?/c`, `\:x?`): lookup paths never hold a query string, so it could never match. `\?` is a literal; `+` / `*` stay literal in a static segment (`/c++`). Shares `MISPLACED_MODIFIER` (where each goes: `?` after `:name` / `:name(…)`, `+` / `*` after a whole-segment `:name`, none after `**:name`; and the escape) with the modifier errors and the mid-segment `**` (one message, bundle size). diff --git a/.agents/testing.md b/.agents/testing.md index 23718c8..8326cec 100644 --- a/.agents/testing.md +++ b/.agents/testing.md @@ -4,7 +4,7 @@ - Matcher tests compare `findRoute` / `findAllRoutes` with compiled JIT and AOT output; tree and codegen are snapshot-tested. - Paths with empty segments (`/a//`, `/a//b`) must be in every sweep: a `:name` / `**:name` can't take one while `*` / `**` can (`sweepPaths()`, the `overlap.test.ts` / `suffix.test.ts` alphabets hold `""`, and `find.test.ts` "empty segments (compiled parity, sweep)" compares interpreter and compiled on random routers). - Brute-force sweeps (pairs of patterns × short paths) back the hard invariants: `find-all.test.ts` (containing route listed first, see [matching.md](matching.md#findallroutes-ordering-public-contract)), `suffix.test.ts` (never pick a strictly broader route), `method-agnostic.test.ts`, `overlap.test.ts`, `route-node-keys.test.ts`, `regexp.test.ts`, `regexp-to-route.test.ts`. Keep them passing with 0 violations; known exceptions live in named, stale-guarded sets (a listed entry that stops differing fails). -- `test/wpt.test.ts`: URLPattern WPT data, vendored verbatim (to sync, copy upstream's `urlpattern/resources/urlpatterntestdata.json` and update the SHA in the file header). Read like WPT's runner (`urlpatterntests.js`): `expected_obj: "error"` must throw `rou3:` (except `ACCEPTED_INVALID_PATTERNS`), `baseURL` / URL-string inputs resolve to their pathname, every input is percent-encoded like `new URL().pathname` (`encodePathname`, checked against the runtime's URLPattern in `PERCENT_ENCODING_CASES`), and entries that are not a lone `pathname` pattern are counted as out of scope. Groups compare with `toStrictEqual` (`null` in the data = an unset group = `undefined`); the one modelled difference is `expectedGroups()`: the tree leaves an unset param out of `params`, so for tree strategies an unset URLPattern group ≡ an absent key (a present `undefined` param still differs). Diffs live in `KNOWN_DIFFS`, `REGEXP_ONLY_KNOWN_DIFFS`, `ROUTER_KNOWN_DIFFS`: maps from label to rou3's exact result (groups, `null` for no match; `split(regexp, router)` where the regex and the tree also differ), each asserted to differ from URLPattern **and** to equal the stored result, so a behaviour PR that changes a listed case must update its entry. Rejected syntax is in `RESERVED_PATTERNS` (asserted to throw); an entry the data no longer reaches fails. Each skip names its reason and checks the exact entry shape that reason describes (anything else throws `wpt: unexpected …`); `--reporter=verbose` prints per-strategy counts. Where the runtime has a global `URLPattern` (not Node 22), "agrees with the runtime's URLPattern" checks every in-scope, non-skipped case (the resolved input, groups as read) against it, as do the `EMPTY_SEGMENT_CASES` / `PERCENT_ENCODING_CASES` / `GROUP_PARAM_CASES` side tables. +- `test/wpt.test.ts`: URLPattern WPT data, vendored verbatim (to sync, copy upstream's `urlpattern/resources/urlpatterntestdata.json` and update the SHA in the file header). Read like WPT's runner (`urlpatterntests.js`): `expected_obj: "error"` must throw `rou3:` (except `ACCEPTED_INVALID_PATTERNS`), `baseURL` / URL-string inputs resolve to their pathname, every input is percent-encoded like `new URL().pathname` (`encodePathname`, checked against the runtime's URLPattern in `PERCENT_ENCODING_CASES`), and entries that are not a lone `pathname` pattern are counted as out of scope. Groups compare with `toStrictEqual` (`null` in the data = an unset group = `undefined`); the one modelled difference is `expectedGroups()`: the tree leaves an unset param out of `params`, so for tree strategies an unset URLPattern group ≡ an absent key (a present `undefined` param still differs). Diffs live in `KNOWN_DIFFS`, `REGEXP_ONLY_KNOWN_DIFFS`, `ROUTER_KNOWN_DIFFS`: maps from label to rou3's exact result (groups, `null` for no match; `split(regexp, router)` where the regex and the tree also differ), each asserted to differ from URLPattern **and** to equal the stored result, so a behaviour PR that changes a listed case must update its entry. Rejected syntax is in `RESERVED_PATTERNS` (asserted to throw); an entry the data no longer reaches fails. Each skip names its reason and checks the exact entry shape that reason describes (anything else throws `wpt: unexpected …`); `--reporter=verbose` prints per-strategy counts. Where the runtime has a global `URLPattern` (not Node 22), "agrees with the runtime's URLPattern" checks every in-scope, non-skipped case (the resolved input, groups as read) against it, as do the `EMPTY_SEGMENT_CASES` / `PERCENT_ENCODING_CASES` / `GROUP_PARAM_CASES` / `LEADING_GROUP_CASES` side tables (with `EMPTY_SEGMENT_DIFFS` / `LEADING_GROUP_DIFFS`: where rou3 matches and URLPattern doesn't). ## Regex fixtures and sweeps diff --git a/README.md b/README.md index a4badf9..dbc5a0c 100644 --- a/README.md +++ b/README.md @@ -145,6 +145,8 @@ A route can have only one catch-all. `**`, `**:name`, and a `:name+` / `:name*` Groups can't be nested or repeated (`{...}+` and `{...}*` throw). +A pattern can start with a group. A group that starts with `/` is part of the path, as in URLPattern: `{/:lang}?/docs` matches `/docs` and `/en/docs`, and `{/:lang}?` matches `/` and `/en`. Write `/{/:lang}?/docs` for a route that starts with an empty segment (`//docs`, `//en/docs`). A pattern that doesn't start with `/` gets one (`users/:id` is `/users/:id`), and so does each form of a leading group without one: `{v2}?/api` matches `/v2/api` and `/api`. Text right after a leading `{/…}?` throws (`{/a}?b`, `{/:id}?.png`, `{/a}?{.json}?`): without the group the route would not start with `/`. Follow it with `/`, another `{/…}` group, or nothing. + ### Escaping Escape `:`, `*`, `?`, `+`, `(`, `)`, `{` and `}` with a backslash to match them literally (a literal `?`, `{` or `}` is then [percent-encoded](#percent-encoding), like other literal text). Outside a regex constraint, any escaped character is a literal (`\\.` is `.`, `\\\\` is `\`), as in URLPattern. A `\` can't escape `/` or end a segment. @@ -174,7 +176,7 @@ findRoute(router, "GET", "/café/1"); // undefined ### Invalid patterns -`addRoute` throws a `rou3:` error that quotes the pattern when the syntax has no meaning, instead of silently matching something unexpected. For example: an unclosed `(` or `{`, a nested group, an empty group `()`, a modifier in the wrong place (`*?`, `**+`, `:x.png?`), a `?` after plain text (`/foo?`: lookup paths have no query string, escape a literal one as `\\?`), a `**` in the middle of a segment (`/a**b`), an invalid or repeated param name (`/:0`, `/:café`, `/:id$`, `/a/:x/:x`), a second catch-all, a `\/`, a capturing group inside a regex constraint (`/:x((a))`, use `(?:…)`), or an anchor (`^`, `$`), look-around or numbered backreference (`\1`) in a regex constraint, or a character from U+FFFD to U+FFFF (used internally). The router tests a constraint against its segment alone, while `routeToRegExp` puts it inline, where it would see the rest of the path, so the two would match different paths. +`addRoute` throws a `rou3:` error that quotes the pattern when the syntax has no meaning, instead of silently matching something unexpected. For example: an unclosed `(` or `{`, a nested group, an empty group `()`, a modifier in the wrong place (`*?`, `**+`, `:x.png?`), a `?` after plain text (`/foo?`: lookup paths have no query string, escape a literal one as `\\?`), a `**` in the middle of a segment (`/a**b`), an invalid or repeated param name (`/:0`, `/:café`, `/:id$`, `/a/:x/:x`), a second catch-all, a `\/`, a capturing group inside a regex constraint (`/:x((a))`, use `(?:…)`), or an anchor (`^`, `$`), look-around or numbered backreference (`\1`) in a regex constraint, or a character from U+FFFD to U+FFFF (used internally), or text right after a leading `{/…}?` group (`{/a}?b`). The router tests a constraint against its segment alone, while `routeToRegExp` puts it inline, where it would see the rest of the path, so the two would match different paths. ### Differences from URLPattern @@ -190,6 +192,7 @@ rou3 matches paths segment by segment in a tree, which leads to a few intentiona | Path normalization (`.`/`..`) | Resolved in input paths | Opt-in with `{ normalize: true }` | | Case sensitivity | Can be case-insensitive | Always case-sensitive | | Non-`/`-prefixed paths | Supported | Paths must start with `/` | +| Patterns without a leading `/` (`users/:id`, `{v2}?/api`) | Never match an absolute path | Get a `/` (`/users/:id`); a leading group, in each form without one (`{v2}?/api` matches `/v2/api` and `/api`) | | Optional group with text after a greedy capture in its segment (`/*{.webp}?`) | The capture takes what it can (`/a.webp`: `{ 0: "a.webp" }`) | The route with the group wins (`/a.webp`: `{ 0: "a" }`); a group holding only a param is that param, as in URLPattern (`/*-{:x}?` is `/*-:x?`, and `/a/*{:x}?`, which is `/a/*:x?`: its segment is required, no match on `/a`, and `/a/b` gives `{ 0: "b" }`, not `{ 0: "", x: "b" }`), except before more of its segment, where it stays a group (`/*-{:x}?(y)` on `/a--y`: `{ 0: "a", x: "-", 1: "y" }`, URLPattern `{ 0: "a-", 1: "y" }`) | | Optional group before more of its segment (`/:foo{x}?(.*)`) | The param takes as little as it can (`/abx`: `{ foo: "a", 0: "bx" }`) | The route with the group wins (`/abx`: `{ foo: "ab", 0: "" }`) | | Optional group that can match empty text (`/{:foo}{(\\d*)}?`) | Unset where it matches nothing (`/a`: `{ foo: "a" }`) | The router gives `""` (`/a`: `{ foo: "a", 0: "" }`); `routeToRegExp` leaves it unset | @@ -337,6 +340,8 @@ removeRoute(router, "GET", "/path/:name"); // "/path/:id" is still registered Pass the pattern as you registered it. Spellings that the tree can't tell apart are equivalent (`/a/` and `/a`, `/**.md` and `/**/*.md`), but `/path/*` does not remove `/path/:name`, and `/ab` does not remove `/a{b}`. +`removeRoute` throws the same `rou3:` error as `addRoute`, quoting the pattern, for a reserved group or modifier: `{...}+` / `{...}*`, text right after a leading `{/…}?` (`{/a}?b`), or a misplaced `+` / `*` (`/a/pre-:x+`). It does not check the rest of the [invalid patterns](#invalid-patterns), since no route was added for them: a malformed pattern such as `{oops/x` removes nothing. + ## Compiler For the fastest lookups, compile a router into a single function. The compiled function returns the same results as `findRoute` (or `findAllRoutes` with `matchAll: true`). diff --git a/src/_group-delimiters.ts b/src/_group-delimiters.ts index bb9eee2..4d1345c 100644 --- a/src/_group-delimiters.ts +++ b/src/_group-delimiters.ts @@ -1,4 +1,4 @@ -import { invalidSyntax, MISPLACED_MODIFIER } from "./operations/_utils.ts"; +import { absolutePattern, invalidSyntax, MISPLACED_MODIFIER } from "./operations/_utils.ts"; /** `[pre, body, suf, mod]` split of a `{...}` group, or `undefined`. */ export type GroupDelimiter = [pre: string, body: string, suf: string, mod: string | undefined]; @@ -56,6 +56,15 @@ const NAME_CHAR = /^[\w$\x80-]/; * Expand the first `{...}` / `{...}?` group of `path` into the routes it * stands for. `{...}+` / `{...}*` repetition is not supported: `input` (quoted * in the error) is rejected. + * + * A pattern starting with a group gets no `/` in front (see `addRoute`): each + * expansion is read on its own. One starting with `/` is absolute, as in + * URLPattern (`{/:a}?/b` is `/:a/b` or `/b`); any other one, the empty one + * too, is relative and gets a `/` like a pattern (`{a}?/b` is `/a/b` or `/b`, + * `{/:a}?` is `/:a` or `/`). One starting with `{` is left to the next group. + * Text right after a leading `{/…}?` (`{/a}?b`, `{/:a}?.png`, `{/a}?{b}?/c`) + * throws: without the group the route would be relative, a form URLPattern + * gives no meaning (it matches only `/ab`), so a `/b` would be a guess. */ export function expandGroupDelimiters(path: string, input: string = path): string[] | undefined { if (!path.includes("{")) return; @@ -88,7 +97,13 @@ export function expandGroupDelimiters(path: string, input: string = path): strin } const full = joinGroup(joinGroup(pre, body, input), suf, input); - return mod ? [full, joinGroup(pre, suf, input)] : [full]; + const expanded = mod ? [full, joinGroup(pre, suf, input)] : [full]; + if (pre) return expanded; + // After a leading `{/…}?`: `/`, another `{/…}` group or nothing + if (mod && body.charCodeAt(0) === 47 /* '/' */ && suf && !/^\{?\//.test(suf)) { + invalidSyntax("text after a leading `{/...}?`", input); + } + return expanded.map(absolutePattern); } /** diff --git a/src/operations/_utils.ts b/src/operations/_utils.ts index 6ec4e66..f88caf8 100644 --- a/src/operations/_utils.ts +++ b/src/operations/_utils.ts @@ -154,6 +154,17 @@ export function checkConstraints(route: string): void { } } +/** + * A relative pattern (`foo/:id`) with a `/` in front, as `addRoute`, + * `removeRoute` and `routeToRegExp` read it. A pattern starting with a `{` + * group is left alone: `expandGroupDelimiters` reads each expansion of it + * the same way (`{/:a}?/b` is absolute, as in URLPattern: `/:a/b` or `/b`, + * not `//b`; the empty one of `{/:a}?` is `/`). + */ +export function absolutePattern(path: string): string { + return /^[/{]/.test(path) ? path : `/${path}`; +} + /** * Throws a `rou3:` error for pattern syntax with no meaning (yet), quoting the * route as written. @@ -280,9 +291,14 @@ export function splitRoute(path: string): string[] { * modifiers), shared by `addRoute` and `removeRoute`: its pre-expansion text * with trailing empties dropped and static segments keyed like the tree, so * spellings the tree cannot tell apart (`/a/:x?/` vs `/a/:x?`, `\)` vs `)`) - * share one identity (compared through `routeId`). + * share one identity (compared through `routeId`). A pattern starting with a group (`{/:a}?/b`, the only + * one here without a leading `/`) is read after a `/` (the split would drop + * its first piece) and marked with a `{`, which no other identity starts + * with: read after a `/`, `{a}?/b` would be the same text as `/{a}?/b`, and + * both register `/a/b`. */ export function expandedRouteId(path: string): string { + if (path.charCodeAt(0) !== 47 /* '/' */) return `{${expandedRouteId(`/${path}`)}`; return ( "/" + splitRoute(encodeEscapes(path)) diff --git a/src/operations/add.ts b/src/operations/add.ts index 34f7e20..e70fa49 100644 --- a/src/operations/add.ts +++ b/src/operations/add.ts @@ -5,6 +5,7 @@ import { createRouter } from "../context.ts"; import { NullProtoObj } from "../object.ts"; import type { Node, RouterContext, ParamsIndexMap } from "../types.ts"; import { + absolutePattern, checkConstraints, decodeEscapes, encodeEscapes, @@ -31,6 +32,12 @@ import { * capture the segment is one regex, so a greedy capture takes what it can * (`/*-:x?` on `/--` is `{ 0: "-" }`, `/:a(\\d+):b?` on `/12` `{ a: "12" }`). * + * A pattern without a leading `/` gets one (`foo/:id`). One starting with a + * group gets it per expansion (`absolutePattern`): `{/:a}?/b` is absolute, as + * in URLPattern (`/:a/b` or `/b`), while `{a}?/b` is `/a/b` or `/b`. Text + * right after a leading `{/…}?` throws (`{/a}?b`: without the group the route + * would be relative). + * * @throws a `rou3:` error for pattern syntax with no meaning (yet), quoting * the pattern: an unclosed `(`, unbalanced or nested `{}`, `{…}+` / `{…}*`, * a `?` / `+` / `*` anywhere but after a whole-segment `:name` (`?` also @@ -50,9 +57,7 @@ export function addRoute( data?: T, ): void { method = method.toUpperCase(); - if (path.charCodeAt(0) !== 47 /* '/' */) { - path = `/${path}`; - } + path = absolutePattern(path); checkConstraints(path); _add(ctx, method, path, data); } @@ -286,8 +291,9 @@ export function skipGroup(path: string, input: string, unnamed: Unnamed = same): const count = (p: string) => _add(createRouter(), "", p, undefined, undefined, input); const before = count(pre); // Joined like `expandGroupDelimiters` joins them: `/:a{(\d+)}?` holds an - // unnamed `(\d+)`, not `:a`'s constraint - const skip = count(joinGroup(pre, body, input)) - before; + // unnamed `(\d+)`, not `:a`'s constraint; a relative leading group is + // read after its `/` (`{(\d+)}?/*`) + const skip = count(absolutePattern(joinGroup(pre, body, input))) - before; return skip ? (index) => unnamed(index < before ? index : index + skip) : unnamed; } diff --git a/src/operations/remove.ts b/src/operations/remove.ts index 6746943..3a88218 100644 --- a/src/operations/remove.ts +++ b/src/operations/remove.ts @@ -1,6 +1,7 @@ import { expandGroupDelimiters } from "../_group-delimiters.ts"; import type { RouterContext, Node } from "../types.ts"; import { + absolutePattern, encodeEscapes, expandedRouteId, expandModifiers, @@ -22,33 +23,42 @@ import { export function removeRoute(ctx: RouterContext, method: string = "", path: string): void { // Normalize exactly like `addRoute`, or removal targets a different route method = method.toUpperCase(); - if (path.charCodeAt(0) !== 47 /* '/' */) { - path = `/${path}`; - } - _removeRoute(ctx, method, path); + _removeRoute(ctx, method, absolutePattern(path)); } -/** Mirrors `_add` in add.ts, including how the `route` identity is derived. */ -function _removeRoute(ctx: RouterContext, method: string, path: string, route?: string): void { - const groupExpanded = expandGroupDelimiters(path); +/** + * Mirrors `_add` in add.ts, including how the `route` identity is derived. + * `input` is the pattern as written, quoted in errors (as `addRoute` does). + */ +function _removeRoute( + ctx: RouterContext, + method: string, + path: string, + route?: string, + input: string = path, +): void { + const groupExpanded = expandGroupDelimiters(path, input); if (groupExpanded) { // As in `_add`: a single expansion is that route if (groupExpanded.length > 1) route ??= expandedRouteId(path); for (const expandedPath of groupExpanded) { - _removeRoute(ctx, method, expandedPath, route); + _removeRoute(ctx, method, expandedPath, route, input); } return; } + // A malformed `{…` (no group to expand, `addRoute` rejects it) has no + // leading `/`: it registered nothing + if (path.charCodeAt(0) !== 47 /* '/' */) return; path = encodeEscapes(path); const segments = splitRoute(path); - const modExpanded = expandModifiers(segments); + const modExpanded = expandModifiers(segments, input); if (modExpanded) { route ??= expandedRouteId(path); for (const expandedPath of modExpanded) { - _removeRoute(ctx, method, expandedPath, route); + _removeRoute(ctx, method, expandedPath, route, input); } return; } diff --git a/src/regexp-to-route.ts b/src/regexp-to-route.ts index 6a99bcc..f770812 100644 --- a/src/regexp-to-route.ts +++ b/src/regexp-to-route.ts @@ -6,6 +6,7 @@ // follow the same conventions convert too; constructs outside the dialect // throw. +import { expandGroupDelimiters, scanFirstGroup } from "./_group-delimiters.ts"; import { fromGroupName } from "./_group-names.ts"; import { encodeLiteral } from "./operations/_utils.ts"; @@ -78,7 +79,17 @@ export function regExpToRoute(regexp: RegExp | string): string { return "/"; } - return "/" + parseSegments(src, true, !dotConstraint).join("/"); + // A route starting with a `{/…}?` group (see `mergeGroup`) is absolute as + // is; after a `\/` the group follows an empty first segment (`/{/a}?`) + const route = parseSegments(src, true, !dotConstraint).join("/"); + if (route.charCodeAt(0) !== 123 /* { */ || src.startsWith("\\/")) return `/${route}`; + // Text after a leading group (`{/a}?{b}?/c`) throws like in `addRoute`, + // quoting the whole route + const check = (r: string): void => { + for (const p of expandGroupDelimiters(r, route) || []) if (p.charCodeAt(0) === 123) check(p); + }; + check(route); + return route; } // The look-behind-free endings `withTrailingSlash` emits, as `RegExp#source` @@ -496,7 +507,7 @@ function applyOptional( } // Literal / mixed optional segments, possibly with optionals of their own // (`{/sub/**}?`) -> `{/...}?` merged onto the previous segment. - mergeGroup(segments, `/${parseSegments(inner, last, dot, true).join("/")}`); + mergeGroup(segments, `/${parseSegments(inner, last, dot, true).join("/")}`, inGroup); return; } // In-segment optional -> `{...}?` merged onto the previous segment. @@ -520,9 +531,23 @@ function optionalUnits(src: string): [inner: string, lazy: boolean][] | undefine return units.length > 0 ? units : undefined; } -function mergeGroup(segments: string[], body: string): void { +/** + * Append the optional group `{body}?` to the previous segment. With none, a + * group of whole segments starts the route (`{/a}?/b`, absolute as in + * URLPattern); a group inside a group would nest (also where `body` holds one: + * `(?:\/a(?:\/b)?)?`), and a leading in-segment one (`{a}?`) is relative: + * those throw. + */ +function mergeGroup(segments: string[], body: string, inGroup?: boolean): void { + if (scanFirstGroup(body)) { + throw new Error(`rou3: no route has a group inside a group in "{${body}}?"`); + } if (segments.length === 0) { - throw new Error(`rou3: optional group "{${body}}?" has no preceding segment`); + if (inGroup || body.charCodeAt(0) !== 47 /* / */) { + throw new Error(`rou3: optional group "{${body}}?" has no preceding segment`); + } + segments.push(`{${body}}?`); + return; } segments[segments.length - 1] += `{${body}}?`; } diff --git a/src/regexp.ts b/src/regexp.ts index 98d4d66..8914c76 100644 --- a/src/regexp.ts +++ b/src/regexp.ts @@ -3,6 +3,7 @@ import { toGroupName } from "./_group-names.ts"; import { createRouter } from "./context.ts"; import { addRoute, getParamRegexp, skipGroup, type Unnamed } from "./operations/add.ts"; import { + absolutePattern, encodeEscapes, expandModifiers, PARAM_MODIFIER, @@ -75,9 +76,7 @@ const SOME = "[\\s\\S]+"; * routeToRegExp("/v:version?"); // /^\/v(?:(?[^/]+?))?\/?$/ */ export function routeToRegExp(route: string = "/"): RegExp { - if (route.charCodeAt(0) !== 47 /* '/' */) { - route = `/${route}`; - } + route = absolutePattern(route); // Validate with the router itself: every pattern it rejects (see // `addRoute`) throws here with the same error. addRoute(createRouter(), "", route); @@ -160,9 +159,11 @@ function inlineOptionalGroup(route: string, input: string, unnamed?: Unnamed): R if (mod !== "?" || body === "") { return; } - // The two expansions, joined like `expandGroupDelimiters` joins them - const base = joinGroup(pre, suf); - const full = joinGroup(joinGroup(pre, body), suf); + // The two expansions, joined like `expandGroupDelimiters` joins them; a + // leading group's relative expansion gets a `/` (`{a}?/b` is `/a/b` or + // `/b`, `{:x}?(\d+)` is `/:x…(\d+)` or `/(\d+)`) + const base = absolutePattern(joinGroup(pre, suf)); + const full = absolutePattern(joinGroup(joinGroup(pre, body), suf)); // A group with more of its segment after it (`/{:x}?(\d+)`) const inSegment = suf !== "" && suf.charCodeAt(0) !== 47; /* '/' */ if ( diff --git a/test/_regexp-cases.ts b/test/_regexp-cases.ts index d946bd7..955be57 100644 --- a/test/_regexp-cases.ts +++ b/test/_regexp-cases.ts @@ -398,6 +398,37 @@ export const regexpCases: Record = { match: [["/xb", { a: "x" }]], noMatch: ["/x", "/b"], }, + // A pattern starting with a `{/…}` group is absolute, as in URLPattern: no + // `/` in front, so no empty first segment (`//b`). A relative expansion + // gets one (`{a}?/b` is `/a/b` or `/b`). + "{/:a}?/b": { + regex: /^(?:\/(?[^/]+))?\/b\/?$/, + match: [ + ["/b", { a: undefined }], + ["/x/b", { a: "x" }], + ["/x/b/", { a: "x" }], + ], + noMatch: ["//b", "//x/b", "/x/y/b", "/"], + }, + "{/:a}/b": { + regex: /^\/(?[^/]+)\/b\/?$/, + match: [["/x/b", { a: "x" }]], + noMatch: ["/b", "//x/b", "//b"], + }, + "{/*}?/b": { + regex: /^(?:\/(?<_0>[^/]*))?\/b\/?$/, + match: [ + ["/b", { "0": undefined }], + ["//b", { "0": "" }], + ["/x/b", { "0": "x" }], + ], + noMatch: ["///b", "/x/y/b"], + }, + "{a}?/b": { + regex: /^(?:\/a)?\/b\/?$/, + match: [["/b"], ["/a/b"]], + noMatch: ["//b", "/ab", "/a"], + }, "/:foo{}bar": { regex: /^\/(?[^/]+?)bar\/?$/, match: [["/xbar", { foo: "x" }]], @@ -446,6 +477,16 @@ export const regexpCases: Record = { ], noMatch: ["/x/a", "/x/"], }, + // ... also leading a relative pattern: both expansions get their `/`, so + // the one without the group lines up (no alternation, no duplicate `_0`) + "{:x}?(\\d+)": { + regex: /^\/(?:(?[^/]+?))?(?<_0>\d+)\/?$/, + match: [ + ["/a12", { x: "a", "0": "12" }], + ["/1", { x: undefined, "0": "1" }], + ], + noMatch: ["/a", "/1/2"], + }, "/:foo{(\\d+)}?": { regex: /^\/(?[^/]+?)(?:(?<_0>\d+))?\/?$/, match: [ @@ -1420,6 +1461,7 @@ export const SWEEP_DUPLICATE_NAME_PATTERNS: ReadonlySet = new Set([ "/a/:x{(\\d+)}?/**", "/a/:x{(\\d+)}?/:y?", "/a/:x{(\\d+)}?/b{.json}?", + "{/:x}?/:y?", // An empty segment followed only by optional ones expands like the router. "/{en}?/:page?", "/docs/{v2}?/:page?", @@ -1430,6 +1472,7 @@ export const SWEEP_DUPLICATE_NAME_PATTERNS: ReadonlySet = new Set([ "/a/{:x}?(\\d+)/b{.json}?", "/{a-}?(\\d+)/b{.json}?", "/a/{a-}?(\\d+)/b{.json}?", + "{/a}?{/:x}?/c", // A mid-segment optional group after a greedy capture, also where both can // end the same way (`-x` / `-x-x`). (An optional param, `*-:x?`, compiles // in place like the tree.) @@ -1676,6 +1719,25 @@ function allSweepPatterns(): string[] { "/a{/(\\d+)}?/**", "/x{(\\d+)}?/*", "/a{/**}?/*-:x?", + // A pattern starting with a group: an expansion starting with `/` is + // absolute, any other gets one (`{a}?/b`, `{a}?b`, the empty one of + // `{/:x}?`); several leading groups, and the same group after a `/`. + "{/:x}?/b", + "{/:x}?", + "{/:x}?/:y?", + "{/:x(\\d+)}?/:y", + "{/a}?{/:x}?/c", + "{/a}?{/b}?", + "{/a/:x}?", + "{/a/*}?/b", + "{/**}?/b", + "{/:x*}?/b", + "{/:x}/b", + "{a}?/b", + "{:x}?/b", + "{a}?{/b}?/c", + "{a}?b", + "/{/:x}?/b", ...Object.keys(regexpCases), // Removed from `regexpCases` without duplicate named groups. ...PCRE2_DUPLICATE_NAME_ROUTES, @@ -1751,6 +1813,12 @@ export const UNCLOSED_GROUP_ROUTES: readonly string[] = [ * wrong or silent meaning, or threw a raw `SyntaxError`. */ export const RESERVED_SYNTAX_ROUTES: readonly string[] = [ + // Text right after a leading `{/…}?` group: without the group the route + // would be relative, a form URLPattern gives no meaning (it matched `/b` + // for `{/a}?b`). + "{/a}?b", + "{/:a}?.png", + "{/a}?{.json}?", // A repeat modifier on a constrained param dropped the constraint in the // tree (`/a/b/c` matched with `x: "b/c"`, the regex kept it). "/a/:x(\\d+)+", diff --git a/test/bench/bundle.test.ts b/test/bench/bundle.test.ts index 5dd9927..2623447 100644 --- a/test/bench/bundle.test.ts +++ b/test/bench/bundle.test.ts @@ -174,8 +174,14 @@ describe("benchmark", () => { // `plain` check (any capture-only segment with one required name). // -29B raw / -19B gzip: `expandGroupDelimiters` returns a `{:x}?` rewrite alone // (the caller expands the next group). - expect(bytes).toBeLessThanOrEqual(11775); // <11.78kb - expect(gzipSize).toBeLessThanOrEqual(4985); // <4.99kb + // +~165B raw / +~83B gzip: a pattern starting with a `{…}` group gets no + // `/` in front (`absolutePattern`); each of its expansions does unless it + // starts with one, so `{/:a}?/b` is `/:a/b` or `/b`, not `//b`. Its + // removal identity is marked apart from `/{…}`'s (`{a}?/b` vs `/{a}?/b`), + // `skipGroup` counts a relative one's captures after its `/`, and text + // right after a leading `{/…}?` (`{/a}?b`) throws. + expect(bytes).toBeLessThanOrEqual(11940); // <11.94kb + expect(gzipSize).toBeLessThanOrEqual(5070); // <5.07kb }); }); diff --git a/test/find.test.ts b/test/find.test.ts index 4fd826f..9232490 100644 --- a/test/find.test.ts +++ b/test/find.test.ts @@ -338,6 +338,183 @@ describe("a `{` / `}` ends a param name", () => { }); }); +describe("a pattern starting with a `{…}` group", () => { + // Read expansion by expansion: one starting with `/` is absolute, as in + // URLPattern (`{/:a}?/b` is `/:a/b` or `/b`, never `//b`); any other one, + // the empty one too, is relative and gets a `/` like a pattern without one + // (`{a}/b` is `/a/b`, `{/:a}?` also `/`). `[pattern, path, params]`, `null` + // for no match. + const cases: [string, string, Record | null][] = [ + ["{/:a}?/b", "/b", {}], + ["{/:a}?/b", "/x/b", { a: "x" }], + ["{/:a}?/b", "//b", null], + ["{/:a}?/b", "//x/b", null], + ["{/:a}/b", "/x/b", { a: "x" }], + ["{/:a}/b", "//x/b", null], + ["{/:a}/b", "/b", null], + ["{/:a}?", "/", {}], + ["{/:a}?", "/x", { a: "x" }], + ["{/:a}?", "//x", null], + ["{/:a}?", "//", null], + ["{/:a(\\d+)}?/b", "/1/b", { a: "1" }], + ["{/:a(\\d+)}?/b", "/b", {}], + ["{/:a(\\d+)}?/b", "/x/b", null], + ["{/*}?/b", "/b", {}], + ["{/*}?/b", "/x/b", { "0": "x" }], + ["{/*}?/b", "//b", { "0": "" }], + ["{/a/:b}?", "/", {}], + ["{/a/:b}?", "/a/x", { b: "x" }], + ["{/a/:b}?", "//a/x", null], + ["{/:foo}bar", "/bazbar", { foo: "baz" }], + ["{/a}b", "/ab", {}], + ["{/}a", "/a", {}], + ["{}/a", "/a", {}], + ["{}/a", "//a", null], + ["{/:a}?/:b?", "/", {}], + ["{/:a}?/:b?", "/x", { a: "x" }], + ["{/:a}?/:b?", "/x/y", { a: "x", b: "y" }], + // Several leading groups: the one left after the first is read the same + ["{/a}?{/:b}?/c", "/c", {}], + ["{/a}?{/:b}?/c", "/a/c", {}], + ["{/a}?{/:b}?/c", "/x/c", { b: "x" }], + ["{/a}?{/:b}?/c", "/a/x/c", { b: "x" }], + ["{/a}?{/:b}?/c", "//c", null], + ["{/a}?{/b}?", "/", {}], + ["{/a}?{/b}?", "/b", {}], + ["{/a}?{/b}?", "/a/b", {}], + ["{/a}?{/b}?", "//b", null], + // A relative expansion gets a `/` (URLPattern never matches one) + ["{a}/b", "/a/b", {}], + ["{:x}/b", "/y/b", { x: "y" }], + ["{a}?/b", "/a/b", {}], + ["{a}?/b", "/b", {}], + ["{a}?/b", "//b", null], + ["{:x}?/b", "/y/b", { x: "y" }], + ["{:x}?/b", "/b", {}], + ["{:x}?/b", "//b", null], + // Unnamed captures in a relative leading group are counted after its `/` + ["{(\\d+)}?/*", "/x", { "1": "x" }], + ["{(\\d+)}?/*", "/5/x", { "0": "5", "1": "x" }], + ["{*}?/(\\d+)", "/5", { "1": "5" }], + ["{a}?{/b}?/c", "/a/b/c", {}], + ["{a}?{/b}?/c", "/b/c", {}], + ["{a}?{/b}?/c", "/c", {}], + // An escaped `{` is a literal: the pattern is relative + ["\\{/a\\}", "/%7B/a%7D", {}], + ]; + const patterns = [...new Set(cases.map(([pattern]) => pattern))]; + const routers = new Map(patterns.map((pattern) => [pattern, createRouter([pattern])])); + const lookups = { + findRoute: (pattern: string, path: string) => findRoute(routers.get(pattern)!, "GET", path), + compiledLookup: (pattern: string, path: string) => + compileRouter(routers.get(pattern)!)("GET", path), + aotLookup: (pattern: string, path: string) => + // eslint-disable-next-line no-new-func + new Function(`return ${compileRouterToString(routers.get(pattern)!)}`)()("GET", path), + }; + for (const [name, match] of Object.entries(lookups)) { + it.each(cases)(`%j on %j (${name})`, (pattern, path, params) => { + const result = match(pattern, path); + expect(result ? { ...result.params } : null).toEqual(params); + }); + } + + it.each(cases)("%j on %j (routeToRegExp)", (pattern, path, params) => { + // An alternation fallback (`{/a}?{/:b}?/c`) needs duplicate named groups + if (needsDuplicateNames(pattern)) { + expect(() => routeToRegExp(pattern)).toThrow(/^rou3: .*duplicate named groups/); + return; + } + expect(routeToRegExp(pattern).test(path)).toBe(params !== null); + }); + + it("removes by the pattern as written", () => { + const r = createRouter(patterns); + // The same expansions after a `/` are other routes, left alone + addRoute(r, "GET", "/b", { path: "/b" }); + addRoute(r, "GET", "/{/:a}?/b", { path: "/{/:a}?/b" }); + for (const pattern of patterns) removeRoute(r, "GET", pattern); + expect(findRoute(r, "GET", "/b")?.data).toEqual({ path: "/b" }); + expect(findRoute(r, "GET", "//b")?.data).toEqual({ path: "/{/:a}?/b" }); + expect(findRoute(r, "GET", "//x/b")?.data).toEqual({ path: "/{/:a}?/b" }); + expect(findRoute(r, "GET", "/x/b")).toBeUndefined(); + removeRoute(r, "GET", "/b"); + removeRoute(r, "GET", "/{/:a}?/b"); + expect(r.root).toEqual(createEmptyRouter().root); + + // Two leading groups that differ only before their first `/` share the + // `/b` node: removing one leaves the other's entry + const s = createRouter(["{/:a}?/b", "{x/:a}?/b"]); + removeRoute(s, "GET", "{/:a}?/b/"); + expect(findRoute(s, "GET", "/b")?.data).toEqual({ path: "{x/:a}?/b" }); + expect(findRoute(s, "GET", "/y/b")).toBeUndefined(); + removeRoute(s, "GET", "{x/:a}?/b"); + expect(s.root).toEqual(createEmptyRouter().root); + }); + + it("keeps a leading group's identity apart from the same group after a `/`", () => { + // Both register `/a/b` (`{a}?/b` as `/a/b` or `/b`, `/{a}?/b` as `/a/b` or `//b`) + for (const [removed, kept] of [ + ["{a}?/b", "/{a}?/b"], + ["/{a}?/b", "{a}?/b"], + ]) { + const r = createRouter([removed, kept]); + removeRoute(r, "GET", removed); + expect(findRoute(r, "GET", "/a/b")?.data, removed).toEqual({ path: kept }); + } + }); + + it("removes nothing for a malformed pattern starting with `{`", () => { + // `addRoute` rejects these; without a group to expand they have no + // leading `/` and would split into another route's segments + for (const pattern of ["{oops/users/:id", "{abc/x", "{(}/x", "{", "{a"]) { + const r = createRouter(["/", "/x", "/users/:id"]); + expect(() => addRoute(createEmptyRouter(), "", pattern), pattern).toThrow(/^rou3: /); + removeRoute(r, "GET", pattern); + expect(findRoute(r, "GET", "/")?.data, pattern).toEqual({ path: "/" }); + expect(findRoute(r, "GET", "/x")?.data, pattern).toEqual({ path: "/x" }); + expect(findRoute(r, "GET", "/users/1")?.data, pattern).toEqual({ path: "/users/:id" }); + } + }); + + it("rejects text right after a leading `{/…}?` group", () => { + // Without the group the route would be relative: URLPattern gives that + // form no meaning (`{/a}?b` matches only `/ab`), so it is reserved + for (const pattern of [ + "{/a}?b", + "{/:a}?.png", + "{/a}?{.json}?", + "{/a}?{b}?/c", + "{/a}?\\{x", + "{/a}?{/b}?c", + ]) { + const message = `rou3: text after a leading \`{/...}?\` (${pattern})`; + expect(() => addRoute(createEmptyRouter(), "", pattern), pattern).toThrow(message); + // `removeRoute` quotes the pattern as written too, not an expansion + expect(() => removeRoute(createEmptyRouter(), "", pattern), pattern).toThrow(message); + } + // ... and so for a misplaced modifier (it quoted `undefined`) + for (const pattern of ["/a/pre-:x+", "{/a}?/:x(\\d+)+"]) { + expect(() => removeRoute(createEmptyRouter(), "", pattern), pattern).toThrow( + new RegExp(`^rou3: misplaced .* \\(${pattern.replace(/[{}()?+\\]/g, "\\$&")}\\)$`), + ); + } + // Followed by `/`, another `{/…}` group or nothing, it is fine + for (const pattern of ["{/a}?/b", "{/a}?{/b}?", "{/a}?", "{/a}b", "{a}?b"]) { + expect(() => addRoute(createEmptyRouter(), "", pattern), pattern).not.toThrow(); + } + }); + + it("rejects `{/…}+` / `{/…}*`, quoting the pattern as written", () => { + expect(() => addRoute(createEmptyRouter(), "", "{/a}+")).toThrow( + "rou3: unsupported `{}+` ({/a}+)", + ); + expect(() => addRoute(createEmptyRouter(), "", "{/:a}*/b")).toThrow( + "rou3: unsupported `{}*` ({/:a}*/b)", + ); + }); +}); + describe("params sharing a segment (URLPattern)", () => { const router = createRouter([ "/a/:a-:b", diff --git a/test/overlap.test.ts b/test/overlap.test.ts index ced99dc..0033416 100644 --- a/test/overlap.test.ts +++ b/test/overlap.test.ts @@ -152,6 +152,11 @@ describe("compareRoutes", () => { ["/a{/b}?", "/a", "superset", "optional group matches without"], ["/a{/b}?", "/a/*", "subset", "optional group is a subset of trailing *"], ["/a{/b}?", "/a/c", "disjoint", "optional group rejects other suffix"], + ["{/:a}?/b", "/:a?/b", "equal", "leading group is absolute (URLPattern form)"], + ["{/:a}?/b", "//b", "disjoint", "leading group adds no empty segment"], + ["{/:a}?", "/", "superset", "leading group's empty expansion is the root"], + ["/{/:a}?/b", "//b", "superset", "a group after a `/` keeps it"], + ["{a}?/b", "/a{/b}?", "partial", "relative expansion gets a `/`"], // regex-constrained segments ["/user/:id(\\d+)", "/user/42", "superset", "regex accepts literal (precise)"], diff --git a/test/regexp-to-route.test.ts b/test/regexp-to-route.test.ts index 272b116..22762bd 100644 --- a/test/regexp-to-route.test.ts +++ b/test/regexp-to-route.test.ts @@ -440,6 +440,25 @@ describe("regExpToRoute", () => { expect(() => regExpToRoute(/^(?:foo)?\/?$/)).toThrow(/preceding segment/); }); + it("throws where the route would nest a group or follow a leading one with text", () => { + // `addRoute` rejects `{/a{/b}?}?/c`, `/z{/a{/b}?}?/c` (nested `{}`) and + // `{/a}?{b}?/c` (text after a leading group) + for (const re of [ + /^(?:\/a(?:\/b)?)?\/c\/?$/, + /^\/z(?:\/a(?:\/b)?)?\/c\/?$/, + /^(?:\/a)?(?:b)?\/c\/?$/, + /^(?:\/a)?b\/?$/, + ]) { + expect(() => regExpToRoute(re), re.source).toThrow(/^rou3: /); + } + // The error quotes the whole route, not the expansion that holds the text + expect(() => regExpToRoute(/^(?:\/a)?(?:\/b)?(?:c)?\/d\/?$/)).toThrow( + "rou3: text after a leading `{/...}?` ({/a}?{/b}?{c}?/d)", + ); + // ... while a leading group followed by a segment or another group reads back + expect(regExpToRoute(/^(?:\/a)?(?:\/b)?\/c\/?$/)).toBe("{/a}?{/b}?/c"); + }); + it("rejects out-of-dialect constructs instead of corrupting", () => { // Each of these was previously literalized into a wrong route (or crashed // with an internal TypeError); they must now throw a clear rou3: error. @@ -529,7 +548,9 @@ describe("regExpToRoute", () => { for (const [re, route] of cases) { expect(regExpToRoute(re), re.source).toBe(route); } - for (const route of ["/a{/(\\d+)}?/b", "/a{/(\\d+)}?"]) { + // A root one starts the route with the group (absolute, as in URLPattern) + expect(regExpToRoute(/^(?:\/(?<_0>\d+))?\/b\/?$/)).toBe("{/(\\d+)}?/b"); + for (const route of ["/a{/(\\d+)}?/b", "/a{/(\\d+)}?", "{/(\\d+)}?/b", "{/a}?/b"]) { const re = routeToRegExp(route); expect(regExpToRoute(re), route).toBe(route); } @@ -538,11 +559,9 @@ describe("regExpToRoute", () => { // regex over-matches the route), and reads back as `**` too. expect(regExpToRoute(/^\/a(?:\/(?<_0>(?:[\s\S]*[^/])?\/*?))??\/?$/)).toBe("/a/**"); expect(routeToRegExp("/a{/([\\s\\S]*)}?").source).toBe(routeToRegExp("/a/**").source); - // Unnamed `[^/]+` has no route form, nor does a root one (no segment to - // hold the `{/…}?` group). + // Unnamed `[^/]+` has no route form. expect(() => regExpToRoute(/^\/a(?:\/(?<_0>[^/]+))?\/?$/)).toThrow(/cannot contain/); expect(() => regExpToRoute(/^\/a(?:\/(?<_0>[^/]+)(?:\/b)?)?\/?$/)).toThrow(/cannot contain/); - expect(() => regExpToRoute(/^(?:\/(?<_0>\d+))?\/b\/?$/)).toThrow(/preceding segment/); // Nor an unnamed catch-all (no `:_0*`). expect(() => regExpToRoute(/^\/a(?:\/(?:(?<_0>[\s\S]*)\/)?(?[^/]*))?\/?$/)).toThrow( /^rou3: /, diff --git a/test/route-node-keys.test.ts b/test/route-node-keys.test.ts index d90b802..9877937 100644 --- a/test/route-node-keys.test.ts +++ b/test/route-node-keys.test.ts @@ -76,6 +76,17 @@ describe("routeNodeKeys", () => { ["/x{/a}?{/b}?", ["/x", "/x/a", "/x/a/b", "/x/b"]], // 4 registrations (`/a/:x/:y`, `/a/:x`, `/a/:y`, `/a`) onto 3 nodes. ["/a/:x?/:y?", ["/a", "/a/*", "/a/*/*"]], + // A leading `{/…}` group is absolute: no empty first segment. + ["{/:a}?/b", ["/b", "/*/b"]], + ["{/:a}/b", ["/*/b"]], + ["{/:a}?", ["/", "/*"]], + ["{/a}?{/:b}?/c", ["/a/c", "/a/*/c", "/c", "/*/c"]], + // ... and a relative expansion gets a `/`, like a relative pattern. + ["{a}?/b", ["/a/b", "/b"]], + ["{a}?b", ["/ab", "/b"]], + ["{:x}/b", ["/*/b"]], + // The same group after a `/` keeps its empty first segment. + ["/{/:a}?/b", ["//b", "//*/b"]], ]; it.each(cases)("%j -> %j", (pattern, keys) => { diff --git a/test/types.test-d.ts b/test/types.test-d.ts index c12c645..2946589 100644 --- a/test/types.test-d.ts +++ b/test/types.test-d.ts @@ -199,6 +199,18 @@ describe("types", () => { expectTypeOf>().toEqualTypeOf<{ x: string }>(); }); + it("should read a pattern starting with a group", () => { + expectTypeOf>().toEqualTypeOf<{ a: string | undefined }>(); + expectTypeOf>().toEqualTypeOf<{ a: string }>(); + expectTypeOf>().toEqualTypeOf<{ a: string | undefined }>(); + expectTypeOf>().toEqualTypeOf<{ foo: string }>(); + expectTypeOf>().toEqualTypeOf<{ + b: string | undefined; + }>(); + expectTypeOf>().toEqualTypeOf<{ x: string | undefined }>(); + expectTypeOf>().toEqualTypeOf<{ x: string }>(); + }); + // Types read names like `addRoute` but don't validate routes: a name it // rejects (`:0`, `:id$`) gives no key. it("should give no key for an invalid param name", () => { diff --git a/test/wpt.test.ts b/test/wpt.test.ts index 8b60b25..27ae46b 100644 --- a/test/wpt.test.ts +++ b/test/wpt.test.ts @@ -194,7 +194,9 @@ function normalizeGroups(groups: Record | undefined): Record({ "*/* → foo/bar [match]": null, "*/{*} → foo/bar [match]": null, - // Patterns without leading `/` — rou3 always prefixes `/` in regex (the - // router skips relative inputs). With a leading `/`, the `{:foo}(…)` ones - // agree (`GROUP_PARAM_CASES`). + // Patterns without leading `/` — rou3 prefixes `/` (a leading `{:foo}` + // group's expansions too), so the regex never matches a relative input + // (the router skips relative inputs). With a leading `/`, the `{:foo}(…)` + // ones agree (`GROUP_PARAM_CASES`). ":name → foobar [match]": null, "(foo)(.*) → foobarbaz [match]": null, "{(foo)bar}(.*) → foobarbaz [match]": null, @@ -639,6 +642,102 @@ describe("wpt urlpattern compatibility: percent-encoding", () => { }); }); +// Not in the WPT data (only as `expected_obj`: `/:foo\bar` is `{/:foo}bar`): +// a pattern starting with a `{/…}` group is absolute, so it gets no `/` in +// front (`{/:a}?/b` is `/:a?/b`, never `//b`). `[pattern, input, groups]` (as +// for `EMPTY_SEGMENT_CASES`), checked against the runtime's URLPattern. +const LEADING_GROUP_CASES: [string, string, Result][] = [ + ["{/:a}?/b", "/b", { a: undefined }], + ["{/:a}?/b", "/x/b", { a: "x" }], + ["{/:a}?/b", "//b", null], + ["{/:a}?/b", "//x/b", null], + ["{/:a}/b", "/x/b", { a: "x" }], + ["{/:a}/b", "//x/b", null], + ["{/:a}?", "/x", { a: "x" }], + ["{/:a}?", "//x", null], + ["{/:foo}bar", "/bazbar", { foo: "baz" }], + ["{/:a(\\d+)}?/b", "/1/b", { a: "1" }], + ["{/:a(\\d+)}?/b", "/b", { a: undefined }], + ["{/:a(\\d+)}?/b", "/x/b", null], + ["{/a/:b}?", "/a/x", { b: "x" }], + ["{/a/:b}?", "//a/x", null], + ["{/a}b", "/ab", {}], + ["{/}a", "/a", {}], + ["{}/a", "/a", {}], + ["{}/a", "//a", null], + ["{/a}?{/:b}?/c", "/c", { b: undefined }], + ["{/a}?{/:b}?/c", "/a/c", { b: undefined }], + ["{/a}?{/:b}?/c", "/x/c", { b: "x" }], + ["{/a}?{/:b}?/c", "/a/x/c", { b: "x" }], + ["{/a}?{/:b}?/c", "//c", null], + ["{a}?/b", "/b", {}], + ["{a}?/b", "//b", null], + ["{:x}?/b", "/b", { x: undefined }], + ["{:x}?/b", "//b", null], + // With a regex group after the param's group (`joinGroup`), a `{:x}?` + // rewrite after text, and unnamed numbering over the whole pattern + ["{/:foo}(\\d+)", "/a12", { foo: "a", "0": "12" }], + ["{/:foo}(\\d+)", "/a", null], + ["{/a}/*-{:x}?", "/a/b-c", { "0": "b", x: "c" }], + ["{/a}/*-{:x}?", "/a/--", { "0": "-", x: undefined }], + ["{/a}?/*-{:x}?", "/b-c", { "0": "b", x: "c" }], + ["{/a}?/*-{:x}?", "/a/b-", { "0": "b", x: undefined }], + ["{/(\\d+)}?/*", "/b", { "0": undefined, "1": "b" }], + ["{/(\\d+)}?/*", "/1/b", { "0": "1", "1": "b" }], +]; + +// Where rou3 differs: an expansion that does not start with `/` is relative +// and gets one, as a relative pattern does (URLPattern never matches it on an +// absolute path), and `{/:a}?` matches `/` like `/:a?` (URLPattern matches +// the empty pathname instead, which rou3 reads as `/`). `[pattern, input, rou3's params]`. +const LEADING_GROUP_DIFFS: [string, string, Record][] = [ + ["{/:a}?", "/", {}], + ["{a}/b", "/a/b", {}], + ["{:x}/b", "/y/b", { x: "y" }], + ["{a}?/b", "/a/b", {}], + ["{:x}?/b", "/y/b", { x: "y" }], + // Each expansion gets its `/`, also the one `inlineOptionalGroup` reads + // without the group (`{:x}?(\d+)` is `/:x…(\d+)` or `/(\d+)`) + ["{:foo}(\\d+)", "/a12", { foo: "a", "0": "12" }], + ["{:x}?(\\d+)", "/a12", { x: "a", "0": "12" }], + ["{:x}?(\\d+)", "/12", { x: "1", "0": "2" }], + ["{:x}?(\\d+)", "/1", { "0": "1" }], +]; + +describe("wpt urlpattern compatibility: leading groups", () => { + for (const strategy of strategies) { + for (const [pattern, input, groups] of LEADING_GROUP_CASES) { + // An alternation fallback (`{/a}?{/:b}?/c`) needs duplicate named groups (not Node 22) + const skip = !strategy.router && needsDuplicateNames(pattern); + it.skipIf(skip)(`${strategy.name}: ${pattern} → ${input}`, () => { + const { matched, params } = strategy.match(pattern, input); + expect(matched ? params : null).toStrictEqual(expectedGroups(strategy, groups)); + }); + } + for (const [pattern, input, params] of LEADING_GROUP_DIFFS) { + it(`${strategy.name}: ${pattern} → ${input} (rou3 only)`, () => { + const result = strategy.match(pattern, input); + expect(result.matched).toBe(true); + // `routeToRegExp` reports an unset group as `undefined` + expect(expectedGroups({ ...strategy, router: true }, result.params)).toStrictEqual(params); + }); + } + } + + it.runIf(URLPatternCtor)("agrees with URLPattern", () => { + for (const [pattern, input, groups] of LEADING_GROUP_CASES) { + const result = new URLPatternCtor({ pathname: pattern }).exec({ pathname: input }); + expect(result ? { ...result.pathname.groups } : null, `${pattern} → ${input}`).toStrictEqual( + groups, + ); + } + for (const [pattern, input] of LEADING_GROUP_DIFFS) { + const result = new URLPatternCtor({ pathname: pattern }).exec({ pathname: input }); + expect(result, `${pattern} → ${input}`).toBeNull(); + } + }); +}); + // Where rou3 still differs (see the README): `:name+` / `:name*` / `**` take // empty segments between others (URLPattern's `:name+` / `:name*` need a // value in each).