Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 4 additions & 4 deletions packages/router/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`.
Expand All @@ -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

Expand Down
216 changes: 90 additions & 126 deletions packages/router/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -51,10 +47,10 @@ interface CatchAll<T> {
readonly route: Route<T>
}

/** 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<T> {
readonly key: string
readonly texts: readonly string[]
readonly template: Template
readonly node: Node<T>
}

Expand Down Expand Up @@ -111,13 +107,23 @@ interface MethodRoutes<T> {
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

/**
Expand All @@ -142,8 +148,7 @@ const EMPTY_NODE: Readonly<Node<never>> = {
*
* - `{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`.
Expand All @@ -165,7 +170,8 @@ export class Router<T> {
/**
* 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.
Expand Down Expand Up @@ -239,18 +245,7 @@ function addParsed<T>(
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<RouteParam>).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[]
Expand All @@ -269,6 +264,32 @@ function addParsed<T>(
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<RouteParam>).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<T>(methods: Map<string, MethodRoutes<T>>, method: string): MethodRoutes<T> {
let routes = methods.get(method)
if (routes === undefined) {
Expand Down Expand Up @@ -308,8 +329,12 @@ function addStatic<T>(
* 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.
Expand All @@ -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
}
}
Expand Down Expand Up @@ -483,19 +505,18 @@ function expand<T>(node: Node<T>, 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]
} else {
params.push(segment)
}

if (segment.template !== undefined) {
child = templateChild(child, segment.template)
continue
}

if (!segment.catchAll) {
child.param ??= { ...EMPTY_NODE }
child = child.param
Expand Down Expand Up @@ -529,14 +550,10 @@ function addCatchAll<T>(
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}`
}
}

Expand All @@ -547,18 +564,6 @@ function addCatchAll<T>(
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
Expand All @@ -573,7 +578,7 @@ function templateChild<T>(node: Node<T>, template: Template): Node<T> {
}

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
}
Expand Down Expand Up @@ -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
}

/**
Expand All @@ -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
}

/**
Expand Down Expand Up @@ -826,8 +790,8 @@ function findTemplate<T>(
segments: readonly string[],
index: number,
): Route<T> | 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
Expand Down Expand Up @@ -864,10 +828,10 @@ function toParams<T>(route: Route<T>, segments: readonly string[]): Record<strin
let params: Record<string, string> = {}
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
Expand Down
2 changes: 1 addition & 1 deletion packages/router/tests/prefix.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
Loading
Loading