feat: support Deno! (#336)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Yusuke Wada · committed by GitHub · parent a289e0f · Browse files · 96 files·+10020 added−2 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
96 files+10020 added−2 removed
- tests:+4985 added−0 removed
- other:+5035 added−2 removed
Provenance
- Commit
d9e9e62- Tree
5c4fc15- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
a289e0f
96 files changed+10020 added−2 removed
added:deno_dist/middleware/basic-auth/index.test.ts+159 added
1+import { Buffer } from "https://deno.land/std@0.85.0/node/buffer.ts";2+import { SHA256 } from 'crypto-js DENOIFY: DEPENDENCY UNMET (DEV DEPENDENCY)'3+import { Hono } from '../../hono.ts'4+import { basicAuth } from './index.ts'5+6+describe('Basic Auth by Middleware', () => {7+ const crypto = global.crypto8+ beforeAll(() => {9+ global.crypto = require('crypto').webcrypto10+ })11+ afterAll(() => {12+ global.crypto = crypto13+ })14+15+ const app = new Hono()16+17+ const username = 'hono-user-a'18+ const password = 'hono-password-a'19+ const unicodePassword = '炎'20+21+ const usernameB = 'hono-user-b'22+ const passwordB = 'hono-password-b'23+24+ const usernameC = 'hono-user-c'25+ const passwordC = 'hono-password-c'26+27+ app.use(28+ '/auth/*',29+ basicAuth({30+ username,31+ password,32+ })33+ )34+35+ app.use(36+ '/auth-unicode/*',37+ basicAuth({38+ username: username,39+ password: unicodePassword,40+ })41+ )42+43+ app.use(44+ '/auth-multi/*',45+ basicAuth(46+ {47+ username: usernameB,48+ password: passwordB,49+ },50+ {51+ username: usernameC,52+ password: passwordC,53+ }54+ )55+ )56+57+ app.use(58+ '/auth-override-func/*',59+ basicAuth({60+ username: username,61+ password: password,62+ hashFunction: (data: string) => SHA256(data).toString(),63+ })64+ )65+66+ app.use('/nested/*', async (c, next) => {67+ const auth = basicAuth({ username: username, password: password })68+ await auth(c, next)69+ })70+71+ app.get('/auth/*', () => new Response('auth'))72+ app.get('/auth-unicode/*', () => new Response('auth'))73+ app.get('/auth-multi/*', () => new Response('auth'))74+ app.get('/auth-override-func/*', () => new Response('auth'))75+76+ app.get('/nested/*', () => new Response('nested'))77+78+ it('Should not authorize', async () => {79+ const req = new Request('http://localhost/auth/a')80+ const res = await app.request(req)81+ expect(res).not.toBeNull()82+ expect(res.status).toBe(401)83+ expect(await res.text()).toBe('Unauthorized')84+ })85+86+ it('Should authorize', async () => {87+ const credential = Buffer.from(username + ':' + password).toString('base64')88+89+ const req = new Request('http://localhost/auth/a')90+ req.headers.set('Authorization', `Basic ${credential}`)91+ const res = await app.request(req)92+ expect(res).not.toBeNull()93+ expect(res.status).toBe(200)94+ expect(await res.text()).toBe('auth')95+ })96+97+ it('Should authorize Unicode', async () => {98+ const credential = Buffer.from(username + ':' + unicodePassword).toString('base64')99+100+ const req = new Request('http://localhost/auth-unicode/a')101+ req.headers.set('Authorization', `Basic ${credential}`)102+ const res = await app.request(req)103+ expect(res).not.toBeNull()104+ expect(res.status).toBe(200)105+ expect(await res.text()).toBe('auth')106+ })107+108+ it('Should authorize multiple users', async () => {109+ let credential = Buffer.from(usernameB + ':' + passwordB).toString('base64')110+111+ let req = new Request('http://localhost/auth-multi/b')112+ req.headers.set('Authorization', `Basic ${credential}`)113+ let res = await app.request(req)114+ expect(res).not.toBeNull()115+ expect(res.status).toBe(200)116+ expect(await res.text()).toBe('auth')117+118+ credential = Buffer.from(usernameC + ':' + passwordC).toString('base64')119+ req = new Request('http://localhost/auth-multi/c')120+ req.headers.set('Authorization', `Basic ${credential}`)121+ res = await app.request(req)122+ expect(res).not.toBeNull()123+ expect(res.status).toBe(200)124+ expect(await res.text()).toBe('auth')125+ })126+127+ it('Should authorize with sha256 function override', async () => {128+ const credential = Buffer.from(username + ':' + password).toString('base64')129+130+ const req = new Request('http://localhost/auth-override-func/a')131+ req.headers.set('Authorization', `Basic ${credential}`)132+ const res = await app.request(req)133+ expect(res).not.toBeNull()134+ expect(res.status).toBe(200)135+ expect(await res.text()).toBe('auth')136+ })137+138+ it('Should authorize - nested', async () => {139+ const credential = Buffer.from(username + ':' + password).toString('base64')140+141+ const req = new Request('http://localhost/nested')142+ req.headers.set('Authorization', `Basic ${credential}`)143+ const res = await app.request(req)144+ expect(res).not.toBeNull()145+ expect(res.status).toBe(200)146+ expect(await res.text()).toBe('nested')147+ })148+149+ it('Should not authorize - nested', async () => {150+ const credential = Buffer.from('foo' + ':' + 'bar').toString('base64')151+152+ const req = new Request('http://localhost/nested')153+ req.headers.set('Authorization', `Basic ${credential}`)154+ const res = await app.request(req)155+ expect(res).not.toBeNull()156+ expect(res.status).toBe(401)157+ expect(await res.text()).toBe('Unauthorized')158+ })159+})added:deno_dist/middleware/basic-auth/index.ts+77 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677import type { Context } from '../../context.ts'import type { Next } from '../../hono.ts'import { timingSafeEqual } from '../../utils/buffer.ts'import { decodeBase64 } from '../../utils/encode.ts'
const CREDENTIALS_REGEXP = /^ *(?:[Bb][Aa][Ss][Ii][Cc]) +([A-Za-z0-9._~+/-]+=*) *$/const USER_PASS_REGEXP = /^([^:]*):(.*)$/
const auth = (req: Request) => { if (!req) { throw new TypeError('argument req is required') }
if (typeof req !== 'object') { throw new TypeError('argument req is required to be an object') }
if (!req.headers || typeof req.headers !== 'object') { throw new TypeError('argument req is required to have headers property') }
const match = CREDENTIALS_REGEXP.exec(req.headers.get('Authorization') || '') if (!match) { return undefined }
const userPass = USER_PASS_REGEXP.exec(decodeBase64(match[1]))
if (!userPass) { return undefined }
return { username: userPass[1], password: userPass[2] }}
export const basicAuth = ( options: { username: string; password: string; realm?: string; hashFunction?: Function }, ...users: { username: string; password: string }[]) => { if (!options) { throw new Error('basic auth middleware requires options for "username and password"') }
if (!options.realm) { options.realm = 'Secure Area' } users.unshift({ username: options.username, password: options.password })
return async (ctx: Context, next: Next) => { const requestUser = auth(ctx.req) if (requestUser) { for (const user of users) { const usernameEqual = await timingSafeEqual( user.username, requestUser.username, options.hashFunction ) const passwordEqual = await timingSafeEqual( user.password, requestUser.password, options.hashFunction ) if (usernameEqual && passwordEqual) { // Authorized OK await next() return } } } ctx.res = new Response('Unauthorized', { status: 401, headers: { 'WWW-Authenticate': 'Basic realm="' + options.realm?.replace(/"/g, '\\"') + '"', }, }) }}added:deno_dist/middleware/basic-auth/README.md+47 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647# Basic Auth Middleware
## Usage
```jsimport { Hono } from 'hono'import { basicAuth } from 'hono/basic-auth'
const app = new Hono()
app.use( '/auth/*', basicAuth({ username: 'hono', password: 'acoolproject', }))
app.get('/auth/page', (c) => { return c.text('You are authorized')})
app.fire()```
For Fastly Compute@Edge, polyfill `crypto` or use `crypto-js`.
Install:
```npm i crypto-js```
Override `hashFunction`:
```jsimport { SHA256 } from 'crypto-js'
app.use( '/auth/*', basicAuth({ username: 'hono', password: 'acoolproject', hashFunction: (d: string) => SHA256(d).toString(), // <--- }))```added:deno_dist/middleware/bearer-auth/index.test.ts+67 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667import { Hono } from '../../hono.ts'import { bearerAuth } from './index.ts'
describe('Bearer Auth by Middleware', () => { const app = new Hono()
const token = 'abcdefg12345-._~+/='
app.use('/auth/*', bearerAuth({ token })) app.use('/authBot/*', bearerAuth({ token, prefix: 'Bot' }))
app.get('/auth/*', () => new Response('auth')) app.get('/authBot/*', () => new Response('auth bot'))
it('Should authorize', async () => { const req = new Request('http://localhost/auth/a') req.headers.set('Authorization', 'Bearer abcdefg12345-._~+/=') const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(await res.text()).toBe('auth') })
it('Should not authorize - no authorization header', async () => { const req = new Request('http://localhost/auth/a') const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(401) expect(await res.text()).toBe('Unauthorized') })
it('Should not authorize - invalid request', async () => { const req = new Request('http://localhost/auth/a') req.headers.set('Authorization', 'Beare abcdefg12345-._~+/=') const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(400) expect(await res.text()).toBe('Bad Request') })
it('Should not authorize - invalid token', async () => { const req = new Request('http://localhost/auth/a') req.headers.set('Authorization', 'Bearer invalid-token') const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(401) expect(await res.text()).toBe('Unauthorized') })
it('Should authorize', async () => { const req = new Request('http://localhost/authBot/a') req.headers.set('Authorization', 'Bot abcdefg12345-._~+/=') const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(await res.text()).toBe('auth bot') })
it('Should not authorize - invalid request', async () => { const req = new Request('http://localhost/authBot/a') req.headers.set('Authorization', 'Bearer abcdefg12345-._~+/=') const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(400) expect(await res.text()).toBe('Bad Request') })})added:deno_dist/middleware/bearer-auth/index.ts+66 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566import type { Context } from '../../context.ts'import type { Next } from '../../hono.ts'import { timingSafeEqual } from '../../utils/buffer.ts'
const TOKEN_STRINGS = '[A-Za-z0-9._~+/-]+=*'const PREFIX = 'Bearer'
export const bearerAuth = (options: { token: string realm?: string prefix?: string hashFunction?: Function}) => { if (!options.token) { throw new Error('bearer auth middleware requires options for "token"') } if (!options.realm) { options.realm = '' } if (!options.prefix) { options.prefix = PREFIX }
const realm = options.realm?.replace(/"/g, '\\"')
return async (c: Context, next: Next) => { const headerToken = c.req.headers.get('Authorization')
if (!headerToken) { // No Authorization header c.res = new Response('Unauthorized', { status: 401, headers: { 'WWW-Authenticate': `${options.prefix} realm="` + realm + '"', }, }) } else { const regexp = new RegExp('^' + options.prefix + ' +(' + TOKEN_STRINGS + ') *$') const match = regexp.exec(headerToken) if (!match) { // Invalid Request c.res = new Response('Bad Request', { status: 400, headers: { 'WWW-Authenticate': `${options.prefix} error="invalid_request"`, }, }) } else { const equal = await timingSafeEqual(options.token, match[1], options.hashFunction) if (!equal) { // Invalid Token c.res = new Response('Unauthorized', { status: 401, headers: { 'WWW-Authenticate': `${options.prefix} error="invalid_token"`, }, }) } else { // Authorize OK await next() return } } } }}added:deno_dist/middleware/bearer-auth/README.md+34 added
12345678910111213141516171819202122232425262728293031323334# Bearer Auth Middleware
## Usage
```tsimport { Hono } from 'hono'import { bearerAuth } from 'hono/bearer-auth'
const app = new Hono()
const token = 'honoisacool'
app.use('/auth/*', bearerAuth({ token }))
app.get('/auth/page', (c) => { return c.text('You are authorized')})
app.fire()```
## Options
```tsapp.use( '/auth/*', bearerAuth({ token: 'honoisacool', // Required realm: 'example.com', prefix: 'Bot' hashFunction: (d: string) => SHA256(d).toString(), // For Fastly Compute@Edge }))```added:deno_dist/middleware/body-parse/index.test.ts+62 added
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162import { Hono } from '../../hono.ts'import { bodyParse } from './index.ts'
describe('Parse Body Middleware', () => { const app = new Hono()
app.use('*', bodyParse()) app.post('/json', async (ctx) => { return ctx.json(ctx.req.parsedBody, 200) }) app.post('/text', async (ctx) => { return ctx.text(ctx.req.parsedBody, 200) }) app.post('/form', async (ctx) => { return ctx.json(ctx.req.parsedBody, 200) })
it('POST with JSON', async () => { const payload = { message: 'hello hono' } const req = new Request('http://localhost/json', { method: 'POST', body: JSON.stringify(payload), headers: new Headers({ 'Content-Type': 'application/json' }), }) const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(req.parsedBody).toEqual(payload) expect(await res.json()).toEqual(payload) })
it('POST with text', async () => { const payload = 'hello' const req = new Request('http://localhost/text', { method: 'POST', body: 'hello', headers: new Headers({ 'Content-Type': 'application/text' }), }) const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(req.parsedBody).toEqual(payload) expect(await res.text()).toEqual(payload) })
it('POST with form', async () => { const formData = new URLSearchParams() formData.append('message', 'hello') const req = new Request('https://localhost/form', { method: 'POST', body: formData, headers: { 'Content-Type': 'application/x-www-form-urlencoded', }, }) const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(req.parsedBody).toEqual({ message: 'hello' }) expect(await res.json()).toEqual({ message: 'hello' }) })})added:deno_dist/middleware/body-parse/index.ts+16 added
12345678910111213141516import type { Context } from '../../context.ts'import type { Next } from '../../hono.ts'import { parseBody } from '../../utils/body.ts'
declare global { interface Request { parsedBody: any }}
export const bodyParse = () => { return async (ctx: Context, next: Next) => { ctx.req.parsedBody = await parseBody(ctx.req) await next() }}added:deno_dist/middleware/cookie/index.test.ts+95 added
1+import { Hono } from '../../hono.ts'2+import { cookie } from './index.ts'3+4+describe('Cookie Middleware', () => {5+ describe('Parse cookie', () => {6+ const apps: Record<string, Hono> = {}7+ apps['get by name'] = (() => {8+ const app = new Hono()9+10+ app.use('/cookie', cookie())11+12+ app.get('/cookie', (c) => {13+ const yummyCookie = c.req.cookie('yummy_cookie')14+ const tastyCookie = c.req.cookie('tasty_cookie')15+ const res = new Response('Good cookie')16+ res.headers.set('Yummy-Cookie', yummyCookie)17+ res.headers.set('Tasty-Cookie', tastyCookie)18+ return res19+ })20+21+ return app22+ })()23+24+ apps['get all as an object'] = (() => {25+ const app = new Hono()26+27+ app.use('/cookie', cookie())28+29+ app.get('/cookie', (c) => {30+ const { yummy_cookie: yummyCookie, tasty_cookie: tastyCookie } = c.req.cookie()31+ const res = new Response('Good cookie')32+ res.headers.set('Yummy-Cookie', yummyCookie)33+ res.headers.set('Tasty-Cookie', tastyCookie)34+ return res35+ })36+37+ return app38+ })()39+40+ describe.each(Object.keys(apps))('%s', (name) => {41+ const app = apps[name]42+ it('Parse cookie on c.req.cookie', async () => {43+ const req = new Request('http://localhost/cookie')44+ const cookieString = 'yummy_cookie=choco; tasty_cookie = strawberry '45+ req.headers.set('Cookie', cookieString)46+ const res = await app.request(req)47+48+ expect(res.headers.get('Yummy-Cookie')).toBe('choco')49+ expect(res.headers.get('Tasty-Cookie')).toBe('strawberry')50+ })51+ })52+ })53+54+ describe('Set cookie', () => {55+ const app = new Hono()56+57+ app.use('/set-cookie', cookie())58+59+ app.get('/set-cookie', (c) => {60+ c.cookie('delicious_cookie', 'macha')61+ return c.text('Give cookie')62+ })63+64+ it('Set cookie on c.cookie', async () => {65+ const res = await app.request('http://localhost/set-cookie')66+ expect(res.status).toBe(200)67+ const header = res.headers.get('Set-Cookie')68+ expect(header).toBe('delicious_cookie=macha')69+ })70+71+ app.use('/set-cookie-complex', cookie())72+73+ app.get('/set-cookie-complex', (c) => {74+ c.cookie('great_cookie', 'banana', {75+ path: '/',76+ secure: true,77+ domain: 'example.com',78+ httpOnly: true,79+ maxAge: 1000,80+ expires: new Date(Date.UTC(2000, 11, 24, 10, 30, 59, 900)),81+ sameSite: 'Strict',82+ })83+ return c.text('Give cookie')84+ })85+86+ it('Complex pattern', async () => {87+ const res = await app.request('http://localhost/set-cookie-complex')88+ expect(res.status).toBe(200)89+ const header = res.headers.get('Set-Cookie')90+ expect(header).toBe(91+ 'great_cookie=banana; Max-Age=1000; Domain=example.com; Path=/; Expires=Sun, 24 Dec 2000 10:30:59 GMT; HttpOnly; Secure; SameSite=Strict'92+ )93+ })94+ })95+})added:deno_dist/middleware/cookie/index.ts+94 added
1+import type { Context } from '../../context.ts'2+import type { Next } from '../../hono.ts'3+4+declare global {5+ interface Request {6+ cookie: {7+ (name: string): string8+ (): Record<string, string>9+ }10+ }11+}12+13+declare module '../../context.ts' {14+ interface Context {15+ cookie: (name: string, value: string, options?: CookieOptions) => void16+ }17+}18+19+export type Cookie = Record<string, string>20+export type CookieOptions = {21+ domain?: string22+ expires?: Date23+ httpOnly?: boolean24+ maxAge?: number25+ path?: string26+ secure?: boolean27+ signed?: boolean28+ sameSite?: 'Strict' | 'Lax' | 'None'29+}30+31+export const cookie = () => {32+ return async (c: Context, next: Next) => {33+ c.req.cookie = ((name?: string): string | Record<string, string> => {34+ const cookie = c.req.headers.get('Cookie') || ''35+ const obj = parse(cookie)36+ if (name) {37+ const value = obj[name]38+ return value39+ } else {40+ return obj41+ }42+ }) as typeof c.req.cookie43+ c.cookie = (name: string, value: string, opt?: CookieOptions) => {44+ const cookie = serialize(name, value, opt)45+ c.header('Set-Cookie', cookie)46+ }47+ await next()48+ }49+}50+51+const parse = (cookie: string): Cookie => {52+ const pairs = cookie.split(/;\s*/g)53+ const parsedCookie: Cookie = {}54+ for (let i = 0, len = pairs.length; i < len; i++) {55+ const pair = pairs[i].split(/\s*=\s*([^\s]+)/)56+ parsedCookie[pair[0]] = decodeURIComponent(pair[1])57+ }58+ return parsedCookie59+}60+61+const serialize = (name: string, value: string, opt: CookieOptions = {}): string => {62+ value = encodeURIComponent(value)63+ let cookie = `${name}=${value}`64+65+ if (opt.maxAge) {66+ cookie += `; Max-Age=${Math.floor(opt.maxAge)}`67+ }68+69+ if (opt.domain) {70+ cookie += '; Domain=' + opt.domain71+ }72+73+ if (opt.path) {74+ cookie += '; Path=' + opt.path75+ }76+77+ if (opt.expires) {78+ cookie += '; Expires=' + opt.expires.toUTCString()79+ }80+81+ if (opt.httpOnly) {82+ cookie += '; HttpOnly'83+ }84+85+ if (opt.secure) {86+ cookie += '; Secure'87+ }88+89+ if (opt.sameSite) {90+ cookie += `; SameSite=${opt.sameSite}`91+ }92+93+ return cookie94+}added:deno_dist/middleware/cors/index.test.ts+69 added
1+import { Hono } from '../../hono.ts'2+import { cors } from '../../middleware/cors/index.ts'3+4+describe('CORS by Middleware', () => {5+ const app = new Hono()6+7+ app.use('/api/*', cors())8+ app.use(9+ '/api2/*',10+ cors({11+ origin: 'http://example.com',12+ allowHeaders: ['X-Custom-Header', 'Upgrade-Insecure-Requests'],13+ allowMethods: ['POST', 'GET', 'OPTIONS'],14+ exposeHeaders: ['Content-Length', 'X-Kuma-Revision'],15+ maxAge: 600,16+ credentials: true,17+ })18+ )19+20+ app.all('/api/abc', (c) => {21+ return c.json({ success: true })22+ })23+ app.all('/api2/abc', (c) => {24+ return c.json({ success: true })25+ })26+27+ it('GET default', async () => {28+ const res = await app.request('http://localhost/api/abc')29+30+ expect(res.headers.get('Access-Control-Allow-Origin')).toBe('*')31+ expect(res.headers.get('Vary')).toBeNull()32+ })33+34+ it('Preflight default', async () => {35+ const req = new Request('https://localhost/api/abc', { method: 'OPTIONS' })36+ req.headers.append('Access-Control-Request-Headers', 'X-PINGOTHER, Content-Type')37+ const res = await app.request(req)38+39+ expect(res.status).toBe(204)40+ expect(res.headers.get('Access-Control-Allow-Methods')?.split(',')[0]).toBe('GET')41+ expect(res.headers.get('Access-Control-Allow-Headers')?.split(',')).toEqual([42+ 'X-PINGOTHER',43+ 'Content-Type',44+ ])45+ })46+47+ it('Preflight with options', async () => {48+ const req = new Request('https://localhost/api2/abc', { method: 'OPTIONS' })49+ const res = await app.request(req)50+51+ expect(res.headers.get('Access-Control-Allow-Origin')).toBe('http://example.com')52+ expect(res.headers.get('Vary')?.split(/\s*,\s*/)).toEqual(expect.arrayContaining(['Origin']))53+ expect(res.headers.get('Access-Control-Allow-Headers')?.split(/\s*,\s*/)).toEqual([54+ 'X-Custom-Header',55+ 'Upgrade-Insecure-Requests',56+ ])57+ expect(res.headers.get('Access-Control-Allow-Methods')?.split(/\s*,\s*/)).toEqual([58+ 'POST',59+ 'GET',60+ 'OPTIONS',61+ ])62+ expect(res.headers.get('Access-Control-Expose-Headers')?.split(/\s*,\s*/)).toEqual([63+ 'Content-Length',64+ 'X-Kuma-Revision',65+ ])66+ expect(res.headers.get('Access-Control-Max-Age')).toBe('600')67+ expect(res.headers.get('Access-Control-Allow-Credentials')).toBe('true')68+ })69+})added:deno_dist/middleware/cors/index.ts+81 added
1+import type { Context } from '../../context.ts'2+import type { Next } from '../../hono.ts'3+4+type CORSOptions = {5+ origin: string6+ allowMethods?: string[]7+ allowHeaders?: string[]8+ maxAge?: number9+ credentials?: boolean10+ exposeHeaders?: string[]11+}12+13+export const cors = (options?: CORSOptions) => {14+ const defaults: CORSOptions = {15+ origin: '*',16+ allowMethods: ['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH'],17+ allowHeaders: [],18+ exposeHeaders: [],19+ }20+ const opts = {21+ ...defaults,22+ ...options,23+ }24+25+ return async (c: Context, next: Next) => {26+ await next()27+28+ function set(key: string, value: string) {29+ c.res.headers.append(key, value)30+ }31+32+ set('Access-Control-Allow-Origin', opts.origin)33+34+ // Suppose the server sends a response with an Access-Control-Allow-Origin value with an explicit origin (rather than the "*" wildcard).35+ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Access-Control-Allow-Origin36+ if (opts.origin !== '*') {37+ set('Vary', 'Origin')38+ }39+40+ if (opts.credentials) {41+ set('Access-Control-Allow-Credentials', 'true')42+ }43+44+ if (opts.exposeHeaders?.length) {45+ set('Access-Control-Expose-Headers', opts.exposeHeaders.join(','))46+ }47+48+ if (c.req.method === 'OPTIONS') {49+ // Preflight50+51+ if (opts.maxAge != null) {52+ set('Access-Control-Max-Age', opts.maxAge.toString())53+ }54+55+ if (opts.allowMethods?.length) {56+ set('Access-Control-Allow-Methods', opts.allowMethods.join(','))57+ }58+59+ let headers = opts.allowHeaders60+ if (!headers?.length) {61+ const requestHeaders = c.req.headers.get('Access-Control-Request-Headers')62+ if (requestHeaders) {63+ headers = requestHeaders.split(/\s*,\s*/)64+ }65+ }66+ if (headers?.length) {67+ set('Access-Control-Allow-Headers', headers.join(','))68+ set('Vary', 'Access-Control-Request-Headers')69+ }70+71+ c.res.headers.delete('Content-Length')72+ c.res.headers.delete('Content-Type')73+74+ c.res = new Response(null, {75+ headers: c.res.headers,76+ status: 204,77+ statusText: c.res.statusText,78+ })79+ }80+ }81+}added:deno_dist/middleware/cors/README.md+29 added
1+# CORS Middleware2+3+## Usage4+5+index.js:6+7+```js8+const app = new Hono()9+10+app.use('/api/*', cors())11+app.use(12+ '/api2/*',13+ cors({14+ origin: 'http://example.com',15+ allowHeaders: ['X-Custom-Header', 'Upgrade-Insecure-Requests'],16+ allowMethods: ['POST', 'GET', 'OPTIONS'],17+ exposeHeaders: ['Content-Length', 'X-Kuma-Revision'],18+ maxAge: 600,19+ credentials: true,20+ })21+)22+23+app.all('/api/abc', (c) => {24+ return c.json({ success: true })25+})26+app.all('/api2/abc', (c) => {27+ return c.json({ success: true })28+})29+```added:deno_dist/middleware/etag/index.test.ts+51 added
1+import { Hono } from '../../hono.ts'2+import { etag } from './index.ts'3+4+describe('Etag Middleware', () => {5+ const app = new Hono()6+7+ app.use('/etag/*', etag())8+ app.get('/etag/abc', (c) => {9+ return c.text('Hono is cool')10+ })11+ app.get('/etag/def', (c) => {12+ return c.json({ message: 'Hono is cool' })13+ })14+15+ app.use('/etag-weak/*', etag({ weak: true }))16+ app.get('/etag-weak/abc', (c) => {17+ return c.text('Hono is cool')18+ })19+20+ it('Should return etag header', async () => {21+ let res = await app.request('http://localhost/etag/abc')22+ expect(res.headers.get('ETag')).not.toBeFalsy()23+ expect(res.headers.get('ETag')).toBe('"4e32298b1cb4edc595237405e5b696e105c2399a"')24+25+ res = await app.request('http://localhost/etag/def')26+ expect(res.headers.get('ETag')).not.toBeFalsy()27+ expect(res.headers.get('ETag')).toBe('"c1d44ff03aff1372856c281854f454e2e1d15b7c"')28+ })29+30+ it('Should return etag header - weak', async () => {31+ const res = await app.request('http://localhost/etag-weak/abc')32+ expect(res.headers.get('ETag')).not.toBeFalsy()33+ expect(res.headers.get('ETag')).toBe('W/"4e32298b1cb4edc595237405e5b696e105c2399a"')34+ })35+36+ it('Should return 304 response', async () => {37+ let res = await app.request('http://localhost/etag/abc')38+ expect(res.status).toBe(200)39+ expect(res.headers.get('ETag')).not.toBeFalsy()40+ const etag = res.headers.get('Etag') || ''41+42+ const req = new Request('http://localhost/etag/abc', {43+ headers: {44+ 'If-None-Match': etag,45+ },46+ })47+ res = await app.request(req)48+ expect(res.status).toBe(304)49+ expect(await res.text()).toBe('')50+ })51+})added:deno_dist/middleware/etag/index.ts+35 added
1+import type { Context } from '../../context.ts'2+import type { Next } from '../../hono.ts'3+import { parseBody } from '../../utils/body.ts'4+import { sha1 } from '../../utils/crypto.ts'5+6+type ETagOptions = {7+ weak: boolean8+}9+10+export const etag = (options: ETagOptions = { weak: false }) => {11+ return async (c: Context, next: Next) => {12+ const ifNoneMatch = c.req.header('If-None-Match') || c.req.header('if-none-match')13+14+ await next()15+16+ const res = c.res as Response17+ const clone = res.clone()18+ const body = await parseBody(res)19+ const hash = await sha1(body)20+21+ const etag = options.weak ? `W/"${hash}"` : `"${hash}"`22+23+ if (ifNoneMatch && ifNoneMatch === etag) {24+ await clone.blob() // Force using body25+ c.res = new Response(null, {26+ status: 304,27+ statusText: 'Not Modified',28+ })29+ c.res.headers.delete('Content-Length')30+ } else {31+ c.res = new Response(clone.body, clone)32+ c.res.headers.append('ETag', etag)33+ }34+ }35+}added:deno_dist/middleware/etag/README.md+16 added
1+# ETag Middleware2+3+## Usage4+5+index.js:6+7+```js8+const app = new Hono()9+10+app.use('/etag/*', etag())11+app.get('/etag/abc', (c) => {12+ return c.text('Hono is cool')13+})14+15+app.fire()16+```added:deno_dist/middleware/graphql-server/index.test.ts+573 added
1+import {2+ buildSchema,3+ GraphQLSchema,4+ GraphQLString,5+ GraphQLObjectType,6+ GraphQLNonNull,7+} from 'https://cdn.skypack.dev/graphql@16.4.0?dts'8+import { Hono } from '../../hono.ts'9+import { errorMessages, graphqlServer } from './index.ts'10+11+// Do not show `console.error` messages12+jest.spyOn(console, 'error').mockImplementation()13+14+describe('errorMessages', () => {15+ const messages = errorMessages(['message a', 'message b'])16+ expect(messages).toEqual({17+ errors: [18+ {19+ message: 'message a',20+ },21+ {22+ message: 'message b',23+ },24+ ],25+ })26+})27+28+describe('GraphQL Middleware - Simple way', () => {29+ // Construct a schema, using GraphQL schema language30+ const schema = buildSchema(`31+ type Query {32+ hello: String33+ }34+`)35+36+ // The root provides a resolver function for each API endpoint37+ const rootValue = {38+ hello: () => 'Hello world!',39+ }40+41+ const app = new Hono()42+43+ app.use(44+ '/graphql',45+ graphqlServer({46+ schema,47+ rootValue,48+ })49+ )50+51+ app.all('*', (c) => {52+ c.header('foo', 'bar')53+ return c.text('fallback')54+ })55+56+ it('Should return GraphQL response', async () => {57+ const query = 'query { hello }'58+ const body = {59+ query: query,60+ }61+62+ const res = await app.request('http://localhost/graphql', {63+ method: 'POST',64+ headers: {65+ 'Content-Type': 'application/json',66+ },67+ body: JSON.stringify(body),68+ })69+ expect(res).not.toBeNull()70+ expect(res.status).toBe(200)71+ expect(await res.text()).toBe('{"data":{"hello":"Hello world!"}}')72+ expect(res.headers.get('foo')).toBeNull() // GraphQL Server middleware should be Handler73+ })74+})75+76+const QueryRootType = new GraphQLObjectType({77+ name: 'QueryRoot',78+ fields: {79+ test: {80+ type: GraphQLString,81+ args: {82+ who: { type: GraphQLString },83+ },84+ resolve: (_root, args: { who?: string }) => 'Hello ' + (args.who ?? 'World'),85+ },86+ thrower: {87+ type: GraphQLString,88+ resolve() {89+ throw new Error('Throws!')90+ },91+ },92+ },93+})94+95+const TestSchema = new GraphQLSchema({96+ query: QueryRootType,97+ mutation: new GraphQLObjectType({98+ name: 'MutationRoot',99+ fields: {100+ writeTest: {101+ type: QueryRootType,102+ resolve: () => ({}),103+ },104+ },105+ }),106+})107+108+const urlString = (query?: Record<string, string>): string => {109+ const base = 'http://localhost/graphql'110+ if (!query) return base111+ const queryString = new URLSearchParams(query).toString()112+ return `${base}?${queryString}`113+}114+115+describe('GraphQL Middleware - GET functionality', () => {116+ const app = new Hono()117+ app.use(118+ '/graphql',119+ graphqlServer({120+ schema: TestSchema,121+ })122+ )123+124+ it('Allows GET with variable values', async () => {125+ const query = {126+ query: 'query helloWho($who: String){ test(who: $who) }',127+ variables: JSON.stringify({ who: 'Dolly' }),128+ }129+130+ const res = await app.request(urlString(query), {131+ method: 'GET',132+ })133+ expect(res.status).toBe(200)134+ expect(await res.text()).toBe('{"data":{"test":"Hello Dolly"}}')135+ })136+137+ it('Allows GET with operation name', async () => {138+ const query = {139+ query: `140+ query helloYou { test(who: "You"), ...shared }141+ query helloWorld { test(who: "World"), ...shared }142+ query helloDolly { test(who: "Dolly"), ...shared }143+ fragment shared on QueryRoot {144+ shared: test(who: "Everyone")145+ }146+ `,147+ operationName: 'helloWorld',148+ }149+150+ const res = await app.request(urlString(query), {151+ method: 'GET',152+ })153+ expect(res.status).toBe(200)154+ expect(await res.json()).toEqual({155+ data: {156+ test: 'Hello World',157+ shared: 'Hello Everyone',158+ },159+ })160+ })161+162+ it('Reports validation errors', async () => {163+ const query = { query: '{ test, unknownOne, unknownTwo }' }164+ const res = await app.request(urlString(query), {165+ method: 'GET',166+ })167+ expect(res.status).toBe(400)168+ })169+170+ it('Errors when missing operation name', async () => {171+ const query = {172+ query: `173+ query TestQuery { test }174+ mutation TestMutation { writeTest { test } }175+ `,176+ }177+ const res = await app.request(urlString(query), {178+ method: 'GET',179+ })180+ expect(res.status).toBe(500)181+ })182+183+ it('Errors when sending a mutation via GET', async () => {184+ const query = {185+ query: 'mutation TestMutation { writeTest { test } }',186+ }187+ const res = await app.request(urlString(query), {188+ method: 'GET',189+ })190+ expect(res.status).toBe(405)191+ })192+193+ it('Errors when selecting a mutation within a GET', async () => {194+ const query = {195+ operationName: 'TestMutation',196+ query: `197+ query TestQuery { test }198+ mutation TestMutation { writeTest { test } }199+ `,200+ }201+ const res = await app.request(urlString(query), {202+ method: 'GET',203+ })204+ expect(res.status).toBe(405)205+ })206+207+ it('Allows a mutation to exist within a GET', async () => {208+ const query = {209+ operationName: 'TestQuery',210+ query: `211+ mutation TestMutation { writeTest { test } }212+ query TestQuery { test }213+ `,214+ }215+ const res = await app.request(urlString(query), {216+ method: 'GET',217+ })218+ expect(res.status).toBe(200)219+ expect(await res.json()).toEqual({220+ data: {221+ test: 'Hello World',222+ },223+ })224+ })225+})226+227+describe('GraphQL Middleware - POST functionality', () => {228+ const app = new Hono()229+ app.use(230+ '/graphql',231+ graphqlServer({232+ schema: TestSchema,233+ })234+ )235+236+ it('Allows POST with JSON encoding', async () => {237+ const query = { query: '{test}' }238+239+ const res = await app.request(urlString(), {240+ method: 'POST',241+ headers: {242+ 'Content-Type': 'application/json',243+ },244+ body: JSON.stringify(query),245+ })246+ expect(res.status).toBe(200)247+ expect(await res.text()).toBe('{"data":{"test":"Hello World"}}')248+ })249+250+ it('Allows sending a mutation via POST', async () => {251+ const query = { query: 'mutation TestMutation { writeTest { test } }' }252+ const res = await app.request(urlString(), {253+ method: 'POST',254+ headers: {255+ 'Content-Type': 'application/json',256+ },257+ body: JSON.stringify(query),258+ })259+ expect(res.status).toBe(200)260+ expect(await res.text()).toBe('{"data":{"writeTest":{"test":"Hello World"}}}')261+ })262+263+ it('Allows POST with url encoding', async () => {264+ const query = {265+ query: '{test}',266+ }267+ const res = await app.request(urlString(query), {268+ method: 'POST',269+ })270+ expect(res.status).toBe(200)271+ expect(await res.text()).toBe('{"data":{"test":"Hello World"}}')272+ })273+274+ it('Supports POST JSON query with string variables', async () => {275+ const query = {276+ query: 'query helloWho($who: String){ test(who: $who) }',277+ variables: JSON.stringify({ who: 'Dolly' }),278+ }279+ const res = await app.request(urlString(), {280+ method: 'POST',281+ headers: {282+ 'Content-Type': 'application/json',283+ },284+ body: JSON.stringify(query),285+ })286+ expect(res.status).toBe(200)287+ expect(await res.text()).toBe('{"data":{"test":"Hello Dolly"}}')288+ })289+290+ it('Supports POST url encoded query with string variables', async () => {291+ const searchParams = new URLSearchParams({292+ query: 'query helloWho($who: String){ test(who: $who) }',293+ variables: JSON.stringify({ who: 'Dolly' }),294+ })295+ const res = await app.request(urlString(), {296+ method: 'POST',297+ headers: {298+ 'Content-Type': 'application/x-www-form-urlencoded',299+ },300+ body: searchParams.toString(),301+ })302+ expect(res.status).toBe(200)303+ expect(await res.text()).toBe('{"data":{"test":"Hello Dolly"}}')304+ })305+306+ it('Supports POST JSON query with GET variable values', async () => {307+ const variables = {308+ variables: JSON.stringify({ who: 'Dolly' }),309+ }310+ const query = { query: 'query helloWho($who: String){ test(who: $who) }' }311+ const res = await app.request(urlString(variables), {312+ method: 'POST',313+ headers: {314+ 'Content-Type': 'application/json',315+ },316+ body: JSON.stringify(query),317+ })318+ expect(res.status).toBe(200)319+ expect(await res.text()).toBe('{"data":{"test":"Hello Dolly"}}')320+ })321+322+ it('Supports POST url encoded query with GET variable values', async () => {323+ const searchParams = new URLSearchParams({324+ query: 'query helloWho($who: String){ test(who: $who) }',325+ })326+ const variables = {327+ variables: JSON.stringify({ who: 'Dolly' }),328+ }329+ const res = await app.request(urlString(variables), {330+ method: 'POST',331+ headers: {332+ 'Content-Type': 'application/x-www-form-urlencoded',333+ },334+ body: searchParams.toString(),335+ })336+ expect(res.status).toBe(200)337+ expect(await res.text()).toBe('{"data":{"test":"Hello Dolly"}}')338+ })339+340+ it('Supports POST raw text query with GET variable values', async () => {341+ const variables = {342+ variables: JSON.stringify({ who: 'Dolly' }),343+ }344+ const res = await app.request(urlString(variables), {345+ method: 'POST',346+ headers: {347+ 'Content-Type': 'application/graphql',348+ },349+ body: 'query helloWho($who: String){ test(who: $who) }',350+ })351+ expect(res.status).toBe(200)352+ expect(await res.text()).toBe('{"data":{"test":"Hello Dolly"}}')353+ })354+355+ it('Allows POST with operation name', async () => {356+ const query = {357+ query: `358+ query helloYou { test(who: "You"), ...shared }359+ query helloWorld { test(who: "World"), ...shared }360+ query helloDolly { test(who: "Dolly"), ...shared }361+ fragment shared on QueryRoot {362+ shared: test(who: "Everyone")363+ }364+ `,365+ operationName: 'helloWorld',366+ }367+ const res = await app.request(urlString(), {368+ method: 'POST',369+ headers: {370+ 'Content-Type': 'application/json',371+ },372+ body: JSON.stringify(query),373+ })374+ expect(res.status).toBe(200)375+ expect(await res.json()).toEqual({376+ data: {377+ test: 'Hello World',378+ shared: 'Hello Everyone',379+ },380+ })381+ })382+383+ it('Allows POST with GET operation name', async () => {384+ const res = await app.request(385+ urlString({386+ operationName: 'helloWorld',387+ }),388+ {389+ method: 'POST',390+ headers: {391+ 'Content-Type': 'application/graphql',392+ },393+ body: `394+ query helloYou { test(who: "You"), ...shared }395+ query helloWorld { test(who: "World"), ...shared }396+ query helloDolly { test(who: "Dolly"), ...shared }397+ fragment shared on QueryRoot {398+ shared: test(who: "Everyone")399+ }400+ `,401+ }402+ )403+ expect(res.status).toBe(200)404+ expect(await res.json()).toEqual({405+ data: {406+ test: 'Hello World',407+ shared: 'Hello Everyone',408+ },409+ })410+ })411+})412+413+describe('Pretty printing', () => {414+ it('Supports pretty printing', async () => {415+ const app = new Hono()416+417+ app.use(418+ '/graphql',419+ graphqlServer({420+ schema: TestSchema,421+ pretty: true,422+ })423+ )424+425+ const res = await app.request(urlString({ query: '{test}' }))426+ expect(await res.text()).toEqual(427+ [428+ // Pretty printed JSON429+ '{',430+ ' "data": {',431+ ' "test": "Hello World"',432+ ' }',433+ '}',434+ ].join('\n')435+ )436+ })437+})438+439+describe('Error handling functionality', () => {440+ const app = new Hono()441+ app.use(442+ '/graphql',443+ graphqlServer({444+ schema: TestSchema,445+ })446+ )447+448+ it('Handles query errors from non-null top field errors', async () => {449+ const schema = new GraphQLSchema({450+ query: new GraphQLObjectType({451+ name: 'Query',452+ fields: {453+ test: {454+ type: new GraphQLNonNull(GraphQLString),455+ resolve() {456+ throw new Error('Throws!')457+ },458+ },459+ },460+ }),461+ })462+ const app = new Hono()463+464+ app.use('/graphql', graphqlServer({ schema }))465+466+ const res = await app.request(467+ urlString({468+ query: '{ test }',469+ })470+ )471+472+ expect(res.status).toBe(500)473+ })474+475+ it('Handles syntax errors caught by GraphQL', async () => {476+ const res = await app.request(477+ urlString({478+ query: 'syntax_error',479+ }),480+ {481+ method: 'GET',482+ }483+ )484+485+ expect(res.status).toBe(400)486+ })487+488+ it('Handles errors caused by a lack of query', async () => {489+ const res = await app.request(urlString(), {490+ method: 'GET',491+ })492+493+ expect(res.status).toBe(400)494+ })495+496+ it('Handles invalid JSON bodies', async () => {497+ const res = await app.request(urlString(), {498+ method: 'POST',499+ headers: {500+ 'Content-Type': 'application/json',501+ },502+ body: JSON.stringify([]),503+ })504+505+ expect(res.status).toBe(400)506+ })507+508+ it('Handles incomplete JSON bodies', async () => {509+ const res = await app.request(urlString(), {510+ method: 'POST',511+ headers: {512+ 'Content-Type': 'application/json',513+ },514+ body: '{"query":',515+ })516+ expect(res.status).toBe(400)517+ })518+519+ it('Handles plain POST text', async () => {520+ const res = await app.request(521+ urlString({522+ variables: JSON.stringify({ who: 'Dolly' }),523+ }),524+ {525+ method: 'POST',526+ headers: {527+ 'Content-Type': 'text/plain',528+ },529+ body: 'query helloWho($who: String){ test(who: $who) }',530+ }531+ )532+ expect(res.status).toBe(400)533+ })534+535+ it('Handles poorly formed variables', async () => {536+ const res = await app.request(537+ urlString({538+ variables: 'who:You',539+ query: 'query helloWho($who: String){ test(who: $who) }',540+ }),541+ {542+ method: 'GET',543+ }544+ )545+ expect(res.status).toBe(400)546+ })547+548+ it('Handles invalid variables', async () => {549+ const res = await app.request(urlString(), {550+ method: 'POST',551+ headers: {552+ 'Content-Type': 'application/json',553+ },554+ body: JSON.stringify({555+ query: 'query helloWho($who: String){ test(who: $who) }',556+ variables: { who: ['John', 'Jane'] },557+ }),558+ })559+ expect(res.status).toBe(500)560+ })561+562+ it('Handles unsupported HTTP methods', async () => {563+ const res = await app.request(urlString({ query: '{test}' }), {564+ method: 'PUT',565+ })566+567+ expect(res.status).toBe(405)568+ expect(res.headers.get('allow')).toBe('GET, POST')569+ expect(await res.json()).toEqual({570+ errors: [{ message: 'GraphQL only supports GET and POST requests.' }],571+ })572+ })573+})added:deno_dist/middleware/graphql-server/index.ts+238 added
1+// Based on the code in the `express-graphql` package.2+// https://github.com/graphql/express-graphql/blob/main/src/index.ts3+4+import {5+ Source,6+ parse,7+ execute,8+ validateSchema,9+ validate,10+ specifiedRules,11+ getOperationAST,12+ GraphQLError,13+} from 'https://cdn.skypack.dev/graphql@16.4.0?dts'14+15+import type {16+ GraphQLSchema,17+ DocumentNode,18+ ValidationRule,19+ FormattedExecutionResult,20+ GraphQLFormattedError,21+} from 'https://cdn.skypack.dev/graphql@16.4.0?dts'22+23+import type { Context } from '../../context.ts'24+import type { Next } from '../../hono.ts'25+import { parseBody } from './parse-body.ts'26+27+type Options = {28+ schema: GraphQLSchema29+ rootValue?: unknown30+ pretty?: boolean31+ validationRules?: ReadonlyArray<ValidationRule>32+ // graphiql?: boolean33+}34+35+export const graphqlServer = (options: Options) => {36+ const schema = options.schema37+ const rootValue = options.rootValue38+ const pretty = options.pretty ?? false39+ const validationRules = options.validationRules ?? []40+ // const showGraphiQL = options.graphiql ?? false41+42+ return async (c: Context, next: Next) => {43+ // GraphQL HTTP only supports GET and POST methods.44+ if (c.req.method !== 'GET' && c.req.method !== 'POST') {45+ return c.json(errorMessages(['GraphQL only supports GET and POST requests.']), 405, {46+ Allow: 'GET, POST',47+ })48+ }49+50+ let params: GraphQLParams51+ try {52+ params = await getGraphQLParams(c.req)53+ } catch (e) {54+ if (e instanceof Error) {55+ console.error(`${e.stack || e.message}`)56+ return c.json(errorMessages([e.message], [e]), 400)57+ }58+ throw e59+ }60+61+ const { query, variables, operationName } = params62+63+ if (query == null) {64+ return c.json(errorMessages(['Must provide query string.']), 400)65+ }66+67+ const schemaValidationErrors = validateSchema(schema)68+ if (schemaValidationErrors.length > 0) {69+ // Return 500: Internal Server Error if invalid schema.70+ return c.json(71+ errorMessages(['GraphQL schema validation error.'], schemaValidationErrors),72+ 50073+ )74+ }75+76+ let documentAST: DocumentNode77+ try {78+ documentAST = parse(new Source(query, 'GraphQL request'))79+ } catch (syntaxError: unknown) {80+ // Return 400: Bad Request if any syntax errors errors exist.81+ if (syntaxError instanceof Error) {82+ console.error(`${syntaxError.stack || syntaxError.message}`)83+ const e = new GraphQLError(syntaxError.message, {84+ originalError: syntaxError,85+ })86+ return c.json(errorMessages(['GraphQL syntax error.'], [e]), 400)87+ }88+ throw syntaxError89+ }90+91+ // Validate AST, reporting any errors.92+ const validationErrors = validate(schema, documentAST, [...specifiedRules, ...validationRules])93+94+ if (validationErrors.length > 0) {95+ // Return 400: Bad Request if any validation errors exist.96+ return c.json(errorMessages(['GraphQL validation error.'], validationErrors), 400)97+ }98+99+ if (c.req.method === 'GET') {100+ // Determine if this GET request will perform a non-query.101+ const operationAST = getOperationAST(documentAST, operationName)102+ if (operationAST && operationAST.operation !== 'query') {103+ /*104+ Now , does not support GraphiQL105+ if (showGraphiQL) {106+ //return respondWithGraphiQL(response, graphiqlOptions, params)107+ }108+ */109+110+ // Otherwise, report a 405: Method Not Allowed error.111+ return c.json(112+ errorMessages([113+ `Can only perform a ${operationAST.operation} operation from a POST request.`,114+ ]),115+ 405,116+ { Allow: 'POST' }117+ )118+ }119+ }120+121+ let result: FormattedExecutionResult122+123+ try {124+ result = await execute({125+ schema,126+ document: documentAST,127+ rootValue,128+ variableValues: variables,129+ operationName: operationName,130+ })131+ } catch (contextError: unknown) {132+ if (contextError instanceof Error) {133+ console.error(`${contextError.stack || contextError.message}`)134+ const e = new GraphQLError(contextError.message, {135+ originalError: contextError,136+ nodes: documentAST,137+ })138+ // Return 400: Bad Request if any execution context errors exist.139+ return c.json(errorMessages(['GraphQL execution context error.'], [e]), 400)140+ }141+ throw contextError142+ }143+144+ if (!result.data) {145+ if (result.errors) {146+ return c.json(errorMessages([result.errors.toString()], result.errors), 500)147+ }148+ }149+150+ /*151+ Now, does not support GraphiQL152+ if (showGraphiQL) {153+ }154+ */155+156+ if (pretty) {157+ const payload = JSON.stringify(result, null, pretty ? 2 : 0)158+ return c.text(payload, 200, {159+ 'Content-Type': 'application/json',160+ })161+ } else {162+ return c.json(result)163+ }164+165+ await next() // XXX166+ }167+}168+169+export interface GraphQLParams {170+ query: string | null171+ variables: { readonly [name: string]: unknown } | null172+ operationName: string | null173+ raw: boolean174+}175+176+export const getGraphQLParams = async (request: Request): Promise<GraphQLParams> => {177+ const urlData = new URLSearchParams(request.url.split('?')[1])178+ const bodyData = await parseBody(request)179+180+ // GraphQL Query string.181+ let query = urlData.get('query') ?? (bodyData.query as string | null)182+183+ if (typeof query !== 'string') {184+ query = null185+ }186+187+ // Parse the variables if needed.188+ let variables = (urlData.get('variables') ?? bodyData.variables) as {189+ readonly [name: string]: unknown190+ } | null191+ if (typeof variables === 'string') {192+ try {193+ variables = JSON.parse(variables)194+ } catch {195+ throw Error('Variables are invalid JSON.')196+ }197+ } else if (typeof variables !== 'object') {198+ variables = null199+ }200+201+ // Name of GraphQL operation to execute.202+ let operationName = urlData.get('operationName') ?? (bodyData.operationName as string | null)203+ if (typeof operationName !== 'string') {204+ operationName = null205+ }206+207+ const raw = urlData.get('raw') != null || bodyData.raw !== undefined208+209+ const params: GraphQLParams = {210+ query: query,211+ variables: variables,212+ operationName: operationName,213+ raw: raw,214+ }215+216+ return params217+}218+219+export const errorMessages = (220+ messages: string[],221+ graphqlErrors?: readonly GraphQLError[] | readonly GraphQLFormattedError[]222+) => {223+ if (graphqlErrors) {224+ return {225+ errors: graphqlErrors,226+ }227+ }228+229+ return {230+ errors: messages.map((message) => {231+ return {232+ message: message,233+ }234+ }),235+ }236+}237+238+// export const graphiQLResponse = () => {}added:deno_dist/middleware/graphql-server/parse-body.test.ts+61 added
1+import { parseBody } from './parse-body.ts'2+3+describe('parseBody', () => {4+ it('Should return a blank JSON object', async () => {5+ const req = new Request('http://localhost/graphql')6+ const res = await parseBody(req)7+ expect(res).toEqual({})8+ })9+10+ it('With Content-Type: application/graphql', async () => {11+ const req = new Request('http://localhost/graphql', {12+ method: 'POST',13+ headers: {14+ 'Content-Type': 'application/graphql',15+ },16+ body: 'query { hello }',17+ })18+ const res = await parseBody(req)19+ expect(res).toEqual({ query: 'query { hello }' })20+ })21+22+ it('With Content-Type: application/json', async () => {23+ const variables = JSON.stringify({ who: 'Dolly' })24+ const req = new Request('http://localhost/graphql', {25+ method: 'POST',26+ headers: {27+ 'Content-Type': 'application/json',28+ },29+ body: JSON.stringify({30+ query: 'query { hello }',31+ variables: variables,32+ }),33+ })34+ const res = await parseBody(req)35+ expect(res).toEqual({36+ query: 'query { hello }',37+ variables: variables,38+ })39+ })40+41+ it('With Content-Type: application/x-www-form-urlencoded', async () => {42+ const variables = JSON.stringify({ who: 'Dolly' })43+44+ const searchParams = new URLSearchParams()45+ searchParams.append('query', 'query { hello }')46+ searchParams.append('variables', variables)47+ const req = new Request('http://localhost/graphql', {48+ method: 'POST',49+ headers: {50+ 'Content-Type': 'application/x-www-form-urlencoded',51+ },52+ body: searchParams.toString(),53+ })54+ const res = await parseBody(req)55+56+ expect(res).toEqual({57+ query: 'query { hello }',58+ variables: variables,59+ })60+ })61+})added:deno_dist/middleware/graphql-server/parse-body.ts+29 added
1+export async function parseBody(req: Request): Promise<Record<string, unknown>> {2+ const contentType = req.headers.get('content-type')3+4+ switch (contentType) {5+ case 'application/graphql':6+ return { query: await req.text() }7+ case 'application/json':8+ try {9+ return await req.json()10+ } catch (e) {11+ if (e instanceof Error) {12+ console.error(`${e.stack || e.message}`)13+ }14+ throw Error(`POST body sent invalid JSON: ${e}`)15+ }16+ case 'application/x-www-form-urlencoded':17+ return parseFormURL(req)18+ }19+20+ return {}21+}22+23+const parseFormURL = async (req: Request) => {24+ const text = await req.text()25+ const searchParams = new URLSearchParams(text)26+ const res: { [params: string]: string } = {}27+ searchParams.forEach((v, k) => (res[k] = v))28+ return res29+}added:deno_dist/middleware/graphql-server/README.md+47 added
1+# GraphQL Server Middleware2+3+## Requirements4+5+This middleware depends on [GraphQL.js](https://www.npmjs.com/package/graphql).6+7+```plain8+npm i graphql9+```10+11+or12+13+```plain14+yarn add graphql15+```16+17+## Usage18+19+index.js:20+21+```js22+import { Hono } from 'hono'23+import { graphqlServer } from 'hono/graphql-server'24+import { buildSchema } from 'graphql'25+26+export const app = new Hono()27+28+const schema = buildSchema(`29+type Query {30+ hello: String31+}32+`)33+34+const rootValue = {35+ hello: () => 'Hello Hono!',36+}37+38+app.use(39+ '/graphql',40+ graphqlServer({41+ schema,42+ rootValue,43+ })44+)45+46+app.fire()47+```added:deno_dist/middleware/html/index.test.ts+41 added
1+import { html, raw } from './index.ts'2+3+describe('Tagged Template Literals', () => {4+ it('Should escape special characters', () => {5+ const name = 'John "Johnny" Smith'6+ // eslint-disable-next-line quotes7+ expect(html`<p>I'm ${name}.</p>`.toString()).toBe("<p>I'm John "Johnny" Smith.</p>")8+ })9+10+ describe('Booleans, Null, and Undefined Are Ignored', () => {11+ it.each([true, false, undefined, null])('%s', (item) => {12+ expect(html`${item}`.toString()).toBe('')13+ })14+15+ it('falsy value', () => {16+ expect(html`${0}`.toString()).toBe('0')17+ })18+ })19+20+ it('Should call $array.flat(Infinity)', () => {21+ const values = [22+ 'Name:',23+ ['John "Johnny" Smith', undefined, null],24+ ' Contact:',25+ [html`<a href="http://example.com/">My Website</a>`],26+ ]27+ expect(html`<p>${values}</p>`.toString()).toBe(28+ '<p>Name:John "Johnny" Smith Contact:<a href="http://example.com/">My Website</a></p>'29+ )30+ })31+})32+33+describe('raw', () => {34+ it('Should be marked as escaped.', () => {35+ const name = 'John "Johnny" Smith'36+ expect(html`<p>I'm ${raw(name)}.</p>`.toString()).toBe(37+ // eslint-disable-next-line quotes38+ "<p>I'm John "Johnny" Smith.</p>"39+ )40+ })41+})added:deno_dist/middleware/html/index.ts+33 added
1+import { escape } from '../../utils/html.ts'2+3+export type HtmlEscapedString = string & { isEscaped: true }4+5+export const raw = (value: any): HtmlEscapedString => {6+ const escapedString = new String(value) as HtmlEscapedString7+ escapedString.isEscaped = true8+9+ return escapedString10+}11+12+export const html = (strings: TemplateStringsArray, ...values: any[]): HtmlEscapedString => {13+ let result = ''14+15+ for (let i = 0, len = strings.length - 1; i < len; i++) {16+ result += strings[i]17+18+ const children = values[i] instanceof Array ? values[i].flat(Infinity) : [values[i]]19+ for (let i = 0, len = children.length; i < len; i++) {20+ const child = children[i]21+ if (typeof child === 'boolean' || child === null || child === undefined) {22+ continue23+ } else if (typeof child === 'object' && (child as any).isEscaped) {24+ result += child25+ } else {26+ result += escape(child.toString())27+ }28+ }29+ }30+ result += strings[strings.length - 1]31+32+ return raw(result)33+}added:deno_dist/middleware/html/README.md+153 added
1+# html Middleware2+3+html Middleware provides `html` method for building HTML.4+5+## Usage6+7+index.ts:8+9+```ts10+import { Hono } from 'hono'11+import { html } from 'hono/html'12+13+const app = new Hono()14+15+app.get('/:username', (c) => {16+ const { username } = c.req.param()17+ return c.html(18+ html`<!DOCTYPE html>19+ <h1>Hello! ${username}!</h1>`20+ )21+})22+23+app.fire()24+```25+26+### Insert snippet into JSX27+28+```typescript29+const snippet = html`30+ <script async src="https://www.googletagmanager.com/gtag/js?id=MEASUREMENT_ID"></script>31+ <script>32+ window.dataLayer = window.dataLayer || []33+ function gtag() {34+ dataLayer.push(arguments)35+ }36+ gtag('js', new Date())37+38+ gtag('config', 'MEASUREMENT_ID')39+ </script>40+`41+42+app.get('/', (c) => {43+ return c.render(44+ <html>45+ <head>46+ <title>Test Site</title>47+ {snippet}48+ </head>49+ <body>Hello!</body>50+ </html>51+ )52+})53+```54+55+### Insert inline script into JSX56+57+```typescript58+app.get('/', (c) => {59+ return c.render(60+ <html>61+ <head>62+ <title>Test Site</title>63+ {html`64+ <script>65+ // No need to use dangerouslySetInnerHTML. If you write it here, it will not be escaped.66+ </script>67+ `}68+ </head>69+ <body>Hello!</body>70+ </html>71+ )72+})73+```74+75+### Act as functional component76+77+Since `html` returns an HtmlEscapedString, it can act as a fully functional component without using JSX.78+79+#### Use `html` to speed up the process instead of `memo`80+81+```typescript82+const Footer = () => html`83+ <footer>84+ <address>My Address...</address>85+ </footer>86+`87+```88+89+### Receives props and embeds values90+91+```typescript92+interface SiteData {93+ title: string94+ description: string95+ image: string96+ children?: any97+}98+const Layout = (props: SiteData) => html`99+<html>100+<head>101+ <meta charset="UTF-8">102+ <title>${props.title}</title>103+ <meta name="description" content="${props.description}">104+ <head prefix="og: http://ogp.me/ns#">105+ <meta property="og:type" content="article">106+ <!-- More elements slow down JSX, but not template literals. -->107+ <meta property="og:title" content="${props.title}">108+ <meta property="og:image" content="${props.image}">109+</head>110+<body>111+ ${props.children}112+</body>113+</html>114+`115+116+const Content = (props: { siteData: SiteData; name: string }) => (117+ <Layout {...props.siteData}>118+ <h1>Hello {props.name}</h1>119+ </Layout>120+)121+122+app.get('/', (c) => {123+ const props = {124+ name: 'World',125+ siteData: {126+ title: 'Hello <> World',127+ description: 'This is a description',128+ image: 'https://example.com/image.png',129+ },130+ }131+ return c.render(<Content {...props} />)132+})133+```134+135+## raw136+137+Using `raw`, the content will be rendered as is. You have to escape these strings by yourself.138+139+```ts140+import { html, raw } from 'hono/html'141+142+app.get('/', (c) => {143+ const name = 'John "Johnny" Smith'144+ return c.html(html`<p>I'm ${raw(name)}.</p>`)145+})146+```147+148+## Tips149+150+Thanks to these libraries, Visual Studio Code and vim also interprets template literals as HTML, allowing syntax highlighting and formatting to be applied.151+152+- <https://marketplace.visualstudio.com/items?itemName=bierner.lit-html>153+- <https://github.com/MaxMEllon/vim-jsx-pretty>added:deno_dist/middleware/jsx/index.test.tsx+183 added
1+import { Hono } from '../../hono.ts'2+import { jsx, memo, Fragment } from './index.ts'3+4+describe('JSX middleware', () => {5+ const app = new Hono()6+7+ it('Should render HTML strings', async () => {8+ app.get('/', (c) => {9+ return c.html(<h1>Hello</h1>)10+ })11+ const res = await app.request('http://localhost/')12+ expect(res.status).toBe(200)13+ expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')14+ expect(await res.text()).toBe('<h1>Hello</h1>')15+ })16+})17+18+describe('render to string', () => {19+ it('Nested array', () => {20+ const template = (21+ <p>22+ {[[['a']], [['b']]].map((item1) =>23+ item1.map((item2) => item2.map((item3) => <span>{item3}</span>))24+ )}25+ </p>26+ )27+ expect(template.toString()).toBe('<p><span>a</span><span>b</span></p>')28+ })29+30+ it('Props value is null', () => {31+ const template = <span data-hello={null}>Hello</span>32+ expect(template.toString()).toBe('<span>Hello</span>')33+ })34+35+ it('Props value is undefined', () => {36+ const template = <span data-hello={undefined}>Hello</span>37+ expect(template.toString()).toBe('<span>Hello</span>')38+ })39+40+ describe('dangerouslySetInnerHTML', () => {41+ it('Should render dangerouslySetInnerHTML', () => {42+ const template = <span dangerouslySetInnerHTML={{ __html: '" is allowed here' }}></span>43+ expect(template.toString()).toBe('<span>" is allowed here</span>')44+ })45+46+ it('Should get an error if both dangerouslySetInnerHTML and children are specified', () => {47+ expect(() => (48+ <span dangerouslySetInnerHTML={{ __html: '" is allowed here' }}>Hello</span>49+ )).toThrow()50+ })51+ })52+53+ // https://en.reactjs.org/docs/jsx-in-depth.html#booleans-null-and-undefined-are-ignored54+ describe('Booleans, Null, and Undefined Are Ignored', () => {55+ it.each([true, false, undefined, null])('%s', (item) => {56+ expect((<span>{item}</span>).toString()).toBe('<span></span>')57+ })58+59+ it('falsy value', () => {60+ const template = <span>{0}</span>61+ expect(template.toString()).toBe('<span>0</span>')62+ })63+ })64+65+ // https://en.reactjs.org/docs/jsx-in-depth.html#props-default-to-true66+ describe('Props Default to “True”', () => {67+ it('default prop value', () => {68+ const template = <span data-hello>Hello</span>69+ expect(template.toString()).toBe('<span data-hello="true">Hello</span>')70+ })71+ })72+73+ // https://en.reactjs.org/docs/jsx-in-depth.html#functions-as-children74+ describe('Functions as Children', () => {75+ it('Function', () => {76+ function Repeat(props: any) {77+ const items = []78+ for (let i = 0; i < props.numTimes; i++) {79+ items.push((props.children as Function)(i))80+ }81+ return <div>{items}</div>82+ }83+84+ function ListOfTenThings() {85+ return (86+ <Repeat numTimes={10}>87+ {(index: string) => <div key={index}>This is item {index} in the list</div>}88+ </Repeat>89+ )90+ }91+92+ const template = <ListOfTenThings />93+ expect(template.toString()).toBe(94+ '<div><div key="0">This is item 0 in the list</div><div key="1">This is item 1 in the list</div><div key="2">This is item 2 in the list</div><div key="3">This is item 3 in the list</div><div key="4">This is item 4 in the list</div><div key="5">This is item 5 in the list</div><div key="6">This is item 6 in the list</div><div key="7">This is item 7 in the list</div><div key="8">This is item 8 in the list</div><div key="9">This is item 9 in the list</div></div>'95+ )96+ })97+ })98+})99+100+describe('memo', () => {101+ it('memoized', () => {102+ let counter = 0103+ const Header = memo(() => <title>Test Site {counter}</title>)104+ const Body = () => <span>{counter}</span>105+106+ let template = (107+ <html>108+ <head>109+ <Header />110+ </head>111+ <body>112+ <Body />113+ </body>114+ </html>115+ )116+ expect(template.toString()).toBe(117+ '<html><head><title>Test Site 0</title></head><body><span>0</span></body></html>'118+ )119+120+ counter++121+ template = (122+ <html>123+ <head>124+ <Header />125+ </head>126+ <body>127+ <Body />128+ </body>129+ </html>130+ )131+ expect(template.toString()).toBe(132+ '<html><head><title>Test Site 0</title></head><body><span>1</span></body></html>'133+ )134+ })135+136+ it('props are updated', () => {137+ const Body = memo(({ counter }: { counter: number }) => <span>{counter}</span>)138+139+ let template = <Body counter={0} />140+ expect(template.toString()).toBe('<span>0</span>')141+142+ template = <Body counter={1} />143+ expect(template.toString()).toBe('<span>1</span>')144+ })145+146+ it('custom propsAreEqual', () => {147+ const Body = memo(148+ ({ counter }: { counter: number; refresh?: boolean }) => <span>{counter}</span>,149+ (_, nextProps) => (typeof nextProps.refresh == 'undefined' ? true : !nextProps.refresh)150+ )151+152+ let template = <Body counter={0} />153+ expect(template.toString()).toBe('<span>0</span>')154+155+ template = <Body counter={1} />156+ expect(template.toString()).toBe('<span>0</span>')157+158+ template = <Body counter={2} refresh={true} />159+ expect(template.toString()).toBe('<span>2</span>')160+ })161+})162+163+describe('Fragment', () => {164+ it('Should render children', () => {165+ const template = (166+ <>167+ <p>1</p>168+ <p>2</p>169+ </>170+ )171+ expect(template.toString()).toBe('<p>1</p><p>2</p>')172+ })173+174+ it('Should render nothing for empty Fragment', () => {175+ const template = <></>176+ expect(template.toString()).toBe('')177+ })178+179+ it('Should render nothing for undefined', () => {180+ const template = <>{undefined}</>181+ expect(template.toString()).toBe('')182+ })183+})added:deno_dist/middleware/jsx/index.ts+108 added
1+import { escape } from '../../utils/html.ts'2+import type { HtmlEscapedString } from '../../utils/html.ts'3+4+declare global {5+ // eslint-disable-next-line @typescript-eslint/no-namespace6+ namespace jsx.JSX {7+ interface IntrinsicElements {8+ [tagName: string]: Record<string, any>9+ }10+ }11+}12+13+export const jsx = (14+ tag: string | Function,15+ props: Record<string, any>,16+ ...children: (string | HtmlEscapedString)[]17+): HtmlEscapedString => {18+ if (typeof tag === 'function') {19+ return tag.call(null, { ...props, children: children.length <= 1 ? children[0] : children })20+ }21+22+ let result = tag !== '' ? `<${tag}` : ''23+24+ const propsKeys = Object.keys(props || {})25+ for (let i = 0, len = propsKeys.length; i < len; i++) {26+ const v = props[propsKeys[i]]27+ if (propsKeys[i] === 'dangerouslySetInnerHTML') {28+ if (children.length > 0) {29+ throw 'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'30+ }31+32+ const escapedString = new String(v.__html) as HtmlEscapedString33+ escapedString.isEscaped = true34+ children = [escapedString]35+ continue36+ } else if (v === null || v === undefined) {37+ continue38+ }39+40+ result += ` ${propsKeys[i]}="${escape(v.toString())}"`41+ }42+43+ if (tag !== '') {44+ result += '>'45+ }46+47+ const flattenChildren = children.flat(Infinity)48+ for (let i = 0, len = flattenChildren.length; i < len; i++) {49+ const child = flattenChildren[i]50+ if (typeof child === 'boolean' || child === null || child === undefined) {51+ continue52+ } else if (typeof child === 'object' && (child as any).isEscaped) {53+ result += child54+ } else {55+ result += escape(child.toString())56+ }57+ }58+59+ if (tag !== '') {60+ result += `</${tag}>`61+ }62+63+ const escapedString = new String(result) as HtmlEscapedString64+ escapedString.isEscaped = true65+66+ return escapedString67+}68+69+type FC<T = Record<string, any>> = (props: T) => HtmlEscapedString70+71+const shallowEqual = (a: Record<string, any>, b: Record<string, any>): boolean => {72+ if (a === b) {73+ return true74+ }75+76+ const aKeys = Object.keys(a)77+ const bKeys = Object.keys(b)78+ if (aKeys.length !== bKeys.length) {79+ return false80+ }81+82+ for (let i = 0, len = aKeys.length; i < len; i++) {83+ if (a[aKeys[i]] !== b[aKeys[i]]) {84+ return false85+ }86+ }87+88+ return true89+}90+91+export const memo = <T>(92+ component: FC<T>,93+ propsAreEqual: (prevProps: Readonly<T>, nextProps: Readonly<T>) => boolean = shallowEqual94+): FC<T> => {95+ let computed = undefined96+ let prevProps: T | undefined = undefined97+ return ((props: T): HtmlEscapedString => {98+ if (prevProps && !propsAreEqual(prevProps, props)) {99+ computed = undefined100+ }101+ prevProps = props102+ return (computed ||= component(props))103+ }) as FC<T>104+}105+106+export const Fragment = (props: { key?: string; children?: any }): HtmlEscapedString => {107+ return jsx('', {}, ...(props.children || []))108+}added:deno_dist/middleware/jsx/README.md+170 added
1+# JSX Middleware2+3+JSX Middleware enable rendering HTML with JSX syntax.4+It's just for Sever-Side-Rendering. No virtual DOM.5+This middleware is only for writing with TypeScript.6+7+## Settings8+9+tsconfig.json:10+11+```json12+{13+ "compilerOptions": {14+ "jsx": "react",15+ "jsxFactory": "jsx",16+ "jsxFragmentFactory": "Fragment"17+ }18+}19+```20+21+## Usage22+23+index.tsx:24+25+```tsx26+import { Hono } from 'hono'27+import { jsx } from 'hono/jsx'28+29+const app = new Hono()30+31+const Layout = (props: { children?: string }) => {32+ return (33+ <html>34+ <body>{props.children}</body>35+ </html>36+ )37+}38+39+const Top = (props: { messages: string[] }) => {40+ return (41+ <Layout>42+ <h1>Hello Hono!</h1>43+ <ul>44+ {props.messages.map((message) => {45+ return <li>{message}!!</li>46+ })}47+ </ul>48+ </Layout>49+ )50+}51+52+app.get('/', (c) => {53+ const messages = ['Good Morning', 'Good Evening', 'Good Night']54+ return c.html(<Top messages={messages} />)55+})56+57+app.fire()58+```59+60+## dangerouslySetInnerHTML61+62+`dangerouslySetInnerHTML` allows you to set HTML directly.63+64+```tsx65+app.get('/foo', (c) => {66+ const inner = { __html: 'JSX · SSR' }67+ const Div = <div dangerouslySetInnerHTML={inner} />68+})69+```70+71+## memo72+73+You can memorize calculated strings of the component with `memo`.74+75+```tsx76+import { jsx, memo } from 'hono/jsx'77+78+const Header = memo(() => <header>Welcome to Hono</header>)79+const Footer = memo(() => <footer>Powered by Hono</footer>)80+const Layout = (81+ <div>82+ <Header />83+ <p>Hono is cool!</p>84+ <Footer />85+ </div>86+)87+```88+89+## Fragment90+91+```tsx92+import { jsx, Fragment } from 'hono/jsx'93+94+const List = () => (95+ <Fragment>96+ <p>first child</p>97+ <p>second child</p>98+ <p>third child</p>99+ </Fragment>100+)101+```102+103+## With html Middleware104+105+It's powerful to use JSX middleware with html middleware.106+For more information, see [html middleware docs](https://github.com/honojs/hono/tree/master/src/middleware/html).107+108+```tsx109+import { Hono } from 'hono'110+import { html } from 'hono/html'111+import { jsx } from 'hono/jsx'112+113+const app = new Hono()114+115+interface SiteData {116+ title: string117+ children?: any118+}119+120+const Layout = (props: SiteData) => html`<!DOCTYPE html>121+ <html>122+ <head>123+ <title>${props.title}</title>124+ </head>125+ <body>126+ ${props.children}127+ </body>128+ </html>`129+130+const Content = (props: { siteData: SiteData; name: string }) => (131+ <Layout {...props.siteData}>132+ <h1>Hello {props.name}</h1>133+ </Layout>134+)135+136+app.get('/:name', (c) => {137+ const { name } = c.req.param()138+ const props = {139+ name: name,140+ siteData: {141+ title: 'JSX with html sample',142+ },143+ }144+ return c.html(<Content {...props} />)145+})146+147+app.fire()148+```149+150+## Tips for Cloudflare Workers151+152+It's useful to use Miniflare's`live-reload` option for developing.153+154+package.json:155+156+```json157+{158+ "scripts": {159+ "build": "esbuild --bundle --outdir=dist ./src/index.tsx",160+ "dev": "miniflare --live-reload --debug"161+ }162+}163+```164+165+wrangler.toml:166+167+```toml168+[build]169+command = "yarn build"170+```added:deno_dist/middleware/jwt/index.test.ts+95 added
1+import { Hono } from '../../hono.ts'2+import { jwt } from './index.ts'3+4+describe('Jwt Auth by Middleware', () => {5+ const crypto = global.crypto6+ beforeAll(() => {7+ global.crypto = require('crypto').webcrypto8+ })9+ afterAll(() => {10+ global.crypto = crypto11+ })12+13+ const app = new Hono()14+15+ app.use('/*', async (c, next) => {16+ await next()17+ c.header('x-foo', c.get('x-foo') || '')18+ })19+20+ app.use('/auth/*', jwt({ secret: 'a-secret' }))21+ app.use('/auth-unicode/*', jwt({ secret: 'a-secret' }))22+23+ app.get('/auth/*', (c) => {24+ c.set('x-foo', 'bar')25+ return new Response('auth')26+ })27+ app.get('/auth-unicode/*', (c) => {28+ c.set('x-foo', 'bar')29+ return new Response('auth')30+ })31+32+ it('Should not authorize', async () => {33+ const req = new Request('http://localhost/auth/a')34+ const res = await app.request(req)35+ expect(res).not.toBeNull()36+ expect(res.status).toBe(401)37+ expect(await res.text()).toBe('Unauthorized')38+ expect(res.headers.get('x-foo')).toBeFalsy()39+ })40+41+ it('Should authorize', async () => {42+ const credential =43+ 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'44+ const req = new Request('http://localhost/auth/a')45+ req.headers.set('Authorization', `Bearer ${credential}`)46+ const res = await app.request(req)47+ expect(res).not.toBeNull()48+ expect(res.status).toBe(200)49+ expect(await res.text()).toBe('auth')50+ expect(res.headers.get('x-foo')).toBe('bar')51+ })52+53+ it('Should authorize Unicode', async () => {54+ const credential =55+ 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'56+57+ const req = new Request('http://localhost/auth-unicode/a')58+ req.headers.set('Authorization', `Basic ${credential}`)59+ const res = await app.request(req)60+ expect(res).not.toBeNull()61+ expect(res.status).toBe(200)62+ expect(await res.text()).toBe('auth')63+ expect(res.headers.get('x-foo')).toBe('bar')64+ })65+66+ it('Should not authorize Unicode', async () => {67+ const invalidToken =68+ 'ssyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'69+70+ const url = 'http://localhost/auth-unicode/a'71+ const req = new Request(url)72+ req.headers.set('Authorization', `Basic ${invalidToken}`)73+ const res = await app.request(req)74+ expect(res).not.toBeNull()75+ expect(res.status).toBe(401)76+ expect(res.headers.get('www-authenticate')).toEqual(77+ `Bearer realm="${url}",error="invalid_token",error_description="token verification failure"`78+ )79+ expect(res.headers.get('x-foo')).toBeFalsy()80+ })81+82+ it('Should not authorize', async () => {83+ const invalid_token = 'invalid token'84+ const url = 'http://localhost/auth/a'85+ const req = new Request(url)86+ req.headers.set('Authorization', `Bearer ${invalid_token}`)87+ const res = await app.request(req)88+ expect(res).not.toBeNull()89+ expect(res.status).toBe(401)90+ expect(res.headers.get('www-authenticate')).toEqual(91+ `Bearer realm="${url}",error="invalid_request",error_description="no authorization included in request"`92+ )93+ expect(res.headers.get('x-foo')).toBeFalsy()94+ })95+})added:deno_dist/middleware/jwt/index.ts+55 added
1+import type { Context } from '../../context.ts'2+import type { Next } from '../../hono.ts'3+import { Jwt } from '../../utils/jwt/index.ts'4+import type { AlgorithmTypes } from '../../utils/jwt/types.ts'5+6+export const jwt = (options: { secret: string; alg?: string }) => {7+ if (!options) {8+ throw new Error('JWT auth middleware requires options for "secret')9+ }10+11+ return async (ctx: Context, next: Next) => {12+ const credentials = ctx.req.headers.get('Authorization')13+14+ if (!credentials) {15+ ctx.res = new Response('Unauthorized', {16+ status: 401,17+ headers: {18+ 'WWW-Authenticate': `Bearer realm="${ctx.req.url}",error="invalid_request",error_description="no authorization included in request"`,19+ },20+ })21+ return22+ }23+24+ const parts = credentials.split(/\s+/)25+ if (parts.length !== 2) {26+ ctx.res = new Response('Unauthorized', {27+ status: 401,28+ headers: {29+ 'WWW-Authenticate': `Bearer realm="${ctx.req.url}",error="invalid_request",error_description="no authorization included in request"`,30+ },31+ })32+ return33+ }34+35+ let authorized = false36+ let msg = ''37+ try {38+ authorized = await Jwt.verify(parts[1], options.secret, options.alg as AlgorithmTypes)39+ } catch (e) {40+ msg = `${e}`41+ }42+ if (!authorized) {43+ ctx.res = new Response('Unauthorized', {44+ status: 401,45+ statusText: msg,46+ headers: {47+ 'WWW-Authenticate': `Bearer realm="${ctx.req.url}",error="invalid_token",error_description="token verification failure"`,48+ },49+ })50+ return51+ }52+53+ await next()54+ }55+}added:deno_dist/middleware/jwt/README.md+23 added
1+# JWT Middleware2+3+## Usage4+5+```js6+import { Hono } from 'hono'7+import { jwt } from 'hono/jwt'8+9+const app = new Hono()10+11+app.use(12+ '/auth/*',13+ jwt({14+ secret: 'it-is-very-secret'15+ })16+)17+18+app.get('/auth/page', (c) => {19+ return c.text('You are authorized')20+})21+22+app.fire()23+```added:deno_dist/middleware/logger/index.test.ts+55 added
1+import { Hono } from '../../hono.ts'2+import { logger } from './index.ts'3+4+describe('Logger by Middleware', () => {5+ const app = new Hono()6+7+ let log = ''8+ const logFn = (str: string) => {9+ log = str10+ }11+12+ const shortRandomString = 'hono'13+ const longRandomString = 'hono'.repeat(1000)14+15+ app.use('*', logger(logFn))16+ app.get('/short', (c) => c.text(shortRandomString))17+ app.get('/long', (c) => c.text(longRandomString))18+ app.get('/empty', (c) => c.text(''))19+20+ it('Log status 200 with empty body', async () => {21+ const res = await app.request('http://localhost/empty')22+ expect(res).not.toBeNull()23+ expect(res.status).toBe(200)24+ expect(log.startsWith(' --> GET /empty \x1b[32m200\x1b[0m')).toBe(true)25+ expect(log).toMatch(/m?s$/)26+ })27+28+ it('Log status 200 with small body', async () => {29+ const res = await app.request('http://localhost/short')30+ expect(res).not.toBeNull()31+ expect(res.status).toBe(200)32+ expect(log.startsWith(' --> GET /short \x1b[32m200\x1b[0m')).toBe(true)33+ expect(log).toMatch(/m?s$/)34+ })35+36+ it('Log status 200 with big body', async () => {37+ const res = await app.request('http://localhost/long')38+ expect(res).not.toBeNull()39+ expect(res.status).toBe(200)40+ expect(log.startsWith(' --> GET /long \x1b[32m200\x1b[0m')).toBe(true)41+ expect(log).toMatch(/m?s$/)42+ })43+44+ it('Log status 404', async () => {45+ const msg = 'Default 404 Not Found'46+ app.all('*', (c) => {47+ return c.text(msg, 404)48+ })49+ const res = await app.request('http://localhost/notfound')50+ expect(res).not.toBeNull()51+ expect(res.status).toBe(404)52+ expect(log.startsWith(' --> GET /notfound \x1b[33m404\x1b[0m')).toBe(true)53+ expect(log).toMatch(/m?s$/)54+ })55+})added:deno_dist/middleware/logger/index.ts+67 added
1+import type { Context } from '../../context.ts'2+import type { Next } from '../../hono.ts'3+import { getPathFromURL } from '../../utils/url.ts'4+5+const humanize = (n: string[], opts?: { delimiter?: string; separator?: string }) => {6+ const options = opts || {}7+ const d = options.delimiter || ','8+ const s = options.separator || '.'9+ n = n.toString().split('.')10+ n[0] = n[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1' + d)11+ return n.join(s)12+}13+14+const time = (start: number) => {15+ const delta = Date.now() - start16+ return humanize([delta < 10000 ? delta + 'ms' : Math.round(delta / 1000) + 's'])17+}18+19+const LogPrefix = {20+ Outgoing: '-->',21+ Incoming: '<--',22+ Error: 'xxx',23+}24+25+const colorStatus = (status: number = 0) => {26+ const out: { [key: number]: string } = {27+ 7: `\x1b[35m${status}\x1b[0m`,28+ 5: `\x1b[31m${status}\x1b[0m`,29+ 4: `\x1b[33m${status}\x1b[0m`,30+ 3: `\x1b[36m${status}\x1b[0m`,31+ 2: `\x1b[32m${status}\x1b[0m`,32+ 1: `\x1b[32m${status}\x1b[0m`,33+ 0: `\x1b[33m${status}\x1b[0m`,34+ }35+ return out[(status / 100) | 0]36+}37+type PrintFunc = (str: string, ...rest: string[]) => void38+39+function log(40+ fn: PrintFunc,41+ prefix: string,42+ method: string,43+ path: string,44+ status?: number,45+ elapsed?: string46+) {47+ const out =48+ prefix === LogPrefix.Incoming49+ ? ` ${prefix} ${method} ${path}`50+ : ` ${prefix} ${method} ${path} ${colorStatus(status)} ${elapsed}`51+ fn(out)52+}53+54+export const logger = (fn = console.log) => {55+ return async (c: Context, next: Next) => {56+ const { method } = c.req57+ const path = getPathFromURL(c.req.url)58+59+ log(fn, LogPrefix.Incoming, method, path)60+61+ const start = Date.now()62+63+ await next()64+65+ log(fn, LogPrefix.Outgoing, method, path, c.res.status, time(start))66+ }67+}added:deno_dist/middleware/logger/README.md+17 added
1+# Logger Middleware2+3+## Usage4+5+index.js:6+7+```js8+import { Hono } from 'hono'9+import { logger } from 'hono/logger'10+11+export const app = new Hono()12+13+app.use('*', logger())14+app.get('/', (c) => c.text('Hello Hono!'))15+16+app.fire()17+```added:deno_dist/middleware/mustache/index.ts+1 added
1+export { mustache } from './mustache.ts'added:deno_dist/middleware/mustache/module.mts+15 added
1+// eslint-disable-next-line @typescript-eslint/ban-ts-comment2+// @ts-ignore3+// For ES module mode4+import manifest from '__STATIC_CONTENT_MANIFEST'5+import type { MustacheOptions } from './mustache'6+import { mustache } from './mustache'7+8+const module = (options: MustacheOptions = { root: '' }) => {9+ return mustache({10+ root: options.root,11+ manifest: options.manifest ? options.manifest : manifest,12+ })13+}14+15+export { module as mustache }added:deno_dist/middleware/mustache/mustache.test.ts+73 added
1+import { Hono } from '../../hono.ts'2+import { mustache } from './mustache.ts'3+4+// Mock5+const store: { [key: string]: string } = {6+ 'index.abcdef.mustache': '{{> header}}Title: {{ title }}{{> footer}}',7+ 'header.abcdef.mustache': '<html><body>',8+ 'footer.abcdef.mustache': '</body></html>',9+ 'view/index.abcdef.mustache': '<h1>With Root</h1>',10+ 'view/options.abcdef.mustache': '<h1>With Options</h1>',11+}12+const manifest = JSON.stringify({13+ 'index.mustache': 'index.abcdef.mustache',14+ 'header.mustache': 'header.abcdef.mustache',15+ 'footer.mustache': 'footer.abcdef.mustache',16+ 'view/index.mustache': 'view/index.abcdef.mustache',17+})18+19+Object.assign(global, { __STATIC_CONTENT_MANIFEST: manifest })20+Object.assign(global, {21+ __STATIC_CONTENT: {22+ get: (path: string) => {23+ return store[path]24+ },25+ },26+})27+28+describe('Mustache by Middleware', () => {29+ const app = new Hono()30+31+ app.use('/foo', mustache())32+ app.get('/foo', (c) => {33+ return c.render(34+ 'index',35+ { title: 'Hono!' },36+ {37+ header: 'header',38+ footer: 'footer',39+ }40+ )41+ })42+43+ app.use('/bar', mustache({ root: 'view' }))44+ app.get('/bar', (c) => {45+ return c.render('index')46+ })47+48+ const manifest = {49+ 'view/options.mustache': 'view/options.abcdef.mustache',50+ }51+ app.use('/options', mustache({ root: 'view', manifest: manifest }))52+ app.get('/options', (c) => {53+ return c.render('options')54+ })55+56+ it('Mustache template rendering', async () => {57+ const res = await app.request('http://localhost/foo')58+ expect(res.status).toBe(200)59+ expect(await res.text()).toBe('<html><body>Title: Hono!</body></html>')60+ })61+62+ it('Mustache template rendering with root', async () => {63+ const res = await app.request('http://localhost/bar')64+ expect(res.status).toBe(200)65+ expect(await res.text()).toBe('<h1>With Root</h1>')66+ })67+68+ it('Mustache template rendering with options', async () => {69+ const res = await app.request('http://localhost/options')70+ expect(res.status).toBe(200)71+ expect(await res.text()).toBe('<h1>With Options</h1>')72+ })73+})added:deno_dist/middleware/mustache/mustache.ts+75 added
1+import Mustache from 'mustache DENOIFY: DEPENDENCY UNMET (DEV DEPENDENCY)'2+import type { Context } from '../../context.ts'3+import type { Next } from '../../hono.ts'4+import { bufferToString } from '../../utils/buffer.ts'5+import type { KVAssetOptions } from '../../utils/cloudflare.ts'6+import { getContentFromKVAsset, getKVFilePath } from '../../utils/cloudflare.ts'7+8+const EXTENSION = '.mustache'9+const DEFAULT_DOCUMENT = 'index.mustache'10+11+type Partials = Record<string, string>12+13+interface Mustache {14+ render: (content: string, params: object, partials: Partials) => string15+}16+17+declare module '../../context.ts' {18+ interface Context {19+ render: (content: string, params?: object, options?: object) => Response | Promise<Response>20+ }21+}22+23+export type MustacheOptions = {24+ root: string25+ manifest?: object | string26+ namespace?: KVNamespace27+}28+29+export const mustache = (init: MustacheOptions = { root: '' }) => {30+ const { root } = init31+32+ return async (c: Context, next: Next) => {33+ c.render = async (filename, params = {}, options?): Promise<Response> => {34+ const path = getKVFilePath({35+ filename: `${filename}${EXTENSION}`,36+ root: root,37+ defaultDocument: DEFAULT_DOCUMENT,38+ })39+40+ const kvAssetOptions: KVAssetOptions = {41+ manifest: init.manifest,42+ namespace: init.namespace ? init.namespace : c.env ? c.env.__STATIC_CONTENT : undefined,43+ }44+45+ const buffer = await getContentFromKVAsset(path, kvAssetOptions)46+ if (!buffer) {47+ throw new Error(`Template "${path}" is not found or blank.`)48+ }49+ const content = bufferToString(buffer)50+51+ const partialArgs: Record<string, string> = {}52+53+ if (options) {54+ const partials = options as Partials55+ for (const key of Object.keys(partials)) {56+ const partialPath = getKVFilePath({57+ filename: `${partials[key]}${EXTENSION}`,58+ root: root,59+ defaultDocument: DEFAULT_DOCUMENT,60+ })61+ const partialBuffer = await getContentFromKVAsset(partialPath, kvAssetOptions)62+ if (!partialBuffer) {63+ throw new Error(`Partial Template "${partialPath}" is not found or blank.`)64+ }65+ partialArgs[key] = bufferToString(partialBuffer)66+ }67+ }68+69+ const output = Mustache.render(content, params, partialArgs)70+ return c.html(output)71+ }72+73+ await next()74+ }75+}added:deno_dist/middleware/mustache/README.md+84 added
1+# Mustache Middleware2+3+Mustache Middleware is available only on Cloudflare Workers.4+5+## Requirements6+7+This middleware depends on [mustache.js](https://www.npmjs.com/package/mustache).8+9+```plain10+npm i mustache11+```12+13+or14+15+```plain16+yarn add mustache17+```18+19+## Usage20+21+index.ts:22+23+```ts24+import { Hono } from 'hono'25+import { mustache } from 'hono/mustache'26+27+const app = new Hono()28+29+app.use('*', mustache())30+31+app.get('/', (c) => {32+ return c.render(33+ 'index',34+ { name: 'Hono[炎]', title: 'Hono mustache example' }, // Parameters35+ { footer: 'footer', header: 'header' } // Partials36+ )37+})38+39+app.fire()40+```41+42+In Module Worker mode:43+44+```ts45+import { Hono } from 'hono'46+import { mustache } from 'hono/mustache.module' // <---47+48+const app = new Hono()49+app.use('*', mustache())50+// ...51+52+export default app53+```54+55+index.mustache:56+57+```mustache58+{{> header}}59+<h1>Hello! {{name}}</h1>60+{{> footer}}61+```62+63+header.mustache:64+65+```mustache66+<!DOCTYPE html>67+<html>68+ <head>69+ <meta charset="utf-8" />70+ <title>{{title}}</title>71+ </head>72+ </body>73+```74+75+footer.mustache:76+77+```mustache78+ </body>79+</html>80+```81+82+## Example83+84+<https://github.com/honojs/examples/tree/master/mustache-template>added:deno_dist/middleware/powered-by/index.test.ts+16 added
1+import { Hono } from '../../hono.ts'2+import { poweredBy } from './index.ts'3+4+describe('Powered by Middleware', () => {5+ const app = new Hono()6+7+ app.use('*', poweredBy())8+ app.get('/', (c) => c.text('root'))9+10+ it('Should return with X-Powered-By header', async () => {11+ const res = await app.request('http://localhost/')12+ expect(res).not.toBeNull()13+ expect(res.status).toBe(200)14+ expect(res.headers.get('X-Powered-By')).toBe('Hono')15+ })16+})added:deno_dist/middleware/powered-by/index.ts+9 added
1+import type { Context } from '../../context.ts'2+import type { Next } from '../../hono.ts'3+4+export const poweredBy = () => {5+ return async (c: Context, next: Next) => {6+ await next()7+ c.res.headers.append('X-Powered-By', 'Hono')8+ }9+}added:deno_dist/middleware/pretty-json/index.test.ts+34 added
1+import { Hono } from '../../hono.ts'2+import { prettyJSON } from './index.ts'3+4+describe('JSON pretty by Middleware', () => {5+ it('Should return pretty JSON output', async () => {6+ const app = new Hono()7+ app.use('*', prettyJSON())8+ app.get('/', (c) => {9+ return c.json({ message: 'Hono!' })10+ })11+12+ const res = await app.request('http://localhost/?pretty')13+ expect(res).not.toBeNull()14+ expect(res.status).toBe(200)15+ expect(await res.text()).toBe(`{16+ "message": "Hono!"17+}`)18+ })19+20+ it('Should return pretty JSON output with 4 spaces', async () => {21+ const app = new Hono()22+ app.use('*', prettyJSON({ space: 4 }))23+ app.get('/', (c) => {24+ return c.json({ message: 'Hono!' })25+ })26+27+ const res = await app.request('http://localhost/?pretty')28+ expect(res).not.toBeNull()29+ expect(res.status).toBe(200)30+ expect(await res.text()).toBe(`{31+ "message": "Hono!"32+}`)33+ })34+})added:deno_dist/middleware/pretty-json/index.ts+14 added
1+import type { Context } from '../../context.ts'2+import type { Next } from '../../hono.ts'3+4+type prettyOptions = {5+ space: number6+}7+8+export const prettyJSON = (options: prettyOptions = { space: 2 }) => {9+ return async (c: Context, next: Next) => {10+ const pretty = c.req.query('pretty') || c.req.query('pretty') === '' ? true : false11+ c.pretty(pretty, options.space)12+ await next()13+ }14+}added:deno_dist/middleware/serve-static/index.ts+1 added
1+export { serveStatic } from './serve-static.ts'added:deno_dist/middleware/serve-static/module.mts+15 added
1+// eslint-disable-next-line @typescript-eslint/ban-ts-comment2+// @ts-ignore3+// For ES module mode4+import manifest from '__STATIC_CONTENT_MANIFEST'5+import type { ServeStaticOptions } from './serve-static'6+import { serveStatic } from './serve-static'7+8+const module = (options: ServeStaticOptions = { root: '' }) => {9+ return serveStatic({10+ root: options.root,11+ manifest: options.manifest ? options.manifest : manifest,12+ })13+}14+15+export { module as serveStatic }added:deno_dist/middleware/serve-static/README.md+56 added
1+# Serve Static Middleware2+3+Serve Static Middleware is available only on Cloudflare Workers.4+5+## Usage6+7+index.ts:8+9+```ts10+import { Hono } from 'hono'11+import { serveStatic } from 'hono/serve-static'12+13+const app = new Hono()14+15+app.use('/static/*', serveStatic({ root: './' }))16+app.get('/', (c) => c.text('This is Home! You can access: /static/hello.txt'))17+app.get('*', serveStatic({ path: './static/fallback.txt' }))18+19+app.fire()20+```21+22+In Module Worker mode:23+24+```ts25+import { Hono } from 'hono'26+import { serveStatic } from 'hono/serve-static.module' // <---27+28+const app = new Hono()29+//...30+31+export default app32+```33+34+wrangler.toml:35+36+```toml37+[site]38+bucket = "./assets"39+```40+41+Asset files:42+43+```44+./assets45+└── static46+ ├── demo47+ │ └── index.html48+ ├── hello.txt49+ ├── fallback.txt50+ └── images51+ └── dinotocat.png52+```53+54+## Example55+56+<https://github.com/honojs/examples/tree/master/serve-static>added:deno_dist/middleware/serve-static/serve-static.test.ts+135 added
1+import type { Context } from '../../context.ts'2+import type { Next } from '../../hono.ts'3+import { Hono } from '../../hono.ts'4+import { serveStatic } from './index.ts'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:deno_dist/middleware/serve-static/serve-static.ts+48 added
1+import type { Context, Env } from '../../context.ts'2+import type { Handler, Next } from '../../hono.ts'3+import { getContentFromKVAsset, getKVFilePath } from '../../utils/cloudflare.ts'4+import { getMimeType } from '../../utils/mime.ts'5+6+export type ServeStaticOptions = {7+ root?: string8+ path?: string9+ manifest?: object | string10+ namespace?: KVNamespace11+}12+13+const DEFAULT_DOCUMENT = 'index.html'14+15+// This middleware is available only on Cloudflare Workers.16+export const serveStatic = (options: ServeStaticOptions = { root: '' }): Handler<string, Env> => {17+ return async (c: Context, next: Next): Promise<Response | undefined> => {18+ // Do nothing if Response is already set19+ if (c.res && c.finalized) {20+ await next()21+ }22+23+ const url = new URL(c.req.url)24+25+ const path = getKVFilePath({26+ filename: options.path ?? url.pathname,27+ root: options.root,28+ defaultDocument: DEFAULT_DOCUMENT,29+ })30+31+ const content = await getContentFromKVAsset(path, {32+ manifest: options.manifest,33+ namespace: options.namespace ? options.namespace : c.env ? c.env.__STATIC_CONTENT : undefined,34+ })35+ if (content) {36+ const mimeType = getMimeType(path)37+ if (mimeType) {38+ c.header('Content-Type', mimeType)39+ }40+ // Return Response object41+ return c.body(content)42+ } else {43+ console.warn(`Static file: ${path} is not found`)44+ await next()45+ }46+ return47+ }48+}added:deno_dist/router/reg-exp-router/index.ts+1 added
1+export { RegExpRouter } from './router.ts'added:deno_dist/router/reg-exp-router/node.ts+118 added
1+const LABEL_REG_EXP_STR = '[^/]+'2+const ONLY_WILDCARD_REG_EXP_STR = '.*'3+const TAIL_WILDCARD_REG_EXP_STR = '(?:|/.*)'4+5+export type ParamMap = Array<[string, number]>6+export interface Context {7+ varIndex: number8+}9+10+/**11+ * Sort order:12+ * 1. literal13+ * 2. special pattern (e.g. :label{[0-9]+})14+ * 3. common label pattern (e.g. :label)15+ * 4. wildcard16+ */17+function compareKey(a: string, b: string): number {18+ if (a.length === 1) {19+ return b.length === 1 ? (a < b ? -1 : 1) : -120+ }21+ if (b.length === 1) {22+ return 123+ }24+25+ // wildcard26+ if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {27+ return 128+ } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {29+ return -130+ }31+32+ // label33+ if (a === LABEL_REG_EXP_STR) {34+ return 135+ } else if (b === LABEL_REG_EXP_STR) {36+ return -137+ }38+39+ return a.length === b.length ? (a < b ? -1 : 1) : b.length - a.length40+}41+42+export class Node {43+ index?: number44+ varIndex?: number45+ children: Record<string, Node> = {}46+ reverse: boolean47+48+ constructor({ reverse }: Partial<Node> = { reverse: false }) {49+ this.reverse = reverse as boolean50+ }51+52+ newChildNode(): Node {53+ return new Node({ reverse: this.reverse })54+ }55+56+ insert(tokens: readonly string[], index: number, paramMap: ParamMap, context: Context): void {57+ if (tokens.length === 0) {58+ this.index = index59+ return60+ }61+62+ const [token, ...restTokens] = tokens63+ const pattern =64+ token === '*'65+ ? restTokens.length === 066+ ? ['', '', ONLY_WILDCARD_REG_EXP_STR] // '*' matches to all the trailing paths67+ : ['', '', LABEL_REG_EXP_STR]68+ : token === '/*'69+ ? ['', '', TAIL_WILDCARD_REG_EXP_STR] // '/path/to/*' is /\/path\/to(?:|/.*)$70+ : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/)71+72+ let node73+ if (pattern) {74+ const name = pattern[1]75+ const regexpStr = pattern[2] || LABEL_REG_EXP_STR76+77+ node = this.children[regexpStr]78+ if (!node) {79+ node = this.children[regexpStr] = this.newChildNode()80+ if (name !== '') {81+ node.varIndex = context.varIndex++82+ }83+ }84+ if (name !== '') {85+ paramMap.push([name, node.varIndex as number])86+ }87+ } else {88+ node = this.children[token] ||= this.newChildNode()89+ }90+91+ node.insert(restTokens, index, paramMap, context)92+ }93+94+ buildRegExpStr(): string {95+ let childKeys = Object.keys(this.children).sort(compareKey)96+ if (this.reverse) {97+ childKeys = childKeys.reverse()98+ }99+100+ const strList = childKeys.map((k) => {101+ const c = this.children[k]102+ return (typeof c.varIndex === 'number' ? `(${k})@${c.varIndex}` : k) + c.buildRegExpStr()103+ })104+105+ if (typeof this.index === 'number') {106+ strList.unshift(`#${this.index}`)107+ }108+109+ if (strList.length === 0) {110+ return ''111+ }112+ if (strList.length === 1) {113+ return strList[0]114+ }115+116+ return '(?:' + strList.join('|') + ')'117+ }118+}added:deno_dist/router/reg-exp-router/router.test.ts+295 added
1+import { METHOD_NAME_ALL } from '../../router.ts'2+import { RegExpRouter } from './router.ts'3+4+describe('Basic Usage', () => {5+ const router = new RegExpRouter<string>()6+7+ router.add('GET', '/hello', 'get hello')8+ router.add('POST', '/hello', 'post 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('PUT', '/hello')20+ expect(res).toBeNull()21+22+ res = router.match('GET', '/')23+ expect(res).toBeNull()24+ })25+})26+27+describe('Complex', () => {28+ let router: RegExpRouter<string>29+ beforeEach(() => {30+ router = new RegExpRouter<string>()31+ })32+33+ it('Named Param', async () => {34+ router.add('GET', '/entry/:id', 'get entry')35+ const res = router.match('GET', '/entry/123')36+ expect(res).not.toBeNull()37+ expect(res?.handlers).toEqual(['get entry'])38+ expect(res?.params['id']).toBe('123')39+ })40+41+ it('Wildcard', async () => {42+ router.add('GET', '/wild/*/card', 'get wildcard')43+ const res = router.match('GET', '/wild/xxx/card')44+ expect(res).not.toBeNull()45+ expect(res?.handlers).toEqual(['get wildcard'])46+ })47+48+ it('Default', async () => {49+ router.add('GET', '/api/abc', 'get api')50+ router.add('GET', '/api/*', 'fallback')51+ let res = router.match('GET', '/api/abc')52+ expect(res).not.toBeNull()53+ expect(res?.handlers).toEqual(['get api', 'fallback'])54+ res = router.match('GET', '/api/def')55+ expect(res).not.toBeNull()56+ expect(res?.handlers).toEqual(['fallback'])57+ })58+59+ it('Regexp', async () => {60+ router.add('GET', '/post/:date{[0-9]+}/:title{[a-z]+}', 'get post')61+ let res = router.match('GET', '/post/20210101/hello')62+ expect(res).not.toBeNull()63+ expect(res?.handlers).toEqual(['get post'])64+ expect(res?.params['date']).toBe('20210101')65+ expect(res?.params['title']).toBe('hello')66+ res = router.match('GET', '/post/onetwothree')67+ expect(res).toBeNull()68+ res = router.match('GET', '/post/123/123')69+ expect(res).toBeNull()70+ })71+72+ it('/*', async () => {73+ router.add('GET', '/api/*', 'auth middleware')74+ router.add('GET', '/api', 'top')75+ router.add('GET', '/api/posts', 'posts')76+ router.add('GET', '/api/*', 'fallback')77+78+ let res = router.match('GET', '/api')79+ expect(res).not.toBeNull()80+ expect(res?.handlers).toEqual(['auth middleware', 'top', 'fallback'])81+82+ res = router.match('GET', '/api/posts')83+ expect(res).not.toBeNull()84+ expect(res?.handlers).toEqual(['auth middleware', 'posts', 'fallback'])85+ })86+})87+88+describe('Registration order', () => {89+ let router: RegExpRouter<string>90+ beforeEach(() => {91+ router = new RegExpRouter<string>()92+ })93+94+ it('abstract -> concrete', async () => {95+ router.add('GET', '/:type/:action', 'foo')96+ router.add('GET', '/posts/:id', 'bar')97+ const res = router.match('GET', '/posts/123')98+ expect(res).not.toBeNull()99+ expect(res?.handlers).toEqual(['foo', 'bar'])100+ })101+102+ it('concrete -> abstract', async () => {103+ router.add('GET', '/posts/:id', 'bar')104+ router.add('GET', '/:type/:action', 'foo')105+ const res = router.match('GET', '/posts/123')106+ expect(res).not.toBeNull()107+ expect(res?.handlers).toEqual(['bar', 'foo'])108+ })109+110+ it('middleware -> handler', async () => {111+ router.add('GET', '*', 'bar')112+ router.add('GET', '/:type/:action', 'foo')113+ const res = router.match('GET', '/posts/123')114+ expect(res).not.toBeNull()115+ expect(res?.handlers).toEqual(['bar', 'foo'])116+ })117+118+ it('handler -> fallback', async () => {119+ router.add('GET', '/:type/:action', 'foo')120+ router.add('GET', '*', 'fallback')121+ const res = router.match('GET', '/posts/123')122+ expect(res).not.toBeNull()123+ expect(res?.handlers).toEqual(['foo', 'fallback'])124+ })125+})126+127+describe('Optimization for METHOD_NAME_OF_ALL', () => {128+ let router: RegExpRouter<string>129+ beforeEach(() => {130+ router = new RegExpRouter<string>()131+ })132+133+ it('Apply to all requests', async () => {134+ router.add(METHOD_NAME_ALL, '*', 'OK')135+ const res = router.match('GET', '/entry/123')136+ expect(res).not.toBeNull()137+ expect(res?.handlers).toEqual(['OK'])138+ expect(res?.params).toMatchObject({})139+ })140+141+ it('Apply to all requests under a specific path', async () => {142+ router.add(METHOD_NAME_ALL, '/path/to/*', 'OK')143+ let res = router.match('GET', '/entry/123')144+ expect(res).toBeNull()145+146+ res = router.match('GET', '/path/to/entry/123')147+ expect(res).not.toBeNull()148+ expect(res?.handlers).toEqual(['OK'])149+ expect(res?.params).toMatchObject({})150+ })151+})152+153+describe('Multi match', () => {154+ describe('Blog', () => {155+ const router = new RegExpRouter<string>()156+157+ router.add('ALL', '*', 'middleware a')158+ router.add('GET', '*', 'middleware b')159+ router.add('GET', '/entry', 'get entries')160+ router.add('POST', '/entry/*', 'middleware c')161+ router.add('POST', '/entry', 'post entry')162+ router.add('GET', '/entry/:id', 'get entry')163+ router.add('GET', '/entry/:id/comment/:comment_id', 'get comment')164+ it('GET /', async () => {165+ const res = router.match('GET', '/')166+ expect(res).not.toBeNull()167+ expect(res?.handlers).toEqual(['middleware a', 'middleware b'])168+ })169+ it('GET /entry/123', async () => {170+ const res = router.match('GET', '/entry/123')171+ expect(res).not.toBeNull()172+ expect(res?.handlers).toEqual(['middleware a', 'middleware b', 'get entry'])173+ expect(res?.params['id']).toBe('123')174+ })175+ it('GET /entry/123/comment/456', async () => {176+ const res = router.match('GET', '/entry/123/comment/456')177+ expect(res).not.toBeNull()178+ expect(res?.handlers).toEqual(['middleware a', 'middleware b', 'get comment'])179+ expect(res?.params['id']).toBe('123')180+ expect(res?.params['comment_id']).toBe('456')181+ })182+ it('POST /entry', async () => {183+ const res = router.match('POST', '/entry')184+ expect(res).not.toBeNull()185+ expect(res?.handlers).toEqual(['middleware a', 'middleware c', 'post entry'])186+ })187+ it('DELETE /entry', async () => {188+ const res = router.match('DELETE', '/entry')189+ expect(res).not.toBeNull()190+ expect(res?.handlers).toEqual(['middleware a'])191+ })192+ })193+194+ describe('Ambiguous', () => {195+ const router = new RegExpRouter<string>()196+197+ router.add('GET', '/:user/entries', 'get user entries')198+ router.add('GET', '/entry/:name', 'get entry')199+ it('GET /entry/entry', async () => {200+ const res = router.match('GET', '/entry/entries')201+ expect(res).not.toBeNull()202+ expect(res?.handlers).toEqual(['get user entries', 'get entry'])203+ expect(res?.params['user']).toBe('entry')204+ expect(res?.params['name']).toBe('entries')205+ })206+ })207+208+ describe('Multiple handlers', () => {209+ const router = new RegExpRouter<string>()210+211+ router.add('GET', '/:type/:id', ':type')212+ router.add('GET', '/:class/:id', ':class')213+ router.add('GET', '/:model/:id', ':model')214+ router.add('GET', '/entry/:id', 'entry')215+216+ it('GET /entry/123', async () => {217+ const res = router.match('GET', '/entry/123')218+ expect(res).not.toBeNull()219+ expect(res?.handlers).toEqual([':type', ':class', ':model', 'entry'])220+ expect(res?.params['type']).toBe('entry')221+ expect(res?.params['class']).toBe('entry')222+ expect(res?.params['model']).toBe('entry')223+ })224+ })225+})226+227+describe('Check for duplicate parameter names', () => {228+ it('self', () => {229+ const router = new RegExpRouter<string>()230+ router.add('GET', '/:id/:id', 'get')231+ expect(() => {232+ router.match('GET', '/') // check parameter names on the first `match` call233+ }).toThrowError(/Duplicate param name/)234+ })235+236+ it('parent', () => {237+ const router = new RegExpRouter<string>()238+ router.add('GET', '/:id/:action', 'foo')239+ router.add('GET', '/posts/:id', 'bar')240+ expect(() => {241+ router.match('GET', '/')242+ }).toThrowError(/Duplicate param name/)243+ })244+245+ it('child', () => {246+ const router = new RegExpRouter<string>()247+ router.add('GET', '/posts/:id', 'foo')248+ router.add('GET', '/:id/:action', 'bar')249+250+ expect(() => {251+ router.match('GET', '/')252+ }).toThrowError(/Duplicate param name/)253+ })254+255+ it('hierarchy', () => {256+ const router = new RegExpRouter<string>()257+ router.add('GET', '/posts/:id/comments/:comment_id', 'foo')258+ router.add('GET', '/posts/:id', 'bar')259+ expect(() => {260+ router.match('GET', '/')261+ }).not.toThrow()262+ })263+264+ it('different regular expression', () => {265+ const router = new RegExpRouter<string>()266+ router.add('GET', '/:id/:action{create|update}', 'foo')267+ router.add('GET', '/:id/:action{delete}', 'bar')268+ expect(() => {269+ router.match('GET', '/')270+ }).not.toThrow()271+ })272+})273+274+describe('star', () => {275+ const router = new RegExpRouter<string>()276+277+ router.add('GET', '/', '/')278+ router.add('GET', '/*', '/*')279+ router.add('GET', '*', '*')280+281+ router.add('GET', '/x', '/x')282+ router.add('GET', '/x/*', '/x/*')283+284+ it('top', async () => {285+ const res = router.match('GET', '/')286+ expect(res).not.toBeNull()287+ expect(res?.handlers).toEqual(['/', '/*', '*'])288+ })289+290+ it('Under a certain path', async () => {291+ const res = router.match('GET', '/x')292+ expect(res).not.toBeNull()293+ expect(res?.handlers).toEqual(['/*', '*', '/x', '/x/*'])294+ })295+})added:deno_dist/router/reg-exp-router/router.ts+460 added
1+/* eslint-disable @typescript-eslint/ban-ts-comment */2+import type { Router, Result } from '../../router.ts'3+import { METHOD_NAME_ALL } from '../../router.ts'4+import type { ParamMap } from './trie.ts'5+import { Trie } from './trie.ts'6+7+interface Hint {8+ components: string[]9+ regExpComponents: Array<true | string>10+ componentsLength: number11+ endWithWildcard: boolean12+ paramIndexList: number[]13+ maybeHandler: boolean14+ namedParams: [number, string, string][]15+}16+interface HandlerWithSortIndex<T> {17+ handler: T18+ index: number19+}20+interface Route<T> {21+ method: string22+ path: string23+ hint: Hint24+ handlers: HandlerWithSortIndex<T>[]25+ middleware: HandlerWithSortIndex<T>[]26+ paramAliasMap: Record<string, string[]>27+}28+type HandlerData<T> = [T[], ParamMap | null]29+type Matcher<T> = [RegExp, HandlerData<T>[]]30+type HandlerDataWithSortIndex<T> = [HandlerWithSortIndex<T>[], ParamMap | null]31+type MatcherWithSortIndex<T> = [RegExp, HandlerDataWithSortIndex<T>[]]32+type AnyMatcher<T> = Matcher<T> | MatcherWithSortIndex<T>33+34+type CompareResult =35+ | 0 // different36+ | 1 // included37+ | 2 // ambiguous38+39+const emptyParam = {}40+const nullMatcher: Matcher<any> = [/^$/, []]41+42+function initHint(path: string): Hint {43+ const components = path.match(/\/(?::\w+{[^}]+}|[^\/]*)/g) || []44+ let componentsLength = components.length45+46+ const paramIndexList: number[] = []47+ const regExpComponents: Array<true | string> = []48+ const namedParams: [number, string, string][] = []49+ for (let i = 0, len = components.length; i < len; i++) {50+ if (i === len - 1 && components[i] === '/*') {51+ componentsLength--52+ break53+ }54+55+ const m = components[i].match(/^\/:(\w+)({[^}]+})?/)56+ if (m) {57+ namedParams.push([i, m[1], m[2] || '[^/]+'])58+ regExpComponents[i] = m[2] || true59+ } else if (components[i] === '/*') {60+ regExpComponents[i] = true61+ } else {62+ regExpComponents[i] = components[i]63+ }64+65+ if (/\/(?::|\*)/.test(components[i])) {66+ paramIndexList.push(i)67+ }68+ }69+70+ return {71+ components,72+ regExpComponents,73+ componentsLength,74+ endWithWildcard: path.endsWith('*'),75+ paramIndexList,76+ namedParams,77+ maybeHandler: true,78+ }79+}80+81+function compareRoute<T>(a: Route<T>, b: Route<T>): CompareResult {82+ if (a.path === '*') {83+ return 184+ }85+86+ let i = 087+ const len = a.hint.regExpComponents.length88+ for (; i < len; i++) {89+ if (a.hint.regExpComponents[i] !== b.hint.regExpComponents[i]) {90+ if (a.hint.regExpComponents[i] === true) {91+ break92+ }93+94+ return 095+ }96+ }97+98+ // may be ambiguous99+ for (; i < len; i++) {100+ if (101+ a.hint.regExpComponents[i] !== true &&102+ a.hint.regExpComponents[i] !== b.hint.regExpComponents[i]103+ ) {104+ return 2105+ }106+ }107+108+ return i === b.hint.regExpComponents.length || a.hint.endWithWildcard ? 1 : 0109+}110+111+function compareHandler(a: HandlerWithSortIndex<any>, b: HandlerWithSortIndex<any>) {112+ return a.index - b.index113+}114+115+function getSortedHandlers<T>(116+ handlers: HandlerWithSortIndex<T>[] | IterableIterator<HandlerWithSortIndex<T>>117+): T[] {118+ return [...handlers].sort(compareHandler).map((h) => h.handler)119+}120+121+function buildMatcherFromPreprocessedRoutes<T>(122+ routes: Route<T>[],123+ hasAmbiguous: boolean = false124+): AnyMatcher<T> {125+ const trie = new Trie({ reverse: hasAmbiguous })126+ const handlers: HandlerData<T>[] | HandlerDataWithSortIndex<T>[] = []127+128+ if (routes.length === 0) {129+ return nullMatcher130+ }131+132+ for (let i = 0, len = routes.length; i < len; i++) {133+ const paramMap = trie.insert(routes[i].path, i)134+ handlers[i] = [135+ [...routes[i].middleware, ...routes[i].handlers],136+ Object.keys(paramMap).length !== 0 ? paramMap : null,137+ ]138+ if (!hasAmbiguous) {139+ handlers[i][0] = getSortedHandlers(handlers[i][0] as HandlerWithSortIndex<T>[])140+ }141+ }142+143+ const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp()144+ for (let i = 0, len = handlers.length; i < len; i++) {145+ const paramMap = handlers[i][1]146+ if (paramMap) {147+ for (let j = 0, len = paramMap.length; j < len; j++) {148+ paramMap[j][1] = paramReplacementMap[paramMap[j][1]]149+150+ const aliasTo = routes[i].paramAliasMap[paramMap[j][0]]151+ if (aliasTo) {152+ for (let k = 0, len = aliasTo.length; k < len; k++) {153+ paramMap.push([aliasTo[k], paramMap[j][1]])154+ }155+ }156+ }157+ }158+ }159+160+ const handlerMap: HandlerData<T>[] | HandlerDataWithSortIndex<T>[] = []161+ // using `in` because indexReplacementMap is a sparse array162+ for (const i in indexReplacementMap) {163+ handlerMap[i] = handlers[indexReplacementMap[i]]164+ }165+166+ return [regexp, handlerMap] as AnyMatcher<T>167+}168+169+function verifyDuplicateParam<T>(routes: Route<T>[]): boolean {170+ const nameMap: Record<string, number> = {}171+ for (let i = 0, len = routes.length; i < len; i++) {172+ const route = routes[i]173+174+ for (let k = 0, len = route.hint.namedParams.length; k < len; k++) {175+ const [index, name] = route.hint.namedParams[k]176+ if (name in nameMap && index !== nameMap[name]) {177+ return false178+ } else {179+ nameMap[name] = index180+ }181+ }182+183+ const paramAliasMap = route.paramAliasMap184+ const paramAliasMapKeys = Object.keys(paramAliasMap)185+ for (let k = 0, len = paramAliasMapKeys.length; k < len; k++) {186+ const aliasFrom = paramAliasMapKeys[k]187+ for (let l = 0, len = paramAliasMap[aliasFrom].length; l < len; l++) {188+ const aliasTo = paramAliasMap[aliasFrom][l]189+ const index = nameMap[aliasFrom]190+ if (aliasTo in nameMap && index !== nameMap[aliasTo]) {191+ return false192+ } else {193+ nameMap[aliasTo] = index194+ }195+ }196+ }197+ }198+199+ return true200+}201+202+export class RegExpRouter<T> implements Router<T> {203+ routeData?: {204+ index: number205+ routes: Route<T>[]206+ methods: Set<string>207+ } = { index: 0, routes: [], methods: new Set() }208+209+ add(method: string, path: string, handler: T) {210+ if (!this.routeData) {211+ throw new Error('Can not add a route since the matcher is already built.')212+ }213+ this.routeData.index++214+ const { index, routes, methods } = this.routeData215+216+ if (path === '/*') {217+ path = '*'218+ }219+220+ const hint = initHint(path)221+ const handlerWithSortIndex = {222+ index,223+ handler,224+ }225+226+ for (let i = 0, len = routes.length; i < len; i++) {227+ if (routes[i].method === method && routes[i].path === path) {228+ routes[i].handlers.push(handlerWithSortIndex)229+ return230+ }231+ }232+233+ methods.add(method)234+ routes.push({235+ method,236+ path,237+ hint,238+ handlers: [handlerWithSortIndex],239+ middleware: [],240+ paramAliasMap: {},241+ })242+ }243+244+ match(method: string, path: string): Result<T> | null {245+ const [primaryMatchers, secondaryMatchers, hasAmbiguous] = this.buildAllMatchers()246+247+ this.match = hasAmbiguous248+ ? (method, path) => {249+ const matcher = (primaryMatchers[method] ||250+ primaryMatchers[METHOD_NAME_ALL]) as MatcherWithSortIndex<T>251+ let match = path.match(matcher[0])252+253+ if (!match) {254+ // do not support secondary matchers here.255+ return null256+ }257+258+ const params: Record<string, string> = {}259+ const handlers: Set<HandlerWithSortIndex<T>> = new Set()260+ let regExpSrc = matcher[0].source261+ while (match) {262+ let index = match.indexOf('', 1)263+ for (;;) {264+ const [handler, paramMap] = matcher[1][index]265+266+ if (paramMap) {267+ for (let i = 0, len = paramMap.length; i < len; i++) {268+ params[paramMap[i][0]] = match[paramMap[i][1]]269+ }270+ }271+272+ for (let i = 0, len = handler.length; i < len; i++) {273+ handlers.add(handler[i])274+ }275+276+ const newIndex = match.indexOf('', index + 1)277+ if (newIndex === -1) {278+ break279+ }280+ index = newIndex281+ }282+283+ regExpSrc = regExpSrc.replace(284+ new RegExp(`((?:(?:\\(\\?:|.)*?\\([^)]*\\)){${index - 1}}.*?)\\(\\)`),285+ '$1(^)'286+ )287+ match = path.match(new RegExp(regExpSrc))288+ }289+290+ return { handlers: getSortedHandlers(handlers.values()), params }291+ }292+ : (method, path) => {293+ let matcher = (primaryMatchers[method] || primaryMatchers[METHOD_NAME_ALL]) as Matcher<T>294+ let match = path.match(matcher[0])295+296+ if (!match) {297+ const matchers = secondaryMatchers[method] || secondaryMatchers[METHOD_NAME_ALL]298+ for (let i = 0, len = matchers.length; i < len && !match; i++) {299+ matcher = matchers[i] as Matcher<T>300+ match = path.match(matcher[0])301+ }302+303+ if (!match) {304+ return null305+ }306+ }307+308+ const index = match.indexOf('', 1)309+ const [handlers, paramMap] = matcher[1][index]310+ if (!paramMap) {311+ return { handlers, params: emptyParam }312+ }313+314+ const params: Record<string, string> = {}315+ for (let i = 0, len = paramMap.length; i < len; i++) {316+ params[paramMap[i][0]] = match[paramMap[i][1]]317+ }318+319+ return { handlers, params }320+ }321+322+ return this.match(method, path)323+ }324+325+ private buildAllMatchers(): [326+ Record<string, AnyMatcher<T>>,327+ Record<string, AnyMatcher<T>[]>,328+ boolean329+ ] {330+ // @ts-ignore331+ this.routeData.routes.sort(({ hint: a }, { hint: b }) => {332+ if (a.componentsLength !== b.componentsLength) {333+ return a.componentsLength - b.componentsLength334+ }335+ for (336+ let i = 0, len = Math.min(a.paramIndexList.length, b.paramIndexList.length) + 1;337+ i < len;338+ i++339+ ) {340+ if (a.paramIndexList[i] !== b.paramIndexList[i]) {341+ if (a.paramIndexList[i] === undefined) {342+ return -1343+ } else if (b.paramIndexList[i] === undefined) {344+ return 1345+ } else {346+ return a.paramIndexList[i] - b.paramIndexList[i]347+ }348+ }349+ }350+ if (a.endWithWildcard !== b.endWithWildcard) {351+ return a.endWithWildcard ? -1 : 1352+ }353+ return 0354+ })355+356+ const primaryMatchers: Record<string, AnyMatcher<T>> = {}357+ const secondaryMatchers: Record<string, AnyMatcher<T>[]> = {}358+ let hasAmbiguous = false359+ // @ts-ignore360+ this.routeData.methods.forEach((method) => {361+ let _hasAmbiguous362+ ;[primaryMatchers[method], secondaryMatchers[method], _hasAmbiguous] =363+ this.buildMatcher(method)364+ hasAmbiguous = hasAmbiguous || _hasAmbiguous365+ })366+ primaryMatchers[METHOD_NAME_ALL] ||= nullMatcher367+ secondaryMatchers[METHOD_NAME_ALL] ||= []368+369+ delete this.routeData // to reduce memory usage370+371+ return [primaryMatchers, secondaryMatchers, hasAmbiguous]372+ }373+374+ private buildMatcher(method: string): [AnyMatcher<T>, AnyMatcher<T>[], boolean] {375+ let hasAmbiguous = false376+ const targetMethods = new Set([method, METHOD_NAME_ALL])377+ // @ts-ignore378+ const routes = this.routeData.routes.filter(({ method }) => targetMethods.has(method))379+380+ // Reset temporary data per method381+ for (let i = 0, len = routes.length; i < len; i++) {382+ routes[i].middleware = []383+ routes[i].paramAliasMap = {}384+ }385+386+ // preprocess routes387+ for (let i = 0, len = routes.length; i < len; i++) {388+ for (let j = i + 1; j < len; j++) {389+ const compareResult = compareRoute(routes[i], routes[j])390+ // i includes j391+ if (compareResult === 1) {392+ const components = routes[j].hint.components393+ const namedParams = routes[i].hint.namedParams394+ for (let k = 0, len = namedParams.length; k < len; k++) {395+ const c = components[namedParams[k][0]]396+ const m = c.match(/^\/:(\w+)({[^}]+})?/)397+ if (m && namedParams[k][1] === m[1]) {398+ continue399+ }400+ if (m) {401+ routes[j].paramAliasMap[m[1]] ||= []402+ routes[j].paramAliasMap[m[1]].push(namedParams[k][1])403+ } else {404+ components[namedParams[k][0]] = `/:${namedParams[k][1]}{${c.substring(1)}}`405+ routes[j].hint.namedParams.push([406+ namedParams[k][0],407+ namedParams[k][1],408+ c.substring(1),409+ ])410+ routes[j].path = components.join('')411+ }412+ }413+414+ if (routes[j].hint.components.length < routes[i].hint.components.length) {415+ routes[j].middleware.push(416+ ...routes[i].handlers.map((h) => ({417+ index: h.index,418+ handler: h.handler,419+ }))420+ )421+ } else {422+ routes[j].middleware.push(...routes[i].handlers)423+ }424+425+ routes[i].hint.maybeHandler = false426+ } else if (compareResult === 2) {427+ // ambiguous428+ hasAmbiguous = true429+430+ if (!verifyDuplicateParam([routes[i], routes[j]])) {431+ throw new Error('Duplicate param name')432+ }433+ }434+ }435+436+ if (!verifyDuplicateParam([routes[i]])) {437+ throw new Error('Duplicate param name')438+ }439+ }440+441+ if (hasAmbiguous) {442+ return [buildMatcherFromPreprocessedRoutes(routes, hasAmbiguous), [], hasAmbiguous]443+ }444+445+ const primaryRoutes = []446+ const secondaryRoutes = []447+ for (let i = 0, len = routes.length; i < len; i++) {448+ if (routes[i].hint.maybeHandler || !routes[i].hint.endWithWildcard) {449+ primaryRoutes.push(routes[i])450+ } else {451+ secondaryRoutes.push(routes[i])452+ }453+ }454+ return [455+ buildMatcherFromPreprocessedRoutes(primaryRoutes, hasAmbiguous),456+ [buildMatcherFromPreprocessedRoutes(secondaryRoutes, hasAmbiguous)],457+ hasAmbiguous,458+ ]459+ }460+}added:deno_dist/router/reg-exp-router/trie.ts+57 added
1+import type { ParamMap, Context } from './node.ts'2+import { Node } from './node.ts'3+4+export type { ParamMap } from './node.ts'5+export type ReplacementMap = number[]6+7+interface InitOptions {8+ reverse: boolean9+}10+11+export class Trie {12+ context: Context = { varIndex: 0 }13+ root: Node14+15+ constructor({ reverse }: InitOptions = { reverse: false }) {16+ this.root = new Node({ reverse })17+ }18+19+ insert(path: string, index: number): ParamMap {20+ const paramMap: ParamMap = []21+22+ /**23+ * - pattern (:label, :label{0-9]+}, ...)24+ * - /* wildcard25+ * - character26+ */27+ const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g)28+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment29+ // @ts-ignore30+ this.root.insert(tokens, index, paramMap, this.context)31+32+ return paramMap33+ }34+35+ buildRegExp(): [RegExp, ReplacementMap, ReplacementMap] {36+ let regexp = this.root.buildRegExpStr()37+38+ let captureIndex = 039+ const indexReplacementMap: ReplacementMap = []40+ const paramReplacementMap: ReplacementMap = []41+42+ regexp = regexp.replace(/#(\d+)|@(\d+)|\.\*\$/g, (_, handlerIndex, paramIndex) => {43+ if (typeof handlerIndex !== 'undefined') {44+ indexReplacementMap[++captureIndex] = Number(handlerIndex)45+ return '$()'46+ }47+ if (typeof paramIndex !== 'undefined') {48+ paramReplacementMap[Number(paramIndex)] = ++captureIndex49+ return ''50+ }51+52+ return ''53+ })54+55+ return [new RegExp(`^${regexp}`), indexReplacementMap, paramReplacementMap]56+ }57+}added:deno_dist/router/trie-router/index.ts+1 added
1+export { TrieRouter } from './router.ts'added:deno_dist/router/trie-router/node.test.ts+529 added
1+import { Node } from './node.ts'2+3+describe('Root Node', () => {4+ const node = new Node()5+ node.insert('get', '/', 'get root')6+ it('get /', () => {7+ const res = node.search('get', '/')8+ expect(res).not.toBeNull()9+ expect(res?.handlers).toEqual(['get root'])10+ expect(node.search('get', '/hello')).toBeNull()11+ })12+})13+14+describe('Root Node is not defined', () => {15+ const node = new Node()16+ node.insert('get', '/hello', 'get hello')17+ it('get /', () => {18+ expect(node.search('get', '/')).toBeNull()19+ })20+})21+22+describe('Get with *', () => {23+ const node = new Node()24+ node.insert('get', '*', 'get all')25+ it('get /', () => {26+ expect(node.search('get', '/')).not.toBeNull()27+ expect(node.search('get', '/hello')).not.toBeNull()28+ })29+})30+31+describe('Basic Usage', () => {32+ const node = new Node()33+ node.insert('get', '/hello', 'get hello')34+ node.insert('post', '/hello', 'post hello')35+ node.insert('get', '/hello/foo', 'get hello foo')36+37+ it('get, post /hello', () => {38+ expect(node.search('get', '/')).toBeNull()39+ expect(node.search('post', '/')).toBeNull()40+41+ expect(node.search('get', '/hello')?.handlers).toEqual(['get hello'])42+ expect(node.search('post', '/hello')?.handlers).toEqual(['post hello'])43+ expect(node.search('put', '/hello')).toBeNull()44+ })45+ it('get /nothing', () => {46+ expect(node.search('get', '/nothing')).toBeNull()47+ })48+ it('/hello/foo, /hello/bar', () => {49+ expect(node.search('get', '/hello/foo')?.handlers).toEqual(['get hello foo'])50+ expect(node.search('post', '/hello/foo')).toBeNull()51+ expect(node.search('get', '/hello/bar')).toBeNull()52+ })53+ it('/hello/foo/bar', () => {54+ expect(node.search('get', '/hello/foo/bar')).toBeNull()55+ })56+})57+58+describe('Name path', () => {59+ const node = new Node()60+ node.insert('get', '/entry/:id', 'get entry')61+ node.insert('get', '/entry/:id/comment/:comment_id', 'get comment')62+ node.insert('get', '/map/:location/events', 'get events')63+64+ it('get /entry/123', () => {65+ const res = node.search('get', '/entry/123')66+ expect(res).not.toBeNull()67+ expect(res?.handlers).toEqual(['get entry'])68+ expect(res?.params).not.toBeNull()69+ expect(res?.params['id']).toBe('123')70+ expect(res?.params['id']).not.toBe('1234')71+ })72+73+ it('get /entry/456/comment', () => {74+ const res = node.search('get', '/entry/456/comment')75+ expect(res).toBeNull()76+ })77+78+ it('get /entry/789/comment/123', () => {79+ const res = node.search('get', '/entry/789/comment/123')80+ expect(res).not.toBeNull()81+ expect(res?.handlers).toEqual(['get comment'])82+ expect(res?.params['id']).toBe('789')83+ expect(res?.params['comment_id']).toBe('123')84+ })85+86+ it('get /map/:location/events', () => {87+ const res = node.search('get', '/map/yokohama/events')88+ expect(res).not.toBeNull()89+ expect(res?.handlers).toEqual(['get events'])90+ expect(res?.params['location']).toBe('yokohama')91+ })92+})93+94+describe('Name path - Multiple route', () => {95+ const node = new Node()96+97+ node.insert('get', '/:type/:id', 'common')98+ node.insert('get', '/posts/:id', 'specialized')99+100+ it('get /posts/123', () => {101+ const res = node.search('get', '/posts/123')102+ expect(res).not.toBeNull()103+ expect(res?.handlers).toEqual(['common', 'specialized'])104+ expect(res?.params['id']).toBe('123')105+ })106+})107+108+describe('Wildcard', () => {109+ const node = new Node()110+ node.insert('get', '/wildcard-abc/*/wildcard-efg', 'wildcard')111+ it('/wildcard-abc/xxxxxx/wildcard-efg', () => {112+ const res = node.search('get', '/wildcard-abc/xxxxxx/wildcard-efg')113+ expect(res).not.toBeNull()114+ expect(res?.handlers).toEqual(['wildcard'])115+ })116+ node.insert('get', '/wildcard-abc/*/wildcard-efg/hijk', 'wildcard')117+ it('/wildcard-abc/xxxxxx/wildcard-efg/hijk', () => {118+ const res = node.search('get', '/wildcard-abc/xxxxxx/wildcard-efg/hijk')119+ expect(res).not.toBeNull()120+ expect(res?.handlers).toEqual(['wildcard'])121+ })122+})123+124+describe('Regexp', () => {125+ const node = new Node()126+ node.insert('get', '/regex-abc/:id{[0-9]+}/comment/:comment_id{[a-z]+}', 'regexp')127+ it('/regexp-abc/123/comment/abc', () => {128+ const res = node.search('get', '/regex-abc/123/comment/abc')129+ expect(res).not.toBeNull()130+ expect(res?.handlers).toEqual(['regexp'])131+ expect(res?.params['id']).toBe('123')132+ expect(res?.params['comment_id']).toBe('abc')133+ })134+ it('/regexp-abc/abc', () => {135+ const res = node.search('get', '/regex-abc/abc')136+ expect(res).toBeNull()137+ })138+ it('/regexp-abc/123/comment/123', () => {139+ const res = node.search('get', '/regex-abc/123/comment/123')140+ expect(res).toBeNull()141+ })142+})143+144+describe('All', () => {145+ const node = new Node()146+ node.insert('ALL', '/all-methods', 'all methods') // ALL147+ it('/all-methods', () => {148+ let res = node.search('get', '/all-methods')149+ expect(res).not.toBeNull()150+ expect(res?.handlers).toEqual(['all methods'])151+ res = node.search('put', '/all-methods')152+ expect(res).not.toBeNull()153+ expect(res?.handlers).toEqual(['all methods'])154+ })155+})156+157+describe('Special Wildcard', () => {158+ const node = new Node()159+ node.insert('ALL', '*', 'match all')160+161+ it('/foo', () => {162+ const res = node.search('get', '/foo')163+ expect(res).not.toBeNull()164+ expect(res?.handlers).toEqual(['match all'])165+ })166+ it('/hello', () => {167+ const res = node.search('get', '/hello')168+ expect(res).not.toBeNull()169+ expect(res?.handlers).toEqual(['match all'])170+ })171+ it('/hello/foo', () => {172+ const res = node.search('get', '/hello/foo')173+ expect(res).not.toBeNull()174+ expect(res?.handlers).toEqual(['match all'])175+ })176+})177+178+describe('Special Wildcard deeply', () => {179+ const node = new Node()180+ node.insert('ALL', '/hello/*', 'match hello')181+ it('/hello', () => {182+ const res = node.search('get', '/hello')183+ expect(res).not.toBeNull()184+ expect(res?.handlers).toEqual(['match hello'])185+ })186+ it('/hello/foo', () => {187+ const res = node.search('get', '/hello/foo')188+ expect(res).not.toBeNull()189+ expect(res?.handlers).toEqual(['match hello'])190+ })191+})192+193+describe('Default with wildcard', () => {194+ const node = new Node()195+ node.insert('ALL', '/api/*', 'fallback')196+ node.insert('ALL', '/api/abc', 'match api')197+ it('/api/abc', () => {198+ const res = node.search('get', '/api/abc')199+ expect(res).not.toBeNull()200+ expect(res?.handlers).toEqual(['fallback', 'match api'])201+ })202+ it('/api/def', () => {203+ const res = node.search('get', '/api/def')204+ expect(res).not.toBeNull()205+ expect(res?.handlers).toEqual(['fallback'])206+ })207+})208+209+describe('Multi match', () => {210+ describe('Basic', () => {211+ const node = new Node()212+ node.insert('get', '*', 'GET *')213+ node.insert('get', '/abc/*', 'GET /abc/*')214+ node.insert('get', '/abc/*/edf', 'GET /abc/*/edf')215+ node.insert('get', '/abc/edf', 'GET /abc/edf')216+ node.insert('get', '/abc/*/ghi/jkl', 'GET /abc/*/ghi/jkl')217+ it('get /abc/edf', () => {218+ const res = node.search('get', '/abc/edf')219+ expect(res).not.toBeNull()220+ expect(res?.handlers).toEqual(['GET *', 'GET /abc/*', 'GET /abc/edf'])221+ })222+ it('get /abc/xxx/edf', () => {223+ const res = node.search('get', '/abc/xxx/edf')224+ expect(res).not.toBeNull()225+ expect(res?.handlers).toEqual(['GET *', 'GET /abc/*', 'GET /abc/*/edf'])226+ })227+ it('get /', () => {228+ const res = node.search('get', '/')229+ expect(res).not.toBeNull()230+ expect(res?.handlers).toEqual(['GET *'])231+ })232+ it('post /', () => {233+ const res = node.search('post', '/')234+ expect(res).toBeNull()235+ })236+ it('get /abc/edf/ghi', () => {237+ const res = node.search('get', '/abc/edf/ghi')238+ expect(res).not.toBeNull()239+ expect(res?.handlers).toEqual(['GET *', 'GET /abc/*'])240+ })241+ })242+243+ describe('Blog', () => {244+ const node = new Node()245+ node.insert('get', '*', 'middleware a') // 0.1246+ node.insert('ALL', '*', 'middleware b') // 0.2 <===247+ node.insert('get', '/entry', 'get entries') // 1.3248+ node.insert('post', '/entry/*', 'middleware c') // 1.4 <===249+ node.insert('post', '/entry', 'post entry') // 1.5 <===250+ node.insert('get', '/entry/:id', 'get entry') // 2.6251+ node.insert('get', '/entry/:id/comment/:comment_id', 'get comment') // 4.7252+ it('get /entry/123', async () => {253+ const res = node.search('get', '/entry/123')254+ expect(res).not.toBeNull()255+ expect(res?.handlers).toEqual(['middleware a', 'middleware b', 'get entry'])256+ expect(res?.params['id']).toBe('123')257+ })258+ it('get /entry/123/comment/456', async () => {259+ const res = node.search('get', '/entry/123/comment/456')260+ expect(res).not.toBeNull()261+ expect(res?.handlers).toEqual(['middleware a', 'middleware b', 'get comment'])262+ expect(res?.params['id']).toBe('123')263+ expect(res?.params['comment_id']).toBe('456')264+ })265+ it('post /entry', async () => {266+ const res = node.search('post', '/entry')267+ expect(res).not.toBeNull()268+ expect(res?.handlers).toEqual(['middleware b', 'middleware c', 'post entry'])269+ })270+ it('delete /entry', async () => {271+ const res = node.search('delete', '/entry')272+ expect(res).not.toBeNull()273+ expect(res?.handlers).toEqual(['middleware b'])274+ })275+ })276+277+ describe('ALL', () => {278+ const node = new Node()279+ node.insert('ALL', '*', 'ALL *')280+ node.insert('ALL', '/abc/*', 'ALL /abc/*')281+ node.insert('ALL', '/abc/*/def', 'ALL /abc/*/def')282+ it('get /', () => {283+ const res = node.search('get', '/')284+ expect(res).not.toBeNull()285+ expect(res?.handlers).toEqual(['ALL *'])286+ })287+ it('post /abc', () => {288+ const res = node.search('post', '/abc')289+ expect(res).not.toBeNull()290+ expect(res?.handlers).toEqual(['ALL *', 'ALL /abc/*'])291+ })292+ it('delete /abc/xxx/def', () => {293+ const res = node.search('post', '/abc/xxx/def')294+ expect(res).not.toBeNull()295+ expect(res?.handlers).toEqual(['ALL *', 'ALL /abc/*', 'ALL /abc/*/def'])296+ })297+ })298+299+ describe('Regexp', () => {300+ const node = new Node()301+ node.insert('get', '/regex-abc/:id{[0-9]+}/*', 'middleware a')302+ node.insert('get', '/regex-abc/:id{[0-9]+}/def', 'regexp')303+ it('/regexp-abc/123/def', () => {304+ const res = node.search('get', '/regex-abc/123/def')305+ expect(res).not.toBeNull()306+ expect(res?.handlers).toEqual(['middleware a', 'regexp'])307+ expect(res?.params['id']).toBe('123')308+ })309+ it('/regexp-abc/123', () => {310+ const res = node.search('get', '/regex-abc/123/ghi')311+ expect(res).not.toBeNull()312+ expect(res?.handlers).toEqual(['middleware a'])313+ })314+ })315+316+ describe('Trailing slash', () => {317+ const node = new Node()318+ node.insert('get', '/book', 'GET /book')319+ node.insert('get', '/book/:id', 'GET /book/:id')320+ it('get /book', () => {321+ const res = node.search('get', '/book')322+ expect(res).not.toBeNull()323+ })324+ it('get /book/', () => {325+ const res = node.search('get', '/book/')326+ expect(res).toBeNull()327+ })328+ })329+330+ describe('Same path', () => {331+ const node = new Node()332+ node.insert('get', '/hey', 'Middleware A')333+ node.insert('get', '/hey', 'Middleware B')334+ it('get /hey', () => {335+ const res = node.search('get', '/hey')336+ expect(res).not.toBeNull()337+ expect(res?.handlers).toEqual(['Middleware A', 'Middleware B'])338+ })339+ })340+})341+342+describe('Duplicate param name', () => {343+ it('self', () => {344+ const node = new Node()345+ expect(() => {346+ node.insert('get', '/:id/:id', 'foo')347+ }).toThrowError(/Duplicate param name/)348+ })349+350+ it('parent', () => {351+ const node = new Node()352+ node.insert('get', '/:id/:action', 'foo')353+ expect(() => {354+ node.insert('get', '/posts/:id', 'bar')355+ }).toThrowError(/Duplicate param name/)356+ })357+358+ it('child', () => {359+ const node = new Node()360+ node.insert('get', '/posts/:id', 'foo')361+ expect(() => {362+ node.insert('get', '/:id/:action', 'bar')363+ }).toThrowError(/Duplicate param name/)364+ })365+366+ it('hierarchy', () => {367+ const node = new Node()368+ node.insert('get', '/posts/:id/comments/:comment_id', 'foo')369+ expect(() => {370+ node.insert('get', '/posts/:id', 'bar')371+ }).not.toThrowError()372+ })373+374+ it('regular expression', () => {375+ const node = new Node()376+ node.insert('get', '/:id/:action{create|update}', 'foo')377+ expect(() => {378+ node.insert('get', '/:id/:action{delete}', 'bar')379+ }).not.toThrowError()380+ })381+})382+383+describe('Sort Order', () => {384+ describe('Basic', () => {385+ const node = new Node()386+ node.insert('get', '*', 'a')387+ node.insert('get', '/page', '/page')388+ node.insert('get', '/:slug', '/:slug')389+390+ it('get /page', () => {391+ const res = node.search('get', '/page')392+ expect(res).not.toBeNull()393+ expect(res?.handlers).toEqual(['a', '/page', '/:slug'])394+ })395+ })396+397+ describe('With Named path', () => {398+ const node = new Node()399+ node.insert('get', '*', 'a')400+ node.insert('get', '/posts/:id', '/posts/:id')401+ node.insert('get', '/:type/:id', '/:type/:id')402+403+ it('get /posts/123', () => {404+ const res = node.search('get', '/posts/123')405+ expect(res).not.toBeNull()406+ expect(res?.handlers).toEqual(['a', '/posts/:id', '/:type/:id'])407+ })408+ })409+410+ describe('With Wildcards', () => {411+ const node = new Node()412+ node.insert('get', '/api/*', '1st')413+ node.insert('get', '/api/*', '2nd')414+ node.insert('get', '/api/posts/:id', '3rd')415+ node.insert('get', '/api/*', '4th')416+417+ it('get /api/posts/123', () => {418+ const res = node.search('get', '/api/posts/123')419+ expect(res).not.toBeNull()420+ expect(res?.handlers).toEqual(['1st', '2nd', '3rd', '4th'])421+ })422+ })423+424+ describe('With special Wildcard', () => {425+ const node = new Node()426+ node.insert('get', '/posts', '/posts') // 1.1427+ node.insert('get', '/posts/*', '/posts/*') // 1.2428+ node.insert('get', '/posts/:id', '/posts/:id') // 2.3429+430+ it('get /posts', () => {431+ const res = node.search('get', '/posts')432+433+ expect(res).not.toBeNull()434+ expect(res?.handlers).toEqual(['/posts', '/posts/*'])435+ })436+ })437+438+ describe('Complex', () => {439+ const node = new Node()440+ node.insert('get', '/api', 'a') // not match441+ node.insert('get', '/api/*', 'b') // match442+ node.insert('get', '/api/:type', 'c') // not match443+ node.insert('get', '/api/:type/:id', 'd') // match444+ node.insert('get', '/api/posts/:id', 'e') // match445+ node.insert('get', '/api/posts/123', 'f') // match446+ node.insert('get', '/*/*/:id', 'g') // match447+ node.insert('get', '/api/posts/*/comment', 'h') // not match448+ node.insert('get', '*', 'i') // match449+ node.insert('get', '*', 'j') // match450+451+ it('get /api/posts/123', () => {452+ const res = node.search('get', '/api/posts/123')453+ expect(res?.handlers).toEqual(['b', 'd', 'e', 'f', 'g', 'i', 'j'])454+ })455+ })456+457+ describe('Multi match', () => {458+ const node = new Node()459+ node.insert('get', '*', 'GET *') // 0.1460+ node.insert('get', '/abc/*', 'GET /abc/*') // 1.2461+ node.insert('get', '/abc/edf', 'GET /abc/edf') // 2.3462+ node.insert('get', '/abc/*/ghi/jkl', 'GET /abc/*/ghi/jkl') // 4.4463+ it('get /abc/edf', () => {464+ const res = node.search('get', '/abc/edf')465+ expect(res).not.toBeNull()466+ expect(res?.handlers).toEqual(['GET *', 'GET /abc/*', 'GET /abc/edf'])467+ })468+ })469+470+ describe('Multi match', () => {471+ const node = new Node()472+473+ node.insert('get', '/api/*', 'a') // 2.1 for /api/entry474+ node.insert('get', '/api/entry', 'entry') // 2.2475+ node.insert('ALL', '/api/*', 'b') // 2.3 for /api/entry476+477+ it('get /api/entry', async () => {478+ const res = node.search('get', '/api/entry')479+ expect(res).not.toBeNull()480+ expect(res?.handlers).toEqual(['a', 'entry', 'b'])481+ })482+ })483+484+ describe('fallback', () => {485+ describe('Blog - failed', () => {486+ const node = new Node()487+ node.insert('post', '/entry', 'post entry') // 1.1488+ node.insert('post', '/entry/*', 'fallback') // 1.2489+ node.insert('get', '/entry/:id', 'get entry') // 2.3490+ it('post /entry', async () => {491+ const res = node.search('post', '/entry')492+ expect(res).not.toBeNull()493+ expect(res?.handlers).toEqual(['post entry', 'fallback'])494+ })495+ })496+ })497+ describe('page', () => {498+ const node = new Node()499+ node.insert('get', '/page', 'page') // 1.1500+ node.insert('ALL', '/*', 'fallback') // 1.2501+ it('get /page', async () => {502+ const res = node.search('get', '/page')503+ expect(res).not.toBeNull()504+ expect(res?.handlers).toEqual(['page', 'fallback'])505+ })506+ })507+})508+509+describe('star', () => {510+ const node = new Node()511+ node.insert('get', '/', '/')512+ node.insert('get', '/*', '/*')513+ node.insert('get', '*', '*')514+515+ node.insert('get', '/x', '/x')516+ node.insert('get', '/x/*', '/x/*')517+518+ it('top', async () => {519+ const res = node.search('get', '/')520+ expect(res).not.toBeNull()521+ expect(res?.handlers).toEqual(['/', '/*', '*']) // => failed ['*', '/*', '/']522+ })523+524+ it('Under a certain path', async () => {525+ const res = node.search('get', '/x')526+ expect(res).not.toBeNull()527+ expect(res?.handlers).toEqual(['/*', '*', '/x', '/x/*'])528+ })529+})added:deno_dist/router/trie-router/node.ts+203 added
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'5+6+type HandlerSet<T> = {7+ handler: T8+ score: number9+ name: string // For debug10+}11+12+function findParam<T>(node: Node<T>, name: string): boolean {13+ for (let i = 0, len = node.patterns.length; i < len; i++) {14+ if (typeof node.patterns[i] === 'object' && node.patterns[i][1] === name) {15+ return true16+ }17+ }18+ const nodes = Object.values(node.children)19+ for (let i = 0, len = nodes.length; i < len; i++) {20+ if (findParam(nodes[i], name)) {21+ return true22+ }23+ }24+25+ return false26+}27+28+export class Node<T> {29+ methods: Record<string, HandlerSet<T>>[]30+31+ children: Record<string, Node<T>>32+ patterns: Pattern[]33+ order: number = 034+ name: string35+ handlerSetCache: Record<string, HandlerSet<T>[]>36+37+ constructor(method?: string, handler?: T, children?: Record<string, Node<T>>) {38+ this.children = children || {}39+ this.methods = []40+ this.name = ''41+ if (method && handler) {42+ const m: Record<string, HandlerSet<T>> = {}43+ m[method] = { handler: handler, score: 0, name: this.name }44+ this.methods = [m]45+ }46+ this.patterns = []47+ this.handlerSetCache = {}48+ }49+50+ insert(method: string, path: string, handler: T): Node<T> {51+ this.name = `${method} ${path}`52+ this.order = ++this.order53+54+ // eslint-disable-next-line @typescript-eslint/no-this-alias55+ let curNode: Node<T> = this56+ const parts = splitPath(path)57+58+ const parentPatterns: Pattern[] = []59+60+ const errorMessage = (name: string): string => {61+ return `Duplicate param name, use another name instead of '${name}' - ${method} ${path} <--- '${name}'`62+ }63+64+ for (let i = 0, len = parts.length; i < len; i++) {65+ const p: string = parts[i]66+67+ if (Object.keys(curNode.children).includes(p)) {68+ parentPatterns.push(...curNode.patterns)69+ curNode = curNode.children[p]70+ continue71+ }72+73+ curNode.children[p] = new Node()74+75+ const pattern = getPattern(p)76+ if (pattern) {77+ if (typeof pattern === 'object') {78+ for (let j = 0, len = parentPatterns.length; j < len; j++) {79+ if (typeof parentPatterns[j] === 'object' && parentPatterns[j][1] === pattern[1]) {80+ throw new Error(errorMessage(pattern[1]))81+ }82+ }83+ if (Object.values(curNode.children).some((n) => findParam(n, pattern[1]))) {84+ throw new Error(errorMessage(pattern[1]))85+ }86+ }87+ curNode.patterns.push(pattern)88+ parentPatterns.push(...curNode.patterns)89+ }90+91+ parentPatterns.push(...curNode.patterns)92+ curNode = curNode.children[p]93+ }94+95+ if (!curNode.methods.length) {96+ curNode.methods = []97+ }98+99+ const m: Record<string, HandlerSet<T>> = {}100+101+ const handlerSet: HandlerSet<T> = { handler: handler, name: this.name, score: this.order }102+103+ m[method] = handlerSet104+ curNode.methods.push(m)105+106+ return curNode107+ }108+109+ private getHandlerSets(node: Node<T>, method: string, wildcard?: boolean): HandlerSet<T>[] {110+ return (node.handlerSetCache[`${method}:${wildcard ? '1' : '0'}`] ||= (() => {111+ const handlerSets: HandlerSet<T>[] = []112+ node.methods.map((m) => {113+ const handlerSet = m[method] || m[METHOD_NAME_ALL]114+ if (handlerSet !== undefined) {115+ const hs = { ...handlerSet }116+ handlerSets.push(hs)117+ return118+ }119+ })120+121+ return handlerSets122+ })())123+ }124+125+ search(method: string, path: string): Result<T> | null {126+ const handlerSets: HandlerSet<T>[] = []127+ const params: Record<string, string> = {}128+129+ // eslint-disable-next-line @typescript-eslint/no-this-alias130+ const curNode: Node<T> = this131+ let curNodes = [curNode]132+ const parts = splitPath(path)133+134+ for (let i = 0, len = parts.length; i < len; i++) {135+ const part: string = parts[i]136+ const isLast = i === len - 1137+ const tempNodes: Node<T>[] = []138+139+ for (let j = 0, len2 = curNodes.length; j < len2; j++) {140+ const node = curNodes[j]141+142+ for (let k = 0, len3 = node.patterns.length; k < len3; k++) {143+ const pattern = node.patterns[k]144+145+ // Wildcard146+ // '/hello/*/foo' => match /hello/bar/foo147+ if (pattern === '*') {148+ const astNode = node.children['*']149+ if (astNode) {150+ handlerSets.push(...this.getHandlerSets(astNode, method))151+ tempNodes.push(astNode)152+ }153+ continue154+ }155+156+ if (part === '') continue157+158+ // Named match159+ // `/posts/:id` => match /posts/123160+ const [key, name, matcher] = pattern161+ if (matcher === true || (matcher instanceof RegExp && matcher.test(part))) {162+ if (typeof key === 'string') {163+ if (isLast === true) {164+ handlerSets.push(...this.getHandlerSets(node.children[key], method))165+ }166+ tempNodes.push(node.children[key])167+ }168+ if (typeof name === 'string') {169+ params[name] = part170+ }171+ }172+ }173+174+ const nextNode = node.children[part]175+176+ if (nextNode) {177+ if (isLast === true) {178+ // '/hello/*' => match '/hello'179+ if (nextNode.children['*']) {180+ handlerSets.push(...this.getHandlerSets(nextNode.children['*'], method, true))181+ }182+ handlerSets.push(...this.getHandlerSets(nextNode, method))183+ }184+ tempNodes.push(nextNode)185+ }186+ }187+188+ curNodes = tempNodes189+ }190+191+ if (handlerSets.length <= 0) return null192+193+ const handlers = handlerSets194+ .sort((a, b) => {195+ return a.score - b.score196+ })197+ .map((s) => {198+ return s.handler199+ })200+201+ return { handlers, params }202+ }203+}added:deno_dist/router/trie-router/router.test.ts+131 added
1+import { TrieRouter } from './router.ts'2+3+describe('Basic Usage', () => {4+ const router = new TrieRouter<string>()5+6+ router.add('GET', '/hello', 'get hello')7+ router.add('POST', '/hello', 'post hello')8+9+ it('get, post hello', async () => {10+ let res = router.match('GET', '/hello')11+ expect(res).not.toBeNull()12+ expect(res?.handlers).toEqual(['get hello'])13+14+ res = router.match('POST', '/hello')15+ expect(res).not.toBeNull()16+ expect(res?.handlers).toEqual(['post hello'])17+18+ res = router.match('PUT', '/hello')19+ expect(res).toBeNull()20+21+ res = router.match('GET', '/')22+ expect(res).toBeNull()23+ })24+})25+26+describe('Complex', () => {27+ const router = new TrieRouter<string>()28+29+ it('Named Param', async () => {30+ router.add('GET', '/entry/:id', 'get entry')31+ const res = router.match('GET', '/entry/123')32+ expect(res).not.toBeNull()33+ expect(res?.handlers).toEqual(['get entry'])34+ expect(res?.params['id']).toBe('123')35+ })36+37+ it('Wildcard', async () => {38+ router.add('GET', '/wild/*/card', 'get wildcard')39+ const res = router.match('GET', '/wild/xxx/card')40+ expect(res).not.toBeNull()41+ expect(res?.handlers).toEqual(['get wildcard'])42+ })43+44+ it('Default', async () => {45+ router.add('GET', '/api/*', 'fallback')46+ router.add('GET', '/api/abc', 'get api')47+ let res = router.match('GET', '/api/abc')48+ expect(res).not.toBeNull()49+ expect(res?.handlers).toEqual(['fallback', 'get api'])50+ res = router.match('GET', '/api/def')51+ expect(res).not.toBeNull()52+ expect(res?.handlers).toEqual(['fallback'])53+ })54+55+ it('Regexp', async () => {56+ router.add('GET', '/post/:date{[0-9]+}/:title{[a-z]+}', 'get post')57+ let res = router.match('GET', '/post/20210101/hello')58+ expect(res).not.toBeNull()59+ expect(res?.handlers).toEqual(['get post'])60+ expect(res?.params['date']).toBe('20210101')61+ expect(res?.params['title']).toBe('hello')62+ res = router.match('GET', '/post/onetwothree')63+ expect(res).toBeNull()64+ res = router.match('GET', '/post/123/123')65+ expect(res).toBeNull()66+ })67+})68+69+describe('Multi match', () => {70+ const router = new TrieRouter<string>()71+72+ describe('Blog', () => {73+ router.add('ALL', '*', 'middleware a')74+ router.add('GET', '*', 'middleware b')75+ router.add('GET', '/entry', 'get entries')76+ router.add('POST', '/entry/*', 'middleware c')77+ router.add('POST', '/entry', 'post entry')78+ router.add('GET', '/entry/:id', 'get entry')79+ router.add('GET', '/entry/:id/comment/:comment_id', 'get comment')80+ it('GET /', async () => {81+ const res = router.match('GET', '/')82+ expect(res).not.toBeNull()83+ expect(res?.handlers).toEqual(['middleware a', 'middleware b'])84+ })85+ it('GET /entry/123', async () => {86+ const res = router.match('GET', '/entry/123')87+ expect(res).not.toBeNull()88+ expect(res?.handlers).toEqual(['middleware a', 'middleware b', 'get entry'])89+ expect(res?.params['id']).toBe('123')90+ })91+ it('GET /entry/123/comment/456', async () => {92+ const res = router.match('GET', '/entry/123/comment/456')93+ expect(res).not.toBeNull()94+ expect(res?.handlers).toEqual(['middleware a', 'middleware b', 'get comment'])95+ expect(res?.params['id']).toBe('123')96+ expect(res?.params['comment_id']).toBe('456')97+ })98+ it('POST /entry', async () => {99+ const res = router.match('POST', '/entry')100+ expect(res).not.toBeNull()101+ expect(res?.handlers).toEqual(['middleware a', 'middleware c', 'post entry'])102+ })103+ it('DELETE /entry', async () => {104+ const res = router.match('DELETE', '/entry')105+ expect(res).not.toBeNull()106+ expect(res?.handlers).toEqual(['middleware a'])107+ })108+ })109+})110+111+describe('Fallback', () => {112+ const router = new TrieRouter<string>()113+ router.add('POST', '/entry', 'post entry')114+ router.add('POST', '/entry/*', 'fallback')115+ router.add('GET', '/entry/:id', 'get entry')116+ it('POST /entry', async () => {117+ const res = router.match('POST', '/entry')118+ expect(res).not.toBeNull()119+ expect(res?.handlers).toEqual(['post entry', 'fallback'])120+ })121+})122+123+describe('page', () => {124+ const router = new TrieRouter<string>()125+ router.add('GET', '/page', 'page')126+ router.add('ALL', '*', 'fallback') // or '*'127+ it('GET /page', async () => {128+ const res = router.match('GET', '/page')129+ expect(res?.handlers).toEqual(['page', 'fallback'])130+ })131+})added:deno_dist/router/trie-router/router.ts+18 added
1+import type { Result, Router } from '../../router.ts'2+import { Node } from './node.ts'3+4+export class TrieRouter<T> implements Router<T> {5+ node: Node<T>6+7+ constructor() {8+ this.node = new Node()9+ }10+11+ add(method: string, path: string, handler: T) {12+ this.node.insert(method, path, handler)13+ }14+15+ match(method: string, path: string): Result<T> | null {16+ return this.node.search(method, path)17+ }18+}added:deno_dist/utils/jwt/index.ts+1 added
1+export * as Jwt from './jwt.ts'added:deno_dist/utils/jwt/jwt.test.ts+173 added
1+/* eslint-disable @typescript-eslint/ban-ts-comment */2+import * as JWT from './jwt.ts'3+import {4+ AlgorithmTypes,5+ JwtTokenSignatureMismatched,6+ JwtAlorithmNotImplemented,7+ JwtTokenInvalid,8+ JwtTokenNotBefore,9+ JwtTokenExpired,10+} from './types.ts'11+12+describe('JWT', () => {13+ it('JwtAlorithmNotImplemented', async () => {14+ const payload = { message: 'hello world' }15+ const secret = 'a-secret'16+ const alg = ''17+ let tok = ''18+ let err: JwtAlorithmNotImplemented19+ try {20+ tok = await JWT.sign(payload, secret, alg as AlgorithmTypes)21+ } catch (e) {22+ err = e as JwtAlorithmNotImplemented23+ }24+ expect(tok).toBe('')25+ // @ts-ignore26+ expect(err).toEqual(new JwtAlorithmNotImplemented(alg))27+ })28+29+ it('JwtTokenInvalid', async () => {30+ const tok = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ'31+ const secret = 'a-secret'32+ let err: JwtTokenInvalid33+ let authorized = false34+ try {35+ authorized = await JWT.verify(tok, secret, AlgorithmTypes.HS256)36+ } catch (e) {37+ err = e as JwtTokenInvalid38+ }39+ // @ts-ignore40+ expect(err).toEqual(new JwtTokenInvalid(tok))41+ expect(authorized).toBe(false)42+ })43+44+ it('JwtTokenNotBefore', async () => {45+ const tok =46+ 'eyJraWQiOiJFemF7bVZWbnd0TUpUNEFveFVtT0dILWJ0Y2VUVFM3djBYcEJuMm5ZZ2VjIiwiYWxnIjoiSFMyNTYifQ.eyJyb2xlIjoiYXBpX3JvbGUiLCJuYmYiOjE2NjQ1ODI0MDB9.BatadbUj5e41OZ33odEFTAndQFzX0w9aAgpQPgO-zaQ'47+ const secret = 'a-secret'48+ let err: JwtTokenNotBefore49+ let authorized = false50+ try {51+ authorized = await JWT.verify(tok, secret, AlgorithmTypes.HS256)52+ } catch (e) {53+ err = e as JwtTokenNotBefore54+ }55+ // @ts-ignore56+ expect(err).toEqual(new JwtTokenNotBefore(tok))57+ expect(authorized).toBe(false)58+ })59+60+ it('JwtTokenExpired', async () => {61+ const tok =62+ 'eyJraWQiOiJFemF6bVZWbnd0TUpUNEFveFVtT0dILWJ0Y2VUVFM3djBYcEJuMm5ZZ2VjIiwiYWxnIjoiSFMyNTYifQ.eyJyb2xlIjoiYXBpX3JvbGUiLCJleHAiOjE2MzMwNDY0MDB9.Gmq_dozOnwzqkMUMEm7uny7cMZuF1d0QkCnmRXAbTEk'63+ const secret = 'a-secret'64+ let err65+ let authorized = false66+ try {67+ authorized = await JWT.verify(tok, secret, AlgorithmTypes.HS256)68+ } catch (e) {69+ err = e70+ }71+ expect(err).toEqual(new JwtTokenExpired(tok))72+ expect(authorized).toBe(false)73+ })74+75+ it('HS256 sign & verify & decode', async () => {76+ const payload = { message: 'hello world' }77+ const secret = 'a-secret'78+ const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS256)79+ const expected =80+ 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'81+ expect(tok).toEqual(expected)82+83+ expect(await JWT.verify(tok, secret, AlgorithmTypes.HS256)).toBe(true)84+85+ expect(JWT.decode(tok)).toEqual({86+ header: {87+ alg: 'HS256',88+ typ: 'JWT',89+ },90+ payload: {91+ message: 'hello world',92+ },93+ })94+ })95+96+ it('HS256 sign & verify', async () => {97+ const payload = { message: 'hello world' }98+ const secret = 'a-secret'99+ const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS256)100+ const expected =101+ 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'102+ expect(tok).toEqual(expected)103+104+ let err = null105+ let authorized = false106+ try {107+ authorized = await JWT.verify(tok, secret + 'invalid', AlgorithmTypes.HS256)108+ } catch (e) {109+ err = e110+ }111+ expect(authorized).toBe(false)112+ expect(err instanceof JwtTokenSignatureMismatched).toBe(true)113+ })114+115+ it('HS512 sign & verify & decode', async () => {116+ const payload = { message: 'hello world' }117+ const secret = 'a-secret'118+ const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS512)119+ const expected =120+ 'eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.RqVLgExB_GXF1-9T-k4V4HjFmiuQKTEjVSiZd-YL0WERIlywZ7PfzAuTZSJU4gg8cscGamQa030cieEWrYcywg'121+ expect(tok).toEqual(expected)122+123+ expect(await JWT.verify(tok, secret, AlgorithmTypes.HS512)).toBe(true)124+125+ expect(JWT.decode(tok)).toEqual({126+ header: {127+ alg: 'HS512',128+ typ: 'JWT',129+ },130+ payload: {131+ message: 'hello world',132+ },133+ })134+ })135+136+ it('HS512 sign & verify', async () => {137+ const payload = { message: 'hello world' }138+ const secret = 'a-secret'139+ const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS512)140+ const expected =141+ 'eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.RqVLgExB_GXF1-9T-k4V4HjFmiuQKTEjVSiZd-YL0WERIlywZ7PfzAuTZSJU4gg8cscGamQa030cieEWrYcywg'142+ expect(tok).toEqual(expected)143+144+ let err = null145+ let authorized = false146+ try {147+ authorized = await JWT.verify(tok, secret + 'invalid', AlgorithmTypes.HS256)148+ } catch (e) {149+ err = e150+ }151+ expect(authorized).toBe(false)152+ expect(err instanceof JwtTokenSignatureMismatched).toBe(true)153+ })154+155+ it('HS384 sign & verify', async () => {156+ const payload = { message: 'hello world' }157+ const secret = 'a-secret%你好'158+ const tok = await JWT.sign(payload, secret, AlgorithmTypes.HS384)159+ const expected =160+ 'eyJhbGciOiJIUzM4NCIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.C1Br1183Oy6O7th4NDCOaI9WB75i3FMCuYlv1tCL9HggsU89T-SNutghwhJykD3r'161+ expect(tok).toEqual(expected)162+163+ let err = null164+ let authorized = false165+ try {166+ authorized = await JWT.verify(tok, secret + 'invalid', AlgorithmTypes.HS256)167+ } catch (e) {168+ err = e169+ }170+ expect(authorized).toBe(false)171+ expect(err instanceof JwtTokenSignatureMismatched).toBe(true)172+ })173+})added:deno_dist/utils/jwt/jwt.ts+141 added
1+import {2+ utf8ToUint8Array,3+ encodeBase64URL,4+ arrayBufferToBase64URL,5+ decodeBase64URL,6+} from '../../utils/encode.ts'7+import { AlgorithmTypes } from './types.ts'8+import {9+ JwtTokenInvalid,10+ JwtTokenNotBefore,11+ JwtTokenExpired,12+ JwtTokenSignatureMismatched,13+ JwtAlorithmNotImplemented,14+} from './types.ts'15+16+interface AlgorithmParams {17+ name: string18+ namedCurve?: string19+ hash?: {20+ name: string21+ }22+}23+24+enum CryptoKeyFormat {25+ RAW = 'raw',26+ PKCS8 = 'pkcs8',27+ SPKI = 'spki',28+ JWK = 'jwk',29+}30+31+enum CryptoKeyUsage {32+ Ecrypt = 'encrypt',33+ Decrypt = 'decrypt',34+ Sign = 'sign',35+ Verify = 'verify',36+ Deriverkey = 'deriveKey',37+ DeriveBits = 'deriveBits',38+ WrapKey = 'wrapKey',39+ UnwrapKey = 'unwrapKey',40+}41+42+const param = (name: AlgorithmTypes): AlgorithmParams => {43+ switch (name.toUpperCase()) {44+ case 'HS256':45+ return {46+ name: 'HMAC',47+ hash: {48+ name: 'SHA-256',49+ },50+ }51+ case 'HS384':52+ return {53+ name: 'HMAC',54+ hash: {55+ name: 'SHA-384',56+ },57+ }58+ case 'HS512':59+ return {60+ name: 'HMAC',61+ hash: {62+ name: 'SHA-512',63+ },64+ }65+ default:66+ throw new JwtAlorithmNotImplemented(name)67+ }68+}69+70+const signing = async (71+ data: string,72+ secret: string,73+ alg: AlgorithmTypes = AlgorithmTypes.HS25674+): Promise<ArrayBuffer> => {75+ const cryptoKey = await crypto.subtle.importKey(76+ CryptoKeyFormat.RAW,77+ utf8ToUint8Array(secret),78+ param(alg),79+ false,80+ [CryptoKeyUsage.Sign]81+ )82+ return await crypto.subtle.sign(param(alg), cryptoKey, utf8ToUint8Array(data))83+}84+85+export const sign = async (86+ payload: unknown,87+ secret: string,88+ alg: AlgorithmTypes = AlgorithmTypes.HS25689+): Promise<string> => {90+ const encodedPayload = await encodeBase64URL(JSON.stringify(payload))91+ const encodedHeader = await encodeBase64URL(JSON.stringify({ alg, typ: 'JWT' }))92+93+ const partialToken = `${encodedHeader}.${encodedPayload}`94+95+ const signature: string = await arrayBufferToBase64URL(await signing(partialToken, secret, alg))96+97+ return `${partialToken}.${signature}`98+}99+100+export const verify = async (101+ token: string,102+ secret: string,103+ alg: AlgorithmTypes = AlgorithmTypes.HS256104+): Promise<boolean> => {105+ const tokenParts = token.split('.')106+ if (tokenParts.length !== 3) {107+ throw new JwtTokenInvalid(token)108+ }109+110+ const { payload } = decode(token)111+ if (payload.nbf && payload.nbf > Math.floor(Date.now() / 1000)) {112+ throw new JwtTokenNotBefore(token)113+ }114+ if (payload.exp && payload.exp <= Math.floor(Date.now() / 1000)) {115+ throw new JwtTokenExpired(token)116+ }117+118+ const signature: string = await arrayBufferToBase64URL(119+ await signing(tokenParts.slice(0, 2).join('.'), secret, alg)120+ )121+ if (signature !== tokenParts[2]) {122+ throw new JwtTokenSignatureMismatched(token)123+ }124+125+ return true126+}127+128+// eslint-disable-next-line129+export const decode = (token: string): { header: any; payload: any } => {130+ try {131+ const [h, p] = token.split('.')132+ const header = JSON.parse(decodeBase64URL(h))133+ const payload = JSON.parse(decodeBase64URL(p))134+ return {135+ header,136+ payload,137+ }138+ } catch (e) {139+ throw new JwtTokenInvalid(token)140+ }141+}added:deno_dist/utils/jwt/types.test.ts+13 added
1+import { AlgorithmTypes } from './types.ts'2+3+describe('Types', () => {4+ it('AlgorithmTypes', () => {5+ expect('HS256' as AlgorithmTypes).toBe(AlgorithmTypes.HS256)6+ expect('HS384' as AlgorithmTypes).toBe(AlgorithmTypes.HS384)7+ expect('HS512' as AlgorithmTypes).toBe(AlgorithmTypes.HS512)8+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment9+ // @ts-ignore10+ expect(undefined as AlgorithmTypes).toBe(undefined)11+ expect('' as AlgorithmTypes).toBe('')12+ })13+})added:deno_dist/utils/jwt/types.ts+41 added
1+export class JwtAlorithmNotImplemented extends Error {2+ constructor(token: string) {3+ super(`invalid JWT token: ${token}`)4+ this.name = 'JwtAlorithmNotImplemented'5+ }6+}7+8+export class JwtTokenInvalid extends Error {9+ constructor(token: string) {10+ super(`invalid JWT token: ${token}`)11+ this.name = 'JwtTokenInvalid'12+ }13+}14+15+export class JwtTokenNotBefore extends Error {16+ constructor(token: string) {17+ super(`token (${token}) is being used before it's valid`)18+ this.name = 'JwtTokenNotBefore'19+ }20+}21+22+export class JwtTokenExpired extends Error {23+ constructor(token: string) {24+ super(`token (${token}) expired`)25+ this.name = 'JwtTokenExpired'26+ }27+}28+29+export class JwtTokenSignatureMismatched extends Error {30+ constructor(token: string) {31+ super(`token(${token}) signature mismatched`)32+ this.name = 'JwtTokenSignatureMismatched'33+ }34+}35+36+export enum AlgorithmTypes {37+ HS256 = 'HS256',38+ HS384 = 'HS384',39+ HS512 = 'HS512',40+}41+added:deno_dist/utils/body.test.ts+47 added
1+import { parseBody } from './body.ts'2+3+describe('Parse Body Middleware', () => {4+ it('should parse JSON', async () => {5+ const payload = { message: 'hello hono' }6+ const req = new Request('http://localhost/json', {7+ method: 'POST',8+ body: JSON.stringify(payload),9+ headers: new Headers({ 'Content-Type': 'application/json' }),10+ })11+ expect(await parseBody(req)).toEqual(payload)12+ })13+14+ it('should parse Text', async () => {15+ const payload = 'hello'16+ const req = new Request('http://localhost/text', {17+ method: 'POST',18+ body: 'hello',19+ headers: new Headers({ 'Content-Type': 'application/text' }),20+ })21+ expect(await parseBody(req)).toEqual(payload)22+ })23+24+ it('should parse Form', async () => {25+ const formData = new URLSearchParams()26+ formData.append('message', 'hello')27+ const req = new Request('https://localhost/form', {28+ method: 'POST',29+ body: formData,30+ headers: {31+ 'Content-Type': 'application/x-www-form-urlencoded',32+ },33+ })34+ expect(await parseBody(req)).toEqual({ message: 'hello' })35+ })36+37+ it('should parse Response body ', async () => {38+ const payload = 'hello'39+ const res = new Response(payload, {40+ headers: {41+ 'Content-Type': 'text/plain',42+ },43+ })44+ console.log(res.headers.get('Content-Type'))45+ expect(await parseBody(res)).toEqual(payload)46+ })47+})added:deno_dist/utils/body.ts+22 added
1+export const parseBody = async (2+ r: Request | Response3+): Promise<string | object | Record<string, string | File>> => {4+ const contentType = r.headers.get('Content-Type') || ''5+6+ if (contentType.includes('application/json')) {7+ return await r.json()8+ } else if (contentType.includes('application/text')) {9+ return await r.text()10+ } else if (contentType.startsWith('text')) {11+ return await r.text()12+ } else if (contentType.includes('form')) {13+ const form: Record<string, string | File> = {}14+ const data = [...(await r.formData())].reduce((acc, cur) => {15+ acc[cur[0]] = cur[1]16+ return acc17+ }, form)18+ return data19+ }20+21+ return r.arrayBuffer()22+}added:deno_dist/utils/buffer.test.ts+55 added
1+import { SHA256 as sha256CryptoJS } from 'crypto-js DENOIFY: DEPENDENCY UNMET (DEV DEPENDENCY)'2+import { timingSafeEqual, bufferToString } from './buffer.ts'3+4+describe('buffer', () => {5+ it('positive', async () => {6+ expect(7+ await timingSafeEqual(8+ '127e6fbfe24a750e72930c220a8e138275656b8e5d8f48a98c3c92df2caba935',9+ '127e6fbfe24a750e72930c220a8e138275656b8e5d8f48a98c3c92df2caba935'10+ )11+ ).toBe(true)12+ expect(await timingSafeEqual('a', 'a')).toBe(true)13+ expect(await timingSafeEqual('', '')).toBe(true)14+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment15+ // @ts-ignore16+ expect(await timingSafeEqual(undefined, undefined)).toBe(true)17+ expect(await timingSafeEqual(true, true)).toBe(true)18+ expect(await timingSafeEqual(false, false)).toBe(true)19+ expect(await timingSafeEqual(true, true, (d: string) => sha256CryptoJS(d).toString()))20+ })21+22+ it('negative', async () => {23+ expect(await timingSafeEqual('a', 'b')).toBe(false)24+ expect(25+ await timingSafeEqual('a', 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa')26+ ).toBe(false)27+ expect(28+ await timingSafeEqual('aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', 'a')29+ ).toBe(false)30+ expect(await timingSafeEqual('alpha', 'beta')).toBe(false)31+ expect(await timingSafeEqual(false, true)).toBe(false)32+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment33+ // @ts-ignore34+ expect(await timingSafeEqual(false, undefined)).toBe(false)35+ expect(36+ await timingSafeEqual(37+ () => {},38+ () => {}39+ )40+ ).toBe(false)41+ expect(await timingSafeEqual({}, {})).toBe(false)42+ expect(await timingSafeEqual({ a: 1 }, { a: 1 })).toBe(false)43+ expect(await timingSafeEqual({ a: 1 }, { a: 2 })).toBe(false)44+ expect(await timingSafeEqual([1, 2], [1, 2])).toBe(false)45+ expect(await timingSafeEqual([1, 2], [1, 2, 3])).toBe(false)46+ })47+})48+49+describe('bufferToString', () => {50+ it('Should return あいうえお', () => {51+ const bytes = [227, 129, 130, 227, 129, 132, 227, 129, 134, 227, 129, 136, 227, 129, 138]52+ const buffer = Uint8Array.from(bytes).buffer53+ expect(bufferToString(buffer)).toBe('あいうえお')54+ })55+})added:deno_dist/utils/buffer.ts+43 added
1+import { sha256 } from './crypto.ts'2+3+export const equal = (a: ArrayBuffer, b: ArrayBuffer) => {4+ if (a === b) {5+ return true6+ }7+ if (a.byteLength !== b.byteLength) {8+ return false9+ }10+11+ const va = new DataView(a)12+ const vb = new DataView(b)13+14+ let i = va.byteLength15+ while (i--) {16+ if (va.getUint8(i) !== vb.getUint8(i)) {17+ return false18+ }19+ }20+21+ return true22+}23+24+export const timingSafeEqual = async (25+ a: string | object | boolean,26+ b: string | object | boolean,27+ hashFunction?: Function28+) => {29+ if (!hashFunction) {30+ hashFunction = sha25631+ }32+ const sa = await hashFunction(a)33+ const sb = await hashFunction(b)34+ return sa === sb && a === b35+}36+37+export const bufferToString = (buffer: ArrayBuffer): string => {38+ if (buffer instanceof ArrayBuffer) {39+ const enc = new TextDecoder('utf-8')40+ return enc.decode(buffer)41+ }42+ return buffer43+}added:deno_dist/utils/cloudflare.test.ts+49 added
1+import { getContentFromKVAsset, getKVFilePath } from './cloudflare.ts'2+3+// Mock4+const store: { [key: string]: string } = {5+ 'index.abcdef.html': 'This is index',6+ 'assets/static/plain.abcdef.txt': 'Asset text',7+}8+const manifest = JSON.stringify({9+ 'index.html': 'index.abcdef.html',10+ 'assets/static/plain.txt': 'assets/static/plain.abcdef.txt',11+})12+13+Object.assign(global, { __STATIC_CONTENT_MANIFEST: manifest })14+Object.assign(global, {15+ __STATIC_CONTENT: {16+ get: (path: string) => {17+ return store[path]18+ },19+ },20+})21+22+describe('Utils for Cloudflare Workers', () => {23+ it('getContentFromKVAsset', async () => {24+ let content = await getContentFromKVAsset('not-found.txt')25+ expect(content).toBeUndefined()26+ content = await getContentFromKVAsset('index.html')27+ expect(content).not.toBeUndefined()28+ expect(content).toBe('This is index')29+ content = await getContentFromKVAsset('assets/static/plain.txt')30+ expect(content).not.toBeUndefined()31+ expect(content).toBe('Asset text')32+ })33+34+ it('getKVFilePath', async () => {35+ expect(getKVFilePath({ filename: 'foo' })).toBe('foo/index.html')36+ expect(getKVFilePath({ filename: 'foo.txt' })).toBe('foo.txt')37+38+ expect(getKVFilePath({ filename: 'foo', root: 'bar' })).toBe('bar/foo/index.html')39+ expect(getKVFilePath({ filename: 'foo.txt', root: 'bar' })).toBe('bar/foo.txt')40+41+ expect(getKVFilePath({ filename: 'foo', defaultDocument: 'index.txt' })).toBe('foo/index.txt')42+ expect(getKVFilePath({ filename: 'foo', root: 'bar', defaultDocument: 'index.txt' })).toBe(43+ 'bar/foo/index.txt'44+ )45+46+ expect(getKVFilePath({ filename: './foo' })).toBe('foo/index.html')47+ expect(getKVFilePath({ filename: 'foo', root: './bar' })).toBe('bar/foo/index.html')48+ })49+})added:deno_dist/utils/cloudflare.ts+79 added
1+declare const __STATIC_CONTENT: KVNamespace2+declare const __STATIC_CONTENT_MANIFEST: string3+4+export type KVAssetOptions = {5+ manifest?: object | string6+ namespace?: KVNamespace7+}8+9+export const getContentFromKVAsset = async (10+ path: string,11+ options?: KVAssetOptions12+): Promise<ArrayBuffer | null> => {13+ let ASSET_MANIFEST: Record<string, string> = {}14+15+ if (options && options.manifest) {16+ if (typeof options.manifest === 'string') {17+ ASSET_MANIFEST = JSON.parse(options.manifest)18+ } else {19+ ASSET_MANIFEST = options.manifest as Record<string, string>20+ }21+ } else {22+ if (typeof __STATIC_CONTENT_MANIFEST === 'string') {23+ ASSET_MANIFEST = JSON.parse(__STATIC_CONTENT_MANIFEST)24+ } else {25+ ASSET_MANIFEST = __STATIC_CONTENT_MANIFEST26+ }27+ }28+29+ let ASSET_NAMESPACE: KVNamespace30+ if (options && options.namespace) {31+ ASSET_NAMESPACE = options.namespace32+ } else {33+ ASSET_NAMESPACE = __STATIC_CONTENT34+ }35+36+ const key = ASSET_MANIFEST[path] || path37+ if (!key) {38+ return null39+ }40+41+ let content = await ASSET_NAMESPACE.get(key, { type: 'arrayBuffer' })42+43+ if (content) {44+ content = content as ArrayBuffer45+ }46+ return content47+}48+49+type FilePathOptions = {50+ filename: string51+ root?: string52+ defaultDocument?: string53+}54+55+export const getKVFilePath = (options: FilePathOptions): string => {56+ let filename = options.filename57+ let root = options.root || ''58+ const defaultDocument = options.defaultDocument || 'index.html'59+60+ if (filename.endsWith('/')) {61+ // /top/ => /top/index.html62+ filename = filename.concat(defaultDocument)63+ } else if (!filename.match(/\.[a-zA-Z0-9]+$/)) {64+ // /top => /top/index.html65+ filename = filename.concat('/' + defaultDocument)66+ }67+68+ // /foo.html => foo.html69+ filename = filename.replace(/^\.?\//, '')70+71+ // assets/ => assets72+ root = root.replace(/\/$/, '')73+74+ // ./assets/foo.html => assets/foo.html75+ let path = root ? root + '/' + filename : filename76+ path = path.replace(/^\.?\//, '')77+78+ return path79+}added:deno_dist/utils/crypto.test.ts+25 added
1+import { sha256, sha1, md5 } from './crypto.ts'2+3+describe('crypto', () => {4+ it('sha256', async () => {5+ expect(await sha256('hono')).toBe(6+ '8b3dc17add91b7e8f0b5109a389927d66001139cd9b03fa7b95f83126e1b2b23'7+ )8+ expect(await sha256('炎')).toBe(9+ '1fddc5a562ee1fbeb4fc6def7d4be4911fcdae4273b02ae3a507b170ba0ea169'10+ )11+ expect(await sha256('abcdedf')).not.toBe('abcdef')12+ })13+14+ it('sha1', async () => {15+ expect(await sha1('hono')).toBe('28c7e86f5732391917876b45c06c626c04d77f39')16+ expect(await sha1('炎')).toBe('d56e09ae2421b2b8a0b5ee5fdceaed663c8c9472')17+ expect(await sha1('abcdedf')).not.toBe('abcdef')18+ })19+ 20+ it('md5', async () => {21+ expect(await md5('hono')).toBe('cf22a160789a91dd5f737cd3b2640cc2')22+ expect(await md5('炎')).toBe('f620d89a5a782c22b4420acb39121be3')23+ expect(await md5('abcdedf')).not.toBe('abcdef')24+ })25+})added:deno_dist/utils/crypto.ts+40 added
1+type Algorithm = {2+ name: string3+ alias: string4+}5+6+type Data = string | object | boolean7+8+export const sha256 = async (data: Data) => {9+ const algorithm: Algorithm = { name: 'SHA-256', alias: 'sha256' }10+ const hash = await createHash(data, algorithm)11+ return hash12+}13+14+export const sha1 = async (data: Data) => {15+ const algorithm: Algorithm = { name: 'SHA-1', alias: 'sha1' }16+ const hash = await createHash(data, algorithm)17+ return hash18+}19+20+export const md5 = async (data: Data) => {21+ const algorithm: Algorithm = { name: 'MD5', alias: 'md5' }22+ const hash = await createHash(data, algorithm)23+ return hash24+}25+26+export const createHash = async (data: Data, algorithm: Algorithm): Promise<string | null> => {27+ if (crypto && crypto.subtle) {28+ const buffer = await crypto.subtle.digest(29+ {30+ name: algorithm.name,31+ },32+ new TextEncoder().encode(String(data))33+ )34+ const hash = Array.prototype.map35+ .call(new Uint8Array(buffer), (x) => ('00' + x.toString(16)).slice(-2))36+ .join('')37+ return hash38+ }39+ return null40+}added:deno_dist/utils/encode.test.ts+71 added
1+/* eslint-disable @typescript-eslint/ban-ts-comment */2+import {3+ utf8ToUint8Array,4+ decodeBase64,5+ encodeBase64,6+ encodeBase64URL,7+ decodeBase64URL,8+} from './encode.ts'9+10+describe('encode', () => {11+ describe('base64', () => {12+ it('encodeBase64', () => {13+ expect(encodeBase64('hooooooooo')).toBe('aG9vb29vb29vbw==')14+ expect(encodeBase64('炎')).toBe('54KO')15+ expect(encodeBase64('abcdef')).not.toBe('abcdedf')16+ expect(encodeBase64('')).toBe('')17+ expect(() => {18+ // @ts-ignore19+ encodeBase64(null)20+ }).toThrow(TypeError)21+ })22+23+ it('decodeBase64', async () => {24+ expect(decodeBase64('aG9vb29vb29vbw==')).toBe('hooooooooo')25+ expect(decodeBase64('54KO')).toBe('炎')26+ expect(decodeBase64('abcdedf')).not.toBe('abcdef')27+ expect(decodeBase64('')).toBe('')28+ expect(() => {29+ // @ts-ignore30+ decodeBase64(null)31+ }).toThrowError(TypeError)32+ })33+ })34+ describe('base64url', () => {35+ it('encodeBase64URL', () => {36+ expect(encodeBase64URL('hooooooooo')).toBe('aG9vb29vb29vbw')37+ expect(encodeBase64URL('http://github.com/honojs/hono')).toBe(38+ 'aHR0cDovL2dpdGh1Yi5jb20vaG9ub2pzL2hvbm8'39+ )40+ expect(encodeBase64URL('炎')).toBe('54KO')41+ expect(encodeBase64URL('abcdef')).not.toBe('abcdedf')42+ expect(encodeBase64URL('')).toBe('')43+ expect(() => {44+ // @ts-ignore45+ encodeBase64URL(null)46+ }).toThrow(TypeError)47+ })48+49+ it('decodeBase64URL', async () => {50+ expect(decodeBase64URL('aG9vb29vb29vbw')).toBe('hooooooooo')51+ expect(decodeBase64URL('aHR0cDovL2dpdGh1Yi5jb20vaG9ub2pzL2hvbm8')).toBe(52+ 'http://github.com/honojs/hono'53+ )54+ expect(decodeBase64URL('54KO')).toBe('炎')55+ expect(decodeBase64URL('abcdedf')).not.toBe('abcdef')56+ expect(decodeBase64URL('')).toBe('')57+ expect(() => {58+ // @ts-ignore59+ decodeBase64URL(null)60+ }).toThrowError(TypeError)61+ })62+ })63+64+ describe('utf8ToUint8Array', () => {65+ it('should be equal', () => {66+ const k = 'a-secret-key'67+ const arr = utf8ToUint8Array(k)68+ expect(String(arr)).toEqual('97,45,115,101,99,114,101,116,45,107,101,121')69+ })70+ })71+})added:deno_dist/utils/encode.ts+77 added
1+import { Buffer } from "https://deno.land/std@0.85.0/node/buffer.ts";2+export const encodeBase64 = (str: string): string => {3+ if (str === null) {4+ throw new TypeError('1st argument of "encodeBase64" should not be null.')5+ }6+ try {7+ const encoder = new TextEncoder()8+ const bytes = encoder.encode(str)9+ return btoa(String.fromCharCode(...bytes))10+ } catch {}11+12+ try {13+ return Buffer.from(str).toString('base64')14+ } catch (e) {15+ console.error('If you want to do "encodeBase64", polyfill "buffer" module.')16+ throw e17+ }18+}19+20+export const decodeBase64 = (str: string): string => {21+ if (str === null) {22+ throw new TypeError('1st argument of "decodeBase64" should not be null.')23+ }24+ try {25+ const text = atob(str)26+ const bytes = new Uint8Array(text.split('').map((c) => c.charCodeAt(0)))27+ const decoder = new TextDecoder()28+ return decoder.decode(bytes)29+ } catch {}30+31+ try {32+ return Buffer.from(str, 'base64').toString()33+ } catch (e) {34+ console.error('If you want to do "decodeBase64", polyfill "buffer" module.')35+ throw e36+ }37+}38+39+export const encodeBase64URL = (str: string): string => {40+ return encodeBase64(str).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')41+}42+43+export const decodeBase64URL = (str: string): string => {44+ const pad = (s: string) => {45+ const diff = s.length % 446+ if (diff === 2) {47+ return `${s}==`48+ }49+ if (diff === 3) {50+ return `${s}=`51+ }52+ return s53+ }54+55+ return decodeBase64(pad(str).replace(/-/g, '+').replace('_', '/'))56+}57+58+export const utf8ToUint8Array = (str: string): Uint8Array => {59+ const encoder = new TextEncoder()60+ return encoder.encode(str)61+}62+63+export const arrayBufferToBase64 = async (buf: ArrayBuffer): Promise<string> => {64+ if (typeof btoa === 'function') {65+ return btoa(String.fromCharCode(...new Uint8Array(buf)))66+ }67+68+ try {69+ return Buffer.from(String.fromCharCode(...new Uint8Array(buf))).toString('base64')70+ } catch (e) {}71+72+ return ''73+}74+75+export const arrayBufferToBase64URL = async (buf: ArrayBuffer) => {76+ return (await arrayBufferToBase64(buf)).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_')77+}added:deno_dist/utils/html.test.ts+8 added
1+import { escape } from './html.ts'2+3+describe('HTML escape', () => {4+ it('Should escape special characters', () => {5+ expect(escape('I <b>think</b> this is good.')).toBe('I <b>think</b> this is good.')6+ expect(escape('John "Johnny" Smith')).toBe('John "Johnny" Smith')7+ })8+})added:deno_dist/utils/html.ts+13 added
1+export type HtmlEscapedString = string & { isEscaped: true }2+3+const entityMap: Record<string, string> = {4+ '&': '&',5+ '<': '<',6+ '>': '>',7+ '"': '"',8+}9+const escapeRe = new RegExp(`[${Object.keys(entityMap).join('')}]`, 'g')10+const replaceFn = (m: string) => entityMap[m]11+export const escape = (str: string): string => {12+ return str.replace(escapeRe, replaceFn)13+}added:deno_dist/utils/http-status.test.ts+7 added
1+import { getStatusText } from './http-status.ts'2+3+describe('http-status utility', () => {4+ it('getStatusText', () => {5+ expect(getStatusText(200)).toBe('OK')6+ })7+})added:deno_dist/utils/http-status.ts+120 added
1+export const getStatusText = (statusCode: StatusCode): string => {2+ const text = statuses[statusCode]3+ return text4+}5+6+export type StatusCode =7+ | 1008+ | 1019+ | 10210+ | 10311+ | 20012+ | 20113+ | 20214+ | 20315+ | 20416+ | 20517+ | 20618+ | 20719+ | 20820+ | 22621+ | 30022+ | 30123+ | 30224+ | 30325+ | 30426+ | 30527+ | 30628+ | 30729+ | 30830+ | 40031+ | 40132+ | 40233+ | 40334+ | 40435+ | 40536+ | 40637+ | 40738+ | 40839+ | 40940+ | 41041+ | 41142+ | 41243+ | 41344+ | 41445+ | 41546+ | 41647+ | 41748+ | 41849+ | 42050+ | 42151+ | 42252+ | 42353+ | 42454+ | 42555+ | 42656+ | 42857+ | 42958+ | 43159+ | 44460+ | 44961+ | 45062+ | 45163+ | 49964+ | 50065+ | 50166+ | 50267+ | 50368+ | 50469+ | 50570+ | 50671+ | 50772+ | 50873+ | 50974+ | 51075+ | 51176+ | 59877+ | 59978+79+const statuses: Record<StatusCode | number, string> = {80+ 100: 'Continue',81+ 101: 'Switching Protocols',82+ 102: 'Processing',83+ 103: 'Early Hints',84+ 200: 'OK',85+ 201: 'Created',86+ 202: 'Accepted',87+ 204: 'No Content',88+ 206: 'Partial Content',89+ 301: 'Moved Permanently',90+ 302: 'Moved Temporarily',91+ 303: 'See Other',92+ 304: 'Not Modified',93+ 307: 'Temporary Redirect',94+ 308: 'Permanent Redirect',95+ 400: 'Bad Request',96+ 401: 'Unauthorized',97+ 402: 'Payment Required',98+ 403: 'Forbidden',99+ 404: 'Not Found',100+ 405: 'Not Allowed',101+ 406: 'Not Acceptable',102+ 408: 'Request Time-out',103+ 409: 'Conflict',104+ 410: 'Gone',105+ 411: 'Length Required',106+ 412: 'Precondition Failed',107+ 413: 'Request Entity Too Large',108+ 414: 'Request-URI Too Large',109+ 415: 'Unsupported Media Type',110+ 416: 'Requested Range Not Satisfiable',111+ 421: 'Misdirected Request',112+ 429: 'Too Many Requests',113+ 500: 'Internal Server Error',114+ 501: 'Not Implemented',115+ 502: 'Bad Gateway',116+ 503: 'Service Temporarily Unavailable',117+ 504: 'Gateway Time-out',118+ 505: 'HTTP Version Not Supported',119+ 507: 'Insufficient Storage',120+}added:deno_dist/utils/mime.test.ts+12 added
1+import { getMimeType } from './mime.ts'2+3+describe('mime', () => {4+ it('getMimeType', () => {5+ expect(getMimeType('hello.txt')).toBe('text/plain; charset=utf-8')6+ expect(getMimeType('hello.html')).toBe('text/html; charset=utf-8')7+ expect(getMimeType('hello.json')).toBe('application/json; charset=utf-8')8+ expect(getMimeType('good.morning.hello.gif')).toBe('image/gif')9+ expect(getMimeType('goodmorninghellogif')).toBeUndefined()10+ expect(getMimeType('indexjs.abcd')).toBeUndefined()11+ })12+})added:deno_dist/utils/mime.ts+88 added
1+export const getMimeType = (filename: string): string | undefined => {2+ const regexp = /\.([a-zA-Z0-9]+?)$/3+ const match = filename.match(regexp)4+ if (!match) return5+ let mimeType = mimes[match[1]]6+ if ((mimeType && mimeType.startsWith('text')) || mimeType === 'application/json') {7+ mimeType += '; charset=utf-8'8+ }9+ return mimeType10+}11+12+const mimes: Record<string, string> = {13+ aac: 'audio/aac',14+ abw: 'application/x-abiword',15+ arc: 'application/x-freearc',16+ avi: 'video/x-msvideo',17+ azw: 'application/vnd.amazon.ebook',18+ bin: 'application/octet-stream',19+ bmp: 'image/bmp',20+ bz: 'application/x-bzip',21+ bz2: 'application/x-bzip2',22+ csh: 'application/x-csh',23+ css: 'text/css',24+ csv: 'text/csv',25+ doc: 'application/msword',26+ docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',27+ eot: 'application/vnd.ms-fontobject',28+ epub: 'application/epub+zip',29+ gz: 'application/gzip',30+ gif: 'image/gif',31+ htm: 'text/html',32+ html: 'text/html',33+ ico: 'image/vnd.microsoft.icon',34+ ics: 'text/calendar',35+ jar: 'application/java-archive',36+ jpeg: 'image/jpeg',37+ jpg: 'image/jpeg',38+ js: 'text/javascript',39+ json: 'application/json',40+ jsonld: 'application/ld+json',41+ map: 'application/json',42+ mid: 'audio/x-midi',43+ midi: 'audio/x-midi',44+ mjs: 'text/javascript',45+ mp3: 'audio/mpeg',46+ mpeg: 'video/mpeg',47+ mpkg: 'application/vnd.apple.installer+xml',48+ odp: 'application/vnd.oasis.opendocument.presentation',49+ ods: 'application/vnd.oasis.opendocument.spreadsheet',50+ odt: 'application/vnd.oasis.opendocument.text',51+ oga: 'audio/ogg',52+ ogv: 'video/ogg',53+ ogx: 'application/ogg',54+ opus: 'audio/opus',55+ otf: 'font/otf',56+ png: 'image/png',57+ pdf: 'application/pdf',58+ php: 'application/php',59+ ppt: 'application/vnd.ms-powerpoint',60+ pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',61+ rar: 'application/vnd.rar',62+ rtf: 'application/rtf',63+ sh: 'application/x-sh',64+ svg: 'image/svg+xml',65+ swf: 'application/x-shockwave-flash',66+ tar: 'application/x-tar',67+ tif: 'image/tiff',68+ tiff: 'image/tiff',69+ ts: 'video/mp2t',70+ ttf: 'font/ttf',71+ txt: 'text/plain',72+ vsd: 'application/vnd.visio',73+ wav: 'audio/wav',74+ weba: 'audio/webm',75+ webm: 'video/webm',76+ webp: 'image/webp',77+ woff: 'font/woff',78+ woff2: 'font/woff2',79+ xhtml: 'application/xhtml+xml',80+ xls: 'application/vnd.ms-excel',81+ xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',82+ xml: 'application/xml',83+ xul: 'application/vnd.mozilla.xul+xml',84+ zip: 'application/zip',85+ '3gp': 'video/3gpp',86+ '3g2': 'video/3gpp2',87+ '7z': 'application/x-7z-compressed',88+}added:deno_dist/utils/url.test.ts+104 added
1+import { splitPath, getPattern, getPathFromURL, isAbsoluteURL, mergePath } from './url.ts'2+3+describe('url', () => {4+ it('splitPath', () => {5+ let ps = splitPath('/')6+ expect(ps).toStrictEqual([''])7+8+ ps = splitPath('/hello')9+ expect(ps).toStrictEqual(['hello'])10+11+ ps = splitPath('*')12+ expect(ps).toStrictEqual(['*'])13+14+ ps = splitPath('/wildcard-abc/*/wildcard-efg')15+ expect(ps).toStrictEqual(['wildcard-abc', '*', 'wildcard-efg'])16+17+ ps = splitPath('/map/:location/events')18+ expect(ps).toStrictEqual(['map', ':location', 'events'])19+ })20+21+ it('getPattern', () => {22+ let res = getPattern(':id')23+ expect(res).not.toBeNull()24+ expect(res?.[0]).toBe(':id')25+ expect(res?.[1]).toBe('id')26+ expect(res?.[2]).toBe(true)27+ res = getPattern(':id{[0-9]+}')28+ expect(res?.[0]).toBe(':id{[0-9]+}')29+ expect(res?.[1]).toBe('id')30+ expect(res?.[2]).toEqual(/^[0-9]+$/)31+ res = getPattern('*')32+ expect(res).toBe('*')33+ })34+35+ describe('getPathFromURL', () => {36+ it('getPathFromURL - no trailing slash', () => {37+ let path = getPathFromURL('https://example.com/')38+ expect(path).toBe('/')39+ path = getPathFromURL('https://example.com/hello')40+ expect(path).toBe('/hello')41+ path = getPathFromURL('https://example.com/hello/hey')42+ expect(path).toBe('/hello/hey')43+ path = getPathFromURL('https://example.com/hello?name=foo')44+ expect(path).toBe('/hello')45+ path = getPathFromURL('https://example.com/hello/hey?name=foo&name=bar')46+ expect(path).toBe('/hello/hey')47+ })48+49+ it('getPathFromURL - with trailing slash', () => {50+ let path = getPathFromURL('https://example.com/hello/')51+ expect(path).toBe('/hello/')52+ path = getPathFromURL('https://example.com/hello/hey/')53+ expect(path).toBe('/hello/hey/')54+ })55+56+ it('getPathFromURL - no strict is false', () => {57+ let path = getPathFromURL('https://example.com/hello/', false)58+ expect(path).toBe('/hello')59+ path = getPathFromURL('https://example.com/hello/hey/', false)60+ expect(path).toBe('/hello/hey')61+ })62+ })63+64+ describe('isAbsoluteURL', () => {65+ it('absolute url', () => {66+ expect(isAbsoluteURL('https://example.com')).toBeTruthy()67+ expect(isAbsoluteURL('https://example.com/xxx')).toBeTruthy()68+ })69+ it('relative url', () => {70+ expect(isAbsoluteURL('/')).not.toBeTruthy()71+ expect(isAbsoluteURL('/location')).not.toBeTruthy()72+ expect(isAbsoluteURL('')).not.toBeTruthy()73+ })74+ })75+76+ describe('mergePath', () => {77+ it('mergePath', () => {78+ expect(mergePath('/book', '/')).toBe('/book')79+ expect(mergePath('/book/', '/')).toBe('/book/')80+ expect(mergePath('/book', '/hey')).toBe('/book/hey')81+ expect(mergePath('/book/', '/hey')).toBe('/book/hey')82+ expect(mergePath('/book', '/hey/')).toBe('/book/hey/')83+ expect(mergePath('/book/', '/hey/')).toBe('/book/hey/')84+ expect(mergePath('/book', 'hey', 'say')).toBe('/book/hey/say')85+ expect(mergePath('/book', '/hey/', '/say/')).toBe('/book/hey/say/')86+ expect(mergePath('/book', '/hey/', '/say/', '/')).toBe('/book/hey/say/')87+88+ expect(mergePath('book', '/')).toBe('/book')89+ expect(mergePath('book/', '/')).toBe('/book/')90+ expect(mergePath('book', '/hey')).toBe('/book/hey')91+ expect(mergePath('book', 'hey')).toBe('/book/hey')92+ expect(mergePath('book', 'hey/')).toBe('/book/hey/')93+ })94+ it('Should be `/book`', () => {95+ expect(mergePath('/', 'book')).toBe('/book')96+ })97+ it('Should be `/book`', () => {98+ expect(mergePath('/', '/book')).toBe('/book')99+ })100+ it('Should be `/`', () => {101+ expect(mergePath('/', '/')).toBe('/')102+ })103+ })104+})added:deno_dist/utils/url.ts+91 added
1+const URL_REGEXP = /^https?:\/\/[a-zA-Z0-9\-\.:]+(\/?[^?#]*)/2+3+export type Pattern = readonly [string, string, RegExp | true] | '*'4+5+export const splitPath = (path: string): string[] => {6+ const paths = path.split(/\//) // faster than path.split('/')7+ if (paths[0] === '') {8+ paths.shift()9+ }10+ return paths11+}12+13+const patternCache: { [key: string]: Pattern } = {}14+export const getPattern = (label: string): Pattern | null => {15+ // * => wildcard16+ // :id{[0-9]+} => ([0-9]+)17+ // :id => (.+)18+ //const name = ''19+20+ if (label === '*') {21+ return '*'22+ }23+24+ const match = label.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/)25+ if (match) {26+ if (!patternCache[label]) {27+ if (match[2]) {28+ patternCache[label] = [label, match[1], new RegExp('^' + match[2] + '$')]29+ } else {30+ patternCache[label] = [label, match[1], true]31+ }32+ }33+34+ return patternCache[label]35+ }36+37+ return null38+}39+40+export const getPathFromURL = (url: string, strict: boolean = true): string => {41+ const queryIndex = url.indexOf('?')42+ const result = url.substring(url.indexOf('/', 8), queryIndex === -1 ? url.length : queryIndex)43+44+ // if strict routing is false => `/hello/hey/` and `/hello/hey` are treated the same45+ // default is true46+ if (strict === false && result.endsWith('/')) {47+ return result.slice(0, -1)48+ }49+50+ return result51+}52+53+export const isAbsoluteURL = (url: string): boolean => {54+ const match = url.match(URL_REGEXP)55+ if (match) {56+ return true57+ }58+ return false59+}60+61+export const mergePath = (...paths: string[]): string => {62+ let p: string = ''63+ let endsWithSlash = false64+65+ for (let path of paths) {66+ /* ['/hey/','/say'] => ['/hey', '/say'] */67+ if (p.endsWith('/')) {68+ p = p.slice(0, -1)69+ endsWithSlash = true70+ }71+72+ /* ['/hey','say'] => ['/hey', '/say'] */73+ if (!path.startsWith('/')) {74+ path = `/${path}`75+ }76+77+ /* ['/hey/', '/'] => `/hey/` */78+ if (path === '/' && endsWithSlash) {79+ p = `${p}/`80+ } else if (path !== '/') {81+ p = `${p}${path}`82+ }83+84+ /* ['/', '/'] => `/` */85+ if (path === '/' && p === '') {86+ p = '/'87+ }88+ }89+90+ return p91+}added:deno_dist/compose.test.ts+676 added
1+import { compose } from './compose.ts'2+import { Context } from './context.ts'3+import { extendRequestPrototype } from './request.ts'4+5+extendRequestPrototype()6+7+type C = {8+ req: Record<string, string>9+ res: Record<string, string>10+}11+12+describe('compose', () => {13+ const middleware: Function[] = []14+15+ const a = async (c: C, next: Function) => {16+ c.req['log'] = 'log'17+ await next()18+ }19+20+ const b = async (c: C, next: Function) => {21+ await next()22+ c.res['headers'] = 'custom-header'23+ }24+25+ const c = async (c: C, next: Function) => {26+ c.req['xxx'] = 'yyy'27+ await next()28+ c.res['zzz'] = c.req['xxx']29+ }30+31+ const handler = async (c: C, next: Function) => {32+ c.req['log'] = `${c.req.log} message`33+ await next()34+ c.res = { message: 'new response' }35+ }36+37+ middleware.push(a)38+ middleware.push(b)39+ middleware.push(c)40+ middleware.push(handler)41+42+ it('Request', async () => {43+ const c: C = { req: {}, res: {} }44+ const composed = compose<C>(middleware)45+ const context = await composed(c)46+ expect(context.req['log']).not.toBeNull()47+ expect(context.req['log']).toBe('log message')48+ expect(context.req['xxx']).toBe('yyy')49+ })50+ it('Response', async () => {51+ const c: C = { req: {}, res: {} }52+ const composed = compose<C>(middleware)53+ const context = await composed(c)54+ expect(context.res['headers']).not.toBeNull()55+ expect(context.res['headers']).toBe('custom-header')56+ expect(context.res['message']).toBe('new response')57+ expect(context.res['zzz']).toBe('yyy')58+ })59+})60+61+describe('Handler and middlewares', () => {62+ const middleware: Function[] = []63+64+ const req = new Request('http://localhost/')65+ const c: Context = new Context(req)66+67+ const mHandlerFoo = async (c: Context, next: Function) => {68+ c.req.headers.append('x-header-foo', 'foo')69+ await next()70+ }71+72+ const mHandlerBar = async (c: Context, next: Function) => {73+ await next()74+ c.header('x-header-bar', 'bar')75+ }76+77+ const handler = (c: Context) => {78+ const foo = c.req.header('x-header-foo') || ''79+ return c.text(foo)80+ }81+82+ middleware.push(mHandlerFoo)83+ middleware.push(mHandlerBar)84+ middleware.push(handler)85+86+ it('Should return 200 Response', async () => {87+ const composed = compose<Context>(middleware)88+ const context = await composed(c)89+ const res = context.res90+ expect(res).not.toBeNull()91+ expect(res.status).toBe(200)92+ expect(await res.text()).toBe('foo')93+ expect(res.headers.get('x-header-bar')).toBe('bar')94+ })95+})96+97+describe('compose with Context - 200 success', () => {98+ const middleware: Function[] = []99+100+ const req = new Request('http://localhost/')101+ const c: Context = new Context(req)102+ const handler = (c: Context) => {103+ return c.text('Hello')104+ }105+ const mHandler = async (_c: Context, next: Function) => {106+ await next()107+ }108+109+ middleware.push(handler)110+ middleware.push(mHandler)111+112+ it('Should return 200 Response', async () => {113+ const composed = compose<Context>(middleware)114+ const context = await composed(c)115+ expect(context.res).not.toBeNull()116+ expect(context.res.status).toBe(200)117+ expect(await context.res!.text()).toBe('Hello')118+ })119+})120+121+describe('compose with Context - 404 not found', () => {122+ const middleware: Function[] = []123+124+ const req = new Request('http://localhost/')125+ const c: Context = new Context(req)126+ const onError = (_error: Error, c: Context) => {127+ return c.text('onError', 500)128+ }129+ const onNotFound = (c: Context) => {130+ return c.text('onNotFound', 404)131+ }132+ const mHandler = async (_c: Context, next: Function) => {133+ await next()134+ }135+136+ middleware.push(mHandler)137+138+ it('Should return 404 Response', async () => {139+ const composed = compose<Context>(middleware, onError, onNotFound)140+ const context = await composed(c)141+ expect(context.res).not.toBeNull()142+ expect(context.res.status).toBe(404)143+ expect(await context.res.text()).toBe('onNotFound')144+ expect(context.finalized).toBe(true)145+ })146+})147+148+describe('compose with Context - 401 not authorized', () => {149+ const middleware: Function[] = []150+151+ const req = new Request('http://localhost/')152+ const c: Context = new Context(req)153+ const onError = (_error: Error, c: Context) => {154+ return c.text('onError', 500)155+ }156+ const handler = (c: Context, _next: Function) => {157+ return c.text('Hello')158+ }159+ const mHandler = async (c: Context, next: Function) => {160+ await next()161+ c.res = new Response('Not authorized', { status: 401 })162+ }163+164+ middleware.push(mHandler)165+ middleware.push(handler)166+167+ it('Should return 401 Response', async () => {168+ const composed = compose<Context>(middleware, onError)169+ const context = await composed(c)170+ expect(context.res).not.toBeNull()171+ expect(context.res.status).toBe(401)172+ expect(await context.res.text()).toBe('Not authorized')173+ expect(context.finalized).toBe(true)174+ })175+})176+177+describe('compose with Context - next() below', () => {178+ const middleware: Function[] = []179+180+ const req = new Request('http://localhost/')181+ const c: Context = new Context(req)182+ const onError = (_error: Error, c: Context) => {183+ return c.text('onError', 500)184+ }185+ const handler = (c: Context) => {186+ const message = c.req.header('x-custom') || 'blank'187+ return c.text(message)188+ }189+ const mHandler = async (c: Context, next: Function) => {190+ c.req.headers.append('x-custom', 'foo')191+ await next()192+ }193+194+ middleware.push(mHandler)195+ middleware.push(handler)196+197+ it('Should return 200 Response', async () => {198+ const composed = compose<Context>(middleware, onError)199+ const context = await composed(c)200+ expect(context.res).not.toBeNull()201+ expect(context.res.status).toBe(200)202+ expect(await context.res.text()).toBe('foo')203+ expect(context.finalized).toBe(true)204+ })205+})206+207+describe('compose with Context - 500 error', () => {208+ const middleware: Function[] = []209+210+ const req = new Request('http://localhost/')211+ const c: Context = new Context(req)212+ const onError = (_error: Error, c: Context) => {213+ return c.text('onError', 500)214+ }215+216+ it('Error on handler', async () => {217+ const handler = () => {218+ throw new Error()219+ }220+221+ const mHandler = async (_c: Context, next: Function) => {222+ await next()223+ }224+225+ middleware.push(mHandler)226+ middleware.push(handler)227+228+ const composed = compose<Context>(middleware, onError)229+ const context = await composed(c)230+ expect(context.res).not.toBeNull()231+ expect(context.res.status).toBe(500)232+ expect(await context.res.text()).toBe('onError')233+ expect(context.finalized).toBe(true)234+ })235+236+ it('Error on middleware', async () => {237+ const handler = (c: Context) => {238+ return c.text('OK')239+ }240+241+ const mHandler = async () => {242+ throw new Error()243+ }244+245+ middleware.push(mHandler)246+ middleware.push(handler)247+248+ const composed = compose<Context>(middleware, onError)249+ const context = await composed(c)250+ expect(c.res).not.toBeNull()251+ expect(c.res.status).toBe(500)252+ expect(await context.res.text()).toBe('onError')253+ expect(context.finalized).toBe(true)254+ })255+256+ it('Run all the middlewares', async () => {257+ const ctx: C = { req: {}, res: {} }258+ const stack: number[] = []259+ const middlewares = [260+ async (_ctx: C, next: Function) => {261+ stack.push(0)262+ await next()263+ },264+ async (_ctx: C, next: Function) => {265+ stack.push(1)266+ await next()267+ },268+ async (_ctx: C, next: Function) => {269+ stack.push(2)270+ await next()271+ },272+ ]273+ const composed = compose(middlewares)274+ await composed(ctx)275+ expect(stack).toEqual([0, 1, 2])276+ })277+})278+describe('compose with Context - not finalized', () => {279+ const req = new Request('http://localhost/')280+ const c: Context = new Context(req)281+282+ const onError = (_error: Error, c: Context) => {283+ return c.text('onError', 500)284+ }285+ const onNotFound = (c: Context) => {286+ return c.text('onNotFound', 404)287+ }288+289+ it('Should not be finalized - lack `next()`', async () => {290+ const middleware: Function[] = []291+ const mHandler = async (_c: Context, next: Function) => {292+ await next()293+ }294+ const mHandler2 = async () => {}295+296+ middleware.push(mHandler)297+ middleware.push(mHandler2)298+ const composed = compose<Context>(middleware, onError, onNotFound)299+ const context = await composed(c)300+ expect(context.finalized).toBe(false)301+ })302+303+ it('Should not be finalized - lack `return Response`', async () => {304+ const middleware2: Function[] = []305+ const mHandler3 = async (_c: Context, next: Function) => {306+ await next()307+ }308+ const handler = async () => {}309+ middleware2.push(mHandler3)310+ middleware2.push(handler)311+312+ const composed = compose<Context>(middleware2, onError, onNotFound)313+ const context = await composed(c)314+ expect(context.finalized).toBe(false)315+ })316+})317+318+describe('Compose', function () {319+ function isPromise(x: any) {320+ return x && typeof x.then === 'function'321+ }322+323+ it('should get executed order one by one', async () => {324+ const arr: number[] = []325+ const stack = []326+ const called: boolean[] = []327+328+ stack.push(async (_context: C, next: Function) => {329+ called.push(true)330+331+ arr.push(1)332+ await next()333+ arr.push(6)334+ })335+336+ stack.push(async (_context: C, next: Function) => {337+ called.push(true)338+339+ arr.push(2)340+ await next()341+ arr.push(5)342+ })343+344+ stack.push(async (_context: C, next: Function) => {345+ called.push(true)346+347+ arr.push(3)348+ await next()349+ arr.push(4)350+ })351+352+ await compose(stack)({})353+ expect(called).toEqual([true, true, true])354+ expect(arr).toEqual([1, 2, 3, 4, 5, 6])355+ })356+357+ it('should not get executed if previous next() not triggered', async () => {358+ const arr: number[] = []359+ const stack = []360+ const called: boolean[] = []361+362+ stack.push(async (_context: C, next: Function) => {363+ called.push(true)364+365+ arr.push(1)366+ await next()367+ arr.push(6)368+ })369+370+ stack.push(async () => {371+ called.push(true)372+ arr.push(2)373+ })374+375+ stack.push(async (_context: C, next: Function) => {376+ called.push(true)377+378+ arr.push(3)379+ await next()380+ arr.push(4)381+ })382+383+ await compose(stack)({})384+ expect(called).toEqual([true, true])385+ expect(arr).toEqual([1, 2, 6])386+ })387+388+ it('should be able to be called twice', () => {389+ type C = {390+ arr: number[]391+ }392+ const stack = []393+394+ stack.push(async (context: C, next: Function) => {395+ context.arr.push(1)396+ await next()397+ context.arr.push(6)398+ })399+400+ stack.push(async (context: C, next: Function) => {401+ context.arr.push(2)402+ await next()403+ context.arr.push(5)404+ })405+406+ stack.push(async (context: C, next: Function) => {407+ context.arr.push(3)408+ await next()409+ context.arr.push(4)410+ })411+412+ const fn = compose(stack)413+ const ctx1 = { arr: [] as number[] }414+ const ctx2 = { arr: [] as number[] }415+ const out = [1, 2, 3, 4, 5, 6]416+417+ return fn(ctx1)418+ .then(() => {419+ expect(out).toEqual(ctx1.arr)420+ return fn(ctx2)421+ })422+ .then(() => {423+ expect(out).toEqual(ctx2.arr)424+ })425+ })426+427+ it('should create next functions that return a Promise', function () {428+ const stack: any[] = []429+ const arr: any[] = []430+ for (let i = 0; i < 5; i++) {431+ stack.push((_context: C, next: Function) => {432+ arr.push(next())433+ })434+ }435+436+ compose(stack)({})437+438+ for (const next of arr) {439+ expect(isPromise(next)).toBe(true)440+ }441+ })442+443+ it('should work with 0 middleware', function () {444+ return compose([])({})445+ })446+447+ it('should work when yielding at the end of the stack', async () => {448+ const stack = []449+ let called = false450+451+ stack.push(async (_ctx: C, next: Function) => {452+ await next()453+ called = true454+ })455+456+ await compose(stack)({})457+ expect(called).toBe(true)458+ })459+460+ it('should reject on errors in middleware', () => {461+ const stack = []462+463+ stack.push(() => {464+ throw new Error()465+ })466+467+ return compose(stack)({}).then(468+ () => {469+ throw new Error('promise was not rejected')470+ },471+ (e) => {472+ expect(e).toBeInstanceOf(Error)473+ }474+ )475+ })476+477+ it('should keep the context', () => {478+ const ctx = {}479+480+ const stack = []481+482+ stack.push(async (ctx2: C, next: Function) => {483+ await next()484+ expect(ctx2).toEqual(ctx)485+ })486+487+ stack.push(async (ctx2: C, next: Function) => {488+ await next()489+ expect(ctx2).toEqual(ctx)490+ })491+492+ stack.push(async (ctx2: C, next: Function) => {493+ await next()494+ expect(ctx2).toEqual(ctx)495+ })496+497+ return compose(stack)(ctx)498+ })499+500+ it('should catch downstream errors', async () => {501+ const arr: any[] = []502+ const stack = []503+504+ stack.push(async (_ctx: C, next: Function) => {505+ arr.push(1)506+ try {507+ arr.push(6)508+ await next()509+ arr.push(7)510+ } catch (err) {511+ arr.push(2)512+ }513+ arr.push(3)514+ })515+516+ stack.push(async () => {517+ arr.push(4)518+ throw new Error()519+ })520+521+ await compose(stack)({})522+ expect(arr).toEqual([1, 6, 4, 2, 3])523+ })524+525+ it('should compose w/ next', () => {526+ let called = false527+528+ return compose([])({}, async () => {529+ called = true530+ }).then(function () {531+ expect(called).toBe(true)532+ })533+ })534+535+ it('should handle errors in wrapped non-async functions', () => {536+ const stack = []537+538+ stack.push(function () {539+ throw new Error()540+ })541+542+ return compose(stack)({}).then(543+ () => {544+ throw new Error('promise was not rejected')545+ },546+ (e) => {547+ expect(e).toBeInstanceOf(Error)548+ }549+ )550+ })551+552+ // https://github.com/koajs/compose/pull/27#issuecomment-143109739553+ it('should compose w/ other compositions', () => {554+ const called: number[] = []555+556+ return compose([557+ compose([558+ (_ctx: C, next: Function) => {559+ called.push(1)560+ return next()561+ },562+ (_ctx: C, next: Function) => {563+ called.push(2)564+ return next()565+ },566+ ]),567+ (_ctx: C, next: Function) => {568+ called.push(3)569+ return next()570+ },571+ ])({}).then(() => expect(called).toEqual([1, 2, 3]))572+ })573+574+ it('should throw if next() is called multiple times', () => {575+ return compose([576+ async (_ctx: C, next: Function) => {577+ await next()578+ await next()579+ },580+ ])({}).then(581+ () => {582+ throw new Error('boom')583+ },584+ (err) => {585+ expect(/multiple times/.test(err.message)).toBe(true)586+ }587+ )588+ })589+590+ it('should return a valid middleware', () => {591+ let val = 0592+ return compose([593+ compose([594+ (_ctx: C, next: Function) => {595+ val++596+ return next()597+ },598+ (_ctx: C, next: Function) => {599+ val++600+ return next()601+ },602+ ]),603+ (_ctx: C, next: Function) => {604+ val++605+ return next()606+ },607+ ])({}).then(function () {608+ expect(val).toEqual(3)609+ })610+ })611+612+ it('should return last return value', async () => {613+ type C = {614+ val: number615+ }616+ const stack = []617+618+ stack.push(async (ctx: C, next: Function) => {619+ await next()620+ expect(ctx.val).toEqual(2)621+ ctx.val = 1622+ })623+624+ stack.push(async (ctx: C, next: Function) => {625+ ctx.val = 2626+ await next()627+ expect(ctx.val).toEqual(2)628+ })629+630+ const res = await compose(stack)({ val: 0 })631+ expect(res).toEqual({ val: 1 })632+ })633+634+ it('should not affect the original middleware array', () => {635+ const middleware = []636+ const fn1 = (_ctx: C, next: Function) => {637+ return next()638+ }639+ middleware.push(fn1)640+641+ for (const fn of middleware) {642+ expect(fn).toEqual(fn1)643+ }644+645+ compose(middleware)646+647+ for (const fn of middleware) {648+ expect(fn).toEqual(fn1)649+ }650+ })651+652+ it('should not get stuck on the passed in next', async () => {653+ type C = {654+ middleware: number655+ next: number656+ }657+658+ const middleware = [659+ (ctx: C, next: Function) => {660+ ctx.middleware++661+ return next()662+ },663+ ]664+ const ctx = {665+ middleware: 0,666+ next: 0,667+ }668+669+ return compose(middleware)(ctx, (ctx: C, next: Function) => {670+ ctx.next++671+ return next()672+ }).then(() => {673+ expect(ctx).toEqual({ middleware: 1, next: 1 })674+ })675+ })676+})added:deno_dist/compose.ts+48 added
1+import { Context } from './context.ts'2+import type { ErrorHandler, NotFoundHandler } from './hono.ts'3+4+// Based on the code in the MIT licensed `koa-compose` package.5+export const compose = <C>(6+ middleware: Function[],7+ onError?: ErrorHandler,8+ onNotFound?: NotFoundHandler9+) => {10+ return async (context: C, next?: Function) => {11+ let index = -112+ return dispatch(0)13+ async function dispatch(i: number): Promise<C> {14+ if (i <= index) {15+ return Promise.reject(new Error('next() called multiple times'))16+ }17+ let handler = middleware[i]18+ index = i19+ if (i === middleware.length && next) handler = next20+21+ if (!handler) {22+ if (context instanceof Context && context.finalized === false && onNotFound) {23+ context.res = await onNotFound(context)24+ }25+ return Promise.resolve(context)26+ }27+28+ return Promise.resolve(handler(context, () => dispatch(i + 1)))29+ .then(async (res: Response) => {30+ // If handler return Response like `return c.text('foo')`31+ if (res && context instanceof Context) {32+ context.res = res33+ }34+ return context35+ })36+ .catch((err) => {37+ if (context instanceof Context && onError) {38+ if (err instanceof Error) {39+ context.res = onError(err, context)40+ }41+ return context42+ } else {43+ throw err44+ }45+ })46+ }47+ }48+}added:deno_dist/context.test.ts+145 added
1+import { Context } from './context.ts'2+3+describe('Context', () => {4+ const req = new Request('http://localhost/')5+6+ let c: Context7+ beforeEach(() => {8+ c = new Context(req)9+ })10+11+ it('c.text()', async () => {12+ const res = c.text('text in c', 201, { 'X-Custom': 'Message' })13+ expect(res.status).toBe(201)14+ expect(res.headers.get('Content-Type')).toBe('text/plain; charset=UTF-8')15+ expect(await res.text()).toBe('text in c')16+ expect(res.headers.get('X-Custom')).toBe('Message')17+ })18+19+ it('c.json()', async () => {20+ const res = c.json({ message: 'Hello' }, 201, { 'X-Custom': 'Message' })21+ expect(res.status).toBe(201)22+ expect(res.headers.get('Content-Type')).toMatch('application/json; charset=UTF-8')23+ const text = await res.text()24+ expect(text).toBe('{"message":"Hello"}')25+ expect(res.headers.get('X-Custom')).toBe('Message')26+ })27+28+ it('c.json() with c.pretty(true)', async () => {29+ c.pretty(true)30+ const res = c.json({ message: 'Hello' })31+ const text = await res.text()32+ expect(text).toBe(`{33+ "message": "Hello"34+}`)35+ })36+37+ it('c.json() with c.pretty(true, 4)', async () => {38+ c.pretty(true, 4)39+ const res = c.json({ message: 'Hello' })40+ const text = await res.text()41+ expect(text).toBe(`{42+ "message": "Hello"43+}`)44+ })45+46+ it('c.html()', async () => {47+ const res = c.html('<h1>Hello! Hono!</h1>', 201, { 'X-Custom': 'Message' })48+ expect(res.status).toBe(201)49+ expect(res.headers.get('Content-Type')).toMatch('text/html')50+ expect(await res.text()).toBe('<h1>Hello! Hono!</h1>')51+ expect(res.headers.get('X-Custom')).toBe('Message')52+ })53+54+ it('c.redirect()', async () => {55+ let res = c.redirect('/destination')56+ expect(res.status).toBe(302)57+ expect(res.headers.get('Location')).toMatch(/^https?:\/\/.+\/destination$/)58+ res = c.redirect('https://example.com/destination')59+ expect(res.status).toBe(302)60+ expect(res.headers.get('Location')).toBe('https://example.com/destination')61+ })62+63+ it('c.header()', async () => {64+ c.header('X-Foo', 'Bar')65+ const res = c.body('Hi')66+ const foo = res.headers.get('X-Foo')67+ expect(foo).toBe('Bar')68+ })69+70+ it('c.status()', async () => {71+ c.status(201)72+ const res = c.body('Hi')73+ expect(res.status).toBe(201)74+ })75+76+ it('Complex pattern', async () => {77+ c.status(404)78+ const res = c.json({ hono: 'great app' })79+ expect(res.status).toBe(404)80+ expect(res.headers.get('Content-Type')).toMatch('application/json; charset=UTF-8')81+ const obj: { [key: string]: string } = await res.json()82+ expect(obj['hono']).toBe('great app')83+ })84+85+ it('Has headers and status', async () => {86+ c.header('x-custom1', 'Message1')87+ c.header('x-custom2', 'Message2')88+ c.status(200)89+ const res = c.newResponse('this is body', 201, {90+ 'x-custom3': 'Message3',91+ 'x-custom2': 'Message2-Override',92+ })93+ expect(res.headers.get('x-Custom1')).toBe('Message1')94+ expect(res.headers.get('x-Custom2')).toBe('Message2-Override')95+ expect(res.headers.get('x-Custom3')).toBe('Message3')96+ expect(res.status).toBe(201)97+ expect(await res.text()).toBe('this is body')98+99+ // res is already set.100+ c.res = res101+ c.header('X-Custom4', 'Message4')102+ c.status(202)103+ expect(c.res.headers.get('X-Custom4')).toBe('Message4')104+ expect(c.res.status).toBe(201)105+ })106+107+ it('Should return 200 response', async () => {108+ const res = c.text('Text')109+ expect(res.status).toBe(200)110+ })111+112+ it('Should return 204 response', async () => {113+ c.status(204)114+ const res = c.body(null)115+ expect(res.status).toBe(204)116+ expect(await res.text()).toBe('')117+ })118+119+ it('Should be able read env', async () => {120+ const req = new Request('http://localhost/')121+ const key = 'a-secret-key'122+ const ctx = new Context(req, {123+ API_KEY: key,124+ })125+ expect(ctx.env.API_KEY).toBe(key)126+ })127+128+ it('set and set', async () => {129+ const ctx = new Context(req)130+ expect(ctx.get('k-foo')).toEqual(undefined)131+ ctx.set('k-foo', 'v-foo')132+ expect(ctx.get('k-foo')).toEqual('v-foo')133+ expect(ctx.get('k-bar')).toEqual(undefined)134+ ctx.set('k-bar', { k: 'v' })135+ expect(ctx.get('k-bar')).toEqual({ k: 'v' })136+ })137+138+ it('has res object by default', async () => {139+ c = new Context(req)140+ c.res.headers.append('foo', 'bar')141+ const res = c.text('foo')142+ expect(res.headers.get('foo')).not.toBeNull()143+ expect(res.headers.get('foo')).toBe('bar')144+ })145+})added:deno_dist/context.ts+131 added
1+import type { NotFoundHandler } from './hono.ts'2+import type { StatusCode } from './utils/http-status.ts'3+import { isAbsoluteURL } from './utils/url.ts'4+5+type Headers = Record<string, string>6+export type Data = string | ArrayBuffer | ReadableStream7+8+export type Env = Record<string, any>9+10+export class Context<RequestParamKeyType extends string = string, E = Env> {11+ req: Request<RequestParamKeyType>12+ env: E13+ event: FetchEvent | undefined14+ executionCtx: ExecutionContext | undefined15+ finalized: boolean16+17+ private _status: StatusCode = 20018+ private _pretty: boolean = false19+ private _prettySpace: number = 220+ private _map: Record<string, any> | undefined21+ private _headers: Record<string, string> | undefined22+ private _res: Response | undefined23+ private notFoundHandler: NotFoundHandler24+25+ constructor(26+ req: Request,27+ env: E | undefined = undefined,28+ eventOrExecutionCtx: FetchEvent | ExecutionContext | undefined = undefined,29+ notFoundHandler: NotFoundHandler = () => new Response()30+ ) {31+ this.req = req32+ this.env = env ? env : ({} as E)33+34+ if (eventOrExecutionCtx && 'respondWith' in eventOrExecutionCtx) {35+ this.event = eventOrExecutionCtx36+ } else {37+ this.executionCtx = eventOrExecutionCtx38+ }39+40+ this.notFoundHandler = notFoundHandler41+ this.finalized = false42+ }43+44+ get res(): Response {45+ return (this._res ||= new Response())46+ }47+48+ set res(_res: Response) {49+ this._res = _res50+ this.finalized = true51+ }52+53+ header(name: string, value: string): void {54+ this._headers ||= {}55+ this._headers[name] = value56+ if (this.finalized) {57+ this.res.headers.set(name, value)58+ }59+ }60+61+ status(status: StatusCode): void {62+ this._status = status63+ }64+65+ set(key: string, value: any): void {66+ this._map ||= {}67+ this._map[key] = value68+ }69+70+ get(key: string) {71+ if (!this._map) {72+ return undefined73+ }74+ return this._map[key]75+ }76+77+ pretty(prettyJSON: boolean, space: number = 2): void {78+ this._pretty = prettyJSON79+ this._prettySpace = space80+ }81+82+ newResponse(data: Data | null, status: StatusCode, headers: Headers = {}): Response {83+ const _headers = { ...this._headers, ...headers }84+ if (this._res) {85+ this._res.headers.forEach((v, k) => {86+ _headers[k] = v87+ })88+ }89+ return new Response(data, {90+ status: status || this._status || 200,91+ headers: _headers,92+ })93+ }94+95+ body(data: Data | null, status: StatusCode = this._status, headers: Headers = {}): Response {96+ return this.newResponse(data, status, headers)97+ }98+99+ text(text: string, status: StatusCode = this._status, headers: Headers = {}): Response {100+ headers['Content-Type'] ||= 'text/plain; charset=UTF-8'101+ return this.body(text, status, headers)102+ }103+104+ json<T>(object: T, status: StatusCode = this._status, headers: Headers = {}): Response {105+ const body = this._pretty106+ ? JSON.stringify(object, null, this._prettySpace)107+ : JSON.stringify(object)108+ headers['Content-Type'] ||= 'application/json; charset=UTF-8'109+ return this.body(body, status, headers)110+ }111+112+ html(html: string, status: StatusCode = this._status, headers: Headers = {}): Response {113+ headers['Content-Type'] ||= 'text/html; charset=UTF-8'114+ return this.body(html, status, headers)115+ }116+117+ redirect(location: string, status: StatusCode = 302): Response {118+ if (!isAbsoluteURL(location)) {119+ const url = new URL(this.req.url)120+ url.pathname = location121+ location = url.toString()122+ }123+ return this.newResponse(null, status, {124+ Location: location,125+ })126+ }127+128+ notFound(): Response | Promise<Response> {129+ return this.notFoundHandler(this as any)130+ }131+}added:deno_dist/hono.test.ts+876 added
1+import type { Context } from './context.ts'2+import type { Next } from './hono.ts'3+import { Hono } from './hono.ts'4+import { poweredBy } from './middleware/powered-by/index.ts'5+6+describe('GET Request', () => {7+ const app = new Hono()8+9+ app.get('/hello', async () => {10+ return new Response('hello', {11+ status: 200,12+ statusText: 'Hono is OK',13+ })14+ })15+16+ app.get('/hello-with-shortcuts', (c) => {17+ c.header('X-Custom', 'This is Hono')18+ c.status(201)19+ return c.html('<h1>Hono!!!</h1>')20+ })21+22+ it('GET /hello is ok', async () => {23+ const res = await app.request('http://localhost/hello')24+ expect(res).not.toBeNull()25+ expect(res.status).toBe(200)26+ expect(res.statusText).toBe('Hono is OK')27+ expect(await res.text()).toBe('hello')28+ })29+30+ it('GET /hello-with-shortcuts is ok', async () => {31+ const res = await app.request('http://localhost/hello-with-shortcuts')32+ expect(res).not.toBeNull()33+ expect(res.status).toBe(201)34+ expect(res.headers.get('X-Custom')).toBe('This is Hono')35+ expect(res.headers.get('Content-Type')).toMatch(/text\/html/)36+ expect(await res.text()).toBe('<h1>Hono!!!</h1>')37+ })38+39+ it('GET / is not found', async () => {40+ const res = await app.request('http://localhost/')41+ expect(res).not.toBeNull()42+ expect(res.status).toBe(404)43+ })44+})45+46+describe('strict parameter', () => {47+ describe('strict is true with not slash', () => {48+ const app = new Hono()49+50+ app.get('/hello', (c) => {51+ return c.text('/hello')52+ })53+54+ it('/hello/ is not found', async () => {55+ let res = await app.request('http://localhost/hello')56+ expect(res).not.toBeNull()57+ expect(res.status).toBe(200)58+ res = await app.request('http://localhost/hello/')59+ expect(res).not.toBeNull()60+ expect(res.status).toBe(404)61+ })62+ })63+64+ describe('strict is true with slash', () => {65+ const app = new Hono()66+67+ app.get('/hello/', (c) => {68+ return c.text('/hello/')69+ })70+71+ it('/hello is not found', async () => {72+ let res = await app.request('http://localhost/hello/')73+ expect(res).not.toBeNull()74+ expect(res.status).toBe(200)75+ res = await app.request('http://localhost/hello')76+ expect(res).not.toBeNull()77+ expect(res.status).toBe(404)78+ })79+ })80+81+ describe('strict is false', () => {82+ const app = new Hono({ strict: false })83+84+ app.get('/hello', (c) => {85+ return c.text('/hello')86+ })87+88+ it('/hello and /hello/ are treated as the same', async () => {89+ let res = await app.request('http://localhost/hello')90+ expect(res).not.toBeNull()91+ expect(res.status).toBe(200)92+ res = await app.request('http://localhost/hello/')93+ expect(res).not.toBeNull()94+ expect(res.status).toBe(200)95+ })96+ })97+})98+99+describe('Routing', () => {100+ const app = new Hono()101+102+ it('Return it self', async () => {103+ const app2 = app.get('/', () => new Response('get /'))104+ expect(app2).not.toBeUndefined()105+ app2.delete('/', () => new Response('delete /'))106+107+ let res = await app2.request('http://localhost/', { method: 'GET' })108+ expect(res).not.toBeNull()109+ expect(res.status).toBe(200)110+ expect(await res.text()).toBe('get /')111+112+ res = await app2.request('http://localhost/', { method: 'DELETE' })113+ expect(res).not.toBeNull()114+ expect(res.status).toBe(200)115+ expect(await res.text()).toBe('delete /')116+ })117+118+ it('Nested route', async () => {119+ const book = app.route('/book')120+ book.get('/', (c) => c.text('get /book'))121+ book.get('/:id', (c) => {122+ return c.text('get /book/' + c.req.param('id'))123+ })124+ book.post('/', (c) => c.text('post /book'))125+126+ const user = app.route('/user')127+ user.get('/login', (c) => c.text('get /user/login'))128+ user.post('/register', (c) => c.text('post /user/register'))129+130+ let res = await app.request('http://localhost/book', { method: 'GET' })131+ expect(res.status).toBe(200)132+ expect(await res.text()).toBe('get /book')133+134+ res = await app.request('http://localhost/book/123', { method: 'GET' })135+ expect(res.status).toBe(200)136+ expect(await res.text()).toBe('get /book/123')137+138+ res = await app.request('http://localhost/book', { method: 'POST' })139+ expect(res.status).toBe(200)140+ expect(await res.text()).toBe('post /book')141+142+ res = await app.request('http://localhost/book/', { method: 'GET' })143+ expect(res.status).toBe(404)144+145+ res = await app.request('http://localhost/user/login', { method: 'GET' })146+ expect(res.status).toBe(200)147+ expect(await res.text()).toBe('get /user/login')148+149+ res = await app.request('http://localhost/user/register', { method: 'POST' })150+ expect(res.status).toBe(200)151+ expect(await res.text()).toBe('post /user/register')152+ })153+154+ describe('Chained route', () => {155+ app156+ .get('/chained/:abc', (c) => {157+ const abc = c.req.param('abc')158+ return c.text(`GET for ${abc}`)159+ })160+ .post((c) => {161+ const abc = c.req.param('abc')162+ return c.text(`POST for ${abc}`)163+ })164+ it('Should return 200 response from GET request', async () => {165+ const res = await app.request('http://localhost/chained/abc', { method: 'GET' })166+ expect(res.status).toBe(200)167+ expect(await res.text()).toBe('GET for abc')168+ })169+ it('Should return 200 response from POST request', async () => {170+ const res = await app.request('http://localhost/chained/abc', { method: 'POST' })171+ expect(res.status).toBe(200)172+ expect(await res.text()).toBe('POST for abc')173+ })174+ it('Should return 404 response from PUT request', async () => {175+ const res = await app.request('http://localhost/chained/abc', { method: 'PUT' })176+ expect(res.status).toBe(404)177+ })178+ })179+})180+181+describe('param and query', () => {182+ const apps: Record<string, Hono> = {}183+ apps['get by name'] = (() => {184+ const app = new Hono()185+186+ app.get('/entry/:id', (c) => {187+ const id = c.req.param('id')188+ return c.text(`id is ${id}`)189+ })190+191+ app.get('/date/:date{[0-9]+}', (c) => {192+ const date = c.req.param('date')193+ return c.text(`date is ${date}`)194+ })195+196+ app.get('/search', (c) => {197+ const name = c.req.query('name')198+ return c.text(`name is ${name}`)199+ })200+201+ app.get('/multiple-values', (c) => {202+ const queries = c.req.queries('q')203+ const limit = c.req.queries('limit')204+ return c.text(`q is ${queries[0]} and ${queries[1]}, limit is ${limit[0]}`)205+ })206+207+ app.get('/add-header', (c) => {208+ const bar = c.req.header('X-Foo')209+ return c.text(`foo is ${bar}`)210+ })211+212+ return app213+ })()214+215+ apps['get all as an object'] = (() => {216+ const app = new Hono()217+218+ app.get('/entry/:id', (c) => {219+ const { id } = c.req.param()220+ return c.text(`id is ${id}`)221+ })222+223+ app.get('/date/:date{[0-9]+}', (c) => {224+ const { date } = c.req.param()225+ return c.text(`date is ${date}`)226+ })227+228+ app.get('/search', (c) => {229+ const { name } = c.req.query()230+ return c.text(`name is ${name}`)231+ })232+233+ app.get('/multiple-values', (c) => {234+ const { q, limit } = c.req.queries()235+ return c.text(`q is ${q[0]} and ${q[1]}, limit is ${limit[0]}`)236+ })237+238+ app.get('/add-header', (c) => {239+ const { 'x-foo': bar } = c.req.header()240+ return c.text(`foo is ${bar}`)241+ })242+243+ return app244+ })()245+246+ describe.each(Object.keys(apps))('%s', (name) => {247+ const app = apps[name]248+249+ it('param of /entry/:id is found', async () => {250+ const res = await app.request('http://localhost/entry/123')251+ expect(res.status).toBe(200)252+ expect(await res.text()).toBe('id is 123')253+ })254+255+ it('param of /date/:date is found', async () => {256+ const res = await app.request('http://localhost/date/0401')257+ expect(res.status).toBe(200)258+ expect(await res.text()).toBe('date is 0401')259+ })260+261+ it('query of /search?name=sam is found', async () => {262+ const res = await app.request('http://localhost/search?name=sam')263+ expect(res.status).toBe(200)264+ expect(await res.text()).toBe('name is sam')265+ })266+267+ it('query of /search?name=sam&name=tom is found', async () => {268+ const res = await app.request('http://localhost/search?name=sam&name=tom')269+ expect(res.status).toBe(200)270+ expect(await res.text()).toBe('name is sam')271+ })272+273+ it('query of /multiple-values?q=foo&q=bar&limit=10 is found', async () => {274+ const res = await app.request('http://localhost/multiple-values?q=foo&q=bar&limit=10')275+ expect(res.status).toBe(200)276+ expect(await res.text()).toBe('q is foo and bar, limit is 10')277+ })278+279+ it('/add-header header - X-Foo is Bar', async () => {280+ const req = new Request('http://localhost/add-header')281+ req.headers.append('X-Foo', 'Bar')282+ const res = await app.request(req)283+ expect(res.status).toBe(200)284+ expect(await res.text()).toBe('foo is Bar')285+ })286+ })287+})288+289+describe('Middleware', () => {290+ describe('Basic', () => {291+ const app = new Hono()292+293+ // Custom Logger294+ app.use('*', async (c, next) => {295+ console.log(`${c.req.method} : ${c.req.url}`)296+ await next()297+ })298+299+ // Append Custom Header300+ app.use('*', async (c, next) => {301+ await next()302+ c.res.headers.append('x-custom', 'root')303+ })304+305+ app.use('/hello', async (c, next) => {306+ await next()307+ c.res.headers.append('x-message', 'custom-header')308+ })309+310+ app.use('/hello/*', async (c, next) => {311+ await next()312+ c.res.headers.append('x-message-2', 'custom-header-2')313+ })314+315+ app.get('/hello', (c) => {316+ return c.text('hello')317+ })318+319+ app.get('/hello/:message', (c) => {320+ const message = c.req.param('message')321+ return c.text(`${message}`)322+ })323+324+ app.get('/error', () => {325+ throw new Error('Error!')326+ })327+328+ app.notFound((c) => {329+ return c.text('Not Found Foo', 404)330+ })331+332+ it('logging and custom header', async () => {333+ const res = await app.request('http://localhost/hello')334+ expect(res.status).toBe(200)335+ expect(await res.text()).toBe('hello')336+ expect(res.headers.get('x-custom')).toBe('root')337+ expect(res.headers.get('x-message')).toBe('custom-header')338+ expect(res.headers.get('x-message-2')).toBe('custom-header-2')339+ })340+341+ it('logging and custom header with named param', async () => {342+ const res = await app.request('http://localhost/hello/message')343+ expect(res.status).toBe(200)344+ expect(await res.text()).toBe('message')345+ expect(res.headers.get('x-custom')).toBe('root')346+ expect(res.headers.get('x-message-2')).toBe('custom-header-2')347+ })348+349+ it('not found', async () => {350+ const res = await app.request('http://localhost/foo')351+ expect(res.status).toBe(404)352+ expect(await res.text()).toBe('Not Found Foo')353+ })354+355+ it('internal server error', async () => {356+ const res = await app.request('http://localhost/error')357+ expect(res.status).toBe(500)358+ console.log(await res.text())359+ })360+ })361+362+ describe('Chained route', () => {363+ const app = new Hono()364+ app365+ .use('/chained/*', async (c, next) => {366+ c.req.headers.append('x-before', 'abc')367+ await next()368+ })369+ .use(async (c, next) => {370+ await next()371+ c.header('x-after', c.req.header('x-before'))372+ })373+ .get('/chained/abc', (c) => {374+ return c.text('GET chained')375+ })376+ it('GET /chained/abc', async () => {377+ const res = await app.request('http://localhost/chained/abc')378+ expect(res.status).toBe(200)379+ expect(await res.text()).toBe('GET chained')380+ expect(res.headers.get('x-after')).toBe('abc')381+ })382+ })383+384+ describe('Multiple handler', () => {385+ const app = new Hono()386+ app387+ .use(388+ '/multiple/*',389+ async (c, next) => {390+ c.req.headers.append('x-before', 'abc')391+ await next()392+ },393+ async (c, next) => {394+ await next()395+ c.header('x-after', c.req.header('x-before'))396+ }397+ )398+ .get('/multiple/abc', (c) => {399+ return c.text('GET multiple')400+ })401+ it('GET /multiple/abc', async () => {402+ const res = await app.request('http://localhost/multiple/abc')403+ expect(res.status).toBe(200)404+ expect(await res.text()).toBe('GET multiple')405+ expect(res.headers.get('x-after')).toBe('abc')406+ })407+ })408+})409+410+describe('Builtin Middleware', () => {411+ const app = new Hono()412+ app.use('/abc', poweredBy())413+ app.use('/def', async (c, next) => {414+ const middleware = poweredBy()415+ await middleware(c, next)416+ })417+ app.get('/abc', () => new Response())418+ app.get('/def', () => new Response())419+420+ it('"powered-by" middleware', async () => {421+ const res = await app.request('http://localhost/abc')422+ expect(res.headers.get('x-powered-by')).toBe('Hono')423+ })424+425+ it('"powered-by" middleware in a handler', async () => {426+ const res = await app.request('http://localhost/def')427+ expect(res.headers.get('x-powered-by')).toBe('Hono')428+ })429+})430+431+describe('Middleware with app.HTTP_METHOD', () => {432+ describe('Basic', () => {433+ const app = new Hono()434+435+ app.all('*', async (c, next) => {436+ c.header('x-before-dispatch', 'foo')437+ await next()438+ c.header('x-custom-message', 'hello')439+ })440+441+ const customHeader = async (c: Context, next: Next) => {442+ c.req.headers.append('x-custom-foo', 'bar')443+ await next()444+ }445+446+ const customHeader2 = async (c: Context, next: Next) => {447+ await next()448+ c.header('x-custom-foo-2', 'bar-2')449+ }450+451+ app452+ .get('/abc', customHeader, (c) => {453+ const foo = c.req.header('x-custom-foo') || ''454+ return c.text(foo)455+ })456+ .post(customHeader2, (c) => {457+ return c.text('POST /abc')458+ })459+460+ it('GET /abc', async () => {461+ const res = await app.request('http://localhost/abc')462+ expect(res.status).toBe(200)463+ expect(res.headers.get('x-custom-message')).toBe('hello')464+ expect(res.headers.get('x-before-dispatch')).toBe('foo')465+ expect(await res.text()).toBe('bar')466+ })467+ it('POST /abc', async () => {468+ const res = await app.request('http://localhost/abc', { method: 'POST' })469+ expect(res.status).toBe(200)470+ expect(await res.text()).toBe('POST /abc')471+ expect(res.headers.get('x-custom-foo-2')).toBe('bar-2')472+ })473+ })474+475+ describe('With builtin middleware', () => {476+ const app = new Hono()477+ app.get('/abc', poweredBy(), (c) => {478+ return c.text('GET /abc')479+ })480+ it('GET /abc', async () => {481+ const res = await app.request('http://localhost/abc')482+ expect(res.status).toBe(200)483+ expect(await res.text()).toBe('GET /abc')484+ expect(res.headers.get('x-powered-by')).toBe('Hono')485+ })486+ })487+})488+489+describe('Not Found', () => {490+ const app = new Hono()491+492+ app.notFound((c) => {493+ return c.text('Custom 404 Not Found', 404)494+ })495+496+ app.get('/hello', (c) => {497+ return c.text('hello')498+ })499+500+ app.get('/notfound', (c) => {501+ return c.notFound()502+ })503+504+ it('Custom 404 Not Found', async () => {505+ let res = await app.request('http://localhost/hello')506+ expect(res.status).toBe(200)507+ res = await app.request('http://localhost/notfound')508+ expect(res.status).toBe(404)509+ res = await app.request('http://localhost/foo')510+ expect(res.status).toBe(404)511+ expect(await res.text()).toBe('Custom 404 Not Found')512+ })513+})514+515+describe('Redirect', () => {516+ const app = new Hono()517+ app.get('/redirect', (c) => {518+ return c.redirect('/')519+ })520+521+ it('Absolute URL', async () => {522+ const res = await app.request('https://example.com/redirect')523+ expect(res.status).toBe(302)524+ expect(res.headers.get('Location')).toBe('https://example.com/')525+ })526+})527+528+describe('Error handle', () => {529+ const app = new Hono()530+531+ app.get('/error', () => {532+ throw new Error('This is Error')533+ })534+535+ app.use('/error-middleware', async () => {536+ throw new Error('This is Middleware Error')537+ })538+539+ app.onError((err, c) => {540+ c.header('x-debug', err.message)541+ return c.text('Custom Error Message', 500)542+ })543+544+ it('Custom Error Message', async () => {545+ let res = await app.request('https://example.com/error')546+ expect(res.status).toBe(500)547+ expect(await res.text()).toBe('Custom Error Message')548+ expect(res.headers.get('x-debug')).toBe('This is Error')549+550+ res = await app.request('https://example.com/error-middleware')551+ expect(res.status).toBe(500)552+ expect(await res.text()).toBe('Custom Error Message')553+ expect(res.headers.get('x-debug')).toBe('This is Middleware Error')554+ })555+})556+557+describe('Request methods with custom middleware', () => {558+ const app = new Hono()559+560+ app.use('*', async (c, next) => {561+ const query = c.req.query('foo')562+ const param = c.req.param('foo')563+ const header = c.req.header('User-Agent')564+ await next()565+ c.header('X-Query-2', query)566+ c.header('X-Param-2', param)567+ c.header('X-Header-2', header)568+ })569+570+ app.get('/:foo', (c) => {571+ const query = c.req.query('foo')572+ const param = c.req.param('foo')573+ const header = c.req.header('User-Agent')574+ c.header('X-Query', query)575+ c.header('X-Param', param)576+ c.header('X-Header', header)577+ return c.body('Hono')578+ })579+580+ it('query', async () => {581+ const url = new URL('http://localhost/bar')582+ url.searchParams.append('foo', 'bar')583+ const req = new Request(url.toString())584+ req.headers.append('User-Agent', 'bar')585+ const res = await app.request(req)586+587+ expect(res.status).toBe(200)588+ expect(res.headers.get('X-Query')).toBe('bar')589+ expect(res.headers.get('X-Param')).toBe('bar')590+ expect(res.headers.get('X-Header')).toBe('bar')591+592+ expect(res.headers.get('X-Query-2')).toBe('bar')593+ expect(res.headers.get('X-Param-2')).toBe('bar')594+ expect(res.headers.get('X-Header-2')).toBe('bar')595+ })596+})597+598+describe('Hono with `app.route`', () => {599+ describe('Basic', () => {600+ const app = new Hono()601+ const api = new Hono()602+ const middleware = new Hono()603+604+ api.use('*', async (c, next) => {605+ await next()606+ c.res.headers.append('x-custom-a', 'a')607+ })608+609+ api.get('/posts', (c) => c.text('List'))610+ api.post('/posts', (c) => c.text('Create'))611+ api.get('/posts/:id', (c) => c.text(`GET ${c.req.param('id')}`))612+613+ middleware.use('*', async (c, next) => {614+ await next()615+ c.res.headers.append('x-custom-b', 'b')616+ })617+618+ app.route('/api', middleware)619+ app.route('/api', api)620+621+ app.get('/foo', (c) => c.text('bar'))622+623+ it('Should return not found response', async () => {624+ const res = await app.request('http://localhost/')625+ expect(res.status).toBe(404)626+ })627+628+ it('Should return not found response', async () => {629+ const res = await app.request('http://localhost/posts')630+ expect(res.status).toBe(404)631+ })632+633+ test('GET /api/posts', async () => {634+ const res = await app.request('http://localhost/api/posts')635+ expect(res.status).toBe(200)636+ expect(await res.text()).toBe('List')637+ })638+639+ test('Custom header by middleware', async () => {640+ const res = await app.request('http://localhost/api/posts')641+ expect(res.status).toBe(200)642+ expect(res.headers.get('x-custom-a')).toBe('a')643+ expect(res.headers.get('x-custom-b')).toBe('b')644+ })645+646+ test('POST /api/posts', async () => {647+ const res = await app.request('http://localhost/api/posts', { method: 'POST' })648+ expect(res.status).toBe(200)649+ expect(await res.text()).toBe('Create')650+ })651+652+ test('GET /api/posts/123', async () => {653+ const res = await app.request('http://localhost/api/posts/123')654+ expect(res.status).toBe(200)655+ expect(await res.text()).toBe('GET 123')656+ })657+658+ test('GET /foo', async () => {659+ const res = await app.request('http://localhost/foo')660+ expect(res.status).toBe(200)661+ expect(await res.text()).toBe('bar')662+ })663+ })664+665+ describe('Chaining', () => {666+ const app = new Hono()667+ const route = new Hono()668+ route.get('/post', (c) => c.text('GET /POST v2')).post((c) => c.text('POST /POST v2'))669+ app.route('/v2', route)670+671+ it('Should return 200 response - GET /v2/post', async () => {672+ const res = await app.request('http://localhost/v2/post')673+ expect(res.status).toBe(200)674+ expect(await res.text()).toBe('GET /POST v2')675+ })676+677+ it('Should return 200 response - POST /v2/post', async () => {678+ const res = await app.request('http://localhost/v2/post', { method: 'POST' })679+ expect(res.status).toBe(200)680+ expect(await res.text()).toBe('POST /POST v2')681+ })682+683+ it('Should return 404 response - DELETE /v2/post', async () => {684+ const res = await app.request('http://localhost/v2/post', { method: 'DELETE' })685+ expect(res.status).toBe(404)686+ })687+ })688+689+ describe('Nested', () => {690+ const app = new Hono()691+ const api = new Hono()692+ const book = new Hono()693+694+ book.get('/', (c) => c.text('list books'))695+ book.get('/:id', (c) => c.text(`book ${c.req.param('id')}`))696+697+ api.get('/', (c) => c.text('this is API'))698+ api.route('/book', book)699+700+ app.get('/', (c) => c.text('root'))701+ app.route('/v2', api)702+703+ it('Should return 200 response - GET /', async () => {704+ const res = await app.request('http://localhost/')705+ expect(res.status).toBe(200)706+ expect(await res.text()).toBe('root')707+ })708+709+ it('Should return 200 response - GET /v2', async () => {710+ const res = await app.request('http://localhost/v2')711+ expect(res.status).toBe(200)712+ expect(await res.text()).toBe('this is API')713+ })714+715+ it('Should return 200 response - GET /v2/book', async () => {716+ const res = await app.request('http://localhost/v2/book')717+ expect(res.status).toBe(200)718+ expect(await res.text()).toBe('list books')719+ })720+721+ it('Should return 200 response - GET /v2/book/123', async () => {722+ const res = await app.request('http://localhost/v2/book/123')723+ expect(res.status).toBe(200)724+ expect(await res.text()).toBe('book 123')725+ })726+ })727+})728+729+describe('Multiple handler', () => {730+ describe('handler + handler', () => {731+ const app = new Hono()732+733+ app.get('/posts/:id', (c) => {734+ const id = c.req.param('id')735+ c.header('foo', 'bar')736+ return c.text(`id is ${id}`)737+ })738+739+ app.get('/:type/:id', (c) => {740+ c.status(404)741+ c.header('foo2', 'bar2')742+ return c.text('foo')743+ })744+ it('Should return response from `specialized` route', async () => {745+ const res = await app.request('http://localhost/posts/123')746+ expect(res.status).toBe(200)747+ expect(await res.text()).toBe('id is 123')748+ expect(res.headers.get('foo')).toBe('bar')749+ expect(res.headers.get('foo2')).toBeNull()750+ })751+ })752+753+ describe('Duplicate param name', () => {754+ it('self', () => {755+ const app = new Hono()756+ expect(() => {757+ app.get('/:id/:id', (c) => {758+ const id = c.req.param('id')759+ return c.text(`id is ${id}`)760+ })761+ }).toThrowError(/Duplicate param name/)762+ })763+764+ it('parent', () => {765+ const app = new Hono()766+ app.get('/:id/:action', (c) => {767+ return c.text('foo')768+ })769+ expect(() => {770+ app.get('/posts/:id', (c) => {771+ const id = c.req.param('id')772+ return c.text(`id is ${id}`)773+ })774+ }).toThrowError(/Duplicate param name/)775+ })776+777+ it('child', () => {778+ const app = new Hono()779+ app.get('/posts/:id', (c) => {780+ return c.text('foo')781+ })782+ expect(() => {783+ app.get('/:id/:action', (c) => {784+ const id = c.req.param('id')785+ return c.text(`id is ${id}`)786+ })787+ }).toThrowError(/Duplicate param name/)788+ })789+790+ it('hierarchy', () => {791+ const app = new Hono()792+ app.get('/posts/:id/comments/:comment_id', (c) => {793+ return c.text('foo')794+ })795+ expect(() => {796+ app.get('/posts/:id', (c) => {797+ const id = c.req.param('id')798+ return c.text(`id is ${id}`)799+ })800+ }).not.toThrow()801+ })802+803+ it('different regular expression', () => {804+ const app = new Hono()805+ app.get('/:id/:action{create|update}', (c) => {806+ return c.text('foo')807+ })808+ expect(() => {809+ app.get('/:id/:action{delete}', (c) => {810+ const id = c.req.param('id')811+ return c.text(`id is ${id}`)812+ })813+ }).not.toThrow()814+ })815+ })816+})817+818+describe('Multiple handler - async', () => {819+ describe('handler + handler', () => {820+ const app = new Hono()821+ app.get('/posts/:id', async (c) => {822+ await new Promise((resolve) => setTimeout(resolve, 1))823+ c.header('foo2', 'bar2')824+ const id = c.req.param('id')825+ return c.text(`id is ${id}`)826+ })827+ app.get('/:type/:id', async (c) => {828+ await new Promise((resolve) => setTimeout(resolve, 1))829+ c.header('foo', 'bar')830+ c.status(404)831+ return c.text('foo')832+ })833+834+ it('Should return response from `specialized` route', async () => {835+ const res = await app.request('http://localhost/posts/123')836+ expect(res.status).toBe(200)837+ expect(await res.text()).toBe('id is 123')838+ expect(res.headers.get('foo')).toBeNull()839+ expect(res.headers.get('foo2')).toBe('bar2')840+ })841+ })842+})843+844+describe('Context is not finalized', () => {845+ it('should throw error - lack `await next()`', async () => {846+ const app = new Hono()847+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment848+ // @ts-ignore849+ app.use('*', () => {})850+ app.get('/foo', (c) => {851+ return c.text('foo')852+ })853+ app.onError((err, c) => {854+ return c.text(err.message, 500)855+ })856+ const res = await app.request('http://localhost/foo')857+ expect(res.status).toBe(500)858+ expect(await res.text()).toMatch(/^Context is not finalized/)859+ })860+861+ it('should throw error - lack `returning Response`', async () => {862+ const app = new Hono()863+ app.use('*', async (_c, next) => {864+ await next()865+ })866+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment867+ // @ts-ignore868+ app.get('/foo', () => {})869+ app.onError((err, c) => {870+ return c.text(err.message, 500)871+ })872+ const res = await app.request('http://localhost/foo')873+ expect(res.status).toBe(500)874+ expect(await res.text()).toMatch(/^Context is not finalized/)875+ })876+})added:deno_dist/hono.ts+209 added
1+import { compose } from './compose.ts'2+import { Context } from './context.ts'3+import type { Env } from './context.ts'4+import { extendRequestPrototype } from './request.ts'5+import type { Router } from './router.ts'6+import { METHOD_NAME_ALL, METHOD_NAME_ALL_LOWERCASE } from './router.ts'7+import { TrieRouter } from './router/trie-router/index.ts' // Default Router8+import { getPathFromURL, mergePath } from './utils/url.ts'9+10+export type Handler<RequestParamKeyType extends string = string, E = Env> = (11+ c: Context<RequestParamKeyType, E>,12+ next: Next13+) => Response | Promise<Response> | Promise<void> | Promise<Response | undefined>14+export type NotFoundHandler<E = Env> = (c: Context<string, E>) => Response | Promise<Response>15+export type ErrorHandler<E = Env> = (err: Error, c: Context<string, E>) => Response16+export type Next = () => Promise<void>17+18+// eslint-disable-next-line @typescript-eslint/no-unused-vars19+type ParamKeyName<NameWithPattern> = NameWithPattern extends `${infer Name}{${infer _Pattern}`20+ ? Name21+ : NameWithPattern22+23+type ParamKey<Component> = Component extends `:${infer NameWithPattern}`24+ ? ParamKeyName<NameWithPattern>25+ : never26+27+type ParamKeys<Path> = Path extends `${infer Component}/${infer Rest}`28+ ? ParamKey<Component> | ParamKeys<Rest>29+ : ParamKey<Path>30+31+interface HandlerInterface<T extends string, E extends Env = Env, U = Hono<E, T>> {32+ // app.get('/', handler, handler...)33+ <Path extends string>(34+ path: Path,35+ ...handlers: Handler<ParamKeys<Path> extends never ? string : ParamKeys<Path>, E>[]36+ ): U37+ (path: string, ...handlers: Handler<string, E>[]): U38+ // app.get(handler...)39+ <Path extends string>(40+ ...handlers: Handler<ParamKeys<Path> extends never ? string : ParamKeys<Path>, E>[]41+ ): U42+ (...handlers: Handler<string, E>[]): U43+}44+45+const methods = ['get', 'post', 'put', 'delete', 'head', 'options', 'patch'] as const46+type Methods = typeof methods[number] | typeof METHOD_NAME_ALL_LOWERCASE47+48+function defineDynamicClass(): {49+ new <E extends Env, T extends string, U>(): {50+ [K in Methods]: HandlerInterface<T, E, U>51+ }52+} {53+ return class {} as any54+}55+56+interface Route<E extends Env> {57+ path: string58+ method: string59+ handler: Handler<string, E>60+}61+62+export class Hono<E extends Env = Env, P extends string = '/'> extends defineDynamicClass()<63+ E,64+ P,65+ Hono<E, P>66+> {67+ readonly router: Router<Handler<string, E>> = new TrieRouter()68+ readonly strict: boolean = true // strict routing - default is true69+ private _tempPath: string = ''70+ private path: string = '/'71+72+ routes: Route<E>[] = []73+74+ constructor(init: Partial<Pick<Hono, 'router' | 'strict'>> = {}) {75+ super()76+77+ extendRequestPrototype()78+79+ const allMethods = [...methods, METHOD_NAME_ALL_LOWERCASE]80+ allMethods.map((method) => {81+ this[method] = <Path extends string = ''>(82+ args1: Path | Handler<ParamKeys<Path>, E>,83+ ...args: [Handler<ParamKeys<Path>, E>]84+ ) => {85+ if (typeof args1 === 'string') {86+ this.path = args187+ } else {88+ this.addRoute(method, this.path, args1)89+ }90+ args.map((handler) => {91+ if (typeof handler !== 'string') {92+ this.addRoute(method, this.path, handler)93+ }94+ })95+ return this96+ }97+ })98+99+ Object.assign(this, init)100+ }101+102+ private notFoundHandler: NotFoundHandler = (c: Context) => {103+ const message = '404 Not Found'104+ return c.text(message, 404)105+ }106+107+ private errorHandler: ErrorHandler = (err: Error, c: Context) => {108+ console.error(`${err.stack || err.message}`)109+ const message = 'Internal Server Error'110+ return c.text(message, 500)111+ }112+113+ route(path: string, app?: Hono<any>): Hono<E, P> {114+ this._tempPath = path115+ if (app) {116+ app.routes.map((r) => {117+ this.addRoute(r.method, r.path, r.handler)118+ })119+ this._tempPath = ''120+ }121+122+ return this123+ }124+125+ use(path: string, ...middleware: Handler<string, E>[]): Hono<E, P>126+ use(...middleware: Handler<string, E>[]): Hono<E, P>127+ use(arg1: string | Handler<string, E>, ...handlers: Handler<string, E>[]): Hono<E, P> {128+ if (typeof arg1 === 'string') {129+ this.path = arg1130+ } else {131+ handlers.unshift(arg1)132+ }133+ handlers.map((handler) => {134+ this.addRoute(METHOD_NAME_ALL, this.path, handler)135+ })136+ return this137+ }138+139+ onError(handler: ErrorHandler<E>): Hono<E, P> {140+ this.errorHandler = handler as ErrorHandler141+ return this142+ }143+144+ notFound(handler: NotFoundHandler<E>): Hono<E, P> {145+ this.notFoundHandler = handler as NotFoundHandler146+ return this147+ }148+149+ private addRoute(method: string, path: string, handler: Handler<string, E>): void {150+ method = method.toUpperCase()151+ if (this._tempPath) {152+ path = mergePath(this._tempPath, path)153+ }154+ this.router.add(method, path, handler)155+ const r: Route<E> = { path: path, method: method, handler: handler }156+ this.routes.push(r)157+ }158+159+ private matchRoute(method: string, path: string) {160+ return this.router.match(method, path)161+ }162+163+ private async dispatch(164+ request: Request,165+ eventOrExecutionCtx?: ExecutionContext | FetchEvent,166+ env?: E167+ ): Promise<Response> {168+ const path = getPathFromURL(request.url, this.strict)169+ const method = request.method170+171+ const result = this.matchRoute(method, path)172+ request.paramData = result?.params173+174+ const handlers = result ? result.handlers : [this.notFoundHandler]175+176+ const c = new Context<string, E>(request, env, eventOrExecutionCtx, this.notFoundHandler)177+178+ const composed = compose<Context>(handlers, this.errorHandler, this.notFoundHandler)179+ let context: Context180+ try {181+ context = await composed(c)182+ if (!context.finalized) {183+ throw new Error(184+ 'Context is not finalized. You may forget returning Response object or `await next()`'185+ )186+ }187+ } catch (err) {188+ if (err instanceof Error) {189+ return this.errorHandler(err, c)190+ }191+ throw err192+ }193+194+ return context.res195+ }196+197+ async handleEvent(event: FetchEvent): Promise<Response> {198+ return this.dispatch(event.request, event)199+ }200+201+ async fetch(request: Request, env?: E, executionCtx?: ExecutionContext): Promise<Response> {202+ return this.dispatch(request, executionCtx, env)203+ }204+205+ request(input: RequestInfo, requestInit?: RequestInit): Promise<Response> {206+ const req = input instanceof Request ? input : new Request(input, requestInit)207+ return this.dispatch(req)208+ }209+}added:deno_dist/index.ts+21 added
1+// eslint-disable-next-line @typescript-eslint/triple-slash-reference2+/// <reference path="./request.ts" /> Import "declare global" for the Request interface.3+4+import { Hono } from './hono.ts'5+export type { Handler, Next } from './hono.ts'6+export { Context } from './context.ts'7+export type { Env } from './context.ts'8+9+declare module './hono.ts' {10+ interface Hono {11+ fire(): void12+ }13+}14+15+Hono.prototype.fire = function () {16+ addEventListener('fetch', (event: FetchEvent): void => {17+ void event.respondWith(this.handleEvent(event))18+ })19+}20+21+export { Hono }added:deno_dist/LICENSE+21 added
1+MIT License2+3+Copyright (c) 2021 Yusuke Wada4+5+Permission is hereby granted, free of charge, to any person obtaining a copy6+of this software and associated documentation files (the "Software"), to deal7+in the Software without restriction, including without limitation the rights8+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell9+copies of the Software, and to permit persons to whom the Software is10+furnished to do so, subject to the following conditions:11+12+The above copyright notice and this permission notice shall be included in all13+copies or substantial portions of the Software.14+15+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR16+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,17+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE18+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER19+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,20+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE21+SOFTWARE.added:deno_dist/mod.ts+52 added
1+import { Hono } from './hono.ts'2+3+declare global {4+ interface FetchEvent extends Event {5+ readonly request: Request6+ respondWith(response: Promise<Response> | Response): Promise<Response>7+ }8+ interface ExecutionContext {9+ waitUntil(promise: Promise<any>): void10+ passThroughOnException(): void11+ }12+}13+14+interface ConnInfo {15+ readonly localAddr: Deno.Addr16+ readonly remoteAddr: Deno.Addr17+}18+19+declare module './hono.ts' {20+ interface Hono {21+ fire(): (req: Request, connInfo?: ConnInfo) => Response | Promise<Response>22+ }23+}24+25+Hono.prototype.fire = function () {26+ return (req: Request, _connInfo?: ConnInfo): Response | Promise<Response> => {27+ return this.request(req)28+ }29+}30+31+export type { Handler, Next } from './hono.ts'32+export { Context } from './context.ts'33+export type { Env } from './context.ts'34+export { Hono }35+36+// Router37+export { RegExpRouter } from './router/reg-exp-router/index.ts'38+export { TrieRouter } from './router/trie-router/index.ts'39+40+// Middleware41+export { basicAuth } from './middleware/basic-auth/index.ts'42+export { bearerAuth } from './middleware/bearer-auth/index.ts'43+export { bodyParse } from './middleware/body-parse/index.ts'44+export { cookie } from './middleware/cookie/index.ts'45+export { cors } from './middleware/cors/index.ts'46+export { etag } from './middleware/etag/index.ts'47+export { html } from './middleware/html/index.ts'48+export { jsx } from './middleware/jsx/index.ts'49+export { jwt } from './middleware/jwt/index.ts'50+export { logger } from './middleware/logger/index.ts'51+export { poweredBy } from './middleware/powered-by/index.ts'52+export { prettyJSON } from './middleware/pretty-json/index.ts'added:deno_dist/README.md+769 added
1+<div align="center">2+ <a href="https://github.com/honojs/hono">3+ <img src="https://raw.githubusercontent.com/honojs/hono/master/docs/images/hono-title.png" width="500" height="auto" alt="Hono"/>4+ </a>5+</div>6+7+<hr />8+9+[](https://github.com/honojs/hono/actions)10+[](https://github.com/honojs/hono/blob/master/LICENSE)11+[](https://www.npmjs.com/package/hono)12+[](https://www.npmjs.com/package/hono)13+[](https://www.npmjs.com/package/hono)14+[](https://github.com/honojs/hono/pulse)15+[](https://github.com/honojs/hono/commits/master)16+17+Hono - _**[炎] means flame🔥 in Japanese**_ - is a small, simple, and ultrafast web framework for Cloudflare Workers or Service Worker based serverless such as Fastly Compute@Edge.18+19+```ts20+import { Hono } from 'hono'21+const app = new Hono()22+23+app.get('/', (c) => c.text('Hono!!'))24+25+app.fire()26+```27+28+## Features29+30+- **Ultrafast** - the router does not use linear loops.31+- **Zero-dependencies** - using only Service Worker and Web Standard API.32+- **Middleware** - built-in middleware and ability to extend with your own middleware.33+- **TypeScript** - first-class TypeScript support.34+- **Optimized** - for Cloudflare Workers.35+36+## Benchmark37+38+**Hono is fastest**, compared to other routers for Cloudflare Workers.39+40+```plain41+hono - trie-router(default) x 389,510 ops/sec ±3.16% (85 runs sampled)42+hono - regexp-router x 452,290 ops/sec ±2.64% (84 runs sampled)43+itty-router x 206,013 ops/sec ±3.39% (90 runs sampled)44+sunder x 323,131 ops/sec ±0.75% (97 runs sampled)45+worktop x 191,218 ops/sec ±2.70% (91 runs sampled)46+Fastest is hono - regexp-router47+✨ Done in 43.56s.48+```49+50+## Why so fast?51+52+Routers used in Hono are really smart.53+54+- **TrieRouter**(default) - Implemented with Trie tree structure.55+- **RegExpRouter** - Match the route with using one big Regex made before dispatch.56+57+## Hono in 1 minute58+59+A demonstration to create an application for Cloudflare Workers with Hono.60+61+62+63+## Not only fast64+65+Hono is fast. But not only fast.66+67+### Write Less, do more68+69+Built-in middleware make _"**Write Less, do more**"_ in reality. You can use a lot of middleware without writing code from scratch. Below are examples.70+71+- [Basic Authentication](https://github.com/honojs/hono/tree/master/src/middleware/basic-auth/)72+- [Cookie parsing / serializing](https://github.com/honojs/hono/tree/master/src/middleware/cookie/)73+- [CORS](https://github.com/honojs/hono/tree/master/src/middleware/cors/)74+- [ETag](https://github.com/honojs/hono/tree/master/src/middleware/etag/)75+- [GraphQL Server](https://github.com/honojs/hono/tree/master/src/middleware/graphql-server/)76+- [html](https://github.com/honojs/hono/tree/master/src/middleware/html/)77+- [JSX](https://github.com/honojs/hono/tree/master/src/middleware/jsx/)78+- [JWT Authentication](https://github.com/honojs/hono/tree/master/src/middleware/jwt/)79+- [Logger](https://github.com/honojs/hono/tree/master/src/middleware/logger/)80+- [Mustache template engine](https://github.com/honojs/hono/tree/master/src/middleware/mustache/) (Only for Cloudflare Workers)81+- [JSON pretty printing](https://github.com/honojs/hono/tree/master/src/middleware/pretty-json/)82+- [Serving static files](https://github.com/honojs/hono/tree/master/src/middleware/serve-static/) (Only for Cloudflare Workers)83+84+To enable logger and Etag middleware with just this code.85+86+```ts87+import { Hono } from 'hono'88+import { etag } from 'hono/etag'89+import { logger } from 'hono/logger'90+91+const app = new Hono()92+app.use('*', etag(), logger())93+```94+95+And, the routing of Hono is so flexible. It's easy to construct large web applications.96+97+```ts98+import { Hono } from 'hono'99+import { basicAuth } from 'hono/basic-auth'100+101+const v1 = new Hono()102+v1.get('/posts', (c) => {103+ return c.text('list posts')104+})105+ .post(basicAuth({ username, password }), (c) => {106+ return c.text('created!', 201)107+ })108+ .get('/posts/:id', (c) => {109+ const id = c.req.param('id')110+ return c.text(`your id is ${id}`)111+ })112+113+const app = new Hono()114+app.route('/v1', v1)115+```116+117+### Web Standard118+119+Request and Response object used in Hono are extensions of the Web Standard [Fetch API](https://developer.mozilla.org/ja/docs/Web/API/Fetch_API). If you are familiar with that, you don't need to know more than that.120+121+### Developer Experience122+123+Hono provides fine _"**Developer Experience**"_. Easy access to Request/Response thanks to the `Context` object.124+Above all, Hono is written in TypeScript. So, Hono has _"**Types**"_!125+126+For example, the named path parameters will be literal types.127+128+129+130+## Install131+132+You can install Hono from the npm registry.133+134+```sh135+npm install hono136+```137+138+## Methods139+140+An instance of `Hono` has these methods.141+142+- app.**HTTP_METHOD**(\[path,\]handler|middleware...)143+- app.**all**(\[path,\]handler|middleware...)144+- app.**route**(path, \[app\])145+- app.**use**(\[path,\]middleware)146+- app.**notFound**(handler)147+- app.**onError**(err, handler)148+- app.**fire**()149+- app.**fetch**(request, env, event)150+- app.**request**(path, options)151+152+## Routing153+154+### Basic155+156+```ts157+// HTTP Methods158+app.get('/', (c) => c.text('GET /'))159+app.post('/', (c) => c.text('POST /'))160+app.put('/', (c) => c.text('PUT /'))161+app.delete('/', (c) => c.text('DELETE /'))162+163+// Wildcard164+app.get('/wild/*/card', (c) => {165+ return c.text('GET /wild/*/card')166+})167+168+// Any HTTP methods169+app.all('/hello', (c) => c.text('Any Method /hello'))170+```171+172+### Named Parameter173+174+```ts175+app.get('/user/:name', (c) => {176+ const name = c.req.param('name')177+ ...178+})179+```180+181+or all parameters at once:182+183+```ts184+app.get('/posts/:id/comment/:comment_id', (c) => {185+ const { id, comment_id } = c.req.param()186+ ...187+})188+```189+190+### Regexp191+192+```ts193+app.get('/post/:date{[0-9]+}/:title{[a-z]+}', (c) => {194+ const { date, title } = c.req.param()195+ ...196+})197+```198+199+### Chained route200+201+```ts202+app203+ .get('/endpoint', (c) => {204+ return c.text('GET /endpoint')205+ })206+ .post((c) => {207+ return c.text('POST /endpoint')208+ })209+ .delete((c) => {210+ return c.text('DELETE /endpoint')211+ })212+```213+214+### no strict215+216+If `strict` is set false, `/hello`and`/hello/` are treated the same.217+218+```ts219+const app = new Hono({ strict: false }) // Default is true220+221+app.get('/hello', (c) => c.text('/hello or /hello/'))222+```223+224+### async/await225+226+```js227+app.get('/fetch-url', async (c) => {228+ const response = await fetch('https://example.com/')229+ return c.text(`Status is ${response.status}`)230+})231+```232+233+## Grouping234+235+Group the routes with `Hono` instance and add them to the main app with `route` method.236+237+```ts238+const book = new Hono()239+240+book.get('/', (c) => c.text('List Books')) // GET /book241+book.get('/:id', (c) => {242+ // GET /book/:id243+ const id = c.req.param('id')244+ return c.text('Get Book: ' + id)245+})246+book.post('/', (c) => c.text('Create Book')) // POST /book247+248+const app = new Hono()249+app.route('/book', book)250+```251+252+## Middleware253+254+Middleware works after/before Handler. We can get `Request` before dispatching or manipulate `Response` after dispatching.255+256+### Definition of Middleware257+258+- Handler - should return `Response` object. Only one handler will be called.259+- Middleware - should return nothing, will be proceeded to next middleware with `await next()`260+261+The user can register middleware using `c.use` or using `c.HTTP_METHOD` as well as the handlers. For this feature, it's easy to specify the path and the method.262+263+```ts264+// match any method, all routes265+app.use('*', logger())266+267+// specify path268+app.use('/posts/*', cors())269+270+// specify method and path271+app.post('/posts/*', basicAuth(), bodyParse())272+```273+274+If the handler returns `Response`, it will be used for the end-user, and stopping the processing.275+276+```ts277+app.post('/posts', (c) => c.text('Created!', 201))278+```279+280+In this case, four middleware are processed before dispatching like this:281+282+```ts283+logger() -> cors() -> basicAuth() -> bodyParse() -> *handler*284+```285+286+### Built-in Middleware287+288+Hono has built-in middleware.289+290+```ts291+import { Hono } from 'hono'292+import { poweredBy } from 'hono/powered-by'293+import { logger } from 'hono/logger'294+import { basicAuth } from 'hono/basicAuth'295+296+const app = new Hono()297+298+app.use('*', poweredBy())299+app.use('*', logger())300+301+app.use(302+ '/auth/*',303+ basicAuth({304+ username: 'hono',305+ password: 'acoolproject',306+ })307+)308+```309+310+Available built-in middleware is listed on [src/middleware](https://github.com/honojs/hono/tree/master/src/middleware).311+312+### Custom Middleware313+314+You can write your own middleware.315+316+```ts317+// Custom logger318+app.use('*', async (c, next) => {319+ console.log(`[${c.req.method}] ${c.req.url}`)320+ await next()321+})322+323+// Add a custom header324+app.use('/message/*', async (c, next) => {325+ await next()326+ c.header('x-message', 'This is middleware!')327+})328+329+app.get('/message/hello', (c) => c.text('Hello Middleware!'))330+```331+332+## Not Found333+334+`app.notFound` for customizing Not Found Response.335+336+```js337+app.notFound((c) => {338+ return c.text('Custom 404 Message', 404)339+})340+```341+342+## Error Handling343+344+`app.onError` handle the error and return the customized Response.345+346+```js347+app.onError((err, c) => {348+ console.error(`${err}`)349+ return c.text('Custom Error Message', 500)350+})351+```352+353+## Context354+355+To handle Request and Response, you can use `Context` object.356+357+### c.req358+359+```ts360+// Get Request object361+app.get('/hello', (c) => {362+ const userAgent = c.req.headers.get('User-Agent')363+ ...364+})365+366+// Shortcut to get a header value367+app.get('/shortcut', (c) => {368+ const userAgent = c.req.header('User-Agent')369+ ...370+})371+372+// Query params373+app.get('/search', (c) => {374+ const query = c.req.query('q')375+ ...376+})377+378+// Get all params at once379+app.get('/search', (c) => {380+ const { q, limit, offset } = c.req.query()381+ ...382+})383+384+// Multiple query values385+app.get('/search', (c) => {386+ const queries = c.req.queries('q')387+ // ---> GET search?q=foo&q=bar388+ // queries[0] => foo, queries[1] => bar389+ ...390+})391+392+// Captured params393+app.get('/entry/:id', (c) => {394+ const id = c.req.param('id')395+ ...396+})397+```398+399+### Shortcuts for Response400+401+```ts402+app.get('/welcome', (c) => {403+ // Set headers404+ c.header('X-Message', 'Hello!')405+ c.header('Content-Type', 'text/plain')406+407+ // Set HTTP status code408+ c.status(201)409+410+ // Return the response body411+ return c.body('Thank you for comming')412+})413+```414+415+The Response is the same as below.416+417+```ts418+new Response('Thank you for comming', {419+ status: 201,420+ headers: {421+ 'X-Message': 'Hello',422+ 'Content-Type': 'text/plain',423+ },424+})425+```426+427+### c.text()428+429+Render text as `Content-Type:text/plain`.430+431+```ts432+app.get('/say', (c) => {433+ return c.text('Hello!')434+})435+```436+437+### c.json()438+439+Render JSON as `Content-Type:application/json`.440+441+```ts442+app.get('/api', (c) => {443+ return c.json({ message: 'Hello!' })444+})445+```446+447+### c.html()448+449+Render HTML as `Content-Type:text/html`.450+451+```ts452+app.get('/', (c) => {453+ return c.html('<h1>Hello! Hono!</h1>')454+})455+```456+457+### c.notFound()458+459+Return the `Not Found` Response.460+461+```ts462+app.get('/notfound', (c) => {463+ return c.notFound()464+})465+```466+467+### c.redirect()468+469+Redirect, default status code is `302`.470+471+```ts472+app.get('/redirect', (c) => c.redirect('/'))473+app.get('/redirect-permanently', (c) => c.redirect('/', 301))474+```475+476+### c.res477+478+```ts479+// Response object480+app.use('/', async (c, next) => {481+ await next()482+ c.res.headers.append('X-Debug', 'Debug message')483+})484+```485+486+### c.executionCtx487+488+```ts489+// ExecutionContext object490+app.get('/foo', async (c) => {491+ c.executionCtx.waitUntil(492+ c.env.KV.put(key, data)493+ )494+ ...495+})496+```497+498+### c.event499+500+```ts501+// FetchEvent object (only set when using Service Worker syntax)502+app.get('/foo', async (c) => {503+ c.event.waitUntil(504+ c.env.KV.put(key, data)505+ )506+ ...507+})508+```509+510+### c.env511+512+Environment variables, secrets, and KV namespaces are known as bindings. Regardless of type, bindings are always available as global variables and can be accessed via the context `c.env.BINDING_KEY`.513+514+```ts515+// Environment object for Cloudflare Workers516+app.get('*', async c => {517+ const counter = c.env.COUNTER518+ ...519+})520+```521+522+## fire523+524+`app.fire()` do this.525+526+```ts527+addEventListener('fetch', (event) => {528+ event.respondWith(this.handleEvent(event))529+})530+```531+532+## fetch533+534+`app.fetch` for Cloudflare Module Worker syntax.535+536+```ts537+export default {538+ fetch(request: Request, env: Env, ctx: ExecutionContext) {539+ return app.fetch(request, env, ctx)540+ },541+}542+```543+544+or just do:545+546+```ts547+export default app548+```549+550+## request551+552+`request` is a useful method for testing.553+554+```js555+test('GET /hello is ok', async () => {556+ const res = await app.request('http://localhost/hello')557+ expect(res.status).toBe(200)558+})559+```560+561+## router562+563+The `router` option specify which router is used inside. The default router is `TrieRouter`. If you want to use `RexExpRouter`, write like this:564+565+```ts566+import { RegExpRouter } from 'hono/router/reg-exp-router'567+568+const app = new Hono({ router: new RegExpRouter() })569+```570+571+## Routing priority572+573+Handlers or middleware will be executed in registration order.574+575+```ts576+app.get('/book/a', (c) => c.text('a')) // a577+app.get('/book/:slug', (c) => c.text('common')) // common578+```579+580+```http581+GET /book/a ---> `a`582+GET /book/b ---> `common`583+```584+585+When a handler is executed, the process will be stopped.586+587+```ts588+app.get('*', (c) => c.text('common')) // common589+app.get('/foo', (c) => c.text('foo')) // foo590+```591+592+```http593+GET /foo ---> `common` // foo will not be dispatched594+```595+596+If you have the middleware that you want to execute, write the code above the handler.597+598+```ts599+app.use('*', logger())600+app.get('/foo', (c) => c.text('foo'))601+```602+603+If you want a "_fallback_" handler, write the code below the other handler.604+605+```ts606+app.get('/foo', (c) => c.text('foo')) // foo607+app.get('*', (c) => c.text('fallback')) // fallback608+```609+610+```http611+GET /bar ---> `fallback`612+```613+614+## Cloudflare Workers with Hono615+616+Using [Wrangler](https://developers.cloudflare.com/workers/cli-wrangler/), you can develop the application locally and publish it with few commands.617+618+Let's write your first code for Cloudflare Workers with Hono.619+620+### 1. `wrangler init`621+622+Initialize as a wrangler project.623+624+```625+mkdir hono-example626+cd hono-example627+npx wrangler init -y628+```629+630+### 2. `npm install hono`631+632+Install `hono` from the npm registry.633+634+```635+npm init -y636+npm i hono637+```638+639+### 3. Write your app640+641+Edit `src/index.ts`. Only 4 lines!!642+643+```ts644+// src/index.ts645+import { Hono } from 'hono'646+const app = new Hono()647+648+app.get('/', (c) => c.text('Hello! Hono!'))649+650+app.fire()651+```652+653+### 4. Run654+655+Run the development server locally. Then, access `http://127.0.0.1:8787/` in your Web browser.656+657+```658+npx wrangler dev659+```660+661+### 5. Publish662+663+Deploy to Cloudflare. That's all!664+665+```666+npx wrangler publish ./src/index.ts667+```668+669+## Starter template670+671+You can start making your Cloudflare Workers application with [the starter template](https://github.com/honojs/hono-minimal). It is really minimal using TypeScript, esbuild, Miniflare, and Jest.672+673+To generate a project skeleton, run this command.674+675+```676+npx create-cloudflare my-app https://github.com/honojs/hono-minimal677+```678+679+## Practical Example680+681+How about writing web API with Hono?682+683+```ts684+import { Hono } from 'hono'685+import { cors } from 'hono/cors'686+import { basicAuth } from 'hono/basic-auth'687+import { prettyJSON } from 'hono/pretty-json'688+import { getPosts, getPost, createPost, Post } from './model'689+690+const app = new Hono()691+app.get('/', (c) => c.text('Pretty Blog API'))692+app.use('*', prettyJSON())693+app.notFound((c) => c.json({ message: 'Not Found', ok: false }, 404))694+695+export interface Bindings {696+ USERNAME: string697+ PASSWORD: string698+}699+700+const api = new Hono<Bindings>()701+api.use('/posts/*', cors())702+703+api.get('/posts', (c) => {704+ const { limit, offset } = c.req.query()705+ const posts = getPosts({ limit, offset })706+ return c.json({ posts })707+})708+709+api.get('/posts/:id', (c) => {710+ const id = c.req.param('id')711+ const post = getPost({ id })712+ return c.json({ post })713+})714+715+api.post(716+ '/posts',717+ async (c, next) => {718+ const auth = basicAuth({ username: c.env.USERNAME, password: c.env.PASSWORD })719+ await auth(c, next)720+ },721+ async (c) => {722+ const post = await c.req.json<Post>()723+ const ok = createPost({ post })724+ return c.json({ ok })725+ }726+)727+728+app.route('/api', api)729+730+export default app731+```732+733+## Other Examples734+735+- Hono Examples - <https://github.com/honojs/examples>736+737+## Related projects738+739+Implementation of the original router `TrieRouter` is inspired by [goblin](https://github.com/bmf-san/goblin). `RegExpRouter` is inspired by [Router::Boom](https://github.com/tokuhirom/Router-Boom). API design is inspired by [express](https://github.com/expressjs/express) and [koa](https://github.com/koajs/koa). [itty-router](https://github.com/kwhitley/itty-router), [Sunder](https://github.com/SunderJS/sunder), and [worktop](https://github.com/lukeed/worktop) are the other routers or frameworks for Cloudflare Workers.740+741+- express - <https://github.com/expressjs/express>742+- koa - <https://github.com/koajs/koa>743+- itty-router - <https://github.com/kwhitley/itty-router>744+- Sunder - <https://github.com/SunderJS/sunder>745+- goblin - <https://github.com/bmf-san/goblin>746+- worktop - <https://github.com/lukeed/worktop>747+- Router::Boom - <https://github.com/tokuhirom/Router-Boom>748+749+## Contributing750+751+Contributions Welcome! You can contribute in the following ways.752+753+- Write or fix documents754+- Write code of middleware755+- Fix bugs756+- Refactor the code757+- etc.758+759+## Contributors760+761+Thanks to [all contributors](https://github.com/honojs/hono/graphs/contributors)! Especially, [@metrue](https://github.com/metrue) and [@usualoma](https://github.com/usualoma)!762+763+## Author764+765+Yusuke Wada <https://github.com/yusukebe>766+767+## License768+769+Distributed under the MIT License. See [LICENSE](LICENSE) for more information.added:deno_dist/request.ts+77 added
1+declare global {2+ interface Request<ParamKeyType extends string = string> {3+ param: {4+ (key: ParamKeyType): string5+ (): Record<ParamKeyType, string>6+ }7+ paramData?: Record<ParamKeyType, string>8+ query: {9+ (key: string): string10+ (): Record<string, string>11+ }12+ queries: {13+ (key: string): string[]14+ (): Record<string, string[]>15+ }16+ header: {17+ (name: string): string18+ (): Record<string, string>19+ }20+ }21+}22+23+export function extendRequestPrototype() {24+ if (!!Request.prototype.param as boolean) {25+ // already extended26+ return27+ }28+29+ Request.prototype.param = function (this: Request, key?: string) {30+ if (this.paramData) {31+ if (key) {32+ return this.paramData[key]33+ } else {34+ return this.paramData35+ }36+ }37+ return null38+ } as InstanceType<typeof Request>['param']39+40+ Request.prototype.header = function (this: Request, name?: string) {41+ if (name) {42+ return this.headers.get(name)43+ } else {44+ const result: Record<string, string> = {}45+ for (const [key, value] of this.headers) {46+ result[key] = value47+ }48+ return result49+ }50+ } as InstanceType<typeof Request>['header']51+52+ Request.prototype.query = function (this: Request, key?: string) {53+ const url = new URL(this.url)54+ if (key) {55+ return url.searchParams.get(key)56+ } else {57+ const result: Record<string, string> = {}58+ for (const key of url.searchParams.keys()) {59+ result[key] = url.searchParams.get(key) || ''60+ }61+ return result62+ }63+ } as InstanceType<typeof Request>['query']64+65+ Request.prototype.queries = function (this: Request, key?: string) {66+ const url = new URL(this.url)67+ if (key) {68+ return url.searchParams.getAll(key)69+ } else {70+ const result: Record<string, string[]> = {}71+ for (const key of url.searchParams.keys()) {72+ result[key] = url.searchParams.getAll(key)73+ }74+ return result75+ }76+ } as InstanceType<typeof Request>['queries']77+}added:deno_dist/router.ts+12 added
1+export const METHOD_NAME_ALL = 'ALL' as const2+export const METHOD_NAME_ALL_LOWERCASE = 'all' as const3+4+export interface Router<T> {5+ add(method: string, path: string, handler: T): void6+ match(method: string, path: string): Result<T> | null7+}8+9+export interface Result<T> {10+ handlers: T[]11+ params: Record<string, string>12+}added:src/mod.ts+52 added
1+import { Hono } from './hono'2+3+declare global {4+ interface FetchEvent extends Event {5+ readonly request: Request6+ respondWith(response: Promise<Response> | Response): Promise<Response>7+ }8+ interface ExecutionContext {9+ waitUntil(promise: Promise<any>): void10+ passThroughOnException(): void11+ }12+}13+14+interface ConnInfo {15+ readonly localAddr: Deno.Addr16+ readonly remoteAddr: Deno.Addr17+}18+19+declare module './hono' {20+ interface Hono {21+ fire(): (req: Request, connInfo?: ConnInfo) => Response | Promise<Response>22+ }23+}24+25+Hono.prototype.fire = function () {26+ return (req: Request, _connInfo?: ConnInfo): Response | Promise<Response> => {27+ return this.request(req)28+ }29+}30+31+export type { Handler, Next } from './hono'32+export { Context } from './context'33+export type { Env } from './context'34+export { Hono }35+36+// Router37+export { RegExpRouter } from './router/reg-exp-router'38+export { TrieRouter } from './router/trie-router'39+40+// Middleware41+export { basicAuth } from './middleware/basic-auth'42+export { bearerAuth } from './middleware/bearer-auth'43+export { bodyParse } from './middleware/body-parse'44+export { cookie } from './middleware/cookie'45+export { cors } from './middleware/cors'46+export { etag } from './middleware/etag'47+export { html } from './middleware/html'48+export { jsx } from './middleware/jsx'49+export { jwt } from './middleware/jwt'50+export { logger } from './middleware/logger'51+export { poweredBy } from './middleware/powered-by'52+export { prettyJSON } from './middleware/pretty-json'modified:package.json+2 added
9 unmodified lines10 "scripts": {11 "test": "jest",12 "lint": "eslint --ext js,ts src .eslintrc.js",13 "lint:fix": "eslint --ext js,ts src .eslintrc.js --fix",14+ "denoify": "rimraf deno_dist && denoify",15 "build": "rimraf dist && tsc --project tsconfig.build.esm.json && tsc --project tsconfig.build.json",16 "watch": "tsc --project tsconfig.build.json -w",17 "prepublishOnly": "yarn build"18 },115 unmodified lines134 "@types/node": "^17.0.29",135 "@typescript-eslint/eslint-plugin": "^5.21.0",136 "@typescript-eslint/parser": "^5.21.0",137 "crypto-js": "^4.1.1",138+ "denoify": "^0.11.1",139 "eslint": "^8.14.0",140 "eslint-config-prettier": "^8.5.0",141 "eslint-define-config": "^1.4.0",142 "eslint-import-resolver-typescript": "^2.7.1",19 unmodified linesmodified:tsconfig.build.json+1 added
2 unmodified lines3 "include": [4 "src/**/*.ts"5 ],6 "exclude": [7+ "src/mod.ts",8 "src/**/*.test.ts"9 ]10 }modified:yarn.lock+273 added-2 removed
871 unmodified lines872 dependencies:873 "@nodelib/fs.scandir" "2.1.5"874 fastq "^1.6.0"875 876+"@octokit/auth-token@^2.4.4":877+ version "2.5.0"878+ resolved "https://registry.yarnpkg.com/@octokit/auth-token/-/auth-token-2.5.0.tgz#27c37ea26c205f28443402477ffd261311f21e36"879+ integrity sha512-r5FVUJCOLl19AxiuZD2VRZ/ORjp/4IN98Of6YJoJOkY75CIBuYfmiNHGrDwXr+aLGG55igl9QrxX3hbiXlLb+g==880+ dependencies:881+ "@octokit/types" "^6.0.3"882+883+"@octokit/core@^3.5.1":884+ version "3.6.0"885+ resolved "https://registry.yarnpkg.com/@octokit/core/-/core-3.6.0.tgz#3376cb9f3008d9b3d110370d90e0a1fcd5fe6085"886+ integrity sha512-7RKRKuA4xTjMhY+eG3jthb3hlZCsOwg3rztWh75Xc+ShDWOfDDATWbeZpAHBNRpm4Tv9WgBMOy1zEJYXG6NJ7Q==887+ dependencies:888+ "@octokit/auth-token" "^2.4.4"889+ "@octokit/graphql" "^4.5.8"890+ "@octokit/request" "^5.6.3"891+ "@octokit/request-error" "^2.0.5"892+ "@octokit/types" "^6.0.3"893+ before-after-hook "^2.2.0"894+ universal-user-agent "^6.0.0"895+896+"@octokit/endpoint@^6.0.1":897+ version "6.0.12"898+ resolved "https://registry.yarnpkg.com/@octokit/endpoint/-/endpoint-6.0.12.tgz#3b4d47a4b0e79b1027fb8d75d4221928b2d05658"899+ integrity sha512-lF3puPwkQWGfkMClXb4k/eUT/nZKQfxinRWJrdZaJO85Dqwo/G0yOC434Jr2ojwafWJMYqFGFa5ms4jJUgujdA==900+ dependencies:901+ "@octokit/types" "^6.0.3"902+ is-plain-object "^5.0.0"903+ universal-user-agent "^6.0.0"904+905+"@octokit/graphql@^4.5.8":906+ version "4.8.0"907+ resolved "https://registry.yarnpkg.com/@octokit/graphql/-/graphql-4.8.0.tgz#664d9b11c0e12112cbf78e10f49a05959aa22cc3"908+ integrity sha512-0gv+qLSBLKF0z8TKaSKTsS39scVKF9dbMxJpj3U0vC7wjNWFuIpL/z76Qe2fiuCbDRcJSavkXsVtMS6/dtQQsg==909+ dependencies:910+ "@octokit/request" "^5.6.0"911+ "@octokit/types" "^6.0.3"912+ universal-user-agent "^6.0.0"913+914+"@octokit/openapi-types@^12.5.0":915+ version "12.6.0"916+ resolved "https://registry.yarnpkg.com/@octokit/openapi-types/-/openapi-types-12.6.0.tgz#87489027e7089c039eb0ee4f807f7b52294fd8c3"917+ integrity sha512-7uS/1woIC7FvIxNSTcY4BLnNFbPtv/iteW041u7EfrZxFrUzB6C402sLyCEezl89HPHRjQet9Q1SHLMe0StITg==918+919+"@octokit/plugin-paginate-rest@^2.16.8":920+ version "2.21.0"921+ resolved "https://registry.yarnpkg.com/@octokit/plugin-paginate-rest/-/plugin-paginate-rest-2.21.0.tgz#ddd425eaa09214dfdfdc9cc411fcf676b8985e65"922+ integrity sha512-MoGEKjvDpTOCVb5gbeiW7kZm/cRfT256UJwHEuy+y+gTUuKziyXaiOkt5rM/4nzhp8UxVgvok9Tu7dMMpUybiQ==923+ dependencies:924+ "@octokit/types" "^6.38.1"925+926+"@octokit/plugin-request-log@^1.0.4":927+ version "1.0.4"928+ resolved "https://registry.yarnpkg.com/@octokit/plugin-request-log/-/plugin-request-log-1.0.4.tgz#5e50ed7083a613816b1e4a28aeec5fb7f1462e85"929+ integrity sha512-mLUsMkgP7K/cnFEw07kWqXGF5LKrOkD+lhCrKvPHXWDywAwuDUeDwWBpc69XK3pNX0uKiVt8g5z96PJ6z9xCFA==930+931+"@octokit/plugin-rest-endpoint-methods@^5.12.0":932+ version "5.16.0"933+ resolved "https://registry.yarnpkg.com/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-5.16.0.tgz#e0a774d78bb17fb9b6b9ae48d5517940f7f61e90"934+ integrity sha512-mvdwq+LvhR2GRDY82FgSZ52xX6wkOCpjiI3amiKbzKHd9nyKeFdXLsIQ3Go12tWRtvo+HwqoypLHDjRrgMFDQA==935+ dependencies:936+ "@octokit/types" "^6.38.0"937+ deprecation "^2.3.1"938+939+"@octokit/request-error@^2.0.5", "@octokit/request-error@^2.1.0":940+ version "2.1.0"941+ resolved "https://registry.yarnpkg.com/@octokit/request-error/-/request-error-2.1.0.tgz#9e150357831bfc788d13a4fd4b1913d60c74d677"942+ integrity sha512-1VIvgXxs9WHSjicsRwq8PlR2LR2x6DwsJAaFgzdi0JfJoGSO8mYI/cHJQ+9FbN21aa+DrgNLnwObmyeSC8Rmpg==943+ dependencies:944+ "@octokit/types" "^6.0.3"945+ deprecation "^2.0.0"946+ once "^1.4.0"947+948+"@octokit/request@^5.6.0", "@octokit/request@^5.6.3":949+ version "5.6.3"950+ resolved "https://registry.yarnpkg.com/@octokit/request/-/request-5.6.3.tgz#19a022515a5bba965ac06c9d1334514eb50c48b0"951+ integrity sha512-bFJl0I1KVc9jYTe9tdGGpAMPy32dLBXXo1dS/YwSCTL/2nd9XeHsY616RE3HPXDVk+a+dBuzyz5YdlXwcDTr2A==952+ dependencies:953+ "@octokit/endpoint" "^6.0.1"954+ "@octokit/request-error" "^2.1.0"955+ "@octokit/types" "^6.16.1"956+ is-plain-object "^5.0.0"957+ node-fetch "^2.6.7"958+ universal-user-agent "^6.0.0"959+960+"@octokit/rest@^18.0.0":961+ version "18.12.0"962+ resolved "https://registry.yarnpkg.com/@octokit/rest/-/rest-18.12.0.tgz#f06bc4952fc87130308d810ca9d00e79f6988881"963+ integrity sha512-gDPiOHlyGavxr72y0guQEhLsemgVjwRePayJ+FcKc2SJqKUbxbkvf5kAZEWA/MKvsfYlQAMVzNJE3ezQcxMJ2Q==964+ dependencies:965+ "@octokit/core" "^3.5.1"966+ "@octokit/plugin-paginate-rest" "^2.16.8"967+ "@octokit/plugin-request-log" "^1.0.4"968+ "@octokit/plugin-rest-endpoint-methods" "^5.12.0"969+970+"@octokit/types@^6.0.3", "@octokit/types@^6.16.1", "@octokit/types@^6.38.0", "@octokit/types@^6.38.1":971+ version "6.38.1"972+ resolved "https://registry.yarnpkg.com/@octokit/types/-/types-6.38.1.tgz#03d70745564954dfdae32df23d5f1578f958474f"973+ integrity sha512-kWMohLCIvnwApRmxRFDOqve7puiNNdtVfgwdDOm6QyJNorWOgKv2/AodCcGqx63o28kF7Dr4/nJCatrwwqhULg==974+ dependencies:975+ "@octokit/openapi-types" "^12.5.0"976+977 "@sinclair/typebox@^0.23.3":978 version "0.23.5"979 resolved "https://registry.yarnpkg.com/@sinclair/typebox/-/typebox-0.23.5.tgz#93f7b9f4e3285a7a9ade7557d9a8d36809cbc47d"980 integrity sha512-AFBVi/iT4g20DHoujvMH1aEDn8fGJh4xsRGCP6d8RpLPMqsNPvW01Jcn0QysXTsg++/xj25NmJsGyH9xug/wKg==74 unmodified lines1055 integrity sha512-kVzjari1s2YVi77D3w1yuvohV2idweYXMCDzqBiVNN63TcDWrIlTVOYpqVrvbbyOE/IyzBoTKF0fdnLPEORFxA==1056 dependencies:1057 "@babel/types" "^7.3.0"1058 1059+"@types/comment-json@^1.1.1":1060+ version "1.1.1"1061+ resolved "https://registry.yarnpkg.com/@types/comment-json/-/comment-json-1.1.1.tgz#b4ae889912a93e64619f97989aecaff8ce889dca"1062+ integrity sha512-U70oEqvnkeSSp8BIJwJclERtT13rd9ejK7XkIzMCQQePZe3VW1b7iQggXyW4ZvfGtGeXD0pZw24q5iWNe++HqQ==1063+1064 "@types/crypto-js@^4.1.1":1065 version "4.1.1"1066 resolved "https://registry.yarnpkg.com/@types/crypto-js/-/crypto-js-4.1.1.tgz#602859584cecc91894eb23a4892f38cfa927890d"1067 integrity sha512-BG7fQKZ689HIoc5h+6D2Dgq1fABRa0RbBWKBd9SP/MVRVXROflpm5fhwyATX5duFmbStzyzyycPB8qUYKDH3NA==367 unmodified lines1435 version "1.0.2"1436 resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee"1437 integrity sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==1438 1439+before-after-hook@^2.2.0:1440+ version "2.2.2"1441+ resolved "https://registry.yarnpkg.com/before-after-hook/-/before-after-hook-2.2.2.tgz#a6e8ca41028d90ee2c24222f201c90956091613e"1442+ integrity sha512-3pZEU3NT5BFUo/AD5ERPWOgQOCZITni6iavr5AUw5AUwQjMlI0kzu5btnyD39AF0gUEsDPwJT+oY1ORBJijPjQ==1443+1444 brace-expansion@^1.1.7:1445 version "1.1.11"1446 resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.11.tgz#3c7fcbf529d87226f3d2f52b966ff5271eb441dd"1447 integrity sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==159 unmodified lines1607 integrity sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==1608 dependencies:1609 delayed-stream "~1.0.0"1610 1611+commander@^4.1.1:1612+ version "4.1.1"1613+ resolved "https://registry.yarnpkg.com/commander/-/commander-4.1.1.tgz#9fd602bd936294e9e9ef46a3f4d6964044b18068"1614+ integrity sha512-NOKm8xhkzAjzFx8B2v5OAHT+u5pRQc2UCa2Vq9jYL/31o2wi9mxBA7LIFs3sV5VSC49z6pEhfbMULvShKj26WA==1615+1616+comment-json@^3.0.2:1617+ version "3.0.3"1618+ resolved "https://registry.yarnpkg.com/comment-json/-/comment-json-3.0.3.tgz#0cadacd6278602b57b8c51b1814dc5d311d228c4"1619+ integrity sha512-P7XwYkC3qjIK45EAa9c5Y3lR7SMXhJqwFdWg3niAIAcbk3zlpKDdajV8Hyz/Y3sGNn3l+YNMl8A2N/OubSArHg==1620+ dependencies:1621+ core-util-is "^1.0.2"1622+ esprima "^4.0.1"1623+ has-own-prop "^2.0.0"1624+ repeat-string "^1.6.1"1625+1626 concat-map@0.0.1:1627 version "0.0.1"1628 resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b"1629 integrity sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=9 unmodified lines1639 version "0.4.1"1640 resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.4.1.tgz#afd713fe26ebd21ba95ceb61f9a8116e50a537d1"1641 integrity sha512-ZwrFkGJxUR3EIoXtO+yVE69Eb7KlixbaeAWfBQB9vVsNn/o+Yw69gBWSSDK825hQNdN+wF8zELf3dFNl/kxkUA==1642 1643+core-util-is@^1.0.2:1644+ version "1.0.3"1645+ resolved "https://registry.yarnpkg.com/core-util-is/-/core-util-is-1.0.3.tgz#a6042d3634c2b27e9328f837b965fac83808db85"1646+ integrity sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==1647+1648 cron-schedule@^3.0.4:1649 version "3.0.4"1650 resolved "https://registry.yarnpkg.com/cron-schedule/-/cron-schedule-3.0.4.tgz#9d3c3b6ed9069a77856b287f70ab47da271c14e3"1651 integrity sha512-wEspID2dNPfWyh7t2ZvE4Izunzk20QacZg8oZcqfTrN1j5kImj0CEYT3ZGZo+KqGQUgRc9tKlEJmY4uFVt4ccA==97 unmodified lines1749 version "1.0.0"1750 resolved "https://registry.yarnpkg.com/delayed-stream/-/delayed-stream-1.0.0.tgz#df3ae199acadfb7d440aaae0b29e2272b24ec619"1751 integrity sha1-3zrhmayt+31ECqrgsp4icrJOxhk=1752 1753+denoify@^0.11.1:1754+ version "0.11.1"1755+ resolved "https://registry.yarnpkg.com/denoify/-/denoify-0.11.1.tgz#b3623719afdb38d8e678408f8a26bffb76d400a2"1756+ integrity sha512-HwRxpKpx4shhIruTXuZuPPCKD+aB1DT2dMDWqgTDpbZH9IV5SU95zVW/zVkX9m8VGozDe/N9DHIIrc/AYXgz8w==1757+ dependencies:1758+ "@octokit/rest" "^18.0.0"1759+ "@types/comment-json" "^1.1.1"1760+ commander "^4.1.1"1761+ comment-json "^3.0.2"1762+ evt beta1763+ get-github-default-branch-name "^0.0.4"1764+ gitignore-parser "0.0.2"1765+ glob "^7.1.6"1766+ node-fetch "^2.6.0"1767+ path-depth "^1.0.0"1768+ scripting-tools "^0.19.13"1769+ tsafe "^0.8.0"1770+ url-join "^4.0.1"1771+1772+deprecation@^2.0.0, deprecation@^2.3.1:1773+ version "2.3.1"1774+ resolved "https://registry.yarnpkg.com/deprecation/-/deprecation-2.3.1.tgz#6368cbdb40abf3373b525ac87e4a260c3a700919"1775+ integrity sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ==1776+1777 detect-newline@^3.0.0:1778 version "3.1.0"1779 resolved "https://registry.yarnpkg.com/detect-newline/-/detect-newline-3.1.0.tgz#576f5dfc63ae1a192ff192d8ad3af6308991b651"1780 integrity sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA==350 unmodified lines2131 version "2.0.3"2132 resolved "https://registry.yarnpkg.com/esutils/-/esutils-2.0.3.tgz#74d2eb4de0b8da1293711910d50775b9b710ef64"2133 integrity sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==2134 2135+evt@beta:2136+ version "2.0.0-beta.44"2137+ resolved "https://registry.yarnpkg.com/evt/-/evt-2.0.0-beta.44.tgz#7b936e65b3a8c2536e21f1c2af9e85fb95cc32ec"2138+ integrity sha512-2XKKP3UhwLY1jOe8Ta0iL44ZZCy8iG1fGRHeyuU8W/aRcpcKy0PFi/FkVhaaI3tkWjqqfNJQ0wRgDovNP6N3KQ==2139+ dependencies:2140+ minimal-polyfills "^2.2.1"2141+ run-exclusive "^2.2.14"2142+ tsafe "^0.4.1"2143+2144 execa@^5.0.0:2145 version "5.1.1"2146 resolved "https://registry.yarnpkg.com/execa/-/execa-5.1.1.tgz#f80ad9cbf4298f7bd1d4c9555c21e93741c411dd"2147 integrity sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==152 unmodified lines2300 version "2.0.5"2301 resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-2.0.5.tgz#4f94412a82db32f36e3b0b9741f8a97feb031f7e"2302 integrity sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==2303 2304+get-github-default-branch-name@^0.0.4:2305+ version "0.0.4"2306+ resolved "https://registry.yarnpkg.com/get-github-default-branch-name/-/get-github-default-branch-name-0.0.4.tgz#9c0c6606ba606edb136d2fd26e4d515b69f2de90"2307+ integrity sha512-ltOGC9Jk0k8boe48Gk7SkJErwxt7MhwXtbNrBUyNCZcwcXSmGRdkKb2u0YO250PGvPsUtdqRjg7lVuIk1VtpCg==2308+ dependencies:2309+ "@octokit/rest" "^18.0.0"2310+ scripting-tools "^0.19.12"2311+2312 get-intrinsic@^1.0.2, get-intrinsic@^1.1.0, get-intrinsic@^1.1.1:2313 version "1.1.1"2314 resolved "https://registry.yarnpkg.com/get-intrinsic/-/get-intrinsic-1.1.1.tgz#15f59f376f855c446963948f0d24cd3637b4abc6"2315 integrity sha512-kWZrnVM42QCiEA2Ig1bG8zjoIMOgxWwYCEeNdwY6Tv/cOSeGpcoX4pXHfKUxNKVoArnrEr2e9srnAxxGIraS9Q==19 unmodified lines2335 dependencies:2336 call-bind "^1.0.2"2337 get-intrinsic "^1.1.1"2338 2339+gitignore-parser@0.0.2:2340+ version "0.0.2"2341+ resolved "https://registry.yarnpkg.com/gitignore-parser/-/gitignore-parser-0.0.2.tgz#f61259b985dd91414b9a7168faef9171c2eec5df"2342+ integrity sha512-X6mpqUv59uWLGD4n3hZ8Cu8KbF2PMWPSFYmxZjdkpm3yOU7hSUYnzTkZI1mcWqchphvqyuz3/BhgBR4E/JtkCg==2343+2344 glob-parent@^5.1.2:2345 version "5.1.2"2346 resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-5.1.2.tgz#869832c58034fe68a4093c17dc15e8340d8401c4"2347 integrity sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==18 unmodified lines2366 minimatch "^3.0.4"2367 once "^1.3.0"2368 path-is-absolute "^1.0.0"2369 2370+glob@^7.1.6:2371+ version "7.2.3"2372+ resolved "https://registry.yarnpkg.com/glob/-/glob-7.2.3.tgz#b8df0fb802bbfa8e89bd1d938b4e16578ed44f2b"2373+ integrity sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==2374+ dependencies:2375+ fs.realpath "^1.0.0"2376+ inflight "^1.0.4"2377+ inherits "2"2378+ minimatch "^3.1.1"2379+ once "^1.3.0"2380+ path-is-absolute "^1.0.0"2381+2382 globals@^11.1.0:2383 version "11.12.0"2384 resolved "https://registry.yarnpkg.com/globals/-/globals-11.12.0.tgz#ab8795338868a0babd8525758018c2a7eb95c42e"2385 integrity sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==46 unmodified lines2432 version "4.0.0"2433 resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-4.0.0.tgz#944771fd9c81c81265c4d6941860da06bb59479b"2434 integrity sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==2435 2436+has-own-prop@^2.0.0:2437+ version "2.0.0"2438+ resolved "https://registry.yarnpkg.com/has-own-prop/-/has-own-prop-2.0.0.tgz#f0f95d58f65804f5d218db32563bb85b8e0417af"2439+ integrity sha512-Pq0h+hvsVm6dDEa8x82GnLSYHOzNDt7f0ddFa3FqcQlgzEiptPqL+XrOJNavjOzSYiYWIrgeVYYgGlLmnxwilQ==2440+2441 has-symbols@^1.0.1, has-symbols@^1.0.2:2442 version "1.0.2"2443 resolved "https://registry.yarnpkg.com/has-symbols/-/has-symbols-1.0.2.tgz#165d3070c00309752a1236a479331e3ac56f1423"2444 integrity sha512-chXa79rL/UC2KlX17jo3vRGz0azaWEx5tGqZg5pO3NUyEJVB17dMruQlzCCOfUvElghKcm5194+BCRvi2Rv/Gw==188 unmodified lines2633 version "7.0.0"2634 resolved "https://registry.yarnpkg.com/is-number/-/is-number-7.0.0.tgz#7535345b896734d5f80c4d06c50955527a14f12b"2635 integrity sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==2636 2637+is-plain-object@^5.0.0:2638+ version "5.0.0"2639+ resolved "https://registry.yarnpkg.com/is-plain-object/-/is-plain-object-5.0.0.tgz#4427f50ab3429e9025ea7d52e9043a9ef4159344"2640+ integrity sha512-VRSzKkbMm5jMDoKLbltAkFQ5Qr7VDiTFGXxYFXXowVj387GeGNOCsOH6Msy00SGZ3Fp84b1Naa1psqgcCIEP5Q==2641+2642 is-potential-custom-element-name@^1.0.1:2643 version "1.0.1"2644 resolved "https://registry.yarnpkg.com/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz#171ed6f19e3ac554394edf78caa05784a45bebb5"2645 integrity sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==805 unmodified lines3451 semiver "^1.1.0"3452 source-map-support "^0.5.20"3453 undici "5.5.1"3454 3455+minimal-polyfills@^2.1.5, minimal-polyfills@^2.2.1:3456+ version "2.2.1"3457+ resolved "https://registry.yarnpkg.com/minimal-polyfills/-/minimal-polyfills-2.2.1.tgz#7249d7ece666d3b4e1ec1c1b8f949eb9d44e2308"3458+ integrity sha512-WLmHQrsZob4rVYf8yHapZPNJZ3sspGa/sN8abuSD59b0FifDEE7HMfLUi24z7mPZqTpBXy4Svp+iGvAmclCmXg==3459+3460 minimatch@^3.0.4:3461 version "3.0.4"3462 resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.0.4.tgz#5166e286457f03306064be5497e8dbb0c3d32083"3463 integrity sha512-yJHVQEhyqPLUTgt9B83PXu6W3rx4MvvHvSUvToogpwoGDOUQ+yDrR0HRot+yOCdCO7u4hX3pWft6kWBBcqh0UA==3464 dependencies:3465 brace-expansion "^1.1.7"3466 3263-minimatch@^3.1.2:3467+minimatch@^3.1.1, minimatch@^3.1.2:3468 version "3.1.2"3469 resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.1.2.tgz#19cd194bfd3e428f049a70817c038d89ab4be35b"3470 integrity sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==3471 dependencies:33 unmodified lines3505 version "1.4.0"3506 resolved "https://registry.yarnpkg.com/natural-compare/-/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7"3507 integrity sha1-Sr6/7tdUHywnrPspvbvRXI1bpPc=3508 3509+node-fetch@^2.6.0, node-fetch@^2.6.7:3510+ version "2.6.7"3511+ resolved "https://registry.yarnpkg.com/node-fetch/-/node-fetch-2.6.7.tgz#24de9fba827e3b4ae44dc8b20256a379160052ad"3512+ integrity sha512-ZjMPFEfVx5j+y2yF35Kzx5sF7kDzxuDj6ziH4FFbOp87zKDZNx8yExJIb05OGF4Nlt9IHFIMBkRl41VdvcNdbQ==3513+ dependencies:3514+ whatwg-url "^5.0.0"3515+3516 node-forge@^1.2.0:3517 version "1.2.1"3518 resolved "https://registry.yarnpkg.com/node-forge/-/node-forge-1.2.1.tgz#82794919071ef2eb5c509293325cec8afd0fd53c"3519 integrity sha512-Fcvtbb+zBcZXbTTVwqGA5W+MKBj56UjVRevvchv5XrcyXbmNdesfZL37nlcWOfpgHhgmxApw3tQbTr4CqNmX4w==53 unmodified lines3573 call-bind "^1.0.2"3574 define-properties "^1.1.3"3575 es-abstract "^1.19.1"3576 3366-once@^1.3.0:3577+once@^1.3.0, once@^1.4.0:3578 version "1.4.0"3579 resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1"3580 integrity sha1-WDsap3WWHUsROsF9nFC6753Xa9E=3581 dependencies:89 unmodified lines3671 version "6.0.1"3672 resolved "https://registry.yarnpkg.com/parse5/-/parse5-6.0.1.tgz#e1a1c085c569b3dc08321184f19a39cc27f7c30b"3673 integrity sha512-Ofn/CTFzRGTTxwpNEs9PP93gXShHcTq255nzRYSKe8AkVpZY7e1fpmTfOyoIvjP5HG7Z2ZM7VS9PPhQGW2pOpw==3674 3675+path-depth@^1.0.0:3676+ version "1.0.0"3677+ resolved "https://registry.yarnpkg.com/path-depth/-/path-depth-1.0.0.tgz#88cf881097e171b8b54d450d2167ea76063d3086"3678+ integrity sha512-dEiwdXAQyLvOi6ktLqhFhjVelJiVsdp2xBX3BaUtYCCkMRZTwUiq7cha+A0myvAVXRHbXfjhfTf4mNoAWzm2iA==3679+3680 path-exists@^3.0.0:3681 version "3.0.0"3682 resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-3.0.0.tgz#ce0ebeaa5f78cb18925ea7d810d7b59b010fd515"3683 integrity sha1-zg6+ql94yxiSXqfYENe1mwEP1RU=130 unmodified lines3814 version "3.2.0"3815 resolved "https://registry.yarnpkg.com/regexpp/-/regexpp-3.2.0.tgz#0425a2768d8f23bad70ca4b90461fa2f1213e1b2"3816 integrity sha512-pq2bWo9mVD43nbts2wGv17XLiNLya+GklZ8kaDLV2Z08gDCsGpnKn9BFMepvWuHCbyVvY7J5o5+BVvoQbmlJLg==3817 3818+repeat-string@^1.6.1:3819+ version "1.6.1"3820+ resolved "https://registry.yarnpkg.com/repeat-string/-/repeat-string-1.6.1.tgz#8dcae470e1c88abc2d600fff4a776286da75e637"3821+ integrity sha512-PV0dzCYDNfRi1jCDbJzpW7jNNDRuCOG/jI5ctQcGKt/clZD+YcPS3yIlWuTJMmESC8aevCFmWJy5wjAFgNqN6w==3822+3823 require-directory@^2.1.1:3824 version "2.1.1"3825 resolved "https://registry.yarnpkg.com/require-directory/-/require-directory-2.1.1.tgz#8c64ad5fd30dab1c976e2344ffe7f792a6a6df42"3826 integrity sha1-jGStX9MNqxyXbiNE/+f3kqam30I=40 unmodified lines3867 integrity sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==3868 dependencies:3869 glob "^7.1.3"3870 3871+run-exclusive@^2.2.14:3872+ version "2.2.14"3873+ resolved "https://registry.yarnpkg.com/run-exclusive/-/run-exclusive-2.2.14.tgz#4f41dc7843e091f10991f8708fce87b09022a0ce"3874+ integrity sha512-NHaQfB3zPJFx7p4M06AcmoK8xz/h8YDMCdy3jxfyoC9VqIbl1U+DiVjUuAYZBRMwvj5qkQnOUGfsmyUC4k46dg==3875+ dependencies:3876+ minimal-polyfills "^2.1.5"3877+3878 run-parallel@^1.1.9:3879 version "1.2.0"3880 resolved "https://registry.yarnpkg.com/run-parallel/-/run-parallel-1.2.0.tgz#66d1368da7bdf921eb9d95bd1a9229e7f21a43ee"3881 integrity sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==16 unmodified lines3898 integrity sha512-5LBh1Tls8c9xgGjw3QrMwETmTMVk0oFgvrFSvWx62llR2hcEInrKNZ2GZCCuuy2lvWrdl5jhbpeqc5hRYKFOcw==3899 dependencies:3900 xmlchars "^2.2.0"3901 3902+scripting-tools@^0.19.12, scripting-tools@^0.19.13:3903+ version "0.19.13"3904+ resolved "https://registry.yarnpkg.com/scripting-tools/-/scripting-tools-0.19.13.tgz#836df7d9c2ec99aea91984d1d5b2bd110670afec"3905+ integrity sha512-d09H8vzSVa8p4XUTJqHZDbjKDyl5TG3SyPfNPUUkfyOwjwykStmfK8AXyWq7VRWjcgzTpkTiJ9uMk1NytMQY7w==3906+3907 selfsigned@^2.0.0:3908 version "2.0.0"3909 resolved "https://registry.yarnpkg.com/selfsigned/-/selfsigned-2.0.0.tgz#e927cd5377cbb0a1075302cff8df1042cc2bce5b"3910 integrity sha512-cUdFiCbKoa1mZ6osuJs2uDHrs0k0oprsKveFiiaBKCNq3SYyb5gs2HxhQyDNLCmL51ZZThqi4YNDpCK6GOP1iQ==278 unmodified lines4189 integrity sha512-15Ih7phfcdP5YxqiB+iDtLoaTz4Nd35+IiAv0kQ5FNKHzXgdWqPoTIqEDDJmXceQt4JZk6lVPT8lnDlPpGDppw==4190 dependencies:4191 punycode "^2.1.1"4192 4193+tr46@~0.0.3:4194+ version "0.0.3"4195+ resolved "https://registry.yarnpkg.com/tr46/-/tr46-0.0.3.tgz#8184fd347dac9cdc185992f3a6622e14b9d9ab6a"4196+ integrity sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==4197+4198 ts-jest@^27.1.4:4199 version "27.1.4"4200 resolved "https://registry.yarnpkg.com/ts-jest/-/ts-jest-27.1.4.tgz#84d42cf0f4e7157a52e7c64b1492c46330943e00"4201 integrity sha512-qjkZlVPWVctAezwsOD1OPzbZ+k7zA5z3oxII4dGdZo5ggX/PL7kvwTM0pXTr10fAtbiVpJaL3bWd502zAhpgSQ==6 unmodified lines4208 make-error "1.x"4209 semver "7.x"4210 yargs-parser "20.x"4211 4212+tsafe@^0.4.1:4213+ version "0.4.1"4214+ resolved "https://registry.yarnpkg.com/tsafe/-/tsafe-0.4.1.tgz#00af1be2db82abb4be531209b90232d7954e1a03"4215+ integrity sha512-+OZ0gdgmwcru+MOSheCx+ymAvQz+1/ui+KFJRuaq0t2m8RNrlf7eSzEieptoPQXPY67Mdkqgkdjknn8azoD5sw==4216+4217+tsafe@^0.8.0:4218+ version "0.8.1"4219+ resolved "https://registry.yarnpkg.com/tsafe/-/tsafe-0.8.1.tgz#9af7e1540bc04313a82d60c98056a5017c8b086b"4220+ integrity sha512-EfPjxQHzndQAV/uh0SMGP26Wg3dCuaw8dRv2VPEuGHen5qzg2oqsMvZw2wkQFkiMisZq2fm95m5lheimW2Fpvg==4221+4222 tsconfig-paths@^3.14.1:4223 version "3.14.1"4224 resolved "https://registry.yarnpkg.com/tsconfig-paths/-/tsconfig-paths-3.14.1.tgz#ba0734599e8ea36c862798e920bcf163277b137a"4225 integrity sha512-fxDhWnFSLt3VuTwtvJt5fpwxBHg5AdKWMsgcPOOIilyjymcYVZoCQF8fvFRezCNfblEXmi+PcM1eYHeOAgXCOQ==70 unmodified lines4296 version "5.5.1"4297 resolved "https://registry.yarnpkg.com/undici/-/undici-5.5.1.tgz#baaf25844a99eaa0b22e1ef8d205bffe587c8f43"4298 integrity sha512-MEvryPLf18HvlCbLSzCW0U00IMftKGI5udnjrQbC5D4P0Hodwffhv+iGfWuJwg16Y/TK11ZFK8i+BPVW2z/eAw==4299 4300+universal-user-agent@^6.0.0:4301+ version "6.0.0"4302+ resolved "https://registry.yarnpkg.com/universal-user-agent/-/universal-user-agent-6.0.0.tgz#3381f8503b251c0d9cd21bc1de939ec9df5480ee"4303+ integrity sha512-isyNax3wXoKaulPDZWHQqbmIx1k2tb9fb3GGDBRxCscfYV2Ch7WxPArBsFEG8s/safwXTT7H4QGhaIkTp9447w==4304+4305 universalify@^0.1.2:4306 version "0.1.2"4307 resolved "https://registry.yarnpkg.com/universalify/-/universalify-0.1.2.tgz#b646f69be3942dabcecc9d6639c80dc105efaa66"4308 integrity sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==4 unmodified lines4313 integrity sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==4314 dependencies:4315 punycode "^2.1.0"4316 4317+url-join@^4.0.1:4318+ version "4.0.1"4319+ resolved "https://registry.yarnpkg.com/url-join/-/url-join-4.0.1.tgz#b642e21a2646808ffa178c4c5fda39844e12cde7"4320+ integrity sha512-jk1+QP6ZJqyOiuEI9AEWQfju/nB2Pw466kbA0LEZljHwKeMgd9WrAEgEGxjPDD2+TNbbb37rTyhEfrCXfuKXnA==4321+4322 urlpattern-polyfill@^4.0.3:4323 version "4.0.3"4324 resolved "https://registry.yarnpkg.com/urlpattern-polyfill/-/urlpattern-polyfill-4.0.3.tgz#c1fa7a73eb4e6c6a1ffb41b24cf31974f7392d3b"4325 integrity sha512-DOE84vZT2fEcl9gqCUTcnAw5ZY5Id55ikUcziSUntuEFL3pRvavg5kwDmTEUJkeCHInTlV/HexFomgYnzO5kdQ==32 unmodified lines4358 integrity sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ==4359 dependencies:4360 makeerror "1.0.12"4361 4362+webidl-conversions@^3.0.0:4363+ version "3.0.1"4364+ resolved "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-3.0.1.tgz#24534275e2a7bc6be7bc86611cc16ae0a5654871"4365+ integrity sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==4366+4367 webidl-conversions@^5.0.0:4368 version "5.0.0"4369 resolved "https://registry.yarnpkg.com/webidl-conversions/-/webidl-conversions-5.0.0.tgz#ae59c8a00b121543a2acc65c0434f57b0fc11aff"4370 integrity sha512-VlZwKPCkYKxQgeSbH5EyngOmRp7Ww7I9rQLERETtf5ofd9pGeswWiOtogpEO850jziPRarreGxn5QIiTqpb2wA==14 unmodified lines4385 version "2.3.0"4386 resolved "https://registry.yarnpkg.com/whatwg-mimetype/-/whatwg-mimetype-2.3.0.tgz#3d4b1e0312d2079879f826aff18dbeeca5960fbf"4387 integrity sha512-M4yMwr6mAnQz76TbJm914+gPpB/nCwvZbJU28cUD6dR004SAxDLOOSUaB1JDRqLtaOV/vi0IC5lEAGFgrjGv/g==4388 4389+whatwg-url@^5.0.0:4390+ version "5.0.0"4391+ resolved "https://registry.yarnpkg.com/whatwg-url/-/whatwg-url-5.0.0.tgz#966454e8765462e37644d3626f6742ce8b70965d"4392+ integrity sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==4393+ dependencies:4394+ tr46 "~0.0.3"4395+ webidl-conversions "^3.0.0"4396+4397 whatwg-url@^8.0.0, whatwg-url@^8.5.0:4398 version "8.7.0"4399 resolved "https://registry.yarnpkg.com/whatwg-url/-/whatwg-url-8.7.0.tgz#656a78e510ff8f3937bc0bcbe9f5c0ac35941b77"4400 integrity sha512-gAojqb/m9Q8a5IV96E3fHJM70AzCkgt4uXYX2O7EmuyOnLrViCQlsEBmF9UQIu3/aeAIp2U17rtbpZWNntQqdg==109 unmodified lines