Merge pull request #5154 from honojs/next
Before adoption: this commit came in with the history the project adopted, so no landing records it.
next
authored by Yusuke Wada · committed by Yusuke Wada · parents 734755a, 8f07028 · Browse files · 41 files·+2061 added−348 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
41 files+2061 added−348 removed
- tests:+1369 added−44 removed
- other:+692 added−304 removed
Provenance
- Commit
b0c2d90- Tree
b46b4bf- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
Yusuke Wada <yusuke@kamawada.com>- Parent 1
734755a- Parent 2
8f07028
41 files changed+2061 added−348 removed
modified:benchmarks/fetch/bench.mts+41 added-12 removed
9 unmodified lines1011121314151617171818192020212223242511 unmodified lines373839404142434445464748495051525354555657585051596061626364656667685 unmodified lines7475767778798081828384858687888990919293949574969798767778798081991001011021031041051061071081091101111121131144 unmodified lines9 unmodified lines// Env:// HONO_SRC ... path to the hono `src` directory to benchmark (default: ../../src)// HONO_LABEL ... label used in the output (default: hono)// HONO_JSON=1 ... suppress mitata output and print a single JSON line instead// HONO_CASE ... run only cases whose name starts with this prefix (e.g. "ping")//// Runs on both Bun and Node.import './ts-resolve.mjs'import { run, bench } from 'mitata'import { pathToFileURL } from 'node:url'import { run, bench, measure } from 'mitata'import { fileURLToPath, pathToFileURL } from 'node:url'
const src = process.env.HONO_SRC ?? new URL('../../src', import.meta.url).pathnameconst src = process.env.HONO_SRC ?? fileURLToPath(new URL('../../src', import.meta.url))const label = process.env.HONO_LABEL ?? 'hono'const asJson = process.env.HONO_JSON === '1'
// eslint-disable-next-line @typescript-eslint/no-explicit-any11 unmodified lines const name = c.req.query('name') c.header('x-powered-by', 'benchmark') return c.text(`${id} ${name}`) }) .get('/user', (c: any) => c.json({ id: 123, name: 'Alice', roles: ['admin', 'editor'] })) .use('/mw/*', async (_c: any, next: any) => { await next() }) .get('/mw/hello', (c: any) => c.text('mw')) return app}
const app = await makeApp(src)
const ping = new Request('http://localhost/')const query = new Request('http://localhost/id/1?name=bun')const user = new Request('http://localhost/user')const mw = new Request('http://localhost/mw/hello')
let sink: unknown
const caseFilter = process.env.HONO_CASE const cases: [string, (app: any) => Promise<unknown>][] = [
const allCases: [string, (app: any) => Promise<unknown>][] = [ ['ping GET /', (app) => app.fetch(ping)], ['query GET /id/1?name=bun', (app) => app.fetch(query)], ['json GET /user', (app) => app.fetch(user)], ['middleware GET /mw/hello', (app) => app.fetch(mw)], [ 'body POST /json', (app) => app.fetch(5 unmodified lines ), ],]
const cases = caseFilter ? allCases.filter(([name]) => name.startsWith(caseFilter)) : allCasesif (cases.length === 0) { throw new Error(`no cases match HONO_CASE=${caseFilter}`)}
// Warm up before registering benches: the first fetch builds the router// lazily (>500µs), which makes mitata skip batching for the first bench.for (const [, fn] of allCases) { sink = await fn(app)}
for (const [name, fn] of cases) { bench(name, async () => { sink = await fn(app) })}
if (asJson) { const { benchmarks } = await run({ format: 'quiet' }) // Force batching on: without it, each iteration is timed individually at // timer granularity (~41ns on Apple Silicon), which is too coarse here. const results: Record<string, { avg: number; min: number; p75: number }> = {} for (const b of benchmarks) { const { stats, error } = b.runs[0] if (error || !stats) { throw error ?? new Error(`no stats for ${b.alias}`) } results[b.alias] = { avg: stats.avg, min: stats.min, p75: stats.p75 } for (const [name, fn] of cases) { const stats = await measure( async () => { sink = await fn(app) }, { warmup_threshold: Number.MAX_SAFE_INTEGER, batch_threshold: Number.MAX_SAFE_INTEGER, } ) // p50 rather than avg: insensitive to the slow JIT tier-up windows results[name] = { avg: stats.p50, min: stats.min, p75: stats.p75 } } console.log(JSON.stringify({ label, cases: results })) console.error(typeof sink)} else {4 unmodified linesmodified:src/client/types.test.ts+1 added
115 unmodified lines116 expectTypeOf(client['all-route']).toHaveProperty('$put')117 expectTypeOf(client['all-route']).toHaveProperty('$delete')118 expectTypeOf(client['all-route']).toHaveProperty('$options')119 expectTypeOf(client['all-route']).toHaveProperty('$patch')120+ expectTypeOf(client['all-route']).toHaveProperty('$query')121 })122 123 it('should have correct return type for expanded methods', async () => {124 // The response type should match the original handler's return type22 unmodified linesmodified:src/client/types.ts+1 added-1 removed
10 unmodified lines11 type MethodNameAll = `$${typeof METHOD_NAME_ALL_LOWERCASE}`12 13 /**14 * Type representing all standard HTTP methods prefixed with '$'15- * e.g., '$get' | '$post' | '$put' | '$delete' | '$options' | '$patch'15+ * e.g., '$get' | '$post' | '$put' | '$delete' | '$options' | '$patch' | '$query'16 */17 type StandardMethods = `$${(typeof METHODS)[number]}`18 19 /**374 unmodified linesmodified:src/jsx/dom/intrinsic-element/components.ts+3 added-3 removed
20 unmodified lines21 }22 23 // this function is exported for testing and should not be used by the user24 export const composeRef = <T>(25- ref: RefObject<T> | Function | undefined,25+ ref: RefObject<T | null> | Function | undefined,26 cb: (e: T) => void | (() => void)27 ): ((e: T) => () => void) => {28 return useMemo(29 () => (e: T) => {289 unmodified lines319 export const form: FC<320 PropsWithChildren<{321 action?: Function | string322 method?: 'get' | 'post'323- ref?: RefObject<HTMLFormElement> | ((e: HTMLFormElement | null) => void | (() => void))323+ ref?: RefObject<HTMLFormElement | null> | ((e: HTMLFormElement | null) => void | (() => void))324 }>325 > = (props) => {326 const { action, ...restProps } = props327 if (typeof action !== 'function') {63 unmodified lines391 formAction,392 ...props393 }: {394 formAction?: Function | string395- ref?: RefObject<HTMLInputElement> | ((e: HTMLInputElement) => void | (() => void))395+ ref?: RefObject<HTMLInputElement | null> | ((e: HTMLInputElement) => void | (() => void))396 }397 ) => {398 if (typeof formAction === 'function') {399 const onClick = useCallback<(ev: MouseEvent) => void>((ev: MouseEvent) => {39 unmodified linesmodified:src/jsx/dom/index.test.tsx+53 added-4 removed
372 unmodified lines373 expect(root.innerHTML).toBe('<div>2</div><div>1</div><button>+</button>')374 expect(Child).toBeCalledTimes(3)375 })376 377+ it('returning an array', async () => {378+ const App = () => {379+ const [count, setCount] = useState(0)380+ return [<div>{count}</div>, <button onClick={() => setCount(count + 1)}>+</button>]381+ }382+ render(<App />, root)383+ expect(root.innerHTML).toBe('<div>0</div><button>+</button>')384+ root.querySelector('button')?.click()385+ await Promise.resolve()386+ expect(root.innerHTML).toBe('<div>1</div><button>+</button>')387+ })388+389+ it('typed as FC returning an array', async () => {390+ const App: FC = () => {391+ const [count, setCount] = useState(0)392+ return [<div>{count}</div>, <button onClick={() => setCount(count + 1)}>+</button>]393+ }394+ render(<App />, root)395+ expect(root.innerHTML).toBe('<div>0</div><button>+</button>')396+ root.querySelector('button')?.click()397+ await Promise.resolve()398+ expect(root.innerHTML).toBe('<div>1</div><button>+</button>')399+ })400+401 it('multiple children', async () => {402 const Child = ({ name }: { name: string }) => {403 const [count, setCount] = useState(0)404 return (1523 unmodified lines1928 })1929 })1930 1931 describe('useRef', async () => {1932+ it('types: non-null initial value returns RefObject<T>', () => {1933+ const ref = useRef(new Map<string, number>())1934+ // .current is non-nullable; this line would not type-check without the overload1935+ ref.current.set('a', 1)1936+ expect(ref.current.get('a')).toBe(1)1937+ })1938+1939+ it('types: null initial value returns RefObject<T | null>', () => {1940+ const ref = useRef<HTMLDivElement>(null)1941+ expect(ref.current).toBeNull()1942+ })1943+1944+ it('types: undefined initial value returns RefObject<T | undefined>', () => {1945+ const ref = useRef<number>(undefined)1946+ expect(ref.current).toBeUndefined()1947+ ref.current = 11948+ expect(ref.current).toBe(1)1949+ })1950+1951 it('simple', async () => {1909- const Input = ({ label, ref }: { label: string; ref: RefObject<HTMLInputElement> }) => {1952+ const Input = ({1953+ label,1954+ ref,1955+ }: {1956+ label: string1957+ ref: RefObject<HTMLInputElement | null>1958+ }) => {1959 return (1960 <div>1961 <label>{label}</label>1962 <input ref={ref} />100 unmodified lines2063 expect(root.innerHTML).toBe('<div>2</div>')2064 })2065 2066 it('cleanup', async () => {2018- const Child = ({ parent }: { parent: RefObject<HTMLElement> }) => {2067+ const Child = ({ parent }: { parent: RefObject<HTMLElement | null> }) => {2068 useEffect(() => {2069 return () => {2070 parent.current?.setAttribute('data-cleanup', 'true')2071 }91 unmodified lines2163 expect(root.innerHTML).toBe('<div>2</div>')2164 })2165 2166 it('cleanup', async () => {2118- const Child = ({ parent }: { parent: RefObject<HTMLElement> }) => {2167+ const Child = ({ parent }: { parent: RefObject<HTMLElement | null> }) => {2168 useLayoutEffect(() => {2169 return () => {2170 parent.current?.setAttribute('data-cleanup', 'true')2171 }105 unmodified lines2277 expect(root.innerHTML).toBe('<div>useInsertionEffect,useLayoutEffect</div>')2278 })2279 2280 it('cleanup', async () => {2232- const Child = ({ parent }: { parent: RefObject<HTMLElement> }) => {2281+ const Child = ({ parent }: { parent: RefObject<HTMLElement | null> }) => {2282 useInsertionEffect(() => {2283 return () => {2284 parent.current?.setAttribute('data-cleanup', 'true')2285 }663 unmodified linesmodified:src/jsx/dom/render.ts+1 added-1 removed
282 unmodified lines283 ...node.props,284 }285 : node.props286 try {287- return [func.call(null, props)]287+ return [func.call(null, props) as Child]288 } finally {289 buildDataStack.pop()290 }291 }534 unmodified linesmodified:src/jsx/hooks/index.ts+11 added-7 removed
313 unmodified lines314 }315 return callback316 }317 318-export type RefObject<T> = { current: T | null }319-export const useRef = <T>(initialValue: T | null): RefObject<T> => {318+export type RefObject<T> = { current: T }319+320+export function useRef<T>(initialValue: T): RefObject<T>321+export function useRef<T>(initialValue: T | null): RefObject<T | null>322+export function useRef<T>(initialValue: T | undefined): RefObject<T | undefined>323+export function useRef<T>(initialValue?: T | null): RefObject<T | null | undefined> {324 const buildData = buildDataStack.at(-1) as [unknown, NodeObject]325 if (!buildData) {322- return { current: initialValue }326+ return { current: initialValue } as RefObject<T | null | undefined>327 }328 const [, node] = buildData329 330 const refArray = (node[DOM_STASH][1][STASH_REF] ||= [])40 unmodified lines371 372 // Define to avoid errors. This hook currently does nothing.373 export const useDebugValue = (_value: unknown, _formatter?: (value: unknown) => string): void => {}374 371-export const createRef = <T>(): RefObject<T> => {375+export const createRef = <T>(): RefObject<T | null> => {376 return { current: null }377 }378 379 export const forwardRef = <T, P = {}>(376- Component: (props: P, ref?: RefObject<T>) => JSX.Element377-): ((props: P & { ref?: RefObject<T> }) => JSX.Element) => {380+ Component: (props: P, ref?: RefObject<T | null>) => JSX.Element381+): ((props: P & { ref?: RefObject<T | null> }) => JSX.Element) => {382 return (props) => {383 const { ref, ...rest } = props384 return Component(rest as P, ref)385 }386 }387 388 export const useImperativeHandle = <T>(385- ref: RefObject<T>,389+ ref: RefObject<T | null>,390 createHandle: () => T,391 deps: readonly unknown[]392 ): void => {393 useEffect(() => {44 unmodified linesmodified:src/jsx/intrinsic-element/components.test.tsx+18 added
1 /** @jsxImportSource ../ */2 import { useActionState } from '../'3+import { HtmlEscapedCallbackPhase, resolveCallback } from '../../utils/html'4 5 describe('intrinsic element', () => {6 describe('document metadata', () => {7 describe('title element', () => {10 unmodified lines18 expect(template.toString()).toBe(19 '<html><head><title>Hello</title></head><body><h1>World</h1></body></html>'20 )21 })22+23+ it('should hoist a title from an async component array', async () => {24+ const Metadata = async () => [<title>Hello</title>]25+ const template = (26+ <html>27+ <head></head>28+ <body>29+ <Metadata />30+ <h1>World</h1>31+ </body>32+ </html>33+ )34+ const rendered = await template.toString()35+ expect(await resolveCallback(rendered, HtmlEscapedCallbackPhase.Stringify, false, {})).toBe(36+ '<html><head><title>Hello</title></head><body><h1>World</h1></body></html>'37+ )38+ })39 })40 41 describe('link element', () => {42 it('should be hoisted link tag', async () => {562 unmodified linesmodified:src/jsx/base.ts+41 added-18 removed
23 unmodified lines24 } from './utils'25 26 // eslint-disable-next-line @typescript-eslint/no-explicit-any27 export type Props = Record<string, any>28+type FunctionComponentResult =29+ | HtmlEscapedString30+ | Child[]31+ | Promise<HtmlEscapedString | Child[]>32+ | null33 export type FC<P = Props> = {29- (props: P): HtmlEscapedString | Promise<HtmlEscapedString> | null34+ (props: P): FunctionComponentResult35 defaultProps?: Partial<P> | undefined36 displayName?: string | undefined37 }38 export type DOMAttributes = HonoJSX.HTMLAttributes39 40 // eslint-disable-next-line @typescript-eslint/no-namespace41 export namespace JSX {42 export type Element = HtmlEscapedString | Promise<HtmlEscapedString>43+ export type ElementType = string | ((props: never) => FunctionComponentResult)44 export interface ElementChildrenAttribute {45 children: Child46 }47 export interface IntrinsicElements extends IntrinsicElementsDefined {62 unmodified lines110 'reversed',111 'selected',112 ]113 114+type SuspendedContext = <T>(callback: () => T) => T115+116+const resolveFunctionComponentResult = (117+ result: Promise<string | JSXNode | Child[]>,118+ suspendedContext?: SuspendedContext119+): Promise<string> =>120+ result.then((resolved) => {121+ if (!Array.isArray(resolved) && !(resolved instanceof JSXNode)) {122+ return resolved123+ }124+ const children = Array.isArray(resolved) ? resolved : [resolved]125+ const render = () => {126+ const buffer: StringBufferWithCallbacks = [''] as StringBufferWithCallbacks127+ childrenToStringToBuffer(children, buffer)128+ return buffer.length === 1129+ ? raw(buffer[0], buffer.callbacks)130+ : stringBufferToString(buffer, buffer.callbacks)131+ }132+ return suspendedContext ? suspendedContext(render) : runWithRenderContext(render)133+ })134+135 const childrenToStringToBuffer = (children: Child[], buffer: StringBufferWithCallbacks): void => {136 for (let i = 0, len = children.length; i < len; i++) {137 const child = children[i]138 if (typeof child === 'string') {1 unmodified line140 } else if (typeof child === 'boolean' || child === null || child === undefined) {141 continue142 } else if (child instanceof JSXNode) {143 child.toStringToBuffer(buffer)117- } else if (118- typeof child === 'number' ||119- (child as unknown as { isEscaped: boolean }).isEscaped120- ) {144+ } else if (typeof child === 'number') {145 ;(buffer[0] as string) += child146+ } else if ((child as unknown as HtmlEscaped).isEscaped) {147+ ;(buffer[0] as string) += child148+ const callbacks = (child as unknown as HtmlEscapedString).callbacks149+ if (callbacks) {150+ buffer.callbacks ||= []151+ buffer.callbacks.push(...callbacks)152+ }153 } else if (child instanceof Promise) {154 buffer.unshift('', child)155 } else {156 // `child` type is `Child[]`, so stringify recursively16 unmodified lines173 props: Props174 key?: string175 children: Child[]176 isEscaped: true = true as const146- suspendedContext?: <T>(callback: () => T) => T177 constructor(tag: string | Function, props: Props, children: Child[]) {178 if (typeof tag !== 'function' && !isValidTagName(tag)) {179 throw new Error(`Invalid JSX tag name: ${tag}`)180 }21 unmodified lines202 ? resolveCallbackSync(raw(buffer[0], buffer.callbacks)).toString()203 : buffer[0]204 : stringBufferToString(buffer, buffer.callbacks)205 }176- return this.suspendedContext ? this.suspendedContext(render) : runWithRenderContext(render)206+ return runWithRenderContext(render)207 }208 209 toStringToBuffer(buffer: StringBufferWithCallbacks): void {210 const tag = this.tag as string85 unmodified lines296 // boolean or null or undefined297 return298 } else if (res instanceof Promise) {299 if (globalContexts.length === 0) {270- buffer.unshift('', res)300+ buffer.unshift('', resolveFunctionComponentResult(res))301 } else {302 // save the current context state for resuming the suspended subtree273- const suspendedContext = captureRenderContext()274- buffer.unshift(275- '',276- res.then((childRes) => {277- if (childRes instanceof JSXNode) {278- childRes.suspendedContext = suspendedContext279- }280- return childRes281- })282- )303+ buffer.unshift('', resolveFunctionComponentResult(res, captureRenderContext()))304 }305 } else if (res instanceof JSXNode) {306 res.toStringToBuffer(buffer)307+ } else if (Array.isArray(res)) {308+ childrenToStringToBuffer(res, buffer)309 } else if (typeof res === 'number' || (res as HtmlEscaped).isEscaped) {310 buffer[0] += res311 if (res.callbacks) {312 buffer.callbacks ||= []147 unmodified linesmodified:src/jsx/index.test.tsx+95 added-1 removed
1 /** @jsxImportSource ./ */2 /* eslint-disable @typescript-eslint/no-explicit-any */3-import { html } from '../helper/html'3+import { html, raw } from '../helper/html'4 import { Hono } from '../hono'5 import { DOM_MEMO } from './constants'6 import { captureRenderContext } from './context'7 import { Suspense, renderToReadableStream } from './streaming'163 unmodified lines171 )172 expect(template.toString()).toBe('<p><span>a</span><span>b</span></p>')173 })174 175+ it('Component returning an array', () => {176+ const Item = ({ x }: { x: number }) => <span>{x}</span>177+ const Items = () => [0, 1].map((x) => <Item key={x} x={x} />)178+ const template = <Items />179+ expect(template.toString()).toBe('<span>0</span><span>1</span>')180+ })181+182+ it('Component returning a nested array', () => {183+ const Items = () => [['a', 'b'], [<span>c</span>], null]184+ const template = <Items />185+ expect(template.toString()).toBe('ab<span>c</span>')186+ })187+188+ it('Component returning an array preserves escaped string callbacks', () => {189+ const Items = () => [190+ raw('a', [191+ ({ buffer }) => {192+ if (buffer) {193+ buffer[0] += 'b'194+ }195+ },196+ ]),197+ ]198+ expect((<Items />).toString()).toBe('ab')199+ })200+201+ it('Component returning an array escapes strings', async () => {202+ const SyncItems = () => ['<script>alert(1)</script>']203+ const AsyncItems = async () => ['<script>alert(1)</script>']204+ const expected = '<script>alert(1)</script>'205+206+ expect((<SyncItems />).toString()).toBe(expected)207+ expect((await (<AsyncItems />).toString()).toString()).toBe(expected)208+ })209+210+ it('Component returning an array including async components', async () => {211+ const AsyncItem = async ({ x }: { x: number }) => <span>{x}</span>212+ const Items = () => [0, 1].map((x) => <AsyncItem key={x} x={x} />)213+ const template = <Items />214+ expect((await template.toString()).toString()).toBe('<span>0</span><span>1</span>')215+ })216+217+ it('Component typed as FC returning an array', () => {218+ const Item: FC<{ x: number }> = ({ x }) => <span>{x}</span>219+ const Items: FC = () => [0, 1].map((x) => <Item key={x} x={x} />)220+ const template = <Items />221+ expect(template.toString()).toBe('<span>0</span><span>1</span>')222+ })223+224+ it('Async component returning an array', async () => {225+ const AsyncItems = async () => [<span>a</span>, <span>b</span>]226+ const template = <AsyncItems />227+ expect((await template.toString()).toString()).toBe('<span>a</span><span>b</span>')228+ })229+230+ it('Async component returning an array of async components', async () => {231+ const AsyncItem = async ({ x }: { x: number }) => <span>{x}</span>232+ const AsyncItems = async () => [<AsyncItem key={0} x={0} />, <AsyncItem key={1} x={1} />]233+ const template = <AsyncItems />234+ expect((await template.toString()).toString()).toBe('<span>0</span><span>1</span>')235+ })236+237 it('Empty elements are rended without closing tag', () => {238 const template = <input />239 expect(template.toString()).toBe('<input/>')240 })1072 unmodified lines1313 )1314 expect((await template.toString()).toString()).toBe('<span>dark</span>')1315 })1316 1317+ it('returning an array', async () => {1318+ const ArrayConsumer = async () => {1319+ await new Promise((resolve) => setTimeout(resolve, 10))1320+ return [<span>{useContext(ThemeContext)}</span>, <span>x</span>]1321+ }1322+ const template = (1323+ <ThemeContext.Provider value='dark'>1324+ <ArrayConsumer />1325+ </ThemeContext.Provider>1326+ )1327+ expect((await template.toString()).toString()).toBe('<span>dark</span><span>x</span>')1328+ })1329+1330+ it('isolates a shared async result between providers', async () => {1331+ const sharedResult = Promise.resolve(<Consumer />)1332+ const SharedConsumer = () => sharedResult1333+ const [dark, black] = await Promise.all([1334+ (1335+ <ThemeContext.Provider value='dark'>1336+ <SharedConsumer />1337+ </ThemeContext.Provider>1338+ ).toString(),1339+ (1340+ <ThemeContext.Provider value='black'>1341+ <SharedConsumer />1342+ </ThemeContext.Provider>1343+ ).toString(),1344+ ])1345+ expect(dark.toString()).toBe('<span>dark</span>')1346+ expect(black.toString()).toBe('<span>black</span>')1347+ })1348+1349 it('nested', async () => {1350 const template = (1351 <ThemeContext.Provider value='dark'>1352 <ParentAsyncConsumer />334 unmodified linesmodified:src/jsx/streaming.test.tsx+40 added
28 unmodified lines29 afterEach(() => {30 suspenseCounter++31 })32 33+ it('Suspense / async component returning an array', async () => {34+ const Content = async () => {35+ await new Promise((resolve) => setTimeout(resolve, 10))36+ return [<h1>Hello</h1>, <h2>World</h2>]37+ }38+39+ const stream = renderToReadableStream(40+ <Suspense fallback={<p>Loading...</p>}>41+ <Content />42+ </Suspense>43+ )44+45+ const chunks = []46+ const textDecoder = new TextDecoder()47+ for await (const chunk of stream as any) {48+ chunks.push(textDecoder.decode(chunk))49+ }50+51+ expect(chunks[0]).toBe(52+ `<template id="H:${suspenseCounter}"></template><p>Loading...</p><!--/$-->`53+ )54+ expect(chunks[1]).toContain(55+ `<template data-hono-target="H:${suspenseCounter}"><h1>Hello</h1><h2>World</h2></template>`56+ )57+ })58+59+ it('preserves callbacks in a streamed async component array', async () => {60+ const phases: number[] = []61+ const Content = async () => [62+ raw('Hello', [({ phase }) => void phases.push(phase)]),63+ <span>World</span>,64+ ]65+66+ const html = await drainStream(renderToReadableStream(<Content />))67+68+ expect(html).toBe('Hello<span>World</span>')69+ expect(phases).toEqual([HtmlEscapedCallbackPhase.BeforeStream, HtmlEscapedCallbackPhase.Stream])70+ suspenseCounter--71+ })72+73 it('Suspense / renderToReadableStream', async () => {74 let contentEvaluatedCount = 075 const Content = () => {76 contentEvaluatedCount++1081 unmodified linesmodified:src/middleware/cache/index.test.ts+394 added-1 removed
99 unmodified lines100 101 it('Should use dynamically generated cache key', async () => {102 await app.request('http://localhost/dynamic-cache-key/')103 const cache = await caches.open('my-app-v1')104- const response = await cache.match(dynamicCacheKey)104+ const response = await cache.match(105+ 'http://localhost/.hono/cache?__hono_cache_key=dynamic-cache-key&__hono_cache_method=GET'106+ )107 expect(response).not.toBeNull()108 })109 110 it('Should retrieve cached response with dynamic cache name and key', async () => {295 unmodified lines406 })407 const res = await app.request('/')408 expect(res.status).toBe(200)409 expect(spy).toHaveBeenCalledOnce()410+ expect(spy).toHaveBeenCalledWith(411+ 'Cache Middleware is not enabled because caches is not defined.'412+ )413 vi.unstubAllGlobals()414 })415 416 it('Should suppress default log when onCacheNotAvailable is false', async () => {328 unmodified lines745 expect(caches.open).not.toHaveBeenCalled()746 expect(putSpy).not.toHaveBeenCalled()747 })748 749+ it('Should cache QUERY responses without consuming the handler request body', async () => {750+ const { mockCache } = stubStoreBackedCache()751+ const app = new Hono()752+ let queryCount = 0753+ app.use('*', cache({ cacheName: 'query-test', wait: true, cacheControl: 'max-age=10' }))754+ app.on('QUERY', '/resource', async (c) => {755+ queryCount++756+ c.header('X-Count', `${queryCount}`)757+ return c.text(await c.req.raw.text())758+ })759+760+ const request = () =>761+ app.request('/resource', {762+ method: 'QUERY',763+ headers: { 'Content-Type': 'application/json' },764+ body: '{"query":"hono"}',765+ })766+767+ await request()768+ const res = await request()769+770+ expect(await res.text()).toBe('{"query":"hono"}')771+ expect(res.headers.get('X-Count')).toBe('1')772+ expect(res.headers.get('Cache-Control')).toBe('max-age=10')773+ expect(mockCache.put).toHaveBeenCalledOnce()774+ })775+776+ it('Should bypass QUERY caching when the measured body exceeds the configured limit', async () => {777+ const { mockCache } = stubStoreBackedCache()778+ const app = new Hono()779+ let queryCount = 0780+ app.use('*', cache({ cacheName: 'query-body-limit-test', wait: true, maxQueryBodySize: 4 }))781+ app.on('QUERY', '/resource', async (c) => {782+ queryCount++783+ c.header('X-Count', `${queryCount}`)784+ return c.text(await c.req.text())785+ })786+787+ const request = () => {788+ const body = new ReadableStream({789+ start(controller) {790+ controller.enqueue(new TextEncoder().encode('ab'))791+ controller.enqueue(new TextEncoder().encode('cde'))792+ controller.close()793+ },794+ })795+ return app.request('/resource', {796+ method: 'QUERY',797+ headers: {798+ 'Content-Length': '1',799+ 'Content-Type': 'text/plain',800+ },801+ body,802+ duplex: 'half',803+ } as RequestInit & { duplex: 'half' })804+ }805+806+ await request()807+ const res = await request()808+809+ expect(await res.text()).toBe('abcde')810+ expect(res.headers.get('X-Count')).toBe('2')811+ expect(caches.open).not.toHaveBeenCalled()812+ expect(mockCache.put).not.toHaveBeenCalled()813+ })814+815+ it('Should cache QUERY requests at the configured body size limit', async () => {816+ const { mockCache } = stubStoreBackedCache()817+ const app = new Hono()818+ let queryCount = 0819+ app.use(820+ '*',821+ cache({ cacheName: 'query-body-limit-boundary-test', wait: true, maxQueryBodySize: 4 })822+ )823+ app.on('QUERY', '/resource', async (c) => {824+ queryCount++825+ c.header('X-Count', `${queryCount}`)826+ return c.text(await c.req.text())827+ })828+829+ const request = () =>830+ app.request('/resource', {831+ method: 'QUERY',832+ headers: { 'Content-Type': 'text/plain' },833+ body: 'abcd',834+ })835+836+ await request()837+ const res = await request()838+839+ expect(await res.text()).toBe('abcd')840+ expect(res.headers.get('X-Count')).toBe('1')841+ expect(mockCache.put).toHaveBeenCalledOnce()842+ })843+844+ it('Should keep QUERY request content and Content-Type in separate cache variants', async () => {845+ const { mockCache } = stubStoreBackedCache()846+ const app = new Hono()847+ let queryCount = 0848+ app.use(849+ '*',850+ cache({ cacheName: 'query-variant-test', wait: true, keyGenerator: () => 'query-key' })851+ )852+ app.on('QUERY', '/resource', async (c) => {853+ queryCount++854+ c.header('X-Count', `${queryCount}`)855+ return c.text(`${c.req.header('Content-Type')}:${await c.req.text()}`)856+ })857+858+ const request = (body: string, contentType: string) =>859+ app.request('/resource', {860+ method: 'QUERY',861+ headers: { 'Content-Type': contentType },862+ body,863+ })864+865+ await request('one', 'text/plain')866+ const same = await request('one', 'text/plain')867+ await request('two', 'text/plain')868+ const differentContent = await request('two', 'text/plain')869+ await request('one', 'application/json')870+ const differentContentType = await request('one', 'application/json')871+872+ expect(same.headers.get('X-Count')).toBe('1')873+ expect(differentContent.headers.get('X-Count')).toBe('2')874+ expect(differentContentType.headers.get('X-Count')).toBe('3')875+ expect(mockCache.put).toHaveBeenCalledTimes(3)876+ })877+878+ it('Should keep GET and QUERY responses in separate cache entries', async () => {879+ const { mockCache } = stubStoreBackedCache()880+ const app = new Hono()881+ app.use('*', cache({ cacheName: 'method-test', wait: true }))882+ app.get('/resource', (c) => c.text('get response'))883+ app.on('QUERY', '/resource', (c) => c.text('query response'))884+885+ await app.request('/resource')886+ await app.request('/resource', {887+ method: 'QUERY',888+ headers: { 'Content-Type': 'application/json' },889+ body: '{}',890+ })891+ const getRes = await app.request('/resource')892+ const queryRes = await app.request('/resource', {893+ method: 'QUERY',894+ headers: { 'Content-Type': 'application/json' },895+ body: '{}',896+ })897+898+ expect(await getRes.text()).toBe('get response')899+ expect(await queryRes.text()).toBe('query response')900+ expect(mockCache.put).toHaveBeenCalledTimes(2)901+ })902+903+ it('Should not let a GET URL alias an internally generated QUERY cache key', async () => {904+ const { mockCache } = stubStoreBackedCache()905+ const app = new Hono()906+ app.use('*', cache({ cacheName: 'method-collision-test', wait: true }))907+ app.get('/resource', (c) => c.text('get response'))908+ app.get('*', (c) => c.text('get response'))909+ app.on('QUERY', '/resource', (c) => c.text('query response'))910+911+ await app.request('/resource', {912+ method: 'QUERY',913+ headers: { 'Content-Type': 'application/json' },914+ body: '{}',915+ })916+917+ const queryKey = mockCache.put.mock.calls[0][0] as string918+ const getRes = await app.request(queryKey)919+ const queryRes = await app.request('/resource', {920+ method: 'QUERY',921+ headers: { 'Content-Type': 'application/json' },922+ body: '{}',923+ })924+925+ expect(await getRes.text()).toBe('get response')926+ expect(await queryRes.text()).toBe('query response')927+ expect(mockCache.put).toHaveBeenCalledTimes(2)928+ })929+930+ it('Should not resolve a custom cache key as a request URL', async () => {931+ const { mockCache } = stubStoreBackedCache()932+ const app = new Hono()933+ app.use(934+ '/resource',935+ cache({936+ cacheName: 'custom-key-collision-test',937+ wait: true,938+ keyGenerator: () => 'query-key',939+ })940+ )941+ app.use('/query-key', cache({ cacheName: 'custom-key-collision-test', wait: true }))942+ app.get('/resource', (c) => c.text('custom key response'))943+ app.get('/query-key', (c) => c.text('request URL response'))944+945+ expect(await (await app.request('/resource')).text()).toBe('custom key response')946+ expect(await (await app.request('/query-key')).text()).toBe('request URL response')947+ expect(mockCache.put).toHaveBeenCalledTimes(2)948+ })949+950+ it('Should keep QUERY digest and vary values with a fragmented custom cache key', async () => {951+ const { mockCache } = stubStoreBackedCache()952+ const app = new Hono()953+ let queryCount = 0954+ app.use(955+ '*',956+ cache({957+ cacheName: 'query-fragment-test',958+ wait: true,959+ vary: 'X-Variant',960+ keyGenerator: (c) => `${c.req.url}#custom-fragment`,961+ })962+ )963+ app.on('QUERY', '/resource', async (c) => {964+ queryCount++965+ return c.text(`${await c.req.text()}:${c.req.header('X-Variant')}`)966+ })967+968+ const request = (body: string, variant: string) =>969+ app.request('/resource', {970+ method: 'QUERY',971+ headers: { 'Content-Type': 'text/plain', 'X-Variant': variant },972+ body,973+ })974+975+ expect(await (await request('one', 'a')).text()).toBe('one:a')976+ expect(await (await request('two', 'a')).text()).toBe('two:a')977+ expect(await (await request('one', 'b')).text()).toBe('one:b')978+ expect(await (await request('one', 'a')).text()).toBe('one:a')979+ expect(queryCount).toBe(3)980+ expect(mockCache.put).toHaveBeenCalledTimes(3)981+ })982+983+ it('Should bypass QUERY caching when Web Crypto is not available', async () => {984+ const originalCrypto = globalThis.crypto985+ vi.stubGlobal('crypto', undefined)986+987+ try {988+ const { mockCache } = stubStoreBackedCache()989+ const app = new Hono()990+ let queryCount = 0991+ let getCount = 0992+ const onCacheNotAvailable = vi.fn()993+ app.use(994+ '*',995+ cache({996+ cacheName: 'query-no-crypto-test',997+ wait: true,998+ onCacheNotAvailable,999+ })1000+ )1001+ app.get('/resource', (c) => {1002+ getCount++1003+ c.header('X-Count', `${getCount}`)1004+ return c.text('get response')1005+ })1006+ app.on('QUERY', '/resource', (c) => {1007+ queryCount++1008+ c.header('X-Count', `${queryCount}`)1009+ return c.text('query response')1010+ })1011+1012+ expect(onCacheNotAvailable).toHaveBeenCalledOnce()1013+ expect(onCacheNotAvailable).toHaveBeenCalledWith(1014+ 'Cache Middleware cannot cache QUERY requests because Web Crypto is not available.'1015+ )1016+1017+ const request = () =>1018+ app.request('/resource', {1019+ method: 'QUERY',1020+ headers: { 'Content-Type': 'application/json' },1021+ body: '{}',1022+ })1023+1024+ await request()1025+ const res = await request()1026+1027+ expect(res.headers.get('X-Count')).toBe('2')1028+ expect(caches.open).not.toHaveBeenCalled()1029+ expect(onCacheNotAvailable).toHaveBeenCalledOnce()1030+1031+ await app.request('/resource')1032+ const getRes = await app.request('/resource')1033+1034+ expect(getRes.headers.get('X-Count')).toBe('1')1035+ expect(mockCache.put).toHaveBeenCalledOnce()1036+ } finally {1037+ vi.stubGlobal('crypto', originalCrypto)1038+ }1039+ })1040+1041+ it('Should bypass QUERY caching when the request content cannot be read', async () => {1042+ const app = new Hono()1043+ let queryCount = 01044+ app.use('*', async (c, next) => {1045+ await c.req.raw.text()1046+ await next()1047+ })1048+ app.use('*', cache({ cacheName: 'query-consumed-body-test', wait: true }))1049+ app.on('QUERY', '/resource', (c) => {1050+ queryCount++1051+ c.header('X-Count', `${queryCount}`)1052+ return c.text('query response')1053+ })1054+1055+ const request = () =>1056+ app.request('/resource', {1057+ method: 'QUERY',1058+ headers: { 'Content-Type': 'application/json' },1059+ body: '{}',1060+ })1061+1062+ await request()1063+ const res = await request()1064+1065+ expect(res.headers.get('X-Count')).toBe('2')1066+ expect(caches.open).not.toHaveBeenCalled()1067+ })1068+1069+ it('Should bypass QUERY caching after the body was read directly as FormData', async () => {1070+ const { mockCache } = stubStoreBackedCache()1071+ const app = new Hono()1072+ let queryCount = 01073+ app.use('*', async (c, next) => {1074+ expect((await c.req.formData()).get('query')).toBe('hono')1075+ await next()1076+ })1077+ app.use('*', cache({ cacheName: 'query-cached-form-data-test', wait: true }))1078+ app.on('QUERY', '/resource', (c) => {1079+ queryCount++1080+ c.header('X-Count', `${queryCount}`)1081+ return c.text('query response')1082+ })1083+1084+ const body = [1085+ '--hono-boundary',1086+ 'Content-Disposition: form-data; name="query"',1087+ '',1088+ 'hono',1089+ '--hono-boundary--',1090+ '',1091+ ].join('\r\n')1092+ const request = () =>1093+ app.request('/resource', {1094+ method: 'QUERY',1095+ headers: { 'Content-Type': 'multipart/form-data; boundary=hono-boundary' },1096+ body,1097+ })1098+1099+ await request()1100+ const res = await request()1101+1102+ expect(res.headers.get('X-Count')).toBe('2')1103+ expect(caches.open).not.toHaveBeenCalled()1104+ expect(mockCache.put).not.toHaveBeenCalled()1105+ })1106+1107+ it('Should cache QUERY after the body was read through HonoRequest', async () => {1108+ const { mockCache } = stubStoreBackedCache()1109+ const app = new Hono()1110+ let queryCount = 01111+ app.use('*', async (c, next) => {1112+ expect(await c.req.text()).toBe('{}')1113+ await next()1114+ })1115+ app.use('*', cache({ cacheName: 'query-cached-body-test', wait: true }))1116+ app.on('QUERY', '/resource', async (c) => {1117+ queryCount++1118+ c.header('X-Count', `${queryCount}`)1119+ return c.text(await c.req.text())1120+ })1121+1122+ const request = () =>1123+ app.request('/resource', {1124+ method: 'QUERY',1125+ headers: { 'Content-Type': 'application/json' },1126+ body: '{}',1127+ })1128+1129+ await request()1130+ const res = await request()1131+1132+ expect(await res.text()).toBe('{}')1133+ expect(res.headers.get('X-Count')).toBe('1')1134+ expect(mockCache.put).toHaveBeenCalledOnce()1135+ })1136+1137 it('Should not use or store cache for POST requests', async () => {1138 const app = new Hono()1139 let postCount = 01140 app.use('*', cache({ cacheName: 'skip-test', wait: true, cacheControl: 'max-age=10' }))21 unmodified linesmodified:src/middleware/cache/index.ts+153 added-13 removed
2 unmodified lines3 * Cache Middleware for Hono.4 */5 6 import type { Context } from '../../context'7+import { cloneRawRequest } from '../../request'8 import type { MiddlewareHandler } from '../../types'9+import { sha256 } from '../../utils/crypto'10 import type { StatusCode } from '../../utils/http-status'11 12 /**13 * status codes that can be cached by default.14 */15 const defaultCacheableStatusCodes: ReadonlyArray<StatusCode> = [200]16 17+const defaultMaxQueryBodySize = 64 * 102418+19+const cacheKeyPath = '/.hono/cache'20+const cacheKeyParameter = '__hono_cache_key'21+const cacheMethodKeyParameter = '__hono_cache_method'22+const queryDigestKeyParameter = '__hono_query_digest'23+const cacheVaryKeyParameter = '__hono_cache_vary'24+25+type CacheKeyRequest =26+ | { method: 'GET' }27+ | {28+ method: 'QUERY'29+ digest: string30+ }31+32+const queryRepresentationMetadataHeaders = [33+ 'content-type',34+ 'content-encoding',35+ 'content-language',36+ 'content-location',37+] as const38+39 const shouldSkipCacheControl = (cacheControl: string | null): boolean =>40 !!cacheControl && /(?:^|,\s*)(?:private|no-(?:store|cache))(?:\s*(?:=|,|$))/i.test(cacheControl)41 42 const parseVaryDirectives = (vary: string | string[] | null | undefined): string[] => {4 unmodified lines47 .map((directive) => directive.trim().toLowerCase())48 .filter(Boolean)49 }50 51+const createCacheKey = (52+ key: string,53+ requestUrl: string,54+ request: CacheKeyRequest,55+ varyHeaders: [string, string][]56+): string => {57+ const url = new URL(cacheKeyPath, requestUrl)58+ url.searchParams.append(cacheKeyParameter, key.split('#', 1)[0])59+ url.searchParams.append(cacheMethodKeyParameter, request.method)60+61+ if (request.method === 'QUERY') {62+ url.searchParams.append(queryDigestKeyParameter, request.digest)63+ }64+65+ for (const header of varyHeaders) {66+ url.searchParams.append(cacheVaryKeyParameter, JSON.stringify(header))67+ }68+69+ return url.href70+}71+72 const shouldSkipCache = (73 res: Response,74 optionsVaryDirectives: Set<string> | undefined,75 responseVary: string[]2 unmodified lines78 (!optionsVaryDirectives || responseVary.some((name) => !optionsVaryDirectives.has(name)))) ||79 shouldSkipCacheControl(res.headers.get('Cache-Control')) ||80 res.headers.has('Set-Cookie')81 82+const reportCacheNotAvailable = (83+ onCacheNotAvailable: ((reason: string) => void) | false | undefined,84+ reason: string85+): void => {86+ if (onCacheNotAvailable === false) {87+ // suppress log88+ } else if (onCacheNotAvailable) {89+ onCacheNotAvailable(reason)90+ } else {91+ console.log(reason)92+ }93+}94+95+const createQueryDigest = async (96+ c: Context,97+ maxQueryBodySize: number98+): Promise<string | undefined> => {99+ if (!globalThis.crypto?.subtle) {100+ return undefined101+ }102+103+ if (c.req.raw.bodyUsed && Object.keys(c.req.bodyCache)[0] === 'formData') {104+ // FormData cannot be reserialized with a stable multipart boundary after105+ // the original request body has been consumed.106+ return undefined107+ }108+109+ try {110+ // RFC 10008 Section 2.7 requires QUERY cache keys to incorporate the111+ // request content and its related representation metadata.112+ const requestHeaders = c.req.raw.headers113+ const metadata = new TextEncoder().encode(114+ JSON.stringify(115+ queryRepresentationMetadataHeaders.map((header) => [header, requestHeaders.get(header)])116+ )117+ )118+ const body = (await cloneRawRequest(c.req)).body119+ const chunks: Uint8Array[] = []120+ let bodySize = 0121+122+ if (body) {123+ const reader = body.getReader()124+ for (;;) {125+ const { done, value } = await reader.read()126+ if (done) {127+ break128+ }129+ bodySize += value.byteLength130+ if (bodySize > maxQueryBodySize) {131+ // Do not await cancellation because a cloned stream's cancellation132+ // can wait for the original request stream to finish.133+ void reader.cancel().catch(() => {})134+ return undefined135+ }136+ chunks.push(value)137+ }138+ }139+140+ const data = new Uint8Array(metadata.byteLength + bodySize)141+ data.set(metadata)142+ let offset = metadata.byteLength143+ for (const chunk of chunks) {144+ data.set(chunk, offset)145+ offset += chunk.byteLength146+ }147+148+ return (await sha256(data)) ?? undefined149+ } catch {150+ // A QUERY response cannot be cached safely if its content cannot be read.151+ return undefined152+ }153+}154+155 /**156 * Cache Middleware for Hono.157 *158 * @see {@link https://hono.dev/docs/middleware/builtin/cache}2 unmodified lines161 * @param {string | Function} options.cacheName - The name of the cache. Can be used to store multiple caches with different identifiers.162 * @param {boolean} [options.wait=false] - A boolean indicating if Hono should wait for the Promise of the `cache.put` function to resolve before continuing with the request. Required to be true for the Deno environment.163 * @param {string} [options.cacheControl] - A string of directives for the `Cache-Control` header.164 * @param {string | string[]} [options.vary] - Adds the configured request headers to the cache key variants and sets the `Vary` header in the response. If the original response header already contains a `Vary` header, the values are merged, removing any duplicates.47- * @param {Function} [options.keyGenerator] - Generates keys for every request in the `cacheName` store. This can be used to cache data based on request parameters or context parameters.165+ * @param {Function} [options.keyGenerator] - Generates keys for every request in the `cacheName` store. This can be used to cache data based on request parameters or context parameters. QUERY keys additionally include a digest of the request content and its representation metadata.166+ * @param {number} [options.maxQueryBodySize=65536] - The maximum QUERY request body size in bytes that can be cached. Larger QUERY requests bypass the cache.167 * @param {number[]} [options.cacheableStatusCodes=[200]] - An array of status codes that can be cached.49- * @param {Function | false} [options.onCacheNotAvailable] - A callback invoked when `globalThis.caches` is not available. By default, a message is logged to the console. Set to `false` to suppress the log, or provide a custom function.168+ * @param {Function | false} [options.onCacheNotAvailable] - A callback invoked with the reason when `globalThis.caches` is not available or QUERY caching cannot use Web Crypto. By default, the reason is logged to the console. Set to `false` to suppress the log, or provide a custom function.169 * @returns {MiddlewareHandler} The middleware handler function.170 * @throws {Error} If the `vary` option includes "*".171 *172 * @example173 * ```ts55- * app.get(174+ * app.use(175 * '*',176 * cache({177 * cacheName: 'my-app',178 * cacheControl: 'max-age=3600',6 unmodified lines185 wait?: boolean186 cacheControl?: string187 vary?: string | string[]188 keyGenerator?: (c: Context) => Promise<string> | string189+ maxQueryBodySize?: number190 cacheableStatusCodes?: StatusCode[]71- onCacheNotAvailable?: (() => void) | false191+ onCacheNotAvailable?: ((reason: string) => void) | false192 }): MiddlewareHandler => {193 if (!globalThis.caches) {74- if (options.onCacheNotAvailable === false) {75- // suppress log76- } else if (options.onCacheNotAvailable) {77- options.onCacheNotAvailable()78- } else {79- console.log('Cache Middleware is not enabled because caches is not defined.')80- }194+ reportCacheNotAvailable(195+ options.onCacheNotAvailable,196+ 'Cache Middleware is not enabled because caches is not defined.'197+ )198 return async (_c, next) => await next()199 }200 201+ if (!globalThis.crypto?.subtle) {202+ reportCacheNotAvailable(203+ options.onCacheNotAvailable,204+ 'Cache Middleware cannot cache QUERY requests because Web Crypto is not available.'205+ )206+ }207+208 if (options.wait === undefined) {209 options.wait = false210 }211 12 unmodified lines224 225 const cacheableStatusCodes = new Set<number>(226 options.cacheableStatusCodes ?? defaultCacheableStatusCodes227 )228+ const maxQueryBodySize = options.maxQueryBodySize ?? defaultMaxQueryBodySize229 230 const addHeader = (c: Context, responseVary: string[]) => {231 if (cacheControlDirectives) {232 const existingDirectives =30 unmodified lines263 }264 }265 266 return async function cache(c, next) {142- if (c.req.method !== 'GET' || c.req.raw.headers.has('Authorization')) {267+ if (268+ (c.req.method !== 'GET' && c.req.method !== 'QUERY') ||269+ c.req.raw.headers.has('Authorization')270+ ) {271 await next()272 return273 }274 275+ let cacheKeyRequest: CacheKeyRequest = { method: 'GET' }276+ if (c.req.method === 'QUERY') {277+ const digest = await createQueryDigest(c, maxQueryBodySize)278+ if (digest === undefined) {279+ await next()280+ return281+ }282+ cacheKeyRequest = { method: 'QUERY', digest }283+ }284+285 let key = c.req.url286 if (options.keyGenerator) {287 key = await options.keyGenerator(c)288 }289+ const varyHeaders: [string, string][] = []290 if (varyDirectives) {291 for (const directive of varyDirectives) {292 const value = c.req.raw.headers.get(directive) ?? ''154- key += `::${directive}=${encodeURIComponent(value)}`293+ varyHeaders.push([directive, value])294 }295 }296+ key = createCacheKey(key, c.req.url, cacheKeyRequest, varyHeaders)297 298 const cacheName =299 typeof options.cacheName === 'function' ? await options.cacheName(c) : options.cacheName300 const cache = await caches.open(cacheName)24 unmodified linesmodified:src/middleware/compress/index.test.ts+87 added
257 unmodified lines258 expect(res.headers.get('ETag')).toBeNull()259 })260 })261 262+ describe('Vary Header', () => {263+ const app = new Hono()264+ app.use('*', compress())265+ app.get('/no-vary', (c) => {266+ c.header('Content-Type', 'text/plain')267+ c.header('Content-Length', '1024')268+ return c.text('a'.repeat(1024))269+ })270+ app.get('/existing-vary', (c) => {271+ c.header('Content-Type', 'text/plain')272+ c.header('Content-Length', '1024')273+ c.header('Vary', 'Cookie')274+ return c.text('a'.repeat(1024))275+ })276+ app.get('/already-accept-encoding', (c) => {277+ c.header('Content-Type', 'text/plain')278+ c.header('Content-Length', '1024')279+ c.header('Vary', 'Accept-Encoding')280+ return c.text('a'.repeat(1024))281+ })282+ app.get('/wildcard-vary', (c) => {283+ c.header('Content-Type', 'text/plain')284+ c.header('Content-Length', '1024')285+ c.header('Vary', '*')286+ return c.text('a'.repeat(1024))287+ })288+ app.get('/not-compressible', (c) => {289+ c.header('Content-Type', 'image/png')290+ c.header('Content-Length', '1024')291+ return c.body('a'.repeat(1024))292+ })293+294+ it('should set Vary: Accept-Encoding when compressing', async () => {295+ const res = await app.request('/no-vary', {296+ headers: { 'Accept-Encoding': 'gzip' },297+ })298+ expect(res.headers.get('Content-Encoding')).toBe('gzip')299+ expect(res.headers.get('Vary')).toBe('Accept-Encoding')300+ })301+302+ it('should append Accept-Encoding to an existing Vary header', async () => {303+ const res = await app.request('/existing-vary', {304+ headers: { 'Accept-Encoding': 'gzip' },305+ })306+ expect(res.headers.get('Content-Encoding')).toBe('gzip')307+ expect(res.headers.get('Vary')).toBe('Cookie, Accept-Encoding')308+ })309+310+ it('should not duplicate Accept-Encoding when Vary already lists it', async () => {311+ const res = await app.request('/already-accept-encoding', {312+ headers: { 'Accept-Encoding': 'gzip' },313+ })314+ expect(res.headers.get('Content-Encoding')).toBe('gzip')315+ expect(res.headers.get('Vary')).toBe('Accept-Encoding')316+ })317+318+ it('should leave Vary: * unchanged', async () => {319+ const res = await app.request('/wildcard-vary', {320+ headers: { 'Accept-Encoding': 'gzip' },321+ })322+ expect(res.headers.get('Content-Encoding')).toBe('gzip')323+ expect(res.headers.get('Vary')).toBe('*')324+ })325+326+ it('should set Vary on an identity response when Accept-Encoding is absent', async () => {327+ const res = await app.request('/no-vary')328+ expect(res.headers.get('Content-Encoding')).toBeNull()329+ expect(res.headers.get('Vary')).toBe('Accept-Encoding')330+ })331+332+ it('should set Vary on an identity response when no offered encoding is accepted', async () => {333+ const res = await app.request('/no-vary', {334+ headers: { 'Accept-Encoding': 'br' },335+ })336+ expect(res.headers.get('Content-Encoding')).toBeNull()337+ expect(res.headers.get('Vary')).toBe('Accept-Encoding')338+ })339+340+ it('should not add a Vary header when the response is not eligible for compression', async () => {341+ const res = await app.request('/not-compressible', {342+ headers: { 'Accept-Encoding': 'gzip' },343+ })344+ expect(res.headers.get('Content-Encoding')).toBeNull()345+ expect(res.headers.get('Vary')).toBeNull()346+ })347+ })348+349 describe('contentTypeFilter', () => {350 describe('RegExp', () => {351 const app = new Hono()352 app.use('*', compress({ contentTypeFilter: /^application\/json/, threshold: 0 }))183 unmodified linesmodified:src/middleware/compress/index.ts+14 added
41 unmodified lines42 }43 return best?.encoding44 }45 46+const varyAcceptEncodingRegExp = /(?:^|,)\s*accept-encoding\s*(?:,|$)/i47+48 /**49 * Compress Middleware for Hono.50 *51 * @see {@link https://hono.dev/docs/middleware/builtin/compress}50 unmodified lines102 ) {103 return104 }105 106+ // From here on the representation is selected from the request's Accept-Encoding,107+ // so caches must key on that header. This is done before the negotiation result is108+ // known, because an identity response served for a missing or unsupported109+ // Accept-Encoding is just as much a negotiated representation: RFC 9110 lists110+ // Accept-Encoding "or lack thereof" as a determining factor. Without this, a shared111+ // cache could reuse the identity response for a client that does accept gzip.112+ // https://www.rfc-editor.org/rfc/rfc9110#field.vary113+ const current = ctx.res.headers.get('Vary')114+ if (current !== '*' && !(current && varyAcceptEncodingRegExp.test(current))) {115+ ctx.header('Vary', current ? `${current}, Accept-Encoding` : 'Accept-Encoding')116+ }117+118 const accepted = ctx.req.header('Accept-Encoding')119 const encoding = selectEncoding(accepted, candidates)120 if (!encoding || !ctx.res.body) {121 return22 unmodified linesmodified:src/middleware/cors/index.test.ts+16 added-3 removed
143 unmodified lines144 expect(res.headers.get('Vary')).toBeNull()145 })146 147 it('Preflight default', async () => {148- const req = new Request('https://localhost/api/abc', { method: 'OPTIONS' })149- req.headers.append('Access-Control-Request-Headers', 'X-PINGOTHER, Content-Type')148+ const req = new Request('https://localhost/api/abc', {149+ method: 'OPTIONS',150+ headers: {151+ 'Access-Control-Request-Method': 'QUERY',152+ 'Access-Control-Request-Headers': 'X-PINGOTHER, Content-Type',153+ },154+ })155 const res = await app.request(req)156 157 expect(res.status).toBe(204)158 expect(res.statusText).toBe('No Content')154- expect(res.headers.get('Access-Control-Allow-Methods')?.split(',')[0]).toBe('GET')159+ expect(res.headers.get('Access-Control-Allow-Methods')?.split(',')).toEqual([160+ 'GET',161+ 'HEAD',162+ 'PUT',163+ 'POST',164+ 'DELETE',165+ 'PATCH',166+ 'QUERY',167+ ])168 expect(res.headers.get('Access-Control-Allow-Headers')?.split(',')).toEqual([169 'X-PINGOTHER',170 'Content-Type',171 ])322 unmodified linesmodified:src/middleware/cors/index.ts+2 added-2 removed
26 unmodified lines27 * @see {@link https://hono.dev/docs/middleware/builtin/cors}28 *29 * @param {CORSOptions} [options] - The options for the CORS middleware.30 * @param {string | string[] | ((origin: string, c: Context) => Promise<string | undefined | null> | string | undefined | null)} [options.origin='*'] - The value of "Access-Control-Allow-Origin" CORS header.31- * @param {string[] | ((origin: string, c: Context) => Promise<string[]> | string[])} [options.allowMethods=['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH']] - The value of "Access-Control-Allow-Methods" CORS header.31+ * @param {string[] | ((origin: string, c: Context) => Promise<string[]> | string[])} [options.allowMethods=['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH', 'QUERY']] - The value of "Access-Control-Allow-Methods" CORS header.32 * @param {string[]} [options.allowHeaders=[]] - The value of "Access-Control-Allow-Headers" CORS header.33 * @param {number} [options.maxAge] - The value of "Access-Control-Max-Age" CORS header.34 * @param {boolean} [options.credentials] - The value of "Access-Control-Allow-Credentials" CORS header.35 * @param {string[]} [options.exposeHeaders=[]] - The value of "Access-Control-Expose-Headers" CORS header.26 unmodified lines62 */63 export const cors = (options?: CORSOptions): MiddlewareHandler => {64 const opts = {65 origin: '*',66- allowMethods: ['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH'],66+ allowMethods: ['GET', 'HEAD', 'PUT', 'POST', 'DELETE', 'PATCH', 'QUERY'],67 allowHeaders: [],68 exposeHeaders: [],69 ...options,70 } satisfies CORSOptions87 unmodified linesmodified:src/middleware/etag/index.test.ts+47 added
224 unmodified lines225 })226 expect(res.status).toBe(304)227 })228 229+ it('Should handle conditional QUERY requests', async () => {230+ const app = new Hono()231+ app.use('/etag/*', etag())232+ app.on('QUERY', '/etag/query', (c) => c.text('Hono is great'))233+234+ // unconditional QUERY235+ let res = await app.request('http://localhost/etag/query', {236+ method: 'QUERY',237+ body: 'select *',238+ })239+ expect(res.status).toBe(200)240+ expect(res.headers.get('ETag')).not.toBeFalsy()241+ const etagHeaderValue = res.headers.get('ETag') || ''242+243+ // conditional QUERY with the wrong ETag:244+ res = await app.request('http://localhost/etag/query', {245+ method: 'QUERY',246+ body: 'select *',247+ headers: {248+ 'If-None-Match': '"not the right etag"',249+ },250+ })251+ expect(res.status).toBe(200)252+253+ // conditional QUERY with matching ETag:254+ res = await app.request('http://localhost/etag/query', {255+ method: 'QUERY',256+ body: 'select *',257+ headers: {258+ 'If-None-Match': etagHeaderValue,259+ },260+ })261+ expect(res.status).toBe(304)262+ expect(res.headers.get('ETag')).toBe(etagHeaderValue)263+ expect(await res.text()).toBe('')264+265+ // conditional QUERY with `*` wildcard:266+ res = await app.request('http://localhost/etag/query', {267+ method: 'QUERY',268+ body: 'select *',269+ headers: {270+ 'If-None-Match': '*',271+ },272+ })273+ expect(res.status).toBe(304)274+ })275+276 it('Should not return 304 for `If-None-Match: *` on unsafe methods or error responses', async () => {277 const app = new Hono()278 app.use('/etag/*', etag())279 app.put('/etag/put', (c) => c.text('created', 201))118 unmodified linesmodified:src/middleware/etag/index.ts+1 added-1 removed
104 unmodified lines105 }106 107 const matched =108 ifNoneMatch === '*'109- ? (c.req.method === 'GET' || c.req.method === 'HEAD') && res.ok109+ ? (c.req.method === 'GET' || c.req.method === 'HEAD' || c.req.method === 'QUERY') && res.ok110 : etagMatches(etag, ifNoneMatch)111 112 if (matched) {113 c.res = new Response(null, {16 unmodified linesmodified:src/middleware/jsx-renderer/index.test.tsx+16 added
53 unmodified lines54 '<!DOCTYPE html><div class="nested"><h1>http://localhost/nested</h1></div>'55 )56 })57 58+ it('accepts an array result', async () => {59+ const app = new Hono()60+ app.use(jsxRenderer(({ children }) => [<header>Header</header>, <main>{children}</main>]))61+ app.get('/', (c) => c.render(<h1>Hello</h1>, { title: 'Hello' }))62+63+ const res = await app.request('/')64+ expect(await res.text()).toBe(65+ '<!DOCTYPE html><header>Header</header><main><h1>Hello</h1></main>'66+ )67+ })68+69+ it('does not accept a null result', () => {70+ // @ts-expect-error A JSX renderer component must produce renderable content.71+ jsxRenderer(() => null)72+ })73+74 it('Should get the context object as a 2nd arg', async () => {75 const app = new Hono()76 app.use(77 jsxRenderer(453 unmodified linesmodified:src/middleware/jsx-renderer/index.ts+4 added-6 removed
8 unmodified lines9 import { Fragment, createContext, jsx, useContext } from '../../jsx'10 import type { FC, Context as JSXContext, JSXNode, PropsWithChildren } from '../../jsx'11 import { renderToReadableStream } from '../../jsx/streaming'12 import type { Env, Input, MiddlewareHandler } from '../../types'13-import type { HtmlEscapedString } from '../../utils/html'13 14 export const RequestContext: JSXContext<Context<any, any, {}> | null> =15 createContext<Context | null>(null)16 1 unmodified line18 docType?: boolean | string19 stream?: boolean | Record<string, string>20 }21 23-type Component = (24- props: PropsForRenderer & { Layout: FC },25- c: Context26-) => HtmlEscapedString | Promise<HtmlEscapedString>22+type ComponentResult = Exclude<ReturnType<FC>, null>23 24+type Component = (props: PropsForRenderer & { Layout: FC }, c: Context) => ComponentResult25+26 type ComponentWithChildren = (27 props: PropsWithChildren<PropsForRenderer & { Layout: FC }>,28 c: Context31-) => HtmlEscapedString | Promise<HtmlEscapedString>29+) => ComponentResult30 31 const createRenderer =32 (33 c: Context,130 unmodified linesmodified:src/middleware/jwk/index.test.ts+55 added
1075 unmodified lines1076 1077 // Note: Test for "no whitelist" was removed because alg is now required.1078 // This is a breaking change that enforces explicit algorithm specification for security.1079 })1080+ describe('WWW-Authenticate realm', () => {1081+ it('Should default to the request URL', async () => {1082+ const app = new Hono()1083+ app.use('/auth/*', jwk({ keys: verify_keys, alg: ['RS256'] }))1084+ app.get('/auth/*', (c) => c.text('ok'))1085+1086+ const res = await app.request('http://localhost/auth/page?a=1')1087+1088+ expect(res.status).toBe(401)1089+ expect(res.headers.get('WWW-Authenticate')).toBe(1090+ 'Bearer realm="http://localhost/auth/page?a=1",error="invalid_request",error_description="no authorization included in request"'1091+ )1092+ })1093+1094+ it('Should use the configured realm', async () => {1095+ const app = new Hono()1096+ app.use('/auth/*', jwk({ keys: verify_keys, alg: ['RS256'], realm: 'my-api' }))1097+ app.get('/auth/*', (c) => c.text('ok'))1098+1099+ const res = await app.request('http://localhost/auth/page?a=1')1100+1101+ expect(res.status).toBe(401)1102+ expect(res.headers.get('WWW-Authenticate')).toBe(1103+ 'Bearer realm="my-api",error="invalid_request",error_description="no authorization included in request"'1104+ )1105+ })1106+1107+ it('Should use the configured realm for an invalid token', async () => {1108+ const app = new Hono()1109+ app.use('/auth/*', jwk({ keys: verify_keys, alg: ['RS256'], realm: 'my-api' }))1110+ app.get('/auth/*', (c) => c.text('ok'))1111+1112+ const req = new Request('http://localhost/auth/page')1113+ req.headers.set('Authorization', 'Bearer invalid-token')1114+ const res = await app.request(req)1115+1116+ expect(res.status).toBe(401)1117+ expect(res.headers.get('WWW-Authenticate')).toBe(1118+ 'Bearer realm="my-api",error="invalid_token",error_description="token verification failure"'1119+ )1120+ })1121+1122+ it('Should escape double quotes in the realm', async () => {1123+ const app = new Hono()1124+ app.use('/auth/*', jwk({ keys: verify_keys, alg: ['RS256'], realm: 'my "quoted" api' }))1125+ app.get('/auth/*', (c) => c.text('ok'))1126+1127+ const res = await app.request('http://localhost/auth/page')1128+1129+ expect(res.status).toBe(401)1130+ expect(res.headers.get('WWW-Authenticate')).toBe(1131+ 'Bearer realm="my \\"quoted\\" api",error="invalid_request",error_description="no authorization included in request"'1132+ )1133+ })1134+ })1135 })modified:src/middleware/jwk/jwk.ts+14 added-1 removed
23 unmodified lines24 * @param {string | ((ctx: Context) => Promise<string> | string)} [options.jwks_uri] - If set to a URI string or a function that returns a URI string, attempt to fetch JWKs from it. The response must be a JSON object containing a `keys` array, which will be merged with the `keys` option.25 * @param {boolean} [options.allow_anon] - If set to `true`, the middleware allows requests without a token to proceed without authentication.26 * @param {string} [options.cookie] - If set, the middleware attempts to retrieve the token from a cookie with these options (optionally signed) only if no token is found in the header.27 * @param {string} [options.headerName='Authorization'] - The name of the header to look for the JWT token. Default is 'Authorization'.28+ * @param {string} [options.realm] - The protection space described by the `realm` parameter of the returned `WWW-Authenticate` challenge header. Defaults to the request URL.29 * @param {AsymmetricAlgorithm[]} options.alg - An array of allowed asymmetric algorithms for JWT verification. Only tokens signed with these algorithms will be accepted.30 * @param {RequestInit} [init] - Optional init options for the `fetch` request when retrieving JWKS from a URI.31 * @param {VerifyOptions} [options.verification] - Additional options for JWK payload verification.32 * @returns {MiddlewareHandler} The middleware handler function.25 unmodified lines58 headerName?: string59 60 alg: AsymmetricAlgorithm[]61 62+ realm?: string63+64 verification?: VerifyOptions65 },66 init?: RequestInit67 ): MiddlewareHandler => {21 unmodified lines89 res: unauthorizedResponse({90 ctx,91 error: 'invalid_request',92 errDescription,93+ realm: options.realm,94 }),95 })96 } else {97 token = parts[1]31 unmodified lines129 res: unauthorizedResponse({130 ctx,131 error: 'invalid_request',132 errDescription,133+ realm: options.realm,134 }),135 })136 }137 22 unmodified lines160 ctx,161 error: 'invalid_token',162 statusText: 'Unauthorized',163 errDescription: 'token verification failure',164+ realm: options.realm,165 }),166 cause,167 })168 }8 unmodified lines177 ctx: Context178 error: string179 errDescription: string180 statusText?: string181+ realm?: string182 }) {183+ // `realm` and `error_description` end up inside a quoted-string, so any `"`184+ // they contain has to be escaped or the header is cut short. Same handling as185+ // the bearer-auth middleware.186+ const realm = (opts.realm ?? opts.ctx.req.url).replace(/"/g, '\\"')187+ const errDescription = opts.errDescription.replace(/"/g, '\\"')188+189 return new Response('Unauthorized', {190 status: 401,191 statusText: opts.statusText,192 headers: {180- 'WWW-Authenticate': `Bearer realm="${opts.ctx.req.url}",error="${opts.error}",error_description="${opts.errDescription}"`,193+ 'WWW-Authenticate': `Bearer realm="${realm}",error="${opts.error}",error_description="${errDescription}"`,194 },195 })196 }modified:src/middleware/jwt/index.test.ts+55 added
742 unmodified lines743 return c.json(payload)744 })745 })746 })747+ describe('WWW-Authenticate realm', () => {748+ it('Should default to the request URL', async () => {749+ const app = new Hono()750+ app.use('/auth/*', jwt({ secret: 'a-secret', alg: 'HS256' }))751+ app.get('/auth/*', (c) => c.text('ok'))752+753+ const res = await app.request('http://localhost/auth/page?a=1')754+755+ expect(res.status).toBe(401)756+ expect(res.headers.get('WWW-Authenticate')).toBe(757+ 'Bearer realm="http://localhost/auth/page?a=1",error="invalid_request",error_description="no authorization included in request"'758+ )759+ })760+761+ it('Should use the configured realm', async () => {762+ const app = new Hono()763+ app.use('/auth/*', jwt({ secret: 'a-secret', alg: 'HS256', realm: 'my-api' }))764+ app.get('/auth/*', (c) => c.text('ok'))765+766+ const res = await app.request('http://localhost/auth/page?a=1')767+768+ expect(res.status).toBe(401)769+ expect(res.headers.get('WWW-Authenticate')).toBe(770+ 'Bearer realm="my-api",error="invalid_request",error_description="no authorization included in request"'771+ )772+ })773+774+ it('Should use the configured realm for an invalid token', async () => {775+ const app = new Hono()776+ app.use('/auth/*', jwt({ secret: 'a-secret', alg: 'HS256', realm: 'my-api' }))777+ app.get('/auth/*', (c) => c.text('ok'))778+779+ const req = new Request('http://localhost/auth/page')780+ req.headers.set('Authorization', 'Bearer invalid-token')781+ const res = await app.request(req)782+783+ expect(res.status).toBe(401)784+ expect(res.headers.get('WWW-Authenticate')).toBe(785+ 'Bearer realm="my-api",error="invalid_token",error_description="token verification failure"'786+ )787+ })788+789+ it('Should escape double quotes in the realm', async () => {790+ const app = new Hono()791+ app.use('/auth/*', jwt({ secret: 'a-secret', alg: 'HS256', realm: 'my "quoted" api' }))792+ app.get('/auth/*', (c) => c.text('ok'))793+794+ const res = await app.request('http://localhost/auth/page')795+796+ expect(res.status).toBe(401)797+ expect(res.headers.get('WWW-Authenticate')).toBe(798+ 'Bearer realm="my \\"quoted\\" api",error="invalid_request",error_description="no authorization included in request"'799+ )800+ })801+ })802 })modified:src/middleware/jwt/jwt.ts+13 added-1 removed
27 unmodified lines28 * @param {SignatureKey} options.secret - A value of your secret key.29 * @param {string} [options.cookie] - If this value is set, then the value is retrieved from the cookie header using that value as a key, which is then validated as a token.30 * @param {SignatureAlgorithm} options.alg - An algorithm type that is used for verifying (required). Available types are `HS256` | `HS384` | `HS512` | `RS256` | `RS384` | `RS512` | `PS256` | `PS384` | `PS512` | `ES256` | `ES384` | `ES512` | `EdDSA`.31 * @param {string} [options.headerName='Authorization'] - The name of the header to look for the JWT token. Default is 'Authorization'.32+ * @param {string} [options.realm] - The protection space described by the `realm` parameter of the returned `WWW-Authenticate` challenge header. Defaults to the request URL.33 * @param {VerifyOptions} [options.verification] - Additional options for JWT payload verification.34 * @returns {MiddlewareHandler} The middleware handler function.35 *36 * @example20 unmodified lines57 | string58 | { key: string; secret?: string | BufferSource; prefixOptions?: CookiePrefixOptions }59 alg: SignatureAlgorithm60 headerName?: string61+ realm?: string62 verification?: VerifyOptions63 }): MiddlewareHandler => {64 const verifyOpts = options.verification || {}65 23 unmodified lines89 res: unauthorizedResponse({90 ctx,91 error: 'invalid_request',92 errDescription,93+ realm: options.realm,94 }),95 })96 } else {97 token = parts[1]28 unmodified lines126 res: unauthorizedResponse({127 ctx,128 error: 'invalid_request',129 errDescription,130+ realm: options.realm,131 }),132 })133 }134 14 unmodified lines149 ctx,150 error: 'invalid_token',151 statusText: 'Unauthorized',152 errDescription: 'token verification failure',153+ realm: options.realm,154 }),155 cause,156 })157 }8 unmodified lines166 ctx: Context167 error: string168 errDescription: string169 statusText?: string170+ realm?: string171 }) {172+ // `realm` and `error_description` end up inside a quoted-string, so any `"`173+ // they contain has to be escaped or the header is cut short. Same handling as174+ // the bearer-auth middleware.175+ const realm = (opts.realm ?? opts.ctx.req.url).replace(/"/g, '\\"')176+ const errDescription = opts.errDescription.replace(/"/g, '\\"')177+178 return new Response('Unauthorized', {179 status: 401,180 statusText: opts.statusText,181 headers: {170- 'WWW-Authenticate': `Bearer realm="${opts.ctx.req.url}",error="${opts.error}",error_description="${opts.errDescription}"`,182+ 'WWW-Authenticate': `Bearer realm="${realm}",error="${opts.error}",error_description="${errDescription}"`,183 },184 })185 }186 4 unmodified linesadded:src/middleware/method-not-allowed/index.test.ts+292 added
1+import { Hono } from '../../hono'2+import { methodNotAllowed } from '.'3+4+describe('Method Not Allowed Middleware', () => {5+ it('infers the environment from the app', () => {6+ const app = new Hono<{ Variables: { requestId: string } }>()7+ const middleware = methodNotAllowed({8+ app,9+ onMethodNotAllowed: (c) => c.text(c.var.requestId, 405),10+ })11+12+ expect(middleware).toBeTypeOf('function')13+ })14+15+ it('returns 405 with every allowed method for an existing path', async () => {16+ const app = new Hono()17+ app.use(methodNotAllowed({ app }))18+ app.get('/resource', (c) => c.text('GET'))19+ app.post('/resource', (c) => c.text('POST'))20+ app.delete('/resource', (c) => c.text('DELETE'))21+22+ const res = await app.request('/resource', { method: 'PUT' })23+24+ expect(res.status).toBe(405)25+ expect(res.headers.get('Allow')).toBe('GET, HEAD, POST, DELETE')26+ expect(await res.text()).toBe('Method Not Allowed')27+28+ const resUsingCachedRouter = await app.request('/resource', { method: 'OPTIONS' })29+ expect(resUsingCachedRouter.status).toBe(405)30+ expect(resUsingCachedRouter.headers.get('Allow')).toBe('GET, HEAD, POST, DELETE')31+ })32+33+ it('does not affect an allowed method', async () => {34+ const app = new Hono()35+ app.use(methodNotAllowed({ app }))36+ app.get('/resource', (c) => c.text('GET'))37+38+ const res = await app.request('/resource')39+40+ expect(res.status).toBe(200)41+ expect(res.headers.has('Allow')).toBe(false)42+ expect(await res.text()).toBe('GET')43+ })44+45+ it('returns 404 when the path does not exist', async () => {46+ const app = new Hono()47+ app.use(methodNotAllowed({ app }))48+ app.get('/resource', (c) => c.text('GET'))49+50+ const res = await app.request('/missing', { method: 'POST' })51+52+ expect(res.status).toBe(404)53+ expect(res.headers.has('Allow')).toBe(false)54+ })55+56+ it('matches parameterized and overlapping routes without duplicate methods', async () => {57+ const app = new Hono()58+ app.use(methodNotAllowed({ app }))59+ app.get('/users/:id', (_c, next) => next())60+ app.get('/users/me', (c) => c.text('me'))61+ app.patch('/users/:id', (c) => c.text(c.req.param('id')))62+63+ const res = await app.request('/users/me', { method: 'POST' })64+65+ expect(res.status).toBe(405)66+ expect(res.headers.get('Allow')).toBe('GET, HEAD, PATCH')67+ })68+69+ it('preserves an intentional 404 from a handler registered for the request method', async () => {70+ const app = new Hono()71+ app.use(methodNotAllowed({ app }))72+ app.get('/users/:id', (c) => c.notFound())73+ app.post('/users/:id', (c) => c.text('Created'))74+75+ const res = await app.request('/users/123')76+77+ expect(res.status).toBe(404)78+ expect(res.headers.has('Allow')).toBe(false)79+ })80+81+ it('preserves an intentional 404 for HEAD when a GET route is registered', async () => {82+ const app = new Hono()83+ app.use(methodNotAllowed({ app }))84+ app.get('/users/:id', (c) => c.notFound())85+ app.post('/users/:id', (c) => c.text('Created'))86+87+ const res = await app.request('/users/123', { method: 'HEAD' })88+89+ expect(res.status).toBe(404)90+ expect(res.headers.has('Allow')).toBe(false)91+ })92+93+ it('preserves a 404 returned by the error handler', async () => {94+ const app = new Hono()95+ app.onError((_error, c) => c.text('Handled error', 404))96+ app.use(methodNotAllowed({ app }))97+ app.use('/resource', () => {98+ throw new Error('boom')99+ })100+ app.get('/resource', (c) => c.text('GET'))101+102+ const res = await app.request('/resource', { method: 'POST' })103+104+ expect(res.status).toBe(404)105+ expect(res.headers.has('Allow')).toBe(false)106+ expect(await res.text()).toBe('Handled error')107+ })108+109+ it('returns 405 for HEAD when the path does not support GET', async () => {110+ const app = new Hono()111+ app.use(methodNotAllowed({ app }))112+ app.post('/resource', (c) => c.text('POST'))113+114+ const res = await app.request('/resource', { method: 'HEAD' })115+116+ expect(res.status).toBe(405)117+ expect(res.headers.get('Allow')).toBe('POST')118+ expect(await res.text()).toBe('')119+ })120+121+ it('does not advertise explicit HEAD routes that Hono cannot dispatch', async () => {122+ const app = new Hono()123+ app.use(methodNotAllowed({ app }))124+ app.on('HEAD', '/resource', (c) => c.text('HEAD'))125+126+ const headRes = await app.request('/resource', { method: 'HEAD' })127+ expect(headRes.status).toBe(404)128+ expect(headRes.headers.has('Allow')).toBe(false)129+130+ const putRes = await app.request('/resource', { method: 'PUT' })131+ expect(putRes.status).toBe(404)132+ expect(putRes.headers.has('Allow')).toBe(false)133+ })134+135+ it('supports custom methods', async () => {136+ const app = new Hono()137+ app.use(methodNotAllowed({ app }))138+ app.on('PURGE', '/cache', (c) => c.text('Purged'))139+140+ const res = await app.request('/cache', { method: 'POST' })141+142+ expect(res.status).toBe(405)143+ expect(res.headers.get('Allow')).toBe('PURGE')144+ })145+146+ it('compares request methods case-sensitively', async () => {147+ const app = new Hono()148+ app.use(methodNotAllowed({ app }))149+ app.patch('/item', (c) => c.text('PATCH'))150+151+ const request = new Request('http://localhost/item', { method: 'PATCH' })152+ Object.defineProperty(request, 'method', { value: 'patch' })153+ const res = await app.request(request)154+155+ expect(res.status).toBe(405)156+ expect(res.headers.get('Allow')).toBe('PATCH')157+ })158+159+ it('works with routes mounted using app.route()', async () => {160+ const api = new Hono()161+ api.get('/resource', (c) => c.text('GET'))162+ api.post('/resource', (c) => c.text('POST'))163+164+ const app = new Hono()165+ app.use(methodNotAllowed({ app }))166+ app.route('/api', api)167+168+ const res = await app.request('/api/resource', { method: 'DELETE' })169+170+ expect(res.status).toBe(405)171+ expect(res.headers.get('Allow')).toBe('GET, HEAD, POST')172+ })173+174+ it('works when installed in an app mounted using app.route()', async () => {175+ const api = new Hono().basePath('/v1')176+ api.use(methodNotAllowed({ app: api }))177+ api.get('/resource', (c) => c.text('GET'))178+ api.post('/resource', (c) => c.text('POST'))179+180+ const app = new Hono()181+ app.route('/api', api)182+183+ const res = await app.request('/api/v1/resource', { method: 'DELETE' })184+185+ expect(res.status).toBe(405)186+ expect(res.headers.get('Allow')).toBe('GET, HEAD, POST')187+ })188+189+ it('ignores ALL routes when collecting allowed methods', async () => {190+ const app = new Hono()191+ app.use(methodNotAllowed({ app }))192+ app.all('/resource', (_c, next) => next())193+194+ const res = await app.request('/resource', { method: 'POST' })195+196+ expect(res.status).toBe(404)197+ expect(res.headers.has('Allow')).toBe(false)198+ })199+200+ it('does not invoke the error handler for a 405 response', async () => {201+ const app = new Hono()202+ const onError = vi.fn(() => new Response('error', { status: 500 }))203+ app.onError(onError)204+ app.use(methodNotAllowed({ app }))205+ app.get('/resource', (c) => c.text('GET'))206+207+ const res = await app.request('/resource', { method: 'POST' })208+209+ expect(res.status).toBe(405)210+ expect(onError).not.toHaveBeenCalled()211+ })212+213+ it('preserves downstream headers and lets outer middleware observe the final status', async () => {214+ const app = new Hono()215+ let observedStatus: number | undefined216+217+ app.use(async (c, next) => {218+ await next()219+ observedStatus = c.res.status220+ })221+ app.use(methodNotAllowed({ app }))222+ app.use(async (c, next) => {223+ await next()224+ c.header('X-Downstream', 'true')225+ })226+ app.get('/resource', (c) => c.text('GET'))227+228+ const res = await app.request('/resource', { method: 'POST' })229+230+ expect(res.status).toBe(405)231+ expect(res.headers.get('X-Downstream')).toBe('true')232+ expect(observedStatus).toBe(405)233+ })234+235+ it('replaces stale representation headers from the not-found response', async () => {236+ const app = new Hono()237+ app.use(methodNotAllowed({ app }))238+ app.get('/resource', (c) => c.text('GET'))239+ app.post('/resource', (c) => c.text('POST'))240+ app.notFound((c) =>241+ c.text('Missing', 404, {242+ Allow: 'BOGUS',243+ 'Content-Length': '7',244+ })245+ )246+247+ const res = await app.request('/resource', { method: 'PUT' })248+249+ expect(res.status).toBe(405)250+ expect(res.headers.get('Allow')).toBe('GET, HEAD, POST')251+ expect(res.headers.has('Content-Length')).toBe(false)252+ expect(await res.text()).toBe('Method Not Allowed')253+ })254+255+ it('supports a custom method-not-allowed response', async () => {256+ const app = new Hono()257+ app.use(258+ methodNotAllowed({259+ app,260+ onMethodNotAllowed: (c, allowedMethods) =>261+ c.json({ error: 'Method Not Allowed', allowedMethods }, 405, {262+ Allow: allowedMethods.join(', '),263+ }),264+ })265+ )266+ app.get('/resource', (c) => c.text('GET'))267+ app.post('/resource', (c) => c.text('POST'))268+269+ const res = await app.request('/resource', { method: 'PUT' })270+271+ expect(res.status).toBe(405)272+ expect(res.headers.get('Allow')).toBe('GET, HEAD, POST')273+ expect(res.headers.get('Content-Type')).toMatch(/^application\/json/)274+ expect(await res.json()).toEqual({275+ error: 'Method Not Allowed',276+ allowedMethods: ['GET', 'HEAD', 'POST'],277+ })278+ })279+280+ it('leaves a non-404 custom not-found response unchanged', async () => {281+ const app = new Hono()282+ app.use(methodNotAllowed({ app }))283+ app.get('/resource', (c) => c.text('GET'))284+ app.notFound((c) => c.text('Missing', 410))285+286+ const res = await app.request('/resource', { method: 'POST' })287+288+ expect(res.status).toBe(410)289+ expect(res.headers.has('Allow')).toBe(false)290+ expect(await res.text()).toBe('Missing')291+ })292+})added:src/middleware/method-not-allowed/index.ts+141 added
1+/**2+ * @module3+ * Method Not Allowed Middleware for Hono.4+ */5+6+import type { Context } from '../../context'7+import { basePath, matchedRoutes } from '../../helper/route'8+import type { Hono } from '../../hono'9+import { METHOD_NAME_ALL } from '../../router'10+import { TrieRouter } from '../../router/trie-router'11+import type { Env, MiddlewareHandler } from '../../types'12+13+type MethodNotAllowedHandler<E extends Env> = (14+ c: Context<E>,15+ allowedMethods: string[]16+) => Response | Promise<Response>17+18+type MethodNotAllowedOptions<E extends Env> = {19+ // eslint-disable-next-line @typescript-eslint/no-explicit-any20+ app: Hono<E, any, any>21+ onMethodNotAllowed?: MethodNotAllowedHandler<E>22+}23+24+/**25+ * Method Not Allowed Middleware for Hono.26+ *27+ * Returns a `405 Method Not Allowed` response with an `Allow` header when the request path28+ * matches a registered route but the request method is not supported.29+ *30+ * @param {MethodNotAllowedOptions} options - The options for the middleware.31+ * @param {Hono} options.app - The Hono instance used by the application.32+ * @param {MethodNotAllowedHandler} [options.onMethodNotAllowed] - Generates the response, including its `Allow` header.33+ * @returns {MiddlewareHandler} The middleware handler function.34+ *35+ * @example36+ * ```ts37+ * const app = new Hono()38+ *39+ * app.use(methodNotAllowed({ app }))40+ *41+ * app.get('/hello', (c) => c.text('Hello!'))42+ * app.post('/hello', (c) => c.text('Posted!'))43+ *44+ * // PUT /hello -> 405 Method Not Allowed45+ * // Allow: GET, HEAD, POST46+ * ```47+ *48+ * @example49+ * ```ts50+ * app.use(51+ * methodNotAllowed({52+ * app,53+ * onMethodNotAllowed: (c, methods) =>54+ * c.json({ error: 'Method Not Allowed' }, 405, { Allow: methods.join(', ') }),55+ * })56+ * )57+ * ```58+ */59+export const methodNotAllowed = <E extends Env = Env>(60+ options: MethodNotAllowedOptions<E>61+): MiddlewareHandler<E> => {62+ let methodRouter: TrieRouter<string[]> | undefined63+64+ return async function methodNotAllowed(c, next) {65+ const routeIndex = c.req.routeIndex66+ await next()67+68+ if (c.res.status !== 404) {69+ return70+ }71+72+ if (c.error) {73+ return74+ }75+76+ if (!methodRouter) {77+ const methodsByPath = new Map<string, Set<string>>()78+79+ for (const route of options.app.routes) {80+ // Hono does not distinguish middleware registered with `app.use()` from handlers81+ // registered with `app.all()`, so `ALL` routes cannot contribute to the Allow header.82+ if (route.method === METHOD_NAME_ALL || route.method === 'HEAD') {83+ continue84+ }85+86+ const methods = methodsByPath.get(route.path) ?? new Set<string>()87+ methods.add(route.method)88+89+ // Hono dispatches HEAD requests to GET routes.90+ if (route.method === 'GET') {91+ methods.add('HEAD')92+ }93+94+ methodsByPath.set(route.path, methods)95+ }96+97+ methodRouter = new TrieRouter()98+ for (const [path, methods] of methodsByPath) {99+ methodRouter.add(METHOD_NAME_ALL, path, [...methods])100+ }101+ }102+103+ let requestPath = c.req.path104+ const routes = matchedRoutes(c)105+ const currentRoute = routes[routeIndex]106+ const sourceRoute = options.app.routes.find((route) => route.handler === methodNotAllowed)107+ if (currentRoute && sourceRoute) {108+ const currentBasePathParts = basePath(c, routeIndex).split('/').filter(Boolean)109+ const sourceBasePathLength = sourceRoute.basePath.split('/').filter(Boolean).length110+ const mountBasePathParts = currentBasePathParts.slice(111+ 0,112+ currentBasePathParts.length - sourceBasePathLength113+ )114+ if (mountBasePathParts.length > 0) {115+ const mountBasePath = `/${mountBasePathParts.join('/')}`116+ requestPath = c.req.path.slice(mountBasePath.length) || '/'117+ }118+ }119+120+ const allowedMethods = new Set<string>()121+ for (const [methods] of methodRouter.match(METHOD_NAME_ALL, requestPath)[0]) {122+ for (const method of methods) {123+ allowedMethods.add(method)124+ }125+ }126+127+ if (allowedMethods.size === 0 || allowedMethods.has(c.req.method)) {128+ return129+ }130+131+ // Prevent stale headers from being carried over from the 404 response.132+ c.res.headers.delete('Allow')133+ c.res.headers.delete('Content-Length')134+135+ const methods = [...allowedMethods]136+ const allow = methods.join(', ')137+ c.res = options.onMethodNotAllowed138+ ? await options.onMethodNotAllowed(c, methods)139+ : c.text('Method Not Allowed', 405, { Allow: allow })140+ }141+}modified:src/router/reg-exp-router/node.ts+86 added-80 removed
23 unmodified lines24 if (b.length === 1) {25 return 126 }27 28- // wildcard28+ // wildcard: the only wildcard (.*) precedes the tail wildcard29 if (a === ONLY_WILDCARD_REG_EXP_STR || a === TAIL_WILDCARD_REG_EXP_STR) {30- return 130+ return b === TAIL_WILDCARD_REG_EXP_STR ? -1 : 131 } else if (b === ONLY_WILDCARD_REG_EXP_STR || b === TAIL_WILDCARD_REG_EXP_STR) {32 return -133 }34 7 unmodified lines42 return a.length === b.length ? (a < b ? -1 : 1) : b.length - a.length43 }44 45 export class Node {46+ // handler index of a dynamic path, or -1 for a static path terminal47 #index?: number48 #varIndex?: number49 #children: Record<string, Node> = Object.create(null)50 1 unmodified line52 tokens: readonly string[],53 index: number,54 paramMap: ParamAssocArray,55 context: Context,55- pathErrorCheckOnly: boolean56+ isStatic: boolean57 ): void {57- if (tokens.length === 0) {58- if (this.#index !== undefined) {59- throw PATH_ERROR60- }61- if (pathErrorCheckOnly) {62- return63- }58+ // eslint-disable-next-line @typescript-eslint/no-this-alias59+ let node: Node = this60+ for (let i = 0, len = tokens.length; i < len; i++) {61+ const token = tokens[i]62+ const pattern =63+ token.length === 164+ ? token === '*'65+ ? i === len - 166+ ? ['', '', ONLY_WILDCARD_REG_EXP_STR] // '*' matches to all the trailing paths67+ : ['', '', LABEL_REG_EXP_STR]68+ : null69+ : token === '/*'70+ ? ['', '', TAIL_WILDCARD_REG_EXP_STR] // '/path/to/*' is /\/path\/to(?:|/.*)$71+ : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/)72 65- this.#index = index66- return67- }68-69- const [token, ...restTokens] = tokens70- const pattern =71- token === '*'72- ? restTokens.length === 073- ? ['', '', ONLY_WILDCARD_REG_EXP_STR] // '*' matches to all the trailing paths74- : ['', '', LABEL_REG_EXP_STR]75- : token === '/*'76- ? ['', '', TAIL_WILDCARD_REG_EXP_STR] // '/path/to/*' is /\/path\/to(?:|/.*)$77- : token.match(/^\:([^\{\}]+)(?:\{(.+)\})?$/)78-79- let node80- if (pattern) {81- const name = pattern[1]82- let regexpStr = pattern[2] || LABEL_REG_EXP_STR83- if (name && pattern[2]) {84- if (regexpStr === '.*') {85- throw PATH_ERROR73+ let nextNode: Node74+ if (pattern) {75+ const name = pattern[1]76+ let regexpStr = pattern[2] || LABEL_REG_EXP_STR77+ if (name && pattern[2]) {78+ if (regexpStr === '.*') {79+ throw PATH_ERROR80+ }81+ regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, '(?:') // (a|b) => (?:a|b)82+ if (/\((?!\?:)/.test(regexpStr)) {83+ // prefix(?:a|b) is allowed, but prefix(a|b) is not84+ throw PATH_ERROR85+ }86+ if (regexpStr.length === 1 && regExpMetaChars.has(regexpStr)) {87+ // a single-char pattern like :x{.} is ambiguous with a literal character88+ throw PATH_ERROR89+ }90 }87- regexpStr = regexpStr.replace(/^\((?!\?:)(?=[^)]+\)$)/, '(?:') // (a|b) => (?:a|b)88- if (/\((?!\?:)/.test(regexpStr)) {89- // prefix(?:a|b) is allowed, but prefix(a|b) is not90- throw PATH_ERROR91- }92- }91 94- node = this.#children[regexpStr]95- if (!node) {96- if (97- Object.keys(this.#children).some(98- (k) => k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR99- )100- ) {101- throw PATH_ERROR92+ nextNode = node.#children[regexpStr]93+ if (!nextNode) {94+ if (regexpStr !== ONLY_WILDCARD_REG_EXP_STR && regexpStr !== TAIL_WILDCARD_REG_EXP_STR) {95+ for (const k in node.#children) {96+ if (97+ // a single-char pattern coexists with single-char literals as a literal does98+ (regexpStr.length > 1 || k.length > 1) &&99+ k !== ONLY_WILDCARD_REG_EXP_STR &&100+ k !== TAIL_WILDCARD_REG_EXP_STR101+ ) {102+ throw PATH_ERROR103+ }104+ }105+ }106+ nextNode = node.#children[regexpStr] = new Node()107 }103- if (pathErrorCheckOnly) {104- return105- }106- node = this.#children[regexpStr] = new Node()108 if (name !== '') {108- node.#varIndex = context.varIndex++109+ nextNode.#varIndex ??= context.varIndex++110+ paramMap.push([name, nextNode.#varIndex])111 }110- }111- if (!pathErrorCheckOnly && name !== '') {112- paramMap.push([name, node.#varIndex as number])113- }114- } else {115- node = this.#children[token]116- if (!node) {117- if (118- Object.keys(this.#children).some(119- (k) =>120- k.length > 1 && k !== ONLY_WILDCARD_REG_EXP_STR && k !== TAIL_WILDCARD_REG_EXP_STR121- )122- ) {123- throw PATH_ERROR112+ } else {113+ nextNode = node.#children[token]114+ if (!nextNode) {115+ for (const k in node.#children) {116+ if (117+ k.length > 1 &&118+ k !== ONLY_WILDCARD_REG_EXP_STR &&119+ k !== TAIL_WILDCARD_REG_EXP_STR120+ ) {121+ throw PATH_ERROR122+ }123+ }124+ nextNode = node.#children[token] = new Node()125 }125- if (pathErrorCheckOnly) {126- return127- }128- node = this.#children[token] = new Node()126 }127+128+ node = nextNode129 }130 132- node.insert(restTokens, index, paramMap, context, pathErrorCheckOnly)131+ if (node.#index !== undefined) {132+ throw PATH_ERROR133+ }134+ node.#index = isStatic ? -1 : index135 }136 137 buildRegExpStr(): string {138 const childKeys = Object.keys(this.#children).sort(compareKey)139 138- const strList = childKeys.map((k) => {139- const c = this.#children[k]140- return (141- (typeof c.#varIndex === 'number'142- ? `(${k})@${c.#varIndex}`143- : regExpMetaChars.has(k)144- ? `\\${k}`145- : k) + c.buildRegExpStr()146- )147- })140+ const strList = childKeys141+ .map((k) => {142+ const c = this.#children[k]143+ const childStr = c.buildRegExpStr()144+ // an empty childStr means a static-only branch, which is handled by staticMap145+ return childStr === ''146+ ? ''147+ : (typeof c.#varIndex === 'number'148+ ? `(${k})@${c.#varIndex}`149+ : regExpMetaChars.has(k)150+ ? `\\${k}`151+ : k) + childStr152+ })153+ .filter(Boolean)154 149- if (typeof this.#index === 'number') {155+ if (typeof this.#index === 'number' && this.#index !== -1) {156 strList.unshift(`#${this.#index}`)157 }158 159 if (strList.length === 0) {9 unmodified linesmodified:src/router/reg-exp-router/router.test.ts+159 added-35 removed
1-import type { ParamStash } from '../../router'1+import type { ParamIndexMap, ParamStash } from '../../router'2 import { UnsupportedPathError } from '../../router'3 import { runTest } from '../common.case.test'4 import { RegExpRouter } from './router'5 32 unmodified lines38 })39 40 describe('UnsupportedPathError', () => {41 describe('Ambiguous', () => {42- const router = new RegExpRouter<string>()43-44- router.add('GET', '/:user/entries', 'get user entries')45- router.add('GET', '/entry/:name', 'get entry')46- router.add('POST', '/entry', 'create entry')47-48- it('GET /entry/entries', () => {42+ it('GET /entry/:name', () => {43+ const router = new RegExpRouter<string>()44+ router.add('GET', '/:user/entries', 'get user entries')45 expect(() => {50- router.match('GET', '/entry/entries')46+ router.add('GET', '/entry/:name', 'get entry')47 }).toThrowError(UnsupportedPathError)48 })49 })50 51 describe('Multiple handlers with different label', () => {56- const router = new RegExpRouter<string>()57-58- router.add('GET', '/:type/:id', ':type')59- router.add('GET', '/:class/:id', ':class')60- router.add('GET', '/:model/:id', ':model')61-62- it('GET /entry/123', () => {52+ it('GET /:class/:id', () => {53+ const router = new RegExpRouter<string>()54+ router.add('GET', '/:type/:id', ':type')55 expect(() => {64- router.match('GET', '/entry/123')56+ router.add('GET', '/:class/:id', ':class')57 }).toThrowError(UnsupportedPathError)58 })59 })60 61 it('parent', () => {62 const router = new RegExpRouter<string>()63 router.add('GET', '/:id/:action', 'foo')72- router.add('GET', '/posts/:id', 'bar')64 expect(() => {74- router.match('GET', '/')65+ router.add('GET', '/posts/:id', 'bar')66 }).toThrowError(UnsupportedPathError)67 })68 69 it('child', () => {70 const router = new RegExpRouter<string>()71 router.add('GET', '/posts/:id', 'foo')81- router.add('GET', '/:id/:action', 'bar')82-72 expect(() => {84- router.match('GET', '/')73+ router.add('GET', '/:id/:action', 'bar')74 }).toThrowError(UnsupportedPathError)75 })76 77 describe('static and dynamic', () => {78 it('static first', () => {79 const router = new RegExpRouter<string>()80 router.add('GET', '/reg-exp/router', 'foo')92- router.add('GET', '/reg-exp/:id', 'bar')93-81 expect(() => {95- router.match('GET', '/')82+ router.add('GET', '/reg-exp/:id', 'bar')83 }).toThrowError(UnsupportedPathError)84 })85 86 it('long label', () => {87 const router = new RegExpRouter<string>()88 router.add('GET', '/reg-exp/router', 'foo')102- router.add('GET', '/reg-exp/:service', 'bar')103-89 expect(() => {105- router.match('GET', '/')90+ router.add('GET', '/reg-exp/:service', 'bar')91 }).toThrowError(UnsupportedPathError)92 })93 94 it('dynamic first', () => {95 const router = new RegExpRouter<string>()96 router.add('GET', '/reg-exp/:id', 'bar')112- router.add('GET', '/reg-exp/router', 'foo')113-97 expect(() => {115- router.match('GET', '/')98+ router.add('GET', '/reg-exp/router', 'foo')99 }).toThrowError(UnsupportedPathError)100 })101 })102 103 it('different regular expression', () => {104 const router = new RegExpRouter<string>()105 router.add('GET', '/:id/:action{create|update}', 'foo')123- router.add('GET', '/:id/:action{delete}', 'bar')106 expect(() => {125- router.match('GET', '/')107+ router.add('GET', '/:id/:action{delete}', 'bar')108 }).toThrowError(UnsupportedPathError)109 })110 111+ it('ALL route added after a specific-method route', () => {112+ const router = new RegExpRouter<string>()113+ router.add('GET', '/foo/:a', 'foo')114+ expect(() => {115+ router.add('ALL', '/foo/:b', 'bar')116+ }).toThrowError(UnsupportedPathError)117+ })118+119+ it('specific-method route added after an ALL route', () => {120+ const router = new RegExpRouter<string>()121+ router.add('ALL', '/reg-exp/router', 'foo')122+123+ expect(() => {124+ router.add('GET', '/reg-exp/:id', 'bar')125+ }).toThrowError(UnsupportedPathError)126+ })127+128+ it('different methods do not conflict', () => {129+ const router = new RegExpRouter<string>()130+ router.add('GET', '/reg-exp/router', 'foo')131+ router.add('POST', '/reg-exp/:id', 'bar')132+133+ expect(router.match('GET', '/reg-exp/router')[0][0][0]).toBe('foo')134+ expect(router.match('POST', '/reg-exp/router')[0][0][0]).toBe('bar')135+ })136+137 describe('Capture Group', () => {138 describe('Complex capturing group', () => {139 it('GET request', () => {140 const router = new RegExpRouter<string>()133- router.add('GET', '/foo/:capture{ba(r|z)}', 'ok')141 expect(() => {135- router.match('GET', '/foo/bar')142+ router.add('GET', '/foo/:capture{ba(r|z)}', 'ok')143 }).toThrowError(UnsupportedPathError)144 })145 })146 })147 })148+149+ describe('Wildcard after label', () => {150+ it('Should be able to add a tail wildcard after a label', () => {151+ const router = new RegExpRouter<string>()152+ router.add('GET', '/api/:x', 'label')153+ router.add('GET', '/api/*', 'wildcard')154+155+ const [res] = router.match('GET', '/api/foo')156+ expect(res.length).toBe(2)157+ expect(res[0][0]).toBe('label')158+ expect(res[1][0]).toBe('wildcard')159+ })160+161+ it('Should prioritize the only wildcard over the tail wildcard regardless of the order', () => {162+ for (const paths of [163+ ['/a*', '/a/*'],164+ ['/a/*', '/a*'],165+ ]) {166+ const router = new RegExpRouter<string>()167+ for (const path of paths) {168+ router.add('GET', path, path)169+ }170+ const [res] = router.match('GET', '/a')171+ expect(res[0][0]).toBe('/a*')172+ }173+ })174+ })175+176+ describe('Single character regexp pattern', () => {177+ it('Should capture a param even if a static path created the node first', () => {178+ const router = new RegExpRouter<string>()179+ router.add('GET', '/a/c', 'static')180+ router.add('GET', '/:x{a}/b', 'pattern')181+182+ const [res, stash] = router.match('GET', '/a/b')183+ expect(res.length).toBe(1)184+ expect(res[0][0]).toBe('pattern')185+ expect((stash as ParamStash)[(res[0][1] as ParamIndexMap)['x']]).toBe('a')186+ })187+188+ it('Should throw an error when a pattern terminal conflicts with a static terminal', () => {189+ for (const paths of [190+ ['/a', '/:x{a}'],191+ ['/:x{a}', '/a'],192+ ]) {193+ const router = new RegExpRouter<string>()194+ router.add('GET', paths[0], paths[0])195+ expect(() => {196+ router.add('GET', paths[1], paths[1])197+ }).toThrowError(UnsupportedPathError)198+ }199+ })200+201+ it('Should coexist with static paths regardless of the order', () => {202+ for (const paths of [203+ ['/foo/bar', '/:y{b}'],204+ ['/:y{b}', '/foo/bar'],205+ ]) {206+ const router = new RegExpRouter<string>()207+ for (const path of paths) {208+ router.add('GET', path, path)209+ }210+ expect(router.match('GET', '/foo/bar')[0][0][0]).toBe('/foo/bar')211+ expect(router.match('GET', '/b')[0][0][0]).toBe('/:y{b}')212+ }213+ })214+215+ it('Should coexist with dynamic paths regardless of the order', () => {216+ for (const paths of [217+ ['/foo/:p', '/:x{a}'],218+ ['/:x{a}', '/foo/:p'],219+ ]) {220+ const router = new RegExpRouter<string>()221+ for (const path of paths) {222+ router.add('GET', path, path)223+ }224+ expect(router.match('GET', '/a')[0][0][0]).toBe('/:x{a}')225+ expect(router.match('GET', '/foo/v')[0][0][0]).toBe('/foo/:p')226+ }227+ })228+229+ it('Should throw an error for a single meta character pattern', () => {230+ const router = new RegExpRouter<string>()231+ expect(() => {232+ router.add('GET', '/:x{.}', 'meta')233+ }).toThrowError(UnsupportedPathError)234+ })235+ })236+237+ describe('Capture a param of a label node created by a middle wildcard', () => {238+ it('Should capture the param', () => {239+ const router = new RegExpRouter<string>()240+ router.add('GET', '/w/*/x', 'wildcard')241+ router.add('GET', '/w/:id/y', 'label')242+243+ const [res, stash] = router.match('GET', '/w/123/y')244+ expect(res.length).toBe(1)245+ expect(res[0][0]).toBe('label')246+ expect((stash as ParamStash)[(res[0][1] as ParamIndexMap)['id']]).toBe('123')247+ })248+ })249+250+ describe('Static path including a colon in the middle', () => {251+ it('Should be treated as a static path', () => {252+ for (const paths of [253+ ['/v1/name:activate', '/v1/name2'],254+ ['/v1/name2', '/v1/name:activate'],255+ ]) {256+ const router = new RegExpRouter<string>()257+ for (const path of paths) {258+ router.add('GET', path, path)259+ }260+ expect(router.match('GET', '/v1/name:activate')[0][0][0]).toBe('/v1/name:activate')261+ expect(router.match('GET', '/v1/name2')[0][0][0]).toBe('/v1/name2')262+ }263+ })264+ })265 })modified:src/router/reg-exp-router/router.ts+71 added-112 removed
6 unmodified lines7 import { checkOptionalParameter } from '../../utils/url'8 import type { HandlerData, StaticMap, Matcher, MatcherMap } from './matcher'9 import { match, emptyParam } from './matcher'10 import { PATH_ERROR } from './node'11-import type { ParamAssocArray } from './node'11 import { Trie } from './trie'12 13 type HandlerWithMetadata<T> = [T, number] // [handler, paramCount]14 16-// eslint-disable-next-line @typescript-eslint/no-explicit-any17-const nullMatcher: Matcher<any> = [/^$/, [], Object.create(null)]18-15 let wildcardRegExpCache: Record<string, RegExp> = Object.create(null)16 function buildWildcardRegExp(path: string): RegExp {17 return (wildcardRegExpCache[path] ??= new RegExp(18 path === '*'7 unmodified lines26 function clearWildcardRegExpCache() {27 wildcardRegExpCache = Object.create(null)28 }29 34-function buildMatcherFromPreprocessedRoutes<T>(35- routes: [string, HandlerWithMetadata<T>[]][]36-): Matcher<T> {37- const trie = new Trie()38- const handlerData: HandlerData<T>[] = []39- if (routes.length === 0) {40- return nullMatcher41- }42-43- const routesWithStaticPathFlag = routes44- .map(45- (route) => [!/\*|\/:/.test(route[0]), ...route] as [boolean, string, HandlerWithMetadata<T>[]]46- )47- .sort(([isStaticA, pathA], [isStaticB, pathB]) =>48- isStaticA ? 1 : isStaticB ? -1 : pathA.length - pathB.length49- )50-51- const staticMap: StaticMap<T> = Object.create(null)52- for (let i = 0, j = -1, len = routesWithStaticPathFlag.length; i < len; i++) {53- const [pathErrorCheckOnly, path, handlers] = routesWithStaticPathFlag[i]54- if (pathErrorCheckOnly) {55- staticMap[path] = [handlers.map(([h]) => [h, Object.create(null)]), emptyParam]56- } else {57- j++58- }59-60- let paramAssoc: ParamAssocArray61- try {62- paramAssoc = trie.insert(path, j, pathErrorCheckOnly)63- } catch (e) {64- throw e === PATH_ERROR ? new UnsupportedPathError(path) : e65- }66-67- if (pathErrorCheckOnly) {68- continue69- }70-71- handlerData[j] = handlers.map(([h, paramCount]) => {72- const paramIndexMap: ParamIndexMap = Object.create(null)73- paramCount -= 174- for (; paramCount >= 0; paramCount--) {75- const [key, value] = paramAssoc[paramCount]76- paramIndexMap[key] = value77- }78- return [h, paramIndexMap]79- })80- }81-82- const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp()83- for (let i = 0, len = handlerData.length; i < len; i++) {84- for (let j = 0, len = handlerData[i].length; j < len; j++) {85- const map = handlerData[i][j]?.[1]86- if (!map) {87- continue88- }89- const keys = Object.keys(map)90- for (let k = 0, len = keys.length; k < len; k++) {91- map[keys[k]] = paramReplacementMap[map[keys[k]]]92- }93- }94- }95-96- const handlerMap: HandlerData<T>[] = []97- // using `in` because indexReplacementMap is a sparse array98- for (const i in indexReplacementMap) {99- handlerMap[i] = handlerData[indexReplacementMap[i]]100- }101-102- return [regexp, handlerMap, staticMap] as Matcher<T>103-}104-30 function findMiddleware<T>(31 middleware: Record<string, T[]> | undefined,32 path: string33 ): T[] | undefined {13 unmodified lines47 export class RegExpRouter<T> implements Router<T> {48 name: string = 'RegExpRouter'49 #middleware?: Record<string, Record<string, HandlerWithMetadata<T>[]>>50 #routes?: Record<string, Record<string, HandlerWithMetadata<T>[]>>51+ #tries?: Record<string, Trie>52 53 constructor() {54 this.#middleware = { [METHOD_NAME_ALL]: Object.create(null) }55 this.#routes = { [METHOD_NAME_ALL]: Object.create(null) }56+ this.#tries = { [METHOD_NAME_ALL]: new Trie() }57 }58 59+ #insertPath(method: string, path: string) {60+ try {61+ this.#tries![method].insert(path, !/\*|\/:/.test(path))62+ } catch (e) {63+ throw e === PATH_ERROR ? new UnsupportedPathError(path) : e64+ }65+ }66+67 add(method: string, path: string, handler: T) {68 const middleware = this.#middleware69 const routes = this.#routes70 1 unmodified line72 throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT)73 }74 75 if (!middleware[method]) {76+ this.#tries![method] = new Trie()77 ;[middleware, routes].forEach((handlerMap) => {78 handlerMap[method] = Object.create(null)79 Object.keys(handlerMap[METHOD_NAME_ALL]).forEach((p) => {80 handlerMap[method][p] = [...handlerMap[METHOD_NAME_ALL][p]]81+ this.#insertPath(method, p)82 })83 })84 }85 4 unmodified lines90 const paramCount = (path.match(/\/:/g) || []).length91 92 if (/\*$/.test(path)) {93 const re = buildWildcardRegExp(path)157- if (method === METHOD_NAME_ALL) {158- Object.keys(middleware).forEach((m) => {159- middleware[m][path] ||=94+ Object.keys(middleware).forEach((m) => {95+ if ((method === METHOD_NAME_ALL || method === m) && !middleware[m][path]) {96+ this.#insertPath(m, path)97+ middleware[m][path] =98 findMiddleware(middleware[m], path) ||99 findMiddleware(middleware[METHOD_NAME_ALL], path) ||100 []163- })164- } else {165- middleware[method][path] ||=166- findMiddleware(middleware[method], path) ||167- findMiddleware(middleware[METHOD_NAME_ALL], path) ||168- []169- }101+ }102+ })103 Object.keys(middleware).forEach((m) => {104 if (method === METHOD_NAME_ALL || method === m) {105 Object.keys(middleware[m]).forEach((p) => {106 re.test(p) && middleware[m][p].push([handler, paramCount])17 unmodified lines124 const path = paths[i]125 126 Object.keys(routes).forEach((m) => {127 if (method === METHOD_NAME_ALL || method === m) {128+ if (!routes[m][path]) {129+ this.#insertPath(m, path)195- routes[m][path] ||= [196- ...(findMiddleware(middleware[m], path) ||197- findMiddleware(middleware[METHOD_NAME_ALL], path) ||198- []),199- ]130+ routes[m][path] = [131+ ...(findMiddleware(middleware[m], path) ||132+ findMiddleware(middleware[METHOD_NAME_ALL], path) ||133+ []),134+ ]135+ }136 routes[m][path].push([handler, paramCount - len + i + 1])137 }138 })139 }10 unmodified lines150 matchers[method] ||= this.#buildMatcher(method)151 })152 153 // Release cache218- this.#middleware = this.#routes = undefined154+ this.#middleware = this.#routes = this.#tries = undefined155 clearWildcardRegExpCache()156 157 return matchers158 }159 224- #buildMatcher(method: string): Matcher<T> | null {225- const routes: [string, HandlerWithMetadata<T>[]][] = []160+ #buildMatcher(method: string): Matcher<T> {161+ const middleware = this.#middleware![method]162+ const routes = this.#routes![method]163 227- let hasOwnRoute = method === METHOD_NAME_ALL164+ const trie = this.#tries![method]165+ const staticMap: StaticMap<T> = Object.create(null)166+ const handlerData: HandlerData<T>[] = []167 229- ;[this.#middleware!, this.#routes!].forEach((r) => {230- const ownRoute = r[method]231- ? Object.keys(r[method]).map((path) => [path, r[method][path]])232- : []233- if (ownRoute.length !== 0) {234- hasOwnRoute ||= true235- routes.push(...(ownRoute as [string, HandlerWithMetadata<T>[]][]))236- } else if (method !== METHOD_NAME_ALL) {237- routes.push(238- ...(Object.keys(r[METHOD_NAME_ALL]).map((path) => [path, r[METHOD_NAME_ALL][path]]) as [239- string,240- HandlerWithMetadata<T>[],241- ][])242- )168+ ;[middleware, routes].forEach((r) => {169+ for (const path in r) {170+ const handlers = r[path]171+ const pathData = trie.paths[path]172+ if (!pathData) {173+ staticMap[path] = [handlers.map(([h]) => [h, Object.create(null)]), emptyParam]174+ continue175+ }176+ const paramAssoc = pathData[1]177+ handlerData[pathData[0]] = handlers.map(([h, paramCount]) => {178+ const paramIndexMap: ParamIndexMap = Object.create(null)179+ paramCount -= 1180+ for (; paramCount >= 0; paramCount--) {181+ const [key, value] = paramAssoc[paramCount]182+ paramIndexMap[key] = value183+ }184+ return [h, paramIndexMap]185+ })186 }187 })188 246- if (!hasOwnRoute) {247- return null248- } else {249- return buildMatcherFromPreprocessedRoutes(routes)189+ const [regexp, indexReplacementMap, paramReplacementMap] = trie.buildRegExp()190+ for (let i = 0, len = handlerData.length; i < len; i++) {191+ for (let j = 0, len = handlerData[i].length; j < len; j++) {192+ const map = handlerData[i][j]?.[1]193+ if (!map) {194+ continue195+ }196+ const keys = Object.keys(map)197+ for (let k = 0, len = keys.length; k < len; k++) {198+ map[keys[k]] = paramReplacementMap[map[keys[k]]]199+ }200+ }201 }202+203+ const handlerMap: HandlerData<T>[] = []204+ // using `in` because indexReplacementMap is a sparse array205+ for (const i in indexReplacementMap) {206+ handlerMap[i] = handlerData[indexReplacementMap[i]]207+ }208+209+ return [regexp, handlerMap, staticMap] as Matcher<T>210 }211 }modified:src/router/reg-exp-router/trie.ts+15 added-6 removed
4 unmodified lines5 6 export class Trie {7 #context: Context = { varIndex: 0 }8 #root: Node = new Node()9+ #index: number = 010+ // dynamic path -> [handler index, param assoc]; static paths are not registered11+ paths: Record<string, [number, ParamAssocArray]> = Object.create(null)12 10- insert(path: string, index: number, pathErrorCheckOnly: boolean): ParamAssocArray {13+ insert(path: string, isStatic: boolean): void {14+ if (isStatic) {15+ // a static path has no pattern; every character is a literal token16+ this.#root.insert(path.split(''), 0, [], this.#context, true)17+ return18+ }19+20 const paramAssoc: ParamAssocArray = []21 22 const groups: [string, string][] = [] // [mark, original string]23+ let markedPath = path24 for (let i = 0; ; ) {25 let replaced = false16- path = path.replace(/\{[^}]+\}/g, (m) => {26+ markedPath = markedPath.replace(/\{[^}]+\}/g, (m) => {27 const mark = `@\\${i}`28 groups[i] = [mark, m]29 i++30 replaced = true8 unmodified lines39 * - pattern (:label, :label{0-9]+}, ...)40 * - /* wildcard41 * - character42 */33- const tokens = path.match(/(?::[^\/]+)|(?:\/\*$)|./g) || []43+ const tokens = markedPath.match(/(?::[^\/]+)|(?:\/\*$)|./g) || []44 for (let i = groups.length - 1; i >= 0; i--) {45 const [mark] = groups[i]46 for (let j = tokens.length - 1; j >= 0; j--) {47 if (tokens[j].indexOf(mark) !== -1) {2 unmodified lines50 }51 }52 }53 44- this.#root.insert(tokens, index, paramAssoc, this.#context, pathErrorCheckOnly)45-46- return paramAssoc54+ this.#root.insert(tokens, this.#index, paramAssoc, this.#context, false)55+ this.paths[path] = [this.#index++, paramAssoc]56 }57 58 buildRegExp(): [RegExp, ReplacementMap, ReplacementMap] {59 let regexp = this.#root.buildRegExpStr()24 unmodified linesmodified:src/utils/cookie.ts+2 added-3 removed
1 unmodified line2 * @module3 * Cookie utility.4 */5 6-import { decodeURIComponent_, tryDecode } from './url'6+import { tryDecodeURIComponent } from './url'7 8 export type Cookie = Record<string, string>9 export type SignedCookie = Record<string, string | false>10 121 unmodified lines132 if (cookieValue.startsWith('"') && cookieValue.endsWith('"')) {133 cookieValue = cookieValue.slice(1, -1)134 }135 if (validCookieValueRegEx.test(cookieValue)) {136- parsedCookie[cookieName] =137- cookieValue.indexOf('%') !== -1 ? tryDecode(cookieValue, decodeURIComponent_) : cookieValue136+ parsedCookie[cookieName] = tryDecodeURIComponent(cookieValue)137 if (name) {138 // Fast-path: return only the demanded-key immediately. Other keys are not needed.139 break140 }140 unmodified linesmodified:src/utils/headers.ts+23 added-1 removed
15 unmodified lines16 | 'Accept-Features'17 | 'Accept-Language'18 | 'Accept-Patch'19 | 'Accept-Post'20+ | 'Accept-Query'21 | 'Accept-Ranges'22 | 'Accept-Signature'23 | 'Access-Control'24 | 'Access-Control-Allow-Credentials'3 unmodified lines28 | 'Access-Control-Expose-Headers'29 | 'Access-Control-Max-Age'30 | 'Access-Control-Request-Headers'31 | 'Access-Control-Request-Method'32+ | 'Activate-Storage-Access'33 | 'Age'34 | 'Allow'35 | 'ALPN'36 | 'Alt-Svc'10 unmodified lines47 | 'C-Opt'48 | 'C-PEP'49 | 'C-PEP-Info'50 | 'Cache-Control'51+ | 'Cache-Group-Invalidation'52+ | 'Cache-Groups'53 | 'Cache-Status'54 | 'Cal-Managed-ID'55 | 'CalDAV-Timezones'56 | 'Capsule-Protocol'46 unmodified lines103 | 'Deprecation'104 | 'Depth'105 | 'Derived-From'106 | 'Destination'107+ | 'Detached-JWS'108 | 'Differential-ID'109 | 'Dictionary-ID'110 | 'Digest'111 | 'DPoP'19 unmodified lines131 | 'If-Schedule-Tag-Match'132 | 'If-Unmodified-Since'133 | 'IM'134 | 'Include-Referred-Token-Binding-ID'135+ | 'Incremental'136 | 'Isolation'137 | 'Keep-Alive'138 | 'Label'139 | 'Last-Event-ID'65 unmodified lines205 | 'Retry-After'206 | 'Safe'207 | 'Schedule-Reply'208 | 'Schedule-Tag'209+ | 'Sec-Fetch-Dest'210+ | 'Sec-Fetch-Mode'211+ | 'Sec-Fetch-Site'212+ | 'Sec-Fetch-Storage-Access'213+ | 'Sec-Fetch-User'214 | 'Sec-GPC'215 | 'Sec-Purpose'216 | 'Sec-Token-Binding'217 | 'Sec-WebSocket-Accept'5 unmodified lines223 | 'Server'224 | 'Server-Timing'225 | 'Set-Cookie'226 | 'Set-Cookie2'227+ | 'Set-Txn'228 | 'SetProfile'229 | 'Signature'230 | 'Signature-Input'231 | 'SLUG'12 unmodified lines244 | 'Tracestate'245 | 'Trailer'246 | 'Transfer-Encoding'247 | 'TTL'248+ | 'Unencoded-Digest'249 | 'Upgrade'250 | 'Urgency'251 | 'URI'252 | 'Use-As-Dictionary'3 unmodified lines256 | 'Via'257 | 'Want-Content-Digest'258 | 'Want-Digest'259 | 'Want-Repr-Digest'260+ | 'Want-Unencoded-Digest'261 | 'Warning'262 | 'WWW-Authenticate'263 | 'X-Content-Type-Options'264 | 'X-Frame-Options'265 266 export type ResponseHeader =267+ | 'Accept-Query'268 | 'Access-Control-Allow-Credentials'269 | 'Access-Control-Allow-Headers'270 | 'Access-Control-Allow-Methods'271 | 'Access-Control-Allow-Origin'272 | 'Access-Control-Expose-Headers'273 | 'Access-Control-Max-Age'274+ | 'Activate-Storage-Access'275 | 'Age'276 | 'Allow'277 | 'Cache-Control'278+ | 'Cache-Group-Invalidation'279+ | 'Cache-Groups'280 | 'Clear-Site-Data'281 | 'Content-Disposition'282 | 'Content-Encoding'283 | 'Content-Language'9 unmodified lines293 | 'Cross-Origin-Resource-Policy'294 | 'Date'295 | 'ETag'296 | 'Expires'297+ | 'Incremental'298 | 'Last-Modified'299 | 'Location'300 | 'Permissions-Policy'301 | 'Pragma'20 unmodified lines322 | 'Server'323 | 'Server-Timing'324 | 'Service-Worker-Navigation-Preload'325 | 'Set-Cookie'326+ | 'Set-Txn'327 | 'Strict-Transport-Security'328 | 'Timing-Allow-Origin'329 | 'Trailer'330 | 'Transfer-Encoding'331+ | 'Unencoded-Digest'332 | 'Upgrade'333 | 'Vary'313- | 'WWW-Authenticate'334+ | 'Want-Unencoded-Digest'335 | 'Warning'336+ | 'WWW-Authenticate'337 | 'X-Content-Type-Options'338 | 'X-DNS-Prefetch-Control'339 | 'X-Frame-Options'340 | 'X-Permitted-Cross-Domain-Policies'15 unmodified linesmodified:src/utils/url.ts+6 added-6 removed
203 unmodified lines204 205 return results.filter((v, i, a) => a.indexOf(v) === i)206 }207 208+export const tryDecodeURIComponent = (str: string): string =>209+ str.indexOf('%') !== -1 ? tryDecode(str, decodeURIComponent_) : str210+211 // Optimized209-const _decodeURI = (value: string) => {210- if (!/[%+]/.test(value)) {211- return value212- }212+const _decodeURI = (value: string): string => {213 if (value.indexOf('+') !== -1) {214 value = value.replace(/\+/g, ' ')215 }216- return value.indexOf('%') !== -1 ? tryDecode(value, decodeURIComponent_) : value216+ return tryDecodeURIComponent(value)217 }218 219 const _getQueryParam = (220 url: string,1 unmodified line222 multiple?: boolean223 ): string | undefined | Record<string, string> | string[] | Record<string, string[]> => {224 let encoded225 226- if (!multiple && key && !/[%+]/.test(key)) {226+ if (!multiple && key && key.indexOf('%') === -1 && key.indexOf('+') === -1) {227 // optimized for unencoded key228 229 let keyIndex = url.indexOf('?', 8)230 if (keyIndex === -1) {89 unmodified linesmodified:src/context.ts+28 added-15 removed
604 unmodified lines605 data: Data | null,606 arg?: StatusCode | ResponseOrInit,607 headers?: HeaderRecord608 ): Response {609- const responseHeaders = this.#res610- ? new Headers(this.#res.headers)611- : (this.#preparedHeaders ?? new Headers())609+ let responseHeaders = this.#res ? new Headers(this.#res.headers) : this.#preparedHeaders610 613- if (typeof arg === 'object' && 'headers' in arg) {614- const argHeaders = arg.headers instanceof Headers ? arg.headers : new Headers(arg.headers)615- for (const [key, value] of argHeaders) {616- if (key.toLowerCase() === 'set-cookie') {611+ if (typeof arg === 'object' && arg.headers) {612+ responseHeaders ??= new Headers()613+ for (const [key, value] of new Headers(arg.headers)) {614+ if (key === 'set-cookie') {615 responseHeaders.append(key, value)616 } else {617 responseHeaders.set(key, value)618 }619 }620 }621 622 if (headers) {625- for (const [k, v] of Object.entries(headers)) {626- if (typeof v === 'string') {627- responseHeaders.set(k, v)628- } else {629- responseHeaders.delete(k)630- for (const v2 of v) {631- responseHeaders.append(k, v2)623+ if (!responseHeaders) {624+ let count = 0625+ for (const k in headers) {626+ if (++count > 1 || typeof headers[k as keyof HeaderRecord] !== 'string') {627+ responseHeaders = new Headers()628+ break629 }630 }631 }632+ if (responseHeaders) {633+ for (const k in headers) {634+ const v = headers[k as keyof HeaderRecord]635+ if (typeof v === 'string') {636+ responseHeaders.set(k, v)637+ } else {638+ responseHeaders.delete(k)639+ for (const v2 of v) {640+ responseHeaders.append(k, v2)641+ }642+ }643+ }644+ }645 }646 647 const status = typeof arg === 'number' ? arg : (arg?.status ?? this.#status)638- return createResponseInstance(data, { status, headers: responseHeaders })648+ return createResponseInstance(data, {649+ status,650+ headers: responseHeaders ?? (headers as Record<string, string> | undefined),651+ })652 }653 654 newResponse: NewResponse = (...args) => this.#newResponse(...(args as Parameters<NewResponse>))655 138 unmodified linesmodified:src/hono-base.ts+4 added-3 removed
105 unmodified lines106 put!: HandlerInterface<E, 'put', S, BasePath, CurrentPath>107 delete!: HandlerInterface<E, 'delete', S, BasePath, CurrentPath>108 options!: HandlerInterface<E, 'options', S, BasePath, CurrentPath>109 patch!: HandlerInterface<E, 'patch', S, BasePath, CurrentPath>110+ query!: HandlerInterface<E, 'query', S, BasePath, CurrentPath>111 all!: HandlerInterface<E, 'all', S, BasePath, CurrentPath>112 on: OnHandlerInterface<E, S, BasePath>113 use: MiddlewareHandlerInterface<E, S, BasePath>114 356 unmodified lines471 *472 * @see {@link https://hono.dev/docs/api/hono#fetch}473 *474 * @param {Request} request - request Object of request474- * @param {Env} Env - env Object475- * @param {ExecutionContext} - context of execution475+ * @param {Env} env - env Object476+ * @param {ExecutionContext} executionCtx - context of execution477 * @returns {Response | Promise<Response>} response of request478 *479 */480 fetch: (481 request: Request,481- Env?: E['Bindings'] | {},482+ env?: E['Bindings'] | {},483 executionCtx?: ExecutionContext484 ) => Response | Promise<Response> = (request, ...rest) => {485 return this.#dispatch(request, rest[1], rest[0], request.method)486 }60 unmodified linesmodified:src/hono.test.ts+41 added
2077 unmodified lines2078 expect(res.status).toBe(404)2079 })2080 })2081 2082+describe('Using QUERY with `app.query` and `app.on`', () => {2083+ it('Should handle QUERY method with app.query()', async () => {2084+ const app = new Hono()2085+2086+ app.query('/query', (c) => c.text('Accepted', 202))2087+2088+ const req = new Request('http://localhost/query', {2089+ method: 'QUERY',2090+ })2091+ const res = await app.request(req)2092+ expect(res.status).toBe(202)2093+ expect(await res.text()).toBe('Accepted')2094+ })2095+2096+ it('Should handle QUERY method with RegExpRouter', async () => {2097+ const app = new Hono({ router: new RegExpRouter() })2098+2099+ app.on('QUERY', '/query', (c) => c.text('Accepted', 202))2100+2101+ const req = new Request('http://localhost/query', {2102+ method: 'QUERY',2103+ })2104+ const res = await app.request(req)2105+ expect(res.status).toBe(202)2106+ expect(await res.text()).toBe('Accepted')2107+ })2108+2109+ it('Should handle QUERY method with TrieRouter', async () => {2110+ const app = new Hono({ router: new TrieRouter() })2111+2112+ app.on('QUERY', '/query', (c) => c.text('Accepted', 202))2113+2114+ const req = new Request('http://localhost/query', {2115+ method: 'QUERY',2116+ })2117+ const res = await app.request(req)2118+ expect(res.status).toBe(202)2119+ expect(await res.text()).toBe('Accepted')2120+ })2121+})2122+2123 describe('Multiple paths with one handler', () => {2124 const app = new Hono()2125 2126 const paths = ['/hello', '/ja/hello', '/en/hello']1674 unmodified linesmodified:src/request.ts+7 added-11 removed
13 unmodified lines14 import { parseBody } from './utils/body'15 import type { BodyData, ParseBodyOptions } from './utils/body'16 import type { CustomHeader, RequestHeader } from './utils/headers'17 import type { Simplify, UnionToIntersection } from './utils/types'18-import { decodeURIComponent_, getQueryParam, getQueryParams, tryDecode } from './utils/url'18+import { getQueryParam, getQueryParams, tryDecodeURIComponent } from './utils/url'19 20 type Body = {21 json: any22 text: string7 unmodified lines30 type RequiredRequestInit = Required<Omit<RequestInit, OptionalRequestInitProperties>> & {31 [Key in OptionalRequestInitProperties]?: RequestInit[Key]32 }33 34-const tryDecodeURIComponent = (str: string) => tryDecode(str, decodeURIComponent_)35-34 export class HonoRequest<P extends string = '/', I extends Input['out'] = {}> {35 /**36 * `.raw` can get the raw Request object.37 *9 unmodified lines47 * ```48 */49 raw: Request50 53- #validatedData: { [K in keyof ValidationTargets]?: {} } // Short name of validatedData51+ #validatedData: { [K in keyof ValidationTargets]?: {} } | undefined // Short name of validatedData52 #matchResult: Result<[unknown, RouterRoute]>53 routeIndex: number = 054 /**55 * `.path` can get the pathname of the request.17 unmodified lines73 ) {74 this.raw = request75 this.path = path76 this.#matchResult = matchResult79- this.#validatedData = {}77 }78 79 /**80 * `.req.param()` gets the path parameters.21 unmodified lines102 103 #getDecodedParam(key: string): string | undefined {104 const paramKey = this.#matchResult[0][this.routeIndex][1][key]105 const param = this.#getParamValue(paramKey)109- return param && /\%/.test(param) ? tryDecodeURIComponent(param) : param106+ return param && tryDecodeURIComponent(param)107 }108 109 #getAllDecodedParams(): Record<string, string> {110 const decoded: Record<string, string> = {}1 unmodified line112 const keys = Object.keys(this.#matchResult[0][this.routeIndex][1])113 for (const key of keys) {114 const value = this.#getParamValue(this.#matchResult[0][this.routeIndex][1][key])115 if (value !== undefined) {119- decoded[key] = /\%/.test(value) ? tryDecodeURIComponent(value) : value116+ decoded[key] = tryDecodeURIComponent(value)117 }118 }119 120 return decoded100 unmodified lines221 if (cachedBody) {222 return cachedBody223 }224 228- const anyCachedKey = Object.keys(bodyCache)[0]229- if (anyCachedKey) {225+ for (const anyCachedKey in bodyCache) {226 return (bodyCache[anyCachedKey as keyof Body] as Promise<BodyInit>).then((body) => {227 if (anyCachedKey === 'json') {228 body = JSON.stringify(body)229 }102 unmodified lines332 * @param target - The target of the validation.333 * @param data - The validated data to add.334 */335 addValidatedData(target: keyof ValidationTargets, data: {}) {340- this.#validatedData[target] = data336+ ;(this.#validatedData ??= {})[target] = data337 }338 339 /**340 * Gets validated data from the request.4 unmodified lines345 * @see https://hono.dev/docs/api/request#valid346 */347 valid<T extends keyof I & keyof ValidationTargets>(target: T): InputToDataByTarget<I, T>348 valid(target: keyof ValidationTargets) {353- return this.#validatedData[target] as unknown349+ return this.#validatedData?.[target] as unknown350 }351 352 /**353 * `.url()` can get the request url strings.156 unmodified linesmodified:src/router.ts+1 added-1 removed
12 unmodified lines13 export const METHOD_NAME_ALL_LOWERCASE = 'all' as const14 /**15 * Array of supported HTTP methods.16 */17-export const METHODS = ['get', 'post', 'put', 'delete', 'options', 'patch'] as const17+export const METHODS = ['get', 'post', 'put', 'delete', 'options', 'patch', 'query'] as const18 /**19 * Error message indicating that a route cannot be added because the matcher is already built.20 */21 export const MESSAGE_MATCHER_IS_ALREADY_BUILT =82 unmodified linesmodified:jsr.json+1 added
43 unmodified lines44 "./jwk": "./src/middleware/jwk/jwk.ts",45 "./timeout": "./src/middleware/timeout/index.ts",46 "./timing": "./src/middleware/timing/timing.ts",47 "./logger": "./src/middleware/logger/index.ts",48+ "./method-not-allowed": "./src/middleware/method-not-allowed/index.ts",49 "./method-override": "./src/middleware/method-override/index.ts",50 "./powered-by": "./src/middleware/powered-by/index.ts",51 "./pretty-json": "./src/middleware/pretty-json/index.ts",52 "./request-id": "./src/middleware/request-id/request-id.ts",60 unmodified linesmodified:package.json+8 added
229 unmodified lines230 "types": "./dist/types/middleware/logger/index.d.ts",231 "import": "./dist/middleware/logger/index.js",232 "require": "./dist/cjs/middleware/logger/index.js"233 },234+ "./method-not-allowed": {235+ "types": "./dist/types/middleware/method-not-allowed/index.d.ts",236+ "import": "./dist/middleware/method-not-allowed/index.js",237+ "require": "./dist/cjs/middleware/method-not-allowed/index.js"238+ },239 "./method-override": {240 "types": "./dist/types/middleware/method-override/index.d.ts",241 "import": "./dist/middleware/method-override/index.js",242 "require": "./dist/cjs/middleware/method-override/index.js"289 unmodified lines532 ],533 "logger": [534 "./dist/types/middleware/logger"535 ],536+ "method-not-allowed": [537+ "./dist/types/middleware/method-not-allowed"538+ ],539 "method-override": [540 "./dist/types/middleware/method-override"541 ],542 "powered-by": [164 unmodified lines