{"name":"rou3","version":"0.7.4","license":"MIT","_id":"rou3@0.7.4","maintainers":[{"name":"pi0","email":"pyapar@gmail.com"}],"homepage":"https://github.com/h3js/rou3#readme","bugs":{"url":"https://github.com/h3js/rou3/issues"},"dist":{"shasum":"690bff25ea1043207c9aecb4c290793be1535833","tarball":"http://registry-npm.ywwl.com/rou3/download/rou3-0.7.4.tgz","fileCount":7,"integrity":"sha512-I067614ZZYztQ9qK0pE0F2zpMbPI8vh/NyG4qw4YtbWSZKVcL+9HCGdlJH/UptS7usLuElna5OIPXbDQRx2IMA==","signatures":[{"sig":"MEQCIDUFD0BEt5CX5JDVnlv71ero7YAsNlu8Vj4Sjrcjrr2UAiBigF3+9B/oKc5mxUWA/JA7LPkrY1tCFq21Pd3fD4aLTA==","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":23219,"size":6626,"noattachment":false,"key":"/rou3/-/rou3-0.7.4.tgz"},"type":"module","types":"./dist/index.d.mts","exports":{".":"./dist/index.mjs","./compiler":"./dist/compiler.mjs"},"gitHead":"7942aa183fb3ac1fe976616a220d942d866ccff0","scripts":{"dev":"vitest","lint":"eslint . && prettier -c src test","test":"pnpm lint && pnpm test:types && vitest run --coverage","build":"obuild","release":"pnpm test && pnpm build && changelogen --release && git push --follow-tags && npm publish","lint:fix":"automd && eslint --fix . && prettier -w src test","bench:bun":"bun ./test/bench","bench:deno":"deno run -A ./test/bench/index.ts","bench:node":"node --expose-gc --allow-natives-syntax --disable-warning=ExperimentalWarning --experimental-strip-types ./test/bench/index.ts","test:types":"tsc --noEmit"},"_npmUser":{"name":"pi0","email":"pyapar@gmail.com"},"repository":{"url":"git+https://github.com/h3js/rou3.git","type":"git"},"_npmVersion":"10.9.2","description":"Lightweight and fast router for JavaScript.","directories":{},"sideEffects":false,"_nodeVersion":"22.14.0","_hasShrinkwrap":false,"packageManager":"pnpm@10.16.1","devDependencies":{"0x":"^6.0.0","jiti":"^2.5.1","automd":"^0.4.2","eslint":"^9.35.0","mitata":"^1.0.34","obuild":"^0.2.1","vitest":"^3.2.4","esbuild":"^0.25.9","listhen":"^1.9.0","prettier":"^3.6.2","typescript":"^5.9.2","@types/node":"^24.5.1","changelogen":"^0.6.2","rou3-latest":"npm:rou3@^0.7.3","@mitata/counters":"^0.0.8","eslint-config-unjs":"^0.5.0","@vitest/coverage-v8":"^3.2.4"},"_npmOperationalInternal":{"tmp":"tmp/rou3_0.7.4_1758102975142_0.08768763839611249","host":"s3://npm-registry-packages-npm-production"},"readme":"# 🌳 rou3\n\n<!-- automd:badges codecov bundlejs -->\n\n[![npm version](https://img.shields.io/npm/v/rou3)](https://npmjs.com/package/rou3)\n[![npm downloads](https://img.shields.io/npm/dm/rou3)](https://npm.chart.dev/rou3)\n[![bundle size](https://img.shields.io/bundlejs/size/rou3)](https://bundlejs.com/?q=rou3)\n[![codecov](https://img.shields.io/codecov/c/gh/h3js/rou3)](https://codecov.io/gh/h3js/rou3)\n\n<!-- /automd -->\n\nLightweight and fast router for JavaScript.\n\n- 🌲 **Tree-based lookups**, one node per path segment, with a fast path for static routes.\n- 🧩 **URLPattern-like syntax**: params, regex constraints, optional segments, groups and wildcards.\n- ⚡ **Compiler** that turns a router into one optimized function, at runtime or at build time.\n- 🧪 **Utilities** to compare patterns, find overlapping routes and convert routes to and from `RegExp`.\n- 📦 **Zero dependencies**, tree-shakeable, typed.\n\n## Install\n\n```sh\n# ✨ Auto-detect\nnpx nypm install rou3\n```\n\nrou3 is ESM only. It runs on Node.js 20.19+, Bun, Deno and modern browsers.\n\n## Quick start\n\n```js\nimport { createRouter, addRoute, findRoute, findAllRoutes, removeRoute } from \"rou3\";\n\nconst router = createRouter();\n\naddRoute(router, \"GET\", \"/about\", { page: \"about\" });\naddRoute(router, \"GET\", \"/users/:id\", { page: \"user\" });\naddRoute(router, \"GET\", \"/docs/**\", { page: \"docs\" });\n```\n\n`findRoute` returns the best match, or `undefined`:\n\n```js\nfindRoute(router, \"GET\", \"/about\");\n// { data: { page: \"about\" } }\n\nfindRoute(router, \"GET\", \"/users/42\");\n// { data: { page: \"user\" }, params: { id: \"42\" } }\n\nfindRoute(router, \"GET\", \"/docs/guide/intro\");\n// { data: { page: \"docs\" }, params: { _: \"guide/intro\" } }\n\nfindRoute(router, \"GET\", \"/missing\");\n// undefined\n```\n\n`findAllRoutes` returns every match, from the least to the most specific:\n\n```js\naddRoute(router, \"GET\", \"/docs/:section/intro\", { page: \"intro\" });\n\nfindAllRoutes(router, \"GET\", \"/docs/guide/intro\");\n// [\n//   { data: { page: \"docs\" }, params: { _: \"guide/intro\" } },\n//   { data: { page: \"intro\" }, params: { section: \"guide\" } },\n// ]\n```\n\n`removeRoute` removes a route by the pattern it was added with:\n\n```js\nremoveRoute(router, \"GET\", \"/users/:id\");\n```\n\nRoute data can be anything: a handler, a config object, an id. rou3 stores it and hands it back on a match.\n\n## Route patterns\n\nrou3 supports [URLPattern](https://developer.mozilla.org/en-US/docs/Web/API/URL_Pattern_API)-like syntax. A **segment** is the part of a path between two `/`.\n\n| Pattern                     | Example match                            | Params                                               |\n| --------------------------- | ---------------------------------------- | ---------------------------------------------------- |\n| `/path/to/resource`         | `/path/to/resource`                      | `{}`                                                 |\n| `/users/:name`              | `/users/foo`                             | `{ name: \"foo\" }`                                    |\n| `/users/:id(\\\\d+)`          | `/users/123`                             | `{ id: \"123\" }`                                      |\n| `/files/:ext(png\\|jpg)`     | `/files/png`                             | `{ ext: \"png\" }`                                     |\n| `/path/(\\\\d+)`              | `/path/123`                              | `{ \"0\": \"123\" }`                                     |\n| `/users/:id?`               | `/users` or `/users/123`                 | `{}` or `{ id: \"123\" }`                              |\n| `/files/:path+`             | `/files/a/b/c`                           | `{ path: \"a/b/c\" }`                                  |\n| `/files/:path*`             | `/files` or `/files/a/b`                 | `{}` or `{ path: \"a/b\" }`                            |\n| `/files/*.png`              | `/files/icon.png`                        | `{ \"0\": \"icon\" }`                                    |\n| `/files/file-*-*.png`       | `/files/file-a-b.png`                    | `{ \"0\": \"a\", \"1\": \"b\" }`                             |\n| `/path/**`                  | `/path/foo/bar`                          | `{ _: \"foo/bar\" }`                                   |\n| `/path/**:rest`             | `/path/foo/bar`                          | `{ rest: \"foo/bar\" }`                                |\n| `/**/_payload.json`         | `/_payload.json` or `/a/b/_payload.json` | `{ _: \"\" }` or `{ _: \"a/b\" }`                        |\n| `/**.md`                    | `/docs/intro.md`                         | `{ _: \"docs\", \"0\": \"intro\" }`                        |\n| `/book{s}?`                 | `/book` or `/books`                      | `{}`                                                 |\n| `/blog/:id(\\\\d+){-:title}?` | `/blog/123` or `/blog/123-my-post`       | `{ id: \"123\" }` or `{ id: \"123\", title: \"my-post\" }` |\n| `/files/:name.:ext`         | `/files/a.tar.gz`                        | `{ name: \"a\", ext: \"tar.gz\" }`                       |\n| `/v:version?`               | `/v` or `/v2`                            | `{}` or `{ version: \"2\" }`                           |\n\n> [!NOTE]\n> In JavaScript strings a regex backslash is written twice: `\"/users/:id(\\\\d+)\"` is the pattern `/users/:id(\\d+)`.\n\n### Params\n\n- **Named params** `:name` match one segment: `/users/:name`. They can also sit inside a segment: `/blog/:year-:month`. When several params share a segment, each one takes as little as it can, as in URLPattern: `/:a-:b` on `/x-y-z` gives `{ a: \"x\", b: \"y-z\" }`, and `/:name.:ext` on `/a.tar.gz` gives `{ name: \"a\", ext: \"tar.gz\" }`. A `*` takes as much as it can: `/*-:a` on `/x-y-z` gives `{ \"0\": \"x-y\", a: \"z\" }`.\n- **Regex constraints** `:name(regex)` only match when the regex does: `/users/:id(\\\\d+)`. The regex applies to one segment and can't contain `/`.\n- **Unnamed groups** `(regex)` capture into numbered keys `\"0\"`, `\"1\"`, …: `/path/(\\\\d+)`. Inside a regex, group with `(?:…)`: a capturing group there throws (`/:x((a))`, `/:x((?<n>a))`).\n- **Modifiers** go at the end of a whole-segment param:\n  - `:name?` optional (also works with a regex: `:id(\\\\d+)?`)\n  - `:name+` one or more segments\n  - `:name*` zero or more segments\n- **`?` inside a segment** makes only the param optional: `/pre-:x?` matches `/pre-` and `/pre-a`, but not `/`. Use a group for an optional segment: `/{pre-:x}?`. Where it matches, the route with the param wins (see the differences below).\n\n<details>\n<summary>Param naming rules</summary>\n\n- A name starts with a letter or `_` and goes on with word characters (`[A-Za-z_][A-Za-z0-9_]*`), as in URLPattern: `:v2` and `:_0` are names, `:0` and `:1st` throw.\n- Any other ASCII character but `$` ends a name, `-` included: `/blog/:year-:month` has two params, and `/users/:user-id` is the param `user` followed by a literal `-id` (write `:user_id` for one param). A group's `{` or `}` ends one too: `/:a{b}?` is the param `a` followed by an optional `b`.\n- A non-ASCII character or `$` right after a name throws (`/:café`, `/:id$`: URLPattern reads them as part of the name). To end a name early, escape the next character: `/:caf\\\\é` gives `{ caf }` followed by a literal `é`, and `/:id\\\\$` gives `{ id }` followed by a literal `$`.\n- A name can appear only once per route: `/a/:x/:x` throws.\n- A `:` must start a name. Write a literal colon as `\\\\:`.\n- `+` and `*` only repeat a whole-segment `:name` (`:id(\\d+)+` and `pre-:x+` throw).\n\n</details>\n\n### Wildcards\n\n- **`*`** matches one segment, or part of one, and captures it into a numbered key: `/files/*`, `/files/*.png`.\n- **`**`** matches zero or more segments and captures them into `_`: `/docs/**`.\n- **`**:name`** matches one or more segments and captures them into `name`: `/docs/**:path`. Like `:name` and `:name+`, it needs a value: `/docs//` doesn't match (see [empty segments](#trailing-slashes-and-empty-segments)).\n- **Segments after `**`** are matched from the **end** of the path, and the `**` takes whatever is in between. `/**/_payload.json` matches `_payload.json` in any directory, and `/blog/**:path/og.png` matches `og.png` anywhere under `/blog`.\n- **`**` followed by text** is short for `**/*<text>`: `/**.md` matches any path whose last segment ends in `.md`. Anywhere else in a segment, `**` throws (`/a**b`, `/a/x**`): write `*` for one capture or `\\\\*\\\\*` for a literal.\n\nA route can have only one catch-all. `**`, `**:name`, and a `:name+` / `:name*` that is not the last segment all count as one.\n\n### Groups\n\n`{...}` groups part of a pattern without capturing it. Add `?` to make it optional:\n\n- `/book{s}?` matches `/book` and `/books`.\n- `/users{/:id}?/posts` matches `/users/posts` and `/users/42/posts`.\n\nGroups can't be nested or repeated (`{...}+` and `{...}*` throw).\n\n### Escaping\n\nEscape `:`, `*`, `?`, `+`, `(`, `)`, `{` and `}` with a backslash to match them literally. Outside a regex constraint, any escaped character is a literal (`\\\\.` is `.`, `\\\\\\\\` is `\\`), as in URLPattern. A `\\` can't escape `/` or end a segment.\n\n```js\naddRoute(router, \"GET\", \"/static\\\\:path/\\\\*\\\\*\", {}); // matches only \"/static:path/**\"\naddRoute(router, \"GET\", \"/files/\\\\(2024\\\\)\", {}); // matches only \"/files/(2024)\"\n```\n\n### Invalid patterns\n\n`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.\n\n### Differences from URLPattern\n\nrou3 matches paths segment by segment in a tree, which leads to a few intentional differences:\n\n| Feature                       | URLPattern                         | rou3                                            |\n| ----------------------------- | ---------------------------------- | ----------------------------------------------- |\n| `*` (single star)             | Greedy catch-all `(.*)` across `/` | One segment (or part of one), `([^/]*)`         |\n| Trailing `*`                  | Required (`/foo/*` doesn't match `/foo`) | Optional (`/foo/*` matches `/foo`), so `use(\"/api/*\")`-style scopes cover `/api` too |\n| `**` (double star)            | Literal `**`                       | Catch-all, zero or more segments, one per route |\n| `(.*)` in a segment           | Greedy match across `/`            | Stays within the segment                        |\n| `{...}+` / `{...}*` groups    | Group repetition                   | Not supported (throws)                          |\n| Path normalization (`.`/`..`) | Resolved in input paths            | Opt-in with `{ normalize: true }`               |\n| Case sensitivity              | Can be case-insensitive            | Always case-sensitive                           |\n| Non-`/`-prefixed paths        | Supported                          | Paths must start with `/`                       |\n| Optional param after a greedy capture (`/*-:x?`, `/:a(\\d+):b?`) | The greedy capture takes what it can (`/--`: `{ 0: \"-\" }`; `/12`: `{ a: \"12\" }`) | The route with the param wins (`/--`: `{ 0: \"\", x: \"-\" }`; `/12`: `{ a: \"1\", b: \"2\" }`) |\n| Param names                   | Unicode identifiers                | `[A-Za-z_]\\w*`; a non-ASCII char or `$` right after one throws |\n| Empty segments in `:name*` / `:name+` | Every repeated segment needs a value (`/foo/:bar*` doesn't match `/foo//`) | A `:name*` may be empty (`/foo/:bar*` on `/foo//` is `{ bar: \"\" }`), a `:name+` needs a value as a whole (`/foo/:bar+` on `/foo//a` is `{ bar: \"/a\" }`) |\n| Percent-encoding              | Normalizes `%xx` sequences         | Input is not decoded                            |\n\n## Matching\n\n### Methods and paths\n\nThe paths you look up must start with `/` and the methods must be **UPPERCASE** (`\"GET\"`, not `\"get\"`). rou3 does not normalize lookup input, so do it before calling `findRoute`.\n\n### Routes for any method\n\nRegister a route with the method `\"\"` to match every method. It's useful for things like middleware or auth checks:\n\n```js\naddRoute(router, \"\", \"/users/*\", { auth: true }); // any method\naddRoute(router, \"GET\", \"/users/:id(\\\\d+)\", { handler: \"user\" });\n\nfindAllRoutes(router, \"GET\", \"/users/42\").map((m) => m.data);\n// [{ auth: true }, { handler: \"user\" }]\n\nfindRoute(router, \"GET\", \"/users/42\")?.data; // { handler: \"user\" }\nfindRoute(router, \"GET\", \"/users/me\")?.data; // { auth: true }\nfindRoute(router, \"POST\", \"/users/42\")?.data; // { auth: true }\n```\n\nA lookup sees the routes for its method and the method-agnostic ones together, and the most specific one wins. When two routes are equally specific, the one registered for the method wins over the method-agnostic one (and comes after it in `findAllRoutes`). A lookup with the method `\"\"` only sees method-agnostic routes.\n\n### Trailing slashes and empty segments\n\n- **At most one trailing slash** is ignored: `/users/foo/` matches `/users/:name`, `/users/foo//` does not.\n- In patterns, trailing slashes are ignored: `/users/`, `/users//` and `/users` are the same route.\n- **Empty segments in the middle are real**: `/a//b` does not match `/a/b`.\n- A `:name`, `:name+` or `**:name` needs a value, as in URLPattern: it never captures `\"\"`. A `*`, `**`, `:name*` or a regex constraint that can match empty (`:id(\\\\d*)`) takes an empty segment:\n\n```js\naddRoute(router, \"GET\", \"/admin/:id\", {});\naddRoute(router, \"GET\", \"/files/:path+\", {});\naddRoute(router, \"GET\", \"/raw/*\", {});\n\nfindRoute(router, \"GET\", \"/admin/\"); // undefined (the trailing slash is ignored)\nfindRoute(router, \"GET\", \"/admin//\"); // undefined (an empty segment)\nfindRoute(router, \"GET\", \"/files//\"); // undefined\nfindRoute(router, \"GET\", \"/files///\"); // params: { path: \"/\" } (two empty segments)\nfindRoute(router, \"GET\", \"/raw//\"); // params: { \"0\": \"\" }\n```\n\n### Path normalization\n\n`.` and `..` segments are **not** resolved by default. If your input paths may contain them, enable `normalize`:\n\n```js\nfindRoute(router, \"GET\", \"/foo/bar/../baz\", { normalize: true }); // matches \"/foo/baz\"\nfindAllRoutes(router, \"GET\", \"/foo/./bar\", { normalize: true }); // matches \"/foo/bar\"\n```\n\nThe [compiler](#compiler) accepts the same option: `compileRouter(router, { normalize: true })`.\n\n### Skipping params\n\nIf you only need the route data, pass `{ params: false }` to skip building the params object:\n\n```js\nfindRoute(router, \"GET\", \"/docs/guide\", { params: false });\n// { data: { page: \"docs\" } }\n```\n\n### Result ordering\n\n`findAllRoutes` returns matches from the **least to the most specific**, and `findRoute` returns the most specific one. This order is part of the public API: you can rely on it, for example to merge all matched route rules so that the most specific one wins.\n\n```js\nconst router = createRouter();\naddRoute(router, \"GET\", \"/**\", { name: \"catch-all\" });\naddRoute(router, \"GET\", \"/api/**\", { name: \"api\" });\naddRoute(router, \"GET\", \"/api/:v/users/:id\", { name: \"user\" });\n\nfindAllRoutes(router, \"GET\", \"/api/v1/users/42\").map((m) => m.data.name);\n// [\"catch-all\", \"api\", \"user\"]\n```\n\nThe [compiled](#compiler) `matchAll` function returns exactly the same results in the same order.\n\nIn short: static segments beat params, and params beat wildcards. Among routes that end on the same kind of segment, a constrained or required param beats an optional or unconstrained one. Registration order only breaks exact ties.\n\n<details>\n<summary>Detailed ordering rules</summary>\n\n- **Across the tree:** at each level, wildcard (`**`) matches come first, then single-segment params (`*`, `:name`), then static segments. Broader and shallower routes come before more static and deeper ones.\n- **Routes on the same tree node** (for example `/foo/*` and `/foo/:id(\\d+)`, see [Route node keys](#route-node-keys)): optional and unconstrained routes come before required and regex-constrained ones. Ties keep registration order. Method-agnostic routes are sorted together with the method's own routes, and on a tie the method-agnostic one comes first (so `findRoute` picks the method's own).\n- **Consistent with containment:** when no pattern uses optional syntax and each pattern contains the next (a `\"superset\"` per [`compareRoutes`](#pattern-overlap)), the result order is broadest first.\n- **Carve-out — optional syntax:** a pattern with `:name?`, `:name*` or `{...}?` registers one entry per variant, and results are ordered by the variant that matched, not by the whole pattern. A broader pattern can therefore come **last**:\n\n  ```js\n  const router = createRouter();\n  addRoute(router, \"GET\", \"/admin\", { name: \"admin\" });\n  addRoute(router, \"GET\", \"/admin/:page?\", { name: \"admin-page\" }); // superset of \"/admin\"\n\n  findAllRoutes(router, \"GET\", \"/admin\").map((m) => m.data.name);\n  // [\"admin\", \"admin-page\"] (the broader pattern is last)\n  ```\n\n  Both routes match `/admin` with an identical entry, so registration order decides: adding `/admin/:page?` first swaps them. If you need a strict pattern-level order with optional syntax, sort the result with [`compareRoutes`](#pattern-overlap).\n\n- **Segments after a wildcard:** a route like `/**/_payload.json` is anchored at the end of the path. On every path such a route matches, all matches are ranked **from the last segment backwards**: a literal segment beats a regex-constrained param, which beats a plain param or a segment covered by `**`. Ties fall back to the rules above. Paths that no such route matches are not affected:\n\n  ```js\n  const router = createRouter();\n  addRoute(router, \"GET\", \"/blog/**\", { name: \"blog\" });\n  addRoute(router, \"GET\", \"/blog/:slug\", { name: \"post\" });\n  addRoute(router, \"GET\", \"/**/_payload.json\", { name: \"payload\" });\n  addRoute(router, \"GET\", \"/blog/:slug/_payload.json\", { name: \"post-payload\" });\n\n  findAllRoutes(router, \"GET\", \"/blog/_payload.json\").map((m) => m.data.name);\n  // [\"blog\", \"post\", \"payload\"]\n  findAllRoutes(router, \"GET\", \"/blog/hello/_payload.json\").map((m) => m.data.name);\n  // [\"blog\", \"payload\", \"post-payload\"]\n  findRoute(router, \"GET\", \"/blog/hello\")?.data.name; // \"post\"\n  ```\n\n  This also applies between the other routes on those paths: with `/**/_payload.json` registered, `/:lang/_payload.json` wins over `/blog/:slug` on `/blog/_payload.json`, because it pins the last segment.\n\n</details>\n\n### Removing routes\n\n`removeRoute(router, method, pattern)` removes everything that the matching `addRoute` call added, including all variants of an optional pattern and duplicate registrations. Other routes are left alone, even ones that share a tree node:\n\n```js\naddRoute(router, \"GET\", \"/path/:id\", { a: true });\naddRoute(router, \"GET\", \"/path/:name\", { b: true });\n\nremoveRoute(router, \"GET\", \"/path/:name\"); // \"/path/:id\" is still registered\n```\n\nPass 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}`.\n\n## Compiler\n\nFor the fastest lookups, compile a router into a single function. The compiled function returns the same results as `findRoute` (or `findAllRoutes` with `matchAll: true`).\n\n- **`compileRouter`** compiles at runtime (JIT) with `new Function()`.\n- **`compileRouterToString`** generates code ahead of time (AOT), for example into a build output. It needs no `eval` and no rou3 at runtime.\n\nBoth are imported from `rou3/compiler`.\n\n<!-- automd:jsdocs src=\"./src/compiler.ts\" -->\n\n### `compileRouter(router, opts?)`\n\nCompiles the router instance into a faster route-matching function.\n\n**IMPORTANT:** `compileRouter` requires eval support with `new Function()` in the runtime for JIT compilation (not allowed under a CSP without `unsafe-eval`: use `compileRouterToString` at build time there).\n\nThe compiled function is a **snapshot** of the router: routes added or removed afterwards are not seen, compile again after changing it. Route data is kept by reference. It returns what `findRoute` returns (with `matchAll: true`, what `findAllRoutes` returns), except that `params` is a plain object where `findRoute`'s has a null prototype.\n\n**Example:**\n\n```ts\nimport { createRouter, addRoute } from \"rou3\";\nimport { compileRouter } from \"rou3/compiler\";\nconst router = createRouter();\n// [add some routes]\nconst findRoute = compileRouter(router);\nconst matchAll = compileRouter(router, { matchAll: true });\nfindRoute(\"GET\", \"/path/foo/bar\");\n```\n\n### `compileRouterToString(router, opts?, legacyOpts?)`\n\nCompile the router instance into a compact runnable code (ahead of time, e.g. into a build output).\n\nThe output is a self-contained JavaScript expression (or a `const <functionName>=…;` statement): no imports, no runtime dependency on rou3, and no `eval` / `new Function()`, so it runs under a strict CSP. It needs ES2018 (named capture groups, object spread). Like `compileRouter`, it is a **snapshot** of the router at compile time.\n\n**IMPORTANT:** The exact generated code is **not** stable across rou3 versions: generate it at build time with the installed rou3, don't commit, patch or parse it.\n\n**IMPORTANT:** Route data is emitted with `JSON.stringify` (`toJSON()` applies at every depth, as in JSON). Data containing a function, symbol or bigint throws: pass `opts.serialize` to emit each route's data as a JavaScript expression of your own instead.\n\n**Example:**\n\n```ts\nimport { createRouter, addRoute } from \"rou3\";\nimport { compileRouterToString } from \"rou3/compiler\";\nconst router = createRouter();\n// [add some routes with serializable data]\nconst compilerCode = compileRouterToString(router, { functionName: \"findRoute\" });\n// \"const findRoute=(m, p) => {}\"\n// Route data as code (e.g. handler imports)\ncompileRouterToString(router, { serialize: (data) => `{handler:${data.importName}}` });\n```\n\n<!--/automd -->\n\n## Pattern utilities\n\n`findRoute` and `findAllRoutes` match a **path** against patterns. The utilities below compare **patterns against patterns**, for example to check whether two route rules can apply to the same URL. They are tree-shaken away when you don't import them.\n\n### Pattern overlap\n\n```js\nimport { createRouter, addRoute, routesOverlap, compareRoutes, findOverlappingRoutes } from \"rou3\";\n\n// Can the two patterns match a common path?\nroutesOverlap(\"/**\", \"/protected/feed/**\"); // true\nroutesOverlap(\"/a/**\", \"/b/**\"); // false\n\n// How do the sets of paths they match relate?\ncompareRoutes(\"/api/**\", \"/api/admin/**\"); // \"superset\"\ncompareRoutes(\"/api/admin/**\", \"/api/**\"); // \"subset\"\ncompareRoutes(\"/a/:x\", \"/a/:y\"); // \"equal\" (param names don't matter)\ncompareRoutes(\"/a/*/c\", \"/a/b/*\"); // \"partial\"\ncompareRoutes(\"/a/**\", \"/b/**\"); // \"disjoint\"\n\n// Which registered routes can match a path that the pattern matches?\nconst router = createRouter();\naddRoute(router, \"GET\", \"/**\", { isr: true });\naddRoute(router, \"GET\", \"/protected/**\", { basicAuth: true });\naddRoute(router, \"GET\", \"/protected/feed/**\", { isr: 60 });\n\nfindOverlappingRoutes(router, \"GET\", \"/protected/feed/**\");\n// [\n//   { data: { isr: true } },       // /**\n//   { data: { basicAuth: true } }, // /protected/**\n//   { data: { isr: 60 } },         // /protected/feed/**\n// ]\n```\n\n- **`routesOverlap(a, b)`** returns `true` if at least one path is matched by both patterns.\n- **`compareRoutes(a, b)`** reads as \"`a` is … of `b`\":\n  - `\"equal\"`: both match the same paths.\n  - `\"superset\"`: `a` matches every path `b` matches, and more.\n  - `\"subset\"`: `b` matches every path `a` matches, and more.\n  - `\"disjoint\"`: no path matches both.\n  - `\"partial\"`: none of the above could be proven. The patterns may share some paths.\n- **`findOverlappingRoutes(router, method, pattern)`** works like `findAllRoutes`, but takes a pattern instead of a path. It returns every registered route that can match a path the pattern matches, in the same least to most specific order and with the same method handling. Matches only have `data` (there is no single path to extract params from). A route that was registered with optional syntax is reported once.\n\nThese utilities understand the full pattern syntax (groups, modifiers, escapes) using the same rules as the router, so their answers agree with `findRoute`.\n\n<details>\n<summary>Precision and limits</summary>\n\n- **Answers are safe, not always exact.** Whenever `compareRoutes` claims containment or disjointness, it is proven. When something can't be decided, it answers with a weaker verdict (usually `\"partial\"`), never a wrong one.\n- **Regex constraints** are checked exactly against literal segments (`/user/:id(\\d+)` does not overlap `/user/abc`). Two dynamic segments where at least one has a regex are assumed to overlap: `routesOverlap(\"/user/:id(\\d+)\", \"/user/:name([a-z]+)\")` returns `true` although no path matches both. For the same reason, two different regexes compare as `\"partial\"`, even when they are equivalent.\n- An actually equal pair that is only provable in one direction reports that containment: `/u/:id(42)` vs `/u/42` is `\"superset\"`.\n- **Segment counts:** `**` matches zero or more segments (so `/a/**` overlaps `/a`), `**:name` one or more, a trailing `*` zero or one, and `*` or `:name` elsewhere exactly one. Segments after a `**` are aligned to the end of the path: `compareRoutes(\"/**/_payload.json\", \"/blog/:slug/_payload.json\")` is `\"superset\"`.\n- **Optional syntax:** a pattern with `:x?`, `:x*` or `{...}?` expands into several variants, and two patterns overlap when any pair of variants does.\n- In `findOverlappingRoutes`, different routes (another pattern or method) are always reported separately, even when they share the same `data`. Registering the same route twice with the same `data` reports it once. A route with segments after `**` comes right after the bare `**` it follows.\n\n</details>\n\n### Route node keys\n\nDifferent patterns can end on the **same node** of the route tree: `/users/:id` and `/users/*` both mean \"any single segment under `/users`\". `routeNodeKeys(pattern)` returns the node(s) a pattern lands on:\n\n```js\nimport { routeNodeKeys } from \"rou3\";\n\nrouteNodeKeys(\"/users/:id\"); // [\"/users/*\"]\nrouteNodeKeys(\"/users/*\"); // [\"/users/*\"] (same node as /users/:id)\nrouteNodeKeys(\"/admin/**:rest\"); // [\"/admin/**\"]\nrouteNodeKeys(\"/**:path/og.png\"); // [\"/**/og.png\"]\nrouteNodeKeys(\"/a/:x?\"); // [\"/a\", \"/a/*\"] (optional syntax lands on two nodes)\n```\n\nRoutes on the same node compete: for a given path, `findRoute` returns at most one of them. If you keep your own per-route metadata (route rules, middleware, auth) in a map keyed by pattern text, `/users/*` and `/users/:id` look unrelated. Key the map by `routeNodeKeys` instead, to merge metadata per node or warn when one route shadows another.\n\n> `routeNodeKeys(a)` and `routeNodeKeys(b)` share a key **if and only if** `a` and `b` share a node.\n\n- The result is a deduplicated array, since optional syntax registers on several nodes (`/x{/a}?{/b}?` registers on 4).\n- Each key is itself a valid pattern for its node: `routeNodeKeys(key)` is `[key]`.\n- Invalid patterns throw exactly like `addRoute`.\n\n> [!IMPORTANT]\n> Sharing a node does **not** mean matching the same paths. Keys drop regex constraints and widen `**:name` to `**`, so `/u/:id(\\d+)` and `/u/:slug([a-z]+)` share the key `/u/*` but never match the same path. To compare which paths two patterns match, use [`compareRoutes`](#pattern-overlap).\n\n### Regular expressions\n\n`routeToRegExp(route)` converts a pattern into an anchored `RegExp` with named groups for the params:\n\n```js\nimport { routeToRegExp } from \"rou3\";\n\nconst re = routeToRegExp(\"/users/:id(\\\\d+)\");\n// /^\\/users\\/(?<id>\\d+)\\/?$/\n\n\"/users/123\".match(re).groups; // { id: \"123\" }\n```\n\nThe regex matches **exactly the paths `findRoute` matches** on a router that only holds that route, including the router's tolerances (one optional trailing slash, empty segments, an optional trailing `*`, segments after `**` matched from the end). That makes it safe to use as a guard or scope check outside the router. Like `findRoute` without `normalize`, it compares paths as-is.\n\nThe one exception is a regex constraint that can match `/`, such as `(.*)`: the router applies it to one segment, but in the regex it can span several, so `routeToRegExp(\"/foo/(.*)\")` also matches `/foo/a/b`. The regex then matches more paths than the router, never fewer, so a guard built on it still runs.\n\nThe output is **PCRE-compatible**, so its `.source` also works in `grep -P`, `rg -P`, PHP `preg_*` and Perl. Most routes also compile without look-behind, so they work in RE2-family engines (RE2, Go `regexp`, Rust `regex`).\n\n`regExpToRoute(regexp)` goes the other way. It accepts a `RegExp` or its source string:\n\n```js\nimport { regExpToRoute } from \"rou3\";\n\nregExpToRoute(/^\\/users\\/(?<id>\\d+)\\/?$/); // \"/users/:id(\\\\d+)\"\nregExpToRoute(/^\\/path\\/(?<param>[^/]+)\\/?$/); // \"/path/:param\"\nregExpToRoute(/^\\/path(?:\\/(?<_>(?:[\\s\\S]*[^/])?\\/*?))?\\/?$/); // \"/path/**\"\nregExpToRoute(\"^\\\\/files\\\\/(?<_0>[^/]*)\\\\.png\\\\/?$\"); // \"/files/*.png\"\nregExpToRoute(/^\\/?(?<_>[\\s\\S]*)\\/_payload\\.json\\/?$/); // \"/**/_payload.json\"\n```\n\nIt understands the regexes `routeToRegExp` emits, and every one of them round-trips exactly: `routeToRegExp(regExpToRoute(re)).source === re.source`. Anything else throws a `rou3:` error instead of returning a wrong pattern.\n\n<details>\n<summary>What <code>routeToRegExp</code> doesn't model</summary>\n\n- A constraint that can match `/` (`:x(.+)`, `:x([^.]+)`) can span several segments in the regex (`/a/:x(.+)` matches `/a/b/c`), while the router splits the path into segments first.\n- The empty path `\"\"`: the router treats it as `/`. The regex matches it only for root routes whose first segment is optional (`/**`, `/:x*`, `/:x?`, `/*`), not for `/` itself.\n- In PCRE and Perl, `$` also matches before a final `\\n`, so there the regex also matches `<path>\\n`.\n- `.` and `..` are not resolved. Normalize the path first if your router uses `normalize: true`.\n\n**Params.** The regex leaves a group **unset** where the router reports a value in three cases: a `**` that matches no segment (`/a` on `/a/**`, where the router reports `\"\"`; at the root the regex captures `\"\"` too), a `**:name` / `:name+` at the end whose value is two empty segments (`/a///` on `/a/**:x`, where the router reports `/`), and a `*` after a `**` on an empty last segment (`/a//` on `/**/*`, where the router reports `\"\"`). When optional segments meet a `*` or a constrained optional, or several optional segments follow a `**`, the regex can assign a segment to a different param than the router (`/a/:x?/*` on `/a/b` sets `x`, the router sets `*`). The set of matched paths is still the same.\n\n**Errors.** Patterns that `addRoute` rejects throw the same error, and so does a route that declares the same param name twice (`/files/:path/**:path`; a bare `**` is the param `_`).\n\n</details>\n\n<details>\n<summary>Regex output and engine support</summary>\n\nThe trailing-slash rule (at most one trailing slash, exactly one when the last segment is empty) is built into the end of each regex:\n\n| Route                          | Regex                                                            |\n| ------------------------------ | ---------------------------------------------------------------- |\n| `/users/:id(\\d+)`              | `^\\/users\\/(?<id>\\d+)\\/?$`                                       |\n| `/path/:id?`                   | `^\\/path(?:\\/(?<id>[^/]+))?\\/?$`                                 |\n| `/path/:param`                 | `^\\/path\\/(?<param>[^/]+)\\/?$`                                    |\n| `/users/:id/:tab?`             | `^\\/users\\/(?<id>[^/]+)(?:\\/(?<tab>[^/]+))?\\/?$`                  |\n| `/path/**`                     | `^\\/path(?:\\/(?<_>(?:[\\s\\S]*[^/])?\\/*?))?\\/?$`                   |\n| `/base/**:path`                | `^\\/base\\/(?:\\/\\/\\|(?<path>(?:[\\s\\S]*[^/]\\|\\/\\/)\\/*?)\\/?)$`      |\n| `/**`                          | `^\\/?(?<_>(?:[\\s\\S]*[^/])?\\/*?)\\/?$`                             |\n| `/**/_payload.json`            | `^\\/?(?<_>[\\s\\S]*)\\/_payload\\.json\\/?$`                          |\n| `/path/**/suffix`              | `^\\/path(?:\\/(?<_>[\\s\\S]*))?\\/suffix\\/?$`                        |\n| `/**/:file`                    | `^\\/?(?<_>[\\s\\S]*)\\/(?<file>[^/]+)\\/?$`                           |\n| `/a/**/:page?`                 | `^\\/a(?:\\/(?<_>[\\s\\S]*?))??(?:\\/(?<page>[^/]+))?\\/?$`             |\n| `/`                            | `^\\/$`                                                           |\n| `/path/:id(\\d*)` (look-behind) | `^\\/path\\/(?<id>\\d*)(?:(?<=\\/)\\/\\|(?<!\\/)\\/?)$`                  |\n\n**Look-behind.** The suffix `(?:(?<=\\/)\\/|(?<!\\/)\\/?)$` is only used when the end of the path can't be decided otherwise, for example:\n\n- a constraint at the end of the route whose match can end in `/` (`:name([^.]+)`, `:x(.+)`),\n- a required last segment whose constraint can match empty (`/path/:id(\\d*)`),\n- optional segments side by side where an earlier one can be empty (`/a/:x(\\d*)?/:y?`),\n- a catch-all combined with optional segments (`/a/**:rest/:page?`, `/a/*/**/:n(\\d+)?`, `/a/**/:y?{/b}?`).\n\nFixed-length look-behinds work in JavaScript, PCRE and Perl, but not in RE2-family engines.\n\n**Optional groups.** A single optional group that ends a segment is compiled inline as `(?:...)?`, so each param appears once:\n\n```js\nrouteToRegExp(\"/blog/:id(\\\\d+){-:title}?\");\n// /^\\/blog\\/(?<id>\\d+)(?:-(?<title>[^/]+?))?\\/?$/\nrouteToRegExp(\"/files/:name{.:ext}?\");\n// /^\\/files\\/(?<name>[^/]+?)(?:\\.(?<ext>[^/]+?))?\\/?$/\nrouteToRegExp(\"/users{/:id}?/posts/:post\");\n// /^\\/users(?:\\/(?<id>[^/]+))?\\/posts\\/(?<post>[^/]+)\\/?$/\n```\n\nA param in a segment with other text is lazy (`[^/]+?`), like in the router, so `/files/:name{.:ext}?` splits `archive.tar.gz` into `name: \"archive\"` and `ext: \"tar.gz\"`, and `/pre-:x?` compiles to `^\\/pre-(?:(?<x>[^/]+?))?\\/?$`. When the group follows a `*` or a regex constraint in its segment (`/files/*{.:ext}?/raw`), a look-ahead gives the capture the same value as the router. RE2-family engines reject that output.\n\n**Duplicate named groups.** Other optional combinations compile to an alternation: several groups, an in-segment group followed by optional segments (`/:x{.:e}?/:y?`), an optional part after a capture that could take its text (`/media/*{.webp}?`, `/*-:x?`, `/*-x{-x}?`, `/:a([a-z-]+)-:b?`), `/a/:rest*/b/*` and `/a/**{.png}?`. The alternation repeats a named group. That works in JavaScript engines with duplicate named groups (Node.js 23+, Chrome 125+, Firefox 129+, Safari 17+) and Perl, and needs `PCRE2_DUPNAMES` in strict PCRE2 engines. On Node.js 22, `routeToRegExp` throws a `rou3:` `SyntaxError` for these routes, and `regExpToRoute` can't convert them back.\n\n**Catch-all with optional segments.** With one optional segment right after a `**`, the regex picks the same route as the router (`/a/**/:n(\\d+)?` gives `/a/b/1` to `n`). With several, it matches the same paths but may assign segments differently (`/docs/**/:page?/:lang(en|fr)?` on `/docs/en` sets `page`, the router sets `lang`).\n\n</details>\n\n<details>\n<summary>What <code>regExpToRoute</code> accepts</summary>\n\n- The dialect `routeToRegExp` emits: `(?<name>...)` groups, `[^/]*` segments and `[^/]+?` params inside one, `[\\s\\S]*` catch-alls, `(?:/...)?` optional groups and the endings shown above. Unnamed groups such as `(\\d+)` work too, and the regex inside a constraint is kept verbatim.\n- Looser forms, as older versions emitted: a plain `\\/?` ending, `.*` / `.+` catch-alls and `[^/]+` params, read as `:name`. A `:name` inside a segment is lazy, so a hand-written greedy `(?<a>[^/]+)-(?<b>[^/]+)` comes back as `/:a-:b`, which splits `/x-y-z` as `x` and `y-z`. An old catch-all inside an optional group is the exception: 0.9.2's regex for `/a{/:w*}?` throws, and its regex for `/a{/:w+}?` comes back as `/a/:w(.+)?` (the current regexes come back as `/a/:w*` and `/a{/:w+}?`).\n- Routes that compile to the same regex come back in one spelling: `/base/**:path` becomes `/base/:path+`, `/**.md` becomes `/**/*.md`, `/a/pre-{:x}?` becomes `/a/pre-:x?`, and `/a/:x?/:y?` becomes `/a{/:x/:y?}?`.\n\nIt throws for: a regex not anchored with both `^` and `$`, look-arounds and backreferences, regex operators outside a constraint (`|`, `.`, `+`, `[…]`, …), the flags `i`, `m`, `s`, `u` and `v` (`g`, `y` and `d` are ignored), the duplicate-group alternations above, and constraints that can't be written as a route (for example one containing `/`).\n\n</details>\n\n## TypeScript\n\nRoute data is typed through the router, and `InferRouteParams` gives you the params of a pattern:\n\n```ts\nimport { createRouter, addRoute, findRoute, type InferRouteParams } from \"rou3\";\n\nconst router = createRouter<{ page: string }>();\naddRoute(router, \"GET\", \"/users/:id\", { page: \"user\" });\n\nfindRoute(router, \"GET\", \"/users/42\")?.data.page; // string\n\ntype Params = InferRouteParams<\"/users/:id/:tab?\">;\n// { id: string; tab: string | undefined }\n```\n\n## License\n\nPublished under the [MIT](https://github.com/h3js/rou3/blob/main/LICENSE) license.\n","publish_time":1758102975392,"_cnpm_publish_time":1758102975392,"dist-tags":{"latest":"1.0.0"}}