Merge pull request #905 from honojs/next
Before adoption: this commit came in with the history the project adopted, so no landing records it.
v3
authored by Yusuke Wada · committed by GitHub · parents 93da440, 433ed53 · Browse files · 169 files·+7374 added−6552 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
169 files+7374 added−6552 removed
- tests:+2267 added−3082 removed
- other:+5107 added−3470 removed
Provenance
- Commit
4b75b94- Tree
160283b- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent 1
93da440- Parent 2
433ed53
169 files changed+7374 added−6552 removed
modified:.github/workflows/ci.yml+33 added-12 removed
12344567891011111213141516121319201415221617181920212223242526272829353031323334353637384339404142434445464748495051525354555657585960612 unmodified lines64656667686970717273747576777879name: cion: push: branches: [main] branches: [main, next] pull_request: branches: ['*']
jobs: ci: name: 'Cloudflare Workers (main)' runs-on: ubuntu-latest
strategy: matrix: node-version: [16.x, 18.x] # See supported Node.js release schedule at https://nodejs.org/en/about/releases/
steps: - uses: actions/checkout@v2 - name: Use Node.js ${{ matrix.node-version }} uses: actions/setup-node@v2 - uses: actions/setup-node@v2 with: node-version: ${{ matrix.node-version }} node-version: 18.x - run: yarn install --frozen-lockfile - run: npm run lint - run: npm run build - run: npm test
deno: name: 'Deno' runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: denoland/setup-deno@v1 with: deno-version: v1.x - run: deno test --allow-read deno_test - run: deno test --allow-read test_deno
bun: name: 'Bun' runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions/setup-node@v2 with: node-version: 16.x node-version: 18.x - run: curl -fsSL https://bun.sh/install | bash - run: echo "${HOME}/.bun/bin" >> $GITHUB_PATH - run: npm run test:bun
fastly: name: 'Fastly Compute@Edge' runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions/setup-node@v2 with: node-version: 18.x - run: yarn install --frozen-lockfile - run: npm run build - run: npm run test:fastly
lagon: name: 'Lagon' runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions/setup-node@v22 unmodified lines - run: yarn install --frozen-lockfile - run: npm run build - run: npm i -g @lagon/cli@latest esbuild@latest - run: npm run test:lagon
node: name: 'Node.js' runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 - uses: actions/setup-node@v2 with: node-version: 18.x - run: yarn install --frozen-lockfile - run: npm run build - run: npm run test:nodemodified:benchmarks/deno/hono.ts+2 added-2 removed
11233456713 unmodified linesimport { Hono } from '../../deno_dist/mod.ts'import { Hono, RegExpRouter } from '../../deno_dist/mod.ts'
const app = new Hono()const app = new Hono({ router: new RegExpRouter() })
app.get('/user', (c) => c.text('User'))app.get('/user/comments', (c) => c.text('User Comments'))app.get('/user/avatar', (c) => c.text('User Avatar'))13 unmodified linesadded:benchmarks/deno/magalo.ts+20 added
1234567891011121314151617181920import { Megalo } from 'https://deno.land/x/megalo@v0.3.0/mod.ts'
const app = new Megalo()
app.get('/user', () => {})app.get('/user/comments', () => {})app.get('/user/avatar', () => {})app.get('/user/lookup/email/:address', () => {})app.get('/event/:id', () => {})app.get('/event/:id/comments', () => {})app.post('/event/:id/comments', () => {})app.post('/status', () => {})app.get('/very/deeply/nested/route/hello/there', () => {})app.get('/user/lookup/username/:username', ({ params }, res) => { res.json({ message: `Hello ${params.username}`, })})
app.listen({ port: 8000 })modified:benchmarks/handle-event/index.js+4 added-4 removed
1 import Benchmark from 'benchmark'2 import { makeEdgeEnv } from 'edge-mock'3-import itty from 'itty-router'4-const { Router: IttyRouter } = itty3+import { Router as IttyRouter } from 'itty-router'4 import { Request, Response } from 'node-fetch'5 import { Router as SunderRouter, Sunder } from 'sunder'6 import { Router as WorktopRouter } from 'worktop'8-import { Hono } from '../../dist/cjs/hono'7+import { Hono } from '../../dist/hono'8+import { RegExpRouter } from '../../dist/router/reg-exp-router'9 10 globalThis.Request = Request11 globalThis.Response = Response12 12 unmodified lines25 })26 return hono27 }28 29-const hono = initHono(new Hono())29+const hono = initHono(new Hono({ router: new RegExpRouter() }))30 31 // itty-router32 const ittyRouter = IttyRouter()33 ittyRouter.get('/user', () => new Response('User'))116 unmodified linesmodified:benchmarks/handle-event/package.json+2 added-2 removed
11 unmodified lines12131415161617181920212111 unmodified lines "license": "MIT", "devDependencies": { "benchmark": "^2.1.4", "edge-mock": "^0.0.15", "itty-router": "^2.6.3", "itty-router": "^3.0.11", "node-fetch": "^3.2.10", "sunder": "^0.10.1", "worktop": "^0.7.3" }}}No newline at end of filemodified:benchmarks/handle-event/yarn.lock+4 added-4 removed
343 unmodified lines344 version "7.0.0"345 resolved "https://registry.yarnpkg.com/is-number/-/is-number-7.0.0.tgz#7535345b896734d5f80c4d06c50955527a14f12b"346 integrity sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==347 348-itty-router@^2.6.3:349- version "2.6.3"350- resolved "https://registry.yarnpkg.com/itty-router/-/itty-router-2.6.3.tgz#d95a8b6873da0cdcc7e4955e2dbbac2982aba27e"351- integrity sha512-w9aELaE7U/vH5ykJ2wacgNe0hOa1z4XdiSgYgAuEg1eZ+G8wZvURWIa3Vib2UhrFY2r+hZgVIjP1mFO+Vkhk5Q==348+itty-router@^3.0.11:349+ version "3.0.11"350+ resolved "https://registry.yarnpkg.com/itty-router/-/itty-router-3.0.11.tgz#256c2ef0a12721a839656f49db640d40ed2fb308"351+ integrity sha512-vWsoHBi2CmU15YzyUeHjRfjdySL2jqZQKA9jP1LXkBcLJAo0KQNVlQMvhtzG0mzABhVYifeBF97UkrrpuTCWYQ==352 353 livereload-js@^3.3.1:354 version "3.4.0"355 resolved "https://registry.yarnpkg.com/livereload-js/-/livereload-js-3.4.0.tgz#2083158125f16fb5207141bbadb9bdc26cfdb1ef"323 unmodified linesadded:benchmarks/routers/src/bench.mts+82 added
1+import { run, bench, group } from 'mitata'2+import { expressRouter } from './express.mts'3+import { findMyWayRouter } from './find-my-way.mts'4+import { regExpRouter, trieRouter } from './hono.mts'5+import { koaRouter } from './koa-router.mts'6+import { koaTreeRouter } from './koa-tree-router.mts'7+import { medleyRouter } from './medley-router.mts'8+import type { Route, RouterInterface } from './tool.mts'9+import { trekRouter } from './trek-router.mts'10+11+const routers: RouterInterface[] = [12+ regExpRouter,13+ trieRouter,14+ medleyRouter,15+ findMyWayRouter,16+ koaTreeRouter,17+ trekRouter,18+ expressRouter,19+ koaRouter,20+]21+22+medleyRouter.match({ method: 'GET', path: '/user' })23+24+const routes: (Route & { name: string })[] = [25+ {26+ name: 'short static',27+ method: 'GET',28+ path: '/user',29+ },30+ {31+ name: 'static with same radix',32+ method: 'GET',33+ path: '/user/comments',34+ },35+ {36+ name: 'dynamic route',37+ method: 'GET',38+ path: '/user/lookup/username/hey',39+ },40+ {41+ name: 'mixed static dynamic',42+ method: 'GET',43+ path: '/event/abcd1234/comments',44+ },45+ {46+ name: 'post',47+ method: 'POST',48+ path: '/event/abcd1234/comment',49+ },50+ {51+ name: 'long static',52+ method: 'GET',53+ path: '/very/deeply/nested/route/hello/there',54+ },55+ {56+ name: 'wildcard',57+ method: 'GET',58+ path: '/static/index.html',59+ },60+]61+62+for (const route of routes) {63+ group(`${route.name} - ${route.method} ${route.path}`, () => {64+ for (const router of routers) {65+ bench(router.name, async () => {66+ router.match(route)67+ })68+ }69+ })70+}71+72+group('all together', () => {73+ for (const router of routers) {74+ bench(router.name, async () => {75+ for (const route of routes) {76+ router.match(route)77+ }78+ })79+ }80+})81+82+await run()added:benchmarks/routers/src/express.mts+21 added
123456789101112131415161718192021import routerFunc from 'express/lib/router/index.js'import type { RouterInterface } from './tool.mts'import { routes, handler } from './tool.mts'
const router = routerFunc()const name = 'express (WARNING: includes handling)'
for (const route of routes) { if (route.method === 'GET') { router.route(route.path).get(handler) } else { router.route(route.path).post(handler) }}
export const expressRouter: RouterInterface = { name, match: (route) => { router.handle({ method: route.method, url: route.path }) },}added:benchmarks/routers/src/find-my-way.mts+18 added
123456789101112131415161718import type { HTTPMethod } from 'find-my-way'import findMyWay from '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/src/hono.mts+20 added
1+import type { Router } from '../../../src/router.ts'2+import { RegExpRouter } from '../../../src/router/reg-exp-router/index.ts'3+import { TrieRouter } from '../../../src/router/trie-router/index.ts'4+import type { RouterInterface } from './tool.mts'5+import { routes, handler } from './tool.mts'6+7+const createHonoRouter = (name: string, router: Router<unknown>): RouterInterface => {8+ for (const route of routes) {9+ router.add(route.method, route.path, handler)10+ }11+ return {12+ name: `Hono ${name}`,13+ match: (route) => {14+ router.match(route.method, route.path)15+ },16+ }17+}18+19+export const regExpRouter = createHonoRouter('RegExpRouter', new RegExpRouter())20+export const trieRouter = createHonoRouter('TrieRouter', new TrieRouter())added:benchmarks/routers/src/koa-router.mts+21 added
1+import KoaRouter from 'koa-router'2+import type { RouterInterface } from './tool.mts'3+import { routes, handler } from './tool.mts'4+5+const name = 'koa-router'6+const router = new KoaRouter()7+8+for (const route of routes) {9+ if (route.method === 'GET') {10+ router.get(route.path.replace('*', '(.*)'), handler)11+ } else {12+ router.post(route.path, handler)13+ }14+}15+16+export const koaRouter: RouterInterface = {17+ name,18+ match: (route) => {19+ router.match(route.path, route.method) // only matching20+ },21+}added:benchmarks/routers/src/koa-tree-router.mts+19 added
1+import KoaRouter from 'koa-tree-router'2+import type { RouterInterface } from './tool.mts'3+import { routes, handler } from './tool.mts'4+5+const name = 'koa-tree-router'6+const router = new KoaRouter()7+8+for (const route of routes) {9+ router.on(route.method, route.path.replace('*', '*foo'), handler)10+}11+12+export const koaTreeRouter: RouterInterface = {13+ name,14+ match: (route) => {15+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment16+ // @ts-ignore17+ router.find(route.method, route.path)18+ },19+}added:benchmarks/routers/src/medley-router.mts+19 added
1+import Router from '@medley/router'2+import type { RouterInterface } from './tool.mts'3+import { routes, handler } from './tool.mts'4+5+const name = '@medley/router'6+const router = new Router()7+8+for (const route of routes) {9+ const store = router.register(route.path)10+ store[route.method] = handler11+}12+13+export const medleyRouter: RouterInterface = {14+ name,15+ match: (route) => {16+ const match = router.find(route.path)17+ match.store[route.method] // get handler18+ },19+}added:benchmarks/routers/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/src/trek-router.mts+17 added
1+import TrekRouter from '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/package.json+19 added
1+{2+ "scripts": {3+ "bench:node": "tsx ./src/bench.mts",4+ "bench:bun": "bun run ./src/bench.mts"5+ },6+ "license": "MIT",7+ "devDependencies": {8+ "tsx": "^3.12.2"9+ },10+ "dependencies": {11+ "@medley/router": "^0.2.1",12+ "express": "^4.18.2",13+ "find-my-way": "^7.4.0",14+ "koa-router": "^12.0.0",15+ "koa-tree-router": "^0.12.1",16+ "mitata": "^0.1.6",17+ "trek-router": "^1.2.0"18+ }19+}added:benchmarks/routers/README.md+32 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+- [express](https://www.npmjs.com/package/express)9+- [koa-router](https://github.com/alexmingoia/koa-router)10+- [koa-tree-router](https://github.com/steambap/koa-tree-router)11+- [trek-router](https://www.npmjs.com/package/trek-router)12+- [@medley/router](https://www.npmjs.com/package/@medley/router)13+- [Hono RegExpRouter](https://github.com/honojs/hono)14+- [Hono TrieRouter](https://github.com/honojs/hono)15+16+For Node.js:17+18+```19+yarn bench:node20+```21+22+For Bun:23+24+```25+yarn bench:bun26+```27+28+This project heavily impaired by [delvedor/router-benchmark](https://github.com/delvedor/router-benchmark)29+30+## License31+32+MITadded:benchmarks/routers/tsconfig.json+7 added
1+{2+ "compilerOptions": {3+ "allowImportingTsExtensions": true,4+ "esModuleInterop": true,5+ "module": "NodeNext"6+ }7+}added:benchmarks/routers/yarn.lock+814 added
1+# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY.2+# yarn lockfile v13+4+5+"@esbuild-kit/cjs-loader@^2.4.1":6+ version "2.4.1"7+ resolved "https://registry.yarnpkg.com/@esbuild-kit/cjs-loader/-/cjs-loader-2.4.1.tgz#5c1183ac3906223f0da3bb4ff5b74d0f0b13c326"8+ integrity sha512-lhc/XLith28QdW0HpHZvZKkorWgmCNT7sVelMHDj3HFdTfdqkwEKvT+aXVQtNAmCC39VJhunDkWhONWB7335mg==9+ dependencies:10+ "@esbuild-kit/core-utils" "^3.0.0"11+ get-tsconfig "^4.2.0"12+13+"@esbuild-kit/core-utils@^3.0.0":14+ version "3.0.0"15+ resolved "https://registry.yarnpkg.com/@esbuild-kit/core-utils/-/core-utils-3.0.0.tgz#e0f8463a32b4a9c9b456a7f9c31a5e038c8d2c19"16+ integrity sha512-TXmwH9EFS3DC2sI2YJWJBgHGhlteK0Xyu1VabwetMULfm3oYhbrsWV5yaSr2NTWZIgDGVLHbRf0inxbjXqAcmQ==17+ dependencies:18+ esbuild "~0.15.10"19+ source-map-support "^0.5.21"20+21+"@esbuild-kit/esm-loader@^2.5.4":22+ version "2.5.4"23+ resolved "https://registry.yarnpkg.com/@esbuild-kit/esm-loader/-/esm-loader-2.5.4.tgz#cd31fe93963f3e21b1c1d07eef2bd2df1b574326"24+ integrity sha512-afmtLf6uqxD5IgwCzomtqCYIgz/sjHzCWZFvfS5+FzeYxOURPUo4QcHtqJxbxWOMOogKriZanN/1bJQE/ZL93A==25+ dependencies:26+ "@esbuild-kit/core-utils" "^3.0.0"27+ get-tsconfig "^4.2.0"28+29+"@esbuild/android-arm@0.15.18":30+ version "0.15.18"31+ resolved "https://registry.yarnpkg.com/@esbuild/android-arm/-/android-arm-0.15.18.tgz#266d40b8fdcf87962df8af05b76219bc786b4f80"32+ integrity sha512-5GT+kcs2WVGjVs7+boataCkO5Fg0y4kCjzkB5bAip7H4jfnOS3dA6KPiww9W1OEKTKeAcUVhdZGvgI65OXmUnw==33+34+"@esbuild/linux-loong64@0.15.18":35+ version "0.15.18"36+ resolved "https://registry.yarnpkg.com/@esbuild/linux-loong64/-/linux-loong64-0.15.18.tgz#128b76ecb9be48b60cf5cfc1c63a4f00691a3239"37+ integrity sha512-L4jVKS82XVhw2nvzLg/19ClLWg0y27ulRwuP7lcyL6AbUWB5aPglXY3M21mauDQMDfRLs8cQmeT03r/+X3cZYQ==38+39+"@medley/router@^0.2.1":40+ version "0.2.1"41+ resolved "https://registry.yarnpkg.com/@medley/router/-/router-0.2.1.tgz#d8b8aad3fb1de710e9bd35e9e249545dc65945d0"42+ integrity sha512-mdvS1spIxmZoUbTdYmWknHtwm72WwrGNoQCDd4RTvcXJ9G6XThxeC3g+cpOf6Fw6vIERHt50pYiJpsk5XTJQ5w==43+ dependencies:44+ object-treeify "^1.1.20"45+46+"@types/accepts@*":47+ version "1.3.5"48+ resolved "https://registry.yarnpkg.com/@types/accepts/-/accepts-1.3.5.tgz#c34bec115cfc746e04fe5a059df4ce7e7b391575"49+ integrity sha512-jOdnI/3qTpHABjM5cx1Hc0sKsPoYCp+DP/GJRGtDlPd7fiV9oXGGIcjW/ZOxLIvjGz8MA+uMZI9metHlgqbgwQ==50+ dependencies:51+ "@types/node" "*"52+53+"@types/body-parser@*":54+ version "1.19.2"55+ resolved "https://registry.yarnpkg.com/@types/body-parser/-/body-parser-1.19.2.tgz#aea2059e28b7658639081347ac4fab3de166e6f0"56+ integrity sha512-ALYone6pm6QmwZoAgeyNksccT9Q4AWZQ6PvfwR37GT6r6FWUPguq6sUmNGSMV2Wr761oQoBxwGGa6DR5o1DC9g==57+ dependencies:58+ "@types/connect" "*"59+ "@types/node" "*"60+61+"@types/connect@*":62+ version "3.4.35"63+ resolved "https://registry.yarnpkg.com/@types/connect/-/connect-3.4.35.tgz#5fcf6ae445e4021d1fc2219a4873cc73a3bb2ad1"64+ integrity sha512-cdeYyv4KWoEgpBISTxWvqYsVy444DOqehiF3fM3ne10AmJ62RSyNkUnxMJXHQWRQQX2eR94m5y1IZyDwBjV9FQ==65+ dependencies:66+ "@types/node" "*"67+68+"@types/content-disposition@*":69+ version "0.5.5"70+ resolved "https://registry.yarnpkg.com/@types/content-disposition/-/content-disposition-0.5.5.tgz#650820e95de346e1f84e30667d168c8fd25aa6e3"71+ integrity sha512-v6LCdKfK6BwcqMo+wYW05rLS12S0ZO0Fl4w1h4aaZMD7bqT3gVUns6FvLJKGZHQmYn3SX55JWGpziwJRwVgutA==72+73+"@types/cookies@*":74+ version "0.7.7"75+ resolved "https://registry.yarnpkg.com/@types/cookies/-/cookies-0.7.7.tgz#7a92453d1d16389c05a5301eef566f34946cfd81"76+ integrity sha512-h7BcvPUogWbKCzBR2lY4oqaZbO3jXZksexYJVFvkrFeLgbZjQkU4x8pRq6eg2MHXQhY0McQdqmmsxRWlVAHooA==77+ dependencies:78+ "@types/connect" "*"79+ "@types/express" "*"80+ "@types/keygrip" "*"81+ "@types/node" "*"82+83+"@types/express-serve-static-core@^4.17.31":84+ version "4.17.33"85+ resolved "https://registry.yarnpkg.com/@types/express-serve-static-core/-/express-serve-static-core-4.17.33.tgz#de35d30a9d637dc1450ad18dd583d75d5733d543"86+ integrity sha512-TPBqmR/HRYI3eC2E5hmiivIzv+bidAfXofM+sbonAGvyDhySGw9/PQZFt2BLOrjUUR++4eJVpx6KnLQK1Fk9tA==87+ dependencies:88+ "@types/node" "*"89+ "@types/qs" "*"90+ "@types/range-parser" "*"91+92+"@types/express@*":93+ version "4.17.16"94+ resolved "https://registry.yarnpkg.com/@types/express/-/express-4.17.16.tgz#986caf0b4b850611254505355daa24e1b8323de8"95+ integrity sha512-LkKpqRZ7zqXJuvoELakaFYuETHjZkSol8EV6cNnyishutDBCCdv6+dsKPbKkCcIk57qRphOLY5sEgClw1bO3gA==96+ dependencies:97+ "@types/body-parser" "*"98+ "@types/express-serve-static-core" "^4.17.31"99+ "@types/qs" "*"100+ "@types/serve-static" "*"101+102+"@types/http-assert@*":103+ version "1.5.3"104+ resolved "https://registry.yarnpkg.com/@types/http-assert/-/http-assert-1.5.3.tgz#ef8e3d1a8d46c387f04ab0f2e8ab8cb0c5078661"105+ integrity sha512-FyAOrDuQmBi8/or3ns4rwPno7/9tJTijVW6aQQjK02+kOQ8zmoNg2XJtAuQhvQcy1ASJq38wirX5//9J1EqoUA==106+107+"@types/http-errors@*":108+ version "2.0.1"109+ resolved "https://registry.yarnpkg.com/@types/http-errors/-/http-errors-2.0.1.tgz#20172f9578b225f6c7da63446f56d4ce108d5a65"110+ integrity sha512-/K3ds8TRAfBvi5vfjuz8y6+GiAYBZ0x4tXv1Av6CWBWn0IlADc+ZX9pMq7oU0fNQPnBwIZl3rmeLp6SBApbxSQ==111+112+"@types/keygrip@*":113+ version "1.0.2"114+ resolved "https://registry.yarnpkg.com/@types/keygrip/-/keygrip-1.0.2.tgz#513abfd256d7ad0bf1ee1873606317b33b1b2a72"115+ integrity sha512-GJhpTepz2udxGexqos8wgaBx4I/zWIDPh/KOGEwAqtuGDkOUJu5eFvwmdBX4AmB8Odsr+9pHCQqiAqDL/yKMKw==116+117+"@types/koa-compose@*":118+ version "3.2.5"119+ resolved "https://registry.yarnpkg.com/@types/koa-compose/-/koa-compose-3.2.5.tgz#85eb2e80ac50be95f37ccf8c407c09bbe3468e9d"120+ integrity sha512-B8nG/OoE1ORZqCkBVsup/AKcvjdgoHnfi4pZMn5UwAPCbhk/96xyv284eBYW8JlQbQ7zDmnpFr68I/40mFoIBQ==121+ dependencies:122+ "@types/koa" "*"123+124+"@types/koa@*", "@types/koa@^2.13.4":125+ version "2.13.5"126+ resolved "https://registry.yarnpkg.com/@types/koa/-/koa-2.13.5.tgz#64b3ca4d54e08c0062e89ec666c9f45443b21a61"127+ integrity sha512-HSUOdzKz3by4fnqagwthW/1w/yJspTgppyyalPVbgZf8jQWvdIXcVW5h2DGtw4zYntOaeRGx49r1hxoPWrD4aA==128+ dependencies:129+ "@types/accepts" "*"130+ "@types/content-disposition" "*"131+ "@types/cookies" "*"132+ "@types/http-assert" "*"133+ "@types/http-errors" "*"134+ "@types/keygrip" "*"135+ "@types/koa-compose" "*"136+ "@types/node" "*"137+138+"@types/mime@*":139+ version "3.0.1"140+ resolved "https://registry.yarnpkg.com/@types/mime/-/mime-3.0.1.tgz#5f8f2bca0a5863cb69bc0b0acd88c96cb1d4ae10"141+ integrity sha512-Y4XFY5VJAuw0FgAqPNd6NNoV44jbq9Bz2L7Rh/J6jLTiHBSBJa9fxqQIvkIld4GsoDOcCbvzOUAbLPsSKKg+uA==142+143+"@types/node@*":144+ version "18.11.18"145+ resolved "https://registry.yarnpkg.com/@types/node/-/node-18.11.18.tgz#8dfb97f0da23c2293e554c5a50d61ef134d7697f"146+ integrity sha512-DHQpWGjyQKSHj3ebjFI/wRKcqQcdR+MoFBygntYOZytCqNfkd2ZC4ARDJ2DQqhjH5p85Nnd3jhUJIXrszFX/JA==147+148+"@types/qs@*":149+ version "6.9.7"150+ resolved "https://registry.yarnpkg.com/@types/qs/-/qs-6.9.7.tgz#63bb7d067db107cc1e457c303bc25d511febf6cb"151+ integrity sha512-FGa1F62FT09qcrueBA6qYTrJPVDzah9a+493+o2PCXsesWHIn27G98TsSMs3WPNbZIEj4+VJf6saSFpvD+3Zsw==152+153+"@types/range-parser@*":154+ version "1.2.4"155+ resolved "https://registry.yarnpkg.com/@types/range-parser/-/range-parser-1.2.4.tgz#cd667bcfdd025213aafb7ca5915a932590acdcdc"156+ integrity sha512-EEhsLsD6UsDM1yFhAvy0Cjr6VwmpMWqFBCb9w07wVugF7w9nfajxLuVmngTIpgS6svCnm6Vaw+MZhoDCKnOfsw==157+158+"@types/serve-static@*":159+ version "1.15.0"160+ resolved "https://registry.yarnpkg.com/@types/serve-static/-/serve-static-1.15.0.tgz#c7930ff61afb334e121a9da780aac0d9b8f34155"161+ integrity sha512-z5xyF6uh8CbjAu9760KDKsH2FcDxZ2tFCsA4HIMWE6IkiYMXfVoa+4f9KX+FN0ZLsaMw1WNG2ETLA6N+/YA+cg==162+ dependencies:163+ "@types/mime" "*"164+ "@types/node" "*"165+166+accepts@~1.3.8:167+ version "1.3.8"168+ resolved "https://registry.yarnpkg.com/accepts/-/accepts-1.3.8.tgz#0bf0be125b67014adcb0b0921e62db7bffe16b2e"169+ integrity sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==170+ dependencies:171+ mime-types "~2.1.34"172+ negotiator "0.6.3"173+174+array-flatten@1.1.1:175+ version "1.1.1"176+ resolved "https://registry.yarnpkg.com/array-flatten/-/array-flatten-1.1.1.tgz#9a5f699051b1e7073328f2a008968b64ea2955d2"177+ integrity sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==178+179+body-parser@1.20.1:180+ version "1.20.1"181+ resolved "https://registry.yarnpkg.com/body-parser/-/body-parser-1.20.1.tgz#b1812a8912c195cd371a3ee5e66faa2338a5c668"182+ integrity sha512-jWi7abTbYwajOytWCQc37VulmWiRae5RyTpaCyDcS5/lMdtwSz5lOpDE67srw/HYe35f1z3fDQw+3txg7gNtWw==183+ dependencies:184+ bytes "3.1.2"185+ content-type "~1.0.4"186+ debug "2.6.9"187+ depd "2.0.0"188+ destroy "1.2.0"189+ http-errors "2.0.0"190+ iconv-lite "0.4.24"191+ on-finished "2.4.1"192+ qs "6.11.0"193+ raw-body "2.5.1"194+ type-is "~1.6.18"195+ unpipe "1.0.0"196+197+buffer-from@^1.0.0:198+ version "1.1.2"199+ resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.2.tgz#2b146a6fd72e80b4f55d255f35ed59a3a9a41bd5"200+ integrity sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==201+202+bytes@3.1.2:203+ version "3.1.2"204+ resolved "https://registry.yarnpkg.com/bytes/-/bytes-3.1.2.tgz#8b0beeb98605adf1b128fa4386403c009e0221a5"205+ integrity sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==206+207+call-bind@^1.0.0:208+ version "1.0.2"209+ resolved "https://registry.yarnpkg.com/call-bind/-/call-bind-1.0.2.tgz#b1d4e89e688119c3c9a903ad30abb2f6a919be3c"210+ integrity sha512-7O+FbCihrB5WGbFYesctwmTKae6rOiIzmz1icreWJ+0aA7LJfuqhEso2T9ncpcFtzMQtzXf2QGGueWJGTYsqrA==211+ dependencies:212+ function-bind "^1.1.1"213+ get-intrinsic "^1.0.2"214+215+content-disposition@0.5.4:216+ version "0.5.4"217+ resolved "https://registry.yarnpkg.com/content-disposition/-/content-disposition-0.5.4.tgz#8b82b4efac82512a02bb0b1dcec9d2c5e8eb5bfe"218+ integrity sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==219+ dependencies:220+ safe-buffer "5.2.1"221+222+content-type@~1.0.4:223+ version "1.0.4"224+ resolved "https://registry.yarnpkg.com/content-type/-/content-type-1.0.4.tgz#e138cc75e040c727b1966fe5e5f8c9aee256fe3b"225+ integrity sha512-hIP3EEPs8tB9AT1L+NUqtwOAps4mk2Zob89MWXMHjHWg9milF/j4osnnQLXBCBFBk/tvIG/tUc9mOUJiPBhPXA==226+227+cookie-signature@1.0.6:228+ version "1.0.6"229+ resolved "https://registry.yarnpkg.com/cookie-signature/-/cookie-signature-1.0.6.tgz#e303a882b342cc3ee8ca513a79999734dab3ae2c"230+ integrity sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==231+232+cookie@0.5.0:233+ version "0.5.0"234+ resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.5.0.tgz#d1f5d71adec6558c58f389987c366aa47e994f8b"235+ integrity sha512-YZ3GUyn/o8gfKJlnlX7g7xq4gyO6OSuhGPKaaGssGB2qgDUS0gPgtTvoyZLTt9Ab6dC4hfc9dV5arkvc/OCmrw==236+237+debug@2.6.9:238+ version "2.6.9"239+ resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f"240+ integrity sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==241+ dependencies:242+ ms "2.0.0"243+244+depd@2.0.0:245+ version "2.0.0"246+ resolved "https://registry.yarnpkg.com/depd/-/depd-2.0.0.tgz#b696163cc757560d09cf22cc8fad1571b79e76df"247+ integrity sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==248+249+destroy@1.2.0:250+ version "1.2.0"251+ resolved "https://registry.yarnpkg.com/destroy/-/destroy-1.2.0.tgz#4803735509ad8be552934c67df614f94e66fa015"252+ integrity sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==253+254+ee-first@1.1.1:255+ version "1.1.1"256+ resolved "https://registry.yarnpkg.com/ee-first/-/ee-first-1.1.1.tgz#590c61156b0ae2f4f0255732a158b266bc56b21d"257+ integrity sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==258+259+encodeurl@~1.0.2:260+ version "1.0.2"261+ resolved "https://registry.yarnpkg.com/encodeurl/-/encodeurl-1.0.2.tgz#ad3ff4c86ec2d029322f5a02c3a9a606c95b3f59"262+ integrity sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==263+264+esbuild-android-64@0.15.18:265+ version "0.15.18"266+ resolved "https://registry.yarnpkg.com/esbuild-android-64/-/esbuild-android-64-0.15.18.tgz#20a7ae1416c8eaade917fb2453c1259302c637a5"267+ integrity sha512-wnpt3OXRhcjfIDSZu9bnzT4/TNTDsOUvip0foZOUBG7QbSt//w3QV4FInVJxNhKc/ErhUxc5z4QjHtMi7/TbgA==268+269+esbuild-android-arm64@0.15.18:270+ version "0.15.18"271+ resolved "https://registry.yarnpkg.com/esbuild-android-arm64/-/esbuild-android-arm64-0.15.18.tgz#9cc0ec60581d6ad267568f29cf4895ffdd9f2f04"272+ integrity sha512-G4xu89B8FCzav9XU8EjsXacCKSG2FT7wW9J6hOc18soEHJdtWu03L3TQDGf0geNxfLTtxENKBzMSq9LlbjS8OQ==273+274+esbuild-darwin-64@0.15.18:275+ version "0.15.18"276+ resolved "https://registry.yarnpkg.com/esbuild-darwin-64/-/esbuild-darwin-64-0.15.18.tgz#428e1730ea819d500808f220fbc5207aea6d4410"277+ integrity sha512-2WAvs95uPnVJPuYKP0Eqx+Dl/jaYseZEUUT1sjg97TJa4oBtbAKnPnl3b5M9l51/nbx7+QAEtuummJZW0sBEmg==278+279+esbuild-darwin-arm64@0.15.18:280+ version "0.15.18"281+ resolved "https://registry.yarnpkg.com/esbuild-darwin-arm64/-/esbuild-darwin-arm64-0.15.18.tgz#b6dfc7799115a2917f35970bfbc93ae50256b337"282+ integrity sha512-tKPSxcTJ5OmNb1btVikATJ8NftlyNlc8BVNtyT/UAr62JFOhwHlnoPrhYWz09akBLHI9nElFVfWSTSRsrZiDUA==283+284+esbuild-freebsd-64@0.15.18:285+ version "0.15.18"286+ resolved "https://registry.yarnpkg.com/esbuild-freebsd-64/-/esbuild-freebsd-64-0.15.18.tgz#4e190d9c2d1e67164619ae30a438be87d5eedaf2"287+ integrity sha512-TT3uBUxkteAjR1QbsmvSsjpKjOX6UkCstr8nMr+q7zi3NuZ1oIpa8U41Y8I8dJH2fJgdC3Dj3CXO5biLQpfdZA==288+289+esbuild-freebsd-arm64@0.15.18:290+ version "0.15.18"291+ resolved "https://registry.yarnpkg.com/esbuild-freebsd-arm64/-/esbuild-freebsd-arm64-0.15.18.tgz#18a4c0344ee23bd5a6d06d18c76e2fd6d3f91635"292+ integrity sha512-R/oVr+X3Tkh+S0+tL41wRMbdWtpWB8hEAMsOXDumSSa6qJR89U0S/PpLXrGF7Wk/JykfpWNokERUpCeHDl47wA==293+294+esbuild-linux-32@0.15.18:295+ version "0.15.18"296+ resolved "https://registry.yarnpkg.com/esbuild-linux-32/-/esbuild-linux-32-0.15.18.tgz#9a329731ee079b12262b793fb84eea762e82e0ce"297+ integrity sha512-lphF3HiCSYtaa9p1DtXndiQEeQDKPl9eN/XNoBf2amEghugNuqXNZA/ZovthNE2aa4EN43WroO0B85xVSjYkbg==298+299+esbuild-linux-64@0.15.18:300+ version "0.15.18"301+ resolved "https://registry.yarnpkg.com/esbuild-linux-64/-/esbuild-linux-64-0.15.18.tgz#532738075397b994467b514e524aeb520c191b6c"302+ integrity sha512-hNSeP97IviD7oxLKFuii5sDPJ+QHeiFTFLoLm7NZQligur8poNOWGIgpQ7Qf8Balb69hptMZzyOBIPtY09GZYw==303+304+esbuild-linux-arm64@0.15.18:305+ version "0.15.18"306+ resolved "https://registry.yarnpkg.com/esbuild-linux-arm64/-/esbuild-linux-arm64-0.15.18.tgz#5372e7993ac2da8f06b2ba313710d722b7a86e5d"307+ integrity sha512-54qr8kg/6ilcxd+0V3h9rjT4qmjc0CccMVWrjOEM/pEcUzt8X62HfBSeZfT2ECpM7104mk4yfQXkosY8Quptug==308+309+esbuild-linux-arm@0.15.18:310+ version "0.15.18"311+ resolved "https://registry.yarnpkg.com/esbuild-linux-arm/-/esbuild-linux-arm-0.15.18.tgz#e734aaf259a2e3d109d4886c9e81ec0f2fd9a9cc"312+ integrity sha512-UH779gstRblS4aoS2qpMl3wjg7U0j+ygu3GjIeTonCcN79ZvpPee12Qun3vcdxX+37O5LFxz39XeW2I9bybMVA==313+314+esbuild-linux-mips64le@0.15.18:315+ version "0.15.18"316+ resolved "https://registry.yarnpkg.com/esbuild-linux-mips64le/-/esbuild-linux-mips64le-0.15.18.tgz#c0487c14a9371a84eb08fab0e1d7b045a77105eb"317+ integrity sha512-Mk6Ppwzzz3YbMl/ZZL2P0q1tnYqh/trYZ1VfNP47C31yT0K8t9s7Z077QrDA/guU60tGNp2GOwCQnp+DYv7bxQ==318+319+esbuild-linux-ppc64le@0.15.18:320+ version "0.15.18"321+ resolved "https://registry.yarnpkg.com/esbuild-linux-ppc64le/-/esbuild-linux-ppc64le-0.15.18.tgz#af048ad94eed0ce32f6d5a873f7abe9115012507"322+ integrity sha512-b0XkN4pL9WUulPTa/VKHx2wLCgvIAbgwABGnKMY19WhKZPT+8BxhZdqz6EgkqCLld7X5qiCY2F/bfpUUlnFZ9w==323+324+esbuild-linux-riscv64@0.15.18:325+ version "0.15.18"326+ resolved "https://registry.yarnpkg.com/esbuild-linux-riscv64/-/esbuild-linux-riscv64-0.15.18.tgz#423ed4e5927bd77f842bd566972178f424d455e6"327+ integrity sha512-ba2COaoF5wL6VLZWn04k+ACZjZ6NYniMSQStodFKH/Pu6RxzQqzsmjR1t9QC89VYJxBeyVPTaHuBMCejl3O/xg==328+329+esbuild-linux-s390x@0.15.18:330+ version "0.15.18"331+ resolved "https://registry.yarnpkg.com/esbuild-linux-s390x/-/esbuild-linux-s390x-0.15.18.tgz#21d21eaa962a183bfb76312e5a01cc5ae48ce8eb"332+ integrity sha512-VbpGuXEl5FCs1wDVp93O8UIzl3ZrglgnSQ+Hu79g7hZu6te6/YHgVJxCM2SqfIila0J3k0csfnf8VD2W7u2kzQ==333+334+esbuild-netbsd-64@0.15.18:335+ version "0.15.18"336+ resolved "https://registry.yarnpkg.com/esbuild-netbsd-64/-/esbuild-netbsd-64-0.15.18.tgz#ae75682f60d08560b1fe9482bfe0173e5110b998"337+ integrity sha512-98ukeCdvdX7wr1vUYQzKo4kQ0N2p27H7I11maINv73fVEXt2kyh4K4m9f35U1K43Xc2QGXlzAw0K9yoU7JUjOg==338+339+esbuild-openbsd-64@0.15.18:340+ version "0.15.18"341+ resolved "https://registry.yarnpkg.com/esbuild-openbsd-64/-/esbuild-openbsd-64-0.15.18.tgz#79591a90aa3b03e4863f93beec0d2bab2853d0a8"342+ integrity sha512-yK5NCcH31Uae076AyQAXeJzt/vxIo9+omZRKj1pauhk3ITuADzuOx5N2fdHrAKPxN+zH3w96uFKlY7yIn490xQ==343+344+esbuild-sunos-64@0.15.18:345+ version "0.15.18"346+ resolved "https://registry.yarnpkg.com/esbuild-sunos-64/-/esbuild-sunos-64-0.15.18.tgz#fd528aa5da5374b7e1e93d36ef9b07c3dfed2971"347+ integrity sha512-On22LLFlBeLNj/YF3FT+cXcyKPEI263nflYlAhz5crxtp3yRG1Ugfr7ITyxmCmjm4vbN/dGrb/B7w7U8yJR9yw==348+349+esbuild-windows-32@0.15.18:350+ version "0.15.18"351+ resolved "https://registry.yarnpkg.com/esbuild-windows-32/-/esbuild-windows-32-0.15.18.tgz#0e92b66ecdf5435a76813c4bc5ccda0696f4efc3"352+ integrity sha512-o+eyLu2MjVny/nt+E0uPnBxYuJHBvho8vWsC2lV61A7wwTWC3jkN2w36jtA+yv1UgYkHRihPuQsL23hsCYGcOQ==353+354+esbuild-windows-64@0.15.18:355+ version "0.15.18"356+ resolved "https://registry.yarnpkg.com/esbuild-windows-64/-/esbuild-windows-64-0.15.18.tgz#0fc761d785414284fc408e7914226d33f82420d0"357+ integrity sha512-qinug1iTTaIIrCorAUjR0fcBk24fjzEedFYhhispP8Oc7SFvs+XeW3YpAKiKp8dRpizl4YYAhxMjlftAMJiaUw==358+359+esbuild-windows-arm64@0.15.18:360+ version "0.15.18"361+ resolved "https://registry.yarnpkg.com/esbuild-windows-arm64/-/esbuild-windows-arm64-0.15.18.tgz#5b5bdc56d341d0922ee94965c89ee120a6a86eb7"362+ integrity sha512-q9bsYzegpZcLziq0zgUi5KqGVtfhjxGbnksaBFYmWLxeV/S1fK4OLdq2DFYnXcLMjlZw2L0jLsk1eGoB522WXQ==363+364+esbuild@~0.15.10:365+ version "0.15.18"366+ resolved "https://registry.yarnpkg.com/esbuild/-/esbuild-0.15.18.tgz#ea894adaf3fbc036d32320a00d4d6e4978a2f36d"367+ integrity sha512-x/R72SmW3sSFRm5zrrIjAhCeQSAWoni3CmHEqfQrZIQTM3lVCdehdwuIqaOtfC2slvpdlLa62GYoN8SxT23m6Q==368+ optionalDependencies:369+ "@esbuild/android-arm" "0.15.18"370+ "@esbuild/linux-loong64" "0.15.18"371+ esbuild-android-64 "0.15.18"372+ esbuild-android-arm64 "0.15.18"373+ esbuild-darwin-64 "0.15.18"374+ esbuild-darwin-arm64 "0.15.18"375+ esbuild-freebsd-64 "0.15.18"376+ esbuild-freebsd-arm64 "0.15.18"377+ esbuild-linux-32 "0.15.18"378+ esbuild-linux-64 "0.15.18"379+ esbuild-linux-arm "0.15.18"380+ esbuild-linux-arm64 "0.15.18"381+ esbuild-linux-mips64le "0.15.18"382+ esbuild-linux-ppc64le "0.15.18"383+ esbuild-linux-riscv64 "0.15.18"384+ esbuild-linux-s390x "0.15.18"385+ esbuild-netbsd-64 "0.15.18"386+ esbuild-openbsd-64 "0.15.18"387+ esbuild-sunos-64 "0.15.18"388+ esbuild-windows-32 "0.15.18"389+ esbuild-windows-64 "0.15.18"390+ esbuild-windows-arm64 "0.15.18"391+392+escape-html@~1.0.3:393+ version "1.0.3"394+ resolved "https://registry.yarnpkg.com/escape-html/-/escape-html-1.0.3.tgz#0258eae4d3d0c0974de1c169188ef0051d1d1988"395+ integrity sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==396+397+etag@~1.8.1:398+ version "1.8.1"399+ resolved "https://registry.yarnpkg.com/etag/-/etag-1.8.1.tgz#41ae2eeb65efa62268aebfea83ac7d79299b0887"400+ integrity sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==401+402+express@^4.18.2:403+ version "4.18.2"404+ resolved "https://registry.yarnpkg.com/express/-/express-4.18.2.tgz#3fabe08296e930c796c19e3c516979386ba9fd59"405+ integrity sha512-5/PsL6iGPdfQ/lKM1UuielYgv3BUoJfz1aUwU9vHZ+J7gyvwdQXFEBIEIaxeGf0GIcreATNyBExtalisDbuMqQ==406+ dependencies:407+ accepts "~1.3.8"408+ array-flatten "1.1.1"409+ body-parser "1.20.1"410+ content-disposition "0.5.4"411+ content-type "~1.0.4"412+ cookie "0.5.0"413+ cookie-signature "1.0.6"414+ debug "2.6.9"415+ depd "2.0.0"416+ encodeurl "~1.0.2"417+ escape-html "~1.0.3"418+ etag "~1.8.1"419+ finalhandler "1.2.0"420+ fresh "0.5.2"421+ http-errors "2.0.0"422+ merge-descriptors "1.0.1"423+ methods "~1.1.2"424+ on-finished "2.4.1"425+ parseurl "~1.3.3"426+ path-to-regexp "0.1.7"427+ proxy-addr "~2.0.7"428+ qs "6.11.0"429+ range-parser "~1.2.1"430+ safe-buffer "5.2.1"431+ send "0.18.0"432+ serve-static "1.15.0"433+ setprototypeof "1.2.0"434+ statuses "2.0.1"435+ type-is "~1.6.18"436+ utils-merge "1.0.1"437+ vary "~1.1.2"438+439+fast-decode-uri-component@^1.0.1:440+ version "1.0.1"441+ resolved "https://registry.yarnpkg.com/fast-decode-uri-component/-/fast-decode-uri-component-1.0.1.tgz#46f8b6c22b30ff7a81357d4f59abfae938202543"442+ integrity sha512-WKgKWg5eUxvRZGwW8FvfbaH7AXSh2cL+3j5fMGzUMCxWBJ3dV3a7Wz8y2f/uQ0e3B6WmodD3oS54jTQ9HVTIIg==443+444+fast-deep-equal@^3.1.3:445+ version "3.1.3"446+ resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz#3a7d56b559d6cbc3eb512325244e619a65c6c525"447+ integrity sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==448+449+fast-querystring@^1.0.0:450+ version "1.1.0"451+ resolved "https://registry.yarnpkg.com/fast-querystring/-/fast-querystring-1.1.0.tgz#bb645c365db88a3b6433fb6484f7e9e66764cfb9"452+ integrity sha512-LWkjBCZlxjnSanuPpZ6mHswjy8hQv3VcPJsQB3ltUF2zjvrycr0leP3TSTEEfvQ1WEMSRl5YNsGqaft9bjLqEw==453+ dependencies:454+ fast-decode-uri-component "^1.0.1"455+456+finalhandler@1.2.0:457+ version "1.2.0"458+ resolved "https://registry.yarnpkg.com/finalhandler/-/finalhandler-1.2.0.tgz#7d23fe5731b207b4640e4fcd00aec1f9207a7b32"459+ integrity sha512-5uXcUVftlQMFnWC9qu/svkWv3GTd2PfUhK/3PLkYNAe7FbqJMt3515HaxE6eRL74GdsriiwujiawdaB1BpEISg==460+ dependencies:461+ debug "2.6.9"462+ encodeurl "~1.0.2"463+ escape-html "~1.0.3"464+ on-finished "2.4.1"465+ parseurl "~1.3.3"466+ statuses "2.0.1"467+ unpipe "~1.0.0"468+469+find-my-way@^7.4.0:470+ version "7.4.0"471+ resolved "https://registry.yarnpkg.com/find-my-way/-/find-my-way-7.4.0.tgz#22363e6cd1c466f88883703e169a20c983f9c9cc"472+ integrity sha512-JFT7eURLU5FumlZ3VBGnveId82cZz7UR7OUu+THQJOwdQXxmS/g8v0KLoFhv97HreycOrmAbqjXD/4VG2j0uMQ==473+ dependencies:474+ fast-deep-equal "^3.1.3"475+ fast-querystring "^1.0.0"476+ safe-regex2 "^2.0.0"477+478+forwarded@0.2.0:479+ version "0.2.0"480+ resolved "https://registry.yarnpkg.com/forwarded/-/forwarded-0.2.0.tgz#2269936428aad4c15c7ebe9779a84bf0b2a81811"481+ integrity sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==482+483+fresh@0.5.2:484+ version "0.5.2"485+ resolved "https://registry.yarnpkg.com/fresh/-/fresh-0.5.2.tgz#3d8cadd90d976569fa835ab1f8e4b23a105605a7"486+ integrity sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==487+488+fsevents@~2.3.2:489+ version "2.3.2"490+ resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-2.3.2.tgz#8a526f78b8fdf4623b709e0b975c52c24c02fd1a"491+ integrity sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==492+493+function-bind@^1.1.1:494+ version "1.1.1"495+ resolved "https://registry.yarnpkg.com/function-bind/-/function-bind-1.1.1.tgz#a56899d3ea3c9bab874bb9773b7c5ede92f4895d"496+ integrity sha512-yIovAzMX49sF8Yl58fSCWJ5svSLuaibPxXQJFLmBObTuCr0Mf1KiPopGM9NiFjiYBCbfaa2Fh6breQ6ANVTI0A==497+498+get-intrinsic@^1.0.2:499+ version "1.2.0"500+ resolved "https://registry.yarnpkg.com/get-intrinsic/-/get-intrinsic-1.2.0.tgz#7ad1dc0535f3a2904bba075772763e5051f6d05f"501+ integrity sha512-L049y6nFOuom5wGyRc3/gdTLO94dySVKRACj1RmJZBQXlbTMhtNIgkWkUHq+jYmZvKf14EW1EoJnnjbmoHij0Q==502+ dependencies:503+ function-bind "^1.1.1"504+ has "^1.0.3"505+ has-symbols "^1.0.3"506+507+get-tsconfig@^4.2.0:508+ version "4.3.0"509+ resolved "https://registry.yarnpkg.com/get-tsconfig/-/get-tsconfig-4.3.0.tgz#4c26fae115d1050e836aea65d6fe56b507ee249b"510+ integrity sha512-YCcF28IqSay3fqpIu5y3Krg/utCBHBeoflkZyHj/QcqI2nrLPC3ZegS9CmIo+hJb8K7aiGsuUl7PwWVjNG2HQQ==511+512+has-symbols@^1.0.3:513+ version "1.0.3"514+ resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.3.tgz#bb7b2c4349251dce87b125f7bdf874aa7c8b39f8"515+ integrity sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==516+517+has@^1.0.3:518+ version "1.0.3"519+ resolved "https://registry.yarnpkg.com/has/-/has-1.0.3.tgz#722d7cbfc1f6aa8241f16dd814e011e1f41e8796"520+ integrity sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==521+ dependencies:522+ function-bind "^1.1.1"523+524+http-errors@2.0.0, http-errors@^2.0.0:525+ version "2.0.0"526+ resolved "https://registry.yarnpkg.com/http-errors/-/http-errors-2.0.0.tgz#b7774a1486ef73cf7667ac9ae0858c012c57b9d3"527+ integrity sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==528+ dependencies:529+ depd "2.0.0"530+ inherits "2.0.4"531+ setprototypeof "1.2.0"532+ statuses "2.0.1"533+ toidentifier "1.0.1"534+535+iconv-lite@0.4.24:536+ version "0.4.24"537+ resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.4.24.tgz#2022b4b25fbddc21d2f524974a474aafe733908b"538+ integrity sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==539+ dependencies:540+ safer-buffer ">= 2.1.2 < 3"541+542+inherits@2.0.4:543+ version "2.0.4"544+ resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c"545+ integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==546+547+ipaddr.js@1.9.1:548+ version "1.9.1"549+ resolved "https://registry.yarnpkg.com/ipaddr.js/-/ipaddr.js-1.9.1.tgz#bff38543eeb8984825079ff3a2a8e6cbd46781b3"550+ integrity sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==551+552+koa-compose@^4.1.0:553+ version "4.1.0"554+ resolved "https://registry.yarnpkg.com/koa-compose/-/koa-compose-4.1.0.tgz#507306b9371901db41121c812e923d0d67d3e877"555+ integrity sha512-8ODW8TrDuMYvXRwra/Kh7/rJo9BtOfPc6qO8eAfC80CnCvSjSl0bkRM24X6/XBBEyj0v1nRUQ1LyOy3dbqOWXw==556+557+koa-router@^12.0.0:558+ version "12.0.0"559+ resolved "https://registry.yarnpkg.com/koa-router/-/koa-router-12.0.0.tgz#94276df8c7aef424b86728b0ff4a69de50050dbc"560+ integrity sha512-zGrdiXygGYW8WvrzeGsHZvKnHs4DzyGoqJ9a8iHlRkiwuEAOAPyI27//OlhoWdgFAEIM3qbUgr0KCuRaP/TCag==561+ dependencies:562+ http-errors "^2.0.0"563+ koa-compose "^4.1.0"564+ methods "^1.1.2"565+ path-to-regexp "^6.2.1"566+567+koa-tree-router@^0.12.1:568+ version "0.12.1"569+ resolved "https://registry.yarnpkg.com/koa-tree-router/-/koa-tree-router-0.12.1.tgz#0db942bca4f16c1472fba574c8f1c3fe7765a1ee"570+ integrity sha512-U/jJoV+rDFYtbaU/X6r2hcNKT7+DZs8HeXONWA7/OSIMk6/cYhoW5P9MPrjg7vHWRrmZOAiFkPoW7vtxvwLWpw==571+ dependencies:572+ "@types/koa" "^2.13.4"573+ koa-compose "^4.1.0"574+575+media-typer@0.3.0:576+ version "0.3.0"577+ resolved "https://registry.yarnpkg.com/media-typer/-/media-typer-0.3.0.tgz#8710d7af0aa626f8fffa1ce00168545263255748"578+ integrity sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==579+580+merge-descriptors@1.0.1:581+ version "1.0.1"582+ resolved "https://registry.yarnpkg.com/merge-descriptors/-/merge-descriptors-1.0.1.tgz#b00aaa556dd8b44568150ec9d1b953f3f90cbb61"583+ integrity sha512-cCi6g3/Zr1iqQi6ySbseM1Xvooa98N0w31jzUYrXPX2xqObmFGHJ0tQ5u74H3mVh7wLouTseZyYIq39g8cNp1w==584+585+methods@^1.1.2, methods@~1.1.2:586+ version "1.1.2"587+ resolved "https://registry.yarnpkg.com/methods/-/methods-1.1.2.tgz#5529a4d67654134edcc5266656835b0f851afcee"588+ integrity sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==589+590+mime-db@1.52.0:591+ version "1.52.0"592+ resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.52.0.tgz#bbabcdc02859f4987301c856e3387ce5ec43bf70"593+ integrity sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==594+595+mime-types@~2.1.24, mime-types@~2.1.34:596+ version "2.1.35"597+ resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-2.1.35.tgz#381a871b62a734450660ae3deee44813f70d959a"598+ integrity sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==599+ dependencies:600+ mime-db "1.52.0"601+602+mime@1.6.0:603+ version "1.6.0"604+ resolved "https://registry.yarnpkg.com/mime/-/mime-1.6.0.tgz#32cd9e5c64553bd58d19a568af452acff04981b1"605+ integrity sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==606+607+mitata@^0.1.6:608+ version "0.1.6"609+ resolved "https://registry.yarnpkg.com/mitata/-/mitata-0.1.6.tgz#0d25f0dd105d6c50ec8d9047ee21bed1552fbffd"610+ integrity sha512-VKQ0r3jriTOU9E2Z+mwbZrUmbg4Li4QyFfi7kfHKl6reZhGzL0AYlu3wE0VPXzIwA5xnFzmEQoBwCcNT8stUkA==611+612+ms@2.0.0:613+ version "2.0.0"614+ resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8"615+ integrity sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==616+617+ms@2.1.3:618+ version "2.1.3"619+ resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2"620+ integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==621+622+negotiator@0.6.3:623+ version "0.6.3"624+ resolved "https://registry.yarnpkg.com/negotiator/-/negotiator-0.6.3.tgz#58e323a72fedc0d6f9cd4d31fe49f51479590ccd"625+ integrity sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==626+627+object-inspect@^1.9.0:628+ version "1.12.3"629+ resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.12.3.tgz#ba62dffd67ee256c8c086dfae69e016cd1f198b9"630+ integrity sha512-geUvdk7c+eizMNUDkRpW1wJwgfOiOeHbxBR/hLXK1aT6zmVSO0jsQcs7fj6MGw89jC/cjGfLcNOrtMYtGqm81g==631+632+object-treeify@^1.1.20:633+ version "1.1.33"634+ resolved "https://registry.yarnpkg.com/object-treeify/-/object-treeify-1.1.33.tgz#f06fece986830a3cba78ddd32d4c11d1f76cdf40"635+ integrity sha512-EFVjAYfzWqWsBMRHPMAXLCDIJnpMhdWAqR7xG6M6a2cs6PMFpl/+Z20w9zDW4vkxOFfddegBKq9Rehd0bxWE7A==636+637+on-finished@2.4.1:638+ version "2.4.1"639+ resolved "https://registry.yarnpkg.com/on-finished/-/on-finished-2.4.1.tgz#58c8c44116e54845ad57f14ab10b03533184ac3f"640+ integrity sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==641+ dependencies:642+ ee-first "1.1.1"643+644+parseurl@~1.3.3:645+ version "1.3.3"646+ resolved "https://registry.yarnpkg.com/parseurl/-/parseurl-1.3.3.tgz#9da19e7bee8d12dff0513ed5b76957793bc2e8d4"647+ integrity sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==648+649+path-to-regexp@0.1.7:650+ version "0.1.7"651+ resolved "https://registry.yarnpkg.com/path-to-regexp/-/path-to-regexp-0.1.7.tgz#df604178005f522f15eb4490e7247a1bfaa67f8c"652+ integrity sha512-5DFkuoqlv1uYQKxy8omFBeJPQcdoE07Kv2sferDCrAq1ohOU+MSDswDIbnx3YAM60qIOnYa53wBhXW0EbMonrQ==653+654+path-to-regexp@^6.2.1:655+ version "6.2.1"656+ resolved "https://registry.yarnpkg.com/path-to-regexp/-/path-to-regexp-6.2.1.tgz#d54934d6798eb9e5ef14e7af7962c945906918e5"657+ integrity sha512-JLyh7xT1kizaEvcaXOQwOc2/Yhw6KZOvPf1S8401UyLk86CU79LN3vl7ztXGm/pZ+YjoyAJ4rxmHwbkBXJX+yw==658+659+proxy-addr@~2.0.7:660+ version "2.0.7"661+ resolved "https://registry.yarnpkg.com/proxy-addr/-/proxy-addr-2.0.7.tgz#f19fe69ceab311eeb94b42e70e8c2070f9ba1025"662+ integrity sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==663+ dependencies:664+ forwarded "0.2.0"665+ ipaddr.js "1.9.1"666+667+qs@6.11.0:668+ version "6.11.0"669+ resolved "https://registry.yarnpkg.com/qs/-/qs-6.11.0.tgz#fd0d963446f7a65e1367e01abd85429453f0c37a"670+ integrity sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q==671+ dependencies:672+ side-channel "^1.0.4"673+674+range-parser@~1.2.1:675+ version "1.2.1"676+ resolved "https://registry.yarnpkg.com/range-parser/-/range-parser-1.2.1.tgz#3cf37023d199e1c24d1a55b84800c2f3e6468031"677+ integrity sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==678+679+raw-body@2.5.1:680+ version "2.5.1"681+ resolved "https://registry.yarnpkg.com/raw-body/-/raw-body-2.5.1.tgz#fe1b1628b181b700215e5fd42389f98b71392857"682+ integrity sha512-qqJBtEyVgS0ZmPGdCFPWJ3FreoqvG4MVQln/kCgF7Olq95IbOp0/BWyMwbdtn4VTvkM8Y7khCQ2Xgk/tcrCXig==683+ dependencies:684+ bytes "3.1.2"685+ http-errors "2.0.0"686+ iconv-lite "0.4.24"687+ unpipe "1.0.0"688+689+ret@~0.2.0:690+ version "0.2.2"691+ resolved "https://registry.yarnpkg.com/ret/-/ret-0.2.2.tgz#b6861782a1f4762dce43402a71eb7a283f44573c"692+ integrity sha512-M0b3YWQs7R3Z917WRQy1HHA7Ba7D8hvZg6UE5mLykJxQVE2ju0IXbGlaHPPlkY+WN7wFP+wUMXmBFA0aV6vYGQ==693+694+safe-buffer@5.2.1:695+ version "5.2.1"696+ resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz#1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6"697+ integrity sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==698+699+safe-regex2@^2.0.0:700+ version "2.0.0"701+ resolved "https://registry.yarnpkg.com/safe-regex2/-/safe-regex2-2.0.0.tgz#b287524c397c7a2994470367e0185e1916b1f5b9"702+ integrity sha512-PaUSFsUaNNuKwkBijoAPHAK6/eM6VirvyPWlZ7BAQy4D+hCvh4B6lIG+nPdhbFfIbP+gTGBcrdsOaUs0F+ZBOQ==703+ dependencies:704+ ret "~0.2.0"705+706+"safer-buffer@>= 2.1.2 < 3":707+ version "2.1.2"708+ resolved "https://registry.yarnpkg.com/safer-buffer/-/safer-buffer-2.1.2.tgz#44fa161b0187b9549dd84bb91802f9bd8385cd6a"709+ integrity sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==710+711+send@0.18.0:712+ version "0.18.0"713+ resolved "https://registry.yarnpkg.com/send/-/send-0.18.0.tgz#670167cc654b05f5aa4a767f9113bb371bc706be"714+ integrity sha512-qqWzuOjSFOuqPjFe4NOsMLafToQQwBSOEpS+FwEt3A2V3vKubTquT3vmLTQpFgMXp8AlFWFuP1qKaJZOtPpVXg==715+ dependencies:716+ debug "2.6.9"717+ depd "2.0.0"718+ destroy "1.2.0"719+ encodeurl "~1.0.2"720+ escape-html "~1.0.3"721+ etag "~1.8.1"722+ fresh "0.5.2"723+ http-errors "2.0.0"724+ mime "1.6.0"725+ ms "2.1.3"726+ on-finished "2.4.1"727+ range-parser "~1.2.1"728+ statuses "2.0.1"729+730+serve-static@1.15.0:731+ version "1.15.0"732+ resolved "https://registry.yarnpkg.com/serve-static/-/serve-static-1.15.0.tgz#faaef08cffe0a1a62f60cad0c4e513cff0ac9540"733+ integrity sha512-XGuRDNjXUijsUL0vl6nSD7cwURuzEgglbOaFuZM9g3kwDXOWVTck0jLzjPzGD+TazWbboZYu52/9/XPdUgne9g==734+ dependencies:735+ encodeurl "~1.0.2"736+ escape-html "~1.0.3"737+ parseurl "~1.3.3"738+ send "0.18.0"739+740+setprototypeof@1.2.0:741+ version "1.2.0"742+ resolved "https://registry.yarnpkg.com/setprototypeof/-/setprototypeof-1.2.0.tgz#66c9a24a73f9fc28cbe66b09fed3d33dcaf1b424"743+ integrity sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==744+745+side-channel@^1.0.4:746+ version "1.0.4"747+ resolved "https://registry.yarnpkg.com/side-channel/-/side-channel-1.0.4.tgz#efce5c8fdc104ee751b25c58d4290011fa5ea2cf"748+ integrity sha512-q5XPytqFEIKHkGdiMIrY10mvLRvnQh42/+GoBlFW3b2LXLE2xxJpZFdm94we0BaoV3RwJyGqg5wS7epxTv0Zvw==749+ dependencies:750+ call-bind "^1.0.0"751+ get-intrinsic "^1.0.2"752+ object-inspect "^1.9.0"753+754+source-map-support@^0.5.21:755+ version "0.5.21"756+ resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.21.tgz#04fe7c7f9e1ed2d662233c28cb2b35b9f63f6e4f"757+ integrity sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==758+ dependencies:759+ buffer-from "^1.0.0"760+ source-map "^0.6.0"761+762+source-map@^0.6.0:763+ version "0.6.1"764+ resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263"765+ integrity sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==766+767+statuses@2.0.1:768+ version "2.0.1"769+ resolved "https://registry.yarnpkg.com/statuses/-/statuses-2.0.1.tgz#55cb000ccf1d48728bd23c685a063998cf1a1b63"770+ integrity sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==771+772+toidentifier@1.0.1:773+ version "1.0.1"774+ resolved "https://registry.yarnpkg.com/toidentifier/-/toidentifier-1.0.1.tgz#3be34321a88a820ed1bd80dfaa33e479fbb8dd35"775+ integrity sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==776+777+trek-router@^1.2.0:778+ version "1.2.0"779+ resolved "https://registry.yarnpkg.com/trek-router/-/trek-router-1.2.0.tgz#670b1630a16c4139973ffc698826a76bb2bf9137"780+ integrity sha512-43A1krE0myUO2DV+RQBUYLwK3Q5osszQ65jFe/TFGWMnhdZx0nvq2GQXecXwIPU0weSFo1pYmHfhHHaUPPIRNg==781+782+tsx@^3.12.2:783+ version "3.12.2"784+ resolved "https://registry.yarnpkg.com/tsx/-/tsx-3.12.2.tgz#1c8a4fa08a97739e6eedf0ad464bd8218e1a64f0"785+ integrity sha512-ykAEkoBg30RXxeOMVeZwar+JH632dZn9EUJVyJwhfag62k6UO/dIyJEV58YuLF6e5BTdV/qmbQrpkWqjq9cUnQ==786+ dependencies:787+ "@esbuild-kit/cjs-loader" "^2.4.1"788+ "@esbuild-kit/core-utils" "^3.0.0"789+ "@esbuild-kit/esm-loader" "^2.5.4"790+ optionalDependencies:791+ fsevents "~2.3.2"792+793+type-is@~1.6.18:794+ version "1.6.18"795+ resolved "https://registry.yarnpkg.com/type-is/-/type-is-1.6.18.tgz#4e552cd05df09467dcbc4ef739de89f2cf37c131"796+ integrity sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==797+ dependencies:798+ media-typer "0.3.0"799+ mime-types "~2.1.24"800+801+unpipe@1.0.0, unpipe@~1.0.0:802+ version "1.0.0"803+ resolved "https://registry.yarnpkg.com/unpipe/-/unpipe-1.0.0.tgz#b2bf4ee8514aae6165b4817829d21b2ef49904ec"804+ integrity sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==805+806+utils-merge@1.0.1:807+ version "1.0.1"808+ resolved "https://registry.yarnpkg.com/utils-merge/-/utils-merge-1.0.1.tgz#9f95710f50a267947b2ccc124741c1028427e713"809+ integrity sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==810+811+vary@~1.1.2:812+ version "1.1.2"813+ resolved "https://registry.yarnpkg.com/vary/-/vary-1.1.2.tgz#2299f02c6ded30d4a5961b0b9f74524a18f634fc"814+ integrity sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==deleted:bun_test/favicon.icobinary
A binary file, deleted.
deleted:bun_test/index.test.tsx-161 removed
1-import { describe, expect, it } from 'bun:test'2-import { Context } from '../src/context'3-import { Hono } from '../src/index'4-import { basicAuth } from '../src/middleware/basic-auth'5-import { jwt } from '../src/middleware/jwt'6-import { serveStatic } from '../src/middleware/serve-static/bun'7-8-// Test just only minimal patterns.9-// Because others are tested well in Cloudflare Workers environment already.10-11-describe('Basic', () => {12- const app = new Hono()13- app.get('/a/:foo', (c) => {14- c.header('x-param', c.req.param('foo'))15- c.header('x-query', c.req.query('q'))16- return c.text('Hello Deno!')17- })18-19- it('Should return 200 Response', async () => {20- const req = new Request('http://localhost/a/foo?q=bar')21- const res = await app.request(req)22- expect(res.status).toBe(200)23- expect(await res.text()).toBe('Hello Deno!')24- expect(res.headers.get('x-param')).toBe('foo')25- expect(res.headers.get('x-query')).toBe('bar')26- })27-28- it('returns current runtime (bun)', async () => {29- const c = new Context(new Request('http://localhost/'))30- expect(c.runtime).toBe('bun')31- })32-})33-34-describe('Basic Auth Middleware', () => {35- const app = new Hono()36-37- const username = 'hono-user-a'38- const password = 'hono-password-a'39- app.use(40- '/auth/*',41- basicAuth({42- username,43- password,44- })45- )46-47- app.get('/auth/*', () => new Response('auth'))48-49- it('Should not authorize, return 401 Response', async () => {50- const req = new Request('http://localhost/auth/a')51- const res = await app.request(req)52- expect(res.status).toBe(401)53- expect(await res.text()).toBe('Unauthorized')54- })55-56- it('Should authorize, return 200 Response', async () => {57- const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'58- const req = new Request('http://localhost/auth/a')59- req.headers.set('Authorization', `Basic ${credential}`)60- const res = await app.request(req)61- expect(res.status).toBe(200)62- expect(await res.text()).toBe('auth')63- })64-})65-66-describe('Serve Static Middleware', () => {67- const app = new Hono()68- app.all('/favicon.ico', serveStatic({ path: './bun_test/favicon.ico' }))69- app.all('/favicon-notfound.ico', serveStatic({ path: './bun_test/favicon-notfound.ico' }))70- app.use('/favicon-notfound.ico', async (c, next) => {71- await next()72- c.header('X-Custom', 'Bun')73- })74-75- it('Should return static file correctly', async () => {76- const res = await app.request(new Request('http://localhost/favicon.ico'))77- await res.arrayBuffer()78- expect(res.status).toBe(200)79- expect(res.headers.get('Content-Type')).toBe('image/x-icon')80- })81-82- it('Should return 404 response', async () => {83- const res = await app.request(new Request('http://localhost/favicon-notfound.ico'))84- expect(res.status).toBe(404)85- expect(res.headers.get('X-Custom')).toBe('Bun')86- })87-})88-89-// Bun support WebCrypto since v0.2.290-// So, JWT middleware works well.91-describe('JWT Auth Middleware', () => {92- const app = new Hono()93- app.use('/jwt/*', jwt({ secret: 'a-secret' }))94- app.get('/jwt/a', (c) => c.text('auth'))95-96- it('Should not authorize, return 401 Response', async () => {97- const req = new Request('http://localhost/jwt/a')98- const res = await app.request(req)99- expect(res.status).toBe(401)100- expect(await res.text()).toBe('Unauthorized')101- })102-103- it('Should authorize, return 200 Response', async () => {104- const credential =105- 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'106- const req = new Request('http://localhost/jwt/a')107- req.headers.set('Authorization', `Bearer ${credential}`)108- const res = await app.request(req)109- expect(res.status).toBe(200)110- expect(await res.text()).toBe('auth')111- })112-})113-114-// To enable JSX middleware,115-// set "jsxImportSource": "hono/jsx" in the tsconfig.json116-describe('JSX Middleware', () => {117- const app = new Hono()118-119- const Layout = (props: { children?: string }) => {120- return <html>{props.children}</html>121- }122-123- app.get('/', (c) => {124- return c.html(<h1>Hello</h1>)125- })126- app.get('/nest', (c) => {127- return c.html(128- <h1>129- <a href='/top'>Hello</a>130- </h1>131- )132- })133- app.get('/layout', (c) => {134- return c.html(135- <Layout>136- <p>hello</p>137- </Layout>138- )139- })140-141- it('Should return rendered HTML', async () => {142- const res = await app.request(new Request('http://localhost/'))143- expect(res.status).toBe(200)144- expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')145- expect(await res.text()).toBe('<h1>Hello</h1>')146- })147-148- it('Should return rendered HTML with nest', async () => {149- const res = await app.request(new Request('http://localhost/nest'))150- expect(res.status).toBe(200)151- expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')152- expect(await res.text()).toBe('<h1><a href="/top">Hello</a></h1>')153- })154-155- it('Should return rendered HTML with Layout', async () => {156- const res = await app.request(new Request('http://localhost/layout'))157- expect(res.status).toBe(200)158- expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')159- expect(await res.text()).toBe('<html><p>hello</p></html>')160- })161-})added:deno_dist/adapter/deno/index.ts+1 added
1+export { serveStatic } from './serve-static.ts'added:deno_dist/adapter/deno/serve-static.ts+52 added
1+import type { Context } from '../../context.ts'2+import type { Next } from '../../types.ts'3+import { getFilePath } from '../../utils/filepath.ts'4+import { getMimeType } from '../../utils/mime.ts'5+6+export type ServeStaticOptions = {7+ root?: string8+ path?: string9+}10+11+const DEFAULT_DOCUMENT = 'index.html'12+13+export const serveStatic = (options: ServeStaticOptions = { root: '' }) => {14+ return async (c: Context, next: Next) => {15+ // Do nothing if Response is already set16+ if (c.finalized) {17+ await next()18+ return19+ }20+21+ const url = new URL(c.req.url)22+23+ let path = getFilePath({24+ filename: options.path ?? decodeURI(url.pathname),25+ root: options.root,26+ defaultDocument: DEFAULT_DOCUMENT,27+ })28+29+ path = `./${path}`30+31+ let content32+33+ try {34+ content = await Deno.readFile(path)35+ } catch (e) {36+ console.warn(`${e}`)37+ }38+39+ if (content) {40+ const mimeType = getMimeType(path)41+ if (mimeType) {42+ c.header('Content-Type', mimeType)43+ }44+ // Return Response object45+ return c.body(content)46+ } else {47+ console.warn(`Static file: ${path} is not found`)48+ await next()49+ }50+ return51+ }52+}added:deno_dist/client/client.ts+122 added
1+import type { Hono } from '../hono.ts'2+import type { ValidationTargets } from '../types.ts'3+import type { UnionToIntersection } from '../utils/types.ts'4+import type { Callback, Client, RequestOption } from './types.ts'5+import { replaceUrlParam, mergePath, removeIndexString } from './utils.ts'6+7+const createProxy = (callback: Callback, path: string[]) => {8+ const proxy: unknown = new Proxy(() => {}, {9+ get(_obj, key) {10+ if (typeof key !== 'string') return undefined11+ return createProxy(callback, [...path, key])12+ },13+ apply(_1, _2, args) {14+ return callback({15+ path,16+ args,17+ })18+ },19+ })20+ return proxy21+}22+23+class ClientRequestImpl {24+ private url: string25+ private method: string26+ private queryParams: URLSearchParams | undefined = undefined27+ private pathParams: Record<string, string> = {}28+ private rBody: BodyInit | undefined29+ private cType: string | undefined = undefined30+31+ constructor(url: string, method: string) {32+ this.url = url33+ this.method = method34+ }35+ fetch = (36+ args?: ValidationTargets & {37+ param?: Record<string, string>38+ },39+ opt?: RequestOption40+ ) => {41+ if (args) {42+ if (args.query) {43+ for (const [k, v] of Object.entries(args.query)) {44+ this.queryParams ||= new URLSearchParams()45+ this.queryParams.set(k, v)46+ }47+ }48+49+ if (args.queries) {50+ for (const [k, v] of Object.entries(args.queries)) {51+ for (const v2 of v) {52+ this.queryParams ||= new URLSearchParams()53+ this.queryParams.append(k, v2)54+ }55+ }56+ }57+58+ if (args.form) {59+ const form = new FormData()60+ for (const [k, v] of Object.entries(args.form)) {61+ form.append(k, v)62+ }63+ this.rBody = form64+ }65+66+ if (args.json) {67+ this.rBody = JSON.stringify(args.json)68+ this.cType = 'application/json'69+ }70+71+ if (args.param) {72+ this.pathParams = args.param73+ }74+ }75+76+ let methodUpperCase = this.method.toUpperCase()77+ let setBody = !(methodUpperCase === 'GET' || methodUpperCase === 'HEAD')78+79+ const headerValues: Record<string, string> = opt?.headers ? opt.headers : {}80+ if (this.cType) headerValues['Content-Type'] = this.cType81+82+ const headers = new Headers(headerValues ?? undefined)83+ let url = this.url84+85+ url = removeIndexString(url)86+ url = replaceUrlParam(url, this.pathParams)87+88+ if (this.queryParams) {89+ url = url + '?' + this.queryParams.toString()90+ }91+ methodUpperCase = this.method.toUpperCase()92+ setBody = !(methodUpperCase === 'GET' || methodUpperCase === 'HEAD')93+94+ // Pass URL string to 1st arg for testing with MSW and node-fetch95+ return fetch(url, {96+ body: setBody ? this.rBody : undefined,97+ method: methodUpperCase,98+ headers: headers,99+ })100+ }101+}102+103+export const hc = <T extends Hono>(baseUrl: string) =>104+ createProxy(async (opts) => {105+ const parts = [...opts.path]106+107+ let method = ''108+ if (/^\$/.test(parts[parts.length - 1])) {109+ const last = parts.pop()110+ if (last) {111+ method = last.replace(/^\$/, '')112+ }113+ }114+115+ const path = parts.join('/')116+ const url = mergePath(baseUrl, path)117+ const req = new ClientRequestImpl(url, method)118+ if (method) {119+ return req.fetch(opts.args[0], opts.args[1])120+ }121+ return req122+ }, []) as UnionToIntersection<Client<T>>added:deno_dist/client/index.ts+2 added
1+export { hc } from './client.ts'2+export type { InferResponseType, InferRequestType, Fetch } from './types.ts'added:deno_dist/client/types.ts+67 added
1+import type { Hono } from '../hono.ts'2+import type { ValidationTargets, Env } from '../types.ts'3+4+type MethodName = `$${string}`5+6+type Endpoint = Record<MethodName, Data>7+8+type Data = {9+ input: Partial<ValidationTargets> & {10+ param?: Record<string, string>11+ }12+ output: {}13+}14+15+export type RequestOption = {16+ headers?: Record<string, string>17+}18+19+type ClientRequest<S extends Data> = {20+ [M in keyof S]: S[M] extends { input: infer R; output: infer O }21+ ? (args?: R, options?: RequestOption) => Promise<ClientResponse<O>>22+ : never23+}24+25+export interface ClientResponse<T> extends Response {26+ json(): Promise<T>27+}28+29+export type Fetch<T> = (30+ args?: InferRequestType<T>,31+ opt?: RequestOption32+) => Promise<ClientResponse<InferResponseType<T>>>33+34+export type InferResponseType<T> = T extends () => Promise<ClientResponse<infer O>> ? O : never35+export type InferRequestType<T> = T extends (args: infer R) => Promise<ClientResponse<unknown>>36+ ? NonNullable<R>37+ : never38+39+type PathToChain<40+ Path extends string,41+ E extends Endpoint,42+ Original extends string = ''43+> = Path extends `/${infer P}`44+ ? PathToChain<P, E, Path>45+ : Path extends `${infer P}/${infer R}`46+ ? { [K in P]: PathToChain<R, E, Original> }47+ : {48+ [K in Path extends '' ? 'index' : Path]: ClientRequest<49+ E extends Record<string, unknown> ? E[Original] : never50+ >51+ }52+53+export type Client<T> = T extends Hono<Env, infer S>54+ ? S extends Record<infer K, Endpoint>55+ ? K extends string56+ ? PathToChain<K, S>57+ : never58+ : never59+ : never60+61+export type Callback = (opts: CallbackOptions) => unknown62+63+interface CallbackOptions {64+ path: string[]65+ // eslint-disable-next-line @typescript-eslint/no-explicit-any66+ args: any[]67+}added:deno_dist/client/utils.ts+25 added
1+import { getPathFromURL } from '../utils/url.ts'2+3+export const mergePath = (base: string, path: string) => {4+ base = base.replace(/\/+$/, '')5+ base = base + '/'6+ path = path.replace(/^\/+/, '')7+ return base + path8+}9+10+export const replaceUrlParam = (urlString: string, params: Record<string, string>) => {11+ for (const [k, v] of Object.entries(params)) {12+ const reg = new RegExp('/:' + k)13+ urlString = urlString.replace(reg, `/${v}`)14+ }15+ return urlString16+}17+18+export const removeIndexString = (urlSting: string) => {19+ // eslint-disable-next-line @typescript-eslint/no-unused-vars20+ const path = getPathFromURL(urlSting)21+ if (path === '/index') {22+ return urlSting.replace(/index$/, '')23+ }24+ return urlSting25+}deleted:deno_dist/deno/serve-static.ts-52 removed
1-import type { Context } from '../context.ts'2-import type { Next } from '../types.ts'3-import { getFilePath } from '../utils/filepath.ts'4-import { getMimeType } from '../utils/mime.ts'5-6-export type ServeStaticOptions = {7- root?: string8- path?: string9-}10-11-const DEFAULT_DOCUMENT = 'index.html'12-13-export const serveStatic = (options: ServeStaticOptions = { root: '' }) => {14- return async (c: Context, next: Next) => {15- // Do nothing if Response is already set16- if (c.finalized) {17- await next()18- return19- }20-21- const url = new URL(c.req.url)22-23- let path = getFilePath({24- filename: options.path ?? decodeURI(url.pathname),25- root: options.root,26- defaultDocument: DEFAULT_DOCUMENT,27- })28-29- path = `./${path}`30-31- let content32-33- try {34- content = await Deno.readFile(path)35- } catch (e) {36- console.warn(`${e}`)37- }38-39- if (content) {40- const mimeType = getMimeType(path)41- if (mimeType) {42- c.header('Content-Type', mimeType)43- }44- // Return Response object45- return c.body(content)46- } else {47- console.warn(`Static file: ${path} is not found`)48- await next()49- }50- return51- }52-}modified:deno_dist/middleware/basic-auth/index.ts+5 added-2 removed
1+import { HTTPException } from '../../http-exception.ts'2+import type { HonoRequest } from '../../request.ts'3 import type { MiddlewareHandler } from '../../types.ts'4 import { timingSafeEqual } from '../../utils/buffer.ts'5 import { decodeBase64 } from '../../utils/encode.ts'6 7 const CREDENTIALS_REGEXP = /^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/8 const USER_PASS_REGEXP = /^([^:]*):(.*)$/9 8-const auth = (req: Request) => {10+const auth = (req: HonoRequest) => {11 const match = CREDENTIALS_REGEXP.exec(req.headers.get('Authorization') || '')12 if (!match) {13 return undefined14 }39 unmodified lines54 return55 }56 }57 }56- return new Response('Unauthorized', {58+ const res = new Response('Unauthorized', {59 status: 401,60 headers: {61 'WWW-Authenticate': 'Basic realm="' + options.realm?.replace(/"/g, '\\"') + '"',62 },63 })64+ throw new HTTPException(401, { res })65 }66 }modified:deno_dist/middleware/bearer-auth/index.ts+7 added-3 removed
1+import { HTTPException } from '../../http-exception.ts'2 import type { MiddlewareHandler } from '../../types.ts'3 import { timingSafeEqual } from '../../utils/buffer.ts'4 5 const TOKEN_STRINGS = '[A-Za-z0-9._~+/-]+=*'21 unmodified lines27 const headerToken = c.req.headers.get('Authorization')28 29 if (!headerToken) {30 // No Authorization header30- return new Response('Unauthorized', {31+ const res = new Response('Unauthorized', {32 status: 401,33 headers: {34 'WWW-Authenticate': `${options.prefix} realm="` + realm + '"',35 },36 })37+ throw new HTTPException(401, { res })38 } else {39 const regexp = new RegExp('^' + options.prefix + ' +(' + TOKEN_STRINGS + ') *$')40 const match = regexp.exec(headerToken)41 if (!match) {42 // Invalid Request41- return new Response('Bad Request', {43+ const res = new Response('Bad Request', {44 status: 400,45 headers: {46 'WWW-Authenticate': `${options.prefix} error="invalid_request"`,47 },48 })49+ throw new HTTPException(400, { res })50 } else {51 const equal = await timingSafeEqual(options.token, match[1], options.hashFunction)52 if (!equal) {53 // Invalid Token51- return new Response('Unauthorized', {54+ const res = new Response('Unauthorized', {55 status: 401,56 headers: {57 'WWW-Authenticate': `${options.prefix} error="invalid_token"`,58 },59 })60+ throw new HTTPException(401, { res })61 }62 }63 }64 await next()2 unmodified linesmodified:deno_dist/middleware/cache/index.ts+1 added-1 removed
12 unmodified lines13 if (options.cacheControl) response.headers.append('Cache-Control', options.cacheControl)14 }15 16 return async (c, next) => {17- const key = c.req17+ const key = c.req.raw18 const cache = await caches.open(options.cacheName)19 const response = await cache.match(key)20 if (!response) {21 await next()12 unmodified linesmodified:deno_dist/middleware/jsx/index.ts+8 added-4 removed
1 import { escapeToBuffer } from '../../utils/html.ts'2 import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../../utils/html.ts'3 4 // eslint-disable-next-line @typescript-eslint/no-explicit-any5-type Props = Record<string, any>;5+type Props = Record<string, any>6 7 declare global {8 // eslint-disable-next-line @typescript-eslint/no-namespace9- namespace jsx.JSX {9+ namespace JSX {10+ type Element = HtmlEscapedString11 interface IntrinsicElements {11- [tagName: string]: Props,12+ [tagName: string]: Props13 }14 }15 }16 50 unmodified lines67 } else if (typeof child === 'boolean' || child === null || child === undefined) {68 continue69 } else if (child instanceof JSXNode) {70 child.toStringToBuffer(buffer)70- } else if (typeof child === 'number' || (child as unknown as { isEscaped: boolean }).isEscaped) {71+ } else if (72+ typeof child === 'number' ||73+ (child as unknown as { isEscaped: boolean }).isEscaped74+ ) {75 buffer[0] += child76 } else {77 // `child` type is `Child[]`, so stringify recursively78 childrenToStringToBuffer(child, buffer)151 unmodified linesmodified:deno_dist/middleware/jwt/index.ts+7 added-3 removed
1+import { HTTPException } from '../../http-exception.ts'2 import type { MiddlewareHandler } from '../../types.ts'3 import { Jwt } from '../../utils/jwt/index.ts'4 import type { AlgorithmTypes } from '../../utils/jwt/types.ts'5 15 unmodified lines21 let token22 if (credentials) {23 const parts = credentials.split(/\s+/)24 if (parts.length !== 2) {24- return new Response('Unauthorized', {25+ const res = new Response('Unauthorized', {26 status: 401,27 headers: {28 'WWW-Authenticate': `Bearer realm="${ctx.req.url}",error="invalid_request",error_description="invalid credentials structure"`,29 },30 })31+ throw new HTTPException(401, { res })32 } else {33 token = parts[1]34 }35 } else if (options.cookie) {36 token = ctx.req.cookie(options.cookie)37 }38 39 if (!token) {38- return new Response('Unauthorized', {40+ const res = new Response('Unauthorized', {41 status: 401,42 headers: {43 'WWW-Authenticate': `Bearer realm="${ctx.req.url}",error="invalid_request",error_description="no authorization included in request"`,44 },45 })46+ throw new HTTPException(401, { res })47 }48 49 let authorized = false50 let msg = ''2 unmodified lines53 } catch (e) {54 msg = `${e}`55 }56 if (!authorized) {54- return new Response('Unauthorized', {57+ const res = new Response('Unauthorized', {58 status: 401,59 statusText: msg,60 headers: {61 'WWW-Authenticate': `Bearer realm="${ctx.req.url}",error="invalid_token",error_description="token verification failure"`,62 },63 })64+ throw new HTTPException(401, { res })65 }66 67 await next()68 }1 unmodified linemodified:deno_dist/middleware/logger/index.ts+1 added
54 unmodified lines55 56 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)61 62 log(fn, LogPrefix.Incoming, method, path)63 7 unmodified linesdeleted:deno_dist/middleware/serve-static/index.ts-1 removed
1-export { serveStatic } from './serve-static.ts'deleted:deno_dist/middleware/validator/index.ts-2 removed
1-import { validatorMiddleware } from './middleware.ts'2-export { validatorMiddleware as validator }deleted:deno_dist/middleware/validator/middleware.ts-162 removed
1-import type { Context } from '../../context.ts'2-import type { Environment, MiddlewareHandler } from '../../types.ts'3-import { getStatusText } from '../../utils/http-status.ts'4-import { mergeObjects } from '../../utils/object.ts'5-import type { Schema } from '../../validator/schema.ts'6-import type { ValidateResult } from '../../validator/validator.ts'7-import { Validator, VBase, VObjectBase } from '../../validator/validator.ts'8-9-type ResultSet = {10- hasError: boolean11- messages: string[]12- results: ValidateResult[]13-}14-15-type Done<P extends string, E extends Partial<Environment> = Environment> = (16- resultSet: ResultSet,17- c: Context<P, E>18-) => Response | void19-20-type ValidationFunction<21- P extends string,22- E extends Partial<Environment> = Environment,23- S = unknown24-> = (v: Validator, c: Context<P, E>) => S25-26-export const validatorMiddleware = <27- P extends string,28- E extends Partial<Environment> = Environment,29- S = unknown30->(31- validationFunction: ValidationFunction<P, E, S>,32- options?: { done?: Done<P, E> }33-) => {34- console.warn(`Current Validator Middleware will be changed with "breaking changes" at the ext major release "v3".35- See the migration guide: https://github.com/honojs/hono/blob/main/docs/MIGRATION.md`)36-37- const v = new Validator()38- const handler: MiddlewareHandler<string, E, S> = async (c, next) => {39- const resultSet: ResultSet = {40- hasError: false,41- messages: [],42- results: [],43- }44-45- // eslint-disable-next-line @typescript-eslint/ban-ts-comment46- // @ts-ignore47- const schema = validationFunction(v, c)48- const validatorList = getValidatorList(schema)49- // eslint-disable-next-line @typescript-eslint/no-explicit-any50- let data: any = {}51-52- for (const [keys, validator] of validatorList) {53- let results: ValidateResult[]54- try {55- results = await validator.validate(c.req)56- } catch (e) {57- // Invalid JSON request58- if (e instanceof Error) {59- const result = getErrorResult(e)60- resultSet.hasError = true61- resultSet.messages = [result.message || '']62- resultSet.results = [result]63- break64- } else {65- return c.text(getStatusText(400), 400)66- }67- }68-69- let isValid = true70- const value = results[0].value71- const jsonData = results[0].jsonData72-73- for (const result of results) {74- if (!result.isValid) {75- isValid = false76- resultSet.hasError = true77- if (result.ruleType === 'value' && result.message !== undefined) {78- resultSet.messages.push(result.message)79- }80- }81- resultSet.results.push(result)82- }83-84- // If it's invalid but it has no "value" messages, have to set the "type" messages.85- // This approach is verbose, but if do not so, the response body will be empty.86- if (!isValid && resultSet.messages.length === 0) {87- resultSet.results.map((r) => {88- if (!r.isValid && r.ruleType === 'type' && r.message) {89- resultSet.messages.push(r.message)90- }91- })92- }93-94- // Set data on request object95- if (isValid) {96- // Set data on request object97- if (jsonData) {98- const dst = data99- data = mergeObjects(dst, jsonData)100- } else {101- let tmp = data102- for (let i = 0; i < keys.length - 1; i++) {103- tmp = tmp[keys[i]] ||= {}104- }105- tmp[keys[keys.length - 1]] = value106- }107- }108- }109-110- if (!resultSet.hasError) {111- c.req.valid(data)112- }113-114- if (options && options.done) {115- // eslint-disable-next-line @typescript-eslint/ban-ts-comment116- // @ts-ignore117- const res = options.done(resultSet, c)118- if (res) {119- return res120- }121- }122-123- if (resultSet.hasError) {124- return c.text(resultSet.messages.join('\n'), 400)125- }126- await next()127- }128- return handler129-}130-131-function getValidatorList<T>(schema: T) {132- const map: [string[], VBase][] = []133- for (const [key, value] of Object.entries(schema as unknown as Schema)) {134- if (value instanceof VObjectBase) {135- const validators = value.getValidators()136- for (const validator of validators) {137- map.push([value.keys, validator])138- }139- } else if (value instanceof VBase) {140- map.push([[key], value])141- } else {142- const children = getValidatorList(value as Schema)143- for (const [keys, validator] of children) {144- map.push([[key, ...keys], validator])145- }146- }147- }148- return map149-}150-151-const getErrorResult = (e: Error) => {152- const result: ValidateResult = {153- isValid: false,154- message: e.message,155- target: 'unknown',156- key: null,157- value: null,158- ruleName: e.message,159- ruleType: 'value',160- }161- return result162-}modified:deno_dist/router/reg-exp-router/node.ts+18 added-3 removed
43 unmodified lines44 index?: number45 varIndex?: number46 children: Record<string, Node> = {}47 48- insert(tokens: readonly string[], index: number, paramMap: ParamMap, context: Context): void {48+ insert(49+ tokens: readonly string[],50+ index: number,51+ paramMap: ParamMap,52+ context: Context,53+ pathErrorCheckOnly: boolean54+ ): void {55 if (tokens.length === 0) {56 if (this.index !== undefined) {57 throw PATH_ERROR58 }59+ if (pathErrorCheckOnly) {60+ return61+ }62 63 this.index = index64 return65 }21 unmodified lines87 )88 ) {89 throw PATH_ERROR90 }91+ if (pathErrorCheckOnly) {92+ return93+ }94 node = this.children[regexpStr] = new Node()95 if (name !== '') {96 node.varIndex = context.varIndex++97 }98 }87- if (name !== '') {99+ if (!pathErrorCheckOnly && name !== '') {100 if (paramMap.some((p) => p[0] === name)) {101 throw new Error('Duplicate param name')102 }103 paramMap.push([name, node.varIndex as number])8 unmodified lines112 )113 ) {114 throw PATH_ERROR115 }116+ if (pathErrorCheckOnly) {117+ return118+ }119 node = this.children[token] = new Node()120 }121 }122 108- node.insert(restTokens, index, paramMap, context)123+ node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly)124 }125 126 buildRegExpStr(): string {127 const childKeys = Object.keys(this.children).sort(compareKey)20 unmodified linesmodified:deno_dist/router/reg-exp-router/router.ts+33 added-9 removed
6 unmodified lines7 import { Trie } from './trie.ts'8 9 const methodNames = [METHOD_NAME_ALL, ...METHODS].map((method) => method.toUpperCase())10 11-type HandlerData<T> = [T[], ParamMap | null]12-type Matcher<T> = [RegExp, HandlerData<T>[]]11+type HandlerData<T> = [T[], ParamMap] | [Result<T>, null]12+type StaticMap<T> = Record<string, Result<T>>13+type Matcher<T> = [RegExp, HandlerData<T>[], StaticMap<T>]14 15 const emptyParam = {}16 // eslint-disable-next-line @typescript-eslint/no-explicit-any16-const nullMatcher: Matcher<any> = [/^$/, []]17+const nullMatcher: Matcher<any> = [/^$/, [], {}]18 19 let wildcardRegExpCache: Record<string, RegExp> = {}20 function buildWildcardRegExp(path: string): RegExp {21 return (wildcardRegExpCache[path] ??= new RegExp(13 unmodified lines35 }36 37 routes = routes.sort(([a], [b]) => a.length - b.length)38 39+ const staticMap: StaticMap<T> = {}38- for (let i = 0, len = routes.length; i < len; i++) {40+ for (let i = 0, j = -1, len = routes.length; i < len; i++) {41+ const path = routes[i][0]42+ let pathErrorCheckOnly = false43+ if (!/\*|\/:/.test(path)) {44+ pathErrorCheckOnly = true45+ staticMap[routes[i][0]] = { handlers: routes[i][1], params: emptyParam }46+ } else {47+ j++48+ }49+50 let paramMap51 try {41- paramMap = trie.insert(routes[i][0], i)52+ paramMap = trie.insert(path, j, pathErrorCheckOnly)53 } catch (e) {43- throw e === PATH_ERROR ? new UnsupportedPathError(routes[i][0]) : e54+ throw e === PATH_ERROR ? new UnsupportedPathError(path) : e55 }56 46- handlers[i] = [routes[i][1], paramMap.length !== 0 ? paramMap : null]57+ if (pathErrorCheckOnly) {58+ continue59+ }60+61+ handlers[j] =62+ paramMap.length === 063+ ? [{ handlers: routes[i][1], params: emptyParam }, null]64+ : [routes[i][1], paramMap]65 }66 67 const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp()68 for (let i = 0, len = handlers.length; i < len; i++) {10 unmodified lines79 for (const i in indexReplacementMap) {80 handlerMap[i] = handlers[indexReplacementMap[i]]81 }82 65- return [regexp, handlerMap] as Matcher<T>83+ return [regexp, handlerMap, staticMap] as Matcher<T>84 }85 86 function findMiddleware<T>(87 middleware: Record<string, T[]> | undefined,97 unmodified lines185 const matchers = this.buildAllMatchers()186 187 this.match = (method, path) => {188 const matcher = matchers[method]189+190+ const staticMatch = matcher[2][path]191+ if (staticMatch) {192+ return staticMatch193+ }194+195 const match = path.match(matcher[0])196 if (!match) {197 return null198 }199 200 const index = match.indexOf('', 1)201 const [handlers, paramMap] = matcher[1][index]202 if (!paramMap) {179- return { handlers, params: emptyParam }203+ return handlers204 }205 206 const params: Record<string, string> = {}207 for (let i = 0, len = paramMap.length; i < len; i++) {51 unmodified linesmodified:deno_dist/router/reg-exp-router/trie.ts+31 added-5 removed
6 unmodified lines7 export class Trie {8 context: Context = { varIndex: 0 }9 root: Node = new Node()10 11- insert(path: string, index: number): ParamMap {11+ insert(path: string, index: number, pathErrorCheckOnly: boolean): ParamMap {12 const paramMap: ParamMap = []13 14+ const groups: [string, string][] = [] // [mark, original string]15+ for (let i = 0; ; ) {16+ let replaced = false17+ path = path.replace(/\{[^}]+\}/g, (m) => {18+ const mark = `@\\${i}`19+ groups[i] = [mark, m]20+ i++21+ replaced = true22+ return mark23+ })24+ if (!replaced) {25+ break26+ }27+ }28+29 /**30 * - pattern (:label, :label{0-9]+}, ...)31 * - /* wildcard32 * - character33 */19- const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g)20- // eslint-disable-next-line @typescript-eslint/ban-ts-comment21- // @ts-ignore22- this.root.insert(tokens, index, paramMap, this.context)34+ const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || []35+ for (let i = groups.length - 1; i >= 0; i--) {36+ const [mark] = groups[i]37+ for (let j = tokens.length - 1; j >= 0; j--) {38+ if (tokens[j].indexOf(mark) !== -1) {39+ tokens[j] = tokens[j].replace(mark, groups[i][1])40+ break41+ }42+ }43+ }44 45+ this.root.insert(tokens, index, paramMap, this.context, pathErrorCheckOnly)46+47 return paramMap48 }49 50 buildRegExp(): [RegExp, ReplacementMap, ReplacementMap] {51 let regexp = this.root.buildRegExpStr()52+ if (regexp === '') {53+ return [/^$/, [], []] // never match54+ }55 56 let captureIndex = 057 const indexReplacementMap: ReplacementMap = []58 const paramReplacementMap: ReplacementMap = []17 unmodified linesdeleted:deno_dist/router/static-router/index.ts-1 removed
1-export { StaticRouter } from './router.ts'deleted:deno_dist/router/static-router/router.ts-96 removed
1-/* eslint-disable @typescript-eslint/ban-ts-comment */2-import type { Router, Result } from '../../router.ts'3-import { METHOD_NAME_ALL, METHODS, UnsupportedPathError } from '../../router.ts'4-5-export class StaticRouter<T> implements Router<T> {6- middleware: Record<string, Result<T>>7- routes: Record<string, Record<string, Result<T>>>8-9- constructor() {10- this.middleware = {}11-12- this.routes = {} as StaticRouter<T>['routes']13- ;[METHOD_NAME_ALL, ...METHODS].forEach((method) => {14- this.routes[method.toUpperCase()] = {}15- })16- }17-18- private newRoute(): Record<string, Result<T>> {19- const route: Record<string, Result<T>> = {}20- const routeAll = this.routes[METHOD_NAME_ALL]21- Object.keys(routeAll).forEach((path) => {22- route[path] = {23- handlers: [...routeAll[path].handlers],24- params: {},25- }26- })27-28- return route29- }30-31- add(method: string, path: string, handler: T) {32- const { middleware, routes } = this33-34- routes[method] ||= this.newRoute()35-36- if (path === '/*') {37- path = '*'38- }39-40- if (path === '*') {41- if (method === METHOD_NAME_ALL) {42- middleware[METHOD_NAME_ALL] ||= { handlers: [], params: {} }43- Object.keys(middleware).forEach((m) => {44- middleware[m].handlers.push(handler)45- })46- Object.keys(routes).forEach((m) => {47- Object.values(routes[m]).forEach((matchRes) => matchRes.handlers.push(handler))48- })49- } else {50- middleware[method] ||= {51- handlers: [...(middleware[METHOD_NAME_ALL]?.handlers || [])],52- params: {},53- }54- middleware[method].handlers.push(handler)55- if (routes[method]) {56- Object.values(routes[method]).forEach((matchRes) => matchRes.handlers.push(handler))57- }58- }59- return60- }61-62- if (/\*|\/:/.test(path)) {63- throw new UnsupportedPathError(path)64- }65-66- routes[method][path] ||= {67- handlers: [68- ...(routes[METHOD_NAME_ALL][path]?.handlers ||69- middleware[method]?.handlers ||70- middleware[METHOD_NAME_ALL]?.handlers ||71- []),72- ],73- params: {},74- }75- if (method === METHOD_NAME_ALL) {76- Object.keys(routes).forEach((m) => {77- routes[m][path]?.handlers?.push(handler)78- })79- } else {80- routes[method][path].handlers.push(handler)81- }82- }83-84- match(method: string, path: string): Result<T> | null {85- const { routes, middleware } = this86-87- this.match = (method, path) =>88- routes[method][path] ||89- routes[METHOD_NAME_ALL][path] ||90- middleware[method] ||91- middleware[METHOD_NAME_ALL] ||92- null93-94- return this.match(method, path)95- }96-}modified:deno_dist/router/trie-router/node.ts+11 added-2 removed
1 import type { Result } from '../../router.ts'2 import { METHOD_NAME_ALL } from '../../router.ts'3 import type { Pattern } from '../../utils/url.ts'4-import { splitPath, getPattern } from '../../utils/url.ts'4+import { splitPath, splitRoutingPath, getPattern } from '../../utils/url.ts'5 6 type HandlerSet<T> = {7 handler: T8 score: number44 unmodified lines53 this.order = ++this.order54 55 // eslint-disable-next-line @typescript-eslint/no-this-alias56 let curNode: Node<T> = this57- const parts = splitPath(path)57+ const parts = splitRoutingPath(path)58 59 const parentPatterns: Pattern[] = []60 const errorMessage = (name: string): string => {61 return `Duplicate param name, use another name instead of '${name}' - ${method} ${path} <--- '${name}'`109 unmodified lines171 172 // Named match173 // `/posts/:id` => match /posts/123174 const [key, name, matcher] = pattern175+176+ // `/js/:filename{[a-z]+.js}` => match /js/chunk/123.js177+ const restPathString = parts.slice(i).join('/')178+ if (matcher instanceof RegExp && matcher.test(restPathString)) {179+ handlerSets.push(...this.getHandlerSets(node.children[key], method))180+ params[name] = restPathString181+ continue182+ }183+184 if (matcher === true || (matcher instanceof RegExp && matcher.test(part))) {185 if (typeof key === 'string') {186 if (isLast === true) {187 handlerSets.push(...this.getHandlerSets(node.children[key], method))40 unmodified linesmodified:deno_dist/utils/body.ts+5 added-7 removed
1-export type BodyData = Record<string, string | number | boolean | File>1+export type BodyData = Record<string, string | File>2 3-export async function parseBody<BodyType extends BodyData>(4- r: Request | Response5-): Promise<BodyType> {6- let body: Record<string, string | File> = {}3+export async function parseBody(r: Request | Response) {4+ let body: BodyData = {}5 const contentType = r.headers.get('Content-Type')6 if (7 contentType &&8 (contentType.startsWith('multipart/form-data') ||9 contentType === 'application/x-www-form-urlencoded')10 ) {13- const form: Record<string, string | File> = {}11+ const form: BodyData = {}12 ;(await r.formData()).forEach((value, key) => {13 form[key] = value14 })15 body = form16 }19- return body as BodyType17+ return body18 }modified:deno_dist/utils/buffer.ts+6 added
27 unmodified lines28 ) => {29 if (!hashFunction) {30 hashFunction = sha25631 }32+33 const sa = await hashFunction(a)34 const sb = await hashFunction(b)35+36+ if (!sa || !sb) {37+ return false38+ }39+40 return sa === sb && a === b41 }42 43 export const bufferToString = (buffer: ArrayBuffer): string => {6 unmodified linesmodified:deno_dist/utils/encode.ts+2 added-2 removed
10 unmodified lines11 12 try {13 return Buffer.from(str).toString('base64')14 } catch (e) {15- console.error('If you want to do "encodeBase64", polyfill "buffer" module.')15+ console.error('Error: If you want to do "encodeBase64", polyfill "buffer" module.')16 throw e17 }18 }19 10 unmodified lines30 31 try {32 return Buffer.from(str, 'base64').toString()33 } catch (e) {34- console.error('If you want to do "decodeBase64", polyfill "buffer" module.')34+ console.error('Error: If you want to do "decodeBase64", polyfill "buffer" module.')35 throw e36 }37 }38 39 unmodified linesdeleted:deno_dist/utils/json.ts-95 removed
1-export type JSONPrimitive = string | boolean | number | null | undefined2-export type JSONArray = (JSONPrimitive | JSONObject | JSONArray)[]3-export type JSONObject = { [key: string]: JSONPrimitive | JSONArray | JSONObject }4-export type JSONValue = JSONObject | JSONArray | JSONPrimitive5-6-const JSONPathCopyInternal = (7- src: JSONObject,8- dst: JSONObject,9- parts: string[],10- results: JSONArray11-): JSONValue => {12- let srcVal: JSONObject = src13- let dstVal: JSONObject = dst14- const length = parts.length15- for (let i = 0; i < length && srcVal !== undefined && dstVal; i++) {16- const p = parts[i]17-18- if (typeof srcVal !== 'object') {19- return srcVal20- }21-22- if (srcVal === null) {23- return undefined24- }25-26- if (p === '*') {27- const restParts = parts.slice(i + 1)28- const restLength = srcVal.length as number29-30- if (restLength === undefined) {31- parts = Object.keys(srcVal)32- for (const p of parts) {33- const srcVal2 = srcVal34- const dst2: JSONObject = {}35- JSONPathCopyInternal(srcVal2, dst2, [p], results)36- dstVal[p] = dst2[p]37- }38- } else {39- const res = []40- for (let i2 = 0; i2 < restLength; i2++) {41- if (typeof srcVal[i2] !== 'object' || srcVal[i2] === undefined) {42- res.push(srcVal[i2])43- } else {44- const srcVal2 = srcVal[i2] as JSONObject45- const dst2: JSONObject = {}46- const res2 = JSONPathCopyInternal(srcVal2, dst2, restParts, results)47- if (res2 === undefined) results.push(undefined)48- dstVal[i2] = dst249- }50- }51- if (res.length) {52- Object.assign(dstVal, srcVal)53- results.push(...res)54- }55- }56- return results57- }58-59- if (typeof srcVal[p] === 'object') {60- // eslint-disable-next-line @typescript-eslint/ban-ts-comment61- // @ts-ignore62- dstVal[p] ||= new srcVal[p].constructor()63- } else if (typeof srcVal[p] !== 'undefined') {64- dstVal[p] = srcVal[p]65- } else {66- return undefined67- }68-69- srcVal = srcVal[p] as JSONObject70- dstVal = dstVal[p] as JSONObject71- }72-73- if (typeof srcVal === 'object' && dstVal) {74- Object.assign(dstVal, srcVal)75- }76-77- results.push(srcVal)78- return results79-}80-81-export const JSONPathCopy = (src: JSONObject, dst: JSONObject, path: string) => {82- const results: JSONArray = []83- const parts = path.replace(/\.?\[(.*?)\]/g, '.$1').split(/\./)84- try {85- JSONPathCopyInternal(src, dst, parts, results)86- if (results.length === 0) {87- return undefined88- } else if (results.length === 1 && !parts.includes('*')) {89- return results[0]90- }91- return results92- } catch (e) {93- return undefined94- }95-}modified:deno_dist/utils/mime.ts+2 added-2 removed
85 unmodified lines86 '3gp': 'video/3gpp',87 '3g2': 'video/3gpp2',88 '7z': 'application/x-7z-compressed',89 gltf: 'model/gltf+json',90- glb: 'model/gltf-binary'91-}90+ glb: 'model/gltf-binary',91+}deleted:deno_dist/utils/object.ts-31 removed
1-/* eslint-disable @typescript-eslint/no-explicit-any */2-export const isObject = (val: any): boolean => val && typeof val === 'object' && !Array.isArray(val)3-4-export const mergeObjects = (target: any, source: any) => {5- const merged = Object.assign({}, target)6- if (isObject(target) && isObject(source)) {7- for (const key of Object.keys(source)) {8- if (isObject(source[key])) {9- if (target[key] === undefined) Object.assign(merged, { [key]: source[key] })10- else merged[key] = mergeObjects(target[key], source[key])11- } else if (Array.isArray(source[key]) && Array.isArray(target[key])) {12- const srcArr = source[key]13- const tgtArr = target[key]14- const outArr = [] as any[]15- for (let i = 0; i < srcArr.length; i += 1) {16- // If corresponding index for both arrays is an object, then merge them17- // Otherwise just copy src arr index into out arr index18- if (isObject(srcArr[i]) && isObject(tgtArr[i])) {19- outArr[i] = mergeObjects(tgtArr[i], srcArr[i])20- } else {21- outArr[i] = srcArr[i]22- }23- }24- Object.assign(merged, { [key]: outArr })25- } else {26- Object.assign(merged, { [key]: source[key] })27- }28- }29- }30- return merged31-}modified:deno_dist/utils/url.ts+104 added-4 removed
1 export type Pattern = readonly [string, string, RegExp | true] | '*'2 3 export const splitPath = (path: string): string[] => {4- const paths = path.split(/\//) // faster than path.split('/')4+ const paths = path.split('/')5 if (paths[0] === '') {6 paths.shift()7 }8 return paths9 }10 11+export const splitRoutingPath = (path: string): string[] => {12+ const groups: [string, string][] = [] // [mark, original string]13+ for (let i = 0; ; ) {14+ let replaced = false15+ path = path.replace(/\{[^}]+\}/g, (m) => {16+ const mark = `@\\${i}`17+ groups[i] = [mark, m]18+ i++19+ replaced = true20+ return mark21+ })22+ if (!replaced) {23+ break24+ }25+ }26+27+ const paths = path.split('/')28+ if (paths[0] === '') {29+ paths.shift()30+ }31+ for (let i = groups.length - 1; i >= 0; i--) {32+ const [mark] = groups[i]33+ for (let j = paths.length - 1; j >= 0; j--) {34+ if (paths[j].indexOf(mark) !== -1) {35+ paths[j] = paths[j].replace(mark, groups[i][1])36+ break37+ }38+ }39+ }40+41+ return paths42+}43+44 const patternCache: { [key: string]: Pattern } = {}45 export const getPattern = (label: string): Pattern | null => {46 // * => wildcard47 // :id{[0-9]+} => ([0-9]+)20 unmodified lines68 return null69 }70 71 export const getPathFromURL = (url: string, strict: boolean = true): string => {39- const queryIndex = url.indexOf('?')72+ const queryIndex = url.indexOf('?', 8)73 const result = url.substring(url.indexOf('/', 8), queryIndex === -1 ? url.length : queryIndex)74 75 // if strict routing is false => `/hello/hey/` and `/hello/hey` are treated the same76 // default is true4 unmodified lines81 return result82 }83 84 export const getQueryStringFromURL = (url: string): string => {52- const queryIndex = url.indexOf('?')53- const result = queryIndex !== -1 ? url.substring(queryIndex) : ''85+ const queryIndex = url.indexOf('?', 8)86+ const result = queryIndex !== -1 ? url.slice(queryIndex + 1) : ''87 return result88 }89 90 export const mergePath = (...paths: string[]): string => {40 unmodified lines131 const base = match[1]132 const optional = base + match[2]133 return [base, optional]134 }135+136+const removeFragment = (queryString: string): string => {137+ const fragIndex = queryString.indexOf('#')138+ if (fragIndex !== -1) {139+ queryString = queryString.slice(0, fragIndex)140+ }141+ return queryString142+}143+144+// Optimized145+export const getQueryParam = (146+ queryString: string,147+ key?: string148+): string | null | Record<string, string> => {149+ queryString = removeFragment(queryString)150+151+ const results: Record<string, string> = {}152+153+ // eslint-disable-next-line no-constant-condition154+ while (true) {155+ const andIndex = queryString.indexOf('&')156+ let strings = ''157+ if (andIndex === -1) {158+ strings = queryString159+ } else {160+ strings = queryString.substring(0, andIndex)161+ }162+163+ const eqIndex = strings.indexOf('=')164+ if (eqIndex !== -1) {165+ const v = strings.substring(eqIndex + 1)166+ const k = strings.substring(0, eqIndex)167+ if (key === k) {168+ return /\%/.test(v) ? decodeURI(v) : v169+ } else {170+ results[k] ||= v171+ }172+ } else if (strings === key) {173+ return ''174+ }175+176+ if (andIndex === -1) break177+ queryString = queryString.substring(andIndex + 1, queryString.length)178+ }179+180+ if (key) return null181+ return results182+}183+184+export const getQueryParams = (185+ queryString: string,186+ key?: string187+): string[] | null | Record<string, string[]> => {188+ queryString = removeFragment(queryString)189+ const results: Record<string, string[]> = {}190+191+ for (const strings of queryString.split('&')) {192+ let [k, v] = strings.split('=')193+ if (v === undefined) v = ''194+ results[k] ||= []195+ results[k].push(v.indexOf('%') !== -1 ? decodeURI(v) : v)196+ }197+198+ if (key) return results[key] ? results[key] : null199+200+ return results201+}added:deno_dist/validator/index.ts+1 added
1+export { validator } from './validator.ts'deleted:deno_dist/validator/rule.ts-90 removed
1-// Some validation rules is are based on Validator.js2-// Validator.js3-// License (MIT)4-// Copyright (c) 2018 Chris O'Hara <cohara87@gmail.com>5-// https://github.com/validatorjs/validator.js6-7-export const rule = {8- // string9- isEmpty(10- value: string,11- options: {12- ignore_whitespace: boolean13- } = { ignore_whitespace: false }14- ): boolean {15- if (value === undefined) return false16- return (options.ignore_whitespace ? value.trim().length : value.length) === 017- },18-19- isLength: (20- value: string,21- options: Partial<{ min: number; max: number }> | number,22- arg2?: number23- ) => {24- if (value === undefined) return false25- let min: number26- let max: number | undefined27- if (typeof options === 'object') {28- min = options.min || 029- max = options.max30- } else {31- // backwards compatibility: isLength(str, min [, max])32- min = options || 033- max = arg234- }35- const presentationSequences = value.match(/(\uFE0F|\uFE0E)/g) || []36- const surrogatePairs = value.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g) || []37- const len = value.length - presentationSequences.length - surrogatePairs.length38- return len >= min && (typeof max === 'undefined' || len <= max)39- },40-41- isAlpha: (value: string): boolean => {42- if (value === undefined) return false43- return /^[A-Z]+$/i.test(value)44- },45-46- isNumeric: (value: string): boolean => {47- if (value === undefined) return false48- return /^[0-9]+$/.test(value)49- },50-51- contains: (52- value: string,53- elem: string,54- options: Partial<{ ignoreCase: boolean; minOccurrences: number }> = {55- ignoreCase: false,56- minOccurrences: 1,57- }58- ): boolean => {59- if (value === undefined || elem === undefined) return false60- options.ignoreCase ||= false61- options.minOccurrences ||= 162- if (options.ignoreCase) {63- return value.toLowerCase().split(elem.toLowerCase()).length > options.minOccurrences64- }65- return value.split(elem).length > options.minOccurrences66- },67-68- isIn: (value: string, options: string[]): boolean => {69- if (value === undefined) return false70- if (typeof options === 'object') {71- for (const elem of options) {72- if (elem === value) return true73- }74- }75- return false76- },77-78- match: (value: string, regExp: RegExp): boolean => {79- if (value === undefined || regExp === undefined) return false80- return regExp.test(value)81- },82-83- // number84- isGte: (value: number, min: number) => min <= value,85- isLte: (value: number, max: number) => value <= max,86-87- // boolean88- isTrue: (value: boolean) => value === true,89- isFalse: (value: boolean) => value === false,90-}deleted:deno_dist/validator/sanitizer.ts-3 removed
1-export const sanitizer = {2- trim: (value: string) => value.trim(),3-}deleted:deno_dist/validator/schema.ts-47 removed
1-import type {2- VString,3- VNumber,4- VBoolean,5- VObject,6- VArray,7- VNumberArray,8- VStringArray,9- VBooleanArray,10- VBase,11-} from './validator.ts'12-13-export type Schema = {14- [key: string]: VString | VNumber | VBoolean | Schema | VObject<Schema> | VArray<Schema>15-}16-17-type Primitive<T> = T extends VNumberArray18- ? number[]19- : T extends VNumber20- ? number21- : T extends VStringArray22- ? string[]23- : T extends VString24- ? string25- : T extends VBooleanArray26- ? boolean[]27- : T extends VBoolean28- ? boolean29- : T30-31-type P<T> = T extends VArray<infer R>32- ? P<R>[]33- : T extends VObject<infer R>34- ? P<R>35- : {36- [K in keyof T]: T[K] extends VBase37- ? Primitive<T[K]>38- : T[K] extends VArray<infer R>39- ? P<R>[]40- : T[K] extends VObject<infer R>41- ? P<R>42- : T[K] extends Schema43- ? P<T[K]>44- : never45- }46-47-export type SchemaToProp<T> = P<T>modified:deno_dist/validator/validator.ts+44 added-493 removed
1-import { JSONPathCopy } from './../utils/json.ts'2-import type { JSONObject, JSONPrimitive, JSONArray } from './../utils/json.ts'3-import { rule } from './rule.ts'4-import { sanitizer } from './sanitizer.ts'5-import type { Schema } from './schema.ts'1+import type { Context } from '../context.ts'2+import type { Env, ValidationTargets, MiddlewareHandler } from '../types.ts'3 7-type Target = 'query' | 'queries' | 'header' | 'body' | 'json'8-type Type = JSONPrimitive | JSONObject | JSONArray | File9-type RuleFunc = (value: Type) => boolean10-type Rule = {11- name: string12- func: RuleFunc13- customMessage?: string14- type: 'type' | 'value'15-}16-type Sanitizer = (value: Type) => Type4+type ValidationTargetKeysWithBody = 'form' | 'json'5+type ValidationTargetByMethod<M> = M extends 'get' | 'head' // GET and HEAD request must not have a body content.6+ ? Exclude<keyof ValidationTargets, ValidationTargetKeysWithBody>7+ : keyof ValidationTargets8 18-export type ValidateResult = {19- isValid: boolean20- message: string | undefined21- target: Target | 'unknown'22- key: string | null23- value: Type | null24- ruleName: string25- ruleType: 'type' | 'value'26- jsonData?: JSONObject27-}9+export const validator = <10+ T,11+ P extends string,12+ M extends string,13+ U extends ValidationTargetByMethod<M>,14+ V extends { [K in U]: T },15+ // eslint-disable-next-line @typescript-eslint/no-explicit-any16+ E extends Env = any17+>(18+ target: U,19+ validationFunc: (value: ValidationTargets[U], c: Context<E>) => T | Response | Promise<Response>20+): MiddlewareHandler<E, P, V> => {21+ return async (c, next) => {22+ let value = {}23 29-export abstract class VObjectBase<T extends Schema> {30- container: T31- keys: string[] = []32- protected _isOptional: boolean = false33- constructor(container: T, key: string) {34- this.container = container35- if (this instanceof VArray) {36- this.keys.push(key, '[*]')37- } else if (this instanceof VObject) {38- this.keys.push(key)39- }40- }41-42- isOptional() {43- this._isOptional = true44- return this45- }46-47- getValidators = (): VBase[] => {48- const validators: VBase[] = []49-50- const walk = (container: T, keys: string[], isOptional: boolean) => {51- for (const v of Object.values(container)) {52- if (v instanceof VArray || v instanceof VObject) {53- // eslint-disable-next-line @typescript-eslint/ban-ts-comment54- // @ts-ignore55- isOptional ||= v._isOptional56- walk(v.container as T, [...keys, ...v.keys], isOptional)57- } else if (v instanceof VBase) {58- if (isOptional) v.isOptional()59- v.baseKeys.push(...keys)60- validators.push(v)61- }62- }63- }64-65- walk(this.container, this.keys, this._isOptional)66-67- return validators68- }69-}70-71-export class VObject<T extends Schema> extends VObjectBase<T> {72- constructor(container: T, key: string) {73- super(container, key)74- }75-}76-77-export class VArray<T extends Schema> extends VObjectBase<T> {78- type: 'array' = 'array'79- constructor(container: T, key: string) {80- super(container, key)81- }82-}83-84-export class Validator {85- constructor(private inArray: boolean = false) {}86-87- query = (key: string): VString => new VString({ target: 'query', key: key })88- queries = (key: string): VStringArray => new VStringArray({ target: 'queries', key: key })89- header = (key: string): VString => new VString({ target: 'header', key: key })90- body = (key: string): VString => new VString({ target: 'body', key: key })91- json = (key: string) => {92- if (this.inArray) {93- return new VStringArray({ target: 'json', key: key })94- } else {95- return new VString({ target: 'json', key: key })96- }97- }98- array = <T extends Schema>(path: string, validatorFn: (v: Validator) => T): VArray<T> => {99- const validator = new Validator(true)100- const res = validatorFn(validator)101- const arr = new VArray(res, path)102- return arr103- }104- object = <T extends Schema>(path: string, validatorFn: (v: Validator) => T): VObject<T> => {105- const validator = new Validator(this.inArray)106- const res = validatorFn(validator)107- const obj = new VObject(res, path)108- return obj109- }110-}111-112-type VOptions = {113- target: Target114- key: string115- type?: 'string' | 'number' | 'boolean' | 'object'116- isArray?: boolean117-}118-119-export abstract class VBase {120- type: 'string' | 'number' | 'boolean' | 'object'121- target: Target122- baseKeys: string[] = []123- key: string124- rules: Rule[]125- sanitizers: Sanitizer[]126- isArray: boolean127- private _optional: boolean128- constructor(options: VOptions) {129- this.target = options.target130- this.key = options.key131- this.type = options.type || 'string'132- this.rules = [133- {134- name: this.getTypeRuleName(),135- type: 'type',136- func: this.validateType,137- },138- ]139- this.sanitizers = []140- this._optional = false141- this.isArray = options.isArray || false142- }143-144- private _nested = () => (this.baseKeys.length ? true : false)145-146- addRule(func: RuleFunc): this147- addRule(name: string, func: RuleFunc): this148- addRule(arg: string | RuleFunc, func?: RuleFunc) {149- if (typeof arg === 'string' && func) {150- this.rules.push({ name: arg, func, type: 'value' })151- } else if (arg instanceof Function) {152- this.rules.push({ name: arg.name, func: arg, type: 'value' })153- }154- return this155- }156-157- addSanitizer = (sanitizer: Sanitizer) => {158- this.sanitizers.push(sanitizer)159- return this160- }161-162- message = (text: string) => {163- const len = this.rules.length164- if (len >= 1) {165- this.rules[len - 1].customMessage = text166- }167- return this168- }169-170- isRequired = () => {171- return this.addRule('isRequired', (value: unknown) => {172- if (value !== undefined && value !== null && value !== '') return true173- return false174- })175- }176-177- isOptional = () => {178- this._optional = true179- return this.addRule('isOptional', () => true)180- }181-182- isEqual = (comparison: unknown) => {183- return this.addRule('isEqual', (value: unknown) => {184- return value === comparison185- })186- }187-188- asNumber = () => {189- return new VNumber({ ...this, type: 'number' })190- }191-192- asBoolean = () => {193- return new VBoolean({ ...this, type: 'boolean' })194- }195-196- get(value: string) {197- const len = this.rules.length198- if (len > 0) {199- this.rules[this.rules.length - 1].customMessage = value200- }201- return this202- }203-204- validate = async <R extends Request>(req: R): Promise<ValidateResult[]> => {205- let value: Type = undefined206- let jsonData: JSONObject | undefined = undefined207-208- if (this.target === 'query') {209- value = req.query(this.key)210- }211- if (this.target === 'queries') {212- value = req.queries(this.key)213- }214- if (this.target === 'header') {215- value = req.header(this.key)216- }217- if (this.target === 'body') {218- const body = await req.parseBody()219- value = body[this.key]220- }221- if (this.target === 'json') {222- if (this._nested()) {223- this.key = `${this.baseKeys.join('.')}.${this.key}`224- }225- let obj = {}226- try {227- obj = (await req.json()) as JSONObject228- } catch (e) {229- throw new Error('Malformed JSON in request body')230- }231- const dst = {}232- value = JSONPathCopy(obj, dst, this.key)233- if (this._nested()) jsonData = dst234- }235-236- value = this.sanitizeValue(value)237-238- const results: ValidateResult[] = []239-240- let typeRule = this.rules.shift()241-242- for (const rule of this.rules) {243- if (rule.type === 'type') {244- typeRule = rule245- } else if (rule.type === 'value') {246- const result = this.validateRule(rule, value)247- result.jsonData ||= jsonData248- results.push(result)249- }250- }251-252- if (typeRule) {253- const typeResult = this.validateRule(typeRule, value)254- typeResult.jsonData ||= jsonData255- results.unshift(typeResult)256- this.rules.unshift(typeRule)257- }258-259- return results260- }261-262- protected getTypeRuleName(): string {263- const prefix = 'should be'264- return this.isArray ? `${prefix} "${this.type}[]"` : `${prefix} "${this.type}"`265- }266-267- private sanitizeValue = (value: Type) =>268- this.sanitizers.reduce((acc, sanitizer) => sanitizer(acc), value)269-270- private validateRule(rule: Rule, value: Type): ValidateResult {271- let isValid: boolean = false272-273- if (this._nested() && this.target != 'json') {274- isValid = false275- } else if (rule.type === 'value') {276- isValid = this.validateValue(rule.func, value)277- } else if (rule.type === 'type') {278- isValid = this.validateType(value)279- }280-281- const message = isValid282- ? undefined283- : rule.customMessage || this.getMessage({ ruleName: rule.name, value })284- const result = {285- isValid: isValid,286- message: message,287- target: this.target,288- key: this.key,289- value,290- ruleName: rule.name,291- ruleType: rule.type,292- }293- return result294- }295-296- private validateType = (value: Type): boolean => {297- if (this.isArray) {298- if (!Array.isArray(value)) {299- return this._optional && typeof value === 'undefined'300- }301- for (const val of value) {302- if (typeof val === 'undefined' && this._nested()) {303- value.pop()304- }305- for (const val of value) {306- if (typeof val !== this.type) {307- // Value is of wrong type here308- // If it is not optional and not undefined, return false309- if (!this._optional || typeof val !== 'undefined') return false310- }311- }312- }313- } else {314- if (typeof value !== this.type) {315- if (this._optional && (typeof value === 'undefined' || Array.isArray(value))) {316- // Do nothing.317- // If it is optional it's OK to be `undefined` or Array318- } else {319- return false320- }321- }322- }323- return true324- }325-326- private validateValue = (func: (value: Type) => boolean, value: Type): boolean => {327- if (this._optional && typeof value === 'undefined') return true328-329- if (Array.isArray(value)) {330- if (value.length === 0 && !this._optional) return false331- for (const val of value) {332- if (!func(val)) {333- return false334- }335- }336- return true337- } else {338- if (!func(value)) {339- return false340- }341- return true342- }343- }344-345- private getMessage = (opts: { ruleName: string; value: Type }): string => {346- let keyText: string347- const valueText = Array.isArray(opts.value)348- ? `${opts.value349- .map((val) =>350- val === undefined ? 'undefined' : typeof val === 'string' ? `"${val}"` : val24+ switch (target) {25+ case 'json':26+ try {27+ value = await c.req.json()28+ } catch {29+ console.error('Error: Malformed JSON in request body')30+ return c.json(31+ {32+ success: false,33+ message: 'Malformed JSON in request body',34+ },35+ 40036 )352- .join(', ')}`353- : opts.value354- switch (this.target) {37+ }38+ break39+ case 'form':40+ value = await c.req.parseBody()41+ break42 case 'query':356- keyText = `the query parameter "${this.key}"`43+ value = c.req.query()44 break45 case 'queries':359- keyText = `the query parameters "${this.key}"`46+ value = c.req.queries()47 break361- case 'header':362- keyText = `the request header "${this.key}"`363- break364- case 'body':365- keyText = `the request body "${this.key}"`366- break367- case 'json':368- keyText = `the JSON body "${this.key}"`369- break48 }371- return `Invalid Value [${valueText}]: ${keyText} is invalid - ${opts.ruleName}`372- }373-}49 375-export class VString extends VBase {376- constructor(options: VOptions) {377- super(options)378- this.type = 'string'379- }50+ const res = validationFunc(value, c)51 381- asArray = () => {382- return new VStringArray(this)383- }384-385- isEmpty = (386- options: {387- ignore_whitespace: boolean388- } = { ignore_whitespace: false }389- ) => {390- return this.addRule('isEmpty', (value) => rule.isEmpty(value as string, options))391- }392-393- isLength = (options: Partial<{ min: number; max: number }> | number, arg2?: number) => {394- return this.addRule('isLength', (value) => rule.isLength(value as string, options, arg2))395- }396-397- isAlpha = () => {398- return this.addRule('isAlpha', (value) => rule.isAlpha(value as string))399- }400-401- isNumeric = () => {402- return this.addRule('isNumeric', (value) => rule.isNumeric(value as string))403- }404-405- contains = (406- elem: string,407- options: Partial<{ ignoreCase: boolean; minOccurrences: number }> = {408- ignoreCase: false,409- minOccurrences: 1,52+ if (res instanceof Response || res instanceof Promise) {53+ return res54 }411- ) => {412- return this.addRule('contains', (value) => rule.contains(value as string, elem, options))413- }55 415- isIn = (options: string[]) => {416- return this.addRule('isIn', (value) => rule.isIn(value as string, options))417- }56+ c.req.addValidatedData(target, res as never)57 419- match = (regExp: RegExp) => {420- return this.addRule('match', (value) => rule.match(value as string, regExp))58+ await next()59 }422-423- trim = () => {424- return this.addSanitizer((value) => sanitizer.trim(value as string))425- }60 }427-428-export class VNumber extends VBase {429- constructor(options: VOptions) {430- super(options)431- this.type = 'number'432- }433-434- asArray = () => {435- return new VNumberArray(this)436- }437-438- isGte = (min: number) => {439- return this.addRule('isGte', (value) => rule.isGte(value as number, min))440- }441-442- isLte = (min: number) => {443- return this.addRule('isLte', (value) => rule.isLte(value as number, min))444- }445-}446-447-export class VBoolean extends VBase {448- constructor(options: VOptions) {449- super(options)450- this.type = 'boolean'451- }452-453- asArray = () => {454- return new VBooleanArray(this)455- }456-457- isTrue = () => {458- return this.addRule('isTrue', (value) => rule.isTrue(value as boolean))459- }460-461- isFalse = () => {462- return this.addRule('isFalse', (value) => rule.isFalse(value as boolean))463- }464-}465-466-export class VNumberArray extends VNumber {467- isArray: true468- constructor(options: VOptions) {469- super(options)470- this.isArray = true471- this.rules[0].name = this.getTypeRuleName()472- }473- asNumber = () => {474- return new VNumberArray({ ...this, type: 'number' })475- }476- asBoolean = () => {477- return new VBooleanArray({ ...this, type: 'boolean' })478- }479-}480-481-export class VStringArray extends VString {482- isArray: true483- constructor(options: VOptions) {484- super(options)485- this.isArray = true486- this.rules[0].name = this.getTypeRuleName()487- }488- asNumber = () => {489- return new VNumberArray({ ...this, type: 'number' })490- }491- asBoolean = () => {492- return new VBooleanArray({ ...this, type: 'boolean' })493- }494-}495-496-export class VBooleanArray extends VBoolean {497- isArray: true498- constructor(options: VOptions) {499- super(options)500- this.isArray = true501- this.rules[0].name = this.getTypeRuleName()502- }503- asNumber = () => {504- return new VNumberArray({ ...this, type: 'number' })505- }506- asBoolean = () => {507- return new VBooleanArray({ ...this, type: 'boolean' })508- }509-}modified:deno_dist/compose.ts+8 added-2 removed
1 import { Context } from './context.ts'2-import type { Environment, NotFoundHandler, ErrorHandler } from './types.ts'2+import type { Env, NotFoundHandler, ErrorHandler } from './types.ts'3 4 interface ComposeContext {5 finalized: boolean6 res: unknown7 }8 9 // Based on the code in the MIT licensed `koa-compose` package.10-export const compose = <C extends ComposeContext, E extends Partial<Environment> = Environment>(10+export const compose = <C extends ComposeContext, E extends Env = Env>(11 middleware: Function[],12 onError?: ErrorHandler<E>,13 onNotFound?: NotFoundHandler<E>14 ) => {34 unmodified lines49 }50 }51 52 if (!(res instanceof Promise)) {53+ if (res !== undefined && 'response' in res) {54+ res = res['response']55+ }56 if (res && (context.finalized === false || isError)) {57 context.res = res58 }59 return context60 } else {61 return res62 .then((res) => {63+ if (res !== undefined && 'response' in res) {64+ res = res['response']65+ }66 if (res && context.finalized === false) {67 context.res = res68 }69 return context13 unmodified linesmodified:deno_dist/context.ts+167 added-101 removed
1-import type { ExecutionContext } from './types.ts'2-import type { Environment, NotFoundHandler, ContextVariableMap } from './types.ts'1+import { HonoRequest } from './request.ts'2+import type { TypedResponse } from './types.ts'3+import type { Env, NotFoundHandler, Input } from './types.ts'4 import type { CookieOptions } from './utils/cookie.ts'5 import { serialize } from './utils/cookie.ts'6 import type { StatusCode } from './utils/http-status.ts'6-import type { Schema, SchemaToProp } from './validator/schema.ts'7 8-type HeaderField = [string, string]9-type Headers = Record<string, string | string[]>10-type Runtime = 'node' | 'deno' | 'bun' | 'cloudflare' | 'fastly' | 'vercel' | 'lagon' | 'other'11-export type Data = string | ArrayBuffer | ReadableStream8+type Runtime = 'node' | 'deno' | 'bun' | 'workerd' | 'fastly' | 'edge-light' | 'lagon' | 'other'9+type HeaderRecord = Record<string, string | string[]>10+type Data = string | ArrayBuffer | ReadableStream11 12+export interface ExecutionContext {13+ waitUntil(promise: Promise<void>): void14+ passThroughOnException(): void15+}16+export interface ContextVariableMap {}17+18+type GetVariable<K, E extends Env> = K extends keyof E['Variables']19+ ? E['Variables'][K]20+ : K extends keyof ContextVariableMap21+ ? ContextVariableMap[K]22+ : unknown23+24+type ContextOptions<E extends Env> = {25+ env: E['Bindings']26+ executionCtx?: FetchEvent | ExecutionContext | undefined27+ notFoundHandler?: NotFoundHandler<E>28+ paramData?: Record<string, string>29+}30+31 export class Context<14- P extends string = string,15- E extends Partial<Environment> = Environment,32 // eslint-disable-next-line @typescript-eslint/no-explicit-any17- S = any33+ E extends Env = any,34+ // eslint-disable-next-line @typescript-eslint/no-explicit-any35+ P extends string = any,36+ I extends Input = {}37 > {19- req: Request<unknown, P, S extends Schema ? SchemaToProp<S> : S>20- env: E['Bindings']21- finalized: boolean38+ env: E['Bindings'] = {}39+ finalized: boolean = false40 error: Error | undefined = undefined41 42+ // eslint-disable-next-line @typescript-eslint/no-explicit-any43+ private _req?: HonoRequest<any, any>44 private _status: StatusCode = 20045 private _executionCtx: FetchEvent | ExecutionContext | undefined46 private _pretty: boolean = false47 private _prettySpace: number = 248 private _map: Record<string, unknown> | undefined29- private _headers: Record<string, string[]> | undefined49+ private _headers: Headers | undefined = undefined50+ private _preparedHeaders: Record<string, string> | undefined = undefined51 private _res: Response | undefined52+ private _paramData?: Record<string, string> | null53+ private rawRequest?: Request | null31- private notFoundHandler: NotFoundHandler<E>54+ private notFoundHandler: NotFoundHandler<E> = () => new Response()55 33- constructor(34- req: Request<unknown, P>,35- env: E['Bindings'] = {},36- executionCtx: FetchEvent | ExecutionContext | undefined = undefined,37- notFoundHandler: NotFoundHandler<E> = () => new Response()38- ) {39- this._executionCtx = executionCtx40- this.req = req as Request<unknown, P>41- this.env = env56+ constructor(req: Request, options?: ContextOptions<E>) {57+ this.rawRequest = req58+ if (options) {59+ this._executionCtx = options.executionCtx60+ this._paramData = options.paramData61+ this.env = options.env62+ if (options.notFoundHandler) {63+ this.notFoundHandler = options.notFoundHandler64+ }65+ }66+ }67 43- this.notFoundHandler = notFoundHandler44- this.finalized = false68+ get req(): HonoRequest<P, I> {69+ if (this._req) {70+ return this._req71+ } else {72+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion73+ this._req = new HonoRequest(this.rawRequest!, this._paramData!)74+ this.rawRequest = undefined75+ this._paramData = undefined76+ return this._req77+ }78 }79 80 get event(): FetchEvent {81 if (this._executionCtx instanceof FetchEvent) {26 unmodified lines108 this.finalized = true109 }110 111 header = (name: string, value: string, options?: { append?: boolean }): void => {79- this._headers ||= {}80- const key = name.toLowerCase()81-82- let shouldAppend = false83- if (options && options.append) {84- const vAlreadySet = this._headers[key]85- if (vAlreadySet && vAlreadySet.length) {86- shouldAppend = true112+ if (options?.append) {113+ if (!this._headers) {114+ this._headers = new Headers(this._preparedHeaders)115 }88- }89-90- if (shouldAppend) {91- this._headers[key].push(value)116+ this._headers.append(name, value)117 } else {93- this._headers[key] = [value]118+ if (this._headers) {119+ this._headers.set(name, value)120+ } else {121+ this._preparedHeaders ??= {}122+ this._preparedHeaders[name.toLowerCase()] = value123+ }124 }125 126 if (this.finalized) {97- if (shouldAppend) {127+ if (options?.append) {128 this.res.headers.append(name, value)129 } else {130 this.res.headers.set(name, value)131 }3 unmodified lines135 status = (status: StatusCode): void => {136 this._status = status137 }138 109- set<Key extends keyof ContextVariableMap>(key: Key, value: ContextVariableMap[Key]): void110- set<Key extends keyof E['Variables']>(key: Key, value: E['Variables'][Key]): void111- set(key: string, value: unknown): void112- set(key: string, value: unknown): void {139+ set = <Key extends keyof E['Variables'] | keyof ContextVariableMap>(140+ key: Key,141+ value: GetVariable<Key, E>142+ ): void => {143 this._map ||= {}114- this._map[key] = value144+ this._map[key as string] = value145 }146 117- get<Key extends keyof ContextVariableMap>(key: Key): ContextVariableMap[Key]118- get<Key extends keyof E['Variables']>(key: Key): E['Variables'][Key]119- get<T>(key: string): T120- get(key: string) {121- if (!this._map) {122- return undefined123- }124- return this._map[key]147+ get = <Key extends keyof E['Variables'] | keyof ContextVariableMap>(148+ key: Key149+ ): GetVariable<Key, E> => {150+ return this._map?.[key as string] as GetVariable<Key, E>151 }152 153 pretty = (prettyJSON: boolean, space: number = 2): void => {154 this._pretty = prettyJSON155 this._prettySpace = space156 }157 132- newResponse = (data: Data | null, status: StatusCode, headers: Headers = {}): Response => {133- return new Response(data, {134- status,135- headers: this._finalizeHeaders(headers),136- })137- }158+ newResponse = (data: Data | null, status?: StatusCode, headers?: HeaderRecord): Response => {159+ // Optimized160+ if (!headers && !this._headers && !this._res && !status) {161+ return new Response(data, {162+ headers: this._preparedHeaders,163+ })164+ }165 139- private _finalizeHeaders(incomingHeaders: Headers): HeaderField[] {140- const finalizedHeaders: HeaderField[] = []141- const headersKv = this._headers || {}142- // If Response is already set166+ this._preparedHeaders ??= {}167+168+ if (!this._headers) {169+ this._headers = new Headers()170+ for (const [k, v] of Object.entries(this._preparedHeaders)) {171+ this._headers.set(k, v)172+ }173+ }174+175 if (this._res) {176 this._res.headers.forEach((v, k) => {145- headersKv[k] = [v]177+ this._headers?.set(k, v)178 })179+ for (const [k, v] of Object.entries(this._preparedHeaders)) {180+ this._headers.set(k, v)181+ }182 }148- for (const key of Object.keys(incomingHeaders)) {149- const value = incomingHeaders[key]150- if (typeof value === 'string') {151- finalizedHeaders.push([key, value])183+184+ headers ??= {}185+ for (const [k, v] of Object.entries(headers)) {186+ if (typeof v === 'string') {187+ this._headers.set(k, v)188 } else {153- for (const v of value) {154- finalizedHeaders.push([key, v])189+ this._headers.delete(k)190+ for (const v2 of v) {191+ this._headers.append(k, v2)192 }193 }157- delete headersKv[key]194 }159- for (const key of Object.keys(headersKv)) {160- for (const value of headersKv[key]) {161- const kv: HeaderField = [key, value]162- finalizedHeaders.push(kv)163- }164- }165- return finalizedHeaders195+196+ return new Response(data, {197+ status,198+ headers: this._headers,199+ })200 }201 202 body = (203 data: Data | null,204 status: StatusCode = this._status,171- headers: Headers = {}205+ headers?: HeaderRecord206 ): Response => {207 return this.newResponse(data, status, headers)208 }209 176- text = (text: string, status?: StatusCode, headers?: Headers): Response => {210+ text = (text: string, status?: StatusCode, headers?: HeaderRecord): Response => {211 // If the header is empty, return Response immediately.212 // Content-Type will be added automatically as `text/plain`.213+ if (!this._preparedHeaders) {179- if (!headers && !status && !this._res && !this._headers) {180- return new Response(text)214+ if (!headers && !this._res && !this._headers && !status) {215+ return new Response(text)216+ }217+ this._preparedHeaders = {}218 }182- status ||= this._status183- headers ||= {}184- headers['content-type'] = 'text/plain; charset=UTF-8'219+ // If Content-Type is not set, we don't have to set `text/plain`.220+ // Fewer the header values, it will be faster.221+ if (this._preparedHeaders['content-type']) {222+ this._preparedHeaders['content-type'] = 'text/plain; charset=UTF8'223+ }224 return this.newResponse(text, status, headers)225 }226 188- json = <T>(object: T, status: StatusCode = this._status, headers: Headers = {}): Response => {227+ json = <T = object>(228+ object: T,229+ status: StatusCode = this._status,230+ headers?: HeaderRecord231+ ): Response => {232 const body = this._pretty233 ? JSON.stringify(object, null, this._prettySpace)234 : JSON.stringify(object)235+ this._preparedHeaders ??= {}192- headers['content-type'] = 'application/json; charset=UTF-8'236+ this._preparedHeaders['content-type'] = 'application/json; charset=UTF-8'237 return this.newResponse(body, status, headers)238 }239 196- html = (html: string, status: StatusCode = this._status, headers: Headers = {}): Response => {197- headers['content-type'] = 'text/html; charset=UTF-8'240+ jsonT = <T = object>(241+ object: T,242+ status: StatusCode = this._status,243+ headers?: HeaderRecord244+ ): TypedResponse<T> => {245+ return {246+ response: this.json(object, status, headers),247+ data: object,248+ format: 'json',249+ }250+ }251+252+ html = (html: string, status: StatusCode = this._status, headers?: HeaderRecord): Response => {253+ this._preparedHeaders ??= {}254+ this._preparedHeaders['content-type'] = 'text/html; charset=UTF-8'255 return this.newResponse(html, status, headers)256 }257 258 redirect = (location: string, status: StatusCode = 302): Response => {202- return this.newResponse(null, status, {203- Location: location,204- })259+ this._headers ??= new Headers()260+ this._headers.set('Location', location)261+ return this.newResponse(null, status)262 }263 264 cookie = (name: string, value: string, opt?: CookieOptions): void => {265 const cookie = serialize(name, value, opt)266 this.header('set-cookie', cookie, { append: true })267 }268 269 notFound = (): Response | Promise<Response> => {270+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment271+ // @ts-ignore213- return this.notFoundHandler(this as unknown as Context<string, E>)272+ return this.notFoundHandler(this)273 }274 275 get runtime(): Runtime {276 // eslint-disable-next-line @typescript-eslint/no-explicit-any7 unmodified lines284 return 'bun'285 }286 287 if (typeof global?.WebSocketPair === 'function') {229- return 'cloudflare'288+ return 'workerd'289 }290 232- if (global?.fastly !== undefined) {233- return 'fastly'234- }235-291 if (typeof global?.EdgeRuntime === 'string') {237- return 'vercel'292+ return 'edge-light'293 }294 240- if (global?.process?.release?.name === 'node') {241- return 'node'295+ let onFastly = false296+ try {297+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment298+ // @ts-ignore299+ const { env } = require('fastly:env')300+ if (env instanceof Function) onFastly = true301+ } catch {}302+ if (onFastly) {303+ return 'fastly'304 }305 306 if (global?.__lagon__ !== undefined) {307 return 'lagon'308 }309 310+ if (global?.process?.release?.name === 'node') {311+ return 'node'312+ }313+314 return 'other'315 }316 }modified:deno_dist/hono.ts+102 added-117 removed
1 import { compose } from './compose.ts'2 import { Context } from './context.ts'3-import { extendRequestPrototype } from './request.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 { RegExpRouter } from './router/reg-exp-router/index.ts'8 import { SmartRouter } from './router/smart-router/index.ts'8-import { StaticRouter } from './router/static-router/index.ts'9 import { TrieRouter } from './router/trie-router/index.ts'10-import type { ExecutionContext } from './types.ts'11-import type { Handler, Environment, ParamKeys, ErrorHandler, NotFoundHandler } from './types.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+} from './types.ts'22 import { getPathFromURL, mergePath } from './utils/url.ts'23 14-interface HandlerInterface<15- P extends string,16- E extends Partial<Environment> = Environment,17- S = unknown,18- U = Hono<E, P, S>19-> {20- // app.get(handler...)21- <Path extends string, Data = S>(22- ...handlers: Handler<ParamKeys<Path> extends never ? string : ParamKeys<Path>, E, Data>[]23- ): Hono<E, Path, Data & S>24- (...handlers: Handler<P, E, S>[]): U24+type Methods = typeof METHODS[number] | typeof METHOD_NAME_ALL_LOWERCASE25 26- // app.get('/', handler, handler...)27- <Path extends string, Data = S>(28- path: Path,29- ...handlers: Handler<ParamKeys<Path> extends never ? string : ParamKeys<Path>, E, Data>[]30- ): Hono<E, Path, Data & S>31- <Path extends string, Data = S>(path: Path, ...handlers: Handler<string, E, Data>[]): Hono<32- E,33- string,34- Data & S35- >36- (path: string, ...handlers: Handler<P, E, S>[]): U26+interface RouterRoute {27+ path: string28+ method: string29+ handler: H30 }31 39-type Methods = typeof METHODS[number] | typeof METHOD_NAME_ALL_LOWERCASE40-32 function defineDynamicClass(): {42- new <43- E extends Partial<Environment> = Environment,44- P extends string = string,45- S = unknown,46- U = Hono<E, P, S>47- >(): {48- [K in Methods]: HandlerInterface<P, E, S, U>33+ new <E extends Env = Env, S = {}>(): {34+ [M in Methods]: HandlerInterface<E, M, S>35+ } & {36+ on: OnHandlerInterface<E, S>37+ } & {38+ use: MiddlewareHandlerInterface<E, S>39 }40 } {41 return class {} as never42 }43 54-interface Route<55- P extends string = string,56- E extends Partial<Environment> = Environment,57- S = unknown58-> {59- path: string60- method: string61- handler: Handler<P, E, S>62-}63-64-const notFoundHandler = <E extends Partial<Environment>>(c: Context<string, E>) => {44+const notFoundHandler = (c: Context) => {45 return c.text('404 Not Found', 404)46 }47 68-const errorHandler = <E extends Partial<Environment>>(err: Error, c: Context<string, E>) => {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 74-export class Hono<75- E extends Partial<Environment> = Environment,76- P extends string = string,77- S = unknown78-> extends defineDynamicClass()<E, P, S, Hono<E, P, S>> {79- readonly router: Router<Handler<P, E, S>> = new SmartRouter({80- routers: [new StaticRouter(), new RegExpRouter(), new TrieRouter()],57+export class Hono<E extends Env = Env, S = {}> extends defineDynamicClass()<E, S> {58+ readonly router: Router<H> = new SmartRouter({59+ routers: [new RegExpRouter(), new TrieRouter()],60 })61 readonly strict: boolean = true // strict routing - default is true62 private _tempPath: string = ''84- private path: string = '/'63+ private path: string = '*'64 86- routes: Route<P, E, S>[] = []65+ routes: RouterRoute[] = []66 67 constructor(init: Partial<Pick<Hono, 'router' | 'strict'>> = {}) {68 super()69 91- extendRequestPrototype()92-70+ // Implementation of app.get(...handlers[]) or app.get(path, ...handlers[])71 const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE]72 allMethods.map((method) => {95- // eslint-disable-next-line @typescript-eslint/ban-ts-comment96- // @ts-ignore97- this[method] = (args1: string | Handler, ...args: Handler[]) => {73+ this[method] = (args1: string | H, ...args: H[]) => {74 if (typeof args1 === 'string') {75 this.path = args176 } else {101- this.addRoute(method, this.path, args1 as unknown as Handler<P, E, S>)77+ this.addRoute(method, this.path, args1)78 }79 args.map((handler) => {80 if (typeof handler !== 'string') {105- this.addRoute(method, this.path, handler as unknown as Handler<P, E, S>)81+ this.addRoute(method, this.path, handler)82 }83 })108- // eslint-disable-next-line @typescript-eslint/no-explicit-any109- return this as unknown as Hono<E, any, any>84+ return this85 }86 })87 88+ // Implementation of app.on(method, path, ...handlers[])89+ this.on = (method: string | string[], path: string, ...handlers: H[]) => {90+ if (!method) return this91+ this.path = path92+ for (const m of [method].flat()) {93+ handlers.map((handler) => {94+ this.addRoute(m.toUpperCase(), this.path, handler)95+ })96+ }97+ return this98+ }99+100+ // Implementation of app.use(...handlers[]) or app.get(path, ...handlers[])101+ this.use = (arg1: string | MiddlewareHandler, ...handlers: MiddlewareHandler[]) => {102+ if (typeof arg1 === 'string') {103+ this.path = arg1104+ } else {105+ handlers.unshift(arg1)106+ }107+ handlers.map((handler) => {108+ this.addRoute(METHOD_NAME_ALL, this.path, handler)109+ })110+ return this111+ }112+113 Object.assign(this, init)114 }115 116- private notFoundHandler: NotFoundHandler<E> = notFoundHandler117- private errorHandler: ErrorHandler<E> = errorHandler116+ private notFoundHandler: NotFoundHandler = notFoundHandler117+ private errorHandler: ErrorHandler = errorHandler118 119 // eslint-disable-next-line @typescript-eslint/no-explicit-any120- route(path: string, app?: Hono<any>) {120+ route(path: string, app?: Hono<any, any>) {121 this._tempPath = path122 if (app) {123 app.routes.map((r) => {124- const handler = (124+ const handler =125 app.errorHandler === errorHandler126 ? r.handler127- : async (...args) =>128- (await compose<Context<P, E>, E>([r.handler], app.errorHandler)(...args)).res129- ) as Handler<P, E, S>127+ : async (c: Context, next: Next) =>128+ (await compose<Context>([r.handler], app.errorHandler)(c, next)).res129 this.addRoute(r.method, r.path, handler)130 })131 this._tempPath = ''132 }133 return this134 }135 137- use<Path extends string = string, Data = unknown>(138- ...middleware: Handler<Path, E, Data>[]139- ): Hono<E, P, S>140- use<Path extends string = string, Data = unknown>(141- arg1: string,142- ...middleware: Handler<Path, E, Data>[]143- ): Hono<E, P, S>144- use(arg1: string | Handler<P, E, S>, ...handlers: Handler<P, E, S>[]) {145- if (typeof arg1 === 'string') {146- this.path = arg1147- } else {148- handlers.unshift(arg1)149- }150- handlers.map((handler) => {151- this.addRoute(METHOD_NAME_ALL, this.path, handler)152- })153- return this154- }155-156- on(method: string, path: string, ...handlers: Handler<P, E, S>[]) {157- if (!method) return this158- this.path = path159- handlers.map((handler) => {160- this.addRoute(method.toUpperCase(), this.path, handler)161- })162- return this163- }164-136 onError(handler: ErrorHandler<E>) {137 this.errorHandler = handler138 return this139 }11 unmodified lines151 )152 })153 }154 184- private addRoute(method: string, path: string, handler: Handler<P, E, S>) {155+ private addRoute(method: string, path: string, handler: H) {156 method = method.toUpperCase()157 if (this._tempPath) {158 path = mergePath(this._tempPath, path)159 }160 this.router.add(method, path, handler)190- const r: Route<P, E, S> = { path: path, method: method, handler: handler }161+ const r: RouterRoute = { path: path, method: method, handler: handler }162 this.routes.push(r)163 }164 165 private matchRoute(method: string, path: string) {166 return this.router.match(method, path)167 }168 198- private handleError(err: unknown, c: Context<string, E>) {169+ private handleError(err: unknown, c: Context<E>) {170 if (err instanceof Error) {171 return this.errorHandler(err, c)172 }173 throw err2 unmodified lines176 private dispatch(177 request: Request,178 eventOrExecutionCtx?: ExecutionContext | FetchEvent,179 env?: E['Bindings']209- ) {180+ ): Response | Promise<Response> {181 const path = getPathFromURL(request.url, this.strict)182 const method = request.method183 184 const result = this.matchRoute(method, path)214- request.paramData = result?.params185+ const paramData = result?.params186 216- const c = new Context<string, E>(request, env, eventOrExecutionCtx, this.notFoundHandler)187+ const c = new Context(request, {188+ env,189+ executionCtx: eventOrExecutionCtx,190+ notFoundHandler: this.notFoundHandler,191+ paramData,192+ })193 194 // Do not `compose` if it has only one handler219- if (result && result.handlers.length === 1) {195+ if (result?.handlers.length === 1) {196 const handler = result.handlers[0]221- let res: ReturnType<Handler<P>>197+ let res: ReturnType<H>198 199 try {224- // eslint-disable-next-line @typescript-eslint/no-explicit-any225- res = handler(c as any, async () => {})226- if (!res) return this.notFoundHandler(c)200+ res = handler(c, async () => {})201+ if (!res) {202+ return this.notFoundHandler(c)203+ }204 } catch (err) {205 return this.handleError(err, c)206 }207 208 if (res instanceof Response) return res209 210+ if ('response' in res) {211+ res = res.response212+ }213+214+ if (res instanceof Response) return res215+216 return (async () => {234- let awaited: Response | undefined | void217+ let awaited: Response | TypedResponse | void218 try {219 awaited = await res220+ if (awaited !== undefined && 'response' in awaited) {221+ awaited = awaited['response'] as Response222+ }223 if (!awaited) {224 return this.notFoundHandler(c)225 }226 } catch (err) {3 unmodified lines230 })()231 }232 233 const handlers = result ? result.handlers : [this.notFoundHandler]248- const composed = compose<Context<P, E>, E>(handlers, this.errorHandler, this.notFoundHandler)234+ const composed = compose<Context>(handlers, this.errorHandler, this.notFoundHandler)235 236 return (async () => {237 try {252- // eslint-disable-next-line @typescript-eslint/no-explicit-any253- const tmp = composed(c as any)238+ const tmp = composed(c)239 const context = tmp instanceof Promise ? await tmp : tmp240 if (!context.finalized) {241 throw new Error(242 'Context is not finalized. You may forget returning Response object or `await next()`'9 unmodified lines252 handleEvent = (event: FetchEvent) => {253 return this.dispatch(event.request, event)254 }255 271- fetch = (request: Request, Environment?: E['Bindings'], executionCtx?: ExecutionContext) => {272- return this.dispatch(request, executionCtx, Environment)256+ fetch = (request: Request, Env?: E['Bindings'] | {}, executionCtx?: ExecutionContext) => {257+ return this.dispatch(request, executionCtx, Env)258 }259 260 request = async (input: Request | string, requestInit?: RequestInit) => {261 const req = input instanceof Request ? input : new Request(input, requestInit)3 unmodified linesadded:deno_dist/http-exception.ts+26 added
1+import type { StatusCode } from './utils/http-status.ts'2+import { getStatusText } from './utils/http-status.ts'3+4+type HTTPExceptionOptions = {5+ res?: Response6+ message?: string7+}8+9+export class HTTPException extends Error {10+ readonly res?: Response11+ readonly status: StatusCode12+ constructor(status: StatusCode = 500, options?: HTTPExceptionOptions) {13+ super(options?.message || getStatusText(status))14+ this.res = options?.res15+ this.status = status16+ }17+ getResponse(): Response {18+ if (this.res) {19+ return this.res20+ }21+ return new Response(this.message, {22+ status: this.status,23+ statusText: getStatusText(this.status),24+ })25+ }26+}modified:deno_dist/middleware.ts+1 added-2 removed
9 unmodified lines10 export * from './middleware/jwt/index.ts'11 export * from './middleware/logger/index.ts'12 export * from './middleware/powered-by/index.ts'13 export * from './middleware/pretty-json/index.ts'14-export * from './middleware/validator/index.ts'15-export * from './deno/serve-static.ts'14+export * from './adapter/deno/serve-static.ts'modified:deno_dist/mod.ts+15 added-8 removed
1 import { Hono } from './hono.ts'2 3 declare global {4+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment5+ // @ts-ignore6 class ExtendableEvent extends Event {7 constructor(type: string, init?: EventInit)8 waitUntil(promise: Promise<void>): void9 }10+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment11+ // @ts-ignore12 abstract class FetchEvent extends ExtendableEvent {13 readonly request: Request14 respondWith(promise: Response | Promise<Response>): void15 passThroughOnException(): void4 unmodified lines20 }21 }22 23 export type {20- Next,21- ContextVariableMap,22- MiddlewareHandler,24+ Env,25 ErrorHandler,26+ Handler,27+ MiddlewareHandler,28+ Next,29 NotFoundHandler,30+ ValidationTargets,31 } from './types.ts'26-import type { CustomHandler } from './types.ts'27-export type { CustomHandler as Handler }28-export type { Context } from './context.ts'32+export type { Context, ContextVariableMap } from './context.ts'33 export { Hono }34 35 // Router36 export { RegExpRouter } from './router/reg-exp-router/index.ts'37 export { TrieRouter } from './router/trie-router/index.ts'34-export { StaticRouter } from './router/static-router/index.ts'38 export { SmartRouter } from './router/smart-router/index.ts'39 40 // Validator38-export type { Validator } from './validator/validator.ts'41+export { validator } from './validator/index.ts'42+43+// Client44+export { hc } from './client/index.ts'45+export type { InferResponseType } from './client/index.ts'modified:deno_dist/README.md+23 added-19 removed
1 <div align="center">2- <a href="https://honojs.dev">2+ <a href="https://hono.dev">3 <img src="https://raw.githubusercontent.com/honojs/hono/main/docs/images/hono-title.png" width="500" height="auto" alt="Hono"/>4 </a>5 </div>6 7 <hr />8 9 <p align="center">10-<a href="https://honojs.dev"><b>Documentation :point_right: honojs.dev</b></a><br />11-<i>v2.x has been released!</i> <a href="docs/MIGRATION.md">Migration guide</b>10+<a href="https://hono.dev"><b>Documentation :point_right: hono.dev</b></a><br />11+<i>v3 has been released!</i> <a href="docs/MIGRATION.md">Migration guide</b>12 </p>13 14 <hr />15 16 [](https://github.com/honojs/hono/actions)17 [](https://github.com/honojs/hono/blob/main/LICENSE)18 [](https://www.npmjs.com/package/hono)19 [](https://www.npmjs.com/package/hono)20+[](https://bundlephobia.com/result?p=hono)21+[](https://bundlephobia.com/result?p=hono)22 [](https://www.npmjs.com/package/hono)23 [](https://github.com/honojs/hono/pulse)24 [](https://github.com/honojs/hono/commits/main)25 [](https://doc.deno.land/https/deno.land/x/hono/mod.ts)26 [](https://discord.gg/KMh2eNSdxV)27 26-Hono - _**[炎] means flame🔥 in Japanese**_ - is a small, simple, and ultrafast web framework for Cloudflare Workers, Deno, Bun, and others.28+Hono - _**\[炎\] means flame🔥 in Japanese**_ - is a small, simple, and ultrafast web framework for the Edge.29+It works on Cloudflare Workers, Fastly Compute@Edge, Deno, Bun, Vercel, Lagon, Node.js, and others.30+Fast, but not only fast.31 32 ```ts33 import { Hono } from 'hono'34 const app = new Hono()35 32-app.get('/', (c) => c.text('Hono!!'))36+app.get('/', (c) => c.text('Hono!'))37 38 export default app39 ```40 41 ## Features42 39-- **Ultrafast** - The routers are really smart. Not using linear loops. The fastest one will be selected from three routers.40-- **Zero-dependencies** - Using only Web Standard API. Does not depend on other npm or Deno libraries.41-- **Middleware** - Hono has built-in middleware, custom middleware, and third-party middleware. Batteries included.42-- **TypeScript** - First-class TypeScript support. Now, we've got "Types".43-- **Multi-runtime** - Works on Cloudflare Workers, Fastly Compute@Edge, Deno, Bun, or Node.js. The same code runs on all platforms.43+- **Ultrafast** - The routers are really fast and smart. Not using linear loops. Fast.44+- **Multi-runtime** - Works on Cloudflare Workers, Fastly Compute@Edge, Deno, Bun, Lagon, or Node.js. The same code runs on all platforms.45+- **Batteries Included** - Hono has built-in middleware, custom middleware, and third-party middleware. Batteries included.46+- **Fine DX** - First-class TypeScript support. Now, we've got "Types".47+- **Small** - About 20kB. Zero-dependencies. Using only Web Standard API.48 49 ## Benchmarks50 47-**Hono is fastest**, compared to other routers for Cloudflare Workers.51+**Hono is the fastest**, compared to other routers for Cloudflare Workers.52 49-```plain50-Hono x 616,464 ops/sec ±4.76% (83 runs sampled)51-itty-router x 203,074 ops/sec ±3.66% (88 runs sampled)52-sunder x 314,306 ops/sec ±2.28% (87 runs sampled)53-worktop x 194,111 ops/sec ±2.78% (81 runs sampled)53+```54+Hono x 385,807 ops/sec ±5.02% (76 runs sampled)55+itty-router x 205,318 ops/sec ±3.63% (84 runs sampled)56+sunder x 287,198 ops/sec ±4.90% (74 runs sampled)57+worktop x 191,134 ops/sec ±3.06% (85 runs sampled)58 Fastest is Hono55-✨ Done in 30.77s.59+✨ Done in 27.51s.60 ```61 62 ## Documentation63 60-The documentation is available on [honojs.dev](https://honojs.dev).64+The documentation is available on [hono.dev](https://hono.dev).65 66 ## Migration67 64-Migration guide is available on [docs/MIGRATION.md](docs/MIGRATION.md).68+The migration guide is available on [docs/MIGRATION.md](docs/MIGRATION.md).69 70 ## Communication71 72 [Twitter](https://twitter.com/honojs) and [Discord channel](https://discord.gg/KMh2eNSdxV) are available.24 unmodified linesmodified:deno_dist/request.ts+139 added-134 removed
1+import type {2+ Input,3+ InputToDataByTarget,4+ ParamKeys,5+ ParamKeyToRecord,6+ RemoveQuestion,7+ UndefinedIfHavingQuestion,8+ ValidationTargets,9+} from './types.ts'10 import { parseBody } from './utils/body.ts'11 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'6-import { getQueryStringFromURL } from './utils/url.ts'15+import { getQueryStringFromURL, getQueryParam, getQueryParams } from './utils/url.ts'16 8-type RemoveQuestion<T> = T extends `${infer R}?` ? R : T9-// eslint-disable-next-line @typescript-eslint/no-unused-vars10-type UndefinedIfHavingQuestion<T> = T extends `${infer _}?` ? string | undefined : string11-type ParamKeyToRecord<T extends string> = T extends `${infer R}?`12- ? Record<R, string | undefined>13- : Record<T, string>17+export class HonoRequest<P extends string = '/', I extends Input = {}> {18+ raw: Request19 15-declare global {16- interface Request<17- // eslint-disable-next-line @typescript-eslint/no-unused-vars18- CfHostMetadata = unknown,19- ParamKey extends string = string,20- // eslint-disable-next-line @typescript-eslint/no-explicit-any21- Data = any22- > {23- paramData?: Record<ParamKey, string>24- param: {25- (key: RemoveQuestion<ParamKey>): UndefinedIfHavingQuestion<ParamKey>26- (): UnionToIntersection<ParamKeyToRecord<ParamKey>>27- }28- queryData?: Record<string, string>29- query: {30- (key: string): string31- (): Record<string, string>32- }33- queries: {34- (key: string): string[]35- (): Record<string, string[]>36- }37- headerData?: Record<string, string>38- header: {39- (name: string): string | undefined40- (): Record<string, string>41- }42- cookie: {43- (name: string): string | undefined44- (): Cookie45- }46- bodyData?: BodyData47- parseBody<BodyType extends BodyData>(): Promise<BodyType>48- // eslint-disable-next-line @typescript-eslint/no-explicit-any49- jsonData?: any50- json<T>(): Promise<T>51- data: Data52- valid: {53- (data: Data): Data54- (): Data55- }56- }57-}20+ private paramData: Record<string, string> | undefined21+ private validatedData: { [K in keyof ValidationTargets]?: {} }22 59-export function extendRequestPrototype() {60- if (!!Request.prototype.param as boolean) {61- // already extended62- return23+ constructor(request: Request, paramData?: Record<string, string> | undefined) {24+ this.raw = request25+ this.paramData = paramData26+ this.validatedData = {}27 }28 65- Request.prototype.param = function (this: Request, key?: string) {29+ param(key: RemoveQuestion<ParamKeys<P>>): UndefinedIfHavingQuestion<ParamKeys<P>>30+ param(): UnionToIntersection<ParamKeyToRecord<ParamKeys<P>>>31+ param(key?: string): unknown {32 if (this.paramData) {33 if (key) {34 const param = this.paramData[key]69- return param ? decodeURIComponent(param) : undefined35+ return param ? (/\%/.test(param) ? decodeURIComponent(param) : param) : undefined36 } else {37 const decoded: Record<string, string> = {}38 39 for (const [key, value] of Object.entries(this.paramData)) {74- if (value) {75- decoded[key] = decodeURIComponent(value)40+ if (value && typeof value === 'string') {41+ decoded[key] = /\%/.test(value) ? decodeURIComponent(value) : value42 }43 }44 45 return decoded46 }47 }48 return null83- } as InstanceType<typeof Request>['param']49+ }50 85- Request.prototype.header = function (this: Request, name?: string) {86- if (!this.headerData) {87- this.headerData = {}88- this.headers.forEach((value, key) => {89- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion90- this.headerData![key] = value91- })92- }93- if (name) {94- return this.headerData[name.toLowerCase()]95- } else {96- return this.headerData97- }98- } as InstanceType<typeof Request>['header']99-100- Request.prototype.query = function (this: Request, key?: string) {51+ query(key: string): string | undefined52+ query(): Record<string, string>53+ query(key?: string) {54 const queryString = getQueryStringFromURL(this.url)102- const searchParams = new URLSearchParams(queryString)103- if (!this.queryData) {104- this.queryData = {}105- for (const key of searchParams.keys()) {106- this.queryData[key] = searchParams.get(key) || ''107- }108- }109- if (key) {110- return this.queryData[key]111- } else {112- return this.queryData113- }114- } as InstanceType<typeof Request>['query']55+ const result = getQueryParam(queryString, key)56+ if (result === null) return undefined57+ return result58+ }59 116- Request.prototype.queries = function (this: Request, key?: string) {60+ queries(key: string): string[] | undefined61+ queries(): Record<string, string[]>62+ queries(key?: string) {63 const queryString = getQueryStringFromURL(this.url)118- const searchParams = new URLSearchParams(queryString)119- if (key) {120- return searchParams.getAll(key)121- } else {122- const result: Record<string, string[]> = {}123- for (const key of searchParams.keys()) {124- result[key] = searchParams.getAll(key)125- }126- return result64+ const result = getQueryParams(queryString, key)65+ if (result === null) return undefined66+ return result67+ }68+69+ header(name: string): string | undefined70+ header(): Record<string, string>71+ header(name?: string) {72+ const headerData: Record<string, string> = {}73+ this.raw.headers.forEach((value, key) => {74+ headerData[key] = value75+ })76+ if (!name) {77+ return headerData78 }128- } as InstanceType<typeof Request>['queries']79+ return headerData[name.toLowerCase()] || undefined80+ }81 130- Request.prototype.cookie = function (this: Request, key?: string) {131- const cookie = this.headers.get('Cookie') || ''82+ cookie(key: string): string | undefined83+ cookie(): Cookie84+ cookie(key?: string) {85+ const cookie = this.raw.headers.get('Cookie')86+ if (!cookie) return87 const obj = parse(cookie)88 if (key) {89 const value = obj[key]90 return value91 } else {92 return obj93 }139- } as InstanceType<typeof Request>['cookie']94+ }95 141- Request.prototype.parseBody = async function <BodyType extends BodyData>(142- this: Request143- ): Promise<BodyType> {144- // Cache the parsed body145- let body: BodyType146- if (!this.bodyData) {147- body = await parseBody<BodyType>(this)148- this.bodyData = body149- } else {150- body = this.bodyData as BodyType151- }152- return body153- } as InstanceType<typeof Request>['parseBody']96+ async parseBody(): Promise<BodyData> {97+ return await parseBody(this.raw)98+ }99 155- Request.prototype.json = async function <JSONData = unknown>(this: Request) {156- // Cache the JSON body157- let jsonData: Partial<JSONData>158- if (!this.jsonData) {159- jsonData = JSON.parse(await this.text())160- this.jsonData = jsonData161- } else {162- jsonData = this.jsonData163- }164- return jsonData165- } as InstanceType<typeof Request>['jsonData']100+ // eslint-disable-next-line @typescript-eslint/no-explicit-any101+ json<T = any>(): Promise<T> {102+ return this.raw.json()103+ }104 167- Request.prototype.valid = function (this: Request, data?: unknown) {168- if (!this.data) {169- this.data = {}105+ text() {106+ return this.raw.text()107+ }108+109+ arrayBuffer() {110+ return this.raw.arrayBuffer()111+ }112+113+ blob() {114+ return this.raw.blob()115+ }116+117+ formData() {118+ return this.raw.formData()119+ }120+121+ addValidatedData(target: keyof ValidationTargets, data: {}) {122+ this.validatedData[target] = data123+ }124+125+ valid<126+ T extends keyof ValidationTargets = I extends Record<infer R, unknown>127+ ? R extends keyof ValidationTargets128+ ? R129+ : never130+ : never131+ >(target: T): InputToDataByTarget<I, T>132+ valid(): never133+ valid(target?: keyof ValidationTargets) {134+ if (target) {135+ return this.validatedData[target] as unknown136 }171- if (data) {172- this.data = data173- }174- return this.data175- } as InstanceType<typeof Request>['valid']137+ }138+139+ get url() {140+ return this.raw.url141+ }142+ get method() {143+ return this.raw.method144+ }145+ get headers() {146+ return this.raw.headers147+ }148+ get redirect() {149+ return this.raw.redirect150+ }151+ get body() {152+ return this.raw.body153+ }154+ get bodyUsed() {155+ return this.raw.bodyUsed156+ }157+ get cache() {158+ return this.raw.cache159+ }160+ get credentials() {161+ return this.raw.credentials162+ }163+ get integrity() {164+ return this.raw.integrity165+ }166+ get keepalive() {167+ return this.raw.keepalive168+ }169+ get mode() {170+ return this.raw.mode171+ }172+ get referrer() {173+ return this.raw.referrer174+ }175+ get refererPolicy() {176+ return this.raw.referrerPolicy177+ }178+ get signal() {179+ return this.raw.signal180+ }181 }modified:deno_dist/types.ts+278 added-53 removed
1+/* eslint-disable @typescript-eslint/no-unused-vars */2+/* eslint-disable @typescript-eslint/no-explicit-any */3+/* eslint-disable @typescript-eslint/ban-types */4 import type { Context } from './context.ts'5+import type { Hono } from './hono.ts'6+import type { UnionToIntersection } from './utils/types.ts'7 3-export interface ContextVariableMap {}8+////////////////////////////////////////9+////// //////10+////// Values //////11+////// //////12+////////////////////////////////////////13 5-// eslint-disable-next-line @typescript-eslint/no-explicit-any6-export type Bindings = Record<string, any> // For Cloudflare Workers7-// eslint-disable-next-line @typescript-eslint/no-explicit-any8-export type Variables = Record<string, any> // For c.set/c.get functions9-export type Environment = {10- Bindings: Bindings11- Variables: Variables14+export type Bindings = Record<string, unknown>15+export type Variables = Record<string, unknown>16+17+export type Env = {18+ Bindings?: Bindings19+ Variables?: Variables20 }21 22+export type Next = () => Promise<void>23+24+export type Input = unknown25+26+////////////////////////////////////////27+////// //////28+////// Handlers //////29+////// //////30+////////////////////////////////////////31+32 export type Handler<15- P extends string = string,16- E extends Partial<Environment> = Environment,17- // eslint-disable-next-line @typescript-eslint/no-explicit-any18- S = any19-> = (c: Context<P, E, S>, next: Next) => Response | Promise<Response | undefined | void>33+ E extends Env = any,34+ P extends string = any,35+ I extends Input = Input,36+ O = {}37+> = (38+ c: Context<E, P, I>,39+ next: Next40+) => Response | Promise<Response | TypedResponse<O>> | TypedResponse<O>41 21-export type MiddlewareHandler<22- P extends string = string,23- E extends Partial<Environment> = Environment,24- // eslint-disable-next-line @typescript-eslint/no-explicit-any25- S = any26-> = (c: Context<P, E, S>, next: Next) => Promise<Response | undefined | void>42+export type MiddlewareHandler<E extends Env = any, P extends string = any, I extends Input = {}> = (43+ c: Context<E, P, I>,44+ next: Next45+) => Promise<Response | void>46 28-export type NotFoundHandler<E extends Partial<Environment> = Environment> = (29- c: Context<string, E>30-) => Response | Promise<Response>47+export type H<E extends Env = any, P extends string = any, I extends Input = {}, O = {}> =48+ | Handler<E, P, I, O>49+ | MiddlewareHandler<E, P, I>50 32-export type ErrorHandler<E extends Partial<Environment> = Environment> = (33- err: Error,34- c: Context<string, E>35-) => Response51+export type NotFoundHandler<E extends Env = any> = (c: Context<E>) => Response | Promise<Response>52+export type ErrorHandler<E extends Env = any> = (err: Error, c: Context<E>) => Response53 37-export type Next = () => Promise<void>54+////////////////////////////////////////55+////// //////56+////// HandlerInterface //////57+////// //////58+////////////////////////////////////////59 60+export interface HandlerInterface<E extends Env = Env, M extends string = any, S = {}> {61+ //// app.get(...handlers[])62+63+ // app.get(handler, handler)64+ <I = {}, O = {}>(...handlers: [H<E, ExtractKey<S>, I, O>, H<E, ExtractKey<S>, I, O>]): Hono<65+ E,66+ S & Schema<M, ExtractKey<S>, I, O>67+ >68+69+ // app.get(handler x 3)70+ <P extends string, O = {}, I = {}, I2 = I, I3 = I & I2>(71+ ...handlers: [H<E, ExtractKey<S>, I, O>, H<E, ExtractKey<S>, I2, O>, H<E, ExtractKey<S>, I3, O>]72+ ): Hono<E, S & Schema<M, ExtractKey<S>, I3, O>>73+74+ // app.get(handler x 4)75+ <P extends string, O = {}, I = {}, I2 = I, I3 = I & I2, I4 = I2 & I3>(76+ ...handlers: [77+ H<E, ExtractKey<S>, I, O>,78+ H<E, ExtractKey<S>, I2, O>,79+ H<E, ExtractKey<S>, I3, O>,80+ H<E, ExtractKey<S>, I4, O>81+ ]82+ ): Hono<E, S & Schema<M, ExtractKey<S>, I4, O>>83+84+ // app.get(handler x 5)85+ <P extends string, O = {}, I = {}, I2 = I, I3 = I & I2, I4 = I2 & I3, I5 = I3 & I4>(86+ ...handlers: [87+ H<E, ExtractKey<S>, I, O>,88+ H<E, ExtractKey<S>, I2, O>,89+ H<E, ExtractKey<S>, I3, O>,90+ H<E, ExtractKey<S>, I4, O>,91+ H<E, ExtractKey<S>, I5, O>92+ ]93+ ): Hono<E, S & Schema<M, ExtractKey<S>, I5, O>>94+95+ // app.get(...handlers[])96+ <I = {}, O = {}>(...handlers: Handler<E, ExtractKey<S>, I, O>[]): Hono<97+ E,98+ S & Schema<M, ExtractKey<S>, I, O>99+ >100+101+ //// app.get(path, ...handlers[])102+103+ // app.get(path, handler, handler)104+ <P extends string, O = {}, I = {}>(path: P, ...handlers: [H<E, P, I, O>, H<E, P, I, O>]): Hono<105+ E,106+ S & Schema<M, P, I, O>107+ >108+109+ // app.get(path, handler x3)110+ <P extends string, O = {}, I = {}, I2 = I, I3 = I & I2>(111+ path: P,112+ ...handlers: [H<E, P, I, O>, H<E, P, I2, O>, H<E, P, I3, O>]113+ ): Hono<E, S & Schema<M, P, I3, O>>114+115+ // app.get(path, handler x4)116+ <P extends string, O = {}, I = {}, I2 = I, I3 = I & I2, I4 = I2 & I3>(117+ path: P,118+ ...handlers: [H<E, P, I, O>, H<E, P, I2, O>, H<E, P, I3, O>, H<E, P, I4, O>]119+ ): Hono<E, S & Schema<M, P, I4, O>>120+121+ // app.get(path, handler x5)122+ <P extends string, O = {}, I = {}, I2 = I, I3 = I & I2, I4 = I2 & I3, I5 = I3 & I4>(123+ path: P,124+ ...handlers: [H<E, P, I, O>, H<E, P, I2, O>, H<E, P, I3, O>, H<E, P, I4, O>, H<E, P, I5, O>]125+ ): Hono<E, S & Schema<M, P, I5, O>>126+127+ // app.get(path, ...handlers[])128+ <P extends string, I = {}, O = {}>(path: P, ...handlers: H<E, P, I, O>[]): Hono<129+ E,130+ S & Schema<M, P, I, O>131+ >132+}133+134+////////////////////////////////////////135+////// //////136+////// MiddlewareHandlerInterface //////137+////// //////138+////////////////////////////////////////139+140+export interface MiddlewareHandlerInterface<E extends Env = Env, S = {}> {141+ //// app.get(...handlers[])142+ (...handlers: MiddlewareHandler<E, ExtractKey<S>>[]): Hono<E, S>143+ //// app.get(path, ...handlers[])144+ <P extends string>(path: P, ...handlers: MiddlewareHandler<E, P>[]): Hono<E, S>145+}146+147+////////////////////////////////////////148+////// //////149+////// OnHandlerInterface //////150+////// //////151+////////////////////////////////////////152+153+export interface OnHandlerInterface<E extends Env = Env, S = {}> {154+ // app.on(method, path, handler, handler)155+ <M extends string, P extends string, O = {}, I = {}>(156+ method: M,157+ path: P,158+ ...handlers: [H<E, P, I, O>, H<E, P, I, O>]159+ ): Hono<E, S & Schema<M, P, I, O>>160+161+ // app.get(method, path, handler x3)162+ <M extends string, P extends string, O = {}, I = {}, I2 = I, I3 = I & I2>(163+ method: M,164+ path: P,165+ ...handlers: [H<E, P, I, O>, H<E, P, I2, O>, H<E, P, I3, O>]166+ ): Hono<E, S & Schema<M, P, I3, O>>167+168+ // app.get(method, path, handler x4)169+ <M extends string, P extends string, O = {}, I = {}, I2 = I, I3 = I & I2, I4 = I2 & I3>(170+ method: M,171+ path: P,172+ ...handlers: [H<E, P, I, O>, H<E, P, I2, O>, H<E, P, I3, O>, H<E, P, I4, O>]173+ ): Hono<E, S & Schema<M, P, I4, O>>174+175+ // app.get(method, path, handler x5)176+ <177+ M extends string,178+ P extends string,179+ O = {},180+ I = {},181+ I2 = I,182+ I3 = I & I2,183+ I4 = I2 & I3,184+ I5 = I3 & I4185+ >(186+ method: M,187+ path: P,188+ ...handlers: [H<E, P, I, O>, H<E, P, I2, O>, H<E, P, I3, O>, H<E, P, I4, O>, H<E, P, I5, O>]189+ ): Hono<E, S & Schema<M, P, I5, O>>190+191+ <M extends string, P extends string, O extends {} = {}, I = {}>(192+ method: M,193+ path: P,194+ ...handlers: H<E, P, I, O>[]195+ ): Hono<E, S & Schema<M, P, I, O>>196+197+ // app.on(method[], path, ...handler)198+ <P extends string, O extends {} = {}, I = {}>(199+ methods: string[],200+ path: P,201+ ...handlers: H<E, P, I, O>[]202+ ): Hono<E, S & Schema<string, P, I, O>>203+}204+205+type ExtractKey<S> = S extends Record<infer Key, unknown>206+ ? Key extends string207+ ? Key208+ : never209+ : string210+211+////////////////////////////////////////212+////// //////213+////// Schema //////214+////// //////215+////////////////////////////////////////216+217+export type Schema<M extends string, P extends string, I extends Input, O> = {218+ [K in P]: AddDollar<{ [K2 in M]: { input: AddParam<I, P>; output: O } }>219+}220+221+export type AddParam<I, P extends string> = ParamKeys<P> extends never222+ ? I223+ : I & { param: UnionToIntersection<ParamKeyToRecord<ParamKeys<P>>> }224+225+export type AddDollar<T> = T extends Record<infer K, infer R>226+ ? K extends string227+ ? { [MethodName in `$${Lowercase<K>}`]: R }228+ : never229+ : never230+231+////////////////////////////////////////232+////// //////233+////// TypedResponse //////234+////// //////235+////////////////////////////////////////236+237+export type TypedResponse<T = unknown> = {238+ response: Response | Promise<Response>239+ data: T240+ format: 'json' // Currently, support only `json` with `c.jsonT()`241+}242+243+////////////////////////////////////////244+////// /////245+////// ValidationTargets /////246+////// /////247+////////////////////////////////////////248+249+export type ValidationTargets = {250+ json: any251+ form: Record<string, string | File>252+ query: Record<string, string>253+ queries: Record<string, string[]>254+}255+256+////////////////////////////////////////257+////// //////258+////// Path parameters //////259+////// //////260+////////////////////////////////////////261+262 // eslint-disable-next-line @typescript-eslint/no-unused-vars263 type ParamKeyName<NameWithPattern> = NameWithPattern extends `${infer Name}{${infer _Pattern}`264 ? Name265 : NameWithPattern5 unmodified lines271 export type ParamKeys<Path> = Path extends `${infer Component}/${infer Rest}`272 ? ParamKey<Component> | ParamKeys<Rest>273 : ParamKey<Path>274 52-// This is not used for internally53-// Will be used by users as `Handler`54-// eslint-disable-next-line @typescript-eslint/no-explicit-any55-export interface CustomHandler<P = string, E = Partial<Environment>, S = any> {56- (57- c: Context<58- P extends string ? P : string,59- P extends Partial<Environment> ? P : E extends Partial<Environment> ? E : never,60- P extends string61- ? E extends Partial<Environment>62- ? S63- : P extends Partial<Environment>64- ? E65- : never66- : P extends Partial<Environment>67- ? E extends Partial<Environment>68- ? S69- : E70- : P71- >,72- next: Next73- ): Response | Promise<Response | undefined | void>74-}275+export type ParamKeyToRecord<T extends string> = T extends `${infer R}?`276+ ? Record<R, string | undefined>277+ : { [K in T]: string }278 76-export interface ExecutionContext {77- waitUntil(promise: Promise<void>): void78- passThroughOnException(): void279+////////////////////////////////////////280+////// //////281+///// For HonoRequest //////282+////// //////283+////////////////////////////////////////284+285+export type InputToDataByTarget<286+ T extends Input,287+ Target extends keyof ValidationTargets288+> = T extends {289+ [K in Target]: infer R290 }291+ ? R292+ : never293+294+export type RemoveQuestion<T> = T extends `${infer R}?` ? R : T295+296+export type UndefinedIfHavingQuestion<T> = T extends `${infer _}?` ? string | undefined : string297+298+////////////////////////////////////////299+////// //////300+////// Utilities //////301+////// //////302+////////////////////////////////////////303+304+export type ExtractSchema<T> = T extends Hono<infer _, infer S> ? S : neverdeleted:deno_test/.vscode/settings.json-12 removed
1-{2- "eslint.validate": [3- "javascript",4- "javascriptreact",5- "typescript",6- "typescriptreact"7- ],8- "editor.codeActionsOnSave": {9- "source.fixAll.eslint": true10- },11- "deno.enable": true12-}deleted:deno_test/deps.ts-1 removed
1-export { assert, assertEquals, assertMatch } from 'https://deno.land/std@0.147.0/testing/asserts.ts'deleted:deno_test/favicon.icobinary
A binary file, deleted.
deleted:deno_test/hono.test.ts-25 removed
1-import { Context } from '../deno_dist/context.ts'2-import { Hono } from '../deno_dist/mod.ts'3-import { assertEquals } from './deps.ts'4-5-// Test just only minimal patterns.6-// Because others are tested well in Cloudflare Workers environment already.7-8-Deno.test('Hello World', async () => {9- const app = new Hono()10- app.get('/:foo', (c) => {11- c.header('x-param', c.req.param('foo'))12- c.header('x-query', c.req.query('q'))13- return c.text('Hello Deno!')14- })15- const res = await app.request('http://localhost/foo?q=bar')16- assertEquals(res.status, 200)17- assertEquals(await res.text(), 'Hello Deno!')18- assertEquals(res.headers.get('x-param'), 'foo')19- assertEquals(res.headers.get('x-query'), 'bar')20-})21-22-Deno.test('runtime', async () => {23- const c = new Context(new Request('http://localhost/'))24- assertEquals(c.runtime, 'deno')25-})deleted:deno_test/middleware.test.tsx-102 removed
1-/** @jsx jsx */2-/** @jsxFrag Fragment */3-import { basicAuth, jsx, Fragment, serveStatic, jwt } from '../deno_dist/middleware.ts'4-import { Hono } from '../deno_dist/mod.ts'5-import { assertEquals, assertMatch } from './deps.ts'6-7-// Test just only minimal patterns.8-// Because others are already tested well in Cloudflare Workers environment.9-10-Deno.test('Basic Auth Middleware', async () => {11- const app = new Hono()12-13- const username = 'hono-user-a'14- const password = 'hono-password-a'15-16- app.use(17- '/auth/*',18- basicAuth({19- username,20- password,21- })22- )23-24- app.get('/auth/*', () => new Response('auth'))25-26- const res = await app.request('http://localhost/auth/a')27- assertEquals(res.status, 401)28- assertEquals(await res.text(), 'Unauthorized')29-30- const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'31-32- const req = new Request('http://localhost/auth/a')33- req.headers.set('Authorization', `Basic ${credential}`)34- const resOK = await app.request(req)35- assertEquals(resOK.status, 200)36- assertEquals(await resOK.text(), 'auth')37-})38-39-Deno.test('JSX middleware', async () => {40- const app = new Hono()41- app.get('/', (c) => {42- return c.html(<h1>Hello</h1>)43- })44- const res = await app.request('http://localhost/')45- assertEquals(res.status, 200)46- assertEquals(res.headers.get('Content-Type'), 'text/html; charset=UTF-8')47- assertEquals(await res.text(), '<h1>Hello</h1>')48-49- // Fragment50- const template = (51- <>52- <p>1</p>53- <p>2</p>54- </>55- )56- assertEquals(template.toString(), '<p>1</p><p>2</p>')57-})58-59-Deno.test('Serve Static middleware', async () => {60- const app = new Hono()61- app.all('/favicon.ico', serveStatic({ path: './deno_test/favicon.ico' }))62- app.all('/favicon-notfound.ico', serveStatic({ path: './deno_test/favicon-notfound.ico' }))63- app.use('/favicon-notfound.ico', async (c, next) => {64- await next()65- c.header('X-Custom', 'Deno')66- })67- let res = await app.request('http://localhost/favicon.ico')68- assertEquals(res.status, 200)69- assertEquals(res.headers.get('Content-Type'), 'image/x-icon')70- res = await app.request('http://localhost/favicon-notfound.ico')71- assertEquals(res.status, 404)72- assertMatch(res.headers.get('Content-Type') || '', /^text\/plain/)73- assertEquals(res.headers.get('X-Custom'), 'Deno')74-})75-76-Deno.test('JWT Authentication middleware', async () => {77- const app = new Hono()78- app.use('/*', async (c, next) => {79- await next()80- c.header('x-foo', c.get('x-foo') || '')81- })82- app.use('/auth/*', jwt({ secret: 'a-secret' }))83- app.get('/auth/*', (c) => {84- c.set('x-foo', 'bar')85- return new Response('auth')86- })87-88- const req = new Request('http://localhost/auth/a')89- const res = await app.request(req)90- assertEquals(res.status, 401)91- assertEquals(await res.text(), 'Unauthorized')92- assertEquals(res.headers.get('x-foo'), '')93-94- const credential =95- 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'96- const reqOK = new Request('http://localhost/auth/a')97- reqOK.headers.set('Authorization', `Bearer ${credential}`)98- const resOK = await app.request(reqOK)99- assertEquals(resOK.status, 200)100- assertEquals(await resOK.text(), 'auth')101- assertEquals(resOK.headers.get('x-foo'), 'bar')102-})modified:docs/MIGRATION.md+66 added
1 # Migration Guide2 3+## v2.7.8 to v3.0.04+5+There are some breaking changes.6+In addition to the following, type mismatches may occur.7+8+### `c.req` is now `HonoRequest`9+10+`c.req` becomes `HonoRequest`, not `Request`.11+Although APIs are almost same, but if you want to access `Request`, use `c.req.raw`.12+13+```ts14+app.post('/', async (c) => {15+ const metadata = c.req.raw.cf?.hostMetadata?16+ ...17+})18+```19+20+### StaticRouter is obsolete21+22+You can't use `StaticRouter`.23+24+### Validator is changed25+26+Previous Validator Middleware is obsolete.27+You can still use `hono/validator`, but the API has been changed.28+See [the document](https://hono.dev).29+30+### `serveStatic` is provided from Adapter31+32+Serve Static Middleware is obsolete. Use Adapters instead.33+34+```ts35+// For Cloudflare Workers36+import { serveStatic } from 'hono/cloudflare-workers'37+38+// For Bun39+// import { serveStatic } from 'hono/bun'40+41+// For Deno42+// import { serveStatic } from 'npm:hono/deno'43+44+// ...45+46+app.get('/static/*', serveStatic({ root: './' }))47+```48+49+### `serveStatic` for Cloudflare Workers "Service Worker mode" is obsolete50+51+For Cloudflare Workers, the `serveStatic` is obsolete in Service Worker mode.52+53+Note: Service Worker mode is that using `app.fire()`.54+We recommend use "Module Worker" mode with `export default app`.55+56+### Use `type` to define the Generics for `new Hono`57+58+You must use `type` to define the Generics for `new Hono`. Do not use `interface`.59+60+```ts61+// Should use `type`62+type Bindings = {63+ TOKEN: string64+}65+66+const app = new Hono<{ Bindings: Bindings }>()67+```68+69 ## v2.7.1 - v2.x.x70 71 ### Current Validator Middleware is deprecated72 167 unmodified linesdeleted:lagon_test/index.test.ts-200 removed
1-describe('Example', () => {2- test('GET /', async () => {3- const res = await fetch('http://127.0.0.1:1234')4- expect(res.status).toBe(200)5- expect(await res.text()).toBe('Hono!!')6- expect(res.headers.get('x-powered-by')).toBe('Hono')7- expect(res.headers.get('x-response-time')).toContain('ms')8- })9-10- test('GET /hello/anything', async () => {11- const res = await fetch('http://127.0.0.1:1234/hello/anything')12- expect(res.status).toBe(404)13- expect(res.headers.get('x-message')).toBe('This is addHeader middleware!')14- })15-16- test('GET /hello', async () => {17- const res = await fetch('http://127.0.0.1:1234/hello')18- expect(res.status).toBe(200)19- expect(await res.text()).toBe('This is /hello')20- })21-22- test('GET /runtime', async () => {23- const res = await fetch('http://127.0.0.1:1234/runtime')24- expect(res.status).toBe(200)25- expect(await res.text()).toBe('lagon')26- })27-28- test('GET /entry/:id', async () => {29- const res = await fetch('http://127.0.0.1:1234/entry/42')30- expect(res.status).toBe(200)31- expect(await res.text()).toBe('Your ID is 42')32- })33-34- describe('/book', () => {35- test('GET /book', async () => {36- const res = await fetch('http://127.0.0.1:1234/book')37- expect(res.status).toBe(200)38- expect(await res.text()).toBe('List Books')39- })40-41- test('GET /book/:id', async () => {42- const res = await fetch('http://127.0.0.1:1234/book/3')43- expect(res.status).toBe(200)44- expect(await res.text()).toBe('Get Book: 3')45- })46-47- test('POST /book', async () => {48- const res = await fetch('http://127.0.0.1:1234/book', {49- method: 'POST',50- })51- expect(res.status).toBe(200)52- expect(await res.text()).toBe('Create Book')53- })54- })55-56- test('GET /redirect', async () => {57- const res = await fetch('http://127.0.0.1:1234/redirect', {58- redirect: 'manual',59- })60- expect(res.status).toBe(302)61- expect(res.headers.get('location')).toBe('/')62- })63-64- describe('/basic-auth', () => {65- test('GET /basic-auth/anyroute unauthorized', async () => {66- const res = await fetch('http://127.0.0.1:1234/basic-auth/anyroute')67- expect(res.status).toBe(401)68- expect(await res.text()).toBe('Unauthorized')69- })70-71- test('GET /basic-auth/anyroute', async () => {72- const res = await fetch('http://127.0.0.1:1234/basic-auth/anyroute', {73- headers: {74- authorization: `Basic ${btoa('hono:acoolproject')}`,75- },76- })77- expect(res.status).toBe(200)78- expect(await res.text()).toBe('You are authorized')79- })80- })81-82- describe('/bearer-auth', () => {83- test('GET /bearer-auth/anyroute unauthorized', async () => {84- const res = await fetch('http://127.0.0.1:1234/bearer-auth/anyroute')85- expect(res.status).toBe(401)86- expect(await res.text()).toBe('Unauthorized')87- })88-89- test('GET /bearer-auth/anyroute', async () => {90- const res = await fetch('http://127.0.0.1:1234/bearer-auth/anyroute', {91- headers: {92- authorization: 'Bearer secrettoken',93- },94- })95- expect(res.status).toBe(200)96- expect(await res.text()).toBe('You are authorized')97- })98- })99-100- test('GET /etag/cached', async () => {101- const res = await fetch('http://127.0.0.1:1234/etag/cached')102- expect(res.status).toBe(200)103- expect(res.headers.get('etag')).toBe('"90ea638841fff3c326fc22cbd156f1146ac0ac02"')104- expect(await res.text()).toBe('Is this cached?')105- })106-107- test('GET /fetch-url', async () => {108- const res = await fetch('http://127.0.0.1:1234/fetch-url')109- expect(res.status).toBe(200)110- expect(await res.text()).toBe('https://example.com/ is 200')111- })112-113- test('GET /user-agent', async () => {114- const res = await fetch('http://127.0.0.1:1234/user-agent', {115- headers: {116- 'user-agent': 'Lagon',117- },118- })119- expect(res.status).toBe(200)120- expect(await res.text()).toBe('Your UserAgent is Lagon')121- })122-123- test('GET /api/posts', async () => {124- const res = await fetch('http://127.0.0.1:1234/api/posts')125- expect(res.status).toBe(200)126- expect(await res.json()).toEqual([127- { id: 1, title: 'Good Morning' },128- { id: 2, title: 'Good Aternoon' },129- { id: 3, title: 'Good Evening' },130- { id: 4, title: 'Good Night' },131- ])132- })133-134- test('POST /api/posts', async () => {135- const res = await fetch('http://127.0.0.1:1234/api/posts', {136- method: 'POST',137- })138- expect(res.status).toBe(201)139- expect(await res.json()).toEqual({ message: 'Created!' })140- })141-142- test('GET /api/default-route', async () => {143- const res = await fetch('http://127.0.0.1:1234/api/default-route')144- expect(res.status).toBe(404)145- expect(await res.text()).toBe('API endpoint is not found')146- })147-148- describe('/form', () => {149- test('POST /form x-www-form-urlencoded', async () => {150- const res = await fetch('http://127.0.0.1:1234/form', {151- method: 'POST',152- headers: {153- 'content-type': 'application/x-www-form-urlencoded',154- },155- body: 'username=john&password=Pa%24%24w0rd',156- })157- expect(res.status).toBe(200)158- expect(await res.json()).toEqual({159- password: 'Pa$$w0rd',160- username: 'john',161- })162- })163-164- test('POST /form', async () => {165- const res = await fetch('http://127.0.0.1:1234/form', {166- method: 'POST',167- headers: {168- 'content-type':169- 'multipart/form-data; boundary=---------------------------9051914041544843365972754266',170- },171- body: `-----------------------------9051914041544843365972754266172-Content-Disposition: form-data; name="hello"173-174-world!175------------------------------9051914041544843365972754266176-Content-Disposition: form-data; name="description"177-178-this is another field179------------------------------9051914041544843365972754266--`,180- })181- expect(res.status).toBe(200)182- expect(await res.json()).toEqual({183- description: 'this is another field',184- hello: 'world!',185- })186- })187- })188-189- test('GET /error', async () => {190- const res = await fetch('http://127.0.0.1:1234/error')191- expect(res.status).toBe(500)192- expect(await res.text()).toBe('Custom Error Message')193- })194-195- test('GET /api/default-route', async () => {196- const res = await fetch('http://127.0.0.1:1234/api/default-route')197- expect(res.status).toBe(404)198- expect(await res.text()).toBe('API endpoint is not found')199- })200-})deleted:lagon_test/index.ts-124 removed
1-import { Hono } from '../src'2-import { basicAuth } from '../src/middleware/basic-auth'3-import { bearerAuth } from '../src/middleware/bearer-auth'4-import { etag } from '../src/middleware/etag'5-import { poweredBy } from '../src/middleware/powered-by'6-import { prettyJSON } from '../src/middleware/pretty-json'7-8-const app = new Hono()9-10-// Mount Builtin Middleware11-app.use('*', poweredBy())12-// app.use('*', logger())13-app.use(14- '/basic-auth/*',15- basicAuth({16- username: 'hono',17- password: 'acoolproject',18- })19-)20-app.use(21- '/bearer-auth/*',22- bearerAuth({23- token: 'secrettoken',24- })25-)26-app.use('/etag/*', etag())27-28-// Custom Middleware29-// Add Custom Header30-app.use('/hello/*', async (c, next) => {31- await next()32- c.header('X-message', 'This is addHeader middleware!')33-})34-35-// Add X-Response-Time header36-app.use('*', async (c, next) => {37- const start = Date.now()38- await next()39- const ms = Date.now() - start40- c.header('X-Response-Time', `${ms}ms`)41-})42-43-// Custom Not Found Message44-app.notFound((c) => {45- return c.text('Custom 404 Not Found', 404)46-})47-48-// Error handling49-app.onError((err, c) => {50- console.error(`${err}`)51- return c.text('Custom Error Message', 500)52-})53-54-app.head('/', (c) => c.text('OK'))55-56-// Routing57-app.get('/', (c) => c.text('Hono!!'))58-// Use Response object directly59-app.get('/hello', () => new Response('This is /hello'))60-61-app.get('/runtime', (c) => new Response(c.runtime))62-63-// Named parameter64-app.get('/entry/:id', (c) => {65- const id = c.req.param('id')66- return c.text(`Your ID is ${id}`)67-})68-69-// Nested route70-const book = new Hono()71-book.get('/', (c) => c.text('List Books'))72-book.get('/:id', (c) => {73- const id = c.req.param('id')74- return c.text('Get Book: ' + id)75-})76-book.post('/', (c) => c.text('Create Book'))77-app.route('/book', book)78-79-// Redirect80-app.get('/redirect', (c) => c.redirect('/'))81-// Authentication required82-app.get('/basic-auth/*', (c) => c.text('You are authorized'))83-app.get('/bearer-auth/*', (c) => c.text('You are authorized'))84-// ETag85-app.get('/etag/cached', (c) => c.text('Is this cached?'))86-87-// Async88-app.get('/fetch-url', async (c) => {89- const response = await fetch('https://example.com/')90- return c.text(`https://example.com/ is ${response.status}`)91-})92-93-// Request headers94-app.get('/user-agent', (c) => {95- const userAgent = c.req.header('User-Agent')96- return c.text(`Your UserAgent is ${userAgent}`)97-})98-99-// JSON100-app.get('/api/posts', prettyJSON(), (c) => {101- const posts = [102- { id: 1, title: 'Good Morning' },103- { id: 2, title: 'Good Aternoon' },104- { id: 3, title: 'Good Evening' },105- { id: 4, title: 'Good Night' },106- ]107- return c.json(posts)108-})109-// status code110-app.post('/api/posts', (c) => c.json({ message: 'Created!' }, 201))111-// default route112-app.get('/api/*', (c) => c.text('API endpoint is not found', 404))113-114-app.post('/form', async (c) => {115- const body = await c.req.parseBody()116- return c.json(body)117-})118-119-// Throw Error120-app.get('/error', () => {121- throw Error('Error has occurred')122-})123-124-export const handler = app.fetchadded:src/adapter/bun/index.ts+2 added
1+// @denoify-ignore2+export { serveStatic } from './serve-static'added:src/adapter/bun/serve-static.ts+51 added
1+// @denoify-ignore2+/* eslint-disable @typescript-eslint/ban-ts-comment */3+import { existsSync } from 'fs'4+import type { Context } from '../../context'5+import type { Next } from '../../types'6+import { getFilePath } from '../../utils/filepath'7+import { getMimeType } from '../../utils/mime'8+9+// @ts-ignore10+const { file } = Bun11+12+export type ServeStaticOptions = {13+ root?: string14+ path?: string15+}16+17+const DEFAULT_DOCUMENT = 'index.html'18+19+export const serveStatic = (options: ServeStaticOptions = { root: '' }) => {20+ return async (c: Context, next: Next) => {21+ // Do nothing if Response is already set22+ if (c.finalized) {23+ await next()24+ return25+ }26+ const url = new URL(c.req.url)27+28+ let path = getFilePath({29+ filename: options.path ?? decodeURI(url.pathname),30+ root: options.root,31+ defaultDocument: DEFAULT_DOCUMENT,32+ })33+ path = `./${path}`34+35+ if (existsSync(path)) {36+ const content = file(path)37+ if (content) {38+ const mimeType = getMimeType(path)39+ if (mimeType) {40+ c.header('Content-Type', mimeType)41+ }42+ // Return Response object43+ return c.body(content)44+ }45+ }46+47+ console.warn(`Static file: ${path} is not found`)48+ await next()49+ return50+ }51+}added:src/adapter/cloudflare-pages/handler.test.ts+41 added
1+import { Hono } from '../../hono'2+import { handle } from './handler'3+4+type Env = {5+ Bindings: {6+ TOKEN: string7+ }8+}9+10+describe('Adapter for Cloudflare Pages', () => {11+ it('Should return 200 response', async () => {12+ const request = new Request('http://localhost/api/foo')13+ const env = {14+ TOKEN: 'HONOISCOOL',15+ }16+ const app = new Hono<Env>()17+ app.get('/api/foo', (c) => {18+ return c.text(c.env.TOKEN)19+ })20+ const handler = handle(app)21+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment22+ // @ts-ignore23+ const res = await handler({ request, env })24+ expect(res.status).toBe(200)25+ expect(await res.text()).toBe('HONOISCOOL')26+ })27+28+ it('Should return 200 response with path', async () => {29+ const request = new Request('http://localhost/api/foo')30+ const app = new Hono()31+ app.get('/foo', (c) => {32+ return c.text('/api/foo')33+ })34+ const handler = handle(app, '/api')35+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment36+ // @ts-ignore37+ const res = await handler({ request })38+ expect(res.status).toBe(200)39+ expect(await res.text()).toBe('/api/foo')40+ })41+})added:src/adapter/cloudflare-pages/handler.ts+22 added
1+// @denoify-ignore2+import { Hono } from '../../hono'3+import type { Env } from '../../types'4+5+type EventContext = {6+ request: Request7+ waitUntil: (promise: Promise<unknown>) => void8+ env: {} & { ASSETS: { fetch: typeof fetch } }9+}10+11+interface HandleInterface {12+ <E extends Env>(app: Hono<E>, path?: string): (13+ eventContext: EventContext14+ ) => Response | Promise<Response>15+}16+17+export const handle: HandleInterface =18+ <E extends Env>(subApp: Hono<E>, path: string = '/') =>19+ ({ request, env, waitUntil }) =>20+ new Hono()21+ .route(path, subApp)22+ .fetch(request, env, { waitUntil, passThroughOnException: () => {} })added:src/adapter/cloudflare-pages/index.ts+2 added
1+// @denoify-ignore2+export { handle } from './handler'added:src/adapter/cloudflare-workers/index.ts+2 added
1+// @denoify-ignore2+export { serveStatic } from './server-static-module'added:src/adapter/cloudflare-workers/serve-static.test.ts+135 added
1+import type { Context } from '../../context'2+import { Hono } from '../../hono'3+import type { Next } from '../../types'4+import { serveStatic } from './serve-static'5+6+// Mock7+const store: Record<string, string> = {8+ 'assets/static/plain.abcdef.txt': 'This is plain.txt',9+ 'assets/static/hono.abcdef.html': '<h1>Hono!</h1>',10+ 'assets/static/top/index.abcdef.html': '<h1>Top</h1>',11+ 'static-no-root/plain.abcdef.txt': 'That is plain.txt',12+ 'assets/static/options/foo.abcdef.txt': 'With options',13+}14+const manifest = JSON.stringify({15+ 'assets/static/plain.txt': 'assets/static/plain.abcdef.txt',16+ 'assets/static/hono.html': 'assets/static/hono.abcdef.html',17+ 'assets/static/top/index.html': 'assets/static/top/index.abcdef.html',18+ 'static-no-root/plain.txt': 'static-no-root/plain.abcdef.txt',19+})20+21+Object.assign(global, { __STATIC_CONTENT_MANIFEST: manifest })22+Object.assign(global, {23+ __STATIC_CONTENT: {24+ get: (path: string) => {25+ return store[path]26+ },27+ },28+})29+30+describe('ServeStatic Middleware', () => {31+ const app = new Hono()32+ app.use('/static/*', serveStatic({ root: './assets' }))33+ app.use('/static-no-root/*', serveStatic())34+35+ it('Should return plain.txt', async () => {36+ const res = await app.request('http://localhost/static/plain.txt')37+ expect(res.status).toBe(200)38+ expect(await res.text()).toBe('This is plain.txt')39+ expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8')40+ })41+42+ it('Should return hono.html', async () => {43+ const res = await app.request('http://localhost/static/hono.html')44+ expect(res.status).toBe(200)45+ expect(await res.text()).toBe('<h1>Hono!</h1>')46+ expect(res.headers.get('Content-Type')).toBe('text/html; charset=utf-8')47+ })48+49+ it('Should return 404 response', async () => {50+ const res = await app.request('http://localhost/static/not-found.html')51+ expect(res.status).toBe(404)52+ })53+54+ it('Should return plan.txt', async () => {55+ const res = await app.request('http://localhost/static-no-root/plain.txt')56+ expect(res.status).toBe(200)57+ expect(await res.text()).toBe('That is plain.txt')58+ expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8')59+ })60+61+ it('Should return index.html', async () => {62+ const res = await app.request('http://localhost/static/top')63+ expect(res.status).toBe(200)64+ expect(await res.text()).toBe('<h1>Top</h1>')65+ expect(res.headers.get('Content-Type')).toBe('text/html; charset=utf-8')66+ })67+})68+69+describe('With options', () => {70+ const manifest = {71+ 'assets/static/options/foo.txt': 'assets/static/options/foo.abcdef.txt',72+ }73+74+ const app = new Hono()75+ app.use('/static/*', serveStatic({ root: './assets', manifest: manifest }))76+77+ it('Should return foo.txt', async () => {78+ const res = await app.request('http://localhost/static/options/foo.txt')79+ expect(res.status).toBe(200)80+ expect(await res.text()).toBe('With options')81+ expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8')82+ })83+})84+85+describe('With `file` options', () => {86+ const app = new Hono()87+ app.get('/foo/*', serveStatic({ path: './assets/static/hono.html' }))88+ app.get('/bar/*', serveStatic({ path: './static/hono.html', root: './assets' }))89+90+ it('Should return hono.html', async () => {91+ const res = await app.request('http://localhost/foo/fallback')92+ expect(res.status).toBe(200)93+ expect(await res.text()).toBe('<h1>Hono!</h1>')94+ })95+96+ it('Should return hono.html - with `root` option', async () => {97+ const res = await app.request('http://localhost/bar/fallback')98+ expect(res.status).toBe(200)99+ expect(await res.text()).toBe('<h1>Hono!</h1>')100+ })101+})102+103+describe('With middleware', () => {104+ const app = new Hono()105+ const md1 = async (c: Context, next: Next) => {106+ await next()107+ c.res.headers.append('x-foo', 'bar')108+ }109+ const md2 = async (c: Context, next: Next) => {110+ await next()111+ c.res.headers.append('x-foo2', 'bar2')112+ }113+114+ app.use('/static/*', md1)115+ app.use('/static/*', md2)116+ app.use('/static/*', serveStatic({ root: './assets' }))117+ app.get('/static/foo', (c) => {118+ return c.text('bar')119+ })120+121+ it('Should return plain.txt with correct headers', async () => {122+ const res = await app.request('http://localhost/static/plain.txt')123+ expect(res.status).toBe(200)124+ expect(await res.text()).toBe('This is plain.txt')125+ expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8')126+ expect(res.headers.get('x-foo')).toBe('bar')127+ expect(res.headers.get('x-foo2')).toBe('bar2')128+ })129+130+ it('Should return 200 Response', async () => {131+ const res = await app.request('http://localhost/static/foo')132+ expect(res.status).toBe(200)133+ expect(await res.text()).toBe('bar')134+ })135+})added:src/adapter/cloudflare-workers/serve-static.ts+53 added
1+// @denoify-ignore2+import type { KVNamespace } from '@cloudflare/workers-types'3+import type { MiddlewareHandler } from '../../types'4+import { getContentFromKVAsset } from '../../utils/cloudflare'5+import { getFilePath } from '../../utils/filepath'6+import { getMimeType } from '../../utils/mime'7+8+export type ServeStaticOptions = {9+ root?: string10+ path?: string11+ manifest?: object | string12+ namespace?: KVNamespace13+}14+15+const DEFAULT_DOCUMENT = 'index.html'16+17+// This middleware is available only on Cloudflare Workers.18+export const serveStatic = (options: ServeStaticOptions = { root: '' }): MiddlewareHandler => {19+ return async (c, next) => {20+ // Do nothing if Response is already set21+ if (c.finalized) {22+ await next()23+ return24+ }25+26+ const url = new URL(c.req.url)27+28+ const path = getFilePath({29+ filename: options.path ?? decodeURI(url.pathname),30+ root: options.root,31+ defaultDocument: DEFAULT_DOCUMENT,32+ })33+34+ const content = await getContentFromKVAsset(path, {35+ manifest: options.manifest,36+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment37+ // @ts-ignore38+ namespace: options.namespace ? options.namespace : c.env ? c.env.__STATIC_CONTENT : undefined,39+ })40+ if (content) {41+ const mimeType = getMimeType(path)42+ if (mimeType) {43+ c.header('Content-Type', mimeType)44+ }45+ // Return Response object46+ return c.body(content)47+ } else {48+ console.warn(`Static file: ${path} is not found`)49+ await next()50+ }51+ return52+ }53+}added:src/adapter/cloudflare-workers/server-static-module.ts+17 added
1+// @denoify-ignore2+// eslint-disable-next-line @typescript-eslint/ban-ts-comment3+// @ts-ignore4+// For ES module mode5+import manifest from '__STATIC_CONTENT_MANIFEST'6+import type { ServeStaticOptions } from './serve-static'7+import { serveStatic } from './serve-static'8+9+const module = (options: ServeStaticOptions = { root: '' }) => {10+ return serveStatic({11+ root: options.root,12+ path: options.path,13+ manifest: options.manifest ? options.manifest : manifest,14+ })15+}16+17+export { module as serveStatic }added:src/adapter/deno/index.ts+1 added
1+export { serveStatic } from './serve-static'added:src/adapter/deno/serve-static.ts+52 added
1+import type { Context } from '../../context'2+import type { Next } from '../../types'3+import { getFilePath } from '../../utils/filepath'4+import { getMimeType } from '../../utils/mime'5+6+export type ServeStaticOptions = {7+ root?: string8+ path?: string9+}10+11+const DEFAULT_DOCUMENT = 'index.html'12+13+export const serveStatic = (options: ServeStaticOptions = { root: '' }) => {14+ return async (c: Context, next: Next) => {15+ // Do nothing if Response is already set16+ if (c.finalized) {17+ await next()18+ return19+ }20+21+ const url = new URL(c.req.url)22+23+ let path = getFilePath({24+ filename: options.path ?? decodeURI(url.pathname),25+ root: options.root,26+ defaultDocument: DEFAULT_DOCUMENT,27+ })28+29+ path = `./${path}`30+31+ let content32+33+ try {34+ content = await Deno.readFile(path)35+ } catch (e) {36+ console.warn(`${e}`)37+ }38+39+ if (content) {40+ const mimeType = getMimeType(path)41+ if (mimeType) {42+ c.header('Content-Type', mimeType)43+ }44+ // Return Response object45+ return c.body(content)46+ } else {47+ console.warn(`Static file: ${path} is not found`)48+ await next()49+ }50+ return51+ }52+}added:src/adapter/nextjs/handler.test.ts+28 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 return 200 response with path', async () => {18+ const app = new Hono()19+ app.get('/foo', (c) => {20+ return c.text('/api/foo')21+ })22+ const handler = handle(app, '/api')23+ const req = new Request('http://localhost/api/foo')24+ const res = await handler(req)25+ expect(res.status).toBe(200)26+ expect(await res.text()).toBe('/api/foo')27+ })28+})added:src/adapter/nextjs/handler.ts+12 added
1+// @denoify-ignore2+import { Hono } from '../../hono'3+import type { Env } from '../../types'4+5+interface HandleInterface {6+ <E extends Env>(subApp: Hono<E>, path?: string): (req: Request) => Promise<Response>7+}8+9+export const handle: HandleInterface =10+ <E extends Env>(subApp: Hono<E>, path: string = '/') =>11+ async (req) =>12+ new Hono().route(path, subApp).fetch(req)added:src/adapter/nextjs/index.ts+2 added
1+// @denoify-ignore2+export { handle } from './handler'added:src/client/client.test.ts+270 added
1+/* eslint-disable @typescript-eslint/no-unused-vars */2+/* eslint-disable @typescript-eslint/ban-ts-comment */3+import FormData from 'form-data'4+import { rest } from 'msw'5+import { setupServer } from 'msw/node'6+import _fetch, { Request as NodeFetchRequest } from 'node-fetch'7+import { Hono } from '../hono'8+import type { Equal, Expect } from '../utils/types'9+import { validator } from '../validator'10+import { hc } from './client'11+import type { InferRequestType, InferResponseType } from './types'12+13+// @ts-ignore14+global.fetch = _fetch15+// @ts-ignore16+global.Request = NodeFetchRequest17+// @ts-ignore18+global.FormData = FormData19+20+describe('Basic - JSON', () => {21+ const app = new Hono()22+23+ const route = app24+ .post(25+ '/posts',26+ validator('json', () => {27+ return {} as {28+ id: number29+ title: string30+ }31+ }),32+ (c) => {33+ return c.jsonT({34+ success: true,35+ message: 'dummy',36+ requestContentType: 'dummy',37+ requestMessage: 'dummy',38+ requestBody: {39+ id: 123,40+ title: 'dummy',41+ },42+ })43+ }44+ )45+ .get('/hello-not-found', (c) => c.notFound())46+47+ type AppType = typeof route48+49+ const server = setupServer(50+ rest.post('http://localhost/posts', async (req, res, ctx) => {51+ const requestContentType = req.headers.get('content-type')52+ const requestMessage = req.headers.get('x-message')53+ const requestBody = await req.json()54+ const payload = {55+ message: 'Hello!',56+ success: true,57+ requestContentType,58+ requestMessage,59+ requestBody,60+ }61+ return res(ctx.status(200), ctx.json(payload))62+ }),63+ rest.get('http://localhost/hello-not-found', (_req, res, ctx) => {64+ return res(ctx.status(404))65+ })66+ )67+68+ beforeAll(() => server.listen())69+ afterEach(() => server.resetHandlers())70+ afterAll(() => server.close())71+72+ const payload = {73+ id: 123,74+ title: 'Hello! Hono!',75+ }76+77+ const client = hc<AppType>('http://localhost')78+79+ it('Should get 200 response', async () => {80+ const res = await client.posts.$post(81+ {82+ json: payload,83+ },84+ {85+ headers: {86+ 'x-message': 'foobar',87+ },88+ }89+ )90+91+ expect(res.ok).toBe(true)92+ const data = await res.json()93+ expect(data.success).toBe(true)94+ expect(data.message).toBe('Hello!')95+ expect(data.requestContentType).toBe('application/json')96+ expect(data.requestMessage).toBe('foobar')97+ expect(data.requestBody).toEqual(payload)98+ })99+100+ it('Should get 404 response', async () => {101+ const res = await client['hello-not-found'].$get()102+ expect(res.status).toBe(404)103+ })104+})105+106+describe('Basic - query, queries, form, and path params', () => {107+ const app = new Hono()108+109+ const route = app110+ .get(111+ '/search',112+ validator('query', () => {113+ return {} as { q: string }114+ }),115+ (c) => {116+ return c.jsonT({117+ entries: [118+ {119+ title: 'Foo',120+ },121+ ],122+ })123+ }124+ )125+ .get(126+ '/posts',127+ validator('queries', () => {128+ return {129+ tags: ['a', 'b'],130+ }131+ }),132+ (c) => {133+ const data = c.req.valid('queries')134+ return c.jsonT(data)135+ }136+ )137+ .put(138+ '/posts/:id',139+ validator('form', () => {140+ return {141+ title: 'Hello',142+ }143+ }),144+ (c) => {145+ const data = c.req.valid('form')146+ return c.jsonT(data)147+ }148+ )149+150+ const server = setupServer(151+ rest.get('http://localhost/api/search', (req, res, ctx) => {152+ const url = new URL(req.url)153+ const query = url.searchParams.get('q')154+ return res(155+ ctx.status(200),156+ ctx.json({157+ q: query,158+ })159+ )160+ }),161+ rest.get('http://localhost/api/posts', (req, res, ctx) => {162+ const url = new URL(req.url)163+ const tags = url.searchParams.getAll('tags')164+ return res(165+ ctx.status(200),166+ ctx.json({167+ tags: tags,168+ })169+ )170+ }),171+ rest.put('http://localhost/api/posts/123', async (req, res, ctx) => {172+ const buffer = await req.arrayBuffer()173+ // @ts-ignore174+ const string = String.fromCharCode.apply('', new Uint8Array(buffer))175+ return res(ctx.status(200), ctx.text(string))176+ })177+ )178+179+ beforeAll(() => server.listen())180+ afterEach(() => server.resetHandlers())181+ afterAll(() => server.close())182+183+ type AppType = typeof route184+185+ const client = hc<AppType>('http://localhost/api')186+187+ it('Should get 200 response - query', async () => {188+ const res = await client.search.$get({189+ query: {190+ q: 'foobar',191+ },192+ })193+194+ expect(res.status).toBe(200)195+ expect(await res.json()).toEqual({196+ q: 'foobar',197+ })198+ })199+200+ it('Should get 200 response - queries', async () => {201+ const res = await client.posts.$get({202+ queries: {203+ tags: ['A', 'B', 'C'],204+ },205+ })206+207+ expect(res.status).toBe(200)208+ expect(await res.json()).toEqual({209+ tags: ['A', 'B', 'C'],210+ })211+ })212+213+ it('Should get 200 response - form, params', async () => {214+ const res = await client.posts[':id'].$put({215+ form: {216+ title: 'Good Night',217+ },218+ param: {219+ id: '123',220+ },221+ })222+223+ expect(res.status).toBe(200)224+ expect(await res.text()).toMatch('Good Night')225+ })226+})227+228+describe('Infer the request type', () => {229+ const app = new Hono()230+ const route = app.get(231+ '/',232+ validator('query', () => {233+ return {234+ name: 'dummy',235+ age: 'dummy',236+ }237+ }),238+ (c) =>239+ c.jsonT({240+ id: 123,241+ title: 'Morning!',242+ })243+ )244+245+ type AppType = typeof route246+247+ it('Should infer response type the type correctly', () => {248+ const client = hc<AppType>('/')249+ const req = client.index.$get250+251+ type Actual = InferResponseType<typeof req>252+ type Expected = {253+ id: number254+ title: string255+ }256+ type verify = Expect<Equal<Expected, Actual>>257+ })258+259+ it('Should infer request type the type correctly', () => {260+ const client = hc<AppType>('/')261+ const req = client.index.$get262+263+ type Actual = InferRequestType<typeof req>264+ type Expected = {265+ age: string266+ name: string267+ }268+ type verify = Expect<Equal<Expected, Actual['query']>>269+ })270+})added:src/client/client.ts+122 added
1+import type { Hono } from '../hono'2+import type { ValidationTargets } from '../types'3+import type { UnionToIntersection } from '../utils/types'4+import type { Callback, Client, RequestOption } from './types'5+import { replaceUrlParam, mergePath, removeIndexString } from './utils'6+7+const createProxy = (callback: Callback, path: string[]) => {8+ const proxy: unknown = new Proxy(() => {}, {9+ get(_obj, key) {10+ if (typeof key !== 'string') return undefined11+ return createProxy(callback, [...path, key])12+ },13+ apply(_1, _2, args) {14+ return callback({15+ path,16+ args,17+ })18+ },19+ })20+ return proxy21+}22+23+class ClientRequestImpl {24+ private url: string25+ private method: string26+ private queryParams: URLSearchParams | undefined = undefined27+ private pathParams: Record<string, string> = {}28+ private rBody: BodyInit | undefined29+ private cType: string | undefined = undefined30+31+ constructor(url: string, method: string) {32+ this.url = url33+ this.method = method34+ }35+ fetch = (36+ args?: ValidationTargets & {37+ param?: Record<string, string>38+ },39+ opt?: RequestOption40+ ) => {41+ if (args) {42+ if (args.query) {43+ for (const [k, v] of Object.entries(args.query)) {44+ this.queryParams ||= new URLSearchParams()45+ this.queryParams.set(k, v)46+ }47+ }48+49+ if (args.queries) {50+ for (const [k, v] of Object.entries(args.queries)) {51+ for (const v2 of v) {52+ this.queryParams ||= new URLSearchParams()53+ this.queryParams.append(k, v2)54+ }55+ }56+ }57+58+ if (args.form) {59+ const form = new FormData()60+ for (const [k, v] of Object.entries(args.form)) {61+ form.append(k, v)62+ }63+ this.rBody = form64+ }65+66+ if (args.json) {67+ this.rBody = JSON.stringify(args.json)68+ this.cType = 'application/json'69+ }70+71+ if (args.param) {72+ this.pathParams = args.param73+ }74+ }75+76+ let methodUpperCase = this.method.toUpperCase()77+ let setBody = !(methodUpperCase === 'GET' || methodUpperCase === 'HEAD')78+79+ const headerValues: Record<string, string> = opt?.headers ? opt.headers : {}80+ if (this.cType) headerValues['Content-Type'] = this.cType81+82+ const headers = new Headers(headerValues ?? undefined)83+ let url = this.url84+85+ url = removeIndexString(url)86+ url = replaceUrlParam(url, this.pathParams)87+88+ if (this.queryParams) {89+ url = url + '?' + this.queryParams.toString()90+ }91+ methodUpperCase = this.method.toUpperCase()92+ setBody = !(methodUpperCase === 'GET' || methodUpperCase === 'HEAD')93+94+ // Pass URL string to 1st arg for testing with MSW and node-fetch95+ return fetch(url, {96+ body: setBody ? this.rBody : undefined,97+ method: methodUpperCase,98+ headers: headers,99+ })100+ }101+}102+103+export const hc = <T extends Hono>(baseUrl: string) =>104+ createProxy(async (opts) => {105+ const parts = [...opts.path]106+107+ let method = ''108+ if (/^\$/.test(parts[parts.length - 1])) {109+ const last = parts.pop()110+ if (last) {111+ method = last.replace(/^\$/, '')112+ }113+ }114+115+ const path = parts.join('/')116+ const url = mergePath(baseUrl, path)117+ const req = new ClientRequestImpl(url, method)118+ if (method) {119+ return req.fetch(opts.args[0], opts.args[1])120+ }121+ return req122+ }, []) as UnionToIntersection<Client<T>>added:src/client/index.ts+2 added
1+export { hc } from './client'2+export type { InferResponseType, InferRequestType, Fetch } from './types'added:src/client/types.ts+67 added
1+import type { Hono } from '../hono'2+import type { ValidationTargets, Env } from '../types'3+4+type MethodName = `$${string}`5+6+type Endpoint = Record<MethodName, Data>7+8+type Data = {9+ input: Partial<ValidationTargets> & {10+ param?: Record<string, string>11+ }12+ output: {}13+}14+15+export type RequestOption = {16+ headers?: Record<string, string>17+}18+19+type ClientRequest<S extends Data> = {20+ [M in keyof S]: S[M] extends { input: infer R; output: infer O }21+ ? (args?: R, options?: RequestOption) => Promise<ClientResponse<O>>22+ : never23+}24+25+export interface ClientResponse<T> extends Response {26+ json(): Promise<T>27+}28+29+export type Fetch<T> = (30+ args?: InferRequestType<T>,31+ opt?: RequestOption32+) => Promise<ClientResponse<InferResponseType<T>>>33+34+export type InferResponseType<T> = T extends () => Promise<ClientResponse<infer O>> ? O : never35+export type InferRequestType<T> = T extends (args: infer R) => Promise<ClientResponse<unknown>>36+ ? NonNullable<R>37+ : never38+39+type PathToChain<40+ Path extends string,41+ E extends Endpoint,42+ Original extends string = ''43+> = Path extends `/${infer P}`44+ ? PathToChain<P, E, Path>45+ : Path extends `${infer P}/${infer R}`46+ ? { [K in P]: PathToChain<R, E, Original> }47+ : {48+ [K in Path extends '' ? 'index' : Path]: ClientRequest<49+ E extends Record<string, unknown> ? E[Original] : never50+ >51+ }52+53+export type Client<T> = T extends Hono<Env, infer S>54+ ? S extends Record<infer K, Endpoint>55+ ? K extends string56+ ? PathToChain<K, S>57+ : never58+ : never59+ : never60+61+export type Callback = (opts: CallbackOptions) => unknown62+63+interface CallbackOptions {64+ path: string[]65+ // eslint-disable-next-line @typescript-eslint/no-explicit-any66+ args: any[]67+}added:src/client/utils.test.ts+35 added
1+import { mergePath, removeIndexString, replaceUrlParam } from './utils'2+3+describe('mergePath', () => {4+ it('Should merge paths correctly', () => {5+ expect(mergePath('http://localhost', '/api')).toBe('http://localhost/api')6+ expect(mergePath('http://localhost/', '/api')).toBe('http://localhost/api')7+ expect(mergePath('http://localhost', 'api')).toBe('http://localhost/api')8+ expect(mergePath('http://localhost/', 'api')).toBe('http://localhost/api')9+ expect(mergePath('http://localhost/', '/')).toBe('http://localhost/')10+ })11+})12+13+describe('replaceUrlParams', () => {14+ it('Should replace correctly', () => {15+ const url = 'http://localhost/posts/:postId/comments/:commentId'16+ const params = {17+ postId: '123',18+ commentId: '456',19+ }20+ const replacedUrl = replaceUrlParam(url, params)21+ expect(replacedUrl).toBe('http://localhost/posts/123/comments/456')22+ })23+})24+25+describe('removeIndexString', () => {26+ it('Should remove last `index` string', () => {27+ let url = 'http://localhost/index'28+ let newUrl = removeIndexString(url)29+ expect(newUrl).toBe('http://localhost/')30+31+ url = '/index'32+ newUrl = removeIndexString(url)33+ expect(newUrl).toBe('/')34+ })35+})added:src/client/utils.ts+25 added
1+import { getPathFromURL } from '../utils/url'2+3+export const mergePath = (base: string, path: string) => {4+ base = base.replace(/\/+$/, '')5+ base = base + '/'6+ path = path.replace(/^\/+/, '')7+ return base + path8+}9+10+export const replaceUrlParam = (urlString: string, params: Record<string, string>) => {11+ for (const [k, v] of Object.entries(params)) {12+ const reg = new RegExp('/:' + k)13+ urlString = urlString.replace(reg, `/${v}`)14+ }15+ return urlString16+}17+18+export const removeIndexString = (urlSting: string) => {19+ // eslint-disable-next-line @typescript-eslint/no-unused-vars20+ const path = getPathFromURL(urlSting)21+ if (path === '/index') {22+ return urlSting.replace(/index$/, '')23+ }24+ return urlSting25+}deleted:src/deno/serve-static.ts-52 removed
1-import type { Context } from '../context'2-import type { Next } from '../types'3-import { getFilePath } from '../utils/filepath'4-import { getMimeType } from '../utils/mime'5-6-export type ServeStaticOptions = {7- root?: string8- path?: string9-}10-11-const DEFAULT_DOCUMENT = 'index.html'12-13-export const serveStatic = (options: ServeStaticOptions = { root: '' }) => {14- return async (c: Context, next: Next) => {15- // Do nothing if Response is already set16- if (c.finalized) {17- await next()18- return19- }20-21- const url = new URL(c.req.url)22-23- let path = getFilePath({24- filename: options.path ?? decodeURI(url.pathname),25- root: options.root,26- defaultDocument: DEFAULT_DOCUMENT,27- })28-29- path = `./${path}`30-31- let content32-33- try {34- content = await Deno.readFile(path)35- } catch (e) {36- console.warn(`${e}`)37- }38-39- if (content) {40- const mimeType = getMimeType(path)41- if (mimeType) {42- c.header('Content-Type', mimeType)43- }44- // Return Response object45- return c.body(content)46- } else {47- console.warn(`Static file: ${path} is not found`)48- await next()49- }50- return51- }52-}modified:src/middleware/basic-auth/index.ts+5 added-2 removed
1+import { HTTPException } from '../../http-exception'2+import type { HonoRequest } from '../../request'3 import type { MiddlewareHandler } from '../../types'4 import { timingSafeEqual } from '../../utils/buffer'5 import { decodeBase64 } from '../../utils/encode'6 7 const CREDENTIALS_REGEXP = /^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/8 const USER_PASS_REGEXP = /^([^:]*):(.*)$/9 8-const auth = (req: Request) => {10+const auth = (req: HonoRequest) => {11 const match = CREDENTIALS_REGEXP.exec(req.headers.get('Authorization') || '')12 if (!match) {13 return undefined14 }39 unmodified lines54 return55 }56 }57 }56- return new Response('Unauthorized', {58+ const res = new Response('Unauthorized', {59 status: 401,60 headers: {61 'WWW-Authenticate': 'Basic realm="' + options.realm?.replace(/"/g, '\\"') + '"',62 },63 })64+ throw new HTTPException(401, { res })65 }66 }modified:src/middleware/bearer-auth/index.ts+7 added-3 removed
1+import { HTTPException } from '../../http-exception'2 import type { MiddlewareHandler } from '../../types'3 import { timingSafeEqual } from '../../utils/buffer'4 5 const TOKEN_STRINGS = '[A-Za-z0-9._~+/-]+=*'21 unmodified lines27 const headerToken = c.req.headers.get('Authorization')28 29 if (!headerToken) {30 // No Authorization header30- return new Response('Unauthorized', {31+ const res = new Response('Unauthorized', {32 status: 401,33 headers: {34 'WWW-Authenticate': `${options.prefix} realm="` + realm + '"',35 },36 })37+ throw new HTTPException(401, { res })38 } else {39 const regexp = new RegExp('^' + options.prefix + ' +(' + TOKEN_STRINGS + ') *$')40 const match = regexp.exec(headerToken)41 if (!match) {42 // Invalid Request41- return new Response('Bad Request', {43+ const res = new Response('Bad Request', {44 status: 400,45 headers: {46 'WWW-Authenticate': `${options.prefix} error="invalid_request"`,47 },48 })49+ throw new HTTPException(400, { res })50 } else {51 const equal = await timingSafeEqual(options.token, match[1], options.hashFunction)52 if (!equal) {53 // Invalid Token51- return new Response('Unauthorized', {54+ const res = new Response('Unauthorized', {55 status: 401,56 headers: {57 'WWW-Authenticate': `${options.prefix} error="invalid_token"`,58 },59 })60+ throw new HTTPException(401, { res })61 }62 }63 }64 await next()2 unmodified linesmodified:src/middleware/cache/index.ts+1 added-1 removed
12 unmodified lines13 if (options.cacheControl) response.headers.append('Cache-Control', options.cacheControl)14 }15 16 return async (c, next) => {17- const key = c.req17+ const key = c.req.raw18 const cache = await caches.open(options.cacheName)19 const response = await cache.match(key)20 if (!response) {21 await next()12 unmodified linesmodified:src/middleware/jsx/index.ts+8 added-4 removed
1 import { escapeToBuffer } from '../../utils/html'2 import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../../utils/html'3 4 // eslint-disable-next-line @typescript-eslint/no-explicit-any5-type Props = Record<string, any>;5+type Props = Record<string, any>6 7 declare global {8 // eslint-disable-next-line @typescript-eslint/no-namespace9- namespace jsx.JSX {9+ namespace JSX {10+ type Element = HtmlEscapedString11 interface IntrinsicElements {11- [tagName: string]: Props,12+ [tagName: string]: Props13 }14 }15 }16 50 unmodified lines67 } else if (typeof child === 'boolean' || child === null || child === undefined) {68 continue69 } else if (child instanceof JSXNode) {70 child.toStringToBuffer(buffer)70- } else if (typeof child === 'number' || (child as unknown as { isEscaped: boolean }).isEscaped) {71+ } else if (72+ typeof child === 'number' ||73+ (child as unknown as { isEscaped: boolean }).isEscaped74+ ) {75 buffer[0] += child76 } else {77 // `child` type is `Child[]`, so stringify recursively78 childrenToStringToBuffer(child, buffer)151 unmodified linesmodified:src/middleware/jwt/index.ts+7 added-3 removed
1+import { HTTPException } from '../../http-exception'2 import type { MiddlewareHandler } from '../../types'3 import { Jwt } from '../../utils/jwt'4 import type { AlgorithmTypes } from '../../utils/jwt/types'5 15 unmodified lines21 let token22 if (credentials) {23 const parts = credentials.split(/\s+/)24 if (parts.length !== 2) {24- return new Response('Unauthorized', {25+ const res = new Response('Unauthorized', {26 status: 401,27 headers: {28 'WWW-Authenticate': `Bearer realm="${ctx.req.url}",error="invalid_request",error_description="invalid credentials structure"`,29 },30 })31+ throw new HTTPException(401, { res })32 } else {33 token = parts[1]34 }35 } else if (options.cookie) {36 token = ctx.req.cookie(options.cookie)37 }38 39 if (!token) {38- return new Response('Unauthorized', {40+ const res = new Response('Unauthorized', {41 status: 401,42 headers: {43 'WWW-Authenticate': `Bearer realm="${ctx.req.url}",error="invalid_request",error_description="no authorization included in request"`,44 },45 })46+ throw new HTTPException(401, { res })47 }48 49 let authorized = false50 let msg = ''2 unmodified lines53 } catch (e) {54 msg = `${e}`55 }56 if (!authorized) {54- return new Response('Unauthorized', {57+ const res = new Response('Unauthorized', {58 status: 401,59 statusText: msg,60 headers: {61 'WWW-Authenticate': `Bearer realm="${ctx.req.url}",error="invalid_token",error_description="token verification failure"`,62 },63 })64+ throw new HTTPException(401, { res })65 }66 67 await next()68 }1 unmodified linemodified:src/middleware/logger/index.ts+1 added
54 unmodified lines55 56 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)61 62 log(fn, LogPrefix.Incoming, method, path)63 7 unmodified linesdeleted:src/middleware/serve-static/bun.ts-51 removed
1-// @denoify-ignore2-/* eslint-disable @typescript-eslint/ban-ts-comment */3-import { existsSync } from 'fs'4-import type { Context } from '../../context'5-import type { Next } from '../../types'6-import { getFilePath } from '../../utils/filepath'7-import { getMimeType } from '../../utils/mime'8-9-// @ts-ignore10-const { file } = Bun11-12-export type ServeStaticOptions = {13- root?: string14- path?: string15-}16-17-const DEFAULT_DOCUMENT = 'index.html'18-19-export const serveStatic = (options: ServeStaticOptions = { root: '' }) => {20- return async (c: Context, next: Next) => {21- // Do nothing if Response is already set22- if (c.finalized) {23- await next()24- return25- }26- const url = new URL(c.req.url)27-28- let path = getFilePath({29- filename: options.path ?? decodeURI(url.pathname),30- root: options.root,31- defaultDocument: DEFAULT_DOCUMENT,32- })33- path = `./${path}`34-35- if (existsSync(path)) {36- const content = file(path)37- if (content) {38- const mimeType = getMimeType(path)39- if (mimeType) {40- c.header('Content-Type', mimeType)41- }42- // Return Response object43- return c.body(content)44- }45- }46-47- console.warn(`Static file: ${path} is not found`)48- await next()49- return50- }51-}deleted:src/middleware/serve-static/index.ts-1 removed
1-export { serveStatic } from './serve-static'deleted:src/middleware/serve-static/module.ts-17 removed
1-// @denoify-ignore2-// eslint-disable-next-line @typescript-eslint/ban-ts-comment3-// @ts-ignore4-// For ES module mode5-import manifest from '__STATIC_CONTENT_MANIFEST'6-import type { ServeStaticOptions } from './serve-static'7-import { serveStatic } from './serve-static'8-9-const module = (options: ServeStaticOptions = { root: '' }) => {10- return serveStatic({11- root: options.root,12- path: options.path,13- manifest: options.manifest ? options.manifest : manifest,14- })15-}16-17-export { module as serveStatic }deleted:src/middleware/serve-static/serve-static.test.ts-135 removed
1-import type { Context } from '../../context'2-import { Hono } from '../../hono'3-import type { Next } from '../../types'4-import { serveStatic } from '.'5-6-// Mock7-const store: Record<string, string> = {8- 'assets/static/plain.abcdef.txt': 'This is plain.txt',9- 'assets/static/hono.abcdef.html': '<h1>Hono!</h1>',10- 'assets/static/top/index.abcdef.html': '<h1>Top</h1>',11- 'static-no-root/plain.abcdef.txt': 'That is plain.txt',12- 'assets/static/options/foo.abcdef.txt': 'With options',13-}14-const manifest = JSON.stringify({15- 'assets/static/plain.txt': 'assets/static/plain.abcdef.txt',16- 'assets/static/hono.html': 'assets/static/hono.abcdef.html',17- 'assets/static/top/index.html': 'assets/static/top/index.abcdef.html',18- 'static-no-root/plain.txt': 'static-no-root/plain.abcdef.txt',19-})20-21-Object.assign(global, { __STATIC_CONTENT_MANIFEST: manifest })22-Object.assign(global, {23- __STATIC_CONTENT: {24- get: (path: string) => {25- return store[path]26- },27- },28-})29-30-describe('ServeStatic Middleware', () => {31- const app = new Hono()32- app.use('/static/*', serveStatic({ root: './assets' }))33- app.use('/static-no-root/*', serveStatic())34-35- it('Should return plain.txt', async () => {36- const res = await app.request('http://localhost/static/plain.txt')37- expect(res.status).toBe(200)38- expect(await res.text()).toBe('This is plain.txt')39- expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8')40- })41-42- it('Should return hono.html', async () => {43- const res = await app.request('http://localhost/static/hono.html')44- expect(res.status).toBe(200)45- expect(await res.text()).toBe('<h1>Hono!</h1>')46- expect(res.headers.get('Content-Type')).toBe('text/html; charset=utf-8')47- })48-49- it('Should return 404 response', async () => {50- const res = await app.request('http://localhost/static/not-found.html')51- expect(res.status).toBe(404)52- })53-54- it('Should return plan.txt', async () => {55- const res = await app.request('http://localhost/static-no-root/plain.txt')56- expect(res.status).toBe(200)57- expect(await res.text()).toBe('That is plain.txt')58- expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8')59- })60-61- it('Should return index.html', async () => {62- const res = await app.request('http://localhost/static/top')63- expect(res.status).toBe(200)64- expect(await res.text()).toBe('<h1>Top</h1>')65- expect(res.headers.get('Content-Type')).toBe('text/html; charset=utf-8')66- })67-})68-69-describe('With options', () => {70- const manifest = {71- 'assets/static/options/foo.txt': 'assets/static/options/foo.abcdef.txt',72- }73-74- const app = new Hono()75- app.use('/static/*', serveStatic({ root: './assets', manifest: manifest }))76-77- it('Should return foo.txt', async () => {78- const res = await app.request('http://localhost/static/options/foo.txt')79- expect(res.status).toBe(200)80- expect(await res.text()).toBe('With options')81- expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8')82- })83-})84-85-describe('With `file` options', () => {86- const app = new Hono()87- app.get('/foo/*', serveStatic({ path: './assets/static/hono.html' }))88- app.get('/bar/*', serveStatic({ path: './static/hono.html', root: './assets' }))89-90- it('Should return hono.html', async () => {91- const res = await app.request('http://localhost/foo/fallback')92- expect(res.status).toBe(200)93- expect(await res.text()).toBe('<h1>Hono!</h1>')94- })95-96- it('Should return hono.html - with `root` option', async () => {97- const res = await app.request('http://localhost/bar/fallback')98- expect(res.status).toBe(200)99- expect(await res.text()).toBe('<h1>Hono!</h1>')100- })101-})102-103-describe('With middleware', () => {104- const app = new Hono()105- const md1 = async (c: Context, next: Next) => {106- await next()107- c.res.headers.append('x-foo', 'bar')108- }109- const md2 = async (c: Context, next: Next) => {110- await next()111- c.res.headers.append('x-foo2', 'bar2')112- }113-114- app.use('/static/*', md1)115- app.use('/static/*', md2)116- app.use('/static/*', serveStatic({ root: './assets' }))117- app.get('/static/foo', (c) => {118- return c.text('bar')119- })120-121- it('Should return plain.txt with correct headers', async () => {122- const res = await app.request('http://localhost/static/plain.txt')123- expect(res.status).toBe(200)124- expect(await res.text()).toBe('This is plain.txt')125- expect(res.headers.get('Content-Type')).toBe('text/plain; charset=utf-8')126- expect(res.headers.get('x-foo')).toBe('bar')127- expect(res.headers.get('x-foo2')).toBe('bar2')128- })129-130- it('Should return 200 Response', async () => {131- const res = await app.request('http://localhost/static/foo')132- expect(res.status).toBe(200)133- expect(await res.text()).toBe('bar')134- })135-})deleted:src/middleware/serve-static/serve-static.ts-51 removed
1-// @denoify-ignore2-import type { KVNamespace } from '@cloudflare/workers-types'3-import type { MiddlewareHandler } from '../../types'4-import { getContentFromKVAsset } from '../../utils/cloudflare'5-import { getFilePath } from '../../utils/filepath'6-import { getMimeType } from '../../utils/mime'7-8-export type ServeStaticOptions = {9- root?: string10- path?: string11- manifest?: object | string12- namespace?: KVNamespace13-}14-15-const DEFAULT_DOCUMENT = 'index.html'16-17-// This middleware is available only on Cloudflare Workers.18-export const serveStatic = (options: ServeStaticOptions = { root: '' }): MiddlewareHandler => {19- return async (c, next) => {20- // Do nothing if Response is already set21- if (c.finalized) {22- await next()23- return24- }25-26- const url = new URL(c.req.url)27-28- const path = getFilePath({29- filename: options.path ?? decodeURI(url.pathname),30- root: options.root,31- defaultDocument: DEFAULT_DOCUMENT,32- })33-34- const content = await getContentFromKVAsset(path, {35- manifest: options.manifest,36- namespace: options.namespace ? options.namespace : c.env ? c.env.__STATIC_CONTENT : undefined,37- })38- if (content) {39- const mimeType = getMimeType(path)40- if (mimeType) {41- c.header('Content-Type', mimeType)42- }43- // Return Response object44- return c.body(content)45- } else {46- console.warn(`Static file: ${path} is not found`)47- await next()48- }49- return50- }51-}deleted:src/middleware/validator/index.ts-2 removed
1-import { validatorMiddleware } from './middleware'2-export { validatorMiddleware as validator }deleted:src/middleware/validator/middleware.test.ts-887 removed
1-/* eslint-disable @typescript-eslint/no-unused-vars */2-import { Hono } from '../../hono'3-import type { CustomHandler } from '../../types'4-import type { Expect, Equal } from '../../utils/types'5-import { validator } from './index'6-7-describe('Basic - query', () => {8- const app = new Hono()9- // query10- app.get(11- '/foo',12- validator((v) => ({13- page: v.query('page').isRequired().isNumeric(),14- q: v.query('q').isAlpha(),15- q2: v.query('q2').isAlpha().contains('abc'),16- q3: v.query('q3').contains('abc').isAlpha(),17- q4: v.query('q4').contains('abc').isLength(1, 10),18- q5: v.query('q5').isEmpty().isRequired(),19- q6: v.query('q6').contains('abc').isRequired().isLength(5, 100),20- })),21- (c) => {22- return c.text('Valid')23- }24- )25-26- it('Should return 400 response - query', async () => {27- const searchParams = new URLSearchParams({28- q: 'foobar',29- q2: 'abcdef',30- q3: 'abcdef',31- q4: 'abcde',32- q5: '123',33- q6: 'abcdef',34- })35- const req = new Request(`http://localhost/foo?${searchParams.toString()}`)36- const res = await app.request(req)37- expect(res.status).toBe(400)38- expect(await res.text()).toBe(39- [40- 'Invalid Value [undefined]: the query parameter "page" is invalid - isRequired',41- 'Invalid Value [undefined]: the query parameter "page" is invalid - isNumeric',42- 'Invalid Value [123]: the query parameter "q5" is invalid - isEmpty',43- ].join('\n')44- )45- })46-})47-48-describe('Basic - queries', () => {49- const app = new Hono()50-51- app.get(52- '/',53- validator((v) => ({54- ids: v.queries('id').isNumeric().isRequired(),55- tags: v.queries('tag').isOptional(),56- })),57- (c) => {58- return c.text('Valid')59- }60- )61-62- it('Should return 200 response', async () => {63- const res = await app.request('http://localhost/?id=123&id=456')64- expect(res.status).toBe(200)65- })66-67- it('Should return 400 response - id is not set', async () => {68- const res = await app.request('http://localhost/')69- expect(res.status).toBe(400)70- const messages = [71- 'Invalid Value []: the query parameters "id" is invalid - isNumeric',72- 'Invalid Value []: the query parameters "id" is invalid - isRequired',73- ]74- expect(await res.text()).toBe(messages.join('\n'))75- })76-77- it('Should return 400 response - is is not numeric', async () => {78- const res = await app.request('http://localhost/?id=one')79- expect(res.status).toBe(400)80- const messages = ['Invalid Value ["one"]: the query parameters "id" is invalid - isNumeric']81- expect(await res.text()).toBe(messages.join('\n'))82- })83-})84-85-describe('Basic - body', () => {86- const app = new Hono()87-88- const middleware = validator((v) => ({89- title: v.body('title').isRequired(),90- }))91-92- app.post('/posts', middleware, (c) => {93- const data = c.req.valid()94- c.header('x-title', data.title)95- return c.text('Valid!')96- })97-98- it('Should return 200 response - body', async () => {99- const body = new FormData()100- body.append('title', 'This is Title')101- const req = new Request('http://localhost/posts', {102- method: 'POST',103- body: body,104- })105- const res = await app.request(req)106- expect(res.status).toBe(200)107- expect(await res.text()).toBe('Valid!')108- expect(res.headers.get('x-title')).toBe('This is Title')109- })110-111- it('Should return 400 response - body', async () => {112- const body = new FormData()113- const req = new Request('http://localhost/posts', {114- method: 'POST',115- body: body,116- })117- const res = await app.request(req)118- expect(res.status).toBe(400)119- const messages = ['Invalid Value [undefined]: the request body "title" is invalid - isRequired']120- expect(await res.text()).toBe(messages.join('\n'))121- })122-})123-124-describe('Basic - header & custom message', () => {125- const app = new Hono()126- // header & custom error message127- app.get(128- '/',129- validator((v) => ({130- xHeader: v.header('x-header').isRequired().message('CUSTOM MESSAGE'),131- })),132- (c) => {133- return c.text('Valid')134- }135- )136-137- it('Should return 400 response - header & custom error message', async () => {138- const res = await app.request('http://localhost/')139- expect(res.status).toBe(400)140- expect(await res.text()).toBe('CUSTOM MESSAGE')141- })142-})143-144-describe('Basic - JSON with type check', () => {145- const app = new Hono()146- // JSON147- app.post(148- '/json',149- validator((v) => ({150- id: v.json('post.author.id').asNumber(),151- name: v.json('post.author.name').isAlpha(),152- })),153- (c) => {154- const { id, name } = c.req.valid()155- type verifyID = Expect<Equal<typeof id, number>>156- type verifyName = Expect<Equal<typeof name, string>>157- return c.text('Valid')158- }159- )160-161- it('Should return 200 response - JSON', async () => {162- const json = {163- post: {164- author: {165- id: 123,166- name: 'abcdef',167- },168- },169- }170- const req = new Request('http://localhost/json', {171- method: 'POST',172- body: JSON.stringify(json),173- })174- const res = await app.request(req)175- expect(res.status).toBe(200)176- })177-178- it('Should return 400 Bad Request when given an invalid JSON body', async () => {179- const req1 = new Request('http://localhost/json', {180- method: 'POST',181- body: 'Not json!',182- })183- const req2 = new Request('http://localhost/json', {184- method: 'POST',185- })186-187- const messages = ['Malformed JSON in request body']188-189- const res1 = await app.request(req1)190- expect(res1.status).toBe(400)191- expect(await res1.text()).toBe(messages.join('\n'))192-193- const res2 = await app.request(req2)194- expect(res2.status).toBe(400)195- expect(await res2.text()).toBe(messages.join('\n'))196- })197-})198-199-describe('Custom Error Handling', () => {200- const app = new Hono()201-202- // Custom Error handling203- app.get(204- '/custom-error',205- // Custom Error handler should be above.206- validator(207- (v) => ({208- userId: v.query('userId').isRequired(),209- }),210- {211- done: (result, c) => {212- if (result.hasError) {213- return c.json({ ERROR: true }, 404)214- }215- },216- }217- ),218- (c) => {219- c.header('x-valid', 'OK')220- return c.text('Valid')221- }222- )223-224- it('Should return 404 response - custom error handling', async () => {225- const res = await app.request('http://localhost/custom-error')226- expect(res.status).toBe(404)227- expect(res.headers.get('Content-Type')).toBe('application/json; charset=UTF-8')228- expect(await res.text()).toEqual(JSON.stringify({ ERROR: true }))229- expect(res.headers.get('x-valid')).toBeFalsy()230- })231-})232-233-describe('Custom Validation', () => {234- const app = new Hono()235-236- // Custom Validator237- app.post(238- '/custom-validator',239- validator((v) => ({240- password: v.body('password').addRule((value) => {241- if (typeof value === 'string') {242- return value.match(/^[a-zA-Z0-9]+$/) ? true : false243- }244- return false245- }),246- })),247- (c) => {248- return c.text('Valid')249- }250- )251-252- it('Should return 200 response - custom validator', async () => {253- const formData = new FormData()254- formData.append('password', 'abcd123')255- const req = new Request('http://localhost/custom-validator', {256- method: 'POST',257- body: formData,258- })259- const res = await app.request(req)260- expect(res.status).toBe(200)261- })262-})263-264-describe('Result objects', () => {265- const app = new Hono()266-267- app.post(268- '/posts',269- validator(270- (v) => ({271- title: v.body('title').isLength({ max: 5 }),272- }),273- {274- done: (res, c) => {275- return c.json(res['results'])276- },277- }278- ),279- (c) => {280- return c.text('Valid')281- }282- )283-284- app.post(285- '/multiple-posts',286- validator(287- (v) => ({288- posts: v.array('posts', (v) => ({289- title: v.json('title').isRequired(),290- })),291- }),292- {293- done: (res, c) => {294- return c.json(res['results'])295- },296- }297- ),298- (c) => {299- return c.text('Valid')300- }301- )302-303- it('Should return the result objects', async () => {304- const formData = new FormData()305- formData.append('title', 'abcdef')306- const req = new Request('http://localhost/posts', {307- method: 'POST',308- body: formData,309- })310- const res = await app.request(req)311- expect(await res.json()).toEqual([312- {313- isValid: true,314- key: 'title',315- ruleName: 'should be "string"',316- ruleType: 'type',317- target: 'body',318- value: 'abcdef',319- },320- {321- isValid: false,322- key: 'title',323- message: 'Invalid Value [abcdef]: the request body "title" is invalid - isLength',324- ruleName: 'isLength',325- ruleType: 'value',326- target: 'body',327- value: 'abcdef',328- },329- ])330- })331-332- it('Should return all elements of the array path', async () => {333- const body = {334- posts: [{ title: 'Post #1' }, {}, { title: 'Post #3' }, {}],335- }336- const req = new Request('http://localhost/multiple-posts', {337- method: 'POST',338- body: JSON.stringify(body),339- })340- const res = await app.request(req)341- const body1 = await res.json()342- expect(body1).toEqual([343- {344- isValid: false,345- message:346- 'Invalid Value ["Post #1", undefined, "Post #3", undefined]: the JSON body "posts.[*].title" is invalid - should be "string[]"',347- target: 'json',348- key: 'posts.[*].title',349- value: ['Post #1', null, 'Post #3', null],350- ruleName: 'should be "string[]"',351- ruleType: 'type',352- jsonData: {353- posts: [354- {355- title: 'Post #1',356- },357- {},358- {359- title: 'Post #3',360- },361- {},362- ],363- },364- },365- {366- isValid: false,367- message:368- 'Invalid Value ["Post #1", undefined, "Post #3", undefined]: the JSON body "posts.[*].title" is invalid - isRequired',369- target: 'json',370- key: 'posts.[*].title',371- value: ['Post #1', null, 'Post #3', null],372- ruleName: 'isRequired',373- ruleType: 'value',374- jsonData: {375- posts: [376- {377- title: 'Post #1',378- },379- {},380- {381- title: 'Post #3',382- },383- {},384- ],385- },386- },387- ])388- })389-})390-391-describe('Array parameter', () => {392- const app = new Hono()393-394- // Array parameter395- app.post(396- '/array-parameter',397- validator((v) => ({398- foo: v.body('value').isRequired().isEqual('valid'),399- })),400- (c) => {401- return c.text('Valid')402- }403- )404-405- it('Should return 200 response - array parameter', async () => {406- const formData = new FormData()407- formData.append('value', 'valid')408- const req = new Request('http://localhost/array-parameter', {409- method: 'POST',410- body: formData,411- })412- const res = await app.request(req)413- expect(res.status).toBe(200)414- expect(await res.text()).toBe('Valid')415- })416-417- it('Should return 400 response - array parameter', async () => {418- const formData = new FormData()419- formData.append('value', 'invalid')420- const req = new Request('http://localhost/array-parameter', {421- method: 'POST',422- body: formData,423- })424- const res = await app.request(req)425- expect(res.status).toBe(400)426- })427-})428-429-describe('Clone Request object if validate JSON or body', () => {430- const app = new Hono()431-432- app.post(433- '/body',434- validator((v) => ({435- value: v.body('value').isRequired(),436- })),437- async (c) => {438- const data = c.req.valid()439- return c.text(data.value || '')440- }441- )442- app.post(443- '/json',444- validator((v) => ({445- value: v.json('value').isRequired(),446- foo: v.json('foo').asBoolean().isFalse(),447- bar: v.json('bar').asBoolean().isTrue(),448- })),449- async (c) => {450- const data = c.req.valid()451- return c.text(data.value)452- }453- )454-455- it('Should return 200 response - clone body/body', async () => {456- const formData = new FormData()457- formData.append('value', 'foo')458- const req = new Request('http://localhost/body', {459- method: 'POST',460- body: formData,461- })462- const res = await app.request(req)463- expect(res.status).toBe(200)464- expect(await res.text()).toBe('foo')465- })466-467- it('Should return 200 response - clone body/JSON', async () => {468- const json = {469- value: 'foo',470- foo: false,471- bar: true,472- }473- const req = new Request('http://localhost/json', {474- method: 'POST',475- body: JSON.stringify(json),476- })477- const res = await app.request(req)478- expect(res.status).toBe(200)479- expect(await res.text()).toBe('foo')480- })481-})482-483-describe('Check duplicate values', () => {484- type Env = { Variables: { mail2: string } }485-486- const app = new Hono<Env>()487- app488- .post(489- '/bar',490- validator((v) => ({491- mail2: v.body('mail2').isRequired(),492- })),493- async (c, next) => {494- c.set('mail2', c.req.valid()['mail2'])495- await next()496- }497- )498- .post(499- validator((v, c) => ({500- mail: v.body('mail1').isEqual(c.get('mail2')),501- })),502- (c) => {503- const { mail } = c.req.valid()504- type verifyBindings = Expect<Equal<typeof mail, string>>505- return c.text('Valid')506- }507- )508-509- it('Should return 200 response - duplicate values', async () => {510- const formData = new FormData()511- formData.append('mail1', 'foo@honojs.dev')512- formData.append('mail2', 'foo@honojs.dev')513- const req = new Request('http://localhost/bar', {514- method: 'POST',515- body: formData,516- })517- const res = await app.request(req)518- expect(res.status).toBe(200)519- expect(await res.text()).toBe('Valid')520- })521-})522-523-describe('Remove additional properties', () => {524- const app = new Hono()525- // query526- app.get(527- '/foo',528- validator((v) => ({529- q: v.query('q').isOptional(),530- page: v.query('page').isNumeric(),531- })),532- (c) => {533- return c.json(c.req.valid())534- }535- )536-537- it('Should only return validated params', async () => {538- const searchParams = new URLSearchParams({539- q: 'foobar',540- page: '3',541- foo: 'additional query',542- })543- const req = new Request(`http://localhost/foo?${searchParams.toString()}`)544- const res = await app.request(req)545- expect(res.status).toBe(200)546- expect(await res.json()).toEqual({ q: 'foobar', page: '3' })547- })548-549- // JSON550- app.post(551- '/json',552- validator((v) => ({553- name: v.json('post.author.name').isAlpha(),554- })),555- async (c) => {556- return c.json(c.req.valid())557- }558- )559-560- it('Should only return validated JSON data', async () => {561- const json = {562- post: {563- title: 'Hello',564- author: {565- name: 'abcdef',566- age: 20,567- },568- },569- }570- const req = new Request('http://localhost/json', {571- method: 'POST',572- body: JSON.stringify(json),573- })574- const res = await app.request(req)575- expect(res.status).toBe(200)576- expect(await res.json()).toEqual({ name: 'abcdef' })577- })578-})579-580-describe('Structured data', () => {581- const app = new Hono()582-583- app.post(584- '/post',585- validator((v) => ({586- header: {587- 'x-foo': v.header('x-foo').isAlpha(),588- },589- post: {590- title: v.json('post.title').isAlpha(),591- content: v.json('post.content'),592- },593- })),594- (c) => {595- const header = c.req.valid().header596- const post = c.req.valid().post597- return c.json({ header, post })598- }599- )600-601- it('Should return 200 response', async () => {602- const json = {603- post: {604- title: 'Hello',605- content: 'World',606- },607- }608- const headers = {609- 'x-foo': 'bar',610- }611- const req = new Request('http://localhost/post', {612- method: 'POST',613- headers,614- body: JSON.stringify(json),615- })616- const res = await app.request(req)617- expect(res.status).toBe(200)618- expect(await res.json()).toEqual({ header: headers, post: json.post })619- })620-621- it('Should return 400 response - missing a required header', async () => {622- const json = {623- post: {624- title: 'Hello',625- content: 'World',626- },627- }628- const req = new Request('http://localhost/post', {629- method: 'POST',630- body: JSON.stringify(json),631- })632- const res = await app.request(req)633- expect(res.status).toBe(400)634- })635-})636-637-describe('Array values with type check', () => {638- const app = new Hono()639- app.post(640- '/post',641- validator((v) => ({642- post: {643- title: v.json('post.title').isAlpha(),644- tags: v.json('post.tags').asArray().isRequired(),645- ids: v.json('post.ids').asNumber().asArray(),646- },647- })),648- (c) => {649- const { post } = c.req.valid()650-651- type verifyTitle = Expect<Equal<typeof post.title, string>>652- type verifyTags = Expect<Equal<typeof post.tags, string[]>>653- type verifyIDs = Expect<Equal<typeof post.ids, number[]>>654-655- return c.json({ tag1: post.tags[0] })656- }657- )658-659- it('Should return 200 response', async () => {660- const json = {661- post: {662- title: 'foo',663- tags: ['Workers', 'Deno', 'Bun'],664- ids: [1, 3, 5],665- },666- }667- const req = new Request('http://localhost/post', {668- method: 'POST',669- body: JSON.stringify(json),670- })671- const res = await app.request(req)672- expect(res.status).toBe(200)673- expect(await res.json()).toEqual({ tag1: 'Workers' })674- })675-})676-677-describe('Nested structured data', () => {678- const json = {679- posts: [680- {681- id: 123,682- title: 'JavaScript',683- tags: [684- {685- name: 'Node.js',686- },687- {688- name: 'Deno',689- },690- {691- name: 'Bun',692- },693- ],694- },695- {696- id: 456,697- title: 'Framework',698- tags: [699- {700- name: 'Hono',701- },702- {703- name: 'Express',704- },705- {706- name: 'Fastify',707- },708- ],709- },710- ],711- meta: {712- pager: 'pager',713- },714- }715-716- it('Should return 200 response - nested objects', async () => {717- const app = new Hono()718- app.post(719- '/posts',720- validator((v) => ({721- posts: v.array('posts', (v) => ({722- id: v.json('id').asNumber(),723- title: v.json('title').isRequired(),724- tags: v.array('tags', (v) => ({725- name: v.json('name'),726- })),727- })),728- meta: v.object('meta', (v) => ({729- pager: v.json('pager'),730- })),731- })),732- (c) => {733- const res = c.req.valid()734- return c.json({ posts: res.posts })735- }736- )737- const req = new Request('http://localhost/posts', {738- method: 'POST',739- body: JSON.stringify(json),740- })741-742- const res = await app.request(req)743- expect(res.status).toBe(200)744- expect(await res.json()).toEqual({ posts: json.posts })745- })746-747- it('Should return 400 response - nested objects', async () => {748- const app = new Hono()749- app.post(750- '/posts-invalid',751- validator((v) => ({752- posts: v.array('posts', (v) => ({753- id: v.json('ids').asArray().asNumber(),754- })),755- })),756- (c) => {757- const res = c.req.valid()758- return c.json({ posts: res.posts })759- }760- )761- const req = new Request('http://localhost/posts-invalid', {762- method: 'POST',763- body: JSON.stringify(json),764- })765-766- const res = await app.request(req)767- expect(res.status).toBe(400)768- })769-})770-771-describe('Special case', () => {772- const app = new Hono()773- app.get(774- '/search',775- validator((v) => ({776- q: v.query('q').isRequired(),777- page: v.query('page').asNumber(),778- })),779- (c) => {780- return c.text('Valid')781- }782- )783- it('Should show the type message error if it does not have "value" errors', async () => {784- const res = await app.request('http://localhost/search?q=foo')785- expect(res.status).toBe(400)786- expect(await res.text()).toBe(787- [788- 'Invalid Value [undefined]: the query parameter "page" is invalid - should be "number"',789- ].join('\n')790- )791- })792-})793-794-describe('Type check in special case', () => {795- it('Should return 200 response with correct types', async () => {796- const app = new Hono()797- app.post(798- '/posts/:id',799- validator((v) => ({800- title: v.body('title').isRequired(),801- })),802- (c) => {803- const res = c.req.valid()804- const id = c.req.param('id')805- type verifyTitle = Expect<Equal<typeof res.title, string>>806- type verifyId = Expect<Equal<typeof id, string>>807- return c.text(`${id} is ${res.title}`)808- }809- )810- const body = new FormData()811- body.append('title', 'Hello')812- const req = new Request('http://localhost/posts/123', {813- method: 'POST',814- body: body,815- })816- const res = await app.request(req)817- expect(res.status).toBe(200)818- expect(await res.text()).toBe('123 is Hello')819- })820-821- it('Should return 200 response with correct types - validator and named parameter', async () => {822- const app = new Hono()823-824- const vm = validator((v) => ({825- title: v.body('title').isRequired(),826- }))827-828- app.post('/posts', vm, (c) => {829- const { title } = c.req.valid()830- type verify = Expect<Equal<typeof title, string>>831- return c.text(title)832- })833-834- app.post('/posts/:id', vm, (c) => {835- const id = c.req.param('id')836- const { title } = c.req.valid()837- type verify = Expect<Equal<typeof title, string>>838- return c.text(`${id} is ${title}`)839- })840-841- const body = new FormData()842- body.append('title', 'Hello')843-844- let res = await app.request('http://localhost/posts', {845- method: 'POST',846- body: body,847- })848- expect(res.status).toBe(200)849- expect(await res.text()).toBe('Hello')850- res = await app.request('http://localhost/posts/123?title=foo', {851- method: 'POST',852- body: body,853- })854- expect(res.status).toBe(200)855- expect(await res.text()).toBe('123 is Hello')856- })857-858- it('Should return 200 response with correct types - Context in validator function', async () => {859- type Env = { Bindings: { FOO: 'abc' } }860-861- const app = new Hono<Env>()862-863- app.get(864- '/search',865- validator(866- (v) => ({867- foo: v.query('foo'),868- }),869- {870- done: (_, c) => {871- type verifyBindings = Expect<Equal<typeof c.env.FOO, 'abc'>>872- },873- }874- ),875- (c) => {876- const { foo } = c.req.valid()877- type verifyBindings = Expect<Equal<typeof c.env.FOO, 'abc'>>878- type verify = Expect<Equal<typeof foo, string>>879- return c.text(foo)880- }881- )882-883- const res = await app.request('http://localhost/search?foo=bar')884- expect(res.status).toBe(200)885- expect(await res.text()).toBe('bar')886- })887-})deleted:src/middleware/validator/middleware.ts-162 removed
1-import type { Context } from '../../context'2-import type { Environment, MiddlewareHandler } from '../../types'3-import { getStatusText } from '../../utils/http-status'4-import { mergeObjects } from '../../utils/object'5-import type { Schema } from '../../validator/schema'6-import type { ValidateResult } from '../../validator/validator'7-import { Validator, VBase, VObjectBase } from '../../validator/validator'8-9-type ResultSet = {10- hasError: boolean11- messages: string[]12- results: ValidateResult[]13-}14-15-type Done<P extends string, E extends Partial<Environment> = Environment> = (16- resultSet: ResultSet,17- c: Context<P, E>18-) => Response | void19-20-type ValidationFunction<21- P extends string,22- E extends Partial<Environment> = Environment,23- S = unknown24-> = (v: Validator, c: Context<P, E>) => S25-26-export const validatorMiddleware = <27- P extends string,28- E extends Partial<Environment> = Environment,29- S = unknown30->(31- validationFunction: ValidationFunction<P, E, S>,32- options?: { done?: Done<P, E> }33-) => {34- console.warn(`Current Validator Middleware will be changed with "breaking changes" at the ext major release "v3".35- See the migration guide: https://github.com/honojs/hono/blob/main/docs/MIGRATION.md`)36-37- const v = new Validator()38- const handler: MiddlewareHandler<string, E, S> = async (c, next) => {39- const resultSet: ResultSet = {40- hasError: false,41- messages: [],42- results: [],43- }44-45- // eslint-disable-next-line @typescript-eslint/ban-ts-comment46- // @ts-ignore47- const schema = validationFunction(v, c)48- const validatorList = getValidatorList(schema)49- // eslint-disable-next-line @typescript-eslint/no-explicit-any50- let data: any = {}51-52- for (const [keys, validator] of validatorList) {53- let results: ValidateResult[]54- try {55- results = await validator.validate(c.req)56- } catch (e) {57- // Invalid JSON request58- if (e instanceof Error) {59- const result = getErrorResult(e)60- resultSet.hasError = true61- resultSet.messages = [result.message || '']62- resultSet.results = [result]63- break64- } else {65- return c.text(getStatusText(400), 400)66- }67- }68-69- let isValid = true70- const value = results[0].value71- const jsonData = results[0].jsonData72-73- for (const result of results) {74- if (!result.isValid) {75- isValid = false76- resultSet.hasError = true77- if (result.ruleType === 'value' && result.message !== undefined) {78- resultSet.messages.push(result.message)79- }80- }81- resultSet.results.push(result)82- }83-84- // If it's invalid but it has no "value" messages, have to set the "type" messages.85- // This approach is verbose, but if do not so, the response body will be empty.86- if (!isValid && resultSet.messages.length === 0) {87- resultSet.results.map((r) => {88- if (!r.isValid && r.ruleType === 'type' && r.message) {89- resultSet.messages.push(r.message)90- }91- })92- }93-94- // Set data on request object95- if (isValid) {96- // Set data on request object97- if (jsonData) {98- const dst = data99- data = mergeObjects(dst, jsonData)100- } else {101- let tmp = data102- for (let i = 0; i < keys.length - 1; i++) {103- tmp = tmp[keys[i]] ||= {}104- }105- tmp[keys[keys.length - 1]] = value106- }107- }108- }109-110- if (!resultSet.hasError) {111- c.req.valid(data)112- }113-114- if (options && options.done) {115- // eslint-disable-next-line @typescript-eslint/ban-ts-comment116- // @ts-ignore117- const res = options.done(resultSet, c)118- if (res) {119- return res120- }121- }122-123- if (resultSet.hasError) {124- return c.text(resultSet.messages.join('\n'), 400)125- }126- await next()127- }128- return handler129-}130-131-function getValidatorList<T>(schema: T) {132- const map: [string[], VBase][] = []133- for (const [key, value] of Object.entries(schema as unknown as Schema)) {134- if (value instanceof VObjectBase) {135- const validators = value.getValidators()136- for (const validator of validators) {137- map.push([value.keys, validator])138- }139- } else if (value instanceof VBase) {140- map.push([[key], value])141- } else {142- const children = getValidatorList(value as Schema)143- for (const [keys, validator] of children) {144- map.push([[key, ...keys], validator])145- }146- }147- }148- return map149-}150-151-const getErrorResult = (e: Error) => {152- const result: ValidateResult = {153- isValid: false,154- message: e.message,155- target: 'unknown',156- key: null,157- value: null,158- ruleName: e.message,159- ruleType: 'value',160- }161- return result162-}modified:src/router/reg-exp-router/node.ts+18 added-3 removed
43 unmodified lines44 index?: number45 varIndex?: number46 children: Record<string, Node> = {}47 48- insert(tokens: readonly string[], index: number, paramMap: ParamMap, context: Context): void {48+ insert(49+ tokens: readonly string[],50+ index: number,51+ paramMap: ParamMap,52+ context: Context,53+ pathErrorCheckOnly: boolean54+ ): void {55 if (tokens.length === 0) {56 if (this.index !== undefined) {57 throw PATH_ERROR58 }59+ if (pathErrorCheckOnly) {60+ return61+ }62 63 this.index = index64 return65 }21 unmodified lines87 )88 ) {89 throw PATH_ERROR90 }91+ if (pathErrorCheckOnly) {92+ return93+ }94 node = this.children[regexpStr] = new Node()95 if (name !== '') {96 node.varIndex = context.varIndex++97 }98 }87- if (name !== '') {99+ if (!pathErrorCheckOnly && name !== '') {100 if (paramMap.some((p) => p[0] === name)) {101 throw new Error('Duplicate param name')102 }103 paramMap.push([name, node.varIndex as number])8 unmodified lines112 )113 ) {114 throw PATH_ERROR115 }116+ if (pathErrorCheckOnly) {117+ return118+ }119 node = this.children[token] = new Node()120 }121 }122 108- node.insert(restTokens, index, paramMap, context)123+ node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly)124 }125 126 buildRegExpStr(): string {127 const childKeys = Object.keys(this.children).sort(compareKey)20 unmodified linesmodified:src/router/reg-exp-router/router.test.ts+69 added-1 removed
180 unmodified lines181 router.add('GET', '/:user/entries', 'get user entries')182 router.add('GET', '/entry/:name', 'get entry')183 router.add('POST', '/entry', 'create entry')184 185- it('GET /entry/entry', async () => {185+ it('GET /entry/entries', async () => {186 expect(() => {187 router.match('GET', '/entry/entries')188 }).toThrowError(UnsupportedPathError)189 })31 unmodified lines221 router.match('GET', '/')222 }).toThrowError(UnsupportedPathError)223 })224 225+ it('static and dynamic', () => {226+ const router = new RegExpRouter<string>()227+ router.add('GET', '/reg-exp/router', 'foo')228+ router.add('GET', '/reg-exp/:id', 'bar')229+230+ expect(() => {231+ router.match('GET', '/')232+ }).toThrowError(UnsupportedPathError)233+ })234+235+ it('dynamic and static', () => {236+ const router = new RegExpRouter<string>()237+ router.add('GET', '/reg-exp/:id', 'bar')238+ router.add('GET', '/reg-exp/router', 'foo')239+240+ expect(() => {241+ router.match('GET', '/')242+ }).toThrowError(UnsupportedPathError)243+ })244+245 it('different regular expression', () => {246 const router = new RegExpRouter<string>()247 router.add('GET', '/:id/:action{create|update}', 'foo')248 router.add('GET', '/:id/:action{delete}', 'bar')100 unmodified lines349 const res = router.match('GET', '/long/prefix/test')350 expect(res?.handlers).toEqual(['long-prefix', 'long', 'star1', 'star2'])351 })352 })353+354+ describe('Including slashes', () => {355+ const router = new RegExpRouter<string>()356+357+ router.add('GET', '/js/:filename{[a-z0-9/]+.js}', 'any file')358+359+ // XXX This route can not be added with `:label` to RegExpRouter. This is ambiguous.360+ // router.add('GET', '/js/main.js', 'main.js')361+ // it('get /js/main.js', () => {362+ // const res = router.match('GET', '/js/main.js')363+ // expect(res).not.toBeNull()364+ // expect(res?.handlers).toEqual(['any file', 'main.js'])365+ // expect(res?.params).toEqual({ filename: 'main.js' })366+ // })367+368+ it('get /js/chunk/123.js', () => {369+ const res = router.match('GET', '/js/chunk/123.js')370+ expect(res).not.toBeNull()371+ expect(res?.handlers).toEqual(['any file'])372+ expect(res?.params).toEqual({ filename: 'chunk/123.js' })373+ })374+375+ it('get /js/chunk/nest/123.js', () => {376+ const res = router.match('GET', '/js/chunk/nest/123.js')377+ expect(res).not.toBeNull()378+ expect(res?.handlers).toEqual(['any file'])379+ expect(res?.params).toEqual({ filename: 'chunk/nest/123.js' })380+ })381+ })382+383+ describe('REST API', () => {384+ const router = new RegExpRouter<string>()385+386+ router.add('GET', '/users/:username{[a-z]+}', 'profile')387+ router.add('GET', '/users/:username{[a-z]+}/posts', 'posts')388+389+ it('get /users/hono', () => {390+ const res = router.match('GET', '/users/hono')391+ expect(res).not.toBeNull()392+ expect(res?.handlers).toEqual(['profile'])393+ })394+395+ it('get /users/hono/posts', () => {396+ const res = router.match('GET', '/users/hono/posts')397+ expect(res).not.toBeNull()398+ expect(res?.handlers).toEqual(['posts'])399+ })400+ })401 })402 403 describe('static routes of ALL and GET', () => {404 const router = new RegExpRouter<string>()69 unmodified linesmodified:src/router/reg-exp-router/router.ts+33 added-9 removed
6 unmodified lines7 import { Trie } from './trie'8 9 const methodNames = [METHOD_NAME_ALL, ...METHODS].map((method) => method.toUpperCase())10 11-type HandlerData<T> = [T[], ParamMap | null]12-type Matcher<T> = [RegExp, HandlerData<T>[]]11+type HandlerData<T> = [T[], ParamMap] | [Result<T>, null]12+type StaticMap<T> = Record<string, Result<T>>13+type Matcher<T> = [RegExp, HandlerData<T>[], StaticMap<T>]14 15 const emptyParam = {}16 // eslint-disable-next-line @typescript-eslint/no-explicit-any16-const nullMatcher: Matcher<any> = [/^$/, []]17+const nullMatcher: Matcher<any> = [/^$/, [], {}]18 19 let wildcardRegExpCache: Record<string, RegExp> = {}20 function buildWildcardRegExp(path: string): RegExp {21 return (wildcardRegExpCache[path] ??= new RegExp(13 unmodified lines35 }36 37 routes = routes.sort(([a], [b]) => a.length - b.length)38 39+ const staticMap: StaticMap<T> = {}38- for (let i = 0, len = routes.length; i < len; i++) {40+ for (let i = 0, j = -1, len = routes.length; i < len; i++) {41+ const path = routes[i][0]42+ let pathErrorCheckOnly = false43+ if (!/\*|\/:/.test(path)) {44+ pathErrorCheckOnly = true45+ staticMap[routes[i][0]] = { handlers: routes[i][1], params: emptyParam }46+ } else {47+ j++48+ }49+50 let paramMap51 try {41- paramMap = trie.insert(routes[i][0], i)52+ paramMap = trie.insert(path, j, pathErrorCheckOnly)53 } catch (e) {43- throw e === PATH_ERROR ? new UnsupportedPathError(routes[i][0]) : e54+ throw e === PATH_ERROR ? new UnsupportedPathError(path) : e55 }56 46- handlers[i] = [routes[i][1], paramMap.length !== 0 ? paramMap : null]57+ if (pathErrorCheckOnly) {58+ continue59+ }60+61+ handlers[j] =62+ paramMap.length === 063+ ? [{ handlers: routes[i][1], params: emptyParam }, null]64+ : [routes[i][1], paramMap]65 }66 67 const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp()68 for (let i = 0, len = handlers.length; i < len; i++) {10 unmodified lines79 for (const i in indexReplacementMap) {80 handlerMap[i] = handlers[indexReplacementMap[i]]81 }82 65- return [regexp, handlerMap] as Matcher<T>83+ return [regexp, handlerMap, staticMap] as Matcher<T>84 }85 86 function findMiddleware<T>(87 middleware: Record<string, T[]> | undefined,97 unmodified lines185 const matchers = this.buildAllMatchers()186 187 this.match = (method, path) => {188 const matcher = matchers[method]189+190+ const staticMatch = matcher[2][path]191+ if (staticMatch) {192+ return staticMatch193+ }194+195 const match = path.match(matcher[0])196 if (!match) {197 return null198 }199 200 const index = match.indexOf('', 1)201 const [handlers, paramMap] = matcher[1][index]202 if (!paramMap) {179- return { handlers, params: emptyParam }203+ return handlers204 }205 206 const params: Record<string, string> = {}207 for (let i = 0, len = paramMap.length; i < len; i++) {51 unmodified linesmodified:src/router/reg-exp-router/trie.ts+31 added-5 removed
6 unmodified lines7 export class Trie {8 context: Context = { varIndex: 0 }9 root: Node = new Node()10 11- insert(path: string, index: number): ParamMap {11+ insert(path: string, index: number, pathErrorCheckOnly: boolean): ParamMap {12 const paramMap: ParamMap = []13 14+ const groups: [string, string][] = [] // [mark, original string]15+ for (let i = 0; ; ) {16+ let replaced = false17+ path = path.replace(/\{[^}]+\}/g, (m) => {18+ const mark = `@\\${i}`19+ groups[i] = [mark, m]20+ i++21+ replaced = true22+ return mark23+ })24+ if (!replaced) {25+ break26+ }27+ }28+29 /**30 * - pattern (:label, :label{0-9]+}, ...)31 * - /* wildcard32 * - character33 */19- const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g)20- // eslint-disable-next-line @typescript-eslint/ban-ts-comment21- // @ts-ignore22- this.root.insert(tokens, index, paramMap, this.context)34+ const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || []35+ for (let i = groups.length - 1; i >= 0; i--) {36+ const [mark] = groups[i]37+ for (let j = tokens.length - 1; j >= 0; j--) {38+ if (tokens[j].indexOf(mark) !== -1) {39+ tokens[j] = tokens[j].replace(mark, groups[i][1])40+ break41+ }42+ }43+ }44 45+ this.root.insert(tokens, index, paramMap, this.context, pathErrorCheckOnly)46+47 return paramMap48 }49 50 buildRegExp(): [RegExp, ReplacementMap, ReplacementMap] {51 let regexp = this.root.buildRegExpStr()52+ if (regexp === '') {53+ return [/^$/, [], []] // never match54+ }55 56 let captureIndex = 057 const indexReplacementMap: ReplacementMap = []58 const paramReplacementMap: ReplacementMap = []17 unmodified linesmodified:src/router/smart-router/router.test.ts+2 added-65 removed
1 import { RegExpRouter } from '../reg-exp-router'2-import { StaticRouter } from '../static-router'2 import { TrieRouter } from '../trie-router'3 import { SmartRouter } from './router'4 6-describe('StaticRouter', () => {7- describe('Basic Usage', () => {8- const router = new SmartRouter<string>({9- routers: [new StaticRouter(), new RegExpRouter(), new TrieRouter()],10- })11-12- router.add('GET', '/hello', 'get hello')13- router.add('POST', '/hello', 'post hello')14- router.add('PURGE', '/hello', 'purge hello')15-16- it('get, post hello', async () => {17- let res = router.match('GET', '/hello')18- expect(res).not.toBeNull()19- expect(res?.handlers).toEqual(['get hello'])20-21- res = router.match('POST', '/hello')22- expect(res).not.toBeNull()23- expect(res?.handlers).toEqual(['post hello'])24-25- res = router.match('PURGE', '/hello')26- expect(res).not.toBeNull()27- expect(res?.handlers).toEqual(['purge hello'])28-29- res = router.match('PUT', '/hello')30- expect(res).toBeNull()31-32- res = router.match('GET', '/')33- expect(res).toBeNull()34-35- expect(router.activeRouter).toBeInstanceOf(StaticRouter)36- })37- })38-39- describe('Multi match', () => {40- describe('Blog', () => {41- const router = new SmartRouter<string>({42- routers: [new StaticRouter(), new RegExpRouter(), new TrieRouter()],43- })44-45- router.add('ALL', '*', 'middleware a')46- router.add('GET', '*', 'middleware b')47- router.add('GET', '/entry', 'get entries')48- it('GET /', async () => {49- const res = router.match('GET', '/')50- expect(res).not.toBeNull()51- expect(res?.handlers).toEqual(['middleware a', 'middleware b'])52- expect(router.activeRouter).toBeInstanceOf(StaticRouter)53- })54- it('GET /entry', async () => {55- const res = router.match('GET', '/entry')56- expect(res).not.toBeNull()57- expect(res?.handlers).toEqual(['middleware a', 'middleware b', 'get entries'])58- })59- it('DELETE /entry', async () => {60- const res = router.match('DELETE', '/entry')61- expect(res).not.toBeNull()62- expect(res?.handlers).toEqual(['middleware a'])63- })64- })65- })66-})67-5 describe('RegExpRouter', () => {6 describe('Complex', () => {7 let router: SmartRouter<string>8 beforeEach(() => {9 router = new SmartRouter<string>({73- routers: [new StaticRouter(), new RegExpRouter(), new TrieRouter()],10+ routers: [new RegExpRouter(), new TrieRouter()],11 })12 })13 14 it('Named Param', async () => {54 unmodified lines69 })70 71 describe('TrieRouter', () => {72 const router = new SmartRouter<string>({136- routers: [new StaticRouter(), new RegExpRouter(), new TrieRouter()],73+ routers: [new RegExpRouter(), new TrieRouter()],74 })75 76 router.add('GET', '/:user/entries', 'get user entries')77 router.add('GET', '/entry/:name', 'get entry')9 unmodified linesdeleted:src/router/static-router/index.ts-1 removed
1-export { StaticRouter } from './router'deleted:src/router/static-router/router.test.ts-54 removed
1-import { StaticRouter } from './router'2-3-describe('Basic Usage', () => {4- const router = new StaticRouter<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('Multi match', () => {32- describe('Blog', () => {33- const router = new StaticRouter<string>()34-35- router.add('ALL', '*', 'middleware a')36- router.add('GET', '*', 'middleware b')37- router.add('GET', '/entry', 'get entries')38- it('GET /', async () => {39- const res = router.match('GET', '/')40- expect(res).not.toBeNull()41- expect(res?.handlers).toEqual(['middleware a', 'middleware b'])42- })43- it('GET /entry', async () => {44- const res = router.match('GET', '/entry')45- expect(res).not.toBeNull()46- expect(res?.handlers).toEqual(['middleware a', 'middleware b', 'get entries'])47- })48- it('DELETE /entry', async () => {49- const res = router.match('DELETE', '/entry')50- expect(res).not.toBeNull()51- expect(res?.handlers).toEqual(['middleware a'])52- })53- })54-})deleted:src/router/static-router/router.ts-96 removed
1-/* eslint-disable @typescript-eslint/ban-ts-comment */2-import type { Router, Result } from '../../router'3-import { METHOD_NAME_ALL, METHODS, UnsupportedPathError } from '../../router'4-5-export class StaticRouter<T> implements Router<T> {6- middleware: Record<string, Result<T>>7- routes: Record<string, Record<string, Result<T>>>8-9- constructor() {10- this.middleware = {}11-12- this.routes = {} as StaticRouter<T>['routes']13- ;[METHOD_NAME_ALL, ...METHODS].forEach((method) => {14- this.routes[method.toUpperCase()] = {}15- })16- }17-18- private newRoute(): Record<string, Result<T>> {19- const route: Record<string, Result<T>> = {}20- const routeAll = this.routes[METHOD_NAME_ALL]21- Object.keys(routeAll).forEach((path) => {22- route[path] = {23- handlers: [...routeAll[path].handlers],24- params: {},25- }26- })27-28- return route29- }30-31- add(method: string, path: string, handler: T) {32- const { middleware, routes } = this33-34- routes[method] ||= this.newRoute()35-36- if (path === '/*') {37- path = '*'38- }39-40- if (path === '*') {41- if (method === METHOD_NAME_ALL) {42- middleware[METHOD_NAME_ALL] ||= { handlers: [], params: {} }43- Object.keys(middleware).forEach((m) => {44- middleware[m].handlers.push(handler)45- })46- Object.keys(routes).forEach((m) => {47- Object.values(routes[m]).forEach((matchRes) => matchRes.handlers.push(handler))48- })49- } else {50- middleware[method] ||= {51- handlers: [...(middleware[METHOD_NAME_ALL]?.handlers || [])],52- params: {},53- }54- middleware[method].handlers.push(handler)55- if (routes[method]) {56- Object.values(routes[method]).forEach((matchRes) => matchRes.handlers.push(handler))57- }58- }59- return60- }61-62- if (/\*|\/:/.test(path)) {63- throw new UnsupportedPathError(path)64- }65-66- routes[method][path] ||= {67- handlers: [68- ...(routes[METHOD_NAME_ALL][path]?.handlers ||69- middleware[method]?.handlers ||70- middleware[METHOD_NAME_ALL]?.handlers ||71- []),72- ],73- params: {},74- }75- if (method === METHOD_NAME_ALL) {76- Object.keys(routes).forEach((m) => {77- routes[m][path]?.handlers?.push(handler)78- })79- } else {80- routes[method][path].handlers.push(handler)81- }82- }83-84- match(method: string, path: string): Result<T> | null {85- const { routes, middleware } = this86-87- this.match = (method, path) =>88- routes[method][path] ||89- routes[METHOD_NAME_ALL][path] ||90- middleware[method] ||91- middleware[METHOD_NAME_ALL] ||92- null93-94- return this.match(method, path)95- }96-}modified:src/router/trie-router/node.test.ts+45 added
357 unmodified lines358 expect(res).not.toBeNull()359 expect(res?.handlers).toEqual(['Middleware A', 'Middleware B'])360 })361 })362+363+ describe('Including slashes', () => {364+ const node = new Node()365+ node.insert('get', '/js/:filename{[a-z0-9/]+.js}', 'any file')366+ node.insert('get', '/js/main.js', 'main.js')367+368+ it('get /js/main.js', () => {369+ const res = node.search('get', '/js/main.js')370+ expect(res).not.toBeNull()371+ expect(res?.handlers).toEqual(['any file', 'main.js'])372+ expect(res?.params).toEqual({ filename: 'main.js' })373+ })374+375+ it('get /js/chunk/123.js', () => {376+ const res = node.search('get', '/js/chunk/123.js')377+ expect(res).not.toBeNull()378+ expect(res?.handlers).toEqual(['any file'])379+ expect(res?.params).toEqual({ filename: 'chunk/123.js' })380+ })381+382+ it('get /js/chunk/nest/123.js', () => {383+ const res = node.search('get', '/js/chunk/nest/123.js')384+ expect(res).not.toBeNull()385+ expect(res?.handlers).toEqual(['any file'])386+ expect(res?.params).toEqual({ filename: 'chunk/nest/123.js' })387+ })388+ })389+390+ describe('REST API', () => {391+ const node = new Node()392+ node.insert('get', '/users/:username{[a-z]+}', 'profile')393+ node.insert('get', '/users/:username{[a-z]+}/posts', 'posts')394+395+ it('get /users/hono', () => {396+ const res = node.search('get', '/users/hono')397+ expect(res).not.toBeNull()398+ expect(res?.handlers).toEqual(['profile'])399+ })400+401+ it('get /users/hono/posts', () => {402+ const res = node.search('get', '/users/hono/posts')403+ expect(res).not.toBeNull()404+ expect(res?.handlers).toEqual(['posts'])405+ })406+ })407 })408 409 describe('Duplicate param name', () => {410 it('self', () => {211 unmodified linesmodified:src/router/trie-router/node.ts+11 added-2 removed
1 import type { Result } from '../../router'2 import { METHOD_NAME_ALL } from '../../router'3 import type { Pattern } from '../../utils/url'4-import { splitPath, getPattern } from '../../utils/url'4+import { splitPath, splitRoutingPath, getPattern } from '../../utils/url'5 6 type HandlerSet<T> = {7 handler: T8 score: number44 unmodified lines53 this.order = ++this.order54 55 // eslint-disable-next-line @typescript-eslint/no-this-alias56 let curNode: Node<T> = this57- const parts = splitPath(path)57+ const parts = splitRoutingPath(path)58 59 const parentPatterns: Pattern[] = []60 const errorMessage = (name: string): string => {61 return `Duplicate param name, use another name instead of '${name}' - ${method} ${path} <--- '${name}'`109 unmodified lines171 172 // Named match173 // `/posts/:id` => match /posts/123174 const [key, name, matcher] = pattern175+176+ // `/js/:filename{[a-z]+.js}` => match /js/chunk/123.js177+ const restPathString = parts.slice(i).join('/')178+ if (matcher instanceof RegExp && matcher.test(restPathString)) {179+ handlerSets.push(...this.getHandlerSets(node.children[key], method))180+ params[name] = restPathString181+ continue182+ }183+184 if (matcher === true || (matcher instanceof RegExp && matcher.test(part))) {185 if (typeof key === 'string') {186 if (isLast === true) {187 handlerSets.push(...this.getHandlerSets(node.children[key], method))40 unmodified linesmodified:src/utils/body.ts+5 added-7 removed
1-export type BodyData = Record<string, string | number | boolean | File>1+export type BodyData = Record<string, string | File>2 3-export async function parseBody<BodyType extends BodyData>(4- r: Request | Response5-): Promise<BodyType> {6- let body: Record<string, string | File> = {}3+export async function parseBody(r: Request | Response) {4+ let body: BodyData = {}5 const contentType = r.headers.get('Content-Type')6 if (7 contentType &&8 (contentType.startsWith('multipart/form-data') ||9 contentType === 'application/x-www-form-urlencoded')10 ) {13- const form: Record<string, string | File> = {}11+ const form: BodyData = {}12 ;(await r.formData()).forEach((value, key) => {13 form[key] = value14 })15 body = form16 }19- return body as BodyType17+ return body18 }modified:src/utils/buffer.ts+6 added
27 unmodified lines28 ) => {29 if (!hashFunction) {30 hashFunction = sha25631 }32+33 const sa = await hashFunction(a)34 const sb = await hashFunction(b)35+36+ if (!sa || !sb) {37+ return false38+ }39+40 return sa === sb && a === b41 }42 43 export const bufferToString = (buffer: ArrayBuffer): string => {6 unmodified linesmodified:src/utils/encode.ts+2 added-2 removed
9 unmodified lines10 11 try {12 return Buffer.from(str).toString('base64')13 } catch (e) {14- console.error('If you want to do "encodeBase64", polyfill "buffer" module.')14+ console.error('Error: If you want to do "encodeBase64", polyfill "buffer" module.')15 throw e16 }17 }18 10 unmodified lines29 30 try {31 return Buffer.from(str, 'base64').toString()32 } catch (e) {33- console.error('If you want to do "decodeBase64", polyfill "buffer" module.')33+ console.error('Error: If you want to do "decodeBase64", polyfill "buffer" module.')34 throw e35 }36 }37 39 unmodified linesdeleted:src/utils/json.test.ts-200 removed
1-import type { JSONArray } from './json'2-import { JSONPathCopy } from './json'3-4-describe('JSONPathCopy', () => {5- const data = {6- post: {7- title: 'Hello',8- author: {9- name: 'Superman',10- age: 20,11- },12- tags: ['foo', 'bar', { framework: 'Hono' }],13- },14- relatedPosts: [15- {16- title: 'HelloWorld',17- author: {18- name: 'The Flash',19- age: 32,20- },21- tags: ['flash', 'marvel'],22- },23- {24- title: 'Hello World',25- author: {26- name: 'Spiderman',27- age: 26,28- },29- tags: ['spider', 'man'],30- },31- {32- title: 'World. Hello!',33- author: {34- name: 'Batman',35- age: 45,36- },37- tags: ['bat', 'man'],38- },39- ],40- releases: [41- {42- code: 'buster',43- amd64: true,44- },45- {46- code: 'stretch',47- amd64: true,48- },49- {50- code: 'potato',51- },52- ],53- nestedArray: [[[1]]],54- }55-56- it('Should return the string or number pointed by JSON Path', () => {57- const dst = {}58- expect(JSONPathCopy(data, dst, 'post.title')).toBe('Hello')59- expect(JSONPathCopy(data, dst, 'post.author.name')).toBe('Superman')60- expect(JSONPathCopy(data, dst, 'post.author.age')).toBe(20)61- expect(JSONPathCopy(data, dst, 'post.tags.0')).toBe('foo')62- expect(JSONPathCopy(data, dst, 'post.tags[0]')).toBe('foo')63- expect(JSONPathCopy(data, dst, 'post.tags.1')).toBe('bar')64- expect(JSONPathCopy(data, dst, 'post.tags[1]')).toBe('bar')65- expect(JSONPathCopy(data, dst, 'post.tags.2.framework')).toBe('Hono')66- expect(JSONPathCopy(data, dst, 'post.tags[2].framework')).toBe('Hono')67- expect(dst).toEqual({68- post: {69- title: 'Hello',70- author: {71- name: 'Superman',72- age: 20,73- },74- tags: ['foo', 'bar', { framework: 'Hono' }],75- },76- })77- })78-79- it('Should return undefined', () => {80- const dst = {}81- expect(JSONPathCopy(data, dst, 'post.foo')).toBe(undefined)82- expect(JSONPathCopy(data, dst, 'post.author.foo')).toBe(undefined)83- expect(JSONPathCopy(data, dst, 'post.tags.3')).toBe(undefined)84- expect(JSONPathCopy(data, dst, 'post.tags[3]')).toBe(undefined)85- expect(dst).toEqual({ post: { author: {}, tags: [] } })86- })87-88- it('Should return objects pointed by JSON Path', () => {89- const dst = {}90- expect(typeof JSONPathCopy(data, dst, 'post')).toBe('object')91- expect(JSONPathCopy(data, dst, 'post.author')).toEqual({ name: 'Superman', age: 20 })92- expect((JSONPathCopy(data, dst, 'post.tags') as JSONArray).length).toBe(3)93- })94-95- it('Should return values of object as array', () => {96- const dst = {}97- expect(JSONPathCopy(data, dst, 'post.author[*]')).toEqual(['Superman', 20])98- expect(dst).toEqual({99- post: {100- author: {101- name: 'Superman',102- age: 20,103- },104- },105- })106- expect(JSONPathCopy(data, dst, 'post.author.[*]')).toEqual(['Superman', 20])107- })108-109- it('Should return an array when targeting fields in arrays of objects', () => {110- const dst = {}111- expect(Array.isArray(JSONPathCopy(data, dst, 'relatedPosts[*].title'))).toBe(true)112- expect(JSONPathCopy(data, dst, 'relatedPosts[*].title')).toEqual([113- 'HelloWorld',114- 'Hello World',115- 'World. Hello!',116- ])117- expect(dst).toEqual({118- relatedPosts: [{ title: 'HelloWorld' }, { title: 'Hello World' }, { title: 'World. Hello!' }],119- })120- })121-122- it('Should return all deeply nested JSON path results', () => {123- let dst = {}124- expect(Array.isArray(JSONPathCopy(data, dst, 'relatedPosts[*].tags[*]'))).toBe(true)125- expect(dst).toEqual({126- relatedPosts: [127- { tags: ['flash', 'marvel'] },128- { tags: ['spider', 'man'] },129- { tags: ['bat', 'man'] },130- ],131- })132- dst = {}133- expect(JSONPathCopy(data, dst, 'relatedPosts[*].tags[*]')).toEqual([134- 'flash',135- 'marvel',136- 'spider',137- 'man',138- 'bat',139- 'man',140- ])141- dst = {}142- expect(JSONPathCopy(data, dst, 'relatedPosts[*].tags[1]')).toEqual(['marvel', 'man', 'man'])143- })144-145- it('Should return only the data that exist if only some of the data have values.', () => {146- const dst = {}147- expect(JSONPathCopy(data, dst, 'releases[*].amd64')).toEqual([true, true])148- })149-150- it('Should return undefined if there is no matching path.', () => {151- const dst = {}152- expect(JSONPathCopy(data, dst, 'post.category')).toEqual(undefined)153- })154-155- it('Should return array of undefined if there is no matching path within array', () => {156- const dst = {}157- expect(JSONPathCopy(data, dst, 'releases[*].i386')).toEqual([undefined, undefined, undefined])158- expect(dst).toEqual({159- releases: [{}, {}, {}],160- })161- })162- it('Should return value from nested array', () => {163- let dst = {}164- expect(JSONPathCopy(data, dst, 'nestedArray.0.0.0')).toBe(1)165- expect(dst).toEqual({166- nestedArray: [[[1]]],167- })168- dst = {}169- expect(JSONPathCopy(data, dst, 'nestedArray[0][0][0]')).toBe(1)170- expect(dst).toEqual({171- nestedArray: [[[1]]],172- })173- })174-175- it('Should merge structured data', () => {176- const dst = {}177- JSONPathCopy(data, dst, 'relatedPosts.0')178- JSONPathCopy(data, dst, 'relatedPosts.1')179- expect(dst).toEqual({180- relatedPosts: [181- {182- title: 'HelloWorld',183- author: {184- name: 'The Flash',185- age: 32,186- },187- tags: ['flash', 'marvel'],188- },189- {190- title: 'Hello World',191- author: {192- name: 'Spiderman',193- age: 26,194- },195- tags: ['spider', 'man'],196- },197- ],198- })199- })200-})deleted:src/utils/json.ts-95 removed
1-export type JSONPrimitive = string | boolean | number | null | undefined2-export type JSONArray = (JSONPrimitive | JSONObject | JSONArray)[]3-export type JSONObject = { [key: string]: JSONPrimitive | JSONArray | JSONObject }4-export type JSONValue = JSONObject | JSONArray | JSONPrimitive5-6-const JSONPathCopyInternal = (7- src: JSONObject,8- dst: JSONObject,9- parts: string[],10- results: JSONArray11-): JSONValue => {12- let srcVal: JSONObject = src13- let dstVal: JSONObject = dst14- const length = parts.length15- for (let i = 0; i < length && srcVal !== undefined && dstVal; i++) {16- const p = parts[i]17-18- if (typeof srcVal !== 'object') {19- return srcVal20- }21-22- if (srcVal === null) {23- return undefined24- }25-26- if (p === '*') {27- const restParts = parts.slice(i + 1)28- const restLength = srcVal.length as number29-30- if (restLength === undefined) {31- parts = Object.keys(srcVal)32- for (const p of parts) {33- const srcVal2 = srcVal34- const dst2: JSONObject = {}35- JSONPathCopyInternal(srcVal2, dst2, [p], results)36- dstVal[p] = dst2[p]37- }38- } else {39- const res = []40- for (let i2 = 0; i2 < restLength; i2++) {41- if (typeof srcVal[i2] !== 'object' || srcVal[i2] === undefined) {42- res.push(srcVal[i2])43- } else {44- const srcVal2 = srcVal[i2] as JSONObject45- const dst2: JSONObject = {}46- const res2 = JSONPathCopyInternal(srcVal2, dst2, restParts, results)47- if (res2 === undefined) results.push(undefined)48- dstVal[i2] = dst249- }50- }51- if (res.length) {52- Object.assign(dstVal, srcVal)53- results.push(...res)54- }55- }56- return results57- }58-59- if (typeof srcVal[p] === 'object') {60- // eslint-disable-next-line @typescript-eslint/ban-ts-comment61- // @ts-ignore62- dstVal[p] ||= new srcVal[p].constructor()63- } else if (typeof srcVal[p] !== 'undefined') {64- dstVal[p] = srcVal[p]65- } else {66- return undefined67- }68-69- srcVal = srcVal[p] as JSONObject70- dstVal = dstVal[p] as JSONObject71- }72-73- if (typeof srcVal === 'object' && dstVal) {74- Object.assign(dstVal, srcVal)75- }76-77- results.push(srcVal)78- return results79-}80-81-export const JSONPathCopy = (src: JSONObject, dst: JSONObject, path: string) => {82- const results: JSONArray = []83- const parts = path.replace(/\.?\[(.*?)\]/g, '.$1').split(/\./)84- try {85- JSONPathCopyInternal(src, dst, parts, results)86- if (results.length === 0) {87- return undefined88- } else if (results.length === 1 && !parts.includes('*')) {89- return results[0]90- }91- return results92- } catch (e) {93- return undefined94- }95-}modified:src/utils/mime.ts+2 added-2 removed
85 unmodified lines86 '3gp': 'video/3gpp',87 '3g2': 'video/3gpp2',88 '7z': 'application/x-7z-compressed',89 gltf: 'model/gltf+json',90- glb: 'model/gltf-binary'91-}90+ glb: 'model/gltf-binary',91+}deleted:src/utils/object.test.ts-25 removed
1-import { mergeObjects } from './object'2-3-describe('mergeObject', () => {4- it('Should merge two objects into one object', () => {5- const src = { author: { name: 'superman' }, posts: [{ id: 123 }, { id: 456 }] }6- const dst = { author: { age: 20 }, posts: [{ title: 'JavaScript' }, { title: 'Framework' }] }7- const res = mergeObjects(dst, src)8- expect(res).toEqual({9- posts: [10- {11- id: 123,12- title: 'JavaScript',13- },14- {15- id: 456,16- title: 'Framework',17- },18- ],19- author: {20- name: 'superman',21- age: 20,22- },23- })24- })25-})deleted:src/utils/object.ts-31 removed
1-/* eslint-disable @typescript-eslint/no-explicit-any */2-export const isObject = (val: any): boolean => val && typeof val === 'object' && !Array.isArray(val)3-4-export const mergeObjects = (target: any, source: any) => {5- const merged = Object.assign({}, target)6- if (isObject(target) && isObject(source)) {7- for (const key of Object.keys(source)) {8- if (isObject(source[key])) {9- if (target[key] === undefined) Object.assign(merged, { [key]: source[key] })10- else merged[key] = mergeObjects(target[key], source[key])11- } else if (Array.isArray(source[key]) && Array.isArray(target[key])) {12- const srcArr = source[key]13- const tgtArr = target[key]14- const outArr = [] as any[]15- for (let i = 0; i < srcArr.length; i += 1) {16- // If corresponding index for both arrays is an object, then merge them17- // Otherwise just copy src arr index into out arr index18- if (isObject(srcArr[i]) && isObject(tgtArr[i])) {19- outArr[i] = mergeObjects(tgtArr[i], srcArr[i])20- } else {21- outArr[i] = srcArr[i]22- }23- }24- Object.assign(merged, { [key]: outArr })25- } else {26- Object.assign(merged, { [key]: source[key] })27- }28- }29- }30- return merged31-}modified:src/utils/url.test.ts+78 added-7 removed
1 import {2 splitPath,3+ splitRoutingPath,4 getPattern,5 getPathFromURL,6 mergePath,7 getQueryStringFromURL,8 checkOptionalParameter,9+ getQueryParam,10+ getQueryParams,11 } from './url'12 13 describe('url', () => {14 it('splitPath', () => {1 unmodified line16 expect(ps).toStrictEqual([''])17 18 ps = splitPath('/hello')19 expect(ps).toStrictEqual(['hello'])20+ })21 22+ it('splitRoutingPath', () => {23+ let ps = splitRoutingPath('/')24+ expect(ps).toStrictEqual([''])25+26+ ps = splitRoutingPath('/hello')27+ expect(ps).toStrictEqual(['hello'])28+18- ps = splitPath('*')29+ ps = splitRoutingPath('*')30 expect(ps).toStrictEqual(['*'])31 21- ps = splitPath('/wildcard-abc/*/wildcard-efg')32+ ps = splitRoutingPath('/wildcard-abc/*/wildcard-efg')33 expect(ps).toStrictEqual(['wildcard-abc', '*', 'wildcard-efg'])34 24- ps = splitPath('/map/:location/events')35+ ps = splitRoutingPath('/map/:location/events')36 expect(ps).toStrictEqual(['map', ':location', 'events'])37+38+ ps = splitRoutingPath('/js/:location{[a-z/]+.js}')39+ expect(ps).toStrictEqual(['js', ':location{[a-z/]+.js}'])40+41+ ps = splitRoutingPath('/users/:name{[0-9a-zA-Z_-]{3,10}}')42+ expect(ps).toStrictEqual(['users', ':name{[0-9a-zA-Z_-]{3,10}}'])43+44+ ps = splitRoutingPath('/users/:@name{[0-9a-zA-Z_-]{3,10}}')45+ expect(ps).toStrictEqual(['users', ':@name{[0-9a-zA-Z_-]{3,10}}'])46+47+ ps = splitRoutingPath('/users/:dept{\\d+}/:@name{[0-9a-zA-Z_-]{3,10}}')48+ expect(ps).toStrictEqual(['users', ':dept{\\d+}', ':@name{[0-9a-zA-Z_-]{3,10}}'])49 })50 51 it('getPattern', () => {52 let res = getPattern(':id')40 unmodified lines93 94 describe('getQueryStringFromURL', () => {95 it('should return strings of query params', () => {96 let queryString = getQueryStringFromURL('https://example.com/?foo=bar')74- expect(queryString).toBe('?foo=bar')97+ expect(queryString).toBe('foo=bar')98 queryString = getQueryStringFromURL('https://example.com/?foo=bar&foo2=bar2')76- expect(queryString).toBe('?foo=bar&foo2=bar2')99+ expect(queryString).toBe('foo=bar&foo2=bar2')100 queryString = getQueryStringFromURL('https://example.com/')101 expect(queryString).toBe('')102 // This specification allows the fragments as query strings103 queryString = getQueryStringFromURL('https://example.com/?#foo=#bar&#foo2=#bar2')81- expect(queryString).toBe('?#foo=#bar&#foo2=#bar2')104+ expect(queryString).toBe('#foo=#bar&#foo2=#bar2')105 // This specification allows that the string includes two `?` or more106 queryString = getQueryStringFromURL('https://example.com/?foo=bar?foo2=bar2')84- expect(queryString).toBe('?foo=bar?foo2=bar2')107+ expect(queryString).toBe('foo=bar?foo2=bar2')108 })109 })110 111 describe('mergePath', () => {37 unmodified lines149 expect(checkOptionalParameter('/api/:animals?/type')).toBeNull()150 expect(checkOptionalParameter('/api/animals/:type?/')).toBeNull()151 })152 })153+154+ describe('getQueryParam', () => {155+ it('Parse URL query strings', () => {156+ expect(getQueryParam('name=hey', 'name')).toBe('hey')157+ expect(getQueryParam('name=hey&age=20&tall=170', 'age')).toBe('20')158+ let searchParams = new URLSearchParams({ name: '炎' })159+ expect(getQueryParam(searchParams.toString(), 'name')).toBe('炎')160+ expect(getQueryParam('name=hey&age=20&tall=170', 'weight')).toBe(null)161+ expect(getQueryParam('name=hey&age=20&tall=170')).toEqual({162+ name: 'hey',163+ age: '20',164+ tall: '170',165+ })166+ expect(getQueryParam('pretty', 'pretty')).toBe('')167+ expect(getQueryParam('pretty', 'prtt')).toBe(null)168+ expect(getQueryParam('name=sam&name=tom', 'name')).toBe('sam')169+ expect(getQueryParam('name=sam&name=tom')).toEqual({170+ name: 'sam',171+ })172+ searchParams = new URLSearchParams('?name=sam=tom')173+ expect(getQueryParam('name', searchParams.get('name')?.toString()))174+ })175+ })176+177+ describe('getQueryParams', () => {178+ it('Parse URL query strings', () => {179+ expect(getQueryParams('name=hey', 'name')).toEqual(['hey'])180+ expect(getQueryParams('name=hey#fragment', 'name')).toEqual(['hey'])181+ expect(getQueryParams('name=hey&name=foo', 'name')).toEqual(['hey', 'foo'])182+ expect(getQueryParams('name=hey&age=20&tall=170', 'age')).toEqual(['20'])183+ expect(getQueryParams('name=hey&age=20&tall=170&name=foo&age=30', 'age')).toEqual([184+ '20',185+ '30',186+ ])187+ const searchParams = new URLSearchParams()188+ searchParams.append('tag', '炎')189+ searchParams.append('tag', 'ほのお')190+ expect(getQueryParams(searchParams.toString(), 'tag')).toEqual(['炎', 'ほのお'])191+ expect(getQueryParams('name=hey&age=20&tall=170', 'weight')).toEqual(null)192+ expect(getQueryParams('name=hey&age=20&tall=170&name=foo&age=30&tall=180')).toEqual({193+ name: ['hey', 'foo'],194+ age: ['20', '30'],195+ tall: ['170', '180'],196+ })197+ expect(getQueryParams('pretty', 'pretty')).toEqual([''])198+ expect(getQueryParams('pretty', 'prtt')).toBe(null)199+ })200+ })201 })modified:src/utils/url.ts+104 added-4 removed
1 export type Pattern = readonly [string, string, RegExp | true] | '*'2 3 export const splitPath = (path: string): string[] => {4- const paths = path.split(/\//) // faster than path.split('/')4+ const paths = path.split('/')5 if (paths[0] === '') {6 paths.shift()7 }8 return paths9 }10 11+export const splitRoutingPath = (path: string): string[] => {12+ const groups: [string, string][] = [] // [mark, original string]13+ for (let i = 0; ; ) {14+ let replaced = false15+ path = path.replace(/\{[^}]+\}/g, (m) => {16+ const mark = `@\\${i}`17+ groups[i] = [mark, m]18+ i++19+ replaced = true20+ return mark21+ })22+ if (!replaced) {23+ break24+ }25+ }26+27+ const paths = path.split('/')28+ if (paths[0] === '') {29+ paths.shift()30+ }31+ for (let i = groups.length - 1; i >= 0; i--) {32+ const [mark] = groups[i]33+ for (let j = paths.length - 1; j >= 0; j--) {34+ if (paths[j].indexOf(mark) !== -1) {35+ paths[j] = paths[j].replace(mark, groups[i][1])36+ break37+ }38+ }39+ }40+41+ return paths42+}43+44 const patternCache: { [key: string]: Pattern } = {}45 export const getPattern = (label: string): Pattern | null => {46 // * => wildcard47 // :id{[0-9]+} => ([0-9]+)20 unmodified lines68 return null69 }70 71 export const getPathFromURL = (url: string, strict: boolean = true): string => {39- const queryIndex = url.indexOf('?')72+ const queryIndex = url.indexOf('?', 8)73 const result = url.substring(url.indexOf('/', 8), queryIndex === -1 ? url.length : queryIndex)74 75 // if strict routing is false => `/hello/hey/` and `/hello/hey` are treated the same76 // default is true4 unmodified lines81 return result82 }83 84 export const getQueryStringFromURL = (url: string): string => {52- const queryIndex = url.indexOf('?')53- const result = queryIndex !== -1 ? url.substring(queryIndex) : ''85+ const queryIndex = url.indexOf('?', 8)86+ const result = queryIndex !== -1 ? url.slice(queryIndex + 1) : ''87 return result88 }89 90 export const mergePath = (...paths: string[]): string => {40 unmodified lines131 const base = match[1]132 const optional = base + match[2]133 return [base, optional]134 }135+136+const removeFragment = (queryString: string): string => {137+ const fragIndex = queryString.indexOf('#')138+ if (fragIndex !== -1) {139+ queryString = queryString.slice(0, fragIndex)140+ }141+ return queryString142+}143+144+// Optimized145+export const getQueryParam = (146+ queryString: string,147+ key?: string148+): string | null | Record<string, string> => {149+ queryString = removeFragment(queryString)150+151+ const results: Record<string, string> = {}152+153+ // eslint-disable-next-line no-constant-condition154+ while (true) {155+ const andIndex = queryString.indexOf('&')156+ let strings = ''157+ if (andIndex === -1) {158+ strings = queryString159+ } else {160+ strings = queryString.substring(0, andIndex)161+ }162+163+ const eqIndex = strings.indexOf('=')164+ if (eqIndex !== -1) {165+ const v = strings.substring(eqIndex + 1)166+ const k = strings.substring(0, eqIndex)167+ if (key === k) {168+ return /\%/.test(v) ? decodeURI(v) : v169+ } else {170+ results[k] ||= v171+ }172+ } else if (strings === key) {173+ return ''174+ }175+176+ if (andIndex === -1) break177+ queryString = queryString.substring(andIndex + 1, queryString.length)178+ }179+180+ if (key) return null181+ return results182+}183+184+export const getQueryParams = (185+ queryString: string,186+ key?: string187+): string[] | null | Record<string, string[]> => {188+ queryString = removeFragment(queryString)189+ const results: Record<string, string[]> = {}190+191+ for (const strings of queryString.split('&')) {192+ let [k, v] = strings.split('=')193+ if (v === undefined) v = ''194+ results[k] ||= []195+ results[k].push(v.indexOf('%') !== -1 ? decodeURI(v) : v)196+ }197+198+ if (key) return results[key] ? results[key] : null199+200+ return results201+}added:src/validator/index.ts+1 added
1+export { validator } from './validator'deleted:src/validator/rule.test.ts-75 removed
1-/* eslint-disable @typescript-eslint/ban-ts-comment */2-import { rule } from './rule'3-4-describe('Rules', () => {5- // string6- test('isEmpty', () => {7- /** @ts-ignore */8- expect(rule.isEmpty()).toBeFalsy()9- expect(rule.isEmpty('')).toBeTruthy()10- expect(rule.isEmpty('abcdef')).toBeFalsy()11- expect(rule.isEmpty('')).toBeTruthy()12- expect(rule.isEmpty(' ')).toBeFalsy()13- expect(rule.isEmpty(' ', { ignore_whitespace: true })).toBeTruthy()14- })15- test('isLength', () => {16- // eslint-disable-next-line @typescript-eslint/ban-ts-comment17- /** @ts-ignore */18- expect(rule.isLength(undefined, { min: 1 })).toBeFalsy()19- expect(rule.isLength('abcde', { min: 1, max: 10 })).toBeTruthy()20- expect(rule.isLength('abcde', { min: 1, max: 4 })).toBeFalsy()21- expect(rule.isLength('abcde', { max: 10 })).toBeTruthy()22- expect(rule.isLength('abcde', { max: 4 })).toBeFalsy()23- expect(rule.isLength('abcde', { min: 10 })).toBeFalsy()24- expect(rule.isLength('abcde', { min: 4 })).toBeTruthy()25- expect(rule.isLength('abcde', 1, 10)).toBeTruthy()26- expect(rule.isLength('abcde', 1, 4)).toBeFalsy()27- })28- test('isAlpha', () => {29- /** @ts-ignore */30- expect(rule.isAlpha()).toBeFalsy()31- expect(rule.isAlpha('abcdef')).toBeTruthy()32- expect(rule.isAlpha('abc123')).toBeFalsy()33- })34- test('isNumeric', () => {35- /** @ts-ignore */36- expect(rule.isNumeric()).toBeFalsy()37- expect(rule.isNumeric('01234')).toBeTruthy()38- expect(rule.isNumeric('012abc')).toBeFalsy()39- })40- test('contains', () => {41- /** @ts-ignore */42- expect(rule.contains()).toBeFalsy()43- expect(rule.contains('barfoobaz', 'foo')).toBeTruthy()44- expect(rule.contains('barfoobaz', 'fooo')).toBeFalsy()45- expect(rule.contains('barfoobaz', 'Foo')).toBeFalsy()46- expect(rule.contains('barfoobaz', 'Foo', { ignoreCase: true })).toBeTruthy()47- })48- test('isIn', () => {49- /** @ts-ignore */50- expect(rule.isIn()).toBeFalsy()51- expect(rule.isIn('foo', ['foo', 'bar'])).toBeTruthy()52- expect(rule.isIn('foo', ['zzz', 'yyy'])).toBeFalsy()53- })54- test('match', () => {55- /** @ts-ignore */56- expect(rule.match()).toBeFalsy()57- expect(rule.match('abcdef', /def$/)).toBeTruthy()58- expect(rule.match('abcdef', /^def$/)).toBeFalsy()59- })60- // number61- test('isGte', () => {62- /** @ts-ignore */63- expect(rule.isGte()).toBeFalsy()64- expect(rule.isGte(20, 10)).toBeTruthy()65- expect(rule.isGte(10, 20)).toBeFalsy()66- expect(rule.isGte(10, 10)).toBeTruthy()67- })68- test('isLte', () => {69- /** @ts-ignore */70- expect(rule.isLte()).toBeFalsy()71- expect(rule.isLte(10, 20)).toBeTruthy()72- expect(rule.isLte(20, 10)).toBeFalsy()73- expect(rule.isLte(10, 10)).toBeTruthy()74- })75-})deleted:src/validator/rule.ts-90 removed
1-// Some validation rules is are based on Validator.js2-// Validator.js3-// License (MIT)4-// Copyright (c) 2018 Chris O'Hara <cohara87@gmail.com>5-// https://github.com/validatorjs/validator.js6-7-export const rule = {8- // string9- isEmpty(10- value: string,11- options: {12- ignore_whitespace: boolean13- } = { ignore_whitespace: false }14- ): boolean {15- if (value === undefined) return false16- return (options.ignore_whitespace ? value.trim().length : value.length) === 017- },18-19- isLength: (20- value: string,21- options: Partial<{ min: number; max: number }> | number,22- arg2?: number23- ) => {24- if (value === undefined) return false25- let min: number26- let max: number | undefined27- if (typeof options === 'object') {28- min = options.min || 029- max = options.max30- } else {31- // backwards compatibility: isLength(str, min [, max])32- min = options || 033- max = arg234- }35- const presentationSequences = value.match(/(\uFE0F|\uFE0E)/g) || []36- const surrogatePairs = value.match(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g) || []37- const len = value.length - presentationSequences.length - surrogatePairs.length38- return len >= min && (typeof max === 'undefined' || len <= max)39- },40-41- isAlpha: (value: string): boolean => {42- if (value === undefined) return false43- return /^[A-Z]+$/i.test(value)44- },45-46- isNumeric: (value: string): boolean => {47- if (value === undefined) return false48- return /^[0-9]+$/.test(value)49- },50-51- contains: (52- value: string,53- elem: string,54- options: Partial<{ ignoreCase: boolean; minOccurrences: number }> = {55- ignoreCase: false,56- minOccurrences: 1,57- }58- ): boolean => {59- if (value === undefined || elem === undefined) return false60- options.ignoreCase ||= false61- options.minOccurrences ||= 162- if (options.ignoreCase) {63- return value.toLowerCase().split(elem.toLowerCase()).length > options.minOccurrences64- }65- return value.split(elem).length > options.minOccurrences66- },67-68- isIn: (value: string, options: string[]): boolean => {69- if (value === undefined) return false70- if (typeof options === 'object') {71- for (const elem of options) {72- if (elem === value) return true73- }74- }75- return false76- },77-78- match: (value: string, regExp: RegExp): boolean => {79- if (value === undefined || regExp === undefined) return false80- return regExp.test(value)81- },82-83- // number84- isGte: (value: number, min: number) => min <= value,85- isLte: (value: number, max: number) => value <= max,86-87- // boolean88- isTrue: (value: boolean) => value === true,89- isFalse: (value: boolean) => value === false,90-}deleted:src/validator/sanitizer.test.ts-7 removed
1-import { sanitizer } from './sanitizer'2-3-describe('Sanitizers', () => {4- test('trim', () => {5- expect(sanitizer.trim(' abc ')).toBe('abc')6- })7-})deleted:src/validator/sanitizer.ts-3 removed
1-export const sanitizer = {2- trim: (value: string) => value.trim(),3-}deleted:src/validator/schema.test.ts-51 removed
1-import type { Expect, Equal } from '../utils/types'2-import type { SchemaToProp } from './schema'3-import type { Validator } from './validator'4-5-describe('SchemaToProp', () => {6- const schema = (v: Validator) => ({7- post: {8- id: v.json('id').asNumber(),9- title: v.json('title'),10- tags: v.array('tags', (v) => ({11- name: v.json('name'),12- numbers: v.json('numbers').asArray().asNumber(),13- strings: v.json('strings').asArray(),14- booleans: v.json('booleans').asBoolean().asArray(),15- })),16- authors: v.json('authors').asArray(),17- meta: v.object('meta', (v) => ({18- currentPage: v.json('currentPage').asNumber(),19- flag: v.json('flag').asBoolean(),20- })),21- },22- })23-24- it('Should return correct types', () => {25- const data = {26- post: {27- id: 1,28- title: 'Hello',29- tags: [30- {31- name: 'Daily',32- numbers: [1, 2, 3],33- strings: ['one', 'two', 'three'],34- booleans: [true, false],35- },36- ],37- authors: ['foo', 'bar'],38- meta: {39- currentPage: 1,40- flag: true,41- },42- },43- }44-45- type T = SchemaToProp<ReturnType<typeof schema>>46- type Data = typeof data47- // eslint-disable-next-line @typescript-eslint/no-unused-vars48- type verify = Expect<Equal<T, Data>>49- expect(true).toBe(true) // Fake50- })51-})deleted:src/validator/schema.ts-47 removed
1-import type {2- VString,3- VNumber,4- VBoolean,5- VObject,6- VArray,7- VNumberArray,8- VStringArray,9- VBooleanArray,10- VBase,11-} from './validator'12-13-export type Schema = {14- [key: string]: VString | VNumber | VBoolean | Schema | VObject<Schema> | VArray<Schema>15-}16-17-type Primitive<T> = T extends VNumberArray18- ? number[]19- : T extends VNumber20- ? number21- : T extends VStringArray22- ? string[]23- : T extends VString24- ? string25- : T extends VBooleanArray26- ? boolean[]27- : T extends VBoolean28- ? boolean29- : T30-31-type P<T> = T extends VArray<infer R>32- ? P<R>[]33- : T extends VObject<infer R>34- ? P<R>35- : {36- [K in keyof T]: T[K] extends VBase37- ? Primitive<T[K]>38- : T[K] extends VArray<infer R>39- ? P<R>[]40- : T[K] extends VObject<infer R>41- ? P<R>42- : T[K] extends Schema43- ? P<T[K]>44- : never45- }46-47-export type SchemaToProp<T> = P<T>modified:src/validator/validator.test.ts+385 added-923 removed
1-import { extendRequestPrototype } from '../request'2-import { Validator } from './validator'1+/* eslint-disable @typescript-eslint/no-unused-vars */2+import type { ZodSchema } from 'zod'3+import { z } from 'zod'4+import type { Context } from '../context'5+import { Hono } from '../hono'6+import type { ExtractSchema } from '../types'7+import type { Equal, Expect } from '../utils/types'8+import { validator } from './validator'9 4-extendRequestPrototype()10+const validatorFunc =11+ <T extends ZodSchema>(schema: T) =>12+ (value: unknown, c: Context) => {13+ const parsed = schema.safeParse(value)14+ if (!parsed.success) {15+ return c.text('Invalid!', 400)16+ }17+ const data = parsed.data as z.infer<T>18+ return data19+ }20 6-describe('Basic - query', () => {7- const v = new Validator()21+describe('Validator middleware', () => {22+ const app = new Hono()23 9- const req = new Request('http://localhost/?q=foo&page=3')24+ const route = app.get(25+ '/search',26+ async (_c, next) => {27+ await next()28+ },29+ validator('query', (value, c) => {30+ if (!value) {31+ return c.text('Invalid!', 400)32+ }33+ }),34+ (c) => {35+ return c.text('Valid!')36+ }37+ )38 11- it('Should be valid - page', async () => {12- const validator = v.query('page').trim().isNumeric()13- expect(validator.type).toBe('string')14- const results = await validator.validate(req)15- expect(results[0].isValid).toBe(true)16- expect(results[0].message).toBeUndefined()17- expect(results[1].isValid).toBe(true)18- expect(results[1].message).toBeUndefined()19- })39+ type Expected = {40+ '/search': {41+ $get: {42+ input: {43+ query: undefined44+ }45+ output: {}46+ }47+ }48+ }49 21- it('Should be invalid - q', async () => {22- const validator = v.query('q').isRequired().asNumber()23- expect(validator.type).toBe('number')24- const results = await validator.validate(req)25- expect(results[0].isValid).toBe(false)26- const messages = [27- 'Invalid Value [foo]: the query parameter "q" is invalid - should be "number"',28- ]29- expect(results[0].message).toBe(messages.join('\n'))30- })50+ type Actual = ExtractSchema<typeof route>51 32- it('Should be invalid - q2', async () => {33- const validator = v.query('q2').isRequired()34- const results = await validator.validate(req)35- expect(results[0].isValid).toBe(false)36- let messages = [37- 'Invalid Value [undefined]: the query parameter "q2" is invalid - should be "string"',38- ]39- expect(results[0].message).toBe(messages.join('\n'))40- expect(results[1].isValid).toBe(false)41- messages = ['Invalid Value [undefined]: the query parameter "q2" is invalid - isRequired']42- expect(results[1].message).toBe(messages.join('\n'))43- })44-})52+ type verify = Expect<Equal<Expected, Actual>>53 46-describe('Basic - queries', () => {47- const v = new Validator()48-49- const req = new Request('http://localhost/?tag=foo&tag=bar&id=123&id=456')50-51- it('Should be valid - tag', async () => {52- const validator = v.queries('tag').isRequired()53- const results = await validator.validate(req)54- expect(results[0].isValid).toBe(true)55- expect(results[0].message).toBeUndefined()56- expect(results[0].value).toEqual(['foo', 'bar'])57- expect(results[1].isValid).toBe(true)58- expect(results[1].message).toBeUndefined()54+ it('Should return 200 response', async () => {55+ const res = await app.request('http://localhost/search?q=foo')56+ expect(res.status).toBe(200)57 })58 61- it('Should be invalid - ids', async () => {62- const validator = v.queries('ids').isRequired()63- const results = await validator.validate(req)64- expect(results[0].isValid).toBe(true)65- expect(results[1].isValid).toBe(false)66- expect(results[1].message).toBe(67- 'Invalid Value []: the query parameters "ids" is invalid - isRequired'68- )59+ it('Should return 400 response', async () => {60+ const res = await app.request('http://localhost/search')61+ expect(res.status).toBe(200)62 })70-71- it('Should be valid - id', async () => {72- const validator = v.queries('id').isNumeric()73- const results = await validator.validate(req)74- expect(results[0].isValid).toBe(true)75- expect(results[0].message).toBeUndefined()76- expect(results[1].isValid).toBe(true)77- expect(results[1].message).toBeUndefined()78- })79-80- it('Should be valid - comment is options', async () => {81- const validator = v.queries('comment').isOptional()82- const results = await validator.validate(req)83- expect(results[0].isValid).toBe(true)84- expect(results[0].message).toBeUndefined()85- expect(results[1].isValid).toBe(true)86- expect(results[1].message).toBeUndefined()87- })63 })64 90-describe('Basic - header', () => {91- const v = new Validator()65+describe('Malformed JSON', () => {66+ const app = new Hono()67 93- const req = new Request('http://localhost/', {94- headers: {95- 'x-message': 'hello world!',96- 'x-number': '12345',97- },98- })68+ app.post(69+ '/post',70+ validator('json', (value, c) => {}),71+ (c) => {72+ return c.text('Valid!')73+ }74+ )75 100- it('Should be valid - x-message', async () => {101- const validator = v.header('x-message').isRequired().contains('Hello', { ignoreCase: true })102- const results = await validator.validate(req)103- expect(results[0].isValid).toBe(true)104- expect(results[0].message).toBeUndefined()105- expect(results[1].isValid).toBe(true)106- expect(results[1].message).toBeUndefined()107- expect(results[2].isValid).toBe(true)108- expect(results[2].message).toBeUndefined()76+ it('Should return 400 response', async () => {77+ const res = await app.request('http://localhost/post', {78+ method: 'POST',79+ })80+ expect(res.status).toBe(400)81 })110-111- it('Should be invalid - x-number', async () => {112- const validator = v.header('x-number').isEqual(12345)113- const results = await validator.validate(req)114- expect(results[0].isValid).toBe(true)115- expect(results[1].isValid).toBe(false)116- const messages = ['Invalid Value [12345]: the request header "x-number" is invalid - isEqual']117- expect(results[1].message).toBe(messages.join('\n'))118- })82 })83 121-describe('Basic - body', () => {122- const v = new Validator()84+describe('Validator middleware with Zod validates JSON', () => {85+ const app = new Hono()86 124- const body = new FormData()125- body.append('title', ' abcdef ')126- body.append('title2', 'abcdef')127- const req = new Request('http://localhost/', {128- method: 'POST',129- body: body,87+ const schema = z.object({88+ id: z.number(),89+ title: z.string(),90 })91 132- it('Should be valid - title', async () => {133- const validator = v.body('title').trim().isLength({ max: 10 }).isRequired()134- const results = await validator.validate(req)135- expect(results[0].isValid).toBe(true)136- expect(results[0].message).toBeUndefined()137- expect(results[1].isValid).toBe(true)138- expect(results[1].message).toBeUndefined()139- expect(results[2].isValid).toBe(true)140- expect(results[2].message).toBeUndefined()92+ const route = app.post('/post', validator('json', validatorFunc(schema)), (c) => {93+ const post = c.req.valid('json')94+ type Expected = {95+ id: number96+ title: string97+ }98+ type verify = Expect<Equal<Expected, typeof post>>99+ return c.jsonT({100+ post: post,101+ })102 })103 143- it('Should be invalid - title2', async () => {144- const validator = v.body('title2').isLength({ max: 5 })145- const results = await validator.validate(req)146- expect(results[0].isValid).toBe(true)147- expect(results[0].message).toBeUndefined()148- expect(results[1].isValid).toBe(false)149- const messages = ['Invalid Value [abcdef]: the request body "title2" is invalid - isLength']150- expect(results[1].message).toBe(messages.join('\n'))151- })152-})153-154-describe('Basic - JSON', () => {155- const v = new Validator()156-157- const post = {158- id: 1234,159- title: 'This is title',160- author: {161- name: 'Superman',162- age: 20,163- },104+ type Expected = {105+ '/post': {106+ $post: {107+ input: {108+ json: {109+ id: number110+ title: string111+ }112+ }113+ output: {114+ post: {115+ id: number116+ title: string117+ }118+ }119+ }120+ }121 }122 166- const req = new Request('http://localhost/', {167- method: 'POST',168- body: JSON.stringify(post),169- })123+ type Actual = ExtractSchema<typeof route>124 171- it('Should be valid - id', async () => {172- const validator = v.json('id').asNumber().isEqual(1234)173- const results = await validator.validate(req)174- expect(results[0].isValid).toBe(true)175- expect(results[0].message).toBeUndefined()176- expect(results[1].isValid).toBe(true)177- expect(results[1].message).toBeUndefined()178- })125+ type verify2 = Expect<Equal<Expected, Actual>>126 180- it('Should be valid - author.name', async () => {181- const validator = v.json('author.name').isIn(['Ultra man', 'Superman'])182- const results = await validator.validate(req)183- expect(results[0].isValid).toBe(true)184- expect(results[0].message).toBeUndefined()185- expect(results[1].isValid).toBe(true)186- expect(results[1].message).toBeUndefined()127+ it('Should validate JSON and return 200 response', async () => {128+ const res = await app.request('http://localhost/post', {129+ method: 'POST',130+ body: JSON.stringify({131+ id: 123,132+ title: 'Hello',133+ }),134+ })135+ expect(res.status).toBe(200)136+ expect(await res.json()).toEqual({137+ post: {138+ id: 123,139+ title: 'Hello',140+ },141+ })142 })143 189- it('Should be invalid - author.age', async () => {190- const validator = v.json('author.age').asNumber().isLte(10)191- const results = await validator.validate(req)192- expect(results[0].isValid).toBe(true)193- expect(results[1].isValid).toBe(false)194- const messages = ['Invalid Value [20]: the JSON body "author.age" is invalid - isLte']195- expect(results[1].message).toBe(messages.join('\n'))144+ it('Should validate JSON and return 400 response', async () => {145+ const res = await app.request('http://localhost/post', {146+ method: 'POST',147+ body: JSON.stringify({148+ id: '123',149+ title: 'Hello',150+ }),151+ })152+ expect(res.status).toBe(400)153+ expect(await res.text()).toBe('Invalid!')154 })155 })156 199-describe('Handle required values', () => {200- const v = new Validator()157+describe('Validator middleware with Zod validates Form data', () => {158+ const app = new Hono()159 202- const req = new Request('http://localhost/', {203- method: 'POST',204- body: JSON.stringify({ comment: null, name: 'John', admin: false }),160+ const schema = z.object({161+ id: z.string(),162+ title: z.string(),163 })206-207- it('Should be valid - `name` is required', async () => {208- const validator = v.json('name').isRequired()209- const results = await validator.validate(req)210- expect(results[0].isValid).toBe(true)211- expect(results[1].isValid).toBe(true)164+ app.post('/post', validator('form', validatorFunc(schema)), (c) => {165+ const post = c.req.valid('form')166+ return c.jsonT({167+ post: post,168+ })169 })170 214- it('Should be invalid - `comment` is required but missing', async () => {215- const validator = v.json('comment').isRequired()216- const results = await validator.validate(req)217- expect(results[0].isValid).toBe(false)218- expect(results[1].isValid).toBe(false)171+ it('Should validate Form data and return 200 response', async () => {172+ const form = new FormData()173+ form.append('id', '123')174+ form.append('title', 'Hello')175+ const res = await app.request('http://localhost/post', {176+ method: 'POST',177+ body: form,178+ })179+ expect(res.status).toBe(200)180+ expect(await res.json()).toEqual({181+ post: {182+ id: '123',183+ title: 'Hello',184+ },185+ })186 })187 221- it('Should be valid - `admin` is required and present, although falsy', async () => {222- const validator = v.json('admin').asBoolean().isRequired()223- const results = await validator.validate(req)224- expect(results[0].isValid).toBe(true)225- expect(results[1].isValid).toBe(true)226- expect(results[1].value).toBe(false)227- })228-})229-230-describe('Handle optional values', () => {231- it('Should be valid - `comment` is optional', async () => {232- const v = new Validator()233- const req = new Request('http://localhost/', {188+ it('Should validate Form data and return 400 response', async () => {189+ const res = await app.request('http://localhost/post', {190 method: 'POST',191 })236- const validator = v.body('comment').isOptional()237- const results = await validator.validate(req)238- expect(results[0].isValid).toBe(true)192+ expect(res.status).toBe(400)193+ expect(await res.text()).toBe('Invalid!')194 })240- it('Should be valid - "isNumeric" but "isOptional"', async () => {241- const v = new Validator()242- const validator = v.query('page').isNumeric().isOptional()243- const req = new Request('http://localhost/')244- const results = await validator.validate(req)245- expect(results[0].isValid).toBe(true)246- expect(results[1].isValid).toBe(true)247- expect(results[1].message).toBeUndefined()248- })195 })196 251-describe('Handling types error', () => {252- const v = new Validator()197+describe('Validator middleware with Zod validates query params', () => {198+ const app = new Hono()199 254- const post = {255- id: '1234',256- title: 'This is title',257- published: 'true',258- }200+ const schema = z.object({201+ page: z202+ .string()203+ .refine((v) => {204+ return !isNaN(Number(v))205+ })206+ .transform((v) => {207+ return Number(v)208+ }),209+ })210 260- const req = new Request('http://localhost/', {261- method: 'POST',262- body: JSON.stringify(post),211+ app.get('/search', validator('query', validatorFunc(schema)), (c) => {212+ const res = c.req.valid('query')213+ return c.jsonT({214+ page: res.page,215+ })216 })217 265- it('Should be invalid - "1234" is not number', async () => {266- const validator = v.json('id').asNumber().isEqual(1234)267- const results = await validator.validate(req)268- expect(results[0].isValid).toBe(false)269- const messages = ['Invalid Value [1234]: the JSON body "id" is invalid - should be "number"']270- expect(results[0].message).toBe(messages.join('\n'))218+ it('Should validate query params and return 200 response', async () => {219+ const res = await app.request('http://localhost/search?page=123')220+ expect(res.status).toBe(200)221+ expect(await res.json()).toEqual({222+ page: 123,223+ })224 })225 273- it('Should be invalid - "true" is not boolean', async () => {274- const validator = v.json('published').asBoolean()275- const results = await validator.validate(req)276- expect(results[0].isValid).toBe(false)277- const messages = [278- 'Invalid Value [true]: the JSON body "published" is invalid - should be "boolean"',279- ]280- expect(results[0].message).toBe(messages.join('\n'))226+ it('Should validate query params and return 400 response', async () => {227+ const res = await app.request('http://localhost/search?page=onetwothree')228+ expect(res.status).toBe(400)229+ expect(await res.text()).toBe('Invalid!')230 })231 })232 284-describe('Handle array paths', () => {285- const v = new Validator()233+describe('Validator middleware with Zod validates queries params', () => {234+ const app = new Hono()235 287- const body = {288- posts: [289- {290- id: 12411,291- title: 'This is title #1',292- published: true,293- rating: [true, 'cool'],294- awesome: true,295- testing: false,296- },297- {298- id: 12412,299- title: 'This is title #2',300- published: true,301- rating: [false],302- awesome: 'true',303- testing: true,304- },305- {306- id: 12413,307- title: 'This is title #3',308- published: false,309- rating: [true, 'lame'],310- awesome: false,311- },312- ],313- }314-315- const req = new Request('http://localhost/', {316- method: 'POST',317- body: JSON.stringify(body),236+ const schema = z.object({237+ tags: z.array(z.string()),238 })239 320- it('Should validate targeted path in array', async () => {321- const validator = v.json('posts[*].published').asArray().asBoolean().isRequired()322- const results = await validator.validate(req)323- expect(results[0].isValid).toBe(true)324- expect(results[1].isValid).toBe(true)325- expect(results[1].message).toBeUndefined()326- expect(results[1].value).toEqual([true, true, false])240+ app.get('/posts', validator('queries', validatorFunc(schema)), (c) => {241+ const res = c.req.valid('queries')242+ return c.jsonT({243+ tags: res.tags,244+ })245 })246 329- it('Should allow nested array paths', async () => {330- const validator = v.json('posts[*].rating[0]').asArray().asBoolean().isRequired()331- const results = await validator.validate(req)332- expect(results[0].isValid).toBe(true)333- expect(results[1].isValid).toBe(true)334- expect(results[1].message).toBeUndefined()335- expect(results[1].value).toEqual([true, false, true])247+ it('Should validate queries params and return 200 response', async () => {248+ const res = await app.request('http://localhost/posts?tags=book&tags=movie')249+ expect(res.status).toBe(200)250+ expect(await res.json()).toEqual({251+ tags: ['book', 'movie'],252+ })253 })254 338- it('Should allow optional array paths', async () => {339- const validator = v.json('posts[*].rating[1]').asArray().isOptional()340- const results = await validator.validate(req)341- expect(results[0].isValid).toBe(true)342- expect(results[1].isValid).toBe(true)343- expect(results[1].message).toBeUndefined()344- expect(results[1].value).toEqual(['cool', undefined, 'lame'])255+ it('Should validate queries params and return 400 response', async () => {256+ const res = await app.request('http://localhost/posts')257+ expect(res.status).toBe(400)258+ expect(await res.text()).toBe('Invalid!')259 })260+})261 347- it('Should provide error with invalid array paths', async () => {348- const validator = v.json('posts[*].rating[3]').asArray()349- const results = await validator.validate(req)350- expect(results[0].isValid).toBe(false)351- const messages = [352- 'Invalid Value [undefined, undefined, undefined]: the JSON body "posts[*].rating[3]" is invalid - should be "string[]"',353- ]354- expect(results[0].message).toBe(messages.join('\n'))355- expect(results[0].value).toEqual([undefined, undefined, undefined])356- })357-358- it('Should prevent invalid types within array', async () => {359- const validator = v.json('posts[*].awesome').asArray().asBoolean()360- const results = await validator.validate(req)361- expect(results[0].isValid).toBe(false)362- const messages = [363- 'Invalid Value [true, "true", false]: the JSON body "posts[*].awesome" is invalid - should be "boolean[]"',364- ]365- expect(results[0].message).toBe(messages.join('\n'))366- expect(results[0].value).toEqual([true, 'true', false])367- })368-369- it('Should allow undefined values when optional', async () => {370- const validator = v.json('posts[*].testing').asArray().asBoolean().isOptional()371- const results = await validator.validate(req)372- expect(results[0].isValid).toBe(true)373- expect(results[0].value).toEqual([false, true, undefined])374- })375-376- ;[undefined, []].forEach(value => {377- it(`Should allow ${value === undefined ? 'undefined' : 'empty'} arrays when optional`, async () => {378- const req = new Request('http://localhost/', {379- method: 'POST',380- body: JSON.stringify({ blog: {381- ...(value === undefined ? {} : { posts: [] })382- } }),262+describe('Validator middleware with Zod multiple validators', () => {263+ const app = new Hono<{ Variables: { id: number } }>()264+ const route = app.post(265+ '/posts',266+ validator('query', (value, c) => {267+ const id = c.get('id')268+ type verify = Expect<Equal<number, typeof id>>269+ const schema = z.object({270+ page: z271+ .string()272+ .refine((v) => {273+ return !isNaN(Number(v))274+ })275+ .transform((v) => {276+ return Number(v)277+ }),278 })384- const vObject = v.object('blog', v => ({385- posts: v.array('posts', v => ({386- id: v.json('id').asNumber().isOptional(),387- title: v.json('title').isOptional(),388- author: v.object('author', v => ({389- name: v.json('name'),390- })).isOptional()391- })).isOptional(),392- highlightedPostId: v.json('highlightedPostId').asNumber(),393- }))394- for (const validator of vObject.getValidators()) {395- const results = await validator.validate(req)396- expect(results[0].isValid).toBe(true)397- expect(results[0].message).toBeUndefined()279+ const parsed = schema.safeParse(value)280+ if (!parsed.success) {281+ return c.text('Invalid!', 400)282 }399- })400- })401-})283+ const data = parsed.data as z.infer<typeof schema>284+ return data285+ }),286+ validator('form', (value, c) => {287+ const id = c.get('id')288+ type verify = Expect<Equal<number, typeof id>>289+ const schema = z.object({290+ title: z.string(),291+ })292+ const parsed = schema.safeParse(value)293+ if (!parsed.success) {294+ return c.text('Invalid!', 400)295+ }296+ const data = parsed.data as z.infer<typeof schema>297+ return data298+ }),299+ (c) => {300+ const id = c.get('id')301+ type verify = Expect<Equal<number, typeof id>>302+ const formValidatedData = c.req.valid('form')303+ type verify2 = Expect<Equal<{ title: string }, typeof formValidatedData>>304+ const { page } = c.req.valid('query')305+ const { title } = c.req.valid('form')306+ return c.jsonT({ page, title })307+ }308+ )309 403-describe('Validate with asArray', () => {404- const v = new Validator()405- const json = {406- post: {407- title: ['Hello'],408- flags: [true, false],409- published: [true],410- comments: [411- {412- title: 'abc',413- author: 'John',414- category: 'Heroes',415- flags: [true, false],416- },417- {418- title: 'def',419- author: 'Dave',420- flags: [false, true],421- },422- ],423- },424- pager: {425- prev: true,426- },310+ type Actual = ExtractSchema<typeof route>311+312+ type Expected = {313+ '/posts': {314+ $post: {315+ input: {316+ query: {317+ page: number318+ }319+ } & {320+ form: {321+ title: string322+ }323+ }324+ output: {325+ page: number326+ title: string327+ }328+ }329+ }330 }331 429- const req = new Request('http://localhost/', {430- method: 'POST',431- body: JSON.stringify(json),432- })332+ type verify = Expect<Equal<Expected, Actual>>333 434- it('Should validate array values', async () => {435- const validator = v.json('post.title').asArray().isAlpha()436- const results = await validator.validate(req)437- expect(results[0].isValid).toBe(true)438- expect(results[1].isValid).toBe(true)439- })440-441- it('Should validate array values - specify with `*`', async () => {442- const validator = v.json('post.comments[*].title').asArray().isAlpha()443- const results = await validator.validate(req)444- expect(results[0].isValid).toBe(true)445- expect(results[1].isValid).toBe(true)446- })447-448- it('Should return the same result for `.asArray().as{Type}()` and `.as{Type}().asArray()', async () => {449- const validator1 = v.json('post.flags').asArray().asBoolean().isRequired()450- const validator2 = v.json('post.flags').asBoolean().asArray().isRequired()451- const res1 = await validator1.validate(req)452- const res2 = await validator2.validate(req)453-454- expect(res1[0].isValid).toBe(true)455- expect(res1[0].message).toBeUndefined()456- expect(res1[0].value).toEqual([true, false])457- expect(res1[1].isValid).toBe(true)458-459- // Entire responses should be equal460- expect(res1).toEqual(res2)461- })462-463- it('Should fail validation if value is array but `.asArray()` not called', async () => {464- const validator = v.json('post.flags').asBoolean().isRequired()465- const results = await validator.validate(req)466- expect(results[0].isValid).toBe(false)467- const messages = [468- 'Invalid Value [true, false]: the JSON body "post.flags" is invalid - should be "boolean"',469- ]470- expect(results[0].message).toBe(messages.join('\n'))471- expect(results[0].value).toEqual([true, false])472- expect(results[1].isValid).toBe(true)473- })474-475- it('Should pass validation if `isRequired` and path has no missing entries', async () => {476- const validator = v.json('post.comments[*].author').asArray().isRequired()477- const results = await validator.validate(req)478- expect(results[0].isValid).toBe(true)479- expect(results[1].isValid).toBe(true)480- })481-482- it('Should fail validation if `isRequired` and missing entry for path', async () => {483- const validator = v.json('post.comments[*].heroes').asArray().isRequired()484- const results = await validator.validate(req)485- expect(results[0].isValid).toBe(false)486- let messages = [487- 'Invalid Value [undefined, undefined]: the JSON body "post.comments[*].heroes" is invalid - should be "string[]"',488- ]489- expect(results[0].message).toBe(messages.join('\n'))490- expect(results[1].isValid).toBe(false)491- messages = [492- 'Invalid Value [undefined, undefined]: the JSON body "post.comments[*].heroes" is invalid - isRequired',493- ]494- expect(results[1].message).toBe(messages.join('\n'))495- })496-497- it('Should fail validation if value is not array but `asArray` is set', async () => {498- const validator = v.json('pager.prev').asBoolean().asArray()499- const results = await validator.validate(req)500- expect(results[0].isValid).toBe(false)501- const messages = [502- 'Invalid Value [true]: the JSON body "pager.prev" is invalid - should be "boolean[]"',503- ]504- expect(results[0].message).toBe(messages.join('\n'))505- })506-})507-508-describe('Invalid HTTP request handling', () => {509- const v = new Validator()510-511- it('Should throw malformed error when JSON body absent', async () => {512- const req = new Request('http://localhost/', {334+ it('Should validate both query param and form data and return 200 response', async () => {335+ const form = new FormData()336+ form.append('title', 'Hello')337+ const res = await app.request('http://localhost/posts?page=2', {338 method: 'POST',339+ body: form,340 })515-516- let error517- try {518- const validator = v.json('post.title').isRequired()519- await validator.validate(req)520- } catch (e) {521- error = e522- }523- expect(error instanceof Error).toBe(true)524- expect((error as Error).message).toBe('Malformed JSON in request body')341+ expect(res.status).toBe(200)342+ expect(await res.json()).toEqual({343+ page: 2,344+ title: 'Hello',345+ })346 })347 527- it('Should throw malformed error when a JSON body is not valid JSON', async () => {528- const req = new Request('http://localhost/', {348+ it('Should validate both query param and form data and return 400 response', async () => {349+ const res = await app.request('http://localhost/posts?page=2', {350 method: 'POST',530- body: 'Not json!',351 })532-533- let error534- try {535- const validator = v.json('post.title').isRequired()536- await validator.validate(req)537- } catch (e) {538- error = e539- }540- expect(error instanceof Error).toBe(true)541- expect((error as Error).message).toBe('Malformed JSON in request body')352+ expect(res.status).toBe(400)353+ expect(await res.text()).toBe('Invalid!')354 })355 })356 545-describe('Nested objects', () => {546- const json = {547- posts: [548- {549- id: 123,550- title: 'JavaScript',551- authors: [552- {553- name: 'Superman',554- age: 20,555- like: {556- food: 'fish',557- },558- },559- ],560- tags: [561- {562- name: 'Node.js',563- },564- {565- name: 'Deno',566- },567- {568- name: 'Bun',569- },570- ],571- },572- {573- id: 456,574- title: 'Framework',575- tags: [576- {577- name: 'Hono',578- },579- {580- name: 'Express',581- },582- ],583- },584- ],585- pager: {586- prev: true,587- next: false,588- meta: {589- perPage: 10,590- pages: [591- {592- num: 1,593- },594- ],595- },596- },597- }357+describe('With path parameters', () => {358+ const app = new Hono()359 599- const req = new Request('http://localhost/', {600- method: 'POST',601- body: JSON.stringify(json),602- })603-604- it('Should validate nested array values', async () => {605- const v = new Validator()606- const vArray = v.array('posts', (v) => ({607- id: v.json('id').asNumber(),608- title: v.json('title'),609- authors: v610- .array('authors', (v) => ({611- name: v.json('name'),612- age: v.json('age').asNumber(),613- like: v.object('like', (v) => ({614- food: v.json('food').isRequired(),615- })),616- }))617- .isOptional(),618- tags: v619- .array('tags', (v) => ({620- name: v.json('name'),621- }))622- .isOptional(),623- }))624- for (const validator of vArray.getValidators()) {625- const results = await validator.validate(req)626- expect(results[0].isValid).toBe(true)627- expect(results[0].message).toBeUndefined()360+ const route = app.put(361+ '/posts/:id',362+ validator('form', () => {363+ return {364+ title: 'Foo',365+ }366+ }),367+ (c) => {368+ return c.text('Valid!')369 }629- })370+ )371 631- it('Should validate nested object values', async () => {632- const v = new Validator()633- const vObject = v.object('pager', (v) => ({634- prev: v.json('prev').asBoolean(),635- next: v.json('next').asBoolean(),636- meta: v.object('meta', (v) => ({637- totalCount: v.json('perPage').asNumber(),638- pages: v.array('pages', (v) => ({639- num: v.json('num').asNumber(),640- })),641- })),642- }))643-644- for (const validator of vObject.getValidators()) {645- const results = await validator.validate(req)646- expect(results[0].isValid).toBe(true)647- expect(results[0].message).toBeUndefined()648- }649- })650-651- it('Should validate nested array values', async () => {652- let v = new Validator()653- const vArray = v.array('posts', (v) => ({654- id: v.json('id'),655- }))656-657- for (const validator of vArray.getValidators()) {658- const results = await validator.validate(req)659- expect(results[0].isValid).toBe(false)660- const messages = [661- 'Invalid Value [123, 456]: the JSON body "posts.[*].id" is invalid - should be "string[]"',662- ]663- expect(results[0].message).toBe(messages.join('\n'))664- }665-666- v = new Validator()667- const vArray2 = v.array('posts', (v) => ({668- optionalProperty: v.json('optional-property').isOptional(),669- }))670- for (const validator of vArray2.getValidators()) {671- const results = await validator.validate(req)672- expect(results[0].isValid).toBe(true)673- expect(results[0].message).toBeUndefined()674- }675- })676-677- it('Should validate nested array values with `isOptional`', async () => {678- const v = new Validator()679- const vArray = v.array('posts', (v) => ({680- title: v.json('optional-title').isOptional(),681- comments: v682- .array('comments', (v) => ({683- body: v.json('body'),684- }))685- .isOptional(),686- }))687-688- for (const validator of vArray.getValidators()) {689- const results = await validator.validate(req)690- expect(results[0].isValid).toBe(true)691- expect(results[0].message).toBeUndefined()692- }693-694- const vArray2 = v695- .array('posts', (v) => ({696- title: v.json('title').asNumber(),697- }))698- .isOptional()699-700- for (const validator of vArray2.getValidators()) {701- const results = await validator.validate(req)702- expect(results[0].isValid).toBe(false)703- const messages = [704- 'Invalid Value ["JavaScript", "Framework"]: the JSON body "posts.[*].title" is invalid - should be "number[]"',705- ]706- expect(results[0].message).toBe(messages.join('\n'))707- }708- })709-710- it('Should validate nested object values with `isOptional`', async () => {711- const v = new Validator()712- const vObject = v.object('pager', (v) => ({713- current: v.json('optional-value').isOptional(),714- method: v715- .object('method', (v) => ({716- name: v.json('name'),717- }))718- .isOptional(),719- }))720-721- for (const validator of vObject.getValidators()) {722- const results = await validator.validate(req)723- expect(results[0].isValid).toBe(true)724- expect(results[0].message).toBeUndefined()725- }726- })727-728- it('Should only allow `v.json()` in nested array or object', async () => {729- const v = new Validator()730- const vArray = v.array('posts', (v) => ({731- id: v.header('id').asNumber().isRequired(),732- }))733-734- for (const validator of vArray.getValidators()) {735- const results = await validator.validate(req)736- expect(results[0].isValid).toBe(false)737- const messages = [738- 'Invalid Value [undefined]: the request header "id" is invalid - should be "number"',739- ]740- expect(results[0].message).toBe(messages.join('\n'))741- }742-743- const vObject = v.object('pager', (v) => ({744- prev: v.query('prev').asBoolean(),745- next: v.body('next').asBoolean(),746- }))747-748- const messages = [749- 'Invalid Value [undefined]: the query parameter "prev" is invalid - should be "boolean"',750- 'Invalid Value [undefined]: the request body "next" is invalid - should be "boolean"',751- ]752-753- for (const [i, validator] of vObject.getValidators().entries()) {754- const results = await validator.validate(req)755- expect(results[0].isValid).toBe(false)756- expect(results[0].message).toBe(`${messages[i]}`)757- }758- })759-760- const blogJson = {761- blog: {762- totalPosts: '3',763- meta: {764- foo: {765- bar: 'test',372+ type Expected = {373+ '/posts/:id': {374+ $put: {375+ input: {376+ form: {377+ title: string378+ }379+ } & {380+ param: {381+ id: string382+ }383 }767- },768- posts: [769- {770- id: 123,771- title: 'JavaScript',772- author: {773- name: 'foo',774- },775- publisher: {776- name: 'Foo',777- },778- },779- {780- id: '456',781- title: 'Framework',782- author: {783- name: 'bar',784- },785- publisher: {786- name: 'Bar',787- },788- },789- {790- id: 789,791- title: 'Hono',792- author: {793- name: 'baz',794- },795- publisher: {796- name: 'Baz',797- },798- },799- ],800- highlightedPostId: '123',384+ output: {}385+ }386 }387 }388 804- it('Should threat `v.json()` as a nested array type only inside an array', async () => {805- const req = new Request('http://localhost/', {806- method: 'POST',807- body: JSON.stringify(blogJson),808- })389+ type Actual = ExtractSchema<typeof route>390+ type verify = Expect<Equal<Expected, Actual>>391+})392 810- const v = new Validator()811- const vObject = v.object('blog', v => ({812- totalPosts: v.json('totalPosts').asNumber(),813- posts: v.array('posts', v => ({814- id: v.json('id').asNumber(),815- title: v.json('title'),816- author: v.object('author', v => ({817- name: v.json('name'),818- }))819- })),820- highlightedPostId: v.json('highlightedPostId').asNumber(),821- }))393+describe('`on`', () => {394+ const app = new Hono()395 823- const validators = vObject.getValidators()824-825- const totalPostsResult = await validators[0].validate(req)826- expect(totalPostsResult[0].isValid).toBe(false)827- expect(totalPostsResult[0].message).toBe('Invalid Value [3]: the JSON body "blog.totalPosts" is invalid - should be "number"')828-829- const postsIdResult = await validators[1].validate(req)830- expect(postsIdResult[0].isValid).toBe(false)831- expect(postsIdResult[0].message).toBe('Invalid Value [123, "456", 789]: the JSON body "blog.posts.[*].id" is invalid - should be "number[]"')832-833- const postsTitleResult = await validators[2].validate(req)834- expect(postsTitleResult[0].isValid).toBe(true)835-836- const postAuthorResult = await validators[3].validate(req)837- expect(postAuthorResult[0].isValid).toBe(true)838-839- const highlightedPostResult = await validators[4].validate(req)840- expect(highlightedPostResult[0].isValid).toBe(false)841- expect(highlightedPostResult[0].message).toBe('Invalid Value [123]: the JSON body "blog.highlightedPostId" is invalid - should be "number"')842- })843-844- it('Should correctly handle sequences of nested objects inside an array', async () => {845- const req = new Request('http://localhost/', {846- method: 'POST',847- body: JSON.stringify(blogJson),848- })849-850- const v = new Validator()851- const vObject = v.object('blog', v => ({852- posts: v.array('posts', v => ({853- author: v.object('author', v => ({854- name: v.json('name'),855- })),856- publisher: v.object('publisher', v => ({857- name: v.json('name'),858- }))859- })),860- }))861-862- for (const validator of vObject.getValidators()) {863- const results = await validator.validate(req)864- expect(results[0].isValid).toBe(true)865- expect(results[0].message).toBeUndefined()396+ const route = app.on(397+ 'PURGE',398+ '/purge',399+ validator('form', () => {400+ return {401+ tag: 'foo',402+ }403+ }),404+ validator('query', () => {405+ return {406+ q: 'bar',407+ }408+ }),409+ (c) => {410+ return c.jsonT({411+ success: true,412+ })413 }867- })414+ )415 869- it('Should correctly handle values inside objects and arrays', async () => {870- const req = new Request('http://localhost/', {871- method: 'POST',872- body: JSON.stringify(blogJson),873- })874-875- const v = new Validator()876- const vObject = v.object('blog', (v) => ({877- meta: v.object('meta', (v) => ({878- foo: v.object('foo', (v) => ({879- bar: v.json('bar'),880- })),881- })),882- posts: v.array('posts', (v) => ({883- author: v.object('author', (v) => ({884- name: v.json('name'),885- })),886- })),887- }))888- for (const validator of vObject.getValidators()) {889- const results = await validator.validate(req)890- expect(results[0].isValid).toBe(true)891- expect(results[0].message).toBeUndefined()416+ type Expected = {417+ '/purge': {418+ $purge: {419+ input: {420+ form: {421+ tag: string422+ }423+ } & {424+ query: {425+ q: string426+ }427+ }428+ output: {429+ success: boolean430+ }431+ }432 }893- })894-})895-896-describe('Custom message', () => {897- const v = new Validator()898-899- const json = {900- title: 'foo',901- post: [902- {903- id: 123,904- },905- ],433 }434 908- const req = new Request('http://localhost/', {909- method: 'POST',910- body: JSON.stringify(json),911- })912-913- it('Should return custom error message - value', async () => {914- const customMessage1 = 'Custom message: not contain!'915- const customMessage2 = 'Custom message: not numeric!'916- const validator = v917- .json('title')918- .contains('bar')919- .message([customMessage1].join('\n'))920- .isNumeric()921- .message([customMessage2].join('\n'))922- const results = await validator.validate(req)923- expect(results[0].isValid).toBe(true)924- expect(results[1].isValid).toBe(false)925- expect(results[1].message).toBe([customMessage1].join('\n'))926- expect(results[2].isValid).toBe(false)927- expect(results[2].message).toBe([customMessage2].join('\n'))928- })929-930- it('Should return custom error message - validate type', async () => {931- const customMessage = 'Custom message: not string array!'932- const validator = v.json('post[*].id').message([customMessage].join('\n'))933- const results = await validator.validate(req)934- expect(results[0].isValid).toBe(false)935- expect(results[0].message).toBe([customMessage].join('\n'))936- })435+ type Actual = ExtractSchema<typeof route>436+ type verify = Expect<Equal<Expected, Actual>>437 })438 939-describe('Custom rule', () => {940- const v = new Validator()941- const validator = v.body('screenName').addRule('should be screen name', (value) => {942- if (typeof value === 'string') {943- return /^[0-9a-zA-Z\_]+$/.test(value)944- }945- return false946- })439+describe('`app.on`', () => {440+ const app = new Hono()441 948- it('Should be valid - custom rule', async () => {949- const body = new FormData()950- body.append('screenName', 'honojs_honojs_honojs_honojs_honojs')951-952- const req = new Request('http://localhost/', {953- method: 'POST',954- body: body,955- })956- const results = await validator.validate(req)957- expect(results[0].isValid).toBe(true)958- expect(results[1].isValid).toBe(true)959- })960-961- it('Should be invalid - custom rule', async () => {962- const body = new FormData()963- body.append('screenName', 'honojs+honojs')964-965- const req = new Request('http://localhost/', {966- method: 'POST',967- body: body,968- })969- const results = await validator.validate(req)970- expect(results[0].isValid).toBe(true)971- expect(results[1].isValid).toBe(false)972- expect(results[1].message).toBe(973- [974- 'Invalid Value [honojs+honojs]: the request body "screenName" is invalid - should be screen name',975- ].join('\n')442+ const route = app443+ .get(444+ '/posts',445+ validator('query', () => {446+ return {447+ page: '2',448+ }449+ }),450+ (c) => {451+ return c.jsonT({452+ posts: [453+ {454+ title: 'foo',455+ },456+ ],457+ })458+ }459 )460+ .post(461+ validator('json', () => {462+ return {463+ title: 'Hello',464+ }465+ }),466+ validator('query', () => {467+ return {468+ title: 'Hello',469+ }470+ }),471+ (c) => {472+ return c.jsonT({473+ success: true,977- })978-})474+ })475+ }476+ )477 980-describe('Sanitizer', () => {981- describe('built-in', () => {982- test('trim', async () => {983- const v = new Validator()984- 985- const post = { name: ' a bc ' }986- 987- const req = new Request('http://localhost/', {988- method: 'POST',989- body: JSON.stringify(post),990- })991- 992- const validator = v.json('name').trim()993- const [result] = await validator.validate(req)994- 995- expect(result.value).toBe('a bc')996- })997- })998-999- test('custom', async () => {1000- const v = new Validator()1001-1002- const post = { name: ' a bc ' }1003-1004- const req = new Request('http://localhost/', {1005- method: 'POST',1006- body: JSON.stringify(post),1007- })1008-1009- const validator = v1010- .json('name')1011- .addSanitizer((s: unknown) => `${s}`.replace(/\s/g, ''))1012- .addSanitizer((s: unknown) => `${s}`.toUpperCase())1013-1014- const [results] = await validator.validate(req)1015-1016- expect(results.value).toBe('ABC')1017- })478+ type Actual = ExtractSchema<typeof route>479+ //type verify = Expect<Equal<Expected, Actual>>480 })modified:src/validator/validator.ts+44 added-493 removed
1-import { JSONPathCopy } from './../utils/json'2-import type { JSONObject, JSONPrimitive, JSONArray } from './../utils/json'3-import { rule } from './rule'4-import { sanitizer } from './sanitizer'5-import type { Schema } from './schema'1+import type { Context } from '../context'2+import type { Env, ValidationTargets, MiddlewareHandler } from '../types'3 7-type Target = 'query' | 'queries' | 'header' | 'body' | 'json'8-type Type = JSONPrimitive | JSONObject | JSONArray | File9-type RuleFunc = (value: Type) => boolean10-type Rule = {11- name: string12- func: RuleFunc13- customMessage?: string14- type: 'type' | 'value'15-}16-type Sanitizer = (value: Type) => Type4+type ValidationTargetKeysWithBody = 'form' | 'json'5+type ValidationTargetByMethod<M> = M extends 'get' | 'head' // GET and HEAD request must not have a body content.6+ ? Exclude<keyof ValidationTargets, ValidationTargetKeysWithBody>7+ : keyof ValidationTargets8 18-export type ValidateResult = {19- isValid: boolean20- message: string | undefined21- target: Target | 'unknown'22- key: string | null23- value: Type | null24- ruleName: string25- ruleType: 'type' | 'value'26- jsonData?: JSONObject27-}9+export const validator = <10+ T,11+ P extends string,12+ M extends string,13+ U extends ValidationTargetByMethod<M>,14+ V extends { [K in U]: T },15+ // eslint-disable-next-line @typescript-eslint/no-explicit-any16+ E extends Env = any17+>(18+ target: U,19+ validationFunc: (value: ValidationTargets[U], c: Context<E>) => T | Response | Promise<Response>20+): MiddlewareHandler<E, P, V> => {21+ return async (c, next) => {22+ let value = {}23 29-export abstract class VObjectBase<T extends Schema> {30- container: T31- keys: string[] = []32- protected _isOptional: boolean = false33- constructor(container: T, key: string) {34- this.container = container35- if (this instanceof VArray) {36- this.keys.push(key, '[*]')37- } else if (this instanceof VObject) {38- this.keys.push(key)39- }40- }41-42- isOptional() {43- this._isOptional = true44- return this45- }46-47- getValidators = (): VBase[] => {48- const validators: VBase[] = []49-50- const walk = (container: T, keys: string[], isOptional: boolean) => {51- for (const v of Object.values(container)) {52- if (v instanceof VArray || v instanceof VObject) {53- // eslint-disable-next-line @typescript-eslint/ban-ts-comment54- // @ts-ignore55- isOptional ||= v._isOptional56- walk(v.container as T, [...keys, ...v.keys], isOptional)57- } else if (v instanceof VBase) {58- if (isOptional) v.isOptional()59- v.baseKeys.push(...keys)60- validators.push(v)61- }62- }63- }64-65- walk(this.container, this.keys, this._isOptional)66-67- return validators68- }69-}70-71-export class VObject<T extends Schema> extends VObjectBase<T> {72- constructor(container: T, key: string) {73- super(container, key)74- }75-}76-77-export class VArray<T extends Schema> extends VObjectBase<T> {78- type: 'array' = 'array'79- constructor(container: T, key: string) {80- super(container, key)81- }82-}83-84-export class Validator {85- constructor(private inArray: boolean = false) {}86-87- query = (key: string): VString => new VString({ target: 'query', key: key })88- queries = (key: string): VStringArray => new VStringArray({ target: 'queries', key: key })89- header = (key: string): VString => new VString({ target: 'header', key: key })90- body = (key: string): VString => new VString({ target: 'body', key: key })91- json = (key: string) => {92- if (this.inArray) {93- return new VStringArray({ target: 'json', key: key })94- } else {95- return new VString({ target: 'json', key: key })96- }97- }98- array = <T extends Schema>(path: string, validatorFn: (v: Validator) => T): VArray<T> => {99- const validator = new Validator(true)100- const res = validatorFn(validator)101- const arr = new VArray(res, path)102- return arr103- }104- object = <T extends Schema>(path: string, validatorFn: (v: Validator) => T): VObject<T> => {105- const validator = new Validator(this.inArray)106- const res = validatorFn(validator)107- const obj = new VObject(res, path)108- return obj109- }110-}111-112-type VOptions = {113- target: Target114- key: string115- type?: 'string' | 'number' | 'boolean' | 'object'116- isArray?: boolean117-}118-119-export abstract class VBase {120- type: 'string' | 'number' | 'boolean' | 'object'121- target: Target122- baseKeys: string[] = []123- key: string124- rules: Rule[]125- sanitizers: Sanitizer[]126- isArray: boolean127- private _optional: boolean128- constructor(options: VOptions) {129- this.target = options.target130- this.key = options.key131- this.type = options.type || 'string'132- this.rules = [133- {134- name: this.getTypeRuleName(),135- type: 'type',136- func: this.validateType,137- },138- ]139- this.sanitizers = []140- this._optional = false141- this.isArray = options.isArray || false142- }143-144- private _nested = () => (this.baseKeys.length ? true : false)145-146- addRule(func: RuleFunc): this147- addRule(name: string, func: RuleFunc): this148- addRule(arg: string | RuleFunc, func?: RuleFunc) {149- if (typeof arg === 'string' && func) {150- this.rules.push({ name: arg, func, type: 'value' })151- } else if (arg instanceof Function) {152- this.rules.push({ name: arg.name, func: arg, type: 'value' })153- }154- return this155- }156-157- addSanitizer = (sanitizer: Sanitizer) => {158- this.sanitizers.push(sanitizer)159- return this160- }161-162- message = (text: string) => {163- const len = this.rules.length164- if (len >= 1) {165- this.rules[len - 1].customMessage = text166- }167- return this168- }169-170- isRequired = () => {171- return this.addRule('isRequired', (value: unknown) => {172- if (value !== undefined && value !== null && value !== '') return true173- return false174- })175- }176-177- isOptional = () => {178- this._optional = true179- return this.addRule('isOptional', () => true)180- }181-182- isEqual = (comparison: unknown) => {183- return this.addRule('isEqual', (value: unknown) => {184- return value === comparison185- })186- }187-188- asNumber = () => {189- return new VNumber({ ...this, type: 'number' })190- }191-192- asBoolean = () => {193- return new VBoolean({ ...this, type: 'boolean' })194- }195-196- get(value: string) {197- const len = this.rules.length198- if (len > 0) {199- this.rules[this.rules.length - 1].customMessage = value200- }201- return this202- }203-204- validate = async <R extends Request>(req: R): Promise<ValidateResult[]> => {205- let value: Type = undefined206- let jsonData: JSONObject | undefined = undefined207-208- if (this.target === 'query') {209- value = req.query(this.key)210- }211- if (this.target === 'queries') {212- value = req.queries(this.key)213- }214- if (this.target === 'header') {215- value = req.header(this.key)216- }217- if (this.target === 'body') {218- const body = await req.parseBody()219- value = body[this.key]220- }221- if (this.target === 'json') {222- if (this._nested()) {223- this.key = `${this.baseKeys.join('.')}.${this.key}`224- }225- let obj = {}226- try {227- obj = (await req.json()) as JSONObject228- } catch (e) {229- throw new Error('Malformed JSON in request body')230- }231- const dst = {}232- value = JSONPathCopy(obj, dst, this.key)233- if (this._nested()) jsonData = dst234- }235-236- value = this.sanitizeValue(value)237-238- const results: ValidateResult[] = []239-240- let typeRule = this.rules.shift()241-242- for (const rule of this.rules) {243- if (rule.type === 'type') {244- typeRule = rule245- } else if (rule.type === 'value') {246- const result = this.validateRule(rule, value)247- result.jsonData ||= jsonData248- results.push(result)249- }250- }251-252- if (typeRule) {253- const typeResult = this.validateRule(typeRule, value)254- typeResult.jsonData ||= jsonData255- results.unshift(typeResult)256- this.rules.unshift(typeRule)257- }258-259- return results260- }261-262- protected getTypeRuleName(): string {263- const prefix = 'should be'264- return this.isArray ? `${prefix} "${this.type}[]"` : `${prefix} "${this.type}"`265- }266-267- private sanitizeValue = (value: Type) =>268- this.sanitizers.reduce((acc, sanitizer) => sanitizer(acc), value)269-270- private validateRule(rule: Rule, value: Type): ValidateResult {271- let isValid: boolean = false272-273- if (this._nested() && this.target != 'json') {274- isValid = false275- } else if (rule.type === 'value') {276- isValid = this.validateValue(rule.func, value)277- } else if (rule.type === 'type') {278- isValid = this.validateType(value)279- }280-281- const message = isValid282- ? undefined283- : rule.customMessage || this.getMessage({ ruleName: rule.name, value })284- const result = {285- isValid: isValid,286- message: message,287- target: this.target,288- key: this.key,289- value,290- ruleName: rule.name,291- ruleType: rule.type,292- }293- return result294- }295-296- private validateType = (value: Type): boolean => {297- if (this.isArray) {298- if (!Array.isArray(value)) {299- return this._optional && typeof value === 'undefined'300- }301- for (const val of value) {302- if (typeof val === 'undefined' && this._nested()) {303- value.pop()304- }305- for (const val of value) {306- if (typeof val !== this.type) {307- // Value is of wrong type here308- // If it is not optional and not undefined, return false309- if (!this._optional || typeof val !== 'undefined') return false310- }311- }312- }313- } else {314- if (typeof value !== this.type) {315- if (this._optional && (typeof value === 'undefined' || Array.isArray(value))) {316- // Do nothing.317- // If it is optional it's OK to be `undefined` or Array318- } else {319- return false320- }321- }322- }323- return true324- }325-326- private validateValue = (func: (value: Type) => boolean, value: Type): boolean => {327- if (this._optional && typeof value === 'undefined') return true328-329- if (Array.isArray(value)) {330- if (value.length === 0 && !this._optional) return false331- for (const val of value) {332- if (!func(val)) {333- return false334- }335- }336- return true337- } else {338- if (!func(value)) {339- return false340- }341- return true342- }343- }344-345- private getMessage = (opts: { ruleName: string; value: Type }): string => {346- let keyText: string347- const valueText = Array.isArray(opts.value)348- ? `${opts.value349- .map((val) =>350- val === undefined ? 'undefined' : typeof val === 'string' ? `"${val}"` : val24+ switch (target) {25+ case 'json':26+ try {27+ value = await c.req.json()28+ } catch {29+ console.error('Error: Malformed JSON in request body')30+ return c.json(31+ {32+ success: false,33+ message: 'Malformed JSON in request body',34+ },35+ 40036 )352- .join(', ')}`353- : opts.value354- switch (this.target) {37+ }38+ break39+ case 'form':40+ value = await c.req.parseBody()41+ break42 case 'query':356- keyText = `the query parameter "${this.key}"`43+ value = c.req.query()44 break45 case 'queries':359- keyText = `the query parameters "${this.key}"`46+ value = c.req.queries()47 break361- case 'header':362- keyText = `the request header "${this.key}"`363- break364- case 'body':365- keyText = `the request body "${this.key}"`366- break367- case 'json':368- keyText = `the JSON body "${this.key}"`369- break48 }371- return `Invalid Value [${valueText}]: ${keyText} is invalid - ${opts.ruleName}`372- }373-}49 375-export class VString extends VBase {376- constructor(options: VOptions) {377- super(options)378- this.type = 'string'379- }50+ const res = validationFunc(value, c)51 381- asArray = () => {382- return new VStringArray(this)383- }384-385- isEmpty = (386- options: {387- ignore_whitespace: boolean388- } = { ignore_whitespace: false }389- ) => {390- return this.addRule('isEmpty', (value) => rule.isEmpty(value as string, options))391- }392-393- isLength = (options: Partial<{ min: number; max: number }> | number, arg2?: number) => {394- return this.addRule('isLength', (value) => rule.isLength(value as string, options, arg2))395- }396-397- isAlpha = () => {398- return this.addRule('isAlpha', (value) => rule.isAlpha(value as string))399- }400-401- isNumeric = () => {402- return this.addRule('isNumeric', (value) => rule.isNumeric(value as string))403- }404-405- contains = (406- elem: string,407- options: Partial<{ ignoreCase: boolean; minOccurrences: number }> = {408- ignoreCase: false,409- minOccurrences: 1,52+ if (res instanceof Response || res instanceof Promise) {53+ return res54 }411- ) => {412- return this.addRule('contains', (value) => rule.contains(value as string, elem, options))413- }55 415- isIn = (options: string[]) => {416- return this.addRule('isIn', (value) => rule.isIn(value as string, options))417- }56+ c.req.addValidatedData(target, res as never)57 419- match = (regExp: RegExp) => {420- return this.addRule('match', (value) => rule.match(value as string, regExp))58+ await next()59 }422-423- trim = () => {424- return this.addSanitizer((value) => sanitizer.trim(value as string))425- }60 }427-428-export class VNumber extends VBase {429- constructor(options: VOptions) {430- super(options)431- this.type = 'number'432- }433-434- asArray = () => {435- return new VNumberArray(this)436- }437-438- isGte = (min: number) => {439- return this.addRule('isGte', (value) => rule.isGte(value as number, min))440- }441-442- isLte = (min: number) => {443- return this.addRule('isLte', (value) => rule.isLte(value as number, min))444- }445-}446-447-export class VBoolean extends VBase {448- constructor(options: VOptions) {449- super(options)450- this.type = 'boolean'451- }452-453- asArray = () => {454- return new VBooleanArray(this)455- }456-457- isTrue = () => {458- return this.addRule('isTrue', (value) => rule.isTrue(value as boolean))459- }460-461- isFalse = () => {462- return this.addRule('isFalse', (value) => rule.isFalse(value as boolean))463- }464-}465-466-export class VNumberArray extends VNumber {467- isArray: true468- constructor(options: VOptions) {469- super(options)470- this.isArray = true471- this.rules[0].name = this.getTypeRuleName()472- }473- asNumber = () => {474- return new VNumberArray({ ...this, type: 'number' })475- }476- asBoolean = () => {477- return new VBooleanArray({ ...this, type: 'boolean' })478- }479-}480-481-export class VStringArray extends VString {482- isArray: true483- constructor(options: VOptions) {484- super(options)485- this.isArray = true486- this.rules[0].name = this.getTypeRuleName()487- }488- asNumber = () => {489- return new VNumberArray({ ...this, type: 'number' })490- }491- asBoolean = () => {492- return new VBooleanArray({ ...this, type: 'boolean' })493- }494-}495-496-export class VBooleanArray extends VBoolean {497- isArray: true498- constructor(options: VOptions) {499- super(options)500- this.isArray = true501- this.rules[0].name = this.getTypeRuleName()502- }503- asNumber = () => {504- return new VNumberArray({ ...this, type: 'number' })505- }506- asBoolean = () => {507- return new VBooleanArray({ ...this, type: 'boolean' })508- }509-}modified:src/compose.test.ts-3 removed
1 import { compose } from './compose'2 import { Context } from './context'3-import { extendRequestPrototype } from './request'3 5-extendRequestPrototype()6-4 type C = {5 req: Record<string, string>6 res: Record<string, string>7 finalized: boolean652 unmodified linesmodified:src/compose.ts+8 added-2 removed
1 import { Context } from './context'2-import type { Environment, NotFoundHandler, ErrorHandler } from './types'2+import type { Env, NotFoundHandler, ErrorHandler } from './types'3 4 interface ComposeContext {5 finalized: boolean6 res: unknown7 }8 9 // Based on the code in the MIT licensed `koa-compose` package.10-export const compose = <C extends ComposeContext, E extends Partial<Environment> = Environment>(10+export const compose = <C extends ComposeContext, E extends Env = Env>(11 middleware: Function[],12 onError?: ErrorHandler<E>,13 onNotFound?: NotFoundHandler<E>14 ) => {34 unmodified lines49 }50 }51 52 if (!(res instanceof Promise)) {53+ if (res !== undefined && 'response' in res) {54+ res = res['response']55+ }56 if (res && (context.finalized === false || isError)) {57 context.res = res58 }59 return context60 } else {61 return res62 .then((res) => {63+ if (res !== undefined && 'response' in res) {64+ res = res['response']65+ }66 if (res && context.finalized === false) {67 context.res = res68 }69 return context13 unmodified linesmodified:src/context.test.ts+5 added-3 removed
148 unmodified lines149 it('Should be able read env', async () => {150 const req = new Request('http://localhost/')151 const key = 'a-secret-key'152 const ctx = new Context(req, {153+ env: {153- API_KEY: key,154+ API_KEY: key,155+ },156 })157 expect(ctx.env.API_KEY).toBe(key)158 })159 14 unmodified lines174 expect(res.headers.get('foo')).not.toBeNull()175 expect(res.headers.get('foo')).toBe('bar')176 })177 176- it('returns current runtime (cloudflare)', async () => {178+ it('returns current runtime (workerd)', async () => {179 c = new Context(req)178- expect(c.runtime).toBe('cloudflare')180+ expect(c.runtime).toBe('workerd')181 })182 })183 184 describe('Context header', () => {16 unmodified linesmodified:src/context.ts+167 added-101 removed
1-import type { ExecutionContext } from './types'2-import type { Environment, NotFoundHandler, ContextVariableMap } from './types'1+import { HonoRequest } from './request'2+import type { TypedResponse } from './types'3+import type { Env, NotFoundHandler, Input } from './types'4 import type { CookieOptions } from './utils/cookie'5 import { serialize } from './utils/cookie'6 import type { StatusCode } from './utils/http-status'6-import type { Schema, SchemaToProp } from './validator/schema'7 8-type HeaderField = [string, string]9-type Headers = Record<string, string | string[]>10-type Runtime = 'node' | 'deno' | 'bun' | 'cloudflare' | 'fastly' | 'vercel' | 'lagon' | 'other'11-export type Data = string | ArrayBuffer | ReadableStream8+type Runtime = 'node' | 'deno' | 'bun' | 'workerd' | 'fastly' | 'edge-light' | 'lagon' | 'other'9+type HeaderRecord = Record<string, string | string[]>10+type Data = string | ArrayBuffer | ReadableStream11 12+export interface ExecutionContext {13+ waitUntil(promise: Promise<void>): void14+ passThroughOnException(): void15+}16+export interface ContextVariableMap {}17+18+type GetVariable<K, E extends Env> = K extends keyof E['Variables']19+ ? E['Variables'][K]20+ : K extends keyof ContextVariableMap21+ ? ContextVariableMap[K]22+ : unknown23+24+type ContextOptions<E extends Env> = {25+ env: E['Bindings']26+ executionCtx?: FetchEvent | ExecutionContext | undefined27+ notFoundHandler?: NotFoundHandler<E>28+ paramData?: Record<string, string>29+}30+31 export class Context<14- P extends string = string,15- E extends Partial<Environment> = Environment,32 // eslint-disable-next-line @typescript-eslint/no-explicit-any17- S = any33+ E extends Env = any,34+ // eslint-disable-next-line @typescript-eslint/no-explicit-any35+ P extends string = any,36+ I extends Input = {}37 > {19- req: Request<unknown, P, S extends Schema ? SchemaToProp<S> : S>20- env: E['Bindings']21- finalized: boolean38+ env: E['Bindings'] = {}39+ finalized: boolean = false40 error: Error | undefined = undefined41 42+ // eslint-disable-next-line @typescript-eslint/no-explicit-any43+ private _req?: HonoRequest<any, any>44 private _status: StatusCode = 20045 private _executionCtx: FetchEvent | ExecutionContext | undefined46 private _pretty: boolean = false47 private _prettySpace: number = 248 private _map: Record<string, unknown> | undefined29- private _headers: Record<string, string[]> | undefined49+ private _headers: Headers | undefined = undefined50+ private _preparedHeaders: Record<string, string> | undefined = undefined51 private _res: Response | undefined52+ private _paramData?: Record<string, string> | null53+ private rawRequest?: Request | null31- private notFoundHandler: NotFoundHandler<E>54+ private notFoundHandler: NotFoundHandler<E> = () => new Response()55 33- constructor(34- req: Request<unknown, P>,35- env: E['Bindings'] = {},36- executionCtx: FetchEvent | ExecutionContext | undefined = undefined,37- notFoundHandler: NotFoundHandler<E> = () => new Response()38- ) {39- this._executionCtx = executionCtx40- this.req = req as Request<unknown, P>41- this.env = env56+ constructor(req: Request, options?: ContextOptions<E>) {57+ this.rawRequest = req58+ if (options) {59+ this._executionCtx = options.executionCtx60+ this._paramData = options.paramData61+ this.env = options.env62+ if (options.notFoundHandler) {63+ this.notFoundHandler = options.notFoundHandler64+ }65+ }66+ }67 43- this.notFoundHandler = notFoundHandler44- this.finalized = false68+ get req(): HonoRequest<P, I> {69+ if (this._req) {70+ return this._req71+ } else {72+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion73+ this._req = new HonoRequest(this.rawRequest!, this._paramData!)74+ this.rawRequest = undefined75+ this._paramData = undefined76+ return this._req77+ }78 }79 80 get event(): FetchEvent {81 if (this._executionCtx instanceof FetchEvent) {26 unmodified lines108 this.finalized = true109 }110 111 header = (name: string, value: string, options?: { append?: boolean }): void => {79- this._headers ||= {}80- const key = name.toLowerCase()81-82- let shouldAppend = false83- if (options && options.append) {84- const vAlreadySet = this._headers[key]85- if (vAlreadySet && vAlreadySet.length) {86- shouldAppend = true112+ if (options?.append) {113+ if (!this._headers) {114+ this._headers = new Headers(this._preparedHeaders)115 }88- }89-90- if (shouldAppend) {91- this._headers[key].push(value)116+ this._headers.append(name, value)117 } else {93- this._headers[key] = [value]118+ if (this._headers) {119+ this._headers.set(name, value)120+ } else {121+ this._preparedHeaders ??= {}122+ this._preparedHeaders[name.toLowerCase()] = value123+ }124 }125 126 if (this.finalized) {97- if (shouldAppend) {127+ if (options?.append) {128 this.res.headers.append(name, value)129 } else {130 this.res.headers.set(name, value)131 }3 unmodified lines135 status = (status: StatusCode): void => {136 this._status = status137 }138 109- set<Key extends keyof ContextVariableMap>(key: Key, value: ContextVariableMap[Key]): void110- set<Key extends keyof E['Variables']>(key: Key, value: E['Variables'][Key]): void111- set(key: string, value: unknown): void112- set(key: string, value: unknown): void {139+ set = <Key extends keyof E['Variables'] | keyof ContextVariableMap>(140+ key: Key,141+ value: GetVariable<Key, E>142+ ): void => {143 this._map ||= {}114- this._map[key] = value144+ this._map[key as string] = value145 }146 117- get<Key extends keyof ContextVariableMap>(key: Key): ContextVariableMap[Key]118- get<Key extends keyof E['Variables']>(key: Key): E['Variables'][Key]119- get<T>(key: string): T120- get(key: string) {121- if (!this._map) {122- return undefined123- }124- return this._map[key]147+ get = <Key extends keyof E['Variables'] | keyof ContextVariableMap>(148+ key: Key149+ ): GetVariable<Key, E> => {150+ return this._map?.[key as string] as GetVariable<Key, E>151 }152 153 pretty = (prettyJSON: boolean, space: number = 2): void => {154 this._pretty = prettyJSON155 this._prettySpace = space156 }157 132- newResponse = (data: Data | null, status: StatusCode, headers: Headers = {}): Response => {133- return new Response(data, {134- status,135- headers: this._finalizeHeaders(headers),136- })137- }158+ newResponse = (data: Data | null, status?: StatusCode, headers?: HeaderRecord): Response => {159+ // Optimized160+ if (!headers && !this._headers && !this._res && !status) {161+ return new Response(data, {162+ headers: this._preparedHeaders,163+ })164+ }165 139- private _finalizeHeaders(incomingHeaders: Headers): HeaderField[] {140- const finalizedHeaders: HeaderField[] = []141- const headersKv = this._headers || {}142- // If Response is already set166+ this._preparedHeaders ??= {}167+168+ if (!this._headers) {169+ this._headers = new Headers()170+ for (const [k, v] of Object.entries(this._preparedHeaders)) {171+ this._headers.set(k, v)172+ }173+ }174+175 if (this._res) {176 this._res.headers.forEach((v, k) => {145- headersKv[k] = [v]177+ this._headers?.set(k, v)178 })179+ for (const [k, v] of Object.entries(this._preparedHeaders)) {180+ this._headers.set(k, v)181+ }182 }148- for (const key of Object.keys(incomingHeaders)) {149- const value = incomingHeaders[key]150- if (typeof value === 'string') {151- finalizedHeaders.push([key, value])183+184+ headers ??= {}185+ for (const [k, v] of Object.entries(headers)) {186+ if (typeof v === 'string') {187+ this._headers.set(k, v)188 } else {153- for (const v of value) {154- finalizedHeaders.push([key, v])189+ this._headers.delete(k)190+ for (const v2 of v) {191+ this._headers.append(k, v2)192 }193 }157- delete headersKv[key]194 }159- for (const key of Object.keys(headersKv)) {160- for (const value of headersKv[key]) {161- const kv: HeaderField = [key, value]162- finalizedHeaders.push(kv)163- }164- }165- return finalizedHeaders195+196+ return new Response(data, {197+ status,198+ headers: this._headers,199+ })200 }201 202 body = (203 data: Data | null,204 status: StatusCode = this._status,171- headers: Headers = {}205+ headers?: HeaderRecord206 ): Response => {207 return this.newResponse(data, status, headers)208 }209 176- text = (text: string, status?: StatusCode, headers?: Headers): Response => {210+ text = (text: string, status?: StatusCode, headers?: HeaderRecord): Response => {211 // If the header is empty, return Response immediately.212 // Content-Type will be added automatically as `text/plain`.213+ if (!this._preparedHeaders) {179- if (!headers && !status && !this._res && !this._headers) {180- return new Response(text)214+ if (!headers && !this._res && !this._headers && !status) {215+ return new Response(text)216+ }217+ this._preparedHeaders = {}218 }182- status ||= this._status183- headers ||= {}184- headers['content-type'] = 'text/plain; charset=UTF-8'219+ // If Content-Type is not set, we don't have to set `text/plain`.220+ // Fewer the header values, it will be faster.221+ if (this._preparedHeaders['content-type']) {222+ this._preparedHeaders['content-type'] = 'text/plain; charset=UTF8'223+ }224 return this.newResponse(text, status, headers)225 }226 188- json = <T>(object: T, status: StatusCode = this._status, headers: Headers = {}): Response => {227+ json = <T = object>(228+ object: T,229+ status: StatusCode = this._status,230+ headers?: HeaderRecord231+ ): Response => {232 const body = this._pretty233 ? JSON.stringify(object, null, this._prettySpace)234 : JSON.stringify(object)235+ this._preparedHeaders ??= {}192- headers['content-type'] = 'application/json; charset=UTF-8'236+ this._preparedHeaders['content-type'] = 'application/json; charset=UTF-8'237 return this.newResponse(body, status, headers)238 }239 196- html = (html: string, status: StatusCode = this._status, headers: Headers = {}): Response => {197- headers['content-type'] = 'text/html; charset=UTF-8'240+ jsonT = <T = object>(241+ object: T,242+ status: StatusCode = this._status,243+ headers?: HeaderRecord244+ ): TypedResponse<T> => {245+ return {246+ response: this.json(object, status, headers),247+ data: object,248+ format: 'json',249+ }250+ }251+252+ html = (html: string, status: StatusCode = this._status, headers?: HeaderRecord): Response => {253+ this._preparedHeaders ??= {}254+ this._preparedHeaders['content-type'] = 'text/html; charset=UTF-8'255 return this.newResponse(html, status, headers)256 }257 258 redirect = (location: string, status: StatusCode = 302): Response => {202- return this.newResponse(null, status, {203- Location: location,204- })259+ this._headers ??= new Headers()260+ this._headers.set('Location', location)261+ return this.newResponse(null, status)262 }263 264 cookie = (name: string, value: string, opt?: CookieOptions): void => {265 const cookie = serialize(name, value, opt)266 this.header('set-cookie', cookie, { append: true })267 }268 269 notFound = (): Response | Promise<Response> => {270+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment271+ // @ts-ignore213- return this.notFoundHandler(this as unknown as Context<string, E>)272+ return this.notFoundHandler(this)273 }274 275 get runtime(): Runtime {276 // eslint-disable-next-line @typescript-eslint/no-explicit-any7 unmodified lines284 return 'bun'285 }286 287 if (typeof global?.WebSocketPair === 'function') {229- return 'cloudflare'288+ return 'workerd'289 }290 232- if (global?.fastly !== undefined) {233- return 'fastly'234- }235-291 if (typeof global?.EdgeRuntime === 'string') {237- return 'vercel'292+ return 'edge-light'293 }294 240- if (global?.process?.release?.name === 'node') {241- return 'node'295+ let onFastly = false296+ try {297+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment298+ // @ts-ignore299+ const { env } = require('fastly:env')300+ if (env instanceof Function) onFastly = true301+ } catch {}302+ if (onFastly) {303+ return 'fastly'304 }305 306 if (global?.__lagon__ !== undefined) {307 return 'lagon'308 }309 310+ if (global?.process?.release?.name === 'node') {311+ return 'node'312+ }313+314 return 'other'315 }316 }modified:src/hono.test.ts+155 added-27 removed
1 /* eslint-disable @typescript-eslint/no-unused-vars */2 import type { Context } from './context'3 import { Hono } from './hono'4+import { HTTPException } from './http-exception'5 import { logger } from './middleware/logger'6 import { poweredBy } from './middleware/powered-by'7 import { RegExpRouter } from './router/reg-exp-router'7-import { StaticRouter } from './router/static-router'8 import { TrieRouter } from './router/trie-router'9 import type { Handler, Next } from './types'10 import type { Expect, Equal } from './utils/types'11 289 unmodified lines301 return c.text(`name is ${name}`)302 })303 304 app.get('/multiple-values', (c) => {305- const queries = c.req.queries('q')306- const limit = c.req.queries('limit')305+ const queries = c.req.queries('q') ?? throwExpression('missing query values')306+ const limit = c.req.queries('limit') ?? throwExpression('missing query values')307 return c.text(`q is ${queries[0]} and ${queries[1]}, limit is ${limit[0]}`)308 })309 310 app.get('/add-header', (c) => {205 unmodified lines516 await next()517 })518 .use(async (c, next) => {519 await next()520- c.header('x-after', c.req.header('x-before') ?? throwExpression('missing `x-before` header'))520+ c.header(521+ 'x-after',522+ c.req.header('x-before') ?? throwExpression('missing `x-before` header')523+ )524 })525 .get('/chained/abc', (c) => {526 return c.text('GET chained')527 })15 unmodified lines543 await next()544 },545 async (c, next) => {546 await next()544- c.header('x-after', c.req.header('x-before') ?? throwExpression('missing `x-before` header'))547+ c.header(548+ 'x-after',549+ c.req.header('x-before') ?? throwExpression('missing `x-before` header')550+ )551 }552 )553 .get('/multiple/abc', (c) => {554 return c.text('GET multiple')151 unmodified lines706 expect(res.status).toBe(500)707 expect(await res.text()).toBe('Custom Error Message')708 expect(res.headers.get('x-debug')).toBe('This is Middleware Error')709 })710+711+ describe('Handle HTTPException', () => {712+ const app = new Hono()713+714+ app.get('/exception', () => {715+ throw new HTTPException(401)716+ })717+718+ it('Should return 401 response', async () => {719+ const res = await app.request('http://localhost/exception')720+ expect(res.status).toBe(401)721+ expect(res.statusText).toBe('Unauthorized')722+ expect(await res.text()).toBe('Unauthorized')723+ })724+725+ const app2 = new Hono()726+727+ app2.get('/exception', () => {728+ throw new HTTPException(401)729+ })730+731+ app2.onError((err, c) => {732+ if (err instanceof HTTPException && err.status === 401) {733+ return c.text('Custom Error Message', 401)734+ }735+ return c.text('Internal Server Error', 500)736+ })737+738+ it('Should return 401 response with a custom message', async () => {739+ const res = await app2.request('http://localhost/exception')740+ expect(res.status).toBe(401)741+ expect(await res.text()).toBe('Custom Error Message')742+ })743+ })744 })745 746 describe('Error handling in middleware', () => {747 const app = new Hono()66 unmodified lines814 const app = new Hono()815 816 app.use('*', async (c, next) => {817 const query = c.req.query('foo')818+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment819+ // @ts-ignore778- const param = c.req.param('foo')820+ const param = c.req.param('foo') // This will cause a type error.821 const header = c.req.header('User-Agent')822 await next()781- c.header('X-Query-2', query)823+ c.header('X-Query-2', query ?? throwExpression('missing `X-Query-2` header'))824 c.header('X-Param-2', param)825 c.header('X-Header-2', header ?? throwExpression('missing `X-Header-2` header'))826 })827 828 app.get('/:foo', (c) => {829 const query = c.req.query('foo')830 const param = c.req.param('foo')831 const header = c.req.header('User-Agent')790- c.header('X-Query', query)832+ c.header('X-Query', query ?? throwExpression('missing `X-Query` header'))833 c.header('X-Param', param)834 c.header('X-Header', header ?? throwExpression('missing `X-Header` header'))835 return c.body('Hono')836 })272 unmodified lines1109 })1110 })1111 1112 describe('Using other methods with `app.on`', () => {1071- it('Should handle PURGE method with StaticRouter', async () => {1072- const app = new Hono({ router: new StaticRouter() })1113+ it('Should handle PURGE method with RegExpRouter', async () => {1114+ const app = new Hono({ router: new RegExpRouter() })1115 1116 app.on('PURGE', '/purge', (c) => c.text('Accepted', 202))1117 1118 const req = new Request('http://localhost/purge', {3 unmodified lines1122 expect(res.status).toBe(202)1123 expect(await res.text()).toBe('Accepted')1124 })1125 1084- it('Should handle PURGE method with RegExpRouter', async () => {1085- const app = new Hono({ router: new RegExpRouter() })1126+ it('Should handle PURGE method with TrieRouter', async () => {1127+ const app = new Hono({ router: new TrieRouter() })1128 1129 app.on('PURGE', '/purge', (c) => c.text('Accepted', 202))1130 1131 const req = new Request('http://localhost/purge', {2 unmodified lines1134 const res = await app.request(req)1135 expect(res.status).toBe(202)1136 expect(await res.text()).toBe('Accepted')1137 })1138+})1139 1097- it('Should handle PURGE method with TrieRouter', async () => {1098- const app = new Hono({ router: new TrieRouter() })1140+describe('Multiple methods with `app.on`', () => {1141+ const app = new Hono()1142+ app.on(['PUT', 'DELETE'], '/posts/:id', (c) => {1143+ return c.json({1144+ postId: c.req.param('id'),1145+ method: c.req.method,1146+ })1147+ })1148 1100- app.on('PURGE', '/purge', (c) => c.text('Accepted', 202))1149+ it('Should return 200 with PUT', async () => {1150+ const req = new Request('http://localhost/posts/123', {1151+ method: 'PUT',1152+ })1153+ const res = await app.request(req)1154+ expect(res.status).toBe(200)1155+ expect(await res.json()).toEqual({1156+ postId: '123',1157+ method: 'PUT',1158+ })1159+ })1160 1161+ it('Should return 200 with DELETE', async () => {1102- const req = new Request('http://localhost/purge', {1103- method: 'PURGE',1162+ const req = new Request('http://localhost/posts/123', {1163+ method: 'DELETE',1164 })1165 const res = await app.request(req)1106- expect(res.status).toBe(202)1107- expect(await res.text()).toBe('Accepted')1166+ expect(res.status).toBe(200)1167+ expect(await res.json()).toEqual({1168+ postId: '123',1169+ method: 'DELETE',1170+ })1171 })1172+1173+ it('Should return 404 with POST', async () => {1174+ const req = new Request('http://localhost/posts/123', {1175+ method: 'POST',1176+ })1177+ const res = await app.request(req)1178+ expect(res.status).toBe(404)1179+ })1180 })1181 1182 describe('Multiple handler', () => {1183 describe('handler + handler', () => {265 unmodified lines1449 })1450 const res = await app.request(req)1451 expect(res).not.toBeNull()1452 expect(res.status).toBe(200)1382- const body = await req.parseBody()1383- expect(body).toEqual({})1453 })1454 1455 it('POST with `multipart/form-data`', async () => {1456 const formData = new FormData()5 unmodified lines1462 1463 const res = await app.request(req)1464 expect(res).not.toBeNull()1465 expect(res.status).toBe(200)1397- expect(await req.parseBody()).toEqual({ message: 'hello' })1466 expect(await res.json()).toEqual({ message: 'hello' })1467 })1468 1469 it('POST with `application/x-www-form-urlencoded`', async () => {9 unmodified lines1479 1480 const res = await app.request(req)1481 expect(res).not.toBeNull()1482 expect(res.status).toBe(200)1415- expect(await req.parseBody()).toEqual({ message: 'hello' })1483 expect(await res.json()).toEqual({ message: 'hello' })1484 })1485 })1486 66 unmodified lines1553 })1554 app.get('/', (c) => {1555 const id = c.get('id')1556 const title = c.get('title')1490- type verifyID = Expect<Equal<typeof id, number>>1491- type verifyTitle = Expect<Equal<typeof title, string>>1557+ type verifyID = Expect<Equal<number, typeof id>>1558+ type verifyTitle = Expect<Equal<string, typeof title>>1559 return c.text(`${id} is ${title}`)1560 })1561 const res = await app.request('http://localhost/')1562 expect(res.status).toBe(200)10 unmodified lines1573 const app = new Hono<{ Bindings: Bindings }>()1574 1575 it('Should get binding variables with correct types', async () => {1576 app.get('/', (c) => {1510- type verifyID = Expect<Equal<typeof c.env.USER_ID, number>>1511- type verifyName = Expect<Equal<typeof c.env.USER_NAME, string>>1577+ type verifyID = Expect<Equal<number, typeof c.env.USER_ID>>1578+ type verifyName = Expect<Equal<string, typeof c.env.USER_NAME>>1579 return c.text('These are verified')1580 })1581 const res = await app.request('http://localhost/')1582 expect(res.status).toBe(200)26 unmodified lines1609 expect(console.log).toBeCalled()1610 })1611 })1612 1613+describe('jsonT', () => {1614+ const api = new Hono()1615+1616+ api.get('/message', (c) => {1617+ return c.jsonT({1618+ message: 'Hello',1619+ })1620+ })1621+1622+ api.get('/message-async', async (c) => {1623+ return c.jsonT({1624+ message: 'Hello',1625+ })1626+ })1627+1628+ describe('Single handler', () => {1629+ const app = new Hono()1630+ app.route('/api', api)1631+1632+ it('Should return 200 response', async () => {1633+ const res = await app.request('http://localhost/api/message')1634+ expect(res.status).toBe(200)1635+ expect(await res.json()).toEqual({1636+ message: 'Hello',1637+ })1638+ })1639+1640+ it('Should return 200 response - with async', async () => {1641+ const res = await app.request('http://localhost/api/message-async')1642+ expect(res.status).toBe(200)1643+ expect(await res.json()).toEqual({1644+ message: 'Hello',1645+ })1646+ })1647+ })1648+1649+ describe('With middleware', () => {1650+ const app = new Hono()1651+ app.use('*', async (_c, next) => {1652+ await next()1653+ })1654+ app.route('/api', api)1655+1656+ it('Should return 200 response', async () => {1657+ const res = await app.request('http://localhost/api/message')1658+ expect(res.status).toBe(200)1659+ expect(await res.json()).toEqual({1660+ message: 'Hello',1661+ })1662+ })1663+1664+ it('Should return 200 response - with async', async () => {1665+ const res = await app.request('http://localhost/api/message-async')1666+ expect(res.status).toBe(200)1667+ expect(await res.json()).toEqual({1668+ message: 'Hello',1669+ })1670+ })1671+ })1672+})1673+1674 describe('Optional parameters', () => {1675 const app = new Hono()1676 app.get('/api/:version/animal/:type?', (c) => {1677 const type1 = c.req.param('type')26 unmodified linesmodified:src/hono.ts+102 added-117 removed
1 import { compose } from './compose'2 import { Context } from './context'3-import { extendRequestPrototype } from './request'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 { RegExpRouter } from './router/reg-exp-router'8 import { SmartRouter } from './router/smart-router'8-import { StaticRouter } from './router/static-router'9 import { TrieRouter } from './router/trie-router'10-import type { ExecutionContext } from './types'11-import type { Handler, Environment, ParamKeys, ErrorHandler, NotFoundHandler } from './types'10+import type {11+ Env,12+ ErrorHandler,13+ H,14+ HandlerInterface,15+ MiddlewareHandler,16+ MiddlewareHandlerInterface,17+ Next,18+ NotFoundHandler,19+ OnHandlerInterface,20+ TypedResponse,21+} from './types'22 import { getPathFromURL, mergePath } from './utils/url'23 14-interface HandlerInterface<15- P extends string,16- E extends Partial<Environment> = Environment,17- S = unknown,18- U = Hono<E, P, S>19-> {20- // app.get(handler...)21- <Path extends string, Data = S>(22- ...handlers: Handler<ParamKeys<Path> extends never ? string : ParamKeys<Path>, E, Data>[]23- ): Hono<E, Path, Data & S>24- (...handlers: Handler<P, E, S>[]): U24+type Methods = typeof METHODS[number] | typeof METHOD_NAME_ALL_LOWERCASE25 26- // app.get('/', handler, handler...)27- <Path extends string, Data = S>(28- path: Path,29- ...handlers: Handler<ParamKeys<Path> extends never ? string : ParamKeys<Path>, E, Data>[]30- ): Hono<E, Path, Data & S>31- <Path extends string, Data = S>(path: Path, ...handlers: Handler<string, E, Data>[]): Hono<32- E,33- string,34- Data & S35- >36- (path: string, ...handlers: Handler<P, E, S>[]): U26+interface RouterRoute {27+ path: string28+ method: string29+ handler: H30 }31 39-type Methods = typeof METHODS[number] | typeof METHOD_NAME_ALL_LOWERCASE40-32 function defineDynamicClass(): {42- new <43- E extends Partial<Environment> = Environment,44- P extends string = string,45- S = unknown,46- U = Hono<E, P, S>47- >(): {48- [K in Methods]: HandlerInterface<P, E, S, U>33+ new <E extends Env = Env, S = {}>(): {34+ [M in Methods]: HandlerInterface<E, M, S>35+ } & {36+ on: OnHandlerInterface<E, S>37+ } & {38+ use: MiddlewareHandlerInterface<E, S>39 }40 } {41 return class {} as never42 }43 54-interface Route<55- P extends string = string,56- E extends Partial<Environment> = Environment,57- S = unknown58-> {59- path: string60- method: string61- handler: Handler<P, E, S>62-}63-64-const notFoundHandler = <E extends Partial<Environment>>(c: Context<string, E>) => {44+const notFoundHandler = (c: Context) => {45 return c.text('404 Not Found', 404)46 }47 68-const errorHandler = <E extends Partial<Environment>>(err: Error, c: Context<string, E>) => {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 74-export class Hono<75- E extends Partial<Environment> = Environment,76- P extends string = string,77- S = unknown78-> extends defineDynamicClass()<E, P, S, Hono<E, P, S>> {79- readonly router: Router<Handler<P, E, S>> = new SmartRouter({80- routers: [new StaticRouter(), new RegExpRouter(), new TrieRouter()],57+export class Hono<E extends Env = Env, S = {}> extends defineDynamicClass()<E, S> {58+ readonly router: Router<H> = new SmartRouter({59+ routers: [new RegExpRouter(), new TrieRouter()],60 })61 readonly strict: boolean = true // strict routing - default is true62 private _tempPath: string = ''84- private path: string = '/'63+ private path: string = '*'64 86- routes: Route<P, E, S>[] = []65+ routes: RouterRoute[] = []66 67 constructor(init: Partial<Pick<Hono, 'router' | 'strict'>> = {}) {68 super()69 91- extendRequestPrototype()92-70+ // Implementation of app.get(...handlers[]) or app.get(path, ...handlers[])71 const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE]72 allMethods.map((method) => {95- // eslint-disable-next-line @typescript-eslint/ban-ts-comment96- // @ts-ignore97- this[method] = (args1: string | Handler, ...args: Handler[]) => {73+ this[method] = (args1: string | H, ...args: H[]) => {74 if (typeof args1 === 'string') {75 this.path = args176 } else {101- this.addRoute(method, this.path, args1 as unknown as Handler<P, E, S>)77+ this.addRoute(method, this.path, args1)78 }79 args.map((handler) => {80 if (typeof handler !== 'string') {105- this.addRoute(method, this.path, handler as unknown as Handler<P, E, S>)81+ this.addRoute(method, this.path, handler)82 }83 })108- // eslint-disable-next-line @typescript-eslint/no-explicit-any109- return this as unknown as Hono<E, any, any>84+ return this85 }86 })87 88+ // Implementation of app.on(method, path, ...handlers[])89+ this.on = (method: string | string[], path: string, ...handlers: H[]) => {90+ if (!method) return this91+ this.path = path92+ for (const m of [method].flat()) {93+ handlers.map((handler) => {94+ this.addRoute(m.toUpperCase(), this.path, handler)95+ })96+ }97+ return this98+ }99+100+ // Implementation of app.use(...handlers[]) or app.get(path, ...handlers[])101+ this.use = (arg1: string | MiddlewareHandler, ...handlers: MiddlewareHandler[]) => {102+ if (typeof arg1 === 'string') {103+ this.path = arg1104+ } else {105+ handlers.unshift(arg1)106+ }107+ handlers.map((handler) => {108+ this.addRoute(METHOD_NAME_ALL, this.path, handler)109+ })110+ return this111+ }112+113 Object.assign(this, init)114 }115 116- private notFoundHandler: NotFoundHandler<E> = notFoundHandler117- private errorHandler: ErrorHandler<E> = errorHandler116+ private notFoundHandler: NotFoundHandler = notFoundHandler117+ private errorHandler: ErrorHandler = errorHandler118 119 // eslint-disable-next-line @typescript-eslint/no-explicit-any120- route(path: string, app?: Hono<any>) {120+ route(path: string, app?: Hono<any, any>) {121 this._tempPath = path122 if (app) {123 app.routes.map((r) => {124- const handler = (124+ const handler =125 app.errorHandler === errorHandler126 ? r.handler127- : async (...args) =>128- (await compose<Context<P, E>, E>([r.handler], app.errorHandler)(...args)).res129- ) as Handler<P, E, S>127+ : async (c: Context, next: Next) =>128+ (await compose<Context>([r.handler], app.errorHandler)(c, next)).res129 this.addRoute(r.method, r.path, handler)130 })131 this._tempPath = ''132 }133 return this134 }135 137- use<Path extends string = string, Data = unknown>(138- ...middleware: Handler<Path, E, Data>[]139- ): Hono<E, P, S>140- use<Path extends string = string, Data = unknown>(141- arg1: string,142- ...middleware: Handler<Path, E, Data>[]143- ): Hono<E, P, S>144- use(arg1: string | Handler<P, E, S>, ...handlers: Handler<P, E, S>[]) {145- if (typeof arg1 === 'string') {146- this.path = arg1147- } else {148- handlers.unshift(arg1)149- }150- handlers.map((handler) => {151- this.addRoute(METHOD_NAME_ALL, this.path, handler)152- })153- return this154- }155-156- on(method: string, path: string, ...handlers: Handler<P, E, S>[]) {157- if (!method) return this158- this.path = path159- handlers.map((handler) => {160- this.addRoute(method.toUpperCase(), this.path, handler)161- })162- return this163- }164-136 onError(handler: ErrorHandler<E>) {137 this.errorHandler = handler138 return this139 }11 unmodified lines151 )152 })153 }154 184- private addRoute(method: string, path: string, handler: Handler<P, E, S>) {155+ private addRoute(method: string, path: string, handler: H) {156 method = method.toUpperCase()157 if (this._tempPath) {158 path = mergePath(this._tempPath, path)159 }160 this.router.add(method, path, handler)190- const r: Route<P, E, S> = { path: path, method: method, handler: handler }161+ const r: RouterRoute = { path: path, method: method, handler: handler }162 this.routes.push(r)163 }164 165 private matchRoute(method: string, path: string) {166 return this.router.match(method, path)167 }168 198- private handleError(err: unknown, c: Context<string, E>) {169+ private handleError(err: unknown, c: Context<E>) {170 if (err instanceof Error) {171 return this.errorHandler(err, c)172 }173 throw err2 unmodified lines176 private dispatch(177 request: Request,178 eventOrExecutionCtx?: ExecutionContext | FetchEvent,179 env?: E['Bindings']209- ) {180+ ): Response | Promise<Response> {181 const path = getPathFromURL(request.url, this.strict)182 const method = request.method183 184 const result = this.matchRoute(method, path)214- request.paramData = result?.params185+ const paramData = result?.params186 216- const c = new Context<string, E>(request, env, eventOrExecutionCtx, this.notFoundHandler)187+ const c = new Context(request, {188+ env,189+ executionCtx: eventOrExecutionCtx,190+ notFoundHandler: this.notFoundHandler,191+ paramData,192+ })193 194 // Do not `compose` if it has only one handler219- if (result && result.handlers.length === 1) {195+ if (result?.handlers.length === 1) {196 const handler = result.handlers[0]221- let res: ReturnType<Handler<P>>197+ let res: ReturnType<H>198 199 try {224- // eslint-disable-next-line @typescript-eslint/no-explicit-any225- res = handler(c as any, async () => {})226- if (!res) return this.notFoundHandler(c)200+ res = handler(c, async () => {})201+ if (!res) {202+ return this.notFoundHandler(c)203+ }204 } catch (err) {205 return this.handleError(err, c)206 }207 208 if (res instanceof Response) return res209 210+ if ('response' in res) {211+ res = res.response212+ }213+214+ if (res instanceof Response) return res215+216 return (async () => {234- let awaited: Response | undefined | void217+ let awaited: Response | TypedResponse | void218 try {219 awaited = await res220+ if (awaited !== undefined && 'response' in awaited) {221+ awaited = awaited['response'] as Response222+ }223 if (!awaited) {224 return this.notFoundHandler(c)225 }226 } catch (err) {3 unmodified lines230 })()231 }232 233 const handlers = result ? result.handlers : [this.notFoundHandler]248- const composed = compose<Context<P, E>, E>(handlers, this.errorHandler, this.notFoundHandler)234+ const composed = compose<Context>(handlers, this.errorHandler, this.notFoundHandler)235 236 return (async () => {237 try {252- // eslint-disable-next-line @typescript-eslint/no-explicit-any253- const tmp = composed(c as any)238+ const tmp = composed(c)239 const context = tmp instanceof Promise ? await tmp : tmp240 if (!context.finalized) {241 throw new Error(242 'Context is not finalized. You may forget returning Response object or `await next()`'9 unmodified lines252 handleEvent = (event: FetchEvent) => {253 return this.dispatch(event.request, event)254 }255 271- fetch = (request: Request, Environment?: E['Bindings'], executionCtx?: ExecutionContext) => {272- return this.dispatch(request, executionCtx, Environment)256+ fetch = (request: Request, Env?: E['Bindings'] | {}, executionCtx?: ExecutionContext) => {257+ return this.dispatch(request, executionCtx, Env)258 }259 260 request = async (input: Request | string, requestInit?: RequestInit) => {261 const req = input instanceof Request ? input : new Request(input, requestInit)3 unmodified linesadded:src/http-exception.test.ts+13 added
1+import { HTTPException } from './http-exception'2+3+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)8+ expect(exception.status).toBe(401)9+ expect(exception.message).toBe('Unauthorized')10+ const res = exception.getResponse()11+ expect(res.status).toBe(401)12+ })13+})added:src/http-exception.ts+26 added
1+import type { StatusCode } from './utils/http-status'2+import { getStatusText } from './utils/http-status'3+4+type HTTPExceptionOptions = {5+ res?: Response6+ message?: string7+}8+9+export class HTTPException extends Error {10+ readonly res?: Response11+ readonly status: StatusCode12+ constructor(status: StatusCode = 500, options?: HTTPExceptionOptions) {13+ super(options?.message || getStatusText(status))14+ this.res = options?.res15+ this.status = status16+ }17+ getResponse(): Response {18+ if (this.res) {19+ return this.res20+ }21+ return new Response(this.message, {22+ status: this.status,23+ statusText: getStatusText(this.status),24+ })25+ }26+}modified:src/index.ts+6 added-9 removed
1 // @denoify-ignore2-// eslint-disable-next-line @typescript-eslint/triple-slash-reference3-/// <reference path="./request.ts" /> Import "declare global" for the Request interface.2 3 import { Hono } from './hono'4 export type {7- Next,8- ContextVariableMap,9- MiddlewareHandler,5+ Env,6 ErrorHandler,7+ Handler,8+ MiddlewareHandler,9+ Next,10 NotFoundHandler,11+ ValidationTargets,12 } from './types'13-export type { Context } from './context'14-export type { Validator } from './validator/validator'15-import type { CustomHandler } from './types'16-export type { CustomHandler as Handler }13+export type { Context, ContextVariableMap } from './context'14 15 declare module './hono' {16 interface Hono {17 fire(): void12 unmodified linesmodified:src/middleware.ts+1 added-2 removed
9 unmodified lines10 export * from './middleware/jwt'11 export * from './middleware/logger'12 export * from './middleware/powered-by'13 export * from './middleware/pretty-json'14-export * from './middleware/validator'15-export * from './deno/serve-static'14+export * from './adapter/deno/serve-static'modified:src/mod.ts+15 added-8 removed
1 import { Hono } from './hono'2 3 declare global {4+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment5+ // @ts-ignore6 class ExtendableEvent extends Event {7 constructor(type: string, init?: EventInit)8 waitUntil(promise: Promise<void>): void9 }10+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment11+ // @ts-ignore12 abstract class FetchEvent extends ExtendableEvent {13 readonly request: Request14 respondWith(promise: Response | Promise<Response>): void15 passThroughOnException(): void4 unmodified lines20 }21 }22 23 export type {20- Next,21- ContextVariableMap,22- MiddlewareHandler,24+ Env,25 ErrorHandler,26+ Handler,27+ MiddlewareHandler,28+ Next,29 NotFoundHandler,30+ ValidationTargets,31 } from './types'26-import type { CustomHandler } from './types'27-export type { CustomHandler as Handler }28-export type { Context } from './context'32+export type { Context, ContextVariableMap } from './context'33 export { Hono }34 35 // Router36 export { RegExpRouter } from './router/reg-exp-router'37 export { TrieRouter } from './router/trie-router'34-export { StaticRouter } from './router/static-router'38 export { SmartRouter } from './router/smart-router'39 40 // Validator38-export type { Validator } from './validator/validator'41+export { validator } from './validator'42+43+// Client44+export { hc } from './client'45+export type { InferResponseType } from './client'added:src/request.test.ts+59 added
1+import { HonoRequest } from './request'2+3+describe('Query', () => {4+ const rawRequest = new Request('http://localhost?page=2&tag=A&tag=B')5+ const req = new HonoRequest(rawRequest)6+7+ test('req.query() and req.queries()', () => {8+ const page = req.query('page')9+ expect(page).not.toBeUndefined()10+ expect(page).toBe('2')11+12+ const q = req.query('q')13+ expect(q).toBeUndefined()14+15+ const tags = req.queries('tag')16+ expect(tags).not.toBeUndefined()17+ expect(tags).toEqual(['A', 'B'])18+19+ const q2 = req.queries('q2')20+ expect(q2).toBeUndefined()21+ })22+})23+24+describe('req.addValidatedData() and req.data()', () => {25+ const rawRequest = new Request('http://localhost')26+27+ const payload = {28+ title: 'hello',29+ author: {30+ name: 'young man',31+ age: 20,32+ },33+ }34+35+ test('add data - json', () => {36+ const req = new HonoRequest(rawRequest)37+ req.addValidatedData('json', payload)38+ const data = req.valid('json')39+ expect(data).toEqual(payload)40+ })41+42+ test('replace data - json', () => {43+ const req = new HonoRequest(rawRequest)44+ req.addValidatedData('json', payload)45+ req.addValidatedData('json', {46+ tag: ['sport', 'music'],47+ author: {48+ tall: 170,49+ },50+ })51+ const data = req.valid('json')52+ expect(data).toEqual({53+ author: {54+ tall: 170,55+ },56+ tag: ['sport', 'music'],57+ })58+ })59+})modified:src/request.ts+139 added-134 removed
1+import type {2+ Input,3+ InputToDataByTarget,4+ ParamKeys,5+ ParamKeyToRecord,6+ RemoveQuestion,7+ UndefinedIfHavingQuestion,8+ ValidationTargets,9+} from './types'10 import { parseBody } from './utils/body'11 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'6-import { getQueryStringFromURL } from './utils/url'15+import { getQueryStringFromURL, getQueryParam, getQueryParams } from './utils/url'16 8-type RemoveQuestion<T> = T extends `${infer R}?` ? R : T9-// eslint-disable-next-line @typescript-eslint/no-unused-vars10-type UndefinedIfHavingQuestion<T> = T extends `${infer _}?` ? string | undefined : string11-type ParamKeyToRecord<T extends string> = T extends `${infer R}?`12- ? Record<R, string | undefined>13- : Record<T, string>17+export class HonoRequest<P extends string = '/', I extends Input = {}> {18+ raw: Request19 15-declare global {16- interface Request<17- // eslint-disable-next-line @typescript-eslint/no-unused-vars18- CfHostMetadata = unknown,19- ParamKey extends string = string,20- // eslint-disable-next-line @typescript-eslint/no-explicit-any21- Data = any22- > {23- paramData?: Record<ParamKey, string>24- param: {25- (key: RemoveQuestion<ParamKey>): UndefinedIfHavingQuestion<ParamKey>26- (): UnionToIntersection<ParamKeyToRecord<ParamKey>>27- }28- queryData?: Record<string, string>29- query: {30- (key: string): string31- (): Record<string, string>32- }33- queries: {34- (key: string): string[]35- (): Record<string, string[]>36- }37- headerData?: Record<string, string>38- header: {39- (name: string): string | undefined40- (): Record<string, string>41- }42- cookie: {43- (name: string): string | undefined44- (): Cookie45- }46- bodyData?: BodyData47- parseBody<BodyType extends BodyData>(): Promise<BodyType>48- // eslint-disable-next-line @typescript-eslint/no-explicit-any49- jsonData?: any50- json<T>(): Promise<T>51- data: Data52- valid: {53- (data: Data): Data54- (): Data55- }56- }57-}20+ private paramData: Record<string, string> | undefined21+ private validatedData: { [K in keyof ValidationTargets]?: {} }22 59-export function extendRequestPrototype() {60- if (!!Request.prototype.param as boolean) {61- // already extended62- return23+ constructor(request: Request, paramData?: Record<string, string> | undefined) {24+ this.raw = request25+ this.paramData = paramData26+ this.validatedData = {}27 }28 65- Request.prototype.param = function (this: Request, key?: string) {29+ param(key: RemoveQuestion<ParamKeys<P>>): UndefinedIfHavingQuestion<ParamKeys<P>>30+ param(): UnionToIntersection<ParamKeyToRecord<ParamKeys<P>>>31+ param(key?: string): unknown {32 if (this.paramData) {33 if (key) {34 const param = this.paramData[key]69- return param ? decodeURIComponent(param) : undefined35+ return param ? (/\%/.test(param) ? decodeURIComponent(param) : param) : undefined36 } else {37 const decoded: Record<string, string> = {}38 39 for (const [key, value] of Object.entries(this.paramData)) {74- if (value) {75- decoded[key] = decodeURIComponent(value)40+ if (value && typeof value === 'string') {41+ decoded[key] = /\%/.test(value) ? decodeURIComponent(value) : value42 }43 }44 45 return decoded46 }47 }48 return null83- } as InstanceType<typeof Request>['param']49+ }50 85- Request.prototype.header = function (this: Request, name?: string) {86- if (!this.headerData) {87- this.headerData = {}88- this.headers.forEach((value, key) => {89- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion90- this.headerData![key] = value91- })92- }93- if (name) {94- return this.headerData[name.toLowerCase()]95- } else {96- return this.headerData97- }98- } as InstanceType<typeof Request>['header']99-100- Request.prototype.query = function (this: Request, key?: string) {51+ query(key: string): string | undefined52+ query(): Record<string, string>53+ query(key?: string) {54 const queryString = getQueryStringFromURL(this.url)102- const searchParams = new URLSearchParams(queryString)103- if (!this.queryData) {104- this.queryData = {}105- for (const key of searchParams.keys()) {106- this.queryData[key] = searchParams.get(key) || ''107- }108- }109- if (key) {110- return this.queryData[key]111- } else {112- return this.queryData113- }114- } as InstanceType<typeof Request>['query']55+ const result = getQueryParam(queryString, key)56+ if (result === null) return undefined57+ return result58+ }59 116- Request.prototype.queries = function (this: Request, key?: string) {60+ queries(key: string): string[] | undefined61+ queries(): Record<string, string[]>62+ queries(key?: string) {63 const queryString = getQueryStringFromURL(this.url)118- const searchParams = new URLSearchParams(queryString)119- if (key) {120- return searchParams.getAll(key)121- } else {122- const result: Record<string, string[]> = {}123- for (const key of searchParams.keys()) {124- result[key] = searchParams.getAll(key)125- }126- return result64+ const result = getQueryParams(queryString, key)65+ if (result === null) return undefined66+ return result67+ }68+69+ header(name: string): string | undefined70+ header(): Record<string, string>71+ header(name?: string) {72+ const headerData: Record<string, string> = {}73+ this.raw.headers.forEach((value, key) => {74+ headerData[key] = value75+ })76+ if (!name) {77+ return headerData78 }128- } as InstanceType<typeof Request>['queries']79+ return headerData[name.toLowerCase()] || undefined80+ }81 130- Request.prototype.cookie = function (this: Request, key?: string) {131- const cookie = this.headers.get('Cookie') || ''82+ cookie(key: string): string | undefined83+ cookie(): Cookie84+ cookie(key?: string) {85+ const cookie = this.raw.headers.get('Cookie')86+ if (!cookie) return87 const obj = parse(cookie)88 if (key) {89 const value = obj[key]90 return value91 } else {92 return obj93 }139- } as InstanceType<typeof Request>['cookie']94+ }95 141- Request.prototype.parseBody = async function <BodyType extends BodyData>(142- this: Request143- ): Promise<BodyType> {144- // Cache the parsed body145- let body: BodyType146- if (!this.bodyData) {147- body = await parseBody<BodyType>(this)148- this.bodyData = body149- } else {150- body = this.bodyData as BodyType151- }152- return body153- } as InstanceType<typeof Request>['parseBody']96+ async parseBody(): Promise<BodyData> {97+ return await parseBody(this.raw)98+ }99 155- Request.prototype.json = async function <JSONData = unknown>(this: Request) {156- // Cache the JSON body157- let jsonData: Partial<JSONData>158- if (!this.jsonData) {159- jsonData = JSON.parse(await this.text())160- this.jsonData = jsonData161- } else {162- jsonData = this.jsonData163- }164- return jsonData165- } as InstanceType<typeof Request>['jsonData']100+ // eslint-disable-next-line @typescript-eslint/no-explicit-any101+ json<T = any>(): Promise<T> {102+ return this.raw.json()103+ }104 167- Request.prototype.valid = function (this: Request, data?: unknown) {168- if (!this.data) {169- this.data = {}105+ text() {106+ return this.raw.text()107+ }108+109+ arrayBuffer() {110+ return this.raw.arrayBuffer()111+ }112+113+ blob() {114+ return this.raw.blob()115+ }116+117+ formData() {118+ return this.raw.formData()119+ }120+121+ addValidatedData(target: keyof ValidationTargets, data: {}) {122+ this.validatedData[target] = data123+ }124+125+ valid<126+ T extends keyof ValidationTargets = I extends Record<infer R, unknown>127+ ? R extends keyof ValidationTargets128+ ? R129+ : never130+ : never131+ >(target: T): InputToDataByTarget<I, T>132+ valid(): never133+ valid(target?: keyof ValidationTargets) {134+ if (target) {135+ return this.validatedData[target] as unknown136 }171- if (data) {172- this.data = data173- }174- return this.data175- } as InstanceType<typeof Request>['valid']137+ }138+139+ get url() {140+ return this.raw.url141+ }142+ get method() {143+ return this.raw.method144+ }145+ get headers() {146+ return this.raw.headers147+ }148+ get redirect() {149+ return this.raw.redirect150+ }151+ get body() {152+ return this.raw.body153+ }154+ get bodyUsed() {155+ return this.raw.bodyUsed156+ }157+ get cache() {158+ return this.raw.cache159+ }160+ get credentials() {161+ return this.raw.credentials162+ }163+ get integrity() {164+ return this.raw.integrity165+ }166+ get keepalive() {167+ return this.raw.keepalive168+ }169+ get mode() {170+ return this.raw.mode171+ }172+ get referrer() {173+ return this.raw.referrer174+ }175+ get refererPolicy() {176+ return this.raw.referrerPolicy177+ }178+ get signal() {179+ return this.raw.signal180+ }181 }modified:src/types.test.ts+280 added-131 removed
1+/* eslint-disable @typescript-eslint/ban-types */2 /* eslint-disable @typescript-eslint/no-unused-vars */3+import type { Context } from './context'4 import { Hono } from './hono'3-import { validator } from './middleware/validator'4-import type { CustomHandler as Handler, MiddlewareHandler } from './types'5-import type { Expect, Equal, NotEqual } from './utils/types'6-import type { Validator } from './validator/validator'5+import { poweredBy } from './middleware/powered-by'6+import type {7+ Env,8+ ExtractSchema,9+ Handler,10+ InputToDataByTarget,11+ MiddlewareHandler,12+ ParamKeys,13+ ParamKeyToRecord,14+ RemoveQuestion,15+ Schema,16+ UndefinedIfHavingQuestion,17+} from './types'18+import type { Expect, Equal } from './utils/types'19 20+describe('Env', () => {8-describe('Test types of CustomHandler', () => {9- type Env = {10- Variables: {11- foo: string21+ test('Env', () => {22+ type E = {23+ Variables: {24+ foo: string25+ }26+ Bindings: {27+ FLAG: boolean28+ }29 }13- }30+ const app = new Hono<E>()31+ app.use('*', poweredBy())32+ app.get('/', (c) => {33+ const foo = c.get('foo')34+ type verify = Expect<Equal<string, typeof foo>>35+ const FLAG = c.env.FLAG36+ type verify2 = Expect<Equal<boolean, typeof FLAG>>37+ return c.text('foo')38+ })39+ })40+})41 15- let app: Hono42+describe('HandlerInterface', () => {43+ type Env = {}44 17- beforeEach(() => {18- app = new Hono()45+ describe('no path pattern', () => {46+ const app = new Hono<Env>()47+ const middleware: MiddlewareHandler<48+ Env,49+ never,50+ { json: { foo: string; bar: boolean } }51+ > = async (_c, next) => {52+ await next()53+ }54+ test('Context', () => {55+ const route = app.get(middleware, (c) => {56+ type Expected = Context<Env, never, { json: { foo: string; bar: boolean } }>57+ type verify = Expect<Equal<Expected, typeof c>>58+ return c.jsonT({59+ message: 'Hello!',60+ })61+ })62+ app.get(middleware, (c) => {63+ const data = c.req.valid('json')64+ type verify = Expect<Equal<{ foo: string; bar: boolean }, typeof data>>65+ return c.jsonT({66+ message: 'Hello!',67+ })68+ })69+ })70 })71 21- const schema = (v: Validator) => ({22- query: v.query('q').isRequired(),72+ describe('path pattern', () => {73+ const app = new Hono<Env>()74+ const middleware: MiddlewareHandler<75+ Env,76+ '/foo',77+ { json: { foo: string; bar: boolean } }78+ > = async (_c, next) => {79+ await next()80+ }81+ test('Context and AppType', () => {82+ const route = app.get('/foo', middleware, (c) => {83+ type Expected = Context<Env, '/foo', { json: { foo: string; bar: boolean } }>84+ type verify = Expect<Equal<Expected, typeof c>>85+ return c.jsonT({86+ message: 'Hello!',87+ })88+ })89+ type Actual = ExtractSchema<typeof route>90+ type Expected = {91+ '/foo': {92+ $get: {93+ input: {94+ json: {95+ foo: string96+ bar: boolean97+ }98+ }99+ output: {100+ message: string101+ }102+ }103+ }104+ }105+ type verify = Expect<Equal<Expected, Actual>>106+ })107 })24- type Schema = ReturnType<typeof schema>25- const url = 'http://localhost/'108+})109 27- test('No arguments', async () => {28- const handler: Handler = (c) => {29- const data = c.req.valid()30- // eslint-disable-next-line @typescript-eslint/no-explicit-any31- type verifySchema = Expect<Equal<typeof data['foo'], any>>32- return c.text('Hi')110+describe('OnHandlerInterface', () => {111+ const app = new Hono()112+ test('Context', () => {113+ const middleware: MiddlewareHandler<Env, '/purge', { form: { id: number } }> = async (114+ _c,115+ next116+ ) => {117+ await next()118 }34- app.get('/', handler)35- const res = await app.request(url)36- expect(res.status).toBe(200)119+ const route = app.on('PURGE', '/purge', middleware, (c) => {120+ const data = c.req.valid('form')121+ type verify = Expect<Equal<{ id: number }, typeof data>>122+ return c.jsonT({123+ success: true,124+ })125+ })126+ type Actual = ExtractSchema<typeof route>127+ type Expected = {128+ '/purge': {129+ $purge: {130+ input: {131+ form: {132+ id: number133+ }134+ }135+ output: {136+ success: boolean137+ }138+ }139+ }140+ }141+ type verify = Expect<Equal<Expected, Actual>>142 })143+})144 39- test('Path', async () => {40- const handler: Handler<'id'> = (c) => {41- const id = c.req.param('id')42- type verifyPath = Expect<Equal<typeof id, string>>43- const data = c.req.valid()44- // eslint-disable-next-line @typescript-eslint/no-explicit-any45- type verifySchema = Expect<Equal<typeof data['foo'], any>>46- return c.text('Hi')145+describe('Schema', () => {146+ test('Schema', () => {147+ type AppType = Hono<148+ Env,149+ Schema<150+ 'post',151+ '/api/posts/:id',152+ {153+ json: {154+ id: number155+ title: string156+ }157+ },158+ {159+ message: string160+ success: boolean161+ }162+ >163+ >164+165+ type Actual = ExtractSchema<AppType>166+ type Expected = {167+ '/api/posts/:id': {168+ $post: {169+ input: {170+ json: {171+ id: number172+ title: string173+ }174+ } & {175+ param: {176+ id: string177+ }178+ }179+ output: {180+ message: string181+ success: boolean182+ }183+ }184+ }185 }48- app.get('/', handler)49- const res = await app.request(url)50- expect(res.status).toBe(200)186+ type verify = Expect<Equal<Expected, Actual>>187 })188+})189 53- test('Path, Env', async () => {54- const handler: Handler<'id', Env> = (c) => {55- const id = c.req.param('id')56- type verifyPath = Expect<Equal<typeof id, string>>57- const foo = c.get('foo')58- type verifyEnv = Expect<Equal<typeof foo, string>>59- const data = c.req.valid()60- // eslint-disable-next-line @typescript-eslint/no-explicit-any61- type verifySchema = Expect<Equal<typeof data['foo'], any>>62- return c.text('Hi')190+describe('Test types of Handler', () => {191+ type E = {192+ Variables: {193+ foo: number194 }64- app.get('/', handler)65- const res = await app.request(url)66- expect(res.status).toBe(200)67- })195+ }196 69- test('Path, Env, Schema', async () => {70- const handler: Handler<'id', Env, Schema> = (c) => {71- const id = c.req.param('id')72- type verifyPath = Expect<Equal<typeof id, string>>197+ const url = 'http://localhost/'198+199+ test('Env', async () => {200+ const app = new Hono<E>()201+ const handler: Handler<E> = (c) => {202 const foo = c.get('foo')74- type verifyEnv = Expect<Equal<typeof foo, string>>75- const { query } = c.req.valid()76- type verifySchema = Expect<Equal<typeof query, string>>203+ type verifyEnv = Expect<Equal<number, typeof foo>>204+ const id = c.req.param('id')205+ type verifyPath = Expect<Equal<string, typeof id>>206 return c.text('Hi')207 }208 app.get('/', handler)209 const res = await app.request(url)210 expect(res.status).toBe(200)211 })212 84- test('Env', async () => {85- const handler: Handler<Env> = (c) => {213+ test('Env, Path', async () => {214+ const app = new Hono<E>()215+ const handler: Handler<E, '/'> = (c) => {216 const foo = c.get('foo')87- type verifyEnv = Expect<Equal<typeof foo, string>>88- const { query } = c.req.valid()89- type verifySchema = Expect<NotEqual<typeof query, string>>217+ type verifyEnv = Expect<Equal<number, typeof foo>>218 return c.text('Hi')219 }220 app.get('/', handler)221+222 const res = await app.request(url)223 expect(res.status).toBe(200)224 })225 97- test('Env, Schema', async () => {98- const handler: Handler<Env, Schema> = (c) => {226+ type User = {227+ name: string228+ age: number229+ }230+231+ test('Env, Path, Type', async () => {232+ const app = new Hono<E>()233+ const handler: Handler<E, '/', { json: User }> = (c) => {234 const foo = c.get('foo')100- type verifyEnv = Expect<Equal<typeof foo, string>>101- const { query } = c.req.valid()102- type verifySchema = Expect<Equal<typeof query, string>>235+ type verifyEnv = Expect<Equal<number, typeof foo>>236+ const { name } = c.req.valid('json')237+ type verifySchema = Expect<Equal<string, typeof name>>238 return c.text('Hi')239 }105- app.get('/', handler)106- const res = await app.request(url)107- expect(res.status).toBe(200)240 })241+})242 110- test('Schema', async () => {111- const handler: Handler<Schema> = (c) => {112- const { query } = c.req.valid()113- type verifySchema = Expect<Equal<typeof query, string>>114- return c.text('Hi')115- }116- app.get('/', handler)117- const res = await app.request(url)118- expect(res.status).toBe(200)243+describe('`jsonT()`', () => {244+ const app = new Hono<{ Variables: { foo: string } }>()245+246+ app.get('/post/:id', (c) => {247+ c.req.param('id')248+ const id = c.req.param('id')249+ return c.text('foo')250 })251 121- test('Complex', async () => {122- const app = new Hono<Env>()123- const handler: Handler<Env> = (c) => {124- const foo = c.get('foo')125- type verifyEnv = Expect<Equal<typeof foo, string>>126- const data = c.req.valid()127- // eslint-disable-next-line @typescript-eslint/no-explicit-any128- type verifySchema = Expect<Equal<typeof data['foo'], any>>129- return c.text(foo)130- }131- app.get(132- '/',133- async (c, next) => {134- c.set('foo', 'bar')135- await next()136- },137- handler138- )139- app.get('/v', validator(schema), (c) => {140- const { query } = c.req.valid()141- type verify = Expect<Equal<typeof query, string>>142- return c.text(query)252+ const route = app.get('/hello', (c) => {253+ return c.jsonT({254+ message: 'Hello!',255 })144- let res = await app.request(url)145- expect(res.status).toBe(200)146- expect(await res.text()).toBe('bar')147-148- res = await app.request('http://localhost/?q=bar')149- expect(res.status).toBe(200)150- expect(await res.text()).toBe('bar')256 })257 153- test('Normal types', () => {154- type User = {155- name: string156- age: number157- }258+ test('jsonT', () => {259+ type Actual = ExtractSchema<typeof route>260 159- const handler: Handler<User> = (c) => {160- const user = c.req.valid()161- type verifySchema = Expect<Equal<typeof user, User>>162- return c.text('Hi')261+ type Expected = {262+ '/hello': {263+ $get: {264+ input: {}265+ output: {266+ message: string267+ }268+ }269+ }270 }271+272+ type verify = Expect<Equal<Expected, Actual>>273 })274 })275 167-describe('CustomHandler as middleware', () => {168- const app = new Hono()169- const mid1 = (): MiddlewareHandler => {170- return async (_c, next) => {171- await next()276+describe('Path parameters', () => {277+ test('ParamKeys', () => {278+ type Actual = ParamKeys<'/posts/:postId/comment/:commentId'>279+ type Expected = 'postId' | 'commentId'280+ type verify = Expect<Equal<Expected, Actual>>281+ })282+283+ describe('ParamKeyToRecord', () => {284+ test('With ?', () => {285+ type Actual = ParamKeyToRecord<'/animal/type?'>286+ type Expected = { [K in '/animal/type']: string | undefined }287+ type verify = Expect<Equal<Expected, Actual>>288+ })289+ test('Without ?', () => {290+ type Actual = ParamKeyToRecord<'/animal/type'>291+ type Expected = { [K in '/animal/type']: string }292+ type verify = Expect<Equal<Expected, Actual>>293+ })294+ })295+})296+297+describe('For HonoRequest', () => {298+ type Input = {299+ json: {300+ id: number301+ title: string302 }303+ query: {304+ page: string305+ }306 }307 175- const mid2 = (): Handler<{ Foo: string }> => {176- return async (_c, next) => {177- await next()308+ test('InputToDataByType with value', () => {309+ type Actual = InputToDataByTarget<Input, 'json'>310+ type Expected = {311+ id: number312+ title: string313 }179- }314+ type verify = Expect<Equal<Expected, Actual>>315+ })316 181- it('Should not throw Type error', async () => {182- app.get('*', mid1(), mid2(), (c) => {183- return c.text('foo')317+ test('InputToDataByType without value', () => {318+ type Actual = InputToDataByTarget<Input, 'form'>319+ type verify = Expect<Equal<never, Actual>>320+ })321+322+ test('RemoveQuestion', () => {323+ type Actual = RemoveQuestion<'/animal/type?'>324+ type verify = Expect<Equal<'/animal/type', Actual>>325+ })326+327+ describe('UndefinedIfHavingQuestion', () => {328+ test('With ?', () => {329+ type Actual = UndefinedIfHavingQuestion<'/animal/type?'>330+ type verify = Expect<Equal<string | undefined, Actual>>331 })185- const res = await app.request('http://localhost/')186- expect(res.status).toBe(200)332+ test('Without ?', () => {333+ type Actual = UndefinedIfHavingQuestion<'/animal/type'>334+ type verify = Expect<Equal<string, Actual>>335+ })336 })337 })modified:src/types.ts+278 added-53 removed
1+/* eslint-disable @typescript-eslint/no-unused-vars */2+/* eslint-disable @typescript-eslint/no-explicit-any */3+/* eslint-disable @typescript-eslint/ban-types */4 import type { Context } from './context'5+import type { Hono } from './hono'6+import type { UnionToIntersection } from './utils/types'7 3-export interface ContextVariableMap {}8+////////////////////////////////////////9+////// //////10+////// Values //////11+////// //////12+////////////////////////////////////////13 5-// eslint-disable-next-line @typescript-eslint/no-explicit-any6-export type Bindings = Record<string, any> // For Cloudflare Workers7-// eslint-disable-next-line @typescript-eslint/no-explicit-any8-export type Variables = Record<string, any> // For c.set/c.get functions9-export type Environment = {10- Bindings: Bindings11- Variables: Variables14+export type Bindings = Record<string, unknown>15+export type Variables = Record<string, unknown>16+17+export type Env = {18+ Bindings?: Bindings19+ Variables?: Variables20 }21 22+export type Next = () => Promise<void>23+24+export type Input = unknown25+26+////////////////////////////////////////27+////// //////28+////// Handlers //////29+////// //////30+////////////////////////////////////////31+32 export type Handler<15- P extends string = string,16- E extends Partial<Environment> = Environment,17- // eslint-disable-next-line @typescript-eslint/no-explicit-any18- S = any19-> = (c: Context<P, E, S>, next: Next) => Response | Promise<Response | undefined | void>33+ E extends Env = any,34+ P extends string = any,35+ I extends Input = Input,36+ O = {}37+> = (38+ c: Context<E, P, I>,39+ next: Next40+) => Response | Promise<Response | TypedResponse<O>> | TypedResponse<O>41 21-export type MiddlewareHandler<22- P extends string = string,23- E extends Partial<Environment> = Environment,24- // eslint-disable-next-line @typescript-eslint/no-explicit-any25- S = any26-> = (c: Context<P, E, S>, next: Next) => Promise<Response | undefined | void>42+export type MiddlewareHandler<E extends Env = any, P extends string = any, I extends Input = {}> = (43+ c: Context<E, P, I>,44+ next: Next45+) => Promise<Response | void>46 28-export type NotFoundHandler<E extends Partial<Environment> = Environment> = (29- c: Context<string, E>30-) => Response | Promise<Response>47+export type H<E extends Env = any, P extends string = any, I extends Input = {}, O = {}> =48+ | Handler<E, P, I, O>49+ | MiddlewareHandler<E, P, I>50 32-export type ErrorHandler<E extends Partial<Environment> = Environment> = (33- err: Error,34- c: Context<string, E>35-) => Response51+export type NotFoundHandler<E extends Env = any> = (c: Context<E>) => Response | Promise<Response>52+export type ErrorHandler<E extends Env = any> = (err: Error, c: Context<E>) => Response53 37-export type Next = () => Promise<void>54+////////////////////////////////////////55+////// //////56+////// HandlerInterface //////57+////// //////58+////////////////////////////////////////59 60+export interface HandlerInterface<E extends Env = Env, M extends string = any, S = {}> {61+ //// app.get(...handlers[])62+63+ // app.get(handler, handler)64+ <I = {}, O = {}>(...handlers: [H<E, ExtractKey<S>, I, O>, H<E, ExtractKey<S>, I, O>]): Hono<65+ E,66+ S & Schema<M, ExtractKey<S>, I, O>67+ >68+69+ // app.get(handler x 3)70+ <P extends string, O = {}, I = {}, I2 = I, I3 = I & I2>(71+ ...handlers: [H<E, ExtractKey<S>, I, O>, H<E, ExtractKey<S>, I2, O>, H<E, ExtractKey<S>, I3, O>]72+ ): Hono<E, S & Schema<M, ExtractKey<S>, I3, O>>73+74+ // app.get(handler x 4)75+ <P extends string, O = {}, I = {}, I2 = I, I3 = I & I2, I4 = I2 & I3>(76+ ...handlers: [77+ H<E, ExtractKey<S>, I, O>,78+ H<E, ExtractKey<S>, I2, O>,79+ H<E, ExtractKey<S>, I3, O>,80+ H<E, ExtractKey<S>, I4, O>81+ ]82+ ): Hono<E, S & Schema<M, ExtractKey<S>, I4, O>>83+84+ // app.get(handler x 5)85+ <P extends string, O = {}, I = {}, I2 = I, I3 = I & I2, I4 = I2 & I3, I5 = I3 & I4>(86+ ...handlers: [87+ H<E, ExtractKey<S>, I, O>,88+ H<E, ExtractKey<S>, I2, O>,89+ H<E, ExtractKey<S>, I3, O>,90+ H<E, ExtractKey<S>, I4, O>,91+ H<E, ExtractKey<S>, I5, O>92+ ]93+ ): Hono<E, S & Schema<M, ExtractKey<S>, I5, O>>94+95+ // app.get(...handlers[])96+ <I = {}, O = {}>(...handlers: Handler<E, ExtractKey<S>, I, O>[]): Hono<97+ E,98+ S & Schema<M, ExtractKey<S>, I, O>99+ >100+101+ //// app.get(path, ...handlers[])102+103+ // app.get(path, handler, handler)104+ <P extends string, O = {}, I = {}>(path: P, ...handlers: [H<E, P, I, O>, H<E, P, I, O>]): Hono<105+ E,106+ S & Schema<M, P, I, O>107+ >108+109+ // app.get(path, handler x3)110+ <P extends string, O = {}, I = {}, I2 = I, I3 = I & I2>(111+ path: P,112+ ...handlers: [H<E, P, I, O>, H<E, P, I2, O>, H<E, P, I3, O>]113+ ): Hono<E, S & Schema<M, P, I3, O>>114+115+ // app.get(path, handler x4)116+ <P extends string, O = {}, I = {}, I2 = I, I3 = I & I2, I4 = I2 & I3>(117+ path: P,118+ ...handlers: [H<E, P, I, O>, H<E, P, I2, O>, H<E, P, I3, O>, H<E, P, I4, O>]119+ ): Hono<E, S & Schema<M, P, I4, O>>120+121+ // app.get(path, handler x5)122+ <P extends string, O = {}, I = {}, I2 = I, I3 = I & I2, I4 = I2 & I3, I5 = I3 & I4>(123+ path: P,124+ ...handlers: [H<E, P, I, O>, H<E, P, I2, O>, H<E, P, I3, O>, H<E, P, I4, O>, H<E, P, I5, O>]125+ ): Hono<E, S & Schema<M, P, I5, O>>126+127+ // app.get(path, ...handlers[])128+ <P extends string, I = {}, O = {}>(path: P, ...handlers: H<E, P, I, O>[]): Hono<129+ E,130+ S & Schema<M, P, I, O>131+ >132+}133+134+////////////////////////////////////////135+////// //////136+////// MiddlewareHandlerInterface //////137+////// //////138+////////////////////////////////////////139+140+export interface MiddlewareHandlerInterface<E extends Env = Env, S = {}> {141+ //// app.get(...handlers[])142+ (...handlers: MiddlewareHandler<E, ExtractKey<S>>[]): Hono<E, S>143+ //// app.get(path, ...handlers[])144+ <P extends string>(path: P, ...handlers: MiddlewareHandler<E, P>[]): Hono<E, S>145+}146+147+////////////////////////////////////////148+////// //////149+////// OnHandlerInterface //////150+////// //////151+////////////////////////////////////////152+153+export interface OnHandlerInterface<E extends Env = Env, S = {}> {154+ // app.on(method, path, handler, handler)155+ <M extends string, P extends string, O = {}, I = {}>(156+ method: M,157+ path: P,158+ ...handlers: [H<E, P, I, O>, H<E, P, I, O>]159+ ): Hono<E, S & Schema<M, P, I, O>>160+161+ // app.get(method, path, handler x3)162+ <M extends string, P extends string, O = {}, I = {}, I2 = I, I3 = I & I2>(163+ method: M,164+ path: P,165+ ...handlers: [H<E, P, I, O>, H<E, P, I2, O>, H<E, P, I3, O>]166+ ): Hono<E, S & Schema<M, P, I3, O>>167+168+ // app.get(method, path, handler x4)169+ <M extends string, P extends string, O = {}, I = {}, I2 = I, I3 = I & I2, I4 = I2 & I3>(170+ method: M,171+ path: P,172+ ...handlers: [H<E, P, I, O>, H<E, P, I2, O>, H<E, P, I3, O>, H<E, P, I4, O>]173+ ): Hono<E, S & Schema<M, P, I4, O>>174+175+ // app.get(method, path, handler x5)176+ <177+ M extends string,178+ P extends string,179+ O = {},180+ I = {},181+ I2 = I,182+ I3 = I & I2,183+ I4 = I2 & I3,184+ I5 = I3 & I4185+ >(186+ method: M,187+ path: P,188+ ...handlers: [H<E, P, I, O>, H<E, P, I2, O>, H<E, P, I3, O>, H<E, P, I4, O>, H<E, P, I5, O>]189+ ): Hono<E, S & Schema<M, P, I5, O>>190+191+ <M extends string, P extends string, O extends {} = {}, I = {}>(192+ method: M,193+ path: P,194+ ...handlers: H<E, P, I, O>[]195+ ): Hono<E, S & Schema<M, P, I, O>>196+197+ // app.on(method[], path, ...handler)198+ <P extends string, O extends {} = {}, I = {}>(199+ methods: string[],200+ path: P,201+ ...handlers: H<E, P, I, O>[]202+ ): Hono<E, S & Schema<string, P, I, O>>203+}204+205+type ExtractKey<S> = S extends Record<infer Key, unknown>206+ ? Key extends string207+ ? Key208+ : never209+ : string210+211+////////////////////////////////////////212+////// //////213+////// Schema //////214+////// //////215+////////////////////////////////////////216+217+export type Schema<M extends string, P extends string, I extends Input, O> = {218+ [K in P]: AddDollar<{ [K2 in M]: { input: AddParam<I, P>; output: O } }>219+}220+221+export type AddParam<I, P extends string> = ParamKeys<P> extends never222+ ? I223+ : I & { param: UnionToIntersection<ParamKeyToRecord<ParamKeys<P>>> }224+225+export type AddDollar<T> = T extends Record<infer K, infer R>226+ ? K extends string227+ ? { [MethodName in `$${Lowercase<K>}`]: R }228+ : never229+ : never230+231+////////////////////////////////////////232+////// //////233+////// TypedResponse //////234+////// //////235+////////////////////////////////////////236+237+export type TypedResponse<T = unknown> = {238+ response: Response | Promise<Response>239+ data: T240+ format: 'json' // Currently, support only `json` with `c.jsonT()`241+}242+243+////////////////////////////////////////244+////// /////245+////// ValidationTargets /////246+////// /////247+////////////////////////////////////////248+249+export type ValidationTargets = {250+ json: any251+ form: Record<string, string | File>252+ query: Record<string, string>253+ queries: Record<string, string[]>254+}255+256+////////////////////////////////////////257+////// //////258+////// Path parameters //////259+////// //////260+////////////////////////////////////////261+262 // eslint-disable-next-line @typescript-eslint/no-unused-vars263 type ParamKeyName<NameWithPattern> = NameWithPattern extends `${infer Name}{${infer _Pattern}`264 ? Name265 : NameWithPattern5 unmodified lines271 export type ParamKeys<Path> = Path extends `${infer Component}/${infer Rest}`272 ? ParamKey<Component> | ParamKeys<Rest>273 : ParamKey<Path>274 52-// This is not used for internally53-// Will be used by users as `Handler`54-// eslint-disable-next-line @typescript-eslint/no-explicit-any55-export interface CustomHandler<P = string, E = Partial<Environment>, S = any> {56- (57- c: Context<58- P extends string ? P : string,59- P extends Partial<Environment> ? P : E extends Partial<Environment> ? E : never,60- P extends string61- ? E extends Partial<Environment>62- ? S63- : P extends Partial<Environment>64- ? E65- : never66- : P extends Partial<Environment>67- ? E extends Partial<Environment>68- ? S69- : E70- : P71- >,72- next: Next73- ): Response | Promise<Response | undefined | void>74-}275+export type ParamKeyToRecord<T extends string> = T extends `${infer R}?`276+ ? Record<R, string | undefined>277+ : { [K in T]: string }278 76-export interface ExecutionContext {77- waitUntil(promise: Promise<void>): void78- passThroughOnException(): void279+////////////////////////////////////////280+////// //////281+///// For HonoRequest //////282+////// //////283+////////////////////////////////////////284+285+export type InputToDataByTarget<286+ T extends Input,287+ Target extends keyof ValidationTargets288+> = T extends {289+ [K in Target]: infer R290 }291+ ? R292+ : never293+294+export type RemoveQuestion<T> = T extends `${infer R}?` ? R : T295+296+export type UndefinedIfHavingQuestion<T> = T extends `${infer _}?` ? string | undefined : string297+298+////////////////////////////////////////299+////// //////300+////// Utilities //////301+////// //////302+////////////////////////////////////////303+304+export type ExtractSchema<T> = T extends Hono<infer _, infer S> ? S : neveradded:test_bun/favicon.icobinary
A binary file, added.
added:test_bun/index.test.tsx+161 added
1+import { describe, expect, it } from 'bun:test'2+import { serveStatic } from '../src/adapter/bun'3+import { Context } from '../src/context'4+import { Hono } from '../src/index'5+import { basicAuth } from '../src/middleware/basic-auth'6+import { jwt } from '../src/middleware/jwt'7+8+// Test just only minimal patterns.9+// Because others are tested well in Cloudflare Workers environment already.10+11+describe('Basic', () => {12+ const app = new Hono()13+ app.get('/a/:foo', (c) => {14+ c.header('x-param', c.req.param('foo'))15+ c.header('x-query', c.req.query('q'))16+ return c.text('Hello Deno!')17+ })18+19+ it('Should return 200 Response', async () => {20+ const req = new Request('http://localhost/a/foo?q=bar')21+ const res = await app.request(req)22+ expect(res.status).toBe(200)23+ expect(await res.text()).toBe('Hello Deno!')24+ expect(res.headers.get('x-param')).toBe('foo')25+ expect(res.headers.get('x-query')).toBe('bar')26+ })27+28+ it('returns current runtime (bun)', async () => {29+ const c = new Context(new Request('http://localhost/'))30+ expect(c.runtime).toBe('bun')31+ })32+})33+34+describe('Basic Auth Middleware', () => {35+ const app = new Hono()36+37+ const username = 'hono-user-a'38+ const password = 'hono-password-a'39+ app.use(40+ '/auth/*',41+ basicAuth({42+ username,43+ password,44+ })45+ )46+47+ app.get('/auth/*', () => new Response('auth'))48+49+ it('Should not authorize, return 401 Response', async () => {50+ const req = new Request('http://localhost/auth/a')51+ const res = await app.request(req)52+ expect(res.status).toBe(401)53+ expect(await res.text()).toBe('Unauthorized')54+ })55+56+ it('Should authorize, return 200 Response', async () => {57+ const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'58+ const req = new Request('http://localhost/auth/a')59+ req.headers.set('Authorization', `Basic ${credential}`)60+ const res = await app.request(req)61+ expect(res.status).toBe(200)62+ expect(await res.text()).toBe('auth')63+ })64+})65+66+describe('Serve Static Middleware', () => {67+ const app = new Hono()68+ app.all('/favicon.ico', serveStatic({ path: './test_bun/favicon.ico' }))69+ app.all('/favicon-notfound.ico', serveStatic({ path: './test_bun/favicon-notfound.ico' }))70+ app.use('/favicon-notfound.ico', async (c, next) => {71+ await next()72+ c.header('X-Custom', 'Bun')73+ })74+75+ it('Should return static file correctly', async () => {76+ const res = await app.request(new Request('http://localhost/favicon.ico'))77+ await res.arrayBuffer()78+ expect(res.status).toBe(200)79+ expect(res.headers.get('Content-Type')).toBe('image/x-icon')80+ })81+82+ it('Should return 404 response', async () => {83+ const res = await app.request(new Request('http://localhost/favicon-notfound.ico'))84+ expect(res.status).toBe(404)85+ expect(res.headers.get('X-Custom')).toBe('Bun')86+ })87+})88+89+// Bun support WebCrypto since v0.2.290+// So, JWT middleware works well.91+describe('JWT Auth Middleware', () => {92+ const app = new Hono()93+ app.use('/jwt/*', jwt({ secret: 'a-secret' }))94+ app.get('/jwt/a', (c) => c.text('auth'))95+96+ it('Should not authorize, return 401 Response', async () => {97+ const req = new Request('http://localhost/jwt/a')98+ const res = await app.request(req)99+ expect(res.status).toBe(401)100+ expect(await res.text()).toBe('Unauthorized')101+ })102+103+ it('Should authorize, return 200 Response', async () => {104+ const credential =105+ 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'106+ const req = new Request('http://localhost/jwt/a')107+ req.headers.set('Authorization', `Bearer ${credential}`)108+ const res = await app.request(req)109+ expect(res.status).toBe(200)110+ expect(await res.text()).toBe('auth')111+ })112+})113+114+// To enable JSX middleware,115+// set "jsxImportSource": "hono/jsx" in the tsconfig.json116+describe('JSX Middleware', () => {117+ const app = new Hono()118+119+ const Layout = (props: { children?: string }) => {120+ return <html>{props.children}</html>121+ }122+123+ app.get('/', (c) => {124+ return c.html(<h1>Hello</h1>)125+ })126+ app.get('/nest', (c) => {127+ return c.html(128+ <h1>129+ <a href='/top'>Hello</a>130+ </h1>131+ )132+ })133+ app.get('/layout', (c) => {134+ return c.html(135+ <Layout>136+ <p>hello</p>137+ </Layout>138+ )139+ })140+141+ it('Should return rendered HTML', async () => {142+ const res = await app.request(new Request('http://localhost/'))143+ expect(res.status).toBe(200)144+ expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')145+ expect(await res.text()).toBe('<h1>Hello</h1>')146+ })147+148+ it('Should return rendered HTML with nest', async () => {149+ const res = await app.request(new Request('http://localhost/nest'))150+ expect(res.status).toBe(200)151+ expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')152+ expect(await res.text()).toBe('<h1><a href="/top">Hello</a></h1>')153+ })154+155+ it('Should return rendered HTML with Layout', async () => {156+ const res = await app.request(new Request('http://localhost/layout'))157+ expect(res.status).toBe(200)158+ expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')159+ expect(await res.text()).toBe('<html><p>hello</p></html>')160+ })161+})added:test_deno/.vscode/settings.json+12 added
1+{2+ "eslint.validate": [3+ "javascript",4+ "javascriptreact",5+ "typescript",6+ "typescriptreact"7+ ],8+ "editor.codeActionsOnSave": {9+ "source.fixAll.eslint": true10+ },11+ "deno.enable": true12+}added:test_deno/deps.ts+1 added
1+export { assert, assertEquals, assertMatch } from 'https://deno.land/std@0.147.0/testing/asserts.ts'added:test_deno/favicon.icobinary
A binary file, added.
added:test_deno/hono.test.ts+25 added
1+import { Context } from '../deno_dist/context.ts'2+import { Hono } from '../deno_dist/mod.ts'3+import { assertEquals } from './deps.ts'4+5+// Test just only minimal patterns.6+// Because others are tested well in Cloudflare Workers environment already.7+8+Deno.test('Hello World', async () => {9+ const app = new Hono()10+ app.get('/:foo', (c) => {11+ c.header('x-param', c.req.param('foo'))12+ c.header('x-query', c.req.query('q') || '')13+ return c.text('Hello Deno!')14+ })15+ const res = await app.request('http://localhost/foo?q=bar')16+ assertEquals(res.status, 200)17+ assertEquals(await res.text(), 'Hello Deno!')18+ assertEquals(res.headers.get('x-param'), 'foo')19+ assertEquals(res.headers.get('x-query'), 'bar')20+})21+22+Deno.test('runtime', async () => {23+ const c = new Context(new Request('http://localhost/'))24+ assertEquals(c.runtime, 'deno')25+})added:test_deno/middleware.test.tsx+102 added
1+/** @jsx jsx */2+/** @jsxFrag Fragment */3+import { basicAuth, jsx, Fragment, serveStatic, jwt } from '../deno_dist/middleware.ts'4+import { Hono } from '../deno_dist/mod.ts'5+import { assertEquals, assertMatch } from './deps.ts'6+7+// Test just only minimal patterns.8+// Because others are already tested well in Cloudflare Workers environment.9+10+Deno.test('Basic Auth Middleware', async () => {11+ const app = new Hono()12+13+ const username = 'hono-user-a'14+ const password = 'hono-password-a'15+16+ app.use(17+ '/auth/*',18+ basicAuth({19+ username,20+ password,21+ })22+ )23+24+ app.get('/auth/*', () => new Response('auth'))25+26+ const res = await app.request('http://localhost/auth/a')27+ assertEquals(res.status, 401)28+ assertEquals(await res.text(), 'Unauthorized')29+30+ const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'31+32+ const req = new Request('http://localhost/auth/a')33+ req.headers.set('Authorization', `Basic ${credential}`)34+ const resOK = await app.request(req)35+ assertEquals(resOK.status, 200)36+ assertEquals(await resOK.text(), 'auth')37+})38+39+Deno.test('JSX middleware', async () => {40+ const app = new Hono()41+ app.get('/', (c) => {42+ return c.html(<h1>Hello</h1>)43+ })44+ const res = await app.request('http://localhost/')45+ assertEquals(res.status, 200)46+ assertEquals(res.headers.get('Content-Type'), 'text/html; charset=UTF-8')47+ assertEquals(await res.text(), '<h1>Hello</h1>')48+49+ // Fragment50+ const template = (51+ <>52+ <p>1</p>53+ <p>2</p>54+ </>55+ )56+ assertEquals(template.toString(), '<p>1</p><p>2</p>')57+})58+59+Deno.test('Serve Static middleware', async () => {60+ const app = new Hono()61+ app.all('/favicon.ico', serveStatic({ path: './test_deno/favicon.ico' }))62+ app.all('/favicon-notfound.ico', serveStatic({ path: './test_deno/favicon-notfound.ico' }))63+ app.use('/favicon-notfound.ico', async (c, next) => {64+ await next()65+ c.header('X-Custom', 'Deno')66+ })67+ let res = await app.request('http://localhost/favicon.ico')68+ assertEquals(res.status, 200)69+ assertEquals(res.headers.get('Content-Type'), 'image/x-icon')70+ res = await app.request('http://localhost/favicon-notfound.ico')71+ assertEquals(res.status, 404)72+ assertMatch(res.headers.get('Content-Type') || '', /^text\/plain/)73+ assertEquals(res.headers.get('X-Custom'), 'Deno')74+})75+76+Deno.test('JWT Authentication middleware', async () => {77+ const app = new Hono<{ Variables: { 'x-foo': string } }>()78+ app.use('/*', async (c, next) => {79+ await next()80+ c.header('x-foo', c.get('x-foo') || '')81+ })82+ app.use('/auth/*', jwt({ secret: 'a-secret' }))83+ app.get('/auth/*', (c) => {84+ c.set('x-foo', 'bar')85+ return new Response('auth')86+ })87+88+ const req = new Request('http://localhost/auth/a')89+ const res = await app.request(req)90+ assertEquals(res.status, 401)91+ assertEquals(await res.text(), 'Unauthorized')92+ assertEquals(res.headers.get('x-foo'), '')93+94+ const credential =95+ 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'96+ const reqOK = new Request('http://localhost/auth/a')97+ reqOK.headers.set('Authorization', `Bearer ${credential}`)98+ const resOK = await app.request(reqOK)99+ assertEquals(resOK.status, 200)100+ assertEquals(await resOK.text(), 'auth')101+ assertEquals(resOK.headers.get('x-foo'), 'bar')102+})added:test_fastly/index.test.ts+92 added
1+import { SHA256 } from 'crypto-js'2+import { Hono } from '../src/index'3+import { basicAuth } from '../src/middleware/basic-auth'4+import { jwt } from '../src/middleware/jwt'5+6+const app = new Hono()7+8+describe('Hello World', () => {9+ app.get('/', (c) => c.text('Hello! Compute!'))10+ app.get('/runtime-name', (c) => {11+ return c.text(c.runtime)12+ })13+14+ it('Should return 200', async () => {15+ const res = await app.request('http://localhost/')16+ expect(res.status).toBe(200)17+ expect(await res.text()).toBe('Hello! Compute!')18+ })19+20+ it('Should return the correct runtime name', async () => {21+ const res = await app.request('http://localhost/runtime-name')22+ expect(res.status).toBe(200)23+ expect(await res.text()).toBe('fastly')24+ })25+})26+27+describe('Basic Auth Middleware without `hashFunction`', () => {28+ const app = new Hono()29+30+ const username = 'hono-user-a'31+ const password = 'hono-password-a'32+ app.use(33+ '/auth/*',34+ basicAuth({35+ username,36+ password,37+ })38+ )39+40+ app.get('/auth/*', () => new Response('auth'))41+42+ it('Should authorize, return 401 Response', async () => {43+ const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'44+ const req = new Request('http://localhost/auth/a')45+ req.headers.set('Authorization', `Basic ${credential}`)46+ const res = await app.request(req)47+ expect(res.status).toBe(401)48+ })49+})50+51+describe('Basic Auth Middleware with `hashFunction`', () => {52+ const app = new Hono()53+54+ const username = 'hono-user-a'55+ const password = 'hono-password-a'56+ app.use(57+ '/auth/*',58+ basicAuth({59+ username,60+ password,61+ hashFunction: (m: string) => SHA256(m).toString(),62+ })63+ )64+65+ app.get('/auth/*', () => new Response('auth'))66+67+ it('Should not authorize, return 401 Response', async () => {68+ const req = new Request('http://localhost/auth/a')69+ const res = await app.request(req)70+ expect(res.status).toBe(401)71+ expect(await res.text()).toBe('Unauthorized')72+ })73+74+ it('Should authorize, return 200 Response', async () => {75+ const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'76+ const req = new Request('http://localhost/auth/a')77+ req.headers.set('Authorization', `Basic ${credential}`)78+ const res = await app.request(req)79+ expect(res.status).toBe(200)80+ expect(await res.text()).toBe('auth')81+ })82+})83+84+describe('JWT Auth Middleware does not work', () => {85+ const app = new Hono()86+87+ it('Should throw error', () => {88+ expect(() => {89+ app.use('/jwt/*', jwt({ secret: 'secret' }))90+ }).toThrow(/`crypto.subtle.importKey` is undefined/)91+ })92+})added:test_lagon/index.test.ts+200 added
1+describe('Example', () => {2+ test('GET /', async () => {3+ const res = await fetch('http://127.0.0.1:1234')4+ expect(res.status).toBe(200)5+ expect(await res.text()).toBe('Hono!!')6+ expect(res.headers.get('x-powered-by')).toBe('Hono')7+ expect(res.headers.get('x-response-time')).toContain('ms')8+ })9+10+ test('GET /hello/anything', async () => {11+ const res = await fetch('http://127.0.0.1:1234/hello/anything')12+ expect(res.status).toBe(404)13+ expect(res.headers.get('x-message')).toBe('This is addHeader middleware!')14+ })15+16+ test('GET /hello', async () => {17+ const res = await fetch('http://127.0.0.1:1234/hello')18+ expect(res.status).toBe(200)19+ expect(await res.text()).toBe('This is /hello')20+ })21+22+ test('GET /runtime', async () => {23+ const res = await fetch('http://127.0.0.1:1234/runtime')24+ expect(res.status).toBe(200)25+ expect(await res.text()).toBe('lagon')26+ })27+28+ test('GET /entry/:id', async () => {29+ const res = await fetch('http://127.0.0.1:1234/entry/42')30+ expect(res.status).toBe(200)31+ expect(await res.text()).toBe('Your ID is 42')32+ })33+34+ describe('/book', () => {35+ test('GET /book', async () => {36+ const res = await fetch('http://127.0.0.1:1234/book')37+ expect(res.status).toBe(200)38+ expect(await res.text()).toBe('List Books')39+ })40+41+ test('GET /book/:id', async () => {42+ const res = await fetch('http://127.0.0.1:1234/book/3')43+ expect(res.status).toBe(200)44+ expect(await res.text()).toBe('Get Book: 3')45+ })46+47+ test('POST /book', async () => {48+ const res = await fetch('http://127.0.0.1:1234/book', {49+ method: 'POST',50+ })51+ expect(res.status).toBe(200)52+ expect(await res.text()).toBe('Create Book')53+ })54+ })55+56+ test('GET /redirect', async () => {57+ const res = await fetch('http://127.0.0.1:1234/redirect', {58+ redirect: 'manual',59+ })60+ expect(res.status).toBe(302)61+ expect(res.headers.get('location')).toBe('/')62+ })63+64+ describe('/basic-auth', () => {65+ test('GET /basic-auth/anyroute unauthorized', async () => {66+ const res = await fetch('http://127.0.0.1:1234/basic-auth/anyroute')67+ expect(res.status).toBe(401)68+ expect(await res.text()).toBe('Unauthorized')69+ })70+71+ test('GET /basic-auth/anyroute', async () => {72+ const res = await fetch('http://127.0.0.1:1234/basic-auth/anyroute', {73+ headers: {74+ authorization: `Basic ${btoa('hono:acoolproject')}`,75+ },76+ })77+ expect(res.status).toBe(200)78+ expect(await res.text()).toBe('You are authorized')79+ })80+ })81+82+ describe('/bearer-auth', () => {83+ test('GET /bearer-auth/anyroute unauthorized', async () => {84+ const res = await fetch('http://127.0.0.1:1234/bearer-auth/anyroute')85+ expect(res.status).toBe(401)86+ expect(await res.text()).toBe('Unauthorized')87+ })88+89+ test('GET /bearer-auth/anyroute', async () => {90+ const res = await fetch('http://127.0.0.1:1234/bearer-auth/anyroute', {91+ headers: {92+ authorization: 'Bearer secrettoken',93+ },94+ })95+ expect(res.status).toBe(200)96+ expect(await res.text()).toBe('You are authorized')97+ })98+ })99+100+ test('GET /etag/cached', async () => {101+ const res = await fetch('http://127.0.0.1:1234/etag/cached')102+ expect(res.status).toBe(200)103+ expect(res.headers.get('etag')).toBe('"90ea638841fff3c326fc22cbd156f1146ac0ac02"')104+ expect(await res.text()).toBe('Is this cached?')105+ })106+107+ test('GET /fetch-url', async () => {108+ const res = await fetch('http://127.0.0.1:1234/fetch-url')109+ expect(res.status).toBe(200)110+ expect(await res.text()).toBe('https://example.com/ is 200')111+ })112+113+ test('GET /user-agent', async () => {114+ const res = await fetch('http://127.0.0.1:1234/user-agent', {115+ headers: {116+ 'user-agent': 'Lagon',117+ },118+ })119+ expect(res.status).toBe(200)120+ expect(await res.text()).toBe('Your UserAgent is Lagon')121+ })122+123+ test('GET /api/posts', async () => {124+ const res = await fetch('http://127.0.0.1:1234/api/posts')125+ expect(res.status).toBe(200)126+ expect(await res.json()).toEqual([127+ { id: 1, title: 'Good Morning' },128+ { id: 2, title: 'Good Aternoon' },129+ { id: 3, title: 'Good Evening' },130+ { id: 4, title: 'Good Night' },131+ ])132+ })133+134+ test('POST /api/posts', async () => {135+ const res = await fetch('http://127.0.0.1:1234/api/posts', {136+ method: 'POST',137+ })138+ expect(res.status).toBe(201)139+ expect(await res.json()).toEqual({ message: 'Created!' })140+ })141+142+ test('GET /api/default-route', async () => {143+ const res = await fetch('http://127.0.0.1:1234/api/default-route')144+ expect(res.status).toBe(404)145+ expect(await res.text()).toBe('API endpoint is not found')146+ })147+148+ describe('/form', () => {149+ test('POST /form x-www-form-urlencoded', async () => {150+ const res = await fetch('http://127.0.0.1:1234/form', {151+ method: 'POST',152+ headers: {153+ 'content-type': 'application/x-www-form-urlencoded',154+ },155+ body: 'username=john&password=Pa%24%24w0rd',156+ })157+ expect(res.status).toBe(200)158+ expect(await res.json()).toEqual({159+ password: 'Pa$$w0rd',160+ username: 'john',161+ })162+ })163+164+ test('POST /form', async () => {165+ const res = await fetch('http://127.0.0.1:1234/form', {166+ method: 'POST',167+ headers: {168+ 'content-type':169+ 'multipart/form-data; boundary=---------------------------9051914041544843365972754266',170+ },171+ body: `-----------------------------9051914041544843365972754266172+Content-Disposition: form-data; name="hello"173+174+world!175+-----------------------------9051914041544843365972754266176+Content-Disposition: form-data; name="description"177+178+this is another field179+-----------------------------9051914041544843365972754266--`,180+ })181+ expect(res.status).toBe(200)182+ expect(await res.json()).toEqual({183+ description: 'this is another field',184+ hello: 'world!',185+ })186+ })187+ })188+189+ test('GET /error', async () => {190+ const res = await fetch('http://127.0.0.1:1234/error')191+ expect(res.status).toBe(500)192+ expect(await res.text()).toBe('Custom Error Message')193+ })194+195+ test('GET /api/default-route', async () => {196+ const res = await fetch('http://127.0.0.1:1234/api/default-route')197+ expect(res.status).toBe(404)198+ expect(await res.text()).toBe('API endpoint is not found')199+ })200+})added:test_lagon/index.ts+128 added
1+import { Hono } from '../src'2+import { HTTPException } from '../src/http-exception'3+import { basicAuth } from '../src/middleware/basic-auth'4+import { bearerAuth } from '../src/middleware/bearer-auth'5+import { etag } from '../src/middleware/etag'6+import { poweredBy } from '../src/middleware/powered-by'7+import { prettyJSON } from '../src/middleware/pretty-json'8+9+const app = new Hono()10+11+// Mount Builtin Middleware12+app.use('*', poweredBy())13+// app.use('*', logger())14+app.use(15+ '/basic-auth/*',16+ basicAuth({17+ username: 'hono',18+ password: 'acoolproject',19+ })20+)21+app.use(22+ '/bearer-auth/*',23+ bearerAuth({24+ token: 'secrettoken',25+ })26+)27+app.use('/etag/*', etag())28+29+// Custom Middleware30+// Add Custom Header31+app.use('/hello/*', async (c, next) => {32+ await next()33+ c.header('X-message', 'This is addHeader middleware!')34+})35+36+// Add X-Response-Time header37+app.use('*', async (c, next) => {38+ const start = Date.now()39+ await next()40+ const ms = Date.now() - start41+ c.header('X-Response-Time', `${ms}ms`)42+})43+44+// Custom Not Found Message45+app.notFound((c) => {46+ return c.text('Custom 404 Not Found', 404)47+})48+49+// Error handling50+app.onError((err, c) => {51+ if (err instanceof HTTPException) {52+ return err.getResponse()53+ }54+ console.error(`${err}`)55+ return c.text('Custom Error Message', 500)56+})57+58+app.head('/', (c) => c.text('OK'))59+60+// Routing61+app.get('/', (c) => c.text('Hono!!'))62+// Use Response object directly63+app.get('/hello', () => new Response('This is /hello'))64+65+app.get('/runtime', (c) => new Response(c.runtime))66+67+// Named parameter68+app.get('/entry/:id', (c) => {69+ const id = c.req.param('id')70+ return c.text(`Your ID is ${id}`)71+})72+73+// Nested route74+const book = new Hono()75+book.get('/', (c) => c.text('List Books'))76+book.get('/:id', (c) => {77+ const id = c.req.param('id')78+ return c.text('Get Book: ' + id)79+})80+book.post('/', (c) => c.text('Create Book'))81+app.route('/book', book)82+83+// Redirect84+app.get('/redirect', (c) => c.redirect('/'))85+// Authentication required86+app.get('/basic-auth/*', (c) => c.text('You are authorized'))87+app.get('/bearer-auth/*', (c) => c.text('You are authorized'))88+// ETag89+app.get('/etag/cached', (c) => c.text('Is this cached?'))90+91+// Async92+app.get('/fetch-url', async (c) => {93+ const response = await fetch('https://example.com/')94+ return c.text(`https://example.com/ is ${response.status}`)95+})96+97+// Request headers98+app.get('/user-agent', (c) => {99+ const userAgent = c.req.header('User-Agent')100+ return c.text(`Your UserAgent is ${userAgent}`)101+})102+103+// JSON104+app.get('/api/posts', prettyJSON(), (c) => {105+ const posts = [106+ { id: 1, title: 'Good Morning' },107+ { id: 2, title: 'Good Aternoon' },108+ { id: 3, title: 'Good Evening' },109+ { id: 4, title: 'Good Night' },110+ ]111+ return c.json(posts)112+})113+// status code114+app.post('/api/posts', (c) => c.json({ message: 'Created!' }, 201))115+// default route116+app.get('/api/*', (c) => c.text('API endpoint is not found', 404))117+118+app.post('/form', async (c) => {119+ const body = await c.req.parseBody()120+ return c.json(body)121+})122+123+// Throw Error124+app.get('/error', () => {125+ throw Error('Error has occurred')126+})127+128+export const handler = app.fetchadded:test_node/index.test.ts+87 added
1+import { createAdaptorServer } from '@hono/node-server'2+import request from 'supertest'3+import { Hono } from '../src'4+import { basicAuth } from '../src/middleware/basic-auth'5+import { jwt } from '../src/middleware/jwt'6+7+// Test only minimal patterns.8+// See <https://github.com/honojs/node-server> for more tests and information.9+10+describe('Basic', () => {11+ const app = new Hono()12+13+ app.get('/', (c) => {14+ return c.text('Hello! Node.js!')15+ })16+ app.get('/runtime-name', (c) => {17+ return c.text(c.runtime)18+ })19+20+ const server = createAdaptorServer(app)21+22+ it('Should return 200 response', async () => {23+ const res = await request(server).get('/')24+ expect(res.status).toBe(200)25+ expect(res.text).toBe('Hello! Node.js!')26+ })27+28+ it('Should return correct runtime name', async () => {29+ const res = await request(server).get('/runtime-name')30+ expect(res.status).toBe(200)31+ expect(res.text).toBe('node')32+ })33+})34+35+describe('Basic Auth Middleware', () => {36+ const app = new Hono()37+38+ const username = 'hono-user-a'39+ const password = 'hono-password-a'40+ app.use(41+ '/auth/*',42+ basicAuth({43+ username,44+ password,45+ })46+ )47+48+ app.get('/auth/*', () => new Response('auth'))49+50+ const server = createAdaptorServer(app)51+52+ it('Should not authorize, return 401 Response', async () => {53+ const res = await request(server).get('/auth/a')54+ expect(res.status).toBe(401)55+ expect(res.text).toBe('Unauthorized')56+ })57+58+ it('Should authorize, return 200 Response', async () => {59+ const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'60+ const res = await request(server).get('/auth/a').set('Authorization', `Basic ${credential}`)61+ expect(res.status).toBe(200)62+ expect(res.text).toBe('auth')63+ })64+})65+66+describe('JWT Auth Middleware', () => {67+ const app = new Hono()68+69+ app.use('/jwt/*', jwt({ secret: 'a-secret' }))70+ app.get('/jwt/a', (c) => c.text('auth'))71+72+ const server = createAdaptorServer(app)73+74+ it('Should not authorize, return 401 Response', async () => {75+ const res = await request(server).get('/jwt/a')76+ expect(res.status).toBe(401)77+ expect(res.text).toBe('Unauthorized')78+ })79+80+ it('Should authorize, return 200 Response', async () => {81+ const credential =82+ 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'83+ const res = await request(server).get('/jwt/a').set('Authorization', `Bearer ${credential}`)84+ expect(res.status).toBe(200)85+ expect(res.text).toBe('auth')86+ })87+})modified:.eslintrc.cjs+1 added
36 unmodified lines37 'error',38 {39 types: {40 Function: false,41+ '{}': false,42 },43 },44 ],45 'sort-imports': 0,16 unmodified linesdeleted:.npmignore-8 removed
1-examples2-benchmark3-.github4-tsconfig.json5-tsconfig.build.json6-src7-docs8-yarn.lockadded:jest.fastly.config.js+7 added
1+export default {2+ testMatch: ['**/test_fastly/**/*.+(ts|tsx|js)'],3+ transform: {4+ '^.+\\.(ts|tsx)$': 'ts-jest',5+ },6+ preset: 'jest-preset-fastly-js-compute/typescript/esm',7+}added:jest.node.config.js+6 added
1+export default {2+ testMatch: ['**/test_node/**/*.+(ts|tsx|js)'],3+ transform: {4+ '^.+\\.(ts|tsx)$': 'ts-jest',5+ },6+}modified:package.json+79 added-43 removed
1 {2 "name": "hono",3- "version": "2.7.8",4- "description": "Ultrafast web framework for Cloudflare Workers, Deno, and Bun.",3+ "version": "3.0.0-rc.16",4+ "description": "Ultrafast web framework for the Edge",5 "main": "dist/cjs/index.js",6 "type": "module",7 "module": "dist/index.js",8 "types": "dist/types/index.d.ts",1 unmodified line10 "dist"11 ],12 "scripts": {13 "test": "jest",14- "test:deno": "deno test --allow-read deno_test",15- "test:bun": "bun wiptest --jsx-import-source ../src/middleware/jsx/jsx-dev-runtime bun_test/index.test.tsx",16- "test:lagon": "npx start-server-and-test \"lagon dev lagon_test/index.ts\" http://127.0.0.1:1234 \"yarn jest lagon_test/index.test.ts --testMatch '**/*.test.ts'\"",17- "test:all": "yarn test && yarn test:deno && yarn test:bun && yarn test:lagon",14+ "test:deno": "deno test --allow-read test_deno",15+ "test:bun": "bun wiptest --jsx-import-source ../src/middleware/jsx/jsx-dev-runtime test_bun/index.test.tsx",16+ "test:fastly": "jest --config ./jest.fastly.config.js",17+ "test:lagon": "start-server-and-test \"lagon dev test_lagon/index.ts\" http://127.0.0.1:1234 \"yarn jest test_lagon/index.test.ts --testMatch '**/*.test.ts'\"",18+ "test:node": "jest --config ./jest.node.config.js",19+ "test:all": "yarn test && yarn test:deno && yarn test:bun && yarn test:fastly && yarn test:lagon && yarn test:node",20 "lint": "eslint --ext js,ts src .eslintrc.cjs",21 "lint:fix": "eslint --ext js,ts src .eslintrc.cjs --fix",22 "denoify": "rimraf deno_dist && denoify && rimraf 'deno_dist/**/*.test.ts'",23 "copy:package.cjs.json": "cp ./package.cjs.json ./dist/cjs/package.json && cp ./package.cjs.json ./dist/types/package.json ",8 unmodified lines32 "types": "./dist/types/index.d.ts",33 "import": "./dist/index.js",34 "require": "./dist/cjs/index.js"35 },36+ "./http-exception": {37+ "types": "./dist/types/http-exception.d.ts",38+ "import": "./dist/http-exception.js",39+ "require": "./dist/cjs/http-exception.js"40+ },41 "./basic-auth": {42 "types": "./dist/types/middleware/basic-auth/index.d.ts",43 "import": "./dist/middleware/basic-auth/index.js",44 "require": "./dist/cjs/middleware/basic-auth/index.js"62 unmodified lines107 "types": "./dist/types/middleware/pretty-json/index.d.ts",108 "import": "./dist/middleware/pretty-json/index.js",109 "require": "./dist/cjs/middleware/pretty-json/index.js"110 },104- "./serve-static": {105- "types": "./dist/types/middleware/serve-static/index.d.ts",106- "import": "./dist/middleware/serve-static/index.js",107- "require": "./dist/cjs/middleware/serve-static/index.js"108- },109- "./serve-static.bun": {110- "types": "./dist/types/middleware/serve-static/bun.d.ts",111- "import": "./dist/middleware/serve-static/bun.js",112- "require": "./dist/cjs/middleware/serve-static/bun.js"113- },114- "./serve-static.module": {115- "types": "./dist/types/middleware/serve-static/module.d.ts",116- "import": "./dist/middleware/serve-static/module.js"117- },111 "./validator": {119- "types": "./dist/types/middleware/validator/index.d.ts",120- "import": "./dist/middleware/validator/index.js",121- "require": "./dist/cjs/middleware/validator/index.js"112+ "types": "./dist/types/validator/index.d.ts",113+ "import": "./dist/validator/index.js",114+ "require": "./dist/cjs/validator/index.js"115 },116 "./router/reg-exp-router": {117 "types": "./dist/types/router/reg-exp-router/index.d.ts",118 "import": "./dist/router/reg-exp-router/index.js",3 unmodified lines122 "types": "./dist/types/router/smart-router/index.d.ts",123 "import": "./dist/router/smart-router/index.js",124 "require": "./dist/cjs/router/smart-router/index.js"125 },133- "./router/static-router": {134- "types": "./dist/types/router/static-router/index.d.ts",135- "import": "./dist/router/static-router/index.js",136- "require": "./dist/cjs/router/static-router/index.js"137- },126 "./router/trie-router": {127 "types": "./dist/types/router/trie-router/index.d.ts",128 "import": "./dist/router/trie-router/index.js",129 "require": "./dist/cjs/router/trie-router/index.js"6 unmodified lines136 "./utils/*": {137 "types": "./dist/types/utils/*.d.ts",138 "import": "./dist/utils/*.js",139 "require": "./dist/cjs/utils/*.js"140+ },141+ "./client": {142+ "types": "./dist/types/client/index.d.ts",143+ "import": "./dist/client/index.js",144+ "require": "./dist/cjs/client/index.js"145+ },146+ "./cloudflare-workers": {147+ "types": "./dist/types/adapter/cloudflare-workers/index.d.ts",148+ "import": "./dist/adapter/cloudflare-workers/index.js",149+ "require": "./dist/cjs/adapter/cloudflare-workers/index.js"150+ },151+ "./cloudflare-pages": {152+ "types": "./dist/types/adapter/cloudflare-pages/index.d.ts",153+ "import": "./dist/adapter/cloudflare-pages/index.js",154+ "require": "./dist/cjs/adapter/cloudflare-pages/index.js"155+ },156+ "./deno": {157+ "types": "./dist/types/adapter/deno/index.d.ts",158+ "import": "./dist/adapter/deno/index.js",159+ "require": "./dist/cjs/adapter/deno/index.js"160+ },161+ "./bun": {162+ "types": "./dist/types/adapter/bun/index.d.ts",163+ "import": "./dist/adapter/bun/index.js",164+ "require": "./dist/cjs/adapter/bun/index.js"165+ },166+ "./nextjs": {167+ "types": "./dist/types/adapter/nextjs/index.d.ts",168+ "import": "./dist/adapter/nextjs/index.js",169+ "require": "./dist/cjs/adapter/nextjs/index.js"170 }171 },172 "typesVersions": {173 "*": {174+ "http-exception": [175+ "./dist/types/http-exception"176+ ],177 "basic-auth": [178 "./dist/types/middleware/basic-auth"179 ],180 "bearer-auth": [34 unmodified lines215 ],216 "pretty-json": [217 "./dist/types/middleware/pretty-json"218 ],198- "serve-static": [199- "./dist/types/middleware/serve-static/index.d.ts"200- ],201- "serve-static.bun": [202- "./dist/types/middleware/serve-static/bun.d.ts"203- ],204- "serve-static.module": [205- "./dist/types/middleware/serve-static/module.d.ts"206- ],219 "validator": [208- "./dist/types/middleware/validator"220+ "./dist/types/validator/index.d.ts"221 ],222 "router/reg-exp-router": [223 "./dist/types/router/reg-exp-router/router.d.ts"224 ],225 "router/smart-router": [226 "./dist/types/router/smart-router/router.d.ts"227 ],216- "router/static-router": [217- "./dist/types/router/static-router/router.d.ts"218- ],228 "router/trie-router": [229 "./dist/types/router/trie-router/router.d.ts"230 ],231 "utils/jwt": [232 "./dist/types/utils/jwt/index.d.ts"233 ],234 "utils/*": [235 "./dist/types/utils/*"236+ ],237+ "client": [238+ "./dist/types/client/index.d.ts"239+ ],240+ "cloudflare-workers": [241+ "./dist/types/adapter/cloudflare-workers"242+ ],243+ "cloudflare-pages": [244+ "./dist/types/adapter/cloudflare-pages"245+ ],246+ "deno": [247+ "./dist/types/adapter/deno"248+ ],249+ "bun": [250+ "./dist/types/adapter/bun"251+ ],252+ "nextjs": [253+ "./dist/types/adapter/nextjs"254 ]255 }256 },257 "author": "Yusuke Wada <yusuke@kamawada.com> (https://github.com/yusukebe)",4 unmodified lines262 },263 "publishConfig": {264 "registry": "https://registry.npmjs.org"265 },239- "homepage": "https://honojs.dev",266+ "homepage": "https://hono.dev",267 "keywords": [268 "hono",269 "web",270 "app",9 unmodified lines280 "bun"281 ],282 "devDependencies": {283 "@cloudflare/workers-types": "^4.20221111.1",284+ "@hono/node-server": "^0.2.3",285 "@types/crypto-js": "^4.1.1",286 "@types/glob": "^8.0.0",287 "@types/jest": "^29.0.2",288 "@types/node": "^17.0.29",289+ "@types/node-fetch": "^2.6.2",290+ "@types/supertest": "^2.0.12",291 "@typescript-eslint/eslint-plugin": "^5.21.0",292 "@typescript-eslint/parser": "^5.21.0",293 "arg": "^5.0.2",294 "crypto-js": "^4.1.1",9 unmodified lines304 "eslint-plugin-node": "^11.1.0",305 "form-data": "^4.0.0",306 "jest": "^29.0.3",307 "jest-environment-miniflare": "2.7.1",308+ "jest-preset-fastly-js-compute": "^0.6.1",309+ "msw": "^1.0.0",310+ "node-fetch": "2",311 "np": "^7.6.2",312 "prettier": "^2.6.2",313 "publint": "^0.1.8",314 "rimraf": "^3.0.2",315+ "start-server-and-test": "^1.15.2",316+ "supertest": "^6.3.3",317 "ts-jest": "^29.0.1",318 "tsx": "^3.11.0",284- "typescript": "^4.8.3"319+ "typescript": "^4.8.3",320+ "zod": "^3.20.2"321 },322 "engines": {323 "node": ">=16.0.0"324 }1 unmodified linemodified:README.md+23 added-19 removed
1 <div align="center">2- <a href="https://honojs.dev">2+ <a href="https://hono.dev">3 <img src="https://raw.githubusercontent.com/honojs/hono/main/docs/images/hono-title.png" width="500" height="auto" alt="Hono"/>4 </a>5 </div>6 7 <hr />8 9 <p align="center">10-<a href="https://honojs.dev"><b>Documentation :point_right: honojs.dev</b></a><br />11-<i>v2.x has been released!</i> <a href="docs/MIGRATION.md">Migration guide</b>10+<a href="https://hono.dev"><b>Documentation :point_right: hono.dev</b></a><br />11+<i>v3 has been released!</i> <a href="docs/MIGRATION.md">Migration guide</b>12 </p>13 14 <hr />15 16 [](https://github.com/honojs/hono/actions)17 [](https://github.com/honojs/hono/blob/main/LICENSE)18 [](https://www.npmjs.com/package/hono)19 [](https://www.npmjs.com/package/hono)20+[](https://bundlephobia.com/result?p=hono)21+[](https://bundlephobia.com/result?p=hono)22 [](https://www.npmjs.com/package/hono)23 [](https://github.com/honojs/hono/pulse)24 [](https://github.com/honojs/hono/commits/main)25 [](https://doc.deno.land/https/deno.land/x/hono/mod.ts)26 [](https://discord.gg/KMh2eNSdxV)27 26-Hono - _**[炎] means flame🔥 in Japanese**_ - is a small, simple, and ultrafast web framework for Cloudflare Workers, Deno, Bun, and others.28+Hono - _**\[炎\] means flame🔥 in Japanese**_ - is a small, simple, and ultrafast web framework for the Edge.29+It works on Cloudflare Workers, Fastly Compute@Edge, Deno, Bun, Vercel, Lagon, Node.js, and others.30+Fast, but not only fast.31 32 ```ts33 import { Hono } from 'hono'34 const app = new Hono()35 32-app.get('/', (c) => c.text('Hono!!'))36+app.get('/', (c) => c.text('Hono!'))37 38 export default app39 ```40 41 ## Features42 39-- **Ultrafast** - The routers are really smart. Not using linear loops. The fastest one will be selected from three routers.40-- **Zero-dependencies** - Using only Web Standard API. Does not depend on other npm or Deno libraries.41-- **Middleware** - Hono has built-in middleware, custom middleware, and third-party middleware. Batteries included.42-- **TypeScript** - First-class TypeScript support. Now, we've got "Types".43-- **Multi-runtime** - Works on Cloudflare Workers, Fastly Compute@Edge, Deno, Bun, or Node.js. The same code runs on all platforms.43+- **Ultrafast** - The routers are really fast and smart. Not using linear loops. Fast.44+- **Multi-runtime** - Works on Cloudflare Workers, Fastly Compute@Edge, Deno, Bun, Lagon, or Node.js. The same code runs on all platforms.45+- **Batteries Included** - Hono has built-in middleware, custom middleware, and third-party middleware. Batteries included.46+- **Fine DX** - First-class TypeScript support. Now, we've got "Types".47+- **Small** - About 20kB. Zero-dependencies. Using only Web Standard API.48 49 ## Benchmarks50 47-**Hono is fastest**, compared to other routers for Cloudflare Workers.51+**Hono is the fastest**, compared to other routers for Cloudflare Workers.52 49-```plain50-Hono x 616,464 ops/sec ±4.76% (83 runs sampled)51-itty-router x 203,074 ops/sec ±3.66% (88 runs sampled)52-sunder x 314,306 ops/sec ±2.28% (87 runs sampled)53-worktop x 194,111 ops/sec ±2.78% (81 runs sampled)53+```54+Hono x 385,807 ops/sec ±5.02% (76 runs sampled)55+itty-router x 205,318 ops/sec ±3.63% (84 runs sampled)56+sunder x 287,198 ops/sec ±4.90% (74 runs sampled)57+worktop x 191,134 ops/sec ±3.06% (85 runs sampled)58 Fastest is Hono55-✨ Done in 30.77s.59+✨ Done in 27.51s.60 ```61 62 ## Documentation63 60-The documentation is available on [honojs.dev](https://honojs.dev).64+The documentation is available on [hono.dev](https://hono.dev).65 66 ## Migration67 64-Migration guide is available on [docs/MIGRATION.md](docs/MIGRATION.md).68+The migration guide is available on [docs/MIGRATION.md](docs/MIGRATION.md).69 70 ## Communication71 72 [Twitter](https://twitter.com/honojs) and [Discord channel](https://discord.gg/KMh2eNSdxV) are available.24 unmodified linesmodified:yarn.lock+830 added-18 removed
537 unmodified lines538 js-yaml "^4.1.0"539 minimatch "^3.0.4"540 strip-json-comments "^3.1.1"541 542+"@hapi/hoek@^9.0.0":543+ version "9.3.0"544+ resolved "https://registry.yarnpkg.com/@hapi/hoek/-/hoek-9.3.0.tgz#8368869dcb735be2e7f5cb7647de78e167a251fb"545+ integrity sha512-/c6rf4UJlmHlC9b5BaNvzAcFv7HZ2QHaV0D4/HNlBdvFnvQq8RI4kYdhyPCl7Xj+oWvTWQ8ujhqS53LIgAe6KQ==546+547+"@hapi/topo@^5.0.0":548+ version "5.1.0"549+ resolved "https://registry.yarnpkg.com/@hapi/topo/-/topo-5.1.0.tgz#dc448e332c6c6e37a4dc02fd84ba8d44b9afb012"550+ integrity sha512-foQZKJig7Ob0BMAYBfcJk8d77QtOe7Wo4ox7ff1lQYoNNAb6jwcY1ncdoy2e9wQZzvNy7ODZCYJkK8kzmcAnAg==551+ dependencies:552+ "@hapi/hoek" "^9.0.0"553+554+"@hono/node-server@^0.2.3":555+ version "0.2.3"556+ resolved "https://registry.yarnpkg.com/@hono/node-server/-/node-server-0.2.3.tgz#d73146da1c0b4bc47f26d03418a4ef6da0ba520c"557+ integrity sha512-cG1xEkj+ZAK3L1tl/JJXRXzYUhijIScKeYZ+qsqQM8MM6kK71zierpEHUMkpYa4nsTzsq84fGnlGiM8+pXM/kg==558+ dependencies:559+ "@remix-run/web-fetch" "^4.3.2"560+ "@remix-run/web-file" "^3.0.2"561+ "@remix-run/web-stream" "^1.0.3"562+563 "@humanwhocodes/config-array@^0.9.2":564 version "0.9.5"565 resolved "https://registry.yarnpkg.com/@humanwhocodes/config-array/-/config-array-0.9.5.tgz#2cbaf9a89460da24b5ca6531b8bbfc23e1df50c7"566 integrity sha512-ObyMyWxZiCu/yTisA7uzx81s40xR2fD5Cg/2Kq7G02ajkNubJf6BopgDTmDyc3U7sXpNKM8cYOw7s7Tyr+DnCw==461 unmodified lines1028 "@miniflare/shared" "2.7.1"1029 undici "5.9.1"1030 ws "^8.2.2"1031 1032+"@mswjs/cookies@^0.2.2":1033+ version "0.2.2"1034+ resolved "https://registry.yarnpkg.com/@mswjs/cookies/-/cookies-0.2.2.tgz#b4e207bf6989e5d5427539c2443380a33ebb922b"1035+ integrity sha512-mlN83YSrcFgk7Dm1Mys40DLssI1KdJji2CMKN8eOlBqsTADYzj2+jWzsANsUTFbxDMWPD5e9bfA1RGqBpS3O1g==1036+ dependencies:1037+ "@types/set-cookie-parser" "^2.4.0"1038+ set-cookie-parser "^2.4.6"1039+1040+"@mswjs/interceptors@^0.17.5":1041+ version "0.17.7"1042+ resolved "https://registry.yarnpkg.com/@mswjs/interceptors/-/interceptors-0.17.7.tgz#3a41c6a56ddf236eddc0afd513026559ae4a1e5c"1043+ integrity sha512-dPInyLEF6ybLxfKGY99euI+mbT6ls4PVO9qPgGIsRk3+2VZVfT7fo9Sq6Q8eKT9W38QtUyhG74hN7xMtKWioGw==1044+ dependencies:1045+ "@open-draft/until" "^1.0.3"1046+ "@types/debug" "^4.1.7"1047+ "@xmldom/xmldom" "^0.8.3"1048+ debug "^4.3.3"1049+ headers-polyfill "^3.1.0"1050+ outvariant "^1.2.1"1051+ strict-event-emitter "^0.2.4"1052+ web-encoding "^1.1.5"1053+1054 "@nodelib/fs.scandir@2.1.5":1055 version "2.1.5"1056 resolved "https://registry.yarnpkg.com/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz#7619c2eb21b25483f6d167548b4cfd5a7488c3d5"1057 integrity sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==114 unmodified lines1172 integrity sha512-kWMohLCIvnwApRmxRFDOqve7puiNNdtVfgwdDOm6QyJNorWOgKv2/AodCcGqx63o28kF7Dr4/nJCatrwwqhULg==1173 dependencies:1174 "@octokit/openapi-types" "^12.5.0"1175 1176+"@open-draft/until@^1.0.3":1177+ version "1.0.3"1178+ resolved "https://registry.yarnpkg.com/@open-draft/until/-/until-1.0.3.tgz#db9cc719191a62e7d9200f6e7bab21c5b848adca"1179+ integrity sha512-Aq58f5HiWdyDlFffbbSjAlv596h/cOnt2DO1w3DOC7OJ5EHs0hd/nycJfiu9RJbT6Yk6F1knnRRXNSpxoIVZ9Q==1180+1181+"@remix-run/web-blob@^3.0.3", "@remix-run/web-blob@^3.0.4":1182+ version "3.0.4"1183+ resolved "https://registry.yarnpkg.com/@remix-run/web-blob/-/web-blob-3.0.4.tgz#99c67b9d0fb641bd0c07d267fd218ae5aa4ae5ed"1184+ integrity sha512-AfegzZvSSDc+LwnXV+SwROTrDtoLiPxeFW+jxgvtDAnkuCX1rrzmVJ6CzqZ1Ai0bVfmJadkG5GxtAfYclpPmgw==1185+ dependencies:1186+ "@remix-run/web-stream" "^1.0.0"1187+ web-encoding "1.1.5"1188+1189+"@remix-run/web-fetch@^4.3.2":1190+ version "4.3.2"1191+ resolved "https://registry.yarnpkg.com/@remix-run/web-fetch/-/web-fetch-4.3.2.tgz#193758bb7a301535540f0e3a86c743283f81cf56"1192+ integrity sha512-aRNaaa0Fhyegv/GkJ/qsxMhXvyWGjPNgCKrStCvAvV1XXphntZI0nQO/Fl02LIQg3cGL8lDiOXOS1gzqDOlG5w==1193+ dependencies:1194+ "@remix-run/web-blob" "^3.0.4"1195+ "@remix-run/web-form-data" "^3.0.3"1196+ "@remix-run/web-stream" "^1.0.3"1197+ "@web3-storage/multipart-parser" "^1.0.0"1198+ abort-controller "^3.0.0"1199+ data-uri-to-buffer "^3.0.1"1200+ mrmime "^1.0.0"1201+1202+"@remix-run/web-file@^3.0.2":1203+ version "3.0.2"1204+ resolved "https://registry.yarnpkg.com/@remix-run/web-file/-/web-file-3.0.2.tgz#1a6cc0900a1310ede4bc96abad77ac6eb27a2131"1205+ integrity sha512-eFC93Onh/rZ5kUNpCQersmBtxedGpaXK2/gsUl49BYSGK/DvuPu3l06vmquEDdcPaEuXcsdGP0L7zrmUqrqo4A==1206+ dependencies:1207+ "@remix-run/web-blob" "^3.0.3"1208+1209+"@remix-run/web-form-data@^3.0.3":1210+ version "3.0.4"1211+ resolved "https://registry.yarnpkg.com/@remix-run/web-form-data/-/web-form-data-3.0.4.tgz#18c5795edaffbc88c320a311766dc04644125bab"1212+ integrity sha512-UMF1jg9Vu9CLOf8iHBdY74Mm3PUvMW8G/XZRJE56SxKaOFWGSWlfxfG+/a3boAgHFLTkP7K4H1PxlRugy1iQtw==1213+ dependencies:1214+ web-encoding "1.1.5"1215+1216+"@remix-run/web-stream@^1.0.0", "@remix-run/web-stream@^1.0.3":1217+ version "1.0.3"1218+ resolved "https://registry.yarnpkg.com/@remix-run/web-stream/-/web-stream-1.0.3.tgz#3284a6a45675d1455c4d9c8f31b89225c9006438"1219+ integrity sha512-wlezlJaA5NF6SsNMiwQnnAW6tnPzQ5I8qk0Y0pSohm0eHKa2FQ1QhEKLVVcDDu02TmkfHgnux0igNfeYhDOXiA==1220+ dependencies:1221+ web-streams-polyfill "^3.1.1"1222+1223 "@samverschueren/stream-to-observable@^0.3.0", "@samverschueren/stream-to-observable@^0.3.1":1224 version "0.3.1"1225 resolved "https://registry.yarnpkg.com/@samverschueren/stream-to-observable/-/stream-to-observable-0.3.1.tgz#a21117b19ee9be70c379ec1877537ef2e1c63301"1226 integrity sha512-c/qwwcHyafOQuVQJj0IlBjf5yYgBI7YPJ77k4fOJYesb41jio65eaJODRUmfYKhTOFBrIZ66kgvGPlNbjuoRdQ==1227 dependencies:1228 any-observable "^0.3.0"1229 1230+"@sideway/address@^4.1.3":1231+ version "4.1.4"1232+ resolved "https://registry.yarnpkg.com/@sideway/address/-/address-4.1.4.tgz#03dccebc6ea47fdc226f7d3d1ad512955d4783f0"1233+ integrity sha512-7vwq+rOHVWjyXxVlR76Agnvhy8I9rpzjosTESvmhNeXOXdZZB15Fl+TI9x1SiHZH5Jv2wTGduSxFDIaq0m3DUw==1234+ dependencies:1235+ "@hapi/hoek" "^9.0.0"1236+1237+"@sideway/formula@^3.0.0":1238+ version "3.0.1"1239+ resolved "https://registry.yarnpkg.com/@sideway/formula/-/formula-3.0.1.tgz#80fcbcbaf7ce031e0ef2dd29b1bfc7c3f583611f"1240+ integrity sha512-/poHZJJVjx3L+zVD6g9KgHfYnb443oi7wLu/XKojDviHy6HOEOA6z1Trk5aR1dGcmPenJEgb2sK2I80LeS3MIg==1241+1242+"@sideway/pinpoint@^2.0.0":1243+ version "2.0.0"1244+ resolved "https://registry.yarnpkg.com/@sideway/pinpoint/-/pinpoint-2.0.0.tgz#cff8ffadc372ad29fd3f78277aeb29e632cc70df"1245+ integrity sha512-RNiOoTPkptFtSVzQevY/yWtZwf/RxyVnPy/OcA9HBM3MlGDnBEYL5B41H0MTn0Uec8Hi+2qUtTfG2WWZBmMejQ==1246+1247 "@sinclair/typebox@^0.23.3":1248 version "0.23.5"1249 resolved "https://registry.yarnpkg.com/@sinclair/typebox/-/typebox-0.23.5.tgz#93f7b9f4e3285a7a9ade7557d9a8d36809cbc47d"1250 integrity sha512-AFBVi/iT4g20DHoujvMH1aEDn8fGJh4xsRGCP6d8RpLPMqsNPvW01Jcn0QysXTsg++/xj25NmJsGyH9xug/wKg==93 unmodified lines1344 version "1.1.1"1345 resolved "https://registry.yarnpkg.com/@types/comment-json/-/comment-json-1.1.1.tgz#b4ae889912a93e64619f97989aecaff8ce889dca"1346 integrity sha512-U70oEqvnkeSSp8BIJwJclERtT13rd9ejK7XkIzMCQQePZe3VW1b7iQggXyW4ZvfGtGeXD0pZw24q5iWNe++HqQ==1347 1348+"@types/cookie@^0.4.1":1349+ version "0.4.1"1350+ resolved "https://registry.yarnpkg.com/@types/cookie/-/cookie-0.4.1.tgz#bfd02c1f2224567676c1545199f87c3a861d878d"1351+ integrity sha512-XW/Aa8APYr6jSVVA1y/DEIZX0/GMKLEVekNG727R8cs56ahETkRAy/3DR7+fJyh7oUgGwNQaRfXCun0+KbWY7Q==1352+1353+"@types/cookiejar@*":1354+ version "2.1.2"1355+ resolved "https://registry.yarnpkg.com/@types/cookiejar/-/cookiejar-2.1.2.tgz#66ad9331f63fe8a3d3d9d8c6e3906dd10f6446e8"1356+ integrity sha512-t73xJJrvdTjXrn4jLS9VSGRbz0nUY3cl2DMGDU48lKl+HR9dbbjW2A9r3g40VA++mQpy6uuHg33gy7du2BKpog==1357+1358 "@types/crypto-js@^4.1.1":1359 version "4.1.1"1360 resolved "https://registry.yarnpkg.com/@types/crypto-js/-/crypto-js-4.1.1.tgz#602859584cecc91894eb23a4892f38cfa927890d"1361 integrity sha512-BG7fQKZ689HIoc5h+6D2Dgq1fABRa0RbBWKBd9SP/MVRVXROflpm5fhwyATX5duFmbStzyzyycPB8qUYKDH3NA==1362 1363+"@types/debug@^4.1.7":1364+ version "4.1.7"1365+ resolved "https://registry.yarnpkg.com/@types/debug/-/debug-4.1.7.tgz#7cc0ea761509124709b8b2d1090d8f6c17aadb82"1366+ integrity sha512-9AonUzyTjXXhEOa0DnqpzZi6VHlqKMswga9EXjpXnnqxwLtdvPPtlO8evrI5D9S6asFRCQ6v+wpiUKbw+vKqyg==1367+ dependencies:1368+ "@types/ms" "*"1369+1370 "@types/glob@^8.0.0":1371 version "8.0.0"1372 resolved "https://registry.yarnpkg.com/@types/glob/-/glob-8.0.0.tgz#321607e9cbaec54f687a0792b2d1d370739455d2"1373 integrity sha512-l6NQsDDyQUVeoTynNpC9uRvCUint/gSUXQA2euwmTuWGvPY5LSDUu6tkCtJB2SvGQlJQzLaKqcGZP4//7EDveA==39 unmodified lines1413 dependencies:1414 expect "^29.0.0"1415 pretty-format "^29.0.0"1416 1417+"@types/js-levenshtein@^1.1.1":1418+ version "1.1.1"1419+ resolved "https://registry.yarnpkg.com/@types/js-levenshtein/-/js-levenshtein-1.1.1.tgz#ba05426a43f9e4e30b631941e0aa17bf0c890ed5"1420+ integrity sha512-qC4bCqYGy1y/NP7dDVr7KJarn+PbX1nSpwA7JXdu0HxT3QYjO8MJ+cntENtHFVy2dRAyBV23OZ6MxsW1AM1L8g==1421+1422 "@types/json-buffer@~3.0.0":1423 version "3.0.0"1424 resolved "https://registry.yarnpkg.com/@types/json-buffer/-/json-buffer-3.0.0.tgz#85c1ff0f0948fc159810d4b5be35bf8c20875f64"1425 integrity sha512-3YP80IxxFJB4b5tYC2SUPwkg0XQLiu0nWvhRgEatgjf+29IcWO9X1k8xRv5DGssJ/lCrjYTjQPcobJr2yWIVuQ==24 unmodified lines1450 version "1.2.2"1451 resolved "https://registry.yarnpkg.com/@types/minimist/-/minimist-1.2.2.tgz#ee771e2ba4b3dc5b372935d549fd9617bf345b8c"1452 integrity sha512-jhuKLIRrhvCPLqwPcx6INqmKeiA5EWrsCOPhrlFSrbrmU4ZMPjj5Ul/oLCMDO98XRUIwVm78xICz4EPCektzeQ==1453 1454+"@types/ms@*":1455+ version "0.7.31"1456+ resolved "https://registry.yarnpkg.com/@types/ms/-/ms-0.7.31.tgz#31b7ca6407128a3d2bbc27fe2d21b345397f6197"1457+ integrity sha512-iiUgKzV9AuaEkZqkOLDIvlQiL6ltuZd9tGcW3gwpnX8JbuiuhFlEGmmFXEXkN50Cvq7Os88IY2v0dkDqXYWVgA==1458+1459+"@types/node-fetch@^2.6.2":1460+ version "2.6.2"1461+ resolved "https://registry.yarnpkg.com/@types/node-fetch/-/node-fetch-2.6.2.tgz#d1a9c5fd049d9415dce61571557104dec3ec81da"1462+ integrity sha512-DHqhlq5jeESLy19TYhLakJ07kNumXWjcDdxXsLUMJZ6ue8VZJj4kLPQVE/2mdHh3xZziNF1xppu5lwmS53HR+A==1463+ dependencies:1464+ "@types/node" "*"1465+ form-data "^3.0.0"1466+1467 "@types/node@*":1468 version "17.0.13"1469 resolved "https://registry.yarnpkg.com/@types/node/-/node-17.0.13.tgz#5ed7ed7c662948335fcad6c412bb42d99ea754e3"1470 integrity sha512-Y86MAxASe25hNzlDbsviXl8jQHb0RDvKt4c40ZJQ1Don0AAL0STLZSs4N+6gLEO55pedy7r2cLwS+ZDxPm/2Bw==24 unmodified lines1495 integrity sha512-85Y2BjiufFzaMIlvJDvTTB8Fxl2xfLo4HgmHzVBz08w4wDePCTjYw66PdrolO0kzli3yam/YCgRufyo1DdQVTA==1496 dependencies:1497 "@types/node" "*"1498 1499+"@types/set-cookie-parser@^2.4.0":1500+ version "2.4.2"1501+ resolved "https://registry.yarnpkg.com/@types/set-cookie-parser/-/set-cookie-parser-2.4.2.tgz#b6a955219b54151bfebd4521170723df5e13caad"1502+ integrity sha512-fBZgytwhYAUkj/jC/FAV4RQ5EerRup1YQsXQCh8rZfiHkc4UahC192oH0smGwsXol3cL3A5oETuAHeQHmhXM4w==1503+ dependencies:1504+ "@types/node" "*"1505+1506 "@types/stack-trace@0.0.29":1507 version "0.0.29"1508 resolved "https://registry.yarnpkg.com/@types/stack-trace/-/stack-trace-0.0.29.tgz#eb7a7c60098edb35630ed900742a5ecb20cfcb4d"1509 integrity sha512-TgfOX+mGY/NyNxJLIbDWrO9DjGoVSW9+aB8H2yy1fy32jsvxijhmyJI9fDFgvz3YP4lvJaq9DzdR/M1bOgVc9g==2 unmodified lines1512 version "2.0.1"1513 resolved "https://registry.yarnpkg.com/@types/stack-utils/-/stack-utils-2.0.1.tgz#20f18294f797f2209b5f65c8e3b5c8e8261d127c"1514 integrity sha512-Hl219/BT5fLAaz6NDkSuhzasy49dwQS/DSdu4MdggFB8zcXv7vflBI3xp7FEmkmdDkBUI2bPUNeMttp2knYdxw==1515 1516+"@types/superagent@*":1517+ version "4.1.16"1518+ resolved "https://registry.yarnpkg.com/@types/superagent/-/superagent-4.1.16.tgz#12c9c16f232f9d89beab91d69368f96ce8e2d881"1519+ integrity sha512-tLfnlJf6A5mB6ddqF159GqcDizfzbMUB1/DeT59/wBNqzRTNNKsaw79A/1TZ84X+f/EwWH8FeuSkjlCLyqS/zQ==1520+ dependencies:1521+ "@types/cookiejar" "*"1522+ "@types/node" "*"1523+1524+"@types/supertest@^2.0.12":1525+ version "2.0.12"1526+ resolved "https://registry.yarnpkg.com/@types/supertest/-/supertest-2.0.12.tgz#ddb4a0568597c9aadff8dbec5b2e8fddbe8692fc"1527+ integrity sha512-X3HPWTwXRerBZS7Mo1k6vMVR1Z6zmJcDVn5O/31whe0tnjE4te6ZJSJGq1RiqHPjzPdMTfjCFogDJmwng9xHaQ==1528+ dependencies:1529+ "@types/superagent" "*"1530+1531 "@types/yargs-parser@*":1532 version "20.2.1"1533 resolved "https://registry.yarnpkg.com/@types/yargs-parser/-/yargs-parser-20.2.1.tgz#3b9ce2489919d9e4fea439b76916abc34b2df129"1534 integrity sha512-7tFImggNeNBVMsn0vLrpn1H1uPrUBdnARPTpZoitY37ZrdJREzf7I16tMrlK3hen349gr1NYh8CmZQa7CTG6Aw==84 unmodified lines1619 dependencies:1620 "@typescript-eslint/types" "5.21.0"1621 eslint-visitor-keys "^3.0.0"1622 1623+"@web3-storage/multipart-parser@^1.0.0":1624+ version "1.0.0"1625+ resolved "https://registry.yarnpkg.com/@web3-storage/multipart-parser/-/multipart-parser-1.0.0.tgz#6b69dc2a32a5b207ba43e556c25cc136a56659c4"1626+ integrity sha512-BEO6al7BYqcnfX15W2cnGR+Q566ACXAT9UQykORCWW80lmkpWsnEob6zJS1ZVBKsSJC8+7vJkHwlp+lXG1UCdw==1627+1628+"@xmldom/xmldom@^0.8.3":1629+ version "0.8.6"1630+ resolved "https://registry.yarnpkg.com/@xmldom/xmldom/-/xmldom-0.8.6.tgz#8a1524eb5bd5e965c1e3735476f0262469f71440"1631+ integrity sha512-uRjjusqpoqfmRkTaNuLJ2VohVr67Q5YwDATW3VU7PfzTj6IRaihGrYI7zckGZjxQPBIp63nfvJbM+Yu5ICh0Bg==1632+1633+"@zxing/text-encoding@0.9.0":1634+ version "0.9.0"1635+ resolved "https://registry.yarnpkg.com/@zxing/text-encoding/-/text-encoding-0.9.0.tgz#fb50ffabc6c7c66a0c96b4c03e3d9be74864b70b"1636+ integrity sha512-U/4aVJ2mxI0aDNI8Uq0wEhMgY+u4CNtEb0om3+y3+niDAsoTCOB33UF0sxpzqzdqXLqmvc+vZyAt4O8pPdfkwA==1637+1638+abort-controller@^3.0.0:1639+ version "3.0.0"1640+ resolved "https://registry.yarnpkg.com/abort-controller/-/abort-controller-3.0.0.tgz#eaf54d53b62bae4138e809ca225c8439a6efb392"1641+ integrity sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==1642+ dependencies:1643+ event-target-shim "^5.0.0"1644+1645 acorn-jsx@^5.3.1:1646 version "5.3.2"1647 resolved "https://registry.yarnpkg.com/acorn-jsx/-/acorn-jsx-5.3.2.tgz#7ed5bb55908b3b2f1bc55c6af1653bada7f07937"1648 integrity sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==101 unmodified lines1750 dependencies:1751 normalize-path "^3.0.0"1752 picomatch "^2.0.4"1753 1754+anymatch@~3.1.2:1755+ version "3.1.3"1756+ resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-3.1.3.tgz#790c58b19ba1720a84205b57c618d5ad8524973e"1757+ integrity sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==1758+ dependencies:1759+ normalize-path "^3.0.0"1760+ picomatch "^2.0.4"1761+1762 arg@^5.0.2:1763 version "5.0.2"1764 resolved "https://registry.yarnpkg.com/arg/-/arg-5.0.2.tgz#c81433cc427c92c4dcf4865142dbca6f15acd59c"1765 integrity sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==39 unmodified lines1805 version "1.0.1"1806 resolved "https://registry.yarnpkg.com/arrify/-/arrify-1.0.1.tgz#898508da2226f380df904728456849c1501a4b0d"1807 integrity sha512-3CYzex9M9FGQjCGMGyi6/31c8GJbgb0qGyrx5HWxPd0aCwh4cB2YjMb2Xf9UuoogrMrlO9cTqnB5rI5GHZTcUA==1808 1809+asap@^2.0.0:1810+ version "2.0.6"1811+ resolved "https://registry.yarnpkg.com/asap/-/asap-2.0.6.tgz#e50347611d7e690943208bbdafebcbc2fb866d46"1812+ integrity sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==1813+1814 async-exit-hook@^2.0.1:1815 version "2.0.1"1816 resolved "https://registry.yarnpkg.com/async-exit-hook/-/async-exit-hook-2.0.1.tgz#8bd8b024b0ec9b1c01cccb9af9db29bd717dfaf3"1817 integrity sha512-NW2cX8m1Q7KPA7a5M2ULQeZ2wR5qI5PAbw5L0UOMxdioVk9PMZ0h1TmyZEkPYrCvYjDlFICusOu1dlEKAAeXBw==2 unmodified lines1820 version "0.4.0"1821 resolved "https://registry.yarnpkg.com/asynckit/-/asynckit-0.4.0.tgz#c79ed97f7f34cb8f2ba1bc9790bcc366474b4b79"1822 integrity sha1-x57Zf380y48robyXkLzDZkdLS3k=1823 1824+available-typed-arrays@^1.0.5:1825+ version "1.0.5"1826+ resolved "https://registry.yarnpkg.com/available-typed-arrays/-/available-typed-arrays-1.0.5.tgz#92f95616501069d07d10edb2fc37d3e1c65123b7"1827+ integrity sha512-DMD0KiN46eipeziST1LPP/STfDU0sufISXmjSgvVsoU2tqxctQeASejWcfNtxYKqETM1UxQ8sp2OrSBWpHY6sw==1828+1829+axios@^0.25.0:1830+ version "0.25.0"1831+ resolved "https://registry.yarnpkg.com/axios/-/axios-0.25.0.tgz#349cfbb31331a9b4453190791760a8d35b093e0a"1832+ integrity sha512-cD8FOb0tRH3uuEe6+evtAbgJtfxr7ly3fQjYcMcuPlgkwVS9xboaVIpcDV+cYQe+yGykgwZCs1pzjntcGa6l5g==1833+ dependencies:1834+ follow-redirects "^1.14.7"1835+1836 babel-jest@^29.0.3:1837 version "29.0.3"1838 resolved "https://registry.yarnpkg.com/babel-jest/-/babel-jest-29.0.3.tgz#64e156a47a77588db6a669a88dedff27ed6e260f"1839 integrity sha512-ApPyHSOhS/sVzwUOQIWJmdvDhBsMG01HX9z7ogtkp1TToHGGUWFlnXJUIzCgKPSfiYLn3ibipCYzsKSURHEwLg==57 unmodified lines1897 version "1.0.2"1898 resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee"1899 integrity sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==1900 1901+base64-js@^1.3.1:1902+ version "1.5.1"1903+ resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.5.1.tgz#1b1b440160a5bf7ad40b650f095963481903930a"1904+ integrity sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==1905+1906 before-after-hook@^2.2.0:1907 version "2.2.2"1908 resolved "https://registry.yarnpkg.com/before-after-hook/-/before-after-hook-2.2.2.tgz#a6e8ca41028d90ee2c24222f201c90956091613e"1909 integrity sha512-3pZEU3NT5BFUo/AD5ERPWOgQOCZITni6iavr5AUw5AUwQjMlI0kzu5btnyD39AF0gUEsDPwJT+oY1ORBJijPjQ==1910 1911+binary-extensions@^2.0.0:1912+ version "2.2.0"1913+ resolved "https://registry.yarnpkg.com/binary-extensions/-/binary-extensions-2.2.0.tgz#75f502eeaf9ffde42fc98829645be4ea76bd9e2d"1914+ integrity sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==1915+1916+bl@^4.1.0:1917+ version "4.1.0"1918+ resolved "https://registry.yarnpkg.com/bl/-/bl-4.1.0.tgz#451535264182bec2fbbc83a62ab98cf11d9f7b3a"1919+ integrity sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==1920+ dependencies:1921+ buffer "^5.5.0"1922+ inherits "^2.0.4"1923+ readable-stream "^3.4.0"1924+1925+bluebird@3.7.2:1926+ version "3.7.2"1927+ resolved "https://registry.yarnpkg.com/bluebird/-/bluebird-3.7.2.tgz#9f229c15be272454ffa973ace0dbee79a1b0c36f"1928+ integrity sha512-XpNj6GDQzdfW+r2Wnn7xiSAd7TM3jzkxGXBGTtWKuSXv1xUV+azxAm8jdWZN06QTQk+2N2XB9jRDkvbmQmcRtg==1929+1930 boxen@^5.0.0:1931 version "5.1.2"1932 resolved "https://registry.yarnpkg.com/boxen/-/boxen-5.1.2.tgz#788cb686fc83c1f486dfa8a40c68fc2b831d2b50"1933 integrity sha512-9gYgQKXx+1nP8mP7CzFyaUARhg7D3n1dF/FnErWmu9l6JvGpNUN278h0aSb+QjoiKSWG+iZ3uHrcqk0qrY9RQQ==21 unmodified lines1955 integrity sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==1956 dependencies:1957 balanced-match "^1.0.0"1958 1724-braces@^3.0.1:1959+braces@^3.0.1, braces@~3.0.2:1960 version "3.0.2"1961 resolved "https://registry.yarnpkg.com/braces/-/braces-3.0.2.tgz#3454e1a462ee8d599e236df336cd9ea4f8afe107"1962 integrity sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==1963 dependencies:38 unmodified lines2002 version "1.1.2"2003 resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.2.tgz#2b146a6fd72e80b4f55d255f35ed59a3a9a41bd5"2004 integrity sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==2005 2006+buffer@^5.5.0:2007+ version "5.7.1"2008+ resolved "https://registry.yarnpkg.com/buffer/-/buffer-5.7.1.tgz#ba62e7c13133053582197160851a8f648e99eed0"2009+ integrity sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ==2010+ dependencies:2011+ base64-js "^1.3.1"2012+ ieee754 "^1.1.13"2013+2014 builtins@^1.0.3:2015 version "1.0.3"2016 resolved "https://registry.yarnpkg.com/builtins/-/builtins-1.0.3.tgz#cb94faeb61c8696451db36534e1422f94f0aee88"2017 integrity sha512-uYBjakWipfaO/bXI7E8rq6kpwHRZK5cNYrUv2OzZSI/FvmdMyXJ2tG9dKcjEC5YHmHpUAwsargWIZNWdxb/bnQ==80 unmodified lines2098 version "1.0.30001399"2099 resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001399.tgz#1bf994ca375d7f33f8d01ce03b7d5139e8587873"2100 integrity sha512-4vQ90tMKS+FkvuVWS5/QY1+d805ODxZiKFzsU8o/RsVJz49ZSRR8EjykLJbqhzdPgadbX6wB538wOzle3JniRA==2101 2102+chalk@4.1.1:2103+ version "4.1.1"2104+ resolved "https://registry.yarnpkg.com/chalk/-/chalk-4.1.1.tgz#c80b3fab28bf6371e6863325eee67e618b77e6ad"2105+ integrity sha512-diHzdDKxcU+bAsUboHLPEDQiw0qEe0qd7SYUn3HgcFlWgbDcfLGswOHYeGrHKzG9z6UYf01d9VFMfZxPM1xZSg==2106+ dependencies:2107+ ansi-styles "^4.1.0"2108+ supports-color "^7.1.0"2109+2110 chalk@^1.0.0, chalk@^1.1.3:2111 version "1.1.3"2112 resolved "https://registry.yarnpkg.com/chalk/-/chalk-1.1.3.tgz#a8115c55e4a702fe4d150abd3872822a7e09fc98"2113 integrity sha512-U3lRVLMSlsCfjqYPbLyVv11M9CPW4I728d6TCKMAOJueEeB9/8o+eSsMnxPJD+Q+K909sdESg7C+tIkoH6on1A==12 unmodified lines2126 ansi-styles "^3.2.1"2127 escape-string-regexp "^1.0.5"2128 supports-color "^5.3.0"2129 1879-chalk@^4.0.0, chalk@^4.1.0:2130+chalk@^4.0.0, chalk@^4.1.0, chalk@^4.1.1:2131 version "4.1.2"2132 resolved "https://registry.yarnpkg.com/chalk/-/chalk-4.1.2.tgz#aac4e2b7734a740867aeb16bf02aad556a1e7a01"2133 integrity sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==2134 dependencies:9 unmodified lines2144 version "0.7.0"2145 resolved "https://registry.yarnpkg.com/chardet/-/chardet-0.7.0.tgz#90094849f0937f2eedc2425d0d28a9e5f0cbad9e"2146 integrity sha512-mT8iDcrh03qDGRRmoA2hmBJnxpllMR+0/0qlzjqZES6NdiWDcZkCNAk4rPFZ9Q85r27unkiNNg8ZOiwZXBHwcA==2147 2148+check-more-types@2.24.0:2149+ version "2.24.0"2150+ resolved "https://registry.yarnpkg.com/check-more-types/-/check-more-types-2.24.0.tgz#1420ffb10fd444dcfc79b43891bbfffd32a84600"2151+ integrity sha512-Pj779qHxV2tuapviy1bSZNEL1maXr13bPYpsvSDB68HlYcYuhlDrmGd63i0JHMCLKzc7rUSNIrpdJlhVlNwrxA==2152+2153+chokidar@^3.4.2:2154+ version "3.5.3"2155+ resolved "https://registry.yarnpkg.com/chokidar/-/chokidar-3.5.3.tgz#1cf37c8707b932bd1af1ae22c0432e2acd1903bd"2156+ integrity sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==2157+ dependencies:2158+ anymatch "~3.1.2"2159+ braces "~3.0.2"2160+ glob-parent "~5.1.2"2161+ is-binary-path "~2.1.0"2162+ is-glob "~4.0.1"2163+ normalize-path "~3.0.0"2164+ readdirp "~3.6.0"2165+ optionalDependencies:2166+ fsevents "~2.3.2"2167+2168 ci-info@^2.0.0:2169 version "2.0.0"2170 resolved "https://registry.yarnpkg.com/ci-info/-/ci-info-2.0.0.tgz#67a9e964be31a51e15e5010d58e6f12834002f46"2171 integrity sha512-5tK7EtrZ0N+OLFMthtqOj4fI2Jeb88C4CAZPu25LDVUgXJ0A3Js4PMGqrn0JU1W0Mh1/Z8wZzYPxqUrXeBboCQ==31 unmodified lines2203 integrity sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==2204 dependencies:2205 restore-cursor "^3.1.0"2206 2207+cli-spinners@^2.5.0:2208+ version "2.7.0"2209+ resolved "https://registry.yarnpkg.com/cli-spinners/-/cli-spinners-2.7.0.tgz#f815fd30b5f9eaac02db604c7a231ed7cb2f797a"2210+ integrity sha512-qu3pN8Y3qHNgE2AFweciB1IfMnmZ/fsNTEE+NOFjmGB2F/7rLhnhzppvpCnN4FovtP26k8lHyy9ptEbNwWFLzw==2211+2212 cli-truncate@^0.2.1:2213 version "0.2.1"2214 resolved "https://registry.yarnpkg.com/cli-truncate/-/cli-truncate-0.2.1.tgz#9f15cfbb0705005369216c626ac7d05ab90dd574"2215 integrity sha512-f4r4yJnbT++qUPI9NR4XLDLq41gQ+uqnPItWG0F5ZkehuNiTTa3EY0S4AqTSUOeJ7/zU41oWPQSNkW5BqPL9bg==26 unmodified lines2242 integrity sha512-yjLXh88P599UOyPTFX0POsd7WxnbsVsGohcwzHOLspIhhpalPw1BcqED8NblyZLKcGrL8dTgMlcaZxV2jAD41Q==2243 dependencies:2244 mimic-response "^1.0.0"2245 2246+clone@^1.0.2:2247+ version "1.0.4"2248+ resolved "https://registry.yarnpkg.com/clone/-/clone-1.0.4.tgz#da309cc263df15994c688ca902179ca3c7cd7c7e"2249+ integrity sha512-JQHZ2QMW6l3aH/j6xCqQThY/9OH4D/9ls34cgkUBiEeocRTU04tHfKPBsUK1PqZCUQM7GiA0IIXJSuXHI64Kbg==2250+2251 co@^4.6.0:2252 version "4.6.0"2253 resolved "https://registry.yarnpkg.com/co/-/co-4.6.0.tgz#6ea6bdf3d853ae54ccb8e47bfa0bf3f9031fb184"2254 integrity sha1-bqa989hTrlTMuOR7+gvz+QMfsYQ=53 unmodified lines2308 esprima "^4.0.1"2309 has-own-prop "^2.0.0"2310 repeat-string "^1.6.1"2311 2312+component-emitter@^1.3.0:2313+ version "1.3.0"2314+ resolved "https://registry.yarnpkg.com/component-emitter/-/component-emitter-1.3.0.tgz#16e4070fba8ae29b679f2215853ee181ab2eabc0"2315+ integrity sha512-Rd3se6QB+sO1TwqZjscQrurpEPIfO0/yYnSin6Q/rD3mOutHvUrCAhJub3r90uNb+SESBuE0QYoB90YdfatsRg==2316+2317 compress-brotli@^1.3.8:2318 version "1.3.8"2319 resolved "https://registry.yarnpkg.com/compress-brotli/-/compress-brotli-1.3.8.tgz#0c0a60c97a989145314ec381e84e26682e7b38db"2320 integrity sha512-lVcQsjhxhIXsuupfy9fmZUFtAIdBmXA7EGY6GBdgZ++qkM9zG4YFT8iU7FoBxzryNDMOpD1HIFHUSX4D87oqhQ==24 unmodified lines2345 integrity sha512-+OQdjP49zViI/6i7nIJpA8rAl4sV/JdPfU9nZs3VqOwGIgizICvuN2ru6fMd+4llL0tar18UYJXfZ/TWtmhUjA==2346 dependencies:2347 safe-buffer "~5.1.1"2348 2063-cookie@^0.4.1:2349+cookie@^0.4.1, cookie@^0.4.2:2350 version "0.4.2"2351 resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.4.2.tgz#0e41f24de5ecf317947c82fc789e06a884824432"2352 integrity sha512-aSWTXFzaKWkvHO1Ny/s+ePFpvKsPnjc551iI41v3ny/ow6tBG5Vd+FuqGNhh1LxOmVzOlGUriIlOaokOvhaStA==2353 2354+cookiejar@^2.1.3:2355+ version "2.1.3"2356+ resolved "https://registry.yarnpkg.com/cookiejar/-/cookiejar-2.1.3.tgz#fc7a6216e408e74414b90230050842dacda75acc"2357+ integrity sha512-JxbCBUdrfr6AQjOXrxoTvAMJO4HBTUIlBzslcJPAz+/KT8yk53fXun51u+RenNYvad/+Vc2DIz5o9UxlCDymFQ==2358+2359 core-util-is@^1.0.2:2360 version "1.0.3"2361 resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.3.tgz#a6042d3634c2b27e9328f837b965fac83808db85"2362 integrity sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==32 unmodified lines2395 version "2.0.0"2396 resolved "https://registry.yarnpkg.com/crypto-random-string/-/crypto-random-string-2.0.0.tgz#ef2a7a966ec11083388369baa02ebead229b30d5"2397 integrity sha512-v1plID3y9r/lPhviJ1wrXpLeyUIGAZ2SHNYTEapm7/8A9nLPoyvVp3RK/EPFqn5kEznyWgYZNsRtYYIWbuG8KA==2398 2399+data-uri-to-buffer@^3.0.1:2400+ version "3.0.1"2401+ resolved "https://registry.yarnpkg.com/data-uri-to-buffer/-/data-uri-to-buffer-3.0.1.tgz#594b8973938c5bc2c33046535785341abc4f3636"2402+ integrity sha512-WboRycPNsVw3B3TL559F7kuBUM4d8CgMEvk6xEJlOp7OBPjt6G7z8WMWlD2rOFZLk6OYfFIUGsCOWzcQH9K2og==2403+2404 date-fns@^1.27.2:2405 version "1.30.1"2406 resolved "https://registry.yarnpkg.com/date-fns/-/date-fns-1.30.1.tgz#2e71bf0b119153dbb4cc4e88d9ea5acfb50dc05c"2407 integrity sha512-hBSVCvSmWC+QypYObzwGOd9wqdDpOt+0wl0KbU+R+uuZBS1jN8VsD1ss3irQDknRj5NvxiTF6oj/nDRnN/UQNw==2408 2409+debug@4.3.4, debug@^4.3.3, debug@^4.3.4:2410+ version "4.3.4"2411+ resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.4.tgz#1319f6579357f2338d3337d2cdd4914bb5dcc865"2412+ integrity sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==2413+ dependencies:2414+ ms "2.1.2"2415+2416 debug@^2.6.9:2417 version "2.6.9"2418 resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f"2419 integrity sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==13 unmodified lines2433 integrity sha512-/zxw5+vh1Tfv+4Qn7a5nsbcJKPaSvCDhojn6FEl9vupwK2VCSDtEiEtqr8DFtzYFOdz63LBkxec7DYuc2jon6Q==2434 dependencies:2435 ms "2.1.2"2436 2134-debug@^4.3.4:2135- version "4.3.4"2136- resolved "https://registry.yarnpkg.com/debug/-/debug-4.3.4.tgz#1319f6579357f2338d3337d2cdd4914bb5dcc865"2137- integrity sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==2138- dependencies:2139- ms "2.1.2"2140-2437 decamelize-keys@^1.1.0:2438 version "1.1.0"2439 resolved "https://registry.yarnpkg.com/decamelize-keys/-/decamelize-keys-1.1.0.tgz#d171a87933252807eb3cb61dc1c1445d078df2d9"2440 integrity sha512-ocLWuYzRPoS9bfiSdDd3cxvrzovVMZnRDVEzAs+hWIVXGDbHxWMECij2OBuyB/An0FFW/nLuq6Kv1i/YC5Qfzg==39 unmodified lines2480 version "4.2.2"2481 resolved "https://registry.yarnpkg.com/deepmerge/-/deepmerge-4.2.2.tgz#44d2ea3679b8f4d4ffba33f03d865fc1e7bf4955"2482 integrity sha512-FJ3UgI4gIl+PHZm53knsuSFpE+nESMr7M4v9QcgB7S63Kj/6WqMiFQJpBBYz1Pt+66bZpP3Q7Lye0Oo9MPKEdg==2483 2484+defaults@^1.0.3:2485+ version "1.0.4"2486+ resolved "https://registry.yarnpkg.com/defaults/-/defaults-1.0.4.tgz#b0b02062c1e2aa62ff5d9528f0f98baa90978d7a"2487+ integrity sha512-eFuaLoy/Rxalv2kr+lqMlUnrDWV+3j4pljOIJgLIhI058IQfWJ7vXhyEIHu+HtC738klGALYxOKDO0bQP3tg8A==2488+ dependencies:2489+ clone "^1.0.2"2490+2491 defer-to-connect@^1.0.1:2492 version "1.1.3"2493 resolved "https://registry.yarnpkg.com/defer-to-connect/-/defer-to-connect-1.1.3.tgz#331ae050c08dcf789f8c83a7b81f0ed94f4ac591"2494 integrity sha512-0ISdNousHvZT2EiFlZeZAHBUvSxmKswVCEf8hW7KWgG4a8MVEu/3Vb6uWYozkjylyCxe0JBIiRB1jV45S70WVQ==58 unmodified lines2553 version "3.1.0"2554 resolved "https://registry.yarnpkg.com/detect-newline/-/detect-newline-3.1.0.tgz#576f5dfc63ae1a192ff192d8ad3af6308991b651"2555 integrity sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA==2556 2557+dezalgo@^1.0.4:2558+ version "1.0.4"2559+ resolved "https://registry.yarnpkg.com/dezalgo/-/dezalgo-1.0.4.tgz#751235260469084c132157dfa857f386d4c33d81"2560+ integrity sha512-rXSP0bf+5n0Qonsb+SVVfNfIsimO4HEtmnIpPHY8Q1UCzKlQrDMfdobr8nJOOsRgWCyMRqeSBQzmWUMq7zvVig==2561+ dependencies:2562+ asap "^2.0.0"2563+ wrappy "1"2564+2565 diff-sequences@^29.0.0:2566 version "29.0.0"2567 resolved "https://registry.yarnpkg.com/diff-sequences/-/diff-sequences-29.0.0.tgz#bae49972ef3933556bcb0800b72e8579d19d9e4f"2568 integrity sha512-7Qe/zd1wxSDL4D/X/FPjOMB+ZMDt71W94KYaq05I2l0oQqgXgs7s4ftYYmV38gBSrPz2vcygxfs1xn0FT+rKNA==42 unmodified lines2611 version "0.1.4"2612 resolved "https://registry.yarnpkg.com/duplexer3/-/duplexer3-0.1.4.tgz#ee01dd1cac0ed3cbc7fdbea37dc0a8f1ce002ce2"2613 integrity sha512-CEj8FwwNA4cVH2uFCoHUrmojhYh1vmCdOaneKJXwkeY1i9jnlslVo9dx+hQ5Hl9GnH/Bwy/IjxAyOePyPKYnzA==2614 2615+duplexer@~0.1.1:2616+ version "0.1.2"2617+ resolved "https://registry.yarnpkg.com/duplexer/-/duplexer-0.1.2.tgz#3abe43aef3835f8ae077d136ddce0f276b0400e6"2618+ integrity sha512-jtD6YG370ZCIi/9GTaJKQxWTZD045+4R4hTk/x1UyoqadyJ9x9CgSi1RlVDQF8U2sxLLSnFkCaMihqljHIWgMg==2619+2620 electron-to-chromium@^1.4.17:2621 version "1.4.57"2622 resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.4.57.tgz#2b2766df76ac8dbc0a1d41249bc5684a31849892"2623 integrity sha512-FNC+P5K1n6pF+M0zIK+gFCoXcJhhzDViL3DRIGy2Fv5PohuSES1JHR7T+GlwxSxlzx4yYbsuzCZvHxcBSRCIOw==450 unmodified lines3074 version "2.0.3"3075 resolved "https://registry.yarnpkg.com/esutils/-/esutils-2.0.3.tgz#74d2eb4de0b8da1293711910d50775b9b710ef64"3076 integrity sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==3077 3078+event-stream@=3.3.4:3079+ version "3.3.4"3080+ resolved "https://registry.yarnpkg.com/event-stream/-/event-stream-3.3.4.tgz#4ab4c9a0f5a54db9338b4c34d86bfce8f4b35571"3081+ integrity sha512-QHpkERcGsR0T7Qm3HNJSyXKEEj8AHNxkY3PK8TS2KJvQ7NiSHe3DDpwVKKtoYprL/AreyzFBeIkBIWChAqn60g==3082+ dependencies:3083+ duplexer "~0.1.1"3084+ from "~0"3085+ map-stream "~0.1.0"3086+ pause-stream "0.0.11"3087+ split "0.3"3088+ stream-combiner "~0.0.4"3089+ through "~2.3.1"3090+3091+event-target-shim@^5.0.0:3092+ version "5.0.1"3093+ resolved "https://registry.yarnpkg.com/event-target-shim/-/event-target-shim-5.0.1.tgz#5d4d3ebdf9583d63a5333ce2deb7480ab2b05789"3094+ integrity sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==3095+3096+events@^3.3.0:3097+ version "3.3.0"3098+ resolved "https://registry.yarnpkg.com/events/-/events-3.3.0.tgz#31a95ad0a924e2d2c419a813aeb2c4e878ea7400"3099+ integrity sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==3100+3101 evt@^2.4.2:3102 version "2.4.2"3103 resolved "https://registry.yarnpkg.com/evt/-/evt-2.4.2.tgz#8f29f53a71609f1f5ad09ba313ad8cc0b9c63077"3104 integrity sha512-wPGX4eGgxh5NRff+1VkRfdTRaJA5vbr9rC9CRUIgprVDGDFtI0/vF9I0Yp3HAEGuFbUO978QAsaH6lIgpRCFAg==1 unmodified line3106 minimal-polyfills "^2.2.2"3107 run-exclusive "^2.2.16"3108 tsafe "^1.0.1"3109 2771-execa@^5.0.0:3110+execa@5.1.1, execa@^5.0.0:3111 version "5.1.1"3112 resolved "https://registry.yarnpkg.com/execa/-/execa-5.1.1.tgz#f80ad9cbf4298f7bd1d4c9555c21e93741c411dd"3113 integrity sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==3114 dependencies:57 unmodified lines3172 version "2.0.6"3173 resolved "https://registry.yarnpkg.com/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz#3d8a5c66883a16a30ca8643e851f19baa7797917"3174 integrity sha1-PYpcZog6FqMMqGQ+hR8Zuqd5eRc=3175 3176+fast-safe-stringify@^2.1.1:3177+ version "2.1.1"3178+ resolved "https://registry.yarnpkg.com/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz#c406a83b6e70d9e35ce3b30a81141df30aeba884"3179+ integrity sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==3180+3181 fastq@^1.6.0:3182 version "1.13.0"3183 resolved "https://registry.yarnpkg.com/fastq/-/fastq-1.13.0.tgz#616760f88a7526bdfc596b7cab8c18938c36b98c"3184 integrity sha512-YpkpUnK8od0o1hmeSc7UUs/eB/vIPWJYjKck2QKIzAf71Vm1AAQ3EbuZB3g2JIy+pg+ERD0vqI79KyZiB2e2Nw==78 unmodified lines3263 version "3.2.5"3264 resolved "https://registry.yarnpkg.com/flatted/-/flatted-3.2.5.tgz#76c8584f4fc843db64702a6bd04ab7a8bd666da3"3265 integrity sha512-WIWGi2L3DyTUvUrwRKgGi9TwxQMUEqPOPQBVi71R96jZXJdFskXEmf54BoZaS1kknGODoIGASGEzBUYdyMCBJg==3266 3267+follow-redirects@^1.14.7:3268+ version "1.15.2"3269+ resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.15.2.tgz#b460864144ba63f2681096f274c4e57026da2c13"3270+ integrity sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA==3271+3272+for-each@^0.3.3:3273+ version "0.3.3"3274+ resolved "https://registry.yarnpkg.com/for-each/-/for-each-0.3.3.tgz#69b447e88a0a5d32c3e7084f3f1710034b21376e"3275+ integrity sha512-jqYfLp7mo9vIyQf8ykW2v7A+2N4QjeCeI5+Dz9XraiO1ign81wjiH7Fb9vSOWvQfNtmSa4H2RoQTrrXivdUZmw==3276+ dependencies:3277+ is-callable "^1.1.3"3278+3279+form-data@^3.0.0:3280+ version "3.0.1"3281+ resolved "https://registry.yarnpkg.com/form-data/-/form-data-3.0.1.tgz#ebd53791b78356a99af9a300d4282c4d5eb9755f"3282+ integrity sha512-RHkBKtLWUVwd7SqRIvCZMEvAMoGUp0XU+seQiZejj0COz3RI3hWP4sCv3gZWWLjJTd7rGwcsF5eKZGii0r/hbg==3283+ dependencies:3284+ asynckit "^0.4.0"3285+ combined-stream "^1.0.8"3286+ mime-types "^2.1.12"3287+3288 form-data@^4.0.0:3289 version "4.0.0"3290 resolved "https://registry.yarnpkg.com/form-data/-/form-data-4.0.0.tgz#93919daeaf361ee529584b9b31664dc12c9fa452"3291 integrity sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==1 unmodified line3293 asynckit "^0.4.0"3294 combined-stream "^1.0.8"3295 mime-types "^2.1.12"3296 3297+formidable@^2.1.1:3298+ version "2.1.1"3299+ resolved "https://registry.yarnpkg.com/formidable/-/formidable-2.1.1.tgz#81269cbea1a613240049f5f61a9d97731517414f"3300+ integrity sha512-0EcS9wCFEzLvfiks7omJ+SiYJAiD+TzK4Pcw1UlUoGnhUxDcMKjt0P7x8wEb0u6OHu8Nb98WG3nxtlF5C7bvUQ==3301+ dependencies:3302+ dezalgo "^1.0.4"3303+ hexoid "^1.0.0"3304+ once "^1.4.0"3305+ qs "^6.11.0"3306+3307+from@~0:3308+ version "0.1.7"3309+ resolved "https://registry.yarnpkg.com/from/-/from-0.1.7.tgz#83c60afc58b9c56997007ed1a768b3ab303a44fe"3310+ integrity sha512-twe20eF1OxVxp/ML/kq2p1uc6KvFK/+vs8WjEbeKmV2He22MKm7YF2ANIt+EOqhJ5L3K/SuuPhk0hWQDjOM23g==3311+3312 fs.realpath@^1.0.0:3313 version "1.0.0"3314 resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f"3315 integrity sha1-FQStJSMVjKpA20onh8sBQRmU6k8=39 unmodified lines3355 function-bind "^1.1.1"3356 has "^1.0.3"3357 has-symbols "^1.0.1"3358 3359+get-intrinsic@^1.1.3:3360+ version "1.1.3"3361+ resolved "https://registry.yarnpkg.com/get-intrinsic/-/get-intrinsic-1.1.3.tgz#063c84329ad93e83893c7f4f243ef63ffa351385"3362+ integrity sha512-QJVz1Tj7MS099PevUG5jvnt9tSkXN8K14dxQlikJuPt4uD9hHAHjLyLBiLR5zELelBdD9QNRAXZzsJx0WaDL9A==3363+ dependencies:3364+ function-bind "^1.1.1"3365+ has "^1.0.3"3366+ has-symbols "^1.0.3"3367+3368 get-package-type@^0.1.0:3369 version "0.1.0"3370 resolved "https://registry.yarnpkg.com/get-package-type/-/get-package-type-0.1.0.tgz#8de2d803cff44df3bc6c456e6668b36c3926e11a"3371 integrity sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q==39 unmodified lines3411 version "0.0.2"3412 resolved "https://registry.yarnpkg.com/gitignore-parser/-/gitignore-parser-0.0.2.tgz#f61259b985dd91414b9a7168faef9171c2eec5df"3413 integrity sha512-X6mpqUv59uWLGD4n3hZ8Cu8KbF2PMWPSFYmxZjdkpm3yOU7hSUYnzTkZI1mcWqchphvqyuz3/BhgBR4E/JtkCg==3414 3026-glob-parent@^5.1.2:3415+glob-parent@^5.1.2, glob-parent@~5.1.2:3416 version "5.1.2"3417 resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-5.1.2.tgz#869832c58034fe68a4093c17dc15e8340d8401c4"3418 integrity sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==3419 dependencies:78 unmodified lines3498 ignore "^5.2.0"3499 merge2 "^1.4.1"3500 slash "^3.0.0"3501 3502+gopd@^1.0.1:3503+ version "1.0.1"3504+ resolved "https://registry.yarnpkg.com/gopd/-/gopd-1.0.1.tgz#29ff76de69dac7489b7c0918a5788e56477c332c"3505+ integrity sha512-d65bNlIadxvpb/A2abVdlqKqV563juRnZ1Wtk6s1sIR8uNsXR70xqIzVqxVf1eTqDunwT2MkczEeaezCKTZhwA==3506+ dependencies:3507+ get-intrinsic "^1.1.3"3508+3509 got@^10.6.0:3510 version "10.7.0"3511 resolved "https://registry.yarnpkg.com/got/-/got-10.7.0.tgz#62889dbcd6cca32cd6a154cc2d0c6895121d091f"3512 integrity sha512-aWTDeNw9g+XqEZNcTjMMZSy7B7yE9toWOFYip7ofFTLleJhvZwUxxTxkTpKvF+p1SAA4VHmuEy7PiHTHyq8tJg==40 unmodified lines3553 version "4.2.9"3554 resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.9.tgz#041b05df45755e587a24942279b9d113146e1c96"3555 integrity sha512-NtNxqUcXgpW2iMrfqSfR73Glt39K+BLwWsPs94yR63v45T0Wbej7eRmL5cWfwEgqXnmjQp3zaJTshdRW/qC2ZQ==3556 3557+"graphql@^15.0.0 || ^16.0.0":3558+ version "16.6.0"3559+ resolved "https://registry.yarnpkg.com/graphql/-/graphql-16.6.0.tgz#c2dcffa4649db149f6282af726c8c83f1c7c5fdb"3560+ integrity sha512-KPIBPDlW7NxrbT/eh4qPXz5FiFdL5UbaA0XUNz2Rp3Z3hqBSkbj0GVjwFDztsWVauZUWsbKHgMg++sk8UX0bkw==3561+3562 hard-rejection@^2.1.0:3563 version "2.1.0"3564 resolved "https://registry.yarnpkg.com/hard-rejection/-/hard-rejection-2.1.0.tgz#1c6eda5c1685c63942766d79bb40ae773cecd883"3565 integrity sha512-VIZB+ibDhx7ObhAe7OVtoEbuP4h/MuOTHJ+J8h/eBXotJYl0fBgR72xDFCKgIh22OJZIOVNxBMWuhAr10r8HdA==29 unmodified lines3595 version "1.0.2"3596 resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.2.tgz#165d3070c00309752a1236a479331e3ac56f1423"3597 integrity sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==3598 3599+has-symbols@^1.0.3:3600+ version "1.0.3"3601+ resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.3.tgz#bb7b2c4349251dce87b125f7bdf874aa7c8b39f8"3602+ integrity sha512-l3LCuF6MgDNwTDKkdYGEihYjt5pRPbEg46rtlmnSPlUbgmB8LOIrKJbYYFBSbnPaJexMKtiPO8hmeRjRz2Td+A==3603+3604 has-tostringtag@^1.0.0:3605 version "1.0.0"3606 resolved "https://registry.yarnpkg.com/has-tostringtag/-/has-tostringtag-1.0.0.tgz#7e133818a7d394734f941e73c3d3f9291e658b25"3607 integrity sha512-kFjcSNhnlGV1kyoGk7OXKSawH5JOb/LzUc5w9B02hOTO0dfFRjbHQKvg1d6cf3HbeUmtU9VbbV3qzZ2Teh97WQ==11 unmodified lines3619 integrity sha512-f2dvO0VU6Oej7RkWJGrehjbzMAjFp5/VKPp5tTpWIV4JHHZK1/BxbFRtf/siA2SWTe09caDmVtYYzWEIbBS4zw==3620 dependencies:3621 function-bind "^1.1.1"3622 3623+headers-polyfill@^3.1.0:3624+ version "3.1.2"3625+ resolved "https://registry.yarnpkg.com/headers-polyfill/-/headers-polyfill-3.1.2.tgz#9a4dcb545c5b95d9569592ef7ec0708aab763fbe"3626+ integrity sha512-tWCK4biJ6hcLqTviLXVR9DTRfYGQMXEIUj3gwJ2rZ5wO/at3XtkI4g8mCvFdUF9l1KMBNCfmNAdnahm1cgavQA==3627+3628+hexoid@^1.0.0:3629+ version "1.0.0"3630+ resolved "https://registry.yarnpkg.com/hexoid/-/hexoid-1.0.0.tgz#ad10c6573fb907de23d9ec63a711267d9dc9bc18"3631+ integrity sha512-QFLV0taWQOZtvIRIAdBChesmogZrtuXvVWsFHZTk2SU+anspqZ2vMnoLg7IE1+Uk16N19APic1BuF8bC8c2m5g==3632+3633 hosted-git-info@^2.1.4:3634 version "2.8.9"3635 resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-2.8.9.tgz#dffc0bf9a21c02209090f2aa69429e1414daf3f9"3636 integrity sha512-mxIDAb9Lsm6DoOJ7xH+5+X4y1LU/4Hi50L9C5sIswK3JzULS4bwk1FvjdBgvYR4bzT4tuUQiC15FE2f5HbLvYw==38 unmodified lines3675 integrity sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==3676 dependencies:3677 safer-buffer ">= 2.1.2 < 3"3678 3679+ieee754@^1.1.13:3680+ version "1.2.1"3681+ resolved "https://registry.yarnpkg.com/ieee754/-/ieee754-1.2.1.tgz#8eb7a10a63fff25d15a57b001586d177d1b0d352"3682+ integrity sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==3683+3684 ignore-walk@^3.0.3:3685 version "3.0.4"3686 resolved "https://registry.yarnpkg.com/ignore-walk/-/ignore-walk-3.0.4.tgz#c9a09f69b7c7b479a5d74ac1a3c0d4236d2a6335"3687 integrity sha512-PY6Ii8o1jMRA1z4F2hRkH/xN59ox43DavKvD3oDpfurRlOJyAHpifIwpbdv1n4jt4ov0jSpw3kQ4GhJnpBL6WQ==55 unmodified lines3743 dependencies:3744 once "^1.3.0"3745 wrappy "1"3746 3326-inherits@2:3747+inherits@2, inherits@^2.0.3, inherits@^2.0.4:3748 version "2.0.4"3749 resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c"3750 integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==3751 58 unmodified lines3810 string-width "^4.1.0"3811 strip-ansi "^6.0.0"3812 through "^2.3.6"3813 3814+inquirer@^8.2.0:3815+ version "8.2.5"3816+ resolved "https://registry.yarnpkg.com/inquirer/-/inquirer-8.2.5.tgz#d8654a7542c35a9b9e069d27e2df4858784d54f8"3817+ integrity sha512-QAgPDQMEgrDssk1XiwwHoOGYF9BAbUcc1+j+FhEvaOt8/cKRqyLn0U5qA6F74fGhTMGxf92pOvPBeh29jQJDTQ==3818+ dependencies:3819+ ansi-escapes "^4.2.1"3820+ chalk "^4.1.1"3821+ cli-cursor "^3.1.0"3822+ cli-width "^3.0.0"3823+ external-editor "^3.0.3"3824+ figures "^3.0.0"3825+ lodash "^4.17.21"3826+ mute-stream "0.0.8"3827+ ora "^5.4.1"3828+ run-async "^2.4.0"3829+ rxjs "^7.5.5"3830+ string-width "^4.1.0"3831+ strip-ansi "^6.0.0"3832+ through "^2.3.6"3833+ wrap-ansi "^7.0.0"3834+3835 internal-slot@^1.0.3:3836 version "1.0.3"3837 resolved "https://registry.yarnpkg.com/internal-slot/-/internal-slot-1.0.3.tgz#7347e307deeea2faac2ac6205d4bc7d34967f59c"3838 integrity sha512-O0DB1JC/sPyZl7cIo78n5dR7eUSwwpYPiXRhTzNxZVAMUuB8vlnRFyLxdrVToks6XPLVnFfbzaVd5WLjhgg+vA==1 unmodified line3840 get-intrinsic "^1.1.0"3841 has "^1.0.3"3842 side-channel "^1.0.4"3843 3844+is-arguments@^1.0.4:3845+ version "1.1.1"3846+ resolved "https://registry.yarnpkg.com/is-arguments/-/is-arguments-1.1.1.tgz#15b3f88fda01f2a97fec84ca761a560f123efa9b"3847+ integrity sha512-8Q7EARjzEnKpt/PCD7e1cgUS0a6X8u5tdSiMqXhojOdoV9TsMsiO+9VLC5vAmO8N7/GmXn7yjR8qnA6bVAEzfA==3848+ dependencies:3849+ call-bind "^1.0.2"3850+ has-tostringtag "^1.0.0"3851+3852 is-arrayish@^0.2.1:3853 version "0.2.1"3854 resolved "https://registry.yarnpkg.com/is-arrayish/-/is-arrayish-0.2.1.tgz#77c99840527aa8ecb1a8ba697b80645a7a926a9d"3855 integrity sha1-d8mYQFJ6qOyxqLppe4BkWnqSap0=4 unmodified lines3860 integrity sha512-zB9CruMamjym81i2JZ3UMn54PKGsQzsJeo6xvN3HJJ4CAsQNB6iRutp2To77OfCNuoxspsIhzaPoO1zyCEhFOg==3861 dependencies:3862 has-bigints "^1.0.1"3863 3864+is-binary-path@~2.1.0:3865+ version "2.1.0"3866+ resolved "https://registry.yarnpkg.com/is-binary-path/-/is-binary-path-2.1.0.tgz#ea1f7f3b80f064236e83470f86c09c254fb45b09"3867+ integrity sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==3868+ dependencies:3869+ binary-extensions "^2.0.0"3870+3871 is-boolean-object@^1.1.0:3872 version "1.1.2"3873 resolved "https://registry.yarnpkg.com/is-boolean-object/-/is-boolean-object-1.1.2.tgz#5c6dc200246dd9321ae4b885a114bb1f75f63719"3874 integrity sha512-gDYaKHJmnj4aWxyj6YHyXVpdQawtVLHU5cb+eztPGczf6cjuTdwve5ZIEfgXqH4e57An1D1AKf8CZ3kYrQRqYA==3875 dependencies:3876 call-bind "^1.0.2"3877 has-tostringtag "^1.0.0"3878 3879+is-callable@^1.1.3:3880+ version "1.2.7"3881+ resolved "https://registry.yarnpkg.com/is-callable/-/is-callable-1.2.7.tgz#3bc2a85ea742d9e36205dcacdd72ca1fdc51b055"3882+ integrity sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==3883+3884 is-callable@^1.1.4, is-callable@^1.2.4:3885 version "1.2.4"3886 resolved "https://registry.yarnpkg.com/is-callable/-/is-callable-1.2.4.tgz#47301d58dd0259407865547853df6d61fe471945"3887 integrity sha512-nsuwtxZfMX67Oryl9LCQ+upnC0Z0BgpwntpS89m1H/TLF0zNfzfLMV/9Wa/6MZsj0acpEjAO0KF1xT6ZdLl95w==57 unmodified lines3945 version "2.1.0"3946 resolved "https://registry.yarnpkg.com/is-generator-fn/-/is-generator-fn-2.1.0.tgz#7d140adc389aaf3011a8f2a2a4cfa6faadffb118"3947 integrity sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ==3948 3949+is-generator-function@^1.0.7:3950+ version "1.0.10"3951+ resolved "https://registry.yarnpkg.com/is-generator-function/-/is-generator-function-1.0.10.tgz#f1558baf1ac17e0deea7c0415c438351ff2b3c72"3952+ integrity sha512-jsEjy9l3yiXEQ+PsXdmBwEPcOxaXWLspKdplFUVI9vq1iZgIekeC0L167qeu86czQaxed3q/Uzuw0swL0irL8A==3953+ dependencies:3954+ has-tostringtag "^1.0.0"3955+3487-is-glob@^4.0.0, is-glob@^4.0.1, is-glob@^4.0.3:3956+is-glob@^4.0.0, is-glob@^4.0.1, is-glob@^4.0.3, is-glob@~4.0.1:3957 version "4.0.3"3958 resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-4.0.3.tgz#64f61e42cbbb2eec2071a9dac0b28ba1e65d5084"3959 integrity sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==3960 dependencies:24 unmodified lines3985 version "2.0.2"3986 resolved "https://registry.yarnpkg.com/is-negative-zero/-/is-negative-zero-2.0.2.tgz#7bf6f03a28003b8b3965de3ac26f664d765f3150"3987 integrity sha512-dqJvarLawXsFbNDeJW7zAz8ItJ9cd28YufuuFzh0G8pNHjJMnY08Dv7sYX2uF5UpQOwieAeOExEYAWWfu7ZZUA==3988 3989+is-node-process@^1.0.1:3990+ version "1.0.1"3991+ resolved "https://registry.yarnpkg.com/is-node-process/-/is-node-process-1.0.1.tgz#4fc7ac3a91e8aac58175fe0578abbc56f2831b23"3992+ integrity sha512-5IcdXuf++TTNt3oGl9EBdkvndXA8gmc4bz/Y+mdEpWh3Mcn/+kOw6hI7LD5CocqJWMzeb0I0ClndRVNdEPuJXQ==3993+3994 is-npm@^5.0.0:3995 version "5.0.0"3996 resolved "https://registry.yarnpkg.com/is-npm/-/is-npm-5.0.0.tgz#43e8d65cc56e1b67f8d47262cf667099193f45a8"3997 integrity sha512-WW/rQLOazUq+ST/bCAVBp/2oMERWLsR7OrKyt052dNDk4DHcDE0/7QSXITlmi+VBcV13DfIbysG3tZJm5RfdBA==90 unmodified lines4088 integrity sha512-C/CPBqKWnvdcxqIARxyOh4v1UUEOCHpgDa0WYgpKDFMszcrPcffg5uhwSgPCLD2WWxmq6isisz87tzT01tuGhg==4089 dependencies:4090 has-symbols "^1.0.2"4091 4092+is-typed-array@^1.1.10, is-typed-array@^1.1.3:4093+ version "1.1.10"4094+ resolved "https://registry.yarnpkg.com/is-typed-array/-/is-typed-array-1.1.10.tgz#36a5b5cb4189b575d1a3e4b08536bfb485801e3f"4095+ integrity sha512-PJqgEHiWZvMpaFZ3uTc8kHPM4+4ADTlDniuQL7cU/UDA0Ql7F70yGfHph3cLNe+c9toaigv+DFzTJKhc2CtO6A==4096+ dependencies:4097+ available-typed-arrays "^1.0.5"4098+ call-bind "^1.0.2"4099+ for-each "^0.3.3"4100+ gopd "^1.0.1"4101+ has-tostringtag "^1.0.0"4102+4103 is-typedarray@^1.0.0:4104 version "1.0.0"4105 resolved "https://registry.yarnpkg.com/is-typedarray/-/is-typedarray-1.0.0.tgz#e479c80858df0c1b11ddda6940f96011fcda4a9a"4106 integrity sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=312 unmodified lines4419 version "1.2.2"4420 resolved "https://registry.yarnpkg.com/jest-pnp-resolver/-/jest-pnp-resolver-1.2.2.tgz#b704ac0ae028a89108a4d040b3f919dfddc8e33c"4421 integrity sha512-olV41bKSMm8BdnuMsewT4jqlZ8+3TCARAXjZGT9jcoSnrfUnRCqnMoF9XEeoWjbzObpqF9dRhHQj0Xb9QdF6/w==4422 4423+jest-preset-fastly-js-compute@^0.6.1:4424+ version "0.6.1"4425+ resolved "https://registry.yarnpkg.com/jest-preset-fastly-js-compute/-/jest-preset-fastly-js-compute-0.6.1.tgz#91562b7d532da42a5a1ec70aefe1d8f26da5e1de"4426+ integrity sha512-iYew/0jzKkuX8Ob7L2WqpMkqXv8KML183jYQWDVwthEi36fI6c3fAJpNNDsgfrq168KcBXgjszPgI31L4RmLTQ==4427+ dependencies:4428+ node-fetch "^2.6.7"4429+ ts-jest "^29.0.3"4430+4431 jest-regex-util@^29.0.0:4432 version "29.0.0"4433 resolved "https://registry.yarnpkg.com/jest-regex-util/-/jest-regex-util-29.0.0.tgz#b442987f688289df8eb6c16fa8df488b4cd007de"4434 integrity sha512-BV7VW7Sy0fInHWN93MMPtlClweYv2qrSCwfeFWmpribGZtQPWNvRSq9XOVgOEjU1iBGRKXUZil0o2AH7Iy9Lug==174 unmodified lines4609 "@jest/types" "^29.0.3"4610 import-local "^3.0.2"4611 jest-cli "^29.0.3"4612 4613+joi@^17.6.0:4614+ version "17.7.0"4615+ resolved "https://registry.yarnpkg.com/joi/-/joi-17.7.0.tgz#591a33b1fe1aca2bc27f290bcad9b9c1c570a6b3"4616+ integrity sha512-1/ugc8djfn93rTE3WRKdCzGGt/EtiYKxITMO4Wiv6q5JL1gl9ePt4kBsl1S499nbosspfctIQTpYIhSmHA3WAg==4617+ dependencies:4618+ "@hapi/hoek" "^9.0.0"4619+ "@hapi/topo" "^5.0.0"4620+ "@sideway/address" "^4.1.3"4621+ "@sideway/formula" "^3.0.0"4622+ "@sideway/pinpoint" "^2.0.0"4623+4624+js-levenshtein@^1.1.6:4625+ version "1.1.6"4626+ resolved "https://registry.yarnpkg.com/js-levenshtein/-/js-levenshtein-1.1.6.tgz#c6cee58eb3550372df8deb85fad5ce66ce01d59d"4627+ integrity sha512-X2BB11YZtrRqY4EnQcLX5Rh373zbK4alC1FW7D7MBhL2gtcC17cTnr6DmfHZeS0s2rTHjUTMMHfG7gO8SSdw+g==4628+4629 js-tokens@^4.0.0:4630 version "4.0.0"4631 resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499"4632 integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==98 unmodified lines4731 integrity sha512-weT+r0kTkRQdCdYCNtkMwWXQTMEswKrFBkm4ckQOMVhhqhIMI1UT2hMj+1iigIhgSZm5gTmrRXBNoGUgaTY1xA==4732 dependencies:4733 package-json "^6.3.0"4734 4735+lazy-ass@1.6.0:4736+ version "1.6.0"4737+ resolved "https://registry.yarnpkg.com/lazy-ass/-/lazy-ass-1.6.0.tgz#7999655e8646c17f089fdd187d150d3324d54513"4738+ integrity sha512-cc8oEVoctTvsFZ/Oje/kGnHbpWHYBe8IAJe4C0QNc3t8uM/0Y8+erSz/7Y1ALuXTEZTMvxXwO6YbX1ey3ujiZw==4739+4740 leven@^3.1.0:4741 version "3.1.0"4742 resolved "https://registry.yarnpkg.com/leven/-/leven-3.1.0.tgz#77891de834064cccba82ae7842bb6b14a13ed7f2"4743 integrity sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A==118 unmodified lines4862 integrity sha512-mmPrW0Fh2fxOzdBbFv4g1m6pR72haFLPJ2G5SJEELf1y+iaQrDG6cWCPjy54RHYbZAt7X+ls690Kw62AdWXBzQ==4863 dependencies:4864 chalk "^1.0.0"4865 4352-log-symbols@^4.0.0:4866+log-symbols@^4.0.0, log-symbols@^4.1.0:4867 version "4.1.0"4868 resolved "https://registry.yarnpkg.com/log-symbols/-/log-symbols-4.1.0.tgz#3fbdbb95b4683ac9fc785111e792e558d4abd503"4869 integrity sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==4870 dependencies:61 unmodified lines4932 version "4.3.0"4933 resolved "https://registry.yarnpkg.com/map-obj/-/map-obj-4.3.0.tgz#9304f906e93faae70880da102a9f1df0ea8bb05a"4934 integrity sha512-hdN1wVrZbb29eBGiGjJbeP8JbKjq1urkHJ/LIP/NY48MZ1QVXUsQBV1G1zvYFHn1XE06cwjBsOI2K3Ulnj1YXQ==4935 4936+map-stream@~0.1.0:4937+ version "0.1.0"4938+ resolved "https://registry.yarnpkg.com/map-stream/-/map-stream-0.1.0.tgz#e56aa94c4c8055a16404a0674b78f215f7c8e194"4939+ integrity sha512-CkYQrPYZfWnu/DAmVCpTSX/xHpKZ80eKh2lAkyA6AJTef6bW+6JpbQZN5rofum7da+SyN1bi5ctTm+lTfcCW3g==4940+4941 meow@^8.1.0:4942 version "8.1.2"4943 resolved "https://registry.yarnpkg.com/meow/-/meow-8.1.2.tgz#bcbe45bda0ee1729d350c03cffc8395a36c4e897"4944 integrity sha512-r85E3NdZ+mpYk1C6RjPFEMSE+s1iZMuHtsHAqY0DT3jZczl0diWUZ8g6oU7h0M9cD2EL+PzaYghhCLzR0ZNn5Q==19 unmodified lines4964 version "1.4.1"4965 resolved "https://registry.yarnpkg.com/merge2/-/merge2-1.4.1.tgz#4368892f885e907455a6fd7dc55c0c9d404990ae"4966 integrity sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==4967 4968+methods@^1.1.2:4969+ version "1.1.2"4970+ resolved "https://registry.yarnpkg.com/methods/-/methods-1.1.2.tgz#5529a4d67654134edcc5266656835b0f851afcee"4971+ integrity sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==4972+4973 micromatch@^4.0.4:4974 version "4.0.4"4975 resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-4.0.4.tgz#896d519dfe9db25fce94ceb7a500919bf881ebf9"4976 integrity sha512-pRmzw/XUcwXGpD9aI9q/0XOwLNygjETJ8y0ao0wdqprrzDa4YnxLcz7fQRZr8voh8V10kGhABbNcHVk5wHgWwg==12 unmodified lines4989 integrity sha512-6cP692WwGIs9XXdOO4++N+7qjqv0rqxxVvJ3VHPh/Sc9mVZcQP+ZGhkKiTvWMQRr2tbHkJP/Yn7Y0npb3ZBs4A==4990 dependencies:4991 mime-db "1.51.0"4992 4993+mime@2.6.0:4994+ version "2.6.0"4995+ resolved "https://registry.yarnpkg.com/mime/-/mime-2.6.0.tgz#a2a682a95cd4d0cb1d6257e28f83da7e35800367"4996+ integrity sha512-USPkMeET31rOMiarsBNIHZKLGgvKc/LrjofAnBlOttf5ajRvqiRA8QsenbcooctK6d6Ts6aqZXBA+XbkKthiQg==4997+4998 mimic-fn@^1.0.0:4999 version "1.2.0"5000 resolved "https://registry.yarnpkg.com/mimic-fn/-/mimic-fn-1.2.0.tgz#820c86a39334640e99516928bd03fca88057d022"5001 integrity sha512-jf84uxzwiuiIVKiOLpfYk7N46TSy8ubTonmneY9vrpHNAnp0QBt2BxWV9dO3/j+BoVAb+a5G6YDPW3M5HOdMWQ==102 unmodified lines5104 version "1.2.0"5105 resolved "https://registry.yarnpkg.com/mri/-/mri-1.2.0.tgz#6721480fec2a11a4889861115a48b6cbe7cc8f0b"5106 integrity sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==5107 5108+mrmime@^1.0.0:5109+ version "1.0.1"5110+ resolved "https://registry.yarnpkg.com/mrmime/-/mrmime-1.0.1.tgz#5f90c825fad4bdd41dc914eff5d1a8cfdaf24f27"5111+ integrity sha512-hzzEagAgDyoU1Q6yg5uI+AorQgdvMCur3FcKf7NhMKWsaYg+RnbTyHRa/9IlLF9rf455MOCtcqqrQQ83pPP7Uw==5112+5113 ms@2.0.0:5114 version "2.0.0"5115 resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8"5116 integrity sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=7 unmodified lines5124 version "2.1.3"5125 resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2"5126 integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==5127 5128+msw@^1.0.0:5129+ version "1.0.0"5130+ resolved "https://registry.yarnpkg.com/msw/-/msw-1.0.0.tgz#4f8e63aa23912561a63b99ff560a089da6969418"5131+ integrity sha512-8QVa1RAN/Nzbn/tKmtimJ+b2M1QZOMdETQW7/1TmBOZ4w+wJojfxuh1Hj5J4FYdBgZWW/TK4CABUOlOM4OjTOA==5132+ dependencies:5133+ "@mswjs/cookies" "^0.2.2"5134+ "@mswjs/interceptors" "^0.17.5"5135+ "@open-draft/until" "^1.0.3"5136+ "@types/cookie" "^0.4.1"5137+ "@types/js-levenshtein" "^1.1.1"5138+ chalk "4.1.1"5139+ chokidar "^3.4.2"5140+ cookie "^0.4.2"5141+ graphql "^15.0.0 || ^16.0.0"5142+ headers-polyfill "^3.1.0"5143+ inquirer "^8.2.0"5144+ is-node-process "^1.0.1"5145+ js-levenshtein "^1.1.6"5146+ node-fetch "^2.6.7"5147+ outvariant "^1.3.0"5148+ path-to-regexp "^6.2.0"5149+ strict-event-emitter "^0.4.3"5150+ type-fest "^2.19.0"5151+ yargs "^17.3.1"5152+5153 mustache@^4.2.0:5154 version "4.2.0"5155 resolved "https://registry.yarnpkg.com/mustache/-/mustache-4.2.0.tgz#e5892324d60a12ec9c2a73359edca52972bf6f64"5156 integrity sha512-71ippSywq5Yb7/tVYyGbkBggbU8H3u5Rz56fH60jGFgr8uHwxs+aSKeqmluIVzM0m0kB7xQjKS6qPfd0b2ZoqQ==19 unmodified lines5176 integrity sha512-dle7yf655IMjyFUqn6Nxkb18r4AOAkzRcgcZv6WZ0IqrOH4QCEZ8Sm6I7XX21zvHdBeeMeTkhR9qT2Z0EJDx6A==5177 dependencies:5178 type-fest "^0.4.1"5179 5180+node-fetch@2:5181+ version "2.6.9"5182+ resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.6.9.tgz#7c7f744b5cc6eb5fd404e0c7a9fec630a55657e6"5183+ integrity sha512-DJm/CJkZkRjKKj4Zi4BsKVZh3ValV5IR5s7LVZnW+6YMh0W1BfNA8XSs6DLMGYlId5F3KnA70uu2qepcR08Qqg==5184+ dependencies:5185+ whatwg-url "^5.0.0"5186+5187 node-fetch@^2.6.7:5188 version "2.6.7"5189 resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.6.7.tgz#24de9fba827e3b4ae44dc8b20256a379160052ad"5190 integrity sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==39 unmodified lines5230 is-core-module "^2.5.0"5231 semver "^7.3.4"5232 validate-npm-package-license "^3.0.1"5233 4668-normalize-path@^3.0.0:5234+normalize-path@^3.0.0, normalize-path@~3.0.0:5235 version "3.0.0"5236 resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-3.0.0.tgz#0dcd69ff23a1c9b11fd0978316644a0388216a65"5237 integrity sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==5238 175 unmodified lines5414 prelude-ls "^1.2.1"5415 type-check "^0.4.0"5416 word-wrap "^1.2.3"5417 5418+ora@^5.4.1:5419+ version "5.4.1"5420+ resolved "https://registry.yarnpkg.com/ora/-/ora-5.4.1.tgz#1b2678426af4ac4a509008e5e4ac9e9959db9e18"5421+ integrity sha512-5b6Y85tPxZZ7QytO+BQzysW31HJku27cRIlkbAXaNx+BdcVi+LlRFmVXzeF6a7JCwJpyw5c4b+YSVImQIrBpuQ==5422+ dependencies:5423+ bl "^4.1.0"5424+ chalk "^4.1.0"5425+ cli-cursor "^3.1.0"5426+ cli-spinners "^2.5.0"5427+ is-interactive "^1.0.0"5428+ is-unicode-supported "^0.1.0"5429+ log-symbols "^4.1.0"5430+ strip-ansi "^6.0.0"5431+ wcwidth "^1.0.1"5432+5433 org-regex@^1.0.0:5434 version "1.0.0"5435 resolved "https://registry.yarnpkg.com/org-regex/-/org-regex-1.0.0.tgz#67ebb9ab3cb124fea5841289d60b59434f041a59"5436 integrity sha512-7bqkxkEJwzJQUAlyYniqEZ3Ilzjh0yoa62c7gL6Ijxj5bEpPL+8IE1Z0PFj0ywjjXQcdrwR51g9MIcLezR0hKQ==2 unmodified lines5439 version "1.0.2"5440 resolved "https://registry.yarnpkg.com/os-tmpdir/-/os-tmpdir-1.0.2.tgz#bbe67406c79aa85c5cfec766fe5734555dfa1274"5441 integrity sha512-D2FR03Vir7FIu45XBY20mTb+/ZSWB00sjU9jdQXt83gDrI4Ztz5Fs7/yy74g2N5SVQY4xY1qDr4rNddwYRVX0g==5442 5443+outvariant@^1.2.1, outvariant@^1.3.0:5444+ version "1.3.0"5445+ resolved "https://registry.yarnpkg.com/outvariant/-/outvariant-1.3.0.tgz#c39723b1d2cba729c930b74bf962317a81b9b1c9"5446+ integrity sha512-yeWM9k6UPfG/nzxdaPlJkB2p08hCg4xP6Lx99F+vP8YF7xyZVfTmJjrrNalkmzudD4WFvNLVudQikqUmF8zhVQ==5447+5448 ow@^0.21.0:5449 version "0.21.0"5450 resolved "https://registry.yarnpkg.com/ow/-/ow-0.21.0.tgz#c2df2ad78d1bfc2ea9cdca311b7a6275258df621"5451 integrity sha512-dlsoDe39g7mhdsdrC1R/YwjT7yjVqE3svWwOlMGvN690waBkgEZBmKBdkmKvSt5/wZ6E0Jn/nIesPqMZOpPKqw==193 unmodified lines5645 version "1.0.7"5646 resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.7.tgz#fbc114b60ca42b30d9daf5858e4bd68bbedb6735"5647 integrity sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==5648 5649+path-to-regexp@^6.2.0:5650+ version "6.2.1"5651+ resolved "https://registry.yarnpkg.com/path-to-regexp/-/path-to-regexp-6.2.1.tgz#d54934d6798eb9e5ef14e7af7962c945906918e5"5652+ integrity sha512-JLyh7xT1kizaEvcaXOQwOc2/Yhw6KZOvPf1S8401UyLk86CU79LN3vl7ztXGm/pZ+YjoyAJ4rxmHwbkBXJX+yw==5653+5654 path-type@^4.0.0:5655 version "4.0.0"5656 resolved "https://registry.yarnpkg.com/path-type/-/path-type-4.0.0.tgz#84ed01c0a7ba380afe09d90a8c180dcd9d03043b"5657 integrity sha512-gDKb8aZMDeD/tZWs9P6+q0J9Mwkdl6xMV8TjnGP3qJVJ06bdMgkbBlLU8IdfOsIsFz2BW1rNVT3XuNEl8zPAvw==5658 5659+pause-stream@0.0.11:5660+ version "0.0.11"5661+ resolved "https://registry.yarnpkg.com/pause-stream/-/pause-stream-0.0.11.tgz#fe5a34b0cbce12b5aa6a2b403ee2e73b602f1445"5662+ integrity sha512-e3FBlXLmN/D1S+zHzanP4E/4Z60oFAa3O051qt1pxa7DEJWKAyil6upYVXCWadEnuoqa4Pkc9oUx9zsxYeRv8A==5663+ dependencies:5664+ through "~2.3"5665+5666 picocolors@^1.0.0:5667 version "1.0.0"5668 resolved "https://registry.yarnpkg.com/picocolors/-/picocolors-1.0.0.tgz#cb5bdc74ff3f51892236eaf79d68bc44564ab81c"5669 integrity sha512-1fygroTLlHu66zi26VoTDv8yRgm0Fccecssto+MhsZ0D/DGW2sm8E8AjW7NU5VVTRt5GxbeZ5qBuJr+HyLYkjQ==5670 5073-picomatch@^2.0.4, picomatch@^2.2.3, picomatch@^2.3.1:5671+picomatch@^2.0.4, picomatch@^2.2.1, picomatch@^2.2.3, picomatch@^2.3.1:5672 version "2.3.1"5673 resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.3.1.tgz#3ba3833733646d9d3e4995946c1365a67fb07a42"5674 integrity sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==5675 57 unmodified lines5733 dependencies:5734 kleur "^3.0.3"5735 sisteransi "^1.0.5"5736 5737+ps-tree@1.2.0:5738+ version "1.2.0"5739+ resolved "https://registry.yarnpkg.com/ps-tree/-/ps-tree-1.2.0.tgz#5e7425b89508736cdd4f2224d028f7bb3f722ebd"5740+ integrity sha512-0VnamPPYHl4uaU/nSFeZZpR21QAWRz+sRv4iW9+v/GS/J5U5iZB5BNN6J0RMoOvdx2gWM2+ZFMIm58q24e4UYA==5741+ dependencies:5742+ event-stream "=3.3.4"5743+5744 publint@^0.1.8:5745 version "0.1.8"5746 resolved "https://registry.yarnpkg.com/publint/-/publint-0.1.8.tgz#a679fccc67578f232ecffa568acfccf3a7c983c5"5747 integrity sha512-czOfocZAwS3d5RNrx4VyMxJJDyTn9MajMfuzJYlMrztFLrWkM+3KVdPozTfd8ka8aGWfR1cS66tMSDCgF70T+A==21 unmodified lines5769 integrity sha512-l1jNAspIBSFqbT+y+5FosojNpVpF94nlI+wDUpqP9enwOTfHx9f0gh5nB96vl+6yTpsJsypeNrwfzPrKuHB41A==5770 dependencies:5771 escape-goat "^2.0.0"5772 5773+qs@^6.11.0:5774+ version "6.11.0"5775+ resolved "https://registry.yarnpkg.com/qs/-/qs-6.11.0.tgz#fd0d963446f7a65e1367e01abd85429453f0c37a"5776+ integrity sha512-MvjoMCJwEarSbUYk5O+nmoSzSutSsTwF85zcHPQ9OrlFoZOYIjaqBAJIqIXjptyD5vThxGq52Xu/MaJzRkIk4Q==5777+ dependencies:5778+ side-channel "^1.0.4"5779+5780 queue-microtask@^1.2.2:5781 version "1.2.3"5782 resolved "https://registry.yarnpkg.com/queue-microtask/-/queue-microtask-1.2.3.tgz#4929228bbc724dfac43e0efb058caf7b6cfb6243"5783 integrity sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==36 unmodified lines5820 normalize-package-data "^2.5.0"5821 parse-json "^5.0.0"5822 type-fest "^0.6.0"5823 5824+readable-stream@^3.4.0:5825+ version "3.6.0"5826+ resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-3.6.0.tgz#337bbda3adc0706bd3e024426a286d4b4b2c9198"5827+ integrity sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==5828+ dependencies:5829+ inherits "^2.0.3"5830+ string_decoder "^1.1.1"5831+ util-deprecate "^1.0.1"5832+5833+readdirp@~3.6.0:5834+ version "3.6.0"5835+ resolved "https://registry.yarnpkg.com/readdirp/-/readdirp-3.6.0.tgz#74a370bd857116e245b29cc97340cd431a02a6c7"5836+ integrity sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==5837+ dependencies:5838+ picomatch "^2.2.1"5839+5840 redent@^3.0.0:5841 version "3.0.0"5842 resolved "https://registry.yarnpkg.com/redent/-/redent-3.0.0.tgz#e557b7998316bb53c9f1f56fa626352c6963059f"5843 integrity sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==137 unmodified lines5981 integrity sha512-hTdwr+7yYNIT5n4AMYp85KA6yw2Va0FLa3Rguvbpa4W3I5xynaBZo41cM3XM+4Q6fRMj3sBYIR1VAmZMXYJvRQ==5982 dependencies:5983 tslib "^1.9.0"5984 5985+rxjs@^7.5.4, rxjs@^7.5.5:5986+ version "7.8.0"5987+ resolved "https://registry.yarnpkg.com/rxjs/-/rxjs-7.8.0.tgz#90a938862a82888ff4c7359811a595e14e1e09a4"5988+ integrity sha512-F2+gxDshqmIub1KdvZkaEfGDwLNpPvk9Fs6LD/MyQxNgMds/WH9OdDDXOmxUZpME+iSK3rQCctkL0DYyytUqMg==5989+ dependencies:5990+ tslib "^2.1.0"5991+5992 sade@^1.8.1:5993 version "1.8.1"5994 resolved "https://registry.yarnpkg.com/sade/-/sade-1.8.1.tgz#0a78e81d658d394887be57d2a409bf703a3b2701"5995 integrity sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A==4 unmodified lines6000 version "5.1.2"6001 resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.1.2.tgz#991ec69d296e0313747d59bdfd2b745c35f8828d"6002 integrity sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==6003 6004+safe-buffer@~5.2.0:6005+ version "5.2.1"6006+ resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz#1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6"6007+ integrity sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==6008+6009 "safer-buffer@>= 2.1.2 < 3":6010 version "2.1.2"6011 resolved "https://registry.yarnpkg.com/safer-buffer/-/safer-buffer-2.1.2.tgz#44fa161b0187b9549dd84bb91802f9bd8385cd6a"6012 integrity sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==50 unmodified lines6063 integrity sha512-QlYTucUYOews+WeEujDoEGziz4K6c47V/Bd+LjSSYcA94p+DmINdf7ncaUinThfvZyu13lN9OY1XDxt8C0Tw0g==6064 dependencies:6065 lru-cache "^6.0.0"6066 6067+semver@^7.3.8:6068+ version "7.3.8"6069+ resolved "https://registry.yarnpkg.com/semver/-/semver-7.3.8.tgz#07a78feafb3f7b32347d725e33de7e2a2df67798"6070+ integrity sha512-NB1ctGL5rlHrPJtFDVIVzTyQylMLu9N9VICA6HSFJo8MCGVTMW6gfpicwKmmK/dAjTOrqu5l63JJOpDSrAis3A==6071+ dependencies:6072+ lru-cache "^6.0.0"6073+6074+set-cookie-parser@^2.4.6:6075+ version "2.5.1"6076+ resolved "https://registry.yarnpkg.com/set-cookie-parser/-/set-cookie-parser-2.5.1.tgz#ddd3e9a566b0e8e0862aca974a6ac0e01349430b"6077+ integrity sha512-1jeBGaKNGdEq4FgIrORu/N570dwoPYio8lSoYLWmX7sQ//0JY08Xh9o5pBcgmHQ/MbsYp/aZnOe1s1lIsbLprQ==6078+6079 set-cookie-parser@^2.4.8:6080 version "2.4.8"6081 resolved "https://registry.yarnpkg.com/set-cookie-parser/-/set-cookie-parser-2.4.8.tgz#d0da0ed388bc8f24e706a391f9c9e252a13c58b2"6082 integrity sha512-edRH8mBKEWNVIVMKejNnuJxleqYE/ZSdcT8/Nem9/mmosx12pctd80s2Oy00KNZzrogMZS5mauK2/ymL1bvlvg==95 unmodified lines6178 version "3.0.11"6179 resolved "https://registry.yarnpkg.com/spdx-license-ids/-/spdx-license-ids-3.0.11.tgz#50c0d8c40a14ec1bf449bae69a0ea4685a9d9f95"6180 integrity sha512-Ctl2BrFiM0X3MANYgj3CkygxhRmr9mi6xhejbdO960nF6EDJApTYpn0BQnDKlnNBULKiCN1n3w9EBkHK8ZWg+g==6181 6182+split@0.3:6183+ version "0.3.3"6184+ resolved "https://registry.yarnpkg.com/split/-/split-0.3.3.tgz#cd0eea5e63a211dfff7eb0f091c4133e2d0dd28f"6185+ integrity sha512-wD2AeVmxXRBoX44wAycgjVpMhvbwdI2aZjCkvfNcH1YqHQvJVa1duWc73OyVGJUc05fhFaTZeQ/PYsrmyH0JVA==6186+ dependencies:6187+ through "2"6188+6189 split@^1.0.1:6190 version "1.0.1"6191 resolved "https://registry.yarnpkg.com/split/-/split-1.0.1.tgz#605bd9be303aa59fb35f9229fbea0ddec9ea07d9"6192 integrity sha512-mTyOoPbrivtXnwnIxZRFYRrPNtEFKlpB2fvjSnCQUiAA6qAZzqwna5envK4uk6OIeP17CsdF3rSBGYVBsU0Tkg==16 unmodified lines6209 integrity sha512-xrQcmYhOsn/1kX+Vraq+7j4oE2j/6BFscZ0etmYg81xuM8Gq0022Pxb8+IqgOFUIaxHs0KaSb7T1+OegiNrNFA==6210 dependencies:6211 escape-string-regexp "^2.0.0"6212 6213+start-server-and-test@^1.15.2:6214+ version "1.15.2"6215+ resolved "https://registry.yarnpkg.com/start-server-and-test/-/start-server-and-test-1.15.2.tgz#3c4f9b358a0dc5ae03a96dd7d7ae9e25a3b24165"6216+ integrity sha512-t5xJX04Hg7hqxiKHMJBz/n4zIMsE6G7hpAcerFAH+4Vh9le/LeyFcJERJM7WLiPygWF9TOg33oroJF1XOzJtYQ==6217+ dependencies:6218+ arg "^5.0.2"6219+ bluebird "3.7.2"6220+ check-more-types "2.24.0"6221+ debug "4.3.4"6222+ execa "5.1.1"6223+ lazy-ass "1.6.0"6224+ ps-tree "1.2.0"6225+ wait-on "6.0.1"6226+6227+stream-combiner@~0.0.4:6228+ version "0.0.4"6229+ resolved "https://registry.yarnpkg.com/stream-combiner/-/stream-combiner-0.0.4.tgz#4d5e433c185261dde623ca3f44c586bcf5c4ad14"6230+ integrity sha512-rT00SPnTVyRsaSz5zgSPma/aHSOic5U1prhYdRy5HS2kTZviFpmDgzilbtsJsxiroqACmayynDN/9VzIbX5DOw==6231+ dependencies:6232+ duplexer "~0.1.1"6233+6234 streamsearch@^1.1.0:6235 version "1.1.0"6236 resolved "https://registry.yarnpkg.com/streamsearch/-/streamsearch-1.1.0.tgz#404dd1e2247ca94af554e841a8ef0eaa238da764"6237 integrity sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==6238 6239+strict-event-emitter@^0.2.4:6240+ version "0.2.8"6241+ resolved "https://registry.yarnpkg.com/strict-event-emitter/-/strict-event-emitter-0.2.8.tgz#b4e768927c67273c14c13d20e19d5e6c934b47ca"6242+ integrity sha512-KDf/ujU8Zud3YaLtMCcTI4xkZlZVIYxTLr+XIULexP+77EEVWixeXroLUXQXiVtH4XH2W7jr/3PT1v3zBuvc3A==6243+ dependencies:6244+ events "^3.3.0"6245+6246+strict-event-emitter@^0.4.3:6247+ version "0.4.4"6248+ resolved "https://registry.yarnpkg.com/strict-event-emitter/-/strict-event-emitter-0.4.4.tgz#47e98eb408fbed187460592385f6547ca200cffb"6249+ integrity sha512-rTCFXHBxs2/XvNc7InSkSwUkwyQ0T9eop/Qvm0atNUXpBxjwsJ5yb7Ih/tgHbjPdeCcB4aCP8K4tuo7hNKssNg==6250+6251 string-length@^4.0.1:6252 version "4.0.2"6253 resolved "https://registry.yarnpkg.com/string-length/-/string-length-4.0.2.tgz#a8a8dc7bd5c1a82b9b3c8b87e125f66871b6e57a"6254 integrity sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ==47 unmodified lines6302 dependencies:6303 call-bind "^1.0.2"6304 define-properties "^1.1.3"6305 6306+string_decoder@^1.1.1:6307+ version "1.3.0"6308+ resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.3.0.tgz#42f114594a46cf1a8e30b0a84f56c78c3edac21e"6309+ integrity sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==6310+ dependencies:6311+ safe-buffer "~5.2.0"6312+6313 strip-ansi@^3.0.0, strip-ansi@^3.0.1:6314 version "3.0.1"6315 resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-3.0.1.tgz#6a385fb8853d952d5ff05d0e8aaf94278dc63dcf"6316 integrity sha512-VhumSSbBqDTP8p2ZLKj40UjBCV4+v8bUSEpUb4KjRgWk9pbqGF4REFj6KEagidb2f/M6AzC0EmFyDNGaw9OCzg==52 unmodified lines6369 version "2.0.1"6370 resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-2.0.1.tgz#3c531942e908c2697c0ec344858c286c7ca0a60a"6371 integrity sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ==6372 6373+superagent@^8.0.5:6374+ version "8.0.6"6375+ resolved "https://registry.yarnpkg.com/superagent/-/superagent-8.0.6.tgz#e3fb0b3112b79b12acd605c08846253197765bf6"6376+ integrity sha512-HqSe6DSIh3hEn6cJvCkaM1BLi466f1LHi4yubR0tpewlMpk4RUFFy35bKz8SsPBwYfIIJy5eclp+3tCYAuX0bw==6377+ dependencies:6378+ component-emitter "^1.3.0"6379+ cookiejar "^2.1.3"6380+ debug "^4.3.4"6381+ fast-safe-stringify "^2.1.1"6382+ form-data "^4.0.0"6383+ formidable "^2.1.1"6384+ methods "^1.1.2"6385+ mime "2.6.0"6386+ qs "^6.11.0"6387+ semver "^7.3.8"6388+6389+supertest@^6.3.3:6390+ version "6.3.3"6391+ resolved "https://registry.yarnpkg.com/supertest/-/supertest-6.3.3.tgz#42f4da199fee656106fd422c094cf6c9578141db"6392+ integrity sha512-EMCG6G8gDu5qEqRQ3JjjPs6+FYT1a7Hv5ApHvtSghmOFJYtsU5S+pSb6Y2EUeCEY3CmEL3mmQ8YWlPOzQomabA==6393+ dependencies:6394+ methods "^1.1.2"6395+ superagent "^8.0.5"6396+6397 supports-color@^2.0.0:6398 version "2.0.0"6399 resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-2.0.0.tgz#535d045ce6b6363fa40117084629995e9df324c7"6400 integrity sha512-KKNVtd6pCYgPIKU4cp2733HWYCpplQhddZLBUryaAHou723x+FRzQ5Df824Fj+IyyuiQTRoub4SnIFfIcrp70g==63 unmodified lines6464 version "0.2.0"6465 resolved "https://registry.yarnpkg.com/text-table/-/text-table-0.2.0.tgz#7f5ee823ae805207c00af2df4a84ec3fcfa570b4"6466 integrity sha1-f17oI66AUgfACvLfSoTsP8+lcLQ=6467 5745-through@2, through@^2.3.6, through@^2.3.8:6468+through@2, through@^2.3.6, through@^2.3.8, through@~2.3, through@~2.3.1:6469 version "2.3.8"6470 resolved "https://registry.yarnpkg.com/through/-/through-2.3.8.tgz#0dd4c9ffaabc357960b1b724115d7e0e86a2e1f5"6471 integrity sha512-w89qg7PI8wAdvX60bMDP+bFoD5Dvhm9oLheFp5O4a2QF0cSBGsBX4qZmadPMvVqlLJBBci+WqGGOAPvcDeNSVg==6472 54 unmodified lines6527 make-error "1.x"6528 semver "7.x"6529 yargs-parser "^21.0.1"6530 6531+ts-jest@^29.0.3:6532+ version "29.0.3"6533+ resolved "https://registry.yarnpkg.com/ts-jest/-/ts-jest-29.0.3.tgz#63ea93c5401ab73595440733cefdba31fcf9cb77"6534+ integrity sha512-Ibygvmuyq1qp/z3yTh9QTwVVAbFdDy/+4BtIQR2sp6baF2SJU/8CKK/hhnGIDY2L90Az2jIqTwZPnN2p+BweiQ==6535+ dependencies:6536+ bs-logger "0.x"6537+ fast-json-stable-stringify "2.x"6538+ jest-util "^29.0.0"6539+ json5 "^2.2.1"6540+ lodash.memoize "4.x"6541+ make-error "1.x"6542+ semver "7.x"6543+ yargs-parser "^21.0.1"6544+6545 tsafe@^1.0.1:6546 version "1.0.1"6547 resolved "https://registry.yarnpkg.com/tsafe/-/tsafe-1.0.1.tgz#c8c4eb2d75d1478418a4941307c5dd667fd76d23"6548 integrity sha512-FgJ1a4rE7YbmW5QIzpsfFl4tsAp0x74FH2bVE6qODb2U8jSrwTr5/ckIazeylme5zXndVbtgKm4BZdqmoGhiPw==12 unmodified lines6561 version "1.14.1"6562 resolved "https://registry.yarnpkg.com/tslib/-/tslib-1.14.1.tgz#cf2d38bdc34a134bcaf1091c41f6619e2f672d00"6563 integrity sha512-Xni35NKzjgMrwevysHTCArtLDpPvye8zV/0E4EyYn43P7/7qvQwPh9BGkHewbMulVntbigmcT7rdX3BNo9wRJg==6564 6565+tslib@^2.1.0:6566+ version "2.4.1"6567+ resolved "https://registry.yarnpkg.com/tslib/-/tslib-2.4.1.tgz#0d0bfbaac2880b91e22df0768e55be9753a5b17e"6568+ integrity sha512-tGyy4dAjRIEwI7BzsB0lynWgOpfqjUdq91XXAlIWD2OwKBH7oCl/GZG/HT4BOHrTlPMOASlMQ7veyTqpmRcrNA==6569+6570 tsutils@^3.21.0:6571 version "3.21.0"6572 resolved "https://registry.yarnpkg.com/tsutils/-/tsutils-3.21.0.tgz#b48717d394cea6c1e096983eed58e9d61715b623"6573 integrity sha512-mHKK3iUXL+3UF6xL5k0PEhKRUBKPBCv/+RkEOpjRWxxx27KKRBmmA60A9pgOUvMi8GKhRMPEmjBRPzs2W7O1OA==57 unmodified lines6631 version "0.8.1"6632 resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.8.1.tgz#09e249ebde851d3b1e48d27c105444667f17b83d"6633 integrity sha512-4dbzIzqvjtgiM5rw1k5rEHtBANKmdudhGyBEajN01fEyhaAIhsoKNy6y7+IN93IfpFtwY9iqi7kD+xwKhQsNJA==6634 6635+type-fest@^2.19.0:6636+ version "2.19.0"6637+ resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-2.19.0.tgz#88068015bb33036a598b952e55e9311a60fd3a9b"6638+ integrity sha512-RAH822pAdBgcNMAfWnCBU3CFZcfZ/i1eZjwFU/dsLKumyuuP3niueg2UAukXYF0E2AAoc82ZSSf9J0WQBinzHA==6639+6640 typedarray-to-buffer@^3.1.5:6641 version "3.1.5"6642 resolved "https://registry.yarnpkg.com/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz#a97ee7a9ff42691b9f783ff1bc5112fe3fca9080"6643 integrity sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==83 unmodified lines6727 version "4.0.3"6728 resolved "https://registry.yarnpkg.com/urlpattern-polyfill/-/urlpattern-polyfill-4.0.3.tgz#c1fa7a73eb4e6c6a1ffb41b24cf31974f7392d3b"6729 integrity sha512-DOE84vZT2fEcl9gqCUTcnAw5ZY5Id55ikUcziSUntuEFL3pRvavg5kwDmTEUJkeCHInTlV/HexFomgYnzO5kdQ==6730 6731+util-deprecate@^1.0.1:6732+ version "1.0.2"6733+ resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf"6734+ integrity sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==6735+6736+util@^0.12.3:6737+ version "0.12.5"6738+ resolved "https://registry.yarnpkg.com/util/-/util-0.12.5.tgz#5f17a6059b73db61a875668781a1c2b136bd6fbc"6739+ integrity sha512-kZf/K6hEIrWHI6XqOFUiiMa+79wE/D8Q+NCNAWclkyg3b4d2k7s0QGepNjiABc+aR3N1PAyHL7p6UcLY6LmrnA==6740+ dependencies:6741+ inherits "^2.0.3"6742+ is-arguments "^1.0.4"6743+ is-generator-function "^1.0.7"6744+ is-typed-array "^1.1.3"6745+ which-typed-array "^1.1.2"6746+6747 v8-compile-cache@^2.0.3:6748 version "2.3.0"6749 resolved "https://registry.yarnpkg.com/v8-compile-cache/-/v8-compile-cache-2.3.0.tgz#2de19618c66dc247dcfb6f99338035d8245a2cee"6750 integrity sha512-l8lCEmLcLYZh4nbunNZvQCJc5pv7+RCwa8q/LdUx8u7lsWvPDKmpodJAJNwkAhJC//dFY48KuIEmjtd4RViDrA==26 unmodified lines6777 integrity sha512-M6w37eVCMMouJ9V/sdPGnC5H4uDr73/+xdq0FBLO3TFFX1+7wiUY6Es328NN+y43tmY+doUdN9g9J21vqB7iLw==6778 dependencies:6779 builtins "^1.0.3"6780 6781+wait-on@6.0.1:6782+ version "6.0.1"6783+ resolved "https://registry.yarnpkg.com/wait-on/-/wait-on-6.0.1.tgz#16bbc4d1e4ebdd41c5b4e63a2e16dbd1f4e5601e"6784+ integrity sha512-zht+KASY3usTY5u2LgaNqn/Cd8MukxLGjdcZxT2ns5QzDmTFc4XoWBgC+C/na+sMRZTuVygQoMYwdcVjHnYIVw==6785+ dependencies:6786+ axios "^0.25.0"6787+ joi "^17.6.0"6788+ lodash "^4.17.21"6789+ minimist "^1.2.5"6790+ rxjs "^7.5.4"6791+6792 walker@^1.0.8:6793 version "1.0.8"6794 resolved "https://registry.yarnpkg.com/walker/-/walker-1.0.8.tgz#bd498db477afe573dc04185f011d3ab8a8d7653f"6795 integrity sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ==6796 dependencies:6797 makeerror "1.0.12"6798 6799+wcwidth@^1.0.1:6800+ version "1.0.1"6801+ resolved "https://registry.yarnpkg.com/wcwidth/-/wcwidth-1.0.1.tgz#f0b0dcf915bc5ff1528afadb2c0e17b532da2fe8"6802+ integrity sha512-XHPEwS0q6TaxcvG85+8EYkbiCux2XtWG2mkc47Ng2A77BQu9+DqIOJldST4HgPkuea7dvKSj5VgX3P1d4rW8Tg==6803+ dependencies:6804+ defaults "^1.0.3"6805+6806+web-encoding@1.1.5, web-encoding@^1.1.5:6807+ version "1.1.5"6808+ resolved "https://registry.yarnpkg.com/web-encoding/-/web-encoding-1.1.5.tgz#fc810cf7667364a6335c939913f5051d3e0c4864"6809+ integrity sha512-HYLeVCdJ0+lBYV2FvNZmv3HJ2Nt0QYXqZojk3d9FJOLkwnuhzM9tmamh8d7HPM8QqjKH8DeHkFTx+CFlWpZZDA==6810+ dependencies:6811+ util "^0.12.3"6812+ optionalDependencies:6813+ "@zxing/text-encoding" "0.9.0"6814+6815+web-streams-polyfill@^3.1.1:6816+ version "3.2.1"6817+ resolved "https://registry.yarnpkg.com/web-streams-polyfill/-/web-streams-polyfill-3.2.1.tgz#71c2718c52b45fd49dbeee88634b3a60ceab42a6"6818+ integrity sha512-e0MO3wdXWKrLbL0DgGnUV7WHVuw9OUvL4hjgnPkIeEvESk74gAITi5G606JtZPp39cd8HA9VQzCIvA49LpPN5Q==6819+6820 webidl-conversions@^3.0.0:6821 version "3.0.1"6822 resolved "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-3.0.1.tgz#24534275e2a7bc6be7bc86611cc16ae0a5654871"6823 integrity sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==16 unmodified lines6840 is-number-object "^1.0.4"6841 is-string "^1.0.5"6842 is-symbol "^1.0.3"6843 6844+which-typed-array@^1.1.2:6845+ version "1.1.9"6846+ resolved "https://registry.yarnpkg.com/which-typed-array/-/which-typed-array-1.1.9.tgz#307cf898025848cf995e795e8423c7f337efbde6"6847+ integrity sha512-w9c4xkx6mPidwp7180ckYWfMmvxpjlZuIudNtDf4N/tTAUB8VJbX25qZoAsrtGuYNnGw3pa0AXgbGKRB8/EceA==6848+ dependencies:6849+ available-typed-arrays "^1.0.5"6850+ call-bind "^1.0.2"6851+ for-each "^0.3.3"6852+ gopd "^1.0.1"6853+ has-tostringtag "^1.0.0"6854+ is-typed-array "^1.1.10"6855+6856 which@^2.0.1:6857 version "2.0.2"6858 resolved "https://registry.yarnpkg.com/which/-/which-2.0.2.tgz#7c6a8dd0a636a0327e10b59c9286eee93f3f51b1"6859 integrity sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==113 unmodified lines6973 "@types/stack-trace" "0.0.29"6974 cookie "^0.4.1"6975 mustache "^4.2.0"6976 stack-trace "0.0.10"6977+6978+zod@^3.20.2:6979+ version "3.20.2"6980+ resolved "https://registry.yarnpkg.com/zod/-/zod-3.20.2.tgz#068606642c8f51b3333981f91c0a8ab37dfc2807"6981+ integrity sha512-1MzNQdAvO+54H+EaK5YpyEy0T+Ejo/7YLHS93G3RnYWh5gaotGHwGeN/ZO687qEDU2y4CdStQYXVHIgrUl5UVQ==