diff --git a/packages/router/README.md b/packages/router/README.md index e63603c..299b63c 100644 --- a/packages/router/README.md +++ b/packages/router/README.md @@ -58,9 +58,9 @@ underUser('/projects/42') // false ## Path templates - `{name}` as a whole segment is a param. It matches one non-empty segment. Names are made of letters, digits, `_`, and `-`. -- `{name}` with literal text around it in a segment, as in `/files/{name}.json` or `/apps/{id}:publish`, is a param too, and its value cannot be empty. Params in one segment need text between them, as in `{name}-{version}.zip`, and each one takes the shortest value that lets the rest of the segment match. -- `{+name}` as a whole segment is a catch-all param. It matches one or more segments, slashes included, and its value cannot be empty. A path can have one, and segments can follow it, as in `/files/{+path}/raw`. Adding a path with more than one throws a `TypeError`. -- Any other text is literal, including braces around other names, as in `/{a.b}`, a segment where two params touch, as in `/{a}{b}`, and characters other routers treat as syntax, such as `:`, `*`, `?`, `(`, and `.`. +- `{name}` with literal text around it in a segment, as in `/files/{name}.json` or `/apps/{id}:publish`, is a param too, and its value cannot be empty. A segment can have one param, since `{name}.{ext}` could split `a.b.c` as `a` and `b.c` or as `a.b` and `c`. Adding a path, or creating a prefix matcher, with more than one param in a segment, as in `{name}.{ext}` or `{a}{b}`, throws a `TypeError`. +- `{+name}` as a whole segment is a catch-all param. It matches one or more segments, slashes included, and its value cannot be empty. A path can have one, and segments can follow it, as in `/files/{+path}/raw`. Adding a path, or creating a prefix matcher, with more than one throws a `TypeError`. +- Any other text is literal, including braces around other names, as in `/{a.b}`, a catch-all param inside a segment, as in `/{+path}.json`, and characters other routers treat as syntax, such as `:`, `*`, `?`, `(`, and `.`. - Literal text matches however the route or the request percent-encodes it: `/café` matches `/caf%C3%A9`, and `/v1^beta` matches `/v1%5Ebeta`. A `%2F` stays inside its segment. Text whose percent-encoding is malformed is compared as written. - Param values are percent-decoded. A catch-all param joins its decoded segments with `/`. - One trailing slash is ignored, in routes and in requests. Other empty segments are kept: `/a//b` does not match `/a/b`. @@ -81,7 +81,7 @@ router.match('GET', '/users/me/posts') // 'posts', with { id: 'me' } router.match('GET', '/users/me/likes') // 'fallback' ``` -Of two params with text around them, the one with more literal text wins, as `{name}.json` does over `{name}.{ext}`, whatever order they were added in. Catch-all params that start at the same segment compare the segments after them from the last one, so `/files/{+path}/raw` beats `/files/{+path}` for `/files/a/raw`. A route with the same method and segments as one added earlier, even with other param names, is ignored. +Of two params with text around them, the one with more literal text wins, as `{name}.tar.gz` does over `{name}.gz`, whatever order they were added in. Catch-all params that start at the same segment compare the segments after them from the last one, so `/files/{+path}/raw` beats `/files/{+path}` for `/files/a/raw`. A route with the same method and segments as one added earlier, even with other param names, is ignored. ## Performance diff --git a/packages/router/src/index.ts b/packages/router/src/index.ts index d5a2121..db68bb5 100644 --- a/packages/router/src/index.ts +++ b/packages/router/src/index.ts @@ -19,18 +19,14 @@ interface RouteParam { readonly catchAll: boolean /** The template of its segment, for a param with literal text around it there. */ readonly template?: Template | undefined - /** Which of the template's params this is. */ - readonly place?: number | undefined } -/** - * A segment with params and literal text around them, as in `{id}.json` or - * `{name}-{version}.zip`. - */ +/** The literal text around a param in a segment, as in `{id}.json` or `v{version}`. */ interface Template { - /** The decoded literal text before, between, and after its params. */ - readonly texts: readonly string[] - readonly names: readonly string[] + /** The decoded literal text before the param. */ + readonly before: string + /** The decoded literal text after the param. */ + readonly after: string /** * Tells templates apart by their literal text, and sorts the one with more * of it first, then those with as much by that text. @@ -51,10 +47,10 @@ interface CatchAll { readonly route: Route } -/** The child for a template at a node, with the template's key and texts. */ +/** The child for a template at a node, with the template's key. */ interface TemplateChild { readonly key: string - readonly texts: readonly string[] + readonly template: Template readonly node: Node } @@ -111,13 +107,23 @@ interface MethodRoutes { pending: unknown[] } -/** A literal segment's decoded text, a param, or a template. */ -type Segment = string | RouteParam | Template +/** A literal segment's decoded text, or a param, with the template around it, if any. */ +type Segment = string | RouteParam const PARAM_NAME = /^[\w-]+$/ const TEMPLATE_PARAM = /\{([\w-]+)\}/ +/** Two `{name}` params with no `/` between them, so in one segment. */ +const TWO_IN_SEGMENT = /\{[\w-]+\}[^/]*\{[\w-]+\}/ + +/** + * A `}` with more of its segment after it, as the first of two params in a + * segment has. Most paths have none, and this pattern rules them out at about + * half the cost of `TWO_IN_SEGMENT`. + */ +const TEXT_AFTER_BRACE = /\}[^/]/ + const FILTER_AFTER = 1024 /** @@ -142,8 +148,7 @@ const EMPTY_NODE: Readonly> = { * * - `{name}` as a whole segment is a param, matching one non-empty segment. * - `{name}` with literal text around it in a segment, as in `{id}.json`, is - * a param too, with a non-empty value. Params in one segment need text - * between them, and each takes the shortest value that lets the rest match. + * a param too, with a non-empty value. A segment can have one param. * - `{+name}` as a whole segment is a catch-all param, matching one or more * segments, slashes included, with a non-empty value. A path can have one, * and segments can follow it, as in `/files/{+path}/raw`. @@ -165,7 +170,8 @@ export class Router { /** * Adds a route for requests with exactly this `method`. * - * @throws {TypeError} if `path` has more than one catch-all param, before adding anything + * @throws {TypeError} if `path` has more than one param in a segment, or more + * than one catch-all param, before adding anything */ add(method: string, path: `/${string}`, data: T): void { // Without `{` or `%`, a path has only literal segments, which read the same decoded. @@ -239,18 +245,7 @@ function addParsed( braced: boolean, ): void { if (braced) { - // Only a path with `{+` twice can have two catch-all params. `lastIndexOf` - // would cost more, as V8 runs it outside its fast builtins. - const catchAll = path.indexOf('{+') - if ( - catchAll !== -1 && - path.includes('{+', catchAll + 2) && - parse(path).filter((segment) => (segment as Partial).catchAll === true).length > 1 - ) { - throw new TypeError( - `OpenAPI path "${path}" has more than one catch-all param ({+name}), but only one is supported per path.`, - ) - } + checkParams(path) } else { // Without `{`, every segment is literal text. const segments = parse(path) as string[] @@ -269,6 +264,32 @@ function addParsed( routesOf(methods, method).pending.push(path, data, undefined) } +/** + * Throws for a path whose params could split a request path in more than one + * way: with two params in a segment, as in `{name}.{ext}`, or two catch-all + * params. + */ +function checkParams(path: `/${string}`): void { + if (TEXT_AFTER_BRACE.test(path) && TWO_IN_SEGMENT.test(path)) { + throw new TypeError( + `OpenAPI path "${path}" has more than one param in a segment, but only one is supported per segment.`, + ) + } + + // Only a path with `{+` twice can have two catch-all params. `lastIndexOf` + // would cost more, as V8 runs it outside its fast builtins. + const catchAll = path.indexOf('{+') + if ( + catchAll !== -1 && + path.includes('{+', catchAll + 2) && + parse(path).filter((segment) => (segment as Partial).catchAll === true).length > 1 + ) { + throw new TypeError( + `OpenAPI path "${path}" has more than one catch-all param ({+name}), but only one is supported per path.`, + ) + } +} + function routesOf(methods: Map>, method: string): MethodRoutes { let routes = methods.get(method) if (routes === undefined) { @@ -308,8 +329,12 @@ function addStatic( * Creates a test of whether a request path can match a route under `prefix`, * such as one of a lazy router, to know when to load it. Segments after the * prefix, or from its catch-all param on, are not checked. + * + * @throws {TypeError} if `prefix` has more than one param in a segment, or more + * than one catch-all param */ export function createPrefixMatcher(prefix: `/${string}`): (pathname: `/${string}`) => boolean { + checkParams(prefix) const head: (string | Template | undefined)[] = [] // Built in this loop rather than with `every` and `map`, which a cold start // would compile as two more functions. @@ -323,13 +348,10 @@ export function createPrefixMatcher(prefix: `/${string}`): (pathname: `/${string } else if (text !== undefined) { text += '/' + segment } - } else if ('texts' in segment) { - head.push(segment) - text = undefined } else if (segment.catchAll) { break } else { - head.push(undefined) + head.push(segment.template) text = undefined } } @@ -483,12 +505,6 @@ function expand(node: Node, pending: unknown[], start: number): void { continue } - if ('texts' in segment) { - params = pushTemplateParams(params, segment, index) - child = templateChild(child, segment) - continue - } - // An array literal holds just its items, where a push to `[]` reserves 17. if (params === undefined) { params = [segment] @@ -496,6 +512,11 @@ function expand(node: Node, pending: unknown[], start: number): void { params.push(segment) } + if (segment.template !== undefined) { + child = templateChild(child, segment.template) + continue + } + if (!segment.catchAll) { child.param ??= { ...EMPTY_NODE } child = child.param @@ -529,14 +550,10 @@ function addCatchAll( if (typeof after === 'string') { tail.push(after) order = `0${order}` - } else if ('texts' in after) { - tail.push(after) - pushTemplateParams(params, after, i - parts.length) - order = `1${after.key}${order}` } else { - tail.push(undefined) + tail.push(after.template) params.push(after) - order = `2${order}` + order = after.template === undefined ? `2${order}` : `1${after.template.key}${order}` } } @@ -547,18 +564,6 @@ function addCatchAll( node.catchAlls.sort(byKey) } -function pushTemplateParams( - params: RouteParam[] | undefined, - template: Template, - index: number, -): RouteParam[] { - const list = params ?? [] - for (let place = 0; place < template.names.length; place++) { - list.push({ name: template.names[place]!, index, catchAll: false, template, place }) - } - return list -} - /** * The child for `template`, the one already there for a template with the * same literal text, with any param names, or a new one, kept after those @@ -573,7 +578,7 @@ function templateChild(node: Node, template: Template): Node { } const child = { ...EMPTY_NODE } - templates.push({ key: template.key, texts: template.texts, node: child }) + templates.push({ key: template.key, template, node: child }) templates.sort(byKey) return child } @@ -619,76 +624,35 @@ function toSegment(text: string, index: number): Segment { } } - return (text.includes('{') && toTemplate(text)) || decode(text) -} - -/** - * Reads a segment with `{name}` params inside literal text, as in `{id}.json`, - * or returns `undefined` when it has none, or two with no text between them, - * which would make their values ambiguous. - */ -function toTemplate(text: string): Template | undefined { - // Splitting on a pattern with a group puts each param name between the texts around it. - const parts = text.split(TEMPLATE_PARAM) - const texts: string[] = [] - const names: string[] = [] - for (let i = 0; i < parts.length; i += 2) { - const literal = decode(parts[i]!) - if (literal === '' && i > 0 && i < parts.length - 1) { - return undefined - } - texts.push(literal) - if (i < parts.length - 1) { - names.push(parts[i + 1]!) - } + // `add` and `createPrefixMatcher` reject a segment with two params, so + // splitting on a pattern with a group gives at most the text before one, + // its name, and the text after it. + const parts = text.includes('{') ? text.split(TEMPLATE_PARAM) : undefined + if (parts?.length === 3) { + const before = decode(parts[0]!) + const after = decode(parts[2]!) + // The first character sorts the template with more literal text first, + // and JSON keeps one key from being the start of another. + const key = + String.fromCharCode(Math.max(0, 65535 - before.length - after.length)) + + JSON.stringify([before, after]) + return { name: parts[1]!, index, catchAll: false, template: { before, after, key } } } - // The first character sorts the template with more literal text first, and - // JSON keeps one key from being the start of another. - return names.length === 0 - ? undefined - : { - texts, - names, - key: - String.fromCharCode(Math.max(0, 65535 - texts.join('').length)) + JSON.stringify(texts), - } + return decode(text) } /** - * The value of a template's param at `place`, or of its last one, in a decoded - * segment, or `undefined` if the segment does not match. Values are never - * empty. Each text between two params is taken where it first appears, which - * leaves the most room for the rest, so no other place needs trying, and the - * time stays linear in the segment's length, where a RegExp with a lazy group - * per param backtracks. One value, rather than an array of all of them, - * spares each match an allocation. + * The value of the param in a decoded segment that matches its template, or + * `undefined` if the segment does not. Values are never empty. */ -function templateValue( - texts: readonly string[], - segment: string, - place?: number, -): string | undefined { - const last = texts.length - 1 - const end = segment.length - texts[last]!.length - let start = texts[0]!.length - if (end - start < last || !segment.startsWith(texts[0]!) || !segment.endsWith(texts[last]!)) { - return undefined - } - - let value: string | undefined - for (let i = 1; i < last; i++) { - const at = segment.indexOf(texts[i]!, start + 1) - if (at === -1 || at + texts[i]!.length >= end) { - return undefined - } - if (i - 1 === place) { - value = segment.slice(start, at) - } - start = at + texts[i]!.length - } - - return value ?? segment.slice(start, end) +function templateValue(template: Template, segment: string): string | undefined { + const end = segment.length - template.after.length + return end > template.before.length && + segment.startsWith(template.before) && + segment.endsWith(template.after) + ? segment.slice(template.before.length, end) + : undefined } /** @@ -700,7 +664,7 @@ function matchesPart(expected: string | Template | undefined, segment: string): ? segment !== '' : typeof expected === 'string' ? segment === expected - : templateValue(expected.texts, segment) !== undefined + : templateValue(expected, segment) !== undefined } /** @@ -826,8 +790,8 @@ function findTemplate( segments: readonly string[], index: number, ): Route | undefined { - for (const { texts, node } of templates) { - if (templateValue(texts, segments[index]!) !== undefined) { + for (const { template, node } of templates) { + if (templateValue(template, segments[index]!) !== undefined) { const route = find(node, segments, index + 1) if (route !== undefined) { return route @@ -864,10 +828,10 @@ function toParams(route: Route, segments: readonly string[]): Record = {} const end = segments.length - route.tail - for (const { name, index, catchAll, template, place } of route.params!) { + for (const { name, index, catchAll, template } of route.params!) { let value = segments[index < 0 ? segments.length + index : index]! if (template !== undefined) { - value = templateValue(template.texts, value, place)! + value = templateValue(template, value)! } // Faster than `segments.slice(index, end).join('/')`. A template literal diff --git a/packages/router/tests/prefix.test.ts b/packages/router/tests/prefix.test.ts index 1499d19..59e2eaa 100644 --- a/packages/router/tests/prefix.test.ts +++ b/packages/router/tests/prefix.test.ts @@ -65,7 +65,7 @@ describe('createPrefixMatcher', () => { '/o/r': false, '/o/r/blobs/a': false, }) - expectPrefix('/files/{+path}/{+more}/x', { + expectPrefix('/files/{+path}/x', { '/files': true, '/files/a/b/info': true, '/filesx': false, diff --git a/packages/router/tests/router.test.ts b/packages/router/tests/router.test.ts index fcc8241..c3be281 100644 --- a/packages/router/tests/router.test.ts +++ b/packages/router/tests/router.test.ts @@ -1,4 +1,4 @@ -import { Router } from '@openapi-spec/router' +import { createPrefixMatcher, Router } from '@openapi-spec/router' import { expectMatches, routerOf } from './helpers' @@ -178,6 +178,7 @@ describe('Router', () => { ), ) expect(router.match('GET', '/a/x/b')).toBeUndefined() + expect(() => createPrefixMatcher('/{+a}/x/{+b}')).toThrowError(TypeError) }) it('accepts `{+` more than once when only one is a catch-all param', () => { diff --git a/packages/router/tests/templates.test.ts b/packages/router/tests/templates.test.ts index dd4d263..b7b6684 100644 --- a/packages/router/tests/templates.test.ts +++ b/packages/router/tests/templates.test.ts @@ -35,58 +35,76 @@ describe('params with text around them in a segment', () => { expect(createPrefixMatcher('/files/{name}%2Ejson')('/files/report.xml')).toBe(false) }) - it('reads params with text between them from left to right', () => { - const router = routerOf('/p/{name}-{version}.zip', '/q/{a}.{b}') + it('needs a non-empty value where the text before and after the param is the same', () => { + const router = routerOf('/x{id}x') expectMatches(router, { - '/p/router-1.2.zip': ['/p/{name}-{version}.zip', { name: 'router', version: '1.2' }], - '/p/open-api-1.zip': ['/p/{name}-{version}.zip', { name: 'open', version: 'api-1' }], - '/p/-1.zip': undefined, - '/p/a-.zip': undefined, - '/q/a.b.c': ['/q/{a}.{b}', { a: 'a', b: 'b.c' }], - '/q/a%0Ab.c': ['/q/{a}.{b}', { a: 'a\nb', b: 'c' }], + '/xax': ['/x{id}x', { id: 'a' }], + '/xxx': ['/x{id}x', { id: 'x' }], + '/xx': undefined, + '/x': undefined, }) }) - it('reads a long segment in linear time, where a lazy RegExp would backtrack', () => { - const router = routerOf('/p/{a}-{b}-{c}.zip') + it('throws for more than one param in a segment, adding nothing', () => { + const router = new Router() + + for (const path of [ + '/q/{a}.{b}', + '/p/{name}-{version}.zip', + '/a/{x}{y}', + '/{a}-{b}-{c}', + '/f/{+p}/{a}.{b}', + '/f/{+p}/x/{a}.{b}/y', + ] as const) { + expect(() => router.add('GET', path, path)).toThrowError( + new TypeError( + `OpenAPI path "${path}" has more than one param in a segment, but only one is supported per segment.`, + ), + ) + expect(() => createPrefixMatcher(path)).toThrowError(TypeError) + } + expect(router.match('GET', '/q/a.b')).toBeUndefined() + expect(router.match('GET', '/a/xy')).toBeUndefined() + }) - expect(router.match('GET', `/p/${'-'.repeat(100_000)}`)).toBeUndefined() - expect(router.match('GET', `/p/${'a-'.repeat(50_000)}.zip`)).toStrictEqual({ - data: '/p/{a}-{b}-{c}.zip', - params: { a: 'a', b: 'a', c: 'a-'.repeat(49_998) }, + it('accepts one param in a segment beside braces that are not a param', () => { + expectMatches(routerOf('/a/{x}.{a.b}', '/b/{+x}.{y}', '/c/{x}/{y}.{z'), { + '/a/1.%7Ba.b%7D': ['/a/{x}.{a.b}', { x: '1' }], + '/b/%7B+x%7D.1': ['/b/{+x}.{y}', { y: '1' }], + '/c/1/2.%7Bz': ['/c/{x}/{y}.{z', { x: '1', y: '2' }], }) }) it('ranks them after literals and before params, more literal text first', () => { const router = routerOf( '/f/{x}', - '/f/{a}.{b}', + '/f/{a}n', '/f/{name}.json', '/f/me.json', '/f/{+rest}', - '/g/{x}.{y}/raw', + '/g/{x}.zip/raw', '/g/{id}/{+rest}', ) expectMatches(router, { '/f/me.json': ['/f/me.json'], '/f/you.json': ['/f/{name}.json', { name: 'you' }], - '/f/you.xml': ['/f/{a}.{b}', { a: 'you', b: 'xml' }], + '/f/you.xn': ['/f/{a}n', { a: 'you.x' }], '/f/you': ['/f/{x}', { x: 'you' }], '/f/a/b': ['/f/{+rest}', { rest: 'a/b' }], - '/g/a.b/raw': ['/g/{x}.{y}/raw', { x: 'a', y: 'b' }], + '/g/a.zip/raw': ['/g/{x}.zip/raw', { x: 'a' }], // falls back to the param when the rest of the path does not match - '/g/a.b/other': ['/g/{id}/{+rest}', { id: 'a.b', rest: 'other' }], + '/g/a.zip/other': ['/g/{id}/{+rest}', { id: 'a.zip', rest: 'other' }], }) }) it('falls back to the next one when the rest of the path does not match', () => { - const router = routerOf('/h/{name}.json/raw', '/h/{a}.{b}/other') + const router = routerOf('/h/{name}.json/raw', '/h/{a}n/other') expectMatches(router, { '/h/x.json/raw': ['/h/{name}.json/raw', { name: 'x' }], - '/h/x.json/other': ['/h/{a}.{b}/other', { a: 'x', b: 'json' }], + '/h/x.json/other': ['/h/{a}n/other', { a: 'x.jso' }], }) }) @@ -99,22 +117,20 @@ describe('params with text around them in a segment', () => { }) it('keeps that order whatever segments follow them', () => { - const paths = ['/{a}.{b}/{c}', '/{a}b/b'] as const + const paths = ['/{a}-x/{c}', '/x-{b}/b'] as const for (const router of [routerOf(...paths), routerOf(...paths.toReversed())]) { - expect(router.match('GET', '/x.yb/b')).toStrictEqual({ - data: '/{a}.{b}/{c}', - params: { a: 'x', b: 'yb', c: 'b' }, + expect(router.match('GET', '/x-x/b')).toStrictEqual({ + data: '/{a}-x/{c}', + params: { a: 'x', c: 'b' }, }) } }) - it('keeps braces literal around other names, and segments where two params touch', () => { - const router = routerOf('/a/{x}{y}', '/b/{x}.{a.b}', '/c/{+x}.json') + it('keeps braces literal around other names, and a catch-all param inside a segment', () => { + const router = routerOf('/b/{x}.{a.b}', '/c/{+x}.json') expectMatches(router, { - '/a/%7Bx%7D%7By%7D': ['/a/{x}{y}'], - '/a/12': undefined, '/b/1.%7Ba.b%7D': ['/b/{x}.{a.b}', { x: '1' }], '/b/1.2': undefined, '/c/%7B+x%7D.json': ['/c/{+x}.json'], @@ -149,23 +165,23 @@ describe('params with text around them in a segment', () => { }) it('ranks templates after a catch-all param the same way', () => { - const paths = ['/f/{+p}/{a}-{b}', '/f/{+p}/{name}.json'] as const + const paths = ['/f/{+p}/{a}n', '/f/{+p}/{name}.json'] as const for (const router of [routerOf(...paths), routerOf(...paths.toReversed())]) { expectMatches(router, { '/f/x/a-b.json': ['/f/{+p}/{name}.json', { p: 'x', name: 'a-b' }], - '/f/x/a-b': ['/f/{+p}/{a}-{b}', { p: 'x', a: 'a', b: 'b' }], + '/f/x/a-bn': ['/f/{+p}/{a}n', { p: 'x', a: 'a-b' }], }) } }) it('ranks the one with more literal text first after a catch-all param, before the segments ahead of it', () => { - const paths = ['/f/{+p}/{x}/{a}.{b}', '/f/{+p}/{name}.json'] as const + const paths = ['/f/{+p}/{x}/{a}n', '/f/{+p}/{name}.json'] as const for (const router of [routerOf(...paths), routerOf(...paths.toReversed())]) { expectMatches(router, { '/f/x/y/z.json': ['/f/{+p}/{name}.json', { p: 'x/y', name: 'z' }], - '/f/x/y/z.xml': ['/f/{+p}/{x}/{a}.{b}', { p: 'x', x: 'y', a: 'z', b: 'xml' }], + '/f/x/y/z.xn': ['/f/{+p}/{x}/{a}n', { p: 'x', x: 'y', a: 'z.x' }], }) } })