diff --git a/test/router-parity/README.md b/test/router-parity/README.md new file mode 100644 index 0000000..e28b709 --- /dev/null +++ b/test/router-parity/README.md @@ -0,0 +1,50 @@ +# Router parity corpus (frozen) + +The compatibility baseline for replacing the linear HTTP matcher with a radix index +(FPRD-001 CARD-07/08/09/10, issue #109). Everything here was captured from +`@green-tea/core` at **`ed47836c9820c47bf4ed5e902d91e019abdb110a`** (develop after #117 and #122). + +## The rule + +**The baseline is immutable through CARD-07 review.** If the router change makes a test here fail, +the router changed behaviour. That is a compatibility failure, not a stale fixture. + +A deliberate compatibility change needs its own maintainer approval, recorded on the card, and a +reviewed edit to the specific frozen file, in a commit that says why. Do not edit a golden to make a +test pass, do not edit `oracle.ts` to fit a new implementation, and do not delete a frozen file to +let a capture run recreate it. + +Nothing can regenerate the baseline by accident: + +- `vitest -u` is refused with an error. These are plain JSON files, not vitest snapshots. +- `ROUTER_PARITY_CAPTURE=1` only writes a frozen file that **does not exist**. It never + overwrites. It is how the files were first captured, and how a new fixture gets added later. + +## What is here + +| File | What it freezes | +|---|---| +| `manifest.json` | Existing tests retained unchanged (ROUTER-CORPUS §1), with the verification result at the pinned revision. `manifest.test.ts` fails if a named file or test disappears. | +| `oracle.ts` | Verbatim copy of the pre-radix `matchRoute`, `resolveRoute`, `allowedMethods`, `normalizeRequestPath`, `compilePattern` and `matchWsRoute`. Test-only; `src/` must never import it. | +| `cases.ts`, `generator.ts` | Matcher inputs: 24 hand-picked scenarios (§2), and a fixed-seed generator (`router-parity-gen-v1`, seed `10908`). | +| `frozen/matcher-*.json` | Captured matcher outputs: declaration ID, decoded params, `implicitHead`, ordered `Allow`, or the normalization error. The generated file also stores the seed, the generator rules and every generated input. | +| `frozen/app-*.json` | Status, headers, `Allow` and body through `app.fetch` and through a Node socket, including HEAD body suppression. | +| `frozen/ws-*.json` | WS upgrade selection through `app.upgrade` and the Node listener, plus HTTP requests at the WS paths. | +| `frozen/boot-*.json` | Boot-time rejections: pattern compilation, local ambiguity, mesh splicing. | +| `frozen/golden-*.json` | `graph()`, `explain()`, `openapi({ title: 'Parity', version: '1' })`, and a mesh teacup before and after `ready()`. | + +## How the comparison works + +`matcher.test.ts` runs every scenario through the oracle **and** through the live +`src/http/router` exports, and requires both to equal the frozen capture. Today the live router is +the linear matcher, so this proves the oracle is a faithful copy. CARD-07 replaces the internals +behind the same exports, and the same test then compares oracle against radix with no edit here. + +Each run builds fresh `RouteDef` objects, so the two implementations never share a cached table, and +the answering route is identified by declaration ID, never by pattern text. + +Application-level, WS, boot and introspection files are compared against the live code only, +because there is no second implementation of `app.fetch` to diff against; the frozen capture plays +the oracle's role. + +The performance half of the baseline is in `bench/lookup.ts` and `bench/baseline/router-ed47836/`. diff --git a/test/router-parity/frozen.ts b/test/router-parity/frozen.ts new file mode 100644 index 0000000..0ab4450 --- /dev/null +++ b/test/router-parity/frozen.ts @@ -0,0 +1,69 @@ +/** + * Reads the frozen router-parity baseline. Read README.md in this directory before touching it. + * + * Every expected output under `frozen/` was captured from the pinned revision below, by running + * these tests with `ROUTER_PARITY_CAPTURE=1` while the file did not exist yet. Nothing here ever + * overwrites a file: a capture only fills a gap, and `vitest -u` is refused outright, because a + * baseline that a flag can rewrite is a baseline a new implementation can quietly move. + */ +import { existsSync, readFileSync, writeFileSync } from 'fs'; +import { join } from 'path'; +import { expect } from 'vitest'; + +/** The `@green-tea/core` commit every frozen output was captured from (develop after #117 and #122). */ +export const PINNED_REVISION = 'ed47836c9820c47bf4ed5e902d91e019abdb110a'; + +const FROZEN_DIR = join(__dirname, 'frozen'); + +interface FrozenFile { + revision: string; + data: T; +} + +function refuseSnapshotUpdate(name: string): void { + // `_updateSnapshot` is vitest's private record of `-u` ('all') versus a normal run ('new'/'none'). + const state = expect.getState().snapshotState as unknown as { _updateSnapshot?: string } | undefined; + if (state?._updateSnapshot !== 'all') return; + + throw new Error( + `router-parity: '${name}' is a frozen baseline captured at ${PINNED_REVISION} and is never ` + + 'rewritten by `vitest -u`. A behaviour difference against it is a compatibility failure. ' + + 'If the change is deliberate, it needs its own maintainer approval and a reviewed edit of ' + + `test/router-parity/frozen/${name}.json — see test/router-parity/README.md.`, + ); +} + +/** + * Returns the frozen data for `name`. When the file is missing it fails, unless + * `ROUTER_PARITY_CAPTURE=1` is set, in which case `capture()` runs against the current code and its + * result is written. An existing file is never replaced. + */ +export async function frozen(name: string, capture: () => T | Promise): Promise { + refuseSnapshotUpdate(name); + const file = join(FROZEN_DIR, `${name}.json`); + + if (!existsSync(file)) { + if (process.env.ROUTER_PARITY_CAPTURE !== '1') + throw new Error( + `router-parity: frozen file ${file} is missing — the baseline cannot be regenerated by a test run`, + ); + const data = JSON.parse(JSON.stringify(await capture())) as T; + const record: FrozenFile = { revision: PINNED_REVISION, data }; + writeFileSync(file, `${JSON.stringify(record, null, 2)}\n`); + return data; + } + + const record = JSON.parse(readFileSync(file, 'utf8')) as FrozenFile; + expect(record.revision, `${name}.json was captured from a different revision`).toBe(PINNED_REVISION); + return record.data; +} + +/** + * Structural equality that also holds array order and object key order. `toEqual` alone ignores key + * order, which is observable in `openapi().paths` and in serialized introspection output. + */ +export function expectFrozenEqual(actual: unknown, expected: unknown, label: string): void { + const plain = JSON.parse(JSON.stringify(actual)); + expect(plain, label).toEqual(expected); + expect(JSON.stringify(plain), `${label} (key and array order)`).toBe(JSON.stringify(expected)); +} diff --git a/test/router-parity/manifest.json b/test/router-parity/manifest.json new file mode 100644 index 0000000..ea2d19b --- /dev/null +++ b/test/router-parity/manifest.json @@ -0,0 +1,155 @@ +{ + "purpose": "Existing tests retained unchanged as the radix-router compatibility baseline (FPRD-001 CARD-08, ROUTER-CORPUS §1, #109).", + "revision": "ed47836c9820c47bf4ed5e902d91e019abdb110a", + "corpusRevision": "42376c6693c7e15fadbcfb544172cc571fcacef0", + "verification": { + "date": "2026-10-10", + "revision": "ed47836c9820c47bf4ed5e902d91e019abdb110a", + "command": "npx vitest run --reporter=json; npm run test:deno; npm run test:bun; npm run test:edge", + "result": "Every file and every named test exists at the pinned revision and passes. No test was renamed or removed between 42376c6 and ed47836; src/http/router.ts is byte-identical between the two.", + "renamed": [] + }, + "retained": [ + { + "surface": "Pattern grammar, normalization, matching, Allow, HEAD", + "file": "test/router.test.ts", + "scope": "file" + }, + { + "surface": "HTTP adapter", + "file": "test/http.test.ts", + "scope": "tests", + "tests": [ + "matches a static + :param route and extracts params", + "http streaming > routes by method (non-GET no longer falls through)" + ] + }, + { + "surface": "Fetch adapter", + "file": "test/fetch.test.ts", + "scope": "tests", + "tests": [ + "app.fetch > handles GET and returns JSON 200", + "app.fetch > 404s an unknown route", + "app.fetch on a mesh app > serves without ever calling listen()", + "app.fetch on a mesh app > does not re-boot when listen() follows a fetch" + ] + }, + { + "surface": "App declarations and introspection", + "file": "test/app.test.ts", + "scope": "tests", + "tests": [ + "app.graph / explain > graph() returns nodes (with origin/needs/provides) and routes with their sliced chain", + "app.graph / explain > explain() returns the rich chain with origin and a handler entry", + "route table validation > rejects routes with the same method and effective pattern", + "route table validation > allows the same effective pattern under different methods", + "devGraph endpoint > serves /__graph__ as HTML when devGraph:true", + "devGraph endpoint > does NOT mount /__graph__ without devGraph", + "devGraph endpoint > serves /__graph__ and /__openapi__ over app.fetch too (runtime-agnostic dev tools)", + "app streaming wiring > serves a @Ws route receiving @inbound and returning a channel" + ] + }, + { + "surface": "OpenAPI", + "file": "test/openapi.test.ts", + "scope": "file" + }, + { + "surface": "WebSocket selection", + "file": "test/ws-core.test.ts", + "scope": "tests", + "tests": ["runWsConnection (neutral core) > matchWsRoute finds a pattern and captures params"] + }, + { + "surface": "Node WebSocket upgrade", + "file": "test/ws.test.ts", + "scope": "tests", + "tests": [ + "ws upgrade > echoes inbound to outbound and aborts on close", + "ws upgrade > closes with a 4000+status code when the WS open() throws an HttpError" + ] + }, + { + "surface": "Mesh route splicing", + "file": "test/mesh/integration.test.ts", + "scope": "tests", + "tests": [ + "mesh skeleton integration > teapot still serves its own local route (regression)", + "mesh skeleton integration > refuses to boot when two teapots export the same route, naming both", + "mesh skeleton integration > refuses ambiguous remote routes that differ only by parameter name", + "mesh skeleton integration > accepts the same route from a single teapot (regression: no false positive)", + "mesh skeleton integration > gives a local route precedence over a remote one, and says so", + "mesh skeleton integration > does not warn when a remote route has no local twin" + ] + } + ], + "runtimeSmoke": [ + { + "file": "test/deno/ws.test.ts", + "runner": "npm run test:deno", + "tests": [ + "serveDeno: HTTP + WebSocket round-trip through the graph", + "serveDeno: a malformed upgrade path closes 1008 and the server keeps serving" + ] + }, + { + "file": "test/bun/ws.test.ts", + "runner": "npm run test:bun", + "tests": [ + "serveBun: HTTP + WebSocket round-trip", + "serveBun: a malformed upgrade path closes 1008 and the server keeps serving" + ] + }, + { + "file": "test/deno/mesh.test.ts", + "runner": "npm run test:deno", + "tests": [ + "mesh on Deno: teacup resolves a Deno teapot through the graph", + "mesh on Deno: a teapot refuses a bad secret over its control channel" + ] + }, + { + "file": "test/bun/mesh.test.ts", + "runner": "npm run test:bun", + "tests": [ + "mesh on Bun: teacup resolves a Bun teapot through the graph", + "mesh on Bun: a teapot refuses a bad secret over its control channel" + ] + }, + { + "file": "test/edge/run.ts", + "runner": "npm run test:edge", + "tests": [] + } + ], + "supplementary": { + "note": "Not in ROUTER-CORPUS §1. Proposed because #117 (merged after the corpus was written) moved WS upgrade paths through normalizeRequestPath and added the reserved-path refusal on app.upgrade. Pending D5 approval; they run in npm test either way.", + "retained": [ + { + "surface": "Node upgrade path normalization and rejection (#104)", + "file": "test/ws-upgrade-reject.test.ts", + "scope": "file" + }, + { + "surface": "Reserved mesh control path ahead of WS routes (Node)", + "file": "test/mesh/control-upgrade.test.ts", + "scope": "file" + }, + { + "surface": "Reserved mesh control path over app.upgrade", + "file": "test/mesh/fetch-boot.test.ts", + "scope": "tests", + "tests": [ + "mesh control over app.upgrade (no listen) > serves the handshake to a peer that never touched a Node server", + "mesh control over app.upgrade (no listen) > refuses the reserved path explicitly on an app that exports nothing" + ] + } + ] + }, + "frozenFixtures": { + "dir": "test/router-parity/frozen", + "oracle": "test/router-parity/oracle.ts", + "readme": "test/router-parity/README.md" + } +} diff --git a/test/router-parity/manifest.test.ts b/test/router-parity/manifest.test.ts new file mode 100644 index 0000000..1fe50d9 --- /dev/null +++ b/test/router-parity/manifest.test.ts @@ -0,0 +1,59 @@ +/** + * Keeps the retained-test manifest honest: every file it names must exist and every test it names + * must still be declared there. A rename or deletion during CARD-07 fails here instead of silently + * shrinking the compatibility baseline. Whether those tests *pass* is `npm test` and the runtime + * suites' job; this only proves they are still the tests the manifest says they are. + */ +import { existsSync, readFileSync, readdirSync } from 'fs'; +import { join } from 'path'; +import { describe, it, expect } from 'vitest'; +import { PINNED_REVISION } from './frozen'; + +interface Entry { + file: string; + scope?: 'file' | 'tests'; + tests?: string[]; +} + +const ROOT = join(__dirname, '..', '..'); +const manifest = JSON.parse(readFileSync(join(__dirname, 'manifest.json'), 'utf8')) as { + revision: string; + retained: Entry[]; + runtimeSmoke: Entry[]; + supplementary: { retained: Entry[] }; + frozenFixtures: { oracle: string; readme: string }; +}; + +const entries: Entry[] = [...manifest.retained, ...manifest.runtimeSmoke, ...manifest.supplementary.retained]; + +describe('router parity: retained-test manifest', () => { + it('is pinned to the same revision as the frozen fixtures', () => { + expect(manifest.revision).toBe(PINNED_REVISION); + }); + + for (const entry of entries) { + it(`${entry.file} exists and declares every named test`, () => { + const path = join(ROOT, entry.file); + expect(existsSync(path), `${entry.file} is missing`).toBe(true); + const source = readFileSync(path, 'utf8'); + + for (const name of entry.tests ?? []) { + for (const part of name.split(' > ')) expect(source, `${entry.file}: '${name}'`).toContain(part); + } + }); + } + + it('names an oracle and a README that exist', () => { + for (const file of [manifest.frozenFixtures.oracle, manifest.frozenFixtures.readme]) + expect(existsSync(join(ROOT, file)), file).toBe(true); + }); + + it('the oracle is not imported from src/', () => { + // A frozen oracle the product can reach is no longer frozen: someone will "fix" it. + const files = readdirSync(join(ROOT, 'src'), { recursive: true, encoding: 'utf8' }).filter((f) => + f.endsWith('.ts'), + ); + const hits = files.filter((f) => readFileSync(join(ROOT, 'src', f), 'utf8').includes('router-parity')); + expect(hits).toEqual([]); + }); +}); diff --git a/test/router-parity/oracle.ts b/test/router-parity/oracle.ts new file mode 100644 index 0000000..db5493b --- /dev/null +++ b/test/router-parity/oracle.ts @@ -0,0 +1,472 @@ +/** + * FROZEN ORACLE — the pre-radix HTTP and WebSocket matcher, copied verbatim from `@green-tea/core` + * at ed47836c9820c47bf4ed5e902d91e019abdb110a (`src/http/router.ts`, minus `parseQuery`, plus + * `matchWsRoute` from `src/http/ws-core.ts`). + * + * DO NOT EDIT THIS FILE TO FIT A NEW IMPLEMENTATION. It is the reference the radix index (CARD-07, + * #109) is judged against: if the live matcher disagrees with it, the live matcher is what changed. + * A deliberate compatibility change needs its own maintainer approval and a new pinned oracle, + * never an edit here. Test-only: nothing under `src/` may import it. + * + * The only departures from the source are mechanical: the route types are declared locally (so a + * later change to `src/http/types.ts` cannot alter what this file compiles to), and the module-level + * caches are this file's own, so the oracle never shares compiled state with the live matcher. + */ + +/** The fields of `RouteDef` the matcher reads. A live `RouteDef` is assignable to it. */ +export interface OracleRoute { + method: string; + pattern: string; + transport: string; +} + +/** The fields of `WsRouteDef` the WS matcher reads. */ +export interface OracleWsRoute { + pattern: string; +} + +export interface MatchedRoute { + params: Record; + def: OracleRoute; +} + +export type CompiledSegment = + | { kind: 'static'; value: string } + | { kind: 'param'; name: string; constraint?: RegExp; constraintSource?: string } + | { kind: 'catchAll'; name: string }; + +/** Parsed route pattern reused by matching, specificity, ambiguity checks, and OpenAPI projection. */ +export interface CompiledPattern { + source: string; + normalized: string; + shape: string; + segments: CompiledSegment[]; + kinds: number[]; + catchAll: boolean; +} + +const compiledCache = new Map(); +const PARAM_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/; +const MAX_CONSTRAINT_LENGTH = 128; + +/** Request-path syntax error. Adapters translate this to the standard 400 response envelope. */ +export class InvalidRequestPathError extends Error { + constructor(message: string) { + super(message); + this.name = 'InvalidRequestPathError'; + } +} + +interface ConstraintToken { + length: number; + unbounded: boolean; + separator: boolean; +} + +/** Reads one atom plus its optional quantifier from the deliberately small safe-regex subset. */ +function readConstraintToken(source: string): ConstraintToken | undefined { + const atom = /^(?:\\[dDsSwW]|\\[.\-_/]|[A-Za-z0-9_.-]|\[(?:\\.|[^\]\\])+\])/u.exec(source)?.[0]; + if (!atom) return undefined; + + const rest = source.slice(atom.length); + const quantifier = /^(?:[+*?]|\{\d+(?:,\d*)?\})/u.exec(rest)?.[0] ?? ''; + if (quantifier.startsWith('{')) assertBoundedQuantifier(quantifier); + + return { + length: atom.length + quantifier.length, + unbounded: quantifier === '+' || quantifier === '*' || quantifier.endsWith(',}'), + separator: quantifier === '' && /^(?:\\[.\-_/]|[._-])$/u.test(atom), + }; +} + +/** Rejects nonsensical or excessively large counted quantifiers before RegExp compilation. */ +function assertBoundedQuantifier(quantifier: string): void { + const [minText, maxText] = quantifier.slice(1, -1).split(','); + const min = Number(minText); + const max = maxText === undefined || maxText === '' ? min : Number(maxText); + if (min > max || max > 2048) throw new Error(`unsafe route constraint: invalid quantifier '${quantifier}'`); +} + +/** Accepts only a linear, group-free regex subset to keep attacker-controlled segments ReDoS-safe. */ +function assertSafeConstraint(source: string): void { + if (!source || source.length > MAX_CONSTRAINT_LENGTH) + throw new Error('unsafe route constraint: expression must contain 1-128 characters'); + + let offset = 0; + let previousUnbounded = false; + + while (offset < source.length) { + const token = readConstraintToken(source.slice(offset)); + if (!token) throw new Error(`unsafe route constraint: unsupported expression '${source}'`); + if (previousUnbounded && token.unbounded) + throw new Error(`unsafe route constraint: adjacent unbounded quantifiers in '${source}'`); + previousUnbounded = token.separator ? false : token.unbounded; + offset += token.length; + } +} + +function assertParamName(name: string, pattern: string): void { + if (!PARAM_NAME.test(name)) throw new Error(`invalid route pattern '${pattern}': invalid parameter name '${name}'`); +} + +function compileParam(segment: string, pattern: string): Extract { + const constraintStart = segment.indexOf('('); + + if (constraintStart < 0) { + const name = segment.slice(1); + assertParamName(name, pattern); + return { kind: 'param', name }; + } + + if (!segment.endsWith(')')) throw new Error(`invalid route pattern '${pattern}': malformed constraint`); + const name = segment.slice(1, constraintStart); + const constraintSource = segment.slice(constraintStart + 1, -1); + assertParamName(name, pattern); + assertSafeConstraint(constraintSource); + return { + kind: 'param', + name, + constraintSource, + constraint: new RegExp(`^(?:${constraintSource})$`, 'u'), + }; +} + +function compileSegments(pattern: string, rawSegments: string[]): CompiledSegment[] { + const names = new Set(); + const compiled: CompiledSegment[] = []; + + for (let index = 0; index < rawSegments.length; index++) { + const raw = rawSegments[index]; + let segment: CompiledSegment; + + if (raw.startsWith(':') && raw.endsWith('*')) { + const name = raw.slice(1, -1); + assertParamName(name, pattern); + if (index !== rawSegments.length - 1) + throw new Error(`invalid route pattern '${pattern}': catch-all must be the final segment`); + segment = { kind: 'catchAll', name }; + } else if (raw.startsWith(':')) { + segment = compileParam(raw, pattern); + } else { + segment = { kind: 'static', value: raw }; + } + + if (segment.kind !== 'static') { + if (names.has(segment.name)) + throw new Error(`invalid route pattern '${pattern}': duplicate parameter '${segment.name}'`); + names.add(segment.name); + } + + compiled.push(segment); + } + + return compiled; +} + +function segmentShape(segment: CompiledSegment): string { + if (segment.kind === 'static') return `s:${segment.value}`; + if (segment.kind === 'catchAll') return 'c'; + return segment.constraintSource ? `r:${segment.constraintSource}` : 'p'; +} + +/** Compiles and validates one route pattern. Results are cached by source string. */ +export function compilePattern(pattern: string): CompiledPattern { + const cached = compiledCache.get(pattern); + if (cached) return cached; + if (!pattern.startsWith('/')) throw new Error(`invalid route pattern '${pattern}': pattern must start with '/'`); + if (pattern.includes('//')) throw new Error(`invalid route pattern '${pattern}': repeated slash`); + + const normalized = pattern.length > 1 && pattern.endsWith('/') ? pattern.slice(0, -1) : pattern; + const rawSegments = normalized === '/' ? [] : normalized.split('/').slice(1); + const segments = compileSegments(pattern, rawSegments); + const compiled: CompiledPattern = { + source: pattern, + normalized, + shape: segments.map(segmentShape).join('/'), + segments, + kinds: segments + .filter((segment) => segment.kind !== 'catchAll') + .map((segment) => (segment.kind === 'static' ? 3 : segment.constraint ? 2 : 1)), + catchAll: segments.at(-1)?.kind === 'catchAll', + }; + compiledCache.set(pattern, compiled); + return compiled; +} + +/** Matches a `.` or `..` segment, percent-encoded or not, sitting alone between separators. */ +const DOT_SEGMENT = /(?:^|\/)(?:\.|%2e){1,2}(?:\/|$)/i; + +/** + * Classifies one path segment as `.`, `..`, or neither. + * + * `%2e` is a dot as far as the URL spec is concerned, so `/a/%2e%2e/b` and `/a/../b` are the same + * path. Skipping the encoded spelling would leave the encoded form as a way to reach a route the + * plain form resolves away from. + */ +function dotSegment(segment: string): '.' | '..' | undefined { + if (segment === '.' || segment === '..') return segment; + if (segment.length > 6 || !segment.includes('%')) return undefined; + const decoded = segment.toLowerCase().replace(/%2e/g, '.'); + return decoded === '.' || decoded === '..' ? decoded : undefined; +} + +/** + * Resolves `.` and `..` segments, the way RFC 3986 §5.2.4 and the WHATWG URL parser both do. + * + * This runs for the *Node* adapter's benefit. Every fetch-based runtime — Deno, Bun, workerd — + * resolves dot segments inside the `Request` constructor, before green-tea is handed anything: + * `new Request('http://x/public/../admin').url` is already `http://x/admin`. The raw target is + * simply not recoverable there, so rejecting dot segments outright — which is what this module + * does for `//`, and would be the stricter policy — cannot be implemented on three of the four + * runtimes. Resolving is the only rule all four can agree on. + * + * Before this, the same bytes on the wire routed differently per runtime: `GET /public/../admin` + * reached a `/admin` route under Deno/Bun/edge and 404'd under Node. + */ +function resolveDotSegments(path: string): string { + const out: string[] = []; + + for (const segment of path.split('/').slice(1)) { + const dots = dotSegment(segment); + if (dots === '.') continue; + + if (dots === '..') { + out.pop(); + continue; + } + + out.push(segment); + } + + return `/${out.join('/')}`; +} + +/** Applies the public trailing-slash policy and validates every segment's percent encoding. */ +export function normalizeRequestPath(path: string): string { + if (!path.startsWith('/')) throw new InvalidRequestPathError('invalid request path: path must start with slash'); + if (path.includes('//')) throw new InvalidRequestPathError('invalid request path: repeated slash'); + + // Two `indexOf` scans gate the regex, and the regex gates the split. A path with no `.` and no + // `%` at all — which is most of them — pays only the scans. + const resolved = + (path.includes('.') || path.includes('%')) && DOT_SEGMENT.test(path) ? resolveDotSegments(path) : path; + const normalized = resolved.length > 1 && resolved.endsWith('/') ? resolved.slice(0, -1) : resolved; + + // Validation only — the decoded value is deliberately discarded, matching is done on the raw + // path. So the work is skipped entirely unless there is something to validate. + // + // This used to split the path and call `decodeURIComponent` per segment, on every request, and + // throw all of it away. Measured on this path: 95.8 ns for `/hello`, 342.7 ns for a six-segment + // route — around 8% of a whole request, spent proving that a string nobody decodes could be + // decoded. The guard below is 15.7 ns and 6.7 ns for the same two paths. + // + // One call on the whole string rather than per segment is the same check: `decodeURIComponent` + // throws on the first malformed `%` sequence wherever it appears, and a `%2F` inside a segment + // decodes fine either way. Only the throw matters here, never the result. + if (normalized.includes('%')) { + try { + decodeURIComponent(normalized); + } catch { + throw new InvalidRequestPathError('invalid request path: malformed path encoding'); + } + } + + return normalized; +} + +function decodeSegment(value: string): string { + // Same gate `normalizeRequestPath` uses on the whole path, for the same reason: a segment with no + // `%` decodes to itself, so the call only ever proves that. Most segments have no `%`, and this + // runs for every param segment of every candidate route the scan reaches. + return value.includes('%') ? decodeURIComponent(value) : value; +} + +/** + * Splits a request path into its non-empty segments. + * + * Called once per request by the scanning functions below, not once per candidate route. It used to + * live inside {@link matchCompiled}, which meant `split` + `filter` — two allocations — ran for every + * registered route on every request, always producing the same array. + */ +function splitPath(path: string): string[] { + return path.split('/').filter(Boolean); +} + +/** + * Matches one compiled pattern against a request's segments. + * + * `decoded` memoizes per request, not per candidate: a scan reaching the same parameter position on + * several routes decoded the same string once per route. Position is all decoding depends on, so one + * array shared across the scan is the same answer for less work. + */ +function matchCompiled( + compiled: CompiledPattern, + pathSegs: string[], + decoded?: Array, +): Record | undefined { + const params: Record = {}; + + for (let index = 0; index < compiled.segments.length; index++) { + const segment = compiled.segments[index]; + + if (segment.kind === 'catchAll') { + params[segment.name] = pathSegs.slice(index).map(decodeSegment).join('/'); + return params; + } + + if (index >= pathSegs.length) return undefined; + + if (segment.kind === 'static') { + if (segment.value !== pathSegs[index]) return undefined; + continue; + } + + const value = decoded ? (decoded[index] ??= decodeSegment(pathSegs[index])) : decodeSegment(pathSegs[index]); + if (segment.constraint && !segment.constraint.test(value)) return undefined; + params[segment.name] = value; + } + + return compiled.segments.length === pathSegs.length ? params : undefined; +} + +/** Matches a compiled segment pattern and returns its decoded parameters. */ +export function matchPattern(pattern: string, path: string): Record | undefined { + return matchCompiled(compilePattern(pattern), splitPath(path)); +} + +/** + * Orders patterns by exactness, then static/constrained/plain segment specificity. + * + * Takes compiled patterns rather than their source strings: it used to re-derive both through + * `compilePattern`, which is a `Map` lookup each, on every comparison of every request. + */ +function moreSpecific(a: CompiledPattern, b: CompiledPattern): number { + const scoreA = a; + const scoreB = b; + if (scoreA.catchAll !== scoreB.catchAll) return scoreA.catchAll ? -1 : 1; + const length = Math.max(scoreA.kinds.length, scoreB.kinds.length); + + for (let index = 0; index < length; index++) { + const kindA = scoreA.kinds[index] ?? -1; + const kindB = scoreB.kinds[index] ?? -1; + if (kindA !== kindB) return kindA - kindB; + } + + return 0; +} + +/** One route with its pattern already compiled. Built once per table, ordered within its method. */ +interface IndexedRoute { + def: OracleRoute; + compiled: CompiledPattern; +} + +/** + * Compiled, method-bucketed, specificity-ordered route tables, keyed by the identity of the array + * they were built from. + * + * A server hands the same array to every request, so this is built once and collected with the + * table it describes. A table assembled fresh — mesh splicing a teapot's exports in at boot — is a + * different array and gets its own index, so nothing has to remember to invalidate anything. + */ +const routeIndexCache = new WeakMap>(); + +function routeIndex(routes: OracleRoute[]): Map { + const cached = routeIndexCache.get(routes); + if (cached) return cached; + + const byMethod = new Map(); + + for (const def of routes) { + const entry: IndexedRoute = { def, compiled: compilePattern(def.pattern) }; + const bucket = byMethod.get(def.method); + if (bucket) bucket.push(entry); + else byMethod.set(def.method, [entry]); + } + + // Most specific first, so the first match *is* the answer. `sort` is stable, so equal patterns + // keep registration order — which is exactly what the old scan did by refusing to replace its + // best on a tie. + for (const bucket of byMethod.values()) bucket.sort((a, b) => moreSpecific(b.compiled, a.compiled)); + + routeIndexCache.set(routes, byMethod); + return byMethod; +} + +/** + * Finds the most specific route matching both method and path; ties keep registration order. + * + * The ranking is settled when the table is built, not per request: the answer cannot change between + * requests, and re-deriving it charged every request for a scan to the end plus a `moreSpecific` + * call — two `compilePattern` lookups each — per candidate. Both scaled with the size of the route + * table. What is left here is a walk that stops at the first match. + */ +export function matchRoute(routes: OracleRoute[], method: string, path: string): MatchedRoute | undefined { + const candidates = routeIndex(routes).get(method); + if (!candidates) return undefined; + + const pathSegs = splitPath(path); + const decoded: Array = new Array(pathSegs.length); + + for (const { def, compiled } of candidates) { + const params = matchCompiled(compiled, pathSegs, decoded); + if (params) return { params, def }; + } + + return undefined; +} + +/** Route resolution adds the one HTTP fallback the matcher supports: buffered GET serves HEAD. */ +export interface ResolvedRoute extends MatchedRoute { + implicitHead: boolean; +} + +export function resolveRoute(routes: OracleRoute[], method: string, path: string): ResolvedRoute | undefined { + const explicit = matchRoute(routes, method, path); + if (explicit) return { ...explicit, implicitHead: false }; + if (method !== 'HEAD') return undefined; + + const fallback = matchRoute( + routes.filter((route) => route.transport === 'buffer'), + 'GET', + path, + ); + return fallback ? { ...fallback, implicitHead: true } : undefined; +} + +const METHOD_ORDER = ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS']; + +/** Lists the distinct HTTP methods whose pattern matches the path — used to build a 405 `Allow` header. */ +export function allowedMethods(routes: OracleRoute[], path: string): string[] { + const pathSegs = splitPath(path); + const methods = new Set(); + + for (const route of routes) { + if (!matchCompiled(compilePattern(route.pattern), pathSegs)) continue; + methods.add(route.method); + if (route.method === 'GET' && route.transport === 'buffer') methods.add('HEAD'); + } + + if (methods.size) methods.add('OPTIONS'); + return [...methods].sort((a, b) => { + const indexA = METHOD_ORDER.indexOf(a); + const indexB = METHOD_ORDER.indexOf(b); + return ( + (indexA < 0 ? METHOD_ORDER.length : indexA) - (indexB < 0 ? METHOD_ORDER.length : indexB) || a.localeCompare(b) + ); + }); +} + +/** + * Selects the first registered WS declaration whose pattern matches — no specificity ranking. + * Copied from `src/http/ws-core.ts`; both adapters hand it a path already through + * `normalizeRequestPath` (Node `routeUpgrade`, and `buildAppUpgrade` for app.upgrade). + */ +export function matchWsRoute( + wsRoutes: W[], + path: string, +): { def: W; params: Record | undefined } | undefined { + return wsRoutes + .map((candidate) => ({ def: candidate, params: matchPattern(candidate.pattern, path) })) + .find((entry) => entry.params); +}