Skip to content
Myr

Merge pull request #1774 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 GitHub · parents 0497097, 22b5f53 · Browse files · 78 files+5433 added−878 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

78 files+5433 added−878 removed

  • tests:+1678 added−113 removed
  • other:+3755 added−765 removed

78 files+5433 added−878 removed

added:deno_dist/helper/dev/index.ts+62 added
modified:deno_dist/helper/factory/index.ts+272 added-4 removed
modified:deno_dist/helper/html/index.ts+8 added-3 removed
1import { escapeToBuffer, stringBufferToString } from '../../utils/html.ts'2import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../../utils/html.ts'2import type {3 StringBuffer,4 HtmlEscaped,5 HtmlEscapedString,6 HtmlEscapedCallback,7} from '../../utils/html.ts'84export const raw = (value: unknown, promises?: Promise<string>[]): HtmlEscapedString => {9export const raw = (value: unknown, callbacks?: HtmlEscapedCallback[]): HtmlEscapedString => {10 const escapedString = new String(value) as HtmlEscapedString11 escapedString.isEscaped = true7 escapedString.promises = promises12 escapedString.callbacks = callbacks1314 return escapedString15}16
37 unmodified lines
added:deno_dist/jsx/components.ts+163 added
1import { raw } from '../helper/html/index.ts'2import type { HtmlEscapedString } from '../utils/html.ts'3import type { FC, Child } from './index.ts'45let errorBoundaryCounter = 067export const childrenToString = async (children: Child[]): Promise<HtmlEscapedString[]> => {8 try {9 return children.map((c) => c.toString()) as HtmlEscapedString[]10 } catch (e) {11 if (e instanceof Promise) {12 await e13 return childrenToString(children)14 } else {15 throw e16 }17 }18}1920type ErrorHandler = (error: Error) => void21type FallbackRender = (error: Error) => Child2223/**24 * @experimental25 * `ErrorBoundary` is an experimental feature.26 * The API might be changed.27 */28export const ErrorBoundary: FC<{29 fallback?: Child30 fallbackRender?: FallbackRender31 onError?: ErrorHandler32}> = async ({ children, fallback, fallbackRender, onError }) => {33 if (!children) {34 return raw('')35 }3637 if (!Array.isArray(children)) {38 children = [children]39 }4041 const fallbackRes = (error: Error): HtmlEscapedString => {42 onError?.(error)43 return (fallback || fallbackRender?.(error) || '').toString() as HtmlEscapedString44 }45 let resArray: HtmlEscapedString[] | Promise<HtmlEscapedString[]>[] = []46 try {47 resArray = children.map((c) => c.toString()) as HtmlEscapedString[]48 } catch (e) {49 if (e instanceof Promise) {50 resArray = [51 e.then(() => childrenToString(children as Child[])).catch((e) => fallbackRes(e)),52 ] as Promise<HtmlEscapedString[]>[]53 } else {54 resArray = [fallbackRes(e as Error)]55 }56 }5758 if (resArray.some((res) => (res as {}) instanceof Promise)) {59 const index = errorBoundaryCounter++60 const replaceRe = RegExp(`(<template id="E:${index}"></template>.*?)(.*?)(<!--E:${index}-->)`)61 const caught = false62 const catchCallback = ({ error, buffer }: { error: Error; buffer?: [string] }) => {63 if (caught) {64 return ''65 }6667 const fallbackResString = fallbackRes(error)68 if (buffer) {69 buffer[0] = buffer[0].replace(replaceRe, fallbackResString)70 }71 return buffer72 ? ''73 : `<template>${fallbackResString}</template><script>74((d,c,n) => {75c=d.currentScript.previousSibling76d=d.getElementById('E:${index}')77if(!d)return78do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='E:${index}')79d.replaceWith(c.content)80})(document)81</script>`82 }83 return raw(`<template id="E:${index}"></template><!--E:${index}-->`, [84 ({ buffer }) => {85 return Promise.all(resArray)86 .then((htmlArray) => {87 htmlArray = htmlArray.flat()88 const content = htmlArray.join('')89 const html = buffer90 ? ''91 : `<template>${content}</template><script>92((d,c) => {93c=d.currentScript.previousSibling94d=d.getElementById('E:${index}')95if(!d)return96d.parentElement.insertBefore(c.content,d.nextSibling)97})(document)98</script>`99100 if (htmlArray.every((html) => !(html as HtmlEscapedString).callbacks?.length)) {101 if (buffer) {102 buffer[0] = buffer[0].replace(replaceRe, content)103 }104 return html105 }106107 if (buffer) {108 buffer[0] = buffer[0].replace(109 replaceRe,110 (_all, pre, _, post) => `${pre}${content}${post}`111 )112 }113114 const callbacks = htmlArray115 .map((html) => (html as HtmlEscapedString).callbacks || [])116 .flat()117118 let resolvedCount = 0119 const promises = callbacks.map(120 (c) =>121 ({ buffer }: { buffer: [string] }) =>122 c({ buffer })123 .then((content) => {124 resolvedCount++125126 if (buffer) {127 if (resolvedCount === callbacks.length) {128 buffer[0] = buffer[0].replace(replaceRe, (_all, _pre, content) => content)129 }130 buffer[0] += content131 return raw('', (content as HtmlEscapedString).callbacks)132 }133134 return raw(135 content +136 (resolvedCount !== callbacks.length137 ? ''138 : `<script>139((d,c,n) => {140d=d.getElementById('E:${index}')141if(!d)return142n=d.nextSibling143do{n=n.nextSibling}while(n.nodeType!=8||n.nodeValue!='E:${index}')144n.remove()145d.remove()146})(document)147</script>`),148 (content as HtmlEscapedString).callbacks149 )150 })151 .catch((error) => catchCallback({ error, buffer }))152 )153154 // eslint-disable-next-line @typescript-eslint/no-explicit-any155 return raw(html, promises as any)156 })157 .catch((error) => catchCallback({ error, buffer }))158 },159 ])160 } else {161 return raw(resArray.join(''))162 }163}
modified:deno_dist/jsx/index.ts+2 added-1 removed
1import { raw } from '../helper/html/index.ts'2import { escapeToBuffer, stringBufferToString } from '../utils/html.ts'3import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../utils/html.ts'4import type { IntrinsicElements as IntrinsicElementsDefined } from './intrinsic-elements.ts'5export { ErrorBoundary } from './components.ts'67// eslint-disable-next-line @typescript-eslint/no-explicit-any8type Props = Record<string, any>9
263 unmodified lines
273 if (string instanceof Promise) {274 return Promise.resolve().then<HtmlEscapedString>(async () => {275 values.push(props.value)276 const awaited = await string276 const promiseRes = raw(awaited, (awaited as HtmlEscapedString).promises)277 const promiseRes = raw(awaited, (awaited as HtmlEscapedString).callbacks)278 values.pop()279 return promiseRes280 })281 } else {
9 unmodified lines
modified:deno_dist/jsx/streaming.ts+32 added-29 removed
1import { raw } from '../helper/html/index.ts'2import type { HtmlEscapedString } from '../utils/html.ts'3import { childrenToString } from './components.ts'4import type { FC, Child } from './index.ts'56let suspenseCounter = 077async function childrenToString(children: Child[]): Promise<HtmlEscapedString[]> {8 try {9 return children.map((c) => c.toString()) as HtmlEscapedString[]10 } catch (e) {11 if (e instanceof Promise) {12 await e13 return childrenToString(children)14 } else {15 throw e16 }17 }18}198/**9 * @experimental10 * `Suspense` is an experimental feature.11 * The API might be changed.
22 unmodified lines
3435 if (resArray.some((res) => (res as {}) instanceof Promise)) {36 const index = suspenseCounter++37 return raw(`<template id="H:${index}"></template>${fallback.toString()}<!--/$-->`, [38 ({ buffer }) => {50 Promise.all(resArray).then((htmlArray) => {51 htmlArray = htmlArray.flat()52 const html = `<template>${htmlArray.join('')}</template><script>39 return Promise.all(resArray).then((htmlArray) => {40 htmlArray = htmlArray.flat()41 const content = htmlArray.join('')42 if (buffer) {43 buffer[0] = buffer[0].replace(44 new RegExp(`<template id="H:${index}"></template>.*?<!--/\\$-->`),45 content46 )47 }48 const html = buffer49 ? ''50 : `<template>${content}</template><script>51((d,c,n) => {52c=d.currentScript.previousSibling53d=d.getElementById('H:${index}')54if(!d)return55do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')56d.replaceWith(c.content)57})(document)58</script>`60 if (htmlArray.every((html) => !(html as HtmlEscapedString).promises?.length)) {61 return html62 }59 if (htmlArray.every((html) => !(html as HtmlEscapedString).callbacks?.length)) {60 return html61 }6264 return raw(html, htmlArray.map((html) => (html as HtmlEscapedString).promises || []).flat())65 }),63 return raw(64 html,65 htmlArray.map((html) => (html as HtmlEscapedString).callbacks || []).flat()66 )67 })68 },69 ])70 } else {71 return raw(resArray.join(''))72 }
13 unmodified lines
86 const resolved = str instanceof Promise ? await str : await str.toString()87 controller.enqueue(textEncoder.encode(resolved))8889 let resolvedCount = 087 const promises: Promise<void>[] = []90 const callbacks: Promise<void>[] = []91 const then = (promise: Promise<string>) => {89 promises.push(92 callbacks.push(93 promise94 .catch((err) => {95 console.trace(err)96 return ''97 })98 .then((res) => {96 if ((res as HtmlEscapedString).promises) {97 const resPromises = (res as HtmlEscapedString).promises || []98 resPromises.forEach(then)99 if ((res as HtmlEscapedString).callbacks) {100 const callbacks = (res as HtmlEscapedString).callbacks || []101 callbacks.map((c) => c({})).forEach(then)102 }103 resolvedCount++104 controller.enqueue(textEncoder.encode(res))105 })106 )107 }105 ;(resolved as HtmlEscapedString).promises?.map(then)106 while (resolvedCount !== promises.length) {107 await Promise.all(promises)108 ;(resolved as HtmlEscapedString).callbacks?.map((c) => c({})).forEach(then)109 while (resolvedCount !== callbacks.length) {110 await Promise.all(callbacks)111 }112113 controller.close()114 },
3 unmodified lines
modified:deno_dist/middleware/basic-auth/index.ts+1 added-1 removed
37 unmodified lines
38 options.realm = 'Secure Area'39 }40 users.unshift({ username: options.username, password: options.password })4142 return async (ctx, next) => {42 return async function basicAuth(ctx, next) {43 const requestUser = auth(ctx.req)44 if (requestUser) {45 for (const user of users) {46 const usernameEqual = await timingSafeEqual(
24 unmodified lines
modified:deno_dist/middleware/bearer-auth/index.ts+13 added-3 removed
4 unmodified lines
5const TOKEN_STRINGS = '[A-Za-z0-9._~+/-]+=*'6const PREFIX = 'Bearer'78export const bearerAuth = (options: {9 token: string9 token: string | string[]10 realm?: string11 prefix?: string12 hashFunction?: Function13}): MiddlewareHandler => {
8 unmodified lines
22 }2324 const realm = options.realm?.replace(/"/g, '\\"')2526 return async (c, next) => {26 return async function bearerAuth(c, next) {27 const headerToken = c.req.header('Authorization')2829 if (!headerToken) {30 // No Authorization header
16 unmodified lines
47 },48 })49 throw new HTTPException(400, { res })50 } else {51 let equal = false52 if (typeof options.token === 'string') {51 const equal = await timingSafeEqual(options.token, match[1], options.hashFunction)53 equal = await timingSafeEqual(options.token, match[1], options.hashFunction)54 } else if (Array.isArray(options.token) && options.token.length > 0) {55 for (const token of options.token) {56 if (await timingSafeEqual(token, match[1], options.hashFunction)) {57 equal = true58 break59 }60 }61 }62 if (!equal) {63 // Invalid Token64 const res = new Response('Unauthorized', {65 status: 401,
11 unmodified lines
modified:deno_dist/middleware/cache/index.ts+1 added-1 removed
11 unmodified lines
12 const addHeader = (response: Response) => {13 if (options.cacheControl) response.headers.set('Cache-Control', options.cacheControl)14 }1516 return async (c, next) => {16 return async function cache(c, next) {17 const key = c.req.url18 const cache = await caches.open(options.cacheName)19 const response = await cache.match(key)20 if (!response) {
16 unmodified lines
modified:deno_dist/middleware/compress/index.ts+1 added-1 removed
5 unmodified lines
6 encoding?: typeof ENCODING_TYPES[number]7}89export const compress = (options?: CompressionOptions): MiddlewareHandler => {10 return async (ctx, next) => {10 return async function compress(ctx, next) {11 await next()12 const accepted = ctx.req.headers.get('Accept-Encoding')13 const encoding =14 options?.encoding ?? ENCODING_TYPES.find((encoding) => accepted?.includes(encoding))
11 unmodified lines
modified:deno_dist/middleware/cors/index.ts+1 added-1 removed
29 unmodified lines
30 return (origin: string) => (optsOrigin.includes(origin) ? origin : optsOrigin[0])31 }32 })(opts.origin)3334 return async (c, next) => {34 return async function cors(c, next) {35 function set(key: string, value: string) {36 c.res.headers.set(key, value)37 }38
55 unmodified lines
modified:deno_dist/middleware/etag/index.ts+1 added-1 removed
27 unmodified lines
28export const etag = (options?: ETagOptions): MiddlewareHandler => {29 const retainedHeaders = options?.retainedHeaders ?? RETAINED_304_HEADERS30 const weak = options?.weak ?? false3132 return async (c, next) => {32 return async function etag(c, next) {33 const ifNoneMatch = c.req.header('If-None-Match') ?? null3435 await next()36
27 unmodified lines
modified:deno_dist/middleware/jsx-renderer/index.ts+5 added-3 removed
46 unmodified lines
47 return c.html(body)48 }49 }5051export const jsxRenderer =52 (component?: FC<PropsForRenderer>, options?: RendererOptions): MiddlewareHandler =>53 (c, next) => {51export const jsxRenderer = (52 component?: FC<PropsForRenderer>,53 options?: RendererOptions54): MiddlewareHandler =>55 function jsxRenderer(c, next) {56 /* eslint-disable @typescript-eslint/no-explicit-any */57 c.setRenderer(createRenderer(c, component, options) as any)58 return next()59 }
12 unmodified lines
modified:deno_dist/middleware/jwt/index.ts+1 added-1 removed
22 unmodified lines
23 if (!crypto.subtle || !crypto.subtle.importKey) {24 throw new Error('`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.')25 }2627 return async (ctx, next) => {27 return async function jwt(ctx, next) {28 const credentials = ctx.req.headers.get('Authorization')29 let token30 if (credentials) {31 const parts = credentials.split(/\s+/)
52 unmodified lines
modified:deno_dist/middleware/logger/index.ts+1 added-1 removed
52 unmodified lines
53 fn(out)54}5556export const logger = (fn: PrintFunc = console.log): MiddlewareHandler => {57 return async (c, next) => {57 return async function logger(c, next) {58 const { method } = c.req59 // eslint-disable-next-line @typescript-eslint/no-unused-vars60 const path = getPath(c.req.raw)61
9 unmodified lines
modified:deno_dist/middleware/powered-by/index.ts+1 added-1 removed
1import type { MiddlewareHandler } from '../../types.ts'23export const poweredBy = (): MiddlewareHandler => {4 return async (c, next) => {4 return async function poweredBy(c, next) {5 await next()6 c.res.headers.set('X-Powered-By', 'Hono')7 }8}
modified:deno_dist/middleware/pretty-json/index.ts+1 added-1 removed
3 unmodified lines
4 space: number5}67export const prettyJSON = (options: prettyOptions = { space: 2 }): MiddlewareHandler => {8 return async (c, next) => {8 return async function prettyJSON(c, next) {9 const pretty = c.req.query('pretty') || c.req.query('pretty') === '' ? true : false10 await next()11 if (pretty && c.res.headers.get('Content-Type')?.startsWith('application/json')) {12 const obj = await c.res.json()
4 unmodified lines
modified:deno_dist/middleware/secure-headers/index.ts+1 added-1 removed
128 unmodified lines
129 const reportToOptions = options.reportTo.map((option) => JSON.stringify(option)).join(', ')130 headersToSet.push(['Report-To', reportToOptions])131 }132133 return async (ctx, next) => {133 return async function secureHeaders(ctx, next) {134 await next()135 headersToSet.forEach(([header, value]) => {136 ctx.res.headers.set(header, value)137 })
4 unmodified lines
modified:deno_dist/middleware/timing/index.ts+1 added-1 removed
40 unmodified lines
41 crossOrigin: false,42 },43 ...config,44 }45 return async (c, next) => {45 return async function timing(c, next) {46 const headers: string[] = []47 const timers = new Map<string, Timer>()48 c.set('metric', { headers, timers })49
86 unmodified lines
modified:deno_dist/router/reg-exp-router/router.ts+7 added-2 removed
1/* eslint-disable @typescript-eslint/ban-ts-comment */2import type { Router, Result, ParamIndexMap } from '../../router.ts'3import { METHOD_NAME_ALL, METHODS, UnsupportedPathError } from '../../router.ts'3import {4 METHOD_NAME_ALL,5 METHODS,6 UnsupportedPathError,7 MESSAGE_MATCHER_IS_ALREADY_BUILT,8} from '../../router.ts'9import { checkOptionalParameter } from '../../utils/url.ts'10import { PATH_ERROR, type ParamAssocArray } from './node.ts'11import { Trie } from './trie.ts'12
120 unmodified lines
133 add(method: string, path: string, handler: T) {134 const { middleware, routes } = this135136 if (!middleware || !routes) {132 throw new Error('Can not add a route since the matcher is already built.')137 throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT)138 }139140 if (methodNames.indexOf(method) === -1) methodNames.push(method)141 if (!middleware[method]) {
135 unmodified lines
modified:deno_dist/router/smart-router/router.ts+2 added-2 removed
1/* eslint-disable @typescript-eslint/ban-ts-comment */2import type { Router, Result } from '../../router.ts'3import { UnsupportedPathError } from '../../router.ts'3import { UnsupportedPathError, MESSAGE_MATCHER_IS_ALREADY_BUILT } from '../../router.ts'45export class SmartRouter<T> implements Router<T> {6 name: string = 'SmartRouter'7 routers: Router<T>[] = []
4 unmodified lines
12 }1314 add(method: string, path: string, handler: T) {15 if (!this.routes) {16 throw new Error('Can not add a route since the matcher is already built.')16 throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT)17 }1819 this.routes.push([method, path, handler])20 }
49 unmodified lines
modified:deno_dist/utils/html.ts+28 added-5 removed
1export type HtmlEscaped = { isEscaped: true; promises?: Promise<string>[] }1type HtmlEscapedCallbackOpts = { error?: Error; buffer?: [string] }2export type HtmlEscapedCallback = (opts: HtmlEscapedCallbackOpts) => Promise<string>3export type HtmlEscaped = {4 isEscaped: true5 callbacks?: HtmlEscapedCallback[]6}7export type HtmlEscapedString = string & HtmlEscaped8export type StringBuffer = (string | Promise<string>)[]9import { raw } from '../helper/html/index.ts'10
3 unmodified lines
14const escapeRe = /[&<>'"]/1516export const stringBufferToString = async (buffer: StringBuffer): Promise<HtmlEscapedString> => {17 let str = ''13 const promises: Promise<string>[] = []18 const callbacks: HtmlEscapedCallback[] = []19 for (let i = buffer.length - 1; i >= 0; i--) {20 let r = await buffer[i]21 if (typeof r === 'object') {17 promises.push(...((r as HtmlEscapedString).promises || []))22 callbacks.push(...((r as HtmlEscapedString).callbacks || []))23 }24 r = await (typeof r === 'object' ? (r as HtmlEscapedString).toString() : r)25 if (typeof r === 'object') {21 promises.push(...((r as HtmlEscapedString).promises || []))26 callbacks.push(...((r as HtmlEscapedString).callbacks || []))27 }28 str += r29 }3026 return raw(str, promises)31 return raw(str, callbacks)32}3334export const escapeToBuffer = (str: string, buffer: StringBuffer): void => {35 const match = str.search(escapeRe)
32 unmodified lines
68 }6970 buffer[0] += str.substring(lastIndex, index)71}7273export const resolveStream = (74 str: string | HtmlEscapedString,75 buffer?: [string]76): Promise<string> => {77 if (!(str as HtmlEscapedString).callbacks?.length) {78 return Promise.resolve(str)79 }80 const callbacks = (str as HtmlEscapedString).callbacks as HtmlEscapedCallback[]81 if (buffer) {82 buffer[0] += str83 } else {84 buffer = [str]85 }86 return Promise.all(callbacks.map((c) => c({ buffer }))).then((res) =>87 Promise.all(res.map((str) => resolveStream(str, buffer))).then(() => (buffer as [string])[0])88 )89}
modified:deno_dist/compose.ts+3 added-6 removed
7 unmodified lines
8}910// Based on the code in the MIT licensed `koa-compose` package.11export const compose = <C extends ComposeContext, E extends Env = Env>(12 middleware: [Function, ParamIndexMap | Params][],12 middleware: [[Function, unknown], ParamIndexMap | Params][],13 onError?: ErrorHandler<E>,14 onNotFound?: NotFoundHandler<E>15) => {16 return (context: C, next?: Function) => {
10 unmodified lines
27 let isError = false28 let handler2930 if (middleware[i]) {31 handler = middleware[i][0]31 handler = middleware[i][0][0]32 if (context instanceof Context) {33 context.req.setParams(middleware[i][1])33 context.req.routeIndex = i34 }35 } else {36 handler = (i === middleware.length && next) || undefined37 }
17 unmodified lines
55 }56 }57 }5859 if (res !== undefined && 'response' in res) {60 res = res['response']61 }59 if (res && (context.finalized === false || isError)) {60 context.res = res61 }62 return context
3 unmodified lines
modified:deno_dist/context.ts+121 added-126 removed
1 unmodified line
2import type { HonoRequest } from './request.ts'3import type { Env, FetchEventLike, NotFoundHandler, Input, TypedResponse } from './types.ts'4import type { CookieOptions } from './utils/cookie.ts'5import { serialize } from './utils/cookie.ts'6import { resolveStream } from './utils/html.ts'7import type { StatusCode } from './utils/http-status.ts'8import { StreamingApi } from './utils/stream.ts'9import type { JSONValue, InterfaceToType } from './utils/types.ts'10
10 unmodified lines
21export interface ContextRenderer {}22interface DefaultRenderer {23 (content: string | Promise<string>): Response | Promise<Response>24}2526export type Renderer = ContextRenderer extends Function ? ContextRenderer : DefaultRenderer2728interface Get<E extends Env> {29 <Key extends keyof ContextVariableMap>(key: Key): ContextVariableMap[Key]
17 unmodified lines
47 (text: string, init?: ResponseInit): Response48}4950interface JSONRespond {49 <T = JSONValue>(object: T, status?: StatusCode, headers?: HeaderRecord): Response50 <T = JSONValue>(object: T, init?: ResponseInit): Response51}5253interface JSONTRespond {51 <T>(55 object: InterfaceToType<T> extends JSONValue ? T : JSONValue,52 object: InterfaceToType<T> extends JSONValue ? T : T extends JSONValue ? JSONValue : T,53 status?: StatusCode,54 headers?: HeaderRecord58 ): TypedResponse<59 InterfaceToType<T> extends JSONValue60 ? JSONValue extends InterfaceToType<T>61 ? never62 : T63 : never64 >65 <T>(66 object: InterfaceToType<T> extends JSONValue ? T : JSONValue,67 init?: ResponseInit68 ): TypedResponse<69 InterfaceToType<T> extends JSONValue70 ? JSONValue extends InterfaceToType<T>71 ? never72 : T73 : never74 >55 ): Response &56 TypedResponse<57 InterfaceToType<T> extends JSONValue58 ? JSONValue extends InterfaceToType<T>59 ? never60 : T61 : never62 >63 <T>(object: InterfaceToType<T> extends JSONValue ? T : JSONValue, init?: ResponseInit): Response &64 TypedResponse<65 InterfaceToType<T> extends JSONValue66 ? JSONValue extends InterfaceToType<T>67 ? never68 : T69 : never70 >71}7273interface HTMLRespond {74 (html: string | Promise<string>, status?: StatusCode, headers?: HeaderRecord):
22 unmodified lines
97 private _var: E['Variables'] = {}98 finalized: boolean = false99 error: Error | undefined = undefined100105 private _status: StatusCode = 200106 private _exCtx: FetchEventLike | ExecutionContext | undefined // _executionCtx107 private _h: Headers | undefined = undefined // _headers108 private _pH: Record<string, string> | undefined = undefined // _preparedHeaders109 private _res: Response | undefined110 private _init = true111 private _renderer: Renderer = (content: string | Promise<string>) => this.html(content)101 #status: StatusCode = 200102 #executionCtx: FetchEventLike | ExecutionContext | undefined103 #headers: Headers | undefined = undefined104 #preparedHeaders: Record<string, string> | undefined = undefined105 #res: Response | undefined106 #isFresh = true107 private renderer: Renderer = (content: string | Promise<string>) => this.html(content)108 private notFoundHandler: NotFoundHandler<E> = () => new Response()109110 constructor(req: HonoRequest<P, I['out']>, options?: ContextOptions<E>) {111 this.req = req112 if (options) {117 this._exCtx = options.executionCtx113 this.#executionCtx = options.executionCtx114 this.env = options.env115 if (options.notFoundHandler) {116 this.notFoundHandler = options.notFoundHandler117 }118 }119 }120121 get event(): FetchEventLike {126 if (this._exCtx && 'respondWith' in this._exCtx) {127 return this._exCtx122 if (this.#executionCtx && 'respondWith' in this.#executionCtx) {123 return this.#executionCtx124 } else {125 throw Error('This context has no FetchEvent')126 }127 }128129 get executionCtx(): ExecutionContext {134 if (this._exCtx) {135 return this._exCtx as ExecutionContext130 if (this.#executionCtx) {131 return this.#executionCtx as ExecutionContext132 } else {133 throw Error('This context has no ExecutionContext')134 }135 }136137 get res(): Response {142 this._init = false143 return (this._res ||= new Response('404 Not Found', { status: 404 }))138 this.#isFresh = false139 return (this.#res ||= new Response('404 Not Found', { status: 404 }))140 }141142 set res(_res: Response | undefined) {147 this._init = false148 if (this._res && _res) {149 this._res.headers.delete('content-type')150 this._res.headers.forEach((v, k) => {143 this.#isFresh = false144 if (this.#res && _res) {145 this.#res.headers.delete('content-type')146 this.#res.headers.forEach((v, k) => {147 _res.headers.set(k, v)148 })149 }154 this._res = _res150 this.#res = _res151 this.finalized = true152 }153158 /**159 * @experimental160 * `c.render()` is an experimental feature.161 * The API might be changed.162 */154 // eslint-disable-next-line @typescript-eslint/ban-ts-comment155 // @ts-ignore156 // eslint-disable-next-line @typescript-eslint/no-explicit-any166 render: Renderer = (...args: any[]) => this._renderer(...args)157 render: Renderer = (...args: any[]) => this.renderer(...args)158168 /**169 * @experimental170 * `c.setRenderer()` is an experimental feature.171 * The API might be changed.172 */159 setRenderer = (renderer: Renderer) => {174 this._renderer = renderer160 this.renderer = renderer161 }162163 header = (name: string, value: string | undefined, options?: { append?: boolean }): void => {164 // Clear the header165 if (value === undefined) {180 if (this._h) {181 this._h.delete(name)182 } else if (this._pH) {183 delete this._pH[name.toLocaleLowerCase()]166 if (this.#headers) {167 this.#headers.delete(name)168 } else if (this.#preparedHeaders) {169 delete this.#preparedHeaders[name.toLocaleLowerCase()]170 }171 if (this.finalized) {172 this.res.headers.delete(name)173 }174 return175 }176177 if (options?.append) {192 if (!this._h) {193 this._init = false194 this._h = new Headers(this._pH)195 this._pH = {}178 if (!this.#headers) {179 this.#isFresh = false180 this.#headers = new Headers(this.#preparedHeaders)181 this.#preparedHeaders = {}182 }197 this._h.append(name, value)183 this.#headers.append(name, value)184 } else {199 if (this._h) {200 this._h.set(name, value)185 if (this.#headers) {186 this.#headers.set(name, value)187 } else {202 this._pH ??= {}203 this._pH[name.toLowerCase()] = value188 this.#preparedHeaders ??= {}189 this.#preparedHeaders[name.toLowerCase()] = value190 }191 }192193 if (this.finalized) {
5 unmodified lines
199 }200 }201202 status = (status: StatusCode): void => {217 this._init = false218 this._status = status203 this.#isFresh = false204 this.#status = status205 }206207 set: Set<E> = (key: string, value: unknown) => {208 this._var ??= {}
14 unmodified lines
223 arg?: StatusCode | ResponseInit,224 headers?: HeaderRecord225 ): Response => {226 // Optimized241 if (this._init && !headers && !arg && this._status === 200) {227 if (this.#isFresh && !headers && !arg && this.#status === 200) {228 return new Response(data, {243 headers: this._pH,229 headers: this.#preparedHeaders,230 })231 }232233 // Return Response immediately if arg is ResponseInit.234 if (arg && typeof arg !== 'number') {235 const res = new Response(data, arg)250 const contentType = this._pH?.['content-type']236 const contentType = this.#preparedHeaders?.['content-type']237 if (contentType) {238 res.headers.set('content-type', contentType)239 }240 return res241 }242257 const status = arg ?? this._status258 this._pH ??= {}243 const status = arg ?? this.#status244 this.#preparedHeaders ??= {}245260 this._h ??= new Headers()261 for (const [k, v] of Object.entries(this._pH)) {262 this._h.set(k, v)246 this.#headers ??= new Headers()247 for (const [k, v] of Object.entries(this.#preparedHeaders)) {248 this.#headers.set(k, v)249 }250265 if (this._res) {266 this._res.headers.forEach((v, k) => {267 this._h?.set(k, v)251 if (this.#res) {252 this.#res.headers.forEach((v, k) => {253 this.#headers?.set(k, v)254 })269 for (const [k, v] of Object.entries(this._pH)) {270 this._h.set(k, v)255 for (const [k, v] of Object.entries(this.#preparedHeaders)) {256 this.#headers.set(k, v)257 }258 }259260 headers ??= {}261 for (const [k, v] of Object.entries(headers)) {262 if (typeof v === 'string') {277 this._h.set(k, v)263 this.#headers.set(k, v)264 } else {279 this._h.delete(k)265 this.#headers.delete(k)266 for (const v2 of v) {281 this._h.append(k, v2)267 this.#headers.append(k, v2)268 }269 }270 }271272 return new Response(data, {273 status,288 headers: this._h,274 headers: this.#headers,275 })276 }277278 body: BodyRespond = (
12 unmodified lines
291 headers?: HeaderRecord292 ): Response => {293 // If the header is empty, return Response immediately.294 // Content-Type will be added automatically as `text/plain`.309 if (!this._pH) {310 if (this._init && !headers && !arg) {295 if (!this.#preparedHeaders) {296 if (this.#isFresh && !headers && !arg) {297 return new Response(text)298 }313 this._pH = {}299 this.#preparedHeaders = {}300 }315 this._pH['content-type'] = TEXT_PLAIN301 this.#preparedHeaders['content-type'] = TEXT_PLAIN302 return typeof arg === 'number'303 ? this.newResponse(text, arg, headers)304 : this.newResponse(text, arg)305 }306321 json: JSONRespond = <T = {}>(322 object: T,307 json: JSONRespond = <T>(308 object: InterfaceToType<T> extends JSONValue ? T : T extends JSONValue ? JSONValue : T,309 arg?: StatusCode | ResponseInit,310 headers?: HeaderRecord311 ): Response &312 TypedResponse<313 InterfaceToType<T> extends JSONValue314 ? JSONValue extends InterfaceToType<T>315 ? never316 : T317 : never325 ) => {318 > => {319 const body = JSON.stringify(object)327 this._pH ??= {}328 this._pH['content-type'] = 'application/json; charset=UTF-8'329 return typeof arg === 'number'330 ? this.newResponse(body, arg, headers)331 : this.newResponse(body, arg)320 this.#preparedHeaders ??= {}321 this.#preparedHeaders['content-type'] = 'application/json; charset=UTF-8'322 /* eslint-disable @typescript-eslint/no-explicit-any */323 return (324 typeof arg === 'number' ? this.newResponse(body, arg, headers) : this.newResponse(body, arg)325 ) as any326 }327328 /**329 * @deprecated330 * `c.jsonT()` will be removed in v4.331 * Use `c.json()` instead of `c.jsonT()`.332 * `c.json()` now returns data type, so you can just replace `c.jsonT()` to `c.json()`.333 */334 jsonT: JSONTRespond = <T>(335 object: InterfaceToType<T> extends JSONValue ? T : JSONValue,334 jsonT: JSONRespond = <T>(335 object: InterfaceToType<T> extends JSONValue ? T : T extends JSONValue ? JSONValue : T,336 arg?: StatusCode | ResponseInit,337 headers?: HeaderRecord338 ): TypedResponse<339 InterfaceToType<T> extends JSONValue340 ? JSONValue extends InterfaceToType<T>341 ? never342 : T343 : never344 > => {345 const response =346 typeof arg === 'number' ? this.json(object, arg, headers) : this.json(object, arg)347348 return {349 response,350 // eslint-disable-next-line @typescript-eslint/no-explicit-any351 data: object as any,352 format: 'json',353 status: response.status,354 }338 ): Response &339 TypedResponse<340 InterfaceToType<T> extends JSONValue341 ? JSONValue extends InterfaceToType<T>342 ? never343 : T344 : never345 > => {346 // eslint-disable-next-line @typescript-eslint/no-explicit-any347 return this.json(object, arg as any, headers) as any348 }349350 html: HTMLRespond = (351 html: string | Promise<string>,352 arg?: StatusCode | ResponseInit,353 headers?: HeaderRecord354 ): Response | Promise<Response> => {362 this._pH ??= {}363 this._pH['content-type'] = 'text/html; charset=UTF-8'355 this.#preparedHeaders ??= {}356 this.#preparedHeaders['content-type'] = 'text/html; charset=UTF-8'357358 if (typeof html === 'object') {359 if (!(html instanceof Promise)) {360 html = (html as string).toString() // HtmlEscapedString object to string361 }362 if ((html as string | Promise<string>) instanceof Promise) {363 return (html as unknown as Promise<string>)364 .then((html) => resolveStream(html))370 return (html as unknown as Promise<string>).then((html) => {371 return typeof arg === 'number'372 ? this.newResponse(html, arg, headers)373 : this.newResponse(html, arg)374 })365 .then((html) => {366 return typeof arg === 'number'367 ? this.newResponse(html, arg, headers)368 : this.newResponse(html, arg)369 })370 }371 }372373 return typeof arg === 'number'
1 unmodified line
375 : this.newResponse(html as string, arg)376 }377378 redirect = (location: string, status: StatusCode = 302): Response => {384 this._h ??= new Headers()385 this._h.set('Location', location)379 this.#headers ??= new Headers()380 this.#headers.set('Location', location)381 return this.newResponse(null, status)382 }383384 streamText = (
95 unmodified lines
modified:deno_dist/helper.ts+1 added
3 unmodified lines
4export * from './helper/factory/index.ts'5export * from './helper/html/index.ts'6export * from './helper/streaming/index.ts'7export * from './helper/testing/index.ts'8export * from './helper/dev/index.ts'
modified:deno_dist/hono-base.ts+35 added-41 removed
13 unmodified lines
14 MiddlewareHandlerInterface,15 Next,16 NotFoundHandler,17 OnHandlerInterface,18 TypedResponse,18 MergePath,19 MergeSchemaPath,20 FetchEventLike,21 Schema,22 RouterRoute,23} from './types.ts'24import { getPath, getPathNoStrict, getQueryStrings, mergePath } from './utils/url.ts'2526type Methods = typeof METHODS[number] | typeof METHOD_NAME_ALL_LOWERCASE2728interface RouterRoute {29 path: string30 method: string31 handler: H32}3328function defineDynamicClass(): {29 new <E extends Env = Env, S extends Schema = {}, BasePath extends string = '/'>(): {30 [M in Methods]: HandlerInterface<E, M, S, BasePath>31 } & {
21 unmodified lines
53type GetPath<E extends Env> = (request: Request, options?: { env?: E['Bindings'] }) => string5455export type HonoOptions<E extends Env> = {56 strict?: boolean63 router?: Router<H>57 router?: Router<[H, RouterRoute]>58 getPath?: GetPath<E>59}6061class Hono<
4 unmodified lines
66 /*67 This class is like an abstract class and does not have a router.68 To use it, inherit the class and implement router in the constructor.69 */76 router!: Router<H>70 router!: Router<[H, RouterRoute]>71 readonly getPath: GetPath<E>78 private _basePath: string = '/'79 private path: string = '/'72 #basePath: string = '/'73 #path: string = '/'7475 routes: RouterRoute[] = []7677 constructor(options: HonoOptions<E> = {}) {
3 unmodified lines
81 const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE]82 allMethods.map((method) => {83 this[method] = (args1: string | H, ...args: H[]) => {84 if (typeof args1 === 'string') {91 this.path = args185 this.#path = args186 } else {93 this.addRoute(method, this.path, args1)87 this.addRoute(method, this.#path, args1)88 }89 args.map((handler) => {90 if (typeof handler !== 'string') {97 this.addRoute(method, this.path, handler)91 this.addRoute(method, this.#path, handler)92 }93 })94 // eslint-disable-next-line @typescript-eslint/no-explicit-any100 return this95 return this as any96 }97 })9899 // Implementation of app.on(method, path, ...handlers[])100 this.on = (method: string | string[], path: string, ...handlers: H[]) => {101 if (!method) return this107 this.path = path102 this.#path = path103 for (const m of [method].flat()) {104 handlers.map((handler) => {110 this.addRoute(m.toUpperCase(), this.path, handler)105 this.addRoute(m.toUpperCase(), this.#path, handler)106 })107 }108 // eslint-disable-next-line @typescript-eslint/no-explicit-any113 return this109 return this as any110 }111112 // Implementation of app.use(...handlers[]) or app.get(path, ...handlers[])113 // eslint-disable-next-line @typescript-eslint/no-explicit-any114 this.use = (arg1: string | MiddlewareHandler<any>, ...handlers: MiddlewareHandler<any>[]) => {115 if (typeof arg1 === 'string') {120 this.path = arg1116 this.#path = arg1117 } else {118 handlers.unshift(arg1)119 }120 handlers.map((handler) => {125 this.addRoute(METHOD_NAME_ALL, this.path, handler)121 this.addRoute(METHOD_NAME_ALL, this.#path, handler)122 })123 return this124 }125
42 unmodified lines
168 }169170 basePath<SubPath extends string>(path: SubPath): Hono<E, S, MergePath<BasePath, SubPath>> {171 const subApp = this.clone()176 subApp._basePath = mergePath(this._basePath, path)172 subApp.#basePath = mergePath(this.#basePath, path)173 return subApp174 }175176 onError(handler: ErrorHandler<E>) {
5 unmodified lines
182 this.notFoundHandler = handler183 return this184 }185186 /**187 * @deprecated188 * Use `showRoutes()` utility methods provided by 'hono/helper' instead of `app.showRoutes()`.189 * `app.showRoutes()` will be removed in v4.190 * @example191 * You could rewrite `app.showRoutes()` as follows192 * import { showRoutes } from 'hono/helper'193 * showRoutes(app)194 */195 showRoutes() {196 const length = 8197 this.routes.map((route) => {198 console.log(
7 unmodified lines
206 // eslint-disable-next-line @typescript-eslint/no-explicit-any207 applicationHandler: (request: Request, ...args: any) => Response | Promise<Response>,208 optionHandler?: (c: Context) => unknown209 ): Hono<E, S, BasePath> {205 const mergedPath = mergePath(this._basePath, path)210 const mergedPath = mergePath(this.#basePath, path)211 const pathPrefixLength = mergedPath === '/' ? 0 : mergedPath.length212213 const handler: MiddlewareHandler = async (c, next) => {214 let executionContext: ExecutionContext | undefined = undefined
36 unmodified lines
251 }252253 private addRoute(method: string, path: string, handler: H) {254 method = method.toUpperCase()250 path = mergePath(this._basePath, path)251 this.router.add(method, path, handler)255 path = mergePath(this.#basePath, path)256 const r: RouterRoute = { path: path, method: method, handler: handler }257 this.router.add(method, path, [handler, r])258 this.routes.push(r)259 }260261 private matchRoute(method: string, path: string) {
19 unmodified lines
281 new Response(null, await this.dispatch(request, executionCtx, env, 'GET')))()282 }283284 const path = this.getPath(request, { env })280 const [handlers, paramStash] = this.matchRoute(method, path)285 const matchResult = this.matchRoute(method, path)286282 const c = new Context(new HonoRequest(request, path, paramStash), {287 const c = new Context(new HonoRequest(request, path, matchResult), {288 env,289 executionCtx,290 notFoundHandler: this.notFoundHandler,291 })292293 // Do not `compose` if it has only one handler289 if (handlers.length === 1) {294 if (matchResult[0].length === 1) {295 let res: ReturnType<H>291292 c.req.setParams(handlers[0][1])296 try {294 res = handlers[0][0](c, async () => {})297 res = matchResult[0][0][0][0](c, async () => {})298 if (!res) {299 return this.notFoundHandler(c)300 }301 } catch (err) {
1 unmodified line
303 }304305 if (res instanceof Response) return res306304 if ('response' in res) {305 res = res.response306 }307308 if (res instanceof Response) return res309307 return (async () => {311 let awaited: Response | TypedResponse | void308 let awaited: Response | void309 try {310 awaited = await res314 if (awaited !== undefined && 'response' in awaited) {315 awaited = awaited['response'] as Response316 }311 if (!awaited) {312 return this.notFoundHandler(c)313 }314 } catch (err) {
2 unmodified lines
317 return awaited318 })()319 }320327 const composed = compose<Context>(handlers, this.errorHandler, this.notFoundHandler)321 const composed = compose<Context>(matchResult[0], this.errorHandler, this.notFoundHandler)322323 return (async () => {324 try {325 const context = await composed(c)
53 unmodified lines
modified:deno_dist/request.ts+29 added-17 removed
1/* eslint-disable @typescript-eslint/no-explicit-any */2/* eslint-disable @typescript-eslint/no-non-null-assertion */3import type { ParamIndexMap, ParamStash, Params } from './router.ts'2import type { Result } from './router.ts'3import type {4 Input,5 InputToDataByTarget,6 ParamKeys,7 ParamKeyToRecord,8 RemoveQuestion,9 UndefinedIfHavingQuestion,10 ValidationTargets,11 RouterRoute,12} from './types.ts'13import { parseBody } from './utils/body.ts'14import type { BodyData, ParseBodyOptions } from './utils/body.ts'15import type { Cookie } from './utils/cookie.ts'
12 unmodified lines
2829export class HonoRequest<P extends string = '/', I extends Input['out'] = {}> {30 raw: Request3132 private _s: ParamStash | undefined33 private vData: { [K in keyof ValidationTargets]?: {} } // Short name of validatedData34 private _p: ParamIndexMap | Params = {}32 #validatedData: { [K in keyof ValidationTargets]?: {} } // Short name of validatedData33 #matchResult: Result<[unknown, RouterRoute]>34 routeIndex: number = 035 path: string36 bodyCache: BodyCache = {}3738 constructor(39 request: Request,40 path: string = '/',41 paramStash: ParamStash | undefined = undefined41 matchResult: Result<[unknown, RouterRoute]> = [[]]42 ) {43 this.raw = request44 this.path = path45 this._s = paramStash46 this.vData = {}45 this.#matchResult = matchResult46 this.#validatedData = {}47 }4849 setParams(params: ParamIndexMap | Params) {50 this._p = params51 }5249 param<P2 extends string = P>(50 key: RemoveQuestion<ParamKeys<P2>>51 ): UndefinedIfHavingQuestion<ParamKeys<P2>>52 param<P2 extends string = P>(): UnionToIntersection<ParamKeyToRecord<ParamKeys<P2>>>53 param(key?: string): unknown {54 if (key) {59 const param = (this._s ? this._s[this._p[key] as any] : this._p[key]) as string | undefined55 const param = (56 this.#matchResult[1]57 ? this.#matchResult[1][this.#matchResult[0][this.routeIndex][1][key] as any]58 : this.#matchResult[0][this.routeIndex][1][key]59 ) as string | undefined60 return param ? (/\%/.test(param) ? decodeURIComponent_(param) : param) : undefined61 } else {62 const decoded: Record<string, string> = {}6364 const keys = Object.keys(this._p)64 const keys = Object.keys(this.#matchResult[0][this.routeIndex][1])65 for (let i = 0, len = keys.length; i < len; i++) {66 const key = keys[i]67 const value = (this._s ? this._s[this._p[key] as any] : this._p[key]) as string | undefined67 const value = (68 this.#matchResult[1]69 ? this.#matchResult[1][this.#matchResult[0][this.routeIndex][1][key] as any]70 : this.#matchResult[0][this.routeIndex][1][key]71 ) as string | undefined72 if (value && typeof value === 'string') {73 decoded[key] = /\%/.test(value) ? decodeURIComponent_(value) : value74 }75 }
103 unmodified lines
179 return this.cachedBody('formData')180 }181182 addValidatedData(target: keyof ValidationTargets, data: {}) {179 this.vData[target] = data183 this.#validatedData[target] = data184 }185186 valid<T extends keyof I & keyof ValidationTargets>(target: T): InputToDataByTarget<I, T>187 valid(target: keyof ValidationTargets) {184 return this.vData[target] as unknown188 return this.#validatedData[target] as unknown189 }190191 get url() {192 return this.raw.url
2 unmodified lines
195 get method() {196 return this.raw.method197 }198199 get matchedRoutes(): RouterRoute[] {200 return this.#matchResult[0].map(([[, route]]) => route)201 }202203 get routePath(): string {204 return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path205 }206207 /** @deprecated208 * Use `c.req.raw.headers` instead of `c.req.headers`. The `c.req.headers` will be removed in v4.209 * Or you can get the header values with using `c.req.header`.210 * @example
52 unmodified lines
modified:deno_dist/router.ts+2 added
1export const METHOD_NAME_ALL = 'ALL' as const2export const METHOD_NAME_ALL_LOWERCASE = 'all' as const3export const METHODS = ['get', 'post', 'put', 'delete', 'options', 'patch'] as const4export const MESSAGE_MATCHER_IS_ALREADY_BUILT =5 'Can not add a route since the matcher is already built.'67export interface Router<T> {8 name: string9 add(method: string, path: string, handler: T): void
33 unmodified lines
modified:deno_dist/types.ts+1038 added-99 removed
27 unmodified lines
28}2930////////////////////////////////////////31////// //////32////// Routes //////33////// //////34////////////////////////////////////////3536export interface RouterRoute {37 path: string38 method: string39 handler: H40}4142////////////////////////////////////////43////// //////44////// Handlers //////45////// //////46////////////////////////////////////////4736type HandlerResponse<O> = Response | TypedResponse<O> | Promise<Response | TypedResponse<O>>48export type HandlerResponse<O> = Response | TypedResponse<O> | Promise<Response | TypedResponse<O>>4950export type Handler<51 E extends Env = any,52 P extends string = any,
41 unmodified lines
94 R extends HandlerResponse<any> = any,95 E2 extends Env = E96 >(97 handler: H<E2, P, I, R>86 ): Hono<E & E2, S & ToSchema<M, P, I['in'], MergeTypedResponseData<R>>, BasePath>98 ): Hono<99 IntersectNonAnyTypes<[E, E2]>,100 S & ToSchema<M, P, I['in'], MergeTypedResponseData<R>>,101 BasePath102 >10388 // app.get(handler, handler)104 // app.get(handler x2)105 <106 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,107 I extends Input = {},108 I2 extends Input = I,109 R extends HandlerResponse<any> = any,110 E2 extends Env = E,111 E3 extends Env = IntersectNonAnyTypes<[E, E2]>112 >(96 ...handlers: [H<E2, P, I, R>, H<E3, P, I, R>]97 ): Hono<E & E2 & E3, S & ToSchema<M, P, I['in'], MergeTypedResponseData<R>>, BasePath>113 ...handlers: [H<E2, P, I>, H<E3, P, I2, R>]114 ): Hono<115 IntersectNonAnyTypes<[E, E2, E3]>,116 S & ToSchema<M, P, I2['in'], MergeTypedResponseData<R>>,117 BasePath118 >119120 // app.get(handler x 3)121 <122 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,
4 unmodified lines
127 E2 extends Env = E,128 E3 extends Env = E,129 E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>130 >(110 ...handlers: [H<E2, P, I, R>, H<E3, P, I2, R>, H<E4, P, I3, R>]111 ): Hono<E & E2 & E3 & E4, S & ToSchema<M, P, I3['in'], MergeTypedResponseData<R>>, BasePath>131 ...handlers: [H<E2, P, I>, H<E3, P, I2>, H<E4, P, I3, R>]132 ): Hono<133 IntersectNonAnyTypes<[E, E2, E3, E4]>,134 S & ToSchema<M, P, I3['in'], MergeTypedResponseData<R>>,135 BasePath136 >137138 // app.get(handler x 4)139 <140 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,
6 unmodified lines
147 E3 extends Env = E,148 E4 extends Env = E,149 E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>150 >(126 ...handlers: [H<E2, P, I, R>, H<E3, P, I2, R>, H<E4, P, I3, R>, H<E5, P, I4, R>]127 ): Hono<E & E2 & E3 & E4 & E5, S & ToSchema<M, P, I4['in'], MergeTypedResponseData<R>>, BasePath>151 ...handlers: [H<E2, P, I>, H<E3, P, I2>, H<E4, P, I3>, H<E5, P, I4, R>]152 ): Hono<153 IntersectNonAnyTypes<[E, E2, E3, E4, E5]>,154 S & ToSchema<M, P, I4['in'], MergeTypedResponseData<R>>,155 BasePath156 >157158 // app.get(handler x 5)159 <160 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,161 R extends HandlerResponse<any> = any,162 I extends Input = {},163 I2 extends Input = I,164 I3 extends Input = I & I2,136 I4 extends Input = I2 & I3,165 I4 extends Input = I & I2 & I3,166 I5 extends Input = I & I2 & I3 & I4,167 E2 extends Env = E,168 E3 extends Env = E,169 E4 extends Env = E,170 E5 extends Env = E,171 E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>172 >(173 ...handlers: [H<E2, P, I>, H<E3, P, I2>, H<E4, P, I3>, H<E5, P, I4>, H<E6, P, I5, R>]174 ): Hono<175 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>,176 S & ToSchema<M, P, I5['in'], MergeTypedResponseData<R>>,177 BasePath178 >179180 // app.get(handler x 6)181 <182 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,183 R extends HandlerResponse<any> = any,184 I extends Input = {},185 I2 extends Input = I,186 I3 extends Input = I & I2,187 I4 extends Input = I & I2 & I3,188 I5 extends Input = I & I2 & I3 & I4,189 I6 extends Input = I & I2 & I3 & I4 & I5,190 E2 extends Env = E,191 E3 extends Env = E,192 E4 extends Env = E,193 E5 extends Env = E,194 E6 extends Env = E,195 E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>196 >(197 ...handlers: [145 H<E2, P, I, R>,146 H<E3, P, I2, R>,147 H<E4, P, I3, R>,148 H<E5, P, I3, R>,149 H<E6, P, I3, R>198 H<E2, P, I>,199 H<E3, P, I2>,200 H<E4, P, I3>,201 H<E5, P, I4>,202 H<E6, P, I5>,203 H<E7, P, I6, R>204 ]205 ): Hono<152 E & E2 & E3 & E4 & E5 & E6,153 S & ToSchema<M, P, I5['in'], MergeTypedResponseData<R>>,206 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>,207 S & ToSchema<M, P, I6['in'], MergeTypedResponseData<R>>,208 BasePath209 >210211 // app.get(handler x 7)212 <213 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,214 R extends HandlerResponse<any> = any,215 I extends Input = {},216 I2 extends Input = I,217 I3 extends Input = I & I2,218 I4 extends Input = I & I2 & I3,219 I5 extends Input = I & I2 & I3 & I4,220 I6 extends Input = I & I2 & I3 & I4 & I5,221 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,222 E2 extends Env = E,223 E3 extends Env = E,224 E4 extends Env = E,225 E5 extends Env = E,226 E6 extends Env = E,227 E7 extends Env = E,228 E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>229 >(230 ...handlers: [231 H<E2, P, I>,232 H<E3, P, I2>,233 H<E4, P, I3>,234 H<E5, P, I4>,235 H<E6, P, I5>,236 H<E7, P, I6>,237 H<E8, P, I7, R>238 ]239 ): Hono<240 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>,241 S & ToSchema<M, P, I7['in'], MergeTypedResponseData<R>>,242 BasePath243 >244245 // app.get(handler x 8)246 <247 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,248 R extends HandlerResponse<any> = any,249 I extends Input = {},250 I2 extends Input = I,251 I3 extends Input = I & I2,252 I4 extends Input = I & I2 & I3,253 I5 extends Input = I & I2 & I3 & I4,254 I6 extends Input = I & I2 & I3 & I4 & I5,255 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,256 I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7,257 E2 extends Env = E,258 E3 extends Env = E,259 E4 extends Env = E,260 E5 extends Env = E,261 E6 extends Env = E,262 E7 extends Env = E,263 E8 extends Env = E,264 E9 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>265 >(266 ...handlers: [267 H<E2, P, I>,268 H<E3, P, I2>,269 H<E4, P, I3>,270 H<E5, P, I4>,271 H<E6, P, I5>,272 H<E7, P, I6>,273 H<E8, P, I7>,274 H<E9, P, I8, R>275 ]276 ): Hono<277 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>,278 S & ToSchema<M, P, I8['in'], MergeTypedResponseData<R>>,279 BasePath280 >281282 // app.get(handler x 9)283 <284 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,285 R extends HandlerResponse<any> = any,286 I extends Input = {},287 I2 extends Input = I,288 I3 extends Input = I & I2,289 I4 extends Input = I & I2 & I3,290 I5 extends Input = I & I2 & I3 & I4,291 I6 extends Input = I & I2 & I3 & I4 & I5,292 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,293 I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7,294 I9 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8,295 E2 extends Env = E,296 E3 extends Env = E,297 E4 extends Env = E,298 E5 extends Env = E,299 E6 extends Env = E,300 E7 extends Env = E,301 E8 extends Env = E,302 E9 extends Env = E,303 E10 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>304 >(305 ...handlers: [306 H<E2, P, I>,307 H<E3, P, I2>,308 H<E4, P, I3>,309 H<E5, P, I4>,310 H<E6, P, I5>,311 H<E7, P, I6>,312 H<E8, P, I7>,313 H<E9, P, I8>,314 H<E10, P, I9, R>315 ]316 ): Hono<317 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>,318 S & ToSchema<M, P, I9['in'], MergeTypedResponseData<R>>,319 BasePath320 >321322 // app.get(handler x 10)323 <324 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,325 R extends HandlerResponse<any> = any,326 I extends Input = {},327 I2 extends Input = I,328 I3 extends Input = I & I2,329 I4 extends Input = I & I2 & I3,330 I5 extends Input = I & I2 & I3 & I4,331 I6 extends Input = I & I2 & I3 & I4 & I5,332 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,333 I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7,334 I9 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8,335 I10 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8 & I9,336 E2 extends Env = E,337 E3 extends Env = E,338 E4 extends Env = E,339 E5 extends Env = E,340 E6 extends Env = E,341 E7 extends Env = E,342 E8 extends Env = E,343 E9 extends Env = E,344 E10 extends Env = E,345 E11 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>346 >(347 ...handlers: [348 H<E2, P, I>,349 H<E3, P, I2>,350 H<E4, P, I3>,351 H<E5, P, I4>,352 H<E6, P, I5>,353 H<E7, P, I6>,354 H<E8, P, I7>,355 H<E9, P, I8>,356 H<E10, P, I9>,357 H<E11, P, I10, R>358 ]359 ): Hono<360 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11]>,361 S & ToSchema<M, P, I10['in'], MergeTypedResponseData<R>>,362 BasePath363 >364365 // app.get(...handlers[])366 <367 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,368 I extends Input = {},
15 unmodified lines
384385 // app.get(path, handler)386 <387 P extends string,180 P2 extends string = P,388 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,389 R extends HandlerResponse<any> = any,390 I extends Input = {},391 E2 extends Env = E392 >(393 path: P,186 handler: H<E2, MergePath<BasePath, P2>, I, R>394 handler: H<E2, MergedPath, I, R>395 ): Hono<188 E & E2,189 S & ToSchema<M, MergePath<BasePath, P>, I['in'], MergeTypedResponseData<R>>,396 IntersectNonAnyTypes<[E, E2]>,397 S & ToSchema<M, MergedPath, I['in'], MergeTypedResponseData<R>>,398 BasePath399 >400193 // app.get(path, handler, handler)401 // app.get(path, handler x2)402 <403 P extends string,196 P2 extends string = P,197 P3 extends string = P,404 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,405 R extends HandlerResponse<any> = any,406 I extends Input = {},407 I2 extends Input = I,408 E2 extends Env = E,409 E3 extends Env = IntersectNonAnyTypes<[E, E2]>410 >(411 path: P,204 ...handlers: [H<E2, MergePath<BasePath, P2>, I, R>, H<E3, MergePath<BasePath, P3>, I, R>]412 ...handlers: [H<E2, MergedPath, I>, H<E3, MergedPath, I2, R>]413 ): Hono<206 E & E2 & E3,207 S & ToSchema<M, MergePath<BasePath, P>, I['in'], MergeTypedResponseData<R>>,414 IntersectNonAnyTypes<[E, E2, E3]>,415 S & ToSchema<M, MergedPath, I2['in'], MergeTypedResponseData<R>>,416 BasePath417 >418419 // app.get(path, handler x3)420 <421 P extends string,214 P2 extends string = P,215 P3 extends string = P,216 P4 extends string = P,422 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,423 R extends HandlerResponse<any> = any,424 I extends Input = {},425 I2 extends Input = I,426 I3 extends Input = I & I2,
1 unmodified line
428 E3 extends Env = E,429 E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>430 >(431 path: P,226 ...handlers: [227 H<E2, MergePath<BasePath, P2>, I, R>,228 H<E3, MergePath<BasePath, P3>, I2, R>,229 H<E4, MergePath<BasePath, P4>, I3, R>230 ]432 ...handlers: [H<E2, MergedPath, I>, H<E3, MergedPath, I2>, H<E4, MergedPath, I3, R>]433 ): Hono<232 E & E2 & E3 & E4,233 S & ToSchema<M, MergePath<BasePath, P>, I3['in'], MergeTypedResponseData<R>>,434 IntersectNonAnyTypes<[E, E2, E3, E4]>,435 S & ToSchema<M, MergedPath, I3['in'], MergeTypedResponseData<R>>,436 BasePath437 >438439 // app.get(path, handler x4)440 <441 P extends string,240 P2 extends string = P,241 P3 extends string = P,242 P4 extends string = P,243 P5 extends string = P,442 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,443 R extends HandlerResponse<any> = any,444 I extends Input = {},445 I2 extends Input = I,446 I3 extends Input = I & I2,
4 unmodified lines
451 E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>452 >(453 path: P,454 ...handlers: [256 H<E2, MergePath<BasePath, P2>, I, R>,257 H<E3, MergePath<BasePath, P3>, I2, R>,258 H<E4, MergePath<BasePath, P4>, I3, R>,259 H<E5, MergePath<BasePath, P5>, I4, R>455 H<E2, MergedPath, I>,456 H<E3, MergedPath, I2>,457 H<E4, MergedPath, I3>,458 H<E5, MergedPath, I4, R>459 ]460 ): Hono<262 E & E2 & E3 & E4 & E5,263 S & ToSchema<M, MergePath<BasePath, P>, I4['in'], MergeTypedResponseData<R>>,461 IntersectNonAnyTypes<[E, E2, E3, E4, E5]>,462 S & ToSchema<M, MergedPath, I4['in'], MergeTypedResponseData<R>>,463 BasePath464 >465466 // app.get(path, handler x5)467 <468 P extends string,270 P2 extends string = P,271 P3 extends string = P,272 P4 extends string = P,273 P5 extends string = P,274 P6 extends string = P,469 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,470 R extends HandlerResponse<any> = any,471 I extends Input = {},472 I2 extends Input = I,473 I3 extends Input = I & I2,279 I4 extends Input = I2 & I3,474 I4 extends Input = I & I2 & I3,475 I5 extends Input = I & I2 & I3 & I4,476 E2 extends Env = E,477 E3 extends Env = E,478 E4 extends Env = E,
1 unmodified line
480 E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>481 >(482 path: P,483 ...handlers: [289 H<E2, MergePath<BasePath, P2>, I, R>,290 H<E3, MergePath<BasePath, P3>, I2, R>,291 H<E4, MergePath<BasePath, P4>, I3, R>,292 H<E5, MergePath<BasePath, P5>, I4, R>,293 H<E6, MergePath<BasePath, P6>, I5, R>484 H<E2, MergedPath, I>,485 H<E3, MergedPath, I2>,486 H<E4, MergedPath, I3>,487 H<E5, MergedPath, I4>,488 H<E6, MergedPath, I5, R>489 ]490 ): Hono<296 E & E2 & E3 & E4 & E5 & E6,297 S & ToSchema<M, MergePath<BasePath, P>, I5['in'], MergeTypedResponseData<R>>,491 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>,492 S & ToSchema<M, MergedPath, I5['in'], MergeTypedResponseData<R>>,493 BasePath494 >495496 // app.get(path, handler x6)497 <498 P extends string,499 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,500 R extends HandlerResponse<any> = any,501 I extends Input = {},502 I2 extends Input = I,503 I3 extends Input = I & I2,504 I4 extends Input = I & I2 & I3,505 I5 extends Input = I & I2 & I3 & I4,506 I6 extends Input = I & I2 & I3 & I4 & I5,507 E2 extends Env = E,508 E3 extends Env = E,509 E4 extends Env = E,510 E5 extends Env = E,511 E6 extends Env = E,512 E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>513 >(514 path: P,515 ...handlers: [516 H<E2, MergedPath, I>,517 H<E3, MergedPath, I2>,518 H<E4, MergedPath, I3>,519 H<E5, MergedPath, I4>,520 H<E6, MergedPath, I5>,521 H<E7, MergedPath, I6, R>522 ]523 ): Hono<524 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>,525 S & ToSchema<M, MergedPath, I6['in'], MergeTypedResponseData<R>>,526 BasePath527 >528529 // app.get(path, handler x7)530 <531 P extends string,532 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,533 R extends HandlerResponse<any> = any,534 I extends Input = {},535 I2 extends Input = I,536 I3 extends Input = I & I2,537 I4 extends Input = I & I2 & I3,538 I5 extends Input = I & I2 & I3 & I4,539 I6 extends Input = I & I2 & I3 & I4 & I5,540 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,541 E2 extends Env = E,542 E3 extends Env = E,543 E4 extends Env = E,544 E5 extends Env = E,545 E6 extends Env = E,546 E7 extends Env = E,547 E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>548 >(549 path: P,550 ...handlers: [551 H<E2, MergedPath, I>,552 H<E3, MergedPath, I2>,553 H<E4, MergedPath, I3>,554 H<E5, MergedPath, I4>,555 H<E6, MergedPath, I5>,556 H<E7, MergedPath, I6>,557 H<E8, MergedPath, I7, R>558 ]559 ): Hono<560 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>,561 S & ToSchema<M, MergedPath, I7['in'], MergeTypedResponseData<R>>,562 BasePath563 >564565 // app.get(path, handler x8)566 <567 P extends string,568 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,569 R extends HandlerResponse<any> = any,570 I extends Input = {},571 I2 extends Input = I,572 I3 extends Input = I & I2,573 I4 extends Input = I & I2 & I3,574 I5 extends Input = I & I2 & I3 & I4,575 I6 extends Input = I & I2 & I3 & I4 & I5,576 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,577 I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7,578 E2 extends Env = E,579 E3 extends Env = E,580 E4 extends Env = E,581 E5 extends Env = E,582 E6 extends Env = E,583 E7 extends Env = E,584 E8 extends Env = E,585 E9 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>586 >(587 path: P,588 ...handlers: [589 H<E2, MergedPath, I>,590 H<E3, MergedPath, I2>,591 H<E4, MergedPath, I3>,592 H<E5, MergedPath, I4>,593 H<E6, MergedPath, I5>,594 H<E7, MergedPath, I6>,595 H<E8, MergedPath, I7>,596 H<E9, MergedPath, I8, R>597 ]598 ): Hono<599 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>,600 S & ToSchema<M, MergedPath, I8['in'], MergeTypedResponseData<R>>,601 BasePath602 >603604 // app.get(path, handler x9)605 <606 P extends string,607 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,608 R extends HandlerResponse<any> = any,609 I extends Input = {},610 I2 extends Input = I,611 I3 extends Input = I & I2,612 I4 extends Input = I & I2 & I3,613 I5 extends Input = I & I2 & I3 & I4,614 I6 extends Input = I & I2 & I3 & I4 & I5,615 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,616 I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7,617 I9 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8,618 E2 extends Env = E,619 E3 extends Env = E,620 E4 extends Env = E,621 E5 extends Env = E,622 E6 extends Env = E,623 E7 extends Env = E,624 E8 extends Env = E,625 E9 extends Env = E,626 E10 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>627 >(628 path: P,629 ...handlers: [630 H<E2, MergedPath, I>,631 H<E3, MergedPath, I2>,632 H<E4, MergedPath, I3>,633 H<E5, MergedPath, I4>,634 H<E6, MergedPath, I5>,635 H<E7, MergedPath, I6>,636 H<E8, MergedPath, I7>,637 H<E9, MergedPath, I8>,638 H<E10, MergedPath, I9, R>639 ]640 ): Hono<641 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>,642 S & ToSchema<M, MergedPath, I9['in'], MergeTypedResponseData<R>>,643 BasePath644 >645646 // app.get(path, handler x10)647 <648 P extends string,649 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,650 R extends HandlerResponse<any> = any,651 I extends Input = {},652 I2 extends Input = I,653 I3 extends Input = I & I2,654 I4 extends Input = I & I2 & I3,655 I5 extends Input = I & I2 & I3 & I4,656 I6 extends Input = I & I2 & I3 & I4 & I5,657 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,658 I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7,659 I9 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8,660 I10 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8 & I9,661 E2 extends Env = E,662 E3 extends Env = E,663 E4 extends Env = E,664 E5 extends Env = E,665 E6 extends Env = E,666 E7 extends Env = E,667 E8 extends Env = E,668 E9 extends Env = E,669 E10 extends Env = E,670 E11 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>671 >(672 path: P,673 ...handlers: [674 H<E2, MergedPath, I>,675 H<E3, MergedPath, I2>,676 H<E4, MergedPath, I3>,677 H<E5, MergedPath, I4>,678 H<E6, MergedPath, I5>,679 H<E7, MergedPath, I6>,680 H<E8, MergedPath, I7>,681 H<E9, MergedPath, I8>,682 H<E10, MergedPath, I9>,683 H<E11, MergedPath, I10, R>684 ]685 ): Hono<686 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11]>,687 S & ToSchema<M, MergedPath, I10['in'], MergeTypedResponseData<R>>,688 BasePath689 >690691 // app.get(path, ...handlers[])692 <P extends string, I extends Input = {}, R extends HandlerResponse<any> = any>(693 path: P,694 ...handlers: H<E, MergePath<BasePath, P>, I, R>[]
33 unmodified lines
728 E extends Env = Env,729 S extends Schema = {},730 BasePath extends string = '/'731> {342 // app.on(method, path, handler, handler)732 // app.on(method, path, handler)733 <734 M extends string,735 P extends string,346 P2 extends string = P,347 P3 extends string = P,736 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,737 R extends HandlerResponse<any> = any,738 I extends Input = {},739 E2 extends Env = E740 >(741 method: M,742 path: P,743 handler: H<E2, MergedPath, I, R>744 ): Hono<745 IntersectNonAnyTypes<[E, E2]>,746 S & ToSchema<M, MergedPath, I['in'], MergeTypedResponseData<R>>,747 BasePath748 >749750 // app.on(method, path, handler x2)751 <752 M extends string,753 P extends string,754 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,755 R extends HandlerResponse<any> = any,756 I extends Input = {},757 I2 extends Input = I,758 E2 extends Env = E,759 E3 extends Env = IntersectNonAnyTypes<[E, E2]>760 >(761 method: M,762 path: P,355 ...handlers: [H<E2, MergePath<BasePath, P2>, I, R>, H<E3, MergePath<BasePath, P3>, I, R>]356 ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I['in'], MergeTypedResponseData<R>>, BasePath>763 ...handlers: [H<E2, MergedPath, I>, H<E3, MergedPath, I2, R>]764 ): Hono<765 IntersectNonAnyTypes<[E, E2, E3]>,766 S & ToSchema<M, MergedPath, I2['in'], MergeTypedResponseData<R>>,767 BasePath768 >769358 // app.get(method, path, handler x3)770 // app.on(method, path, handler x3)771 <772 M extends string,773 P extends string,362 P2 extends string = P,363 P3 extends string = P,364 P4 extends string = P,774 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,775 R extends HandlerResponse<any> = any,776 I extends Input = {},777 I2 extends Input = I,778 I3 extends Input = I & I2,
2 unmodified lines
781 E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>782 >(783 method: M,784 path: P,375 ...handlers: [376 H<E2, MergePath<BasePath, P2>, I, R>,377 H<E3, MergePath<BasePath, P3>, I2, R>,378 H<E4, MergePath<BasePath, P4>, I3, R>379 ]380 ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I3['in'], MergeTypedResponseData<R>>, BasePath>381 // app.get(method, path, handler x4)785 ...handlers: [H<E2, MergedPath, I>, H<E3, MergedPath, I2>, H<E4, MergedPath, I3, R>]786 ): Hono<787 IntersectNonAnyTypes<[E, E2, E3, E4]>,788 S & ToSchema<M, MergedPath, I3['in'], MergeTypedResponseData<R>>,789 BasePath790 >791792 // app.on(method, path, handler x4)793 <794 M extends string,795 P extends string,385 P2 extends string = P,386 P3 extends string = P,387 P4 extends string = P,388 P5 extends string = P,796 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,797 R extends HandlerResponse<any> = any,798 I extends Input = {},799 I2 extends Input = I,800 I3 extends Input = I & I2,
5 unmodified lines
806 >(807 method: M,808 path: P,809 ...handlers: [402 H<E2, MergePath<BasePath, P2>, I, R>,403 H<E3, MergePath<BasePath, P3>, I2, R>,404 H<E4, MergePath<BasePath, P4>, I3, R>,405 H<E5, MergePath<BasePath, P5>, I4, R>810 H<E2, MergedPath, I>,811 H<E3, MergedPath, I2>,812 H<E4, MergedPath, I3>,813 H<E5, MergedPath, I4, R>814 ]407 ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I4['in'], MergeTypedResponseData<R>>, BasePath>815 ): Hono<816 IntersectNonAnyTypes<[E, E2, E3, E4, E5]>,817 S & ToSchema<M, MergedPath, I4['in'], MergeTypedResponseData<R>>,818 BasePath819 >820409 // app.get(method, path, handler x5)821 // app.on(method, path, handler x5)822 <823 M extends string,824 P extends string,413 P2 extends string = P,414 P3 extends string = P,415 P4 extends string = P,416 P5 extends string = P,417 P6 extends string = P,825 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,826 R extends HandlerResponse<any> = any,827 I extends Input = {},828 I2 extends Input = I,829 I3 extends Input = I & I2,
7 unmodified lines
837 >(838 method: M,839 path: P,840 ...handlers: [433 H<E2, MergePath<BasePath, P2>, I, R>,434 H<E3, MergePath<BasePath, P3>, I2, R>,435 H<E4, MergePath<BasePath, P4>, I3, R>,436 H<E5, MergePath<BasePath, P5>, I4, R>,437 H<E6, MergePath<BasePath, P6>, I5, R>841 H<E2, MergedPath, I>,842 H<E3, MergedPath, I2>,843 H<E4, MergedPath, I3>,844 H<E5, MergedPath, I4>,845 H<E6, MergedPath, I5, R>846 ]439 ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I5['in'], MergeTypedResponseData<R>>, BasePath>847 ): Hono<848 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>,849 S & ToSchema<M, MergedPath, I5['in'], MergeTypedResponseData<R>>,850 BasePath851 >852853 // app.on(method, path, handler x6)854 <855 M extends string,856 P extends string,857 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,858 R extends HandlerResponse<any> = any,859 I extends Input = {},860 I2 extends Input = I,861 I3 extends Input = I & I2,862 I4 extends Input = I & I2 & I3,863 I5 extends Input = I & I2 & I3 & I4,864 I6 extends Input = I & I2 & I3 & I4 & I5,865 E2 extends Env = E,866 E3 extends Env = E,867 E4 extends Env = E,868 E5 extends Env = E,869 E6 extends Env = E,870 E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>871 >(872 method: M,873 path: P,874 ...handlers: [875 H<E2, MergedPath, I>,876 H<E3, MergedPath, I2>,877 H<E4, MergedPath, I3>,878 H<E5, MergedPath, I4>,879 H<E6, MergedPath, I5>,880 H<E7, MergedPath, I6, R>881 ]882 ): Hono<883 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>,884 S & ToSchema<M, MergedPath, I6['in'], MergeTypedResponseData<R>>,885 BasePath886 >887888 // app.on(method, path, handler x7)889 <890 M extends string,891 P extends string,892 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,893 R extends HandlerResponse<any> = any,894 I extends Input = {},895 I2 extends Input = I,896 I3 extends Input = I & I2,897 I4 extends Input = I & I2 & I3,898 I5 extends Input = I & I2 & I3 & I4,899 I6 extends Input = I & I2 & I3 & I4 & I5,900 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,901 E2 extends Env = E,902 E3 extends Env = E,903 E4 extends Env = E,904 E5 extends Env = E,905 E6 extends Env = E,906 E7 extends Env = E,907 E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>908 >(909 method: M,910 path: P,911 ...handlers: [912 H<E2, MergedPath, I>,913 H<E3, MergedPath, I2>,914 H<E4, MergedPath, I3>,915 H<E5, MergedPath, I4>,916 H<E6, MergedPath, I5>,917 H<E7, MergedPath, I6>,918 H<E8, MergedPath, I7, R>919 ]920 ): Hono<921 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>,922 S & ToSchema<M, MergedPath, I7['in'], MergeTypedResponseData<R>>,923 BasePath924 >925926 // app.on(method, path, handler x8)927 <928 M extends string,929 P extends string,930 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,931 R extends HandlerResponse<any> = any,932 I extends Input = {},933 I2 extends Input = I,934 I3 extends Input = I & I2,935 I4 extends Input = I & I2 & I3,936 I5 extends Input = I & I2 & I3 & I4,937 I6 extends Input = I & I2 & I3 & I4 & I5,938 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,939 I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7,940 E2 extends Env = E,941 E3 extends Env = E,942 E4 extends Env = E,943 E5 extends Env = E,944 E6 extends Env = E,945 E7 extends Env = E,946 E8 extends Env = E,947 E9 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>948 >(949 method: M,950 path: P,951 ...handlers: [952 H<E2, MergedPath, I>,953 H<E3, MergedPath, I2>,954 H<E4, MergedPath, I3>,955 H<E5, MergedPath, I4>,956 H<E6, MergedPath, I5>,957 H<E7, MergedPath, I6>,958 H<E8, MergedPath, I7>,959 H<E9, MergedPath, I8, R>960 ]961 ): Hono<962 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>,963 S & ToSchema<M, MergedPath, I8['in'], MergeTypedResponseData<R>>,964 BasePath965 >966967 // app.on(method, path, handler x9)968 <969 M extends string,970 P extends string,971 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,972 R extends HandlerResponse<any> = any,973 I extends Input = {},974 I2 extends Input = I,975 I3 extends Input = I & I2,976 I4 extends Input = I & I2 & I3,977 I5 extends Input = I & I2 & I3 & I4,978 I6 extends Input = I & I2 & I3 & I4 & I5,979 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,980 I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7,981 I9 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8,982 E2 extends Env = E,983 E3 extends Env = E,984 E4 extends Env = E,985 E5 extends Env = E,986 E6 extends Env = E,987 E7 extends Env = E,988 E8 extends Env = E,989 E9 extends Env = E,990 E10 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>991 >(992 method: M,993 path: P,994 ...handlers: [995 H<E2, MergedPath, I>,996 H<E3, MergedPath, I2>,997 H<E4, MergedPath, I3>,998 H<E5, MergedPath, I4>,999 H<E6, MergedPath, I5>,1000 H<E7, MergedPath, I6>,1001 H<E8, MergedPath, I7>,1002 H<E9, MergedPath, I8>,1003 H<E10, MergedPath, I9, R>1004 ]1005 ): Hono<1006 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>,1007 S & ToSchema<M, MergedPath, I9['in'], MergeTypedResponseData<R>>,1008 BasePath1009 >10101011 // app.on(method, path, handler x10)1012 <1013 M extends string,1014 P extends string,1015 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1016 I extends Input = {},1017 I2 extends Input = I,1018 I3 extends Input = I & I2,1019 I4 extends Input = I & I2 & I3,1020 I5 extends Input = I & I2 & I3 & I4,1021 I6 extends Input = I & I2 & I3 & I4 & I5,1022 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,1023 I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7,1024 I9 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8,1025 I10 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8 & I9,1026 E2 extends Env = E,1027 E3 extends Env = E,1028 E4 extends Env = E,1029 E5 extends Env = E,1030 E6 extends Env = E,1031 E7 extends Env = E,1032 E8 extends Env = E,1033 E9 extends Env = E,1034 E10 extends Env = E,1035 E11 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>1036 >(1037 method: M,1038 path: P,1039 ...handlers: [1040 H<E2, MergedPath, I>,1041 H<E3, MergedPath, I2>,1042 H<E4, MergedPath, I3>,1043 H<E5, MergedPath, I4>,1044 H<E6, MergedPath, I5>,1045 H<E7, MergedPath, I6>,1046 H<E8, MergedPath, I7>,1047 H<E9, MergedPath, I8>,1048 H<E10, MergedPath, I9>,1049 H<E11, MergedPath, I10>1050 ]1051 ): Hono<1052 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11]>,1053 S & ToSchema<M, MergedPath, I10['in'], MergeTypedResponseData<HandlerResponse<any>>>,1054 BasePath1055 >10561057 // app.get(method, path, ...handler)1058 <M extends string, P extends string, R extends HandlerResponse<any> = any, I extends Input = {}>(1059 method: M,1060 path: P,1061 ...handlers: H<E, MergePath<BasePath, P>, I, R>[]1062 ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I['in'], MergeTypedResponseData<R>>, BasePath>10631064 // app.get(method[], path, handler)1065 <1066 Ms extends string[],1067 P extends string,1068 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1069 R extends HandlerResponse<any> = any,1070 I extends Input = {},1071 E2 extends Env = E1072 >(1073 methods: Ms,1074 path: P,1075 handler: H<E2, MergedPath, I, R>1076 ): Hono<1077 IntersectNonAnyTypes<[E, E2]>,1078 S & ToSchema<Ms[number], MergedPath, I['in'], MergeTypedResponseData<R>>,1079 BasePath1080 >10811082 // app.get(method[], path, handler x2)1083 <1084 Ms extends string[],1085 P extends string,1086 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1087 R extends HandlerResponse<any> = any,1088 I extends Input = {},1089 I2 extends Input = I,1090 E2 extends Env = E,1091 E3 extends Env = IntersectNonAnyTypes<[E, E2]>1092 >(1093 methods: Ms,1094 path: P,1095 ...handlers: [H<E2, MergedPath, I>, H<E3, MergedPath, I2, R>]1096 ): Hono<1097 IntersectNonAnyTypes<[E, E2, E3]>,1098 S & ToSchema<Ms[number], MergedPath, I2['in'], MergeTypedResponseData<R>>,1099 BasePath1100 >11011102 // app.get(method[], path, handler x3)1103 <1104 Ms extends string[],1105 P extends string,1106 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1107 R extends HandlerResponse<any> = any,1108 I extends Input = {},1109 I2 extends Input = I,1110 I3 extends Input = I & I2,1111 E2 extends Env = E,1112 E3 extends Env = E,1113 E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>1114 >(1115 methods: Ms,1116 path: P,1117 ...handlers: [H<E2, MergedPath, I>, H<E3, MergedPath, I2>, H<E4, MergedPath, I3, R>]1118 ): Hono<1119 IntersectNonAnyTypes<[E, E2, E3, E4]>,1120 S & ToSchema<Ms[number], MergedPath, I3['in'], MergeTypedResponseData<R>>,1121 BasePath1122 >11231124 // app.get(method[], path, handler x4)1125 <1126 Ms extends string[],1127 P extends string,1128 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1129 R extends HandlerResponse<any> = any,1130 I extends Input = {},1131 I2 extends Input = I,1132 I3 extends Input = I & I2,1133 I4 extends Input = I & I2 & I3,1134 E2 extends Env = E,1135 E3 extends Env = E,1136 E4 extends Env = E,1137 E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>1138 >(1139 methods: Ms,1140 path: P,1141 ...handlers: [1142 H<E2, MergedPath, I>,1143 H<E3, MergedPath, I2>,1144 H<E4, MergedPath, I3>,1145 H<E5, MergedPath, I4, R>1146 ]1147 ): Hono<1148 IntersectNonAnyTypes<[E, E2, E3, E4, E5]>,1149 S & ToSchema<Ms[number], MergedPath, I4['in'], MergeTypedResponseData<R>>,1150 BasePath1151 >11521153 // app.get(method[], path, handler x5)1154 <1155 Ms extends string[],1156 P extends string,1157 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1158 R extends HandlerResponse<any> = any,1159 I extends Input = {},1160 I2 extends Input = I,1161 I3 extends Input = I & I2,1162 I4 extends Input = I & I2 & I3,1163 I5 extends Input = I & I2 & I3 & I4,1164 E2 extends Env = E,1165 E3 extends Env = E,1166 E4 extends Env = E,1167 E5 extends Env = E,1168 E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>1169 >(1170 methods: Ms,1171 path: P,1172 ...handlers: [1173 H<E2, MergedPath, I>,1174 H<E3, MergedPath, I2>,1175 H<E4, MergedPath, I3>,1176 H<E5, MergedPath, I4>,1177 H<E6, MergedPath, I5, R>1178 ]1179 ): Hono<1180 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>,1181 S & ToSchema<Ms[number], MergedPath, I5['in'], MergeTypedResponseData<R>>,1182 BasePath1183 >11841185 // app.get(method[], path, handler x6)1186 <1187 Ms extends string[],1188 P extends string,1189 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1190 R extends HandlerResponse<any> = any,1191 I extends Input = {},1192 I2 extends Input = I,1193 I3 extends Input = I & I2,1194 I4 extends Input = I & I2 & I3,1195 I5 extends Input = I & I2 & I3 & I4,1196 I6 extends Input = I & I2 & I3 & I4 & I5,1197 E2 extends Env = E,1198 E3 extends Env = E,1199 E4 extends Env = E,1200 E5 extends Env = E,1201 E6 extends Env = E,1202 E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>1203 >(1204 methods: Ms,1205 path: P,1206 ...handlers: [1207 H<E2, MergedPath, I>,1208 H<E3, MergedPath, I2>,1209 H<E4, MergedPath, I3>,1210 H<E5, MergedPath, I4>,1211 H<E6, MergedPath, I5>,1212 H<E7, MergedPath, I6, R>1213 ]1214 ): Hono<1215 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>,1216 S & ToSchema<Ms[number], MergedPath, I6['in'], MergeTypedResponseData<R>>,1217 BasePath1218 >12191220 // app.get(method[], path, handler x7)1221 <1222 Ms extends string[],1223 P extends string,1224 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1225 R extends HandlerResponse<any> = any,1226 I extends Input = {},1227 I2 extends Input = I,1228 I3 extends Input = I & I2,1229 I4 extends Input = I & I2 & I3,1230 I5 extends Input = I & I2 & I3 & I4,1231 I6 extends Input = I & I2 & I3 & I4 & I5,1232 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,1233 E2 extends Env = E,1234 E3 extends Env = E,1235 E4 extends Env = E,1236 E5 extends Env = E,1237 E6 extends Env = E,1238 E7 extends Env = E,1239 E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>1240 >(1241 methods: Ms,1242 path: P,1243 ...handlers: [1244 H<E2, MergedPath, I>,1245 H<E3, MergedPath, I2>,1246 H<E4, MergedPath, I3>,1247 H<E5, MergedPath, I4>,1248 H<E6, MergedPath, I5>,1249 H<E7, MergedPath, I6>,1250 H<E8, MergedPath, I7, R>1251 ]1252 ): Hono<1253 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>,1254 S & ToSchema<Ms[number], MergedPath, I7['in'], MergeTypedResponseData<R>>,1255 BasePath1256 >12571258 // app.get(method[], path, handler x8)1259 <1260 Ms extends string[],1261 P extends string,1262 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1263 R extends HandlerResponse<any> = any,1264 I extends Input = {},1265 I2 extends Input = I,1266 I3 extends Input = I & I2,1267 I4 extends Input = I & I2 & I3,1268 I5 extends Input = I & I2 & I3 & I4,1269 I6 extends Input = I & I2 & I3 & I4 & I5,1270 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,1271 I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7,1272 E2 extends Env = E,1273 E3 extends Env = E,1274 E4 extends Env = E,1275 E5 extends Env = E,1276 E6 extends Env = E,1277 E7 extends Env = E,1278 E8 extends Env = E,1279 E9 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>1280 >(1281 methods: Ms,1282 path: P,1283 ...handlers: [1284 H<E2, MergedPath, I>,1285 H<E3, MergedPath, I2>,1286 H<E4, MergedPath, I3>,1287 H<E5, MergedPath, I4>,1288 H<E6, MergedPath, I5>,1289 H<E7, MergedPath, I6>,1290 H<E8, MergedPath, I7>,1291 H<E9, MergedPath, I8, R>1292 ]1293 ): Hono<1294 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>,1295 S & ToSchema<Ms[number], MergedPath, I8['in'], MergeTypedResponseData<R>>,1296 BasePath1297 >12981299 // app.get(method[], path, handler x9)1300 <1301 Ms extends string[],1302 P extends string,1303 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1304 I extends Input = {},1305 I2 extends Input = I,1306 I3 extends Input = I & I2,1307 I4 extends Input = I & I2 & I3,1308 I5 extends Input = I & I2 & I3 & I4,1309 I6 extends Input = I & I2 & I3 & I4 & I5,1310 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,1311 I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7,1312 I9 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8,1313 E2 extends Env = E,1314 E3 extends Env = E,1315 E4 extends Env = E,1316 E5 extends Env = E,1317 E6 extends Env = E,1318 E7 extends Env = E,1319 E8 extends Env = E,1320 E9 extends Env = E,1321 E10 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>1322 >(1323 methods: Ms,1324 path: P,1325 ...handlers: [1326 H<E2, MergedPath, I>,1327 H<E3, MergedPath, I2>,1328 H<E4, MergedPath, I3>,1329 H<E5, MergedPath, I4>,1330 H<E6, MergedPath, I5>,1331 H<E7, MergedPath, I6>,1332 H<E8, MergedPath, I7>,1333 H<E9, MergedPath, I8>,1334 H<E10, MergedPath, I9>1335 ]1336 ): Hono<1337 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>,1338 S & ToSchema<Ms[number], MergedPath, I9['in'], MergeTypedResponseData<HandlerResponse<any>>>,1339 BasePath1340 >13411342 // app.get(method[], path, handler x10)1343 <1344 Ms extends string[],1345 P extends string,1346 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1347 I extends Input = {},1348 I2 extends Input = I,1349 I3 extends Input = I & I2,1350 I4 extends Input = I & I2 & I3,1351 I5 extends Input = I & I2 & I3 & I4,1352 I6 extends Input = I & I2 & I3 & I4 & I5,1353 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,1354 I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7,1355 I9 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8,1356 I10 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8 & I9,1357 E2 extends Env = E,1358 E3 extends Env = E,1359 E4 extends Env = E,1360 E5 extends Env = E,1361 E6 extends Env = E,1362 E7 extends Env = E,1363 E8 extends Env = E,1364 E9 extends Env = E,1365 E10 extends Env = E,1366 E11 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>1367 >(1368 methods: Ms,1369 path: P,1370 ...handlers: [1371 H<E2, MergedPath, I>,1372 H<E3, MergedPath, I2>,1373 H<E4, MergedPath, I3>,1374 H<E5, MergedPath, I4>,1375 H<E6, MergedPath, I5>,1376 H<E7, MergedPath, I6>,1377 H<E8, MergedPath, I7>,1378 H<E9, MergedPath, I8>,1379 H<E10, MergedPath, I9>,1380 H<E11, MergedPath, I10>1381 ]1382 ): Hono<1383 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11]>,1384 S & ToSchema<Ms[number], MergedPath, I10['in'], MergeTypedResponseData<HandlerResponse<any>>>,1385 BasePath1386 >13871388 // app.on(method[], path, ...handler)1389 <P extends string, R extends HandlerResponse<any> = any, I extends Input = {}>(1390 methods: string[],1391 path: P,
67 unmodified lines
1459////// //////1460////////////////////////////////////////14611462export type TypedResponse<T = unknown> = {522 response: Response | Promise<Response>1463 data: T1464 format: 'json' // Currently, support only `json` with `c.jsonT()`525 status: StatusCode1465}14661467type ExtractResponseData<T> = T extends Promise<infer T2>1468 ? T2 extends TypedResponse<infer U>
89 unmodified lines
modified:runtime_tests/deno-jsx/jsx.test.tsx+1 added
68 unmodified lines
69 `<template><h1>Hello</h1></template><script>70((d,c,n) => {71c=d.currentScript.previousSibling72d=d.getElementById('H:0')73if(!d)return74do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')75d.replaceWith(c.content)76})(document)77</script>`,
2 unmodified lines
modified:runtime_tests/lambda/index.test.ts+121 added-15 removed
1import { Readable } from 'stream'2import type {3 ApiGatewayRequestContext,4 LambdaFunctionUrlRequestContext,4 ApiGatewayRequestContextV2,5} from '../../src/adapter/aws-lambda/custom-context'6import { handle, streamHandle } from '../../src/adapter/aws-lambda/handler'7import type { LambdaEvent } from '../../src/adapter/aws-lambda/handler'8import type { LambdaContext } from '../../src/adapter/aws-lambda/types'9import { getCookie, setCookie } from '../../src/helper/cookie'10import { streamSSE } from '../../src/helper/streaming'11import { Hono } from '../../src/hono'12import { basicAuth } from '../../src/middleware/basic-auth'13import './mock'1415type Bindings = {16 event: LambdaEvent17 lambdaContext: LambdaContext16 requestContext: ApiGatewayRequestContext | LambdaFunctionUrlRequestContext18 requestContext: ApiGatewayRequestContext | ApiGatewayRequestContextV219}2019const testLambdaFunctionUrlRequestContext = {21const testApiGatewayRequestContextV2 = {22 accountId: '123456789012',23 apiId: 'urlid',24 authentication: null,25 authorizer: {
51 unmodified lines
77 const password = 'hono-password-a'78 app.use('/auth/*', basicAuth({ username, password }))79 app.get('/auth/abc', (c) => c.text('Good Night Lambda!'))8081 app.get('/lambda-event', (c) => {82 const event = c.env.event83 return c.json(event)84 })8586 app.get('/lambda-context', (c) => {87 const fnctx = c.env.lambdaContext88 return c.json(fnctx)89 })9091 app.get('/custom-context/v1/apigw', (c) => {92 const lambdaContext = c.env.requestContext93 return c.json(lambdaContext)94 })9596 app.get('/custom-context/apigw', (c) => {97 const lambdaContext = c.env.event.requestContext98 return c.json(lambdaContext)99 })100101 app.get('/custom-context/v1/lambda', (c) => {102 const lambdaContext = c.env.requestContext103 return c.json(lambdaContext)104 })105106 app.get('/custom-context/lambda', (c) => {90 const lambdaContext = c.env.requestContext107 const lambdaContext = c.env.event.requestContext108 return c.json(lambdaContext)109 })110111 const testCookie1 = {
51 unmodified lines
163 stage: '$default',164 customProperty: 'customValue',165 }166167 const testApiGatewayRequestContextV2 = {168 accountId: '123456789012',169 apiId: 'urlid',170 authentication: null,171 authorizer: {172 iam: {173 accessKey: 'AKIA...',174 accountId: '111122223333',175 callerId: 'AIDA...',176 cognitoIdentity: null,177 principalOrgId: null,178 userArn: 'arn:aws:iam::111122223333:user/example-user',179 userId: 'AIDA...',180 },181 },182 domainName: 'example.com',183 domainPrefix: '<url-id>',184 http: {185 method: 'POST',186 path: '/my/path',187 protocol: 'HTTP/1.1',188 sourceIp: '123.123.123.123',189 userAgent: 'agent',190 },191 requestId: 'id',192 routeKey: '$default',193 stage: '$default',194 time: '12/Mar/2020:19:03:58 +0000',195 timeEpoch: 1583348638390,196 customProperty: 'customValue',197 }198199 const testALBRequestContext = {200 elb: {201 targetGroupArn:202 'arn:aws:elasticloadbalancing:us-east-1:123456789012:targetgroup/lambda-279XGJDqGZ5rsrHC2Fjr/49e9d65c45c6791a',203 },204 }205206 it('Should handle a GET request and return a 200 response', async () => {207 const event = {208 version: '1.0',209 resource: '/',210 httpMethod: 'GET',211 headers: { 'content-type': 'text/plain' },212 path: '/',213 body: null,
9 unmodified lines
223 })224225 it('Should handle a GET request and return a 200 response with binary', async () => {226 const event = {227 version: '1.0',228 resource: '/binary',229 httpMethod: 'GET',230 headers: {},231 path: '/binary',232 body: null,
9 unmodified lines
242 })243244 it('Should handle a GET request and return a 200 response (LambdaFunctionUrlEvent)', async () => {245 const event = {246 version: '2.0',247 routeKey: '$default',248 headers: { 'content-type': 'text/plain' },249 rawPath: '/',250 rawQueryString: '',251 body: null,252 isBase64Encoded: false,191 requestContext: testLambdaFunctionUrlRequestContext,253 requestContext: testApiGatewayRequestContextV2,254 }255194 testLambdaFunctionUrlRequestContext.http.method = 'GET'256 testApiGatewayRequestContextV2.http.method = 'GET'257258 const response = await handler(event)259 expect(response.statusCode).toBe(200)260 expect(response.body).toBe('Hello Lambda!')261 expect(response.headers['content-type']).toMatch(/^text\/plain/)262 expect(response.isBase64Encoded).toBe(false)263 })264265 it('Should handle a GET request and return a 200 response (ALBEvent)', async () => {266 const event = {267 headers: { 'content-type': 'text/plain' },268 httpMethod: 'GET',269 path: '/',270 queryStringParameters: {271 query: '1234ABCD',272 },273 body: null,274 isBase64Encoded: false,275 requestContext: testALBRequestContext,276 }277278 const response = await handler(event)279 expect(response.statusCode).toBe(200)280 expect(response.body).toBe('Hello Lambda!')281 expect(response.headers['content-type']).toMatch(/^text\/plain/)282 expect(response.isBase64Encoded).toBe(false)283 })284285 it('Should handle a GET request and return a 404 response', async () => {286 const event = {287 version: '1.0',288 resource: '/nothing',289 httpMethod: 'GET',290 headers: { 'content-type': 'text/plain' },291 path: '/nothing',292 body: null,
8 unmodified lines
301 it('Should handle a POST request and return a 200 response', async () => {302 const searchParam = new URLSearchParams()303 searchParam.append('message', 'Good Morning Lambda!')304 const event = {305 version: '1.0',306 resource: '/post',307 httpMethod: 'POST',308 headers: {309 'Content-Type': 'application/x-www-form-urlencoded',310 },
11 unmodified lines
322 it('Should handle a POST request and return a 200 response (LambdaFunctionUrlEvent)', async () => {323 const searchParam = new URLSearchParams()324 searchParam.append('message', 'Good Morning Lambda!')325 const event = {326 version: '2.0',327 routeKey: '$default',328 headers: {329 'Content-Type': 'application/x-www-form-urlencoded',330 },331 rawPath: '/post',332 rawQueryString: '',333 body: Buffer.from(searchParam.toString()).toString('base64'),334 isBase64Encoded: true,247 requestContext: testLambdaFunctionUrlRequestContext,335 requestContext: testApiGatewayRequestContextV2,336 }337250 testLambdaFunctionUrlRequestContext.http.method = 'POST'338 testApiGatewayRequestContextV2.http.method = 'POST'339340 const response = await handler(event)341 expect(response.statusCode).toBe(200)342 expect(response.body).toBe('Good Morning Lambda!')
2 unmodified lines
345 it('Should handle a POST request with binary and return a 200 response', async () => {346 const array = new Uint8Array([0xc0, 0xff, 0xee])347 const buffer = Buffer.from(array)348 const event = {349 version: '1.0',350 resource: '/post/binary',351 httpMethod: 'POST',352 headers: {353 'Content-Type': 'application/x-www-form-urlencoded',354 },
9 unmodified lines
364 })365366 it('Should handle a request and return a 401 response with Basic auth', async () => {367 const event = {368 version: '1.0',369 resource: '/auth/abc',370 httpMethod: 'GET',371 headers: {372 'Content-Type': 'plain/text',373 },
9 unmodified lines
383384 it('Should handle a request and return a 200 response with Basic auth', async () => {385 const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'386 const event = {387 version: '1.0',388 resource: '/auth/abc',389 httpMethod: 'GET',390 headers: {391 'Content-Type': 'plain/text',392 Authorization: `Basic ${credential}`,
10 unmodified lines
403 })404405 it('Should handle a GET request and return custom context', async () => {406 const event = {407 version: '1.0',408 resource: '/custom-context/apigw',409 httpMethod: 'GET',410 headers: { 'content-type': 'application/json' },411 path: '/custom-context/apigw',412 body: null,
7 unmodified lines
420 })421422 it('Should handle a GET request and context', async () => {423 const event = {424 version: '1.0',425 resource: '/lambda-context',426 httpMethod: 'GET',427 headers: { 'content-type': 'application/json' },428 path: '/lambda-context',429 body: null,
19 unmodified lines
449 })450451 it('Should handle a POST request and return a 200 response with cookies set (APIGatewayProxyEvent V1 and V2)', async () => {452 const apiGatewayEvent = {453 version: '1.0',454 resource: '/cookie',455 httpMethod: 'POST',456 headers: { 'content-type': 'text/plain' },457 path: '/cookie',458 body: null,
9 unmodified lines
468 testCookie2.serialized,469 ])470471 const apiGatewayEventV2 = {472 version: '2.0',473 routeKey: '$default',474 httpMethod: 'POST',475 headers: { 'content-type': 'text/plain' },476 rawPath: '/cookie',477 rawQueryString: '',478 body: null,479 isBase64Encoded: false,378 requestContext: testApiGatewayRequestContext,480 requestContext: testApiGatewayRequestContextV2,481 }482483 const apiGatewayResponseV2 = await handler(apiGatewayEventV2)484
5 unmodified lines
490 })491492 it('Should handle a POST request and return a 200 response if cookies match (APIGatewayProxyEvent V1 and V2)', async () => {493 const apiGatewayEvent = {494 version: '1.0',495 resource: '/cookie',496 httpMethod: 'GET',497 headers: {498 'content-type': 'text/plain',499 cookie: [testCookie1.serialized, testCookie2.serialized].join('; '),
11 unmodified lines
511 expect(apiGatewayResponse.headers['content-type']).toMatch(/^text\/plain/)512 expect(apiGatewayResponse.isBase64Encoded).toBe(false)513514 const apiGatewayEventV2 = {411 httpMethod: 'GET',515 version: '2.0',516 routeKey: '$default',517 headers: { 'content-type': 'text/plain' },518 rawPath: '/cookie',519 cookies: [testCookie1.serialized, testCookie2.serialized],520 rawQueryString: '',521 body: null,522 isBase64Encoded: false,418 requestContext: testApiGatewayRequestContext,523 requestContext: testApiGatewayRequestContextV2,524 }525 testApiGatewayRequestContextV2.http.method = 'GET'526527 const apiGatewayResponseV2 = await handler(apiGatewayEventV2)528529 expect(apiGatewayResponseV2.statusCode).toBe(200)
40 unmodified lines
570 rawPath: '/stream/text',571 rawQueryString: '',572 body: null,573 isBase64Encoded: false,468 requestContext: testLambdaFunctionUrlRequestContext,574 requestContext: testApiGatewayRequestContextV2,575 }576471 testLambdaFunctionUrlRequestContext.http.method = 'GET'577 testApiGatewayRequestContextV2.http.method = 'GET'578579 const mockReadableStream = new Readable({580 // eslint-disable-next-line @typescript-eslint/no-empty-function581 read() {},
20 unmodified lines
602 rawPath: '/sse',603 rawQueryString: '',604 body: null,605 isBase64Encoded: false,500 requestContext: testLambdaFunctionUrlRequestContext,606 requestContext: testApiGatewayRequestContextV2,607 }608503 testLambdaFunctionUrlRequestContext.http.method = 'GET'609 testApiGatewayRequestContextV2.http.method = 'GET'610611 const mockReadableStream = new Readable({612 // eslint-disable-next-line @typescript-eslint/no-empty-function613 read() {},
42 unmodified lines
modified:src/adapter/aws-lambda/custom-context.ts+12 added-1 removed
59 unmodified lines
60 userId: string61 }62}6364export interface LambdaFunctionUrlRequestContext {64export interface ApiGatewayRequestContextV2 {65 accountId: string66 apiId: string67 authentication: null68 authorizer: Authorizer
11 unmodified lines
80 stage: string81 time: string82 timeEpoch: number83}8485export interface ALBRequestContext {86 elb: {87 targetGroupArn: string88 }89}9091/**92 * @deprecated Use ApiGatewayRequestContextV2 instead.93 */94export type LambdaFunctionUrlRequestContext = ApiGatewayRequestContextV2
modified:src/adapter/aws-lambda/handler.ts+60 added-58 removed
2 unmodified lines
3import type { Hono } from '../../hono'4import type { Env, Schema } from '../../types'56import { encodeBase64 } from '../../utils/encode'7import type { ApiGatewayRequestContext, LambdaFunctionUrlRequestContext } from './custom-context'7import type {8 ApiGatewayRequestContext,9 ApiGatewayRequestContextV2,10 ALBRequestContext,11} from './custom-context'12import type { LambdaContext } from './types'1314// eslint-disable-next-line @typescript-eslint/ban-ts-comment15// @ts-ignore16globalThis.crypto ??= crypto1718export type LambdaEvent = APIGatewayProxyEvent | APIGatewayProxyEventV2 | ALBProxyEvent1914// When calling Lambda directly through function urls20// When calling HTTP API or Lambda directly through function urls21export interface APIGatewayProxyEventV2 {16 httpMethod: string22 version: string23 routeKey: string24 headers: Record<string, string | undefined>25 cookies?: string[]26 rawPath: string27 rawQueryString: string28 body: string | null29 isBase64Encoded: boolean23 requestContext: ApiGatewayRequestContext30 requestContext: ApiGatewayRequestContextV231 queryStringParameters?: {32 [name: string]: string | undefined33 }34 pathParameters?: {35 [name: string]: string | undefined36 }37 stageVariables?: {38 [name: string]: string | undefined39 }40}4126// When calling Lambda through an API Gateway or an ELB42// When calling Lambda through an API Gateway43export interface APIGatewayProxyEvent {44 version: string45 httpMethod: string46 headers: Record<string, string | undefined>47 multiValueHeaders?: {48 [headerKey: string]: string[]
2 unmodified lines
51 body: string | null52 isBase64Encoded: boolean53 queryStringParameters?: Record<string, string | undefined>54 requestContext: ApiGatewayRequestContext55 resource: string56 multiValueQueryStringParameters?: {57 [parameterKey: string]: string[]58 }59 pathParameters?: Record<string, string>60 stageVariables?: Record<string, string>61}6240// When calling Lambda through an Lambda Function URLs41export interface LambdaFunctionUrlEvent {63// When calling Lambda through an Application Load Balancer64export interface ALBProxyEvent {65 httpMethod: string66 headers: Record<string, string | undefined>43 rawPath: string44 rawQueryString: string67 path: string68 body: string | null69 isBase64Encoded: boolean70 queryStringParameters?: Record<string, string | undefined>47 requestContext: LambdaFunctionUrlRequestContext71 requestContext: ALBRequestContext72}7374export interface APIGatewayProxyResult {75 statusCode: number76 statusDescription?: string77 body: string78 headers: Record<string, string>79 cookies?: string[]80 multiValueHeaders?: {
2 unmodified lines
83 isBase64Encoded: boolean84}8586const getRequestContext = (62 event: APIGatewayProxyEvent | APIGatewayProxyEventV2 | LambdaFunctionUrlEvent63): ApiGatewayRequestContext | LambdaFunctionUrlRequestContext => {87 event: LambdaEvent88): ApiGatewayRequestContext | ApiGatewayRequestContextV2 | ALBRequestContext => {89 return event.requestContext90}9192const streamToNodeStream = async (
15 unmodified lines
108>(109 app: Hono<E, S, BasePath>110) => {111 return awslambda.streamifyResponse(87 async (88 event: APIGatewayProxyEvent | APIGatewayProxyEventV2 | LambdaFunctionUrlEvent,89 responseStream: NodeJS.WritableStream,90 context: LambdaContext91 ) => {112 async (event: LambdaEvent, responseStream: NodeJS.WritableStream, context: LambdaContext) => {113 try {114 const req = createRequest(event)115 const requestContext = getRequestContext(event)116117 const res = await app.fetch(req, {118 event,119 requestContext,120 context,121 })122
25 unmodified lines
148export const handle = <E extends Env = Env, S extends Schema = {}, BasePath extends string = '/'>(149 app: Hono<E, S, BasePath>150) => {151 return async (130 event: APIGatewayProxyEvent | APIGatewayProxyEventV2 | LambdaFunctionUrlEvent,152 event: LambdaEvent,153 lambdaContext?: LambdaContext154 ): Promise<APIGatewayProxyResult> => {155 const req = createRequest(event)156 const requestContext = getRequestContext(event)157158 const res = await app.fetch(req, {159 event,160 requestContext,161 lambdaContext,162 })163164 return createResult(event, res)165 }166}167145const createResult = async (146 event: APIGatewayProxyEvent | APIGatewayProxyEventV2 | LambdaFunctionUrlEvent,147 res: Response148): Promise<APIGatewayProxyResult> => {168const createResult = async (event: LambdaEvent, res: Response): Promise<APIGatewayProxyResult> => {169 const contentType = res.headers.get('content-type')170 let isBase64Encoded = contentType && isContentTypeBinary(contentType) ? true : false171172 if (!isBase64Encoded) {
22 unmodified lines
195196 return result197}198179const createRequest = (180 event: APIGatewayProxyEvent | APIGatewayProxyEventV2 | LambdaFunctionUrlEvent181) => {199const createRequest = (event: LambdaEvent) => {200 const queryString = extractQueryString(event)183 const urlPath = `https://${event.requestContext.domainName}${184 isProxyEvent(event) ? event.path : event.rawPath185 }`201 const domainName =202 event.requestContext && 'domainName' in event.requestContext203 ? event.requestContext.domainName204 : event.headers['host']205 const path = isProxyEventV2(event) ? event.rawPath : event.path206 const urlPath = `https://${domainName}${path}`207 const url = queryString ? `${urlPath}?${queryString}` : urlPath208209 const headers = new Headers()210 getCookies(event, headers)211 for (const [k, v] of Object.entries(event.headers)) {212 if (v) headers.set(k, v)213 }214194 const method = 'httpMethod' in event ? event.httpMethod : event.requestContext.http.method215 const method = isProxyEventV2(event) ? event.requestContext.http.method : event.httpMethod216 const requestInit: RequestInit = {217 headers,218 method,219 }
4 unmodified lines
224225 return new Request(url, requestInit)226}227207const extractQueryString = (208 event: APIGatewayProxyEvent | APIGatewayProxyEventV2 | LambdaFunctionUrlEvent209) => {210 if (isProxyEvent(event)) {211 return Object.entries(event.queryStringParameters || {})212 .filter(([, value]) => value)213 .map(([key, value]) => `${key}=${value}`)214 .join('&')215 }216217 return isProxyEventV2(event) ? event.rawQueryString : event.rawQueryString228const extractQueryString = (event: LambdaEvent) => {229 return isProxyEventV2(event)230 ? event.rawQueryString231 : Object.entries(event.queryStringParameters || {})232 .filter(([, value]) => value)233 .map(([key, value]) => `${key}=${value}`)234 .join('&')235}236220const getCookies = (221 event: APIGatewayProxyEvent | APIGatewayProxyEventV2 | LambdaFunctionUrlEvent,222 headers: Headers223) => {237const getCookies = (event: LambdaEvent, headers: Headers) => {238 if (isProxyEventV2(event) && Array.isArray(event.cookies)) {239 headers.set('Cookie', event.cookies.join('; '))240 }241}242229const setCookies = (230 event: APIGatewayProxyEvent | APIGatewayProxyEventV2 | LambdaFunctionUrlEvent,231 res: Response,232 result: APIGatewayProxyResult233) => {243const setCookies = (event: LambdaEvent, res: Response, result: APIGatewayProxyResult) => {244 if (res.headers.has('set-cookie')) {245 const cookies = res.headers.get('set-cookie')?.split(', ')246 if (Array.isArray(cookies)) {247 if (isProxyEventV2(event)) {
7 unmodified lines
255 }256 }257}258249const isProxyEvent = (250 event: APIGatewayProxyEvent | APIGatewayProxyEventV2 | LambdaFunctionUrlEvent251): event is APIGatewayProxyEvent => {252 return Object.prototype.hasOwnProperty.call(event, 'path')253}254255const isProxyEventV2 = (256 event: APIGatewayProxyEvent | APIGatewayProxyEventV2 | LambdaFunctionUrlEvent257): event is APIGatewayProxyEventV2 => {259const isProxyEventV2 = (event: LambdaEvent): event is APIGatewayProxyEventV2 => {260 return Object.prototype.hasOwnProperty.call(event, 'rawPath')261}262263export const isContentTypeBinary = (contentType: string) => {
11 unmodified lines
modified:src/adapter/aws-lambda/index.ts+7 added-2 removed
1// @denoify-ignore2export { handle, streamHandle } from './handler'3export type { APIGatewayProxyResult } from './handler'4export type { ApiGatewayRequestContext, LambdaFunctionUrlRequestContext } from './custom-context'3export type { APIGatewayProxyResult, LambdaEvent } from './handler'4export type {5 ApiGatewayRequestContext,6 ApiGatewayRequestContextV2,7 ALBRequestContext,8 LambdaFunctionUrlRequestContext,9} from './custom-context'10export type { LambdaContext } from './types'
modified:src/client/client.test.ts+18 added-19 removed
41 unmodified lines
42 title: string43 }44 }),45 (c) => {46 return c.jsonT({46 return c.json({47 success: true,48 message: 'dummy',49 requestContentType: 'dummy',50 requestHono: 'dummy',
80 unmodified lines
131 validator('query', () => {132 return {} as { q: string; tag: string[]; filter: string }133 }),134 (c) => {135 return c.jsonT({135 return c.json({136 q: 'fake',137 tag: ['fake'],138 filter: 'fake',139 })
7 unmodified lines
147 }148 }),149 (c) => {150 const data = c.req.valid('queries')151 return c.jsonT(data)151 return c.json(data)152 }153 )154 .put(155 '/posts/:id',
3 unmodified lines
159 }160 }),161 (c) => {162 const data = c.req.valid('form')163 return c.jsonT(data)163 return c.json(data)164 }165 )166 .get(167 '/header',
3 unmodified lines
171 }172 }),173 (c) => {174 const data = c.req.valid('header')175 return c.jsonT(data)175 return c.json(data)176 }177 )178 .get(179 '/cookie',
3 unmodified lines
183 }184 }),185 (c) => {186 const data = c.req.valid('cookie')187 return c.jsonT(data)187 return c.json(data)188 }189 )190191 const server = setupServer(
137 unmodified lines
329 name: 'dummy',330 }331 }),332 (c) =>333 c.jsonT({333 c.json({334 id: 123,335 title: 'Morning!',336 })337 )
48 unmodified lines
386 type verify = Expect<Equal<Expected, Actual['cookie']>>387 })388389 describe('Without input', () => {390 const route = app.get('/', (c) => c.jsonT({ ok: true }))390 const route = app.get('/', (c) => c.json({ ok: true }))391 type AppType = typeof route392393 it('Should infer response type the type correctly', () => {394 const client = hc<AppType>('/')
57 unmodified lines
452 }453 }454455 it('Should have correct types', async () => {456 const api = new Hono<Env>().get('/search', (c) => c.jsonT({ ok: true }))456 const api = new Hono<Env>().get('/search', (c) => c.json({ ok: true }))457 const app = new Hono<Env>().route('/api', api)458 type AppType = typeof app459 const client = hc<AppType>('http://localhost')460 const res = await client.api.search.$get()
3 unmodified lines
464 })465466 it('Should have correct types - basePath() then get()', async () => {467 const base = new Hono<Env>().basePath('/api')468 const app = base.get('/search', (c) => c.jsonT({ ok: true }))468 const app = base.get('/search', (c) => c.json({ ok: true }))469 type AppType = typeof app470 const client = hc<AppType>('http://localhost')471 const res = await client.api.search.$get()472 const data = await res.json()
1 unmodified line
474 expect(data.ok).toBe(true)475 })476477 it('Should have correct types - basePath(), route(), get()', async () => {478 const book = new Hono().get('/', (c) => c.jsonT({ ok: true }))478 const book = new Hono().get('/', (c) => c.json({ ok: true }))479 const app = new Hono().basePath('/v1').route('/book', book)480 type AppType = typeof app481 const client = hc<AppType>('http://localhost')482 const res = await client.v1.book.$get()
7 unmodified lines
490 ok: boolean491 }492 const result: Result = { ok: true }493 const base = new Hono<Env>().basePath('/api')494 const app = base.get('/search', (c) => c.jsonT(result))494 const app = base.get('/search', (c) => c.json(result))495 type AppType = typeof app496 const client = hc<AppType>('http://localhost')497 const res = await client.api.search.$get()498 const data = await res.json()
2 unmodified lines
501 })502503 it('Should not allow the incorrect JSON type', async () => {504 const app = new Hono()505 // @ts-expect-error506 const route = app.get('/api/foo', (c) => c.jsonT({ datetime: new Date() }))505 const route = app.get('/api/foo', (c) => c.json({ datetime: new Date() }))506 type AppType = typeof route507 const client = hc<AppType>('http://localhost')508 const res = await client.api.foo.$get()509 const data = await res.json()
1 unmodified line
511 })512513 describe('Multiple endpoints', () => {514 const api = new Hono()516 .get('/foo', (c) => c.jsonT({ foo: '' }))517 .post('/bar', (c) => c.jsonT({ bar: 0 }))515 .get('/foo', (c) => c.json({ foo: '' }))516 .post('/bar', (c) => c.json({ bar: 0 }))517 const app = new Hono().route('/api', api)518 type AppType = typeof app519 const client = hc<typeof app>('http://localhost')520
18 unmodified lines
539describe('Use custom fetch method', () => {540 it('Should call the custom fetch method when provided', async () => {541 const fetchMock = vi.fn()542544 const api = new Hono().get('/search', (c) => c.jsonT({ ok: true }))543 const api = new Hono().get('/search', (c) => c.json({ ok: true }))544 const app = new Hono().route('/api', api)545 type AppType = typeof app546 const client = hc<AppType>('http://localhost', { fetch: fetchMock })547 await client.api.search.$get()
4 unmodified lines
552 const fetchMock = vi.fn()553 const returnValue = new Response(null, { status: 200 })554 fetchMock.mockReturnValueOnce(returnValue)555557 const api = new Hono().get('/search', (c) => c.jsonT({ ok: true }))556 const api = new Hono().get('/search', (c) => c.json({ ok: true }))557 const app = new Hono().route('/api', api)558 type AppType = typeof app559 const client = hc<AppType>('http://localhost', { fetch: fetchMock })560 const res = await client.api.search.$get()
3 unmodified lines
564})565566describe('Use custom fetch (app.request) method', () => {567 it('Should return Response from app request method', async () => {569 const app = new Hono().get('/search', (c) => c.jsonT({ ok: true }))568 const app = new Hono().get('/search', (c) => c.json({ ok: true }))569 type AppType = typeof app570 const client = hc<AppType>('', { fetch: app.request })571 const res = await client.search.$get()572 expect(res.ok).toBe(true)
17 unmodified lines
added:src/helper/dev/index.test.ts+94 added
1import { Hono } from '../../hono'2import type { Handler, MiddlewareHandler } from '../../types'3import { inspectRoutes, showRoutes } from '.'45const namedMiddleware: MiddlewareHandler = (_, next) => next()6const namedHandler: Handler = (c) => c.text('hi')7const app = new Hono()8 .use('*', (c, next) => next())9 .get(10 '/',11 (_, next) => next(),12 (c) => c.text('hi')13 )14 .get('/named', namedMiddleware, namedHandler)15 .post('/', (c) => c.text('hi'))16 .put('/', (c) => c.text('hi'))17 .patch('/', (c) => c.text('hi'))18 .delete('/', (c) => c.text('hi'))19 .options('/', (c) => c.text('hi'))20 .get('/static', () => new Response('hi'))2122describe('inspectRoutes()', () => {23 it('should return correct data', async () => {24 expect(inspectRoutes(app)).toEqual([25 { path: '/*', method: 'ALL', name: '[middleware]', isMiddleware: true },26 { path: '/', method: 'GET', name: '[middleware]', isMiddleware: true },27 { path: '/', method: 'GET', name: '[handler]', isMiddleware: false },28 { path: '/named', method: 'GET', name: 'namedMiddleware', isMiddleware: true },29 { path: '/named', method: 'GET', name: 'namedHandler', isMiddleware: false },30 { path: '/', method: 'POST', name: '[handler]', isMiddleware: false },31 { path: '/', method: 'PUT', name: '[handler]', isMiddleware: false },32 { path: '/', method: 'PATCH', name: '[handler]', isMiddleware: false },33 { path: '/', method: 'DELETE', name: '[handler]', isMiddleware: false },34 { path: '/', method: 'OPTIONS', name: '[handler]', isMiddleware: false },35 { path: '/static', method: 'GET', name: '[handler]', isMiddleware: false },36 ])37 })38})3940describe('showRoutes()', () => {41 let logs: string[] = []4243 let originalLog: typeof console.log44 beforeAll(() => {45 originalLog = console.log46 console.log = (...args) => logs.push(...args)47 })48 afterAll(() => {49 console.log = originalLog50 })5152 beforeEach(() => {53 logs = []54 })55 it('should render simple output', async () => {56 showRoutes(app)57 expect(logs).toEqual([58 '\x1b[32mGET\x1b[0m /',59 '\x1b[32mGET\x1b[0m /named',60 '\x1b[32mPOST\x1b[0m /',61 '\x1b[32mPUT\x1b[0m /',62 '\x1b[32mPATCH\x1b[0m /',63 '\x1b[32mDELETE\x1b[0m /',64 '\x1b[32mOPTIONS\x1b[0m /',65 '\x1b[32mGET\x1b[0m /static',66 ])67 })6869 it('should render output includes handlers and middlewares', async () => {70 showRoutes(app, { verbose: true })71 expect(logs).toEqual([72 '\x1b[32mALL\x1b[0m /*',73 ' [middleware]',74 '\x1b[32mGET\x1b[0m /',75 ' [middleware]',76 ' [handler]',77 '\x1b[32mGET\x1b[0m /named',78 ' namedMiddleware',79 ' namedHandler',80 '\x1b[32mPOST\x1b[0m /',81 ' [handler]',82 '\x1b[32mPUT\x1b[0m /',83 ' [handler]',84 '\x1b[32mPATCH\x1b[0m /',85 ' [handler]',86 '\x1b[32mDELETE\x1b[0m /',87 ' [handler]',88 '\x1b[32mOPTIONS\x1b[0m /',89 ' [handler]',90 '\x1b[32mGET\x1b[0m /static',91 ' [handler]',92 ])93 })94})
added:src/helper/dev/index.ts+62 added
1import type { Hono } from '../../hono'2import type { RouterRoute } from '../../types'34interface ShowRoutesOptions {5 verbose?: boolean6}78interface RouteData {9 path: string10 method: string11 name: string12 isMiddleware: boolean13}1415const isMiddleware = (handler: Function) => handler.length > 116const handlerName = (handler: Function) => {17 return handler.name || (isMiddleware(handler) ? '[middleware]' : '[handler]')18}1920export const inspectRoutes = (hono: Hono): RouteData[] => {21 return hono.routes.map(({ path, method, handler }: RouterRoute) => ({22 path,23 method,24 name: handlerName(handler),25 isMiddleware: isMiddleware(handler),26 }))27}2829export const showRoutes = (hono: Hono, opts?: ShowRoutesOptions) => {30 const routeData: Record<string, RouteData[]> = {}31 let maxMethodLength = 032 let maxPathLength = 03334 inspectRoutes(hono)35 .filter(({ isMiddleware }) => opts?.verbose || !isMiddleware)36 .map((route) => {37 const key = `${route.method}-${route.path}`38 ;(routeData[key] ||= []).push(route)39 if (routeData[key].length > 1) {40 return41 }42 maxMethodLength = Math.max(maxMethodLength, route.method.length)43 maxPathLength = Math.max(maxPathLength, route.path.length)44 return { method: route.method, path: route.path, routes: routeData[key] }45 })46 .forEach((data) => {47 if (!data) {48 return49 }50 const { method, path, routes } = data5152 console.log(`\x1b[32m${method}\x1b[0m ${' '.repeat(maxMethodLength - method.length)} ${path}`)5354 if (!opts?.verbose) {55 return56 }5758 routes.forEach(({ name }) => {59 console.log(`${' '.repeat(maxMethodLength + 3)} ${name}`)60 })61 })62}
modified:src/helper/factory/index.test.ts+151 added-1 removed
1import { expectTypeOf } from 'vitest'2import { hc } from '../../client'3import { Hono } from '../../index'4import type { ToSchema } from '../../types'5import { validator } from '../../validator'3import { createMiddleware } from './index'6import { createMiddleware, createFactory } from './index'78describe('createMiddleware', () => {9 type Env = { Variables: { foo: string } }10 const app = new Hono<Env>()
21 unmodified lines
32 const url = client.message.$url()33 expect(url.pathname).toBe('/message')34 })35})3637describe('createHandler', () => {38 const mw = (message: string) =>39 createMiddleware(async (c, next) => {40 await next()41 c.header('x-message', message)42 })4344 describe('Basic', () => {45 const factory = createFactory()46 const app = new Hono()4748 const handlersA = factory.createHandlers((c) => {49 return c.text('A')50 })51 app.get('/a', ...handlersA)5253 const handlersB = factory.createHandlers(mw('B'), (c) => {54 return c.text('B')55 })56 app.get('/b', ...handlersB)5758 it('Should return 200 response - GET /a', async () => {59 const res = await app.request('/a')60 expect(res.status).toBe(200)61 expect(await res.text()).toBe('A')62 })6364 it('Should return 200 response with a custom header - GET /b', async () => {65 const res = await app.request('/b')66 expect(res.status).toBe(200)67 expect(res.headers.get('x-message')).toBe('B')68 expect(await res.text()).toBe('B')69 })70 })7172 describe('Types', () => {73 type Env = { Variables: { foo: string } }7475 const factory = createFactory<Env>()76 const app = new Hono<Env>()7778 const handlers = factory.createHandlers(79 validator('query', () => {80 return {81 page: '1',82 }83 }),84 (c) => {85 const foo = c.var.foo86 const { page } = c.req.valid('query')87 return c.jsonT({ page, foo })88 }89 )90 const routes = app.get('/posts', ...handlers)9192 type Expected = Hono<93 Env,94 ToSchema<95 'get',96 '/posts',97 {98 query: {99 page: string100 }101 },102 {103 page: string104 foo: string105 }106 >,107 '/'108 >109110 it('Should return correct types', () => {111 expectTypeOf(routes).toEqualTypeOf<Expected>()112 })113 })114115 // It's difficult to cover all possible patterns,116 // so these tests will only cover the minimal cases.117118 describe('Types - Complex', () => {119 type Env = { Variables: { foo: string } }120121 const factory = createFactory<Env>()122 const app = new Hono<Env>()123124 const handlers = factory.createHandlers(125 validator('header', () => {126 return {127 auth: 'token',128 }129 }),130 validator('query', () => {131 return {132 page: '1',133 }134 }),135 validator('json', () => {136 return {137 id: 123,138 }139 }),140 (c) => {141 const foo = c.var.foo142 const { auth } = c.req.valid('header')143 const { page } = c.req.valid('query')144 const { id } = c.req.valid('json')145 return c.jsonT({ auth, page, foo, id })146 }147 )148 const routes = app.get('/posts', ...handlers)149150 type Expected = Hono<151 Env,152 ToSchema<153 'get',154 '/posts',155 {156 header: {157 auth: string158 }159 } & {160 query: {161 page: string162 }163 } & {164 json: {165 id: number166 }167 },168 {169 auth: string170 page: string171 foo: string172 id: number173 }174 >,175 '/'176 >177178 it('Should return correct types', () => {179 expectTypeOf(routes).toEqualTypeOf<Expected>()180 })181 })182})
modified:src/helper/factory/index.ts+272 added-4 removed
1/* eslint-disable @typescript-eslint/no-explicit-any */1import type { Env, Input, MiddlewareHandler } from '../../types'2import type { Env, Input, MiddlewareHandler, H, HandlerResponse } from '../../types'33// eslint-disable-next-line @typescript-eslint/no-explicit-any4/**5 * @experimental6 * `Factory` class is an experimental feature.7 * The API might be changed.8 */9export class Factory<E extends Env = any, P extends string = any> {10 createMiddleware = <I extends Input = {}>(middleware: MiddlewareHandler<E, P, I>) => middleware1112 /**13 * @experimental14 * `createHandlers` is an experimental feature.15 * The API might be changed.16 */17 createHandlers<I extends Input = {}>(handler1: H<E, P, I>): [H<E, P, I>]1819 // handler x220 /**21 * @experimental22 * `createHandlers` is an experimental feature.23 * The API might be changed.24 */25 createHandlers<I extends Input = {}, I2 extends Input = I, R extends HandlerResponse<any> = any>(26 handler1: H<E, P, I, R>,27 handler2: H<E, P, I2, R>28 ): [H<E, P, I, R>, H<E, P, I2, R>]2930 // handler x331 /**32 * @experimental33 * `createHandlers` is an experimental feature.34 * The API might be changed.35 */36 createHandlers<37 I extends Input = {},38 I2 extends Input = I,39 I3 extends Input = I & I2,40 R extends HandlerResponse<any> = any41 >(42 handler1: H<E, P, I, R>,43 handler2: H<E, P, I2, R>,44 handler3: H<E, P, I3, R>45 ): [H<E, P, I, R>, H<E, P, I2, R>, H<E, P, I3, R>]4647 // handler x448 /**49 * @experimental50 * `createHandlers` is an experimental feature.51 * The API might be changed.52 */53 createHandlers<54 I extends Input = {},55 I2 extends Input = I,56 I3 extends Input = I & I2,57 I4 extends Input = I & I2 & I3,58 R extends HandlerResponse<any> = any59 >(60 handler1: H<E, P, I, R>,61 handler2: H<E, P, I2, R>,62 handler3: H<E, P, I3, R>,63 handler4: H<E, P, I4, R>64 ): [H<E, P, I, R>, H<E, P, I2, R>, H<E, P, I3, R>, H<E, P, I4, R>]6566 // handler x567 /**68 * @experimental69 * `createHandlers` is an experimental feature.70 * The API might be changed.71 */72 createHandlers<73 I extends Input = {},74 I2 extends Input = I,75 I3 extends Input = I & I2,76 I4 extends Input = I & I2 & I3,77 I5 extends Input = I & I2 & I3 & I4,78 R extends HandlerResponse<any> = any79 >(80 handler1: H<E, P, I, R>,81 handler2: H<E, P, I2, R>,82 handler3: H<E, P, I3, R>,83 handler4: H<E, P, I4, R>,84 handler5: H<E, P, I5, R>85 ): [H<E, P, I, R>, H<E, P, I2, R>, H<E, P, I3, R>, H<E, P, I4, R>, H<E, P, I5, R>]8687 // handler x688 /**89 * @experimental90 * `createHandlers` is an experimental feature.91 * The API might be changed.92 */93 createHandlers<94 I extends Input = {},95 I2 extends Input = I,96 I3 extends Input = I & I2,97 I4 extends Input = I & I2 & I3,98 I5 extends Input = I & I2 & I3 & I4,99 I6 extends Input = I & I2 & I3 & I4 & I5,100 R extends HandlerResponse<any> = any101 >(102 handler1: H<E, P, I, R>,103 handler2: H<E, P, I2, R>,104 handler3: H<E, P, I3, R>,105 handler4: H<E, P, I4, R>,106 handler5: H<E, P, I5, R>,107 handler6: H<E, P, I6, R>108 ): [H<E, P, I, R>, H<E, P, I2, R>, H<E, P, I3, R>, H<E, P, I4, R>, H<E, P, I5, R>, H<E, P, I6, R>]109110 // handler x7111 /**112 * @experimental113 * `createHandlers` is an experimental feature.114 * The API might be changed.115 */116 createHandlers<117 I extends Input = {},118 I2 extends Input = I,119 I3 extends Input = I & I2,120 I4 extends Input = I & I2 & I3,121 I5 extends Input = I & I2 & I3 & I4,122 I6 extends Input = I & I2 & I3 & I4 & I5,123 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,124 R extends HandlerResponse<any> = any125 >(126 handler1: H<E, P, I, R>,127 handler2: H<E, P, I2, R>,128 handler3: H<E, P, I3, R>,129 handler4: H<E, P, I4, R>,130 handler5: H<E, P, I5, R>,131 handler6: H<E, P, I6, R>,132 handler7: H<E, P, I7, R>133 ): [134 H<E, P, I, R>,135 H<E, P, I2, R>,136 H<E, P, I3, R>,137 H<E, P, I4, R>,138 H<E, P, I5, R>,139 H<E, P, I6, R>,140 H<E, P, I7, R>141 ]142143 // handler x8144 /**145 * @experimental146 * `createHandlers` is an experimental feature.147 * The API might be changed.148 */149 createHandlers<150 I extends Input = {},151 I2 extends Input = I,152 I3 extends Input = I & I2,153 I4 extends Input = I & I2 & I3,154 I5 extends Input = I & I2 & I3 & I4,155 I6 extends Input = I & I2 & I3 & I4 & I5,156 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,157 I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7,158 R extends HandlerResponse<any> = any159 >(160 handler1: H<E, P, I, R>,161 handler2: H<E, P, I2, R>,162 handler3: H<E, P, I3, R>,163 handler4: H<E, P, I4, R>,164 handler5: H<E, P, I5, R>,165 handler6: H<E, P, I6, R>,166 handler7: H<E, P, I7, R>,167 handler8: H<E, P, I8, R>168 ): [169 H<E, P, I, R>,170 H<E, P, I2, R>,171 H<E, P, I3, R>,172 H<E, P, I4, R>,173 H<E, P, I5, R>,174 H<E, P, I6, R>,175 H<E, P, I7, R>,176 H<E, P, I8, R>177 ]178179 // handler x9180 /**181 * @experimental182 * `createHandlers` is an experimental feature.183 * The API might be changed.184 */185 createHandlers<186 I extends Input = {},187 I2 extends Input = I,188 I3 extends Input = I & I2,189 I4 extends Input = I & I2 & I3,190 I5 extends Input = I & I2 & I3 & I4,191 I6 extends Input = I & I2 & I3 & I4 & I5,192 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,193 I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7,194 I9 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8,195 R extends HandlerResponse<any> = any196 >(197 handler1: H<E, P, I, R>,198 handler2: H<E, P, I2, R>,199 handler3: H<E, P, I3, R>,200 handler4: H<E, P, I4, R>,201 handler5: H<E, P, I5, R>,202 handler6: H<E, P, I6, R>,203 handler7: H<E, P, I7, R>,204 handler8: H<E, P, I8, R>,205 handler9: H<E, P, I9, R>206 ): [207 H<E, P, I, R>,208 H<E, P, I2, R>,209 H<E, P, I3, R>,210 H<E, P, I4, R>,211 H<E, P, I5, R>,212 H<E, P, I6, R>,213 H<E, P, I7, R>,214 H<E, P, I8, R>,215 H<E, P, I9, R>216 ]217218 // handler x10219 /**220 * @experimental221 * `createHandlers` is an experimental feature.222 * The API might be changed.223 */224 createHandlers<225 I extends Input = {},226 I2 extends Input = I,227 I3 extends Input = I & I2,228 I4 extends Input = I & I2 & I3,229 I5 extends Input = I & I2 & I3 & I4,230 I6 extends Input = I & I2 & I3 & I4 & I5,231 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,232 I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7,233 I9 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8,234 I10 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8 & I9,235 R extends HandlerResponse<any> = any236 >(237 handler1: H<E, P, I, R>,238 handler2: H<E, P, I2, R>,239 handler3: H<E, P, I3, R>,240 handler4: H<E, P, I4, R>,241 handler5: H<E, P, I5, R>,242 handler6: H<E, P, I6, R>,243 handler7: H<E, P, I7, R>,244 handler8: H<E, P, I8, R>,245 handler9: H<E, P, I9, R>,246 handler10: H<E, P, I10, R>247 ): [248 H<E, P, I, R>,249 H<E, P, I2, R>,250 H<E, P, I3, R>,251 H<E, P, I4, R>,252 H<E, P, I5, R>,253 H<E, P, I6, R>,254 H<E, P, I7, R>,255 H<E, P, I8, R>,256 H<E, P, I9, R>,257 H<E, P, I10, R>258 ]259260 createHandlers(...handlers: H[]) {261 return handlers.filter((handler) => handler !== undefined)262 }263}264265/**266 * @experimental267 * `createFactory` is an experimental feature.268 * The API might be changed.269 */270export const createFactory = <E extends Env = any, P extends string = any>() => new Factory<E, P>()271272export const createMiddleware = <E extends Env = any, P extends string = any, I extends Input = {}>(5 middleware: MiddlewareHandler<E, P, I>6) => middleware273 middleware: MiddlewareHandler274) => createFactory<E, P>().createMiddleware<I>(middleware)
modified:src/helper/html/index.ts+8 added-3 removed
1import { escapeToBuffer, stringBufferToString } from '../../utils/html'2import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../../utils/html'2import type {3 StringBuffer,4 HtmlEscaped,5 HtmlEscapedString,6 HtmlEscapedCallback,7} from '../../utils/html'84export const raw = (value: unknown, promises?: Promise<string>[]): HtmlEscapedString => {9export const raw = (value: unknown, callbacks?: HtmlEscapedCallback[]): HtmlEscapedString => {10 const escapedString = new String(value) as HtmlEscapedString11 escapedString.isEscaped = true7 escapedString.promises = promises12 escapedString.callbacks = callbacks1314 return escapedString15}16
37 unmodified lines
modified:src/helper/testing/index.test.ts+2 added-2 removed
1 unmodified line
2import { testClient } from '.'34describe('hono testClinet', () => {5 it('should return the correct search result', async () => {6 const app = new Hono().get('/search', (c) => c.jsonT({ hello: 'world' }))6 const app = new Hono().get('/search', (c) => c.json({ hello: 'world' }))7 const res = await testClient(app).search.$get()8 expect(await res.json()).toEqual({ hello: 'world' })9 })1011 it('should return the correct environment variables value', async () => {12 type Bindings = { hello: string }13 const app = new Hono<{ Bindings: Bindings }>().get('/search', (c) => {14 return c.jsonT({ hello: c.env.hello })14 return c.json({ hello: c.env.hello })15 })16 const res = await testClient(app, { hello: 'world' }).search.$get()17 expect(await res.json()).toEqual({ hello: 'world' })18 })
1 unmodified line
added:src/jsx/components.test.tsx+472 added
1import { JSDOM } from 'jsdom'2import { resolveStream } from '../utils/html'3import { ErrorBoundary } from './components'4import { Suspense, renderToReadableStream } from './streaming'5// eslint-disable-next-line @typescript-eslint/no-unused-vars6import { jsx, Fragment } from './index'78function replacementResult(html: string) {9 const document = new JSDOM(html, { runScripts: 'dangerously' }).window.document10 document.querySelectorAll('template, script').forEach((e) => e.remove())11 return document.body.innerHTML12}1314const Fallback = () => <div>Out Of Service</div>1516describe('ErrorBoundary', () => {17 let errorBoundaryCounter = 018 let suspenseCounter = 019 afterEach(() => {20 errorBoundaryCounter++21 suspenseCounter++22 })2324 describe('sync', async () => {25 const Component = ({ error }: { error?: boolean }) => {26 if (error) {27 throw new Error('Error')28 }29 return <div>Hello</div>30 }3132 it('no error', async () => {33 const html = (34 <ErrorBoundary fallback={<Fallback />}>35 <Component />36 </ErrorBoundary>37 )3839 expect((await resolveStream(await html.toString())).toString()).toEqual('<div>Hello</div>')4041 errorBoundaryCounter--42 suspenseCounter--43 })4445 it('error', async () => {46 const html = (47 <ErrorBoundary fallback={<Fallback />}>48 <Component error={true} />49 </ErrorBoundary>50 )5152 expect((await resolveStream(await html.toString())).toString()).toEqual(53 '<div>Out Of Service</div>'54 )5556 suspenseCounter--57 })58 })5960 describe('async', async () => {61 const Component = async ({ error }: { error?: boolean }) => {62 await new Promise((resolve) => setTimeout(resolve, 10))63 if (error) {64 throw new Error('Error')65 }66 return <div>Hello</div>67 }6869 it('no error', async () => {70 const html = (71 <ErrorBoundary fallback={<Fallback />}>72 <Component />73 </ErrorBoundary>74 )7576 expect((await resolveStream(await html.toString())).toString()).toEqual('<div>Hello</div>')7778 errorBoundaryCounter--79 suspenseCounter--80 })8182 it('error', async () => {83 const html = (84 <ErrorBoundary fallback={<Fallback />}>85 <Component error={true} />86 </ErrorBoundary>87 )8889 expect((await resolveStream(await html.toString())).toString()).toEqual(90 '<div>Out Of Service</div>'91 )9293 suspenseCounter--94 })95 })9697 describe('async : nested', async () => {98 const handlers: Record<number, { resolve: (value: unknown) => void; reject: () => void }> = {}99 const Component = async ({ id }: { id: number }) => {100 await new Promise((resolve, reject) => (handlers[id] = { resolve, reject }))101 return <div>{id}</div>102 }103104 it('no error', async () => {105 const html = (106 <ErrorBoundary fallback={<Fallback />}>107 <Component id={1} />108 <ErrorBoundary fallback={<Fallback />}>109 <Component id={2} />110 </ErrorBoundary>111 </ErrorBoundary>112 ).toString()113114 Object.values(handlers).forEach(({ resolve }) => resolve(undefined))115116 expect((await resolveStream(await html)).toString()).toEqual('<div>1</div><div>2</div>')117118 errorBoundaryCounter++119 suspenseCounter--120 })121122 it('error in parent', async () => {123 const html = (124 <ErrorBoundary fallback={<Fallback />}>125 <Component id={1} />126 <ErrorBoundary fallback={<Fallback />}>127 <Component id={2} />128 </ErrorBoundary>129 </ErrorBoundary>130 ).toString()131132 handlers[2].resolve(undefined)133 handlers[1].reject()134135 expect((await resolveStream(await html)).toString()).toEqual('<div>Out Of Service</div>')136137 errorBoundaryCounter++138 suspenseCounter--139 })140141 it('error in child', async () => {142 const html = (143 <ErrorBoundary fallback={<Fallback />}>144 <Component id={1} />145 <ErrorBoundary fallback={<Fallback />}>146 <Component id={2} />147 </ErrorBoundary>148 </ErrorBoundary>149 ).toString()150151 handlers[1].resolve(undefined)152 handlers[2].reject()153154 expect((await resolveStream(await html)).toString()).toEqual(155 '<div>1</div><div>Out Of Service</div>'156 )157158 errorBoundaryCounter++159 suspenseCounter--160 })161 })162163 describe('streaming', async () => {164 const Component = async ({ error }: { error?: boolean }) => {165 await new Promise((resolve) => setTimeout(resolve, 10))166 if (error) {167 throw new Error('Error')168 }169 return <div>Hello</div>170 }171172 it('no error', async () => {173 const stream = renderToReadableStream(174 <ErrorBoundary fallback={<Fallback />}>175 <Suspense fallback={<p>Loading...</p>}>176 <Component />177 </Suspense>178 </ErrorBoundary>179 )180 const chunks = []181 const textDecoder = new TextDecoder()182 for await (const chunk of stream as any) {183 chunks.push(textDecoder.decode(chunk))184 }185186 expect(chunks).toEqual([187 `<template id="E:${errorBoundaryCounter}"></template><!--E:${errorBoundaryCounter}-->`,188 `<template><template id="H:${suspenseCounter}"></template><p>Loading...</p><!--/$--></template><script>189((d,c) => {190c=d.currentScript.previousSibling191d=d.getElementById('E:${errorBoundaryCounter}')192if(!d)return193d.parentElement.insertBefore(c.content,d.nextSibling)194})(document)195</script>`,196 `<template><div>Hello</div></template><script>197((d,c,n) => {198c=d.currentScript.previousSibling199d=d.getElementById('H:${suspenseCounter}')200if(!d)return201do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')202d.replaceWith(c.content)203})(document)204</script><script>205((d,c,n) => {206d=d.getElementById('E:${errorBoundaryCounter}')207if(!d)return208n=d.nextSibling209do{n=n.nextSibling}while(n.nodeType!=8||n.nodeValue!='E:${errorBoundaryCounter}')210n.remove()211d.remove()212})(document)213</script>`,214 ])215216 expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual(217 '<div>Hello</div>'218 )219 })220221 it('error', async () => {222 const html = (223 <ErrorBoundary fallback={<Fallback />}>224 <Component error={true} />225 </ErrorBoundary>226 )227228 expect((await resolveStream(await html.toString())).toString()).toEqual(229 '<div>Out Of Service</div>'230 )231 })232 })233234 describe('streaming : contains multiple suspense', async () => {235 const handlers: Record<number, { resolve: (value: unknown) => void; reject: () => void }> = {}236 const Component = async ({ id }: { id: number }) => {237 await new Promise((resolve, reject) => (handlers[id] = { resolve, reject }))238 return <div>{id}</div>239 }240241 it('no error', async () => {242 const stream = renderToReadableStream(243 <ErrorBoundary fallback={<Fallback />}>244 <Suspense fallback={<p>Loading...</p>}>245 <Component id={1} />246 </Suspense>247 <Suspense fallback={<p>Loading...</p>}>248 <Component id={2} />249 </Suspense>250 <Suspense fallback={<p>Loading...</p>}>251 <Component id={3} />252 </Suspense>253 </ErrorBoundary>254 )255256 Object.values(handlers).forEach(({ resolve }) => resolve(undefined))257258 const chunks = []259 const textDecoder = new TextDecoder()260 for await (const chunk of stream as any) {261 chunks.push(textDecoder.decode(chunk))262 }263264 expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual(265 '<div>1</div><div>2</div><div>3</div>'266 )267 })268269 it('error', async () => {270 const stream = renderToReadableStream(271 <ErrorBoundary fallback={<Fallback />}>272 <Suspense fallback={<p>Loading...</p>}>273 <Component id={1} />274 </Suspense>275 <Suspense fallback={<p>Loading...</p>}>276 <Component id={2} />277 </Suspense>278 <Suspense fallback={<p>Loading...</p>}>279 <Component id={3} />280 </Suspense>281 </ErrorBoundary>282 )283284 handlers[1].resolve(undefined)285 handlers[2].resolve(undefined)286 handlers[3].reject()287288 const chunks = []289 const textDecoder = new TextDecoder()290 for await (const chunk of stream as any) {291 chunks.push(textDecoder.decode(chunk))292 }293294 expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual(295 '<div>Out Of Service</div>'296 )297 })298 })299300 describe('streaming : nested', async () => {301 const handlers: Record<number, { resolve: (value: unknown) => void; reject: () => void }> = {}302 const Component = async ({ id }: { id: number }) => {303 await new Promise((resolve, reject) => (handlers[id] = { resolve, reject }))304 return <div>{id}</div>305 }306307 it('no error', async () => {308 const stream = renderToReadableStream(309 <ErrorBoundary fallback={<Fallback />}>310 <Suspense fallback={<p>Loading...</p>}>311 <Component id={1} />312 </Suspense>313 <ErrorBoundary fallback={<Fallback />}>314 <Suspense fallback={<p>Loading...</p>}>315 <Component id={2} />316 </Suspense>317 </ErrorBoundary>318 </ErrorBoundary>319 )320321 Object.values(handlers).forEach(({ resolve }) => resolve(undefined))322323 const chunks = []324 const textDecoder = new TextDecoder()325 for await (const chunk of stream as any) {326 chunks.push(textDecoder.decode(chunk))327 }328329 expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual(330 '<div>1</div><div>2</div>'331 )332 })333334 it('error in parent', async () => {335 const stream = renderToReadableStream(336 <ErrorBoundary fallback={<Fallback />}>337 <Suspense fallback={<p>Loading...</p>}>338 <Component id={1} />339 </Suspense>340 <ErrorBoundary fallback={<Fallback />}>341 <Suspense fallback={<p>Loading...</p>}>342 <Component id={2} />343 </Suspense>344 </ErrorBoundary>345 </ErrorBoundary>346 )347348 handlers[2].resolve(undefined)349 handlers[1].reject()350351 const chunks = []352 const textDecoder = new TextDecoder()353 for await (const chunk of stream as any) {354 chunks.push(textDecoder.decode(chunk))355 }356357 expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual(358 '<div>Out Of Service</div>'359 )360 })361362 it('error in child', async () => {363 const stream = renderToReadableStream(364 <ErrorBoundary fallback={<Fallback />}>365 <Suspense fallback={<p>Loading...</p>}>366 <Component id={1} />367 </Suspense>368 <ErrorBoundary fallback={<Fallback />}>369 <Suspense fallback={<p>Loading...</p>}>370 <Component id={2} />371 </Suspense>372 </ErrorBoundary>373 </ErrorBoundary>374 )375376 handlers[1].resolve(undefined)377 handlers[2].reject()378379 const chunks = []380 const textDecoder = new TextDecoder()381 for await (const chunk of stream as any) {382 chunks.push(textDecoder.decode(chunk))383 }384385 expect(replacementResult(`<html><body>${chunks.join('')}</body></html>`)).toEqual(386 '<div>1</div><div>Out Of Service</div>'387 )388 })389 })390391 describe('onError', async () => {392 const Component = ({ error }: { error?: boolean }) => {393 if (error) {394 throw new Error('Error')395 }396 return <div>Hello</div>397 }398399 it('no error', async () => {400 const errors: Error[] = []401 const html = (402 <ErrorBoundary fallback={<Fallback />} onError={(err) => errors.push(err)}>403 <Component />404 </ErrorBoundary>405 )406407 expect((await resolveStream(await html.toString())).toString()).toEqual('<div>Hello</div>')408409 errorBoundaryCounter--410 suspenseCounter--411412 expect(errors).toEqual([])413 })414415 it('error', async () => {416 const errors: Error[] = []417 const html = (418 <ErrorBoundary fallback={<Fallback />} onError={(err) => errors.push(err)}>419 <Component error={true} />420 </ErrorBoundary>421 )422423 expect((await resolveStream(await html.toString())).toString()).toEqual(424 '<div>Out Of Service</div>'425 )426427 suspenseCounter--428429 expect(errors[0]).toEqual(new Error('Error'))430 })431 })432433 describe('fallbackRender', async () => {434 const fallbackRenderer = (error: Error) => <div data-error>{error.message}</div>435 const Component = ({ error }: { error?: boolean }) => {436 if (error) {437 throw new Error('Error')438 }439 return <div>Hello</div>440 }441442 it('no error', async () => {443 const errors: Error[] = []444 const html = (445 <ErrorBoundary fallbackRender={fallbackRenderer}>446 <Component />447 </ErrorBoundary>448 )449450 expect((await resolveStream(await html.toString())).toString()).toEqual('<div>Hello</div>')451452 errorBoundaryCounter--453 suspenseCounter--454455 expect(errors).toEqual([])456 })457458 it('error', async () => {459 const html = (460 <ErrorBoundary fallbackRender={fallbackRenderer}>461 <Component error={true} />462 </ErrorBoundary>463 )464465 expect((await resolveStream(await html.toString())).toString()).toEqual(466 '<div data-error="true">Error</div>'467 )468469 suspenseCounter--470 })471 })472})
added:src/jsx/components.ts+163 added
1import { raw } from '../helper/html'2import type { HtmlEscapedString } from '../utils/html'3import type { FC, Child } from './index'45let errorBoundaryCounter = 067export const childrenToString = async (children: Child[]): Promise<HtmlEscapedString[]> => {8 try {9 return children.map((c) => c.toString()) as HtmlEscapedString[]10 } catch (e) {11 if (e instanceof Promise) {12 await e13 return childrenToString(children)14 } else {15 throw e16 }17 }18}1920type ErrorHandler = (error: Error) => void21type FallbackRender = (error: Error) => Child2223/**24 * @experimental25 * `ErrorBoundary` is an experimental feature.26 * The API might be changed.27 */28export const ErrorBoundary: FC<{29 fallback?: Child30 fallbackRender?: FallbackRender31 onError?: ErrorHandler32}> = async ({ children, fallback, fallbackRender, onError }) => {33 if (!children) {34 return raw('')35 }3637 if (!Array.isArray(children)) {38 children = [children]39 }4041 const fallbackRes = (error: Error): HtmlEscapedString => {42 onError?.(error)43 return (fallback || fallbackRender?.(error) || '').toString() as HtmlEscapedString44 }45 let resArray: HtmlEscapedString[] | Promise<HtmlEscapedString[]>[] = []46 try {47 resArray = children.map((c) => c.toString()) as HtmlEscapedString[]48 } catch (e) {49 if (e instanceof Promise) {50 resArray = [51 e.then(() => childrenToString(children as Child[])).catch((e) => fallbackRes(e)),52 ] as Promise<HtmlEscapedString[]>[]53 } else {54 resArray = [fallbackRes(e as Error)]55 }56 }5758 if (resArray.some((res) => (res as {}) instanceof Promise)) {59 const index = errorBoundaryCounter++60 const replaceRe = RegExp(`(<template id="E:${index}"></template>.*?)(.*?)(<!--E:${index}-->)`)61 const caught = false62 const catchCallback = ({ error, buffer }: { error: Error; buffer?: [string] }) => {63 if (caught) {64 return ''65 }6667 const fallbackResString = fallbackRes(error)68 if (buffer) {69 buffer[0] = buffer[0].replace(replaceRe, fallbackResString)70 }71 return buffer72 ? ''73 : `<template>${fallbackResString}</template><script>74((d,c,n) => {75c=d.currentScript.previousSibling76d=d.getElementById('E:${index}')77if(!d)return78do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='E:${index}')79d.replaceWith(c.content)80})(document)81</script>`82 }83 return raw(`<template id="E:${index}"></template><!--E:${index}-->`, [84 ({ buffer }) => {85 return Promise.all(resArray)86 .then((htmlArray) => {87 htmlArray = htmlArray.flat()88 const content = htmlArray.join('')89 const html = buffer90 ? ''91 : `<template>${content}</template><script>92((d,c) => {93c=d.currentScript.previousSibling94d=d.getElementById('E:${index}')95if(!d)return96d.parentElement.insertBefore(c.content,d.nextSibling)97})(document)98</script>`99100 if (htmlArray.every((html) => !(html as HtmlEscapedString).callbacks?.length)) {101 if (buffer) {102 buffer[0] = buffer[0].replace(replaceRe, content)103 }104 return html105 }106107 if (buffer) {108 buffer[0] = buffer[0].replace(109 replaceRe,110 (_all, pre, _, post) => `${pre}${content}${post}`111 )112 }113114 const callbacks = htmlArray115 .map((html) => (html as HtmlEscapedString).callbacks || [])116 .flat()117118 let resolvedCount = 0119 const promises = callbacks.map(120 (c) =>121 ({ buffer }: { buffer: [string] }) =>122 c({ buffer })123 .then((content) => {124 resolvedCount++125126 if (buffer) {127 if (resolvedCount === callbacks.length) {128 buffer[0] = buffer[0].replace(replaceRe, (_all, _pre, content) => content)129 }130 buffer[0] += content131 return raw('', (content as HtmlEscapedString).callbacks)132 }133134 return raw(135 content +136 (resolvedCount !== callbacks.length137 ? ''138 : `<script>139((d,c,n) => {140d=d.getElementById('E:${index}')141if(!d)return142n=d.nextSibling143do{n=n.nextSibling}while(n.nodeType!=8||n.nodeValue!='E:${index}')144n.remove()145d.remove()146})(document)147</script>`),148 (content as HtmlEscapedString).callbacks149 )150 })151 .catch((error) => catchCallback({ error, buffer }))152 )153154 // eslint-disable-next-line @typescript-eslint/no-explicit-any155 return raw(html, promises as any)156 })157 .catch((error) => catchCallback({ error, buffer }))158 },159 ])160 } else {161 return raw(resArray.join(''))162 }163}
modified:src/jsx/index.ts+2 added-1 removed
1import { raw } from '../helper/html'2import { escapeToBuffer, stringBufferToString } from '../utils/html'3import type { StringBuffer, HtmlEscaped, HtmlEscapedString } from '../utils/html'4import type { IntrinsicElements as IntrinsicElementsDefined } from './intrinsic-elements'5export { ErrorBoundary } from './components'67// eslint-disable-next-line @typescript-eslint/no-explicit-any8type Props = Record<string, any>9
263 unmodified lines
273 if (string instanceof Promise) {274 return Promise.resolve().then<HtmlEscapedString>(async () => {275 values.push(props.value)276 const awaited = await string276 const promiseRes = raw(awaited, (awaited as HtmlEscapedString).promises)277 const promiseRes = raw(awaited, (awaited as HtmlEscapedString).callbacks)278 values.pop()279 return promiseRes280 })281 } else {
9 unmodified lines
modified:src/jsx/streaming.test.tsx+29 added
1import { JSDOM } from 'jsdom'2import { raw } from '../helper/html'3import { resolveStream } from '../utils/html'4import type { HtmlEscapedString } from '../utils/html'5import { Suspense, renderToReadableStream } from './streaming'6// eslint-disable-next-line @typescript-eslint/no-unused-vars7import { jsx, Fragment } from './index'
37 unmodified lines
45 `<template><h1>Hello</h1></template><script>46((d,c,n) => {47c=d.currentScript.previousSibling48d=d.getElementById('H:${suspenseCounter}')49if(!d)return50do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')51d.replaceWith(c.content)52})(document)53</script>`,
39 unmodified lines
93 `<template><p>thrown a promise then resolved</p></template><script>94((d,c,n) => {95c=d.currentScript.previousSibling96d=d.getElementById('H:${suspenseCounter}')97if(!d)return98do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')99d.replaceWith(c.content)100})(document)101</script>`,
107 unmodified lines
209 `<template><p></p></template><script>210((d,c,n) => {211c=d.currentScript.previousSibling212d=d.getElementById('H:${suspenseCounter}')213if(!d)return214do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')215d.replaceWith(c.content)216})(document)217</script>`,
25 unmodified lines
243 `<template><p></p></template><script>244((d,c,n) => {245c=d.currentScript.previousSibling246d=d.getElementById('H:${suspenseCounter}')247if(!d)return248do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')249d.replaceWith(c.content)250})(document)251</script>`,
65 unmodified lines
317 `<template><h1>Hello</h1><h2>World</h2></template><script>318((d,c,n) => {319c=d.currentScript.previousSibling320d=d.getElementById('H:${suspenseCounter}')321if(!d)return322do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')323d.replaceWith(c.content)324})(document)325</script>`,
37 unmodified lines
363 `<template><h1>Hello</h1></template><script>364((d,c,n) => {365c=d.currentScript.previousSibling366d=d.getElementById('H:${suspenseCounter}')367if(!d)return368do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')369d.replaceWith(c.content)370})(document)371</script>`,
49 unmodified lines
421 }\"></template><p>Loading sub content...</p><!--/$--></template><script>422((d,c,n) => {423c=d.currentScript.previousSibling424d=d.getElementById('H:${suspenseCounter}')425if(!d)return426do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')427d.replaceWith(c.content)428})(document)429</script>`,430 `<template><h2>World</h2></template><script>431((d,c,n) => {432c=d.currentScript.previousSibling433d=d.getElementById('H:${suspenseCounter + 1}')434if(!d)return435do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')436d.replaceWith(c.content)437})(document)438</script>`,
69 unmodified lines
508 '<p>first</p><p>last</p>'509 )510 })511512 it('Suspense with resolveStream', async () => {513 let contentEvaluatedCount = 0514 const Content = () => {515 contentEvaluatedCount++516 const content = new Promise<HtmlEscapedString>((resolve) =>517 setTimeout(() => resolve(<h1>Hello</h1>), 10)518 )519 return content520 }521522 const str = await resolveStream(await (523 <Suspense fallback={<p>Loading...</p>}>524 <Content />525 </Suspense>526 ).toString())527528 expect(str).toEqual('<h1>Hello</h1>')529 expect(contentEvaluatedCount).toEqual(1)530 })531532 it('renderToReadableStream(str: string)', async () => {533 const str = '<h1>Hello</h1>'534 const stream = renderToReadableStream(raw(str))535
21 unmodified lines
modified:src/jsx/streaming.ts+32 added-29 removed
1import { raw } from '../helper/html'2import type { HtmlEscapedString } from '../utils/html'3import { childrenToString } from './components'4import type { FC, Child } from './index'56let suspenseCounter = 077async function childrenToString(children: Child[]): Promise<HtmlEscapedString[]> {8 try {9 return children.map((c) => c.toString()) as HtmlEscapedString[]10 } catch (e) {11 if (e instanceof Promise) {12 await e13 return childrenToString(children)14 } else {15 throw e16 }17 }18}198/**9 * @experimental10 * `Suspense` is an experimental feature.11 * The API might be changed.
22 unmodified lines
3435 if (resArray.some((res) => (res as {}) instanceof Promise)) {36 const index = suspenseCounter++37 return raw(`<template id="H:${index}"></template>${fallback.toString()}<!--/$-->`, [38 ({ buffer }) => {50 Promise.all(resArray).then((htmlArray) => {51 htmlArray = htmlArray.flat()52 const html = `<template>${htmlArray.join('')}</template><script>39 return Promise.all(resArray).then((htmlArray) => {40 htmlArray = htmlArray.flat()41 const content = htmlArray.join('')42 if (buffer) {43 buffer[0] = buffer[0].replace(44 new RegExp(`<template id="H:${index}"></template>.*?<!--/\\$-->`),45 content46 )47 }48 const html = buffer49 ? ''50 : `<template>${content}</template><script>51((d,c,n) => {52c=d.currentScript.previousSibling53d=d.getElementById('H:${index}')54if(!d)return55do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')56d.replaceWith(c.content)57})(document)58</script>`60 if (htmlArray.every((html) => !(html as HtmlEscapedString).promises?.length)) {61 return html62 }59 if (htmlArray.every((html) => !(html as HtmlEscapedString).callbacks?.length)) {60 return html61 }6264 return raw(html, htmlArray.map((html) => (html as HtmlEscapedString).promises || []).flat())65 }),63 return raw(64 html,65 htmlArray.map((html) => (html as HtmlEscapedString).callbacks || []).flat()66 )67 })68 },69 ])70 } else {71 return raw(resArray.join(''))72 }
13 unmodified lines
86 const resolved = str instanceof Promise ? await str : await str.toString()87 controller.enqueue(textEncoder.encode(resolved))8889 let resolvedCount = 087 const promises: Promise<void>[] = []90 const callbacks: Promise<void>[] = []91 const then = (promise: Promise<string>) => {89 promises.push(92 callbacks.push(93 promise94 .catch((err) => {95 console.trace(err)96 return ''97 })98 .then((res) => {96 if ((res as HtmlEscapedString).promises) {97 const resPromises = (res as HtmlEscapedString).promises || []98 resPromises.forEach(then)99 if ((res as HtmlEscapedString).callbacks) {100 const callbacks = (res as HtmlEscapedString).callbacks || []101 callbacks.map((c) => c({})).forEach(then)102 }103 resolvedCount++104 controller.enqueue(textEncoder.encode(res))105 })106 )107 }105 ;(resolved as HtmlEscapedString).promises?.map(then)106 while (resolvedCount !== promises.length) {107 await Promise.all(promises)108 ;(resolved as HtmlEscapedString).callbacks?.map((c) => c({})).forEach(then)109 while (resolvedCount !== callbacks.length) {110 await Promise.all(callbacks)111 }112113 controller.close()114 },
3 unmodified lines
modified:src/middleware/basic-auth/index.ts+1 added-1 removed
37 unmodified lines
38 options.realm = 'Secure Area'39 }40 users.unshift({ username: options.username, password: options.password })4142 return async (ctx, next) => {42 return async function basicAuth(ctx, next) {43 const requestUser = auth(ctx.req)44 if (requestUser) {45 for (const user of users) {46 const usernameEqual = await timingSafeEqual(
24 unmodified lines
modified:src/middleware/bearer-auth/index.test.ts+26 added
3 unmodified lines
4describe('Bearer Auth by Middleware', () => {5 let app: Hono6 let handlerExecuted: boolean7 let token: string8 let tokens: string[]910 beforeEach(async () => {11 app = new Hono()12 handlerExecuted = false13 token = 'abcdefg12345-._~+/='14 tokens = ['abcdefg12345-._~+/=', 'alternative']1516 app.use('/auth/*', bearerAuth({ token }))17 app.use('/auth/*', async (c, next) => {18 c.header('x-custom', 'foo')
17 unmodified lines
36 app.get('/nested/*', (c) => {37 handlerExecuted = true38 return c.text('auth nested')39 })4041 app.use('/auths/*', bearerAuth({ token: tokens }))42 app.get('/auths/*', (c) => {43 handlerExecuted = true44 return c.text('auths')45 })46 })4748 it('Should authorize', async () => {49 const req = new Request('http://localhost/auth/a')
75 unmodified lines
125 expect(handlerExecuted).toBeFalsy()126 expect(res.status).toBe(401)127 expect(await res.text()).toBe('Unauthorized')128 })129130 it('Should authorize - with any token in list', async () => {131 const req1 = new Request('http://localhost/auths/a')132 req1.headers.set('Authorization', 'Bearer abcdefg12345-._~+/=')133 const res1 = await app.request(req1)134 expect(res1).not.toBeNull()135 expect(res1.status).toBe(200)136 expect(handlerExecuted).toBeTruthy()137 expect(await res1.text()).toBe('auths')138139 const req2 = new Request('http://localhost/auths/a')140 req2.headers.set('Authorization', 'Bearer alternative')141 const res2 = await app.request(req2)142 expect(res2).not.toBeNull()143 expect(res2.status).toBe(200)144 expect(handlerExecuted).toBeTruthy()145 expect(await res2.text()).toBe('auths')146 })147})
modified:src/middleware/bearer-auth/index.ts+13 added-3 removed
4 unmodified lines
5const TOKEN_STRINGS = '[A-Za-z0-9._~+/-]+=*'6const PREFIX = 'Bearer'78export const bearerAuth = (options: {9 token: string9 token: string | string[]10 realm?: string11 prefix?: string12 hashFunction?: Function13}): MiddlewareHandler => {
8 unmodified lines
22 }2324 const realm = options.realm?.replace(/"/g, '\\"')2526 return async (c, next) => {26 return async function bearerAuth(c, next) {27 const headerToken = c.req.header('Authorization')2829 if (!headerToken) {30 // No Authorization header
16 unmodified lines
47 },48 })49 throw new HTTPException(400, { res })50 } else {51 let equal = false52 if (typeof options.token === 'string') {51 const equal = await timingSafeEqual(options.token, match[1], options.hashFunction)53 equal = await timingSafeEqual(options.token, match[1], options.hashFunction)54 } else if (Array.isArray(options.token) && options.token.length > 0) {55 for (const token of options.token) {56 if (await timingSafeEqual(token, match[1], options.hashFunction)) {57 equal = true58 break59 }60 }61 }62 if (!equal) {63 // Invalid Token64 const res = new Response('Unauthorized', {65 status: 401,
11 unmodified lines
modified:src/middleware/cache/index.ts+1 added-1 removed
11 unmodified lines
12 const addHeader = (response: Response) => {13 if (options.cacheControl) response.headers.set('Cache-Control', options.cacheControl)14 }1516 return async (c, next) => {16 return async function cache(c, next) {17 const key = c.req.url18 const cache = await caches.open(options.cacheName)19 const response = await cache.match(key)20 if (!response) {
16 unmodified lines
modified:src/middleware/compress/index.ts+1 added-1 removed
5 unmodified lines
6 encoding?: typeof ENCODING_TYPES[number]7}89export const compress = (options?: CompressionOptions): MiddlewareHandler => {10 return async (ctx, next) => {10 return async function compress(ctx, next) {11 await next()12 const accepted = ctx.req.headers.get('Accept-Encoding')13 const encoding =14 options?.encoding ?? ENCODING_TYPES.find((encoding) => accepted?.includes(encoding))
11 unmodified lines
modified:src/middleware/cors/index.ts+1 added-1 removed
29 unmodified lines
30 return (origin: string) => (optsOrigin.includes(origin) ? origin : optsOrigin[0])31 }32 })(opts.origin)3334 return async (c, next) => {34 return async function cors(c, next) {35 function set(key: string, value: string) {36 c.res.headers.set(key, value)37 }38
55 unmodified lines
modified:src/middleware/etag/index.ts+1 added-1 removed
27 unmodified lines
28export const etag = (options?: ETagOptions): MiddlewareHandler => {29 const retainedHeaders = options?.retainedHeaders ?? RETAINED_304_HEADERS30 const weak = options?.weak ?? false3132 return async (c, next) => {32 return async function etag(c, next) {33 const ifNoneMatch = c.req.header('If-None-Match') ?? null3435 await next()36
27 unmodified lines
modified:src/middleware/jsx-renderer/index.test.tsx+2 added
160 unmodified lines
161 `<template><p>Hello Hono!</p></template><script>162((d,c,n) => {163c=d.currentScript.previousSibling164d=d.getElementById('H:0')165if(!d)return166do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')167d.replaceWith(c.content)168})(document)169</script>`,
58 unmodified lines
228 `<template><p>Hello Hono again!</p></template><script>229((d,c,n) => {230c=d.currentScript.previousSibling231d=d.getElementById('H:1')232if(!d)return233do{n=d.nextSibling;n.remove()}while(n.nodeType!=8||n.nodeValue!='/$')234d.replaceWith(c.content)235})(document)236</script>`,
47 unmodified lines
modified:src/middleware/jsx-renderer/index.ts+5 added-3 removed
46 unmodified lines
47 return c.html(body)48 }49 }5051export const jsxRenderer =52 (component?: FC<PropsForRenderer>, options?: RendererOptions): MiddlewareHandler =>53 (c, next) => {51export const jsxRenderer = (52 component?: FC<PropsForRenderer>,53 options?: RendererOptions54): MiddlewareHandler =>55 function jsxRenderer(c, next) {56 /* eslint-disable @typescript-eslint/no-explicit-any */57 c.setRenderer(createRenderer(c, component, options) as any)58 return next()59 }
12 unmodified lines
modified:src/middleware/jwt/index.ts+1 added-1 removed
22 unmodified lines
23 if (!crypto.subtle || !crypto.subtle.importKey) {24 throw new Error('`crypto.subtle.importKey` is undefined. JWT auth middleware requires it.')25 }2627 return async (ctx, next) => {27 return async function jwt(ctx, next) {28 const credentials = ctx.req.headers.get('Authorization')29 let token30 if (credentials) {31 const parts = credentials.split(/\s+/)
52 unmodified lines
modified:src/middleware/logger/index.ts+1 added-1 removed
52 unmodified lines
53 fn(out)54}5556export const logger = (fn: PrintFunc = console.log): MiddlewareHandler => {57 return async (c, next) => {57 return async function logger(c, next) {58 const { method } = c.req59 // eslint-disable-next-line @typescript-eslint/no-unused-vars60 const path = getPath(c.req.raw)61
9 unmodified lines
modified:src/middleware/powered-by/index.ts+1 added-1 removed
1import type { MiddlewareHandler } from '../../types'23export const poweredBy = (): MiddlewareHandler => {4 return async (c, next) => {4 return async function poweredBy(c, next) {5 await next()6 c.res.headers.set('X-Powered-By', 'Hono')7 }8}
modified:src/middleware/pretty-json/index.ts+1 added-1 removed
3 unmodified lines
4 space: number5}67export const prettyJSON = (options: prettyOptions = { space: 2 }): MiddlewareHandler => {8 return async (c, next) => {8 return async function prettyJSON(c, next) {9 const pretty = c.req.query('pretty') || c.req.query('pretty') === '' ? true : false10 await next()11 if (pretty && c.res.headers.get('Content-Type')?.startsWith('application/json')) {12 const obj = await c.res.json()
4 unmodified lines
modified:src/middleware/secure-headers/index.ts+1 added-1 removed
128 unmodified lines
129 const reportToOptions = options.reportTo.map((option) => JSON.stringify(option)).join(', ')130 headersToSet.push(['Report-To', reportToOptions])131 }132133 return async (ctx, next) => {133 return async function secureHeaders(ctx, next) {134 await next()135 headersToSet.forEach(([header, value]) => {136 ctx.res.headers.set(header, value)137 })
4 unmodified lines
modified:src/middleware/timing/index.ts+1 added-1 removed
40 unmodified lines
41 crossOrigin: false,42 },43 ...config,44 }45 return async (c, next) => {45 return async function timing(c, next) {46 const headers: string[] = []47 const timers = new Map<string, Timer>()48 c.set('metric', { headers, timers })49
86 unmodified lines
modified:src/router/reg-exp-router/router.ts+7 added-2 removed
1/* eslint-disable @typescript-eslint/ban-ts-comment */2import type { Router, Result, ParamIndexMap } from '../../router'3import { METHOD_NAME_ALL, METHODS, UnsupportedPathError } from '../../router'3import {4 METHOD_NAME_ALL,5 METHODS,6 UnsupportedPathError,7 MESSAGE_MATCHER_IS_ALREADY_BUILT,8} from '../../router'9import { checkOptionalParameter } from '../../utils/url'10import { PATH_ERROR, type ParamAssocArray } from './node'11import { Trie } from './trie'12
120 unmodified lines
133 add(method: string, path: string, handler: T) {134 const { middleware, routes } = this135136 if (!middleware || !routes) {132 throw new Error('Can not add a route since the matcher is already built.')137 throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT)138 }139140 if (methodNames.indexOf(method) === -1) methodNames.push(method)141 if (!middleware[method]) {
135 unmodified lines
modified:src/router/smart-router/router.ts+2 added-2 removed
1/* eslint-disable @typescript-eslint/ban-ts-comment */2import type { Router, Result } from '../../router'3import { UnsupportedPathError } from '../../router'3import { UnsupportedPathError, MESSAGE_MATCHER_IS_ALREADY_BUILT } from '../../router'45export class SmartRouter<T> implements Router<T> {6 name: string = 'SmartRouter'7 routers: Router<T>[] = []
4 unmodified lines
12 }1314 add(method: string, path: string, handler: T) {15 if (!this.routes) {16 throw new Error('Can not add a route since the matcher is already built.')16 throw new Error(MESSAGE_MATCHER_IS_ALREADY_BUILT)17 }1819 this.routes.push([method, path, handler])20 }
49 unmodified lines
modified:src/utils/html.ts+28 added-5 removed
1export type HtmlEscaped = { isEscaped: true; promises?: Promise<string>[] }1type HtmlEscapedCallbackOpts = { error?: Error; buffer?: [string] }2export type HtmlEscapedCallback = (opts: HtmlEscapedCallbackOpts) => Promise<string>3export type HtmlEscaped = {4 isEscaped: true5 callbacks?: HtmlEscapedCallback[]6}7export type HtmlEscapedString = string & HtmlEscaped8export type StringBuffer = (string | Promise<string>)[]9import { raw } from '../helper/html'10
3 unmodified lines
14const escapeRe = /[&<>'"]/1516export const stringBufferToString = async (buffer: StringBuffer): Promise<HtmlEscapedString> => {17 let str = ''13 const promises: Promise<string>[] = []18 const callbacks: HtmlEscapedCallback[] = []19 for (let i = buffer.length - 1; i >= 0; i--) {20 let r = await buffer[i]21 if (typeof r === 'object') {17 promises.push(...((r as HtmlEscapedString).promises || []))22 callbacks.push(...((r as HtmlEscapedString).callbacks || []))23 }24 r = await (typeof r === 'object' ? (r as HtmlEscapedString).toString() : r)25 if (typeof r === 'object') {21 promises.push(...((r as HtmlEscapedString).promises || []))26 callbacks.push(...((r as HtmlEscapedString).callbacks || []))27 }28 str += r29 }3026 return raw(str, promises)31 return raw(str, callbacks)32}3334export const escapeToBuffer = (str: string, buffer: StringBuffer): void => {35 const match = str.search(escapeRe)
32 unmodified lines
68 }6970 buffer[0] += str.substring(lastIndex, index)71}7273export const resolveStream = (74 str: string | HtmlEscapedString,75 buffer?: [string]76): Promise<string> => {77 if (!(str as HtmlEscapedString).callbacks?.length) {78 return Promise.resolve(str)79 }80 const callbacks = (str as HtmlEscapedString).callbacks as HtmlEscapedCallback[]81 if (buffer) {82 buffer[0] += str83 } else {84 buffer = [str]85 }86 return Promise.all(callbacks.map((c) => c({ buffer }))).then((res) =>87 Promise.all(res.map((str) => resolveStream(str, buffer))).then(() => (buffer as [string])[0])88 )89}
modified:src/validator/validator.test.ts+12 added-12 removed
176 unmodified lines
177 type Expected = {178 id: number179 }180 type verify = Expect<Equal<Expected, typeof post>>181 return c.jsonT({181 return c.json({182 post,183 })184 })185
50 unmodified lines
236 id: number237 title: string238 }239 type verify = Expect<Equal<Expected, typeof post>>240 return c.jsonT({240 return c.json({241 post: post,242 })243 })244
64 unmodified lines
309 title: z.string(),310 })311 app.post('/post', zodValidator('form', schema), (c) => {312 const post = c.req.valid('form')313 return c.jsonT({313 return c.json({314 post: post,315 })316 })317
39 unmodified lines
357 })358359 app.get('/search', zodValidator('query', schema), (c) => {360 const res = c.req.valid('query')361 return c.jsonT({361 return c.json({362 page: res.page,363 tags: res.tag,364 })365 })
22 unmodified lines
388 })389390 app.get('/posts', zodValidator('queries', schema), (c) => {391 const res = c.req.valid('queries')392 return c.jsonT({392 return c.json({393 tags: res.tags,394 })395 })396
25 unmodified lines
422 title: z.string(),423 })424 app.get('/users/:id/books/:title', zodValidator('param', schema), (c) => {425 const param = c.req.valid('param')426 return c.jsonT({426 return c.json({427 param: param,428 })429 })430
24 unmodified lines
455456 app.get('/ping', zodValidator('header', schema), (c) => {457 const data = c.req.valid('header')458 const xRequestId = data['x-request-id']459 return c.jsonT({459 return c.json({460 xRequestId,461 })462 })463
28 unmodified lines
492 })493494 app.get('/api/user', zodValidator('cookie', schema), (c) => {495 const { debug } = c.req.valid('cookie')496 return c.jsonT({496 return c.json({497 debug,498 })499 })500
49 unmodified lines
550 const formValidatedData = c.req.valid('form')551 type verify2 = Expect<Equal<{ title: string }, typeof formValidatedData>>552 const { page } = c.req.valid('query')553 const { title } = c.req.valid('form')554 return c.jsonT({ page, title })554 return c.json({ page, title })555 }556 )557558 type Actual = ExtractSchema<typeof route>
95 unmodified lines
654 q: 'bar',655 }656 }),657 (c) => {658 return c.jsonT({658 return c.json({659 success: true,660 })661 }662 )
32 unmodified lines
695 page: '2',696 }697 }),698 (c) => {699 return c.jsonT({699 return c.json({700 posts: [701 {702 title: 'foo',703 },
12 unmodified lines
716 title: 'Hello',717 }718 }),719 (c) => {720 return c.jsonT({720 return c.json({721 success: true,722 })723 }724 )
100 unmodified lines
modified:src/compose.test.ts+4 added-4 removed
7 unmodified lines
8 res: Record<string, string>9 finalized: boolean10}1112type MiddlewareTuple = [Function, Params]12type MiddlewareTuple = [[Function, unknown], Params]1314class ExpectedError extends Error {}1516function buildMiddlewareTuple(fn: Function, params?: Params): MiddlewareTuple {17 return [fn, params || {}]17 return [[fn, undefined], params || {}]18}1920describe('compose', () => {21 const middleware: MiddlewareTuple[] = []
674 unmodified lines
696 return next()697 }698 middleware.push(buildMiddlewareTuple(fn1))699700 for (const [fn] of middleware) {700 for (const [[fn]] of middleware) {701 expect(fn).toEqual(fn1)702 }703704 compose(middleware)705706 for (const [fn] of middleware) {706 for (const [[fn]] of middleware) {707 expect(fn).toEqual(fn1)708 }709 })710
30 unmodified lines
modified:src/compose.ts+3 added-6 removed
7 unmodified lines
8}910// Based on the code in the MIT licensed `koa-compose` package.11export const compose = <C extends ComposeContext, E extends Env = Env>(12 middleware: [Function, ParamIndexMap | Params][],12 middleware: [[Function, unknown], ParamIndexMap | Params][],13 onError?: ErrorHandler<E>,14 onNotFound?: NotFoundHandler<E>15) => {16 return (context: C, next?: Function) => {
10 unmodified lines
27 let isError = false28 let handler2930 if (middleware[i]) {31 handler = middleware[i][0]31 handler = middleware[i][0][0]32 if (context instanceof Context) {33 context.req.setParams(middleware[i][1])33 context.req.routeIndex = i34 }35 } else {36 handler = (i === middleware.length && next) || undefined37 }
17 unmodified lines
55 }56 }57 }5859 if (res !== undefined && 'response' in res) {60 res = res['response']61 }59 if (res && (context.finalized === false || isError)) {60 context.res = res61 }62 return context
3 unmodified lines
modified:src/context.test.ts-9 removed
252 unmodified lines
253 expect(res.headers.get('content-type')).toMatch(/^text\/plain/)254 expect(await res.text()).toBe('foo')255 })256257 it('c.jsonT()', async () => {258 const originalResponse = new Response('foo')259 const tRes = c.jsonT({ foo: 'bar' }, originalResponse)260 const res = tRes['response'] as Response261 expect(res.headers.get('content-type')).toMatch(/^application\/json/)262 expect(await res.json()).toEqual({ foo: 'bar' })263 expect(tRes.status).toEqual(200)264 })265257 it('c.html()', async () => {258 const originalResponse = new Response('foo')259 const res = await c.html('<h1>foo</h1>', originalResponse)260 expect(res.headers.get('content-type')).toMatch(/^text\/html/)
75 unmodified lines
modified:src/context.ts+121 added-126 removed
1 unmodified line
2import type { HonoRequest } from './request'3import type { Env, FetchEventLike, NotFoundHandler, Input, TypedResponse } from './types'4import type { CookieOptions } from './utils/cookie'5import { serialize } from './utils/cookie'6import { resolveStream } from './utils/html'7import type { StatusCode } from './utils/http-status'8import { StreamingApi } from './utils/stream'9import type { JSONValue, InterfaceToType } from './utils/types'10
10 unmodified lines
21export interface ContextRenderer {}22interface DefaultRenderer {23 (content: string | Promise<string>): Response | Promise<Response>24}2526export type Renderer = ContextRenderer extends Function ? ContextRenderer : DefaultRenderer2728interface Get<E extends Env> {29 <Key extends keyof ContextVariableMap>(key: Key): ContextVariableMap[Key]
17 unmodified lines
47 (text: string, init?: ResponseInit): Response48}4950interface JSONRespond {49 <T = JSONValue>(object: T, status?: StatusCode, headers?: HeaderRecord): Response50 <T = JSONValue>(object: T, init?: ResponseInit): Response51}5253interface JSONTRespond {51 <T>(55 object: InterfaceToType<T> extends JSONValue ? T : JSONValue,52 object: InterfaceToType<T> extends JSONValue ? T : T extends JSONValue ? JSONValue : T,53 status?: StatusCode,54 headers?: HeaderRecord58 ): TypedResponse<59 InterfaceToType<T> extends JSONValue60 ? JSONValue extends InterfaceToType<T>61 ? never62 : T63 : never64 >65 <T>(66 object: InterfaceToType<T> extends JSONValue ? T : JSONValue,67 init?: ResponseInit68 ): TypedResponse<69 InterfaceToType<T> extends JSONValue70 ? JSONValue extends InterfaceToType<T>71 ? never72 : T73 : never74 >55 ): Response &56 TypedResponse<57 InterfaceToType<T> extends JSONValue58 ? JSONValue extends InterfaceToType<T>59 ? never60 : T61 : never62 >63 <T>(object: InterfaceToType<T> extends JSONValue ? T : JSONValue, init?: ResponseInit): Response &64 TypedResponse<65 InterfaceToType<T> extends JSONValue66 ? JSONValue extends InterfaceToType<T>67 ? never68 : T69 : never70 >71}7273interface HTMLRespond {74 (html: string | Promise<string>, status?: StatusCode, headers?: HeaderRecord):
22 unmodified lines
97 private _var: E['Variables'] = {}98 finalized: boolean = false99 error: Error | undefined = undefined100105 private _status: StatusCode = 200106 private _exCtx: FetchEventLike | ExecutionContext | undefined // _executionCtx107 private _h: Headers | undefined = undefined // _headers108 private _pH: Record<string, string> | undefined = undefined // _preparedHeaders109 private _res: Response | undefined110 private _init = true111 private _renderer: Renderer = (content: string | Promise<string>) => this.html(content)101 #status: StatusCode = 200102 #executionCtx: FetchEventLike | ExecutionContext | undefined103 #headers: Headers | undefined = undefined104 #preparedHeaders: Record<string, string> | undefined = undefined105 #res: Response | undefined106 #isFresh = true107 private renderer: Renderer = (content: string | Promise<string>) => this.html(content)108 private notFoundHandler: NotFoundHandler<E> = () => new Response()109110 constructor(req: HonoRequest<P, I['out']>, options?: ContextOptions<E>) {111 this.req = req112 if (options) {117 this._exCtx = options.executionCtx113 this.#executionCtx = options.executionCtx114 this.env = options.env115 if (options.notFoundHandler) {116 this.notFoundHandler = options.notFoundHandler117 }118 }119 }120121 get event(): FetchEventLike {126 if (this._exCtx && 'respondWith' in this._exCtx) {127 return this._exCtx122 if (this.#executionCtx && 'respondWith' in this.#executionCtx) {123 return this.#executionCtx124 } else {125 throw Error('This context has no FetchEvent')126 }127 }128129 get executionCtx(): ExecutionContext {134 if (this._exCtx) {135 return this._exCtx as ExecutionContext130 if (this.#executionCtx) {131 return this.#executionCtx as ExecutionContext132 } else {133 throw Error('This context has no ExecutionContext')134 }135 }136137 get res(): Response {142 this._init = false143 return (this._res ||= new Response('404 Not Found', { status: 404 }))138 this.#isFresh = false139 return (this.#res ||= new Response('404 Not Found', { status: 404 }))140 }141142 set res(_res: Response | undefined) {147 this._init = false148 if (this._res && _res) {149 this._res.headers.delete('content-type')150 this._res.headers.forEach((v, k) => {143 this.#isFresh = false144 if (this.#res && _res) {145 this.#res.headers.delete('content-type')146 this.#res.headers.forEach((v, k) => {147 _res.headers.set(k, v)148 })149 }154 this._res = _res150 this.#res = _res151 this.finalized = true152 }153158 /**159 * @experimental160 * `c.render()` is an experimental feature.161 * The API might be changed.162 */154 // eslint-disable-next-line @typescript-eslint/ban-ts-comment155 // @ts-ignore156 // eslint-disable-next-line @typescript-eslint/no-explicit-any166 render: Renderer = (...args: any[]) => this._renderer(...args)157 render: Renderer = (...args: any[]) => this.renderer(...args)158168 /**169 * @experimental170 * `c.setRenderer()` is an experimental feature.171 * The API might be changed.172 */159 setRenderer = (renderer: Renderer) => {174 this._renderer = renderer160 this.renderer = renderer161 }162163 header = (name: string, value: string | undefined, options?: { append?: boolean }): void => {164 // Clear the header165 if (value === undefined) {180 if (this._h) {181 this._h.delete(name)182 } else if (this._pH) {183 delete this._pH[name.toLocaleLowerCase()]166 if (this.#headers) {167 this.#headers.delete(name)168 } else if (this.#preparedHeaders) {169 delete this.#preparedHeaders[name.toLocaleLowerCase()]170 }171 if (this.finalized) {172 this.res.headers.delete(name)173 }174 return175 }176177 if (options?.append) {192 if (!this._h) {193 this._init = false194 this._h = new Headers(this._pH)195 this._pH = {}178 if (!this.#headers) {179 this.#isFresh = false180 this.#headers = new Headers(this.#preparedHeaders)181 this.#preparedHeaders = {}182 }197 this._h.append(name, value)183 this.#headers.append(name, value)184 } else {199 if (this._h) {200 this._h.set(name, value)185 if (this.#headers) {186 this.#headers.set(name, value)187 } else {202 this._pH ??= {}203 this._pH[name.toLowerCase()] = value188 this.#preparedHeaders ??= {}189 this.#preparedHeaders[name.toLowerCase()] = value190 }191 }192193 if (this.finalized) {
5 unmodified lines
199 }200 }201202 status = (status: StatusCode): void => {217 this._init = false218 this._status = status203 this.#isFresh = false204 this.#status = status205 }206207 set: Set<E> = (key: string, value: unknown) => {208 this._var ??= {}
14 unmodified lines
223 arg?: StatusCode | ResponseInit,224 headers?: HeaderRecord225 ): Response => {226 // Optimized241 if (this._init && !headers && !arg && this._status === 200) {227 if (this.#isFresh && !headers && !arg && this.#status === 200) {228 return new Response(data, {243 headers: this._pH,229 headers: this.#preparedHeaders,230 })231 }232233 // Return Response immediately if arg is ResponseInit.234 if (arg && typeof arg !== 'number') {235 const res = new Response(data, arg)250 const contentType = this._pH?.['content-type']236 const contentType = this.#preparedHeaders?.['content-type']237 if (contentType) {238 res.headers.set('content-type', contentType)239 }240 return res241 }242257 const status = arg ?? this._status258 this._pH ??= {}243 const status = arg ?? this.#status244 this.#preparedHeaders ??= {}245260 this._h ??= new Headers()261 for (const [k, v] of Object.entries(this._pH)) {262 this._h.set(k, v)246 this.#headers ??= new Headers()247 for (const [k, v] of Object.entries(this.#preparedHeaders)) {248 this.#headers.set(k, v)249 }250265 if (this._res) {266 this._res.headers.forEach((v, k) => {267 this._h?.set(k, v)251 if (this.#res) {252 this.#res.headers.forEach((v, k) => {253 this.#headers?.set(k, v)254 })269 for (const [k, v] of Object.entries(this._pH)) {270 this._h.set(k, v)255 for (const [k, v] of Object.entries(this.#preparedHeaders)) {256 this.#headers.set(k, v)257 }258 }259260 headers ??= {}261 for (const [k, v] of Object.entries(headers)) {262 if (typeof v === 'string') {277 this._h.set(k, v)263 this.#headers.set(k, v)264 } else {279 this._h.delete(k)265 this.#headers.delete(k)266 for (const v2 of v) {281 this._h.append(k, v2)267 this.#headers.append(k, v2)268 }269 }270 }271272 return new Response(data, {273 status,288 headers: this._h,274 headers: this.#headers,275 })276 }277278 body: BodyRespond = (
12 unmodified lines
291 headers?: HeaderRecord292 ): Response => {293 // If the header is empty, return Response immediately.294 // Content-Type will be added automatically as `text/plain`.309 if (!this._pH) {310 if (this._init && !headers && !arg) {295 if (!this.#preparedHeaders) {296 if (this.#isFresh && !headers && !arg) {297 return new Response(text)298 }313 this._pH = {}299 this.#preparedHeaders = {}300 }315 this._pH['content-type'] = TEXT_PLAIN301 this.#preparedHeaders['content-type'] = TEXT_PLAIN302 return typeof arg === 'number'303 ? this.newResponse(text, arg, headers)304 : this.newResponse(text, arg)305 }306321 json: JSONRespond = <T = {}>(322 object: T,307 json: JSONRespond = <T>(308 object: InterfaceToType<T> extends JSONValue ? T : T extends JSONValue ? JSONValue : T,309 arg?: StatusCode | ResponseInit,310 headers?: HeaderRecord311 ): Response &312 TypedResponse<313 InterfaceToType<T> extends JSONValue314 ? JSONValue extends InterfaceToType<T>315 ? never316 : T317 : never325 ) => {318 > => {319 const body = JSON.stringify(object)327 this._pH ??= {}328 this._pH['content-type'] = 'application/json; charset=UTF-8'329 return typeof arg === 'number'330 ? this.newResponse(body, arg, headers)331 : this.newResponse(body, arg)320 this.#preparedHeaders ??= {}321 this.#preparedHeaders['content-type'] = 'application/json; charset=UTF-8'322 /* eslint-disable @typescript-eslint/no-explicit-any */323 return (324 typeof arg === 'number' ? this.newResponse(body, arg, headers) : this.newResponse(body, arg)325 ) as any326 }327328 /**329 * @deprecated330 * `c.jsonT()` will be removed in v4.331 * Use `c.json()` instead of `c.jsonT()`.332 * `c.json()` now returns data type, so you can just replace `c.jsonT()` to `c.json()`.333 */334 jsonT: JSONTRespond = <T>(335 object: InterfaceToType<T> extends JSONValue ? T : JSONValue,334 jsonT: JSONRespond = <T>(335 object: InterfaceToType<T> extends JSONValue ? T : T extends JSONValue ? JSONValue : T,336 arg?: StatusCode | ResponseInit,337 headers?: HeaderRecord338 ): TypedResponse<339 InterfaceToType<T> extends JSONValue340 ? JSONValue extends InterfaceToType<T>341 ? never342 : T343 : never344 > => {345 const response =346 typeof arg === 'number' ? this.json(object, arg, headers) : this.json(object, arg)347348 return {349 response,350 // eslint-disable-next-line @typescript-eslint/no-explicit-any351 data: object as any,352 format: 'json',353 status: response.status,354 }338 ): Response &339 TypedResponse<340 InterfaceToType<T> extends JSONValue341 ? JSONValue extends InterfaceToType<T>342 ? never343 : T344 : never345 > => {346 // eslint-disable-next-line @typescript-eslint/no-explicit-any347 return this.json(object, arg as any, headers) as any348 }349350 html: HTMLRespond = (351 html: string | Promise<string>,352 arg?: StatusCode | ResponseInit,353 headers?: HeaderRecord354 ): Response | Promise<Response> => {362 this._pH ??= {}363 this._pH['content-type'] = 'text/html; charset=UTF-8'355 this.#preparedHeaders ??= {}356 this.#preparedHeaders['content-type'] = 'text/html; charset=UTF-8'357358 if (typeof html === 'object') {359 if (!(html instanceof Promise)) {360 html = (html as string).toString() // HtmlEscapedString object to string361 }362 if ((html as string | Promise<string>) instanceof Promise) {363 return (html as unknown as Promise<string>)364 .then((html) => resolveStream(html))370 return (html as unknown as Promise<string>).then((html) => {371 return typeof arg === 'number'372 ? this.newResponse(html, arg, headers)373 : this.newResponse(html, arg)374 })365 .then((html) => {366 return typeof arg === 'number'367 ? this.newResponse(html, arg, headers)368 : this.newResponse(html, arg)369 })370 }371 }372373 return typeof arg === 'number'
1 unmodified line
375 : this.newResponse(html as string, arg)376 }377378 redirect = (location: string, status: StatusCode = 302): Response => {384 this._h ??= new Headers()385 this._h.set('Location', location)379 this.#headers ??= new Headers()380 this.#headers.set('Location', location)381 return this.newResponse(null, status)382 }383384 streamText = (
95 unmodified lines
modified:src/helper.ts+1 added
3 unmodified lines
4export * from './helper/factory'5export * from './helper/html'6export * from './helper/streaming'7export * from './helper/testing'8export * from './helper/dev'
modified:src/hono-base.ts+35 added-41 removed
13 unmodified lines
14 MiddlewareHandlerInterface,15 Next,16 NotFoundHandler,17 OnHandlerInterface,18 TypedResponse,18 MergePath,19 MergeSchemaPath,20 FetchEventLike,21 Schema,22 RouterRoute,23} from './types'24import { getPath, getPathNoStrict, getQueryStrings, mergePath } from './utils/url'2526type Methods = typeof METHODS[number] | typeof METHOD_NAME_ALL_LOWERCASE2728interface RouterRoute {29 path: string30 method: string31 handler: H32}3328function defineDynamicClass(): {29 new <E extends Env = Env, S extends Schema = {}, BasePath extends string = '/'>(): {30 [M in Methods]: HandlerInterface<E, M, S, BasePath>31 } & {
21 unmodified lines
53type GetPath<E extends Env> = (request: Request, options?: { env?: E['Bindings'] }) => string5455export type HonoOptions<E extends Env> = {56 strict?: boolean63 router?: Router<H>57 router?: Router<[H, RouterRoute]>58 getPath?: GetPath<E>59}6061class Hono<
4 unmodified lines
66 /*67 This class is like an abstract class and does not have a router.68 To use it, inherit the class and implement router in the constructor.69 */76 router!: Router<H>70 router!: Router<[H, RouterRoute]>71 readonly getPath: GetPath<E>78 private _basePath: string = '/'79 private path: string = '/'72 #basePath: string = '/'73 #path: string = '/'7475 routes: RouterRoute[] = []7677 constructor(options: HonoOptions<E> = {}) {
3 unmodified lines
81 const allMethods = [...METHODS, METHOD_NAME_ALL_LOWERCASE]82 allMethods.map((method) => {83 this[method] = (args1: string | H, ...args: H[]) => {84 if (typeof args1 === 'string') {91 this.path = args185 this.#path = args186 } else {93 this.addRoute(method, this.path, args1)87 this.addRoute(method, this.#path, args1)88 }89 args.map((handler) => {90 if (typeof handler !== 'string') {97 this.addRoute(method, this.path, handler)91 this.addRoute(method, this.#path, handler)92 }93 })94 // eslint-disable-next-line @typescript-eslint/no-explicit-any100 return this95 return this as any96 }97 })9899 // Implementation of app.on(method, path, ...handlers[])100 this.on = (method: string | string[], path: string, ...handlers: H[]) => {101 if (!method) return this107 this.path = path102 this.#path = path103 for (const m of [method].flat()) {104 handlers.map((handler) => {110 this.addRoute(m.toUpperCase(), this.path, handler)105 this.addRoute(m.toUpperCase(), this.#path, handler)106 })107 }108 // eslint-disable-next-line @typescript-eslint/no-explicit-any113 return this109 return this as any110 }111112 // Implementation of app.use(...handlers[]) or app.get(path, ...handlers[])113 // eslint-disable-next-line @typescript-eslint/no-explicit-any114 this.use = (arg1: string | MiddlewareHandler<any>, ...handlers: MiddlewareHandler<any>[]) => {115 if (typeof arg1 === 'string') {120 this.path = arg1116 this.#path = arg1117 } else {118 handlers.unshift(arg1)119 }120 handlers.map((handler) => {125 this.addRoute(METHOD_NAME_ALL, this.path, handler)121 this.addRoute(METHOD_NAME_ALL, this.#path, handler)122 })123 return this124 }125
42 unmodified lines
168 }169170 basePath<SubPath extends string>(path: SubPath): Hono<E, S, MergePath<BasePath, SubPath>> {171 const subApp = this.clone()176 subApp._basePath = mergePath(this._basePath, path)172 subApp.#basePath = mergePath(this.#basePath, path)173 return subApp174 }175176 onError(handler: ErrorHandler<E>) {
5 unmodified lines
182 this.notFoundHandler = handler183 return this184 }185186 /**187 * @deprecated188 * Use `showRoutes()` utility methods provided by 'hono/helper' instead of `app.showRoutes()`.189 * `app.showRoutes()` will be removed in v4.190 * @example191 * You could rewrite `app.showRoutes()` as follows192 * import { showRoutes } from 'hono/helper'193 * showRoutes(app)194 */195 showRoutes() {196 const length = 8197 this.routes.map((route) => {198 console.log(
7 unmodified lines
206 // eslint-disable-next-line @typescript-eslint/no-explicit-any207 applicationHandler: (request: Request, ...args: any) => Response | Promise<Response>,208 optionHandler?: (c: Context) => unknown209 ): Hono<E, S, BasePath> {205 const mergedPath = mergePath(this._basePath, path)210 const mergedPath = mergePath(this.#basePath, path)211 const pathPrefixLength = mergedPath === '/' ? 0 : mergedPath.length212213 const handler: MiddlewareHandler = async (c, next) => {214 let executionContext: ExecutionContext | undefined = undefined
36 unmodified lines
251 }252253 private addRoute(method: string, path: string, handler: H) {254 method = method.toUpperCase()250 path = mergePath(this._basePath, path)251 this.router.add(method, path, handler)255 path = mergePath(this.#basePath, path)256 const r: RouterRoute = { path: path, method: method, handler: handler }257 this.router.add(method, path, [handler, r])258 this.routes.push(r)259 }260261 private matchRoute(method: string, path: string) {
19 unmodified lines
281 new Response(null, await this.dispatch(request, executionCtx, env, 'GET')))()282 }283284 const path = this.getPath(request, { env })280 const [handlers, paramStash] = this.matchRoute(method, path)285 const matchResult = this.matchRoute(method, path)286282 const c = new Context(new HonoRequest(request, path, paramStash), {287 const c = new Context(new HonoRequest(request, path, matchResult), {288 env,289 executionCtx,290 notFoundHandler: this.notFoundHandler,291 })292293 // Do not `compose` if it has only one handler289 if (handlers.length === 1) {294 if (matchResult[0].length === 1) {295 let res: ReturnType<H>291292 c.req.setParams(handlers[0][1])296 try {294 res = handlers[0][0](c, async () => {})297 res = matchResult[0][0][0][0](c, async () => {})298 if (!res) {299 return this.notFoundHandler(c)300 }301 } catch (err) {
1 unmodified line
303 }304305 if (res instanceof Response) return res306304 if ('response' in res) {305 res = res.response306 }307308 if (res instanceof Response) return res309307 return (async () => {311 let awaited: Response | TypedResponse | void308 let awaited: Response | void309 try {310 awaited = await res314 if (awaited !== undefined && 'response' in awaited) {315 awaited = awaited['response'] as Response316 }311 if (!awaited) {312 return this.notFoundHandler(c)313 }314 } catch (err) {
2 unmodified lines
317 return awaited318 })()319 }320327 const composed = compose<Context>(handlers, this.errorHandler, this.notFoundHandler)321 const composed = compose<Context>(matchResult[0], this.errorHandler, this.notFoundHandler)322323 return (async () => {324 try {325 const context = await composed(c)
53 unmodified lines
modified:src/hono.test.ts+439 added-17 removed
2099 unmodified lines
2100 expect(console.log).toBeCalled()2101 })2102})21032104describe('jsonT', () => {2104describe('json', () => {2105 const api = new Hono()21062107 api.get('/message', (c) => {2108 return c.jsonT({2108 return c.json({2109 message: 'Hello',2110 })2111 })21122113 api.get('/message-async', async (c) => {2114 return c.jsonT({2114 return c.json({2115 message: 'Hello',2116 })2117 })2118
421 unmodified lines
2540 c.set('echo5', (str) => str)2541 await next()2542 }25432544 const mw6 =2545 (): MiddlewareHandler<{2546 Variables: {2547 echo6: (str: string) => string2548 }2549 }> =>2550 async (c, next) => {2551 c.set('echo6', (str) => str)2552 await next()2553 }25542555 const mw7 =2556 (): MiddlewareHandler<{2557 Variables: {2558 echo7: (str: string) => string2559 }2560 }> =>2561 async (c, next) => {2562 c.set('echo7', (str) => str)2563 await next()2564 }25652566 const mw8 =2567 (): MiddlewareHandler<{2568 Variables: {2569 echo8: (str: string) => string2570 }2571 }> =>2572 async (c, next) => {2573 c.set('echo8', (str) => str)2574 await next()2575 }25762577 const mw9 =2578 (): MiddlewareHandler<{2579 Variables: {2580 echo9: (str: string) => string2581 }2582 }> =>2583 async (c, next) => {2584 c.set('echo9', (str) => str)2585 await next()2586 }25872588 const mw10 =2589 (): MiddlewareHandler<{2590 Variables: {2591 echo10: (str: string) => string2592 }2593 }> =>2594 async (c, next) => {2595 c.set('echo10', (str) => str)2596 await next()2597 }25982599 app.use('/no-path/1').get(mw(), (c) => {2600 return c.text(c.var.echo('hello'))2601 })2602
10 unmodified lines
2613 c.var.echo('hello') + c.var.echo2('hello2') + c.var.echo3('hello3') + c.var.echo4('hello4')2614 )2615 })26162562 // @ts-expect-error2617 app.use('/no-path/5').get(mw(), mw2(), mw3(), mw4(), mw5(), (c) => {2618 return c.text(2565 // @ts-expect-error2619 c.var.echo('hello') +2567 // @ts-expect-error2620 c.var.echo2('hello2') +2569 // @ts-expect-error2621 c.var.echo3('hello3') +2571 // @ts-expect-error2622 c.var.echo4('hello4') +2573 // @ts-expect-error2623 c.var.echo5('hello5')2624 )2625 })26262627 app.use('/no-path/6').get(mw(), mw2(), mw3(), mw4(), mw5(), mw6(), (c) => {2628 return c.text(2629 c.var.echo('hello') +2630 c.var.echo2('hello2') +2631 c.var.echo3('hello3') +2632 c.var.echo4('hello4') +2633 c.var.echo5('hello5') +2634 c.var.echo6('hello6')2635 )2636 })26372638 app.use('/no-path/7').get(mw(), mw2(), mw3(), mw4(), mw5(), mw6(), mw7(), (c) => {2639 return c.text(2640 c.var.echo('hello') +2641 c.var.echo2('hello2') +2642 c.var.echo3('hello3') +2643 c.var.echo4('hello4') +2644 c.var.echo5('hello5') +2645 c.var.echo6('hello6') +2646 c.var.echo7('hello7')2647 )2648 })26492650 app.use('/no-path/8').get(mw(), mw2(), mw3(), mw4(), mw5(), mw6(), mw7(), mw8(), (c) => {2651 return c.text(2652 c.var.echo('hello') +2653 c.var.echo2('hello2') +2654 c.var.echo3('hello3') +2655 c.var.echo4('hello4') +2656 c.var.echo5('hello5') +2657 c.var.echo6('hello6') +2658 c.var.echo7('hello7') +2659 c.var.echo8('hello8')2660 )2661 })26622663 app.use('/no-path/9').get(mw(), mw2(), mw3(), mw4(), mw5(), mw6(), mw7(), mw8(), mw9(), (c) => {2664 return c.text(2665 c.var.echo('hello') +2666 c.var.echo2('hello2') +2667 c.var.echo3('hello3') +2668 c.var.echo4('hello4') +2669 c.var.echo5('hello5') +2670 c.var.echo6('hello6') +2671 c.var.echo7('hello7') +2672 c.var.echo8('hello8') +2673 c.var.echo9('hello9')2674 )2675 })26762677 app.use('/no-path/10').get(2678 // @ts-expect-error2679 mw(),2680 mw2(),2681 mw3(),2682 mw4(),2683 mw5(),2684 mw6(),2685 mw7(),2686 mw8(),2687 mw9(),2688 mw10(),2689 (c) => {2690 return c.text(2691 // @ts-expect-error2692 c.var.echo('hello') +2693 // @ts-expect-error2694 c.var.echo2('hello2') +2695 // @ts-expect-error2696 c.var.echo3('hello3') +2697 // @ts-expect-error2698 c.var.echo4('hello4') +2699 // @ts-expect-error2700 c.var.echo5('hello5') +2701 // @ts-expect-error2702 c.var.echo6('hello6') +2703 // @ts-expect-error2704 c.var.echo7('hello7') +2705 // @ts-expect-error2706 c.var.echo8('hello8') +2707 // @ts-expect-error2708 c.var.echo9('hello9') +2709 // @ts-expect-error2710 c.var.echo10('hello10')2711 )2712 }2713 )27142715 app.get('*', mw())27162717 app.get('/path/1', mw(), (c) => {2718 return c.text(c.var.echo('hello'))
12 unmodified lines
2731 c.var.echo('hello') + c.var.echo2('hello2') + c.var.echo3('hello3') + c.var.echo4('hello4')2732 )2733 })27342598 // @ts-expect-error2735 app.get('/path/5', mw(), mw2(), mw3(), mw4(), mw5(), (c) => {2736 return c.text(2737 c.var.echo('hello') +2738 c.var.echo2('hello2') +2739 c.var.echo3('hello3') +2740 c.var.echo4('hello4') +2741 c.var.echo5('hello5')2742 )2743 })27442745 app.get('/path/6', mw(), mw2(), mw3(), mw4(), mw5(), mw6(), (c) => {2746 return c.text(2747 c.var.echo('hello') +2748 c.var.echo2('hello2') +2749 c.var.echo3('hello3') +2750 c.var.echo4('hello4') +2751 c.var.echo5('hello5') +2752 c.var.echo6('hello6')2753 )2754 })27552756 app.get('/path/7', mw(), mw2(), mw3(), mw4(), mw5(), mw6(), mw7(), (c) => {2757 return c.text(2758 c.var.echo('hello') +2759 c.var.echo2('hello2') +2760 c.var.echo3('hello3') +2761 c.var.echo4('hello4') +2762 c.var.echo5('hello5') +2763 c.var.echo6('hello6') +2764 c.var.echo7('hello7')2765 )2766 })27672768 app.get('/path/8', mw(), mw2(), mw3(), mw4(), mw5(), mw6(), mw7(), mw8(), (c) => {2769 return c.text(2770 c.var.echo('hello') +2771 c.var.echo2('hello2') +2772 c.var.echo3('hello3') +2773 c.var.echo4('hello4') +2774 c.var.echo5('hello5') +2775 c.var.echo6('hello6') +2776 c.var.echo7('hello7') +2777 c.var.echo8('hello8')2778 )2779 })27802781 app.get('/path/9', mw(), mw2(), mw3(), mw4(), mw5(), mw6(), mw7(), mw8(), mw9(), (c) => {2782 return c.text(2783 c.var.echo('hello') +2784 c.var.echo2('hello2') +2785 c.var.echo3('hello3') +2786 c.var.echo4('hello4') +2787 c.var.echo5('hello5') +2788 c.var.echo6('hello6') +2789 c.var.echo7('hello7') +2790 c.var.echo8('hello8') +2791 c.var.echo9('hello9')2792 )2793 })27942795 // @ts-expect-error2796 app.get('/path/10', mw(), mw2(), mw3(), mw4(), mw5(), mw6(), mw7(), mw8(), mw9(), mw10(), (c) => {2797 return c.text(2798 // @ts-expect-error2799 c.var.echo('hello') +2800 // @ts-expect-error2801 c.var.echo2('hello2') +
1 unmodified line
2803 c.var.echo3('hello3') +2804 // @ts-expect-error2805 c.var.echo4('hello4') +2806 // @ts-expect-error2610 c.var.echo5('hello5')2807 c.var.echo5('hello5') +2808 // @ts-expect-error2809 c.var.echo6('hello6') +2810 // @ts-expect-error2811 c.var.echo7('hello7') +2812 // @ts-expect-error2813 c.var.echo8('hello8') +2814 // @ts-expect-error2815 c.var.echo9('hello9') +2816 // @ts-expect-error2817 c.var.echo10('hello10')2818 )2819 })28202821 app.on('GET', '/on/1', mw(), (c) => {
13 unmodified lines
2835 c.var.echo('hello') + c.var.echo2('hello2') + c.var.echo3('hello3') + c.var.echo4('hello4')2836 )2837 })28382632 // @ts-expect-error2839 app.on('GET', '/on/5', mw(), mw2(), mw3(), mw4(), mw5(), (c) => {2840 return c.text(2635 // @ts-expect-error2841 c.var.echo('hello') +2637 // @ts-expect-error2842 c.var.echo2('hello2') +2639 // @ts-expect-error2843 c.var.echo3('hello3') +2641 // @ts-expect-error2844 c.var.echo4('hello4') +2845 c.var.echo5('hello5')2846 )2847 })28482849 app.on('GET', '/on/6', mw(), mw2(), mw3(), mw4(), mw5(), mw6(), (c) => {2850 return c.text(2851 c.var.echo('hello') +2852 c.var.echo2('hello2') +2853 c.var.echo3('hello3') +2854 c.var.echo4('hello4') +2855 c.var.echo5('hello5') +2856 c.var.echo6('hello6')2857 )2858 })28592860 app.on('GET', '/on/7', mw(), mw2(), mw3(), mw4(), mw5(), mw6(), mw7(), (c) => {2861 return c.text(2862 c.var.echo('hello') +2863 c.var.echo2('hello2') +2864 c.var.echo3('hello3') +2865 c.var.echo4('hello4') +2866 c.var.echo5('hello5') +2867 c.var.echo6('hello6') +2868 c.var.echo7('hello7')2869 )2870 })28712872 app.on('GET', '/on/8', mw(), mw2(), mw3(), mw4(), mw5(), mw6(), mw7(), mw8(), (c) => {2873 return c.text(2874 c.var.echo('hello') +2875 c.var.echo2('hello2') +2876 c.var.echo3('hello3') +2877 c.var.echo4('hello4') +2878 c.var.echo5('hello5') +2879 c.var.echo6('hello6') +2880 c.var.echo7('hello7') +2881 c.var.echo8('hello8')2882 )2883 })28842885 app.on('GET', '/on/9', mw(), mw2(), mw3(), mw4(), mw5(), mw6(), mw7(), mw8(), mw9(), (c) => {2886 return c.text(2887 c.var.echo('hello') +2888 c.var.echo2('hello2') +2889 c.var.echo3('hello3') +2890 c.var.echo4('hello4') +2891 c.var.echo5('hello5') +2892 c.var.echo6('hello6') +2893 c.var.echo7('hello7') +2894 c.var.echo8('hello8') +2895 c.var.echo9('hello9')2896 )2897 })28982899 // @ts-expect-error2900 app.on(2901 'GET',2902 '/on/10',2903 mw(),2904 mw2(),2905 mw3(),2906 mw4(),2907 mw5(),2908 mw6(),2909 mw7(),2910 mw8(),2911 mw9(),2912 mw10(),2913 (c) => {2914 return c.text(2915 // @ts-expect-error2916 c.var.echo('hello') +2917 // @ts-expect-error2918 c.var.echo2('hello2') +2919 // @ts-expect-error2920 c.var.echo3('hello3') +2921 // @ts-expect-error2922 c.var.echo4('hello4') +2923 // @ts-expect-error2924 c.var.echo5('hello5') +2925 // @ts-expect-error2926 c.var.echo6('hello6') +2927 // @ts-expect-error2928 c.var.echo7('hello7') +2929 // @ts-expect-error2930 c.var.echo8('hello8') +2931 // @ts-expect-error2932 c.var.echo9('hello9') +2933 // @ts-expect-error2934 c.var.echo10('hello10')2935 )2936 }2937 )29382939 app.on(['GET', 'POST'], '/on/1', mw(), (c) => {2940 return c.text(c.var.echo('hello'))2941 })29422943 app.on(['GET', 'POST'], '/on/2', mw(), mw2(), (c) => {2944 return c.text(c.var.echo('hello') + c.var.echo2('hello2'))2945 })29462947 app.on(['GET', 'POST'], '/on/3', mw(), mw2(), mw3(), (c) => {2948 return c.text(c.var.echo('hello') + c.var.echo2('hello2') + c.var.echo3('hello3'))2949 })29502951 app.on(['GET', 'POST'], '/on/4', mw(), mw2(), mw3(), mw4(), (c) => {2952 return c.text(2953 c.var.echo('hello') + c.var.echo2('hello2') + c.var.echo3('hello3') + c.var.echo4('hello4')2954 )2955 })29562957 app.on(['GET', 'POST'], '/on/5', mw(), mw2(), mw3(), mw4(), mw5(), (c) => {2958 return c.text(2959 c.var.echo('hello') +2960 c.var.echo2('hello2') +2961 c.var.echo3('hello3') +2962 c.var.echo4('hello4') +2963 c.var.echo5('hello5')2964 )2965 })29662967 app.on(['GET', 'POST'], '/on/6', mw(), mw2(), mw3(), mw4(), mw5(), mw6(), (c) => {2968 return c.text(2969 c.var.echo('hello') +2970 c.var.echo2('hello2') +2971 c.var.echo3('hello3') +2972 c.var.echo4('hello4') +2973 c.var.echo5('hello5') +2974 c.var.echo6('hello6')2975 )2976 })29772978 app.on(['GET', 'POST'], '/on/7', mw(), mw2(), mw3(), mw4(), mw5(), mw6(), mw7(), (c) => {2979 return c.text(2980 c.var.echo('hello') +2981 c.var.echo2('hello2') +2982 c.var.echo3('hello3') +2983 c.var.echo4('hello4') +2984 c.var.echo5('hello5') +2985 c.var.echo6('hello6') +2986 c.var.echo7('hello7')2987 )2988 })29892990 app.on(['GET', 'POST'], '/on/8', mw(), mw2(), mw3(), mw4(), mw5(), mw6(), mw7(), mw8(), (c) => {2991 return c.text(2992 c.var.echo('hello') +2993 c.var.echo2('hello2') +2994 c.var.echo3('hello3') +2995 c.var.echo4('hello4') +2996 c.var.echo5('hello5') +2997 c.var.echo6('hello6') +2998 c.var.echo7('hello7') +2999 c.var.echo8('hello8')3000 )3001 })30023003 app.on(3004 ['GET', 'POST'],3005 '/on/9',3006 mw(),3007 mw2(),3008 mw3(),3009 mw4(),3010 mw5(),3011 mw6(),3012 mw7(),3013 mw8(),3014 mw9(),3015 (c) => {3016 return c.text(3017 c.var.echo('hello') +3018 c.var.echo2('hello2') +3019 c.var.echo3('hello3') +3020 c.var.echo4('hello4') +3021 c.var.echo5('hello5') +3022 c.var.echo6('hello6') +3023 c.var.echo7('hello7') +3024 c.var.echo8('hello8') +3025 c.var.echo9('hello9')3026 )3027 }3028 )30293030 // @ts-expect-error3031 app.on(3032 ['GET', 'POST'],3033 '/on/10',3034 mw(),3035 mw2(),3036 mw3(),3037 mw4(),3038 mw5(),3039 mw6(),3040 mw7(),3041 mw8(),3042 mw9(),3043 mw10(),3044 (c) => {3045 return c.text(3046 // @ts-expect-error3047 c.var.echo('hello') +3048 // @ts-expect-error3049 c.var.echo2('hello2') +3050 // @ts-expect-error3051 c.var.echo3('hello3') +3052 // @ts-expect-error3053 c.var.echo4('hello4') +3054 // @ts-expect-error3055 c.var.echo5('hello5') +3056 // @ts-expect-error3057 c.var.echo6('hello6') +3058 // @ts-expect-error3059 c.var.echo7('hello7') +3060 // @ts-expect-error3061 c.var.echo8('hello8') +3062 // @ts-expect-error3063 c.var.echo9('hello9') +3064 // @ts-expect-error3065 c.var.echo10('hello10')3066 )3067 }3068 )30693070 it('Should return the correct response - no-path', async () => {3071 let res = await app.request('/no-path/1')3072 expect(res.status).toBe(200)3073 expect(await res.text()).toBe('hello')
108 unmodified lines
31823183 app.use(mw())3184 app.use('*', mw())31852764 const route = app.get('/posts', mw(), (c) => c.jsonT(0))3186 const route = app.get('/posts', mw(), (c) => c.json(0))3187 const client = hc<typeof route>('/')3188 type key = keyof typeof client3189 type verify = Expect<Equal<'posts', key>>3190 })
10 unmodified lines
modified:src/request.test.ts+62 added-13 removed
1import { HonoRequest } from './request'2import type { RouterRoute } from './types'34describe('Query', () => {5 test('req.query() and req.queries()', () => {6 const rawRequest = new Request('http://localhost?page=2&tag=A&tag=B')
28 unmodified lines
3536describe('Param', () => {37 test('req.param() withth ParamStash', () => {38 const rawRequest = new Request('http://localhost?page=2&tag=A&tag=B')38 const req = new HonoRequest<'/:id/:name'>(rawRequest, '/123/key', ['123', 'key'])39 const req = new HonoRequest<'/:id/:name'>(rawRequest, '/123/key', [40 [41 [[undefined, {} as RouterRoute], { id: 0 }],42 [[undefined, {} as RouterRoute], { id: 0, name: 1 }],43 ],44 ['123', 'key'],45 ])4640 req.setParams({41 id: 0,42 })47 expect(req.param('id')).toBe('123')48 expect(req.param('name')).toBe(undefined)4946 req.setParams({47 id: 0,48 name: 1,49 })50 req.routeIndex = 151 expect(req.param('id')).toBe('123')52 expect(req.param('name')).toBe('key')53 })5455 test('req.param() without ParamStash', () => {56 const rawRequest = new Request('http://localhost?page=2&tag=A&tag=B')56 const req = new HonoRequest<'/:id/:name'>(rawRequest)57 const req = new HonoRequest<'/:id/:name'>(rawRequest, '/123/key', [58 [59 [[undefined, {} as RouterRoute], { id: '123' }],60 [[undefined, {} as RouterRoute], { id: '456', name: 'key' }],61 ],62 ])6358 req.setParams({59 id: '456',60 name: 'key',61 })64 expect(req.param('id')).toBe('123')65 expect(req.param('name')).toBe(undefined)6667 req.routeIndex = 168 expect(req.param('id')).toBe('456')69 expect(req.param('name')).toBe('key')70 })71})7273describe('matchedRoutes', () => {74 test('req.routePath', () => {75 const handlerA = () => {}76 const handlerB = () => {}77 const rawRequest = new Request('http://localhost?page=2&tag=A&tag=B')78 const req = new HonoRequest<'/:id/:name'>(rawRequest, '/123/key', [79 [80 [[handlerA, { handler: handlerA, method: 'GET', path: '/:id' }], { id: '123' }],81 [82 [handlerA, { handler: handlerB, method: 'GET', path: '/:id/:name' }],83 { id: '456', name: 'key' },84 ],85 ],86 ])8788 expect(req.matchedRoutes).toEqual([89 { handler: handlerA, method: 'GET', path: '/:id' },90 { handler: handlerB, method: 'GET', path: '/:id/:name' },91 ])92 })93})9495describe('routePath', () => {96 test('req.routePath', () => {97 const handlerA = () => {}98 const handlerB = () => {}99 const rawRequest = new Request('http://localhost?page=2&tag=A&tag=B')100 const req = new HonoRequest<'/:id/:name'>(rawRequest, '/123/key', [101 [102 [[handlerA, { handler: handlerA, method: 'GET', path: '/:id' }], { id: '123' }],103 [104 [handlerA, { handler: handlerB, method: 'GET', path: '/:id/:name' }],105 { id: '456', name: 'key' },106 ],107 ],108 ])109110 expect(req.routePath).toBe('/:id')111112 req.routeIndex = 1113 expect(req.routePath).toBe('/:id/:name')114 })115})116117describe('req.addValidatedData() and req.data()', () => {118 const rawRequest = new Request('http://localhost')119120 const payload = {
103 unmodified lines
modified:src/request.ts+29 added-17 removed
1/* eslint-disable @typescript-eslint/no-explicit-any */2/* eslint-disable @typescript-eslint/no-non-null-assertion */3import type { ParamIndexMap, ParamStash, Params } from './router'2import type { Result } from './router'3import type {4 Input,5 InputToDataByTarget,6 ParamKeys,7 ParamKeyToRecord,8 RemoveQuestion,9 UndefinedIfHavingQuestion,10 ValidationTargets,11 RouterRoute,12} from './types'13import { parseBody } from './utils/body'14import type { BodyData, ParseBodyOptions } from './utils/body'15import type { Cookie } from './utils/cookie'
12 unmodified lines
2829export class HonoRequest<P extends string = '/', I extends Input['out'] = {}> {30 raw: Request3132 private _s: ParamStash | undefined33 private vData: { [K in keyof ValidationTargets]?: {} } // Short name of validatedData34 private _p: ParamIndexMap | Params = {}32 #validatedData: { [K in keyof ValidationTargets]?: {} } // Short name of validatedData33 #matchResult: Result<[unknown, RouterRoute]>34 routeIndex: number = 035 path: string36 bodyCache: BodyCache = {}3738 constructor(39 request: Request,40 path: string = '/',41 paramStash: ParamStash | undefined = undefined41 matchResult: Result<[unknown, RouterRoute]> = [[]]42 ) {43 this.raw = request44 this.path = path45 this._s = paramStash46 this.vData = {}45 this.#matchResult = matchResult46 this.#validatedData = {}47 }4849 setParams(params: ParamIndexMap | Params) {50 this._p = params51 }5249 param<P2 extends string = P>(50 key: RemoveQuestion<ParamKeys<P2>>51 ): UndefinedIfHavingQuestion<ParamKeys<P2>>52 param<P2 extends string = P>(): UnionToIntersection<ParamKeyToRecord<ParamKeys<P2>>>53 param(key?: string): unknown {54 if (key) {59 const param = (this._s ? this._s[this._p[key] as any] : this._p[key]) as string | undefined55 const param = (56 this.#matchResult[1]57 ? this.#matchResult[1][this.#matchResult[0][this.routeIndex][1][key] as any]58 : this.#matchResult[0][this.routeIndex][1][key]59 ) as string | undefined60 return param ? (/\%/.test(param) ? decodeURIComponent_(param) : param) : undefined61 } else {62 const decoded: Record<string, string> = {}6364 const keys = Object.keys(this._p)64 const keys = Object.keys(this.#matchResult[0][this.routeIndex][1])65 for (let i = 0, len = keys.length; i < len; i++) {66 const key = keys[i]67 const value = (this._s ? this._s[this._p[key] as any] : this._p[key]) as string | undefined67 const value = (68 this.#matchResult[1]69 ? this.#matchResult[1][this.#matchResult[0][this.routeIndex][1][key] as any]70 : this.#matchResult[0][this.routeIndex][1][key]71 ) as string | undefined72 if (value && typeof value === 'string') {73 decoded[key] = /\%/.test(value) ? decodeURIComponent_(value) : value74 }75 }
103 unmodified lines
179 return this.cachedBody('formData')180 }181182 addValidatedData(target: keyof ValidationTargets, data: {}) {179 this.vData[target] = data183 this.#validatedData[target] = data184 }185186 valid<T extends keyof I & keyof ValidationTargets>(target: T): InputToDataByTarget<I, T>187 valid(target: keyof ValidationTargets) {184 return this.vData[target] as unknown188 return this.#validatedData[target] as unknown189 }190191 get url() {192 return this.raw.url
2 unmodified lines
195 get method() {196 return this.raw.method197 }198199 get matchedRoutes(): RouterRoute[] {200 return this.#matchResult[0].map(([[, route]]) => route)201 }202203 get routePath(): string {204 return this.#matchResult[0].map(([[, route]]) => route)[this.routeIndex].path205 }206207 /** @deprecated208 * Use `c.req.raw.headers` instead of `c.req.headers`. The `c.req.headers` will be removed in v4.209 * Or you can get the header values with using `c.req.header`.210 * @example
52 unmodified lines
modified:src/router.ts+2 added
1export const METHOD_NAME_ALL = 'ALL' as const2export const METHOD_NAME_ALL_LOWERCASE = 'all' as const3export const METHODS = ['get', 'post', 'put', 'delete', 'options', 'patch'] as const4export const MESSAGE_MATCHER_IS_ALREADY_BUILT =5 'Can not add a route since the matcher is already built.'67export interface Router<T> {8 name: string9 add(method: string, path: string, handler: T): void
33 unmodified lines
modified:src/types.test.ts+245 added-21 removed
18 unmodified lines
19 ToSchema,20 UndefinedIfHavingQuestion,21} from './types'22import type { Expect, Equal } from './utils/types'23import { validator } from './validator'2425describe('Env', () => {26 test('Env', () => {27 type E = {
43 unmodified lines
71 out: { json: Payload }72 }73 >74 expectTypeOf(c).toEqualTypeOf<Expected>()74 return c.jsonT({75 return c.json({76 message: 'Hello!',77 })78 })79 app.get(middleware, (c) => {80 const data = c.req.valid('json')81 expectTypeOf(data).toEqualTypeOf<Payload>()81 return c.jsonT({82 return c.json({83 message: 'Hello!',84 })85 })86 type Actual = ExtractSchema<typeof route>
25 unmodified lines
112 test('Context and AppType', () => {113 const route = app.get('/foo', middleware, (c) => {114 type Expected = Context<Env, '/foo', { in: { json: Payload }; out: { json: Payload } }>115 expectTypeOf(c).toEqualTypeOf<Expected>()115 return c.jsonT({116 return c.json({117 message: 'Hello!',118 })119 })120 type Actual = ExtractSchema<typeof route>
118 unmodified lines
239 }240 const route = app.on('PURGE', '/purge', middleware, (c) => {241 const data = c.req.valid('form')242 expectTypeOf(data).toEqualTypeOf<{ id: number }>()242 return c.jsonT({243 return c.json({244 success: true,245 })246 })247 type Actual = ExtractSchema<typeof route>
112 unmodified lines
360 }361 })362})363363describe('`jsonT()`', () => {364describe('`json()`', () => {365 const app = new Hono<{ Variables: { foo: string } }>()366367 app.get('/post/:id', (c) => {368 c.req.param('id')
1 unmodified line
370 return c.text('foo')371 })372373 const route = app.get('/hello', (c) => {373 return c.jsonT({374 return c.json({375 message: 'Hello!',376 })377 })378378 test('jsonT', () => {379 test('json', () => {380 type Actual = ExtractSchema<typeof route>381382 type Expected = {383 '/hello': {
156 unmodified lines
540 type verify = Expect<Equal<'/tags', GetKey<Actual>>>541 })542})543543describe('Different types using jsonT()', () => {544describe('Different types using json()', () => {545 describe('no path pattern', () => {546 const app = new Hono()547 test('Three different types', () => {548 const route = app.get((c) => {549 const flag = false550 if (flag) {550 return c.jsonT({551 return c.json({552 ng: true,553 })554 }555 if (!flag) {555 return c.jsonT({556 return c.json({557 ok: true,558 })559 }559 return c.jsonT({560 return c.json({561 default: true,562 })563 })564 type Actual = ExtractSchema<typeof route>
23 unmodified lines
588 test('Three different types', () => {589 const route = app.get('/foo', (c) => {590 const flag = false591 if (flag) {591 return c.jsonT({592 return c.json({593 ng: true,594 })595 }596 if (!flag) {596 return c.jsonT({597 return c.json({598 ok: true,599 })600 }600 return c.jsonT({601 return c.json({602 default: true,603 })604 })605 type Actual = ExtractSchema<typeof route>
18 unmodified lines
624 })625 })626})627627describe('jsonT() in an async handler', () => {628describe('json() in an async handler', () => {629 const app = new Hono()630 test('Three different types', () => {631 const route = app.get(async (c) => {631 return c.jsonT({632 return c.json({633 ok: true,634 })635 })636 type Actual = ExtractSchema<typeof route>
15 unmodified lines
652 * Other tests for `c.var` are written in `hono.test.ts`.653 * This tests are only for types.654 */655describe('c.var with chaining - test only types', () => {655 const mw1 = createMiddleware<{ Variables: { foo1: string } }>(async () => {})656 const mw2 = createMiddleware<{ Variables: { foo2: string } }>(async () => {})657 const mw3 = createMiddleware<{ Variables: { foo3: string } }>(async () => {})658 const mw4 = createMiddleware<{ Variables: { foo4: string } }>(async () => {})659 const mw5 = createMiddleware<{ Variables: { foo5: string } }>(async () => {})656 const mw1 = createMiddleware<657 { Variables: { foo1: string } },658 string,659 { out: { query: { bar1: number } } }660 >(async () => {})661 const mw2 = createMiddleware<662 { Variables: { foo2: string } },663 string,664 { out: { query: { bar2: number } } }665 >(async () => {})666 const mw3 = createMiddleware<667 { Variables: { foo3: string } },668 string,669 { out: { query: { bar3: number } } }670 >(async () => {})671 const mw4 = createMiddleware<672 { Variables: { foo4: string } },673 string,674 { out: { query: { bar4: number } } }675 >(async () => {})676 const mw5 = createMiddleware<677 { Variables: { foo5: string } },678 string,679 { out: { query: { bar5: number } } }680 >(async () => {})681 const mw6 = createMiddleware<682 { Variables: { foo6: string } },683 string,684 { out: { query: { bar6: number } } }685 >(async () => {})686 const mw7 = createMiddleware<687 { Variables: { foo7: string } },688 string,689 { out: { query: { bar7: number } } }690 >(async () => {})691 const mw8 = createMiddleware<692 { Variables: { foo8: string } },693 string,694 { out: { query: { bar8: number } } }695 >(async () => {})696 const mw9 = createMiddleware<697 { Variables: { foo9: string } },698 string,699 { out: { query: { bar9: number } } }700 >(async () => {})701 const mw10 = createMiddleware<702 { Variables: { foo10: string } },703 string,704 { out: { query: { bar10: number } } }705 >(async () => {})706707 it('Should not throw type errors', () => {708 // app.get(handler...)709
31 unmodified lines
741 expectTypeOf(c.var.foo5).toEqualTypeOf<string>()742 return c.json(0)743 })744745 new Hono().get(mw1, mw2, mw3, mw4, mw5, mw6).get('/', (c) => {746 expectTypeOf(c.var.foo1).toEqualTypeOf<string>()747 expectTypeOf(c.var.foo2).toEqualTypeOf<string>()748 expectTypeOf(c.var.foo3).toEqualTypeOf<string>()749 expectTypeOf(c.var.foo4).toEqualTypeOf<string>()750 expectTypeOf(c.var.foo5).toEqualTypeOf<string>()751 expectTypeOf(c.var.foo6).toEqualTypeOf<string>()752 return c.json(0)753 })754755 new Hono().get(mw1, mw2, mw3, mw4, mw5, mw6, mw7).get('/', (c) => {756 expectTypeOf(c.var.foo1).toEqualTypeOf<string>()757 expectTypeOf(c.var.foo2).toEqualTypeOf<string>()758 expectTypeOf(c.var.foo3).toEqualTypeOf<string>()759 expectTypeOf(c.var.foo4).toEqualTypeOf<string>()760 expectTypeOf(c.var.foo5).toEqualTypeOf<string>()761 expectTypeOf(c.var.foo6).toEqualTypeOf<string>()762 expectTypeOf(c.var.foo7).toEqualTypeOf<string>()763 return c.json(0)764 })765766 new Hono().get(mw1, mw2, mw3, mw4, mw5, mw6, mw7, mw8).get('/', (c) => {767 expectTypeOf(c.var.foo1).toEqualTypeOf<string>()768 expectTypeOf(c.var.foo2).toEqualTypeOf<string>()769 expectTypeOf(c.var.foo3).toEqualTypeOf<string>()770 expectTypeOf(c.var.foo4).toEqualTypeOf<string>()771 expectTypeOf(c.var.foo5).toEqualTypeOf<string>()772 expectTypeOf(c.var.foo6).toEqualTypeOf<string>()773 expectTypeOf(c.var.foo7).toEqualTypeOf<string>()774 expectTypeOf(c.var.foo8).toEqualTypeOf<string>()775 return c.json(0)776 })777778 new Hono().get(mw1, mw2, mw3, mw4, mw5, mw6, mw7, mw8, mw9).get('/', (c) => {779 expectTypeOf(c.var.foo1).toEqualTypeOf<string>()780 expectTypeOf(c.var.foo2).toEqualTypeOf<string>()781 expectTypeOf(c.var.foo3).toEqualTypeOf<string>()782 expectTypeOf(c.var.foo4).toEqualTypeOf<string>()783 expectTypeOf(c.var.foo5).toEqualTypeOf<string>()784 expectTypeOf(c.var.foo6).toEqualTypeOf<string>()785 expectTypeOf(c.var.foo7).toEqualTypeOf<string>()786 expectTypeOf(c.var.foo8).toEqualTypeOf<string>()787 expectTypeOf(c.var.foo9).toEqualTypeOf<string>()788 return c.json(0)789 })790791 new Hono().get(mw1, mw2, mw3, mw4, mw5, mw6, mw7, mw8, mw9, mw10).get('/', (c) => {792 expectTypeOf(c.var.foo1).toEqualTypeOf<string>()793 expectTypeOf(c.var.foo2).toEqualTypeOf<string>()794 expectTypeOf(c.var.foo3).toEqualTypeOf<string>()795 expectTypeOf(c.var.foo4).toEqualTypeOf<string>()796 expectTypeOf(c.var.foo5).toEqualTypeOf<string>()797 expectTypeOf(c.var.foo6).toEqualTypeOf<string>()798 expectTypeOf(c.var.foo7).toEqualTypeOf<string>()799 expectTypeOf(c.var.foo8).toEqualTypeOf<string>()800 expectTypeOf(c.var.foo9).toEqualTypeOf<string>()801 expectTypeOf(c.var.foo10).toEqualTypeOf<string>()802 return c.json(0)803 })804805 new Hono().get(mw1, mw2, mw3, mw4, mw5, mw6, mw7, mw8, mw9, (c) => {806 expectTypeOf(c.req.valid('query')).toMatchTypeOf<{807 bar1: number808 bar2: number809 bar3: number810 bar4: number811 bar5: number812 bar6: number813 bar7: number814 bar8: number815 bar9: number816 }>()817818 return c.jsonT(0)819 })820821 // app.get('/', handler...)822823 new Hono().get('/', mw1).get('/', (c) => {824 expectTypeOf(c.var.foo1).toEqualTypeOf<string>()
28 unmodified lines
853 expectTypeOf(c.var.foo4).toEqualTypeOf<string>()854 expectTypeOf(c.var.foo5).toEqualTypeOf<string>()855 return c.json(0)856 })857858 new Hono().get('/', mw1, mw2, mw3, mw4, mw5, mw6).get('/', (c) => {859 expectTypeOf(c.var.foo1).toEqualTypeOf<string>()860 expectTypeOf(c.var.foo2).toEqualTypeOf<string>()861 expectTypeOf(c.var.foo3).toEqualTypeOf<string>()862 expectTypeOf(c.var.foo4).toEqualTypeOf<string>()863 expectTypeOf(c.var.foo5).toEqualTypeOf<string>()864 expectTypeOf(c.var.foo6).toEqualTypeOf<string>()865 return c.json(0)866 })867868 new Hono().get('/', mw1, mw2, mw3, mw4, mw5, mw6, mw7).get('/', (c) => {869 expectTypeOf(c.var.foo1).toEqualTypeOf<string>()870 expectTypeOf(c.var.foo2).toEqualTypeOf<string>()871 expectTypeOf(c.var.foo3).toEqualTypeOf<string>()872 expectTypeOf(c.var.foo4).toEqualTypeOf<string>()873 expectTypeOf(c.var.foo5).toEqualTypeOf<string>()874 expectTypeOf(c.var.foo6).toEqualTypeOf<string>()875 expectTypeOf(c.var.foo7).toEqualTypeOf<string>()876 return c.json(0)877 })878879 new Hono().get('/', mw1, mw2, mw3, mw4, mw5, mw6, mw7, mw8).get('/', (c) => {880 expectTypeOf(c.var.foo1).toEqualTypeOf<string>()881 expectTypeOf(c.var.foo2).toEqualTypeOf<string>()882 expectTypeOf(c.var.foo3).toEqualTypeOf<string>()883 expectTypeOf(c.var.foo4).toEqualTypeOf<string>()884 expectTypeOf(c.var.foo5).toEqualTypeOf<string>()885 expectTypeOf(c.var.foo6).toEqualTypeOf<string>()886 expectTypeOf(c.var.foo7).toEqualTypeOf<string>()887 expectTypeOf(c.var.foo8).toEqualTypeOf<string>()888 return c.json(0)889 })890891 new Hono().get('/', mw1, mw2, mw3, mw4, mw5, mw6, mw7, mw8, mw9).get('/', (c) => {892 expectTypeOf(c.var.foo1).toEqualTypeOf<string>()893 expectTypeOf(c.var.foo2).toEqualTypeOf<string>()894 expectTypeOf(c.var.foo3).toEqualTypeOf<string>()895 expectTypeOf(c.var.foo4).toEqualTypeOf<string>()896 expectTypeOf(c.var.foo5).toEqualTypeOf<string>()897 expectTypeOf(c.var.foo6).toEqualTypeOf<string>()898 expectTypeOf(c.var.foo7).toEqualTypeOf<string>()899 expectTypeOf(c.var.foo8).toEqualTypeOf<string>()900 expectTypeOf(c.var.foo9).toEqualTypeOf<string>()901 return c.json(0)902 })903904 new Hono().get('/', mw1, mw2, mw3, mw4, mw5, mw6, mw7, mw8, mw9, mw10).get('/', (c) => {905 expectTypeOf(c.var.foo1).toEqualTypeOf<string>()906 expectTypeOf(c.var.foo2).toEqualTypeOf<string>()907 expectTypeOf(c.var.foo3).toEqualTypeOf<string>()908 expectTypeOf(c.var.foo4).toEqualTypeOf<string>()909 expectTypeOf(c.var.foo5).toEqualTypeOf<string>()910 expectTypeOf(c.var.foo6).toEqualTypeOf<string>()911 expectTypeOf(c.var.foo7).toEqualTypeOf<string>()912 expectTypeOf(c.var.foo8).toEqualTypeOf<string>()913 expectTypeOf(c.var.foo9).toEqualTypeOf<string>()914 expectTypeOf(c.var.foo10).toEqualTypeOf<string>()915 return c.json(0)916 })917918 new Hono().get('/', mw1, mw2, mw3, mw4, mw5, mw6, mw7, mw8, mw9, (c) => {919 expectTypeOf(c.req.valid('query')).toMatchTypeOf<{920 bar1: number921 bar2: number922 bar3: number923 bar4: number924 bar5: number925 bar6: number926 bar7: number927 bar8: number928 bar9: number929 }>()930931 return c.jsonT(0)932 })933 })934})935936/**
17 unmodified lines
954 return c.json(0)955 })956 })957})958959/**960 * It's challenge to test all cases. This is a minimal pattern.961 */962describe('Env types with chained routes - test only types', () => {963 const app = new Hono<{ Variables: { testVar: string } }>()964 it('Should not throw a type error', () => {965 app966 .post(967 '/',968 validator('json', (v) => v),969 async (c) => {970 expectTypeOf(c.get('testVar')).toEqualTypeOf<string>()971 return c.jsonT({ success: true })972 }973 )974 .patch(975 '/',976 validator('json', (v) => v),977 async (c) => {978 expectTypeOf(c.get('testVar')).toEqualTypeOf<string>()979 return c.jsonT({ success: true })980 }981 )982 })983})
modified:src/types.ts+1038 added-99 removed
27 unmodified lines
28}2930////////////////////////////////////////31////// //////32////// Routes //////33////// //////34////////////////////////////////////////3536export interface RouterRoute {37 path: string38 method: string39 handler: H40}4142////////////////////////////////////////43////// //////44////// Handlers //////45////// //////46////////////////////////////////////////4736type HandlerResponse<O> = Response | TypedResponse<O> | Promise<Response | TypedResponse<O>>48export type HandlerResponse<O> = Response | TypedResponse<O> | Promise<Response | TypedResponse<O>>4950export type Handler<51 E extends Env = any,52 P extends string = any,
41 unmodified lines
94 R extends HandlerResponse<any> = any,95 E2 extends Env = E96 >(97 handler: H<E2, P, I, R>86 ): Hono<E & E2, S & ToSchema<M, P, I['in'], MergeTypedResponseData<R>>, BasePath>98 ): Hono<99 IntersectNonAnyTypes<[E, E2]>,100 S & ToSchema<M, P, I['in'], MergeTypedResponseData<R>>,101 BasePath102 >10388 // app.get(handler, handler)104 // app.get(handler x2)105 <106 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,107 I extends Input = {},108 I2 extends Input = I,109 R extends HandlerResponse<any> = any,110 E2 extends Env = E,111 E3 extends Env = IntersectNonAnyTypes<[E, E2]>112 >(96 ...handlers: [H<E2, P, I, R>, H<E3, P, I, R>]97 ): Hono<E & E2 & E3, S & ToSchema<M, P, I['in'], MergeTypedResponseData<R>>, BasePath>113 ...handlers: [H<E2, P, I>, H<E3, P, I2, R>]114 ): Hono<115 IntersectNonAnyTypes<[E, E2, E3]>,116 S & ToSchema<M, P, I2['in'], MergeTypedResponseData<R>>,117 BasePath118 >119120 // app.get(handler x 3)121 <122 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,
4 unmodified lines
127 E2 extends Env = E,128 E3 extends Env = E,129 E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>130 >(110 ...handlers: [H<E2, P, I, R>, H<E3, P, I2, R>, H<E4, P, I3, R>]111 ): Hono<E & E2 & E3 & E4, S & ToSchema<M, P, I3['in'], MergeTypedResponseData<R>>, BasePath>131 ...handlers: [H<E2, P, I>, H<E3, P, I2>, H<E4, P, I3, R>]132 ): Hono<133 IntersectNonAnyTypes<[E, E2, E3, E4]>,134 S & ToSchema<M, P, I3['in'], MergeTypedResponseData<R>>,135 BasePath136 >137138 // app.get(handler x 4)139 <140 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,
6 unmodified lines
147 E3 extends Env = E,148 E4 extends Env = E,149 E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>150 >(126 ...handlers: [H<E2, P, I, R>, H<E3, P, I2, R>, H<E4, P, I3, R>, H<E5, P, I4, R>]127 ): Hono<E & E2 & E3 & E4 & E5, S & ToSchema<M, P, I4['in'], MergeTypedResponseData<R>>, BasePath>151 ...handlers: [H<E2, P, I>, H<E3, P, I2>, H<E4, P, I3>, H<E5, P, I4, R>]152 ): Hono<153 IntersectNonAnyTypes<[E, E2, E3, E4, E5]>,154 S & ToSchema<M, P, I4['in'], MergeTypedResponseData<R>>,155 BasePath156 >157158 // app.get(handler x 5)159 <160 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,161 R extends HandlerResponse<any> = any,162 I extends Input = {},163 I2 extends Input = I,164 I3 extends Input = I & I2,136 I4 extends Input = I2 & I3,165 I4 extends Input = I & I2 & I3,166 I5 extends Input = I & I2 & I3 & I4,167 E2 extends Env = E,168 E3 extends Env = E,169 E4 extends Env = E,170 E5 extends Env = E,171 E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>172 >(173 ...handlers: [H<E2, P, I>, H<E3, P, I2>, H<E4, P, I3>, H<E5, P, I4>, H<E6, P, I5, R>]174 ): Hono<175 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>,176 S & ToSchema<M, P, I5['in'], MergeTypedResponseData<R>>,177 BasePath178 >179180 // app.get(handler x 6)181 <182 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,183 R extends HandlerResponse<any> = any,184 I extends Input = {},185 I2 extends Input = I,186 I3 extends Input = I & I2,187 I4 extends Input = I & I2 & I3,188 I5 extends Input = I & I2 & I3 & I4,189 I6 extends Input = I & I2 & I3 & I4 & I5,190 E2 extends Env = E,191 E3 extends Env = E,192 E4 extends Env = E,193 E5 extends Env = E,194 E6 extends Env = E,195 E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>196 >(197 ...handlers: [145 H<E2, P, I, R>,146 H<E3, P, I2, R>,147 H<E4, P, I3, R>,148 H<E5, P, I3, R>,149 H<E6, P, I3, R>198 H<E2, P, I>,199 H<E3, P, I2>,200 H<E4, P, I3>,201 H<E5, P, I4>,202 H<E6, P, I5>,203 H<E7, P, I6, R>204 ]205 ): Hono<152 E & E2 & E3 & E4 & E5 & E6,153 S & ToSchema<M, P, I5['in'], MergeTypedResponseData<R>>,206 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>,207 S & ToSchema<M, P, I6['in'], MergeTypedResponseData<R>>,208 BasePath209 >210211 // app.get(handler x 7)212 <213 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,214 R extends HandlerResponse<any> = any,215 I extends Input = {},216 I2 extends Input = I,217 I3 extends Input = I & I2,218 I4 extends Input = I & I2 & I3,219 I5 extends Input = I & I2 & I3 & I4,220 I6 extends Input = I & I2 & I3 & I4 & I5,221 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,222 E2 extends Env = E,223 E3 extends Env = E,224 E4 extends Env = E,225 E5 extends Env = E,226 E6 extends Env = E,227 E7 extends Env = E,228 E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>229 >(230 ...handlers: [231 H<E2, P, I>,232 H<E3, P, I2>,233 H<E4, P, I3>,234 H<E5, P, I4>,235 H<E6, P, I5>,236 H<E7, P, I6>,237 H<E8, P, I7, R>238 ]239 ): Hono<240 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>,241 S & ToSchema<M, P, I7['in'], MergeTypedResponseData<R>>,242 BasePath243 >244245 // app.get(handler x 8)246 <247 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,248 R extends HandlerResponse<any> = any,249 I extends Input = {},250 I2 extends Input = I,251 I3 extends Input = I & I2,252 I4 extends Input = I & I2 & I3,253 I5 extends Input = I & I2 & I3 & I4,254 I6 extends Input = I & I2 & I3 & I4 & I5,255 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,256 I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7,257 E2 extends Env = E,258 E3 extends Env = E,259 E4 extends Env = E,260 E5 extends Env = E,261 E6 extends Env = E,262 E7 extends Env = E,263 E8 extends Env = E,264 E9 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>265 >(266 ...handlers: [267 H<E2, P, I>,268 H<E3, P, I2>,269 H<E4, P, I3>,270 H<E5, P, I4>,271 H<E6, P, I5>,272 H<E7, P, I6>,273 H<E8, P, I7>,274 H<E9, P, I8, R>275 ]276 ): Hono<277 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>,278 S & ToSchema<M, P, I8['in'], MergeTypedResponseData<R>>,279 BasePath280 >281282 // app.get(handler x 9)283 <284 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,285 R extends HandlerResponse<any> = any,286 I extends Input = {},287 I2 extends Input = I,288 I3 extends Input = I & I2,289 I4 extends Input = I & I2 & I3,290 I5 extends Input = I & I2 & I3 & I4,291 I6 extends Input = I & I2 & I3 & I4 & I5,292 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,293 I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7,294 I9 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8,295 E2 extends Env = E,296 E3 extends Env = E,297 E4 extends Env = E,298 E5 extends Env = E,299 E6 extends Env = E,300 E7 extends Env = E,301 E8 extends Env = E,302 E9 extends Env = E,303 E10 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>304 >(305 ...handlers: [306 H<E2, P, I>,307 H<E3, P, I2>,308 H<E4, P, I3>,309 H<E5, P, I4>,310 H<E6, P, I5>,311 H<E7, P, I6>,312 H<E8, P, I7>,313 H<E9, P, I8>,314 H<E10, P, I9, R>315 ]316 ): Hono<317 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>,318 S & ToSchema<M, P, I9['in'], MergeTypedResponseData<R>>,319 BasePath320 >321322 // app.get(handler x 10)323 <324 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,325 R extends HandlerResponse<any> = any,326 I extends Input = {},327 I2 extends Input = I,328 I3 extends Input = I & I2,329 I4 extends Input = I & I2 & I3,330 I5 extends Input = I & I2 & I3 & I4,331 I6 extends Input = I & I2 & I3 & I4 & I5,332 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,333 I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7,334 I9 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8,335 I10 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8 & I9,336 E2 extends Env = E,337 E3 extends Env = E,338 E4 extends Env = E,339 E5 extends Env = E,340 E6 extends Env = E,341 E7 extends Env = E,342 E8 extends Env = E,343 E9 extends Env = E,344 E10 extends Env = E,345 E11 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>346 >(347 ...handlers: [348 H<E2, P, I>,349 H<E3, P, I2>,350 H<E4, P, I3>,351 H<E5, P, I4>,352 H<E6, P, I5>,353 H<E7, P, I6>,354 H<E8, P, I7>,355 H<E9, P, I8>,356 H<E10, P, I9>,357 H<E11, P, I10, R>358 ]359 ): Hono<360 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11]>,361 S & ToSchema<M, P, I10['in'], MergeTypedResponseData<R>>,362 BasePath363 >364365 // app.get(...handlers[])366 <367 P extends string = ExtractKey<S> extends never ? BasePath : ExtractKey<S>,368 I extends Input = {},
15 unmodified lines
384385 // app.get(path, handler)386 <387 P extends string,180 P2 extends string = P,388 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,389 R extends HandlerResponse<any> = any,390 I extends Input = {},391 E2 extends Env = E392 >(393 path: P,186 handler: H<E2, MergePath<BasePath, P2>, I, R>394 handler: H<E2, MergedPath, I, R>395 ): Hono<188 E & E2,189 S & ToSchema<M, MergePath<BasePath, P>, I['in'], MergeTypedResponseData<R>>,396 IntersectNonAnyTypes<[E, E2]>,397 S & ToSchema<M, MergedPath, I['in'], MergeTypedResponseData<R>>,398 BasePath399 >400193 // app.get(path, handler, handler)401 // app.get(path, handler x2)402 <403 P extends string,196 P2 extends string = P,197 P3 extends string = P,404 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,405 R extends HandlerResponse<any> = any,406 I extends Input = {},407 I2 extends Input = I,408 E2 extends Env = E,409 E3 extends Env = IntersectNonAnyTypes<[E, E2]>410 >(411 path: P,204 ...handlers: [H<E2, MergePath<BasePath, P2>, I, R>, H<E3, MergePath<BasePath, P3>, I, R>]412 ...handlers: [H<E2, MergedPath, I>, H<E3, MergedPath, I2, R>]413 ): Hono<206 E & E2 & E3,207 S & ToSchema<M, MergePath<BasePath, P>, I['in'], MergeTypedResponseData<R>>,414 IntersectNonAnyTypes<[E, E2, E3]>,415 S & ToSchema<M, MergedPath, I2['in'], MergeTypedResponseData<R>>,416 BasePath417 >418419 // app.get(path, handler x3)420 <421 P extends string,214 P2 extends string = P,215 P3 extends string = P,216 P4 extends string = P,422 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,423 R extends HandlerResponse<any> = any,424 I extends Input = {},425 I2 extends Input = I,426 I3 extends Input = I & I2,
1 unmodified line
428 E3 extends Env = E,429 E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>430 >(431 path: P,226 ...handlers: [227 H<E2, MergePath<BasePath, P2>, I, R>,228 H<E3, MergePath<BasePath, P3>, I2, R>,229 H<E4, MergePath<BasePath, P4>, I3, R>230 ]432 ...handlers: [H<E2, MergedPath, I>, H<E3, MergedPath, I2>, H<E4, MergedPath, I3, R>]433 ): Hono<232 E & E2 & E3 & E4,233 S & ToSchema<M, MergePath<BasePath, P>, I3['in'], MergeTypedResponseData<R>>,434 IntersectNonAnyTypes<[E, E2, E3, E4]>,435 S & ToSchema<M, MergedPath, I3['in'], MergeTypedResponseData<R>>,436 BasePath437 >438439 // app.get(path, handler x4)440 <441 P extends string,240 P2 extends string = P,241 P3 extends string = P,242 P4 extends string = P,243 P5 extends string = P,442 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,443 R extends HandlerResponse<any> = any,444 I extends Input = {},445 I2 extends Input = I,446 I3 extends Input = I & I2,
4 unmodified lines
451 E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>452 >(453 path: P,454 ...handlers: [256 H<E2, MergePath<BasePath, P2>, I, R>,257 H<E3, MergePath<BasePath, P3>, I2, R>,258 H<E4, MergePath<BasePath, P4>, I3, R>,259 H<E5, MergePath<BasePath, P5>, I4, R>455 H<E2, MergedPath, I>,456 H<E3, MergedPath, I2>,457 H<E4, MergedPath, I3>,458 H<E5, MergedPath, I4, R>459 ]460 ): Hono<262 E & E2 & E3 & E4 & E5,263 S & ToSchema<M, MergePath<BasePath, P>, I4['in'], MergeTypedResponseData<R>>,461 IntersectNonAnyTypes<[E, E2, E3, E4, E5]>,462 S & ToSchema<M, MergedPath, I4['in'], MergeTypedResponseData<R>>,463 BasePath464 >465466 // app.get(path, handler x5)467 <468 P extends string,270 P2 extends string = P,271 P3 extends string = P,272 P4 extends string = P,273 P5 extends string = P,274 P6 extends string = P,469 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,470 R extends HandlerResponse<any> = any,471 I extends Input = {},472 I2 extends Input = I,473 I3 extends Input = I & I2,279 I4 extends Input = I2 & I3,474 I4 extends Input = I & I2 & I3,475 I5 extends Input = I & I2 & I3 & I4,476 E2 extends Env = E,477 E3 extends Env = E,478 E4 extends Env = E,
1 unmodified line
480 E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>481 >(482 path: P,483 ...handlers: [289 H<E2, MergePath<BasePath, P2>, I, R>,290 H<E3, MergePath<BasePath, P3>, I2, R>,291 H<E4, MergePath<BasePath, P4>, I3, R>,292 H<E5, MergePath<BasePath, P5>, I4, R>,293 H<E6, MergePath<BasePath, P6>, I5, R>484 H<E2, MergedPath, I>,485 H<E3, MergedPath, I2>,486 H<E4, MergedPath, I3>,487 H<E5, MergedPath, I4>,488 H<E6, MergedPath, I5, R>489 ]490 ): Hono<296 E & E2 & E3 & E4 & E5 & E6,297 S & ToSchema<M, MergePath<BasePath, P>, I5['in'], MergeTypedResponseData<R>>,491 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>,492 S & ToSchema<M, MergedPath, I5['in'], MergeTypedResponseData<R>>,493 BasePath494 >495496 // app.get(path, handler x6)497 <498 P extends string,499 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,500 R extends HandlerResponse<any> = any,501 I extends Input = {},502 I2 extends Input = I,503 I3 extends Input = I & I2,504 I4 extends Input = I & I2 & I3,505 I5 extends Input = I & I2 & I3 & I4,506 I6 extends Input = I & I2 & I3 & I4 & I5,507 E2 extends Env = E,508 E3 extends Env = E,509 E4 extends Env = E,510 E5 extends Env = E,511 E6 extends Env = E,512 E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>513 >(514 path: P,515 ...handlers: [516 H<E2, MergedPath, I>,517 H<E3, MergedPath, I2>,518 H<E4, MergedPath, I3>,519 H<E5, MergedPath, I4>,520 H<E6, MergedPath, I5>,521 H<E7, MergedPath, I6, R>522 ]523 ): Hono<524 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>,525 S & ToSchema<M, MergedPath, I6['in'], MergeTypedResponseData<R>>,526 BasePath527 >528529 // app.get(path, handler x7)530 <531 P extends string,532 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,533 R extends HandlerResponse<any> = any,534 I extends Input = {},535 I2 extends Input = I,536 I3 extends Input = I & I2,537 I4 extends Input = I & I2 & I3,538 I5 extends Input = I & I2 & I3 & I4,539 I6 extends Input = I & I2 & I3 & I4 & I5,540 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,541 E2 extends Env = E,542 E3 extends Env = E,543 E4 extends Env = E,544 E5 extends Env = E,545 E6 extends Env = E,546 E7 extends Env = E,547 E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>548 >(549 path: P,550 ...handlers: [551 H<E2, MergedPath, I>,552 H<E3, MergedPath, I2>,553 H<E4, MergedPath, I3>,554 H<E5, MergedPath, I4>,555 H<E6, MergedPath, I5>,556 H<E7, MergedPath, I6>,557 H<E8, MergedPath, I7, R>558 ]559 ): Hono<560 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>,561 S & ToSchema<M, MergedPath, I7['in'], MergeTypedResponseData<R>>,562 BasePath563 >564565 // app.get(path, handler x8)566 <567 P extends string,568 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,569 R extends HandlerResponse<any> = any,570 I extends Input = {},571 I2 extends Input = I,572 I3 extends Input = I & I2,573 I4 extends Input = I & I2 & I3,574 I5 extends Input = I & I2 & I3 & I4,575 I6 extends Input = I & I2 & I3 & I4 & I5,576 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,577 I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7,578 E2 extends Env = E,579 E3 extends Env = E,580 E4 extends Env = E,581 E5 extends Env = E,582 E6 extends Env = E,583 E7 extends Env = E,584 E8 extends Env = E,585 E9 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>586 >(587 path: P,588 ...handlers: [589 H<E2, MergedPath, I>,590 H<E3, MergedPath, I2>,591 H<E4, MergedPath, I3>,592 H<E5, MergedPath, I4>,593 H<E6, MergedPath, I5>,594 H<E7, MergedPath, I6>,595 H<E8, MergedPath, I7>,596 H<E9, MergedPath, I8, R>597 ]598 ): Hono<599 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>,600 S & ToSchema<M, MergedPath, I8['in'], MergeTypedResponseData<R>>,601 BasePath602 >603604 // app.get(path, handler x9)605 <606 P extends string,607 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,608 R extends HandlerResponse<any> = any,609 I extends Input = {},610 I2 extends Input = I,611 I3 extends Input = I & I2,612 I4 extends Input = I & I2 & I3,613 I5 extends Input = I & I2 & I3 & I4,614 I6 extends Input = I & I2 & I3 & I4 & I5,615 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,616 I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7,617 I9 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8,618 E2 extends Env = E,619 E3 extends Env = E,620 E4 extends Env = E,621 E5 extends Env = E,622 E6 extends Env = E,623 E7 extends Env = E,624 E8 extends Env = E,625 E9 extends Env = E,626 E10 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>627 >(628 path: P,629 ...handlers: [630 H<E2, MergedPath, I>,631 H<E3, MergedPath, I2>,632 H<E4, MergedPath, I3>,633 H<E5, MergedPath, I4>,634 H<E6, MergedPath, I5>,635 H<E7, MergedPath, I6>,636 H<E8, MergedPath, I7>,637 H<E9, MergedPath, I8>,638 H<E10, MergedPath, I9, R>639 ]640 ): Hono<641 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>,642 S & ToSchema<M, MergedPath, I9['in'], MergeTypedResponseData<R>>,643 BasePath644 >645646 // app.get(path, handler x10)647 <648 P extends string,649 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,650 R extends HandlerResponse<any> = any,651 I extends Input = {},652 I2 extends Input = I,653 I3 extends Input = I & I2,654 I4 extends Input = I & I2 & I3,655 I5 extends Input = I & I2 & I3 & I4,656 I6 extends Input = I & I2 & I3 & I4 & I5,657 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,658 I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7,659 I9 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8,660 I10 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8 & I9,661 E2 extends Env = E,662 E3 extends Env = E,663 E4 extends Env = E,664 E5 extends Env = E,665 E6 extends Env = E,666 E7 extends Env = E,667 E8 extends Env = E,668 E9 extends Env = E,669 E10 extends Env = E,670 E11 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>671 >(672 path: P,673 ...handlers: [674 H<E2, MergedPath, I>,675 H<E3, MergedPath, I2>,676 H<E4, MergedPath, I3>,677 H<E5, MergedPath, I4>,678 H<E6, MergedPath, I5>,679 H<E7, MergedPath, I6>,680 H<E8, MergedPath, I7>,681 H<E9, MergedPath, I8>,682 H<E10, MergedPath, I9>,683 H<E11, MergedPath, I10, R>684 ]685 ): Hono<686 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11]>,687 S & ToSchema<M, MergedPath, I10['in'], MergeTypedResponseData<R>>,688 BasePath689 >690691 // app.get(path, ...handlers[])692 <P extends string, I extends Input = {}, R extends HandlerResponse<any> = any>(693 path: P,694 ...handlers: H<E, MergePath<BasePath, P>, I, R>[]
33 unmodified lines
728 E extends Env = Env,729 S extends Schema = {},730 BasePath extends string = '/'731> {342 // app.on(method, path, handler, handler)732 // app.on(method, path, handler)733 <734 M extends string,735 P extends string,346 P2 extends string = P,347 P3 extends string = P,736 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,737 R extends HandlerResponse<any> = any,738 I extends Input = {},739 E2 extends Env = E740 >(741 method: M,742 path: P,743 handler: H<E2, MergedPath, I, R>744 ): Hono<745 IntersectNonAnyTypes<[E, E2]>,746 S & ToSchema<M, MergedPath, I['in'], MergeTypedResponseData<R>>,747 BasePath748 >749750 // app.on(method, path, handler x2)751 <752 M extends string,753 P extends string,754 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,755 R extends HandlerResponse<any> = any,756 I extends Input = {},757 I2 extends Input = I,758 E2 extends Env = E,759 E3 extends Env = IntersectNonAnyTypes<[E, E2]>760 >(761 method: M,762 path: P,355 ...handlers: [H<E2, MergePath<BasePath, P2>, I, R>, H<E3, MergePath<BasePath, P3>, I, R>]356 ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I['in'], MergeTypedResponseData<R>>, BasePath>763 ...handlers: [H<E2, MergedPath, I>, H<E3, MergedPath, I2, R>]764 ): Hono<765 IntersectNonAnyTypes<[E, E2, E3]>,766 S & ToSchema<M, MergedPath, I2['in'], MergeTypedResponseData<R>>,767 BasePath768 >769358 // app.get(method, path, handler x3)770 // app.on(method, path, handler x3)771 <772 M extends string,773 P extends string,362 P2 extends string = P,363 P3 extends string = P,364 P4 extends string = P,774 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,775 R extends HandlerResponse<any> = any,776 I extends Input = {},777 I2 extends Input = I,778 I3 extends Input = I & I2,
2 unmodified lines
781 E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>782 >(783 method: M,784 path: P,375 ...handlers: [376 H<E2, MergePath<BasePath, P2>, I, R>,377 H<E3, MergePath<BasePath, P3>, I2, R>,378 H<E4, MergePath<BasePath, P4>, I3, R>379 ]380 ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I3['in'], MergeTypedResponseData<R>>, BasePath>381 // app.get(method, path, handler x4)785 ...handlers: [H<E2, MergedPath, I>, H<E3, MergedPath, I2>, H<E4, MergedPath, I3, R>]786 ): Hono<787 IntersectNonAnyTypes<[E, E2, E3, E4]>,788 S & ToSchema<M, MergedPath, I3['in'], MergeTypedResponseData<R>>,789 BasePath790 >791792 // app.on(method, path, handler x4)793 <794 M extends string,795 P extends string,385 P2 extends string = P,386 P3 extends string = P,387 P4 extends string = P,388 P5 extends string = P,796 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,797 R extends HandlerResponse<any> = any,798 I extends Input = {},799 I2 extends Input = I,800 I3 extends Input = I & I2,
5 unmodified lines
806 >(807 method: M,808 path: P,809 ...handlers: [402 H<E2, MergePath<BasePath, P2>, I, R>,403 H<E3, MergePath<BasePath, P3>, I2, R>,404 H<E4, MergePath<BasePath, P4>, I3, R>,405 H<E5, MergePath<BasePath, P5>, I4, R>810 H<E2, MergedPath, I>,811 H<E3, MergedPath, I2>,812 H<E4, MergedPath, I3>,813 H<E5, MergedPath, I4, R>814 ]407 ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I4['in'], MergeTypedResponseData<R>>, BasePath>815 ): Hono<816 IntersectNonAnyTypes<[E, E2, E3, E4, E5]>,817 S & ToSchema<M, MergedPath, I4['in'], MergeTypedResponseData<R>>,818 BasePath819 >820409 // app.get(method, path, handler x5)821 // app.on(method, path, handler x5)822 <823 M extends string,824 P extends string,413 P2 extends string = P,414 P3 extends string = P,415 P4 extends string = P,416 P5 extends string = P,417 P6 extends string = P,825 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,826 R extends HandlerResponse<any> = any,827 I extends Input = {},828 I2 extends Input = I,829 I3 extends Input = I & I2,
7 unmodified lines
837 >(838 method: M,839 path: P,840 ...handlers: [433 H<E2, MergePath<BasePath, P2>, I, R>,434 H<E3, MergePath<BasePath, P3>, I2, R>,435 H<E4, MergePath<BasePath, P4>, I3, R>,436 H<E5, MergePath<BasePath, P5>, I4, R>,437 H<E6, MergePath<BasePath, P6>, I5, R>841 H<E2, MergedPath, I>,842 H<E3, MergedPath, I2>,843 H<E4, MergedPath, I3>,844 H<E5, MergedPath, I4>,845 H<E6, MergedPath, I5, R>846 ]439 ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I5['in'], MergeTypedResponseData<R>>, BasePath>847 ): Hono<848 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>,849 S & ToSchema<M, MergedPath, I5['in'], MergeTypedResponseData<R>>,850 BasePath851 >852853 // app.on(method, path, handler x6)854 <855 M extends string,856 P extends string,857 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,858 R extends HandlerResponse<any> = any,859 I extends Input = {},860 I2 extends Input = I,861 I3 extends Input = I & I2,862 I4 extends Input = I & I2 & I3,863 I5 extends Input = I & I2 & I3 & I4,864 I6 extends Input = I & I2 & I3 & I4 & I5,865 E2 extends Env = E,866 E3 extends Env = E,867 E4 extends Env = E,868 E5 extends Env = E,869 E6 extends Env = E,870 E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>871 >(872 method: M,873 path: P,874 ...handlers: [875 H<E2, MergedPath, I>,876 H<E3, MergedPath, I2>,877 H<E4, MergedPath, I3>,878 H<E5, MergedPath, I4>,879 H<E6, MergedPath, I5>,880 H<E7, MergedPath, I6, R>881 ]882 ): Hono<883 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>,884 S & ToSchema<M, MergedPath, I6['in'], MergeTypedResponseData<R>>,885 BasePath886 >887888 // app.on(method, path, handler x7)889 <890 M extends string,891 P extends string,892 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,893 R extends HandlerResponse<any> = any,894 I extends Input = {},895 I2 extends Input = I,896 I3 extends Input = I & I2,897 I4 extends Input = I & I2 & I3,898 I5 extends Input = I & I2 & I3 & I4,899 I6 extends Input = I & I2 & I3 & I4 & I5,900 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,901 E2 extends Env = E,902 E3 extends Env = E,903 E4 extends Env = E,904 E5 extends Env = E,905 E6 extends Env = E,906 E7 extends Env = E,907 E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>908 >(909 method: M,910 path: P,911 ...handlers: [912 H<E2, MergedPath, I>,913 H<E3, MergedPath, I2>,914 H<E4, MergedPath, I3>,915 H<E5, MergedPath, I4>,916 H<E6, MergedPath, I5>,917 H<E7, MergedPath, I6>,918 H<E8, MergedPath, I7, R>919 ]920 ): Hono<921 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>,922 S & ToSchema<M, MergedPath, I7['in'], MergeTypedResponseData<R>>,923 BasePath924 >925926 // app.on(method, path, handler x8)927 <928 M extends string,929 P extends string,930 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,931 R extends HandlerResponse<any> = any,932 I extends Input = {},933 I2 extends Input = I,934 I3 extends Input = I & I2,935 I4 extends Input = I & I2 & I3,936 I5 extends Input = I & I2 & I3 & I4,937 I6 extends Input = I & I2 & I3 & I4 & I5,938 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,939 I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7,940 E2 extends Env = E,941 E3 extends Env = E,942 E4 extends Env = E,943 E5 extends Env = E,944 E6 extends Env = E,945 E7 extends Env = E,946 E8 extends Env = E,947 E9 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>948 >(949 method: M,950 path: P,951 ...handlers: [952 H<E2, MergedPath, I>,953 H<E3, MergedPath, I2>,954 H<E4, MergedPath, I3>,955 H<E5, MergedPath, I4>,956 H<E6, MergedPath, I5>,957 H<E7, MergedPath, I6>,958 H<E8, MergedPath, I7>,959 H<E9, MergedPath, I8, R>960 ]961 ): Hono<962 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>,963 S & ToSchema<M, MergedPath, I8['in'], MergeTypedResponseData<R>>,964 BasePath965 >966967 // app.on(method, path, handler x9)968 <969 M extends string,970 P extends string,971 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,972 R extends HandlerResponse<any> = any,973 I extends Input = {},974 I2 extends Input = I,975 I3 extends Input = I & I2,976 I4 extends Input = I & I2 & I3,977 I5 extends Input = I & I2 & I3 & I4,978 I6 extends Input = I & I2 & I3 & I4 & I5,979 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,980 I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7,981 I9 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8,982 E2 extends Env = E,983 E3 extends Env = E,984 E4 extends Env = E,985 E5 extends Env = E,986 E6 extends Env = E,987 E7 extends Env = E,988 E8 extends Env = E,989 E9 extends Env = E,990 E10 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>991 >(992 method: M,993 path: P,994 ...handlers: [995 H<E2, MergedPath, I>,996 H<E3, MergedPath, I2>,997 H<E4, MergedPath, I3>,998 H<E5, MergedPath, I4>,999 H<E6, MergedPath, I5>,1000 H<E7, MergedPath, I6>,1001 H<E8, MergedPath, I7>,1002 H<E9, MergedPath, I8>,1003 H<E10, MergedPath, I9, R>1004 ]1005 ): Hono<1006 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>,1007 S & ToSchema<M, MergedPath, I9['in'], MergeTypedResponseData<R>>,1008 BasePath1009 >10101011 // app.on(method, path, handler x10)1012 <1013 M extends string,1014 P extends string,1015 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1016 I extends Input = {},1017 I2 extends Input = I,1018 I3 extends Input = I & I2,1019 I4 extends Input = I & I2 & I3,1020 I5 extends Input = I & I2 & I3 & I4,1021 I6 extends Input = I & I2 & I3 & I4 & I5,1022 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,1023 I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7,1024 I9 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8,1025 I10 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8 & I9,1026 E2 extends Env = E,1027 E3 extends Env = E,1028 E4 extends Env = E,1029 E5 extends Env = E,1030 E6 extends Env = E,1031 E7 extends Env = E,1032 E8 extends Env = E,1033 E9 extends Env = E,1034 E10 extends Env = E,1035 E11 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>1036 >(1037 method: M,1038 path: P,1039 ...handlers: [1040 H<E2, MergedPath, I>,1041 H<E3, MergedPath, I2>,1042 H<E4, MergedPath, I3>,1043 H<E5, MergedPath, I4>,1044 H<E6, MergedPath, I5>,1045 H<E7, MergedPath, I6>,1046 H<E8, MergedPath, I7>,1047 H<E9, MergedPath, I8>,1048 H<E10, MergedPath, I9>,1049 H<E11, MergedPath, I10>1050 ]1051 ): Hono<1052 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11]>,1053 S & ToSchema<M, MergedPath, I10['in'], MergeTypedResponseData<HandlerResponse<any>>>,1054 BasePath1055 >10561057 // app.get(method, path, ...handler)1058 <M extends string, P extends string, R extends HandlerResponse<any> = any, I extends Input = {}>(1059 method: M,1060 path: P,1061 ...handlers: H<E, MergePath<BasePath, P>, I, R>[]1062 ): Hono<E, S & ToSchema<M, MergePath<BasePath, P>, I['in'], MergeTypedResponseData<R>>, BasePath>10631064 // app.get(method[], path, handler)1065 <1066 Ms extends string[],1067 P extends string,1068 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1069 R extends HandlerResponse<any> = any,1070 I extends Input = {},1071 E2 extends Env = E1072 >(1073 methods: Ms,1074 path: P,1075 handler: H<E2, MergedPath, I, R>1076 ): Hono<1077 IntersectNonAnyTypes<[E, E2]>,1078 S & ToSchema<Ms[number], MergedPath, I['in'], MergeTypedResponseData<R>>,1079 BasePath1080 >10811082 // app.get(method[], path, handler x2)1083 <1084 Ms extends string[],1085 P extends string,1086 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1087 R extends HandlerResponse<any> = any,1088 I extends Input = {},1089 I2 extends Input = I,1090 E2 extends Env = E,1091 E3 extends Env = IntersectNonAnyTypes<[E, E2]>1092 >(1093 methods: Ms,1094 path: P,1095 ...handlers: [H<E2, MergedPath, I>, H<E3, MergedPath, I2, R>]1096 ): Hono<1097 IntersectNonAnyTypes<[E, E2, E3]>,1098 S & ToSchema<Ms[number], MergedPath, I2['in'], MergeTypedResponseData<R>>,1099 BasePath1100 >11011102 // app.get(method[], path, handler x3)1103 <1104 Ms extends string[],1105 P extends string,1106 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1107 R extends HandlerResponse<any> = any,1108 I extends Input = {},1109 I2 extends Input = I,1110 I3 extends Input = I & I2,1111 E2 extends Env = E,1112 E3 extends Env = E,1113 E4 extends Env = IntersectNonAnyTypes<[E, E2, E3]>1114 >(1115 methods: Ms,1116 path: P,1117 ...handlers: [H<E2, MergedPath, I>, H<E3, MergedPath, I2>, H<E4, MergedPath, I3, R>]1118 ): Hono<1119 IntersectNonAnyTypes<[E, E2, E3, E4]>,1120 S & ToSchema<Ms[number], MergedPath, I3['in'], MergeTypedResponseData<R>>,1121 BasePath1122 >11231124 // app.get(method[], path, handler x4)1125 <1126 Ms extends string[],1127 P extends string,1128 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1129 R extends HandlerResponse<any> = any,1130 I extends Input = {},1131 I2 extends Input = I,1132 I3 extends Input = I & I2,1133 I4 extends Input = I & I2 & I3,1134 E2 extends Env = E,1135 E3 extends Env = E,1136 E4 extends Env = E,1137 E5 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4]>1138 >(1139 methods: Ms,1140 path: P,1141 ...handlers: [1142 H<E2, MergedPath, I>,1143 H<E3, MergedPath, I2>,1144 H<E4, MergedPath, I3>,1145 H<E5, MergedPath, I4, R>1146 ]1147 ): Hono<1148 IntersectNonAnyTypes<[E, E2, E3, E4, E5]>,1149 S & ToSchema<Ms[number], MergedPath, I4['in'], MergeTypedResponseData<R>>,1150 BasePath1151 >11521153 // app.get(method[], path, handler x5)1154 <1155 Ms extends string[],1156 P extends string,1157 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1158 R extends HandlerResponse<any> = any,1159 I extends Input = {},1160 I2 extends Input = I,1161 I3 extends Input = I & I2,1162 I4 extends Input = I & I2 & I3,1163 I5 extends Input = I & I2 & I3 & I4,1164 E2 extends Env = E,1165 E3 extends Env = E,1166 E4 extends Env = E,1167 E5 extends Env = E,1168 E6 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5]>1169 >(1170 methods: Ms,1171 path: P,1172 ...handlers: [1173 H<E2, MergedPath, I>,1174 H<E3, MergedPath, I2>,1175 H<E4, MergedPath, I3>,1176 H<E5, MergedPath, I4>,1177 H<E6, MergedPath, I5, R>1178 ]1179 ): Hono<1180 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>,1181 S & ToSchema<Ms[number], MergedPath, I5['in'], MergeTypedResponseData<R>>,1182 BasePath1183 >11841185 // app.get(method[], path, handler x6)1186 <1187 Ms extends string[],1188 P extends string,1189 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1190 R extends HandlerResponse<any> = any,1191 I extends Input = {},1192 I2 extends Input = I,1193 I3 extends Input = I & I2,1194 I4 extends Input = I & I2 & I3,1195 I5 extends Input = I & I2 & I3 & I4,1196 I6 extends Input = I & I2 & I3 & I4 & I5,1197 E2 extends Env = E,1198 E3 extends Env = E,1199 E4 extends Env = E,1200 E5 extends Env = E,1201 E6 extends Env = E,1202 E7 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6]>1203 >(1204 methods: Ms,1205 path: P,1206 ...handlers: [1207 H<E2, MergedPath, I>,1208 H<E3, MergedPath, I2>,1209 H<E4, MergedPath, I3>,1210 H<E5, MergedPath, I4>,1211 H<E6, MergedPath, I5>,1212 H<E7, MergedPath, I6, R>1213 ]1214 ): Hono<1215 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>,1216 S & ToSchema<Ms[number], MergedPath, I6['in'], MergeTypedResponseData<R>>,1217 BasePath1218 >12191220 // app.get(method[], path, handler x7)1221 <1222 Ms extends string[],1223 P extends string,1224 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1225 R extends HandlerResponse<any> = any,1226 I extends Input = {},1227 I2 extends Input = I,1228 I3 extends Input = I & I2,1229 I4 extends Input = I & I2 & I3,1230 I5 extends Input = I & I2 & I3 & I4,1231 I6 extends Input = I & I2 & I3 & I4 & I5,1232 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,1233 E2 extends Env = E,1234 E3 extends Env = E,1235 E4 extends Env = E,1236 E5 extends Env = E,1237 E6 extends Env = E,1238 E7 extends Env = E,1239 E8 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7]>1240 >(1241 methods: Ms,1242 path: P,1243 ...handlers: [1244 H<E2, MergedPath, I>,1245 H<E3, MergedPath, I2>,1246 H<E4, MergedPath, I3>,1247 H<E5, MergedPath, I4>,1248 H<E6, MergedPath, I5>,1249 H<E7, MergedPath, I6>,1250 H<E8, MergedPath, I7, R>1251 ]1252 ): Hono<1253 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>,1254 S & ToSchema<Ms[number], MergedPath, I7['in'], MergeTypedResponseData<R>>,1255 BasePath1256 >12571258 // app.get(method[], path, handler x8)1259 <1260 Ms extends string[],1261 P extends string,1262 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1263 R extends HandlerResponse<any> = any,1264 I extends Input = {},1265 I2 extends Input = I,1266 I3 extends Input = I & I2,1267 I4 extends Input = I & I2 & I3,1268 I5 extends Input = I & I2 & I3 & I4,1269 I6 extends Input = I & I2 & I3 & I4 & I5,1270 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,1271 I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7,1272 E2 extends Env = E,1273 E3 extends Env = E,1274 E4 extends Env = E,1275 E5 extends Env = E,1276 E6 extends Env = E,1277 E7 extends Env = E,1278 E8 extends Env = E,1279 E9 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8]>1280 >(1281 methods: Ms,1282 path: P,1283 ...handlers: [1284 H<E2, MergedPath, I>,1285 H<E3, MergedPath, I2>,1286 H<E4, MergedPath, I3>,1287 H<E5, MergedPath, I4>,1288 H<E6, MergedPath, I5>,1289 H<E7, MergedPath, I6>,1290 H<E8, MergedPath, I7>,1291 H<E9, MergedPath, I8, R>1292 ]1293 ): Hono<1294 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>,1295 S & ToSchema<Ms[number], MergedPath, I8['in'], MergeTypedResponseData<R>>,1296 BasePath1297 >12981299 // app.get(method[], path, handler x9)1300 <1301 Ms extends string[],1302 P extends string,1303 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1304 I extends Input = {},1305 I2 extends Input = I,1306 I3 extends Input = I & I2,1307 I4 extends Input = I & I2 & I3,1308 I5 extends Input = I & I2 & I3 & I4,1309 I6 extends Input = I & I2 & I3 & I4 & I5,1310 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,1311 I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7,1312 I9 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8,1313 E2 extends Env = E,1314 E3 extends Env = E,1315 E4 extends Env = E,1316 E5 extends Env = E,1317 E6 extends Env = E,1318 E7 extends Env = E,1319 E8 extends Env = E,1320 E9 extends Env = E,1321 E10 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9]>1322 >(1323 methods: Ms,1324 path: P,1325 ...handlers: [1326 H<E2, MergedPath, I>,1327 H<E3, MergedPath, I2>,1328 H<E4, MergedPath, I3>,1329 H<E5, MergedPath, I4>,1330 H<E6, MergedPath, I5>,1331 H<E7, MergedPath, I6>,1332 H<E8, MergedPath, I7>,1333 H<E9, MergedPath, I8>,1334 H<E10, MergedPath, I9>1335 ]1336 ): Hono<1337 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>,1338 S & ToSchema<Ms[number], MergedPath, I9['in'], MergeTypedResponseData<HandlerResponse<any>>>,1339 BasePath1340 >13411342 // app.get(method[], path, handler x10)1343 <1344 Ms extends string[],1345 P extends string,1346 MergedPath extends MergePath<BasePath, P> = MergePath<BasePath, P>,1347 I extends Input = {},1348 I2 extends Input = I,1349 I3 extends Input = I & I2,1350 I4 extends Input = I & I2 & I3,1351 I5 extends Input = I & I2 & I3 & I4,1352 I6 extends Input = I & I2 & I3 & I4 & I5,1353 I7 extends Input = I & I2 & I3 & I4 & I5 & I6,1354 I8 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7,1355 I9 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8,1356 I10 extends Input = I & I2 & I3 & I4 & I5 & I6 & I7 & I8 & I9,1357 E2 extends Env = E,1358 E3 extends Env = E,1359 E4 extends Env = E,1360 E5 extends Env = E,1361 E6 extends Env = E,1362 E7 extends Env = E,1363 E8 extends Env = E,1364 E9 extends Env = E,1365 E10 extends Env = E,1366 E11 extends Env = IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10]>1367 >(1368 methods: Ms,1369 path: P,1370 ...handlers: [1371 H<E2, MergedPath, I>,1372 H<E3, MergedPath, I2>,1373 H<E4, MergedPath, I3>,1374 H<E5, MergedPath, I4>,1375 H<E6, MergedPath, I5>,1376 H<E7, MergedPath, I6>,1377 H<E8, MergedPath, I7>,1378 H<E9, MergedPath, I8>,1379 H<E10, MergedPath, I9>,1380 H<E11, MergedPath, I10>1381 ]1382 ): Hono<1383 IntersectNonAnyTypes<[E, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11]>,1384 S & ToSchema<Ms[number], MergedPath, I10['in'], MergeTypedResponseData<HandlerResponse<any>>>,1385 BasePath1386 >13871388 // app.on(method[], path, ...handler)1389 <P extends string, R extends HandlerResponse<any> = any, I extends Input = {}>(1390 methods: string[],1391 path: P,
67 unmodified lines
1459////// //////1460////////////////////////////////////////14611462export type TypedResponse<T = unknown> = {522 response: Response | Promise<Response>1463 data: T1464 format: 'json' // Currently, support only `json` with `c.jsonT()`525 status: StatusCode1465}14661467type ExtractResponseData<T> = T extends Promise<infer T2>1468 ? T2 extends TypedResponse<infer U>
89 unmodified lines
modified:package.json+8 added
261 unmodified lines
262 "./testing": {263 "types": "./dist/types/helper/testing/index.d.ts",264 "import": "./dist/helper/testing/index.js",265 "require": "./dist/cjs/helper/testing/index.js"266 },267 "./dev": {268 "types": "./dist/types/helper/dev/index.d.ts",269 "import": "./dist/helper/dev/index.js",270 "require": "./dist/cjs/helper/dev/index.js"271 }272 },273 "typesVersions": {274 "*": {
130 unmodified lines
405 "./dist/types/adapter/lambda-edge"406 ],407 "testing": [408 "./dist/types/helper/testing"409 ],410 "dev": [411 "./dist/types/helper/dev"412 ]413 }414 },415 "author": "Yusuke Wada <yusuke@kamawada.com> (https://github.com/yusukebe)",
76 unmodified lines