feat: Lightweight RegExpRouter reborn (#519)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Introduce RegExpLiteRouter. * Replace RegExpRouter with RegExpLiteRouter. * chore: denoify * Remove old RegExpRouter and rename RegExpLiteRouter to RegExpRouter. * chore: Update benchmarks/handle-event.
authored by Taku Amano · committed by GitHub · parent 46c6a8d · Browse files · 11 files·+338 added−937 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
11 files+338 added−937 removed
- tests:+36 added−88 removed
- other:+302 added−849 removed
Provenance
- Commit
d12a119- Tree
e0fd8fe- Author
Taku Amano <taku@taaas.jp>- Committer
GitHub <noreply@github.com>- Parent
46c6a8d
11 files changed+338 added−937 removed
modified:benchmarks/handle-event/index.js+8 added-1 removed
5 unmodified lines6789101112131413 unmodified lines28293031323334353682 unmodified lines1191201211221231241251261271286 unmodified lines13513613713813513914014114214314414514614714815 unmodified lines5 unmodified linesimport { Router as SunderRouter, Sunder } from 'sunder'import { Router as WorktopRouter } from 'worktop'import { Hono } from '../../dist/hono'import { RegExpRouter } from '../../dist/router/reg-exp-router'import { TrieRouter } from '../../dist/router/trie-router'
globalThis.Request = RequestglobalThis.Response = Response
13 unmodified lines return hono}
const hono = initHono(new Hono())const honoWithTrieRouter = initHono(new Hono({ router: new TrieRouter() }))const honoWithRegExpRouter = initHono(new Hono({ router: new RegExpRouter() }))
// itty-routerconst ittyRouter = IttyRouter()82 unmodified lines
const fn = async () => { let res = await hono.handleEvent(event) console.log(await res.text()) res = await honoWithTrieRouter.handleEvent(event) console.log(await res.text()) res = await honoWithRegExpRouter.handleEvent(event) console.log(await res.text()) res = await ittyRouter.handle(event.request) console.log(await res.text())6 unmodified lines
const suite = new Benchmark.Suite()
suite .add('hono - trie-router(default)', async () => { .add('hono - smart-router(default)', async () => { await hono.handleEvent(event) }) .add('hono - trie-router', async () => { await honoWithTrieRouter.handleEvent(event) }) .add('hono - regexp-router', async () => { await honoWithRegExpRouter.handleEvent(event) }) .add('itty-router', async () => {15 unmodified linesmodified:deno_dist/router/reg-exp-router/node.ts+29 added-15 removed
1 const LABEL_REG_EXP_STR = '[^/]+'2 const ONLY_WILDCARD_REG_EXP_STR = '.*'3 const TAIL_WILDCARD_REG_EXP_STR = '(?:|/.*)'4+export const PATH_ERROR = Symbol()5 6 export type ParamMap = Array<[string, number]>7 export interface Context {8 varIndex: number34 unmodified lines43 export class Node {44 index?: number45 varIndex?: number46 children: Record<string, Node> = {}46- reverse: boolean47 48- constructor({ reverse }: Partial<Node> = { reverse: false }) {49- this.reverse = reverse as boolean50- }51-52- newChildNode(): Node {53- return new Node({ reverse: this.reverse })54- }55-48 insert(tokens: readonly string[], index: number, paramMap: ParamMap, context: Context): void {49 if (tokens.length === 0) {50+ if (this.index !== undefined) {51+ throw PATH_ERROR52+ }53+54 this.index = index55 return56 }57 13 unmodified lines71 const regexpStr = pattern[2] || LABEL_REG_EXP_STR72 73 node = this.children[regexpStr]74 if (!node) {75+ if (76+ Object.keys(this.children).some(77+ (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR78+ )79+ ) {80+ throw PATH_ERROR81+ }79- node = this.children[regexpStr] = this.newChildNode()82+ node = this.children[regexpStr] = new Node()83 if (name !== '') {84 node.varIndex = context.varIndex++85 }86 }87 if (name !== '') {88+ if (paramMap.some((p) => p[0] === name)) {89+ throw new Error('Duplicate param name')90+ }91 paramMap.push([name, node.varIndex as number])92 }93 } else {88- node = this.children[token] ||= this.newChildNode()94+ node = this.children[token]95+ if (!node) {96+ if (97+ Object.keys(this.children).some(98+ (k) =>99+ k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR100+ )101+ ) {102+ throw PATH_ERROR103+ }104+ node = this.children[token] = new Node()105+ }106 }107 108 node.insert(restTokens, index, paramMap, context)109 }110 111 buildRegExpStr(): string {95- let childKeys = Object.keys(this.children).sort(compareKey)96- if (this.reverse) {97- childKeys = childKeys.reverse()98- }112+ const childKeys = Object.keys(this.children).sort(compareKey)113 114 const strList = childKeys.map((k) => {115 const c = this.children[k]116 return (typeof c.varIndex === 'number' ? `(${k})@${c.varIndex}` : k) + c.buildRegExpStr()16 unmodified linesmodified:deno_dist/router/reg-exp-router/router.ts+116 added-399 removed
1 /* eslint-disable @typescript-eslint/ban-ts-comment */2 import type { Router, Result } from '../../router.ts'3-import { METHOD_NAME_ALL, UnsupportedPathError } from '../../router.ts'3+import { METHOD_NAME_ALL, METHODS, UnsupportedPathError } from '../../router.ts'4+import { PATH_ERROR } from './node.ts'5 import type { ParamMap } from './trie.ts'6 import { Trie } from './trie.ts'7 7-interface Hint {8- components: string[]9- regExpComponents: Array<true | string>10- componentsLength: number11- endWithWildcard: boolean12- paramIndexList: number[]13- maybeHandler: boolean14- namedParams: [number, string, string][]15-}16-interface HandlerWithSortIndex<T> {17- handler: T18- index: number19-}20-interface Route<T> {21- method: string22- path: string23- hint: Hint24- handlers: HandlerWithSortIndex<T>[]25- middleware: HandlerWithSortIndex<T>[]26- paramAliasMap: Record<string, string[]>27-}8+const METHOD_NAMES = [METHOD_NAME_ALL, ...METHODS].map((method) => method.toUpperCase())9+10 type HandlerData<T> = [T[], ParamMap | null]11 type Matcher<T> = [RegExp, HandlerData<T>[]]30-type HandlerDataWithSortIndex<T> = [HandlerWithSortIndex<T>[], ParamMap | null]31-type MatcherWithSortIndex<T> = [RegExp, HandlerDataWithSortIndex<T>[]]32-type AnyMatcher<T> = Matcher<T> | MatcherWithSortIndex<T>12 34-type CompareResult =35- | 0 // different36- | 1 // included37- | 2 // ambiguous38-13 const emptyParam = {}14 const nullMatcher: Matcher<any> = [/^$/, []]15 42-function initHint(path: string): Hint {43- const components = path.match(/\/(?::\w+{[^}]+}|[^\/]*)/g) || []44- let componentsLength = components.length45-46- const paramIndexList: number[] = []47- const regExpComponents: Array<true | string> = []48- const namedParams: [number, string, string][] = []49- for (let i = 0, len = components.length; i < len; i++) {50- if (i === len - 1 && components[i] === '/*') {51- componentsLength--52- break53- }54-55- const m = components[i].match(/^\/:(\w+)({[^}]+})?/)56- if (m) {57- namedParams.push([i, m[1], m[2] || '[^/]+'])58- regExpComponents[i] = m[2] || true59- } else if (components[i] === '/*') {60- regExpComponents[i] = true61- } else {62- regExpComponents[i] = components[i]63- }64-65- if (/\/(?::|\*)/.test(components[i])) {66- paramIndexList.push(i)67- }68- }69-70- return {71- components,72- regExpComponents,73- componentsLength,74- endWithWildcard: path.endsWith('*'),75- paramIndexList,76- namedParams,77- maybeHandler: true,78- }16+function buildWildcardRegExp(path: string): RegExp {17+ return new RegExp(path === '*' ? '' : `^${path.replace(/\/\*/, '(?:|/.*)')}$`)18 }19 81-function compareRoute<T>(a: Route<T>, b: Route<T>): CompareResult {82- if (a.path === '*') {83- return 184- }85-86- let i = 087- const len = a.hint.regExpComponents.length88- for (; i < len; i++) {89- if (a.hint.regExpComponents[i] !== b.hint.regExpComponents[i]) {90- if (a.hint.regExpComponents[i] === true) {91- break92- }93-94- return 095- }96- }97-98- // may be ambiguous99- for (; i < len; i++) {100- if (101- a.hint.regExpComponents[i] !== true &&102- a.hint.regExpComponents[i] !== b.hint.regExpComponents[i]103- ) {104- return 2105- }106- }107-108- return i === b.hint.regExpComponents.length || a.hint.endWithWildcard ? 1 : 0109-}110-111-function compareHandler(a: HandlerWithSortIndex<any>, b: HandlerWithSortIndex<any>) {112- return a.index - b.index113-}114-115-function getSortedHandlers<T>(116- handlers: HandlerWithSortIndex<T>[] | IterableIterator<HandlerWithSortIndex<T>>117-): T[] {118- return [...handlers].sort(compareHandler).map((h) => h.handler)119-}120-121-function buildMatcherFromPreprocessedRoutes<T>(122- routes: Route<T>[],123- hasAmbiguous: boolean = false124-): AnyMatcher<T> {125- const trie = new Trie({ reverse: hasAmbiguous })126- const handlers: HandlerData<T>[] | HandlerDataWithSortIndex<T>[] = []127-20+function buildMatcherFromPreprocessedRoutes<T>(routes: [string, T[]][]): Matcher<T> {21+ const trie = new Trie()22+ const handlers: HandlerData<T>[] = []23 if (routes.length === 0) {24 return nullMatcher25 }26 27 for (let i = 0, len = routes.length; i < len; i++) {133- const paramMap = trie.insert(routes[i].path, i)134- handlers[i] = [135- [...routes[i].middleware, ...routes[i].handlers],136- Object.keys(paramMap).length !== 0 ? paramMap : null,137- ]138- if (!hasAmbiguous) {139- handlers[i][0] = getSortedHandlers(handlers[i][0] as HandlerWithSortIndex<T>[])28+ let paramMap29+ try {30+ paramMap = trie.insert(routes[i][0], i)31+ } catch (e) {32+ throw e === PATH_ERROR ? new UnsupportedPathError(routes[i][0]) : e33 }34+35+ handlers[i] = [routes[i][1], paramMap.length !== 0 ? paramMap : null]36 }37 38 const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp()39 for (let i = 0, len = handlers.length; i < len; i++) {40 const paramMap = handlers[i][1]41 if (paramMap) {42 for (let j = 0, len = paramMap.length; j < len; j++) {43 paramMap[j][1] = paramReplacementMap[paramMap[j][1]]149-150- const aliasTo = routes[i].paramAliasMap[paramMap[j][0]]151- if (aliasTo) {152- for (let k = 0, len = aliasTo.length; k < len; k++) {153- paramMap.push([aliasTo[k], paramMap[j][1]])154- }155- }44 }45 }46 }47 160- const handlerMap: HandlerData<T>[] | HandlerDataWithSortIndex<T>[] = []48+ const handlerMap: HandlerData<T>[] = []49 // using `in` because indexReplacementMap is a sparse array50 for (const i in indexReplacementMap) {51 handlerMap[i] = handlers[indexReplacementMap[i]]52 }53 166- return [regexp, handlerMap] as AnyMatcher<T>54+ return [regexp, handlerMap] as Matcher<T>55 }56 169-function verifyDuplicateParam<T>(routes: Route<T>[]): boolean {170- const nameMap: Record<string, number> = {}171- for (let i = 0, len = routes.length; i < len; i++) {172- const route = routes[i]57+function findMiddleware<T>(58+ middleware: Record<string, T[]> | undefined,59+ path: string60+): T[] | undefined {61+ if (!middleware) {62+ return undefined63+ }64 174- for (let k = 0, len = route.hint.namedParams.length; k < len; k++) {175- const [index, name] = route.hint.namedParams[k]176- if (name in nameMap && index !== nameMap[name]) {177- return false178- } else {179- nameMap[name] = index180- }65+ for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {66+ if (buildWildcardRegExp(k).test(path)) {67+ return [...middleware[k]]68 }182-183- const paramAliasMap = route.paramAliasMap184- const paramAliasMapKeys = Object.keys(paramAliasMap)185- for (let k = 0, len = paramAliasMapKeys.length; k < len; k++) {186- const aliasFrom = paramAliasMapKeys[k]187- for (let l = 0, len = paramAliasMap[aliasFrom].length; l < len; l++) {188- const aliasTo = paramAliasMap[aliasFrom][l]189- const index = nameMap[aliasFrom]190- if (aliasTo in nameMap && index !== nameMap[aliasTo]) {191- return false192- } else {193- nameMap[aliasTo] = index194- }195- }196- }69 }70 199- return true71+ return undefined72 }73 74 export class RegExpRouter<T> implements Router<T> {203- allowAmbiguous: boolean = true204- routeData?: {205- index: number206- routes: Route<T>[]207- methods: Set<string>208- } = { index: 0, routes: [], methods: new Set() }75+ middleware?: Record<string, Record<string, T[]>>76+ routes?: Record<string, Record<string, T[]>>77 210- constructor(init: Partial<Pick<RegExpRouter<T>, 'allowAmbiguous'>> = {}) {211- Object.assign(this, init)78+ constructor() {79+ this.middleware = { [METHOD_NAME_ALL]: {} }80+ this.routes = { [METHOD_NAME_ALL]: {} }81 }82 83 add(method: string, path: string, handler: T) {215- if (!this.routeData) {84+ const { middleware, routes } = this85+86+ if (!middleware || !routes) {87 throw new Error('Can not add a route since the matcher is already built.')88 }218- this.routeData.index++219- const { index, routes, methods } = this.routeData89 90 if (path === '/*') {91 path = '*'92 }93 225- const hint = initHint(path)226- const handlerWithSortIndex = {227- index,228- handler,229- }94+ if (/\*$/.test(path)) {95+ middleware[method] ||= {}96+ const re = buildWildcardRegExp(path)97+ middleware[method][path] ||= findMiddleware(middleware[METHOD_NAME_ALL], path) || []98+ Object.keys(middleware).forEach((m) => {99+ if (method === METHOD_NAME_ALL || method === m) {100+ Object.keys(middleware[m]).forEach((p) => {101+ ;(path === '*' || path === p) && middleware[m][p].push(handler)102+ })103+ }104+ })105+ Object.keys(routes).forEach((m) => {106+ if (method === METHOD_NAME_ALL || method === m) {107+ Object.keys(routes[m]).forEach(108+ (p) => (path === '*' || re.test(p)) && routes[m][p].push(handler)109+ )110+ }111+ })112 231- for (let i = 0, len = routes.length; i < len; i++) {232- if (routes[i].method === method && routes[i].path === path) {233- routes[i].handlers.push(handlerWithSortIndex)234- return113+ return235- }114 }115 238- methods.add(method)239- routes.push({240- method,241- path,242- hint,243- handlers: [handlerWithSortIndex],244- middleware: [],245- paramAliasMap: {},116+ routes[method] ||= {}117+ routes[method][path] ||= [118+ ...(routes[METHOD_NAME_ALL][path] ||119+ findMiddleware(middleware[method], path) ||120+ findMiddleware(middleware[METHOD_NAME_ALL], path) ||121+ []),122+ ]123+124+ Object.keys(routes).forEach((m) => {125+ ;(method === METHOD_NAME_ALL || method === m) &&126+ routes[m][path] &&127+ routes[m][path].push(handler)128 })129 }130 131 match(method: string, path: string): Result<T> | null {250- const [primaryMatchers, secondaryMatchers, hasAmbiguous] = this.buildAllMatchers()132+ const matchers = this.buildAllMatchers()133 252- this.match = hasAmbiguous253- ? (method, path) => {254- const matcher = (primaryMatchers[method] ||255- primaryMatchers[METHOD_NAME_ALL]) as MatcherWithSortIndex<T>256- let match = path.match(matcher[0])134+ this.match = (method, path) => {135+ const matcher = matchers[method]136+ const match = path.match(matcher[0])137+ if (!match) {138+ return null139+ }140 258- if (!match) {259- // do not support secondary matchers here.260- return null261- }141+ const index = match.indexOf('', 1)142+ const [handlers, paramMap] = matcher[1][index]143+ if (!paramMap) {144+ return { handlers, params: emptyParam }145+ }146 263- const params: Record<string, string> = {}264- const handlers: Set<HandlerWithSortIndex<T>> = new Set()265- let regExpSrc = matcher[0].source266- while (match) {267- let index = match.indexOf('', 1)268- for (;;) {269- const [handler, paramMap] = matcher[1][index]147+ const params: Record<string, string> = {}148+ for (let i = 0, len = paramMap.length; i < len; i++) {149+ params[paramMap[i][0]] = match[paramMap[i][1]]150+ }151 271- if (paramMap) {272- for (let i = 0, len = paramMap.length; i < len; i++) {273- params[paramMap[i][0]] = match[paramMap[i][1]]274- }275- }152+ return { handlers, params }153+ }154 277- for (let i = 0, len = handler.length; i < len; i++) {278- handlers.add(handler[i])279- }280-281- const newIndex = match.indexOf('', index + 1)282- if (newIndex === -1) {283- break284- }285- index = newIndex286- }287-288- regExpSrc = regExpSrc.replace(289- new RegExp(`((?:(?:\\(\\?:|.)*?\\([^)]*\\)){${index - 1}}.*?)\\(\\)`),290- '$1(^)'291- )292- match = path.match(new RegExp(regExpSrc))293- }294-295- return { handlers: getSortedHandlers(handlers.values()), params }296- }297- : (method, path) => {298- let matcher = (primaryMatchers[method] || primaryMatchers[METHOD_NAME_ALL]) as Matcher<T>299- let match = path.match(matcher[0])300-301- if (!match) {302- const matchers = secondaryMatchers[method] || secondaryMatchers[METHOD_NAME_ALL]303- for (let i = 0, len = matchers.length; i < len && !match; i++) {304- matcher = matchers[i] as Matcher<T>305- match = path.match(matcher[0])306- }307-308- if (!match) {309- return null310- }311- }312-313- const index = match.indexOf('', 1)314- const [handlers, paramMap] = matcher[1][index]315- if (!paramMap) {316- return { handlers, params: emptyParam }317- }318-319- const params: Record<string, string> = {}320- for (let i = 0, len = paramMap.length; i < len; i++) {321- params[paramMap[i][0]] = match[paramMap[i][1]]322- }323-324- return { handlers, params }325- }326-155 return this.match(method, path)156 }157 330- private buildAllMatchers(): [331- Record<string, AnyMatcher<T>>,332- Record<string, AnyMatcher<T>[]>,333- boolean334- ] {335- if (!this.routeData) {336- throw new Error('Can not call the buildAllMatchers since the matcher is already built.')337- }158+ private buildAllMatchers(): Record<string, Matcher<T>> {159+ const matchers: Record<string, Matcher<T>> = {}160 339- this.routeData.routes.sort(({ hint: a }, { hint: b }) => {340- if (a.componentsLength !== b.componentsLength) {341- return a.componentsLength - b.componentsLength342- }343- for (344- let i = 0, len = Math.min(a.paramIndexList.length, b.paramIndexList.length) + 1;345- i < len;346- i++347- ) {348- if (a.paramIndexList[i] !== b.paramIndexList[i]) {349- if (a.paramIndexList[i] === undefined) {350- return -1351- } else if (b.paramIndexList[i] === undefined) {352- return 1353- } else {354- return a.paramIndexList[i] - b.paramIndexList[i]355- }356- }357- }358- if (a.endWithWildcard !== b.endWithWildcard) {359- return a.endWithWildcard ? -1 : 1360- }361- return 0161+ METHOD_NAMES.forEach((method) => {162+ matchers[method] = this.buildMatcher(method) || matchers[METHOD_NAME_ALL]163 })164 364- const primaryMatchers: Record<string, AnyMatcher<T>> = {}365- const secondaryMatchers: Record<string, AnyMatcher<T>[]> = {}366- let hasAmbiguous = false165+ // Release cache166+ this.middleware = this.routes = undefined167 368- this.routeData.methods.forEach((method) => {369- let _hasAmbiguous370- ;[primaryMatchers[method], secondaryMatchers[method], _hasAmbiguous] =371- this.buildMatcher(method)372- hasAmbiguous = hasAmbiguous || _hasAmbiguous373- })374- if (hasAmbiguous) {375- // rebuild all matchers with ambiguous flag376- this.routeData.methods.forEach((method) => {377- ;[primaryMatchers[method], secondaryMatchers[method]] = this.buildMatcher(378- method,379- hasAmbiguous380- )381- })382- }383- primaryMatchers[METHOD_NAME_ALL] ||= nullMatcher384- secondaryMatchers[METHOD_NAME_ALL] ||= []385-386- delete this.routeData // to reduce memory usage387-388- return [primaryMatchers, secondaryMatchers, hasAmbiguous]168+ return matchers169 }170 391- private buildMatcher(392- method: string,393- hasAmbiguous: boolean = false394- ): [AnyMatcher<T>, AnyMatcher<T>[], boolean] {395- const targetMethods = new Set([method, METHOD_NAME_ALL])396- // @ts-ignore397- const routes = this.routeData.routes.filter(({ method }) => targetMethods.has(method))171+ private buildMatcher(method: string): Matcher<T> | null {172+ const routes: [string, T[]][] = []173 399- // Reset temporary data per method400- for (let i = 0, len = routes.length; i < len; i++) {401- routes[i].middleware = []402- routes[i].paramAliasMap = {}403- }404-405- // preprocess routes406- for (let i = 0, len = routes.length; i < len; i++) {407- for (let j = i + 1; j < len; j++) {408- const compareResult = compareRoute(routes[i], routes[j])409- // i includes j410- if (compareResult === 1) {411- const components = routes[j].hint.components412- const namedParams = routes[i].hint.namedParams413- for (let k = 0, len = namedParams.length; k < len; k++) {414- const c = components[namedParams[k][0]]415- const m = c.match(/^\/:(\w+)({[^}]+})?/)416- if (m && namedParams[k][1] === m[1]) {417- continue418- }419- if (m) {420- routes[j].paramAliasMap[m[1]] ||= []421- routes[j].paramAliasMap[m[1]].push(namedParams[k][1])422- } else {423- components[namedParams[k][0]] = `/:${namedParams[k][1]}{${c.substring(1)}}`424- routes[j].hint.namedParams.push([425- namedParams[k][0],426- namedParams[k][1],427- c.substring(1),428- ])429- routes[j].path = components.join('')430- }431- }432-433- if (routes[j].hint.components.length < routes[i].hint.components.length) {434- routes[j].middleware.push(435- ...routes[i].handlers.map((h) => ({436- index: h.index,437- handler: h.handler,438- }))439- )440- } else {441- routes[j].middleware.push(...routes[i].handlers)442- }443-444- routes[i].hint.maybeHandler = false445- } else if (compareResult === 2) {446- if (!this.allowAmbiguous) {447- throw new UnsupportedPathError(routes[i].path)448- }449- // ambiguous450- hasAmbiguous = true451-452- if (!verifyDuplicateParam([routes[i], routes[j]])) {453- throw new Error('Duplicate param name')454- }455- }174+ let hasOwnRoute = method === METHOD_NAME_ALL175+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion176+ ;[this.middleware!, this.routes!].forEach((r) => {177+ const ownRoute = r[method]178+ ? Object.keys(r[method]).map((path) => [path, r[method][path]])179+ : []180+ if (ownRoute.length !== 0) {181+ hasOwnRoute ||= true182+ routes.push(...(ownRoute as [string, T[]][]))183+ } else if (method !== METHOD_NAME_ALL) {184+ routes.push(185+ ...(Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]]) as [186+ string,187+ T[]188+ ][])189+ )190 }191+ })192 458- if (!verifyDuplicateParam([routes[i]])) {459- throw new Error('Duplicate param name')460- }193+ if (!hasOwnRoute) {194+ return null195+ } else {196+ return buildMatcherFromPreprocessedRoutes(routes)197 }462-463- if (hasAmbiguous) {464- return [buildMatcherFromPreprocessedRoutes(routes, hasAmbiguous), [], hasAmbiguous]465- }466-467- const primaryRoutes = []468- const secondaryRoutes = []469- for (let i = 0, len = routes.length; i < len; i++) {470- if (routes[i].hint.maybeHandler || !routes[i].hint.endWithWildcard) {471- primaryRoutes.push(routes[i])472- } else {473- secondaryRoutes.push(routes[i])474- }475- }476- return [477- buildMatcherFromPreprocessedRoutes(primaryRoutes, hasAmbiguous),478- [buildMatcherFromPreprocessedRoutes(secondaryRoutes, hasAmbiguous)],479- hasAmbiguous,480- ]198 }199 }modified:deno_dist/router/reg-exp-router/trie.ts+1 added-9 removed
2 unmodified lines3 4 export type { ParamMap } from './node.ts'5 export type ReplacementMap = number[]6 7-interface InitOptions {8- reverse: boolean9-}10-7 export class Trie {8 context: Context = { varIndex: 0 }13- root: Node9+ root: Node = new Node()10 15- constructor({ reverse }: InitOptions = { reverse: false }) {16- this.root = new Node({ reverse })17- }18-11 insert(path: string, index: number): ParamMap {12 const paramMap: ParamMap = []13 14 /**35 unmodified linesmodified:deno_dist/hono.ts+1 added-1 removed
91 unmodified lines92 E extends Partial<Environment> = Environment,93 P extends string = '/'94 > extends defineDynamicClass()<E, P, Hono<E, P>> {95 readonly router: Router<Handler<string, E>> = new SmartRouter({96- routers: [new StaticRouter(), new RegExpRouter({ allowAmbiguous: false }), new TrieRouter()],96+ routers: [new StaticRouter(), new RegExpRouter(), new TrieRouter()],97 })98 readonly strict: boolean = true // strict routing - default is true99 private _tempPath: string = ''100 private path: string = '/'163 unmodified linesmodified:src/router/reg-exp-router/node.ts+29 added-15 removed
1 const LABEL_REG_EXP_STR = '[^/]+'2 const ONLY_WILDCARD_REG_EXP_STR = '.*'3 const TAIL_WILDCARD_REG_EXP_STR = '(?:|/.*)'4+export const PATH_ERROR = Symbol()5 6 export type ParamMap = Array<[string, number]>7 export interface Context {8 varIndex: number34 unmodified lines43 export class Node {44 index?: number45 varIndex?: number46 children: Record<string, Node> = {}46- reverse: boolean47 48- constructor({ reverse }: Partial<Node> = { reverse: false }) {49- this.reverse = reverse as boolean50- }51-52- newChildNode(): Node {53- return new Node({ reverse: this.reverse })54- }55-48 insert(tokens: readonly string[], index: number, paramMap: ParamMap, context: Context): void {49 if (tokens.length === 0) {50+ if (this.index !== undefined) {51+ throw PATH_ERROR52+ }53+54 this.index = index55 return56 }57 13 unmodified lines71 const regexpStr = pattern[2] || LABEL_REG_EXP_STR72 73 node = this.children[regexpStr]74 if (!node) {75+ if (76+ Object.keys(this.children).some(77+ (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR78+ )79+ ) {80+ throw PATH_ERROR81+ }79- node = this.children[regexpStr] = this.newChildNode()82+ node = this.children[regexpStr] = new Node()83 if (name !== '') {84 node.varIndex = context.varIndex++85 }86 }87 if (name !== '') {88+ if (paramMap.some((p) => p[0] === name)) {89+ throw new Error('Duplicate param name')90+ }91 paramMap.push([name, node.varIndex as number])92 }93 } else {88- node = this.children[token] ||= this.newChildNode()94+ node = this.children[token]95+ if (!node) {96+ if (97+ Object.keys(this.children).some(98+ (k) =>99+ k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR100+ )101+ ) {102+ throw PATH_ERROR103+ }104+ node = this.children[token] = new Node()105+ }106 }107 108 node.insert(restTokens, index, paramMap, context)109 }110 111 buildRegExpStr(): string {95- let childKeys = Object.keys(this.children).sort(compareKey)96- if (this.reverse) {97- childKeys = childKeys.reverse()98- }112+ const childKeys = Object.keys(this.children).sort(compareKey)113 114 const strList = childKeys.map((k) => {115 const c = this.children[k]116 return (typeof c.varIndex === 'number' ? `(${k})@${c.varIndex}` : k) + c.buildRegExpStr()16 unmodified linesmodified:src/router/reg-exp-router/router.test.ts+32 added-84 removed
1-import { METHOD_NAME_ALL } from '../../router'1+import { UnsupportedPathError } from '../../router'2 import { RegExpRouter } from './router'3 4 describe('Basic Usage', () => {5 const router = new RegExpRouter<string>()84 unmodified lines90 beforeEach(() => {91 router = new RegExpRouter<string>()92 })93 94- it('abstract -> concrete', async () => {95- router.add('GET', '/:type/:action', 'foo')96- router.add('GET', '/posts/:id', 'bar')97- const res = router.match('GET', '/posts/123')98- expect(res).not.toBeNull()99- expect(res?.handlers).toEqual(['foo', 'bar'])100- })101-102- it('concrete -> abstract', async () => {103- router.add('GET', '/posts/:id', 'bar')104- router.add('GET', '/:type/:action', 'foo')105- const res = router.match('GET', '/posts/123')106- expect(res).not.toBeNull()107- expect(res?.handlers).toEqual(['bar', 'foo'])108- })109-94 it('middleware -> handler', async () => {95 router.add('GET', '*', 'bar')96 router.add('GET', '/:type/:action', 'foo')97 const res = router.match('GET', '/posts/123')9 unmodified lines107 expect(res?.handlers).toEqual(['foo', 'fallback'])108 })109 })110 127-describe('Optimization for METHOD_NAME_OF_ALL', () => {128- let router: RegExpRouter<string>129- beforeEach(() => {130- router = new RegExpRouter<string>()131- })132-133- it('Apply to all requests', async () => {134- router.add(METHOD_NAME_ALL, '*', 'OK')135- const res = router.match('GET', '/entry/123')136- expect(res).not.toBeNull()137- expect(res?.handlers).toEqual(['OK'])138- expect(res?.params).toMatchObject({})139- })140-141- it('Apply to all requests under a specific path', async () => {142- router.add(METHOD_NAME_ALL, '/path/to/*', 'OK')143- let res = router.match('GET', '/entry/123')144- expect(res).toBeNull()145-146- res = router.match('GET', '/path/to/entry/123')147- expect(res).not.toBeNull()148- expect(res?.handlers).toEqual(['OK'])149- expect(res?.params).toMatchObject({})150- })151-})152-111 describe('Multi match', () => {112 describe('Blog', () => {113 const router = new RegExpRouter<string>()114 33 unmodified lines148 expect(res?.handlers).toEqual(['middleware a'])149 })150 })151 152+ it('hierarchy', () => {153+ const router = new RegExpRouter<string>()154+ router.add('GET', '/posts/:id/comments/:comment_id', 'foo')155+ router.add('GET', '/posts/:id', 'bar')156+ expect(() => {157+ router.match('GET', '/')158+ }).not.toThrow()159+ })160+})161+162+describe('Check for duplicate parameter names', () => {163+ it('self', () => {164+ const router = new RegExpRouter<string>()165+ router.add('GET', '/:id/:id', 'get')166+ expect(() => {167+ router.match('GET', '/') // check parameter names on the first `match` call168+ }).toThrowError(/Duplicate param name/)169+ })170+})171+172+describe('UnsupportedPathError', () => {173 describe('Ambiguous', () => {174 const router = new RegExpRouter<string>()175 176 router.add('GET', '/:user/entries', 'get user entries')177 router.add('GET', '/entry/:name', 'get entry')178 router.add('POST', '/entry', 'create entry')179 180 it('GET /entry/entry', async () => {202- const res = router.match('GET', '/entry/entries')203- expect(res).not.toBeNull()204- expect(res?.handlers).toEqual(['get user entries', 'get entry'])205- expect(res?.params['user']).toBe('entry')206- expect(res?.params['name']).toBe('entries')181+ expect(() => {182+ router.match('GET', '/entry/entries')183+ }).toThrowError(UnsupportedPathError)184 })208-209- it('POST /entry', async () => {210- const res = router.match('POST', '/entry')211- expect(res).not.toBeNull()212- expect(res?.handlers).toEqual(['create entry'])213- })185 })186 216- describe('Multiple handlers', () => {187+ describe('Multiple handlers with different label', () => {188 const router = new RegExpRouter<string>()189 190 router.add('GET', '/:type/:id', ':type')191 router.add('GET', '/:class/:id', ':class')192 router.add('GET', '/:model/:id', ':model')222- router.add('GET', '/entry/:id', 'entry')193 194 it('GET /entry/123', async () => {225- const res = router.match('GET', '/entry/123')226- expect(res).not.toBeNull()227- expect(res?.handlers).toEqual([':type', ':class', ':model', 'entry'])228- expect(res?.params['type']).toBe('entry')229- expect(res?.params['class']).toBe('entry')230- expect(res?.params['model']).toBe('entry')195+ expect(() => {196+ router.match('GET', '/entry/123')197+ }).toThrowError(UnsupportedPathError)198 })199 })233-})200 235-describe('Check for duplicate parameter names', () => {236- it('self', () => {237- const router = new RegExpRouter<string>()238- router.add('GET', '/:id/:id', 'get')239- expect(() => {240- router.match('GET', '/') // check parameter names on the first `match` call241- }).toThrowError(/Duplicate param name/)242- })243-201 it('parent', () => {202 const router = new RegExpRouter<string>()203 router.add('GET', '/:id/:action', 'foo')204 router.add('GET', '/posts/:id', 'bar')205 expect(() => {206 router.match('GET', '/')250- }).toThrowError(/Duplicate param name/)207+ }).toThrowError(UnsupportedPathError)208 })209 210 it('child', () => {211 const router = new RegExpRouter<string>()1 unmodified line213 router.add('GET', '/:id/:action', 'bar')214 215 expect(() => {216 router.match('GET', '/')260- }).toThrowError(/Duplicate param name/)217+ }).toThrowError(UnsupportedPathError)218 })219 263- it('hierarchy', () => {264- const router = new RegExpRouter<string>()265- router.add('GET', '/posts/:id/comments/:comment_id', 'foo')266- router.add('GET', '/posts/:id', 'bar')267- expect(() => {268- router.match('GET', '/')269- }).not.toThrow()270- })271-220 it('different regular expression', () => {221 const router = new RegExpRouter<string>()222 router.add('GET', '/:id/:action{create|update}', 'foo')223 router.add('GET', '/:id/:action{delete}', 'bar')224 expect(() => {225 router.match('GET', '/')278- }).not.toThrow()226+ }).toThrowError(UnsupportedPathError)227 })228 })229 230 describe('star', () => {21 unmodified linesmodified:src/router/reg-exp-router/router.ts+116 added-399 removed
1 /* eslint-disable @typescript-eslint/ban-ts-comment */2 import type { Router, Result } from '../../router'3-import { METHOD_NAME_ALL, UnsupportedPathError } from '../../router'3+import { METHOD_NAME_ALL, METHODS, UnsupportedPathError } from '../../router'4+import { PATH_ERROR } from './node'5 import type { ParamMap } from './trie'6 import { Trie } from './trie'7 7-interface Hint {8- components: string[]9- regExpComponents: Array<true | string>10- componentsLength: number11- endWithWildcard: boolean12- paramIndexList: number[]13- maybeHandler: boolean14- namedParams: [number, string, string][]15-}16-interface HandlerWithSortIndex<T> {17- handler: T18- index: number19-}20-interface Route<T> {21- method: string22- path: string23- hint: Hint24- handlers: HandlerWithSortIndex<T>[]25- middleware: HandlerWithSortIndex<T>[]26- paramAliasMap: Record<string, string[]>27-}8+const METHOD_NAMES = [METHOD_NAME_ALL, ...METHODS].map((method) => method.toUpperCase())9+10 type HandlerData<T> = [T[], ParamMap | null]11 type Matcher<T> = [RegExp, HandlerData<T>[]]30-type HandlerDataWithSortIndex<T> = [HandlerWithSortIndex<T>[], ParamMap | null]31-type MatcherWithSortIndex<T> = [RegExp, HandlerDataWithSortIndex<T>[]]32-type AnyMatcher<T> = Matcher<T> | MatcherWithSortIndex<T>12 34-type CompareResult =35- | 0 // different36- | 1 // included37- | 2 // ambiguous38-13 const emptyParam = {}14 const nullMatcher: Matcher<any> = [/^$/, []]15 42-function initHint(path: string): Hint {43- const components = path.match(/\/(?::\w+{[^}]+}|[^\/]*)/g) || []44- let componentsLength = components.length45-46- const paramIndexList: number[] = []47- const regExpComponents: Array<true | string> = []48- const namedParams: [number, string, string][] = []49- for (let i = 0, len = components.length; i < len; i++) {50- if (i === len - 1 && components[i] === '/*') {51- componentsLength--52- break53- }54-55- const m = components[i].match(/^\/:(\w+)({[^}]+})?/)56- if (m) {57- namedParams.push([i, m[1], m[2] || '[^/]+'])58- regExpComponents[i] = m[2] || true59- } else if (components[i] === '/*') {60- regExpComponents[i] = true61- } else {62- regExpComponents[i] = components[i]63- }64-65- if (/\/(?::|\*)/.test(components[i])) {66- paramIndexList.push(i)67- }68- }69-70- return {71- components,72- regExpComponents,73- componentsLength,74- endWithWildcard: path.endsWith('*'),75- paramIndexList,76- namedParams,77- maybeHandler: true,78- }16+function buildWildcardRegExp(path: string): RegExp {17+ return new RegExp(path === '*' ? '' : `^${path.replace(/\/\*/, '(?:|/.*)')}$`)18 }19 81-function compareRoute<T>(a: Route<T>, b: Route<T>): CompareResult {82- if (a.path === '*') {83- return 184- }85-86- let i = 087- const len = a.hint.regExpComponents.length88- for (; i < len; i++) {89- if (a.hint.regExpComponents[i] !== b.hint.regExpComponents[i]) {90- if (a.hint.regExpComponents[i] === true) {91- break92- }93-94- return 095- }96- }97-98- // may be ambiguous99- for (; i < len; i++) {100- if (101- a.hint.regExpComponents[i] !== true &&102- a.hint.regExpComponents[i] !== b.hint.regExpComponents[i]103- ) {104- return 2105- }106- }107-108- return i === b.hint.regExpComponents.length || a.hint.endWithWildcard ? 1 : 0109-}110-111-function compareHandler(a: HandlerWithSortIndex<any>, b: HandlerWithSortIndex<any>) {112- return a.index - b.index113-}114-115-function getSortedHandlers<T>(116- handlers: HandlerWithSortIndex<T>[] | IterableIterator<HandlerWithSortIndex<T>>117-): T[] {118- return [...handlers].sort(compareHandler).map((h) => h.handler)119-}120-121-function buildMatcherFromPreprocessedRoutes<T>(122- routes: Route<T>[],123- hasAmbiguous: boolean = false124-): AnyMatcher<T> {125- const trie = new Trie({ reverse: hasAmbiguous })126- const handlers: HandlerData<T>[] | HandlerDataWithSortIndex<T>[] = []127-20+function buildMatcherFromPreprocessedRoutes<T>(routes: [string, T[]][]): Matcher<T> {21+ const trie = new Trie()22+ const handlers: HandlerData<T>[] = []23 if (routes.length === 0) {24 return nullMatcher25 }26 27 for (let i = 0, len = routes.length; i < len; i++) {133- const paramMap = trie.insert(routes[i].path, i)134- handlers[i] = [135- [...routes[i].middleware, ...routes[i].handlers],136- Object.keys(paramMap).length !== 0 ? paramMap : null,137- ]138- if (!hasAmbiguous) {139- handlers[i][0] = getSortedHandlers(handlers[i][0] as HandlerWithSortIndex<T>[])28+ let paramMap29+ try {30+ paramMap = trie.insert(routes[i][0], i)31+ } catch (e) {32+ throw e === PATH_ERROR ? new UnsupportedPathError(routes[i][0]) : e33 }34+35+ handlers[i] = [routes[i][1], paramMap.length !== 0 ? paramMap : null]36 }37 38 const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp()39 for (let i = 0, len = handlers.length; i < len; i++) {40 const paramMap = handlers[i][1]41 if (paramMap) {42 for (let j = 0, len = paramMap.length; j < len; j++) {43 paramMap[j][1] = paramReplacementMap[paramMap[j][1]]149-150- const aliasTo = routes[i].paramAliasMap[paramMap[j][0]]151- if (aliasTo) {152- for (let k = 0, len = aliasTo.length; k < len; k++) {153- paramMap.push([aliasTo[k], paramMap[j][1]])154- }155- }44 }45 }46 }47 160- const handlerMap: HandlerData<T>[] | HandlerDataWithSortIndex<T>[] = []48+ const handlerMap: HandlerData<T>[] = []49 // using `in` because indexReplacementMap is a sparse array50 for (const i in indexReplacementMap) {51 handlerMap[i] = handlers[indexReplacementMap[i]]52 }53 166- return [regexp, handlerMap] as AnyMatcher<T>54+ return [regexp, handlerMap] as Matcher<T>55 }56 169-function verifyDuplicateParam<T>(routes: Route<T>[]): boolean {170- const nameMap: Record<string, number> = {}171- for (let i = 0, len = routes.length; i < len; i++) {172- const route = routes[i]57+function findMiddleware<T>(58+ middleware: Record<string, T[]> | undefined,59+ path: string60+): T[] | undefined {61+ if (!middleware) {62+ return undefined63+ }64 174- for (let k = 0, len = route.hint.namedParams.length; k < len; k++) {175- const [index, name] = route.hint.namedParams[k]176- if (name in nameMap && index !== nameMap[name]) {177- return false178- } else {179- nameMap[name] = index180- }65+ for (const k of Object.keys(middleware).sort((a, b) => b.length - a.length)) {66+ if (buildWildcardRegExp(k).test(path)) {67+ return [...middleware[k]]68 }182-183- const paramAliasMap = route.paramAliasMap184- const paramAliasMapKeys = Object.keys(paramAliasMap)185- for (let k = 0, len = paramAliasMapKeys.length; k < len; k++) {186- const aliasFrom = paramAliasMapKeys[k]187- for (let l = 0, len = paramAliasMap[aliasFrom].length; l < len; l++) {188- const aliasTo = paramAliasMap[aliasFrom][l]189- const index = nameMap[aliasFrom]190- if (aliasTo in nameMap && index !== nameMap[aliasTo]) {191- return false192- } else {193- nameMap[aliasTo] = index194- }195- }196- }69 }70 199- return true71+ return undefined72 }73 74 export class RegExpRouter<T> implements Router<T> {203- allowAmbiguous: boolean = true204- routeData?: {205- index: number206- routes: Route<T>[]207- methods: Set<string>208- } = { index: 0, routes: [], methods: new Set() }75+ middleware?: Record<string, Record<string, T[]>>76+ routes?: Record<string, Record<string, T[]>>77 210- constructor(init: Partial<Pick<RegExpRouter<T>, 'allowAmbiguous'>> = {}) {211- Object.assign(this, init)78+ constructor() {79+ this.middleware = { [METHOD_NAME_ALL]: {} }80+ this.routes = { [METHOD_NAME_ALL]: {} }81 }82 83 add(method: string, path: string, handler: T) {215- if (!this.routeData) {84+ const { middleware, routes } = this85+86+ if (!middleware || !routes) {87 throw new Error('Can not add a route since the matcher is already built.')88 }218- this.routeData.index++219- const { index, routes, methods } = this.routeData89 90 if (path === '/*') {91 path = '*'92 }93 225- const hint = initHint(path)226- const handlerWithSortIndex = {227- index,228- handler,229- }94+ if (/\*$/.test(path)) {95+ middleware[method] ||= {}96+ const re = buildWildcardRegExp(path)97+ middleware[method][path] ||= findMiddleware(middleware[METHOD_NAME_ALL], path) || []98+ Object.keys(middleware).forEach((m) => {99+ if (method === METHOD_NAME_ALL || method === m) {100+ Object.keys(middleware[m]).forEach((p) => {101+ ;(path === '*' || path === p) && middleware[m][p].push(handler)102+ })103+ }104+ })105+ Object.keys(routes).forEach((m) => {106+ if (method === METHOD_NAME_ALL || method === m) {107+ Object.keys(routes[m]).forEach(108+ (p) => (path === '*' || re.test(p)) && routes[m][p].push(handler)109+ )110+ }111+ })112 231- for (let i = 0, len = routes.length; i < len; i++) {232- if (routes[i].method === method && routes[i].path === path) {233- routes[i].handlers.push(handlerWithSortIndex)234- return113+ return235- }114 }115 238- methods.add(method)239- routes.push({240- method,241- path,242- hint,243- handlers: [handlerWithSortIndex],244- middleware: [],245- paramAliasMap: {},116+ routes[method] ||= {}117+ routes[method][path] ||= [118+ ...(routes[METHOD_NAME_ALL][path] ||119+ findMiddleware(middleware[method], path) ||120+ findMiddleware(middleware[METHOD_NAME_ALL], path) ||121+ []),122+ ]123+124+ Object.keys(routes).forEach((m) => {125+ ;(method === METHOD_NAME_ALL || method === m) &&126+ routes[m][path] &&127+ routes[m][path].push(handler)128 })129 }130 131 match(method: string, path: string): Result<T> | null {250- const [primaryMatchers, secondaryMatchers, hasAmbiguous] = this.buildAllMatchers()132+ const matchers = this.buildAllMatchers()133 252- this.match = hasAmbiguous253- ? (method, path) => {254- const matcher = (primaryMatchers[method] ||255- primaryMatchers[METHOD_NAME_ALL]) as MatcherWithSortIndex<T>256- let match = path.match(matcher[0])134+ this.match = (method, path) => {135+ const matcher = matchers[method]136+ const match = path.match(matcher[0])137+ if (!match) {138+ return null139+ }140 258- if (!match) {259- // do not support secondary matchers here.260- return null261- }141+ const index = match.indexOf('', 1)142+ const [handlers, paramMap] = matcher[1][index]143+ if (!paramMap) {144+ return { handlers, params: emptyParam }145+ }146 263- const params: Record<string, string> = {}264- const handlers: Set<HandlerWithSortIndex<T>> = new Set()265- let regExpSrc = matcher[0].source266- while (match) {267- let index = match.indexOf('', 1)268- for (;;) {269- const [handler, paramMap] = matcher[1][index]147+ const params: Record<string, string> = {}148+ for (let i = 0, len = paramMap.length; i < len; i++) {149+ params[paramMap[i][0]] = match[paramMap[i][1]]150+ }151 271- if (paramMap) {272- for (let i = 0, len = paramMap.length; i < len; i++) {273- params[paramMap[i][0]] = match[paramMap[i][1]]274- }275- }152+ return { handlers, params }153+ }154 277- for (let i = 0, len = handler.length; i < len; i++) {278- handlers.add(handler[i])279- }280-281- const newIndex = match.indexOf('', index + 1)282- if (newIndex === -1) {283- break284- }285- index = newIndex286- }287-288- regExpSrc = regExpSrc.replace(289- new RegExp(`((?:(?:\\(\\?:|.)*?\\([^)]*\\)){${index - 1}}.*?)\\(\\)`),290- '$1(^)'291- )292- match = path.match(new RegExp(regExpSrc))293- }294-295- return { handlers: getSortedHandlers(handlers.values()), params }296- }297- : (method, path) => {298- let matcher = (primaryMatchers[method] || primaryMatchers[METHOD_NAME_ALL]) as Matcher<T>299- let match = path.match(matcher[0])300-301- if (!match) {302- const matchers = secondaryMatchers[method] || secondaryMatchers[METHOD_NAME_ALL]303- for (let i = 0, len = matchers.length; i < len && !match; i++) {304- matcher = matchers[i] as Matcher<T>305- match = path.match(matcher[0])306- }307-308- if (!match) {309- return null310- }311- }312-313- const index = match.indexOf('', 1)314- const [handlers, paramMap] = matcher[1][index]315- if (!paramMap) {316- return { handlers, params: emptyParam }317- }318-319- const params: Record<string, string> = {}320- for (let i = 0, len = paramMap.length; i < len; i++) {321- params[paramMap[i][0]] = match[paramMap[i][1]]322- }323-324- return { handlers, params }325- }326-155 return this.match(method, path)156 }157 330- private buildAllMatchers(): [331- Record<string, AnyMatcher<T>>,332- Record<string, AnyMatcher<T>[]>,333- boolean334- ] {335- if (!this.routeData) {336- throw new Error('Can not call the buildAllMatchers since the matcher is already built.')337- }158+ private buildAllMatchers(): Record<string, Matcher<T>> {159+ const matchers: Record<string, Matcher<T>> = {}160 339- this.routeData.routes.sort(({ hint: a }, { hint: b }) => {340- if (a.componentsLength !== b.componentsLength) {341- return a.componentsLength - b.componentsLength342- }343- for (344- let i = 0, len = Math.min(a.paramIndexList.length, b.paramIndexList.length) + 1;345- i < len;346- i++347- ) {348- if (a.paramIndexList[i] !== b.paramIndexList[i]) {349- if (a.paramIndexList[i] === undefined) {350- return -1351- } else if (b.paramIndexList[i] === undefined) {352- return 1353- } else {354- return a.paramIndexList[i] - b.paramIndexList[i]355- }356- }357- }358- if (a.endWithWildcard !== b.endWithWildcard) {359- return a.endWithWildcard ? -1 : 1360- }361- return 0161+ METHOD_NAMES.forEach((method) => {162+ matchers[method] = this.buildMatcher(method) || matchers[METHOD_NAME_ALL]163 })164 364- const primaryMatchers: Record<string, AnyMatcher<T>> = {}365- const secondaryMatchers: Record<string, AnyMatcher<T>[]> = {}366- let hasAmbiguous = false165+ // Release cache166+ this.middleware = this.routes = undefined167 368- this.routeData.methods.forEach((method) => {369- let _hasAmbiguous370- ;[primaryMatchers[method], secondaryMatchers[method], _hasAmbiguous] =371- this.buildMatcher(method)372- hasAmbiguous = hasAmbiguous || _hasAmbiguous373- })374- if (hasAmbiguous) {375- // rebuild all matchers with ambiguous flag376- this.routeData.methods.forEach((method) => {377- ;[primaryMatchers[method], secondaryMatchers[method]] = this.buildMatcher(378- method,379- hasAmbiguous380- )381- })382- }383- primaryMatchers[METHOD_NAME_ALL] ||= nullMatcher384- secondaryMatchers[METHOD_NAME_ALL] ||= []385-386- delete this.routeData // to reduce memory usage387-388- return [primaryMatchers, secondaryMatchers, hasAmbiguous]168+ return matchers169 }170 391- private buildMatcher(392- method: string,393- hasAmbiguous: boolean = false394- ): [AnyMatcher<T>, AnyMatcher<T>[], boolean] {395- const targetMethods = new Set([method, METHOD_NAME_ALL])396- // @ts-ignore397- const routes = this.routeData.routes.filter(({ method }) => targetMethods.has(method))171+ private buildMatcher(method: string): Matcher<T> | null {172+ const routes: [string, T[]][] = []173 399- // Reset temporary data per method400- for (let i = 0, len = routes.length; i < len; i++) {401- routes[i].middleware = []402- routes[i].paramAliasMap = {}403- }404-405- // preprocess routes406- for (let i = 0, len = routes.length; i < len; i++) {407- for (let j = i + 1; j < len; j++) {408- const compareResult = compareRoute(routes[i], routes[j])409- // i includes j410- if (compareResult === 1) {411- const components = routes[j].hint.components412- const namedParams = routes[i].hint.namedParams413- for (let k = 0, len = namedParams.length; k < len; k++) {414- const c = components[namedParams[k][0]]415- const m = c.match(/^\/:(\w+)({[^}]+})?/)416- if (m && namedParams[k][1] === m[1]) {417- continue418- }419- if (m) {420- routes[j].paramAliasMap[m[1]] ||= []421- routes[j].paramAliasMap[m[1]].push(namedParams[k][1])422- } else {423- components[namedParams[k][0]] = `/:${namedParams[k][1]}{${c.substring(1)}}`424- routes[j].hint.namedParams.push([425- namedParams[k][0],426- namedParams[k][1],427- c.substring(1),428- ])429- routes[j].path = components.join('')430- }431- }432-433- if (routes[j].hint.components.length < routes[i].hint.components.length) {434- routes[j].middleware.push(435- ...routes[i].handlers.map((h) => ({436- index: h.index,437- handler: h.handler,438- }))439- )440- } else {441- routes[j].middleware.push(...routes[i].handlers)442- }443-444- routes[i].hint.maybeHandler = false445- } else if (compareResult === 2) {446- if (!this.allowAmbiguous) {447- throw new UnsupportedPathError(routes[i].path)448- }449- // ambiguous450- hasAmbiguous = true451-452- if (!verifyDuplicateParam([routes[i], routes[j]])) {453- throw new Error('Duplicate param name')454- }455- }174+ let hasOwnRoute = method === METHOD_NAME_ALL175+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion176+ ;[this.middleware!, this.routes!].forEach((r) => {177+ const ownRoute = r[method]178+ ? Object.keys(r[method]).map((path) => [path, r[method][path]])179+ : []180+ if (ownRoute.length !== 0) {181+ hasOwnRoute ||= true182+ routes.push(...(ownRoute as [string, T[]][]))183+ } else if (method !== METHOD_NAME_ALL) {184+ routes.push(185+ ...(Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]]) as [186+ string,187+ T[]188+ ][])189+ )190 }191+ })192 458- if (!verifyDuplicateParam([routes[i]])) {459- throw new Error('Duplicate param name')460- }193+ if (!hasOwnRoute) {194+ return null195+ } else {196+ return buildMatcherFromPreprocessedRoutes(routes)197 }462-463- if (hasAmbiguous) {464- return [buildMatcherFromPreprocessedRoutes(routes, hasAmbiguous), [], hasAmbiguous]465- }466-467- const primaryRoutes = []468- const secondaryRoutes = []469- for (let i = 0, len = routes.length; i < len; i++) {470- if (routes[i].hint.maybeHandler || !routes[i].hint.endWithWildcard) {471- primaryRoutes.push(routes[i])472- } else {473- secondaryRoutes.push(routes[i])474- }475- }476- return [477- buildMatcherFromPreprocessedRoutes(primaryRoutes, hasAmbiguous),478- [buildMatcherFromPreprocessedRoutes(secondaryRoutes, hasAmbiguous)],479- hasAmbiguous,480- ]198 }199 }modified:src/router/reg-exp-router/trie.ts+1 added-9 removed
2 unmodified lines3 4 export type { ParamMap } from './node'5 export type ReplacementMap = number[]6 7-interface InitOptions {8- reverse: boolean9-}10-7 export class Trie {8 context: Context = { varIndex: 0 }13- root: Node9+ root: Node = new Node()10 15- constructor({ reverse }: InitOptions = { reverse: false }) {16- this.root = new Node({ reverse })17- }18-11 insert(path: string, index: number): ParamMap {12 const paramMap: ParamMap = []13 14 /**35 unmodified linesmodified:src/router/smart-router/router.test.ts+4 added-4 removed
4 unmodified lines5 6 describe('StaticRouter', () => {7 describe('Basic Usage', () => {8 const router = new SmartRouter<string>({9- routers: [new StaticRouter(), new RegExpRouter({ allowAmbiguous: false }), new TrieRouter()],9+ routers: [new StaticRouter(), new RegExpRouter(), new TrieRouter()],10 })11 12 router.add('GET', '/hello', 'get hello')13 router.add('POST', '/hello', 'post hello')19 unmodified lines33 34 describe('Multi match', () => {35 describe('Blog', () => {36 const router = new SmartRouter<string>({37- routers: [new StaticRouter(), new RegExpRouter({ allowAmbiguous: false }), new TrieRouter()],37+ routers: [new StaticRouter(), new RegExpRouter(), new TrieRouter()],38 })39 40 router.add('ALL', '*', 'middleware a')41 router.add('GET', '*', 'middleware b')22 unmodified lines64 describe('Complex', () => {65 let router: SmartRouter<string>66 beforeEach(() => {67 router = new SmartRouter<string>({68- routers: [new StaticRouter(), new RegExpRouter({ allowAmbiguous: false }), new TrieRouter()],68+ routers: [new StaticRouter(), new RegExpRouter(), new TrieRouter()],69 })70 })71 72 it('Named Param', async () => {54 unmodified lines127 })128 129 describe('TrieRouter', () => {130 const router = new SmartRouter<string>({131- routers: [new StaticRouter(), new RegExpRouter({ allowAmbiguous: false }), new TrieRouter()],131+ routers: [new StaticRouter(), new RegExpRouter(), new TrieRouter()],132 })133 134 router.add('GET', '/:user/entries', 'get user entries')135 router.add('GET', '/entry/:name', 'get entry')9 unmodified linesmodified:src/hono.ts+1 added-1 removed
91 unmodified lines92 E extends Partial<Environment> = Environment,93 P extends string = '/'94 > extends defineDynamicClass()<E, P, Hono<E, P>> {95 readonly router: Router<Handler<string, E>> = new SmartRouter({96- routers: [new StaticRouter(), new RegExpRouter({ allowAmbiguous: false }), new TrieRouter()],96+ routers: [new StaticRouter(), new RegExpRouter(), new TrieRouter()],97 })98 readonly strict: boolean = true // strict routing - default is true99 private _tempPath: string = ''100 private path: string = '/'163 unmodified lines