feat(router)!: fail boot on unreachable or ambiguous constrained params
CI / dco (pull_request) Successful in 5s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 27s
CI / runtimes (deno) (pull_request) Successful in 19s
CI / runtimes (edge) (pull_request) Successful in 14s

Before, when two sibling routes could match the same request, the router
picked one by registration order or precedence, and nothing reported it.
Boot now refuses two cases between routes of the same method that branch at
the same segment under the same prefix:

- ambiguous: both params are constrained, the constraints accept a common
  segment, and the rest of both patterns can match one request. The error
  names both declarations and a witness segment with an example path.
- unreachable: a plain param sits next to a constraint that accepts every
  segment, and the constraint wins every request the plain param could take.

A plain param next to a constraint that leaves some segments over is the
documented fallback pattern and still boots.

The check is exact. assertSafeConstraint admits only a linear, group-free
subset, so every constraint reads back as a sequence of (character set, min,
max) blocks. Atom sets follow u-flag semantics. \p{...} is the one construct
that is not modelled, and for it the engine is asked once per code point. A
product walk over two block sequences finds a common segment, or proves none
exists, in O(|A|*|B|*(|A|+|B|)*K) with K <= 2048. "Accepts every segment" is
a closed-form test on the blocks. Both are measured against what the router
hands a param: a decoded, non-empty segment that is never "." or "..".

The check runs per table under that table's own precedence. HTTP ranks by
specificity. WebSocket takes the first declared match. @Stream routes sit in
both tables. Routes exported by different teapots are checked against each
other. Local against remote keeps the local override and its warning.

The lookup path is unchanged. router.ts only exports the two token regexes,
so the boot check and assertSafeConstraint read atoms the same way.

BREAKING CHANGE: an app that declares two overlapping constrained siblings
  (e.g. /u/:id(\d+) and /u/:n(\d{1,3})), or a plain param beside a constraint
  that accepts every segment, now fails createApp. So do a plain WebSocket param
  declared before a constrained sibling, and such pairs across mesh teapots.
Refs: #127
Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-10-12 16:07:58 -05:00
1 parent e41d9560ba
commit 63f60134ea
7 files changed
+1543 -6

No files matched your search

