fix(reg-exp-router): associate wildcard middleware with matching routes (#5266)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* fix(reg-exp-router): associate suffix wildcard routes * fix(reg-exp-router): preserve wildcard parameter names * fix(reg-exp-router): associate patterned wildcard routes * perf(reg-exp-router): reduce minified bundle size * fix(reg-exp-router): associate complex wildcard patterns * perf(reg-exp-router): compact route registration
authored by Taku Amano · committed by GitHub · parent 48e360f · Browse files · 4 files·+175 added−101 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+175 added−101 removed
- tests:+112 added−0 removed
- other:+63 added−101 removed
Provenance
- Commit
a10592f- Tree
ef2ec61- Author
Taku Amano <taku@taaas.jp>- Committer
GitHub <noreply@github.com>- Parent
48e360f
4 files changed+175 added−101 removed
modified:src/router/linear-router/router.test.ts+9 added
10 unmodified lines111213141516171819202122232425262753 unmodified lines10 unmodified lines 'Multi match > `params` per a handler > GET /entry/123/show', 'Capture regex pattern has trailing wildcard > GET /foo/bar/file.html', 'Capture regex param with trailing wildcard on empty remainder > GET /123', 'Capture regex param with trailing wildcard and sibling route > GET /regex-abc/123/ghi', 'Trailing wildcard after a label > GET /abc', 'Trailing wildcard after a label > GET /abc/sub', 'Trailing wildcard after a pattern label > GET /abc', 'Trailing wildcard after a pattern label > GET /reverse/abc in reverse registration order', 'Trailing wildcard after a pattern label > POST /all/abc with ALL middleware', 'Trailing wildcard after a pattern label > GET /posts/2024/comments with nested braces', 'Trailing wildcard after a pattern label > GET /files/foo/detail with regexp meta characters', 'Trailing wildcard after a pattern label > GET /user/123/profile with the default pattern', 'Trailing wildcard after a pattern label > GET /user/123/profile with the default pattern in reverse registration order', 'Complex > Parameter with {.*} regexp', ], }, {53 unmodified linesmodified:src/router/reg-exp-router/node.ts+3 added-3 removed
1-const LABEL_REG_EXP_STR = '[^/]+'2-const ONLY_WILDCARD_REG_EXP_STR = '.*'3-const TAIL_WILDCARD_REG_EXP_STR = '(?:|/.*)'1+export const LABEL_REG_EXP_STR = '[^/]+'2+export const ONLY_WILDCARD_REG_EXP_STR = '.*'3+export const TAIL_WILDCARD_REG_EXP_STR = '(?:|/.*)'4 export const PATH_ERROR = Symbol()5 6 export type ParamAssocArray = [string, number][]7 export interface Context {161 unmodified linesmodified:src/router/reg-exp-router/router.ts+60 added-98 removed
1-import type { ParamIndexMap, Router } from '../../router'1+import type { Router } from '../../router'2 import {3 MESSAGE_MATCHER_IS_ALREADY_BUILT,4 METHOD_NAME_ALL,5 UnsupportedPathError,6 } from '../../router'7 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'10+import {11+ LABEL_REG_EXP_STR,12+ ONLY_WILDCARD_REG_EXP_STR,13+ PATH_ERROR,14+ TAIL_WILDCARD_REG_EXP_STR,15+} from './node'16 import { Trie } from './trie'17 13-type HandlerWithMetadata<T> = [T, number] // [handler, paramCount]18+type HandlerWithMetadata<T> = [T, string] // [handler, path]19 20 let wildcardRegExpCache: Record<string, RegExp> = Object.create(null)21 function buildWildcardRegExp(path: string): RegExp {22 return (wildcardRegExpCache[path] ??= new RegExp(18- path === '*'19- ? ''20- : `^${path.replace(/\/\*$|([.\\+*[^\]$()])/g, (_, metaChar) =>21- metaChar ? `\\${metaChar}` : '(?:|/.*)'22- )}$`23+ `^${path.replace(24+ /\/:[^/{}]+(?:\{\[\^\/]\+})?(?=[/{]|$)|\/?\*$|([.\\+*[^\]$()?{}|])/g,25+ (match, metaChar) =>26+ metaChar27+ ? `\\${metaChar}`28+ : match === '/*'29+ ? TAIL_WILDCARD_REG_EXP_STR30+ : match === '*'31+ ? ONLY_WILDCARD_REG_EXP_STR32+ : `/:${LABEL_REG_EXP_STR}`33+ )}$`34 ))35 }36 26-function clearWildcardRegExpCache() {27- wildcardRegExpCache = Object.create(null)28-}29-30-function findMiddleware<T>(31- middleware: Record<string, T[]> | undefined,32- path: string33-): T[] | undefined {34- if (!middleware) {35- return undefined36- }37-37+function findMiddleware<T>(middleware: Record<string, T[]>, path: string): T[] | undefined {38 for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {39 if (buildWildcardRegExp(k).test(path)) {40 return [...middleware[k]]41 }23 unmodified lines65 }66 67 add(method: string, path: string, handler: T) {68 const middleware = this.#middleware69- const routes = this.#routes69+ const routes = this.#routes!70 71- if (!middleware || !routes) {71+ if (!middleware) {72 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) => {77+ for (const handlerMap of [middleware, routes]) {78 handlerMap[method] = Object.create(null)79- Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {79+ for (const p in handlerMap[METHOD_NAME_ALL]) {80 handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]]81 this.#insertPath(method, p)82- })83- })82+ }83+ }84 }85 86 if (path === '/*') {87 path = '*'88 }89+ const methods = method === METHOD_NAME_ALL ? Object.keys(middleware) : [method]90 90- const paramCount = (path.match(/\/:/g) || []).length91-91 if (/\*$/.test(path)) {92 const re = buildWildcardRegExp(path)94- Object.keys(middleware).forEach((m) => {95- if ((method === METHOD_NAME_ALL || method === m) && !middleware[m][path]) {93+ for (const m of methods) {94+ if (!middleware[m][path]) {95 this.#insertPath(m, path)96 middleware[m][path] =97 findMiddleware(middleware[m], path) ||98 findMiddleware(middleware[METHOD_NAME_ALL], path) ||99 []100 }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])107- })101+ }102+ for (const handlerMap of [middleware, routes]) {103+ for (const m of methods) {104+ for (const p in handlerMap[m]) {105+ re.test(p) && handlerMap[m][p].push([handler, path])106+ }107 }109- })108+ }109 111- Object.keys(routes).forEach((m) => {112- if (method === METHOD_NAME_ALL || method === m) {113- Object.keys(routes[m]).forEach(114- (p) => re.test(p) && routes[m][p].push([handler, paramCount])115- )116- }117- })118-110 return111 }112 113 const paths = checkOptionalParameter(path) || [path]123- for (let i = 0, len = paths.length; i < len; i++) {124- 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)130- routes[m][path] = [131- ...(findMiddleware(middleware[m], path) ||132- findMiddleware(middleware[METHOD_NAME_ALL], path) ||133- []),114+ for (const path of paths) {115+ for (const m of methods) {116+ if (!routes[m][path]) {117+ this.#insertPath(m, path)118+ routes[m][path] =119+ findMiddleware(middleware[m], path) ||120+ findMiddleware(middleware[METHOD_NAME_ALL], path) ||121+ []134- ]135- }136- routes[m][path].push([handler, paramCount - len + i + 1])122 }138- })123+ routes[m][path].push([handler, path])124+ }125 }126 }127 128 match: typeof match<Router<T>, T> = match129 130 protected buildAllMatchers(): MatcherMap<T> {131 const matchers: MatcherMap<T> = Object.create(null)132 147- Object.keys(this.#routes!)148- .concat(Object.keys(this.#middleware!))149- .forEach((method) => {150- matchers[method] ||= this.#buildMatcher(method)151- })133+ for (const method of Object.keys(this.#routes!)) {134+ matchers[method] = this.#buildMatcher(method)135+ }136 137 // Release cache138 this.#middleware = this.#routes = this.#tries = undefined155- clearWildcardRegExpCache()139+ wildcardRegExpCache = Object.create(null)140 141 return matchers142 }143 3 unmodified lines147 148 const trie = this.#tries![method]149 const staticMap: StaticMap<T> = Object.create(null)150 const handlerData: HandlerData<T>[] = []151+ const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp()152 168- ;[middleware, routes].forEach((r) => {153+ for (const r of [middleware, routes]) {154 for (const path in r) {155 const handlers = r[path]156 const pathData = trie.paths[path]157 if (!pathData) {158 staticMap[path] = [handlers.map(([h]) => [h, Object.create(null)]), emptyParam]159 continue160 }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- })161+ handlerData[pathData[0]] = handlers.map(([h, handlerPath]) => [162+ h,163+ trie.paths[handlerPath][1].reduceRight((map, [key], i) => {164+ map[key] = paramReplacementMap[pathData[1][i][1]]165+ return map166+ }, Object.create(null)),167+ ])168 }187- })188-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- }169 }170 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>171+ return [regexp, indexReplacementMap.map((i) => handlerData[i]), staticMap] as Matcher<T>172 }173 }modified:src/router/common.case.test.ts+103 added
395 unmodified lines396 it('GET /asset', async () => {397 const res = match('GET', '/asset')398 expect(res.length).toBe(0)399 })400+401+ it.each([402+ ['/assets*', '/assets/app.js'],403+ ['/assets/app.js', '/assets*'],404+ ])('associates %s before %s', async (first, second) => {405+ router.add('POST', first, first)406+ router.add('POST', second, second)407+ const res = match('POST', '/assets/app.js')408+ expect(res.map(({ handler }) => handler)).toEqual([first, second])409+ })410 })411 412 describe('Trailing wildcard', () => {413 beforeEach(() => {17 unmodified lines431 expect(res.length).toBe(0)432 })433 })434 435+ describe('Trailing wildcard after a label', () => {436+ beforeEach(() => {437+ router.add('GET', '/:name/*', 'middleware')438+ router.add('GET', '/:id', 'handler')439+ })440+441+ it('GET /abc', async () => {442+ const res = match('GET', '/abc')443+ expect(res.length).toBe(2)444+ expect(res[0]).toEqual({ handler: 'middleware', params: { name: 'abc' } })445+ expect(res[1]).toEqual({ handler: 'handler', params: { id: 'abc' } })446+ })447+448+ it('GET /abc/sub', async () => {449+ const res = match('GET', '/abc/sub')450+ expect(res).toEqual([{ handler: 'middleware', params: { name: 'abc' } }])451+ })452+ })453+454+ describe('Trailing wildcard after a pattern label', () => {455+ beforeEach(() => {456+ router.add('GET', '/:name{[a-z]+}/*', 'middleware')457+ router.add('GET', '/:id{[a-z]+}', 'handler')458+ })459+460+ it('GET /abc', async () => {461+ const res = match('GET', '/abc')462+ expect(res.length).toBe(2)463+ expect(res[0]).toEqual({ handler: 'middleware', params: { name: 'abc' } })464+ expect(res[1]).toEqual({ handler: 'handler', params: { id: 'abc' } })465+ })466+467+ it('GET /reverse/abc in reverse registration order', async () => {468+ router = newRouter()469+ router.add('GET', '/reverse/:id{[a-z]+}', 'handler')470+ router.add('GET', '/reverse/:name{[a-z]+}/*', 'middleware')471+ const res = match('GET', '/reverse/abc')472+ expect(res.map(({ handler }) => handler)).toEqual(['handler', 'middleware'])473+ })474+475+ it('POST /all/abc with ALL middleware', async () => {476+ router = newRouter()477+ router.add('ALL', '/all/:name{[a-z]+}/*', 'middleware')478+ router.add('POST', '/all/:id{[a-z]+}', 'handler')479+ const res = match('POST', '/all/abc')480+ expect(res.map(({ handler }) => handler)).toEqual(['middleware', 'handler'])481+ })482+483+ it('GET /posts/2024/comments with nested braces', async () => {484+ router = newRouter()485+ router.add('GET', '/posts/:year{[0-9]{4}}/*', 'middleware')486+ router.add('GET', '/posts/:yr{[0-9]{4}}/comments', 'handler')487+ const res = match('GET', '/posts/2024/comments')488+ expect(res).toEqual([489+ { handler: 'middleware', params: { year: '2024' } },490+ { handler: 'handler', params: { yr: '2024' } },491+ ])492+ })493+494+ it('GET /files/foo/detail with regexp meta characters', async () => {495+ router = newRouter()496+ router.add('GET', '/files/:kind{(?:foo|bar)}/*', 'middleware')497+ router.add('GET', '/files/:type{(?:foo|bar)}/detail', 'handler')498+ const res = match('GET', '/files/foo/detail')499+ expect(res).toEqual([500+ { handler: 'middleware', params: { kind: 'foo' } },501+ { handler: 'handler', params: { type: 'foo' } },502+ ])503+ })504+505+ it('GET /user/123/profile with the default pattern', async () => {506+ router = newRouter()507+ router.add('GET', '/user/:userId{[^/]+}/*', 'middleware')508+ router.add('GET', '/user/:id/profile', 'handler')509+ const res = match('GET', '/user/123/profile')510+ expect(res).toEqual([511+ { handler: 'middleware', params: { userId: '123' } },512+ { handler: 'handler', params: { id: '123' } },513+ ])514+ })515+516+ it('GET /user/123/profile with the default pattern in reverse registration order', async () => {517+ router = newRouter()518+ router.add('GET', '/user/:id/profile', 'handler')519+ router.add('GET', '/user/:userId{[^/]+}/*', 'middleware')520+ const res = match('GET', '/user/123/profile')521+ expect(res).toEqual([522+ { handler: 'handler', params: { id: '123' } },523+ { handler: 'middleware', params: { userId: '123' } },524+ ])525+ })526+ })527+528 describe('Trailing wildcard after a middle wildcard', () => {529 beforeEach(() => {530 router.add('GET', '/a/*/b/*', 'b')531 })570 unmodified lines