fix(trie-router): match suffix wildcard routes (#5236)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* fix(trie-router): match suffix wildcard routes * fix(trie-router): register suffix patterns on existing nodes * refactor(trie-router): reduce bundle without slowing registration * refactor(trie-router): trade registration speed for bundle size
authored by Taku Amano · committed by GitHub · parent ef0739d · Browse files · 4 files·+91 added−99 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+91 added−99 removed
- tests:+41 added−10 removed
- other:+50 added−89 removed
Provenance
- Commit
63bbcf5- Tree
8506b3a- Author
Taku Amano <taku@taaas.jp>- Committer
GitHub <noreply@github.com>- Parent
ef0739d
4 files changed+91 added−99 removed
modified:src/router/trie-router/node.test.ts+27 added-10 removed
35 unmodified lines36 expect(node.search('get', '/hello/__proto__')[0].length).toBe(1)37 })38 })39 40+describe('Get with a suffix wildcard', () => {41+ const node = new Node()42+ node.insert('get', '/assets*', 'assets')43+44+ it.each(['/assets', '/assets-v2', '/assets/app.js'])('matches %s', (path) => {45+ expect(node.search('get', path)[0]).toEqual([['assets', {}]])46+ })47+48+ it('does not match a shorter prefix', () => {49+ expect(node.search('get', '/asset')[0]).toEqual([])50+ })51+52+ it('treats regular expression characters in the prefix literally', () => {53+ const node = new Node()54+ node.insert('get', '/file.+*', 'file')55+ expect(node.search('get', '/file.+js')[0]).toEqual([['file', {}]])56+ expect(node.search('get', '/fileZZjs')[0]).toEqual([])57+ })58+59+ it('registers the pattern when its child already exists', () => {60+ const node = new Node()61+ node.insert('get', '/assets*/x', 'literal')62+ node.insert('get', '/assets*', 'assets')63+ expect(node.search('get', '/assets/app.js')[0]).toEqual([['assets', {}]])64+ })65+})66+67 describe('Basic Usage', () => {68 const node = new Node()69 node.insert('get', '/hello', 'get hello')70 node.insert('post', '/hello', 'post hello')795 unmodified lines866 }867 })868 })869 })843-844-describe('Node with initial method and handler', () => {845- it('should create a node with method and handler via constructor', () => {846- const node = new Node('get', 'initial handler')847- node.insert('get', '/hello', 'hello handler')848- const [res] = node.search('get', '/hello')849- expect(res.length).toBe(1)850- expect(res[0][0]).toEqual('hello handler')851- })852-})modified:src/router/trie-router/node.ts+47 added-76 removed
12 unmodified lines13 params: Record<string, string>14 }15 16 const emptyParams = Object.create(null)17+let order = 018 18-const hasChildren = (children: Record<string, unknown>): boolean => {19- for (const _ in children) {20- return true21- }22- return false23-}24-19 export class Node<T> {26- #methods: Record<string, HandlerSet<T>>[]20+ #methods: Record<string, HandlerSet<T>>[] = []21 28- #children: Record<string, Node<T>>29- #patterns: Pattern[]30- #order: number = 022+ #children: Record<string, Node<T>> = Object.create(null)23+ #patterns: Node<T>[] = []24+ #pattern?: Pattern | string25 #params: Record<string, string> = emptyParams26 33- constructor(method?: string, handler?: T, children?: Record<string, Node<T>>) {34- this.#children = children || Object.create(null)35- this.#methods = []36- if (method && handler) {37- const m: Record<string, HandlerSet<T>> = Object.create(null)38- m[method] = { handler, possibleKeys: [], score: 0 }39- this.#methods = [m]40- }41- this.#patterns = []42- }43-44- insert(method: string, path: string, handler: T): Node<T> {27+ insert(method: string, path: string, handler: T): void {45- this.#order = ++this.#order46-28 // eslint-disable-next-line @typescript-eslint/no-this-alias29 let curNode: Node<T> = this30 const parts = splitRoutingPath(path)31 51- const possibleKeys: string[] = []32+ const possibleKeys = new Set<string>()33 53- for (let i = 0, len = parts.length; i < len; i++) {54- const p: string = parts[i]55- const nextP = parts[i + 1]56- const pattern = getPattern(p, nextP)57- const key = Array.isArray(pattern) ? pattern[0] : p34+ let i = 035+ for (const p of parts) {36+ const nextP = parts[++i]37+ const pattern =38+ getPattern(p, nextP) ||39+ (nextP === undefined && p && p.indexOf('*') === p.length - 1 ? p : null)40+ const isParam = Array.isArray(pattern)41+ const key = isParam ? pattern[0] : pattern || p42 59- if (key in curNode.#children) {60- curNode = curNode.#children[key]61- if (pattern) {62- possibleKeys.push(pattern[1])63- }64- continue43+ const child = (curNode.#children[key] ||= new Node())44+ if (pattern && !child.#pattern) {45+ child.#pattern = pattern46+ curNode.#patterns.push(child)47 }66-67- curNode.#children[key] = new Node()68-69- if (pattern) {70- curNode.#patterns.push(pattern)71- possibleKeys.push(pattern[1])48+ curNode = child49+ if (isParam) {50+ possibleKeys.add(pattern[1])51 }73- curNode = curNode.#children[key]52 }53 54 curNode.#methods.push({55 [method]: {56 handler,79- possibleKeys: possibleKeys.filter((v, i, a) => a.indexOf(v) === i),80- score: this.#order,57+ possibleKeys: [...possibleKeys],58+ score: ++order,59 },60 })83-84- return curNode61 }62 63 #pushHandlerSets(64 handlerSets: HandlerParamsSet<T>[],4 unmodified lines69 ): void {70 for (let i = 0, len = node.#methods.length; i < len; i++) {71 const m = node.#methods[i]72 const handlerSet = (m[method] || m[METHOD_NAME_ALL]) as HandlerParamsSet<T>97- const processedSet: Record<number, boolean> = {}98- if (handlerSet !== undefined) {73+ if (handlerSet) {74 handlerSet.params = Object.create(null)75 handlerSets.push(handlerSet)101- if (nodeParams !== emptyParams || (params && params !== emptyParams)) {102- for (let i = 0, len = handlerSet.possibleKeys.length; i < len; i++) {103- const key = handlerSet.possibleKeys[i]104- const processed = processedSet[handlerSet.score]105- handlerSet.params[key] =106- params?.[key] && !processed ? params[key] : (nodeParams[key] ?? params?.[key])107- processedSet[handlerSet.score] = true108- }76+ for (let i = 0, len = handlerSet.possibleKeys.length; i < len; i++) {77+ const key = handlerSet.possibleKeys[i]78+ handlerSet.params[key] =79+ params?.[key] && !i ? params[key] : (nodeParams[key] ?? params?.[key])80 }81 }82 }83 }32 unmodified lines116 tempNodes.push(nextNode)117 }118 }119 149- for (let k = 0, len3 = node.#patterns.length; k < len3; k++) {150- const pattern = node.#patterns[k]120+ for (const child of node.#patterns) {121+ const pattern = child.#pattern!122 const params = node.#params === emptyParams ? {} : { ...node.#params }123 124 // Wildcard125 // '/hello/*/foo' => match /hello/bar/foo155- if (pattern === '*') {156- const astNode = node.#children['*']157- if (astNode) {158- this.#pushHandlerSets(handlerSets, astNode, method, node.#params)159- astNode.#params = params160- tempNodes.push(astNode)126+ if (typeof pattern === 'string') {127+ if (pattern === '*' || part.startsWith(pattern.slice(0, -1))) {128+ this.#pushHandlerSets(handlerSets, child, method, node.#params)129+ if (pattern === '*') {130+ child.#params = params131+ tempNodes.push(child)132+ }133 }134 continue135 }136 165- const [key, name, matcher] = pattern137+ const [, name, matcher] = pattern138 167- if (!part && !(matcher instanceof RegExp)) {139+ if (!part && matcher === true) {140 continue141 }142 171- const child = node.#children[key]172-143 // `/js/:filename{[a-z]+.js}` => match /js/chunk/123.js174- if (matcher instanceof RegExp) {175- if (partOffsets === null) {176- partOffsets = new Array(len)144+ if (matcher !== true) {145+ if (!partOffsets) {146+ partOffsets = []147 let offset = path[0] === '/' ? 1 : 0148 for (let p = 0; p < len; p++) {149 partOffsets[p] = offset150 offset += parts[p].length + 1151 }152 }183- const restPathString = path.substring(partOffsets[i])153+ const restPathString = path.slice(partOffsets[i])154 155 const m = matcher.exec(restPathString)156 if (m) {157 params[name] = m[0]9 unmodified lines167 params168 )169 }170 201- if (hasChildren(child.#children)) {171+ for (const _ in child.#children) {172 child.#params = params173 const componentCount = m[0].match(/\//g)?.length ?? 0174 const targetCurNodes = (curNodesQueue[componentCount] ||= [])175 targetCurNodes.push(child)176+ break177 }178 179 continue180 }23 unmodified lines204 const shifted = curNodesQueue.shift()205 curNodes = shifted ? tempNodes.concat(shifted) : tempNodes206 }207 237- if (handlerSets.length > 1) {208+ if (handlerSets[1]) {209 handlerSets.sort((a, b) => {210 return a.score - b.score211 })212 }4 unmodified linesmodified:src/router/trie-router/router.ts+3 added-13 removed
2 unmodified lines3456778910111291415161710111819122122131415162 unmodified lines2 unmodified linesimport { Node } from './node'
export class TrieRouter<T> implements Router<T> { name: string = 'TrieRouter' #node: Node<T> #node: Node<T> = new Node()
constructor() { this.#node = new Node() }
add(method: string, path: string, handler: T) { const results = checkOptionalParameter(path) if (results) { for (let i = 0, len = results.length; i < len; i++) { this.#node.insert(method, results[i], handler) for (const result of checkOptionalParameter(path) || [path]) { this.#node.insert(method, result, handler) } return }
this.#node.insert(method, path, handler) }
match(method: string, path: string): Result<T> { return this.#node.search(method, path)2 unmodified linesmodified:src/hono.test.ts+14 added
471 unmodified lines472 expect(res.status).toBe(200)473 expect(await res.text()).toBe('get /add-path-after-route-call')474 })475 476+ it('Should match a suffix wildcard after falling back to TrieRouter', async () => {477+ const app = new Hono()478+ const sub = new Hono()479+ sub.post('/items', (c) => c.text('items'))480+ sub.post('/:slug', (c) => c.text('slug'))481+ app.route('/api', sub)482+ app.get('/assets*', (c) => c.text('asset'))483+484+ const res = await app.request('http://localhost/assets/app.js')485+ expect(res.status).toBe(200)486+ expect(await res.text()).toBe('asset')487+ expect(app.router.name).toBe('SmartRouter + TrieRouter')488+ })489+490 it('Nested route - subApp with basePath', async () => {491 const app = new Hono()492 const book = new Hono().basePath('/book')493 book.get('/', (c) => c.text('get /book'))3321 unmodified lines