Merge pull request #1117 from honojs/next
Before adoption: this commit came in with the history the project adopted, so no landing records it.
v3.2
authored by Yusuke Wada · committed by GitHub · parents 5c49f8d, 2e60647 · Browse files · 86 files·+3324 added−1187 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
86 files+3324 added−1187 removed
- tests:+1147 added−46 removed
- other:+2177 added−1141 removed
Provenance
- Commit
ec6fa09- Tree
5cefc93- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent 1
5c49f8d- Parent 2
2e60647
86 files changed+3324 added−1187 removed
added:benchmarks/routers/src/bench-includes-init.mts+108 added
1+import MedleyRouter from '@medley/router'2+import type { HTTPMethod } from 'find-my-way'3+import findMyWay from 'find-my-way'4+import KoaRouter from 'koa-tree-router'5+import { run, bench, group } from 'mitata'6+import TrekRouter from 'trek-router'7+import { LinearRouter } from '../../../src/router/linear-router/index.ts'8+import { RegExpRouter } from '../../../src/router/reg-exp-router/index.ts'9+import { TrieRouter } from '../../../src/router/trie-router/index.ts'10+import type { Route } from './tool.mts'11+import { routes } from './tool.mts'12+13+const benchRoutes: (Route & { name: string })[] = [14+ {15+ name: 'short static',16+ method: 'GET',17+ path: '/user',18+ },19+ {20+ name: 'static with same radix',21+ method: 'GET',22+ path: '/user/comments',23+ },24+ {25+ name: 'dynamic route',26+ method: 'GET',27+ path: '/user/lookup/username/hey',28+ },29+ {30+ name: 'mixed static dynamic',31+ method: 'GET',32+ path: '/event/abcd1234/comments',33+ },34+ {35+ name: 'post',36+ method: 'POST',37+ path: '/event/abcd1234/comment',38+ },39+ {40+ name: 'long static',41+ method: 'GET',42+ path: '/very/deeply/nested/route/hello/there',43+ },44+ {45+ name: 'wildcard',46+ method: 'GET',47+ path: '/static/index.html',48+ },49+]50+51+for (const benchRoute of benchRoutes) {52+ group(`${benchRoute.method} ${benchRoute.path}`, () => {53+ bench('RegExpRouter', () => {54+ const router = new RegExpRouter()55+ for (const route of routes) {56+ router.add(route.method, route.path, () => {})57+ }58+ router.match(benchRoute.method, benchRoute.path)59+ })60+ bench('TrieRouter', () => {61+ const router = new TrieRouter()62+ for (const route of routes) {63+ router.add(route.method, route.path, () => {})64+ }65+ router.match(benchRoute.method, benchRoute.path)66+ })67+ bench('LinearRouter', () => {68+ const router = new LinearRouter()69+ for (const route of routes) {70+ router.add(route.method, route.path, () => {})71+ }72+ router.match(benchRoute.method, benchRoute.path)73+ })74+ bench('MedleyRouter', () => {75+ const router = new MedleyRouter()76+ for (const route of routes) {77+ const store = router.register(route.path)78+ store[route.method] = () => {}79+ }80+ const match = router.find(benchRoute.path)81+ match.store[benchRoute.method] // get handler82+ })83+ bench('FindMyWay', () => {84+ const router = findMyWay()85+ for (const route of routes) {86+ router.on(route.method as HTTPMethod, route.path, () => {})87+ }88+ router.find(benchRoute.method as HTTPMethod, benchRoute.path)89+ })90+ bench('KoaTreeRouter', () => {91+ const router = new KoaRouter()92+ for (const route of routes) {93+ router.on(route.method, route.path.replace('*', '*foo'), () => {})94+ }95+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment96+ // @ts-ignore97+ router.find(benchRoute.method, benchRoute.path)98+ })99+ bench('TrekRouter', () => {100+ const router = new TrekRouter()101+ for (const route of routes) {102+ router.add(route.method, route.path, () => {})103+ }104+ router.find(benchRoute.method, benchRoute.path)105+ })106+ })107+}108+await run()modified:benchmarks/routers/package.json+4 added-2 removed
1234456789106 unmodified lines171819201921{ "scripts": { "bench:node": "tsx ./src/bench.mts", "bench:bun": "bun run ./src/bench.mts" "bench:bun": "bun run ./src/bench.mts", "bench-includes-init:node": "tsx ./src/bench-includes-init.mts", "bench-includes-init:bun": "bun run ./src/bench-includes-init.mts" }, "license": "MIT", "devDependencies": { "tsx": "^3.12.2"6 unmodified lines "koa-tree-router": "^0.12.1", "mitata": "^0.1.6", "trek-router": "^1.2.0" }}No newline at end of file}modified:benchmarks/routers/README.md+1 added-1 removed
23 unmodified lines2425262728282930313223 unmodified lines```yarn bench:bun```
This project heavily impaired by [delvedor/router-benchmark](https://github.com/delvedor/router-benchmark)This project is heavily impaired by [delvedor/router-benchmark](https://github.com/delvedor/router-benchmark)
## License
MITadded:benchmarks/routers-deno/.vscode/settings.json+12 added
123456789101112{ "eslint.validate": [ "javascript", "javascriptreact", "typescript", "typescriptreact" ], "editor.codeActionsOnSave": { "source.fixAll.eslint": true }, "deno.enable": true}No newline at end of fileadded:benchmarks/routers-deno/src/bench.mts+81 added
1+import { run, bench, group } from 'npm:mitata'2+import { findMyWayRouter } from './find-my-way.mts'3+import { regExpRouter, trieRouter, patternRouter } from './hono.mts'4+import { koaRouter } from './koa-router.mts'5+import { koaTreeRouter } from './koa-tree-router.mts'6+import { medleyRouter } from './medley-router.mts'7+import type { Route, RouterInterface } from './tool.mts'8+import { trekRouter } from './trek-router.mts'9+10+const routers: RouterInterface[] = [11+ regExpRouter,12+ trieRouter,13+ patternRouter,14+ medleyRouter,15+ findMyWayRouter,16+ koaTreeRouter,17+ trekRouter,18+ koaRouter,19+]20+21+medleyRouter.match({ method: 'GET', path: '/user' })22+23+const routes: (Route & { name: string })[] = [24+ {25+ name: 'short static',26+ method: 'GET',27+ path: '/user',28+ },29+ {30+ name: 'static with same radix',31+ method: 'GET',32+ path: '/user/comments',33+ },34+ {35+ name: 'dynamic route',36+ method: 'GET',37+ path: '/user/lookup/username/hey',38+ },39+ {40+ name: 'mixed static dynamic',41+ method: 'GET',42+ path: '/event/abcd1234/comments',43+ },44+ {45+ name: 'post',46+ method: 'POST',47+ path: '/event/abcd1234/comment',48+ },49+ {50+ name: 'long static',51+ method: 'GET',52+ path: '/very/deeply/nested/route/hello/there',53+ },54+ {55+ name: 'wildcard',56+ method: 'GET',57+ path: '/static/index.html',58+ },59+]60+61+for (const route of routes) {62+ group(`${route.name} - ${route.method} ${route.path}`, () => {63+ for (const router of routers) {64+ bench(router.name, async () => {65+ router.match(route)66+ })67+ }68+ })69+}70+71+group('all together', () => {72+ for (const router of routers) {73+ bench(router.name, async () => {74+ for (const route of routes) {75+ router.match(route)76+ }77+ })78+ }79+})80+81+await run()added:benchmarks/routers-deno/src/find-my-way.mts+18 added
123456789101112131415161718import type { HTTPMethod } from 'npm:find-my-way'import findMyWay from 'npm:find-my-way'import type { RouterInterface } from './tool.mts'import { routes, handler } from './tool.mts'
const name = 'find-my-way'const router = findMyWay()
for (const route of routes) { router.on(route.method as HTTPMethod, route.path, handler)}
export const findMyWayRouter: RouterInterface = { name, match: (route) => { router.find(route.method as HTTPMethod, route.path) },}added:benchmarks/routers-deno/src/hono.mts+22 added
12345678910111213141516171819202122import type { Router } from '../../../deno_dist/router.ts'import { RegExpRouter } from '../../../deno_dist/router/reg-exp-router/index.ts'import { TrieRouter } from '../../../deno_dist/router/trie-router/index.ts'import { PatternRouter } from '../../../deno_dist/router/pattern-router/index.ts'import type { RouterInterface } from './tool.mts'import { routes, handler } from './tool.mts'
const createHonoRouter = (name: string, router: Router<unknown>): RouterInterface => { for (const route of routes) { router.add(route.method, route.path, handler) } return { name: `Hono ${name}`, match: (route) => { router.match(route.method, route.path) }, }}
export const regExpRouter = createHonoRouter('RegExpRouter', new RegExpRouter())export const trieRouter = createHonoRouter('TrieRouter', new TrieRouter())export const patternRouter = createHonoRouter('PatternRouter', new PatternRouter())added:benchmarks/routers-deno/src/koa-router.mts+21 added
123456789101112131415161718192021import KoaRouter from 'npm:koa-router'import type { RouterInterface } from './tool.mts'import { routes, handler } from './tool.mts'
const name = 'koa-router'const router = new KoaRouter()
for (const route of routes) { if (route.method === 'GET') { router.get(route.path.replace('*', '(.*)'), handler) } else { router.post(route.path, handler) }}
export const koaRouter: RouterInterface = { name, match: (route) => { router.match(route.path, route.method) // only matching },}added:benchmarks/routers-deno/src/koa-tree-router.mts+19 added
12345678910111213141516171819import KoaRouter from 'npm:koa-tree-router'import type { RouterInterface } from './tool.mts'import { routes, handler } from './tool.mts'
const name = 'koa-tree-router'const router = new KoaRouter()
for (const route of routes) { router.on(route.method, route.path.replace('*', '*foo'), handler)}
export const koaTreeRouter: RouterInterface = { name, match: (route) => { // eslint-disable-next-line @typescript-eslint/ban-ts-comment // @ts-ignore router.find(route.method, route.path) },}added:benchmarks/routers-deno/src/medley-router.mts+19 added
12345678910111213141516171819import Router from 'npm:@medley/router'import type { RouterInterface } from './tool.mts'import { routes, handler } from './tool.mts'
const name = '@medley/router'const router = new Router()
for (const route of routes) { const store = router.register(route.path) store[route.method] = handler}
export const medleyRouter: RouterInterface = { name, match: (route) => { const match = router.find(route.path) match.store[route.method] // get handler },}added:benchmarks/routers-deno/src/tool.mts+26 added
1+export const handler = () => {}2+3+export type Route = {4+ method: 'GET' | 'POST'5+ path: string6+}7+8+export interface RouterInterface {9+ name: string10+ match: (route: Route) => unknown11+}12+13+export const routes: Route[] = [14+ { method: 'GET', path: '/user' },15+ { method: 'GET', path: '/user/comments' },16+ { method: 'GET', path: '/user/avatar' },17+ { method: 'GET', path: '/user/lookup/username/:username' },18+ { method: 'GET', path: '/user/lookup/email/:address' },19+ { method: 'GET', path: '/event/:id' },20+ { method: 'GET', path: '/event/:id/comments' },21+ { method: 'POST', path: '/event/:id/comment' },22+ { method: 'GET', path: '/map/:location/events' },23+ { method: 'GET', path: '/status' },24+ { method: 'GET', path: '/very/deeply/nested/route/hello/there' },25+ { method: 'GET', path: '/static/*' },26+]added:benchmarks/routers-deno/src/trek-router.mts+17 added
1+import TrekRouter from 'npm:trek-router'2+import type { RouterInterface } from './tool.mts'3+import { routes, handler } from './tool.mts'4+5+const name = 'trek-router'6+7+const router = new TrekRouter()8+for (const route of routes) {9+ router.add(route.method, route.path, handler())10+}11+12+export const trekRouter: RouterInterface = {13+ name,14+ match: (route) => {15+ router.find(route.method, route.path)16+ },17+}added:benchmarks/routers-deno/deno.json+5 added
1+{2+ "imports": {3+ "npm/": "https://unpkg.com/"4+ }5+}added:benchmarks/routers-deno/deno.lock+227 added
1+{2+ "version": "2",3+ "remote": {},4+ "npm": {5+ "specifiers": {6+ "@medley/router": "@medley/router@0.2.1",7+ "find-my-way": "find-my-way@7.6.0",8+ "koa-router": "koa-router@12.0.0",9+ "koa-tree-router": "koa-tree-router@0.12.1",10+ "mitata": "mitata@0.1.6",11+ "trek-router": "trek-router@1.2.0"12+ },13+ "packages": {14+ "@medley/router@0.2.1": {15+ "integrity": "sha512-mdvS1spIxmZoUbTdYmWknHtwm72WwrGNoQCDd4RTvcXJ9G6XThxeC3g+cpOf6Fw6vIERHt50pYiJpsk5XTJQ5w==",16+ "dependencies": {17+ "object-treeify": "object-treeify@1.1.33"18+ }19+ },20+ "@types/accepts@1.3.5": {21+ "integrity": "sha512-jOdnI/3qTpHABjM5cx1Hc0sKsPoYCp+DP/GJRGtDlPd7fiV9oXGGIcjW/ZOxLIvjGz8MA+uMZI9metHlgqbgwQ==",22+ "dependencies": {23+ "@types/node": "@types/node@18.16.0"24+ }25+ },26+ "@types/body-parser@1.19.2": {27+ "integrity": "sha512-ALYone6pm6QmwZoAgeyNksccT9Q4AWZQ6PvfwR37GT6r6FWUPguq6sUmNGSMV2Wr761oQoBxwGGa6DR5o1DC9g==",28+ "dependencies": {29+ "@types/connect": "@types/connect@3.4.35",30+ "@types/node": "@types/node@18.16.0"31+ }32+ },33+ "@types/connect@3.4.35": {34+ "integrity": "sha512-cdeYyv4KWoEgpBISTxWvqYsVy444DOqehiF3fM3ne10AmJ62RSyNkUnxMJXHQWRQQX2eR94m5y1IZyDwBjV9FQ==",35+ "dependencies": {36+ "@types/node": "@types/node@18.16.0"37+ }38+ },39+ "@types/content-disposition@0.5.5": {40+ "integrity": "sha512-v6LCdKfK6BwcqMo+wYW05rLS12S0ZO0Fl4w1h4aaZMD7bqT3gVUns6FvLJKGZHQmYn3SX55JWGpziwJRwVgutA==",41+ "dependencies": {}42+ },43+ "@types/cookies@0.7.7": {44+ "integrity": "sha512-h7BcvPUogWbKCzBR2lY4oqaZbO3jXZksexYJVFvkrFeLgbZjQkU4x8pRq6eg2MHXQhY0McQdqmmsxRWlVAHooA==",45+ "dependencies": {46+ "@types/connect": "@types/connect@3.4.35",47+ "@types/express": "@types/express@4.17.17",48+ "@types/keygrip": "@types/keygrip@1.0.2",49+ "@types/node": "@types/node@18.16.0"50+ }51+ },52+ "@types/express-serve-static-core@4.17.33": {53+ "integrity": "sha512-TPBqmR/HRYI3eC2E5hmiivIzv+bidAfXofM+sbonAGvyDhySGw9/PQZFt2BLOrjUUR++4eJVpx6KnLQK1Fk9tA==",54+ "dependencies": {55+ "@types/node": "@types/node@18.16.0",56+ "@types/qs": "@types/qs@6.9.7",57+ "@types/range-parser": "@types/range-parser@1.2.4"58+ }59+ },60+ "@types/express@4.17.17": {61+ "integrity": "sha512-Q4FmmuLGBG58btUnfS1c1r/NQdlp3DMfGDGig8WhfpA2YRUtEkxAjkZb0yvplJGYdF1fsQ81iMDcH24sSCNC/Q==",62+ "dependencies": {63+ "@types/body-parser": "@types/body-parser@1.19.2",64+ "@types/express-serve-static-core": "@types/express-serve-static-core@4.17.33",65+ "@types/qs": "@types/qs@6.9.7",66+ "@types/serve-static": "@types/serve-static@1.15.1"67+ }68+ },69+ "@types/http-assert@1.5.3": {70+ "integrity": "sha512-FyAOrDuQmBi8/or3ns4rwPno7/9tJTijVW6aQQjK02+kOQ8zmoNg2XJtAuQhvQcy1ASJq38wirX5//9J1EqoUA==",71+ "dependencies": {}72+ },73+ "@types/http-errors@2.0.1": {74+ "integrity": "sha512-/K3ds8TRAfBvi5vfjuz8y6+GiAYBZ0x4tXv1Av6CWBWn0IlADc+ZX9pMq7oU0fNQPnBwIZl3rmeLp6SBApbxSQ==",75+ "dependencies": {}76+ },77+ "@types/keygrip@1.0.2": {78+ "integrity": "sha512-GJhpTepz2udxGexqos8wgaBx4I/zWIDPh/KOGEwAqtuGDkOUJu5eFvwmdBX4AmB8Odsr+9pHCQqiAqDL/yKMKw==",79+ "dependencies": {}80+ },81+ "@types/koa-compose@3.2.5": {82+ "integrity": "sha512-B8nG/OoE1ORZqCkBVsup/AKcvjdgoHnfi4pZMn5UwAPCbhk/96xyv284eBYW8JlQbQ7zDmnpFr68I/40mFoIBQ==",83+ "dependencies": {84+ "@types/koa": "@types/koa@2.13.6"85+ }86+ },87+ "@types/koa@2.13.6": {88+ "integrity": "sha512-diYUfp/GqfWBAiwxHtYJ/FQYIXhlEhlyaU7lB/bWQrx4Il9lCET5UwpFy3StOAohfsxxvEQ11qIJgT1j2tfBvw==",89+ "dependencies": {90+ "@types/accepts": "@types/accepts@1.3.5",91+ "@types/content-disposition": "@types/content-disposition@0.5.5",92+ "@types/cookies": "@types/cookies@0.7.7",93+ "@types/http-assert": "@types/http-assert@1.5.3",94+ "@types/http-errors": "@types/http-errors@2.0.1",95+ "@types/keygrip": "@types/keygrip@1.0.2",96+ "@types/koa-compose": "@types/koa-compose@3.2.5",97+ "@types/node": "@types/node@18.16.0"98+ }99+ },100+ "@types/mime@3.0.1": {101+ "integrity": "sha512-Y4XFY5VJAuw0FgAqPNd6NNoV44jbq9Bz2L7Rh/J6jLTiHBSBJa9fxqQIvkIld4GsoDOcCbvzOUAbLPsSKKg+uA==",102+ "dependencies": {}103+ },104+ "@types/node@18.16.0": {105+ "integrity": "sha512-BsAaKhB+7X+H4GnSjGhJG9Qi8Tw+inU9nJDwmD5CgOmBLEI6ArdhikpLX7DjbjDRDTbqZzU2LSQNZg8WGPiSZQ==",106+ "dependencies": {}107+ },108+ "@types/qs@6.9.7": {109+ "integrity": "sha512-FGa1F62FT09qcrueBA6qYTrJPVDzah9a+493+o2PCXsesWHIn27G98TsSMs3WPNbZIEj4+VJf6saSFpvD+3Zsw==",110+ "dependencies": {}111+ },112+ "@types/range-parser@1.2.4": {113+ "integrity": "sha512-EEhsLsD6UsDM1yFhAvy0Cjr6VwmpMWqFBCb9w07wVugF7w9nfajxLuVmngTIpgS6svCnm6Vaw+MZhoDCKnOfsw==",114+ "dependencies": {}115+ },116+ "@types/serve-static@1.15.1": {117+ "integrity": "sha512-NUo5XNiAdULrJENtJXZZ3fHtfMolzZwczzBbnAeBbqBwG+LaG6YaJtuwzwGSQZ2wsCrxjEhNNjAkKigy3n8teQ==",118+ "dependencies": {119+ "@types/mime": "@types/mime@3.0.1",120+ "@types/node": "@types/node@18.16.0"121+ }122+ },123+ "depd@2.0.0": {124+ "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==",125+ "dependencies": {}126+ },127+ "fast-decode-uri-component@1.0.1": {128+ "integrity": "sha512-WKgKWg5eUxvRZGwW8FvfbaH7AXSh2cL+3j5fMGzUMCxWBJ3dV3a7Wz8y2f/uQ0e3B6WmodD3oS54jTQ9HVTIIg==",129+ "dependencies": {}130+ },131+ "fast-deep-equal@3.1.3": {132+ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==",133+ "dependencies": {}134+ },135+ "fast-querystring@1.1.1": {136+ "integrity": "sha512-qR2r+e3HvhEFmpdHMv//U8FnFlnYjaC6QKDuaXALDkw2kvHO8WDjxH+f/rHGR4Me4pnk8p9JAkRNTjYHAKRn2Q==",137+ "dependencies": {138+ "fast-decode-uri-component": "fast-decode-uri-component@1.0.1"139+ }140+ },141+ "find-my-way@7.6.0": {142+ "integrity": "sha512-H7berWdHJ+5CNVr4ilLWPai4ml7Y2qAsxjw3pfeBxPigZmaDTzF0wjJLj90xRCmGcWYcyt050yN+34OZDJm1eQ==",143+ "dependencies": {144+ "fast-deep-equal": "fast-deep-equal@3.1.3",145+ "fast-querystring": "fast-querystring@1.1.1",146+ "safe-regex2": "safe-regex2@2.0.0"147+ }148+ },149+ "http-errors@2.0.0": {150+ "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==",151+ "dependencies": {152+ "depd": "depd@2.0.0",153+ "inherits": "inherits@2.0.4",154+ "setprototypeof": "setprototypeof@1.2.0",155+ "statuses": "statuses@2.0.1",156+ "toidentifier": "toidentifier@1.0.1"157+ }158+ },159+ "inherits@2.0.4": {160+ "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==",161+ "dependencies": {}162+ },163+ "koa-compose@4.2.0": {164+ "integrity": "sha512-/Io2dpt3uU/wWkn2pkRBj3vudzsi6hMssGkREZCxLIczAIvLWy5Jw9PW7ctTxvcfXKCisbgsMLsgE1BvSZB6Kw==",165+ "dependencies": {}166+ },167+ "koa-router@12.0.0": {168+ "integrity": "sha512-zGrdiXygGYW8WvrzeGsHZvKnHs4DzyGoqJ9a8iHlRkiwuEAOAPyI27//OlhoWdgFAEIM3qbUgr0KCuRaP/TCag==",169+ "dependencies": {170+ "http-errors": "http-errors@2.0.0",171+ "koa-compose": "koa-compose@4.2.0",172+ "methods": "methods@1.1.2",173+ "path-to-regexp": "path-to-regexp@6.2.1"174+ }175+ },176+ "koa-tree-router@0.12.1": {177+ "integrity": "sha512-U/jJoV+rDFYtbaU/X6r2hcNKT7+DZs8HeXONWA7/OSIMk6/cYhoW5P9MPrjg7vHWRrmZOAiFkPoW7vtxvwLWpw==",178+ "dependencies": {179+ "@types/koa": "@types/koa@2.13.6",180+ "koa-compose": "koa-compose@4.2.0"181+ }182+ },183+ "methods@1.1.2": {184+ "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==",185+ "dependencies": {}186+ },187+ "mitata@0.1.6": {188+ "integrity": "sha512-VKQ0r3jriTOU9E2Z+mwbZrUmbg4Li4QyFfi7kfHKl6reZhGzL0AYlu3wE0VPXzIwA5xnFzmEQoBwCcNT8stUkA==",189+ "dependencies": {}190+ },191+ "object-treeify@1.1.33": {192+ "integrity": "sha512-EFVjAYfzWqWsBMRHPMAXLCDIJnpMhdWAqR7xG6M6a2cs6PMFpl/+Z20w9zDW4vkxOFfddegBKq9Rehd0bxWE7A==",193+ "dependencies": {}194+ },195+ "path-to-regexp@6.2.1": {196+ "integrity": "sha512-JLyh7xT1kizaEvcaXOQwOc2/Yhw6KZOvPf1S8401UyLk86CU79LN3vl7ztXGm/pZ+YjoyAJ4rxmHwbkBXJX+yw==",197+ "dependencies": {}198+ },199+ "ret@0.2.2": {200+ "integrity": "sha512-M0b3YWQs7R3Z917WRQy1HHA7Ba7D8hvZg6UE5mLykJxQVE2ju0IXbGlaHPPlkY+WN7wFP+wUMXmBFA0aV6vYGQ==",201+ "dependencies": {}202+ },203+ "safe-regex2@2.0.0": {204+ "integrity": "sha512-PaUSFsUaNNuKwkBijoAPHAK6/eM6VirvyPWlZ7BAQy4D+hCvh4B6lIG+nPdhbFfIbP+gTGBcrdsOaUs0F+ZBOQ==",205+ "dependencies": {206+ "ret": "ret@0.2.2"207+ }208+ },209+ "setprototypeof@1.2.0": {210+ "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",211+ "dependencies": {}212+ },213+ "statuses@2.0.1": {214+ "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==",215+ "dependencies": {}216+ },217+ "toidentifier@1.0.1": {218+ "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==",219+ "dependencies": {}220+ },221+ "trek-router@1.2.0": {222+ "integrity": "sha512-43A1krE0myUO2DV+RQBUYLwK3Q5osszQ65jFe/TFGWMnhdZx0nvq2GQXecXwIPU0weSFo1pYmHfhHHaUPPIRNg==",223+ "dependencies": {}224+ }225+ }226+ }227+}added:benchmarks/routers-deno/README.md+25 added
1+# Router benchmarks2+3+Benchmark of the most commonly used HTTP routers.4+5+Tested routes:6+7+- [find-my-way](https://github.com/delvedor/find-my-way)8+- [koa-router](https://github.com/alexmingoia/koa-router)9+- [koa-tree-router](https://github.com/steambap/koa-tree-router)10+- [trek-router](https://www.npmjs.com/package/trek-router)11+- [@medley/router](https://www.npmjs.com/package/@medley/router)12+- [Hono RegExpRouter](https://github.com/honojs/hono)13+- [Hono TrieRouter](https://github.com/honojs/hono)14+15+For Deno:16+17+```18+deno run --allow-read --allow-run src/bench.mts19+```20+21+This project is heavily impaired by [delvedor/router-benchmark](https://github.com/delvedor/router-benchmark)22+23+## License24+25+MITmodified:deno_dist/client/utils.ts-3 removed
1-import { getPathFromURL } from '../utils/url.ts'1 import type { ObjectType } from './types.ts'2 3 export const mergePath = (base: string, path: string) => {4 base = base.replace(/\/+$/, '')10 unmodified lines15 return urlString16 }17 18 export const removeIndexString = (urlSting: string) => {20- // eslint-disable-next-line @typescript-eslint/no-unused-vars21- const path = getPathFromURL(urlSting)19 return urlSting.replace(/\/index$/, '/')20 }21 22 function isObject(item: unknown): item is ObjectType {20 unmodified linesmodified:deno_dist/middleware/logger/index.ts+2 added-2 removed
1 import type { MiddlewareHandler } from '../../types.ts'2-import { getPathFromURL } from '../../utils/url.ts'2+import { getPath } from '../../utils/url.ts'3 4 enum LogPrefix {5 Outgoing = '-->',6 Incoming = '<--',49 unmodified lines56 export const logger = (fn: PrintFunc = console.log): MiddlewareHandler => {57 return async (c, next) => {58 const { method } = c.req59 // eslint-disable-next-line @typescript-eslint/no-unused-vars60- const path = getPathFromURL(c.req.url)60+ const path = getPath(c.req.raw)61 62 log(fn, LogPrefix.Incoming, method, path)63 64 const start = Date.now()6 unmodified linesadded:deno_dist/preset/quick.ts+14 added
1+import { HonoBase } from '../hono-base.ts'2+import { LinearRouter } from '../router/linear-router/index.ts'3+import type { Env } from '../types.ts'4+5+export class Hono<E extends Env = Env, S = {}, BasePath extends string = '/'> extends HonoBase<6+ E,7+ S,8+ BasePath9+> {10+ constructor(init: Partial<Pick<Hono, 'getPath'> & { strict: boolean }> = {}) {11+ super(init)12+ this.router = new LinearRouter()13+ }14+}added:deno_dist/preset/tiny.ts+14 added
1+import { HonoBase } from '../hono-base.ts'2+import { PatternRouter } from '../router/pattern-router/index.ts'3+import type { Env } from '../types.ts'4+5+export class Hono<E extends Env = Env, S = {}, BasePath extends string = '/'> extends HonoBase<6+ E,7+ S,8+ BasePath9+> {10+ constructor(init: Partial<Pick<Hono, 'getPath'> & { strict: boolean }> = {}) {11+ super(init)12+ this.router = new PatternRouter()13+ }14+}added:deno_dist/router/linear-router/index.ts+1 added
1+export { LinearRouter } from './router.ts'added:deno_dist/router/linear-router/router.ts+144 added
1+import type { Router, Result } from '../../router.ts'2+import { METHOD_NAME_ALL, UnsupportedPathError } from '../../router.ts'3+4+type RegExpMatchArrayWithIndices = RegExpMatchArray & { indices: [number, number][] }5+6+const splitPathRe = /\/(:\w+(?:{[^}]+})?)|\/[^\/\?]+|(\?)/g7+const splitByStarRe = /\*/8+export class LinearRouter<T> implements Router<T> {9+ name: string = 'LinearRouter'10+ routes: [string, string, T][] = []11+12+ add(method: string, path: string, handler: T) {13+ if (path.charCodeAt(path.length - 1) === 63) {14+ // /path/to/:label? means /path/to/:label or /path/to15+ this.routes.push([method, path.slice(0, -1), handler])16+ this.routes.push([method, path.replace(/\/[^/]+$/, ''), handler])17+ } else {18+ this.routes.push([method, path, handler])19+ }20+ }21+22+ match(method: string, path: string): Result<T> | null {23+ const handlers: T[] = []24+ const params: Record<string, string> = {}25+ ROUTES_LOOP: for (let i = 0; i < this.routes.length; i++) {26+ const [routeMethod, routePath, handler] = this.routes[i]27+ if (routeMethod !== method && routeMethod !== METHOD_NAME_ALL) {28+ continue29+ }30+ if (routePath === '*' || routePath === '/*') {31+ handlers.push(handler)32+ continue33+ }34+35+ const hasStar = routePath.indexOf('*') !== -136+ const hasLabel = routePath.indexOf(':') !== -137+ if (!hasStar && !hasLabel) {38+ if (routePath === path || routePath + '/' === path) {39+ handlers.push(handler)40+ }41+ } else if (hasStar && !hasLabel) {42+ const endsWithStar = routePath.charCodeAt(routePath.length - 1) === 4243+ const parts = (endsWithStar ? routePath.slice(0, -2) : routePath).split(splitByStarRe)44+45+ const lastIndex = parts.length - 146+ for (let j = 0, pos = 0; j < parts.length; j++) {47+ const part = parts[j]48+ const index = path.indexOf(part, pos)49+ if (index !== pos) {50+ continue ROUTES_LOOP51+ }52+ pos += part.length53+ if (j === lastIndex) {54+ if (55+ !endsWithStar &&56+ pos !== path.length &&57+ !(pos === path.length - 1 && path.charCodeAt(pos) === 47)58+ ) {59+ continue ROUTES_LOOP60+ }61+ } else {62+ const index = path.indexOf('/', pos)63+ if (index === -1) {64+ continue ROUTES_LOOP65+ }66+ pos = index67+ }68+ }69+ handlers.push(handler)70+ } else if (hasLabel && !hasStar) {71+ const localParams: Record<string, string> = {}72+ const parts = routePath.match(splitPathRe) as string[]73+74+ const lastIndex = parts.length - 175+ for (let j = 0, pos = 0; j < parts.length; j++) {76+ if (pos === -1 || pos >= path.length) {77+ continue ROUTES_LOOP78+ }79+80+ const part = parts[j]81+ if (part.charCodeAt(1) === 58) {82+ // /:label83+ let name = part.slice(2)84+ let value85+86+ if (name.charCodeAt(name.length - 1) === 125) {87+ // :label{pattern}88+ const openBracePos = name.indexOf('{')89+ const pattern = name.slice(openBracePos + 1, -1)90+ const restPath = path.slice(pos + 1)91+ const match = new RegExp(pattern, 'd').exec(restPath) as RegExpMatchArrayWithIndices92+ if (!match || match.indices[0][0] !== 0 || match.indices[0][1] === 0) {93+ continue ROUTES_LOOP94+ }95+ name = name.slice(0, openBracePos)96+ value = restPath.slice(...match.indices[0])97+ pos += match.indices[0][1] + 198+ } else {99+ let endValuePos = path.indexOf('/', pos + 1)100+ if (endValuePos === -1) {101+ if (pos + 1 === path.length) {102+ continue ROUTES_LOOP103+ }104+ endValuePos = path.length105+ }106+ value = path.slice(pos + 1, endValuePos)107+ pos = endValuePos108+ }109+110+ if (111+ (params[name] && params[name] !== value) ||112+ (localParams[name] && localParams[name] !== value)113+ ) {114+ throw new Error('Duplicate param name')115+ }116+ localParams[name] = value as string117+ } else {118+ const index = path.indexOf(part, pos)119+ if (index !== pos) {120+ continue ROUTES_LOOP121+ }122+ pos += part.length123+ }124+125+ if (j === lastIndex) {126+ if (pos !== path.length && !(pos === path.length - 1 && path.charCodeAt(pos) === 47)) {127+ continue ROUTES_LOOP128+ }129+ }130+ }131+ Object.assign(params, localParams)132+ handlers.push(handler)133+ } else if (hasLabel && hasStar) {134+ throw new UnsupportedPathError()135+ }136+ }137+ return handlers.length138+ ? {139+ handlers,140+ params,141+ }142+ : null143+ }144+}added:deno_dist/router/pattern-router/index.ts+1 added
1+export { PatternRouter } from './router.ts'added:deno_dist/router/pattern-router/router.ts+70 added
1+import type { Result, Router } from '../../router.ts'2+import { METHOD_NAME_ALL } from '../../router.ts'3+4+type Route<T> = [RegExp, string, T] // [pattern, method, handler]5+6+export class PatternRouter<T> implements Router<T> {7+ name: string = 'PatternRouter'8+ private routes: Route<T>[] = []9+ private dNames: Record<string, number> = {} // Short name of duplicatedNames10+11+ add(method: string, path: string, handler: T) {12+ const endsWithWildcard = path[path.length - 1] === '*'13+ if (endsWithWildcard) {14+ path = path.slice(0, -2)15+ }16+17+ const parts = path.match(/\/?(:\w+(?:{[^}]+})?)|\/?[^\/\?]+|(\?)/g) || []18+ if (parts[parts.length - 1] === '?') {19+ this.add(method, parts.slice(0, parts.length - 2).join(''), handler)20+ parts.pop()21+ }22+23+ for (let i = 0, len = parts.length; i < len; i++) {24+ // Check duplicated names25+ const match = parts[i].match(/^\/:([^{]+)(?:{(.*)})?/)26+ if (match) {27+ const label = match[1]28+ const pos = this.dNames[label]29+ if (typeof pos === 'number' && pos !== i) {30+ throw new Error(31+ `Duplicate param name, use another name instead of '${label}' - ${method} ${path} <--- '${label}'`32+ )33+ }34+ this.dNames[label] = i35+36+ parts[i] = `/(?<${label}>${match[2] || '[^/]+'})`37+ } else if (parts[i] === '/*') {38+ parts[i] = '/[^/]+'39+ }40+ }41+42+ this.routes.push([43+ new RegExp(`^${parts.join('')}${endsWithWildcard ? '' : '/?$'}`),44+ method,45+ handler,46+ ])47+ }48+49+ match(method: string, path: string): Result<T> | null {50+ const handlers: T[] = []51+ let params: Record<string, string> | undefined = undefined52+ for (const [pattern, routeMethod, handler] of this.routes) {53+ if (routeMethod === METHOD_NAME_ALL || routeMethod === method) {54+ const match = pattern.exec(path)55+ if (match) {56+ handlers.push(handler)57+ if (pattern.source.charCodeAt(pattern.source.length - 1) === 36) {58+ params ??= match.groups || {}59+ }60+ }61+ }62+ }63+ return handlers.length64+ ? {65+ handlers,66+ params: params || {},67+ }68+ : null69+ }70+}modified:deno_dist/router/reg-exp-router/router.ts+1 added
99 unmodified lines100 return undefined101 }102 103 export class RegExpRouter<T> implements Router<T> {104+ name: string = 'RegExpRouter'105 middleware?: Record<string, Record<string, T[]>>106 routes?: Record<string, Record<string, T[]>>107 108 constructor() {151 unmodified linesmodified:deno_dist/router/smart-router/router.ts+4 added
1 unmodified line2 import type { Router, Result } from '../../router.ts'3 import { UnsupportedPathError } from '../../router.ts'4 5 export class SmartRouter<T> implements Router<T> {6+ name: string = 'SmartRouter'7 routers: Router<T>[] = []8 routes?: [string, string, T][] = []9 10 constructor(init: Pick<SmartRouter<T>, 'routers'>) {41 unmodified lines52 // not found53 throw new Error('Fatal error')54 }55 56+ // e.g. "SmartRouter + RegExpRouter"57+ this.name = `SmartRouter + ${this.activeRouter.name}`58+59 return res || null60 }61 62 get activeRouter() {7 unmodified linesmodified:deno_dist/router/trie-router/node.ts+7 added-6 removed
105 unmodified lines106 107 return curNode108 }109 110+ // getHandlerSets110- private getHandlerSets(node: Node<T>, method: string, wildcard?: boolean): HandlerSet<T>[] {111+ private gHSets(node: Node<T>, method: string, wildcard?: boolean): HandlerSet<T>[] {112 return (node.handlerSetCache[`${method}:${wildcard ? '1' : '0'}`] ||= (() => {113 const handlerSets: HandlerSet<T>[] = []114 for (let i = 0, len = node.methods.length; i < len; i++) {115 const m = node.methods[i]28 unmodified lines144 if (nextNode) {145 if (isLast === true) {146 // '/hello/*' => match '/hello'147 if (nextNode.children['*']) {147- handlerSets.push(...this.getHandlerSets(nextNode.children['*'], method, true))148+ handlerSets.push(...this.gHSets(nextNode.children['*'], method, true))149 }149- handlerSets.push(...this.getHandlerSets(nextNode, method))150+ handlerSets.push(...this.gHSets(nextNode, method))151 matched = true152 } else {153 tempNodes.push(nextNode)154 }6 unmodified lines161 // '/hello/*/foo' => match /hello/bar/foo162 if (pattern === '*') {163 const astNode = node.children['*']164 if (astNode) {164- handlerSets.push(...this.getHandlerSets(astNode, method))165+ handlerSets.push(...this.gHSets(astNode, method))166 tempNodes.push(astNode)167 }168 continue169 }6 unmodified lines176 177 // `/js/:filename{[a-z]+.js}` => match /js/chunk/123.js178 const restPathString = parts.slice(i).join('/')179 if (matcher instanceof RegExp && matcher.test(restPathString)) {179- handlerSets.push(...this.getHandlerSets(node.children[key], method))180+ handlerSets.push(...this.gHSets(node.children[key], method))181 params[name] = restPathString182 continue183 }184 185 if (matcher === true || (matcher instanceof RegExp && matcher.test(part))) {186 if (typeof key === 'string') {187 if (isLast === true) {187- handlerSets.push(...this.getHandlerSets(node.children[key], method))188+ handlerSets.push(...this.gHSets(node.children[key], method))189 } else {190 tempNodes.push(node.children[key])191 }192 }36 unmodified linesmodified:deno_dist/router/trie-router/router.ts+1 added
1 unmodified line2 import { checkOptionalParameter } from '../../utils/url.ts'3 import { Node } from './node.ts'4 5 export class TrieRouter<T> implements Router<T> {6+ name: string = 'TrieRouter'7 node: Node<T>8 9 constructor() {10 this.node = new Node()18 unmodified linesmodified:deno_dist/utils/cookie.ts+3 added-1 removed
1+import { decodeURIComponent_ } from './url.ts'2+3 export type Cookie = Record<string, string>4 export type CookieOptions = {5 domain?: string6 expires?: Date9 unmodified lines16 const pairs = cookie.split(/;\s*/g)17 const parsedCookie: Cookie = {}18 for (let i = 0, len = pairs.length; i < len; i++) {19 const pair = pairs[i].split(/\s*=\s*([^\s]+)/)18- parsedCookie[pair[0]] = decodeURIComponent(pair[1])20+ parsedCookie[pair[0]] = decodeURIComponent_(pair[1])21 }22 return parsedCookie23 }24 34 unmodified linesmodified:deno_dist/utils/http-status.ts+1 added-120 removed
1-export const getStatusText = (statusCode: StatusCode): string => {2- const text = statuses[statusCode]3- return text4-}5-6-export type StatusCode =1+export type StatusCode = number7- | 1008- | 1019- | 10210- | 10311- | 20012- | 20113- | 20214- | 20315- | 20416- | 20517- | 20618- | 20719- | 20820- | 22621- | 30022- | 30123- | 30224- | 30325- | 30426- | 30527- | 30628- | 30729- | 30830- | 40031- | 40132- | 40233- | 40334- | 40435- | 40536- | 40637- | 40738- | 40839- | 40940- | 41041- | 41142- | 41243- | 41344- | 41445- | 41546- | 41647- | 41748- | 41849- | 42050- | 42151- | 42252- | 42353- | 42454- | 42555- | 42656- | 42857- | 42958- | 43159- | 44460- | 44961- | 45062- | 45163- | 49964- | 50065- | 50166- | 50267- | 50368- | 50469- | 50570- | 50671- | 50772- | 50873- | 50974- | 51075- | 51176- | 59877- | 59978-79-const statuses: Record<StatusCode | number, string> = {80- 100: 'Continue',81- 101: 'Switching Protocols',82- 102: 'Processing',83- 103: 'Early Hints',84- 200: 'OK',85- 201: 'Created',86- 202: 'Accepted',87- 204: 'No Content',88- 206: 'Partial Content',89- 301: 'Moved Permanently',90- 302: 'Moved Temporarily',91- 303: 'See Other',92- 304: 'Not Modified',93- 307: 'Temporary Redirect',94- 308: 'Permanent Redirect',95- 400: 'Bad Request',96- 401: 'Unauthorized',97- 402: 'Payment Required',98- 403: 'Forbidden',99- 404: 'Not Found',100- 405: 'Not Allowed',101- 406: 'Not Acceptable',102- 408: 'Request Time-out',103- 409: 'Conflict',104- 410: 'Gone',105- 411: 'Length Required',106- 412: 'Precondition Failed',107- 413: 'Request Entity Too Large',108- 414: 'Request-URI Too Large',109- 415: 'Unsupported Media Type',110- 416: 'Requested Range Not Satisfiable',111- 421: 'Misdirected Request',112- 429: 'Too Many Requests',113- 500: 'Internal Server Error',114- 501: 'Not Implemented',115- 502: 'Bad Gateway',116- 503: 'Service Temporarily Unavailable',117- 504: 'Gateway Time-out',118- 505: 'HTTP Version Not Supported',119- 507: 'Insufficient Storage',120-}modified:deno_dist/utils/url.ts+15 added-11 removed
66 unmodified lines67 68 return null69 }70 71-export const getPathFromURL = (url: string, strict: boolean = true): string => {71+export const getPath = (request: Request): string => {72+ const url = request.url73 const queryIndex = url.indexOf('?', 8)73- const result = url.substring(url.indexOf('/', 8), queryIndex === -1 ? url.length : queryIndex)74+ return url.slice(url.indexOf('/', 8), queryIndex === -1 ? undefined : queryIndex)75+}76 75- // if strict routing is false => `/hello/hey/` and `/hello/hey` are treated the same76- // default is true77- if (strict === false && /.+\/$/.test(result)) {78- return result.slice(0, -1)79- }77+export const getPathNoStrict = (request: Request): string => {78+ const result = getPath(request)79 81- return result80+ // if strict routing is false => `/hello/hey/` and `/hello/hey` are treated the same81+ return result.length > 1 && result[result.length - 1] === '/' ? result.slice(0, -1) : result82 }83 84 export const mergePath = (...paths: string[]): string => {85 let p: string = ''86 let endsWithSlash = false87 88 for (let path of paths) {89 /* ['/hey/','/say'] => ['/hey', '/say'] */90- if (p.endsWith('/')) {90+ if (p[p.length - 1] === '/') {91 p = p.slice(0, -1)92 endsWithSlash = true93 }94 95 /* ['/hey','say'] => ['/hey', '/say'] */96- if (!path.startsWith('/')) {96+ if (path[0] !== '/') {97 path = `/${path}`98 }99 100 /* ['/hey/', '/'] => `/hey/` */33 unmodified lines134 }135 if (value.includes('+')) {136 value = value.replace(/\+/g, ' ')137 }138- return value.includes('%') ? decodeURIComponent(value) : value138+ return value.includes('%') ? decodeURIComponent_(value) : value139 }140 141 const _getQueryParam = (142 url: string,85 unmodified lines228 key?: string229 ): string[] | undefined | Record<string, string[]> => {230 return _getQueryParam(url, key, true) as string[] | undefined | Record<string, string[]>231 }232+233+// `decodeURIComponent` is a long name.234+// By making it a function, we can use it commonly when minified, reducing the amount of code.235+export const decodeURIComponent_ = decodeURIComponentmodified:deno_dist/compose.ts+2 added-2 removed
66 unmodified lines67 context.res = res68 }69 return context70 })71- .catch((err) => {71+ .catch(async (err) => {72 if (err instanceof Error && context instanceof Context && onError) {73 context.error = err74- context.res = onError(err, context)74+ context.res = await onError(err, context)75 return context76 }77 throw err78 })4 unmodified linesmodified:deno_dist/context.ts+67 added-70 removed
14 unmodified lines15 passThroughOnException(): void16 }17 export interface ContextVariableMap {}18 19+interface Get<E extends Env> {20+ <Key extends keyof ContextVariableMap>(key: Key): ContextVariableMap[Key]21+ <Key extends keyof E['Variables']>(key: Key): E['Variables'][Key]22+}23+24+interface Set<E extends Env> {25+ <Key extends keyof ContextVariableMap>(key: Key, value: ContextVariableMap[Key]): void26+ <Key extends keyof E['Variables']>(key: Key, value: E['Variables'][Key]): void27+}28+29 interface NewResponse {30 (data: Data | null, status?: StatusCode, headers?: HeaderRecord): Response31 (data: Data | null, init?: ResponseInit): Response32 }25 unmodified lines58 (html: string, status?: StatusCode, headers?: HeaderRecord): Response59 (html: string, init?: ResponseInit): Response60 }61 52-type GetVariable<K, E extends Env> = K extends keyof E['Variables']53- ? E['Variables'][K]54- : K extends keyof ContextVariableMap55- ? ContextVariableMap[K]56- : unknown57-62 type ContextOptions<E extends Env> = {63 env: E['Bindings']64 executionCtx?: FetchEvent | ExecutionContext | undefined65 notFoundHandler?: NotFoundHandler<E>14 unmodified lines80 81 // eslint-disable-next-line @typescript-eslint/no-explicit-any82 private _req?: HonoRequest<any, any>83 private _status: StatusCode = 20080- private _executionCtx: FetchEvent | ExecutionContext | undefined81- private _pretty: boolean = false82- private _prettySpace: number = 284+ private _exCtx: FetchEvent | ExecutionContext | undefined // _executionCtx85+ private _pre: boolean = false // _pretty86+ private _preS: number = 2 // _prettySpace87 private _map: Record<string, unknown> | undefined84- private _headers: Headers | undefined = undefined85- private _preparedHeaders: Record<string, string> | undefined = undefined88+ private _h: Headers | undefined = undefined // _headers89+ private _pH: Record<string, string> | undefined = undefined // _preparedHeaders90 private _res: Response | undefined91 private _path: string = '/'88- private _paramData?: Record<string, string> | null92+ private _pData?: Record<string, string> | null // __paramData93 private rawRequest?: Request | null94 private notFoundHandler: NotFoundHandler<E> = () => new Response()95 96 constructor(req: Request, options?: ContextOptions<E>) {97 this.rawRequest = req98 if (options) {95- this._executionCtx = options.executionCtx99+ this._exCtx = options.executionCtx100 this._path = options.path ?? '/'97- this._paramData = options.paramData101+ this._pData = options.paramData102 this.env = options.env103 if (options.notFoundHandler) {104 this.notFoundHandler = options.notFoundHandler105 }4 unmodified lines110 if (this._req) {111 return this._req112 } else {113 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion110- this._req = new HonoRequest(this.rawRequest!, this._path, this._paramData!)114+ this._req = new HonoRequest(this.rawRequest!, this._path, this._pData!)115 this.rawRequest = undefined112- this._paramData = undefined116+ this._pData = undefined117 return this._req118 }119 }120 121 get event(): FetchEvent {118- if (this._executionCtx instanceof FetchEvent) {119- return this._executionCtx122+ if (this._exCtx instanceof FetchEvent) {123+ return this._exCtx124 } else {125 throw Error('This context has no FetchEvent')126 }127 }128 129 get executionCtx(): ExecutionContext {126- if (this._executionCtx) {127- return this._executionCtx as ExecutionContext130+ if (this._exCtx) {131+ return this._exCtx as ExecutionContext132 } else {133 throw Error('This context has no ExecutionContext')134 }135 }15 unmodified lines151 152 header = (name: string, value: string | undefined, options?: { append?: boolean }): void => {153 // Clear the header154 if (value === undefined) {151- if (this._headers) {152- this._headers.delete(name)153- } else if (this._preparedHeaders) {154- delete this._preparedHeaders[name.toLocaleLowerCase()]155+ if (this._h) {156+ this._h.delete(name)157+ } else if (this._pH) {158+ delete this._pH[name.toLocaleLowerCase()]159 }160 if (this.finalized) {161 this.res.headers.delete(name)162 }163 return164 }165 166 if (options?.append) {163- if (!this._headers) {164- this._headers = new Headers(this._preparedHeaders)165- this._preparedHeaders = {}167+ if (!this._h) {168+ this._h = new Headers(this._pH)169+ this._pH = {}170 }167- this._headers.append(name, value)171+ this._h.append(name, value)172 } else {169- if (this._headers) {170- this._headers.set(name, value)173+ if (this._h) {174+ this._h.set(name, value)175 } else {172- this._preparedHeaders ??= {}173- this._preparedHeaders[name.toLowerCase()] = value176+ this._pH ??= {}177+ this._pH[name.toLowerCase()] = value178 }179 }180 181 if (this.finalized) {8 unmodified lines190 status = (status: StatusCode): void => {191 this._status = status192 }193 190- set = <Key extends keyof E['Variables'] | keyof ContextVariableMap>(191- key: Key,192- value: GetVariable<Key, E>193- ): void => {194+ set: Set<E> = (key: string, value: unknown) => {195 this._map ||= {}196 this._map[key as string] = value197 }198 198- get = <Key extends keyof E['Variables'] | keyof ContextVariableMap>(199- key: Key200- ): GetVariable<Key, E> => {201- return this._map?.[key as string] as GetVariable<Key, E>199+ get: Get<E> = (key: string) => {200+ return this._map ? this._map[key] : undefined201 }202 203 pretty = (prettyJSON: boolean, space: number = 2): void => {205- this._pretty = prettyJSON206- this._prettySpace = space204+ this._pre = prettyJSON205+ this._preS = space206 }207 208 newResponse: NewResponse = (209 data: Data | null,210 arg?: StatusCode | ResponseInit,211 headers?: HeaderRecord212 ): Response => {213 // Optimized215- if (!headers && !this._headers && !this._res && !arg && this._status === 200) {214+ if (!headers && !this._h && !this._res && !arg && this._status === 200) {215 return new Response(data, {217- headers: this._preparedHeaders,216+ headers: this._pH,217 })218 }219 220 // Return Response immediately if arg is RequestInit.221 if (arg && typeof arg !== 'number') {222 const res = new Response(data, arg)224- const contentType = this._preparedHeaders?.['content-type']223+ const contentType = this._pH?.['content-type']224 if (contentType) {225 res.headers.set('content-type', contentType)226 }227 return res228 }229 230 const status = arg ?? this._status232- this._preparedHeaders ??= {}231+ this._pH ??= {}232 234- this._headers ??= new Headers()235- for (const [k, v] of Object.entries(this._preparedHeaders)) {236- this._headers.set(k, v)233+ this._h ??= new Headers()234+ for (const [k, v] of Object.entries(this._pH)) {235+ this._h.set(k, v)236 }237 238 if (this._res) {239 this._res.headers.forEach((v, k) => {241- this._headers?.set(k, v)240+ this._h?.set(k, v)241 })243- for (const [k, v] of Object.entries(this._preparedHeaders)) {244- this._headers.set(k, v)242+ for (const [k, v] of Object.entries(this._pH)) {243+ this._h.set(k, v)244 }245 }246 247 headers ??= {}248 for (const [k, v] of Object.entries(headers)) {249 if (typeof v === 'string') {251- this._headers.set(k, v)250+ this._h.set(k, v)251 } else {253- this._headers.delete(k)252+ this._h.delete(k)253 for (const v2 of v) {255- this._headers.append(k, v2)254+ this._h.append(k, v2)255 }256 }257 }258 259 return new Response(data, {260 status,262- headers: this._headers,261+ headers: this._h,262 })263 }264 265 body: BodyRespond = (12 unmodified lines278 headers?: HeaderRecord279 ): Response => {280 // If the header is empty, return Response immediately.281 // Content-Type will be added automatically as `text/plain`.283- if (!this._preparedHeaders) {284- if (!headers && !this._res && !this._headers && !arg) {282+ if (!this._pH) {283+ if (!headers && !this._res && !this._h && !arg) {284 return new Response(text)285 }287- this._preparedHeaders = {}286+ this._pH = {}287 }288 // If Content-Type is not set, we don't have to set `text/plain`.289 // Fewer the header values, it will be faster.291- if (this._preparedHeaders['content-type']) {292- this._preparedHeaders['content-type'] = 'text/plain; charset=UTF-8'290+ if (this._pH['content-type']) {291+ this._pH['content-type'] = 'text/plain; charset=UTF-8'292 }293 return typeof arg === 'number'294 ? this.newResponse(text, arg, headers)295 : this.newResponse(text, arg)3 unmodified lines299 object: T,300 arg?: StatusCode | RequestInit,301 headers?: HeaderRecord302 ) => {304- const body = this._pretty305- ? JSON.stringify(object, null, this._prettySpace)306- : JSON.stringify(object)307- this._preparedHeaders ??= {}308- this._preparedHeaders['content-type'] = 'application/json; charset=UTF-8'303+ const body = this._pre ? JSON.stringify(object, null, this._preS) : JSON.stringify(object)304+ this._pH ??= {}305+ this._pH['content-type'] = 'application/json; charset=UTF-8'306 return typeof arg === 'number'307 ? this.newResponse(body, arg, headers)308 : this.newResponse(body, arg)309 }15 unmodified lines325 html: string,326 arg?: StatusCode | RequestInit,327 headers?: HeaderRecord328 ): Response => {332- this._preparedHeaders ??= {}333- this._preparedHeaders['content-type'] = 'text/html; charset=UTF-8'329+ this._pH ??= {}330+ this._pH['content-type'] = 'text/html; charset=UTF-8'331 return typeof arg === 'number'332 ? this.newResponse(html, arg, headers)333 : this.newResponse(html, arg)334 }335 336 redirect = (location: string, status: StatusCode = 302): Response => {340- this._headers ??= new Headers()341- this._headers.set('Location', location)337+ this._h ??= new Headers()338+ this._h.set('Location', location)339 return this.newResponse(null, status)340 }341 342 /** @deprecated57 unmodified linesadded:deno_dist/hono-base.ts+362 added
1+import { compose } from './compose.ts'2+import { Context } from './context.ts'3+import type { ExecutionContext } from './context.ts'4+import { HTTPException } from './http-exception.ts'5+import type { Router } from './router.ts'6+import { METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE, METHODS } from './router.ts'7+import type {8+ Env,9+ ErrorHandler,10+ H,11+ HandlerInterface,12+ MiddlewareHandler,13+ MiddlewareHandlerInterface,14+ Next,15+ NotFoundHandler,16+ OnHandlerInterface,17+ TypedResponse,18+ MergePath,19+ MergeSchemaPath,20+} from './types.ts'21+import type { RemoveBlankRecord } from './utils/types.ts'22+import { getPath, getPathNoStrict, mergePath } from './utils/url.ts'23+24+type Methods = typeof METHODS[number] | typeof METHOD_NAME_ALL_LOWERCASE25+26+interface RouterRoute {27+ path: string28+ method: string29+ handler: H30+}31+32+function defineDynamicClass(): {33+ new <E extends Env = Env, S = {}, BasePath extends string = '/'>(): {34+ [M in Methods]: HandlerInterface<E, M, S, BasePath>35+ } & {36+ on: OnHandlerInterface<E, S, BasePath>37+ } & {38+ use: MiddlewareHandlerInterface<E, S, BasePath>39+ }40+} {41+ return class {} as never42+}43+44+const notFoundHandler = (c: Context) => {45+ return c.text('404 Not Found', 404)46+}47+48+const errorHandler = (err: Error, c: Context) => {49+ if (err instanceof HTTPException) {50+ return err.getResponse()51+ }52+ console.trace(err)53+ const message = 'Internal Server Error'54+ return c.text(message, 500)55+}56+57+class Hono<E extends Env = Env, S = {}, BasePath extends string = '/'> extends defineDynamicClass()<58+ E,59+ S,60+ BasePath61+> {62+ /*63+ This class is like an abstract class and does not have a router.64+ To use it, inherit the class and implement router in the constructor.65+ */66+ router!: Router<H>67+ readonly getPath: (request: Request) => string68+ private _basePath: string = ''69+ private path: string = '*'70+71+ routes: RouterRoute[] = []72+73+ constructor(init: Partial<Pick<Hono, 'router' | 'getPath'> & { strict: boolean }> = {}) {74+ super()75+76+ // Implementation of app.get(...handlers[]) or app.get(path, ...handlers[])77+ const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE]78+ allMethods.map((method) => {79+ this[method] = (args1: string | H, ...args: H[]) => {80+ if (typeof args1 === 'string') {81+ this.path = args182+ } else {83+ this.addRoute(method, this.path, args1)84+ }85+ args.map((handler) => {86+ if (typeof handler !== 'string') {87+ this.addRoute(method, this.path, handler)88+ }89+ })90+ // eslint-disable-next-line @typescript-eslint/no-explicit-any91+ return this as any92+ }93+ })94+95+ // Implementation of app.on(method, path, ...handlers[])96+ this.on = (method: string | string[], path: string, ...handlers: H[]) => {97+ if (!method) return this98+ this.path = path99+ for (const m of [method].flat()) {100+ handlers.map((handler) => {101+ this.addRoute(m.toUpperCase(), this.path, handler)102+ })103+ }104+ // eslint-disable-next-line @typescript-eslint/no-explicit-any105+ return this as any106+ }107+108+ // Implementation of app.use(...handlers[]) or app.get(path, ...handlers[])109+ this.use = (arg1: string | MiddlewareHandler, ...handlers: MiddlewareHandler[]) => {110+ if (typeof arg1 === 'string') {111+ this.path = arg1112+ } else {113+ handlers.unshift(arg1)114+ }115+ handlers.map((handler) => {116+ this.addRoute(METHOD_NAME_ALL, this.path, handler)117+ })118+ return this119+ }120+121+ const strict = init.strict ?? true122+ delete init.strict123+ Object.assign(this, init)124+ this.getPath ||= strict ? getPath : getPathNoStrict125+ }126+127+ private clone(): Hono<E, S, BasePath> {128+ const clone = new Hono<E, S, BasePath>({129+ router: this.router,130+ getPath: this.getPath,131+ })132+ clone.routes = this.routes133+ return clone134+ }135+136+ private notFoundHandler: NotFoundHandler = notFoundHandler137+ private errorHandler: ErrorHandler = errorHandler138+139+ route<SubPath extends string, SubEnv extends Env, SubSchema, SubBasePath extends string>(140+ path: SubPath,141+ app: Hono<SubEnv, SubSchema, SubBasePath>142+ ): Hono<E, RemoveBlankRecord<MergeSchemaPath<SubSchema, SubPath> | S>, BasePath>143+ /** @deprecated144+ * Use `basePath` instead of `route` with one argument.145+ * The `route` with one argument has been removed in v4.146+ */147+ route<SubPath extends string>(path: SubPath): Hono<E, RemoveBlankRecord<S>, BasePath>148+ route<SubPath extends string, SubEnv extends Env, SubSchema, SubBasePath extends string>(149+ path: SubPath,150+ app?: Hono<SubEnv, SubSchema, SubBasePath>151+ ): Hono<E, RemoveBlankRecord<MergeSchemaPath<SubSchema, SubPath> | S>, BasePath> {152+ const subApp = this.basePath(path)153+154+ if (!app) {155+ // eslint-disable-next-line @typescript-eslint/no-explicit-any156+ return subApp as any157+ }158+159+ app.routes.map((r) => {160+ const handler =161+ app.errorHandler === errorHandler162+ ? r.handler163+ : async (c: Context, next: Next) =>164+ (await compose<Context>([r.handler], app.errorHandler)(c, next)).res165+ subApp.addRoute(r.method, r.path, handler)166+ })167+ // eslint-disable-next-line @typescript-eslint/no-explicit-any168+ return this as any169+ }170+171+ basePath<SubPath extends string>(path: SubPath): Hono<E, S, MergePath<BasePath, SubPath>> {172+ const subApp = this.clone()173+ subApp._basePath = mergePath(this._basePath, path)174+ // eslint-disable-next-line @typescript-eslint/no-explicit-any175+ return subApp as any176+ }177+178+ onError(handler: ErrorHandler<E>) {179+ this.errorHandler = handler180+ return this181+ }182+183+ notFound(handler: NotFoundHandler<E>) {184+ this.notFoundHandler = handler185+ return this186+ }187+188+ showRoutes() {189+ const length = 8190+ this.routes.map((route) => {191+ console.log(192+ `\x1b[32m${route.method}\x1b[0m ${' '.repeat(length - route.method.length)} ${route.path}`193+ )194+ })195+ }196+197+ /**198+ * @experimental199+ * `app.mount()` is an experimental feature.200+ * The API might be changed.201+ */202+ mount(203+ path: string,204+ // eslint-disable-next-line @typescript-eslint/no-explicit-any205+ applicationHandler: (request: Request, ...args: any) => Response | Promise<Response>,206+ optionHandler?: (c: Context) => unknown207+ ): Hono<E, S, BasePath> {208+ const pathPrefixLength = mergePath(this._basePath, path).length209+ const handler: MiddlewareHandler = async (c, next) => {210+ let executionContext: ExecutionContext | undefined = undefined211+ try {212+ executionContext = c.executionCtx213+ } catch {} // Do nothing214+ const options = optionHandler ? optionHandler(c) : [c.env, executionContext]215+ const optionsArray = Array.isArray(options) ? options : [options]216+ const res = await applicationHandler(217+ new Request(new URL(c.req.path.slice(pathPrefixLength) || '/', c.req.url), c.req.raw),218+ ...optionsArray219+ )220+221+ if (res) return res222+223+ await next()224+ }225+ this.addRoute(METHOD_NAME_ALL, mergePath(path, '*'), handler)226+ return this227+ }228+229+ get routerName() {230+ this.matchRoute('GET', '/')231+ return this.router.name232+ }233+234+ private addRoute(method: string, path: string, handler: H) {235+ method = method.toUpperCase()236+ if (this._basePath) {237+ path = mergePath(this._basePath, path)238+ }239+ this.router.add(method, path, handler)240+ const r: RouterRoute = { path: path, method: method, handler: handler }241+ this.routes.push(r)242+ }243+244+ private matchRoute(method: string, path: string) {245+ return this.router.match(method, path)246+ }247+248+ private handleError(err: unknown, c: Context<E>) {249+ if (err instanceof Error) {250+ return this.errorHandler(err, c)251+ }252+ throw err253+ }254+255+ private dispatch(256+ request: Request,257+ eventOrExecutionCtx?: ExecutionContext | FetchEvent,258+ env?: E['Bindings']259+ ): Response | Promise<Response> {260+ const path = this.getPath(request)261+ const method = request.method262+263+ const result = this.matchRoute(method, path)264+ const paramData = result?.params265+266+ const c = new Context(request, {267+ env,268+ executionCtx: eventOrExecutionCtx,269+ notFoundHandler: this.notFoundHandler,270+ path,271+ paramData,272+ })273+274+ // Do not `compose` if it has only one handler275+ if (result?.handlers.length === 1) {276+ const handler = result.handlers[0]277+ let res: ReturnType<H>278+279+ try {280+ res = handler(c, async () => {})281+ if (!res) {282+ return this.notFoundHandler(c)283+ }284+ } catch (err) {285+ return this.handleError(err, c)286+ }287+288+ if (res instanceof Response) return res289+290+ if ('response' in res) {291+ res = res.response292+ }293+294+ if (res instanceof Response) return res295+296+ return (async () => {297+ let awaited: Response | TypedResponse | void298+ try {299+ awaited = await res300+ if (awaited !== undefined && 'response' in awaited) {301+ awaited = awaited['response'] as Response302+ }303+ if (!awaited) {304+ return this.notFoundHandler(c)305+ }306+ } catch (err) {307+ return this.handleError(err, c)308+ }309+ return awaited310+ })()311+ }312+313+ const handlers = result ? result.handlers : [this.notFoundHandler]314+ const composed = compose<Context>(handlers, this.errorHandler, this.notFoundHandler)315+316+ return (async () => {317+ try {318+ const tmp = composed(c)319+ const context = tmp instanceof Promise ? await tmp : tmp320+ if (!context.finalized) {321+ throw new Error(322+ 'Context is not finalized. You may forget returning Response object or `await next()`'323+ )324+ }325+ return context.res326+ } catch (err) {327+ return this.handleError(err, c)328+ }329+ })()330+ }331+332+ handleEvent = (event: FetchEvent) => {333+ return this.dispatch(event.request, event)334+ }335+336+ fetch = (request: Request, Env?: E['Bindings'] | {}, executionCtx?: ExecutionContext) => {337+ return this.dispatch(request, executionCtx, Env)338+ }339+340+ request = async (input: Request | string | URL, requestInit?: RequestInit) => {341+ if (input instanceof Request) {342+ if (requestInit !== undefined) {343+ input = new Request(input, requestInit)344+ }345+ return await this.fetch(input)346+ }347+ input = input.toString()348+ const path = /^https?:\/\//.test(input) ? input : `http://localhost${mergePath('/', input)}`349+ const req = new Request(path, requestInit)350+ return await this.fetch(req)351+ }352+353+ fire = () => {354+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment355+ // @ts-ignore356+ addEventListener('fetch', (event: FetchEvent): void => {357+ void event.respondWith(this.handleEvent(event))358+ })359+ }360+}361+362+export { Hono as HonoBase }modified:deno_dist/hono.ts+13 added-306 removed
1-import { compose } from './compose.ts'2-import { Context } from './context.ts'3-import type { ExecutionContext } from './context.ts'4-import { HTTPException } from './http-exception.ts'5-import type { Router } from './router.ts'6-import { METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE, METHODS } from './router.ts'1+import { HonoBase } from './hono-base.ts'2 import { RegExpRouter } from './router/reg-exp-router/index.ts'3 import { SmartRouter } from './router/smart-router/index.ts'4 import { TrieRouter } from './router/trie-router/index.ts'10-import type {11- Env,12- ErrorHandler,13- H,14- HandlerInterface,15- MiddlewareHandler,16- MiddlewareHandlerInterface,17- Next,18- NotFoundHandler,19- OnHandlerInterface,20- TypedResponse,21- MergePath,22- MergeSchemaPath,23-} from './types.ts'24-import type { RemoveBlankRecord } from './utils/types.ts'25-import { getPathFromURL, mergePath } from './utils/url.ts'5+import type { Env } from './types.ts'6 27-type Methods = typeof METHODS[number] | typeof METHOD_NAME_ALL_LOWERCASE28-29-interface RouterRoute {30- path: string31- method: string32- handler: H33-}34-35-function defineDynamicClass(): {36- new <E extends Env = Env, S = {}, BasePath extends string = ''>(): {37- [M in Methods]: HandlerInterface<E, M, S, BasePath>38- } & {39- on: OnHandlerInterface<E, S, BasePath>40- } & {41- use: MiddlewareHandlerInterface<E, S, BasePath>42- }43-} {44- return class {} as never45-}46-47-const notFoundHandler = (c: Context) => {48- return c.text('404 Not Found', 404)49-}50-51-const errorHandler = (err: Error, c: Context) => {52- if (err instanceof HTTPException) {53- return err.getResponse()54- }55- console.trace(err)56- const message = 'Internal Server Error'57- return c.text(message, 500)58-}59-60-export class Hono<61- E extends Env = Env,62- S = {},63- BasePath extends string = ''64-> extends defineDynamicClass()<E, S, BasePath> {65- readonly router: Router<H> = new SmartRouter({66- routers: [new RegExpRouter(), new TrieRouter()],67- })68- readonly strict: boolean = true // strict routing - default is true69- private _basePath: string = ''70- private path: string = '*'71-72- routes: RouterRoute[] = []73-74- constructor(init: Partial<Pick<Hono, 'router' | 'strict'>> = {}) {75- super()76-77- // Implementation of app.get(...handlers[]) or app.get(path, ...handlers[])78- const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE]79- allMethods.map((method) => {80- this[method] = (args1: string | H, ...args: H[]) => {81- if (typeof args1 === 'string') {82- this.path = args183- } else {84- this.addRoute(method, this.path, args1)85- }86- args.map((handler) => {87- if (typeof handler !== 'string') {88- this.addRoute(method, this.path, handler)89- }90- })91- // eslint-disable-next-line @typescript-eslint/no-explicit-any92- return this as any93- }94- })95-96- // Implementation of app.on(method, path, ...handlers[])97- this.on = (method: string | string[], path: string, ...handlers: H[]) => {98- if (!method) return this99- this.path = path100- for (const m of [method].flat()) {101- handlers.map((handler) => {102- this.addRoute(m.toUpperCase(), this.path, handler)103- })104- }105- // eslint-disable-next-line @typescript-eslint/no-explicit-any106- return this as any107- }108-109- // Implementation of app.use(...handlers[]) or app.get(path, ...handlers[])110- this.use = (arg1: string | MiddlewareHandler, ...handlers: MiddlewareHandler[]) => {111- if (typeof arg1 === 'string') {112- this.path = arg1113- } else {114- handlers.unshift(arg1)115- }116- handlers.map((handler) => {117- this.addRoute(METHOD_NAME_ALL, this.path, handler)7+export class Hono<E extends Env = Env, S = {}, BasePath extends string = '/'> extends HonoBase<8+ E,9+ S,10+ BasePath11+> {12+ constructor(init: Partial<Pick<Hono, 'router' | 'getPath'> & { strict: boolean }> = {}) {13+ super(init)14+ this.router =15+ init.router ??16+ new SmartRouter({17+ routers: [new RegExpRouter(), new TrieRouter()],18 })119- return this120- }121-122- Object.assign(this, init)19 }124-125- private clone(): Hono<E, S, BasePath> {126- const clone = new Hono<E, S, BasePath>({127- router: this.router,128- strict: this.strict,129- })130- clone.routes = this.routes131- return clone132- }133-134- private notFoundHandler: NotFoundHandler = notFoundHandler135- private errorHandler: ErrorHandler = errorHandler136-137- route<SubPath extends string, SubEnv extends Env, SubSchema, SubBasePath extends string>(138- path: SubPath,139- app: Hono<SubEnv, SubSchema, SubBasePath>140- ): Hono<E, RemoveBlankRecord<MergeSchemaPath<SubSchema, SubPath> | S>, BasePath>141- /** @deprecated142- * Use `basePath` instead of `route` with one argument.143- * The `route` with one argument has been removed in v4.144- */145- route<SubPath extends string>(path: SubPath): Hono<E, RemoveBlankRecord<S>, BasePath>146- route<SubPath extends string, SubEnv extends Env, SubSchema, SubBasePath extends string>(147- path: SubPath,148- app?: Hono<SubEnv, SubSchema, SubBasePath>149- ): Hono<E, RemoveBlankRecord<MergeSchemaPath<SubSchema, SubPath> | S>, BasePath> {150- const subApp = this.basePath(path)151-152- if (!app) {153- // eslint-disable-next-line @typescript-eslint/no-explicit-any154- return subApp as any155- }156-157- app.routes.map((r) => {158- const handler =159- app.errorHandler === errorHandler160- ? r.handler161- : async (c: Context, next: Next) =>162- (await compose<Context>([r.handler], app.errorHandler)(c, next)).res163- subApp.addRoute(r.method, r.path, handler)164- })165- // eslint-disable-next-line @typescript-eslint/no-explicit-any166- return this as any167- }168-169- basePath<SubPath extends string>(path: SubPath): Hono<E, S, MergePath<BasePath, SubPath>> {170- const subApp = this.clone()171- subApp._basePath = mergePath(this._basePath, path)172- // eslint-disable-next-line @typescript-eslint/no-explicit-any173- return subApp as any174- }175-176- onError(handler: ErrorHandler<E>) {177- this.errorHandler = handler178- return this179- }180-181- notFound(handler: NotFoundHandler<E>) {182- this.notFoundHandler = handler183- return this184- }185-186- showRoutes() {187- const length = 8188- this.routes.map((route) => {189- console.log(190- `\x1b[32m${route.method}\x1b[0m ${' '.repeat(length - route.method.length)} ${route.path}`191- )192- })193- }194-195- private addRoute(method: string, path: string, handler: H) {196- method = method.toUpperCase()197- if (this._basePath) {198- path = mergePath(this._basePath, path)199- }200- this.router.add(method, path, handler)201- const r: RouterRoute = { path: path, method: method, handler: handler }202- this.routes.push(r)203- }204-205- private matchRoute(method: string, path: string) {206- return this.router.match(method, path)207- }208-209- private handleError(err: unknown, c: Context<E>) {210- if (err instanceof Error) {211- return this.errorHandler(err, c)212- }213- throw err214- }215-216- private dispatch(217- request: Request,218- eventOrExecutionCtx?: ExecutionContext | FetchEvent,219- env?: E['Bindings']220- ): Response | Promise<Response> {221- const path = getPathFromURL(request.url, this.strict)222- const method = request.method223-224- const result = this.matchRoute(method, path)225- const paramData = result?.params226-227- const c = new Context(request, {228- env,229- executionCtx: eventOrExecutionCtx,230- notFoundHandler: this.notFoundHandler,231- path,232- paramData,233- })234-235- // Do not `compose` if it has only one handler236- if (result?.handlers.length === 1) {237- const handler = result.handlers[0]238- let res: ReturnType<H>239-240- try {241- res = handler(c, async () => {})242- if (!res) {243- return this.notFoundHandler(c)244- }245- } catch (err) {246- return this.handleError(err, c)247- }248-249- if (res instanceof Response) return res250-251- if ('response' in res) {252- res = res.response253- }254-255- if (res instanceof Response) return res256-257- return (async () => {258- let awaited: Response | TypedResponse | void259- try {260- awaited = await res261- if (awaited !== undefined && 'response' in awaited) {262- awaited = awaited['response'] as Response263- }264- if (!awaited) {265- return this.notFoundHandler(c)266- }267- } catch (err) {268- return this.handleError(err, c)269- }270- return awaited271- })()272- }273-274- const handlers = result ? result.handlers : [this.notFoundHandler]275- const composed = compose<Context>(handlers, this.errorHandler, this.notFoundHandler)276-277- return (async () => {278- try {279- const tmp = composed(c)280- const context = tmp instanceof Promise ? await tmp : tmp281- if (!context.finalized) {282- throw new Error(283- 'Context is not finalized. You may forget returning Response object or `await next()`'284- )285- }286- return context.res287- } catch (err) {288- return this.handleError(err, c)289- }290- })()291- }292-293- handleEvent = (event: FetchEvent) => {294- return this.dispatch(event.request, event)295- }296-297- fetch = (request: Request, Env?: E['Bindings'] | {}, executionCtx?: ExecutionContext) => {298- return this.dispatch(request, executionCtx, Env)299- }300-301- request = async (input: Request | string | URL, requestInit?: RequestInit) => {302- if (input instanceof Request) {303- if (requestInit !== undefined) {304- input = new Request(input, requestInit)305- }306- return await this.fetch(input)307- }308- input = input.toString()309- const path = /^https?:\/\//.test(input) ? input : `http://localhost${mergePath('/', input)}`310- const req = new Request(path, requestInit)311- return await this.fetch(req)312- }20 }modified:deno_dist/http-exception.ts+2 added-3 removed
1 import type { StatusCode } from './utils/http-status.ts'2-import { getStatusText } from './utils/http-status.ts'2 3 type HTTPExceptionOptions = {4 res?: Response5 message?: string2 unmodified lines8 export class HTTPException extends Error {9 readonly res?: Response10 readonly status: StatusCode11 constructor(status: StatusCode = 500, options?: HTTPExceptionOptions) {13- super(options?.message || getStatusText(status))12+ super(options?.message)13 this.res = options?.res14 this.status = status15 }16 getResponse(): Response {1 unmodified line18 return this.res19 }20 return new Response(this.message, {21 status: this.status,23- statusText: getStatusText(this.status),22+ statusText: this.message,23 })24 }25 }modified:deno_dist/middleware.ts+1 added
2 unmodified lines3 export * from './middleware/bearer-auth/index.ts'4 export * from './middleware/cache/index.ts'5 export * from './middleware/cookie/index.ts'6 export * from './middleware/compress/index.ts'7+export * from './middleware/cookie/index.ts'8 export * from './middleware/cors/index.ts'9 export * from './middleware/etag/index.ts'10 export * from './middleware/html/index.ts'11 export * from './middleware/jsx/index.ts'5 unmodified linesmodified:deno_dist/mod.ts+1 added
37 unmodified lines38 // Router39 export { RegExpRouter } from './router/reg-exp-router/index.ts'40 export { TrieRouter } from './router/trie-router/index.ts'41 export { SmartRouter } from './router/smart-router/index.ts'42+export { PatternRouter } from './router/pattern-router/index.ts'43 44 // Validator45 export { validator } from './validator/index.ts'46 3 unmodified linesmodified:deno_dist/README.md+14 added-13 removed
24 unmodified lines25 [](https://doc.deno.land/https/deno.land/x/hono/mod.ts)26 [](https://discord.gg/KMh2eNSdxV)27 28 Hono - _**\[炎\] means flame🔥 in Japanese**_ - is a small, simple, and ultrafast web framework for the Edges.29-It works on Cloudflare Workers, Fastly Compute@Edge, Deno, Bun, Vercel, Lagon, Node.js, and others.29+It works on any JavaScrip runtime: Cloudflare Workers, Fastly Compute@Edge, Deno, Bun, Vercel, Lagon, AWS Lambda, and Node.js.30+31 Fast, but not only fast.32 33 ```ts34 import { Hono } from 'hono'11 unmodified lines46 ```47 48 ## Features49 49-- **Ultrafast** - The routers are really fast and smart. Not using linear loops. Fast.50-- **Multi-runtime** - Works on Cloudflare Workers, Fastly Compute@Edge, Deno, Bun, Lagon, or Node.js. The same code runs on all platforms.51-- **Batteries Included** - Hono has built-in middleware, custom middleware, and third-party middleware. Batteries included.52-- **Delightful DX** - First-class TypeScript support. Now, we've got "Types".53-- **Small** - About 20kB. Zero-dependencies. Using only Web Standard API.50+- **Ultrafast** 🚀 - The router `RegExpRouter` is really fast. Not using linear loops. Fast.51+- **Lightweight** 🪶 - The `hono/tiny` preset is under 12kB. Hono has zero dependencies and uses only the Web Standard API.52+- **Multi-runtime** 🌍 - Works on Cloudflare Workers, Fastly Compute@Edge, Deno, Bun, Lagon, AWS Lambda, or Node.js. The same code runs on all platforms.53+- **Batteries Included** 🔋 - Hono has built-in middleware, custom middleware, and third-party middleware. Batteries included.54+- **Delightful DX** 🛠️ - Super clean APIs. First-class TypeScript support. Now, we've got "Types".55 56 ## Benchmarks57 58 **Hono is the fastest**, compared to other routers for Cloudflare Workers.59 60 ```60-Hono x 385,807 ops/sec ±5.02% (76 runs sampled)61-itty-router x 205,318 ops/sec ±3.63% (84 runs sampled)62-sunder x 287,198 ops/sec ±4.90% (74 runs sampled)63-worktop x 191,134 ops/sec ±3.06% (85 runs sampled)61+Hono x 402,820 ops/sec ±4.78% (80 runs sampled)62+itty-router x 212,598 ops/sec ±3.11% (87 runs sampled)63+sunder x 297,036 ops/sec ±4.76% (77 runs sampled)64+worktop x 197,345 ops/sec ±2.40% (88 runs sampled)65 Fastest is Hono65-✨ Done in 27.51s.66+✨ Done in 28.06s.67 ```68 69 ## Documentation70 20 unmodified lines91 For more details, see [docs/CONTRIBUTING.md](docs/CONTRIBUTING.md).92 93 ## Contributors94 94-Thanks to [all contributors](https://github.com/honojs/hono/graphs/contributors)! Especially, [@metrue](https://github.com/metrue) and [@usualoma](https://github.com/usualoma)!95+Thanks to [all contributors](https://github.com/honojs/hono/graphs/contributors)!96 97 ## Authors98 99 Yusuke Wada <https://github.com/yusukebe>100 100-"RegExpRouter" and "SmartRouter" are created by Taku Amano <https://github.com/usualoma>101+_RegExpRouter_, _SmartRouter_, _LinearRouter_, and _PatternRouter_ are created by Taku Amano <https://github.com/usualoma>102 103 ## License104 105 Distributed under the MIT License. See [LICENSE](LICENSE) for more information.modified:deno_dist/request.ts+7 added-7 removed
10 unmodified lines11 import type { BodyData } from './utils/body.ts'12 import type { Cookie } from './utils/cookie.ts'13 import { parse } from './utils/cookie.ts'14 import type { UnionToIntersection } from './utils/types.ts'15-import { getQueryParam, getQueryParams } from './utils/url.ts'15+import { getQueryParam, getQueryParams, decodeURIComponent_ } from './utils/url.ts'16 17 export class HonoRequest<P extends string = '/', I extends Input['out'] = {}> {18 raw: Request19 20 private paramData: Record<string, string> | undefined21- private validatedData: { [K in keyof ValidationTargets]?: {} }21+ private vData: { [K in keyof ValidationTargets]?: {} } // Short name of validatedData22 path: string23 24 constructor(25 request: Request,2 unmodified lines28 ) {29 this.raw = request30 this.path = path31 this.paramData = paramData32- this.validatedData = {}32+ this.vData = {}33 }34 35 param(key: RemoveQuestion<ParamKeys<P>>): UndefinedIfHavingQuestion<ParamKeys<P>>36 param(): UnionToIntersection<ParamKeyToRecord<ParamKeys<P>>>37 param(key?: string): unknown {38 if (this.paramData) {39 if (key) {40 const param = this.paramData[key]41- return param ? (/\%/.test(param) ? decodeURIComponent(param) : param) : undefined41+ return param ? (/\%/.test(param) ? decodeURIComponent_(param) : param) : undefined42 } else {43 const decoded: Record<string, string> = {}44 45 for (const [key, value] of Object.entries(this.paramData)) {46 if (value && typeof value === 'string') {47- decoded[key] = /\%/.test(value) ? decodeURIComponent(value) : value47+ decoded[key] = /\%/.test(value) ? decodeURIComponent_(value) : value48 }49 }50 51 return decoded86 unmodified lines138 return this.raw.formData()139 }140 141 addValidatedData(target: keyof ValidationTargets, data: {}) {142- this.validatedData[target] = data142+ this.vData[target] = data143 }144 145 valid<146 T extends keyof ValidationTargets = I extends Record<infer R, unknown>4 unmodified lines151 >(target: T): InputToDataByTarget<I, T>152 valid(): never153 valid(target?: keyof ValidationTargets) {154 if (target) {155- return this.validatedData[target] as unknown155+ return this.vData[target] as unknown156 }157 }158 159 get url() {42 unmodified linesmodified:deno_dist/router.ts+1 added
1 unmodified line2 export const METHOD_NAME_ALL_LOWERCASE = 'all' as const3 export const METHODS = ['get', 'post', 'put', 'delete', 'head', 'options', 'patch'] as const4 5 export interface Router<T> {6+ name: string7 add(method: string, path: string, handler: T): void8 match(method: string, path: string): Result<T> | null9 }10 6 unmodified linesmodified:deno_dist/types.ts+8 added-3 removed
50 unmodified lines51 | Handler<E, P, I, O>52 | MiddlewareHandler<E, P, I>53 54 export type NotFoundHandler<E extends Env = any> = (c: Context<E>) => Response | Promise<Response>55-export type ErrorHandler<E extends Env = any> = (err: Error, c: Context<E>) => Response55+export type ErrorHandler<E extends Env = any> = (56+ err: Error,57+ c: Context<E>58+) => Response | Promise<Response>59 60 ////////////////////////////////////////61 ////// //////62 ////// HandlerInterface //////133 unmodified lines196 197 export interface MiddlewareHandlerInterface<198 E extends Env = Env,199 S = {},197- BasePath extends string = ''200+ BasePath extends string = '/'201 > {202 //// app.get(...handlers[])203 (...handlers: MiddlewareHandler<E, MergePath<BasePath, ExtractKey<S>>>[]): Hono<E, S, BasePath>204 //// app.get(path, ...handlers[])9 unmodified lines214 ////// OnHandlerInterface //////215 ////// //////216 ////////////////////////////////////////217 215-export interface OnHandlerInterface<E extends Env = Env, S = {}, BasePath extends string = ''> {218+export interface OnHandlerInterface<E extends Env = Env, S = {}, BasePath extends string = '/'> {219 // app.on(method, path, handler, handler)220 <M extends string, P extends string, O = {}, I extends Input = {}>(221 method: M,222 path: P,112 unmodified lines335 : never336 337 export type MergePath<A extends string, B extends string> = A extends ''338 ? B339+ : A extends '/'340+ ? B341 : A extends `${infer P}/`342 ? B extends `/${infer Q}`343 ? `${P}/${Q}`344 : `${P}/${B}`81 unmodified linesmodified:src/adapter/cloudflare-pages/handler.ts+4 added-9 removed
18 unmodified lines19 data: Data20 }21 22 interface HandleInterface {23- <E extends Env, S extends {}, BasePath extends string>(app: Hono<E, S, BasePath>): (24- eventContext: EventContext25- ) => Response | Promise<Response>23+ // eslint-disable-next-line @typescript-eslint/no-explicit-any24+ (app: Hono<any, any, any>): (eventContext: EventContext) => Response | Promise<Response>25 /** @deprecated26 * Use `app.basePath()` to set a sub path instead of passing the second argument.27 * The `handle` will have only one argument in v4.28 */2 unmodified lines31 ) => Response | Promise<Response>32 }33 34 export const handle: HandleInterface =36- <E extends Env, S extends {}, BasePath extends string>(37- subApp: Hono<E, S, BasePath>,38- path?: string39- ) =>40- (eventContext) => {41- const app = path ? new Hono<E, S, BasePath>().route(path, subApp as never) : subApp35+ (subApp: Hono, path?: string) => (eventContext: EventContext) => {36+ const app = path ? new Hono().route(path, subApp as never) : subApp37 return app.fetch(38 eventContext.request,39 { ...eventContext.env, eventContext },40 {5 unmodified linesmodified:src/adapter/cloudflare-workers/server-static-module.ts+1 added
9 unmodified lines10 return serveStatic({11 root: options.root,12 path: options.path,13 manifest: options.manifest ? options.manifest : manifest,14+ rewriteRequestPath: options.rewriteRequestPath,15 })16 }17 18 export { module as serveStatic }modified:src/adapter/nextjs/handler.ts+10 added-12 removed
1 unmodified line2 import { Hono } from '../../hono'3 import type { Env } from '../../types'4 5 interface HandleInterface {6- <E extends Env, S extends {}, BasePath extends string>(subApp: Hono<E, S, BasePath>): (7- req: Request8- ) => Response | Promise<Response>6 /** @deprecated7+ * `hono/nextjs` will become obsolete in v4.8+ * Use `hono/vercel` instead.9+ */10+ // eslint-disable-next-line @typescript-eslint/no-explicit-any11+ (subApp: Hono<any, any, any>): (req: Request) => Response | Promise<Response>12+ /** @deprecated13 * Use `app.basePath()` to set a sub path instead of passing the second argument.14 * The `handle` will have only one argument in v4.15 */16 <E extends Env, S extends {}, BasePath extends string>(1 unmodified line18 path: string19 ): (req: Request) => Response | Promise<Response>20 }21 19-export const handle: HandleInterface =20- <E extends Env, S extends {}, BasePath extends string>(21- subApp: Hono<E, S, BasePath>,22- path?: string23- ) =>24- (req) => {25- const app = path ? new Hono<E, S, BasePath>().route(path, subApp as never) : subApp26- return app.fetch(req)27- }22+export const handle: HandleInterface = (subApp: Hono, path?: string) => (req: Request) => {23+ const app = path ? new Hono().route(path, subApp as never) : subApp24+ return app.fetch(req)25+}added:src/adapter/vercel/handler.test.ts+31 added
1+import { Hono } from '../../hono'2+import { handle } from './handler'3+4+describe('Adapter for Next.js', () => {5+ it('Should return 200 response', async () => {6+ const app = new Hono()7+ app.get('/api/foo', (c) => {8+ return c.text('/api/foo')9+ })10+ const handler = handle(app)11+ const req = new Request('http://localhost/api/foo')12+ const res = await handler(req)13+ expect(res.status).toBe(200)14+ expect(await res.text()).toBe('/api/foo')15+ })16+17+ it('Should not use `route()` if path argument is not passed', async () => {18+ const app = new Hono().basePath('/api')19+20+ app.onError((e) => {21+ throw e22+ })23+ app.get('/error', () => {24+ throw new Error('Custom Error')25+ })26+27+ const handler = handle(app)28+ const req = new Request('http://localhost/api/error')29+ expect(() => handler(req)).toThrowError('Custom Error')30+ })31+})added:src/adapter/vercel/handler.ts+7 added
1+// @denoify-ignore2+import type { Hono } from '../../hono'3+4+// eslint-disable-next-line @typescript-eslint/no-explicit-any5+export const handle = (app: Hono<any, any, any>) => (req: Request) => {6+ return app.fetch(req)7+}added:src/adapter/vercel/index.ts+2 added
1+// @denoify-ignore2+export { handle } from './handler'modified:src/client/utils.ts-3 removed
1-import { getPathFromURL } from '../utils/url'1 import type { ObjectType } from './types'2 3 export const mergePath = (base: string, path: string) => {4 base = base.replace(/\/+$/, '')10 unmodified lines15 return urlString16 }17 18 export const removeIndexString = (urlSting: string) => {20- // eslint-disable-next-line @typescript-eslint/no-unused-vars21- const path = getPathFromURL(urlSting)19 return urlSting.replace(/\/index$/, '/')20 }21 22 function isObject(item: unknown): item is ObjectType {20 unmodified linesmodified:src/middleware/logger/index.ts+2 added-2 removed
1 import type { MiddlewareHandler } from '../../types'2-import { getPathFromURL } from '../../utils/url'2+import { getPath } from '../../utils/url'3 4 enum LogPrefix {5 Outgoing = '-->',6 Incoming = '<--',49 unmodified lines56 export const logger = (fn: PrintFunc = console.log): MiddlewareHandler => {57 return async (c, next) => {58 const { method } = c.req59 // eslint-disable-next-line @typescript-eslint/no-unused-vars60- const path = getPathFromURL(c.req.url)60+ const path = getPath(c.req.raw)61 62 log(fn, LogPrefix.Incoming, method, path)63 64 const start = Date.now()6 unmodified linesadded:src/preset/quick.ts+14 added
1+import { HonoBase } from '../hono-base'2+import { LinearRouter } from '../router/linear-router'3+import type { Env } from '../types'4+5+export class Hono<E extends Env = Env, S = {}, BasePath extends string = '/'> extends HonoBase<6+ E,7+ S,8+ BasePath9+> {10+ constructor(init: Partial<Pick<Hono, 'getPath'> & { strict: boolean }> = {}) {11+ super(init)12+ this.router = new LinearRouter()13+ }14+}added:src/preset/tiny.ts+14 added
1+import { HonoBase } from '../hono-base'2+import { PatternRouter } from '../router/pattern-router'3+import type { Env } from '../types'4+5+export class Hono<E extends Env = Env, S = {}, BasePath extends string = '/'> extends HonoBase<6+ E,7+ S,8+ BasePath9+> {10+ constructor(init: Partial<Pick<Hono, 'getPath'> & { strict: boolean }> = {}) {11+ super(init)12+ this.router = new PatternRouter()13+ }14+}added:src/router/linear-router/index.ts+1 added
1+export { LinearRouter } from './router'added:src/router/linear-router/router.test.ts+297 added
1+import { LinearRouter } from './router'2+3+describe('Basic Usage', () => {4+ const router = new LinearRouter<string>()5+6+ router.add('GET', '/hello', 'get hello')7+ router.add('POST', '/hello', 'post hello')8+ router.add('PURGE', '/hello', 'purge hello')9+10+ it('get, post hello', async () => {11+ let res = router.match('GET', '/hello')12+ expect(res).not.toBeNull()13+ expect(res?.handlers).toEqual(['get hello'])14+15+ res = router.match('POST', '/hello')16+ expect(res).not.toBeNull()17+ expect(res?.handlers).toEqual(['post hello'])18+19+ res = router.match('PURGE', '/hello')20+ expect(res).not.toBeNull()21+ expect(res?.handlers).toEqual(['purge hello'])22+23+ res = router.match('PUT', '/hello')24+ expect(res).toBeNull()25+26+ res = router.match('GET', '/')27+ expect(res).toBeNull()28+ })29+})30+31+describe('Complex', () => {32+ let router: LinearRouter<string>33+ beforeEach(() => {34+ router = new LinearRouter<string>()35+ })36+37+ it('Named Param', async () => {38+ router.add('GET', '/entry/:id', 'get entry')39+ const res = router.match('GET', '/entry/123')40+ expect(res).not.toBeNull()41+ expect(res?.handlers).toEqual(['get entry'])42+ expect(res?.params['id']).toBe('123')43+ })44+45+ it('Wildcard', async () => {46+ router.add('GET', '/wild/*/card', 'get wildcard')47+48+ let res = router.match('GET', '/wild/xxx/card')49+ expect(res).not.toBeNull()50+ expect(res?.handlers).toEqual(['get wildcard'])51+52+ res = router.match('GET', '/wild/xxx/card/yyy')53+ expect(res).toBeNull()54+ })55+56+ it('Default', async () => {57+ router.add('GET', '/api/abc', 'get api')58+ router.add('GET', '/api/*', 'fallback')59+ let res = router.match('GET', '/api/abc')60+ expect(res).not.toBeNull()61+ expect(res?.handlers).toEqual(['get api', 'fallback'])62+ res = router.match('GET', '/api/def')63+ expect(res).not.toBeNull()64+ expect(res?.handlers).toEqual(['fallback'])65+ })66+67+ it('Regexp', async () => {68+ router.add('GET', '/post/:date{[0-9]+}/:title{[a-z]+}', 'get post')69+ let res = router.match('GET', '/post/20210101/hello')70+ expect(res).not.toBeNull()71+ expect(res?.handlers).toEqual(['get post'])72+ expect(res?.params['date']).toBe('20210101')73+ expect(res?.params['title']).toBe('hello')74+ res = router.match('GET', '/post/onetwothree')75+ expect(res).toBeNull()76+ res = router.match('GET', '/post/123/123')77+ expect(res).toBeNull()78+ })79+80+ it('/*', async () => {81+ router.add('GET', '/api/*', 'auth middleware')82+ router.add('GET', '/api', 'top')83+ router.add('GET', '/api/posts', 'posts')84+ router.add('GET', '/api/*', 'fallback')85+86+ let res = router.match('GET', '/api')87+ expect(res).not.toBeNull()88+ expect(res?.handlers).toEqual(['auth middleware', 'top', 'fallback'])89+90+ res = router.match('GET', '/api/posts')91+ expect(res).not.toBeNull()92+ expect(res?.handlers).toEqual(['auth middleware', 'posts', 'fallback'])93+ })94+})95+96+describe('Multi match', () => {97+ const router = new LinearRouter<string>()98+99+ describe('Blog', () => {100+ router.add('ALL', '*', 'middleware a')101+ router.add('GET', '*', 'middleware b')102+ router.add('GET', '/entry', 'get entries')103+ router.add('POST', '/entry/*', 'middleware c')104+ router.add('POST', '/entry', 'post entry')105+ router.add('GET', '/entry/:id', 'get entry')106+ router.add('GET', '/entry/:id/comment/:comment_id', 'get comment')107+ it('GET /', async () => {108+ const res = router.match('GET', '/')109+ expect(res).not.toBeNull()110+ expect(res?.handlers).toEqual(['middleware a', 'middleware b'])111+ })112+ it('GET /entry/123', async () => {113+ const res = router.match('GET', '/entry/123')114+ expect(res).not.toBeNull()115+ expect(res?.handlers).toEqual(['middleware a', 'middleware b', 'get entry'])116+ expect(res?.params['id']).toBe('123')117+ })118+ it('GET /entry/123/comment/456', async () => {119+ const res = router.match('GET', '/entry/123/comment/456')120+ expect(res).not.toBeNull()121+ expect(res?.handlers).toEqual(['middleware a', 'middleware b', 'get comment'])122+ expect(res?.params['id']).toBe('123')123+ expect(res?.params['comment_id']).toBe('456')124+ })125+ it('POST /entry', async () => {126+ const res = router.match('POST', '/entry')127+ expect(res).not.toBeNull()128+ expect(res?.handlers).toEqual(['middleware a', 'middleware c', 'post entry'])129+ })130+ it('DELETE /entry', async () => {131+ const res = router.match('DELETE', '/entry')132+ expect(res).not.toBeNull()133+ expect(res?.handlers).toEqual(['middleware a'])134+ })135+ })136+})137+138+describe('page', () => {139+ const router = new LinearRouter<string>()140+ router.add('GET', '/page', 'page')141+ router.add('ALL', '*', 'fallback') // or '*'142+ it('GET /page', async () => {143+ const res = router.match('GET', '/page')144+ expect(res?.handlers).toEqual(['page', 'fallback'])145+ })146+})147+148+describe('Optional route', () => {149+ const router = new LinearRouter<string>()150+ router.add('GET', '/api/animals/:type?', 'animals')151+ it('GET /api/animals/dog', async () => {152+ const res = router.match('GET', '/api/animals/dog')153+ expect(res?.handlers).toEqual(['animals'])154+ expect(res?.params['type']).toBe('dog')155+ })156+ it('GET /api/animals', async () => {157+ const res = router.match('GET', '/api/animals')158+ expect(res?.handlers).toEqual(['animals'])159+ expect(res?.params['type']).toBeUndefined()160+ })161+})162+163+describe('Trailing slash', () => {164+ const router = new LinearRouter<string>()165+ router.add('GET', '/book', 'GET /book')166+ router.add('GET', '/book/:id', 'GET /book/:id')167+ it('GET /book', () => {168+ const res = router.match('GET', '/book')169+ expect(res?.handlers).toEqual(['GET /book'])170+ })171+ it('GET /book/', () => {172+ const res = router.match('GET', '/book/')173+ expect(res?.handlers).toEqual(['GET /book'])174+ })175+})176+177+describe('Same path', () => {178+ const router = new LinearRouter<string>()179+ router.add('GET', '/hey', 'Middleware A')180+ router.add('GET', '/hey', 'Middleware B')181+ it('GET /hey', () => {182+ const res = router.match('GET', '/hey')183+ expect(res?.handlers).toEqual(['Middleware A', 'Middleware B'])184+ })185+})186+187+describe('Including slashes', () => {188+ const router = new LinearRouter<string>()189+ router.add('GET', '/js/:filename{[a-z0-9/]+.js}', 'any file')190+ router.add('GET', '/js/main.js', 'main.js')191+192+ it('GET /js/main.js', () => {193+ const res = router.match('GET', '/js/main.js')194+ expect(res?.handlers).toEqual(['any file', 'main.js'])195+ expect(res?.params).toEqual({ filename: 'main.js' })196+ })197+198+ it('get /js/chunk/123.js', () => {199+ const res = router.match('GET', '/js/chunk/123.js')200+ expect(res?.handlers).toEqual(['any file'])201+ expect(res?.params).toEqual({ filename: 'chunk/123.js' })202+ })203+204+ it('get /js/chunk/nest/123.js', () => {205+ const res = router.match('GET', '/js/chunk/nest/123.js')206+ expect(res?.handlers).toEqual(['any file'])207+ expect(res?.params).toEqual({ filename: 'chunk/nest/123.js' })208+ })209+})210+211+describe('REST API', () => {212+ const router = new LinearRouter<string>()213+ router.add('GET', '/users/:username{[a-z]+}', 'profile')214+ router.add('GET', '/users/:username{[a-z]+}/posts', 'posts')215+216+ it('GET /users/hono', () => {217+ const res = router.match('GET', '/users/hono')218+ expect(res).not.toBeNull()219+ expect(res?.handlers).toEqual(['profile'])220+ })221+222+ it('GET /users/hono/posts', () => {223+ const res = router.match('GET', '/users/hono/posts')224+ expect(res).not.toBeNull()225+ expect(res?.handlers).toEqual(['posts'])226+ })227+})228+229+describe('star', () => {230+ const router = new LinearRouter<string>()231+ router.add('get', '/', '/')232+ router.add('get', '/*', '/*')233+ router.add('get', '*', '*')234+235+ router.add('get', '/x', '/x')236+ router.add('get', '/x/*', '/x/*')237+238+ it('top', async () => {239+ const res = router.match('get', '/')240+ expect(res).not.toBeNull()241+ expect(res?.handlers).toEqual(['/', '/*', '*']) // => failed ['*', '/*', '/']242+ })243+244+ it('Under a certain path', async () => {245+ const res = router.match('get', '/x')246+ expect(res).not.toBeNull()247+ expect(res?.handlers).toEqual(['/*', '*', '/x', '/x/*'])248+ })249+})250+251+describe('Duplicate param name', () => {252+ it('self', () => {253+ const router = new LinearRouter<string>()254+ router.add('GET', '/:id/:id', 'foo')255+ expect(() => {256+ router.match('GET', '/123/456')257+ }).toThrowError(/Duplicate param name/)258+ })259+260+ it('parent', () => {261+ const router = new LinearRouter<string>()262+ router.add('GET', '/:id/:action', 'foo')263+ router.add('GET', '/posts/:id', 'bar')264+ expect(() => {265+ router.match('GET', '/posts/get')266+ }).toThrowError(/Duplicate param name/)267+ })268+269+ it('child', () => {270+ const router = new LinearRouter<string>()271+ router.add('GET', '/posts/:id', 'foo')272+ router.add('GET', '/:id/:action', 'bar')273+ expect(() => {274+ router.match('GET', '/posts/get')275+ }).toThrowError(/Duplicate param name/)276+ })277+})278+279+describe('Routing with a hostname', () => {280+ const router = new LinearRouter<string>()281+ router.add('get', 'www1.example.com/hello', 'www1')282+ router.add('get', 'www2.example.com/hello', 'www2')283+ it('GET www1.example.com/hello', () => {284+ const res = router.match('get', 'www1.example.com/hello')285+ expect(res).not.toBeNull()286+ expect(res?.handlers).toEqual(['www1'])287+ })288+ it('GET www2.example.com/hello', () => {289+ const res = router.match('get', 'www2.example.com/hello')290+ expect(res).not.toBeNull()291+ expect(res?.handlers).toEqual(['www2'])292+ })293+ it('GET /hello', () => {294+ const res = router.match('get', '/hello')295+ expect(res).toBeNull()296+ })297+})added:src/router/linear-router/router.ts+144 added
1+import type { Router, Result } from '../../router'2+import { METHOD_NAME_ALL, UnsupportedPathError } from '../../router'3+4+type RegExpMatchArrayWithIndices = RegExpMatchArray & { indices: [number, number][] }5+6+const splitPathRe = /\/(:\w+(?:{[^}]+})?)|\/[^\/\?]+|(\?)/g7+const splitByStarRe = /\*/8+export class LinearRouter<T> implements Router<T> {9+ name: string = 'LinearRouter'10+ routes: [string, string, T][] = []11+12+ add(method: string, path: string, handler: T) {13+ if (path.charCodeAt(path.length - 1) === 63) {14+ // /path/to/:label? means /path/to/:label or /path/to15+ this.routes.push([method, path.slice(0, -1), handler])16+ this.routes.push([method, path.replace(/\/[^/]+$/, ''), handler])17+ } else {18+ this.routes.push([method, path, handler])19+ }20+ }21+22+ match(method: string, path: string): Result<T> | null {23+ const handlers: T[] = []24+ const params: Record<string, string> = {}25+ ROUTES_LOOP: for (let i = 0; i < this.routes.length; i++) {26+ const [routeMethod, routePath, handler] = this.routes[i]27+ if (routeMethod !== method && routeMethod !== METHOD_NAME_ALL) {28+ continue29+ }30+ if (routePath === '*' || routePath === '/*') {31+ handlers.push(handler)32+ continue33+ }34+35+ const hasStar = routePath.indexOf('*') !== -136+ const hasLabel = routePath.indexOf(':') !== -137+ if (!hasStar && !hasLabel) {38+ if (routePath === path || routePath + '/' === path) {39+ handlers.push(handler)40+ }41+ } else if (hasStar && !hasLabel) {42+ const endsWithStar = routePath.charCodeAt(routePath.length - 1) === 4243+ const parts = (endsWithStar ? routePath.slice(0, -2) : routePath).split(splitByStarRe)44+45+ const lastIndex = parts.length - 146+ for (let j = 0, pos = 0; j < parts.length; j++) {47+ const part = parts[j]48+ const index = path.indexOf(part, pos)49+ if (index !== pos) {50+ continue ROUTES_LOOP51+ }52+ pos += part.length53+ if (j === lastIndex) {54+ if (55+ !endsWithStar &&56+ pos !== path.length &&57+ !(pos === path.length - 1 && path.charCodeAt(pos) === 47)58+ ) {59+ continue ROUTES_LOOP60+ }61+ } else {62+ const index = path.indexOf('/', pos)63+ if (index === -1) {64+ continue ROUTES_LOOP65+ }66+ pos = index67+ }68+ }69+ handlers.push(handler)70+ } else if (hasLabel && !hasStar) {71+ const localParams: Record<string, string> = {}72+ const parts = routePath.match(splitPathRe) as string[]73+74+ const lastIndex = parts.length - 175+ for (let j = 0, pos = 0; j < parts.length; j++) {76+ if (pos === -1 || pos >= path.length) {77+ continue ROUTES_LOOP78+ }79+80+ const part = parts[j]81+ if (part.charCodeAt(1) === 58) {82+ // /:label83+ let name = part.slice(2)84+ let value85+86+ if (name.charCodeAt(name.length - 1) === 125) {87+ // :label{pattern}88+ const openBracePos = name.indexOf('{')89+ const pattern = name.slice(openBracePos + 1, -1)90+ const restPath = path.slice(pos + 1)91+ const match = new RegExp(pattern, 'd').exec(restPath) as RegExpMatchArrayWithIndices92+ if (!match || match.indices[0][0] !== 0 || match.indices[0][1] === 0) {93+ continue ROUTES_LOOP94+ }95+ name = name.slice(0, openBracePos)96+ value = restPath.slice(...match.indices[0])97+ pos += match.indices[0][1] + 198+ } else {99+ let endValuePos = path.indexOf('/', pos + 1)100+ if (endValuePos === -1) {101+ if (pos + 1 === path.length) {102+ continue ROUTES_LOOP103+ }104+ endValuePos = path.length105+ }106+ value = path.slice(pos + 1, endValuePos)107+ pos = endValuePos108+ }109+110+ if (111+ (params[name] && params[name] !== value) ||112+ (localParams[name] && localParams[name] !== value)113+ ) {114+ throw new Error('Duplicate param name')115+ }116+ localParams[name] = value as string117+ } else {118+ const index = path.indexOf(part, pos)119+ if (index !== pos) {120+ continue ROUTES_LOOP121+ }122+ pos += part.length123+ }124+125+ if (j === lastIndex) {126+ if (pos !== path.length && !(pos === path.length - 1 && path.charCodeAt(pos) === 47)) {127+ continue ROUTES_LOOP128+ }129+ }130+ }131+ Object.assign(params, localParams)132+ handlers.push(handler)133+ } else if (hasLabel && hasStar) {134+ throw new UnsupportedPathError()135+ }136+ }137+ return handlers.length138+ ? {139+ handlers,140+ params,141+ }142+ : null143+ }144+}added:src/router/pattern-router/index.ts+1 added
1+export { PatternRouter } from './router'added:src/router/pattern-router/router.test.ts+471 added
1+import { PatternRouter } from './router'2+3+describe('Basic', () => {4+ const router = new PatternRouter<string>()5+ router.add('GET', '/hello', 'get hello')6+ router.add('POST', '/hello', 'post hello')7+ router.add('PURGE', '/hello', 'purge hello')8+9+ it('get, post, purge hello', async () => {10+ let res = router.match('GET', '/hello')11+ expect(res).not.toBeNull()12+ expect(res?.handlers).toEqual(['get hello'])13+14+ res = router.match('POST', '/hello')15+ expect(res).not.toBeNull()16+ expect(res?.handlers).toEqual(['post hello'])17+18+ res = router.match('PURGE', '/hello')19+ expect(res).not.toBeNull()20+ expect(res?.handlers).toEqual(['purge hello'])21+22+ res = router.match('PUT', '/hello')23+ expect(res).toBeNull()24+25+ res = router.match('GET', '/')26+ expect(res).toBeNull()27+ })28+})29+30+describe('Complex', () => {31+ const router = new PatternRouter<string>()32+33+ it('Named Param', async () => {34+ router.add('GET', '/entry/:id', 'get entry')35+ const res = router.match('GET', '/entry/123')36+ expect(res).not.toBeNull()37+ expect(res?.handlers).toEqual(['get entry'])38+ expect(res?.params['id']).toBe('123')39+ })40+41+ it('Wildcard', async () => {42+ router.add('GET', '/wild/*/card', 'get wildcard')43+ const res = router.match('GET', '/wild/xxx/card')44+ expect(res).not.toBeNull()45+ expect(res?.handlers).toEqual(['get wildcard'])46+ })47+48+ it('Default', async () => {49+ router.add('GET', '/api/*', 'fallback')50+ router.add('GET', '/api/abc', 'get api')51+ let res = router.match('GET', '/api/abc')52+ expect(res).not.toBeNull()53+ expect(res?.handlers).toEqual(['fallback', 'get api'])54+ res = router.match('GET', '/api/def')55+ expect(res).not.toBeNull()56+ expect(res?.handlers).toEqual(['fallback'])57+ })58+59+ it('Regexp', async () => {60+ router.add('GET', '/post/:date{[0-9]+}/:title{[a-z]+}', 'get post')61+ let res = router.match('GET', '/post/20210101/hello')62+ expect(res).not.toBeNull()63+ expect(res?.handlers).toEqual(['get post'])64+ expect(res?.params['date']).toBe('20210101')65+ expect(res?.params['title']).toBe('hello')66+ res = router.match('GET', '/post/onetwothree')67+ expect(res).toBeNull()68+ res = router.match('GET', '/post/123/123')69+ expect(res).toBeNull()70+ })71+})72+73+describe('Multi match', () => {74+ const router = new PatternRouter<string>()75+76+ describe('Blog', () => {77+ router.add('ALL', '*', 'middleware a')78+ router.add('GET', '*', 'middleware b')79+ router.add('GET', '/entry', 'get entries')80+ router.add('POST', '/entry/*', 'middleware c')81+ router.add('POST', '/entry', 'post entry')82+ router.add('GET', '/entry/:id', 'get entry')83+ router.add('GET', '/entry/:id/comment/:comment_id', 'get comment')84+ it('GET /', async () => {85+ const res = router.match('GET', '/')86+ expect(res).not.toBeNull()87+ expect(res?.handlers).toEqual(['middleware a', 'middleware b'])88+ })89+ it('GET /entry/123', async () => {90+ const res = router.match('GET', '/entry/123')91+ expect(res).not.toBeNull()92+ expect(res?.handlers).toEqual(['middleware a', 'middleware b', 'get entry'])93+ expect(res?.params['id']).toBe('123')94+ })95+ it('GET /entry/123/comment/456', async () => {96+ const res = router.match('GET', '/entry/123/comment/456')97+ expect(res).not.toBeNull()98+ expect(res?.handlers).toEqual(['middleware a', 'middleware b', 'get comment'])99+ expect(res?.params['id']).toBe('123')100+ expect(res?.params['comment_id']).toBe('456')101+ })102+ it('POST /entry', async () => {103+ const res = router.match('POST', '/entry')104+ expect(res).not.toBeNull()105+ expect(res?.handlers).toEqual(['middleware a', 'middleware c', 'post entry'])106+ })107+ it('DELETE /entry', async () => {108+ const res = router.match('DELETE', '/entry')109+ expect(res).not.toBeNull()110+ expect(res?.handlers).toEqual(['middleware a'])111+ })112+ })113+})114+115+describe('Fallback', () => {116+ const router = new PatternRouter<string>()117+ router.add('POST', '/entry', 'post entry')118+ router.add('POST', '/entry/*', 'fallback')119+ router.add('GET', '/entry/:id', 'get entry')120+ it('POST /entry', async () => {121+ const res = router.match('POST', '/entry')122+ expect(res).not.toBeNull()123+ expect(res?.handlers).toEqual(['post entry', 'fallback'])124+ })125+})126+127+describe('page', () => {128+ const router = new PatternRouter<string>()129+ router.add('GET', '/page', 'page')130+ router.add('ALL', '*', 'fallback') // or '*'131+ it('GET /page', async () => {132+ const res = router.match('GET', '/page')133+ expect(res?.handlers).toEqual(['page', 'fallback'])134+ })135+})136+137+describe('Optional route', () => {138+ const router = new PatternRouter<string>()139+ router.add('GET', '/api/animals/:type?', 'animals')140+ it('GET /api/animals/dog', async () => {141+ const res = router.match('GET', '/api/animals/dog')142+ expect(res?.handlers).toEqual(['animals'])143+ expect(res?.params['type']).toBe('dog')144+ })145+ it('GET /api/animals', async () => {146+ const res = router.match('GET', '/api/animals')147+ expect(res?.handlers).toEqual(['animals'])148+ expect(res?.params['type']).toBeUndefined()149+ })150+})151+152+describe('routing order with named parameters', () => {153+ const router = new PatternRouter<string>()154+ router.add('GET', '/book/a', 'no-slug')155+ router.add('GET', '/book/:slug', 'slug')156+ router.add('GET', '/book/b', 'no-slug-b')157+ it('GET /book/a', async () => {158+ const res = router.match('GET', '/book/a')159+ expect(res?.handlers).toEqual(['no-slug', 'slug'])160+ expect(res?.params['slug']).toBeUndefined()161+ })162+ it('GET /book/foo', async () => {163+ const res = router.match('GET', '/book/foo')164+ expect(res?.handlers).toEqual(['slug'])165+ expect(res?.params['slug']).toBe('foo')166+ })167+ it('GET /book/b', async () => {168+ const res = router.match('GET', '/book/b')169+ expect(res?.handlers).toEqual(['slug', 'no-slug-b'])170+ expect(res?.params['slug']).toBe('b')171+ })172+})173+174+describe('Trailing slash', () => {175+ const router = new PatternRouter<string>()176+ router.add('GET', '/book', 'GET /book')177+ router.add('GET', '/book/:id', 'GET /book/:id')178+ it('GET /book', () => {179+ const res = router.match('GET', '/book')180+ expect(res?.handlers).toEqual(['GET /book'])181+ })182+ it('GET /book/', () => {183+ const res = router.match('GET', '/book/')184+ expect(res?.handlers).toEqual(['GET /book'])185+ })186+})187+188+describe('Same path', () => {189+ const router = new PatternRouter<string>()190+ router.add('GET', '/hey', 'Middleware A')191+ router.add('GET', '/hey', 'Middleware B')192+ it('GET /hey', () => {193+ const res = router.match('GET', '/hey')194+ expect(res?.handlers).toEqual(['Middleware A', 'Middleware B'])195+ })196+})197+198+describe('Including slashes', () => {199+ const router = new PatternRouter<string>()200+ router.add('GET', '/js/:filename{[a-z0-9/]+.js}', 'any file')201+ router.add('GET', '/js/main.js', 'main.js')202+203+ it('GET /js/main.js', () => {204+ const res = router.match('GET', '/js/main.js')205+ expect(res?.handlers).toEqual(['any file', 'main.js'])206+ expect(res?.params).toEqual({ filename: 'main.js' })207+ })208+209+ it('get /js/chunk/123.js', () => {210+ const res = router.match('GET', '/js/chunk/123.js')211+ expect(res?.handlers).toEqual(['any file'])212+ expect(res?.params).toEqual({ filename: 'chunk/123.js' })213+ })214+215+ it('get /js/chunk/nest/123.js', () => {216+ const res = router.match('GET', '/js/chunk/nest/123.js')217+ expect(res?.handlers).toEqual(['any file'])218+ expect(res?.params).toEqual({ filename: 'chunk/nest/123.js' })219+ })220+})221+222+describe('REST API', () => {223+ const router = new PatternRouter<string>()224+ router.add('GET', '/users/:username{[a-z]+}', 'profile')225+ router.add('GET', '/users/:username{[a-z]+}/posts', 'posts')226+227+ it('GET /users/hono', () => {228+ const res = router.match('GET', '/users/hono')229+ expect(res).not.toBeNull()230+ expect(res?.handlers).toEqual(['profile'])231+ })232+233+ it('GET /users/hono/posts', () => {234+ const res = router.match('GET', '/users/hono/posts')235+ expect(res).not.toBeNull()236+ expect(res?.handlers).toEqual(['posts'])237+ })238+})239+240+describe('Duplicate param name', () => {241+ it('self', () => {242+ const router = new PatternRouter<string>()243+ expect(() => {244+ router.add('GET', '/:id/:id', 'foo')245+ }).toThrowError(/Duplicate param name/)246+ })247+248+ it('parent', () => {249+ const router = new PatternRouter<string>()250+ router.add('get', '/:id/:action', 'foo')251+ expect(() => {252+ router.add('get', '/posts/:id', 'bar')253+ }).toThrowError(/Duplicate param name/)254+ })255+256+ it('child', () => {257+ const router = new PatternRouter<string>()258+ router.add('get', '/posts/:id', 'foo')259+ expect(() => {260+ router.add('get', '/:id/:action', 'bar')261+ }).toThrowError(/Duplicate param name/)262+ })263+264+ it('hierarchy', () => {265+ const router = new PatternRouter<string>()266+ router.add('get', '/posts/:id/comments/:comment_id', 'foo')267+ expect(() => {268+ router.add('get', '/posts/:id', 'bar')269+ }).not.toThrowError()270+ })271+272+ it('regular expression', () => {273+ const router = new PatternRouter<string>()274+ router.add('get', '/:id/:action{create|update}', 'foo')275+ expect(() => {276+ router.add('get', '/:id/:action{delete}', 'bar')277+ }).not.toThrowError()278+ })279+})280+281+describe('Sort Order', () => {282+ describe('Basic', () => {283+ const router = new PatternRouter<string>()284+ router.add('get', '*', 'a')285+ router.add('get', '/page', '/page')286+ router.add('get', '/:slug', '/:slug')287+288+ it('get /page', () => {289+ const res = router.match('get', '/page')290+ expect(res?.handlers).toEqual(['a', '/page', '/:slug'])291+ })292+ })293+294+ describe('With Named path', () => {295+ const router = new PatternRouter<string>()296+ router.add('get', '*', 'a')297+ router.add('get', '/posts/:id', '/posts/:id')298+ router.add('get', '/:type/:id', '/:type/:id')299+300+ it('get /posts/123', () => {301+ const res = router.match('get', '/posts/123')302+ expect(res).not.toBeNull()303+ expect(res?.handlers).toEqual(['a', '/posts/:id', '/:type/:id'])304+ })305+ })306+307+ describe('With Wildcards', () => {308+ const router = new PatternRouter<string>()309+ router.add('get', '/api/*', '1st')310+ router.add('get', '/api/*', '2nd')311+ router.add('get', '/api/posts/:id', '3rd')312+ router.add('get', '/api/*', '4th')313+314+ it('get /api/posts/123', () => {315+ const res = router.match('get', '/api/posts/123')316+ expect(res).not.toBeNull()317+ expect(res?.handlers).toEqual(['1st', '2nd', '3rd', '4th'])318+ })319+ })320+321+ describe('With special Wildcard', () => {322+ const router = new PatternRouter<string>()323+ router.add('get', '/posts', '/posts') // 1.1324+ router.add('get', '/posts/*', '/posts/*') // 1.2325+ router.add('get', '/posts/:id', '/posts/:id') // 2.3326+327+ it('get /posts', () => {328+ const res = router.match('get', '/posts')329+330+ expect(res).not.toBeNull()331+ expect(res?.handlers).toEqual(['/posts', '/posts/*'])332+ })333+ })334+335+ describe('Complex', () => {336+ const router = new PatternRouter<string>()337+ router.add('get', '/api', 'a') // not match338+ router.add('get', '/api/*', 'b') // match339+ router.add('get', '/api/:type', 'c') // not match340+ router.add('get', '/api/:type/:id', 'd') // match341+ router.add('get', '/api/posts/:id', 'e') // match342+ router.add('get', '/api/posts/123', 'f') // match343+ router.add('get', '/*/*/:id', 'g') // match344+ router.add('get', '/api/posts/*/comment', 'h') // not match345+ router.add('get', '*', 'i') // match346+ router.add('get', '*', 'j') // match347+348+ it('get /api/posts/123', () => {349+ const res = router.match('get', '/api/posts/123')350+ expect(res?.handlers).toEqual(['b', 'd', 'e', 'f', 'g', 'i', 'j'])351+ })352+ })353+354+ describe('Multi match', () => {355+ const router = new PatternRouter<string>()356+ router.add('get', '*', 'GET *') // 0.1357+ router.add('get', '/abc/*', 'GET /abc/*') // 1.2358+ router.add('get', '/abc/edf', 'GET /abc/edf') // 2.3359+ router.add('get', '/abc/*/ghi/jkl', 'GET /abc/*/ghi/jkl') // 4.4360+ it('get /abc/edf', () => {361+ const res = router.match('get', '/abc/edf')362+ expect(res).not.toBeNull()363+ expect(res?.handlers).toEqual(['GET *', 'GET /abc/*', 'GET /abc/edf'])364+ })365+ })366+367+ describe('Multi match', () => {368+ const router = new PatternRouter<string>()369+370+ router.add('get', '/api/*', 'a') // 2.1 for /api/entry371+ router.add('get', '/api/entry', 'entry') // 2.2372+ router.add('ALL', '/api/*', 'b') // 2.3 for /api/entry373+374+ it('get /api/entry', async () => {375+ const res = router.match('get', '/api/entry')376+ expect(res).not.toBeNull()377+ expect(res?.handlers).toEqual(['a', 'entry', 'b'])378+ })379+ })380+381+ describe('fallback', () => {382+ describe('Blog - failed', () => {383+ const router = new PatternRouter<string>()384+ router.add('post', '/entry', 'post entry') // 1.1385+ router.add('post', '/entry/*', 'fallback') // 1.2386+ router.add('get', '/entry/:id', 'get entry') // 2.3387+ it('post /entry', async () => {388+ const res = router.match('post', '/entry')389+ expect(res).not.toBeNull()390+ expect(res?.handlers).toEqual(['post entry', 'fallback'])391+ })392+ })393+ })394+ describe('page', () => {395+ const router = new PatternRouter<string>()396+ router.add('get', '/page', 'page') // 1.1397+ router.add('ALL', '/*', 'fallback') // 1.2398+ it('get /page', async () => {399+ const res = router.match('get', '/page')400+ expect(res).not.toBeNull()401+ expect(res?.handlers).toEqual(['page', 'fallback'])402+ })403+ })404+})405+406+describe('star', () => {407+ const router = new PatternRouter<string>()408+ router.add('get', '/', '/')409+ router.add('get', '/*', '/*')410+ router.add('get', '*', '*')411+412+ router.add('get', '/x', '/x')413+ router.add('get', '/x/*', '/x/*')414+415+ it('top', async () => {416+ const res = router.match('get', '/')417+ expect(res).not.toBeNull()418+ expect(res?.handlers).toEqual(['/', '/*', '*']) // => failed ['*', '/*', '/']419+ })420+421+ it('Under a certain path', async () => {422+ const res = router.match('get', '/x')423+ expect(res).not.toBeNull()424+ expect(res?.handlers).toEqual(['/*', '*', '/x', '/x/*'])425+ })426+})427+428+describe('Routing order With named parameters', () => {429+ const router = new PatternRouter<string>()430+ router.add('get', '/book/a', 'no-slug')431+ router.add('get', '/book/:slug', 'slug')432+ router.add('get', '/book/b', 'no-slug-b')433+ it('/book/a', () => {434+ const res = router.match('get', '/book/a')435+ expect(res).not.toBeNull()436+ expect(res?.handlers).toEqual(['no-slug', 'slug'])437+ expect(res?.params['slug']).toBeUndefined()438+ })439+ it('/book/foo', () => {440+ const res = router.match('get', '/book/foo')441+ expect(res).not.toBeNull()442+ expect(res?.handlers).toEqual(['slug'])443+ expect(res?.params['slug']).toBe('foo')444+ })445+ it('/book/b', () => {446+ const res = router.match('get', '/book/b')447+ expect(res).not.toBeNull()448+ expect(res?.handlers).toEqual(['slug', 'no-slug-b'])449+ expect(res?.params['slug']).toBe('b')450+ })451+})452+453+describe('Routing with a hostname', () => {454+ const router = new PatternRouter<string>()455+ router.add('get', 'www1.example.com/hello', 'www1')456+ router.add('get', 'www2.example.com/hello', 'www2')457+ it('GET www1.example.com/hello', () => {458+ const res = router.match('get', 'www1.example.com/hello')459+ expect(res).not.toBeNull()460+ expect(res?.handlers).toEqual(['www1'])461+ })462+ it('GET www2.example.com/hello', () => {463+ const res = router.match('get', 'www2.example.com/hello')464+ expect(res).not.toBeNull()465+ expect(res?.handlers).toEqual(['www2'])466+ })467+ it('GET /hello', () => {468+ const res = router.match('get', '/hello')469+ expect(res).toBeNull()470+ })471+})added:src/router/pattern-router/router.ts+70 added
1+import type { Result, Router } from '../../router'2+import { METHOD_NAME_ALL } from '../../router'3+4+type Route<T> = [RegExp, string, T] // [pattern, method, handler]5+6+export class PatternRouter<T> implements Router<T> {7+ name: string = 'PatternRouter'8+ private routes: Route<T>[] = []9+ private dNames: Record<string, number> = {} // Short name of duplicatedNames10+11+ add(method: string, path: string, handler: T) {12+ const endsWithWildcard = path[path.length - 1] === '*'13+ if (endsWithWildcard) {14+ path = path.slice(0, -2)15+ }16+17+ const parts = path.match(/\/?(:\w+(?:{[^}]+})?)|\/?[^\/\?]+|(\?)/g) || []18+ if (parts[parts.length - 1] === '?') {19+ this.add(method, parts.slice(0, parts.length - 2).join(''), handler)20+ parts.pop()21+ }22+23+ for (let i = 0, len = parts.length; i < len; i++) {24+ // Check duplicated names25+ const match = parts[i].match(/^\/:([^{]+)(?:{(.*)})?/)26+ if (match) {27+ const label = match[1]28+ const pos = this.dNames[label]29+ if (typeof pos === 'number' && pos !== i) {30+ throw new Error(31+ `Duplicate param name, use another name instead of '${label}' - ${method} ${path} <--- '${label}'`32+ )33+ }34+ this.dNames[label] = i35+36+ parts[i] = `/(?<${label}>${match[2] || '[^/]+'})`37+ } else if (parts[i] === '/*') {38+ parts[i] = '/[^/]+'39+ }40+ }41+42+ this.routes.push([43+ new RegExp(`^${parts.join('')}${endsWithWildcard ? '' : '/?$'}`),44+ method,45+ handler,46+ ])47+ }48+49+ match(method: string, path: string): Result<T> | null {50+ const handlers: T[] = []51+ let params: Record<string, string> | undefined = undefined52+ for (const [pattern, routeMethod, handler] of this.routes) {53+ if (routeMethod === METHOD_NAME_ALL || routeMethod === method) {54+ const match = pattern.exec(path)55+ if (match) {56+ handlers.push(handler)57+ if (pattern.source.charCodeAt(pattern.source.length - 1) === 36) {58+ params ??= match.groups || {}59+ }60+ }61+ }62+ }63+ return handlers.length64+ ? {65+ handlers,66+ params: params || {},67+ }68+ : null69+ }70+}modified:src/router/reg-exp-router/router.test.ts+20 added
469 unmodified lines470 expect(res).not.toBeNull()471 expect(res?.handlers).toEqual(['wildcard', 'star2', 'bar'])472 })473 })474+475+describe('Routing with a hostname', () => {476+ const router = new RegExpRouter<string>()477+ router.add('get', 'www1.example.com/hello', 'www1')478+ router.add('get', 'www2.example.com/hello', 'www2')479+ it('GET www1.example.com/hello', () => {480+ const res = router.match('get', 'www1.example.com/hello')481+ expect(res).not.toBeNull()482+ expect(res?.handlers).toEqual(['www1'])483+ })484+ it('GET www2.example.com/hello', () => {485+ const res = router.match('get', 'www2.example.com/hello')486+ expect(res).not.toBeNull()487+ expect(res?.handlers).toEqual(['www2'])488+ })489+ it('GET /hello', () => {490+ const res = router.match('get', '/hello')491+ expect(res).toBeNull()492+ })493+})modified:src/router/reg-exp-router/router.ts+1 added
99 unmodified lines100 return undefined101 }102 103 export class RegExpRouter<T> implements Router<T> {104+ name: string = 'RegExpRouter'105 middleware?: Record<string, Record<string, T[]>>106 routes?: Record<string, Record<string, T[]>>107 108 constructor() {151 unmodified linesmodified:src/router/smart-router/router.test.ts+2 added
16 unmodified lines17 expect(res).not.toBeNull()18 expect(res?.handlers).toEqual(['get entry'])19 expect(res?.params['id']).toBe('123')20 expect(router.activeRouter).toBeInstanceOf(RegExpRouter)21+ expect(router.name).toBe('SmartRouter + RegExpRouter')22 })23 24 it('Wildcard', async () => {25 router.add('GET', '/wild/*/card', 'get wildcard')56 unmodified lines82 expect(res?.handlers).toEqual(['get user entries', 'get entry'])83 expect(res?.params['user']).toBe('entry')84 expect(res?.params['name']).toBe('entries')85 expect(router.activeRouter).toBeInstanceOf(TrieRouter)86+ expect(router.name).toBe('SmartRouter + TrieRouter')87 })88 })modified:src/router/smart-router/router.ts+4 added
1 unmodified line2 import type { Router, Result } from '../../router'3 import { UnsupportedPathError } from '../../router'4 5 export class SmartRouter<T> implements Router<T> {6+ name: string = 'SmartRouter'7 routers: Router<T>[] = []8 routes?: [string, string, T][] = []9 10 constructor(init: Pick<SmartRouter<T>, 'routers'>) {41 unmodified lines52 // not found53 throw new Error('Fatal error')54 }55 56+ // e.g. "SmartRouter + RegExpRouter"57+ this.name = `SmartRouter + ${this.activeRouter.name}`58+59 return res || null60 }61 62 get activeRouter() {7 unmodified linesmodified:src/router/trie-router/node.ts+7 added-6 removed
105 unmodified lines106 107 return curNode108 }109 110+ // getHandlerSets110- private getHandlerSets(node: Node<T>, method: string, wildcard?: boolean): HandlerSet<T>[] {111+ private gHSets(node: Node<T>, method: string, wildcard?: boolean): HandlerSet<T>[] {112 return (node.handlerSetCache[`${method}:${wildcard ? '1' : '0'}`] ||= (() => {113 const handlerSets: HandlerSet<T>[] = []114 for (let i = 0, len = node.methods.length; i < len; i++) {115 const m = node.methods[i]28 unmodified lines144 if (nextNode) {145 if (isLast === true) {146 // '/hello/*' => match '/hello'147 if (nextNode.children['*']) {147- handlerSets.push(...this.getHandlerSets(nextNode.children['*'], method, true))148+ handlerSets.push(...this.gHSets(nextNode.children['*'], method, true))149 }149- handlerSets.push(...this.getHandlerSets(nextNode, method))150+ handlerSets.push(...this.gHSets(nextNode, method))151 matched = true152 } else {153 tempNodes.push(nextNode)154 }6 unmodified lines161 // '/hello/*/foo' => match /hello/bar/foo162 if (pattern === '*') {163 const astNode = node.children['*']164 if (astNode) {164- handlerSets.push(...this.getHandlerSets(astNode, method))165+ handlerSets.push(...this.gHSets(astNode, method))166 tempNodes.push(astNode)167 }168 continue169 }6 unmodified lines176 177 // `/js/:filename{[a-z]+.js}` => match /js/chunk/123.js178 const restPathString = parts.slice(i).join('/')179 if (matcher instanceof RegExp && matcher.test(restPathString)) {179- handlerSets.push(...this.getHandlerSets(node.children[key], method))180+ handlerSets.push(...this.gHSets(node.children[key], method))181 params[name] = restPathString182 continue183 }184 185 if (matcher === true || (matcher instanceof RegExp && matcher.test(part))) {186 if (typeof key === 'string') {187 if (isLast === true) {187- handlerSets.push(...this.getHandlerSets(node.children[key], method))188+ handlerSets.push(...this.gHSets(node.children[key], method))189 } else {190 tempNodes.push(node.children[key])191 }192 }36 unmodified linesmodified:src/router/trie-router/router.test.ts+20 added
169 unmodified lines170 expect(res?.handlers).toEqual(['slug', 'no-slug-b'])171 expect(res?.params['slug']).toBe('b')172 })173 })174+175+describe('Routing with a hostname', () => {176+ const router = new TrieRouter<string>()177+ router.add('get', 'www1.example.com/hello', 'www1')178+ router.add('get', 'www2.example.com/hello', 'www2')179+ it('GET www1.example.com/hello', () => {180+ const res = router.match('get', 'www1.example.com/hello')181+ expect(res).not.toBeNull()182+ expect(res?.handlers).toEqual(['www1'])183+ })184+ it('GET www2.example.com/hello', () => {185+ const res = router.match('get', 'www2.example.com/hello')186+ expect(res).not.toBeNull()187+ expect(res?.handlers).toEqual(['www2'])188+ })189+ it('GET /hello', () => {190+ const res = router.match('get', '/hello')191+ expect(res).toBeNull()192+ })193+})modified:src/router/trie-router/router.ts+1 added
1 unmodified line2 import { checkOptionalParameter } from '../../utils/url'3 import { Node } from './node'4 5 export class TrieRouter<T> implements Router<T> {6+ name: string = 'TrieRouter'7 node: Node<T>8 9 constructor() {10 this.node = new Node()18 unmodified linesmodified:src/utils/cookie.ts+3 added-1 removed
1+import { decodeURIComponent_ } from './url'2+3 export type Cookie = Record<string, string>4 export type CookieOptions = {5 domain?: string6 expires?: Date9 unmodified lines16 const pairs = cookie.split(/;\s*/g)17 const parsedCookie: Cookie = {}18 for (let i = 0, len = pairs.length; i < len; i++) {19 const pair = pairs[i].split(/\s*=\s*([^\s]+)/)18- parsedCookie[pair[0]] = decodeURIComponent(pair[1])20+ parsedCookie[pair[0]] = decodeURIComponent_(pair[1])21 }22 return parsedCookie23 }24 34 unmodified linesdeleted:src/utils/http-status.test.ts-7 removed
1-import { getStatusText } from './http-status'2-3-describe('http-status utility', () => {4- it('getStatusText', () => {5- expect(getStatusText(200)).toBe('OK')6- })7-})modified:src/utils/http-status.ts+1 added-120 removed
1-export const getStatusText = (statusCode: StatusCode): string => {2- const text = statuses[statusCode]3- return text4-}5-6-export type StatusCode =1+export type StatusCode = number7- | 1008- | 1019- | 10210- | 10311- | 20012- | 20113- | 20214- | 20315- | 20416- | 20517- | 20618- | 20719- | 20820- | 22621- | 30022- | 30123- | 30224- | 30325- | 30426- | 30527- | 30628- | 30729- | 30830- | 40031- | 40132- | 40233- | 40334- | 40435- | 40536- | 40637- | 40738- | 40839- | 40940- | 41041- | 41142- | 41243- | 41344- | 41445- | 41546- | 41647- | 41748- | 41849- | 42050- | 42151- | 42252- | 42353- | 42454- | 42555- | 42656- | 42857- | 42958- | 43159- | 44460- | 44961- | 45062- | 45163- | 49964- | 50065- | 50166- | 50267- | 50368- | 50469- | 50570- | 50671- | 50772- | 50873- | 50974- | 51075- | 51176- | 59877- | 59978-79-const statuses: Record<StatusCode | number, string> = {80- 100: 'Continue',81- 101: 'Switching Protocols',82- 102: 'Processing',83- 103: 'Early Hints',84- 200: 'OK',85- 201: 'Created',86- 202: 'Accepted',87- 204: 'No Content',88- 206: 'Partial Content',89- 301: 'Moved Permanently',90- 302: 'Moved Temporarily',91- 303: 'See Other',92- 304: 'Not Modified',93- 307: 'Temporary Redirect',94- 308: 'Permanent Redirect',95- 400: 'Bad Request',96- 401: 'Unauthorized',97- 402: 'Payment Required',98- 403: 'Forbidden',99- 404: 'Not Found',100- 405: 'Not Allowed',101- 406: 'Not Acceptable',102- 408: 'Request Time-out',103- 409: 'Conflict',104- 410: 'Gone',105- 411: 'Length Required',106- 412: 'Precondition Failed',107- 413: 'Request Entity Too Large',108- 414: 'Request-URI Too Large',109- 415: 'Unsupported Media Type',110- 416: 'Requested Range Not Satisfiable',111- 421: 'Misdirected Request',112- 429: 'Too Many Requests',113- 500: 'Internal Server Error',114- 501: 'Not Implemented',115- 502: 'Bad Gateway',116- 503: 'Service Temporarily Unavailable',117- 504: 'Gateway Time-out',118- 505: 'HTTP Version Not Supported',119- 507: 'Insufficient Storage',120-}modified:src/utils/url.test.ts+19 added-16 removed
1 import {2 splitPath,3 splitRoutingPath,4 getPattern,5- getPathFromURL,5+ getPath,6+ getPathNoStrict,7 mergePath,8 checkOptionalParameter,9 getQueryParam,10 getQueryParams,50 unmodified lines61 res = getPattern('*')62 expect(res).toBe('*')63 })64 64- describe('getPathFromURL', () => {65- it('getPathFromURL - no trailing slash', () => {66- let path = getPathFromURL('https://example.com/')65+ describe('getPath', () => {66+ it('getPath - no trailing slash', () => {67+ let path = getPath(new Request('https://example.com/'))68 expect(path).toBe('/')68- path = getPathFromURL('https://example.com/hello')69+ path = getPath(new Request('https://example.com/hello'))70 expect(path).toBe('/hello')70- path = getPathFromURL('https://example.com/hello/hey')71+ path = getPath(new Request('https://example.com/hello/hey'))72 expect(path).toBe('/hello/hey')72- path = getPathFromURL('https://example.com/hello?name=foo')73+ path = getPath(new Request('https://example.com/hello?name=foo'))74 expect(path).toBe('/hello')74- path = getPathFromURL('https://example.com/hello/hey?name=foo&name=bar')75+ path = getPath(new Request('https://example.com/hello/hey?name=foo&name=bar'))76 expect(path).toBe('/hello/hey')77 })78 78- it('getPathFromURL - with trailing slash', () => {79- let path = getPathFromURL('https://example.com/hello/')79+ it('getPath - with trailing slash', () => {80+ let path = getPath(new Request('https://example.com/hello/'))81 expect(path).toBe('/hello/')81- path = getPathFromURL('https://example.com/hello/hey/')82+ path = getPath(new Request('https://example.com/hello/hey/'))83 expect(path).toBe('/hello/hey/')84 })85+ })86 85- it('getPathFromURL - no strict is false', () => {86- let path = getPathFromURL('https://example.com/hello/', false)87+ describe('getPathNoStrict', () => {88+ it('getPathNoStrict - no strict is false', () => {89+ let path = getPathNoStrict(new Request('https://example.com/hello/'))90 expect(path).toBe('/hello')88- path = getPathFromURL('https://example.com/hello/hey/', false)91+ path = getPathNoStrict(new Request('https://example.com/hello/hey/'))92 expect(path).toBe('/hello/hey')93 })94 92- it('getPathFromURL - return `/` even if strict is false', () => {93- const path = getPathFromURL('https://example.com/', false)95+ it('getPathNoStrict - return `/` even if strict is false', () => {96+ const path = getPathNoStrict(new Request('https://example.com/'))97 expect(path).toBe('/')98 })99 })100 141 unmodified linesmodified:src/utils/url.ts+15 added-11 removed
66 unmodified lines67 68 return null69 }70 71-export const getPathFromURL = (url: string, strict: boolean = true): string => {71+export const getPath = (request: Request): string => {72+ const url = request.url73 const queryIndex = url.indexOf('?', 8)73- const result = url.substring(url.indexOf('/', 8), queryIndex === -1 ? url.length : queryIndex)74+ return url.slice(url.indexOf('/', 8), queryIndex === -1 ? undefined : queryIndex)75+}76 75- // if strict routing is false => `/hello/hey/` and `/hello/hey` are treated the same76- // default is true77- if (strict === false && /.+\/$/.test(result)) {78- return result.slice(0, -1)79- }77+export const getPathNoStrict = (request: Request): string => {78+ const result = getPath(request)79 81- return result80+ // if strict routing is false => `/hello/hey/` and `/hello/hey` are treated the same81+ return result.length > 1 && result[result.length - 1] === '/' ? result.slice(0, -1) : result82 }83 84 export const mergePath = (...paths: string[]): string => {85 let p: string = ''86 let endsWithSlash = false87 88 for (let path of paths) {89 /* ['/hey/','/say'] => ['/hey', '/say'] */90- if (p.endsWith('/')) {90+ if (p[p.length - 1] === '/') {91 p = p.slice(0, -1)92 endsWithSlash = true93 }94 95 /* ['/hey','say'] => ['/hey', '/say'] */96- if (!path.startsWith('/')) {96+ if (path[0] !== '/') {97 path = `/${path}`98 }99 100 /* ['/hey/', '/'] => `/hey/` */33 unmodified lines134 }135 if (value.includes('+')) {136 value = value.replace(/\+/g, ' ')137 }138- return value.includes('%') ? decodeURIComponent(value) : value138+ return value.includes('%') ? decodeURIComponent_(value) : value139 }140 141 const _getQueryParam = (142 url: string,85 unmodified lines228 key?: string229 ): string[] | undefined | Record<string, string[]> => {230 return _getQueryParam(url, key, true) as string[] | undefined | Record<string, string[]>231 }232+233+// `decodeURIComponent` is a long name.234+// By making it a function, we can use it commonly when minified, reducing the amount of code.235+export const decodeURIComponent_ = decodeURIComponentmodified:src/compose.ts+2 added-2 removed
66 unmodified lines67 context.res = res68 }69 return context70 })71- .catch((err) => {71+ .catch(async (err) => {72 if (err instanceof Error && context instanceof Context && onError) {73 context.error = err74- context.res = onError(err, context)74+ context.res = await onError(err, context)75 return context76 }77 throw err78 })4 unmodified linesmodified:src/context.test.ts-2 removed
195 unmodified lines196 expect(c.runtime).toBe('workerd')197 })198 })199 200-/*200 describe('Context header', () => {201 const req = new Request('http://localhost/')202 let c: Context203 beforeEach(() => {72 unmodified lines276 expect(res.headers.get('content-type')).toMatch(/^text\/html/)277 expect(await res.text()).toBe('<h1>foo</h1>')278 })279 })281-*/modified:src/context.ts+67 added-70 removed
14 unmodified lines15 passThroughOnException(): void16 }17 export interface ContextVariableMap {}18 19+interface Get<E extends Env> {20+ <Key extends keyof ContextVariableMap>(key: Key): ContextVariableMap[Key]21+ <Key extends keyof E['Variables']>(key: Key): E['Variables'][Key]22+}23+24+interface Set<E extends Env> {25+ <Key extends keyof ContextVariableMap>(key: Key, value: ContextVariableMap[Key]): void26+ <Key extends keyof E['Variables']>(key: Key, value: E['Variables'][Key]): void27+}28+29 interface NewResponse {30 (data: Data | null, status?: StatusCode, headers?: HeaderRecord): Response31 (data: Data | null, init?: ResponseInit): Response32 }25 unmodified lines58 (html: string, status?: StatusCode, headers?: HeaderRecord): Response59 (html: string, init?: ResponseInit): Response60 }61 52-type GetVariable<K, E extends Env> = K extends keyof E['Variables']53- ? E['Variables'][K]54- : K extends keyof ContextVariableMap55- ? ContextVariableMap[K]56- : unknown57-62 type ContextOptions<E extends Env> = {63 env: E['Bindings']64 executionCtx?: FetchEvent | ExecutionContext | undefined65 notFoundHandler?: NotFoundHandler<E>14 unmodified lines80 81 // eslint-disable-next-line @typescript-eslint/no-explicit-any82 private _req?: HonoRequest<any, any>83 private _status: StatusCode = 20080- private _executionCtx: FetchEvent | ExecutionContext | undefined81- private _pretty: boolean = false82- private _prettySpace: number = 284+ private _exCtx: FetchEvent | ExecutionContext | undefined // _executionCtx85+ private _pre: boolean = false // _pretty86+ private _preS: number = 2 // _prettySpace87 private _map: Record<string, unknown> | undefined84- private _headers: Headers | undefined = undefined85- private _preparedHeaders: Record<string, string> | undefined = undefined88+ private _h: Headers | undefined = undefined // _headers89+ private _pH: Record<string, string> | undefined = undefined // _preparedHeaders90 private _res: Response | undefined91 private _path: string = '/'88- private _paramData?: Record<string, string> | null92+ private _pData?: Record<string, string> | null // __paramData93 private rawRequest?: Request | null94 private notFoundHandler: NotFoundHandler<E> = () => new Response()95 96 constructor(req: Request, options?: ContextOptions<E>) {97 this.rawRequest = req98 if (options) {95- this._executionCtx = options.executionCtx99+ this._exCtx = options.executionCtx100 this._path = options.path ?? '/'97- this._paramData = options.paramData101+ this._pData = options.paramData102 this.env = options.env103 if (options.notFoundHandler) {104 this.notFoundHandler = options.notFoundHandler105 }4 unmodified lines110 if (this._req) {111 return this._req112 } else {113 // eslint-disable-next-line @typescript-eslint/no-non-null-assertion110- this._req = new HonoRequest(this.rawRequest!, this._path, this._paramData!)114+ this._req = new HonoRequest(this.rawRequest!, this._path, this._pData!)115 this.rawRequest = undefined112- this._paramData = undefined116+ this._pData = undefined117 return this._req118 }119 }120 121 get event(): FetchEvent {118- if (this._executionCtx instanceof FetchEvent) {119- return this._executionCtx122+ if (this._exCtx instanceof FetchEvent) {123+ return this._exCtx124 } else {125 throw Error('This context has no FetchEvent')126 }127 }128 129 get executionCtx(): ExecutionContext {126- if (this._executionCtx) {127- return this._executionCtx as ExecutionContext130+ if (this._exCtx) {131+ return this._exCtx as ExecutionContext132 } else {133 throw Error('This context has no ExecutionContext')134 }135 }15 unmodified lines151 152 header = (name: string, value: string | undefined, options?: { append?: boolean }): void => {153 // Clear the header154 if (value === undefined) {151- if (this._headers) {152- this._headers.delete(name)153- } else if (this._preparedHeaders) {154- delete this._preparedHeaders[name.toLocaleLowerCase()]155+ if (this._h) {156+ this._h.delete(name)157+ } else if (this._pH) {158+ delete this._pH[name.toLocaleLowerCase()]159 }160 if (this.finalized) {161 this.res.headers.delete(name)162 }163 return164 }165 166 if (options?.append) {163- if (!this._headers) {164- this._headers = new Headers(this._preparedHeaders)165- this._preparedHeaders = {}167+ if (!this._h) {168+ this._h = new Headers(this._pH)169+ this._pH = {}170 }167- this._headers.append(name, value)171+ this._h.append(name, value)172 } else {169- if (this._headers) {170- this._headers.set(name, value)173+ if (this._h) {174+ this._h.set(name, value)175 } else {172- this._preparedHeaders ??= {}173- this._preparedHeaders[name.toLowerCase()] = value176+ this._pH ??= {}177+ this._pH[name.toLowerCase()] = value178 }179 }180 181 if (this.finalized) {8 unmodified lines190 status = (status: StatusCode): void => {191 this._status = status192 }193 190- set = <Key extends keyof E['Variables'] | keyof ContextVariableMap>(191- key: Key,192- value: GetVariable<Key, E>193- ): void => {194+ set: Set<E> = (key: string, value: unknown) => {195 this._map ||= {}196 this._map[key as string] = value197 }198 198- get = <Key extends keyof E['Variables'] | keyof ContextVariableMap>(199- key: Key200- ): GetVariable<Key, E> => {201- return this._map?.[key as string] as GetVariable<Key, E>199+ get: Get<E> = (key: string) => {200+ return this._map ? this._map[key] : undefined201 }202 203 pretty = (prettyJSON: boolean, space: number = 2): void => {205- this._pretty = prettyJSON206- this._prettySpace = space204+ this._pre = prettyJSON205+ this._preS = space206 }207 208 newResponse: NewResponse = (209 data: Data | null,210 arg?: StatusCode | ResponseInit,211 headers?: HeaderRecord212 ): Response => {213 // Optimized215- if (!headers && !this._headers && !this._res && !arg && this._status === 200) {214+ if (!headers && !this._h && !this._res && !arg && this._status === 200) {215 return new Response(data, {217- headers: this._preparedHeaders,216+ headers: this._pH,217 })218 }219 220 // Return Response immediately if arg is RequestInit.221 if (arg && typeof arg !== 'number') {222 const res = new Response(data, arg)224- const contentType = this._preparedHeaders?.['content-type']223+ const contentType = this._pH?.['content-type']224 if (contentType) {225 res.headers.set('content-type', contentType)226 }227 return res228 }229 230 const status = arg ?? this._status232- this._preparedHeaders ??= {}231+ this._pH ??= {}232 234- this._headers ??= new Headers()235- for (const [k, v] of Object.entries(this._preparedHeaders)) {236- this._headers.set(k, v)233+ this._h ??= new Headers()234+ for (const [k, v] of Object.entries(this._pH)) {235+ this._h.set(k, v)236 }237 238 if (this._res) {239 this._res.headers.forEach((v, k) => {241- this._headers?.set(k, v)240+ this._h?.set(k, v)241 })243- for (const [k, v] of Object.entries(this._preparedHeaders)) {244- this._headers.set(k, v)242+ for (const [k, v] of Object.entries(this._pH)) {243+ this._h.set(k, v)244 }245 }246 247 headers ??= {}248 for (const [k, v] of Object.entries(headers)) {249 if (typeof v === 'string') {251- this._headers.set(k, v)250+ this._h.set(k, v)251 } else {253- this._headers.delete(k)252+ this._h.delete(k)253 for (const v2 of v) {255- this._headers.append(k, v2)254+ this._h.append(k, v2)255 }256 }257 }258 259 return new Response(data, {260 status,262- headers: this._headers,261+ headers: this._h,262 })263 }264 265 body: BodyRespond = (12 unmodified lines278 headers?: HeaderRecord279 ): Response => {280 // If the header is empty, return Response immediately.281 // Content-Type will be added automatically as `text/plain`.283- if (!this._preparedHeaders) {284- if (!headers && !this._res && !this._headers && !arg) {282+ if (!this._pH) {283+ if (!headers && !this._res && !this._h && !arg) {284 return new Response(text)285 }287- this._preparedHeaders = {}286+ this._pH = {}287 }288 // If Content-Type is not set, we don't have to set `text/plain`.289 // Fewer the header values, it will be faster.291- if (this._preparedHeaders['content-type']) {292- this._preparedHeaders['content-type'] = 'text/plain; charset=UTF-8'290+ if (this._pH['content-type']) {291+ this._pH['content-type'] = 'text/plain; charset=UTF-8'292 }293 return typeof arg === 'number'294 ? this.newResponse(text, arg, headers)295 : this.newResponse(text, arg)3 unmodified lines299 object: T,300 arg?: StatusCode | RequestInit,301 headers?: HeaderRecord302 ) => {304- const body = this._pretty305- ? JSON.stringify(object, null, this._prettySpace)306- : JSON.stringify(object)307- this._preparedHeaders ??= {}308- this._preparedHeaders['content-type'] = 'application/json; charset=UTF-8'303+ const body = this._pre ? JSON.stringify(object, null, this._preS) : JSON.stringify(object)304+ this._pH ??= {}305+ this._pH['content-type'] = 'application/json; charset=UTF-8'306 return typeof arg === 'number'307 ? this.newResponse(body, arg, headers)308 : this.newResponse(body, arg)309 }15 unmodified lines325 html: string,326 arg?: StatusCode | RequestInit,327 headers?: HeaderRecord328 ): Response => {332- this._preparedHeaders ??= {}333- this._preparedHeaders['content-type'] = 'text/html; charset=UTF-8'329+ this._pH ??= {}330+ this._pH['content-type'] = 'text/html; charset=UTF-8'331 return typeof arg === 'number'332 ? this.newResponse(html, arg, headers)333 : this.newResponse(html, arg)334 }335 336 redirect = (location: string, status: StatusCode = 302): Response => {340- this._headers ??= new Headers()341- this._headers.set('Location', location)337+ this._h ??= new Headers()338+ this._h.set('Location', location)339 return this.newResponse(null, status)340 }341 342 /** @deprecated57 unmodified linesadded:src/hono-base.ts+362 added
1+import { compose } from './compose'2+import { Context } from './context'3+import type { ExecutionContext } from './context'4+import { HTTPException } from './http-exception'5+import type { Router } from './router'6+import { METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE, METHODS } from './router'7+import type {8+ Env,9+ ErrorHandler,10+ H,11+ HandlerInterface,12+ MiddlewareHandler,13+ MiddlewareHandlerInterface,14+ Next,15+ NotFoundHandler,16+ OnHandlerInterface,17+ TypedResponse,18+ MergePath,19+ MergeSchemaPath,20+} from './types'21+import type { RemoveBlankRecord } from './utils/types'22+import { getPath, getPathNoStrict, mergePath } from './utils/url'23+24+type Methods = typeof METHODS[number] | typeof METHOD_NAME_ALL_LOWERCASE25+26+interface RouterRoute {27+ path: string28+ method: string29+ handler: H30+}31+32+function defineDynamicClass(): {33+ new <E extends Env = Env, S = {}, BasePath extends string = '/'>(): {34+ [M in Methods]: HandlerInterface<E, M, S, BasePath>35+ } & {36+ on: OnHandlerInterface<E, S, BasePath>37+ } & {38+ use: MiddlewareHandlerInterface<E, S, BasePath>39+ }40+} {41+ return class {} as never42+}43+44+const notFoundHandler = (c: Context) => {45+ return c.text('404 Not Found', 404)46+}47+48+const errorHandler = (err: Error, c: Context) => {49+ if (err instanceof HTTPException) {50+ return err.getResponse()51+ }52+ console.trace(err)53+ const message = 'Internal Server Error'54+ return c.text(message, 500)55+}56+57+class Hono<E extends Env = Env, S = {}, BasePath extends string = '/'> extends defineDynamicClass()<58+ E,59+ S,60+ BasePath61+> {62+ /*63+ This class is like an abstract class and does not have a router.64+ To use it, inherit the class and implement router in the constructor.65+ */66+ router!: Router<H>67+ readonly getPath: (request: Request) => string68+ private _basePath: string = ''69+ private path: string = '*'70+71+ routes: RouterRoute[] = []72+73+ constructor(init: Partial<Pick<Hono, 'router' | 'getPath'> & { strict: boolean }> = {}) {74+ super()75+76+ // Implementation of app.get(...handlers[]) or app.get(path, ...handlers[])77+ const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE]78+ allMethods.map((method) => {79+ this[method] = (args1: string | H, ...args: H[]) => {80+ if (typeof args1 === 'string') {81+ this.path = args182+ } else {83+ this.addRoute(method, this.path, args1)84+ }85+ args.map((handler) => {86+ if (typeof handler !== 'string') {87+ this.addRoute(method, this.path, handler)88+ }89+ })90+ // eslint-disable-next-line @typescript-eslint/no-explicit-any91+ return this as any92+ }93+ })94+95+ // Implementation of app.on(method, path, ...handlers[])96+ this.on = (method: string | string[], path: string, ...handlers: H[]) => {97+ if (!method) return this98+ this.path = path99+ for (const m of [method].flat()) {100+ handlers.map((handler) => {101+ this.addRoute(m.toUpperCase(), this.path, handler)102+ })103+ }104+ // eslint-disable-next-line @typescript-eslint/no-explicit-any105+ return this as any106+ }107+108+ // Implementation of app.use(...handlers[]) or app.get(path, ...handlers[])109+ this.use = (arg1: string | MiddlewareHandler, ...handlers: MiddlewareHandler[]) => {110+ if (typeof arg1 === 'string') {111+ this.path = arg1112+ } else {113+ handlers.unshift(arg1)114+ }115+ handlers.map((handler) => {116+ this.addRoute(METHOD_NAME_ALL, this.path, handler)117+ })118+ return this119+ }120+121+ const strict = init.strict ?? true122+ delete init.strict123+ Object.assign(this, init)124+ this.getPath ||= strict ? getPath : getPathNoStrict125+ }126+127+ private clone(): Hono<E, S, BasePath> {128+ const clone = new Hono<E, S, BasePath>({129+ router: this.router,130+ getPath: this.getPath,131+ })132+ clone.routes = this.routes133+ return clone134+ }135+136+ private notFoundHandler: NotFoundHandler = notFoundHandler137+ private errorHandler: ErrorHandler = errorHandler138+139+ route<SubPath extends string, SubEnv extends Env, SubSchema, SubBasePath extends string>(140+ path: SubPath,141+ app: Hono<SubEnv, SubSchema, SubBasePath>142+ ): Hono<E, RemoveBlankRecord<MergeSchemaPath<SubSchema, SubPath> | S>, BasePath>143+ /** @deprecated144+ * Use `basePath` instead of `route` with one argument.145+ * The `route` with one argument has been removed in v4.146+ */147+ route<SubPath extends string>(path: SubPath): Hono<E, RemoveBlankRecord<S>, BasePath>148+ route<SubPath extends string, SubEnv extends Env, SubSchema, SubBasePath extends string>(149+ path: SubPath,150+ app?: Hono<SubEnv, SubSchema, SubBasePath>151+ ): Hono<E, RemoveBlankRecord<MergeSchemaPath<SubSchema, SubPath> | S>, BasePath> {152+ const subApp = this.basePath(path)153+154+ if (!app) {155+ // eslint-disable-next-line @typescript-eslint/no-explicit-any156+ return subApp as any157+ }158+159+ app.routes.map((r) => {160+ const handler =161+ app.errorHandler === errorHandler162+ ? r.handler163+ : async (c: Context, next: Next) =>164+ (await compose<Context>([r.handler], app.errorHandler)(c, next)).res165+ subApp.addRoute(r.method, r.path, handler)166+ })167+ // eslint-disable-next-line @typescript-eslint/no-explicit-any168+ return this as any169+ }170+171+ basePath<SubPath extends string>(path: SubPath): Hono<E, S, MergePath<BasePath, SubPath>> {172+ const subApp = this.clone()173+ subApp._basePath = mergePath(this._basePath, path)174+ // eslint-disable-next-line @typescript-eslint/no-explicit-any175+ return subApp as any176+ }177+178+ onError(handler: ErrorHandler<E>) {179+ this.errorHandler = handler180+ return this181+ }182+183+ notFound(handler: NotFoundHandler<E>) {184+ this.notFoundHandler = handler185+ return this186+ }187+188+ showRoutes() {189+ const length = 8190+ this.routes.map((route) => {191+ console.log(192+ `\x1b[32m${route.method}\x1b[0m ${' '.repeat(length - route.method.length)} ${route.path}`193+ )194+ })195+ }196+197+ /**198+ * @experimental199+ * `app.mount()` is an experimental feature.200+ * The API might be changed.201+ */202+ mount(203+ path: string,204+ // eslint-disable-next-line @typescript-eslint/no-explicit-any205+ applicationHandler: (request: Request, ...args: any) => Response | Promise<Response>,206+ optionHandler?: (c: Context) => unknown207+ ): Hono<E, S, BasePath> {208+ const pathPrefixLength = mergePath(this._basePath, path).length209+ const handler: MiddlewareHandler = async (c, next) => {210+ let executionContext: ExecutionContext | undefined = undefined211+ try {212+ executionContext = c.executionCtx213+ } catch {} // Do nothing214+ const options = optionHandler ? optionHandler(c) : [c.env, executionContext]215+ const optionsArray = Array.isArray(options) ? options : [options]216+ const res = await applicationHandler(217+ new Request(new URL(c.req.path.slice(pathPrefixLength) || '/', c.req.url), c.req.raw),218+ ...optionsArray219+ )220+221+ if (res) return res222+223+ await next()224+ }225+ this.addRoute(METHOD_NAME_ALL, mergePath(path, '*'), handler)226+ return this227+ }228+229+ get routerName() {230+ this.matchRoute('GET', '/')231+ return this.router.name232+ }233+234+ private addRoute(method: string, path: string, handler: H) {235+ method = method.toUpperCase()236+ if (this._basePath) {237+ path = mergePath(this._basePath, path)238+ }239+ this.router.add(method, path, handler)240+ const r: RouterRoute = { path: path, method: method, handler: handler }241+ this.routes.push(r)242+ }243+244+ private matchRoute(method: string, path: string) {245+ return this.router.match(method, path)246+ }247+248+ private handleError(err: unknown, c: Context<E>) {249+ if (err instanceof Error) {250+ return this.errorHandler(err, c)251+ }252+ throw err253+ }254+255+ private dispatch(256+ request: Request,257+ eventOrExecutionCtx?: ExecutionContext | FetchEvent,258+ env?: E['Bindings']259+ ): Response | Promise<Response> {260+ const path = this.getPath(request)261+ const method = request.method262+263+ const result = this.matchRoute(method, path)264+ const paramData = result?.params265+266+ const c = new Context(request, {267+ env,268+ executionCtx: eventOrExecutionCtx,269+ notFoundHandler: this.notFoundHandler,270+ path,271+ paramData,272+ })273+274+ // Do not `compose` if it has only one handler275+ if (result?.handlers.length === 1) {276+ const handler = result.handlers[0]277+ let res: ReturnType<H>278+279+ try {280+ res = handler(c, async () => {})281+ if (!res) {282+ return this.notFoundHandler(c)283+ }284+ } catch (err) {285+ return this.handleError(err, c)286+ }287+288+ if (res instanceof Response) return res289+290+ if ('response' in res) {291+ res = res.response292+ }293+294+ if (res instanceof Response) return res295+296+ return (async () => {297+ let awaited: Response | TypedResponse | void298+ try {299+ awaited = await res300+ if (awaited !== undefined && 'response' in awaited) {301+ awaited = awaited['response'] as Response302+ }303+ if (!awaited) {304+ return this.notFoundHandler(c)305+ }306+ } catch (err) {307+ return this.handleError(err, c)308+ }309+ return awaited310+ })()311+ }312+313+ const handlers = result ? result.handlers : [this.notFoundHandler]314+ const composed = compose<Context>(handlers, this.errorHandler, this.notFoundHandler)315+316+ return (async () => {317+ try {318+ const tmp = composed(c)319+ const context = tmp instanceof Promise ? await tmp : tmp320+ if (!context.finalized) {321+ throw new Error(322+ 'Context is not finalized. You may forget returning Response object or `await next()`'323+ )324+ }325+ return context.res326+ } catch (err) {327+ return this.handleError(err, c)328+ }329+ })()330+ }331+332+ handleEvent = (event: FetchEvent) => {333+ return this.dispatch(event.request, event)334+ }335+336+ fetch = (request: Request, Env?: E['Bindings'] | {}, executionCtx?: ExecutionContext) => {337+ return this.dispatch(request, executionCtx, Env)338+ }339+340+ request = async (input: Request | string | URL, requestInit?: RequestInit) => {341+ if (input instanceof Request) {342+ if (requestInit !== undefined) {343+ input = new Request(input, requestInit)344+ }345+ return await this.fetch(input)346+ }347+ input = input.toString()348+ const path = /^https?:\/\//.test(input) ? input : `http://localhost${mergePath('/', input)}`349+ const req = new Request(path, requestInit)350+ return await this.fetch(req)351+ }352+353+ fire = () => {354+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment355+ // @ts-ignore356+ addEventListener('fetch', (event: FetchEvent): void => {357+ void event.respondWith(this.handleEvent(event))358+ })359+ }360+}361+362+export { Hono as HonoBase }modified:src/hono.test.ts+284 added-20 removed
3 unmodified lines4 import { Hono } from './hono'5 import { HTTPException } from './http-exception'6 import { logger } from './middleware/logger'7 import { poweredBy } from './middleware/powered-by'8+import { SmartRouter } from './mod'9 import { RegExpRouter } from './router/reg-exp-router'10 import { TrieRouter } from './router/trie-router'11 import type { Handler, Next } from './types'12 import type { Expect, Equal } from './utils/types'13+import { getPath } from './utils/url'14 15 // https://stackoverflow.com/a/6566640216 function throwExpression(errorMessage: string): never {17 throw new Error(errorMessage)59 unmodified lines77 expect(res.status).toBe(404)78 })79 })80 81+describe('router option', () => {82+ it('Should be SmartRouter', () => {83+ const app = new Hono()84+ expect(app.router instanceof SmartRouter).toBe(true)85+ })86+ it('Should be RegExpRouter', () => {87+ const app = new Hono({88+ router: new RegExpRouter(),89+ })90+ expect(app.router instanceof RegExpRouter).toBe(true)91+ })92+})93+94 describe('strict parameter', () => {95 describe('strict is true with not slash', () => {96 const app = new Hono()97 234 unmodified lines332 expect(status).toBe(404)333 })334 })335 336+ it('routing with hostname', async () => {337+ const app = new Hono({338+ getPath: (req) => req.url.replace(/^https?:\/\//, ''),339+ })340+341+ app.get('www1.example.com/hello', () => new Response('hello www1'))342+ app.get('www2.example.com/hello', () => new Response('hello www2'))343+344+ let res = await app.request('http://www1.example.com/hello')345+ expect(res).not.toBeNull()346+ expect(res.status).toBe(200)347+ expect(await res.text()).toBe('hello www1')348+349+ res = await app.request('http://www2.example.com/hello')350+ expect(res).not.toBeNull()351+ expect(res.status).toBe(200)352+ expect(await res.text()).toBe('hello www2')353+ })354+355+ it('routing with request header', async () => {356+ const app = new Hono({357+ getPath: (req) => req.headers.get('host') + req.url.replace(/^https?:\/\/[^\/]+/, ''),358+ })359+360+ app.get('www1.example.com/hello', () => new Response('hello www1'))361+ app.get('www2.example.com/hello', () => new Response('hello www2'))362+363+ let res = await app.request('http://www1.example.com/hello', {364+ headers: { host: 'www1.example.com' },365+ })366+ expect(res).not.toBeNull()367+ expect(res.status).toBe(200)368+ expect(await res.text()).toBe('hello www1')369+370+ res = await app.request('http://www2.example.com/hello', {371+ headers: { host: 'www2.example.com' },372+ })373+ expect(res).not.toBeNull()374+ expect(res.status).toBe(200)375+ expect(await res.text()).toBe('hello www2')376+ })377+378 describe('Chained route', () => {379 const app = new Hono()380 381 app469 unmodified lines851 })852 })853 854 describe('Error handle', () => {855+ describe('Basic', () => {798- const app = new Hono()856+ const app = new Hono()857 800- app.get('/error', () => {801- throw new Error('This is Error')802- })858+ app.get('/error', () => {859+ throw new Error('This is Error')860+ })861 804- app.use('/error-middleware', async () => {805- throw new Error('This is Middleware Error')806- })862+ app.use('/error-middleware', async () => {863+ throw new Error('This is Middleware Error')864+ })865 808- app.onError((err, c) => {809- c.header('x-debug', err.message)810- return c.text('Custom Error Message', 500)866+ app.onError((err, c) => {867+ c.header('x-debug', err.message)868+ return c.text('Custom Error Message', 500)869+ })870+871+ it('Custom Error Message', async () => {872+ let res = await app.request('https://example.com/error')873+ expect(res.status).toBe(500)874+ expect(await res.text()).toBe('Custom Error Message')875+ expect(res.headers.get('x-debug')).toBe('This is Error')876+877+ res = await app.request('https://example.com/error-middleware')878+ expect(res.status).toBe(500)879+ expect(await res.text()).toBe('Custom Error Message')880+ expect(res.headers.get('x-debug')).toBe('This is Middleware Error')881+ })882 })883 813- it('Custom Error Message', async () => {814- let res = await app.request('https://example.com/error')815- expect(res.status).toBe(500)816- expect(await res.text()).toBe('Custom Error Message')817- expect(res.headers.get('x-debug')).toBe('This is Error')884+ describe('Async custom handler', () => {885+ const app = new Hono()886 887+ app.get('/error', () => {888+ throw new Error('This is Error')889+ })890+891+ app.use('/error-middleware', async () => {892+ throw new Error('This is Middleware Error')893+ })894+895+ app.onError(async (err, c) => {896+ const promise = new Promise((resolve) =>897+ setTimeout(() => {898+ resolve('Promised')899+ }, 1)900+ )901+ const message = (await promise) as string902+ c.header('x-debug', err.message)903+ return c.text(`Custom Error Message with ${message}`, 500)904+ })905+906+ it('Custom Error Message', async () => {907+ let res = await app.request('https://example.com/error')908+ expect(res.status).toBe(500)909+ expect(await res.text()).toBe('Custom Error Message with Promised')910+ expect(res.headers.get('x-debug')).toBe('This is Error')911+819- res = await app.request('https://example.com/error-middleware')820- expect(res.status).toBe(500)821- expect(await res.text()).toBe('Custom Error Message')822- expect(res.headers.get('x-debug')).toBe('This is Middleware Error')912+ res = await app.request('https://example.com/error-middleware')913+ expect(res.status).toBe(500)914+ expect(await res.text()).toBe('Custom Error Message with Promised')915+ expect(res.headers.get('x-debug')).toBe('This is Middleware Error')916+ })917 })918 919 describe('Handle HTTPException', () => {920 const app = new Hono()921 922 app.get('/exception', () => {829- throw new HTTPException(401)923+ throw new HTTPException(401, {924+ message: 'Unauthorized',925+ })926 })927 928 it('Should return 401 response', async () => {929 const res = await app.request('http://localhost/exception')980 unmodified lines1910 type: undefined,1911 })1912 })1913 })1914+1915+describe('app.mount()', () => {1916+ describe('Basic', () => {1917+ const anotherApp = (req: Request, params: unknown) => {1918+ const path = getPath(req)1919+ console.log(`path in anotherApp: ${path}`)1920+ if (path === '/') {1921+ return new Response('AnotherApp')1922+ }1923+ if (path === '/hello') {1924+ return new Response('Hello from AnotherApp')1925+ }1926+ if (path === '/header') {1927+ const message = req.headers.get('x-message')1928+ return new Response(message)1929+ }1930+ if (path == '/with-params') {1931+ return new Response(1932+ JSON.stringify({1933+ params,1934+ }),1935+ {1936+ headers: {1937+ 'Content-Type': 'application.json',1938+ },1939+ }1940+ )1941+ }1942+ console.log(`before 404 ${req.url}`)1943+ return new Response('Not Found from AnotherApp', {1944+ status: 404,1945+ })1946+ }1947+1948+ const app = new Hono()1949+ app.use('*', async (c, next) => {1950+ await next()1951+ c.header('x-message', 'Foo')1952+ })1953+ app.get('/', (c) => c.text('Hono'))1954+ app.mount('/another-app', anotherApp, () => {1955+ return 'params'1956+ })1957+ app.mount('/another-app2/sub-slash/', anotherApp)1958+1959+ const api = new Hono().basePath('/api')1960+ api.mount('/another-app', anotherApp)1961+1962+ it('Should return responses from Hono app', async () => {1963+ const res = await app.request('/')1964+ expect(res.status).toBe(200)1965+ expect(res.headers.get('x-message')).toBe('Foo')1966+ expect(await res.text()).toBe('Hono')1967+ })1968+1969+ it('Should return responses from AnotherApp', async () => {1970+ let res = await app.request('/another-app')1971+ expect(res.status).toBe(200)1972+ expect(res.headers.get('x-message')).toBe('Foo')1973+ expect(await res.text()).toBe('AnotherApp')1974+1975+ res = await app.request('/another-app/hello')1976+ expect(res.status).toBe(200)1977+ expect(res.headers.get('x-message')).toBe('Foo')1978+ expect(await res.text()).toBe('Hello from AnotherApp')1979+1980+ const req = new Request('http://localhost/another-app/header', {1981+ headers: {1982+ 'x-message': 'Message Foo!',1983+ },1984+ })1985+ res = await app.request(req)1986+ expect(res.status).toBe(200)1987+ expect(res.headers.get('x-message')).toBe('Foo')1988+ expect(await res.text()).toBe('Message Foo!')1989+1990+ res = await app.request('/another-app/not-found')1991+ expect(res.status).toBe(404)1992+ expect(res.headers.get('x-message')).toBe('Foo')1993+ expect(await res.text()).toBe('Not Found from AnotherApp')1994+1995+ res = await app.request('/another-app/with-params')1996+ expect(res.status).toBe(200)1997+ expect(await res.json()).toEqual({1998+ params: 'params',1999+ })2000+ })2001+2002+ it('Should return responses from AnotherApp - sub + slash', async () => {2003+ const res = await app.request('/another-app2/sub-slash')2004+ expect(res.status).toBe(200)2005+ expect(await res.text()).toBe('AnotherApp')2006+ })2007+2008+ it('Should return responses from AnotherApp - with `basePath()`', async () => {2009+ const res = await api.request('/api/another-app')2010+ expect(res.status).toBe(200)2011+ expect(await res.text()).toBe('AnotherApp')2012+ })2013+ })2014+2015+ describe('With fetch', () => {2016+ const anotherApp = async (req: Request, env: {}, executionContext: ExecutionContext) => {2017+ const path = getPath(req)2018+ if (path === '/') {2019+ return new Response(2020+ JSON.stringify({2021+ env,2022+ executionContext,2023+ }),2024+ {2025+ headers: {2026+ 'Content-Type': 'application/json',2027+ },2028+ }2029+ )2030+ }2031+ return new Response('Not Found from AnotherApp', {2032+ status: 404,2033+ })2034+ }2035+2036+ const app = new Hono()2037+ app.mount('/another-app', anotherApp)2038+2039+ it('Should handle Env and ExecuteContext', async () => {2040+ const request = new Request('http://localhost/another-app')2041+ const res = await app.fetch(2042+ request,2043+ {2044+ TOKEN: 'foo',2045+ },2046+ {2047+ // Force mocking!2048+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment2049+ // @ts-ignore2050+ waitUntil: 'waitUntil',2051+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment2052+ // @ts-ignore2053+ passThroughOnException: 'passThroughOnException',2054+ }2055+ )2056+ expect(res.status).toBe(200)2057+ expect(await res.json()).toEqual({2058+ env: {2059+ TOKEN: 'foo',2060+ },2061+ executionContext: {2062+ waitUntil: 'waitUntil',2063+ passThroughOnException: 'passThroughOnException',2064+ },2065+ })2066+ })2067+ })2068+})2069+2070+describe('Router Name', () => {2071+ it('Should return the correct router name', async () => {2072+ const app = new Hono({2073+ router: new RegExpRouter(),2074+ })2075+ app.get('/router-name', (c) => {2076+ return c.text(app.routerName ?? 'N/A')2077+ })2078+ const res = await app.request('/router-name')2079+ expect(await res.text()).toBe('RegExpRouter')2080+ })2081+})modified:src/hono.ts+13 added-306 removed
1-import { compose } from './compose'2-import { Context } from './context'3-import type { ExecutionContext } from './context'4-import { HTTPException } from './http-exception'5-import type { Router } from './router'6-import { METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE, METHODS } from './router'1+import { HonoBase } from './hono-base'2 import { RegExpRouter } from './router/reg-exp-router'3 import { SmartRouter } from './router/smart-router'4 import { TrieRouter } from './router/trie-router'10-import type {11- Env,12- ErrorHandler,13- H,14- HandlerInterface,15- MiddlewareHandler,16- MiddlewareHandlerInterface,17- Next,18- NotFoundHandler,19- OnHandlerInterface,20- TypedResponse,21- MergePath,22- MergeSchemaPath,23-} from './types'24-import type { RemoveBlankRecord } from './utils/types'25-import { getPathFromURL, mergePath } from './utils/url'5+import type { Env } from './types'6 27-type Methods = typeof METHODS[number] | typeof METHOD_NAME_ALL_LOWERCASE28-29-interface RouterRoute {30- path: string31- method: string32- handler: H33-}34-35-function defineDynamicClass(): {36- new <E extends Env = Env, S = {}, BasePath extends string = ''>(): {37- [M in Methods]: HandlerInterface<E, M, S, BasePath>38- } & {39- on: OnHandlerInterface<E, S, BasePath>40- } & {41- use: MiddlewareHandlerInterface<E, S, BasePath>42- }43-} {44- return class {} as never45-}46-47-const notFoundHandler = (c: Context) => {48- return c.text('404 Not Found', 404)49-}50-51-const errorHandler = (err: Error, c: Context) => {52- if (err instanceof HTTPException) {53- return err.getResponse()54- }55- console.trace(err)56- const message = 'Internal Server Error'57- return c.text(message, 500)58-}59-60-export class Hono<61- E extends Env = Env,62- S = {},63- BasePath extends string = ''64-> extends defineDynamicClass()<E, S, BasePath> {65- readonly router: Router<H> = new SmartRouter({66- routers: [new RegExpRouter(), new TrieRouter()],67- })68- readonly strict: boolean = true // strict routing - default is true69- private _basePath: string = ''70- private path: string = '*'71-72- routes: RouterRoute[] = []73-74- constructor(init: Partial<Pick<Hono, 'router' | 'strict'>> = {}) {75- super()76-77- // Implementation of app.get(...handlers[]) or app.get(path, ...handlers[])78- const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE]79- allMethods.map((method) => {80- this[method] = (args1: string | H, ...args: H[]) => {81- if (typeof args1 === 'string') {82- this.path = args183- } else {84- this.addRoute(method, this.path, args1)85- }86- args.map((handler) => {87- if (typeof handler !== 'string') {88- this.addRoute(method, this.path, handler)89- }90- })91- // eslint-disable-next-line @typescript-eslint/no-explicit-any92- return this as any93- }94- })95-96- // Implementation of app.on(method, path, ...handlers[])97- this.on = (method: string | string[], path: string, ...handlers: H[]) => {98- if (!method) return this99- this.path = path100- for (const m of [method].flat()) {101- handlers.map((handler) => {102- this.addRoute(m.toUpperCase(), this.path, handler)103- })104- }105- // eslint-disable-next-line @typescript-eslint/no-explicit-any106- return this as any107- }108-109- // Implementation of app.use(...handlers[]) or app.get(path, ...handlers[])110- this.use = (arg1: string | MiddlewareHandler, ...handlers: MiddlewareHandler[]) => {111- if (typeof arg1 === 'string') {112- this.path = arg1113- } else {114- handlers.unshift(arg1)115- }116- handlers.map((handler) => {117- this.addRoute(METHOD_NAME_ALL, this.path, handler)7+export class Hono<E extends Env = Env, S = {}, BasePath extends string = '/'> extends HonoBase<8+ E,9+ S,10+ BasePath11+> {12+ constructor(init: Partial<Pick<Hono, 'router' | 'getPath'> & { strict: boolean }> = {}) {13+ super(init)14+ this.router =15+ init.router ??16+ new SmartRouter({17+ routers: [new RegExpRouter(), new TrieRouter()],18 })119- return this120- }121-122- Object.assign(this, init)19 }124-125- private clone(): Hono<E, S, BasePath> {126- const clone = new Hono<E, S, BasePath>({127- router: this.router,128- strict: this.strict,129- })130- clone.routes = this.routes131- return clone132- }133-134- private notFoundHandler: NotFoundHandler = notFoundHandler135- private errorHandler: ErrorHandler = errorHandler136-137- route<SubPath extends string, SubEnv extends Env, SubSchema, SubBasePath extends string>(138- path: SubPath,139- app: Hono<SubEnv, SubSchema, SubBasePath>140- ): Hono<E, RemoveBlankRecord<MergeSchemaPath<SubSchema, SubPath> | S>, BasePath>141- /** @deprecated142- * Use `basePath` instead of `route` with one argument.143- * The `route` with one argument has been removed in v4.144- */145- route<SubPath extends string>(path: SubPath): Hono<E, RemoveBlankRecord<S>, BasePath>146- route<SubPath extends string, SubEnv extends Env, SubSchema, SubBasePath extends string>(147- path: SubPath,148- app?: Hono<SubEnv, SubSchema, SubBasePath>149- ): Hono<E, RemoveBlankRecord<MergeSchemaPath<SubSchema, SubPath> | S>, BasePath> {150- const subApp = this.basePath(path)151-152- if (!app) {153- // eslint-disable-next-line @typescript-eslint/no-explicit-any154- return subApp as any155- }156-157- app.routes.map((r) => {158- const handler =159- app.errorHandler === errorHandler160- ? r.handler161- : async (c: Context, next: Next) =>162- (await compose<Context>([r.handler], app.errorHandler)(c, next)).res163- subApp.addRoute(r.method, r.path, handler)164- })165- // eslint-disable-next-line @typescript-eslint/no-explicit-any166- return this as any167- }168-169- basePath<SubPath extends string>(path: SubPath): Hono<E, S, MergePath<BasePath, SubPath>> {170- const subApp = this.clone()171- subApp._basePath = mergePath(this._basePath, path)172- // eslint-disable-next-line @typescript-eslint/no-explicit-any173- return subApp as any174- }175-176- onError(handler: ErrorHandler<E>) {177- this.errorHandler = handler178- return this179- }180-181- notFound(handler: NotFoundHandler<E>) {182- this.notFoundHandler = handler183- return this184- }185-186- showRoutes() {187- const length = 8188- this.routes.map((route) => {189- console.log(190- `\x1b[32m${route.method}\x1b[0m ${' '.repeat(length - route.method.length)} ${route.path}`191- )192- })193- }194-195- private addRoute(method: string, path: string, handler: H) {196- method = method.toUpperCase()197- if (this._basePath) {198- path = mergePath(this._basePath, path)199- }200- this.router.add(method, path, handler)201- const r: RouterRoute = { path: path, method: method, handler: handler }202- this.routes.push(r)203- }204-205- private matchRoute(method: string, path: string) {206- return this.router.match(method, path)207- }208-209- private handleError(err: unknown, c: Context<E>) {210- if (err instanceof Error) {211- return this.errorHandler(err, c)212- }213- throw err214- }215-216- private dispatch(217- request: Request,218- eventOrExecutionCtx?: ExecutionContext | FetchEvent,219- env?: E['Bindings']220- ): Response | Promise<Response> {221- const path = getPathFromURL(request.url, this.strict)222- const method = request.method223-224- const result = this.matchRoute(method, path)225- const paramData = result?.params226-227- const c = new Context(request, {228- env,229- executionCtx: eventOrExecutionCtx,230- notFoundHandler: this.notFoundHandler,231- path,232- paramData,233- })234-235- // Do not `compose` if it has only one handler236- if (result?.handlers.length === 1) {237- const handler = result.handlers[0]238- let res: ReturnType<H>239-240- try {241- res = handler(c, async () => {})242- if (!res) {243- return this.notFoundHandler(c)244- }245- } catch (err) {246- return this.handleError(err, c)247- }248-249- if (res instanceof Response) return res250-251- if ('response' in res) {252- res = res.response253- }254-255- if (res instanceof Response) return res256-257- return (async () => {258- let awaited: Response | TypedResponse | void259- try {260- awaited = await res261- if (awaited !== undefined && 'response' in awaited) {262- awaited = awaited['response'] as Response263- }264- if (!awaited) {265- return this.notFoundHandler(c)266- }267- } catch (err) {268- return this.handleError(err, c)269- }270- return awaited271- })()272- }273-274- const handlers = result ? result.handlers : [this.notFoundHandler]275- const composed = compose<Context>(handlers, this.errorHandler, this.notFoundHandler)276-277- return (async () => {278- try {279- const tmp = composed(c)280- const context = tmp instanceof Promise ? await tmp : tmp281- if (!context.finalized) {282- throw new Error(283- 'Context is not finalized. You may forget returning Response object or `await next()`'284- )285- }286- return context.res287- } catch (err) {288- return this.handleError(err, c)289- }290- })()291- }292-293- handleEvent = (event: FetchEvent) => {294- return this.dispatch(event.request, event)295- }296-297- fetch = (request: Request, Env?: E['Bindings'] | {}, executionCtx?: ExecutionContext) => {298- return this.dispatch(request, executionCtx, Env)299- }300-301- request = async (input: Request | string | URL, requestInit?: RequestInit) => {302- if (input instanceof Request) {303- if (requestInit !== undefined) {304- input = new Request(input, requestInit)305- }306- return await this.fetch(input)307- }308- input = input.toString()309- const path = /^https?:\/\//.test(input) ? input : `http://localhost${mergePath('/', input)}`310- const req = new Request(path, requestInit)311- return await this.fetch(req)312- }20 }modified:src/http-exception.test.ts+3 added-1 removed
2 unmodified lines3 describe('HTTPFatalError', () => {4 it('Should be 401 HTTP exception object', () => {5 // We should throw an exception if is not authorized6 // because next handlers should not be fired.7- const exception = new HTTPException(401)7+ const exception = new HTTPException(401, {8+ message: 'Unauthorized',9+ })10 expect(exception.status).toBe(401)11 expect(exception.message).toBe('Unauthorized')12 const res = exception.getResponse()13 expect(res.status).toBe(401)2 unmodified linesmodified:src/http-exception.ts+2 added-3 removed
1 import type { StatusCode } from './utils/http-status'2-import { getStatusText } from './utils/http-status'2 3 type HTTPExceptionOptions = {4 res?: Response5 message?: string2 unmodified lines8 export class HTTPException extends Error {9 readonly res?: Response10 readonly status: StatusCode11 constructor(status: StatusCode = 500, options?: HTTPExceptionOptions) {13- super(options?.message || getStatusText(status))12+ super(options?.message)13 this.res = options?.res14 this.status = status15 }16 getResponse(): Response {1 unmodified line18 return this.res19 }20 return new Response(this.message, {21 status: this.status,23- statusText: getStatusText(this.status),22+ statusText: this.message,23 })24 }25 }modified:src/index.ts-14 removed
12 unmodified lines13 } from './types'14 export type { Context, ContextVariableMap } from './context'15 export type { HonoRequest } from './request'16 17-declare module './hono' {18- interface Hono {19- fire(): void20- }21-}22-23-Hono.prototype.fire = function () {24- // eslint-disable-next-line @typescript-eslint/ban-ts-comment25- // @ts-ignore26- addEventListener('fetch', (event: FetchEvent): void => {27- void event.respondWith(this.handleEvent(event))28- })29-}30-17 export { Hono }modified:src/middleware.ts+1 added
2 unmodified lines3 export * from './middleware/bearer-auth'4 export * from './middleware/cache'5 export * from './middleware/cookie'6 export * from './middleware/compress'7+export * from './middleware/cookie'8 export * from './middleware/cors'9 export * from './middleware/etag'10 export * from './middleware/html'11 export * from './middleware/jsx'5 unmodified linesmodified:src/mod.ts+1 added
37 unmodified lines38 // Router39 export { RegExpRouter } from './router/reg-exp-router'40 export { TrieRouter } from './router/trie-router'41 export { SmartRouter } from './router/smart-router'42+export { PatternRouter } from './router/pattern-router'43 44 // Validator45 export { validator } from './validator'46 3 unmodified linesmodified:src/request.ts+7 added-7 removed
10 unmodified lines11 import type { BodyData } from './utils/body'12 import type { Cookie } from './utils/cookie'13 import { parse } from './utils/cookie'14 import type { UnionToIntersection } from './utils/types'15-import { getQueryParam, getQueryParams } from './utils/url'15+import { getQueryParam, getQueryParams, decodeURIComponent_ } from './utils/url'16 17 export class HonoRequest<P extends string = '/', I extends Input['out'] = {}> {18 raw: Request19 20 private paramData: Record<string, string> | undefined21- private validatedData: { [K in keyof ValidationTargets]?: {} }21+ private vData: { [K in keyof ValidationTargets]?: {} } // Short name of validatedData22 path: string23 24 constructor(25 request: Request,2 unmodified lines28 ) {29 this.raw = request30 this.path = path31 this.paramData = paramData32- this.validatedData = {}32+ this.vData = {}33 }34 35 param(key: RemoveQuestion<ParamKeys<P>>): UndefinedIfHavingQuestion<ParamKeys<P>>36 param(): UnionToIntersection<ParamKeyToRecord<ParamKeys<P>>>37 param(key?: string): unknown {38 if (this.paramData) {39 if (key) {40 const param = this.paramData[key]41- return param ? (/\%/.test(param) ? decodeURIComponent(param) : param) : undefined41+ return param ? (/\%/.test(param) ? decodeURIComponent_(param) : param) : undefined42 } else {43 const decoded: Record<string, string> = {}44 45 for (const [key, value] of Object.entries(this.paramData)) {46 if (value && typeof value === 'string') {47- decoded[key] = /\%/.test(value) ? decodeURIComponent(value) : value47+ decoded[key] = /\%/.test(value) ? decodeURIComponent_(value) : value48 }49 }50 51 return decoded86 unmodified lines138 return this.raw.formData()139 }140 141 addValidatedData(target: keyof ValidationTargets, data: {}) {142- this.validatedData[target] = data142+ this.vData[target] = data143 }144 145 valid<146 T extends keyof ValidationTargets = I extends Record<infer R, unknown>4 unmodified lines151 >(target: T): InputToDataByTarget<I, T>152 valid(): never153 valid(target?: keyof ValidationTargets) {154 if (target) {155- return this.validatedData[target] as unknown155+ return this.vData[target] as unknown156 }157 }158 159 get url() {42 unmodified linesmodified:src/router.ts+1 added
1 unmodified line2 export const METHOD_NAME_ALL_LOWERCASE = 'all' as const3 export const METHODS = ['get', 'post', 'put', 'delete', 'head', 'options', 'patch'] as const4 5 export interface Router<T> {6+ name: string7 add(method: string, path: string, handler: T): void8 match(method: string, path: string): Result<T> | null9 }10 6 unmodified linesmodified:src/types.ts+8 added-3 removed
50 unmodified lines51 | Handler<E, P, I, O>52 | MiddlewareHandler<E, P, I>53 54 export type NotFoundHandler<E extends Env = any> = (c: Context<E>) => Response | Promise<Response>55-export type ErrorHandler<E extends Env = any> = (err: Error, c: Context<E>) => Response55+export type ErrorHandler<E extends Env = any> = (56+ err: Error,57+ c: Context<E>58+) => Response | Promise<Response>59 60 ////////////////////////////////////////61 ////// //////62 ////// HandlerInterface //////133 unmodified lines196 197 export interface MiddlewareHandlerInterface<198 E extends Env = Env,199 S = {},197- BasePath extends string = ''200+ BasePath extends string = '/'201 > {202 //// app.get(...handlers[])203 (...handlers: MiddlewareHandler<E, MergePath<BasePath, ExtractKey<S>>>[]): Hono<E, S, BasePath>204 //// app.get(path, ...handlers[])9 unmodified lines214 ////// OnHandlerInterface //////215 ////// //////216 ////////////////////////////////////////217 215-export interface OnHandlerInterface<E extends Env = Env, S = {}, BasePath extends string = ''> {218+export interface OnHandlerInterface<E extends Env = Env, S = {}, BasePath extends string = '/'> {219 // app.on(method, path, handler, handler)220 <M extends string, P extends string, O = {}, I extends Input = {}>(221 method: M,222 path: P,112 unmodified lines335 : never336 337 export type MergePath<A extends string, B extends string> = A extends ''338 ? B339+ : A extends '/'340+ ? B341 : A extends `${infer P}/`342 ? B extends `/${infer Q}`343 ? `${P}/${Q}`344 : `${P}/${B}`81 unmodified linesmodified:package.json+32 added-5 removed
1 {2 "name": "hono",3- "version": "3.1.8",4- "description": "Ultrafast web framework for the Edge",3+ "version": "3.2.0-rc.4",4+ "description": "Ultrafast web framework for the Edges",5 "main": "dist/cjs/index.js",6 "type": "module",7 "module": "dist/index.js",8 "types": "dist/types/index.d.ts",25 unmodified lines34 "types": "./dist/types/index.d.ts",35 "import": "./dist/index.js",36 "require": "./dist/cjs/index.js"37 },38+ "./tiny": {39+ "types": "./dist/types/preset/tiny.d.ts",40+ "import": "./dist/preset/tiny.js",41+ "require": "./dist/cjs/preset/tiny.js"42+ },43+ "./quick": {44+ "types": "./dist/types/preset/quick.d.ts",45+ "import": "./dist/preset/quick.js",46+ "require": "./dist/cjs/preset/quick.js"47+ },48 "./http-exception": {49 "types": "./dist/types/http-exception.d.ts",50 "import": "./dist/http-exception.js",51 "require": "./dist/cjs/http-exception.js"141 unmodified lines193 "./aws-lambda": {194 "types": "./dist/types/adapter/aws-lambda/index.d.ts",195 "import": "./dist/adapter/aws-lambda/index.js",196 "require": "./dist/cjs/adapter/aws-lambda/index.js"197+ },198+ "./vercel": {199+ "types": "./dist/types/adapter/vercel/index.d.ts",200+ "import": "./dist/adapter/vercel/index.js",201+ "require": "./dist/cjs/adapter/vercel/index.js"202 }203 },204 "typesVersions": {205 "*": {206+ "tiny": [207+ "./dist/types/preset/tiny"208+ ],209+ "quick": [210+ "./dist/types/preset/quick"211+ ],212 "http-exception": [213 "./dist/types/http-exception"214 ],215 "basic-auth": [81 unmodified lines297 "./dist/types/adapter/nextjs"298 ],299 "aws-lambda": [300 "./dist/types/adapter/aws-lambda"301+ ],302+ "vercel": [303+ "./dist/types/adapter/vercel"304 ]305 }306 },307 "author": "Yusuke Wada <yusuke@kamawada.com> (https://github.com/yusukebe)",18 unmodified lines326 "workers",327 "fastly",328 "compute@edge",329 "deno",306- "bun"330+ "bun",331+ "lagon",332+ "lambda",333+ "nodejs"334 ],335 "devDependencies": {336 "@cloudflare/workers-types": "^4.20221111.1",337 "@hono/node-server": "^0.2.3",22 unmodified lines360 "jest-environment-miniflare": "2.7.1",361 "jest-preset-fastly-js-compute": "^0.6.1",362 "msw": "^1.0.0",363 "node-fetch": "2",337- "np": "^7.6.2",364+ "np": "^7.7.0",365 "prettier": "^2.6.2",366 "publint": "^0.1.8",367 "rimraf": "^3.0.2",368 "start-server-and-test": "^1.15.2",6 unmodified lines375 },376 "engines": {377 "node": ">=16.0.0"378 }352-}379+}modified:README.md+14 added-13 removed
24 unmodified lines25 [](https://doc.deno.land/https/deno.land/x/hono/mod.ts)26 [](https://discord.gg/KMh2eNSdxV)27 28 Hono - _**\[炎\] means flame🔥 in Japanese**_ - is a small, simple, and ultrafast web framework for the Edges.29-It works on Cloudflare Workers, Fastly Compute@Edge, Deno, Bun, Vercel, Lagon, Node.js, and others.29+It works on any JavaScrip runtime: Cloudflare Workers, Fastly Compute@Edge, Deno, Bun, Vercel, Lagon, AWS Lambda, and Node.js.30+31 Fast, but not only fast.32 33 ```ts34 import { Hono } from 'hono'11 unmodified lines46 ```47 48 ## Features49 49-- **Ultrafast** - The routers are really fast and smart. Not using linear loops. Fast.50-- **Multi-runtime** - Works on Cloudflare Workers, Fastly Compute@Edge, Deno, Bun, Lagon, or Node.js. The same code runs on all platforms.51-- **Batteries Included** - Hono has built-in middleware, custom middleware, and third-party middleware. Batteries included.52-- **Delightful DX** - First-class TypeScript support. Now, we've got "Types".53-- **Small** - About 20kB. Zero-dependencies. Using only Web Standard API.50+- **Ultrafast** 🚀 - The router `RegExpRouter` is really fast. Not using linear loops. Fast.51+- **Lightweight** 🪶 - The `hono/tiny` preset is under 12kB. Hono has zero dependencies and uses only the Web Standard API.52+- **Multi-runtime** 🌍 - Works on Cloudflare Workers, Fastly Compute@Edge, Deno, Bun, Lagon, AWS Lambda, or Node.js. The same code runs on all platforms.53+- **Batteries Included** 🔋 - Hono has built-in middleware, custom middleware, and third-party middleware. Batteries included.54+- **Delightful DX** 🛠️ - Super clean APIs. First-class TypeScript support. Now, we've got "Types".55 56 ## Benchmarks57 58 **Hono is the fastest**, compared to other routers for Cloudflare Workers.59 60 ```60-Hono x 385,807 ops/sec ±5.02% (76 runs sampled)61-itty-router x 205,318 ops/sec ±3.63% (84 runs sampled)62-sunder x 287,198 ops/sec ±4.90% (74 runs sampled)63-worktop x 191,134 ops/sec ±3.06% (85 runs sampled)61+Hono x 402,820 ops/sec ±4.78% (80 runs sampled)62+itty-router x 212,598 ops/sec ±3.11% (87 runs sampled)63+sunder x 297,036 ops/sec ±4.76% (77 runs sampled)64+worktop x 197,345 ops/sec ±2.40% (88 runs sampled)65 Fastest is Hono65-✨ Done in 27.51s.66+✨ Done in 28.06s.67 ```68 69 ## Documentation70 20 unmodified lines91 For more details, see [docs/CONTRIBUTING.md](docs/CONTRIBUTING.md).92 93 ## Contributors94 94-Thanks to [all contributors](https://github.com/honojs/hono/graphs/contributors)! Especially, [@metrue](https://github.com/metrue) and [@usualoma](https://github.com/usualoma)!95+Thanks to [all contributors](https://github.com/honojs/hono/graphs/contributors)!96 97 ## Authors98 99 Yusuke Wada <https://github.com/yusukebe>100 100-"RegExpRouter" and "SmartRouter" are created by Taku Amano <https://github.com/usualoma>101+_RegExpRouter_, _SmartRouter_, _LinearRouter_, and _PatternRouter_ are created by Taku Amano <https://github.com/usualoma>102 103 ## License104 105 Distributed under the MIT License. See [LICENSE](LICENSE) for more information.modified:yarn.lock+4 added-4 removed
6021 unmodified lines6022 version "6.1.0"6023 resolved "https://registry.yarnpkg.com/normalize-url/-/normalize-url-6.1.0.tgz#40d0885b535deffe3f3147bec877d05fe4c5668a"6024 integrity sha512-DlL+XwOy3NxAQ8xuC0okPgK46iuVNAK01YN7RueYBqqFeGsBjV9XmCAzAdgt+667bCl5kPh9EqKKDwnaPG1I7A==6025 6026-np@^7.6.2:6027- version "7.6.2"6028- resolved "https://registry.yarnpkg.com/np/-/np-7.6.2.tgz#02650c024b232cb8c958846c44f672c2f8951b7c"6029- integrity sha512-gExmKGKixh7ITc4Q+Lv7nfCby0CVKvzri9zN8970oKD8976T4L5dw8QWUtMcXcIjhFF6h5lbvztao/NurDbmxQ==6026+np@^7.7.0:6027+ version "7.7.0"6028+ resolved "https://registry.yarnpkg.com/np/-/np-7.7.0.tgz#7fbf2495f6395bcc702b84ca38c4a125363fd5a5"6029+ integrity sha512-G4HfO6JUl7iKOX1qfYHM/kG5ApqqZ4ma8YjtVAJoyS5VdKkGE/OdSG3cOE9Lwr71klNz9n6KIZmPRnh0L7qM1Q==6030 dependencies:6031 "@samverschueren/stream-to-observable" "^0.3.1"6032 any-observable "^0.5.1"6033 async-exit-hook "^2.0.1"1947 unmodified lines