+279
View File
@@ -0,0 +1,279 @@
/**
* CARD-13 (#127) through `createApp`: the card's test cases T1–T9, at boot, with the exact messages.
* The decision procedure itself is covered in `route-conflicts.test.ts`.
*/
import 'reflect-metadata';
import { describe, it, expect, vi } from 'vitest';
import { createApp, Route, Get, Post, Ws, Stream, Module, param } from '../src/index';
import type { RouteDecorator } from '../src/metadata';
type Decl = [RouteDecorator, string];
/** One controller with a handler per declaration, `h0`, `h1`, … in order, each echoing its params. */
function moduleWith(decls: Decl[], options?: { export: boolean }) {
class Routes {}
decls.forEach(([decorator, path], index) => {
const name = `h${index}`;
Object.defineProperty(Routes.prototype, name, {
value: (p: Record<string, string>) => ({ route: name, params: p }),
configurable: true,
});
param()(Routes.prototype, name, 0);
(options ? decorator(path, options) : decorator(path))(
Routes.prototype,
name,
Object.getOwnPropertyDescriptor(Routes.prototype, name)!,
);
});
Route('/')(Routes);
class RoutesModule {}
Module({ mountpoint: '/', controllers: [Routes] })(RoutesModule);
return RoutesModule;
}
const boot = (decls: Decl[]) => createApp({ modules: [moduleWith(decls)] });
const bootError = (decls: Decl[]): string => {
try {
boot(decls);
} catch (error) {
return (error as Error).message;
}
throw new Error('expected the app to refuse to boot');
};
async function get(app: ReturnType<typeof createApp>, path: string) {
const res = await app.fetch(new Request(`http://x${path}`));
return res.json();
}
describe('CARD-13: constrained params that can never be reached, or tie with a sibling', () => {
it('T1: GET /algo/:id + GET /algo/:a(.*) boots — `.` leaves line terminators to :id', async () => {
// The card expected `:id` to be unreachable. It is not: without the `s` flag `.` excludes line
// terminators, so a segment such as `%0A` fails `(.*)` and lands on `:id`. Refusing to boot would
// claim something false about the router.
const app = boot([
[Get, '/algo/:id'],
[Get, '/algo/:a(.*)'],
]);
expect(await get(app, '/algo/x')).toEqual({ route: 'h1', params: { a: 'x' } });
expect(await get(app, '/algo/%0A')).toEqual({ route: 'h0', params: { id: '\n' } });
});
it('T1 (every segment): GET /algo/:id + GET /algo/:a([^]*) fails, naming both', () => {
expect(
bootError([
[Get, '/algo/:id'],
[Get, '/algo/:a([^]*)'],
]),
).toBe(
'unreachable route GET /algo/:id at Routes.h0: GET /algo/:a([^]*) at Routes.h1 matches every request it would, ' +
'and wins each one — its constraint accepts every segment, and a constrained parameter outranks a plain one. ' +
'Remove one of them, or narrow the constraint',
);
});
it('T2: GET /u/:id(\\d+) + GET /u/:n(\\d{1,3}) fails with a witness', () => {
expect(
bootError([
[Get, '/u/:id(\\d+)'],
[Get, '/u/:n(\\d{1,3})'],
]),
).toBe(
"ambiguous route GET /u/:n(\\d{1,3}) at Routes.h1 conflicts with GET /u/:id(\\d+) at Routes.h0: both match '0' " +
'(GET /u/0), so only declaration order would choose between them — give the constraints disjoint languages, ' +
'or merge the routes',
);
});
it('T3: equivalent sources — GET /u/:id(\\d+) + GET /u/:id([0-9]+) fails', () => {
expect(
bootError([
[Get, '/u/:id(\\d+)'],
[Get, '/u/:id([0-9]+)'],
]),
).toMatch(
/^ambiguous route GET \/u\/:id\(\[0-9\]\+\) at Routes\.h1 conflicts with GET \/u\/:id\(\\d\+\) .*both match '0'/,
);
});
it('T4: GET /u/:id(\\d+) + GET /u/:slug boots, and routing is unchanged', async () => {
for (const order of [
[
[Get, '/u/:id(\\d+)'],
[Get, '/u/:slug'],
],
[
[Get, '/u/:slug'],
[Get, '/u/:id(\\d+)'],
],
] as Decl[][]) {
const app = boot(order);
const idRoute = order[0][1].includes('(') ? 'h0' : 'h1';
const slugRoute = idRoute === 'h0' ? 'h1' : 'h0';
expect(await get(app, '/u/42')).toEqual({ route: idRoute, params: { id: '42' } });
expect(await get(app, '/u/bob')).toEqual({ route: slugRoute, params: { slug: 'bob' } });
}
});
it('T5: disjoint constraints — GET /u/:id(\\d+) + GET /u/:s([a-z]+) boots', () => {
expect(() =>
boot([
[Get, '/u/:id(\\d+)'],
[Get, '/u/:s([a-z]+)'],
]),
).not.toThrow();
});
it('T6: different methods — GET /u/:id(\\d+) + POST /u/:n(\\d{1,3}) boots', () => {
expect(() =>
boot([
[Get, '/u/:id(\\d+)'],
[Post, '/u/:n(\\d{1,3})'],
]),
).not.toThrow();
});
it('T7: WS /r/:id + WS /r/:a(.*) fails — WebSocket routes match in declaration order', () => {
expect(
bootError([
[Ws, '/r/:id'],
[Ws, '/r/:a(.*)'],
]),
).toBe(
'unreachable route WS /r/:a(.*) at Routes.h1: WS /r/:id at Routes.h0 matches every request it would, and wins ' +
'each one — WebSocket routes are matched in declaration order, and it is declared first. Remove one of them, ' +
'or narrow the constraint',
);
});
it('T7 (more): WS follows rule 2, and only its own table', () => {
expect(
bootError([
[Ws, '/r/:id(\\d+)'],
[Ws, '/r/:n(\\d{1,3})'],
]),
).toMatch(/^ambiguous route WS \/r\/:n.*both match '0' \(WebSocket \/r\/0\)/);
// A WS route and an HTTP GET are different tables: an upgrade never reaches the HTTP route.
expect(() =>
boot([
[Ws, '/r/:id'],
[Get, '/r/:a([^]*)'],
]),
).not.toThrow();
// `@Stream` (negotiate) is served from both tables, so it is checked under both precedences.
expect(
bootError([
[Stream, '/s/:id'],
[Ws, '/s/:a(\\d+)'],
]),
).toMatch(/^unreachable route WS \/s\/:a\(\\d\+\) at Routes\.h1: GET \/s\/:id at Routes\.h0/);
});
it('T9: {0,2048} against {0,2048} at boot — result and time', () => {
const started = performance.now();
expect(
bootError([
[Get, '/t/:a(\\d{0,2048})'],
[Get, '/t/:b([0-9]{0,2048})'],
]),
).toMatch(/both match '0' \(GET \/t\/0\)/);
expect(() =>
boot([
[Get, '/t/:a(\\d{0,2048})'],
[Get, '/t/:b([a-z]{0,2048})'],
]),
).not.toThrow();
expect(() =>
boot([
[Get, `/w/:a(${'\\d{0,2048}'.repeat(12)}a)`],
[Get, `/w/:b(${'[0-9]{0,2048}'.repeat(9)}b)`],
]),
).not.toThrow();
expect(performance.now() - started).toBeLessThan(5000);
});
});
// ── T8: mesh ─────────────────────────────────────────────────────────────────────────────────────
const SECRET = 'card-13-secret';
const controlUrl = (server: { address(): unknown }) =>
`ws://127.0.0.1:${(server.address() as { port: number }).port}/__mesh__/control`;
async function teacupWith(teapots: Decl[][], local: Decl[] = [[Get, '/c/ok']]) {
const servers = await Promise.all(
teapots.map((decls) =>
createApp({
modules: [moduleWith(decls, { export: true })],
experimental: true,
mesh: { secret: SECRET },
}).listen(0),
),
);
const teacup = createApp({
modules: [moduleWith(local)],
experimental: true,
mesh: { teapots: servers.map((server) => ({ url: controlUrl(server), secret: SECRET })) },
});
return {
teacup,
urls: servers.map(controlUrl),
close: async () => {
await teacup.close();
servers.forEach((server) => server.close());
},
};
}
describe('CARD-13 T8: the same check between remote siblings', () => {
it("T8: two teapots exporting T2's pair refuse to boot the teacup", async () => {
const { teacup, urls, close } = await teacupWith([[[Get, '/u/:id(\\d+)']], [[Get, '/u/:n(\\d{1,3})']]]);
try {
await expect(teacup.ready()).rejects.toThrow(
`mesh: ambiguous remote route 'GET /u/:n(\\d{1,3})' from ${urls[1]} conflicts with 'GET /u/:id(\\d+)' ` +
`from ${urls[0]}: both match '0' (GET /u/0) — green-tea will not choose one for you. ` +
'Export only one of them, or give their constraints disjoint languages.',
);
} finally {
await close();
}
});
it('an unreachable remote sibling refuses to boot too', async () => {
const { teacup, close } = await teacupWith([[[Get, '/v/:id']], [[Get, '/v/:a([^]+)']]]);
try {
await expect(teacup.ready()).rejects.toThrow(
/^mesh: unreachable remote route 'GET \/v\/:id' from .*'GET \/v\/:a\(\[\^\]\+\)'/,
);
} finally {
await close();
}
});
it('a fallback pair across teapots boots and routes as before', async () => {
const { teacup, close } = await teacupWith([[[Get, '/u/:id(\\d+)']], [[Get, '/u/:slug']]]);
try {
expect(await get(teacup, '/u/42')).toEqual({ route: 'h0', params: { id: '42' } });
expect(await get(teacup, '/u/bob')).toEqual({ route: 'h0', params: { slug: 'bob' } });
} finally {
await close();
}
});
it('local against remote keeps the deliberate local override: no new error', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
const { teacup, close } = await teacupWith([[[Get, '/u/:n(\\d{1,3})']]], [[Get, '/u/:id(\\d+)']]);
try {
expect(await get(teacup, '/u/7')).toEqual({ route: 'h0', params: { id: '7' } });
} finally {
warn.mockRestore();
await close();
}
});
});
+296
View File
@@ -0,0 +1,296 @@
/**
* The decision procedure behind CARD-13 (#127): constraint atoms read back as character sets,
* intersection with a witness, "accepts every segment", and the route-level definitions.
*
* Every answer is checked against the RegExp engine itself, which is the router's ground truth: atom
* sets code point by code point, witnesses by matching them, and the product walk against brute-force
* enumeration over short strings (fixed seed).
*/
import { describe, it, expect } from 'vitest';
import { compilePattern } from '../src/http/router';
import {
acceptsEverySegment,
atomSet,
constraintBlocks,
intersectionWitness,
routeConflict,
type CharSet,
type Precedence,
} from '../src/http/route-conflicts';
const engine = (source: string) => new RegExp(`^(?:${source})$`, 'u');
/** What the router can hand a param: non-empty, and never `.` or `..` (normalization resolves them). */
const inUniverse = (segment: string) => segment.length > 0 && segment !== '.' && segment !== '..';
function inSet(set: CharSet, cp: number): boolean {
for (let i = 0; i < set.length; i += 2) if (cp >= set[i] && cp <= set[i + 1]) return true;
return false;
}
/** All of the BMP but surrogates, a stride through the astral planes, and every range edge ± 1. */
function probes(set: CharSet): number[] {
const out: number[] = [];
for (let cp = 0; cp <= 0xffff; cp++) if (cp < 0xd800 || cp > 0xdfff) out.push(cp);
for (let cp = 0x10000; cp <= 0x10ffff; cp += 97) out.push(cp);
for (const edge of set) out.push(edge - 1, edge, edge + 1);
return out.filter((cp) => cp >= 0 && cp <= 0x10ffff && (cp < 0xd800 || cp > 0xdfff));
}
const ATOMS = [
'\\d',
'\\D',
'\\w',
'\\W',
'\\s',
'\\S',
'.',
'\\.',
'a',
'_',
'-',
'[a-z]',
'[^a-z]',
'[^]',
'[\\s\\S]',
'[\\d\\-x]',
'[-a]',
'[a-]',
'[^.]',
'[\\u0041-\\u005A]',
'[\\u{1F600}-\\u{1F602}]',
'[\\uD83D\\uDE00]',
'[\\x00-\\x1f]',
'[\\b\\cJ\\0\\t]',
'[\\]\\[\\\\\\/]',
'[😀-😂]',
'[\\p{L}]',
'[^\\P{Nd}]',
];
describe('constraint atoms read back as character sets', () => {
it.each(ATOMS)('%s matches exactly what the engine matches', (atom) => {
const set = atomSet(atom);
const test = engine(atom);
const wrong = probes(set).filter((cp) => inSet(set, cp) !== test.test(String.fromCodePoint(cp)));
expect(wrong.slice(0, 5)).toEqual([]);
});
it('an unescaped dot is not every character: line terminators are outside it', () => {
// Without the `s` flag, `.` excludes \n, \r, U+2028 and U+2029 — so `(.*)` does not cover every
// segment, and `/algo/%0A` still reaches a plain sibling. This is the router's real behaviour.
const dot = atomSet('.');
expect([0x0a, 0x0d, 0x2028, 0x2029].map((cp) => inSet(dot, cp))).toEqual([false, false, false, false]);
expect(acceptsEverySegment(constraintBlocks('.*'))).toBe(false);
expect(acceptsEverySegment(constraintBlocks('[^]*'))).toBe(true);
});
});
describe('acceptsEverySegment', () => {
it.each([
['[^]*', true],
['[^]+', true],
['[\\s\\S]*', true],
['[\\s\\S]{0,4}[^]*', true],
['[^]?[^]*', true],
['a?[^]*', true],
['[^][^]+', false], // needs two characters: `a` is a segment
['a[^]*', false], // a mandatory block narrower than Σ
['[^]{0,2048}', false], // bounded
['.*', false],
['\\S+', false],
['[a-z]*[^]{1,2048}', false],
])('%s → %s', (source, expected) => {
expect(acceptsEverySegment(constraintBlocks(source))).toBe(expected);
});
});
// ── property: the product walk against brute force ───────────────────────────────────────────────
/** mulberry32, fixed seed: the generated pairs are the same on every run. */
function rng(seed: number) {
return () => {
seed = (seed + 0x6d2b79f5) | 0;
let t = Math.imul(seed ^ (seed >>> 15), 1 | seed);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
}
const SEED = 13127;
const GEN_ATOMS = [
'\\d',
'\\D',
'\\w',
'\\s',
'\\S',
'.',
'\\.',
'a',
'0',
'-',
'[a-c]',
'[^0-9]',
'[.a]',
'[^.]',
'[^]',
];
const GEN_QUANTIFIERS = ['', '', '?', '*', '+', '{0,2}', '{1,3}', '{2}', '{1,}'];
const PROBE_CHARS = ['0', '5', 'a', 'c', 'Z', '.', '-', '_', ' ', '\n', 'é', '😀', '/'];
function randomConstraint(next: () => number): string | undefined {
const pick = <T>(list: T[]) => list[Math.floor(next() * list.length)];
const atoms = 1 + Math.floor(next() * 3);
let source = '';
for (let i = 0; i < atoms; i++) source += pick(GEN_ATOMS) + pick(GEN_QUANTIFIERS);
try {
compilePattern(`/p/:x(${source})`); // only what the router accepts
return source;
} catch {
return undefined;
}
}
function shortStrings(maxLength: number): string[] {
let level = [''];
const out: string[] = [];
for (let length = 1; length <= maxLength; length++) {
level = level.flatMap((prefix) => PROBE_CHARS.map((c) => prefix + c));
out.push(...level);
}
return out.filter(inUniverse);
}
describe('intersectionWitness', () => {
const STRINGS = shortStrings(3);
it(`agrees with brute force over short strings (seed ${SEED})`, () => {
const next = rng(SEED);
let pairs = 0;
let intersecting = 0;
while (pairs < 300) {
const a = randomConstraint(next);
const b = randomConstraint(next);
if (!a || !b) continue;
pairs++;
const witness = intersectionWitness(constraintBlocks(a), constraintBlocks(b));
const [ra, rb] = [engine(a), engine(b)];
const brute = STRINGS.find((s) => ra.test(s) && rb.test(s));
// Sound: a witness is a real segment both accept.
if (witness !== undefined) {
intersecting++;
expect({ a, b, witness, ok: inUniverse(witness) && ra.test(witness) && rb.test(witness) }).toMatchObject({
ok: true,
});
}
// Complete: anything brute force finds, the walk finds too.
if (brute !== undefined) expect({ a, b, brute, found: witness !== undefined }).toMatchObject({ found: true });
}
// Both outcomes are exercised, not just one.
expect(intersecting).toBeGreaterThan(30);
expect(pairs - intersecting).toBeGreaterThan(30);
});
it.each([
['\\d+', '\\d{1,3}', '0'],
['\\d+', '[0-9]+', '0'],
['\\d+', '[a-z]+', undefined],
['\\d{2}', '\\d{3}', undefined],
['a\\d{2}', '\\w{3}', 'a00'],
['\\.', '[.]', undefined], // only `.`, which normalization removes
['\\.{1,2}', '[.]+', undefined], // `.` and `..` only
['\\.+', '[.]{2,5}', '...'],
['[^]{3}', '\\D\\d', undefined],
['[^]{3}', '\\D\\d-', 'a0-'],
['\\d{0,2048}', '[0-9]{0,2048}', '0'],
['\\d{0,2048}', '[a-z]{0,2048}', undefined],
['\\d{2048}', '\\d{0,2047}', undefined],
])('%s ∩ %s → %s', (a, b, expected) => {
const witness = intersectionWitness(constraintBlocks(a), constraintBlocks(b));
expect(witness).toBe(expected);
if (witness !== undefined) expect(engine(a).test(witness) && engine(b).test(witness)).toBe(true);
});
it('T9: {0,2048} against {0,2048}, and the largest product the grammar allows, stay well inside boot time', () => {
// A {0,2048} block is 10 source characters, so 12 fill the 128-character limit. The trailing
// `a` / `b` makes the intersection empty, so the walk must visit every reachable state.
const worstA = constraintBlocks('\\d{0,2048}'.repeat(12) + 'a');
const worstB = constraintBlocks('[0-9]{0,2048}'.repeat(9) + 'b');
const started = performance.now();
expect(intersectionWitness(constraintBlocks('\\d{0,2048}'), constraintBlocks('[0-9]{0,2048}'))).toBe('0');
expect(intersectionWitness(worstA, worstB)).toBeUndefined();
// Measured at ~0.1 ms and ~100 ms on an M-series laptop; the bound only guards against a
// regression to the exponential or quadratic-per-value walk.
expect(performance.now() - started).toBeLessThan(5000);
});
});
// ── route level ──────────────────────────────────────────────────────────────────────────────────
const conflict = (a: string, b: string, precedence: Precedence = 'specificity') =>
routeConflict(compilePattern(a), compilePattern(b), precedence);
describe('routeConflict', () => {
it.each([
// Rule 1: a constraint that accepts every segment outranks a plain sibling, whatever the order.
['/algo/:id', '/algo/:a([^]*)', { kind: 'unreachable', loser: 0 }],
['/algo/:a([\\s\\S]+)', '/algo/:id', { kind: 'unreachable', loser: 1 }],
['/algo/:id', '/algo/:a(.*)', undefined], // `.` leaves line terminators to `:id`
// Rule 2, with the whole-pattern condition.
['/u/:id(\\d+)', '/u/:n(\\d{1,3})', { kind: 'ambiguous', segment: '0', path: '/u/0' }],
['/u/:id(\\d+)', '/u/:id([0-9]+)', { kind: 'ambiguous', segment: '0', path: '/u/0' }],
['/u/:id(\\d+)/a', '/u/:n(\\d{1,3})/b', undefined],
['/u/:id(\\d+)/a', '/u/:n(\\d{1,3})/:x', { kind: 'ambiguous', segment: '0', path: '/u/0/a' }],
['/u/:id(\\d+)/:r*', '/u/:n(\\d{1,3})/x/y', { kind: 'ambiguous', segment: '0', path: '/u/0/x/y' }],
['/u/:id(\\d+)', '/u/:n(\\d{1,3})/:r*', { kind: 'ambiguous', segment: '0', path: '/u/0' }],
['/:p([a-z]+)/:id(\\d+)', '/:p([a-z]+)/:n(\\d{2})', { kind: 'ambiguous', segment: '00', path: '/a/00' }],
// Rule 3 and other non-errors.
['/u/:id(\\d+)', '/u/:slug', undefined],
['/u/:id(\\d+)', '/u/:s([a-z]+)', undefined],
['/u/me', '/u/:id(me)', undefined], // a static is not a sibling param: `/u/%6De` still reaches `:id`
['/x/:a/:id(\\d+)', '/x/s/:n([0-9]+)', undefined], // different radix nodes: the static decides
['/a/:id', '/a/:x([^]*)/:r*', undefined], // an exact route outranks a catch-all one
// Rule 1 needs the rest included, segment by segment.
['/a/:x([^]+)/b', '/a/:id/c', undefined],
['/a/:x([^]+)/:y', '/a/:id/c', { kind: 'unreachable', loser: 1 }],
['/a/:x([^]+)/:y/:r*', '/a/:id/c/:s*', { kind: 'unreachable', loser: 1 }],
['/a/:x([^]+)/:r*', '/a/:id/c/d', undefined], // the exact route outranks the catch-all one
['/a/:x([^]+)/:y(\\d+)', '/a/:id/:z(\\d+)', { kind: 'unreachable', loser: 1 }],
// Different constraints at a later position are not compared, so this boots (documented limit).
['/a/:x([^]+)/:y(\\d+)', '/a/:id/:z([0-9]+)', undefined],
])('%s vs %s', (a, b, expected) => {
expect(conflict(a, b)).toEqual(expected);
});
it('WebSocket precedence is declaration order', () => {
expect(conflict('/r/:id', '/r/:a(.*)', 'registration')).toEqual({ kind: 'unreachable', loser: 1 });
expect(conflict('/r/:slug', '/r/:id(\\d+)', 'registration')).toEqual({ kind: 'unreachable', loser: 1 });
expect(conflict('/r/:id(\\d+)', '/r/:slug', 'registration')).toBeUndefined();
expect(conflict('/r/:id(\\d+)', '/r/:n(\\d{1,3})', 'registration')).toMatchObject({ kind: 'ambiguous' });
});
it('every ambiguous witness path is a request both routes really match', async () => {
const { matchPattern } = await import('../src/http/router');
const pairs: Array<[string, string]> = [
['/u/:id(\\d+)/a', '/u/:n(\\d{1,3})/:x'],
['/v/:a([^a-z]+)', '/v/:b(\\s)'],
['/w/:a([%x]{2})', '/w/:b(\\W+)'],
['/k/:a(\\.+)', '/k/:b([.]{2,5})'],
];
for (const [a, b] of pairs) {
const found = conflict(a, b);
expect(found?.kind).toBe('ambiguous');
const path = (found as { path: string }).path;
expect([a, path, matchPattern(a, path)]).not.toContain(undefined);
expect([b, path, matchPattern(b, path)]).not.toContain(undefined);
}
});
});