feat: RegExpRouter (#109)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* Make the Router abstract class. * Introduce RegExpRouter. * Add RegExpRouter to benchmark target. * Optimize for special short routes. ``` * "*" * "/path/to/*" * "/path/to/*/content" ``` * Add assertion to `add` method.
authored by Taku Amano · committed by GitHub · parent ea329b8 · Browse files · 10 files·+407 added−44 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+407 added−44 removed
- tests:+73 added−3 removed
- other:+334 added−41 removed
Provenance
- Commit
92513d0- Tree
ab44ec7- Author
Taku Amano <taku@taaas.jp>- Committer
GitHub <noreply@github.com>- Parent
ea329b8
10 files changed+407 added−44 removed
modified:benchmarks/handle-event/index.js+29 added-18 removed
1234567891011111213141516171819202122232425262712131415161718192021222324252627282930293132333435363738394069 unmodified lines1101111121131141151161171181198 unmodified lines12812913013113213313413513613713812 unmodified linesimport Benchmark from 'benchmark'import { makeEdgeEnv } from 'edge-mock'import { Hono } from '../../dist/index'import { RegExpRouter } from '../../dist/router/reg-exp-router'import itty from 'itty-router'const { Router: IttyRouter } = ittyimport { Router as SunderRouter, Sunder } from 'sunder'import { Router as WorktopRouter } from 'worktop'
makeEdgeEnv()
const hono = new Hono()hono.get('/user', () => new Response('User'))hono.get('/user/comments', () => new Response('User Comments'))hono.get('/user/avatar', () => new Response('User Avatar'))hono.get('/user/lookup/email/:address', () => new Response('User Lookup Email Address'))hono.get('/event/:id', () => new Response('Event'))hono.get('/event/:id/comments', () => new Response('Event Comments'))hono.post('/event/:id/comments', () => new Response('POST Event Comments'))hono.post('/status', () => new Response('Status'))hono.get('/very/deeply/nested/route/hello/there', () => new Response('Very Deeply Nested Route'))//hono.get('/static/*', () => new Response('Static'))hono.get('/user/lookup/username/:username', (c) => { return new Response(`Hello ${c.req.param('username')}`, { status: 200, headers: { 'Content-Type': 'text/plain;charset=UTF-8', },const initHono = (hono) => { hono.get('/user', () => new Response('User')) hono.get('/user/comments', () => new Response('User Comments')) hono.get('/user/avatar', () => new Response('User Avatar')) hono.get('/user/lookup/email/:address', () => new Response('User Lookup Email Address')) hono.get('/event/:id', () => new Response('Event')) hono.get('/event/:id/comments', () => new Response('Event Comments')) hono.post('/event/:id/comments', () => new Response('POST Event Comments')) hono.post('/status', () => new Response('Status')) hono.get('/very/deeply/nested/route/hello/there', () => new Response('Very Deeply Nested Route')) //hono.get('/static/*', () => new Response('Static')) hono.get('/user/lookup/username/:username', (c) => { return new Response(`Hello ${c.req.param('username')}`, { status: 200, headers: { 'Content-Type': 'text/plain;charset=UTF-8', }, }) })}) return hono}
const hono = initHono(new Hono())const honoWithRegExpRouter = initHono(new Hono({routerClass: RegExpRouter}))
const ittyRouter = IttyRouter()ittyRouter.get('/user', () => new Response('User'))ittyRouter.get('/user/comments', () => new Response('User Comments'))ittyRouter.get('/user/avatar', () => new Response('User Avatar'))69 unmodified lines
const fn = async () => { let res = await hono.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()) res = await sunderApp.handle(event) console.log(await res.text())8 unmodified lines .add('hono', async () => { // hono.matchRoute('GET', '/user/lookup/username/hey') await hono.handleEvent(event) }) .add('hono with RegExpRouter', async () => { await honoWithRegExpRouter.handleEvent(event) }) .add('itty-router', async () => { await ittyRouter.handle(event.request) }) .add('sunder', async () => {12 unmodified linesadded:src/router/reg-exp-router/index.ts+1 added
1export { RegExpRouter } from './router'added:src/router/reg-exp-router/node.ts+110 added
1+const LABEL_REG_EXP_STR = '[^/]+'2+const ONLY_WILDCARD_REG_EXP_STR = '.*'3+const TAIL_WILDCARD_REG_EXP_STR = '(?:|/.*)'4+5+export interface ParamMap {6+ [key: string]: number7+}8+export interface Context {9+ varIndex: number10+}11+12+/**13+ * Sort order:14+ * 1. literal15+ * 2. special pattern (e.g. :label{[0-9]+})16+ * 3. common label pattern (e.g. :label)17+ * 4. wildcard18+ */19+function compareKey(a: string, b: string): number {20+ if (a.length === 1) {21+ return b.length === 1 ? (a < b ? -1 : 1) : -122+ }23+ if (b.length === 1) {24+ return 125+ }26+27+ // wildcard28+ if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {29+ return 130+ } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {31+ return -132+ }33+34+ // label35+ if (a === LABEL_REG_EXP_STR) {36+ return 137+ } else if (b === LABEL_REG_EXP_STR) {38+ return -139+ }40+41+ return a.length === b.length ? (a < b ? -1 : 1) : b.length - a.length42+}43+44+export class Node {45+ index?: number46+ varIndex?: number47+ children: {48+ [key: string]: Node49+ } = {}50+51+ insert(tokens: readonly string[], index: number, paramMap: ParamMap, context: Context): void {52+ if (tokens.length === 0) {53+ this.index = index54+ return55+ }56+57+ const [token, ...restTokens] = tokens58+ const pattern =59+ token === '*'60+ ? restTokens.length === 061+ ? ['', '', ONLY_WILDCARD_REG_EXP_STR] // '*' matches to all the trailing paths62+ : ['', '', LABEL_REG_EXP_STR]63+ : token === '/*'64+ ? ['', '', TAIL_WILDCARD_REG_EXP_STR] // '/path/to/*' is /\/path\/to(?:|/.*)$65+ : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/)66+67+ let node68+ if (pattern) {69+ const name = pattern[1]70+ const regexpStr = pattern[2] || LABEL_REG_EXP_STR71+72+ node = this.children[regexpStr]73+ if (!node) {74+ node = this.children[regexpStr] = new Node()75+ if (name !== '') {76+ node.varIndex = context.varIndex++77+ }78+ }79+ if (name !== '') {80+ paramMap[name] = node.varIndex81+ }82+ } else {83+ node = this.children[token] ||= new Node()84+ }85+86+ node.insert(restTokens, index, paramMap, context)87+ }88+89+ buildRegExpStr(): string {90+ const strList = Object.keys(this.children)91+ .sort(compareKey)92+ .map((k) => {93+ const c = this.children[k]94+ return (typeof c.varIndex === 'number' ? `(${k})@${c.varIndex}` : k) + c.buildRegExpStr()95+ })96+97+ if (typeof this.index === 'number') {98+ strList.push(`#${this.index}`)99+ }100+101+ if (strList.length === 0) {102+ return ''103+ }104+ if (strList.length === 1) {105+ return strList[0]106+ }107+108+ return '(?:' + strList.join('|') + ')'109+ }110+}added:src/router/reg-exp-router/router.test.ts+70 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970import { RegExpRouter } from './router'
describe('Basic Usage', () => { const router = new RegExpRouter<string>()
router.add('GET', '/hello', 'get hello') router.add('POST', '/hello', 'post hello')
it('get, post hello', async () => { let res = router.match('GET', '/hello') expect(res).not.toBeNull() expect(res.handler).toBe('get hello')
res = router.match('POST', '/hello') expect(res).not.toBeNull() expect(res.handler).toBe('post hello')
res = router.match('PUT', '/hello') expect(res).toBeNull()
res = router.match('GET', '/') expect(res).toBeNull() })})
describe('Complex', () => { let router: RegExpRouter<string> beforeEach(() => { router = new RegExpRouter<string>() })
it('Named Param', async () => { router.add('GET', '/entry/:id', 'get entry') const res = router.match('GET', '/entry/123') expect(res).not.toBeNull() expect(res.handler).toBe('get entry') expect(res.params['id']).toBe('123') })
it('Wildcard', async () => { router.add('GET', '/wild/*/card', 'get wildcard') const res = router.match('GET', '/wild/xxx/card') expect(res).not.toBeNull() expect(res.handler).toBe('get wildcard') })
it('Default', async () => { router.add('GET', '/api/abc', 'get api') router.add('GET', '/api/*', 'fallback') let res = router.match('GET', '/api/abc') expect(res).not.toBeNull() expect(res.handler).toBe('get api') res = router.match('GET', '/api/def') expect(res).not.toBeNull() expect(res.handler).toBe('fallback') })
it('Regexp', async () => { router.add('GET', '/post/:date{[0-9]+}/:title{[a-z]+}', 'get post') let res = router.match('GET', '/post/20210101/hello') expect(res).not.toBeNull() expect(res.handler).toBe('get post') expect(res.params['date']).toBe('20210101') expect(res.params['title']).toBe('hello') res = router.match('GET', '/post/onetwothree') expect(res).toBeNull() res = router.match('GET', '/post/123/123') expect(res).toBeNull() })})added:src/router/reg-exp-router/router.ts+119 added
1+import { Router, Result, METHOD_NAME_OF_ALL } from '../../router'2+import type { ParamMap, ReplacementMap } from './trie'3+import { Trie } from './trie'4+5+type Route<T> = [string, T]6+type HandlerData<T> = [T, ParamMap]7+type Matcher<T> = [RegExp | true, ReplacementMap, HandlerData<T>[]]8+9+export class RegExpRouter<T> extends Router<T> {10+ routes?: {11+ [method: string]: Route<T>[]12+ } = {}13+14+ matchers?: {15+ [method: string]: Matcher<T> | null16+ } = null17+18+ add(method: string, path: string, handler: T) {19+ if (!this.routes) {20+ throw new Error('Can not add a route since the matcher is already built.')21+ }22+23+ this.routes[method] ||= []24+ this.routes[method].push([path, handler])25+ }26+27+ match(method: string, path: string): Result<T> | null {28+ if (!this.matchers) {29+ this.buildAllMatchers()30+ }31+32+ const matcher = this.matchers[method] || this.matchers[METHOD_NAME_OF_ALL]33+ if (!matcher) {34+ return null35+ }36+37+ const [regexp, replacementMap, handlers] = matcher38+ if (regexp === true) {39+ // '*'40+ return new Result(handlers[0][0], {})41+ }42+43+ const match = path.match(regexp)44+ if (!match) {45+ return null46+ }47+ if (!replacementMap) {48+ // there is only one route and no capture49+ return new Result(handlers[0][0], {})50+ }51+52+ const index = match.indexOf('', 1)53+ const [handler, paramMap] = handlers[replacementMap[index]]54+ const params: { [key: string]: string } = {}55+ const keys = Object.keys(paramMap)56+ for (let i = 0; i < keys.length; i++) {57+ params[keys[i]] = match[paramMap[keys[i]]]58+ }59+ return new Result(handler, params)60+ }61+62+ private buildAllMatchers() {63+ this.matchers ||= {}64+65+ Object.keys(this.routes).forEach((method) => {66+ this.buildMatcher(method)67+ })68+69+ delete this.routes // to reduce memory usage70+ }71+72+ private buildMatcher(method: string) {73+ this.matchers ||= {}74+75+ const trie = new Trie()76+ const handlers: HandlerData<T>[] = []77+78+ const targetMethods = [method]79+ if (method !== METHOD_NAME_OF_ALL) {80+ targetMethods.unshift(METHOD_NAME_OF_ALL)81+ }82+ const routes = targetMethods.flatMap((method) => this.routes[method] || [])83+84+ if (routes.length === 0) {85+ this.matchers[method] = null86+ return87+ }88+89+ if (routes.length === 1 && routes[0][0] === '*') {90+ this.matchers[method] = [true, null, [[routes[0][1], {}]]]91+ return92+ }93+94+ if (routes.length === 1 && !routes[0][0].match(/:/)) {95+ // there is only one route and no capture96+ const tmp = routes[0][0].endsWith('*')97+ ? routes[0][0].replace(/\/\*$/, '(?:$|/)') // /path/to/* => /path/to(?:$|/)98+ : `${routes[0][0]}$` // /path/to/action => /path/to/action$99+ const regExpStr = `^${tmp.replace(/\*/g, '[^/]+')}` // /prefix/*/path/to => /prefix/[^/]+/path/to100+ this.matchers[method] = [new RegExp(regExpStr), null, [[routes[0][1], {}]]]101+ return102+ }103+104+ for (let i = 0; i < routes.length; i++) {105+ const paramMap = trie.insert(routes[i][0], i)106+ handlers[i] = [routes[i][1], paramMap]107+ }108+109+ const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp()110+ for (let i = 0; i < handlers.length; i++) {111+ const paramMap = handlers[i][1]112+ Object.keys(paramMap).forEach((k) => {113+ paramMap[k] = paramReplacementMap[paramMap[k]]114+ })115+ }116+117+ this.matchers[method] = [new RegExp(regexp), indexReplacementMap, handlers]118+ }119+}added:src/router/reg-exp-router/trie.ts+47 added
1+import type { ParamMap, Context } from './node'2+import { Node } from './node'3+4+export type { ParamMap } from './node'5+export type ReplacementMap = number[]6+7+export class Trie {8+ context: Context = { varIndex: 0 }9+ root: Node = new Node()10+11+ insert(path: string, index: number): ParamMap {12+ const paramMap = {}13+14+ /**15+ * - pattern (:label, :label{0-9]+}, ...)16+ * - /* wildcard17+ * - character18+ */19+ const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g)20+ this.root.insert(tokens, index, paramMap, this.context)21+22+ return paramMap23+ }24+25+ buildRegExp(): [RegExp, ReplacementMap, ReplacementMap] {26+ let regexp = this.root.buildRegExpStr()27+28+ let captureIndex = 029+ const indexReplacementMap: ReplacementMap = []30+ const paramReplacementMap: ReplacementMap = []31+32+ regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {33+ if (typeof handlerIndex !== 'undefined') {34+ indexReplacementMap[++captureIndex] = Number(handlerIndex)35+ return '$()'36+ }37+ if (typeof paramIndex !== 'undefined') {38+ paramReplacementMap[Number(paramIndex)] = ++captureIndex39+ return ''40+ }41+42+ return ''43+ })44+45+ return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap]46+ }47+}modified:src/hono.ts+12 added-12 removed
1-import type { Result } from './node'2-import { Node, METHOD_NAME_OF_ALL } from './node'1+import { Node } from './node'2 import { compose } from './compose'3 import { getPathFromURL, mergePath } from './utils/url'4 import { Context } from './context'5 import type { Env } from './context'6+import type { Result } from './router'7+import { Router, METHOD_NAME_OF_ALL } from './router'8 9 declare global {10 interface Request<ParamKeyType = string> {11 param: (key: ParamKeyType) => string22 unmodified lines34 type ParamKeys<Path> = Path extends `${infer Component}/${infer Rest}`35 ? ParamKey<Component> | ParamKeys<Rest>36 : ParamKey<Path>37 37-export class Router<T> {38+export class TrieRouter<T> extends Router<T> {39 node: Node<T>40 41 constructor() {42+ super()43 this.node = new Node()44 }45 46 add(method: string, path: string, handler: T) {4 unmodified lines51 return this.node.search(method, path)52 }53 }54 53-type Init = {54- strict?: boolean55-}56-55 export class Hono {56+ routerClass: { new (): Router<any> } = TrieRouter57+ strict: boolean = true // strict routing - default is true58 router: Router<Handler>59 middlewareRouters: Router<MiddlewareHandler>[]60 tempPath: string61- strict: boolean61 63- constructor(init: Init = { strict: true }) {64- this.router = new Router()62+ constructor(init: Partial<Pick<Hono, 'routerClass' | 'strict'>> = {}) {63+ Object.assign(this, init)64+65+ this.router = new this.routerClass()66 this.middlewareRouters = []67 this.tempPath = null67- this.strict = init.strict // strict routing - default is true68 }69 70 /* HTTP METHODS */71 get<Path extends string>(path: Path, handler: Handler<ParamKeys<Path>>): Hono47 unmodified lines119 use(path: string, middleware: MiddlewareHandler): void {120 if (middleware.constructor.name !== 'AsyncFunction') {121 throw new TypeError('middleware must be a async function!')122 }123- const router = new Router<MiddlewareHandler>()123+ const router = new this.routerClass()124 router.add(METHOD_NAME_OF_ALL, path, middleware)125 this.middlewareRouters.push(router)126 }127 102 unmodified linesmodified:src/node.ts+1 added-11 removed
1 import type { Pattern } from './utils/url'2 import { splitPath, getPattern } from './utils/url'3+import { Result, METHOD_NAME_OF_ALL } from './router'4 4-export const METHOD_NAME_OF_ALL = 'ALL'5-6-export class Result<T> {7- handler: T8- params: Record<string, string>9- constructor(handler: T, params: Record<string, string>) {10- this.handler = handler11- this.params = params12- }13-}14-5 const noRoute = (): null => {6 return null7 }8 112 unmodified linesadded:src/router.ts+15 added
123456789101112131415export const METHOD_NAME_OF_ALL = 'ALL'
export abstract class Router<T> { abstract add(method: string, path: string, handler: T): void abstract match(method: string, path: string): Result<T> | null}
export class Result<T> { handler: T params: Record<string, string> constructor(handler: T, params: Record<string, string>) { this.handler = handler this.params = params }}modified:test/router.test.ts+3 added-3 removed
1-import { Router } from '../src/hono'1+import { TrieRouter } from '../src/hono'2 3 describe('Basic Usage', () => {4- const router = new Router<string>()4+ const router = new TrieRouter<string>()5 6 router.add('GET', '/hello', 'get hello')7 router.add('POST', '/hello', 'post hello')8 14 unmodified lines23 })24 })25 26 describe('Complex', () => {27- const router = new Router<string>()27+ const router = new TrieRouter<string>()28 29 it('Named Param', async () => {30 router.add('GET', '/entry/:id', 'get entry')31 const res = router.match('GET', '/entry/123')36 unmodified lines