feat(reg-exp-router): throw UnsupportedPathError during route registration (#5171)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* fix(reg-exp-router): make wildcard sibling order in the regexp deterministic compareKey() was inconsistent when comparing the only wildcard with the tail wildcard, so their order relied on the insertion order normalized by the path-length sort in the matcher build. * fix(reg-exp-router): capture params on a label node created by an unnamed wildcard A param like /w/:id/y registered together with /w/*/x reused the label node created by the unnamed wildcard, which has no var index assigned, so the param value was lost. * feat(reg-exp-router): throw UnsupportedPathError when adding routes Insert paths into per-method tries incrementally in add() so that unsupported path combinations are detected at registration time instead of at the first match. - Static paths are inserted as real nodes (character by character, with no pattern interpretation), but branches without a dynamic terminal are excluded from the regexp, so the generated matchers stay identical to the previous implementation. - Conflict checks no longer depend on the insertion order: wildcard nodes coexist with anything, and a single-character pattern like /:x{a} coexists with single-character literals. - Node#insert is now a loop instead of recursion with array spreads, making registration plus the first match roughly 20% faster. * test(reg-exp-router): cover method-specific path validation
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+331 added−233 removed
- tests:+159 added−35 removed
- other:+172 added−198 removed
Provenance
- Commit
8a0b18f- Tree
b4c064c- Author
Taku Amano <taku@taaas.jp>- Committer
GitHub <noreply@github.com>- Parent
3feb355
4 files changed+331 added−233 removed
modified:src/router/reg-exp-router/node.ts+86 added-80 removed
23 unmodified lines242526272828293030313233347 unmodified lines4243444546474849505152535455555657575859606162635859606162636465666768697071726566676869707172737475767778798081828384857374757677787980818283848586878889908788899091929194959697989910010192939495969798991001011021031041051061071031041051061081081091101111101111121131141151161171181191201211221231121131141151161171181191201211221231241251251261271281261271281291301321311321331341351361371381391381391401411421431441451461471401411421431441451461471481491501511521531541491551561571581599 unmodified lines23 unmodified lines if (b.length === 1) { return 1 }
// wildcard // wildcard: the only wildcard (.*) precedes the tail wildcard if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) { return 1 return b === TAIL_WILDCARD_REG_EXP_STR ? -1 : 1 } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) { return -1 }
7 unmodified lines return a.length === b.length ? (a < b ? -1 : 1) : b.length - a.length}
export class Node { // handler index of a dynamic path, or -1 for a static path terminal #index?: number #varIndex?: number #children: Record<string, Node> = Object.create(null)
insert( tokens: readonly string[], index: number, paramMap: ParamAssocArray, context: Context, pathErrorCheckOnly: boolean isStatic: boolean ): void { if (tokens.length === 0) { if (this.#index !== undefined) { throw PATH_ERROR } if (pathErrorCheckOnly) { return } // eslint-disable-next-line @typescript-eslint/no-this-alias let node: Node = this for (let i = 0, len = tokens.length; i < len; i++) { const token = tokens[i] const pattern = token.length === 1 ? token === '*' ? i === len - 1 ? ['', '', ONLY_WILDCARD_REG_EXP_STR] // '*' matches to all the trailing paths : ['', '', LABEL_REG_EXP_STR] : null : token === '/*' ? ['', '', TAIL_WILDCARD_REG_EXP_STR] // '/path/to/*' is /\/path\/to(?:|/.*)$ : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/)
this.#index = index return }
const [token, ...restTokens] = tokens const pattern = token === '*' ? restTokens.length === 0 ? ['', '', ONLY_WILDCARD_REG_EXP_STR] // '*' matches to all the trailing paths : ['', '', LABEL_REG_EXP_STR] : token === '/*' ? ['', '', TAIL_WILDCARD_REG_EXP_STR] // '/path/to/*' is /\/path\/to(?:|/.*)$ : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/)
let node if (pattern) { const name = pattern[1] let regexpStr = pattern[2] || LABEL_REG_EXP_STR if (name && pattern[2]) { if (regexpStr === '.*') { throw PATH_ERROR let nextNode: Node if (pattern) { const name = pattern[1] let regexpStr = pattern[2] || LABEL_REG_EXP_STR if (name && pattern[2]) { if (regexpStr === '.*') { throw PATH_ERROR } regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, '(?:') // (a|b) => (?:a|b) if (/\((?!\?:)/.test(regexpStr)) { // prefix(?:a|b) is allowed, but prefix(a|b) is not throw PATH_ERROR } if (regexpStr.length === 1 && regExpMetaChars.has(regexpStr)) { // a single-char pattern like :x{.} is ambiguous with a literal character throw PATH_ERROR } } regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, '(?:') // (a|b) => (?:a|b) if (/\((?!\?:)/.test(regexpStr)) { // prefix(?:a|b) is allowed, but prefix(a|b) is not throw PATH_ERROR } }
node = this.#children[regexpStr] if (!node) { if ( Object.keys(this.#children).some( (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR ) ) { throw PATH_ERROR nextNode = node.#children[regexpStr] if (!nextNode) { if (regexpStr !== ONLY_WILDCARD_REG_EXP_STR && regexpStr !== TAIL_WILDCARD_REG_EXP_STR) { for (const k in node.#children) { if ( // a single-char pattern coexists with single-char literals as a literal does (regexpStr.length > 1 || k.length > 1) && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR ) { throw PATH_ERROR } } } nextNode = node.#children[regexpStr] = new Node() } if (pathErrorCheckOnly) { return } node = this.#children[regexpStr] = new Node() if (name !== '') { node.#varIndex = context.varIndex++ nextNode.#varIndex ??= context.varIndex++ paramMap.push([name, nextNode.#varIndex]) } } if (!pathErrorCheckOnly && name !== '') { paramMap.push([name, node.#varIndex as number]) } } else { node = this.#children[token] if (!node) { if ( Object.keys(this.#children).some( (k) => k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR ) ) { throw PATH_ERROR } else { nextNode = node.#children[token] if (!nextNode) { for (const k in node.#children) { if ( k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR ) { throw PATH_ERROR } } nextNode = node.#children[token] = new Node() } if (pathErrorCheckOnly) { return } node = this.#children[token] = new Node() }
node = nextNode }
node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly) if (node.#index !== undefined) { throw PATH_ERROR } node.#index = isStatic ? -1 : index }
buildRegExpStr(): string { const childKeys = Object.keys(this.#children).sort(compareKey)
const strList = childKeys.map((k) => { const c = this.#children[k] return ( (typeof c.#varIndex === 'number' ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + c.buildRegExpStr() ) }) const strList = childKeys .map((k) => { const c = this.#children[k] const childStr = c.buildRegExpStr() // an empty childStr means a static-only branch, which is handled by staticMap return childStr === '' ? '' : (typeof c.#varIndex === 'number' ? `(${k})@${c.#varIndex}` : regExpMetaChars.has(k) ? `\\${k}` : k) + childStr }) .filter(Boolean)
if (typeof this.#index === 'number') { if (typeof this.#index === 'number' && this.#index !== -1) { strList.unshift(`#${this.#index}`) }
if (strList.length === 0) {9 unmodified linesmodified:src/router/reg-exp-router/router.test.ts+159 added-35 removed
1-import type { ParamStash } from '../../router'1+import type { ParamIndexMap, ParamStash } from '../../router'2 import { UnsupportedPathError } from '../../router'3 import { runTest } from '../common.case.test'4 import { RegExpRouter } from './router'5 32 unmodified lines38 })39 40 describe('UnsupportedPathError', () => {41 describe('Ambiguous', () => {42- const router = new RegExpRouter<string>()43-44- router.add('GET', '/:user/entries', 'get user entries')45- router.add('GET', '/entry/:name', 'get entry')46- router.add('POST', '/entry', 'create entry')47-48- it('GET /entry/entries', () => {42+ it('GET /entry/:name', () => {43+ const router = new RegExpRouter<string>()44+ router.add('GET', '/:user/entries', 'get user entries')45 expect(() => {50- router.match('GET', '/entry/entries')46+ router.add('GET', '/entry/:name', 'get entry')47 }).toThrowError(UnsupportedPathError)48 })49 })50 51 describe('Multiple handlers with different label', () => {56- const router = new RegExpRouter<string>()57-58- router.add('GET', '/:type/:id', ':type')59- router.add('GET', '/:class/:id', ':class')60- router.add('GET', '/:model/:id', ':model')61-62- it('GET /entry/123', () => {52+ it('GET /:class/:id', () => {53+ const router = new RegExpRouter<string>()54+ router.add('GET', '/:type/:id', ':type')55 expect(() => {64- router.match('GET', '/entry/123')56+ router.add('GET', '/:class/:id', ':class')57 }).toThrowError(UnsupportedPathError)58 })59 })60 61 it('parent', () => {62 const router = new RegExpRouter<string>()63 router.add('GET', '/:id/:action', 'foo')72- router.add('GET', '/posts/:id', 'bar')64 expect(() => {74- router.match('GET', '/')65+ router.add('GET', '/posts/:id', 'bar')66 }).toThrowError(UnsupportedPathError)67 })68 69 it('child', () => {70 const router = new RegExpRouter<string>()71 router.add('GET', '/posts/:id', 'foo')81- router.add('GET', '/:id/:action', 'bar')82-72 expect(() => {84- router.match('GET', '/')73+ router.add('GET', '/:id/:action', 'bar')74 }).toThrowError(UnsupportedPathError)75 })76 77 describe('static and dynamic', () => {78 it('static first', () => {79 const router = new RegExpRouter<string>()80 router.add('GET', '/reg-exp/router', 'foo')92- router.add('GET', '/reg-exp/:id', 'bar')93-81 expect(() => {95- router.match('GET', '/')82+ router.add('GET', '/reg-exp/:id', 'bar')83 }).toThrowError(UnsupportedPathError)84 })85 86 it('long label', () => {87 const router = new RegExpRouter<string>()88 router.add('GET', '/reg-exp/router', 'foo')102- router.add('GET', '/reg-exp/:service', 'bar')103-89 expect(() => {105- router.match('GET', '/')90+ router.add('GET', '/reg-exp/:service', 'bar')91 }).toThrowError(UnsupportedPathError)92 })93 94 it('dynamic first', () => {95 const router = new RegExpRouter<string>()96 router.add('GET', '/reg-exp/:id', 'bar')112- router.add('GET', '/reg-exp/router', 'foo')113-97 expect(() => {115- router.match('GET', '/')98+ router.add('GET', '/reg-exp/router', 'foo')99 }).toThrowError(UnsupportedPathError)100 })101 })102 103 it('different regular expression', () => {104 const router = new RegExpRouter<string>()105 router.add('GET', '/:id/:action{create|update}', 'foo')123- router.add('GET', '/:id/:action{delete}', 'bar')106 expect(() => {125- router.match('GET', '/')107+ router.add('GET', '/:id/:action{delete}', 'bar')108 }).toThrowError(UnsupportedPathError)109 })110 111+ it('ALL route added after a specific-method route', () => {112+ const router = new RegExpRouter<string>()113+ router.add('GET', '/foo/:a', 'foo')114+ expect(() => {115+ router.add('ALL', '/foo/:b', 'bar')116+ }).toThrowError(UnsupportedPathError)117+ })118+119+ it('specific-method route added after an ALL route', () => {120+ const router = new RegExpRouter<string>()121+ router.add('ALL', '/reg-exp/router', 'foo')122+123+ expect(() => {124+ router.add('GET', '/reg-exp/:id', 'bar')125+ }).toThrowError(UnsupportedPathError)126+ })127+128+ it('different methods do not conflict', () => {129+ const router = new RegExpRouter<string>()130+ router.add('GET', '/reg-exp/router', 'foo')131+ router.add('POST', '/reg-exp/:id', 'bar')132+133+ expect(router.match('GET', '/reg-exp/router')[0][0][0]).toBe('foo')134+ expect(router.match('POST', '/reg-exp/router')[0][0][0]).toBe('bar')135+ })136+137 describe('Capture Group', () => {138 describe('Complex capturing group', () => {139 it('GET request', () => {140 const router = new RegExpRouter<string>()133- router.add('GET', '/foo/:capture{ba(r|z)}', 'ok')141 expect(() => {135- router.match('GET', '/foo/bar')142+ router.add('GET', '/foo/:capture{ba(r|z)}', 'ok')143 }).toThrowError(UnsupportedPathError)144 })145 })146 })147 })148+149+ describe('Wildcard after label', () => {150+ it('Should be able to add a tail wildcard after a label', () => {151+ const router = new RegExpRouter<string>()152+ router.add('GET', '/api/:x', 'label')153+ router.add('GET', '/api/*', 'wildcard')154+155+ const [res] = router.match('GET', '/api/foo')156+ expect(res.length).toBe(2)157+ expect(res[0][0]).toBe('label')158+ expect(res[1][0]).toBe('wildcard')159+ })160+161+ it('Should prioritize the only wildcard over the tail wildcard regardless of the order', () => {162+ for (const paths of [163+ ['/a*', '/a/*'],164+ ['/a/*', '/a*'],165+ ]) {166+ const router = new RegExpRouter<string>()167+ for (const path of paths) {168+ router.add('GET', path, path)169+ }170+ const [res] = router.match('GET', '/a')171+ expect(res[0][0]).toBe('/a*')172+ }173+ })174+ })175+176+ describe('Single character regexp pattern', () => {177+ it('Should capture a param even if a static path created the node first', () => {178+ const router = new RegExpRouter<string>()179+ router.add('GET', '/a/c', 'static')180+ router.add('GET', '/:x{a}/b', 'pattern')181+182+ const [res, stash] = router.match('GET', '/a/b')183+ expect(res.length).toBe(1)184+ expect(res[0][0]).toBe('pattern')185+ expect((stash as ParamStash)[(res[0][1] as ParamIndexMap)['x']]).toBe('a')186+ })187+188+ it('Should throw an error when a pattern terminal conflicts with a static terminal', () => {189+ for (const paths of [190+ ['/a', '/:x{a}'],191+ ['/:x{a}', '/a'],192+ ]) {193+ const router = new RegExpRouter<string>()194+ router.add('GET', paths[0], paths[0])195+ expect(() => {196+ router.add('GET', paths[1], paths[1])197+ }).toThrowError(UnsupportedPathError)198+ }199+ })200+201+ it('Should coexist with static paths regardless of the order', () => {202+ for (const paths of [203+ ['/foo/bar', '/:y{b}'],204+ ['/:y{b}', '/foo/bar'],205+ ]) {206+ const router = new RegExpRouter<string>()207+ for (const path of paths) {208+ router.add('GET', path, path)209+ }210+ expect(router.match('GET', '/foo/bar')[0][0][0]).toBe('/foo/bar')211+ expect(router.match('GET', '/b')[0][0][0]).toBe('/:y{b}')212+ }213+ })214+215+ it('Should coexist with dynamic paths regardless of the order', () => {216+ for (const paths of [217+ ['/foo/:p', '/:x{a}'],218+ ['/:x{a}', '/foo/:p'],219+ ]) {220+ const router = new RegExpRouter<string>()221+ for (const path of paths) {222+ router.add('GET', path, path)223+ }224+ expect(router.match('GET', '/a')[0][0][0]).toBe('/:x{a}')225+ expect(router.match('GET', '/foo/v')[0][0][0]).toBe('/foo/:p')226+ }227+ })228+229+ it('Should throw an error for a single meta character pattern', () => {230+ const router = new RegExpRouter<string>()231+ expect(() => {232+ router.add('GET', '/:x{.}', 'meta')233+ }).toThrowError(UnsupportedPathError)234+ })235+ })236+237+ describe('Capture a param of a label node created by a middle wildcard', () => {238+ it('Should capture the param', () => {239+ const router = new RegExpRouter<string>()240+ router.add('GET', '/w/*/x', 'wildcard')241+ router.add('GET', '/w/:id/y', 'label')242+243+ const [res, stash] = router.match('GET', '/w/123/y')244+ expect(res.length).toBe(1)245+ expect(res[0][0]).toBe('label')246+ expect((stash as ParamStash)[(res[0][1] as ParamIndexMap)['id']]).toBe('123')247+ })248+ })249+250+ describe('Static path including a colon in the middle', () => {251+ it('Should be treated as a static path', () => {252+ for (const paths of [253+ ['/v1/name:activate', '/v1/name2'],254+ ['/v1/name2', '/v1/name:activate'],255+ ]) {256+ const router = new RegExpRouter<string>()257+ for (const path of paths) {258+ router.add('GET', path, path)259+ }260+ expect(router.match('GET', '/v1/name:activate')[0][0][0]).toBe('/v1/name:activate')261+ expect(router.match('GET', '/v1/name2')[0][0][0]).toBe('/v1/name2')262+ }263+ })264+ })265 })modified:src/router/reg-exp-router/router.ts+71 added-112 removed
6 unmodified lines7 import { checkOptionalParameter } from '../../utils/url'8 import type { HandlerData, StaticMap, Matcher, MatcherMap } from './matcher'9 import { match, emptyParam } from './matcher'10 import { PATH_ERROR } from './node'11-import type { ParamAssocArray } from './node'11 import { Trie } from './trie'12 13 type HandlerWithMetadata<T> = [T, number] // [handler, paramCount]14 16-// eslint-disable-next-line @typescript-eslint/no-explicit-any17-const nullMatcher: Matcher<any> = [/^$/, [], Object.create(null)]18-15 let wildcardRegExpCache: Record<string, RegExp> = Object.create(null)16 function buildWildcardRegExp(path: string): RegExp {17 return (wildcardRegExpCache[path] ??= new RegExp(18 path === '*'7 unmodified lines26 function clearWildcardRegExpCache() {27 wildcardRegExpCache = Object.create(null)28 }29 34-function buildMatcherFromPreprocessedRoutes<T>(35- routes: [string, HandlerWithMetadata<T>[]][]36-): Matcher<T> {37- const trie = new Trie()38- const handlerData: HandlerData<T>[] = []39- if (routes.length === 0) {40- return nullMatcher41- }42-43- const routesWithStaticPathFlag = routes44- .map(45- (route) => [!/\*|\/:/.test(route[0]), ...route] as [boolean, string, HandlerWithMetadata<T>[]]46- )47- .sort(([isStaticA, pathA], [isStaticB, pathB]) =>48- isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length49- )50-51- const staticMap: StaticMap<T> = Object.create(null)52- for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {53- const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i]54- if (pathErrorCheckOnly) {55- staticMap[path] = [handlers.map(([h]) => [h, Object.create(null)]), emptyParam]56- } else {57- j++58- }59-60- let paramAssoc: ParamAssocArray61- try {62- paramAssoc = trie.insert(path, j, pathErrorCheckOnly)63- } catch (e) {64- throw e === PATH_ERROR ? new UnsupportedPathError(path) : e65- }66-67- if (pathErrorCheckOnly) {68- continue69- }70-71- handlerData[j] = handlers.map(([h, paramCount]) => {72- const paramIndexMap: ParamIndexMap = Object.create(null)73- paramCount -= 174- for (; paramCount >= 0; paramCount--) {75- const [key, value] = paramAssoc[paramCount]76- paramIndexMap[key] = value77- }78- return [h, paramIndexMap]79- })80- }81-82- const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp()83- for (let i = 0, len = handlerData.length; i < len; i++) {84- for (let j = 0, len = handlerData[i].length; j < len; j++) {85- const map = handlerData[i][j]?.[1]86- if (!map) {87- continue88- }89- const keys = Object.keys(map)90- for (let k = 0, len = keys.length; k < len; k++) {91- map[keys[k]] = paramReplacementMap[map[keys[k]]]92- }93- }94- }95-96- const handlerMap: HandlerData<T>[] = []97- // using `in` because indexReplacementMap is a sparse array98- for (const i in indexReplacementMap) {99- handlerMap[i] = handlerData[indexReplacementMap[i]]100- }101-102- return [regexp, handlerMap, staticMap] as Matcher<T>103-}104-30 function findMiddleware<T>(31 middleware: Record<string, T[]> | undefined,32 path: string33 ): T[] | undefined {13 unmodified lines47 export class RegExpRouter<T> implements Router<T> {48 name: string = 'RegExpRouter'49 #middleware?: Record<string, Record<string, HandlerWithMetadata<T>[]>>50 #routes?: Record<string, Record<string, HandlerWithMetadata<T>[]>>51+ #tries?: Record<string, Trie>52 53 constructor() {54 this.#middleware = { [METHOD_NAME_ALL]: Object.create(null) }55 this.#routes = { [METHOD_NAME_ALL]: Object.create(null) }56+ this.#tries = { [METHOD_NAME_ALL]: new Trie() }57 }58 59+ #insertPath(method: string, path: string) {60+ try {61+ this.#tries![method].insert(path, !/\*|\/:/.test(path))62+ } catch (e) {63+ throw e === PATH_ERROR ? new UnsupportedPathError(path) : e64+ }65+ }66+67 add(method: string, path: string, handler: T) {68 const middleware = this.#middleware69 const routes = this.#routes70 1 unmodified line72 throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT)73 }74 75 if (!middleware[method]) {76+ this.#tries![method] = new Trie()77 ;[middleware, routes].forEach((handlerMap) => {78 handlerMap[method] = Object.create(null)79 Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {80 handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]]81+ this.#insertPath(method, p)82 })83 })84 }85 4 unmodified lines90 const paramCount = (path.match(/\/:/g) || []).length91 92 if (/\*$/.test(path)) {93 const re = buildWildcardRegExp(path)157- if (method === METHOD_NAME_ALL) {158- Object.keys(middleware).forEach((m) => {159- middleware[m][path] ||=94+ Object.keys(middleware).forEach((m) => {95+ if ((method === METHOD_NAME_ALL || method === m) && !middleware[m][path]) {96+ this.#insertPath(m, path)97+ middleware[m][path] =98 findMiddleware(middleware[m], path) ||99 findMiddleware(middleware[METHOD_NAME_ALL], path) ||100 []163- })164- } else {165- middleware[method][path] ||=166- findMiddleware(middleware[method], path) ||167- findMiddleware(middleware[METHOD_NAME_ALL], path) ||168- []169- }101+ }102+ })103 Object.keys(middleware).forEach((m) => {104 if (method === METHOD_NAME_ALL || method === m) {105 Object.keys(middleware[m]).forEach((p) => {106 re.test(p) && middleware[m][p].push([handler, paramCount])17 unmodified lines124 const path = paths[i]125 126 Object.keys(routes).forEach((m) => {127 if (method === METHOD_NAME_ALL || method === m) {128+ if (!routes[m][path]) {129+ this.#insertPath(m, path)195- routes[m][path] ||= [196- ...(findMiddleware(middleware[m], path) ||197- findMiddleware(middleware[METHOD_NAME_ALL], path) ||198- []),199- ]130+ routes[m][path] = [131+ ...(findMiddleware(middleware[m], path) ||132+ findMiddleware(middleware[METHOD_NAME_ALL], path) ||133+ []),134+ ]135+ }136 routes[m][path].push([handler, paramCount - len + i + 1])137 }138 })139 }10 unmodified lines150 matchers[method] ||= this.#buildMatcher(method)151 })152 153 // Release cache218- this.#middleware = this.#routes = undefined154+ this.#middleware = this.#routes = this.#tries = undefined155 clearWildcardRegExpCache()156 157 return matchers158 }159 224- #buildMatcher(method: string): Matcher<T> | null {225- const routes: [string, HandlerWithMetadata<T>[]][] = []160+ #buildMatcher(method: string): Matcher<T> {161+ const middleware = this.#middleware![method]162+ const routes = this.#routes![method]163 227- let hasOwnRoute = method === METHOD_NAME_ALL164+ const trie = this.#tries![method]165+ const staticMap: StaticMap<T> = Object.create(null)166+ const handlerData: HandlerData<T>[] = []167 229- ;[this.#middleware!, this.#routes!].forEach((r) => {230- const ownRoute = r[method]231- ? Object.keys(r[method]).map((path) => [path, r[method][path]])232- : []233- if (ownRoute.length !== 0) {234- hasOwnRoute ||= true235- routes.push(...(ownRoute as [string, HandlerWithMetadata<T>[]][]))236- } else if (method !== METHOD_NAME_ALL) {237- routes.push(238- ...(Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]]) as [239- string,240- HandlerWithMetadata<T>[],241- ][])242- )168+ ;[middleware, routes].forEach((r) => {169+ for (const path in r) {170+ const handlers = r[path]171+ const pathData = trie.paths[path]172+ if (!pathData) {173+ staticMap[path] = [handlers.map(([h]) => [h, Object.create(null)]), emptyParam]174+ continue175+ }176+ const paramAssoc = pathData[1]177+ handlerData[pathData[0]] = handlers.map(([h, paramCount]) => {178+ const paramIndexMap: ParamIndexMap = Object.create(null)179+ paramCount -= 1180+ for (; paramCount >= 0; paramCount--) {181+ const [key, value] = paramAssoc[paramCount]182+ paramIndexMap[key] = value183+ }184+ return [h, paramIndexMap]185+ })186 }187 })188 246- if (!hasOwnRoute) {247- return null248- } else {249- return buildMatcherFromPreprocessedRoutes(routes)189+ const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp()190+ for (let i = 0, len = handlerData.length; i < len; i++) {191+ for (let j = 0, len = handlerData[i].length; j < len; j++) {192+ const map = handlerData[i][j]?.[1]193+ if (!map) {194+ continue195+ }196+ const keys = Object.keys(map)197+ for (let k = 0, len = keys.length; k < len; k++) {198+ map[keys[k]] = paramReplacementMap[map[keys[k]]]199+ }200+ }201 }202+203+ const handlerMap: HandlerData<T>[] = []204+ // using `in` because indexReplacementMap is a sparse array205+ for (const i in indexReplacementMap) {206+ handlerMap[i] = handlerData[indexReplacementMap[i]]207+ }208+209+ return [regexp, handlerMap, staticMap] as Matcher<T>210 }211 }modified:src/router/reg-exp-router/trie.ts+15 added-6 removed
4 unmodified lines5 6 export class Trie {7 #context: Context = { varIndex: 0 }8 #root: Node = new Node()9+ #index: number = 010+ // dynamic path -> [handler index, param assoc]; static paths are not registered11+ paths: Record<string, [number, ParamAssocArray]> = Object.create(null)12 10- insert(path: string, index: number, pathErrorCheckOnly: boolean): ParamAssocArray {13+ insert(path: string, isStatic: boolean): void {14+ if (isStatic) {15+ // a static path has no pattern; every character is a literal token16+ this.#root.insert(path.split(''), 0, [], this.#context, true)17+ return18+ }19+20 const paramAssoc: ParamAssocArray = []21 22 const groups: [string, string][] = [] // [mark, original string]23+ let markedPath = path24 for (let i = 0; ; ) {25 let replaced = false16- path = path.replace(/\{[^}]+\}/g, (m) => {26+ markedPath = markedPath.replace(/\{[^}]+\}/g, (m) => {27 const mark = `@\\${i}`28 groups[i] = [mark, m]29 i++30 replaced = true8 unmodified lines39 * - pattern (:label, :label{0-9]+}, ...)40 * - /* wildcard41 * - character42 */33- const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || []43+ const tokens = markedPath.match(/(?::[^\/]+)|(?:\/\*$)|./g) || []44 for (let i = groups.length - 1; i >= 0; i--) {45 const [mark] = groups[i]46 for (let j = tokens.length - 1; j >= 0; j--) {47 if (tokens[j].indexOf(mark) !== -1) {2 unmodified lines50 }51 }52 }53 44- this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly)45-46- return paramAssoc54+ this.#root.insert(tokens, this.#index, paramAssoc, this.#context, false)55+ this.paths[path] = [this.#index++, paramAssoc]56 }57 58 buildRegExp(): [RegExp, ReplacementMap, ReplacementMap] {59 let regexp = this.#root.buildRegExpStr()24 unmodified lines